Beispiel #1
0
    def update_model(self, fit=False):
        """
        Parses code, updates model. If error is raised, highlight line and
        update statusbar.

        Args:
            fit(bool): If fit_in_view should be called
        """
        try:
            model = pyflies_mm.model_from_str(
                str(self.current_editor.toPlainText()))
            model._tx_filename = self.current_editor.filename
            self.current_editor.model = model

            dot_file = str(uuid.uuid4())
            if self.actionVisalizationMode.isChecked():
                model_export(model, dot_file)
            else:
                custom_export(model, dot_file)

            svg_file = "%s.jpg" % dot_file
            call(["dot", "-Tjpg", "-O", dot_file])
            self.current_graphview.scene().load_svg(svg_file)
            if fit:
                self.current_graphview.fit_in_view()
            os.remove(svg_file)
            os.remove(dot_file)
            self.statusbar.clearMessage()

        except TextXError as e:
            self.current_editor.highlight_error(e.line, e.col)
            self.statusbar.showMessage(str(e))
Beispiel #2
0
def test_multiple_imports():
    """
    Test that rules grammars imported from multiple places
    results in the same meta-class objects.
    """

    current_dir = os.path.dirname(__file__)
    mm = metamodel_from_file(os.path.join(current_dir,
                             'multiple', 'first.tx'))

    print(mm['First']._tx_attrs)
    print(mm['First']._tx_attrs['first'].cls._tx_attrs['second'].cls.__name__)
    print(mm['Third'])
    print(type(mm['First']._tx_attrs['first']))
    assert mm['First']._tx_attrs['first'].cls._tx_attrs['second'].cls \
        is mm['relative.third.Third']
    metamodel_export(mm, 'multipleimport_test_mm.dot')

    model = """
        first 1 2
        third "one" "two"
    """

    model = mm.model_from_str(model)
    model_export(model, 'multipleimport_test_model.dot')
    def parse(self, path, grammar_file_name, model_file_name, export_dot):
        meta_path = os.path.join(path, grammar_file_name)
        meta_name = os.path.splitext(meta_path)[0]
        type_builtins = {
            'int': SimpleType(None, 'Int'),
            'string': SimpleType(None, 'String'),
            'long': SimpleType(None, 'Long'),
            'double': SimpleType(None, 'Double'),
            'byte': SimpleType(None, 'Byte'),
            'float': SimpleType(None, 'Float'),
            'boolean': SimpleType(None, 'Boolean')
        }
        metamodel = metamodel_from_file(meta_path,
                                        classes=[SimpleType],
                                        builtins=type_builtins)
        obj_processors = {
            'Product': Parser.product_obj_processor,
            'Category': Parser.category_obj_processor,
            'Property': Parser.property_obj_processor
        }
        metamodel.register_obj_processors(obj_processors)
        metamodel.register_model_processor(Parser.check_some_semantics)

        if export_dot:
            metamodel_export(metamodel, meta_name + '.dot')

        model_path = os.path.join(path, model_file_name)
        model_name = os.path.splitext(model_path)[0]

        model = metamodel.model_from_file(model_path)

        if export_dot:
            model_export(model, model_name + '.dot')

        return model
Beispiel #4
0
def execute_for_web(path, grammar_file_name, query, export_dot, export_png):

    meta_path = os.path.join(path, grammar_file_name)
    meta_name = os.path.splitext(meta_path)[0]
    metamodel = metamodel_from_file(meta_path)

    if export_dot:
        metamodel_export(metamodel, meta_name + '.dot')
        if export_png:
            graph = pydot.graph_from_dot_file(meta_name + '.dot')
            #graph[0].write_png(meta_name + '.png')

    model = metamodel.model_from_str(query)
    model_name = ""
    if BASE_DIR.__contains__('/'):
        model_name = path + '/query'  # linux
    else:
        model_name = path + '\query'  # windows

    if export_dot:
        model_export(model, model_name + '.dot')
    if export_png:
        graph = pydot.graph_from_dot_file(model_name + '.dot')
        #graph[0].write_png(model_name + '.png')

    return model
Beispiel #5
0
def visualize(ctx, meta_model_file, model_file, ignore_case, output_format):
    """
    Generate .dot file(s) from meta-model and optionally model.
    """
    debug = ctx.obj['debug']
    meta_model, model = check_model(meta_model_file,
                                    model_file, debug, ignore_case)
    if output_format == 'plantuml':
        pu_file = "{}.pu".format(meta_model_file)
        click.echo("Generating '{}' file for meta-model.".format(pu_file))
        click.echo("To convert to png run 'plantuml {}'".format(pu_file))
        click.echo("To convert to svg run 'plantuml -tsvg {}'".format(pu_file))
        metamodel_export(meta_model, pu_file, PlantUmlRenderer())
    else:
        dot_file = "{}.dot".format(meta_model_file)
        click.echo("Generating '{}' file for meta-model.".format(dot_file))
        click.echo("To convert to png run 'dot -Tpng -O {}'".format(dot_file))
        metamodel_export(meta_model, dot_file)

    if model_file:
        if output_format == 'plantuml':
            raise Exception("plantuml is not supported for model files, yet.")
        dot_file = "{}.dot".format(model_file)
        click.echo("Generating '{}' file for model.".format(model_file))
        click.echo(
            "To convert to png run 'dot -Tpng -O {}'".format(model_file))
        model_export(model, dot_file)
