Parses the given pattern and returns the antlr parse tree.

        :param pattern_str: The STIX pattern
        :return: The parse tree
        :raises ParseException: If there is a parse error
511965
def __do_parse(self, pattern_str):
        
        in_ = antlr4.InputStream(pattern_str)
        lexer = STIXPatternLexer(in_)
        lexer.removeErrorListeners()  # remove the default "console" listener
        token_stream = antlr4.CommonTokenStream(lexer)

        parser = STIXPatternParser(token_stream)
        parser.removeErrorListeners()  # remove the default "console" listener
        error_listener = ParserErrorListener()
        parser.addErrorListener(error_listener)

        # I found no public API for this...
        # The default error handler tries to keep parsing, and I don't
        # think that's appropriate here.  (These error handlers are only for
        # handling the built-in RecognitionException errors.)
        parser._errHandler = antlr4.BailErrorStrategy()

        # To improve error messages, replace "<INVALID>" in the literal
        # names with symbolic names.  This is a hack, but seemed like
        # the simplest workaround.
        for i, lit_name in enumerate(parser.literalNames):
            if lit_name == u"<INVALID>":
                parser.literalNames[i] = parser.symbolicNames[i]

        # parser.setTrace(True)

        try:
            tree = parser.pattern()
            # print(tree.toStringTree(recog=parser))

            return tree
        except antlr4.error.Errors.ParseCancellationException as e:
            # The cancellation exception wraps the real RecognitionException
            # which caused the parser to bail.
            real_exc = e.args[0]

            # I want to bail when the first error is hit.  But I also want
            # a decent error message.  When an error is encountered in
            # Parser.match(), the BailErrorStrategy produces the
            # ParseCancellationException.  It is not a subclass of
            # RecognitionException, so none of the 'except' clauses which would
            # normally report an error are invoked.
            #
            # Error message creation is buried in the ErrorStrategy, and I can
            # (ab)use the API to get a message: register an error listener with
            # the parser, force an error report, then get the message out of the
            # listener.  Error listener registration is above; now we force its
            # invocation.  Wish this could be cleaner...
            parser._errHandler.reportError(parser, real_exc)

            # should probably chain exceptions if we can...
            # Should I report the cancellation or recognition exception as the
            # cause...?
            six.raise_from(ParseException(error_listener.error_message),
                           real_exc)
79538
public HString findPattern(@NonNull Pattern regex) {
      Matcher m = matcher(regex);
      if (m.find()) {
         return union(substring(m.start(), m.end()).tokens());
      }
      return Fragments.empty(document());
   }
173045
def parse(self, lines):
    

    if isinstance(lines, str):
      lines = lines.split('\n')
    sub = _re.sub
    for line in lines:
      if line.endswith('\n'):
        line = line[:-1]
      line = line.lstrip()
      if not line.startswith('#'):
        invert = False
        if line.startswith('!'):
          line = line[1:]
          invert = True
        while line.endswith(' ') and line[-2:] != '\ ':
          line = line[:-1]
        line = sub(r'\\([!# ])', r'\1', line)
        if '/' in line and not line.startswith('/'):
          # Patterns with a slash can only be matched absolute.
          line = '/' + line
        self.patterns.append(Pattern(line, invert))
173905
def parse_regex(regex_tokens):
    
    # We add a closing brace because that represents the final pop of the stack.
    tokens = [')'] + regex_tokens[::-1]

    def wrap(lst):
        """ Turn list into sequence when it contains several items. """
        if len(lst) == 1:
            return lst[0]
        else:
            return Sequence(lst)

    def _parse():
        or_list = []
        result = []

        def wrapped_result():
            if or_list == []:
                return wrap(result)
            else:
                or_list.append(result)
                return Any([wrap(i) for i in or_list])

        while tokens:
            t = tokens.pop()

            if t.startswith('(?P<'):
                variable = Variable(_parse(), varname=t[4:-1])
                result.append(variable)

            elif t in ('*', '*?'):
                greedy = (t == '*')
                result[-1] = Repeat(result[-1], greedy=greedy)

            elif t in ('+', '+?'):
                greedy = (t == '+')
                result[-1] = Repeat(result[-1], min_repeat=1, greedy=greedy)

            elif t in ('?', '??'):
                if result == []:
                    raise Exception('Nothing to repeat.' + repr(tokens))
                else:
                    greedy = (t == '?')
                    result[-1] = Repeat(result[-1], min_repeat=0, max_repeat=1, greedy=greedy)

            elif t == '|':
                or_list.append(result)
                result = []

            elif t in ('(', '(?:'):
                result.append(_parse())

            elif t == '(?!':
                result.append(Lookahead(_parse(), negative=True))

            elif t == '(?=':
                result.append(Lookahead(_parse(), negative=False))

            elif t == ')':
                return wrapped_result()

            elif t.startswith('#'):
                pass

            elif t.startswith('{'):
                # TODO: implement!
                raise Exception('{}-style repitition not yet supported' % t)

            elif t.startswith('(?'):
                raise Exception('%r not supported' % t)

            elif t.isspace():
                pass
            else:
                result.append(Regex(t))

        raise Exception("Expecting ')' token")

    result = _parse()

    if len(tokens) != 0:
        raise Exception("Unmatched parantheses.")
    else:
        return result
353028
private static Type doParse(String str) throws Exception {
        Class<?> token = PRIMITIVES.get(str);
        if (token != null) {
            return token;
        }
        int first = str.indexOf('<');
        if (first < 0) {
            return StringConvert.loadType(str);
        }
        int last = str.lastIndexOf('>');
        String baseStr = str.substring(0, first);
        Class<?> base = StringConvert.loadType(baseStr);
        String argsStr = str.substring(first + 1, last);
        List<String> splitArgs = split(argsStr);
        List<Type> types = new ArrayList<Type>();
        for (String splitArg : splitArgs) {
            Type argType;
            if (splitArg.startsWith(EXTENDS)) {
                String remainder = splitArg.substring(EXTENDS.length());
                argType = wildExtendsType(doParse(remainder));
            } else if (splitArg.startsWith(SUPER)) {
                String remainder = splitArg.substring(SUPER.length());
                argType = wildSuperType(doParse(remainder));
            } else if (splitArg.equals("?")) {
                argType = wildExtendsType(Object.class);
            } else if (splitArg.endsWith("[]")) {
                String componentStr = splitArg.substring(0, splitArg.length() - 2);
                Class<?> componentCls = StringConvert.loadType(componentStr);
                argType = Array.newInstance(componentCls, 0).getClass();
            } else if (splitArg.startsWith("[L") && splitArg.endsWith(";")) {
                String componentStr = splitArg.substring(2, splitArg.length() - 1);
                Class<?> componentCls = StringConvert.loadType(componentStr);
                argType = Array.newInstance(componentCls, 0).getClass();
            } else {
                argType = doParse(splitArg);
            }
            types.add(argType);
        }
        return newParameterizedType(base, types.toArray(new Type[types.size()]));
    }
1010792
public static Parser<Void> string(String str) {
    return Patterns.string(str).toScanner(str);
  }
569445
def glob(self, pattern):
        
        pattern = self._flavour.casefold(pattern)
        drv, root, pattern_parts = self._flavour.parse_parts((pattern,))
        if drv or root:
            raise NotImplementedError("Non-relative patterns are unsupported")
        selector = _make_selector(tuple(pattern_parts))
        for p in selector.select_from(self):
            yield p
57896
def parse(str)
      if str.nil? || str == ""
        raise ParserError.new("Empty input",0,"")
      end

      s = StringScanner.new str
      @tokens = []

      until s.eos?
        s.skip(/\s+/) ? nil :
          s.scan(/\A[-+]?[0-9]*\.[0-9]+(e[-+]?[0-9]+)?/i) ? (@tokens << [:FLOAT, s.matched]) :
          s.scan(/\A[-+]?(0|[1-9]\d*)/)      ? (@tokens << [:INTEGER, s.matched]) :
          s.scan(/\A\.(?=\s)/)               ? (@tokens << ['.', '.']) :
          s.scan(/\A[a-z\-.\/_:*<>+=$#][a-z\-.\/_:$*<>+=0-9]*/i) ? (@tokens << [:SYMBOL, s.matched]) :
          s.scan(/\A"(([^\\"]|\\.)*)"/)        ? (@tokens << [:STRING, _unescape_string(s.matched.slice(1...-1))])  :
          s.scan(/\A./)                      ? (a = s.matched; @tokens << [a, a]) :
          (raise ParserError.new("Scanner error",s.pos,s.peek(5)))
      end
      @tokens.push [false, 'END']

      return do_parse.map do |i|
        normalize(i)
      end
    end
