Convert a factored expression to a literal, and a list of constraints.
19326
def _tseitin(ex, auxvarname, auxvars=None):
    
    if isinstance(ex, Literal):
        return ex, list()
    else:
        if auxvars is None:
            auxvars = list()

        lits = list()
        constraints = list()
        for x in ex.xs:
            lit, subcons = _tseitin(x, auxvarname, auxvars)
            lits.append(lit)
            constraints.extend(subcons)

        auxvarindex = len(auxvars)
        auxvar = exprvar(auxvarname, auxvarindex)
        auxvars.append(auxvar)

        f = ASTOPS[ex.ASTOP](*lits)
        constraints.append((auxvar, f))
        return auxvar, constraints
218996
def expand_brackets(s):
    """"""
    s = ''.join(s.split())
    while True:
        start = s.find('(')
        if start == -1:
            break
        count = 1 # Number of hanging open brackets
        p = start + 1
        while p < len(s):
            if s[p] == '(':
                count += 1
            if s[p] == ')':
                count -= 1
            if not count:
                break
            p += 1
        if count:
            raise ValueError("Unbalanced parenthesis in '{0}'.".format(s))
        if start == 0 or s[start - 1] != '*':
            s = s[0:start] + s[start + 1:p] + s[p + 1:]
        else:
            m = BRACKET_RE.search(s)
            if m:
                factor = int(m.group('factor'))
                matchstart = m.start('factor')
                s = s[0:matchstart] + (factor - 1) * (s[start + 1:p] + ',') + s[start + 1:p] + s[p + 1:]
            else:
                raise ValueError("Failed to parse '{0}'.".format(s))
    return s
770987
def expression_list_to_conjunction(expression_list):
    """"""
    if not isinstance(expression_list, list):
        raise AssertionError(u'Expected `list`, Received {}.'.format(expression_list))

    if len(expression_list) == 0:
        return TrueLiteral

    if not isinstance(expression_list[0], Expression):
        raise AssertionError(u'Non-Expression object {} found in expression_list'
                             .format(expression_list[0]))
    if len(expression_list) == 1:
        return expression_list[0]
    else:
        return BinaryComposition(u'&&',
                                 expression_list_to_conjunction(expression_list[1:]),
                                 expression_list[0])
14233
def add_constraints(constrs)
      GLPK.glp_add_rows(@ptr, constrs.length)

      # Store each constraint and initialize a matrix used to hold
      # the coefficients of each value in the constraint matrix
      #
      # * ia - row (constraint) index
      # * ja - column (variable) index
      # * ar - constraint coefficient
      constrs.each do |constr|
        store_constraint constr
        constr.expression.terms.each do |var, coeff|
          @ia << constr.index
          @ja << var.index
          @ar << coeff
        end
      end

      ia_buffer = build_pointer_array @ia, :int
      ja_buffer = build_pointer_array @ja, :int
      ar_buffer = build_pointer_array @ar, :double

      GLPK.glp_load_matrix(@ptr, @ar.length - 1, ia_buffer, ja_buffer,
                           ar_buffer)

      @constraints.concat constrs
    end
587977
def parse_declaration_expressn_tupleliteral(self, values, es):
        
        es = es + '('
        for ast in values:
            es = es + self.parse_declaration_expressn(ast, es='') + ', '
        if es.endswith(', '):
            es = es[:-2]
        return es + ')'
858526
def parse(expression):
    
    result = []
    current = ""
    for i in expression:
        if i.isdigit() or i == '.':
            current += i
        else:
            if len(current) > 0:
                result.append(current)
                current = ""
            if i in __operators__ or i in __parenthesis__:
                result.append(i)
            else:
                raise Exception("invalid syntax " + i)

    if len(current) > 0:
        result.append(current)
    return result
64187
def get_implicit_constraints(self,relations):
        ''' '''

        constraints = []
        for relation in [r for r in relations if not r.is_negated()]  :
            const_dict = relation.get_constants()
            for constant in const_dict:
                for position in const_dict[constant]:
                    constraints.append( \
                        relation.get_name() + '.' + self.mapPositionToColumnName(relation,position) + ' = ' + str(constant) \
                    )
        return constraints
1335326
def _construct_regex(cls, fmt):
        """"""
        return re.compile(fmt.format(**vars(cls)), flags=re.U)
433757
def build_constraint_matrix(constrs)
      cbeg = []
      cind = []
      cval = []
      constrs.each.map do |constr|
        cbeg << cind.length
        constr.expression.terms.each do |var, coeff|
          cind << var.index
          cval << coeff
        end
      end

      [cbeg, cind, cval]
    end
