``nested_expression`` is the result of parsing a logical form in Lisp format.
        We process it recursively and return a string in the format that NLTK's ``LogicParser``
        would understand.
15074
def _process_nested_expression(self, nested_expression) -> str:
        
        expression_is_list = isinstance(nested_expression, list)
        expression_size = len(nested_expression)
        if expression_is_list and expression_size == 1 and isinstance(nested_expression[0], list):
            return self._process_nested_expression(nested_expression[0])
        elements_are_leaves = [isinstance(element, str) for element in nested_expression]
        if all(elements_are_leaves):
            mapped_names = [self._map_name(name) for name in nested_expression]
        else:
            mapped_names = []
            for element, is_leaf in zip(nested_expression, elements_are_leaves):
                if is_leaf:
                    mapped_names.append(self._map_name(element))
                else:
                    mapped_names.append(self._process_nested_expression(element))
        if mapped_names[0] == "\\":
            # This means the predicate is lambda. NLTK wants the variable name to not be within parantheses.
            # Adding parentheses after the variable.
            arguments = [mapped_names[1]] + [f"({name})" for name in mapped_names[2:]]
        else:
            arguments = [f"({name})" for name in mapped_names[1:]]
        return f'({mapped_names[0]} {" ".join(arguments)})'
939376
private ParseTree parseShiftExpression() {
    SourcePosition start = getTreeStartLocation();
    ParseTree left = parseAdditiveExpression();
    while (peekShiftOperator()) {
      Token operator = nextToken();
      ParseTree right = parseAdditiveExpression();
      left = new BinaryOperatorTree(getTreeLocation(start), left, operator, right);
    }
    return left;
  }
1039556
def p_l_expression(self, p):
        '''     
        '''
        _LOGGER.debug("l -> expresion")

        l = TypedList( [ p[1] ] )
        p[0] = l
828112
function processParentheses(tokenizer, scope) {
  if (tokenizer.token.match(types.CLOSE_PARENTHESES)) {
    throw new SyntaxError('Unexpected end of expression');
  }

  if (tokenizer.token.match(types.OPEN_PARENTHESES)) {
    const node = processLogicalOr(tokenizer.skipToken(), scope);

    if (!tokenizer.token.match(types.CLOSE_PARENTHESES)) {
      throw new SyntaxError('Unexpected end of expression');
    }

    tokenizer.skipToken();
    return node;
  }

  throw new SyntaxError('Unexpected end of expression');
}
148479
def _parse_expression(s):
    """"""

    # Converters for opeartor clauses
    operators = {
        'and': And,
        'or': Or,
        None: lambda *args: args[0]
    }

    # Pairing of end group symbols with start group symbols
    group_pairs = {
        ')': '(',
        ']': '['
    }

    scanner = re.compile(r'''
        (\s+) |              # space
        (\(|\[) |            # group_start
        (\)|\]) |            # group_end
        ((?:or|and)\b) |     # operator
        ([^\s\(\)\[\]]+) |   # variable
        (\Z) |               # end
        (.)                  # error
    ''', re.DOTALL | re.VERBOSE | re.UNICODE | re.IGNORECASE)

    # Parsed using two states and a stack of open clauses
    # At state 0 (not expect_operator): Expect variable, or parenthesis group
    #  start.
    # At state 1 (expect_operator): Expect operator, parenthesis group end, or
    #  end.
    expect_operator = False
    clause_stack = []
    current_clause = []
    clause_operator = None
    clause_symbol = None

    def close():
        prev_op, prev_symbol, prev_clause = clause_stack.pop()
        prev_clause.append(operators[clause_operator](*current_clause))
        return prev_op, prev_symbol, prev_clause

    for match in re.finditer(scanner, s):
        (space, group_start, group_end, operator, variable, end,
            error) = match.groups()

        if error is not None:
            raise ParseError('Invalid token in expression string: {}'.format(
                repr(match.group(0))), span=(match.start(), match.end()))
        elif space is not None:
            continue
        elif expect_operator and operator is not None:
            operator = operator.lower()
            if operator == 'and' and clause_operator != 'and':
                prev_term = current_clause.pop()
                clause_stack.append(
                    (clause_operator, clause_symbol, current_clause))
                current_clause = [prev_term]
            elif operator == 'or' and clause_operator == 'and':
                clause_operator, clause_symbol, current_clause = close()
            clause_operator = operator
            expect_operator = False
        elif expect_operator and group_end is not None:
            if clause_operator == 'and':
                clause_operator, clause_symbol, current_clause = close()
            if len(clause_stack) == 0:
                raise ParseError(
                    'Unbalanced parenthesis group in expression',
                    span=(match.start(), match.end()))
            if group_pairs[group_end] != clause_symbol:
                raise ParseError(
                    'Group started with {} ended with {}'.format(
                        clause_symbol, group_end),
                    span=(match.start(), match.end()))
            clause_operator, clause_symbol, current_clause = close()
        elif expect_operator and end is not None:
            if clause_operator == 'and':
                clause_operator, clause_symbol, current_clause = close()
        elif not expect_operator and variable is not None:
            current_clause.append(Variable(variable))
            expect_operator = True
        elif not expect_operator and group_start is not None:
            clause_stack.append(
                (clause_operator, clause_symbol, current_clause))
            current_clause = []
            clause_operator = None
            clause_symbol = group_start
        else:
            raise ParseError(
                'Invalid token in expression string: {!r}'.format(
                    match.group(0)),
                span=(match.start(), match.end()))

    if len(clause_stack) > 0:
        raise ParseError('Unbalanced parenthesis group in expression')

    expr = operators[clause_operator](*current_clause)
    return expr
