From 160fafef70269279cf4af97d05937cd3e143cae3 Mon Sep 17 00:00:00 2001 From: Lan_G <2911328695@qq.com> Date: Mon, 6 May 2024 00:12:57 +0800 Subject: [PATCH] =?UTF-8?q?misc:=20=E6=B8=85=E9=99=A4=E5=86=97=E4=BD=99?= =?UTF-8?q?=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reviewed-on: https://git.rrricardo.top/PostGuard/Canon/pulls/75 Co-authored-by: Lan_G <2911328695@qq.com> Co-committed-by: Lan_G <2911328695@qq.com> --- Canon.Core/Abstractions/ICCodeGenerator.cs | 11 - Canon.Core/CodeGenerators/CCodeBuilder.cs | 6 - Canon.Core/Exceptions/SemanticException.cs | 12 - .../SemanticParser/CCodeGenerateVisitor.cs | 623 ------------------ Canon.Core/SemanticParser/TypeCheckVisitor.cs | 38 +- Canon.Core/SemanticParser/TypeTable.cs | 2 - Canon.Core/SyntaxNodes/AddOperator.cs | 1 - Canon.Core/SyntaxNodes/BasicType.cs | 2 - Canon.Core/SyntaxNodes/ConstValue.cs | 1 - Canon.Core/SyntaxNodes/ElsePart.cs | 1 - Canon.Core/SyntaxNodes/Expression.cs | 57 -- Canon.Core/SyntaxNodes/ExpressionList.cs | 18 - Canon.Core/SyntaxNodes/Factor.cs | 17 - Canon.Core/SyntaxNodes/IdentifierVarPart.cs | 6 - Canon.Core/SyntaxNodes/MultiplyOperator.cs | 1 - Canon.Core/SyntaxNodes/Parameter.cs | 6 - Canon.Core/SyntaxNodes/ProgramBody.cs | 16 - Canon.Core/SyntaxNodes/ProgramStruct.cs | 6 - Canon.Core/SyntaxNodes/RelationOperator.cs | 1 - Canon.Core/SyntaxNodes/SimpleExpression.cs | 21 - Canon.Core/SyntaxNodes/Statement.cs | 1 - Canon.Core/SyntaxNodes/StatementList.cs | 1 - Canon.Core/SyntaxNodes/Subprogram.cs | 11 - Canon.Core/SyntaxNodes/SubprogramBody.cs | 16 - Canon.Core/SyntaxNodes/SubprogramHead.cs | 2 - Canon.Core/SyntaxNodes/SyntaxNodeBase.cs | 1 - Canon.Core/SyntaxNodes/Term.cs | 21 - Canon.Core/SyntaxNodes/TypeSyntaxNode.cs | 6 - Canon.Core/SyntaxNodes/VarParameter.cs | 1 - Canon.Core/SyntaxNodes/Variable.cs | 1 - 30 files changed, 11 insertions(+), 896 deletions(-) delete mode 100644 Canon.Core/Abstractions/ICCodeGenerator.cs delete mode 100644 Canon.Core/Exceptions/SemanticException.cs delete mode 100644 Canon.Core/SemanticParser/CCodeGenerateVisitor.cs diff --git a/Canon.Core/Abstractions/ICCodeGenerator.cs b/Canon.Core/Abstractions/ICCodeGenerator.cs deleted file mode 100644 index a8181f0..0000000 --- a/Canon.Core/Abstractions/ICCodeGenerator.cs +++ /dev/null @@ -1,11 +0,0 @@ -using Canon.Core.CodeGenerators; - -namespace Canon.Core.Abstractions; - -/// -/// 支持生成C语言代码的接口 -/// -public interface ICCodeGenerator -{ - public void GenerateCCode(CCodeBuilder builder); -} diff --git a/Canon.Core/CodeGenerators/CCodeBuilder.cs b/Canon.Core/CodeGenerators/CCodeBuilder.cs index 347bf6d..aab6d89 100644 --- a/Canon.Core/CodeGenerators/CCodeBuilder.cs +++ b/Canon.Core/CodeGenerators/CCodeBuilder.cs @@ -1,5 +1,4 @@ using System.Text; -using Canon.Core.SemanticParser; namespace Canon.Core.CodeGenerators; @@ -13,11 +12,6 @@ public class CCodeBuilder private int _scopeCount = 0; private string _scopeEmpty = string.Empty; - public void AddString(string code) - { - _builder.Append(code); - } - public void AddLine(string code) { foreach (string line in code.Split('\n')) diff --git a/Canon.Core/Exceptions/SemanticException.cs b/Canon.Core/Exceptions/SemanticException.cs deleted file mode 100644 index ddb9201..0000000 --- a/Canon.Core/Exceptions/SemanticException.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Canon.Core.Exceptions; -/// -/// 语义分析中引发的异常 -/// -public class SemanticException : Exception -{ - public SemanticException() : base() { } - - public SemanticException(string message) : base(message) { } - - public SemanticException(string message, Exception innerException) : base(message, innerException) { } -} diff --git a/Canon.Core/SemanticParser/CCodeGenerateVisitor.cs b/Canon.Core/SemanticParser/CCodeGenerateVisitor.cs deleted file mode 100644 index cf539ff..0000000 --- a/Canon.Core/SemanticParser/CCodeGenerateVisitor.cs +++ /dev/null @@ -1,623 +0,0 @@ -using System.Globalization; -using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; -using Canon.Core.Enums; -using Canon.Core.LexicalParser; -using Canon.Core.SyntaxNodes; -using BasicType = Canon.Core.SyntaxNodes.BasicType; - -namespace Canon.Core.SemanticParser; - -public class CCodeGenerateVisitor(ICompilerLogger? logger = null) : TypeCheckVisitor(logger) -{ - public CCodeBuilder Builder { get; } = new(); - - public override void PreVisit(ProgramStruct programStruct) - { - base.PreVisit(programStruct); - - Builder.AddString("#include \n"); - Builder.AddString("#include \n"); - } - - private string? _constValue; - public override void PreVisit(ConstDeclaration constDeclaration) - { - base.PreVisit(constDeclaration); - (_, ConstValue constValue) = constDeclaration.ConstValue; - constValue.OnCharacterGenerator += (_, e) => - { - _constValue = "'" + e.Token.LiteralValue + "'"; - }; - constValue.OnNumberGenerator += (_, e) => - { - if (e.IsNegative) - { - _constValue = "-"; - } - - if (e.Token.NumberType == NumberType.Integer) - { - _constValue += e.Token.ParseAsInteger(); - } - else - { - _constValue += e.Token.ParseAsReal(); - } - }; - } - - public override void PostVisit(ConstDeclaration constDeclaration) - { - base.PostVisit(constDeclaration); - (IdentifierSemanticToken token, ConstValue constValue) = constDeclaration.ConstValue; - - string cTypeName = TryParseBasicType(constValue.ConstType); - Builder.AddString("const " + cTypeName + " " + token.IdentifierName + " = " + _constValue + ";\n"); - _constValue = ""; - } - - public override void PostVisit(VarDeclaration varDeclaration) - { - base.PostVisit(varDeclaration); - - string idName = varDeclaration.Token.IdentifierName; - var type = varDeclaration.IdentifierList.DefinitionType; - - if (type is PascalBasicType) - { - Builder.AddString(idName + ";\n"); - } - else - { - TryParseArrayType(type, out string _, out string periods); - Builder.AddString(idName + periods + ";\n"); - } - - } - - public override void PreVisit(IdentifierList identifierList) - { - base.PreVisit(identifierList); - identifierList.OnTypeGenerator += (_, e) => - { - e.TypeSyntaxNode.IsProcedure = identifierList.IsProcedure; - }; - } - - public override void PostVisit(IdentifierList identifierList) - { - base.PostVisit(identifierList); - identifierList.OnIdentifierGenerator += (_, e) => - { - if(!identifierList.IsProcedure) - { - string periods = ""; //如果是数组定义,需要每个标识符后带上 - if (e.IdentifierList.DefinitionType is PascalArrayType pascalArrayType) - { - TryParseArrayType(pascalArrayType, out string _, out string periods0); - periods = periods0; - } - - Builder.AddString(e.IdentifierToken.IdentifierName + periods + ", "); - } - }; - } - - - public override void PreVisit(TypeSyntaxNode typeSyntaxNode) - { - base.PreVisit(typeSyntaxNode); - typeSyntaxNode.OnBasicTypeGenerator += (_, e) => - { - e.BasicType.IsProcedure = typeSyntaxNode.IsProcedure; - }; - typeSyntaxNode.OnArrayTypeGenerator += (_, e) => - { - e.BasicType.IsProcedure = typeSyntaxNode.IsProcedure; - }; - } - - public override void PostVisit(BasicType basicType) - { - base.PostVisit(basicType); - if (!basicType.IsProcedure) - { - Builder.AddString(TryParseBasicType(basicType.PascalType) + " "); - } - } - - - public override void PostVisit(SubprogramHead subprogramHead) - { - base.PostVisit(subprogramHead); - - string subprogramName = subprogramHead.SubprogramName.IdentifierName; - //只需特判过程,函数的返回值类型已在basicType节点上生成 - if (subprogramHead.IsProcedure) - { - Builder.AddString("void "); - } - Builder.AddString(subprogramName); - //生成参数列表 - Builder.AddString("("); - List parametersInfo = new(); - - foreach (List children in ValueParameters) - { - foreach (Symbol symbol in children.AsEnumerable().Reverse()) - { - if (symbol.SymbolType is PascalBasicType pascalType) - { - string typeName = TryParseBasicType(pascalType); - if (symbol.Reference) - { - parametersInfo.Add(typeName + "* " + symbol.SymbolName); - } - else - { - parametersInfo.Add(typeName + " " + symbol.SymbolName); - } - } - else - { - TryParseArrayType(symbol.SymbolType, out string basicTypeName, out string periods); - parametersInfo.Add(string.Concat(basicTypeName, " ", symbol.SymbolName, "[]", - periods.Substring(periods.IndexOf(']') + 1))); - } - } - } - Builder.AddString(string.Join(", ", parametersInfo)); - Builder.AddString(")\n"); - } - - private string _subprogramName = ""; - public override void PreVisit(Subprogram subprogram) - { - base.PreVisit(subprogram); - _subprogramName = subprogram.Head.SubprogramName.IdentifierName; - } - - public override void PostVisit(Subprogram subprogram) - { - base.PostVisit(subprogram); - if (subprogram.Head.IsProcedure) - { - Builder.AddString("\n}\n"); - } - else - { - //为函数生成返回语句 - Builder.AddString("return " + subprogram.Head.SubprogramName.IdentifierName + ";\n}\n"); - } - } - - public override void PreVisit(SubprogramBody subprogramBody) - { - base.PreVisit(subprogramBody); - Builder.AddString("{\n"); - //生成函数返回值变量 - SymbolTable.TryGetSymbol(_subprogramName, out var symbol); - if (symbol is null || symbol.SymbolType is not PascalBasicType) - { - return; - } - - Builder.AddString(TryParseBasicType(symbol.SymbolType.Convert()) + " " + _subprogramName + ";\n"); - } - - public override void PreVisit(ProcedureCall procedureCall) - { - base.PreVisit(procedureCall); - string procedureName = procedureCall.ProcedureId.IdentifierName; - - if (procedureName == "read") - { - Builder.AddString("scanf(\"%d\", &"); - return; - } - if (procedureName == "write") - { - Builder.AddString("printf(\"%d\", "); - return; - } - - Builder.AddString(procedureName + "("); - - procedureCall.OnParameterGenerator += (_, e) => - { - string procedureIdName = procedureCall.ProcedureId.IdentifierName; - - SymbolTable.TryGetParent(out var parentTable); - parentTable ??= SymbolTable; - - parentTable.TryGetSymbol(procedureIdName, out var symbol); - - if (symbol is null) - { - return; - } - e.Parameters.ParameterTypes.AddRange(symbol.SymbolType.Convert().Parameters); - e.Parameters.Expression.LastParam = true; - e.Parameters.IsParamList = true; - }; - } - - public override void PostVisit(ProcedureCall procedureCall) - { - base.PostVisit(procedureCall); - Builder.AddString(")"); - } - - public override void PreVisit(ProgramBody programBody) - { - base.PreVisit(programBody); - //当子函数全部定义完成时,生成main函数头 - programBody.CompoundStatement.IsMain = true; - } - - public override void PostVisit(CompoundStatement compoundStatement) - { - base.PostVisit(compoundStatement); - if (compoundStatement.IsMain) - { - Builder.AddString("\nreturn 0;\n"); - } - Builder.AddString("}\n"); - } - - public override void PreVisit(CompoundStatement compoundStatement) - { - base.PreVisit(compoundStatement); - if (compoundStatement.IsMain) - { - Builder.AddString("int main()\n"); - } - Builder.AddString("{\n"); - } - - public override void PreVisit(Statement statement) - { - base.PreVisit(statement); - statement.OnForGenerator += (_, e) => - { - e.Begin.Iterator = e.Iterator; - e.Begin.IsForConditionBegin = true; - e.End.Iterator = e.Iterator; - e.End.IsForConditionEnd = true; - }; - statement.OnAssignGenerator += (_, e) => - { - e.Expression.IsAssign = true; - }; - } - - public override void PostVisit(Statement statement) - { - base.PostVisit(statement); - Builder.AddString(";\n"); - } - - public override void PreVisit(Variable variable) - { - base.PreVisit(variable); - - SymbolTable.TryGetSymbol(variable.Identifier.IdentifierName, out var symbol); - if (symbol == null) - { - return; - } - - if (symbol.Reference) - { - Builder.AddString("(*" + variable.Identifier.IdentifierName + ")"); - } - else - { - Builder.AddString(variable.Identifier.IdentifierName); - } - - if (symbol.SymbolType is PascalArrayType) - { - //解析数组类型,获取左边界列表 - List leftBounds = new(); - PascalType curType = symbol.SymbolType; - while (curType is not PascalBasicType) - { - leftBounds.Add(curType.Convert().Begin); - curType = curType.Convert().ElementType; - } - - //将数组维度信息向下传递 - variable.VarPart.LeftBounds.AddRange(leftBounds); - } - } - - public override void PreVisit(IdentifierVarPart identifierVarPart) - { - base.PreVisit(identifierVarPart); - identifierVarPart.OnIndexGenerator += (_, e) => - { - e.IndexParameters.IsIndex = true; - e.IndexParameters.LeftBounds = identifierVarPart.LeftBounds; - }; - } - - public override void PreVisit(ExpressionList expressionList) - { - base.PreVisit(expressionList); - - if (expressionList.IsIndex) - { - expressionList.Expression.LeftBound = expressionList.LeftBounds.Last(); - expressionList.Expression.IsIndex = true; - } - - if (expressionList.IsParamList) - { - expressionList.Expression.ReferenceParam = expressionList.ParameterTypes.Last().IsVar; - expressionList.Expression.IsParam = true; - } - expressionList.OnExpressionList += (_, e) => - { - if (expressionList.IsIndex) - { - e.ExpressionList.IsIndex = true; - expressionList.LeftBounds.RemoveAt(expressionList.LeftBounds.Count - 1); - e.ExpressionList.LeftBounds = expressionList.LeftBounds; - } - - if (expressionList.IsParamList) - { - e.ExpressionList.IsParamList = true; - for (int i = 0; i < expressionList.ParameterTypes.Count - 1; i++) - { - e.ExpressionList.ParameterTypes.Add(expressionList.ParameterTypes[i]); - } - } - }; - } - - public override void PreVisit(Expression expression) - { - base.PreVisit(expression); - if (expression.IsIndex) - { - Builder.AddString("["); - } - - if (expression.IsForConditionBegin) - { - Builder.AddString("for(" + expression.Iterator.IdentifierName + " = "); - } - if (expression.IsForConditionEnd) - { - Builder.AddString(expression.Iterator.IdentifierName + " <= "); - } - if (expression.IsAssign) - { - Builder.AddString(" = "); - } - - if (expression.ReferenceParam) - { - Builder.AddString("&"); - } - } - - public override void PostVisit(Expression expression) - { - base.PostVisit(expression); - if (expression.IsIndex) - { - //数组下标减去当前维度的左边界 - Builder.AddString("-" + expression.LeftBound + "]"); - } - if (expression.IsForConditionEnd) - { - Builder.AddString("; " + expression.Iterator.IdentifierName + "++)"); - } - if (expression is { IsParam: true, LastParam: false }) - { - Builder.AddString(", "); - } - } - - public override void PostVisit(Factor factor) - { - base.PostVisit(factor); - factor.OnNumberGenerator += (_, e) => - { - var token = e.Token; - string num = token.NumberType == NumberType.Integer ? token.ParseAsInteger().ToString() : - token.ParseAsReal().ToString(CultureInfo.InvariantCulture); - Builder.AddString(num); - }; - factor.OnNotGenerator += (_, _) => - { - Builder.AddString(")"); - }; - factor.OnUminusGenerator += (_, _) => - { - Builder.AddString(")"); - }; - } - - public override void PreVisit(Factor factor) - { - base.PreVisit(factor); - - factor.OnNotGenerator += (_, _) => - { - Builder.AddString("(~"); - }; - factor.OnUminusGenerator += (_, _) => - { - Builder.AddString("(-"); - }; - } - - public override void PostVisit(MultiplyOperator multiplyOperator) - { - base.PostVisit(multiplyOperator); - if (multiplyOperator.OperatorToken.TokenType == SemanticTokenType.Operator) - { - var operatorType = multiplyOperator.OperatorToken.Convert().OperatorType; - if (operatorType == OperatorType.Multiply) - { - Builder.AddString(" * "); - } - else if (operatorType == OperatorType.Divide) - { - //实数除法,需要将操作数强转为double - Builder.AddString(" /(double)"); - } - } - else - { - var keywordType = multiplyOperator.OperatorToken.Convert().KeywordType; - switch (keywordType) - { - case KeywordType.And: - Builder.AddString(" && "); - break; - case KeywordType.Mod: - Builder.AddString(" % "); - break; - default: - Builder.AddString(" / "); - break; - } - } - } - - public override void PostVisit(AddOperator addOperator) - { - base.PostVisit(addOperator); - var token = addOperator.OperatorToken; - if (token.TokenType == SemanticTokenType.Operator) - { - var operatorType = token.Convert().OperatorType; - if (operatorType == OperatorType.Plus) - { - Builder.AddString(" + "); - } - else if (operatorType == OperatorType.Minus) - { - Builder.AddString(" - "); - } - } - else - { - Builder.AddString(" || "); - } - } - - public override void PostVisit(RelationOperator relationOperator) - { - base.PostVisit(relationOperator); - var operatorType = relationOperator.OperatorToken.Convert().OperatorType; - switch (operatorType) - { - case OperatorType.Equal: - Builder.AddString(" == "); - break; - case OperatorType.Greater: - Builder.AddString(" > "); - break; - case OperatorType.Less: - Builder.AddString(" < "); - break; - case OperatorType.GreaterEqual: - Builder.AddString(" >= "); - break; - case OperatorType.LessEqual: - Builder.AddString(" <= "); - break; - case OperatorType.NotEqual: - Builder.AddString(" != "); - break; - } - } - - public override void PostVisit(TerminatedSyntaxNode terminatedSyntaxNode) - { - base.PostVisit(terminatedSyntaxNode); - string literalValue = terminatedSyntaxNode.Token.LiteralValue; - switch (literalValue) - { - case "if": - Builder.AddString("if("); - break; - case "then": - Builder.AddString(")\n"); - break; - case "else": - Builder.AddString("else\n"); - break; - case "to": - Builder.AddString("; "); - break; - } - } - - /// - /// 尝试将pascalBasicType解析成C语言的基本类型 - /// - /// C语言形式的基本类型名 - /// - private string TryParseBasicType(PascalType pascalType) - { - if (pascalType is PascalBasicType basicType) - { - if (basicType == PascalBasicType.Integer) - { - return "int"; - } - if (basicType == PascalBasicType.Real) - { - return "double"; - } - - if (basicType == PascalBasicType.Character) - { - return "char"; - } - - if (basicType == PascalBasicType.Boolean) - { - return "bool"; - } - - if (basicType == PascalBasicType.Void) - { - return "void"; - } - } - - throw new InvalidOperationException("Not a basic type"); - } - - /// - /// 尝试解析Pascal数组类型 - /// - /// - /// 数组实际存储的元素类型 - /// 数组下标定义 - private void TryParseArrayType(PascalType pascalType, out string basicTypeName, out string periods) - { - periods = ""; - PascalType curType = pascalType; - //依次处理数组每一维 - while (curType is PascalArrayType pascalArrayType) - { - int begin = pascalArrayType.Begin; - int end = pascalArrayType.End; - //C语言数组下标从0开始,所以下标要减去begin - periods += "[" + (end - begin + 1) + "]"; - curType = pascalArrayType.ElementType; - } - - basicTypeName = TryParseBasicType(curType); - } -} diff --git a/Canon.Core/SemanticParser/TypeCheckVisitor.cs b/Canon.Core/SemanticParser/TypeCheckVisitor.cs index e5693c8..b2599e3 100644 --- a/Canon.Core/SemanticParser/TypeCheckVisitor.cs +++ b/Canon.Core/SemanticParser/TypeCheckVisitor.cs @@ -87,11 +87,9 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito switch (e.Token.NumberType) { case NumberType.Integer: - factor.FactorType = PascalBasicType.Integer; factor.VariableType = PascalBasicType.Integer; break; case NumberType.Real: - factor.FactorType = PascalBasicType.Real; factor.VariableType = PascalBasicType.Real; break; } @@ -100,14 +98,12 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito // factor -> true | false factor.OnBooleanGenerator += (_, _) => { - factor.FactorType = PascalBasicType.Boolean; factor.VariableType = PascalBasicType.Boolean; }; // factor -> variable factor.OnVariableGenerator += (_, e) => { - factor.FactorType = e.Variable.VariableType; factor.VariableType = e.Variable.VariableType; }; @@ -115,7 +111,6 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito // factor -> (expression) factor.OnParethnesisGenerator += (_, e) => { - factor.FactorType = e.Expression.ExpressionType; factor.VariableType = e.Expression.VariableType; }; @@ -126,7 +121,6 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito { if (functionType.ReturnType != PascalBasicType.Void) { - factor.FactorType = functionType.ReturnType; factor.VariableType = functionType.ReturnType; return; } @@ -137,28 +131,24 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito } } - factor.FactorType = PascalBasicType.Void; factor.VariableType = PascalBasicType.Void; }; // factor -> not factor factor.OnNotGenerator += (_, e) => { - factor.FactorType = e.Factor.FactorType; factor.VariableType = e.Factor.VariableType; }; // factor -> uminus factor factor.OnUminusGenerator += (_, e) => { - factor.FactorType = e.Factor.FactorType; factor.VariableType = e.Factor.VariableType; }; // factor -> plus factor factor.OnPlusGenerator += (_, e) => { - factor.FactorType = e.Factor.FactorType; factor.VariableType = e.Factor.VariableType; }; } @@ -169,16 +159,14 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito term.OnFactorGenerator += (_, e) => { - term.TermType = e.Factor.FactorType; term.VariableType = e.Factor.VariableType; }; term.OnMultiplyGenerator += (_, e) => { - if (PascalType.IsCalculatable(e.Left.TermType) && PascalType.IsCalculatable(e.Right.FactorType)) + if (PascalType.IsCalculatable(e.Left.VariableType) && PascalType.IsCalculatable(e.Right.VariableType)) { - term.TermType = e.Left.TermType + e.Right.FactorType; - term.VariableType = e.Left.TermType + e.Right.FactorType; + term.VariableType = e.Left.VariableType + e.Right.VariableType; return; } @@ -193,15 +181,13 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito simpleExpression.OnTermGenerator += (_, e) => { - simpleExpression.SimpleExpressionType = e.Term.TermType; simpleExpression.VariableType = e.Term.VariableType; }; simpleExpression.OnAddGenerator += (_, e) => { - if (PascalType.IsCalculatable(e.Left.SimpleExpressionType) && PascalType.IsCalculatable(e.Right.TermType)) + if (PascalType.IsCalculatable(e.Left.VariableType) && PascalType.IsCalculatable(e.Right.VariableType)) { - simpleExpression.SimpleExpressionType = e.Left.SimpleExpressionType + e.Right.TermType; simpleExpression.VariableType = e.Left.VariableType + e.Right.VariableType; return; } @@ -217,13 +203,11 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito expression.OnSimpleExpressionGenerator += (_, e) => { - expression.ExpressionType = e.SimpleExpression.SimpleExpressionType; expression.VariableType = e.SimpleExpression.VariableType; }; expression.OnRelationGenerator += (_, _) => { - expression.ExpressionType = PascalBasicType.Boolean; expression.VariableType = PascalBasicType.Boolean; }; } @@ -468,7 +452,7 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito } // 检查ExpressionA是否为Integer - if (e.Begin.ExpressionType != PascalBasicType.Integer) + if (e.Begin.VariableType != PascalBasicType.Integer) { IsError = true; logger?.LogError("The loop begin parameter is not integer."); @@ -476,7 +460,7 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito } // 检查ExpressionB是否为Integer - if (e.End.ExpressionType != PascalBasicType.Integer) + if (e.End.VariableType != PascalBasicType.Integer) { IsError = true; logger?.LogError("The loop end parameter is not integer."); @@ -487,11 +471,11 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito statement.OnIfGenerator += (_, e) => { // 条件是否为Boolean - if (e.Condition.ExpressionType != PascalBasicType.Boolean) + if (e.Condition.VariableType != PascalBasicType.Boolean) { IsError = true; logger?.LogError("Expect '{}' but '{}'.", PascalBasicType.Boolean.TypeName, - e.Condition.ExpressionType.ToString()); + e.Condition.VariableType.ToString()); } }; } @@ -566,11 +550,11 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito { foreach (Expression expression in e.IndexParameters.Expressions) { - if (expression.ExpressionType != PascalBasicType.Integer) + if (expression.VariableType != PascalBasicType.Integer) { IsError = true; logger?.LogError("Index of array expect 'int' but '{}'", - expression.ExpressionType.ToString()); + expression.VariableType.ToString()); } } @@ -652,11 +636,11 @@ public class TypeCheckVisitor(ICompilerLogger? logger = null) : SyntaxNodeVisito foreach ((Expression expression, PascalParameterType parameterType) in parameters.Zip(targetFunctionType .Parameters)) { - if (expression.ExpressionType != parameterType.ParameterType) + if (expression.VariableType != parameterType.ParameterType) { IsError = true; logger?.LogError("Parameter expect '{}' but '{}' is provided.", - parameterType.ParameterType, expression.ExpressionType); + parameterType.ParameterType, expression.VariableType); } } diff --git a/Canon.Core/SemanticParser/TypeTable.cs b/Canon.Core/SemanticParser/TypeTable.cs index 6b82f0e..b68718b 100644 --- a/Canon.Core/SemanticParser/TypeTable.cs +++ b/Canon.Core/SemanticParser/TypeTable.cs @@ -1,6 +1,4 @@ using System.Diagnostics.CodeAnalysis; -using System.Security; -using Canon.Core.Exceptions; namespace Canon.Core.SemanticParser; diff --git a/Canon.Core/SyntaxNodes/AddOperator.cs b/Canon.Core/SyntaxNodes/AddOperator.cs index e54dbd1..70223ee 100644 --- a/Canon.Core/SyntaxNodes/AddOperator.cs +++ b/Canon.Core/SyntaxNodes/AddOperator.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; using Canon.Core.LexicalParser; diff --git a/Canon.Core/SyntaxNodes/BasicType.cs b/Canon.Core/SyntaxNodes/BasicType.cs index 12964a5..f2133f7 100644 --- a/Canon.Core/SyntaxNodes/BasicType.cs +++ b/Canon.Core/SyntaxNodes/BasicType.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; using Canon.Core.LexicalParser; using Canon.Core.SemanticParser; @@ -10,7 +9,6 @@ public class BasicType : NonTerminatedSyntaxNode { public override NonTerminatorType Type => NonTerminatorType.BasicType; - public bool IsProcedure; /// /// BasicType代表的Pascal类型 /// diff --git a/Canon.Core/SyntaxNodes/ConstValue.cs b/Canon.Core/SyntaxNodes/ConstValue.cs index 5d58fad..48111a6 100644 --- a/Canon.Core/SyntaxNodes/ConstValue.cs +++ b/Canon.Core/SyntaxNodes/ConstValue.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; using Canon.Core.LexicalParser; using Canon.Core.SemanticParser; diff --git a/Canon.Core/SyntaxNodes/ElsePart.cs b/Canon.Core/SyntaxNodes/ElsePart.cs index a20bfcf..3760639 100644 --- a/Canon.Core/SyntaxNodes/ElsePart.cs +++ b/Canon.Core/SyntaxNodes/ElsePart.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; namespace Canon.Core.SyntaxNodes; diff --git a/Canon.Core/SyntaxNodes/Expression.cs b/Canon.Core/SyntaxNodes/Expression.cs index 95c727d..5a21e73 100644 --- a/Canon.Core/SyntaxNodes/Expression.cs +++ b/Canon.Core/SyntaxNodes/Expression.cs @@ -1,8 +1,5 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; -using Canon.Core.LexicalParser; -using Canon.Core.SemanticParser; namespace Canon.Core.SyntaxNodes; @@ -36,21 +33,6 @@ public class Expression : NonTerminatedSyntaxNode RaiseEvent(); } - public bool IsParam; //是否为传参 - - public bool ReferenceParam; //是否为引用传参 - - public bool LastParam; //是否为传参列表里最后一个参数 - /// - /// 是否为数组下标 - /// - public bool IsIndex { get; set; } - - /// - /// 当前表达式对应的数组下标维度的左边界 - /// - public int LeftBound; - /// /// 是否为FOR语句中的起始语句 /// @@ -60,32 +42,12 @@ public class Expression : NonTerminatedSyntaxNode /// 是否为FOR语句中的结束语句 /// public bool IsForConditionEnd { get; set; } - public bool IsAssign { get; set; } /// /// 是否为IF语句中的条件语句 /// public bool IsIfCondition { get; set; } - private IdentifierSemanticToken? _iterator; - - public IdentifierSemanticToken Iterator - { - get - { - if (_iterator is null) - { - throw new InvalidOperationException(); - } - - return _iterator; - } - set - { - _iterator = value; - } - } - /// /// 直接赋值产生式的事件 /// @@ -96,25 +58,6 @@ public class Expression : NonTerminatedSyntaxNode /// public event EventHandler? OnRelationGenerator; - private PascalType? _expressionType; - - public PascalType ExpressionType - { - get - { - if (_expressionType is null) - { - throw new InvalidOperationException(); - } - - return _expressionType; - } - set - { - _expressionType = value; - } - } - public static Expression Create(List children) { return new Expression { Children = children }; diff --git a/Canon.Core/SyntaxNodes/ExpressionList.cs b/Canon.Core/SyntaxNodes/ExpressionList.cs index 9b3c1b0..0b45d12 100644 --- a/Canon.Core/SyntaxNodes/ExpressionList.cs +++ b/Canon.Core/SyntaxNodes/ExpressionList.cs @@ -1,6 +1,5 @@ using Canon.Core.Abstractions; using Canon.Core.Enums; -using Canon.Core.SemanticParser; namespace Canon.Core.SyntaxNodes; @@ -18,23 +17,6 @@ public class ExpressionList : NonTerminatedSyntaxNode /// public List Expressions { get; } = []; - /// - /// 是否为传参列表 - /// - public bool IsParamList; - - public List ParameterTypes { get; } = []; - - /// - /// 是否为数组下标索引 - /// - public bool IsIndex { get; set; } - - /// - /// 数组左边界列表 - /// - public List LeftBounds = new(); - /// /// 当前ExpressionList中的Expression定义 /// diff --git a/Canon.Core/SyntaxNodes/Factor.cs b/Canon.Core/SyntaxNodes/Factor.cs index 39ccb0e..03ed69d 100644 --- a/Canon.Core/SyntaxNodes/Factor.cs +++ b/Canon.Core/SyntaxNodes/Factor.cs @@ -1,7 +1,6 @@ using Canon.Core.Abstractions; using Canon.Core.Enums; using Canon.Core.LexicalParser; -using Canon.Core.SemanticParser; namespace Canon.Core.SyntaxNodes; @@ -103,22 +102,6 @@ public class Factor : NonTerminatedSyntaxNode /// public event EventHandler? OnProcedureCallGenerator; - private PascalType? _factorType; - - public PascalType FactorType - { - get - { - if (_factorType is null) - { - throw new InvalidOperationException(); - } - - return _factorType; - } - set { _factorType = value; } - } - public static Factor Create(List children) { return new Factor { Children = children }; diff --git a/Canon.Core/SyntaxNodes/IdentifierVarPart.cs b/Canon.Core/SyntaxNodes/IdentifierVarPart.cs index e48aa79..ee297af 100644 --- a/Canon.Core/SyntaxNodes/IdentifierVarPart.cs +++ b/Canon.Core/SyntaxNodes/IdentifierVarPart.cs @@ -1,6 +1,5 @@ using Canon.Core.Abstractions; using Canon.Core.Enums; -using Canon.Core.SemanticParser; namespace Canon.Core.SyntaxNodes; @@ -18,11 +17,6 @@ public class IdentifierVarPart : NonTerminatedSyntaxNode /// public int IndexCount { get; set; } - /// - /// 数组左边界列表 - /// - public List LeftBounds = new(); - /// /// 索引中的表达式 /// diff --git a/Canon.Core/SyntaxNodes/MultiplyOperator.cs b/Canon.Core/SyntaxNodes/MultiplyOperator.cs index b949ab8..1d90069 100644 --- a/Canon.Core/SyntaxNodes/MultiplyOperator.cs +++ b/Canon.Core/SyntaxNodes/MultiplyOperator.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; using Canon.Core.LexicalParser; diff --git a/Canon.Core/SyntaxNodes/Parameter.cs b/Canon.Core/SyntaxNodes/Parameter.cs index f4c4acc..3fe4f53 100644 --- a/Canon.Core/SyntaxNodes/Parameter.cs +++ b/Canon.Core/SyntaxNodes/Parameter.cs @@ -12,12 +12,6 @@ public class Parameter : NonTerminatedSyntaxNode /// public bool IsVar { get; private init; } - /// - /// 声明的变量名称 - /// - public ValueParameter ValueParameter => - IsVar ? Children[0].Convert().ValueParameter : Children[0].Convert(); - public override void PreVisit(SyntaxNodeVisitor visitor) { visitor.PreVisit(this); diff --git a/Canon.Core/SyntaxNodes/ProgramBody.cs b/Canon.Core/SyntaxNodes/ProgramBody.cs index 6cb2d67..e231515 100644 --- a/Canon.Core/SyntaxNodes/ProgramBody.cs +++ b/Canon.Core/SyntaxNodes/ProgramBody.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; namespace Canon.Core.SyntaxNodes; @@ -8,21 +7,6 @@ public class ProgramBody : NonTerminatedSyntaxNode { public override NonTerminatorType Type => NonTerminatorType.ProgramBody; - /// - /// 常量声明 - /// - public ConstDeclarations ConstDeclarations => Children[0].Convert(); - - /// - /// 变量声明 - /// - public VarDeclarations VarDeclarations => Children[1].Convert(); - - /// - /// 子程序声明 - /// - public SubprogramDeclarations SubprogramDeclarations => Children[2].Convert(); - /// /// 语句声明 /// diff --git a/Canon.Core/SyntaxNodes/ProgramStruct.cs b/Canon.Core/SyntaxNodes/ProgramStruct.cs index 6a5f760..bc1c7d0 100644 --- a/Canon.Core/SyntaxNodes/ProgramStruct.cs +++ b/Canon.Core/SyntaxNodes/ProgramStruct.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; namespace Canon.Core.SyntaxNodes; @@ -13,11 +12,6 @@ public class ProgramStruct : NonTerminatedSyntaxNode /// public ProgramHead Head => Children[0].Convert(); - /// - /// 程序体 - /// - public ProgramBody Body => Children[2].Convert(); - public override void PreVisit(SyntaxNodeVisitor visitor) { visitor.PreVisit(this); diff --git a/Canon.Core/SyntaxNodes/RelationOperator.cs b/Canon.Core/SyntaxNodes/RelationOperator.cs index 2788fe0..b62fba6 100644 --- a/Canon.Core/SyntaxNodes/RelationOperator.cs +++ b/Canon.Core/SyntaxNodes/RelationOperator.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; using Canon.Core.LexicalParser; diff --git a/Canon.Core/SyntaxNodes/SimpleExpression.cs b/Canon.Core/SyntaxNodes/SimpleExpression.cs index da938da..65a27c1 100644 --- a/Canon.Core/SyntaxNodes/SimpleExpression.cs +++ b/Canon.Core/SyntaxNodes/SimpleExpression.cs @@ -1,7 +1,5 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; -using Canon.Core.SemanticParser; namespace Canon.Core.SyntaxNodes; @@ -45,25 +43,6 @@ public class SimpleExpression : NonTerminatedSyntaxNode /// public event EventHandler? OnAddGenerator; - private PascalType? _simpleExpressionType; - - public PascalType SimpleExpressionType - { - get - { - if (_simpleExpressionType is null) - { - throw new InvalidOperationException(); - } - - return _simpleExpressionType; - } - set - { - _simpleExpressionType = value; - } - } - public static SimpleExpression Create(List children) { return new SimpleExpression { Children = children }; diff --git a/Canon.Core/SyntaxNodes/Statement.cs b/Canon.Core/SyntaxNodes/Statement.cs index 0242502..0cfec9a 100644 --- a/Canon.Core/SyntaxNodes/Statement.cs +++ b/Canon.Core/SyntaxNodes/Statement.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; using Canon.Core.LexicalParser; diff --git a/Canon.Core/SyntaxNodes/StatementList.cs b/Canon.Core/SyntaxNodes/StatementList.cs index 210784d..0741d52 100644 --- a/Canon.Core/SyntaxNodes/StatementList.cs +++ b/Canon.Core/SyntaxNodes/StatementList.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; namespace Canon.Core.SyntaxNodes; diff --git a/Canon.Core/SyntaxNodes/Subprogram.cs b/Canon.Core/SyntaxNodes/Subprogram.cs index 454937f..ffcd449 100644 --- a/Canon.Core/SyntaxNodes/Subprogram.cs +++ b/Canon.Core/SyntaxNodes/Subprogram.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; namespace Canon.Core.SyntaxNodes; @@ -8,16 +7,6 @@ public class Subprogram : NonTerminatedSyntaxNode { public override NonTerminatorType Type => NonTerminatorType.Subprogram; - /// - /// 子程序头部 - /// - public SubprogramHead Head => Children[0].Convert(); - - /// - /// 子程序体 - /// - public SubprogramBody Body => Children[2].Convert(); - public override void PreVisit(SyntaxNodeVisitor visitor) { visitor.PreVisit(this); diff --git a/Canon.Core/SyntaxNodes/SubprogramBody.cs b/Canon.Core/SyntaxNodes/SubprogramBody.cs index 186f062..abd9934 100644 --- a/Canon.Core/SyntaxNodes/SubprogramBody.cs +++ b/Canon.Core/SyntaxNodes/SubprogramBody.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; namespace Canon.Core.SyntaxNodes; @@ -8,21 +7,6 @@ public class SubprogramBody : NonTerminatedSyntaxNode { public override NonTerminatorType Type => NonTerminatorType.SubprogramBody; - /// - /// 常量声明部分 - /// - public ConstDeclarations ConstDeclarations => Children[0].Convert(); - - /// - /// 变量声明部分 - /// - public VarDeclarations VarDeclarations => Children[1].Convert(); - - /// - /// 语句声明部分 - /// - public CompoundStatement CompoundStatement => Children[2].Convert(); - public override void PreVisit(SyntaxNodeVisitor visitor) { visitor.PreVisit(this); diff --git a/Canon.Core/SyntaxNodes/SubprogramHead.cs b/Canon.Core/SyntaxNodes/SubprogramHead.cs index 5778046..7f1c2ce 100644 --- a/Canon.Core/SyntaxNodes/SubprogramHead.cs +++ b/Canon.Core/SyntaxNodes/SubprogramHead.cs @@ -26,8 +26,6 @@ public class SubprogramHead : NonTerminatedSyntaxNode public IdentifierSemanticToken SubprogramName => Children[1].Convert().Token.Convert(); - public FormalParameter Parameters => Children[2].Convert(); - public override void PreVisit(SyntaxNodeVisitor visitor) { visitor.PreVisit(this); diff --git a/Canon.Core/SyntaxNodes/SyntaxNodeBase.cs b/Canon.Core/SyntaxNodes/SyntaxNodeBase.cs index cc8e808..aaadad7 100644 --- a/Canon.Core/SyntaxNodes/SyntaxNodeBase.cs +++ b/Canon.Core/SyntaxNodes/SyntaxNodeBase.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; using Canon.Core.LexicalParser; diff --git a/Canon.Core/SyntaxNodes/Term.cs b/Canon.Core/SyntaxNodes/Term.cs index 23fcf6f..d9b0b7e 100644 --- a/Canon.Core/SyntaxNodes/Term.cs +++ b/Canon.Core/SyntaxNodes/Term.cs @@ -1,7 +1,5 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; -using Canon.Core.SemanticParser; namespace Canon.Core.SyntaxNodes; @@ -45,25 +43,6 @@ public class Term : NonTerminatedSyntaxNode /// public event EventHandler? OnMultiplyGenerator; - private PascalType? _termType; - - public PascalType TermType - { - get - { - if (_termType is null) - { - throw new InvalidOperationException(); - } - - return _termType; - } - set - { - _termType = value; - } - } - public static Term Create(List children) { return new Term { Children = children }; diff --git a/Canon.Core/SyntaxNodes/TypeSyntaxNode.cs b/Canon.Core/SyntaxNodes/TypeSyntaxNode.cs index a8d0441..948e1cc 100644 --- a/Canon.Core/SyntaxNodes/TypeSyntaxNode.cs +++ b/Canon.Core/SyntaxNodes/TypeSyntaxNode.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; using Canon.Core.SemanticParser; @@ -37,11 +36,6 @@ public class TypeSyntaxNode : NonTerminatedSyntaxNode public event EventHandler? OnArrayTypeGenerator; - /// - /// 是否在过程定义中使用 - /// - public bool IsProcedure { get; set; } - private PascalType? _pascalType; /// diff --git a/Canon.Core/SyntaxNodes/VarParameter.cs b/Canon.Core/SyntaxNodes/VarParameter.cs index a2ade7c..bde81e3 100644 --- a/Canon.Core/SyntaxNodes/VarParameter.cs +++ b/Canon.Core/SyntaxNodes/VarParameter.cs @@ -1,5 +1,4 @@ using Canon.Core.Abstractions; -using Canon.Core.CodeGenerators; using Canon.Core.Enums; namespace Canon.Core.SyntaxNodes; diff --git a/Canon.Core/SyntaxNodes/Variable.cs b/Canon.Core/SyntaxNodes/Variable.cs index 7e58364..7dfdbf6 100644 --- a/Canon.Core/SyntaxNodes/Variable.cs +++ b/Canon.Core/SyntaxNodes/Variable.cs @@ -1,7 +1,6 @@ using Canon.Core.Abstractions; using Canon.Core.Enums; using Canon.Core.LexicalParser; -using Canon.Core.SemanticParser; namespace Canon.Core.SyntaxNodes;