public void TestCanEmit_FunctorDefinition() { var consoleWriteLine = AssemblyRegistry.GetCompatibleMethod(assemblyEmitter, "System.Console", "WriteLine", new[] { assemblyEmitter.TypeSystem.String }); var functorType = AssemblyRegistry.GetFunctorType(assemblyEmitter, consoleWriteLine); var localVariable = new VariableDefinition(functorType); BodyCodeBlock = new CodeBlockNode() { Nodes = new List <IParserNode>() { new SymbolDeclarationNode() { Variable = localVariable, Initializer = new FunctionNode() { ExpressionReturnType = functorType, Method = consoleWriteLine } }, new MethodCallNode() { ExpressionReturnType = consoleWriteLine.GetReturnType(), Function = new LocalVariableNode(localVariable), Args = new[] { new LiteralNode(assemblyEmitter.TypeSystem.String, "Hello, world!") } } } }; ExpectedOutput = "Hello, world!"; AssertSuccessByExecution(); }
public static IEnumerable <Node> Collect(CodeBlockNode node) { var c = new ListCollector(); node.Accept(c); return(c.nodes); }
private void AnalyzeCodeBlock(CodeBlockNode codeBlock) { ICollection <StatementNode> statements = codeBlock.Statements; foreach (StatementNode statement in statements) { switch (statement) { case VariableDeclarationStatementNode variableDeclaration: AnalyzeVariableDeclaration(variableDeclaration); break; case VariableAssignmentStatementNode variableAssignment: AnalyzeVariableAssignment(variableAssignment); break; case StandardInputStatementNode standardInputStatement: AnalzyeStandardInputStatement(standardInputStatement); break; case StandardOutputStatementNode standardOutputStatement: AnalyzeStandardOutputStatement(standardOutputStatement); break; default: throw new NotImplementedException($"No semantic analysis implemented for AST node of type `{statement.GetType()}`."); } } }
/// <inheritdoc/> public CompiledFunctionBody Compile(List <AstStatement> statements) { var node = new CodeBlockNode(_context); node.Run(statements); var resultCommandsList = node.Result; #if DEBUG //Log($"resultCommandsList = {resultCommandsList.WriteListToString()}"); #endif NumerateSequence(resultCommandsList); #if DEBUG //Log($"resultCommandsList (2) = {resultCommandsList.WriteListToString()}"); #endif var sehIndex = 0; var result = new CompiledFunctionBody(); foreach (var command in resultCommandsList) { result.Commands.Add(command.Position, ConvertIntermediateScriptCommandToScriptCommand(command, result.SEH, ref sehIndex)); } #if DEBUG //Log($"result = {result}"); //Log($"result = {result.ToDbgString()}"); #endif return(result); }
public void CanPaserEmptySourceBlock() { DocumentNode documentNode = MarkdownStringToDocumentNode( @"#### 1: ```powershell ``` ```powershell [Parameter( ValueFromPipeline = $true, ParameterSetName = 'Set 1')] ``` "); HeadingNode headingNode = this.AssertNodeType <HeadingNode>( documentNode.Children.ElementAtOrDefault(0), MarkdownNodeType.Heading); Assert.Equal(4, headingNode.HeadingLevel); CodeBlockNode codeBlockNode = this.AssertNodeType <CodeBlockNode>( documentNode.Children.ElementAtOrDefault(1), MarkdownNodeType.CodeBlock); Assert.Equal("", codeBlockNode.Text); }
public void CanUseMultiplyInputStrings() { MarkdownParser markdownParser = new MarkdownParser(); DocumentNode documentNode = markdownParser.ParseString(new string[] { @"# Hello ", // TODO: bug: if there is no new-line after header, it fails to parse it. @"This is new line", @"```powershell Code snippet ```" }); Assert.Equal(3, documentNode.Children.Count()); HeadingNode node1 = this.AssertNodeType <HeadingNode>( documentNode.Children.ElementAtOrDefault(0), MarkdownNodeType.Heading); ParagraphNode node2 = this.AssertNodeType <ParagraphNode>( documentNode.Children.ElementAtOrDefault(1), MarkdownNodeType.Paragraph); CodeBlockNode node3 = this.AssertNodeType <CodeBlockNode>( documentNode.Children.ElementAtOrDefault(2), MarkdownNodeType.CodeBlock); }
/// <summary> /// Does the first pass of compilation and returns a list of wanrnings in compilation /// </summary> /// <param name="code"></param> /// <param name="core"></param> /// <param name="blockId"></param> /// <returns></returns> public static ProtoCore.BuildStatus PreCompile(string code, Core core, CodeBlockNode codeBlock, out int blockId) { blockId = ProtoCore.DSASM.Constants.kInvalidIndex; try { //defining the global Assoc block that wraps the entire .ds source file ProtoCore.LanguageCodeBlock globalBlock = new ProtoCore.LanguageCodeBlock(); globalBlock.Language = ProtoCore.Language.Associative; globalBlock.Code = code; //passing the global Assoc wrapper block to the compiler ProtoCore.CompileTime.Context context = new ProtoCore.CompileTime.Context(); ProtoCore.Language id = globalBlock.Language; core.Compilers[id].Compile(out blockId, null, globalBlock, context, codeBlockNode: codeBlock); core.BuildStatus.ReportBuildResult(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); if (!(ex is ProtoCore.BuildHaltException)) { throw ex; } } return(core.BuildStatus); }
// The following methods are used to insert methods to the bottom of the AST and convert operator to these method calls // to support replication on operators private static void InsertUnaryOperationMethod(Core core, CodeBlockNode root, UnaryOperator op, PrimitiveType r, PrimitiveType operand) { FunctionDefinitionNode funcDefNode = new FunctionDefinitionNode(); funcDefNode.Access = CompilerDefinitions.AccessModifier.Public; funcDefNode.IsAssocOperator = true; funcDefNode.IsBuiltIn = true; funcDefNode.Name = Op.GetUnaryOpFunction(op); funcDefNode.ReturnType = new Type() { Name = core.TypeSystem.GetType((int)r), UID = (int)r }; ArgumentSignatureNode args = new ArgumentSignatureNode(); args.AddArgument(new VarDeclNode() { Access = CompilerDefinitions.AccessModifier.Public, NameNode = AstFactory.BuildIdentifier("%param"), ArgumentType = new Type { Name = core.TypeSystem.GetType((int)operand), UID = (int)operand } }); funcDefNode.Signature = args; CodeBlockNode body = new CodeBlockNode(); IdentifierNode param = AstFactory.BuildIdentifier("%param"); body.Body.Add(AstFactory.BuildReturnStatement(new UnaryExpressionNode() { Expression = param, Operator = op })); funcDefNode.FunctionBody = body; root.Body.Add(funcDefNode); }
public Node Parse() { if (tokens.Count == 0) { return(null); } CodeBlockNode module = new CodeBlockNode(); SourcePosition start = CurrentToken.Position; while (position < tokens.Count - 1) { Node statement = ParseStatement(); if (statement == null) { break; } module.Children.Add(statement); } module.Range = new SourceRange(start, CurrentToken.Position); return(module); }
private bool HandleCreateCodeBlockNode(GraphCommand command) { double mouseX = ((double)command.GetArgument(0)); double mouseY = ((double)command.GetArgument(1)); string content = command.GetArgument(2) as string; CodeBlockNode node = new CodeBlockNode(this, content); object parameter = null; int intResult = 0; bool boolResult = false; double dblResult = 0; if (Int32.TryParse(content, out intResult)) { parameter = intResult; } else if (Double.TryParse(content, out dblResult)) { parameter = dblResult; } else if (Boolean.TryParse(content, out boolResult)) { parameter = boolResult; } else { parameter = content; // String type. } this.CreateNodeInternal(node, mouseX, mouseY); return(true); }
/// <summary> /// Does the first pass of compilation and returns a list of wanrnings in compilation /// </summary> /// <param name="code"></param> /// <param name="core"></param> /// <param name="blockId"></param> /// <returns></returns> public static ProtoCore.BuildStatus PreCompile(string code, Core core, CodeBlockNode codeBlock, out int blockId) { core.ExecMode = ProtoCore.DSASM.InterpreterMode.kNormal; blockId = ProtoCore.DSASM.Constants.kInvalidIndex; try { //defining the global Assoc block that wraps the entire .ds source file ProtoCore.LanguageCodeBlock globalBlock = new ProtoCore.LanguageCodeBlock(); globalBlock.language = ProtoCore.Language.kAssociative; globalBlock.body = code; //the wrapper block can be given a unique id to identify it as the global scope globalBlock.id = ProtoCore.LanguageCodeBlock.OUTERMOST_BLOCK_ID; //passing the global Assoc wrapper block to the compiler ProtoCore.CompileTime.Context context = new ProtoCore.CompileTime.Context(); ProtoCore.Language id = globalBlock.language; core.Executives[id].Compile(out blockId, null, globalBlock, context, codeBlockNode: codeBlock); core.BuildStatus.ReportBuildResult(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); if (!(ex is ProtoCore.BuildHaltException)) { throw ex; } } return(core.BuildStatus); }
private static bool CompileCodeBlockAST(Core core, ParseParam parseParams) { Dictionary <int, List <VariableLine> > unboundIdentifiers = new Dictionary <int, List <VariableLine> >(); IEnumerable <BuildData.WarningEntry> warnings = null; ProtoCore.BuildStatus buildStatus = null; try { int blockId = ProtoCore.DSASM.Constants.kInvalidIndex; CodeBlockNode codeblock = new CodeBlockNode(); List <AssociativeNode> nodes = new List <AssociativeNode>(); foreach (var i in parseParams.ParsedNodes) { AssociativeNode assocNode = i as AssociativeNode; if (assocNode != null) { nodes.Add(NodeUtils.Clone(assocNode)); } } codeblock.Body.AddRange(nodes); bool parsingPreloadFlag = core.IsParsingPreloadedAssembly; bool parsingCbnFlag = core.IsParsingPreloadedAssembly; core.IsParsingPreloadedAssembly = false; core.IsParsingCodeBlockNode = true; core.ResetForPrecompilation(); buildStatus = PreCompile(string.Empty, core, codeblock, out blockId); core.IsParsingCodeBlockNode = parsingCbnFlag; core.IsParsingPreloadedAssembly = parsingPreloadFlag; parseParams.AppendErrors(buildStatus.Errors); parseParams.AppendWarnings(buildStatus.Warnings); if (buildStatus.ErrorCount > 0) { return(false); } warnings = buildStatus.Warnings; // Get the unboundIdentifiers from the warnings GetInputLines(parseParams.ParsedNodes, warnings, unboundIdentifiers); foreach (KeyValuePair <int, List <VariableLine> > kvp in unboundIdentifiers) { foreach (VariableLine vl in kvp.Value) { parseParams.AppendUnboundIdentifier(vl.variable); } } return(true); } catch (Exception) { buildStatus = null; return(false); } }
public void ParsesDocumentWithMultipleNodes() { string documentText = string.Format( @" # {0} {2} ``` {1} ``` ## {0} {2} [{3}]({4}) ", headingText, codeBlockText, paragraphText, hyperlinkText, hyperlinkUri); MarkdownParser markdownParser = new MarkdownParser(); DocumentNode documentNode = markdownParser.ParseString( documentText); HeadingNode headingNode = this.AssertNodeType <HeadingNode>( documentNode.Children.ElementAtOrDefault(0), MarkdownNodeType.Heading); Assert.Equal(headingText, headingNode.Text); Assert.Equal(1, headingNode.HeadingLevel); CodeBlockNode codeBlockNode = this.AssertNodeType <CodeBlockNode>( documentNode.Children.ElementAtOrDefault(2), MarkdownNodeType.CodeBlock); Assert.Equal(codeBlockText, codeBlockNode.Text); headingNode = this.AssertNodeType <HeadingNode>( documentNode.Children.ElementAtOrDefault(3), MarkdownNodeType.Heading); Assert.Equal(headingText, headingNode.Text); Assert.Equal(2, headingNode.HeadingLevel); ParagraphNode paragraphNode = this.AssertNodeType <ParagraphNode>( documentNode.Children.ElementAtOrDefault(4), MarkdownNodeType.Paragraph); Assert.Equal(paragraphText.Replace("\r\n", " "), paragraphNode.Spans.First().Text); HyperlinkSpan hyperlinkSpan = Assert.IsType <HyperlinkSpan>( paragraphNode.Spans.ElementAt(1)); Assert.Equal(hyperlinkText, hyperlinkSpan.Text); Assert.Equal(hyperlinkUri, hyperlinkSpan.Uri); }
public void TestCanEmit_FunctorAssignmentToDelegate() { const int kArg1 = 123; const string kArg2 = "fghbsajdnkmf"; var voidType = assemblyEmitter.TypeSystem.Void; var intType = assemblyEmitter.TypeSystem.Int32; var stringType = assemblyEmitter.TypeSystem.String; var arguments = new TypeReference[] { intType, stringType }; var functorType = AssemblyRegistry.GetFunctorType(assemblyEmitter, voidType, arguments); var functorField = new FieldDefinition("myFunction", FieldAttributes.Public | FieldAttributes.Static, functorType); typeEmitter.AddField(functorField); typeEmitter.AddFieldInitializer(functorField, new FunctionNode() { Method = EmitMethodToOutputArgs(null, arguments), ExpressionReturnType = functorType }); var declaringType = (TypeDefinition)typeEmitter.Get(assemblyEmitter); var delegateType = DelegateEmitter.Create(assemblyEmitter, declaringType, voidType, arguments); declaringType.NestedTypes.Add(delegateType); var delegateField = new FieldDefinition("myDelegate", FieldAttributes.Public | FieldAttributes.Static, delegateType); typeEmitter.AddField(delegateField); BodyCodeBlock = new CodeBlockNode() { Nodes = new List <IParserNode>() { new AssignmentOperatorNode() { LeftOperand = new FieldNode(delegateField), RightOperand = new FieldNode(functorField) }, new MethodCallNode() { ExpressionReturnType = voidType, Function = new FieldNode(delegateField), Args = new IExpressionNode[] { new LiteralNode(intType, kArg1), new LiteralNode(stringType, kArg2) } } } }; ExpectedOutput = string.Format("{0}\r\n{1}", kArg1, kArg2); AssertSuccessByExecution(); }
private void Parsing(CodeBlockNode node, string methodName) { for (int i = 0; i < node.ChildCount; i++) { dynamic tmp = node.GetChild(i); Parsing(tmp, methodName); } }
protected MethodEntityBase(bool isImported = false) { Body = new CodeBlockNode(); Arguments = new HashList<FunctionArgument>(); Scope = new Scope(); IsImported = isImported; }
public MethodEntity(TypeEntity type, bool isImported = false) : base(type, isImported) { var scopeKind = type.Kind == TypeEntityKind.Closure ? ScopeKind.LambdaRoot : ScopeKind.FunctionRoot; Body = new CodeBlockNode(scopeKind); }
private static void InsertBuiltInMethods(Core core, CodeBlockNode root) { Lang.BuiltInMethods builtInMethods = new Lang.BuiltInMethods(core); foreach (Lang.BuiltInMethods.BuiltInMethod method in builtInMethods.Methods) { root.Body.Add(GenerateBuiltInMethodSignatureNode(method)); } }
public static void InsertPredefinedAndBuiltinMethods(Core core, CodeBlockNode root) { if (DSASM.InterpreterMode.Normal == core.Options.RunMode) { InsertPredefinedMethod(core, root); InsertBuiltInMethods(core, root); } }
public MethodEntity(TypeEntity type, bool isImported = false) : base(type, isImported) { var scopeKind = type.Kind == TypeEntityKind.Closure ? ScopeKind.LambdaRoot : ScopeKind.FunctionRoot; Body = new CodeBlockNode(scopeKind); }
public DustObject Interpret(CodeBlockNode root) { BoundTree tree = new Binder().Bind(root); /*foreach (Statement statement in root.Children) * {*/ return(EvaluateStatement(tree.Statements[0])); /*}*/ }
public void CopyParsedResults(IParsedScript other) { if (null == other) { return; } this.codeBlockNode = other.GetParsedResults(); }
public void ParsesCodeBlock() { CodeBlockNode codeBlockNode = this.ParseAndGetExpectedChild <CodeBlockNode>( string.Format("```\r\n{0}\r\n```\r\n", codeBlockText), MarkdownNodeType.CodeBlock); Assert.Equal(codeBlockText, codeBlockNode.Text); }
public static IVisualNode Create(IGraphController graphController, IStorage storage) { if (graphController == null || storage == null) { throw new ArgumentNullException("graphcontroller, storage"); } storage.Seek(12, SeekOrigin.Current); //Skip NodeSignature NodeType type = (NodeType)storage.ReadInteger(FieldCode.NodeType); storage.Seek(-24, SeekOrigin.Current); //Shift cursor back to the start point of reading NodeSignature VisualNode node = null; switch (type) { case NodeType.CodeBlock: node = new CodeBlockNode(graphController); node.Deserialize(storage); break; case NodeType.Condensed: node = new CondensedNode(graphController); node.Deserialize(storage); break; case NodeType.Driver: node = new DriverNode(graphController); node.Deserialize(storage); break; case NodeType.Function: node = new FunctionNode(graphController); node.Deserialize(storage); break; case NodeType.Identifier: node = new IdentifierNode(graphController); node.Deserialize(storage); break; case NodeType.Property: node = new PropertyNode(graphController); node.Deserialize(storage); break; case NodeType.Render: node = new RenderNode(graphController); node.Deserialize(storage); break; default: throw new ArgumentException("Invalid 'nodeType'"); } return(node); }
public void TestCanEmit_CallFunctor_PassReturnValueAsArgument() { const int kReturnValue = 75231; const string kArg1 = "Str"; const float kArg2 = 3.5f; var voidType = assemblyEmitter.TypeSystem.Void; var intType = assemblyEmitter.TypeSystem.Int32; var stringType = assemblyEmitter.TypeSystem.String; var floatType = assemblyEmitter.TypeSystem.Single; var functorType = AssemblyRegistry.GetFunctorType(assemblyEmitter, intType, new List <TypeReference>() { stringType, floatType }); var field = new FieldDefinition("myFunction", FieldAttributes.Public | FieldAttributes.Static, functorType); typeEmitter.AddField(field); typeEmitter.AddFieldInitializer(field, new FunctionNode() { ExpressionReturnType = functorType, Method = EmitMethodToOutputArgs(new LiteralNode(intType, kReturnValue), stringType, floatType) }); BodyCodeBlock = new CodeBlockNode() { Nodes = new List <IParserNode>() { CallConsoleWriteLine( new MethodCallNode() { ExpressionReturnType = intType, Function = new FieldNode(field), Args = new List <IExpressionNode>() { new MethodCallNode() { Args = new IExpressionNode[0], Function = new FunctionNode() { ExpressionReturnType = stringType, Method = EmitMethodToOutputArgs(new LiteralNode(stringType, kArg1)) }, ExpressionReturnType = stringType }, new LiteralNode(floatType, kArg2) } }) } }; ExpectedOutput = string.Format("{0}\r\n{1}\r\n{2}", kArg1, kArg2, kReturnValue); AssertSuccessByExecution(); }
private void Parsing(CodeBlockNode node, StringBuilder sb, ref int lineNum) { if (node.Children != null) { foreach (dynamic item in node.Children) { Parsing(item, sb, ref lineNum); } } }
public AstNode Parse() { CodeBlockNode code = new CodeBlockNode(Location); while (position < tokens.Count) { code.Children.Add(parseStatement()); } return(code); }
public void ParsesCodeBlockWithLanguageSpecified() { CodeBlockNode codeBlockNode = this.ParseAndGetExpectedChild <CodeBlockNode>( string.Format("```powershell\r\n{0}\r\n```\r\n", codeBlockText), MarkdownNodeType.CodeBlock); Assert.Equal(codeBlockText, codeBlockNode.Text); Assert.Equal("powershell", codeBlockNode.LanguageMoniker); }
public override AbstractNode VisitCodeBlock([NotNull] GiraphParser.CodeBlockContext context) { //VertexDclsNode VerDclsNode = new VertexDclsNode(context.Start.Line, context.Start.Column); CodeBlockNode CodeNode = new CodeBlockNode(context.Start.Line, context.Start.Column); foreach (var Child in context.codeBlockContent()) { CodeNode.AdoptChildren(Visit(Child.GetChild(0))); } return(CodeNode); }
public BoundTree Bind(CodeBlockNode node) { BoundTree tree = new BoundTree(); foreach (Statement statement in node.Children) { tree.Statements.Add(BindStatement(statement)); } return(tree); }
private void AddAboutCodeBlock(CodeBlockNode codeblockNode) { var lines = codeblockNode.Text.Split(new[] { "\r\n" }, StringSplitOptions.None); foreach (var line in lines) { _stringBuilder.Append(AboutIndentation); _stringBuilder.AppendLine(line); } _stringBuilder.AppendLine(); }
/// <summary> /// API used by external host to build AST for any function call /// </summary> /// <param name="type"></param> /// <param name="hostInstancePtr"></param> /// <param name="functionName"></param> /// <param name="userDefinedArgs"></param> /// <param name="primitiveArgs"></param> /// <param name="formatString"></param> /// <param name="core"></param> /// <param name="symbolName"></param> /// <param name="code"></param> /// <returns></returns> public static AssociativeNode BuildAST(string type, long hostInstancePtr, string functionName, List <IntPtr> userDefinedArgs, List <string> primitiveArgs, string formatString, ProtoCore.Core core, ref string symbolName, ref string code) { symbolName = string.Empty; List <AssociativeNode> astNodes = new List <AssociativeNode>(); FunctionDotCallNode dotCall = null; BinaryExpressionNode bNode = null; ProtoCore.AST.AssociativeAST.FunctionDotCallNode dotCallNode = null; List <AssociativeNode> argNodes = new List <AssociativeNode>(); if (userDefinedArgs != null) { foreach (var arg in userDefinedArgs) { dotCallNode = CreateEntityNode((long)arg, core); bNode = CreateAssignmentNode(dotCallNode); argNodes.Add(bNode); } astNodes.AddRange(argNodes); } List <ProtoCore.AST.AssociativeAST.AssociativeNode> args = CreateArgs(formatString, primitiveArgs, argNodes); if (hostInstancePtr != 0) { dotCallNode = CreateEntityNode(hostInstancePtr, core); bNode = CreateAssignmentNode(dotCallNode); astNodes.Add(bNode); dotCall = CreateFunctionCallNode((bNode.LeftNode as IdentifierNode).Value, functionName, args, core); } else { dotCall = CreateFunctionCallNode(type, functionName, args, core); } bNode = CreateAssignmentNode(dotCall); if (bNode.LeftNode is IdentifierNode) { symbolName = (bNode.LeftNode as IdentifierNode).Value; } astNodes.Add(bNode); CodeBlockNode codeBlockNode = new CodeBlockNode(); codeBlockNode.Body = astNodes; ProtoCore.CodeGenDS codeGen = new ProtoCore.CodeGenDS(astNodes); code = codeGen.GenerateCode(); return(codeBlockNode); }
public override AstNode Process(ParserReader parser) { var reader = parser.Input; reader.Skip("-"); var code = reader.ReadToEndMultiLine(); var node = new CodeBlockNode(code); if (reader.NextLine != null && reader.NextLine.Indent > reader.CurrentLine.Indent) { node.Child = parser.ParseChildren(parser.Indent, node.Child); } return node; }
/// <summary> /// Expands the current rule into a block of checks. /// </summary> public CodeBlockNode ExpandRules(Context ctx, NodeBase expression, Label expressionLabel) { var block = new CodeBlockNode(); // rule is never true: do not emit its code at all if (Condition != null && Condition.IsConstant && Condition.ConstantValue == false) return block; // declare variables foreach (var binding in _BindingSet) block.Add(Expr.Var(binding.Name, binding.Type.FullName)); foreach (var rule in MatchRules) { // current and next labels for each rule var ruleLabels = ParentNode.GetRuleLabels(rule); block.Add(Expr.JumpLabel(ruleLabels.CurrentRule)); block.AddRange(rule.Expand(ctx, expression, ruleLabels.NextRule)); if (Condition != null) { block.Add( Expr.If( Expr.Not(Condition), Expr.Block(Expr.JumpTo(ruleLabels.NextRule)) ) ); } block.Add(Expr.JumpTo(expressionLabel)); } block.AddRange( Expr.JumpLabel(expressionLabel), Expression, Expr.JumpTo(ParentNode.EndLabel) ); return block; }
public ConstructorEntity(TypeEntity type) : base(type) { Body = new CodeBlockNode(ScopeKind.FunctionRoot); }
public CatchNode() { Code = new CodeBlockNode(); }
public AstNode Parse() { CodeBlockNode tree = new CodeBlockNode(); while (!EndOfStream) tree.Children.Add(Nodes.StatementNode.Parse(this)); return tree; }
public FunctionNode() { Body = new CodeBlockNode(ScopeKind.FunctionRoot); }
public void emit(CodeBlockNode codeblock) { astNodes = codeblock.Body; foreach(Node node in astNodes) { dfsTraverse(node); } executable.functionTable = functions; executable.globsize = symbols.globs; executable.debugsymbols = symbols; }
public WhileNode() { Body = new CodeBlockNode(); }
public IfNode() { TrueAction = new CodeBlockNode(); }
protected FunctionNodeBase() { Arguments = new List<FunctionArgument>(); Body = new CodeBlockNode(); }
public virtual void Visit(CodeBlockNode node) { if (node.Child != null) Visit(node.Child); }
public CodeBlockNode(CodeBlockNode rhs) : base(rhs) { Body = new List<ImperativeNode>(); foreach (ImperativeNode aNode in rhs.Body) { ImperativeNode newNode = ProtoCore.Utils.NodeUtils.Clone(aNode); Body.Add(newNode); } }
private List<VisualNode> CreateVisualNodesFromSnapshotNodes(List<SnapshotNode> snapshotNodes) { List<IVisualNode> visualNodes = new List<IVisualNode>(); foreach (SnapshotNode snapshotNode in snapshotNodes) { VisualNode visualNode = new CodeBlockNode(this, snapshotNode); visualNodes.Add(visualNode); this.graphProperties.RuntimeStates.AddVariablesDefinedInNode(visualNode, true); } undoRedoRecorder.RecordNodeCreationForUndo(visualNodes); ValidateDefinedAndReferencedVariables(); List<VisualNode> resultVisualNodes = new List<VisualNode>(); foreach (VisualNode node in visualNodes) resultVisualNodes.Add(node); return resultVisualNodes; }
private static AstNode parseTerm(Parser parser) { if ((string)parser.CurrentToken(1).Value == ":") { LabelNode lnode; if (parser.MatchToken(TokenType.Identifier)) lnode = new LabelNode((string)parser.ExpectToken(TokenType.Identifier).Value); else if (parser.MatchToken(TokenType.Number)) lnode = new LabelNode(Convert.ToString(parser.ExpectToken(TokenType.Number).Value)); else throw new Exception("Unknown label type " + parser.CurrentToken().TokenType + " " + parser.CurrentToken().Value); parser.ExpectToken(TokenType.Identifier, ":"); return lnode; } else if (parser.MatchToken(TokenType.Number)) return new NumberNode(Convert.ToDouble(parser.ExpectToken(TokenType.Number).Value)); else if (parser.AcceptToken(TokenType.Parentheses, "(")) { AstNode statement = ExpressionNode.Parse(parser); parser.ExpectToken(TokenType.Parentheses, ")"); return statement; } else if (parser.MatchToken(TokenType.Identifier, "THEN")) { CodeBlockNode block = new CodeBlockNode(); parser.ExpectToken(TokenType.Identifier, "THEN"); while (!parser.EndOfStream && !parser.MatchToken(TokenType.Identifier, "ENDIF") && !parser.MatchToken(TokenType.Identifier, "ELSE")) block.Children.Add(StatementNode.Parse(parser)); if (parser.MatchToken(TokenType.Identifier, "ELSE")) return block; parser.ExpectToken(TokenType.Identifier, "ENDIF"); return block; } else if (parser.MatchToken(TokenType.Identifier, "ELSE")) { parser.ExpectToken(TokenType.Identifier, "ELSE"); return StatementNode.Parse(parser); } else if (parser.MatchToken(TokenType.Identifier, "DO")) { CodeBlockNode block = new CodeBlockNode(); parser.ExpectToken(TokenType.Identifier, "DO"); while (!parser.EndOfStream && !parser.MatchToken(TokenType.Identifier, "WEND")) block.Children.Add(StatementNode.Parse(parser)); parser.ExpectToken(TokenType.Identifier, "WEND"); return block; } else if (parser.AcceptToken(TokenType.Identifier, "END")) { if (parser.MatchToken(TokenType.Number)) return new EndNode(Convert.ToInt32(parser.ExpectToken(TokenType.Number).Value)); else return new EndNode(); } else if (parser.MatchToken(TokenType.String)) return new StringNode((string)parser.ExpectToken(TokenType.String).Value); else if (parser.MatchToken(TokenType.Identifier)) return new IdentifierNode((string)parser.ExpectToken(TokenType.Identifier).Value); else throw new Exception("Unexpected " + parser.CurrentToken().TokenType + " in Parser: " + parser.CurrentToken().Value + "."); }
public TryNode() { Code = new CodeBlockNode(); CatchClauses = new List<CatchNode>(); }
public override void Visit(CodeBlockNode node) { if (node.Child != null) { WriteStartBlock(node.Code.Trim(), true); VisitAndIdentAlways(node.Child,true); WriteEndBlock(); } else { WriteStartBlock(node.Code.Trim(), false); } }
public LambdaNode() { Body = new CodeBlockNode(ScopeKind.LambdaRoot); }
public WhileNode() { Body = new CodeBlockNode(ScopeKind.Loop); }