コード例 #1
0
ファイル: dissector.py プロジェクト: goto40/mdsd
def get_all_referenced_structs(s):
    mm = get_metamodel(s)
    l = set()
    l.add(s)
    n = 0
    while n != len(l):
        n = len(l)
        l0 = l.copy()
        for s in l0:
            c = get_children_of_type("ScalarAttribute", s)
            for a in c:
                if textx_isinstance(a.type, mm["Struct"]):
                    l.add(a.type)
                    # print(f"1added {a.type.name}")
            c = get_children_of_type("ArrayAttribute", s)
            for a in c:
                if textx_isinstance(a.type, mm["Struct"]):
                    l.add(a.type)
                    # print(f"2added {a.type.name}")
            c = get_children_of_type("VariantMapping", s)
            for m in c:
                if textx_isinstance(m.type, mm["Struct"]):
                    l.add(m.type)
                    # print(f"3added {m.type.name}")
    return l
コード例 #2
0
def generate_cpp(metamodel, model, output_path, overwrite, debug):
    "Generating c++ code from the item model"
    input_file = model._tx_filename
    base_dir = output_path if output_path else os.path.dirname(input_file)

    structs = get_children_of_type("Struct", model)
    enums = get_children_of_type("Enum", model)
    constants = get_children_of_type("Constants", model)

    for elem in structs:
        output_file = create_folder_and_return_output_filename(
            elem, base_dir, overwrite
        )
        generate_cpp_for_struct(elem, output_file, overwrite)

    for elem in enums:
        output_file = create_folder_and_return_output_filename(
            elem, base_dir, overwrite
        )
        generate_cpp_for_enum(elem, output_file, overwrite)

    for elem in constants:
        output_file = create_folder_and_return_output_filename(
            elem, base_dir, overwrite
        )
        generate_cpp_for_constants(elem, output_file, overwrite)
コード例 #3
0
ファイル: test_children.py プロジェクト: igordejanovic/textX
def test_children():
    """
    This test checks the get_children function
    """
    #################################
    # META MODEL DEF
    #################################

    my_metamodel = metamodel_from_str(metamodel_str)

    my_metamodel.register_scope_providers({"*.*": scoping_providers.FQN()})

    #################################
    # MODEL PARSING
    #################################

    my_model = my_metamodel.model_from_str('''
    package P1 {
        class Part1 {
        }
    }
    package P2 {
        class Part2 {
            attr C2 rec;
        }
        class C2 {
            attr P1.Part1 p1;
            attr Part2 p2a;
            attr P2.Part2 p2b;
        }
    }
    ''')

    #################################
    # TEST
    #################################

    res = get_children_of_type("Class", my_model)
    res.sort(key=lambda x: x.name)
    assert len(res) == 3
    assert all(map(eq, map(lambda x: x.name, res), ["C2", "Part1", "Part2"]))
    assert not all(map(eq, map(lambda x: x.name, res),
                       ["Part1", "Part2", "C2"]))
    for x in res:
        assert x.__class__.__name__ == "Class"

    res = get_children_of_type("Attribute", my_model)
    res.sort(key=lambda x: x.name)
    assert len(res) == 4
    assert all(map(eq, map(lambda x: x.name, res),
                   ["p1", "p2a", "p2b", "rec"]))
    for x in res:
        assert x.__class__.__name__ == "Attribute"

    res = get_children(lambda x: hasattr(x, "name") and re.match(
        ".*2.*", x.name), my_model)
    res.sort(key=lambda x: x.name)
    assert len(res) == 5
    assert all(map(eq, map(lambda x: x.name, res),
                   ["C2", "P2", "Part2", "p2a", "p2b"]))
コード例 #4
0
def test_big_example():
    mm = metamodel_for_language("item")
    assert mm is not None

    inpath = join(this_folder, "model")

    model = mm.model_from_file(join(inpath, "big_example.item"))
    assert model is not None

    outpath = join(this_folder, "src-gen")
    gen = generator_for_language_target("item", "cpp_v2")

    if exists(outpath):
        rmtree(outpath)
    mkdir(outpath)
    gen(mm, model, output_path=outpath, overwrite=True, debug=False)

    refpath = join(inpath, "ref")

    structs = get_children_of_type("Struct", model)
    enums = get_children_of_type("Enum", model)
    constants = get_children_of_type("Constants", model)

    for s in structs + enums + constants:
        outputfile = output_filename(refpath, s, "regex_ref")
        if exists(outputfile):
            check_file(
                filename=output_filename(outpath, s),
                regex_reference_filename=outputfile,
            )
コード例 #5
0
def do_test_diagram_choice(diagram):
    transitions = textx.get_children_of_type("TransitionExpression", diagram._model)
    assert len(transitions) == 4

    pseudo_states = textx.get_children_of_type("PseudoState", diagram._model)
    assert len(pseudo_states) == 1
    assert pseudo_states[0].type == "<<choice>>"