Beispiel #6
0
    def update_model(self, fit=False):
        """
        Parses code, updates model. If error is raised, highlight line and
        update statusbar.

        Args:
            fit(bool): If fit_in_view should be called
        """
        try:
            model = pyflies_mm.model_from_str(
                str(self.current_editor.toPlainText()))
            model._filename = self.current_editor.filename
            self.current_editor.model = model

            dot_file = str(uuid.uuid4())
            if self.actionVisalizationMode.isChecked():
                model_export(model, dot_file)
            else:
                custom_export(model, dot_file)

            svg_file = "%s.jpg" % dot_file
            call(["dot", "-Tjpg", "-O", dot_file])
            self.current_graphview.scene().load_svg(svg_file)
            if fit:
                self.current_graphview.fit_in_view()
            os.remove(svg_file)
            os.remove(dot_file)
            self.statusbar.clearMessage()

        except TextXError as e:
            self.current_editor.highlight_error(e.line, e.col)
            self.statusbar.showMessage(str(e))
Beispiel #7
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)
Beispiel #8
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)
Beispiel #9
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)
Beispiel #10
0
def load_model(file_name):
    """Generates program model from '/examples' and returns it."""

    # current_dir = os.path.dirname(__file__)
    # __file__ is unbound in interactive mode

    current_dir = os.path.dirname(os.path.realpath(__file__)) 
    visualization_dir = os.path.join(current_dir, pymajorme_config.VISUALIZATION_DIR)
    if not os.path.exists(visualization_dir):
        os.makedirs(visualization_dir)

    # jorm_mm = entity_mm.get_entity_mm()

    jorm_mm = metamodel_from_file(os.path.join(current_dir, 'languages', 'pymajorme_language.tx'),
                                    classes=[javatype.JavaType],  # Register Entity class
                                    builtins=javatype.get_java_builtins(),
                                    debug=False)

    metamodel_export(jorm_mm, os.path.join(visualization_dir, 'jorm_metamodel.dot'))

    model = jorm_mm.model_from_file(os.path.join(current_dir, file_name))
 
    model_export(model, os.path.join(visualization_dir, 'jorm_model.dot'))

    return model
Beispiel #11
0
 def _visualize(self, fileName):
     fileType = self.get_file_type(fileName)
     if fileType == METAMODEL:
         # Get meta-model from language description
         try:
             self.meta_model = metamodel_from_file(fileName)
             if not self.graph_widget.isHidden():
                 # Export model to dot
                 path = os.path.join(PRJ_PATH, "meta.dot")
                 metamodel_export(self.meta_model, path)
                 svg_path = os.path.join(PRJ_PATH, "img", METAMODEL_SVG)
                 self.create_load_svg(
                     path, svg_path, file_manager.get_module_name(fileName),
                     0)
         except TextXError as error:
             self.handle_exception(fileName, 0, error.line)
     elif fileType == MODEL:
         if not self.graph_widget.isHidden():
             try:
                 self.model = self.meta_model.model_from_file(fileName)
                 path = os.path.join(PRJ_PATH, "model.dot")
                 model_export(self.model, path)
                 svg_path = os.path.join(PRJ_PATH, "img", MODEL_SVG)
                 self.create_load_svg(
                     path, svg_path, file_manager.get_module_name(fileName),
                     1)
             except TextXError as error:
                 self.handle_exception(fileName, 1, error.line)
Beispiel #12
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)
Beispiel #13
0
def execute(path, grammar_file_name, example_file_name, export_dot, export_png):
    '''U svrhe brzeg testiranja, metoda koja prima putanju do foldera, naziv fajla gde je gramatika i naziv fajla gde je
        primer programa u nasem jeziku i indikator da li da se eksportuju .dot i .png fajlovi'''

    meta_path = os.path.join(path, grammar_file_name)
    meta_name = os.path.splitext(meta_path)[0]
    metamodel = metamodel_from_file(meta_path)

    if export_dot:
        metamodel_export(metamodel, meta_name + '.dot')
        if export_png:
            graph = pydotplus.graph_from_dot_file(meta_name + '.dot')
            graph.write_png(meta_name + '.png')

    model_path = os.path.join(path, example_file_name)
    model_name = os.path.splitext(model_path)[0]

    model = metamodel.model_from_file(model_path)

    if export_dot:
        model_export(model, model_name + '.dot')
    if export_png:
        graph = pydotplus.graph_from_dot_file(model_name + '.dot')
        graph.write_png(model_name + '.png')

    return model
Beispiel #14
0
def execute(path, grammar_file_name, example_file_name, export_dot, export_png):
    """U svrhe brzeg testiranja, metoda koja prima putanju do foldera, naziv fajla gde je gramatika i naziv fajla gde je
        primer programa u nasem jeziku i indikator da li da se eksportuju .dot i .png fajlovi"""

    meta_path = os.path.join(SRC_DIR, 'model', grammar_file_name)
    meta_name = os.path.splitext(meta_path)[0]
    metamodel = metamodel_from_file(meta_path)

    if export_dot:
        metamodel_export(metamodel, meta_name + '.dot')
        if export_png:
            graph = pydot.graph_from_dot_file(meta_name + '.dot')
            graph.write_png(meta_name + '.png')

    model_path = os.path.join(path, example_file_name)
    model_name = os.path.splitext(model_path)[0]

    model = metamodel.model_from_file(model_path)

    if export_dot:
        model_export(model, model_name + '.dot')
    if export_png:
        graph = pydot.graph_from_dot_file(model_name + '.dot')
        graph.write_png(model_name + '.png')

    return model
