Refactored the Java and C# code generators into one.

Also made the C# implementation support unsigned types, and
made it more like the Java version.

Bug: 17359988
Change-Id: If5305c08cd5c97f35426639516ce05e53bbec36c
Tested: on Linux and Windows.
parent d01b30cd
...@@ -12,8 +12,7 @@ set(FlatBuffers_Compiler_SRCS ...@@ -12,8 +12,7 @@ set(FlatBuffers_Compiler_SRCS
include/flatbuffers/util.h include/flatbuffers/util.h
src/idl_parser.cpp src/idl_parser.cpp
src/idl_gen_cpp.cpp src/idl_gen_cpp.cpp
src/idl_gen_java.cpp src/idl_gen_general.cpp
src/idl_gen_csharp.cpp
src/idl_gen_go.cpp src/idl_gen_go.cpp
src/idl_gen_text.cpp src/idl_gen_text.cpp
src/flatc.cpp src/flatc.cpp
......
...@@ -266,13 +266,12 @@ ...@@ -266,13 +266,12 @@
<ClInclude Include="..\..\include\flatbuffers\flatbuffers.h" /> <ClInclude Include="..\..\include\flatbuffers\flatbuffers.h" />
<ClInclude Include="..\..\include\flatbuffers\idl.h" /> <ClInclude Include="..\..\include\flatbuffers\idl.h" />
<ClInclude Include="..\..\include\flatbuffers\util.h" /> <ClInclude Include="..\..\include\flatbuffers\util.h" />
<ClCompile Include="..\..\src\idl_gen_csharp.cpp" /> <ClCompile Include="..\..\src\idl_gen_general.cpp" />
<ClCompile Include="..\..\src\idl_gen_go.cpp"> <ClCompile Include="..\..\src\idl_gen_go.cpp">
<WarningLevel Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Level4</WarningLevel> <WarningLevel Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Level4</WarningLevel>
</ClCompile> </ClCompile>
<ClCompile Include="..\..\src\idl_parser.cpp" /> <ClCompile Include="..\..\src\idl_parser.cpp" />
<ClCompile Include="..\..\src\idl_gen_cpp.cpp" /> <ClCompile Include="..\..\src\idl_gen_cpp.cpp" />
<ClCompile Include="..\..\src\idl_gen_java.cpp" />
<ClCompile Include="..\..\src\idl_gen_text.cpp" /> <ClCompile Include="..\..\src\idl_gen_text.cpp" />
<ClCompile Include="..\..\src\flatc.cpp" /> <ClCompile Include="..\..\src\flatc.cpp" />
</ItemGroup> </ItemGroup>
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
<LocalDebuggerCommandArguments>-j -c -n -g -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments> <LocalDebuggerCommandArguments>-j -c -n -g -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LocalDebuggerCommandArguments>-j -c -g -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments> <LocalDebuggerCommandArguments>-j -c -g -n -b -t monster_test.fbs monsterdata_test.golden</LocalDebuggerCommandArguments>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LocalDebuggerWorkingDirectory>..\..\tests</LocalDebuggerWorkingDirectory> <LocalDebuggerWorkingDirectory>..\..\tests</LocalDebuggerWorkingDirectory>
......
...@@ -32,31 +32,38 @@ namespace flatbuffers { ...@@ -32,31 +32,38 @@ namespace flatbuffers {
// Additionally, Parser::ParseType assumes bool..string is a contiguous range // Additionally, Parser::ParseType assumes bool..string is a contiguous range
// of type tokens. // of type tokens.
#define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \ #define FLATBUFFERS_GEN_TYPES_SCALAR(TD) \
TD(NONE, "", uint8_t, byte, byte) \ TD(NONE, "", uint8_t, byte, byte, byte) \
TD(UTYPE, "", uint8_t, byte, byte) /* begin scalars, ints */ \ TD(UTYPE, "", uint8_t, byte, byte, byte) /* begin scalar/int */ \
TD(BOOL, "bool", uint8_t, byte, byte) \ TD(BOOL, "bool", uint8_t, byte, byte, byte) \
TD(CHAR, "byte", int8_t, byte, int8) \ TD(CHAR, "byte", int8_t, byte, int8, sbyte) \
TD(UCHAR, "ubyte", uint8_t, byte, byte) \ TD(UCHAR, "ubyte", uint8_t, byte, byte, byte) \
TD(SHORT, "short", int16_t, short, int16) \ TD(SHORT, "short", int16_t, short, int16, short) \
TD(USHORT, "ushort", uint16_t, short, uint16) \ TD(USHORT, "ushort", uint16_t, short, uint16, ushort) \
TD(INT, "int", int32_t, int, int32) \ TD(INT, "int", int32_t, int, int32, int) \
TD(UINT, "uint", uint32_t, int, uint32) \ TD(UINT, "uint", uint32_t, int, uint32, uint) \
TD(LONG, "long", int64_t, long, int64) \ TD(LONG, "long", int64_t, long, int64, long) \
TD(ULONG, "ulong", uint64_t, long, uint64) /* end ints */ \ TD(ULONG, "ulong", uint64_t, long, uint64, ulong) /* end int */ \
TD(FLOAT, "float", float, float, float32) /* begin floats */ \ TD(FLOAT, "float", float, float, float32, float) /* begin float */ \
TD(DOUBLE, "double", double, double, float64) /* end floats, scalars */ TD(DOUBLE, "double", double, double, float64, double) /* end float/scalar */
#define FLATBUFFERS_GEN_TYPES_POINTER(TD) \ #define FLATBUFFERS_GEN_TYPES_POINTER(TD) \
TD(STRING, "string", Offset<void>, int, int) \ TD(STRING, "string", Offset<void>, int, int, int) \
TD(VECTOR, "", Offset<void>, int, int) \ TD(VECTOR, "", Offset<void>, int, int, int) \
TD(STRUCT, "", Offset<void>, int, int) \ TD(STRUCT, "", Offset<void>, int, int, int) \
TD(UNION, "", Offset<void>, int, int) TD(UNION, "", Offset<void>, 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. // using these macros, we can now write code dealing with types just once, e.g.
/* /*
switch (type) { switch (type) {
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) \ #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \
case BASE_TYPE_ ## ENUM: \ case BASE_TYPE_ ## ENUM: \
// do something specific to CTYPE here // do something specific to CTYPE here
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
...@@ -73,12 +80,13 @@ switch (type) { ...@@ -73,12 +80,13 @@ switch (type) {
__extension__ // Stop GCC complaining about trailing comma with -Wpendantic. __extension__ // Stop GCC complaining about trailing comma with -Wpendantic.
#endif #endif
enum BaseType { 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) FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef 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), \ static_assert(sizeof(CTYPE) <= sizeof(largest_scalar_t), \
"define largest_scalar_t as " #CTYPE); "define largest_scalar_t as " #CTYPE);
FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
...@@ -327,22 +335,11 @@ class Parser { ...@@ -327,22 +335,11 @@ class Parser {
std::map<std::string, bool> included_files_; std::map<std::string, bool> included_files_;
}; };
// Utility functions for generators: // Utility functions for multiple generators:
// Convert an underscore_based_indentifier in to camelCase. extern std::string MakeCamel(const std::string &in, bool first = true);
// Also uppercases the first character if first is true. extern void GenComment(const std::string &dc, std::string *code_ptr,
inline std::string MakeCamel(const std::string &in, bool first = true) { const char *prefix = "");
std::string s;
for (size_t i = 0; i < in.length(); i++) {
if (!i && first)
s += static_cast<char>(toupper(in[0]));
else if (in[i] == '_' && i + 1 < in.length())
s += static_cast<char>(toupper(in[++i]));
else
s += in[i];
}
return s;
}
// Container of options that may apply to any of the source/text generators. // Container of options that may apply to any of the source/text generators.
struct GeneratorOptions { struct GeneratorOptions {
...@@ -351,8 +348,14 @@ struct GeneratorOptions { ...@@ -351,8 +348,14 @@ struct GeneratorOptions {
bool output_enum_identifiers; bool output_enum_identifiers;
bool prefixed_enums; 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), 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 // Generate text (JSON) from a given FlatBuffer, and a given Parser
...@@ -397,6 +400,12 @@ extern bool GenerateCSharp(const Parser &parser, ...@@ -397,6 +400,12 @@ extern bool GenerateCSharp(const Parser &parser,
const std::string &file_name, const std::string &file_name,
const GeneratorOptions &opts); 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 } // namespace flatbuffers
......
...@@ -25,6 +25,7 @@ namespace FlatBuffers ...@@ -25,6 +25,7 @@ namespace FlatBuffers
public class ByteBuffer public class ByteBuffer
{ {
private readonly byte[] _buffer; private readonly byte[] _buffer;
private int _pos; // Must track start of the buffer.
public int Length { get { return _buffer.Length; } } public int Length { get { return _buffer.Length; } }
...@@ -33,8 +34,11 @@ namespace FlatBuffers ...@@ -33,8 +34,11 @@ namespace FlatBuffers
public ByteBuffer(byte[] buffer) public ByteBuffer(byte[] buffer)
{ {
_buffer = buffer; _buffer = buffer;
_pos = 0;
} }
public int position() { return _pos; }
protected void WriteLittleEndian(int offset, byte[] data) protected void WriteLittleEndian(int offset, byte[] data)
{ {
if (!BitConverter.IsLittleEndian) if (!BitConverter.IsLittleEndian)
...@@ -42,6 +46,7 @@ namespace FlatBuffers ...@@ -42,6 +46,7 @@ namespace FlatBuffers
data = data.Reverse().ToArray(); data = data.Reverse().ToArray();
} }
Buffer.BlockCopy(data, 0, _buffer, offset, data.Length); Buffer.BlockCopy(data, 0, _buffer, offset, data.Length);
_pos = offset;
} }
protected byte[] ReadLittleEndian(int offset, int count) protected byte[] ReadLittleEndian(int offset, int count)
...@@ -62,10 +67,18 @@ namespace FlatBuffers ...@@ -62,10 +67,18 @@ namespace FlatBuffers
throw new ArgumentOutOfRangeException(); 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) public void PutByte(int offset, byte value)
{ {
AssertOffsetAndLength(offset, sizeof(byte)); AssertOffsetAndLength(offset, sizeof(byte));
_buffer[offset] = value; _buffer[offset] = value;
_pos = offset;
} }
public void PutShort(int offset, short value) public void PutShort(int offset, short value)
...@@ -74,18 +87,36 @@ namespace FlatBuffers ...@@ -74,18 +87,36 @@ namespace FlatBuffers
WriteLittleEndian(offset, BitConverter.GetBytes(value)); 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) public void PutInt(int offset, int value)
{ {
AssertOffsetAndLength(offset, sizeof(int)); AssertOffsetAndLength(offset, sizeof(int));
WriteLittleEndian(offset, BitConverter.GetBytes(value)); 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) public void PutLong(int offset, long value)
{ {
AssertOffsetAndLength(offset, sizeof(long)); AssertOffsetAndLength(offset, sizeof(long));
WriteLittleEndian(offset, BitConverter.GetBytes(value)); 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) public void PutFloat(int offset, float value)
{ {
AssertOffsetAndLength(offset, sizeof(float)); AssertOffsetAndLength(offset, sizeof(float));
...@@ -98,6 +129,12 @@ namespace FlatBuffers ...@@ -98,6 +129,12 @@ namespace FlatBuffers
WriteLittleEndian(offset, BitConverter.GetBytes(value)); WriteLittleEndian(offset, BitConverter.GetBytes(value));
} }
public sbyte GetSbyte(int index)
{
AssertOffsetAndLength(index, sizeof(sbyte));
return (sbyte)_buffer[index];
}
public byte Get(int index) public byte Get(int index)
{ {
AssertOffsetAndLength(index, sizeof(byte)); AssertOffsetAndLength(index, sizeof(byte));
...@@ -111,6 +148,13 @@ namespace FlatBuffers ...@@ -111,6 +148,13 @@ namespace FlatBuffers
return value; 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) public int GetInt(int index)
{ {
var tmp = ReadLittleEndian(index, sizeof(int)); var tmp = ReadLittleEndian(index, sizeof(int));
...@@ -118,6 +162,13 @@ namespace FlatBuffers ...@@ -118,6 +162,13 @@ namespace FlatBuffers
return value; 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) public long GetLong(int index)
{ {
var tmp = ReadLittleEndian(index, sizeof(long)); var tmp = ReadLittleEndian(index, sizeof(long));
...@@ -125,6 +176,13 @@ namespace FlatBuffers ...@@ -125,6 +176,13 @@ namespace FlatBuffers
return value; 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) public float GetFloat(int index)
{ {
var tmp = ReadLittleEndian(index, sizeof(float)); var tmp = ReadLittleEndian(index, sizeof(float));
......
...@@ -50,7 +50,7 @@ namespace FlatBuffers ...@@ -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) public void Pad(int size)
{ {
...@@ -105,6 +105,11 @@ namespace FlatBuffers ...@@ -105,6 +105,11 @@ namespace FlatBuffers
Pad(alignSize); Pad(alignSize);
} }
public void PutSbyte(sbyte x)
{
_bb.PutSbyte(_space -= sizeof(sbyte), x);
}
public void PutByte(byte x) public void PutByte(byte x)
{ {
_bb.PutByte(_space -= sizeof(byte), x); _bb.PutByte(_space -= sizeof(byte), x);
...@@ -115,16 +120,31 @@ namespace FlatBuffers ...@@ -115,16 +120,31 @@ namespace FlatBuffers
_bb.PutShort(_space -= sizeof(short), x); _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); _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); _bb.PutLong(_space -= sizeof(long), x);
} }
public void PutUlong(ulong x)
{
_bb.PutUlong(_space -= sizeof(ulong), x);
}
public void PutFloat(float x) public void PutFloat(float x)
{ {
_bb.PutFloat(_space -= sizeof(float), x); _bb.PutFloat(_space -= sizeof(float), x);
...@@ -137,10 +157,14 @@ namespace FlatBuffers ...@@ -137,10 +157,14 @@ namespace FlatBuffers
// Adds a scalar to the buffer, properly aligned, and the buffer grown // Adds a scalar to the buffer, properly aligned, and the buffer grown
// if needed. // 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 AddByte(byte x) { Prep(sizeof(byte), 0); PutByte(x); }
public void AddShort(short x) { Prep(sizeof(short), 0); PutShort(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 AddUshort(ushort x) { Prep(sizeof(ushort), 0); PutUshort(x); }
public void AddLong(long x) { Prep(sizeof(long), 0); PutInt64(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 AddFloat(float x) { Prep(sizeof(float), 0); PutFloat(x); }
public void AddDouble(double x) { Prep(sizeof(double), 0); public void AddDouble(double x) { Prep(sizeof(double), 0);
PutDouble(x); } PutDouble(x); }
...@@ -151,11 +175,11 @@ namespace FlatBuffers ...@@ -151,11 +175,11 @@ namespace FlatBuffers
public void AddOffset(int off) public void AddOffset(int off)
{ {
Prep(sizeof(int), 0); // Ensure alignment is already done. Prep(sizeof(int), 0); // Ensure alignment is already done.
if (off > Offset) if (off > Offset())
throw new ArgumentException(); throw new ArgumentException();
off = Offset - off + sizeof(int); off = Offset() - off + sizeof(int);
PutInt32(off); PutInt(off);
} }
public void StartVector(int elemSize, int count, int alignment) public void StartVector(int elemSize, int count, int alignment)
...@@ -168,8 +192,8 @@ namespace FlatBuffers ...@@ -168,8 +192,8 @@ namespace FlatBuffers
public int EndVector() public int EndVector()
{ {
PutInt32(_vectorNumElems); PutInt(_vectorNumElems);
return Offset; return Offset();
} }
public void Nested(int obj) public void Nested(int obj)
...@@ -177,7 +201,7 @@ namespace FlatBuffers ...@@ -177,7 +201,7 @@ namespace FlatBuffers
// Structs are always stored inline, so need to be created right // Structs are always stored inline, so need to be created right
// where they are used. You'll get this assert if you created it // where they are used. You'll get this assert if you created it
// elsewhere. // elsewhere.
if (obj != Offset) if (obj != Offset())
throw new Exception( throw new Exception(
"FlatBuffers: struct must be serialized inline."); "FlatBuffers: struct must be serialized inline.");
} }
...@@ -195,7 +219,7 @@ namespace FlatBuffers ...@@ -195,7 +219,7 @@ namespace FlatBuffers
{ {
NotNested(); NotNested();
_vtable = new int[numfields]; _vtable = new int[numfields];
_objectStart = Offset; _objectStart = Offset();
} }
...@@ -203,14 +227,18 @@ namespace FlatBuffers ...@@ -203,14 +227,18 @@ namespace FlatBuffers
// buffer. // buffer.
public void Slot(int voffset) 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` // 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 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 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 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 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 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); } } public void AddOffset(int o, int x, int d) { if (x != d) { AddOffset(x); Slot(o); } }
...@@ -245,7 +273,7 @@ namespace FlatBuffers ...@@ -245,7 +273,7 @@ namespace FlatBuffers
"Flatbuffers: calling endObject without a startObject"); "Flatbuffers: calling endObject without a startObject");
AddInt((int)0); AddInt((int)0);
var vtableloc = Offset; var vtableloc = Offset();
// Write out the current vtable. // Write out the current vtable.
for (int i = _vtable.Length - 1; i >= 0 ; i--) { for (int i = _vtable.Length - 1; i >= 0 ; i--) {
// Offset relative to the start of the table. // Offset relative to the start of the table.
...@@ -298,9 +326,9 @@ namespace FlatBuffers ...@@ -298,9 +326,9 @@ namespace FlatBuffers
_vtables = newvtables; _vtables = newvtables;
}; };
_vtables[_numVtables++] = Offset; _vtables[_numVtables++] = Offset();
// Point table to current vtable. // Point table to current vtable.
_bb.PutInt(_bb.Length - vtableloc, Offset - vtableloc); _bb.PutInt(_bb.Length - vtableloc, Offset() - vtableloc);
} }
_vtable = null; _vtable = null;
...@@ -313,17 +341,13 @@ namespace FlatBuffers ...@@ -313,17 +341,13 @@ namespace FlatBuffers
AddOffset(rootTable); AddOffset(rootTable);
} }
public ByteBuffer Data { get { return _bb; }} public ByteBuffer DataBuffer() { return _bb; }
// The FlatBuffer data doesn't start at offset 0 in the ByteBuffer:
public int DataStart { get { return _space; } }
// Utility function for copying a byte array that starts at 0. // Utility function for copying a byte array that starts at 0.
public byte[] SizedByteArray() public byte[] SizedByteArray()
{ {
var newArray = new byte[_bb.Data.Length]; 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); _bb.Data.Length);
return newArray; return newArray;
} }
......
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>FlatBuffers</id>
<version>1.0.0-alpha00003</version>
<authors>Google Inc</authors>
<description>A .NET port of Google Inc's FlatBuffers project.</description>
<language>en-US</language>
<projectUrl>https://github.com/evolutional/flatbuffers</projectUrl>
<licenseUrl>http://www.apache.org/licenses/LICENSE-2.0</licenseUrl>
</metadata>
</package>
\ No newline at end of file
...@@ -74,14 +74,14 @@ namespace FlatBuffers ...@@ -74,14 +74,14 @@ namespace FlatBuffers
return t; 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) if (ident.Length != FlatBufferConstants.FileIdentifierLength)
throw new ArgumentException("FlatBuffers: file identifier must be length " + FlatBufferConstants.FileIdentifierLength, "ident"); throw new ArgumentException("FlatBuffers: file identifier must be length " + FlatBufferConstants.FileIdentifierLength, "ident");
for (var i = 0; i < FlatBufferConstants.FileIdentifierLength; i++) 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; return true;
......
...@@ -62,21 +62,28 @@ struct Generator { ...@@ -62,21 +62,28 @@ struct Generator {
const flatbuffers::GeneratorOptions &opts); const flatbuffers::GeneratorOptions &opts);
const char *extension; const char *extension;
const char *name; const char *name;
flatbuffers::GeneratorOptions::Language lang;
const char *help; const char *help;
}; };
const Generator generators[] = { const Generator generators[] = {
{ flatbuffers::GenerateBinary, "b", "binary", { flatbuffers::GenerateBinary, "b", "binary",
flatbuffers::GeneratorOptions::kMAX,
"Generate wire format binaries for any data definitions" }, "Generate wire format binaries for any data definitions" },
{ flatbuffers::GenerateTextFile, "t", "text", { flatbuffers::GenerateTextFile, "t", "text",
flatbuffers::GeneratorOptions::kMAX,
"Generate text output for any data definitions" }, "Generate text output for any data definitions" },
{ flatbuffers::GenerateCPP, "c", "C++", { flatbuffers::GenerateCPP, "c", "C++",
flatbuffers::GeneratorOptions::kMAX,
"Generate C++ headers for tables/structs" }, "Generate C++ headers for tables/structs" },
{ flatbuffers::GenerateGo, "g", "Go", { flatbuffers::GenerateGo, "g", "Go",
flatbuffers::GeneratorOptions::kMAX,
"Generate Go files for tables/structs" }, "Generate Go files for tables/structs" },
{ flatbuffers::GenerateJava, "j", "Java", { flatbuffers::GenerateGeneral, "j", "Java",
flatbuffers::GeneratorOptions::kJava,
"Generate Java classes for tables/structs" }, "Generate Java classes for tables/structs" },
{ flatbuffers::GenerateCSharp, "n", "C#", { flatbuffers::GenerateGeneral, "n", "C#",
flatbuffers::GeneratorOptions::kCSharp,
"Generate C# classes for tables/structs" } "Generate C# classes for tables/structs" }
}; };
...@@ -194,6 +201,7 @@ int main(int argc, const char *argv[]) { ...@@ -194,6 +201,7 @@ int main(int argc, const char *argv[]) {
for (size_t i = 0; i < num_generators; ++i) { for (size_t i = 0; i < num_generators; ++i) {
if (generator_enabled[i]) { if (generator_enabled[i]) {
flatbuffers::EnsureDirExists(output_path); flatbuffers::EnsureDirExists(output_path);
opts.lang = generators[i].lang;
if (!generators[i].generate(parser, output_path, filebase, opts)) { if (!generators[i].generate(parser, output_path, filebase, opts)) {
Error((std::string("Unable to generate ") + Error((std::string("Unable to generate ") +
generators[i].name + generators[i].name +
......
...@@ -26,7 +26,7 @@ namespace cpp { ...@@ -26,7 +26,7 @@ namespace cpp {
// Return a C++ type from the table in idl.h // Return a C++ type from the table in idl.h
static std::string GenTypeBasic(const Type &type) { static std::string GenTypeBasic(const Type &type) {
static const char *ctypename[] = { 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) FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
}; };
...@@ -96,16 +96,6 @@ static std::string GenTypeGet(const Parser &parser, const Type &type, ...@@ -96,16 +96,6 @@ static std::string GenTypeGet(const Parser &parser, const Type &type,
: beforeptr + GenTypePointer(parser, type) + afterptr; : 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, static std::string GenEnumVal(const EnumDef &enum_def, const EnumVal &enum_val,
const GeneratorOptions &opts) { const GeneratorOptions &opts) {
return opts.prefixed_enums ? enum_def.name + "_" + enum_val.name return opts.prefixed_enums ? enum_def.name + "_" + enum_val.name
......
/*
* 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
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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. * limitations under the License.
*/ */
...@@ -21,25 +21,116 @@ ...@@ -21,25 +21,116 @@
#include "flatbuffers/util.h" #include "flatbuffers/util.h"
namespace flatbuffers { namespace flatbuffers {
namespace java {
static std::string GenTypeBasic(const Type &type) { // Convert an underscore_based_indentifier in to camelCase.
static const char *ctypename[] = { // Also uppercases the first character if first is true.
#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE) #JTYPE, 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<char>(toupper(in[0]));
else if (in[i] == '_' && i + 1 < in.length())
s += static_cast<char>(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<char>(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) FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef 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) { switch (type.base_type) {
case BASE_TYPE_STRING: case BASE_TYPE_STRING:
return "String"; return lang.string_type;
case BASE_TYPE_VECTOR: case BASE_TYPE_VECTOR:
return GenTypeGet(type.VectorType()); return GenTypeGet(lang, type.VectorType());
case BASE_TYPE_STRUCT: case BASE_TYPE_STRUCT:
return type.struct_def->name; return type.struct_def->name;
case BASE_TYPE_UNION: case BASE_TYPE_UNION:
...@@ -49,38 +140,32 @@ static std::string GenTypePointer(const Type &type) { ...@@ -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) return IsScalar(type.base_type)
? GenTypeBasic(type) ? GenTypeBasic(lang, type)
: GenTypePointer(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; std::string &code = *code_ptr;
if (enum_def.generated) return; if (enum_def.generated) return;
// Generate enum definitions of the form: // Generate enum definitions of the form:
// public static final int name = value; // public static (final) int name = value;
// We use ints rather than the Java Enum feature, because we want them // 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. // to map directly to how they're used in C/C++ and file formats.
// That, and Java Enums are expensive, and not universally liked. // That, and Java Enums are expensive, and not universally liked.
GenComment(enum_def.doc_comment, code_ptr); 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(); for (auto it = enum_def.vals.vec.begin();
it != enum_def.vals.vec.end(); it != enum_def.vals.vec.end();
++it) { ++it) {
auto &ev = **it; auto &ev = **it;
GenComment(ev.doc_comment, code_ptr, " "); 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 += " " + ev.name + " = ";
code += NumToString(ev.value) + ";\n"; code += NumToString(ev.value) + ";\n";
} }
...@@ -88,30 +173,33 @@ static void GenEnum(EnumDef &enum_def, std::string *code_ptr) { ...@@ -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. // 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) { switch (type.base_type) {
case BASE_TYPE_STRING: return "__string"; case BASE_TYPE_STRING: return "__string";
case BASE_TYPE_STRUCT: return "__struct"; case BASE_TYPE_STRUCT: return "__struct";
case BASE_TYPE_UNION: return "__union"; case BASE_TYPE_UNION: return "__union";
case BASE_TYPE_VECTOR: return GenGetter(type.VectorType()); case BASE_TYPE_VECTOR: return GenGetter(lang, type.VectorType());
default: default:
return "bb.get" + (SizeOf(type.base_type) > 1 return "bb." + FunctionStart(lang, 'G') + "et" +
? MakeCamel(GenTypeGet(type)) (GenTypeBasic(lang, type) != "byte"
: ""); ? MakeCamel(GenTypeGet(lang, type))
: "");
} }
} }
// Returns the method name for use with add/put calls. // 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) return IsScalar(type.base_type)
? MakeCamel(GenTypeBasic(type)) ? MakeCamel(GenTypeBasic(lang, type))
: (IsStruct(type) ? "Struct" : "Offset"); : (IsStruct(type) ? "Struct" : "Offset");
} }
// Recursively generate arguments for a constructor, to deal with nested // Recursively generate arguments for a constructor, to deal with nested
// structs. // structs.
static void GenStructArgs(const StructDef &struct_def, std::string *code_ptr, static void GenStructArgs(const LanguageParameters &lang,
const char *nameprefix) { const StructDef &struct_def,
std::string *code_ptr, const char *nameprefix) {
std::string &code = *code_ptr; std::string &code = *code_ptr;
for (auto it = struct_def.fields.vec.begin(); for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); it != struct_def.fields.vec.end();
...@@ -121,11 +209,11 @@ static void GenStructArgs(const StructDef &struct_def, std::string *code_ptr, ...@@ -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 // Generate arguments for a struct inside a struct. To ensure names
// don't clash, and to make it obvious these arguments are constructing // don't clash, and to make it obvious these arguments are constructing
// a nested struct, prefix the name with the struct name. // 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()); (field.value.type.struct_def->name + "_").c_str());
} else { } else {
code += ", " + GenTypeBasic(field.value.type) + " " + nameprefix; code += ", " + GenTypeBasic(lang, field.value.type) + " " + nameprefix;
code += MakeCamel(field.name, false); code += MakeCamel(field.name, lang.first_camel_upper);
} }
} }
} }
...@@ -133,29 +221,33 @@ static void GenStructArgs(const StructDef &struct_def, std::string *code_ptr, ...@@ -133,29 +221,33 @@ static void GenStructArgs(const StructDef &struct_def, std::string *code_ptr,
// Recusively generate struct construction statements of the form: // Recusively generate struct construction statements of the form:
// builder.putType(name); // builder.putType(name);
// and insert manual padding. // and insert manual padding.
static void GenStructBody(const StructDef &struct_def, std::string *code_ptr, static void GenStructBody(const LanguageParameters &lang,
const char *nameprefix) { const StructDef &struct_def,
std::string *code_ptr, const char *nameprefix) {
std::string &code = *code_ptr; 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"; code += NumToString(struct_def.bytesize) + ");\n";
for (auto it = struct_def.fields.vec.rbegin(); for (auto it = struct_def.fields.vec.rbegin();
it != struct_def.fields.vec.rend(); it != struct_def.fields.vec.rend(); ++it) {
++it) {
auto &field = **it; auto &field = **it;
if (field.padding) if (field.padding) {
code += " builder.pad(" + NumToString(field.padding) + ");\n"; code += " builder." + FunctionStart(lang, 'P') + "ad(";
code += NumToString(field.padding) + ");\n";
}
if (IsStruct(field.value.type)) { 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()); (field.value.type.struct_def->name + "_").c_str());
} else { } else {
code += " builder.put" + GenMethod(field.value.type) + "("; code += " builder." + FunctionStart(lang, 'P') + "ut";
code += nameprefix + MakeCamel(field.name, false) + ");\n"; 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, static void GenStruct(const LanguageParameters &lang, const Parser &parser,
std::string *code_ptr) { StructDef &struct_def, std::string *code_ptr) {
if (struct_def.generated) return; if (struct_def.generated) return;
std::string &code = *code_ptr; std::string &code = *code_ptr;
...@@ -166,22 +258,24 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, ...@@ -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; // int o = __offset(offset); return o != 0 ? bb.getType(o + i) : default;
// } // }
GenComment(struct_def.doc_comment, code_ptr); 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 += struct_def.fixed ? "Struct" : "Table";
code += " {\n"; code += " {\n";
if (!struct_def.fixed) { if (!struct_def.fixed) {
// Generate a special accessor for the table that when used as the root // Generate a special accessor for the table that when used as the root
// of a FlatBuffer // of a FlatBuffer
code += " public static " + struct_def.name + " getRootAs"; code += " public static " + struct_def.name + " ";
code += struct_def.name; code += FunctionStart(lang, 'G') + "etRootAs" + struct_def.name;
code += "(ByteBuffer _bb) { "; code += "(ByteBuffer _bb) { ";
code += "_bb.order(ByteOrder.LITTLE_ENDIAN); "; code += lang.set_bb_byteorder;
code += "return (new " + struct_def.name; 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.root_struct_def == &struct_def) {
if (parser.file_identifier_.length()) { if (parser.file_identifier_.length()) {
// Check if a buffer has the identifier. // 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 += "BufferHasIdentifier(ByteBuffer _bb) { return ";
code += "__has_identifier(_bb, \"" + parser.file_identifier_; code += "__has_identifier(_bb, \"" + parser.file_identifier_;
code += "\"); }\n"; code += "\"); }\n";
...@@ -199,37 +293,42 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, ...@@ -199,37 +293,42 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
auto &field = **it; auto &field = **it;
if (field.deprecated) continue; if (field.deprecated) continue;
GenComment(field.doc_comment, code_ptr, " "); 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 + " " + 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. // Generate the accessors that don't do object reuse.
if (field.value.type.base_type == BASE_TYPE_STRUCT) { if (field.value.type.base_type == BASE_TYPE_STRUCT) {
// Calls the accessor that takes an accessor object with a new object. // 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 += "(new ";
code += type_name + "()); }\n"; code += type_name + "()); }\n";
} else if (field.value.type.base_type == BASE_TYPE_VECTOR && } else if (field.value.type.base_type == BASE_TYPE_VECTOR &&
field.value.type.element == BASE_TYPE_STRUCT) { field.value.type.element == BASE_TYPE_STRUCT) {
// Accessors for vectors of structs also take accessor objects, this // Accessors for vectors of structs also take accessor objects, this
// generates a variant without that argument. // 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 += "(new ";
code += type_name + "(), j); }\n"; code += type_name + "(), j); }\n";
} }
std::string getter = GenGetter(field.value.type); std::string getter = GenGetter(lang, field.value.type);
code += method_start + "("; code += method_start + "(";
// Most field accessors need to retrieve and test the field offset first, // Most field accessors need to retrieve and test the field offset first,
// this is the prefix code for that: // this is the prefix code for that:
auto offset_prefix = ") { int o = __offset(" + auto offset_prefix = ") { int o = __offset(" +
NumToString(field.value.offset) + NumToString(field.value.offset) +
"); return o != 0 ? "; "); return o != 0 ? ";
std::string default_cast = "";
if (lang.language == GeneratorOptions::kCSharp)
default_cast = "(" + type_name + ")";
if (IsScalar(field.value.type.base_type)) { if (IsScalar(field.value.type.base_type)) {
if (struct_def.fixed) { if (struct_def.fixed) {
code += ") { return " + getter; code += ") { return " + getter;
code += "(bb_pos + " + NumToString(field.value.offset) + ")"; code += "(bb_pos + " + NumToString(field.value.offset) + ")";
} else { } else {
code += offset_prefix + getter; code += offset_prefix + getter;
code += "(o + bb_pos) : " + field.value.constant; code += "(o + bb_pos) : " + default_cast + field.value.constant;
} }
} else { } else {
switch (field.value.type.base_type) { switch (field.value.type.base_type) {
...@@ -268,7 +367,9 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, ...@@ -268,7 +367,9 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
code += index; code += index;
} }
code += ") : "; code += ") : ";
code += IsScalar(field.value.type.element) ? "0" : "null"; code += IsScalar(field.value.type.element)
? default_cast + "0"
: "null";
break; break;
} }
case BASE_TYPE_UNION: case BASE_TYPE_UNION:
...@@ -281,13 +382,15 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, ...@@ -281,13 +382,15 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
} }
code += "; }\n"; code += "; }\n";
if (field.value.type.base_type == BASE_TYPE_VECTOR) { if (field.value.type.base_type == BASE_TYPE_VECTOR) {
code += " public int " + MakeCamel(field.name, false) + "Length("; code += " public int " + MakeCamel(field.name, lang.first_camel_upper);
code += offset_prefix; code += "Length(" + offset_prefix;
code += "__vector_len(o) : 0; }\n"; code += "__vector_len(o) : 0; }\n";
} }
if (field.value.type.base_type == BASE_TYPE_VECTOR || if ((field.value.type.base_type == BASE_TYPE_VECTOR ||
field.value.type.base_type == BASE_TYPE_STRING) { field.value.type.base_type == BASE_TYPE_STRING) &&
code += " public ByteBuffer " + MakeCamel(field.name, false); lang.language == GeneratorOptions::kJava) {
code += " public ByteBuffer ";
code += MakeCamel(field.name, lang.first_camel_upper);
code += "AsByteBuffer() { return __vector_as_bytebuffer("; code += "AsByteBuffer() { return __vector_as_bytebuffer(";
code += NumToString(field.value.offset) + ", "; code += NumToString(field.value.offset) + ", ";
code += NumToString(field.value.type.base_type == BASE_TYPE_STRING ? 1 : code += NumToString(field.value.type.base_type == BASE_TYPE_STRING ? 1 :
...@@ -298,31 +401,36 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, ...@@ -298,31 +401,36 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
code += "\n"; code += "\n";
if (struct_def.fixed) { if (struct_def.fixed) {
// create a struct constructor function // create a struct constructor function
code += " public static int create" + struct_def.name; code += " public static int " + FunctionStart(lang, 'C') + "reate";
code += "(FlatBufferBuilder builder"; code += struct_def.name + "(FlatBufferBuilder builder";
GenStructArgs(struct_def, code_ptr, ""); GenStructArgs(lang, struct_def, code_ptr, "");
code += ") {\n"; code += ") {\n";
GenStructBody(struct_def, code_ptr, ""); GenStructBody(lang, struct_def, code_ptr, "");
code += " return builder.offset();\n }\n"; code += " return builder.";
code += FunctionStart(lang, 'O') + "ffset();\n }\n";
} else { } else {
// Create a set of static methods that allow table construction, // Create a set of static methods that allow table construction,
// of the form: // of the form:
// public static void addName(FlatBufferBuilder builder, short name) // public static void addName(FlatBufferBuilder builder, short name)
// { builder.addShort(id, name, default); } // { builder.addShort(id, name, default); }
code += " public static void start" + struct_def.name; code += " public static void " + FunctionStart(lang, 'S') + "tart";
code += "(FlatBufferBuilder builder) { builder.startObject("; code += struct_def.name;
code += "(FlatBufferBuilder builder) { builder.";
code += FunctionStart(lang, 'S') + "tartObject(";
code += NumToString(struct_def.fields.vec.size()) + "); }\n"; code += NumToString(struct_def.fields.vec.size()) + "); }\n";
for (auto it = struct_def.fields.vec.begin(); for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); it != struct_def.fields.vec.end();
++it) { ++it) {
auto &field = **it; auto &field = **it;
if (field.deprecated) continue; if (field.deprecated) continue;
code += " public static void add" + MakeCamel(field.name); code += " public static void " + FunctionStart(lang, 'A') + "dd";
code += "(FlatBufferBuilder builder, " + GenTypeBasic(field.value.type); code += MakeCamel(field.name);
code += "(FlatBufferBuilder builder, ";
code += GenTypeBasic(lang, field.value.type);
auto argname = MakeCamel(field.name, false); auto argname = MakeCamel(field.name, false);
if (!IsScalar(field.value.type.base_type)) argname += "Offset"; if (!IsScalar(field.value.type.base_type)) argname += "Offset";
code += " " + argname + ") { builder.add"; code += " " + argname + ") { builder." + FunctionStart(lang, 'A') + "dd";
code += GenMethod(field.value.type) + "("; code += GenMethod(lang, field.value.type) + "(";
code += NumToString(it - struct_def.fields.vec.begin()) + ", "; code += NumToString(it - struct_def.fields.vec.begin()) + ", ";
code += argname + ", " + field.value.constant; code += argname + ", " + field.value.constant;
code += "); }\n"; code += "); }\n";
...@@ -332,30 +440,40 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, ...@@ -332,30 +440,40 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
auto elem_size = InlineSize(vector_type); auto elem_size = InlineSize(vector_type);
if (!IsStruct(vector_type)) { if (!IsStruct(vector_type)) {
// Generate a method to create a vector from a Java array. // 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 += "Vector(FlatBufferBuilder builder, ";
code += GenTypeBasic(vector_type) + "[] data) "; code += GenTypeBasic(lang, vector_type) + "[] data) ";
code += "{ builder.startVector("; code += "{ builder." + FunctionStart(lang, 'S') + "tartVector(";
code += NumToString(elem_size); code += NumToString(elem_size);
code += ", data.length, " + NumToString(alignment); code += ", data." + FunctionStart(lang, 'L') + "ength, ";
code += "); for (int i = data.length - 1; i >= 0; i--) builder.add"; code += NumToString(alignment);
code += GenMethod(vector_type); code += "); for (int i = data.";
code += "(data[i]); return builder.endVector(); }\n"; 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. // 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 += "Vector(FlatBufferBuilder builder, int numElems) ";
code += "{ builder.startVector("; code += "{ builder." + FunctionStart(lang, 'S') + "tartVector(";
code += NumToString(elem_size); code += NumToString(elem_size);
code += ", numElems, " + NumToString(alignment); code += ", numElems, " + NumToString(alignment);
code += "); }\n"; } code += "); }\n";
}
} }
code += " public static int end" + struct_def.name; code += " public static int ";
code += "(FlatBufferBuilder builder) { return builder.endObject(); }\n"; 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) { 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 += "Buffer(FlatBufferBuilder builder, int offset) { ";
code += "builder.finish(offset"; code += "builder." + FunctionStart(lang, 'F') + "inish(offset";
if (parser.file_identifier_.length()) if (parser.file_identifier_.length())
code += ", \"" + parser.file_identifier_ + "\""; code += ", \"" + parser.file_identifier_ + "\"";
code += "); }\n"; code += "); }\n";
...@@ -364,58 +482,58 @@ static void GenStruct(const Parser &parser, StructDef &struct_def, ...@@ -364,58 +482,58 @@ static void GenStruct(const Parser &parser, StructDef &struct_def,
code += "};\n\n"; 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. // declaration boilerplate.
static bool SaveClass(const Parser &parser, const Definition &def, static bool SaveClass(const LanguageParameters &lang, const Parser &parser,
const std::string &classcode, const std::string &path, const Definition &def, const std::string &classcode,
bool needs_imports) { const std::string &path, bool needs_includes) {
if (!classcode.length()) return true; if (!classcode.length()) return true;
std::string namespace_java; std::string namespace_general;
std::string namespace_dir = path; std::string namespace_dir = path;
auto &namespaces = parser.namespaces_.back()->components; auto &namespaces = parser.namespaces_.back()->components;
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) { for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
if (namespace_java.length()) { if (namespace_general.length()) {
namespace_java += "."; namespace_general += ".";
namespace_dir += kPathSeparator; namespace_dir += kPathSeparator;
} }
namespace_java += *it; namespace_general += *it;
namespace_dir += *it; namespace_dir += *it;
} }
EnsureDirExists(namespace_dir); EnsureDirExists(namespace_dir);
std::string code = "// automatically generated, do not modify\n\n"; std::string code = "// automatically generated, do not modify\n\n";
code += "package " + namespace_java + ";\n\n"; code += lang.namespace_ident + namespace_general + lang.namespace_begin;
if (needs_imports) { code += "\n\n";
code += "import java.nio.*;\nimport java.lang.*;\nimport java.util.*;\n"; if (needs_includes) code += lang.includes;
code += "import com.google.flatbuffers.*;\n\n";
}
code += classcode; 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); 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, assert(opts.lang <= GeneratorOptions::kMAX);
const std::string &path, auto lang = language_parameters[opts.lang];
const std::string & /*file_name*/,
const GeneratorOptions & /*opts*/) {
using namespace java;
for (auto it = parser.enums_.vec.begin(); for (auto it = parser.enums_.vec.begin();
it != parser.enums_.vec.end(); ++it) { it != parser.enums_.vec.end(); ++it) {
std::string enumcode; std::string enumcode;
GenEnum(**it, &enumcode); GenEnum(lang, **it, &enumcode);
if (!SaveClass(parser, **it, enumcode, path, false)) if (!SaveClass(lang, parser, **it, enumcode, path, false))
return false; return false;
} }
for (auto it = parser.structs_.vec.begin(); for (auto it = parser.structs_.vec.begin();
it != parser.structs_.vec.end(); ++it) { it != parser.structs_.vec.end(); ++it) {
std::string declcode; std::string declcode;
GenStruct(parser, **it, &declcode); GenStruct(lang, parser, **it, &declcode);
if (!SaveClass(parser, **it, declcode, path, true)) if (!SaveClass(lang, parser, **it, declcode, path, true))
return false; return false;
} }
......
...@@ -612,7 +612,7 @@ static bool SaveType(const Parser &parser, const Definition &def, ...@@ -612,7 +612,7 @@ static bool SaveType(const Parser &parser, const Definition &def,
static std::string GenTypeBasic(const Type &type) { static std::string GenTypeBasic(const Type &type) {
static const char *ctypename[] = { 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) FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
}; };
......
...@@ -159,7 +159,7 @@ template<> void Print<const void *>(const void *val, ...@@ -159,7 +159,7 @@ template<> void Print<const void *>(const void *val,
type = type.VectorType(); type = type.VectorType();
// Call PrintVector above specifically for each element type: // Call PrintVector above specifically for each element type:
switch (type.base_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: \ case BASE_TYPE_ ## ENUM: \
PrintVector<CTYPE>( \ PrintVector<CTYPE>( \
*reinterpret_cast<const Vector<CTYPE> *>(val), \ *reinterpret_cast<const Vector<CTYPE> *>(val), \
...@@ -225,7 +225,7 @@ static void GenStruct(const StructDef &struct_def, const Table *table, ...@@ -225,7 +225,7 @@ static void GenStruct(const StructDef &struct_def, const Table *table,
OutputIdentifier(fd.name, opts, _text); OutputIdentifier(fd.name, opts, _text);
text += ": "; text += ": ";
switch (fd.value.type.base_type) { 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: \ case BASE_TYPE_ ## ENUM: \
GenField<CTYPE>(fd, table, struct_def.fixed, \ GenField<CTYPE>(fd, table, struct_def.fixed, \
opts, indent + Indent(opts), _text); \ opts, indent + Indent(opts), _text); \
...@@ -233,7 +233,7 @@ static void GenStruct(const StructDef &struct_def, const Table *table, ...@@ -233,7 +233,7 @@ static void GenStruct(const StructDef &struct_def, const Table *table,
FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD) FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
// Generate drop-thru case statements for all pointer types: // 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: case BASE_TYPE_ ## ENUM:
FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD) FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
......
...@@ -23,14 +23,15 @@ ...@@ -23,14 +23,15 @@
namespace flatbuffers { namespace flatbuffers {
const char *const kTypeNames[] = { 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) FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
nullptr nullptr
}; };
const char kTypeSizes[] = { 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) FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
}; };
...@@ -92,7 +93,8 @@ enum { ...@@ -92,7 +93,8 @@ enum {
#define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME = VALUE, #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME = VALUE,
FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN) FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
#undef 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) FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
}; };
...@@ -102,7 +104,7 @@ static std::string TokenToString(int t) { ...@@ -102,7 +104,7 @@ static std::string TokenToString(int t) {
#define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) STRING, #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) STRING,
FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN) FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN)
#undef 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) FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
#undef FLATBUFFERS_TD #undef FLATBUFFERS_TD
}; };
...@@ -200,7 +202,7 @@ void Parser::Next() { ...@@ -200,7 +202,7 @@ void Parser::Next() {
attribute_.clear(); attribute_.clear();
attribute_.append(start, cursor_); attribute_.append(start, cursor_);
// First, see if it is a type keyword from the table of types: // 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) { \ if (attribute_ == IDLTYPE) { \
token_ = kToken ## ENUM; \ token_ = kToken ## ENUM; \
return; \ return; \
...@@ -491,7 +493,7 @@ uoffset_t Parser::ParseTable(const StructDef &struct_def) { ...@@ -491,7 +493,7 @@ uoffset_t Parser::ParseTable(const StructDef &struct_def) {
auto field = it->second; auto field = it->second;
if (!struct_def.sortbysize || size == SizeOf(value.type.base_type)) { if (!struct_def.sortbysize || size == SizeOf(value.type.base_type)) {
switch (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: \ case BASE_TYPE_ ## ENUM: \
builder_.Pad(field->padding); \ builder_.Pad(field->padding); \
if (struct_def.fixed) { \ if (struct_def.fixed) { \
...@@ -504,7 +506,7 @@ uoffset_t Parser::ParseTable(const StructDef &struct_def) { ...@@ -504,7 +506,7 @@ uoffset_t Parser::ParseTable(const StructDef &struct_def) {
break; break;
FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD); FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD);
#undef 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: \ case BASE_TYPE_ ## ENUM: \
builder_.Pad(field->padding); \ builder_.Pad(field->padding); \
if (IsStruct(field->value.type)) { \ if (IsStruct(field->value.type)) { \
...@@ -559,7 +561,7 @@ uoffset_t Parser::ParseVector(const Type &type) { ...@@ -559,7 +561,7 @@ uoffset_t Parser::ParseVector(const Type &type) {
// start at the back, since we're building the data backwards. // start at the back, since we're building the data backwards.
auto &val = field_stack_.back().first; auto &val = field_stack_.back().first;
switch (val.type.base_type) { 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: \ case BASE_TYPE_ ## ENUM: \
if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \ if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \
else builder_.PushElement(atot<CTYPE>(val.constant.c_str())); \ else builder_.PushElement(atot<CTYPE>(val.constant.c_str())); \
......
...@@ -63,7 +63,7 @@ namespace FlatBuffers.Test ...@@ -63,7 +63,7 @@ namespace FlatBuffers.Test
{ {
action(); action();
} }
catch (T ex) catch (T)
{ {
caught = true; caught = true;
} }
......
...@@ -39,7 +39,7 @@ namespace FlatBuffers.Test ...@@ -39,7 +39,7 @@ namespace FlatBuffers.Test
var str = fbb.CreateString("MyMonster"); var str = fbb.CreateString("MyMonster");
var test1 = fbb.CreateString("test1"); var test1 = fbb.CreateString("test1");
var test2 = fbb.CreateString("test2"); var test2 = fbb.CreateString("test2");
Monster.StartInventoryVector(fbb, 5); Monster.StartInventoryVector(fbb, 5);
...@@ -54,19 +54,19 @@ namespace FlatBuffers.Test ...@@ -54,19 +54,19 @@ namespace FlatBuffers.Test
var mon2 = Monster.EndMonster(fbb); var mon2 = Monster.EndMonster(fbb);
Monster.StartTest4Vector(fbb, 2); Monster.StartTest4Vector(fbb, 2);
MyGame.Example.Test.CreateTest(fbb, (short)10, (byte)20); MyGame.Example.Test.CreateTest(fbb, (short)10, (sbyte)20);
MyGame.Example.Test.CreateTest(fbb, (short)30, (byte)40); MyGame.Example.Test.CreateTest(fbb, (short)30, (sbyte)40);
var test4 = fbb.EndVector(); var test4 = fbb.EndVector();
Monster.StartTestarrayofstringVector(fbb, 2); Monster.StartTestarrayofstringVector(fbb, 2);
fbb.AddOffset(test2); fbb.AddOffset(test2);
fbb.AddOffset(test1); fbb.AddOffset(test1);
var testArrayOfString = fbb.EndVector(); var testArrayOfString = fbb.EndVector();
Monster.StartMonster(fbb); Monster.StartMonster(fbb);
Monster.AddPos(fbb, Vec3.CreateVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0, 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.AddHp(fbb, (short)80);
Monster.AddName(fbb, str); Monster.AddName(fbb, str);
Monster.AddInventory(fbb, inv); Monster.AddInventory(fbb, inv);
...@@ -79,19 +79,19 @@ namespace FlatBuffers.Test ...@@ -79,19 +79,19 @@ namespace FlatBuffers.Test
fbb.Finish(mon); fbb.Finish(mon);
// Dump to output directory so we can inspect later, if needed // 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(); var data = ms.ToArray();
File.WriteAllBytes(@"Resources/monsterdata_cstest.bin",data); File.WriteAllBytes(@"Resources/monsterdata_cstest.bin",data);
} }
// Now assert the buffer // 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(80, monster.Hp());
Assert.AreEqual(150, monster.Mana()); Assert.AreEqual(150, monster.Mana());
...@@ -103,10 +103,10 @@ namespace FlatBuffers.Test ...@@ -103,10 +103,10 @@ namespace FlatBuffers.Test
Assert.AreEqual(3.0f, pos.Z()); Assert.AreEqual(3.0f, pos.Z());
Assert.AreEqual(3.0f, pos.Test1()); Assert.AreEqual(3.0f, pos.Test1());
Assert.AreEqual((byte)4, pos.Test2()); Assert.AreEqual((sbyte)4, pos.Test2());
var t = pos.Test3(); var t = pos.Test3();
Assert.AreEqual((short)5, t.A()); 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()); Assert.AreEqual((byte)Any.Monster, monster.TestType());
...@@ -132,14 +132,14 @@ namespace FlatBuffers.Test ...@@ -132,14 +132,14 @@ namespace FlatBuffers.Test
Assert.AreEqual(2, monster.TestarrayofstringLength()); Assert.AreEqual(2, monster.TestarrayofstringLength());
Assert.AreEqual("test1", monster.Testarrayofstring(0)); Assert.AreEqual("test1", monster.Testarrayofstring(0));
Assert.AreEqual("test2", monster.Testarrayofstring(1)); Assert.AreEqual("test2", monster.Testarrayofstring(1));
} }
public void CanReadCppGeneratedWireFile() public void CanReadCppGeneratedWireFile()
{ {
var data = File.ReadAllBytes(@"Resources/monsterdata_test.bin"); var data = File.ReadAllBytes(@"Resources/monsterdata_test.bin");
var bb = new ByteBuffer(data); var bb = new ByteBuffer(data);
TestBuffer(bb, 0); TestBuffer(bb);
} }
} }
} }
...@@ -3,8 +3,6 @@ ...@@ -3,8 +3,6 @@
namespace MyGame.Example namespace MyGame.Example
{ {
using FlatBuffers;
public class Any public class Any
{ {
public static byte NONE = 0; public static byte NONE = 0;
......
...@@ -3,13 +3,11 @@ ...@@ -3,13 +3,11 @@
namespace MyGame.Example namespace MyGame.Example
{ {
using FlatBuffers;
public class Color public class Color
{ {
public static byte Red = 1; public static sbyte Red = 1;
public static byte Green = 2; public static sbyte Green = 2;
public static byte Blue = 8; public static sbyte Blue = 8;
}; };
......
// automatically generated, do not modify // automatically generated, do not modify
namespace MyGame.Example namespace MyGame.Example
{ {
using FlatBuffers; using FlatBuffers;
public class Monster : Table { public class Monster : Table {
public static Monster GetRootAsMonster(ByteBuffer _bb, int offset) { return (new Monster()).__init(_bb.GetInt(offset) + offset, _bb); } public static Monster GetRootAsMonster(ByteBuffer _bb) { return (new Monster()).__init(_bb.GetInt(_bb.position()) + _bb.position(), _bb); }
public static bool MonsterBufferHasIdentifier(ByteBuffer _bb, int offset) { return __has_identifier(_bb, offset, "MONS"); } 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 Monster __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; }
public Vec3 Pos() { return Pos(new Vec3()); } 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 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 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 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 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 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 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 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 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 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(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 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 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 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; } 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 */ /// 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(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 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 int TestarrayoftablesLength() { int o = __offset(26); return o != 0 ? __vector_len(o) : 0; }
public Monster Enemy() { return Enemy(new Monster()); } 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 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 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 int TestnestedflatbufferLength() { int o = __offset(30); return o != 0 ? __vector_len(o) : 0; }
public Monster Testempty() { return Testempty(new Monster()); } 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 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 StartMonster(FlatBufferBuilder builder) { builder.StartObject(15); }
public static void AddPos(FlatBufferBuilder builder, int posOffset) { builder.AddStruct(0, posOffset, 0); } 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 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 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 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 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 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 AddColor(FlatBufferBuilder builder, byte color) { builder.AddByte(6, color, 8); } public static void StartInventoryVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); }
public static void AddTestType(FlatBufferBuilder builder, byte testType) { builder.AddByte(7, testType, 0); } public static void AddColor(FlatBufferBuilder builder, sbyte color) { builder.AddSbyte(6, color, 8); }
public static void AddTest(FlatBufferBuilder builder, int testOffset) { builder.AddOffset(8, testOffset, 0); } public static void AddTestType(FlatBufferBuilder builder, byte testType) { builder.AddByte(7, testType, 0); }
public static void AddTest4(FlatBufferBuilder builder, int test4Offset) { builder.AddOffset(9, test4Offset, 0); } public static void AddTest(FlatBufferBuilder builder, int testOffset) { builder.AddOffset(8, testOffset, 0); }
public static void StartTest4Vector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 2); } public static void AddTest4(FlatBufferBuilder builder, int test4Offset) { builder.AddOffset(9, test4Offset, 0); }
public static void AddTestarrayofstring(FlatBufferBuilder builder, int testarrayofstringOffset) { builder.AddOffset(10, testarrayofstringOffset, 0); } public static void StartTest4Vector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 2); }
public static void StartTestarrayofstringVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } public static void AddTestarrayofstring(FlatBufferBuilder builder, int testarrayofstringOffset) { builder.AddOffset(10, testarrayofstringOffset, 0); }
public static void AddTestarrayoftables(FlatBufferBuilder builder, int testarrayoftablesOffset) { builder.AddOffset(11, testarrayoftablesOffset, 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 StartTestarrayoftablesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } public static void StartTestarrayofstringVector(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 AddTestarrayoftables(FlatBufferBuilder builder, int testarrayoftablesOffset) { builder.AddOffset(11, testarrayoftablesOffset, 0); }
public static void AddTestnestedflatbuffer(FlatBufferBuilder builder, int testnestedflatbufferOffset) { builder.AddOffset(13, testnestedflatbufferOffset, 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 StartTestnestedflatbufferVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } public static void StartTestarrayoftablesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); }
public static void AddTestempty(FlatBufferBuilder builder, int testemptyOffset) { builder.AddOffset(14, testemptyOffset, 0); } public static void AddEnemy(FlatBufferBuilder builder, int enemyOffset) { builder.AddOffset(12, enemyOffset, 0); }
public static int EndMonster(FlatBufferBuilder builder) { return builder.EndObject(); } public static void AddTestnestedflatbuffer(FlatBufferBuilder builder, int testnestedflatbufferOffset) { builder.AddOffset(13, testnestedflatbufferOffset, 0); }
public static void FinishMonsterBuffer(FlatBufferBuilder builder, int offset) { builder.Finish(offset, "MONS"); } 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"); }
};
}
...@@ -9,14 +9,14 @@ public class Test : Struct { ...@@ -9,14 +9,14 @@ public class Test : Struct {
public Test __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; } public Test __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; }
public short A() { return bb.GetShort(bb_pos + 0); } 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.Prep(2, 4);
builder.Pad(1); builder.Pad(1);
builder.PutByte(B); builder.PutSbyte(B);
builder.PutShort(A); builder.PutShort(A);
return builder.Offset; return builder.Offset();
} }
}; };
......
...@@ -12,25 +12,25 @@ public class Vec3 : Struct { ...@@ -12,25 +12,25 @@ public class Vec3 : Struct {
public float Y() { return bb.GetFloat(bb_pos + 4); } public float Y() { return bb.GetFloat(bb_pos + 4); }
public float Z() { return bb.GetFloat(bb_pos + 8); } public float Z() { return bb.GetFloat(bb_pos + 8); }
public double Test1() { return bb.GetDouble(bb_pos + 16); } 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() { return Test3(new Test()); }
public Test Test3(Test obj) { return obj.__init(bb_pos + 26, bb); } 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.Prep(16, 32);
builder.Pad(2); builder.Pad(2);
builder.Prep(2, 4); builder.Prep(2, 4);
builder.Pad(1); builder.Pad(1);
builder.PutByte(Test_B); builder.PutSbyte(Test_B);
builder.PutShort(Test_A); builder.PutShort(Test_A);
builder.Pad(1); builder.Pad(1);
builder.PutByte(Test2); builder.PutSbyte(Test2);
builder.PutDouble(Test1); builder.PutDouble(Test1);
builder.Pad(4); builder.Pad(4);
builder.PutFloat(Z); builder.PutFloat(Z);
builder.PutFloat(Y); builder.PutFloat(Y);
builder.PutFloat(X); builder.PutFloat(X);
return builder.Offset; return builder.Offset();
} }
}; };
......
...@@ -36,5 +36,7 @@ ...@@ -36,5 +36,7 @@
testarrayofstring: [ testarrayofstring: [
"test1", "test1",
"test2" "test2"
] ],
testempty: {
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment