diff --git a/CMakeLists.txt b/CMakeLists.txt index c8ac1e63d..68bfb601f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,8 +12,7 @@ set(FlatBuffers_Compiler_SRCS include/flatbuffers/util.h src/idl_parser.cpp src/idl_gen_cpp.cpp - src/idl_gen_java.cpp - src/idl_gen_csharp.cpp + src/idl_gen_general.cpp src/idl_gen_go.cpp src/idl_gen_text.cpp src/flatc.cpp diff --git a/build/VS2010/flatc.vcxproj b/build/VS2010/flatc.vcxproj index 1e2b44abd..2f9c33ffc 100755 --- a/build/VS2010/flatc.vcxproj +++ b/build/VS2010/flatc.vcxproj @@ -266,13 +266,12 @@ - + Level4 - diff --git a/build/VS2010/flatc.vcxproj.user b/build/VS2010/flatc.vcxproj.user index f86bf4820..26953575f 100755 --- a/build/VS2010/flatc.vcxproj.user +++ b/build/VS2010/flatc.vcxproj.user @@ -11,7 +11,7 @@ -j -c -n -g -b -t monster_test.fbs monsterdata_test.golden - -j -c -g -b -t monster_test.fbs monsterdata_test.golden + -j -c -g -n -b -t monster_test.fbs monsterdata_test.golden ..\..\tests diff --git a/include/flatbuffers/idl.h b/include/flatbuffers/idl.h index 65ebf8376..4aa9a256c 100644 --- a/include/flatbuffers/idl.h +++ b/include/flatbuffers/idl.h @@ -32,31 +32,38 @@ namespace flatbuffers { // Additionally, Parser::ParseType assumes bool..string is a contiguous range // of type tokens. #define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \ - TD(NONE, "", uint8_t, byte, byte) \ - TD(UTYPE, "", uint8_t, byte, byte) /* begin scalars, ints */ \ - TD(BOOL, "bool", uint8_t, byte, byte) \ - TD(CHAR, "byte", int8_t, byte, int8) \ - TD(UCHAR, "ubyte", uint8_t, byte, byte) \ - TD(SHORT, "short", int16_t, short, int16) \ - TD(USHORT, "ushort", uint16_t, short, uint16) \ - TD(INT, "int", int32_t, int, int32) \ - TD(UINT, "uint", uint32_t, int, uint32) \ - TD(LONG, "long", int64_t, long, int64) \ - TD(ULONG, "ulong", uint64_t, long, uint64) /* end ints */ \ - TD(FLOAT, "float", float, float, float32) /* begin floats */ \ - TD(DOUBLE, "double", double, double, float64) /* end floats, scalars */ + TD(NONE, "", uint8_t, byte, byte, byte) \ + TD(UTYPE, "", uint8_t, byte, byte, byte) /* begin scalar/int */ \ + TD(BOOL, "bool", uint8_t, byte, byte, byte) \ + TD(CHAR, "byte", int8_t, byte, int8, sbyte) \ + TD(UCHAR, "ubyte", uint8_t, byte, byte, byte) \ + TD(SHORT, "short", int16_t, short, int16, short) \ + TD(USHORT, "ushort", uint16_t, short, uint16, ushort) \ + TD(INT, "int", int32_t, int, int32, int) \ + TD(UINT, "uint", uint32_t, int, uint32, uint) \ + TD(LONG, "long", int64_t, long, int64, long) \ + TD(ULONG, "ulong", uint64_t, long, uint64, ulong) /* end int */ \ + TD(FLOAT, "float", float, float, float32, float) /* begin float */ \ + TD(DOUBLE, "double", double, double, float64, double) /* end float/scalar */ #define FLATBUFFERS_GEN_TYPES_POINTER(TD) \ - TD(STRING, "string", Offset, int, int) \ - TD(VECTOR, "", Offset, int, int) \ - TD(STRUCT, "", Offset, int, int) \ - TD(UNION, "", Offset, int, int) + TD(STRING, "string", Offset, int, int, int) \ + TD(VECTOR, "", Offset, int, int, int) \ + TD(STRUCT, "", Offset, int, int, int) \ + TD(UNION, "", Offset, int, int, int) +// The fields are: +// - enum +// - FlatBuffers schema type. +// - C++ type. +// - Java type. +// - Go type. +// - C# / .Net type. // using these macros, we can now write code dealing with types just once, e.g. /* switch (type) { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \ + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ case BASE_TYPE_ ## ENUM: \ // do something specific to CTYPE here FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) @@ -73,12 +80,13 @@ switch (type) { __extension__ // Stop GCC complaining about trailing comma with -Wpendantic. #endif enum BaseType { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) BASE_TYPE_ ## ENUM, + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ + BASE_TYPE_ ## ENUM, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD }; -#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \ +#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ static_assert(sizeof(CTYPE) <= sizeof(largest_scalar_t), \ "define largest_scalar_t as " #CTYPE); FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) @@ -327,22 +335,11 @@ class Parser { std::map included_files_; }; -// Utility functions for generators: +// Utility functions for multiple generators: -// Convert an underscore_based_indentifier in to camelCase. -// Also uppercases the first character if first is true. -inline std::string MakeCamel(const std::string &in, bool first = true) { - std::string s; - for (size_t i = 0; i < in.length(); i++) { - if (!i && first) - s += static_cast(toupper(in[0])); - else if (in[i] == '_' && i + 1 < in.length()) - s += static_cast(toupper(in[++i])); - else - s += in[i]; - } - return s; -} +extern std::string MakeCamel(const std::string &in, bool first = true); +extern void GenComment(const std::string &dc, std::string *code_ptr, + const char *prefix = ""); // Container of options that may apply to any of the source/text generators. struct GeneratorOptions { @@ -351,8 +348,14 @@ struct GeneratorOptions { bool output_enum_identifiers; bool prefixed_enums; + // Possible options for the more general generator below. + enum Language { kJava, kCSharp, kMAX }; + + Language lang; + GeneratorOptions() : strict_json(false), indent_step(2), - output_enum_identifiers(true), prefixed_enums(true) {} + output_enum_identifiers(true), prefixed_enums(true), + lang(GeneratorOptions::kJava) {} }; // Generate text (JSON) from a given FlatBuffer, and a given Parser @@ -397,6 +400,12 @@ extern bool GenerateCSharp(const Parser &parser, const std::string &file_name, const GeneratorOptions &opts); +// Generate Java/C#/.. files from the definitions in the Parser object. +// See idl_gen_general.cpp. +extern bool GenerateGeneral(const Parser &parser, + const std::string &path, + const std::string &file_name, + const GeneratorOptions &opts); } // namespace flatbuffers diff --git a/net/FlatBuffers/ByteBuffer.cs b/net/FlatBuffers/ByteBuffer.cs index a1c29ab42..c406faf35 100644 --- a/net/FlatBuffers/ByteBuffer.cs +++ b/net/FlatBuffers/ByteBuffer.cs @@ -25,6 +25,7 @@ namespace FlatBuffers public class ByteBuffer { private readonly byte[] _buffer; + private int _pos; // Must track start of the buffer. public int Length { get { return _buffer.Length; } } @@ -33,8 +34,11 @@ namespace FlatBuffers public ByteBuffer(byte[] buffer) { _buffer = buffer; + _pos = 0; } + public int position() { return _pos; } + protected void WriteLittleEndian(int offset, byte[] data) { if (!BitConverter.IsLittleEndian) @@ -42,6 +46,7 @@ namespace FlatBuffers data = data.Reverse().ToArray(); } Buffer.BlockCopy(data, 0, _buffer, offset, data.Length); + _pos = offset; } protected byte[] ReadLittleEndian(int offset, int count) @@ -62,10 +67,18 @@ namespace FlatBuffers throw new ArgumentOutOfRangeException(); } + public void PutSbyte(int offset, sbyte value) + { + AssertOffsetAndLength(offset, sizeof(sbyte)); + _buffer[offset] = (byte)value; + _pos = offset; + } + public void PutByte(int offset, byte value) { AssertOffsetAndLength(offset, sizeof(byte)); _buffer[offset] = value; + _pos = offset; } public void PutShort(int offset, short value) @@ -74,18 +87,36 @@ namespace FlatBuffers WriteLittleEndian(offset, BitConverter.GetBytes(value)); } + public void PutUshort(int offset, ushort value) + { + AssertOffsetAndLength(offset, sizeof(ushort)); + WriteLittleEndian(offset, BitConverter.GetBytes(value)); + } + public void PutInt(int offset, int value) { AssertOffsetAndLength(offset, sizeof(int)); WriteLittleEndian(offset, BitConverter.GetBytes(value)); } + public void PutUint(int offset, uint value) + { + AssertOffsetAndLength(offset, sizeof(uint)); + WriteLittleEndian(offset, BitConverter.GetBytes(value)); + } + public void PutLong(int offset, long value) { AssertOffsetAndLength(offset, sizeof(long)); WriteLittleEndian(offset, BitConverter.GetBytes(value)); } + public void PutUlong(int offset, ulong value) + { + AssertOffsetAndLength(offset, sizeof(ulong)); + WriteLittleEndian(offset, BitConverter.GetBytes(value)); + } + public void PutFloat(int offset, float value) { AssertOffsetAndLength(offset, sizeof(float)); @@ -98,6 +129,12 @@ namespace FlatBuffers WriteLittleEndian(offset, BitConverter.GetBytes(value)); } + public sbyte GetSbyte(int index) + { + AssertOffsetAndLength(index, sizeof(sbyte)); + return (sbyte)_buffer[index]; + } + public byte Get(int index) { AssertOffsetAndLength(index, sizeof(byte)); @@ -111,6 +148,13 @@ namespace FlatBuffers return value; } + public ushort GetUshort(int index) + { + var tmp = ReadLittleEndian(index, sizeof(ushort)); + var value = BitConverter.ToUInt16(tmp, 0); + return value; + } + public int GetInt(int index) { var tmp = ReadLittleEndian(index, sizeof(int)); @@ -118,6 +162,13 @@ namespace FlatBuffers return value; } + public uint GetUint(int index) + { + var tmp = ReadLittleEndian(index, sizeof(uint)); + var value = BitConverter.ToUInt32(tmp, 0); + return value; + } + public long GetLong(int index) { var tmp = ReadLittleEndian(index, sizeof(long)); @@ -125,6 +176,13 @@ namespace FlatBuffers return value; } + public ulong GetUlong(int index) + { + var tmp = ReadLittleEndian(index, sizeof(ulong)); + var value = BitConverter.ToUInt64(tmp, 0); + return value; + } + public float GetFloat(int index) { var tmp = ReadLittleEndian(index, sizeof(float)); diff --git a/net/FlatBuffers/FlatBufferBuilder.cs b/net/FlatBuffers/FlatBufferBuilder.cs index f48e7a477..f4a6ca427 100644 --- a/net/FlatBuffers/FlatBufferBuilder.cs +++ b/net/FlatBuffers/FlatBufferBuilder.cs @@ -50,7 +50,7 @@ namespace FlatBuffers } - public int Offset { get { return _bb.Length - _space; } } + public int Offset() { return _bb.Length - _space; } public void Pad(int size) { @@ -105,6 +105,11 @@ namespace FlatBuffers Pad(alignSize); } + public void PutSbyte(sbyte x) + { + _bb.PutSbyte(_space -= sizeof(sbyte), x); + } + public void PutByte(byte x) { _bb.PutByte(_space -= sizeof(byte), x); @@ -115,16 +120,31 @@ namespace FlatBuffers _bb.PutShort(_space -= sizeof(short), x); } - public void PutInt32(int x) + public void PutUshort(ushort x) + { + _bb.PutUshort(_space -= sizeof(ushort), x); + } + + public void PutInt(int x) { _bb.PutInt(_space -= sizeof(int), x); } - public void PutInt64(long x) + public void PutUint(uint x) + { + _bb.PutUint(_space -= sizeof(uint), x); + } + + public void PutLong(long x) { _bb.PutLong(_space -= sizeof(long), x); } + public void PutUlong(ulong x) + { + _bb.PutUlong(_space -= sizeof(ulong), x); + } + public void PutFloat(float x) { _bb.PutFloat(_space -= sizeof(float), x); @@ -137,10 +157,14 @@ namespace FlatBuffers // Adds a scalar to the buffer, properly aligned, and the buffer grown // if needed. + public void AddSbyte(sbyte x) { Prep(sizeof(sbyte), 0); PutSbyte(x); } public void AddByte(byte x) { Prep(sizeof(byte), 0); PutByte(x); } public void AddShort(short x) { Prep(sizeof(short), 0); PutShort(x); } - public void AddInt(int x) { Prep(sizeof(int), 0); PutInt32(x); } - public void AddLong(long x) { Prep(sizeof(long), 0); PutInt64(x); } + public void AddUshort(ushort x) { Prep(sizeof(ushort), 0); PutUshort(x); } + public void AddInt(int x) { Prep(sizeof(int), 0); PutInt(x); } + public void AddUint(uint x) { Prep(sizeof(uint), 0); PutUint(x); } + public void AddLong(long x) { Prep(sizeof(long), 0); PutLong(x); } + public void AddULong(ulong x) { Prep(sizeof(ulong), 0); PutUlong(x); } public void AddFloat(float x) { Prep(sizeof(float), 0); PutFloat(x); } public void AddDouble(double x) { Prep(sizeof(double), 0); PutDouble(x); } @@ -151,11 +175,11 @@ namespace FlatBuffers public void AddOffset(int off) { Prep(sizeof(int), 0); // Ensure alignment is already done. - if (off > Offset) + if (off > Offset()) throw new ArgumentException(); - off = Offset - off + sizeof(int); - PutInt32(off); + off = Offset() - off + sizeof(int); + PutInt(off); } public void StartVector(int elemSize, int count, int alignment) @@ -168,8 +192,8 @@ namespace FlatBuffers public int EndVector() { - PutInt32(_vectorNumElems); - return Offset; + PutInt(_vectorNumElems); + return Offset(); } public void Nested(int obj) @@ -177,7 +201,7 @@ namespace FlatBuffers // Structs are always stored inline, so need to be created right // where they are used. You'll get this assert if you created it // elsewhere. - if (obj != Offset) + if (obj != Offset()) throw new Exception( "FlatBuffers: struct must be serialized inline."); } @@ -195,7 +219,7 @@ namespace FlatBuffers { NotNested(); _vtable = new int[numfields]; - _objectStart = Offset; + _objectStart = Offset(); } @@ -203,14 +227,18 @@ namespace FlatBuffers // buffer. public void Slot(int voffset) { - _vtable[voffset] = Offset; + _vtable[voffset] = Offset(); } // Add a scalar to a table at `o` into its vtable, with value `x` and default `d` - public void AddByte(int o, byte x, int d) { if (x != d) { AddByte(x); Slot(o); } } + public void AddSbyte(int o, sbyte x, sbyte d) { if (x != d) { AddSbyte(x); Slot(o); } } + public void AddByte(int o, byte x, byte d) { if (x != d) { AddByte(x); Slot(o); } } public void AddShort(int o, short x, int d) { if (x != d) { AddShort(x); Slot(o); } } + public void AddUshort(int o, ushort x, ushort d) { if (x != d) { AddUshort(x); Slot(o); } } public void AddInt(int o, int x, int d) { if (x != d) { AddInt(x); Slot(o); } } + public void AddUint(int o, uint x, uint d) { if (x != d) { AddUint(x); Slot(o); } } public void AddLong(int o, long x, long d) { if (x != d) { AddLong(x); Slot(o); } } + public void AddULong(int o, ulong x, ulong d) { if (x != d) { AddULong(x); Slot(o); } } public void AddFloat(int o, float x, double d) { if (x != d) { AddFloat(x); Slot(o); } } public void AddDouble(int o, double x, double d) { if (x != d) { AddDouble(x); Slot(o); } } public void AddOffset(int o, int x, int d) { if (x != d) { AddOffset(x); Slot(o); } } @@ -245,7 +273,7 @@ namespace FlatBuffers "Flatbuffers: calling endObject without a startObject"); AddInt((int)0); - var vtableloc = Offset; + var vtableloc = Offset(); // Write out the current vtable. for (int i = _vtable.Length - 1; i >= 0 ; i--) { // Offset relative to the start of the table. @@ -298,9 +326,9 @@ namespace FlatBuffers _vtables = newvtables; }; - _vtables[_numVtables++] = Offset; + _vtables[_numVtables++] = Offset(); // Point table to current vtable. - _bb.PutInt(_bb.Length - vtableloc, Offset - vtableloc); + _bb.PutInt(_bb.Length - vtableloc, Offset() - vtableloc); } _vtable = null; @@ -313,17 +341,13 @@ namespace FlatBuffers AddOffset(rootTable); } - public ByteBuffer Data { get { return _bb; }} - - // The FlatBuffer data doesn't start at offset 0 in the ByteBuffer: - public int DataStart { get { return _space; } } - + public ByteBuffer DataBuffer() { return _bb; } // Utility function for copying a byte array that starts at 0. public byte[] SizedByteArray() { var newArray = new byte[_bb.Data.Length]; - Buffer.BlockCopy(_bb.Data, DataStart, newArray, 0, + Buffer.BlockCopy(_bb.Data, _bb.position(), newArray, 0, _bb.Data.Length); return newArray; } diff --git a/net/FlatBuffers/FlatBuffers.1.0.0.nuspec b/net/FlatBuffers/FlatBuffers.1.0.0.nuspec deleted file mode 100644 index 93ddf938b..000000000 --- a/net/FlatBuffers/FlatBuffers.1.0.0.nuspec +++ /dev/null @@ -1,12 +0,0 @@ - - - - FlatBuffers - 1.0.0-alpha00003 - Google Inc - A .NET port of Google Inc's FlatBuffers project. - en-US - https://github.com/evolutional/flatbuffers - http://www.apache.org/licenses/LICENSE-2.0 - - \ No newline at end of file diff --git a/net/FlatBuffers/Table.cs b/net/FlatBuffers/Table.cs index f09cb05e0..f13311130 100644 --- a/net/FlatBuffers/Table.cs +++ b/net/FlatBuffers/Table.cs @@ -74,14 +74,14 @@ namespace FlatBuffers return t; } - protected static bool __has_identifier(ByteBuffer bb, int offset, string ident) + protected static bool __has_identifier(ByteBuffer bb, string ident) { if (ident.Length != FlatBufferConstants.FileIdentifierLength) throw new ArgumentException("FlatBuffers: file identifier must be length " + FlatBufferConstants.FileIdentifierLength, "ident"); for (var i = 0; i < FlatBufferConstants.FileIdentifierLength; i++) { - if (ident[i] != (char)bb.Get(offset + sizeof(int) + i)) return false; + if (ident[i] != (char)bb.Get(bb.position() + sizeof(int) + i)) return false; } return true; diff --git a/src/flatc.cpp b/src/flatc.cpp index 88c59d7b6..425f78c0a 100755 --- a/src/flatc.cpp +++ b/src/flatc.cpp @@ -62,21 +62,28 @@ struct Generator { const flatbuffers::GeneratorOptions &opts); const char *extension; const char *name; + flatbuffers::GeneratorOptions::Language lang; const char *help; }; const Generator generators[] = { { flatbuffers::GenerateBinary, "b", "binary", + flatbuffers::GeneratorOptions::kMAX, "Generate wire format binaries for any data definitions" }, { flatbuffers::GenerateTextFile, "t", "text", + flatbuffers::GeneratorOptions::kMAX, "Generate text output for any data definitions" }, { flatbuffers::GenerateCPP, "c", "C++", + flatbuffers::GeneratorOptions::kMAX, "Generate C++ headers for tables/structs" }, { flatbuffers::GenerateGo, "g", "Go", + flatbuffers::GeneratorOptions::kMAX, "Generate Go files for tables/structs" }, - { flatbuffers::GenerateJava, "j", "Java", + { flatbuffers::GenerateGeneral, "j", "Java", + flatbuffers::GeneratorOptions::kJava, "Generate Java classes for tables/structs" }, - { flatbuffers::GenerateCSharp, "n", "C#", + { flatbuffers::GenerateGeneral, "n", "C#", + flatbuffers::GeneratorOptions::kCSharp, "Generate C# classes for tables/structs" } }; @@ -194,6 +201,7 @@ int main(int argc, const char *argv[]) { for (size_t i = 0; i < num_generators; ++i) { if (generator_enabled[i]) { flatbuffers::EnsureDirExists(output_path); + opts.lang = generators[i].lang; if (!generators[i].generate(parser, output_path, filebase, opts)) { Error((std::string("Unable to generate ") + generators[i].name + diff --git a/src/idl_gen_cpp.cpp b/src/idl_gen_cpp.cpp index 4aa731e32..e7497b784 100644 --- a/src/idl_gen_cpp.cpp +++ b/src/idl_gen_cpp.cpp @@ -26,7 +26,7 @@ namespace cpp { // Return a C++ type from the table in idl.h static std::string GenTypeBasic(const Type &type) { static const char *ctypename[] = { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) #CTYPE, + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) #CTYPE, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD }; @@ -96,16 +96,6 @@ static std::string GenTypeGet(const Parser &parser, const Type &type, : beforeptr + GenTypePointer(parser, type) + afterptr; } -// Generate a documentation comment, if available. -static void GenComment(const std::string &dc, - std::string *code_ptr, - const char *prefix = "") { - std::string &code = *code_ptr; - if (dc.length()) { - code += std::string(prefix) + "///" + dc + "\n"; - } -} - static std::string GenEnumVal(const EnumDef &enum_def, const EnumVal &enum_val, const GeneratorOptions &opts) { return opts.prefixed_enums ? enum_def.name + "_" + enum_val.name diff --git a/src/idl_gen_csharp.cpp b/src/idl_gen_csharp.cpp deleted file mode 100644 index 03210bc56..000000000 --- a/src/idl_gen_csharp.cpp +++ /dev/null @@ -1,403 +0,0 @@ -/* - * Copyright 2014 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 "flatbuffers/flatbuffers.h" -#include "flatbuffers/idl.h" -#include "flatbuffers/util.h" - -namespace flatbuffers { -namespace csharp { - -static std::string GenTypeBasic(const Type &type) { - static const char *ctypename[] = { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) #JTYPE, - FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) - #undef FLATBUFFERS_TD - }; - return ctypename[type.base_type]; -} - -static std::string GenTypeGet(const Type &type); - -static std::string GenTypePointer(const Type &type) { - switch (type.base_type) { - case BASE_TYPE_STRING: - return "string"; - case BASE_TYPE_VECTOR: - return GenTypeGet(type.VectorType()); - case BASE_TYPE_STRUCT: - return type.struct_def->name; - case BASE_TYPE_UNION: - // fall through - default: - return "Table"; - } -} - -static std::string GenTypeGet(const Type &type) { - return IsScalar(type.base_type) - ? GenTypeBasic(type) - : GenTypePointer(type); -} - -static void GenComment(const std::string &dc, - std::string *code_ptr, - const char *prefix = "") { - std::string &code = *code_ptr; - if (dc.length()) { - code += std::string(prefix) + "/*" + dc + "*/\n"; - } -} - - -static void GenEnum(EnumDef &enum_def, std::string *code_ptr) { - std::string &code = *code_ptr; - if (enum_def.generated) return; - - // Generate enum definitions of the form: - // public static int Name = value; - // We use ints rather than the C# Enum feature, because we want them - // to map directly to how they're used in C/C++ and file formats. - GenComment(enum_def.doc_comment, code_ptr); - code += "public class " + enum_def.name + "\n{\n"; - for (auto it = enum_def.vals.vec.begin(); - it != enum_def.vals.vec.end(); - ++it) { - auto &ev = **it; - GenComment(ev.doc_comment, code_ptr, " "); - code += " public static " + GenTypeBasic(enum_def.underlying_type); - code += " " + ev.name + " = "; - code += NumToString(ev.value) + ";\n"; - } - code += "};\n\n"; -} - -// Returns the function name that is able to read a value of the given type. -static std::string GenGetter(const Type &type) { - switch (type.base_type) { - case BASE_TYPE_STRING: return "__string"; - case BASE_TYPE_STRUCT: return "__struct"; - case BASE_TYPE_UNION: return "__union"; - case BASE_TYPE_VECTOR: return GenGetter(type.VectorType()); - default: - return "bb.Get" + (SizeOf(type.base_type) > 1 - ? MakeCamel(GenTypeGet(type)) - : ""); - } -} - -// Returns the method name for use with add/put calls. -static std::string GenMethod(const FieldDef &field) { - return IsScalar(field.value.type.base_type) - ? MakeCamel(GenTypeBasic(field.value.type)) - : (IsStruct(field.value.type) ? "Struct" : "Offset"); -} - -// Recursively generate arguments for a constructor, to deal with nested -// structs. -static void GenStructArgs(const StructDef &struct_def, std::string *code_ptr, - const char *nameprefix) { - std::string &code = *code_ptr; - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); - ++it) { - auto &field = **it; - if (IsStruct(field.value.type)) { - // Generate arguments for a struct inside a struct. To ensure names - // don't clash, and to make it obvious these arguments are constructing - // a nested struct, prefix the name with the struct name. - GenStructArgs(*field.value.type.struct_def, code_ptr, - (field.value.type.struct_def->name + "_").c_str()); - } else { - code += ", " + GenTypeBasic(field.value.type) + " " + nameprefix; - code += MakeCamel(field.name, true); - } - } -} - -// Recusively generate struct construction statements of the form: -// builder.PutType(name); -// and insert manual padding. -static void GenStructBody(const StructDef &struct_def, std::string *code_ptr, - const char *nameprefix) { - std::string &code = *code_ptr; - code += " builder.Prep(" + NumToString(struct_def.minalign) + ", "; - code += NumToString(struct_def.bytesize) + ");\n"; - for (auto it = struct_def.fields.vec.rbegin(); - it != struct_def.fields.vec.rend(); - ++it) { - auto &field = **it; - if (field.padding) - code += " builder.Pad(" + NumToString(field.padding) + ");\n"; - if (IsStruct(field.value.type)) { - GenStructBody(*field.value.type.struct_def, code_ptr, - (field.value.type.struct_def->name + "_").c_str()); - } else { - code += " builder.Put" + GenMethod(field) + "("; - code += nameprefix + MakeCamel(field.name, true) + ");\n"; - } - } -} - -static void GenStruct(const Parser &parser, StructDef &struct_def, - std::string *code_ptr) { - if (struct_def.generated) return; - std::string &code = *code_ptr; - - // Generate a struct accessor class, with methods of the form: - // public type Name() { return bb.GetType(i + offset); } - // or for tables of the form: - // public type Name() { - // int o = __offset(offset); return o != 0 ? bb.GetType(o + i) : default; - // } - GenComment(struct_def.doc_comment, code_ptr); - code += "public class " + struct_def.name + " : "; - code += struct_def.fixed ? "Struct" : "Table"; - code += " {\n"; - if (!struct_def.fixed) { - // Generate a special accessor for the table that when used as the root - // of a FlatBuffer - code += " public static " + struct_def.name + " GetRootAs"; - code += struct_def.name; - code += "(ByteBuffer _bb, int offset) { "; - // Endian handled by .NET ByteBuffer impl - code += "return (new " + struct_def.name; - code += "()).__init(_bb.GetInt(offset) + offset, _bb); }\n"; - if (parser.root_struct_def == &struct_def) { - if (parser.file_identifier_.length()) { - // Check if a buffer has the identifier. - code += " public static bool " + struct_def.name; - code += "BufferHasIdentifier(ByteBuffer _bb, int offset) { return "; - code += "__has_identifier(_bb, offset, \"" + parser.file_identifier_; - code += "\"); }\n"; - } - } - } - // Generate the __init method that sets the field in a pre-existing - // accessor object. This is to allow object reuse. - code += " public " + struct_def.name; - code += " __init(int _i, ByteBuffer _bb) "; - code += "{ bb_pos = _i; bb = _bb; return this; }\n\n"; - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); - ++it) { - auto &field = **it; - if (field.deprecated) continue; - GenComment(field.doc_comment, code_ptr, " "); - std::string type_name = GenTypeGet(field.value.type); - std::string method_start = " public " + type_name + " " + - MakeCamel(field.name, true); - // Generate the accessors that don't do object reuse. - if (field.value.type.base_type == BASE_TYPE_STRUCT) { - // Calls the accessor that takes an accessor object with a new object. - code += method_start + "() { return " + MakeCamel(field.name, true); - code += "(new "; - code += type_name + "()); }\n"; - } else if (field.value.type.base_type == BASE_TYPE_VECTOR && - field.value.type.element == BASE_TYPE_STRUCT) { - // Accessors for vectors of structs also take accessor objects, this - // generates a variant without that argument. - code += method_start + "(int j) { return " + MakeCamel(field.name, true); - code += "(new "; - code += type_name + "(), j); }\n"; - } - std::string getter = GenGetter(field.value.type); - code += method_start + "("; - // Most field accessors need to retrieve and test the field offset first, - // this is the prefix code for that: - auto offset_prefix = ") { int o = __offset(" + - NumToString(field.value.offset) + - "); return o != 0 ? "; - if (IsScalar(field.value.type.base_type)) { - if (struct_def.fixed) { - code += ") { return " + getter; - code += "(bb_pos + " + NumToString(field.value.offset) + ")"; - } else { - code += offset_prefix + getter; - code += "(o + bb_pos) : ("; - code += type_name; - code += ")" + field.value.constant; - } - } else { - switch (field.value.type.base_type) { - case BASE_TYPE_STRUCT: - code += type_name + " obj"; - if (struct_def.fixed) { - code += ") { return obj.__init(bb_pos + "; - code += NumToString(field.value.offset) + ", bb)"; - } else { - code += offset_prefix; - code += "obj.__init("; - code += field.value.type.struct_def->fixed - ? "o + bb_pos" - : "__indirect(o + bb_pos)"; - code += ", bb) : null"; - } - break; - case BASE_TYPE_STRING: - code += offset_prefix + getter +"(o + bb_pos) : null"; - break; - case BASE_TYPE_VECTOR: { - auto vectortype = field.value.type.VectorType(); - if (vectortype.base_type == BASE_TYPE_STRUCT) { - code += type_name + " obj, "; - getter = "obj.__init"; - } - code += "int j" + offset_prefix + getter +"("; - auto index = "__vector(o) + j * " + - NumToString(InlineSize(vectortype)); - if (vectortype.base_type == BASE_TYPE_STRUCT) { - code += vectortype.struct_def->fixed - ? index - : "__indirect(" + index + ")"; - code += ", bb"; - } else { - code += index; - } - code += ") : "; - code += IsScalar(field.value.type.element) ? "(" + type_name + ")0" : "null"; - break; - } - case BASE_TYPE_UNION: - code += type_name + " obj" + offset_prefix + getter; - code += "(obj, o) : null"; - break; - default: - assert(0); - } - } - code += "; }\n"; - if (field.value.type.base_type == BASE_TYPE_VECTOR) { - code += " public int " + MakeCamel(field.name, true) + "Length("; - code += offset_prefix; - code += "__vector_len(o) : 0; }\n"; - } - } - code += "\n"; - if (struct_def.fixed) { - // create a struct constructor function - code += " public static int Create" + struct_def.name; - code += "(FlatBufferBuilder builder"; - GenStructArgs(struct_def, code_ptr, ""); - code += ") {\n"; - GenStructBody(struct_def, code_ptr, ""); - code += " return builder.Offset;\n }\n"; - } else { - // Create a set of static methods that allow table construction, - // of the form: - // public static void AddName(FlatBufferBuilder builder, short name) - // { builder.AddShort(id, name, default); } - code += " public static void Start" + struct_def.name; - code += "(FlatBufferBuilder builder) { builder.StartObject("; - code += NumToString(struct_def.fields.vec.size()) + "); }\n"; - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); - ++it) { - auto &field = **it; - if (field.deprecated) continue; - code += " public static void Add" + MakeCamel(field.name); - code += "(FlatBufferBuilder builder, " + GenTypeBasic(field.value.type); - auto argname = MakeCamel(field.name, false); - if (!IsScalar(field.value.type.base_type)) argname += "Offset"; - code += " " + argname + ") { builder.Add"; - code += GenMethod(field) + "("; - code += NumToString(it - struct_def.fields.vec.begin()) + ", "; - code += argname + ", " + field.value.constant; - code += "); }\n"; - if (field.value.type.base_type == BASE_TYPE_VECTOR) { - code += " public static void Start" + MakeCamel(field.name); - code += "Vector(FlatBufferBuilder builder, int numElems) "; - code += "{ builder.StartVector("; - auto vector_type = field.value.type.VectorType(); - auto alignment = InlineAlignment(vector_type); - auto elem_size = InlineSize(vector_type); - code += NumToString(elem_size); - code += ", numElems, " + NumToString(alignment); - code += "); }\n"; - } - } - code += " public static int End" + struct_def.name; - code += "(FlatBufferBuilder builder) { return builder.EndObject(); }\n"; - if (parser.root_struct_def == &struct_def) { - code += " public static void Finish" + struct_def.name; - code += "Buffer(FlatBufferBuilder builder, int offset) { "; - code += "builder.Finish(offset"; - if (parser.file_identifier_.length()) - code += ", \"" + parser.file_identifier_ + "\""; - code += "); }\n"; - } - } - code += "};\n\n"; -} - -// Save out the generated code for a single Java class while adding -// declaration boilerplate. -static bool SaveClass(const Parser &parser, const Definition &def, - const std::string &classcode, const std::string &path) { - if (!classcode.length()) return true; - - std::string namespace_csharp; - std::string namespace_dir = path; - auto &namespaces = parser.namespaces_.back()->components; - for (auto it = namespaces.begin(); it != namespaces.end(); ++it) { - if (namespace_csharp.length()) { - namespace_csharp += "."; - namespace_dir += kPathSeparator; - } - namespace_csharp += *it; - namespace_dir += *it; - } - EnsureDirExists(namespace_dir); - - std::string code = "// automatically generated, do not modify\n\n"; - code += "namespace " + namespace_csharp + "\n{\n\n"; -// Other usings - code += "using FlatBuffers;\n\n"; - code += classcode; - code += "\n}\n"; - auto filename = namespace_dir + kPathSeparator + def.name + ".cs"; - return SaveFile(filename.c_str(), code, false); -} - -} // namespace csharp - -bool GenerateCSharp(const Parser &parser, - const std::string &path, - const std::string & /*file_name*/, - const GeneratorOptions & /*opts*/) { - using namespace csharp; - - for (auto it = parser.enums_.vec.begin(); - it != parser.enums_.vec.end(); ++it) { - std::string enumcode; - GenEnum(**it, &enumcode); - if (!SaveClass(parser, **it, enumcode, path)) - return false; - } - - for (auto it = parser.structs_.vec.begin(); - it != parser.structs_.vec.end(); ++it) { - std::string declcode; - GenStruct(parser, **it, &declcode); - if (!SaveClass(parser, **it, declcode, path)) - return false; - } - - return true; -} - -} // namespace flatbuffers - diff --git a/src/idl_gen_java.cpp b/src/idl_gen_general.cpp old mode 100755 new mode 100644 similarity index 51% rename from src/idl_gen_java.cpp rename to src/idl_gen_general.cpp index ba4ca558f..1d1371e9b --- a/src/idl_gen_java.cpp +++ b/src/idl_gen_general.cpp @@ -10,7 +10,7 @@ * 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 + * See the License for the specific GeneratorOptions::Language governing permissions and * limitations under the License. */ @@ -21,25 +21,116 @@ #include "flatbuffers/util.h" namespace flatbuffers { -namespace java { -static std::string GenTypeBasic(const Type &type) { - static const char *ctypename[] = { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) #JTYPE, +// Convert an underscore_based_indentifier in to camelCase. +// Also uppercases the first character if first is true. +std::string MakeCamel(const std::string &in, bool first) { + std::string s; + for (size_t i = 0; i < in.length(); i++) { + if (!i && first) + s += static_cast(toupper(in[0])); + else if (in[i] == '_' && i + 1 < in.length()) + s += static_cast(toupper(in[++i])); + else + s += in[i]; + } + return s; +} + +// Generate a documentation comment, if available. +void GenComment(const std::string &dc, std::string *code_ptr, + const char *prefix) { + std::string &code = *code_ptr; + if (dc.length()) { + code += std::string(prefix) + "///" + dc + "\n"; + } +} + +// These arrays need to correspond to the GeneratorOptions::k enum. + +struct LanguageParameters { + GeneratorOptions::Language language; + // Whether function names in the language typically start with uppercase. + bool first_camel_upper; + const char *file_extension; + const char *string_type; + const char *bool_type; + const char *open_curly; + const char *const_decl; + const char *inheritance_marker; + const char *namespace_ident; + const char *namespace_begin; + const char *namespace_end; + const char *set_bb_byteorder; + const char *includes; +}; + +LanguageParameters language_parameters[] = { + { + GeneratorOptions::kJava, + false, + ".java", + "String", + "boolean ", + " {\n", + " public static final ", + " extends ", + "package ", + ";", + "", + "_bb.order(ByteOrder.LITTLE_ENDIAN); ", + "import java.nio.*;\nimport java.lang.*;\nimport java.util.*;\n" + "import com.google.flatbuffers.*;\n\n", + }, + { + GeneratorOptions::kCSharp, + true, + ".cs", + "string", + "bool ", + "\n{\n", + " public static ", + " : ", + "namespace ", + "\n{", + "\n}\n", + "", + "using FlatBuffers;\n\n", + } +}; + +static_assert(sizeof(language_parameters) / sizeof(LanguageParameters) == + GeneratorOptions::kMAX, + "Please add extra elements to the arrays above."); + +static std::string FunctionStart(const LanguageParameters &lang, char upper) { + return std::string() + + (lang.language == GeneratorOptions::kJava + ? static_cast(tolower(upper)) + : upper); +} + +static std::string GenTypeBasic(const LanguageParameters &lang, + const Type &type) { + static const char *gtypename[] = { + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ + #JTYPE, #NTYPE, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD }; - return ctypename[type.base_type]; + return gtypename[type.base_type * GeneratorOptions::kMAX + lang.language]; } -static std::string GenTypeGet(const Type &type); +static std::string GenTypeGet(const LanguageParameters &lang, + const Type &type); -static std::string GenTypePointer(const Type &type) { +static std::string GenTypePointer(const LanguageParameters &lang, + const Type &type) { switch (type.base_type) { case BASE_TYPE_STRING: - return "String"; + return lang.string_type; case BASE_TYPE_VECTOR: - return GenTypeGet(type.VectorType()); + return GenTypeGet(lang, type.VectorType()); case BASE_TYPE_STRUCT: return type.struct_def->name; case BASE_TYPE_UNION: @@ -49,38 +140,32 @@ static std::string GenTypePointer(const Type &type) { } } -static std::string GenTypeGet(const Type &type) { +static std::string GenTypeGet(const LanguageParameters &lang, + const Type &type) { return IsScalar(type.base_type) - ? GenTypeBasic(type) - : GenTypePointer(type); + ? GenTypeBasic(lang, type) + : GenTypePointer(lang, type); } -static void GenComment(const std::string &dc, - std::string *code_ptr, - const char *prefix = "") { - std::string &code = *code_ptr; - if (dc.length()) { - code += std::string(prefix) + "///" + dc + "\n"; - } -} - -static void GenEnum(EnumDef &enum_def, std::string *code_ptr) { +static void GenEnum(const LanguageParameters &lang, EnumDef &enum_def, + std::string *code_ptr) { std::string &code = *code_ptr; if (enum_def.generated) return; // Generate enum definitions of the form: - // public static final int name = value; - // We use ints rather than the Java Enum feature, because we want them + // public static (final) int name = value; + // In Java, we use ints rather than the Enum feature, because we want them // to map directly to how they're used in C/C++ and file formats. // That, and Java Enums are expensive, and not universally liked. GenComment(enum_def.doc_comment, code_ptr); - code += "public class " + enum_def.name + " {\n"; + code += "public class " + enum_def.name + lang.open_curly; for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end(); ++it) { auto &ev = **it; GenComment(ev.doc_comment, code_ptr, " "); - code += " public static final " + GenTypeBasic(enum_def.underlying_type); + code += lang.const_decl; + code += GenTypeBasic(lang, enum_def.underlying_type); code += " " + ev.name + " = "; code += NumToString(ev.value) + ";\n"; } @@ -88,30 +173,33 @@ static void GenEnum(EnumDef &enum_def, std::string *code_ptr) { } // Returns the function name that is able to read a value of the given type. -static std::string GenGetter(const Type &type) { +static std::string GenGetter(const LanguageParameters &lang, + const Type &type) { switch (type.base_type) { case BASE_TYPE_STRING: return "__string"; case BASE_TYPE_STRUCT: return "__struct"; case BASE_TYPE_UNION: return "__union"; - case BASE_TYPE_VECTOR: return GenGetter(type.VectorType()); + case BASE_TYPE_VECTOR: return GenGetter(lang, type.VectorType()); default: - return "bb.get" + (SizeOf(type.base_type) > 1 - ? MakeCamel(GenTypeGet(type)) - : ""); + return "bb." + FunctionStart(lang, 'G') + "et" + + (GenTypeBasic(lang, type) != "byte" + ? MakeCamel(GenTypeGet(lang, type)) + : ""); } } // Returns the method name for use with add/put calls. -static std::string GenMethod(const Type &type) { +static std::string GenMethod(const LanguageParameters &lang, const Type &type) { return IsScalar(type.base_type) - ? MakeCamel(GenTypeBasic(type)) + ? MakeCamel(GenTypeBasic(lang, type)) : (IsStruct(type) ? "Struct" : "Offset"); } // Recursively generate arguments for a constructor, to deal with nested // structs. -static void GenStructArgs(const StructDef &struct_def, std::string *code_ptr, - const char *nameprefix) { +static void GenStructArgs(const LanguageParameters &lang, + const StructDef &struct_def, + std::string *code_ptr, const char *nameprefix) { std::string &code = *code_ptr; for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); @@ -121,11 +209,11 @@ static void GenStructArgs(const StructDef &struct_def, std::string *code_ptr, // Generate arguments for a struct inside a struct. To ensure names // don't clash, and to make it obvious these arguments are constructing // a nested struct, prefix the name with the struct name. - GenStructArgs(*field.value.type.struct_def, code_ptr, + GenStructArgs(lang, *field.value.type.struct_def, code_ptr, (field.value.type.struct_def->name + "_").c_str()); } else { - code += ", " + GenTypeBasic(field.value.type) + " " + nameprefix; - code += MakeCamel(field.name, false); + code += ", " + GenTypeBasic(lang, field.value.type) + " " + nameprefix; + code += MakeCamel(field.name, lang.first_camel_upper); } } } @@ -133,29 +221,33 @@ static void GenStructArgs(const StructDef &struct_def, std::string *code_ptr, // Recusively generate struct construction statements of the form: // builder.putType(name); // and insert manual padding. -static void GenStructBody(const StructDef &struct_def, std::string *code_ptr, - const char *nameprefix) { +static void GenStructBody(const LanguageParameters &lang, + const StructDef &struct_def, + std::string *code_ptr, const char *nameprefix) { std::string &code = *code_ptr; - code += " builder.prep(" + NumToString(struct_def.minalign) + ", "; + code += " builder." + FunctionStart(lang, 'P') + "rep("; + code += NumToString(struct_def.minalign) + ", "; code += NumToString(struct_def.bytesize) + ");\n"; for (auto it = struct_def.fields.vec.rbegin(); - it != struct_def.fields.vec.rend(); - ++it) { + it != struct_def.fields.vec.rend(); ++it) { auto &field = **it; - if (field.padding) - code += " builder.pad(" + NumToString(field.padding) + ");\n"; + if (field.padding) { + code += " builder." + FunctionStart(lang, 'P') + "ad("; + code += NumToString(field.padding) + ");\n"; + } if (IsStruct(field.value.type)) { - GenStructBody(*field.value.type.struct_def, code_ptr, + GenStructBody(lang, *field.value.type.struct_def, code_ptr, (field.value.type.struct_def->name + "_").c_str()); } else { - code += " builder.put" + GenMethod(field.value.type) + "("; - code += nameprefix + MakeCamel(field.name, false) + ");\n"; + code += " builder." + FunctionStart(lang, 'P') + "ut"; + code += GenMethod(lang, field.value.type) + "(" += nameprefix; + code += MakeCamel(field.name, lang.first_camel_upper) + ");\n"; } } } -static void GenStruct(const Parser &parser, StructDef &struct_def, - std::string *code_ptr) { +static void GenStruct(const LanguageParameters &lang, const Parser &parser, + StructDef &struct_def, std::string *code_ptr) { if (struct_def.generated) return; std::string &code = *code_ptr; @@ -166,22 +258,24 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, // int o = __offset(offset); return o != 0 ? bb.getType(o + i) : default; // } GenComment(struct_def.doc_comment, code_ptr); - code += "public class " + struct_def.name + " extends "; + code += "public class " + struct_def.name + lang.inheritance_marker; code += struct_def.fixed ? "Struct" : "Table"; code += " {\n"; if (!struct_def.fixed) { // Generate a special accessor for the table that when used as the root // of a FlatBuffer - code += " public static " + struct_def.name + " getRootAs"; - code += struct_def.name; + code += " public static " + struct_def.name + " "; + code += FunctionStart(lang, 'G') + "etRootAs" + struct_def.name; code += "(ByteBuffer _bb) { "; - code += "_bb.order(ByteOrder.LITTLE_ENDIAN); "; + code += lang.set_bb_byteorder; code += "return (new " + struct_def.name; - code += "()).__init(_bb.getInt(_bb.position()) + _bb.position(), _bb); }\n"; + code += "()).__init(_bb." + FunctionStart(lang, 'G'); + code += "etInt(_bb.position()) + _bb.position(), _bb); }\n"; if (parser.root_struct_def == &struct_def) { if (parser.file_identifier_.length()) { // Check if a buffer has the identifier. - code += " public static boolean " + struct_def.name; + code += " public static "; + code += lang.bool_type + struct_def.name; code += "BufferHasIdentifier(ByteBuffer _bb) { return "; code += "__has_identifier(_bb, \"" + parser.file_identifier_; code += "\"); }\n"; @@ -199,37 +293,42 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, auto &field = **it; if (field.deprecated) continue; GenComment(field.doc_comment, code_ptr, " "); - std::string type_name = GenTypeGet(field.value.type); + std::string type_name = GenTypeGet(lang, field.value.type); std::string method_start = " public " + type_name + " " + - MakeCamel(field.name, false); + MakeCamel(field.name, lang.first_camel_upper); // Generate the accessors that don't do object reuse. if (field.value.type.base_type == BASE_TYPE_STRUCT) { // Calls the accessor that takes an accessor object with a new object. - code += method_start + "() { return " + MakeCamel(field.name, false); + code += method_start + "() { return "; + code += MakeCamel(field.name, lang.first_camel_upper); code += "(new "; code += type_name + "()); }\n"; } else if (field.value.type.base_type == BASE_TYPE_VECTOR && field.value.type.element == BASE_TYPE_STRUCT) { // Accessors for vectors of structs also take accessor objects, this // generates a variant without that argument. - code += method_start + "(int j) { return " + MakeCamel(field.name, false); + code += method_start + "(int j) { return "; + code += MakeCamel(field.name, lang.first_camel_upper); code += "(new "; code += type_name + "(), j); }\n"; } - std::string getter = GenGetter(field.value.type); + std::string getter = GenGetter(lang, field.value.type); code += method_start + "("; // Most field accessors need to retrieve and test the field offset first, // this is the prefix code for that: auto offset_prefix = ") { int o = __offset(" + NumToString(field.value.offset) + "); return o != 0 ? "; + std::string default_cast = ""; + if (lang.language == GeneratorOptions::kCSharp) + default_cast = "(" + type_name + ")"; if (IsScalar(field.value.type.base_type)) { if (struct_def.fixed) { code += ") { return " + getter; code += "(bb_pos + " + NumToString(field.value.offset) + ")"; } else { code += offset_prefix + getter; - code += "(o + bb_pos) : " + field.value.constant; + code += "(o + bb_pos) : " + default_cast + field.value.constant; } } else { switch (field.value.type.base_type) { @@ -268,7 +367,9 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, code += index; } code += ") : "; - code += IsScalar(field.value.type.element) ? "0" : "null"; + code += IsScalar(field.value.type.element) + ? default_cast + "0" + : "null"; break; } case BASE_TYPE_UNION: @@ -281,13 +382,15 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, } code += "; }\n"; if (field.value.type.base_type == BASE_TYPE_VECTOR) { - code += " public int " + MakeCamel(field.name, false) + "Length("; - code += offset_prefix; + code += " public int " + MakeCamel(field.name, lang.first_camel_upper); + code += "Length(" + offset_prefix; code += "__vector_len(o) : 0; }\n"; } - if (field.value.type.base_type == BASE_TYPE_VECTOR || - field.value.type.base_type == BASE_TYPE_STRING) { - code += " public ByteBuffer " + MakeCamel(field.name, false); + if ((field.value.type.base_type == BASE_TYPE_VECTOR || + field.value.type.base_type == BASE_TYPE_STRING) && + lang.language == GeneratorOptions::kJava) { + code += " public ByteBuffer "; + code += MakeCamel(field.name, lang.first_camel_upper); code += "AsByteBuffer() { return __vector_as_bytebuffer("; code += NumToString(field.value.offset) + ", "; code += NumToString(field.value.type.base_type == BASE_TYPE_STRING ? 1 : @@ -298,31 +401,36 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, code += "\n"; if (struct_def.fixed) { // create a struct constructor function - code += " public static int create" + struct_def.name; - code += "(FlatBufferBuilder builder"; - GenStructArgs(struct_def, code_ptr, ""); + code += " public static int " + FunctionStart(lang, 'C') + "reate"; + code += struct_def.name + "(FlatBufferBuilder builder"; + GenStructArgs(lang, struct_def, code_ptr, ""); code += ") {\n"; - GenStructBody(struct_def, code_ptr, ""); - code += " return builder.offset();\n }\n"; + GenStructBody(lang, struct_def, code_ptr, ""); + code += " return builder."; + code += FunctionStart(lang, 'O') + "ffset();\n }\n"; } else { // Create a set of static methods that allow table construction, // of the form: // public static void addName(FlatBufferBuilder builder, short name) // { builder.addShort(id, name, default); } - code += " public static void start" + struct_def.name; - code += "(FlatBufferBuilder builder) { builder.startObject("; + code += " public static void " + FunctionStart(lang, 'S') + "tart"; + code += struct_def.name; + code += "(FlatBufferBuilder builder) { builder."; + code += FunctionStart(lang, 'S') + "tartObject("; code += NumToString(struct_def.fields.vec.size()) + "); }\n"; for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { auto &field = **it; if (field.deprecated) continue; - code += " public static void add" + MakeCamel(field.name); - code += "(FlatBufferBuilder builder, " + GenTypeBasic(field.value.type); + code += " public static void " + FunctionStart(lang, 'A') + "dd"; + code += MakeCamel(field.name); + code += "(FlatBufferBuilder builder, "; + code += GenTypeBasic(lang, field.value.type); auto argname = MakeCamel(field.name, false); if (!IsScalar(field.value.type.base_type)) argname += "Offset"; - code += " " + argname + ") { builder.add"; - code += GenMethod(field.value.type) + "("; + code += " " + argname + ") { builder." + FunctionStart(lang, 'A') + "dd"; + code += GenMethod(lang, field.value.type) + "("; code += NumToString(it - struct_def.fields.vec.begin()) + ", "; code += argname + ", " + field.value.constant; code += "); }\n"; @@ -332,30 +440,40 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, auto elem_size = InlineSize(vector_type); if (!IsStruct(vector_type)) { // Generate a method to create a vector from a Java array. - code += " public static int create" + MakeCamel(field.name); + code += " public static int " + FunctionStart(lang, 'C') + "reate"; + code += MakeCamel(field.name); code += "Vector(FlatBufferBuilder builder, "; - code += GenTypeBasic(vector_type) + "[] data) "; - code += "{ builder.startVector("; + code += GenTypeBasic(lang, vector_type) + "[] data) "; + code += "{ builder." + FunctionStart(lang, 'S') + "tartVector("; code += NumToString(elem_size); - code += ", data.length, " + NumToString(alignment); - code += "); for (int i = data.length - 1; i >= 0; i--) builder.add"; - code += GenMethod(vector_type); - code += "(data[i]); return builder.endVector(); }\n"; + code += ", data." + FunctionStart(lang, 'L') + "ength, "; + code += NumToString(alignment); + code += "); for (int i = data."; + code += FunctionStart(lang, 'L') + "ength - 1; i >= 0; i--) builder."; + code += FunctionStart(lang, 'A') + "dd"; + code += GenMethod(lang, vector_type); + code += "(data[i]); return builder."; + code += FunctionStart(lang, 'E') + "ndVector(); }\n"; } // Generate a method to start a vector, data to be added manually after. - code += " public static void start" + MakeCamel(field.name); + code += " public static void " + FunctionStart(lang, 'S') + "tart"; + code += MakeCamel(field.name); code += "Vector(FlatBufferBuilder builder, int numElems) "; - code += "{ builder.startVector("; + code += "{ builder." + FunctionStart(lang, 'S') + "tartVector("; code += NumToString(elem_size); code += ", numElems, " + NumToString(alignment); - code += "); }\n"; } + code += "); }\n"; + } } - code += " public static int end" + struct_def.name; - code += "(FlatBufferBuilder builder) { return builder.endObject(); }\n"; + code += " public static int "; + code += FunctionStart(lang, 'E') + "nd" + struct_def.name; + code += "(FlatBufferBuilder builder) { return builder."; + code += FunctionStart(lang, 'E') + "ndObject(); }\n"; if (parser.root_struct_def == &struct_def) { - code += " public static void finish" + struct_def.name; + code += " public static void "; + code += FunctionStart(lang, 'F') + "inish" + struct_def.name; code += "Buffer(FlatBufferBuilder builder, int offset) { "; - code += "builder.finish(offset"; + code += "builder." + FunctionStart(lang, 'F') + "inish(offset"; if (parser.file_identifier_.length()) code += ", \"" + parser.file_identifier_ + "\""; code += "); }\n"; @@ -364,58 +482,58 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, code += "};\n\n"; } -// Save out the generated code for a single Java class while adding +// Save out the generated code for a single class while adding // declaration boilerplate. -static bool SaveClass(const Parser &parser, const Definition &def, - const std::string &classcode, const std::string &path, - bool needs_imports) { +static bool SaveClass(const LanguageParameters &lang, const Parser &parser, + const Definition &def, const std::string &classcode, + const std::string &path, bool needs_includes) { if (!classcode.length()) return true; - std::string namespace_java; + std::string namespace_general; std::string namespace_dir = path; auto &namespaces = parser.namespaces_.back()->components; for (auto it = namespaces.begin(); it != namespaces.end(); ++it) { - if (namespace_java.length()) { - namespace_java += "."; + if (namespace_general.length()) { + namespace_general += "."; namespace_dir += kPathSeparator; } - namespace_java += *it; + namespace_general += *it; namespace_dir += *it; } EnsureDirExists(namespace_dir); std::string code = "// automatically generated, do not modify\n\n"; - code += "package " + namespace_java + ";\n\n"; - if (needs_imports) { - code += "import java.nio.*;\nimport java.lang.*;\nimport java.util.*;\n"; - code += "import com.google.flatbuffers.*;\n\n"; - } + code += lang.namespace_ident + namespace_general + lang.namespace_begin; + code += "\n\n"; + if (needs_includes) code += lang.includes; code += classcode; - auto filename = namespace_dir + kPathSeparator + def.name + ".java"; + code += lang.namespace_end; + auto filename = namespace_dir + kPathSeparator + def.name + + lang.file_extension; return SaveFile(filename.c_str(), code, false); } -} // namespace java +bool GenerateGeneral(const Parser &parser, + const std::string &path, + const std::string & /*file_name*/, + const GeneratorOptions &opts) { -bool GenerateJava(const Parser &parser, - const std::string &path, - const std::string & /*file_name*/, - const GeneratorOptions & /*opts*/) { - using namespace java; + assert(opts.lang <= GeneratorOptions::kMAX); + auto lang = language_parameters[opts.lang]; for (auto it = parser.enums_.vec.begin(); it != parser.enums_.vec.end(); ++it) { std::string enumcode; - GenEnum(**it, &enumcode); - if (!SaveClass(parser, **it, enumcode, path, false)) + GenEnum(lang, **it, &enumcode); + if (!SaveClass(lang, parser, **it, enumcode, path, false)) return false; } for (auto it = parser.structs_.vec.begin(); it != parser.structs_.vec.end(); ++it) { std::string declcode; - GenStruct(parser, **it, &declcode); - if (!SaveClass(parser, **it, declcode, path, true)) + GenStruct(lang, parser, **it, &declcode); + if (!SaveClass(lang, parser, **it, declcode, path, true)) return false; } diff --git a/src/idl_gen_go.cpp b/src/idl_gen_go.cpp index ce12d17b9..b71c09b7a 100644 --- a/src/idl_gen_go.cpp +++ b/src/idl_gen_go.cpp @@ -612,7 +612,7 @@ static bool SaveType(const Parser &parser, const Definition &def, static std::string GenTypeBasic(const Type &type) { static const char *ctypename[] = { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) #GTYPE, + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) #GTYPE, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD }; diff --git a/src/idl_gen_text.cpp b/src/idl_gen_text.cpp index cbcd1719c..e0299379d 100644 --- a/src/idl_gen_text.cpp +++ b/src/idl_gen_text.cpp @@ -159,7 +159,7 @@ template<> void Print(const void *val, type = type.VectorType(); // Call PrintVector above specifically for each element type: switch (type.base_type) { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \ + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ case BASE_TYPE_ ## ENUM: \ PrintVector( \ *reinterpret_cast *>(val), \ @@ -225,7 +225,7 @@ static void GenStruct(const StructDef &struct_def, const Table *table, OutputIdentifier(fd.name, opts, _text); text += ": "; switch (fd.value.type.base_type) { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \ + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ case BASE_TYPE_ ## ENUM: \ GenField(fd, table, struct_def.fixed, \ opts, indent + Indent(opts), _text); \ @@ -233,7 +233,7 @@ static void GenStruct(const StructDef &struct_def, const Table *table, FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD) #undef FLATBUFFERS_TD // Generate drop-thru case statements for all pointer types: - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \ + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ case BASE_TYPE_ ## ENUM: FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD) #undef FLATBUFFERS_TD diff --git a/src/idl_parser.cpp b/src/idl_parser.cpp index ea21ec664..316fb7173 100644 --- a/src/idl_parser.cpp +++ b/src/idl_parser.cpp @@ -23,14 +23,15 @@ namespace flatbuffers { const char *const kTypeNames[] = { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) IDLTYPE, + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) IDLTYPE, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD nullptr }; const char kTypeSizes[] = { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) sizeof(CTYPE), + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ + sizeof(CTYPE), FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD }; @@ -92,7 +93,8 @@ enum { #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME = VALUE, FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN) #undef FLATBUFFERS_TOKEN - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) kToken ## ENUM, + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ + kToken ## ENUM, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD }; @@ -102,7 +104,7 @@ static std::string TokenToString(int t) { #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) STRING, FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN) #undef FLATBUFFERS_TOKEN - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) IDLTYPE, + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) IDLTYPE, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD }; @@ -200,7 +202,7 @@ void Parser::Next() { attribute_.clear(); attribute_.append(start, cursor_); // First, see if it is a type keyword from the table of types: - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \ + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ if (attribute_ == IDLTYPE) { \ token_ = kToken ## ENUM; \ return; \ @@ -491,7 +493,7 @@ uoffset_t Parser::ParseTable(const StructDef &struct_def) { auto field = it->second; if (!struct_def.sortbysize || size == SizeOf(value.type.base_type)) { switch (value.type.base_type) { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \ + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ case BASE_TYPE_ ## ENUM: \ builder_.Pad(field->padding); \ if (struct_def.fixed) { \ @@ -504,7 +506,7 @@ uoffset_t Parser::ParseTable(const StructDef &struct_def) { break; FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD); #undef FLATBUFFERS_TD - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \ + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ case BASE_TYPE_ ## ENUM: \ builder_.Pad(field->padding); \ if (IsStruct(field->value.type)) { \ @@ -559,7 +561,7 @@ uoffset_t Parser::ParseVector(const Type &type) { // start at the back, since we're building the data backwards. auto &val = field_stack_.back().first; switch (val.type.base_type) { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \ + #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ case BASE_TYPE_ ## ENUM: \ if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \ else builder_.PushElement(atot(val.constant.c_str())); \ diff --git a/tests/FlatBuffers.Test/Assert.cs b/tests/FlatBuffers.Test/Assert.cs index 9e4108239..7f2a1228e 100644 --- a/tests/FlatBuffers.Test/Assert.cs +++ b/tests/FlatBuffers.Test/Assert.cs @@ -63,7 +63,7 @@ namespace FlatBuffers.Test { action(); } - catch (T ex) + catch (T) { caught = true; } diff --git a/tests/FlatBuffers.Test/FlatBuffersExampleTests.cs b/tests/FlatBuffers.Test/FlatBuffersExampleTests.cs index ed946b16a..a084dda07 100644 --- a/tests/FlatBuffers.Test/FlatBuffersExampleTests.cs +++ b/tests/FlatBuffers.Test/FlatBuffersExampleTests.cs @@ -39,7 +39,7 @@ namespace FlatBuffers.Test var str = fbb.CreateString("MyMonster"); var test1 = fbb.CreateString("test1"); - var test2 = fbb.CreateString("test2"); + var test2 = fbb.CreateString("test2"); Monster.StartInventoryVector(fbb, 5); @@ -54,19 +54,19 @@ namespace FlatBuffers.Test var mon2 = Monster.EndMonster(fbb); Monster.StartTest4Vector(fbb, 2); - MyGame.Example.Test.CreateTest(fbb, (short)10, (byte)20); - MyGame.Example.Test.CreateTest(fbb, (short)30, (byte)40); + MyGame.Example.Test.CreateTest(fbb, (short)10, (sbyte)20); + MyGame.Example.Test.CreateTest(fbb, (short)30, (sbyte)40); var test4 = fbb.EndVector(); - Monster.StartTestarrayofstringVector(fbb, 2); - fbb.AddOffset(test2); - fbb.AddOffset(test1); - var testArrayOfString = fbb.EndVector(); + Monster.StartTestarrayofstringVector(fbb, 2); + fbb.AddOffset(test2); + fbb.AddOffset(test1); + var testArrayOfString = fbb.EndVector(); Monster.StartMonster(fbb); Monster.AddPos(fbb, Vec3.CreateVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0, - (byte)4, (short)5, (byte)6)); + (sbyte)4, (short)5, (sbyte)6)); Monster.AddHp(fbb, (short)80); Monster.AddName(fbb, str); Monster.AddInventory(fbb, inv); @@ -79,19 +79,19 @@ namespace FlatBuffers.Test fbb.Finish(mon); // Dump to output directory so we can inspect later, if needed - using (var ms= new MemoryStream(fbb.Data.Data, fbb.DataStart, fbb.Offset)) + using (var ms = new MemoryStream(fbb.DataBuffer().Data, fbb.DataBuffer().position(), fbb.Offset())) { var data = ms.ToArray(); File.WriteAllBytes(@"Resources/monsterdata_cstest.bin",data); } // Now assert the buffer - TestBuffer(fbb.Data, fbb.DataStart); + TestBuffer(fbb.DataBuffer()); } - private void TestBuffer(ByteBuffer bb, int start) + private void TestBuffer(ByteBuffer bb) { - var monster = Monster.GetRootAsMonster(bb, start); + var monster = Monster.GetRootAsMonster(bb); Assert.AreEqual(80, monster.Hp()); Assert.AreEqual(150, monster.Mana()); @@ -103,10 +103,10 @@ namespace FlatBuffers.Test Assert.AreEqual(3.0f, pos.Z()); Assert.AreEqual(3.0f, pos.Test1()); - Assert.AreEqual((byte)4, pos.Test2()); + Assert.AreEqual((sbyte)4, pos.Test2()); var t = pos.Test3(); Assert.AreEqual((short)5, t.A()); - Assert.AreEqual((byte)6, t.B()); + Assert.AreEqual((sbyte)6, t.B()); Assert.AreEqual((byte)Any.Monster, monster.TestType()); @@ -132,14 +132,14 @@ namespace FlatBuffers.Test Assert.AreEqual(2, monster.TestarrayofstringLength()); Assert.AreEqual("test1", monster.Testarrayofstring(0)); - Assert.AreEqual("test2", monster.Testarrayofstring(1)); + Assert.AreEqual("test2", monster.Testarrayofstring(1)); } public void CanReadCppGeneratedWireFile() { var data = File.ReadAllBytes(@"Resources/monsterdata_test.bin"); var bb = new ByteBuffer(data); - TestBuffer(bb, 0); + TestBuffer(bb); } } } diff --git a/tests/MyGame/Example/Any.cs b/tests/MyGame/Example/Any.cs index 73a22487a..8f88a9d41 100644 --- a/tests/MyGame/Example/Any.cs +++ b/tests/MyGame/Example/Any.cs @@ -3,8 +3,6 @@ namespace MyGame.Example { -using FlatBuffers; - public class Any { public static byte NONE = 0; diff --git a/tests/MyGame/Example/Color.cs b/tests/MyGame/Example/Color.cs index 34abc641c..7d9df7b63 100644 --- a/tests/MyGame/Example/Color.cs +++ b/tests/MyGame/Example/Color.cs @@ -3,13 +3,11 @@ namespace MyGame.Example { -using FlatBuffers; - public class Color { - public static byte Red = 1; - public static byte Green = 2; - public static byte Blue = 8; + public static sbyte Red = 1; + public static sbyte Green = 2; + public static sbyte Blue = 8; }; diff --git a/tests/MyGame/Example/Monster.cs b/tests/MyGame/Example/Monster.cs index 0e02416bf..2910aa6b1 100644 --- a/tests/MyGame/Example/Monster.cs +++ b/tests/MyGame/Example/Monster.cs @@ -1,64 +1,68 @@ -// automatically generated, do not modify - -namespace MyGame.Example -{ - -using FlatBuffers; - -public class Monster : Table { - public static Monster GetRootAsMonster(ByteBuffer _bb, int offset) { return (new Monster()).__init(_bb.GetInt(offset) + offset, _bb); } - public static bool MonsterBufferHasIdentifier(ByteBuffer _bb, int offset) { return __has_identifier(_bb, offset, "MONS"); } - public Monster __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; } - - public Vec3 Pos() { return Pos(new Vec3()); } - public Vec3 Pos(Vec3 obj) { int o = __offset(4); return o != 0 ? obj.__init(o + bb_pos, bb) : null; } - public short Mana() { int o = __offset(6); return o != 0 ? bb.GetShort(o + bb_pos) : (short)150; } - public short Hp() { int o = __offset(8); return o != 0 ? bb.GetShort(o + bb_pos) : (short)100; } - public string Name() { int o = __offset(10); return o != 0 ? __string(o + bb_pos) : null; } - public byte Inventory(int j) { int o = __offset(14); return o != 0 ? bb.Get(__vector(o) + j * 1) : (byte)0; } - public int InventoryLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; } - public byte Color() { int o = __offset(16); return o != 0 ? bb.Get(o + bb_pos) : (byte)8; } - public byte TestType() { int o = __offset(18); return o != 0 ? bb.Get(o + bb_pos) : (byte)0; } - public Table Test(Table obj) { int o = __offset(20); return o != 0 ? __union(obj, o) : null; } - public Test Test4(int j) { return Test4(new Test(), j); } - public Test Test4(Test obj, int j) { int o = __offset(22); return o != 0 ? obj.__init(__vector(o) + j * 4, bb) : null; } - public int Test4Length() { int o = __offset(22); return o != 0 ? __vector_len(o) : 0; } - public string Testarrayofstring(int j) { int o = __offset(24); return o != 0 ? __string(__vector(o) + j * 4) : null; } - public int TestarrayofstringLength() { int o = __offset(24); return o != 0 ? __vector_len(o) : 0; } - /* an example documentation comment: this will end up in the generated code multiline too */ - public Monster Testarrayoftables(int j) { return Testarrayoftables(new Monster(), j); } - public Monster Testarrayoftables(Monster obj, int j) { int o = __offset(26); return o != 0 ? obj.__init(__indirect(__vector(o) + j * 4), bb) : null; } - public int TestarrayoftablesLength() { int o = __offset(26); return o != 0 ? __vector_len(o) : 0; } - public Monster Enemy() { return Enemy(new Monster()); } - public Monster Enemy(Monster obj) { int o = __offset(28); return o != 0 ? obj.__init(__indirect(o + bb_pos), bb) : null; } - public byte Testnestedflatbuffer(int j) { int o = __offset(30); return o != 0 ? bb.Get(__vector(o) + j * 1) : (byte)0; } - public int TestnestedflatbufferLength() { int o = __offset(30); return o != 0 ? __vector_len(o) : 0; } - public Monster Testempty() { return Testempty(new Monster()); } - public Monster Testempty(Monster obj) { int o = __offset(32); return o != 0 ? obj.__init(__indirect(o + bb_pos), bb) : null; } - - public static void StartMonster(FlatBufferBuilder builder) { builder.StartObject(15); } - public static void AddPos(FlatBufferBuilder builder, int posOffset) { builder.AddStruct(0, posOffset, 0); } - public static void AddMana(FlatBufferBuilder builder, short mana) { builder.AddShort(1, mana, 150); } - public static void AddHp(FlatBufferBuilder builder, short hp) { builder.AddShort(2, hp, 100); } - public static void AddName(FlatBufferBuilder builder, int nameOffset) { builder.AddOffset(3, nameOffset, 0); } - public static void AddInventory(FlatBufferBuilder builder, int inventoryOffset) { builder.AddOffset(5, inventoryOffset, 0); } - public static void StartInventoryVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } - public static void AddColor(FlatBufferBuilder builder, byte color) { builder.AddByte(6, color, 8); } - public static void AddTestType(FlatBufferBuilder builder, byte testType) { builder.AddByte(7, testType, 0); } - public static void AddTest(FlatBufferBuilder builder, int testOffset) { builder.AddOffset(8, testOffset, 0); } - public static void AddTest4(FlatBufferBuilder builder, int test4Offset) { builder.AddOffset(9, test4Offset, 0); } - public static void StartTest4Vector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 2); } - public static void AddTestarrayofstring(FlatBufferBuilder builder, int testarrayofstringOffset) { builder.AddOffset(10, testarrayofstringOffset, 0); } - public static void StartTestarrayofstringVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } - public static void AddTestarrayoftables(FlatBufferBuilder builder, int testarrayoftablesOffset) { builder.AddOffset(11, testarrayoftablesOffset, 0); } - public static void StartTestarrayoftablesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } - public static void AddEnemy(FlatBufferBuilder builder, int enemyOffset) { builder.AddOffset(12, enemyOffset, 0); } - public static void AddTestnestedflatbuffer(FlatBufferBuilder builder, int testnestedflatbufferOffset) { builder.AddOffset(13, testnestedflatbufferOffset, 0); } - public static void StartTestnestedflatbufferVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } - public static void AddTestempty(FlatBufferBuilder builder, int testemptyOffset) { builder.AddOffset(14, testemptyOffset, 0); } - public static int EndMonster(FlatBufferBuilder builder) { return builder.EndObject(); } - public static void FinishMonsterBuffer(FlatBufferBuilder builder, int offset) { builder.Finish(offset, "MONS"); } -}; - - -} +// automatically generated, do not modify + +namespace MyGame.Example +{ + +using FlatBuffers; + +public class Monster : Table { + public static Monster GetRootAsMonster(ByteBuffer _bb) { return (new Monster()).__init(_bb.GetInt(_bb.position()) + _bb.position(), _bb); } + public static bool MonsterBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "MONS"); } + public Monster __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; } + + public Vec3 Pos() { return Pos(new Vec3()); } + public Vec3 Pos(Vec3 obj) { int o = __offset(4); return o != 0 ? obj.__init(o + bb_pos, bb) : null; } + public short Mana() { int o = __offset(6); return o != 0 ? bb.GetShort(o + bb_pos) : (short)150; } + public short Hp() { int o = __offset(8); return o != 0 ? bb.GetShort(o + bb_pos) : (short)100; } + public string Name() { int o = __offset(10); return o != 0 ? __string(o + bb_pos) : null; } + public byte Inventory(int j) { int o = __offset(14); return o != 0 ? bb.Get(__vector(o) + j * 1) : (byte)0; } + public int InventoryLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; } + public sbyte Color() { int o = __offset(16); return o != 0 ? bb.GetSbyte(o + bb_pos) : (sbyte)8; } + public byte TestType() { int o = __offset(18); return o != 0 ? bb.Get(o + bb_pos) : (byte)0; } + public Table Test(Table obj) { int o = __offset(20); return o != 0 ? __union(obj, o) : null; } + public Test Test4(int j) { return Test4(new Test(), j); } + public Test Test4(Test obj, int j) { int o = __offset(22); return o != 0 ? obj.__init(__vector(o) + j * 4, bb) : null; } + public int Test4Length() { int o = __offset(22); return o != 0 ? __vector_len(o) : 0; } + public string Testarrayofstring(int j) { int o = __offset(24); return o != 0 ? __string(__vector(o) + j * 4) : null; } + public int TestarrayofstringLength() { int o = __offset(24); return o != 0 ? __vector_len(o) : 0; } + /// an example documentation comment: this will end up in the generated code multiline too + public Monster Testarrayoftables(int j) { return Testarrayoftables(new Monster(), j); } + public Monster Testarrayoftables(Monster obj, int j) { int o = __offset(26); return o != 0 ? obj.__init(__indirect(__vector(o) + j * 4), bb) : null; } + public int TestarrayoftablesLength() { int o = __offset(26); return o != 0 ? __vector_len(o) : 0; } + public Monster Enemy() { return Enemy(new Monster()); } + public Monster Enemy(Monster obj) { int o = __offset(28); return o != 0 ? obj.__init(__indirect(o + bb_pos), bb) : null; } + public byte Testnestedflatbuffer(int j) { int o = __offset(30); return o != 0 ? bb.Get(__vector(o) + j * 1) : (byte)0; } + public int TestnestedflatbufferLength() { int o = __offset(30); return o != 0 ? __vector_len(o) : 0; } + public Monster Testempty() { return Testempty(new Monster()); } + public Monster Testempty(Monster obj) { int o = __offset(32); return o != 0 ? obj.__init(__indirect(o + bb_pos), bb) : null; } + + public static void StartMonster(FlatBufferBuilder builder) { builder.StartObject(15); } + public static void AddPos(FlatBufferBuilder builder, int posOffset) { builder.AddStruct(0, posOffset, 0); } + public static void AddMana(FlatBufferBuilder builder, short mana) { builder.AddShort(1, mana, 150); } + public static void AddHp(FlatBufferBuilder builder, short hp) { builder.AddShort(2, hp, 100); } + public static void AddName(FlatBufferBuilder builder, int nameOffset) { builder.AddOffset(3, nameOffset, 0); } + public static void AddInventory(FlatBufferBuilder builder, int inventoryOffset) { builder.AddOffset(5, inventoryOffset, 0); } + public static int CreateInventoryVector(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); for (int i = data.Length - 1; i >= 0; i--) builder.AddByte(data[i]); return builder.EndVector(); } + public static void StartInventoryVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } + public static void AddColor(FlatBufferBuilder builder, sbyte color) { builder.AddSbyte(6, color, 8); } + public static void AddTestType(FlatBufferBuilder builder, byte testType) { builder.AddByte(7, testType, 0); } + public static void AddTest(FlatBufferBuilder builder, int testOffset) { builder.AddOffset(8, testOffset, 0); } + public static void AddTest4(FlatBufferBuilder builder, int test4Offset) { builder.AddOffset(9, test4Offset, 0); } + public static void StartTest4Vector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 2); } + public static void AddTestarrayofstring(FlatBufferBuilder builder, int testarrayofstringOffset) { builder.AddOffset(10, testarrayofstringOffset, 0); } + public static int CreateTestarrayofstringVector(FlatBufferBuilder builder, int[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i]); return builder.EndVector(); } + public static void StartTestarrayofstringVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static void AddTestarrayoftables(FlatBufferBuilder builder, int testarrayoftablesOffset) { builder.AddOffset(11, testarrayoftablesOffset, 0); } + public static int CreateTestarrayoftablesVector(FlatBufferBuilder builder, int[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i]); return builder.EndVector(); } + public static void StartTestarrayoftablesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static void AddEnemy(FlatBufferBuilder builder, int enemyOffset) { builder.AddOffset(12, enemyOffset, 0); } + public static void AddTestnestedflatbuffer(FlatBufferBuilder builder, int testnestedflatbufferOffset) { builder.AddOffset(13, testnestedflatbufferOffset, 0); } + public static int CreateTestnestedflatbufferVector(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); for (int i = data.Length - 1; i >= 0; i--) builder.AddByte(data[i]); return builder.EndVector(); } + public static void StartTestnestedflatbufferVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } + public static void AddTestempty(FlatBufferBuilder builder, int testemptyOffset) { builder.AddOffset(14, testemptyOffset, 0); } + public static int EndMonster(FlatBufferBuilder builder) { return builder.EndObject(); } + public static void FinishMonsterBuffer(FlatBufferBuilder builder, int offset) { builder.Finish(offset, "MONS"); } +}; + + +} diff --git a/tests/MyGame/Example/Test.cs b/tests/MyGame/Example/Test.cs index 20d8fe6f6..1603582b8 100644 --- a/tests/MyGame/Example/Test.cs +++ b/tests/MyGame/Example/Test.cs @@ -9,14 +9,14 @@ public class Test : Struct { public Test __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; } public short A() { return bb.GetShort(bb_pos + 0); } - public byte B() { return bb.Get(bb_pos + 2); } + public sbyte B() { return bb.GetSbyte(bb_pos + 2); } - public static int CreateTest(FlatBufferBuilder builder, short A, byte B) { + public static int CreateTest(FlatBufferBuilder builder, short A, sbyte B) { builder.Prep(2, 4); builder.Pad(1); - builder.PutByte(B); + builder.PutSbyte(B); builder.PutShort(A); - return builder.Offset; + return builder.Offset(); } }; diff --git a/tests/MyGame/Example/Vec3.cs b/tests/MyGame/Example/Vec3.cs index 169a94435..4284aba4a 100644 --- a/tests/MyGame/Example/Vec3.cs +++ b/tests/MyGame/Example/Vec3.cs @@ -12,25 +12,25 @@ public class Vec3 : Struct { public float Y() { return bb.GetFloat(bb_pos + 4); } public float Z() { return bb.GetFloat(bb_pos + 8); } public double Test1() { return bb.GetDouble(bb_pos + 16); } - public byte Test2() { return bb.Get(bb_pos + 24); } + public sbyte Test2() { return bb.GetSbyte(bb_pos + 24); } public Test Test3() { return Test3(new Test()); } public Test Test3(Test obj) { return obj.__init(bb_pos + 26, bb); } - public static int CreateVec3(FlatBufferBuilder builder, float X, float Y, float Z, double Test1, byte Test2, short Test_A, byte Test_B) { + public static int CreateVec3(FlatBufferBuilder builder, float X, float Y, float Z, double Test1, sbyte Test2, short Test_A, sbyte Test_B) { builder.Prep(16, 32); builder.Pad(2); builder.Prep(2, 4); builder.Pad(1); - builder.PutByte(Test_B); + builder.PutSbyte(Test_B); builder.PutShort(Test_A); builder.Pad(1); - builder.PutByte(Test2); + builder.PutSbyte(Test2); builder.PutDouble(Test1); builder.Pad(4); builder.PutFloat(Z); builder.PutFloat(Y); builder.PutFloat(X); - return builder.Offset; + return builder.Offset(); } }; diff --git a/tests/monsterdata_test.json b/tests/monsterdata_test.json index a738caec4..ca63f4285 100755 --- a/tests/monsterdata_test.json +++ b/tests/monsterdata_test.json @@ -36,5 +36,7 @@ testarrayofstring: [ "test1", "test2" - ] + ], + testempty: { + } }