internal static ISemanticNode Or(BranchParseNode branch, Func <BranchParseNode, ISemanticNode> recurse) { ISemanticNode left = recurse(branch.GetDescendant(0)); ISemanticNode right = recurse(branch.GetDescendant(2)); return(new BranchSemanticNode((int)EbnfNodeType.Or, left, right)); }
public void SingleToken() { var grammar = $@" abc = ""abc""; root = abc; "; var settings = new ParserSettings { Algorithm = Parser.Algorithm.LL, NestingType = Parser.NestingType.Stack, Unit = Parser.Unit.Character, }; Parser parser = parserGen.SpawnParser(settings, grammar); parser.AttachAction("abc", (branch, recurse) => { var value = branch.Leaf.MatchedText; var startIndex = branch.Leaf.StartIndex; return(new LeafSemanticNode(0, startIndex, value)); }); parser.AttachAction("root", (branch, recurse) => { return(recurse(branch.GetDescendant(0))); }); parser.Lock(); ISemanticNode result = parser.Parse("abc"); }
internal static ISemanticNode FunctionCall(BranchParseNode branch, Func <BranchParseNode, ISemanticNode> recurse) { ISemanticNode @ref = recurse(branch.GetDescendant(0)); BranchParseNode first = branch.GetDescendant(1, 0, 1, 0); BranchParseNode fragments = branch.GetDescendant(1, 0, 1, 1); if (first != null) { if (fragments != null) { ISemanticNode args = CompositeExpression(recurse(first), fragments, recurse); return(new BranchSemanticNode((int)JsNodeType.FunctionCall, @ref, args)); } else { return(new BranchSemanticNode((int)JsNodeType.FunctionCall, @ref, recurse(first))); } } else { return(new BranchSemanticNode((int)JsNodeType.FunctionCall, @ref)); } }
internal static ISemanticNode PropertyAssignment(BranchParseNode branch, Func <BranchParseNode, ISemanticNode> recurse) { ISemanticNode lvalue = recurse(branch.GetDescendant(0)); ISemanticNode rvalue = recurse(branch.GetDescendant(2)); return(new BranchSemanticNode((int)JsNodeType.Assignment, lvalue, rvalue)); }
private static ISemanticNode CompositeExpression(ISemanticNode first, IEnumerable <ISemanticNode> rest) { ISemanticNode result = first; foreach (ISemanticNode fragment in rest) { JsNodeType nodeType; switch ((JsNodeType)fragment.NodeType) { case JsNodeType.ArgumentList: nodeType = JsNodeType.FunctionCall; break; case JsNodeType.DotReference: case JsNodeType.KeyReference: nodeType = JsNodeType.Property; break; default: throw new Exception(); } result = new BranchSemanticNode((int)nodeType, result, fragment); } return(result); }
internal static ISemanticNode CompositeExpression(BranchParseNode branch, Func <BranchParseNode, ISemanticNode> recurse) { ISemanticNode first = recurse(branch.GetDescendant(0)); BranchParseNode fragments = branch.GetDescendant(1); return(CompositeExpression(first, fragments, recurse)); }
internal static ISemanticNode And(BranchParseNode branch, Func <BranchParseNode, ISemanticNode> recurse) { branch = branch.Unwrap(); ISemanticNode left = recurse(branch.GetDescendant(0)); ISemanticNode right = recurse(branch.GetDescendant(1)); return(new BranchSemanticNode((int)EbnfNodeType.And, left, right)); }
public void RealCode() { var source = Resources.LoadString("Tests.Resources.angular-mocks.js"); Parser parser = Standard.GetParser(); parser.Lock(); ISemanticNode tree = parser.Parse(source); }
public void Parse() { var text = Standard.Text; Parser parser = Standard.GetParser(); parser.Lock(); ISemanticNode tree = parser.Parse(text); }
public Grammar BuildGrammar(string grammar, params string[] implicitNames) { var resultGrammar = new Grammar(); foreach (var name in implicitNames) { resultGrammar.SetImplicit(name); } parser.Lock(); ISemanticNode semantics = parser.Parse(grammar); var root = (BranchSemanticNode)semantics; foreach (BranchSemanticNode decl in root.Children.Cast <BranchSemanticNode>()) { var left = (LeafSemanticNode)decl.Children[0]; var name = left.Value; ISemanticNode right = decl.Children[1]; if (right is BranchSemanticNode branch) { Rule rule = Interpret(resultGrammar, right); resultGrammar.DefineRule(name, rule); } else if (right is LeafSemanticNode leaf) { switch ((EbnfNodeType)leaf.NodeType) { case EbnfNodeType.Identifier: resultGrammar.DefineRule(name, resultGrammar.ReferenceRule(leaf.Value)); break; case EbnfNodeType.String: resultGrammar.DefineString(name, leaf.Value); break; case EbnfNodeType.Regex: resultGrammar.DefineRegex(name, leaf.Value); break; default: throw new Exception(); } } else { throw new Exception(); } } return(resultGrammar); }
internal static ISemanticNode Token(BranchParseNode branch, Func <BranchParseNode, ISemanticNode> recurse) { BranchParseNode identNode = branch.GetDescendant(0); var ident = identNode.Leaf.MatchedText; var startIndex = identNode.Leaf.StartIndex; var name = new LeafSemanticNode((int)EbnfNodeType.Identifier, startIndex, ident); ISemanticNode expr = recurse(branch.GetDescendant(2)); return(new BranchSemanticNode((int)EbnfNodeType.Token, name.StartIndex, new[] { name, expr })); }
public ISemanticNode Parse(string input) { if (!IsLocked) { throw new Exception(); } BranchParseNode parseTree = ParseSyntax(input); ISemanticNode semanticTree = ParseSemantics(parseTree); return(semanticTree); }
private static List <ISemanticNode> ExpressionFragments(BranchParseNode fragments, Func <BranchParseNode, ISemanticNode> recurse) { ISemanticNode first = recurse(fragments.GetDescendant(0)); BranchParseNode restNode = fragments.GetDescendant(1); if (restNode != null) { List <ISemanticNode> rest = ExpressionFragments(restNode, recurse); return(new[] { first }.Concat(rest).ToList()); } else { return(new[] { first }.ToList()); } }
public CommandParser(Parameters parameters) { command = new Command("", parameters); var grammar = $@" equals = ""=""; shortOptions = /(?<= )-[_\w]+/; shortOption = /(?<= )-[_\w]/; longOption = /(?<= )--[_\w][-_\w]*/; endOptions = /(?<= )--(?= )/; doubleString = /""(?:\\\\""|\\\\[^""]|[^""\\\\])*""/; singleString = /'(?:\\\\'|\\\\[^']|[^'\\\\])*'/; identifier = /[_\w][-_\w]*/; literal = /.+/; ws = /\s+/; path = /(([A-Za-z]:)?[\/\\\\])?[-_\\w.]+([\/\\\\][-_\\w.]+)*[\/\\\\]?/; string = doubleString | singleString; shortOptionWithValue = shortOption equals (identifier | string); longOptionWithValue = longOption equals (identifier | string); options = *(shortOptionWithValue | longOptionWithValue | shortOptions | longOption | identifier | string); details = options ?(endOptions literal); root = (string | path) ?details; "; var parserGen = new ParserGenerator(); var settings = new ParserSettings { Algorithm = Algorithm.LL, NestingType = NestingType.Stack, Unit = Unit.Character, }; parser = parserGen.SpawnParser(settings, grammar, "ws"); parser.AttachAction("shortOptions", (branch, recurse) => { var startIndex = branch.Leaf.StartIndex; IEnumerable <BranchSemanticNode> nodes = branch.Leaf.MatchedText .Skip(1) .Select((c, i) => { return(new BranchSemanticNode((int)CommandNodeType.Argument, new LeafSemanticNode((int)CommandNodeType.ShortOption, startIndex + 1 + i, c.ToString()))); }); return(new BranchSemanticNode((int)CommandNodeType.Arguments, startIndex, nodes)); }); parser.AttachAction("shortOption", (branch, recurse) => { LeafParseNode nameNode = branch.Leaf; var startIndex = nameNode.StartIndex; var name = nameNode.MatchedText[1].ToString(); return(new BranchSemanticNode((int)CommandNodeType.Argument, new LeafSemanticNode((int)CommandNodeType.ShortOption, startIndex, name))); }); parser.AttachAction("shortOptionWithValue", (branch, recurse) => { LeafParseNode nameNode = branch.GetDescendant(0).Leaf; var startIndex = nameNode.StartIndex; var name = nameNode.MatchedText[1].ToString(); ISemanticNode value = recurse(branch.GetDescendant(2)); return(new BranchSemanticNode((int)CommandNodeType.Argument, new LeafSemanticNode((int)CommandNodeType.ShortOption, startIndex, name), value)); }); parser.AttachAction("longOption", (branch, recurse) => { LeafParseNode nameNode = branch.Leaf; var startIndex = nameNode.StartIndex; var name = nameNode.MatchedText.Substring(2); return(new BranchSemanticNode((int)CommandNodeType.Argument, new LeafSemanticNode((int)CommandNodeType.LongOption, startIndex, name))); }); parser.AttachAction("longOptionWithValue", (branch, recurse) => { LeafParseNode nameNode = branch.GetDescendant(0).Leaf; var startIndex = nameNode.StartIndex; var name = nameNode.MatchedText.Substring(2); ISemanticNode value = recurse(branch.GetDescendant(2)); return(new BranchSemanticNode((int)CommandNodeType.Argument, new LeafSemanticNode((int)CommandNodeType.LongOption, startIndex, name), value)); }); parser.AttachAction("identifier", (branch, recurse) => { LeafParseNode nameNode = branch.Leaf; var startIndex = nameNode.StartIndex; var name = nameNode.MatchedText; return(new LeafSemanticNode((int)CommandNodeType.String, startIndex, name)); }); parser.AttachAction("doubleString", (branch, recurse) => { var text = branch.Leaf.MatchedText; text = text .Substring(1, text.Length - 2) .Replace(@"\\", @"\") .Replace(@"\""", @""""); var startIndex = branch.Leaf.StartIndex; return(new LeafSemanticNode((int)CommandNodeType.String, startIndex, text)); }); parser.AttachAction("singleString", (branch, recurse) => { var text = branch.Leaf.MatchedText; text = text .Substring(1, text.Length - 2) .Replace(@"\\", @"\") .Replace(@"\'", @"'"); var startIndex = branch.Leaf.StartIndex; return(new LeafSemanticNode((int)CommandNodeType.String, startIndex, text)); }); parser.AttachAction("string", (branch, recurse) => recurse(branch.GetDescendant(0))); parser.AttachAction("options", (branch, recurse) => { IEnumerable <ISemanticNode> options = branch.GetDescendant(0) ?.Elements ?.Select(recurse); return(new BranchSemanticNode((int)CommandNodeType.Options, branch.StartIndex, options ?? new ISemanticNode[0])); }); parser.AttachAction("literal", (branch, recurse) => { var value = branch.Leaf.MatchedText; return(new LeafSemanticNode((int)CommandNodeType.String, branch.StartIndex, value)); }); parser.AttachAction("details", (branch, recurse) => { BranchParseNode optionsNode = branch.GetDescendant(0); BranchParseNode literalNode = branch.GetDescendant(1, 1); var results = new List <ISemanticNode>(); if (optionsNode != null) { results.Add(recurse(optionsNode)); } if (literalNode != null) { results.Add(recurse(literalNode)); } return(new BranchSemanticNode((int)CommandNodeType.Details, branch.StartIndex, results)); }); parser.AttachAction("path", (branch, recurse) => { var value = branch.MatchedText; return(new LeafSemanticNode((int)CommandNodeType.String, branch.StartIndex, value)); }); parser.AttachAction("root", (branch, recurse) => { ISemanticNode path = recurse(branch.GetDescendant(0)); ISemanticNode details = recurse(branch.GetDescendant(1)); return(new BranchSemanticNode((int)CommandNodeType.Root, path, details)); }); }
// для одного node из ICollection public void prepare_node_in_collection(ISemanticNode subnode, string node_name, myTreeNode tn_parent, bool is_leaf) { myTreeNode t; if (treeView.SelectedNode == null) t = null; else if (treeView.SelectedNode.Tag == null) t = null; else t = treeView.SelectedNode as myTreeNode; if (subnode != null) { myTreeNode tn = new myTreeNode(); tn.Text = node_name + " : " + subnode.GetType().Name; tn.Tag = subnode; SematicTreeVisitor vs = new SematicTreeVisitor(tn.Nodes); tn_parent.Nodes.Add(tn); try { if (!table_subnodes.ContainsKey(subnode)) table_subnodes.Add(subnode, tn); } catch (System.Exception e) { MessageBox.Show("Exception was \n" + e.ToString()); } //treeView.Invalidate(); //(tn as myTreeNode).is_leaf = is_leaf; } }
//-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- // для обычного node - потомка ISemanticNode public void prepare_node(ISemanticNode subnode, string node_name) { myTreeNode t; if (treeView.SelectedNode == null) t = null; else if (treeView.SelectedNode.Tag == null) t = null; else t = treeView.SelectedNode as myTreeNode; if (subnode != null) { myTreeNode tn = new myTreeNode(); tn.Text = node_name + " : " + subnode.GetType().Name; tn.Tag = subnode; SematicTreeVisitor vs = new SematicTreeVisitor(tn.Nodes); if (t != null) t.Nodes.Add(tn); else nodes.Add(tn); try { if (!table_subnodes.ContainsKey(subnode)) table_subnodes.Add(subnode, tn); } catch (System.Exception e) { MessageBox.Show("Exception was \n" + e.ToString()); } } }
// ------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------- // ------------------------------------------------------------------------------------------------------------------- public void visit(ISemanticNode value) { }
public void prepare_node_in_collection_up_link(ISemanticNode subnode, string node_name, myTreeNode tn_parent) { myTreeNode t; if (treeView.SelectedNode == null) t = null; else if (treeView.SelectedNode.Tag == null) t = null; else t = treeView.SelectedNode as myTreeNode; if (subnode != null) { myTreeNode tn = new myTreeNode(); tn.Tag = subnode; tn.BackColor = System.Drawing.Color.Yellow; tn.Text = node_name + " : " + subnode.GetType().Name; tn.is_leaf = true; tn_parent.Nodes.Add(tn); try { if (!table_up_rows.ContainsKey(tn) && tn != null) table_up_rows.Add(tn, subnode); } catch (System.Exception e) { MessageBox.Show("Exception was \n" + e.ToString()); } } }
public void prepare_up_link_node(string str, string text, ISemanticNode sem_node) { myTreeNode t; if (treeView.SelectedNode == null) t = null; else if (treeView.SelectedNode.Tag == null) t = null; else t = treeView.SelectedNode as myTreeNode; myTreeNode tn = new myTreeNode(); tn.Tag = sem_node; tn.BackColor = System.Drawing.Color.Yellow; tn.Text = text + " : " + str; //tn.Tag = str; if (t != null) t.Nodes.Add(tn); else nodes.Add(tn); try { if (!table_up_rows.ContainsKey(tn) && tn != null) table_up_rows.Add(tn, sem_node); } catch (System.Exception e) { MessageBox.Show("Exception was \n" + e.ToString()); } }
public static Grammar GetGrammar() { var grammarString = $@" varKeyword = /\b(var)\b/; // -/ letKeyword = /\b(let)\b/; // -/ newKeyword = /\b(new)\b/; // -/ deleteKeyword = /\b(delete)\b/; // X ? instanceofKeyword = /\b(instanceof)\b/; // X ? withKeyword = /\b(with)\b/; // X voidKeyword = /\b(void)\b/; // X typeofKeyword = /\b(typeof)\b/; // X ? thisKeyword = /\b(this)\b/; // X ? debuggerKeyword = /\b(debugger)\b/; // X importKeyword = /\b(import)\b/; // X classKeyword = /\b(class)\b/; // X constKeyword = /\b(const)\b/; // X ? extendsKeyword = /\b(extends)\b/; // X yieldKeyword = /\b(yield)\b/; // X superKeyword = /\b(super)\b/; // X functionKeyword = /\b(function)\b/; // -/ tryKeyword = /\b(try)\b/; // X ? catchKeyword = /\b(catch)\b/; // X ? finallyKeyword = /\b(finally)\b/; // X ? throwKeyword = /\b(throw)\b/; // X ? returnKeyword = /\b(return)\b/; // X ? ifKeyword = /\b(if)\b/; // X ? elseKeyword = /\b(else)\b/; // X ? whileKeyword = /\b(while)\b/; // X ? doKeyword = /\b(do)\b/; // X ? forKeyword = /\b(for)\b/; // X ? inKeyword = /\b(in)\b/; // X ? switchKeyword = /\b(switch)\b/; // X ? caseKeyword = /\b(case)\b/; // X ? defaultKeyword = /\b(default)\b/; // X ? breakKeyword = /\b(break)\b/; // X ? continueKeyword = /\b(continue)\b/; // X ? implementsKeyword = /\b(implements)\b/; // X interfaceKeyword = /\b(interface)\b/; // X packageKeyword = /\b(package)\b/; // X privateKeyword = /\b(private)\b/; // X protectedKeyword = /\b(protected)\b/; // X publicKeyword = /\b(public)\b/; // X staticKeyword = /\b(static)\b/; // X awaitKeyword = /\b(await)\b/; // X enumKeyword = /\b(enum)\b/; // X leftBracket = ""{{""; rightBracket = ""}}""; leftParen = ""(""; rightParen = "")""; leftSquare = ""[""; rightSquare = ""]""; comma = "",""; dot = "".""; equals = ""=""; colon = "":""; semicolon = "";""; and = ""&&""; or = ""||""; not = ""!""; strictEquality = ""===""; strictInequality = ""!==""; equality = ""==""; inequality = ""!=""; lessThanOrEqual = ""<=""; greaterThanOrEqual = "">=""; lessThan = ""<""; greaterThan = "">""; ws = /\s+/; ident = /\b[$A-Za-z_][$A-Za-z_0-9]*\b/; number = /\b\d+(?:\.\d+)?\b/; doubleString = /""(?:\\\\""|\\\\[^""]|[^""\\\\])*""/; singleString = /'(?:\\\\'|\\\\[^']|[^'\\\\])*'/; regex = /\/(?:\\\\\/|\\\\|[^\/])+\/[A-Za-z]*/; lineComment = /\/\/[^{"\r\n"}]*/; blockComment = /\/\*([^*]|\*[^\/])*\*\//; minusEquals = ""-=""; plusEquals = ""+=""; timesEquals = ""*=""; divideEquals = ""/=""; modulusEquals = ""%=""; bitAndEquals = ""&=""; bitOrEquals = ""|=""; bitXorEquals = ""^=""; minus = ""-""; plus = ""+""; times = ""*""; divide = ""/""; modulus = ""%""; bitAnd = ""&""; bitOr = ""|""; bitNot = ""~""; bitXor = ""^""; question = ""?""; basicKeywords = varKeyword | letKeyword | newKeyword | deleteKeyword | instanceofKeyword | withKeyword | voidKeyword | typeofKeyword | thisKeyword | debuggerKeyword | importKeyword | classKeyword | constKeyword | extendsKeyword | yieldKeyword | superKeyword; functionLevelKeywords = functionKeyword | tryKeyword | catchKeyword | finallyKeyword | throwKeyword | returnKeyword; controlKeywords = ifKeyword | elseKeyword | whileKeyword | doKeyword | forKeyword | inKeyword | switchKeyword | caseKeyword | defaultKeyword | breakKeyword | continueKeyword; futureKeywords = implementsKeyword | interfaceKeyword | packageKeyword | privateKeyword | protectedKeyword | publicKeyword | staticKeyword | awaitKeyword | enumKeyword; validIdent = im !(basicKeywords | functionLevelKeywords | controlKeywords | futureKeywords) ident; string = doubleString | singleString; paren = leftParen expr3 rightParen; unaryOper = minus | plus; unaryMath = unaryOper *unaryOper expr2; typeof = typeofKeyword expr2; block = leftBracket *statement rightBracket; paramList = leftParen ?(validIdent *(comma validIdent)) rightParen; namedFunction = functionKeyword validIdent paramList block; anonFunction = functionKeyword paramList block; propertyDef = (validIdent | string) colon expr3; object = leftBracket ?(propertyDef *(comma propertyDef)) rightBracket; dotRef = dot validIdent; key = leftSquare expr3 rightSquare; argList = leftParen ?(expr3 *(comma expr3)) rightParen; expressionFragment = dotRef | key | argList; propertyFragments = (expressionFragment propertyFragments) | dotRef | key; functionCallFragments = (expressionFragment functionCallFragments) | argList; constructor = newKeyword functionCall; // == END expr0 DEFINITIONS == functionCall = expr0 functionCallFragments; propertyReference = expr0 propertyFragments; // == END expr1 definitions == mathOper = minus | plus | times | divide; math = expr1 mathOper expr2; logicOper = and | or; logicNegation = not expr2; logic = expr1 logicOper expr2; bitOper = bitAnd | bitOr | bitXor; bitNegation = bitNot expr2; bitwise = expr1 bitOper expr2; instanceof = expr1 instanceofKeyword expr3; in = expr1 inKeyword expr3; // == END expr2 DEFINITIONS == assignOper = equals | minusEquals | plusEquals | timesEquals | divideEquals | modulusEquals | bitAndEquals | bitOrEquals | bitXorEquals; localAssignment = validIdent assignOper expr3; propertyAssignment = propertyReference assignOper expr3; assignment = localAssignment | propertyAssignment; ternary = expr2 question expr3 colon expr3; // == END expr3 DEFINITIONS == variable = localAssignment | validIdent; variableDecl = (varKeyword | letKeyword | constKeyword) variable *(comma variable); break = breakKeyword; continue = continueKeyword; return = returnKeyword ?expr3; throw = throwKeyword ?expr3; delete = deleteKeyword propertyReference; catch = catchKeyword block; finally = finallyKeyword block; try = tryKeyword block catch *catch ?finally; default = defaultKeyword colon *statement; case = caseKeyword (string | number | (validIdent *dotRef)) colon *statement; switch = switchKeyword leftBracket *case ?default *case rightBracket; else = elseKeyword statement; if = ifKeyword statement ?else; while = whileKeyword paren statement; doWhile = doKeyword statement whileKeyword paren ?semicolon; for = forKeyword leftParen ((variableDecl | expr3) semicolon expr3 semicolon expr3) rightParen statement; expr0 = thisKeyword | anonFunction | validIdent | number | string | paren | unaryMath | logicNegation | bitNegation | constructor | object; expr1 = functionCall | propertyReference | expr0; expr2 = math | logic | instanceof | in | bitwise | expr1; expr3 = ternary | assignment | expr2; blockStatement = if | while | doWhile | forIn | for | switch | namedFunction | block; statement = blockStatement | ((variableDecl | break | continue | return | throw | delete | expr3) ?semicolon) | semicolon; root = statement *statement; "; var parserGen = new ParserGenerator(); Grammar grammar = parserGen.BuildGrammar(grammarString, "ws", "lineComment", "blockComment"); grammar.AttachAction("root", (branch, recurse) => { ISemanticNode first = recurse(branch.GetDescendant(0)); ISemanticNode[] rest = branch.GetDescendant(1) .Elements .Select(recurse) .ToArray(); return(new BranchSemanticNode((int)JsNodeType.Root, first, rest)); }); grammar.AttachAction("statement", (branch, recurse) => { ISemanticNode stmt = recurse(branch.GetDescendant(0)); return(new BranchSemanticNode((int)JsNodeType.Statement, stmt)); }); grammar.AttachAction("variableDecl", (branch, recurse) => { ISemanticNode first = recurse(branch.GetDescendant(1, 0)); ISemanticNode[] rest = branch.GetDescendant(2) .Elements .Select(n => recurse(n.GetDescendant(1, 0))) .ToArray(); return(new BranchSemanticNode((int)JsNodeType.Variable, first, rest)); }); grammar.AttachAction("localAssignment", (branch, recurse) => { ISemanticNode lvalue = recurse(branch.GetDescendant(0)); ISemanticNode expr2 = recurse(branch.GetDescendant(2)); return(new BranchSemanticNode((int)JsNodeType.Assignment, lvalue, expr2)); }); grammar.AttachAction("propertyAssignment", RuleActions.PropertyAssignment); grammar.AttachAction("propertyReference", RuleActions.CompositeExpression); grammar.AttachAction("argList", (branch, recurse) => { BranchParseNode args = branch.GetDescendant(1); if (args.Elements.Count == 0) { return(new BranchSemanticNode((int)JsNodeType.ArgumentList, branch.StartIndex, new ISemanticNode[0])); } ISemanticNode first = recurse(args.GetDescendant(0)); ISemanticNode[] rest = args .GetDescendant(1) .Elements .Select(n => recurse(n.GetDescendant(1))) .ToArray(); return(new BranchSemanticNode((int)JsNodeType.ArgumentList, branch.StartIndex, new[] { first }.Concat(rest))); }); grammar.AttachAction("dotRef", (branch, recurse) => { ISemanticNode ident = recurse(branch.GetDescendant(1)); return(new BranchSemanticNode((int)JsNodeType.DotReference, ident)); }); grammar.AttachAction("key", (branch, recurse) => { ISemanticNode key = recurse(branch.GetDescendant(1)); return(new BranchSemanticNode((int)JsNodeType.KeyReference, key)); }); grammar.AttachAction("functionCall", RuleActions.FunctionCall); grammar.AttachAction("constructor", RuleActions.Constructor); grammar.AttachAction("expressionFragment", RuleActions.Unwrap); grammar.AttachAction("object", (branch, recurse) => { BranchParseNode firstNode = branch.GetDescendant(1, 0); if (firstNode == null) { return(new BranchSemanticNode((int)JsNodeType.Object, branch.StartIndex, new ISemanticNode[0])); } ISemanticNode first = recurse(firstNode); ISemanticNode[] rest = branch.GetDescendant(1, 1) .Elements .Select(n => recurse(n.GetDescendant(1))) .ToArray(); return(new BranchSemanticNode((int)JsNodeType.Object, branch.StartIndex, first, rest)); }); grammar.AttachAction("propertyDef", (branch, recurse) => { ISemanticNode ident = recurse(branch.GetDescendant(0)); ISemanticNode value = recurse(branch.GetDescendant(2)); return(new BranchSemanticNode((int)JsNodeType.PropertyDefinition, ident, value)); }); grammar.AttachAction("anonFunction", (branch, recurse) => { ISemanticNode paramList = recurse(branch.GetDescendant(1)); ISemanticNode body = recurse(branch.GetDescendant(2)); return(new BranchSemanticNode((int)JsNodeType.AnonymousFunction, paramList, body)); }); grammar.AttachAction("namedFunction", (branch, recurse) => { ISemanticNode name = recurse(branch.GetDescendant(1)); ISemanticNode paramList = recurse(branch.GetDescendant(2)); ISemanticNode body = recurse(branch.GetDescendant(3)); return(new BranchSemanticNode((int)JsNodeType.NamedFunction, paramList, body)); }); grammar.AttachAction("paramList", (branch, recurse) => { ISemanticNode first = recurse(branch.GetDescendant(1, 0)); ISemanticNode[] rest = branch.GetDescendant(1, 1) .Elements .Select(n => recurse(n.GetDescendant(1))) .ToArray(); return(new BranchSemanticNode((int)JsNodeType.ParameterList, first, rest)); }); grammar.AttachAction("block", (branch, recurse) => { ISemanticNode[] stmts = branch.GetDescendant(1) .Elements .Select(recurse) .ToArray(); return(new BranchSemanticNode((int)JsNodeType.Block, branch.StartIndex, stmts)); }); grammar.AttachAction("bitwise", (branch, recurse) => { ISemanticNode left = recurse(branch.GetDescendant(0)); ISemanticNode right = recurse(branch.GetDescendant(2)); return(new BranchSemanticNode((int)JsNodeType.Bitwise, left, right)); }); grammar.AttachAction("bitNegation", (branch, recurse) => { ISemanticNode operand = recurse(branch.GetDescendant(1)); return(new BranchSemanticNode((int)JsNodeType.BitwiseNegation, operand)); }); grammar.AttachAction("logic", (branch, recurse) => { ISemanticNode left = recurse(branch.GetDescendant(0)); ISemanticNode right = recurse(branch.GetDescendant(2)); return(new BranchSemanticNode((int)JsNodeType.Logic, left, right)); }); grammar.AttachAction("logicNegation", (branch, recurse) => { ISemanticNode operand = recurse(branch.GetDescendant(1)); return(new BranchSemanticNode((int)JsNodeType.LogicNegation, operand)); }); grammar.AttachAction("math", (branch, recurse) => { ISemanticNode left = recurse(branch.GetDescendant(0)); ISemanticNode right = recurse(branch.GetDescendant(2)); return(new BranchSemanticNode((int)JsNodeType.Math, left, right)); }); grammar.AttachAction("unaryMath", (branch, recurse) => { ISemanticNode operand = recurse(branch.GetDescendant(1)); return(new BranchSemanticNode((int)JsNodeType.UnaryMath, operand)); }); grammar.AttachAction("paren", (branch, recurse) => { ISemanticNode operand = recurse(branch.GetDescendant(1)); return(new BranchSemanticNode((int)JsNodeType.Parenthetical, operand)); }); grammar.AttachAction("validIdent", (branch, recurse) => { branch = branch.GetDescendant(1); var ident = branch.Leaf.MatchedText; var startIndex = branch.Leaf.StartIndex; return(new LeafSemanticNode((int)JsNodeType.Identifier, startIndex, ident)); }); grammar.AttachAction("doubleString", (branch, recurse) => { var text = branch.Leaf.MatchedText; text = text .Substring(1, text.Length - 2) .Replace(@"\\", @"\") .Replace(@"\""", @""""); var startIndex = branch.Leaf.StartIndex; return(new LeafSemanticNode((int)JsNodeType.String, startIndex, text)); }); grammar.AttachAction("singleString", (branch, recurse) => { var text = branch.Leaf.MatchedText; text = text .Substring(1, text.Length - 2) .Replace(@"\\", @"\") .Replace(@"\'", @"'"); var startIndex = branch.Leaf.StartIndex; return(new LeafSemanticNode((int)JsNodeType.String, startIndex, text)); }); grammar.AttachAction("string", RuleActions.Unwrap); grammar.AttachAction("regex", (branch, recurse) => { var pattern = branch.Leaf.MatchedText; pattern = pattern .Substring(1, pattern.Length - 2) .Replace(@"\\", @"\") .Replace(@"\/", @"/"); var startIndex = branch.Leaf.StartIndex; return(new LeafSemanticNode((int)JsNodeType.RegularExpression, startIndex, pattern)); }); grammar.AttachAction("number", (branch, recurse) => { var number = branch.Leaf.MatchedText; var startIndex = branch.Leaf.StartIndex; return(new LeafSemanticNode((int)JsNodeType.Number, startIndex, number)); }); grammar.AttachAction("expr0", RuleActions.Unwrap); grammar.AttachAction("expr1", RuleActions.Unwrap); grammar.AttachAction("expr2", RuleActions.Unwrap); grammar.AttachAction("expr3", RuleActions.Unwrap); grammar.AttachAction("assignment", RuleActions.Unwrap); return(grammar); }
private static ISemanticNode CompositeExpression(ISemanticNode first, BranchParseNode fragments, Func <BranchParseNode, ISemanticNode> recurse) { List <ISemanticNode> rest = ExpressionFragments(fragments, recurse); return(CompositeExpression(first, rest)); }
public virtual void visit(ISemanticNode value) { }
public void visit(ISemanticNode value) { throw new System.NotSupportedException(value.GetType().ToString()); }
private Rule Interpret(Grammar grammar, ISemanticNode node) { Rule rule = null; if (node is BranchSemanticNode branch) { switch ((EbnfNodeType)branch.NodeType) { case EbnfNodeType.Group: rule = Interpret(grammar, branch.Children[0]); break; case EbnfNodeType.Repeat: rule = new RepeatRule(grammar, Interpret(grammar, branch.Children[0])); break; case EbnfNodeType.Optional: rule = new OptionalRule(grammar, Interpret(grammar, branch.Children[0])); break; case EbnfNodeType.Not: rule = new NotRule(grammar, Interpret(grammar, branch.Children[0])); break; case EbnfNodeType.And: rule = new AndRule(grammar, branch.Children.Select(child => Interpret(grammar, child))); break; case EbnfNodeType.Or: rule = new OrRule(grammar, branch.Children.Select(child => Interpret(grammar, child))); break; case EbnfNodeType.None: rule = Interpret(grammar, branch.Children.Single()); break; case EbnfNodeType.Root: case EbnfNodeType.Rule: case EbnfNodeType.Token: default: throw new Exception(); } } else if (node is LeafSemanticNode leaf) { switch ((EbnfNodeType)leaf.NodeType) { case EbnfNodeType.Identifier: rule = grammar.ReferenceRule(leaf.Value); break; case EbnfNodeType.String: case EbnfNodeType.Regex: break; default: throw new Exception(); } } if (rule == null) { throw new Exception(); } else { return(rule); } }
private static ISemanticNode CompositeExpression(ISemanticNode first, params ISemanticNode[] rest) => CompositeExpression(first, (IEnumerable <ISemanticNode>)rest);
public BranchSemanticNode(int nodeType, ISemanticNode first, params ISemanticNode[] rest) : this(nodeType, first, (IEnumerable <ISemanticNode>)rest) { }
internal static ISemanticNode Constructor(BranchParseNode branch, Func <BranchParseNode, ISemanticNode> recurse) { ISemanticNode funCall = recurse(branch.GetDescendant(1)); return(new BranchSemanticNode((int)JsNodeType.Constructor, funCall)); }
protected BaseWebApiPathSymbol(IEnumerable<Annotation> annotations, ISemanticNode parent, TypeReference result, Identifier name, Maybe<AtomSymbol> argument, Func<BaseWebApiQuerySymbol, IEnumerable<AtomSymbol>> filters, Func<BaseWebApiPathSymbol, IEnumerable<IWebApiPathMember>> members) : base(annotations, parent, result, name, argument, filters) { Members = Guard.NotNull(members, "members")(this).ToArray(); }
// для строкового поля public void prepare_string_node_with_tag(string str, string text, ISemanticNode sem) { myTreeNode t; if (treeView.SelectedNode == null) t = null; else if (treeView.SelectedNode.Tag == null) t = null; else t = treeView.SelectedNode as myTreeNode; myTreeNode tn = new myTreeNode(); tn.Text = text + " : " + str; tn.Tag = sem; if (t != null) t.Nodes.Add(tn); else nodes.Add(tn); }
public BranchSemanticNode(int nodeType, ISemanticNode first, IEnumerable <ISemanticNode> rest) : this(nodeType, first.StartIndex, new[] { first }.Concat(rest)) { }
public void prepare_string_node_with_tag2(string str, string text, ISemanticNode sem) { myTreeNode tn = new myTreeNode(); myTreeNode t = treeView.Nodes[0] as myTreeNode; tn.Text = text + " : " + str; tn.Tag = sem; if (t != null) t.Nodes.Add(tn); else nodes.Add(tn); treeView.Nodes[0].Text = "compiled_types : " + "Count " + compiled_types.Count; }
// для обычного node - потомка ISemanticNode public void prepare_node(ISemanticNode subnode, string node_name) { }