Пример #1
0
 def runTest(self):
     parser = pypeg2.Parser()
     r = parser.parse("hello, world", pypeg2.attr("some", pypeg2.Symbol))
     self.assertEqual(
         r,
         (
             ', world',
             pypeg2.attr.Class(name='some', thing=pypeg2.Symbol('hello'),
                 subtype=None)
         )
     )
Пример #2
0
class Function(List):
    grammar = attr('typing',
                   Type), blank, name(), '(', Parameters, ')', endl, block
Пример #3
0
class DispositionParm(str):
    """A parameter for the Disposition-Type header (RFC6266, Section 4.1)."""

    grammar = peg.attr('name', NoExtToken), '=', Value
Пример #4
0
class KeywordRule(LeafRule):
    grammar = attr('value', re.compile(r"[\w\d]+(\.[\w\d]+)*"))
Пример #5
0
class Main(UnaryRule):
    grammar = [
        (omit(_), attr('op', Query), omit(_)),
        attr('op', EmptyQueryRule),
    ]
Пример #6
0
class ImplicitAndQuery(UnaryRule):
    grammar = [
        attr('op', NotQuery),
        attr('op', ParenthesizedQuery),
        attr('op', SimpleQuery),
    ]
Пример #7
0
class SimpleQuery(UnaryRule):
    grammar = attr('op', [KeywordQuery, ValueQuery])
                   re.compile(r'\b(?!\d\d\d\w{0,3}|%s)\S+\b:' %
                              "|".join([x + ":"
                                        for x in SPIRES_KEYWORDS.keys()])))


class KeywordQuery(BinaryRule):
    pass


class EmptyQueryRule(LeafRule):
    grammar = attr('value', re.compile(r'\s*'))


