Create an expression equivalent to a pattern.
514524
protected PExp patternToExp(PPattern pattern, IPogAssistantFactory af,
			UniqueNameGenerator unq)
	{
		PatternToExpVisitor visitor = new PatternToExpVisitor(unq, af);
		try
		{
			return pattern.apply(visitor);
		} catch (AnalysisException e)
		{
			return null;
		}
	}
763268
def emit(self, string, match, pattern, **_):
        """"""
        return grammar.Token(name=pattern.name, value=string,
                             start=match.start(), end=match.end())
210705
def create_pattern(cls, userdata):
        """"""
        empty = cls.create_empty(None)
        userdata_dict = cls.normalize(empty, userdata)
        return Userdata(userdata_dict)
1314001
def __expr_str(cls, expr, level):
        ''''''
        ident = ' ' * level * 4

        if isinstance(expr, tuple):
            return '{}{}'.format(ident, str(expr))

        if expr.etype[0] in ['pvar', 'constant']:
            return '{}Expression(etype={}, args={})'.format(ident, expr.etype, expr.args)

        if not isinstance(expr, Expression):
            return '{}{}'.format(ident, str(expr))

        args = list(cls.__expr_str(arg, level + 1) for arg in expr.args)
        args = '\n'.join(args)
        return '{}Expression(etype={}, args=\n{})'.format(ident, expr.etype, args)
893836
function compilePattern(pattern) {
  // pass estree syntax tree obj
  if (pattern && pattern.type) return pattern;

  if (typeof pattern !== 'string') {
    throw new Error('input pattern is neither a string nor an estree node.');
  }

  let exp = parser(pattern);

  if (exp.type !== 'Program' || !exp.body) {
    throw new Error(`Not a valid expression:  "${pattern}".`);
  }

  if (exp.body.length === 0) {
    throw new Error(`There is no statement in pattern "${pattern}".`);
  }

  if (exp.body.length > 1) {
    throw new Error(`Multiple statements is not supported "${pattern}".`);
  }

  exp = exp.body[0];
  // get the real expression underneath
  if (exp.type === 'ExpressionStatement') exp = exp.expression;
  return exp;
}
1160627
private void fromExpression(PatternDescrBuilder<?> pattern) throws RecognitionException {
        String expr = conditionalOrExpression();
        if (state.failed)
            return;

        if (state.backtracking == 0) {
            pattern.from().expression(expr);
            if (input.LA(1) != DRL6Lexer.EOF) {
                helper.emit(Location.LOCATION_LHS_BEGIN_OF_CONDITION);
            }
        }
    }
580259
function cloneRegexp(re) {
  const pattern = re.source;

  let flags = '';

  if (re.global) flags += 'g';
  if (re.multiline) flags += 'm';
  if (re.ignoreCase) flags += 'i';
  if (re.sticky) flags += 'y';
  if (re.unicode) flags += 'u';

  return new RegExp(pattern, flags);
}
1090484
@SuppressWarnings("unchecked")
    public static Expression<String> likeToRegex(Expression<String> expr, boolean matchStartAndEnd) {
        // TODO : this should take the escape character into account
        if (expr instanceof Constant<?>) {
            final String like = expr.toString();
            final StringBuilder rv = new StringBuilder(like.length() + 4);
            if (matchStartAndEnd && !like.startsWith("%")) {
                rv.append('^');
            }
            for (int i = 0; i < like.length(); i++) {
                char ch = like.charAt(i);
                if (ch == '.' || ch == '*' || ch == '?') {
                    rv.append('\\');
                } else if (ch == '%') {
                    rv.append(".*");
                    continue;
                } else if (ch == '_') {
                    rv.append('.');
                    continue;
                }
                rv.append(ch);
            }
            if (matchStartAndEnd && !like.endsWith("%")) {
                rv.append('$');
            }
            if (!like.equals(rv.toString())) {
                return ConstantImpl.create(rv.toString());
            }
        } else if (expr instanceof Operation<?>) {
            Operation<?> o = (Operation<?>) expr;
            if (o.getOperator() == Ops.CONCAT) {
                Expression<String> lhs = likeToRegex((Expression<String>) o.getArg(0), false);
                Expression<String> rhs = likeToRegex((Expression<String>) o.getArg(1), false);
                if (lhs != o.getArg(0) || rhs != o.getArg(1)) {
                    return operation(String.class, Ops.CONCAT, lhs, rhs);
                }
            }
        }
        return expr;
    }
