コード例 #1
0
def test_repetition_single_assignment_error():
    """
    Test that plain assignment in repetition end up being a list in the model.
    """

    grammar = r"""
    Rep: many_a*=A;
    A: 'A'
      ( ('b' '=' b=BOOL) |
        ('c' '=' c=C)
      )*;
    B: "b";
    C: "c";
    """
    mm = metamodel_from_str(grammar)
    model = mm.model_from_str(" A c=c b=true ")

    assert model.many_a[0].b == [True]
    assert model.many_a[0].c == ["c"]

    grammar = r"""
    Rep: many_a*=A;
    A: ( ('b' '=' b=BOOL) |
        ('c' '=' c=C)
      )*;
    B: "b";
    C: "c";
    """
    mm = metamodel_from_str(grammar)
    model = mm.model_from_str(" c=c b=true ")

    assert model.many_a[0].b == [True]
    assert model.many_a[0].c == ["c"]
コード例 #2
0
def test_user_classes_callable():
    """
    See metamodel.md, "Custom classes"
    See issue270
    """
    # fix/works (no unused user classes):
    mm = metamodel_from_str(grammar, classes=[Sender, Receiver])
    _ = mm.model_from_str(modelstring)

    # fix/works (no unused user classes; see grammar_with_baseclass_fix):
    mm = metamodel_from_str(grammar_with_baseclass_fix,
                            classes=[ConnectionHandler, Sender, Receiver])
    _ = mm.model_from_str(modelstring)

    # does not work
    with raises(TextXSemanticError,
                match="ConnectionHandler class is not used in the grammar"):
        _ = metamodel_from_str(grammar,
                               classes=[ConnectionHandler, Sender, Receiver])

    # does work (allow unused user classes by providing a callable instead of
    # a list of classes: the callable returns a user class for a given rule name
    # or None)
    def class_provider(name):
        classes = [ConnectionHandler, Sender, Receiver]
        classes = dict(map(lambda x: (x.__name__, x), classes))
        return classes.get(name)

    mm = metamodel_from_str(grammar, classes=class_provider)
    m = mm.model_from_str(modelstring)
    for s in m.sender:
        assert isinstance(s, Sender)
    for r in m.receiver:
        assert isinstance(r, Receiver)
コード例 #3
0
def test_match_rule_suppress():
    """
    Test suppressing operator in match rules.
    """
    grammar = """
    FullyQualifiedID[noskipws]:
        /\s*/-
        QuotedID+['.']
        /\s*/-
    ;
    QuotedID:
        '"'?- ID '"'?-
    ;
    """

    meta = metamodel_from_str(grammar)
    model = meta.model_from_str('''
                                first."second".third."fourth"
                                ''')
    assert model == 'first.second.third.fourth'

    # Checking suppress rule reference
    grammar = """
        First: 'a' Second- Third;
        Second: 'b';
        Third: Second;
    """
    meta = metamodel_from_str(grammar)
    model = meta.model_from_str('a b b')
    # Second b should be suppressed
    assert model == 'ab'
コード例 #4
0
ファイル: test_textx_language.py プロジェクト: c4pone/textX
def test_match_rule_suppress():
    """
    Test suppressing operator in match rules.
    """
    grammar = """
    FullyQualifiedID[noskipws]:
        /\s*/-
        QuotedID+['.']
        /\s*/-
    ;
    QuotedID:
        '"'?- ID '"'?-
    ;
    """

    meta = metamodel_from_str(grammar)
    model = meta.model_from_str('''
                                first."second".third."fourth"
                                ''')
    assert model == 'first.second.third.fourth'

    # Checking suppress rule reference
    grammar = """
        First: 'a' Second- Third;
        Second: 'b';
        Third: Second;
    """
    meta = metamodel_from_str(grammar)
    model = meta.model_from_str('a b b')
    # Second b should be suppressed
    assert model == 'ab'
コード例 #5
0
ファイル: test_repeat_modifiers.py プロジェクト: zeph/textX
def test_modifier_separator_optional():
    model = """
    Rule:
        ("a"|"b")?[','];
    """
    with pytest.raises(TextXSyntaxError):
        # Modifiers are not possible for ? operator
        metamodel_from_str(model)
コード例 #6
0
def test_modifier_separator_optional():
    model = """
    Rule:
        ("a"|"b")?[','];
    """
    with pytest.raises(TextXSyntaxError):
        # Modifiers are not possible for ? operator
        metamodel_from_str(model)
コード例 #7
0
def test_assignment_modifier_separator_optional():
    model = """
    Rule:
        a?=AorB[','];
    AorB:
        "a"|"b";
    """
    with pytest.raises(TextXSyntaxError):
        metamodel_from_str(model)
