How to use the pyleri.Grammar function in pyleri

To help you get started, we’ve selected a few pyleri examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github transceptor-technology / pyleri / test / test_pyleri.py View on Github external
def test_compile_error(self):
        with self.assertRaises(ReKeywordsChangedError):
            class _G1(Grammar):
                k_test = Keyword('test')
                RE_KEYWORDS = '[a-z]+'

        with self.assertRaises(KeywordError):
            class _G2(Grammar):
                k_test = Keyword('test-nomatch')

        with self.assertRaises(KeywordError):
            # test 'deep' keyword checks.
            class _G3(Grammar):
                START = Optional(Keyword('test-nomatch'))

        with self.assertRaises(NameAssignedError):
            class _G4(Grammar):
                k_test = Keyword('test')
                k_test2 = k_test

        with self.assertRaises(NameAssignedError):
            class _G5(Grammar):
                k_test = Keyword('test')
                k_Test = Keyword('duplicate')

        with self.assertRaises(MissingStartError):
            class _G6(Grammar):
                k_test = Keyword('test')
github transceptor-technology / pyleri / test / test_pyleri.py View on Github external
def test_compile_error(self):
        with self.assertRaises(ReKeywordsChangedError):
            class _G1(Grammar):
                k_test = Keyword('test')
                RE_KEYWORDS = '[a-z]+'

        with self.assertRaises(KeywordError):
            class _G2(Grammar):
                k_test = Keyword('test-nomatch')

        with self.assertRaises(KeywordError):
            # test 'deep' keyword checks.
            class _G3(Grammar):
                START = Optional(Keyword('test-nomatch'))

        with self.assertRaises(NameAssignedError):
            class _G4(Grammar):
                k_test = Keyword('test')
                k_test2 = k_test
github transceptor-technology / pyleri / test_tree.py View on Github external
import json
from pyleri import Choice
from pyleri import Grammar
from pyleri import Keyword
from pyleri import Regex
from pyleri import Repeat
from pyleri import Sequence


# Create a Grammar Class to define your language
class MyGrammar(Grammar):
    r_name = Regex('(?:"(?:[^"]*)")+')
    k_hi = Keyword('hi')
    k_bye = Keyword('bye')
    START = Repeat(Sequence(Choice(k_hi, k_bye), r_name))


# Returns properties of a node object as a dictionary:
def node_props(node, children):
    return {
        'start': node.start,
        'end': node.end,
        'name': node.element.name if hasattr(node.element, 'name') else None,
        'element': node.element.__class__.__name__,
        'string': node.string,
        'children': children}
github transceptor-technology / pyleri / test / test_pyleri.py View on Github external
k_test = Keyword('test')
    k_ignore_case = Keyword('ignore_case', ign_case=True)
    START = Sequence(k_test, k_ignore_case)


class _TestGrammar2(Grammar):
    k_ni = Keyword('ni')
    s_seq = Sequence('(', THIS, ')')
    START = Prio(
        k_ni,
        s_seq,
        Sequence(THIS, Keyword('and'), THIS),
        Sequence(THIS, Keyword('or'), THIS))


class _TestGrammar3(Grammar):
    s_tic_tac = Sequence(Keyword('tic'), Keyword('tac'))
    s_tic_tac_toe = Sequence(Keyword('tic'), Keyword('tac'), Keyword('toe'))

    START = Sequence(
        Choice(s_tic_tac, s_tic_tac_toe),
        Choice(s_tic_tac, s_tic_tac_toe, most_greedy=False))


class _TestGrammar4(Grammar):
    START = Ref()
    ni_item = Choice(Keyword('ni'), START)
    START = Sequence('[', List(ni_item), ']')


class TestPyleri(unittest.TestCase):
github transceptor-technology / pyleri / test_expecting.py View on Github external
import re
import random
from pyleri import Choice
from pyleri import Grammar
from pyleri import Keyword
from pyleri import Repeat
from pyleri import Sequence
from pyleri import end_of_statement


