Exemple #1
0
def test_custom_filter_and_test(gen_paths):  # type: ignore
    root_path = str(gen_paths.dsdl_dir / Path("uavcan"))
    output_path = gen_paths.out_dir / 'filter_and_test'
    compound_types = read_namespace(root_path, [])
    language_context = LanguageContext(extension='.json')
    namespace = build_namespace_tree(compound_types, root_path, output_path,
                                     language_context)
    template_path = gen_paths.templates_dir / Path('custom_filter_and_test')
    generator = Generator(
        namespace,
        templates_dir=template_path,
        additional_filters={'custom_filter': lambda T: 'hi mum'},
        additional_tests={'custom_test': lambda T: True})

    generator.generate_all()
    outfile = gen_paths.find_outfile_in_namespace(
        "uavcan.time.SynchronizedTimestamp", namespace)

    assert (outfile is not None)

    with open(str(outfile), 'r') as json_file:
        json_blob = json.load(json_file)

    assert json_blob is not None
    assert json_blob['filter_result'] == 'hi mum'
    assert json_blob['test_result'] == 'yes'
Exemple #2
0
def test_python_filter_imports_for_array_type(gen_paths, stropping,
                                              sort):  # type: ignore
    lctx = LanguageContext()
    lctx.config.set('nunavut.lang.py', 'enable_stropping', str(stropping))

    uavcan_dir = str(gen_paths.dsdl_dir / pathlib.Path('uavcan'))
    type_map = read_namespace(str(gen_paths.dsdl_dir / pathlib.Path('new')),
                              [uavcan_dir])

    assert len(type_map) == 2

    from nunavut.lang.py import filter_imports

    test_subject = next(
        filter(lambda type: (type.short_name == 'hotness'), type_map))
    imports = filter_imports(lctx.get_language('nunavut.lang.py'),
                             test_subject,
                             sort=sort)
    assert len(imports) == 3
    assert 'new' == imports[0]
    if stropping:
        assert 'uavcan.str_' == imports[1]
    else:
        assert 'uavcan.str' == imports[1]
    assert 'uavcan.time' == imports[2]
Exemple #3
0
def _test_common_namespace(gen_paths, target_language: str = 'js', extension: str = '.json'):  # type: ignore
    root_namespace_dir = gen_paths.dsdl_dir / pathlib.Path("uavcan")
    root_namespace = str(root_namespace_dir)
    return nunavut.build_namespace_tree(pydsdl.read_namespace(root_namespace, []),
                                        root_namespace_dir,
                                        gen_paths.out_dir,
                                        LanguageContext(target_language, extension=extension))
Exemple #4
0
def test_get_templates(gen_paths):  # type: ignore
    """
    Verifies the nunavut.jinja.DSDLCodeGenerator.get_templates() method.
    """
    root_namespace_dir = gen_paths.dsdl_dir / Path("uavcan")
    root_namespace = str(root_namespace_dir)
    serializable_types = read_namespace(root_namespace, [])
    language_context = LanguageContext(extension='.json')
    namespace = build_namespace_tree(serializable_types,
                                     root_namespace_dir,
                                     gen_paths.out_dir,
                                     language_context)
    generator = DSDLCodeGenerator(namespace, templates_dir=gen_paths.templates_dir)

    templates = generator.get_templates()

    count = 0
    for template in templates:
        count += 1
    assert count > 0

    # Do it twice just to cover in-memory cache
    templates = generator.get_templates()

    count = 0
    for template in templates:
        count += 1
    assert count > 0
Exemple #5
0
def ptest_lang_cpp(gen_paths, implicit):  # type: ignore
    """Generates and verifies JSON with values filtered using the cpp language module.
    """

    root_namespace_dir = gen_paths.dsdl_dir / Path("langtest")
    root_namespace = str(root_namespace_dir)
    compound_types = read_namespace(root_namespace, [], allow_unregulated_fixed_port_id=True)
    if implicit:
        templates_dirs = [gen_paths.templates_dir / Path("implicit") / Path("cpp")]
    else:
        templates_dirs = [gen_paths.templates_dir / Path("explicit")]

    templates_dirs.append(gen_paths.templates_dir / Path("common"))

    language_context = LanguageContext('cpp' if implicit else None, '.hpp' if not implicit else None)

    namespace = build_namespace_tree(compound_types,
                                     root_namespace_dir,
                                     gen_paths.out_dir,
                                     language_context)

    generator = Generator(namespace,
                          templates_dir=templates_dirs)

    generator.generate_all(False)

    # Now read back in and verify
    outfile = gen_paths.find_outfile_in_namespace("langtest.cpp.ns.TestType", namespace)

    assert (outfile is not None)

    generated_values = {}  # type: Dict
    with open(str(outfile), 'r') as python_file:
        exec(python_file.read(), generated_values)

    assert len(generated_values)

    lang_cpp_output = generated_values["tests"]["lang_cpp"]
    assert lang_cpp_output["namespace"] == "langtest.cpp.ns"
    assert lang_cpp_output["namespace_open"] == r'''namespace langtest
{
namespace cpp
{
namespace ns
{
'''
    assert lang_cpp_output["namespace_open_wo_nl"] == r'''namespace langtest {
namespace cpp {
namespace ns {
'''
    assert lang_cpp_output["namespace_close"] == r'''}
}
}
'''
    assert lang_cpp_output["namespace_close_w_comments"] == r'''} // namespace ns
} // namespace cpp
} // namespace langtest
'''
    return generated_values
Exemple #6
0
def test_python_filter_short_reference_name(gen_paths):  # type: ignore
    type_map = read_namespace(str(gen_paths.dsdl_dir / pathlib.Path('uavcan')), [])

    from nunavut.lang.py import filter_short_reference_name

    test_subject = next(filter(lambda type: (type.short_name == 'SynchronizedTimestamp'), type_map))
    full_reference_name = filter_short_reference_name(test_subject)
    assert "SynchronizedTimestamp_1_0" == full_reference_name
