OCaml protoc plugin
The goal of the OCaml protoc plugin is to create a plugin for
the Google protobuf compiler (protoc) to generate OCaml types and
serialization and deserialization functions from a .proto
file. ocaml-protoc-plugin aims to be a fully compliant implementation
of the Google protobuf standard and guidelines.
The main features include:
- Messages are mapped to idiomatic OCaml types, using modules
- Support service descriptions
- proto3 compliant
- proto2 compliant
- Supports includes
- Supports proto2 extensions
- Built-in support for Google well-known types
- Configurable annotations for all generated types
- JSON serialization and deserialization based on protobuf
specification
- Implemented in pure OCaml, making the library usable with
js-of-ocaml, melange, etc.
Table of contents
Comparison with other OCaml protobuf handlers.
| Feature |
ocaml-protoc-plugin |
ocaml-protoc |
ocaml-pb |
| OCaml types |
Supported |
Supported |
Defined at runtime[^1] |
| Service endpoints |
Supported |
Supported |
N/A |
| proto3 |
Supported |
Supported[^2] |
Supported |
| proto2 |
Supported |
Supported[^2] |
Supported |
| proto2 extends |
Supported |
Ignored |
Supported |
| proto2 groups |
Not supported[^3] |
Ignored |
? |
| json mappings |
Supported |
Supported |
? |
[^1]: ocaml-pb has a sister project, ocaml-pb-plugin, which emits
ocaml-pb definitions from a .proto. The generated code follows proto2-style
OCaml type definitions (all fields are option types), and repeated
fields are not packed by default.
[^2]: ocaml_protoc will always transmit all fields that are not
marked optional, and does not strictly comply to the protobuf
specification.
[^3]: Groups has been deprecated by Google and should not be used.
Types
Basic types are mapped trivially to OCaml types:
Primitive types:
| Protobuf Type |
OCaml type |
| int32, int64, uint32, uint64, sint32, sint64 |
int[^4] |
| fixed64, sfixed64, fixed32, sfixed32 |
int32, int64[^4] |
| bool |
bool |
| float, double |
float |
| string |
string |
| bytes |
bytes |
[^4]: The plugin supports changing the type for scalar types to
int/int64/int32. See options section below.
A message declaration is compiled to a module with a record type
t. Single field messages are mapped not wrapped in a record and messages without any fields are mapped to unit.
Packages are trivially mapped to modules.
Included proto files (<name>.proto) are assumed to have been compiled
to <name>.ml, and types in included proto files are referenced by
their full name.
Compound types are mapped like:
| Protobuf Type |
OCaml type |
| oneof |
Polymorphic variants: [ Field1 of fieldtype1, Field1 of fieldtype2 ] |
| repeated 'a |
'a list |
| message |
message option |
| enum |
Abstract data types: Enum1, Enum2, Enum3 |
| map<'a, 'b> |
Associative list: ('a * 'b) list |
Invocation
If the plugin is available in the path as protoc-gen-ocaml, you
can generate the OCaml code by running:
protoc --ocaml_out=. --ocaml_opt=<options> file.proto
Options
Options control the code/types generated.
| Option |
Description |
Example |
Default |
| annot |
Type annotations. |
annot=[@@deriving show] |
"" |
| debug |
Enable debugging |
debug |
Not set |
| open |
Add open at top of generated files. May be given multiple times |
open=Base.Sexp |
[] |
| int64_as_int |
Map *int64 types to int instead of int64 |
int64_as_int=false |
true |
| int32_as_int |
Map *int32 types to int instead of int32 |
int32_as_int=false |
true |
| fixed_as_int |
Map *fixed* types to int |
fixed_as_int=true |
false |
| singleton_record |
Messages with only one field will be wrapped in a record |
singleton_record=true |
false |
| prefix_output_with_package |
Emit files prefixed with their package name. This allows multiple protofiles of the same name with different package names to be used |
prefix_output_with_package=true[^5] |
false |
| singleton_oneof_as_option |
oneof declarations containing only one field are mapped to a single optional field |
singleton_oneof_as_option=false |
true |
Parameters are separated by ;
[^5]: When using prefix_output_with_package=true, all dependencies need to be compiled
with this option too. For example, if the protobuf file depends on
Google well-known types, you need to rebuild those using
prefix_output_with_package=true as well. This dune file
dune
lists how to do that.
Common option combinations:
- Keep stable generated paths across packages:
prefix_output_with_package=true
- Preserve explicit oneof wrappers:
singleton_oneof_as_option=false
- Keep 32/64-bit protobuf scalars as OCaml fixed-width integers:
int32_as_int=false;int64_as_int=false
If protoc-gen-ocaml is not located in the path, it is possible to
specify the exact path to the plugin:
protoc --plugin=protoc-gen-ocaml=../plugin/ocaml-protocol-plugin.exe --ocaml_out=. <file>.proto
JSON serialization and deserialization
ocaml-protoc-plugin can serialize and deserialize to/from
JSON, using the functions to_json, from_json and
from_json_exn similar to regular protobuf serialization and
deserialization.
JSON serialization can be controlled using optional arguments:
val to_json: Json_options.t -> t -> Json.t
The Json.t type is identical to
Yojson.Basic.t. ocaml-protoc-plugin does not depend on Yojson
to limit number of dependencies.
The options argument allows finer-grained control over JSON
serialization. The following options are supported:
| argument |
comment |
default |
enum_names |
By default enum names are used when serializing to JSON. Setting to false uses enum values instead |
true |
json_names |
By default JSON uses camelCase names for fields. Setting to false uses names as defined in the proto file |
true |
omit_default_values |
By default JSON omits default values to reduce size. Setting to false forces all values to be emitted |
true |
JSON deserialization accepts JSON constructed with any combination
of options.
JSON serialization and deserialization support
special handling of the following types to follow the
protobuf
specification
as close as possible:
| type |
JSON example |
notes |
| bytes |
"Ynl0ZXM=" |
Base64 encoded |
| google.protobuf.Empty |
{} |
|
| google.protobuf.Duration |
"123.456s" |
|
| google.protobuf.Timestamp |
"2024-03-08T20:54:43.000000000Z" |
|
| google.protobuf.Value |
{ "x": 4 } |
|
| google.protobuf.Struct |
{ "x": 4 } |
|
| google.protobuf.ListValue |
[ 4,5,6 ] |
|
| google.protobuf.FieldMask |
"camelCase,camelCased" |
Not guaranteed to be reversible due to camel case conversion |
| google.protobuf.Any |
|
Not handled, as the ocaml-protobuf-plugin does not support dynamic protobuf parsing |
JSON serialization and deserialization is not well optimized and
should not be used in performance critical applications.
Older versions of protoc
Some older versions of the Google protobuf compiler protoc do not
support the --ocaml_opt flag. As an alternative, options can also be
passed with the --ocaml_out flag:
protoc --plugin=protoc-gen-ocaml=../plugin/ocaml.exe --ocaml_out=annot=debug;[@@deriving show { with_path = false }, eq]:. <file>.proto
Example
test.proto
syntax = "proto3";
message Address {
enum Planet {
Earth = 0; Mars = 1; Pluto = 2;
}
string street = 1;
uint64 number = 2;
Planet planet = 3;
}
message Person {
uint64 id = 1;
string name = 2;
Address address = 3;
}
$ protoc --ocaml_out=. test.proto
Generates a file test.ml with the following signature:
module Address : sig
module rec Planet : sig
type t = Earth | Mars | Pluto
val to_int: t -> int
val from_int: int -> t Protobuf.Deserialize.result
end
val name': unit -> string
type t = {
street: string;
number: int;
planet: Planet.t;
}
val make: ?street:string ?number:int ?planet:Planet.t -> unit -> t
val to_proto: t -> Protobuf.Writer.t
val from_proto: Protobuf.Reader.t -> (t, Protobuf.Deserialize.error) result
end
module Person : sig
val name': unit -> string
type t = {
id: int;
name: string;
address: Address.t option;
}
val make: ?id:int ?name:string ?address:Address.t -> unit -> t
val to_proto: t -> Protobuf.Writer.t
val from_proto: Protobuf.Reader.t -> (t, Protobuf.Deserialize.error) result
end = struct
Note that if test.proto had a package declaration such as package testing,
the modules Address and Person listed above would be defined as sub-modules
of a top-level module Testing.
The function make allows the user to create messages without
specifying all (or any) fields. Using this function allows users
to add fields to messages later without modifying existing code, as
new fields are set to default values.
Protobuf.Reader and Protobuf.Writer are used when reading or
writing protobuf binary format. Below is an example of decoding a message:
let string_of_planet = function
| Address.Earth -> "earth"
| Mars -> "mars"
| Pluto -> "pluto"
in
let read_person binary_message =
let reader = Protobuf.Reader.create binary_message in
match Person.from_proto reader with
| Ok Person.{ id; name; address = Some Address.{ street; number; planet } } ->
Printf.printf "P: %d %s - %s %s %d\n" id name (string_of_planet planet) street number
| Ok Person.{ id; name; address = None } ->
Printf.printf "P: %d %s - Address unknown\n" id name
| Error _ -> failwith "Could not decode"
More examples can be found under
examples
Advanced reference
Mangle generated names
Idiomatic protobuf names are somewhat alien to
OCaml. Ocaml_protoc_plugin has an option to mangle protobuf names
into somewhat more OCaml idiomatic names. When this option is set (see
below), names are mangled to snake case as described in the table
below:
| Protobuf type |
Protobuf name |
OCaml name |
| package |
CapitalizedSnakeCase |
Capitalized_snake_case |
| message |
CapitalizedSnakeCase |
Capitalized_snake_case |
| field |
lowercased_snake_case |
lowercased_snake_case |
| oneof name |
lowercased_snake_case |
lowercased_snake_case |
| oneof field |
capitalized_snake_case |
Capitalized_snake_case |
| enum |
CAPITALIZED_SNAKE_CASE |
Capitalized_snake_case |
| service name |
CapitalizedSnakeCase |
Capitalized_snake_case |