Files
flatbuffers/src/idl_namer.h
Paulo Pinheiro b7856f8e27 Add Kotlin multiplatform support (#7969)
* [Kotlin] Introduction to Kotlin Multiplaform

The first implementation of the Kotlin code generation was made years
ago at the time Kotlin Multiplaform was not stable and Kotlin is mostly
used on JVM-based targets. For this reason the generated code uses java
based runtime.

That design decision comes with many drawbacks, leaving the code
generated more java-like and making it impossible to use more advanced
features of the Kotlin language.

In this change we are adding two parts: A pure, multi-plaform, Kotlin
runtime and a new code generator to accompany it.

* [Kotlin] Remove scalar sign cast from code generation

Now that we have a new runtime the accepts unsigned types, we don't
need to code generate casting back and from signed scalars. This
MR removes this from both code generations and adds the necessary
API to the runtime.

* [Kotlin] Use offset on public API to represent buffer position

Currently, kotlin was following Java's approach of representing objects,
vectors, tables as "Int" (the position of it in the buffer). This change
replaces naked Int with Offset<T>, offering a type-safe API. So,
instead of

fun Table.createTable(b: FlatBufferBuilder, subTable: Int)

We will have

fun Table.createTable(b: FlatBufferBuilder, subTable: Offset<SubTable>)

Making impossible to accidentally switch parameters.

The performance should be similar to use Int as we are using value
class for Offset and ArrayOffset, which most of the time translate to
Int in the bytecode.

* [Kotlin] Add builder for tables

Add builder constructor to make create of table more ergonomic.
For example the movie sample for the test set could be written as:

Movie.createMovie(fbb,
    mainCharacterType = Character_.MuLan,
    mainCharacter = att) {
    charactersType = charsType
    this.characters = characters
}

instead of:

Movie.startMovie(fbb)
Movie.addMainCharacterType(fbb, Character_.MuLan)
Movie.addMainCharacter(fbb, att as Offset<Any>)
Movie.addCharactersType(fbb, charsType)
Movie.addCharacters(fbb, charsVec)
Movie.endMovie(fbb)

* [Kotlin] Move enum types to value class

Moving to flatbuffer enums to value class adds type safety for parameters
with minimum to no performance impact.

* [Kotlin] Simplify Union parameters to avoid naked casting

Just a small change on the APIs that receive union as parameters,
creating a typealias UnionOffset to avoid using Offset<Any>. To "convert"
an table offset to an union, one just call Offset.toUnion().

* [Kotlin] Apply clang-format on kotlin code generators

* [Kotlin] Update kotlin generator to follow official naming conventions

Updating directory, package and enum naming to follow Kotlin official
convention.

https://kotlinlang.org/docs/coding-conventions.html#naming-rules

* [Kotlin] Add fixes to improve performance

1 - Add benchmark comparing serialization between Java & Kotlin
2 - ReadWriteBuffer does not auto-grow (thus avoid check size in every op)
3 - Add specialized add functions on FlatBufferBuilder to avoid boxing
offsets.
4 - Remove a few Kotlin syntax sugar that generated performance penalties.

* [Kotlin] Remove builder from Kotlin KMP and add some optimizations
to avoid boxing of Offset classes

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
2023-05-26 11:00:33 -07:00

180 lines
6.2 KiB
C++

#ifndef FLATBUFFERS_IDL_NAMER
#define FLATBUFFERS_IDL_NAMER
#include "flatbuffers/idl.h"
#include "namer.h"
namespace flatbuffers {
// Provides Namer capabilities to types defined in the flatbuffers IDL.
class IdlNamer : public Namer {
public:
explicit IdlNamer(Config config, std::set<std::string> keywords)
: Namer(config, std::move(keywords)) {}
using Namer::Constant;
using Namer::Directories;
using Namer::Field;
using Namer::File;
using Namer::Function;
using Namer::Method;
using Namer::Namespace;
using Namer::NamespacedType;
using Namer::ObjectType;
using Namer::Type;
using Namer::Variable;
using Namer::Variant;
std::string Constant(const FieldDef &d) const { return Constant(d.name); }
// Types are always structs or enums so we can only expose these two
// overloads.
std::string Type(const StructDef &d) const { return Type(d.name); }
std::string Type(const EnumDef &d) const { return Type(d.name); }
std::string Function(const Definition &s) const { return Function(s.name); }
std::string Function(const std::string& prefix, const Definition &s) const {
return Function(prefix + s.name);
}
std::string Field(const FieldDef &s) const { return Field(s.name); }
std::string Field(const FieldDef &d, const std::string &s) const {
return Field(d.name + "_" + s);
}
std::string Variable(const FieldDef &s) const { return Variable(s.name); }
std::string Variable(const StructDef &s) const { return Variable(s.name); }
std::string Variant(const EnumVal &s) const { return Variant(s.name); }
std::string EnumVariant(const EnumDef &e, const EnumVal &v) const {
return Type(e) + config_.enum_variant_seperator + Variant(v);
}
std::string ObjectType(const StructDef &d) const {
return ObjectType(d.name);
}
std::string ObjectType(const EnumDef &d) const { return ObjectType(d.name); }
std::string Method(const FieldDef &d, const std::string &suffix) const {
return Method(d.name, suffix);
}
std::string Method(const std::string &prefix, const StructDef &d) const {
return Method(prefix, d.name);
}
std::string Method(const std::string &prefix, const FieldDef &d) const {
return Method(prefix, d.name);
}
std::string Method(const std::string &prefix, const FieldDef &d,
const std::string &suffix) const {
return Method(prefix, d.name, suffix);
}
std::string Namespace(const struct Namespace &ns) const {
return Namespace(ns.components);
}
std::string NamespacedEnumVariant(const EnumDef &e, const EnumVal &v) const {
return NamespacedString(e.defined_namespace, EnumVariant(e, v));
}
std::string NamespacedType(const Definition &def) const {
return NamespacedString(def.defined_namespace, Type(def.name));
}
std::string NamespacedObjectType(const Definition &def) const {
return NamespacedString(def.defined_namespace, ObjectType(def.name));
}
std::string Directories(const struct Namespace &ns,
SkipDir skips = SkipDir::None,
Case input_case = Case::kUpperCamel) const {
return Directories(ns.components, skips, input_case);
}
// Legacy fields do not really follow the usual config and should be
// considered for deprecation.
std::string LegacyRustNativeVariant(const EnumVal &v) const {
return ConvertCase(EscapeKeyword(v.name), Case::kUpperCamel);
}
std::string LegacyRustFieldOffsetName(const FieldDef &field) const {
return "VT_" + ConvertCase(EscapeKeyword(field.name), Case::kAllUpper);
}
std::string LegacyRustUnionTypeOffsetName(const FieldDef &field) const {
return "VT_" + ConvertCase(EscapeKeyword(field.name + "_type"), Case::kAllUpper);
}
std::string LegacySwiftVariant(const EnumVal &ev) const {
auto name = ev.name;
if (isupper(name.front())) {
std::transform(name.begin(), name.end(), name.begin(), CharToLower);
}
return EscapeKeyword(ConvertCase(name, Case::kLowerCamel));
}
// Also used by Kotlin, lol.
std::string LegacyJavaMethod2(const std::string &prefix, const StructDef &sd,
const std::string &suffix) const {
return prefix + sd.name + suffix;
}
std::string LegacyKotlinVariant(EnumVal &ev) const {
// Namer assumes the input case is snake case which is wrong...
return ConvertCase(EscapeKeyword(ev.name), Case::kLowerCamel);
}
// Kotlin methods escapes keywords after case conversion but before
// prefixing and suffixing.
std::string LegacyKotlinMethod(const std::string &prefix, const FieldDef &d,
const std::string &suffix) const {
return prefix + ConvertCase(EscapeKeyword(d.name), Case::kUpperCamel) +
suffix;
}
std::string LegacyKotlinMethod(const std::string &prefix, const StructDef &d,
const std::string &suffix) const {
return prefix + ConvertCase(EscapeKeyword(d.name), Case::kUpperCamel) +
suffix;
}
// This is a mix of snake case and keep casing, when Ts should be using
// lower camel case.
std::string LegacyTsMutateMethod(const FieldDef& d) {
return "mutate_" + d.name;
}
std::string LegacyRustUnionTypeMethod(const FieldDef &d) {
// assert d is a union
// d should convert case but not escape keywords due to historical reasons
return ConvertCase(d.name, config_.fields, Case::kLowerCamel) + "_type";
}
private:
std::string NamespacedString(const struct Namespace *ns,
const std::string &str) const {
std::string ret;
if (ns != nullptr) { ret += Namespace(ns->components); }
if (!ret.empty()) ret += config_.namespace_seperator;
return ret + str;
}
};
// This is a temporary helper function for code generators to call until all
// flag-overriding logic into flatc.cpp
inline Namer::Config WithFlagOptions(const Namer::Config &input,
const IDLOptions &opts,
const std::string &path) {
Namer::Config result = input;
result.object_prefix = opts.object_prefix;
result.object_suffix = opts.object_suffix;
result.output_path = path;
result.filename_suffix = opts.filename_suffix;
return result;
}
} // namespace flatbuffers
#endif // FLATBUFFERS_IDL_NAMER