Lua Generator using IR. (#6940)

* initial hack to get new Lua generator into flatc

* Starting to output enum defs for Lua

* Continue to work on table generation for Lua

* Finished basic getter access for Lua

* Added ability to get object by index

* Finished struct builder

* aliased reflection to r

* finish table builder generation

* register requiring files

* better generated header info

* Tying up loose ends

* Updated reflection to handle struct padding

* Addd type sizes to reflection

* Fixed some vector indirect issues

* Lua tests passed

* Misc cleanup

* ci fixes 1

* ci fixes 2

* renaming

* up size of type sizes

* manually ran clang-format-11 -i src/idl_parser.cpp

* fixed some windows casting

* remove stupid auto import

* more static_casting

* remove std

* update other build environments

* remove scoped enums

* replaced std::to_string with NumToString

* more win fixes

* more win fixes

* replaced old lua with new

* removed auto import

* review responses

* more style fixes

* refactor bfbs_gen_len to use code +=

* added consts

* fix lambda capture for windows

* remove unused return type
This commit is contained in:
Derek Bailey 2021-12-02 21:29:19 -08:00 committed by GitHub
parent cffe0c4546
commit 061d61f3f8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
43 changed files with 3461 additions and 1725 deletions

1
.github/labeler.yml vendored
View File

@ -49,6 +49,7 @@ lua:
- '**/*.lua'
- lua/**/*
- src/idl_gen_lua.cpp
- src/bfbs_gen_lua.cpp
lobster:
- '**/*.lobster'

View File

@ -40,6 +40,7 @@ filegroup(
"include/flatbuffers/allocator.h",
"include/flatbuffers/array.h",
"include/flatbuffers/base.h",
"include/flatbuffers/bfbs_generator.h",
"include/flatbuffers/buffer.h",
"include/flatbuffers/buffer_ref.h",
"include/flatbuffers/code_generators.h",

View File

@ -92,6 +92,7 @@ set(FlatBuffers_Library_SRCS
include/flatbuffers/allocator.h
include/flatbuffers/array.h
include/flatbuffers/base.h
include/flatbuffers/bfbs_generator.h
include/flatbuffers/buffer.h
include/flatbuffers/buffer_ref.h
include/flatbuffers/default_allocator.h
@ -139,7 +140,10 @@ set(FlatBuffers_Compiler_SRCS
src/idl_gen_swift.cpp
src/flatc.cpp
src/flatc_main.cpp
src/bfbs_gen.h
src/bfbs_gen_lua.h
include/flatbuffers/code_generators.h
src/bfbs_gen_lua.cpp
src/code_generators.cpp
grpc/src/compiler/schema_interface.h
grpc/src/compiler/cpp_generator.h

View File

@ -18,6 +18,7 @@ set(FlatBuffers_Library_SRCS
${FLATBUFFERS_SRC}/include/flatbuffers/allocator.h
${FLATBUFFERS_SRC}/include/flatbuffers/array.h
${FLATBUFFERS_SRC}/include/flatbuffers/base.h
${FLATBUFFERS_SRC}/include/flatbuffers/bfbs_generator.h
${FLATBUFFERS_SRC}/include/flatbuffers/buffer.h
${FLATBUFFERS_SRC}/include/flatbuffers/buffer_ref.h
${FLATBUFFERS_SRC}/include/flatbuffers/default_allocator.h

View File

@ -0,0 +1,43 @@
/*
* Copyright 2021 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FLATBUFFERS_BFBS_GENERATOR_H_
#define FLATBUFFERS_BFBS_GENERATOR_H_
#include <cstdint>
namespace flatbuffers {
enum GeneratorStatus {
OK,
FAILED,
FAILED_VERIFICATION,
};
// A Flatbuffer Code Generator that receives a binary serialized reflection.fbs
// and generates code from it.
class BfbsGenerator {
public:
virtual ~BfbsGenerator() {}
// Generate code from the provided `buffer` of given `length`. The buffer is
// a serialized reflection.fbs.
virtual GeneratorStatus Generate(const uint8_t *buffer, int64_t length) = 0;
};
} // namespace flatbuffers
#endif // FLATBUFFERS_BFBS_GENERATOR_H_

View File

@ -21,6 +21,7 @@
#include <limits>
#include <string>
#include "flatbuffers/bfbs_generator.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
@ -51,6 +52,7 @@ class FlatCompiler {
flatbuffers::IDLOptions::Language lang;
const char *generator_help;
MakeRuleFn make_rule;
BfbsGenerator *bfbs_generator;
};
typedef void (*WarnFn)(const FlatCompiler *flatc, const std::string &warn,

View File

@ -162,7 +162,9 @@ struct Type FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_BASE_TYPE = 4,
VT_ELEMENT = 6,
VT_INDEX = 8,
VT_FIXED_LENGTH = 10
VT_FIXED_LENGTH = 10,
VT_BASE_SIZE = 12,
VT_ELEMENT_SIZE = 14
};
reflection::BaseType base_type() const {
return static_cast<reflection::BaseType>(GetField<int8_t>(VT_BASE_TYPE, 0));
@ -176,12 +178,22 @@ struct Type FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
uint16_t fixed_length() const {
return GetField<uint16_t>(VT_FIXED_LENGTH, 0);
}
/// The size (octets) of the `base_type` field.
uint32_t base_size() const {
return GetField<uint32_t>(VT_BASE_SIZE, 4);
}
/// The size (octets) of the `element` field, if present.
uint32_t element_size() const {
return GetField<uint32_t>(VT_ELEMENT_SIZE, 0);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyField<int8_t>(verifier, VT_BASE_TYPE) &&
VerifyField<int8_t>(verifier, VT_ELEMENT) &&
VerifyField<int32_t>(verifier, VT_INDEX) &&
VerifyField<uint16_t>(verifier, VT_FIXED_LENGTH) &&
VerifyField<uint32_t>(verifier, VT_BASE_SIZE) &&
VerifyField<uint32_t>(verifier, VT_ELEMENT_SIZE) &&
verifier.EndTable();
}
};
@ -202,6 +214,12 @@ struct TypeBuilder {
void add_fixed_length(uint16_t fixed_length) {
fbb_.AddElement<uint16_t>(Type::VT_FIXED_LENGTH, fixed_length, 0);
}
void add_base_size(uint32_t base_size) {
fbb_.AddElement<uint32_t>(Type::VT_BASE_SIZE, base_size, 4);
}
void add_element_size(uint32_t element_size) {
fbb_.AddElement<uint32_t>(Type::VT_ELEMENT_SIZE, element_size, 0);
}
explicit TypeBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@ -218,8 +236,12 @@ inline flatbuffers::Offset<Type> CreateType(
reflection::BaseType base_type = reflection::None,
reflection::BaseType element = reflection::None,
int32_t index = -1,
uint16_t fixed_length = 0) {
uint16_t fixed_length = 0,
uint32_t base_size = 4,
uint32_t element_size = 0) {
TypeBuilder builder_(_fbb);
builder_.add_element_size(element_size);
builder_.add_base_size(base_size);
builder_.add_index(index);
builder_.add_fixed_length(fixed_length);
builder_.add_element(element);
@ -556,7 +578,8 @@ struct Field FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
VT_KEY = 20,
VT_ATTRIBUTES = 22,
VT_DOCUMENTATION = 24,
VT_OPTIONAL = 26
VT_OPTIONAL = 26,
VT_PADDING = 28
};
const flatbuffers::String *name() const {
return GetPointer<const flatbuffers::String *>(VT_NAME);
@ -600,6 +623,10 @@ struct Field FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
bool optional() const {
return GetField<uint8_t>(VT_OPTIONAL, 0) != 0;
}
/// Number of padding octets to always add after this field. Structs only.
uint16_t padding() const {
return GetField<uint16_t>(VT_PADDING, 0);
}
bool Verify(flatbuffers::Verifier &verifier) const {
return VerifyTableStart(verifier) &&
VerifyOffsetRequired(verifier, VT_NAME) &&
@ -620,6 +647,7 @@ struct Field FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {
verifier.VerifyVector(documentation()) &&
verifier.VerifyVectorOfStrings(documentation()) &&
VerifyField<uint8_t>(verifier, VT_OPTIONAL) &&
VerifyField<uint16_t>(verifier, VT_PADDING) &&
verifier.EndTable();
}
};
@ -664,6 +692,9 @@ struct FieldBuilder {
void add_optional(bool optional) {
fbb_.AddElement<uint8_t>(Field::VT_OPTIONAL, static_cast<uint8_t>(optional), 0);
}
void add_padding(uint16_t padding) {
fbb_.AddElement<uint16_t>(Field::VT_PADDING, padding, 0);
}
explicit FieldBuilder(flatbuffers::FlatBufferBuilder &_fbb)
: fbb_(_fbb) {
start_ = fbb_.StartTable();
@ -690,7 +721,8 @@ inline flatbuffers::Offset<Field> CreateField(
bool key = false,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<reflection::KeyValue>>> attributes = 0,
flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>> documentation = 0,
bool optional = false) {
bool optional = false,
uint16_t padding = 0) {
FieldBuilder builder_(_fbb);
builder_.add_default_real(default_real);
builder_.add_default_integer(default_integer);
@ -698,6 +730,7 @@ inline flatbuffers::Offset<Field> CreateField(
builder_.add_attributes(attributes);
builder_.add_type(type);
builder_.add_name(name);
builder_.add_padding(padding);
builder_.add_offset(offset);
builder_.add_id(id);
builder_.add_optional(optional);
@ -720,7 +753,8 @@ inline flatbuffers::Offset<Field> CreateFieldDirect(
bool key = false,
std::vector<flatbuffers::Offset<reflection::KeyValue>> *attributes = nullptr,
const std::vector<flatbuffers::Offset<flatbuffers::String>> *documentation = nullptr,
bool optional = false) {
bool optional = false,
uint16_t padding = 0) {
auto name__ = name ? _fbb.CreateString(name) : 0;
auto attributes__ = attributes ? _fbb.CreateVectorOfSortedTables<reflection::KeyValue>(attributes) : 0;
auto documentation__ = documentation ? _fbb.CreateVector<flatbuffers::Offset<flatbuffers::String>>(*documentation) : 0;
@ -737,7 +771,8 @@ inline flatbuffers::Offset<Field> CreateFieldDirect(
key,
attributes__,
documentation__,
optional);
optional,
padding);
}
struct Object FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table {

View File

@ -38,6 +38,10 @@ table Type {
// If base_type == Union, UnionType, or integral derived
// from an enum, index into "enums" below.
fixed_length:uint16 = 0; // Only if base_type == Array.
/// The size (octets) of the `base_type` field.
base_size:uint = 4; // 4 Is a common size due to offsets being that size.
/// The size (octets) of the `element` field, if present.
element_size:uint = 0;
}
table KeyValue {
@ -77,6 +81,8 @@ table Field {
attributes:[KeyValue];
documentation:[string];
optional:bool = false;
/// Number of padding octets to always add after this field. Structs only.
padding:uint16 = 0;
}
table Object { // Used for both tables and structs.

Binary file not shown.

View File

@ -127,7 +127,6 @@ flatc(
"--dart",
"--go",
"--lobster",
"--lua",
"--php",
],
schema="monster_test.fbs",
@ -135,6 +134,12 @@ flatc(
data="monsterdata_test.json",
)
flatc(
["--lua", "--bfbs-filenames", str(tests_path)],
schema="monster_test.fbs",
include="include_test"
)
flatc(
NO_INCL_OPTS + CPP_OPTS + ["--grpc"],
schema="monster_test.fbs",

View File

@ -34,6 +34,9 @@ cc_library(
cc_library(
name = "flatc_library",
srcs = [
"bfbs_gen.h",
"bfbs_gen_lua.cpp",
"bfbs_gen_lua.h",
"flatc.cpp",
],
hdrs = [
@ -50,6 +53,9 @@ cc_library(
cc_library(
name = "flatc",
srcs = [
"bfbs_gen.h",
"bfbs_gen_lua.cpp",
"bfbs_gen_lua.h",
"flatc_main.cpp",
"idl_gen_cpp.cpp",
"idl_gen_csharp.cpp",

224
src/bfbs_gen.h Normal file
View File

@ -0,0 +1,224 @@
/*
* Copyright 2021 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FLATBUFFERS_BFBS_GEN_H_
#define FLATBUFFERS_BFBS_GEN_H_
#include <cstdint>
#include "flatbuffers/bfbs_generator.h"
#include "flatbuffers/reflection_generated.h"
namespace flatbuffers {
void ForAllEnums(
const flatbuffers::Vector<flatbuffers::Offset<reflection::Enum>> *enums,
std::function<void(const reflection::Enum *)> func) {
for (auto it = enums->cbegin(); it != enums->cend(); ++it) { func(*it); }
}
void ForAllObjects(
const flatbuffers::Vector<flatbuffers::Offset<reflection::Object>> *objects,
std::function<void(const reflection::Object *)> func) {
for (auto it = objects->cbegin(); it != objects->cend(); ++it) { func(*it); }
}
void ForAllEnumValues(const reflection::Enum *enum_def,
std::function<void(const reflection::EnumVal *)> func) {
for (auto it = enum_def->values()->cbegin(); it != enum_def->values()->cend();
++it) {
func(*it);
}
}
void ForAllDocumentation(
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>
*documentation,
std::function<void(const flatbuffers::String *)> func) {
if (!documentation) { return; }
for (auto it = documentation->cbegin(); it != documentation->cend(); ++it) {
func(*it);
}
}
// Maps the field index into object->fields() to the field's ID (the ith element
// in the return vector).
static std::vector<uint32_t> FieldIdToIndex(const reflection::Object *object) {
std::vector<uint32_t> field_index_by_id;
field_index_by_id.resize(object->fields()->size());
// Create the mapping of field ID to the index into the vector.
for (uint32_t i = 0; i < object->fields()->size(); ++i) {
auto field = object->fields()->Get(i);
field_index_by_id[field->id()] = i;
}
return field_index_by_id;
}
static bool IsStructOrTable(const reflection::BaseType base_type) {
return base_type == reflection::Obj;
}
static bool IsScalar(const reflection::BaseType base_type) {
return base_type >= reflection::UType && base_type <= reflection::Double;
}
static bool IsFloatingPoint(const reflection::BaseType base_type) {
return base_type == reflection::Float || base_type == reflection::Double;
}
static bool IsBool(const reflection::BaseType base_type) {
return base_type == reflection::Bool;
}
static bool IsSingleByte(const reflection::BaseType base_type) {
return base_type >= reflection::UType && base_type <= reflection::UByte;
}
static bool IsVector(const reflection::BaseType base_type) {
return base_type == reflection::Vector;
}
static std::string MakeCamelCase(const std::string &in,
bool uppercase_first = true) {
std::string s;
for (size_t i = 0; i < in.length(); i++) {
if (!i && uppercase_first)
s += static_cast<char>(::toupper(static_cast<unsigned char>(in[0])));
else if (in[i] == '_' && i + 1 < in.length())
s += static_cast<char>(::toupper(static_cast<unsigned char>(in[++i])));
else
s += in[i];
}
return s;
}
static std::string Denamespace(const flatbuffers::String *name,
std::string &ns) {
const size_t pos = name->str().find_last_of('.');
if (pos == std::string::npos) {
ns = "";
return name->str();
}
ns = name->str().substr(0, pos);
return name->str().substr(pos + 1);
}
static std::string Denamespace(const flatbuffers::String *name) {
std::string ns;
return Denamespace(name, ns);
}
// A concrete base Flatbuffer Generator that specific language generators can
// derive from.
class BaseBfbsGenerator : public BfbsGenerator {
public:
virtual ~BaseBfbsGenerator() {}
BaseBfbsGenerator() : schema_(nullptr) {}
virtual GeneratorStatus GenerateFromSchema(
const reflection::Schema *schema) = 0;
//
virtual uint64_t SupportedAdvancedFeatures() const = 0;
// Override of the Generator::generate method that does the initial
// deserialization and verification steps.
GeneratorStatus Generate(const uint8_t *buffer,
int64_t length) FLATBUFFERS_OVERRIDE {
flatbuffers::Verifier verifier(buffer, static_cast<size_t>(length));
if (!reflection::VerifySchemaBuffer(verifier)) {
return FAILED_VERIFICATION;
}
// Store the root schema since there are cases where leaf nodes refer to
// things in the root schema (e.g., indexing the objects).
schema_ = reflection::GetSchema(buffer);
const uint64_t advance_features = schema_->advanced_features();
if (advance_features > SupportedAdvancedFeatures()) {
return FAILED_VERIFICATION;
}
GeneratorStatus status = GenerateFromSchema(schema_);
schema_ = nullptr;
return status;
}
protected:
const reflection::Object *GetObject(const reflection::Type *type) const {
if (type->index() >= 0 && IsStructOrTable(type->base_type())) {
return GetObjectByIndex(type->index());
}
return nullptr;
}
const reflection::Enum *GetEnum(const reflection::Type *type) const {
// TODO(derekbailey): it would be better to have a explicit list of allowed
// base types, instead of negating Obj types.
if (type->index() >= 0 && !IsStructOrTable(type->base_type())) {
return GetEnumByIndex(type->index());
}
return nullptr;
}
// Used to get a object that is reference by index. (e.g.
// reflection::Type::index). Returns nullptr if no object is available.
const reflection::Object *GetObjectByIndex(int32_t index) const {
if (!schema_ || index < 0 ||
index >= static_cast<int32_t>(schema_->objects()->size())) {
return nullptr;
}
return schema_->objects()->Get(index);
}
// Used to get a enum that is reference by index. (e.g.
// reflection::Type::index). Returns nullptr if no enum is available.
const reflection::Enum *GetEnumByIndex(int32_t index) const {
if (!schema_ || index < 0 ||
index >= static_cast<int32_t>(schema_->enums()->size())) {
return nullptr;
}
return schema_->enums()->Get(index);
}
void ForAllFields(const reflection::Object *object, bool reverse,
std::function<void(const reflection::Field *)> func) const {
const std::vector<uint32_t> field_to_id_map = FieldIdToIndex(object);
for (size_t i = 0; i < field_to_id_map.size(); ++i) {
func(object->fields()->Get(
field_to_id_map[reverse ? field_to_id_map.size() - (i + 1) : i]));
}
}
bool IsTable(const reflection::Type *type, bool use_element = false) const {
return !IsStruct(type, use_element);
}
bool IsStruct(const reflection::Type *type, bool use_element = false) const {
const reflection::BaseType base_type =
use_element ? type->element() : type->base_type();
return IsStructOrTable(base_type) &&
GetObjectByIndex(type->index())->is_struct();
}
const reflection::Schema *schema_;
};
} // namespace flatbuffers
#endif // FLATBUFFERS_BFBS_GEN_H_

620
src/bfbs_gen_lua.cpp Normal file
View File

@ -0,0 +1,620 @@
/*
* Copyright 2021 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bfbs_gen_lua.h"
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <unordered_set>
#include <vector>
// Ensure no includes to flatc internals. bfbs_gen.h and generator.h are OK.
#include "bfbs_gen.h"
#include "flatbuffers/bfbs_generator.h"
// The intermediate representation schema.
#include "flatbuffers/reflection_generated.h"
namespace flatbuffers {
namespace {
// To reduce typing
namespace r = ::reflection;
class LuaBfbsGenerator : public BaseBfbsGenerator {
public:
explicit LuaBfbsGenerator(const std::string &flatc_version)
: BaseBfbsGenerator(),
keywords_(),
requires_(),
current_obj_(nullptr),
current_enum_(nullptr),
flatc_version_(flatc_version) {
static const char *const keywords[] = {
"and", "break", "do", "else", "elseif", "end", "false", "for",
"function", "goto", "if", "in", "local", "nil", "not", "or",
"repeat", "return", "then", "true", "until", "while"
};
keywords_.insert(std::begin(keywords), std::end(keywords));
}
GeneratorStatus GenerateFromSchema(const r::Schema *schema)
FLATBUFFERS_OVERRIDE {
if (!GenerateEnums(schema->enums())) { return FAILED; }
if (!GenerateObjects(schema->objects(), schema->root_table())) {
return FAILED;
}
return OK;
}
uint64_t SupportedAdvancedFeatures() const FLATBUFFERS_OVERRIDE {
return 0xF;
}
protected:
bool GenerateEnums(
const flatbuffers::Vector<flatbuffers::Offset<r::Enum>> *enums) {
ForAllEnums(enums, [&](const r::Enum *enum_def) {
std::string code;
StartCodeBlock(enum_def);
std::string ns;
const std::string enum_name =
NormalizeName(Denamespace(enum_def->name(), ns));
GenerateDocumentation(enum_def->documentation(), "", code);
code += "local " + enum_name + " = {\n";
ForAllEnumValues(enum_def, [&](const reflection::EnumVal *enum_val) {
GenerateDocumentation(enum_val->documentation(), " ", code);
code += " " + NormalizeName(enum_val->name()) + " = " +
NumToString(enum_val->value()) + ",\n";
});
code += "}\n";
code += "\n";
EmitCodeBlock(code, enum_name, ns, enum_def->declaration_file()->str());
});
return true;
}
bool GenerateObjects(
const flatbuffers::Vector<flatbuffers::Offset<r::Object>> *objects,
const r::Object *root_object) {
ForAllObjects(objects, [&](const r::Object *object) {
std::string code;
StartCodeBlock(object);
// Register the main flatbuffers module.
RegisterRequires("flatbuffers", "flatbuffers");
std::string ns;
const std::string object_name =
NormalizeName(Denamespace(object->name(), ns));
GenerateDocumentation(object->documentation(), "", code);
code += "local " + object_name + " = {}\n";
code += "local mt = {}\n";
code += "\n";
code += "function " + object_name + ".New()\n";
code += " local o = {}\n";
code += " setmetatable(o, {__index = mt})\n";
code += " return o\n";
code += "end\n";
code += "\n";
if (object == root_object) {
code += "function " + object_name + ".GetRootAs" + object_name +
"(buf, offset)\n";
code += " if type(buf) == \"string\" then\n";
code += " buf = flatbuffers.binaryArray.New(buf)\n";
code += " end\n";
code += "\n";
code += " local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)\n";
code += " local o = " + object_name + ".New()\n";
code += " o:Init(buf, n + offset)\n";
code += " return o\n";
code += "end\n";
code += "\n";
}
// Generates a init method that receives a pre-existing accessor object,
// so that objects can be reused.
code += "function mt:Init(buf, pos)\n";
code += " self.view = flatbuffers.view.New(buf, pos)\n";
code += "end\n";
code += "\n";
// Create all the field accessors.
ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
// Skip writing deprecated fields altogether.
if (field->deprecated()) { return; }
const std::string field_name = NormalizeName(field->name());
const std::string field_name_camel_case = MakeCamelCase(field_name);
const r::BaseType base_type = field->type()->base_type();
// Generate some fixed strings so we don't repeat outselves later.
const std::string getter_signature =
"function mt:" + field_name_camel_case + "()\n";
const std::string offset_prefix = "local o = self.view:Offset(" +
NumToString(field->offset()) + ")\n";
const std::string offset_prefix_2 = "if o ~= 0 then\n";
GenerateDocumentation(field->documentation(), "", code);
if (IsScalar(base_type)) {
code += getter_signature;
if (object->is_struct()) {
// TODO(derekbailey): it would be nice to modify the view:Get to
// just pass in the offset and not have to add it its own
// self.view.pos.
code += " return " + GenerateGetter(field->type()) +
"self.view.pos + " + NumToString(field->offset()) + ")\n";
} else {
// Table accessors
code += " " + offset_prefix;
code += " " + offset_prefix_2;
std::string getter =
GenerateGetter(field->type()) + "self.view.pos + o)";
if (IsBool(base_type)) { getter = "(" + getter + " ~=0)"; }
code += " return " + getter + "\n";
code += " end\n";
code += " return " + DefaultValue(field) + "\n";
}
code += "end\n";
code += "\n";
} else {
switch (base_type) {
case r::String: {
code += getter_signature;
code += " " + offset_prefix;
code += " " + offset_prefix_2;
code += " return " + GenerateGetter(field->type()) +
"self.view.pos + o)\n";
code += " end\n";
code += "end\n";
code += "\n";
break;
}
case r::Obj: {
if (object->is_struct()) {
code += "function mt:" + field_name_camel_case + "(obj)\n";
code += " obj:Init(self.view.bytes, self.view.pos + " +
NumToString(field->offset()) + ")\n";
code += " return obj\n";
code += "end\n";
code += "\n";
} else {
code += getter_signature;
code += " " + offset_prefix;
code += " " + offset_prefix_2;
const r::Object *field_object = GetObject(field->type());
if (!field_object) {
// TODO(derekbailey): this is an error condition. we
// should report it better.
return;
}
code += " local x = " +
std::string(
field_object->is_struct()
? "self.view.pos + o\n"
: "self.view:Indirect(self.view.pos + o)\n");
const std::string require_name = RegisterRequires(field);
code += " local obj = " + require_name + ".New()\n";
code += " obj:Init(self.view.bytes, x)\n";
code += " return obj\n";
code += " end\n";
code += "end\n";
code += "\n";
}
break;
}
case r::Union: {
code += getter_signature;
code += " " + offset_prefix;
code += " " + offset_prefix_2;
code +=
" local obj = "
"flatbuffers.view.New(flatbuffers.binaryArray.New("
"0), 0)\n";
code += " " + GenerateGetter(field->type()) + "obj, o)\n";
code += " return obj\n";
code += " end\n";
code += "end\n";
code += "\n";
break;
}
case r::Array:
case r::Vector: {
const r::BaseType vector_base_type = field->type()->element();
int32_t element_size = field->type()->element_size();
code += "function mt:" + field_name_camel_case + "(j)\n";
code += " " + offset_prefix;
code += " " + offset_prefix_2;
if (IsStructOrTable(vector_base_type)) {
code += " local x = self.view:Vector(o)\n";
code +=
" x = x + ((j-1) * " + NumToString(element_size) + ")\n";
if (IsTable(field->type(), /*use_element=*/true)) {
code += " x = self.view:Indirect(x)\n";
} else {
// Vector of structs are inline, so we need to query the
// size of the struct.
const reflection::Object *obj =
GetObjectByIndex(field->type()->index());
element_size = obj->bytesize();
}
// Include the referenced type, thus we need to make sure
// we set `use_element` to true.
const std::string require_name =
RegisterRequires(field, /*use_element=*/true);
code += " local obj = " + require_name + ".New()\n";
code += " obj:Init(self.view.bytes, x)\n";
code += " return obj\n";
} else {
code += " local a = self.view:Vector(o)\n";
code += " return " + GenerateGetter(field->type()) +
"a + ((j-1) * " + NumToString(element_size) + "))\n";
}
code += " end\n";
// Only generate a default value for those types that are
// supported.
if (!IsStructOrTable(vector_base_type)) {
code +=
" return " +
std::string(vector_base_type == r::String ? "''\n" : "0\n");
}
code += "end\n";
code += "\n";
// If the vector is composed of single byte values, we
// generate a helper function to get it as a byte string in
// Lua.
if (IsSingleByte(vector_base_type)) {
code += "function mt:" + field_name_camel_case +
"AsString(start, stop)\n";
code += " return self.view:VectorAsString(" +
NumToString(field->offset()) + ", start, stop)\n";
code += "end\n";
code += "\n";
}
// We also make a new accessor to query just the length of the
// vector.
code += "function mt:" + field_name_camel_case + "Length()\n";
code += " " + offset_prefix;
code += " " + offset_prefix_2;
code += " return self.view:VectorLen(o)\n";
code += " end\n";
code += " return 0\n";
code += "end\n";
code += "\n";
break;
}
default: {
return;
}
}
}
return;
});
// Create all the builders
if (object->is_struct()) {
code += "function " + object_name + ".Create" + object_name +
"(builder" + GenerateStructBuilderArgs(object) + ")\n";
code += AppendStructBuilderBody(object);
code += " return builder:Offset()\n";
code += "end\n";
code += "\n";
} else {
// Table builders
code += "function " + object_name + ".Start(builder)\n";
code += " builder:StartObject(" +
NumToString(object->fields()->size()) + ")\n";
code += "end\n";
code += "\n";
ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
if (field->deprecated()) { return; }
const std::string field_name = NormalizeName(field->name());
code += "function " + object_name + ".Add" +
MakeCamelCase(field_name) + "(builder, " +
MakeCamelCase(field_name, false) + ")\n";
code += " builder:Prepend" + GenerateMethod(field) + "Slot(" +
NumToString(field->id()) + ", " +
MakeCamelCase(field_name, false) + ", " +
DefaultValue(field) + ")\n";
code += "end\n";
code += "\n";
if (IsVector(field->type()->base_type())) {
code += "function " + object_name + ".Start" +
MakeCamelCase(field_name) + "Vector(builder, numElems)\n";
const int32_t element_size = field->type()->element_size();
int32_t alignment = 0;
if (IsStruct(field->type(), /*use_element=*/true)) {
alignment = GetObjectByIndex(field->type()->index())->minalign();
} else {
alignment = element_size;
}
code += " return builder:StartVector(" +
NumToString(element_size) + ", numElems, " +
NumToString(alignment) + ")\n";
code += "end\n";
code += "\n";
}
});
code += "function " + object_name + ".End(builder)\n";
code += " return builder:EndObject()\n";
code += "end\n";
code += "\n";
}
EmitCodeBlock(code, object_name, ns, object->declaration_file()->str());
});
return true;
}
private:
void GenerateDocumentation(
const flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>
*documentation,
std::string indent, std::string &code) const {
flatbuffers::ForAllDocumentation(
documentation, [&](const flatbuffers::String *str) {
code += indent + "--" + str->str() + "\n";
});
}
std::string GenerateStructBuilderArgs(const r::Object *object,
std::string prefix = "") const {
std::string signature;
ForAllFields(object, /*reverse=*/false, [&](const r::Field *field) {
if (IsStructOrTable(field->type()->base_type())) {
const r::Object *field_object = GetObject(field->type());
signature += GenerateStructBuilderArgs(
field_object, prefix + NormalizeName(field->name()) + "_");
} else {
signature +=
", " + prefix + MakeCamelCase(NormalizeName(field->name()), false);
}
});
return signature;
}
std::string AppendStructBuilderBody(const r::Object *object,
std::string prefix = "") const {
std::string code;
code += " builder:Prep(" + NumToString(object->minalign()) + ", " +
NumToString(object->bytesize()) + ")\n";
// We need to reverse the order we iterate over, since we build the
// buffer backwards.
ForAllFields(object, /*reverse=*/true, [&](const r::Field *field) {
const int32_t num_padding_bytes = field->padding();
if (num_padding_bytes) {
code += " builder:Pad(" + NumToString(num_padding_bytes) + ")\n";
}
if (IsStructOrTable(field->type()->base_type())) {
const r::Object *field_object = GetObject(field->type());
code += AppendStructBuilderBody(
field_object, prefix + NormalizeName(field->name()) + "_");
} else {
code += " builder:Prepend" + GenerateMethod(field) + "(" + prefix +
MakeCamelCase(NormalizeName(field->name()), false) + ")\n";
}
});
return code;
}
std::string GenerateMethod(const r::Field *field) const {
const r::BaseType base_type = field->type()->base_type();
if (IsScalar(base_type)) { return MakeCamelCase(GenerateType(base_type)); }
if (IsStructOrTable(base_type)) { return "Struct"; }
return "UOffsetTRelative";
}
std::string GenerateGetter(const r::Type *type,
bool element_type = false) const {
switch (element_type ? type->element() : type->base_type()) {
case r::String: return "self.view:String(";
case r::Union: return "self.view:Union(";
case r::Vector: return GenerateGetter(type, true);
default:
return "self.view:Get(flatbuffers.N." +
MakeCamelCase(GenerateType(type, element_type)) + ", ";
}
}
std::string GenerateType(const r::Type *type,
bool element_type = false) const {
const r::BaseType base_type =
element_type ? type->element() : type->base_type();
if (IsScalar(base_type)) { return GenerateType(base_type); }
switch (base_type) {
case r::String: return "string";
case r::Vector: return GenerateGetter(type, true);
case r::Obj: {
const r::Object *obj = GetObject(type);
return NormalizeName(Denamespace(obj->name()));
};
default: return "*flatbuffers.Table";
}
}
std::string GenerateType(const r::BaseType base_type) const {
// Need to override the default naming to match the Lua runtime libraries.
// TODO(derekbailey): make overloads in the runtime libraries to avoid this.
switch (base_type) {
case r::None: return "uint8";
case r::UType: return "uint8";
case r::Byte: return "int8";
case r::UByte: return "uint8";
case r::Short: return "int16";
case r::UShort: return "uint16";
case r::Int: return "int32";
case r::UInt: return "uint32";
case r::Long: return "int64";
case r::ULong: return "uint64";
case r::Float: return "Float32";
case r::Double: return "Float64";
default: return r::EnumNameBaseType(base_type);
}
}
std::string DefaultValue(const r::Field *field) const {
const r::BaseType base_type = field->type()->base_type();
if (IsFloatingPoint(base_type)) {
return NumToString(field->default_real());
}
if (IsBool(base_type)) {
return field->default_integer() ? "true" : "false";
}
if (IsScalar(base_type)) { return NumToString((field->default_integer())); }
// represents offsets
return "0";
}
std::string NormalizeName(const std::string name) const {
return keywords_.find(name) == keywords_.end() ? name : "_" + name;
}
std::string NormalizeName(const flatbuffers::String *name) const {
return NormalizeName(name->str());
}
void StartCodeBlock(const reflection::Enum *enum_def) {
current_enum_ = enum_def;
current_obj_ = nullptr;
requires_.clear();
}
void StartCodeBlock(const reflection::Object *object) {
current_obj_ = object;
current_enum_ = nullptr;
requires_.clear();
}
std::string RegisterRequires(const r::Field *field,
bool use_element = false) {
std::string type_name;
const r::BaseType type =
use_element ? field->type()->element() : field->type()->base_type();
if (IsStructOrTable(type)) {
const r::Object *object = GetObjectByIndex(field->type()->index());
if (object == current_obj_) { return Denamespace(object->name()); }
type_name = object->name()->str();
} else {
const r::Enum *enum_def = GetEnumByIndex(field->type()->index());
if (enum_def == current_enum_) { return Denamespace(enum_def->name()); }
type_name = enum_def->name()->str();
}
// Prefix with double __ to avoid name clashing, since these are defined
// at the top of the file and have lexical scoping. Replace '.' with '_'
// so it can be a legal identifier.
std::string name = "__" + type_name;
std::replace(name.begin(), name.end(), '.', '_');
return RegisterRequires(name, type_name);
}
std::string RegisterRequires(const std::string &local_name,
const std::string &requires_name) {
requires_[local_name] = requires_name;
return local_name;
}
void EmitCodeBlock(const std::string &code_block, const std::string &name,
const std::string &ns,
const std::string &declaring_file) const {
const std::string root_type = schema_->root_table()->name()->str();
const std::string root_file =
schema_->root_table()->declaration_file()->str();
const std::string full_qualified_name = ns.empty() ? name : ns + "." + name;
std::string code = "--[[ " + full_qualified_name + "\n\n";
code +=
" Automatically generated by the FlatBuffers compiler, do not "
"modify.\n";
code += " Or modify. I'm a message, not a cop.\n";
code += "\n";
code += " flatc version: " + flatc_version_ + "\n";
code += "\n";
code += " Declared by : " + declaring_file + "\n";
code += " Rooting type : " + root_type + " (" + root_file + ")\n";
code += "\n--]]\n\n";
if (!requires_.empty()) {
for (auto it = requires_.cbegin(); it != requires_.cend(); ++it) {
code += "local " + it->first + " = require('" + it->second + "')\n";
}
code += "\n";
}
code += code_block;
code += "return " + name;
// Namespaces are '.' deliminted, so replace it with the path separator.
std::string path = ns;
if (path.empty()) {
path = ".";
} else {
std::replace(path.begin(), path.end(), '.', '/');
}
// TODO(derekbailey): figure out a save file without depending on util.h
EnsureDirExists(path);
const std::string file_name = path + "/" + name + ".lua";
SaveFile(file_name.c_str(), code, false);
}
std::unordered_set<std::string> keywords_;
std::map<std::string, std::string> requires_;
const r::Object *current_obj_;
const r::Enum *current_enum_;
const std::string flatc_version_;
};
} // namespace
std::unique_ptr<BfbsGenerator> NewLuaBfbsGenerator(
const std::string &flatc_version) {
return std::unique_ptr<LuaBfbsGenerator>(new LuaBfbsGenerator(flatc_version));
}
} // namespace flatbuffers