コード例 #6
0
def test_attr_ref2():
    text = r"""
    package example
    struct Point {
      scalar x : built_in.float
      scalar y : built_in.float
    }
    struct Header {
      scalar n : built_in.uint32 (.maxValue=100, .defaultValue=1)
      scalar nb_bytes: built_in.uint32
    }
    struct Polygon {
      scalar header: Header
      array points : Point[header.n]
    }
    """
    mm = metamodel_for_language("item")
    assert mm is not None
    model = mm.model_from_str(text)
    assert model is not None
    items = get_children_of_type("Struct", model)
    assert len(items) == 3

    assert not items[2].attributes[1].has_fixed_size()
    Header = items[1]
    Polygon = items[2]
    r = get_children_of_type("AttrRef", Polygon.attributes[1])
    assert len(r) == 1
    assert r[0].ref == Header.attributes[0]
コード例 #7
0
def test_is_dynamic():
    mm = metamodel_for_language("item")
    assert mm is not None
    model = mm.model_from_file(
        os.path.join(
            os.path.abspath(os.path.dirname(__file__)), "model", "big_example.item"
        )
    )
    assert model is not None

    Color = next(
        filter(lambda x: x.name == "Color", get_children_of_type("Struct", model))
    )
    assert Color.name == "Color"
    assert not is_dynamic(Color.attributes[0])
    assert not is_dynamic(Color)

    MultiMessage = next(
        filter(
            lambda x: x.name == "MultiMessage", get_children_of_type("Struct", model)
        )
    )
    assert MultiMessage.name == "MultiMessage"
    assert is_dynamic(MultiMessage)

    Polygon = next(
        filter(lambda x: x.name == "Polygon", get_children_of_type("Struct", model))
    )
    assert Polygon.name == "Polygon"
    assert not is_dynamic(Polygon.attributes[0])
    assert is_dynamic(Polygon.attributes[1])
    assert not is_dynamic(Polygon.attributes[2])
    assert is_dynamic(Polygon)
コード例 #8
0
ファイル: code_gen.py プロジェクト: goto40/recipec
def model_export(model, output_file):
    import jinja2
    plan = get_children_of_type("Plan", model)
    assert len(plan) == 1
    plan = plan[0]

    all_ingredients = {}  # ingredientType, count
    for e in get_children_of_type("PlanEntry", plan):
        for i in get_children_of_type("Ingredient", e.get_recipe()):
            all_ingredients[i.get_type()] = \
                all_ingredients.get(i.get_type(),0.0) \
                + i.get_count_in_default_units(float(e.person_count))
            #print("{} {}".format(i.get_type().name, all_ingredients[i.get_type()]))

    config = get_all(model, "Config")
    config = config[0]

    this_folder = dirname(abspath(__file__))
    jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(
        join(this_folder, "template")),
                                   trim_blocks=True,
                                   lstrip_blocks=True)
    template = jinja_env.get_template('plan.template')
    with open(output_file, 'w') as f:
        f.write(
            template.render(plan=plan,
                            config=config,
                            all_ingredients=all_ingredients))
コード例 #9
0
def do_test_diagram_long_state_names(diagram):
    transitions = textx.get_children_of_type("TransitionExpression", diagram._model)
    assert len(transitions) == 11

    alias = textx.get_children_of_type("StateAliasExpression", diagram._model)
    assert len(alias) == 1
    assert alias[0].longname == r"Accumulate Enough Data\nLong State Name"
    assert alias[0].name == "long1"
コード例 #10
0
ファイル: test_children.py プロジェクト: rowhit/textX
def test_fully_qualified_name_ref():
    #################################
    # META MODEL DEF
    #################################

    my_metamodel = metamodel_from_str(metamodel_str)

    my_metamodel.register_scope_providers({"*.*": scoping_providers.FQN()})

    #################################
    # MODEL PARSING
    #################################

    my_model = my_metamodel.model_from_str('''
    package P1 {
        class Part1 {
        }
    }
    package P2 {
        class Part2 {
            attr C2 rec;
        }
        class C2 {
            attr P1.Part1 p1;
            attr Part2 p2a;
            attr P2.Part2 p2b;
        }
    }
    ''')

    #################################
    # TEST
    #################################

    res = get_children_of_type("Class", my_model)
    res.sort(key=lambda x: x.name)
    assert len(res) == 3
    assert all(map(eq, map(lambda x: x.name, res), ["C2", "Part1", "Part2"]))
    assert not all(
        map(eq, map(lambda x: x.name, res), ["Part1", "Part2", "C2"]))
    for x in res:
        assert x.__class__.__name__ == "Class"

    res = get_children_of_type("Attribute", my_model)
    res.sort(key=lambda x: x.name)
    assert len(res) == 4
    assert all(map(eq, map(lambda x: x.name, res),
                   ["p1", "p2a", "p2b", "rec"]))
    for x in res:
        assert x.__class__.__name__ == "Attribute"

    res = get_children(
        lambda x: hasattr(x, "name") and re.match(".*2.*", x.name), my_model)
    res.sort(key=lambda x: x.name)
    assert len(res) == 5
    assert all(
        map(eq, map(lambda x: x.name, res),
            ["C2", "P2", "Part2", "p2a", "p2b"]))