837137
def string(s):
    ''''''
    @Parser
    def string_parser(text, index=0):
        slen, tlen = len(s), len(text)
        if text[index:index + slen] == s:
            return Value.success(index + slen, s)
        else:
            matched = 0
            while matched < slen and index + matched < tlen and text[index + matched] == s[matched]:
                matched = matched + 1
            return Value.failure(index + matched, s)
    return string_parser
1031970
def string(self, *pattern, **kwargs):
        
        self.pattern(self.build_string(*pattern, **kwargs))
        return self
76821
def _parse_known_pattern(self, pattern: str) -> List[str]:
        
        if pattern.endswith(os.path.sep):
            patterns = [
                filename
                for filename in os.listdir(pattern)
                if os.path.isdir(os.path.join(pattern, filename))
            ]
        else:
            patterns = [pattern]

        return patterns
822940
def main():
    
    parser = argparse.ArgumentParser(description='Validate STIX Patterns.')
    parser.add_argument('-f', '--file',
                        help="Specify this arg to read patterns from a file.",
                        type=argparse.FileType("r"))
    args = parser.parse_args()

    pass_count = fail_count = 0

    # I tried using a generator (where each iteration would run raw_input()),
    # but raw_input()'s behavior seems to change when called from within a
    # generator: I only get one line, then the generator completes!  I don't
    # know why behavior changes...
    import functools
    if args.file:
        nextpattern = args.file.readline
    else:
        nextpattern = functools.partial(six.moves.input, "Enter a pattern to validate: ")

    try:
        while True:
            pattern = nextpattern()
            if not pattern:
                break
            tests_passed, err_strings = validate(pattern, True)

            if tests_passed:
                print("\nPASS: %s" % pattern)
                pass_count += 1

            else:
                for err in err_strings:
                    print(err, '\n')
                fail_count += 1
    except (EOFError, KeyboardInterrupt):
        pass
    finally:
        if args.file:
            args.file.close()

    print("\nPASSED:", pass_count, " patterns")
    print("FAILED:", fail_count, " patterns")
1136750
def pattern_to_str(pattern):
    
    if isinstance(pattern, str):
        return repr(pattern)
    else:
        return repr(pattern.pattern) if pattern else None
1257674
def parse(self):
        
        #print("Parsing: %s"%self.parse_string)
        self.tokenize()
        if self.debug: print("Tokens found: %s"%self.token_list)
        
        try:
            parse_tree = self.parse2()
        except Exception as e:
                raise e
        return parse_tree
1084223
def parse(timestring):
    
    for parser in _PARSERS:
        match = parser['pattern'].match(timestring)
        if match:
            groups = match.groups()
            ints = tuple(map(int, groups))
            time = parser['factory'](ints)
            return time

    raise TimeError('Unsupported time format {}'.format(timestring))
394280
def parse_pattern(format_string, env, wrapper=lambda x, y: y):
    

    formatter = Formatter()
    fields = [x[1] for x in formatter.parse(format_string) if x[1] is not None]

    prepared_env = {}

    # Create a prepared environment with only used fields, all as list:
    for field in fields:
        # Search for a movie attribute for each alternative field separated
        # by a pipe sign:
        for field_alt in (x.strip() for x in field.split('|')):
            # Handle default values (enclosed by quotes):
            if field_alt[0] in '\'"' and field_alt[-1] in '\'"':
                field_values = field_alt[1:-1]
            else:
                field_values = env.get(field_alt)
            if field_values is not None:
                break
        else:
            field_values = []
        if not isinstance(field_values, list):
            field_values = [field_values]
        prepared_env[field] = wrapper(field_alt, field_values)

    return prepared_env
604472
def parse(self):
        
        if self.parse_string is not None and self._parse is None:
            self._parse = Tree.parse(self._parse_string)
        return self._parse