33
src/bfbs_gen_lua.h Normal file
View File

@ -0,0 +1,33 @@
/*
* Copyright 2021 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FLATBUFFERS_BFBS_GEN_LUA_H_
#define FLATBUFFERS_BFBS_GEN_LUA_H_
#include <memory>
#include <string>
#include "flatbuffers/bfbs_generator.h"
namespace flatbuffers {
// Constructs a new Lua Code generator.
std::unique_ptr<BfbsGenerator> NewLuaBfbsGenerator(
const std::string &flatc_version);
} // namespace flatbuffers
#endif // FLATBUFFERS_BFBS_GEN_LUA_H_

View File

@ -18,6 +18,9 @@
#include <list>
#include "bfbs_gen_lua.h"
#include "flatbuffers/util.h"
namespace flatbuffers {
const char *FLATC_VERSION() { return FLATBUFFERS_VERSION(); }
@ -205,6 +208,7 @@ int FlatCompiler::Compile(int argc, const char **argv) {
bool raw_binary = false;
bool schema_binary = false;
bool grpc_enabled = false;
bool requires_bfbs = false;
std::vector<std::string> filenames;
std::list<std::string> include_directories_storage;
std::vector<const char *> include_directories;
@ -405,10 +409,15 @@ int FlatCompiler::Compile(int argc, const char **argv) {
generator_enabled[i] = true;
any_generator = true;
opts.lang_to_generate |= params_.generators[i].lang;
if (params_.generators[i].bfbs_generator) {
opts.binary_schema_comments = true;
requires_bfbs = true;
}
goto found;
}
}
Error("unknown commandline argument: " + arg, true);
found:;
}
} else {
@ -528,20 +537,42 @@ int FlatCompiler::Compile(int argc, const char **argv) {
parser->file_extension_ = reflection::SchemaExtension();
}
}
std::string filebase =
flatbuffers::StripPath(flatbuffers::StripExtension(filename));
// If one of the generators uses bfbs, serialize the parser and get
// the serialized buffer and length.
const uint8_t *bfbs_buffer = nullptr;
int64_t bfbs_length = 0;
if (requires_bfbs) {
parser->Serialize();
bfbs_buffer = parser->builder_.GetBufferPointer();
bfbs_length = parser->builder_.GetSize();
}
for (size_t i = 0; i < params_.num_generators; ++i) {
if (generator_enabled[i]) {
if (!print_make_rules) {
flatbuffers::EnsureDirExists(output_path);
if ((!params_.generators[i].schema_only ||
(is_schema || is_binary_schema)) &&
!params_.generators[i].generate(*parser.get(), output_path,
filebase)) {
Error(std::string("Unable to generate ") +
params_.generators[i].lang_name + " for " + filebase);
// Prefer bfbs generators if present.
if (params_.generators[i].bfbs_generator) {
const GeneratorStatus status =
params_.generators[i].bfbs_generator->Generate(bfbs_buffer,
bfbs_length);
if (status != OK) {
Error(std::string("Unable to generate ") +
params_.generators[i].lang_name + " for " + filebase +
" using bfbs generator.");
}
} else {
if ((!params_.generators[i].schema_only ||
(is_schema || is_binary_schema)) &&
!params_.generators[i].generate(*parser.get(), output_path,
filebase)) {
Error(std::string("Unable to generate ") +
params_.generators[i].lang_name + " for " + filebase);
}
}
} else {
if (params_.generators[i].make_rule == nullptr) {

View File

@ -14,6 +14,10 @@
* limitations under the License.
*/
#include <memory>
#include "bfbs_gen_lua.h"
#include "flatbuffers/base.h"
#include "flatbuffers/flatc.h"
#include "flatbuffers/util.h"
@ -50,59 +54,69 @@ int main(int argc, const char *argv[]) {
// Prevent Appveyor-CI hangs.
flatbuffers::SetupDefaultCRTReportMode();
const std::string flatbuffers_version(flatbuffers::FLATBUFFERS_VERSION());
std::unique_ptr<flatbuffers::BfbsGenerator> bfbs_gen_lua =
flatbuffers::NewLuaBfbsGenerator(flatbuffers_version);
g_program_name = argv[0];
const flatbuffers::FlatCompiler::Generator generators[] = {
{ flatbuffers::GenerateBinary, "-b", "--binary", "binary", false, nullptr,
flatbuffers::IDLOptions::kBinary,
"Generate wire format binaries for any data definitions",
flatbuffers::BinaryMakeRule },
flatbuffers::BinaryMakeRule, nullptr },
{ flatbuffers::GenerateTextFile, "-t", "--json", "text", false, nullptr,
flatbuffers::IDLOptions::kJson,
"Generate text output for any data definitions",
flatbuffers::TextMakeRule },
flatbuffers::TextMakeRule, nullptr },
{ flatbuffers::GenerateCPP, "-c", "--cpp", "C++", true,
flatbuffers::GenerateCppGRPC, flatbuffers::IDLOptions::kCpp,
"Generate C++ headers for tables/structs", flatbuffers::CPPMakeRule },
"Generate C++ headers for tables/structs", flatbuffers::CPPMakeRule,
nullptr },
{ flatbuffers::GenerateGo, "-g", "--go", "Go", true,
flatbuffers::GenerateGoGRPC, flatbuffers::IDLOptions::kGo,
"Generate Go files for tables/structs", nullptr },
"Generate Go files for tables/structs", nullptr, nullptr },
{ flatbuffers::GenerateJava, "-j", "--java", "Java", true,
flatbuffers::GenerateJavaGRPC, flatbuffers::IDLOptions::kJava,
"Generate Java classes for tables/structs", flatbuffers::JavaMakeRule },
"Generate Java classes for tables/structs", flatbuffers::JavaMakeRule,
nullptr },
{ flatbuffers::GenerateDart, "-d", "--dart", "Dart", true, nullptr,
flatbuffers::IDLOptions::kDart,
"Generate Dart classes for tables/structs", flatbuffers::DartMakeRule },
"Generate Dart classes for tables/structs", flatbuffers::DartMakeRule,
nullptr },
{ flatbuffers::GenerateTS, "-T", "--ts", "TypeScript", true,
flatbuffers::GenerateTSGRPC, flatbuffers::IDLOptions::kTs,
"Generate TypeScript code for tables/structs", flatbuffers::TSMakeRule },
"Generate TypeScript code for tables/structs", flatbuffers::TSMakeRule,
nullptr },
{ flatbuffers::GenerateCSharp, "-n", "--csharp", "C#", true, nullptr,
flatbuffers::IDLOptions::kCSharp,
"Generate C# classes for tables/structs", flatbuffers::CSharpMakeRule },
"Generate C# classes for tables/structs", flatbuffers::CSharpMakeRule,
nullptr },
{ flatbuffers::GeneratePython, "-p", "--python", "Python", true,
flatbuffers::GeneratePythonGRPC, flatbuffers::IDLOptions::kPython,
"Generate Python files for tables/structs", nullptr },
"Generate Python files for tables/structs", nullptr, nullptr },
{ flatbuffers::GenerateLobster, nullptr, "--lobster", "Lobster", true,
nullptr, flatbuffers::IDLOptions::kLobster,
"Generate Lobster files for tables/structs", nullptr },
"Generate Lobster files for tables/structs", nullptr, nullptr },
{ flatbuffers::GenerateLua, "-l", "--lua", "Lua", true, nullptr,
flatbuffers::IDLOptions::kLua, "Generate Lua files for tables/structs",
nullptr },
nullptr, bfbs_gen_lua.get() },
{ flatbuffers::GenerateRust, "-r", "--rust", "Rust", true, nullptr,
flatbuffers::IDLOptions::kRust, "Generate Rust files for tables/structs",
flatbuffers::RustMakeRule },
flatbuffers::RustMakeRule, nullptr },
{ flatbuffers::GeneratePhp, nullptr, "--php", "PHP", true, nullptr,
flatbuffers::IDLOptions::kPhp, "Generate PHP files for tables/structs",
nullptr },
nullptr, nullptr },
{ flatbuffers::GenerateKotlin, nullptr, "--kotlin", "Kotlin", true, nullptr,
flatbuffers::IDLOptions::kKotlin,
"Generate Kotlin classes for tables/structs", nullptr },
"Generate Kotlin classes for tables/structs", nullptr, nullptr },
{ flatbuffers::GenerateJsonSchema, nullptr, "--jsonschema", "JsonSchema",
true, nullptr, flatbuffers::IDLOptions::kJsonSchema,
"Generate Json schema", nullptr },
"Generate Json schema", nullptr, nullptr },
{ flatbuffers::GenerateSwift, nullptr, "--swift", "swift", true,
flatbuffers::GenerateSwiftGRPC, flatbuffers::IDLOptions::kSwift,
"Generate Swift files for tables/structs", nullptr },
"Generate Swift files for tables/structs", nullptr, nullptr },
};
flatbuffers::FlatCompiler::InitParams params;

View File

@ -3669,7 +3669,7 @@ Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder,
IsInteger(value.type.base_type) ? StringToInt(value.constant.c_str()) : 0,
// result may be platform-dependent if underlying is float (not double)
IsFloat(value.type.base_type) ? d : 0.0, deprecated, IsRequired(), key,
attr__, docs__, IsOptional());
attr__, docs__, IsOptional(), static_cast<uint16_t>(padding));
// TODO: value.constant is almost always "0", we could save quite a bit of
// space by sharing it. Same for common values of value.type.
}
@ -3685,6 +3685,7 @@ bool FieldDef::Deserialize(Parser &parser, const reflection::Field *field) {
value.constant = FloatToString(field->default_real(), 16);
}
presence = FieldDef::MakeFieldPresence(field->optional(), field->required());
padding = field->padding();
key = field->key();
if (!DeserializeAttributes(parser, field->attributes())) return false;
// TODO: this should probably be handled by a separate attribute
@ -3828,7 +3829,8 @@ Offset<reflection::Type> Type::Serialize(FlatBufferBuilder *builder) const {
*builder, static_cast<reflection::BaseType>(base_type),
static_cast<reflection::BaseType>(element),
struct_def ? struct_def->index : (enum_def ? enum_def->index : -1),
fixed_length);
fixed_length, static_cast<uint32_t>(SizeOf(base_type)),
static_cast<uint32_t>(SizeOf(element)));
}
bool Type::Deserialize(const Parser &parser, const reflection::Type *type) {

View File

@ -23,7 +23,7 @@
namespace flatbuffers {
int64_t GetAnyValueI(reflection::BaseType type, const uint8_t *data) {
// clang-format off
// clang-format off
#define FLATBUFFERS_GET(T) static_cast<int64_t>(ReadScalar<T>(data))
switch (type) {
case reflection::UType:
@ -121,7 +121,7 @@ std::string GetAnyValueS(reflection::BaseType type, const uint8_t *data,
}
void SetAnyValueI(reflection::BaseType type, uint8_t *data, int64_t val) {
// clang-format off
// clang-format off
#define FLATBUFFERS_SET(T) WriteScalar(data, static_cast<T>(val))
switch (type) {
case reflection::UType:

View File

@ -1,8 +1,6 @@
set buildtype=Release
if "%1"=="-b" set buildtype=%2
..\%buildtype%\flatc.exe --lua -I include_test monster_test.fbs
echo Run with LuaJIT:
luajit.exe luatest.lua
echo Run with Lua 5.3:

View File

@ -17,8 +17,6 @@
pushd "$(dirname $0)" >/dev/null
test_dir="$(pwd)"
${test_dir}/../flatc --lua -I include_test monster_test.fbs
declare -a versions=(luajit lua5.1 lua5.2 lua5.3 lua5.4)
for i in "${versions[@]}"

View File

@ -1,31 +1,43 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.Ability
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local flatbuffers = require('flatbuffers')
local Ability = {} -- the module
local Ability_mt = {} -- the class metatable
local Ability = {}
local mt = {}
function Ability.New()
local o = {}
setmetatable(o, {__index = Ability_mt})
return o
end
function Ability_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Ability_mt:Id()
return self.view:Get(flatbuffers.N.Uint32, self.view.pos + 0)
end
function Ability_mt:Distance()
return self.view:Get(flatbuffers.N.Uint32, self.view.pos + 4)
end
function Ability.CreateAbility(builder, id, distance)
builder:Prep(4, 8)
builder:PrependUint32(distance)
builder:PrependUint32(id)
return builder:Offset()
local o = {}
setmetatable(o, {__index = mt})
return o
end
return Ability -- return the module
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:Id()
return self.view:Get(flatbuffers.N.Uint32, self.view.pos + 0)
end
function mt:Distance()
return self.view:Get(flatbuffers.N.Uint32, self.view.pos + 4)
end
function Ability.CreateAbility(builder, id, distance)
builder:Prep(4, 8)
builder:PrependUint32(distance)
builder:PrependUint32(id)
return builder:Offset()
end
return Ability

View File

@ -1,12 +1,20 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.Any
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local Any = {
NONE = 0,
Monster = 1,
TestSimpleTableWithEnum = 2,
MyGame_Example2_Monster = 3,
NONE = 0,
Monster = 1,
TestSimpleTableWithEnum = 2,
MyGame_Example2_Monster = 3,
}
return Any -- return the module
return Any

View File

@ -1,12 +1,20 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.AnyAmbiguousAliases
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local AnyAmbiguousAliases = {
NONE = 0,
M1 = 1,
M2 = 2,
M3 = 3,
NONE = 0,
M1 = 1,
M2 = 2,
M3 = 3,
}
return AnyAmbiguousAliases -- return the module
return AnyAmbiguousAliases

View File

@ -1,12 +1,20 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.AnyUniqueAliases
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local AnyUniqueAliases = {
NONE = 0,
M = 1,
TS = 2,
M2 = 3,
NONE = 0,
M = 1,
TS = 2,
M2 = 3,
}
return AnyUniqueAliases -- return the module
return AnyUniqueAliases

View File

@ -1,15 +1,23 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.Color
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
-- Composite components of Monster color.
local Color = {
Red = 1,
-- \brief color Green
-- Green is bit_flag with value (1u << 1)
Green = 2,
-- \brief color Blue (1u << 3)
Blue = 8,
Red = 1,
-- \brief color Green
-- Green is bit_flag with value (1u << 1)
Green = 2,
-- \brief color Blue (1u << 3)
Blue = 8,
}
return Color -- return the module
return Color

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,20 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.Race
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local Race = {
None = -1,
Human = 0,
Dwarf = 1,
Elf = 2,
None = -1,
Human = 0,
Dwarf = 1,
Elf = 2,
}
return Race -- return the module
return Race

View File

@ -1,38 +1,48 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.Referrable
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local flatbuffers = require('flatbuffers')
local Referrable = {} -- the module
local Referrable_mt = {} -- the class metatable
local Referrable = {}
local mt = {}
function Referrable.New()
local o = {}
setmetatable(o, {__index = Referrable_mt})
return o
local o = {}
setmetatable(o, {__index = mt})
return o
end
function Referrable.GetRootAsReferrable(buf, offset)
if type(buf) == "string" then
buf = flatbuffers.binaryArray.New(buf)
end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = Referrable.New()
o:Init(buf, n + offset)
return o
end
function Referrable_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Referrable_mt:Id()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint64, o + self.view.pos)
end
return 0
end
function Referrable.Start(builder) builder:StartObject(1) end
function Referrable.AddId(builder, id) builder:PrependUint64Slot(0, id, 0) end
function Referrable.End(builder) return builder:EndObject() end
return Referrable -- return the module
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:Id()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
end
return 0
end
function Referrable.Start(builder)
builder:StartObject(1)
end
function Referrable.AddId(builder, id)
builder:PrependUint64Slot(0, id, 0)
end
function Referrable.End(builder)
return builder:EndObject()
end
return Referrable

View File

@ -1,53 +1,71 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.Stat
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local flatbuffers = require('flatbuffers')
local Stat = {} -- the module
local Stat_mt = {} -- the class metatable
local Stat = {}
local mt = {}
function Stat.New()
local o = {}
setmetatable(o, {__index = Stat_mt})
return o
local o = {}
setmetatable(o, {__index = mt})
return o
end
function Stat.GetRootAsStat(buf, offset)
if type(buf) == "string" then
buf = flatbuffers.binaryArray.New(buf)
end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = Stat.New()
o:Init(buf, n + offset)
return o
end
function Stat_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Stat_mt:Id()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:String(o + self.view.pos)
end
end
function Stat_mt:Val()
local o = self.view:Offset(6)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int64, o + self.view.pos)
end
return 0
end
function Stat_mt:Count()
local o = self.view:Offset(8)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint16, o + self.view.pos)
end
return 0
end
function Stat.Start(builder) builder:StartObject(3) end
function Stat.AddId(builder, id) builder:PrependUOffsetTRelativeSlot(0, id, 0) end
function Stat.AddVal(builder, val) builder:PrependInt64Slot(1, val, 0) end
function Stat.AddCount(builder, count) builder:PrependUint16Slot(2, count, 0) end
function Stat.End(builder) return builder:EndObject() end
return Stat -- return the module
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:Id()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:String(self.view.pos + o)
end
end
function mt:Val()
local o = self.view:Offset(6)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int64, self.view.pos + o)
end
return 0
end
function mt:Count()
local o = self.view:Offset(8)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint16, self.view.pos + o)
end
return 0
end
function Stat.Start(builder)
builder:StartObject(3)
end
function Stat.AddId(builder, id)
builder:PrependUOffsetTRelativeSlot(0, id, 0)
end
function Stat.AddVal(builder, val)
builder:PrependInt64Slot(1, val, 0)
end
function Stat.AddCount(builder, count)
builder:PrependUint16Slot(2, count, 0)
end
function Stat.End(builder)
return builder:EndObject()
end
return Stat

View File

@ -1,45 +1,58 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.StructOfStructs
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local flatbuffers = require('flatbuffers')
local StructOfStructs = {} -- the module
local StructOfStructs_mt = {} -- the class metatable
local StructOfStructs = {}
local mt = {}
function StructOfStructs.New()
local o = {}
setmetatable(o, {__index = StructOfStructs_mt})
return o
end
function StructOfStructs_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function StructOfStructs_mt:A(obj)
obj:Init(self.view.bytes, self.view.pos + 0)
return obj
end
function StructOfStructs_mt:B(obj)
obj:Init(self.view.bytes, self.view.pos + 8)
return obj
end
function StructOfStructs_mt:C(obj)
obj:Init(self.view.bytes, self.view.pos + 12)
return obj
end
function StructOfStructs.CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance)
builder:Prep(4, 20)
builder:Prep(4, 8)
builder:PrependUint32(c_distance)
builder:PrependUint32(c_id)
builder:Prep(2, 4)
builder:Pad(1)
builder:PrependInt8(b_b)
builder:PrependInt16(b_a)
builder:Prep(4, 8)
builder:PrependUint32(a_distance)
builder:PrependUint32(a_id)
return builder:Offset()
local o = {}
setmetatable(o, {__index = mt})
return o
end
return StructOfStructs -- return the module
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:A(obj)
obj:Init(self.view.bytes, self.view.pos + 0)
return obj
end
function mt:B(obj)
obj:Init(self.view.bytes, self.view.pos + 8)
return obj
end
function mt:C(obj)
obj:Init(self.view.bytes, self.view.pos + 12)
return obj
end
function StructOfStructs.CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance)
builder:Prep(4, 20)
builder:Prep(4, 8)
builder:PrependUint32(c_distance)
builder:PrependUint32(c_id)
builder:Prep(2, 4)
builder:Pad(1)
builder:PrependInt8(b_b)
builder:PrependInt16(b_a)
builder:Prep(4, 8)
builder:PrependUint32(a_distance)
builder:PrependUint32(a_id)
return builder:Offset()
end
return StructOfStructs