コード例 #11
0
def do_test_diagram_fork_join(diagram):
    transitions = textx.get_children_of_type("TransitionExpression", diagram._model)
    assert len(transitions) == 7

    fork_joins = textx.get_children_of_type("PseudoState", diagram._model)
    assert len(fork_joins) == 2

    assert fork_joins[0].type == "<<fork>>"
    assert fork_joins[1].type == "<<join>>"
コード例 #12
0
def do_test_diagram_expansions(diagram):
    transitions = textx.get_children_of_type("TransitionExpression", diagram._model)
    assert len(transitions) == 7

    pseudo_states = textx.get_children_of_type("PseudoState", diagram._model)
    assert len(pseudo_states) == 3
    assert pseudo_states[0].type == "<<expansionInput>>"
    assert pseudo_states[1].type == "<<expansionInput>>"
    assert pseudo_states[2].type == "<<expansionOutput>>"
コード例 #13
0
def do_test_diagram_entry_exit_pin(diagram):
    transitions = textx.get_children_of_type("TransitionExpression", diagram._model)
    assert len(transitions) == 7

    pseudo_states = textx.get_children_of_type("PseudoState", diagram._model)
    assert len(pseudo_states) == 3
    assert pseudo_states[0].type == "<<inputPin>>"
    assert pseudo_states[1].type == "<<inputPin>>"
    assert pseudo_states[2].type == "<<outputPin>>"
コード例 #14
0
def test_model_with_local_scope_and_circular_ref_via_two_models():
    """
    Test for FQNGlobalRepo + circular references.
    """
    #################################
    # META MODEL DEF
    #################################

    my_meta_model = metamodel_from_file(
        join(abspath(dirname(__file__)),
             'components_model1', 'Components.tx'),
        global_repository=True)
    global_scope = scoping_providers.FQNGlobalRepo(
        join(abspath(dirname(__file__)),
             "components_model1", "example_?.components"))
    my_meta_model.register_scope_providers({
        "*.*": global_scope,
        "Connection.from_port":
            scoping_providers.RelativeName("from_inst.component.slots"),
        "Connection.to_port":
            scoping_providers.RelativeName("to_inst.component.slots")
    })

    #################################
    # MODEL PARSING
    #################################

    my_model_a = my_meta_model.model_from_file(
        join(abspath(dirname(__file__)),
             "components_model1", "example_A.components"))
    my_model_b = my_meta_model.model_from_file(
        join(abspath(dirname(__file__)),
             "components_model1", "example_B.components"))

    a_my_a = get_unique_named_object(my_model_a, "mya")
    a_my_b = get_unique_named_object(my_model_a, "myb")
    b_my_a = get_unique_named_object(my_model_b, "mya")
    b_my_b = get_unique_named_object(my_model_b, "myb")

    assert a_my_a != b_my_a
    assert a_my_b != b_my_b

    assert a_my_a.component == b_my_a.component  # same component "class"
    assert a_my_b.component == b_my_b.component  # same component "class"

    a_connections = get_children_of_type("Connection", my_model_a)
    b_connections = get_children_of_type("Connection", my_model_b)

    a_connection = list(filter(
        lambda x: x.from_inst == a_my_a and x.to_inst == a_my_b,
        a_connections))
    b_connection = list(filter(
        lambda x: x.from_inst == b_my_a and x.to_inst == b_my_b,
        b_connections))
    assert len(a_connection) == 1
    assert len(b_connection) == 1
コード例 #15
0
def do_test_diagram_pseudostates(diagram):
    transitions = textx.get_children_of_type("TransitionExpression", diagram._model)
    assert len(transitions) == 9

    pseudo_states = textx.get_children_of_type("PseudoState", diagram._model)
    assert len(pseudo_states) == 4
    assert pseudo_states[0].type == "<<choice>>"
    assert pseudo_states[1].type == "<<fork>>"
    assert pseudo_states[2].type == "<<join>>"
    assert pseudo_states[3].type == "<<end>>"
コード例 #16
0
def do_test_diagram_inline_pseudostate(diagram):
    transitions = textx.get_children_of_type("TransitionExpression", diagram._model)
    assert len(transitions) == 7

    pseudo_states = textx.get_children_of_type("PseudoState", diagram._model)
    assert len(pseudo_states) == 3
    assert pseudo_states[0].type == "<<entryPoint>>"
    assert pseudo_states[1].type == "<<entryPoint>>"
    assert pseudo_states[2].type == "<<exitPoint>>"
    assert pseudo_states[2].parent.name == "exitA"
    assert pseudo_states[2].parent.parent.__class__.__name__ == "TransitionExpression"
コード例 #17
0
def test_get_children_of_type():

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

    thirds = get_children_of_type('Third', model)
    assert len(thirds) == 5
    assert set(['first', 'second', 'third', 'one', 'two']) \
        == set([a.x for a in thirds])

    # Test search in the part of the model
    thirds = get_children_of_type("Third", model.a[1])
    assert len(thirds) == 1
    assert 'two' == list(thirds)[0].x
コード例 #18
0
ファイル: test_model_api.py プロジェクト: igordejanovic/textX
def test_get_children_of_type():

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

    thirds = get_children_of_type('Third', model)
    assert len(thirds) == 5
    assert set(['first', 'second', 'third', 'one', 'two']) \
        == set([a.x for a in thirds])

    # Test search in the part of the model
    thirds = get_children_of_type("Third", model.a[1])
    assert len(thirds) == 1
    assert 'two' == list(thirds)[0].x
コード例 #19
0
def do_test_diagram_composite_states_1(diagram):
    transitions = textx.get_children_of_type("TransitionExpression", diagram._model)
    assert len(transitions) == 2

    composites = textx.get_children_of_type("CompositeState", diagram._model)
    assert len(composites) == 5

    names = ["A", "X", "Y", "B", "Z"]

    for i, s in enumerate(composites):
        assert s.parent.name == names[i]

    assert composites[1].parent.parent == composites[0]
    assert composites[2].parent.parent == composites[0]
    assert composites[4].parent.parent == composites[3]
コード例 #20
0
ファイル: test_big_example.py プロジェクト: goto40/mdsd
def test_big_example():
    mm = metamodel_for_language("item")
    assert mm is not None

    inpath = join(this_folder, "../../mdsd_support_library_common/model")

    model = mm.model_from_file(join(inpath, "big_example.item"))
    assert model is not None
    refpath = join(this_folder, "model", "ref")

    structs = get_children_of_type("Struct", model)
    enums = get_children_of_type("Enum", model)
    constants = get_children_of_type("Constants", model)

    outpath = join(this_folder, "../src-gen")
コード例 #21
0
ファイル: codegen.py プロジェクト: r4mtor/itemlang
def _generate_python_construct_code(idl_model, srcgen_folder, this_folder):
    import itemlang.itemc.support_python_construct_code.custom_idl_pyctool as pyctool
    jinja_env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(this_folder +
                                       "/support_python_construct_code"),
        trim_blocks=True,
        lstrip_blocks=True)
    # Load Java template
    template = jinja_env.get_template('python-construct.template')
    for struct in get_children_of_type("Struct", idl_model):
        # For each entity generate java file
        struct_folder = join(srcgen_folder, pyctool.path_to_file_name(struct))
        if not exists(struct_folder):
            makedirs(struct_folder)

        if struct.parent.target_namespace:
            parts = struct.parent.target_namespace.name.split(".")
            dir = srcgen_folder
            for part in parts:
                dir = join(dir, part)
                init_filename = join(dir, "__init__.py")
                with open(init_filename, 'w') as f:
                    f.write("")

        with open(join(srcgen_folder, pyctool.full_path_to_file_name(struct)),
                  'w') as f:
            f.write(template.render(struct=struct, pyctool=pyctool))
コード例 #22
0
def test_attr_formula1():
    text = r"""
    package example
    struct Image {
      scalar w: built_in.uint32  (.defaultValue=1, .maxValue=1000)
      scalar h: built_in.uint32  (.defaultValue=1, .maxValue=1000)
      array pixel : built_in.float[w*h]
    }
    """
    mm = metamodel_for_language("item")
    assert mm is not None
    model = mm.model_from_str(text)
    assert model is not None
    items = get_children_of_type("Struct", model)
    assert len(items) == 1

    model._tx_filename = "example.item"
    path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "src-gen")
    gen1 = generator_for_language_target("item", "cpp")
    gen2 = generator_for_language_target("item", "python")

    if os.path.exists(path):
        shutil.rmtree(path)
    os.mkdir(path)
    gen1(mm, model, output_path=path, overwrite=True, debug=False)
    gen2(mm, model, output_path=path, overwrite=True, debug=False)

    cpp_code = open(os.path.join(path, "example", "Image.h")).read()
    print(cpp_code)
    assert "struct Image" in cpp_code
    assert "s.w*s.h" in cpp_code
コード例 #23
0
ファイル: components.py プロジェクト: pyflies/pyflies
    def __init__(self, spec, context=None):
        super().__init__(spec)

        # Find out if this param is dependent on trial condition variables
        test = get_parent_of_type("TestType", self.spec)
        cond_var_names = test.table_spec.variables

        self.value = spec.value
        if isinstance(self.value, String):
            # Special handling of strings. If there is a variable reference
            # consider it non-constant
            self.is_constant = '{{' not in self.value.value
        else:
            # expressions with variables or messages are considered non-constant
            self.is_constant = \
                not any([r.name in cond_var_names
                         for r in unresolvable_refs(self.value)])\
                and not get_children_of_type("MessageExpression", self.value)

        if not self.is_constant and context is None:
            # Use default value
            self.value = spec.type.default.eval()
        else:
            try:
                self.value = self.value.eval(context)
            except PyFliesException as e:
                if 'Undefined variable' in str(e):
                    # This may happen if expression contains strings with
                    # interpolated variables which are not available
                    # Use default value
                    self.value = spec.type.default.eval()
