Compiler tiding up, refactoring Keywords class and uniting errors in Errors file (#3179)

* Tidy up first part of compiler code

* Rename Net Compiler Options

* Move CompilationErrors to Errors project

* Return default constructor to compiler warning

* Rename semantic check for include namespaces in unit

* Create two Errors files instead of one in Errors project

* Fix current unit is not main program check

* Add documentation to compilation errors in Errors project

* Return compiler thrown errors to Compiler project

* Refactor keywords class - extract base keywords functionality

* Fix keywords case sensitivity

* Fix case sensitivity again...

* Optimize keywords initialization

* Fix parse expression error because of wrong constructor call
This commit is contained in:
AlexanderZemlyak 2024-07-13 18:44:49 +03:00 committed by GitHub
parent 78748e10a3
commit 97c29a4e1b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 1020 additions and 950 deletions

View file

@ -46,7 +46,6 @@ namespace CodeCompletion
public static Dictionary<string, InterfaceUnitScope> pabcNamespaces = new Dictionary<string, InterfaceUnitScope>();
public static string currentLanguageISO;
static string doctagsParserExtension = ".pasdt" + StringConstants.hideParserExtensionPostfixChar;
//public static PascalABCCompiler.Parsers.IParser currentParser;
static string cur_ext = ".pas";
private static IParser currentParser;
@ -64,7 +63,7 @@ namespace CodeCompletion
private static string get_doctagsParserExtension(string ext)
{
return ext + "dt" + StringConstants.hideParserExtensionPostfixChar;
return ext + "dt";
}
public static IParser CurrentParser

File diff suppressed because it is too large Load diff

View file

@ -164,6 +164,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="Compiler.cs" />
<Compile Include="Errors.cs" />
<Compile Include="Config\AssemblyInfo.cs" />
<Compile Include="ConsoleCompilerCommands.cs" />
<Compile Include="DocXml.cs" />
@ -173,9 +174,6 @@
<Compile Include="RemoteCompiler.cs" />
<Compile Include="SemanticTreeConverters\ISemanticTreeConverter.cs" />
<Compile Include="SemanticTreeConverters\SemanticTreeConvertersController.cs" />
<Compile Include="Errors.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="PCU\PCUFileFormatVersion.cs" />
<Compile Include="PCU\PCUWriter.cs" />
<Compile Include="PCU\PCUReader.cs" />

View file

@ -1,107 +1,429 @@
// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt)
// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
namespace PascalABCCompiler
using System;
using PascalABCCompiler.SyntaxTree;
namespace PascalABCCompiler.Errors
{
public class FileNotFound : TreeConverter.CompilationErrorWithLocation
{
private string _file_name;
/// <summary>
/// Базовый класс для ошибок, бросаемых компилятором
/// </summary>
public class CompilerThrownError : LocatedError
{
public CompilerThrownError(string message)
: base(message)
{
}
public CompilerThrownError(string message, string FileName)
: base(message, FileName)
{
}
public override string ToString()
{
return Message;
}
}
public FileNotFound(string file_name, TreeRealization.location loc):base(loc)
{
_file_name=file_name;
}
/// <summary>
/// Бросается в случае невозможности чтения pcu
/// </summary>
public class ReadPCUError : CompilerThrownError
{
public ReadPCUError(string FileName)
: base(string.Format(StringResources.Get("COMPILATIONERROR_READ_PCU{0}_ERROR"), FileName))
{
}
}
public string file_name
{
get
{
return _file_name;
}
}
/// <summary>
/// Бросается в случае использования uses in в пространстве имен
/// </summary>
public class NamespaceCannotHaveInSection : CompilerThrownError
{
public NamespaceCannotHaveInSection(SyntaxTree.SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_NAMESPACE_CANNOT_HAVE_IN_SECTION")))
{
this.source_context = sc;
}
}
public override string ToString()
{
return string.Format(StringResources.Get("COMPILATIONERROR_FILE_{0}_NOT_FOUND"), _file_name);
/// <summary>
/// Бросается, если встречена не основная программа (там где она должна быть)
/// </summary>
public class ProgramModuleExpected : CompilerThrownError
{
public ProgramModuleExpected(string FileName, SyntaxTree.SourceContext sc)
: base(StringResources.Get("COMPILATIONERROR_PROGRAM_MODULE_EXPECTED"), FileName)
{
this.source_context = sc;
}
}
/// <summary>
/// Бросается, если встречен не модуль (там где он должна быть)
/// </summary>
public class UnitModuleExpected : CompilerThrownError
{
public UnitModuleExpected(string FileName, SyntaxTree.SourceContext sc)
: base(StringResources.Get("COMPILATIONERROR_UNIT_MODULE_EXPECTED"), FileName)
{
this.source_context = sc;
}
}
/// <summary>
/// Бросается при обнаружении директивы {$apptype dll} не в библиотеке
/// </summary>
public class AppTypeDllIsAllowedOnlyForLibraries : CompilerThrownError
{
public AppTypeDllIsAllowedOnlyForLibraries(string FileName, SyntaxTree.SourceContext sc)
: base(StringResources.Get("COMPILATIONERROR_APPTYPE_DLL_IS_ALLOWED_ONLY_FOR_LIBRARIES"), FileName)
{
this.source_context = sc;
}
}
/// <summary>
/// Бросается при компиляции библиотеки не первой
/// </summary>
public class UnitModuleExpectedLibraryFound : CompilerThrownError
{
public UnitModuleExpectedLibraryFound(string FileName, SyntaxTree.SourceContext sc)
: base(StringResources.Get("COMPILATIONERROR_UNIT_MODULE_EXPECTED_LIBRARY_FOUND"), FileName)
{
this.source_context = sc;
}
}
/// <summary>
/// Бросается, если файл сборки не найден
/// </summary>
public class AssemblyNotFound : CompilerThrownError
{
public string AssemblyFileName;
public AssemblyNotFound(string FileName, string AssemblyFileName, SyntaxTree.SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_ASSEMBLY_{0}_NOT_FOUND"), AssemblyFileName), FileName)
{
this.AssemblyFileName = AssemblyFileName;
this.source_context = sc;
}
}
}
public class DLLReadingError : TreeConverter.CompilationError
{
private string _dll_name;
/// <summary>
/// Бросается при невозможности чтения сборки
/// </summary>
public class AssemblyReadingError : CompilerThrownError
{
public string AssemblyFileName;
public AssemblyReadingError(string FileName, string AssemblyFileName, SyntaxTree.SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_ASSEMBLY_{0}_READING_ERROR"), AssemblyFileName), FileName)
{
this.AssemblyFileName = AssemblyFileName;
this.source_context = sc;
}
}
public DLLReadingError(string dll_name)
{
_dll_name=dll_name;
}
/// <summary>
/// Бросается при попытке обработки неправильного пути к сборке
/// </summary>
public class InvalidAssemblyPathError : CompilerThrownError
{
public InvalidAssemblyPathError(string FileName, SyntaxTree.SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_INVALID_ASSEMBLY_PATH")), FileName)
{
this.source_context = sc;
}
}
public string dll_name
{
get
{
return _dll_name;
}
}
/// <summary>
/// Бросается при попытке обработки неправильного пути к файлу
/// </summary>
public class InvalidPathError : CompilerThrownError
{
public InvalidPathError(SyntaxTree.SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_INVALID_PATH")))
{
this.source_context = sc;
this.fileName = sc.FileName;
}
}
public override string ToString()
{
//return ("Dll: "+dll_name+" not found");
return string.Format(StringResources.Get("COMPILATIONERROR_ASSEMBLY_{0}_READING_ERROR"), dll_name);
}
/// <summary>
/// Бросается при неудаче в нахождении файла ресурсов
/// </summary>
public class ResourceFileNotFound : CompilerThrownError
{
public ResourceFileNotFound(string fileName, string ResFileName, SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_RESOURCEFILE_{0}_NOT_FOUND"), ResFileName), fileName)
{
source_context = sc;
}
}
}
/// <summary>
/// Бросается при подключении явного пространства имен в модуле
/// </summary>
public class IncludeNamespaceInUnitError : CompilerThrownError
{
public IncludeNamespaceInUnitError(string FileName, SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_INCLUDE_NAMESPACE_IN_UNIT")), FileName)
{
this.source_context = sc;
}
}
public class InvalidUnit : TreeConverter.CompilationError
{
private string _unit_name;
/// <summary>
/// Бросается, если встречено не явное пространство имен
/// </summary>
public class NamespaceModuleExpected : CompilerThrownError
{
public NamespaceModuleExpected(SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_NAMESPACE_MODULE_EXPECTED")))
{
this.source_context = sc;
}
}
public InvalidUnit(string unit_name)
{
_unit_name=unit_name;
}
/// <summary>
/// Бросается в случае некорректного использования директивы {$mainresource ...}
/// </summary>
public class MainResourceNotAllowed : CompilerThrownError
{
public MainResourceNotAllowed(string fileName, SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_MAINRESOURCE_NOT_ALLOWED")), fileName)
{
source_context = sc;
}
public string unit_name
{
get
{
return _unit_name;
}
}
}
public override string ToString()
{
return ("Invalid unit: "+_unit_name);
}
/// <summary>
/// Бросается при нахождении дубликатов в секции uses
/// </summary>
public class DuplicateUsesUnit : CompilerThrownError
{
public string UnitName;
public DuplicateUsesUnit(string FileName, string UnitName, SyntaxTree.SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_DUPLICATE_USES_UNIT{0}"), UnitName), FileName)
{
this.UnitName = UnitName;
this.source_context = sc;
}
}
}
/// <summary>
/// Бросается при нахождении дубликатов директив, не поддерживающих многократное использование в рамках некоторого контекста
/// </summary>
public class DuplicateDirective : CompilerThrownError
{
public string DirectiveName;
public DuplicateDirective(string FileName, string DirectiveName, SyntaxTree.SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_DUPLICATE_DIRECTIVE{0}"), DirectiveName), FileName)
{
this.DirectiveName = DirectiveName;
this.source_context = sc;
}
}
public class UnitCompilationError : TreeConverter.CompilationError
{
private SyntaxTree.unit_or_namespace _SyntaxUsesUnit;
private string _file_name;
/// <summary>
/// Legacy, бросается, если unitModule.unitName.HeaderKeyword == SyntaxTree.UnitHeaderKeyword.Namespace
/// </summary>
public class NamespacesCanBeCompiledOnlyInProjects : CompilerThrownError
{
public NamespacesCanBeCompiledOnlyInProjects(SyntaxTree.SourceContext sc)
: base(StringResources.Get("COMPILATIONERROR_NAMESPACE_CAN_BE_COMPILED_ONLY_IN_PROJECTS"))
{
this.source_context = sc;
}
}
public UnitCompilationError(string fileName,SyntaxTree.unit_or_namespace syntaxUsesUnit)
{
_SyntaxUsesUnit=syntaxUsesUnit;
_file_name=fileName;
}
/// <summary>
/// Бросается, если модуль (unit) не найден по некоторому пути
/// </summary>
public class UnitNotFound : CompilerThrownError
{
public string UnitName;
public UnitNotFound(string FileName, string UnitName, SyntaxTree.SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_UNIT_{0}_NOT_FOUND"), UnitName), FileName)
{
this.UnitName = UnitName;
this.source_context = sc;
}
}
public SyntaxTree.unit_or_namespace SyntaxUsesUnit
{
get
{
return _SyntaxUsesUnit;
}
}
/// <summary>
/// Бросается при некорректном пути в uses in
/// </summary>
public class UsesInWrongName : CompilerThrownError
{
public string UnitName1;
public string UnitName2;
public UsesInWrongName(string FileName, string UnitName1, string UnitName2, SyntaxTree.SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_USES_IN_WRONG_NAME"), UnitName1, UnitName2), FileName)
{
this.UnitName1 = UnitName1;
this.UnitName2 = UnitName2;
this.source_context = sc;
}
}
public string file_name
{
get
{
return _file_name;
}
}
}
/// <summary>
/// Бросается при невозможности найти исходник по некотрому пути
/// </summary>
public class SourceFileNotFound : CompilerThrownError
{
public SourceFileNotFound(string FileName)
: base(string.Format(StringResources.Get("COMPILATIONERROR_SOURCE_FILE_{0}_NOT_FOUND"), FileName))
{
}
}
/// <summary>
/// Бросается при попытке файловой операции с недостаточными правами
/// </summary>
public class UnauthorizedAccessToFile : CompilerThrownError
{
public UnauthorizedAccessToFile(string FileName)
: base(string.Format(StringResources.Get("COMPILATIONERROR_NO_ACCESS_TO_FILE{0}"), FileName))
{
}
}
/// <summary>
/// Бросается в случае обнаружения циклической зависимости модулей
/// </summary>
public class CycleUnitReference : CompilerThrownError
{
public CycleUnitReference(string FileName, SyntaxTree.unit_or_namespace SyntaxUsesUnit)
: base(string.Format(StringResources.Get("COMPILATIONERROR_CYCLIC_UNIT_REFERENCE_WITH_UNIT_{0}"), SyntaxTree.Utils.IdentListToString(SyntaxUsesUnit.name.idents, ".")), FileName)
{
this.source_context = SyntaxUsesUnit.source_context;
}
}
/// <summary>
/// Бросается, если пользователь указывает неподдерживаемый целевой framework
/// </summary>
public class UnsupportedTargetFramework : CompilerThrownError
{
public UnsupportedTargetFramework(string FrameworkName, SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_UNSUPPORTED_TARGETFRAMEWORK_{0}"), FrameworkName))
{
this.source_context = sc;
}
}
/// <summary>
/// Бросается, если пользователь указывает неподдерживаемую целевую платформу
/// </summary>
public class UnsupportedTargetPlatform : CompilerThrownError
{
public UnsupportedTargetPlatform(string platformName, SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_UNSUPPORTED_TARGET_PLATFORM{0}"), platformName))
{
source_context = sc;
}
}
/// <summary>
/// Бросается, если пользователь указывает неподдерживаемый тип выходного файла (например, в директиве {$apptype ...})
/// </summary>
public class UnsupportedOutputFileType : CompilerThrownError
{
public UnsupportedOutputFileType(string outputFileType, SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_UNSUPPORTED_OUTPUT_FILE_TYPE{0}"), outputFileType))
{
source_context = sc;
}
}
/// <summary>
/// Бросается при отсутствии некоторого файла по некоторому пути
/// </summary>
public class FileNotFound : CompilerThrownError
{
public FileNotFound(string fileName, SourceContext sc)
: base(string.Format(StringResources.Get("COMPILATIONERROR_FILE_{0}_NOT_FOUND"), fileName))
{
this.source_context = sc;
}
}
/*public class DLLReadingError : TreeConverter.CompilationError
{
private string _dll_name;
public DLLReadingError(string dll_name)
{
_dll_name = dll_name;
}
public string dll_name
{
get
{
return _dll_name;
}
}
public override string ToString()
{
//return ("Dll: "+dll_name+" not found");
return string.Format(StringResources.Get("COMPILATIONERROR_ASSEMBLY_{0}_READING_ERROR"), dll_name);
}
}
public class InvalidUnit : TreeConverter.CompilationError
{
private string _unit_name;
public InvalidUnit(string unit_name)
{
_unit_name = unit_name;
}
public string unit_name
{
get
{
return _unit_name;
}
}
public override string ToString()
{
return ("Invalid unit: " + _unit_name);
}
}
public class UnitCompilationError : TreeConverter.CompilationError
{
private SyntaxTree.unit_or_namespace _SyntaxUsesUnit;
private string _file_name;
public UnitCompilationError(string fileName, SyntaxTree.unit_or_namespace syntaxUsesUnit)
{
_SyntaxUsesUnit = syntaxUsesUnit;
_file_name = fileName;
}
public SyntaxTree.unit_or_namespace SyntaxUsesUnit
{
get
{
return _SyntaxUsesUnit;
}
}
public string file_name
{
get
{
return _file_name;
}
}
}*/
}

View file

@ -223,7 +223,7 @@ namespace PascalABCCompiler.PCU
{
var FullUnitName = comp.FindPCUFileName(UnitName, dir, out _);
if (FullUnitName == null) throw new FileNotFound(UnitName, null);
if (FullUnitName == null) throw new Errors.FileNotFound(UnitName, null);
return FullUnitName;
}

View file

@ -61,7 +61,6 @@
<ItemGroup>
<Compile Include="Conf\AssemblyInfo.cs" />
<Compile Include="CRC32.cs" />
<Compile Include="Errors\Errors.cs" />
<Compile Include="Errors\ErrorsStrategy.cs" />
<Compile Include="EventedStreamReaderList.cs" />
<Compile Include="Tools.cs" />

View file

@ -1,72 +0,0 @@
// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.IO;
using PascalABCCompiler.SyntaxTree;
namespace PascalABCCompiler.Errors
{
public class SemanticError : LocatedError
{
public SemanticError(string Message, string fileName)
: base(Message,fileName)
{
this.fileName = fileName;
}
public virtual SemanticTree.ILocation Location
{
get
{
return null;
}
}
public SemanticError()
{
}
public override string ToString()
{
return String.Format(StringResources.Get("COMPILATIONERROR_UNDEFINED_SEMANTIC_ERROR{0}"), this.GetType().ToString());
}
public override SourceLocation SourceLocation
{
get
{
if (sourceLocation != null)
return sourceLocation;
if (Location != null)
{
return new SourceLocation(Location.document.file_name,
Location.begin_line_num, Location.begin_column_num, Location.end_line_num, Location.end_column_num);
}
return null;
}
}
public override string Message
{
get
{
return (this.ToString());
}
}
}
public class SemanticNonSupportedError : SemanticError
{
public SemanticNonSupportedError(string fileName)
: base("", fileName)
{
}
}
}

View file

@ -1,8 +1,6 @@
// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Text;
namespace PascalABCCompiler.Errors
{

View file

@ -1,14 +1,18 @@
// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.IO;
using PascalABCCompiler.SyntaxTree;
namespace PascalABCCompiler.Errors
{
public class Error:Exception
{
public Error(string Message)
/// <summary>
/// Базовый класс для всех ошибок проекта
/// </summary>
public class Error : Exception
{
public Error(string Message)
: base(Message)
{
}
@ -24,9 +28,13 @@ namespace PascalABCCompiler.Errors
public Error()
{
}
}
public class LocatedError:Error
{
}
/// <summary>
/// Базовый класс для ошибки, содержащей информацию о позиции кода, вызвавшего ее
/// </summary>
public class LocatedError : Error
{
protected SourceContext source_context = null;
protected SourceLocation sourceLocation = null;
public string fileName = null;
@ -55,14 +63,14 @@ namespace PascalABCCompiler.Errors
fn = Path.GetFileName(file_name);
return string.Format(StringResources.Get("PARSER_ERRORS_COMPILATION_ERROR{0}{1}{2}"), fn, pos, Message);
*/
return (new CompilerInternalError("Errors.ToString",new Exception(string.Format("Не переопеределена {0}.ToString",this.GetType())))).ToString();
return (new CompilerInternalError("Errors.ToString", new Exception(string.Format("Не переопеределена {0}.ToString", this.GetType())))).ToString();
}
public virtual SourceLocation SourceLocation
{
get
{
if(sourceLocation!=null)
if (sourceLocation != null)
return sourceLocation;
if (SourceContext != null)
return new SourceLocation(FileName, SourceContext.begin_position.line_num, SourceContext.begin_position.column_num, SourceContext.end_position.line_num, SourceContext.end_position.column_num);
@ -86,35 +94,57 @@ namespace PascalABCCompiler.Errors
return fileName;
}
}
}
public class CommonCompilerError : Errors.LocatedError
}
/// <summary>
/// Внутренняя ошибка компилятора (нештатная)
/// </summary>
public class CompilerInternalError : Error
{
public CommonCompilerError(string mes, string fileName, int line, int col):base(mes,fileName)
{
this.sourceLocation = new SourceLocation(fileName,line,col,line,col);
this.source_context = new SyntaxTree.SourceContext(line,col,line,col);
}
public Exception exception = null;
public string Module;
public CompilerInternalError(string module, Exception exc)
: base(exc.ToString())
{
Module = module;
exception = exc;
}
public override string ToString()
{
return string.Format("{0} ({1},{2}): {3}", Path.GetFileName(sourceLocation.FileName), sourceLocation.BeginPosition.Line, sourceLocation.BeginPosition.Column,this.Message);
return string.Format(StringResources.Get("COMPILER_INTERNAL_ERROR_IN_UNIT_{0}_:{1}"), Module, Message + ' ' + exception.ToString());
}
}
public class CompilerWarning : Errors.LocatedError
/// <summary>
/// Обобщенный тип ошибки для случаев не требущих детального описания в Message
/// </summary>
public class CommonCompilerError : LocatedError
{
public CompilerWarning()
{
}
public CompilerWarning(string Message, string fileName)
public CommonCompilerError(string mes, string fileName, int line, int col) : base(mes, fileName)
{
this.sourceLocation = new SourceLocation(fileName, line, col, line, col);
this.source_context = new SyntaxTree.SourceContext(line, col, line, col);
}
public override string ToString()
{
return string.Format("{0} ({1},{2}): {3}", Path.GetFileName(sourceLocation.FileName), sourceLocation.BeginPosition.Line, sourceLocation.BeginPosition.Column, this.Message);
}
}
/// <summary>
/// Базовый класс для предупреждения
/// </summary>
public class CompilerWarning : LocatedError
{
public CompilerWarning() { }
public CompilerWarning(string Message, string fileName)
: base(Message)
{
this.fileName = fileName;
}
public override string Message
public override string Message
{
get
{
@ -122,19 +152,22 @@ namespace PascalABCCompiler.Errors
}
}
}
/// <summary>
/// Обобщенный тип предупреждения
/// </summary>
public class CommonWarning : CompilerWarning
{
string _mes;
public CommonWarning(string mes, string fileName, int line, int col):base(mes,fileName)
{
this.sourceLocation = new SourceLocation(fileName,line,col,line,col);
this.source_context = new SyntaxTree.SourceContext(line,col,line,col);
_mes = mes;
}
public override string Message
string _mes;
public CommonWarning(string mes, string fileName, int line, int col) : base(mes, fileName)
{
this.sourceLocation = new SourceLocation(fileName, line, col, line, col);
this.source_context = new SyntaxTree.SourceContext(line, col, line, col);
_mes = mes;
}
public override string Message
{
get
{
@ -142,7 +175,10 @@ namespace PascalABCCompiler.Errors
}
}
}
/// <summary>
/// Базовый класс для синтаксической ошибки
/// </summary>
public class SyntaxError : LocatedError
{
public syntax_tree_node bad_node;
@ -165,9 +201,9 @@ namespace PascalABCCompiler.Errors
if (source_context.FileName != null)
base.fileName = source_context.FileName;
break;
}
}
} while (bn != null);
}
bad_node = _bad_node;
}
@ -178,7 +214,7 @@ namespace PascalABCCompiler.Errors
public override string ToString()
{
string snode="";
string snode = "";
/*if (bad_node == null)
snode = " (bad_node==null)";
else
@ -191,13 +227,6 @@ namespace PascalABCCompiler.Errors
return Path.GetFileName(FileName) + pos + ": Синтаксическая ошибка : " + Message + snode;
}
public override SourceContext SourceContext
{
get
{
return source_context;
}
}
public override SourceLocation SourceLocation
{
get
@ -205,29 +234,72 @@ namespace PascalABCCompiler.Errors
if (source_context == null)
return null;
return new SourceLocation(fileName,
source_context.begin_position.line_num,source_context.begin_position.column_num,
source_context.begin_position.line_num, source_context.begin_position.column_num,
source_context.end_position.line_num, source_context.end_position.column_num);
}
}
}
public class CompilerInternalError : Error
/// <summary>
/// Базовый класс для семантической ошибки
/// </summary>
public class SemanticError : LocatedError
{
public Exception exception = null;
public string Module;
public CompilerInternalError(string module, Exception exc)
: base(exc.ToString())
public SemanticError(string Message, string fileName)
: base(Message, fileName)
{
this.fileName = fileName;
}
public virtual SemanticTree.ILocation Location
{
get
{
return null;
}
}
public SemanticError()
{
Module = module;
exception = exc;
}
public override string ToString()
{
return String.Format(StringResources.Get("COMPILER_INTERNAL_ERROR_IN_UNIT_{0}_:{1}"), Module, Message+' '+ exception.ToString());
return String.Format(StringResources.Get("COMPILATIONERROR_UNDEFINED_SEMANTIC_ERROR{0}"), this.GetType().ToString());
}
public override SourceLocation SourceLocation
{
get
{
if (sourceLocation != null)
return sourceLocation;
if (Location != null)
{
return new SourceLocation(Location.document.file_name,
Location.begin_line_num, Location.begin_column_num, Location.end_line_num, Location.end_column_num);
}
return null;
}
}
public override string Message
{
get
{
return (this.ToString());
}
}
}
/// <summary>
/// Базовый класс для NotSupportedError из TreeConverter | возможно, излишний EVA
/// </summary>
public class SemanticNonSupportedError : SemanticError
{
public SemanticNonSupportedError(string fileName)
: base("", fileName)
{
}
}
}

View file

@ -63,7 +63,7 @@
<Link>Config\globalassemblyinfo.cs</Link>
</Compile>
<Compile Include="Config\AssemblyInfo.cs" />
<Compile Include="Errors.cs" />
<Compile Include="BaseErrors.cs" />
<Compile Include="SourceLocation.cs" />
</ItemGroup>
<ItemGroup>
@ -71,6 +71,10 @@
<Project>{2DE2842F-0912-4251-BC0F-480854C44A13}</Project>
<Name>Localization</Name>
</ProjectReference>
<ProjectReference Include="..\SemanticTree\SemanticTree.csproj">
<Project>{613e0dda-aa8a-437c-ac45-507b47429ff9}</Project>
<Name>SemanticTree</Name>
</ProjectReference>
<ProjectReference Include="..\SyntaxTree\SyntaxTree.csproj">
<Project>{C2CAC65A-B2AE-4CCC-B067-E6B8E75DF73A}</Project>
<Name>SyntaxTree</Name>

View file

@ -14,6 +14,9 @@ namespace Languages.Facade
public abstract class BaseLanguage : ILanguage
{
/// <summary>
/// Все параметры должны быть не null (и не пустым массивом), кроме IDocParser в случае, если он не требуется
/// </summary>
public BaseLanguage(string name, string version, string copyright, IParser parser, IDocParser docParser,
List<ISyntaxTreeConverter> syntaxTreeConverters, syntax_tree_visitor syntaxTreeToSemanticTreeConverter,
string[] filesExtensions, bool caseSensitive, string[] systemUnitNames)

View file

@ -73,8 +73,9 @@
<Compile Include="ParserTools\CommentBinder.cs" />
<Compile Include="ParserTools\DefaultLanguageInformation.cs" />
<Compile Include="ParserTools\Errors.cs" />
<Compile Include="ParserTools\KeyWord.cs" />
<Compile Include="ParserTools\Keywords\BaseKeywords.cs" />
<Compile Include="ParserTools\ILanguageInformation.cs" />
<Compile Include="ParserTools\Keywords\KeywordKind.cs" />
<Compile Include="ParserTools\ParserTools.cs" />
<Compile Include="ParserTools\ShiftReduceParserCode.cs" />
<Compile Include="ParserTools\SourceContextMap.cs" />

View file

@ -30,6 +30,8 @@ namespace PascalABCCompiler.Parsers
}
}
public BaseKeywords Keywords { get; protected set; }
/// <summary>
/// Возвращеает синтаксическое дерево модуля
/// </summary>

View file

@ -34,6 +34,11 @@ namespace PascalABCCompiler.Parsers
get;
}
/// <summary>
/// Класс, отвечащий за хранение и обработку ключевых слов языка
/// </summary>
BaseKeywords Keywords { get; }
compilation_unit GetCompilationUnit(string FileName, string Text, List<Error> Errors, List<CompilerWarning> Warnings, ParseMode parseMode, List<string> DefinesList = null);
compilation_unit GetCompilationUnitForFormatter(string FileName, string Text, List<Error> Errors, List<CompilerWarning> Warnings);

View file

@ -0,0 +1,77 @@
// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace PascalABCCompiler.Parsers
{
public abstract class BaseKeywords
{
/// <summary>
/// Соотвествие ключевых слов токенам
/// </summary>
protected abstract Dictionary<string, int> KeywordsToTokens { get; set; }
/// <summary>
/// Словарь соответствий ключевых слов их эквивалентам (задается пользователем в специальном файле)
/// </summary>
private Dictionary<string, string> keymap = new Dictionary<string, string>();
/// <summary>
/// Название файла с информацией об эквивалентах ключевых слов
/// </summary>
protected abstract string FileName { get; }
/// <summary>
/// Функция загрузки эквивалентов ключевых слов из файла
/// </summary>
private void ReloadKeyMap()
{
try
{
var pathToKeymapFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName), FileName);
if (System.IO.File.Exists(pathToKeymapFile))
keymap = System.IO.File.ReadLines(pathToKeymapFile, Encoding.Unicode).Select(s => s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).ToDictionary(w => w[0], w => w[1]);
}
catch (Exception e)
{
//var w = e.Message;
}
}
/// <summary>
/// Возвращает само эквивалент ключевого слова, либо его само, если эквивалента нет
/// </summary>
public string ConvertKeyword(string keyword)
{
if (keymap.Count() == 0 || !keymap.ContainsKey(keyword))
return keyword;
else
return keymap[keyword];
}
public BaseKeywords()
{
ReloadKeyMap();
}
/// <summary>
/// Возвращает токен, соответствующий идентификатору
/// </summary>
protected abstract int GetIdToken();
/// <summary>
/// Возвращает токен соответствующий ключевому слову, либо токен идентификатора, если такого ключевого слова нет
/// </summary>
public int KeywordOrIDToken(string keyword)
{
if (KeywordsToTokens.TryGetValue(keyword, out int token))
return token;
else
return GetIdToken();
}
}
}

View file

@ -1,8 +1,5 @@
// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt)
// Copyright (c) Ivan Bondarev, Stanislav Mikhalkovich (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Collections.Generic;
using System.Text;
namespace PascalABCCompiler.Parsers
{
@ -57,7 +54,8 @@ namespace PascalABCCompiler.Parsers
CommonKeyword,
CommonExpressionKeyword
}
public class Keyword
/*public class Keyword
{
string _name;
KeywordKind _kind = KeywordKind.None;
@ -88,5 +86,5 @@ namespace PascalABCCompiler.Parsers
{
return Name;
}
}
}*/
}

View file

@ -1,9 +1,9 @@
//
// This CSharp output file generated by Gardens Point LEX
// Version: 1.1.3.301
// Machine: DESKTOP-G8V08V4
// DateTime: 17.06.2024 16:43:45
// UserName: ?????????
// Machine: DESKTOP-V3E9T2U
// DateTime: 11.07.2024 9:39:17
// UserName: alex
// GPLEX input file <ABCPascal.lex>
// GPLEX frame file <embedded resource>
//
@ -136,16 +136,19 @@ namespace Languages.Pascal.Frontend.Core
#region user code
public PascalParserTools parserTools;
Stack<BufferContext> buffStack = new Stack<BufferContext>();
Stack<string> fNameStack = new Stack<string>();
Stack<bool> IfDefInElseBranch = new Stack<bool>();
Stack<string> IfDefVar = new Stack<string>();
private PascalABCCompiler.Parsers.BaseKeywords keywords;
private Stack<BufferContext> buffStack = new Stack<BufferContext>();
private Stack<string> fNameStack = new Stack<string>();
private Stack<bool> IfDefInElseBranch = new Stack<bool>();
private Stack<string> IfDefVar = new Stack<string>();
public List<string> Defines = new List<string>();
int IfExclude;
string Pars;
LexLocation currentLexLocation;
bool HiddenIdents = false;
bool ExprMode = false;
private int IfExclude;
private string Pars;
private LexLocation currentLexLocation;
private bool HiddenIdents = false;
private bool ExprMode = false;
public Scanner(PascalABCCompiler.Parsers.BaseKeywords keywords) { this.keywords = keywords; }
#endregion user code
int state;
@ -1854,7 +1857,7 @@ yylval = new Union(); yylval.ti = new token_info(yytext); return (int)Tokens.tkA
break;
case 28:
string cur_yytext = yytext;
int res = Keywords.KeywordOrIDToken(cur_yytext);
int res = keywords.KeywordOrIDToken(cur_yytext);
currentLexLocation = CurrentLexLocation;
if (res == (int)Tokens.tkIdentifier)
{

View file

@ -1,15 +1,18 @@
%{
public PascalParserTools parserTools;
Stack<BufferContext> buffStack = new Stack<BufferContext>();
Stack<string> fNameStack = new Stack<string>();
Stack<bool> IfDefInElseBranch = new Stack<bool>();
Stack<string> IfDefVar = new Stack<string>();
public PascalParserTools parserTools;
private PascalABCCompiler.Parsers.BaseKeywords keywords;
private Stack<BufferContext> buffStack = new Stack<BufferContext>();
private Stack<string> fNameStack = new Stack<string>();
private Stack<bool> IfDefInElseBranch = new Stack<bool>();
private Stack<string> IfDefVar = new Stack<string>();
public List<string> Defines = new List<string>();
int IfExclude;
string Pars;
LexLocation currentLexLocation;
bool HiddenIdents = false;
bool ExprMode = false;
private int IfExclude;
private string Pars;
private LexLocation currentLexLocation;
private bool HiddenIdents = false;
private bool ExprMode = false;
public Scanner(PascalABCCompiler.Parsers.BaseKeywords keywords) { this.keywords = keywords; }
%}
%namespace Languages.Pascal.Frontend.Core
@ -276,7 +279,7 @@ UNICODEARROW \x890
[&]?[!]?{ID} {
string cur_yytext = yytext;
int res = Keywords.KeywordOrIDToken(cur_yytext);
int res = keywords.KeywordOrIDToken(cur_yytext);
currentLexLocation = CurrentLexLocation;
if (res == (int)Tokens.tkIdentifier)
{
@ -619,4 +622,4 @@ UNICODEARROW \x890
}
}
// Статический класс, определяющий ключевые слова языка, находится в файле Keywords.cs
// Класс, определяющий ключевые слова языка, находится в файле Keywords.cs

View file

@ -16,21 +16,10 @@ namespace Languages.Pascal.Frontend.Documentation
public PascalDocTagsLanguageParser()
{
filesExtensions = new string[1];
filesExtensions[0] = ".pasdt" + StringConstants.hideParserExtensionPostfixChar;
sectionNames.Add("summary");
sectionNames.Add("returns");
}
string[] filesExtensions;
public string[] FilesExtensions
{
get
{
return filesExtensions;
}
}
documentation_comment_section parse_section(string text)
{
documentation_comment_section dcs = new documentation_comment_section();

View file

@ -3,167 +3,127 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Languages.Pascal.Frontend.Core
{
// Статический класс, определяющий ключевые слова языка
public static class Keywords
public class PascalABCKeywords : PascalABCCompiler.Parsers.BaseKeywords
{
private static Dictionary<string, int> keywords = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);
public static Dictionary<string, string> keymap = new Dictionary<string, string>();
protected override string FileName => "keywordsmap.pabc";
public static string fname = "keywordsmap.pabc";
public static void ReloadKeyMap()
protected override Dictionary<string, int> KeywordsToTokens { get; set; }
public PascalABCKeywords() : base()
{
try
KeywordsToTokens = new Dictionary<string, int>
{
if (keymap != null)
{
keymap.Clear();
keymap = null;
}
var fn = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName), fname);
if (System.IO.File.Exists(fn))
keymap = System.IO.File.ReadLines(fn,Encoding.Unicode).Select(s=>s.Split(new char[] { ' ' },StringSplitOptions.RemoveEmptyEntries)).ToDictionary(w => w[0], w => w[1]);
["or"] = (int)Tokens.tkOr,
["xor"] = (int)Tokens.tkXor,
["and"] = (int)Tokens.tkAnd,
["div"] = (int)Tokens.tkDiv,
["mod"] = (int)Tokens.tkMod,
["shl"] = (int)Tokens.tkShl,
["shr"] = (int)Tokens.tkShr,
["not"] = (int)Tokens.tkNot,
["as"] = (int)Tokens.tkAs,
["in"] = (int)Tokens.tkIn,
["is"] = (int)Tokens.tkIs,
["implicit"] = (int)Tokens.tkImplicit,
["explicit"] = (int)Tokens.tkExplicit,
["sizeof"] = (int)Tokens.tkSizeOf,
["typeof"] = (int)Tokens.tkTypeOf,
["where"] = (int)Tokens.tkWhere,
["array"] = (int)Tokens.tkArray,
["begin"] = (int)Tokens.tkBegin,
["case"] = (int)Tokens.tkCase,
["class"] = (int)Tokens.tkClass,
["const"] = (int)Tokens.tkConst,
["constructor"] = (int)Tokens.tkConstructor,
["default"] = (int)Tokens.tkDefault,
["destructor"] = (int)Tokens.tkDestructor,
["downto"] = (int)Tokens.tkDownto,
["do"] = (int)Tokens.tkDo,
["else"] = (int)Tokens.tkElse,
["end"] = (int)Tokens.tkEnd,
["event"] = (int)Tokens.tkEvent,
["except"] = (int)Tokens.tkExcept,
["exports"] = (int)Tokens.tkExports,
["file"] = (int)Tokens.tkFile,
["finalization"] = (int)Tokens.tkFinalization,
["finally"] = (int)Tokens.tkFinally,
["for"] = (int)Tokens.tkFor,
["foreach"] = (int)Tokens.tkForeach,
["function"] = (int)Tokens.tkFunction,
["goto"] = (int)Tokens.tkGoto,
["if"] = (int)Tokens.tkIf,
["implementation"] = (int)Tokens.tkImplementation,
["inherited"] = (int)Tokens.tkInherited,
["initialization"] = (int)Tokens.tkInitialization,
["interface"] = (int)Tokens.tkInterface,
["label"] = (int)Tokens.tkLabel,
["lock"] = (int)Tokens.tkLock,
["loop"] = (int)Tokens.tkLoop,
["nil"] = (int)Tokens.tkNil,
["procedure"] = (int)Tokens.tkProcedure,
["of"] = (int)Tokens.tkOf,
["operator"] = (int)Tokens.tkOperator,
["property"] = (int)Tokens.tkProperty,
["raise"] = (int)Tokens.tkRaise,
["record"] = (int)Tokens.tkRecord,
["repeat"] = (int)Tokens.tkRepeat,
["set"] = (int)Tokens.tkSet,
["try"] = (int)Tokens.tkTry,
["type"] = (int)Tokens.tkType,
["then"] = (int)Tokens.tkThen,
["to"] = (int)Tokens.tkTo,
["until"] = (int)Tokens.tkUntil,
["uses"] = (int)Tokens.tkUses,
["var"] = (int)Tokens.tkVar,
["while"] = (int)Tokens.tkWhile,
["with"] = (int)Tokens.tkWith,
["program"] = (int)Tokens.tkProgram,
["template"] = (int)Tokens.tkTemplate,
["resourcestring"] = (int)Tokens.tkResourceString,
["threadvar"] = (int)Tokens.tkThreadvar,
["sealed"] = (int)Tokens.tkSealed,
["partial"] = (int)Tokens.tkPartial,
["params"] = (int)Tokens.tkParams,
["unit"] = (int)Tokens.tkUnit,
["library"] = (int)Tokens.tkLibrary,
["external"] = (int)Tokens.tkExternal,
["name"] = (int)Tokens.tkName,
["private"] = (int)Tokens.tkPrivate,
["protected"] = (int)Tokens.tkProtected,
["public"] = (int)Tokens.tkPublic,
["internal"] = (int)Tokens.tkInternal,
["read"] = (int)Tokens.tkRead,
["write"] = (int)Tokens.tkWrite,
["on"] = (int)Tokens.tkOn,
["forward"] = (int)Tokens.tkForward,
["abstract"] = (int)Tokens.tkAbstract,
["overload"] = (int)Tokens.tkOverload,
["reintroduce"] = (int)Tokens.tkReintroduce,
["override"] = (int)Tokens.tkOverride,
["virtual"] = (int)Tokens.tkVirtual,
["extensionmethod"] = (int)Tokens.tkExtensionMethod,
["new"] = (int)Tokens.tkNew,
["auto"] = (int)Tokens.tkAuto,
["sequence"] = (int)Tokens.tkSequence,
["yield"] = (int)Tokens.tkYield,
["match"] = (int)Tokens.tkMatch,
["when"] = (int)Tokens.tkWhen,
["namespace"] = (int)Tokens.tkNamespace,
["static"] = (int)Tokens.tkStatic,
["step"] = (int)Tokens.tkStep,
["index"] = (int)Tokens.tkIndex,
["async"] = (int)Tokens.tkAsync,
["await"] = (int)Tokens.tkAwait
}
catch(Exception e) // погасить любые исключения
{
//var w = e.Message;
}
}
public static string Convert(string s)
{
if (keymap == null || keymap.Count() == 0)
return s;
else if (!keymap.ContainsKey(s))
return s;
else return keymap[s];
.ToDictionary(kv => ConvertKeyword(kv.Key), kv => kv.Value, StringComparer.CurrentCultureIgnoreCase);
}
public static void KeywordsAdd()
{
if (keymap == null || keymap.Count() == 0)
ReloadKeyMap();
keywords.Clear();
keywords.Add(Convert("or"), (int)Tokens.tkOr);
keywords.Add(Convert("xor"), (int)Tokens.tkXor);
keywords.Add(Convert("and"), (int)Tokens.tkAnd);
keywords.Add(Convert("div"), (int)Tokens.tkDiv);
keywords.Add(Convert("mod"), (int)Tokens.tkMod);
keywords.Add(Convert("shl"), (int)Tokens.tkShl);
keywords.Add(Convert("shr"), (int)Tokens.tkShr);
keywords.Add(Convert("not"), (int)Tokens.tkNot);
keywords.Add(Convert("as"), (int)Tokens.tkAs);
keywords.Add(Convert("in"), (int)Tokens.tkIn);
keywords.Add(Convert("is"), (int)Tokens.tkIs);
keywords.Add(Convert("implicit"), (int)Tokens.tkImplicit);
keywords.Add(Convert("explicit"), (int)Tokens.tkExplicit);
keywords.Add(Convert("sizeof"), (int)Tokens.tkSizeOf);
keywords.Add(Convert("typeof"), (int)Tokens.tkTypeOf);
keywords.Add(Convert("where"), (int)Tokens.tkWhere);
keywords.Add(Convert("array"), (int)Tokens.tkArray);
keywords.Add(Convert("begin"), (int)Tokens.tkBegin);
keywords.Add(Convert("case"), (int)Tokens.tkCase);
keywords.Add(Convert("class"), (int)Tokens.tkClass);
keywords.Add(Convert("const"), (int)Tokens.tkConst);
keywords.Add(Convert("constructor"), (int)Tokens.tkConstructor);
keywords.Add(Convert("default"), (int)Tokens.tkDefault);
keywords.Add(Convert("destructor"), (int)Tokens.tkDestructor);
keywords.Add(Convert("downto"), (int)Tokens.tkDownto);
keywords.Add(Convert("do"), (int)Tokens.tkDo);
keywords.Add(Convert("else"), (int)Tokens.tkElse);
keywords.Add(Convert("end"), (int)Tokens.tkEnd);
keywords.Add(Convert("event"), (int)Tokens.tkEvent);
keywords.Add(Convert("except"), (int)Tokens.tkExcept);
keywords.Add(Convert("exports"), (int)Tokens.tkExports);
keywords.Add(Convert("file"), (int)Tokens.tkFile);
keywords.Add(Convert("finalization"), (int)Tokens.tkFinalization);
keywords.Add(Convert("finally"), (int)Tokens.tkFinally);
keywords.Add(Convert("for"), (int)Tokens.tkFor);
keywords.Add(Convert("foreach"), (int)Tokens.tkForeach);
keywords.Add(Convert("function"), (int)Tokens.tkFunction);
keywords.Add(Convert("goto"), (int)Tokens.tkGoto);
keywords.Add(Convert("if"), (int)Tokens.tkIf);
keywords.Add(Convert("implementation"), (int)Tokens.tkImplementation);
keywords.Add(Convert("inherited"), (int)Tokens.tkInherited);
keywords.Add(Convert("initialization"), (int)Tokens.tkInitialization);
keywords.Add(Convert("interface"), (int)Tokens.tkInterface);
keywords.Add(Convert("label"), (int)Tokens.tkLabel);
keywords.Add(Convert("lock"), (int)Tokens.tkLock);
keywords.Add(Convert("loop"), (int)Tokens.tkLoop);
keywords.Add(Convert("nil"), (int)Tokens.tkNil);
keywords.Add(Convert("procedure"), (int)Tokens.tkProcedure);
keywords.Add(Convert("of"), (int)Tokens.tkOf);
keywords.Add(Convert("operator"), (int)Tokens.tkOperator);
keywords.Add(Convert("property"), (int)Tokens.tkProperty);
keywords.Add(Convert("raise"), (int)Tokens.tkRaise);
keywords.Add(Convert("record"), (int)Tokens.tkRecord);
keywords.Add(Convert("repeat"), (int)Tokens.tkRepeat);
keywords.Add(Convert("set"), (int)Tokens.tkSet);
keywords.Add(Convert("try"), (int)Tokens.tkTry);
keywords.Add(Convert("type"), (int)Tokens.tkType);
keywords.Add(Convert("then"), (int)Tokens.tkThen);
keywords.Add(Convert("to"), (int)Tokens.tkTo);
keywords.Add(Convert("until"), (int)Tokens.tkUntil);
keywords.Add(Convert("uses"), (int)Tokens.tkUses);
keywords.Add(Convert("var"), (int)Tokens.tkVar);
keywords.Add(Convert("while"), (int)Tokens.tkWhile);
keywords.Add(Convert("with"), (int)Tokens.tkWith);
keywords.Add(Convert("program"), (int)Tokens.tkProgram);
keywords.Add(Convert("template"), (int)Tokens.tkTemplate);
keywords.Add(Convert("resourcestring"), (int)Tokens.tkResourceString);
keywords.Add(Convert("threadvar"), (int)Tokens.tkThreadvar);
keywords.Add(Convert("sealed"), (int)Tokens.tkSealed);
keywords.Add(Convert("partial"), (int)Tokens.tkPartial);
keywords.Add(Convert("params"), (int)Tokens.tkParams);
keywords.Add(Convert("unit"), (int)Tokens.tkUnit);
keywords.Add(Convert("library"), (int)Tokens.tkLibrary);
keywords.Add(Convert("external"), (int)Tokens.tkExternal);
keywords.Add(Convert("name"), (int)Tokens.tkName);
keywords.Add(Convert("private"), (int)Tokens.tkPrivate);
keywords.Add(Convert("protected"), (int)Tokens.tkProtected);
keywords.Add(Convert("public"), (int)Tokens.tkPublic);
keywords.Add(Convert("internal"), (int)Tokens.tkInternal);
keywords.Add(Convert("read"), (int)Tokens.tkRead);
keywords.Add(Convert("write"), (int)Tokens.tkWrite);
keywords.Add(Convert("on"), (int)Tokens.tkOn);
keywords.Add(Convert("forward"), (int)Tokens.tkForward);
keywords.Add(Convert("abstract"), (int)Tokens.tkAbstract);
keywords.Add(Convert("overload"), (int)Tokens.tkOverload);
keywords.Add(Convert("reintroduce"), (int)Tokens.tkReintroduce);
keywords.Add(Convert("override"), (int)Tokens.tkOverride);
keywords.Add(Convert("virtual"), (int)Tokens.tkVirtual);
keywords.Add(Convert("extensionmethod"), (int)Tokens.tkExtensionMethod);
keywords.Add(Convert("new"), (int)Tokens.tkNew);
keywords.Add(Convert("auto"), (int)Tokens.tkAuto);
keywords.Add(Convert("sequence"), (int)Tokens.tkSequence);
keywords.Add(Convert("yield"), (int)Tokens.tkYield);
keywords.Add(Convert("match"), (int)Tokens.tkMatch);
keywords.Add(Convert("when"), (int)Tokens.tkWhen);
keywords.Add(Convert("namespace"), (int)Tokens.tkNamespace);
keywords.Add(Convert("static"), (int)Tokens.tkStatic);
keywords.Add(Convert("step"), (int)Tokens.tkStep);
keywords.Add(Convert("index"), (int)Tokens.tkIndex);
keywords.Add(Convert("async"), (int)Tokens.tkAsync);
keywords.Add(Convert("await"), (int)Tokens.tkAwait);
}
static Keywords()
{
KeywordsAdd();
}
public static int KeywordOrIDToken(string s)
{
//s = s.ToUpper();
int keyword = 0;
if (keywords.TryGetValue(s, out keyword))
return keyword;
else
return (int)Tokens.tkIdentifier;
}
protected override int GetIdToken() => (int)Tokens.tkIdentifier;
}
}

View file

@ -78,6 +78,7 @@ namespace Languages.Pascal.Frontend.Wrapping
public PascalABCNewLanguageParser()
{
InitializeValidDirectives();
Keywords = new PascalABCKeywords();
}
public override void Reset()
@ -156,7 +157,7 @@ namespace Languages.Pascal.Frontend.Wrapping
parserTools.currentFileName = Path.GetFullPath(fileName);
Scanner scanner = new Scanner();
Scanner scanner = new Scanner(Keywords);
scanner.SetSource(Text, 0);
scanner.parserTools = parserTools; // передали parserTools в объект сканера
if (definesList != null)

View file

@ -403,7 +403,7 @@ namespace Languages.Pascal.Frontend.Core
parserTools.warnings = new List<CompilerWarning>();
parserTools.currentFileName = System.IO.Path.GetFullPath(this.parserTools.currentFileName);
parserTools.buildTreeForFormatterStrings = true;
Scanner scanner = new Scanner();
Scanner scanner = new Scanner(this.parserTools.ParserRef.Keywords);
scanner.SetSource("<<expression>>"+Text, 0);
scanner.parserTools = parserTools;// передали parserTools в объект сканера
GPPGParser parser = new GPPGParser(scanner);

View file

@ -372,10 +372,6 @@ namespace PascalABCCompiler
public const string pascalLanguageDllName = "PascalLanguage.dll";
#endregion
#region PARSERS
public const char hideParserExtensionPostfixChar = '_';
#endregion
public static string get_array_type_name(string type_name, int rank)
{
if (rank == 1)

View file

@ -7,7 +7,6 @@ using System.Collections.Generic;
using PascalABCCompiler.SemanticTree;
using PascalABCCompiler.TreeRealization;
using PascalABCCompiler.TreeConverter;
namespace PascalABCCompiler.TreeConverter
{