private void AddChild <TParent, TChild>(TParent parentContext, Func <ParserRuleContext, TChild> createChild) where TParent : ParserRuleContext where TChild : ParserRuleContext { ParserRuleContext AggregateFunc(ParserRuleContext parent, Type type) { var child = (ParserRuleContext)Activator.CreateInstance(type, new object[] { parent, 0 }); parent.AddChild(child); return(child); } var contextTypes = new Type[] { typeof(VisualBasicParser.OrExprContext), typeof(VisualBasicParser.AndExprContext), typeof(VisualBasicParser.NotExprContext), typeof(VisualBasicParser.CompareExprContext), typeof(VisualBasicParser.AddExprContext), typeof(VisualBasicParser.ModExprContext), typeof(VisualBasicParser.TermContext), typeof(VisualBasicParser.UnaryExprContext), typeof(VisualBasicParser.PowerExprContext), typeof(VisualBasicParser.PrimaryExprContext), }; var contextTypesWithoutParentType = contextTypes .SkipWhile(type => type != typeof(TParent)) .Skip(1) .ToList(); if (contextTypesWithoutParentType.Exists(type => type == typeof(TChild))) { contextTypesWithoutParentType .TakeWhile(type => type != typeof(TChild)) .Aggregate((ParserRuleContext)parentContext, AggregateFunc); return; } var primaryExprContext = contextTypesWithoutParentType .Aggregate((ParserRuleContext)parentContext, AggregateFunc); var exprContext = new VisualBasicParser.ExpressionContext(primaryExprContext, 0); primaryExprContext.AddChild(new CommonToken(VisualBasicParser.OPEN_PAREN, "(")); primaryExprContext.AddChild(exprContext); primaryExprContext.AddChild(new CommonToken(VisualBasicParser.CLOSE_PAREN, ")")); var fromParentContext = contextTypes .TakeWhile(type => type != typeof(TChild)) .Aggregate((ParserRuleContext)exprContext, AggregateFunc); var fromContext = createChild(fromParentContext); fromParentContext.AddChild(fromContext); }
public override ParserRuleContext VisitXorExpr([NotNull] StructuredTextParser.XorExprContext context) { var result = new VisualBasicParser.ExpressionContext(_contextStack.Peek(), 0); _contextStack.Push(result); result.AddChild(Visit(context.lhs)); for (int i = 1; i < context.ChildCount; i += 2) { result.AddChild(new CommonToken(VisualBasicParser.XOR, "XOR")); result.AddChild(Visit(context.GetChild(i + 1))); } _contextStack.Pop(); return(result); }
/// <summary> /// Visit a parse tree produced by <see cref="VisualBasicParser.expression"/>. /// <para> /// The default implementation returns the result of calling <see cref="AbstractParseTreeVisitor{Result}.VisitChildren(IRuleNode)"/> /// on <paramref name="context"/>. /// </para> /// </summary> /// <param name="context">The parse tree.</param> /// <return>The visitor result.</return> public virtual Result VisitExpression([NotNull] VisualBasicParser.ExpressionContext context) { return(VisitChildren(context)); }