Beispiel #15
0
def textx():
    """
    textx console command.
    """

    class MyParser(argparse.ArgumentParser):
        """
        Custom argument parser for printing help message in case of an error.
        See
        http://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu
        """
        def error(self, message):
            sys.stderr.write('error: %s\n' % message)
            self.print_help()
            sys.exit(2)

    parser = MyParser(description='textX checker and visualizer')
    parser.add_argument('cmd', help='Command - "check" or "visualize"')
    parser.add_argument('metamodel', help='Meta-model file name')
    parser.add_argument('model', help='Model file name', nargs='?')
    parser.add_argument('-i', help='case-insensitive parsing',
                        action='store_true')
    parser.add_argument('-d', help='run in debug mode',
                        action='store_true')

    args = parser.parse_args()

    if args.cmd not in ['visualize', 'check']:
        print("Unknown command {}. Command must be one of"
              " 'visualize', 'check'.".format(args.cmd))
        sys.exit(1)

    try:
        metamodel = metamodel_from_file(args.metamodel, ignore_case=args.i,
                                        debug=args.d)
        print("Meta-model OK.")
    except TextXError as e:
        print("Error in meta-model file.")
        print(e)
        sys.exit(1)

    if args.model:
        try:
            model = metamodel.model_from_file(args.model, debug=args.d)
            print("Model OK.")
        except TextXError as e:
            print("Error in model file.")
            print(e)
            sys.exit(1)

    if args.cmd == "visualize":
        print("Generating '%s.dot' file for meta-model." % args.metamodel)
        print("To convert to png run 'dot -Tpng -O %s.dot'" % args.metamodel)
        metamodel_export(metamodel, "%s.dot" % args.metamodel)

        if args.model:
            print("Generating '%s.dot' file for model." % args.model)
            print("To convert to png run 'dot -Tpng -O %s.dot'" % args.model)
            model_export(model, "%s.dot" % args.model)
Beispiel #16
0
def main(debug = False):
    metamodel_export(data_dsl_mm, join(this_folder, 'family-tree_meta.dot'))
    family_tree_model = data_dsl_mm.model_from_file(join(this_folder, "miljkovic.family"))
    model_export(family_tree_model, join(this_folder, 'family-tree.dot'))
    family_tree_to_txt = generator_for_language_target('family_tree_dsl', 'txt')
    family_tree_to_txt(data_dsl_mm, family_tree_model,this_folder,True)
    family_tree_to_html = generator_for_language_target('family_tree_dsl', 'html')
    family_tree_to_html(data_dsl_mm, family_tree_model,this_folder,True)
Beispiel #17
0
 def get_outline_model(self):
     this_folder = dirname(__file__)
     language = metamodel_from_file(join(dirname(__file__), 'outline.tx'))
     metamodel_export(language, join(dirname(__file__), 'outline.dot'))
     grammar_model = language.model_from_file(
         join(this_folder, 'outline.ol'))
     model_export(grammar_model, join(this_folder, 'outline.dot'))
     return grammar_model
Beispiel #18
0
def main(debug=False):
    entity_mm = get_entity_mm(debug)
    dot_folder = join(this_folder, 'dotexport')
    if not os.path.exists(dot_folder):
        os.mkdir(dot_folder)
    metamodel_export(entity_mm, join(dot_folder, 'entity_meta.dot'))
    Car_model = entity_mm.model_from_file(join(this_folder, 'Car.ent'))
    model_export(Car_model, join(dot_folder, 'Car.dot'))
Beispiel #19
0
def textx():
    """
    textx console command
    """

    class MyParser(argparse.ArgumentParser):
        """
        Custom arugment parser for printing help message in case of error.
        See http://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argu
        """
        def error(self, message):
            sys.stderr.write('error: %s\n' % message)
            self.print_help()
            sys.exit(2)

    parser = MyParser(description='textX checker and visualizer')
    parser.add_argument('cmd', help='Command - "check" or "visualize"')
    parser.add_argument('metamodel', help='Meta-model file name')
    parser.add_argument('model', help='Model file name', nargs='?')
    parser.add_argument('-i', help='case-insensitive parsing',
                        action='store_true')
    parser.add_argument('-d', help='run in debug mode',
                        action='store_true')

    args = parser.parse_args()

    if args.cmd not in ['visualize', 'check']:
        print("Unknown command {}. Command must be one of"
              " 'visualize', 'check'.".format(args.cmd))
        sys.exit(1)

    try:
        metamodel = metamodel_from_file(args.metamodel, ignore_case=args.i,
                                        debug=args.d)
        print("Meta-model OK.")
    except TextXError as e:
        print("Error in meta-model file.")
        print(e)
        sys.exit(1)

    if args.model:
        try:
            model = metamodel.model_from_file(args.model, debug=args.d)
            print("Model OK.")
        except TextXError as e:
            print("Error in model file.")
            print(e)
            sys.exit(1)

    if args.cmd == "visualize":
        print("Generating '%s.dot' file for meta-model." % args.metamodel)
        print("To convert to png run 'dot -Tpng -O %s.dot'" % args.metamodel)
        metamodel_export(metamodel, "%s.dot" % args.metamodel)

        if args.model:
            print("Generating '%s.dot' file for model." % args.model)
            print("To convert to png run 'dot -Tpng -O %s.dot'" % args.model)
            model_export(model, "%s.dot" % args.model)