コード例 #24
0
def test_model_with_multi_import():
    """
    Basic test for FQNImportURI + multi imports (import "*.if")
    """
    #################################
    # META MODEL DEF
    #################################

    my_meta_model = metamodel_from_file(
        join(abspath(dirname(__file__)),
             'interface_model1', 'Interface.tx'))
    my_meta_model.register_scope_providers(
        {"*.*": scoping_providers.FQNImportURI()})

    #################################
    # MODEL PARSING
    #################################

    my_model = my_meta_model.model_from_file(
        join(abspath(dirname(__file__)),
             "interface_model1", "model_c", "A_multi_import.if"))

    #################################
    # TEST MODEL
    #################################

    imports = get_children_of_type("Import", my_model)
    assert 1 == len(imports)
    i = imports[0]
    assert 4 == len(i._tx_loaded_models)  # 4 files
    assert 4 == len(set(i._tx_loaded_models))  # 4 different files
コード例 #25
0
ファイル: test_properties.py プロジェクト: goto40/mdsd
def test_property2():
    text = r"""
    package example.one (property_set example.one.ProjExt)
    property_set ProjExt {
        property optional myprop1: STRING
        property applicable for rawtype, enum myprop2: ATTRTYPE
    }
    struct A {
        scalar x: built_in.int32 (.description="a", .myprop2=1)
    }
    """
    mm = metamodel_for_language("item")
    assert mm is not None
    model = mm.model_from_str(text)
    assert model is not None
    items = get_children_of_type("Struct", model)
    assert len(items) == 1

    pdefs = get_all_possible_properties(items[0].attributes[0])
    assert len(pdefs) >= 7

    assert "minValue" in pdefs
    assert "maxValue" in pdefs
    assert "defaultValue" in pdefs
    assert "description" in pdefs
    assert "myprop1" in pdefs
    assert "myprop2" in pdefs
    pdefs["myprop1"].internaltype == "STRING"
    pdefs["myprop2"].internaltype == "ATTRTYPE"

    pdefs = get_all_possible_mandatory_properties(items[0].attributes[0])
    assert len(pdefs) == 1
    assert "myprop2" in pdefs
コード例 #26
0
def _get_referenced_if_attributes(self):
    mm = get_metamodel(self)
    return list(
        filter(
            lambda x: textx_isinstance(x.ref, mm["Attribute"]),
            get_children_of_type("AttrRef", self.if_attr),
        ))
コード例 #27
0
def test_example2():
    text = r"""
    package example
    struct Point {
      scalar x : built_in.float
      scalar y : built_in.float
    }
    struct Line {
      scalar p1 : Point
      scalar p2 : Point
    }
    struct Circle {
      scalar center : Point
      scalar radius : built_in.float
    }
    struct VariantExample {
        scalar selector: built_in.uint32
        variant payload: selector -> {
            10: Point
            11: Line
            12: Circle
        }
    }
    """
    mm = metamodel_for_language("item")
    assert mm is not None
    model = mm.model_from_str(text)
    assert model is not None
    items = get_children_of_type("Struct", model)
    assert len(items) == 4

    refs = get_referenced_elements_of_struct(items[3])
    assert len(refs) == 3
コード例 #28
0
def test_inheritance_processor():
    """
    Basic test for ExtRelativeName (using an inheritance example)
    """
    #################################
    # META MODEL DEF
    #################################

    my_meta_model = metamodel_from_file(
        abspath(dirname(__file__)) + '/components_model1/Components.tx')
    my_meta_model.register_scope_providers({
        "*.*": scoping_providers.FQN(),
        "Connection.from_port":
            scoping_providers.ExtRelativeName("from_inst.component",
                                              "slots",
                                              "extends"),
        "Connection.to_port":
            scoping_providers.ExtRelativeName("to_inst.component",
                                              "slots",
                                              "extends"),
    })

    #################################
    # MODEL PARSING
    #################################

    my_model = my_meta_model.model_from_file(
        abspath(dirname(__file__)) +
        "/components_model1/example_inherit3.components")

    #################################
    # TEST MODEL
    #################################

    components = get_children_of_type("Component", my_model)

    expected = """
        Start
        BaseProc
        ExtProc(BaseProc)
        Plus
        ExtProc2(Plus,ExtProc(BaseProc))
        End
        End2
    """

    def myformatter(compo):
        if len(compo.extends) == 0:
            return compo.name
        else:
            return compo.name + "(" + ",".join(map(lambda x: myformatter(x),
                                                   compo.extends)) + ")"

    res = "\n\n"
    # possibly in future version, the order need to be normalized...
    for c in components:
        res += myformatter(c) + "\n"

    print(res)
    assert re.sub(r'\s*', "", expected) == re.sub(r'\s*', "", res)
