From b79fd65a83e6563393807efbc44be3e2bdb16537 Mon Sep 17 00:00:00 2001 From: Josh Haberman Date: Tue, 11 Sep 2018 10:59:08 -0700 Subject: WIP. --- tools/dump_cinit.lua | 725 --------------------------------------------------- tools/make_c_api.lua | 1 + tools/test_cinit.lua | 64 ----- 3 files changed, 1 insertion(+), 789 deletions(-) delete mode 100644 tools/dump_cinit.lua delete mode 100644 tools/test_cinit.lua (limited to 'tools') diff --git a/tools/dump_cinit.lua b/tools/dump_cinit.lua deleted file mode 100644 index 56c47ea..0000000 --- a/tools/dump_cinit.lua +++ /dev/null @@ -1,725 +0,0 @@ ---[[ - - Routines for dumping internal data structures into C initializers - that can be compiled into a .o file. - ---]] - -local upbtable = require "upb.table" -local upb = require "upb" -local export = {} - --- A tiny little abstraction that decouples the dump_* functions from --- what they're writing to (appending to a string, writing to file I/O, etc). --- This could possibly matter since naive string building is O(n^2) in the --- number of appends. -function export.str_appender() - local str = "" - local function append(fmt, ...) - str = str .. string.format(fmt, ...) - end - local function get() - return str - end - return append, get -end - -function export.file_appender(file) - local f = file - local function append(fmt, ...) - f:write(string.format(fmt, ...)) - end - return append -end - -function handler_types(base) - local ret = {} - for k, _ in pairs(base) do - if string.find(k, "^" .. "HANDLER_") then - ret[#ret + 1] = k - end - end - return ret -end - -function octchar(num) - assert(num < 8) - local idx = num + 1 -- 1-based index - return string.sub("01234567", idx, idx) -end - -function c_escape(num) - assert(num < 256) - return string.format("\\%s%s%s", - octchar(math.floor(num / 64)), - octchar(math.floor(num / 8) % 8), - octchar(num % 8)); -end - --- const(f, label) -> UPB_LABEL_REPEATED, where f:label() == upb.LABEL_REPEATED -function const(obj, name, base) - local val = obj[name] - base = base or upb - - -- Support both f:label() and f.label. - if type(val) == "function" then - val = val(obj) - end - - for k, v in pairs(base) do - if v == val and string.find(k, "^" .. string.upper(name)) then - return "UPB_" .. k - end - end - assert(false, "Couldn't find UPB_" .. string.upper(name) .. - " constant for value: " .. val) -end - -function sortedkeys(tab) - arr = {} - for key in pairs(tab) do - arr[#arr + 1] = key - end - table.sort(arr) - return arr -end - -function sorted_defs(defs) - local sorted = {} - - for def in defs do - if def.type == deftype then - sorted[#sorted + 1] = def - end - end - - table.sort(sorted, - function(a, b) return a:full_name() < b:full_name() end) - - return sorted -end - -function constlist(pattern) - local ret = {} - for k, v in pairs(upb) do - if string.find(k, "^" .. pattern) then - ret[k] = v - end - end - return ret -end - -function boolstr(val) - if val == true then - return "true" - elseif val == false then - return "false" - else - assert(false, "Bad bool value: " .. tostring(val)) - end -end - ---[[ - - LinkTable: an object that tracks all linkable objects and their offsets to - facilitate linking. - ---]] - -local LinkTable = {} -function LinkTable:new(types) - local linktab = { - types = types, - table = {}, -- ptr -> {type, 0-based offset} - obj_arrays = {} -- Establishes the ordering for each object type - } - for type, _ in pairs(types) do - linktab.obj_arrays[type] = {} - end - setmetatable(linktab, {__index = LinkTable}) -- Inheritance - return linktab -end - --- Adds a new object to the sequence of objects of this type. -function LinkTable:add(objtype, ptr, obj) - obj = obj or ptr - assert(self.table[obj] == nil) - assert(self.types[objtype]) - local arr = self.obj_arrays[objtype] - self.table[ptr] = {objtype, #arr} - arr[#arr + 1] = obj -end - --- Returns a C symbol name for the given objtype and offset. -function LinkTable:csym(objtype, offset) - local typestr = assert(self.types[objtype]) - return string.format("%s[%d]", typestr, offset) -end - --- Returns the address of the given C object. -function LinkTable:addr(obj) - if obj == upbtable.NULL then - return "NULL" - else - local tabent = assert(self.table[obj], "unknown object: " .. tostring(obj)) - return "&" .. self:csym(tabent[1], tabent[2]) - end -end - --- Returns an array declarator indicating how many objects have been added. -function LinkTable:cdecl(objtype) - return self:csym(objtype, #self.obj_arrays[objtype]) -end - -function LinkTable:objs(objtype) - -- Return iterator function, allowing use as: - -- for obj in linktable:objs(type) do - -- -- ... - -- done - local array = self.obj_arrays[objtype] - local i = 0 - return function() - i = i + 1 - if array[i] then return array[i] end - end -end - -function LinkTable:empty(objtype) - return #self.obj_arrays[objtype] == 0 -end - ---[[ - - Dumper: an object that can dump C initializers for several constructs. - Uses a LinkTable to resolve references when necessary. - ---]] - -local Dumper = {} -function Dumper:new(linktab) - local obj = {linktab = linktab} - setmetatable(obj, {__index = Dumper}) -- Inheritance - return obj -end - --- Dumps a upb_tabval, eg: --- UPB_TABVALUE_INIT(5) -function Dumper:_value(val, upbtype) - if type(val) == "nil" then - return "UPB_TABVALUE_EMPTY_INIT" - elseif type(val) == "number" then - -- Use upbtype to disambiguate what kind of number it is. - if upbtype == upbtable.CTYPE_INT32 then - return string.format("UPB_TABVALUE_INT_INIT(%d)", val) - else - -- TODO(haberman): add support for these so we can properly support - -- default values. - error("Unsupported number type " .. upbtype) - end - elseif type(val) == "string" then - return string.format('UPB_TABVALUE_PTR_INIT("%s")', val) - else - -- We take this as an object reference that has an entry in the link table. - return string.format("UPB_TABVALUE_PTR_INIT(%s)", self.linktab:addr(val)) - end -end - --- Dumps a table key. -function Dumper:tabkey(key) - if type(key) == "nil" then - return "UPB_TABKEY_NONE" - elseif type(key) == "string" then - local len = #key - local len1 = c_escape(len % 256) - local len2 = c_escape(math.floor(len / 256) % 256) - local len3 = c_escape(math.floor(len / (256 * 256)) % 256) - local len4 = c_escape(math.floor(len / (256 * 256 * 256)) % 256) - return string.format('UPB_TABKEY_STR("%s", "%s", "%s", "%s", "%s")', - len1, len2, len3, len4, key) - else - return string.format("UPB_TABKEY_NUM(%d)", key) - end -end - --- Dumps a table entry. -function Dumper:tabent(ent) - local key = self:tabkey(ent.key) - local val = self:_value(ent.value, ent.valtype) - local next = self.linktab:addr(ent.next) - return string.format(' {%s, %s, %s},\n', key, val, next) -end - --- Dumps an inttable array entry. This is almost the same as value() above, --- except that nil values have a special value to indicate "empty". -function Dumper:arrayval(val) - if val.val then - return string.format(" %s,\n", self:_value(val.val, val.valtype)) - else - return " UPB_TABVALUE_EMPTY_INIT,\n" - end -end - --- Dumps an initializer for the given strtable/inttable (respectively). Its --- entries must have previously been added to the linktable. -function Dumper:strtable(t) - -- UPB_STRTABLE_INIT(count, mask, type, size_lg2, entries) - return string.format( - "UPB_STRTABLE_INIT(%d, %d, %s, %d, %s)", - t.count, t.mask, const(t, "ctype", upbtable) , t.size_lg2, - self.linktab:addr(t.entries[1].ptr)) -end - -function Dumper:inttable(t) - local lt = assert(self.linktab) - -- UPB_INTTABLE_INIT(count, mask, type, size_lg2, ent, a, asize, acount) - local entries = "NULL" - if #t.entries > 0 then - entries = lt:addr(t.entries[1].ptr) - end - return string.format( - "UPB_INTTABLE_INIT(%d, %d, %s, %d, %s, %s, %d, %d)", - t.count, t.mask, const(t, "ctype", upbtable), t.size_lg2, entries, - lt:addr(t.array[1].ptr), t.array_size, t.array_count) -end - --- A visitor for visiting all tables of a def. Used first to count entries --- and later to dump them. -local function gettables(def) - if def:def_type() == upb.DEF_MSG then - return {int = upbtable.msgdef_itof(def), str = upbtable.msgdef_ntof(def)} - elseif def:def_type() == upb.DEF_ENUM then - return {int = upbtable.enumdef_iton(def), str = upbtable.enumdef_ntoi(def)} - end -end - -local function emit_file_warning(filedef, append) - append('/* This file was generated by upbc (the upb compiler) from the input\n') - append(' * file:\n') - append(' *\n') - append(' * %s\n', filedef:name()) - append(' *\n') - append(' * Do not edit -- your changes will be discarded when the file is\n') - append(' * regenerated. */\n\n') -end - -local function join(...) - return table.concat({...}, ".") -end - -local function split(str) - local ret = {} - for word in string.gmatch(str, "%w+") do - table.insert(ret, word) - end - return ret -end - -local function to_cident(...) - return string.gsub(join(...), "[%./]", "_") -end - -local function to_preproc(...) - return string.upper(to_cident(...)) -end - --- Strips away last path element, ie: --- foo.Bar.Baz -> foo.Bar -local function remove_name(name) - local package_end = 0 - for i=1,string.len(name) do - if string.byte(name, i) == string.byte(".", 1) then - package_end = i - 1 - end - end - return string.sub(name, 1, package_end) -end - -local function start_namespace(package, append) - local package_components = split(package) - for _, component in ipairs(package_components) do - append("namespace %s {\n", component) - end -end - -local function end_namespace(package, append) - local package_components = split(package) - for i=#package_components,1,-1 do - append("} /* namespace %s */\n", package_components[i]) - end -end - ---[[ - - Top-level, exported dumper functions - ---]] - -local function dump_defs_c(filedef, append) - local defs = {} - for def in filedef:defs(upb.DEF_ANY) do - defs[#defs + 1] = def - if (def:def_type() == upb.DEF_MSG) then - for field in def:fields() do - defs[#defs + 1] = field - end - end - end - - -- Sort all defs by (type, name). - -- This gives us a linear ordering that we can use to create offsets into - -- shared arrays like REFTABLES, hash table entries, and arrays. - table.sort(defs, function(a, b) - if a:def_type() ~= b:def_type() then - return a:def_type() < b:def_type() - else - return a:full_name() < b:full_name() end - end - ) - - -- Perform pre-pass to build the link table. - local linktab = LinkTable:new{ - [upb.DEF_MSG] = "msgs", - [upb.DEF_FIELD] = "fields", - [upb.DEF_ENUM] = "enums", - intentries = "intentries", - strentries = "strentries", - arrays = "arrays", - } - local reftable_count = 0 - - for _, def in ipairs(defs) do - assert(def:is_frozen(), "can only dump frozen defs.") - linktab:add(def:def_type(), def) - reftable_count = reftable_count + 2 - local tables = gettables(def) - if tables then - for _, e in ipairs(tables.str.entries) do - linktab:add("strentries", e.ptr, e) - end - for _, e in ipairs(tables.int.entries) do - linktab:add("intentries", e.ptr, e) - end - for _, e in ipairs(tables.int.array) do - linktab:add("arrays", e.ptr, e) - end - end - end - - -- Emit forward declarations. - emit_file_warning(filedef, append) - append('#include "upb/def.h"\n') - append('#include "upb/structdefs.int.h"\n\n') - append("static const upb_msgdef %s;\n", linktab:cdecl(upb.DEF_MSG)) - append("static const upb_fielddef %s;\n", linktab:cdecl(upb.DEF_FIELD)) - if not linktab:empty(upb.DEF_ENUM) then - append("static const upb_enumdef %s;\n", linktab:cdecl(upb.DEF_ENUM)) - end - append("static const upb_tabent %s;\n", linktab:cdecl("strentries")) - if not linktab:empty("intentries") then - append("static const upb_tabent %s;\n", linktab:cdecl("intentries")) - end - append("static const upb_tabval %s;\n", linktab:cdecl("arrays")) - append("\n") - append("#ifdef UPB_DEBUG_REFS\n") - append("static upb_inttable reftables[%d];\n", reftable_count) - append("#endif\n") - append("\n") - - -- Emit defs. - local dumper = Dumper:new(linktab) - - local reftable = 0 - - append("static const upb_msgdef %s = {\n", linktab:cdecl(upb.DEF_MSG)) - for m in linktab:objs(upb.DEF_MSG) do - local tables = gettables(m) - -- UPB_MSGDEF_INIT(name, selector_count, submsg_field_count, itof, ntof, - -- refs, ref2s) - append(' UPB_MSGDEF_INIT("%s", %d, %d, %s, %s, %s, %s,' .. - ' &reftables[%d], &reftables[%d]),\n', - m:full_name(), - upbtable.msgdef_selector_count(m), - upbtable.msgdef_submsg_field_count(m), - dumper:inttable(tables.int), - dumper:strtable(tables.str), - boolstr(m:_map_entry()), - const(m, "syntax"), - reftable, reftable + 1) - reftable = reftable + 2 - end - append("};\n\n") - - append("static const upb_fielddef %s = {\n", linktab:cdecl(upb.DEF_FIELD)) - for f in linktab:objs(upb.DEF_FIELD) do - local subdef = "NULL" - if f:has_subdef() then - subdef = string.format("(const upb_def*)(%s)", linktab:addr(f:subdef())) - end - local intfmt - if f:type() == upb.TYPE_UINT32 or - f:type() == upb.TYPE_INT32 or - f:type() == upb.TYPE_UINT64 or - f:type() == upb.TYPE_INT64 then - intfmt = const(f, "intfmt") - else - intfmt = "0" - end - -- UPB_FIELDDEF_INIT(label, type, intfmt, tagdelim, is_extension, lazy, - -- packed, name, num, msgdef, subdef, selector_base, - -- index, -- default_value) - append(' UPB_FIELDDEF_INIT(%s, %s, %s, %s, %s, %s, %s, "%s", %d, %s, ' .. - '%s, %d, %d, {0},' .. -- TODO: support default value - '&reftables[%d], &reftables[%d]),\n', - const(f, "label"), const(f, "type"), intfmt, - boolstr(f:istagdelim()), boolstr(f:is_extension()), - boolstr(f:lazy()), boolstr(f:packed()), f:name(), f:number(), - linktab:addr(f:containing_type()), subdef, - upbtable.fielddef_selector_base(f), f:index(), - reftable, reftable + 1 - ) - reftable = reftable + 2 - end - append("};\n\n") - - if not linktab:empty(upb.DEF_ENUM) then - append("static const upb_enumdef %s = {\n", linktab:cdecl(upb.DEF_ENUM)) - for e in linktab:objs(upb.DEF_ENUM) do - local tables = gettables(e) - -- UPB_ENUMDEF_INIT(name, ntoi, iton, defaultval) - append(' UPB_ENUMDEF_INIT("%s", %s, %s, %d, ' .. - '&reftables[%d], &reftables[%d]),\n', - e:full_name(), - dumper:strtable(tables.str), - dumper:inttable(tables.int), - --e:default()) - 0, - reftable, reftable + 1) - reftable = reftable + 2 - end - append("};\n\n") - end - - append("static const upb_tabent %s = {\n", linktab:cdecl("strentries")) - for ent in linktab:objs("strentries") do - append(dumper:tabent(ent)) - end - append("};\n\n"); - - if not linktab:empty("intentries") then - append("static const upb_tabent %s = {\n", linktab:cdecl("intentries")) - for ent in linktab:objs("intentries") do - append(dumper:tabent(ent)) - end - append("};\n\n"); - end - - append("static const upb_tabval %s = {\n", linktab:cdecl("arrays")) - for ent in linktab:objs("arrays") do - append(dumper:arrayval(ent)) - end - append("};\n\n"); - - append("#ifdef UPB_DEBUG_REFS\n") - append("static upb_inttable reftables[%d] = {\n", reftable_count) - for i = 1,reftable_count do - append(" UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),\n") - end - append("};\n") - append("#endif\n\n") - - append("static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {\n") - append(" upb_msgdef_ref(m, owner);\n") - append(" return m;\n") - append("}\n\n") - append("static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {\n") - append(" upb_enumdef_ref(e, owner);\n") - append(" return e;\n") - append("}\n\n") - - append("/* Public API. */\n") - - for m in linktab:objs(upb.DEF_MSG) do - append("const upb_msgdef *upbdefs_%s_get(const void *owner)" .. - " { return refm(%s, owner); }\n", - to_cident(m:full_name()), linktab:addr(m)) - end - - append("\n") - - for e in linktab:objs(upb.DEF_ENUM) do - append("const upb_enumdef *upbdefs_%s_get(const void *owner)" .. - " { return refe(%s, owner); }\n", - to_cident(e:full_name()), linktab:addr(e)) - end - - return linktab -end - -local function dump_defs_for_type(format, defs, append) - local sorted = sorted_defs(defs) - for _, def in ipairs(sorted) do - append(format, to_cident(def:full_name()), def:full_name()) - end - - append("\n") -end - -local function make_children_map(file) - -- Maps file:package() or msg:full_name() -> children. - local map = {} - for def in file:defs(upb.DEF_ANY) do - local container = remove_name(def:full_name()) - if not map[container] then - map[container] = {} - end - table.insert(map[container], def) - end - - -- Sort all the lists for a consistent ordering. - for name, children in pairs(map) do - table.sort(children, function(a, b) return a:name() < b:name() end) - end - - return map -end - -local print_classes - -local function print_message(def, map, indent, append) - append("\n") - append("%sclass %s : public ::upb::reffed_ptr {\n", - indent, def:name()) - append("%s public:\n", indent) - append("%s %s(const ::upb::MessageDef* m, const void *ref_donor = NULL)\n", - indent, def:name()) - append("%s : reffed_ptr(m, ref_donor) {\n", indent) - append("%s UPB_ASSERT(upbdefs_%s_is(m));\n", indent, to_cident(def:full_name())) - append("%s }\n", indent) - append("\n") - append("%s static %s get() {\n", indent, def:name()) - append("%s const ::upb::MessageDef* m = upbdefs_%s_get(&m);\n", indent, to_cident(def:full_name())) - append("%s return %s(m, &m);\n", indent, def:name()) - append("%s }\n", indent) - -- TODO(haberman): add fields - print_classes(def:full_name(), map, indent .. " ", append) - append("%s};\n", indent) -end - -local function print_enum(def, indent, append) - append("\n") - append("%sclass %s : public ::upb::reffed_ptr {\n", - indent, def:name()) - append("%s public:\n", indent) - append("%s %s(const ::upb::EnumDef* e, const void *ref_donor = NULL)\n", - indent, def:name()) - append("%s : reffed_ptr(e, ref_donor) {\n", indent) - append("%s UPB_ASSERT(upbdefs_%s_is(e));\n", indent, to_cident(def:full_name())) - append("%s }\n", indent) - append("%s static %s get() {\n", indent, def:name()) - append("%s const ::upb::EnumDef* e = upbdefs_%s_get(&e);\n", indent, to_cident(def:full_name())) - append("%s return %s(e, &e);\n", indent, def:name()) - append("%s }\n", indent) - append("%s};\n", indent) -end - -function print_classes(name, map, indent, append) - if not map[name] then - return - end - - for _, def in ipairs(map[name]) do - if def:def_type() == upb.DEF_MSG then - print_message(def, map, indent, append) - elseif def:def_type() == upb.DEF_ENUM then - print_enum(def, indent, append) - else - error("Unknown def type for " .. def:full_name()) - end - end -end - -local function dump_defs_h(file, append, linktab) - local basename_preproc = to_preproc(file:name()) - append("/* This file contains accessors for a set of compiled-in defs.\n") - append(" * Note that unlike Google's protobuf, it does *not* define\n") - append(" * generated classes or any other kind of data structure for\n") - append(" * actually storing protobufs. It only contains *defs* which\n") - append(" * let you reflect over a protobuf *schema*.\n") - append(" */\n") - emit_file_warning(file, append) - append('#ifndef %s_UPB_H_\n', basename_preproc) - append('#define %s_UPB_H_\n\n', basename_preproc) - append('#include "upb/def.h"\n\n') - append('UPB_BEGIN_EXTERN_C\n\n') - - -- Dump C enums for proto enums. - - append("/* MessageDefs: call these functions to get a ref to a msgdef. */\n") - dump_defs_for_type( - "const upb_msgdef *upbdefs_%s_get(const void *owner);\n", - file:defs(upb.DEF_MSG), append) - - append("/* EnumDefs: call these functions to get a ref to an enumdef. */\n") - dump_defs_for_type( - "const upb_enumdef *upbdefs_%s_get(const void *owner);\n", - file:defs(upb.DEF_ENUM), append) - - append("/* Functions to test whether this message is of a certain type. */\n") - dump_defs_for_type( - "UPB_INLINE bool upbdefs_%s_is(const upb_msgdef *m) {\n" .. - " return strcmp(upb_msgdef_fullname(m), \"%s\") == 0;\n}\n", - file:defs(upb.DEF_MSG), append) - - append("/* Functions to test whether this enum is of a certain type. */\n") - dump_defs_for_type( - "UPB_INLINE bool upbdefs_%s_is(const upb_enumdef *e) {\n" .. - " return strcmp(upb_enumdef_fullname(e), \"%s\") == 0;\n}\n", - file:defs(upb.DEF_ENUM), append) - - append("\n") - - -- fields - local fields = {} - - for f in linktab:objs(upb.DEF_FIELD) do - local symname = f:containing_type():full_name() .. "." .. f:name() - fields[#fields + 1] = {to_cident(symname), f} - end - - table.sort(fields, function(a, b) return a[1] < b[1] end) - - append("/* Functions to get a fielddef from a msgdef reference. */\n") - for _, field in ipairs(fields) do - local f = field[2] - local msg_cident = to_cident(f:containing_type():full_name()) - local field_cident = to_cident(f:name()) - append("UPB_INLINE const upb_fielddef *upbdefs_%s_f_%s(const upb_msgdef *m) {" .. - " UPB_ASSERT(upbdefs_%s_is(m));" .. - " return upb_msgdef_itof(m, %d); }\n", - msg_cident, field_cident, msg_cident, f:number()) - end - - append('\nUPB_END_EXTERN_C\n\n') - - -- C++ wrappers. - local children_map = make_children_map(file) - - append("#ifdef __cplusplus\n\n") - append("namespace upbdefs {\n") - start_namespace(file:package(), append) - print_classes(file:package(), children_map, "", append) - append("\n") - end_namespace(file:package(), append) - append("} /* namespace upbdefs */\n\n") - append("#endif /* __cplusplus */\n") - - append("\n") - append('#endif /* %s_UPB_H_ */\n', basename_preproc) -end - -function export.dump_defs(filedef, append_h, append_c) - local linktab = dump_defs_c(filedef, append_c) - dump_defs_h(filedef, append_h, linktab) -end - -return export diff --git a/tools/make_c_api.lua b/tools/make_c_api.lua index bf79b26..c333ff0 100644 --- a/tools/make_c_api.lua +++ b/tools/make_c_api.lua @@ -333,6 +333,7 @@ local function write_h_file(filedef, append) append('#ifndef %s_UPB_H_\n', basename_preproc) append('#define %s_UPB_H_\n\n', basename_preproc) + append('#include \n\n') append('#include "upb/msg.h"\n\n') append('#include "upb/decode.h"\n') append('#include "upb/encode.h"\n') diff --git a/tools/test_cinit.lua b/tools/test_cinit.lua deleted file mode 100644 index 8356d63..0000000 --- a/tools/test_cinit.lua +++ /dev/null @@ -1,64 +0,0 @@ ---[[ - - Tests for dump_cinit.lua. Runs first in a mode that generates - some C code for an extension. The C code is compiled and then - loaded by a second invocation of the test which checks that the - generated defs are as expected. - ---]] - -local dump_cinit = require "dump_cinit" -local upb = require "upb" - --- Once APIs for loading descriptors are fleshed out, we should replace this --- with a descriptor for a meaty protobuf like descriptor.proto. -local symtab = upb.SymbolTable{ - upb.EnumDef{full_name = "MyEnum", - values = { - {"FOO", 1}, - {"BAR", 77} - } - }, - upb.MessageDef{full_name = "MyMessage", - fields = { - upb.FieldDef{label = upb.LABEL_REQUIRED, name = "field1", number = 1, - type = upb.TYPE_INT32}, - upb.FieldDef{label = upb.LABEL_REPEATED, name = "field2", number = 2, - type = upb.TYPE_ENUM, subdef_name = ".MyEnum"}, - upb.FieldDef{name = "field3", number = 3, type = upb.TYPE_MESSAGE, - subdef_name = ".MyMessage"} - } - } -} - -if arg[1] == "generate" then - local f = assert(io.open(arg[2], "w")) - local f_h = assert(io.open(arg[2] .. ".h", "w")) - local appendc = dump_cinit.file_appender(f) - local appendh = dump_cinit.file_appender(f_h) - f:write('#include "lua.h"\n') - f:write('#include "upb/bindings/lua/upb.h"\n') - dump_cinit.dump_defs(symtab, "testdefs", appendh, appendc) - f:write([[int luaopen_staticdefs(lua_State *L) { - const upb_symtab *s = upbdefs_testdefs(&s); - lupb_symtab_pushwrapper(L, s, &s); - return 1; - }]]) - f_h:close() - f:close() -elseif arg[1] == "test" then - local symtab = require "staticdefs" - local msg = assert(symtab:lookup("MyMessage")) - local enum = assert(symtab:lookup("MyEnum")) - local f2 = assert(msg:field("field2")) - assert(msg:def_type() == upb.DEF_MSG) - assert(msg:full_name() == "MyMessage") - assert(enum:def_type() == upb.DEF_ENUM) - assert(enum:full_name() == "MyEnum") - assert(enum:value("FOO") == 1) - assert(f2:name() == "field2") - assert(f2:containing_type() == msg) - assert(f2:subdef() == enum) -else - error("Unknown operation " .. arg[1]) -end -- cgit v1.2.3 From 377871f10403c7b4e1cc6f769b9443b5197aecc8 Mon Sep 17 00:00:00 2001 From: Joshua Haberman Date: Sun, 16 Dec 2018 14:32:14 -0800 Subject: Got test_decoder working! --- BUILD | 15 + CMakeLists.txt | 1 + build_defs.bzl | 51 ++- tests/pb/test_decoder.cc | 91 +++--- tests/pb/test_decoder.proto | 42 +++ tools/dump_cinit.lua | 749 -------------------------------------------- tools/make_cmakelists.py | 3 + tools/upbc.lua | 91 ------ upb/def.c | 51 ++- upb/def.h | 10 +- upb/upb.h | 1 - upbc/generator.cc | 104 ++++++ 12 files changed, 317 insertions(+), 892 deletions(-) delete mode 100644 tools/dump_cinit.lua delete mode 100644 tools/upbc.lua (limited to 'tools') diff --git a/BUILD b/BUILD index 9b8513d..b3f397a 100644 --- a/BUILD +++ b/BUILD @@ -8,6 +8,7 @@ load( "make_shell_script", "upb_amalgamation", "upb_proto_library", + "upb_proto_reflection_library", ) # C/C++ rules ################################################################## @@ -167,10 +168,24 @@ cc_test( ], ) +proto_library( + name = "test_decoder_proto", + srcs = [ + "tests/pb/test_decoder.proto" + ] +) + +upb_proto_reflection_library( + name = "test_decoder_upbproto", + deps = ["test_decoder_proto"], + upbc = ":protoc-gen-upb", +) + cc_test( name = "test_decoder", srcs = ["tests/pb/test_decoder.cc"], deps = [ + ":test_decoder_upbproto", ":upb_pb", ":upb_test", ], diff --git a/CMakeLists.txt b/CMakeLists.txt index 6133c16..3439aac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -131,6 +131,7 @@ add_executable(test_decoder tests/pb/test_decoder.cc) add_test(NAME test_decoder COMMAND test_decoder) target_link_libraries(test_decoder + test_decoder_upbproto upb_pb upb_test) add_executable(test_encoder diff --git a/build_defs.bzl b/build_defs.bzl index 8251014..3867976 100644 --- a/build_defs.bzl +++ b/build_defs.bzl @@ -217,7 +217,7 @@ def _remove_up(string): return _remove_suffix(string, ".proto") -def _upb_proto_library_srcs_impl(ctx): +def _upb_proto_srcs_impl(ctx, suffix): sources = [] outs = [] include_dirs = {} @@ -225,14 +225,19 @@ def _upb_proto_library_srcs_impl(ctx): if hasattr(dep, 'proto'): for src in dep.proto.transitive_sources: sources.append(src) - include_dirs[_remove_suffix(src.path, _remove_up(src.short_path) + "." + src.extension)] = True - outs.append(ctx.actions.declare_file(_remove_up(src.short_path) + ".upb.h")) - outs.append(ctx.actions.declare_file(_remove_up(src.short_path) + ".upb.c")) - outdir = _remove_suffix(outs[-1].path, _remove_up(src.short_path) + ".upb.c") + include_dir = _remove_suffix(src.path, _remove_up(src.short_path) + "." + src.extension) + if include_dir: + include_dirs[include_dir] = True + outs.append(ctx.actions.declare_file(_remove_up(src.short_path) + suffix + ".h")) + outs.append(ctx.actions.declare_file(_remove_up(src.short_path) + suffix + ".c")) + outdir = _remove_suffix(outs[-1].path, _remove_up(src.short_path) + suffix + ".c") source_paths = [d.path for d in sources] include_args = ["-I" + root for root in include_dirs.keys()] + print(source_paths) + print(include_args) + ctx.actions.run( inputs = [ctx.executable.upbc] + sources, outputs = outs, @@ -243,6 +248,12 @@ def _upb_proto_library_srcs_impl(ctx): return [DefaultInfo(files = depset(outs))] +def _upb_proto_library_srcs_impl(ctx): + return _upb_proto_srcs_impl(ctx, ".upb") + +def _upb_proto_reflection_library_srcs_impl(ctx): + return _upb_proto_srcs_impl(ctx, ".upbdefs") + _upb_proto_library_srcs = rule( implementation = _upb_proto_library_srcs_impl, attrs = { @@ -272,3 +283,33 @@ def upb_proto_library(name, deps, upbc): deps = [":upb"], copts = ["-Ibazel-out/k8-fastbuild/bin"], ) + +_upb_proto_reflection_library_srcs = rule( + implementation = _upb_proto_reflection_library_srcs_impl, + attrs = { + "upbc": attr.label( + executable = True, + cfg = "host", + ), + "protoc": attr.label( + executable = True, + cfg = "host", + default = "@com_google_protobuf//:protoc", + ), + "deps": attr.label_list(), + } +) + +def upb_proto_reflection_library(name, deps, upbc): + srcs_rule = name + "_defsrcs.cc" + _upb_proto_reflection_library_srcs( + name = srcs_rule, + upbc = upbc, + deps = deps, + ) + native.cc_library( + name = name, + srcs = [":" + srcs_rule], + deps = [":upb"], + copts = ["-Ibazel-out/k8-fastbuild/bin"], + ) diff --git a/tests/pb/test_decoder.cc b/tests/pb/test_decoder.cc index a931779..d0e3fa3 100644 --- a/tests/pb/test_decoder.cc +++ b/tests/pb/test_decoder.cc @@ -36,6 +36,7 @@ #include "tests/test_util.h" #include "tests/upb_test.h" +#include "tests/pb/test_decoder.upbdefs.h" #ifdef AMALGAMATED #include "upb.h" @@ -387,7 +388,6 @@ void reg_subm(upb_handlers *h, uint32_t num) { ASSERT( h->SetStartSubMessageHandler(f, UpbBind(startsubmsg, new uint32_t(num)))); ASSERT(h->SetEndSubMessageHandler(f, UpbBind(endsubmsg, new uint32_t(num)))); - ASSERT(upb_handlers_setsubhandlers(h, f, h)); } void reg_str(upb_handlers *h, uint32_t num) { @@ -399,52 +399,60 @@ void reg_str(upb_handlers *h, uint32_t num) { ASSERT(h->SetStringHandler(f, UpbBind(value_string, new uint32_t(num)))); } -upb::reffed_ptr NewHandlers(TestMode mode) { - - upb::reffed_ptr h(upb::Handlers::New(NewMessageDef().get())); +struct HandlerRegisterData { + TestMode mode; +}; - if (mode == ALL_HANDLERS) { +void callback(const void *closure, upb_handlers *h) { + const HandlerRegisterData* data = + static_cast(closure); + if (data->mode == ALL_HANDLERS) { h->SetStartMessageHandler(UpbMakeHandler(startmsg)); h->SetEndMessageHandler(UpbMakeHandler(endmsg)); // Register handlers for each type. - reg(h.get(), UPB_DESCRIPTOR_TYPE_DOUBLE); - reg (h.get(), UPB_DESCRIPTOR_TYPE_FLOAT); - reg (h.get(), UPB_DESCRIPTOR_TYPE_INT64); - reg(h.get(), UPB_DESCRIPTOR_TYPE_UINT64); - reg (h.get(), UPB_DESCRIPTOR_TYPE_INT32); - reg(h.get(), UPB_DESCRIPTOR_TYPE_FIXED64); - reg(h.get(), UPB_DESCRIPTOR_TYPE_FIXED32); - reg (h.get(), UPB_DESCRIPTOR_TYPE_BOOL); - reg(h.get(), UPB_DESCRIPTOR_TYPE_UINT32); - reg (h.get(), UPB_DESCRIPTOR_TYPE_ENUM); - reg (h.get(), UPB_DESCRIPTOR_TYPE_SFIXED32); - reg (h.get(), UPB_DESCRIPTOR_TYPE_SFIXED64); - reg (h.get(), UPB_DESCRIPTOR_TYPE_SINT32); - reg (h.get(), UPB_DESCRIPTOR_TYPE_SINT64); - - reg_str(h.get(), UPB_DESCRIPTOR_TYPE_STRING); - reg_str(h.get(), UPB_DESCRIPTOR_TYPE_BYTES); - reg_str(h.get(), rep_fn(UPB_DESCRIPTOR_TYPE_STRING)); - reg_str(h.get(), rep_fn(UPB_DESCRIPTOR_TYPE_BYTES)); + reg(h, UPB_DESCRIPTOR_TYPE_DOUBLE); + reg (h, UPB_DESCRIPTOR_TYPE_FLOAT); + reg (h, UPB_DESCRIPTOR_TYPE_INT64); + reg(h, UPB_DESCRIPTOR_TYPE_UINT64); + reg (h, UPB_DESCRIPTOR_TYPE_INT32); + reg(h, UPB_DESCRIPTOR_TYPE_FIXED64); + reg(h, UPB_DESCRIPTOR_TYPE_FIXED32); + reg (h, UPB_DESCRIPTOR_TYPE_BOOL); + reg(h, UPB_DESCRIPTOR_TYPE_UINT32); + reg (h, UPB_DESCRIPTOR_TYPE_ENUM); + reg (h, UPB_DESCRIPTOR_TYPE_SFIXED32); + reg (h, UPB_DESCRIPTOR_TYPE_SFIXED64); + reg (h, UPB_DESCRIPTOR_TYPE_SINT32); + reg (h, UPB_DESCRIPTOR_TYPE_SINT64); + + reg_str(h, UPB_DESCRIPTOR_TYPE_STRING); + reg_str(h, UPB_DESCRIPTOR_TYPE_BYTES); + reg_str(h, rep_fn(UPB_DESCRIPTOR_TYPE_STRING)); + reg_str(h, rep_fn(UPB_DESCRIPTOR_TYPE_BYTES)); // Register submessage/group handlers that are self-recursive // to this type, eg: message M { optional M m = 1; } - reg_subm(h.get(), UPB_DESCRIPTOR_TYPE_MESSAGE); - reg_subm(h.get(), rep_fn(UPB_DESCRIPTOR_TYPE_MESSAGE)); - reg_subm(h.get(), UPB_DESCRIPTOR_TYPE_GROUP); - reg_subm(h.get(), rep_fn(UPB_DESCRIPTOR_TYPE_GROUP)); + reg_subm(h, UPB_DESCRIPTOR_TYPE_MESSAGE); + reg_subm(h, rep_fn(UPB_DESCRIPTOR_TYPE_MESSAGE)); + + if (h->message_def()->full_name() == std::string("DecoderTest")) { + reg_subm(h, UPB_DESCRIPTOR_TYPE_GROUP); + reg_subm(h, rep_fn(UPB_DESCRIPTOR_TYPE_GROUP)); + } // For NOP_FIELD we register no handlers, so we can pad a proto freely without // changing the output. } - - bool ok = h->Freeze(NULL); - ASSERT(ok); - - return h; } +upb::reffed_ptr NewHandlers(upb::SymbolTable* symtab, + TestMode mode) { + HandlerRegisterData handlerdata; + handlerdata.mode = mode; + return upb::Handlers::NewFrozen(DecoderTest_getmsgdef(symtab), callback, + &handlerdata); +} /* Running of test cases ******************************************************/ @@ -1132,14 +1140,11 @@ upb::reffed_ptr NewMethod( return cache.GetDecoderMethod(upb::pb::DecoderMethodOptions(dest_handlers)); } -void test_emptyhandlers(bool allowjit) { +void test_emptyhandlers(upb::SymbolTable* symtab, bool allowjit) { // Create an empty handlers to make sure that the decoder can handle empty // messages. - upb::reffed_ptr md = upb::MessageDef::New(); - ASSERT(md->set_full_name("Empty", NULL)); - ASSERT(md->Freeze(NULL)); - - upb::reffed_ptr h(upb::Handlers::New(md.get())); + const upb::MessageDef* md = Empty_getmsgdef(symtab); + upb::reffed_ptr h(upb::Handlers::New(md)); bool ok = h->Freeze(NULL); ASSERT(ok); upb::reffed_ptr method = @@ -1178,9 +1183,9 @@ upb::reffed_ptr method = void run_tests(bool use_jit) { upb::reffed_ptr method; upb::reffed_ptr handlers; - upb::SymbolTable symtab; + upb::SymbolTable* symtab = upb::SymbolTable::New(); - handlers = NewHandlers(test_mode); + handlers = NewHandlers(symtab, test_mode); global_handlers = handlers.get(); method = NewMethod(handlers.get(), use_jit); @@ -1191,7 +1196,9 @@ void run_tests(bool use_jit) { test_invalid(); test_valid(); - test_emptyhandlers(use_jit); + test_emptyhandlers(symtab, use_jit); + + upb::SymbolTable::Free(symtab); } void run_test_suite() { diff --git a/tests/pb/test_decoder.proto b/tests/pb/test_decoder.proto index 8197dea..e9fa6ad 100644 --- a/tests/pb/test_decoder.proto +++ b/tests/pb/test_decoder.proto @@ -5,6 +5,8 @@ enum TestEnum { FOO = 1; } +message Empty {} + message DecoderTest { optional double f_double = 1; optional float f_float = 2; @@ -62,6 +64,26 @@ message DecoderTest { optional sfixed64 f_sfixed64 = 16; optional sint32 f_sint32 = 17; optional sint64 f_sint64 = 18; + + optional string nop_field = 40; + + repeated double r_double = 536869912; + repeated float r_float = 536869913; + repeated int64 r_int64 = 536869914; + repeated uint64 r_uint64 = 536869915; + repeated int32 r_int32 = 536869916; + repeated fixed64 r_fixed64 = 536869917; + repeated fixed32 r_fixed32 = 536869918; + repeated bool r_bool = 536869919; + repeated string r_string = 536869920; + repeated DecoderTest r_message = 536869922; + repeated bytes r_bytes = 536869923; + repeated uint32 r_uint32 = 536869924; + repeated TestEnum r_enum = 536869925; + repeated sfixed32 r_sfixed32 = 536869926; + repeated sfixed64 r_sfixed64 = 536869927; + repeated sint32 r_sint32 = 536869928; + repeated sint64 r_sint64 = 536869929; } optional group R_group = 536869921 { @@ -82,5 +104,25 @@ message DecoderTest { optional sfixed64 f_sfixed64 = 16; optional sint32 f_sint32 = 17; optional sint64 f_sint64 = 18; + + optional string nop_field = 40; + + repeated double r_double = 536869912; + repeated float r_float = 536869913; + repeated int64 r_int64 = 536869914; + repeated uint64 r_uint64 = 536869915; + repeated int32 r_int32 = 536869916; + repeated fixed64 r_fixed64 = 536869917; + repeated fixed32 r_fixed32 = 536869918; + repeated bool r_bool = 536869919; + repeated string r_string = 536869920; + repeated DecoderTest r_message = 536869922; + repeated bytes r_bytes = 536869923; + repeated uint32 r_uint32 = 536869924; + repeated TestEnum r_enum = 536869925; + repeated sfixed32 r_sfixed32 = 536869926; + repeated sfixed64 r_sfixed64 = 536869927; + repeated sint32 r_sint32 = 536869928; + repeated sint64 r_sint64 = 536869929; } } diff --git a/tools/dump_cinit.lua b/tools/dump_cinit.lua deleted file mode 100644 index 93ee12e..0000000 --- a/tools/dump_cinit.lua +++ /dev/null @@ -1,749 +0,0 @@ ---[[ - - Routines for dumping internal data structures into C initializers - that can be compiled into a .o file. - ---]] - -local upbtable = require "upb.table" -local upb = require "upb" -local export = {} - --- A tiny little abstraction that decouples the dump_* functions from --- what they're writing to (appending to a string, writing to file I/O, etc). --- This could possibly matter since naive string building is O(n^2) in the --- number of appends. -function export.str_appender() - local str = "" - local function append(fmt, ...) - str = str .. string.format(fmt, ...) - end - local function get() - return str - end - return append, get -end - -function export.file_appender(file) - local f = file - local function append(fmt, ...) - f:write(string.format(fmt, ...)) - end - return append -end - -function handler_types(base) - local ret = {} - for k, _ in pairs(base) do - if string.find(k, "^" .. "HANDLER_") then - ret[#ret + 1] = k - end - end - return ret -end - -function octchar(num) - assert(num < 8) - local idx = num + 1 -- 1-based index - return string.sub("01234567", idx, idx) -end - -function c_escape(num) - assert(num < 256) - return string.format("\\%s%s%s", - octchar(math.floor(num / 64)), - octchar(math.floor(num / 8) % 8), - octchar(num % 8)); -end - --- const(f, label) -> UPB_LABEL_REPEATED, where f:label() == upb.LABEL_REPEATED -function const(obj, name, base) - local val = obj[name] - base = base or upb - - -- Support both f:label() and f.label. - if type(val) == "function" then - val = val(obj) - end - - for k, v in pairs(base) do - if v == val and string.find(k, "^" .. string.upper(name)) then - return "UPB_" .. k - end - end - assert(false, "Couldn't find UPB_" .. string.upper(name) .. - " constant for value: " .. val) -end - -function sortedkeys(tab) - arr = {} - for key in pairs(tab) do - arr[#arr + 1] = key - end - table.sort(arr) - return arr -end - -function sorted_defs(defs) - local sorted = {} - - for def in defs do - if def.type == deftype then - sorted[#sorted + 1] = def - end - end - - table.sort(sorted, - function(a, b) return a:full_name() < b:full_name() end) - - return sorted -end - -function constlist(pattern) - local ret = {} - for k, v in pairs(upb) do - if string.find(k, "^" .. pattern) then - ret[k] = v - end - end - return ret -end - -function boolstr(val) - if val == true then - return "true" - elseif val == false then - return "false" - else - assert(false, "Bad bool value: " .. tostring(val)) - end -end - ---[[ - - LinkTable: an object that tracks all linkable objects and their offsets to - facilitate linking. - ---]] - -local LinkTable = {} -function LinkTable:new(types) - local linktab = { - types = types, - table = {}, -- ptr -> {type, 0-based offset} - obj_arrays = {} -- Establishes the ordering for each object type - } - for type, _ in pairs(types) do - linktab.obj_arrays[type] = {} - end - setmetatable(linktab, {__index = LinkTable}) -- Inheritance - return linktab -end - --- Adds a new object to the sequence of objects of this type. -function LinkTable:add(objtype, ptr, obj) - obj = obj or ptr - assert(self.table[obj] == nil) - assert(self.types[objtype]) - local arr = self.obj_arrays[objtype] - self.table[ptr] = {objtype, #arr} - arr[#arr + 1] = obj -end - --- Returns a C symbol name for the given objtype and offset. -function LinkTable:csym(objtype, offset) - local typestr = assert(self.types[objtype]) - return string.format("%s[%d]", typestr, offset) -end - --- Returns the address of the given C object. -function LinkTable:addr(obj) - if obj == upbtable.NULL then - return "NULL" - else - local tabent = assert(self.table[obj], "unknown object: " .. tostring(obj)) - return "&" .. self:csym(tabent[1], tabent[2]) - end -end - --- Returns an array declarator indicating how many objects have been added. -function LinkTable:cdecl(objtype) - return self:csym(objtype, #self.obj_arrays[objtype]) -end - -function LinkTable:objs(objtype) - -- Return iterator function, allowing use as: - -- for obj in linktable:objs(type) do - -- -- ... - -- done - local array = self.obj_arrays[objtype] - local i = 0 - return function() - i = i + 1 - if array[i] then return array[i] end - end -end - -function LinkTable:empty(objtype) - return #self.obj_arrays[objtype] == 0 -end - ---[[ - - Dumper: an object that can dump C initializers for several constructs. - Uses a LinkTable to resolve references when necessary. - ---]] - -local Dumper = {} -function Dumper:new(linktab) - local obj = {linktab = linktab} - setmetatable(obj, {__index = Dumper}) -- Inheritance - return obj -end - --- Dumps a upb_tabval, eg: --- UPB_TABVALUE_INIT(5) -function Dumper:_value(val, upbtype) - if type(val) == "nil" then - return "UPB_TABVALUE_EMPTY_INIT" - elseif type(val) == "number" then - -- Use upbtype to disambiguate what kind of number it is. - if upbtype == upbtable.CTYPE_INT32 then - return string.format("UPB_TABVALUE_INT_INIT(%d)", val) - else - -- TODO(haberman): add support for these so we can properly support - -- default values. - error("Unsupported number type " .. upbtype) - end - elseif type(val) == "string" then - return string.format('UPB_TABVALUE_PTR_INIT("%s")', val) - else - -- We take this as an object reference that has an entry in the link table. - return string.format("UPB_TABVALUE_PTR_INIT(%s)", self.linktab:addr(val)) - end -end - --- Dumps a table key. -function Dumper:tabkey(key) - if type(key) == "nil" then - return "UPB_TABKEY_NONE" - elseif type(key) == "string" then - local len = #key - local len1 = c_escape(len % 256) - local len2 = c_escape(math.floor(len / 256) % 256) - local len3 = c_escape(math.floor(len / (256 * 256)) % 256) - local len4 = c_escape(math.floor(len / (256 * 256 * 256)) % 256) - return string.format('UPB_TABKEY_STR("%s", "%s", "%s", "%s", "%s")', - len1, len2, len3, len4, key) - else - return string.format("UPB_TABKEY_NUM(%d)", key) - end -end - --- Dumps a table entry. -function Dumper:tabent(ent) - local key = self:tabkey(ent.key) - local val = self:_value(ent.value, ent.valtype) - local next = self.linktab:addr(ent.next) - return string.format(' {%s, %s, %s},\n', key, val, next) -end - --- Dumps an inttable array entry. This is almost the same as value() above, --- except that nil values have a special value to indicate "empty". -function Dumper:arrayval(val) - if val.val then - return string.format(" %s,\n", self:_value(val.val, val.valtype)) - else - return " UPB_TABVALUE_EMPTY_INIT,\n" - end -end - --- Dumps an initializer for the given strtable/inttable (respectively). Its --- entries must have previously been added to the linktable. -function Dumper:strtable(t) - -- UPB_STRTABLE_INIT(count, mask, type, size_lg2, entries) - return string.format( - "UPB_STRTABLE_INIT(%d, %d, %s, %d, %s)", - t.count, t.mask, const(t, "ctype", upbtable) , t.size_lg2, - self.linktab:addr(t.entries[1].ptr)) -end - -function Dumper:inttable(t) - local lt = assert(self.linktab) - -- UPB_INTTABLE_INIT(count, mask, type, size_lg2, ent, a, asize, acount) - local entries = "NULL" - if #t.entries > 0 then - entries = lt:addr(t.entries[1].ptr) - end - return string.format( - "UPB_INTTABLE_INIT(%d, %d, %s, %d, %s, %s, %d, %d)", - t.count, t.mask, const(t, "ctype", upbtable), t.size_lg2, entries, - lt:addr(t.array[1].ptr), t.array_size, t.array_count) -end - --- A visitor for visiting all tables of a def. Used first to count entries --- and later to dump them. -local function gettables(def) - if def:def_type() == upb.DEF_MSG then - return {int = upbtable.msgdef_itof(def), str = upbtable.msgdef_ntof(def)} - elseif def:def_type() == upb.DEF_ENUM then - return {int = upbtable.enumdef_iton(def), str = upbtable.enumdef_ntoi(def)} - end -end - -local function emit_file_warning(filedef, append) - append('/* This file was generated by upbc (the upb compiler) from the input\n') - append(' * file:\n') - append(' *\n') - append(' * %s\n', filedef:name()) - append(' *\n') - append(' * Do not edit -- your changes will be discarded when the file is\n') - append(' * regenerated. */\n\n') -end - -local function join(...) - return table.concat({...}, ".") -end - -local function split(str) - local ret = {} - for word in string.gmatch(str, "%w+") do - table.insert(ret, word) - end - return ret -end - -local function to_cident(...) - return string.gsub(join(...), "[%./]", "_") -end - -local function to_preproc(...) - return string.upper(to_cident(...)) -end - --- Strips away last path element, ie: --- foo.Bar.Baz -> foo.Bar -local function remove_name(name) - local package_end = 0 - for i=1,string.len(name) do - if string.byte(name, i) == string.byte(".", 1) then - package_end = i - 1 - end - end - return string.sub(name, 1, package_end) -end - -local function start_namespace(package, append) - local package_components = split(package) - for _, component in ipairs(package_components) do - append("namespace %s {\n", component) - end -end - -local function end_namespace(package, append) - local package_components = split(package) - for i=#package_components,1,-1 do - append("} /* namespace %s */\n", package_components[i]) - end -end - -local function well_known_type(m) - local type_map = {} - type_map["google.protobuf.Duration"] = "UPB_WELLKNOWN_DURATION" - type_map["google.protobuf.Timestamp"] = "UPB_WELLKNOWN_TIMESTAMP" - type_map["google.protobuf.Value"] = "UPB_WELLKNOWN_VALUE" - type_map["google.protobuf.ListValue"] = "UPB_WELLKNOWN_LISTVALUE" - type_map["google.protobuf.Struct"] = "UPB_WELLKNOWN_STRUCT" - type_map["google.protobuf.DoubleValue"] = "UPB_WELLKNOWN_DOUBLEVALUE" - type_map["google.protobuf.FloatValue"] = "UPB_WELLKNOWN_FLOATVALUE" - type_map["google.protobuf.Int64Value"] = "UPB_WELLKNOWN_INT64VALUE" - type_map["google.protobuf.UInt64Value"] = "UPB_WELLKNOWN_UINT64VALUE" - type_map["google.protobuf.Int32Value"] = "UPB_WELLKNOWN_INT32VALUE" - type_map["google.protobuf.UInt32Value"] = "UPB_WELLKNOWN_UINT32VALUE" - type_map["google.protobuf.BoolValue"] = "UPB_WELLKNOWN_BOOLVALUE" - type_map["google.protobuf.StringValue"] = "UPB_WELLKNOWN_STRINGVALUE" - type_map["google.protobuf.BytesValue"] = "UPB_WELLKNOWN_BYTESVALUE" - local t = type_map[m:full_name()] - if (t == nil) then - t = "UPB_WELLKNOWN_UNSPECIFIED" - end - return t -end - ---[[ - - Top-level, exported dumper functions - ---]] - -local function dump_defs_c(filedef, append) - local defs = {} - for def in filedef:defs(upb.DEF_ANY) do - defs[#defs + 1] = def - if (def:def_type() == upb.DEF_MSG) then - for field in def:fields() do - defs[#defs + 1] = field - end - end - end - - -- Sort all defs by (type, name). - -- This gives us a linear ordering that we can use to create offsets into - -- shared arrays like REFTABLES, hash table entries, and arrays. - table.sort(defs, function(a, b) - if a:def_type() ~= b:def_type() then - return a:def_type() < b:def_type() - else - return a:full_name() < b:full_name() end - end - ) - - -- Perform pre-pass to build the link table. - local linktab = LinkTable:new{ - [upb.DEF_MSG] = "msgs", - [upb.DEF_FIELD] = "fields", - [upb.DEF_ENUM] = "enums", - intentries = "intentries", - strentries = "strentries", - arrays = "arrays", - } - local reftable_count = 0 - - for _, def in ipairs(defs) do - assert(def:is_frozen(), "can only dump frozen defs.") - linktab:add(def:def_type(), def) - reftable_count = reftable_count + 2 - local tables = gettables(def) - if tables then - for _, e in ipairs(tables.str.entries) do - linktab:add("strentries", e.ptr, e) - end - for _, e in ipairs(tables.int.entries) do - linktab:add("intentries", e.ptr, e) - end - for _, e in ipairs(tables.int.array) do - linktab:add("arrays", e.ptr, e) - end - end - end - - -- Emit forward declarations. - emit_file_warning(filedef, append) - append('#include "upb/def.h"\n') - append('#include "upb/structdefs.int.h"\n\n') - append("static const upb_msgdef %s;\n", linktab:cdecl(upb.DEF_MSG)) - append("static const upb_fielddef %s;\n", linktab:cdecl(upb.DEF_FIELD)) - if not linktab:empty(upb.DEF_ENUM) then - append("static const upb_enumdef %s;\n", linktab:cdecl(upb.DEF_ENUM)) - end - append("static const upb_tabent %s;\n", linktab:cdecl("strentries")) - if not linktab:empty("intentries") then - append("static const upb_tabent %s;\n", linktab:cdecl("intentries")) - end - append("static const upb_tabval %s;\n", linktab:cdecl("arrays")) - append("\n") - append("#ifdef UPB_DEBUG_REFS\n") - append("static upb_inttable reftables[%d];\n", reftable_count) - append("#endif\n") - append("\n") - - -- Emit defs. - local dumper = Dumper:new(linktab) - - local reftable = 0 - - append("static const upb_msgdef %s = {\n", linktab:cdecl(upb.DEF_MSG)) - for m in linktab:objs(upb.DEF_MSG) do - local tables = gettables(m) - -- UPB_MSGDEF_INIT(name, selector_count, submsg_field_count, itof, ntof, - -- refs, ref2s) - append(' UPB_MSGDEF_INIT("%s", %d, %d, %s, %s, %s, %s, %s,' .. - ' &reftables[%d], &reftables[%d]),\n', - m:full_name(), - upbtable.msgdef_selector_count(m), - upbtable.msgdef_submsg_field_count(m), - dumper:inttable(tables.int), - dumper:strtable(tables.str), - boolstr(m:_map_entry()), - const(m, "syntax"), - well_known_type(m), - reftable, reftable + 1) - reftable = reftable + 2 - end - append("};\n\n") - - append("static const upb_fielddef %s = {\n", linktab:cdecl(upb.DEF_FIELD)) - for f in linktab:objs(upb.DEF_FIELD) do - local subdef = "NULL" - if f:has_subdef() then - subdef = string.format("(const upb_def*)(%s)", linktab:addr(f:subdef())) - end - local intfmt - if f:type() == upb.TYPE_UINT32 or - f:type() == upb.TYPE_INT32 or - f:type() == upb.TYPE_UINT64 or - f:type() == upb.TYPE_INT64 then - intfmt = const(f, "intfmt") - else - intfmt = "0" - end - -- UPB_FIELDDEF_INIT(label, type, intfmt, tagdelim, is_extension, lazy, - -- packed, name, num, msgdef, subdef, selector_base, - -- index, -- default_value) - append(' UPB_FIELDDEF_INIT(%s, %s, %s, %s, %s, %s, %s, "%s", %d, %s, ' .. - '%s, %d, %d, {0},' .. -- TODO: support default value - '&reftables[%d], &reftables[%d]),\n', - const(f, "label"), const(f, "type"), intfmt, - boolstr(f:istagdelim()), boolstr(f:is_extension()), - boolstr(f:lazy()), boolstr(f:packed()), f:name(), f:number(), - linktab:addr(f:containing_type()), subdef, - upbtable.fielddef_selector_base(f), f:index(), - reftable, reftable + 1 - ) - reftable = reftable + 2 - end - append("};\n\n") - - if not linktab:empty(upb.DEF_ENUM) then - append("static const upb_enumdef %s = {\n", linktab:cdecl(upb.DEF_ENUM)) - for e in linktab:objs(upb.DEF_ENUM) do - local tables = gettables(e) - -- UPB_ENUMDEF_INIT(name, ntoi, iton, defaultval) - append(' UPB_ENUMDEF_INIT("%s", %s, %s, %d, ' .. - '&reftables[%d], &reftables[%d]),\n', - e:full_name(), - dumper:strtable(tables.str), - dumper:inttable(tables.int), - --e:default()) - 0, - reftable, reftable + 1) - reftable = reftable + 2 - end - append("};\n\n") - end - - append("static const upb_tabent %s = {\n", linktab:cdecl("strentries")) - for ent in linktab:objs("strentries") do - append(dumper:tabent(ent)) - end - append("};\n\n"); - - if not linktab:empty("intentries") then - append("static const upb_tabent %s = {\n", linktab:cdecl("intentries")) - for ent in linktab:objs("intentries") do - append(dumper:tabent(ent)) - end - append("};\n\n"); - end - - append("static const upb_tabval %s = {\n", linktab:cdecl("arrays")) - for ent in linktab:objs("arrays") do - append(dumper:arrayval(ent)) - end - append("};\n\n"); - - append("#ifdef UPB_DEBUG_REFS\n") - append("static upb_inttable reftables[%d] = {\n", reftable_count) - for i = 1,reftable_count do - append(" UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),\n") - end - append("};\n") - append("#endif\n\n") - - append("static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {\n") - append(" upb_msgdef_ref(m, owner);\n") - append(" return m;\n") - append("}\n\n") - append("static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {\n") - append(" upb_enumdef_ref(e, owner);\n") - append(" return e;\n") - append("}\n\n") - - append("/* Public API. */\n") - - for m in linktab:objs(upb.DEF_MSG) do - append("const upb_msgdef *upbdefs_%s_get(const void *owner)" .. - " { return refm(%s, owner); }\n", - to_cident(m:full_name()), linktab:addr(m)) - end - - append("\n") - - for e in linktab:objs(upb.DEF_ENUM) do - append("const upb_enumdef *upbdefs_%s_get(const void *owner)" .. - " { return refe(%s, owner); }\n", - to_cident(e:full_name()), linktab:addr(e)) - end - - return linktab -end - -local function dump_defs_for_type(format, defs, append) - local sorted = sorted_defs(defs) - for _, def in ipairs(sorted) do - append(format, to_cident(def:full_name()), def:full_name()) - end - - append("\n") -end - -local function make_children_map(file) - -- Maps file:package() or msg:full_name() -> children. - local map = {} - for def in file:defs(upb.DEF_ANY) do - local container = remove_name(def:full_name()) - if not map[container] then - map[container] = {} - end - table.insert(map[container], def) - end - - -- Sort all the lists for a consistent ordering. - for name, children in pairs(map) do - table.sort(children, function(a, b) return a:name() < b:name() end) - end - - return map -end - -local print_classes - -local function print_message(def, map, indent, append) - append("\n") - append("%sclass %s : public ::upb::reffed_ptr {\n", - indent, def:name()) - append("%s public:\n", indent) - append("%s %s(const ::upb::MessageDef* m, const void *ref_donor = NULL)\n", - indent, def:name()) - append("%s : reffed_ptr(m, ref_donor) {\n", indent) - append("%s UPB_ASSERT(upbdefs_%s_is(m));\n", indent, to_cident(def:full_name())) - append("%s }\n", indent) - append("\n") - append("%s static %s get() {\n", indent, def:name()) - append("%s const ::upb::MessageDef* m = upbdefs_%s_get(&m);\n", indent, to_cident(def:full_name())) - append("%s return %s(m, &m);\n", indent, def:name()) - append("%s }\n", indent) - -- TODO(haberman): add fields - print_classes(def:full_name(), map, indent .. " ", append) - append("%s};\n", indent) -end - -local function print_enum(def, indent, append) - append("\n") - append("%sclass %s : public ::upb::reffed_ptr {\n", - indent, def:name()) - append("%s public:\n", indent) - append("%s %s(const ::upb::EnumDef* e, const void *ref_donor = NULL)\n", - indent, def:name()) - append("%s : reffed_ptr(e, ref_donor) {\n", indent) - append("%s UPB_ASSERT(upbdefs_%s_is(e));\n", indent, to_cident(def:full_name())) - append("%s }\n", indent) - append("%s static %s get() {\n", indent, def:name()) - append("%s const ::upb::EnumDef* e = upbdefs_%s_get(&e);\n", indent, to_cident(def:full_name())) - append("%s return %s(e, &e);\n", indent, def:name()) - append("%s }\n", indent) - append("%s};\n", indent) -end - -function print_classes(name, map, indent, append) - if not map[name] then - return - end - - for _, def in ipairs(map[name]) do - if def:def_type() == upb.DEF_MSG then - print_message(def, map, indent, append) - elseif def:def_type() == upb.DEF_ENUM then - print_enum(def, indent, append) - else - error("Unknown def type for " .. def:full_name()) - end - end -end - -local function dump_defs_h(file, append, linktab) - local basename_preproc = to_preproc(file:name()) - append("/* This file contains accessors for a set of compiled-in defs.\n") - append(" * Note that unlike Google's protobuf, it does *not* define\n") - append(" * generated classes or any other kind of data structure for\n") - append(" * actually storing protobufs. It only contains *defs* which\n") - append(" * let you reflect over a protobuf *schema*.\n") - append(" */\n") - emit_file_warning(file, append) - append('#ifndef %s_UPB_H_\n', basename_preproc) - append('#define %s_UPB_H_\n\n', basename_preproc) - append('#include "upb/def.h"\n\n') - append('UPB_BEGIN_EXTERN_C\n\n') - - -- Dump C enums for proto enums. - - append("/* MessageDefs: call these functions to get a ref to a msgdef. */\n") - dump_defs_for_type( - "const upb_msgdef *upbdefs_%s_get(const void *owner);\n", - file:defs(upb.DEF_MSG), append) - - append("/* EnumDefs: call these functions to get a ref to an enumdef. */\n") - dump_defs_for_type( - "const upb_enumdef *upbdefs_%s_get(const void *owner);\n", - file:defs(upb.DEF_ENUM), append) - - append("/* Functions to test whether this message is of a certain type. */\n") - dump_defs_for_type( - "UPB_INLINE bool upbdefs_%s_is(const upb_msgdef *m) {\n" .. - " return strcmp(upb_msgdef_fullname(m), \"%s\") == 0;\n}\n", - file:defs(upb.DEF_MSG), append) - - append("/* Functions to test whether this enum is of a certain type. */\n") - dump_defs_for_type( - "UPB_INLINE bool upbdefs_%s_is(const upb_enumdef *e) {\n" .. - " return strcmp(upb_enumdef_fullname(e), \"%s\") == 0;\n}\n", - file:defs(upb.DEF_ENUM), append) - - append("\n") - - -- fields - local fields = {} - - for f in linktab:objs(upb.DEF_FIELD) do - local symname = f:containing_type():full_name() .. "." .. f:name() - fields[#fields + 1] = {to_cident(symname), f} - end - - table.sort(fields, function(a, b) return a[1] < b[1] end) - - append("/* Functions to get a fielddef from a msgdef reference. */\n") - for _, field in ipairs(fields) do - local f = field[2] - local msg_cident = to_cident(f:containing_type():full_name()) - local field_cident = to_cident(f:name()) - append("UPB_INLINE const upb_fielddef *upbdefs_%s_f_%s(const upb_msgdef *m) {" .. - " UPB_ASSERT(upbdefs_%s_is(m));" .. - " return upb_msgdef_itof(m, %d); }\n", - msg_cident, field_cident, msg_cident, f:number()) - end - - append('\nUPB_END_EXTERN_C\n\n') - - -- C++ wrappers. - local children_map = make_children_map(file) - - append("#ifdef __cplusplus\n\n") - append("namespace upbdefs {\n") - start_namespace(file:package(), append) - print_classes(file:package(), children_map, "", append) - append("\n") - end_namespace(file:package(), append) - append("} /* namespace upbdefs */\n\n") - append("#endif /* __cplusplus */\n") - - append("\n") - append('#endif /* %s_UPB_H_ */\n', basename_preproc) -end - -function export.dump_defs(filedef, append_h, append_c) - local linktab = dump_defs_c(filedef, append_c) - dump_defs_h(filedef, append_h, linktab) -end - -return export diff --git a/tools/make_cmakelists.py b/tools/make_cmakelists.py index b8f46b9..2b426b5 100755 --- a/tools/make_cmakelists.py +++ b/tools/make_cmakelists.py @@ -120,6 +120,9 @@ class BuildFileFunctions(object): def upb_proto_library(self, **kwargs): pass + def upb_proto_reflection_library(self, **kwargs): + pass + def genrule(self, **kwargs): pass diff --git a/tools/upbc.lua b/tools/upbc.lua deleted file mode 100644 index 80d2886..0000000 --- a/tools/upbc.lua +++ /dev/null @@ -1,91 +0,0 @@ ---[[ - - The upb compiler. It can write two different kinds of output - files: - - - generated code for a C API (foo.upb.h, foo.upb.c) - - (obsolete): definitions of upb defs. (foo.upbdefs.h, foo.upbdefs.c) - ---]] - -local dump_cinit = require "dump_cinit" -local upb = require "upb" - -local generate_upbdefs = false -local outdir = "." - -i = 1 -while i <= #arg do - argument = arg[i] - if argument.sub(argument, 1, 2) == "--" then - if argument == "--generate-upbdefs" then - generate_upbdefs = true - elseif argument == "--outdir" then - i = i + 1 - outdir = arg[i] - else - print("Unknown flag: " .. argument) - return 1 - end - else - if src then - print("upbc can only handle one input file at a time.") - return 1 - end - src = argument - end - i = i + 1 -end - -if not src then - print("Usage: upbc [--generate-upbdefs] ") - return 1 -end - -function strip_proto(filename) - return string.gsub(filename, '%.proto$','') -end - -local function open(filename) - local full_name = outdir .. "/" .. filename - return assert(io.open(full_name, "w"), "couldn't open " .. full_name) -end - --- Open input/output files. -local f = assert(io.open(src, "r"), "couldn't open input file " .. src) -local descriptor = f:read("*all") -local files = upb.load_descriptor(descriptor) -local symtab = upb.SymbolTable() - -for _, file in ipairs(files) do - symtab:add_file(file) - local outbase = strip_proto(file:name()) - - -- Write upbdefs. - - local hfilename = outbase .. ".upbdefs.h" - local cfilename = outbase .. ".upbdefs.c" - - if os.getenv("UPBC_VERBOSE") then - print("upbc:") - print(string.format(" source file=%s", src)) - print(string.format(" output file base=%s", outbase)) - print(string.format(" hfilename=%s", hfilename)) - print(string.format(" cfilename=%s", cfilename)) - end - - os.execute(string.format("mkdir -p `dirname %s`", outbase)) - - assert(generate_upbdefs) - -- Legacy generated defs. - local hfile = open(hfilename) - local cfile = open(cfilename) - - local happend = dump_cinit.file_appender(hfile) - local cappend = dump_cinit.file_appender(cfile) - - dump_cinit.dump_defs(file, happend, cappend) - - hfile:close() - cfile:close() -end diff --git a/upb/def.c b/upb/def.c index ba6de50..047684e 100644 --- a/upb/def.c +++ b/upb/def.c @@ -643,7 +643,7 @@ uint32_t upb_msgdef_submsgfieldcount(const upb_msgdef *m) { const upb_fielddef *upb_msgdef_itof(const upb_msgdef *m, uint32_t i) { upb_value val; return upb_inttable_lookup32(&m->itof, i, &val) ? - upb_value_getptr(val) : NULL; + upb_value_getconstptr(val) : NULL; } const upb_fielddef *upb_msgdef_ntof(const upb_msgdef *m, const char *name, @@ -1128,12 +1128,14 @@ static bool create_fielddef( if (m) { /* direct message field. */ + upb_value v, packed_v; + f = (upb_fielddef*)&m->fields[m->field_count++]; f->msgdef = m; f->is_extension_ = false; - upb_value packed_v = pack_def(f, UPB_DEFTYPE_FIELD); - upb_value v = upb_value_constptr(f); + packed_v = pack_def(f, UPB_DEFTYPE_FIELD); + v = upb_value_constptr(f); if (!upb_strtable_insert3(&m->ntof, name.data, name.size, packed_v, alloc)) { upb_status_seterrf(ctx->status, "duplicate field name (%s)", shortname); @@ -1580,5 +1582,48 @@ bool upb_symtab_addfile(upb_symtab *s, return ok; } +/* Include here since we want most of this file to be stdio-free. */ +#include + +bool _upb_symtab_loaddefinit(upb_symtab *s, const upb_def_init *init) { + /* Since this function should never fail (it would indicate a bug in upb) we + * print errors to stderr instead of returning error status to the user. */ + upb_def_init **deps = init->deps; + google_protobuf_FileDescriptorProto *file; + upb_arena arena; + upb_status status = UPB_STATUS_INIT; + + if (upb_strtable_lookup(&s->files, init->filename, NULL)) { + return true; + } + + for (; *deps; deps++) { + if (!_upb_symtab_loaddefinit(s, *deps)) goto err; + } + + upb_arena_init(&arena); + file = google_protobuf_FileDescriptorProto_parsenew(init->descriptor, &arena); + + if (!file) { + upb_status_seterrf( + &status, + "Failed to parse compiled-in descriptor for file '%s'. This should " + "never happen.", + init->filename); + goto err; + } + + if (!upb_symtab_addfile(s, file, &status)) goto err; + + upb_arena_uninit(&arena); + return true; + +err: + fprintf(stderr, "Error loading compiled-in descriptor: %s\n", + upb_status_errmsg(&status)); + upb_arena_uninit(&arena); + return false; +} + #undef CHK #undef CHK_OOM diff --git a/upb/def.h b/upb/def.h index 4fe6d04..e6fdf21 100644 --- a/upb/def.h +++ b/upb/def.h @@ -659,7 +659,6 @@ const upb_filedef *upb_filedef_dep(const upb_filedef *f, int i); const upb_msgdef *upb_filedef_msg(const upb_filedef *f, int i); const upb_enumdef *upb_filedef_enum(const upb_filedef *f, int i); - UPB_END_EXTERN_C #ifdef __cplusplus @@ -707,6 +706,15 @@ bool upb_symtab_addfile(upb_symtab *s, const google_protobuf_FileDescriptorProto* file, upb_status *status); +/* For generated code only: loads a generated descriptor. */ +typedef struct upb_def_init { + struct upb_def_init **deps; + const char *filename; + upb_stringview descriptor; +} upb_def_init; + +bool _upb_symtab_loaddefinit(upb_symtab *s, const upb_def_init *init); + UPB_END_EXTERN_C #ifdef __cplusplus diff --git a/upb/upb.h b/upb/upb.h index 020022b..2fb7a88 100644 --- a/upb/upb.h +++ b/upb/upb.h @@ -463,7 +463,6 @@ struct upb_alloc { UPB_INLINE void *upb_malloc(upb_alloc *alloc, size_t size) { UPB_ASSERT(alloc); - UPB_ASSERT(size < 65535); return alloc->func(alloc, NULL, 0, size); } diff --git a/upbc/generator.cc b/upbc/generator.cc index 68996a9..3b4f6ac 100644 --- a/upbc/generator.cc +++ b/upbc/generator.cc @@ -8,6 +8,7 @@ #include "absl/strings/substitute.h" #include "google/protobuf/compiler/code_generator.h" #include "google/protobuf/descriptor.h" +#include "google/protobuf/descriptor.pb.h" #include "google/protobuf/io/zero_copy_stream.h" #include "upbc/generator.h" @@ -32,6 +33,14 @@ static std::string SourceFilename(std::string proto_filename) { return StripExtension(proto_filename) + ".upb.c"; } +static std::string DefHeaderFilename(std::string proto_filename) { + return StripExtension(proto_filename) + ".upbdefs.h"; +} + +static std::string DefSourceFilename(std::string proto_filename) { + return StripExtension(proto_filename) + ".upbdefs.c"; +} + class Output { public: Output(protobuf::io::ZeroCopyOutputStream* stream) : stream_(stream) {} @@ -165,6 +174,10 @@ std::string ToCIdent(absl::string_view str) { return absl::StrReplaceAll(str, {{".", "_"}, {"/", "_"}}); } +std::string DefInitSymbol(const protobuf::FileDescriptor *file) { + return ToCIdent(file->name()) + "_upbdefinit"; +} + std::string ToPreproc(absl::string_view str) { return absl::AsciiStrToUpper(ToCIdent(str)); } @@ -558,6 +571,91 @@ void WriteSource(const protobuf::FileDescriptor* file, Output& output) { output("\n"); } +void GenerateMessageDefAccessor(const protobuf::Descriptor* d, Output& output) { + output("UPB_INLINE const upb_msgdef *$0_getmsgdef(upb_symtab *s) {\n", + ToCIdent(d->full_name())); + output(" _upb_symtab_loaddefinit(s, &$0);\n", DefInitSymbol(d->file())); + output(" return upb_symtab_lookupmsg(s, \"$0\");\n", d->full_name()); + output("}\n"); + output("\n"); + + for (int i = 0; i < d->nested_type_count(); i++) { + GenerateMessageDefAccessor(d->nested_type(i), output); + } +} + +void WriteDefHeader(const protobuf::FileDescriptor* file, Output& output) { + EmitFileWarning(file, output); + + output("extern upb_def_init $0;\n", DefInitSymbol(file)); + + for (int i = 0; i < file->message_type_count(); i++) { + GenerateMessageDefAccessor(file->message_type(i), output); + } +} + +// Escape C++ trigraphs by escaping question marks to \? +std::string EscapeTrigraphs(absl::string_view to_escape) { + return absl::StrReplaceAll(to_escape, {{"?", "\\?"}}); +} + +void WriteDefSource(const protobuf::FileDescriptor* file, Output& output) { + EmitFileWarning(file, output); + + output("#include \"upb/def.h\"\n"); + output("\n"); + + for (int i = 0; i < file->dependency_count(); i++) { + output("extern upb_def_init $0;\n", DefInitSymbol(file->dependency(i))); + } + + protobuf::FileDescriptorProto file_proto; + file->CopyTo(&file_proto); + std::string file_data; + file_proto.SerializeToString(&file_data); + + output("static const char descriptor[$0] =\n", file_data.size()); + + { + if (file_data.size() > 65535) { + // Workaround for MSVC: "Error C1091: compiler limit: string exceeds + // 65535 bytes in length". Declare a static array of chars rather than + // use a string literal. Only write 25 bytes per line. + static const int kBytesPerLine = 25; + output("{ "); + for (int i = 0; i < file_data.size();) { + for (int j = 0; j < kBytesPerLine && i < file_data.size(); ++i, ++j) { + output("'$0', ", absl::CEscape(file_data.substr(i, 1))); + } + output("\n"); + } + output("'\\0' }"); // null-terminate + } else { + // Only write 40 bytes per line. + static const int kBytesPerLine = 40; + for (int i = 0; i < file_data.size(); i += kBytesPerLine) { + output( + "\"$0\"\n", + EscapeTrigraphs(absl::CEscape(file_data.substr(i, kBytesPerLine)))); + } + } + output(";\n"); + } + + output("static upb_def_init *deps[$0] = {\n", file->dependency_count() + 1); + for (int i = 0; i < file->dependency_count(); i++) { + output(" $0,\n", DefInitSymbol(file->dependency(i))); + } + output(" NULL\n"); + output("};\n"); + + output("upb_def_init $0 = {\n", DefInitSymbol(file)); + output(" deps,\n"); + output(" \"$0\",\n", file->name()); + output(" UPB_STRINGVIEW_INIT(descriptor, $0)\n", file_data.size()); + output("};\n"); +} + bool Generator::Generate(const protobuf::FileDescriptor* file, const std::string& parameter, protoc::GeneratorContext* context, @@ -568,6 +666,12 @@ bool Generator::Generate(const protobuf::FileDescriptor* file, Output c_output(context->Open(SourceFilename(file->name()))); WriteSource(file, c_output); + Output h_def_output(context->Open(DefHeaderFilename(file->name()))); + WriteDefHeader(file, h_def_output); + + Output c_def_output(context->Open(DefSourceFilename(file->name()))); + WriteDefSource(file, c_def_output); + return true; } -- cgit v1.2.3 From 549a828f76bfbc42276797ca5eef2c1f730b0d1f Mon Sep 17 00:00:00 2001 From: Josh Haberman Date: Mon, 17 Dec 2018 18:21:26 -0800 Subject: Disbled CMake tests for now. --- CMakeLists.txt | 53 ------------------------------------------------ tools/make_cmakelists.py | 44 +++++++++++++++++++++------------------- 2 files changed, 23 insertions(+), 74 deletions(-) (limited to 'tools') diff --git a/CMakeLists.txt b/CMakeLists.txt index 0a24f90..699653f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -115,58 +115,5 @@ add_library(upb_test tests/testmain.cc tests/test_util.h tests/upb_test.h) -add_executable(test_varint - tests/pb/test_varint.c) -add_test(NAME test_varint COMMAND test_varint) -target_link_libraries(test_varint - upb_pb - upb_test) -add_executable(test_handlers - tests/test_handlers.c) -add_test(NAME test_handlers COMMAND test_handlers) -target_link_libraries(test_handlers - descriptor_upbproto - upb_pb - upb_test) -add_executable(test_decoder - tests/pb/test_decoder.cc) -add_test(NAME test_decoder COMMAND test_decoder) -target_link_libraries(test_decoder - test_decoder_upbproto - upb_pb - upb_test) -add_executable(test_encoder - tests/pb/test_encoder.cc) -add_test(NAME test_encoder COMMAND test_encoder) -add_custom_command( - TARGET test_encoder POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy - ${CMAKE_SOURCE_DIR}/google/protobuf/descriptor.pb - ${CMAKE_CURRENT_BINARY_DIR}/google/protobuf/descriptor.pb) -target_link_libraries(test_encoder - upb_cc_bindings - upb_pb - upb_test) -add_executable(test_cpp - tests/test_cpp.cc) -add_test(NAME test_cpp COMMAND test_cpp) -target_link_libraries(test_cpp - test_cpp_upbproto - upb - upb_pb - upb_test) -add_executable(test_table - tests/test_table.cc) -add_test(NAME test_table COMMAND test_table) -target_link_libraries(test_table - upb - upb_test) -add_executable(test_json - tests/json/test_json.cc) -add_test(NAME test_json COMMAND test_json) -target_link_libraries(test_json - test_json_upbproto - upb_json - upb_test) diff --git a/tools/make_cmakelists.py b/tools/make_cmakelists.py index 2b426b5..0d5640d 100755 --- a/tools/make_cmakelists.py +++ b/tools/make_cmakelists.py @@ -59,27 +59,29 @@ class BuildFileFunctions(object): pass def cc_test(self, **kwargs): - self.converter.toplevel += "add_executable(%s\n %s)\n" % ( - kwargs["name"], - "\n ".join(kwargs["srcs"]) - ) - self.converter.toplevel += "add_test(NAME %s COMMAND %s)\n" % ( - kwargs["name"], - kwargs["name"], - ) - - if "data" in kwargs: - for data_dep in kwargs["data"]: - self.converter.toplevel += textwrap.dedent("""\ - add_custom_command( - TARGET %s POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy - ${CMAKE_SOURCE_DIR}/%s - ${CMAKE_CURRENT_BINARY_DIR}/%s)\n""" % ( - kwargs["name"], data_dep, data_dep - )) - - self._add_deps(kwargs) + # Disable this until we properly support upb_proto_library(). + # self.converter.toplevel += "add_executable(%s\n %s)\n" % ( + # kwargs["name"], + # "\n ".join(kwargs["srcs"]) + # ) + # self.converter.toplevel += "add_test(NAME %s COMMAND %s)\n" % ( + # kwargs["name"], + # kwargs["name"], + # ) + + # if "data" in kwargs: + # for data_dep in kwargs["data"]: + # self.converter.toplevel += textwrap.dedent("""\ + # add_custom_command( + # TARGET %s POST_BUILD + # COMMAND ${CMAKE_COMMAND} -E copy + # ${CMAKE_SOURCE_DIR}/%s + # ${CMAKE_CURRENT_BINARY_DIR}/%s)\n""" % ( + # kwargs["name"], data_dep, data_dep + # )) + + # self._add_deps(kwargs) + pass def py_library(self, **kwargs): pass -- cgit v1.2.3 From 1508648f30cbaf5a3590572b2313fb5b595a7946 Mon Sep 17 00:00:00 2001 From: Joshua Haberman Date: Tue, 15 Jan 2019 04:21:56 -0800 Subject: Build & fix the JIT. --- BUILD | 20 ++- tools/amalgamate.py | 4 + tools/make_cmakelists.py | 6 + upb/pb/compile_decoder_x64.c | 3 +- upb/pb/compile_decoder_x64.dasc | 19 ++- upb/pb/compile_decoder_x64.h | 287 ++++++++++++++++++++-------------------- upb/upb.h | 1 + 7 files changed, 189 insertions(+), 151 deletions(-) (limited to 'tools') diff --git a/BUILD b/BUILD index 9e79d95..5804d36 100644 --- a/BUILD +++ b/BUILD @@ -11,6 +11,11 @@ load( "upb_proto_reflection_library", ) +config_setting( + name = "k8", + values = {"cpu": "k8"}, +) + # C/C++ rules ################################################################## cc_library( @@ -62,7 +67,15 @@ cc_library( "upb/pb/textprinter.c", "upb/pb/varint.c", "upb/pb/varint.int.h", - ], + ] + select({ + ":k8": [ + "upb/pb/compile_decoder_x64.c", + "upb/pb/compile_decoder_x64.h", + "third_party/dynasm/dasm_proto.h", + "third_party/dynasm/dasm_x86.h", + ], + "//conditions:default": [], + }), hdrs = [ "upb/pb/decoder.h", "upb/pb/encoder.h", @@ -72,7 +85,10 @@ cc_library( "-std=c89", "-pedantic", "-Wno-long-long", - ], + ] + select({ + ":k8": ["-DUPB_USE_JIT_X64"], + "//conditions:default": [], + }), deps = [ ":upb", ], diff --git a/tools/amalgamate.py b/tools/amalgamate.py index 4739a94..9ad0286 100755 --- a/tools/amalgamate.py +++ b/tools/amalgamate.py @@ -51,6 +51,10 @@ output_path = sys.argv[2] amalgamator = Amalgamator(include_path, output_path) for filename in sys.argv[3:]: + # Leave JIT out of the amalgamation. + if "x64" in filename or "dynasm" in filename: + continue + amalgamator.add_src(filename.strip()) amalgamator.finish() diff --git a/tools/make_cmakelists.py b/tools/make_cmakelists.py index 0d5640d..c2700b6 100755 --- a/tools/make_cmakelists.py +++ b/tools/make_cmakelists.py @@ -128,6 +128,12 @@ class BuildFileFunctions(object): def genrule(self, **kwargs): pass + def config_setting(self, **kwargs): + pass + + def select(self, arg_dict): + return [] + def glob(*args): return [] diff --git a/upb/pb/compile_decoder_x64.c b/upb/pb/compile_decoder_x64.c index fd541a4..7c716e8 100644 --- a/upb/pb/compile_decoder_x64.c +++ b/upb/pb/compile_decoder_x64.c @@ -233,7 +233,8 @@ static int getjmptarget(jitcompiler *jc, const void *key) { * * Creates/allocates a pclabel for this target if one does not exist already. */ static int jmptarget(jitcompiler *jc, const void *key) { - // Optimizer sometimes can't figure out that initializing this is unnecessary. + /* Optimizer sometimes can't figure out that initializing this is unnecessary. + */ int pclabel = 0; if (!try_getjmptarget(jc, key, &pclabel)) { pclabel = alloc_pclabel(jc); diff --git a/upb/pb/compile_decoder_x64.dasc b/upb/pb/compile_decoder_x64.dasc index 7fcd006..7dc1987 100644 --- a/upb/pb/compile_decoder_x64.dasc +++ b/upb/pb/compile_decoder_x64.dasc @@ -92,7 +92,7 @@ |.endmacro | |.macro load_handler_data, h, arg -| ld64 upb_handlers_gethandlerdata(h, arg) +| ld64 gethandlerdata(h, arg) |.endmacro | |.macro chkeob, bytes, target @@ -140,7 +140,7 @@ #define DECODE_EOF -3 static upb_func *gethandler(const upb_handlers *h, upb_selector_t sel) { - return h ? upb_handlers_gethandler(h, sel) : NULL; + return h ? upb_handlers_gethandler(h, sel, NULL) : NULL; } /* Defines an "assembly label" for the current code generation offset. @@ -179,14 +179,19 @@ static void asmlabel(jitcompiler *jc, const char *fmt, ...) { /* Should only be called when the associated handler is known to exist. */ static bool alwaysok(const upb_handlers *h, upb_selector_t sel) { - upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER; + upb_handlerattr attr = UPB_HANDLERATTR_INIT; bool ok = upb_handlers_getattr(h, sel, &attr); - bool ret; UPB_ASSERT(ok); - ret = upb_handlerattr_alwaysok(&attr); - upb_handlerattr_uninit(&attr); - return ret; + return attr.alwaysok; +} + +static const void *gethandlerdata(const upb_handlers *h, upb_selector_t sel) { + upb_handlerattr attr = UPB_HANDLERATTR_INIT; + bool ok = upb_handlers_getattr(h, sel, &attr); + + UPB_ASSERT(ok); + return attr.handler_data; } /* Emit static assembly routines; code that does not vary based on the message diff --git a/upb/pb/compile_decoder_x64.h b/upb/pb/compile_decoder_x64.h index 2c07063..4a4dffc 100644 --- a/upb/pb/compile_decoder_x64.h +++ b/upb/pb/compile_decoder_x64.h @@ -278,7 +278,7 @@ static const char *const upb_jit_globalnames[] = { /*|.endmacro */ /*| */ /*|.macro load_handler_data, h, arg */ -/*| ld64 upb_handlers_gethandlerdata(h, arg) */ +/*| ld64 gethandlerdata(h, arg) */ /*|.endmacro */ /*| */ /*|.macro chkeob, bytes, target */ @@ -326,7 +326,7 @@ static const char *const upb_jit_globalnames[] = { #define DECODE_EOF -3 static upb_func *gethandler(const upb_handlers *h, upb_selector_t sel) { - return h ? upb_handlers_gethandler(h, sel) : NULL; + return h ? upb_handlers_gethandler(h, sel, NULL) : NULL; } /* Defines an "assembly label" for the current code generation offset. @@ -367,14 +367,19 @@ static void asmlabel(jitcompiler *jc, const char *fmt, ...) { /* Should only be called when the associated handler is known to exist. */ static bool alwaysok(const upb_handlers *h, upb_selector_t sel) { - upb_handlerattr attr = UPB_HANDLERATTR_INITIALIZER; + upb_handlerattr attr = UPB_HANDLERATTR_INIT; bool ok = upb_handlers_getattr(h, sel, &attr); - bool ret; UPB_ASSERT(ok); - ret = upb_handlerattr_alwaysok(&attr); - upb_handlerattr_uninit(&attr); - return ret; + return attr.alwaysok; +} + +static const void *gethandlerdata(const upb_handlers *h, upb_selector_t sel) { + upb_handlerattr attr = UPB_HANDLERATTR_INIT; + bool ok = upb_handlers_getattr(h, sel, &attr); + + UPB_ASSERT(ok); + return attr.handler_data; } /* Emit static assembly routines; code that does not vary based on the message @@ -424,7 +429,7 @@ static void emit_static_asm(jitcompiler *jc) { /*|1: */ /*| pop rbx */ dasm_put(Dst, 2, (unsigned int)((uintptr_t)upb_pbdecoder_resume), (unsigned int)(((uintptr_t)upb_pbdecoder_resume)>>32), 0xfffffffffffffff0UL, Dt2(->saved_rsp), Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt1(->sink.closure), Dt1(->end_ofs), Dt2(->bufstart_ofs), Dt2(->buf), Dt2(->call_len), Dt2(->size_param), Dt2(->call_len)); -# 238 "upb/pb/compile_decoder_x64.dasc" +# 243 "upb/pb/compile_decoder_x64.dasc" /*| pop r12 */ /*| pop r13 */ /*| pop r14 */ @@ -445,7 +450,7 @@ static void emit_static_asm(jitcompiler *jc) { /*| // the JIT resumes, and more buffer space will be available. */ /*| // Args: eax=the value that decode() should return. */ dasm_put(Dst, 115, Dt2(->callstack), (unsigned int)((uintptr_t)memcpy), (unsigned int)(((uintptr_t)memcpy)>>32), 0xfffffffffffffff0UL); -# 257 "upb/pb/compile_decoder_x64.dasc" +# 262 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "exitjit"); /*|->exitjit: */ /*| // Save the stack into DECODER->callstack. */ @@ -473,7 +478,7 @@ static void emit_static_asm(jitcompiler *jc) { /*| // (from the caller's perspective) not to return until the decoder is */ /*| // resumed. */ dasm_put(Dst, 161, Dt2(->callstack), Dt2(->saved_rsp), Dt2(->call_len), (unsigned int)((uintptr_t)memcpy), (unsigned int)(((uintptr_t)memcpy)>>32), 0xfffffffffffffff0UL, Dt2(->saved_rsp)); -# 283 "upb/pb/compile_decoder_x64.dasc" +# 288 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "suspend"); /*|->suspend: */ /*| cmp DECODER->ptr, PTR */ @@ -486,7 +491,7 @@ static void emit_static_asm(jitcompiler *jc) { /*| jmp ->exitjit */ /*| */ dasm_put(Dst, 222, Dt2(->ptr), Dt2(->checkpoint), Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt2(->delim_end), Dt2(->buf), Dt2(->bufstart_ofs), Dt1(->end_ofs), Dt1(->sink.closure), (unsigned int)((uintptr_t)upb_pbdecoder_suspend), (unsigned int)(((uintptr_t)upb_pbdecoder_suspend)>>32), 0xfffffffffffffff0UL); -# 294 "upb/pb/compile_decoder_x64.dasc" +# 299 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "pushlendelim"); /*|->pushlendelim: */ /*|1: */ @@ -499,7 +504,7 @@ static void emit_static_asm(jitcompiler *jc) { } else { dasm_put(Dst, 321); } -# 300 "upb/pb/compile_decoder_x64.dasc" +# 305 "upb/pb/compile_decoder_x64.dasc" /*| mov rcx, DELIMEND */ /*| sub rcx, PTR */ /*| sub rcx, rdx */ @@ -520,7 +525,7 @@ static void emit_static_asm(jitcompiler *jc) { /*| ja >2 */ /*| mov DATAEND, DELIMEND // If DELIMEND >= PTR && DELIMEND < DATAEND */ dasm_put(Dst, 337, Dt1(->end_ofs), Dt2(->limit), sizeof(upb_pbdecoder_frame), Dt1(->groupnum), Dt2(->end)); -# 319 "upb/pb/compile_decoder_x64.dasc" +# 324 "upb/pb/compile_decoder_x64.dasc" /*|2: */ /*| ret */ /*|3: */ @@ -540,7 +545,7 @@ static void emit_static_asm(jitcompiler *jc) { dasm_put(Dst, 454); } } -# 327 "upb/pb/compile_decoder_x64.dasc" +# 332 "upb/pb/compile_decoder_x64.dasc" /*| callp upb_pbdecoder_seterr */ /*| call ->suspend */ /*| jmp <1 */ @@ -561,7 +566,7 @@ static void emit_static_asm(jitcompiler *jc) { dasm_put(Dst, 454); } } -# 336 "upb/pb/compile_decoder_x64.dasc" +# 341 "upb/pb/compile_decoder_x64.dasc" /*| callp upb_pbdecoder_seterr */ /*| call ->suspend */ /*| jmp <1 */ @@ -592,7 +597,7 @@ static void emit_static_asm(jitcompiler *jc) { /*|.endmacro */ /*| */ dasm_put(Dst, 497, (unsigned int)((uintptr_t)upb_pbdecoder_seterr), (unsigned int)(((uintptr_t)upb_pbdecoder_seterr)>>32), 0xfffffffffffffff0UL); -# 365 "upb/pb/compile_decoder_x64.dasc" +# 370 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "parse_unknown"); /*| // Args: edx=fieldnum, cl=wire type */ /*|->parse_unknown: */ @@ -607,7 +612,7 @@ static void emit_static_asm(jitcompiler *jc) { /*| cmp eax, DECODE_ENDGROUP */ /*| jne >1 */ dasm_put(Dst, 526, Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt2(->delim_end), Dt2(->buf), Dt2(->bufstart_ofs), Dt1(->end_ofs), Dt1(->sink.closure), (unsigned int)((uintptr_t)upb_pbdecoder_skipunknown), (unsigned int)(((uintptr_t)upb_pbdecoder_skipunknown)>>32), 0xfffffffffffffff0UL, Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt1(->sink.closure), Dt1(->end_ofs), Dt2(->bufstart_ofs), Dt2(->buf), DECODE_ENDGROUP); -# 378 "upb/pb/compile_decoder_x64.dasc" +# 383 "upb/pb/compile_decoder_x64.dasc" /*| ret // Return eax=DECODE_ENDGROUP, not zero */ /*|1: */ /*| cmp eax, DECODE_OK */ @@ -627,26 +632,26 @@ static void emit_static_asm(jitcompiler *jc) { /*| // completes. We also set DECODER->ptr to this value which is a signal to */ /*| // ->suspend that DECODER->checkpoint is up to date. */ dasm_put(Dst, 623, DECODE_OK); -# 396 "upb/pb/compile_decoder_x64.dasc" +# 401 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "skip_decode_f32_fallback"); /*|->skipf32_fallback: */ /*|->decodef32_fallback: */ /*| getvalue_slow upb_pbdecoder_decode_f32, 4 */ dasm_put(Dst, 647, Dt2(->checkpoint), Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt2(->delim_end), Dt2(->buf), Dt2(->bufstart_ofs), Dt1(->end_ofs), Dt1(->sink.closure), (unsigned int)((uintptr_t)upb_pbdecoder_decode_f32), (unsigned int)(((uintptr_t)upb_pbdecoder_decode_f32)>>32), 0xfffffffffffffff0UL, Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt1(->sink.closure), Dt1(->end_ofs)); -# 400 "upb/pb/compile_decoder_x64.dasc" +# 405 "upb/pb/compile_decoder_x64.dasc" /*| */ dasm_put(Dst, 751, Dt2(->bufstart_ofs), Dt2(->buf), Dt2(->ptr)); -# 401 "upb/pb/compile_decoder_x64.dasc" +# 406 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "skip_decode_f64_fallback"); /*|->skipf64_fallback: */ /*|->decodef64_fallback: */ /*| getvalue_slow upb_pbdecoder_decode_f64, 8 */ dasm_put(Dst, 799, Dt2(->checkpoint), Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt2(->delim_end), Dt2(->buf), Dt2(->bufstart_ofs), Dt1(->end_ofs), Dt1(->sink.closure), (unsigned int)((uintptr_t)upb_pbdecoder_decode_f64), (unsigned int)(((uintptr_t)upb_pbdecoder_decode_f64)>>32), 0xfffffffffffffff0UL, Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt1(->sink.closure), Dt1(->end_ofs)); -# 405 "upb/pb/compile_decoder_x64.dasc" +# 410 "upb/pb/compile_decoder_x64.dasc" /*| */ /*| // Called for varint >= 1 byte. */ dasm_put(Dst, 903, Dt2(->bufstart_ofs), Dt2(->buf), Dt2(->ptr)); -# 407 "upb/pb/compile_decoder_x64.dasc" +# 412 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "skip_decode_v32_fallback"); /*|->skipv32_fallback: */ /*|->skipv64_fallback: */ @@ -657,7 +662,7 @@ static void emit_static_asm(jitcompiler *jc) { } else { dasm_put(Dst, 964); } -# 411 "upb/pb/compile_decoder_x64.dasc" +# 416 "upb/pb/compile_decoder_x64.dasc" /*| // With at least 16 bytes left, we can do a branch-less SSE version. */ /*| movdqu xmm0, [PTR] */ /*| pmovmskb eax, xmm0 // bits 0-15 are continuation bits, 16-31 are 0. */ @@ -687,7 +692,7 @@ static void emit_static_asm(jitcompiler *jc) { /*| */ /*| // Returns tag in edx */ dasm_put(Dst, 980, 10); -# 439 "upb/pb/compile_decoder_x64.dasc" +# 444 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "decode_unknown_tag_fallback"); /*|->decode_unknown_tag_fallback: */ /*| sub rsp, 16 */ @@ -705,7 +710,7 @@ static void emit_static_asm(jitcompiler *jc) { /*| callp upb_pbdecoder_decode_varint_slow */ /*| load_regs */ dasm_put(Dst, 1053, Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt2(->delim_end), Dt2(->buf), Dt2(->bufstart_ofs), Dt1(->end_ofs), Dt1(->sink.closure), (unsigned int)((uintptr_t)upb_pbdecoder_decode_varint_slow), (unsigned int)(((uintptr_t)upb_pbdecoder_decode_varint_slow)>>32), 0xfffffffffffffff0UL, Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt1(->sink.closure)); -# 455 "upb/pb/compile_decoder_x64.dasc" +# 460 "upb/pb/compile_decoder_x64.dasc" /*| cmp eax, 0 */ /*| jge >3 */ /*| mov edx, [rsp] // Success; return parsed data. */ @@ -717,7 +722,7 @@ static void emit_static_asm(jitcompiler *jc) { /*| */ /*| // Called for varint >= 1 byte. */ dasm_put(Dst, 1156, Dt1(->end_ofs), Dt2(->bufstart_ofs), Dt2(->buf)); -# 465 "upb/pb/compile_decoder_x64.dasc" +# 470 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "decode_v32_v64_fallback"); /*|->decodev32_fallback: */ /*|->decodev64_fallback: */ @@ -728,7 +733,7 @@ static void emit_static_asm(jitcompiler *jc) { } else { dasm_put(Dst, 1207); } -# 469 "upb/pb/compile_decoder_x64.dasc" +# 474 "upb/pb/compile_decoder_x64.dasc" /*| // OPT: do something faster than just calling the C version. */ /*| mov rdi, PTR */ /*| callp upb_vdecode_fast */ @@ -740,17 +745,17 @@ static void emit_static_asm(jitcompiler *jc) { /*| ret */ /*| */ dasm_put(Dst, 1223, (unsigned int)((uintptr_t)upb_vdecode_fast), (unsigned int)(((uintptr_t)upb_vdecode_fast)>>32), 0xfffffffffffffff0UL, Dt2(->ptr)); -# 479 "upb/pb/compile_decoder_x64.dasc" +# 484 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "decode_varint_slow"); /*|->decode_varint_slow: */ /*| // Slow path: end of buffer or error (varint length >= 10). */ /*| getvalue_slow upb_pbdecoder_decode_varint_slow, 1 */ dasm_put(Dst, 1268, Dt2(->checkpoint), Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt2(->delim_end), Dt2(->buf), Dt2(->bufstart_ofs), Dt1(->end_ofs), Dt1(->sink.closure), (unsigned int)((uintptr_t)upb_pbdecoder_decode_varint_slow), (unsigned int)(((uintptr_t)upb_pbdecoder_decode_varint_slow)>>32), 0xfffffffffffffff0UL, Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt1(->sink.closure), Dt1(->end_ofs), Dt2(->bufstart_ofs)); -# 483 "upb/pb/compile_decoder_x64.dasc" +# 488 "upb/pb/compile_decoder_x64.dasc" /*| */ /*| // Args: rsi=expected tag, return=rax (DECODE_{OK,MISMATCH}) */ dasm_put(Dst, 1374, Dt2(->buf), Dt2(->ptr)); -# 485 "upb/pb/compile_decoder_x64.dasc" +# 490 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "checktag_fallback"); /*|->checktag_fallback: */ /*| sub rsp, 8 */ @@ -762,7 +767,7 @@ static void emit_static_asm(jitcompiler *jc) { /*| callp upb_pbdecoder_checktag_slow */ /*| load_regs */ dasm_put(Dst, 1418, Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt2(->delim_end), Dt2(->buf), Dt2(->bufstart_ofs), Dt1(->end_ofs), Dt1(->sink.closure), Dt2(->checkpoint), (unsigned int)((uintptr_t)upb_pbdecoder_checktag_slow), (unsigned int)(((uintptr_t)upb_pbdecoder_checktag_slow)>>32), 0xfffffffffffffff0UL, Dt2(->top), Dt2(->ptr), Dt2(->data_end), Dt1(->sink.closure), Dt1(->end_ofs), Dt2(->bufstart_ofs)); -# 495 "upb/pb/compile_decoder_x64.dasc" +# 500 "upb/pb/compile_decoder_x64.dasc" /*| cmp eax, 0 */ /*| jge >2 */ /*| add rsp, 8 */ @@ -780,7 +785,7 @@ static void emit_static_asm(jitcompiler *jc) { /*| // Preserves: rcx, rdx */ /*| // OPT: Could write this in assembly if it's a hotspot. */ dasm_put(Dst, 1517, Dt2(->buf), DECODE_EOF); -# 511 "upb/pb/compile_decoder_x64.dasc" +# 516 "upb/pb/compile_decoder_x64.dasc" asmlabel(jc, "hashlookup"); /*|->hashlookup: */ /*| push rcx */ @@ -802,7 +807,7 @@ static void emit_static_asm(jitcompiler *jc) { /*| not rax */ /*| ret */ dasm_put(Dst, 1559, (unsigned int)((uintptr_t)upb_inttable_lookup), (unsigned int)(((uintptr_t)upb_inttable_lookup)>>32), 0xfffffffffffffff0UL); -# 531 "upb/pb/compile_decoder_x64.dasc" +# 536 "upb/pb/compile_decoder_x64.dasc" } static void jitprimitive(jitcompiler *jc, opcode op, @@ -828,63 +833,63 @@ static void jitprimitive(jitcompiler *jc, opcode op, } else { dasm_put(Dst, 1636, fastbytes); } -# 550 "upb/pb/compile_decoder_x64.dasc" +# 555 "upb/pb/compile_decoder_x64.dasc" /*|2: */ dasm_put(Dst, 1652); -# 551 "upb/pb/compile_decoder_x64.dasc" +# 556 "upb/pb/compile_decoder_x64.dasc" switch (vtype) { case V32: /*| call ->decodev32_fallback */ dasm_put(Dst, 1655); -# 554 "upb/pb/compile_decoder_x64.dasc" +# 559 "upb/pb/compile_decoder_x64.dasc" break; case V64: /*| call ->decodev64_fallback */ dasm_put(Dst, 1659); -# 557 "upb/pb/compile_decoder_x64.dasc" +# 562 "upb/pb/compile_decoder_x64.dasc" break; case F32: /*| call ->decodef32_fallback */ dasm_put(Dst, 1663); -# 560 "upb/pb/compile_decoder_x64.dasc" +# 565 "upb/pb/compile_decoder_x64.dasc" break; case F64: /*| call ->decodef64_fallback */ dasm_put(Dst, 1667); -# 563 "upb/pb/compile_decoder_x64.dasc" +# 568 "upb/pb/compile_decoder_x64.dasc" break; case X: break; } /*| jmp >4 */ dasm_put(Dst, 1671); -# 567 "upb/pb/compile_decoder_x64.dasc" +# 572 "upb/pb/compile_decoder_x64.dasc" /* Fast path decode; for when check_bytes bytes are available. */ /*|3: */ dasm_put(Dst, 1676); -# 570 "upb/pb/compile_decoder_x64.dasc" +# 575 "upb/pb/compile_decoder_x64.dasc" switch (op) { case OP_PARSE_SFIXED32: case OP_PARSE_FIXED32: /*| mov edx, dword [PTR] */ dasm_put(Dst, 1679); -# 574 "upb/pb/compile_decoder_x64.dasc" +# 579 "upb/pb/compile_decoder_x64.dasc" break; case OP_PARSE_SFIXED64: case OP_PARSE_FIXED64: /*| mov rdx, qword [PTR] */ dasm_put(Dst, 1682); -# 578 "upb/pb/compile_decoder_x64.dasc" +# 583 "upb/pb/compile_decoder_x64.dasc" break; case OP_PARSE_FLOAT: /*| movss xmm0, dword [PTR] */ dasm_put(Dst, 1686); -# 581 "upb/pb/compile_decoder_x64.dasc" +# 586 "upb/pb/compile_decoder_x64.dasc" break; case OP_PARSE_DOUBLE: /*| movsd xmm0, qword [PTR] */ dasm_put(Dst, 1692); -# 584 "upb/pb/compile_decoder_x64.dasc" +# 589 "upb/pb/compile_decoder_x64.dasc" break; default: /* Inline one byte of varint decoding. */ @@ -892,7 +897,7 @@ static void jitprimitive(jitcompiler *jc, opcode op, /*| test dl, dl */ /*| js <2 // Fallback to slow path for >1 byte varint. */ dasm_put(Dst, 1698); -# 590 "upb/pb/compile_decoder_x64.dasc" +# 595 "upb/pb/compile_decoder_x64.dasc" break; } @@ -900,7 +905,7 @@ static void jitprimitive(jitcompiler *jc, opcode op, /* (only needed for a few types). */ /*|4: */ dasm_put(Dst, 1708); -# 596 "upb/pb/compile_decoder_x64.dasc" +# 601 "upb/pb/compile_decoder_x64.dasc" switch (op) { case OP_PARSE_SINT32: /* 32-bit zig-zag decode. */ @@ -910,7 +915,7 @@ static void jitprimitive(jitcompiler *jc, opcode op, /*| neg eax */ /*| xor edx, eax */ dasm_put(Dst, 1711); -# 604 "upb/pb/compile_decoder_x64.dasc" +# 609 "upb/pb/compile_decoder_x64.dasc" break; case OP_PARSE_SINT64: /* 64-bit zig-zag decode. */ @@ -920,13 +925,13 @@ static void jitprimitive(jitcompiler *jc, opcode op, /*| neg rax */ /*| xor rdx, rax */ dasm_put(Dst, 1725); -# 612 "upb/pb/compile_decoder_x64.dasc" +# 617 "upb/pb/compile_decoder_x64.dasc" break; case OP_PARSE_BOOL: /*| test rdx, rdx */ /*| setne dl */ dasm_put(Dst, 1744); -# 616 "upb/pb/compile_decoder_x64.dasc" +# 621 "upb/pb/compile_decoder_x64.dasc" break; default: break; } @@ -938,29 +943,29 @@ static void jitprimitive(jitcompiler *jc, opcode op, case UPB_TYPE_UINT64: /*| mov [CLOSURE + offset], rdx */ dasm_put(Dst, 1751, offset); -# 626 "upb/pb/compile_decoder_x64.dasc" +# 631 "upb/pb/compile_decoder_x64.dasc" break; case UPB_TYPE_INT32: case UPB_TYPE_UINT32: case UPB_TYPE_ENUM: /*| mov [CLOSURE + offset], edx */ dasm_put(Dst, 1756, offset); -# 631 "upb/pb/compile_decoder_x64.dasc" +# 636 "upb/pb/compile_decoder_x64.dasc" break; case UPB_TYPE_DOUBLE: /*| movsd qword [CLOSURE + offset], XMMARG1 */ dasm_put(Dst, 1761, offset); -# 634 "upb/pb/compile_decoder_x64.dasc" +# 639 "upb/pb/compile_decoder_x64.dasc" break; case UPB_TYPE_FLOAT: /*| movss dword [CLOSURE + offset], XMMARG1 */ dasm_put(Dst, 1769, offset); -# 637 "upb/pb/compile_decoder_x64.dasc" +# 642 "upb/pb/compile_decoder_x64.dasc" break; case UPB_TYPE_BOOL: /*| mov [CLOSURE + offset], dl */ dasm_put(Dst, 1777, offset); -# 640 "upb/pb/compile_decoder_x64.dasc" +# 645 "upb/pb/compile_decoder_x64.dasc" break; case UPB_TYPE_STRING: case UPB_TYPE_BYTES: @@ -971,13 +976,13 @@ static void jitprimitive(jitcompiler *jc, opcode op, if (hasbit >= 0) { dasm_put(Dst, 1782, ((uint32_t)hasbit / 8), (1 << ((uint32_t)hasbit % 8))); } -# 647 "upb/pb/compile_decoder_x64.dasc" +# 652 "upb/pb/compile_decoder_x64.dasc" } else if (handler) { /*| mov ARG1_64, CLOSURE */ /*| load_handler_data h, sel */ dasm_put(Dst, 1788); { - uintptr_t v = (uintptr_t)upb_handlers_gethandlerdata(h, sel); + uintptr_t v = (uintptr_t)gethandlerdata(h, sel); if (v > 0xffffffff) { dasm_put(Dst, 446, (unsigned int)(v), (unsigned int)((v)>>32)); } else if (v) { @@ -986,10 +991,10 @@ static void jitprimitive(jitcompiler *jc, opcode op, dasm_put(Dst, 454); } } -# 650 "upb/pb/compile_decoder_x64.dasc" +# 655 "upb/pb/compile_decoder_x64.dasc" /*| callp handler */ dasm_put(Dst, 1793, (unsigned int)((uintptr_t)handler), (unsigned int)(((uintptr_t)handler)>>32), 0xfffffffffffffff0UL); -# 651 "upb/pb/compile_decoder_x64.dasc" +# 656 "upb/pb/compile_decoder_x64.dasc" if (!alwaysok(h, sel)) { /*| test al, al */ /*| jnz >5 */ @@ -997,7 +1002,7 @@ static void jitprimitive(jitcompiler *jc, opcode op, /*| jmp <1 */ /*|5: */ dasm_put(Dst, 1815); -# 657 "upb/pb/compile_decoder_x64.dasc" +# 662 "upb/pb/compile_decoder_x64.dasc" } } @@ -1005,7 +1010,7 @@ static void jitprimitive(jitcompiler *jc, opcode op, * data until the callback has returned success. */ /*| add PTR, fastbytes */ dasm_put(Dst, 1831, fastbytes); -# 663 "upb/pb/compile_decoder_x64.dasc" +# 668 "upb/pb/compile_decoder_x64.dasc" } else { /* No handler registered for this value, just skip it. */ /*| chkneob fastbytes, >3 */ @@ -1014,30 +1019,30 @@ static void jitprimitive(jitcompiler *jc, opcode op, } else { dasm_put(Dst, 1636, fastbytes); } -# 666 "upb/pb/compile_decoder_x64.dasc" +# 671 "upb/pb/compile_decoder_x64.dasc" /*|2: */ dasm_put(Dst, 1652); -# 667 "upb/pb/compile_decoder_x64.dasc" +# 672 "upb/pb/compile_decoder_x64.dasc" switch (vtype) { case V32: /*| call ->skipv32_fallback */ dasm_put(Dst, 1836); -# 670 "upb/pb/compile_decoder_x64.dasc" +# 675 "upb/pb/compile_decoder_x64.dasc" break; case V64: /*| call ->skipv64_fallback */ dasm_put(Dst, 1840); -# 673 "upb/pb/compile_decoder_x64.dasc" +# 678 "upb/pb/compile_decoder_x64.dasc" break; case F32: /*| call ->skipf32_fallback */ dasm_put(Dst, 1844); -# 676 "upb/pb/compile_decoder_x64.dasc" +# 681 "upb/pb/compile_decoder_x64.dasc" break; case F64: /*| call ->skipf64_fallback */ dasm_put(Dst, 1848); -# 679 "upb/pb/compile_decoder_x64.dasc" +# 684 "upb/pb/compile_decoder_x64.dasc" break; case X: break; } @@ -1045,16 +1050,16 @@ static void jitprimitive(jitcompiler *jc, opcode op, /* Fast-path skip. */ /*|3: */ dasm_put(Dst, 1676); -# 685 "upb/pb/compile_decoder_x64.dasc" +# 690 "upb/pb/compile_decoder_x64.dasc" if (vtype == V32 || vtype == V64) { /*| test byte [PTR], 0x80 */ /*| jnz <2 */ dasm_put(Dst, 1852); -# 688 "upb/pb/compile_decoder_x64.dasc" +# 693 "upb/pb/compile_decoder_x64.dasc" } /*| add PTR, fastbytes */ dasm_put(Dst, 1831, fastbytes); -# 690 "upb/pb/compile_decoder_x64.dasc" +# 695 "upb/pb/compile_decoder_x64.dasc" } } @@ -1075,7 +1080,7 @@ static void jitdispatch(jitcompiler *jc, /*|=>define_jmptarget(jc, &method->dispatch): */ /*|1: */ dasm_put(Dst, 1861, define_jmptarget(jc, &method->dispatch)); -# 709 "upb/pb/compile_decoder_x64.dasc" +# 714 "upb/pb/compile_decoder_x64.dasc" /* Decode the field tag. */ /*| mov aword DECODER->checkpoint, PTR */ /*| chkeob 2, >6 */ @@ -1085,7 +1090,7 @@ static void jitdispatch(jitcompiler *jc, } else { dasm_put(Dst, 1873); } -# 712 "upb/pb/compile_decoder_x64.dasc" +# 717 "upb/pb/compile_decoder_x64.dasc" /*| movzx edx, byte [PTR] */ /*| test dl, dl */ /*| jns >7 // Jump if first byte has no continuation bit. */ @@ -1110,48 +1115,48 @@ static void jitdispatch(jitcompiler *jc, /*| shr edx, 3 */ /*| and cl, 7 */ dasm_put(Dst, 1889, 1); -# 735 "upb/pb/compile_decoder_x64.dasc" +# 740 "upb/pb/compile_decoder_x64.dasc" /* See comment attached to upb_pbdecodermethod.dispatch for layout of the * dispatch table. */ /*|2: */ /*| cmp edx, dispatch->array_size */ dasm_put(Dst, 1954, dispatch->array_size); -# 740 "upb/pb/compile_decoder_x64.dasc" +# 745 "upb/pb/compile_decoder_x64.dasc" if (has_hash_entries) { /*| jae >7 */ dasm_put(Dst, 1961); -# 742 "upb/pb/compile_decoder_x64.dasc" +# 747 "upb/pb/compile_decoder_x64.dasc" } else { /*| jae >5 */ dasm_put(Dst, 1966); -# 744 "upb/pb/compile_decoder_x64.dasc" +# 749 "upb/pb/compile_decoder_x64.dasc" } /*| // OPT: Compact the lookup arr into 32-bit entries. */ if ((uintptr_t)dispatch->array > 0x7fffffff) { /*| mov64 rax, (uintptr_t)dispatch->array */ /*| mov rax, qword [rax + rdx * 8] */ dasm_put(Dst, 1971, (unsigned int)((uintptr_t)dispatch->array), (unsigned int)(((uintptr_t)dispatch->array)>>32)); -# 749 "upb/pb/compile_decoder_x64.dasc" +# 754 "upb/pb/compile_decoder_x64.dasc" } else { /*| mov rax, qword [rdx * 8 + dispatch->array] */ dasm_put(Dst, 1980, dispatch->array); -# 751 "upb/pb/compile_decoder_x64.dasc" +# 756 "upb/pb/compile_decoder_x64.dasc" } /*|3: */ /*| // We take advantage of the fact that non-present entries are stored */ /*| // as -1, which will result in wire types that will never match. */ /*| cmp al, cl */ dasm_put(Dst, 1986); -# 756 "upb/pb/compile_decoder_x64.dasc" +# 761 "upb/pb/compile_decoder_x64.dasc" if (has_multi_wiretype) { /*| jne >6 */ dasm_put(Dst, 1991); -# 758 "upb/pb/compile_decoder_x64.dasc" +# 763 "upb/pb/compile_decoder_x64.dasc" } else { /*| jne >5 */ dasm_put(Dst, 1996); -# 760 "upb/pb/compile_decoder_x64.dasc" +# 765 "upb/pb/compile_decoder_x64.dasc" } /*| shr rax, 16 */ /*| */ @@ -1182,7 +1187,7 @@ static void jitdispatch(jitcompiler *jc, /*| lea rax, [>9] // ENDGROUP; Load address of OP_ENDMSG. */ /*| ret */ dasm_put(Dst, 2001, define_jmptarget(jc, dispatch->array), (unsigned int)((uintptr_t)method->dest_handlers_), (unsigned int)(((uintptr_t)method->dest_handlers_)>>32), Dt1(->sink.handlers)); -# 789 "upb/pb/compile_decoder_x64.dasc" +# 794 "upb/pb/compile_decoder_x64.dasc" if (has_multi_wiretype) { /*|6: */ @@ -1193,7 +1198,7 @@ static void jitdispatch(jitcompiler *jc, /*| add rdx, UPB_MAX_FIELDNUMBER */ /*| // This key will never be in the array part, so do a hash lookup. */ dasm_put(Dst, 2043, UPB_MAX_FIELDNUMBER); -# 798 "upb/pb/compile_decoder_x64.dasc" +# 803 "upb/pb/compile_decoder_x64.dasc" UPB_ASSERT(has_hash_entries); /*| ld64 dispatch */ { @@ -1206,10 +1211,10 @@ static void jitdispatch(jitcompiler *jc, dasm_put(Dst, 454); } } -# 800 "upb/pb/compile_decoder_x64.dasc" +# 805 "upb/pb/compile_decoder_x64.dasc" /*| jmp ->hashlookup // Tail call. */ dasm_put(Dst, 2056); -# 801 "upb/pb/compile_decoder_x64.dasc" +# 806 "upb/pb/compile_decoder_x64.dasc" } if (has_hash_entries) { @@ -1227,11 +1232,11 @@ static void jitdispatch(jitcompiler *jc, dasm_put(Dst, 454); } } -# 807 "upb/pb/compile_decoder_x64.dasc" +# 812 "upb/pb/compile_decoder_x64.dasc" /*| call ->hashlookup */ /*| jmp <3 */ dasm_put(Dst, 2064); -# 809 "upb/pb/compile_decoder_x64.dasc" +# 814 "upb/pb/compile_decoder_x64.dasc" } } @@ -1258,7 +1263,7 @@ static void jittag(jitcompiler *jc, uint64_t tag, int n, int ofs, } else { dasm_put(Dst, 2080, n); } -# 830 "upb/pb/compile_decoder_x64.dasc" +# 835 "upb/pb/compile_decoder_x64.dasc" /*| // OPT: this is way too much fallback code to put here. */ /*| // Reduce and/or move to a separate section to make better icache usage. */ @@ -1273,7 +1278,7 @@ static void jittag(jitcompiler *jc, uint64_t tag, int n, int ofs, dasm_put(Dst, 454); } } -# 834 "upb/pb/compile_decoder_x64.dasc" +# 839 "upb/pb/compile_decoder_x64.dasc" /*| call ->checktag_fallback */ /*| cmp eax, DECODE_MISMATCH */ /*| je >3 */ @@ -1281,21 +1286,21 @@ static void jittag(jitcompiler *jc, uint64_t tag, int n, int ofs, /*| je =>jmptarget(jc, delimend) */ /*| jmp >5 */ dasm_put(Dst, 2096, DECODE_MISMATCH, DECODE_EOF, jmptarget(jc, delimend)); -# 840 "upb/pb/compile_decoder_x64.dasc" +# 845 "upb/pb/compile_decoder_x64.dasc" /*|1: */ dasm_put(Dst, 112); -# 842 "upb/pb/compile_decoder_x64.dasc" +# 847 "upb/pb/compile_decoder_x64.dasc" switch (n) { case 1: /*| cmp byte [PTR], tag */ dasm_put(Dst, 2119, tag); -# 845 "upb/pb/compile_decoder_x64.dasc" +# 850 "upb/pb/compile_decoder_x64.dasc" break; case 2: /*| cmp word [PTR], tag */ dasm_put(Dst, 2123, tag); -# 848 "upb/pb/compile_decoder_x64.dasc" +# 853 "upb/pb/compile_decoder_x64.dasc" break; case 3: /*| // OPT: Slightly more efficient code, but depends on an extra byte. */ @@ -1307,41 +1312,41 @@ static void jittag(jitcompiler *jc, uint64_t tag, int n, int ofs, /*| cmp byte [PTR + 2], (tag >> 16) */ /*|2: */ dasm_put(Dst, 2128, (tag & 0xffff), 2, (tag >> 16)); -# 858 "upb/pb/compile_decoder_x64.dasc" +# 863 "upb/pb/compile_decoder_x64.dasc" break; case 4: /*| cmp dword [PTR], tag */ dasm_put(Dst, 2143, tag); -# 861 "upb/pb/compile_decoder_x64.dasc" +# 866 "upb/pb/compile_decoder_x64.dasc" break; case 5: /*| cmp dword [PTR], (tag & 0xffffffff) */ /*| jne >3 */ /*| cmp byte [PTR + 4], (tag >> 32) */ dasm_put(Dst, 2147, (tag & 0xffffffff), 4, (tag >> 32)); -# 866 "upb/pb/compile_decoder_x64.dasc" +# 871 "upb/pb/compile_decoder_x64.dasc" } /*| je >4 */ /*|3: */ dasm_put(Dst, 2159); -# 869 "upb/pb/compile_decoder_x64.dasc" +# 874 "upb/pb/compile_decoder_x64.dasc" if (ofs == 0) { /*| call =>jmptarget(jc, &method->dispatch) */ /*| test rax, rax */ /*| jz =>jmptarget(jc, delimend) */ /*| jmp rax */ dasm_put(Dst, 2166, jmptarget(jc, &method->dispatch), jmptarget(jc, delimend)); -# 874 "upb/pb/compile_decoder_x64.dasc" +# 879 "upb/pb/compile_decoder_x64.dasc" } else { /*| jmp =>jmptarget(jc, jc->pc + ofs) */ dasm_put(Dst, 2178, jmptarget(jc, jc->pc + ofs)); -# 876 "upb/pb/compile_decoder_x64.dasc" +# 881 "upb/pb/compile_decoder_x64.dasc" } /*|4: */ /*| add PTR, n */ /*|5: */ dasm_put(Dst, 2182, n); -# 880 "upb/pb/compile_decoder_x64.dasc" +# 885 "upb/pb/compile_decoder_x64.dasc" } /* Compile the bytecode to x64. */ @@ -1364,7 +1369,7 @@ static void jitbytecode(jitcompiler *jc) { * TODO: optimize this to only define pclabels that are actually used. */ /*|=>define_jmptarget(jc, jc->pc): */ dasm_put(Dst, 0, define_jmptarget(jc, jc->pc)); -# 901 "upb/pb/compile_decoder_x64.dasc" +# 906 "upb/pb/compile_decoder_x64.dasc" } jc->pc++; @@ -1379,7 +1384,7 @@ static void jitbytecode(jitcompiler *jc) { /*| load_handler_data h, UPB_STARTMSG_SELECTOR */ dasm_put(Dst, 2191); { - uintptr_t v = (uintptr_t)upb_handlers_gethandlerdata(h, UPB_STARTMSG_SELECTOR); + uintptr_t v = (uintptr_t)gethandlerdata(h, UPB_STARTMSG_SELECTOR); if (v > 0xffffffff) { dasm_put(Dst, 446, (unsigned int)(v), (unsigned int)((v)>>32)); } else if (v) { @@ -1388,10 +1393,10 @@ static void jitbytecode(jitcompiler *jc) { dasm_put(Dst, 454); } } -# 913 "upb/pb/compile_decoder_x64.dasc" +# 918 "upb/pb/compile_decoder_x64.dasc" /*| callp startmsg */ dasm_put(Dst, 1793, (unsigned int)((uintptr_t)startmsg), (unsigned int)(((uintptr_t)startmsg)>>32), 0xfffffffffffffff0UL); -# 914 "upb/pb/compile_decoder_x64.dasc" +# 919 "upb/pb/compile_decoder_x64.dasc" if (!alwaysok(h, UPB_STARTMSG_SELECTOR)) { /*| test al, al */ /*| jnz >2 */ @@ -1399,12 +1404,12 @@ static void jitbytecode(jitcompiler *jc) { /*| jmp <1 */ /*|2: */ dasm_put(Dst, 2198); -# 920 "upb/pb/compile_decoder_x64.dasc" +# 925 "upb/pb/compile_decoder_x64.dasc" } } else { /*| nop */ dasm_put(Dst, 2214); -# 923 "upb/pb/compile_decoder_x64.dasc" +# 928 "upb/pb/compile_decoder_x64.dasc" } break; } @@ -1412,14 +1417,14 @@ static void jitbytecode(jitcompiler *jc) { upb_func *endmsg = gethandler(h, UPB_ENDMSG_SELECTOR); /*|9: */ dasm_put(Dst, 2216); -# 929 "upb/pb/compile_decoder_x64.dasc" +# 934 "upb/pb/compile_decoder_x64.dasc" if (endmsg) { /* bool endmsg(void *closure, const void *hd, upb_status *status) */ /*| mov ARG1_64, CLOSURE */ /*| load_handler_data h, UPB_ENDMSG_SELECTOR */ dasm_put(Dst, 1788); { - uintptr_t v = (uintptr_t)upb_handlers_gethandlerdata(h, UPB_ENDMSG_SELECTOR); + uintptr_t v = (uintptr_t)gethandlerdata(h, UPB_ENDMSG_SELECTOR); if (v > 0xffffffff) { dasm_put(Dst, 446, (unsigned int)(v), (unsigned int)((v)>>32)); } else if (v) { @@ -1428,11 +1433,11 @@ static void jitbytecode(jitcompiler *jc) { dasm_put(Dst, 454); } } -# 933 "upb/pb/compile_decoder_x64.dasc" +# 938 "upb/pb/compile_decoder_x64.dasc" /*| mov ARG3_64, DECODER->status */ /*| callp endmsg */ dasm_put(Dst, 2219, Dt2(->status), (unsigned int)((uintptr_t)endmsg), (unsigned int)(((uintptr_t)endmsg)>>32), 0xfffffffffffffff0UL); -# 935 "upb/pb/compile_decoder_x64.dasc" +# 940 "upb/pb/compile_decoder_x64.dasc" } break; } @@ -1465,7 +1470,7 @@ static void jitbytecode(jitcompiler *jc) { /*|=>define_jmptarget(jc, method): */ /*| sub rsp, 8 */ dasm_put(Dst, 2245, define_jmptarget(jc, op_pc), define_jmptarget(jc, method)); -# 966 "upb/pb/compile_decoder_x64.dasc" +# 971 "upb/pb/compile_decoder_x64.dasc" break; } @@ -1497,7 +1502,7 @@ static void jitbytecode(jitcompiler *jc) { /*| load_handler_data h, arg */ dasm_put(Dst, 2191); { - uintptr_t v = (uintptr_t)upb_handlers_gethandlerdata(h, arg); + uintptr_t v = (uintptr_t)gethandlerdata(h, arg); if (v > 0xffffffff) { dasm_put(Dst, 446, (unsigned int)(v), (unsigned int)((v)>>32)); } else if (v) { @@ -1506,16 +1511,16 @@ static void jitbytecode(jitcompiler *jc) { dasm_put(Dst, 454); } } -# 995 "upb/pb/compile_decoder_x64.dasc" +# 1000 "upb/pb/compile_decoder_x64.dasc" if (op == OP_STARTSTR) { /*| mov ARG3_64, DELIMEND */ /*| sub ARG3_64, PTR */ dasm_put(Dst, 2253); -# 998 "upb/pb/compile_decoder_x64.dasc" +# 1003 "upb/pb/compile_decoder_x64.dasc" } /*| callp start */ dasm_put(Dst, 1793, (unsigned int)((uintptr_t)start), (unsigned int)(((uintptr_t)start)>>32), 0xfffffffffffffff0UL); -# 1000 "upb/pb/compile_decoder_x64.dasc" +# 1005 "upb/pb/compile_decoder_x64.dasc" if (!alwaysok(h, arg)) { /*| test rax, rax */ /*| jnz >2 */ @@ -1523,16 +1528,16 @@ static void jitbytecode(jitcompiler *jc) { /*| jmp <1 */ /*|2: */ dasm_put(Dst, 2261); -# 1006 "upb/pb/compile_decoder_x64.dasc" +# 1011 "upb/pb/compile_decoder_x64.dasc" } /*| mov CLOSURE, rax */ dasm_put(Dst, 2278); -# 1008 "upb/pb/compile_decoder_x64.dasc" +# 1013 "upb/pb/compile_decoder_x64.dasc" } else { /* TODO: nop is only required because of asmlabel(). */ /*| nop */ dasm_put(Dst, 2214); -# 1011 "upb/pb/compile_decoder_x64.dasc" +# 1016 "upb/pb/compile_decoder_x64.dasc" } break; } @@ -1549,7 +1554,7 @@ static void jitbytecode(jitcompiler *jc) { /*| load_handler_data h, arg */ dasm_put(Dst, 2191); { - uintptr_t v = (uintptr_t)upb_handlers_gethandlerdata(h, arg); + uintptr_t v = (uintptr_t)gethandlerdata(h, arg); if (v > 0xffffffff) { dasm_put(Dst, 446, (unsigned int)(v), (unsigned int)((v)>>32)); } else if (v) { @@ -1558,10 +1563,10 @@ static void jitbytecode(jitcompiler *jc) { dasm_put(Dst, 454); } } -# 1025 "upb/pb/compile_decoder_x64.dasc" +# 1030 "upb/pb/compile_decoder_x64.dasc" /*| callp end */ dasm_put(Dst, 1793, (unsigned int)((uintptr_t)end), (unsigned int)(((uintptr_t)end)>>32), 0xfffffffffffffff0UL); -# 1026 "upb/pb/compile_decoder_x64.dasc" +# 1031 "upb/pb/compile_decoder_x64.dasc" if (!alwaysok(h, arg)) { /*| test al, al */ /*| jnz >2 */ @@ -1569,13 +1574,13 @@ static void jitbytecode(jitcompiler *jc) { /*| jmp <1 */ /*|2: */ dasm_put(Dst, 2198); -# 1032 "upb/pb/compile_decoder_x64.dasc" +# 1037 "upb/pb/compile_decoder_x64.dasc" } } else { /* TODO: nop is only required because of asmlabel(). */ /*| nop */ dasm_put(Dst, 2214); -# 1036 "upb/pb/compile_decoder_x64.dasc" +# 1041 "upb/pb/compile_decoder_x64.dasc" } break; } @@ -1590,7 +1595,7 @@ static void jitbytecode(jitcompiler *jc) { /*| jmp <1 */ /*|2: */ dasm_put(Dst, 2282); -# 1049 "upb/pb/compile_decoder_x64.dasc" +# 1054 "upb/pb/compile_decoder_x64.dasc" if (str) { /* size_t str(void *closure, const void *hd, const char *str, * size_t n) */ @@ -1598,7 +1603,7 @@ static void jitbytecode(jitcompiler *jc) { /*| load_handler_data h, arg */ dasm_put(Dst, 1788); { - uintptr_t v = (uintptr_t)upb_handlers_gethandlerdata(h, arg); + uintptr_t v = (uintptr_t)gethandlerdata(h, arg); if (v > 0xffffffff) { dasm_put(Dst, 446, (unsigned int)(v), (unsigned int)((v)>>32)); } else if (v) { @@ -1607,7 +1612,7 @@ static void jitbytecode(jitcompiler *jc) { dasm_put(Dst, 454); } } -# 1054 "upb/pb/compile_decoder_x64.dasc" +# 1059 "upb/pb/compile_decoder_x64.dasc" /*| mov ARG3_64, PTR */ /*| mov ARG4_64, DATAEND */ /*| sub ARG4_64, PTR */ @@ -1615,25 +1620,25 @@ static void jitbytecode(jitcompiler *jc) { /*| callp str */ /*| add PTR, rax */ dasm_put(Dst, 2309, Dt2(->handle), (unsigned int)((uintptr_t)str), (unsigned int)(((uintptr_t)str)>>32), 0xfffffffffffffff0UL); -# 1060 "upb/pb/compile_decoder_x64.dasc" +# 1065 "upb/pb/compile_decoder_x64.dasc" if (!alwaysok(h, arg)) { /*| cmp PTR, DATAEND */ /*| je >3 */ /*| call ->strret_fallback */ /*|3: */ dasm_put(Dst, 2347); -# 1065 "upb/pb/compile_decoder_x64.dasc" +# 1070 "upb/pb/compile_decoder_x64.dasc" } } else { /*| mov PTR, DATAEND */ dasm_put(Dst, 2360); -# 1068 "upb/pb/compile_decoder_x64.dasc" +# 1073 "upb/pb/compile_decoder_x64.dasc" } /*| cmp PTR, DELIMEND */ /*| jne <1 */ /*|4: */ dasm_put(Dst, 2364); -# 1072 "upb/pb/compile_decoder_x64.dasc" +# 1077 "upb/pb/compile_decoder_x64.dasc" break; } case OP_PUSHTAGDELIM: @@ -1649,18 +1654,18 @@ static void jitbytecode(jitcompiler *jc) { /*| add FRAME, sizeof(upb_pbdecoder_frame) */ /*| mov dword FRAME->groupnum, arg */ dasm_put(Dst, 2375, Dt1(->sink.closure), Dt1(->end_ofs), Dt2(->limit), sizeof(upb_pbdecoder_frame), Dt1(->groupnum), arg); -# 1086 "upb/pb/compile_decoder_x64.dasc" +# 1091 "upb/pb/compile_decoder_x64.dasc" break; case OP_PUSHLENDELIM: /*| call ->pushlendelim */ dasm_put(Dst, 2405); -# 1089 "upb/pb/compile_decoder_x64.dasc" +# 1094 "upb/pb/compile_decoder_x64.dasc" break; case OP_POP: /*| sub FRAME, sizeof(upb_pbdecoder_frame) */ /*| mov CLOSURE, FRAME->sink.closure */ dasm_put(Dst, 2409, sizeof(upb_pbdecoder_frame), Dt1(->sink.closure)); -# 1093 "upb/pb/compile_decoder_x64.dasc" +# 1098 "upb/pb/compile_decoder_x64.dasc" break; case OP_SETDELIM: /* OPT: experiment with testing vs old offset to optimize away. */ @@ -1673,35 +1678,35 @@ static void jitbytecode(jitcompiler *jc) { /*| mov DATAEND, DELIMEND */ /*|1: */ dasm_put(Dst, 2419, Dt2(->end), Dt1(->end_ofs), Dt2(->buf)); -# 1104 "upb/pb/compile_decoder_x64.dasc" +# 1109 "upb/pb/compile_decoder_x64.dasc" break; case OP_SETBIGGROUPNUM: /*| mov dword FRAME->groupnum, *jc->pc++ */ dasm_put(Dst, 2399, Dt1(->groupnum), *jc->pc++); -# 1107 "upb/pb/compile_decoder_x64.dasc" +# 1112 "upb/pb/compile_decoder_x64.dasc" break; case OP_CHECKDELIM: /*| cmp DELIMEND, PTR */ /*| je =>jmptarget(jc, jc->pc + longofs) */ dasm_put(Dst, 2449, jmptarget(jc, jc->pc + longofs)); -# 1111 "upb/pb/compile_decoder_x64.dasc" +# 1116 "upb/pb/compile_decoder_x64.dasc" break; case OP_CALL: /*| call =>jmptarget(jc, jc->pc + longofs) */ dasm_put(Dst, 2456, jmptarget(jc, jc->pc + longofs)); -# 1114 "upb/pb/compile_decoder_x64.dasc" +# 1119 "upb/pb/compile_decoder_x64.dasc" break; case OP_BRANCH: /*| jmp =>jmptarget(jc, jc->pc + longofs); */ dasm_put(Dst, 2178, jmptarget(jc, jc->pc + longofs)); -# 1117 "upb/pb/compile_decoder_x64.dasc" +# 1122 "upb/pb/compile_decoder_x64.dasc" break; case OP_RET: /*|9: */ /*| add rsp, 8 */ /*| ret */ dasm_put(Dst, 2459); -# 1122 "upb/pb/compile_decoder_x64.dasc" +# 1127 "upb/pb/compile_decoder_x64.dasc" break; case OP_TAG1: jittag(jc, (arg >> 8) & 0xff, 1, (int8_t)arg, method); @@ -1718,7 +1723,7 @@ static void jitbytecode(jitcompiler *jc) { case OP_DISPATCH: /*| call =>jmptarget(jc, &method->dispatch) */ dasm_put(Dst, 2456, jmptarget(jc, &method->dispatch)); -# 1137 "upb/pb/compile_decoder_x64.dasc" +# 1142 "upb/pb/compile_decoder_x64.dasc" break; case OP_HALT: UPB_ASSERT(false); @@ -1728,5 +1733,5 @@ static void jitbytecode(jitcompiler *jc) { asmlabel(jc, "eof"); /*| nop */ dasm_put(Dst, 2214); -# 1145 "upb/pb/compile_decoder_x64.dasc" +# 1150 "upb/pb/compile_decoder_x64.dasc" } diff --git a/upb/upb.h b/upb/upb.h index 07b0455..1c13dd9 100644 --- a/upb/upb.h +++ b/upb/upb.h @@ -262,6 +262,7 @@ size_t upb_arena_bytesallocated(const upb_arena *a); UPB_INLINE upb_alloc *upb_arena_alloc(upb_arena *a) { return (upb_alloc*)a; } /* Convenience wrappers around upb_alloc functions. */ + UPB_INLINE void *upb_arena_malloc(upb_arena *a, size_t size) { return upb_malloc(upb_arena_alloc(a), size); } -- cgit v1.2.3 From 0517c462e687b721e53a4b3071fc961de4839ea4 Mon Sep 17 00:00:00 2001 From: Joshua Haberman Date: Wed, 23 Jan 2019 16:10:17 -0800 Subject: Delete obsolete dump_cinit.lua. --- tools/dump_cinit.lua | 751 --------------------------------------------------- 1 file changed, 751 deletions(-) delete mode 100644 tools/dump_cinit.lua (limited to 'tools') diff --git a/tools/dump_cinit.lua b/tools/dump_cinit.lua deleted file mode 100644 index 34d6ac6..0000000 --- a/tools/dump_cinit.lua +++ /dev/null @@ -1,751 +0,0 @@ ---[[ - - Routines for dumping internal data structures into C initializers - that can be compiled into a .o file. - ---]] - -local upbtable = require "upb.table" -local upb = require "upb" -local export = {} - --- A tiny little abstraction that decouples the dump_* functions from --- what they're writing to (appending to a string, writing to file I/O, etc). --- This could possibly matter since naive string building is O(n^2) in the --- number of appends. -function export.str_appender() - local str = "" - local function append(fmt, ...) - str = str .. string.format(fmt, ...) - end - local function get() - return str - end - return append, get -end - -function export.file_appender(file) - local f = file - local function append(fmt, ...) - f:write(string.format(fmt, ...)) - end - return append -end - -function handler_types(base) - local ret = {} - for k, _ in pairs(base) do - if string.find(k, "^" .. "HANDLER_") then - ret[#ret + 1] = k - end - end - return ret -end - -function octchar(num) - assert(num < 8) - local idx = num + 1 -- 1-based index - return string.sub("01234567", idx, idx) -end - -function c_escape(num) - assert(num < 256) - return string.format("\\%s%s%s", - octchar(math.floor(num / 64)), - octchar(math.floor(num / 8) % 8), - octchar(num % 8)); -end - --- const(f, label) -> UPB_LABEL_REPEATED, where f:label() == upb.LABEL_REPEATED -function const(obj, name, base) - local val = obj[name] - base = base or upb - - -- Support both f:label() and f.label. - if type(val) == "function" then - val = val(obj) - end - - for k, v in pairs(base) do - if v == val and string.find(k, "^" .. string.upper(name)) then - return "UPB_" .. k - end - end - assert(false, "Couldn't find UPB_" .. string.upper(name) .. - " constant for value: " .. val) -end - -function sortedkeys(tab) - arr = {} - for key in pairs(tab) do - arr[#arr + 1] = key - end - table.sort(arr) - return arr -end - -function sorted_defs(defs) - local sorted = {} - - for def in defs do - if def.type == deftype then - sorted[#sorted + 1] = def - end - end - - table.sort(sorted, - function(a, b) return a:full_name() < b:full_name() end) - - return sorted -end - -function constlist(pattern) - local ret = {} - for k, v in pairs(upb) do - if string.find(k, "^" .. pattern) then - ret[k] = v - end - end - return ret -end - -function boolstr(val) - if val == true then - return "true" - elseif val == false then - return "false" - else - assert(false, "Bad bool value: " .. tostring(val)) - end -end - ---[[ - - LinkTable: an object that tracks all linkable objects and their offsets to - facilitate linking. - ---]] - -local LinkTable = {} -function LinkTable:new(types) - local linktab = { - types = types, - table = {}, -- ptr -> {type, 0-based offset} - obj_arrays = {} -- Establishes the ordering for each object type - } - for type, _ in pairs(types) do - linktab.obj_arrays[type] = {} - end - setmetatable(linktab, {__index = LinkTable}) -- Inheritance - return linktab -end - --- Adds a new object to the sequence of objects of this type. -function LinkTable:add(objtype, ptr, obj) - obj = obj or ptr - assert(self.table[obj] == nil) - assert(self.types[objtype]) - local arr = self.obj_arrays[objtype] - self.table[ptr] = {objtype, #arr} - arr[#arr + 1] = obj -end - --- Returns a C symbol name for the given objtype and offset. -function LinkTable:csym(objtype, offset) - local typestr = assert(self.types[objtype]) - return string.format("%s[%d]", typestr, offset) -end - --- Returns the address of the given C object. -function LinkTable:addr(obj) - if obj == upbtable.NULL then - return "NULL" - else - local tabent = assert(self.table[obj], "unknown object: " .. tostring(obj)) - return "&" .. self:csym(tabent[1], tabent[2]) - end -end - --- Returns an array declarator indicating how many objects have been added. -function LinkTable:cdecl(objtype) - return self:csym(objtype, #self.obj_arrays[objtype]) -end - -function LinkTable:objs(objtype) - -- Return iterator function, allowing use as: - -- for obj in linktable:objs(type) do - -- -- ... - -- done - local array = self.obj_arrays[objtype] - local i = 0 - return function() - i = i + 1 - if array[i] then return array[i] end - end -end - -function LinkTable:empty(objtype) - return #self.obj_arrays[objtype] == 0 -end - ---[[ - - Dumper: an object that can dump C initializers for several constructs. - Uses a LinkTable to resolve references when necessary. - ---]] - -local Dumper = {} -function Dumper:new(linktab) - local obj = {linktab = linktab} - setmetatable(obj, {__index = Dumper}) -- Inheritance - return obj -end - --- Dumps a upb_tabval, eg: --- UPB_TABVALUE_INIT(5) -function Dumper:_value(val, upbtype) - if type(val) == "nil" then - return "UPB_TABVALUE_EMPTY_INIT" - elseif type(val) == "number" then - -- Use upbtype to disambiguate what kind of number it is. - if upbtype == upbtable.CTYPE_INT32 then - return string.format("UPB_TABVALUE_INT_INIT(%d)", val) - else - -- TODO(haberman): add support for these so we can properly support - -- default values. - error("Unsupported number type " .. upbtype) - end - elseif type(val) == "string" then - return string.format('UPB_TABVALUE_PTR_INIT("%s")', val) - else - -- We take this as an object reference that has an entry in the link table. - return string.format("UPB_TABVALUE_PTR_INIT(%s)", self.linktab:addr(val)) - end -end - --- Dumps a table key. -function Dumper:tabkey(key) - if type(key) == "nil" then - return "UPB_TABKEY_NONE" - elseif type(key) == "string" then - local len = #key - local len1 = c_escape(len % 256) - local len2 = c_escape(math.floor(len / 256) % 256) - local len3 = c_escape(math.floor(len / (256 * 256)) % 256) - local len4 = c_escape(math.floor(len / (256 * 256 * 256)) % 256) - return string.format('UPB_TABKEY_STR("%s", "%s", "%s", "%s", "%s")', - len1, len2, len3, len4, key) - else - return string.format("UPB_TABKEY_NUM(%d)", key) - end -end - --- Dumps a table entry. -function Dumper:tabent(ent) - local key = self:tabkey(ent.key) - local val = self:_value(ent.value, ent.valtype) - local next = self.linktab:addr(ent.next) - return string.format(' {%s, %s, %s},\n', key, val, next) -end - --- Dumps an inttable array entry. This is almost the same as value() above, --- except that nil values have a special value to indicate "empty". -function Dumper:arrayval(val) - if val.val then - return string.format(" %s,\n", self:_value(val.val, val.valtype)) - else - return " UPB_TABVALUE_EMPTY_INIT,\n" - end -end - --- Dumps an initializer for the given strtable/inttable (respectively). Its --- entries must have previously been added to the linktable. -function Dumper:strtable(t) - -- UPB_STRTABLE_INIT(count, mask, type, size_lg2, entries) - return string.format( - "UPB_STRTABLE_INIT(%d, %d, %s, %d, %s)", - t.count, t.mask, const(t, "ctype", upbtable) , t.size_lg2, - self.linktab:addr(t.entries[1].ptr)) -end - -function Dumper:inttable(t) - local lt = assert(self.linktab) - -- UPB_INTTABLE_INIT(count, mask, type, size_lg2, ent, a, asize, acount) - local entries = "NULL" - if #t.entries > 0 then - entries = lt:addr(t.entries[1].ptr) - end - return string.format( - "UPB_INTTABLE_INIT(%d, %d, %s, %d, %s, %s, %d, %d)", - t.count, t.mask, const(t, "ctype", upbtable), t.size_lg2, entries, - lt:addr(t.array[1].ptr), t.array_size, t.array_count) -end - --- A visitor for visiting all tables of a def. Used first to count entries --- and later to dump them. -local function gettables(def) - if def:def_type() == upb.DEF_MSG then - return {int = upbtable.msgdef_itof(def), str = upbtable.msgdef_ntof(def)} - elseif def:def_type() == upb.DEF_ENUM then - return {int = upbtable.enumdef_iton(def), str = upbtable.enumdef_ntoi(def)} - end -end - -local function emit_file_warning(filedef, append) - append('/* This file was generated by upbc (the upb compiler) from the input\n') - append(' * file:\n') - append(' *\n') - append(' * %s\n', filedef:name()) - append(' *\n') - append(' * Do not edit -- your changes will be discarded when the file is\n') - append(' * regenerated. */\n\n') -end - -local function join(...) - return table.concat({...}, ".") -end - -local function split(str) - local ret = {} - for word in string.gmatch(str, "%w+") do - table.insert(ret, word) - end - return ret -end - -local function to_cident(...) - return string.gsub(join(...), "[%./]", "_") -end - -local function to_preproc(...) - return string.upper(to_cident(...)) -end - --- Strips away last path element, ie: --- foo.Bar.Baz -> foo.Bar -local function remove_name(name) - local package_end = 0 - for i=1,string.len(name) do - if string.byte(name, i) == string.byte(".", 1) then - package_end = i - 1 - end - end - return string.sub(name, 1, package_end) -end - -local function start_namespace(package, append) - local package_components = split(package) - for _, component in ipairs(package_components) do - append("namespace %s {\n", component) - end -end - -local function end_namespace(package, append) - local package_components = split(package) - for i=#package_components,1,-1 do - append("} /* namespace %s */\n", package_components[i]) - end -end - -local function well_known_type(m) - local type_map = {} - type_map["google.protobuf.Any"] = "UPB_WELLKNOWN_ANY" - type_map["google.protobuf.FieldMask"] = "UPB_WELLKNOWN_FIELDMASK" - type_map["google.protobuf.Duration"] = "UPB_WELLKNOWN_DURATION" - type_map["google.protobuf.Timestamp"] = "UPB_WELLKNOWN_TIMESTAMP" - type_map["google.protobuf.Value"] = "UPB_WELLKNOWN_VALUE" - type_map["google.protobuf.ListValue"] = "UPB_WELLKNOWN_LISTVALUE" - type_map["google.protobuf.Struct"] = "UPB_WELLKNOWN_STRUCT" - type_map["google.protobuf.DoubleValue"] = "UPB_WELLKNOWN_DOUBLEVALUE" - type_map["google.protobuf.FloatValue"] = "UPB_WELLKNOWN_FLOATVALUE" - type_map["google.protobuf.Int64Value"] = "UPB_WELLKNOWN_INT64VALUE" - type_map["google.protobuf.UInt64Value"] = "UPB_WELLKNOWN_UINT64VALUE" - type_map["google.protobuf.Int32Value"] = "UPB_WELLKNOWN_INT32VALUE" - type_map["google.protobuf.UInt32Value"] = "UPB_WELLKNOWN_UINT32VALUE" - type_map["google.protobuf.BoolValue"] = "UPB_WELLKNOWN_BOOLVALUE" - type_map["google.protobuf.StringValue"] = "UPB_WELLKNOWN_STRINGVALUE" - type_map["google.protobuf.BytesValue"] = "UPB_WELLKNOWN_BYTESVALUE" - local t = type_map[m:full_name()] - if (t == nil) then - t = "UPB_WELLKNOWN_UNSPECIFIED" - end - return t -end - ---[[ - - Top-level, exported dumper functions - ---]] - -local function dump_defs_c(filedef, append) - local defs = {} - for def in filedef:defs(upb.DEF_ANY) do - defs[#defs + 1] = def - if (def:def_type() == upb.DEF_MSG) then - for field in def:fields() do - defs[#defs + 1] = field - end - end - end - - -- Sort all defs by (type, name). - -- This gives us a linear ordering that we can use to create offsets into - -- shared arrays like REFTABLES, hash table entries, and arrays. - table.sort(defs, function(a, b) - if a:def_type() ~= b:def_type() then - return a:def_type() < b:def_type() - else - return a:full_name() < b:full_name() end - end - ) - - -- Perform pre-pass to build the link table. - local linktab = LinkTable:new{ - [upb.DEF_MSG] = "msgs", - [upb.DEF_FIELD] = "fields", - [upb.DEF_ENUM] = "enums", - intentries = "intentries", - strentries = "strentries", - arrays = "arrays", - } - local reftable_count = 0 - - for _, def in ipairs(defs) do - assert(def:is_frozen(), "can only dump frozen defs.") - linktab:add(def:def_type(), def) - reftable_count = reftable_count + 2 - local tables = gettables(def) - if tables then - for _, e in ipairs(tables.str.entries) do - linktab:add("strentries", e.ptr, e) - end - for _, e in ipairs(tables.int.entries) do - linktab:add("intentries", e.ptr, e) - end - for _, e in ipairs(tables.int.array) do - linktab:add("arrays", e.ptr, e) - end - end - end - - -- Emit forward declarations. - emit_file_warning(filedef, append) - append('#include "upb/def.h"\n') - append('#include "upb/structdefs.int.h"\n\n') - append("static const upb_msgdef %s;\n", linktab:cdecl(upb.DEF_MSG)) - append("static const upb_fielddef %s;\n", linktab:cdecl(upb.DEF_FIELD)) - if not linktab:empty(upb.DEF_ENUM) then - append("static const upb_enumdef %s;\n", linktab:cdecl(upb.DEF_ENUM)) - end - append("static const upb_tabent %s;\n", linktab:cdecl("strentries")) - if not linktab:empty("intentries") then - append("static const upb_tabent %s;\n", linktab:cdecl("intentries")) - end - append("static const upb_tabval %s;\n", linktab:cdecl("arrays")) - append("\n") - append("#ifdef UPB_DEBUG_REFS\n") - append("static upb_inttable reftables[%d];\n", reftable_count) - append("#endif\n") - append("\n") - - -- Emit defs. - local dumper = Dumper:new(linktab) - - local reftable = 0 - - append("static const upb_msgdef %s = {\n", linktab:cdecl(upb.DEF_MSG)) - for m in linktab:objs(upb.DEF_MSG) do - local tables = gettables(m) - -- UPB_MSGDEF_INIT(name, selector_count, submsg_field_count, itof, ntof, - -- refs, ref2s) - append(' UPB_MSGDEF_INIT("%s", %d, %d, %s, %s, %s, %s, %s,' .. - ' &reftables[%d], &reftables[%d]),\n', - m:full_name(), - upbtable.msgdef_selector_count(m), - upbtable.msgdef_submsg_field_count(m), - dumper:inttable(tables.int), - dumper:strtable(tables.str), - boolstr(m:_map_entry()), - const(m, "syntax"), - well_known_type(m), - reftable, reftable + 1) - reftable = reftable + 2 - end - append("};\n\n") - - append("static const upb_fielddef %s = {\n", linktab:cdecl(upb.DEF_FIELD)) - for f in linktab:objs(upb.DEF_FIELD) do - local subdef = "NULL" - if f:has_subdef() then - subdef = string.format("(const upb_def*)(%s)", linktab:addr(f:subdef())) - end - local intfmt - if f:type() == upb.TYPE_UINT32 or - f:type() == upb.TYPE_INT32 or - f:type() == upb.TYPE_UINT64 or - f:type() == upb.TYPE_INT64 then - intfmt = const(f, "intfmt") - else - intfmt = "0" - end - -- UPB_FIELDDEF_INIT(label, type, intfmt, tagdelim, is_extension, lazy, - -- packed, name, num, msgdef, subdef, selector_base, - -- index, -- default_value) - append(' UPB_FIELDDEF_INIT(%s, %s, %s, %s, %s, %s, %s, "%s", %d, %s, ' .. - '%s, %d, %d, {0},' .. -- TODO: support default value - '&reftables[%d], &reftables[%d]),\n', - const(f, "label"), const(f, "type"), intfmt, - boolstr(f:istagdelim()), boolstr(f:is_extension()), - boolstr(f:lazy()), boolstr(f:packed()), f:name(), f:number(), - linktab:addr(f:containing_type()), subdef, - upbtable.fielddef_selector_base(f), f:index(), - reftable, reftable + 1 - ) - reftable = reftable + 2 - end - append("};\n\n") - - if not linktab:empty(upb.DEF_ENUM) then - append("static const upb_enumdef %s = {\n", linktab:cdecl(upb.DEF_ENUM)) - for e in linktab:objs(upb.DEF_ENUM) do - local tables = gettables(e) - -- UPB_ENUMDEF_INIT(name, ntoi, iton, defaultval) - append(' UPB_ENUMDEF_INIT("%s", %s, %s, %d, ' .. - '&reftables[%d], &reftables[%d]),\n', - e:full_name(), - dumper:strtable(tables.str), - dumper:inttable(tables.int), - --e:default()) - 0, - reftable, reftable + 1) - reftable = reftable + 2 - end - append("};\n\n") - end - - append("static const upb_tabent %s = {\n", linktab:cdecl("strentries")) - for ent in linktab:objs("strentries") do - append(dumper:tabent(ent)) - end - append("};\n\n"); - - if not linktab:empty("intentries") then - append("static const upb_tabent %s = {\n", linktab:cdecl("intentries")) - for ent in linktab:objs("intentries") do - append(dumper:tabent(ent)) - end - append("};\n\n"); - end - - append("static const upb_tabval %s = {\n", linktab:cdecl("arrays")) - for ent in linktab:objs("arrays") do - append(dumper:arrayval(ent)) - end - append("};\n\n"); - - append("#ifdef UPB_DEBUG_REFS\n") - append("static upb_inttable reftables[%d] = {\n", reftable_count) - for i = 1,reftable_count do - append(" UPB_EMPTY_INTTABLE_INIT(UPB_CTYPE_PTR),\n") - end - append("};\n") - append("#endif\n\n") - - append("static const upb_msgdef *refm(const upb_msgdef *m, const void *owner) {\n") - append(" upb_msgdef_ref(m, owner);\n") - append(" return m;\n") - append("}\n\n") - append("static const upb_enumdef *refe(const upb_enumdef *e, const void *owner) {\n") - append(" upb_enumdef_ref(e, owner);\n") - append(" return e;\n") - append("}\n\n") - - append("/* Public API. */\n") - - for m in linktab:objs(upb.DEF_MSG) do - append("const upb_msgdef *upbdefs_%s_get(const void *owner)" .. - " { return refm(%s, owner); }\n", - to_cident(m:full_name()), linktab:addr(m)) - end - - append("\n") - - for e in linktab:objs(upb.DEF_ENUM) do - append("const upb_enumdef *upbdefs_%s_get(const void *owner)" .. - " { return refe(%s, owner); }\n", - to_cident(e:full_name()), linktab:addr(e)) - end - - return linktab -end - -local function dump_defs_for_type(format, defs, append) - local sorted = sorted_defs(defs) - for _, def in ipairs(sorted) do - append(format, to_cident(def:full_name()), def:full_name()) - end - - append("\n") -end - -local function make_children_map(file) - -- Maps file:package() or msg:full_name() -> children. - local map = {} - for def in file:defs(upb.DEF_ANY) do - local container = remove_name(def:full_name()) - if not map[container] then - map[container] = {} - end - table.insert(map[container], def) - end - - -- Sort all the lists for a consistent ordering. - for name, children in pairs(map) do - table.sort(children, function(a, b) return a:name() < b:name() end) - end - - return map -end - -local print_classes - -local function print_message(def, map, indent, append) - append("\n") - append("%sclass %s : public ::upb::reffed_ptr {\n", - indent, def:name()) - append("%s public:\n", indent) - append("%s %s(const ::upb::MessageDef* m, const void *ref_donor = NULL)\n", - indent, def:name()) - append("%s : reffed_ptr(m, ref_donor) {\n", indent) - append("%s UPB_ASSERT(upbdefs_%s_is(m));\n", indent, to_cident(def:full_name())) - append("%s }\n", indent) - append("\n") - append("%s static %s get() {\n", indent, def:name()) - append("%s const ::upb::MessageDef* m = upbdefs_%s_get(&m);\n", indent, to_cident(def:full_name())) - append("%s return %s(m, &m);\n", indent, def:name()) - append("%s }\n", indent) - -- TODO(haberman): add fields - print_classes(def:full_name(), map, indent .. " ", append) - append("%s};\n", indent) -end - -local function print_enum(def, indent, append) - append("\n") - append("%sclass %s : public ::upb::reffed_ptr {\n", - indent, def:name()) - append("%s public:\n", indent) - append("%s %s(const ::upb::EnumDef* e, const void *ref_donor = NULL)\n", - indent, def:name()) - append("%s : reffed_ptr(e, ref_donor) {\n", indent) - append("%s UPB_ASSERT(upbdefs_%s_is(e));\n", indent, to_cident(def:full_name())) - append("%s }\n", indent) - append("%s static %s get() {\n", indent, def:name()) - append("%s const ::upb::EnumDef* e = upbdefs_%s_get(&e);\n", indent, to_cident(def:full_name())) - append("%s return %s(e, &e);\n", indent, def:name()) - append("%s }\n", indent) - append("%s};\n", indent) -end - -function print_classes(name, map, indent, append) - if not map[name] then - return - end - - for _, def in ipairs(map[name]) do - if def:def_type() == upb.DEF_MSG then - print_message(def, map, indent, append) - elseif def:def_type() == upb.DEF_ENUM then - print_enum(def, indent, append) - else - error("Unknown def type for " .. def:full_name()) - end - end -end - -local function dump_defs_h(file, append, linktab) - local basename_preproc = to_preproc(file:name()) - append("/* This file contains accessors for a set of compiled-in defs.\n") - append(" * Note that unlike Google's protobuf, it does *not* define\n") - append(" * generated classes or any other kind of data structure for\n") - append(" * actually storing protobufs. It only contains *defs* which\n") - append(" * let you reflect over a protobuf *schema*.\n") - append(" */\n") - emit_file_warning(file, append) - append('#ifndef %s_UPB_H_\n', basename_preproc) - append('#define %s_UPB_H_\n\n', basename_preproc) - append('#include "upb/def.h"\n\n') - append('UPB_BEGIN_EXTERN_C\n\n') - - -- Dump C enums for proto enums. - - append("/* MessageDefs: call these functions to get a ref to a msgdef. */\n") - dump_defs_for_type( - "const upb_msgdef *upbdefs_%s_get(const void *owner);\n", - file:defs(upb.DEF_MSG), append) - - append("/* EnumDefs: call these functions to get a ref to an enumdef. */\n") - dump_defs_for_type( - "const upb_enumdef *upbdefs_%s_get(const void *owner);\n", - file:defs(upb.DEF_ENUM), append) - - append("/* Functions to test whether this message is of a certain type. */\n") - dump_defs_for_type( - "UPB_INLINE bool upbdefs_%s_is(const upb_msgdef *m) {\n" .. - " return strcmp(upb_msgdef_fullname(m), \"%s\") == 0;\n}\n", - file:defs(upb.DEF_MSG), append) - - append("/* Functions to test whether this enum is of a certain type. */\n") - dump_defs_for_type( - "UPB_INLINE bool upbdefs_%s_is(const upb_enumdef *e) {\n" .. - " return strcmp(upb_enumdef_fullname(e), \"%s\") == 0;\n}\n", - file:defs(upb.DEF_ENUM), append) - - append("\n") - - -- fields - local fields = {} - - for f in linktab:objs(upb.DEF_FIELD) do - local symname = f:containing_type():full_name() .. "." .. f:name() - fields[#fields + 1] = {to_cident(symname), f} - end - - table.sort(fields, function(a, b) return a[1] < b[1] end) - - append("/* Functions to get a fielddef from a msgdef reference. */\n") - for _, field in ipairs(fields) do - local f = field[2] - local msg_cident = to_cident(f:containing_type():full_name()) - local field_cident = to_cident(f:name()) - append("UPB_INLINE const upb_fielddef *upbdefs_%s_f_%s(const upb_msgdef *m) {" .. - " UPB_ASSERT(upbdefs_%s_is(m));" .. - " return upb_msgdef_itof(m, %d); }\n", - msg_cident, field_cident, msg_cident, f:number()) - end - - append('\nUPB_END_EXTERN_C\n\n') - - -- C++ wrappers. - local children_map = make_children_map(file) - - append("#ifdef __cplusplus\n\n") - append("namespace upbdefs {\n") - start_namespace(file:package(), append) - print_classes(file:package(), children_map, "", append) - append("\n") - end_namespace(file:package(), append) - append("} /* namespace upbdefs */\n\n") - append("#endif /* __cplusplus */\n") - - append("\n") - append('#endif /* %s_UPB_H_ */\n', basename_preproc) -end - -function export.dump_defs(filedef, append_h, append_c) - local linktab = dump_defs_c(filedef, append_c) - dump_defs_h(filedef, append_h, linktab) -end - -return export -- cgit v1.2.3 From 7f9f7222bf5ab3ad3720b1afd55370b0e473109f Mon Sep 17 00:00:00 2001 From: Joshua Haberman Date: Wed, 23 Jan 2019 17:10:22 -0800 Subject: Changes for google3 import. --- BUILD | 35 ++++++++++++++++++++--------------- build_defs.bzl | 25 ++++++++++++++----------- tools/make_cmakelists.py | 3 +++ 3 files changed, 37 insertions(+), 26 deletions(-) (limited to 'tools') diff --git a/BUILD b/BUILD index 0a8a684..9593936 100644 --- a/BUILD +++ b/BUILD @@ -1,6 +1,7 @@ load( ":build_defs.bzl", "generated_file_staleness_test", + "licenses", # copybara:strip_for_google3 "lua_binary", "lua_cclibrary", "lua_library", @@ -11,6 +12,21 @@ load( "upb_proto_reflection_library", ) +licenses(["notice"]) # BSD (Google-authored w/ possible external contributions) + +exports_files([ + "LICENSE", + "build_defs", +]) + +COPTS = [ + # copybara:strip_for_google3_begin + "-std=c89", + "-pedantic", + "-Wno-long-long", + # copybara:strip_end +] + # C/C++ rules ################################################################## cc_library( @@ -44,11 +60,7 @@ cc_library( "upb/sink.h", "upb/upb.h", ], - copts = [ - "-std=c89", - "-pedantic", - "-Wno-long-long", - ], + copts = COPTS, visibility = ["//visibility:public"], ) @@ -68,11 +80,7 @@ cc_library( "upb/pb/encoder.h", "upb/pb/textprinter.h", ], - copts = [ - "-std=c89", - "-pedantic", - "-Wno-long-long", - ], + copts = COPTS, deps = [ ":upb", ], @@ -88,11 +96,7 @@ cc_library( "upb/json/parser.h", "upb/json/printer.h", ], - copts = [ - "-std=c89", - "-pedantic", - "-Wno-long-long", - ], + copts = COPTS, deps = [ ":upb", ":upb_pb", @@ -309,6 +313,7 @@ cc_library( name = "amalgamation", srcs = ["upb.c"], hdrs = ["upb.h"], + copts = COPTS, ) # Lua libraries. ############################################################### diff --git a/build_defs.bzl b/build_defs.bzl index da21e86..bb4d6f8 100644 --- a/build_defs.bzl +++ b/build_defs.bzl @@ -1,4 +1,3 @@ - _shell_find_runfiles = """ # --- begin runfiles.bash initialization --- # Copy-pasted from Bazel's Bash runfiles library (tools/bash/runfiles/runfiles.bash). @@ -100,7 +99,7 @@ BASE=$(dirname $(rlocation upb/upb_c.so)) export LUA_CPATH="$BASE/?.so" export LUA_PATH="$BASE/?.lua" $(rlocation lua/lua) $(rlocation upb/tools/upbc.lua) "$@" -""" +""", ) rule( @@ -109,10 +108,10 @@ $(rlocation lua/lua) $(rlocation upb/tools/upbc.lua) "$@" data = ["@lua//:lua", "@bazel_tools//tools/bash/runfiles", luamain] + luadeps, ) -def lua_binary(name, luamain, luadeps=[]): +def lua_binary(name, luamain, luadeps = []): _lua_binary_or_test(name, luamain, luadeps, native.sh_binary) -def lua_test(name, luamain, luadeps=[]): +def lua_test(name, luamain, luadeps = []): _lua_binary_or_test(name, luamain, luadeps, native.sh_test) def generated_file_staleness_test(name, outs, generated_pattern): @@ -163,9 +162,9 @@ def generated_file_staleness_test(name, outs, generated_pattern): SrcList = provider( fields = { - 'srcs' : 'list of srcs', - 'hdrs' : 'list of hdrs', - } + "srcs": "list of srcs", + "hdrs": "list of hdrs", + }, ) def _file_list_aspect_impl(target, ctx): @@ -205,7 +204,7 @@ upb_amalgamation = rule( ), "libs": attr.label_list(aspects = [_file_list_aspect]), "outs": attr.output_list(), - } + }, ) # upb_proto_library() rule @@ -223,7 +222,7 @@ def _upb_proto_srcs_impl(ctx, suffix): outs = [] include_dirs = {} for dep in ctx.attr.deps: - if hasattr(dep, 'proto'): + if hasattr(dep, "proto"): for src in dep.proto.transitive_sources: sources.append(src) include_dir = _remove_suffix(src.path, _remove_up(src.short_path) + "." + src.extension) @@ -265,7 +264,7 @@ _upb_proto_library_srcs = rule( default = "@com_google_protobuf//:protoc", ), "deps": attr.label_list(), - } + }, ) def upb_proto_library(name, deps, upbc): @@ -295,7 +294,7 @@ _upb_proto_reflection_library_srcs = rule( default = "@com_google_protobuf//:protoc", ), "deps": attr.label_list(), - } + }, ) def upb_proto_reflection_library(name, deps, upbc): @@ -311,3 +310,7 @@ def upb_proto_reflection_library(name, deps, upbc): deps = [":upb"], copts = ["-Ibazel-out/k8-fastbuild/bin"], ) + +def licenses(*args): + # No-op (for Google-internal usage). + pass diff --git a/tools/make_cmakelists.py b/tools/make_cmakelists.py index c2700b6..1e1c1ee 100755 --- a/tools/make_cmakelists.py +++ b/tools/make_cmakelists.py @@ -137,6 +137,9 @@ class BuildFileFunctions(object): def glob(*args): return [] + def licenses(*args): + pass + class WorkspaceFileFunctions(object): def __init__(self, converter): -- cgit v1.2.3 From 9bc7973e3893a72a62e75b8c7075d692c8794ec1 Mon Sep 17 00:00:00 2001 From: Joshua Haberman Date: Wed, 23 Jan 2019 17:16:31 -0800 Subject: Fixes for Google import. --- tools/amalgamate.py | 4 ++-- upb/handlers-inl.h | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) (limited to 'tools') diff --git a/tools/amalgamate.py b/tools/amalgamate.py index 9ad0286..9640201 100755 --- a/tools/amalgamate.py +++ b/tools/amalgamate.py @@ -16,11 +16,11 @@ class Amalgamator: self.output_h = open(output_path + "upb.h", "w") self.output_c = open(output_path + "upb.c", "w") - self.output_c.write("// Amalgamated source file\n") + self.output_c.write("/* Amalgamated source file */\n") self.output_c.write('#include "upb.h"\n') self.output_c.write(open("upb/port_def.inc").read()) - self.output_h.write("// Amalgamated source file\n") + self.output_h.write("/* Amalgamated source file */\n") self.output_h.write(open("upb/port_def.inc").read()) def finish(self): diff --git a/upb/handlers-inl.h b/upb/handlers-inl.h index 5677a4a..40a0047 100644 --- a/upb/handlers-inl.h +++ b/upb/handlers-inl.h @@ -7,6 +7,8 @@ #define UPB_HANDLERS_INL_H_ #include +#include +#include "upb/handlers.h" #ifdef __cplusplus @@ -162,8 +164,8 @@ struct FuncInfo { * These functions are not bound to a handler data so have no data or cleanup * handler. */ struct UnboundFunc { - CleanupFunc *GetCleanup() { return NULL; } - void *GetData() { return NULL; } + CleanupFunc *GetCleanup() { return nullptr; } + void *GetData() { return nullptr; } }; template -- cgit v1.2.3 From ca5f951137a121e55ca21ee162afd1be596775ba Mon Sep 17 00:00:00 2001 From: Josh Haberman Date: Thu, 24 Jan 2019 12:19:08 -0800 Subject: More fixes for google3 import. --- BUILD | 17 +++++++++++++---- build_defs.bzl | 19 +++++++++++++++++-- tools/make_cmakelists.py | 7 +++++-- 3 files changed, 35 insertions(+), 8 deletions(-) (limited to 'tools') diff --git a/BUILD b/BUILD index 9593936..1c6cdef 100644 --- a/BUILD +++ b/BUILD @@ -7,6 +7,7 @@ load( "lua_library", "lua_test", "make_shell_script", + "map_dep", "upb_amalgamation", "upb_proto_library", "upb_proto_reflection_library", @@ -122,9 +123,9 @@ cc_library( ], hdrs = ["upbc/generator.h"], deps = [ - "@absl//absl/strings", - "@com_google_protobuf//:protobuf", - "@com_google_protobuf//:protoc_lib", + map_dep("@absl//absl/strings"), + map_dep("@com_google_protobuf//:protobuf"), + map_dep("@com_google_protobuf//:protoc_lib"), ], ) @@ -133,10 +134,16 @@ cc_binary( srcs = ["upbc/main.cc"], deps = [ ":upbc_generator", - "@com_google_protobuf//:protoc_lib", + map_dep("@com_google_protobuf//:protoc_lib"), ], ) + +# We strip the tests and remaining rules from google3 until the upb_proto_library() +# and upb_proto_reflection_library() rules are fixed. + +# copybara:strip_for_google3_begin + # C/C++ tests ################################################################## cc_library( @@ -487,3 +494,5 @@ generated_file_staleness_test( ], generated_pattern = "generated/%s", ) + +# copybara:strip_end diff --git a/build_defs.bzl b/build_defs.bzl index bb4d6f8..1c26a00 100644 --- a/build_defs.bzl +++ b/build_defs.bzl @@ -207,6 +207,21 @@ upb_amalgamation = rule( }, ) +is_bazel = not hasattr(native, "genmpm") + +google3_dep_map = { + "@absl//absl/strings": "//third_party/absl/strings", + "@com_google_protobuf//:protoc": "//third_party/protobuf:protoc", + "@com_google_protobuf//:protobuf": "//third_party/protobuf:protobuf", + "@com_google_protobuf//:protoc_lib": "//third_party/protobuf:libprotoc", +} + +def map_dep(dep): + if is_bazel: + return dep + else: + return google3_dep_map[dep] + # upb_proto_library() rule def _remove_up(string): @@ -261,7 +276,7 @@ _upb_proto_library_srcs = rule( "protoc": attr.label( executable = True, cfg = "host", - default = "@com_google_protobuf//:protoc", + default = map_dep("@com_google_protobuf//:protoc"), ), "deps": attr.label_list(), }, @@ -291,7 +306,7 @@ _upb_proto_reflection_library_srcs = rule( "protoc": attr.label( executable = True, cfg = "host", - default = "@com_google_protobuf//:protoc", + default = map_dep("@com_google_protobuf//:protoc"), ), "deps": attr.label_list(), }, diff --git a/tools/make_cmakelists.py b/tools/make_cmakelists.py index 1e1c1ee..86544cb 100755 --- a/tools/make_cmakelists.py +++ b/tools/make_cmakelists.py @@ -134,12 +134,15 @@ class BuildFileFunctions(object): def select(self, arg_dict): return [] - def glob(*args): + def glob(self, *args): return [] - def licenses(*args): + def licenses(self, *args): pass + def map_dep(self, arg): + return arg + class WorkspaceFileFunctions(object): def __init__(self, converter): -- cgit v1.2.3 From ad905b08f5f93b497311290fb4df4059ccd083eb Mon Sep 17 00:00:00 2001 From: Josh Haberman Date: Sun, 17 Feb 2019 20:36:26 -0800 Subject: Fixed amalgamation to properly include stdint.h first for UPB_SIZE(). --- tools/amalgamate.py | 1 + upb/port_def.inc | 4 ++++ 2 files changed, 5 insertions(+) (limited to 'tools') diff --git a/tools/amalgamate.py b/tools/amalgamate.py index 9640201..374d126 100755 --- a/tools/amalgamate.py +++ b/tools/amalgamate.py @@ -21,6 +21,7 @@ class Amalgamator: self.output_c.write(open("upb/port_def.inc").read()) self.output_h.write("/* Amalgamated source file */\n") + self.output_h.write('#include ') self.output_h.write(open("upb/port_def.inc").read()) def finish(self): diff --git a/upb/port_def.inc b/upb/port_def.inc index 33ff78c..fe975a0 100644 --- a/upb/port_def.inc +++ b/upb/port_def.inc @@ -1,4 +1,8 @@ +#ifndef UINTPTR_MAX +#error must include stdint.h first +#endif + #if UINTPTR_MAX == 0xffffffff #define UPB_SIZE(size32, size64) size32 #else -- cgit v1.2.3 From 8b75e5c1197621b29ec2924cdd90f88b1e71ce3b Mon Sep 17 00:00:00 2001 From: Bo Yang Date: Tue, 5 Mar 2019 14:27:35 -0800 Subject: Add _XOPEN_SOURCE to amalgamate.py --- tools/amalgamate.py | 1 + 1 file changed, 1 insertion(+) (limited to 'tools') diff --git a/tools/amalgamate.py b/tools/amalgamate.py index 038c83f..c4c8a1b 100755 --- a/tools/amalgamate.py +++ b/tools/amalgamate.py @@ -17,6 +17,7 @@ class Amalgamator: self.output_c = open(output_path + "upb.c", "w") self.output_c.write("/* Amalgamated source file */\n") + self.output_c.write('#define _XOPEN_SOURCE 700\n') self.output_c.write('#include "upb.h"\n') self.output_c.write(open("upb/port_def.inc").read()) -- cgit v1.2.3 From f298f3078be3fc084f05bd96cb7a3629e74f003c Mon Sep 17 00:00:00 2001 From: Bo Yang Date: Mon, 25 Mar 2019 17:20:49 +0000 Subject: Remove _XOPEN_SOURCE from amalgamate.py --- tools/amalgamate.py | 1 - 1 file changed, 1 deletion(-) (limited to 'tools') diff --git a/tools/amalgamate.py b/tools/amalgamate.py index 5545af5..374d126 100755 --- a/tools/amalgamate.py +++ b/tools/amalgamate.py @@ -17,7 +17,6 @@ class Amalgamator: self.output_c = open(output_path + "upb.c", "w") self.output_c.write("/* Amalgamated source file */\n") - self.output_c.write('#define _XOPEN_SOURCE 700\n') self.output_c.write('#include "upb.h"\n') self.output_c.write(open("upb/port_def.inc").read()) -- cgit v1.2.3