Exemple #7
0
def test_python_filter_imports(gen_paths):  # type: ignore
    type_map = read_namespace(str(gen_paths.dsdl_dir / pathlib.Path('uavcan')), [])

    from nunavut.lang.py import filter_imports

    test_subject = next(filter(lambda type: (type.short_name == 'bar'), type_map))
    imports = filter_imports(test_subject)
    assert len(imports) == 1
    assert 'uavcan.time' == imports[0]
Exemple #8
0
def gen_test_namespace(gen_paths: typing.Any, language_context: LanguageContext) -> \
        typing.Tuple[Namespace, str, typing.List[CompositeType]]:
    root_namespace_path = str(gen_paths.dsdl_dir / Path("scotec"))
    includes = [str(gen_paths.dsdl_dir / Path("uavcan"))]
    compound_types = read_namespace(root_namespace_path, includes, allow_unregulated_fixed_port_id=True)
    return build_namespace_tree(compound_types,
                                root_namespace_path,
                                gen_paths.out_dir,
                                language_context), root_namespace_path, compound_types
Exemple #9
0
def generate_types(
    language_key: str,
    root_namespace_dir: pathlib.Path,
    out_dir: pathlib.Path,
    omit_serialization_support: bool = True,
    is_dryrun: bool = False,
    allow_overwrite: bool = True,
    lookup_directories: typing.Optional[typing.Iterable[str]] = None,
    allow_unregulated_fixed_port_id: bool = False,
    language_options: typing.Optional[typing.Mapping[str, typing.Any]] = None,
) -> None:
    """
    Helper method that uses default settings and built-in templates to generate types for a given
    language. This method is the most direct way to generate code using Nunavut.

    :param str language_key: The name of the language to generate source for.
                See the :doc:`../../docs/templates` for details on available language support.
    :param pathlib.Path root_namespace_dir: The path to the root of the DSDL types to generate
                code for.
    :param pathlib.Path out_dir: The path to generate code at and under.
    :param bool omit_serialization_support: If True then logic used to serialize and deserialize data is omitted.
    :param bool is_dryrun: If True then nothing is generated but all other activity is performed and any errors
                that would have occurred are reported.
    :param bool allow_overwrite: If True then generated files are allowed to overwrite existing files under the
                `out_dir` path.
    :param typing.Optional[typing.Iterable[str]] lookup_directories: Additional directories to search for dependent
                types referenced by the types provided under the `root_namespace_dir`. Types will not be generated
                for these unless they are used by a type in the root namespace.
    :param bool allow_unregulated_fixed_port_id: If True then errors will become warning when using fixed port
                identifiers for unregulated datatypes.
    :param typing.Optional[typing.Mapping[str, typing.Any]] language_options: Opaque arguments passed through to the
                language objects. The supported arguments and valid values are different depending on the language
                specified by the `language_key` parameter.
    """
    from nunavut.generators import create_generators

    language_context = LanguageContext(
        language_key,
        omit_serialization_support_for_target=omit_serialization_support,
        language_options=language_options,
    )

    if lookup_directories is None:
        lookup_directories = []

    type_map = pydsdl.read_namespace(
        str(root_namespace_dir),
        lookup_directories,
        allow_unregulated_fixed_port_id=allow_unregulated_fixed_port_id)

    namespace = build_namespace_tree(type_map, str(root_namespace_dir),
                                     str(out_dir), language_context)

    generator, support_generator = create_generators(namespace)
    support_generator.generate_all(is_dryrun, allow_overwrite)
    generator.generate_all(is_dryrun, allow_overwrite)
Exemple #10
0
def ptest_lang_py(gen_paths, implicit, unique_name_evaluator):  # type: ignore
    """ Generates and verifies JSON with values filtered using the python language support module.
    """

    root_namespace_dir = gen_paths.dsdl_dir / Path("langtest")
    root_namespace = str(root_namespace_dir)
    if implicit:
        templates_dirs = [
            gen_paths.templates_dir / Path("implicit") / Path("py")
        ]
    else:
        templates_dirs = [gen_paths.templates_dir / Path("explicit")]

    templates_dirs.append(gen_paths.templates_dir / Path("common"))

    compound_types = read_namespace(root_namespace, [],
                                    allow_unregulated_fixed_port_id=True)

    language_context = LanguageContext('py' if implicit else None,
                                       '.py' if not implicit else None)

    namespace = build_namespace_tree(compound_types, root_namespace_dir,
                                     gen_paths.out_dir, language_context)
    generator = DSDLCodeGenerator(namespace,
                                  generate_namespace_types=YesNoDefault.NO,
                                  templates_dir=templates_dirs)

    generator.generate_all(False)

    # Now read back in and verify
    outfile = gen_paths.find_outfile_in_namespace("langtest.py.TestType",
                                                  namespace)

    assert (outfile is not None)

    generated_values = {}  # type: Dict
    with open(str(outfile), 'r') as python_file:
        exec(python_file.read(), generated_values)

    assert len(generated_values) > 0

    lang_py_output = generated_values["tests"]["lang_py"]
    unique_name_evaluator(r'_NAME\d+_', lang_py_output["unique_name_0"])
    unique_name_evaluator(r'_NAME\d+_', lang_py_output["unique_name_1"])
    unique_name_evaluator(r'_name\d+_', lang_py_output["unique_name_2"])
    assert "identifier_zero" == lang_py_output["id_0"]

    many_unique_names = lang_py_output.get("many_unique_names")
    if many_unique_names is not None:
        for name in many_unique_names:
            unique_name_evaluator(r'_f\d+_', name)

    return generated_values
