def wrap(value, opts=opts): if opts: return LazyFormat( "{}({}, {})", caller_name, value, LazyKeywordsRepr(opts) ) else: return LazyFormat("{}({})", caller_name, value)
def write_field_one( self, c, d, schema_name, definition, name, field, opts, wrap=None ): field_class_name = None if self.resolver.has_ref(field): field_class_name, field = self.resolver.resolve_ref_definition( d, field, level=1 ) if field_class_name == schema_name and deepequal(field, definition): field_class_name = "self" if self.resolver.has_many(field): return self.write_field_many( c, d, field_class_name, definition, name, field, opts ) # finding original definition if self.resolver.has_ref(field): ref_name, field = self.resolver.resolve_ref_definition(d, field) if self.resolver.has_many(field): return self.write_field_many( c, d, field_class_name, definition, name, field, opts ) if ref_name is None: raise CodegenError("ref: %r is not found", field["$ref"]) logger.debug(" field: %s", lazy_json_dump(field)) self.accessor.update_option_on_property(c, field, opts) caller_name = self.accessor.resolver.resolve_caller_name(c, name, field) if caller_name is None: raise CodegenError( "matched field class is not found. name=%r, schema=%r", name, schema_name, ) normalized_name = self.resolver.resolve_normalized_name(name) if normalized_name != name: opts["data_key"] = name if keyword.iskeyword(normalized_name) or normalized_name == "fields": opts["data_key"] = normalized_name normalized_name = normalized_name + "_" kwargs = LazyKeywordsRepr(opts) if self.resolver.has_nested(d, field) and field_class_name: logger.debug(" nested: %s, %s", caller_name, field_class_name) if opts: kwargs = LazyFormat(", {}", kwargs) value = LazyFormat("{}({!r}{})", caller_name, field_class_name, kwargs) else: if caller_name == "fields.Nested": caller_name = "fields.Field" # field value = LazyFormat("{}({})", caller_name, kwargs) logger.info(" write field: write %s, field=%s", name, caller_name) if wrap is not None: value = wrap(value) c.m.stmt(LazyFormat("{} = {}", normalized_name, value))
def write(self, c, d): for path, methods in self.accessor.paths(d): sc = c.new_child() found = False lazy_clsname = self.get_lazy_clsname(path) with sc.m.class_(LazyFormat("{}Input", lazy_clsname)): toplevel_parameters = self.accessor.parameters(methods) if self.OVERRIDE_NAME_MARKER in methods: lazy_clsname.pop() lazy_clsname.append(methods[self.OVERRIDE_NAME_MARKER]) for method, definition in self.accessor.methods(methods): ssc = sc.new_child() with ssc.m.class_(titleize(method)): if "summary" in definition or "description" in definition: ssc.m.stmt('"""') if "summary" in definition: for line in definition["summary"].rstrip( "\n").split("\n"): ssc.m.stmt(line) elif "description" in definition: for line in definition["description"].rstrip( "\n").split("\n"): ssc.m.stmt(line) ssc.m.stmt('"""') ssc.m.stmt("") path_info = self.build_path_info( d, toplevel_parameters, self.accessor.parameters(definition)) for section, properties in sorted( path_info.info.items()): if section is None: continue clsname = titleize(section) if section == "body": definition = next(iter( properties.values()))["schema"] self.schema_writer.write_schema(ssc, d, clsname, definition, force=True) else: definition = { "properties": properties, "required": path_info.required[section] } self.schema_writer.write_schema(ssc, d, clsname, definition, force=True) if path_info and not path_info.info: ssc.m.stmt("pass") if not path_info: ssc.m.clear() found = found or bool(path_info) if not found: sc.m.clear()
def write(self, c, d): for path, methods in self.accessor.paths(d): lazy_clsname = self.get_lazy_clsname(path) sc = c.new_child() found = False with sc.m.class_(LazyFormat("{}Output", lazy_clsname)): if self.OVERRIDE_NAME_MARKER in methods: lazy_clsname.pop() lazy_clsname.append(methods[self.OVERRIDE_NAME_MARKER]) for method, definition in self.accessor.methods(methods): for status, definition in self.accessor.responses( definition): if self.resolver.has_ref(definition): _, definition = self.resolver.resolve_ref_definition( d, definition) if "schema" in definition: found = True clsname = titleize(method) + status schema_definition = definition["schema"] def meta(m): if "description" in definition: m.stmt('"""{}"""'.format( definition["description"])) self.schema_writer.write_schema(sc, d, clsname, schema_definition, force=True, meta_writer=meta) if not found: sc.m.clear()
def run(m: Module) -> Module: filename = Symbol("filename") doSomething = Symbol("doSomething") # todo: import with m.func("Run", LazyFormat("{}: string", filename), return_="error"): config = load_config(m, filename) m.return_(doSomething(config)) # or "return nil" return m
def load_config(m: Module, filename: Symbol) -> Symbol: LoadConfig = Symbol("LoadConfig") # todo: import config = Symbol("config") err = Symbol("err") m.stmt("{}, {} := {}", config, err, LoadConfig(filename)) with m.if_(LazyFormat("{} != nil", err)): m.return_(err) return config
def code(m: Module, name: str) -> Module: with m.class_(name): for name, typ, kind in spec.parameters: if typ.__module__ != "builtins": m.toplevel.import_(typ.__module__, as_=spec._aliases.get(typ.__module__)) if kind == "var_kw": rhs = spec.type_str_of(t.Dict[str, typ]) elif kind == "var_args": rhs = spec.type_str_of(t.List[typ]) else: rhs = spec.type_str_of(typ) if kind == "kw_defaults" or kind == "args_defaults": rhs = LazyFormat("{} = {}", rhs, spec.default_str_of(name)) m.stmt("{}: {} # {}", name, rhs, kind) return m
def add_view(self, pattern, sym, route, method, d, docstring=None): name = sym.rsplit(".", 1)[-1] m = self.m self.from_("pyramid.view", "view_config") view_setting = self.parent.build_view_setting(pattern, route, method, here=self) m.stmt(LazyFormat("@view_config({})", LazyKeywordsRepr(view_setting))) with m.def_(name, "context", "request"): m.stmt('"""') if "summary" in d: m.stmt(d["summary"]) if docstring: m.stmt("") for line in docstring.split("\n"): m.stmt(line) m.stmt('"""') m.return_("{}")
from metashape.runtime import get_walker from prestring.python import Module from prestring.utils import LazyArgumentsAndKeywords, LazyFormat from typestr import typestr class Person: name: str age: int = 0 m = Module() w = get_walker([Person]) for cls in w.walk(): name = w.resolver.resolve_typename(cls) args = [] for fieldname, info, metadata in w.for_type(cls).walk(): # todo: import # todo: add function at info args.append(LazyFormat("{}: {}", fieldname, typestr(info.raw))) with m.def_(name, LazyArgumentsAndKeywords(args)): m.stmt("...") print(m)
def _is_not_(self, x, y): return LazyFormat("{} is not {}", x, y)
def not_(self, x): return LazyFormat("not {}", x)
def __eq__(self, x): return Symbol(str(LazyFormat("{} == {}", self, x)))
def __gt__(self, x): return Symbol(str(LazyFormat("{} < {}", self, x)))
def __ne__(self, x): return Symbol(str(LazyFormat("{} != {}", self, x)))
def f(name: str, *vals: int) -> None: pass m = Module() m.toplevel = m.submodule(import_unique=True) m.sep() spec = fnspec(f) with m.class_("F"): for name, typ, kind in spec.parameters: if typ.__module__ != "builtins": m.toplevel.import_(typ.__module__) info = typeinfo(typ) type_str = spec.type_str_of(info.normalized) if info.is_optional: type_str = LazyFormat("typing.Optional[{}]", type_str) elif kind == "var_kw": type_str = LazyFormat("typing.Dict[str, {}]", type_str) elif kind == "var_args": type_str = LazyFormat("typing.List[{}]", type_str) m.stmt("{}: {}", name, type_str) if kind == "kw_defaults" or kind == "args_defaults": m.unnewline() m.stmt(" = {}", spec.default_of(name)) print(m)
from prestring.python import Module from prestring.utils import LazyFormat, LazyArgumentsAndKeywords from typestr import typestr class Hello: name: str age: int nickname: t.Optional[str] = None m = Module() w = get_walker([Hello]) for cls in w.walk(): name = w.resolver.resolve_typename(cls) args = [] for fieldname, info, metadata in w.for_type(cls).walk(): # todo: default if "default" in metadata: args.append( LazyFormat( "{}: {} = {}", fieldname, typestr(info.raw), metadata["default"] ) ) else: args.append(LazyFormat("{}: {}", fieldname, typestr(info.raw))) with m.def_(name, LazyArgumentsAndKeywords(args)): m.stmt("...") print(m)
def is_not_(self, x: "Emittable", y: "Emittable") -> "Stringer": """like `is <ob>`""" return LazyFormat("{} is not {}", x, y)
def in_(self, x: "Emittable", y: "Emittable") -> "Stringer": """like `in <ob>`""" return LazyFormat("{} in {}", x, y)
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: schema_classes[cls] = clsname for name, info, metadata in w.walk_fields(cls): options = {"required": True} if info.is_optional: options.pop("required") if info.user_defined_type is None: m.stmt("{} = {}", name, dispatch_type(fields, info)(**options)) else: params = LazyArgumentsAndKeywords( args=[ LazyFormat("lambda: {}()", schema_classes[info.type_]) ], kwargs=options, ) m.stmt("{} = {}({})", name, fields.Nested, params) print(m)