Esempio n. 1
0
 def __init__(self, m, name, sinfo):
     m.stmt("/* structure")
     cm = GoModule()
     m.stmt(cm)
     cm.stmt(name)
     self.cm_map = {sinfo["jsonname"]: cm}
     m.stmt("*/")
Esempio n. 2
0
def emit_code(sinfo, name, m=None, score_map={"Parent": -1, "": -1}):
    m = m or GoModule()
    with m.import_group() as im:
        cw = CommentWriter(m, name, sinfo)
        writer = StructWriter(m, cw, im, score_map=score_map)
        writer.write(name, sinfo)
    return m
Esempio n. 3
0
    def emit(self, state, name, m=None):
        m = m or GoModule()
        if state.get("type") != Struct:
            raise ValueError("hmm")

        with m.type_(name, self.value_formatter.to_type(state)):
            for name, substate in sorted(state["children"].items()):
                self._emit(substate, name, m, parent=state)
        return m
Esempio n. 4
0
def json_to_go(json_string, name, m=None, rx=re.compile("\.0", re.M)):
    m = m or GoModule()
    data = json.loads(rx.sub(".1", json_string))
    s = detect_struct_info(data, name)

    with m.import_group() as im:
        pass
    emit_code(s, name, m=m, im=im)
    im.clear_ifempty()
    return m
Esempio n. 5
0
def emit_code(sinfo, name, m=None, score_map={"Parent": -1, "": -1}):
    def make_signature(sinfo):
        return tuple([(k, v["type"], v.get("type2"))
                      for k, v in sorted(sinfo["children"].items())])

    def _emit_struct(sinfo, name, m, parent=None):
        with m.type_(name, to_type_struct_info(sinfo)):
            for name, subinfo in sorted(sinfo["children"].items()):
                _emit_code(subinfo, name, m, parent=sinfo)

    def _emit_code(sinfo, name, m, parent=None):
        typ = sinfo.get("type")
        if typ == "struct":
            signature = make_signature(sinfo)
            cont.append((name, sinfo, signature))
            m.stmt(LazyFormat('{} {}', name, typename_map[signature]))
        else:
            m.stmt('{} {}'.format(name, to_type_struct_info(sinfo)))
        # append tag
        if is_omitempty_struct_info(sinfo, parent):
            m.insert_after('  `json:"{},omitempty"`'.format(sinfo["jsonname"]))
        else:
            m.insert_after('  `json:"{}"`'.format(sinfo["jsonname"]))

    m = m or GoModule()
    if sinfo.get("type") != "struct":
        raise ValueError("hmm")

    typename_map = defaultdict(lambda: PreString(""))
    defined = set()
    cont = deque([(name, sinfo, make_signature(sinfo))])
    name_store = NameStore()

    while cont:
        name, sinfo, signature = cont.popleft()
        lazy_type_name = typename_map[signature]
        name_store[signature] = name
        lazy_type_name.append(name_store[signature])
        if signature in defined:
            continue
        defined.add(signature)
        _emit_struct(sinfo, name_store[signature], m)

    for typename in typename_map.values():
        typename.body = list(
            reversed(sorted(typename.body,
                            key=lambda x: score_map.get(x, 0))))[0]
    return m
Esempio n. 6
0
def run(src_file):
    reader = Reader()
    writer = Writer()
    with open(src_file) as rf:
        world = reader.read_world(json.load(rf, object_pairs_hook=OrderedDict))
        world.normalize()
    m = GoModule()
    m.comment("from: skill.go")
    writer.write_file(world.modules["src"].files["../src/skill.go"], m=m)
    m.comment("from: user.go")
    writer.write_file(world.modules["src"].files["../src/user.go"], m=m)
    print(m)