Beispiel #20
0
def main(debug=False):

    this_folder = dirname(__file__)

    pyflies_mm = metamodel_from_file(join(this_folder,'pyflies.tx'), debug=debug)
    metamodel_export(pyflies_mm, join(this_folder, 'pyflies_meta.dot'))

    experiment = pyflies_mm.model_from_file(join(this_folder, 'experiment.pf'))
    model_export(experiment, join(this_folder, 'experiment.dot'))
Beispiel #21
0
 def get_outline_model(self):
     this_folder = dirname(__file__)
     language = metamodel_from_file(
         join(dirname(__file__), 'resources', 'outline.tx'))
     metamodel_export(language, join(dirname(__file__), 'outline.dot'))
     grammar_model = language.model_from_file(
         self.configuration.outline_path)
     model_export(grammar_model, join(this_folder, 'outline.dot'))
     return grammar_model
Beispiel #22
0
def getmodel(debug=False):
    this_folder = dirname(__file__)
    bt_mm = metamodel_from_file(join(this_folder, 'BinaryTree.tx'),
                                debug=False)
    metamodel_export(bt_mm, join(this_folder, 'bt_meta.dot'))
    bt_model = bt_mm.model_from_file(join(this_folder, 'temp.bt'))
    model_export(bt_model, join(this_folder, 'temp.dot'))
    binarytree = BinaryTree()
    binarytree.interpret(bt_model)
    return binarytree
Beispiel #23
0
def main():

    mm = get_metamodel()

    dot_folder = join(this_folder, 'dotexport')
    if not os.path.exists(dot_folder):
        os.mkdir(dot_folder)
    metamodel_export(mm, join(dot_folder, 'term.dot'))

    model = mm.model_from_file('model/model.term')
    model_export(model, join(dot_folder, 'model.dot'))
Beispiel #24
0
def createDotFiles(form_mm,form_model,dotFolder):
    # Export to .dot file for visualization
    metamodel_export(form_mm, join(dotFolder, 'form_meta.dot'))
    # Export to .dot file for visualization
    model_export(form_model, join(dotFolder, 'form.dot'))

    (graph,) = pydot.graph_from_dot_file(join(dotFolder,'form_meta.dot'))
    graph.write_png(join(dotFolder,'form_meta.png'))
    
    (graph,) = pydot.graph_from_dot_file(join(dotFolder,'form.dot'))
    graph.write_png(join(dotFolder,'form.png'))
Beispiel #25
0
def test_issue_14():
    """
    Test object processors in context of match rules with base types.
    """

    grammar = """
        Program:
        'begin'
            commands*=Command
        'end'
        ;

        Command:
        InitialCommand | InteractCommand
        ;

        InitialCommand:
        'initial' x=INT ',' y=INT
        ;

        InteractCommand:
            'sleep' | NUMBER | BOOL | STRING
        ;
    """
    # note: you can also use "STRICTFLOAT | INT" instead of "NUMBER"

    mm = metamodel_from_str(grammar)
    metamodel_export(mm, 'test_issue_14_metamodel.dot')

    # Error happens only when there are obj. processors registered
    mm.register_obj_processors({'InitialCommand': lambda x: x})

    model_str = """
        begin
            initial 2, 3
            sleep
            34
            4.3
            true
            "a string"
        end
    """
    model = mm.model_from_str(model_str)
    model_export(model, 'test_issue_14_model.dot')
    assert model.commands[0].x == 2
    assert model.commands[0].y == 3
    assert model.commands[1] == 'sleep'
    assert model.commands[2] == 34
    assert model.commands[3] == 4.3
    assert model.commands[4] is True
    assert model.commands[5] == "a string"
Beispiel #26
0
 def wrapper(*args, **kwargs):
     errors, uri, model = func(*args, **kwargs)
     if (len(errors) == 0):
         file_name = os.path.basename(uri)
         dot_file_name = 'dot/' + file_name.replace(".st", "") + '.dot'
         try:
             model_export(model, dot_file_name)
             check_call([
                 'dot', '-Tpng', dot_file_name, '-o',
                 'images/' + file_name.replace(".st", "") + '.png'
             ])
         except:
             return errors, uri, model
     return errors, uri, model
Beispiel #27
0
def main(debug=False):

    entity_mm = get_entity_mm(debug)

    # Exportar a archivo .dot para visualización
    dot_folder = join(this_folder, 'dotexport')
    if not os.path.exists(dot_folder):
        os.mkdir(dot_folder)
    metamodel_export(entity_mm, join(dot_folder, 'entity_meta.dot'))

    # Construir modelo de persona a partir del archivo person.ent
    person_model = entity_mm.model_from_file(join(this_folder, 'biblioteca.ent'))

    # Exportar a archivo .dot para visualización
    model_export(person_model, join(dot_folder, 'biblioteca.dot'))
Beispiel #28
0
def main(debug=False):

    this_folder = dirname(__file__)

    robot_mm = metamodel_from_file(join(this_folder, 'robot.tx'), debug=False)
    metamodel_export(robot_mm, join(this_folder, 'robot_meta.dot'))

    # Register object processor for MoveCommand
    robot_mm.register_obj_processors({'MoveCommand': move_command_processor})

    robot_model = robot_mm.model_from_file(join(this_folder, 'program.rbt'))
    model_export(robot_model, join(this_folder, 'program.dot'))

    robot = Robot()
    robot.interpret(robot_model)
