diff --git a/.gitignore b/.gitignore index b0ab0f323..9a9c16ce8 100644 --- a/.gitignore +++ b/.gitignore @@ -37,6 +37,7 @@ **/CompilerController.dll **/CompilerTools.dll **/Errors.dll +**/ShiftReduceParser.dll **/HelpBuilder.dll **/InternalErrorReport.dll **/LambdaAnySynToSemConverter.dll @@ -70,6 +71,7 @@ **/PascalABCNET.exe.config **/PascalABCNETLinux.exe **/PascalABCNETLinux.exe.config +**/UniversalParserHelper.dll diff --git a/CodeCompletion/CodeCompletion.cs b/CodeCompletion/CodeCompletion.cs index a3b02ba60..02a9bc486 100644 --- a/CodeCompletion/CodeCompletion.cs +++ b/CodeCompletion/CodeCompletion.cs @@ -133,8 +133,8 @@ namespace CodeCompletion Warnings.Clear(); try { - //cu = ParsersController.GetComilationUnit(FileName, Text+")))));end.",comp.CompilerOptions.ParserSearchPatchs,ErrorsList); - //cu = ParsersControllerGetComilationUnit(FileName, get_temp_text(Text), ErrorsList, true); + //cu = ParsersController.GetComilationUnit(file_name, Text+")))));end.",comp.CompilerOptions.ParserSearchPatchs,ErrorsList); + //cu = ParsersControllerGetComilationUnit(file_name, get_temp_text(Text), ErrorsList, true); string tmp = ParsersHelper.GetModifiedProgramm(Text); if (tmp != null) { @@ -164,7 +164,7 @@ namespace CodeCompletion } } if (docs != null) docs.Clear(); - //if (dconv.is_compiled) comp_modules[FileName]=dconv; + //if (dconv.is_compiled) comp_modules[file_name]=dconv; return dconv; //ConvertToDom(cu); } @@ -233,7 +233,7 @@ namespace CodeCompletion { ErrorsList.Clear(); Warnings.Clear(); - //cu = ParsersControllerGetComilationUnit(FileName, Text, ErrorsList, true); + //cu = ParsersControllerGetComilationUnit(file_name, Text, ErrorsList, true); if (comp_modules[FileName] == null) { string tmp = ParsersHelper.GetModifiedProgramm(Text); @@ -260,7 +260,7 @@ namespace CodeCompletion dconv.ConvertToDom(cu); } } - //comp_modules[FileName] = dconv; + //comp_modules[file_name] = dconv; if (dconv.is_compiled) comp_modules[FileName] = dconv; if (docs != null) docs.Clear(); @@ -299,7 +299,7 @@ namespace CodeCompletion { ErrorsList.Clear(); Warnings.Clear(); - //cu = ParsersControllerGetComilationUnit(FileName, Text, ErrorsList, true); + //cu = ParsersControllerGetComilationUnit(file_name, Text, ErrorsList, true); if (comp_modules[FileName] == null) { string tmp = ParsersHelper.GetModifiedProgramm(Text); @@ -327,7 +327,7 @@ namespace CodeCompletion } if (dconv.is_compiled) comp_modules[FileName] = dconv; if (docs != null) docs.Clear(); - //comp_modules[FileName] = dconv; + //comp_modules[file_name] = dconv; // GC.Collect(); return dconv; } @@ -376,9 +376,11 @@ namespace CodeCompletion const string LibSourceDirectoryIdent = "%LIBSOURCEDIRECTORY%"; public static string FindSourceFileName(string unit_name, out int found_dir_ind, params string[] ddirs) { + // TODO: check error in older version List Dirs = new List(); Dirs.AddRange(ddirs); - Dirs.AddRange(CodeCompletionController.comp.CompilerOptions.SearchDirectory); + if (CodeCompletionController.comp != null) + Dirs.AddRange(CodeCompletionController.comp.CompilerOptions.SearchDirectory); if (CodeCompletionController.StandartDirectories.ContainsKey(LibSourceDirectoryIdent)) Dirs.Add((string)CodeCompletionController.StandartDirectories[LibSourceDirectoryIdent]); return CodeCompletionController.comp.FindSourceFileNameInDirs(unit_name, out found_dir_ind, Dirs.ToArray()); diff --git a/CodeCompletion/DomSyntaxTreeVisitor.cs b/CodeCompletion/DomSyntaxTreeVisitor.cs index 0af8994d3..e543ddbae 100644 --- a/CodeCompletion/DomSyntaxTreeVisitor.cs +++ b/CodeCompletion/DomSyntaxTreeVisitor.cs @@ -4829,7 +4829,7 @@ namespace CodeCompletion { //throw new Exception("The method or operation is not implemented."); SymScope tmp = cur_scope; - unl.clear(); + unl.Clear(); cur_scope = new ImplementationUnitScope(new SymInfo("$implementation", SymbolKind.Namespace, "implementation"), cur_scope); tmp.AddName("$implementation", cur_scope); (tmp as InterfaceUnitScope).impl_scope = cur_scope as ImplementationUnitScope; diff --git a/CodeCompletion/SymTable.cs b/CodeCompletion/SymTable.cs index 0d8c3d093..e1af7fb22 100644 --- a/CodeCompletion/SymTable.cs +++ b/CodeCompletion/SymTable.cs @@ -5250,7 +5250,7 @@ namespace CodeCompletion { this.name = name; this.si = new SymInfo(name, SymbolKind.Namespace, name); - this.si.description = CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + this.si.description = CodeCompletionController.CurrentParser?.LanguageInformation.GetDescription(this); } public override ScopeKind Kind @@ -5559,7 +5559,7 @@ namespace CodeCompletion } if (si.name == null) AssemblyDocCache.AddDescribeToComplete(this.si, ctn); - this.si.name = CodeCompletionController.CurrentParser.LanguageInformation.GetShortName(this); + this.si.name = CodeCompletionController.CurrentParser?.LanguageInformation.GetShortName(this); this.si.kind = get_kind(); this.si.description = GetDescription(); @@ -6196,7 +6196,7 @@ namespace CodeCompletion public override string GetDescription() { - return CodeCompletionController.CurrentParser.LanguageInformation.GetDescription(this); + return CodeCompletionController.CurrentParser?.LanguageInformation.GetDescription(this); } public override SymInfo[] GetNames(ExpressionVisitor ev, PascalABCCompiler.Parsers.KeywordKind keyword, bool called_in_base) diff --git a/Compiler/Compiler.cs b/Compiler/Compiler.cs index 58c224b33..e3f7ab765 100644 --- a/Compiler/Compiler.cs +++ b/Compiler/Compiler.cs @@ -1,14 +1,12 @@ // 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) - /*************************************************************************** - * - * Управляющий блок компилятора, алгоритм компиляции модулей - * Зависит от Errors,SyntaxTree,SemanticTree,Parsers,TreeConvertor, - * CodeGenerators - * - ***************************************************************************/ - -//TODO разобраться с ToLower()!!! +/*************************************************************************** +* +* Управляющий блок компилятора, алгоритм компиляции модулей +* Зависит от Errors,SyntaxTree,SemanticTree,Parsers,TreeConvertor, +* CodeGenerators +* +***************************************************************************/ #region algorithm /*************************************************************************** @@ -54,7 +52,7 @@ * ТаблицаМодулей[ИмяФайла]=ТекущийМодуль; * ТекущийМодуль.Состояние=BeginCompilation; * - * 5.СинтаксическийСписокМодулей=ТекущийМодуль.СинтаксическоеДерево.Interface.UsesList; + * 5.СинтаксическийСписокМодулей=ТекущийМодуль.СинтаксическоеДерево.Interface.usesList; * Для(i=СинтаксическийСписокМодулей.Количество-1-ТекущийМодуль.КомпилированыеВInterface.Количество;i>=0;i--) * ТекушийМодуль.ТекущийUsesМодуль=СинтаксическийСписокМодулей[i].ИмяФайла; * ИмяUsesФайла=СинтаксическийСписокМодулей[i].ИмяФайла; @@ -72,7 +70,7 @@ * ТекущийМодуль.КомпилированыеВInterface, * ТекущийМодуль.СписокОшибок); * СписокМодулей.Добавить(ТекущийМодуль); - * СинтаксическийСписокМодулей=ТекущийМодуль.СинтаксическоеДерево.Implementation.UsesList; + * СинтаксическийСписокМодулей=ТекущийМодуль.СинтаксическоеДерево.Implementation.usesList; * Для(i=СинтаксическийСписокМодулей.Количество-1;i>=0;i--) * Если (ТаблицаМодулей[СинтаксическийСписокМодулей[i].ИмяФайла].Состояние=BeginCompilation) * СписокОтложенойКомпиляции.Добавить(ТаблицаМодулей[СинтаксическийСписокМодулей[i].ИмяФайла]); @@ -142,30 +140,24 @@ #endregion #define DEBUG -//#undef DEBUG -using System; -using System.IO; -using System.Collections; -using System.Collections.Generic; -using System.Xml; +using ICSharpCode.NRefactory; +using Microsoft.Scripting; +using Microsoft.Scripting.Hosting; using PascalABCCompiler.Errors; using PascalABCCompiler.PCU; using PascalABCCompiler.SemanticTreeConverters; -using ICSharpCode.NRefactory; -using ICSharpCode.NRefactory.Parser.VB; -using System.CodeDom.Compiler; - -//using IronPython.Hosting; -using Microsoft.Scripting.Hosting; -using Microsoft.Scripting; -using System.Reflection; -//using SyntaxTreeChanger; using PascalABCCompiler.SyntaxTreeConverters; -using System.Text; using PascalABCCompiler.TreeRealization; + +using System; +using System.CodeDom.Compiler; +using System.Collections; +using System.Collections.Generic; +using System.IO; using System.Linq; +using System.Reflection; namespace PascalABCCompiler { @@ -188,7 +180,7 @@ namespace PascalABCCompiler public class ReadPCUError : CompilerCompilationError { public ReadPCUError(string FileName) - : base(string.Format(StringResources.Get("COMPILATIONERROR_READ_PCU{0}_ERROR"),FileName)) + : base(string.Format(StringResources.Get("COMPILATIONERROR_READ_PCU{0}_ERROR"), FileName)) { } } @@ -237,23 +229,23 @@ namespace PascalABCCompiler this.source_context = sc; } } - + public class AssemblyNotFound : CompilerCompilationError { public string AssemblyFileName; - public AssemblyNotFound(string FileName,string AssemblyFileName, SyntaxTree.SourceContext sc) + 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) + 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; @@ -263,7 +255,7 @@ namespace PascalABCCompiler public class InvalidAssemblyPathError : CompilerCompilationError { - public InvalidAssemblyPathError(string FileName,SyntaxTree.SourceContext sc) + public InvalidAssemblyPathError(string FileName, SyntaxTree.SourceContext sc) : base(string.Format(StringResources.Get("COMPILATIONERROR_INVALID_ASSEMBLY_PATH")), FileName) { this.source_context = sc; @@ -285,7 +277,7 @@ namespace PascalABCCompiler 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); + 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 ResourceFileNotFound(string ResFileName) @@ -295,9 +287,9 @@ namespace PascalABCCompiler } } - public class IncludeNamespaceInUnit: CompilerCompilationError + public class IncludeNamespaceInUnitError : CompilerCompilationError { - public IncludeNamespaceInUnit(string FileName, SyntaxTree.SourceContext sc) + public IncludeNamespaceInUnitError(string FileName, SyntaxTree.SourceContext sc) : base(string.Format(StringResources.Get("COMPILATIONERROR_INCLUDE_NAMESPACE_IN_UNIT")), FileName) { this.source_context = sc; @@ -344,7 +336,7 @@ namespace PascalABCCompiler } } - public class NamespacesCanBeCompiledOnlyInProjects: CompilerCompilationError + public class NamespacesCanBeCompiledOnlyInProjects : CompilerCompilationError { public NamespacesCanBeCompiledOnlyInProjects(SyntaxTree.SourceContext sc) : base(StringResources.Get("COMPILATIONERROR_NAMESPACE_CAN_BE_COMPILED_ONLY_IN_PROJECTS")) @@ -380,7 +372,7 @@ namespace PascalABCCompiler public class SourceFileNotFound : CompilerCompilationError { public SourceFileNotFound(string FileName) - : base(string.Format(StringResources.Get("COMPILATIONERROR_SOURCE_FILE_{0}_NOT_FOUND"),FileName)) + : base(string.Format(StringResources.Get("COMPILATIONERROR_SOURCE_FILE_{0}_NOT_FOUND"), FileName)) { } } @@ -388,7 +380,7 @@ namespace PascalABCCompiler public class UnauthorizedAccessToFile : CompilerCompilationError { public UnauthorizedAccessToFile(string FileName) - : base(string.Format(StringResources.Get("COMPILATIONERROR_NO_ACCESS_TO_FILE{0}"),FileName)) + : base(string.Format(StringResources.Get("COMPILATIONERROR_NO_ACCESS_TO_FILE{0}"), FileName)) { } } @@ -396,16 +388,16 @@ namespace PascalABCCompiler { 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) + : 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 UnsupportetTargetFramework: CompilerCompilationError + public class UnsupportedTargetFramework : CompilerCompilationError { - public UnsupportetTargetFramework(string FrameworkName, TreeRealization.location sl) + public UnsupportedTargetFramework(string FrameworkName, TreeRealization.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); @@ -414,56 +406,65 @@ namespace PascalABCCompiler public enum UnitState { BeginCompilation, InterfaceCompiled, Compiled } - public class CompilationUnit - { + public class CompilationUnit + { internal bool CaseSensitive = false; - public string CurrentUsesUnitId; + /// + /// поле для проверки на циклическую зависимость интерфейсов модулей + /// + public string currentUsedUnitId; public PascalABCCompiler.Errors.SyntaxError syntax_error; public string UnitFileName; - public List ErrorList=new List(); - public bool Documented; - internal List PossibleNamespaces = new List(); + public List ErrorList = new List(); + public bool Documented; + internal List possibleNamespaces = new List(); //internal List AssemblyReferences = new List(); //private SemanticTree.compilation_unitArrayList _interfaceUsedUnits=new SemanticTree.compilation_unitArrayList(); - public Dictionary DirectInterfaceCompilationUnits { get; } = new Dictionary(); - public PascalABCCompiler.TreeRealization.unit_node_list InterfaceUsedUnits { get; } = new PascalABCCompiler.TreeRealization.unit_node_list(); + /// + /// Только "реальные" юниты (не dll и namespace) + /// + public Dictionary InterfaceUsedDirectUnits { get; } = new Dictionary(); - public Dictionary DirectImplementationCompilationUnits { get; } = new Dictionary(); - public PascalABCCompiler.TreeRealization.unit_node_list ImplementationUsedUnits { get; } = new PascalABCCompiler.TreeRealization.unit_node_list(); + public unit_node_list InterfaceUsedUnits { get; } = new unit_node_list(); + /// + /// Только "реальные" юниты (не dll и namespace) + /// + public Dictionary ImplementationUsedDirectUnits { get; } = new Dictionary(); + public unit_node_list ImplementationUsedUnits { get; } = new unit_node_list(); public bool ForEachDirectCompilationUnit(Func on_unit) { - foreach (var kvp in DirectInterfaceCompilationUnits) + foreach (var kvp in InterfaceUsedDirectUnits) if (!on_unit(kvp.Value, InterfaceUsedUnits.unit_uses_paths[kvp.Key])) return false; - foreach (var kvp in DirectImplementationCompilationUnits) + foreach (var kvp in ImplementationUsedDirectUnits) if (!on_unit(kvp.Value, ImplementationUsedUnits.unit_uses_paths[kvp.Key])) return false; return true; } - private SyntaxTree.compilation_unit _syntaxTree=null; - public SyntaxTree.compilation_unit SyntaxTree - { - get {return _syntaxTree;} - set {_syntaxTree=value;} - } + private SyntaxTree.compilation_unit _syntaxTree = null; + public SyntaxTree.compilation_unit SyntaxTree + { + get { return _syntaxTree; } + set { _syntaxTree = value; } + } private PascalABCCompiler.TreeRealization.unit_node _semanticTree = null; public PascalABCCompiler.TreeRealization.unit_node SemanticTree - { - get {return _semanticTree;} - set {_semanticTree=value;} - } + { + get { return _semanticTree; } + set { _semanticTree = value; } + } - private SyntaxTree.unit_or_namespace _syntaxUnitName=null; - public SyntaxTree.unit_or_namespace SyntaxUnitName - { - get {return _syntaxUnitName;} - set {_syntaxUnitName=value;} - } + 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 @@ -479,38 +480,35 @@ namespace PascalABCCompiler set { _implementation_using_namespace_list = value; } } - public UnitState State=UnitState.BeginCompilation; - } - - public class CompilationUnitHashTable:Hashtable - { - public CompilationUnitHashTable() - //DarkStar: fixed error in test_standartuses.pas at rebuild - :base(StringComparer.InvariantCultureIgnoreCase) + public UnitState State = UnitState.BeginCompilation; + } + + public class CompilationUnitHashTable : Hashtable + { + public CompilationUnitHashTable() : base(StringComparer.InvariantCultureIgnoreCase) { } + + public CompilationUnit this[string key] { - } - public CompilationUnit this [string key] - { - get - { + get + { if (key != null) return (base[key] as CompilationUnit); return null; - } - set - { - base[key]=value; - } - } - } - + } + set + { + base[key] = value; + } + } + } + /// /// Опции компиляции /// //[Serializable()] public class CompilerOptions : MarshalByRefObject { - public enum OutputType {ClassLibrary=0, ConsoleApplicaton=1, WindowsApplication=2, PascalCompiledUnit=3, SemanticTree=4 } + public enum OutputType { ClassLibrary = 0, ConsoleApplicaton = 1, WindowsApplication = 2, PascalCompiledUnit = 3, SemanticTree = 4 } public bool Debug = false; public bool ForDebugging = false; @@ -518,10 +516,10 @@ namespace PascalABCCompiler public bool Rebuild = false; public bool Optimise = false; public bool SavePCUInThreadPull = false; - public bool RunWithEnvironment = false; - public string CompiledUnitExtension=".pcu"; - public bool ProjectCompiled = false; - public IProjectInfo CurrentProject = null; + public bool RunWithEnvironment = false; + public string CompiledUnitExtension = ".pcu"; + public bool ProjectCompiled = false; + public IProjectInfo CurrentProject = null; public OutputType OutputFileType = OutputType.ConsoleApplicaton; public bool GenerateCode = true; public bool SaveDocumentation = true; @@ -539,7 +537,7 @@ namespace PascalABCCompiler get { return sourceFileName; } set { - sourceFileName = value; + sourceFileName = value; OutputFileName = value; sourceFileDirectory = Path.GetDirectoryName(value); if (sourceFileDirectory == "") sourceFileDirectory = Environment.CurrentDirectory; @@ -548,16 +546,17 @@ namespace PascalABCCompiler } } - + private string sourceFileDirectory = null; public string SourceFileDirectory { get { return sourceFileDirectory; } } + + private string outputFileName = null; - private string outputFileName=null; - //имя выходного файла без расширения - //ели имя указано без пути то в качестве пути используетя OutputDirectory + // имя выходного файла без расширения + // если имя указано без пути то в качестве пути используетя OutputDirectory public string OutputFileName { get @@ -567,19 +566,18 @@ namespace PascalABCCompiler { case OutputType.ConsoleApplicaton: case OutputType.WindowsApplication: FileName = FileName + ".exe"; break; - case OutputType.ClassLibrary: FileName = FileName + ".dll"; break; + case OutputType.ClassLibrary: FileName = FileName + ".dll"; break; case OutputType.PascalCompiledUnit: FileName = FileName + CompiledUnitExtension; break; } if (Path.GetDirectoryName(FileName) == "") FileName = Path.Combine(OutputDirectory, FileName); return FileName; } - set - { + set + { outputFileName = Path.GetFileNameWithoutExtension(value); } } - // public string SystemDirectory; public List ForceDefines = new List(); @@ -597,65 +595,64 @@ namespace PascalABCCompiler set { useDllForSystemUnits = value; - PascalABCCompiler.NetHelper.NetHelper.UsePABCRtl = value; + NetHelper.NetHelper.UsePABCRtl = value; } } - public string[] ParserSearchPatchs; + public string[] ParserSearchPaths; - public enum StandartModuleAddMethod {LeftToAll, RightToMain}; + public enum StandardModuleAddMethod { LeftToAll, RightToMain }; [Serializable()] - public class StandartModule : MarshalByRefObject + public class StandardModule : MarshalByRefObject { public string Name = null; - public StandartModuleAddMethod AddMethod = StandartModuleAddMethod.LeftToAll; + public StandardModuleAddMethod AddMethod = StandardModuleAddMethod.LeftToAll; public SyntaxTree.LanguageId AddToLanguages = SyntaxTree.LanguageId.PascalABCNET; - public StandartModule(string Name, StandartModuleAddMethod AddMethod) + public StandardModule(string Name, StandardModuleAddMethod AddMethod) { this.Name = Name; this.AddMethod = AddMethod; } - public StandartModule(string Name, StandartModuleAddMethod AddMethod, SyntaxTree.LanguageId AddToLanguages) + public StandardModule(string Name, StandardModuleAddMethod AddMethod, SyntaxTree.LanguageId AddToLanguages) { this.Name = Name; this.AddToLanguages = AddToLanguages; this.AddMethod = AddMethod; } - public StandartModule(string Name) + public StandardModule(string Name) { this.Name = Name; } - public StandartModule(string Name, SyntaxTree.LanguageId AddToLanguages) + public StandardModule(string Name, SyntaxTree.LanguageId AddToLanguages) { this.AddToLanguages = AddToLanguages; this.Name = Name; } } + /// - /// Module at index 0 is System module + /// module at index 0 is System module /// - public List StandartModules; - public void RemoveStandartModule(string Name) + public List StandardModules; + + public void RemoveStandardModule(string name) { - StandartModule module_to_del=null; - foreach (StandartModule module in StandartModules) - if (module.Name == Name) - { - module_to_del = module; - break; - } - if (module_to_del != null) - StandartModules.Remove(module_to_del); + int moduleIndex = StandardModules.FindIndex(module => module.Name == name); + + if (moduleIndex != -1) + StandardModules.RemoveAt(moduleIndex); } - public void RemoveStandartModuleAtIndex(int index) + + public void RemoveStandardModuleAtIndex(int index) { - if(index(); - StandartModules.Add(new StandartModule("PABCSystem", SyntaxTree.LanguageId.PascalABCNET | SyntaxTree.LanguageId.C)); - StandartModules.Add(new StandartModule("PABCExtensions", SyntaxTree.LanguageId.PascalABCNET | SyntaxTree.LanguageId.C)); + StandardModules = new List(); + StandardModules.Add(new StandardModule("PABCSystem", SyntaxTree.LanguageId.PascalABCNET)); + StandardModules.Add(new StandardModule("PABCExtensions", SyntaxTree.LanguageId.PascalABCNET)); } private void SetDirectories() { SystemDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName); - StandartDirectories = new Hashtable(StringComparer.InvariantCultureIgnoreCase); - StandartDirectories.Add("%PABCSYSTEM%", SystemDirectory); + StandardDirectories = new Hashtable(StringComparer.InvariantCultureIgnoreCase); + StandardDirectories.Add("%PABCSYSTEM%", SystemDirectory); - ParserSearchPatchs = new string[] { Path.Combine(SystemDirectory, "Lib") }; - SearchDirectory = ParserSearchPatchs.ToList(); + ParserSearchPaths = new string[] { Path.Combine(SystemDirectory, "Lib") }; + SearchDirectory = ParserSearchPaths.ToList(); } public CompilerOptions() { SetDirectories(); - SetStandartModules(); + SetStandardModules(); } public CompilerOptions(string SourceFileName, OutputType OutputFileType) { SetDirectories(); - SetStandartModules(); + SetStandardModules(); this.SourceFileName = SourceFileName; this.OutputFileType = OutputFileType; } - + } public enum CompilerState @@ -726,12 +723,12 @@ namespace PascalABCCompiler public bool AddStandartUnits = true; public bool SkipPCUErrors = true; public bool IncludeDebugInfoInPCU = true; - public bool AlwaysGenerateXMLDoc=false; + public bool AlwaysGenerateXMLDoc = false; public bool SkipInternalErrorsIfSyntaxTreeIsCorrupt = true; public bool UseStandarParserForIntellisense = true; public bool RunOnMono = false; - public List DocumentedUnits=new List(); - + public List DocumentedUnits = new List(); + #if DEBUG public bool DebugVersion { @@ -778,9 +775,9 @@ namespace PascalABCCompiler } public delegate void ChangeCompilerStateEventDelegate(ICompiler sender, CompilerState State, string FileName); - + public class Compiler : MarshalByRefObject, ICompiler - { + { //public ISyntaxTreeChanger SyntaxTreeChanger = null; // SSM 17/08/15 - для операций над синтаксическим деревом после его построения int pABCCodeHealth = 0; public int PABCCodeHealth { get { return pABCCodeHealth; } } @@ -798,7 +795,9 @@ namespace PascalABCCompiler { if (RevisionClass.Build == "0") return RevisionClass.MainVersion; - else return RevisionClass.MainVersion + "." + RevisionClass.Build; + else + // TODO: Недостижимый код | EVA + return RevisionClass.MainVersion + "." + RevisionClass.Build; } } public static DateTime VersionDateTime @@ -840,12 +839,12 @@ namespace PascalABCCompiler private Hashtable BadNodesInSyntaxTree = new Hashtable(); - TreeRealization.program_node _semantic_tree = null; + program_node semanticTree = null; public SemanticTree.IProgramNode SemanticTree { get { - return _semantic_tree; + return semanticTree; } } @@ -853,7 +852,7 @@ namespace PascalABCCompiler { get { - return _semantic_tree; + return semanticTree; } } @@ -863,7 +862,7 @@ namespace PascalABCCompiler //public Hashtable CompilerDirectives //{ - // get { return compilerDirectives; } + // get { return compiler_directives; } //} private uint linesCompiled; @@ -871,7 +870,7 @@ namespace PascalABCCompiler { get { return linesCompiled; } } - + private CompilerInternalDebug internalDebug; public CompilerInternalDebug InternalDebug { @@ -890,7 +889,7 @@ namespace PascalABCCompiler { get { return state; } } - + private void SetSupportedSourceFiles() { List supportedSourceFilesList = new List(); @@ -902,10 +901,10 @@ namespace PascalABCCompiler } supportedSourceFiles = supportedSourceFilesList.ToArray(); } - + private void SetSupportedProjectFiles() { - List supportedProjectFilesList = new List(); + List supportedProjectFilesList = new List(); /*for (int i = 0; i < ParsersController.Parsers.Count; i++) { SupportedSourceFile sf = SupportedSourceFile.Make(ParsersController.Parsers[i]); @@ -913,7 +912,7 @@ namespace PascalABCCompiler supportedSourceFilesList.Add(sf); }*/ //vremenno - supportedProjectFilesList.Add(new SupportedSourceFile(new string[1]{".pabcproj"},"PascalABC.NET")); + supportedProjectFilesList.Add(new SupportedSourceFile(new string[1] { ".pabcproj" }, "PascalABC.NET")); supportedProjectFiles = supportedProjectFilesList.ToArray(); } @@ -923,33 +922,21 @@ namespace PascalABCCompiler get { return supportedSourceFiles; } set { supportedSourceFiles = value; } } - + private SupportedSourceFile[] supportedProjectFiles = null; public SupportedSourceFile[] SupportedProjectFiles { - get { return supportedProjectFiles; } - } - - private CompilationUnitHashTable unitTable=new CompilationUnitHashTable(); - public CompilationUnitHashTable UnitTable{ get { return unitTable; } } - public List UnitsSortedList = new List(); - - private List StandarModules = new List(); - - private CompilerOptions compilerOptions = new CompilerOptions(); - public CompilerOptions CompilerOptions - { - get - { - return compilerOptions; - } - set - { - compilerOptions = value; - } + get { return supportedProjectFiles; } } - internal Dictionary DLLCache = new Dictionary(); + private CompilationUnitHashTable unitTable = new CompilationUnitHashTable(); + public CompilationUnitHashTable UnitTable { get { return unitTable; } } + public List UnitsLogicallySortedList = new List(); + + private List StandardModules = new List(); + public CompilerOptions CompilerOptions { get; set; } = new CompilerOptions(); + + internal Dictionary DLLCache = new Dictionary(); private Parsers.Controller parsersController = null; public Parsers.Controller ParsersController @@ -967,14 +954,24 @@ namespace PascalABCCompiler public CodeGenerators.Controller CodeGeneratorsController = null; //public LLVMConverter.Controller LLVMCodeGeneratorsController = null; //public PascalToCppConverter.Controller PABCToCppCodeGeneratorsController = null; - public SyntaxTree.unit_or_namespace CurrentSyntaxUnit; - private List UnitsToCompile = new List(); + 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 FirstCompilationUnit = null; + public 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(); @@ -991,6 +988,7 @@ namespace PascalABCCompiler } } + public int BeginOffset { get @@ -1000,10 +998,10 @@ namespace PascalABCCompiler } public int VarBeginOffset { - get - { - return varBeginOffset; - } + get + { + return varBeginOffset; + } } private List warnings = new List(); public List Warnings @@ -1025,11 +1023,11 @@ namespace PascalABCCompiler foreach (CompilerWarning cw in WarningList) warnings.Add(cw); } - + public event ChangeCompilerStateEventDelegate OnChangeCompilerState; private void ChangeCompilerStateEvent(ICompiler sender, CompilerState State, string FileName) { - this.state=State; + this.state = State; } private bool SourceFileExists(string FileName) @@ -1052,9 +1050,9 @@ namespace PascalABCCompiler private List errorsList = new List(); public List ErrorsList - { - get{return errorsList;} - } + { + get { return errorsList; } + } public Compiler() { @@ -1063,24 +1061,24 @@ namespace PascalABCCompiler OnChangeCompilerState += ChangeCompilerStateEvent; Reload(); } - + public Compiler(ICompiler comp, SourceFilesProviderDelegate SourceFilesProvider, ChangeCompilerStateEventDelegate ChangeCompilerState) { //SyntaxTreeChanger = new SyntaxTreeChanger.SyntaxTreeChange(); // SSM 01/05/16 - подключение изменяльщика синтаксического дерева this.ParsersController = comp.ParsersController; - this.internalDebug = comp.InternalDebug; - OnChangeCompilerState += ChangeCompilerStateEvent; - if (SourceFilesProvider != null) + this.internalDebug = comp.InternalDebug; + OnChangeCompilerState += ChangeCompilerStateEvent; + if (SourceFilesProvider != null) this.sourceFilesProvider = SourceFilesProvider; if (ChangeCompilerState != null) OnChangeCompilerState += ChangeCompilerState; this.supportedSourceFiles = comp.SupportedSourceFiles; this.supportedProjectFiles = comp.SupportedProjectFiles; } - + public Compiler(SourceFilesProviderDelegate SourceFilesProvider, ChangeCompilerStateEventDelegate ChangeCompilerState) - { + { //SyntaxTreeChanger = new SyntaxTreeChanger.SyntaxTreeChange(); // SSM 01/05/16 - подключение изменяльщика синтаксического дерева OnChangeCompilerState += ChangeCompilerStateEvent; if (SourceFilesProvider != null) @@ -1089,7 +1087,7 @@ namespace PascalABCCompiler OnChangeCompilerState += ChangeCompilerState; Reload(); } - + public void Reload() { OnChangeCompilerState(this, CompilerState.Reloading, null); @@ -1121,7 +1119,7 @@ namespace PascalABCCompiler semanticTreeConvertersController.ChangeState += semanticTreeConvertersController_ChangeState; semanticTreeConvertersController.AddConverters(); - OnChangeCompilerState(this, CompilerState.Ready, null); + OnChangeCompilerState(this, CompilerState.Ready, null); } void ParsersController_ParserConnected(PascalABCCompiler.Parsers.IParser Parser) @@ -1156,26 +1154,28 @@ namespace PascalABCCompiler } } - private Dictionary> GetCompilerDirectives(List Units) + private Dictionary> GetCompilerDirectives(List Units) { - Dictionary> Directives = new Dictionary>(StringComparer.CurrentCultureIgnoreCase); + Dictionary> directives = new Dictionary>(StringComparer.CurrentCultureIgnoreCase); for (int i = 0; i < Units.Count; i++) { - TreeRealization.common_unit_node cun = Units[i].SemanticTree as TreeRealization.common_unit_node; - if (cun != null) - foreach (TreeRealization.compiler_directive cd in cun.compiler_directives) + common_unit_node unitNode = Units[i].SemanticTree as common_unit_node; + if (unitNode != null) + { + foreach (compiler_directive cd in unitNode.compiler_directives) { - if (!Directives.ContainsKey(cd.name)) - Directives.Add(cd.name, new List()); - else if (string.Compare(cd.name, "mainresource", true) == 0) + if (!directives.ContainsKey(cd.name)) + directives.Add(cd.name, new List()); + else if (cd.name.Equals("mainresource", StringComparison.CurrentCultureIgnoreCase)) throw new DuplicateDirective(cd.location.doc.file_name, "mainresource", cd.location); - Directives[cd.name].Insert(0, cd); + directives[cd.name].Insert(0, cd); } + } } - return Directives; + return directives; } - + private Hashtable GetCompilerDirectives(CompilationUnit Unit) { Hashtable Directives = new Hashtable(StringComparer.CurrentCultureIgnoreCase); @@ -1185,7 +1185,7 @@ namespace PascalABCCompiler Directives[cd.name] = cd; return Directives; } - + private TreeRealization.location get_location_from_treenode(SyntaxTree.syntax_tree_node tn, string FileName) { if (tn.source_context == null) @@ -1195,13 +1195,19 @@ namespace PascalABCCompiler return new TreeRealization.location(tn.source_context.begin_position.line_num, tn.source_context.begin_position.column_num, tn.source_context.end_position.line_num, tn.source_context.end_position.column_num, new TreeRealization.document(FileName)); } - - private System.Collections.Generic.List ConvertDirectives(SyntaxTree.compilation_unit cu) + + /// + /// преобразует в директивы семантического уровня + /// + private List GetDirectivesAsSemanticNodes(List compilerDirectives, string unitFileName) { - System.Collections.Generic.List list = new System.Collections.Generic.List(); - foreach (SyntaxTree.compiler_directive sncd in cu.compiler_directives) + List list = new List(); + foreach (SyntaxTree.compiler_directive directive in compilerDirectives) { - list.Add(new TreeRealization.compiler_directive(sncd.Name.text, sncd.Directive!=null?sncd.Directive.text:"", get_location_from_treenode(sncd,cu.file_name), cu.file_name)); + list.Add(new compiler_directive(directive.Name.text, + directive.Directive?.text ?? "", + get_location_from_treenode(directive, unitFileName), + unitFileName)); } return list; } @@ -1210,7 +1216,7 @@ namespace PascalABCCompiler { Compile(); } - + public void StartCompile() { System.Threading.Thread th = new System.Threading.Thread(syncStartCompile); @@ -1224,7 +1230,7 @@ namespace PascalABCCompiler return Compile(); } - internal void Reset() + private void Reset() { SourceFileNamesDictionary.Clear(); PCUFileNamesDictionary.Clear(); @@ -1232,8 +1238,8 @@ namespace PascalABCCompiler Warnings.Clear(); errorsList.Clear(); //if (!File.Exists(CompilerOptions.SourceFileName)) throw new SourceFileNotFound(CompilerOptions.SourceFileName); - CurrentCompilationUnit = null; - FirstCompilationUnit = null; + currentCompilationUnit = null; + firstCompilationUnit = null; linesCompiled = 0; pABCCodeHealth = 0; PCUReadersAndWritersClosed = false; @@ -1241,254 +1247,260 @@ namespace PascalABCCompiler SyntaxTreeToSemanticTreeConverter.Reset(); CodeGeneratorsController.Reset(); //PABCToCppCodeGeneratorsController.Reset(); - UnitsToCompile.Clear(); + UnitsToCompileDelayedList.Clear(); DLLCache.Clear(); project = null; } - void CheckErrors() + void CheckErrorsAndThrowTheFirstOne() { - if (compilerOptions.ForIntellisense) + if (CompilerOptions.ForIntellisense) return; if (ErrorsList.Count > 0) throw ErrorsList[0]; } - private void moveSystemUnitToForwardUnitSortedList() + private void MoveSystemUnitForwardInUnitLogicallySortedList() { - if(CompilerOptions.StandartModules.Count==0) + if (CompilerOptions.StandardModules.Count == 0) return; + CompilationUnit system_unit = null; - foreach (CompilationUnit cu in UnitsSortedList) - if (cu.SemanticTree != null && cu.SemanticTree is PascalABCCompiler.TreeRealization.common_unit_node) - if ((cu.SemanticTree as PascalABCCompiler.TreeRealization.common_unit_node).unit_name == CompilerOptions.StandartModules[0].Name) + foreach (CompilationUnit unit in UnitsLogicallySortedList) + { + if (unit.SemanticTree != null && unit.SemanticTree is common_unit_node) + { + if ((unit.SemanticTree as common_unit_node).unit_name == CompilerOptions.StandardModules[0].Name) { - system_unit = cu; + system_unit = unit; break; } - if (system_unit != null && system_unit != UnitsSortedList[0]) + } + } + + if (system_unit != null && system_unit != UnitsLogicallySortedList[0]) { - UnitsSortedList.Remove(system_unit); - UnitsSortedList.Insert(0, system_unit); + UnitsLogicallySortedList.Remove(system_unit); + UnitsLogicallySortedList.Insert(0, system_unit); } } - + 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; - } - - class ProgInfo - { - public string entry_module; - public int entry_method_name_pos; - public int entry_method_line; - public int using_pos=-1; - 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); - ht["GraphABC"] = "GraphABC"; - ht["GraphABCHelper"] = "GraphABCHelper"; - ht["ABCObjects"] = "ABCObjects"; - ht["Robot"] = "Robot"; - ht["Drawman"] = "Drawman"; - ht["DrawManField"] = "DrawManField"; - foreach (string s in imports) - { - string low_s = s.ToLower(); - //string mod_file = FindSourceFileInDirectories(s+".mod",Path.Combine(this.CompilerOptions.SystemDirectory,"lib")); - if (ht[s] != null) - { - string name = ht[s] as string; - if (!info.modules.Contains(name)) - { - info.modules.Add(name); - info.addit_imports.Add(name+"."+name); - } - } - /*if (!string.IsNullOrEmpty(mod_file)) - { - switch (low_s) - { - case "graphabc" : - if (!info.modules.Contains("GraphABC") && !info.modules.Contains("ABCObjects") && !info.modules.Contains("ABCButtons") && !info.modules.Contains("ABCHouse") - && !info.modules.Contains("ABCSprites") && !info.modules.Contains("RobotField")) - { - info.modules.Add("GraphABC"); - info.addit_imports.Add("GraphABC.GraphABC"); - } - else if (!info.addit_imports.Contains("GraphABC.GraphABC")) - { - info.addit_imports.Add("GraphABC.GraphABC"); - } - break; - case "abcobjects" : - if (!info.modules.Contains("ABCObjects") && !info.modules.Contains("ABCButtons") && !info.modules.Contains("ABCHouse") - && !info.modules.Contains("ABCSprites") && !info.modules.Contains("RobotField")) - { - info.modules.Add("ABCObjects"); - info.addit_imports.Add("ABCObjects.ABCObjects"); - if (info.modules.Contains("GraphABC")) - { - info.modules.Remove("GraphABC"); - //info.addit_imports.Remove("GraphABC.GraphABC"); - } - } - break; - default: - if (!info.modules.Contains(s)) - { - info.modules.Add(s); - info.addit_imports.Add(s+"."+s); - } - break; - } - }*/ - else - { - string source_file = FindFileInDirs(s+".vb", out _, Path.GetDirectoryName(CompilerOptions.SourceFileName),Path.Combine(this.CompilerOptions.SystemDirectory,"lib"), - Path.Combine(this.CompilerOptions.SystemDirectory,"LibSource")); - if (!string.IsNullOrEmpty(source_file)) - { - if (!info.addit_project_files.Contains(source_file)) - { - info.addit_project_files.Add(source_file); - } - } - } - } - /*List mods = new List(); - List inds = new List(); - for (int i=0; i usings = new List(); - foreach (ICSharpCode.NRefactory.Ast.INode node in cu.Children) - { - if (node is ICSharpCode.NRefactory.Ast.TypeDeclaration) - { - ICSharpCode.NRefactory.Ast.TypeDeclaration td = node as ICSharpCode.NRefactory.Ast.TypeDeclaration; - if (td.Type == ICSharpCode.NRefactory.Ast.ClassType.Module) - { - foreach (ICSharpCode.NRefactory.Ast.INode node2 in td.Children) - { - if (node2 is ICSharpCode.NRefactory.Ast.MethodDeclaration) - { - ICSharpCode.NRefactory.Ast.MethodDeclaration meth = node2 as ICSharpCode.NRefactory.Ast.MethodDeclaration; - if (string.Compare(meth.Name,"Main",true)==0 && (meth.Parameters == null || meth.Parameters.Count == 0)) - { - //info = new ProgInfo(); - info.entry_module = (meth.Parent as ICSharpCode.NRefactory.Ast.TypeDeclaration).Name; - //info.entry_method_name_line = meth.StartLocation.Line; - //info.entry_method_name_col = meth.StartLocation.Column; - info.entry_method_name_pos = find_pos(source,meth.StartLocation.Line,meth.StartLocation.Column,true); - if (meth.Body.Children.Count > 0) - { - for (int i=0; i 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); + ht["GraphABC"] = "GraphABC"; + ht["GraphABCHelper"] = "GraphABCHelper"; + ht["ABCObjects"] = "ABCObjects"; + ht["Robot"] = "Robot"; + ht["Drawman"] = "Drawman"; + ht["DrawManField"] = "DrawManField"; + foreach (string s in imports) + { + string low_s = s.ToLower(); + //string mod_file = FindSourceFileInDirectories(s+".mod",Path.Combine(this.CompilerOptions.SystemDirectory,"lib")); + if (ht[s] != null) + { + string name = ht[s] as string; + if (!info.modules.Contains(name)) + { + info.modules.Add(name); + info.addit_imports.Add(name + "." + name); + } + } + /*if (!string.IsNullOrEmpty(mod_file)) + { + switch (low_s) + { + case "graphabc" : + if (!info.modules.Contains("GraphABC") && !info.modules.Contains("ABCObjects") && !info.modules.Contains("ABCButtons") && !info.modules.Contains("ABCHouse") + && !info.modules.Contains("ABCSprites") && !info.modules.Contains("RobotField")) + { + info.modules.Add("GraphABC"); + info.addit_imports.Add("GraphABC.GraphABC"); + } + else if (!info.addit_imports.Contains("GraphABC.GraphABC")) + { + info.addit_imports.Add("GraphABC.GraphABC"); + } + break; + case "abcobjects" : + if (!info.modules.Contains("ABCObjects") && !info.modules.Contains("ABCButtons") && !info.modules.Contains("ABCHouse") + && !info.modules.Contains("ABCSprites") && !info.modules.Contains("RobotField")) + { + info.modules.Add("ABCObjects"); + info.addit_imports.Add("ABCObjects.ABCObjects"); + if (info.modules.Contains("GraphABC")) + { + info.modules.Remove("GraphABC"); + //info.addit_imports.Remove("GraphABC.GraphABC"); + } + } + break; + default: + if (!info.modules.Contains(s)) + { + info.modules.Add(s); + info.addit_imports.Add(s+"."+s); + } + break; + } + }*/ + else + { + string source_file = FindFileInDirs(s + ".vb", out _, Path.GetDirectoryName(CompilerOptions.SourceFileName), Path.Combine(this.CompilerOptions.SystemDirectory, "lib"), + Path.Combine(this.CompilerOptions.SystemDirectory, "LibSource")); + if (!string.IsNullOrEmpty(source_file)) + { + if (!info.addit_project_files.Contains(source_file)) + { + info.addit_project_files.Add(source_file); + } + } + } + } + /*List mods = new List(); + List inds = new List(); + for (int i=0; i usings = new List(); + foreach (ICSharpCode.NRefactory.Ast.INode node in cu.Children) + { + if (node is ICSharpCode.NRefactory.Ast.TypeDeclaration) + { + ICSharpCode.NRefactory.Ast.TypeDeclaration td = node as ICSharpCode.NRefactory.Ast.TypeDeclaration; + if (td.Type == ICSharpCode.NRefactory.Ast.ClassType.Module) + { + foreach (ICSharpCode.NRefactory.Ast.INode node2 in td.Children) + { + if (node2 is ICSharpCode.NRefactory.Ast.MethodDeclaration) + { + ICSharpCode.NRefactory.Ast.MethodDeclaration meth = node2 as ICSharpCode.NRefactory.Ast.MethodDeclaration; + if (string.Compare(meth.Name, "Main", true) == 0 && (meth.Parameters == null || meth.Parameters.Count == 0)) + { + //info = new ProgInfo(); + info.entry_module = (meth.Parent as ICSharpCode.NRefactory.Ast.TypeDeclaration).Name; + //info.entry_method_name_line = meth.StartLocation.Line; + //info.entry_method_name_col = meth.StartLocation.Column; + info.entry_method_name_pos = find_pos(source, meth.StartLocation.Line, meth.StartLocation.Column, true); + if (meth.Body.Children.Count > 0) + { + for (int i = 0; i < meth.Body.Children.Count; i++) + { + if (!(meth.Body.Children[i] is ICSharpCode.NRefactory.Ast.LocalVariableDeclaration)) + { + info.entry_method_line = meth.Body.Children[i].StartLocation.Line; + break; + } + } + } + else + info.entry_method_line = meth.Body.EndLocation.Line; + } + } + } + } + } + else if (node is ICSharpCode.NRefactory.Ast.UsingDeclaration) + { + ICSharpCode.NRefactory.Ast.UsingDeclaration using_node = node as ICSharpCode.NRefactory.Ast.UsingDeclaration; + + foreach (ICSharpCode.NRefactory.Ast.Using us in using_node.Usings) + if (!string.IsNullOrEmpty(us.Name)) + usings.Add(us.Name); + if (info.using_pos == -1) + info.using_pos = find_pos(source, using_node.EndLocation.Line, using_node.EndLocation.Column, false); + } + } + if (info.entry_module != null) + { + add_import_info(info, usings); + return info; + } + return null; + } + + 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); @@ -1501,7 +1513,7 @@ namespace PascalABCCompiler comp_opt.WarningLevel = 3; comp_opt.CompilerOptions = "/platform:x86 "; comp_opt.OutputAssembly = CompilerOptions.OutputFileName; - if (RefAssemblies!=null) + if (RefAssemblies != null) comp_opt.ReferencedAssemblies.AddRange(RefAssemblies); //string source = GetSourceFileText(CompilerOptions.SourceFileName); @@ -1510,7 +1522,7 @@ namespace PascalABCCompiler { for (int i = 0; i < res.Errors.Count; i++) { - if (!res.Errors[i].IsWarning && errorsList.Count == 0 /*&& res.Errors[i].FileName != 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)); @@ -1539,13 +1551,13 @@ namespace PascalABCCompiler class PyErrorHandler : ErrorListener { Compiler c; - public PyErrorHandler(Compiler cc) {c=cc;} + public PyErrorHandler(Compiler cc) { c = cc; } public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity) { - if (severity==Severity.Warning) - c.warnings.Add(new Errors.CommonWarning(message, c.compilerOptions.SourceFileName, span.Start.Line, span.Start.Column)); + if (severity == Severity.Warning) + c.warnings.Add(new Errors.CommonWarning(message, c.CompilerOptions.SourceFileName, span.Start.Line, span.Start.Column)); else - c.errorsList.Add(new Errors.CommonCompilerError(message, c.compilerOptions.SourceFileName, span.Start.Line, span.Start.Column)); + c.errorsList.Add(new Errors.CommonCompilerError(message, c.CompilerOptions.SourceFileName, span.Start.Line, span.Start.Column)); } } @@ -1558,7 +1570,7 @@ namespace PascalABCCompiler Reset(); if (IronPythonAssembly == null) - { + { IronPythonAssembly = Assembly.LoadFrom("IronPython.dll"); PythonCreateEngineMethod = IronPythonAssembly.GetType("IronPython.Hosting.Python").GetMethod("CreateEngine"); } @@ -1578,8 +1590,8 @@ namespace PascalABCCompiler OnChangeCompilerState(this, CompilerState.Ready, null); //if (errorsList.Count > 0) - return null; - //else return res.PathToAssembly; + return null; + //else return dlls.PathToAssembly; } public string CompileCS() @@ -1587,7 +1599,7 @@ namespace PascalABCCompiler OnChangeCompilerState(this, CompilerState.CompilationStarting, CompilerOptions.SourceFileName); OnChangeCompilerState(this, CompilerState.BeginCompileFile, CompilerOptions.SourceFileName); Reset(); - var d = new Dictionary(); + var d = new Dictionary(); d["CompilerVersion"] = "v4.0"; var cscp = new Microsoft.CSharp.CSharpCodeProvider(d); @@ -1628,7 +1640,7 @@ namespace PascalABCCompiler { for (int i = 0; i < res.Errors.Count; i++) { - if (!res.Errors[i].IsWarning && errorsList.Count == 0 /*&& res.Errors[i].FileName != 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)); @@ -1656,171 +1668,171 @@ namespace PascalABCCompiler public string CompileVB() { - OnChangeCompilerState(this, CompilerState.CompilationStarting, CompilerOptions.SourceFileName); - OnChangeCompilerState(this,CompilerState.BeginCompileFile,CompilerOptions.SourceFileName); - Reset(); - Microsoft.VisualBasic.VBCodeProvider vbcp = new Microsoft.VisualBasic.VBCodeProvider(); - List sources = new List(); - sources.Add(CompilerOptions.SourceFileName); - System.CodeDom.Compiler.CompilerParameters comp_opt = new System.CodeDom.Compiler.CompilerParameters(); - comp_opt.OutputAssembly = CompilerOptions.OutputFileName; - comp_opt.WarningLevel = 3; - comp_opt.ReferencedAssemblies.Add("System.Windows.Forms.dll"); - comp_opt.ReferencedAssemblies.Add("System.Drawing.dll"); - comp_opt.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll"); - comp_opt.IncludeDebugInformation = CompilerOptions.Debug; - comp_opt.GenerateExecutable = true; - string fname = Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName),"_temp$"+Path.GetFileName(CompilerOptions.SourceFileName)); - File.Copy(CompilerOptions.SourceFileName,fname,true); - string source = GetSourceFileText(CompilerOptions.SourceFileName); - - IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(ICSharpCode.NRefactory.SupportedLanguage.VBNet,new StringReader(source)); - parser.Parse(); - ProgInfo info = get_programm_info(parser.CompilationUnit, source); - parser.Dispose(); - if (info != null) - sources.AddRange(info.addit_project_files); - string redirect_base_fname = FindFileInDirs("__RedirectIOMode.vb", out _, Path.Combine(this.CompilerOptions.SystemDirectory,"Lib"),Path.Combine(this.CompilerOptions.SystemDirectory,"LibSource")); - string system_unit_name = FindFileInDirs("VBSystem.vb", out _, Path.Combine(this.CompilerOptions.SystemDirectory,"lib"),Path.Combine(this.CompilerOptions.SystemDirectory,"LibSource")); - string redirect_fname = Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName),"_RedirectIOMode.vb"); - StreamReader sr = File.OpenText(redirect_base_fname); - string redirect_module = sr.ReadToEnd(); - sr.Close(); - if (info != null) - { - System.Text.StringBuilder tmp_sb = new System.Text.StringBuilder(); - if (info.modules.Count > 0) - { - tmp_sb.AppendLine("GetType(Fictive.Fictive).Assembly.GetType(\"PABCSystem_implementation$.PABCSystem_implementation$\").GetMethod(\"$Initialization\").Invoke(Nothing,Nothing)"); - } - for (int i=0; i 0) - { - comp_opt.ReferencedAssemblies.Add(Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName),PascalABCCompiler.TreeConverter.compiler_string_consts.pabc_rtl_dll_name)); - string mod_file_name = FindFileInDirs("PABCRtl.dll", out _, Path.Combine(this.CompilerOptions.SystemDirectory,"Lib")); - File.Copy(mod_file_name,Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName),"PABCRtl.dll"),true); - /*foreach (string mod in info.modules) - { - comp_opt.ReferencedAssemblies.Add(Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName),mod+".dll")); - string mod_file_name = FindSourceFileInDirectories(mod+".mod",Path.Combine(this.CompilerOptions.SystemDirectory,"lib")); - File.Copy(mod_file_name,Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName),mod+".dll"),true); - }*/ - } - sources.Add(redirect_fname); - sources.Add(system_unit_name); - System.CodeDom.Compiler.CompilerResults res = vbcp.CompileAssemblyFromFile(comp_opt,sources.ToArray()); - if (res.Errors.Count > 0) + OnChangeCompilerState(this, CompilerState.CompilationStarting, CompilerOptions.SourceFileName); + OnChangeCompilerState(this, CompilerState.BeginCompileFile, CompilerOptions.SourceFileName); + Reset(); + Microsoft.VisualBasic.VBCodeProvider vbcp = new Microsoft.VisualBasic.VBCodeProvider(); + List sources = new List(); + sources.Add(CompilerOptions.SourceFileName); + System.CodeDom.Compiler.CompilerParameters comp_opt = new System.CodeDom.Compiler.CompilerParameters(); + comp_opt.OutputAssembly = CompilerOptions.OutputFileName; + comp_opt.WarningLevel = 3; + comp_opt.ReferencedAssemblies.Add("System.Windows.Forms.dll"); + comp_opt.ReferencedAssemblies.Add("System.Drawing.dll"); + comp_opt.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll"); + comp_opt.IncludeDebugInformation = CompilerOptions.Debug; + comp_opt.GenerateExecutable = true; + string fname = Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName), "_temp$" + Path.GetFileName(CompilerOptions.SourceFileName)); + File.Copy(CompilerOptions.SourceFileName, fname, true); + string source = GetSourceFileText(CompilerOptions.SourceFileName); + + IParser parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(ICSharpCode.NRefactory.SupportedLanguage.VBNet, new StringReader(source)); + parser.Parse(); + ProgInfo info = get_programm_info(parser.CompilationUnit, source); + parser.Dispose(); + if (info != null) + sources.AddRange(info.addit_project_files); + string redirect_base_fname = FindFileInDirs("__RedirectIOMode.vb", out _, Path.Combine(this.CompilerOptions.SystemDirectory, "Lib"), Path.Combine(this.CompilerOptions.SystemDirectory, "LibSource")); + string system_unit_name = FindFileInDirs("VBSystem.vb", out _, Path.Combine(this.CompilerOptions.SystemDirectory, "lib"), Path.Combine(this.CompilerOptions.SystemDirectory, "LibSource")); + string redirect_fname = Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName), "_RedirectIOMode.vb"); + StreamReader sr = File.OpenText(redirect_base_fname); + string redirect_module = sr.ReadToEnd(); + sr.Close(); + if (info != null) { - for (int i=0; i 0) + { + tmp_sb.AppendLine("GetType(Fictive.Fictive).Assembly.GetType(\"PABCSystem_implementation$.PABCSystem_implementation$\").GetMethod(\"$Initialization\").Invoke(Nothing,Nothing)"); + } + for (int i = 0; i < info.modules.Count; i++) + { + tmp_sb.AppendLine("GetType(Fictive.Fictive).Assembly.GetType(\"" + info.modules[i] + "_implementation$." + info.modules[i] + + "_implementation$\").GetMethod(\"$Initialization\").Invoke(Nothing,Nothing)"); + + } + tmp_sb.AppendLine(info.entry_module + "." + "___Main()"); + for (int i = 0; i < info.modules.Count; i++) + { + tmp_sb.AppendLine("GetType(Fictive.Fictive).Assembly.GetType(\"" + info.modules[i] + "_implementation$." + info.modules[i] + + "_implementation$\").GetMethod(\"$Finalization\").Invoke(Nothing,Nothing)"); + + } + redirect_module = redirect_module.Replace("%MAIN%", tmp_sb.ToString()); } - linesCompiled = get_compiled_lines(CompilerOptions.SourceFileName); - if (info != null) - { - beginOffset = info.entry_method_line; - //if (info.using_pos == -1) - // beginOffset -= 1; - } - OnChangeCompilerState(this, CompilerState.CompilationFinished, CompilerOptions.SourceFileName); - ClearAll(); - File.Copy(fname,CompilerOptions.SourceFileName,true); - File.Delete(fname); - File.Delete(redirect_fname); + StreamWriter sw = new StreamWriter(redirect_fname, false); + if (info != null) + { + sw.WriteLine(redirect_module); + } + else + { + sw.WriteLine("module _RedirectIOMode"); + sw.WriteLine("End module"); + } + sw.Close(); + + sw = new StreamWriter(CompilerOptions.SourceFileName, false); + if (info != null && info.entry_method_name_pos != -1) + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + int start_pos = 0; + if (info.using_pos != -1) + { + start_pos = info.using_pos; + sb.Append(source.Substring(0, info.using_pos)); + for (int i = 0; i < info.addit_imports.Count; i++) + { + sb.Append("," + info.addit_imports[i]); + } + sb.Append(",System.Collections.Generic"); + + sb.Append(",Microsoft.VisualBasic.Strings"); + sb.Append(",Microsoft.VisualBasic.Constants"); + sb.Append(",Microsoft.VisualBasic.VBMath"); + sb.Append(",Microsoft.VisualBasic.Information"); + sb.Append(",Microsoft.VisualBasic.Interaction"); + sb.Append(",Microsoft.VisualBasic.FileSystem"); + sb.Append(",Microsoft.VisualBasic.Financial"); + sb.Append(",Microsoft.VisualBasic.DateAndTime"); + } + else + { + start_pos = 0; + sb.Append("Imports System"); + sb.Append(",System.Collections.Generic"); + sb.Append(",Microsoft.VisualBasic.Strings"); + sb.Append(",Microsoft.VisualBasic.Constants"); + sb.Append(",Microsoft.VisualBasic.VBMath"); + sb.Append(",Microsoft.VisualBasic.Information"); + sb.Append(",Microsoft.VisualBasic.Interaction"); + sb.Append(",Microsoft.VisualBasic.FileSystem"); + sb.Append(",Microsoft.VisualBasic.Financial"); + sb.Append(",Microsoft.VisualBasic.DateAndTime"); + sb.Append(":"); + } + sb.Append(source.Substring(start_pos, info.entry_method_name_pos - start_pos)); + sb.Append("___"); + sb.Append(source.Substring(info.entry_method_name_pos)); + sw.Write(sb.ToString()); + } + else + { + sw.Write(source); + } + sw.Close(); + + if (info != null && info.modules.Count > 0) + { + comp_opt.ReferencedAssemblies.Add(Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName), PascalABCCompiler.TreeConverter.compiler_string_consts.pabc_rtl_dll_name)); + string mod_file_name = FindFileInDirs("PABCRtl.dll", out _, Path.Combine(this.CompilerOptions.SystemDirectory, "Lib")); + File.Copy(mod_file_name, Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName), "PABCRtl.dll"), true); + /*foreach (string mod in info.modules) + { + comp_opt.ReferencedAssemblies.Add(Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName),mod+".dll")); + string mod_file_name = FindSourceFileInDirectories(mod+".mod",Path.Combine(this.CompilerOptions.SystemDirectory,"lib")); + File.Copy(mod_file_name,Path.Combine(Path.GetDirectoryName(CompilerOptions.SourceFileName),mod+".dll"),true); + }*/ + } + sources.Add(redirect_fname); + sources.Add(system_unit_name); + System.CodeDom.Compiler.CompilerResults res = vbcp.CompileAssemblyFromFile(comp_opt, sources.ToArray()); + 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, 1)); + else + errorsList.Add(new Errors.CommonCompilerError(res.Errors[i].ErrorText, CompilerOptions.SourceFileName, res.Errors[i].Line != 0 ? res.Errors[i].Line : 1, 1)); + } + else if (res.Errors[i].IsWarning) + { + warnings.Add(new Errors.CommonWarning(res.Errors[i].ErrorText, res.Errors[i].FileName, res.Errors[i].Line, 1)); + } + } + } + linesCompiled = get_compiled_lines(CompilerOptions.SourceFileName); + if (info != null) + { + beginOffset = info.entry_method_line; + //if (info.using_pos == -1) + // beginOffset -= 1; + } + OnChangeCompilerState(this, CompilerState.CompilationFinished, CompilerOptions.SourceFileName); + ClearAll(); + File.Copy(fname, CompilerOptions.SourceFileName, true); + File.Delete(fname); + File.Delete(redirect_fname); OnChangeCompilerState(this, CompilerState.Ready, null); if (errorsList.Count > 0) - return null; + return null; else - return res.PathToAssembly; + return res.PathToAssembly; } - + private ProjectInfo project; private void PrepareCompileOptionsForProject() @@ -1841,553 +1853,695 @@ namespace PascalABCCompiler CompilerOptions.OutputDirectory = project.output_directory; } - public static bool CheckPathValid(string path) { + public static bool CheckPathValid(string path) + { return !Path.GetInvalidPathChars().Any(path.Contains); } - public static void TryThrowInvalidPath(string path, SyntaxTree.SourceContext loc) { + public static void TryThrowInvalidPath(string path, SyntaxTree.SourceContext loc) + { if (CheckPathValid(path)) return; throw new InvalidPathError(loc); } + private void CompileUnitsFromDelayedList() + { + // проход по всем юнитам из списка отложенной компиляции + foreach (CompilationUnit CurrentUnit in UnitsToCompileDelayedList) + { + if (CurrentUnit.State != UnitState.Compiled) + { + currentCompilationUnit = CurrentUnit; + string unitFileName = currentCompilationUnit.SyntaxTree.file_name; + + // получение списка используемых модулей в файле (uses 1, 2, 3...) + List implementationUsesList = GetImplementationUsesSection(CurrentUnit.SyntaxTree); + + CurrentUnit.possibleNamespaces.Clear(); + if (HasIncludeNamespaceDirective(CurrentUnit)) + CompilerOptions.UseDllForSystemUnits = false; + + if (implementationUsesList != null) + { + SetUseDLLForSystemUnits(Path.GetDirectoryName(unitFileName), implementationUsesList, implementationUsesList.Count - 1); + + for (int i = implementationUsesList.Count - 1; i >= 0; i--) + { + if (!IsPossibleNetNamespaceOrStandardPasFile(implementationUsesList[i], true, Path.GetDirectoryName(unitFileName))) + { + // докомпилируем юнит, если он не является пространством имен или стандартным pas файлом из Lib + CompileUnit(CurrentUnit.ImplementationUsedUnits, CurrentUnit.ImplementationUsedDirectUnits, implementationUsesList[i], Path.GetDirectoryName(unitFileName)); + } + else + { + // добавление в списки только пространств имен + CurrentUnit.ImplementationUsedUnits.AddElement(new namespace_unit_node(GetNamespace(implementationUsesList[i])), null); + CurrentUnit.possibleNamespaces.Add(implementationUsesList[i]); + } + } + + } + + AddNamespacesToUsingList(CurrentUnit.ImplementationUsingNamespaceList, CurrentUnit.possibleNamespaces, true, null); + + // Console.WriteLine("Compiling implementation delayed " + unitFileName); + + CompileCurrentUnitImplementation(unitFileName, CurrentUnit, null); + + CurrentUnit.State = UnitState.Compiled; // отметка о скомпилированности + OnChangeCompilerState(this, CompilerState.EndCompileFile, unitFileName); // состояние конец компиляции + //SavePCU(compilationUnit, unitFileName); + CurrentUnit.UnitFileName = unitFileName; + } + } + } + + private void SetOutputFileTypeOption() + { + if (compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.compiler_directive_apptype)) + { + string directive = compilerDirectives[TreeConverter.compiler_string_consts.compiler_directive_apptype][0].directive.ToLower(); + switch (directive) + { + case "console": + CompilerOptions.OutputFileType = CompilerOptions.OutputType.ConsoleApplicaton; + break; + case "windows": + CompilerOptions.OutputFileType = CompilerOptions.OutputType.WindowsApplication; + break; + case "dll": + CompilerOptions.OutputFileType = CompilerOptions.OutputType.ClassLibrary; + break; + case "pcu": + CompilerOptions.OutputFileType = CompilerOptions.OutputType.PascalCompiledUnit; + break; + default: + throw new Exception("No possible OutputFileType!"); + } + } + } + + private void SetOutputPlatformOption(NETGenerator.CompilerOptions compilerOptions) + { + List compilerDirectivesList = new List(); + if (compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.compiler_directive_platformtarget, out compilerDirectivesList)) + { + string plt = compilerDirectivesList[0].directive.ToLower(); + switch (plt) + { + case "x86": + compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x86; + break; + case "x64": + compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x64; + break; + case "anycpu": + compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.AnyCPU; + break; + case "dotnet5win": + compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5win; + break; + case "dotnet5linux": + compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5linux; + break; + case "dotnet5macos": + compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5macos; + break; + case "native": + if (Environment.OSVersion.Platform == PlatformID.Unix) + { + compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetlinuxnative; + } + else if (Environment.OSVersion.Platform == PlatformID.MacOSX) + { + compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetmacosnative; + } + else + { + compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetwinnative; + } + break; + default: + throw new Exception("Unknown platform!"); + } + if (CompilerOptions.Only32Bit) + compilerOptions.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x86; + + // целевой framework + if (this.compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.compiler_directive_targetframework, out compilerDirectivesList)) + { + compilerOptions.TargetFramework = compilerDirectivesList[0].directive; + if (!(new string[] { "net40", "net403", "net45", "net451", "net452", "net46", "net461", "net462", "net47", "net471", "net472", "net48", "net481" }) + .Contains(compilerOptions.TargetFramework)) + ErrorsList.Add(new UnsupportedTargetFramework(compilerOptions.TargetFramework, compilerDirectivesList[0].location)); + } + } + } + + private void FillCompilerInfoOptions(NETGenerator.CompilerOptions compilerOptions) + { + var compilerDirectives = new List(); + + if (this.compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.product_string, out compilerDirectives)) + { + compilerOptions.Product = compilerDirectives[0].directive; + } + if (this.compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.version_string, out compilerDirectives)) + { + compilerOptions.ProductVersion = compilerDirectives[0].directive; + } + if (this.compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.company_string, out compilerDirectives)) + { + compilerOptions.Company = compilerDirectives[0].directive; + } + if (this.compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.trademark_string, out compilerDirectives)) + { + compilerOptions.TradeMark = compilerDirectives[0].directive; + } + if (this.compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.copyright_string, out compilerDirectives)) + { + compilerOptions.Copyright = compilerDirectives[0].directive; + } + if (this.compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.title_string, out compilerDirectives)) + { + compilerOptions.Title = compilerDirectives[0].directive; + } + if (this.compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.description_string, out compilerDirectives)) + { + compilerOptions.Description = compilerDirectives[0].directive; + } + if (this.compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.main_resource_string, out compilerDirectives)) + { + if (this.compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.product_string) || + this.compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.version_string) || + this.compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.company_string) || + this.compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.trademark_string) || + this.compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.title_string) || + this.compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.description_string) || + this.compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.copyright_string)) + { + ErrorsList.Add(new MainResourceNotAllowed(compilerDirectives[0].location)); + } + TryThrowInvalidPath(compilerDirectives[0].directive, compilerDirectives[0].location); + // Тут не обязательно нормализовывать путь + // И если он слишком длинный - File.Exists вернёт false + compilerOptions.MainResourceFileName = Path.Combine(Path.GetDirectoryName(compilerDirectives[0].source_file), compilerDirectives[0].directive); + if (!File.Exists(compilerOptions.MainResourceFileName)) + ErrorsList.Add(new ResourceFileNotFound(compilerDirectives[0].directive, compilerDirectives[0].location)); + } + + } + + private void FillCompilerOptionsFromProject(NETGenerator.CompilerOptions compilerOptions) + { + 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; + + if (!string.IsNullOrEmpty(project.product)) + compilerOptions.Product = project.product; + + if (!string.IsNullOrEmpty(project.company)) + compilerOptions.Company = project.company; + + if (!string.IsNullOrEmpty(project.trademark)) + compilerOptions.TradeMark = project.trademark; + + if (!string.IsNullOrEmpty(project.copyright)) + compilerOptions.Copyright = project.copyright; + + if (!string.IsNullOrEmpty(project.title)) + compilerOptions.Title = project.title; + + if (!string.IsNullOrEmpty(project.description)) + compilerOptions.Description = project.description; + + if (project.ProjectType == ProjectType.WindowsApp) + compilerOptions.target = NETGenerator.TargetType.WinExe; + + // возможно, требуется переименование EVA + // CreateRCFile(compilerOptions); + } + } + + private void CreateRCFile(NETGenerator.CompilerOptions compilerOptions) + { + if (!string.IsNullOrEmpty(project.app_icon)) + { + //cdo.MainResourceFileName = project.app_icon; + string rc_file = Path.GetFileNameWithoutExtension(project.app_icon) + ".rc"; + StreamWriter sw = File.CreateText(rc_file); + sw.WriteLine("1 ICON \"" + project.app_icon.Replace("\\", "\\\\") + "\""); + if (compilerOptions.NeedDefineVersionInfo) + { + compilerOptions.NeedDefineVersionInfo = false; + 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"); + 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("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 + "\""); + sw.WriteLine("VALUE \"ProductVersion\"," + "\"" + ver + "\""); + sw.WriteLine("VALUE \"FileDescription\"," + "\"" + compilerOptions.Description + "\""); + sw.WriteLine("VALUE \"OriginalFileName\"," + "\"" + Path.GetFileName(CompilerOptions.OutputFileName) + "\""); + sw.WriteLine("VALUE \"InternalName\"," + "\"" + Path.GetFileNameWithoutExtension(CompilerOptions.OutputFileName) + "\""); + sw.WriteLine("VALUE \"CompanyName\"," + "\"" + compilerOptions.Company + "\""); + sw.WriteLine("VALUE \"LegalTrademarks1\"," + "\"" + compilerOptions.TradeMark + "\""); + sw.WriteLine("VALUE \"LegalCopyright\"," + "\"" + compilerOptions.Copyright + "\""); + sw.WriteLine("END"); + sw.WriteLine("END"); + + sw.WriteLine("BLOCK \"VarFileInfo\"\r\nBEGIN"); + sw.WriteLine("VALUE \"Translation\", 0x0419, 1251"); + sw.WriteLine("END"); + sw.WriteLine("END"); + } + sw.Close(); + System.Diagnostics.Process prc = new System.Diagnostics.Process(); + prc.StartInfo.FileName = Path.Combine(this.CompilerOptions.SystemDirectory, "rc.exe"); + prc.StartInfo.Arguments = Path.Combine(Path.GetDirectoryName(project.app_icon), Path.GetFileNameWithoutExtension(project.app_icon) + ".rc"); + prc.StartInfo.CreateNoWindow = true; + prc.StartInfo.UseShellExecute = false; + prc.StartInfo.RedirectStandardOutput = true; + prc.StartInfo.RedirectStandardError = true; + prc.Start(); + prc.WaitForExit(); + string res_file = Path.Combine(Path.GetDirectoryName(project.app_icon), Path.GetFileNameWithoutExtension(project.app_icon) + ".res"); + if (File.Exists(res_file)) + { + compilerOptions.MainResourceFileName = res_file; // !!! главный ресурсный файл + } + File.Delete(rc_file); + } + } + + private void SetTargetTypeOption(NETGenerator.CompilerOptions compilerOptions) + { + compilerOptions.ForRunningWithEnvironment = CompilerOptions.RunWithEnvironment; + + // тип выходного файла + if (compilerOptions.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; + } + } + + // Debug / Release + compilerOptions.dbg_attrs = CompilerOptions.Debug ? NETGenerator.DebugAttributes.Debug : NETGenerator.DebugAttributes.Release; + if (CompilerOptions.ForDebugging) + compilerOptions.dbg_attrs = NETGenerator.DebugAttributes.ForDebugging; + } + public string Compile() { - - try + try { - //var timer = System.Diagnostics.Stopwatch.StartNew(); ////// - - if (Path.GetExtension(CompilerOptions.SourceFileName) == ".vb") - { - return CompileVB(); - } - + // компиляция C# if (Path.GetExtension(CompilerOptions.SourceFileName) == ".cs") { return CompileCS(); } - - OnChangeCompilerState(this, CompilerState.CompilationStarting, CompilerOptions.SourceFileName); + // вызов события смены состояния компилятора - начало компиляции + // событие имеет много потенциальных обработчиков + OnChangeCompilerState(this, CompilerState.CompilationStarting, CompilerOptions.SourceFileName); + + // очистка всех переменных и списков, используемых в процессе Reset(); - //Console.WriteLine(timer.ElapsedMilliseconds / 1000.0); ////// + + // если проект скомпилирован, то заполнение информации о проекте в опциях компилятора if (CompilerOptions.ProjectCompiled) { - PrepareCompileOptionsForProject(); + PrepareCompileOptionsForProject(); } - CurrentSyntaxUnit = new SyntaxTree.uses_unit_in(null, new SyntaxTree.string_const(Path.GetFullPath(CompilerOptions.SourceFileName))); - + + #region CONSTRUCTING SYNTAX AND SEMANTIC TREES STAGE + + // компиляция всех юнитов произойдет рекурсивно (кроме отложенных) CompileUnit( - new PascalABCCompiler.TreeRealization.unit_node_list(), + new unit_node_list(), new Dictionary(), - CurrentSyntaxUnit, null); - - //Console.WriteLine(timer.ElapsedMilliseconds / 1000.0); ////// - foreach (CompilationUnit CurrentUnit in UnitsToCompile) - if (CurrentUnit.State != UnitState.Compiled) - { - CurrentCompilationUnit = CurrentUnit; - string UnitName = CurrentCompilationUnit.SyntaxTree.file_name; - //if(CurrentUnit.State!=UnitState.InterfaceCompiled) //DEBUG - //Console.WriteLine("ERROR! interface not compiled "+GetUnitFileName(CurrentUnit.SyntaxUnitName));//DEBUG - System.Collections.Generic.List SyntaxUsesList = GetSyntaxImplementationUsesList(CurrentUnit.SyntaxTree); - CurrentUnit.PossibleNamespaces.Clear(); - if (HasIncludeNamespacesDirective(CurrentUnit)) - compilerOptions.UseDllForSystemUnits = false; - if (SyntaxUsesList != null) - { - for (int i = SyntaxUsesList.Count - 1; i >= 0; i--) - if (!IsPossibleNamespace(SyntaxUsesList[i], false, Path.GetDirectoryName(UnitName))) - { - compilerOptions.UseDllForSystemUnits = false; - break; - } - for (int i = SyntaxUsesList.Count - 1; i >= 0; i--) - if (!IsPossibleNamespace(SyntaxUsesList[i], true, Path.GetDirectoryName(UnitName))) - { - CompileUnit(CurrentUnit.ImplementationUsedUnits, CurrentUnit.DirectImplementationCompilationUnits, SyntaxUsesList[i], Path.GetDirectoryName(UnitName)); - } - else - { - CurrentUnit.ImplementationUsedUnits.AddElement(new TreeRealization.namespace_unit_node(GetNamespace(SyntaxUsesList[i])), null); - CurrentUnit.PossibleNamespaces.Add(SyntaxUsesList[i]); - } - } - //Console.WriteLine("Compile Implementation "+UnitName);//DEBUG - //TODO: Избавиться от преобразования типа. + new SyntaxTree.uses_unit_in(null, new SyntaxTree.string_const(Path.GetFullPath(CompilerOptions.SourceFileName))), + null); - AddNamespaces(CurrentUnit.ImplementationUsingNamespaceList, CurrentUnit.PossibleNamespaces, true, null); - -#if DEBUG - if (InternalDebug.SemanticAnalysis) -#endif - { - OnChangeCompilerState(this, CompilerState.CompileImplementation, UnitName); - PascalABCCompiler.TreeConverter.SemanticRules.SymbolTableCaseSensitive = CurrentUnit.CaseSensitive; - SyntaxTreeToSemanticTreeConverter.CompileImplementation( - (PascalABCCompiler.TreeRealization.common_unit_node)CurrentUnit.SemanticTree, - CurrentUnit.SyntaxTree, - buildImplementationUsesList(CurrentUnit), - ErrorsList,Warnings, - CurrentUnit.syntax_error, BadNodesInSyntaxTree, - CurrentUnit.InterfaceUsingNamespaceList, - CurrentUnit.ImplementationUsingNamespaceList, - null, - CompilerOptions.Debug, - CompilerOptions.ForDebugging, - CompilerOptions.ForIntellisense, - CompiledVariables - ); - CheckErrors(); - } - CurrentUnit.State = UnitState.Compiled; - OnChangeCompilerState(this, CompilerState.EndCompileFile, UnitName); - //SavePCU(CurrentUnit, UnitName); - CurrentUnit.UnitFileName = UnitName; - } + // компиляция юнитов из списка отложенной компиляции, если он не пуст + CompileUnitsFromDelayedList(); + #endregion + // Закрытие чтения и записи .pcu файлов ClosePCUReadersAndWriters(); - if (CompilerOptions.SaveDocumentation) - SaveDocumentations(); - - compilerDirectives = GetCompilerDirectives(UnitsSortedList); - if (compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.compiler_directive_apptype)) - { - string directive = compilerDirectives[TreeConverter.compiler_string_consts.compiler_directive_apptype][0].directive; - if (string.Compare(directive,"console",true)==0) - CompilerOptions.OutputFileType = CompilerOptions.OutputType.ConsoleApplicaton; - else - if (string.Compare(directive,"windows",true)==0) - CompilerOptions.OutputFileType = CompilerOptions.OutputType.WindowsApplication; - else - if (string.Compare(directive,"dll",true)==0) - CompilerOptions.OutputFileType = CompilerOptions.OutputType.ClassLibrary; - else - if (string.Compare(directive,"pcu",true)==0) - CompilerOptions.OutputFileType = CompilerOptions.OutputType.PascalCompiledUnit; - } + PrebuildMainSemanticTreeActions(out var compilerOptions, out var resourceFiles); - moveSystemUnitToForwardUnitSortedList(); - PascalABCCompiler.TreeRealization.common_unit_node system_unit = null; - if (UnitsSortedList.Count>0) - system_unit = UnitsSortedList[0].SemanticTree as PascalABCCompiler.TreeRealization.common_unit_node; - if (system_unit != null) - system_unit.IsConsoleApplicationVariable = CompilerOptions.OutputFileType == CompilerOptions.OutputType.ConsoleApplicaton; - - TreeRealization.program_node pn = null; - NETGenerator.CompilerOptions cdo = new NETGenerator.CompilerOptions(); - List cds; - if (compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.compiler_directive_platformtarget, out cds)) - { - string plt = cds[0].directive.ToLower(); - if (plt.Equals("x86")) - cdo.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x86; - else if (plt.Equals("x64")) - cdo.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x64; - else if (plt.Equals("anycpu")) - cdo.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.AnyCPU; - else if (plt.Equals("dotnet5win")) - cdo.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5win; - else if (plt.Equals("dotnet5linux")) - cdo.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5linux; - else if (plt.Equals("dotnet5macos")) - cdo.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnet5macos; - else if (plt.Equals("native")) - { - if (Environment.OSVersion.Platform == PlatformID.Unix) - cdo.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetlinuxnative; - else if (Environment.OSVersion.Platform == PlatformID.MacOSX) - cdo.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetmacosnative; - else - cdo.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.dotnetwinnative; - } - } - if (this.compilerOptions.Only32Bit) - cdo.platformtarget = NETGenerator.CompilerOptions.PlatformTarget.x86; - if (compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.compiler_directive_targetframework, out cds)) - { - cdo.TargetFramework = cds[0].directive; - if (!new string[] { "net40", "net403", "net45", "net451", "net452", "net46", "net461", "net462", "net47", "net471", "net472", "net48", "net481" } - .Contains(cdo.TargetFramework)) - ErrorsList.Add(new UnsupportetTargetFramework(cdo.TargetFramework, cds[0].location)); - } - if (compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.product_string, out cds)) - { - cdo.Product = cds[0].directive; - } - if (compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.version_string, out cds)) - { - cdo.ProductVersion = cds[0].directive; - } - if (compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.company_string, out cds)) - { - cdo.Company = cds[0].directive; - } - if (compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.trademark_string, out cds)) - { - cdo.TradeMark = cds[0].directive; - } - if (compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.copyright_string, out cds)) - { - cdo.Copyright = cds[0].directive; - } - if (compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.title_string, out cds)) - { - cdo.Title = cds[0].directive; - } - if (compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.description_string, out cds)) - { - cdo.Description = cds[0].directive; - } - if (compilerDirectives.TryGetValue(TreeConverter.compiler_string_consts.main_resource_string, out cds)) - { - if (compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.product_string) || - compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.version_string) || - compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.company_string) || - compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.trademark_string) || - compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.title_string) || - compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.description_string) || - compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.copyright_string)) - { - ErrorsList.Add(new MainResourceNotAllowed(cds[0].location)); - } - TryThrowInvalidPath(cds[0].directive, cds[0].location); - // Тут не обязательно нормализовывать путь - // И если он слишком длинный - File.Exists вернёт false - cdo.MainResourceFileName = Path.Combine(Path.GetDirectoryName(cds[0].source_file), cds[0].directive); - if (!File.Exists(cdo.MainResourceFileName)) - ErrorsList.Add(new ResourceFileNotFound(cds[0].directive, cds[0].location)); - } - - List ResourceFiles = null; - if (compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.compiler_directive_resource)) - { - ResourceFiles = new List(); - List ResourceDirectives = compilerDirectives[TreeConverter.compiler_string_consts.compiler_directive_resource]; - foreach (TreeRealization.compiler_directive cd in ResourceDirectives) { - TryThrowInvalidPath(cd.directive, cd.location); - var resource_fname = Path.Combine(Path.GetDirectoryName(cd.source_file), cd.directive); - - // Так же как с main_resource - if (File.Exists(resource_fname)) - ResourceFiles.Add(resource_fname); - else - ErrorsList.Add(new ResourceFileNotFound(cd.directive, cd.location)); - - } - } - string res_file = null; - if (project != null) - { - if (!(project.major_version == 0 && project.minor_version == 0 && project.build_version == 0 && project.revision_version == 0)) - cdo.ProductVersion = project.major_version + "." + project.minor_version + "." + project.build_version + "." + project.revision_version; - if (!string.IsNullOrEmpty(project.product)) - cdo.Product = project.product; - if (!string.IsNullOrEmpty(project.company)) - cdo.Company = project.company; - if (!string.IsNullOrEmpty(project.trademark)) - cdo.TradeMark = project.trademark; - if (!string.IsNullOrEmpty(project.copyright)) - cdo.Copyright = project.copyright; - if (!string.IsNullOrEmpty(project.title)) - cdo.Title = project.title; - if (!string.IsNullOrEmpty(project.description)) - cdo.Description = project.description; - if (!string.IsNullOrEmpty(project.app_icon) && false) - { - //cdo.MainResourceFileName = project.app_icon; - string rc_file = Path.GetFileNameWithoutExtension(project.app_icon) + ".rc"; - StreamWriter sw = File.CreateText(rc_file); - sw.WriteLine("1 ICON \"" + project.app_icon.Replace("\\", "\\\\") + "\""); - if (cdo.NeedDefineVersionInfo) - { - cdo.NeedDefineVersionInfo = false; - 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"); - 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("BEGIN \r\n BLOCK \"StringFileInfo\"\r\n BEGIN \r\n BLOCK \"041904E3\"\r\nBEGIN"); - sw.WriteLine("VALUE \"ProductName\"," + "\"" + cdo.Product + "\""); - sw.WriteLine("VALUE \"FileVersion\"," + "\"" + ver + "\""); - sw.WriteLine("VALUE \"ProductVersion\"," + "\"" + ver + "\""); - sw.WriteLine("VALUE \"FileDescription\"," + "\"" + cdo.Description + "\""); - sw.WriteLine("VALUE \"OriginalFileName\"," + "\"" + Path.GetFileName(CompilerOptions.OutputFileName) + "\""); - sw.WriteLine("VALUE \"InternalName\"," + "\"" + Path.GetFileNameWithoutExtension(CompilerOptions.OutputFileName) + "\""); - sw.WriteLine("VALUE \"CompanyName\"," + "\"" + cdo.Company + "\""); - sw.WriteLine("VALUE \"LegalTrademarks1\"," + "\"" + cdo.TradeMark + "\""); - sw.WriteLine("VALUE \"LegalCopyright\"," + "\"" + cdo.Copyright + "\""); - sw.WriteLine("END"); - sw.WriteLine("END"); - - sw.WriteLine("BLOCK \"VarFileInfo\"\r\nBEGIN"); - sw.WriteLine("VALUE \"Translation\", 0x0419, 1251"); - sw.WriteLine("END"); - sw.WriteLine("END"); - } - sw.Close(); - System.Diagnostics.Process prc = new System.Diagnostics.Process(); - prc.StartInfo.FileName = Path.Combine(this.CompilerOptions.SystemDirectory, "rc.exe"); - prc.StartInfo.Arguments = Path.Combine(Path.GetDirectoryName(project.app_icon), Path.GetFileNameWithoutExtension(project.app_icon) + ".rc"); - prc.StartInfo.CreateNoWindow = true; - prc.StartInfo.UseShellExecute = false; - prc.StartInfo.RedirectStandardOutput = true; - prc.StartInfo.RedirectStandardError = true; - prc.Start(); - prc.WaitForExit(); - res_file = Path.Combine(Path.GetDirectoryName(project.app_icon), Path.GetFileNameWithoutExtension(project.app_icon) + ".res"); - if (File.Exists(res_file)) - { - cdo.MainResourceFileName = res_file; - } - File.Delete(rc_file); - } - } - + #region GENERATING CODE STAGE if (ErrorsList.Count == 0) { - cdo.ForRunningWithEnvironment = CompilerOptions.RunWithEnvironment; - switch (CompilerOptions.OutputFileType) + + //TODO: Разобратся c location для program_node и правильно передавать main_function. Добавить генератор main_function в SyntaxTreeToSemanticTreeConverter. | Думать позже EVA + // получние полного семантического дерева, включающего все зависимости + program_node semanticTree = ConstructMainSemanticTree(compilerOptions); + + if (firstCompilationUnit.SyntaxTree is SyntaxTree.unit_module && CompilerOptions.OutputFileType != CompilerOptions.OutputType.ClassLibrary) { - case CompilerOptions.OutputType.ClassLibrary: cdo.target = NETGenerator.TargetType.Dll; break; - case CompilerOptions.OutputType.ConsoleApplicaton: cdo.target = NETGenerator.TargetType.Exe; break; - case CompilerOptions.OutputType.WindowsApplication: cdo.target = NETGenerator.TargetType.WinExe; break; - - } - if (project != null && project.ProjectType == ProjectType.WindowsApp) - cdo.target = PascalABCCompiler.NETGenerator.TargetType.WinExe; - switch (CompilerOptions.Debug) - { - case true: cdo.dbg_attrs = NETGenerator.DebugAttributes.Debug; break; - case false: cdo.dbg_attrs = NETGenerator.DebugAttributes.Release; break; - } - if (CompilerOptions.ForDebugging) - cdo.dbg_attrs = NETGenerator.DebugAttributes.ForDebugging; - - - //TODO: Разобратся c location для program_node и правильно передавать main_function. Добавить генератор main_function в SyntaxTreeToSemanticTreeConverter. - pn = new PascalABCCompiler.TreeRealization.program_node(null, null); - - for (int i = 0; i < UnitsSortedList.Count; i++) - pn.units.AddElement(UnitsSortedList[i].SemanticTree as TreeRealization.common_unit_node); - - //(ssyy) Добавил в условие c_module - if (FirstCompilationUnit.SyntaxTree is SyntaxTree.program_module || - FirstCompilationUnit.SyntaxTree is SyntaxTree.c_module) - { - if ((cdo.target == NETGenerator.TargetType.Exe) || (cdo.target == NETGenerator.TargetType.WinExe)) - { - if (UnitsSortedList.Count > 0) - { - pn.main_function = ((PascalABCCompiler.TreeRealization.common_unit_node)UnitsSortedList[UnitsSortedList.Count - 1].SemanticTree).main_function; - /***************************Ivan added*******************************/ - if (pn.main_function.function_code.location != null) - { - bool flag = false; - PascalABCCompiler.TreeRealization.common_namespace_node main_ns = pn.main_function.namespace_node; - for (int i = 0; i < main_ns.variables.Count; i++) - { - PascalABCCompiler.TreeRealization.namespace_variable nv = main_ns.variables[i]; - if (nv.inital_value != null && nv.inital_value.location != null && !(nv.inital_value is PascalABCCompiler.TreeRealization.constant_node) - && !(nv.inital_value is PascalABCCompiler.TreeRealization.record_initializer) && !(nv.inital_value is PascalABCCompiler.TreeRealization.array_initializer)) - { - varBeginOffset = main_ns.variables[i].inital_value.location.begin_line_num; - flag = true; - break; - } - } - beginOffset = pn.main_function.function_code.location.begin_line_num; - } - /*******************************************************************/ - Dictionary config_dic = new Dictionary(); - if (CompilerOptions.Locale != null && PascalABCCompiler.StringResourcesLanguage.GetLCIDByTwoLetterISO(CompilerOptions.Locale) != null) - { - config_dic["locale"] = CompilerOptions.Locale; - config_dic["full_locale"] = PascalABCCompiler.StringResourcesLanguage.GetLCIDByTwoLetterISO(CompilerOptions.Locale); - } - pn.create_main_function(StandarModules.ToArray(), config_dic); - - } - } - } - else if (FirstCompilationUnit.SyntaxTree is SyntaxTree.unit_module && cdo.target == NETGenerator.TargetType.Dll) - { - pn.create_main_function_as_in_module(); - } - if (compilerOptions.GenerateCode) - pn = semanticTreeConvertersController.Convert(pn) as TreeRealization.program_node; - - _semantic_tree = pn; - - if (FirstCompilationUnit.SyntaxTree is SyntaxTree.unit_module && CompilerOptions.OutputFileType != CompilerOptions.OutputType.ClassLibrary) - { - //если мы комилируем PCU + // если мы комилируем PCU CompilerOptions.OutputFileType = CompilerOptions.OutputType.PascalCompiledUnit; } - else if (compilerOptions.GenerateCode) + // генерация IL кода + else if (CompilerOptions.GenerateCode) { - if( CompilerOptions.OutputFileType!= CompilerOptions.OutputType.SemanticTree) -#if DEBUG - if (InternalDebug.CodeGeneration) -#endif - { - int n = 1; - try - { - n = 2; - var fs = File.Create(CompilerOptions.OutputFileName); - n = 3; - fs.Close(); - n = 4; - ///////File.Delete(CompilerOptions.OutputFileName); - string pdb_file_name=Path.ChangeExtension(CompilerOptions.OutputFileName, ".pdb"); - if (File.Exists(pdb_file_name)) - File.Delete(pdb_file_name); - n = 5; // PVS 01/2022 - } - catch (Exception e) - { - throw new UnauthorizedAccessToFile(CompilerOptions.OutputFileName + " -- " + n + " " + e.ToString()); - //throw e; - } - OnChangeCompilerState(this, CompilerState.CodeGeneration, CompilerOptions.OutputFileName); - string[] ResourceFilesArray = null; - if (ResourceFiles != null) - ResourceFilesArray = ResourceFiles.ToArray(); - cds = null; - /*if (compilerDirectives.TryGetValue("platform", out cds) && cds[0].directive.ToLower() == "native") - { - //LLVMCodeGeneratorsController.Compile(pn, CompilerOptions.OutputFileName, CompilerOptions.SourceFileName, ResourceFilesArray); - PABCToCppCodeGeneratorsController.Compile(pn, CompilerOptions.OutputFileName, CompilerOptions.SourceFileName, ResourceFilesArray); - } - else*/ - if (compilerOptions.UseDllForSystemUnits) - cdo.RtlPABCSystemType = NetHelper.NetHelper.FindRtlType("PABCSystem.PABCSystem"); - CodeGeneratorsController.Compile(pn, CompilerOptions.OutputFileName, CompilerOptions.SourceFileName, cdo, CompilerOptions.StandartDirectories, ResourceFilesArray); - CodeGeneratorsController.EmitAssemblyRedirects( - assemblyResolveScope, - CompilerOptions.OutputFileName); - if (res_file != null) - File.Delete(res_file); - } - } - } - } - catch (TreeConverter.ParserError err) - { - //конвертор уткнулся в ошибку. ничего не делаем - } - catch (Errors.CompilerInternalError err) - { - if (ErrorsList.Count == 0) - ErrorsList.Add(err); - else - { -#if DEBUG - if (!InternalDebug.SkipInternalErrorsIfSyntaxTreeIsCorrupt) - ErrorsList.Add(err); -#endif - } - } - catch (Errors.Error err) - { - if (ErrorsList.Count == 0) - ErrorsList.Add(err); - else - if (err != ErrorsList[0]) - { - if (err is SemanticError) - { - int pos = ErrorsList.Count; - SourceLocation loc = (err as SemanticError).SourceLocation, loctmp; - if (loc != null) - for (int i = 0; i < ErrorsList.Count; i++) - if (ErrorsList[i] is LocatedError) - if ((loctmp = (ErrorsList[i] as LocatedError).SourceLocation) != null) - if (loctmp > loc) - { - pos = i; - break; - } + if (CompilerOptions.UseDllForSystemUnits) + compilerOptions.RtlPABCSystemType = NetHelper.NetHelper.FindRtlType("PABCSystem.PABCSystem"); - ErrorsList.Insert(pos, err); - } - else - ErrorsList.Add(err); + GenerateILCode(semanticTree, compilerOptions, resourceFiles); } + } + #endregion + + } + // TODO: просмотреть возможные ParserError EVA + catch (TreeConverter.ParserError) + { + // конвертор уткнулся в ошибку. ничего не делаем + } + catch (CompilerInternalError err) + { + AddInternalErrorToErrorList(err); + } + catch (Error err) + { + // здесь учитывается позиция Located error + AddErrorToErrorListConsideringPosition(err); } catch (Exception err) { - - string fn = "Compiler"; - if (CurrentCompilationUnit != null && this.CurrentCompilationUnit.SyntaxTree != null) fn = Path.GetFileName(this.CurrentCompilationUnit.SyntaxTree.file_name); - Errors.CompilerInternalError comp_err = new Errors.CompilerInternalError(string.Format("Compiler.Compile[{0}]", fn), err); - if (ErrorsList.Count == 0) - ErrorsList.Add(comp_err); - else - { -#if DEBUG - if (!InternalDebug.SkipInternalErrorsIfSyntaxTreeIsCorrupt) - ErrorsList.Add(comp_err); -#endif - } + // здесь добавляются только ошибки генерации кода + AddCodeGenerationErrorToErrorList(err); } - - //удаляем лишние ошибки - /*foreach(Error er in errorsList) - { - }*/ - - //на случай если мы вывалились по исключению но у нас есть откомпилированные модули + // на случай если мы вывалились по исключению, но у нас есть откомпилированные модули try { ClosePCUReadersAndWriters(); } catch (Exception e) { - ErrorsList.Add(new Errors.CompilerInternalError("Compiler.ClosePCUReadersAndWriters", e)); + ErrorsList.Add(new CompilerInternalError("Compiler.ClosePCUReadersAndWriters", e)); } - bool need_recompiled = false; - if (ErrorsList.Count > 0) - { - if (compilerOptions.UseDllForSystemUnits && !has_only_syntax_errors(ErrorsList) && compilerOptions.IgnoreRtlErrors) - { - compilerOptions.UseDllForSystemUnits = false; - ErrorsList.Clear(); - - need_recompiled = true; - } - } - OnChangeCompilerState(this, CompilerState.CompilationFinished, CompilerOptions.SourceFileName); + OnChangeCompilerState(this, CompilerState.CompilationFinished, CompilerOptions.SourceFileName); // compilation finished state + if (ClearAfterCompilation) - ClearAll(); - - if (!need_recompiled) - OnChangeCompilerState(this, CompilerState.Ready, null); + ClearAll(); + + // на случай ошибки в самом .pcu формате | теоретически, здесь могут быть не только pcu errors EVA + bool recompilationNeeded = CheckForInternalErrors(); + + if (!recompilationNeeded) + OnChangeCompilerState(this, CompilerState.Ready, null); // компилятор окончательно завершил работу + if (ErrorsList.Count > 0) { return null; } - else if (need_recompiled) + else if (recompilationNeeded) { //Compiler c = new Compiler(sourceFilesProvider,OnChangeCompilerState); //return c.Compile(this.compilerOptions); return Compile(); } - else - return CompilerOptions.OutputFileName; + else return CompilerOptions.OutputFileName; } - private bool has_only_syntax_errors(List errors) + private void PrebuildMainSemanticTreeActions(out NETGenerator.CompilerOptions compilerOptions, out List resourceFiles) + { + if (CompilerOptions.SaveDocumentation) + { + SaveDocumentationsForUnits(); + } + + compilerDirectives = GetCompilerDirectives(UnitsLogicallySortedList); + + // выяснение типа выходного файла по соотв. директиве компилятора + SetOutputFileTypeOption(); + + // перемещаем PABCSystem в начало списка + MoveSystemUnitForwardInUnitLogicallySortedList(); + + // передача информации о типе выходного файла системному юниту + if (UnitsLogicallySortedList.Count > 0) + { + bool isConsoleApplication = CompilerOptions.OutputFileType == CompilerOptions.OutputType.ConsoleApplicaton; + common_unit_node systemUnit = UnitsLogicallySortedList[0].SemanticTree as common_unit_node; + systemUnit.IsConsoleApplicationVariable = isConsoleApplication; + } + + compilerOptions = new NETGenerator.CompilerOptions(); + + // выяснение целевой платформы + SetOutputPlatformOption(compilerOptions); + + // остальные директивы + FillCompilerInfoOptions(compilerOptions); + + // заполнение опций компилятора из заголовка проекта + FillCompilerOptionsFromProject(compilerOptions); + + // Устанавливает опции компилятора, связанные с типом выходного файла + SetTargetTypeOption(compilerOptions); + + resourceFiles = GetResourceFilesFromCompilerDirectives(); + } + + private program_node ConstructMainSemanticTree(NETGenerator.CompilerOptions compilerOptions) + { + program_node mainSemanticTree = new program_node(null, null); + + for (int i = 0; i < UnitsLogicallySortedList.Count; i++) + mainSemanticTree.units.AddElement(UnitsLogicallySortedList[i].SemanticTree as common_unit_node); + + bool targetTypeIsExe = compilerOptions.target == NETGenerator.TargetType.Exe || compilerOptions.target == NETGenerator.TargetType.WinExe; + + // если компилируем exe или WinExe (первый модуль - основная программа) + if (firstCompilationUnit.SyntaxTree is SyntaxTree.program_module && targetTypeIsExe && UnitsLogicallySortedList.Count > 0) + { + mainSemanticTree.main_function = ((common_unit_node)UnitsLogicallySortedList.Last().SemanticTree).main_function; + + PrepareFinalMainFunctionForExe(mainSemanticTree); + } + // если мы компилируем dll + else if (firstCompilationUnit.SyntaxTree is SyntaxTree.unit_module) + { + // TODO: посмотреть инициализирующий код .dll EVA + mainSemanticTree.create_main_function_as_in_module(); + } + + if (CompilerOptions.GenerateCode) // семантические преобразования с оптимизацией кода + mainSemanticTree = semanticTreeConvertersController.Convert(mainSemanticTree) as program_node; + + semanticTree = mainSemanticTree; + return mainSemanticTree; + } + + public void PrepareFinalMainFunctionForExe(program_node mainSemanticTree) + { + // вычисляем номер строку первой переменной и строки с началом основной программы + if (mainSemanticTree.main_function.function_code.location != null) + { + common_namespace_node main_ns = mainSemanticTree.main_function.namespace_node; + + foreach (namespace_variable variable in main_ns.variables) + { + if (variable.inital_value?.location != null && !(variable.inital_value is constant_node) + && !(variable.inital_value is record_initializer) && !(variable.inital_value is array_initializer)) + { + varBeginOffset = variable.inital_value.location.begin_line_num; + break; + } + } + beginOffset = mainSemanticTree.main_function.function_code.location.begin_line_num; + } + + // локализация + Dictionary config_dict = new Dictionary(); + if (CompilerOptions.Locale != null && StringResourcesLanguage.GetLCIDByTwoLetterISO(CompilerOptions.Locale) != null) + { + config_dict["locale"] = CompilerOptions.Locale; + config_dict["full_locale"] = StringResourcesLanguage.GetLCIDByTwoLetterISO(CompilerOptions.Locale); + } + mainSemanticTree.create_main_function(StandardModules.ToArray(), config_dict); + } + + private void AddErrorToErrorListConsideringPosition(Error err) + { + if (ErrorsList.Count == 0) + ErrorsList.Add(err); + else if (err != ErrorsList[0]) + { + if (err is SemanticError) + { + int position = FindPositionForSemanticErrorInTheErrorList(err); // семантические ошибки отсортированы по location + + ErrorsList.Insert(position, err); + } + else ErrorsList.Add(err); + } + } + + private int FindPositionForSemanticErrorInTheErrorList(Error err) + { + int position = ErrorsList.Count; + + SourceLocation location = (err as SemanticError).SourceLocation; + SourceLocation locationTemp; + if (location != null) + { + for (int i = 0; i < ErrorsList.Count; i++) + { + if ((locationTemp = (ErrorsList[i] as LocatedError)?.SourceLocation) != null) + { + if (locationTemp > location) + { + position = i; + break; + } + } + } + } + + return position; + } + + private void AddCodeGenerationErrorToErrorList(Exception err) + { + string fileName = Path.GetFileName(currentCompilationUnit?.SyntaxTree?.file_name) ?? "Compiler"; + CompilerInternalError compilationError = new CompilerInternalError(string.Format("Compiler.Compile[{0}]", fileName), err); + + AddInternalErrorToErrorList(compilationError); + } + + private void AddInternalErrorToErrorList(CompilerInternalError internalError) + { + if (ErrorsList.Count == 0) + ErrorsList.Add(internalError); + else + { +#if DEBUG + if (!InternalDebug.SkipInternalErrorsIfSyntaxTreeIsCorrupt) + ErrorsList.Add(internalError); +#endif + } + } + + + private bool CheckForInternalErrors() + { + bool anyExternalErrors = false; + + if (ErrorsList.Count > 0) + { + // rtl - та самая dll со всей паскалевской системой (PABCSystem) + if (CompilerOptions.UseDllForSystemUnits && !HasOnlySyntaxErrors(ErrorsList) && CompilerOptions.IgnoreRtlErrors) + { + CompilerOptions.UseDllForSystemUnits = false; + ErrorsList.Clear(); + + anyExternalErrors = true; + + } + } + + return anyExternalErrors; + } + + private void GenerateILCode(program_node programNode, NETGenerator.CompilerOptions compilerOptions, List resourceFiles) + { + + if (CompilerOptions.OutputFileType != CompilerOptions.OutputType.SemanticTree) +#if DEBUG + if (InternalDebug.CodeGeneration) +#endif + { + // генерация файла .pdb для дебага + DebugOutputFileCreationUsingPDB(); + + OnChangeCompilerState(this, CompilerState.CodeGeneration, CompilerOptions.OutputFileName); // состояние генерации кода + + // трансляция в IL-код | В semanticTree находится ЕДИНСТВЕННОЕ семантическое дерево, содержащее программу и все семантические модули + CodeGeneratorsController.GenerateILCodeAndSaveAssembly(programNode, CompilerOptions.OutputFileName, + CompilerOptions.SourceFileName, compilerOptions, CompilerOptions.StandardDirectories, + resourceFiles?.ToArray()); + + CodeGeneratorsController.EmitAssemblyRedirects( + assemblyResolveScope, + CompilerOptions.OutputFileName); + + if (compilerOptions.MainResourceFileName != null) + File.Delete(compilerOptions.MainResourceFileName); + } + } + + private void DebugOutputFileCreationUsingPDB() + { + int n = 1; + try + { + n = 2; + var fs = File.Create(CompilerOptions.OutputFileName); + n = 3; + fs.Close(); + n = 4; + ///////File.Delete(CompilerOptions.OutputFileName); + string pdb_file_name = Path.ChangeExtension(CompilerOptions.OutputFileName, ".pdb"); + if (File.Exists(pdb_file_name)) + File.Delete(pdb_file_name); + n = 5; // PVS 01/2022 + } + catch (Exception e) + { + throw new UnauthorizedAccessToFile(CompilerOptions.OutputFileName + " -- " + n + " " + e.ToString()); + //throw e; + } + } + + private List GetResourceFilesFromCompilerDirectives() + { + List ResourceFiles = null; + if (compilerDirectives.ContainsKey(TreeConverter.compiler_string_consts.compiler_directive_resource)) + { + ResourceFiles = new List(); + List ResourceDirectives = compilerDirectives[TreeConverter.compiler_string_consts.compiler_directive_resource]; + + foreach (compiler_directive cd in ResourceDirectives) + { + TryThrowInvalidPath(cd.directive, cd.location); + var resourceFileName = Path.Combine(Path.GetDirectoryName(cd.source_file), cd.directive); + + // Так же как с main_resource + if (File.Exists(resourceFileName)) + ResourceFiles.Add(resourceFileName); + else + ErrorsList.Add(new ResourceFileNotFound(cd.directive, cd.location)); + + } + } + + return ResourceFiles; + } + + private bool HasOnlySyntaxErrors(List errors) { foreach (Error err in errors) { @@ -2397,41 +2551,41 @@ namespace PascalABCCompiler return true; } - private void SaveDocumentations() - { - DocXmlManager dxm = new DocXmlManager(); - foreach (CompilationUnit cu in UnitsSortedList) + private void SaveDocumentationsForUnits() + { + DocXmlManager dxm = new DocXmlManager(); + foreach (CompilationUnit cu in UnitsLogicallySortedList) { - if (cu.Documented) - dxm.SaveXml(cu); - } - } - + if (cu.Documented) + dxm.SaveXml(cu); + } + } + private void ClosePCUReadersAndWriters() { if (PCUReadersAndWritersClosed) return; PCUReadersAndWritersClosed = true; - + bool all_restored = false; while (!all_restored) { - foreach (PCUReader p in PCUReader.AllReaders) - { - p.AddInitFinalMethods(); + foreach (PCUReader p in PCUReader.AllReaders) + { + p.AddInitFinalMethods(); SystemLibrary.SystemLibInitializer.RestoreStandardFunctions(); p.ProcessWaitedToRestoreFields(); p.RestoreWaitedMethodCodes(); - } - bool rest = true; - for (int i=0; i usesList) + + /// + /// Бросает ошибку если находит дупликаты в секции uses + /// + void CheckForDuplicatesInUsesSection(List usesList) { - if(usesList==null) + if (usesList == null) return; List names = new List(); foreach (SyntaxTree.unit_or_namespace un in usesList) { - string name=SyntaxTree.Utils.IdentListToString(un.name.idents,".").ToLower(); + string name = SyntaxTree.Utils.IdentListToString(un.name.idents, ".").ToLower(); if (un.source_context != null) { if (names.Contains(name)) - throw new DuplicateUsesUnit(CurrentCompilationUnit.SyntaxTree.file_name, name, un.source_context); + throw new DuplicateUsesUnit(currentCompilationUnit.SyntaxTree.file_name, name, un.source_context); else names.Add(name); } } } - - public List GetSyntaxInterfaceUsesList(SyntaxTree.compilation_unit CurrentSyntaxUnit) - { - List result = null; - if(CurrentSyntaxUnit is SyntaxTree.unit_module) - { - SyntaxTree.interface_node intp = (CurrentSyntaxUnit as SyntaxTree.unit_module).interface_part; - if (intp.uses_modules == null) - if (CompilerOptions.StandartModules.Count > 0)//если есть стандартые модули то создать список - { - intp.uses_modules = new SyntaxTree.uses_list(); - intp.uses_modules.source_context = new SyntaxTree.SourceContext(1, 1, 1, 1, 1, 1); - } - else - return null; - result = intp.uses_modules.units; - } - if (CurrentSyntaxUnit is SyntaxTree.program_module) - { - SyntaxTree.program_module pm = (CurrentSyntaxUnit as SyntaxTree.program_module); - if (pm.used_units == null) - if (CompilerOptions.StandartModules.Count > 0)//если есть стандартые модули то создать список - { - pm.used_units = new SyntaxTree.uses_list(); - pm.used_units.source_context = new SyntaxTree.SourceContext(1, 1, 1, 1, 1, 1); - } - else - return null; - result = pm.used_units.units; - } - if (CurrentSyntaxUnit is SyntaxTree.c_module) - { - SyntaxTree.c_module pm = (CurrentSyntaxUnit as SyntaxTree.c_module); - if (pm.used_units == null) - if (CompilerOptions.StandartModules.Count > 0)//если есть стандартые модули то создать список - { - pm.used_units = new SyntaxTree.uses_list(); - pm.used_units.source_context = new SyntaxTree.SourceContext(1, 1, 1, 1, 1, 1); - } - else - return null; - result = pm.used_units.units; - } - checkDuplicateUsesUnit(result); - return result; - } - private List GetSyntaxImplementationUsesList(SyntaxTree.compilation_unit CurrentSyntaxUnit) - { - List result = null; - if(CurrentSyntaxUnit is SyntaxTree.unit_module) - if ((CurrentSyntaxUnit as SyntaxTree.unit_module).implementation_part!=null) - if ((CurrentSyntaxUnit as SyntaxTree.unit_module).implementation_part.uses_modules != null) + /// + /// Возвращает список зависимостей из интерфейсной части модуля (или основной программы) + /// + public List GetInterfaceUsesSection(SyntaxTree.compilation_unit unitSyntaxTree) + { + List usesList = null; + + if (unitSyntaxTree is SyntaxTree.unit_module unitModule) + { + if (unitModule.interface_part.uses_modules == null) + { + if (CompilerOptions.StandardModules.Count > 0) { - result = (CurrentSyntaxUnit as SyntaxTree.unit_module).implementation_part.uses_modules.units; - checkDuplicateUsesUnit(result); - return result; + unitModule.interface_part.uses_modules = new SyntaxTree.uses_list(); + unitModule.interface_part.uses_modules.source_context = new SyntaxTree.SourceContext(); } - if(CurrentSyntaxUnit is SyntaxTree.program_module) - return null; - return null; - } - + else return null; + } + + usesList = unitModule.interface_part.uses_modules.units; + } + else if (unitSyntaxTree is SyntaxTree.program_module programModule) + { + if (programModule.used_units == null) + { + if (CompilerOptions.StandardModules.Count > 0) + { + programModule.used_units = new SyntaxTree.uses_list(); + programModule.used_units.source_context = new SyntaxTree.SourceContext(); + } + else return null; + } + + usesList = programModule.used_units.units; + } + CheckForDuplicatesInUsesSection(usesList); + return usesList; + } + + private List GetImplementationUsesSection(SyntaxTree.compilation_unit unitSyntaxTree) + { + + List usesSection = (unitSyntaxTree as SyntaxTree.unit_module)?.implementation_part?.uses_modules?.units; + + CheckForDuplicatesInUsesSection(usesSection); + + return usesSection; + } + public string FindPCUFileName(string fname, string curr_path, out int folder_priority) { if (string.IsNullOrEmpty(Path.GetExtension(fname))) @@ -2557,7 +2701,7 @@ namespace PascalABCCompiler else if (FindFileInDirs(Path.GetFileName(fname), out _, CompilerOptions.OutputDirectory) is string res_s2) res = Tuple.Create(res_s2, 2); else if (FindFileInDirs(fname, out var dir_ind, CompilerOptions.SearchDirectory.ToArray()) is string res_s3) - res = Tuple.Create(res_s3, 3+dir_ind); + res = Tuple.Create(res_s3, 3 + dir_ind); else res = null; @@ -2578,7 +2722,7 @@ namespace PascalABCCompiler if (FindSourceFileNameInDirs(fname, out _, curr_path) is string res_s1) res = Tuple.Create(res_s1, 1); else if (FindSourceFileNameInDirs(fname, out var dir_ind, CompilerOptions.SearchDirectory.ToArray()) is string res_s3) - res = Tuple.Create(res_s3, 3+dir_ind); + res = Tuple.Create(res_s3, 3 + dir_ind); else res = null; @@ -2588,7 +2732,7 @@ namespace PascalABCCompiler folder_priority = res == null ? 0 : res.Item2; return res?.Item1; } - + public string FindSourceFileNameInDirs(string fname, out int found_dir_ind, params string[] Dirs) { var fname_ext = Path.GetExtension(fname); @@ -2596,10 +2740,10 @@ namespace PascalABCCompiler foreach (SupportedSourceFile sf in SupportedSourceFiles) foreach (string ext in sf.Extensions) - if (need_ext || fname_ext==ext) + if (need_ext || fname_ext == ext) { - var res = FindFileInDirs(need_ext ? fname+ext : fname, out found_dir_ind, Dirs); - //if (!(CompilerOptions.UseDllForSystemUnits && Path.GetDirectoryName(res) == CompilerOptions.SearchDirectory)) + var res = FindFileInDirs(need_ext ? fname + ext : fname, out found_dir_ind, Dirs); + //if (!(CompilerOptions.UseDllForSystemUnits && Path.GetDirectoryName(dlls) == CompilerOptions.SearchDirectory)) if (res != null) return res; } @@ -2608,13 +2752,16 @@ namespace PascalABCCompiler return null; } - public static string CombinePathsRelatively(string path1, string path2) { + public static string CombinePathsRelatively(string path1, string path2) + { if (Path.IsPathRooted(path2)) return path2; int i = 0; - foreach (var s in path2.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar })) { - if (s==".") continue; - if (s==".." && !string.IsNullOrWhiteSpace(path1) && !path1.EndsWith("..")) { + foreach (var s in path2.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar })) + { + if (s == ".") continue; + if (s == ".." && !string.IsNullOrWhiteSpace(path1) && !path1.EndsWith("..")) + { path1 = Path.GetDirectoryName(path1); if (path1 == null) return null; // Path.GetDirectoryName("C:\") возвращает null } @@ -2675,8 +2822,9 @@ namespace PascalABCCompiler return File.Exists(FileName) ? FileName : null; } - for (int dir_i = 0; dir_i UsesList = GetSyntaxInterfaceUsesList(cu); - if (UsesList == null) + if (CompilerOptions.StandardModules.Count == 0) return; - string cu_module_name = Path.GetFileNameWithoutExtension(cu.file_name).ToLower(); - foreach (CompilerOptions.StandartModule Module in CompilerOptions.StandartModules) - { - //Я стандартный?? - ModuleName = Path.GetFileNameWithoutExtension(Module.Name); - if (ModuleName.ToLower() == cu_module_name) - return; - } - foreach (CompilerOptions.StandartModule Module in CompilerOptions.StandartModules) - { - if ((Module.AddToLanguages & FirstCompilationUnit.SyntaxTree.Language) != FirstCompilationUnit.SyntaxTree.Language - && (Module.AddToLanguages & CurrentCompilationUnit.SyntaxTree.Language) != CurrentCompilationUnit.SyntaxTree.Language) - continue; - ModuleName = Path.GetFileNameWithoutExtension(Module.Name); - if (Module.AddMethod == CompilerOptions.StandartModuleAddMethod.RightToMain && CurrentCompilationUnit != FirstCompilationUnit) - continue; - foreach (SyntaxTree.unit_or_namespace curunit in UsesList) - { - if (curunit.name.idents.Count == 1 && curunit.name.idents[0].name.ToLower() == ModuleName.ToLower()) - continue; - } - PascalABCCompiler.SyntaxTree.unit_or_namespace to_add; - if (Path.GetExtension(Module.Name) != "" /*&& Path.GetExtension(ModuleFileName).ToLower() != ".dll"*/) + List usesList = GetInterfaceUsesSection(unitSyntaxTree); + + string currentModuleName = Path.GetFileNameWithoutExtension(unitSyntaxTree.file_name).ToLower(); + + foreach (CompilerOptions.StandardModule module in CompilerOptions.StandardModules) + { + string moduleName = Path.GetFileNameWithoutExtension(module.Name); + if (moduleName.ToLower() == currentModuleName) + return; + } + + foreach (CompilerOptions.StandardModule module in CompilerOptions.StandardModules) + { + if ((module.AddToLanguages & firstCompilationUnit.SyntaxTree.Language) != firstCompilationUnit.SyntaxTree.Language + && (module.AddToLanguages & currentCompilationUnit.SyntaxTree.Language) != currentCompilationUnit.SyntaxTree.Language) + continue; + + if (module.AddMethod == CompilerOptions.StandardModuleAddMethod.RightToMain && currentCompilationUnit != firstCompilationUnit) + continue; + + string moduleName = Path.GetFileNameWithoutExtension(module.Name); + + // если стандартный модуль уже подключен + bool isModuleAlreadyInUsesSection = false; + foreach (SyntaxTree.unit_or_namespace currentUnitNode in usesList) { - uses_unit_in = new SyntaxTree.uses_unit_in( - _name: new SyntaxTree.ident_list(new SyntaxTree.ident(ModuleName)), - _in_file: new SyntaxTree.string_const(Module.Name)); - //uses_unit_in.source_context = uses_unit_in.in_file.source_context = uses_unit_in.name.source_context = new SyntaxTree.SourceContext(1, 1, 1, 1); - to_add = uses_unit_in; + if (currentUnitNode.name.idents.Count == 1 && currentUnitNode.name.idents[0].name.ToLower() == moduleName.ToLower()) + { + isModuleAlreadyInUsesSection = true; + break; + } + + } + if (isModuleAlreadyInUsesSection) continue; + + // здесь присвоится либо паскалевский юнит, либо пространство имен + SyntaxTree.unit_or_namespace unitToAdd; + + if (Path.GetExtension(module.Name) != "" /*&& Path.GetExtension(ModuleFileName).ToLower() != ".dll"*/) + { + unitToAdd = new SyntaxTree.uses_unit_in( + new SyntaxTree.ident_list(new SyntaxTree.ident(moduleName)), + new SyntaxTree.string_const(module.Name)); + //uses_unit_in.source_context = uses_unit_in.in_file.source_context = uses_unit_in.name.source_context = new SyntaxTree.SourceContext(1, 1, 1, 1); Вопрос EVA } else { - uses_unit = new SyntaxTree.unit_or_namespace(new SyntaxTree.ident_list(new SyntaxTree.ident(ModuleName))); + unitToAdd = new SyntaxTree.unit_or_namespace(new SyntaxTree.ident_list(new SyntaxTree.ident(moduleName))); //uses_unit.source_context = uses_unit.name.source_context = new SyntaxTree.SourceContext(1, 1, 1, 1); - to_add = uses_unit; } - switch (Module.AddMethod) + + // добавление + if (module.AddMethod == CompilerOptions.StandardModuleAddMethod.RightToMain) { - case CompilerOptions.StandartModuleAddMethod.RightToMain: - UsesList.Add(to_add); - break; - case CompilerOptions.StandartModuleAddMethod.LeftToAll: - UsesList.Insert(0, to_add); - break; + usesList.Add(unitToAdd); } - + else if (module.AddMethod == CompilerOptions.StandardModuleAddMethod.LeftToAll) + { + usesList.Insert(0, unitToAdd); + } + } } - private Assembly PreloadReference(TreeRealization.compiler_directive reference) + private Assembly PreloadReference(compiler_directive reference) { var sc = GetSourceContext(reference); var fileName = GetReferenceFileName(reference.directive, sc, Path.GetDirectoryName(reference.source_file), true); return assemblyResolveScope.PreloadAssembly(fileName); } - private CompilationUnit CompileReference(PascalABCCompiler.TreeRealization.unit_node_list Units, TreeRealization.compiler_directive cd) + private CompilationUnit CompileReference(unit_node_list dlls, compiler_directive reference) { - var sc = GetSourceContext(cd); - string UnitName = null; + var sourceContext = GetSourceContext(reference); + string unitName; try { - UnitName = GetReferenceFileName(cd.directive, sc, Path.GetDirectoryName(cd.source_file), false); + unitName = GetReferenceFileName(reference.directive, sourceContext, Path.GetDirectoryName(reference.source_file), false); } - catch (AssemblyNotFound ex) + catch (AssemblyNotFound) { throw; } - //ToDo плохо, пока дебажил - тут постоянно ловились другие исключения, не связанные с неправильным знаками в пути к сборке - catch (Exception ex) + // ToDo плохо, пока дебажил - тут постоянно ловились другие исключения, не связанные с неправильным знаками в пути к сборке | + // EVA (проверить) + catch (Exception) { - throw new InvalidAssemblyPathError(CurrentCompilationUnit.SyntaxTree.file_name, sc); + throw new InvalidAssemblyPathError(currentCompilationUnit.SyntaxTree.file_name, sourceContext); } - CompilationUnit CurrentUnit = null; - if (UnitTable.Count == 0) throw new ProgramModuleExpected(UnitName, null); - if ((CurrentUnit = ReadDLL(UnitName, sc)) != null) + + CompilationUnit currentUnit = null; + if (UnitTable.Count == 0) throw new ProgramModuleExpected(unitName, null); + if ((currentUnit = ReadDLL(unitName, sourceContext)) != null) { - Units.AddElement(CurrentUnit.SemanticTree, null); - UnitTable[UnitName] = CurrentUnit; - return CurrentUnit; + dlls.AddElement(currentUnit.SemanticTree, null); + UnitTable[unitName] = currentUnit; + return currentUnit; } - else - //throw new DLLReadingError(UnitName); - throw new AssemblyReadingError(CurrentCompilationUnit.SyntaxTree.file_name, UnitName, sc); + else throw new AssemblyReadingError(currentCompilationUnit.SyntaxTree.file_name, unitName, sourceContext); } - - private SyntaxTree.SourceContext GetSourceContext(TreeRealization.compiler_directive cd) + + private SyntaxTree.SourceContext GetSourceContext(compiler_directive directive) { - var loc = cd.location; + var loc = directive.location; if (loc == null) return null; return new SyntaxTree.SourceContext(loc.begin_line_num, loc.begin_column_num, loc.end_line_num, loc.end_column_num, 0, 0); } - private bool HasIncludeNamespacesDirective(CompilationUnit Unit) + private bool HasIncludeNamespaceDirective(CompilationUnit unit) { - var directives = ConvertDirectives(Unit.SyntaxTree); - foreach (TreeRealization.compiler_directive cd in directives) + var directives = GetDirectivesAsSemanticNodes(unit.SyntaxTree.compiler_directives, unit.SyntaxTree.file_name); + + return directives.Any(directive => directive.name.ToLower() == TreeConverter.compiler_string_consts.include_namespace_directive); + } + + + private Dictionary PrepareUserNamespacesUsedInTheCurrentUnit(CompilationUnit compilationUnit) + { + var directives = GetDirectivesAsSemanticNodes(compilationUnit.SyntaxTree.compiler_directives, compilationUnit.SyntaxTree.file_name); + + List files = GetIncludedFilesFromDirectives(compilationUnit, directives); + + Dictionary namespaces = new Dictionary(StringComparer.OrdinalIgnoreCase); + + List namespaceModules = new List(); + + foreach (string file in files) { - if (cd.name.ToLower() == TreeConverter.compiler_string_consts.include_namespace_directive) + SyntaxTree.compilation_unit syntaxTree = GetNamespaceSyntaxTree(file); + + #region SEMANTIC CHECKS : PASCAL NAMESPACE + + SemanticCheckIsPascalNamespace(syntaxTree); + + #endregion + + SyntaxTree.unit_module unitModule = syntaxTree as SyntaxTree.unit_module; + + SyntaxTree.syntax_namespace_node namespaceNode = null; + + if (!namespaces.TryGetValue(unitModule.unit_name.idunit_name.name, out namespaceNode)) { - return true; + namespaceNode = new SyntaxTree.syntax_namespace_node(unitModule.unit_name.idunit_name.name); + namespaceNode.referenced_units = new unit_node_list(); + namespaces[unitModule.unit_name.idunit_name.name] = namespaceNode; + } + + AddDeclarationsAndReferencedUnitsToNamespaces(namespaceModules, file, unitModule, namespaceNode); + } + + // TODO: выделить в другой метод + + SyntaxTree.unit_module mainLibrary = compilationUnit.SyntaxTree as SyntaxTree.unit_module; + SyntaxTree.program_module main_program = compilationUnit.SyntaxTree as SyntaxTree.program_module; + + foreach (string s in namespaces.Keys) + { + if (mainLibrary != null) + mainLibrary.interface_part.interface_definitions.Insert(0, namespaces[s]); + else + main_program.program_block.defs.Insert(0, namespaces[s]); + } + + SyntaxTree.uses_list mainUsesList = GetMainUsesList(mainLibrary, main_program, namespaceModules); + + if (mainLibrary != null) + mainLibrary.interface_part.uses_modules = mainUsesList; + else + main_program.used_units = mainUsesList; + return namespaces; + } + + private static SyntaxTree.uses_list GetMainUsesList(SyntaxTree.unit_module mainLibrary, SyntaxTree.program_module main_program, List namespaceModules) + { + SyntaxTree.uses_list mainUsesList = null; + if (mainLibrary != null) + { + if (mainLibrary.interface_part.uses_modules != null) + mainUsesList = mainLibrary.interface_part.uses_modules; + } + else if (main_program.used_units != null) + mainUsesList = main_program.used_units; + if (mainUsesList == null) + mainUsesList = new SyntaxTree.uses_list(); + + HashSet set = new HashSet(); + foreach (SyntaxTree.unit_or_namespace name_space in namespaceModules) + { + string name = SyntaxTree.Utils.IdentListToString(name_space.name.idents, ".").ToLower(); + if (!set.Contains(name)) + { + mainUsesList.Add(name_space); + set.Add(name); } } - return false; - } - - private Dictionary IncludeNamespaces(CompilationUnit Unit) + return mainUsesList; + } + + private void AddDeclarationsAndReferencedUnitsToNamespaces(List namespace_modules, string file, + SyntaxTree.unit_module unitModule, SyntaxTree.syntax_namespace_node namespaceNode) + { + if (unitModule.interface_part.interface_definitions != null) + { + foreach (SyntaxTree.declaration decl in unitModule.interface_part.interface_definitions.defs) + { + namespaceNode.defs.Add(decl); + } + if (unitModule.interface_part.uses_modules != null) + { + CheckForDuplicatesInUsesSection(unitModule.interface_part.uses_modules.units); + foreach (SyntaxTree.unit_or_namespace name_space in unitModule.interface_part.uses_modules.units) + { + 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); + } + else + { + namespace_modules.Add(name_space); + } + } + } + } + } + + private void SemanticCheckIsPascalNamespace(SyntaxTree.compilation_unit unitSyntaxTree) + { + if (!(unitSyntaxTree is SyntaxTree.unit_module)) + throw new NamespaceModuleExpected(unitSyntaxTree.source_context); + + SyntaxTree.unit_module unitModule = unitSyntaxTree as SyntaxTree.unit_module; + + if (unitModule.unit_name.HeaderKeyword != SyntaxTree.UnitHeaderKeyword.Namespace) + throw new NamespaceModuleExpected(unitModule.unit_name.source_context); + if (unitModule.implementation_part != null) + throw new NamespaceModuleExpected(unitModule.implementation_part.source_context); + if (unitModule.finalization_part != null) + throw new NamespaceModuleExpected(unitModule.finalization_part.source_context); + if (unitModule.initialization_part != null && unitModule.initialization_part.list.Count > 0) + throw new NamespaceModuleExpected(unitModule.initialization_part.source_context); + } + + private static List GetIncludedFilesFromDirectives(CompilationUnit compilationUnit, List directives) { - if (HasIncludeNamespacesDirective(Unit) && Unit.SyntaxTree is SyntaxTree.unit_module && (Unit.SyntaxTree as SyntaxTree.unit_module).unit_name.HeaderKeyword != SyntaxTree.UnitHeaderKeyword.Library) - throw new IncludeNamespaceInUnit(CurrentCompilationUnit.SyntaxTree.file_name, CurrentCompilationUnit.SyntaxTree.source_context); - var directives = ConvertDirectives(Unit.SyntaxTree); - SyntaxTree.unit_module main_library = Unit.SyntaxTree as SyntaxTree.unit_module; - SyntaxTree.program_module main_program = Unit.SyntaxTree as SyntaxTree.program_module; List files = new List(); - foreach (TreeRealization.compiler_directive cd in directives) + foreach (compiler_directive cd in directives) { if (cd.name.ToLower() == TreeConverter.compiler_string_consts.include_namespace_directive) { @@ -2979,185 +3255,95 @@ namespace PascalABCCompiler if (directive == "*.pas" || directive.EndsWith(Path.DirectorySeparatorChar + "*.pas")) { - string dir = Path.Combine(Path.GetDirectoryName(Unit.SyntaxTree.file_name), directive.Replace(Path.DirectorySeparatorChar + "*.pas", "")); + string dir = Path.Combine(Path.GetDirectoryName(compilationUnit.SyntaxTree.file_name), directive.Replace(Path.DirectorySeparatorChar + "*.pas", "")); foreach (string file in Directory.EnumerateFiles(dir, "*.pas")) { if (!File.Exists(file)) throw new FileNotFound(file, cd.location); files.Add(file); } - + } else { - string file = Path.Combine(Path.GetDirectoryName(Unit.SyntaxTree.file_name), directive); + string file = Path.Combine(Path.GetDirectoryName(compilationUnit.SyntaxTree.file_name), directive); if (!File.Exists(file)) throw new FileNotFound(file, cd.location); files.Add(file); } - + } + } - - } - } - Dictionary namespaces = new Dictionary(StringComparer.OrdinalIgnoreCase); - List namespace_modules = new List(); - foreach (string file in files) - { - - SyntaxTree.compilation_unit tree = GetNamespaceSyntaxTree(file); - if (!(tree is SyntaxTree.unit_module)) - throw new NamespaceModuleExpected(tree.source_context); - SyntaxTree.unit_module unit = tree as SyntaxTree.unit_module; - if (unit.unit_name.HeaderKeyword != SyntaxTree.UnitHeaderKeyword.Namespace) - throw new NamespaceModuleExpected(unit.unit_name.source_context); - if (unit.implementation_part != null) - throw new NamespaceModuleExpected(unit.implementation_part.source_context); - if (unit.finalization_part != null) - throw new NamespaceModuleExpected(unit.finalization_part.source_context); - if (unit.initialization_part != null && unit.initialization_part.list.Count > 0) - throw new NamespaceModuleExpected(unit.initialization_part.source_context); - SyntaxTree.syntax_namespace_node ns = null; - if (!namespaces.TryGetValue(unit.unit_name.idunit_name.name, out ns)) - { - ns = new SyntaxTree.syntax_namespace_node(unit.unit_name.idunit_name.name); - ns.referenced_units = new TreeRealization.unit_node_list(); - namespaces[unit.unit_name.idunit_name.name] = ns; - } - if (unit.interface_part.interface_definitions != null) - { - foreach (SyntaxTree.declaration decl in unit.interface_part.interface_definitions.defs) - { - ns.defs.Add(decl); - } - if (unit.interface_part.uses_modules != null) - { - checkDuplicateUsesUnit(unit.interface_part.uses_modules.units); - foreach (SyntaxTree.unit_or_namespace name_space in unit.interface_part.uses_modules.units) - { - if (IsPossibleNamespace(name_space, false, Path.GetDirectoryName(file))) - { - ns.referenced_units.AddElement(new TreeRealization.namespace_unit_node(GetNamespace(name_space), get_location_from_treenode(name_space, tree.file_name)), null); - } - else - { - namespace_modules.Add(name_space); - } - } - } - } - } - foreach (string s in namespaces.Keys) - { - if (main_library != null) - main_library.interface_part.interface_definitions.Insert(0, namespaces[s]); - else - main_program.program_block.defs.Insert(0, namespaces[s]); - } - SyntaxTree.uses_list main_uses = null; - if (main_library != null) - { - if (main_library.interface_part.uses_modules != null) - main_uses = main_library.interface_part.uses_modules; - } - else if (main_program.used_units != null) - main_uses = main_program.used_units; - if (main_uses == null) - main_uses = new SyntaxTree.uses_list(); - Dictionary dict = new Dictionary(); - foreach (SyntaxTree.unit_or_namespace name_space in namespace_modules) - { - string name = SyntaxTree.Utils.IdentListToString(name_space.name.idents, ".").ToLower(); - if (!dict.ContainsKey(name)) - { - main_uses.Add(name_space); - dict.Add(name, name); - } - } - if (main_library != null) - main_library.interface_part.uses_modules = main_uses; - else - main_program.used_units = main_uses; - return namespaces; + return files; } - private SyntaxTree.compilation_unit GetNamespaceSyntaxTree(string FileName) + private void SemanticCheckNoIncludeDirectivesInPascalUnit(CompilationUnit compilationUnit) { - string SourceText = GetSourceFileText(FileName); - List DefinesList = new List(); - DefinesList.Add("PASCALABC"); // SSM 11/07/20 - if (!compilerOptions.Debug && !compilerOptions.ForDebugging) - DefinesList.Add("RELEASE"); + if (HasIncludeNamespaceDirective(compilationUnit) && compilationUnit.SyntaxTree is SyntaxTree.unit_module unitModule + && unitModule.unit_name.HeaderKeyword != SyntaxTree.UnitHeaderKeyword.Library) + { + throw new IncludeNamespaceInUnitError(currentCompilationUnit.SyntaxTree.file_name, currentCompilationUnit.SyntaxTree.source_context); + } + } + + private SyntaxTree.compilation_unit GetNamespaceSyntaxTree(string fileName) + { + string sourceText = GetSourceFileText(fileName); + List definesList = new List { "PASCALABC" }; // SSM 11/07/20 + + if (!CompilerOptions.Debug && !CompilerOptions.ForDebugging) + definesList.Add("RELEASE"); else - DefinesList.Add("DEBUG"); - DefinesList.AddRange(CompilerOptions.ForceDefines); - SyntaxTree.compilation_unit SyntaxTree = InternalParseText(FileName, SourceText, errorsList, warnings, DefinesList); + definesList.Add("DEBUG"); + + definesList.AddRange(CompilerOptions.ForceDefines); + + SyntaxTree.compilation_unit syntaxTree = InternalParseText(fileName, sourceText, errorsList, warnings, definesList); + if (errorsList.Count > 0) throw errorsList[0]; - SyntaxTree = syntaxTreeConvertersController.Convert(SyntaxTree) as SyntaxTree.compilation_unit; - return SyntaxTree; + + syntaxTree = syntaxTreeConvertersController.Convert(syntaxTree) as SyntaxTree.compilation_unit; + + return syntaxTree; } - public TreeRealization.unit_node_list GetReferences(CompilationUnit Unit) + public unit_node_list GetReferences(CompilationUnit compilationUnit) { - //TODO переделать, ConvertDirectives определена дважды и вызывается дважды! - TreeRealization.unit_node_list res = new TreeRealization.unit_node_list(); - List directives; - if (Unit.SemanticTree is TreeRealization.common_unit_node) - directives = (Unit.SemanticTree as TreeRealization.common_unit_node).compiler_directives; + unit_node_list dlls = new unit_node_list(); + List directives; + if (compilationUnit.SemanticTree is common_unit_node) + directives = (compilationUnit.SemanticTree as common_unit_node).compiler_directives; else - directives = ConvertDirectives(Unit.SyntaxTree); - foreach (TreeRealization.compiler_directive cd in directives) + directives = GetDirectivesAsSemanticNodes(compilationUnit.SyntaxTree.compiler_directives, compilationUnit.SyntaxTree.file_name); + + AddReferencesToSystemUnits(compilationUnit, directives); + + var referenceDirectives = new List(); + foreach (compiler_directive directive in directives) { - if (cd.name.ToLower() == TreeConverter.compiler_string_consts.compiler_directive_platformtarget && !string.IsNullOrEmpty(cd.directive) && cd.directive.IndexOf("dotnet5") != -1) - CompilerOptions.UseDllForSystemUnits = false; - } - if (CompilerOptions.UseDllForSystemUnits) - { - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\PABCRtl.dll", null, ".")); - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\mscorlib.dll", null, ".")); - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\System.dll", null, ".")); - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\System.Core.dll", null, ".")); - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\System.Numerics.dll", null, ".")); - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\System.Windows.Forms.dll", null, ".")); - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\System.Drawing.dll", null, ".")); - if (Unit.SyntaxTree is SyntaxTree.program_module && (Unit.SyntaxTree as SyntaxTree.program_module).used_units != null) - foreach (SyntaxTree.unit_or_namespace uui in (Unit.SyntaxTree as SyntaxTree.program_module).used_units.units) + if (directive.name.ToLower() == TreeConverter.compiler_string_consts.compiler_directive_reference) { - if (uui.name.ToString() == "Graph3D") - { - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\PresentationFramework.dll", null, ".")); - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\WindowsBase.dll", null, ".")); - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\PresentationCore.dll", null, ".")); - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\HelixToolkit.Wpf.dll", null, ".")); - directives.Add(new TreeRealization.compiler_directive("reference", "%GAC%\\HelixToolkit.dll", null, ".")); - } + #region SEMANTIC CHECKS : EMPTY REFERENCE + if (string.IsNullOrEmpty(directive.directive)) + throw new TreeConverter.SimpleSemanticError(directive.location, "EXPECTED_ASSEMBLY_NAME"); // Семантическая ошибка + #endregion + + referenceDirectives.Add(directive); } - } - var referenceDirectives = new List(); - foreach (TreeRealization.compiler_directive cd in directives) - { - if (cd.name.ToLower() == TreeConverter.compiler_string_consts.compiler_directive_reference) - { - if (string.IsNullOrEmpty(cd.directive)) - throw new TreeConverter.SimpleSemanticError(cd.location, "EXPECTED_ASSEMBLY_NAME"); - else - referenceDirectives.Add(cd); - } - } if (CompilerOptions.ProjectCompiled) { - foreach (ReferenceInfo ri in project.references) - { - referenceDirectives.Add(new TreeRealization.compiler_directive("reference", ri.full_assembly_name, null, project.MainFile)); - } + foreach (ReferenceInfo ri in project.references) + { + referenceDirectives.Add(new compiler_directive("reference", ri.full_assembly_name, null, project.MainFile)); + } } if (assemblyResolveScope == null) assemblyResolveScope = new NetHelper.AssemblyResolveScope(AppDomain.CurrentDomain); - + // It's important to preload all the referenced assemblies before starting the compilation. During the // compilation, we need to access types from every referenced assembly. An attempt to access them could fail // if a transitively dependent assembly is not loaded, yet. @@ -3168,89 +3354,133 @@ namespace PascalABCCompiler PreloadReference(reference); foreach (var reference in referenceDirectives) - CompileReference(res, reference); + CompileReference(dlls, reference); - return res; + return dlls; + } + + private void AddReferencesToSystemUnits(CompilationUnit compilationUnit, List directives) + { + foreach (compiler_directive cd in directives) + { + if (cd.name.ToLower() == TreeConverter.compiler_string_consts.compiler_directive_platformtarget + && !string.IsNullOrEmpty(cd.directive) && cd.directive.IndexOf("dotnet5") != -1) + { + CompilerOptions.UseDllForSystemUnits = false; + } + } + if (CompilerOptions.UseDllForSystemUnits) + { + directives.Add(new compiler_directive("reference", "%GAC%\\PABCRtl.dll", null, ".")); + directives.Add(new compiler_directive("reference", "%GAC%\\mscorlib.dll", null, ".")); + directives.Add(new compiler_directive("reference", "%GAC%\\System.dll", null, ".")); + directives.Add(new compiler_directive("reference", "%GAC%\\System.Core.dll", null, ".")); + directives.Add(new compiler_directive("reference", "%GAC%\\System.Numerics.dll", null, ".")); + directives.Add(new compiler_directive("reference", "%GAC%\\System.Windows.Forms.dll", null, ".")); + directives.Add(new compiler_directive("reference", "%GAC%\\System.Drawing.dll", null, ".")); + + if (compilationUnit.SyntaxTree is SyntaxTree.program_module && (compilationUnit.SyntaxTree as SyntaxTree.program_module).used_units != null) + { + foreach (SyntaxTree.unit_or_namespace usedUnit in (compilationUnit.SyntaxTree as SyntaxTree.program_module).used_units.units) + { + if (usedUnit.name.ToString() == "Graph3D") + { + directives.Add(new compiler_directive("reference", "%GAC%\\PresentationFramework.dll", null, ".")); + directives.Add(new compiler_directive("reference", "%GAC%\\WindowsBase.dll", null, ".")); + directives.Add(new compiler_directive("reference", "%GAC%\\PresentationCore.dll", null, ".")); + directives.Add(new compiler_directive("reference", "%GAC%\\HelixToolkit.Wpf.dll", null, ".")); + directives.Add(new compiler_directive("reference", "%GAC%\\HelixToolkit.dll", null, ".")); + + break; + } + } + } + } } NetHelper.AssemblyResolveScope assemblyResolveScope; - private bool IsPossibleNamespace(SyntaxTree.unit_or_namespace name_space, bool add_to_standard_modules, string curr_path) + private bool IsPossibleNetNamespaceOrStandardPasFile(SyntaxTree.unit_or_namespace name_space, bool addToStandardModules, string currentPath) { if (name_space is SyntaxTree.uses_unit_in) return false; + + // если это "что-то"."что-то"... (полный путь к пространству имен) if (name_space.name.idents.Count > 1) return true; - string src = FindSourceFileName(name_space.name.idents[0].name, curr_path, out _); - string pcu = FindPCUFileName(name_space.name.idents[0].name, curr_path, out _); - if (src == null && pcu == null) + + string sourceFileName = FindSourceFileName(name_space.name.idents[0].name, currentPath, out _); + string pcuFileName = FindPCUFileName(name_space.name.idents[0].name, currentPath, out _); + + // если нет исходников и pcu + if (sourceFileName == null && pcuFileName == null) return true; - if (CompilerOptions.UseDllForSystemUnits && src != null && string.Compare(Path.GetDirectoryName(src), Path.Combine(CompilerOptions.SystemDirectory, "Lib"), true) == 0 - && string.Compare(Path.GetFileNameWithoutExtension(src), "PT4", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(src), "CRT", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(src), "Arrays", true) != 0 - //&& string.Compare(Path.GetFileNameWithoutExtension(src), "FormsABC", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(src), "MPI", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(src), "LibForHaskell", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(src), "Collections", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(src), "Core", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(src), "Oberon00System", true) != 0) + + // если есть что-то одно + string fileName = sourceFileName ?? pcuFileName; + + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); + + // оставить только PT4 и протестировать + string[] standardFilesExcludedFromRTL = new string[] { "PT4", "CRT", "Arrays", "MPI", "Collections", "Core"}; + + bool includeInRTL = standardFilesExcludedFromRTL.All(file => !file.Equals(fileNameWithoutExtension, StringComparison.CurrentCultureIgnoreCase)); + + // если это исходный файл из папки Lib (стандартные паскалевские библиотеки) + if (CompilerOptions.UseDllForSystemUnits + && Path.GetDirectoryName(fileName).Equals(Path.Combine(CompilerOptions.SystemDirectory, "Lib"), StringComparison.CurrentCultureIgnoreCase) + && includeInRTL) { - string s = Path.GetFileNameWithoutExtension(src).ToLower(); - if (add_to_standard_modules && !StandarModules.Contains(s)) - StandarModules.Add(s); - return true; - } - if (CompilerOptions.UseDllForSystemUnits && pcu != null && string.Compare(Path.GetDirectoryName(pcu), Path.Combine(CompilerOptions.SystemDirectory, "Lib"), true) == 0 - && string.Compare(Path.GetFileNameWithoutExtension(pcu), "PT4", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(pcu), "CRT", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(pcu), "Arrays", true) != 0 - //&& string.Compare(Path.GetFileNameWithoutExtension(pcu), "FormsABC", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(pcu), "MPI", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(pcu), "LibForHaskell", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(pcu), "Collections", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(pcu), "Core", true) != 0 - && string.Compare(Path.GetFileNameWithoutExtension(pcu), "Oberon00System", true) != 0 - ) - { - string s = Path.GetFileNameWithoutExtension(pcu).ToLower(); - if (add_to_standard_modules && !StandarModules.Contains(s)) - StandarModules.Add(s); + string s = Path.GetFileNameWithoutExtension(fileName).ToLower(); + if (addToStandardModules && !StandardModules.Contains(s)) + StandardModules.Add(s); return true; } + return false; } - public TreeRealization.using_namespace GetNamespace(SyntaxTree.unit_or_namespace _name_space) + public using_namespace GetNamespace(SyntaxTree.unit_or_namespace _name_space) { - return new TreeRealization.using_namespace(SyntaxTree.Utils.IdentListToString(_name_space.name.idents, ".")); + return new using_namespace(SyntaxTree.Utils.IdentListToString(_name_space.name.idents, ".")); } - private TreeRealization.using_namespace GetNamespace(TreeRealization.using_namespace_list using_list, string full_namespace_name, SyntaxTree.unit_or_namespace _name_space, bool possible_is_unit, Dictionary pabc_namespaces) + /// + /// Формирует узел семантического дерева, соответствующий пространству имен (.NET или пользовательскому) + /// + /// + /// + private using_namespace GetNamespace(using_namespace_list usingList, string fullNamespaceName, SyntaxTree.unit_or_namespace name_space, bool mightBeUnit, Dictionary namespaces) { - if (!NetHelper.NetHelper.NamespaceExists(full_namespace_name) && !(pabc_namespaces != null && pabc_namespaces.ContainsKey(full_namespace_name))) + if (!NetHelper.NetHelper.NamespaceExists(fullNamespaceName) && (namespaces == null || !namespaces.ContainsKey(fullNamespaceName))) { - if (possible_is_unit) - if (!full_namespace_name.Contains(".")) - throw new UnitNotFound(CurrentCompilationUnit.SyntaxTree.file_name, full_namespace_name, _name_space.source_context); - throw new TreeConverter.NamespaceNotFound(full_namespace_name, get_location_from_treenode(_name_space.name, CurrentCompilationUnit.SyntaxTree.file_name)); + 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)); } - return new TreeRealization.using_namespace(full_namespace_name); + return new using_namespace(fullNamespaceName); } - public void AddNamespaces(TreeRealization.using_namespace_list using_list, List namespaces, bool possible_is_units, Dictionary pabc_namespaces) + public void AddNamespacesToUsingList(using_namespace_list usingList, List possibleNamespaces, bool mightContainUnits, Dictionary namespaces) { - foreach (SyntaxTree.unit_or_namespace ns in namespaces) - using_list.AddElement(GetNamespace(using_list, SyntaxTree.Utils.IdentListToString(ns.name.idents, "."), ns, possible_is_units, pabc_namespaces)); - } - - public void AddNamespaces(TreeRealization.using_namespace_list using_list, SyntaxTree.using_list ul) - { - if (ul != null) - AddNamespaces(using_list, ul.namespaces, false, null); + foreach (SyntaxTree.unit_or_namespace name_space in possibleNamespaces) + { + usingList.AddElement(GetNamespace(usingList, SyntaxTree.Utils.IdentListToString(name_space.name.idents, "."), + name_space, mightContainUnits, namespaces)); + } } - public SyntaxTree.using_list GetInterfaceSyntaxUsingList(SyntaxTree.compilation_unit cu) + public void AddNamespacesToUsingList(using_namespace_list using_list, SyntaxTree.using_list ul) + { + if (ul != null) + AddNamespacesToUsingList(using_list, ul.namespaces, false, null); + } + + /// + /// получение списка using - legacy code !!! + /// + public SyntaxTree.using_list GetInterfaceUsingList(SyntaxTree.compilation_unit cu) { if (cu is SyntaxTree.unit_module) return (cu as SyntaxTree.unit_module).interface_part.using_namespaces; @@ -3258,122 +3488,696 @@ namespace PascalABCCompiler return (cu as SyntaxTree.program_module).using_namespaces; return null; } - + + /// + /// получение списка using - legacy code !!! + /// private SyntaxTree.using_list GetImplementationSyntaxUsingList(SyntaxTree.compilation_unit cu) { if (cu is SyntaxTree.unit_module) - if ((cu as SyntaxTree.unit_module).implementation_part!=null) + if ((cu as SyntaxTree.unit_module).implementation_part != null) return (cu as SyntaxTree.unit_module).implementation_part.using_namespaces; return null; } + /// + /// получение списка using - legacy code !!! + /// public string GetSourceFileText(string FileName) { return (string)SourceFilesProvider(FileName, SourceFileOperation.GetText); } - public SyntaxTree.compilation_unit ParseText(string FileName, string Text, List ErrorList, List Warnings) + public SyntaxTree.compilation_unit ParseText(string fileName, string text, List errorList, List warnings) { Reset(); - OnChangeCompilerState(this, CompilerState.CompilationStarting, FileName); - SyntaxTree.compilation_unit cu = InternalParseText(FileName, Text, ErrorsList, Warnings); - OnChangeCompilerState(this, CompilerState.Ready, FileName); + OnChangeCompilerState(this, CompilerState.CompilationStarting, fileName); + SyntaxTree.compilation_unit cu = InternalParseText(fileName, text, ErrorsList, warnings); + OnChangeCompilerState(this, CompilerState.Ready, fileName); return cu; } - private SyntaxTree.compilation_unit InternalParseText(string FileName, string Text, List ErrorList, List Warnings, List DefinesList = null) + private SyntaxTree.compilation_unit InternalParseText(string fileName, string text, List errorList, List warnings, List definesList = null) { - OnChangeCompilerState(this, CompilerState.BeginParsingFile, FileName); - SyntaxTree.compilation_unit cu = ParsersController.GetCompilationUnit(FileName, Text, ErrorsList, Warnings, DefinesList); - OnChangeCompilerState(this, CompilerState.EndParsingFile, FileName); + OnChangeCompilerState(this, CompilerState.BeginParsingFile, fileName); + SyntaxTree.compilation_unit unitSyntaxTree = ParsersController.GetCompilationUnit(fileName, text, ErrorsList, warnings, definesList); + OnChangeCompilerState(this, CompilerState.EndParsingFile, fileName); //Вычисляем сколько строк скомпилировали - if (ErrorList.Count == 0 && cu != null && cu.source_context!=null) + if (errorList.Count == 0 && unitSyntaxTree != null && unitSyntaxTree.source_context != null) { - linesCompiled += (uint)(cu.source_context.end_position.line_num - cu.source_context.begin_position.line_num + 1); + linesCompiled += (uint)(unitSyntaxTree.source_context.end_position.line_num - unitSyntaxTree.source_context.begin_position.line_num + 1); // 500 - это наибольшая программа для начинающих. БОльшая программа - здоровье кода только по кнопке (чтобы не замедлять) if (linesCompiled <= 500) { // Это только для локального компилятора? var stat = new SyntaxVisitors.ABCStatisticsVisitor(); - stat.ProcessNode(cu); + stat.ProcessNode(unitSyntaxTree); pABCCodeHealth = stat.CalcHealth(out int neg, out int pos); } } - return cu; + return unitSyntaxTree; } - /*private bool check_for_library(List directives) + /// + /// Проверяет, является ли модуль dll по соответствующей директиве + /// + public static bool IsDll(SyntaxTree.compilation_unit unitSyntaxTree) { - foreach (compiler_directive cd in directives) - { - if (string.Compare(cd.name,"apptype")==0 && string.Compare(cd.directive,"dll")==0) - return true; - } - return false; - }*/ - - public static bool is_dll(SyntaxTree.compilation_unit cu) - { - foreach (SyntaxTree.compiler_directive cd in cu.compiler_directives) - if (string.Compare(cd.Name.text, "apptype", true) == 0 && string.Compare(cd.Directive.text, "dll", true) == 0) + foreach (SyntaxTree.compiler_directive directive in unitSyntaxTree.compiler_directives) + { + if (string.Equals(directive.Name.text, "apptype", StringComparison.CurrentCultureIgnoreCase) + && string.Equals(directive.Directive.text, "dll", StringComparison.CurrentCultureIgnoreCase)) + { return true; + } + } return false; } - public CompilationUnit CompileUnit(PascalABCCompiler.TreeRealization.unit_node_list Units, Dictionary DirectCompilationUnits, SyntaxTree.unit_or_namespace SyntaxUsesUnit, string prev_path) + /// + /// Проверяет, является ли модуль dll по соответствующей директиве и возвращает эту директиву выходным параметром + /// + public static bool IsDll(SyntaxTree.compilation_unit unitSyntaxTree, out SyntaxTree.compiler_directive dllDirective) { - string UnitFileName = GetUnitFileName(SyntaxUsesUnit, prev_path); - string UnitId = Path.ChangeExtension(UnitFileName, null); + foreach (SyntaxTree.compiler_directive directive in unitSyntaxTree.compiler_directives) + { + if (string.Equals(directive.Name.text, "apptype", StringComparison.CurrentCultureIgnoreCase) + && string.Equals(directive.Directive.text, "dll", StringComparison.CurrentCultureIgnoreCase)) + { + dllDirective = directive; + return true; + } + } + dllDirective = null; + return false; + } + + /// + /// Компилирует основную программу и все используемые ей юниты рекурсивно + /// + /// Вспомогательная переменная для заполнения CompilationUnit.interfaceUsedUnits и + /// CompilationUnit.implementationUsedUnits (здесь могут содержаться юниты и dll) + /// + /// Вспомогательная переменная для заполнения CompilationUnit.interfaceUsedDirectUnits и + /// CompilationUnit.implementationUsedDirectUnits + /// + /// Синтаксический узел текущего модуля (или пространства имен) + /// Директория родительского модуля + /// Скомпилированный юнит + public CompilationUnit CompileUnit(unit_node_list unitsFromUsesSection, Dictionary directUnitsFromUsesSection, SyntaxTree.unit_or_namespace currentUnitNode, string previousPath) + { + string unitFileName = GetUnitFileName(currentUnitNode, previousPath); + string unitId = Path.ChangeExtension(unitFileName, null); // Имя папки, в которой лежит текущий модуль // Используется для подключения модулей, $include и т.п. из модуля, подключённого с uses-in - var curr_path = Path.GetDirectoryName(UnitFileName); + var currentDirectory = Path.GetDirectoryName(unitFileName); - CompilationUnit CurrentUnit = UnitTable[UnitId]; - if (CurrentUnit != null && CurrentUnit.SemanticTree is PascalABCCompiler.TreeRealization.dot_net_unit_node - && SyntaxUsesUnit is PascalABCCompiler.SyntaxTree.uses_unit_in ui && ui.in_file != null) // значит, это пространство имен и секция in у него должна отсутствовать + // вернет null, если юнит еще не был инициализирован + CompilationUnit currentUnit = UnitTable[unitId]; + + Dictionary docs = null; + + if (currentUnit != null) + { + #region SEMANTIC CHECKS : USES IN SECTION LOGIC + + // ошибка - пространство имен не может содержать in секцию (для указания файла) + SemanticCheckUsesInIsNotNamespace(currentUnitNode, currentUnit); + #endregion + + // если модуль уже скомпилирован - возвращаем (возможно, только интерфейс модуля и тогда он докомпилируется в другом рекурсивном вызове) EVA + if (currentUnit.State != UnitState.BeginCompilation || currentUnit.SemanticTree != null) //TODO: ИЗБАВИТЬСЯ ОТ ВТОРОГО УСЛОВИЯ + { + AddCurrentUnitAndItsReferencesToUsesLists(unitsFromUsesSection, directUnitsFromUsesSection, + currentUnitNode, currentUnit, GetReferences(currentUnit)); + return currentUnit; + } + } + else + { + // если есть pcu - возврат EVA + if (UnitHasPCU(unitsFromUsesSection, directUnitsFromUsesSection, currentUnitNode, ref unitFileName, ref currentUnit)) + return currentUnit; + + // нет pcu и модуль не откомпилирован => новый модуль EVA + InitializeNewUnit(currentUnitNode, unitFileName, unitId, + ref currentUnit, ref docs); + } + + // формирование списков зависимостей текущего модуля (uses list, dll, пространства имен) + CreateDependencyListsForCurrentUnit(currentUnit, currentDirectory, out var interfaceUsesList, out var references, out var namespaces); + + #region INTERFACE PART + // комплируем зависимости из интерфейса EVA + if (interfaceUsesList != null) + { + CompileInterfaceDependencies(unitsFromUsesSection, directUnitsFromUsesSection, currentUnitNode, + unitFileName, currentDirectory, currentUnit, interfaceUsesList, references, namespaces, out bool shouldReturnCurUnit); + + if (shouldReturnCurUnit) + return currentUnit; + } + + currentCompilationUnit = currentUnit; + + currentUnit.InterfaceUsedUnits.AddRange(references); + + // Добавление пространств имен из uses list (могут быть разных видов) + AddNamespacesToUsingList(currentUnit.InterfaceUsingNamespaceList, currentUnit.possibleNamespaces, true, namespaces); + + #region USING LIST LEGACY CODE + // Добавление пространств имен NET из using list - устаревшее ключевое слово using + AddNamespacesToUsingList(currentUnit.InterfaceUsingNamespaceList, GetInterfaceUsingList(currentUnit.SyntaxTree)); + + #endregion + + //Console.WriteLine("Compiling Interface "+ unitFileName);//DEBUG + + // компилируем интерфейс текущего модуля EVA + CompileCurrentUnitInterface(unitFileName, currentUnit, docs); + + // интерфейс скомпилирован - переходим к секции реализации + currentUnit.State = UnitState.InterfaceCompiled; + + // заполнение списков uses семантического уровня + AddCurrentUnitAndItsReferencesToUsesLists(unitsFromUsesSection, directUnitsFromUsesSection, currentUnitNode, currentUnit, references); + #endregion + + #region IMPLEMENTATION PART + // берем модули из секции uses в реализации + List implementationUsesList = GetImplementationUsesSection(currentUnit.SyntaxTree); + + currentUnit.ImplementationUsedUnits.Clear(); + currentUnit.possibleNamespaces.Clear(); + + common_unit_node semanticTreeAsCommonNode = currentUnit.SemanticTree as common_unit_node; + + // Компиляция зависимостей в области реализации EVA + CompileImplementationDependencies(currentDirectory, currentUnit, implementationUsesList, namespaces, semanticTreeAsCommonNode, out bool shouldReturnCurrentUnit); + + if (shouldReturnCurrentUnit) + return currentUnit; + + // Console.WriteLine("Compiling Implementation "+ unitFileName);//DEBUG + + // компилируем реализацию текущего модуля EVA + CompileCurrentUnitImplementation(unitFileName, currentUnit, docs); + #endregion + + currentUnit.State = UnitState.Compiled; + + if (semanticTreeAsCommonNode != null) + { + if (!UnitsLogicallySortedList.Contains(currentUnit))//vnimanie zdes inogda pri silnoj zavisimosti modulej moduli popadajut neskolko raz + UnitsLogicallySortedList.Add(currentUnit); + } + + OnChangeCompilerState(this, CompilerState.EndCompileFile, unitFileName); + + //SavePCU(currentUnit, unitFileName); + currentUnit.UnitFileName = unitFileName; + + return currentUnit; + + + /*if(currentUnit.State!=UnitState.Compiled) + { + //Console.WriteLine("Compile Interface "+unitFileName);//DEBUG + currentUnit.SemanticTree=SyntaxTreeToSemanticTreeConverter.CompileInterface(currentUnit.SyntaxTree, + currentUnit.InterfaceUsedUnits,currentUnit.syntax_error); + currentUnit.State=UnitState.InterfaceCompiled; + implementationUsesList=GetSemanticImplementationUsesList(currentUnit.SyntaxTree); + if(implementationUsesList!=null) + for(int i=implementationUsesList.Count-1;i>=0;i--) + CompileUnit(currentUnit.ImplementationUsedUnits,implementationUsesList[i]); + //Console.WriteLine("Compile Implementation "+unitFileName);//DEBUG + if (currentUnit.SyntaxTree is SyntaxTree.unit_module) + { + SyntaxTreeToSemanticTreeConverter.CompileImplementation(currentUnit.SemanticTree, + currentUnit.SyntaxTree,currentUnit.ImplementationUsedUnits,currentUnit.syntax_error); + } + currentUnit.State=UnitState.Compiled; + unitsFromUsesSection.Add(currentUnit.SemanticTree); + SaveSemanticTreeToFile(currentUnit,unitFileName); + }*/ + } + + private void CreateDependencyListsForCurrentUnit(CompilationUnit currentUnit, string currentDirectory, out List interfaceUsesList, + out unit_node_list references, out Dictionary namespaces) + { + interfaceUsesList = GetInterfaceUsesSection(currentUnit.SyntaxTree); + + SetUseDLLForSystemUnits(currentDirectory, interfaceUsesList, interfaceUsesList.Count - 1 - currentUnit.InterfaceUsedUnits.Count); + + references = GetReferences(currentUnit); + + // TODO: закончить рефакторинг | Вопрос, как мы будем подключать про-ва имен из других языков EVA + namespaces = PrepareUserNamespacesUsedInTheCurrentUnit(currentUnit); + } + + private void AddCurrentUnitAndItsReferencesToUsesLists(unit_node_list unitsFromUsesSection, Dictionary directUnitsFromUsesSection, + SyntaxTree.unit_or_namespace currentUnitNode, CompilationUnit currentUnit, unit_node_list references) + { + if (unitsFromUsesSection != null) + { + if (unitsFromUsesSection.AddElement(currentUnit.SemanticTree, currentUnitNode.UsesPath())) + directUnitsFromUsesSection.Add(currentUnit.SemanticTree, currentUnit); + unitsFromUsesSection.AddRange(references); + } + } + + private void SemanticCheckUsesInIsNotNamespace(SyntaxTree.unit_or_namespace currentUnitNode, CompilationUnit currentUnit) + { + if (currentUnit.SemanticTree is dot_net_unit_node + && currentUnitNode is SyntaxTree.uses_unit_in ui && ui.in_file != null) // значит, это пространство имен и секция in у него должна отсутствовать { ErrorsList.Add(new NamespaceCannotHaveInSection(ui.in_file.source_context)); } + } - if (CurrentUnit != null) - if (CurrentUnit.State != UnitState.BeginCompilation || CurrentUnit.SemanticTree != null) //ИЗБАВИТЬСЯ ОТ ВТОРОГО УСЛОВИЯ + private void CompileCurrentUnitImplementation(string UnitFileName, CompilationUnit currentUnit, Dictionary docs) + { + if (currentUnit.SyntaxTree is SyntaxTree.unit_module) + { +#if DEBUG + if (InternalDebug.SemanticAnalysis) +#endif { - if (Units.AddElement(CurrentUnit.SemanticTree, SyntaxUsesUnit.UsesPath())) - DirectCompilationUnits.Add(CurrentUnit.SemanticTree, CurrentUnit); - Units.AddRange(GetReferences(CurrentUnit)); - return CurrentUnit; + OnChangeCompilerState(this, CompilerState.CompileImplementation, UnitFileName); + + TreeConverter.SemanticRules.SymbolTableCaseSensitive = currentUnit.CaseSensitive; + + SyntaxTreeToSemanticTreeConverter.CompileImplementation( + (common_unit_node)currentUnit.SemanticTree, + currentUnit.SyntaxTree, + buildImplementationUsesList(currentUnit), + ErrorsList, Warnings, + currentUnit.syntax_error, + BadNodesInSyntaxTree, + currentUnit.InterfaceUsingNamespaceList, + currentUnit.ImplementationUsingNamespaceList, + docs, + CompilerOptions.Debug, + CompilerOptions.ForDebugging, + CompilerOptions.ForIntellisense, + CompiledVariables + ); + CheckErrorsAndThrowTheFirstOne(); + } + } + } + + /// + /// Компилирует модули из секции uses текущего модуля реализации рекурсивно + /// + private void CompileImplementationDependencies(string currentPath, CompilationUnit currentUnit, List implementationUsesList, + Dictionary namespaces, common_unit_node commonUnitNode, out bool shouldReturnCurrentUnit) + + { + shouldReturnCurrentUnit = false; + + if (implementationUsesList != null) + { + for (int i = implementationUsesList.Count - 1; i >= 0; i--) + { + if (!IsPossibleNetNamespaceOrStandardPasFile(implementationUsesList[i], true, currentPath)) + { + CompilationUnit unitFromUsesSection = UnitTable[Path.ChangeExtension(GetUnitFileName(implementationUsesList[i], currentPath), null)]; + + // защита от попадания в бесконечный цикл (когда мы вернемся в тот юнит, в котором уже были (еще не скомпилированный), а затем спустимся по дереву зависимостей сюда же и т.д.) + // первая часть условия - если мы встречаем юнит не первый раз, вторая часть - если интерфейс еще не скомпилирован + if (unitFromUsesSection != null && unitFromUsesSection.State == UnitState.BeginCompilation) + { + UnitsToCompileDelayedList.Add(unitFromUsesSection); + shouldReturnCurrentUnit = true; // обрубаем компиляцию реализации в CompileUnit - не все интерфейсы еще откомпилированы !!! +#if DEBUG + // Console.WriteLine("[DEBUGINFO]Send compile to end " + Path.GetFileName(GetUnitFileName(implementationUsesList[i])));//DEBUG +#endif + } + else + { + CompileUnit(currentUnit.ImplementationUsedUnits, currentUnit.ImplementationUsedDirectUnits, implementationUsesList[i], currentPath); + } + } + else + { + currentUnit.ImplementationUsedUnits.AddElement(new TreeRealization.namespace_unit_node(GetNamespace(implementationUsesList[i])), null); + currentUnit.possibleNamespaces.Add(implementationUsesList[i]); + } } - if (CurrentUnit==null && Path.GetExtension(UnitFileName).ToLower() == CompilerOptions.CompiledUnitExtension) + } + + currentCompilationUnit = currentUnit; + + AddNamespacesToUsingList(currentUnit.ImplementationUsingNamespaceList, currentUnit.possibleNamespaces, true, namespaces); + + #region USING LIST LEGACY CODE + AddNamespacesToUsingList(currentUnit.ImplementationUsingNamespaceList, GetImplementationSyntaxUsingList(currentUnit.SyntaxTree)); + #endregion + + if (shouldReturnCurrentUnit) + { + // помещаем текущий модуль в список отложенной компиляции + UnitsToCompileDelayedList.Add(currentUnit); + + if (commonUnitNode != null) + { + if (!UnitsLogicallySortedList.Contains(currentUnit))//vnimanie zdes inogda pri silnoj zavisimosti modulej moduli popadajut neskolko raz + UnitsLogicallySortedList.Add(currentUnit); + } + //Console.WriteLine("Send compile to end "+unitFileName);//DEBUG + } + } + + private void CompileCurrentUnitInterface(string UnitFileName, CompilationUnit currentUnit, Dictionary docs) + { +#if DEBUG + if (InternalDebug.SemanticAnalysis) +#endif + { + if (currentUnit.State != UnitState.InterfaceCompiled) + { + OnChangeCompilerState(this, CompilerState.CompileInterface, UnitFileName); + TreeConverter.SemanticRules.SymbolTableCaseSensitive = currentUnit.CaseSensitive; + currentUnit.SemanticTree = SyntaxTreeToSemanticTreeConverter.CompileInterface( + currentUnit.SyntaxTree, + currentUnit.InterfaceUsedUnits, + ErrorsList, Warnings, + currentUnit.syntax_error, + BadNodesInSyntaxTree, + currentUnit.InterfaceUsingNamespaceList, + docs, + CompilerOptions.Debug, + CompilerOptions.ForDebugging, + CompilerOptions.ForIntellisense, + CompiledVariables + ); + CheckErrorsAndThrowTheFirstOne(); + } + } + } + + /// + /// Компилирует модули из секции uses интерфейса текущего модуля рекурсивно + /// + /// + private void CompileInterfaceDependencies(unit_node_list unitsFromUsesSection, Dictionary directUnitsFromUsesSection, SyntaxTree.unit_or_namespace currentUnitNode, + string unitFileName, string currentPath, CompilationUnit currentUnit, List interfaceUsesList, unit_node_list references, + Dictionary namespaces, out bool shouldReturnCurrentUnit) + { + shouldReturnCurrentUnit = false; + for (int i = interfaceUsesList.Count - 1 - currentUnit.InterfaceUsedUnits.Count; i >= 0; i--) // здесь откидываются модули с уже откомпилированными интерфейсами из секции uses (см. комментарий, обозначенный #1710) + { + if (IsPossibleNetNamespaceOrStandardPasFile(interfaceUsesList[i], true, currentPath) || namespaces.ContainsKey(interfaceUsesList[i].name.idents[0].name)) + { + currentUnit.InterfaceUsedUnits.AddElement(new namespace_unit_node(GetNamespace(interfaceUsesList[i])), null); + currentUnit.possibleNamespaces.Add(interfaceUsesList[i]); + } + else + { + #region SEMANTIC CHECKS : CYCLE DEPENDENCY OF INTERFACES + + SemanticCheckNoLoopDependenciesOfInterfaces(currentUnit, unitFileName, interfaceUsesList[i], currentPath); + + #endregion + + // компиляция модулей из интерфейса текущего модуля + CompileUnit(currentUnit.InterfaceUsedUnits, currentUnit.InterfaceUsedDirectUnits, interfaceUsesList[i], currentPath); + + // если текущий модуль был откомпилирован в другом рекурсивном вызове + if (currentUnit.State == UnitState.Compiled) + { + AddCurrentUnitAndItsReferencesToUsesLists(unitsFromUsesSection, directUnitsFromUsesSection, currentUnitNode, currentUnit, references); // #1710 добавление в список модулей из uses происходит только в конце компиляции интерфейса юнита или позже во всех случаях + shouldReturnCurrentUnit = true; + } + } + + } + } + + private void SemanticCheckNoLoopDependenciesOfInterfaces(CompilationUnit currentUnit, string unitFileName, SyntaxTree.unit_or_namespace usedUnitNode, string currentPath) + { + var usedUnitFileName = GetUnitFileName(usedUnitNode, currentPath); + var usedUnitId = Path.ChangeExtension(usedUnitFileName, null); + + // когда образуется цикл здесь сохранится инцидентная вершина графа (используемый юнит), которая тоже принадлежит циклу + currentUnit.currentUsedUnitId = usedUnitId; + + // если используемый юнит имеет не скомпилированный интерфейс, но был инициализирован + if (UnitTable[usedUnitId] != null && UnitTable[usedUnitId].State == UnitState.BeginCompilation) + { + string transitivelyUsedUnit = UnitTable[usedUnitId].currentUsedUnitId; + if (transitivelyUsedUnit != null) + { + // если сначала взяли pcu а потом решили его перекомпилировать, поэтому в таблице его нет + if (UnitTable[transitivelyUsedUnit] == null) + UnitTable[usedUnitId].currentUsedUnitId = transitivelyUsedUnit; // Вопрос EVA + // если "используемый используемого" (транзитивно зависимый) модуль находится в том же состоянии, что и просто используемый, то это означает циклическую зависимость + if (UnitTable[usedUnitId].currentUsedUnitId != null && UnitTable[UnitTable[usedUnitId].currentUsedUnitId].State == UnitState.BeginCompilation) + throw new CycleUnitReference(unitFileName, usedUnitNode); + } + } + } + + /// + /// Если в программе в секции uses есть не про-во имен и не стандартный модуль, то использование PABCRtl.dll отменяется + /// + private void SetUseDLLForSystemUnits(string currentDirectory, List usesList, int lastUnitIndex) + { + if (usesList != null && CompilerOptions.UseDllForSystemUnits) + { + for (int i = lastUnitIndex; i >= 0; i--) + { + if (!IsPossibleNetNamespaceOrStandardPasFile(usesList[i], false, currentDirectory)) + { + CompilerOptions.UseDllForSystemUnits = false; + break; + } + } + } + } + + /// + /// Получение исходного кода модуля, заполнение документации, + /// генерация синтаксического дерева, + /// обработка синтаксических ошибок + /// + private void InitializeNewUnit(SyntaxTree.unit_or_namespace currentUnitNode, string UnitFileName, string UnitId, ref CompilationUnit currentUnit, ref Dictionary docs) + { + currentUnit = new CompilationUnit(); + if (firstCompilationUnit == null) + firstCompilationUnit = currentUnit; + + OnChangeCompilerState(this, CompilerState.BeginCompileFile, UnitFileName); // начало компиляции модуля + + #region SYNTAX TREE CONSTRUCTING + // получение синтаксического дерева + string sourceText = GetSourceCode(currentUnitNode, UnitFileName, currentUnit); + + currentUnit.SyntaxTree = ConstructSyntaxTree(UnitFileName, currentUnit, sourceText); + #endregion + + if (currentUnit.SyntaxTree is SyntaxTree.unit_module) + CompilerOptions.UseDllForSystemUnits = false; + + if (errorsList.Count == 0) // SSM 2/05/16 - для преобразования синтаксических деревьев извне (синтаксический сахар) + { + currentUnit.SyntaxTree = syntaxTreeConvertersController.Convert(currentUnit.SyntaxTree) as SyntaxTree.compilation_unit; + } + + // генерация документации к узлам синтаксического дерева EVA + docs = GenUnitDocumentation(currentUnit, sourceText); + + #region SEMANTIC CHECKS : DIRECTIVES AND OUTPUT FILE TYPE + + // SSM 21/05/20 Проверка, что мы не записали apptype dll в небиблиотеку + bool isDll = IsDll(currentUnit.SyntaxTree, out var dllDirective); + SemanticCheckDLLDirectiveOnlyForLibraries(currentUnit.SyntaxTree, isDll, dllDirective); + + // ошибка - компилируем вторую основную программу или вторую dll вместо юнита + SemanticCheckCurrentUnitMustBePascalUnit(UnitFileName, currentUnit, isDll); + + // ошибка директива include в паскалевском юните + SemanticCheckNoIncludeDirectivesInPascalUnit(currentUnit); + #endregion + + // Set output file type for dll + if (isDll) + CompilerOptions.OutputFileType = CompilerOptions.OutputType.ClassLibrary; // Вопрос, нужно ли это здесь, если это есть в Compile в конце EVA + + if (ParsersController.LastParser != null) + currentUnit.CaseSensitive = ParsersController.LastParser.CaseSensitive; + + currentCompilationUnit = currentUnit; + + currentUnit.SyntaxUnitName = currentUnitNode; + + // сопоставление нодам ошибок EVA + MatchErrorsToBadNodes(currentUnit); + + CheckErrorsAndThrowTheFirstOne(); + + UnitTable[UnitId] = currentUnit; + + // здесь добавляем стандартные модули в секцию uses интерфейса +#if DEBUG + if (InternalDebug.AddStandartUnits) +#endif + AddStandardUnitsToInterfaceUsesSection(currentUnit.SyntaxTree); + + + currentCompilationUnit = currentUnit; + + currentUnit.possibleNamespaces.Clear(); + } + + private void SemanticCheckNamespacesOnlyInProjects(CompilationUnit currentUnit) + { + // legacy + if (currentUnit.SyntaxTree is SyntaxTree.unit_module) + { + // Проверка на явный namespace (паскалевский) + if ((currentUnit.SyntaxTree as SyntaxTree.unit_module).unit_name.HeaderKeyword == SyntaxTree.UnitHeaderKeyword.Namespace) + throw new NamespacesCanBeCompiledOnlyInProjects(currentUnit.SyntaxTree.source_context); + } + } + + // Синтактико-семантическая ошибка - проверка, что compilationUnit является модулем, + // а не основной программой и не dll EVA + private void SemanticCheckCurrentUnitMustBePascalUnit(string UnitFileName, CompilationUnit currentUnit, bool isDll) + { + if (UnitTable.Count > 0) // если это не главный модуль (программа в unittable всегда идет первой) + { + if (currentUnit.SyntaxTree is SyntaxTree.program_module) + throw new UnitModuleExpected(UnitFileName, currentUnit.SyntaxTree.source_context.LeftSourceContext); + else if (isDll) + throw new UnitModuleExpectedLibraryFound(UnitFileName, currentUnit.SyntaxTree.source_context.LeftSourceContext); + } + } + + private void MatchErrorsToBadNodes(CompilationUnit currentUnit) + { + if (errorsList.Count > 0) + { + currentUnit.syntax_error = errorsList[0] as SyntaxError; + foreach (Error er in errorsList) + if (er is SyntaxError && (er as SyntaxError).bad_node != null) + BadNodesInSyntaxTree[(er as SyntaxError).bad_node] = er; + } + } + + + /// + /// Проверка, что директива dll только в Library - требует передачи директивы dll + /// + private void SemanticCheckDLLDirectiveOnlyForLibraries(SyntaxTree.compilation_unit unitSyntaxTree, bool isDll, SyntaxTree.compiler_directive dllDirective) + { + // Если Library и apptype dll не указано, то никакой ошибки нет EVA + if (unitSyntaxTree != null && isDll) + { + if (!(unitSyntaxTree is SyntaxTree.unit_module) || + (unitSyntaxTree is SyntaxTree.unit_module unitNode && unitNode.unit_name.HeaderKeyword != SyntaxTree.UnitHeaderKeyword.Library)) + { + // если в директивах появилось {$apptype dll}, но это не Library + ErrorsList.Add(new AppTypeDllIsAllowedOnlyForLibraries(unitSyntaxTree.file_name, dllDirective.source_context)); + } + } + } + + private SyntaxTree.compilation_unit ConstructSyntaxTree(string unitFileName, CompilationUnit currentUnit, string sourceText) + { + List DefinesList = new List { "PASCALABC" }; + if (!CompilerOptions.Debug && !CompilerOptions.ForDebugging) + DefinesList.Add("RELEASE"); + else + DefinesList.Add("DEBUG"); + DefinesList.AddRange(CompilerOptions.ForceDefines); + + SyntaxTree.compilation_unit syntaxTree; + + if (CompilerOptions.UnitSyntaxTree != null) + { + syntaxTree = CompilerOptions.UnitSyntaxTree; + CompilerOptions.UnitSyntaxTree = null; + } + // синтаксический анализ + else + syntaxTree = InternalParseText(unitFileName, sourceText, errorsList, warnings, DefinesList); + + // проверка, что пространства имен только в проектах + SemanticCheckNamespacesOnlyInProjects(currentUnit); + + return syntaxTree; + } + + private string GetSourceCode(SyntaxTree.unit_or_namespace currentUnitNode, string UnitFileName, CompilationUnit currentUnit) + { + string SourceText = null; + if (CompilerOptions.UnitSyntaxTree == null) + { + SourceText = GetSourceFileText(UnitFileName); + if (SourceText == null) + { + if (currentUnit == firstCompilationUnit) + throw new SourceFileNotFound(UnitFileName); + else + throw new UnitNotFound(currentCompilationUnit.SyntaxTree.file_name, UnitFileName, currentUnitNode.source_context); + } + } + return SourceText; + } + + private Dictionary GenUnitDocumentation(CompilationUnit currentUnit, string SourceText) + { + Dictionary docs = null; + + if (errorsList.Count == 0 && IsDocumentationNeeded(currentUnit.SyntaxTree)) + { + if (SourceText != null) + { + docs = AddDocumentationToNodes(currentUnit.SyntaxTree, SourceText); + if (docs != null) + currentUnit.Documented = true; + } + } + return docs; + } + + private bool UnitHasPCU(unit_node_list unitsFromUsesSection, Dictionary directUnitsFromUsesSection, SyntaxTree.unit_or_namespace currentUnitNode, ref string UnitFileName, ref CompilationUnit currentUnit) + { + if (Path.GetExtension(UnitFileName).ToLower() == CompilerOptions.CompiledUnitExtension) + { if (File.Exists(UnitFileName)) { if (UnitTable.Count == 0) throw new ProgramModuleExpected(UnitFileName, null); try { - if ((CurrentUnit = ReadPCU(UnitFileName)) != null) + if ((currentUnit = ReadPCU(UnitFileName)) != null) { - if (Units.AddElement(CurrentUnit.SemanticTree, SyntaxUsesUnit.UsesPath())) - DirectCompilationUnits.Add(CurrentUnit.SemanticTree, CurrentUnit); - Units.AddRange(GetReferences(CurrentUnit)); - UnitTable[UnitId] = CurrentUnit; - return CurrentUnit; + AddCurrentUnitAndItsReferencesToUsesLists(unitsFromUsesSection, directUnitsFromUsesSection, + currentUnitNode, currentUnit, GetReferences(currentUnit)); + + UnitTable[Path.ChangeExtension(UnitFileName, null)] = currentUnit; + return true; } } catch (InvalidPCUFule) { //Перекомпилируем.... } + // Так надо (для дебага) catch (Error) { throw; } catch (Exception e) { - OnChangeCompilerState(this, CompilerState.PCUReadingError, UnitFileName); + OnChangeCompilerState(this, CompilerState.PCUReadingError, UnitFileName); // ошибка чтения PCU #if DEBUG if (!InternalDebug.SkipPCUErrors) - throw new Errors.CompilerInternalError("PCUReader", e); + throw new CompilerInternalError("PCUReader", e); #endif } string SourceFileName = FindSourceFileName(Path.ChangeExtension(UnitFileName, null), null, out _); @@ -3382,361 +4186,48 @@ namespace PascalABCCompiler else UnitFileName = SourceFileName; } - string SourceText = null; - Dictionary docs = null; - if (CurrentUnit == null) - { - - CurrentUnit = new CompilationUnit(); - if (FirstCompilationUnit == null) - FirstCompilationUnit = CurrentUnit; - OnChangeCompilerState(this, CompilerState.BeginCompileFile, UnitFileName); - if (compilerOptions.UnitSyntaxTree == null) - { - SourceText = GetSourceFileText(UnitFileName); - if (SourceText == null) - if (CurrentUnit == FirstCompilationUnit) - throw new SourceFileNotFound(UnitFileName); - else - throw new UnitNotFound(CurrentCompilationUnit.SyntaxTree.file_name, UnitFileName, SyntaxUsesUnit.source_context); - } - - List DefinesList = new List(); - DefinesList.Add("PASCALABC"); - if (!compilerOptions.Debug && !compilerOptions.ForDebugging) - DefinesList.Add("RELEASE"); - else - DefinesList.Add("DEBUG"); - DefinesList.AddRange(CompilerOptions.ForceDefines); - if (compilerOptions.UnitSyntaxTree != null) - { - CurrentUnit.SyntaxTree = compilerOptions.UnitSyntaxTree; - compilerOptions.UnitSyntaxTree = null; - } - else - CurrentUnit.SyntaxTree = InternalParseText(UnitFileName, SourceText, errorsList, warnings, DefinesList); - - if (errorsList.Count == 0) // SSM 2/05/16 - для преобразования синтаксических деревьев извне - { - CurrentUnit.SyntaxTree = syntaxTreeConvertersController.Convert(CurrentUnit.SyntaxTree) as SyntaxTree.compilation_unit; - - } - - if (errorsList.Count == 0 && need_gen_doc(CurrentUnit.SyntaxTree)) - { - if (SourceText != null) - { - docs = AddDocumentationToNodes(CurrentUnit.SyntaxTree, SourceText); - if (docs != null) - CurrentUnit.Documented = true; - } - } - if (CurrentUnit.SyntaxTree is SyntaxTree.unit_module) - { - if ((CurrentUnit.SyntaxTree as SyntaxTree.unit_module).unit_name.HeaderKeyword == SyntaxTree.UnitHeaderKeyword.Namespace) - throw new NamespacesCanBeCompiledOnlyInProjects(CurrentUnit.SyntaxTree.source_context); - compilerOptions.UseDllForSystemUnits = false; - } - - // SSM 21/05/20 Проверка, что мы не записали apptype dll в небиблиотеку - - var ccu = CurrentUnit.SyntaxTree; - // !!!!!!!!!!!!!!!!!!!!!! - if (ccu != null) // SSM 06.06.22 - здесь была ошибка - ccu может быть null и тогда исключение!!! Добавил if - foreach (SyntaxTree.compiler_directive cd in ccu.compiler_directives) - if (string.Compare(cd.Name.text, "apptype", true) == 0 && string.Compare(cd.Directive.text, "dll", true) == 0) - { - if (!(ccu is SyntaxTree.unit_module) || - (ccu is SyntaxTree.unit_module um && um.unit_name.HeaderKeyword != SyntaxTree.UnitHeaderKeyword.Library)) - { - ErrorsList.Add(new AppTypeDllIsAllowedOnlyForLibraries(ccu.file_name, cd.source_context)); - break; - } - } - // - - if (is_dll(CurrentUnit.SyntaxTree)) - compilerOptions.OutputFileType = PascalABCCompiler.CompilerOptions.OutputType.ClassLibrary; - if (ParsersController.LastParser != null) - CurrentUnit.CaseSensitive = ParsersController.LastParser.CaseSensitive; - CurrentCompilationUnit = CurrentUnit; - - CurrentUnit.SyntaxUnitName = SyntaxUsesUnit; - - //BadNodesInSyntaxTree.Clear(); - if (errorsList.Count > 0) - { - CurrentUnit.syntax_error = errorsList[0] as PascalABCCompiler.Errors.SyntaxError; - foreach (Errors.Error er in errorsList) - if (er is SyntaxError && (er as SyntaxError).bad_node != null) - BadNodesInSyntaxTree[(er as SyntaxError).bad_node] = er; - } - - //if (CurrentUnit.SyntaxTree == null) - if (errorsList.Count > 0) - { - //if (errorsList.Count == 0) - // throw new Errors.SyntaxError("Internal parser error: Parser not create syntax tree", UnitName,null,null); - throw errorsList[0]; - } - - UnitTable[UnitId] = CurrentUnit; - - if (UnitTable.Count > 1)//если это не главный модуль - if (CurrentUnit.SyntaxTree is SyntaxTree.program_module) - throw new UnitModuleExpected(UnitFileName, CurrentUnit.SyntaxTree.source_context.LeftSourceContext); - else if (is_dll(CurrentUnit.SyntaxTree)) - throw new UnitModuleExpectedLibraryFound(UnitFileName, CurrentUnit.SyntaxTree.source_context.LeftSourceContext); - //здесь в начало uses добавляем стандартные модули -#if DEBUG - if (InternalDebug.AddStandartUnits) -#endif - AddStandartUnitsToUsesSection(CurrentUnit.SyntaxTree); - - } - CurrentSyntaxUnit = SyntaxUsesUnit; - CurrentCompilationUnit = CurrentUnit; - - CurrentUnit.PossibleNamespaces.Clear(); - - //TODO переделать, слишком сложно, некоторый код дублируется - - - System.Collections.Generic.List SyntaxUsesList; - SyntaxUsesList = GetSyntaxInterfaceUsesList(CurrentUnit.SyntaxTree); - - if (SyntaxUsesList != null) - { - for (int i = SyntaxUsesList.Count - 1 - CurrentUnit.InterfaceUsedUnits.Count; i >= 0; i--) - { - if (!IsPossibleNamespace(SyntaxUsesList[i], false, curr_path)) - { - compilerOptions.UseDllForSystemUnits = false; - break; - } - } - } - TreeRealization.unit_node_list References = GetReferences(CurrentUnit); - var namespaces = IncludeNamespaces(CurrentUnit); - if (SyntaxUsesList != null) - { - - for (int i = SyntaxUsesList.Count - 1 - CurrentUnit.InterfaceUsedUnits.Count; i >= 0; i--) - { - if (IsPossibleNamespace(SyntaxUsesList[i], true, curr_path) || namespaces.ContainsKey(SyntaxUsesList[i].name.idents[0].name)) - { - CurrentUnit.InterfaceUsedUnits.AddElement(new TreeRealization.namespace_unit_node(GetNamespace(SyntaxUsesList[i])), null); - CurrentUnit.PossibleNamespaces.Add(SyntaxUsesList[i]); - } - else - { - var CurrentSyntaxUnitFileName = GetUnitFileName(SyntaxUsesList[i], curr_path); - var CurrentSyntaxUnitId = Path.ChangeExtension(CurrentSyntaxUnitFileName, null); - CurrentUnit.CurrentUsesUnitId = CurrentSyntaxUnitId; - - if (UnitTable[CurrentSyntaxUnitId] != null) - if (UnitTable[CurrentSyntaxUnitId].State == UnitState.BeginCompilation) - { - string CurrentSyntaxUnit_CurrentUsesUnitId = UnitTable[CurrentSyntaxUnitId].CurrentUsesUnitId; - if (CurrentSyntaxUnit_CurrentUsesUnitId != null) - { - //если сначало взяли pcu а потом решили его перекомпилировать, поэтому в таблице его нет - if (UnitTable[CurrentSyntaxUnit_CurrentUsesUnitId] == null) - UnitTable[CurrentSyntaxUnitId].CurrentUsesUnitId = CurrentSyntaxUnit_CurrentUsesUnitId; - //далее финальная поверка на зацикливание - if (UnitTable[CurrentSyntaxUnitId].CurrentUsesUnitId != null && UnitTable[UnitTable[CurrentSyntaxUnitId].CurrentUsesUnitId].State == UnitState.BeginCompilation) - throw new CycleUnitReference(UnitFileName, SyntaxUsesList[i]); - } - } - CompileUnit(CurrentUnit.InterfaceUsedUnits, CurrentUnit.DirectInterfaceCompilationUnits, SyntaxUsesList[i], curr_path); - if (CurrentUnit.State == UnitState.Compiled) - { - if (Units.AddElement(CurrentUnit.SemanticTree, SyntaxUsesUnit.UsesPath())) - DirectCompilationUnits.Add(CurrentUnit.SemanticTree, CurrentUnit); - Units.AddRange(References); - return CurrentUnit; - } - } - - } } - CurrentCompilationUnit = CurrentUnit; - - CurrentUnit.InterfaceUsedUnits.AddRange(References); - - AddNamespaces(CurrentUnit.InterfaceUsingNamespaceList, CurrentUnit.PossibleNamespaces, true, namespaces); - AddNamespaces(CurrentUnit.InterfaceUsingNamespaceList, GetInterfaceSyntaxUsingList(CurrentUnit.SyntaxTree)); - - //Console.WriteLine("Compile Interface "+UnitName);//DEBUG -#if DEBUG - if (InternalDebug.SemanticAnalysis) -#endif - { - if (CurrentUnit.State != UnitState.InterfaceCompiled) - { - OnChangeCompilerState(this, CompilerState.CompileInterface, UnitFileName); - PascalABCCompiler.TreeConverter.SemanticRules.SymbolTableCaseSensitive = CurrentUnit.CaseSensitive; - CurrentUnit.SemanticTree = SyntaxTreeToSemanticTreeConverter.CompileInterface( - CurrentUnit.SyntaxTree, - CurrentUnit.InterfaceUsedUnits, - ErrorsList, Warnings, - CurrentUnit.syntax_error, - BadNodesInSyntaxTree, - CurrentUnit.InterfaceUsingNamespaceList, - docs, - CompilerOptions.Debug, - CompilerOptions.ForDebugging, - CompilerOptions.ForIntellisense, - CompiledVariables - ); - CheckErrors(); - } - } - TreeRealization.common_unit_node cun = CurrentUnit.SemanticTree as TreeRealization.common_unit_node; - /*if (cun != null) - { - if (!UnitsSortedList.Contains(CurrentUnit))//vnimanie zdes inogda pri silnoj zavisimosti modulej moduli popadajut neskolko raz - UnitsSortedList.Add(CurrentUnit); - }*/ - CurrentUnit.State = UnitState.InterfaceCompiled; - if (Units != null) - { - if (Units.AddElement(CurrentUnit.SemanticTree, SyntaxUsesUnit.UsesPath())) - DirectCompilationUnits.Add(CurrentUnit.SemanticTree, CurrentUnit); - Units.AddRange(References); - } - SyntaxUsesList = GetSyntaxImplementationUsesList(CurrentUnit.SyntaxTree); - CompilationUnit cu = null; bool interfcompile = true; - CurrentUnit.ImplementationUsedUnits.clear(); - CurrentUnit.PossibleNamespaces.Clear(); - if (SyntaxUsesList != null) - { - for (int i = SyntaxUsesList.Count - 1; i >= 0; i--) - if (!IsPossibleNamespace(SyntaxUsesList[i], true, curr_path)) - { - cu = UnitTable[Path.ChangeExtension(GetUnitFileName(SyntaxUsesList[i], curr_path), null)]; - if (cu != null && cu.State == UnitState.BeginCompilation) - { - UnitsToCompile.Add(cu); - interfcompile = false; -#if DEBUG - // Console.WriteLine("[DEBUGINFO]Send compile to end " + Path.GetFileName(GetUnitFileName(SyntaxUsesList[i])));//DEBUG -#endif - } - else - { - CompileUnit(CurrentUnit.ImplementationUsedUnits, CurrentUnit.DirectImplementationCompilationUnits, SyntaxUsesList[i], curr_path); - } - } - else - { - CurrentUnit.ImplementationUsedUnits.AddElement(new TreeRealization.namespace_unit_node(GetNamespace(SyntaxUsesList[i])), null); - CurrentUnit.PossibleNamespaces.Add(SyntaxUsesList[i]); - } - } - - CurrentCompilationUnit = CurrentUnit; - - AddNamespaces(CurrentUnit.ImplementationUsingNamespaceList, CurrentUnit.PossibleNamespaces, true, namespaces); - AddNamespaces(CurrentUnit.ImplementationUsingNamespaceList, GetImplementationSyntaxUsingList(CurrentUnit.SyntaxTree)); - - if (!interfcompile) - { - UnitsToCompile.Add(CurrentUnit); - if (cun != null) - { - if (!UnitsSortedList.Contains(CurrentUnit))//vnimanie zdes inogda pri silnoj zavisimosti modulej moduli popadajut neskolko raz - UnitsSortedList.Add(CurrentUnit); - } - //Console.WriteLine("Send compile to end "+UnitName);//DEBUG - return CurrentUnit; - } - - //Console.WriteLine("Compile Implementation "+UnitName);//DEBUG - if (CurrentUnit.SyntaxTree is SyntaxTree.unit_module) - { -#if DEBUG - if (InternalDebug.SemanticAnalysis) -#endif - { - OnChangeCompilerState(this, CompilerState.CompileImplementation, UnitFileName); - PascalABCCompiler.TreeConverter.SemanticRules.SymbolTableCaseSensitive = CurrentUnit.CaseSensitive; - SyntaxTreeToSemanticTreeConverter.CompileImplementation( - (PascalABCCompiler.TreeRealization.common_unit_node)CurrentUnit.SemanticTree, - CurrentUnit.SyntaxTree, - buildImplementationUsesList(CurrentUnit), - ErrorsList, Warnings, - CurrentUnit.syntax_error, - BadNodesInSyntaxTree, - CurrentUnit.InterfaceUsingNamespaceList, - CurrentUnit.ImplementationUsingNamespaceList, - docs, - CompilerOptions.Debug, - CompilerOptions.ForDebugging, - CompilerOptions.ForIntellisense, - CompiledVariables - ); - CheckErrors(); - } - } - CurrentUnit.State = UnitState.Compiled; - if (cun != null) - { - if (!UnitsSortedList.Contains(CurrentUnit))//vnimanie zdes inogda pri silnoj zavisimosti modulej moduli popadajut neskolko raz - UnitsSortedList.Add(CurrentUnit); - } - OnChangeCompilerState(this, CompilerState.EndCompileFile, UnitFileName); - //SavePCU(CurrentUnit, UnitName); - CurrentUnit.UnitFileName = UnitFileName; - return CurrentUnit; - /*if(CurrentUnit.State!=UnitState.Compiled) - { - //Console.WriteLine("Compile Interface "+UnitName);//DEBUG - CurrentUnit.SemanticTree=SyntaxTreeToSemanticTreeConverter.CompileInterface(CurrentUnit.SyntaxTree, - CurrentUnit.InterfaceUsedUnits,CurrentUnit.syntax_error); - CurrentUnit.State=UnitState.InterfaceCompiled; - SyntaxUsesList=GetSemanticImplementationUsesList(CurrentUnit.SyntaxTree); - if(SyntaxUsesList!=null) - for(int i=SyntaxUsesList.Count-1;i>=0;i--) - CompileUnit(CurrentUnit.ImplementationUsedUnits,SyntaxUsesList[i]); - //Console.WriteLine("Compile Implementation "+UnitName);//DEBUG - if (CurrentUnit.SyntaxTree is SyntaxTree.unit_module) - { - SyntaxTreeToSemanticTreeConverter.CompileImplementation(CurrentUnit.SemanticTree, - CurrentUnit.SyntaxTree,CurrentUnit.ImplementationUsedUnits,CurrentUnit.syntax_error); - } - CurrentUnit.State=UnitState.Compiled; - Units.Add(CurrentUnit.SemanticTree); - SaveSemanticTreeToFile(CurrentUnit,UnitName); - }*/ + return false; } - - private Dictionary AddDocumentationToNodes(SyntaxTree.compilation_unit cu, string Text) + + private Dictionary AddDocumentationToNodes(SyntaxTree.compilation_unit unitSyntaxTree, string text) { - List errors = new List(); - List warnings = new List(); - string doctagsParserExtension = Path.GetExtension(cu.file_name)+"dt"+PascalABCCompiler.Parsers.Controller.HideParserExtensionPostfixChar; - PascalABCCompiler.SyntaxTree.documentation_comment_list dt = ParsersController.Compile(System.IO.Path.ChangeExtension(cu.file_name, doctagsParserExtension), Text, errors, warnings, PascalABCCompiler.Parsers.ParseMode.Normal) as PascalABCCompiler.SyntaxTree.documentation_comment_list; - if (errors.Count > 0) return null; - PascalABCCompiler.DocumentationConstructor docconst = new PascalABCCompiler.DocumentationConstructor(); - return docconst.Construct(cu, dt); + List errors = new List(); + + string doctagsParserExtension = Path.GetExtension(unitSyntaxTree.file_name) + "dt" + Parsers.Controller.HideParserExtensionPostfixChar; + + SyntaxTree.documentation_comment_list docCommentList = ParsersController.Compile(Path.ChangeExtension(unitSyntaxTree.file_name, doctagsParserExtension), + text, errors, new List(), Parsers.ParseMode.Normal) as SyntaxTree.documentation_comment_list; + + if (errors.Count > 0) return null; + + return new DocumentationConstructor().Construct(unitSyntaxTree, docCommentList); } - - private bool need_gen_doc(SyntaxTree.compilation_unit cu) + + private bool IsDocumentationNeeded(SyntaxTree.compilation_unit unitSyntaxTree) { if (project != null && project.generate_xml_doc) return true; - if (cu == null) - return false; - if (cu.file_name != null && internalDebug.DocumentedUnits.Contains(cu.file_name.ToLower())) - return true; - foreach (SyntaxTree.compiler_directive cd in cu.compiler_directives) - if (string.Compare(cd.Name.text, "gendoc",true)==0 && string.Compare(cd.Directive.text,"true",true)==0) - return true; - return false; + + if (unitSyntaxTree == null) + return false; + + if (unitSyntaxTree.file_name != null && internalDebug.DocumentedUnits.Contains(unitSyntaxTree.file_name.ToLower())) + return true; + + foreach (SyntaxTree.compiler_directive directive in unitSyntaxTree.compiler_directives) + { + if (string.Equals(directive.Name.text, "gendoc", StringComparison.CurrentCultureIgnoreCase) + && string.Equals(directive.Directive.text, "true", StringComparison.CurrentCultureIgnoreCase)) + { + return true; + } + } + + return false; } - + private TreeRealization.unit_node_list buildImplementationUsesList(CompilationUnit cu) { TreeRealization.unit_node_list unl = new PascalABCCompiler.TreeRealization.unit_node_list(); @@ -3750,8 +4241,8 @@ namespace PascalABCCompiler } public void SavePCU(CompilationUnit Unit) - { -//#if DEBUG + { + //#if DEBUG try { if (Unit.SyntaxTree != null && Unit.SyntaxTree is SyntaxTree.unit_module) @@ -3767,44 +4258,44 @@ namespace PascalABCCompiler catch { } -//#endif - PCUWriter writer=null; + //#endif + PCUWriter writer = null; try { #if DEBUG if (InternalDebug.PCUGenerate) #endif - if (compilerOptions.SavePCU) - if ((Unit.SemanticTree as TreeRealization.common_unit_node).namespaces.Count > 1 && - Unit.SyntaxTree!=null && - Unit.State == UnitState.Compiled) - { - writer = new PCUWriter(this, pr_ChangeState); - - bool dbginfo = true;/*CompilerOptions.Debug*/ + if (CompilerOptions.SavePCU) + if ((Unit.SemanticTree as TreeRealization.common_unit_node).namespaces.Count > 1 && + Unit.SyntaxTree != null && + Unit.State == UnitState.Compiled) + { + writer = new PCUWriter(this, pr_ChangeState); + + bool dbginfo = true;/*CompilerOptions.Debug*/ #if DEBUG - dbginfo = InternalDebug.IncludeDebugInfoInPCU; + dbginfo = InternalDebug.IncludeDebugInfoInPCU; #endif - - writer.SaveSemanticTree(Unit, Path.ChangeExtension(Unit.UnitFileName, CompilerOptions.CompiledUnitExtension), dbginfo); - - } + + writer.SaveSemanticTree(Unit, Path.ChangeExtension(Unit.UnitFileName, CompilerOptions.CompiledUnitExtension), dbginfo); + + } } catch (Exception err) { - //ErrorsList.Add(new Errors.CompilerInternalError(string.Format("Compiler.Compile[{0}]", Path.GetFileName(this.CurrentCompilationUnit.SyntaxTree.file_name)), err)); + //ErrorsList.Add(new Errors.CompilerInternalError(string.Format("Compiler.Compile[{0}]", Path.GetFileName(this.currentCompilationUnit.SyntaxTree.file_name)), err)); OnChangeCompilerState(this, CompilerState.PCUWritingError, Unit.UnitFileName); #if DEBUG if (!InternalDebug.SkipPCUErrors) - throw new Errors.CompilerInternalError(string.Format("Compiler.Compile[{0}]", Path.GetFileName(this.CurrentCompilationUnit.SyntaxTree.file_name)), err); + throw new Errors.CompilerInternalError(string.Format("Compiler.Compile[{0}]", Path.GetFileName(this.currentCompilationUnit.SyntaxTree.file_name)), err); writer.RemoveSelf(); #endif } } - public CompilationUnit ReadPCU(string FileName) - { - if (compilerOptions.ForIntellisense && false) + public CompilationUnit ReadPCU(string FileName) + { + if (CompilerOptions.ForIntellisense && false) { CompilationUnit unit = null; if (pcuCompilationUnits.ContainsKey(FileName)) @@ -3822,8 +4313,8 @@ namespace PascalABCCompiler PCUReader pr = new PCUReader(this, pr_ChangeState); return pr.GetCompilationUnit(FileName, CompilerOptions.Debug); } - - } + + } void pr_ChangeState(object Sender, PCUReaderWriterState State, object obj) { @@ -3836,7 +4327,7 @@ namespace PascalABCCompiler CompilationUnit cu = obj as CompilationUnit; cu.State = UnitState.Compiled; unitTable[(Sender as PCUReader).FileName] = cu; - UnitsSortedList.Add(cu); + UnitsLogicallySortedList.Add(cu); GetReferences(cu); break; case PCUReaderWriterState.EndSaveTree: @@ -3845,16 +4336,16 @@ namespace PascalABCCompiler } } - /* TreeRealization.common_unit_node cun11 = CurrentUnit.SemanticTree as TreeRealization.common_unit_node; + /* TreeRealization.common_unit_node cun11 = currentUnit.SemanticTree as TreeRealization.common_unit_node; if (cun11 != null) - UnitsSortedList.AddElement(cun11);*/ + UnitsLogicallySortedList.AddElement(cun11);*/ static string standartAssemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(string)).ManifestModule.FullyQualifiedName); public static Dictionary standart_assembly_dict = new Dictionary(); static Compiler() { - string[] ss = new string[] { "mscorlib.dll","System.dll", "System.Core.dll", "System.Numerics.dll", "System.Windows.Forms.dll", "PABCRtl.dll" }; + string[] ss = new string[] { "mscorlib.dll", "System.dll", "System.Core.dll", "System.Numerics.dll", "System.Windows.Forms.dll", "PABCRtl.dll" }; foreach (var x in ss) standart_assembly_dict[x] = get_standart_assembly_path(x); } @@ -3973,11 +4464,9 @@ namespace PascalABCCompiler return get_standart_assembly_path(name); } - - - public CompilationUnit ReadDLL(string FileName, SyntaxTree.SourceContext sc=null) - { + public CompilationUnit ReadDLL(string FileName, SyntaxTree.SourceContext sc = null) + { if (DLLCache.ContainsKey(FileName)) return DLLCache[FileName]; OnChangeCompilerState(this, CompilerState.ReadDLL, FileName); @@ -3986,13 +4475,13 @@ namespace PascalABCCompiler { TreeRealization.dot_net_unit_node un = new TreeRealization.dot_net_unit_node(new NetHelper.NetScope(using_namespaces, - /*System.Reflection.Assembly.LoadFrom(FileName)*/ + /*System.Reflection.Assembly.LoadFrom(file_name)*/ PascalABCCompiler.NetHelper.NetHelper.LoadAssembly(FileName), SyntaxTreeToSemanticTreeConverter.SymbolTable)); CompilationUnit cu = new CompilationUnit(); cu.SemanticTree = un; //un.dotNetScope=new PascalABCCompiler.NetHelper.NetScope(using_namespaces, - // System.Reflection.Assembly.LoadFrom(FileName),SyntaxTreeToSemanticTreeConverter.SymbolTable); + // System.Reflection.Assembly.LoadFrom(file_name),SyntaxTreeToSemanticTreeConverter.SymbolTable); DLLCache[FileName] = cu; return cu; @@ -4000,7 +4489,7 @@ namespace PascalABCCompiler catch (ReflectionTypeLoadException e) { foreach (var assm in assemblyResolveScope.missingAssemblies) - errorsList.Add(new AssemblyNotFound(CurrentCompilationUnit.UnitFileName, assm, sc)); + errorsList.Add(new AssemblyNotFound(currentCompilationUnit.UnitFileName, assm, sc)); /*Console.Error.WriteLine(e.Message); foreach (var eLoaderException in e.LoaderExceptions) { @@ -4014,19 +4503,19 @@ namespace PascalABCCompiler Console.Error.WriteLine(e.Message); return null; } - } + } /*public CompilationUnit RecompileUnit(string unit_name) { Console.WriteLine("recompile {0}", unit_name); - CurrentSyntaxUnit = new SyntaxTree.uses_unit_in(new SyntaxTree.string_const(program_folder + "\\" + unit_name+".pas")); - CompileUnit(Units, CurrentSyntaxUnit); - CompilationUnit cu = new CompilationUnit(); - if (Units.Count != 0) - cu.SemanticTree = Units[Units.Count - 1]; + currentUnit = new SyntaxTree.uses_unit_in(new SyntaxTree.string_const(program_folder + "\\" + unit_name+".pas")); + CompileUnit(unitsFromUsesSection, compilationUnit); + CompilationUnit compilationUnit = new CompilationUnit(); + if (unitsFromUsesSection.Count != 0) + compilationUnit.SemanticTree = unitsFromUsesSection[unitsFromUsesSection.Count - 1]; else return null; - return cu; + return compilationUnit; }*/ public bool NeedRecompiled(string pcu_name, string[] included, PCUReader pr) { @@ -4065,7 +4554,7 @@ namespace PascalABCCompiler { string pcu_name2 = FindPCUFileName(included[i], dir, out _); //TODO: Спросить у Сащи насчет < и <=. - + if ((File.Exists(pcu_name2) && File.GetLastWriteTime(pcu_name) < File.GetLastWriteTime(pcu_name2) && !pr.AlreadyCompiled(pcu_name2))) { pr.AddAlreadyCompiledUnit(pcu_name2); @@ -4079,25 +4568,25 @@ namespace PascalABCCompiler return false; } - public void ClearAll(bool close_pcu=true) + public void ClearAll(bool close_pcu = true) { - _semantic_tree = null; + semanticTree = null; if (close_pcu) { PCUReader.CloseUnits(); PCUWriter.Clear(); } - + RecompileList.Clear(); CycleUnits.Clear(); UnitTable.Clear(); - UnitsSortedList.Clear(); + UnitsLogicallySortedList.Clear(); //TreeRealization.PCUReturner.Clear(); BadNodesInSyntaxTree.Clear(); if (close_pcu) PCUReader.AllReaders.Clear(); project = null; - StandarModules.Clear(); + StandardModules.Clear(); CompiledVariables.Clear(); if (assemblyResolveScope != null) assemblyResolveScope.Dispose(); @@ -4108,7 +4597,7 @@ namespace PascalABCCompiler } //SystemLibrary.SystemLibrary.RestoreStandartNames(); } - + public CompilerType CompilerType { get @@ -4116,7 +4605,7 @@ namespace PascalABCCompiler return CompilerType.Standart; } } - + public void Free() { } diff --git a/Compiler/DocXml.cs b/Compiler/DocXml.cs index aa6375082..dcecbdebf 100644 --- a/Compiler/DocXml.cs +++ b/Compiler/DocXml.cs @@ -24,7 +24,7 @@ namespace PascalABCCompiler try { this.cu = cu; - is_assembly = cu.SyntaxTree is SyntaxTree.program_module || Compiler.is_dll(cu.SyntaxTree); + is_assembly = cu.SyntaxTree is SyntaxTree.program_module || Compiler.IsDll(cu.SyntaxTree); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.Indent = true; diff --git a/Compiler/PCU/PCUReader.cs b/Compiler/PCU/PCUReader.cs index 787bc550e..80b8690dd 100644 --- a/Compiler/PCU/PCUReader.cs +++ b/Compiler/PCU/PCUReader.cs @@ -259,7 +259,7 @@ namespace PascalABCCompiler.PCU PCUReader pr = (PCUReader)units[FileName]; if (pr != null) return pr.unit; if (!File.Exists(FileName)) return null; - //fs = new FileStream(FileName, FileMode.Open, FileAccess.Read); + //fs = new FileStream(file_name, FileMode.Open, FileAccess.Read); ms = new MemoryStream(File.ReadAllBytes(FileName)); br = new BinaryReader(ms); ReadPCUHeader(); @@ -274,7 +274,7 @@ namespace PascalABCCompiler.PCU CloseUnit(); this.unit = null; need = true; - return null; // return comp.RecompileUnit(FileName); + return null; // return comp.RecompileUnit(file_name); } ChangeState(this, PCUReaderWriterState.BeginReadTree, unit); cun.scope = new WrappedUnitInterfaceScope(this); @@ -369,7 +369,7 @@ namespace PascalABCCompiler.PCU { var sub_u = pr.GetCompilationUnit(used_unit_fname, this.readDebugInfo); if (sub_u == null) return true; - this.unit.DirectInterfaceCompilationUnits.Add(sub_u.SemanticTree, sub_u); + this.unit.InterfaceUsedDirectUnits.Add(sub_u.SemanticTree, sub_u); this.unit.InterfaceUsedUnits.AddElement(sub_u.SemanticTree, pcu_file.incl_modules[i]); } } diff --git a/Compiler/PCU/PCUWriter.cs b/Compiler/PCU/PCUWriter.cs index c8051dc91..441ef742e 100644 --- a/Compiler/PCU/PCUWriter.cs +++ b/Compiler/PCU/PCUWriter.cs @@ -885,7 +885,7 @@ namespace PascalABCCompiler.PCU comp_cnn = (tn as common_generic_instance_type_node).common_original_generic.comprehensive_namespace; if (comp_cnn != null && !ns_dict.ContainsKey(comp_cnn) && unit.SemanticTree != comp_cnn.cont_unit) { - var path = Compiler.GetUnitPath(unit, compiler.UnitsSortedList.Find(u => u.SemanticTree == comp_cnn.cont_unit)); + var path = Compiler.GetUnitPath(unit, compiler.UnitsLogicallySortedList.Find(u => u.SemanticTree == comp_cnn.cont_unit)); if (interf) unit.InterfaceUsedUnits.AddElement(comp_cnn.cont_unit, path); @@ -904,7 +904,7 @@ namespace PascalABCCompiler.PCU common_namespace_node comp_cnn = cnfn.namespace_node; if (comp_cnn != null && !ns_dict.ContainsKey(comp_cnn) && unit.SemanticTree != comp_cnn.cont_unit) { - var path = Compiler.GetUnitPath(unit, compiler.UnitsSortedList.Find(u => u.SemanticTree == comp_cnn.cont_unit)); + var path = Compiler.GetUnitPath(unit, compiler.UnitsLogicallySortedList.Find(u => u.SemanticTree == comp_cnn.cont_unit)); if (interf) unit.InterfaceUsedUnits.AddElement(comp_cnn.cont_unit, path); diff --git a/Compiler/RemoteCompiler.cs b/Compiler/RemoteCompiler.cs index 4290b8adc..f0a9819e5 100644 --- a/Compiler/RemoteCompiler.cs +++ b/Compiler/RemoteCompiler.cs @@ -388,7 +388,7 @@ namespace PascalABCCompiler sendCommand(ConsoleCompilerConstants.CompilerOptionsClearStandartModules); if (compilerOptions.Locale != null) sendCommand(ConsoleCompilerConstants.CompilerLocale, compilerOptions.Locale); - foreach (PascalABCCompiler.CompilerOptions.StandartModule sm in compilerOptions.StandartModules) + foreach (PascalABCCompiler.CompilerOptions.StandardModule sm in compilerOptions.StandardModules) sendCommand( ConsoleCompilerConstants.CompilerOptionsStandartModule, sm.Name,(int)sm.AddMethod,(int)sm.AddToLanguages); diff --git a/Configuration/GlobalAssemblyInfo.cs b/Configuration/GlobalAssemblyInfo.cs index 8dbc5bca6..5d74e384d 100644 --- a/Configuration/GlobalAssemblyInfo.cs +++ b/Configuration/GlobalAssemblyInfo.cs @@ -15,7 +15,7 @@ internal static class RevisionClass public const string Major = "3"; public const string Minor = "9"; public const string Build = "0"; - public const string Revision = "3390"; + public const string Revision = "3391"; public const string MainVersion = Major + "." + Minor; public const string FullVersion = Major + "." + Minor + "." + Build + "." + Revision; diff --git a/Configuration/Version.defs b/Configuration/Version.defs index 476dc5314..1f33fe1fe 100644 --- a/Configuration/Version.defs +++ b/Configuration/Version.defs @@ -1,4 +1,4 @@ -%COREVERSION%=0 -%REVISION%=3390 %MINOR%=9 +%REVISION%=3391 +%COREVERSION%=0 %MAJOR%=3 diff --git a/Errors/Errors.cs b/Errors/Errors.cs index 144410b3c..8d116b3cc 100644 --- a/Errors/Errors.cs +++ b/Errors/Errors.cs @@ -51,8 +51,8 @@ namespace PascalABCCompiler.Errors if (source_context != null) pos = "(" + source_context.begin_position.line_num + "," + source_context.begin_position.column_num + ")"; string fn = null; - if (FileName != null) - fn = Path.GetFileName(FileName); + if (file_name != null) + 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(); diff --git a/Grammars/Oberon00/ShiftReduceParser.dll b/Grammars/Oberon00/ShiftReduceParser.dll deleted file mode 100644 index 4e113ba04..000000000 Binary files a/Grammars/Oberon00/ShiftReduceParser.dll and /dev/null differ diff --git a/Libraries/ShiftReduceParser.dll b/Libraries/ShiftReduceParser.dll deleted file mode 100644 index 4e113ba04..000000000 Binary files a/Libraries/ShiftReduceParser.dll and /dev/null differ diff --git a/Localization/DefaultLang.resources b/Localization/DefaultLang.resources index ba9e218f4..ad5db3072 100644 Binary files a/Localization/DefaultLang.resources and b/Localization/DefaultLang.resources differ diff --git a/NETGenerator/CodeGenerator.cs b/NETGenerator/CodeGenerator.cs index 765cd5b06..a183b5175 100644 --- a/NETGenerator/CodeGenerator.cs +++ b/NETGenerator/CodeGenerator.cs @@ -22,7 +22,7 @@ namespace PascalABCCompiler.CodeGenerators { private NETGenerator.ILConverter il_converter;//=new NETGenerator.ILConverter(); - public void Compile(SemanticTree.IProgramNode ProgramTree,string TargetFileName,string SourceFileName , + public void GenerateILCodeAndSaveAssembly(SemanticTree.IProgramNode ProgramTree,string TargetFileName,string SourceFileName , NETGenerator.CompilerOptions options, Hashtable StandartDirectories, string[] ResourceFiles) { il_converter = new NETGenerator.ILConverter(StandartDirectories); diff --git a/ParserTools/ParsersController.cs b/ParserTools/ParsersController.cs index 1aa565f3f..0a9a05aee 100644 --- a/ParserTools/ParsersController.cs +++ b/ParserTools/ParsersController.cs @@ -4,7 +4,9 @@ using System; using System.IO; using PascalABCCompiler.ParserTools; using PascalABCCompiler.Errors; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; namespace PascalABCCompiler.Parsers { @@ -27,22 +29,6 @@ namespace PascalABCCompiler.Parsers IParser pc = null; foreach (FileInfo fi in dllfiles) { - /*if (Path.GetFileName(fi.FullName)=="PascalABCParser.dll" && - string.Compare(Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().ManifestModule.FullyQualifiedName),"PascalABCNET.exe",true)==0) - continue; - else - if (Path.GetFileName(fi.FullName)=="PascalABCPartParser.dll" && - string.Compare(Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().ManifestModule.FullyQualifiedName),"pabcnetc.exe",true)==0) - continue;*/ - //if (Path.GetFileName(fi.FullName) != "PascalABCParser.dll" && Path.GetFileName(fi.FullName) != "VBNETParser.dll") - // continue; - //if (Path.GetFileName(fi.FullName) == "VBNETParser.dll" || Path.GetFileName(fi.FullName) == "PascalABCPartParser.dll") - //if (Path.GetFileName(fi.FullName) != "PascalABCParser.dll" && Path.GetFileName(fi.FullName) != "VBNETParser.dll") - // continue; - //if (Path.GetFileName(fi.FullName) == "PascalABCPartParser.dll") - // continue; - //if (Path.GetFileName(fi.FullName) != "PascalABCParser.dll" /*&& Path.GetFileName(fi.FullName) != "VBNETParser.dll"*/) - // continue; if (Path.GetFileName(fi.FullName) == "VBNETParser.dll" || Path.GetFileName(fi.FullName) == "PascalABCPartParser.dll") continue; asssembly = System.Reflection.Assembly.LoadFile(fi.FullName); @@ -142,6 +128,7 @@ namespace PascalABCCompiler.Parsers return null; if (cu is SyntaxTree.compilation_unit) return cu as SyntaxTree.compilation_unit; + Errors.Add(new Errors.UnexpectedNodeType(FileName, cu.source_context,null)); return null; //throw new Errors.CompilerInternalError("Parsers.Controller.GetComilationUnit", new Exception("bad node type")); diff --git a/ParserTools/Tools.cs b/ParserTools/Tools.cs index dd9143f23..431b2effa 100644 --- a/ParserTools/Tools.cs +++ b/ParserTools/Tools.cs @@ -21,8 +21,8 @@ namespace PascalABCCompiler { case SourceFileOperation.GetText: if (!File.Exists(FileName)) return null; - /*TextReader tr = new StreamReader(FileName, System.Text.Encoding.GetEncoding(1251)); - //TextReader tr = new StreamReader(FileName, System.Text.Encoding.); + /*TextReader tr = new StreamReader(file_name, System.Text.Encoding.GetEncoding(1251)); + //TextReader tr = new StreamReader(file_name, System.Text.Encoding.); string Text = tr.ReadToEnd(); tr.Close();*/ string Text = FileReader.ReadFileContent(FileName, null); diff --git a/ParserTools/XmlDocs.cs b/ParserTools/XmlDocs.cs index e97657865..02ca9b773 100644 --- a/ParserTools/XmlDocs.cs +++ b/ParserTools/XmlDocs.cs @@ -788,7 +788,7 @@ namespace CodeCompletionTools public static XmlDoc Load(string fileName, string cachePath, bool ru) { - //LoggingService.Debug("Loading XmlDoc for " + fileName); + //LoggingService.Debug("Loading XmlDoc for " + file_name); XmlDoc doc; string cacheName = null; if (cachePath != null) { @@ -814,12 +814,12 @@ namespace CodeCompletionTools doc = Load(xmlReader); } } catch (XmlException ex) { - //LoggingService.Warn("Error loading XmlDoc " + fileName, ex); + //LoggingService.Warn("Error loading XmlDoc " + file_name, ex); return new XmlDoc(); } if (cachePath != null && doc.xmlDescription.Count > cacheLength * 2) { - //LoggingService.Debug("XmlDoc: Creating cache for " + fileName); + //LoggingService.Debug("XmlDoc: Creating cache for " + file_name); DateTime date = File.GetLastWriteTimeUtc(fileName); try { doc.Save(cacheName, date); diff --git a/Parsers/PascalABCParserNewSaushkin/GPLex_GPPG/ShiftReduceParser.dll b/Parsers/PascalABCParserNewSaushkin/GPLex_GPPG/ShiftReduceParser.dll deleted file mode 100644 index 4e113ba04..000000000 Binary files a/Parsers/PascalABCParserNewSaushkin/GPLex_GPPG/ShiftReduceParser.dll and /dev/null differ diff --git a/Parsers/PascalABCParserNewSaushkin/Parser.cs b/Parsers/PascalABCParserNewSaushkin/Parser.cs index 030bf6e3c..32e37d152 100644 --- a/Parsers/PascalABCParserNewSaushkin/Parser.cs +++ b/Parsers/PascalABCParserNewSaushkin/Parser.cs @@ -190,7 +190,7 @@ namespace PascalABCCompiler.PascalABCNewParser Errors.Clear(); Warnings.Clear(); /*string[] file_names = new string[1]; - file_names[0] = FileName; + file_names[0] = file_name; preprocessor2.Build(file_names, Errors, null);*/ diff --git a/Parsers/PascalABCParserNewSaushkin/PascalABCSaushkinParser.csproj b/Parsers/PascalABCParserNewSaushkin/PascalABCSaushkinParser.csproj index 3844551a4..ea07f972d 100644 --- a/Parsers/PascalABCParserNewSaushkin/PascalABCSaushkinParser.csproj +++ b/Parsers/PascalABCParserNewSaushkin/PascalABCSaushkinParser.csproj @@ -111,9 +111,6 @@ - - Code - @@ -128,6 +125,10 @@ {AF2EFD7B-69DD-4B43-AF65-B59B29349C23} ParserTools + + {ad4e1292-2537-467a-934d-e9fda3f18d87} + ShiftReduceParser + {C2CAC65A-B2AE-4CCC-B067-E6B8E75DF73A} SyntaxTree diff --git a/PascalABCNET.sln b/PascalABCNET.sln index 74e905329..15c6de3ec 100644 --- a/PascalABCNET.sln +++ b/PascalABCNET.sln @@ -1,13 +1,17 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.28307.1000 +# Visual Studio Version 17 +VisualStudioVersion = 17.8.34309.116 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "VisualPascalABCNET", "VisualPascalABCNET", "{26843C5D-9D7E-4C2C-AC14-2D227FA5592E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PluginsSupport", "PluginsSupport\PluginsSupport.csproj", "{CFC683F8-0165-4A9F-9C3F-BB8C5BAB507F}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VisualPascalABCNET", "VisualPascalABCNET\VisualPascalABCNET.csproj", "{BC35F816-54EE-47E0-89FC-1C66EAC155A9}" + ProjectSection(ProjectDependencies) = postProject + {AD4E1292-2537-467A-934D-E9FDA3F18D87} = {AD4E1292-2537-467A-934D-E9FDA3F18D87} + {E862A9EF-836B-414B-AAC4-9D207CABDC82} = {E862A9EF-836B-414B-AAC4-9D207CABDC82} + EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Plugins", "Plugins", "{EC68A3D8-6D63-4A79-ABA6-BF8E9D7756D7}" EndProject @@ -18,8 +22,8 @@ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompilerController", "VisualPlugins\CompilerController\CompilerController.csproj", "{50F4AB3F-0A1E-4AF9-88CF-48A8D3E1D1D7}" ProjectSection(ProjectDependencies) = postProject {1E42361A-EDA3-4872-88AF-A3AAF600D36D} = {1E42361A-EDA3-4872-88AF-A3AAF600D36D} - {CFC683F8-0165-4A9F-9C3F-BB8C5BAB507F} = {CFC683F8-0165-4A9F-9C3F-BB8C5BAB507F} {A25D26FB-3043-4BCF-833E-E3F4C3BE795E} = {A25D26FB-3043-4BCF-833E-E3F4C3BE795E} + {CFC683F8-0165-4A9F-9C3F-BB8C5BAB507F} = {CFC683F8-0165-4A9F-9C3F-BB8C5BAB507F} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InternalErrorReport", "VisualPlugins\InternalErrorReport\InternalErrorReport.csproj", "{A36031B7-D3D1-4372-B478-07621069602E}" @@ -85,8 +89,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ICSharpCode.Core.WinForms", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PABCNETCclear", "pabcnetc_clear\PABCNETCclear.csproj", "{146083AD-6684-4EBC-A539-AAD749A16364}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PascalABCSaushkinParser", "Parsers\PascalABCParserNewSaushkin\PascalABCSaushkinParser.csproj", "{1443F539-DCC7-4491-B4FD-B716C739DB3C}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DA0402DA-D618-47B4-8BF0-2959D16F2160}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SyntaxTreeConverters", "SyntaxTreeConverters\SyntaxTreeConverters.csproj", "{F10A5330-DCF4-4533-877C-7B1B1BE23884}" @@ -107,6 +109,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TeacherControlPlugin", "Vis EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LambdaAnySynToSemConverter", "LambdaAnySynToSemConverter\LambdaAnySynToSemConverter.csproj", "{27D9800E-2689-4AA1-A2D6-128E4A9BAE98}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShiftReduceParser", "ShiftReduceParser\ShiftReduceParser.csproj", "{AD4E1292-2537-467A-934D-E9FDA3F18D87}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PascalABCSaushkinParser", "Parsers\PascalABCParserNewSaushkin\PascalABCSaushkinParser.csproj", "{1443F539-DCC7-4491-B4FD-B716C739DB3C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UniversalParserHelper", "UniversalParserHelper\UniversalParserHelper.csproj", "{E862A9EF-836B-414B-AAC4-9D207CABDC82}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -387,16 +395,6 @@ Global {146083AD-6684-4EBC-A539-AAD749A16364}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {146083AD-6684-4EBC-A539-AAD749A16364}.Release|Mixed Platforms.Build.0 = Release|Any CPU {146083AD-6684-4EBC-A539-AAD749A16364}.Release|x86.ActiveCfg = Release|Any CPU - {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Debug|x86.ActiveCfg = Debug|Any CPU - {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Release|Any CPU.Build.0 = Release|Any CPU - {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Release|x86.ActiveCfg = Release|Any CPU {F10A5330-DCF4-4533-877C-7B1B1BE23884}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F10A5330-DCF4-4533-877C-7B1B1BE23884}.Debug|Any CPU.Build.0 = Debug|Any CPU {F10A5330-DCF4-4533-877C-7B1B1BE23884}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -501,6 +499,42 @@ Global {27D9800E-2689-4AA1-A2D6-128E4A9BAE98}.Release|Mixed Platforms.Build.0 = Release|Any CPU {27D9800E-2689-4AA1-A2D6-128E4A9BAE98}.Release|x86.ActiveCfg = Release|Any CPU {27D9800E-2689-4AA1-A2D6-128E4A9BAE98}.Release|x86.Build.0 = Release|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Debug|x86.ActiveCfg = Debug|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Debug|x86.Build.0 = Debug|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Release|Any CPU.Build.0 = Release|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Release|x86.ActiveCfg = Release|Any CPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87}.Release|x86.Build.0 = Release|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Debug|x86.ActiveCfg = Debug|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Debug|x86.Build.0 = Debug|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Release|Any CPU.Build.0 = Release|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Release|x86.ActiveCfg = Release|Any CPU + {1443F539-DCC7-4491-B4FD-B716C739DB3C}.Release|x86.Build.0 = Release|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Debug|x86.ActiveCfg = Debug|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Debug|x86.Build.0 = Debug|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Release|Any CPU.Build.0 = Release|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Release|x86.ActiveCfg = Release|Any CPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -536,7 +570,6 @@ Global {7E4A7172-7FF5-48D0-B719-7CD959DD1AC9} = {A5A3667E-8A3B-4569-BA0E-AD49E12D07E7} {857CA1A3-FC88-4BE0-AB6A-D1EE772AB288} = {A5A3667E-8A3B-4569-BA0E-AD49E12D07E7} {146083AD-6684-4EBC-A539-AAD749A16364} = {F8CE2712-826B-450B-A72F-D32D80C99858} - {1443F539-DCC7-4491-B4FD-B716C739DB3C} = {BB6973BA-B3A2-4B31-A986-7CB008F22C4F} {F10A5330-DCF4-4533-877C-7B1B1BE23884} = {F8CE2712-826B-450B-A72F-D32D80C99858} {CE5C55C2-A11C-4E94-A9FA-3FC6CA3E4C09} = {F8CE2712-826B-450B-A72F-D32D80C99858} {A9AB4282-83B4-41A7-86C3-E5BF6A45E7E2} = {F8CE2712-826B-450B-A72F-D32D80C99858} @@ -546,6 +579,9 @@ Global {E009E776-9280-4061-B5CA-7F0C3E2D3C2A} = {26843C5D-9D7E-4C2C-AC14-2D227FA5592E} {536CC813-7C4E-42BC-AE3A-BA1427F38756} = {EC68A3D8-6D63-4A79-ABA6-BF8E9D7756D7} {27D9800E-2689-4AA1-A2D6-128E4A9BAE98} = {F8CE2712-826B-450B-A72F-D32D80C99858} + {AD4E1292-2537-467A-934D-E9FDA3F18D87} = {F8CE2712-826B-450B-A72F-D32D80C99858} + {1443F539-DCC7-4491-B4FD-B716C739DB3C} = {BB6973BA-B3A2-4B31-A986-7CB008F22C4F} + {E862A9EF-836B-414B-AAC4-9D207CABDC82} = {F8CE2712-826B-450B-A72F-D32D80C99858} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {68E993E6-EE86-4DDF-B0A1-4FE884F8AC39} diff --git a/Release/pabcversion.txt b/Release/pabcversion.txt index 011f8c10b..d54f96061 100644 --- a/Release/pabcversion.txt +++ b/Release/pabcversion.txt @@ -1 +1 @@ -3.9.0.3390 +3.9.0.3391 diff --git a/ReleaseGenerators/PascalABCNET_version.nsh b/ReleaseGenerators/PascalABCNET_version.nsh index db91d4b23..489c3f57f 100644 --- a/ReleaseGenerators/PascalABCNET_version.nsh +++ b/ReleaseGenerators/PascalABCNET_version.nsh @@ -1 +1 @@ -!define VERSION '3.9.0.3390' +!define VERSION '3.9.0.3391' diff --git a/ReleaseGenerators/sect_Core.nsh b/ReleaseGenerators/sect_Core.nsh index be6d234b4..9df8041e4 100644 --- a/ReleaseGenerators/sect_Core.nsh +++ b/ReleaseGenerators/sect_Core.nsh @@ -1,10 +1,11 @@ - Section $(DESC_Core) Core + Section $(DESC_Core) Core SectionIn 1 2 RO SetOutPath "$INSTDIR" File ExecHide.exe File "..\bin\Compiler.dll" File "..\bin\CompilerTools.dll" File "..\bin\Errors.dll" + File "..\bin\ShiftReduceParser.dll" File "..\bin\Localization.dll" File "..\bin\NETGenerator.dll" File "..\bin\ParserTools.dll" @@ -28,7 +29,8 @@ File "..\bin\Mono.Cecil.dll" File "..\bin\TeacherControlPlugin.dll" File "..\bin\LambdaAnySynToSemConverter.dll" - ;File "libs\System.Core.dll" + File "..\bin\UniversalParserHelper.dll" + ;File "libs\System.Core.dll" File "gacutil.exe" File "gacutil.exe.config" File "gacutlrc.dll" @@ -40,20 +42,21 @@ ; main config - only .NET 4.7.1 and above - DotNetChecker::IsDotNet471Installed - Pop $0 + DotNetChecker::IsDotNet471Installed + Pop $0 - ${If} $0 == "false" - ${OrIf} $0 == "f" ; if script is compiled in ANSI mode then we get only an "f" https://github.com/ReVolly/NsisDotNetChecker/issues/4 - ${Else} - File "..\bin\PascalABCNET.exe.config" - ${AddFile} "PascalABCNET.exe.config" - ${EndIf} - - - ;dobavljaem fajly v uninst.log - ${AddFile} "Compiler.dll" + ${If} $0 == "false" + ${OrIf} $0 == "f" ; if script is compiled in ANSI mode then we get only an "f" https://github.com/ReVolly/NsisDotNetChecker/issues/4 + ${Else} + File "..\bin\PascalABCNET.exe.config" + ${AddFile} "PascalABCNET.exe.config" + ${EndIf} + + + ;dobavljaem fajly v uninst.log + ${AddFile} "Compiler.dll" ${AddFile} "CompilerTools.dll" + ${AddFile} "ShiftReduceParser.dll" ${AddFile} "Errors.dll" ${AddFile} "Localization.dll" ${AddFile} "NETGenerator.dll" @@ -69,6 +72,7 @@ ${AddFile} "Mono.Cecil.dll" ${AddFile} "TeacherControlPlugin.dll" ${AddFile} "LambdaAnySynToSemConverter.dll" + ${AddFile} "UniversalParserHelper.dll" ${AddFile} "License.txt" ${AddFile} "copyright.txt" ${AddFile} "pabcnetc.exe.config" @@ -77,7 +81,7 @@ Delete "$INSTDIR\Lib\*.pas" SetOutPath "$INSTDIR\Lib" ;File ..\bin\Lib\*.pcu; eto ploho nuzhno kazhdyj pcu raspisyvat - + File ..\bin\Lib\__RedirectIOMode.pcu File ..\bin\Lib\__RunMode.pcu File ..\bin\Lib\ABCButtons.pcu @@ -161,7 +165,7 @@ File ..\bin\Lib\HelixToolkit.dll File ..\bin\Lib\nunit.framework.dll File ..\bin\Lib\InteractiveDataDisplay.WPF.dll - + File ..\bin\Lib\turtle.png ${AddFile} "__RedirectIOMode.pcu" @@ -271,7 +275,7 @@ Push "Lib\InteractiveDataDisplay.WPF.dll" Call NGEN - + SetOutPath "$INSTDIR\LibSource" File ..\bin\Lib\__RedirectIOMode.pas File ..\bin\Lib\__RunMode.pas @@ -346,11 +350,11 @@ File ..\bin\Lib\XLSX.pas File ..\bin\Lib\Мозаика.pas - File ..\bin\Lib\__RedirectIOMode.vb - File ..\bin\Lib\VBSystem.vb - - ;dobavljaem fajly v uninst.log - ${AddFile} "__RedirectIOMode.pas" + File ..\bin\Lib\__RedirectIOMode.vb + File ..\bin\Lib\VBSystem.vb + + ;dobavljaem fajly v uninst.log + ${AddFile} "__RedirectIOMode.pas" ${AddFile} "__RunMode.pas" ${AddFile} "ABCButtons.pas" ${AddFile} "ABCHouse.pas" @@ -395,7 +399,7 @@ ${AddFile} "RobotTaskMaker.pas" ; File ..\bin\Lib\RobotZadan.pas ${AddFile} "Sockets.pas" - ${AddFile} "Timers.pas" + ${AddFile} "Timers.pas" ${AddFile} "Utils.pas" ${AddFile} "VCL.pas" ${AddFile} "RBDMUtils.pas" @@ -423,13 +427,13 @@ ${AddFile} "Мозаика.pas" - ${AddFile} "__RedirectIOMode.vb" + ${AddFile} "__RedirectIOMode.vb" ${AddFile} "VBSystem.vb" - + CreateDirectory "$SMPROGRAMS\PascalABC.NET" Push "OptimizerConversion.dll" Call NGEN - Push "SyntaxVisitors.dll" + Push "SyntaxVisitors.dll" Call NGEN ; SetOutPath "$INSTDIR\Output" diff --git a/ShiftReduceParser/App.config b/ShiftReduceParser/App.config new file mode 100644 index 000000000..74ade9db5 --- /dev/null +++ b/ShiftReduceParser/App.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/ShiftReduceParser/ShiftReduceParser.csproj b/ShiftReduceParser/ShiftReduceParser.csproj new file mode 100644 index 000000000..306d5532e --- /dev/null +++ b/ShiftReduceParser/ShiftReduceParser.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {AD4E1292-2537-467A-934D-E9FDA3F18D87} + Library + GPPG + ShiftReduceParser + v4.0 + 512 + false + true + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + ..\bin\ + TRACE + prompt + 4 + + + + + + + + + + + + + {c2cac65a-b2ae-4ccc-b067-e6b8e75df73a} + SyntaxTree + + + + \ No newline at end of file diff --git a/Parsers/PascalABCParserNewSaushkin/ShiftReduceParserCode.cs b/ShiftReduceParser/ShiftReduceParserCode.cs similarity index 100% rename from Parsers/PascalABCParserNewSaushkin/ShiftReduceParserCode.cs rename to ShiftReduceParser/ShiftReduceParserCode.cs diff --git a/Studio.bat b/Studio.bat index 463e8bff1..10fc7e129 100644 --- a/Studio.bat +++ b/Studio.bat @@ -1,4 +1,4 @@ - + if exist "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\msbuild.exe" ( @@ -23,6 +23,12 @@ if exist "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Community\MSBuild\15. +rem Если хотите добавить другой путь к Visual Studio, можете записать его в переменную среды MSBUILD_PATH +) else if exist "%MSBUILD_PATH%" ( +"%MSBUILD_PATH%" %1 %2 %3 %4 + + + ) else ( ECHO Visual Studio not found SET ERRORLEVEL=1 diff --git a/SyntaxTree/tree/TreeSubsidiary.cs b/SyntaxTree/tree/TreeSubsidiary.cs index cf960dba2..7565b1934 100644 --- a/SyntaxTree/tree/TreeSubsidiary.cs +++ b/SyntaxTree/tree/TreeSubsidiary.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; namespace PascalABCCompiler.SyntaxTree @@ -176,7 +176,7 @@ namespace PascalABCCompiler.SyntaxTree public enum for_cycle_type {to,downto}; - public enum proc_attribute {attr_override, attr_forward, attr_virtual, attr_overload, attr_reintroduce, attr_abstract, attr_static, attr_extension, attr_none }; // attr_none virtual override + public enum proc_attribute {attr_override, attr_forward, attr_virtual, attr_overload, attr_reintroduce, attr_abstract, attr_static, attr_extension, attr_none }; // attr_none нужно для свойств когда virtual И override не указывается public enum definition_attribute {None, Static, Const}; @@ -239,7 +239,6 @@ namespace PascalABCCompiler.SyntaxTree private int _begin_symbol_position; private int _end_symbol_position; private string _file_name=null; - public string FileName { get @@ -252,6 +251,11 @@ namespace PascalABCCompiler.SyntaxTree } } + /// + /// дефолтный конструктор (присваивает всем позициям единицы, что соответствует позиции начала файла) + /// + public SourceContext() : this(1, 1, 1, 1, 1, 1) { } + public SourceContext(int beg_line_num, int beg_column_num, int end_line_num, int end_column_num, int _begin_symbol_position, int _end_symbol_position) { _begin_position=new file_position(beg_line_num,beg_column_num); diff --git a/TreeConverter/Collections/extandable_collection.cs b/TreeConverter/Collections/extandable_collection.cs index bb2bf1710..13fb65720 100644 --- a/TreeConverter/Collections/extandable_collection.cs +++ b/TreeConverter/Collections/extandable_collection.cs @@ -208,7 +208,7 @@ namespace PascalABCCompiler.Collections _elements_as_arr = null; } - public void clear() + public void Clear() { _elements.Clear(); _elements_as_arr = null; diff --git a/TreeConverter/OpenMP/OpenMP.cs b/TreeConverter/OpenMP/OpenMP.cs index 58919b951..27097aef4 100644 --- a/TreeConverter/OpenMP/OpenMP.cs +++ b/TreeConverter/OpenMP/OpenMP.cs @@ -943,10 +943,10 @@ namespace PascalABCCompiler.TreeConverter VarFinderSyntaxVisitor VFvis = new VarFinderSyntaxVisitor(syntax_body, syntax_tree_visitor.context, true); SyntaxTree.compiler_directive dir = syntax_tree_visitor.DirectivesToNodesLinks[for_node]; //if (DirInfosTable[dir].ErrorName == "WARNING_IN_CLAUSE_PARAMETERS_REPEATED_VARS") - // syntax_tree_visitor.AddWarning(new Errors.CommonWarning(StringResources.Get(DirInfosTable[dir].ErrorName), for_node.source_context.FileName, DirInfosTable[dir].SC.begin_position.line_num, DirInfosTable[dir].SC.begin_position.column_num)); + // syntax_tree_visitor.AddWarning(new Errors.CommonWarning(StringResources.Get(DirInfosTable[dir].ErrorName), for_node.source_context.file_name, DirInfosTable[dir].SC.begin_position.line_num, DirInfosTable[dir].SC.begin_position.column_num)); //else if (DirInfosTable[dir].ErrorName == "ERROR_IN_CLAUSE_PARAMETERS") //{ - // syntax_tree_visitor.AddWarning(new Errors.CommonWarning(StringResources.Get(DirInfosTable[dir].ErrorName), for_node.source_context.FileName, DirInfosTable[dir].SC.begin_position.line_num, DirInfosTable[dir].SC.begin_position.column_num)); + // syntax_tree_visitor.AddWarning(new Errors.CommonWarning(StringResources.Get(DirInfosTable[dir].ErrorName), for_node.source_context.file_name, DirInfosTable[dir].SC.begin_position.line_num, DirInfosTable[dir].SC.begin_position.column_num)); //} //else @@ -1057,10 +1057,10 @@ namespace PascalABCCompiler.TreeConverter SyntaxTree.compiler_directive dir = syntax_tree_visitor.DirectivesToNodesLinks[syntax_stmts]; //if (DirInfosTable[dir].ErrorName == "WARNING_IN_CLAUSE_PARAMETERS_REPEATED_VARS") - // syntax_tree_visitor.AddWarning(new Errors.CommonWarning(StringResources.Get(DirInfosTable[dir].ErrorName), syntax_stmts.source_context.FileName, DirInfosTable[dir].SC.begin_position.line_num, DirInfosTable[dir].SC.begin_position.column_num)); + // syntax_tree_visitor.AddWarning(new Errors.CommonWarning(StringResources.Get(DirInfosTable[dir].ErrorName), syntax_stmts.source_context.file_name, DirInfosTable[dir].SC.begin_position.line_num, DirInfosTable[dir].SC.begin_position.column_num)); //else if (DirInfosTable[dir].ErrorName == "ERROR_IN_CLAUSE_PARAMETERS") //{ - // syntax_tree_visitor.AddWarning(new Errors.CommonWarning(StringResources.Get(DirInfosTable[dir].ErrorName), syntax_stmts.source_context.FileName, DirInfosTable[dir].SC.begin_position.line_num, DirInfosTable[dir].SC.begin_position.column_num)); + // syntax_tree_visitor.AddWarning(new Errors.CommonWarning(StringResources.Get(DirInfosTable[dir].ErrorName), syntax_stmts.source_context.file_name, DirInfosTable[dir].SC.begin_position.line_num, DirInfosTable[dir].SC.begin_position.column_num)); //} //else if (DirInfosTable[dir].ErrorName != null) diff --git a/TreeConverter/SystemLib/StaticSystemLib.cs b/TreeConverter/SystemLib/StaticSystemLib.cs index d58b4b5c0..0d290b4a8 100644 --- a/TreeConverter/SystemLib/StaticSystemLib.cs +++ b/TreeConverter/SystemLib/StaticSystemLib.cs @@ -2191,7 +2191,7 @@ namespace PascalABCCompiler.SystemLibrary Type arr_type = typeof(System.Array); System.Reflection.MethodInfo resize_func_mi = arr_type.GetMethod("Resize"); _resize_func = compiled_function_node.get_compiled_method(resize_func_mi); - _resize_func.parameters.clear(); + _resize_func.parameters.Clear(); common_parameter par0 = new common_parameter("Array", _object_type, SemanticTree.parameter_type.value, null, concrete_parameter_type.cpt_none, null, null); common_parameter par1 = new common_parameter("Length", _integer_type, SemanticTree.parameter_type.value, null, diff --git a/TreeConverter/TreeConversion/LambdaHelper.cs b/TreeConverter/TreeConversion/LambdaHelper.cs index 706c84bd5..dfeae74e1 100644 --- a/TreeConverter/TreeConversion/LambdaHelper.cs +++ b/TreeConverter/TreeConversion/LambdaHelper.cs @@ -391,7 +391,7 @@ namespace PascalABCCompiler.TreeConverter res.return_value_type = visitor.convert_strong(def.return_type); else res.return_value_type = null; - res.parameters.clear(); + res.parameters.Clear(); if (def.formal_parameters != null && def.formal_parameters.params_list.Count != 0) { for (int i = 0; i < def.formal_parameters.params_list.Count; i++) diff --git a/TreeConverter/TreeConversion/SyntaxTreeToSemanticTreeConverter.cs b/TreeConverter/TreeConversion/SyntaxTreeToSemanticTreeConverter.cs index fd3be7727..eef4b9beb 100644 --- a/TreeConverter/TreeConversion/SyntaxTreeToSemanticTreeConverter.cs +++ b/TreeConverter/TreeConversion/SyntaxTreeToSemanticTreeConverter.cs @@ -8,7 +8,7 @@ * ***************************************************************************/ -using System; +using PascalABCCompiler.TreeRealization; using System.Collections.Generic; namespace PascalABCCompiler.TreeConverter @@ -82,8 +82,8 @@ namespace PascalABCCompiler.TreeConverter //stv.comp_units=UsedUnits; //stv.visit(SyntaxUnit //stv.interface_using_list = namespaces; - stv.using_list.clear(); - stv.interface_using_list.clear(); + stv.using_list.Clear(); + stv.interface_using_list.Clear(); stv.using_list.AddRange(namespaces); stv.current_document = new TreeRealization.document(SyntaxUnit.file_name); stv.ErrorsList = ErrorsList; @@ -133,7 +133,7 @@ namespace PascalABCCompiler.TreeConverter stv.bad_nodes_in_syntax_tree = bad_nodes; stv.referenced_units = UsedUnits; - stv.using_list.clear(); + stv.using_list.Clear(); stv.using_list.AddRange(interface_namespaces); stv.interface_using_list.AddRange(interface_namespaces); stv.using_list.AddRange(imlementation_namespaces); @@ -153,8 +153,8 @@ namespace PascalABCCompiler.TreeConverter { throw new PascalABCCompiler.TreeConverter.CompilerInternalError("Program has not implementation part"); } - //TODO: Переделать, чтобы Сашин код работал с common_unit_node. - stv.compiled_unit=(PascalABCCompiler.TreeRealization.common_unit_node)SemanticUnit; + + stv.compiled_unit = SemanticUnit; stv.current_document = new TreeRealization.document(SyntaxUnit.file_name); foreach (SyntaxTree.compiler_directive cd in umod.compiler_directives) @@ -165,6 +165,7 @@ namespace PascalABCCompiler.TreeConverter //stv.visit(SyntaxUnit); //return stv.compiled_unit; } + public void Reset() { stv.reset(); diff --git a/TreeConverter/TreeConversion/syntax_tree_visitor.cs b/TreeConverter/TreeConversion/syntax_tree_visitor.cs index 88d9fd45a..f565d439b 100644 --- a/TreeConverter/TreeConversion/syntax_tree_visitor.cs +++ b/TreeConverter/TreeConversion/syntax_tree_visitor.cs @@ -576,7 +576,7 @@ namespace PascalABCCompiler.TreeConverter _compiled_unit = null; _referenced_units = null; current_document = null; - using_list.clear(); + using_list.Clear(); //_referenced_units.clear(); ret.reset(); motivation_keeper.reset(); @@ -1481,7 +1481,7 @@ namespace PascalABCCompiler.TreeConverter { if (cmn.cont_type.IsAbstract) AddError(loc, "ABSTRACT_CONSTRUCTOR_{0}_CALL", cmn.cont_type.name); - ret.clear(); + ret.Clear(); ret.AddElement(new common_constructor_call(cmn, loc)); return ret; } @@ -8869,7 +8869,7 @@ namespace PascalABCCompiler.TreeConverter check_on_loop_variable(en); //if (en.type == null) //throw new CanNotRead(en.location); - exl.clear(); + exl.Clear(); if (read_from_file) exl.AddElement(file); if (read_from_typed_file) @@ -8983,7 +8983,7 @@ namespace PascalABCCompiler.TreeConverter { if (last_call != null && convertion_data_and_alghoritms.statement_list_stack.size > 0) convertion_data_and_alghoritms.statement_list_stack.top().statements.AddElement(last_call); - exl.clear(); + exl.Clear(); if (read_from_file) exl.AddElement(file); @@ -11796,7 +11796,7 @@ namespace PascalABCCompiler.TreeConverter parameter_list temp_params = new parameter_list(); foreach (SyntaxTree.typed_parameters tpars in syn_parametres.params_list) { - temp_params.clear(); + temp_params.Clear(); SemanticTree.parameter_type pt = SemanticTree.parameter_type.value; concrete_parameter_type cpt = concrete_parameter_type.cpt_none; switch (tpars.param_kind) @@ -19053,7 +19053,7 @@ namespace PascalABCCompiler.TreeConverter { current_using_list.AddElement(un); } - using_list.clear(); + using_list.Clear(); foreach (using_namespace un in tc.using_list) { using_list.AddElement(un); @@ -19149,7 +19149,7 @@ namespace PascalABCCompiler.TreeConverter context.converted_namespace = pdi.nspace; using_namespace_list ulist = (pdi.nspace == tc.cnn) ? tc.using_list : tc.using_list2; - using_list.clear(); + using_list.Clear(); foreach (using_namespace un in ulist) { using_list.AddElement(un); @@ -19198,7 +19198,7 @@ namespace PascalABCCompiler.TreeConverter type_section_converting = current_type_section_converting; context.member_decls = current_member_decls; context.var_defs = current_var_defs; - using_list.clear(); + using_list.Clear(); foreach (using_namespace un in current_using_list) { using_list.AddElement(un); diff --git a/UniversalParserHelper/Properties/AssemblyInfo.cs b/UniversalParserHelper/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..46951cebe --- /dev/null +++ b/UniversalParserHelper/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Общие сведения об этой сборке предоставляются следующим набором +// набора атрибутов. Измените значения этих атрибутов для изменения сведений, +// связанные со сборкой. +[assembly: AssemblyTitle("UniversalParserHelper")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("UniversalParserHelper")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми +// для компонентов COM. Если необходимо обратиться к типу в этой сборке через +// COM, задайте атрибуту ComVisible значение TRUE для этого типа. +[assembly: ComVisible(false)] + +// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM +[assembly: Guid("e862a9ef-836b-414b-aac4-9d207cabdc82")] + +// Сведения о версии сборки состоят из указанных ниже четырех значений: +// +// Основной номер версии +// Дополнительный номер версии +// Номер сборки +// Редакция +// +// Можно задать все значения или принять номера сборки и редакции по умолчанию +// используя "*", как показано ниже: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/UniversalParserHelper/UniversalParserHelper.cs b/UniversalParserHelper/UniversalParserHelper.cs new file mode 100644 index 000000000..447c2a2a7 --- /dev/null +++ b/UniversalParserHelper/UniversalParserHelper.cs @@ -0,0 +1,385 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using QUT.Gppg; + +using PascalABCCompiler.SyntaxTree; +using PascalABCCompiler.Errors; + +namespace UniversalParserHelper +{ + public static class StringResources + { + private static string prefix = "PASCALABCPARSER_"; + public static string Get(string Id) + { + string ret = PascalABCCompiler.StringResources.Get(prefix + Id); + if (ret == prefix + Id) + return Id; + else + return ret; + } + } + public abstract class UniversalParserHelper + { + private const int max_char_const = 0xFFFF; + // SSM: Errors инициализируется в другом месте - сюда только передается! + public List errors; + public List warnings; + public System.Collections.Stack NodesStack; // SSM: для каких-то вспомогательных целей в двух правилах + public bool build_tree_for_formatter = false; + public bool build_tree_for_format_strings = false; + public string CurrentFileName; + public List compilerDirectives; + + public List pascalABC_var_statements; + public List pascalABC_type_declarations; + public UniversalParserHelper() + { + NodesStack = new System.Collections.Stack(); + pascalABC_var_statements = new List(); + pascalABC_type_declarations = new List(); + } + public string directive_parameter(string s) + { + var ind = s.IndexOf(" "); + if (ind < 0) + return ""; + else + { + s = s.Substring(ind + 1); + s = s.TrimEnd('}'); + return s; + } + } + public ident create_directive_name(string text, SourceContext sc) + { + ident dn = new ident(new string(text.ToCharArray(1, text.Length - 1))); + dn.source_context = sc; + return dn; + } + + public string RemoveThousandsDelimiter(string s, SourceContext sc) + { + if (s.EndsWith("_") || s.Contains("__")) + { + var errstr = ParserErrorsStringResources.Get("BAD_FORMED_NUM_CONST"); + errors.Add(new SyntaxError(errstr, CurrentFileName, sc, null)); + } + + return s.Replace("_", ""); + } + private const_node create_int_const(string text, SourceContext sc, System.Globalization.NumberStyles NumberStyles) + { + //таблица целых констант на уровне синтаксиса + // не может быть - 0 + + // 32--------16----8----|----8----16--------32----------------64(bits) + // [ int64 )[ int32 ]( int64 ]( uint64 ] + text = RemoveThousandsDelimiter(text, sc); + if (NumberStyles == System.Globalization.NumberStyles.HexNumber) + text = text.Substring(1); + const_node cn = new int32_const(); + if (text.Length < 8) + (cn as int32_const).val = Int32.Parse(text, NumberStyles); + else + { + try + { + UInt64 uint64 = UInt64.Parse(text, NumberStyles); + if (uint64 <= Int32.MaxValue) + (cn as int32_const).val = (Int32)uint64; + else + if (uint64 <= Int64.MaxValue) + cn = new int64_const((Int64)uint64); + else + cn = new uint64_const(uint64); + } + catch (Exception) + { + if (NumberStyles == System.Globalization.NumberStyles.HexNumber) + errors.Add(new BadHex(CurrentFileName, sc, null)); + else + errors.Add(new BadInt(CurrentFileName, sc, null)); + } + } + cn.source_context = sc; + return cn; + } + public const_node create_int_const(string text, SourceContext sc) + { + return create_int_const(text, sc, System.Globalization.NumberStyles.Integer); + } + public const_node create_double_const(string text, SourceContext sc) + { + const_node cn = null; + try + { + System.Globalization.NumberFormatInfo sgnfi = new System.Globalization.NumberFormatInfo(); + sgnfi.NumberDecimalSeparator = "."; + + text = RemoveThousandsDelimiter(text, sc); + + double val = double.Parse(text, sgnfi); + cn = new double_const(val); + cn.source_context = sc; + } + catch (Exception) + { + errors.Add(new BadFloat(CurrentFileName, sc, null)); + } + return cn; + } + public const_node create_bigint_const(string text, SourceContext sc) + { + text = RemoveThousandsDelimiter(text, sc); + + var txt = text.Substring(0, text.Length - 2); + var cn = new bigint_const(); + try + { + cn.val = System.UInt64.Parse(txt); + } + catch (Exception) + { + errors.Add(new BadInt(CurrentFileName, sc, null)); + } + cn.source_context = sc; + return cn; + } + public ident create_ident(string text, SourceContext sc) + { + if (text[0] == '&') + text = text.Substring(1); + ident id = new ident(text); + id.source_context = sc; + return id; + } + + public string ReplaceSpecialSymbols(string text) + { + text = text.Replace("''", "'"); + return text; + } + + public char_const create_char_const(string text, SourceContext sc) + { + string char_text = new string(text.ToCharArray(1, text.Length - 2)); + char_text = ReplaceSpecialSymbols(char_text); + char_const ct = new char_const(); + ct.source_context = sc; + if (char_text.Length == 1) + { + ct.cconst = char_text[0]; + return ct; + } + return null; + } + + public sharp_char_const create_sharp_char_const(string text, SourceContext sc) + { + string int_text = new string(text.ToCharArray(1, text.Length - 1)); + sharp_char_const scc = null; + int val = 0; + if (int.TryParse(int_text, out val)) + { + if (val > max_char_const) + { + scc = new sharp_char_const(0); + errors.Add(new TooBigCharNumberInSharpCharConstant(CurrentFileName, sc, scc)); + } + else + scc = new sharp_char_const(val); + scc.source_context = sc; + } + else + { + errors.Add(new TooBigCharNumberInSharpCharConstant(CurrentFileName, sc, scc)); + } + return scc; + } + + public literal create_string_const(string text, SourceContext sc) + { + literal lt; + if (text.Length == 3 && text[0] == '\'' && text[2] == '\'') + { + lt = new char_const(text[1]); + lt.source_context = sc; + return lt; + } + text = ReplaceSpecialSymbols(text.Substring(1, text.Length - 2)); + lt = new string_const(text); + lt.source_context = sc; + return lt; + } + + public literal create_format_string_const(string text, SourceContext sc) + { + literal lt; + text = ReplaceSpecialSymbols(text.Substring(2, text.Length - 3)); + lt = new string_const(text); + (lt as string_const).IsInterpolated = true; + lt.source_context = sc; + return lt; + } + + public void AddError(string message, LexLocation loc) + { + errors.Add(new SyntaxError(message, CurrentFileName, loc, null)); + } + public string CreateErrorString(string yytext, LexLocation yyloc, params object[] args) + { + string prefix = ""; + if (yytext != "") + prefix = StringResources.Get("FOUND{0}"); + else + prefix = StringResources.Get("FOUNDEOF"); + + if (this.build_tree_for_format_strings && prefix == StringResources.Get("FOUNDEOF")) + { + yytext = "}"; + prefix = StringResources.Get("FOUND{0}"); + } + + // Преобразовали в список строк - хорошо + string expected = String.Join(", ", args.Skip(1).Select(x => x.ToString())); + + var ExpectedString = StringResources.Get("EXPECTED{1}"); + + // string w = string.Join(" или ", tokens.Select(s => ConvertToHumanName((string)s))); + + return string.Format(prefix + ExpectedString, "'" + yytext + "'", expected); + } + /* public string CreateErrorString(string yytext, LexLocation yyloc, params object[] args) + { + string expected = String.Join(", ", args.Skip(1).Select(x => x.ToString())); + string err = $"PARSER ERROR \"{yytext}\" AT LINE #{yyloc.StartLine}: EXPECTED {expected}, FOUND {args[0]}"; + return err; + }*/ + public List ident_list11(object lr1, object lr3) + { + List ar = (List)lr3; + ar.Insert(0, lr1); + return ar; + } + + public List ident_list12(object lr0) + { + List ar = new List(); + ar.Add(lr0); + return ar; + } + + public List ident_list21(object lr0, object lr2) + { + List ar = (List)lr0; + ar.Add(lr2); + return ar; + } + + public List ident_list13(object lr1, object lr3, object lr5) + { + List ar = (List)lr5; + //named_type_reference n_t_r = (named_type_reference)lr3; + var_def_statement vds = new var_def_statement(); + vds.vars = new ident_list(); + vds.vars.idents.Add((ident)lr1); + vds.vars_type = (type_definition)lr3;//n_t_r; + ar.Insert(0, vds); + return ar; + } + + public List ident_list14(object lr1, object lr3) + { + List ar = new List(); + //named_type_reference n_t_r = (named_type_reference)lr3; + var_def_statement vds = new var_def_statement(); + vds.vars = new ident_list(); + vds.vars.idents.Add((ident)lr1); + vds.vars_type = (type_definition)lr3; + ar.Add(vds); + return ar; + } + public void create_source_context(object to, object left, object right) + { + if (to != null) + ((syntax_tree_node)to).source_context = get_source_context(left, right); + } + + public SourceContext get_source_context(object left, object right) + { + //debug + /*if (left == null && right!=null) + { + Console.WriteLine("\n\rerror: left is null(create_source_context)!\n\r"); + Console.WriteLine(((syntax_tree_node)right).source_context.ToString()); + } + if (right == null && left!=null) + { + Console.WriteLine("\n\rerror: right is null(create_source_context)!\n\r"); + Console.WriteLine(((syntax_tree_node)left).source_context.ToString()); + } + if (((syntax_tree_node)left).source_context == null) + { + Console.WriteLine("\n\rerror: source_context is null!(left)\n\r"); + return null; + } + if (((syntax_tree_node)right).source_context == null) + { + Console.WriteLine("\n\rerror: source_context is null!(right)\n\r"); + return null; + } + */ + if ((left == null) || (right == null) || (((syntax_tree_node)left).source_context == null) || (((syntax_tree_node)right).source_context == null)) + return null; + return new SourceContext(((syntax_tree_node)left).source_context, ((syntax_tree_node)right).source_context); + } + + public void create_source_context_left(object to, object left) + { + file_position fp = ((syntax_tree_node)left).source_context.begin_position; + ((syntax_tree_node)to).source_context = new SourceContext(fp.line_num, fp.column_num, fp.line_num, fp.column_num, 0, 0); + } + + public void create_source_context_right(object to, object right) + { + file_position fp = ((syntax_tree_node)right).source_context.end_position; + ((syntax_tree_node)to).source_context = new SourceContext(fp.line_num, fp.column_num, fp.line_num, fp.column_num, 0, 0); + } + + public object sc_not_null(object o1, object o2) + { + if (o1 != null) + if (((syntax_tree_node)o1).source_context != null) return o1; + return o2; + } + + public object sc_not_null(object o1, object o2, object o3) + { + if (o1 != null) + if (((syntax_tree_node)o1).source_context != null) return o1; + if (o2 != null) + if (((syntax_tree_node)o2).source_context != null) return o2; + return o3; + } + + public object sc_not_null(params object[] arr) + { + foreach (object o in arr) + if (o != null) + if (((syntax_tree_node)o).source_context != null) return o; + return null; + } + + public void assign_source_context(object to, object from) + { + //debug + //if (((tree_node)from).source_context==null) Console.WriteLine("\n\rerror: from sc is null(assign_source_context)!\n\r"); + if (to != null && from != null) + ((syntax_tree_node)to).source_context = ((syntax_tree_node)from).source_context; + } + } +} diff --git a/UniversalParserHelper/UniversalParserHelper.csproj b/UniversalParserHelper/UniversalParserHelper.csproj new file mode 100644 index 000000000..42c9a9828 --- /dev/null +++ b/UniversalParserHelper/UniversalParserHelper.csproj @@ -0,0 +1,76 @@ + + + + + Debug + AnyCPU + {E862A9EF-836B-414B-AAC4-9D207CABDC82} + Library + Properties + UniversalParserHelper + UniversalParserHelper + v4.0 + 512 + true + + + + true + full + false + ..\bin\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + ..\bin\ + TRACE + prompt + 4 + + + false + + + + + + + + + + + + + + + + + {44a01f9e-dce7-470c-aae5-c3de0ccbee3b} + Errors + + + {2de2842f-0912-4251-bc0f-480854c44a13} + Localization + + + {af2efd7b-69dd-4b43-af65-b59b29349c23} + ParserTools + + + {ad4e1292-2537-467a-934d-e9fda3f18d87} + ShiftReduceParser + + + {c2cac65a-b2ae-4ccc-b067-e6b8e75df73a} + SyntaxTree + + + + + + + \ No newline at end of file diff --git a/Utils/NodesGeneratorNew/tree.nin b/Utils/NodesGeneratorNew/tree.nin index af4b035d2..396735da1 100644 Binary files a/Utils/NodesGeneratorNew/tree.nin and b/Utils/NodesGeneratorNew/tree.nin differ diff --git a/VisualPascalABCNET/AutoInsertCode/AutoInsertCode.cs b/VisualPascalABCNET/AutoInsertCode/AutoInsertCode.cs index 2dffc6892..fd5d5d384 100644 --- a/VisualPascalABCNET/AutoInsertCode/AutoInsertCode.cs +++ b/VisualPascalABCNET/AutoInsertCode/AutoInsertCode.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using ICSharpCode.TextEditor.Document; using ICSharpCode.TextEditor; using System.Text.RegularExpressions; +using System.Drawing.Imaging; namespace VisualPascalABC { @@ -250,7 +251,7 @@ namespace VisualPascalABC { string cur, next, prev; GetCurNextLines(out cur, out next, out prev); - if (ta.Caret.Column >= cur.Length) + if (ta.Caret.Column >= cur.Length && prev != null) { var prevTrimEnd = prev.TrimEnd(); // если prev заканчивается на then, а cur не начинается с begin, то отступ назад diff --git a/VisualPascalABCNET/DS/FoldingStrategy.cs b/VisualPascalABCNET/DS/FoldingStrategy.cs index 60e090f0f..09c4b4857 100644 --- a/VisualPascalABCNET/DS/FoldingStrategy.cs +++ b/VisualPascalABCNET/DS/FoldingStrategy.cs @@ -11,7 +11,7 @@ namespace ICSharpCode.TextEditor.Document /// /* public class TestFoldingStrategy : IFoldingStrategy { - public List GenerateFoldMarkers(IDocument document, string fileName, object parseInformation) + public List GenerateFoldMarkers(IDocument document, string file_name, object parseInformation) { List l = new List(); Stack offsetStack = new Stack(); diff --git a/VisualPascalABCNET/DS/NavigationManager.cs b/VisualPascalABCNET/DS/NavigationManager.cs index 2baa4a95c..361138ca3 100644 --- a/VisualPascalABCNET/DS/NavigationManager.cs +++ b/VisualPascalABCNET/DS/NavigationManager.cs @@ -23,7 +23,7 @@ namespace VisualPascalABC { SourceLocation sl = null; /*if (lines_to_locations.TryGetValue(LineNum, out sl)) - if (sl.FileName == FileName) + if (sl.file_name == file_name) { sl.BeginPosition.Column = sl.EndPosition.Column = ColumnNum; locations.Remove(sl); diff --git a/VisualPascalABCNET/DS/RunManager/RunManager.cs b/VisualPascalABCNET/DS/RunManager/RunManager.cs index 16b9f7040..c93678c76 100644 --- a/VisualPascalABCNET/DS/RunManager/RunManager.cs +++ b/VisualPascalABCNET/DS/RunManager/RunManager.cs @@ -243,7 +243,7 @@ namespace VisualPascalABC public void SendText(string FileName, string Text) { - //messageServer.SendText(FileName, Text); + //messageServer.SendText(file_name, Text); } /*private void MessageQueueReceive_Callback(IAsyncResult ar) diff --git a/VisualPascalABCNET/DS/VisualEnvironmentCompiler.cs b/VisualPascalABCNET/DS/VisualEnvironmentCompiler.cs index 9f523871c..84864c6b2 100644 --- a/VisualPascalABCNET/DS/VisualEnvironmentCompiler.cs +++ b/VisualPascalABCNET/DS/VisualEnvironmentCompiler.cs @@ -250,7 +250,7 @@ namespace VisualPascalABC return ed.Document.TextContent; if (!File.Exists(FileName)) return null; - /*TextReader tr = new StreamReader(FileName, System.Text.Encoding.GetEncoding(1251)); + /*TextReader tr = new StreamReader(file_name, System.Text.Encoding.GetEncoding(1251)); string Text = tr.ReadToEnd(); tr.Close();*/ string Text = PascalABCCompiler.FileReader.ReadFileContent(FileName, null); diff --git a/VisualPascalABCNET/DockContent/Avalon/CodeFileDocumentTextEditorControl.cs b/VisualPascalABCNET/DockContent/Avalon/CodeFileDocumentTextEditorControl.cs index 6ccc0bd93..c1cdee7da 100644 --- a/VisualPascalABCNET/DockContent/Avalon/CodeFileDocumentTextEditorControl.cs +++ b/VisualPascalABCNET/DockContent/Avalon/CodeFileDocumentTextEditorControl.cs @@ -104,16 +104,16 @@ namespace VisualPascalABC.Avalon public void UpdateFolding() { - CodeCompletionParserController.open_files[this.FileName] = true; + CodeCompletionParserController.open_files[this.file_name] = true; } - public void UpdateFolding(object parseInfo, string fileName) + public void UpdateFolding(object parseInfo, string file_name) { try { - if (EnableFolding && fileName == this.FileName) + if (EnableFolding && file_name == this.file_name) { - foldingManager.UpdateFoldings(fileName, parseInfo); + foldingManager.UpdateFoldings(file_name, parseInfo); refresh_Folding(); } } diff --git a/VisualPascalABCNET/DockContent/CodeFileDocument.cs b/VisualPascalABCNET/DockContent/CodeFileDocument.cs index 6cd480e9b..bac5b7fe5 100644 --- a/VisualPascalABCNET/DockContent/CodeFileDocument.cs +++ b/VisualPascalABCNET/DockContent/CodeFileDocument.cs @@ -514,7 +514,7 @@ namespace VisualPascalABC List Warnings = new List(); //PascalABCCompiler.SyntaxTree.syntax_tree_node sn = // MainForm.VisualEnvironmentCompiler.Compiler.ParsersController.Compile( - // FileName, TextEditor.Text, null, Errors, PascalABCCompiler.Parsers.ParseMode.Normal); + // file_name, TextEditor.Text, null, Errors, PascalABCCompiler.Parsers.ParseMode.Normal); PascalABCCompiler.SyntaxTree.compilation_unit sn = CodeCompletion.CodeCompletionController.ParsersController.GetCompilationUnit( VisualPABCSingleton.MainForm._currentCodeFileDocument.FileName, diff --git a/VisualPascalABCNET/DockContent/ErrorsListWindowForm.cs b/VisualPascalABCNET/DockContent/ErrorsListWindowForm.cs index 45eb9f14e..a49ca88ca 100644 --- a/VisualPascalABCNET/DockContent/ErrorsListWindowForm.cs +++ b/VisualPascalABCNET/DockContent/ErrorsListWindowForm.cs @@ -134,7 +134,7 @@ namespace VisualPascalABC MainForm.ExecuteErrorPos(er.SourceLocation, 2); else // ImageIndex==2 - ошибка выполнения MainForm.ExecuteErrorPos(er.SourceLocation, 1); - //OpenFile(er.SourceLocation.FileName); + //OpenFile(er.SourceLocation.file_name); //(tabControl1.SelectedTab.ag as CodeFileDocumentControl).TextEditor.CaretPosition(er.SourceLocation.BeginPosition.Line,er.SourceLocation.BeginPosition.Column); } } diff --git a/VisualPascalABCNET/Form1.cs b/VisualPascalABCNET/Form1.cs index f91d371fa..e1667fb9c 100644 --- a/VisualPascalABCNET/Form1.cs +++ b/VisualPascalABCNET/Form1.cs @@ -612,7 +612,7 @@ namespace VisualPascalABC case VisualEnvironmentCompilerAction.OpenFile: return WorkbenchServiceFactory.FileService.OpenFile((string)obj, null); case VisualEnvironmentCompilerAction.GetDirectory: - string s=VisualEnvironmentCompiler.Compiler.CompilerOptions.StandartDirectories[(string)obj] as string; + string s=VisualEnvironmentCompiler.Compiler.CompilerOptions.StandardDirectories[(string)obj] as string; if (s != null) return s; return WorkbenchStorage.StandartDirectories[(string)obj] as string; diff --git a/VisualPascalABCNET/FormsDesignerBinding/FormsDesigner/Src/Services/TypeResolutionService.cs b/VisualPascalABCNET/FormsDesignerBinding/FormsDesigner/Src/Services/TypeResolutionService.cs index f7e882903..ed61dfd85 100644 --- a/VisualPascalABCNET/FormsDesignerBinding/FormsDesigner/Src/Services/TypeResolutionService.cs +++ b/VisualPascalABCNET/FormsDesignerBinding/FormsDesigner/Src/Services/TypeResolutionService.cs @@ -65,9 +65,9 @@ namespace ICSharpCode.FormsDesigner.Services } /* We don't need to debug controls inside the forms designer files = Directory.GetFiles(Path.GetTempPath(), "*.pdb"); - foreach (string fileName in files) { + foreach (string file_name in files) { try { - File.Delete(fileName); + File.Delete(file_name); } catch {} }*/ } @@ -268,7 +268,7 @@ namespace ICSharpCode.FormsDesigner.Services File.Copy(fileName, tempPath); /* We don't need to debug controls inside the forms designer - string pdbpath = Path.GetDirectoryName(fileName) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(fileName) + ".pdb"; + string pdbpath = Path.GetDirectoryName(file_name) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(file_name) + ".pdb"; if (File.Exists(pdbpath)) { string newpdbpath = Path.GetTempPath() + Path.DirectorySeparatorChar + Path.GetFileName(pdbpath); try { diff --git a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionActions.cs b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionActions.cs index 64e79aa3f..8911199f3 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionActions.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionActions.cs @@ -600,7 +600,7 @@ namespace VisualPascalABC List Errors = new List(); //PascalABCCompiler.SyntaxTree.syntax_tree_node sn = // MainForm.VisualEnvironmentCompiler.Compiler.ParsersController.Compile( - // FileName, TextEditor.Text, null, Errors, PascalABCCompiler.Parsers.ParseMode.Normal); + // file_name, TextEditor.Text, null, Errors, PascalABCCompiler.Parsers.ParseMode.Normal); string text = WorkbenchServiceFactory.Workbench.VisualEnvironmentCompiler.SourceFilesProvider(VisualPABCSingleton.MainForm.CurrentCodeFileDocument.FileName, PascalABCCompiler.SourceFileOperation.GetText) as string; PascalABCCompiler.SyntaxTree.compilation_unit cu = CodeCompletion.CodeCompletionController.ParsersController.GetCompilationUnitForFormatter( diff --git a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionKeyHandler.cs b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionKeyHandler.cs index 2f0d9c1e8..7e489ef9b 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionKeyHandler.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionKeyHandler.cs @@ -178,8 +178,9 @@ namespace VisualPascalABC CodeCompletion.DomConverter dconv = (CodeCompletion.DomConverter)CodeCompletion.CodeCompletionController.comp_modules[editor.FileName]; if (dconv != null) { + // TODO: check endl error | added null check EVA CodeCompletion.SymScope ss = dconv.FindScopeByLocation(editor.ActiveTextAreaControl.TextArea.Caret.Line + 1, editor.ActiveTextAreaControl.TextArea.Caret.Column + 1); - ss.IncreaseEndLine(); + ss?.IncreaseEndLine(); } } catch diff --git a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionParserController.cs b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionParserController.cs index aff328440..b3dfd8f0c 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionParserController.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionParserController.cs @@ -172,7 +172,7 @@ namespace VisualPascalABC open_files[FileName] = false; if (dc.is_compiled) { - //CodeCompletion.CodeCompletionController.comp_modules.Remove(FileName); + //CodeCompletion.CodeCompletionController.comp_modules.Remove(file_name); if (tmp != null && tmp.visitor.entry_scope != null) { tmp.visitor.entry_scope.Clear(); diff --git a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionProvider.cs b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionProvider.cs index 3fec12767..06b93f399 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionProvider.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/CodeCompletionProvider.cs @@ -236,7 +236,7 @@ namespace VisualPascalABC if (dconv == null) return new List(); List lst = InternalFindReferences(fileName, e, line, column, for_refact); //if (lst != null && expr != null && for_refact) - //lst.Insert(0,new SymbolsViewerSymbol(new PascalABCCompiler.SourceLocation(fileName,line+1,column,line+1,column+expr.Length),ImagesProvider.IconNumberGotoText)); + //lst.Insert(0,new SymbolsViewerSymbol(new PascalABCCompiler.SourceLocation(file_name,line+1,column,line+1,column+expr.Length),ImagesProvider.IconNumberGotoText)); return lst; } @@ -520,7 +520,7 @@ namespace VisualPascalABC foreach (SymInfo mi in mis) { - if (mi.not_include) continue; + if (mi == null || mi.not_include) continue; if (cache.Contains(mi.name + mi.kind)) continue; @@ -572,7 +572,7 @@ namespace VisualPascalABC controller = new CodeCompletion.CodeCompletionController(); int off = textArea.Caret.Offset; string text = textArea.Document.TextContent.Substring(0, textArea.Caret.Offset); - //controller.Compile(fileName, text /*+ ")))));end."*/); + //controller.Compile(file_name, text /*+ ")))));end."*/); FileName = fileName; Text = text; ICompletionData[] data = GetCompletionData(off, text, textArea.Caret.Line, textArea.Caret.Column, charTyped, keyw); CodeCompletion.AssemblyDocCache.CompleteDocumentation(); @@ -626,7 +626,7 @@ namespace VisualPascalABC controller = new CodeCompletion.CodeCompletionController(); int off = textArea.Caret.Offset; string text = textArea.Document.TextContent.Substring(0, textArea.Caret.Offset); - //controller.Compile(fileName, text /*+ ")))));end."*/); + //controller.Compile(file_name, text /*+ ")))));end."*/); FileName = fileName; Text = text; ICompletionData[] data = GetCompletionDataByFirst(off, text, textArea.Caret.Line, textArea.Caret.Column, charTyped, keyw); CodeCompletion.AssemblyDocCache.CompleteDocumentation(); diff --git a/VisualPascalABCNET/IB/CodeCompletion/QuickClassBrowserPanel.cs b/VisualPascalABCNET/IB/CodeCompletion/QuickClassBrowserPanel.cs index db97ca316..59ae896d2 100644 --- a/VisualPascalABCNET/IB/CodeCompletion/QuickClassBrowserPanel.cs +++ b/VisualPascalABCNET/IB/CodeCompletion/QuickClassBrowserPanel.cs @@ -317,7 +317,7 @@ namespace VisualPascalABC { // Still needed ? /*if (currentCompilationUnit == null) { - currentCompilationUnit = (ICompilationUnit)ParserService.GetParseInformation(Path.GetFullPath(textAreaControl.FileName)).MostRecentCompilationUnit; + currentCompilationUnit = (ICompilationUnit)ParserService.GetParseInformation(Path.GetFullPath(textAreaControl.file_name)).MostRecentCompilationUnit; }*/ autoselect = false; @@ -803,7 +803,7 @@ namespace VisualPascalABC { //textAreaControl.ActiveTextAreaControl.Caret.Position = new ICSharpCode.TextEditor.TextLocation(item.Column, item.Line); //textAreaControl.ActiveTextAreaControl.TextArea.Focus(); - //VisualPABCSingleton.MainForm.ExecuteSourceLocationAction(new PascalABCCompiler.SourceLocation(textAreaControl.FileName,item.Line+1,item.Column, + //VisualPABCSingleton.MainForm.ExecuteSourceLocationAction(new PascalABCCompiler.SourceLocation(textAreaControl.file_name,item.Line+1,item.Column, // item.EndLine+1,item.Column),VisualPascalABCPlugins.SourceLocationAction.NavigationGoto); VisualPABCSingleton.MainForm.VisualEnvironmentCompiler.ExecuteSourceLocationAction( new PascalABCCompiler.SourceLocation(textAreaControl.FileName, item.Line + 1, item.Column + 1, item.Line + 1, item.Column + 1), VisualPascalABCPlugins.SourceLocationAction.GotoBeg); diff --git a/VisualPascalABCNET/IB/Debugger/Bookmarks.cs b/VisualPascalABCNET/IB/Debugger/Bookmarks.cs index 647e2e881..59f92fd2b 100644 --- a/VisualPascalABCNET/IB/Debugger/Bookmarks.cs +++ b/VisualPascalABCNET/IB/Debugger/Bookmarks.cs @@ -156,7 +156,7 @@ namespace VisualPascalABC { ITextEditorControlProvider tecp = viewContent as ITextEditorControlProvider; if (tecp != null) - SetPosition(tecp.TextEditorControl.FileName, tecp.TextEditorControl.Document, makerStartLine, makerStartColumn, makerEndLine, makerEndColumn); + SetPosition(tecp.TextEditorControl.file_name, tecp.TextEditorControl.Document, makerStartLine, makerStartColumn, makerEndLine, makerEndColumn); else Remove(); }*/ @@ -269,7 +269,7 @@ namespace VisualPascalABC static int endLine; static int endColumn; - //public static void SetPosition(string fileName, IDocument document, int makerStartLine, int makerEndLine) + //public static void SetPosition(string file_name, IDocument document, int makerStartLine, int makerEndLine) public static void SetPosition(TextEditorControl ctrl, int makerStartLine) { try @@ -342,7 +342,7 @@ namespace VisualPascalABC static int endLine; static int endColumn; - //public static void SetPosition(string fileName, IDocument document, int makerStartLine, int makerEndLine) + //public static void SetPosition(string file_name, IDocument document, int makerStartLine, int makerEndLine) public static void SetPosition(TextEditorControl ctrl, int makerStartLine) { try @@ -426,7 +426,7 @@ namespace VisualPascalABC { ITextEditorControlProvider tecp = viewContent as ITextEditorControlProvider; if (tecp != null) - SetPosition(tecp.TextEditorControl.FileName, tecp.TextEditorControl.Document, makerStartLine, makerStartColumn, makerEndLine, makerEndColumn); + SetPosition(tecp.TextEditorControl.file_name, tecp.TextEditorControl.Document, makerStartLine, makerStartColumn, makerEndLine, makerEndColumn); else Remove(); }*/ diff --git a/VisualPascalABCNET/IB/Debugger/Debugger.cs b/VisualPascalABCNET/IB/Debugger/Debugger.cs index 730f6b672..faf555ba7 100644 --- a/VisualPascalABCNET/IB/Debugger/Debugger.cs +++ b/VisualPascalABCNET/IB/Debugger/Debugger.cs @@ -342,7 +342,7 @@ namespace VisualPascalABC } /// - /// Добавить Breakpoint в файл fileName строку line + /// Добавить Breakpoint в файл file_name строку line /// public Breakpoint AddBreakPoint(string fileName, int line, bool commonBreakpoint) { @@ -367,7 +367,7 @@ namespace VisualPascalABC } /// - /// Получить список Breakpointov в файле fileName + /// Получить список Breakpointov в файле file_name /// public List GetBreakpointsInFile(string fileName) { @@ -412,7 +412,7 @@ namespace VisualPascalABC dbg.ProcessExited += debugProcessExit; dbg.BreakpointHit += debugBreakpointHit; //if (brPoint != null) dbg.RemoveBreakpoint(brPoint); - this.FileName = sourceFileName;//Path.GetFileNameWithoutExtension(fileName) + ".pas"; + this.FileName = sourceFileName;//Path.GetFileNameWithoutExtension(file_name) + ".pas"; this.FullFileName = Path.Combine(Path.GetDirectoryName(fileName), this.FileName); this.ExeFileName = fileName; this.PrevFullFileName = FullFileName; @@ -460,7 +460,7 @@ namespace VisualPascalABC sourceFileName = workbench.VisualEnvironmentCompiler.Compiler.CompilerOptions.SourceFileName; else sourceFileName = ProjectFactory.Instance.CurrentProject.MainFile; - this.FileName = sourceFileName;//Path.GetFileNameWithoutExtension(fileName) + ".pas"; + this.FileName = sourceFileName;//Path.GetFileNameWithoutExtension(file_name) + ".pas"; this.FullFileName = Path.Combine(Path.GetDirectoryName(fileName), this.FileName); this.ExeFileName = fileName; CurrentLine = 0; @@ -469,7 +469,7 @@ namespace VisualPascalABC AssemblyHelper.LoadAssembly(fileName); dbg.ProcessStarted += debugProcessStarted; dbg.ProcessExited += debugProcessExit; - //brPoint = dbg.AddBreakpoint(FileName, frm.VisualEnvironmentCompiler.Compiler.BeginOffset); + //brPoint = dbg.AddBreakpoint(file_name, frm.VisualEnvironmentCompiler.Compiler.BeginOffset); try { debuggedProcess = dbg.DebugActiveProcess(handle, fileName); @@ -1762,7 +1762,7 @@ namespace VisualPascalABC { try { - //cur_brpt = dbg.AddBreakpoint(new SourcecodeSegment((frm.CurrentTabPage.ag as CodeFileDocumentControl).FileName,(frm.CurrentTabPage.ag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Line + 1,(frm.CurrentTabPage.Tag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Column + 1, + //cur_brpt = dbg.AddBreakpoint(new SourcecodeSegment((frm.CurrentTabPage.ag as CodeFileDocumentControl).file_name,(frm.CurrentTabPage.ag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Line + 1,(frm.CurrentTabPage.Tag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Column + 1, // (frm.CurrentTabPage.ag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Column+100), true); workbench.WidgetController.SetStartDebugDisabled(); currentBreakpoint = dbg.AddBreakpoint(WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.FileName, WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.Caret.Line + 1); diff --git a/VisualPascalABCNET/Projects/ProjectProperties.cs b/VisualPascalABCNET/Projects/ProjectProperties.cs index 2f8140a8e..4e7588fc9 100644 --- a/VisualPascalABCNET/Projects/ProjectProperties.cs +++ b/VisualPascalABCNET/Projects/ProjectProperties.cs @@ -224,7 +224,7 @@ namespace VisualPascalABC catch { } - this.tbAppIcon.Text = Path.GetFileName(openFileDialog1.FileName);//PascalABCCompiler.Tools.RelativePathTo(ProjectFactory.Instance.CurrentProject.ProjectDirectory, openFileDialog1.FileName); + this.tbAppIcon.Text = Path.GetFileName(openFileDialog1.FileName);//PascalABCCompiler.Tools.RelativePathTo(ProjectFactory.Instance.CurrentProject.ProjectDirectory, openFileDialog1.file_name); } } diff --git a/VisualPascalABCNET/Properties/Resources.Designer.cs b/VisualPascalABCNET/Properties/Resources.Designer.cs index 852470651..d861da357 100644 --- a/VisualPascalABCNET/Properties/Resources.Designer.cs +++ b/VisualPascalABCNET/Properties/Resources.Designer.cs @@ -19,7 +19,7 @@ namespace VisualPascalABC.Properties { // с помощью такого средства, как ResGen или Visual Studio. // Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen // с параметром /str или перестройте свой проект VS. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { diff --git a/VisualPascalABCNET/Properties/Settings.Designer.cs b/VisualPascalABCNET/Properties/Settings.Designer.cs index 4537e4b3a..15f690152 100644 --- a/VisualPascalABCNET/Properties/Settings.Designer.cs +++ b/VisualPascalABCNET/Properties/Settings.Designer.cs @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------ // // Этот код создан программой. -// Исполняемая версия:4.0.30319.1 +// Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. @@ -12,7 +12,7 @@ namespace VisualPascalABC.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.10.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); diff --git a/VisualPascalABCNET/VisualPascalABCNET.csproj b/VisualPascalABCNET/VisualPascalABCNET.csproj index dcd72eb67..554fa8abb 100644 --- a/VisualPascalABCNET/VisualPascalABCNET.csproj +++ b/VisualPascalABCNET/VisualPascalABCNET.csproj @@ -425,6 +425,7 @@ ABCHealth.cs + Designer Designer diff --git a/VisualPascalABCNET/Workbench/BuildService.cs b/VisualPascalABCNET/Workbench/BuildService.cs index 4e7f6dc99..16c2266b0 100644 --- a/VisualPascalABCNET/Workbench/BuildService.cs +++ b/VisualPascalABCNET/Workbench/BuildService.cs @@ -71,13 +71,13 @@ namespace VisualPascalABC if (Path.GetDirectoryName(CompilerOptions1.SourceFileName).ToLower() == ((string)WorkbenchStorage.StandartDirectories[Constants.LibSourceDirectoryIdent]).ToLower()) Workbench.VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate = false; if (RuntimeServicesModule != null) - CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); + CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandardModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); string ofn = Workbench.VisualEnvironmentCompiler.Compile(CompilerOptions1); Workbench.VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate = savePCU; if (RuntimeServicesModule != null) - CompilerOptions1.RemoveStandartModuleAtIndex(CompilerOptions1.StandartModules.Count - 1); + CompilerOptions1.RemoveStandardModuleAtIndex(CompilerOptions1.StandardModules.Count - 1); if (Workbench.VisualEnvironmentCompiler.Compiler.ErrorsList.Count != 0 || Workbench.VisualEnvironmentCompiler.Compiler.Warnings.Count != 0) { @@ -111,9 +111,9 @@ namespace VisualPascalABC CompilerOptions1.RunWithEnvironment = RunWithEnvironment; //string runtimeModuleFileName = CompilerOptions1.SearchDirectory + "\\" + RuntimeServicesModule; //if (RuntimeServicesModule!=null && File.Exists(runtimeModuleFileName)) - // CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); + // CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); if (RuntimeServicesModule != null) - CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); + CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandardModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); ErrorsList.Clear(); @@ -127,7 +127,7 @@ namespace VisualPascalABC Workbench.VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate = savePCU; if (RuntimeServicesModule != null) - CompilerOptions1.RemoveStandartModuleAtIndex(CompilerOptions1.StandartModules.Count - 1); + CompilerOptions1.RemoveStandardModuleAtIndex(CompilerOptions1.StandardModules.Count - 1); if (Workbench.VisualEnvironmentCompiler.Compiler.ErrorsList.Count != 0 || Workbench.VisualEnvironmentCompiler.Compiler.Warnings.Count != 0) { @@ -159,16 +159,16 @@ namespace VisualPascalABC CompilerOptions1.RunWithEnvironment = RunWithEnvironment; //string runtimeModuleFileName = CompilerOptions1.SearchDirectory + "\\" + RuntimeServicesModule; //if (RuntimeServicesModule!=null && File.Exists(runtimeModuleFileName)) - // CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); + // CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); if (__RuntimeServicesModule != null) - CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); + CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandardModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); ErrorsList.Clear(); //CompilerOptions1.SavePCUInThreadPull = true; __savePCU = Workbench.VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate; - //if (Path.GetDirectoryName(FileName).ToLower() == ((string)StandartDirectories[Constants.LibSourceDirectoryIdent]).ToLower()) + //if (Path.GetDirectoryName(file_name).ToLower() == ((string)StandartDirectories[Constants.LibSourceDirectoryIdent]).ToLower()) // VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate = false; Workbench.VisualEnvironmentCompiler.Compiler.OnChangeCompilerState += CompilationOnChangeCompilerState; @@ -195,9 +195,9 @@ namespace VisualPascalABC CompilerOptions1.RunWithEnvironment = RunWithEnvironment; //string runtimeModuleFileName = CompilerOptions1.SearchDirectory + "\\" + RuntimeServicesModule; //if (RuntimeServicesModule!=null && File.Exists(runtimeModuleFileName)) - // CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); + // CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); if (__RuntimeServicesModule != null) - CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); + CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandardModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); ErrorsList.Clear(); @@ -267,7 +267,7 @@ namespace VisualPascalABC Workbench.VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate = __savePCU; if (__RuntimeServicesModule != null) - CompilerOptions1.RemoveStandartModuleAtIndex(CompilerOptions1.StandartModules.Count - 1); + CompilerOptions1.RemoveStandardModuleAtIndex(CompilerOptions1.StandardModules.Count - 1); if (Workbench.VisualEnvironmentCompiler.Compiler.ErrorsList.Count != 0 || Workbench.VisualEnvironmentCompiler.Compiler.Warnings.Count != 0) { diff --git a/VisualPascalABCNET/Workbench/DialogsService.cs b/VisualPascalABCNET/Workbench/DialogsService.cs index 6acbf6903..1229f9c46 100644 --- a/VisualPascalABCNET/Workbench/DialogsService.cs +++ b/VisualPascalABCNET/Workbench/DialogsService.cs @@ -40,7 +40,7 @@ namespace VisualPascalABC private void saveFileDialog1_FileOk(object sender, CancelEventArgs e) { - //ReplaceLastFile(CurrentSourceFileName, saveFileDialog1.FileName); + //ReplaceLastFile(CurrentSourceFileName, saveFileDialog1.file_name); string fn = Tools.FileNameToLower(saveFileDialog1.FileName); if (OpenDocuments.ContainsKey(fn) && OpenDocuments[fn] != CurrentCodeFileDocument) { diff --git a/VisualPascalABCNET/Workbench/FileOperations.cs b/VisualPascalABCNET/Workbench/FileOperations.cs index 97d04e0db..2462f4b0d 100644 --- a/VisualPascalABCNET/Workbench/FileOperations.cs +++ b/VisualPascalABCNET/Workbench/FileOperations.cs @@ -150,7 +150,7 @@ namespace VisualPascalABC visualStates.FileOpened = true;//????? if (!IsNewFile && !File.Exists(FileName)) { - //MessageBox.Show(string.Format(PascalABCCompiler.StringResources.Get("!FILE_NOT_FOUND{0}"), FileName), PascalABCCompiler.StringResources.Get("!ERROR"), MessageBoxButtons.OK, MessageBoxIcon.Warning); + //MessageBox.Show(string.Format(PascalABCCompiler.StringResources.Get("!FILE_NOT_FOUND{0}"), file_name), PascalABCCompiler.StringResources.Get("!ERROR"), MessageBoxButtons.OK, MessageBoxIcon.Warning); bool exists = false; foreach (string s in search_debug_paths) { @@ -189,7 +189,7 @@ namespace VisualPascalABC else if (!IsNewFile) { - //CheckErrorListAndClear((tabControl1.TabPages[TabIndex].ag as CodeFileDocumentControl).FileName); + //CheckErrorListAndClear((tabControl1.TabPages[TabIndex].ag as CodeFileDocumentControl).file_name); CurrentCodeFileDocument.FileName = FileName; if (!ProjectFactory.Instance.ProjectLoaded) SetTabPageText(CurrentCodeFileDocument); diff --git a/VisualPascalABCNET/Workbench/VisibilityService.cs b/VisualPascalABCNET/Workbench/VisibilityService.cs index 8a81df334..48b4c094d 100644 --- a/VisualPascalABCNET/Workbench/VisibilityService.cs +++ b/VisualPascalABCNET/Workbench/VisibilityService.cs @@ -460,8 +460,8 @@ namespace VisualPascalABC clicked_stop_debug_in_menu = false; this.mDEBUGENDToolStripMenuItem.Enabled = false; //Data fileInfo = debuggedPage.ag as CodeFileDocumentControl; - //debuggedPage.Text = Path.GetFileName(fileInfo.FileName); - //debuggedPage.ToolTipText = fileInfo.FileName; + //debuggedPage.Text = Path.GetFileName(fileInfo.file_name); + //debuggedPage.ToolTipText = fileInfo.file_name; SetTabPageText(debuggedPage); ChangeDebugButtons(false); SaveDebugContext(); diff --git a/VisualPascalABCNET/Workbench/WindowOperations.cs b/VisualPascalABCNET/Workbench/WindowOperations.cs index 9a6ae7191..a0b68f858 100644 --- a/VisualPascalABCNET/Workbench/WindowOperations.cs +++ b/VisualPascalABCNET/Workbench/WindowOperations.cs @@ -252,7 +252,7 @@ namespace VisualPascalABC SetTabPageText(edit); edit.SetHighlightingStrategyForFile(FileName); OpenDocuments.Add(Tools.FileNameToLower(FileName), edit); - //this.codeCompletionParserController.SetAsChanged(FileName); + //this.codeCompletionParserController.SetAsChanged(file_name); //ivan AddBreakPointHandler(edit, FileName); var RunService = WorkbenchServiceFactory.RunService; @@ -473,7 +473,7 @@ namespace VisualPascalABC AddEditorHandlers(edit); } WorkbenchServiceFactory.CodeCompletionParserController.RegisterFileForParsing(tabName + ".pas"); - //edit.FileName = FileName; + //edit.file_name = file_name; //SetTabPageText(edit); } @@ -598,7 +598,7 @@ namespace VisualPascalABC public void AddTextToOutputWindowSync(string fileName, string text) { - //BeginInvoke(new SetFileNameAndTextDelegate(AddTextToOutputWindow), fileName, text); + //BeginInvoke(new SetFileNameAndTextDelegate(AddTextToOutputWindow), file_name, text); Invoke(new SetFileNameAndTextDelegate(AddTextToOutputWindow), fileName, text); } diff --git a/VisualPascalABCNET/app.config b/VisualPascalABCNET/app.config index c59f59fe9..af5ee9e99 100644 --- a/VisualPascalABCNET/app.config +++ b/VisualPascalABCNET/app.config @@ -1,10 +1,10 @@ - + - - + + diff --git a/VisualPascalABCNETLinux/DS/FoldingStrategy.cs b/VisualPascalABCNETLinux/DS/FoldingStrategy.cs index 60e090f0f..09c4b4857 100644 --- a/VisualPascalABCNETLinux/DS/FoldingStrategy.cs +++ b/VisualPascalABCNETLinux/DS/FoldingStrategy.cs @@ -11,7 +11,7 @@ namespace ICSharpCode.TextEditor.Document /// /* public class TestFoldingStrategy : IFoldingStrategy { - public List GenerateFoldMarkers(IDocument document, string fileName, object parseInformation) + public List GenerateFoldMarkers(IDocument document, string file_name, object parseInformation) { List l = new List(); Stack offsetStack = new Stack(); diff --git a/VisualPascalABCNETLinux/DS/NavigationManager.cs b/VisualPascalABCNETLinux/DS/NavigationManager.cs index 2baa4a95c..361138ca3 100644 --- a/VisualPascalABCNETLinux/DS/NavigationManager.cs +++ b/VisualPascalABCNETLinux/DS/NavigationManager.cs @@ -23,7 +23,7 @@ namespace VisualPascalABC { SourceLocation sl = null; /*if (lines_to_locations.TryGetValue(LineNum, out sl)) - if (sl.FileName == FileName) + if (sl.file_name == file_name) { sl.BeginPosition.Column = sl.EndPosition.Column = ColumnNum; locations.Remove(sl); diff --git a/VisualPascalABCNETLinux/DS/RunManager/RunManager.cs b/VisualPascalABCNETLinux/DS/RunManager/RunManager.cs index 17db0787b..074407e69 100644 --- a/VisualPascalABCNETLinux/DS/RunManager/RunManager.cs +++ b/VisualPascalABCNETLinux/DS/RunManager/RunManager.cs @@ -246,7 +246,7 @@ namespace VisualPascalABC public void SendText(string FileName, string Text) { - //messageServer.SendText(FileName, Text); + //messageServer.SendText(file_name, Text); } /*private void MessageQueueReceive_Callback(IAsyncResult ar) diff --git a/VisualPascalABCNETLinux/DS/VisualEnvironmentCompiler.cs b/VisualPascalABCNETLinux/DS/VisualEnvironmentCompiler.cs index 013cbe90f..b76263f8b 100644 --- a/VisualPascalABCNETLinux/DS/VisualEnvironmentCompiler.cs +++ b/VisualPascalABCNETLinux/DS/VisualEnvironmentCompiler.cs @@ -250,7 +250,7 @@ namespace VisualPascalABC return ed.Document.TextContent; if (!File.Exists(FileName)) return null; - /*TextReader tr = new StreamReader(FileName, System.Text.Encoding.GetEncoding(1251)); + /*TextReader tr = new StreamReader(file_name, System.Text.Encoding.GetEncoding(1251)); string Text = tr.ReadToEnd(); tr.Close();*/ string Text = PascalABCCompiler.FileReader.ReadFileContent(FileName, null); diff --git a/VisualPascalABCNETLinux/DockContent/Avalon/CodeFileDocumentTextEditorControl.cs b/VisualPascalABCNETLinux/DockContent/Avalon/CodeFileDocumentTextEditorControl.cs index 6ccc0bd93..c1cdee7da 100644 --- a/VisualPascalABCNETLinux/DockContent/Avalon/CodeFileDocumentTextEditorControl.cs +++ b/VisualPascalABCNETLinux/DockContent/Avalon/CodeFileDocumentTextEditorControl.cs @@ -104,16 +104,16 @@ namespace VisualPascalABC.Avalon public void UpdateFolding() { - CodeCompletionParserController.open_files[this.FileName] = true; + CodeCompletionParserController.open_files[this.file_name] = true; } - public void UpdateFolding(object parseInfo, string fileName) + public void UpdateFolding(object parseInfo, string file_name) { try { - if (EnableFolding && fileName == this.FileName) + if (EnableFolding && file_name == this.file_name) { - foldingManager.UpdateFoldings(fileName, parseInfo); + foldingManager.UpdateFoldings(file_name, parseInfo); refresh_Folding(); } } diff --git a/VisualPascalABCNETLinux/DockContent/CodeFileDocument.cs b/VisualPascalABCNETLinux/DockContent/CodeFileDocument.cs index b3f762a62..c893da564 100644 --- a/VisualPascalABCNETLinux/DockContent/CodeFileDocument.cs +++ b/VisualPascalABCNETLinux/DockContent/CodeFileDocument.cs @@ -521,10 +521,10 @@ namespace VisualPascalABC List Warnings = new List(); //PascalABCCompiler.SyntaxTree.syntax_tree_node sn = // MainForm.VisualEnvironmentCompiler.Compiler.ParsersController.Compile( - // FileName, TextEditor.Text, null, Errors, PascalABCCompiler.Parsers.ParseMode.Normal); + // file_name, TextEditor.Text, null, Errors, PascalABCCompiler.Parsers.ParseMode.Normal); PascalABCCompiler.SyntaxTree.compilation_unit sn = CodeCompletion.CodeCompletionController.ParsersController.GetCompilationUnit( - VisualPABCSingleton.MainForm._currentCodeFileDocument.FileName, + VisualPABCSingleton.MainForm._currentCodeFileDocument.file_name, existing_text, //VisualPascalABC.Form1.Form1_object._currentCodeFileDocument.TextEditor.Text, Errors, Warnings); diff --git a/VisualPascalABCNETLinux/DockContent/ErrorsListWindowForm.cs b/VisualPascalABCNETLinux/DockContent/ErrorsListWindowForm.cs index e62a87333..1669874e0 100644 --- a/VisualPascalABCNETLinux/DockContent/ErrorsListWindowForm.cs +++ b/VisualPascalABCNETLinux/DockContent/ErrorsListWindowForm.cs @@ -140,7 +140,7 @@ namespace VisualPascalABC MainForm.ExecuteErrorPos(er.SourceLocation, 2); else // ImageIndex==2 - ошибка выполнения MainForm.ExecuteErrorPos(er.SourceLocation, 1); - //OpenFile(er.SourceLocation.FileName); + //OpenFile(er.SourceLocation.file_name); //(tabControl1.SelectedTab.ag as CodeFileDocumentControl).TextEditor.CaretPosition(er.SourceLocation.BeginPosition.Line,er.SourceLocation.BeginPosition.Column); } } diff --git a/VisualPascalABCNETLinux/Form1.cs b/VisualPascalABCNETLinux/Form1.cs index 917d7b35a..4859a9a56 100644 --- a/VisualPascalABCNETLinux/Form1.cs +++ b/VisualPascalABCNETLinux/Form1.cs @@ -711,7 +711,7 @@ namespace VisualPascalABC case VisualEnvironmentCompilerAction.OpenFile: return WorkbenchServiceFactory.FileService.OpenFile((string)obj, null); case VisualEnvironmentCompilerAction.GetDirectory: - string s=VisualEnvironmentCompiler.Compiler.CompilerOptions.StandartDirectories[(string)obj] as string; + string s=VisualEnvironmentCompiler.Compiler.CompilerOptions.StandardDirectories[(string)obj] as string; if (s != null) return s; return WorkbenchStorage.StandartDirectories[(string)obj] as string; diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionActions.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionActions.cs index 64e79aa3f..8911199f3 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionActions.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionActions.cs @@ -600,7 +600,7 @@ namespace VisualPascalABC List Errors = new List(); //PascalABCCompiler.SyntaxTree.syntax_tree_node sn = // MainForm.VisualEnvironmentCompiler.Compiler.ParsersController.Compile( - // FileName, TextEditor.Text, null, Errors, PascalABCCompiler.Parsers.ParseMode.Normal); + // file_name, TextEditor.Text, null, Errors, PascalABCCompiler.Parsers.ParseMode.Normal); string text = WorkbenchServiceFactory.Workbench.VisualEnvironmentCompiler.SourceFilesProvider(VisualPABCSingleton.MainForm.CurrentCodeFileDocument.FileName, PascalABCCompiler.SourceFileOperation.GetText) as string; PascalABCCompiler.SyntaxTree.compilation_unit cu = CodeCompletion.CodeCompletionController.ParsersController.GetCompilationUnitForFormatter( diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionParserController.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionParserController.cs index 63bbfe0df..fb4d5fd8e 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionParserController.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionParserController.cs @@ -177,7 +177,7 @@ namespace VisualPascalABC open_files[FileName] = false; if (dc.is_compiled) { - //CodeCompletion.CodeCompletionController.comp_modules.Remove(FileName); + //CodeCompletion.CodeCompletionController.comp_modules.Remove(file_name); if (tmp != null && tmp.visitor.entry_scope != null) { tmp.visitor.entry_scope.Clear(); diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionProvider.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionProvider.cs index 3fec12767..1431d2d40 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionProvider.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/CodeCompletionProvider.cs @@ -236,7 +236,7 @@ namespace VisualPascalABC if (dconv == null) return new List(); List lst = InternalFindReferences(fileName, e, line, column, for_refact); //if (lst != null && expr != null && for_refact) - //lst.Insert(0,new SymbolsViewerSymbol(new PascalABCCompiler.SourceLocation(fileName,line+1,column,line+1,column+expr.Length),ImagesProvider.IconNumberGotoText)); + //lst.Insert(0,new SymbolsViewerSymbol(new PascalABCCompiler.SourceLocation(file_name,line+1,column,line+1,column+expr.Length),ImagesProvider.IconNumberGotoText)); return lst; } @@ -572,7 +572,7 @@ namespace VisualPascalABC controller = new CodeCompletion.CodeCompletionController(); int off = textArea.Caret.Offset; string text = textArea.Document.TextContent.Substring(0, textArea.Caret.Offset); - //controller.Compile(fileName, text /*+ ")))));end."*/); + //controller.Compile(file_name, text /*+ ")))));end."*/); FileName = fileName; Text = text; ICompletionData[] data = GetCompletionData(off, text, textArea.Caret.Line, textArea.Caret.Column, charTyped, keyw); CodeCompletion.AssemblyDocCache.CompleteDocumentation(); @@ -626,7 +626,7 @@ namespace VisualPascalABC controller = new CodeCompletion.CodeCompletionController(); int off = textArea.Caret.Offset; string text = textArea.Document.TextContent.Substring(0, textArea.Caret.Offset); - //controller.Compile(fileName, text /*+ ")))));end."*/); + //controller.Compile(file_name, text /*+ ")))));end."*/); FileName = fileName; Text = text; ICompletionData[] data = GetCompletionDataByFirst(off, text, textArea.Caret.Line, textArea.Caret.Column, charTyped, keyw); CodeCompletion.AssemblyDocCache.CompleteDocumentation(); diff --git a/VisualPascalABCNETLinux/IB/CodeCompletion/QuickClassBrowserPanel.cs b/VisualPascalABCNETLinux/IB/CodeCompletion/QuickClassBrowserPanel.cs index db97ca316..59ae896d2 100644 --- a/VisualPascalABCNETLinux/IB/CodeCompletion/QuickClassBrowserPanel.cs +++ b/VisualPascalABCNETLinux/IB/CodeCompletion/QuickClassBrowserPanel.cs @@ -317,7 +317,7 @@ namespace VisualPascalABC { // Still needed ? /*if (currentCompilationUnit == null) { - currentCompilationUnit = (ICompilationUnit)ParserService.GetParseInformation(Path.GetFullPath(textAreaControl.FileName)).MostRecentCompilationUnit; + currentCompilationUnit = (ICompilationUnit)ParserService.GetParseInformation(Path.GetFullPath(textAreaControl.file_name)).MostRecentCompilationUnit; }*/ autoselect = false; @@ -803,7 +803,7 @@ namespace VisualPascalABC { //textAreaControl.ActiveTextAreaControl.Caret.Position = new ICSharpCode.TextEditor.TextLocation(item.Column, item.Line); //textAreaControl.ActiveTextAreaControl.TextArea.Focus(); - //VisualPABCSingleton.MainForm.ExecuteSourceLocationAction(new PascalABCCompiler.SourceLocation(textAreaControl.FileName,item.Line+1,item.Column, + //VisualPABCSingleton.MainForm.ExecuteSourceLocationAction(new PascalABCCompiler.SourceLocation(textAreaControl.file_name,item.Line+1,item.Column, // item.EndLine+1,item.Column),VisualPascalABCPlugins.SourceLocationAction.NavigationGoto); VisualPABCSingleton.MainForm.VisualEnvironmentCompiler.ExecuteSourceLocationAction( new PascalABCCompiler.SourceLocation(textAreaControl.FileName, item.Line + 1, item.Column + 1, item.Line + 1, item.Column + 1), VisualPascalABCPlugins.SourceLocationAction.GotoBeg); diff --git a/VisualPascalABCNETLinux/IB/Debugger/Bookmarks.cs b/VisualPascalABCNETLinux/IB/Debugger/Bookmarks.cs index 70dc1f0f4..8fc7800af 100644 --- a/VisualPascalABCNETLinux/IB/Debugger/Bookmarks.cs +++ b/VisualPascalABCNETLinux/IB/Debugger/Bookmarks.cs @@ -156,7 +156,7 @@ namespace VisualPascalABC { ITextEditorControlProvider tecp = viewContent as ITextEditorControlProvider; if (tecp != null) - SetPosition(tecp.TextEditorControl.FileName, tecp.TextEditorControl.Document, makerStartLine, makerStartColumn, makerEndLine, makerEndColumn); + SetPosition(tecp.TextEditorControl.file_name, tecp.TextEditorControl.Document, makerStartLine, makerStartColumn, makerEndLine, makerEndColumn); else Remove(); }*/ @@ -269,7 +269,7 @@ namespace VisualPascalABC static int endLine; static int endColumn; - //public static void SetPosition(string fileName, IDocument document, int makerStartLine, int makerEndLine) + //public static void SetPosition(string file_name, IDocument document, int makerStartLine, int makerEndLine) public static void SetPosition(TextEditorControl ctrl, int makerStartLine) { try @@ -342,7 +342,7 @@ namespace VisualPascalABC static int endLine; static int endColumn; - //public static void SetPosition(string fileName, IDocument document, int makerStartLine, int makerEndLine) + //public static void SetPosition(string file_name, IDocument document, int makerStartLine, int makerEndLine) public static void SetPosition(TextEditorControl ctrl, int makerStartLine) { try @@ -426,7 +426,7 @@ namespace VisualPascalABC { ITextEditorControlProvider tecp = viewContent as ITextEditorControlProvider; if (tecp != null) - SetPosition(tecp.TextEditorControl.FileName, tecp.TextEditorControl.Document, makerStartLine, makerStartColumn, makerEndLine, makerEndColumn); + SetPosition(tecp.TextEditorControl.file_name, tecp.TextEditorControl.Document, makerStartLine, makerStartColumn, makerEndLine, makerEndColumn); else Remove(); }*/ diff --git a/VisualPascalABCNETLinux/IB/Debugger/Debugger.cs b/VisualPascalABCNETLinux/IB/Debugger/Debugger.cs index 39ef408ca..e9a73322d 100644 --- a/VisualPascalABCNETLinux/IB/Debugger/Debugger.cs +++ b/VisualPascalABCNETLinux/IB/Debugger/Debugger.cs @@ -362,7 +362,7 @@ namespace VisualPascalABC } /// - /// Добавить Breakpoint в файл fileName строку line + /// Добавить Breakpoint в файл file_name строку line /// public Mono.Debugging.Client.Breakpoint AddBreakPoint(string fileName, int line, bool commonBreakpoint) { @@ -387,7 +387,7 @@ namespace VisualPascalABC } /// - /// Получить список Breakpointov в файле fileName + /// Получить список Breakpointov в файле file_name /// public List GetBreakpointsInFile(string fileName) { @@ -432,11 +432,11 @@ namespace VisualPascalABC dbg.ProcessExited += debugProcessExit; dbg.BreakpointHit += debugBreakpointHit; //if (brPoint != null) dbg.RemoveBreakpoint(brPoint); - this.FileName = sourceFileName;//Path.GetFileNameWithoutExtension(fileName) + ".pas"; + this.FileName = sourceFileName;//Path.GetFileNameWithoutExtension(file_name) + ".pas"; this.FullFileName = Path.Combine(Path.GetDirectoryName(fileName), this.FileName); this.ExeFileName = fileName; this.PrevFullFileName = FullFileName; - //if (need_first_brpt) brPoint = dbg.AddBreakpoint(FileName, workbench.VisualEnvironmentCompiler.Compiler.BeginOffset); + //if (need_first_brpt) brPoint = dbg.AddBreakpoint(file_name, workbench.VisualEnvironmentCompiler.Compiler.BeginOffset); AssemblyHelper.LoadAssembly(fileName); debuggedProcess = dbg.Start(fileName, workingDirectory, arguments); SelectProcess(debuggedProcess); @@ -484,7 +484,7 @@ namespace VisualPascalABC sourceFileName = workbench.VisualEnvironmentCompiler.Compiler.CompilerOptions.SourceFileName; else sourceFileName = ProjectFactory.Instance.CurrentProject.MainFile; - this.FileName = sourceFileName;//Path.GetFileNameWithoutExtension(fileName) + ".pas"; + this.FileName = sourceFileName;//Path.GetFileNameWithoutExtension(file_name) + ".pas"; this.FullFileName = Path.Combine(Path.GetDirectoryName(fileName), this.FileName); this.ExeFileName = fileName; CurrentLine = 0; @@ -508,7 +508,7 @@ namespace VisualPascalABC sourceFileName = workbench.VisualEnvironmentCompiler.Compiler.CompilerOptions.SourceFileName; else sourceFileName = ProjectFactory.Instance.CurrentProject.MainFile; - this.FileName = sourceFileName;//Path.GetFileNameWithoutExtension(fileName) + ".pas"; + this.FileName = sourceFileName;//Path.GetFileNameWithoutExtension(file_name) + ".pas"; this.FullFileName = Path.Combine(Path.GetDirectoryName(fileName), this.FileName); this.ExeFileName = fileName; CurrentLine = 0; @@ -519,7 +519,7 @@ namespace VisualPascalABC Mono.Debugging.Client.DebuggerSessionOptions dso = new Mono.Debugging.Client.DebuggerSessionOptions(); dso.EvaluationOptions = Mono.Debugging.Client.EvaluationOptions.DefaultOptions.Clone(); - //monoDebuggerSession.AttachToProcess(new Mono.Debugging.Client.ProcessInfo(handle, fileName), dso); + //monoDebuggerSession.AttachToProcess(new Mono.Debugging.Client.ProcessInfo(handle, file_name), dso); Mono.Debugging.Soft.SoftDebuggerStartInfo dsi = new Mono.Debugging.Soft.SoftDebuggerStartInfo("", new Dictionary()); dsi.Command = fileName; dsi.Arguments = args; @@ -552,7 +552,7 @@ namespace VisualPascalABC workbench.ServiceContainer.EditorService.SetEditorDisabled(true); TooltipServiceManager.hideToolTip(); IsRunning = true; - //evaluator = new ExpressionEvaluator(e.Process, workbench.VisualEnvironmentCompiler, FileName); + //evaluator = new ExpressionEvaluator(e.Process, workbench.VisualEnvironmentCompiler, file_name); var process = (Mono.Debugger.Soft.VirtualMachineManager.currentProcess as Mono.Debugger.Soft.ProcessWrapper).Process; process.Exited += Process_Exited; return (Mono.Debugger.Soft.VirtualMachineManager.currentProcess as Mono.Debugger.Soft.ProcessWrapper).Process; @@ -741,7 +741,7 @@ namespace VisualPascalABC public void SetFirstBreakpoint(string fileName, int line) { - //brPoint = dbg.AddBreakpoint(fileName, line); + //brPoint = dbg.AddBreakpoint(file_name, line); brPoint = new Mono.Debugging.Client.Breakpoint(fileName, line, 1); monoDebuggerSession.Breakpoints.Add(brPoint); } @@ -1199,7 +1199,7 @@ namespace VisualPascalABC } } } - //CurrentLineBookmark.SetPosition(stackFrame.SourceLocation.FileName, curPage.TextEditor.Document, stackFrame.SourceLocation.Line, 1, stackFrame.SourceLocation.Line, + //CurrentLineBookmark.SetPosition(stackFrame.SourceLocation.file_name, curPage.TextEditor.Document, stackFrame.SourceLocation.Line, 1, stackFrame.SourceLocation.Line, // len); curPage.TextEditor.ActiveTextAreaControl.Invoke(new JumpToLineDelegate(JumpToLineInvoke), stackFrame.SourceLocation.Line - 1); @@ -2178,7 +2178,7 @@ namespace VisualPascalABC { try { - //cur_brpt = dbg.AddBreakpoint(new SourcecodeSegment((frm.CurrentTabPage.ag as CodeFileDocumentControl).FileName,(frm.CurrentTabPage.ag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Line + 1,(frm.CurrentTabPage.Tag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Column + 1, + //cur_brpt = dbg.AddBreakpoint(new SourcecodeSegment((frm.CurrentTabPage.ag as CodeFileDocumentControl).file_name,(frm.CurrentTabPage.ag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Line + 1,(frm.CurrentTabPage.Tag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Column + 1, // (frm.CurrentTabPage.ag as CodeFileDocumentControl).TextEditor.ActiveTextAreaControl.Caret.Column+100), true); workbench.WidgetController.SetStartDebugDisabled(); currentBreakpoint = monoDebuggerSession.Breakpoints.Add(WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.FileName, WorkbenchServiceFactory.DocumentService.CurrentCodeFileDocument.TextEditor.ActiveTextAreaControl.Caret.Line + 1); diff --git a/VisualPascalABCNETLinux/MonoDebugging/Evaluation/ExceptionInfoSource.cs b/VisualPascalABCNETLinux/MonoDebugging/Evaluation/ExceptionInfoSource.cs index a1552b828..7e4917c19 100644 --- a/VisualPascalABCNETLinux/MonoDebugging/Evaluation/ExceptionInfoSource.cs +++ b/VisualPascalABCNETLinux/MonoDebugging/Evaluation/ExceptionInfoSource.cs @@ -196,8 +196,8 @@ namespace Mono.Debugging.Evaluation if (trace == null) return ObjectValue.CreateUnknown ("StackTrace"); - var regex = new Regex ("at (?.*) in (?.*):(?\\d+)(,(?\\d+))?"); - var regexLine = new Regex ("at (?.*) in (?.*):line (?\\d+)(,(?\\d+))?"); + var regex = new Regex ("at (?.*) in (?.*):(?\\d+)(,(?\\d+))?"); + var regexLine = new Regex ("at (?.*) in (?.*):line (?\\d+)(,(?\\d+))?"); var frames = new List (); foreach (var sframe in trace.Split ('\n')) { @@ -215,14 +215,14 @@ namespace Mono.Debugging.Evaluation var match = regex.Match (text); if (match.Success) { text = match.Groups ["MethodName"].ToString (); - file = match.Groups ["FileName"].ToString (); + file = match.Groups ["file_name"].ToString (); int.TryParse (match.Groups ["LineNumber"].ToString (), out line); int.TryParse (match.Groups ["Column"].ToString (), out column); } else { match = regexLine.Match (text); if (match.Success) { text = match.Groups ["MethodName"].ToString (); - file = match.Groups ["FileName"].ToString (); + file = match.Groups ["file_name"].ToString (); int.TryParse (match.Groups ["LineNumber"].ToString (), out line); int.TryParse (match.Groups ["Column"].ToString (), out column); } diff --git a/VisualPascalABCNETLinux/MonoDebugging/Soft/SoftDebuggerSession.cs b/VisualPascalABCNETLinux/MonoDebugging/Soft/SoftDebuggerSession.cs index 60428d7a2..a456010f1 100644 --- a/VisualPascalABCNETLinux/MonoDebugging/Soft/SoftDebuggerSession.cs +++ b/VisualPascalABCNETLinux/MonoDebugging/Soft/SoftDebuggerSession.cs @@ -493,7 +493,7 @@ namespace Mono.Debugging.Soft var parameters = eval.GetParameters (ctx); var startInfo = parameters.First(); - var exe = (string) startInfo.GetChild ("FileName", evalOptions).GetRawValue (evalOptions); + var exe = (string) startInfo.GetChild ("file_name", evalOptions).GetRawValue (evalOptions); // The process being launched is a mono process if the target file is a .exe or .dll, or if the launcher is mono. diff --git a/VisualPascalABCNETLinux/MonoDebugging/Soft/Subprocess.cs b/VisualPascalABCNETLinux/MonoDebugging/Soft/Subprocess.cs index c1fea1e63..8f3992d65 100644 --- a/VisualPascalABCNETLinux/MonoDebugging/Soft/Subprocess.cs +++ b/VisualPascalABCNETLinux/MonoDebugging/Soft/Subprocess.cs @@ -75,7 +75,7 @@ namespace Mono.Debugging.Soft { // Get the exe and arguments from the start info and store them this.arguments = (string)startInfo.GetChild ("Arguments", ops).GetRawValue (ops); - this.exe = (string)startInfo.GetChild ("FileName", ops).GetRawValue (ops); + this.exe = (string)startInfo.GetChild ("file_name", ops).GetRawValue (ops); // Create the new session and custom start arguments. // The actual arguments don't matter much since we'll use a custom launcher for the process. @@ -124,7 +124,7 @@ namespace Mono.Debugging.Soft startInfo.GetChild ("Arguments", ops).SetRawValue (debuggerArgs + " " + arguments, ops); } else { startInfo.GetChild ("Arguments", ops).SetRawValue (debuggerStartInfo.Arguments, ops); - startInfo.GetChild ("FileName", ops).SetRawValue (debuggerStartInfo.FileName, ops); + startInfo.GetChild ("file_name", ops).SetRawValue (debuggerStartInfo.FileName, ops); } return true; } @@ -165,7 +165,7 @@ namespace Mono.Debugging.Soft // Assign the original exe and arguments to the start info object startInfo.GetChild ("Arguments", ctx.Options).SetRawValue (arguments, ctx.Options); - startInfo.GetChild ("FileName", ctx.Options).SetRawValue (exe, ctx.Options); + startInfo.GetChild ("file_name", ctx.Options).SetRawValue (exe, ctx.Options); // Signal TargetProcessLauncher that the process has started and the process ID is available. startedEvent.Set (); diff --git a/VisualPascalABCNETLinux/Projects/ProjectProperties.cs b/VisualPascalABCNETLinux/Projects/ProjectProperties.cs index c1dc5cddc..e765602e8 100644 --- a/VisualPascalABCNETLinux/Projects/ProjectProperties.cs +++ b/VisualPascalABCNETLinux/Projects/ProjectProperties.cs @@ -224,7 +224,7 @@ namespace VisualPascalABC catch { } - this.tbAppIcon.Text = Path.GetFileName(openFileDialog1.FileName);//PascalABCCompiler.Tools.RelativePathTo(ProjectFactory.Instance.CurrentProject.ProjectDirectory, openFileDialog1.FileName); + this.tbAppIcon.Text = Path.GetFileName(openFileDialog1.FileName);//PascalABCCompiler.Tools.RelativePathTo(ProjectFactory.Instance.CurrentProject.ProjectDirectory, openFileDialog1.file_name); } } diff --git a/VisualPascalABCNETLinux/Workbench/BuildService.cs b/VisualPascalABCNETLinux/Workbench/BuildService.cs index 5af494b31..904ef87da 100644 --- a/VisualPascalABCNETLinux/Workbench/BuildService.cs +++ b/VisualPascalABCNETLinux/Workbench/BuildService.cs @@ -69,13 +69,13 @@ namespace VisualPascalABC if (Path.GetDirectoryName(CompilerOptions1.SourceFileName).ToLower() == ((string)WorkbenchStorage.StandartDirectories[Constants.LibSourceDirectoryIdent]).ToLower()) Workbench.VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate = false; if (RuntimeServicesModule != null) - CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); + CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandardModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); string ofn = Workbench.VisualEnvironmentCompiler.Compile(CompilerOptions1); Workbench.VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate = savePCU; if (RuntimeServicesModule != null) - CompilerOptions1.RemoveStandartModuleAtIndex(CompilerOptions1.StandartModules.Count - 1); + CompilerOptions1.RemoveStandardModuleAtIndex(CompilerOptions1.StandardModules.Count - 1); if (Workbench.VisualEnvironmentCompiler.Compiler.ErrorsList.Count != 0 || Workbench.VisualEnvironmentCompiler.Compiler.Warnings.Count != 0) { @@ -109,9 +109,9 @@ namespace VisualPascalABC CompilerOptions1.RunWithEnvironment = RunWithEnvironment; //string runtimeModuleFileName = CompilerOptions1.SearchDirectory + "\\" + RuntimeServicesModule; //if (RuntimeServicesModule!=null && File.Exists(runtimeModuleFileName)) - // CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); + // CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); if (RuntimeServicesModule != null) - CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); + CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandardModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); ErrorsList.Clear(); @@ -126,7 +126,7 @@ namespace VisualPascalABC Workbench.VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate = savePCU; if (RuntimeServicesModule != null) - CompilerOptions1.RemoveStandartModuleAtIndex(CompilerOptions1.StandartModules.Count - 1); + CompilerOptions1.RemoveStandardModuleAtIndex(CompilerOptions1.StandardModules.Count - 1); //MessageBox.Show(Workbench.VisualEnvironmentCompiler.Compiler.ErrorsList.Count.ToString()); if (Workbench.VisualEnvironmentCompiler.Compiler.ErrorsList.Count != 0 || Workbench.VisualEnvironmentCompiler.Compiler.Warnings.Count != 0) @@ -160,16 +160,16 @@ namespace VisualPascalABC CompilerOptions1.RunWithEnvironment = RunWithEnvironment; //string runtimeModuleFileName = CompilerOptions1.SearchDirectory + "\\" + RuntimeServicesModule; //if (RuntimeServicesModule!=null && File.Exists(runtimeModuleFileName)) - // CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); + // CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); if (__RuntimeServicesModule != null) - CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); + CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandardModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); ErrorsList.Clear(); //CompilerOptions1.SavePCUInThreadPull = true; __savePCU = Workbench.VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate; - //if (Path.GetDirectoryName(FileName).ToLower() == ((string)StandartDirectories[Constants.LibSourceDirectoryIdent]).ToLower()) + //if (Path.GetDirectoryName(file_name).ToLower() == ((string)StandartDirectories[Constants.LibSourceDirectoryIdent]).ToLower()) // VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate = false; Workbench.VisualEnvironmentCompiler.Compiler.OnChangeCompilerState += CompilationOnChangeCompilerState; @@ -196,9 +196,9 @@ namespace VisualPascalABC CompilerOptions1.RunWithEnvironment = RunWithEnvironment; //string runtimeModuleFileName = CompilerOptions1.SearchDirectory + "\\" + RuntimeServicesModule; //if (RuntimeServicesModule!=null && File.Exists(runtimeModuleFileName)) - // CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); + // CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(runtimeModuleFileName, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain)); if (__RuntimeServicesModule != null) - CompilerOptions1.StandartModules.Add(new PascalABCCompiler.CompilerOptions.StandartModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandartModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); + CompilerOptions1.StandardModules.Add(new PascalABCCompiler.CompilerOptions.StandardModule(RuntimeServicesModule, PascalABCCompiler.CompilerOptions.StandardModuleAddMethod.RightToMain, PascalABCCompiler.SyntaxTree.LanguageId.C | PascalABCCompiler.SyntaxTree.LanguageId.PascalABCNET | PascalABCCompiler.SyntaxTree.LanguageId.CommonLanguage)); ErrorsList.Clear(); @@ -268,7 +268,7 @@ namespace VisualPascalABC Workbench.VisualEnvironmentCompiler.Compiler.InternalDebug.PCUGenerate = __savePCU; if (__RuntimeServicesModule != null) - CompilerOptions1.RemoveStandartModuleAtIndex(CompilerOptions1.StandartModules.Count - 1); + CompilerOptions1.RemoveStandardModuleAtIndex(CompilerOptions1.StandardModules.Count - 1); if (Workbench.VisualEnvironmentCompiler.Compiler.ErrorsList.Count != 0 || Workbench.VisualEnvironmentCompiler.Compiler.Warnings.Count != 0) { diff --git a/VisualPascalABCNETLinux/Workbench/DialogsService.cs b/VisualPascalABCNETLinux/Workbench/DialogsService.cs index 6acbf6903..1229f9c46 100644 --- a/VisualPascalABCNETLinux/Workbench/DialogsService.cs +++ b/VisualPascalABCNETLinux/Workbench/DialogsService.cs @@ -40,7 +40,7 @@ namespace VisualPascalABC private void saveFileDialog1_FileOk(object sender, CancelEventArgs e) { - //ReplaceLastFile(CurrentSourceFileName, saveFileDialog1.FileName); + //ReplaceLastFile(CurrentSourceFileName, saveFileDialog1.file_name); string fn = Tools.FileNameToLower(saveFileDialog1.FileName); if (OpenDocuments.ContainsKey(fn) && OpenDocuments[fn] != CurrentCodeFileDocument) { diff --git a/VisualPascalABCNETLinux/Workbench/FileOperations.cs b/VisualPascalABCNETLinux/Workbench/FileOperations.cs index 23774bb58..4a14a3061 100644 --- a/VisualPascalABCNETLinux/Workbench/FileOperations.cs +++ b/VisualPascalABCNETLinux/Workbench/FileOperations.cs @@ -120,7 +120,7 @@ namespace VisualPascalABC { if (Path.GetExtension(FileName) == ".pas") { - /*string XMLFile = Path.ChangeExtension(FileName, string_consts.xml_form_extention); + /*string XMLFile = Path.ChangeExtension(file_name, string_consts.xml_form_extention); if (File.Exists(XMLFile)) { if (not_open_designer) @@ -164,7 +164,7 @@ namespace VisualPascalABC visualStates.FileOpened = true;//????? if (!IsNewFile && !File.Exists(FileName)) { - //MessageBox.Show(string.Format(PascalABCCompiler.StringResources.Get("!FILE_NOT_FOUND{0}"), FileName), PascalABCCompiler.StringResources.Get("!ERROR"), MessageBoxButtons.OK, MessageBoxIcon.Warning); + //MessageBox.Show(string.Format(PascalABCCompiler.StringResources.Get("!FILE_NOT_FOUND{0}"), file_name), PascalABCCompiler.StringResources.Get("!ERROR"), MessageBoxButtons.OK, MessageBoxIcon.Warning); bool exists = false; foreach (string s in search_debug_paths) { @@ -205,7 +205,7 @@ namespace VisualPascalABC else if (!IsNewFile) { - //CheckErrorListAndClear((tabControl1.TabPages[TabIndex].ag as CodeFileDocumentControl).FileName); + //CheckErrorListAndClear((tabControl1.TabPages[TabIndex].ag as CodeFileDocumentControl).file_name); CurrentCodeFileDocument.FileName = FileName; if (!ProjectFactory.Instance.ProjectLoaded) SetTabPageText(CurrentCodeFileDocument); @@ -397,7 +397,7 @@ namespace VisualPascalABC OpenDocuments.Remove(Tools.FileNameToLower(dt.FileName)); OpenDocuments.Add(Tools.FileNameToLower(FileName), TbPage); WorkbenchServiceFactory.CodeCompletionParserController.RenameFile(dt.FileName, FileName); - //TbPage.SaveFormFile(FileName); + //TbPage.SaveFormFile(file_name); dt.DocumentChanged = false; dt.FileName = FileName; dt.DocumentSavedToDisk = true; @@ -590,7 +590,7 @@ namespace VisualPascalABC internal bool IsForm(string FileName) { - //string XMLFile = Path.ChangeExtension(FileName, string_consts.xml_form_extention); + //string XMLFile = Path.ChangeExtension(file_name, string_consts.xml_form_extention); // return File.Exists(XMLFile); return false; } diff --git a/VisualPascalABCNETLinux/Workbench/VisibilityService.cs b/VisualPascalABCNETLinux/Workbench/VisibilityService.cs index 52964c402..5a716d6be 100644 --- a/VisualPascalABCNETLinux/Workbench/VisibilityService.cs +++ b/VisualPascalABCNETLinux/Workbench/VisibilityService.cs @@ -465,8 +465,8 @@ namespace VisualPascalABC clicked_stop_debug_in_menu = false; this.mDEBUGENDToolStripMenuItem.Enabled = false; //Data fileInfo = debuggedPage.ag as CodeFileDocumentControl; - //debuggedPage.Text = Path.GetFileName(fileInfo.FileName); - //debuggedPage.ToolTipText = fileInfo.FileName; + //debuggedPage.Text = Path.GetFileName(fileInfo.file_name); + //debuggedPage.ToolTipText = fileInfo.file_name; SetTabPageText(debuggedPage); ChangeDebugButtons(false); SaveDebugContext(); diff --git a/VisualPascalABCNETLinux/Workbench/WindowOperations.cs b/VisualPascalABCNETLinux/Workbench/WindowOperations.cs index 8d3fb4321..bc6738f09 100644 --- a/VisualPascalABCNETLinux/Workbench/WindowOperations.cs +++ b/VisualPascalABCNETLinux/Workbench/WindowOperations.cs @@ -257,7 +257,7 @@ namespace VisualPascalABC SetTabPageText(edit); edit.SetHighlightingStrategyForFile(FileName); OpenDocuments.Add(Tools.FileNameToLower(FileName), edit); - //this.codeCompletionParserController.SetAsChanged(FileName); + //this.codeCompletionParserController.SetAsChanged(file_name); //ivan AddBreakPointHandler(edit, FileName); var RunService = WorkbenchServiceFactory.RunService; @@ -483,7 +483,7 @@ namespace VisualPascalABC AddEditorHandlers(edit); } WorkbenchServiceFactory.CodeCompletionParserController.RegisterFileForParsing(tabName + ".pas"); - //edit.FileName = FileName; + //edit.file_name = file_name; //SetTabPageText(edit); } @@ -573,7 +573,7 @@ namespace VisualPascalABC public void AddTextToOutputWindowSync(string fileName, string text) { - //BeginInvoke(new SetFileNameAndTextDelegate(AddTextToOutputWindow), fileName, text); + //BeginInvoke(new SetFileNameAndTextDelegate(AddTextToOutputWindow), file_name, text); Invoke(new SetFileNameAndTextDelegate(AddTextToOutputWindow), fileName, text); } diff --git a/VisualPlugins/SyntaxTreeVisualisator/SyntaxTreeVisualisatorForm.cs b/VisualPlugins/SyntaxTreeVisualisator/SyntaxTreeVisualisatorForm.cs index 0c0f60892..27546724b 100644 --- a/VisualPlugins/SyntaxTreeVisualisator/SyntaxTreeVisualisatorForm.cs +++ b/VisualPlugins/SyntaxTreeVisualisator/SyntaxTreeVisualisatorForm.cs @@ -206,7 +206,7 @@ namespace VisualPascalABCPlugins string FileText = (string)VisualEnvironmentCompiler.Compiler.SourceFilesProvider(FileName, PascalABCCompiler.SourceFileOperation.GetText); List Errors=new List(); List Warnings = new List(); - //PascalABCCompiler.SyntaxTree.syntax_tree_node sn = VisualEnvironmentCompiler.Compiler.ParsersController.Compile(FileName, FileText, Errors, PascalABCCompiler.ParserTools.ParseMode.Expression); + //PascalABCCompiler.SyntaxTree.syntax_tree_node sn = VisualEnvironmentCompiler.Compiler.ParsersController.Compile(file_name, FileText, Errors, PascalABCCompiler.ParserTools.ParseMode.Expression); PascalABCCompiler.SyntaxTree.syntax_tree_node sn = VisualEnvironmentCompiler.StandartCompiler.ParsersController.GetExpression(FileName, FileText, Errors, Warnings); if (Errors.Count > 0) StatusLabel.Text = Errors.Count + " errors"; diff --git a/bin/GPPG.dll.config b/bin/GPPG.dll.config new file mode 100644 index 000000000..74ade9db5 --- /dev/null +++ b/bin/GPPG.dll.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/bin/ShiftReduceParser.dll.config b/bin/ShiftReduceParser.dll.config new file mode 100644 index 000000000..74ade9db5 --- /dev/null +++ b/bin/ShiftReduceParser.dll.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/pabcnetc/CommandConsoleCompiler.cs b/pabcnetc/CommandConsoleCompiler.cs index 5e659986a..550940aca 100644 --- a/pabcnetc/CommandConsoleCompiler.cs +++ b/pabcnetc/CommandConsoleCompiler.cs @@ -67,7 +67,7 @@ namespace PascalABCCompiler return text; if (!File.Exists(FileName)) return null; - /*TextReader tr = new StreamReader(FileName, System.Text.Encoding.GetEncoding(1251)); + /*TextReader tr = new StreamReader(file_name, System.Text.Encoding.GetEncoding(1251)); text = tr.ReadToEnd(); tr.Close();*/ text = PascalABCCompiler.FileReader.ReadFileContent(FileName, null); @@ -267,13 +267,13 @@ namespace PascalABCCompiler sendWorkingSet(); break; case ConsoleCompilerConstants.CompilerOptionsClearStandartModules: - compiler.CompilerOptions.StandartModules.Clear(); + compiler.CompilerOptions.StandardModules.Clear(); break; case ConsoleCompilerConstants.CompilerOptionsStandartModule: - CompilerOptions.StandartModule sm = new CompilerOptions.StandartModule(args[0], - (CompilerOptions.StandartModuleAddMethod)Convert.ToInt32(args[1]), + CompilerOptions.StandardModule sm = new CompilerOptions.StandardModule(args[0], + (CompilerOptions.StandardModuleAddMethod)Convert.ToInt32(args[1]), (PascalABCCompiler.SyntaxTree.LanguageId)Convert.ToInt32(args[2])); - compiler.CompilerOptions.StandartModules.Add(sm); + compiler.CompilerOptions.StandardModules.Add(sm); break; case ConsoleCompilerConstants.InternalDebug: compiler.InternalDebug = (CompilerInternalDebug)ReadObject(); diff --git a/pabcnetc/ConsoleCompiler.cs b/pabcnetc/ConsoleCompiler.cs index 9da1e1570..0a63f5baf 100644 --- a/pabcnetc/ConsoleCompiler.cs +++ b/pabcnetc/ConsoleCompiler.cs @@ -347,7 +347,7 @@ namespace PascalABCCompiler FileName = string.Format("[{0}]{1} {2}...", Math.Round((DateTime.Now - StartTime).TotalMilliseconds), State, System.IO.Path.GetFileName(FileName)); StartTime = DateTime.Now; Console.WriteLine(FileName); - //Console.Title = FileName; + //Console.Title = file_name; } else { diff --git a/pabcnetc_clear/CommandConsoleCompiler.cs b/pabcnetc_clear/CommandConsoleCompiler.cs index 4b76fc0d9..325ffd587 100644 --- a/pabcnetc_clear/CommandConsoleCompiler.cs +++ b/pabcnetc_clear/CommandConsoleCompiler.cs @@ -66,7 +66,7 @@ namespace PascalABCCompiler return text; if (!File.Exists(FileName)) return null; - /*TextReader tr = new StreamReader(FileName, System.Text.Encoding.GetEncoding(1251)); + /*TextReader tr = new StreamReader(file_name, System.Text.Encoding.GetEncoding(1251)); text = tr.ReadToEnd(); tr.Close();*/ text = PascalABCCompiler.FileReader.ReadFileContent(FileName, null); @@ -245,13 +245,13 @@ namespace PascalABCCompiler sendWorkingSet(); break; case ConsoleCompilerConstants.CompilerOptionsClearStandartModules: - compiler.CompilerOptions.StandartModules.Clear(); + compiler.CompilerOptions.StandardModules.Clear(); break; case ConsoleCompilerConstants.CompilerOptionsStandartModule: - CompilerOptions.StandartModule sm = new CompilerOptions.StandartModule(args[0], - (CompilerOptions.StandartModuleAddMethod)Convert.ToInt32(args[1]), + CompilerOptions.StandardModule sm = new CompilerOptions.StandardModule(args[0], + (CompilerOptions.StandardModuleAddMethod)Convert.ToInt32(args[1]), (PascalABCCompiler.SyntaxTree.LanguageId)Convert.ToInt32(args[2])); - compiler.CompilerOptions.StandartModules.Add(sm); + compiler.CompilerOptions.StandardModules.Add(sm); break; case ConsoleCompilerConstants.InternalDebug: compiler.InternalDebug = (CompilerInternalDebug)ReadObject();