Exemple #11
0
def test_python_filter_imports_for_service_type(gen_paths, stropping, sort):  # type: ignore
    type_map = read_namespace(str(gen_paths.dsdl_dir / pathlib.Path('uavcan')), [])

    from nunavut.lang.py import filter_imports

    test_subject = next(filter(lambda type: (type.short_name == 'bar_svc'), type_map))
    imports = filter_imports(test_subject, sort=sort, stropping=stropping)
    assert len(imports) == 2
    if stropping:
        assert 'uavcan.str_' == imports[0]
    else:
        assert 'uavcan.str' == imports[0]
    assert 'uavcan.time' == imports[1]
Exemple #12
0
def test_realgen(gen_paths, lang_key):  # type: ignore
    """
    Sanity test that runs through the entire public, regulated set of
    UAVCAN types and generates some basic C code.
    """
    root_namespace_dir = gen_paths.root_dir / Path("submodules") / Path(
        "public_regulated_data_types") / Path("uavcan")
    type_map = read_namespace(str(root_namespace_dir), '')
    language_context = LanguageContext(lang_key)
    namespace = build_namespace_tree(type_map, root_namespace_dir,
                                     gen_paths.out_dir, language_context)
    generator = Generator(namespace, False, language_context)
    generator.generate_all(False)
Exemple #13
0
def test_TestType_0_1(gen_paths):  # type: ignore
    """ Generates a JSON blob and then reads it back in.

    This test uses an extremely simple DSDL type to generate JSON then
    reads this JSON back in and parses it using Python's built-in parser.
    """

    root_namespace_dir = gen_paths.dsdl_dir / Path("uavcan")
    root_namespace = str(root_namespace_dir)
    language_context = LanguageContext(extension='.json')
    namespace = build_namespace_tree(read_namespace(root_namespace,
                                                    ''), root_namespace_dir,
                                     gen_paths.out_dir, language_context)
    generator = Generator(namespace, False, language_context,
                          gen_paths.templates_dir)
    generator.generate_all(False)

    # Now read back in and verify
    outfile = gen_paths.find_outfile_in_namespace("uavcan.test.TestType",
                                                  namespace)

    assert (outfile is not None)

    with open(str(outfile), 'r') as json_file:
        json_blob = json.load(json_file)

    assert json_blob is not None
    assert len(json_blob) == 1

    uavcan_namespace = json_blob[0]
    assert uavcan_namespace["type"] == "namespace"
    assert uavcan_namespace["name"] == "uavcan.test"
    assert len(uavcan_namespace["contents"]) == 1

    test_type = uavcan_namespace["contents"][0]
    assert test_type["name"] == "TestType"
    assert test_type["version"]["major"] == 0
    assert test_type["version"]["minor"] == 1
    assert len(test_type["attributes"]) == 2

    test_attr_0 = test_type["attributes"][0]
    assert test_attr_0["name"] == "data"
    assert test_attr_0["type"] == "uint56"
    assert test_attr_0["bit_length"] == 56
    assert test_attr_0["cast_mode"] == "TRUNCATED"

    test_attr_1 = test_type["attributes"][1]
    assert test_attr_1["name"] == "const_bool_example"
    assert test_attr_1["type"] == "uint1"
    assert test_attr_1["bit_length"] == 1
    assert test_attr_1["cast_mode"] == "SATURATED"
def _test_common_namespace(gen_paths,  # type: ignore
                           target_language: str = 'js',
                           extension: str = '.json',
                           additional_config: typing.Optional[typing.Mapping[str, str]] = None):
    root_namespace_dir = gen_paths.dsdl_dir / pathlib.Path("uavcan")
    root_namespace = str(root_namespace_dir)
    lctx = LanguageContext(target_language, extension=extension)
    if additional_config is not None:
        ln_package_name = 'nunavut.lang.{}'.format(target_language)
        for name, value in additional_config.items():
            lctx.config.set(ln_package_name, name, value)
    return nunavut.build_namespace_tree(pydsdl.read_namespace(root_namespace, []),
                                        root_namespace_dir,
                                        gen_paths.out_dir,
                                        lctx)
Exemple #15
0
def test_default_array_type_cpp(gen_paths):  # type: ignore
    """
    Verify that the default array type for C++ is as expected.
    """
    root_namespace = str(gen_paths.dsdl_dir / Path("radar"))
    compound_types = pydsdl.read_namespace(
        root_namespace, [], allow_unregulated_fixed_port_id=True)
    language_context = LanguageContext('cpp')
    namespace = build_namespace_tree(compound_types, root_namespace,
                                     gen_paths.out_dir, language_context)
    generator = DSDLCodeGenerator(namespace)
    generator.generate_all(False)

    assert_pattern_match_in_file(
        gen_paths.find_outfile_in_namespace("radar.Phased", namespace),
        re.compile(r'\s*std::array<float,3>\s+bank_normal_rads;\s*'))
Exemple #16
0
def test_issue_136(gen_paths, lang_key: str,
                   include_format: str):  # type: ignore
    """
    Generates a type that has two different versions using the built-in language support and verifies
    that the header include guards include the type version. This verifies fix #136 has not
    regressed.
    """
    covid_versions = [pydsdl.Version(1, 9), pydsdl.Version(1, 10)]
    root_namespace = str(gen_paths.dsdl_dir / Path("viruses"))
    compound_types = pydsdl.read_namespace(
        root_namespace, [], allow_unregulated_fixed_port_id=True)
    language_context = LanguageContext(
        lang_key, omit_serialization_support_for_target=True)
    namespace = build_namespace_tree(compound_types, root_namespace,
                                     gen_paths.out_dir, language_context)
    generator = DSDLCodeGenerator(namespace)
    generator.generate_all(False)

    for covid_version in covid_versions:

        include_guard_start = re.compile(r'#ifndef {}\b'.format(
            include_format.format(major=covid_version.major,
                                  minor=covid_version.minor)))

        include_guard_def = re.compile(r'#define {}\b'.format(
            include_format.format(major=covid_version.major,
                                  minor=covid_version.minor)))

        # Now read back in and verify
        outfile = gen_paths.find_outfile_in_namespace(
            "viruses.covid", namespace, type_version=covid_version)

        assert (outfile is not None)

        found_open_line = 0
        found_def_line = 0
        with open(str(outfile), 'r') as header_file:
            line_no = 1
            for line in header_file:
                if include_guard_start.match(line):
                    found_open_line = line_no
                if include_guard_def.match(line):
                    found_def_line = line_no
                    break
                line_no += 1
        assert (found_open_line > 0)
        assert (found_def_line > found_open_line)
Exemple #17
0
    def setup(self) -> None:
        """
        Required to prepare this object to run (run method will raise exceptions if called before this method).
        While this may seem a bit clunky it helps isolate errors to two distinct stages; setup and run.

        Setup never generates anything. It only parses the inputs and creates the generator arguments.
        """

        #
        # nunavut : parse inputs
        #
        language_context = self._create_language_context()

        if self._args.generate_support != "only":
            type_map = pydsdl.read_namespace(
                self._args.root_namespace,
                self._extra_includes,
                allow_unregulated_fixed_port_id=self._args.
                allow_unregulated_fixed_port_id,
            )
        else:
            type_map = []

        self._root_namespace = nunavut.build_namespace_tree(
            type_map, self._args.root_namespace, self._args.outdir,
            language_context)

        #
        # nunavut : create generators
        #

        generator_args = {
            "generate_namespace_types":
            (YesNoDefault.YES
             if self._args.generate_namespace_types else YesNoDefault.DEFAULT),
            "templates_dir": (pathlib.Path(self._args.templates)
                              if self._args.templates is not None else None),
            "trim_blocks":
            self._args.trim_blocks,
            "lstrip_blocks":
            self._args.lstrip_blocks,
            "post_processors":
            self._build_post_processor_list_from_args(),
        }

        self._generators = create_generators(self._root_namespace,
                                             **generator_args)
Exemple #18
0
def test_python_filter_includes(gen_paths, stropping, sort):  # type: ignore
    uavcan_dir = str(gen_paths.dsdl_dir / pathlib.Path('uavcan'))
    type_map = read_namespace(str(gen_paths.dsdl_dir / pathlib.Path('new')), [uavcan_dir])
    from nunavut.lang.cpp import filter_includes

    test_subject = next(filter(lambda type: (type.short_name == 'hotness'), type_map))
    mock_environment = MagicMock()
    mock_language_context = MagicMock()
    mock_language_context.get_output_extension = MagicMock(return_value='.h')
    mock_environment.globals = {LanguageContext.ContextInstanceGlobalKey:
                                mock_language_context}
    imports = filter_includes(mock_environment, test_subject, sort=sort, stropping=stropping)
    assert len(imports) == 5

    def assert_path_in_imports(path: str) -> None:
        nonlocal imports
        assert path in imports

    if stropping:
        if sort:
            assert ['<array>',
                    '<cstdint>',
                    '"_new/malloc_1_0.h"',
                    '"uavcan/str/bar_1_0.h"',
                    '"uavcan/time/SynchronizedTimestamp_1_0.h"'
                    ] == imports
        else:

            map(assert_path_in_imports, ('<array>',
                                         '<cstdint>',
                                         '"uavcan/time/SynchronizedTimestamp_1_0.h"',
                                         '"_new/malloc_1_0.h"',
                                         '"uavcan/str/bar_1_0.h"'))
    elif sort:
        assert ['<array>',
                '<cstdint>',
                '"new/malloc_1_0.h"',
                '"uavcan/str/bar_1_0.h"',
                '"uavcan/time/SynchronizedTimestamp_1_0.h"'
                ] == imports
    else:
        map(assert_path_in_imports, ('<array>',
                                     '<cstdint>',
                                     '"uavcan/time/SynchronizedTimestamp_1_0.h"',
                                     '"new/malloc_1_0.h"',
                                     '"uavcan/str/bar_1_0.h"'))
Exemple #19
0
def test_instance_tests(gen_paths):  # type: ignore
    """
    Verifies that instance tests are added for pydsdl.SerializableType and
    all of its subclasses.
    """
    root_namespace_dir = gen_paths.dsdl_dir / Path("buncho")
    type_map = read_namespace(str(root_namespace_dir), [])
    language_context = LanguageContext('js')
    namespace = build_namespace_tree(type_map, root_namespace_dir,
                                     gen_paths.out_dir, language_context)
    generator = DSDLCodeGenerator(namespace,
                                  templates_dir=gen_paths.templates_dir)
    generator.generate_all(False)

    outfile = gen_paths.find_outfile_in_namespace("buncho.serializables",
                                                  namespace)

    assert (outfile is not None)

    with open(str(outfile), 'r') as json_file:
        json_blob = json.load(json_file)

    assert json_blob is not None
    assert json_blob["this_field_is_an_int32"]["isSerializableType"] is True
    assert json_blob["this_field_is_an_int32"]["isSerializable"] is True
    assert json_blob["this_field_is_an_int32"]["isPrimitiveType"] is True
    assert json_blob["this_field_is_an_int32"]["isPrimitive"] is True
    assert json_blob["this_field_is_an_int32"]["isIntegerType"] is True
    assert json_blob["this_field_is_an_int32"]["isFloatType"] is False
    assert json_blob["this_field_is_an_int32"]["isIntegerType_field"] is True
    assert json_blob["this_field_is_an_int32"]["isPaddingField"] is False
    assert json_blob["this_field_is_an_int32"]["isPadding"] is False
    assert json_blob["this_field_is_an_int32"]["isConstant"] is False
    assert json_blob["this_field_is_an_int32"]["isconstant"] is False

    assert json_blob["this_field_is_a_float"]["isSerializableType"] is True
    assert json_blob["this_field_is_a_float"]["isSerializable"] is True
    assert json_blob["this_field_is_a_float"]["isPrimitiveType"] is True
    assert json_blob["this_field_is_a_float"]["isPrimitive"] is True
    assert json_blob["this_field_is_a_float"]["isIntegerType"] is False
    assert json_blob["this_field_is_a_float"]["isIntegerType_field"] is False
    assert json_blob["this_field_is_a_float"]["isFloatType"] is True
    assert json_blob["this_field_is_a_float"]["isPaddingField"] is False
    assert json_blob["this_field_is_a_float"]["isPadding"] is False
    assert json_blob["this_field_is_a_float"]["isConstant"] is False
    assert json_blob["this_field_is_a_float"]["isconstant"] is False