Beispiel #29
0
def main(debug=False):

    entity_mm = get_entity_mm(debug)

    #Exporta el archivo .dot para visualizarlo.
    dot_folder = join(this_folder, 'diagramas')
    if not os.path.exists(dot_folder):
        os.mkdir(dot_folder)
    metamodel_export(entity_mm, join(dot_folder, 'entidades.dot'))

    #Se construye un modelo person del archivo almacen.ent.
    person_model = entity_mm.model_from_file(join(this_folder, 'almacen.ent'))

    #Exporta el archivo .dot para visualizarlo.
    model_export(person_model, join(dot_folder, 'almacen.dot'))
Beispiel #30
0
def main(debug=False):

    entity_mm = get_entity_mm(debug)

    # Export to .dot file for visualization
    dot_folder = join(this_folder, 'dotexport')
    if not os.path.exists(dot_folder):
        os.mkdir(dot_folder)
    metamodel_export(entity_mm, join(dot_folder, 'entity_meta.dot'))

    # Build Person model from person.ent file
    person_model = entity_mm.model_from_file(join(this_folder, 'person.ent'))

    # Export to .dot file for visualization
    model_export(person_model, join(dot_folder, 'person.dot'))
Beispiel #31
0
def model_generate_dot(metamodel, model, output_path, overwrite, debug):
    "Generating dot visualizations from arbitrary models"

    input_file = model._tx_filename
    base_dir = output_path if output_path else os.path.dirname(input_file)
    base_name, _ = os.path.splitext(os.path.basename(input_file))
    output_file = os.path.abspath(
        os.path.join(base_dir, "{}.{}".format(base_name, 'dot')))
    if overwrite or not os.path.exists(output_file):
        click.echo('-> {}'.format(output_file))
        model_export(model, output_file)
        click.echo('   To convert to png run "dot -Tpng -O {}"'
                   .format(os.path.basename(output_file)))
    else:
        click.echo('-- Skipping: {}'.format(output_file))
def main(debug=False):

    entity_mm = get_entity_mm(debug)

    # Export to .dot file for visualization
    dot_folder = join(this_folder, 'dotexport')
    if not os.path.exists(dot_folder):
        os.mkdir(dot_folder)
    metamodel_export(entity_mm, join(dot_folder, 'entity_meta.dot'))

    # Build database model from tablatest.ent file
    database_model = entity_mm.model_from_file(join(this_folder, 'tablatest.ent'))

    # Export to .dot file for visualization
    model_export(database_model, join(dot_folder, 'tablatest.dot'))
Beispiel #33
0
def main(debug=False):

    entity_mm = get_entity_mm(debug)

    # Export to .dot file for visualization
    dot_folder = join(this_folder, 'dotexport')
    if not os.path.exists(dot_folder):
        os.mkdir(dot_folder)
    metamodel_export(entity_mm, join(dot_folder, 'entity_meta.dot'))

    # Build Person model from person.ent file
    person_model = entity_mm.model_from_file(join(this_folder, 'Banda.ent'))

    # Export to .dot file for visualization
    model_export(person_model, join(dot_folder, 'Banda.dot'))
Beispiel #34
0
def main(debug=False):

    this_folder = dirname(__file__)

    robot_mm = metamodel_from_file(join(this_folder, 'robot.tx'), debug=False)
    metamodel_export(robot_mm, join(this_folder, 'robot_meta.dot'))

    # Register object processor for MoveCommand
    robot_mm.register_obj_processors({'MoveCommand': move_command_processor})

    robot_model = robot_mm.model_from_file(join(this_folder, 'program.rbt'))
    model_export(robot_model, join(this_folder, 'program.dot'))

    robot = Robot()
    robot.interpret(robot_model)
Beispiel #35
0
def main(debug=False):

    categoria_mm = get_categoria_mm(debug)

    # Export to .dot file for visualization
    dot_folder = join(this_folder, 'dotexport')
    if not os.path.exists(dot_folder):
        os.mkdir(dot_folder)
    metamodel_export(categoria_mm, join(dot_folder, 'categoria_meta.dot'))

    # Build Person model from person.ent file
    modelo_categoria = categoria_mm.model_from_file(
        join(this_folder, 'tienda.ent'))

    # Export to .dot file for visualization
    model_export(modelo_categoria, join(dot_folder, 'tienda.dot'))
Beispiel #36
0
def main(debug=False):

    this_folder = dirname(__file__)

    # Get meta-model from language description
    hello_meta = metamodel_from_file(join(this_folder, 'hello.tx'), debug=debug)

    # Optionally export meta-model to dot
    metamodel_export(hello_meta, join(this_folder, 'hello_meta.dot'))

    # Instantiate model
    example_hello_model = hello_meta.model_from_file(
        join(this_folder, 'example.hello'))

    # Optionally export model to dot
    model_export(example_hello_model, join(this_folder, 'example.dot'))
Beispiel #37
0
def main(debug=False):

    entity_mm = get_smart_home_mm(debug)

    # Export to .dot file for visualization
    dot_folder = join(this_folder, 'dotexport')
    if not os.path.exists(dot_folder):
        os.mkdir(dot_folder)
    metamodel_export(entity_mm, join(dot_folder, 'smart_home_meta.dot'))

    # Build Person model from smart_home.ev file
    smart_home_model = entity_mm.model_from_file(
        join(this_folder, 'smart_home.shome'))

    # Export to .dot file for visualization
    model_export(smart_home_model, join(dot_folder, 'smart_home.dot'))