254061
function parseArgumentList() {
                    var token, expr, args = [];

                    while (true) {
                        expr = parseExpression();
                        if (typeof expr === 'undefined') {
                            break;
                        }
                        args.push(expr);
                        token = lexer.peek();
                        if (!matchOp(token, ',')) {
                            break;
                        }
                        lexer.next();
                    }

                    return args;
                }
707803
def expressionToAST(ex):
    
    return ASTNode(ex.astType, ex.astKind, ex.value,
                   [expressionToAST(c) for c in ex.children])
60452
public final JavaParser.parExpression_return parExpression() throws RecognitionException {
		JavaParser.parExpression_return retval = new JavaParser.parExpression_return();
		retval.start = input.LT(1);
		int parExpression_StartIndex = input.index();

		try {
			if ( state.backtracking>0 && alreadyParsedRule(input, 104) ) { return retval; }

			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1103:5: ( '(' expression ')' )
			// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1103:7: '(' expression ')'
			{
			match(input,36,FOLLOW_36_in_parExpression4794); if (state.failed) return retval;
			pushFollow(FOLLOW_expression_in_parExpression4796);
			expression();
			state._fsp--;
			if (state.failed) return retval;
			match(input,37,FOLLOW_37_in_parExpression4798); if (state.failed) return retval;
			}

			retval.stop = input.LT(-1);

		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
		}
		finally {
			// do for sure before leaving
			if ( state.backtracking>0 ) { memoize(input, 104, parExpression_StartIndex); }

		}
		return retval;
	}
828433
function _expression()
    {
        // If it's a string return a string node
        if (preg_match("/^\"[^\"]{0,255}\"$/", $this->_current_token)) {
            $result = $this->_createTree($this->_current_token, '', '');
            $this->_advance();
            return $result;
        } elseif ($this->_current_token == SPREADSHEET_EXCEL_WRITER_SUB) {
            // catch "-" Term
            $this->_advance();
            $result2 = $this->_expression();
            $result = $this->_createTree('ptgUminus', $result2, '');
            return $result;
        }
        $result = $this->_term();
        if (PEAR::isError($result)) {
            return $result;
        }
        while (($this->_current_token == SPREADSHEET_EXCEL_WRITER_ADD) or
               ($this->_current_token == SPREADSHEET_EXCEL_WRITER_SUB)) {
        /**/
            if ($this->_current_token == SPREADSHEET_EXCEL_WRITER_ADD) {
                $this->_advance();
                $result2 = $this->_term();
                if (PEAR::isError($result2)) {
                    return $result2;
                }
                $result = $this->_createTree('ptgAdd', $result, $result2);
            } else {
                $this->_advance();
                $result2 = $this->_term();
                if (PEAR::isError($result2)) {
                    return $result2;
                }
                $result = $this->_createTree('ptgSub', $result, $result2);
            }
        }
        return $result;
    }