コード例 #8
0
def test_assignment_modifier_separator_plain():
    """
    Modifiers are not allowed for plain assignment.
    """
    model = """
    Rule:
        a=AorB[','];
    AorB:
        "a"|"b";
    """
    with pytest.raises(TextXSyntaxError):
        metamodel_from_str(model)
コード例 #9
0
ファイル: test_repeat_modifiers.py プロジェクト: atveit/textX
def test_assignment_modifier_separator_plain():
    """
    Modifiers are not allowed for plain assignment.
    """
    model = """
    Rule:
        a=AorB[','];
    AorB:
        "a"|"b";
    """
    with pytest.raises(TextXSyntaxError):
        metamodel_from_str(model)
コード例 #10
0
ファイル: test_metamodel_params.py プロジェクト: atveit/textX
def test_ignore_case():
    langdef = """
    Model: 'start' rules*='first' 'second';
    """
    meta = metamodel_from_str(langdef)

    # By default case is not ignored.
    with pytest.raises(TextXSyntaxError):
        meta.model_from_str('Start first First Second')

    meta = metamodel_from_str(langdef, ignore_case=True)
    meta.model_from_str('Start first First Second')
コード例 #11
0
ファイル: test_metamodel_params.py プロジェクト: atveit/textX
def test_skipws():
    langdef = """
    Model: 'start' rules*='first' 'second';
    """
    meta = metamodel_from_str(langdef)

    # By default ws are skipped.
    meta.model_from_str('start first first second')

    meta = metamodel_from_str(langdef, skipws=False)
    with pytest.raises(TextXSyntaxError):
        meta.model_from_str('start first first second')

    meta.model_from_str('startfirstfirstsecond')
コード例 #12
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_repetition_separator_modifier():
    """
    Match list with regex separator.
    """

    grammar = """
    Model: 'start' attr+=Rule[/,|;/];   // Here a regex match is used to
                                        // define , or ; as a separator
    Rule: Rule1|Rule2|Rule3;
    Rule1: a=INT;
    Rule2: b=STRING;
    Rule3: c=ID;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert set([x.__name__ for x in meta]) == set(['Model', 'Rule', 'Rule1', 'Rule2', 'Rule3'])\
        .union(set(BASE_TYPE_NAMES))

    model = meta.model_from_str('start 34, "foo"; ident')
    assert model
    assert model.attr
    assert model.attr[0].a == 34
    assert model.attr[1].b == "foo"
    assert model.attr[2].c == "ident"
    assert model.attr[0].__class__.__name__ == 'Rule1'
    assert model.attr[1].__class__.__name__ == 'Rule2'
    assert model.attr[2].__class__.__name__ == 'Rule3'

    # There must be at least one Rule matched after 'start'
    with pytest.raises(TextXSyntaxError):
        model = meta.model_from_str('start')
    assert model
コード例 #13
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_assignment_optional():
    grammar = """
    Model: 'start' (attr=Rule)?;    // There should be at most one Rule
                                 // after 'start'
    Rule: Rule1|Rule2|Rule3;
    Rule1: a=INT;
    Rule2: b=STRING;
    Rule3: c=ID;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert set([x.__name__ for x in meta]) == \
        set(['Model', 'Rule', 'Rule1', 'Rule2', 'Rule3'])\
        .union(set(BASE_TYPE_NAMES))

    model = meta.model_from_str('start')
    assert model
    model = meta.model_from_str('start 34')
    assert model
    assert model.attr
    assert model.attr.a == 34
    assert model.attr.__class__.__name__ == 'Rule1'

    # There must be at most one Rule matched after 'start'
    with pytest.raises(TextXSyntaxError):
        model = meta.model_from_str('start 34 "foo"')
    assert model
コード例 #14
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_assignment_zeroormore():

    grammar = """
    Model: 'start' attr*=Rule;     // There should be zero or more Rule-s after
                                    // 'start'
    Rule: Rule1|Rule2|Rule3;
    Rule1: a=INT;
    Rule2: b=STRING;
    Rule3: c=ID;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert set([x.__name__ for x in meta]) == \
        set(['Model', 'Rule', 'Rule1', 'Rule2', 'Rule3'])\
        .union(set(BASE_TYPE_NAMES))

    model = meta.model_from_str('start 34 "foo"')
    assert model
    assert model.attr
    assert model.attr[0].a == 34
    assert model.attr[1].b == "foo"
    assert model.attr[0].__class__.__name__ == 'Rule1'
    assert model.attr[1].__class__.__name__ == 'Rule2'

    model = meta.model_from_str('start')
    assert model
コード例 #15
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_float_int_number():
    """
    Test that numbers are recognized correctly.
    """
    grammar = """
        Rule:
            a=NUMBER
            b=INT
            c=FLOAT
        ;
    """
    meta = metamodel_from_str(grammar)

    model = meta.model_from_str('3.4 5 .3')
    assert model.a == 3.4
    assert type(model.a) is float
    assert model.b == 5
    assert model.c == 0.3

    model = meta.model_from_str('3 5 2.0')
    assert model.a == 3

    # NUMBER type always convert to python float
    assert type(model.a) is float

    assert model.b == 5
    assert model.c == 2
    assert type(model.c) is float
コード例 #16
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_basetype():
    """
    Test that basetype will match each type properly.
    """
    grammar = """
        Rule:
            a1=BASETYPE
            a2=BASETYPE
            a3=BASETYPE
            a4=BASETYPE
            b=BASETYPE
            c=BASETYPE
            d=BASETYPE
            e=BASETYPE
        ;
    """

    meta = metamodel_from_str(grammar)
    assert meta
    assert meta['Rule']._tx_type is RULE_NORMAL

    model = meta.model_from_str('False false true True 0 4.5 "string" some_id')

    assert model.a1 is False
    assert model.a2 is False
    assert model.a3 is True
    assert model.a4 is True
    assert model.b == 0.0
    assert model.c == 4.5
    assert model.d == "string"
    assert model.e == "some_id"
コード例 #17
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_all_basetypes():
    """
    Test that base types are matched properly.
    """
    grammar = """
        Rule:
            a=FLOAT
            b=INT
            c1=BOOL
            c2=BOOL
            d1=STRING
            d2=STRING
            e=ID
        ;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert meta['Rule']._tx_type is RULE_NORMAL

    model = meta.model_from_str('3.4 5 true 0 "some string" '
                                '\'some other string\' some_id')
    assert model.a == 3.4
    assert model.b == 5
    assert model.c1 is True
    assert model.c2 is False
    assert model.d1 == "some string"
    assert model.d2 == "some other string"
    assert model.e == "some_id"
コード例 #18
0
def test_object_processors():
    """
    Test that object processors are called.
    They should be called after each model object construction.
    """

    call_order = []

    def first_obj_processor(first):
        first._first_called = True
        call_order.append(1)

    def second_obj_processor(second):
        second._second_called = True
        call_order.append(2)

        # test that parent is fully initialised.
        # b should be True
        assert second.parent.b

    obj_processors = {
        'First': first_obj_processor,
        'Second': second_obj_processor,
        }

    metamodel = metamodel_from_str(grammar)
    metamodel.register_obj_processors(obj_processors)

    model_str = 'first 34 45 7 A 45 65 B true C "dfdf"'
    first = metamodel.model_from_str(model_str)

    assert hasattr(first, '_first_called')
    for s in first.seconds:
        assert hasattr(s, '_second_called')
    assert call_order == [2, 2, 2, 1]
コード例 #19
0
def main(debug=False):

    calc_mm = metamodel_from_str(
        grammar,
        classes=[Calc, Expression, Term, Factor, Operand],
        debug=debug)

    this_folder = dirname(__file__)
    if debug:
        metamodel_export(calc_mm, join(this_folder, 'calc_metamodel.dot'))

    input_expr = '''
        a = 10;
        b = 2 * a + 17;
        -(4-1)*a+(2+4.67)+b*5.89/(.2+7)
    '''

    model = calc_mm.model_from_str(input_expr)

    if debug:
        model_export(model, join(this_folder, 'calc_model.dot'))

    # Getting value property from the Calc instance will start evaluation.
    result = model.value

    assert (model.value - 6.93805555) < 0.0001
    print("Result is", result)
コード例 #20
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_bool_match():
    grammar = """
    Model: 'start' rule?='rule' rule2?=Rule;   // rule and rule2 attr should be
    Rule: Rule1|Rule2|Rule3;                    // true where match succeeds
    Rule1: a=INT;
    Rule2: b=STRING;
    Rule3: c=ID;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert set([x.__name__ for x in meta]) == \
        set(['Model', 'Rule', 'Rule1', 'Rule2', 'Rule3'])\
        .union(set(BASE_TYPE_NAMES))

    model = meta.model_from_str('start rule 34')
    assert model
    assert hasattr(model, 'rule')
    assert hasattr(model, 'rule2')
    assert model.rule is True
    assert model.rule2 is True

    model = meta.model_from_str('start 34')
    assert model.rule is False
    assert model.rule2 is True

    model = meta.model_from_str('start')
    assert model.rule is False
    assert model.rule2 is False
コード例 #21
0
ファイル: test_metamodel_params.py プロジェクト: atveit/textX
def test_ws():
    langdef = """
    Model: 'start' rules*='first' 'second';
    """
    meta = metamodel_from_str(langdef)

    # Default ws are space, tab and newline
    meta.model_from_str("""start  first 
            first second""")

    meta = metamodel_from_str(langdef, ws=' ')
    with pytest.raises(TextXSyntaxError):
        meta.model_from_str("""start  first 
                first second""")

    meta.model_from_str('start first first second')
コード例 #22
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_abstract_rule_and_object_reference():
    grammar = """
    Model: 'start' rules*=RuleA 'ref' ref=[RuleA];
    RuleA: Rule1|Rule2;
    Rule1: RuleI|RuleE;
    Rule2: 'r2' name=ID;
    RuleI: 'rI' name=ID;
    RuleE: 'rE' name=ID;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert set([x.__name__ for x in meta]) == \
        set(['Model', 'RuleA', 'Rule1', 'Rule2', 'RuleI', 'RuleE'])\
        .union(set(BASE_TYPE_NAMES))

    model = meta.model_from_str('start r2 rule1 rE rule2 ref rule2')
    assert model
    assert hasattr(model, 'rules')
    assert hasattr(model, 'ref')
    assert model.rules
    assert model.ref

    # Reference to first rule
    assert model.ref is model.rules[1]
    assert model.ref.__class__.__name__ == "RuleE"
コード例 #23
0
ファイル: test_textx_language.py プロジェクト: c4pone/textX
def test_syntactic_predicate_not():
    """
    Test negative lookahead using `not` syntactic predicate.
    """
    grammar = """
    Expression: Let | MyID | NUMBER;
    Let:
        'let'
            expr+=Expression
        'end'
    ;

    Keyword: 'let' | 'end';
    MyID: !Keyword ID;
    """
    meta = metamodel_from_str(grammar)

    model = meta.model_from_str("""
                                let let let 34 end let foo end end end
                                """)

    assert model
    assert len(model.expr) == 1
    assert model.expr[0].expr[0].expr[0] == 34
    assert model.expr[0].expr[1].expr[0] == 'foo'
コード例 #24
0
ファイル: test_resolving.py プロジェクト: saidctb/textX
def test_match_complex_recursive_peg_rule_resolve():
    """
    Test that recursive match rules are properly resolved.
    """
    grammar = """
        calc:       expression;
        factor:     INT | ('(' expression ')');
        term:       factor (term_op factor)*;
        term_op:    '*' | '/';
        expression: term  (expr_op term)*;
        expr_op:    '+' | '-';
    """
    metamodel = metamodel_from_str(grammar)

    assert metamodel.parser.parser_model.nodes[0].rule_name == 'expression'
    assert type(metamodel.parser.parser_model.nodes[0]) is Sequence

    calc_rule = metamodel['calc']._tx_peg_rule
    expression_rule = metamodel['expression']._tx_peg_rule
    assert calc_rule is expression_rule
    assert type(calc_rule) is Sequence

    assert type(metamodel['term_op']._tx_peg_rule) is OrderedChoice

    # Recursive factor rule
    factor_rule = metamodel['factor']._tx_peg_rule
    # Find expression reference
    expr_ref = factor_rule.nodes[1].nodes[1]
    assert expr_ref.rule_name == 'expression'
    assert type(expr_ref) is Sequence
    assert expr_ref is expression_rule
コード例 #25
0
def xtest_issue206_regex_reference1():
    mm = metamodel_from_str('''
        Word: ('bar' /[ ]*/)*;
    ''', skipws=False, debug=False)

    m = mm.model_from_str('''bar bar''', debug=False)
    assert m is not None
コード例 #26
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_sequence_ordered_choice():
    """
    Test ordered choice of sequences.
    """

    grammar = """
    Model:
        ('first' a=INT b?='a_is_here')|
        ('second' c=INT d?='c_is_here')|
        (e=RuleA)
        'END'
    ;
    RuleA: 'rule' name=ID;
    """
    meta = metamodel_from_str(grammar, debug=True)
    assert meta
    assert set([x.__name__ for x in meta]) == \
        set(['Model', 'RuleA'])\
        .union(set(BASE_TYPE_NAMES))

    model = meta.model_from_str('first 23 a_is_here END')
    assert model.a == 23
    assert model.c == 0
    assert model.b is True
    assert model.d is False
    model = meta.model_from_str('second 32 END')
    assert model.a == 0
    assert model.c == 32
    assert model.b is False
    assert model.d is False
    model = meta.model_from_str('rule A END')
    assert model.a == 0
    assert model.c == 0
    assert model.b is False
    assert model.d is False
コード例 #27
0
def main(debug=False):

    bool_mm = metamodel_from_str(grammar,
                                 classes=[Bool, Or, And, Not, Operand],
                                 ignore_case=True,
                                 debug=debug)

    this_folder = dirname(__file__)
    if debug:
        metamodel_export(bool_mm, join(this_folder, 'bool_metamodel.dot'))

    input_expr = '''
        a = true;
        b = not a and true;
        a and false or not b
    '''

    model = bool_mm.model_from_str(input_expr)

    if debug:
        model_export(model, join(this_folder, 'bool_model.dot'))

    # Getting value property from the Bool instance will start evaluation.
    result = model.value

    assert model.value is True
    print("Result is", result)
コード例 #28
0
ファイル: test_model_api.py プロジェクト: ScribesZone/textX
def test_model_root():

    metamodel = metamodel_from_str(grammar)
    model = metamodel.model_from_str(model_str)

    t = model.a[0].y
    assert model_root(t) is model
コード例 #29
0
def test_all_basetypes():
    """
    Test that base types are matched properly.
    """
    grammar = """
        Rule:
            a=FLOAT
            b=INT
            c1=BOOL
            c2=BOOL
            d1=STRING
            d2=STRING
            e=ID
        ;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert meta['Rule']._tx_type is RULE_COMMON
    assert meta['BASETYPE']._tx_type is RULE_MATCH
    assert meta['NUMBER']._tx_type is RULE_MATCH
    assert meta['INT']._tx_type is RULE_MATCH
    assert meta['FLOAT']._tx_type is RULE_MATCH
    assert meta['STRING']._tx_type is RULE_MATCH
    assert meta['BOOL']._tx_type is RULE_MATCH

    model = meta.model_from_str('3.4 5 true 0 "some string" '
                                '\'some other string\' some_id')
    assert model.a == 3.4
    assert model.b == 5
    assert model.c1 is True
    assert model.c2 is False
    assert model.d1 == "some string"
    assert model.d2 == "some other string"
    assert model.e == "some_id"
コード例 #30
0
ファイル: test_repeat_modifiers.py プロジェクト: zeph/textX
def test_multiple_modifiers():
    """
    Multiple modifier may be specified separated with space.
    """
    model = """
    Rule:
        'first'
        INT+[eolterm ','] '123456';
    """
    metamodel = metamodel_from_str(model)

    # After 'first' and before newline must
    # be one or more integers separated with comma
    with pytest.raises(TextXSyntaxError):
        model = metamodel.model_from_str("""
            first
            34 56 88 65
            123456
        """)

    # When newline is found matching integers
    # finishes and than a '123456' is matched
    model = metamodel.model_from_str("""
        first 34, 56, 88, 65
        123456
    """)
    assert model
コード例 #31
0
ファイル: test_import.py プロジェクト: saidctb/textX
def test_no_import_for_string():
    """
    Test that import can't be used if meta-model is loaded from string.
    """

    grammar = """
    import relativeimport.first

    Second:
        a = First
    ;

    """

    with pytest.raises(AssertionError):
        metamodel_from_str(grammar)
コード例 #32
0
def test_bool_match():
    grammar = """
    Model: 'start' rule?='rule' rule2?=Rule;   // rule and rule2 attr should be
    Rule: Rule1|Rule2|Rule3;                    // true where match succeeds
    Rule1: a=INT;
    Rule2: b=STRING;
    Rule3: c=ID;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert set([x.__name__ for x in meta]) == \
        set(['Model', 'Rule', 'Rule1', 'Rule2', 'Rule3'])\
        .union(set(ALL_TYPE_NAMES))

    model = meta.model_from_str('start rule 34')
    assert model
    assert hasattr(model, 'rule')
    assert hasattr(model, 'rule2')
    assert model.rule is True
    assert model.rule2 is True

    model = meta.model_from_str('start 34')
    assert model.rule is False
    assert model.rule2 is True

    model = meta.model_from_str('start')
    assert model.rule is False
    assert model.rule2 is False
コード例 #33
0
def test_assignment_oneoormore():

    grammar = """
    Model: 'start' attr+=Rule;    // There should be at least one Rule
                                 // after 'start'
    Rule: Rule1|Rule2|Rule3;
    Rule1: a=INT;
    Rule2: b=STRING;
    Rule3: c=ID;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert set([x.__name__ for x in meta]) == \
        set(['Model', 'Rule', 'Rule1', 'Rule2', 'Rule3'])\
        .union(set(BASE_TYPE_NAMES))

    model = meta.model_from_str('start 34 "foo"')
    assert model
    assert model.attr
    assert model.attr[0].a == 34
    assert model.attr[1].b == "foo"
    assert model.attr[0].__class__.__name__ == 'Rule1'
    assert model.attr[1].__class__.__name__ == 'Rule2'

    # There must be at least one Rule matched after 'start'
    with pytest.raises(TextXSyntaxError):
        model = meta.model_from_str('start')
    assert model
コード例 #34
0
def test_modifier_separator_unordered_group_with_optionals():
    model = """
    Rule:
        ("a" "b"? "c")#[','];
    """
    metamodel = metamodel_from_str(model)

    model = metamodel.model_from_str("a, b, c")
    assert model
    model = metamodel.model_from_str("c, a")
    assert model

    with pytest.raises(TextXSyntaxError):
        metamodel.model_from_str("a, c b")

    with pytest.raises(TextXSyntaxError):
        metamodel.model_from_str("a, c, ")

    with pytest.raises(TextXSyntaxError):
        metamodel.model_from_str("a, c, a, b")

    with pytest.raises(TextXSyntaxError):
        metamodel.model_from_str(",a, c, b")

    with pytest.raises(TextXSyntaxError):
        metamodel.model_from_str("a, c, b, ")

    with pytest.raises(TextXSyntaxError):
        metamodel.model_from_str("a, c, ,b ")
コード例 #35
0
ファイル: test_metamodel.py プロジェクト: ScribesZone/textX
def test_textx_metaclass_repr():
    """
    Test metaclass __repr__
    """

    metamodel = metamodel_from_str(grammar)
    assert '<textx:First class at' in repr(metamodel['First'])
コード例 #36
0
ファイル: test_json_issue.py プロジェクト: saidctb/textX
def test_json_issue():
    """
    Test wrong rule type in json grammar.
    """
    grammar = """
    File:
        Array | Object
    ;

    Array:
        "[" values*=Value[','] "]"
    ;

    Value:
        STRING | FLOAT | BOOL | Object | Array | "null"
    ;

    Object:
        "{" members*=Member[','] "}"
    ;

    Member:
        key=STRING ':' value=Value
    ;
    """
    json_mm = metamodel_from_str(grammar)
    assert json_mm['Object']._tx_type is RULE_COMMON
    assert json_mm['Member']._tx_type is RULE_COMMON
    assert json_mm['Array']._tx_type is RULE_COMMON
    assert json_mm['File']._tx_type is RULE_ABSTRACT
    assert json_mm['Value']._tx_type is RULE_ABSTRACT
コード例 #37
0
def test_syntactic_predicate_not():
    """
    Test negative lookahead using `not` syntactic predicate.
    """
    grammar = """
    Expression: Let | MyID | NUMBER;
    Let:
        'let'
            expr+=Expression
        'end'
    ;

    Keyword: 'let' | 'end';
    MyID: !Keyword ID;
    """
    meta = metamodel_from_str(grammar)

    model = meta.model_from_str("""
                                let let let 34 end let foo end end end
                                """)

    assert model
    assert len(model.expr) == 1
    assert model.expr[0].expr[0].expr[0] == 34
    assert model.expr[0].expr[1].expr[0] == 'foo'
コード例 #38
0
def test_basetype():
    """
    Test that basetype will match each type properly.
    """
    grammar = """
        Rule:
            a1=BASETYPE
            a2=BASETYPE
            a3=BASETYPE
            a4=BASETYPE
            b=BASETYPE
            c=BASETYPE
            d=BASETYPE
            e=BASETYPE
        ;
    """

    meta = metamodel_from_str(grammar)
    assert meta
    assert meta['Rule']._tx_type is RULE_COMMON

    model = meta.model_from_str('False false true True 0 4.5 "string" some_id')

    assert model.a1 is False
    assert model.a2 is False
    assert model.a3 is True
    assert model.a4 is True
    assert model.b == 0.0
    assert model.c == 4.5
    assert model.d == "string"
    assert model.e == "some_id"
コード例 #39
0
def test_repetition_separator_modifier():
    """
    Match list with regex separator.
    """

    grammar = """
    Model: 'start' attr+=Rule[/,|;/];   // Here a regex match is used to
                                        // define , or ; as a separator
    Rule: Rule1|Rule2|Rule3;
    Rule1: a=INT;
    Rule2: b=STRING;
    Rule3: c=ID;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert set([x.__name__ for x in meta]) == set(['Model', 'Rule', 'Rule1',
                                                   'Rule2', 'Rule3'])\
        .union(set(ALL_TYPE_NAMES))

    model = meta.model_from_str('start 34, "foo"; ident')
    assert model
    assert model.attr
    assert model.attr[0].a == 34
    assert model.attr[1].b == "foo"
    assert model.attr[2].c == "ident"
    assert model.attr[0].__class__.__name__ == 'Rule1'
    assert model.attr[1].__class__.__name__ == 'Rule2'
    assert model.attr[2].__class__.__name__ == 'Rule3'

    # There must be at least one Rule matched after 'start'
    with pytest.raises(TextXSyntaxError):
        model = meta.model_from_str('start')
    assert model
コード例 #40
0
def test_assignment_multiple_simple():
    """
    Test that multiple assignments to the same attribute will result in the
    list of values.
    """

    grammar = """
    Model: 'start' a=INT a=INT (a=INT)?;
    """
    meta = metamodel_from_str(grammar)

    model = meta.model_from_str('start 34 23 45')

    assert meta['Model']._tx_attrs['a'].cls.__name__ == 'INT'
    assert meta['Model']._tx_attrs['a'].mult == '1..*'
    assert meta['Model']._tx_attrs['a'].cont
    assert not meta['Model']._tx_attrs['a'].ref
    assert model
    assert model.a
    assert type(model.a) is list
    assert len(model.a) == 3
    assert model.a == [34, 23, 45]

    model = meta.model_from_str('start 34 23')
    assert model.a == [34, 23]
コード例 #41
0
def test_assignment_optional():
    grammar = """
    Model: 'start' (attr=Rule)?;    // There should be at most one Rule
                                 // after 'start'
    Rule: Rule1|Rule2|Rule3;
    Rule1: a=INT;
    Rule2: b=STRING;
    Rule3: c=ID;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert set([x.__name__ for x in meta]) == \
        set(['Model', 'Rule', 'Rule1', 'Rule2', 'Rule3'])\
        .union(set(ALL_TYPE_NAMES))

    model = meta.model_from_str('start')
    assert model
    model = meta.model_from_str('start 34')
    assert model
    assert model.attr
    assert model.attr.a == 34
    assert model.attr.__class__.__name__ == 'Rule1'

    # There must be at most one Rule matched after 'start'
    with pytest.raises(TextXSyntaxError):
        model = meta.model_from_str('start 34 "foo"')
    assert model
コード例 #42
0
def test_float_int_number():
    """
    Test that numbers are recognized correctly.
    """
    grammar = """
        Rule:
            a=NUMBER
            b=INT
            c=FLOAT
        ;
    """
    meta = metamodel_from_str(grammar)

    model = meta.model_from_str('3.4 5 .3')
    assert model.a == 3.4
    assert type(model.a) is float
    assert model.b == 5
    assert model.c == 0.3

    model = meta.model_from_str('3 5 2.0')
    assert model.a == 3

    # NUMBER type always convert to python float
    assert type(model.a) is float

    assert model.b == 5
    assert model.c == 2
    assert type(model.c) is float
コード例 #43
0
def test_assignment_zeroormore():

    grammar = """
    Model: 'start' attr*=Rule;     // There should be zero or more Rule-s after
                                    // 'start'
    Rule: Rule1|Rule2|Rule3;
    Rule1: a=INT;
    Rule2: b=STRING;
    Rule3: c=ID;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert set([x.__name__ for x in meta]) == \
        set(['Model', 'Rule', 'Rule1', 'Rule2', 'Rule3'])\
        .union(set(ALL_TYPE_NAMES))

    model = meta.model_from_str('start 34 "foo"')
    assert model
    assert model.attr
    assert model.attr[0].a == 34
    assert model.attr[1].b == "foo"
    assert model.attr[0].__class__.__name__ == 'Rule1'
    assert model.attr[1].__class__.__name__ == 'Rule2'

    model = meta.model_from_str('start')
    assert model
コード例 #44
0
ファイル: calc.py プロジェクト: atveit/textX
def main(debug=False):

    calc_mm = metamodel_from_str(grammar,
                                 classes=[Calc, Expression, Term, Factor,
                                          Operand],
                                 debug=debug)

    this_folder = dirname(__file__)
    if debug:
        metamodel_export(calc_mm, join(this_folder, 'calc_metamodel.dot'))

    input_expr = '''
        a = 10;
        b = 2 * a + 17;
        -(4-1)*a+(2+4.67)+b*5.89/(.2+7)
    '''

    model = calc_mm.model_from_str(input_expr)

    if debug:
        model_export(model, join(this_folder, 'calc_model.dot'))

    # Getting value property from the Calc instance will start evaluation.
    result = model.value

    assert (model.value - 6.93805555) < 0.0001
    print("Result is", result)