def main(debug=False):

    entity_mm = get_entity_mm(debug)

    # Export to .dot file for visualization
    dot_folder = join(this_folder, 'diagram')
    if not os.path.exists(dot_folder):
        os.mkdir(dot_folder)
    metamodel_export(entity_mm, join(dot_folder, 'entidades.dot'))

    # Build Person model from person.ent file
    restaurante = entity_mm.model_from_file(
        join(this_folder, 'restaurante.ent'))

    # Export to .dot file for visualization
    model_export(restaurante, join(dot_folder, 'entidades.dot'))
Beispiel #39
0
def main():

    # get input arguments
    parser = argparse.ArgumentParser(prog='d_generator')
    parser.add_argument('-m',
                        nargs='?',
                        help='Path to application dgdl model file')
    parser.add_argument('-s',
                        nargs='?',
                        help='Path to desired generation source directory')

    args = parser.parse_args()

    arguments = {'model_path': args.m, 'srcgen': args.s}

    # create metamodel and model
    entity_mm = get_entity_mm()
    application_model = entity_mm.model_from_file(arguments['model_path'])
    semantic_analysis(application_model)

    # find or create source directory
    srcgen_folder = arguments['srcgen']
    if not exists(srcgen_folder):
        mkdir(srcgen_folder)

    # create application object
    appDTO = applicationToDto(application_model)
    plugin_params = (appDTO, srcgen_folder, abspath(arguments['model_path']))

    # run database generator
    db_generator = get_generator(appDTO.configObject.database,
                                 'database_generator', plugin_params)
    db_generator.generate_code()

    # run backend generator
    backend_generator = get_generator(appDTO.configObject.server,
                                      'backend_generator', plugin_params)
    backend_generator.generate_code()

    # run frontend generator
    frontend_generator = get_generator(appDTO.configObject.frontend,
                                       'frontend_generator', plugin_params)
    frontend_generator.generate_code()

    # export model and metamodel description files
    metamodel_export(entity_mm, 'metamodel.dot')
    model_export(application_model, 'model.dot')
Beispiel #40
0
def get_semantic_model_from_file(applang_file, metamodel_file, export_to_dot=False):
    metamodel = metamodel_from_file(metamodel_file)
    if export_to_dot:
        print_log('Exporting metamodel to dot')
        metamodel_export(metamodel, 'applang_metamodel.dot')
        print_log('Exporting metamodel to dot completed')
    model = metamodel.model_from_file(applang_file)

    print_log('Checking model semantics')
    model = check_semantics(model, metamodel)
    print_log('Checking model semantics completed')

    if export_to_dot:
        print_log('Exporting model to dot')
        model_export(model, 'applang_model.dot')
        print_log('Exporting model to dot completed')
    return model
Beispiel #41
0
def main(debug=False):

    this_folder = dirname(__file__)

    # Create metamodel from textX description
    scrum_mm = get_scrum_mm(debug)

    # Export to dot
    # Create png image with: dot -Tpng -O workflow_meta.dot
    metamodel_export(scrum_mm, join(this_folder, 'Models/scrum_meta.dot'))

    # Load example model
    example = scrum_mm.model_from_file(join(this_folder, 'example.sr'))

    # Export to dot
    # Create png image with: dot -Tpng -O example.dot
    model_export(example, join(this_folder, 'Models/example.dot'))
Beispiel #42
0
def main(debug=False):

    this_folder = dirname(__file__)

    # Get meta-model from language description
    hello_meta = metamodel_from_file(join(this_folder, 'hello.tx'),
                                     debug=debug)

    # Optionally export meta-model to dot
    metamodel_export(hello_meta, join(this_folder, 'hello_meta.dot'))

    # Instantiate model
    example_hello_model = hello_meta.model_from_file(
        join(this_folder, 'example.hello'))

    # Optionally export model to dot
    model_export(example_hello_model, join(this_folder, 'example.dot'))
def mean_model(file_name):
    """Generates program model from '/examples' and returns it."""

    # current_dir = os.path.dirname(__file__)
    # __file__ is unbound in interactive mode
    current_dir = os.getcwd()
    visualization_dir = os.path.join(current_dir, mean_gen_config.VISUALIZATION_DIR)
    if not os.path.exists(visualization_dir):
        os.makedirs(visualization_dir)

    mean_mm = metamodel_from_file(os.path.join(current_dir, 'lang', 'mean.tx'))
    metamodel_export(mean_mm, os.path.join(visualization_dir, 'mean_meta.dot'))

    app = mean_mm.model_from_file(os.path.join(current_dir, 'examples',
                                               file_name))
    model_export(app, os.path.join(visualization_dir, 'clue-example.dot'))

    return app
Beispiel #44
0
def main(debug=False):

    this_folder = dirname(__file__)

    # Create metamodel from textX description
    workflow_mm = metamodel_from_file(
        join(this_folder, 'workflow.tx'), debug=debug)

    # Export to dot
    # Create png image with: dot -Tpng -O workflow_meta.dot
    metamodel_export(workflow_mm, join(this_folder, 'workflow_meta.dot'))

    # Load example model
    example = workflow_mm.model_from_file(join(this_folder, 'example.wf'))

    # Export to dot
    # Create png image with: dot -Tpng -O example.dot
    model_export(example, join(this_folder, 'example.dot'))
