diff --git a/CodeCompletion/CodeCompletion.cs b/CodeCompletion/CodeCompletion.cs index 669197e70..43acc6156 100644 --- a/CodeCompletion/CodeCompletion.cs +++ b/CodeCompletion/CodeCompletion.cs @@ -46,7 +46,6 @@ namespace CodeCompletion public static Dictionary pabcNamespaces = new Dictionary(); public static string currentLanguageISO; - static string doctagsParserExtension = ".pasdt" + StringConstants.hideParserExtensionPostfixChar; //public static PascalABCCompiler.Parsers.IParser currentParser; static string cur_ext = ".pas"; private static IParser currentParser; @@ -64,7 +63,7 @@ namespace CodeCompletion private static string get_doctagsParserExtension(string ext) { - return ext + "dt" + StringConstants.hideParserExtensionPostfixChar; + return ext + "dt"; } public static IParser CurrentParser diff --git a/Compiler/Compiler.cs b/Compiler/Compiler.cs index 999c710b4..17ee77e54 100644 --- a/Compiler/Compiler.cs +++ b/Compiler/Compiler.cs @@ -162,261 +162,6 @@ using Languages.Facade; namespace PascalABCCompiler { - public class CompilerCompilationError : LocatedError - { - public CompilerCompilationError(string message) - : base(message) - { - } - public CompilerCompilationError(string message, string FileName) - : base(message, FileName) - { - } - public override string ToString() - { - return Message; - } - } - - public class ReadPCUError : CompilerCompilationError - { - public ReadPCUError(string FileName) - : base(string.Format(StringResources.Get("COMPILATIONERROR_READ_PCU{0}_ERROR"), FileName)) - { - } - } - - public class NamespaceCannotHaveInSection : CompilerCompilationError - { - public NamespaceCannotHaveInSection(SyntaxTree.SourceContext sc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_NAMESPACE_CANNOT_HAVE_IN_SECTION"))) - { - this.source_context = sc; - } - } - - public class ProgramModuleExpected : CompilerCompilationError - { - public ProgramModuleExpected(string FileName, SyntaxTree.SourceContext sc) - : base(StringResources.Get("COMPILATIONERROR_PROGRAM_MODULE_EXPECTED"), FileName) - { - this.source_context = sc; - } - } - - public class UnitModuleExpected : CompilerCompilationError - { - public UnitModuleExpected(string FileName, SyntaxTree.SourceContext sc) - : base(StringResources.Get("COMPILATIONERROR_UNIT_MODULE_EXPECTED"), FileName) - { - this.source_context = sc; - } - } - - public class AppTypeDllIsAllowedOnlyForLibraries : CompilerCompilationError - { - public AppTypeDllIsAllowedOnlyForLibraries(string FileName, SyntaxTree.SourceContext sc) - : base(StringResources.Get("COMPILATIONERROR_APPTYPE_DLL_IS_ALLOWED_ONLY_FOR_LIBRARIES"), FileName) - { - this.source_context = sc; - } - } - - public class UnitModuleExpectedLibraryFound : CompilerCompilationError - { - public UnitModuleExpectedLibraryFound(string FileName, SyntaxTree.SourceContext sc) - : base(StringResources.Get("COMPILATIONERROR_UNIT_MODULE_EXPECTED_LIBRARY_FOUND"), FileName) - { - this.source_context = sc; - } - } - - public class AssemblyNotFound : CompilerCompilationError - { - public string AssemblyFileName; - public AssemblyNotFound(string FileName, string AssemblyFileName, SyntaxTree.SourceContext sc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_ASSEMBLY_{0}_NOT_FOUND"), AssemblyFileName), FileName) - { - this.AssemblyFileName = AssemblyFileName; - this.source_context = sc; - } - - } - - public class AssemblyReadingError : CompilerCompilationError - { - public string AssemblyFileName; - public AssemblyReadingError(string FileName, string AssemblyFileName, SyntaxTree.SourceContext sc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_ASSEMBLY_{0}_READING_ERROR"), AssemblyFileName), FileName) - { - this.AssemblyFileName = AssemblyFileName; - this.source_context = sc; - } - } - - public class InvalidAssemblyPathError : CompilerCompilationError - { - public InvalidAssemblyPathError(string FileName, SyntaxTree.SourceContext sc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_INVALID_ASSEMBLY_PATH")), FileName) - { - this.source_context = sc; - } - } - - public class InvalidPathError : CompilerCompilationError - { - public InvalidPathError(SyntaxTree.SourceContext sc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_INVALID_PATH"))) - { - this.source_context = sc; - this.fileName = sc.FileName; - } - } - - public class ResourceFileNotFound : CompilerCompilationError - { - public ResourceFileNotFound(string ResFileName, TreeRealization.location sl) - : base(string.Format(StringResources.Get("COMPILATIONERROR_RESOURCEFILE_{0}_NOT_FOUND"), ResFileName), sl.doc.file_name) - { - this.sourceLocation = new SourceLocation(sl.doc.file_name, sl.begin_line_num, sl.begin_column_num, sl.end_line_num, sl.end_column_num); - } - } - - public class IncludeNamespaceInUnitError : CompilerCompilationError - { - public IncludeNamespaceInUnitError(string FileName, SyntaxTree.SourceContext sc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_INCLUDE_NAMESPACE_IN_UNIT")), FileName) - { - this.source_context = sc; - } - } - - public class NamespaceModuleExpected : CompilerCompilationError - { - public NamespaceModuleExpected(SyntaxTree.SourceContext sc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_NAMESPACE_MODULE_EXPECTED"))) - { - this.source_context = sc; - } - } - - public class MainResourceNotAllowed : CompilerCompilationError - { - public MainResourceNotAllowed(TreeRealization.location sl) - : base(string.Format(StringResources.Get("COMPILATIONERROR_MAINRESOURCE_NOT_ALLOWED")), sl.doc.file_name) - { - this.sourceLocation = new SourceLocation(sl.doc.file_name, sl.begin_line_num, sl.begin_column_num, sl.end_line_num, sl.end_column_num); - } - - } - - public class DuplicateUsesUnit : CompilerCompilationError - { - public string UnitName; - public DuplicateUsesUnit(string FileName, string UnitName, SyntaxTree.SourceContext sc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_DUPLICATE_USES_UNIT{0}"), UnitName), FileName) - { - this.UnitName = UnitName; - this.source_context = sc; - } - } - public class DuplicateDirective : CompilerCompilationError - { - public string DirectiveName; - public DuplicateDirective(string FileName, string DirectiveName, SyntaxTree.SourceContext sc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_DUPLICATE_DIRECTIVE{0}"), DirectiveName), FileName) - { - this.DirectiveName = DirectiveName; - this.source_context = sc; - } - } - - public class NamespacesCanBeCompiledOnlyInProjects : CompilerCompilationError - { - public NamespacesCanBeCompiledOnlyInProjects(SyntaxTree.SourceContext sc) - : base(StringResources.Get("COMPILATIONERROR_NAMESPACE_CAN_BE_COMPILED_ONLY_IN_PROJECTS")) - { - this.source_context = sc; - } - } - - public class UnitNotFound : CompilerCompilationError - { - public string UnitName; - public UnitNotFound(string FileName, string UnitName, SyntaxTree.SourceContext sc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_UNIT_{0}_NOT_FOUND"), UnitName), FileName) - { - this.UnitName = UnitName; - this.source_context = sc; - } - } - - public class UsesInWrongName : CompilerCompilationError - { - public string UnitName1; - public string UnitName2; - public UsesInWrongName(string FileName, string UnitName1, string UnitName2, SyntaxTree.SourceContext sc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_USES_IN_WRONG_NAME"), UnitName1, UnitName2), FileName) - { - this.UnitName1 = UnitName1; - this.UnitName2 = UnitName2; - this.source_context = sc; - } - } - - public class SourceFileNotFound : CompilerCompilationError - { - public SourceFileNotFound(string FileName) - : base(string.Format(StringResources.Get("COMPILATIONERROR_SOURCE_FILE_{0}_NOT_FOUND"), FileName)) - { - } - } - - public class UnauthorizedAccessToFile : CompilerCompilationError - { - public UnauthorizedAccessToFile(string FileName) - : base(string.Format(StringResources.Get("COMPILATIONERROR_NO_ACCESS_TO_FILE{0}"), FileName)) - { - } - } - public class CycleUnitReference : CompilerCompilationError - { - public SyntaxTree.unit_or_namespace SyntaxUsesUnit; - public CycleUnitReference(string FileName, SyntaxTree.unit_or_namespace SyntaxUsesUnit) - : base(string.Format(StringResources.Get("COMPILATIONERROR_CYCLIC_UNIT_REFERENCE_WITH_UNIT_{0}"), SyntaxTree.Utils.IdentListToString(SyntaxUsesUnit.name.idents, ".")), FileName) - { - this.SyntaxUsesUnit = SyntaxUsesUnit; - this.source_context = SyntaxUsesUnit.source_context; - } - } - - public class UnsupportedTargetFramework : CompilerCompilationError - { - public UnsupportedTargetFramework(string FrameworkName, location sl) - : base(string.Format(StringResources.Get("COMPILATIONERROR_UNSUPPORTED_TARGETFRAMEWORK_{0}"), FrameworkName)) - { - this.sourceLocation = new SourceLocation(sl.doc.file_name, sl.begin_line_num, sl.begin_column_num, sl.end_line_num, sl.end_column_num); - } - } - - public class UnsupportedTargetPlatform : CompilerCompilationError - { - public UnsupportedTargetPlatform(string platformName, location loc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_UNSUPPORTED_TARGET_PLATFORM{0}"), platformName)) - { - sourceLocation = new SourceLocation(loc.doc.file_name, loc.begin_line_num, loc.begin_column_num, loc.end_line_num, loc.end_column_num); - } - } - - public class UnsupportedOutputFileType : CompilerCompilationError - { - public UnsupportedOutputFileType(string outputFileType, location loc) - : base(string.Format(StringResources.Get("COMPILATIONERROR_UNSUPPORTED_OUTPUT_FILE_TYPE{0}"), outputFileType)) - { - sourceLocation = new SourceLocation(loc.doc.file_name, loc.begin_line_num, loc.begin_column_num, loc.end_line_num, loc.end_column_num); - } - } - public enum UnitState { BeginCompilation, InterfaceCompiled, Compiled } public class CompilationUnit @@ -475,12 +220,12 @@ namespace PascalABCCompiler set { _semanticTree = value; } } - private SyntaxTree.unit_or_namespace _syntaxUnitName = null; + /*private SyntaxTree.unit_or_namespace _syntaxUnitName = null; public SyntaxTree.unit_or_namespace SyntaxUnitName { get { return _syntaxUnitName; } set { _syntaxUnitName = value; } - } + }*/ private TreeRealization.using_namespace_list _interface_using_namespace_list = new TreeRealization.using_namespace_list(); public TreeRealization.using_namespace_list InterfaceUsingNamespaceList @@ -623,33 +368,16 @@ namespace PascalABCCompiler [Serializable()] public class StandardModule : MarshalByRefObject { - public string name = null; - public StandardModuleAddMethod addMethod = StandardModuleAddMethod.LeftToAll; - public string languageToAdd = StringConstants.pascalLanguageName; - - public StandardModule(string Name, StandardModuleAddMethod addMethod) - { - this.name = Name; - this.addMethod = addMethod; - } + public string name; + public StandardModuleAddMethod addMethod; + public string languageToAdd; - public StandardModule(string name, StandardModuleAddMethod addMethod, string languageToAdd) + public StandardModule(string name, StandardModuleAddMethod addMethod = StandardModuleAddMethod.LeftToAll, string languageToAdd = StringConstants.pascalLanguageName) { this.name = name; this.languageToAdd = languageToAdd; this.addMethod = addMethod; } - - public StandardModule(string name) - { - this.name = name; - } - - public StandardModule(string name, string languageToAdd) - { - this.languageToAdd = languageToAdd; - this.name = name; - } } private Dictionary> standardModules = new Dictionary>(); @@ -678,7 +406,7 @@ namespace PascalABCCompiler { foreach (ILanguage language in LanguageProvider.Instance.Languages) { - standardModules[language.Name] = language.SystemUnitNames.Select(unitName => new StandardModule(unitName, language.Name)).ToList(); + standardModules[language.Name] = language.SystemUnitNames.Select(unitName => new StandardModule(unitName, StandardModuleAddMethod.LeftToAll, language.Name)).ToList(); } } @@ -722,8 +450,10 @@ namespace PascalABCCompiler { SystemDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName); - StandardDirectories = new Hashtable(StringComparer.InvariantCultureIgnoreCase); - StandardDirectories.Add("%PABCSYSTEM%", SystemDirectory); + StandardDirectories = new Hashtable(StringComparer.InvariantCultureIgnoreCase) + { + { "%PABCSYSTEM%", SystemDirectory } + }; ParserSearchPaths = new string[] { Path.Combine(SystemDirectory, "Lib") }; SearchDirectories = ParserSearchPaths.ToList(); @@ -782,30 +512,31 @@ namespace PascalABCCompiler public class SupportedSourceFile { - private string[] extensions; + private readonly string[] extensions; + public string[] Extensions { get { return extensions; } } - private string languageName; + + private readonly string languageName; + public string LanguageName { get { return languageName; } } + public SupportedSourceFile(string[] extensions, string lname) { - this.extensions = extensions; languageName = lname; + this.extensions = extensions; + languageName = lname; } + public static SupportedSourceFile Make(ILanguage language) - { - List ext = new List(); - foreach (string ex in language.FilesExtensions) - if (ex[ex.Length - 1] != StringConstants.hideParserExtensionPostfixChar) - ext.Add(ex); - if (ext.Count > 0) - return new SupportedSourceFile(ext.ToArray(), language.Name); - return null; + { + return new SupportedSourceFile(language.FilesExtensions, language.Name); } + public override string ToString() { return string.Format("{0} ({1})", LanguageName, FormatTools.ExtensionsToString(Extensions, "*", ";")); @@ -875,14 +606,6 @@ namespace PascalABCCompiler } } - public program_node semantic_tree - { - get - { - return semanticTree; - } - } - public List CompiledVariables = new List(); private uint linesCompiled; @@ -912,28 +635,13 @@ namespace PascalABCCompiler private void SetSupportedSourceFiles() { - List supportedSourceFilesList = new List(); - for (int i = 0; i < LanguageProvider.Languages.Count; i++) - { - SupportedSourceFile sf = SupportedSourceFile.Make(LanguageProvider.Languages[i]); - if (sf != null) - supportedSourceFilesList.Add(sf); - } - supportedSourceFiles = supportedSourceFilesList.ToArray(); + supportedSourceFiles = LanguageProvider.Languages.Select(language => SupportedSourceFile.Make(language)).ToArray(); } private void SetSupportedProjectFiles() { - List supportedProjectFilesList = new List(); - /*for (int i = 0; i < ParsersController.Parsers.Count; i++) - { - SupportedSourceFile sf = SupportedSourceFile.Make(ParsersController.Parsers[i]); - if (sf != null) - supportedSourceFilesList.Add(sf); - }*/ - //vremenno - supportedProjectFilesList.Add(new SupportedSourceFile(new string[1] { ".pabcproj" }, "PascalABC.NET")); - supportedProjectFiles = supportedProjectFilesList.ToArray(); + // проекты только на Паскале пока EVA + supportedProjectFiles = new SupportedSourceFile[] { new SupportedSourceFile(new string[1] { ".pabcproj" }, "PascalABC.NET") }; } private SupportedSourceFile[] supportedSourceFiles = null; @@ -956,36 +664,32 @@ namespace PascalABCCompiler private List StandardModules = new List(); public CompilerOptions CompilerOptions { get; set; } = new CompilerOptions(); - internal Dictionary DLLCache = new Dictionary(); + private Dictionary DLLCache = new Dictionary(); - public LanguageProvider LanguageProvider => LanguageProvider.Instance; + private LanguageProvider LanguageProvider => LanguageProvider.Instance; public TreeConverter.SyntaxTreeToSemanticTreeConverter SyntaxTreeToSemanticTreeConverter = null; public CodeGenerators.Controller CodeGeneratorsController = null; //public LLVMConverter.Controller LLVMCodeGeneratorsController = null; //public PascalToCppConverter.Controller PABCToCppCodeGeneratorsController = null; - public SyntaxTree.unit_or_namespace currentUnitSyntaxTree; /// /// список отложенной компиляции реализации (она будет откомпилирована в Compile, а не в СompileUnit) /// private List UnitsToCompileDelayedList = new List(); + public Hashtable RecompileList = new Hashtable(StringComparer.OrdinalIgnoreCase); - private Hashtable CycleUnits = new Hashtable(); - public CompilationUnit currentCompilationUnit = null; + + private CompilationUnit currentCompilationUnit = null; + private CompilationUnit firstCompilationUnit = null; + private bool PCUReadersAndWritersClosed; - /// - /// Начало основной программы - /// - public int beginOffset; - /// - /// Положение первых переменных в пространстве имен основной программы - /// - public int varBeginOffset; - private bool _clear_after_compilation = true; + private static Dictionary pcuCompilationUnits = new Dictionary(); + private bool _clear_after_compilation = true; + public bool ClearAfterCompilation { get @@ -998,6 +702,10 @@ namespace PascalABCCompiler } } + /// + /// Начало основной программы + /// + public int beginOffset; public int BeginOffset { @@ -1006,6 +714,12 @@ namespace PascalABCCompiler return beginOffset; } } + + /// + /// Положение первых переменных в пространстве имен основной программы + /// + public int varBeginOffset; + public int VarBeginOffset { get @@ -1013,7 +727,9 @@ namespace PascalABCCompiler return varBeginOffset; } } + private List warnings = new List(); + public List Warnings { get @@ -1045,11 +761,14 @@ namespace PascalABCCompiler if (FileName == null) return false; return (bool)SourceFilesProvider(FileName, SourceFileOperation.Exists); } + private DateTime SourceFileGetLastWriteTime(string FileName) { return (DateTime)SourceFilesProvider(FileName, SourceFileOperation.GetLastWriteTime); } + private SourceFilesProviderDelegate sourceFilesProvider = SourceFilesProviders.DefaultSourceFilesProvider; + public SourceFilesProviderDelegate SourceFilesProvider { get @@ -1180,7 +899,7 @@ namespace PascalABCCompiler return directives; } - private Hashtable GetCompilerDirectives(CompilationUnit Unit) + /*private Hashtable GetCompilerDirectives(CompilationUnit Unit) { Hashtable Directives = new Hashtable(StringComparer.CurrentCultureIgnoreCase); TreeRealization.common_unit_node cun = Unit.SemanticTree as TreeRealization.common_unit_node; @@ -1188,10 +907,10 @@ namespace PascalABCCompiler foreach (TreeRealization.compiler_directive cd in cun.compiler_directives) Directives[cd.name] = cd; return Directives; - } + }*/ /// - /// преобразует в директивы семантического уровня | в TreeConverter такая же функция EVA + /// преобразует в директивы семантического уровня | в syntax_tree_visitor такая же функция EVA /// private List GetDirectivesAsSemanticNodes(List compilerDirectives, string unitFileName) { @@ -1200,7 +919,7 @@ namespace PascalABCCompiler { list.Add(new compiler_directive(directive.Name.text, directive.Directive?.text ?? "", - get_location_from_treenode(directive, unitFileName), + GetLocationFromTreenode(directive, unitFileName), unitFileName)); } return list; @@ -1208,7 +927,7 @@ namespace PascalABCCompiler #endregion - private TreeRealization.location get_location_from_treenode(SyntaxTree.syntax_tree_node tn, string FileName) + private TreeRealization.location GetLocationFromTreenode(SyntaxTree.syntax_tree_node tn, string FileName) { if (tn.source_context == null) { @@ -1218,14 +937,9 @@ namespace PascalABCCompiler tn.source_context.end_position.line_num, tn.source_context.end_position.column_num, new TreeRealization.document(FileName)); } - void syncStartCompile() - { - Compile(); - } - public void StartCompile() { - System.Threading.Thread th = new System.Threading.Thread(syncStartCompile); + System.Threading.Thread th = new System.Threading.Thread(() => Compile()); th.SetApartmentState(System.Threading.ApartmentState.STA); th.Start(); } @@ -1265,7 +979,7 @@ namespace PascalABCCompiler throw ErrorsList[0]; } - private void MoveSystemUnitForwardInUnitsTopologicallySortedList() + /*private void MoveSystemUnitForwardInUnitsTopologicallySortedList() { if (CompilerOptions.StandardModules.Count == 0) return; @@ -1292,22 +1006,11 @@ namespace PascalABCCompiler UnitsTopologicallySortedList.Insert(0, systemUnit); } - } + }*/ - private uint get_compiled_lines(string FileName) - { - StreamReader sr = File.OpenText(FileName); - uint line = 0; - while (!sr.EndOfStream) - { - sr.ReadLine(); - line++; - } - sr.Close(); - return line; - } + #region LEGACY - Visual Basic and IronPython - class ProgInfo + /*class ProgInfo { public string entry_module; public int entry_method_name_pos; @@ -1316,8 +1019,9 @@ namespace PascalABCCompiler public List modules = new List(); public List addit_imports = new List(); public List addit_project_files = new List(); - } + }*/ + /* private void add_import_info(ProgInfo info, List imports) { Hashtable ht = new Hashtable(StringComparer.CurrentCultureIgnoreCase); @@ -1340,7 +1044,8 @@ namespace PascalABCCompiler info.addit_imports.Add(name + "." + name); } } - /*if (!string.IsNullOrEmpty(mod_file)) + // Этот if был закомментирован EVA + if (!string.IsNullOrEmpty(mod_file)) { switch (low_s) { @@ -1377,7 +1082,7 @@ namespace PascalABCCompiler } break; } - }*/ + } else { string source_file = FindFileWithExtensionInDirs(s + ".vb", out _, Path.GetDirectoryName(CompilerOptions.SourceFileName), Path.Combine(this.CompilerOptions.SystemDirectory, "lib"), @@ -1391,7 +1096,8 @@ namespace PascalABCCompiler } } } - /*List mods = new List(); + // весь код ниже был закомментирован EVA + List mods = new List(); List inds = new List(); for (int i=0; i usings = new List(); @@ -1506,9 +1211,9 @@ namespace PascalABCCompiler return info; } return null; - } + }*/ - public string CompileWithProvider(string[] sources, System.CodeDom.Compiler.CodeDomProvider cp, params string[] RefAssemblies) + /*public string CompileWithProvider(string[] sources, System.CodeDom.Compiler.CodeDomProvider cp, params string[] RefAssemblies) { OnChangeCompilerState(this, CompilerState.CompilationStarting, CompilerOptions.SourceFileName); OnChangeCompilerState(this, CompilerState.BeginCompileFile, CompilerOptions.SourceFileName); @@ -1530,7 +1235,7 @@ namespace PascalABCCompiler { for (int i = 0; i < res.Errors.Count; i++) { - if (!res.Errors[i].IsWarning && errorsList.Count == 0 /*&& dlls.Errors[i].file_name != redirect_fname*/) + if (!res.Errors[i].IsWarning && errorsList.Count == 0 *//*&& dlls.Errors[i].file_name != redirect_fname*//*) { if (File.Exists(res.Errors[i].FileName)) errorsList.Add(new Errors.CommonCompilerError(res.Errors[i].ErrorText, res.Errors[i].FileName, res.Errors[i].Line != 0 ? res.Errors[i].Line : 1, res.Errors[i].Column != 0 ? res.Errors[i].Column : 1)); @@ -1554,9 +1259,9 @@ namespace PascalABCCompiler return null; else return res.PathToAssembly; - } + }*/ - class PyErrorHandler : ErrorListener + /*class PyErrorHandler : ErrorListener { Compiler c; public PyErrorHandler(Compiler cc) { c = cc; } @@ -1567,11 +1272,12 @@ namespace PascalABCCompiler else c.errorsList.Add(new Errors.CommonCompilerError(message, c.CompilerOptions.SourceFileName, span.Start.Line, span.Start.Column)); } - } + }*/ + /* private Assembly IronPythonAssembly; private MethodInfo PythonCreateEngineMethod; - /*public string CompilePy() + public string CompilePy() { OnChangeCompilerState(this, CompilerState.CompilationStarting, CompilerOptions.SourceFileName); OnChangeCompilerState(this, CompilerState.BeginCompileFile, CompilerOptions.SourceFileName); @@ -1602,78 +1308,6 @@ namespace PascalABCCompiler //else return dlls.PathToAssembly; }*/ - public string CompileCS() - { - OnChangeCompilerState(this, CompilerState.CompilationStarting, CompilerOptions.SourceFileName); - OnChangeCompilerState(this, CompilerState.BeginCompileFile, CompilerOptions.SourceFileName); - Reset(); - var d = new Dictionary(); - d["CompilerVersion"] = "v4.0"; - var cscp = new Microsoft.CSharp.CSharpCodeProvider(d); - - //var cscp = new Microsoft.CSharp.CSharpCodeProvider(); - var comp_opt = new CompilerParameters(); - comp_opt.IncludeDebugInformation = CompilerOptions.Debug; - comp_opt.GenerateExecutable = true; - comp_opt.WarningLevel = 3; - comp_opt.OutputAssembly = CompilerOptions.OutputFileName; - - //comp_opt.ReferencedAssemblies.Add() - - string source = GetSourceFileText(CompilerOptions.SourceFileName); - - using (StringReader sr = new StringReader(source)) - { - do - { - var s = sr.ReadLine(); - - if (s == null) - break; - - if (s.ToLower().StartsWith("//#reference ")) - { - s = s.Remove(0, 13); - s = s.Trim(); - comp_opt.ReferencedAssemblies.Add(s); - } - else break; - - } while (true); - } - - - var res = cscp.CompileAssemblyFromSource(comp_opt, source); - if (res.Errors.Count > 0) - { - for (int i = 0; i < res.Errors.Count; i++) - { - if (!res.Errors[i].IsWarning && errorsList.Count == 0 /*&& dlls.Errors[i].file_name != redirect_fname*/) - { - if (File.Exists(res.Errors[i].FileName)) - errorsList.Add(new Errors.CommonCompilerError(res.Errors[i].ErrorText, res.Errors[i].FileName, res.Errors[i].Line != 0 ? res.Errors[i].Line : 1, res.Errors[i].Column != 0 ? res.Errors[i].Column : 1)); - else - errorsList.Add(new Errors.CommonCompilerError(res.Errors[i].ErrorText, CompilerOptions.SourceFileName, res.Errors[i].Line != 0 ? res.Errors[i].Line : 1, res.Errors[i].Column != 0 ? res.Errors[i].Column : 1)); - } - else if (res.Errors[i].IsWarning) - { - warnings.Add(new Errors.CommonWarning(res.Errors[i].ErrorText, res.Errors[i].FileName, res.Errors[i].Line, res.Errors[i].Column)); - } - } - } - - linesCompiled = get_compiled_lines(CompilerOptions.SourceFileName); - - OnChangeCompilerState(this, CompilerState.CompilationFinished, CompilerOptions.SourceFileName); - ClearAll(); - OnChangeCompilerState(this, CompilerState.Ready, null); - - if (errorsList.Count > 0) - return null; - else - return res.PathToAssembly; - } - /*public string CompileVB() { OnChangeCompilerState(this, CompilerState.CompilationStarting, CompilerOptions.SourceFileName); @@ -1841,9 +1475,83 @@ namespace PascalABCCompiler return res.PathToAssembly; }*/ + #endregion + + public string CompileCS() + { + OnChangeCompilerState(this, CompilerState.CompilationStarting, CompilerOptions.SourceFileName); + OnChangeCompilerState(this, CompilerState.BeginCompileFile, CompilerOptions.SourceFileName); + Reset(); + var d = new Dictionary(); + d["CompilerVersion"] = "v4.0"; + var cscp = new Microsoft.CSharp.CSharpCodeProvider(d); + + //var cscp = new Microsoft.CSharp.CSharpCodeProvider(); + var comp_opt = new CompilerParameters(); + comp_opt.IncludeDebugInformation = CompilerOptions.Debug; + comp_opt.GenerateExecutable = true; + comp_opt.WarningLevel = 3; + comp_opt.OutputAssembly = CompilerOptions.OutputFileName; + + //comp_opt.ReferencedAssemblies.Add() + + string source = GetSourceFileText(CompilerOptions.SourceFileName); + + using (StringReader sr = new StringReader(source)) + { + do + { + var s = sr.ReadLine(); + + if (s == null) + break; + + if (s.ToLower().StartsWith("//#reference ")) + { + s = s.Remove(0, 13); + s = s.Trim(); + comp_opt.ReferencedAssemblies.Add(s); + } + else break; + + } while (true); + } + + + var res = cscp.CompileAssemblyFromSource(comp_opt, source); + if (res.Errors.Count > 0) + { + for (int i = 0; i < res.Errors.Count; i++) + { + if (!res.Errors[i].IsWarning && errorsList.Count == 0 /*&& dlls.Errors[i].file_name != redirect_fname*/) + { + if (File.Exists(res.Errors[i].FileName)) + errorsList.Add(new Errors.CommonCompilerError(res.Errors[i].ErrorText, res.Errors[i].FileName, res.Errors[i].Line != 0 ? res.Errors[i].Line : 1, res.Errors[i].Column != 0 ? res.Errors[i].Column : 1)); + else + errorsList.Add(new Errors.CommonCompilerError(res.Errors[i].ErrorText, CompilerOptions.SourceFileName, res.Errors[i].Line != 0 ? res.Errors[i].Line : 1, res.Errors[i].Column != 0 ? res.Errors[i].Column : 1)); + } + else if (res.Errors[i].IsWarning) + { + warnings.Add(new Errors.CommonWarning(res.Errors[i].ErrorText, res.Errors[i].FileName, res.Errors[i].Line, res.Errors[i].Column)); + } + } + } + + linesCompiled = (uint)File.ReadAllLines(CompilerOptions.SourceFileName).Length; + + OnChangeCompilerState(this, CompilerState.CompilationFinished, CompilerOptions.SourceFileName); + ClearAll(); + OnChangeCompilerState(this, CompilerState.Ready, null); + + if (errorsList.Count > 0) + return null; + else + return res.PathToAssembly; + } + private ProjectInfo project; - private void PrepareCompileOptionsForProject() + private void InitializeProjectInfoAndFillCompilerOptionsFromIt() { project = new ProjectInfo(); project.Load(CompilerOptions.SourceFileName); @@ -1859,6 +1567,8 @@ namespace PascalABCCompiler CompilerOptions.OutputFileName = project.output_file_name; CompilerOptions.OutputDirectory = project.output_directory; + + } public static bool CheckPathValid(string path) @@ -1958,7 +1668,7 @@ namespace PascalABCCompiler } } - private void SetOutputPlatformOption(NETGenerator.CompilerOptions compilerOptions, Dictionary> compilerDirectives) + private void SetOutputPlatformOption(NETGenerator.CompilerOptions netCompilerOptions, Dictionary> compilerDirectives) { List compilerDirectivesList = new List(); if (compilerDirectives.TryGetValue(StringConstants.compiler_directive_platformtarget, out compilerDirectivesList)) @@ -1967,35 +1677,35 @@ namespace PascalABCCompiler switch (platformName) { case "x86": - compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x86; + netCompilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x86; break; case "x64": - compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x64; + netCompilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x64; break; case "anycpu": - compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.AnyCPU; + netCompilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.AnyCPU; break; case "dotnet5win": - compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5win; + netCompilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5win; break; case "dotnet5linux": - compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5linux; + netCompilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5linux; break; case "dotnet5macos": - compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5macos; + netCompilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5macos; break; case "native": if (Environment.OSVersion.Platform == PlatformID.Unix) { - compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetlinuxnative; + netCompilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetlinuxnative; } else if (Environment.OSVersion.Platform == PlatformID.MacOSX) { - compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetmacosnative; + netCompilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetmacosnative; } else { - compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetwinnative; + netCompilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetwinnative; } break; default: @@ -2003,50 +1713,50 @@ namespace PascalABCCompiler break; } if (CompilerOptions.Only32Bit) - compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x86; + netCompilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x86; } if (compilerDirectives.TryGetValue(StringConstants.compiler_directive_targetframework, out compilerDirectivesList)) { - compilerOptions.TargetFramework = compilerDirectivesList[0].directive; + netCompilerOptions.TargetFramework = compilerDirectivesList[0].directive; if (!(new string[] { "net40", "net403", "net45", "net451", "net452", "net46", "net461", "net462", "net47", "net471", "net472", "net48", "net481" }) - .Contains(compilerOptions.TargetFramework)) + .Contains(netCompilerOptions.TargetFramework)) { - ErrorsList.Add(new UnsupportedTargetFramework(compilerOptions.TargetFramework, compilerDirectivesList[0].location)); + ErrorsList.Add(new UnsupportedTargetFramework(netCompilerOptions.TargetFramework, compilerDirectivesList[0].location)); } } } - private void FillCompilerInfoOptions(NETGenerator.CompilerOptions compilerOptions, Dictionary> compilerDirectives) + private void FillNetCompilerOptionsFromCompilerDirectives(NETGenerator.CompilerOptions netCompilerOptions, Dictionary> compilerDirectives) { List compilerDirectivesList; if (compilerDirectives.TryGetValue(StringConstants.compiler_directive_product_string, out compilerDirectivesList)) { - compilerOptions.Product = compilerDirectivesList[0].directive; + netCompilerOptions.Product = compilerDirectivesList[0].directive; } if (compilerDirectives.TryGetValue(StringConstants.compiler_directive_version_string, out compilerDirectivesList)) { - compilerOptions.ProductVersion = compilerDirectivesList[0].directive; + netCompilerOptions.ProductVersion = compilerDirectivesList[0].directive; } if (compilerDirectives.TryGetValue(StringConstants.compiler_directive_company_string, out compilerDirectivesList)) { - compilerOptions.Company = compilerDirectivesList[0].directive; + netCompilerOptions.Company = compilerDirectivesList[0].directive; } if (compilerDirectives.TryGetValue(StringConstants.compiler_directive_trademark_string, out compilerDirectivesList)) { - compilerOptions.TradeMark = compilerDirectivesList[0].directive; + netCompilerOptions.TradeMark = compilerDirectivesList[0].directive; } if (compilerDirectives.TryGetValue(StringConstants.compiler_directive_copyright_string, out compilerDirectivesList)) { - compilerOptions.Copyright = compilerDirectivesList[0].directive; + netCompilerOptions.Copyright = compilerDirectivesList[0].directive; } if (compilerDirectives.TryGetValue(StringConstants.compiler_directive_title_string, out compilerDirectivesList)) { - compilerOptions.Title = compilerDirectivesList[0].directive; + netCompilerOptions.Title = compilerDirectivesList[0].directive; } if (compilerDirectives.TryGetValue(StringConstants.compiler_directive_description_string, out compilerDirectivesList)) { - compilerOptions.Description = compilerDirectivesList[0].directive; + netCompilerOptions.Description = compilerDirectivesList[0].directive; } if (compilerDirectives.TryGetValue(StringConstants.compiler_directive_main_resource_string, out compilerDirectivesList)) { @@ -2058,52 +1768,52 @@ namespace PascalABCCompiler compilerDirectives.ContainsKey(StringConstants.compiler_directive_description_string) || compilerDirectives.ContainsKey(StringConstants.compiler_directive_copyright_string)) { - ErrorsList.Add(new MainResourceNotAllowed(compilerDirectivesList[0].location)); + ErrorsList.Add(new MainResourceNotAllowed(compilerDirectivesList[0].location.doc.file_name, compilerDirectivesList[0].location)); } TryThrowInvalidPath(compilerDirectivesList[0].directive, compilerDirectivesList[0].location); // Тут не обязательно нормализовывать путь // И если он слишком длинный - File.Exists вернёт false - compilerOptions.MainResourceFileName = Path.Combine(Path.GetDirectoryName(compilerDirectivesList[0].source_file), compilerDirectivesList[0].directive); - if (!File.Exists(compilerOptions.MainResourceFileName)) - ErrorsList.Add(new ResourceFileNotFound(compilerDirectivesList[0].directive, compilerDirectivesList[0].location)); + netCompilerOptions.MainResourceFileName = Path.Combine(Path.GetDirectoryName(compilerDirectivesList[0].source_file), compilerDirectivesList[0].directive); + if (!File.Exists(netCompilerOptions.MainResourceFileName)) + ErrorsList.Add(new ResourceFileNotFound(compilerDirectivesList[0].location.doc.file_name, compilerDirectivesList[0].directive, compilerDirectivesList[0].location)); } } - private void FillCompilerOptionsFromProject(NETGenerator.CompilerOptions compilerOptions) + private void FillNetCompilerOptionsFromProject(NETGenerator.CompilerOptions netCompilerOptions) { if (project != null) { if (!(project.major_version == 0 && project.minor_version == 0 && project.build_version == 0 && project.revision_version == 0)) - compilerOptions.ProductVersion = project.major_version + "." + project.minor_version + "." + project.build_version + "." + project.revision_version; + netCompilerOptions.ProductVersion = project.major_version + "." + project.minor_version + "." + project.build_version + "." + project.revision_version; if (!string.IsNullOrEmpty(project.product)) - compilerOptions.Product = project.product; + netCompilerOptions.Product = project.product; if (!string.IsNullOrEmpty(project.company)) - compilerOptions.Company = project.company; + netCompilerOptions.Company = project.company; if (!string.IsNullOrEmpty(project.trademark)) - compilerOptions.TradeMark = project.trademark; + netCompilerOptions.TradeMark = project.trademark; if (!string.IsNullOrEmpty(project.copyright)) - compilerOptions.Copyright = project.copyright; + netCompilerOptions.Copyright = project.copyright; if (!string.IsNullOrEmpty(project.title)) - compilerOptions.Title = project.title; + netCompilerOptions.Title = project.title; if (!string.IsNullOrEmpty(project.description)) - compilerOptions.Description = project.description; + netCompilerOptions.Description = project.description; if (project.ProjectType == ProjectType.WindowsApp) - compilerOptions.target = NETGenerator.TargetType.WinExe; + netCompilerOptions.target = NETGenerator.TargetType.WinExe; // при использовании учесть удаление res_file из этой функции при кодогенерации EVA // CreateRCFile(compilerOptions); } } - private void CreateRCFile(NETGenerator.CompilerOptions compilerOptions) + /*private void CreateRCFile(NETGenerator.CompilerOptions compilerOptions) { if (!string.IsNullOrEmpty(project.app_icon)) { @@ -2117,14 +1827,18 @@ namespace PascalABCCompiler sw.WriteLine("1 VERSIONINFO"); string ver = project.major_version + "," + project.minor_version + "," + project.build_version + "," + project.revision_version; sw.WriteLine("FILEVERSION " + ver); - /*sw.WriteLine("FILEFLAGSMASK VS_FFI_FILEFLAGSMASK"); + + // это было закомментировано ***** EVA + sw.WriteLine("FILEFLAGSMASK VS_FFI_FILEFLAGSMASK"); sw.WriteLine("FILEFLAGS VER_DEBUG"); sw.WriteLine("FILEOS VOS__WINDOWS32"); if (project.project_type != ProjectType.Library) sw.WriteLine("FILETYPE VFT_APP"); else sw.WriteLine("FILETYPE VFT_DLL"); - sw.WriteLine("FILESUBTYPE VFT2_UNKNOWN");*/ + sw.WriteLine("FILESUBTYPE VFT2_UNKNOWN"); + // до сюда ******* + sw.WriteLine("BEGIN \r\n BLOCK \"StringFileInfo\"\r\n BEGIN \r\n BLOCK \"041904E3\"\r\nBEGIN"); sw.WriteLine("VALUE \"ProductName\"," + "\"" + compilerOptions.Product + "\""); sw.WriteLine("VALUE \"FileVersion\"," + "\"" + ver + "\""); @@ -2160,27 +1874,27 @@ namespace PascalABCCompiler } File.Delete(rc_file); } - } + }*/ - private void SetTargetTypeOption(NETGenerator.CompilerOptions compilerOptions) + private void SetTargetTypeOption(NETGenerator.CompilerOptions netCompilerOptions) { - compilerOptions.ForRunningWithEnvironment = CompilerOptions.RunWithEnvironment; + netCompilerOptions.ForRunningWithEnvironment = CompilerOptions.RunWithEnvironment; // тип выходного файла - if (compilerOptions.target == NETGenerator.TargetType.Exe) // если еще не установлен согласно проекту + if (netCompilerOptions.target == NETGenerator.TargetType.Exe) // если еще не установлен согласно проекту { switch (CompilerOptions.OutputFileType) { - case CompilerOptions.OutputType.ClassLibrary: compilerOptions.target = NETGenerator.TargetType.Dll; break; - case CompilerOptions.OutputType.ConsoleApplicaton: compilerOptions.target = NETGenerator.TargetType.Exe; break; - case CompilerOptions.OutputType.WindowsApplication: compilerOptions.target = NETGenerator.TargetType.WinExe; break; + case CompilerOptions.OutputType.ClassLibrary: netCompilerOptions.target = NETGenerator.TargetType.Dll; break; + case CompilerOptions.OutputType.ConsoleApplicaton: netCompilerOptions.target = NETGenerator.TargetType.Exe; break; + case CompilerOptions.OutputType.WindowsApplication: netCompilerOptions.target = NETGenerator.TargetType.WinExe; break; } } // Debug / Release - compilerOptions.dbg_attrs = CompilerOptions.Debug ? NETGenerator.DebugAttributes.Debug : NETGenerator.DebugAttributes.Release; + netCompilerOptions.dbg_attrs = CompilerOptions.Debug ? NETGenerator.DebugAttributes.Debug : NETGenerator.DebugAttributes.Release; if (CompilerOptions.ForDebugging) - compilerOptions.dbg_attrs = NETGenerator.DebugAttributes.ForDebugging; + netCompilerOptions.dbg_attrs = NETGenerator.DebugAttributes.ForDebugging; } public string Compile() @@ -2203,7 +1917,7 @@ namespace PascalABCCompiler // если проект скомпилирован, то заполнение информации о проекте в опциях компилятора if (CompilerOptions.ProjectCompiled) { - PrepareCompileOptionsForProject(); + InitializeProjectInfoAndFillCompilerOptionsFromIt(); } #region CONSTRUCTING SYNTAX AND SEMANTIC TREES @@ -2222,7 +1936,7 @@ namespace PascalABCCompiler // Закрытие чтения и записи .pcu файлов ClosePCUReadersAndWriters(); - PrebuildMainSemanticTreeActions(out var compilerOptions, out var resourceFiles); + PrebuildMainSemanticTreeActions(out var netCompilerOptions, out var resourceFiles); #region GENERATING CODE if (ErrorsList.Count == 0) @@ -2230,7 +1944,7 @@ namespace PascalABCCompiler //TODO: Разобратся c location для program_node и правильно передавать main_function. Добавить генератор main_function в SyntaxTreeToSemanticTreeConverter. | Отложено на потом EVA // получние полного семантического дерева, включающего все зависимости - program_node semanticTree = ConstructMainSemanticTree(compilerOptions); + program_node semanticTree = ConstructMainSemanticTree(netCompilerOptions); if (firstCompilationUnit.SyntaxTree is SyntaxTree.unit_module && CompilerOptions.OutputFileType != CompilerOptions.OutputType.ClassLibrary) { @@ -2241,9 +1955,9 @@ namespace PascalABCCompiler else if (CompilerOptions.GenerateCode) { if (CompilerOptions.UseDllForSystemUnits) - compilerOptions.RtlPABCSystemType = NetHelper.NetHelper.FindRtlType("PABCSystem.PABCSystem"); + netCompilerOptions.RtlPABCSystemType = NetHelper.NetHelper.FindRtlType("PABCSystem.PABCSystem"); - GenerateILCode(semanticTree, compilerOptions, resourceFiles); + GenerateILCode(semanticTree, netCompilerOptions, resourceFiles); } } #endregion @@ -2306,10 +2020,10 @@ namespace PascalABCCompiler /// /// Сохраняет документацию для модулей; /// Выясняет тип выходного файла, целевой фреймворк, платформу; - /// Заполняет опции компиляции согласно директивам и/или информации из проекта; + /// Заполняет опции .NET компиляции согласно директивам и/или информации из проекта; /// Находит ресурсные файлы из директив /// - private void PrebuildMainSemanticTreeActions(out NETGenerator.CompilerOptions compilerOptions, out List resourceFiles) + private void PrebuildMainSemanticTreeActions(out NETGenerator.CompilerOptions netCompilerOptions, out List resourceFiles) { if (CompilerOptions.SaveDocumentation) { @@ -2324,22 +2038,22 @@ namespace PascalABCCompiler // перемещаем PABCSystem в начало списка // MoveSystemUnitForwardInUnitsTopologicallySortedList(); - compilerOptions = new NETGenerator.CompilerOptions(); + netCompilerOptions = new NETGenerator.CompilerOptions(); // выяснение TargetFramework и целевой платформы - SetOutputPlatformOption(compilerOptions, compilerDirectives); + SetOutputPlatformOption(netCompilerOptions, compilerDirectives); // заполнение опций компилятора из директив - FillCompilerInfoOptions(compilerOptions, compilerDirectives); + FillNetCompilerOptionsFromCompilerDirectives(netCompilerOptions, compilerDirectives); // получние путей к файлам ресурсов из директив resourceFiles = GetResourceFilesFromCompilerDirectives(compilerDirectives); // заполнение опций компилятора из заголовка проекта - FillCompilerOptionsFromProject(compilerOptions); + FillNetCompilerOptionsFromProject(netCompilerOptions); // Устанавливает опции компилятора, связанные с типом выходного файла - SetTargetTypeOption(compilerOptions); + SetTargetTypeOption(netCompilerOptions); } private program_node ConstructMainSemanticTree(NETGenerator.CompilerOptions compilerOptions) @@ -2546,7 +2260,7 @@ namespace PascalABCCompiler if (File.Exists(resourceFileName)) ResourceFiles.Add(resourceFileName); else - ErrorsList.Add(new ResourceFileNotFound(cd.directive, cd.location)); + ErrorsList.Add(new ResourceFileNotFound(cd.location.doc.file_name, cd.directive, cd.location)); } } @@ -2608,7 +2322,7 @@ namespace PascalABCCompiler ClosePCUWriters(); } - void WaitCallback_ClosePCUWriters(object state) + private void WaitCallback_ClosePCUWriters(object state) { ClosePCUWriters(); } @@ -3232,7 +2946,7 @@ namespace PascalABCCompiler { if (IsPossibleNetNamespaceOrStandardPasFile(name_space, false, Path.GetDirectoryName(file))) { - namespaceNode.referenced_units.AddElement(new namespace_unit_node(GetNamespace(name_space), get_location_from_treenode(name_space, unitModule.file_name)), null); + namespaceNode.referenced_units.AddElement(new namespace_unit_node(GetNamespace(name_space), GetLocationFromTreenode(name_space, unitModule.file_name)), null); } else { @@ -3293,12 +3007,12 @@ namespace PascalABCCompiler return files; } - private void SemanticCheckNoIncludeDirectivesInPascalUnit(CompilationUnit compilationUnit) + private void SemanticCheckNoIncludeNamespaceDirectivesInUnit(CompilationUnit currentUnit) { - if (compilationUnit.SyntaxTree is SyntaxTree.unit_module unitModule && HasIncludeNamespaceDirective(compilationUnit) + if (currentUnit.SyntaxTree is SyntaxTree.unit_module unitModule && HasIncludeNamespaceDirective(currentUnit) && unitModule.unit_name.HeaderKeyword != SyntaxTree.UnitHeaderKeyword.Library) { - throw new IncludeNamespaceInUnitError(currentCompilationUnit.SyntaxTree.file_name, currentCompilationUnit.SyntaxTree.source_context); + throw new IncludeNamespaceInUnitError(currentUnit.SyntaxTree.file_name, currentUnit.SyntaxTree.source_context); } } @@ -3482,7 +3196,7 @@ namespace PascalABCCompiler if (mightBeUnit && !fullNamespaceName.Contains(".")) throw new UnitNotFound(currentCompilationUnit.SyntaxTree.file_name, fullNamespaceName, name_space.source_context); - throw new TreeConverter.NamespaceNotFound(fullNamespaceName, get_location_from_treenode(name_space.name, currentCompilationUnit.SyntaxTree.file_name)); + throw new TreeConverter.NamespaceNotFound(fullNamespaceName, GetLocationFromTreenode(name_space.name, currentCompilationUnit.SyntaxTree.file_name)); } return new using_namespace(fullNamespaceName); } @@ -3663,8 +3377,7 @@ namespace PascalABCCompiler return currentUnit; // нет pcu и модуль не откомпилирован => новый модуль EVA - InitializeNewUnit(currentUnitNode, unitFileName, unitId, - ref currentUnit, ref docs); + InitializeNewUnit(unitFileName, unitId, ref currentUnit, ref docs); } // формирование списков зависимостей текущего модуля (uses list, dll, пространства имен) @@ -4012,7 +3725,7 @@ namespace PascalABCCompiler /// генерация синтаксического дерева, /// обработка синтаксических ошибок /// - private void InitializeNewUnit(SyntaxTree.unit_or_namespace currentUnitNode, string unitFileName, string UnitId, ref CompilationUnit currentUnit, ref Dictionary docs) + private void InitializeNewUnit(string unitFileName, string UnitId, ref CompilationUnit currentUnit, ref Dictionary docs) { currentUnit = new CompilationUnit(); if (firstCompilationUnit == null) @@ -4027,7 +3740,7 @@ namespace PascalABCCompiler #region SYNTAX TREE CONSTRUCTING // получение синтаксического дерева - string sourceText = GetSourceCode(currentUnitNode, unitFileName, currentUnit); + string sourceText = GetSourceCode(unitFileName, currentUnit); currentUnit.SyntaxTree = ConstructSyntaxTree(unitFileName, currentUnit, sourceText); #endregion @@ -4050,10 +3763,10 @@ namespace PascalABCCompiler SemanticCheckDLLDirectiveOnlyForLibraries(currentUnit.SyntaxTree, isDll, dllDirective); // ошибка - компилируем вторую основную программу или вторую dll вместо юнита - SemanticCheckCurrentUnitMustBePascalUnit(unitFileName, currentUnit, isDll); + SemanticCheckCurrentUnitMustBeUnitModule(unitFileName, currentUnit, isDll); // ошибка директива include в паскалевском юните - SemanticCheckNoIncludeDirectivesInPascalUnit(currentUnit); + SemanticCheckNoIncludeNamespaceDirectivesInUnit(currentUnit); #endregion if (isDll) @@ -4061,13 +3774,14 @@ namespace PascalABCCompiler currentUnit.CaseSensitive = currentUnit.Language.CaseSensitive; - currentUnit.SyntaxUnitName = currentUnitNode; + // currentUnit.SyntaxUnitName = currentUnitNode; // сопоставление нодам ошибок EVA MatchErrorsToBadNodes(currentUnit); CheckErrorsAndThrowTheFirstOne(); + // местоположение этой строчки важно, потому что проверяется UnitTable.Count > 0 выше EVA UnitTable[UnitId] = currentUnit; // здесь добавляем стандартные модули в секцию uses интерфейса @@ -4103,7 +3817,7 @@ namespace PascalABCCompiler // Синтактико-семантическая ошибка - проверка, что compilationUnit является модулем, // а не основной программой и не dll EVA - private void SemanticCheckCurrentUnitMustBePascalUnit(string UnitFileName, CompilationUnit currentUnit, bool isDll) + private void SemanticCheckCurrentUnitMustBeUnitModule(string UnitFileName, CompilationUnit currentUnit, bool isDll) { if (UnitTable.Count > 0) // если это не главный модуль (программа в unittable всегда идет первой) { @@ -4169,7 +3883,7 @@ namespace PascalABCCompiler return syntaxTree; } - private string GetSourceCode(SyntaxTree.unit_or_namespace currentUnitNode, string UnitFileName, CompilationUnit currentUnit) + private string GetSourceCode(string UnitFileName, CompilationUnit currentUnit) { string SourceText = null; if (CompilerOptions.UnitSyntaxTree == null) @@ -4180,7 +3894,7 @@ namespace PascalABCCompiler if (currentUnit == firstCompilationUnit) throw new SourceFileNotFound(UnitFileName); else - throw new UnitNotFound(currentCompilationUnit.SyntaxTree.file_name, UnitFileName, currentUnitNode.source_context); + throw new UnitNotFound(currentUnit.SyntaxTree.file_name, UnitFileName, currentUnit.SyntaxTree.source_context); } } return SourceText; @@ -4192,7 +3906,7 @@ namespace PascalABCCompiler /// private bool CurrentUnitIsNotMainProgram() { - return currentCompilationUnit != firstCompilationUnit; + return UnitTable.Count > 0; } @@ -4638,7 +4352,6 @@ namespace PascalABCCompiler } RecompileList.Clear(); - CycleUnits.Clear(); UnitTable.Clear(); UnitsTopologicallySortedList.Clear(); //TreeRealization.PCUReturner.Clear(); diff --git a/Compiler/Compiler.csproj b/Compiler/Compiler.csproj index 86d9c234b..83f31d8ac 100644 --- a/Compiler/Compiler.csproj +++ b/Compiler/Compiler.csproj @@ -164,6 +164,7 @@ + @@ -173,9 +174,6 @@ - - Code - diff --git a/Compiler/Errors.cs b/Compiler/Errors.cs index 8fc693ba9..f0b5aa8a2 100644 --- a/Compiler/Errors.cs +++ b/Compiler/Errors.cs @@ -1,107 +1,429 @@ -// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) +// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) -namespace PascalABCCompiler + +using System; +using PascalABCCompiler.SyntaxTree; + +namespace PascalABCCompiler.Errors { - public class FileNotFound : TreeConverter.CompilationErrorWithLocation - { - private string _file_name; + /// + /// Базовый класс для ошибок, бросаемых компилятором + /// + public class CompilerThrownError : LocatedError + { + public CompilerThrownError(string message) + : base(message) + { + } + public CompilerThrownError(string message, string FileName) + : base(message, FileName) + { + } + public override string ToString() + { + return Message; + } + } - public FileNotFound(string file_name, TreeRealization.location loc):base(loc) - { - _file_name=file_name; - } + /// + /// Бросается в случае невозможности чтения pcu + /// + public class ReadPCUError : CompilerThrownError + { + public ReadPCUError(string FileName) + : base(string.Format(StringResources.Get("COMPILATIONERROR_READ_PCU{0}_ERROR"), FileName)) + { + } + } - public string file_name - { - get - { - return _file_name; - } - } + /// + /// Бросается в случае использования uses in в пространстве имен + /// + public class NamespaceCannotHaveInSection : CompilerThrownError + { + public NamespaceCannotHaveInSection(SyntaxTree.SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_NAMESPACE_CANNOT_HAVE_IN_SECTION"))) + { + this.source_context = sc; + } + } - public override string ToString() - { - return string.Format(StringResources.Get("COMPILATIONERROR_FILE_{0}_NOT_FOUND"), _file_name); + /// + /// Бросается, если встречена не основная программа (там где она должна быть) + /// + public class ProgramModuleExpected : CompilerThrownError + { + public ProgramModuleExpected(string FileName, SyntaxTree.SourceContext sc) + : base(StringResources.Get("COMPILATIONERROR_PROGRAM_MODULE_EXPECTED"), FileName) + { + this.source_context = sc; + } + } + + /// + /// Бросается, если встречен не модуль (там где он должна быть) + /// + public class UnitModuleExpected : CompilerThrownError + { + public UnitModuleExpected(string FileName, SyntaxTree.SourceContext sc) + : base(StringResources.Get("COMPILATIONERROR_UNIT_MODULE_EXPECTED"), FileName) + { + this.source_context = sc; + } + } + + /// + /// Бросается при обнаружении директивы {$apptype dll} не в библиотеке + /// + public class AppTypeDllIsAllowedOnlyForLibraries : CompilerThrownError + { + public AppTypeDllIsAllowedOnlyForLibraries(string FileName, SyntaxTree.SourceContext sc) + : base(StringResources.Get("COMPILATIONERROR_APPTYPE_DLL_IS_ALLOWED_ONLY_FOR_LIBRARIES"), FileName) + { + this.source_context = sc; + } + } + + /// + /// Бросается при компиляции библиотеки не первой + /// + public class UnitModuleExpectedLibraryFound : CompilerThrownError + { + public UnitModuleExpectedLibraryFound(string FileName, SyntaxTree.SourceContext sc) + : base(StringResources.Get("COMPILATIONERROR_UNIT_MODULE_EXPECTED_LIBRARY_FOUND"), FileName) + { + this.source_context = sc; + } + } + + /// + /// Бросается, если файл сборки не найден + /// + public class AssemblyNotFound : CompilerThrownError + { + public string AssemblyFileName; + public AssemblyNotFound(string FileName, string AssemblyFileName, SyntaxTree.SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_ASSEMBLY_{0}_NOT_FOUND"), AssemblyFileName), FileName) + { + this.AssemblyFileName = AssemblyFileName; + this.source_context = sc; } - } + } - public class DLLReadingError : TreeConverter.CompilationError - { - private string _dll_name; + /// + /// Бросается при невозможности чтения сборки + /// + public class AssemblyReadingError : CompilerThrownError + { + public string AssemblyFileName; + public AssemblyReadingError(string FileName, string AssemblyFileName, SyntaxTree.SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_ASSEMBLY_{0}_READING_ERROR"), AssemblyFileName), FileName) + { + this.AssemblyFileName = AssemblyFileName; + this.source_context = sc; + } + } - public DLLReadingError(string dll_name) - { - _dll_name=dll_name; - } + /// + /// Бросается при попытке обработки неправильного пути к сборке + /// + public class InvalidAssemblyPathError : CompilerThrownError + { + public InvalidAssemblyPathError(string FileName, SyntaxTree.SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_INVALID_ASSEMBLY_PATH")), FileName) + { + this.source_context = sc; + } + } - public string dll_name - { - get - { - return _dll_name; - } - } + /// + /// Бросается при попытке обработки неправильного пути к файлу + /// + public class InvalidPathError : CompilerThrownError + { + public InvalidPathError(SyntaxTree.SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_INVALID_PATH"))) + { + this.source_context = sc; + this.fileName = sc.FileName; + } + } - public override string ToString() - { - //return ("Dll: "+dll_name+" not found"); - return string.Format(StringResources.Get("COMPILATIONERROR_ASSEMBLY_{0}_READING_ERROR"), dll_name); - } + /// + /// Бросается при неудаче в нахождении файла ресурсов + /// + public class ResourceFileNotFound : CompilerThrownError + { + public ResourceFileNotFound(string fileName, string ResFileName, SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_RESOURCEFILE_{0}_NOT_FOUND"), ResFileName), fileName) + { + source_context = sc; + } + } - } + /// + /// Бросается при подключении явного пространства имен в модуле + /// + public class IncludeNamespaceInUnitError : CompilerThrownError + { + public IncludeNamespaceInUnitError(string FileName, SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_INCLUDE_NAMESPACE_IN_UNIT")), FileName) + { + this.source_context = sc; + } + } - public class InvalidUnit : TreeConverter.CompilationError - { - private string _unit_name; + /// + /// Бросается, если встречено не явное пространство имен + /// + public class NamespaceModuleExpected : CompilerThrownError + { + public NamespaceModuleExpected(SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_NAMESPACE_MODULE_EXPECTED"))) + { + this.source_context = sc; + } + } - public InvalidUnit(string unit_name) - { - _unit_name=unit_name; - } + /// + /// Бросается в случае некорректного использования директивы {$mainresource ...} + /// + public class MainResourceNotAllowed : CompilerThrownError + { + public MainResourceNotAllowed(string fileName, SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_MAINRESOURCE_NOT_ALLOWED")), fileName) + { + source_context = sc; + } - public string unit_name - { - get - { - return _unit_name; - } - } + } - public override string ToString() - { - return ("Invalid unit: "+_unit_name); - } + /// + /// Бросается при нахождении дубликатов в секции uses + /// + public class DuplicateUsesUnit : CompilerThrownError + { + public string UnitName; + public DuplicateUsesUnit(string FileName, string UnitName, SyntaxTree.SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_DUPLICATE_USES_UNIT{0}"), UnitName), FileName) + { + this.UnitName = UnitName; + this.source_context = sc; + } + } - } + /// + /// Бросается при нахождении дубликатов директив, не поддерживающих многократное использование в рамках некоторого контекста + /// + public class DuplicateDirective : CompilerThrownError + { + public string DirectiveName; + public DuplicateDirective(string FileName, string DirectiveName, SyntaxTree.SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_DUPLICATE_DIRECTIVE{0}"), DirectiveName), FileName) + { + this.DirectiveName = DirectiveName; + this.source_context = sc; + } + } - public class UnitCompilationError : TreeConverter.CompilationError - { - private SyntaxTree.unit_or_namespace _SyntaxUsesUnit; - private string _file_name; + /// + /// Legacy, бросается, если unitModule.unitName.HeaderKeyword == SyntaxTree.UnitHeaderKeyword.Namespace + /// + public class NamespacesCanBeCompiledOnlyInProjects : CompilerThrownError + { + public NamespacesCanBeCompiledOnlyInProjects(SyntaxTree.SourceContext sc) + : base(StringResources.Get("COMPILATIONERROR_NAMESPACE_CAN_BE_COMPILED_ONLY_IN_PROJECTS")) + { + this.source_context = sc; + } + } - public UnitCompilationError(string fileName,SyntaxTree.unit_or_namespace syntaxUsesUnit) - { - _SyntaxUsesUnit=syntaxUsesUnit; - _file_name=fileName; - } + /// + /// Бросается, если модуль (unit) не найден по некоторому пути + /// + public class UnitNotFound : CompilerThrownError + { + public string UnitName; + public UnitNotFound(string FileName, string UnitName, SyntaxTree.SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_UNIT_{0}_NOT_FOUND"), UnitName), FileName) + { + this.UnitName = UnitName; + this.source_context = sc; + } + } - public SyntaxTree.unit_or_namespace SyntaxUsesUnit - { - get - { - return _SyntaxUsesUnit; - } - } + /// + /// Бросается при некорректном пути в uses in + /// + public class UsesInWrongName : CompilerThrownError + { + public string UnitName1; + public string UnitName2; + public UsesInWrongName(string FileName, string UnitName1, string UnitName2, SyntaxTree.SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_USES_IN_WRONG_NAME"), UnitName1, UnitName2), FileName) + { + this.UnitName1 = UnitName1; + this.UnitName2 = UnitName2; + this.source_context = sc; + } + } - public string file_name - { - get - { - return _file_name; - } - } - } + /// + /// Бросается при невозможности найти исходник по некотрому пути + /// + public class SourceFileNotFound : CompilerThrownError + { + public SourceFileNotFound(string FileName) + : base(string.Format(StringResources.Get("COMPILATIONERROR_SOURCE_FILE_{0}_NOT_FOUND"), FileName)) + { + } + } + /// + /// Бросается при попытке файловой операции с недостаточными правами + /// + public class UnauthorizedAccessToFile : CompilerThrownError + { + public UnauthorizedAccessToFile(string FileName) + : base(string.Format(StringResources.Get("COMPILATIONERROR_NO_ACCESS_TO_FILE{0}"), FileName)) + { + } + } + + /// + /// Бросается в случае обнаружения циклической зависимости модулей + /// + public class CycleUnitReference : CompilerThrownError + { + public CycleUnitReference(string FileName, SyntaxTree.unit_or_namespace SyntaxUsesUnit) + : base(string.Format(StringResources.Get("COMPILATIONERROR_CYCLIC_UNIT_REFERENCE_WITH_UNIT_{0}"), SyntaxTree.Utils.IdentListToString(SyntaxUsesUnit.name.idents, ".")), FileName) + { + this.source_context = SyntaxUsesUnit.source_context; + } + } + + /// + /// Бросается, если пользователь указывает неподдерживаемый целевой framework + /// + public class UnsupportedTargetFramework : CompilerThrownError + { + public UnsupportedTargetFramework(string FrameworkName, SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_UNSUPPORTED_TARGETFRAMEWORK_{0}"), FrameworkName)) + { + this.source_context = sc; + } + } + + /// + /// Бросается, если пользователь указывает неподдерживаемую целевую платформу + /// + public class UnsupportedTargetPlatform : CompilerThrownError + { + public UnsupportedTargetPlatform(string platformName, SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_UNSUPPORTED_TARGET_PLATFORM{0}"), platformName)) + { + source_context = sc; + } + } + + /// + /// Бросается, если пользователь указывает неподдерживаемый тип выходного файла (например, в директиве {$apptype ...}) + /// + public class UnsupportedOutputFileType : CompilerThrownError + { + public UnsupportedOutputFileType(string outputFileType, SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_UNSUPPORTED_OUTPUT_FILE_TYPE{0}"), outputFileType)) + { + source_context = sc; + } + } + + /// + /// Бросается при отсутствии некоторого файла по некоторому пути + /// + public class FileNotFound : CompilerThrownError + { + public FileNotFound(string fileName, SourceContext sc) + : base(string.Format(StringResources.Get("COMPILATIONERROR_FILE_{0}_NOT_FOUND"), fileName)) + { + this.source_context = sc; + } + } + + /*public class DLLReadingError : TreeConverter.CompilationError + { + private string _dll_name; + + public DLLReadingError(string dll_name) + { + _dll_name = dll_name; + } + + public string dll_name + { + get + { + return _dll_name; + } + } + + public override string ToString() + { + //return ("Dll: "+dll_name+" not found"); + return string.Format(StringResources.Get("COMPILATIONERROR_ASSEMBLY_{0}_READING_ERROR"), dll_name); + } + } + + public class InvalidUnit : TreeConverter.CompilationError + { + private string _unit_name; + + public InvalidUnit(string unit_name) + { + _unit_name = unit_name; + } + + public string unit_name + { + get + { + return _unit_name; + } + } + + public override string ToString() + { + return ("Invalid unit: " + _unit_name); + } + } + + public class UnitCompilationError : TreeConverter.CompilationError + { + private SyntaxTree.unit_or_namespace _SyntaxUsesUnit; + private string _file_name; + + public UnitCompilationError(string fileName, SyntaxTree.unit_or_namespace syntaxUsesUnit) + { + _SyntaxUsesUnit = syntaxUsesUnit; + _file_name = fileName; + } + + public SyntaxTree.unit_or_namespace SyntaxUsesUnit + { + get + { + return _SyntaxUsesUnit; + } + } + + public string file_name + { + get + { + return _file_name; + } + } + }*/ } diff --git a/Compiler/PCU/PCUReader.cs b/Compiler/PCU/PCUReader.cs index 9fa3a2d72..aa8199172 100644 --- a/Compiler/PCU/PCUReader.cs +++ b/Compiler/PCU/PCUReader.cs @@ -223,7 +223,7 @@ namespace PascalABCCompiler.PCU { var FullUnitName = comp.FindPCUFileName(UnitName, dir, out _); - if (FullUnitName == null) throw new FileNotFound(UnitName, null); + if (FullUnitName == null) throw new Errors.FileNotFound(UnitName, null); return FullUnitName; } diff --git a/CompilerTools/CompilerTools.csproj b/CompilerTools/CompilerTools.csproj index 9979a3821..5af58fb88 100644 --- a/CompilerTools/CompilerTools.csproj +++ b/CompilerTools/CompilerTools.csproj @@ -61,7 +61,6 @@ - diff --git a/CompilerTools/Errors/Errors.cs b/CompilerTools/Errors/Errors.cs deleted file mode 100644 index 269f72aae..000000000 --- a/CompilerTools/Errors/Errors.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) -// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) -using System; -using System.IO; -using PascalABCCompiler.SyntaxTree; - -namespace PascalABCCompiler.Errors -{ - - public class SemanticError : LocatedError - { - public SemanticError(string Message, string fileName) - : base(Message,fileName) - { - this.fileName = fileName; - } - - public virtual SemanticTree.ILocation Location - { - get - { - return null; - } - } - - public SemanticError() - { - } - public override string ToString() - { - return String.Format(StringResources.Get("COMPILATIONERROR_UNDEFINED_SEMANTIC_ERROR{0}"), this.GetType().ToString()); - } - public override SourceLocation SourceLocation - { - get - { - if (sourceLocation != null) - return sourceLocation; - if (Location != null) - { - return new SourceLocation(Location.document.file_name, - Location.begin_line_num, Location.begin_column_num, Location.end_line_num, Location.end_column_num); - } - return null; - } - } - public override string Message - { - get - { - return (this.ToString()); - } - } - - } - - public class SemanticNonSupportedError : SemanticError - { - public SemanticNonSupportedError(string fileName) - : base("", fileName) - { - } - - } - - - - - - - -} diff --git a/CompilerTools/Errors/ErrorsStrategy.cs b/CompilerTools/Errors/ErrorsStrategy.cs index 2b62805c9..6f0fb44b2 100644 --- a/CompilerTools/Errors/ErrorsStrategy.cs +++ b/CompilerTools/Errors/ErrorsStrategy.cs @@ -1,8 +1,6 @@ // Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) -using System; using System.Collections.Generic; -using System.Text; namespace PascalABCCompiler.Errors { diff --git a/Errors/Errors.cs b/Errors/BaseErrors.cs similarity index 57% rename from Errors/Errors.cs rename to Errors/BaseErrors.cs index 8d116b3cc..3fb0a381f 100644 --- a/Errors/Errors.cs +++ b/Errors/BaseErrors.cs @@ -1,14 +1,18 @@ // Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) + using System; using System.IO; using PascalABCCompiler.SyntaxTree; namespace PascalABCCompiler.Errors { - public class Error:Exception - { - public Error(string Message) + /// + /// Базовый класс для всех ошибок проекта + /// + public class Error : Exception + { + public Error(string Message) : base(Message) { } @@ -24,9 +28,13 @@ namespace PascalABCCompiler.Errors public Error() { } - } - public class LocatedError:Error - { + } + + /// + /// Базовый класс для ошибки, содержащей информацию о позиции кода, вызвавшего ее + /// + public class LocatedError : Error + { protected SourceContext source_context = null; protected SourceLocation sourceLocation = null; public string fileName = null; @@ -55,14 +63,14 @@ namespace PascalABCCompiler.Errors fn = Path.GetFileName(file_name); return string.Format(StringResources.Get("PARSER_ERRORS_COMPILATION_ERROR{0}{1}{2}"), fn, pos, Message); */ - return (new CompilerInternalError("Errors.ToString",new Exception(string.Format("Не переопеределена {0}.ToString",this.GetType())))).ToString(); + return (new CompilerInternalError("Errors.ToString", new Exception(string.Format("Не переопеределена {0}.ToString", this.GetType())))).ToString(); } public virtual SourceLocation SourceLocation { get { - if(sourceLocation!=null) + if (sourceLocation != null) return sourceLocation; if (SourceContext != null) return new SourceLocation(FileName, SourceContext.begin_position.line_num, SourceContext.begin_position.column_num, SourceContext.end_position.line_num, SourceContext.end_position.column_num); @@ -86,35 +94,57 @@ namespace PascalABCCompiler.Errors return fileName; } } - } - - public class CommonCompilerError : Errors.LocatedError + } + + /// + /// Внутренняя ошибка компилятора (нештатная) + /// + public class CompilerInternalError : Error { - public CommonCompilerError(string mes, string fileName, int line, int col):base(mes,fileName) - { - this.sourceLocation = new SourceLocation(fileName,line,col,line,col); - this.source_context = new SyntaxTree.SourceContext(line,col,line,col); - } + public Exception exception = null; + public string Module; + public CompilerInternalError(string module, Exception exc) + : base(exc.ToString()) + { + Module = module; + exception = exc; + } public override string ToString() { - return string.Format("{0} ({1},{2}): {3}", Path.GetFileName(sourceLocation.FileName), sourceLocation.BeginPosition.Line, sourceLocation.BeginPosition.Column,this.Message); + return string.Format(StringResources.Get("COMPILER_INTERNAL_ERROR_IN_UNIT_{0}_:{1}"), Module, Message + ' ' + exception.ToString()); } } - - public class CompilerWarning : Errors.LocatedError + + /// + /// Обобщенный тип ошибки для случаев не требущих детального описания в Message + /// + public class CommonCompilerError : LocatedError { - public CompilerWarning() - { - - } - - public CompilerWarning(string Message, string fileName) + public CommonCompilerError(string mes, string fileName, int line, int col) : base(mes, fileName) + { + this.sourceLocation = new SourceLocation(fileName, line, col, line, col); + this.source_context = new SyntaxTree.SourceContext(line, col, line, col); + } + public override string ToString() + { + return string.Format("{0} ({1},{2}): {3}", Path.GetFileName(sourceLocation.FileName), sourceLocation.BeginPosition.Line, sourceLocation.BeginPosition.Column, this.Message); + } + } + + /// + /// Базовый класс для предупреждения + /// + public class CompilerWarning : LocatedError + { + public CompilerWarning() { } + + public CompilerWarning(string Message, string fileName) : base(Message) { this.fileName = fileName; } - - public override string Message + + public override string Message { get { @@ -122,19 +152,22 @@ namespace PascalABCCompiler.Errors } } } - + + /// + /// Обобщенный тип предупреждения + /// public class CommonWarning : CompilerWarning { - string _mes; - - public CommonWarning(string mes, string fileName, int line, int col):base(mes,fileName) - { - this.sourceLocation = new SourceLocation(fileName,line,col,line,col); - this.source_context = new SyntaxTree.SourceContext(line,col,line,col); - _mes = mes; - } - - public override string Message + string _mes; + + public CommonWarning(string mes, string fileName, int line, int col) : base(mes, fileName) + { + this.sourceLocation = new SourceLocation(fileName, line, col, line, col); + this.source_context = new SyntaxTree.SourceContext(line, col, line, col); + _mes = mes; + } + + public override string Message { get { @@ -142,7 +175,10 @@ namespace PascalABCCompiler.Errors } } } - + + /// + /// Базовый класс для синтаксической ошибки + /// public class SyntaxError : LocatedError { public syntax_tree_node bad_node; @@ -165,9 +201,9 @@ namespace PascalABCCompiler.Errors if (source_context.FileName != null) base.fileName = source_context.FileName; break; - } + } } while (bn != null); - + } bad_node = _bad_node; } @@ -178,7 +214,7 @@ namespace PascalABCCompiler.Errors public override string ToString() { - string snode=""; + string snode = ""; /*if (bad_node == null) snode = " (bad_node==null)"; else @@ -191,13 +227,6 @@ namespace PascalABCCompiler.Errors return Path.GetFileName(FileName) + pos + ": Синтаксическая ошибка : " + Message + snode; } - public override SourceContext SourceContext - { - get - { - return source_context; - } - } public override SourceLocation SourceLocation { get @@ -205,29 +234,72 @@ namespace PascalABCCompiler.Errors if (source_context == null) return null; return new SourceLocation(fileName, - source_context.begin_position.line_num,source_context.begin_position.column_num, + source_context.begin_position.line_num, source_context.begin_position.column_num, source_context.end_position.line_num, source_context.end_position.column_num); } } } - public class CompilerInternalError : Error + /// + /// Базовый класс для семантической ошибки + /// + public class SemanticError : LocatedError { - public Exception exception = null; - public string Module; - public CompilerInternalError(string module, Exception exc) - : base(exc.ToString()) + public SemanticError(string Message, string fileName) + : base(Message, fileName) + { + this.fileName = fileName; + } + + public virtual SemanticTree.ILocation Location + { + get + { + return null; + } + } + + public SemanticError() { - Module = module; - exception = exc; } public override string ToString() { - return String.Format(StringResources.Get("COMPILER_INTERNAL_ERROR_IN_UNIT_{0}_:{1}"), Module, Message+' '+ exception.ToString()); + return String.Format(StringResources.Get("COMPILATIONERROR_UNDEFINED_SEMANTIC_ERROR{0}"), this.GetType().ToString()); } + public override SourceLocation SourceLocation + { + get + { + if (sourceLocation != null) + return sourceLocation; + if (Location != null) + { + return new SourceLocation(Location.document.file_name, + Location.begin_line_num, Location.begin_column_num, Location.end_line_num, Location.end_column_num); + } + return null; + } + } + public override string Message + { + get + { + return (this.ToString()); + } + } + } + /// + /// Базовый класс для NotSupportedError из TreeConverter | возможно, излишний EVA + /// + public class SemanticNonSupportedError : SemanticError + { + public SemanticNonSupportedError(string fileName) + : base("", fileName) + { + } - + } } diff --git a/Errors/Errors.csproj b/Errors/Errors.csproj index 5d223359d..346b3029d 100644 --- a/Errors/Errors.csproj +++ b/Errors/Errors.csproj @@ -63,7 +63,7 @@ Config\globalassemblyinfo.cs - + @@ -71,6 +71,10 @@ {2DE2842F-0912-4251-BC0F-480854C44A13} Localization + + {613e0dda-aa8a-437c-ac45-507b47429ff9} + SemanticTree + {C2CAC65A-B2AE-4CCC-B067-E6B8E75DF73A} SyntaxTree diff --git a/LanguageIntegrator/BaseLanguage.cs b/LanguageIntegrator/BaseLanguage.cs index b01e73775..c4610cfde 100644 --- a/LanguageIntegrator/BaseLanguage.cs +++ b/LanguageIntegrator/BaseLanguage.cs @@ -14,6 +14,9 @@ namespace Languages.Facade public abstract class BaseLanguage : ILanguage { + /// + /// Все параметры должны быть не null (и не пустым массивом), кроме IDocParser в случае, если он не требуется + /// public BaseLanguage(string name, string version, string copyright, IParser parser, IDocParser docParser, List syntaxTreeConverters, syntax_tree_visitor syntaxTreeToSemanticTreeConverter, string[] filesExtensions, bool caseSensitive, string[] systemUnitNames) diff --git a/ParserTools/ParserTools.csproj b/ParserTools/ParserTools.csproj index abfdbfd42..a930a452e 100644 --- a/ParserTools/ParserTools.csproj +++ b/ParserTools/ParserTools.csproj @@ -73,8 +73,9 @@ - + + diff --git a/ParserTools/ParserTools/BaseParser.cs b/ParserTools/ParserTools/BaseParser.cs index d45c80ec5..67050d2c8 100644 --- a/ParserTools/ParserTools/BaseParser.cs +++ b/ParserTools/ParserTools/BaseParser.cs @@ -30,6 +30,8 @@ namespace PascalABCCompiler.Parsers } } + public BaseKeywords Keywords { get; protected set; } + /// /// Возвращеает синтаксическое дерево модуля /// diff --git a/ParserTools/ParserTools/IParser.cs b/ParserTools/ParserTools/IParser.cs index e8d767f9e..94f9d1e4c 100644 --- a/ParserTools/ParserTools/IParser.cs +++ b/ParserTools/ParserTools/IParser.cs @@ -34,6 +34,11 @@ namespace PascalABCCompiler.Parsers get; } + /// + /// , + /// + BaseKeywords Keywords { get; } + compilation_unit GetCompilationUnit(string FileName, string Text, List Errors, List Warnings, ParseMode parseMode, List DefinesList = null); compilation_unit GetCompilationUnitForFormatter(string FileName, string Text, List Errors, List Warnings); diff --git a/ParserTools/ParserTools/Keywords/BaseKeywords.cs b/ParserTools/ParserTools/Keywords/BaseKeywords.cs new file mode 100644 index 000000000..80e7a6c78 --- /dev/null +++ b/ParserTools/ParserTools/Keywords/BaseKeywords.cs @@ -0,0 +1,77 @@ +// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) +// This code is distributed under the GNU LGPL (for details please see \doc\license.txt) +using System; +using System.Collections.Generic; +using System.Text; +using System.Linq; + +namespace PascalABCCompiler.Parsers +{ + public abstract class BaseKeywords + { + /// + /// Соотвествие ключевых слов токенам + /// + protected abstract Dictionary KeywordsToTokens { get; set; } + + /// + /// Словарь соответствий ключевых слов их эквивалентам (задается пользователем в специальном файле) + /// + private Dictionary keymap = new Dictionary(); + + /// + /// Название файла с информацией об эквивалентах ключевых слов + /// + protected abstract string FileName { get; } + + /// + /// Функция загрузки эквивалентов ключевых слов из файла + /// + private void ReloadKeyMap() + { + try + { + var pathToKeymapFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName), FileName); + + if (System.IO.File.Exists(pathToKeymapFile)) + keymap = System.IO.File.ReadLines(pathToKeymapFile, Encoding.Unicode).Select(s => s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).ToDictionary(w => w[0], w => w[1]); + } + catch (Exception e) + { + //var w = e.Message; + } + } + + /// + /// Возвращает само эквивалент ключевого слова, либо его само, если эквивалента нет + /// + public string ConvertKeyword(string keyword) + { + if (keymap.Count() == 0 || !keymap.ContainsKey(keyword)) + return keyword; + else + return keymap[keyword]; + } + + public BaseKeywords() + { + ReloadKeyMap(); + } + + /// + /// Возвращает токен, соответствующий идентификатору + /// + protected abstract int GetIdToken(); + + /// + /// Возвращает токен соответствующий ключевому слову, либо токен идентификатора, если такого ключевого слова нет + /// + public int KeywordOrIDToken(string keyword) + { + if (KeywordsToTokens.TryGetValue(keyword, out int token)) + return token; + else + return GetIdToken(); + } + } +} diff --git a/ParserTools/ParserTools/KeyWord.cs b/ParserTools/ParserTools/Keywords/KeywordKind.cs similarity index 89% rename from ParserTools/ParserTools/KeyWord.cs rename to ParserTools/ParserTools/Keywords/KeywordKind.cs index 64d849a98..cbf9479c3 100644 --- a/ParserTools/ParserTools/KeyWord.cs +++ b/ParserTools/ParserTools/Keywords/KeywordKind.cs @@ -1,8 +1,5 @@ -// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) +// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) -using System; -using System.Collections.Generic; -using System.Text; namespace PascalABCCompiler.Parsers { @@ -57,7 +54,8 @@ namespace PascalABCCompiler.Parsers CommonKeyword, CommonExpressionKeyword } - public class Keyword + + /*public class Keyword { string _name; KeywordKind _kind = KeywordKind.None; @@ -88,5 +86,5 @@ namespace PascalABCCompiler.Parsers { return Name; } - } + }*/ } diff --git a/Parsers/PascalABCParserNewSaushkin/ABCPascal.cs b/Parsers/PascalABCParserNewSaushkin/ABCPascal.cs index 3dc56fbf3..544e59e42 100644 --- a/Parsers/PascalABCParserNewSaushkin/ABCPascal.cs +++ b/Parsers/PascalABCParserNewSaushkin/ABCPascal.cs @@ -1,9 +1,9 @@ // // This CSharp output file generated by Gardens Point LEX // Version: 1.1.3.301 -// Machine: DESKTOP-G8V08V4 -// DateTime: 17.06.2024 16:43:45 -// UserName: ????????? +// Machine: DESKTOP-V3E9T2U +// DateTime: 11.07.2024 9:39:17 +// UserName: alex // GPLEX input file // GPLEX frame file // @@ -136,16 +136,19 @@ namespace Languages.Pascal.Frontend.Core #region user code public PascalParserTools parserTools; - Stack buffStack = new Stack(); - Stack fNameStack = new Stack(); - Stack IfDefInElseBranch = new Stack(); - Stack IfDefVar = new Stack(); + private PascalABCCompiler.Parsers.BaseKeywords keywords; + private Stack buffStack = new Stack(); + private Stack fNameStack = new Stack(); + private Stack IfDefInElseBranch = new Stack(); + private Stack IfDefVar = new Stack(); public List Defines = new List(); - int IfExclude; - string Pars; - LexLocation currentLexLocation; - bool HiddenIdents = false; - bool ExprMode = false; + private int IfExclude; + private string Pars; + private LexLocation currentLexLocation; + private bool HiddenIdents = false; + private bool ExprMode = false; + + public Scanner(PascalABCCompiler.Parsers.BaseKeywords keywords) { this.keywords = keywords; } #endregion user code int state; @@ -1854,7 +1857,7 @@ yylval = new Union(); yylval.ti = new token_info(yytext); return (int)Tokens.tkA break; case 28: string cur_yytext = yytext; - int res = Keywords.KeywordOrIDToken(cur_yytext); + int res = keywords.KeywordOrIDToken(cur_yytext); currentLexLocation = CurrentLexLocation; if (res == (int)Tokens.tkIdentifier) { diff --git a/Parsers/PascalABCParserNewSaushkin/ABCPascal.lex b/Parsers/PascalABCParserNewSaushkin/ABCPascal.lex index 229b3800e..bcebc27f6 100644 --- a/Parsers/PascalABCParserNewSaushkin/ABCPascal.lex +++ b/Parsers/PascalABCParserNewSaushkin/ABCPascal.lex @@ -1,15 +1,18 @@ %{ - public PascalParserTools parserTools; - Stack buffStack = new Stack(); - Stack fNameStack = new Stack(); - Stack IfDefInElseBranch = new Stack(); - Stack IfDefVar = new Stack(); + public PascalParserTools parserTools; + private PascalABCCompiler.Parsers.BaseKeywords keywords; + private Stack buffStack = new Stack(); + private Stack fNameStack = new Stack(); + private Stack IfDefInElseBranch = new Stack(); + private Stack IfDefVar = new Stack(); public List Defines = new List(); - int IfExclude; - string Pars; - LexLocation currentLexLocation; - bool HiddenIdents = false; - bool ExprMode = false; + private int IfExclude; + private string Pars; + private LexLocation currentLexLocation; + private bool HiddenIdents = false; + private bool ExprMode = false; + + public Scanner(PascalABCCompiler.Parsers.BaseKeywords keywords) { this.keywords = keywords; } %} %namespace Languages.Pascal.Frontend.Core @@ -276,7 +279,7 @@ UNICODEARROW \x890 [&]?[!]?{ID} { string cur_yytext = yytext; - int res = Keywords.KeywordOrIDToken(cur_yytext); + int res = keywords.KeywordOrIDToken(cur_yytext); currentLexLocation = CurrentLexLocation; if (res == (int)Tokens.tkIdentifier) { @@ -619,4 +622,4 @@ UNICODEARROW \x890 } } -// Статический класс, определяющий ключевые слова языка, находится в файле Keywords.cs +// Класс, определяющий ключевые слова языка, находится в файле Keywords.cs diff --git a/Parsers/PascalABCParserNewSaushkin/DocTagsParser/Parser.cs b/Parsers/PascalABCParserNewSaushkin/DocTagsParser/Parser.cs index b530734c5..aed106218 100644 --- a/Parsers/PascalABCParserNewSaushkin/DocTagsParser/Parser.cs +++ b/Parsers/PascalABCParserNewSaushkin/DocTagsParser/Parser.cs @@ -16,21 +16,10 @@ namespace Languages.Pascal.Frontend.Documentation public PascalDocTagsLanguageParser() { - filesExtensions = new string[1]; - filesExtensions[0] = ".pasdt" + StringConstants.hideParserExtensionPostfixChar; sectionNames.Add("summary"); sectionNames.Add("returns"); } - string[] filesExtensions; - public string[] FilesExtensions - { - get - { - return filesExtensions; - } - } - documentation_comment_section parse_section(string text) { documentation_comment_section dcs = new documentation_comment_section(); diff --git a/Parsers/PascalABCParserNewSaushkin/Keywords.cs b/Parsers/PascalABCParserNewSaushkin/Keywords.cs index 0420886a9..5c027544a 100644 --- a/Parsers/PascalABCParserNewSaushkin/Keywords.cs +++ b/Parsers/PascalABCParserNewSaushkin/Keywords.cs @@ -3,167 +3,127 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; namespace Languages.Pascal.Frontend.Core { - // Статический класс, определяющий ключевые слова языка - public static class Keywords + + public class PascalABCKeywords : PascalABCCompiler.Parsers.BaseKeywords { - private static Dictionary keywords = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - public static Dictionary keymap = new Dictionary(); + protected override string FileName => "keywordsmap.pabc"; - public static string fname = "keywordsmap.pabc"; - public static void ReloadKeyMap() + protected override Dictionary KeywordsToTokens { get; set; } + + public PascalABCKeywords() : base() { - try + KeywordsToTokens = new Dictionary { - if (keymap != null) - { - keymap.Clear(); - keymap = null; - } - var fn = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName), fname); - if (System.IO.File.Exists(fn)) - keymap = System.IO.File.ReadLines(fn,Encoding.Unicode).Select(s=>s.Split(new char[] { ' ' },StringSplitOptions.RemoveEmptyEntries)).ToDictionary(w => w[0], w => w[1]); + ["or"] = (int)Tokens.tkOr, + ["xor"] = (int)Tokens.tkXor, + ["and"] = (int)Tokens.tkAnd, + ["div"] = (int)Tokens.tkDiv, + ["mod"] = (int)Tokens.tkMod, + ["shl"] = (int)Tokens.tkShl, + ["shr"] = (int)Tokens.tkShr, + ["not"] = (int)Tokens.tkNot, + ["as"] = (int)Tokens.tkAs, + ["in"] = (int)Tokens.tkIn, + ["is"] = (int)Tokens.tkIs, + ["implicit"] = (int)Tokens.tkImplicit, + ["explicit"] = (int)Tokens.tkExplicit, + ["sizeof"] = (int)Tokens.tkSizeOf, + ["typeof"] = (int)Tokens.tkTypeOf, + ["where"] = (int)Tokens.tkWhere, + ["array"] = (int)Tokens.tkArray, + ["begin"] = (int)Tokens.tkBegin, + ["case"] = (int)Tokens.tkCase, + ["class"] = (int)Tokens.tkClass, + ["const"] = (int)Tokens.tkConst, + ["constructor"] = (int)Tokens.tkConstructor, + ["default"] = (int)Tokens.tkDefault, + ["destructor"] = (int)Tokens.tkDestructor, + ["downto"] = (int)Tokens.tkDownto, + ["do"] = (int)Tokens.tkDo, + ["else"] = (int)Tokens.tkElse, + ["end"] = (int)Tokens.tkEnd, + ["event"] = (int)Tokens.tkEvent, + ["except"] = (int)Tokens.tkExcept, + ["exports"] = (int)Tokens.tkExports, + ["file"] = (int)Tokens.tkFile, + ["finalization"] = (int)Tokens.tkFinalization, + ["finally"] = (int)Tokens.tkFinally, + ["for"] = (int)Tokens.tkFor, + ["foreach"] = (int)Tokens.tkForeach, + ["function"] = (int)Tokens.tkFunction, + ["goto"] = (int)Tokens.tkGoto, + ["if"] = (int)Tokens.tkIf, + ["implementation"] = (int)Tokens.tkImplementation, + ["inherited"] = (int)Tokens.tkInherited, + ["initialization"] = (int)Tokens.tkInitialization, + ["interface"] = (int)Tokens.tkInterface, + ["label"] = (int)Tokens.tkLabel, + ["lock"] = (int)Tokens.tkLock, + ["loop"] = (int)Tokens.tkLoop, + ["nil"] = (int)Tokens.tkNil, + ["procedure"] = (int)Tokens.tkProcedure, + ["of"] = (int)Tokens.tkOf, + ["operator"] = (int)Tokens.tkOperator, + ["property"] = (int)Tokens.tkProperty, + ["raise"] = (int)Tokens.tkRaise, + ["record"] = (int)Tokens.tkRecord, + ["repeat"] = (int)Tokens.tkRepeat, + ["set"] = (int)Tokens.tkSet, + ["try"] = (int)Tokens.tkTry, + ["type"] = (int)Tokens.tkType, + ["then"] = (int)Tokens.tkThen, + ["to"] = (int)Tokens.tkTo, + ["until"] = (int)Tokens.tkUntil, + ["uses"] = (int)Tokens.tkUses, + ["var"] = (int)Tokens.tkVar, + ["while"] = (int)Tokens.tkWhile, + ["with"] = (int)Tokens.tkWith, + ["program"] = (int)Tokens.tkProgram, + ["template"] = (int)Tokens.tkTemplate, + ["resourcestring"] = (int)Tokens.tkResourceString, + ["threadvar"] = (int)Tokens.tkThreadvar, + ["sealed"] = (int)Tokens.tkSealed, + ["partial"] = (int)Tokens.tkPartial, + ["params"] = (int)Tokens.tkParams, + ["unit"] = (int)Tokens.tkUnit, + ["library"] = (int)Tokens.tkLibrary, + ["external"] = (int)Tokens.tkExternal, + ["name"] = (int)Tokens.tkName, + ["private"] = (int)Tokens.tkPrivate, + ["protected"] = (int)Tokens.tkProtected, + ["public"] = (int)Tokens.tkPublic, + ["internal"] = (int)Tokens.tkInternal, + ["read"] = (int)Tokens.tkRead, + ["write"] = (int)Tokens.tkWrite, + ["on"] = (int)Tokens.tkOn, + ["forward"] = (int)Tokens.tkForward, + ["abstract"] = (int)Tokens.tkAbstract, + ["overload"] = (int)Tokens.tkOverload, + ["reintroduce"] = (int)Tokens.tkReintroduce, + ["override"] = (int)Tokens.tkOverride, + ["virtual"] = (int)Tokens.tkVirtual, + ["extensionmethod"] = (int)Tokens.tkExtensionMethod, + ["new"] = (int)Tokens.tkNew, + ["auto"] = (int)Tokens.tkAuto, + ["sequence"] = (int)Tokens.tkSequence, + ["yield"] = (int)Tokens.tkYield, + ["match"] = (int)Tokens.tkMatch, + ["when"] = (int)Tokens.tkWhen, + ["namespace"] = (int)Tokens.tkNamespace, + ["static"] = (int)Tokens.tkStatic, + ["step"] = (int)Tokens.tkStep, + ["index"] = (int)Tokens.tkIndex, + ["async"] = (int)Tokens.tkAsync, + ["await"] = (int)Tokens.tkAwait } - catch(Exception e) // погасить любые исключения - { - //var w = e.Message; - } - } - public static string Convert(string s) - { - if (keymap == null || keymap.Count() == 0) - return s; - else if (!keymap.ContainsKey(s)) - return s; - else return keymap[s]; + .ToDictionary(kv => ConvertKeyword(kv.Key), kv => kv.Value, StringComparer.CurrentCultureIgnoreCase); } - public static void KeywordsAdd() - { - if (keymap == null || keymap.Count() == 0) - ReloadKeyMap(); - keywords.Clear(); - keywords.Add(Convert("or"), (int)Tokens.tkOr); - keywords.Add(Convert("xor"), (int)Tokens.tkXor); - keywords.Add(Convert("and"), (int)Tokens.tkAnd); - keywords.Add(Convert("div"), (int)Tokens.tkDiv); - keywords.Add(Convert("mod"), (int)Tokens.tkMod); - keywords.Add(Convert("shl"), (int)Tokens.tkShl); - keywords.Add(Convert("shr"), (int)Tokens.tkShr); - keywords.Add(Convert("not"), (int)Tokens.tkNot); - keywords.Add(Convert("as"), (int)Tokens.tkAs); - keywords.Add(Convert("in"), (int)Tokens.tkIn); - keywords.Add(Convert("is"), (int)Tokens.tkIs); - keywords.Add(Convert("implicit"), (int)Tokens.tkImplicit); - keywords.Add(Convert("explicit"), (int)Tokens.tkExplicit); - keywords.Add(Convert("sizeof"), (int)Tokens.tkSizeOf); - keywords.Add(Convert("typeof"), (int)Tokens.tkTypeOf); - keywords.Add(Convert("where"), (int)Tokens.tkWhere); - keywords.Add(Convert("array"), (int)Tokens.tkArray); - keywords.Add(Convert("begin"), (int)Tokens.tkBegin); - keywords.Add(Convert("case"), (int)Tokens.tkCase); - keywords.Add(Convert("class"), (int)Tokens.tkClass); - keywords.Add(Convert("const"), (int)Tokens.tkConst); - keywords.Add(Convert("constructor"), (int)Tokens.tkConstructor); - keywords.Add(Convert("default"), (int)Tokens.tkDefault); - keywords.Add(Convert("destructor"), (int)Tokens.tkDestructor); - keywords.Add(Convert("downto"), (int)Tokens.tkDownto); - keywords.Add(Convert("do"), (int)Tokens.tkDo); - keywords.Add(Convert("else"), (int)Tokens.tkElse); - keywords.Add(Convert("end"), (int)Tokens.tkEnd); - keywords.Add(Convert("event"), (int)Tokens.tkEvent); - keywords.Add(Convert("except"), (int)Tokens.tkExcept); - keywords.Add(Convert("exports"), (int)Tokens.tkExports); - keywords.Add(Convert("file"), (int)Tokens.tkFile); - keywords.Add(Convert("finalization"), (int)Tokens.tkFinalization); - keywords.Add(Convert("finally"), (int)Tokens.tkFinally); - keywords.Add(Convert("for"), (int)Tokens.tkFor); - keywords.Add(Convert("foreach"), (int)Tokens.tkForeach); - keywords.Add(Convert("function"), (int)Tokens.tkFunction); - keywords.Add(Convert("goto"), (int)Tokens.tkGoto); - keywords.Add(Convert("if"), (int)Tokens.tkIf); - keywords.Add(Convert("implementation"), (int)Tokens.tkImplementation); - keywords.Add(Convert("inherited"), (int)Tokens.tkInherited); - keywords.Add(Convert("initialization"), (int)Tokens.tkInitialization); - keywords.Add(Convert("interface"), (int)Tokens.tkInterface); - keywords.Add(Convert("label"), (int)Tokens.tkLabel); - keywords.Add(Convert("lock"), (int)Tokens.tkLock); - keywords.Add(Convert("loop"), (int)Tokens.tkLoop); - keywords.Add(Convert("nil"), (int)Tokens.tkNil); - keywords.Add(Convert("procedure"), (int)Tokens.tkProcedure); - keywords.Add(Convert("of"), (int)Tokens.tkOf); - keywords.Add(Convert("operator"), (int)Tokens.tkOperator); - keywords.Add(Convert("property"), (int)Tokens.tkProperty); - keywords.Add(Convert("raise"), (int)Tokens.tkRaise); - keywords.Add(Convert("record"), (int)Tokens.tkRecord); - keywords.Add(Convert("repeat"), (int)Tokens.tkRepeat); - keywords.Add(Convert("set"), (int)Tokens.tkSet); - keywords.Add(Convert("try"), (int)Tokens.tkTry); - keywords.Add(Convert("type"), (int)Tokens.tkType); - keywords.Add(Convert("then"), (int)Tokens.tkThen); - keywords.Add(Convert("to"), (int)Tokens.tkTo); - keywords.Add(Convert("until"), (int)Tokens.tkUntil); - keywords.Add(Convert("uses"), (int)Tokens.tkUses); - keywords.Add(Convert("var"), (int)Tokens.tkVar); - keywords.Add(Convert("while"), (int)Tokens.tkWhile); - keywords.Add(Convert("with"), (int)Tokens.tkWith); - keywords.Add(Convert("program"), (int)Tokens.tkProgram); - keywords.Add(Convert("template"), (int)Tokens.tkTemplate); - keywords.Add(Convert("resourcestring"), (int)Tokens.tkResourceString); - keywords.Add(Convert("threadvar"), (int)Tokens.tkThreadvar); - keywords.Add(Convert("sealed"), (int)Tokens.tkSealed); - keywords.Add(Convert("partial"), (int)Tokens.tkPartial); - keywords.Add(Convert("params"), (int)Tokens.tkParams); - keywords.Add(Convert("unit"), (int)Tokens.tkUnit); - keywords.Add(Convert("library"), (int)Tokens.tkLibrary); - keywords.Add(Convert("external"), (int)Tokens.tkExternal); - keywords.Add(Convert("name"), (int)Tokens.tkName); - keywords.Add(Convert("private"), (int)Tokens.tkPrivate); - keywords.Add(Convert("protected"), (int)Tokens.tkProtected); - keywords.Add(Convert("public"), (int)Tokens.tkPublic); - keywords.Add(Convert("internal"), (int)Tokens.tkInternal); - keywords.Add(Convert("read"), (int)Tokens.tkRead); - keywords.Add(Convert("write"), (int)Tokens.tkWrite); - keywords.Add(Convert("on"), (int)Tokens.tkOn); - keywords.Add(Convert("forward"), (int)Tokens.tkForward); - keywords.Add(Convert("abstract"), (int)Tokens.tkAbstract); - keywords.Add(Convert("overload"), (int)Tokens.tkOverload); - keywords.Add(Convert("reintroduce"), (int)Tokens.tkReintroduce); - keywords.Add(Convert("override"), (int)Tokens.tkOverride); - keywords.Add(Convert("virtual"), (int)Tokens.tkVirtual); - keywords.Add(Convert("extensionmethod"), (int)Tokens.tkExtensionMethod); - keywords.Add(Convert("new"), (int)Tokens.tkNew); - keywords.Add(Convert("auto"), (int)Tokens.tkAuto); - keywords.Add(Convert("sequence"), (int)Tokens.tkSequence); - keywords.Add(Convert("yield"), (int)Tokens.tkYield); - keywords.Add(Convert("match"), (int)Tokens.tkMatch); - keywords.Add(Convert("when"), (int)Tokens.tkWhen); - keywords.Add(Convert("namespace"), (int)Tokens.tkNamespace); - keywords.Add(Convert("static"), (int)Tokens.tkStatic); - keywords.Add(Convert("step"), (int)Tokens.tkStep); - keywords.Add(Convert("index"), (int)Tokens.tkIndex); - keywords.Add(Convert("async"), (int)Tokens.tkAsync); - keywords.Add(Convert("await"), (int)Tokens.tkAwait); - } - - static Keywords() - { - KeywordsAdd(); - } - - public static int KeywordOrIDToken(string s) - { - //s = s.ToUpper(); - int keyword = 0; - if (keywords.TryGetValue(s, out keyword)) - return keyword; - else - return (int)Tokens.tkIdentifier; - } + protected override int GetIdToken() => (int)Tokens.tkIdentifier; } } diff --git a/Parsers/PascalABCParserNewSaushkin/Parser.cs b/Parsers/PascalABCParserNewSaushkin/Parser.cs index 9272d7a5a..59ab4e79d 100644 --- a/Parsers/PascalABCParserNewSaushkin/Parser.cs +++ b/Parsers/PascalABCParserNewSaushkin/Parser.cs @@ -78,6 +78,7 @@ namespace Languages.Pascal.Frontend.Wrapping public PascalABCNewLanguageParser() { InitializeValidDirectives(); + Keywords = new PascalABCKeywords(); } public override void Reset() @@ -156,7 +157,7 @@ namespace Languages.Pascal.Frontend.Wrapping parserTools.currentFileName = Path.GetFullPath(fileName); - Scanner scanner = new Scanner(); + Scanner scanner = new Scanner(Keywords); scanner.SetSource(Text, 0); scanner.parserTools = parserTools; // передали parserTools в объект сканера if (definesList != null) diff --git a/Parsers/PascalABCParserNewSaushkin/SemanticRulesForYacc.cs b/Parsers/PascalABCParserNewSaushkin/SemanticRulesForYacc.cs index dd16209e0..a6540fc38 100644 --- a/Parsers/PascalABCParserNewSaushkin/SemanticRulesForYacc.cs +++ b/Parsers/PascalABCParserNewSaushkin/SemanticRulesForYacc.cs @@ -403,7 +403,7 @@ namespace Languages.Pascal.Frontend.Core parserTools.warnings = new List(); parserTools.currentFileName = System.IO.Path.GetFullPath(this.parserTools.currentFileName); parserTools.buildTreeForFormatterStrings = true; - Scanner scanner = new Scanner(); + Scanner scanner = new Scanner(this.parserTools.ParserRef.Keywords); scanner.SetSource("<>"+Text, 0); scanner.parserTools = parserTools;// передали parserTools в объект сканера GPPGParser parser = new GPPGParser(scanner); diff --git a/StringConstants/StringConstants.cs b/StringConstants/StringConstants.cs index 8f7dd097a..e580a8ff4 100644 --- a/StringConstants/StringConstants.cs +++ b/StringConstants/StringConstants.cs @@ -372,10 +372,6 @@ namespace PascalABCCompiler public const string pascalLanguageDllName = "PascalLanguage.dll"; #endregion - #region PARSERS - public const char hideParserExtensionPostfixChar = '_'; - #endregion - public static string get_array_type_name(string type_name, int rank) { if (rank == 1) diff --git a/TreeConverter/TreeConversion/CompilationErrors.cs b/TreeConverter/TreeConversion/CompilationErrors.cs index aedc64243..49d4159bd 100644 --- a/TreeConverter/TreeConversion/CompilationErrors.cs +++ b/TreeConverter/TreeConversion/CompilationErrors.cs @@ -7,7 +7,6 @@ using System.Collections.Generic; using PascalABCCompiler.SemanticTree; using PascalABCCompiler.TreeRealization; -using PascalABCCompiler.TreeConverter; namespace PascalABCCompiler.TreeConverter {