Parses "if [condition] then [delta] elif [condition] then [delta] else [delta] end".
In contrast to most of the other parse methods, this assumes the initial token ('if')
has been consumed already.
966691
private Delta parseConditionalDelta() {
        Condition test = parseCondition();
        String then = _t.nextToken();
        if (!"then".equals(then)) {
            throw _t.syntaxError("Expected 'then' and instead saw '" + then + "'");
        }
        Delta delta = parseDelta();
        String next = _t.nextToken();
        if ("elif".equals(next)) {
            // The recursive call will consume the 'end' token.
            Delta otherwise = parseConditionalDelta();
            return Deltas.conditional(test, delta, otherwise);
        }
        Delta otherwise = Deltas.noop();
        if ("else".equals(next)) {
            otherwise = parseDelta();
            next = _t.nextToken();
        }
        if (!"end".equals(next)) {
            throw _t.syntaxError("Expected 'end' and instead saw '" + next + "'");
        }
        return Deltas.conditional(test, delta, otherwise);
    }
843570
private ParseTree parseReturnStatement() {
    SourcePosition start = getTreeStartLocation();
    eat(TokenType.RETURN);
    ParseTree expression = null;
    if (!peekImplicitSemiColon()) {
      expression = parseExpression();
    }
    eatPossibleImplicitSemiColon();
    return new ReturnStatementTree(getTreeLocation(start), expression);
  }
948986
private ParseTree parseTryStatement() {
    SourcePosition start = getTreeStartLocation();
    eat(TokenType.TRY);
    ParseTree body = parseBlock();
    ParseTree catchBlock = null;
    if (peek(TokenType.CATCH)) {
      catchBlock = parseCatch();
    }
    ParseTree finallyBlock = null;
    if (peek(TokenType.FINALLY)) {
      finallyBlock = parseFinallyBlock();
    }
    if (catchBlock == null && finallyBlock == null) {
      reportError("'catch' or 'finally' expected.");
    }
    return new TryStatementTree(getTreeLocation(start), body, catchBlock, finallyBlock);
  }
309808
def ifposition(parser, token):
    
    bits = list(token.split_contents())
    end_tag = 'end' + bits[0]

    nofallback = False
    if bits[-1] == 'nofallback':
        nofallback = True
        bits.pop()

    if len(bits) >= 4 and bits[-2] == 'for':
        category = template.Variable(bits.pop())
        pos_names = bits[1:-1]
    else:
        raise TemplateSyntaxError('Invalid syntax: {% ifposition POSITION_NAME ... for CATEGORY [nofallback] %}')

    nodelist_true = parser.parse(('else', end_tag))
    token = parser.next_token()

    if token.contents == 'else':
        nodelist_false = parser.parse((end_tag,))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()

    return IfPositionNode(category, pos_names, nofallback, nodelist_true, nodelist_false)
