コード例 #1
0
    def parse_string(self, string):
        '''Populate a new object from a string.
        
        Parsing is hard, so we're going to call out to the pyparsing
        library here.  I hope you installed it!
        '''
        from pyparsing import Suppress, Regex, quotedString, restOfLine, Keyword, nestedExpr, Group, OneOrMore, Word, Literal, alphanums, removeQuotes, replaceWith
        gr_eq = Literal('=')
        gr_stripped_string = quotedString.copy().setParseAction(removeQuotes)
        gr_opt_quoted_string = gr_stripped_string | restOfLine
        gr_name = Keyword('name', caseless=True) + gr_eq + gr_opt_quoted_string
        gr_name.setParseAction(lambda x, y=self: y._set_name(x[2]))
        gr_yn = Keyword('yes', caseless=True).setParseAction(
            replaceWith('1')) | Keyword('no', caseless=True).setParseAction(
                replaceWith('0'))
        gr_phrase = Group(
            OneOrMore(gr_stripped_string | Word(alphanums)) + gr_eq +
            gr_opt_quoted_string)

        def np(words, fn=gr_opt_quoted_string, action=print):
            p = Keyword(words[0], caseless=True)
            for w in words[1:]:
                p = p | Keyword(w, caseless=True)
            p = p + gr_eq + fn
            p.setParseAction(action)
            return p

        gr_ifsc = np(PList('Ignore File Set Changes'),
                     gr_yn,
                     action=self._parse_setter(IGNORECHANGES))
        gr_evss = np(PList('Enable VSS'),
                     gr_yn,
                     action=self._parse_setter(VSSENABLED))

        gr_i_option = Group(
            Keyword(OPTIONS, caseless=True) +
            nestedExpr('{', '}', Regex('[^\}]+', re.MULTILINE)))
        gr_e_option = gr_i_option.copy()
        gr_i_file = gr_phrase.copy()
        gr_e_file = gr_phrase.copy()

        gr_inc = Keyword('include', caseless=True) + nestedExpr(
            '{', '}', OneOrMore(gr_i_option | gr_i_file))
        gr_inc.addParseAction(self._parse_add_entry)
        gr_exc = Keyword('exclude', caseless=True) + nestedExpr(
            '{', '}', OneOrMore(gr_e_option | gr_e_file))
        gr_exc.addParseAction(self._parse_add_entry)

        gr_res = OneOrMore(gr_name | gr_inc | gr_exc | gr_ifsc | gr_evss)
        result = gr_res.parseString(string, parseAll=True)
        return 'Fileset: ' + self[NAME]
コード例 #2
0
ファイル: tokens.py プロジェクト: oerc0122/QASMParser
    class _Block():
        """ Class to set up blocks such as if, for, etc. """
        def __init__(self, name, detParser, version="OPENQASM 2.0"):
            global blocks
            global _reservedKeys
            self.operation = name
            self.parser = Keyword(name)("keyword") + detParser

            self.version = parse_version(version)
            self.parser.addParseAction(
                lambda s, l, t: _set_version(t, self.version))

            _reservedKeys.append(name)
            blocks[name] = self
コード例 #3
0
ファイル: tokens.py プロジェクト: oerc0122/QASMParser
    class _Routine():
        """ Class to set up quantum gates, circuits, etc. """
        def __init__(self,
                     name,
                     pargs=False,
                     spargs=False,
                     gargs=False,
                     qargs=False,
                     returnables=False,
                     prefixes=None,
                     version="OPENQASM 2.0"):
            global blocks
            global _reservedKeys
            if name in qops or name in cops:
                raise IOError(dupTokenWarning.format("Routine", name))
            self.operation = name

            self.parser = Keyword(name)("keyword") + validName("gateName")

            if prefixes:
                localPrefixParser = Each(map(Optional, map(
                    Keyword, prefixes))).addParseAction(prefix_setter)
            else:
                localPrefixParser = prefixParser
            self.parser = localPrefixParser + self.parser

            # Handle different args
            req = []
            if pargs:
                req.append(Optional(pargParser)("pargs"))
            if spargs:
                req.append(Optional(spargParser)("spargs"))
            if gargs:
                req.append(Optional(gargParser)("gargs"))
            self.parser = self.parser + Each(req)
            if qargs:
                self.parser = self.parser + qargParser("qargs")
            if returnables:
                self.parser = self.parser + Optional(returnParser)

            self.version = parse_version(version)
            self.parser.addParseAction(
                lambda s, l, t: _set_version(t, self.version))

            _reservedKeys.append(name)
            blocks[name] = self
