public override void action(Node parent, Node child) { // Set the integral type of the expression for type checking the right hand // side of the expression during parsing and at runtime. if (child is VariableDeclarationNode) { VariableDeclarationNode variableDeclarationNode = (VariableDeclarationNode)child; parent.VariableTypeByIntegralType = variableDeclarationNode.IntegralType; } if (parent is AssignmentNode && parent.Instructions.Count >= 2 && parent.Instructions[0] is VariableDeclarationNode) { if (parent.Instructions[0].Instructions.get(0) is UserDefinedTypeNode) { parent.Instructions[0].Instructions.get(0).Instructions.get(2).IntegralType; return; } else { VariableNode variableNode = (VariableNode)parent.Instructions[0].Instructions.get(1); variableNode.IntegralType; /* if (parent.getIntegralType() != variableNode.getIntegralType()) { * throw new RuntimeException( "invalide types used in expressioin"); * }*/ } } if (child is PrimitiveNode && parent.IntegralType != null && parent.IntegralType != child.IntegralType) { throw new Exception("invald types used in expression"); } }
private Statement ProcessVariableDeclarationStatement(VariableDeclarationNode node) { VariableDeclarationStatement statement = new VariableDeclarationStatement(); TypeSymbol variableType = _symbolSet.ResolveType(node.Type, _symbolTable, _memberContext); foreach (VariableInitializerNode initializerNode in node.Initializers) { string name = initializerNode.Name.Name; VariableSymbol symbol = new VariableSymbol(name, _memberContext, variableType); if (initializerNode.Value != null) { Expression value = _expressionBuilder.BuildExpression(initializerNode.Value); if (value is MemberExpression) { value = _expressionBuilder.TransformMemberExpression((MemberExpression)value); } symbol.SetValue(value); } _symbolTable.AddSymbol(symbol); statement.AddVariable(symbol); } return(statement); }
public void TestAddSecondaryArgument() { MethodDeclarationNode mdn = new MethodDeclarationNode("MyMethod"); VariableDeclarationNode vdn = new VariableDeclarationNode("foo"); Assert.IsNull(mdn.SecondaryArguments); mdn.AddSecondaryArgument(vdn, new WordNode("to", PartOfSpeechTag.Preposition)); Assert.AreEqual(1, mdn.SecondaryArguments.Count); var sec = mdn.SecondaryArguments[0]; Assert.AreEqual(vdn, sec.Argument); Assert.AreEqual("to", sec.Preposition.Text); Assert.AreEqual(PartOfSpeechTag.Preposition, sec.Preposition.Tag); VariableDeclarationNode vdn2 = new VariableDeclarationNode("myParam"); mdn.AddSecondaryArgument(vdn2, new WordNode("from", PartOfSpeechTag.Preposition)); Assert.AreEqual(2, mdn.SecondaryArguments.Count); sec = mdn.SecondaryArguments[0]; Assert.AreEqual(vdn, sec.Argument); Assert.AreEqual("to", sec.Preposition.Text); Assert.AreEqual(PartOfSpeechTag.Preposition, sec.Preposition.Tag); sec = mdn.SecondaryArguments[1]; Assert.AreEqual(vdn2, sec.Argument); Assert.AreEqual("from", sec.Preposition.Text); Assert.AreEqual(PartOfSpeechTag.Preposition, sec.Preposition.Tag); }
public static void Walk([NotNull] VariableDeclarationNode variableDeclaration, [NotNull] IList <string> list) { foreach (var variableDeclaratorNode in variableDeclaration.Declarations) { Walk(variableDeclaratorNode, list); } }
/// <summary> /// Parses a variable definition (_variableDefinitionSyntaxRegex) /// </summary> /// <param name="tokenCount"></param> private void ParseVariableDefinition(int tokenCount) { if (tokenCount != 3 && tokenCount != 5) { throw new ParsingException("[BUG] Variable definition parsing requires either three or five tokens."); } var tokens = _remainingTokens.GetRange(0, tokenCount); _remainingTokens.RemoveRange(0, tokenCount); int index = 0; var variableType = (TypeKeywordToken)tokens[index++]; var variableName = (IdentifierToken)tokens[index++]; string variableDefaultValue = null; if (tokenCount == 5) { var assign = (AssignmentToken)tokens[index++]; var variableValue = (IntegerLiteralToken)tokens[index++]; variableDefaultValue = variableValue.Contents; } var variableNode = new VariableDeclarationNode(_currentNode, variableType.Contents, variableName.Contents, variableDefaultValue); _currentNode.AddChild(variableNode); }
public static string GetVariableDeclaration(VariableDeclarationNode variable, string prefix = "") { string arrayStuff = (variable.IsArray && variable.ArraySize != null) ? "[" + variable.ArraySize + "]" : string.Empty; string semantic = (!string.IsNullOrEmpty(variable.Semantic)) ? " : " + variable.Semantic : string.Empty; string initialValue; if (!string.IsNullOrEmpty(variable.InitialValue)) { string variableInitialValue = variable.InitialValue; if (variableInitialValue.StartsWith("sampler_state")) { variableInitialValue = Regex.Replace(variableInitialValue, @"(Texture=\()([\w]+)(\);)", "$1" + prefix + "$2$3"); } initialValue = " = " + variableInitialValue; } else { initialValue = string.Empty; } return(string.Format("{0} {1}{2}{3}{4}{5};", Token.GetString(variable.DataType), prefix, variable.Name, arrayStuff, semantic, initialValue)); }
public void TestCreateEquivalenceFromUnknownArguments_MissizedArray() { var arg1 = new VariableDeclarationNode("arg1"); var mdn = new MethodDeclarationNode("MyMethod"); mdn.AddUnknownArguments(new VariableDeclarationNode[] { arg1 }); EquivalenceNode equiv = mdn.CreateEquivalenceFromUnknownArguments(new PhraseNode(), new bool[] { true, false }); }
public string GetNextSemantic(VariableDeclarationNode variable) { if (!string.IsNullOrEmpty(variable.Semantic)) { return(variable.Semantic); } return(_semanticPrefix + _currentIndex++); }
public void TestCreateEquivalenceFromUnknownArguments_NullNode() { var arg1 = new VariableDeclarationNode("arg1"); var mdn = new MethodDeclarationNode("MyMethod"); mdn.AddUnknownArguments(new VariableDeclarationNode[] { arg1 }); EquivalenceNode equiv = mdn.CreateEquivalenceFromUnknownArguments(null, new bool[] { true }); }
public Node ProcedureDeclaration() { Expect(TokenCategory.PROCEDURE); var procedure_node = new ProcedureDeclarationNode() { AnchorToken = Expect(TokenCategory.IDENTIFIER) }; Expect(TokenCategory.PARENTHESIS_OPEN); procedure_node.Add(new ParameterDeclarationNode() { ZeroOrMore(TokenCategory.IDENTIFIER, ParameterDeclaration) }); Expect(TokenCategory.PARENTHESIS_CLOSE); var typeNode = Optional(TokenCategory.COLON, Type, true); if (typeNode == null) { typeNode = new VoidTypeNode(); } procedure_node.Add(typeNode); Expect(TokenCategory.SEMICOLON); procedure_node.Add(Optional(TokenCategory.CONST, () => { var node = new ConstantListNode() { AnchorToken = Expect(TokenCategory.CONST) }; node.Add(OneOrMore(TokenCategory.IDENTIFIER, ConstantDeclaration)); return(node); })); procedure_node.Add(Optional(TokenCategory.VAR, () => { var node = new VariableDeclarationNode() { AnchorToken = Expect(TokenCategory.VAR) }; node.Add(OneOrMore(TokenCategory.IDENTIFIER, VariableDeclaration)); return(node); })); Expect(TokenCategory.BEGIN); procedure_node.Add(new StatementListNode() { ZeroOrMore(firstOfStatement, Statement) }); Expect(TokenCategory.END); Expect(TokenCategory.SEMICOLON); return(procedure_node); }
/// <summary> /// 变量定义 /// </summary> /// <param name="node"></param> public void Visit(VariableDeclarationNode node) { var builder = new StringBuilder(); builder.Append("变量定义:"); builder.AppendFormat("{0} {1} ", node.Type, node.Name); Console.Write(builder.ToString()); Visit((Object)node.InitialValueExpression); }
public static ITypeRepresentation ToTypeRepresentation(this VariableDeclarationNode variableDeclarationNode) => variableDeclarationNode.Type .Map(t => t.ToTypeRepresentation()) .IfNone(() => variableDeclarationNode.Expression .Map <ITypeRepresentation>(e => new NotInferredTypeRepresentation(e) ) .IfNone(new NoTypeRepresentation()) );
public void TestClearSecondaryArguments_Null_ExistingArgs() { MethodDeclarationNode mdn = new MethodDeclarationNode("MyMethod"); VariableDeclarationNode vdn = new VariableDeclarationNode("foo"); mdn.AddSecondaryArgument(vdn, new WordNode("to", PartOfSpeechTag.Preposition)); Assert.AreEqual(1, mdn.SecondaryArguments.Count); mdn.ClearSecondaryArguments(); Assert.AreEqual(0, mdn.SecondaryArguments.Count); }
public static bool canPrimitiveValueBeAssignedToVar(VariableDeclarationNode lvalue, PrimitiveNode rvalue) { FinalNode rvalueTerminal = (FinalNode)rvalue.Instructions[0]; VariableNode variableNode; if (juserDefined == lvalue.IntegralType) { variableNode = lvalue.UserDefinedNode.VariableNode; } else { variableNode = (VariableNode)lvalue.Instructions[1]; } string data = rvalueTerminal.dataString(); try { switch (variableNode.IntegralType) { case jinteger: return(true); case jdouble: return(true); case jfloat: return(true); case jlong: return(true); case jstring: return(true); case jobject: return(false); case jboolean: return(Convert.ToBoolean(data)); case juserDefined: return(true); default: return(false); } } catch (NumberFormatException) { return(false); } }
public CSharpSyntaxNode Convert(VariableDeclarationNode node) { //TODO: name is ArrayBindingPattern VariableDeclaratorSyntax csVariable = SyntaxFactory.VariableDeclarator(node.Name.Text); if (node.Initializer != null) { csVariable = csVariable.WithInitializer(SyntaxFactory.EqualsValueClause(node.Initializer.ToCsNode <ExpressionSyntax>())); } return(csVariable); }
private void Visit(VariableDeclarationNode node) { var typeName = node.Type.Name; var typeSymbol = _symbolTable.Lookup <TypeSymbol>(typeName); foreach (var variable in node.Variables) { //var varSymbol = _symbolTable.Lookup<VariableSymbol>(variable.Name); var varSymbol = new VariableSymbol(variable.Name, typeSymbol); _symbolTable.Insert(varSymbol); } }
public override Node visitVariableDeclarationExpression(JuliarParser.VariableDeclarationExpressionContext ctx) { VariableDeclarationNode node = new VariableDeclarationNode(); iterateWrapper(ctx, this, node); if (node.Instructions.Count == 0 || node.Instructions.Count == 2) { // variable has been declared but will be set to null by default. node.addInst(new FinalNode()); } return(node); }
public static Either <ParseException, ProgramNode> Parse(List <IToken> tokens) { Console.WriteLine("ProgramNode"); var declarations = new List <IDeclarationNode>(); var typeTable = new Dictionary <string, IEntityType>(); var symT = new SymT(); var result = new ProgramNode(declarations, symT, typeTable); while (tokens.Count > 0) { var maybeRoutineDeclaration = RoutineDeclarationNode.Parse(tokens, symT, result); if (maybeRoutineDeclaration.IsRight) { tokens = maybeRoutineDeclaration.RightToList()[0].First; var routineDeclaration = maybeRoutineDeclaration.RightToList()[0].Second; declarations.Add(routineDeclaration); typeTable.TryAdd(routineDeclaration.Identifier.Lexeme, routineDeclaration.ToRoutineType()); continue; } var maybeVariableDeclaration = VariableDeclarationNode.Parse(tokens, symT, result); if (maybeVariableDeclaration.IsRight) { tokens = maybeVariableDeclaration.RightToList()[0].First; var varDecl = maybeVariableDeclaration.RightToList()[0].Second; declarations.Add(varDecl); typeTable.TryAdd(varDecl.Identifier.Lexeme, varDecl.ToVariableType()); continue; } var maybeTypeDeclaration = TypeDeclarationNode.Parse(tokens, symT, result); if (maybeTypeDeclaration.IsRight) { tokens = maybeTypeDeclaration.RightToList()[0].First; var typeDecl = maybeTypeDeclaration.RightToList()[0].Second; declarations.Add(typeDecl); typeTable.TryAdd(typeDecl.Identifier.Lexeme, typeDecl.ToTypeAliasType()); continue; } return(maybeTypeDeclaration.LeftToList()[0]); } Console.WriteLine("Program is interprited Successfully"); return(new ProgramNode(declarations, symT, typeTable)); //return Either<ParseException, ProgramNode>.Bottom; }
public void TestAddUnknownArgument() { MethodDeclarationNode mdn = new MethodDeclarationNode("MyMethod"); TypeNode arg = new TypeNode("int", true); mdn.AddUnknownArgument(arg); Assert.IsNotNull(mdn.UnknownArguments); Assert.AreEqual(1, mdn.UnknownArguments.Count); Assert.AreEqual(arg, mdn.UnknownArguments[0]); VariableDeclarationNode vdn = new VariableDeclarationNode("foo"); mdn.AddUnknownArgument(vdn); Assert.AreEqual(2, mdn.UnknownArguments.Count); Assert.AreEqual(arg, mdn.UnknownArguments[0]); Assert.AreEqual(vdn, mdn.UnknownArguments[1]); }
private VariableDeclaration BindVariableDeclaration(VariableDeclarationNode node) { const bool isReadOnly = false; var variableType = BindTypeClause(node.Type); var initializer = node.Initializer == null ? null : BindExpression(node.Initializer); if (variableType == null && initializer != null) // infer the variable type from its initializer { variableType = initializer.Type; } var variable = BindVariable(node.VariableName, isReadOnly, variableType); var realInitializer = initializer == null?BindDefaultInitializer(variableType) : BindConversion(node.Initializer, initializer, variableType); return(new VariableDeclaration(Scope, variable, realInitializer)); }
private void InferType(VariableDeclarationList node) { if (node.Type == null) { if (node.Declarations.Count > 0) { VariableDeclarationNode variableNode = (node.Declarations[0] as VariableDeclarationNode); if (variableNode.Type == null) { this.Visit(variableNode); } node.SetType(variableNode.Type, false); } else { node.SetType(NodeHelper.CreateNode(NodeKind.AnyKeyword)); } } }
public CSharpSyntaxNode Convert(VariableDeclarationList node) { bool isVar = false; Node type = node.Type; if (type.Kind == NodeKind.AnyKeyword && node.Declarations.Count > 0) { VariableDeclarationNode variableNode = node.Declarations[0] as VariableDeclarationNode; if (variableNode.Initializer != null && variableNode.Initializer.Kind != NodeKind.NullKeyword) { isVar = true; } } TypeSyntax csType = isVar ? SyntaxFactory.IdentifierName("var") : node.Type.ToCsNode <TypeSyntax>(); return(SyntaxFactory .VariableDeclaration(csType) .AddVariables(node.Declarations.ToCsNodes <VariableDeclaratorSyntax>())); }
public override Node visitVariableDeclaration(JuliarParser.VariableDeclarationContext ctx) { VariableDeclarationNode variableDeclarationNode = new VariableDeclarationNode(); new IterateOverContext(this, ctx, this, variableDeclarationNode); VariableNode variableNode; if (variableDeclarationNode.Instructions[0] is UserDefinedTypeNode) { variableNode = (VariableNode)variableDeclarationNode.Instructions[0].Instructions[2]; variableNode.VariableType = ctx.children.get(0).getChild(0).Text; } else if (variableDeclarationNode.Instructions.Count >= 2) { variableNode = (VariableNode)variableDeclarationNode.Instructions[1]; variableNode.VariableType = ctx.children.get(0).Text; } return(variableDeclarationNode); }
public Type Visit(VariableDeclarationNode node) { foreach (var typeNode in node) { Type type = Visit((dynamic)typeNode); foreach (var idNode in typeNode) { var varName = idNode.AnchorToken.Lexeme; if (CurrentScopeHasSymbol(varName)) { throw new SemanticError($"Duplicated variable: {varName}", idNode.AnchorToken); } else { AddSymbolToScope(varName, type, Kind.VAR, value: type.DefaultValue()); } } } return(Type.VOID); }
private void InferType(VariableDeclarationNode node) { if (node.Type == null) { if (node.Parent.Kind == NodeKind.CatchClause) { node.SetType(NodeHelper.CreateNode(NodeKind.Identifier, "Exception")); } else { Node type = null; if (node.Initializer != null) { type = TypeHelper.GetNodeType(node.Initializer); } type = type ?? NodeHelper.CreateNode(NodeKind.AnyKeyword); node.SetType(type, type.Parent == null); } } }
public void TestCreateEquivalenceFromUnknownArguments() { var arg1 = new VariableDeclarationNode("arg1"); var arg2 = new VariableDeclarationNode("arg2"); var arg3 = new VariableDeclarationNode("arg3"); var arg4 = new VariableDeclarationNode("arg4"); var mdn = new MethodDeclarationNode("MyMethod"); mdn.AddUnknownArguments(new VariableDeclarationNode[] { arg1, arg2, arg3, arg4 }); Assert.AreEqual(4, mdn.UnknownArguments.Count); var themeNode = new PhraseNode(new string[] { "Relevent", "Args" }); EquivalenceNode equiv = mdn.CreateEquivalenceFromUnknownArguments(themeNode, new bool[] { true, false, true, false }); Assert.AreEqual(3, equiv.EquivalentNodes.Count); Assert.IsTrue(equiv.EquivalentNodes.Contains(themeNode)); Assert.IsTrue(equiv.EquivalentNodes.Contains(arg1)); Assert.IsTrue(equiv.EquivalentNodes.Contains(arg3)); Assert.AreEqual(2, mdn.UnknownArguments.Count); Assert.IsTrue(mdn.UnknownArguments.Contains(arg2)); Assert.IsTrue(mdn.UnknownArguments.Contains(arg4)); }
private static void Walk([NotNull] Agent agent, [NotNull] VariableDeclarationNode variableDeclaration, bool isStrict) { if (variableDeclaration.Kind != VariableKind.Var) { //https://tc39.github.io/ecma262/#sec-let-and-const-declarations-static-semantics-early-errors var boundNames = BoundNamesWalker.Walk(variableDeclaration); if (ContainsDuplicate(boundNames)) { throw agent.CreateSyntaxError(); } if (boundNames.Contains("let")) { throw agent.CreateSyntaxError(); } } foreach (var variableDeclarator in variableDeclaration.Declarations) { Walk(agent, variableDeclarator, isStrict); } }
private void Visit(VariableDeclarationNode node) { foreach (var variable in node.Variables) { if (GlobalVariables.ContainsKey(variable.Name)) { ReportError(new Exception($"Variable \"{variable.Name}\" already declared in global scope!")); continue; } var type = node.Type.Name; var expression = Visit(node.Expression); if (node.Type.IsInferred) { if (expression == null) { ReportError(new Exception("Cannot infer variable type without a value!")); return; } type = expression.GetType().Name; } GlobalVariables.Add(variable.Name, new VariableInfo(type, Visit(node.Expression))); } }
public static IList <Node> evalAssignment(Node n, ActivationFrame activationFrame, Interpreter calback) { AssignmentNode assignmentNode = (AssignmentNode)n; IList <Node> instructions = assignmentNode.Instructions; const int varDeclIndex = 0; const int equalSignIndex = 1; const int primtiveIndex = 2; VariableDeclarationNode variableToAssignTo = (VariableDeclarationNode)instructions[varDeclIndex]; // | zero | one | two // | variableDecl | EqualSign | Primitive // | int variableName | = | 3 if (instructions[equalSignIndex] is EqualSignNode) { object rvalue = instructions[primtiveIndex]; if (rvalue is FunctionCallNode) { functionCallNode((FunctionCallNode)rvalue, activationFrame, variableToAssignTo); } if (rvalue is PrimitiveNode) { primitiveInstance((PrimitiveNode)rvalue, activationFrame, variableToAssignTo); } if (rvalue is BooleanNode) { booleanInstance((BooleanNode)rvalue, activationFrame, variableToAssignTo); } if (rvalue is CommandNode) { commandInstance((CommandNode)rvalue, activationFrame, variableToAssignTo); } } return(new List <>()); }
private static void GenerateVariableDeclaration(VariableDeclarationNode node, DataContext data) { data.VariableMap.DeclareVariable(node.VariableName, node.Line, node.Column); StartLine(data, "context.DeclareVariable(\"{0}\"", node.VariableName); if (node.ValueExpression != null) { Append(data, ", value: "); GenerateExpression(node.ValueExpression, data); } EndLine(data, ");"); }
public StructDefinitionNode(string name, FunctionDefinitionNode[] functions, VariableDeclarationNode[] variables, Token token, int tokenIndex) : base(token, tokenIndex) { Name = name; Functions = functions; Variables = variables; }
public virtual T Visit(VariableDeclarationNode node) => Visit(node as Node);
private void ParseVariableDeclaration(Node subtree) { VariableDeclarationNode node = new VariableDeclarationNode(subtree); VariableNode var = new VariableNode(node); if (tokens.CurrentToken == TokenType.Const) { var.Const = true; tokens.Next(); } tokens.ConsumeToken(TokenType.Type); var.Type = tokens.LastToken.Value; if (tokens.CurrentToken == TokenType.LeftSquare) { var.IsArray = true; tokens.Next(); tokens.ConsumeToken(TokenType.Number); var.ArraySize = uint.Parse(tokens.LastToken.Value); //Currently no variable sized arrays tokens.ConsumeToken(TokenType.RightSquare); } tokens.ConsumeToken(TokenType.Ident); //name var.Ident = tokens.LastToken.Value; SymbolTable.AddVariable(var.Ident, var); if (tokens.CurrentToken == TokenType.Delim) tokens.Next(); //and we're done else { if (tokens.CurrentToken == TokenType.Assign) { tokens.Next(); ParseExpression(node); } else { //something went wrong ErrorHandler.RaiseError(new UnexpectedTokenError(tokens.CurrentToken, " assignment operator or a delim", tokens.CurrentToken.LineNo)); } } }