Exemple #20
0
def test_template_assert(gen_paths):  # type: ignore
    """
    Tests our template assertion extension.
    """
    root_path = str(gen_paths.dsdl_dir / Path("uavcan"))
    output_path = gen_paths.out_dir / 'assert'
    compound_types = read_namespace(root_path, [])
    language_context = LanguageContext(extension='.json')
    namespace = build_namespace_tree(compound_types, root_path, output_path,
                                     language_context)
    template_path = gen_paths.templates_dir / Path('assert')
    generator = DSDLCodeGenerator(namespace, templates_dir=template_path)
    try:
        generator.generate_all()
        assert False
    except TemplateAssertionError as e:
        e.filename == str(template_path / "Any.j2")
        e.filename == 2
        e.message == 'Template assertion failed.'
Exemple #21
0
def test_python_filter_includes(gen_paths, stropping, sort):  # type: ignore
    lctx = LanguageContext(target_language='cpp', extension='.h')
    lctx.config.set('nunavut.lang.cpp', 'enable_stropping', str(stropping))

    uavcan_dir = (gen_paths.dsdl_dir / pathlib.Path('uavcan')).as_posix()
    type_map = read_namespace(
        (gen_paths.dsdl_dir / pathlib.Path('new')).as_posix(), [uavcan_dir])
    from nunavut.lang.cpp import filter_includes

    test_subject = next(
        filter(lambda type: (type.short_name == 'hotness'), type_map))
    imports = filter_includes(lctx.get_language('nunavut.lang.cpp'),
                              test_subject,
                              sort=sort)
    assert len(imports) == 5

    def assert_path_in_imports(path: str) -> None:
        nonlocal imports
        assert path in imports

    if stropping:
        if sort:
            assert [
                '"_new/malloc_1_0.h"', '"uavcan/str/bar_1_0.h"',
                '"uavcan/time/SynchronizedTimestamp_1_0.h"', '<array>',
                '<cstdint>'
            ] == imports
        else:

            map(assert_path_in_imports,
                ('"uavcan/time/SynchronizedTimestamp_1_0.h"',
                 '"_new/malloc_1_0.h"', '"uavcan/str/bar_1_0.h"', '<array>',
                 '<cstdint>'))
    elif sort:
        assert [
            '"new/malloc_1_0.h"', '"uavcan/str/bar_1_0.h"',
            '"uavcan/time/SynchronizedTimestamp_1_0.h"', '<array>', '<cstdint>'
        ] == imports
    else:
        map(assert_path_in_imports,
            ('"uavcan/time/SynchronizedTimestamp_1_0.h"', '"new/malloc_1_0.h"',
             '"uavcan/str/bar_1_0.h"', '<array>', '<cstdint>'))
Exemple #22
0
def test_type_to_include(gen_paths):  # type: ignore
    """Test the type_to_include filter."""
    root_path = (gen_paths.dsdl_dir / Path("uavcan")).as_posix()
    output_path = gen_paths.out_dir / 'type_to_include'
    compound_types = read_namespace(root_path, [])
    language_context = LanguageContext(extension='.json')
    namespace = build_namespace_tree(compound_types, root_path, output_path,
                                     language_context)
    template_path = gen_paths.templates_dir / Path('type_to_include')
    generator = DSDLCodeGenerator(namespace, templates_dir=template_path)
    generator.generate_all()
    outfile = gen_paths.find_outfile_in_namespace(
        "uavcan.time.SynchronizedTimestamp", namespace)

    assert (outfile is not None)

    with open(str(outfile), 'r') as json_file:
        json_blob = json.load(json_file)

    assert json_blob is not None
    assert json_blob['include'] == "uavcan/time/SynchronizedTimestamp_1_0.json"
Exemple #23
0
def test_anygen(gen_paths, lang_key):  # type: ignore
    """
    Verifies that any dsdl type will resolve to an ``Any`` template.
    """
    root_namespace_dir = gen_paths.dsdl_dir / Path("uavcan")
    type_map = read_namespace(str(root_namespace_dir), [])
    language_context = LanguageContext(extension='.json')
    namespace = build_namespace_tree(type_map, root_namespace_dir,
                                     str(gen_paths.out_dir), language_context)
    generator = Generator(namespace, templates_dir=gen_paths.templates_dir)
    generator.generate_all(False)

    outfile = gen_paths.find_outfile_in_namespace(
        "uavcan.time.SynchronizedTimestamp", namespace)

    assert (outfile is not None)

    with open(str(outfile), 'r') as json_file:
        json_blob = json.load(json_file)

    assert json_blob is not None
    assert json_blob["full_name"] == "uavcan.time.SynchronizedTimestamp"