778813
def constraint_matches(self, c, m):
        
        if isinstance(m, tuple):
            d = {}
            if isinstance(c, Operator) and c._op_name == m[0]:
                for c1, m1 in zip(c._args, m[1:]):
                    r = self.constraint_matches(c1, m1)
                    if r is False:
                        return r
                    d.update(r)
                return d
            return False
        return m.match(c)
687378
def p_regex_literal(self, p):
        """"""
        p[0] = self.asttypes.Regex(p[1])
        p[0].setpos(p)
1184323
private Formula constructClause(final LinkedHashSet<Literal> literals) {
    if (literals.isEmpty())
      return this.falsum();
    if (literals.size() == 1)
      return literals.iterator().next();
    Map<LinkedHashSet<? extends Formula>, Or> opOrMap = this.orsN;
    switch (literals.size()) {
      case 2:
        opOrMap = this.ors2;
        break;
      case 3:
        opOrMap = this.ors3;
        break;
      case 4:
        opOrMap = this.ors4;
        break;
      default:
        break;
    }
    Or tempOr = opOrMap.get(literals);
    if (tempOr != null)
      return tempOr;
    tempOr = new Or(literals, this, true);
    opOrMap.put(literals, tempOr);
    return tempOr;
  }
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
1037722
def _formulas(lexer, varname, fmt, nvars):
    """"""
    types = {IntegerToken, LPAREN} | _SAT_TOKS[fmt]
    tok = lexer.peek_token()
    if any(isinstance(tok, t) for t in types):
        first = _sat_formula(lexer, varname, fmt, nvars)
        rest = _formulas(lexer, varname, fmt, nvars)
        return (first, ) + rest
    # null
    else:
        return tuple()
1104502
def _expressions_from_rules(self, rule_syntax, custom_rules):
        
        # Hard-code enough of the rules to parse the grammar that describes the
        # grammar description language, to bootstrap:
        comment = Regex(r'#[^\r\n]*', name='comment')
        meaninglessness = OneOf(Regex(r'\s+'), comment, name='meaninglessness')
        _ = ZeroOrMore(meaninglessness, name='_')
        equals = Sequence(Literal('='), _, name='equals')
        label = Sequence(Regex(r'[a-zA-Z_][a-zA-Z_0-9]*'), _, name='label')
        reference = Sequence(label, Not(equals), name='reference')
        quantifier = Sequence(Regex(r'[*+?]'), _, name='quantifier')
        # This pattern supports empty literals. TODO: A problem?
        spaceless_literal = Regex(r'u?r?"[^"\\]*(?:\\.[^"\\]*)*"',
                                  ignore_case=True,
                                  dot_all=True,
                                  name='spaceless_literal')
        literal = Sequence(spaceless_literal, _, name='literal')
        regex = Sequence(Literal('~'),
                         literal,
                         Regex('[ilmsuxa]*', ignore_case=True),
                         _,
                         name='regex')
        atom = OneOf(reference, literal, regex, name='atom')
        quantified = Sequence(atom, quantifier, name='quantified')

        term = OneOf(quantified, atom, name='term')
        not_term = Sequence(Literal('!'), term, _, name='not_term')
        term.members = (not_term,) + term.members

        sequence = Sequence(term, OneOrMore(term), name='sequence')
        or_term = Sequence(Literal('/'), _, term, name='or_term')
        ored = Sequence(term, OneOrMore(or_term), name='ored')
        expression = OneOf(ored, sequence, term, name='expression')
        rule = Sequence(label, equals, expression, name='rule')
        rules = Sequence(_, OneOrMore(rule), name='rules')

        # Use those hard-coded rules to parse the (more extensive) rule syntax.
        # (For example, unless I start using parentheses in the rule language
        # definition itself, I should never have to hard-code expressions for
        # those above.)

        rule_tree = rules.parse(rule_syntax)

        # Turn the parse tree into a map of expressions:
        return RuleVisitor().visit(rule_tree)
702870
def p_and_p_expression(tok):
        """"""
        if len(tok) == 4:
            tok[0] = LogicalBinOpRule(tok[2], tok[1], tok[3])
        else:
            tok[0] = tok[1]
235644
def _clauses(lexer, varname, nvars):
    """"""
    tok = next(lexer)
    toktype = type(tok)
    if toktype is OP_not or toktype is IntegerToken:
        lexer.unpop_token(tok)
        first = _clause(lexer, varname, nvars)
        rest = _clauses(lexer, varname, nvars)
        return (first, ) + rest
    # null
    else:
        lexer.unpop_token(tok)
        return tuple()