1175153
function groupNestedPredicates(_nestedPredicates) {
    let maxDepth = 0;
    const nestedPredicateObj = {};
    const nestedPredicateParts = _.map(_nestedPredicates, (predicateArr) => {
      const predicate = predicateArr[0];
      const retVal = predicate.split('.');
      nestedPredicateObj[predicate] = predicateArr[1];
      retVal.length > maxDepth && (maxDepth = retVal.length);
      return retVal;
    });
    const groups = {};

    for (let i = 0; i < maxDepth; i++) {
      groups[i] = _.groupBy(nestedPredicateParts, (predicateParts) => {
        let retval = '';
        for (let j = 0; j < i + 1; j++) {
          retval += (predicateParts[j] ? `${predicateParts[j]}.` : '');
        }
        return retval.substr(0, retval.length - 1);
      });
    }

    const completed = {};
    const levels = {};
    const paths = {};

    // Simplifies the grouping
    for (let i = maxDepth - 1; i >= 0; i--) {
      _.each(groups[i], (values, key) => {
        _.each(values, (value) => {
          const strKey = value.join('.');
          if (!completed[strKey] && values.length > 1) {
            (!levels[i] && (levels[i] = []));
            levels[i].push(strKey);
            (completed[strKey] = true);
            paths[i] = key;
          }
          if (!completed[strKey] && i < 1) {
            (!levels[i] && (levels[i] = []));
            levels[i].push(strKey);
            (completed[strKey] = true);
            paths[i] = key;
          }
        });
      });
    }

    return { groups: levels, paths, nestedPredicateObj };
  }
1373589
function parseMultiplicative() {
                    var token, left, right, r;

                    left = parseExponentiation();
                    token = lexer.peek();
                    if (matchOp(token, '*') || matchOp(token, '/')) {
                        token = lexer.next();

                        right = parseMultiplicative();

                        // Multiplication and division is left associative:
                        // a/b/c should be (a/b)/c and not a/(b/c)
                        if (right.subtype === 'naryOperator' || right.subtype === 'binaryOperator') {
                            r = right;
                            while (r.content[0].subtype === 'naryOperator' || r.content[0].subtype === 'binaryOperator') {
                                r = r.content[0];
                            }

                            r.content[0] = new MathLib.Expression({
                                subtype: token.value === '*' ? 'naryOperator' : 'binaryOperator',
                                content: [left, r.content[0]],
                                value: token.value,
                                name: token.value === '*' ? 'times' : 'divide'
                            });
                            return right;
                        } else {
                            return new MathLib.Expression({
                                subtype: token.value === '*' ? 'naryOperator' : 'binaryOperator',
                                value: token.value,
                                name: token.value === '*' ? 'times' : 'divide',
                                content: [left, right]
                            });
                        }
                    }
                    return left;
                }
87066
def parse_argument_list(self):
        
        # Try to parse a subexpression in a subparser.
        expressions = []

        while self.pos < len(self.string):
            subparser = Parser(self.string[self.pos:], in_argument=True)
            subparser.parse_expression()

            # Extract and advance past the parsed expression.
            expressions.append(Expression(subparser.parts))
            self.pos += subparser.pos

            if self.pos >= len(self.string) or \
               self.string[self.pos] == GROUP_CLOSE:
                # Argument list terminated by EOF or closing brace.
                break

            # Only other way to terminate an expression is with ,.
            # Continue to the next argument.
            assert self.string[self.pos] == ARG_SEP
            self.pos += 1

        return expressions
572721
function parseUnaryExpression() {
        var token, expr;

        if (match('++') || match('--')) {
            token = lex();
            expr = parseUnaryExpression();
            // 11.4.4, 11.4.5
            if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
                throwError({}, Messages.StrictLHSPrefix);
            }
            expr = {
                type: Syntax.UpdateExpression,
                operator: token.value,
                argument: expr,
                prefix: true
            };
            return expr;
        }

        if (match('+') || match('-') || match('~') || match('!')) {
            expr = {
                type: Syntax.UnaryExpression,
                operator: lex().value,
                argument: parseUnaryExpression()
            };
            return expr;
        }

        if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
            expr = {
                type: Syntax.UnaryExpression,
                operator: lex().value,
                argument: parseUnaryExpression()
            };
            if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
                throwError({}, Messages.StrictDelete);
            }
            return expr;
        }

        return parsePostfixExpression();
    }
1049584
def _parse_string_to_nested_lists(self, value):
        
        if not re.match(r'\[.*\]', value.strip()):
            if '[' in value or ']' in value or ',' in value:
                raise Exception('Missing outer brace')
            elif len(value.strip()) == 0:
                raise Exception('Missing value')
            else:
                terms = value.split(',')
                terms = [term.strip() for term in terms]
                if len(terms) == 1:
                    return terms[0]
                else:
                    return terms

        # remove outer braces
        value = value[1:-1]
        terms = []
        depth = 0
        leftmost = 0
        first_open_brace = None
        break_on_commas = False
        for i in range(len(value)):
            if value[i] == ',' and depth == 0:
                terms.append(
                    self._parse_string_to_nested_lists(value[leftmost:i]))
                leftmost = i+1
            if value[i] == '[':
                if first_open_brace is None:
                    first_open_brace = i
                depth += 1
            if value[i] == ']':
                depth -= 1
                if depth < 0:
                    raise Exception('Unbalanced close brace')
            i += i
        if depth > 0:
            raise Exception('Expected "]"')
        terms.append(
            self._parse_string_to_nested_lists(value[leftmost:len(value)]))
        return terms