# Create a Grammar Class to define your language.
class MyGrammar(Grammar):
    RE_KEYWORDS = re.compile('\S+')
    r_name = Keyword('"pyleri"')
    k_hi = Keyword('hi')
    k_bye = Keyword('bye')
    START = Repeat(Sequence(Choice(k_hi, k_bye), r_name), mi=2)


# Print the expected elements as a indented and numbered list.
def print_expecting(node_expecting, string_expecting):
    for loop, e in enumerate(node_expecting):
        string_expecting = '{}\n\t({}) {}'.format(string_expecting, loop, e)
    print(string_expecting)


# Complete a string until it is valid according to the grammar.
def auto_correction(string, my_grammar):
github alastairreid / mra_tools / bin / asm.py View on Github external
pos_guards, neg_guards = parse_guards(gs)
        fields = [name_or_const(pos_guards, *f) for f in enc_fields if f[2] != '_']
        lhs = '{}({})'.format(sanitize(enc_name), ', '.join(fields))

        pos_guards = {k: expand_dontcares(v) for k, v in pos_guards.items()}
        neg_guards = {k: expand_dontcares(v) for k, v in neg_guards.items()}
        pos_sail_guards = ' & '.join(['(' + ' | '.join('{} == 0b{}'.format(k, v) for v in vs) + ')' for k, vs in pos_guards.items()])
        neg_sail_guards = ' & '.join(['(' + ' & '.join('{} != 0b{}'.format(k, v) for v in vs) + ')' for k, vs in neg_guards.items()])

        clause = 'mapping clause assembly = {}{}{} <-> {}'.format(lhs,
                                                                  ' if ' if neg_sail_guards else '',
                                                                  neg_sail_guards,
                                                                  rhs.replace(':', '@'))
        print(clause, file=file)

class ASMTemplateGrammar(Grammar):
    doublespace = Regex('\s\s+')
    space = Regex('\s')
    link = Regex('<[A-Za-z0-9_|()+]+>')
    text = Regex('[A-Za-z0-9_[\]!,#.]+')
    optional = Ref()
    optional = Sequence('{', Repeat(Choice(link, text, optional, space), mi=1), '}')
    bracket_alternative = Sequence('(', Repeat(Choice(link, text, space), mi=1), '|', Repeat(Choice(link, text, space), mi=1), ')')
#    unbracket_alternative = Sequence(Choice(link, text), mi=1), '|', Repeat(Choice(link, text), mi=1))
    optional_alternative = Sequence('{', Repeat(Choice(link, text, space), mi=1), '|', Repeat(Choice(link, text, space), mi=1), '}')
    START = Repeat(Choice(doublespace, space, link, text, optional_alternative, bracket_alternative, optional), mi=1)

    def _walk(self, element, pos, tree, rule, is_required):
        if self._pos != pos:
            self._s = self._string[pos:] #.lstrip() # don't strip whitespace
            self._pos = self._len_string - len(self._s)
        node = Node(element, self._string, self._pos)
github domainaware / checkdmarc / checkdmarc.py View on Github external
class BIMIRecordInWrongLocation(BIMIError):
    """Raised when a BIMI record is found at the root of a domain"""


class MultipleBIMIRecords(BIMIError):
    """Raised when multiple BIMI records are found"""


class _SPFGrammar(Grammar):
    """Defines Pyleri grammar for SPF records"""
    version_tag = Regex(SPF_VERSION_TAG_REGEX_STRING)
    mechanism = Regex(SPF_MECHANISM_REGEX_STRING, IGNORECASE)
    START = Sequence(version_tag, Repeat(mechanism))


class _DMARCGrammar(Grammar):
    """Defines Pyleri grammar for DMARC records"""
    version_tag = Regex(DMARC_VERSION_REGEX_STRING)
    tag_value = Regex(DMARC_TAG_VALUE_REGEX_STRING)
    START = Sequence(version_tag, List(tag_value, delimiter=";", opt=True))


class _BIMIGrammar(Grammar):
    """Defines Pyleri grammar for BIMI records"""
    version_tag = Regex(BIMI_VERSION_REGEX_STRING)
    tag_value = Regex(BIMI_TAG_VALUE_REGEX_STRING)
    START = Sequence(version_tag, List(tag_value, delimiter=";", opt=True))


tag_values = OrderedDict(adkim=OrderedDict(name="DKIM Alignment Mode",
                                           default="r",
                                           description='In relaxed mode, '
github transceptor-technology / pyleri / examples / json_grammar.py View on Github external
'''JSON Grammar.'''
from pyleri import (
    Ref,
    Choice,
    Grammar,
    Regex,
    Keyword,
    Sequence,
    List)


class JsonGrammar(Grammar):
    START = Ref()

    # JSON strings should be enclosed in double quotes.
    # A backslash can be used as escape character.
    r_string = Regex(r'(")(?:(?=(\\?))\2.)*?\1')

    # JSON does not support floats or integers prefixed with a + sign
    # and floats must start with a number, for example .5 is not allowed
    # but should be written like 0.5
    r_float = Regex(r'-?[0-9]+\.?[0-9]+')
    r_integer = Regex('-?[0-9]+')

    k_true = Keyword('true')
    k_false = Keyword('false')
    k_null = Keyword('null')
github domainaware / checkdmarc / checkdmarc.py View on Github external
class _SPFGrammar(Grammar):
    """Defines Pyleri grammar for SPF records"""
    version_tag = Regex(SPF_VERSION_TAG_REGEX_STRING)
    mechanism = Regex(SPF_MECHANISM_REGEX_STRING, IGNORECASE)
    START = Sequence(version_tag, Repeat(mechanism))


class _DMARCGrammar(Grammar):
    """Defines Pyleri grammar for DMARC records"""
    version_tag = Regex(DMARC_VERSION_REGEX_STRING)
    tag_value = Regex(DMARC_TAG_VALUE_REGEX_STRING)
    START = Sequence(version_tag, List(tag_value, delimiter=";", opt=True))


class _BIMIGrammar(Grammar):
    """Defines Pyleri grammar for BIMI records"""
    version_tag = Regex(BIMI_VERSION_REGEX_STRING)
    tag_value = Regex(BIMI_TAG_VALUE_REGEX_STRING)
    START = Sequence(version_tag, List(tag_value, delimiter=";", opt=True))


tag_values = OrderedDict(adkim=OrderedDict(name="DKIM Alignment Mode",
                                           default="r",
                                           description='In relaxed mode, '
                                                       'the Organizational '
                                                       'Domains of both the '
                                                       'DKIM-authenticated '
                                                       'signing domain (taken '
                                                       'from the value of the '
                                                       '"d=" tag in the '
                                                       'signature) and that '
github SiriDB / siridb-server / grammar / export_grammar.py View on Github external
f.write(c_file)
    with open(os.path.join(EXPORT_PATH, 'grammar.h'),
              'w',
              encoding='utf-8') as f:
        f.write(h_file)

    print('\nFinished creating new c-grammar files...\n')

    EXPORT_PATH = 'jsgrammar'

    try:
        os.makedirs(EXPORT_PATH)
    except FileExistsError:
        pass

    js_file = siri_grammar.export_js(js_template=Grammar.JS_WINDOW_TEMPLATE)

    with open(os.path.join(EXPORT_PATH, 'grammar.js'),
              'w',
              encoding='utf-8') as f:
        f.write(js_file)

    js_es6_file = siri_grammar.export_js()

    with open(os.path.join(EXPORT_PATH, 'SiriGrammar.js'),
              'w',
              encoding='utf-8') as f:
        f.write(js_es6_file)

    print('\nFinished creating new js-grammar files...\n')

    py_file = siri_grammar.export_py()