KeywordQuery.grammar = [
    (
        attr('left', KeywordRule),
        omit(_, Literal(':'), _),
        # FIXME: This should be replaced with KeywordQuery to restore
        # intented functionality.
        # Also NestedKeywordsRule class should be removed from
        # this file, ./ast.py and ./walkers/pypeg_to_ast.py.
        attr('right', NestedKeywordsRule)
    ),
    (
        attr('left', KeywordRule),
        omit(_, Literal(':'), _),
        attr('right', Value)
    ),
    (
        attr('left', KeywordRule),
        omit(_, Literal(':'), _),
Пример #9
0
class SpiresKeywordQuery(BinaryRule):
    """Keyword queries with space separator (i.e. Spires style)."""
    grammar = attr('left', InspireKeyword), attr('right', Value)
Пример #10
0
class LessThanOp(UnaryRule):
    """Less than operator.

    Supports queries like author-count < 100 or date before 1984.
    """
    grammar = omit(re.compile(r"before|<", re.IGNORECASE)), attr('op', SimpleValue)
Пример #11
0
class GreaterThanOp(UnaryRule):
    """Greater than operator.

    Supports queries like author-count > 2000 or date after 10-2000.
    """
    grammar = omit(re.compile(r"after|>", re.IGNORECASE)), attr('op', SimpleValue)
Пример #12
0
class SimpleValueNegation(UnaryRule):
    """Negation accepting only SimpleValues."""
    grammar = omit(Not), attr('op', SimpleValue)
Пример #13
0
 class Whitespace(LeafRule):
     grammar = attr('value', whitespace)
Пример #14
0
class ParenthesizedQuery(UnaryRule):
    """Parenthesized query for denoting precedence."""
    grammar = omit(Literal('(')), attr('op', Statement), omit(Literal(')'))


class NestedKeywordQuery(BinaryRule):
    """Nested Keyword queries.

    E.g. citedby:author:hui and refersto:author:witten
    """
    pass


Expression.grammar = attr('op', [
    NotQuery,
    NestedKeywordQuery,
    ParenthesizedQuery,
    SimpleQuery,
])


NestedKeywordQuery.grammar = \
    attr('left', [
        # Most specific regex must be higher.
        re.compile(r'citedbyexcludingselfcites', re.IGNORECASE),
        re.compile(r'citedbyx', re.IGNORECASE),
        re.compile(r'citedby', re.IGNORECASE),
        re.compile(r'referstoexcludingselfcites', re.IGNORECASE),
        re.compile(r'referstox', re.IGNORECASE),
        re.compile(r'refersto', re.IGNORECASE),
    ]), \
    optional(omit(":")), \
Пример #15
0
        omit(re.compile(r"or", re.I)),
        [
            (omit(Whitespace), attr('op', SpiresSimpleQuery)),
            (omit(_), attr('op', SpiresParenthesizedQuery)),
                (omit(Whitespace), attr('op', SpiresValueQuery)),
        ]
    )


SpiresQuery.grammar = attr('children', (
    [
        SpiresParenthesizedQuery,
        SpiresSimpleQuery,
    ],
    maybe_some((
        omit(_),
        [
            SpiresNotQuery,
            SpiresAndQuery,
            SpiresOrQuery,
        ]
    )),
))


class NestableKeyword(LeafRule):
    grammar = attr('value', [
        re.compile('refersto', re.I),
        re.compile('citedby', re.I),
    ])

Пример #16
0
    body = None

class List(MExpression):
    head = MSymbol("List")

    grammar = (
        Literal("{"), optional(attr("body", csl(MExpression))), Literal("}")
    )


# Since MExpression is recursive, we need to define the class,
# then the grammar. Moreover, since it depends on List and other
# such things, we need to put it last.
MExpression.grammar = [
    (
        attr("head", MSymbol), Literal("["), optional(attr("body", csl(MExpression))), Literal("]")
    ),
    attr("head", MSymbol),
    List,
    atom
]


## TESTING ###########################################################

if __name__ == "__main__":
    print parse("ab`c", MExpression)
    print parse('12', MExpression)
    print parse('"a"', MExpression)
    print parse("List", MExpression)
    print parse("List[]", MExpression)
Пример #17
0
class NotQuery(UnaryRule):
    """Negation query."""
    grammar = omit(Not), attr('op', Expression)
Пример #18
0
class ParenthesizedQuery(UnaryRule):
    """Parenthesized query for denoting precedence."""
    grammar = omit(Literal('(')), attr('op', Statement), omit(Literal(')'))
Пример #19
0
class RelativeGroupArgument(IntNumMixin):
    grammar = ["group"], "=", peg.attr("num", re.compile(r"[+\-][1-4]"))
Пример #20
0
class ValueQuery(UnaryRule):
    grammar = attr('op', Value)


class Query(ListRule):
    pass


class KeywordQuery(BinaryRule):
    pass


KeywordQuery.grammar = [
    (
        attr('left', KeywordRule),
        omit(_, Literal(':'), _),
        attr('right', KeywordQuery)
    ),
    (
        attr('left', KeywordRule),
        omit(_, Literal(':'), _),
        attr('right', Value)
    ),
    (
        attr('left', KeywordRule),
        omit(_, Literal(':'), _),
        attr('right', Query)
    ),
]
Пример #21
0
class ParenthesizedQuery(UnaryRule):
    grammar = (
        omit(Literal('('), _),
        attr('op', Query),
        omit(_, Literal(')')),
    )
Пример #22
0
class DoubleQuotedString(LeafRule):
    grammar = Literal('"'), attr('value', re.compile(r'([^"]|\\.)*')), \
        Literal('"')
Пример #23
0
class EmptyQueryRule(LeafRule):
    grammar = attr('value', re.compile(r'\s*'))
Пример #24
0
class SlashQuotedString(LeafRule):
    grammar = Literal('/'), attr('value', re.compile(r"([^/]|\\.)*")), \
        Literal('/')
Пример #25
0
class Whitespace(LeafRule):
    grammar = attr('value', re.compile(r"\s+"))
Пример #26
0
class SimpleRangeValue(LeafRule):
    grammar = attr('value', re.compile(r"([^\s\)\(-]|-+[^\s\)\(>])+"))
Пример #27
0
class SingleQuotedString(LeafRule):
    grammar = Literal("'"), attr('value', re.compile(r"([^']|\\.)*")), \
        Literal("'")
Пример #28
0
class RangeValue(UnaryRule):
    grammar = attr('op', [DoubleQuotedString, SimpleRangeValue])
Пример #29
0
class Parameter:
    grammar = attr('typing', Type), blank, name()
Пример #30
0
class RangeOp(BinaryRule):
    grammar = (
        attr('left', RangeValue),
        Literal('->'),
        attr('right', RangeValue)
    )
Пример #31
0
class FromImport(object):
    grammar = "from", blank, attr("name", Package), blank, "import", \
              blank, attr("modules", Modules), endl
Пример #32
0
class NestableKeyword(LeafRule):
    grammar = attr('value', [
        re.compile('refersto', re.I),
        re.compile('citedby', re.I),
    ])
Пример #33
0
    AST node for a conjunction.
    """
    grammar = (attr('left', Term), blank, Keyword('and'), blank,
               attr('right', Expression))


class Disjunction(BinaryNode):
    """
    AST node for a disjunction.
    """
    grammar = (attr('left', Term), blank, Keyword('or'), blank,
               attr('right', Expression))


Term.grammar = attr('expression', [Grouping,
                                   Negation,
                                   Clause,
                                   Tautology])
Expression.grammar = attr('expression', [Conjunction,
                                         Disjunction,
                                         Term])


class Visitor(object):
    """
    Decorator for visitor methods on AST nodes.

        >>> class PrettyPrinter(object):
        ...     visitor = Visitor()
        ...
        ...     @visitor(Tautology)
        ...     def visit(self, node):
Пример #34
0
class Number(LeafRule):
    grammar = attr('value', re.compile(r'\d+'))
Пример #35
0

class ValueQuery(UnaryRule):
    grammar = attr("op", Value)


class Query(ListRule):
    pass


class KeywordQuery(BinaryRule):
    pass


KeywordQuery.grammar = [
    (attr("left", KeywordRule), omit(_, Literal(":"), _), attr("right", KeywordQuery)),
    (attr("left", KeywordRule), omit(_, Literal(":"), _), attr("right", Value)),
    (attr("left", KeywordRule), omit(_, Literal(":"), _), attr("right", Query)),
]


class SimpleQuery(UnaryRule):
    grammar = attr("op", [KeywordQuery, ValueQuery])


class ParenthesizedQuery(UnaryRule):
    grammar = (omit(Literal("("), _), attr("op", Query), omit(_, Literal(")")))


class NotQuery(UnaryRule):
    grammar = [
Пример #36
0
class ValueQuery(UnaryRule):
    grammar = attr('op', Value)
Пример #37
0
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.

"""
Data Access Module
"""
from __future__ import absolute_import, print_function, division

import re

from pypeg2 import word, attr, List, maybe_some, parse as peg_parse

from datacube.model import Range

FIELD_NAME = attr(u'field_name', word)

NUMBER = re.compile(r"[-+]?(\d*\.\d+|\d+\.\d*|\d+)")
# A limited string can be used without quotation marks.
LIMITED_STRING = re.compile(r"[a-zA-Z][\w\._-]*")
# Inside string quotation marks. Kept simple. We're not supporting escapes or much else yet...
STRING_CONTENTS = re.compile(r"[\w\s\._-]*")


class Expr(object):
    def query_repr(self, get_field):
        """
        Return this as a database expression.

        :type get_field: (str) -> datacube.index.fields.Field
        :rtype: datacube.index.fields.Expression
Пример #38
0
    def compose(self, parser: Any, grammar: Any = None, attr_of: str = None) -> str:
        """
        Return the Condition as string format

        :param parser: Parser instance
        :param grammar: Grammar
        :param attr_of: Attribute of...
        """
        if type(self.left) is Condition:
            left = "({0})".format(parser.compose(self.left, grammar=grammar, attr_of=attr_of))
        else:
            left = parser.compose(self.left, grammar=grammar, attr_of=attr_of)

        if getattr(self, 'op', None):

            if type(self.right) is Condition:
                right = "({0})".format(parser.compose(self.right, grammar=grammar, attr_of=attr_of))
            else:
                right = parser.compose(self.right, grammar=grammar, attr_of=attr_of)
            op = parser.compose(self.op, grammar=grammar, attr_of=attr_of)
            result = "{0} {1} {2}".format(left, op, right)
        else:
            result = left
        return result


Condition.grammar = contiguous(attr('left', [SIG, XHX, CSV, CLTV, ('(', Condition, ')')]),
                               maybe_some(whitespace, attr('op', Operator), whitespace,
                                          attr('right', [SIG, XHX, CSV, CLTV, ('(', Condition, ')')])))