Exemple #24
0
def test_one_template(gen_paths):  # type: ignore
    """ Verifies that we can use only a SeralizableType.j2 as the only template when
    no service types are present.
    """
    root_namespace_dir = gen_paths.dsdl_dir / Path("uavcan")
    root_namespace = str(root_namespace_dir)
    serializable_types = read_namespace(root_namespace, [])
    language_context = LanguageContext(extension='.json')
    namespace = build_namespace_tree(serializable_types, root_namespace_dir,
                                     gen_paths.out_dir, language_context)
    generator = Generator(namespace, templates_dir=gen_paths.templates_dir)
    generator.generate_all(False)

    outfile = gen_paths.find_outfile_in_namespace("uavcan.time.TimeSystem",
                                                  namespace)
    assert (outfile is not None)

    with open(str(outfile), 'r') as json_file:
        json_blob = json.load(json_file)

    assert json_blob['uavcan.time.TimeSystem']['namespace'] == 'uavcan.time'
    assert json_blob['uavcan.time.TimeSystem']['is_serializable']
Exemple #25
0
def test_filter_to_template_unique(gen_paths):
    """
    Cover issue #88
    """
    root_path = str(gen_paths.dsdl_dir / Path("one"))
    output_path = gen_paths.out_dir / 'to_unique'
    compound_types = read_namespace(root_path, [])
    language_context = LanguageContext(target_language='c')
    namespace = build_namespace_tree(compound_types, root_path, output_path,
                                     language_context)
    template_path = gen_paths.templates_dir / Path('to_unique')
    generator = DSDLCodeGenerator(namespace, templates_dir=template_path)
    generator.generate_all()
    outfile = gen_paths.find_outfile_in_namespace("one.foo", namespace)

    assert (outfile is not None)

    expected = '_f0_\n_f1_\n_f2_\n_f3_\n\n_f4_\n_f5_\n_f6_\n_f7_\n\n_f8_\n_f9_\n_f10_\n_f11_\n'

    with open(str(outfile), 'r') as foo_file:
        actual = foo_file.read()

    assert expected == actual
Exemple #26
0
def test_python_filter_imports_for_service_type(gen_paths, stropping,
                                                sort):  # type: ignore
    lctx = LanguageContext()
    lctx.config.set('nunavut.lang.py', 'enable_stropping', str(stropping))
    assert stropping == lctx.config.get_config_value_as_bool(
        'nunavut.lang.py', 'enable_stropping')

    type_map = read_namespace(str(gen_paths.dsdl_dir / pathlib.Path('uavcan')),
                              [])

    from nunavut.lang.py import filter_imports

    test_subject = next(
        filter(lambda type: (type.short_name == 'bar_svc'), type_map))
    imports = filter_imports(lctx.get_language('nunavut.lang.py'),
                             test_subject,
                             sort=sort)
    assert len(imports) == 2
    if stropping:
        assert 'uavcan.str_' == imports[0]
    else:
        assert 'uavcan.str' == imports[0]
    assert 'uavcan.time' == imports[1]
Exemple #27
0
def test_var_array_override_cpp(gen_paths):  # type: ignore
    """
    Make sure we can override the type generated for variable-length
    arrays.
    """
    language_option_overrides = {
        'variable_array_type': 'scotec::TerribleArray<{TYPE},{MAX_SIZE}>'
    }
    root_namespace = str(gen_paths.dsdl_dir / Path("radar"))
    compound_types = pydsdl.read_namespace(
        root_namespace, [], allow_unregulated_fixed_port_id=True)
    language_context = LanguageContext(
        'cpp', language_options=language_option_overrides)

    namespace = build_namespace_tree(compound_types, root_namespace,
                                     gen_paths.out_dir, language_context)
    generator = DSDLCodeGenerator(namespace)
    generator.generate_all(False)

    assert_pattern_match_in_file(
        gen_paths.find_outfile_in_namespace("radar.Phased", namespace),
        re.compile(
            r'\s*scotec::TerribleArray<float,2677>\s+antennae_per_bank;\s*'),
        re.compile(r'\s*std::array<float,3>\s+bank_normal_rads;\s*'))
Exemple #28
0
def ptest_lang_c(gen_paths: Any,
                 implicit: bool,
                 unique_name_evaluator: Any,
                 use_standard_types: bool,
                 configurable_language_context_factory: Callable) -> Dict:
    """ Generates and verifies JSON with values filtered using the c language support module.
    """

    root_namespace_dir = gen_paths.dsdl_dir / Path("langtest")
    if implicit:
        templates_dirs = [gen_paths.templates_dir / Path("implicit") / Path("c")]
    else:
        templates_dirs = [gen_paths.templates_dir / Path("explicit")]

    templates_dirs.append(gen_paths.templates_dir / Path("common"))

    root_namespace = str(root_namespace_dir)
    compound_types = read_namespace(root_namespace, [], allow_unregulated_fixed_port_id=True)

    config_overrides = {'nunavut.lang.c': {'use_standard_types': use_standard_types}}
    language_context = configurable_language_context_factory(config_overrides,
                                                             'c' if implicit else None,
                                                             '.h' if not implicit else None)
    namespace = build_namespace_tree(compound_types,
                                     root_namespace_dir,
                                     gen_paths.out_dir,
                                     language_context)
    generator = DSDLCodeGenerator(namespace,
                                  templates_dir=templates_dirs)
    generator.generate_all(False)

    # Now read back in and verify
    outfile = gen_paths.find_outfile_in_namespace("langtest.c.TestType", namespace)

    assert (outfile is not None)

    generated_values = {}  # type: Dict
    with open(str(outfile), 'r') as python_file:
        exec(python_file.read(), generated_values)

    assert len(generated_values) > 0

    lang_c_output = generated_values["tests"]["lang_c"]
    assert lang_c_output["namespace"] == "langtest.c"
    assert lang_c_output["namespace_macrofy"] == "LANGTEST_C"

    if use_standard_types:
        assert lang_c_output["ctype truncated uint8"] == "uint8_t"
        assert lang_c_output["ctype saturated int8"] == "int8_t"
        assert lang_c_output["ctype truncated uint9"] == "uint16_t"
        assert lang_c_output["ctype saturated int9"] == "int16_t"
    else:
        assert lang_c_output["ctype truncated uint8"] == "unsigned char"
        assert lang_c_output["ctype saturated int8"] == "char"
        assert lang_c_output["ctype truncated uint9"] == "unsigned int"
        assert lang_c_output["ctype saturated int9"] == "int"

    if use_standard_types:
        assert lang_c_output["ctype truncated uint32"] == "uint32_t"
        assert lang_c_output["ctype saturated int32"] == "int32_t"
        assert lang_c_output["ctype truncated uint64"] == "uint64_t"
        assert lang_c_output["ctype saturated int64"] == "int64_t"
    else:
        assert lang_c_output["ctype truncated uint32"] == "unsigned long"
        assert lang_c_output["ctype saturated int32"] == "long"
        assert lang_c_output["ctype truncated uint64"] == "unsigned long long"
        assert lang_c_output["ctype saturated int64"] == "long long"

    assert lang_c_output["ctype saturated bool"] == "bool"

    unique_name_evaluator(r'_nAME\d+_', lang_c_output["unique_name_0"])
    unique_name_evaluator(r'_nAME\d+_', lang_c_output["unique_name_1"])
    unique_name_evaluator(r'_naME\d+_', lang_c_output["unique_name_2"])
    unique_name_evaluator(r'_\d+_', lang_c_output["unique_name_3"])

    return generated_values