コード例 #29
0
def test_model_with_multi_import():
    """
    Basic test for FQNImportURI + multi imports (import "*.if")
    """
    #################################
    # META MODEL DEF
    #################################

    my_meta_model = metamodel_from_file(
        join(abspath(dirname(__file__)), 'interface_model1', 'Interface.tx'))
    my_meta_model.register_scope_providers(
        {"*.*": scoping_providers.FQNImportURI()})

    #################################
    # MODEL PARSING
    #################################

    my_model = my_meta_model.model_from_file(
        join(abspath(dirname(__file__)), "interface_model1", "model_c",
             "A_multi_import.if"))

    #################################
    # TEST MODEL
    #################################

    imports = get_children_of_type("Import", my_model)
    assert 1 == len(imports)
    i = imports[0]
    assert 4 == len(i._tx_loaded_models)  # 4 files
    assert 4 == len(set(i._tx_loaded_models))  # 4 different files
コード例 #30
0
def test_example1():
    text = r"""
    package P1.P2.P3
    struct Point {
      scalar x : built_in.float
      scalar y : built_in.float
    }
    struct Line {
      scalar p1 : Point
      scalar p2 : Point
    }
    struct Circle {
      scalar center : Point
      scalar radius : built_in.float
    }
    struct ColoredTriangle {
      array color : built_in.float[3]
      array points : Point[3]
    }
    """
    mm = metamodel_for_language("item")
    assert mm is not None
    model = mm.model_from_str(text)
    assert model is not None
    items = get_children_of_type("Struct", model)
    assert len(items) == 4
コード例 #31
0
ファイル: object_processors.py プロジェクト: goto40/itemlang
def check_array_attribute(array_attribute):
    """
    check if array size depends only on attributes defined before it in
    the struct
    :param array_attribute:
    :return: None
    throws on error
    """
    from itemlang.metamodel_formula import ScalarRef
    dependencies = map(
        lambda x: x.ref0,
        reduce(
            lambda l1, l2: l1 + l2,
            map(lambda node: get_children_of_type(ScalarRef, node),
                array_attribute.array_dimensions), []))
    struct = array_attribute.parent
    index_of_array = struct.attributes.index(array_attribute)
    available_infos_until_this_array = struct.attributes[0:index_of_array]
    for d in dependencies:
        if not (d in available_infos_until_this_array):
            raise Exception(
                "array {}.{} depends on {}.{} not defined " +
                "before it in {}.".format(struct.name, array_attribute.name,
                                          struct.name, d.name,
                                          get_model(struct)._tx_filename))
コード例 #32
0
def do_test_diagram_history_states(diagram):
    transitions = textx.get_children_of_type("TransitionExpression", diagram._model)
    assert len(transitions) == 14

    assert transitions[8].dest.is_deep is False

    assert transitions[10].dest.parent_name == "State3"
    assert transitions[10].dest.is_deep is True
コード例 #33
0
def do_test_diagram_concurrent_state_horizontal(diagram):
    transitions = textx.get_children_of_type("TransitionExpression", diagram._model)
    assert len(transitions) == 10

    composites = textx.get_children_of_type("CompositeState", diagram._model)
    assert len(composites) == 0

    composites = textx.get_children_of_type("ParallelState", diagram._model)
    assert len(composites) == 1

    comp = composites[0]
    regions = comp.regions
    assert len(regions) == 3

    for r in regions:
        transitions = textx.get_children_of_type("TransitionExpression", r)
        assert len(transitions) == 3
コード例 #34
0
def test_model_with_circular_imports():
    """
    Basic test for FQNImportURI + circular imports
    """
    #################################
    # META MODEL DEF
    #################################

    my_meta_model = metamodel_from_file(
        join(abspath(dirname(__file__)),
             'interface_model1', 'Interface.tx'))
    my_meta_model.register_scope_providers(
        {"*.*": scoping_providers.FQNImportURI()})

    #################################
    # MODEL PARSING
    #################################

    my_model = my_meta_model.model_from_file(
        join(abspath(dirname(__file__)),
             "interface_model1", "model_c", "A.if"))

    #################################
    # TEST MODEL
    #################################

    imports = get_children_of_type("Import", my_model)
    assert len(imports) > 0
    for i in imports:
        assert 1 == len(i._tx_loaded_models)  # one file / load import
        assert i.importURI in i._tx_loaded_models[0]._tx_filename

    check_unique_named_object_has_class(my_model, "A", "Interface")
    a = get_unique_named_object(my_model, "A")

    a_self = get_children(lambda x: hasattr(x, 'name') and x.name == "self", a)
    assert len(a_self) == 1
    a_self = a_self[0]

    a_other = get_children(
        lambda x: hasattr(x, 'name') and x.name == "other", a)
    assert len(a_other) == 1
    a_other = a_other[0]

    a_other_self = get_children(
        lambda x: hasattr(x, 'name') and x.name == "self", a_other.ref)
    assert len(a_other_self) == 1
    a_other_self = a_other_self[0]

    a_other_other = get_children(
        lambda x: hasattr(x, 'name') and x.name == "other", a_other.ref)
    assert len(a_other_other) == 1
    a_other_other = a_other_other[0]

    assert a_self.ref == a_other_other.ref
    assert a_self.ref != a_other.ref
    assert a_other.ref == a_other_self.ref
    assert a_other.ref != a_other_other.ref
コード例 #35
0
def test_model_with_local_scope():
    """
    This is a basic test for the local scope provider (good case).
    """
    #################################
    # META MODEL DEF
    #################################

    my_meta_model = metamodel_from_file(
        join(abspath(dirname(__file__)), 'components_model1',
             'Components.tx'))
    my_meta_model.register_scope_providers({
        "*.*": scoping_providers.FQN(),
        "Connection.from_port":
            scoping_providers.RelativeName("from_inst.component.slots"),
        "Connection.to_port":
            scoping_providers.RelativeName("to_inst.component.slots"),
    })

    #################################
    # MODEL PARSING
    #################################

    my_model = my_meta_model.model_from_file(
        join(abspath(dirname(__file__)), "components_model1",
             "example.components"))

    #################################
    # TEST MODEL
    #################################

    # test local refs
    action2 = get_unique_named_object(my_model, "action2")
    action3 = get_unique_named_object(my_model, "action3")
    connections = get_children_of_type("Connection", my_model)
    selected_connections = list(filter(
        lambda x: x.from_inst == action2 and x.to_inst == action3,
        connections))
    assert len(selected_connections) == 1

    # test list of formats
    input2 = get_unique_named_object(my_model, "input2")
    assert len(input2.formats) == 3
    format_names = map(lambda x: x.name, input2.formats)
    assert "A" in format_names
    assert "B" in format_names
    assert "C" in format_names
    assert "D" not in format_names
コード例 #36
0
def test_textx_isinstace():
    grammar = \
        '''
    Model: a=A;
    A: B;
    B: C;
    C: x=ID;
    '''
    my_meta_model = metamodel_from_str(grammar)
    A = my_meta_model['A']
    B = my_meta_model['B']
    C = my_meta_model['C']
    my_model = my_meta_model.model_from_str("c")
    c = get_children_of_type("C", my_model)
    assert len(c) == 1
    c = c[0]
    assert textx_isinstance(c, C)
    assert textx_isinstance(c, B)
    assert textx_isinstance(c, A)
コード例 #37
0
def test_model_with_local_scope_and_inheritance2():
    """
    This is a more complicated test for the local scope provider.
    """
    #################################
    # META MODEL DEF
    #################################

    my_meta_model = metamodel_from_file(
        join(abspath(dirname(__file__)), 'components_model1',
             'Components.tx'))
    my_meta_model.register_scope_providers({
        "*.*": scoping_providers.FQN(),
        "Connection.from_port":
            scoping_providers.ExtRelativeName("from_inst.component",
                                              "slots",
                                              "extends"),
        "Connection.to_port":
            scoping_providers.ExtRelativeName("to_inst.component",
                                              "slots",
                                              "extends"),
    })

    #################################
    # MODEL PARSING
    #################################

    my_model = my_meta_model.model_from_file(
        join(abspath(dirname(__file__)),
             "components_model1", "example_inherit1.components"))

    #################################
    # TEST MODEL
    #################################

    # test inherited ports are same (direct inheritance)
    action1 = get_unique_named_object(my_model, "action1")
    action2 = get_unique_named_object(my_model, "action2")
    action3 = get_unique_named_object(my_model, "action3")
    end = get_unique_named_object(my_model, "end")
    connections = get_children_of_type("Connection", my_model)
    selected_connections_12 = list(filter(
        lambda x: x.from_inst == action1 and x.to_inst == action2,
        connections))
    selected_connections_3e = list(filter(
        lambda x: x.from_inst == action3 and x.to_inst == end,
        connections))
    assert len(selected_connections_12) == 1
    assert len(selected_connections_3e) == 1
    assert selected_connections_12[0].to_port is selected_connections_3e[0].\
        to_port  # output3 is same

    #################################
    # MODEL PARSING
    #################################

    my_model = my_meta_model.model_from_file(
        join(abspath(dirname(__file__)),
             "components_model1", "example_inherit2.components"))

    #################################
    # TEST MODEL
    #################################

    # test inherited ports are same
    # (indirect inheritance: Middle -> Start -> End)
    action1 = get_unique_named_object(my_model, "action1")
    action2 = get_unique_named_object(my_model, "action2")
    action3 = get_unique_named_object(my_model, "action3")
    end = get_unique_named_object(my_model, "end")
    connections = get_children_of_type("Connection", my_model)
    selected_connections_12 = list(filter(
        lambda x: x.from_inst == action1 and x.to_inst == action2,
        connections))
    selected_connections_3e = list(filter(
        lambda x: x.from_inst == action3 and x.to_inst == end, connections))
    assert len(selected_connections_12) == 1
    assert len(selected_connections_3e) == 1
    assert selected_connections_12[0].to_port is selected_connections_3e[0].\
        to_port  # output3 is same