392271
final public void Compare() throws ParseException {
    Concatenation();
    label_10:
    while (true) {
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case GT0:
      case GT1:
      case LT0:
      case LT1:
      case GE0:
      case GE1:
      case LE0:
      case LE1:
        ;
        break;
      default:
        jj_la1[18] = jj_gen;
        break label_10;
      }
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case LT0:
      case LT1:
        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
        case LT0:
          jj_consume_token(LT0);
          break;
        case LT1:
          jj_consume_token(LT1);
          break;
        default:
          jj_la1[19] = jj_gen;
          jj_consume_token(-1);
          throw new ParseException();
        }
                         AstLessThan jjtn001 = new AstLessThan(JJTLESSTHAN);
                         boolean jjtc001 = true;
                         jjtree.openNodeScope(jjtn001);
        try {
          Concatenation();
        } catch (Throwable jjte001) {
                         if (jjtc001) {
                           jjtree.clearNodeScope(jjtn001);
                           jjtc001 = false;
                         } else {
                           jjtree.popNode();
                         }
                         if (jjte001 instanceof RuntimeException) {
                           {if (true) throw (RuntimeException)jjte001;}
                         }
                         if (jjte001 instanceof ParseException) {
                           {if (true) throw (ParseException)jjte001;}
                         }
                         {if (true) throw (Error)jjte001;}
        } finally {
                         if (jjtc001) {
                           jjtree.closeNodeScope(jjtn001,  2);
                         }
        }
        break;
      case GT0:
      case GT1:
        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
        case GT0:
          jj_consume_token(GT0);
          break;
        case GT1:
          jj_consume_token(GT1);
          break;
        default:
          jj_la1[20] = jj_gen;
          jj_consume_token(-1);
          throw new ParseException();
        }
                         AstGreaterThan jjtn002 = new AstGreaterThan(JJTGREATERTHAN);
                         boolean jjtc002 = true;
                         jjtree.openNodeScope(jjtn002);
        try {
          Concatenation();
        } catch (Throwable jjte002) {
                         if (jjtc002) {
                           jjtree.clearNodeScope(jjtn002);
                           jjtc002 = false;
                         } else {
                           jjtree.popNode();
                         }
                         if (jjte002 instanceof RuntimeException) {
                           {if (true) throw (RuntimeException)jjte002;}
                         }
                         if (jjte002 instanceof ParseException) {
                           {if (true) throw (ParseException)jjte002;}
                         }
                         {if (true) throw (Error)jjte002;}
        } finally {
                         if (jjtc002) {
                           jjtree.closeNodeScope(jjtn002,  2);
                         }
        }
        break;
      case LE0:
      case LE1:
        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
        case LE0:
          jj_consume_token(LE0);
          break;
        case LE1:
          jj_consume_token(LE1);
          break;
        default:
          jj_la1[21] = jj_gen;
          jj_consume_token(-1);
          throw new ParseException();
        }
                         AstLessThanEqual jjtn003 = new AstLessThanEqual(JJTLESSTHANEQUAL);
                         boolean jjtc003 = true;
                         jjtree.openNodeScope(jjtn003);
        try {
          Concatenation();
        } catch (Throwable jjte003) {
                         if (jjtc003) {
                           jjtree.clearNodeScope(jjtn003);
                           jjtc003 = false;
                         } else {
                           jjtree.popNode();
                         }
                         if (jjte003 instanceof RuntimeException) {
                           {if (true) throw (RuntimeException)jjte003;}
                         }
                         if (jjte003 instanceof ParseException) {
                           {if (true) throw (ParseException)jjte003;}
                         }
                         {if (true) throw (Error)jjte003;}
        } finally {
                         if (jjtc003) {
                           jjtree.closeNodeScope(jjtn003,  2);
                         }
        }
        break;
      case GE0:
      case GE1:
        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
        case GE0:
          jj_consume_token(GE0);
          break;
        case GE1:
          jj_consume_token(GE1);
          break;
        default:
          jj_la1[22] = jj_gen;
          jj_consume_token(-1);
          throw new ParseException();
        }
                         AstGreaterThanEqual jjtn004 = new AstGreaterThanEqual(JJTGREATERTHANEQUAL);
                         boolean jjtc004 = true;
                         jjtree.openNodeScope(jjtn004);
        try {
          Concatenation();
        } catch (Throwable jjte004) {
                         if (jjtc004) {
                           jjtree.clearNodeScope(jjtn004);
                           jjtc004 = false;
                         } else {
                           jjtree.popNode();
                         }
                         if (jjte004 instanceof RuntimeException) {
                           {if (true) throw (RuntimeException)jjte004;}
                         }
                         if (jjte004 instanceof ParseException) {
                           {if (true) throw (ParseException)jjte004;}
                         }
                         {if (true) throw (Error)jjte004;}
        } finally {
                         if (jjtc004) {
                           jjtree.closeNodeScope(jjtn004,  2);
                         }
        }
        break;
      default:
        jj_la1[23] = jj_gen;
        jj_consume_token(-1);
        throw new ParseException();
      }
    }
  }