コード例 #4
0
    def parse_string(self, string):
        '''Populate a new object from a string.
        
        Parsing is hard, so we're going to call out to the pyparsing
        library here.  I hope you installed it!
        '''
        from pyparsing import Suppress, Regex, quotedString, restOfLine, Keyword, nestedExpr, Group, OneOrMore, Word, Literal, alphanums, removeQuotes, replaceWith
        gr_eq = Literal('=')
        gr_stripped_string = quotedString.copy().setParseAction( removeQuotes )
        gr_opt_quoted_string = gr_stripped_string | restOfLine
        gr_name = Keyword('name', caseless=True) + gr_eq + gr_opt_quoted_string
        gr_name.setParseAction(lambda x, y=self: y._set_name(x[2]))
        gr_yn = Keyword('yes', caseless=True).setParseAction(replaceWith('1')) | Keyword('no', caseless=True).setParseAction(replaceWith('0'))
        gr_phrase = Group(OneOrMore(gr_stripped_string | Word(alphanums)) + gr_eq + gr_opt_quoted_string)

        def np(words, fn = gr_opt_quoted_string, action=print):
            p = Keyword(words[0], caseless=True)
            for w in words[1:]:
                p = p | Keyword(w, caseless=True)
            p = p + gr_eq + fn
            p.setParseAction(action)
            return p
        
        gr_ifsc = np(PList('Ignore File Set Changes'), gr_yn, action=self._parse_setter(IGNORECHANGES))
        gr_evss = np(PList('Enable VSS'), gr_yn, action=self._parse_setter(VSSENABLED))

        gr_i_option = Group(Keyword(OPTIONS, caseless=True) + nestedExpr('{','}', Regex('[^\}]+', re.MULTILINE)))
        gr_e_option = gr_i_option.copy()
        gr_i_file = gr_phrase.copy()
        gr_e_file = gr_phrase.copy()

        gr_inc = Keyword('include', caseless=True) + nestedExpr('{','}', OneOrMore(gr_i_option | gr_i_file))
        gr_inc.addParseAction(self._parse_add_entry)
        gr_exc = Keyword('exclude', caseless=True) + nestedExpr('{','}', OneOrMore(gr_e_option | gr_e_file))
        gr_exc.addParseAction(self._parse_add_entry)

        gr_res = OneOrMore(gr_name | gr_inc | gr_exc | gr_ifsc | gr_evss)
        result = gr_res.parseString(string, parseAll=True)
        return 'Fileset: ' + self[NAME]
コード例 #5
0
ファイル: pcbnew_parser.py プロジェクト: croahs/cpm43
HexStringTok = Word(pyparsing.hexnums)
HexStringTok.addParseAction(lambda toks: int(toks[0], base=16))

UnquotedStringTok = ZeroOrMore(
    White()).suppress() + CharsNotIn("()\"\'" + " \r\n")
UnquotedStringTok.addParseAction(lambda toks: "".join(toks).strip())

QuotedStringTok = Group(dblQuotedString() ^ sglQuotedString())
QuotedStringTok.addParseAction(lambda toks: "".join(toks[0]).strip('"'))

AnystringTok = QuotedStringTok ^ UnquotedStringTok
LeftParenTok = Literal('(').suppress()
RightParenTok = Literal(')').suppress()

BoolTrueTok = Keyword("yes", caseless=True) | Keyword("true", caseless=True)
BoolTrueTok.addParseAction(lambda: True)
BoolFalseTok = Keyword("no", caseless=True) | Keyword("false", caseless=True)
BoolFalseTok.addParseAction(lambda: False)
BooleanTok = BoolTrueTok | BoolFalseTok


def _paren_stmt(keyword, *values, store=True):
    """
    Create a parser for a parenthesized list with an initial keyword.
    """
    # result  = LeftParenTok + Keyword(keyword, caseless=True).suppress()
    result = LeftParenTok + Keyword(keyword, caseless=True).suppress()
    for value in values:
        result += value
    result += RightParenTok
    if store:
コード例 #6
0
def field_cb(tok):
    if tok[0] == "array":
        return ArrayField(tok[0], tok[1])
    return Field(tok[0], tok[1])


def all_cb(tok):
    return AllSub()


def contents_cb(tok):
    return Contents(tok[0], tok[1])


field_element = field_with_type.addParseAction(
    field_cb) ^ contents.addParseAction(contents_cb) ^ all_sub.addParseAction(
        all_cb)

identifier = package_or_class

field_list = Suppress("[") + delimitedList(field_element) + Suppress("]")
ag_grammar = Optional(identifier)("base_id") + Optional(field_list)("fields")

site_identifier = Word(nums).addParseAction(lambda tok: int(tok[0]))

sync_node = (Literal("{s").addParseAction(lambda tok: "SYNC") +
             site_identifier + Suppress("}"))
transition_node = (Suppress("{") +
                   Literal("t").addParseAction(lambda tok: "TR") +
                   site_identifier + Suppress(",") + site_identifier +
                   Suppress("}"))