Example #1
0
def from_file(input: 'filename', to: 'filename'):
    """
    from python source to json file
    """
    path = Path(input)
    with path.open('r') as fr, Path(to).open('w') as fw:
        try:
            data = to_dict(ast.parse(fr.read()))
            data['name'] = path.relative()[:-3]  # remove `.py`
            json.dump([str(path), data], fw, indent=2)
        except SyntaxError as e:
            print(e)
            pass
Example #2
0
    def rewrite(state: MetaState):
        language: Tokenizer
        head: Tokenizer
        tail: typing.List[Tokenizer]
        import_items: typing.List[Tokenizer]
        python: Tokenizer
        path_secs = [head.value, *(each.value for each in tail or ())]
        if not import_items:
            requires = _Wild()
        else:
            requires = {each.value for each in import_items}

        if language or python:
            if python:
                warnings.warn(
                    "keyword `pyimport` is deprecated, "
                    "use [python] import instead.", DeprecationWarning)
            else:
                language = language.value
                if language != "python":
                    # TODO: c/c++, .net, java
                    raise NotImplementedError(language)

            lang: Language = state.data
            from_item = ".".join(path_secs)
            import_items = "*" if isinstance(
                requires, _Wild) else "({})".format(', '.join(requires))
            import_stmt = f"from {from_item} import {import_items}"
            lang._backend_imported.append(import_stmt)
            exec(import_stmt, lang.namespace)

        else:
            # TODO: this implementation is wrong but implementing the correct one requires the sperate asts and parsers.
            # See `rbnf.std.compiler`, this one is correct though it's deprecated.

            possible_paths = [Path('./', *path_secs)]
            lang = state.data

            ruiko_home = os.environ.get('RBNF_HOME')

            if ruiko_home:
                possible_paths.append(Path(ruiko_home, *path_secs))

            for path in possible_paths:
                filename = str(path)
                if not filename[:-5].lower().endswith('.rbnf'):
                    filename = filename + '.rbnf'
                    path = Path(filename)
                if not path.exists():
                    continue

                with path.open('r') as file:
                    state = MetaState(rbnf.implementation,
                                      requires=requires,
                                      filename=str(path))
                    state.data = lang
                    _build_language(file.read(), state=state)
                if not requires:
                    break

            if requires and not isinstance(requires, _Wild):
                raise ImportError(requires)