コード例 #45
0
def test_sequence_ordered_choice():
    """
    Test ordered choice of sequences.
    """

    grammar = """
    Model:
        ('first' a=INT b?='a_is_here' |
        'second' c=INT d?='c_is_here' |
        e=RuleA)
        'END'
    ;
    RuleA: 'rule' name=ID;
    """
    meta = metamodel_from_str(grammar, debug=True)
    assert meta
    assert set([x.__name__ for x in meta]) == \
        set(['Model', 'RuleA'])\
        .union(set(ALL_TYPE_NAMES))

    model = meta.model_from_str('first 23 a_is_here END')
    assert model.a == 23
    assert model.c == 0
    assert model.b is True
    assert model.d is False
    model = meta.model_from_str('second 32 END')
    assert model.a == 0
    assert model.c == 32
    assert model.b is False
    assert model.d is False
    model = meta.model_from_str('rule A END')
    assert model.a == 0
    assert model.c == 0
    assert model.b is False
    assert model.d is False
コード例 #46
0
def test_multiple_modifiers():
    """
    Multiple modifier may be specified separated with space.
    """
    model = """
    Rule:
        'first'
        INT+[eolterm ','] '123456';
    """
    metamodel = metamodel_from_str(model)

    # After 'first' and before newline must
    # be one or more integers separated with comma
    with pytest.raises(TextXSyntaxError):
        model = metamodel.model_from_str("""
            first
            34 56 88 65
            123456
        """)

    # When newline is found matching integers
    # finishes and than a '123456' is matched
    model = metamodel.model_from_str("""
        first 34, 56, 88, 65
        123456
    """)
    assert model
コード例 #47
0
def test_abstract_rule_and_object_reference():
    grammar = """
    Model: 'start' rules*=RuleA 'ref' ref=[RuleA];
    RuleA: Rule1|Rule2;
    Rule1: RuleI|RuleE;
    Rule2: 'r2' name=ID;
    RuleI: 'rI' name=ID;
    RuleE: 'rE' name=ID;
    """
    meta = metamodel_from_str(grammar)
    assert meta
    assert set([x.__name__ for x in meta]) == \
        set(['Model', 'RuleA', 'Rule1', 'Rule2', 'RuleI', 'RuleE'])\
        .union(set(ALL_TYPE_NAMES))

    model = meta.model_from_str('start r2 rule1 rE rule2 ref rule2')
    assert model
    assert hasattr(model, 'rules')
    assert hasattr(model, 'ref')
    assert model.rules
    assert model.ref

    # Reference to first rule
    assert model.ref is model.rules[1]
    assert model.ref.__class__.__name__ == "RuleE"
コード例 #48
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_repeat_rule_ref():
    grammar = """
    Rule: ID*;
    """
    metamodel = metamodel_from_str(grammar)

    model = metamodel.model_from_str("""first second third""")
    assert model
コード例 #49
0
ファイル: test_metamodel.py プロジェクト: ScribesZone/textX
def test_textx_metaclass_instance_repr():
    """
    Test metaclass instance __repr__
    """

    metamodel = metamodel_from_str(grammar)
    model = metamodel.model_from_str('first 42')
    assert '<textx:First instance at' in repr(model)
コード例 #50
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_repeat_strmatch_with_separator():
    grammar = """
    Rule: "first"*[','];
    """
    metamodel = metamodel_from_str(grammar)

    model = metamodel.model_from_str("""first, first""")
    assert model
コード例 #51
0
ファイル: test_textx_language.py プロジェクト: zeph/textX
def test_repeat_strmatch():
    grammar = """
    Rule: "first"*;
    """
    metamodel = metamodel_from_str(grammar)

    model = metamodel.model_from_str("""first first""")
    assert model
コード例 #52
0
ファイル: test_textx_language.py プロジェクト: c4pone/textX
def test_repeat_strmatch():
    grammar = """
    Rule: "first"*;
    """
    metamodel = metamodel_from_str(grammar)

    model = metamodel.model_from_str("""first first""")
    assert metamodel['Rule']._tx_type is RULE_MATCH
    assert model == 'firstfirst'
コード例 #53
0
ファイル: test_textx_language.py プロジェクト: c4pone/textX
def test_repeat_strmatch_with_separator():
    grammar = """
    Rule: "first"*[','];
    """
    metamodel = metamodel_from_str(grammar)

    assert metamodel['Rule']._tx_type is RULE_MATCH
    model = metamodel.model_from_str("""first, first""")
    assert model == 'first,first'
コード例 #54
0
ファイル: test_repeat_modifiers.py プロジェクト: zeph/textX
def test_modifier_separator_zeroormore():
    model = """
    Rule:
        ("a"|"b")*[','];
    """
    metamodel = metamodel_from_str(model)

    model = metamodel.model_from_str("a,b, a, b")
    assert model