Exemple #29
0
def compute_max_num_frames_canfd(bit_length):
    b = (bit_length + 7) // 8
    if b <= 63:
        return 1
    else:
        return (b + 2 + 62) // 63


started_at = time.monotonic()
ns_list = [
    'uavcan',
    'regulated',
]
output = []
for ns in ns_list:
    output += pydsdl.read_namespace(ns, ns_list, print_output_handler=on_print)
elapsed_time = time.monotonic() - started_at

print('Full data type name'.center(58), 'FSID'.center(5),
      'CAN FD fr'.center(9))

for t in output:
    num_frames_to_str = lambda x: str(
        x) if x > 1 else ' '  # Return empty for single-frame transfers
    if isinstance(t, pydsdl.ServiceType):
        max_canfd_frames = '  '.join([
            num_frames_to_str(
                compute_max_num_frames_canfd(max(x.bit_length_set)))
            for x in (t.request_type, t.response_type)
        ])
    else:
Exemple #30
0
def generate_package(root_namespace_directory:        _AnyPath,
                     lookup_directories:              typing.Iterable[_AnyPath] = (),
                     output_directory:                typing.Optional[_AnyPath] = None,
                     allow_unregulated_fixed_port_id: bool = False) -> GeneratedPackageInfo:
    """
    This function runs the DSDL compiler, converting a specified DSDL root namespace into a Python package.
    In the generated package, nested DSDL namespaces are represented as Python subpackages,
    DSDL types as Python classes, type version numbers as class name suffixes separated via underscores
    (like ``Type_1_0``), constants as class attributes, fields as properties.
    For a more detailed information on how to use generated types, just generate them and read the resulting
    code -- it is made to be human-readable and contains docstrings.

    Generated packages can be freely moved around the file system or even deployed on other systems --
    they are fully location-invariant.

    Generated packages do not automatically import their nested subpackages. For example, if the application
    needs to use ``uavcan.node.Heartbeat.1.0``, it has to ``import uavcan.node`` explicitly; doing just
    ``import uavcan`` is not sufficient.

    If the source definition contains identifiers, type names, namespace components, or other entities whose
    names are listed in ``nunavut.lang.py.PYTHON_RESERVED_IDENTIFIERS``,
    the compiler applies stropping by suffixing such entities with an underscore ``_``.

    A small subset of applications may require access to a generated entity without knowing in advance whether
    its name is a reserved identifier or not (i.e., whether it's stropped or not). To simplify usage,
    this submodule provides helper functions
    :func:`pyuavcan.dsdl.get_attribute` and :func:`pyuavcan.dsdl.set_attribute` that provide access to generated
    class/object attributes using their original names before stropping.
    Likewise, the function :func:`pyuavcan.dsdl.get_model` can find a generated type even if any of its name
    components are stropped; e.g., a DSDL type ``str.Type.1.0`` would be imported as ``str_.Type_1_0``.

    The above, however, is irrelevant for an application that does not require genericity (vast majority of
    applications don't), so a much easier approach in that case is just to look at the generated code and see
    if there are any stropped identifiers in it, and then just use appropriate names statically.

    The recommended usage pattern for this function is lazy generation.
    First, add the ``output_directory`` (if not specified it defaults to the current working directory)
    to :data:`sys.path` or to the ``PYTHONPATH`` environment variable to make the generated package(s) importable.
    Then try importing the target DSDL-generated package. If the attempt is successful, our job here is done.
    Otherwise, the package(s) need(s) to be generated by invoking this function,
    and then another import attempt will have to be made.
    Beware that before retrying the import it's necessary to invoke :func:`importlib.invalidate_caches`.

    A package generated for a particular version of PyUAVCAN may be incompatible with any other version of the
    library. If your application relies on lazy generation, consider including the library version string
    :data:`pyuavcan.__version__` in ``output_directory``, so that the generated package cache is
    invalidated automatically when a different version of the library is used.

    Having generated a package, consider updating the include path set of your Python IDE to take advantage
    of code completion and static type checking.

    When using PyUAVCAN from an interactive session (e.g., REPL or Jupyter), it is usually more convenient
    to generate packages using the command-line tool rather than invoking this function manually.
    Please refer to the command-line tool documentation for details.

    :param root_namespace_directory: The source DSDL root namespace directory path. The last component of the path
        is the name of the root namespace. For example, to generate package for the root namespace ``uavcan``,
        the path would be like ``foo/bar/uavcan``.

    :param lookup_directories: An iterable of DSDL root namespace directory paths where to search for referred DSDL
        definitions. The format of each path is the same as for the previous parameter; i.e., the last component
        of each path is a DSDL root namespace name. If you are generating code for a vendor-specific DSDL root
        namespace, make sure to provide at least the path to the standard ``uavcan`` namespace directory here.

    :param output_directory: The generated Python package directory will be placed into this directory.
        If not specified or None, the current working directory is used.
        For example, if this argument equals ``foo/bar``, and the DSDL root namespace name is ``uavcan``,
        the top-level ``__init__.py`` of the generated package will end up in ``foo/bar/uavcan/__init__.py``.
        The directory tree will be created automatically if it does not exist (like ``mkdir -p``).
        If the destination exists, it will be silently written over.
        In production, applications are recommended to shard the output directory by the library version number
        to avoid compatibility issues with code generated by older versions of the library.
        Don't forget to add the output directory to ``PYTHONPATH``, even if it's the current working directory.

    :param allow_unregulated_fixed_port_id: If True, the DSDL processing front-end will not reject unregulated
        data types with fixed port-ID. If you are not sure what it means, do not use it, and read the UAVCAN
        specification first. The default is False.

    :return: An instance of :class:`GeneratedPackageInfo` describing the generated package.

    :raises: :class:`OSError` if required operations on the file system could not be performed;
        ``pydsdl.InvalidDefinitionError`` if the source DSDL definitions are invalid;
        ``pydsdl.InternalError`` if there is a bug in the DSDL processing front-end;
        :class:`ValueError` if any of the arguments are otherwise invalid.

    The following table is an excerpt from the UAVCAN specification. Observe that *unregulated fixed port identifiers*
    are prohibited by default, but it can be overridden.

    +-------+---------------------------------------------------+----------------------------------------------+
    |Scope  | Regulated                                         | Unregulated                                  |
    +=======+===================================================+==============================================+
    |Public |Standard and contributed (e.g., vendor-specific)   |Definitions distributed separately from the   |
    |       |definitions. Fixed port identifiers are allowed;   |UAVCAN specification. Fixed port identifiers  |
    |       |they are called *"regulated port-IDs"*.            |are *not allowed*.                            |
    +-------+---------------------------------------------------+----------------------------------------------+
    |Private|Nonexistent category.                              |Definitions that are not available to anyone  |
    |       |                                                   |except their authors. Fixed port identifiers  |
    |       |                                                   |are permitted (although not recommended); they|
    |       |                                                   |are called *"unregulated fixed port-IDs"*.    |
    +-------+---------------------------------------------------+----------------------------------------------+

    Here is a brief usage example:

    >>> import sys
    >>> import pathlib
    >>> import tempfile
    >>> import importlib
    >>> import pyuavcan
    >>> dsdl_generated_dir = pathlib.Path(tempfile.gettempdir(), 'dsdl-for-my-program', pyuavcan.__version__)
    >>> dsdl_generated_dir.mkdir(parents=True, exist_ok=True)
    >>> sys.path.insert(0, str(dsdl_generated_dir))
    >>> try:
    ...     import sirius_cyber_corp
    ...     import uavcan.si.sample.volumetric_flow_rate
    ... except (ImportError, AttributeError):
    ...     _ = pyuavcan.dsdl.generate_package(root_namespace_directory='tests/dsdl/namespaces/sirius_cyber_corp',
    ...                                        lookup_directories=['tests/public_regulated_data_types/uavcan'],
    ...                                        output_directory=dsdl_generated_dir)
    ...     _ = pyuavcan.dsdl.generate_package(root_namespace_directory='tests/public_regulated_data_types/uavcan',
    ...                                        output_directory=dsdl_generated_dir)
    ...     importlib.invalidate_caches()
    ...     import sirius_cyber_corp
    ...     import uavcan.si.sample.volumetric_flow_rate
    """
    # Read the DSDL definitions
    composite_types = pydsdl.read_namespace(root_namespace_directory=str(root_namespace_directory),
                                            lookup_directories=list(map(str, lookup_directories)),
                                            allow_unregulated_fixed_port_id=allow_unregulated_fixed_port_id)
    root_namespace_name, = set(map(lambda x: x.root_namespace, composite_types))  # type: str,

    # Template primitives
    filters = {
        'pickle':            _pickle_object,
        'numpy_scalar_type': _numpy_scalar_type,
    }

    tests = {
        'PaddingField': lambda x: isinstance(x, pydsdl.PaddingField),
        'saturated':    _test_if_saturated,
    }

    # Generate code
    output_directory = pathlib.Path.cwd() if output_directory is None else output_directory
    language_context = nunavut.lang.LanguageContext('py', namespace_output_stem='__init__')
    root_ns = nunavut.build_namespace_tree(types=composite_types,
                                           root_namespace_dir=root_namespace_directory,
                                           output_dir=str(output_directory),
                                           language_context=language_context)
    generator = nunavut.jinja.Generator(namespace=root_ns,
                                        generate_namespace_types=nunavut.YesNoDefault.YES,
                                        templates_dir=_TEMPLATE_DIRECTORY,
                                        followlinks=True,
                                        additional_filters=filters,
                                        additional_tests=tests,
                                        post_processors=[
                                            nunavut.postprocessors.SetFileMode(_OUTPUT_FILE_PERMISSIONS),
                                            nunavut.postprocessors.LimitEmptyLines(2),
                                            nunavut.postprocessors.TrimTrailingWhitespace(),
                                        ])
    generator.generate_all()

    return GeneratedPackageInfo(path=pathlib.Path(output_directory) / pathlib.Path(root_namespace_name),
                                models=composite_types,
                                name=root_namespace_name)