View File

@ -1,32 +1,44 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.Test
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local flatbuffers = require('flatbuffers')
local Test = {} -- the module
local Test_mt = {} -- the class metatable
local Test = {}
local mt = {}
function Test.New()
local o = {}
setmetatable(o, {__index = Test_mt})
return o
end
function Test_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Test_mt:A()
return self.view:Get(flatbuffers.N.Int16, self.view.pos + 0)
end
function Test_mt:B()
return self.view:Get(flatbuffers.N.Int8, self.view.pos + 2)
end
function Test.CreateTest(builder, a, b)
builder:Prep(2, 4)
builder:Pad(1)
builder:PrependInt8(b)
builder:PrependInt16(a)
return builder:Offset()
local o = {}
setmetatable(o, {__index = mt})
return o
end
return Test -- return the module
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:A()
return self.view:Get(flatbuffers.N.Int16, self.view.pos + 0)
end
function mt:B()
return self.view:Get(flatbuffers.N.Int8, self.view.pos + 2)
end
function Test.CreateTest(builder, a, b)
builder:Prep(2, 4)
builder:Pad(1)
builder:PrependInt8(b)
builder:PrependInt16(a)
return builder:Offset()
end
return Test

View File

@ -1,38 +1,48 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.TestSimpleTableWithEnum
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local flatbuffers = require('flatbuffers')
local TestSimpleTableWithEnum = {} -- the module
local TestSimpleTableWithEnum_mt = {} -- the class metatable
local TestSimpleTableWithEnum = {}
local mt = {}
function TestSimpleTableWithEnum.New()
local o = {}
setmetatable(o, {__index = TestSimpleTableWithEnum_mt})
return o
local o = {}
setmetatable(o, {__index = mt})
return o
end
function TestSimpleTableWithEnum.GetRootAsTestSimpleTableWithEnum(buf, offset)
if type(buf) == "string" then
buf = flatbuffers.binaryArray.New(buf)
end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = TestSimpleTableWithEnum.New()
o:Init(buf, n + offset)
return o
end
function TestSimpleTableWithEnum_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function TestSimpleTableWithEnum_mt:Color()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
end
return 2
end
function TestSimpleTableWithEnum.Start(builder) builder:StartObject(1) end
function TestSimpleTableWithEnum.AddColor(builder, color) builder:PrependUint8Slot(0, color, 2) end
function TestSimpleTableWithEnum.End(builder) return builder:EndObject() end
return TestSimpleTableWithEnum -- return the module
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:Color()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o)
end
return 2
end
function TestSimpleTableWithEnum.Start(builder)
builder:StartObject(1)
end
function TestSimpleTableWithEnum.AddColor(builder, color)
builder:PrependUint8Slot(0, color, 2)
end
function TestSimpleTableWithEnum.End(builder)
return builder:EndObject()
end
return TestSimpleTableWithEnum