319795
def parse(tokens):
    ''''''
    args = []
    kwargs = {}
    last = None
    for token in tokens:
        if token.startswith('--'):
            # If this is a keyword flag, but we've already got one that we've
            # parsed, then we're going to interpret it as a bool
            if last:
                kwargs[last] = True
            # See if it is the --foo=5 style
            last, _, value = token.strip('-').partition('=')
            if value:
                kwargs[last] = value
                last = None
        elif last != None:
            kwargs[last] = token
            last = None
        else:
            args.append(token)

    # If there's a dangling last, set that bool
    if last:
        kwargs[last] = True

    return args, kwargs
82199
def parse_filter_expression(expression, tokens)   #:nodoc:
    # The number of tokens will be either 3 (for 1 expression)
    # or 7 (for 2  expressions).
    #
    if (tokens.size == 7)
      conditional = tokens[3]
      if conditional =~ /^(and|&&)$/
        conditional = 0
      elsif conditional =~ /^(or|\|\|)$/
        conditional = 1
      else
        raise "Token '#{conditional}' is not a valid conditional " +
        "in filter expression '#{expression}'"
      end
      expression_1 = parse_filter_tokens(expression, tokens[0..2])
      expression_2 = parse_filter_tokens(expression, tokens[4..6])
      [expression_1, conditional, expression_2].flatten
    else
      parse_filter_tokens(expression, tokens)
    end
  end
1289436
private boolean parseFunction() {
        if (!(curToken instanceof Id) || isELReserved(curToken.toString())) {
            return false;
        }
        String s1 = null; // Function prefix
        String s2 = curToken.toString(); // Function name
        int mark = getIndex();
        if (hasNext()) {
            Token t = nextToken();
            if (t.toChar() == ':') {
                if (hasNext()) {
                    Token t2 = nextToken();
                    if (t2 instanceof Id) {
                        s1 = s2;
                        s2 = t2.toString();
                        if (hasNext()) {
                            t = nextToken();
                        }
                    }
                }
            }
            if (t.toChar() == '(') {
                ELexpr.add(new ELNode.Function(s1, s2));
                return true;
            }
        }
        setIndex(mark);
        return false;
    }
146340
def parse_condition(
    cond, selectable, aggregated=False, default_aggregation='sum'
):
    """"""
    if cond is None:
        return None

    else:
        if 'and' in cond:
            conditions = [
                parse_condition(
                    c, selectable, aggregated, default_aggregation
                ) for c in cond['and']
            ]
            return and_(*conditions)
        elif 'or' in cond:
            conditions = [
                parse_condition(
                    c, selectable, aggregated, default_aggregation
                ) for c in cond['or']
            ]
            return or_(*conditions)
        elif 'field' not in cond:
            raise BadIngredient('field must be defined in condition')
        field = parse_field(
            cond['field'],
            selectable,
            aggregated=aggregated,
            default_aggregation=default_aggregation
        )
        if 'in' in cond:
            value = cond['in']
            if isinstance(value, dict):
                raise BadIngredient('value for in must be a list')
            condition_expression = getattr(field, 'in_')(tuple(value))
        elif 'gt' in cond:
            value = cond['gt']
            if isinstance(value, (list, dict)):
                raise BadIngredient('conditional value must be a scalar')
            condition_expression = getattr(field, '__gt__')(value)
        elif 'gte' in cond:
            value = cond['gte']
            if isinstance(value, (list, dict)):
                raise BadIngredient('conditional value must be a scalar')
            condition_expression = getattr(field, '__ge__')(value)
        elif 'lt' in cond:
            value = cond['lt']
            if isinstance(value, (list, dict)):
                raise BadIngredient('conditional value must be a scalar')
            condition_expression = getattr(field, '__lt__')(value)
        elif 'lte' in cond:
            value = cond['lte']
            if isinstance(value, (list, dict)):
                raise BadIngredient('conditional value must be a scalar')
            condition_expression = getattr(field, '__le__')(value)
        elif 'eq' in cond:
            value = cond['eq']
            if isinstance(value, (list, dict)):
                raise BadIngredient('conditional value must be a scalar')
            condition_expression = getattr(field, '__eq__')(value)
        elif 'ne' in cond:
            value = cond['ne']
            if isinstance(value, (list, dict)):
                raise BadIngredient('conditional value must be a scalar')
            condition_expression = getattr(field, '__ne__')(value)
        else:
            raise BadIngredient('Bad condition')

        return condition_expression