Beispiel #45
0
def test_issue_14():
    """
    Test object processors in context of match rules with base types.
    """

    grammar = """
        Program:
        'begin'
            commands*=Command
        'end'
        ;

        Command:
        InitialCommand | InteractCommand
        ;

        InitialCommand:
        'initial' x=INT ',' y=INT
        ;

        InteractCommand:
            'sleep' | INT | FLOAT | BOOL | STRING
        ;
    """

    mm = metamodel_from_str(grammar)
    metamodel_export(mm, 'test_issue_14_metamodel.dot')

    # Error happens only when there are obj. processors registered
    mm.register_obj_processors({'InitialCommand': lambda x: x})

    model_str = """
        begin
            initial 2, 3
            sleep
            34
            4.3
            true
            "a string"
        end
    """
    model = mm.model_from_str(model_str)
    model_export(model, 'test_issue_14_model.dot')
Beispiel #46
0
def test_import():
    """
    Test grammar import.
    """

    current_dir = os.path.dirname(__file__)
    mm = metamodel_from_file(os.path.join(current_dir,
                             'relativeimport', 'first.tx'))
    metamodel_export(mm, 'import_test_mm.dot')

    model = """
    first
        second "1" "2"
        third true false true 12 false
    endfirst
    """

    model = mm.model_from_str(model)
    model_export(model, 'import_test_model.dot')
Beispiel #47
0
def main(debug=False):

    this_folder = dirname(__file__)

    json_mm = metamodel_from_file(join(this_folder, 'json.tx'), debug=debug)
    metamodel_export(json_mm, join(this_folder, 'json.tx.dot'))

    model1 = json_mm.model_from_file(join(this_folder, 'example1.json'))
    model_export(model1, join(this_folder, 'example1.json.dot'))

    model2 = json_mm.model_from_file(join(this_folder, 'example2.json'))
    model_export(model2, join(this_folder, 'example2.json.dot'))

    model3 = json_mm.model_from_file(join(this_folder, 'example3.json'))
    model_export(model3, join(this_folder, 'example3.json.dot'))

    model4 = json_mm.model_from_file(join(this_folder, 'example4.json'))
    model_export(model4, join(this_folder, 'example4.json.dot'))

    model5 = json_mm.model_from_file(join(this_folder, 'example5.json'))
    model_export(model5, join(this_folder, 'example5.json.dot'))
Beispiel #48
0
from textx.metamodel import metamodel_from_file
from textx.export import metamodel_export, model_export

# Create metamodel from textX description
workflow_mm = metamodel_from_file('workflow.tx')
# Export to dot
# Create png image with: dot -Tpng -O workflow_meta.dot
metamodel_export(workflow_mm, 'workflow_meta.dot')

# Load example model
example = workflow_mm.model_from_file('example.wf')
# Export to dot
# Create png image with: dot -Tpng -O example.dot
model_export(example, 'example.dot')

Beispiel #49
0
from textx.metamodel import metamodel_from_file
from textx.export import metamodel_export, model_export

pyflies_mm = metamodel_from_file(
    '../../pyflies/lang/pyflies.tx')
metamodel_export(pyflies_mm, 'pyflies_meta.dot')

experiment = pyflies_mm.model_from_file('EriksenFlanker.pf')
model_export(experiment, 'EriksenFlanker.dot')

Beispiel #50
0
        "import model.elements.Elipsa;",
        "import model.elements.Pravougaonik;",
        "import model.elements.Trougao;",
        "import model.elements.Linija;",
        "import model.elements.ZaobljeniPravougaonik;",
        "import view.MainFrame;",
    ]
    return importList


if __name__ == "__main__":

    metamodel = metamodel_from_file("language_definition.tx")
    metamodel_export(metamodel, "meta.dot")
    graph = pydot.graph_from_dot_file("meta.dot")
    graph.write_png("meta.png")

    model = metamodel.model_from_file("example.cafe")
    model_export(model, "model.dot")
    graph = pydot.graph_from_dot_file("model.dot")
    graph.write_png("model.png")

    interpreter = Interpreter(model)
    interpreter.interpret()
    konkretanKafic = interpreter.kafic
    generator.generate(
        "painter_template.java",
        "CafePainter.java",
        {"canvas": model, "imports": javaPackageAndImports(), "kafic": konkretanKafic},
    )
Beispiel #51
0
            self.events.append(Event(action, self.home_team.getPoints(), self.away_team.getPoints(), eventTeam, ""))
        else :
            self.events.append(Event(action, self.home_team.getPoints(), self.away_team.getPoints(), eventTeam, coach))

    def getGameObject(self):
        return Game(game_info=self.game_info, home_team=self.home_team, away_team=self.away_team, events=self.events)

if __name__ == '__main__':

    basket_metamodel = metamodel_from_file('textX/grammar.tx', debug=False)
    metamodel_export(basket_metamodel, 'output/basketStats_meta.dot')
    graph = pydot.graph_from_dot_file('output/basketStats_meta.dot')
    graph.write_png('output/basketStats_meta.png')

    basket_model = basket_metamodel.model_from_file('textX/game.tx')
    model_export(basket_model, 'output/basketStats_model.dot')
    graph = pydot.graph_from_dot_file('output/basketStats_model.dot')
    graph.write_png('output/basketStats_model.png')

    basket = Basket()
    basket.interpret(basket_model)

    env = Environment(trim_blocks=True, lstrip_blocks=True, loader=PackageLoader("basket", "templates"))

    template = env.get_template("statsTemplate.html")
    t = template.render(game=basket.getGameObject())
    print(t)
    
      
   
    out = open("output/stats.html", "w") 