View File

@ -1,147 +1,210 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.TypeAliases
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local flatbuffers = require('flatbuffers')
local TypeAliases = {} -- the module
local TypeAliases_mt = {} -- the class metatable
local TypeAliases = {}
local mt = {}
function TypeAliases.New()
local o = {}
setmetatable(o, {__index = TypeAliases_mt})
return o
local o = {}
setmetatable(o, {__index = mt})
return o
end
function TypeAliases.GetRootAsTypeAliases(buf, offset)
if type(buf) == "string" then
buf = flatbuffers.binaryArray.New(buf)
end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = TypeAliases.New()
o:Init(buf, n + offset)
return o
end
function TypeAliases_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function TypeAliases_mt:I8()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int8, o + self.view.pos)
end
return 0
end
function TypeAliases_mt:U8()
local o = self.view:Offset(6)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos)
end
return 0
end
function TypeAliases_mt:I16()
local o = self.view:Offset(8)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int16, o + self.view.pos)
end
return 0
end
function TypeAliases_mt:U16()
local o = self.view:Offset(10)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint16, o + self.view.pos)
end
return 0
end
function TypeAliases_mt:I32()
local o = self.view:Offset(12)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int32, o + self.view.pos)
end
return 0
end
function TypeAliases_mt:U32()
local o = self.view:Offset(14)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint32, o + self.view.pos)
end
return 0
end
function TypeAliases_mt:I64()
local o = self.view:Offset(16)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int64, o + self.view.pos)
end
return 0
end
function TypeAliases_mt:U64()
local o = self.view:Offset(18)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint64, o + self.view.pos)
end
return 0
end
function TypeAliases_mt:F32()
local o = self.view:Offset(20)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Float32, o + self.view.pos)
end
return 0.0
end
function TypeAliases_mt:F64()
local o = self.view:Offset(22)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Float64, o + self.view.pos)
end
return 0.0
end
function TypeAliases_mt:V8(j)
local o = self.view:Offset(24)
if o ~= 0 then
local a = self.view:Vector(o)
return self.view:Get(flatbuffers.N.Int8, a + ((j-1) * 1))
end
return 0
end
function TypeAliases_mt:V8AsString(start, stop)
return self.view:VectorAsString(24, start, stop)
end
function TypeAliases_mt:V8Length()
local o = self.view:Offset(24)
if o ~= 0 then
return self.view:VectorLen(o)
end
return 0
end
function TypeAliases_mt:Vf64(j)
local o = self.view:Offset(26)
if o ~= 0 then
local a = self.view:Vector(o)
return self.view:Get(flatbuffers.N.Float64, a + ((j-1) * 8))
end
return 0
end
function TypeAliases_mt:Vf64Length()
local o = self.view:Offset(26)
if o ~= 0 then
return self.view:VectorLen(o)
end
return 0
end
function TypeAliases.Start(builder) builder:StartObject(12) end
function TypeAliases.AddI8(builder, i8) builder:PrependInt8Slot(0, i8, 0) end
function TypeAliases.AddU8(builder, u8) builder:PrependUint8Slot(1, u8, 0) end
function TypeAliases.AddI16(builder, i16) builder:PrependInt16Slot(2, i16, 0) end
function TypeAliases.AddU16(builder, u16) builder:PrependUint16Slot(3, u16, 0) end
function TypeAliases.AddI32(builder, i32) builder:PrependInt32Slot(4, i32, 0) end
function TypeAliases.AddU32(builder, u32) builder:PrependUint32Slot(5, u32, 0) end
function TypeAliases.AddI64(builder, i64) builder:PrependInt64Slot(6, i64, 0) end
function TypeAliases.AddU64(builder, u64) builder:PrependUint64Slot(7, u64, 0) end
function TypeAliases.AddF32(builder, f32) builder:PrependFloat32Slot(8, f32, 0.0) end
function TypeAliases.AddF64(builder, f64) builder:PrependFloat64Slot(9, f64, 0.0) end
function TypeAliases.AddV8(builder, v8) builder:PrependUOffsetTRelativeSlot(10, v8, 0) end
function TypeAliases.StartV8Vector(builder, numElems) return builder:StartVector(1, numElems, 1) end
function TypeAliases.AddVf64(builder, vf64) builder:PrependUOffsetTRelativeSlot(11, vf64, 0) end
function TypeAliases.StartVf64Vector(builder, numElems) return builder:StartVector(8, numElems, 8) end
function TypeAliases.End(builder) return builder:EndObject() end
return TypeAliases -- return the module
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:I8()
local o = self.view:Offset(4)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int8, self.view.pos + o)
end
return 0
end
function mt:U8()
local o = self.view:Offset(6)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o)
end
return 0
end
function mt:I16()
local o = self.view:Offset(8)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int16, self.view.pos + o)
end
return 0
end
function mt:U16()
local o = self.view:Offset(10)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint16, self.view.pos + o)
end
return 0
end
function mt:I32()
local o = self.view:Offset(12)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int32, self.view.pos + o)
end
return 0
end
function mt:U32()
local o = self.view:Offset(14)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint32, self.view.pos + o)
end
return 0
end
function mt:I64()
local o = self.view:Offset(16)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Int64, self.view.pos + o)
end
return 0
end
function mt:U64()
local o = self.view:Offset(18)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o)
end
return 0
end
function mt:F32()
local o = self.view:Offset(20)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Float32, self.view.pos + o)
end
return 0.0
end
function mt:F64()
local o = self.view:Offset(22)
if o ~= 0 then
return self.view:Get(flatbuffers.N.Float64, self.view.pos + o)
end
return 0.0
end
function mt:V8(j)
local o = self.view:Offset(24)
if o ~= 0 then
local a = self.view:Vector(o)
return self.view:Get(flatbuffers.N.Int8, a + ((j-1) * 1))
end
return 0
end
function mt:V8AsString(start, stop)
return self.view:VectorAsString(24, start, stop)
end
function mt:V8Length()
local o = self.view:Offset(24)
if o ~= 0 then
return self.view:VectorLen(o)
end
return 0
end
function mt:Vf64(j)
local o = self.view:Offset(26)
if o ~= 0 then
local a = self.view:Vector(o)
return self.view:Get(flatbuffers.N.Float64, a + ((j-1) * 8))
end
return 0
end
function mt:Vf64Length()
local o = self.view:Offset(26)
if o ~= 0 then
return self.view:VectorLen(o)
end
return 0
end
function TypeAliases.Start(builder)
builder:StartObject(12)
end
function TypeAliases.AddI8(builder, i8)
builder:PrependInt8Slot(0, i8, 0)
end
function TypeAliases.AddU8(builder, u8)
builder:PrependUint8Slot(1, u8, 0)
end
function TypeAliases.AddI16(builder, i16)
builder:PrependInt16Slot(2, i16, 0)
end
function TypeAliases.AddU16(builder, u16)
builder:PrependUint16Slot(3, u16, 0)
end
function TypeAliases.AddI32(builder, i32)
builder:PrependInt32Slot(4, i32, 0)
end
function TypeAliases.AddU32(builder, u32)
builder:PrependUint32Slot(5, u32, 0)
end
function TypeAliases.AddI64(builder, i64)
builder:PrependInt64Slot(6, i64, 0)
end
function TypeAliases.AddU64(builder, u64)
builder:PrependUint64Slot(7, u64, 0)
end
function TypeAliases.AddF32(builder, f32)
builder:PrependFloat32Slot(8, f32, 0.0)
end
function TypeAliases.AddF64(builder, f64)
builder:PrependFloat64Slot(9, f64, 0.0)
end
function TypeAliases.AddV8(builder, v8)
builder:PrependUOffsetTRelativeSlot(10, v8, 0)
end
function TypeAliases.StartV8Vector(builder, numElems)
return builder:StartVector(1, numElems, 1)
end
function TypeAliases.AddVf64(builder, vf64)
builder:PrependUOffsetTRelativeSlot(11, vf64, 0)
end
function TypeAliases.StartVf64Vector(builder, numElems)
return builder:StartVector(8, numElems, 8)
end
function TypeAliases.End(builder)
return builder:EndObject()
end
return TypeAliases

View File

@ -1,54 +1,70 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example.Vec3
-- namespace: Example
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local flatbuffers = require('flatbuffers')
local Vec3 = {} -- the module
local Vec3_mt = {} -- the class metatable
local Vec3 = {}
local mt = {}
function Vec3.New()
local o = {}
setmetatable(o, {__index = Vec3_mt})
return o
end
function Vec3_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Vec3_mt:X()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 0)
end
function Vec3_mt:Y()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 4)
end
function Vec3_mt:Z()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 8)
end
function Vec3_mt:Test1()
return self.view:Get(flatbuffers.N.Float64, self.view.pos + 16)
end
function Vec3_mt:Test2()
return self.view:Get(flatbuffers.N.Uint8, self.view.pos + 24)
end
function Vec3_mt:Test3(obj)
obj:Init(self.view.bytes, self.view.pos + 26)
return obj
end
function Vec3.CreateVec3(builder, x, y, z, test1, test2, test3_a, test3_b)
builder:Prep(8, 32)
builder:Pad(2)
builder:Prep(2, 4)
builder:Pad(1)
builder:PrependInt8(test3_b)
builder:PrependInt16(test3_a)
builder:Pad(1)
builder:PrependUint8(test2)
builder:PrependFloat64(test1)
builder:Pad(4)
builder:PrependFloat32(z)
builder:PrependFloat32(y)
builder:PrependFloat32(x)
return builder:Offset()
local o = {}
setmetatable(o, {__index = mt})
return o
end
return Vec3 -- return the module
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:X()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 0)
end
function mt:Y()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 4)
end
function mt:Z()
return self.view:Get(flatbuffers.N.Float32, self.view.pos + 8)
end
function mt:Test1()
return self.view:Get(flatbuffers.N.Float64, self.view.pos + 16)
end
function mt:Test2()
return self.view:Get(flatbuffers.N.Uint8, self.view.pos + 24)
end
function mt:Test3(obj)
obj:Init(self.view.bytes, self.view.pos + 26)
return obj
end
function Vec3.CreateVec3(builder, x, y, z, test1, test2, test3_a, test3_b)
builder:Prep(8, 32)
builder:Pad(2)
builder:Prep(2, 4)
builder:Pad(1)
builder:PrependInt8(test3_b)
builder:PrependInt16(test3_a)
builder:Pad(1)
builder:PrependUint8(test2)
builder:PrependFloat64(test1)
builder:Pad(4)
builder:PrependFloat32(z)
builder:PrependFloat32(y)
builder:PrependFloat32(x)
return builder:Offset()
end
return Vec3