Esempio n. 7
0
def emit_code(sinfo, name, m=None):
    def make_signature(sinfo):
        return tuple([(k, v["type"], v.get("type2"))
                      for k, v in sorted(sinfo["children"].items())])

    def _emit_struct(sinfo, name, m, parent=None):
        with m.type_(name, to_type_struct_info(sinfo)):
            for name, subinfo in sorted(sinfo["children"].items()):
                _emit_code(subinfo, name, m, parent=sinfo)

    def _emit_code(sinfo, name, m, parent=None):
        typ = sinfo.get("type")
        if typ == "struct":
            signature = make_signature(sinfo)
            cont.append((name, sinfo, signature))
            m.stmt(LazyFormat('{} {}', name, signature_map[signature]))
        else:
            m.stmt('{} {}'.format(name, to_type_struct_info(sinfo)))
        # append tag
        if is_omitempty_struct_info(sinfo, parent):
            m.insert_after('  `json:"{},omitempty"`'.format(sinfo["jsonname"]))
        else:
            m.insert_after('  `json:"{}"`'.format(sinfo["jsonname"]))

    m = m or GoModule()
    if sinfo.get("type") != "struct":
        raise ValueError("hmm")

    signature_map = defaultdict(lambda: PreString(""))
    defined = set()
    cont = deque([(name, sinfo, make_signature(sinfo))])
    while cont:
        name, sinfo, signature = cont.popleft()
        if signature in defined:
            continue
        defined.add(signature)
        lazy_type_name = signature_map[signature]
        if str(lazy_type_name) == "":
            lazy_type_name.append(name)
        _emit_struct(sinfo, name, m)
    return m
Esempio n. 8
0
def run(src_file, package_name, src_package):
    reader = Reader()
    with open(src_file) as rf:
        world = reader.read_world(json.load(rf, object_pairs_hook=OrderedDict))
        world.normalize()

    m = GoModule()
    writer = Writer(m)

    module = goconvert.Module(package_name, package_name, parent=world)
    new_file = goconvert.File("{}.go".format(package_name), {}, parent=module)
    for file in world.modules[src_package].files.values():
        for struct in file.structs.values():
            name = "Empty{}".format(titlize(struct.name))
            create_empty_func = build_create_empty_func(name,
                                                        struct,
                                                        new_file=new_file)
            new_file.add_function(name, create_empty_func)
            name = titlize(struct.name)
            create_with_modify_func = build_create_with_modify_func(
                name, struct, create_empty_func, new_file)
            new_file.add_function(name, create_with_modify_func)
    print(new_file.dump(writer))
    def __getitem__(self, value):
        return self.value_map[value]

    def get_name(self, value, name):
        try:
            return self[value]
        except KeyError:
            i = self.c[name]
            return self.new_name(name, i)

    def new_name(self, name, i):
        if i == 0:
            return name
        else:
            return "{}Dup{}".format(name, i)



if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--package", type=str, default="autogen")
    parser.add_argument("--name", type=str, default="AutoGenerated")
    parser.add_argument("src", type=argparse.FileType('r'))
    args = parser.parse_args()

    m = GoModule()
    m.package(args.package)
    print(json_to_go(args.src.read(), args.name, m))
Esempio n. 10
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--src", required=True)
    parser.add_argument("--dst", required=True)
    args = parser.parse_args()

    reader = Reader()

    with open(args.src) as rf:
        src_world = reader.read_world(json.load(rf, object_pairs_hook=OrderedDict))
        src_world.normalize()
    with open(args.dst) as rf:
        dst_world = reader.read_world(json.load(rf, object_pairs_hook=OrderedDict))
        dst_world.normalize()
    gencoder = MiniCodeGenerator(TypeMappingResolver([]))

    m = GoModule()
    m.package("convert")
    with m.import_group() as im:
        iw = ImportWriter(im)
        convertor = TypeConvertor(iw, gencoder, src_world, dst_world)
        iw.import_(src_world["model"])
        iw.import_(dst_world["def"])

    @convertor.as_override("string", src_world["bson"].fulladdress("ObjectId"))
    def string_to_object_id(convertor, m, value, *args):
        new_prefix = convertor.import_writer.import_(src_world["bson"])
        return "{}.ObjectIdHex({})".format(new_prefix, value)

    @convertor.as_override(src_world["bson"].fulladdress("ObjectId"), "string")
    def object_id_to_string(convertor, m, value, *args):
        return "{}.Hex()".format(value)

    @convertor.as_override(src_world["model"].fulladdress("Date"), "time.Time")
    def model_date_to_time(convertor, m, value, *args):
        return "{}.Time()".format(value)

    @convertor.as_override(src_world["bson"].fulladdress("ObjectId"), ("pointer", dst_world["def"].fulladdress("ID")))
    def object_id_to_id(convertor, m, value, *args):
        return "ConvertID({})".format(value)

    m.sep()
    cw = ConvertWriter(m, convertor)
    for module in dst_world.modules.values():
        for file in module.files.values():
            for struct in file.structs.values():
                for module in src_world.modules.values():
                    if struct.name in module:
                        print("@", struct.name, file=sys.stderr)
                        cw.write_function(module[struct.name], struct)
                    elif struct.name.startswith("Enduser") and struct.name[len("Enduser"):] in module:
                        print("<", struct.name, file=sys.stderr)
                        cw.write_function(module[struct.name[len("Enduser"):]], struct)
                    elif struct.name.startswith("Tuner") and struct.name[len("Tuner"):] in module:
                        print(">", struct.name, file=sys.stderr)
                        cw.write_function(module[struct.name[len("Tuner"):]], struct)

    # cw.write_function(src_world["model"]["Page"], dst_world["def"]["Page"])
    # # cw.write_function(dst_world["def"]["Page"], src_world["model"]["Page"])
    # cw.write_function(src_world["model"]["User"], dst_world["def"]["User"])

    print(m)
