View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jeffrey Rosenwald, extended by Peter Ludemann
    4    E-mail:        jeffrose@acm.org, peter.ludemann@gmail.com
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2010-2013, Jeffrey Rosenwald;
    7                   2021-2025, SWI-Prolog Solutions b.v.
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module(protobufs,
   37          [ protobuf_message/2,   % ?Template ?Codes
   38            protobuf_message/3,   % ?Template ?Codes ?Rest
   39            protobuf_parse_from_codes/3, % +WireCodes, +MessageType, -Term
   40            protobuf_serialize_to_codes/3,  % +Term, +MessageType, -WireCodes
   41            protobuf_field_is_map/2, % +MessageType, +FieldName
   42            protobuf_map_pairs/3 % ?ProtobufTermList, ?DictTag, ?Pairs
   43
   44            % TODO: Restore the following to the public interface, if
   45            %       someone needs them.  For now, the tests directly specify
   46            %       them using, e.g. protobufs:uint32_codes(..., ...).
   47            %
   48            % protobuf_segment_message/2,  % ?Segments ?Codes
   49            % protobuf_segment_convert/2,  % +Form1 ?Form2
   50            % uint32_codes/2,
   51            % int32_codes/2,
   52            % float32_codes/2,
   53            % uint64_codes/2,
   54            % int64_codes/2,
   55            % float64_codes/2,
   56            % int64_zigzag/2,
   57            % uint32_int32/2,
   58            % uint64_int64/2,
   59            % uint32_codes_when/2,
   60            % int32_codes_when/2,  % TODO: unused
   61            % float32_codes_when/2,
   62            % uint64_codes_when/2,
   63            % int64_codes_when/2,  % TODO: unused
   64            % float64_codes_when/2,
   65            % int64_zigzag_when/2,
   66            % uint32_int32_when/2,
   67            % uint64_int64_when/2,
   68            % int64_float64_when/2,
   69            % int32_float32_when/2,
   70            % protobuf_var_int//1,
   71            % protobuf_tag_type//2
   72          ]).   73
   74:- use_module(library(apply_macros)).  % autoload(library(apply), [maplist/3, foldl/4]).
   75:- autoload(library(error),
   76            [ must_be/2, domain_error/2, existence_error/2,
   77              representation_error/1, syntax_error/1
   78            ]).   79:- autoload(library(lists), [append/3, append/2]).   80:- autoload(library(pairs), [group_pairs_by_key/2]).   81:- autoload(library(dif), [dif/2]).   82:- autoload(library(dcg/high_order), [sequence//2]).   83:- autoload(library(when), [when/2]).   84:- use_module(library(debug), [assertion/1]). % TODO: remove
   85
   86:- set_prolog_flag(optimise, true). % For arithmetic using is/2.
   87
   88:- create_prolog_flag(protobuf_max_depth, 100, [keep(true), type(integer)]).

Google's Protocol Buffers ("protobufs")

Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data -- think XML, but smaller, faster, and simpler. You define how you want your data to be structured once. This takes the form of a template that describes the data structure. You use this template to encode and decode your data structure into wire-streams that may be sent-to or read-from your peers. The underlying wire stream is platform independent, lossless, and may be used to interwork with a variety of languages and systems regardless of word size or endianness. Techniques exist to safely extend your data structure without breaking deployed programs that are compiled against the "old" format.

The idea behind Google's Protocol Buffers is that you define your structured messages using a domain-specific language and tool set. Further documentation on this is at https://developers.google.com/protocol-buffers.

There are two ways you can use protobufs in Prolog:

The protobuf_parse_from_codes/3 and protobuf_serialize_to_codes/3 interface translates between a "wire stream" and a Prolog term. This interface takes advantage of SWI-Prolog's dict. The protoc plugin (protoc-gen-swipl) generates a Prolog file of meta-information that captures the .proto file's definition in the protobufs module, with the following facts:

The protobuf_message/2 interface allows you to define your message template as a list of predefined Prolog terms that correspond to production rules in the Definite Clause Grammar (DCG) that realizes the interpreter. Each production rule has an equivalent rule in the protobuf grammar. The process is not unlike specifiying the format of a regular expression. To encode a template to a wire-stream, you pass a grounded template, X, and variable, Y, to protobuf_message/2. To decode a wire-stream, Y, you pass an ungrounded template, X, along with a grounded wire-stream, Y, to protobuf_message/2. The interpreter will unify the unbound variables in the template with values decoded from the wire-stream.

For an overview and tutorial with examples, see library(protobufs): Google's Protocol Buffers Examples of usage may also be found by inspecting test_protobufs.pl and the demo directory, or by looking at the "addressbook" example that is typically installed at /usr/lib/swi-prolog/doc/packages/examples/protobufs/interop/addressbook.pl

author
- Jeffrey Rosenwald (JeffRose@acm.org)
- Peter Ludemann (peter.ludemann@gmail.org)
See also
- https://developers.google.com/protocol-buffers
- https://developers.google.com/protocol-buffers/docs/encoding
Compatibility
- SWI-Prolog
  168:- use_foreign_library(foreign(protobufs)).
 protobuf_parse_from_codes(+WireCodes:list(int), +MessageType:atom, -Term) is semidet
Process bytes (list of int) that is the serialized form of a message (designated by MessageType), creating a Prolog term.

Protoc must have been run (with the --swipl_out= option and the resulting top-level _pb.pl file loaded. For more details, see the "protoc" section of the overview documentation.

Fails if the message can't be parsed or if the appropriate meta-data from protoc hasn't been loaded.

All fields that are omitted from the WireCodes are set to their default values (typically the empty string or 0, depending on the type; or [] for repeated groups). There is no way of testing whether a value was specified in WireCodes or given its default value (that is, there is no equivalent of the Python implementation's =HasField`). Optional embedded messages and groups do not have any default value -- you must check their existence by using get_dict/3 or similar. If a field is part of a "oneof" set, then none of the other fields is set. You can determine which field had a value by using get_dict/3.

Messages may be nested at most as deep as the Prolog flag protobuf_max_depth (default 100, the default of the C++ implementation).

Arguments:
WireCodes- Wire format of the message from e.g., read_stream_to_codes/2. (The stream should have options encoding(octet) and type(binary), either as options to read_file_to_codes/3 or by calling set_stream/2 on the stream to read_stream_to_codes/2.)
MessageType- Fully qualified message name (from the .proto file's package and message). For example, if the package is google.protobuf and the message is FileDescriptorSet, then you would use '.google.protobuf.FileDescriptorSet' or 'google.protobuf.FileDescriptorSet'. If there's no package name, use e.g.: 'MyMessage or '.MyMessage'. You can see the packages by looking at protobufs:proto_meta_package(Pkg,File,_) and the message names and fields by protobufs:proto_meta_field_name('.google.protobuf.FileDescriptorSet', FieldNumber, FieldName, FqnName) (the initial '.' is not optional for these facts, only for the top-level name given to protobuf_serialize_to_codes/3).
Term- The generated term, as nested dicts.
Errors
- version_error(Module-Version) you need to recompile the Module with a newer version of protoc.
- resource_error(protobuf_max_depth(Max)) if messages are nested too deeply.
- syntax_error(illegal_utf8_sequence) if a string field is not valid UTF-8.
See also
- library(protobufs): Google's Protocol Buffers
bug
- Ignores .proto extensions.
- map fields don't get special treatment (but see protobuf_map_pairs/3).
- Generates fields in a different order from the C++, Python, Java implementations, which use the field number to determine field order whereas currently this implementation uses field name. (This isn't stricly speaking a bug, because it's allowed by the specification; but it might cause some surprise.)
To be done
- document the generated terms (see library(json) and json_read_dict/3)
- add options such as true and value_string_as (similar to json_read_dict/3)
- add option for form of the dict tags (fully qualified or not)
- add option for outputting fields in the C++/Python/Java order (by field number rather than by field name).
  233protobuf_parse_from_codes(WireCodes, MessageType0, Term) :-
  234    verify_version,
  235    must_be(ground, MessageType0),
  236    (   proto_meta_normalize(MessageType0, MessageType)
  237    ->  true
  238    ;   existence_error(protobuf_package, MessageType0)
  239    ),
  240    max_depth(MaxDepth),
  241    protobuf_segment_message(Segments, WireCodes, first(MaxDepth)),
  242    % protobuf_segment_message/2 can leave choicepoints, backtracking
  243    % through all the possibilities would have combinatoric explosion;
  244    % instead use segment_to_term/3 call protobuf_segment_convert/2 to
  245    % change segments that were guessed incorrectly.
  246    !,
  247    maplist(segment_to_term(MessageType, MaxDepth), Segments, MsgFields),
  248    !, % TODO: remove
  249    combine_fields(MsgFields, MessageType{}, Term),
  250    !. % TODO: remove? - but proto_meta might have left choicepoints if loaded twice
  251
  252verify_version :-
  253    (   protoc_gen_swipl_version(Module, Version),
  254        Version @< [0,9,1] % This must be sync-ed with changes to protoc-gen-swipl
  255    ->  throw(error(version_error(Module-Version), _))
  256    ;   true
  257    ).
 protobuf_serialize_to_codes(+Term:dict, -MessageType:atom, -WireCodes:list(int)) is det
Process a Prolog term into bytes (list of int) that is the serialized form of a message (designated by MessageType).

Protoc must have been run (with the --swipl_out= option and the resulting top-level _pb.pl file loaded. For more details, see the "protoc" section of the overview documentation.

Fails if the term isn't of an appropriate form or if the appropriate meta-data from protoc hasn't been loaded, or if a field name is incorrect (and therefore nothing in the meta-data matches it).

Arguments:
Term- The Prolog form of the data, as nested dicts.
MessageType- Fully qualified message name (from the .proto file's package and message). For example, if the package is google.protobuf and the message is FileDescriptorSet, then you would use '.google.protobuf.FileDescriptorSet' or 'google.protobuf.FileDescriptorSet'. If there's no package name, use e.g.: 'MyMessage or '.MyMessage'. You can see the packages by looking at protobufs:proto_meta_package(Pkg,File,_) and the message names and fields by protobufs:proto_meta_field_name('.google.protobuf.FileDescriptorSet', FieldNumber, FieldName, FqnName) (the initial '.' is not optional for these facts, only for the top-level name given to protobuf_serialize_to_codes/3).
WireCodes- Wire format of the message, which can be output using format('~s', [WireCodes]).
Errors
- version_error(Module-Version) you need to recompile the Module with a newer version of protoc.
- existence_error if a field can't be found in the meta-data
See also
- library(protobufs): Google's Protocol Buffers
bug
- map fields don't get special treatment (but see protobuf_map_pairs/3).
- oneof is not checked for validity.
  292protobuf_serialize_to_codes(Term, MessageType0, WireCodes) :-
  293    verify_version,
  294    must_be(ground, MessageType0),
  295    (   proto_meta_normalize(MessageType0, MessageType)
  296    ->  true
  297    ;   existence_error(protobuf_package, MessageType0)
  298    ),
  299    term_to_segments(Term, MessageType, Segments),
  300    !, % TODO: remove
  301    protobuf_segment_message(Segments, WireCodes),
  302    !. % TODO: remove? - but proto_meta might have left choicepoints if loaded twice
  303
  304%
  305% Map wire type (atom) to its encoding (an int)
  306%
  307wire_type(varint,            0). % for int32, int64, uint32, uint64, sint32, sint64, bool, enum
  308wire_type(fixed64,           1). % for fixed64, sfixed64, double
  309wire_type(length_delimited,  2). % for string, bytes, embedded messages, packed repeated fields
  310wire_type(start_group,       3). % for groups (deprecated)
  311wire_type(end_group,         4). % for groups (deprecated)
  312wire_type(fixed32,           5). % for fixed32, sfixed32, float
  313
  314%
  315%  basic wire-type processing handled by C-support code in DCG-form
  316%
  317
  318fixed_uint32(X, [A0, A1, A2, A3 | Rest], Rest) :-
  319    uint32_codes_when(X, [A0, A1, A2, A3]).
  320/* equivalent to:
  321fixed_uint32_(X) -->
  322  [ A0,A1,A2,A3 ],
  323  { uint32_codes_when(X, [A0,A1,A2,A3]) }.
  324*/
  325
  326fixed_uint64(X, [A0, A1, A2, A3, A4, A5, A6, A7 | Rest], Rest) :-
  327    uint64_codes_when(X, [A0, A1, A2, A3, A4, A5, A6, A7]).
  328
  329fixed_float64(X, [A0, A1, A2, A3, A4, A5, A6, A7 | Rest], Rest) :-
  330    float64_codes_when(X, [A0, A1, A2, A3, A4, A5, A6, A7]).
  331
  332fixed_float32(X, [A0, A1, A2, A3 | Rest], Rest) :-
  333    float32_codes_when(X, [A0, A1, A2, A3]).
  334
  335%
  336%   Start of the DCG
  337%
  338
  339code_string(N, Codes, Rest, Rest1) :-
  340    var(Codes),
  341    !,
  342    take_codes(N, Rest, Codes, Rest1).
  343code_string(N, Codes, Rest, Rest1) :-
  344    length(Codes, N),
  345    append(Codes, Rest1, Rest),
  346    !.
  347
  348% take_codes(+N, +List, -Prefix, -Rest) is semidet.
  349%
  350% Split List after N elements.  Fails if List is shorter than N
  351% without creating a list of N elements first.
  352
  353take_codes(0, Rest, Codes, Rest1) =>
  354    Codes = [],
  355    Rest1 = Rest.
  356take_codes(N, [H|T], Codes, Rest1), N > 0 =>
  357    Codes = [H|Codes1],
  358    N1 is N-1,
  359    take_codes(N1, T, Codes1, Rest1).
  360take_codes(_, _, _, _) =>
  361    fail.
  362/*
  363code_string(N, Codes) -->
  364        { length(Codes, N) },
  365        Codes, !.
  366*/
  367
  368%
  369% deal with Google's method of packing unsigned integers in variable
  370% length, modulo 128 strings.
  371%
  372% protobuf_var_int//1 and protobuf_tag_type//2 productions were rewritten in straight
  373% Prolog for speed's sake.
  374%
 protobuf_var_int(?A:int)// is det
Conversion between an int A and a list of codes, using the "varint" encoding. Raises an error if A is negative or does not fit in 64 bits. This is a low-level predicate; normally, you should use template_message/2 and the appropriate template term. e.g. phrase(protobuf_var_int(300), S) => S = [172,2] phrase(protobuf_var_int(A), [172,2]) -> A = 300
  384protobuf_var_int(X, Codes, Rest) :-
  385    nonvar(X),
  386    !,
  387    must_be(nonneg, X),
  388    (   X =< 0xffffffffffffffff
  389    ->  var_int_encode(X, Codes, Rest)
  390    ;   representation_error(uint64_t(X))
  391    ).
  392protobuf_var_int(A, [A | Rest], Rest) :-
  393    A < 128,
  394    !.
  395protobuf_var_int(X, [A | Rest], Rest1) :-
  396    X0 is A - 128,
  397    var_int_cont(Rest, 7, X0, X, Rest1).
  398
  399var_int_encode(X, Codes, Rest) :-
  400    X < 128,
  401    !,
  402    Codes = [X|Rest].
  403var_int_encode(X, [A|Rest], Rest1) :-
  404    A is 128 + (X /\ 0x7f),
  405    X1 is X >> 7,
  406    var_int_encode(X1, Rest, Rest1).
  407
  408% var_int_cont(+Codes, +Shift, +X0, -X, -Rest)
  409%
  410% Decode the continuation bytes of a varint.  A varint encodes at
  411% most 64 bits and thus has at most 10 bytes.
  412
  413var_int_cont([A|Rest], Shift, X0, X, Rest1) :-
  414    Shift < 70,
  415    (   A < 128
  416    ->  X is X0 + (A << Shift),
  417        Rest1 = Rest
  418    ;   X1 is X0 + ((A - 128) << Shift),
  419        Shift1 is Shift + 7,
  420        var_int_cont(Rest, Shift1, X1, X, Rest1)
  421    ).
 protobuf_tag_type(?Tag:int, ?WireType:atom)// is det
Conversion between Tag (number) + WireType and wirestream codes. This is a low-level predicate; normally, you should use template_message/2 and the appropriate template term. @arg Tag The item's tag (field number) @arg WireType The item's wire type (see prolog_type//2 for how to convert this to a Prolog type)
  430protobuf_tag_type(Tag, WireType, Rest, Rest1) :-
  431    nonvar(Tag), nonvar(WireType),
  432    wire_type(WireType, WireTypeEncoding),
  433    A is Tag << 3 \/ WireTypeEncoding,
  434    protobuf_var_int(A, Rest, Rest1),
  435    !.
  436protobuf_tag_type(Tag, WireType, Rest, Rest1) :-
  437    protobuf_var_int(A, Rest, Rest1),
  438    WireTypeEncoding is A /\ 0x07,
  439    wire_type(WireType, WireTypeEncoding),
  440    Tag is A >> 3.
 prolog_type(?Tag:int, ?PrologType:atom)// is semidet
Match Tag (field number) + PrologType. When Type is a variable, backtracks through all the possibilities for a given wire encoding. Note that 'repeated' isn't here because it's handled by single_message//3. See also segment_type_tag/3.
  448prolog_type(Tag, double) -->     protobuf_tag_type(Tag, fixed64).
  449prolog_type(Tag, integer64) -->  protobuf_tag_type(Tag, fixed64).
  450prolog_type(Tag, unsigned64) --> protobuf_tag_type(Tag, fixed64).
  451prolog_type(Tag, float) -->      protobuf_tag_type(Tag, fixed32).
  452prolog_type(Tag, integer32) -->  protobuf_tag_type(Tag, fixed32).
  453prolog_type(Tag, unsigned32) --> protobuf_tag_type(Tag, fixed32).
  454prolog_type(Tag, integer) -->    protobuf_tag_type(Tag, varint).
  455prolog_type(Tag, unsigned) -->   protobuf_tag_type(Tag, varint).
  456prolog_type(Tag, signed32) -->   protobuf_tag_type(Tag, varint).
  457prolog_type(Tag, signed64) -->   protobuf_tag_type(Tag, varint).
  458prolog_type(Tag, boolean) -->    protobuf_tag_type(Tag, varint).
  459prolog_type(Tag, enum) -->       protobuf_tag_type(Tag, varint).
  460prolog_type(Tag, atom) -->       protobuf_tag_type(Tag, length_delimited).
  461prolog_type(Tag, codes) -->      protobuf_tag_type(Tag, length_delimited).
  462prolog_type(Tag, utf8_codes) --> protobuf_tag_type(Tag, length_delimited).
  463prolog_type(Tag, string) -->     protobuf_tag_type(Tag, length_delimited).
  464prolog_type(Tag, embedded) -->   protobuf_tag_type(Tag, length_delimited).
  465prolog_type(Tag, packed) -->     protobuf_tag_type(Tag, length_delimited).
  466
  467%
  468%   The protobuf-2.1.0 grammar allows negative values in enums.
  469%   But they are encoded as unsigned in the  golden message.
  470%   As such, they use the maximum length of a varint, so it is
  471%   recommended that they be non-negative. However, that's controlled
  472%   by the =|.proto|= file.
  473%
  474:- meta_predicate enumeration(1,?,?).  475
  476enumeration(Type) -->
  477    { call(Type, Value) },
  478    payload(signed64, Value).
 payload(?PrologType, ?Payload) is det
Process the codes into Payload, according to PrologType TODO: payload//2 "mode" is sometimes module-sensitive, sometimes not. payload(enum, A)// has A as a callable all other uses of payload//2, the 2nd arg is not callable.
  488payload(enum, Payload) -->
  489    enumeration(Payload).
  490payload(double, Payload) -->
  491    fixed_float64(Payload).
  492payload(integer64, Payload) -->
  493    { uint64_int64_when(Payload0, Payload) },
  494    fixed_uint64(Payload0).
  495payload(unsigned64, Payload) -->
  496    fixed_uint64(Payload).
  497payload(float, Payload) -->
  498    fixed_float32(Payload).
  499payload(integer32, Payload) -->
  500    { uint32_int32_when(Payload0, Payload) },
  501    fixed_uint32(Payload0).
  502payload(unsigned32, Payload) -->
  503    fixed_uint32(Payload).
  504payload(integer, Payload) -->
  505    { nonvar(Payload), int64_zigzag(Payload, X) }, % TODO: int64_zigzag_when/2
  506    !,
  507    protobuf_var_int(X).
  508payload(integer, Payload) -->
  509    protobuf_var_int(X),
  510    { int64_zigzag(Payload, X) }. % TODO: int64_zigzag_when/2
  511payload(unsigned, Payload) -->
  512    protobuf_var_int(Payload),
  513    { Payload >= 0 }.
  514payload(signed32, Payload) --> % signed32 is not defined by prolog_type//2
  515                               % for wire-stream compatibility reasons.
  516    % signed32 ought to write 5 bytes for negative numbers, but both
  517    % the C++ and Python implementations write 10 bytes. For
  518    % wire-stream compatibility, we follow C++ and Python, even though
  519    % protoc decode appears to work just fine with 5 bytes --
  520    % presumably there are some issues with decoding 5 bytes and
  521    % getting the sign extension correct with some 32/64-bit integer
  522    % models.  See CodedOutputStream::WriteVarint32SignExtended(int32
  523    % value) in google/protobuf/io/coded_stream.h.
  524    payload(signed64, Payload).
  525payload(signed64, Payload) -->
  526    % protobuf_var_int//1 cannot handle negative numbers (note that
  527    % zig-zag encoding always results in a positive number), so
  528    % compute the 64-bit 2s complement, which is what is produced
  529    % form C++ and Python.
  530    { nonvar(Payload) },
  531    !,
  532    { uint64_int64(X, Payload) }, % TODO: uint64_int64_when
  533    protobuf_var_int(X).
  534payload(signed64, Payload) -->
  535    % See comment in previous clause about negative numbers.
  536    protobuf_var_int(X),
  537    { uint64_int64(X, Payload) }. % TODO: uint64_int64_when
  538payload(codes, Payload) -->
  539    { nonvar(Payload),
  540      !,
  541      length(Payload, Len)
  542    },
  543    protobuf_var_int(Len),
  544    code_string(Len, Payload).
  545payload(codes, Payload) -->
  546    protobuf_var_int(Len),
  547    code_string(Len, Payload).
  548payload(utf8_codes, Payload) -->
  549    { nonvar(Payload), % TODO: use freeze/2 or when/2
  550      !,
  551      utf8_codes_strict(Payload, B)
  552    },
  553    payload(codes, B).
  554payload(utf8_codes, Payload) -->
  555    payload(codes, B),
  556    { utf8_codes_strict(Payload, B) }.
  557payload(atom, Payload) -->
  558    { nonvar(Payload),
  559      atom_codes(Payload, Codes)
  560    },
  561    payload(utf8_codes, Codes),
  562    !.
  563payload(atom, Payload) -->
  564    payload(utf8_codes, Codes),
  565    { atom_codes(Payload, Codes) }.
  566payload(boolean, true) -->
  567    payload(unsigned, 1).
  568payload(boolean, false) -->
  569    payload(unsigned, 0).
  570payload(string, Payload) -->
  571    {   nonvar(Payload)
  572    ->  string_codes(Payload, Codes)
  573    ;   true
  574    },
  575    % string_codes produces a list of unicode, not bytes
  576    payload(utf8_codes, Codes),
  577    { string_codes(Payload, Codes) }.
  578payload(embedded, protobuf(PayloadSeq)) -->
  579    { ground(PayloadSeq),
  580      phrase(protobuf(PayloadSeq), Codes)
  581    },
  582    payload(codes, Codes),
  583    !.
  584payload(embedded, protobuf(PayloadSeq)) -->
  585    payload(codes, Codes),
  586    { phrase(protobuf(PayloadSeq), Codes) }.
  587payload(packed, TypedPayloadSeq) -->
  588    { TypedPayloadSeq =.. [PrologType, PayloadSeq],  % TypedPayloadSeq = PrologType(PayloadSeq)
  589      ground(PayloadSeq),
  590      phrase(packed_payload(PrologType, PayloadSeq), Codes)
  591    },
  592    payload(codes, Codes),
  593    !.
  594payload(packed, enum(EnumSeq)) -->
  595    !,
  596    % TODO: combine with next clause
  597    % TODO: replace =.. with a predicate that gives all the possibilities - see detag/6.
  598    { EnumSeq =.. [ Enum, Values ] }, % EnumSeq = Enum(Values)
  599    payload(codes, Codes),
  600    { phrase(packed_enum(Enum, Values), Codes) }.
  601payload(packed, TypedPayloadSeq) -->
  602    payload(codes, Codes),
  603    % TODO: replace =.. with a predicate that gives all the possibilities - see detag/6.
  604    { TypedPayloadSeq =.. [PrologType, PayloadSeq] },  % TypedPayloadSeq = PrologType(PayloadSeq)
  605    { phrase(packed_payload(PrologType, PayloadSeq), Codes) }.
  606
  607packed_payload(enum, EnumSeq) -->
  608    { ground(EnumSeq) }, !,
  609    { EnumSeq =.. [EnumType, Values] }, % EnumSeq = EnumType(Values)
  610    packed_enum(EnumType, Values).
  611packed_payload(PrologType, PayloadSeq) -->
  612    sequence_payload(PrologType, PayloadSeq).
  613
  614% sequence_payload//2 (because sequence//2 isn't compile-time expanded)
  615sequence_payload(PrologType, PayloadSeq) -->
  616    sequence_payload_(PayloadSeq, PrologType).
  617
  618sequence_payload_([], _PrologType) --> [ ].
  619sequence_payload_([Payload|PayloadSeq], PrologType) -->
  620        payload(PrologType, Payload),
  621        sequence_payload_(PayloadSeq, PrologType).
  622
  623packed_enum(Enum, [ A | As ]) -->
  624    % TODO: replace =.. with a predicate that gives all the possibilities - see detag/6.
  625    { E =.. [Enum, A] },
  626    payload(enum, E),
  627    packed_enum(Enum, As).
  628packed_enum(_, []) --> [ ].
  629
  630start_group(Tag) --> protobuf_tag_type(Tag, start_group).
  631
  632end_group(Tag) -->   protobuf_tag_type(Tag, end_group).
  633%
  634%
  635nothing([]) --> [], !.
  636
  637protobuf([Field | Fields]) -->
  638    % TODO: don't use =.. -- move logic to single_message
  639    (   { Field = repeated_embedded(Tag, protobuf(EmbeddedFields), Items) }
  640    ->  repeated_embedded_messages(Tag, EmbeddedFields, Items)
  641    ;   { Field =.. [ PrologType, Tag, Payload] },  % Field = PrologType(Tag, Payload)
  642        single_message(PrologType, Tag, Payload),
  643        (   protobuf(Fields)
  644        ;   nothing(Fields)
  645        )
  646    ),
  647    !.
  648
  649repeated_message(repeated_enum, Tag, Type, [A | B]) -->
  650    % TODO: replace =.. with a predicate that gives all the possibilities - see detag/6.
  651    { TypedPayload =.. [Type, A] },  % TypedPayload = Type(A)
  652    single_message(enum, Tag, TypedPayload),
  653    (   repeated_message(repeated_enum, Tag, Type, B)
  654    ;   nothing(B)
  655    ).
  656repeated_message(Type, Tag, [A | B]) -->
  657    { Type \= repeated_enum },
  658    single_message(Type, Tag, A),
  659    repeated_message(Type, Tag, B).
  660repeated_message(_Type, _Tag, A) -->
  661    nothing(A).
  662
  663repeated_embedded_messages(Tag, EmbeddedFields, [protobuf(A) | B]) -->
  664    { copy_term(EmbeddedFields, A) },
  665    single_message(embedded, Tag, protobuf(A)), !,
  666    repeated_embedded_messages(Tag, EmbeddedFields, B).
  667repeated_embedded_messages(_Tag, _EmbeddedFields, []) -->
  668    [ ].
 single_message(+PrologType:atom, ?Tag, ?Payload)// is det
Processes a single messages (e.g., one item in the list in protobuf([...]). The PrologType, Tag, Payload are from Field =.. [PrologType, Tag, Payload] in the caller
  674single_message(repeated, Tag, enum(EnumSeq)) -->
  675    !,
  676    { EnumSeq =.. [EnumType, Values] },  % EnumSeq = EnumType(Values)
  677    repeated_message(repeated_enum, Tag, EnumType, Values).
  678single_message(repeated, Tag, Payload) -->
  679    !,
  680    % TODO: replace =.. with a predicate that gives all the possibilities - see detag/6.
  681    { Payload =.. [PrologType, A] },  % Payload = PrologType(A)
  682    { PrologType \= enum },
  683    repeated_message(PrologType, Tag, A).
  684single_message(group, Tag, A) -->
  685    !,
  686    start_group(Tag),
  687    protobuf(A),
  688    end_group(Tag).
  689single_message(PrologType, Tag, Payload) -->
  690    { PrologType \= repeated, PrologType \= group },
  691    prolog_type(Tag, PrologType),
  692    payload(PrologType, Payload).
 protobuf_message(?Template, ?WireStream) is semidet
 protobuf_message(?Template, ?WireStream, ?Rest) is nondet
Marshals and unmarshals byte streams encoded using Google's Protobuf grammars. protobuf_message/2 provides a bi-directional parser that marshals a Prolog structure to WireStream, according to rules specified by Template. It can also unmarshal WireStream into a Prolog structure according to the same grammar. protobuf_message/3 provides a difference list version.
Arguments:
Template- is a protobuf grammar specification. On decode, unbound variables in the Template are unified with their respective values in the WireStream. On encode, Template must be ground.
WireStream- is a code list that was generated by a protobuf encoder using an equivalent template.
bug
- The protobuf specification states that the wire-stream can have the fields in any order and that unknown fields are to be ignored. This implementation assumes that the fields are in the exact order of the definition and match exactly. If you use protobuf_parse_from_codes/3, you can avoid this problem.o
  717protobuf_message(protobuf(TemplateList), WireStream) :-
  718    must_be(list, TemplateList),
  719    phrase(protobuf(TemplateList), WireStream),
  720    !.
  721
  722protobuf_message(protobuf(TemplateList), WireStream, Residue) :-
  723    must_be(list, TemplateList),
  724    phrase(protobuf(TemplateList), WireStream, Residue).
 protobuf_segment_message(+Segments:list, -WireStream:list(int)) is det
protobuf_segment_message(-Segments:list, +WireStream:list(int)) is det
Low level marshalling and unmarshalling of byte streams. The processing is independent of the .proto description, similar to the processing done by protoc --decode_raw. This means that field names aren't shown, only field numbers.

For unmarshalling, a simple heuristic is used on length-delimited segments: first interpret it as a message; if that fails, try to interpret as a UTF8 string; otherwise, leave it as a "blob" (if the heuristic was wrong, you can convert to a string or a blob by using protobuf_segment_convert/2). 32-bit and 64-bit numbers are left as codes because they could be either integers or floating point (use int32_codes_when/2, float32_codes_when/2, int64_codes_when/2, uint32_codes_when/2, uint64_codes_when/2, float64_codes_when/2 as appropriate); variable-length numbers ("varint" in the Protocol Buffers encoding documentation), might require "zigzag" conversion, int64_zigzag_when/2.

For marshalling, use the predicates int32_codes_when/2, float32_codes_when/2, int64_codes_when/2, uint32_codes_when/2, uint64_codes_when/2, float64_codes_when/2, int64_zigzag_when/2 to put integer and floating point values into the appropriate form.

Arguments:
Segments- a list containing terms of the following form (Tag is the field number; Codes is a list of integers):
  • varint(Tag,Varint) - Varint may need int64_zigzag_when/2
  • fixed64(Tag,Int) - Int signed, derived from the 8 codes
  • fixed32(Tag,Codes) - Int is signed, derived from the 4 codes
  • message(Tag,Segments)
  • group(Tag,Segments)
  • string(Tag,String) - String is a SWI-Prolog string
  • packed(Tag,Type(Scalars)) - Type is one of varint, fixed64, fixed32; Scalars is a list of Varint or Codes, which should be interpreted as described under those items. Note that the protobuf specification does not allow packed repeated string.
  • length_delimited(Tag,Codes)
  • repeated(List) - List of segments

Of these, group is deprecated in the protobuf documentation and shouldn't appear in modern code, having been superseded by nested message types.

For deciding how to interpret a length-delimited item (when Segments is a variable), an attempt is made to parse the item in the following order (although code should not rely on this order):

  • message
  • string (it must be in the form of a UTF string)
  • packed (which can backtrack through the various Types)
  • length_delimited - which always is possible.

The interpretation of length-delimited items can sometimes guess wrong; the interpretation can be undone by either backtracking or by using protobuf_segment_convert/2 to convert the incorrect segment to a string or a list of codes. Backtracking through all the possibilities is not recommended, because of combinatoric explosion (there is an example in the unit tests); instead, it is suggested that you take the first result and iterate through its items, calling protobuf_segment_convert/2 as needed to reinterpret incorrectly guessed segments.

WireStream- a code list that was generated by a protobuf endoder.
See also
- https://developers.google.com/protocol-buffers/docs/encoding
bug
- This predicate is preliminary and may change as additional functionality is added.
  797protobuf_segment_message(Segments, WireStream) :-
  798    protobuf_segment_message(Segments, WireStream, all).
  799
  800% protobuf_segment_message(?Segments, ?WireStream, +Mode)
  801%
  802% Mode is one of `all`, enumerating all interpretations of
  803% length_delimited segments on backtracking or first(MaxDepth),
  804% committing to the first interpretation of each segment and not
  805% interpreting length_delimited segments as messages or groups
  806% beyond MaxDepth.  Using `all` on input that does not parse results
  807% in a combinatorial explosion.
  808
  809protobuf_segment_message(Segments, WireStream, Mode) :-
  810    phrase(segment_message(Segments, Mode), WireStream).
  811
  812segment_message(Segments, Mode) -->
  813    sequence_segment(Segments, Mode).
  814
  815nested_mode(all, all).
  816nested_mode(first(D0), first(D)) :-
  817    D0 > 0,
  818    D is D0-1.
  819
  820max_depth(Depth) :-
  821    current_prolog_flag(protobuf_max_depth, Depth).
  822
  823% sequence_segment//2 (because sequence//2 isn't compile-time expanded)
  824sequence_segment([], _) --> [ ].
  825sequence_segment([Segment|Segments], Mode) -->
  826    segment(Segment, Mode),
  827    sequence_segment(Segments, Mode).
  828
  829segment(Segment, Mode) -->
  830    { nonvar(Segment) },
  831    !,
  832    % repeated(List) can be created by field_segment_scalar_or_repeated/7
  833    (   { Segment = repeated(Segments) }
  834    ->  sequence_segment(Segments, Mode)
  835    ;   { segment_type_tag(Segment, Type, Tag) },
  836        protobuf_tag_type(Tag, Type),
  837        segment(Type, Tag, Segment, Mode)
  838    ).
  839segment(Segment, first(D)) -->
  840    !,
  841    protobuf_tag_type(Tag, Type),
  842    segment(Type, Tag, Segment, first(D)),
  843    !.
  844segment(Segment, Mode) -->
  845    % { var(Segment) },
  846    protobuf_tag_type(Tag, Type),
  847    segment(Type, Tag, Segment, Mode).
  848
  849segment(varint, Tag, varint(Tag,Value), _) -->
  850    protobuf_var_int(Value).
  851segment(fixed64, Tag, fixed64(Tag, Int64), _) -->
  852    payload(integer64, Int64).
  853segment(fixed32, Tag, fixed32(Tag, Int32), _) -->
  854    payload(integer32, Int32).
  855segment(start_group, Tag, group(Tag, Segments), Mode) -->
  856    { nested_mode(Mode, Mode1) },
  857    segment_message(Segments, Mode1),
  858    protobuf_tag_type(Tag, end_group).
  859segment(length_delimited, Tag, Result, Mode) -->
  860    segment_length_delimited(Tag, Result, Mode).
  861
  862segment_length_delimited(Tag, Result, Mode) -->
  863    { nonvar(Result) },
  864    !,
  865    { length_delimited_segment(Result, Tag, Codes, Mode) },
  866    { length(Codes, CodesLen) },
  867    protobuf_var_int(CodesLen),
  868    code_string(CodesLen, Codes).
  869segment_length_delimited(Tag, Result, Mode) -->
  870    % { var(Result) },
  871    protobuf_var_int(CodesLen),
  872    code_string(CodesLen, Codes),
  873    { length_delimited_segment(Result, Tag, Codes, Mode) }.
  874
  875
  876length_delimited_segment(message(Tag,Segments), Tag, Codes, Mode) :-
  877    nested_mode(Mode, Mode1),
  878    protobuf_segment_message(Segments, Codes, Mode1).
  879length_delimited_segment(group(Tag,Segments), Tag, Codes, Mode) :-
  880    nested_mode(Mode, Mode1),
  881    phrase(segment_group(Tag, Segments, Mode1), Codes).
  882length_delimited_segment(string(Tag,String), Tag, Codes, _) :-
  883    (   nonvar(String)
  884    ->  string_codes(String, StringCodes),
  885        utf8_codes_strict(StringCodes, Codes)
  886    ;   utf8_codes_strict(StringCodes, Codes),
  887        string_codes(String, StringCodes)
  888    ).
  889length_delimited_segment(packed(Tag,Payload), Tag, Codes, _) :-
  890    % We don't know the type of the fields, so we try the 3
  891    % possibilities.  This has a problem: an even number of fixed32
  892    % items can't be distinguished from half the number of fixed64
  893    % items; but it's all we can do. The good news is that usually
  894    % varint (possibly with zig-zag encoding) is more common because
  895    % it's more compact (I don't know whether 32-bit or 64-bit is more
  896    % common for floating point).
  897    packed_option(Type, Items, Payload),
  898    phrase(sequence_payload(Type, Items), Codes).
  899length_delimited_segment(length_delimited(Tag,Codes), Tag, Codes, _).
  900
  901segment_group(Tag, Segments, Mode) -->
  902    start_group(Tag),
  903    segment_message(Segments, Mode),
  904    end_group(Tag).
  905
  906% See also prolog_type//2. Note that this doesn't handle repeated(List),
  907% which is used internally (see field_segment_scalar_or_repeated/7).
  908segment_type_tag(varint(Tag,_Value),           varint,           Tag).
  909segment_type_tag(fixed64(Tag,_Value),          fixed64,          Tag).
  910segment_type_tag(group(Tag,_Segments),         start_group,      Tag).
  911segment_type_tag(fixed32(Tag,_Value),          fixed32,          Tag).
  912segment_type_tag(length_delimited(Tag,_Codes), length_delimited, Tag).
  913segment_type_tag(message(Tag,_Segments),       length_delimited, Tag).
  914segment_type_tag(packed(Tag,_Payload),         length_delimited, Tag).
  915segment_type_tag(string(Tag,_String),          length_delimited, Tag).
 detag(+Compound, -Name, -Tag, -Value, List, -CompoundWithList) is semidet
Deconstruct Compound or the form Name(Tag,Value) and create a new CompoundWithList that replaces Value with List. This is used by packed_list/2 to transform [varint(1,0),varint(1,1)] to varint(1,[0,1]).

Some of Compound items are impossible for packed with the current protobuf spec, but they don't do any harm.

  925detag(varint(Tag,Value),           varint,            Tag, Value,     List, varint(List)).
  926detag(fixed64(Tag,Value),          fixed64,           Tag, Value,     List, fixed64(List)).
  927detag(fixed32(Tag,Value),          fixed32,           Tag, Value,     List, fixed32(List)).
  928detag(length_delimited(Tag,Codes), length_delimited,  Tag, Codes,     List, length_delimited(List)).
  929detag(message(Tag,Segments),       message,           Tag, Segments,  List, message(List)).
  930detag(packed(Tag,Payload),         packed,            Tag, Payload,   List, packed(List)). % TODO: delete?
  931detag(string(Tag,String),          string,            Tag, String,    List, string(List)).
  932
  933% See also prolog_type//2, but pick only one for each wirestream type
  934% For varint(Items), use one that doesn't do zigzag
  935packed_option(integer64, Items, fixed64(Items)).
  936packed_option(integer32, Items, fixed32(Items)).
  937packed_option(unsigned,  Items, varint(Items)).
  938% packed_option(integer,   Items, varint(Items)).
  939% packed_option(double,    Items, fixed64(Items)).
  940% packed_option(float,     Items, fixed32(Items)).
  941% packed_option(signed64,  Items, varint(Items)).
  942% packed_option(boolean,   Items, varint(Items)).
  943% packed_option(enum,      Items, varint(Items)).
 protobuf_segment_convert(+Form1, ?Form2) is multi
A convenience predicate for dealing with the situation where protobuf_segment_message/2 interprets a segment of the wire stream as a form that you don't want (e.g., as a message but it should have been a UTF8 string).

Form1 is converted back to the original wire stream, then the predicate non-deterimisticly attempts to convert the wire stream to a string or length_delimited term (or both: the lattter always succeeds).

The possible conversions are: message(Tag,Segments) => string(Tag,String) message(Tag,Segments) => length_delimited(Tag,Codes) string(Tag,String) => length_delimited(Tag,Codes) length_delimited(Tag,Codes) => length_delimited(Tag,Codes)

Note that for fixed32, fixed64, only the signed integer forms are given; if you want the floating point forms, then you need to do use int64_float64_when/2 and int32_float32_when/2.

For example:

?- protobuf_segment_convert(
       message(10,[fixed64(13,7309475598860382318)]),
       string(10,"inputType")).
?- protobuf_segment_convert(
       message(10,[fixed64(13,7309475598860382318)]),
       length_delimited(10,[105,110,112,117,116,84,121,112,101])).
?- protobuf_segment_convert(
       string(10, "inputType"),
       length_delimited(10,[105,110,112,117,116,84,121,112,101])).
?- forall(protobuf_segment_convert(string(1999,"\x1\\x0\\x0\\x0\\x2\\x0\\x0\\x0\"),Z), writeln(Z)).
      string(1999,)
      packed(1999,fixed64([8589934593]))
      packed(1999,fixed32([1,2]))
      packed(1999,varint([1,0,0,0,2,0,0,0]))
      length_delimited(1999,[1,0,0,0,2,0,0,0])

These come from:

Codes = [82,9,105,110,112,117,116,84,121,112,101],
protobuf_message(protobuf([embedded(T1, protobuf([integer64(T2, I)]))]), Codes),
protobuf_message(protobuf([string(T,S)]), Codes).
   T = 10, T1 = 10, T2 = 13,
   I = 7309475598860382318,
   S = "inputType".
bug
- This predicate is preliminary and may change as additional functionality is added.
- This predicate will sometimes generate unexpected choice points, Such as from protobuf_segment_convert(message(10,...), string(10,...))
Arguments:
Form1- message(Tag,Pieces), string(Tag,String), length_delimited(Tag,Codes), varint(Tag,Value), fixed64(Tag,Value), fixed32(Tag,Value).
Form2- similar to Form1.
 1002protobuf_segment_convert(Form1, Form2) :-
 1003    protobuf_segment_convert(Form1, Form2, all).
 1004
 1005% protobuf_segment_convert(+Form1, ?Form2, +Mode)
 1006%
 1007% As protobuf_segment_convert/2, using Mode as in
 1008% protobuf_segment_message/3 for interpreting nested segments.
 1009
 1010protobuf_segment_convert(Form, Form, _). % for efficiency, don't generate codes
 1011protobuf_segment_convert(Form1, Form2, Mode) :-
 1012    dif(Form1, Form2),          % Form1=Form2 handled by first clause
 1013    protobuf_segment_message([Form1], WireCodes),
 1014    phrase(tag_and_codes(Tag, Codes), WireCodes),
 1015    length_delimited_segment(Form2, Tag, Codes, Mode).
 1016
 1017% segment_convert(+Form1, ?Form2) is nondet.
 1018%
 1019% Used for converting guessed segments using the schema.  Commits to
 1020% the first interpretation of nested segments.
 1021
 1022segment_convert(Form1, Form2) :-
 1023    max_depth(MaxDepth),
 1024    protobuf_segment_convert(Form1, Form2, first(MaxDepth)).
 1025
 1026tag_and_codes(Tag, Codes) -->
 1027    protobuf_tag_type(Tag, length_delimited),
 1028    payload(codes, Codes).
 1029
 1030%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 1031% Documention of the foreign predicates, which are wrapped and exported.
 uint32_codes_when(?Uint32, ?Codes) is det
Convert between a 32-bit unsigned integer value and its wirestream codes. This is a low-level predicate; normally, you should use template_message/2 and the appropriate template term.

This predicate delays until either Uint32 or Codes is sufficiently instantiated.

There is also a non-delayed uint32_codes/2

SWI-Prolog doesn't have a 32-bit integer type, so 32-bit integer is simulated by doing a range check.

Arguments:
Uint32- an unsigned integer that's in the 32-bit range
Codes- a list of 4 integers (codes)
Errors
- Type,Domain if Value or Codes are of the wrong type or out of range.
 1051uint32_codes_when(Uint32, Codes) :-
 1052    when((nonvar(Uint32) ; nonvar(Codes)), uint32_codes(Uint32, Codes)).
 int32_codes_when(?Int32, ?Codes) is det
Convert between a 32-bit signed integer value and its wirestream codes. This is a low-level predicate; normally, you should use template_message/2 and the appropriate template term.

This predicate delays until either Int32 or Codes is sufficiently instantiated.

There is also a non-delayed int32_codes/2

SWI-Prolog doesn't have a 32-bit integer type, so 32-bit integer is simulated by doing a range check.

Arguments:
Int32- an unsigned integer that's in the 32-bit range
Codes- a list of 4 integers (codes)
Errors
- Type,Domain if Value or Codes are of the wrong type or out of range.
 1072int32_codes_when(Int32, Codes) :- % TODO: unused
 1073    when((nonvar(Int32) ; nonvar(Codes)), int32_codes(Int32, Codes)).
 float32_codes_when(?Value, ?Codes) is det
Convert between a 32-bit floating point value and its wirestream codes. This is a low-level predicate; normally, you should use template_message/2 and the appropriate template term.

This predicate delays until either Value or Codes is sufficiently instantiated.

There is also a non-delayed float32_codes/2

Arguments:
Value- a floating point number
Codes- a list of 4 integers (codes)
 1087float32_codes_when(Value, Codes) :-
 1088    when((nonvar(Value) ; nonvar(Codes)), float32_codes(Value, Codes)).
 uint64_codes_when(?Uint64, ?Codes) is det
Convert between a 64-bit unsigned integer value and its wirestream codes. This is a low-level predicate; normally, you should use template_message/2 and the appropriate template term.

SWI-Prolog allows integer values greater than 64 bits, so a range check is done.

This predicate delays until either Uint64 or Codes is sufficiently instantiated.

There is also a non-delayed uint64_codes/2

 1103%
 1104% @param Uint64 an unsigned integer
 1105% @param Codes a list of 8 integers (codes)
 1106%
 1107% @error Type,Domain if =Uint64= or =Codes= are of the wrong
 1108%                    type or out of range.
 1109uint64_codes_when(Uint64, Codes) :-
 1110    when((nonvar(Uint64) ; nonvar(Codes)), uint64_codes(Uint64, Codes)).
 int64_codes_when(?Int64, ?Codes) is det
Convert between a 64-bit signed integer value and its wirestream codes. This is a low-level predicate; normally, you should use template_message/2 and the appropriate template term.

SWI-Prolog allows integer values greater than 64 bits, so a range check is done.

This predicate delays until either Int64 or Codes is sufficiently instantiated.

There is also a non-delayed int64_codes/2

 1125%
 1126% @param Int64 an unsigned integer
 1127% @param Codes a list of 8 integers (codes)
 1128%
 1129% @error Type,Domain if =Int64= or =Codes= are of the wrong
 1130%                    type or out of range.
 1131int64_codes_when(Int64, Codes) :-  % TODO: unused
 1132    when((nonvar(Int64) ; nonvar(Codes)), int64_codes(Int64, Codes)).
 float64_codes_when(?Value, ?Codes) is det
Convert between a 64-bit floating point value and its wirestream codes. This is a low-level predicate; normally, you should use template_message/2 and the appropriate template term.

This predicate delays until either Value or Codes is sufficiently instantiated.

There is also a non-delayed float64_codes/2

Arguments:
Value- a floating point number
Codes- a list of 8 integers (codes)
Errors
- instantiation error if both Value and Codes are uninstantiated.
bug
- May give misleading exception under some circumstances (e.g., float64_codes(_, [_,_,_,_,_,_,_,_]).
 1151float64_codes_when(Value, Codes) :-
 1152    when((nonvar(Value) ; nonvar(Codes)), float64_codes(Value, Codes)).
 int64_zigzag_when(?Original, ?Encoded) is det
Convert between a signed integer value and its zigzag encoding, used for the protobuf sint32 and sint64 types. This is a low-level predicate; normally, you should use template_message/2 and the appropriate template term.

SWI-Prolog allows integer values greater than 64 bits, so a range check is done.

This predicate delays until either Original or Encoded is sufficiently instantiated.

There is also a non-delayed int64_zigzag/2

Arguments:
Original- an integer in the original form
Encoded- the zigzag encoding of Original
Errors
- Type,Domain if Original or Encoded are of the wrong type or out of range.
- instantiation error if both Original and Encoded are uninstantiated.
See also
- https://developers.google.com/protocol-buffers/docs/encoding#types
 1177int64_zigzag_when(Original, Encoded) :-
 1178    when((nonvar(Original) ; nonvar(Encoded)), int64_zigzag(Original, Encoded)).
 uint64_int64_when(?Uint64:integer, ?Int64:integer) is det
Reinterpret-cast between uint64 and int64. For example, uint64_int64(0xffffffffffffffff,-1).

This predicate delays until either Uint64 or Int64 is sufficiently instantiated.

There is also a non-delayed uint64_int64/2

Arguments:
Uint64- 64-bit unsigned integer
Int64- 64-bit signed integer
Errors
- Type,Domain if Value or Codes are of the wrong type or out of range.
- instantiation error if both Value and Codes are uninstantiated.
 1196uint64_int64_when(Uint64, Int64) :-
 1197    when((nonvar(Uint64) ; nonvar(Int64)), uint64_int64(Uint64, Int64)).
 1198
 1199% Reversed argument ordering for maplist/3
 1200int64_uint64_when(Int64, Uint64) :-
 1201    uint64_int64_when(Uint64, Int64).
 uint32_int32_when(?Uint32, ?Int32) is det
Reinterpret-case between uint32 and int32.

This predicate delays until either Uint32 or Int32 is sufficiently instantiated.

There is also a non-delayed uint32_int32/2

Arguments:
Uint32- 32-bit unsigned integer (range between 0 and 4294967295).
Int32- 32-bit signed integer (range between -2147483648 and 2147483647).
Errors
- Type,Domain if Int32 or Uint32 are of the wrong type or out of range.
- instantiation error if both UInt32 and Int32 are uninstantiated.
 1218uint32_int32_when(Uint32, Int32) :-
 1219    when((nonvar(Uint32) ; nonvar(Int32)), uint32_int32(Uint32, Int32)).
 varint_int32_when(?Varint, ?Int32) is det
Conversion between an int32 field and its varint value. As specified, negative values are written sign-extended to 64 bits (10 bytes). When reading, both the 64-bit and the 32-bit forms are accepted.
 1226varint_int32_when(Varint, Int32) :-
 1227    when((nonvar(Varint) ; nonvar(Int32)), varint_int32(Varint, Int32)).
 1228
 1229varint_int32(Varint, Int32) :-
 1230    nonvar(Int32),
 1231    !,
 1232    uint32_int32(_, Int32),             % range check
 1233    uint64_int64(Varint, Int32).
 1234varint_int32(Varint, Int32) :-
 1235    uint32_int32(Varint, Int32).
 1236
 1237% Reversed argument ordering for maplist/3
 1238int32_uint32_when(Int32, Uint32) :-
 1239
 1240    uint32_int32_when(Uint32, Int32).
 int64_float64_when(?Int64:integer, ?Float64:float) is det
Reinterpret-cast between uint64 and float64. For example, int64_float64(3ff0000000000000,1.0).

This predicate delays until either Int64 or Float64 is sufficiently instantiated.

There is also a non-delayed uint64_int64/2

Arguments:
Int64- 64-bit unsigned integer
Float64- 64-bit float
Errors
- Type,Domain if Value or Codes are of the wrong type or out of range.
- instantiation error if both Value and Codes are uninstantiated.
 1258int64_float64_when(Int64, Float64) :-
 1259    when((nonvar(Int64) ; nonvar(Float64)), int64_float64(Int64, Float64)).
 int32_float32_when(?Int32:integer, ?Float32:float) is det
Reinterpret-cast between uint32 and float32. For example, int32_float32(0x3f800000,1.0).

This predicate delays until either Int32 or Float32 is sufficiently instantiated.

There is also a non-delayed uint32_int32/2

Arguments:
Int32- 32-bit unsigned integer
Float32- 32-bit float
Errors
- Type,Domain if Value or Codes are of the wrong type or out of range.
- instantiation error if both Value and Codes are uninstantiated.
 1277int32_float32_when(Int32, Float32) :-
 1278    when((nonvar(Int32) ; nonvar(Float32)), int32_float32(Int32, Float32)).
 1279
 1280
 1281%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 1282%
 1283% Use protobufs meta-data (see the section on protoc in the "overview" documentation).
 1284
 1285% The protoc plugin generates the following facts (all starting with "proto_meta_").
 1286% The are documented in protoc-gen-swipl and in the overview section.
 1287
 1288:- multifile
 1289     proto_meta_normalize/2,              % (Unnormalized, Normalized)
 1290     proto_meta_package/3,                % (Package, FileName, Options)
 1291     proto_meta_message_type/3,           % (Fqn, Package, Name)
 1292     proto_meta_message_type_map_entry/1, % (Fqn)
 1293     proto_meta_field_name/4,             % (Fqn, FieldNumber, FieldName, FqnName)
 1294     proto_meta_field_json_name/2,        % (FqnName, JsonName)
 1295     proto_meta_field_label/2,            % (FqnName, LabelRepeatOptional) % LABEL_OPTIONAL, LABEL_REQUIRED, LABEL_REPEATED
 1296     proto_meta_field_type/2,             % (FqnName, Type) % TYPE_INT32, TYPE_MESSAGE, etc
 1297     proto_meta_field_type_name/2,        % (FqnName, TypeName)
 1298     proto_meta_field_default_value/2,    % (FqnName, DefaultValue)
 1299     proto_meta_field_option_packed/1,    % (FqnName)
 1300     proto_meta_enum_type/3,              % (FqnName, Fqn, Name)
 1301     proto_meta_enum_value/3,             % (FqnName, Name, Number)
 1302     proto_meta_field_oneof_index/2,      % (FqnName, Index)
 1303     proto_meta_oneof/3.                  % (FqnName, Index, Name)
 1304
 1305proto_meta_enum_value_when(ContextType, EnumValue, IntValue) :-
 1306    when((nonvar(EnumValue) ; nonvar(IntValue)),
 1307         proto_meta_enum_value_(ContextType, EnumValue, IntValue)).
 1308
 1309proto_meta_enum_value_(ContextType, EnumValue, IntValue) :-
 1310    (   proto_meta_enum_value(ContextType, EnumValue, IntValue)
 1311    ->  true
 1312    ;   existence_error(ContextType, EnumValue-IntValue)
 1313    ).
 1314
 1315:- det(segment_to_term/4).
 segment_to_term(+ContextType:atom, +Depth, +Segment, -FieldAndValue) is det
ContextType is the type (name) of the containing message Segment is a segment from protobuf_segment_message/2 Depth is the number of further nested messages allowed. TODO: if performance is an issue, this code can be combined with protobuf_segment_message/2 (and thereby avoid the use of protobuf_segment_convert/2)
 1322segment_to_term(ContextType0, Depth, Segment, FieldAndValue) =>
 1323    segment_type_tag(Segment, _, Tag),
 1324    field_and_type(ContextType0, Tag, FieldName, _FqnName, ContextType, RepeatOptional, Type),
 1325    (   RepeatOptional = repeat_packed
 1326    ->  convert_segment_packed(Type, ContextType, Tag, Segment, Value)
 1327    ;   nested_segment(Type, Tag, MsgSegment, MsgSegments)
 1328    ->  (   Depth > 0
 1329        ->  Depth1 is Depth-1
 1330        ;   max_depth(MaxDepth),
 1331            resource_error(protobuf_max_depth(MaxDepth))
 1332        ),
 1333        segment_convert(Segment, MsgSegment),
 1334        maplist(segment_to_term(ContextType, Depth1), MsgSegments, MsgFields),
 1335        combine_fields(MsgFields, ContextType{}, Value)
 1336    ;   convert_segment(Type, ContextType, Tag, Segment, Value)
 1337    ),
 1338    !, % TODO: get rid of this?
 1339    FieldAndValue = field_and_value(FieldName,RepeatOptional,Value).
 1340
 1341nested_segment('TYPE_MESSAGE', Tag, message(Tag, MsgSegments), MsgSegments).
 1342nested_segment('TYPE_GROUP',   Tag, group(Tag, MsgSegments),   MsgSegments).
 1343
 1344% :- det(convert_segment_packed/5). % TODO: "succeeded with a choicepoint"
 1345%! convert_segment_packed(+Type:atom, +ContextType:atom, +Tag:atom, ?Segment, ?Values) is det.
 1346% Reversible on =Segment=, =Values=.
 1347%
 1348% TODO: these are very similar to convert_segment - can they be combined?
 1349
 1350convert_segment_packed('TYPE_DOUBLE', _ContextType, Tag, Segment0, Values) =>
 1351    freeze(Segment0, segment_convert(Segment0, packed(Tag, fixed64(Values0)))),
 1352    maplist(int64_float64_when, Values0, Values), !.
 1353convert_segment_packed('TYPE_FLOAT', _ContextType, Tag, Segment0, Values) =>
 1354    freeze(Segment0, segment_convert(Segment0, packed(Tag, fixed32(Values0)))),
 1355    maplist(int32_float32_when, Values0, Values), !.
 1356convert_segment_packed('TYPE_INT64', _ContextType, Tag, Segment0, Values) =>
 1357    freeze(Segment0, segment_convert(Segment0, packed(Tag, varint(Values0)))),
 1358    maplist(uint64_int64_when, Values0, Values).
 1359convert_segment_packed('TYPE_UINT64', _ContextType, Tag, Segment0, Values) =>
 1360    segment_convert(Segment0, packed(Tag, varint(Values))), !.
 1361convert_segment_packed('TYPE_INT32', _ContextType, Tag, Segment0, Values) =>
 1362    freeze(Segment0, segment_convert(Segment0, packed(Tag, varint(Values0)))),
 1363    maplist(varint_int32_when, Values0, Values).
 1364convert_segment_packed('TYPE_FIXED64', _ContextType, Tag, Segment0, Values) =>
 1365    freeze(Segment0, segment_convert(Segment0, packed(Tag, fixed64(Values0)))),
 1366    maplist(int64_uint64_when, Values0, Values).
 1367convert_segment_packed('TYPE_FIXED32', _ContextType, Tag, Segment0, Values) =>
 1368    freeze(Segment0, segment_convert(Segment0, packed(Tag, fixed32(Values0)))),
 1369    maplist(int32_uint32_when, Values0, Values).
 1370convert_segment_packed('TYPE_BOOL', _ContextType, Tag, Segment0, Values) =>
 1371    freeze(Segment0, segment_convert(Segment0, packed(Tag, varint(Values0)))),
 1372    maplist(int_bool_when, Values0, Values).
 1373% TYPE_STRING  isn't allowed TODO: add it anyway?
 1374% TYPE_GROUP   isn't allowed
 1375% TYPE_MESSAGE isn't allowed
 1376% TYPE_BYTES   isn't allowed TODO: add it anyway?
 1377convert_segment_packed('TYPE_UINT32', _ContextType, Tag, Segment0, Values) =>
 1378    segment_convert(Segment0, packed(Tag, varint(Values))), !.
 1379convert_segment_packed('TYPE_ENUM', ContextType, Tag, Segment0, Values) =>
 1380    % uint64_int64_when(...), % TODO! https://github.com/SWI-Prolog/contrib-protobufs/issues/9
 1381    freeze(Segment0, segment_convert(Segment0, packed(Tag, varint(Values0)))),
 1382    maplist(convert_enum(ContextType), Values, Values0).
 1383convert_segment_packed('TYPE_SFIXED32', _ContextType, Tag, Segment0, Values) =>
 1384    segment_convert(Segment0, packed(Tag, fixed32(Values))).
 1385convert_segment_packed('TYPE_SFIXED64', _ContextType, Tag, Segment0, Values) =>
 1386    segment_convert(Segment0, packed(Tag, fixed64(Values))).
 1387convert_segment_packed('TYPE_SINT32', _ContextType, Tag, Segment0, Values) =>
 1388    freeze(Segment0, segment_convert(Segment0, packed(Tag, varint(Values0)))),
 1389    maplist(int64_zigzag_when, Values, Values0).
 1390convert_segment_packed('TYPE_SINT64', _ContextType, Tag, Segment0, Values) =>
 1391    freeze(Segment0, segment_convert(Segment0, packed(Tag, varint(Values0)))),
 1392    maplist(int64_zigzag_when, Values, Values0).
 1393% convert_segment_packed(Type, ContextType, Tag, Segment, Values) => % TODO: delete this clause
 1394%     domain_error(type(type=Type, % TODO: this is a bit funky
 1395%                       context_type=ContextType),
 1396%                  value(segment=Segment,
 1397%                        tag=Tag,
 1398%                        values=Values)).
 1399
 1400:- det(convert_segment/5).
 convert_segment(+Type:atom, +ContextType:atom, Tag:atom, ?Segment, ?Value) is det
Compute an appropriate Value from the combination of descriptor "type" (in Type) and a Segment. Reversible on Segment, Values.
 1405convert_segment('TYPE_DOUBLE', _ContextType, Tag, Segment0, Value) =>
 1406    Segment = fixed64(Tag,Int64),
 1407    int64_float64_when(Int64, Value),
 1408    segment_convert(Segment0, Segment), !.
 1409convert_segment('TYPE_FLOAT', _ContextType, Tag, Segment0, Value) =>
 1410    Segment = fixed32(Tag,Int32),
 1411    int32_float32_when(Int32, Value),
 1412    segment_convert(Segment0, Segment), !.
 1413convert_segment('TYPE_INT64', _ContextType, Tag, Segment0, Value) =>
 1414    Segment = varint(Tag,Value0),
 1415    uint64_int64_when(Value0, Value),
 1416    segment_convert(Segment0, Segment), !.
 1417convert_segment('TYPE_UINT64', _ContextType, Tag, Segment0, Value) =>
 1418    Segment = varint(Tag,Value),
 1419    segment_convert(Segment0, Segment), !.
 1420convert_segment('TYPE_INT32', _ContextType, Tag, Segment0, Value) =>
 1421    Segment = varint(Tag,Value0),
 1422    varint_int32_when(Value0, Value),
 1423    segment_convert(Segment0, Segment), !.
 1424convert_segment('TYPE_FIXED64', _ContextType, Tag, Segment0, Value) =>
 1425    Segment = fixed64(Tag,Value0),
 1426    uint64_int64_when(Value, Value0),
 1427    segment_convert(Segment0, Segment), !.
 1428convert_segment('TYPE_FIXED32', _ContextType, Tag, Segment0, Value) =>
 1429    Segment = fixed32(Tag,Value0),
 1430    uint32_int32_when(Value, Value0),
 1431    segment_convert(Segment0, Segment), !.
 1432convert_segment('TYPE_BOOL', _ContextType, Tag, Segment0, Value) =>
 1433    Segment = varint(Tag,Value0),
 1434    int_bool_when(Value0, Value),
 1435    segment_convert(Segment0, Segment), !.
 1436% convert_segment('TYPE_STRING', _ContextType, Tag, Segment0, Value) =>
 1437%     Segment = string(Tag,ValueStr),
 1438%     segment_convert(Segment0, Segment), !,
 1439%     (   false    % TODO: control whether atom or string with an option
 1440%     ->  atom_string(Value, ValueStr)
 1441%     ;   Value = ValueStr
 1442%     ).
 1443convert_segment('TYPE_STRING', _ContextType, Tag, Segment0, Value) =>
 1444    % TODO: option to control whether to use atom_string(Value,ValueStr)
 1445    Segment = string(Tag,Value),
 1446    (   segment_convert(Segment0, Segment)
 1447    ->  true
 1448    ;   nonvar(Segment0),
 1449        segment_type_tag(Segment0, length_delimited, _)
 1450    ->  syntax_error(illegal_utf8_sequence)
 1451    ;   fail
 1452    ).
 1453convert_segment('TYPE_GROUP', ContextType, Tag, Segment0, Value) =>
 1454    Segment = group(Tag,MsgSegments),
 1455    % TODO: combine with TYPE_MESSAGE code:
 1456    (   nonvar(Value)
 1457    ->  dict_pairs(Value, _, FieldValues),
 1458        maplist(field_segment(ContextType), FieldValues, MsgSegments),
 1459        segment_convert(Segment0, Segment)
 1460    ;   segment_convert(Segment0, Segment),
 1461        max_depth(MaxDepth),
 1462        maplist(segment_to_term(ContextType, MaxDepth), MsgSegments, MsgFields),
 1463        combine_fields(MsgFields, ContextType{}, Value)
 1464    ), !.
 1465convert_segment('TYPE_MESSAGE', ContextType, Tag, Segment0, Value) =>
 1466    Segment = message(Tag,MsgSegments),
 1467    (   nonvar(Value)
 1468    ->  dict_pairs(Value, _, FieldValues),
 1469        maplist(field_segment(ContextType), FieldValues, MsgSegments),
 1470        segment_convert(Segment0, Segment)
 1471    ;   segment_convert(Segment0, Segment),
 1472        max_depth(MaxDepth),
 1473        maplist(segment_to_term(ContextType, MaxDepth), MsgSegments, MsgFields),
 1474        combine_fields(MsgFields, ContextType{}, Value)
 1475    ), !.
 1476convert_segment('TYPE_BYTES', _ContextType, Tag, Segment0, Value) =>
 1477    Segment = length_delimited(Tag,Value),
 1478    segment_convert(Segment0, Segment), !.
 1479convert_segment('TYPE_UINT32', _ContextType, Tag, Segment0, Value) =>
 1480    Segment = varint(Tag,Value),
 1481    segment_convert(Segment0, Segment), !.
 1482convert_segment('TYPE_ENUM', ContextType, Tag, Segment0, Value) =>
 1483    Segment = varint(Tag,Value0),
 1484    convert_enum(ContextType, Value, Value0), % TODO: negative values: https://github.com/SWI-Prolog/contrib-protobufs/issues/9
 1485    segment_convert(Segment0, Segment), !.
 1486convert_segment('TYPE_SFIXED32', _ContextType, Tag, Segment0, Value) =>
 1487    Segment = fixed32(Tag,Value),
 1488    segment_convert(Segment0, Segment), !.
 1489convert_segment('TYPE_SFIXED64', _ContextType, Tag, Segment0, Value) =>
 1490    Segment = fixed64(Tag,Value),
 1491    segment_convert(Segment0, Segment), !.
 1492convert_segment('TYPE_SINT32', _ContextType, Tag, Segment0, Value) =>
 1493    Segment = varint(Tag,Value0),
 1494    int64_zigzag_when(Value, Value0),
 1495    segment_convert(Segment0, Segment), !.
 1496convert_segment('TYPE_SINT64', _ContextType, Tag, Segment0, Value) =>
 1497    Segment = varint(Tag,Value0),
 1498    int64_zigzag_when(Value, Value0),
 1499    segment_convert(Segment0, Segment), !.
 1500
 1501convert_enum(ContextType, Enum, Uint) :-
 1502    uint64_int64_when(Uint, Int),
 1503    proto_meta_enum_value_when(ContextType, Enum, Int).
 1504
 1505% TODO: use options to translate to/from false, true (see json_read/3)
 1506int_bool(0, false).
 1507int_bool(1, true).
 1508
 1509int_bool_when(Int, Bool) :-
 1510    when((nonvar(Int) ; nonvar(Bool)), int_bool(Int, Bool)).
 add_defaulted_fields(+Value0:dict, ContextType:atom, -Value:dict) is det
 1513add_defaulted_fields(Value0, ContextType, Value) :-
 1514    % Can use bagof or findall if we know that there aren't any
 1515    % duplicated proto_meta_field_name/4 rules, although this isn't
 1516    % strictly necessary (just avoids processing a field twice).
 1517    ( setof(Name-DefaultValue, message_field_default(ContextType, Name, DefaultValue), DefaultValues)
 1518    ->  true
 1519    ;   DefaultValues = []
 1520    ),
 1521    foldl(add_empty_field_if_missing, DefaultValues, Value0, Value).
 message_field_default(+ContextType:atom, Name:atom, -DefaultValue) is semidet
 1524message_field_default(ContextType, Name, DefaultValue) :-
 1525    proto_meta_field_name(ContextType, _FieldNumber, Name, Fqn),
 1526    proto_meta_field_default_value(Fqn, DefaultValue),
 1527    % If the field is part of a "oneof" group, then there will be a
 1528    % proto_meta_oneof entry for it (using the oneof_index). All
 1529    % fields have a oneof_index, but our code doesn't depend on that.
 1530    \+ (proto_meta_field_oneof_index(Fqn, OneofIndex),
 1531        proto_meta_oneof(ContextType, OneofIndex, _)).
 1532
 1533add_empty_field_if_missing(FieldName-DefaultValue, Dict0, Dict) :-
 1534    (   get_dict(FieldName, Dict0, _)
 1535    ->  Dict = Dict0
 1536    ;   put_dict(FieldName, Dict0, DefaultValue, Dict)
 1537    ).
 1538
 1539:- det(combine_fields/3).
 combine_fields(+Fields:list, +MsgDict0, -MsgDict) is det
Combines the fields into a dict and sets missing fields to their default values. If the field is marked as 'norepeat' (optional/required), then the last occurrence is kept (as per the protobuf wire spec) If the field is marked as 'repeat' or 'repeat_packed', then all the occurrences are put into a list, in order. The occurrences do not need to be together, as is allowed by the protobuf spec.
 1547combine_fields(Fields, MsgDict0, MsgDict) :-
 1548    combine_fields_(Fields, MsgDict0, MsgDict1, Repeated),
 1549    keysort(Repeated, Sorted),          % stable: preserves the order
 1550    group_pairs_by_key(Sorted, Grouped),
 1551    foldl(put_repeated, Grouped, MsgDict1, MsgDict2),
 1552    is_dict(MsgDict2, ContextType),
 1553    add_defaulted_fields(MsgDict2, ContextType, MsgDict).
 1554
 1555:- det(combine_fields_/4). 1556combine_fields_([], MsgDict0, MsgDict, Repeated) =>
 1557    MsgDict = MsgDict0,
 1558    Repeated = [].
 1559combine_fields_([field_and_value(Field,norepeat,Value)|Fields], MsgDict0, MsgDict, Repeated) =>
 1560    put_dict(Field, MsgDict0, Value, MsgDict1),
 1561    combine_fields_(Fields, MsgDict1, MsgDict, Repeated).
 1562combine_fields_([field_and_value(Field,repeat_packed,Values)|Fields], MsgDict0, MsgDict, Repeated) =>
 1563    Repeated = [Field-Values|Repeated1],
 1564    combine_fields_(Fields, MsgDict0, MsgDict, Repeated1).
 1565combine_fields_([field_and_value(Field,repeat,Value)|Fields], MsgDict0, MsgDict, Repeated) =>
 1566    Repeated = [Field-[Value]|Repeated1],
 1567    combine_fields_(Fields, MsgDict0, MsgDict, Repeated1).
 1568
 1569put_repeated(Field-ValueLists, MsgDict0, MsgDict) :-
 1570    (   get_dict(Field, MsgDict0, ExistingValues)
 1571    ->  append([ExistingValues|ValueLists], Values)
 1572    ;   append(ValueLists, Values)
 1573    ),
 1574    put_dict(Field, MsgDict0, Values, MsgDict).
 1575
 1576:- det(field_and_type/7).
 field_and_type(+ContextType:atom, +Tag:int, -FieldName:atom, -FqnName:atom, -ContextType2:atom, -RepeatOptional:atom, -Type:atom) is det
Lookup a ContextType and Tag to get the field name, type, etc.
 1579field_and_type(ContextType, Tag, FieldName, FqnName, ContextType2, RepeatOptional, Type) =>
 1580    assertion(ground(ContextType)), % TODO: remove
 1581    assertion(ground(Tag)), % TODO: remove
 1582    (   proto_meta_field_name(ContextType, Tag, FieldName, FqnName),
 1583        proto_meta_field_type_name(FqnName, ContextType2),
 1584        fqn_repeat_optional(FqnName, RepeatOptional),
 1585        proto_meta_field_type(FqnName, Type)
 1586    ->  true % Remove choicepoint, if JITI didn't do the right thing.
 1587    ;   existence_error(ContextType, Tag)
 1588    ).
 fqn_repeat_optional(+FqnName:atom, -RepeatOptional:atom) is det
Lookup up proto_meta_field_label(FqnName, _), proto_meta_field_option_packed(FqnName) and set RepeatOptional to one of norepeat, repeat, repeat_packed.
 1594fqn_repeat_optional(FqnName, RepeatOptional) =>
 1595    % TODO: existence_error if \+ proto_meta_field_label
 1596    proto_meta_field_label(FqnName, LabelRepeatOptional),
 1597    (   LabelRepeatOptional = 'LABEL_REPEATED',
 1598        proto_meta_field_option_packed(FqnName)
 1599    ->  RepeatOptional = repeat_packed
 1600    ;   \+ proto_meta_field_option_packed(FqnName), % validity check
 1601        fqn_repeat_optional_2(LabelRepeatOptional, RepeatOptional)
 1602    ).
 1603
 1604:- det(fqn_repeat_optional_2/2).
 fqn_repeat_optional_2(+DescriptorLabelEnum:atom, -RepeatOrEmpty:atom) is det
Map the descriptor "label" to 'repeat' or 'norepeat'. From proto_meta_enum_value('.google.protobuf.FieldDescriptorProto.Label', Label, _).
 1608fqn_repeat_optional_2('LABEL_OPTIONAL', norepeat).
 1609fqn_repeat_optional_2('LABEL_REQUIRED', norepeat).
 1610fqn_repeat_optional_2('LABEL_REPEATED', repeat).
 field_descriptor_label_repeated(+Label:atom) is semidet
From proto_meta_enum_value('.google.protobuf.FieldDescriptorProto.Label', 'LABEL_REPEATED', _). TODO: unused
 1615field_descriptor_label_repeated('LABEL_REPEATED').
 field_descriptor_label_single(+Label:atom) is semidet
From proto_meta_enum_value('.google.protobuf.FieldDescriptorProto.Label', Label, _).
 1619field_descriptor_label_single('LABEL_OPTIONAL').
 1620field_descriptor_label_single('LABEL_REQUIRED').
 1621
 1622:- det(term_to_segments/3).
 term_to_segments(+Term:dict, +MessageType:atom, Segments) is det
Recursively traverse a Term, generating message segments
 1625term_to_segments(Term, MessageType, Segments) :-
 1626    dict_pairs(Term, _, FieldValues),
 1627    maplist(field_segment(MessageType), FieldValues, Segments).
 1628
 1629:- det(field_segment/3). 1630% MessageType is the FQN of the field type (e.g., '.test.Scalars1')
 1631% FieldName-Value is from the dict_pairs of the term.
 1632% TODO: Throw an error if proto_meta_field_name/4 fails (need to make
 1633%       sure of all the possible uses of field_segment/3 and that
 1634%       nothing depends on it being able to fail without an error).
 1635field_segment(MessageType, FieldName-Value, Segment) :-
 1636    (   proto_meta_field_name(MessageType, Tag, FieldName, FieldFqn),
 1637        proto_meta_field_type(FieldFqn, FieldType),
 1638        proto_meta_field_type_name(FieldFqn, FieldTypeName),
 1639        proto_meta_field_label(FieldFqn, Label)
 1640    ->  true  % Remove choicepoint, if JITI didn't do the right thing.
 1641    ;   existence_error(MessageType, FieldName-Value)
 1642    ),
 1643    (   proto_meta_field_option_packed(FieldFqn)
 1644    ->  Packed = packed
 1645    ;   Packed = not_packed
 1646    ),
 1647    field_segment_scalar_or_repeated(Label, Packed, FieldType, Tag, FieldTypeName, Value, Segment),
 1648    !. % TODO: remove
 1649
 1650:- det(field_segment_scalar_or_repeated/7).
 field_segment_scalar_or_repeated(+Label, +Packed, +FieldType, +Tag, +FieldTypeName, ?Value, Segment) is det
FieldType is from the .proto meta information ('TYPE_SINT32', etc.)
 1653field_segment_scalar_or_repeated('LABEL_OPTIONAL', not_packed, FieldType, Tag, FieldTypeName, Value, Segment) =>
 1654    convert_segment(FieldType, FieldTypeName, Tag, Segment, Value).
 1655field_segment_scalar_or_repeated('LABEL_REQUIRED', not_packed, FieldType, Tag, FieldTypeName, Value, Segment) =>  % same as LABEL_OPTIONAL
 1656    convert_segment(FieldType, FieldTypeName, Tag, Segment, Value).
 1657field_segment_scalar_or_repeated('LABEL_REPEATED', packed, FieldType, Tag, FieldTypeName, Values, Segment) =>
 1658    Segment = packed(Tag,FieldValues),
 1659    maplist(convert_segment_v_s(FieldType, FieldTypeName, Tag), Values, Segments0),
 1660    packed_list(Segments0, FieldValues).
 1661field_segment_scalar_or_repeated('LABEL_REPEATED', not_packed, FieldType, Tag, FieldTypeName, Values, Segment) =>
 1662    Segment = repeated(Segments),
 1663    maplist(convert_segment_v_s(FieldType, FieldTypeName, Tag), Values, Segments).
 1664% field_segment_scalar_or_repeated(Label, Packed, FieldType, Tag, FieldTypeName, Value, Segment) :- % TODO: delete this clause
 1665%     domain_error(type(field_type=FieldType,     % TODO: this is a bit funky
 1666%                       label=Label,
 1667%                       packed=Packed),
 1668%                  value(tag=Tag, field_type_name=FieldTypeName, value=Value, segment=Segment)).
 1669
 1670convert_segment_v_s(FieldType, FieldTypeName, Tag, Value, Segment) :-
 1671    convert_segment(FieldType, FieldTypeName, Tag, Segment, Value).
 1672
 1673% Convert [varint(1,10),varint(1,20)] to varint(1,[10,20]).
 1674packed_list([], []).
 1675packed_list([T1|Ts], PackedList) :-
 1676    detag(T1, Functor, Tag, _V1, List, PackedList),
 1677    packed_list_([T1|Ts], Functor, Tag, List).
 1678
 1679% Functor and Tag are only for verifying that the terms are of the
 1680% expected form.
 1681packed_list_([], _, _, []).
 1682packed_list_([T1|Ts], Functor, Tag, [X1|Xs]) :-
 1683    detag(T1, Functor, Tag, X1, _, _),
 1684    packed_list_(Ts, Functor, Tag, Xs).
 protobuf_field_is_map(+MessageType, +FieldName) is semidet
Succeeds if MessageType's FieldName is defined as a map<...> in the .proto file.
 1689protobuf_field_is_map(MessageType0, FieldName) :-
 1690    proto_meta_normalize(MessageType0, MessageType),
 1691    proto_meta_field_name(MessageType, _, FieldName, FieldFqn),
 1692    proto_meta_field_type(FieldFqn, 'TYPE_MESSAGE'),
 1693    proto_meta_field_label(FieldFqn, 'LABEL_REPEATED'),
 1694    proto_meta_field_type_name(FieldFqn, FieldTypeName),
 1695    proto_meta_message_type_map_entry(FieldTypeName),
 1696    assertion(proto_meta_field_name(FieldTypeName, 1, key, _)),
 1697    assertion(proto_meta_field_name(FieldTypeName, 2, value, _)),
 1698    !.
 protobuf_map_pairs(+ProtobufTermList:list, ?DictTag:atom, ?Pairs) is det
Convert between a list of protobuf map entries (in the form DictTag{key:Key, value:Value} and a key-value list as described in library(pairs). At least one of ProtobufTermList and Pairs must be instantiated; DictTag can be uninstantiated. If ProtobufTermList is from a term created by protobuf_parse_from_codes/3, the ordering of the items is undefined; you can order them by using keysort/2 (or by a predicate such as dict_pairs/3, list_to_assoc/2, or list_to_rbtree/2.
 1709protobuf_map_pairs(ProtobufTermList, DictTag, Pairs) :-
 1710    maplist(protobuf_dict_map_pairs(DictTag), ProtobufTermList, Pairs).
 1711
 1712protobuf_dict_map_pairs(DictTag, DictTag{key:Key,value:Value}, Key-Value)