1067407
def __recursive_parser(self, onlysymbol, data, production, showerrors = False):
        
        LOG.debug("__recursive_parser: Begin ")
        if not data:
            return []
        from pydsl.grammar.symbol import TerminalSymbol, NullSymbol, NonTerminalSymbol
        if isinstance(onlysymbol, TerminalSymbol):
            LOG.debug("Iteration: terminalsymbol")
            return self._reduce_terminal(onlysymbol,data[0], showerrors)
        elif isinstance(onlysymbol, NullSymbol):
            return [ParseTree(0, 0, onlysymbol, "")]
        elif isinstance(onlysymbol, NonTerminalSymbol):
            validstack = []
            invalidstack = []
            for alternative in self._productionset.getProductionsBySide(onlysymbol): #Alternative
                alternativetree = PositionResultList()
                alternativeinvalidstack = []
                for symbol in alternative.rightside: # Symbol
                    symbol_success = False
                    for totalpos in alternativetree.right_limit_list(): # Right limit
                        if totalpos >= len(data):
                            continue
                        thisresult =  self.__recursive_parser(symbol, data[totalpos:], alternative, showerrors)
                        if not (thisresult and all(thisresult)):
                            alternativeinvalidstack += [x for x in thisresult if not x]
                            continue
                        symbol_success = True
                        for x in thisresult:
                            x.shift(totalpos)
                            success = alternativetree.append(x.left, x.right, x)
                            if not success:
                                #TODO: Add as an error to the tree or to another place
                                LOG.debug("Discarded symbol :" + str(symbol) + " position:" + str(totalpos))
                            else:
                                LOG.debug("Added symbol :" + str(symbol) + " position:" + str(totalpos))
                    if not symbol_success:
                        LOG.debug("Symbol doesn't work" + str(symbol))
                        break #Try next alternative
                else: # Alternative success (no break happened)
                    invalidstack += alternativeinvalidstack
                for x in alternativetree.valid_sequences():
                    validstack.append(x)
            result = []

            LOG.debug("iteration result collection finished:" + str(validstack))
            for alternative in self._productionset.getProductionsBySide(onlysymbol):
                nullcount = alternative.rightside.count(NullSymbol())
                for results in validstack:
                    nnullresults = 0
                    left = results[0]['left']
                    right = results[-1]['right']
                    nnullresults = len([x for x in results if x['content'].symbol == NullSymbol()])
                    if len(results) - nnullresults != len(alternative.rightside) - nullcount:
                        LOG.debug("Discarded: incorrect number of non null symbols")
                        continue
                    if right > len(data):
                        LOG.debug("Discarded: length mismatch")
                        continue
                    for x in range(min(len(alternative.rightside), len(results))):
                        if results[x]['content'] != alternative.rightside[x]:
                            LOG.debug("Discarded: rule doesn't match partial result")
                            continue
                    childlist = [x['content'] for x in results]
                    allvalid = all([x.valid for x in childlist])
                    if allvalid:
                        newresult = ParseTree(0, right - left, onlysymbol,
                                data[left:right], childlist = childlist)
                        newresult.valid = True
                        result.append(newresult)
            if showerrors and not result:
                erroresult = ParseTree(0,len(data), onlysymbol , data, valid = False)
                for invalid in invalidstack:
                    if invalid.content in production.rightside:
                        erroresult.append(invalid)
                return [erroresult]
            return result
        raise Exception("Unknown symbol:" + str(onlysymbol))
392688
def execute(self, lf_raw: str) -> int:
        
        # Remove "a:" prefixes from attributes (hack)
        logical_form = re.sub(r"\(a:", r"(", lf_raw)
        parse = semparse_util.lisp_to_nested_expression(logical_form)
        if len(parse) < 2:
            return -1
        if parse[0] == 'infer':
            args = [self._exec_and(arg) for arg in parse[1:]]
            if None in args:
                return -1
            return self._exec_infer(*args)
        return -1
516600
def eval_expr(expr_str, show_tokens=False, showast=False,
              showgrammar=False, compile_mode='exec'):
    

    parser_debug = {'rules': False, 'transition': False,
                    'reduce': showgrammar,
                    'errorstack': True, 'context': True }
    parsed = parse_expr(expr_str, show_tokens=show_tokens,
                        parser_debug=parser_debug)
    if showast:
        print(parsed)

    assert parsed == 'expr', 'Should have parsed grammar start'

    evaluator = ExprEvaluator()

    # What we've been waiting for: Generate source from AST!
    return evaluator.traverse(parsed)