Esempio n. 11
0
    def _emit_struct(self, state, name, m, parent=None):
        with m.block("{} struct".format(name)):
            for name, substate in sorted(state["children"].items()):
                self._emit(substate, name, m, parent=state)
        jsonname = self.value_formatter.to_jsonname(state)
        if self.value_formatter.is_omitempty(state, parent):
            m.insert_after('  `json:"{},omitempty"`'.format(jsonname))
        else:
            m.insert_after('  `json:"{}"`'.format(jsonname))

    def _emit_field(self, state, name, m, parent=None):
        typ = self.value_formatter.to_type(state)
        jsonname = self.value_formatter.to_jsonname(state)
        if self.value_formatter.is_omitempty(state, parent):
            m.stmt('{} {}  `json:"{},omitempty"`'.format(name, typ, jsonname))
        else:
            m.stmt('{} {}  `json:"{}"`'.format(name, typ, jsonname))


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--package", type=str, default="autogen")
    parser.add_argument("--name", type=str, default="AutoGenerated")
    parser.add_argument("src", type=argparse.FileType('r'))
    args = parser.parse_args()

    m = GoModule()
    m.package(args.package)
    print(json_to_go(args.src.read(), args.name, m))
Esempio n. 12
0
from prestring import PreString
from prestring.go import GoModule

m = GoModule()
p = PreString("")
m.stmt("foo")
m.stmt(p)
m.stmt("bar")

p.body.append("*inner*")

print(m)
Esempio n. 13
0
# -*- coding:utf-8 -*-
from prestring.go import GoModule


# cross product
def crossN(m, n):
    def rec(m, i, value):
        if i >= n:
            m.stmt("r = append(r, []string{{{value}}})".format(value=", ".join(value)))
        else:
            v = "v{}".format(i)
            vs = "vs{}".format(i)
            with m.for_("_, {} := range {}".format(v, vs)):
                value.append(v)
                rec(m, i + 1, value)

    args = ["vs{} []string".format(i) for i in range(n)]
    with m.func("cross{}".format(n), *args, return_="[][]string"):
        m.stmt("var r [][]string")
        rec(m, 0, [])
        m.return_("r")
    return m

m = GoModule()
m.package("main")
print(crossN(m, 5))
Esempio n. 14
0
from prestring.go import GoModule

m = GoModule()
with m.import_group() as im:
    im("fmt")

with m.func("main"):
    m.stmt('fmt.Println("Hello, 世界")')
print(m)
Esempio n. 15
0
 def m(self):
     return GoModule()
Esempio n. 16
0
 def _makeContext(self):
     from goconvert.convertor import Context
     from prestring.go import GoModule
     return Context(GoModule())
Esempio n. 17
0
def json_to_go(json_string, name, m=None, rx=re.compile("\.0", re.M)):
    m = m or GoModule()
    data = json.loads(rx.sub(".1", json_string))
    s = detect_struct_info(data, name)
    return emit_code(s, name, m=m)
Esempio n. 18
0
 def create_writer(self, file):
     return Writer(GoModule())
Esempio n. 19
0
# -*- coding:utf-8 -*-
from prestring.go import GoModule


# cross product
def cross2(m):
    with m.func("cross2", "vs0 []string", "vs1 []string", return_="[][]string"):
        m.stmt("var r [][]string")
        with m.for_("_,  v0 := range vs0"):
            with m.for_("_,  v1 := range vs1"):
                m.stmt("r = append(r, []string{v0, v1})")
        m.return_("r")
    return m

m = GoModule()
m.package("main")
print(cross2(m))