1335467
def p_expression_unor(self, p):
        ''
        p[0] = Unor(p[2], lineno=p.lineno(1))
        p.set_lineno(0, p.lineno(1))
997932
def _parse_bracket_expression(pattern, start=0, no_escape=False):
    
    """
    i = start

    if pattern[i:i+len(_BE_OPEN)] != _BE_OPEN:
        raise ValueError(u'Expected {}'.format(repr(_BE_OPEN)))
    i += len(_BE_OPEN)

    # fnmatch builds on top of POSIX, but uses `!` while POSIX uses `^`
    if pattern[i:i+len(_BE_NON_MATCHING)] == _BE_NON_MATCHING:
        matching = False
        i += len(_BE_NON_MATCHING)
    elif pattern[i:i+len(_BE_NON_MATCHING2)] == _BE_NON_MATCHING2:
        matching = False
        i += len(_BE_NON_MATCHING2)
    else:
        matching = True

    # We iterate other the items twice, first we get the tokens and parse most of it except for
    # ranges. Then, we resolve ranges by joining collating elements separated by an empty range
    # marker

    # Items in this bracket expression
    items = []

    # First pass: tokenize
    while len(items) == 0 or pattern[i:i + len(_BE_CLOSE)] != _BE_CLOSE:
        if not no_escape and pattern[i:i+len(_ESCAPE)] == _ESCAPE:  # Literal escape \a
            i += len(_ESCAPE)
            if i >= len(pattern):
                raise ValueError(u'Invalid pattern, incomplete escape sequence')
            items.append(_create_be_collating_element(pattern[i:i + 1]))
            i += 1
        elif pattern[i:i+len(_BE_CS_OPEN)] == _BE_CS_OPEN:  # Collating symbol [.abc.]
            cs, cs_len = _parse_be_collating_symbol(pattern, i)
            items.append(_create_be_collating_element(cs))
            i += cs_len
        elif pattern[i:i+len(_BE_ECE_OPEN)] == _BE_ECE_OPEN:  # Equivalence class expression [=abc=]
            # Currently, equivalence classes are a synonym for collating symbols because we do not
            # support equivalence classes. The difference is that we have to prevent them from
            # ending ranges to eventually add support for equivalence classes in the future
            ec_repr, ece_len = _parse_be_equivalence_class_expression(pattern, i)
            items.append(_create_be_equivalence_class(ec_repr))
            i += ece_len
        elif pattern[i:i+len(_BE_CCE_OPEN)] == _BE_CCE_OPEN:  # Character class expression [:alpha:]
            cc_name, cce_len = _parse_be_character_class_expression(pattern, i)
            items.append(_create_be_character_class(cc_name))
            i += cce_len
        elif pattern[i:i + len(_BE_RANGE)] == _BE_RANGE:  # Range a-c
            items.append(_create_be_unmatched_range())
            i += len(_BE_RANGE)
        else:  # Single-character collating element
            items.append(_create_be_collating_element(pattern[i:i+1]))
            i += 1

        if i >= len(pattern):
            raise ValueError(u'InvalidPattern, end of bracket expression not found')
    i += len(_BE_CLOSE)

    # Second pass: resolve ranges
    items_with_ranges = []
    j = 0
    while j < len(items):
        item = items[j]
        if not _is_be_unmatched_range(item):
            items_with_ranges.append(item)
        else:
            # From here, the current item is an unmatched range, we try to get the previous and next
            # item if they are collating elements
            if j == 0:
                prev_elem = None
            else:
                prev_elem = items_with_ranges[-1]
                if not _is_be_collating_element(prev_elem):
                    prev_elem = None
            if j == len(items) - 1:
                next_elem = None
            else:
                next_elem = items[j + 1]
                # case [a--], [---] or [[.a.]--]
                if prev_elem is not None and _is_be_unmatched_range(next_elem):
                    next_elem = _create_be_collating_element(_BE_RANGE)
                elif not _is_be_collating_element(next_elem):
                    next_elem = None

            # Unmatched dash between two collating elements
            if prev_elem is not None and next_elem is not None:
                # Note that we allow ranges between multi-character collating elements
                range_start = _read_be_collating_element(prev_elem)
                range_end = _read_be_collating_element(next_elem)
                # Equivalent to .pop then .append
                items_with_ranges[-1] = _create_be_range(range_start, range_end)
                j += 1  # Skip the next item (corresponds to the end of the range)
            # Add the dash as a collating element
            else:
                items_with_ranges.append(_create_be_collating_element(_BE_RANGE))
                _create_be_collating_element(_BE_RANGE)
        j += 1

    return _create_bracket_expression(matching, items_with_ranges), i - start
102720
def compile_pattern(self, input, debug=False, with_tree=False):
        """"""
        tokens = tokenize_wrapper(input)
        try:
            root = self.driver.parse_tokens(tokens, debug=debug)
        except parse.ParseError as e:
            raise PatternSyntaxError(str(e))
        if with_tree:
            return self.compile_node(root), root
        else:
            return self.compile_node(root)
769636
def Expression(*args, **kwargs):
    
    # dispatch
    if not hasattr(args[0], '_Expression'):
        return BaseExpression(*args, *kwargs)
    else:
        return args[0]._Expression(*args, **kwargs)
1247293
def build_string(self, *pattern, **kwargs):
        
        set_defaults(self._string_defaults, kwargs)
        set_defaults(self._defaults, kwargs)
        return StringPattern(*pattern, **kwargs)
872017
def match(self, pattern):
        """"""

        m = pattern.match(self._string, self._index)
        if m:
            self._index = m.end()
        return m
887511
function builder(pattern) {
  var args = Array.prototype.splice.call(arguments, 0);

  if (isUndefined(pattern)) {
    throw {
      name: 'Error',
      message: 'Expected pattern to be defined',
      arguments: args
    };
  } else if (!isNumber(pattern) && !isString(pattern)) {
    throw {
      name: 'Error',
      message: 'Expected pattern to be a number or a string, but got ' +
        'something else',
      arguments: args
    };
  }

  var context = {};
  var last;
  var head;
  var current = context;
  if (isNumber(pattern) || (isString(pattern) && pattern.indexOf('.') === -1)) {
    current[pattern] = {};
    last = current;
    head = pattern;
  } else {
    var parts = pattern.split('.');
    while (parts.length) {
      head = parts.shift();
      current[head] = {};
      last = current;
      current = current[head];
    }
  }

  return function (value) {
    last[head] = value;
    return context;
  };
}
95268
public Operator createLikeOperator(Selector ar, String pattern, boolean escaped, char escape)
  {
  Object parsed = Pattern.parsePattern(pattern, escaped, escape);
  if (parsed == null)
    return null;
  else if (parsed == Pattern.matchMany)
    return createOperator(Selector.NOT, createOperator(Selector.ISNULL, ar));
  else if (parsed instanceof String)
    return createOperator(Selector.EQ, ar, createLiteral(parsed));
  else
    return new LikeOperatorImpl(Selector.LIKE, ar, (Pattern) parsed, pattern,
      escaped, escape);
  }
487282
def PATTERN(self):
        
        """
        self.update_mapping()
        return u" |\n".join([pattern_unformatted % (f.name, f._pattern) for f in iter(self)])