Beispiel #1
0
def emit(g: Graph) -> Module:
    i = 0
    m = Module()
    variables: t.Dict[int, Symbol] = {}
    for node in topological_sorted(g):
        if node.is_primitive:
            variables[node.uid] = m.symbol(node.name)
            continue

        args = []
        for dep in node.depends:
            args.append(variables[dep.uid])
        variables[node.uid] = m.let(f"v{i}", m.symbol(node.name)(*args))
        i += 1
    return m
Beispiel #2
0
def emit(
    nodes: t.List[Node],
    *,
    m: t.Optional[Module] = None,
    aliases: t.Optional[t.Dict[str, str]] = None,
) -> Module:
    if aliases is None:
        aliases = {}
    m = Module()
    m.toplevel = m.submodule()

    for node in nodes:
        args = []
        for f in node.fields:
            if "." in f.type_:
                module_path = f.type_.rsplit(".", 1)[0]
                as_ = None
                if module_path in aliases:
                    as_, module_path, = module_path, aliases[module_path]
                m.toplevel.import_(module_path, as_=as_)
            if f.value == UNDEFINED:
                args.append(f"{f.name}: {f.type_}")
            else:
                args.append(f"{f.name}: {f.type_}={f.value!r}")
        with m.def_(node.name, "*", *args, return_type="None"):
            m.stmt("pass")

    if str(m.toplevel) != "":
        m.toplevel.sep()
    return m
Beispiel #3
0
def emit(
    nodes: t.List[Node],
    *,
    m: t.Optional[Module] = None,
    aliases: t.Optional[t.Dict[str, str]] = None,
) -> Module:
    if aliases is None:
        aliases = {}
    m = Module()
    m.toplevel = m.submodule()

    for node in nodes:
        with m.class_(node.name):
            if len(node.fields) == 0:
                m.stmt("pass")
            for f in node.fields:
                if "." in f.type_:
                    module_path = f.type_.rsplit(".", 1)[0]
                    as_ = None
                    if module_path in aliases:
                        as_, module_path, = module_path, aliases[module_path]
                    m.toplevel.import_(module_path, as_=as_)
                m.stmt(f"{f.name}: {f.type_}")

    if str(m.toplevel) != "":
        m.toplevel.sep()
    return m
Beispiel #4
0
def make_code(m: Module, qd: QueryDatum) -> str:
    name = qd.query_name

    args = []
    seen = set()

    def visit(d):
        if hasattr(d, "keys"):
            for k, v in d.items():
                visit(k)
                visit(v)
        elif hasattr(d, "append"):
            for v in d:
                visit(v)
        elif hasattr(d, "startswith"):
            if d.startswith(":"):
                if d in seen:
                    return
                seen.add(d)
                args.append(d[1:])

    d = parse(qdatum.sql)
    visit(d)

    with m.def_(qd.query_name, *args):
        m.docstring(qd.doc_comments)
        m.stmt("do('''{}''')", qd.sql.rstrip("\n;"))
        m.stmt("data = {}", dumps(d, indent=2))
Beispiel #5
0
def gen(d: t.Dict[str, t.Any],
        *,
        m: t.Optional[Module] = None,
        indent: str = "    ") -> None:
    m = m or Module(indent=indent)
    resolver = Resolver()

    m.from_("__future__").import_("annotations")
    t_pkg = m.import_("typing", as_="t")
    tx_pkg = m.import_("typing_extensions", as_="tx")
    m.sep()

    # definitions
    if "definitions" in d:
        g = DefinitionGenerator(d["definitions"], m=m, resolver=resolver)
        for name, def_dict in d["definitions"].items():
            g.generate(name, def_dict)
    return m
Beispiel #6
0
                visit(v)
        elif hasattr(d, "append"):
            for v in d:
                visit(v)
        elif hasattr(d, "startswith"):
            if d.startswith(":"):
                if d in seen:
                    return
                seen.add(d)
                args.append(d[1:])

    d = parse(qdatum.sql)
    visit(d)

    with m.def_(qd.query_name, *args):
        m.docstring(qd.doc_comments)
        m.stmt("do('''{}''')", qd.sql.rstrip("\n;"))
        m.stmt("data = {}", dumps(d, indent=2))


ql = query_loader.QueryLoader(_make_driver_adapter("sqlite3"),
                              record_classes=None)

m = Module()
for qdatum in ql.load_query_data_from_file(pathlib.Path("./queries.sql")):
    # print(qdatum)
    if qdatum.operation_type in (SQLOperationType.SELECT,
                                 SQLOperationType.SELECT_ONE):
        make_code(m, qdatum)
print(m)
Beispiel #7
0
def emit(r: t.Dict[str, t.List[Node]]) -> Module:
    m = Module()
    m.toplevel = m.submodule()
    m.import_("objects")
    m.sep()

    for name, nodelist in r.items():
        m.stmt(f"@first_tag({name!r})")
        with m.class_(name.replace(" ", "_") + "Service"):
            for node in nodelist:
                m.stmt(
                    f"@endpoint(path={node.path!r}, method={node.method.upper()!r}, summary={node.summary!r})"
                )  # , tags={node.tags!r})

                args = []
                for x in node.args:
                    typ = f"{x.type_}"
                    if not x.required:
                        prefix = m.toplevel.import_("typing", as_="t")
                        typ = f"{prefix}.Optional[{typ}]"
                    if x.description:
                        prefix = m.toplevel.import_("typing_extensions",
                                                    as_="tx")
                        typ = f"{prefix}.Annotated[{typ}, Description({x.description!r})]"
                    args.append(f"{x.name}: {typ}")
                with m.def_(
                        node.operationId,
                        "self",
                        *args,
                ):
                    m.docstring(node.description)
                    m.stmt("pass")
                    pass
    return m
Beispiel #8
0
def run(*, filename: str) -> None:
    d = loading.loadfile(filename)
    m = Module()
    m = gen(d, m=m, indent="    ")
    print(m)
Beispiel #9
0
import typing as t
import sys
from metashape.runtime import get_walker
from prestring.python.codeobject import Module
from prestring.utils import LazyArgumentsAndKeywords, LazyFormat


class Person:
    name: str
    age: t.Optional[int]
    # father: t.Optional[Person]
    father: Person


w = get_walker(sys.modules[__name__], aggressive=True)
m = Module()
Schema = m.from_("marshmallow").import_("Schema")
fields = m.from_("marshmallow").import_("fields")
schema_classes = {}


def dispatch_type(fields, info):
    typ = info.type_
    if typ == int:
        return fields.Integer
    else:
        return fields.String


for cls in w.walk():
    with m.class_(f"{cls.__name__}Schema", Schema) as clsname: