public IPHeader(byte[] byBuffer, int nReceived) { NetBinaryReader nbr = new NetBinaryReader(byBuffer, 0, nReceived); Version = nbr.ReadNible(); HeaderLength = nbr.ReadNible(); Precedence = (Precedence)nbr.ReadCustomAmount(3); LowDelay = nbr.ReadBit(); HighThroughput = nbr.ReadBit(); HighRelibility = nbr.ReadBit(); nbr.SkipPadBits(); TotalLength = nbr.ReadUInt16(); Identification = nbr.ReadUInt16(); nbr.ReadBit(); MayFragment = !nbr.ReadBit(); LastFragment = !nbr.ReadBit(); FragmentOffset = (nbr.ReadPadBits() << 3) + nbr.ReadByte(); TTL = nbr.ReadByte(); Protocol = (ProtocolType)nbr.ReadByte(); HeaderChecksum = IPAddress.NetworkToHostOrder(nbr.ReadInt16()); Source = new IPAddress(nbr.ReadBytes(4)); Destination = new IPAddress(nbr.ReadBytes(4)); }
public Operator(char symbol, Precedence precedence, Assosiativity assosiativity, int argumentsTaken) { this.Symbol = symbol; this.Precedence = precedence; this.Assosiativity = assosiativity; this.ArgumentsTaken = argumentsTaken; }
public void PrecedenceSupportsHashCode() { Precedence first = new Precedence { Association = Association.LeftToRight, Level = 1 }; Precedence second = new Precedence { Association = Association.LeftToRight, Level = 1 }; Assert.AreEqual(first.GetHashCode(), second.GetHashCode()); }
public ConfigureUsingAppConfigConnectionStringAttribute(Precedence precedence, Type typeConverter, string appSettingName) : base(precedence, typeConverter) { if (string.IsNullOrWhiteSpace(appSettingName)) { throw new AppSettingKeyCannotBeNullOrWhitespaceException(); } this.ConnectionStringName = appSettingName.Trim(); }
protected ConfigureAttribute(Precedence precedence, Type typeConverter) { this.Precedence = precedence; if (typeConverter.IsSubclassOf(typeof(ITypeConverter))) { throw new ArgumentException("typeConverter must be of type ITypeConverter"); } this.ConvertFunction = (ITypeConverter)Activator.CreateInstance(typeConverter); }
public void PrecedenceSupportsEquals() { Precedence first = new Precedence { Association = Association.LeftToRight, Level = 1 }; Precedence second = new Precedence { Association = Association.LeftToRight, Level = 1 }; Precedence third = new Precedence { Association = Association.LeftToRight, Level = 2 }; Precedence fourth = new Precedence { Association = Association.RightToLeft, Level = 2 }; object fifth = null; object sixth = new Precedence {Association = Association.RightToLeft, Level = 2}; Assert.IsTrue(first.Equals(second)); Assert.IsFalse(second.Equals(third)); Assert.IsFalse(third.Equals(fourth)); Assert.IsFalse(fourth.Equals(fifth)); Assert.IsTrue(fourth.Equals(sixth)); Assert.IsTrue(first == second); Assert.IsFalse(first != second); }
public IExpression ParseExpression(Precedence precedence) { var token = Consume(); var prefix = _prefixParselets.ContainsKey(token.Type) ? _prefixParselets[token.Type] : null; if (prefix == null) { throw new ParseException(string.Format("Could not parse \"{0}\".", token.Value)); } var left = prefix.Parse(this, token); while (precedence < GetPrecedence()) { token = Consume(); var infix = _infixParselets[token.Type]; left = infix.Parse(this, left, token); } return left; }
/// <summary> /// Retrieve the precedence of the current /// token. /// </summary> public int GetCurrentPrecedence() { return(Precedence.Get(Stream.Get().Type)); }
void PrintExpr(LNode n, Precedence context) { PrintExpr(n, context, _flags & Ambiguity.OneLiner); }
/// <summary> /// Instantiates a new BinaryOperatorParselet /// </summary> public BinaryOperatorParselet(Precedence precedence, bool rightAssociative) { PrecedenceLevel = precedence; RightAssociative = rightAssociative; }
protected Precedence FindPrecedence(MMap<object,Precedence> table, object symbol, Precedence @default, bool cacheWordOp) { // You can see the official rules in the LesPrecedence documentation. // Rule 1 (for >= <= != ==) is covered by the pre-populated contents // of the table, and the pre-populated table helps interpret rules // 3-4 also. Precedence prec; if (table.TryGetValue(symbol, out prec)) return prec; string sym = (symbol ?? "").ToString(); if (sym == "") return @default; // empty operator! // Note: all one-character operators should have been found in the table char first = sym[0], last = sym[sym.Length - 1]; if (last == '=' && first != '=' && table == this[OperatorShape.Infix].A) return table[symbol] = table[S.Assign]; var twoCharOp = GSymbol.Get(first.ToString() + last); if (table.TryGetValue(twoCharOp, out prec)) return table[symbol] = prec; var oneCharOp = GSymbol.Get(last.ToString()); if (table.TryGetValue(oneCharOp, out prec)) return table[symbol] = prec; // Default precedence is used for word operators if (cacheWordOp) table[symbol] = @default; return @default; }
public bool AutoPrintOfOperator(Precedence precedence) { bool needSpecialOfNotation = false; var ici = ICI.Default | ICI.AllowAttrs; if ((_flags & Ambiguity.InDefinitionName) != 0) ici |= ICI.NameDefinition; if (!IsComplexIdentifier(_n, ici)) { if (IsComplexIdentifier(_n, ici | ICI.AllowAnyExprInOf)) needSpecialOfNotation = true; else return false; } bool parens; if (!CanAppearHere(precedence, out parens) || parens) return false; Debug.Assert(_n.ArgCount >= 1); PrintExpr(_n.Args[0], precedence.LeftContext(_context), _flags & (Ambiguity.InDefinitionName | Ambiguity.TypeContext)); _out.Write(needSpecialOfNotation ? "!(" : "<", true); for (int i = 1, argC = _n.ArgCount; i < argC; i++) { if (i > 1) WriteThenSpace(',', SpaceOpt.AfterCommaInOf); PrintType(_n.Args[i], StartExpr, Ambiguity.InOf | Ambiguity.AllowPointer | (_flags & Ambiguity.InDefinitionName)); } _out.Write(needSpecialOfNotation ? ')' : '>', true); return true; }
public bool AutoPrintPropDeclExpr(Precedence precedence) { return AutoPrintProperty() != SPResult.Fail; }
/// <summary> /// Returns a value indicating whether this instance is equal to the specified <see cref="Precedence" /> value. /// </summary> public bool Equals(Precedence other) { return(Equals(this, other)); }
public bool AutoPrintPrefixOrInfixOperator(Precedence infixPrec) { if (_n.ArgCount == 2) return AutoPrintInfixBinaryOperator(infixPrec); else return AutoPrintPrefixUnaryOperator(PrefixOperators[_name]); }
/// <summary> /// Indicates whether an expression with this precedence requires parentheses to protect its lower precedence level. /// </summary> /// <param name="against">The precedence to test against.</param> /// <param name="expected">The expected association.</param> /// <returns>True if parens are needed, otherwise false.</returns> public bool RequiresGrouping(Precedence against, Association expected) { return(((Level == against.Level) && (Association != expected)) || (Level < against.Level)); }
/// <summary> /// Determines whether the specified instances of <see cref="Precedence"/> are considered equal. /// </summary> public static bool Equals(Precedence left, Precedence right) { return(int.Equals(left.Level, right.Level) && left.Association.Equals(right.Association)); }
LNode Expr(Precedence context) { TT la0; LNode e = default(LNode); Token lit_excl = default(Token); Token t = default(Token); // Line 156: (KeywordExpression | PrefixExpr greedy( &{CanParse(context, $LI, out prec)} InfixOperatorName Expr | &{context.CanParse(P.Add)} TT.NegativeLiteral | &{context.CanParse(_prec.Find(OperatorShape.Suffix, LT($LI).Value))} TT.PreOrSufOp | &{context.CanParse(P.Primary)} FinishPrimaryExpr | &{context.CanParse(P.Of)} TT.Not (TT.LParen ExprList TT.RParen / Expr) )*) la0 = (TT)LA0; if (la0 == TT.Keyword) { e = KeywordExpression(); } else { // line 157 Precedence prec; e = PrefixExpr(context); // Line 161: greedy( &{CanParse(context, $LI, out prec)} InfixOperatorName Expr | &{context.CanParse(P.Add)} TT.NegativeLiteral | &{context.CanParse(_prec.Find(OperatorShape.Suffix, LT($LI).Value))} TT.PreOrSufOp | &{context.CanParse(P.Primary)} FinishPrimaryExpr | &{context.CanParse(P.Of)} TT.Not (TT.LParen ExprList TT.RParen / Expr) )* for (;;) { switch ((TT)LA0) { case TT.Assignment: case TT.Dot: case TT.NormalOp: { if (CanParse(context, 0, out prec)) { goto match1; } else { goto stop; } } case TT.Colon: { if ((TT)LA(0 + 1) != TT.Newline) { if (CanParse(context, 0, out prec)) { goto match1; } else { goto stop; } } else { goto stop; } } case TT.Id: { if (CanParse(context, 0, out prec)) { if (!Continuators.ContainsKey(LT(0).Value)) { goto match1; } else { goto stop; } } else { goto stop; } } case TT.NegativeLiteral: { if (context.CanParse(P.Add)) { var rhs = MatchAny(); // line 167 e = F.Call(S.Sub, e, ToPositiveLiteral(rhs), e.Range.StartIndex, rhs.EndIndex, rhs.StartIndex, rhs.StartIndex + 1, NodeStyle.Operator); } else { goto stop; } } break; case TT.PreOrSufOp: { if (context.CanParse(_prec.Find(OperatorShape.Suffix, LT(0).Value))) { t = MatchAny(); // line 171 e = F.Call(_prec.ToSuffixOpName((Symbol)t.Value), e, e.Range.StartIndex, t.EndIndex, t.StartIndex, t.EndIndex, NodeStyle.Operator); } else { goto stop; } } break; case TT.LBrack: case TT.LParen: { if (context.CanParse(P.Primary)) { e = FinishPrimaryExpr(e); } else { goto stop; } } break; case TT.Not: { if (context.CanParse(P.Of)) { lit_excl = MatchAny(); // line 178 var args = new VList <LNode> { e }; int endIndex; // Line 179: (TT.LParen ExprList TT.RParen / Expr) la0 = (TT)LA0; if (la0 == TT.LParen) { Skip(); args = ExprList(args); var c = Match((int)TT.RParen); // line 179 endIndex = c.EndIndex; } else { var T = Expr(P.Of); // line 180 args.Add(T); endIndex = T.Range.EndIndex; } // line 182 e = F.Call(S.Of, args, e.Range.StartIndex, endIndex, lit_excl.StartIndex, lit_excl.EndIndex, NodeStyle.Operator); } else { goto stop; } } break; default: goto stop; } continue; match1: { Token op; var opName = InfixOperatorName(out op); var rhs = Expr(prec); // line 164 e = F.Call(opName, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex, op.StartIndex, op.EndIndex, NodeStyle.Operator); } } stop :; } // line 184 return(e); }
public static Queue <string> ConvertToReverse(List <string> tokens) { Stack <string> stack = new Stack <string>(); Queue <string> queque = new Queue <string>(); for (int i = 0; i < tokens.Count; i++) { var currentToken = tokens[i]; double number; if (double.TryParse(currentToken, out number)) { queque.Enqueue(currentToken); } else if (functions.Contains(currentToken)) { stack.Push(currentToken); } else if (currentToken == ",") { if (!stack.Contains("(") || stack.Count == 0) { throw new ArgumentException("Invalid brackets or function separator!"); } while (stack.Peek() != "(") { queque.Enqueue(stack.Pop()); } } else if (operators.Contains(currentToken[0])) { while (stack.Count != 0 && operators.Contains(stack.Peek()[0]) && Precedence.Prec(currentToken) <= Precedence.Prec(stack.Peek())) { queque.Enqueue(stack.Pop()); } stack.Push(currentToken); } else if (currentToken == "(") { stack.Push("("); } else if (currentToken == ")") { if (!stack.Contains("(")) { throw new ArgumentException("Invalid brackets"); } while (stack.Peek() != "(") { queque.Enqueue(stack.Pop()); } stack.Pop(); if (stack.Count != 0 && functions.Contains(stack.Peek())) { queque.Enqueue(stack.Pop()); } } } while (stack.Count != 0) { if (brackets.Contains(stack.Peek()[0])) { throw new ArgumentException("Invalid brackets position! "); } queque.Enqueue(stack.Pop()); } return(queque); }
public PrefixParse(Precedence prec) { _precedence = prec; }
// Checks if an operator with precedence 'prec' can appear in this context. bool CanAppearHere(Precedence prec, out bool extraParens, bool prefix = false) { extraParens = false; if (prec.CanAppearIn(_context, prefix) && (prefix || _o.MixImmiscibleOperators || prec.CanMixWith(_context))) return true; if (_n.IsParenthesizedExpr()) return true; if (_o.AllowChangeParentheses || !EP.Primary.CanAppearIn(_context)) { Trace.WriteLineIf(!_o.AllowChangeParentheses, "Forced to write node in parens"); return extraParens = true; } return false; }
public BigNum Evaluate(Dictionary <String, BigNum> symbols) { lock ( _lock ) { //////////////////////////// // Reinit _valueStack.Clear(); _operatorStack.Clear(); _operatorStack.Push(Operator.Eof); _token = Operator.Eof; _ptoken = Operator.Eof; _value = _factory.Zero; _isFirstToken = true; _toki = 0; if (symbols == null) { symbols = new Dictionary <String, BigNum>(); } _symbols = symbols; Advance(); while (true) { OnStackChanged(); if (_token == Operator.Val) { // if the current token is a value // shift it to value stack Shift(); } else { // get precedence for the last operator and the current operator Operator lastOp = _operatorStack.Peek(); Precedence p = _precedence[(int)lastOp, (int)_token]; switch (p) { case Precedence.Reduce: Reduce(); break; case Precedence.Shift: Shift(); break; case Precedence.Accept: EnsureVal(1); return(_value = _valueStack.Pop()); default: throw new ExpressionException(p.ToString() + " at position " + _toki); } } } //while } //lock }
public bool AutoPrintPrefixUnaryOperator(Precedence precedence) { if (!IsPrefixOperator(_n, (_flags & Ambiguity.CastRhs) != 0)) return false; var arg = _n.Args[0]; bool needParens; if (CanAppearHere(precedence, out needParens, true)) { // Check for the ambiguous case of (Foo)-x, (Foo)+x, (Foo) .x; (Foo)*x and (Foo)&x are OK if ((_flags & Ambiguity.CastRhs) != 0 && !needParens && ( _name == S.Dot || _name == S.PreInc || _name == S.PreDec || _name == S._UnaryPlus || _name == S._Negate) && !_n.IsParenthesizedExpr()) { if (_o.AllowChangeParentheses) needParens = true; // Resolve ambiguity with extra parens else return false; // Fallback to prefix notation } // Check for the ambiguous case of "~Foo(...);" if (_name == S.NotBits && _context.Lo == StartStmt.Lo && arg.IsCall) return false; if (WriteOpenParen(ParenFor.Grouping, needParens)) _context = StartExpr; WriteOperatorName(_name); PrefixSpace(precedence); PrintExpr(arg, precedence.RightContext(_context), 0); //if (backtick) { // Debug.Assert(precedence == EP.Backtick); // if ((SpacingOptions & SpaceOpt.AroundInfix) != 0 && precedence.Lo < SpaceAroundInfixStopPrecedence) // _out.Space(); // PrintOperatorName(_name, Ambiguity.UseBacktick); //} WriteCloseParen(ParenFor.Grouping, needParens); return true; } return false; }
public ParseRule(PrefixFn prefix, InfixFn infix, Precedence precedence) { this.prefix = prefix; this.infix = infix; this.precedence = precedence; }
public bool AutoPrintCastOperator(Precedence precedence) { if (_n.ArgCount != 2) return false; // Cast operators can have attributes on the second argument using // alternate notation, e.g. x(as [A] Foo) is legal but "x as [A] Foo" // is not, because attributes must only appear at the beginning of an // expression and only the second case treats the text after 'as' as // the beginning of a new expression. Also, because a standard cast // like (Foo)(x) is ambiguous (is x being cast to type Foo, or is a // delegate named Foo being called with x as an argument?), an // attribute list can be used to resolve the ambiguity. So (Foo)(x) // is considered a cast, while ([ ] Foo)(x) is a call to Foo in which // Foo happens to be placed in parenthesis. Thus, if target type of a // cast has attributes, it must be expressed in alternate form, e.g. // (x)(->[A] Foo), or in prefix form. // // There is an extra rule for (X)Y casts: X must be a complex (or // simple) identifier, since anything else won't be parsed as a cast. Symbol name = _name; bool alternate = (_n.Style & NodeStyle.Alternate) != 0 && !_o.PreferPlainCSharp; LNode subject = _n.Args[0], target = _n.Args[1]; if (HasPAttrs(subject)) return false; if (HasPAttrs(target) || (name == S.Cast && !IsComplexIdentifier(target, ICI.Default | ICI.AllowAnyExprInOf))) alternate = true; bool needParens; if (alternate) precedence = EP.Primary; if (!CanAppearHere(precedence, out needParens) && name != S.Is) { // There are two different precedences for cast operators; we prefer // the traditional forms (T)x, x as T, x using T which have lower // precedence, but they don't work in this context so consider using // x(->T), x(as T) or x(using T) instead. alternate = true; precedence = EP.Primary; if (!CanAppearHere(precedence, out needParens)) return false; } if (alternate && _o.PreferPlainCSharp) return false; // old-style cast is impossible here if (WriteOpenParen(ParenFor.Grouping, needParens)) _context = StartExpr; if (alternate) { PrintExpr(subject, precedence.LeftContext(_context)); WriteOpenParen(ParenFor.NewCast); _out.Write(GetCastText(_name), true); Space(SpaceOpt.AfterCastArrow); PrintType(target, StartExpr, Ambiguity.AllowPointer); WriteCloseParen(ParenFor.NewCast); } else { if (_name == S.Cast) { WriteOpenParen(ParenFor.Grouping); PrintType(target, ContinueExpr, Ambiguity.AllowPointer); WriteCloseParen(ParenFor.Grouping); Space(SpaceOpt.AfterCast); PrintExpr(subject, precedence.RightContext(_context), Ambiguity.CastRhs); } else { // "x as y" or "x using y" PrintExpr(subject, precedence.LeftContext(_context)); _out.Write(GetCastText(_name), true); PrintType(target, precedence.RightContext(_context)); } } WriteCloseParen(ParenFor.Grouping, needParens); return true; }
public SqlPrefixOperatorParselet(Precedence precedence) { _prefix = new PrefixOperatorParselet((int)precedence); }
Expression ParseExpression(Precedence p, bool vectorMode) { var e = ParseUnaryExpression(vectorMode); while (e != null) { var op = Peek(); if (op == TokenType.Period) { Consume(); var id = Consume(); if (!IsIdentifier(id)) { Error("Expected identifier after '.'"); } e = new MemberExpression(e, id.Value); continue; } if (op == TokenType.LeftSquareBrace) { Consume(); var index = ParseExpression(Precedence.Invalid, true); if (Peek() != TokenType.RightSquareBrace) { Error("Expected ]"); } Consume(); e = new LookUpExpression(e, index); continue; } if (p < Precedence.Assignment) { if (TryConsume(TokenType.Colon)) { e = new NameValuePairExpression(e, Expect(ParseExpression(Precedence.Assignment, false))); continue; } } if (p < Precedence.Conditional) { if (TryConsume(TokenType.QuestionMark)) { var case1 = Expect(ParseExpression(Precedence.Conditional, false)); if (!TryConsume(TokenType.Colon)) { Error("Expected ':'"); } var case2 = Expect(ParseExpression(Precedence.Conditional, false)); e = new ConditionalExpression(e, case1, case2); continue; } } if (p < Precedence.Multiplicative) { if (TryConsume(TokenType.Mul)) { e = new MultiplyExpression(e, Expect(ParseExpression(Precedence.Multiplicative, false))); continue; } if (TryConsume(TokenType.Div)) { e = new DivideExpression(e, Expect(ParseExpression(Precedence.Multiplicative, false))); continue; } } if (p < Precedence.Additive) { if (TryConsume(TokenType.Plus)) { e = new AddExpression(e, Expect(ParseExpression(Precedence.Additive, false))); continue; } if (TryConsume(TokenType.Minus)) { e = new SubtractExpression(e, Expect(ParseExpression(Precedence.Additive, false))); continue; } } if (p < Precedence.LogicalAnd) { if (TryConsume(TokenType.LogAnd)) { e = new LogicalAndExpression(e, Expect(ParseExpression(Precedence.LogicalAnd, false))); continue; } } if (p < Precedence.LogicalOr) { if (TryConsume(TokenType.LogOr)) { e = new LogicalOrExpression(e, Expect(ParseExpression(Precedence.LogicalOr, false))); continue; } } if (p < Precedence.Relational) { if (TryConsume(TokenType.LessThan)) { e = new LessThanExpression(e, Expect(ParseExpression(Precedence.Relational, false))); continue; } if (TryConsume(TokenType.LessOrEqual)) { e = new LessOrEqualExpression(e, Expect(ParseExpression(Precedence.Relational, false))); continue; } if (TryConsume(TokenType.GreaterThan)) { e = new GreaterThanExpression(e, Expect(ParseExpression(Precedence.Relational, false))); continue; } if (TryConsume(TokenType.GreaterOrEqual)) { e = new GreaterOrEqualExpression(e, Expect(ParseExpression(Precedence.Relational, false))); continue; } if (TryConsume(TokenType.NotEqual)) { e = new NotEqualExpression(e, Expect(ParseExpression(Precedence.Relational, false))); continue; } if (TryConsume(TokenType.Equal)) { e = new EqualExpression(e, Expect(ParseExpression(Precedence.Relational, false))); continue; } } if (p < Precedence.NullCoalescing) { if (TryConsume(TokenType.DoubleQuestionMark)) { e = new NullCoalesceExpression(e, Expect(ParseExpression(Precedence.NullCoalescing, false))); } } // Vector op if (vectorMode && p == Precedence.Invalid && Peek() == TokenType.Comma) { var comps = new List <Expression>(); comps.Add(e); while (TryConsume(TokenType.Comma)) { e = Expect(ParseExpression(Precedence.Invalid, false)); comps.Add(e); } e = new VectorExpression(comps.ToArray()).TryFold(); } break; } return(e); }
public void RhSide(Production p) { CSymbol s; ParserOldAction a = null; // last old action seen while (m_tok != null) { if (m_tok.Matches(";")) { break; } if (m_tok.Matches("|")) { break; } if (m_tok.Matches(":")) { Advance(); p.m_alias[m_tok.yytext] = p.m_rhs.Count; Advance(); } else if (m_tok is PrecReference) { if (p.m_rhs.Count == 0) { erh.Error(new CSToolsException(21, "%prec cannot be at the start of a right hand side")); } PrecReference pr = (PrecReference)m_tok; CSymbol r = (CSymbol)p.m_rhs[p.m_rhs.Count - 1]; r.m_prec = pr.precref.m_prec; Advance(); } else { s = (CSymbol)m_tok; if (s.m_symtype == CSymbol.SymType.oldaction) { if (a != null) { Error(42, s.pos, "adjacent actions"); } a = (ParserOldAction)s; if (a.m_action < 0) { // an OldAction that has been converted to a SimpleAction: discard it s = a.m_sym; // add the SimpleAction instead s.m_symtype = CSymbol.SymType.simpleaction; ParserSimpleAction sa = (ParserSimpleAction)s; } else // add it to the Actions function { m_actions += String.Format("\ncase {0} : {1} break;", a.m_action, a.m_initialisation); } a = null; } else if (s.m_symtype != CSymbol.SymType.simpleaction) { s = ((CSymbol)m_tok).Resolve(); } p.AddToRhs(s); Advance(); } } Precedence.Check(p); }
private bool TryResolveShiftReduce(int actionX, int actionY, int incomingToken, out int output) { output = 0; int shiftAction, reduceAction; if (ParserAction.GetKind(actionX) == ParserActionKind.Shift && ParserAction.GetKind(actionY) == ParserActionKind.Reduce) { shiftAction = actionX; reduceAction = actionY; } else if (ParserAction.GetKind(actionY) == ParserActionKind.Shift && ParserAction.GetKind(actionX) == ParserActionKind.Reduce) { shiftAction = actionY; reduceAction = actionX; } else { #if LALR1_TOLERANT // Unsupported conflict type. Use first action output = actionX; #else output = ParserAction.Encode(ParserActionKind.Conflict, 0); #endif return(false); } var shiftTokenPrecedence = grammar.GetTermPrecedence(incomingToken); var reduceRulePrecedence = grammar.GetProductionPrecedence(ParserAction.GetId(reduceAction)); if (shiftTokenPrecedence == null && reduceRulePrecedence == null) { #if LALR1_TOLERANT // In case of conflict prefer shift over reduce output = shiftAction; #else output = ParserAction.Encode(ParserActionKind.Conflict, 0); #endif return(false); } else if (shiftTokenPrecedence == null) { output = reduceAction; } else if (reduceRulePrecedence == null) { output = shiftAction; } else if (Precedence.IsReduce(reduceRulePrecedence, shiftTokenPrecedence)) { output = reduceAction; } else { output = shiftAction; } return(true); }
public T1 Parse <T1>(Precedence precedence = Precedence.Invalid) where T1 : IShellSegment => (T1)this.ParseSpecificSegment(precedence, typeof(T1));
public ParseRule(Action prefix, Action infix, Precedence precedence) { Prefix = prefix; Infix = infix; Precedence = precedence; }
public IShellSegment Parse <T1, T2, T3, T4>(Precedence precedence = Precedence.Invalid) where T1 : IShellSegment where T2 : IShellSegment where T3 : IShellSegment where T4 : IShellSegment => this.ParseSpecificSegment(precedence, typeof(T1), typeof(T2), typeof(T3), typeof(T4));
LNode Expr(Precedence context) { TokenType la0, la1; Debug.Assert(context.CanParse(EP.Prefix)); Precedence prec; var e = PrefixExpr(); // Line 634: greedy( &{context.CanParse(prec = InfixPrecedenceOf($LA))} (TT.@in|TT.Add|TT.And|TT.AndBits|TT.BQString|TT.CompoundSet|TT.DivMod|TT.DotDot|TT.EqNeq|TT.GT|TT.LambdaArrow|TT.LEGE|TT.LT|TT.Mul|TT.NotBits|TT.NullCoalesce|TT.OrBits|TT.OrXor|TT.Power|TT.Set|TT.Sub|TT.XorBits) Expr | &{context.CanParse(prec = InfixPrecedenceOf($LA))} (TT.@as|TT.@is|TT.@using) DataType | &{context.CanParse(EP.Shift)} &{LT($LI).EndIndex == LT($LI + 1).StartIndex} (TT.LT TT.LT Expr | TT.GT TT.GT Expr) | &{context.CanParse(EP.IfElse)} TT.QuestionMark Expr TT.Colon Expr )* for (;;) { switch (LA0) { case TT.GT: case TT.LT: { la0 = LA0; if (context.CanParse(prec = InfixPrecedenceOf(la0))) { if (LT(0).EndIndex == LT(0 + 1).StartIndex) { if (context.CanParse(EP.Shift)) { la1 = LA(1); if (PrefixExpr_set0.Contains((int) la1)) goto match1; else if (la1 == TT.GT || la1 == TT.LT) goto match3; else goto stop; } else { la1 = LA(1); if (PrefixExpr_set0.Contains((int) la1)) goto match1; else goto stop; } } else { la1 = LA(1); if (PrefixExpr_set0.Contains((int) la1)) goto match1; else goto stop; } } else if (LT(0).EndIndex == LT(0 + 1).StartIndex) { if (context.CanParse(EP.Shift)) { la1 = LA(1); if (la1 == TT.GT || la1 == TT.LT) goto match3; else goto stop; } else goto stop; } else goto stop; } case TT.@in: case TT.Add: case TT.And: case TT.AndBits: case TT.BQString: case TT.CompoundSet: case TT.DivMod: case TT.DotDot: case TT.EqNeq: case TT.LambdaArrow: case TT.LEGE: case TT.Mul: case TT.NotBits: case TT.NullCoalesce: case TT.OrBits: case TT.OrXor: case TT.Power: case TT.Set: case TT.Sub: case TT.XorBits: { la0 = LA0; if (context.CanParse(prec = InfixPrecedenceOf(la0))) { la1 = LA(1); if (PrefixExpr_set0.Contains((int) la1)) goto match1; else goto stop; } else goto stop; } case TT.@as: case TT.@is: case TT.@using: { la0 = LA0; if (context.CanParse(prec = InfixPrecedenceOf(la0))) { switch (LA(1)) { case TT.@operator: case TT.ContextualKeyword: case TT.Id: case TT.Substitute: case TT.TypeKeyword: { var op = MatchAny(); var rhs = DataType(true); var opSym = op.Type() == TT.@using ? S.UsingCast : ((Symbol) op.Value); e = SetOperatorStyle(F.Call(opSym, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex)); } break; default: goto stop; } } else goto stop; } break; case TT.QuestionMark: { if (context.CanParse(EP.IfElse)) { la1 = LA(1); if (PrefixExpr_set0.Contains((int) la1)) { Skip(); var then = Expr(ContinueExpr); Match((int) TT.Colon); var @else = Expr(EP.IfElse); #line 656 "EcsParserGrammar.les" e = SetOperatorStyle(F.Call(S.QuestionMark, e, then, @else, e.Range.StartIndex, @else.Range.EndIndex)); #line default } else goto stop; } else goto stop; } break; default: goto stop; } continue; match1: { var op = MatchAny(); var rhs = Expr(prec); #line 638 "EcsParserGrammar.les" e = SetOperatorStyle(F.Call((Symbol) op.Value, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex)); #line default } continue; match3: { // Line 648: (TT.LT TT.LT Expr | TT.GT TT.GT Expr) la0 = LA0; if (la0 == TT.LT) { Skip(); Match((int) TT.LT); var rhs = Expr(EP.Shift); #line 649 "EcsParserGrammar.les" e = SetOperatorStyle(F.Call(S.Shl, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex)); #line default } else { Match((int) TT.GT); Match((int) TT.GT); var rhs = Expr(EP.Shift); #line 651 "EcsParserGrammar.les" e = SetOperatorStyle(F.Call(S.Shr, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex)); #line default } } } stop:; #line 658 "EcsParserGrammar.les" return e; #line default }
private WorkerResource(string name, Precedence precedence) { Name = name; m_precedence = precedence; }
public override void AssocType(Precedence.PrecType pt, int p) { string line; int len,action=0; CSymbol s; line = m_lexer.yytext; prec += 10; if (line[p]!=' '&&line[p]!='\t') Error(33,m_lexer.m_pch,"Expected white space after precedence directive"); for (p++;p<line.Length && (line[p]==' '||line[p]=='\t');p++) ; while (p<line.Length) { len = m_lexer.m_start.Match(line,p,ref action); if (len<0) { Console.WriteLine(line.Substring(p)); Error(34,m_lexer.m_pch,"Expected token"); break; } m_lexer.yytext = line.Substring(p,len); bool rej = false; s = (CSymbol)((yyptokens)(m_lexer.tokens)).OldAction(m_lexer,m_lexer.yytext,action,ref rej); s = s.Resolve(); s.m_prec = new Precedence(pt,prec,s.m_prec); for (p+=len; p<line.Length && (line[p]==' '||line[p]=='\t'); p++) ; } }
public CSharpExpressionWriter(IndentingTextWriter writer) { this.writer = writer; this.precedence = Precedence.Base; }
void PrintExpr(LNode n, Precedence context, Ambiguity flags) { using (With(n, context, CheckOneLiner(flags, n))) PrintCurrentExpr(); }
LNode Expr(Precedence context) { LNode e = default(LNode); Token t = default(Token); // line 123 Precedence prec; e = PrefixExpr(context); // Line 127: greedy( &{context.CanParse(prec = InfixPrecedenceOf(LT($LI)))} ((TT.Assignment|TT.BQString|TT.Dot|TT.NormalOp) | &{LA($LI + 1) != TT.Indent->@int} TT.Colon) Expr | &{context.CanParse(P.Primary)} FinishPrimaryExpr | &{context.CanParse(SuffixPrecedenceOf(LT($LI)))} TT.PreOrSufOp )* for (;;) { switch ((TT)LA0) { case TT.Assignment: case TT.BQString: case TT.Dot: case TT.NormalOp: { if (context.CanParse(prec = InfixPrecedenceOf(LT(0)))) { goto matchExpr; } else { goto stop; } } case TT.Colon: { if (LA(0 + 1) != (int)TT.Indent) { if (context.CanParse(prec = InfixPrecedenceOf(LT(0)))) { goto matchExpr; } else { goto stop; } } else { goto stop; } } case TT.LBrack: case TT.LParen: case TT.Not: { if (context.CanParse(P.Primary)) { e = FinishPrimaryExpr(e); } else { goto stop; } } break; case TT.PreOrSufOp: { if (context.CanParse(SuffixPrecedenceOf(LT(0)))) { t = MatchAny(); // line 140 e = F.Call(ToSuffixOpName((Symbol)t.Value), e, e.Range.StartIndex, t.EndIndex).SetStyle(NodeStyle.Operator); } else { goto stop; } } break; default: goto stop; } continue; matchExpr: { // line 128 if ((!prec.CanMixWith(context))) { Error(0, "Operator '{0}' is not allowed in this context. Add parentheses to clarify the code's meaning.", LT0.Value); } // Line 131: ((TT.Assignment|TT.BQString|TT.Dot|TT.NormalOp) | &{LA($LI + 1) != TT.Indent->@int} TT.Colon) switch ((TT)LA0) { case TT.Assignment: case TT.BQString: case TT.Dot: case TT.NormalOp: t = MatchAny(); break; default: { Check(LA(0 + 1) != (int)TT.Indent, "LA($LI + 1) != TT.Indent->@int"); t = Match((int)TT.Colon); } break; } var rhs = Expr(prec); // line 133 e = F.Call((Symbol)t.Value, e, rhs, e.Range.StartIndex, rhs.Range.EndIndex).SetStyle(NodeStyle.Operator); } } stop :; // line 142 return(e); }
// Checks if an operator that may or may not be configured to output in // `backtick notation` can appear in this context; this method may toggle // backtick notation to make it acceptable (in terms of precedence). bool CanAppearHere(ref Precedence prec, out bool extraParens, ref bool backtick, bool prefix = false) { var altPrec = EP.Backtick; if (backtick) G.Swap(ref prec, ref altPrec); if (CanAppearHere(prec, out extraParens, prefix && !backtick)) return true; backtick = !backtick; G.Swap(ref prec, ref altPrec); return CanAppearHere(prec, out extraParens, prefix && !backtick); }
internal BinaryOperator(IParseNode leftOperand, IParseNode rightOperand, Associativity associativity, bool commutative, Precedence precedence, Position position) { LeftOperand = leftOperand; RightOperand = rightOperand; Associativity = associativity; Commutative = commutative; Precedence = precedence; Position = position; }
public bool AutoPrintInfixBinaryOperator(Precedence prec) { Debug.Assert(!CastOperators.ContainsKey(_name)); // not called for cast operators if (_n.ArgCount != 2) return false; LNode left = _n.Args[0], right = _n.Args[1]; if (!_o.AllowChangeParentheses) { // Attributes on the children normally disqualify operator notation if (HasPAttrs(left) || HasPAttrs(right)) return false; } bool needParens, backtick = (_n.Style & NodeStyle.Alternate) != 0 || (_flags & Ambiguity.UseBacktick) != 0; if (CanAppearHere(ref prec, out needParens, ref backtick)) { // Check for the ambiguous case of "A * b;" and consider using `*` instead if (_name == S.Mul && _context.Left == StartStmt.Left && IsComplexIdentifier(left)) { backtick = true; prec = EP.Backtick; if (!CanAppearHere(prec, out needParens, false)) return false; } if (WriteOpenParen(ParenFor.Grouping, needParens)) _context = StartExpr; Ambiguity lFlags = _flags & Ambiguity.TypeContext; if (_name == S.Assign || _name == S.Lambda) lFlags |= Ambiguity.AllowUnassignedVarDecl; if (_name == S.NotBits) lFlags |= Ambiguity.IsCallTarget; PrintExpr(left, prec.LeftContext(_context), lFlags); PrintInfixWithSpace(_name, _n.Target, prec, backtick); PrintExpr(right, prec.RightContext(_context)); WriteCloseParen(ParenFor.Grouping, needParens); return true; } return false; }
/// <summary> /// Here is the grammar being parsed: /// ``` antlr /// pattern /// : declaration_pattern /// | constant_pattern /// | deconstruction_pattern /// | property_pattern /// | discard_pattern /// ; /// declaration_pattern /// : type identifier /// ; /// constant_pattern /// : expression /// ; /// deconstruction_pattern /// : type? '(' subpatterns? ')' property_subpattern? identifier? /// ; /// subpatterns /// : subpattern /// | subpattern ',' subpatterns /// ; /// subpattern /// : pattern /// | identifier ':' pattern /// ; /// property_subpattern /// : '{' subpatterns? '}' /// ; /// property_pattern /// : property_subpattern identifier? /// ; /// discard_pattern /// : '_' /// ; /// ``` /// /// Priority is the ExpressionSyntax. It might return ExpressionSyntax which might be a constant pattern such as 'case 3:' /// All constant expressions are converted to the constant pattern in the switch binder if it is a match statement. /// It is used for parsing patterns in the switch cases. It never returns constant pattern, because for a `case` we /// need to use a pre-pattern-matching syntax node for a constant case. /// </summary> /// <param name="whenIsKeyword">prevents the use of "when" for the identifier</param> /// <returns></returns> private CSharpSyntaxNode ParseExpressionOrPattern(bool whenIsKeyword, bool forSwitchCase, Precedence precedence) { // handle common error recovery situations during typing var tk = this.CurrentToken.Kind; switch (tk) { case SyntaxKind.CommaToken: case SyntaxKind.SemicolonToken: case SyntaxKind.CloseBraceToken: case SyntaxKind.CloseParenToken: case SyntaxKind.CloseBracketToken: case SyntaxKind.EqualsGreaterThanToken: return(this.ParseIdentifierName(ErrorCode.ERR_MissingPattern)); } if (CurrentToken.ContextualKind == SyntaxKind.UnderscoreToken && !forSwitchCase) { // In a switch case, we parse `_` as an expression. return(_syntaxFactory.DiscardPattern(this.EatContextualToken(SyntaxKind.UnderscoreToken))); } var resetPoint = this.GetResetPoint(); try { TypeSyntax type = null; if (LooksLikeTypeOfPattern(tk)) { type = this.ParseType(ParseTypeMode.DefinitePattern); if (type.IsMissing || !CanTokenFollowTypeInPattern()) { // either it is not shaped like a type, or it is a constant expression. this.Reset(ref resetPoint); type = null; } } PatternSyntax p = ParsePatternContinued(type, whenIsKeyword); if (p != null) { return((whenIsKeyword && p is ConstantPatternSyntax c) ? c.expression : (CSharpSyntaxNode)p); } this.Reset(ref resetPoint); return(this.ParseSubExpression(precedence)); } finally { this.Release(ref resetPoint); } }
public bool AutoPrintPrefixReturnThrowEtc(Precedence prec) { if (!EcsValidators.IsSimpleExecutableKeywordStmt(_n, Pedantics)) return false; bool needParens; if (!CanAppearHere(prec, out needParens)) return false; if (WriteOpenParen(ParenFor.Grouping, needParens)) _context = StartExpr; else if (_context.Left == StartStmt.Left) return false; // cannot print throw/return subexpression at beginning of a statement PrintReturnThrowEtc(_name, _n.Args[0, null]); WriteCloseParen(ParenFor.Grouping, needParens); return true; }
public bool AutoPrintAnonymousFunction(Precedence precedence) { Symbol name = _name; Debug.Assert(name == S.Lambda); if (_n.ArgCount != 2) return false; LNode args = _n.Args[0], body = _n.Args[1]; bool needParens = false; bool canUseOldStyle = body.Calls(S.Braces) && args.Calls(S.AltList); bool oldStyle = _n.BaseStyle == NodeStyle.OldStyle && canUseOldStyle; if (!oldStyle && !CanAppearHere(EP.Lambda, out needParens)) { if (canUseOldStyle) oldStyle = true; else return false; // precedence fail } WriteOpenParen(ParenFor.Grouping, needParens); if (oldStyle) { _out.Write("delegate", true); PrintArgList(_n.Args[0].Args, ParenFor.MethodDecl, true, _o.OmitMissingArguments); PrintBracedBlock(body, NewlineOpt.BeforeOpenBraceInExpr, spaceName: S.Fn); } else { PrintExpr(_n.Args[0], EP.Lambda.LeftContext(_context), Ambiguity.AllowUnassignedVarDecl | (_flags & Ambiguity.OneLiner)); PrintInfixWithSpace(S.Lambda, _n.Target, EP.IfElse); PrintExpr(_n.Args[1], EP.Lambda.RightContext(_context)); } WriteCloseParen(ParenFor.Grouping, needParens); return true; }
public bool AutoPrintListOperator(Precedence precedence) { // Handles #tuple and {} braces. int argCount = _n.ArgCount; Symbol name = _name; Debug.Assert(_n.IsCall); bool? braceMode; if (name == S.Tuple) { braceMode = false; _flags &= Ambiguity.AllowUnassignedVarDecl; } else if (name == S.Braces) { // A braced block is not allowed at start of an expression // statement; the parser would mistake it for a standalone // braced block (the difference is that a standalone braced // block ends automatically after '}', with no semicolon.) if (_context.Left == StartStmt.Left || (_flags & Ambiguity.NoBracedBlock) != 0) return false; braceMode = true; if (_context.Left <= ContinueExpr.Left && _n.BaseStyle == NodeStyle.Expression) braceMode = null; // initializer mode } else if (name == S.ArrayInit) { braceMode = null; // initializer mode } else { Debug.Assert(false); // Code quote operator has been REMOVED from EC#, in favor of #quote(...), at least for now. //Debug.Assert(name == S.CodeQuote || name == S.CodeQuoteSubstituting || name == S.List); //_out.Write(name == S.CodeQuote ? "@" : "@@", false); braceMode = _n.BaseStyle == NodeStyle.Statement && (_flags & Ambiguity.NoBracedBlock) == 0; _flags = 0; } int c = _n.ArgCount; if (braceMode ?? true) { PrintBracedBlock(_n, NewlineOpt.BeforeOpenBraceInExpr, mode: braceMode == null ? BraceMode.Initializer : BraceMode.Normal); } else { WriteOpenParen(ParenFor.Grouping); for (int i = 0; i < c; i++) { if (i != 0) WriteThenSpace(',', SpaceOpt.AfterComma); PrintExpr(_n.Args[i], StartExpr, _flags); } if (name == S.Tuple && c == 1) _out.Write(',', true); WriteCloseParen(ParenFor.Grouping); } return true; }
public bool AutoPrintCallOperator(Precedence precedence) { // Handles "call operators" such as default(...) and checked(...) bool needParens; Debug.Assert(CanAppearHere(precedence, out needParens)); Debug.Assert(_n.HasSpecialName); if (_n.ArgCount != 1) return false; var arg = _n.Args[0]; bool type = (_name == S.Default || _name == S.Typeof || _name == S.Sizeof); if (type && !IsComplexIdentifier(arg, ICI.Default | ICI.AllowAttrs)) return false; WriteOperatorName(_name); if (type) { WriteOpenParen(ParenFor.MethodCall); PrintType(arg, StartExpr, Ambiguity.AllowPointer); WriteCloseParen(ParenFor.MethodCall); } else PrintWithinParens(ParenFor.MethodCall, arg, 0); return true; }
public bool AutoPrintNewOperator(Precedence precedence) { // Prints the new Xyz(...) {...} operator Debug.Assert (_name == S.New); int argCount = _n.ArgCount; if (argCount == 0) return false; bool needParens; Debug.Assert(CanAppearHere(precedence, out needParens) && !needParens); LNode cons = _n.Args[0]; LNode type = cons.Target; var consArgs = cons.Args; // There are two basic uses of new: for objects, and for arrays. // In all cases, #new has 1 arg plus optional initializer arguments, // and there's always a list of "constructor args" even if it is empty // (exception: new {...}). // 1. Init an object: 1a. new Foo<Bar>() { ... } <=> #new(Foo<bar>(...), ...) // 1b. new { ... } <=> #new(@``, ...) // 2. Init an array: 2a. new int[] { ... }, <=> #new(int[](), ...) <=> #new(#of(@`[]`, int)(), ...) // 2b. new[,] { ... }. <=> #new(@`[,]`(), ...) // 2c. new int[10,10] { ... }, <=> #new(#of(@`[,]`, int)(10,10), ...) // 2d. new int[10][] { ... }, <=> #new(#of(@`[]`, #of(@`[]`, int))(10), ...) if (HasPAttrs(cons)) return false; if (type == null ? !cons.IsIdNamed(S.Missing) : HasPAttrs(type) || !IsComplexIdentifier(type)) return false; // Okay, we can now be sure that it's printable, but is it an array decl? if (type == null) { // 1b, new {...} _out.Write("new ", true); PrintBracedBlockInNewExpr(1); } else if (type != null && type.IsId && S.CountArrayDimensions(type.Name) > 0) { // 2b _out.Write("new", true); Debug.Assert(type.Name.Name.StartsWith("#")); _out.Write(type.Name.Name.Substring(1), true); Space(SpaceOpt.Default); PrintBracedBlockInNewExpr(1); } else { _out.Write("new ", true); int dims = CountDimensionsIfArrayType(type); if (dims > 0 && cons.Args.Count == dims) { PrintTypeWithArraySizes(cons); } else { // Otherwise we can print the type name without caring if it's an array or not. PrintType(type, EP.Primary.LeftContext(_context)); if (cons.ArgCount != 0 || (argCount == 1 && dims == 0)) PrintArgList(cons.Args, ParenFor.MethodCall, false, _o.OmitMissingArguments); } if (_n.Args.Count > 1) PrintBracedBlockInNewExpr(1); } return true; }
// Parses the next (maximal) expression with precedence >= precMin. private ExprNode ParseExpr(Precedence precMin) { // ParseOperand may accept PrefixUnary and higher, so ParseExpr should never be called // with precMin > Precedence.PrefixUnary - it will not correctly handle those cases. Contracts.Assert(Precedence.None <= precMin); Contracts.Assert(precMin <= Precedence.PrefixUnary); // Get the left operand. ExprNode node = ParsePrimary(); // Process operators and right operands as long as the precedence bound is satisfied. for (; ;) { Contracts.AssertValue(node); switch (TidCur) { case TokKind.Car: Contracts.Assert(precMin <= Precedence.Power); // Note that the right operand can include unary operators. node = new BinaryOpNode(TokMove(), BinaryOp.Power, node, ParseExpr(Precedence.PrefixUnary)); break; case TokKind.Mul: if (precMin > Precedence.Mul) { return(node); } node = new BinaryOpNode(TokMove(), BinaryOp.Mul, node, ParseExpr(Precedence.Mul + 1)); break; case TokKind.Div: if (precMin > Precedence.Mul) { return(node); } node = new BinaryOpNode(TokMove(), BinaryOp.Div, node, ParseExpr(Precedence.Mul + 1)); break; case TokKind.Per: if (precMin > Precedence.Mul) { return(node); } node = new BinaryOpNode(TokMove(), BinaryOp.Mod, node, ParseExpr(Precedence.Mul + 1)); break; case TokKind.Sub: if (precMin > Precedence.Add) { return(node); } node = new BinaryOpNode(TokMove(), BinaryOp.Sub, node, ParseExpr(Precedence.Add + 1)); break; case TokKind.Add: if (precMin > Precedence.Add) { return(node); } node = new BinaryOpNode(TokMove(), BinaryOp.Add, node, ParseExpr(Precedence.Add + 1)); break; case TokKind.AmpAmp: case TokKind.And: if (precMin > Precedence.And) { return(node); } node = new BinaryOpNode(TokMove(), BinaryOp.And, node, ParseExpr(Precedence.And + 1)); break; case TokKind.BarBar: case TokKind.Or: if (precMin > Precedence.Or) { return(node); } node = new BinaryOpNode(TokMove(), BinaryOp.Or, node, ParseExpr(Precedence.Or + 1)); break; case TokKind.QueQue: if (precMin > Precedence.Coalesce) { return(node); } // Note that the associativity is different than other binary operators (right instead of left), // so the recursive call accepts Precedence.Coal. node = new BinaryOpNode(TokMove(), BinaryOp.Coalesce, node, ParseExpr(Precedence.Coalesce)); break; case TokKind.Que: if (precMin > Precedence.Conditional) { return(node); } node = new ConditionalNode(TokMove(), node, ParseExpr(), TokEat(TokKind.Colon), ParseExpr()); break; // Comparison operators // expr = ... = expr // expr <> ... <> expr case TokKind.Equ: case TokKind.EquEqu: if (precMin > Precedence.Compare) { return(node); } node = ParseCompareExpr(node, CompareOp.Equal, TokKind.Equ, TokKind.EquEqu); break; case TokKind.LssGrt: case TokKind.BngEqu: if (precMin > Precedence.Compare) { return(node); } node = ParseCompareExpr(node, CompareOp.NotEqual, TokKind.LssGrt, TokKind.BngEqu); break; // expr < expr // expr <= expr case TokKind.Lss: case TokKind.LssEqu: if (precMin > Precedence.Compare) { return(node); } node = ParseCompareExpr(node, CompareOp.IncrChain, TokKind.LssEqu, TokKind.Lss); break; // expr > expr // expr >= expr case TokKind.Grt: case TokKind.GrtEqu: if (precMin > Precedence.Compare) { return(node); } node = ParseCompareExpr(node, CompareOp.DecrChain, TokKind.GrtEqu, TokKind.Grt); break; case TokKind.True: case TokKind.False: case TokKind.IntLit: case TokKind.FltLit: case TokKind.DblLit: case TokKind.CharLit: case TokKind.StrLit: PostError(TokCur, "Operator expected"); node = new BinaryOpNode(TokCur, BinaryOp.Error, node, ParseExpr(Precedence.Error)); break; default: return(node); } } }
public bool AutoPrintOtherSpecialOperator(Precedence precedence) { // Handles one of: ? _[] ?[] suf++ suf-- int argCount = _n.ArgCount; Symbol name = _name; if (argCount < 1) return false; // no args bool needParens; if (!CanAppearHere(precedence, out needParens)) return false; // precedence fail // Verify that the special operator can appear at this precedence // level and that its arguments fit the operator's constraints. var first = _n.Args[0]; if (name == S.IndexBracks) { // Careful: a[] means #of(@`[]`, a) in a type context, @`_[]`(a) otherwise int minArgs = (_flags & Ambiguity.TypeContext) != 0 ? 2 : 1; if (argCount < minArgs || HasPAttrs(first)) return false; } else if (name == S.NullIndexBracks) { if (argCount != 2 || HasPAttrs(first) || HasPAttrs(_n.Args[1]) || !_n.Args[1].Calls(S.AltList)) return false; } else if (name == S.QuestionMark) { if (argCount != 3 || HasPAttrs(first) || HasPAttrs(_n.Args[1]) || HasPAttrs(_n.Args[2])) return false; } else { Debug.Assert(name == S.PostInc || name == S.PostDec || name == S.IsLegal); if (argCount != 1 || HasPAttrs(first)) return false; } // Print the thing! WriteOpenParen(ParenFor.Grouping, needParens); if (name == S.IndexBracks) { PrintExpr(first, precedence.LeftContext(_context)); Space(SpaceOpt.BeforeMethodCall); _out.Write('[', true); Space(SpaceOpt.InsideCallParens); for (int i = 1, c = _n.ArgCount; i < c; i++) { if (i != 1) WriteThenSpace(',', SpaceOpt.AfterComma); PrintExpr(_n.Args[i], StartExpr); } Space(SpaceOpt.InsideCallParens); _out.Write(']', true); } else if (name == S.NullIndexBracks) { PrintExpr(first, precedence.LeftContext(_context)); Space(SpaceOpt.BeforeMethodCall); _out.Write("?[", true); Space(SpaceOpt.InsideCallParens); PrintArgs(_n.Args[1], false); Space(SpaceOpt.InsideCallParens); _out.Write(']', true); } else if (name == S.QuestionMark) { PrintExpr(_n.Args[0], precedence.LeftContext(_context)); PrintInfixWithSpace(S.QuestionMark, _n.Target, EP.IfElse); PrintExpr(_n.Args[1], ContinueExpr); PrintInfixWithSpace(S.Colon, null, EP.IfElse); PrintExpr(_n.Args[2], precedence.RightContext(_context)); } else { Debug.Assert(name == S.PostInc || name == S.PostDec || name == S.IsLegal); PrintExpr(first, precedence.LeftContext(_context)); _out.Write(name == S.PostInc ? "++" : name == S.PostDec ? "--" : "is legal", true); } WriteCloseParen(ParenFor.Grouping, needParens); return true; }
protected void PrintType(LNode n, Precedence context, Ambiguity flags = 0) { using (With(n, context, CheckOneLiner(flags | Ambiguity.TypeContext, n))) PrintCurrentType(); }
public bool AutoPrintNamedArg(Precedence precedence) { if (!EcsValidators.IsNamedArgument(_n, Pedantics) || _context.RangeEquals(StartStmt)) return false; bool needParens; if (!CanAppearHere(precedence, out needParens) || needParens) return false; PrintExpr(_n.Args[0], EP.Primary.LeftContext(_context)); WriteThenSpace(':', SpaceOpt.AfterColon); PrintExpr(_n.Args[1], StartExpr); return true; }
public PostfixOperatorParselet(TokenType @operator, Precedence precedence) { _operator = @operator; _precedence = precedence; }
public bool PrintRawText(Precedence mainPrec) { if (!_o.ObeyRawText) return false; _out.Write(GetRawText(_n), true); return true; }
public InfixParselet(Precedence precedence) { Precedence = precedence; }
// // public Packet(byte[] raw):(byte[] raw, DateTime time // { // Packet(raw, DateTime.Now); // } public Packet(byte[] raw, DateTime time) { if (raw == null) { throw new ArgumentNullException(); } if (raw.Length < 20) { throw new ArgumentException(); } this.m_Raw = raw; this.m_Time = time; this.m_HeaderLength = (raw[0] & 0xF) * 4; if ((raw[0] & 0xF) < 5) { throw new ArgumentException(); } this.m_Precedence = (Precedence)((raw[1] & 0xE0) >> 5); this.m_Delay = (Delay)((raw[1] & 0x10) >> 4); this.m_Throughput = (Throughput)((raw[1] & 0x8) >> 3); this.m_Reliability = (Reliability)((raw[1] & 0x4) >> 2); this.m_TotalLength = raw[2] * 256 + raw[3]; if (!(this.m_TotalLength == raw.Length)) { throw new ArgumentException(); } // invalid size of packet; this.m_Identification = raw[4] * 256 + raw[5]; this.m_TimeToLive = raw[8]; m_Protocol = (InternetProtocol)raw[9]; m_Checksum = new byte[2]; m_Checksum[0] = raw[11]; m_Checksum[1] = raw[10]; try { m_SourceAddress = GetIPAddress(raw, 12); m_DestinationAddress = GetIPAddress(raw, 16); } catch (Exception e) { throw; } if (m_Protocol == InternetProtocol.Tcp || m_Protocol == InternetProtocol.Udp) { m_SourcePort = raw[m_HeaderLength] * 256 + raw[m_HeaderLength + 1]; m_DestinationPort = raw[m_HeaderLength + 2] * 256 + raw[m_HeaderLength + 3]; } else { m_SourcePort = -1; m_DestinationPort = -1; } }
public override ParseTree Parse(Lexer lexer, ParserState state) { int start = lexer.Position; state.RuntimeState.Runtime.ParseTrace.Enter(this, lexer.CurrentSource(), "Pattern " + Type.Name); /*state.RuntimeState.Runtime.ParseTrace.Enter(this, lexer.CurrentSource(), "Excluded:"); * * foreach (Pattern excluded in state.Excluded) * state.RuntimeState.Runtime.ParseTrace.Single(excluded.Type.Name); * * state.RuntimeState.Runtime.ParseTrace.Leave(this);*/ if (state.Excluded.Contains(this)) { state.RuntimeState.Runtime.ParseTrace.No(this, lexer.CurrentSource(), "Excluded"); return(ParseTree.No); } ParserMemoryKey key = new ParserMemoryKey(this, start); bool oldSkipMemoryForLeftRecursion = state.SkipMemoryForLeftRecursion; if (state.SkipMemoryForLeftRecursion) { state.SkipMemoryForLeftRecursion = false; } else { ParserMemoryEntry entry; if (state.Memory.TryGetValue(key, out entry)) { state.RuntimeState.Runtime.ParseTrace.LinkNext(entry.Tag); if (entry.Tree == ParseTree.No) { state.RuntimeState.Runtime.ParseTrace.No(this, lexer.SourceFrom(start), "From memory"); } else { state.RuntimeState.Runtime.ParseTrace.Yes(this, lexer.SourceFrom(start), "From memory"); lexer.Position = entry.End; } return(entry.Tree); } } ConcretePattern oldRecursionExclude = state.RecursionExclude; if (RecursionBehaviour != RecursionBehaviour.Recursive) { if (state.RecursionExclude != null) { state.Excluded.Remove(state.RecursionExclude); } state.RecursionExclude = this; state.Excluded.Add(this); } RecursionBehaviour oldRecursionBehaviour = state.RecursionBehaviour; state.RecursionBehaviour = RecursionBehaviour; Precedence oldCurrentPrecedence = state.CurrentPrecedence; if (Precedence.Overwrites(state.CurrentPrecedence)) { state.CurrentPrecedence = Precedence; } bool oldPrecedenceCanEqualCurrent = state.PrecedenceCanEqualCurrent; state.PrecedenceCanEqualCurrent = RecursionBehaviour == RecursionBehaviour.Recursive; ParseTree tree = ParseGraph.Parse(lexer, state); state.CurrentPrecedence = oldCurrentPrecedence; state.PrecedenceCanEqualCurrent = oldPrecedenceCanEqualCurrent; state.RecursionBehaviour = oldRecursionBehaviour; state.RecursionExclude = oldRecursionExclude; state.SkipMemoryForLeftRecursion = oldSkipMemoryForLeftRecursion; if (RecursionBehaviour != RecursionBehaviour.Recursive) { if (oldRecursionExclude != null) { state.Excluded.Add(oldRecursionExclude); } state.Excluded.Remove(this); } if (tree != ParseTree.No) { lexer.Whitespace(state.RuntimeState); tree = Instantiate(lexer, state, start, tree); } object nextTag = new object(); state.RuntimeState.Runtime.ParseTrace.TagNext(nextTag); if (tree == ParseTree.No) { state.RuntimeState.Runtime.ParseTrace.No(this, lexer.SourceFrom(start)); } else { state.RuntimeState.Runtime.ParseTrace.Yes(this, lexer.SourceFrom(start)); if (RecursionBehaviour == RecursionBehaviour.LeftRecursive) { tree = LeftRecurse(lexer, state, start, tree); } } // TODO - can remove some other code if not remembering if (ShouldRemember) { state.Memory[key] = new ParserMemoryEntry(tree, lexer.Position, nextTag); } return(tree); }