337210
private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) {
        StringBuilder retval = new StringBuilder("Unable to parse code syntax. Encountered:");
        Token tok = currentToken;
        while (null != (tok = tok.next))
            retval.append(" ").append(add_escapes(tok.image));

        retval.append(" at line ")
            .append(currentToken.next.beginLine)
            .append(", column ")
            .append(currentToken.next.beginColumn);
        if (null != sourceFile)
            retval.append(" in: ").append(sourceFile);

        if (Interpreter.DEBUG.get() && expectedTokenSequences.length != 0) {
            retval.append(System.getProperty("line.separator", "\n")).append("Exppected");
            if (expectedTokenSequences.length > 1)
                retval.append(" one of");
            retval.append(": ");
            for (int i = 0; i < expectedTokenSequences.length; i++)
                for (int j = 0; j < expectedTokenSequences[i].length; j++)
                    retval.append(tokenImage[expectedTokenSequences[i][j]]
                            .replace('"', ' ').trim()).append(' ');
        }

        return retval.toString();
    }


    /**
     * Used to convert raw characters to their escaped version
     * when these raw version cannot be used as part of an ASCII
     * string literal.
     */
    static String add_escapes(String str) {
        StringBuilder retval = new StringBuilder();
        char ch;
        for (int i = 0; i < str.length(); i++) {
            switch (str.charAt(i)) {
                case '\b':
                    retval.append("\\b");
                    continue;
                case '\t':
                    retval.append("\\t");
                    continue;
                case '\n':
                    retval.append("\\n");
                    continue;
                case '\f':
                    retval.append("\\f");
                    continue;
                case '\r':
                    retval.append("\\r");
                    continue;
                case '\"':
                    retval.append("\\\"");
                    continue;
                case '\'':
                    retval.append("\\\'");
                    continue;
                case '\\':
                    retval.append("\\\\");
                    continue;
                default:
                    if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
                        String s = "0000" + Integer.toString(ch, 16);
                        retval.append("\\u" + s.substring(s.length() - 4, s.length()));
                    } else {
                        retval.append(ch);
                    }
                    continue;
            }
        }
        return retval.toString();
    }


    @Override
    public int getErrorLineNumber() {
        return currentToken.next.beginLine;
    }

    @Override
    public String getErrorText() {
        return this.getMessage();
    }

    public String getMessage() {
        return ParseException.initialise(currentToken, expectedTokenSequences, tokenImage);
    }
    public String getMessage(boolean debug) {
        return this.getMessage();
    }
    public String toString() {
        return this.getMessage();
    }
}
924411
def p_statement_if_then_endif(p):
    
    cond_ = p[1]
    stat_ = p[2]
    endif_ = p[3]
    p[0] = make_sentence('IF', cond_, make_block(stat_, endif_), lineno=p.lineno(1))
1351593
protected void parseElse() {
        Node parent = peek();
        if (!(parent instanceof IfNode)) {
            return;
        }
        IfNode ifNode = (IfNode) pop();
        ElseNode elseNode = new ElseNode();
        ifNode.setElseNode(elseNode);
        push(elseNode);
        tokenizer.skipWhitespace();
    }
242107
protected void parseElse(final int length) {
		Node parent = peek();
		if (!(parent instanceof IfNode)) {
			return;
		}
		IfNode ifNode = (IfNode) pop();
		ElseNode elseNode = new ElseNode(Math.max(this.position - 2, 0), length);
		this.position = this.tokenizer.getPosition();
		ifNode.setElseNode(elseNode);
		push(elseNode);
		tokenizer.skipWhitespace();
	}
