Delete overkill TryCatchDecorators in SPythonStandardSyntaxTreeVisitor (#3416)

This commit is contained in:
Александр Земляк 2026-04-09 09:47:15 +03:00 committed by GitHub
parent 55aa0f6c9a
commit 0f0de28a00
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 28 additions and 19 deletions

View file

@ -9,7 +9,7 @@ namespace Languages.SPython.Frontend.Converters
private readonly bool forIntellisense; private readonly bool forIntellisense;
public NameCorrectVisitor(string unitName, bool forIntellisense, Dictionary<string, Dictionary<string, bool>> namesFromUsedUnits, HashSet<string> definedFunctionsNames) : base(unitName, namesFromUsedUnits) public NameCorrectVisitor(string unitName, bool forIntellisense, Dictionary<string, Dictionary<string, bool>> namesFromUsedUnits, HashSet<string> definedFunctionsNames) : base(unitName, forIntellisense, namesFromUsedUnits)
{ {
this.forIntellisense = forIntellisense; this.forIntellisense = forIntellisense;
foreach (string definedFunctionName in definedFunctionsNames) foreach (string definedFunctionName in definedFunctionsNames)

View file

@ -31,28 +31,28 @@ namespace Languages.SPython.Frontend.Converters
// name bin_bit_op= expr // name bin_bit_op= expr
// на // на
// name = name bin_bit_op (expr) // name = name bin_bit_op (expr)
new TryCatchDecorator(new BitwiseAssignmentDesugarVisitor(), forIntellisense).ProcessNode(root); new BitwiseAssignmentDesugarVisitor().ProcessNode(root);
// замена return; на { exit(); } // замена return; на { exit(); }
// замена return expr; на { result := expr; exit(); } // замена return expr; на { result := expr; exit(); }
new TryCatchDecorator(new ReturnDesugarVisitor(), forIntellisense).ProcessNode(root); new ReturnDesugarVisitor().ProcessNode(root);
// замена вызова функции map(func, sequence) // замена вызова функции map(func, sequence)
// на func(element) for element in sequence // на func(element) for element in sequence
new TryCatchDecorator(new MapDesugarVisitor(), forIntellisense).ProcessNode(root); new MapDesugarVisitor().ProcessNode(root);
// замена генерации последовательностей на Select.Where // замена генерации последовательностей на Select.Where
// (не работает из-за лямбд (скорее всего), если переместить в ConvertAfterUsedModulesCompilation) // (не работает из-за лямбд (скорее всего), если переместить в ApplyConversionsAfterUsedModulesCompilation)
new TryCatchDecorator(new GeneratorObjectDesugarVisitor(root, generatedNamesManager), forIntellisense).ProcessNode(root); new GeneratorObjectDesugarVisitor(root, generatedNamesManager).ProcessNode(root);
// Выносим выражения с лямбдами из заголовка foreach + считаем максимум 10 вложенных лямбд // Выносим выражения с лямбдами из заголовка foreach + считаем максимум 10 вложенных лямбд
// украл из паскаля // украл из паскаля
new TryCatchDecorator(StandOutExprWithLambdaInForeachSequenceAndNestedLambdasVisitor.Create(generatedNamesManager), forIntellisense).ProcessNode(root); new TryCatchDecorator(StandOutExprWithLambdaInForeachSequenceAndNestedLambdasVisitor.Create(generatedNamesManager), forIntellisense).ProcessNode(root);
new TryCatchDecorator(new VarNamesInMethodsWithSameNameAsClassGenericParamsReplacer(root as compilation_unit), forIntellisense).ProcessNode(root); new VarNamesInMethodsWithSameNameAsClassGenericParamsReplacer(root as compilation_unit).ProcessNode(root);
new TryCatchDecorator(FindOnExceptVarsAndApplyRenameVisitor.Create(generatedNamesManager), forIntellisense).ProcessNode(root); FindOnExceptVarsAndApplyRenameVisitor.Create(generatedNamesManager).ProcessNode(root);
// дешугаризация составных сравнительных операций (e.g. a == b == c) // дешугаризация составных сравнительных операций (e.g. a == b == c)
new TryCatchDecorator(new CompoundComparisonDesugarVisitor(generatedNamesManager), forIntellisense).ProcessNode(root); new CompoundComparisonDesugarVisitor(generatedNamesManager).ProcessNode(root);
return root; return root;
} }
@ -63,7 +63,7 @@ namespace Languages.SPython.Frontend.Converters
// украл из паскаля, нужны для работы 'for i1, i2 in expr' (работает с кортежными присваиваниями) // украл из паскаля, нужны для работы 'for i1, i2 in expr' (работает с кортежными присваиваниями)
var binder = new BindCollectLightSymInfo(root as compilation_unit); var binder = new BindCollectLightSymInfo(root as compilation_unit);
new TryCatchDecorator(binder, forIntellisense).ProcessNode(root); binder.ProcessNode(root);
new TryCatchDecorator(new NewAssignTuplesDesugarVisitor(binder, generatedNamesManager), forIntellisense).ProcessNode(root); new TryCatchDecorator(new NewAssignTuplesDesugarVisitor(binder, generatedNamesManager), forIntellisense).ProcessNode(root);
// Заменяет // Заменяет
@ -71,26 +71,26 @@ namespace Languages.SPython.Frontend.Converters
// на // на
// variable_name = str(single_length_string) // variable_name = str(single_length_string)
// чтобы при выведении типа правильно вывел str, а не char // чтобы при выведении типа правильно вывел str, а не char
new TryCatchDecorator(new AssignmentCharAsStringVisitor(), forIntellisense).ProcessNode(root); new AssignmentCharAsStringVisitor().ProcessNode(root);
// Сохраняет множество имён функций, которые объявлены в программе для NameCorrectVisitor // Сохраняет множество имён функций, которые объявлены в программе для NameCorrectVisitor
var ffv = new FindFunctionsNamesVisitor(); var ffv = new FindFunctionsNamesVisitor();
new TryCatchDecorator(ffv, forIntellisense).ProcessNode(root); ffv.ProcessNode(root);
// проверка корректности имён, разрешение неоднозначности // проверка корректности имён, разрешение неоднозначности
// сохранение множества переменных, использующихся как глобальные в ncv.variablesUsedAsGlobal // сохранение множества переменных, использующихся как глобальные в ncv.variablesUsedAsGlobal
var ncv = new NameCorrectVisitor(System.IO.Path.GetFileNameWithoutExtension(((compilation_unit)root).file_name), forIntellisense, var ncv = new NameCorrectVisitor(System.IO.Path.GetFileNameWithoutExtension(((compilation_unit)root).file_name), forIntellisense,
compilationArtifacts.NamesFromUsedUnits, ffv.definedFunctionsNames); compilationArtifacts.NamesFromUsedUnits, ffv.definedFunctionsNames);
new TryCatchDecorator(ncv, forIntellisense).ProcessNode(root); ncv.ProcessNode(root);
// замена типов из SPython на типы из PascalABC.NET // замена типов из SPython на типы из PascalABC.NET
if (!forIntellisense) if (!forIntellisense)
new TypeCorrectVisitor().ProcessNode(root); new TypeCorrectVisitor().ProcessNode(root);
// вынос forward объявлений для всех функций в начало // вынос forward объявлений для всех функций в начало
new TryCatchDecorator(new AddForwardDeclarationsVisitor(), forIntellisense).ProcessNode(root); new AddForwardDeclarationsVisitor().ProcessNode(root);
// выполняет генерацию кода для функций с kwarg-аргументами // выполняет генерацию кода для функций с kwarg-аргументами
new TryCatchDecorator(new KwargsFunctionDesugarVisitor(), forIntellisense).ProcessNode(root); new TryCatchDecorator(new KwargsFunctionDesugarVisitor(), forIntellisense).ProcessNode(root);
@ -100,7 +100,7 @@ namespace Languages.SPython.Frontend.Converters
// выносит объявлений переменных из ncv.variablesUsedAsGlobal на глобальный уровень // выносит объявлений переменных из ncv.variablesUsedAsGlobal на глобальный уровень
// (в модулях все переменные, объявленные на глобальном уровне являются глобальными) // (в модулях все переменные, объявленные на глобальном уровне являются глобальными)
new TryCatchDecorator(new RetainUsedGlobalVariablesVisitor(ncv.variablesUsedAsGlobal), forIntellisense).ProcessNode(root); new RetainUsedGlobalVariablesVisitor(ncv.variablesUsedAsGlobal).ProcessNode(root);
// удаление специфичных синтаксических узлов Spython'a перед конвертацией в семантическое дерево // удаление специфичных синтаксических узлов Spython'a перед конвертацией в семантическое дерево
if (!forIntellisense) if (!forIntellisense)
@ -113,15 +113,15 @@ namespace Languages.SPython.Frontend.Converters
// 3) объявление функции %%MAIN%%, содержащей компилируемую программу // 3) объявление функции %%MAIN%%, содержащей компилируемую программу
// 4) объявления функций, объявленных в программе // 4) объявления функций, объявленных в программе
// 5) begin %%MAIN%%() end. // 5) begin %%MAIN%%() end.
new TryCatchDecorator(new TreeNodesRearrangementVisitor(), forIntellisense).ProcessNode(root); new TreeNodesRearrangementVisitor().ProcessNode(root);
return root; return root;
} }
private class TryCatchDecorator private class TryCatchDecorator
{ {
private WalkingVisitorNew internalVisitor; private readonly WalkingVisitorNew internalVisitor;
private bool forIntellisense; private readonly bool forIntellisense;
public TryCatchDecorator(WalkingVisitorNew internalVisitor, bool forIntellisense) public TryCatchDecorator(WalkingVisitorNew internalVisitor, bool forIntellisense)
{ {

View file

@ -14,8 +14,11 @@ namespace Languages.SPython.Frontend.Converters
private readonly ILanguageInformation languageInformation = Facade.LanguageProvider.Instance.SelectLanguageByName("SPython").LanguageInformation; private readonly ILanguageInformation languageInformation = Facade.LanguageProvider.Instance.SelectLanguageByName("SPython").LanguageInformation;
public SymbolTableFillingVisitor(string unitName, Dictionary<string, Dictionary<string, bool>> par) { private readonly bool forIntellisense;
public SymbolTableFillingVisitor(string unitName, bool forIntellisense, Dictionary<string, Dictionary<string, bool>> par) {
symbolTable = new SymbolTable(unitName, par); symbolTable = new SymbolTable(unitName, par);
this.forIntellisense = forIntellisense;
} }
// нужны методы из BaseChangeVisitor, но порядок обхода из WalkingVisitorNew // нужны методы из BaseChangeVisitor, но порядок обхода из WalkingVisitorNew
@ -149,6 +152,9 @@ namespace Languages.SPython.Frontend.Converters
public override void visit(import_statement _import_statement) public override void visit(import_statement _import_statement)
{ {
if (forIntellisense)
return;
foreach (as_statement as_Statement in _import_statement.modules_names.as_statements) foreach (as_statement as_Statement in _import_statement.modules_names.as_statements)
{ {
string real_name = as_Statement.real_name.name; string real_name = as_Statement.real_name.name;
@ -161,6 +167,9 @@ namespace Languages.SPython.Frontend.Converters
public override void visit(from_import_statement _from_import_statement) public override void visit(from_import_statement _from_import_statement)
{ {
if (forIntellisense)
return;
string module_real_name = _from_import_statement.module_name.name; string module_real_name = _from_import_statement.module_name.name;
string module_name = module_real_name; string module_name = module_real_name;
if (languageInformation.SpecialModulesAliases.ContainsKey(module_name)) if (languageInformation.SpecialModulesAliases.ContainsKey(module_name))