コード例 #38
0
ファイル: drawing.py プロジェクト: igordejanovic/textX
def main(debug=False):

    from textx import metamodel_from_str, get_children_of_type

    grammar = """
    Model: commands*=DrawCommand;
    DrawCommand: MoveCommand | ShapeCommand;
    ShapeCommand: LineTo | Circle;
    MoveCommand: MoveTo | MoveBy;
    MoveTo: 'move' 'to' position=Point;
    MoveBy: 'move' 'by' vector=Point;
    Circle: 'circle' radius=INT;
    LineTo: 'line' 'to' point=Point;
    Point: x=INT ',' y=INT;
    """

    # We will provide our class for Point.
    # Classes for other rules will be dynamically generated.
    class Point(object):
        def __init__(self, parent, x, y):
            self.parent = parent
            self.x = x
            self.y = y

        def __str__(self):
            return "{},{}".format(self.x, self.y)

        def __add__(self, other):
            return Point(self.parent, self.x + other.x, self.y + other.y)

    # Create meta-model from the grammar. Provide `Point` class to be used for
    # the rule `Point` from the grammar.
    mm = metamodel_from_str(grammar, classes=[Point])

    model_str = """
        move to 5, 10
        line to 10, 10
        line to 20, 20
        move by 5, -7
        circle 10
        line to 10, 10
    """

    # Meta-model knows how to parse and instantiate models.
    model = mm.model_from_str(model_str)

    # At this point model is a plain Python object graph with instances of
    # dynamically created classes and attributes following the grammar.

    def cname(o):
        return o.__class__.__name__

    # Let's interpret the model
    position = Point(None, 0, 0)
    for command in model.commands:
        if cname(command) == 'MoveTo':
            print('Moving to position', command.position)
            position = command.position
        elif cname(command) == 'MoveBy':
            position = position + command.vector
            print('Moving by', command.vector, 'to a new position', position)
        elif cname(command) == 'Circle':
            print('Drawing circle at', position, 'with radius', command.radius)
        else:
            print('Drawing line from', position, 'to', command.point)
            position = command.point
    print('End position is', position)

    # Output:
    # Moving to position 5,10
    # Drawing line from 5,10 to 10,10
    # Drawing line from 10,10 to 20,20
    # Moving by 5,-7 to a new position 25,13
    # Drawing circle at 25,13 with radius 10
    # Drawing line from 25,13 to 10,10

    # Collect all points starting from the root of the model
    points = get_children_of_type("Point", model)
    for point in points:
        print('Point: {}'.format(point))
コード例 #39
0
 def get_all(model_repo, what):
     lst = []
     for m in model_repo.filename_to_model.values():
         lst = lst + get_children_of_type(what, m)
     return lst
コード例 #40
0
def test_inheritance_processor():
    """
    Basic test for ExtRelativeName (using an inheritance example)
    """
    #################################
    # META MODEL DEF
    #################################

    my_meta_model = metamodel_from_file(
        join(abspath(dirname(__file__)),
             'components_model1', 'Components.tx'))
    my_meta_model.register_scope_providers({
        "*.*": scoping_providers.FQN(),
        "Connection.from_port":
            scoping_providers.ExtRelativeName("from_inst.component",
                                              "slots",
                                              "extends"),
        "Connection.to_port":
            scoping_providers.ExtRelativeName("to_inst.component",
                                              "slots",
                                              "extends"),
    })

    #################################
    # MODEL PARSING
    #################################

    my_model = my_meta_model.model_from_file(
        join(abspath(dirname(__file__)),
             "components_model1", "example_inherit3.components"))

    #################################
    # TEST MODEL
    #################################

    components = get_children_of_type("Component", my_model)

    expected = """
        Start
        BaseProc
        ExtProc(BaseProc)
        Plus
        ExtProc2(Plus,ExtProc(BaseProc))
        End
        End2
    """

    def myformatter(compo):
        if len(compo.extends) == 0:
            return compo.name
        else:
            return compo.name + "(" + ",".join(map(lambda x: myformatter(x),
                                                   compo.extends)) + ")"

    res = "\n\n"
    # possibly in future version, the order need to be normalized...
    for c in components:
        res += myformatter(c) + "\n"

    print(res)
    assert re.sub(r'\s*', "", expected) == re.sub(r'\s*', "", res)