150778
def parse_tokens(self, tokens, debug=False):
        """"""
        # XXX Move the prefix computation into a wrapper around tokenize.
        p = parse.Parser(self.grammar, self.convert)
        p.setup()
        lineno = 1
        column = 0
        type = value = start = end = line_text = None
        prefix = u""
        for quintuple in tokens:
            type, value, start, end, line_text = quintuple
            if start != (lineno, column):
                assert (lineno, column) <= start, ((lineno, column), start)
                s_lineno, s_column = start
                if lineno < s_lineno:
                    prefix += "\n" * (s_lineno - lineno)
                    lineno = s_lineno
                    column = 0
                if column < s_column:
                    prefix += line_text[column:s_column]
                    column = s_column
            if type in (tokenize.COMMENT, tokenize.NL):
                prefix += value
                lineno, column = end
                if value.endswith("\n"):
                    lineno += 1
                    column = 0
                continue
            if type == token.OP:
                type = grammar.opmap[value]
            if debug:
                self.logger.debug("%s %r (prefix=%r)",
                                  token.tok_name[type], value, prefix)
            if p.addtoken(type, value, (prefix, start)):
                if debug:
                    self.logger.debug("Stop.")
                break
            prefix = ""
            lineno, column = end
            if value.endswith("\n"):
                lineno += 1
                column = 0
        else:
            # We never broke out -- EOF is too soon (how can this happen???)
            raise parse.ParseError("incomplete input",
                                   type, value, (prefix, start))
        return p.rootnode
1201258
private void parse(String text, int start, int end)
   {
      int closing = getClosingParenthesisPosition(text, start);
      if (closing == -1 || closing > end)
      {
         throw new IllegalStateException("Error in parenthesis hierarchy");
      }
      if (!text.startsWith("(0||"))
      {
         throw new IllegalStateException("Not a valid record");
      }

      int valueStart = getNextOpeningParenthesisPosition(text, start);
      int valueStop = getClosingParenthesisPosition(text, valueStart);
      int dictStart = getNextOpeningParenthesisPosition(text, valueStop);
      int dictStop = getClosingParenthesisPosition(text, dictStart);
      parse(text, start + 4, valueStart, valueStop, dictStart, dictStop);
   }
1169186
private Filter<Object> parseCondition(CharSequenceScanner scanner) {

    int index = scanner.getCurrentIndex();
    Filter<Object> condition;
    if (scanner.expect(CONDITION_VAR)) {
      // variable choice
      String symbol = scanner.readWhile(FILTER_COMPARATOR);
      CompareOperator comparator = CompareOperator.fromValue(symbol);
      if (comparator == null) {
        throw new IllegalArgumentException(symbol);
      }
      Object comparatorArgument = parseComparatorArgument(scanner);
      condition = new Condition(comparator, comparatorArgument);
    } else if (scanner.expect(CONDITION_ELSE, false)) {
      condition = FILTER_ELSE;
    } else {
      throw new IllegalArgumentException(scanner.substring(index, scanner.getCurrentIndex()));
    }
    if (!scanner.expect(CONDITION_END)) {
      throw new IllegalArgumentException(scanner.substring(index, scanner.getCurrentIndex()));
    }
    return condition;
  }
246296
def parse_rule(input = @tokens)
      input = TokenScanner.new(input) unless input.is_a?(TokenScanner)

      while input.peek && input.peek[:node] == :whitespace
        input.consume
      end

      if input.peek.nil?
        # Syntax error.
        return create_node(:error, :value => 'empty')
      elsif input.peek[:node] == :at_keyword
        rule = consume_at_rule(input)
      else
        rule = consume_qualified_rule(input)
      end

      while input.peek && input.peek[:node] == :whitespace
        input.consume
      end

      if input.peek.nil?
        rule
      else
        # Syntax error.
        create_node(:error, :value => 'extra-input')
      end
    end