Beispiel #52
0
                dir = c.direction
                print("Going {} for {} step(s).".format(dir, c.steps))

                move = {
                    "up": (0, 1),
                    "down": (0, -1),
                    "left": (-1, 0),
                    "right": (1, 0)
                }[dir]

                # Calculate new robot position
                self.x += c.steps * move[0]
                self.y += c.steps * move[1]

            print(self)

if __name__ == "__main__":

    robot_mm = metamodel_from_file('robot.tx', debug=False)
    metamodel_export(robot_mm, 'robot_meta.dot')

    # Register object processor for MoveCommand
    robot_mm.register_obj_processors({'MoveCommand': move_command_processor})

    robot_model = robot_mm.model_from_file('program.rbt')
    model_export(robot_model, 'program.dot')

    robot = Robot()
    robot.interpret(robot_model)

Beispiel #53
0
def main(debug=False):

    calc_mm = metamodel_from_str(grammar, auto_init_attributes=False,
                                 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'))

    # test whether x is an instance of a certain rule
    # note that it is different than comparing to x.__class__.__name__
    # because the latter only tests for the most derived type and
    # wont be helpful for abstract rules
    def _is(x, rule):
        return textx_isinstance(x, calc_mm[rule])

    def assertIs(x, rule):
        assert _is(x, rule), 'Unexpected object "{}" to rule "{}"'\
                    .format(x, type(x), rule)

    def evaluate(x):

        if isinstance(x, float):
            return x

        elif _is(x, 'Expression'):
            ret = evaluate(x.operands[0])

            for operator, operand in zip(x.operators,
                                         x.operands[1:]):
                if operator == '+':
                    ret += evaluate(operand)
                else:
                    ret -= evaluate(operand)
            return ret

        elif _is(x, 'Term'):
            ret = evaluate(x.operands[0])

            for operator, operand in zip(x.operators,
                                         x.operands[1:]):
                if operator == '*':
                    ret *= evaluate(operand)
                else:
                    ret /= evaluate(operand)
            return ret

        elif _is(x, 'Factor'):
            value = evaluate(x.op)
            return -value if x.sign == '-' else value

        elif _is(x, 'Operand'):
            if _is(x, 'PrimitiveOperand'):
                if x.op_num is not None:
                    return x.op_num
                elif x.op_id:
                    if x.op_id in namespace:
                        return namespace[x.op_id]
                    else:
                        raise Exception('Unknown variable "{}" at position {}'
                                        .format(x.op_id, x._tx_position))
            else:
                assertIs(x, 'CompoundOperand')
                return evaluate(x.expression)

        elif _is(x, 'Calc'):
            for a in x.assignments:
                namespace[a.variable] = evaluate(a.expression)

            return evaluate(x.expression)

        else:
            assert False, 'Unexpected object "{}" of type "{}"'\
                    .format(x, type(x))

    result = evaluate(model)

    assert (result - 6.93805555) < 0.0001
    print("Result is", result)
Beispiel #54
0
from textx.metamodel import metamodel_from_file
from textx.export import metamodel_export, model_export

pyflies_mm = metamodel_from_file('pyflies.tx', debug=True)
metamodel_export(pyflies_mm, 'pyflies_meta.dot')

experiment = pyflies_mm.model_from_file('experiment.pf')
model_export(experiment, 'experiment.dot')

Beispiel #55
0
    Builds and returns a meta-model for Entity language.
    """
    # Built-in primitive types
    # Each model will have this entities during reference resolving but
    # these entities will not be a part of `entities` list of EntityModel.
    entity_builtins = {
            'integer': Entity(None, 'integer', []),
            'string': Entity(None, 'string', [])
    }
    entity_mm = metamodel_from_file('entity.tx',
                                    classes=[Entity],  # Register Entity class
                                    builtins=entity_builtins,
                                    debug=False)

    return entity_mm

if __name__ == "__main__":

    entity_mm = get_entity_mm()

    # Export to .dot file for visualization
    metamodel_export(entity_mm, 'dotexport/entity_meta.dot')

    # Build Person model from person.ent file
    person_model = entity_mm.model_from_file('person.ent')

    # Export to .dot file for visualization
    model_export(person_model, 'dotexport/entity.dot')


Beispiel #56
0
from textx.metamodel import metamodel_from_file
from textx.export import metamodel_export
from textx.export import model_export
hello_meta = metamodel_from_file('hello.tx')
metamodel_export(hello_meta, 'hello_meta.dot')

example_hello_model = hello_meta.model_from_file('example.hello')
model_export(example_hello_model, 'example.dot')
Beispiel #57
0
from textx.metamodel import metamodel_from_file
from textx.export import metamodel_export
from textx.export import model_export
coshh_meta = metamodel_from_file('coshh.tx')
metamodel_export(coshh_meta, 'coshh.dot')
example_coshh_model = coshh_meta.model_from_file('test.coshh')
model_export(example_coshh_model, 'coshh_example.dot')
Beispiel #58
0
from textx.metamodel import metamodel_from_file
from textx.export import metamodel_export, model_export

pyflies_mm = metamodel_from_file("../../pyflies/lang/pyflies.tx")
metamodel_export(pyflies_mm, "pyflies_meta.dot")

experiment = pyflies_mm.model_from_file("ref_experiment.pf")
model_export(experiment, "ref_experiment.dot")