View File

@ -1,30 +1,36 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.Example2.Monster
-- namespace: Example2
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local flatbuffers = require('flatbuffers')
local Monster = {} -- the module
local Monster_mt = {} -- the class metatable
local Monster = {}
local mt = {}
function Monster.New()
local o = {}
setmetatable(o, {__index = Monster_mt})
return o
local o = {}
setmetatable(o, {__index = mt})
return o
end
function Monster.GetRootAsMonster(buf, offset)
if type(buf) == "string" then
buf = flatbuffers.binaryArray.New(buf)
end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = Monster.New()
o:Init(buf, n + offset)
return o
end
function Monster_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Monster.Start(builder) builder:StartObject(0) end
function Monster.End(builder) return builder:EndObject() end
return Monster -- return the module
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function Monster.Start(builder)
builder:StartObject(0)
end
function Monster.End(builder)
return builder:EndObject()
end
return Monster

View File

@ -1,30 +1,36 @@
-- automatically generated by the FlatBuffers compiler, do not modify
--[[ MyGame.InParentNamespace
-- namespace: MyGame
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //monster_test.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local flatbuffers = require('flatbuffers')
local InParentNamespace = {} -- the module
local InParentNamespace_mt = {} -- the class metatable
local InParentNamespace = {}
local mt = {}
function InParentNamespace.New()
local o = {}
setmetatable(o, {__index = InParentNamespace_mt})
return o
local o = {}
setmetatable(o, {__index = mt})
return o
end
function InParentNamespace.GetRootAsInParentNamespace(buf, offset)
if type(buf) == "string" then
buf = flatbuffers.binaryArray.New(buf)
end
local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)
local o = InParentNamespace.New()
o:Init(buf, n + offset)
return o
end
function InParentNamespace_mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function InParentNamespace.Start(builder) builder:StartObject(0) end
function InParentNamespace.End(builder) return builder:EndObject() end
return InParentNamespace -- return the module
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function InParentNamespace.Start(builder)
builder:StartObject(0)
end
function InParentNamespace.End(builder)
return builder:EndObject()
end
return InParentNamespace

View File

@ -0,0 +1,17 @@
--[[ MyGame.OtherNameSpace.FromInclude
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //include_test/sub/include_test2.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local FromInclude = {
IncludeVal = 0,
}
return FromInclude

View File

@ -0,0 +1,51 @@
--[[ MyGame.OtherNameSpace.TableB
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //include_test/sub/include_test2.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local __TableA = require('TableA')
local flatbuffers = require('flatbuffers')
local TableB = {}
local mt = {}
function TableB.New()
local o = {}
setmetatable(o, {__index = mt})
return o
end
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:A()
local o = self.view:Offset(4)
if o ~= 0 then
local x = self.view:Indirect(self.view.pos + o)
local obj = __TableA.New()
obj:Init(self.view.bytes, x)
return obj
end
end
function TableB.Start(builder)
builder:StartObject(1)
end
function TableB.AddA(builder, a)
builder:PrependStructSlot(0, a, 0)
end
function TableB.End(builder)
return builder:EndObject()
end
return TableB

View File

@ -0,0 +1,38 @@
--[[ MyGame.OtherNameSpace.Unused
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //include_test/sub/include_test2.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local flatbuffers = require('flatbuffers')
local Unused = {}
local mt = {}
function Unused.New()
local o = {}
setmetatable(o, {__index = mt})
return o
end
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:A()
return self.view:Get(flatbuffers.N.Int32, self.view.pos + 0)
end
function Unused.CreateUnused(builder, a)
builder:Prep(4, 4)
builder:PrependInt32(a)
return builder:Offset()
end
return Unused

51
tests/TableA.lua Normal file
View File

@ -0,0 +1,51 @@
--[[ TableA
Automatically generated by the FlatBuffers compiler, do not modify.
Or modify. I'm a message, not a cop.
flatc version: 2.0.0
Declared by : //include_test/include_test1.fbs
Rooting type : MyGame.Example.Monster (//monster_test.fbs)
--]]
local __MyGame_OtherNameSpace_TableB = require('MyGame.OtherNameSpace.TableB')
local flatbuffers = require('flatbuffers')
local TableA = {}
local mt = {}
function TableA.New()
local o = {}
setmetatable(o, {__index = mt})
return o
end
function mt:Init(buf, pos)
self.view = flatbuffers.view.New(buf, pos)
end
function mt:B()
local o = self.view:Offset(4)
if o ~= 0 then
local x = self.view:Indirect(self.view.pos + o)
local obj = __MyGame_OtherNameSpace_TableB.New()
obj:Init(self.view.bytes, x)
return obj
end
end
function TableA.Start(builder)
builder:StartObject(1)
end
function TableA.AddB(builder, b)
builder:PrependStructSlot(0, b, 0)
end
function TableA.End(builder)
return builder:EndObject()
end
return TableA

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff