Extend inline / fixed length bytes array support (issue #244)
[apps/agl-service-can-low-level.git] / generator / nanopb_generator.py
1 #!/usr/bin/env python
2
3 from __future__ import unicode_literals
4
5 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
6 nanopb_version = "nanopb-0.3.8-dev"
7
8 import sys
9 import re
10 from functools import reduce
11
12 try:
13     # Add some dummy imports to keep packaging tools happy.
14     import google, distutils.util # bbfreeze seems to need these
15     import pkg_resources # pyinstaller / protobuf 2.5 seem to need these
16 except:
17     # Don't care, we will error out later if it is actually important.
18     pass
19
20 try:
21     import google.protobuf.text_format as text_format
22     import google.protobuf.descriptor_pb2 as descriptor
23 except:
24     sys.stderr.write('''
25          *************************************************************
26          *** Could not import the Google protobuf Python libraries ***
27          *** Try installing package 'python-protobuf' or similar.  ***
28          *************************************************************
29     ''' + '\n')
30     raise
31
32 try:
33     import proto.nanopb_pb2 as nanopb_pb2
34     import proto.plugin_pb2 as plugin_pb2
35 except:
36     sys.stderr.write('''
37          ********************************************************************
38          *** Failed to import the protocol definitions for generator.     ***
39          *** You have to run 'make' in the nanopb/generator/proto folder. ***
40          ********************************************************************
41     ''' + '\n')
42     raise
43
44 # ---------------------------------------------------------------------------
45 #                     Generation of single fields
46 # ---------------------------------------------------------------------------
47
48 import time
49 import os.path
50
51 # Values are tuple (c type, pb type, encoded size, int_size_allowed)
52 FieldD = descriptor.FieldDescriptorProto
53 datatypes = {
54     FieldD.TYPE_BOOL:       ('bool',     'BOOL',        1,  False),
55     FieldD.TYPE_DOUBLE:     ('double',   'DOUBLE',      8,  False),
56     FieldD.TYPE_FIXED32:    ('uint32_t', 'FIXED32',     4,  False),
57     FieldD.TYPE_FIXED64:    ('uint64_t', 'FIXED64',     8,  False),
58     FieldD.TYPE_FLOAT:      ('float',    'FLOAT',       4,  False),
59     FieldD.TYPE_INT32:      ('int32_t',  'INT32',      10,  True),
60     FieldD.TYPE_INT64:      ('int64_t',  'INT64',      10,  True),
61     FieldD.TYPE_SFIXED32:   ('int32_t',  'SFIXED32',    4,  False),
62     FieldD.TYPE_SFIXED64:   ('int64_t',  'SFIXED64',    8,  False),
63     FieldD.TYPE_SINT32:     ('int32_t',  'SINT32',      5,  True),
64     FieldD.TYPE_SINT64:     ('int64_t',  'SINT64',     10,  True),
65     FieldD.TYPE_UINT32:     ('uint32_t', 'UINT32',      5,  True),
66     FieldD.TYPE_UINT64:     ('uint64_t', 'UINT64',     10,  True)
67 }
68
69 # Integer size overrides (from .proto settings)
70 intsizes = {
71     nanopb_pb2.IS_8:     'int8_t',
72     nanopb_pb2.IS_16:    'int16_t',
73     nanopb_pb2.IS_32:    'int32_t',
74     nanopb_pb2.IS_64:    'int64_t',
75 }
76
77 # String types (for python 2 / python 3 compatibility)
78 try:
79     strtypes = (unicode, str)
80 except NameError:
81     strtypes = (str, )
82
83 class Names:
84     '''Keeps a set of nested names and formats them to C identifier.'''
85     def __init__(self, parts = ()):
86         if isinstance(parts, Names):
87             parts = parts.parts
88         self.parts = tuple(parts)
89
90     def __str__(self):
91         return '_'.join(self.parts)
92
93     def __add__(self, other):
94         if isinstance(other, strtypes):
95             return Names(self.parts + (other,))
96         elif isinstance(other, tuple):
97             return Names(self.parts + other)
98         else:
99             raise ValueError("Name parts should be of type str")
100
101     def __eq__(self, other):
102         return isinstance(other, Names) and self.parts == other.parts
103
104 def names_from_type_name(type_name):
105     '''Parse Names() from FieldDescriptorProto type_name'''
106     if type_name[0] != '.':
107         raise NotImplementedError("Lookup of non-absolute type names is not supported")
108     return Names(type_name[1:].split('.'))
109
110 def varint_max_size(max_value):
111     '''Returns the maximum number of bytes a varint can take when encoded.'''
112     if max_value < 0:
113         max_value = 2**64 - max_value
114     for i in range(1, 11):
115         if (max_value >> (i * 7)) == 0:
116             return i
117     raise ValueError("Value too large for varint: " + str(max_value))
118
119 assert varint_max_size(-1) == 10
120 assert varint_max_size(0) == 1
121 assert varint_max_size(127) == 1
122 assert varint_max_size(128) == 2
123
124 class EncodedSize:
125     '''Class used to represent the encoded size of a field or a message.
126     Consists of a combination of symbolic sizes and integer sizes.'''
127     def __init__(self, value = 0, symbols = []):
128         if isinstance(value, EncodedSize):
129             self.value = value.value
130             self.symbols = value.symbols
131         elif isinstance(value, strtypes + (Names,)):
132             self.symbols = [str(value)]
133             self.value = 0
134         else:
135             self.value = value
136             self.symbols = symbols
137
138     def __add__(self, other):
139         if isinstance(other, int):
140             return EncodedSize(self.value + other, self.symbols)
141         elif isinstance(other, strtypes + (Names,)):
142             return EncodedSize(self.value, self.symbols + [str(other)])
143         elif isinstance(other, EncodedSize):
144             return EncodedSize(self.value + other.value, self.symbols + other.symbols)
145         else:
146             raise ValueError("Cannot add size: " + repr(other))
147
148     def __mul__(self, other):
149         if isinstance(other, int):
150             return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
151         else:
152             raise ValueError("Cannot multiply size: " + repr(other))
153
154     def __str__(self):
155         if not self.symbols:
156             return str(self.value)
157         else:
158             return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
159
160     def upperlimit(self):
161         if not self.symbols:
162             return self.value
163         else:
164             return 2**32 - 1
165
166 class Enum:
167     def __init__(self, names, desc, enum_options):
168         '''desc is EnumDescriptorProto'''
169
170         self.options = enum_options
171         self.names = names + desc.name
172
173         if enum_options.long_names:
174             self.values = [(self.names + x.name, x.number) for x in desc.value]
175         else:
176             self.values = [(names + x.name, x.number) for x in desc.value]
177
178         self.value_longnames = [self.names + x.name for x in desc.value]
179         self.packed = enum_options.packed_enum
180
181     def has_negative(self):
182         for n, v in self.values:
183             if v < 0:
184                 return True
185         return False
186
187     def encoded_size(self):
188         return max([varint_max_size(v) for n,v in self.values])
189
190     def __str__(self):
191         result = 'typedef enum _%s {\n' % self.names
192         result += ',\n'.join(["    %s = %d" % x for x in self.values])
193         result += '\n}'
194
195         if self.packed:
196             result += ' pb_packed'
197
198         result += ' %s;' % self.names
199
200         result += '\n#define _%s_MIN %s' % (self.names, self.values[0][0])
201         result += '\n#define _%s_MAX %s' % (self.names, self.values[-1][0])
202         result += '\n#define _%s_ARRAYSIZE ((%s)(%s+1))' % (self.names, self.names, self.values[-1][0])
203
204         if not self.options.long_names:
205             # Define the long names always so that enum value references
206             # from other files work properly.
207             for i, x in enumerate(self.values):
208                 result += '\n#define %s %s' % (self.value_longnames[i], x[0])
209
210         if self.options.enum_to_string:
211             result += '\nconst char *%s_name(%s v);\n' % (self.names, self.names)
212
213         return result
214
215     def enum_to_string_definition(self):
216         if not self.options.enum_to_string:
217             return ""
218
219         result = 'const char *%s_name(%s v) {\n' % (self.names, self.names)
220         result += '    switch (v) {\n'
221
222         for ((enumname, _), strname) in zip(self.values, self.value_longnames):
223             # Strip off the leading type name from the string value.
224             strval = str(strname)[len(str(self.names)) + 1:]
225             result += '        case %s: return "%s";\n' % (enumname, strval)
226
227         result += '    }\n'
228         result += '    return "unknown";\n'
229         result += '}\n'
230
231         return result
232
233 class FieldMaxSize:
234     def __init__(self, worst = 0, checks = [], field_name = 'undefined'):
235         if isinstance(worst, list):
236             self.worst = max(i for i in worst if i is not None)
237         else:
238             self.worst = worst
239
240         self.worst_field = field_name
241         self.checks = list(checks)
242
243     def extend(self, extend, field_name = None):
244         self.worst = max(self.worst, extend.worst)
245
246         if self.worst == extend.worst:
247             self.worst_field = extend.worst_field
248
249         self.checks.extend(extend.checks)
250
251 class Field:
252     def __init__(self, struct_name, desc, field_options):
253         '''desc is FieldDescriptorProto'''
254         self.tag = desc.number
255         self.struct_name = struct_name
256         self.union_name = None
257         self.name = desc.name
258         self.default = None
259         self.max_size = None
260         self.max_count = None
261         self.array_decl = ""
262         self.enc_size = None
263         self.ctype = None
264
265         if field_options.type == nanopb_pb2.FT_INLINE:
266             # Before nanopb-0.3.8, fixed length bytes arrays were specified
267             # by setting type to FT_INLINE. But to handle pointer typed fields,
268             # it makes sense to have it as a separate option.
269             field_options.type = nanopb_pb2.FT_STATIC
270             field_options.fixed_length = True
271
272         # Parse field options
273         if field_options.HasField("max_size"):
274             self.max_size = field_options.max_size
275         
276         if desc.type == FieldD.TYPE_STRING and field_options.HasField("max_length"):
277             # max_length overrides max_size for strings
278             self.max_size = field_options.max_length + 1
279
280         if field_options.HasField("max_count"):
281             self.max_count = field_options.max_count
282
283         if desc.HasField('default_value'):
284             self.default = desc.default_value
285
286         # Check field rules, i.e. required/optional/repeated.
287         can_be_static = True
288         if desc.label == FieldD.LABEL_REPEATED:
289             self.rules = 'REPEATED'
290             if self.max_count is None:
291                 can_be_static = False
292             else:
293                 self.array_decl = '[%d]' % self.max_count
294         elif field_options.proto3:
295             self.rules = 'SINGULAR'
296         elif desc.label == FieldD.LABEL_REQUIRED:
297             self.rules = 'REQUIRED'
298         elif desc.label == FieldD.LABEL_OPTIONAL:
299             self.rules = 'OPTIONAL'
300         else:
301             raise NotImplementedError(desc.label)
302
303         # Check if the field can be implemented with static allocation
304         # i.e. whether the data size is known.
305         if desc.type == FieldD.TYPE_STRING and self.max_size is None:
306             can_be_static = False
307
308         if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
309             can_be_static = False
310
311         # Decide how the field data will be allocated
312         if field_options.type == nanopb_pb2.FT_DEFAULT:
313             if can_be_static:
314                 field_options.type = nanopb_pb2.FT_STATIC
315             else:
316                 field_options.type = nanopb_pb2.FT_CALLBACK
317
318         if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
319             raise Exception("Field %s is defined as static, but max_size or "
320                             "max_count is not given." % self.name)
321
322         if field_options.type == nanopb_pb2.FT_STATIC:
323             self.allocation = 'STATIC'
324         elif field_options.type == nanopb_pb2.FT_POINTER:
325             self.allocation = 'POINTER'
326         elif field_options.type == nanopb_pb2.FT_CALLBACK:
327             self.allocation = 'CALLBACK'
328         else:
329             raise NotImplementedError(field_options.type)
330
331         # Decide the C data type to use in the struct.
332         if desc.type in datatypes:
333             self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type]
334
335             # Override the field size if user wants to use smaller integers
336             if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT:
337                 self.ctype = intsizes[field_options.int_size]
338                 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64:
339                     self.ctype = 'u' + self.ctype;
340         elif desc.type == FieldD.TYPE_ENUM:
341             self.pbtype = 'ENUM'
342             self.ctype = names_from_type_name(desc.type_name)
343             if self.default is not None:
344                 self.default = self.ctype + self.default
345             self.enc_size = None # Needs to be filled in when enum values are known
346         elif desc.type == FieldD.TYPE_STRING:
347             self.pbtype = 'STRING'
348             self.ctype = 'char'
349             if self.allocation == 'STATIC':
350                 self.ctype = 'char'
351                 self.array_decl += '[%d]' % self.max_size
352                 self.enc_size = varint_max_size(self.max_size) + self.max_size
353         elif desc.type == FieldD.TYPE_BYTES:
354             if field_options.fixed_length:
355                 self.pbtype = 'FIXED_LENGTH_BYTES'
356                 self.enc_size = varint_max_size(self.max_size) + self.max_size
357                 self.ctype = 'pb_byte_t'
358                 self.array_decl += '[%d]' % self.max_size
359             else:
360                 self.pbtype = 'BYTES'
361                 self.ctype = 'pb_bytes_array_t'
362                 if self.allocation == 'STATIC':
363                     self.ctype = self.struct_name + self.name + 't'
364                     self.enc_size = varint_max_size(self.max_size) + self.max_size
365         elif desc.type == FieldD.TYPE_MESSAGE:
366             self.pbtype = 'MESSAGE'
367             self.ctype = self.submsgname = names_from_type_name(desc.type_name)
368             self.enc_size = None # Needs to be filled in after the message type is available
369         else:
370             raise NotImplementedError(desc.type)
371
372     def __lt__(self, other):
373         return self.tag < other.tag
374
375     def __str__(self):
376         result = ''
377         if self.allocation == 'POINTER':
378             if self.rules == 'REPEATED':
379                 result += '    pb_size_t ' + self.name + '_count;\n'
380
381             if self.pbtype == 'MESSAGE':
382                 # Use struct definition, so recursive submessages are possible
383                 result += '    struct _%s *%s;' % (self.ctype, self.name)
384             elif self.pbtype == 'FIXED_LENGTH_BYTES':
385                 # Pointer to fixed size array
386                 result += '    %s (*%s)%s;' % (self.ctype, self.name, self.array_decl)
387             elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']:
388                 # String/bytes arrays need to be defined as pointers to pointers
389                 result += '    %s **%s;' % (self.ctype, self.name)
390             else:
391                 result += '    %s *%s;' % (self.ctype, self.name)
392         elif self.allocation == 'CALLBACK':
393             result += '    pb_callback_t %s;' % self.name
394         else:
395             if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
396                 result += '    bool has_' + self.name + ';\n'
397             elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
398                 result += '    pb_size_t ' + self.name + '_count;\n'
399             result += '    %s %s%s;' % (self.ctype, self.name, self.array_decl)
400         return result
401
402     def types(self):
403         '''Return definitions for any special types this field might need.'''
404         if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
405             result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
406         else:
407             result = ''
408         return result
409
410     def get_dependencies(self):
411         '''Get list of type names used by this field.'''
412         if self.allocation == 'STATIC':
413             return [str(self.ctype)]
414         else:
415             return []
416
417     def get_initializer(self, null_init, inner_init_only = False):
418         '''Return literal expression for this field's default value.
419         null_init: If True, initialize to a 0 value instead of default from .proto
420         inner_init_only: If True, exclude initialization for any count/has fields
421         '''
422
423         inner_init = None
424         if self.pbtype == 'MESSAGE':
425             if null_init:
426                 inner_init = '%s_init_zero' % self.ctype
427             else:
428                 inner_init = '%s_init_default' % self.ctype
429         elif self.default is None or null_init:
430             if self.pbtype == 'STRING':
431                 inner_init = '""'
432             elif self.pbtype == 'BYTES':
433                 inner_init = '{0, {0}}'
434             elif self.pbtype == 'FIXED_LENGTH_BYTES':
435                 inner_init = '{0}'
436             elif self.pbtype in ('ENUM', 'UENUM'):
437                 inner_init = '(%s)0' % self.ctype
438             else:
439                 inner_init = '0'
440         else:
441             if self.pbtype == 'STRING':
442                 inner_init = self.default.replace('"', '\\"')
443                 inner_init = '"' + inner_init + '"'
444             elif self.pbtype == 'BYTES':
445                 data = ['0x%02x' % ord(c) for c in self.default]
446                 if len(data) == 0:
447                     inner_init = '{0, {0}}'
448                 else:
449                     inner_init = '{%d, {%s}}' % (len(data), ','.join(data))
450             elif self.pbtype == 'FIXED_LENGTH_BYTES':
451                 data = ['0x%02x' % ord(c) for c in self.default]
452                 if len(data) == 0:
453                     inner_init = '{0}'
454                 else:
455                     inner_init = '{%s}' % ','.join(data)
456             elif self.pbtype in ['FIXED32', 'UINT32']:
457                 inner_init = str(self.default) + 'u'
458             elif self.pbtype in ['FIXED64', 'UINT64']:
459                 inner_init = str(self.default) + 'ull'
460             elif self.pbtype in ['SFIXED64', 'INT64']:
461                 inner_init = str(self.default) + 'll'
462             else:
463                 inner_init = str(self.default)
464
465         if inner_init_only:
466             return inner_init
467
468         outer_init = None
469         if self.allocation == 'STATIC':
470             if self.rules == 'REPEATED':
471                 outer_init = '0, {'
472                 outer_init += ', '.join([inner_init] * self.max_count)
473                 outer_init += '}'
474             elif self.rules == 'OPTIONAL':
475                 outer_init = 'false, ' + inner_init
476             else:
477                 outer_init = inner_init
478         elif self.allocation == 'POINTER':
479             if self.rules == 'REPEATED':
480                 outer_init = '0, NULL'
481             else:
482                 outer_init = 'NULL'
483         elif self.allocation == 'CALLBACK':
484             if self.pbtype == 'EXTENSION':
485                 outer_init = 'NULL'
486             else:
487                 outer_init = '{{NULL}, NULL}'
488
489         return outer_init
490
491     def default_decl(self, declaration_only = False):
492         '''Return definition for this field's default value.'''
493         if self.default is None:
494             return None
495
496         ctype = self.ctype
497         default = self.get_initializer(False, True)
498         array_decl = ''
499
500         if self.pbtype == 'STRING':
501             if self.allocation != 'STATIC':
502                 return None # Not implemented
503             array_decl = '[%d]' % self.max_size
504         elif self.pbtype == 'BYTES':
505             if self.allocation != 'STATIC':
506                 return None # Not implemented
507         elif self.pbtype == 'FIXED_LENGTH_BYTES':
508             if self.allocation != 'STATIC':
509                 return None # Not implemented
510             array_decl = '[%d]' % self.max_size
511
512         if declaration_only:
513             return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
514         else:
515             return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
516
517     def tags(self):
518         '''Return the #define for the tag number of this field.'''
519         identifier = '%s_%s_tag' % (self.struct_name, self.name)
520         return '#define %-40s %d\n' % (identifier, self.tag)
521
522     def pb_field_t(self, prev_field_name, union_index = None):
523         '''Return the pb_field_t initializer to use in the constant array.
524         prev_field_name is the name of the previous field or None. For OneOf
525         unions, union_index is the index of this field inside the OneOf.
526         '''
527
528         if self.rules == 'ONEOF':
529             if self.anonymous:
530                 result = '    PB_ANONYMOUS_ONEOF_FIELD(%s, ' % self.union_name
531             else:
532                 result = '    PB_ONEOF_FIELD(%s, ' % self.union_name
533         else:
534             result = '    PB_FIELD('
535
536         result += '%3d, ' % self.tag
537         result += '%-8s, ' % self.pbtype
538         result += '%s, ' % self.rules
539         result += '%-8s, ' % self.allocation
540         
541         if union_index is not None and union_index > 0:
542             result += 'UNION, '
543         elif prev_field_name is None:
544             result += 'FIRST, '
545         else:
546             result += 'OTHER, '
547         
548         result += '%s, ' % self.struct_name
549         result += '%s, ' % self.name
550         result += '%s, ' % (prev_field_name or self.name)
551
552         if self.pbtype == 'MESSAGE':
553             result += '&%s_fields)' % self.submsgname
554         elif self.default is None:
555             result += '0)'
556         elif self.pbtype in ['BYTES', 'STRING', 'FIXED_LENGTH_BYTES'] and self.allocation != 'STATIC':
557             result += '0)' # Arbitrary size default values not implemented
558         elif self.rules == 'OPTEXT':
559             result += '0)' # Default value for extensions is not implemented
560         else:
561             result += '&%s_default)' % (self.struct_name + self.name)
562
563         return result
564
565     def get_last_field_name(self):
566         return self.name
567
568     def largest_field_value(self):
569         '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
570         Returns numeric value or a C-expression for assert.'''
571         check = []
572         if self.pbtype == 'MESSAGE' and self.allocation == 'STATIC':
573             if self.rules == 'REPEATED':
574                 check.append('pb_membersize(%s, %s[0])' % (self.struct_name, self.name))
575             elif self.rules == 'ONEOF':
576                 if self.anonymous:
577                     check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
578                 else:
579                     check.append('pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name))
580             else:
581                 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
582         elif self.pbtype == 'BYTES' and self.allocation == 'STATIC':
583             if self.max_size > 251:
584                 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
585
586         return FieldMaxSize([self.tag, self.max_size, self.max_count],
587                             check,
588                             ('%s.%s' % (self.struct_name, self.name)))
589
590     def encoded_size(self, dependencies):
591         '''Return the maximum size that this field can take when encoded,
592         including the field tag. If the size cannot be determined, returns
593         None.'''
594
595         if self.allocation != 'STATIC':
596             return None
597
598         if self.pbtype == 'MESSAGE':
599             encsize = None
600             if str(self.submsgname) in dependencies:
601                 submsg = dependencies[str(self.submsgname)]
602                 encsize = submsg.encoded_size(dependencies)
603                 if encsize is not None:
604                     # Include submessage length prefix
605                     encsize += varint_max_size(encsize.upperlimit())
606
607             if encsize is None:
608                 # Submessage or its size cannot be found.
609                 # This can occur if submessage is defined in different
610                 # file, and it or its .options could not be found.
611                 # Instead of direct numeric value, reference the size that
612                 # has been #defined in the other file.
613                 encsize = EncodedSize(self.submsgname + 'size')
614
615                 # We will have to make a conservative assumption on the length
616                 # prefix size, though.
617                 encsize += 5
618
619         elif self.pbtype in ['ENUM', 'UENUM']:
620             if str(self.ctype) in dependencies:
621                 enumtype = dependencies[str(self.ctype)]
622                 encsize = enumtype.encoded_size()
623             else:
624                 # Conservative assumption
625                 encsize = 10
626
627         elif self.enc_size is None:
628             raise RuntimeError("Could not determine encoded size for %s.%s"
629                                % (self.struct_name, self.name))
630         else:
631             encsize = EncodedSize(self.enc_size)
632
633         encsize += varint_max_size(self.tag << 3) # Tag + wire type
634
635         if self.rules == 'REPEATED':
636             # Decoders must be always able to handle unpacked arrays.
637             # Therefore we have to reserve space for it, even though
638             # we emit packed arrays ourselves.
639             encsize *= self.max_count
640
641         return encsize
642
643
644 class ExtensionRange(Field):
645     def __init__(self, struct_name, range_start, field_options):
646         '''Implements a special pb_extension_t* field in an extensible message
647         structure. The range_start signifies the index at which the extensions
648         start. Not necessarily all tags above this are extensions, it is merely
649         a speed optimization.
650         '''
651         self.tag = range_start
652         self.struct_name = struct_name
653         self.name = 'extensions'
654         self.pbtype = 'EXTENSION'
655         self.rules = 'OPTIONAL'
656         self.allocation = 'CALLBACK'
657         self.ctype = 'pb_extension_t'
658         self.array_decl = ''
659         self.default = None
660         self.max_size = 0
661         self.max_count = 0
662
663     def __str__(self):
664         return '    pb_extension_t *extensions;'
665
666     def types(self):
667         return ''
668
669     def tags(self):
670         return ''
671
672     def encoded_size(self, dependencies):
673         # We exclude extensions from the count, because they cannot be known
674         # until runtime. Other option would be to return None here, but this
675         # way the value remains useful if extensions are not used.
676         return EncodedSize(0)
677
678 class ExtensionField(Field):
679     def __init__(self, struct_name, desc, field_options):
680         self.fullname = struct_name + desc.name
681         self.extendee_name = names_from_type_name(desc.extendee)
682         Field.__init__(self, self.fullname + 'struct', desc, field_options)
683
684         if self.rules != 'OPTIONAL':
685             self.skip = True
686         else:
687             self.skip = False
688             self.rules = 'OPTEXT'
689
690     def tags(self):
691         '''Return the #define for the tag number of this field.'''
692         identifier = '%s_tag' % self.fullname
693         return '#define %-40s %d\n' % (identifier, self.tag)
694
695     def extension_decl(self):
696         '''Declaration of the extension type in the .pb.h file'''
697         if self.skip:
698             msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
699             msg +='   type of extension fields is currently supported. */\n'
700             return msg
701
702         return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
703             (self.fullname, str(self).strip()))
704
705     def extension_def(self):
706         '''Definition of the extension type in the .pb.c file'''
707
708         if self.skip:
709             return ''
710
711         result  = 'typedef struct {\n'
712         result += str(self)
713         result += '\n} %s;\n\n' % self.struct_name
714         result += ('static const pb_field_t %s_field = \n  %s;\n\n' %
715                     (self.fullname, self.pb_field_t(None)))
716         result += 'const pb_extension_type_t %s = {\n' % self.fullname
717         result += '    NULL,\n'
718         result += '    NULL,\n'
719         result += '    &%s_field\n' % self.fullname
720         result += '};\n'
721         return result
722
723
724 # ---------------------------------------------------------------------------
725 #                   Generation of oneofs (unions)
726 # ---------------------------------------------------------------------------
727
728 class OneOf(Field):
729     def __init__(self, struct_name, oneof_desc):
730         self.struct_name = struct_name
731         self.name = oneof_desc.name
732         self.ctype = 'union'
733         self.pbtype = 'oneof'
734         self.fields = []
735         self.allocation = 'ONEOF'
736         self.default = None
737         self.rules = 'ONEOF'
738         self.anonymous = False
739
740     def add_field(self, field):
741         if field.allocation == 'CALLBACK':
742             raise Exception("Callback fields inside of oneof are not supported"
743                             + " (field %s)" % field.name)
744
745         field.union_name = self.name
746         field.rules = 'ONEOF'
747         field.anonymous = self.anonymous
748         self.fields.append(field)
749         self.fields.sort(key = lambda f: f.tag)
750
751         # Sort by the lowest tag number inside union
752         self.tag = min([f.tag for f in self.fields])
753
754     def __str__(self):
755         result = ''
756         if self.fields:
757             result += '    pb_size_t which_' + self.name + ";\n"
758             result += '    union {\n'
759             for f in self.fields:
760                 result += '    ' + str(f).replace('\n', '\n    ') + '\n'
761             if self.anonymous:
762                 result += '    };'
763             else:
764                 result += '    } ' + self.name + ';'
765         return result
766
767     def types(self):
768         return ''.join([f.types() for f in self.fields])
769
770     def get_dependencies(self):
771         deps = []
772         for f in self.fields:
773             deps += f.get_dependencies()
774         return deps
775
776     def get_initializer(self, null_init):
777         return '0, {' + self.fields[0].get_initializer(null_init) + '}'
778
779     def default_decl(self, declaration_only = False):
780         return None
781
782     def tags(self):
783         return ''.join([f.tags() for f in self.fields])
784
785     def pb_field_t(self, prev_field_name):
786         parts = []
787         for union_index, field in enumerate(self.fields):
788             parts.append(field.pb_field_t(prev_field_name, union_index))
789         return ',\n'.join(parts)
790
791     def get_last_field_name(self):
792         if self.anonymous:
793             return self.fields[-1].name
794         else:
795             return self.name + '.' + self.fields[-1].name
796
797     def largest_field_value(self):
798         largest = FieldMaxSize()
799         for f in self.fields:
800             largest.extend(f.largest_field_value())
801         return largest
802
803     def encoded_size(self, dependencies):
804         '''Returns the size of the largest oneof field.'''
805         largest = EncodedSize(0)
806         for f in self.fields:
807             size = EncodedSize(f.encoded_size(dependencies))
808             if size.value is None:
809                 return None
810             elif size.symbols:
811                 return None # Cannot resolve maximum of symbols
812             elif size.value > largest.value:
813                 largest = size
814
815         return largest
816
817 # ---------------------------------------------------------------------------
818 #                   Generation of messages (structures)
819 # ---------------------------------------------------------------------------
820
821
822 class Message:
823     def __init__(self, names, desc, message_options):
824         self.name = names
825         self.fields = []
826         self.oneofs = {}
827         no_unions = []
828
829         if message_options.msgid:
830             self.msgid = message_options.msgid
831
832         if hasattr(desc, 'oneof_decl'):
833             for i, f in enumerate(desc.oneof_decl):
834                 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name)
835                 if oneof_options.no_unions:
836                     no_unions.append(i) # No union, but add fields normally
837                 elif oneof_options.type == nanopb_pb2.FT_IGNORE:
838                     pass # No union and skip fields also
839                 else:
840                     oneof = OneOf(self.name, f)
841                     if oneof_options.anonymous_oneof:
842                         oneof.anonymous = True
843                     self.oneofs[i] = oneof
844                     self.fields.append(oneof)
845
846         for f in desc.field:
847             field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
848             if field_options.type == nanopb_pb2.FT_IGNORE:
849                 continue
850
851             field = Field(self.name, f, field_options)
852             if (hasattr(f, 'oneof_index') and
853                 f.HasField('oneof_index') and
854                 f.oneof_index not in no_unions):
855                 if f.oneof_index in self.oneofs:
856                     self.oneofs[f.oneof_index].add_field(field)
857             else:
858                 self.fields.append(field)
859
860         if len(desc.extension_range) > 0:
861             field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
862             range_start = min([r.start for r in desc.extension_range])
863             if field_options.type != nanopb_pb2.FT_IGNORE:
864                 self.fields.append(ExtensionRange(self.name, range_start, field_options))
865
866         self.packed = message_options.packed_struct
867         self.ordered_fields = self.fields[:]
868         self.ordered_fields.sort()
869
870     def get_dependencies(self):
871         '''Get list of type names that this structure refers to.'''
872         deps = []
873         for f in self.fields:
874             deps += f.get_dependencies()
875         return deps
876
877     def __str__(self):
878         result = 'typedef struct _%s {\n' % self.name
879
880         if not self.ordered_fields:
881             # Empty structs are not allowed in C standard.
882             # Therefore add a dummy field if an empty message occurs.
883             result += '    char dummy_field;'
884
885         result += '\n'.join([str(f) for f in self.ordered_fields])
886         result += '\n/* @@protoc_insertion_point(struct:%s) */' % self.name
887         result += '\n}'
888
889         if self.packed:
890             result += ' pb_packed'
891
892         result += ' %s;' % self.name
893
894         if self.packed:
895             result = 'PB_PACKED_STRUCT_START\n' + result
896             result += '\nPB_PACKED_STRUCT_END'
897
898         return result
899
900     def types(self):
901         return ''.join([f.types() for f in self.fields])
902
903     def get_initializer(self, null_init):
904         if not self.ordered_fields:
905             return '{0}'
906
907         parts = []
908         for field in self.ordered_fields:
909             parts.append(field.get_initializer(null_init))
910         return '{' + ', '.join(parts) + '}'
911
912     def default_decl(self, declaration_only = False):
913         result = ""
914         for field in self.fields:
915             default = field.default_decl(declaration_only)
916             if default is not None:
917                 result += default + '\n'
918         return result
919
920     def count_required_fields(self):
921         '''Returns number of required fields inside this message'''
922         count = 0
923         for f in self.fields:
924             if not isinstance(f, OneOf):
925                 if f.rules == 'REQUIRED':
926                     count += 1
927         return count
928
929     def count_all_fields(self):
930         count = 0
931         for f in self.fields:
932             if isinstance(f, OneOf):
933                 count += len(f.fields)
934             else:
935                 count += 1
936         return count
937
938     def fields_declaration(self):
939         result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1)
940         return result
941
942     def fields_definition(self):
943         result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1)
944
945         prev = None
946         for field in self.ordered_fields:
947             result += field.pb_field_t(prev)
948             result += ',\n'
949             prev = field.get_last_field_name()
950
951         result += '    PB_LAST_FIELD\n};'
952         return result
953
954     def encoded_size(self, dependencies):
955         '''Return the maximum size that this message can take when encoded.
956         If the size cannot be determined, returns None.
957         '''
958         size = EncodedSize(0)
959         for field in self.fields:
960             fsize = field.encoded_size(dependencies)
961             if fsize is None:
962                 return None
963             size += fsize
964
965         return size
966
967
968 # ---------------------------------------------------------------------------
969 #                    Processing of entire .proto files
970 # ---------------------------------------------------------------------------
971
972 def iterate_messages(desc, names = Names()):
973     '''Recursively find all messages. For each, yield name, DescriptorProto.'''
974     if hasattr(desc, 'message_type'):
975         submsgs = desc.message_type
976     else:
977         submsgs = desc.nested_type
978
979     for submsg in submsgs:
980         sub_names = names + submsg.name
981         yield sub_names, submsg
982
983         for x in iterate_messages(submsg, sub_names):
984             yield x
985
986 def iterate_extensions(desc, names = Names()):
987     '''Recursively find all extensions.
988     For each, yield name, FieldDescriptorProto.
989     '''
990     for extension in desc.extension:
991         yield names, extension
992
993     for subname, subdesc in iterate_messages(desc, names):
994         for extension in subdesc.extension:
995             yield subname, extension
996
997 def toposort2(data):
998     '''Topological sort.
999     From http://code.activestate.com/recipes/577413-topological-sort/
1000     This function is under the MIT license.
1001     '''
1002     for k, v in list(data.items()):
1003         v.discard(k) # Ignore self dependencies
1004     extra_items_in_deps = reduce(set.union, list(data.values()), set()) - set(data.keys())
1005     data.update(dict([(item, set()) for item in extra_items_in_deps]))
1006     while True:
1007         ordered = set(item for item,dep in list(data.items()) if not dep)
1008         if not ordered:
1009             break
1010         for item in sorted(ordered):
1011             yield item
1012         data = dict([(item, (dep - ordered)) for item,dep in list(data.items())
1013                 if item not in ordered])
1014     assert not data, "A cyclic dependency exists amongst %r" % data
1015
1016 def sort_dependencies(messages):
1017     '''Sort a list of Messages based on dependencies.'''
1018     dependencies = {}
1019     message_by_name = {}
1020     for message in messages:
1021         dependencies[str(message.name)] = set(message.get_dependencies())
1022         message_by_name[str(message.name)] = message
1023
1024     for msgname in toposort2(dependencies):
1025         if msgname in message_by_name:
1026             yield message_by_name[msgname]
1027
1028 def make_identifier(headername):
1029     '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
1030     result = ""
1031     for c in headername.upper():
1032         if c.isalnum():
1033             result += c
1034         else:
1035             result += '_'
1036     return result
1037
1038 class ProtoFile:
1039     def __init__(self, fdesc, file_options):
1040         '''Takes a FileDescriptorProto and parses it.'''
1041         self.fdesc = fdesc
1042         self.file_options = file_options
1043         self.dependencies = {}
1044         self.parse()
1045
1046         # Some of types used in this file probably come from the file itself.
1047         # Thus it has implicit dependency on itself.
1048         self.add_dependency(self)
1049
1050     def parse(self):
1051         self.enums = []
1052         self.messages = []
1053         self.extensions = []
1054
1055         if self.fdesc.package:
1056             base_name = Names(self.fdesc.package.split('.'))
1057         else:
1058             base_name = Names()
1059
1060         for enum in self.fdesc.enum_type:
1061             enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
1062             self.enums.append(Enum(base_name, enum, enum_options))
1063
1064         for names, message in iterate_messages(self.fdesc, base_name):
1065             message_options = get_nanopb_suboptions(message, self.file_options, names)
1066
1067             if message_options.skip_message:
1068                 continue
1069
1070             self.messages.append(Message(names, message, message_options))
1071             for enum in message.enum_type:
1072                 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
1073                 self.enums.append(Enum(names, enum, enum_options))
1074
1075         for names, extension in iterate_extensions(self.fdesc, base_name):
1076             field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
1077             if field_options.type != nanopb_pb2.FT_IGNORE:
1078                 self.extensions.append(ExtensionField(names, extension, field_options))
1079
1080     def add_dependency(self, other):
1081         for enum in other.enums:
1082             self.dependencies[str(enum.names)] = enum
1083
1084         for msg in other.messages:
1085             self.dependencies[str(msg.name)] = msg
1086
1087         # Fix field default values where enum short names are used.
1088         for enum in other.enums:
1089             if not enum.options.long_names:
1090                 for message in self.messages:
1091                     for field in message.fields:
1092                         if field.default in enum.value_longnames:
1093                             idx = enum.value_longnames.index(field.default)
1094                             field.default = enum.values[idx][0]
1095
1096         # Fix field data types where enums have negative values.
1097         for enum in other.enums:
1098             if not enum.has_negative():
1099                 for message in self.messages:
1100                     for field in message.fields:
1101                         if field.pbtype == 'ENUM' and field.ctype == enum.names:
1102                             field.pbtype = 'UENUM'
1103
1104     def generate_header(self, includes, headername, options):
1105         '''Generate content for a header file.
1106         Generates strings, which should be concatenated and stored to file.
1107         '''
1108
1109         yield '/* Automatically generated nanopb header */\n'
1110         if options.notimestamp:
1111             yield '/* Generated by %s */\n\n' % (nanopb_version)
1112         else:
1113             yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1114
1115         if self.fdesc.package:
1116             symbol = make_identifier(self.fdesc.package + '_' + headername)
1117         else:
1118             symbol = make_identifier(headername)
1119         yield '#ifndef PB_%s_INCLUDED\n' % symbol
1120         yield '#define PB_%s_INCLUDED\n' % symbol
1121         try:
1122             yield options.libformat % ('pb.h')
1123         except TypeError:
1124             # no %s specified - use whatever was passed in as options.libformat
1125             yield options.libformat
1126         yield '\n'
1127
1128         for incfile in includes:
1129             noext = os.path.splitext(incfile)[0]
1130             yield options.genformat % (noext + options.extension + '.h')
1131             yield '\n'
1132
1133         yield '/* @@protoc_insertion_point(includes) */\n'
1134
1135         yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1136         yield '#error Regenerate this file with the current version of nanopb generator.\n'
1137         yield '#endif\n'
1138         yield '\n'
1139
1140         yield '#ifdef __cplusplus\n'
1141         yield 'extern "C" {\n'
1142         yield '#endif\n\n'
1143
1144         if self.enums:
1145             yield '/* Enum definitions */\n'
1146             for enum in self.enums:
1147                 yield str(enum) + '\n\n'
1148
1149         if self.messages:
1150             yield '/* Struct definitions */\n'
1151             for msg in sort_dependencies(self.messages):
1152                 yield msg.types()
1153                 yield str(msg) + '\n\n'
1154
1155         if self.extensions:
1156             yield '/* Extensions */\n'
1157             for extension in self.extensions:
1158                 yield extension.extension_decl()
1159             yield '\n'
1160
1161         if self.messages:
1162             yield '/* Default values for struct fields */\n'
1163             for msg in self.messages:
1164                 yield msg.default_decl(True)
1165             yield '\n'
1166
1167             yield '/* Initializer values for message structs */\n'
1168             for msg in self.messages:
1169                 identifier = '%s_init_default' % msg.name
1170                 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
1171             for msg in self.messages:
1172                 identifier = '%s_init_zero' % msg.name
1173                 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
1174             yield '\n'
1175
1176             yield '/* Field tags (for use in manual encoding/decoding) */\n'
1177             for msg in sort_dependencies(self.messages):
1178                 for field in msg.fields:
1179                     yield field.tags()
1180             for extension in self.extensions:
1181                 yield extension.tags()
1182             yield '\n'
1183
1184             yield '/* Struct field encoding specification for nanopb */\n'
1185             for msg in self.messages:
1186                 yield msg.fields_declaration() + '\n'
1187             yield '\n'
1188
1189             yield '/* Maximum encoded size of messages (where known) */\n'
1190             for msg in self.messages:
1191                 msize = msg.encoded_size(self.dependencies)
1192                 identifier = '%s_size' % msg.name
1193                 if msize is not None:
1194                     yield '#define %-40s %s\n' % (identifier, msize)
1195                 else:
1196                     yield '/* %s depends on runtime parameters */\n' % identifier
1197             yield '\n'
1198
1199             yield '/* Message IDs (where set with "msgid" option) */\n'
1200
1201             yield '#ifdef PB_MSGID\n'
1202             for msg in self.messages:
1203                 if hasattr(msg,'msgid'):
1204                     yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name)
1205             yield '\n'
1206
1207             symbol = make_identifier(headername.split('.')[0])
1208             yield '#define %s_MESSAGES \\\n' % symbol
1209
1210             for msg in self.messages:
1211                 m = "-1"
1212                 msize = msg.encoded_size(self.dependencies)
1213                 if msize is not None:
1214                     m = msize
1215                 if hasattr(msg,'msgid'):
1216                     yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name)
1217             yield '\n'
1218
1219             for msg in self.messages:
1220                 if hasattr(msg,'msgid'):
1221                     yield '#define %s_msgid %d\n' % (msg.name, msg.msgid)
1222             yield '\n'
1223
1224             yield '#endif\n\n'
1225
1226         yield '#ifdef __cplusplus\n'
1227         yield '} /* extern "C" */\n'
1228         yield '#endif\n'
1229
1230         # End of header
1231         yield '/* @@protoc_insertion_point(eof) */\n'
1232         yield '\n#endif\n'
1233
1234     def generate_source(self, headername, options):
1235         '''Generate content for a source file.'''
1236
1237         yield '/* Automatically generated nanopb constant definitions */\n'
1238         if options.notimestamp:
1239             yield '/* Generated by %s */\n\n' % (nanopb_version)
1240         else:
1241             yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1242         yield options.genformat % (headername)
1243         yield '\n'
1244         yield '/* @@protoc_insertion_point(includes) */\n'
1245
1246         yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1247         yield '#error Regenerate this file with the current version of nanopb generator.\n'
1248         yield '#endif\n'
1249         yield '\n'
1250
1251         for msg in self.messages:
1252             yield msg.default_decl(False)
1253
1254         yield '\n\n'
1255
1256         for msg in self.messages:
1257             yield msg.fields_definition() + '\n\n'
1258
1259         for ext in self.extensions:
1260             yield ext.extension_def() + '\n'
1261
1262         for enum in self.enums:
1263             yield enum.enum_to_string_definition() + '\n'
1264
1265         # Add checks for numeric limits
1266         if self.messages:
1267             largest_msg = max(self.messages, key = lambda m: m.count_required_fields())
1268             largest_count = largest_msg.count_required_fields()
1269             if largest_count > 64:
1270                 yield '\n/* Check that missing required fields will be properly detected */\n'
1271                 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
1272                 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
1273                 yield '       setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
1274                 yield '#endif\n'
1275
1276         max_field = FieldMaxSize()
1277         checks_msgnames = []
1278         for msg in self.messages:
1279             checks_msgnames.append(msg.name)
1280             for field in msg.fields:
1281                 max_field.extend(field.largest_field_value())
1282
1283         worst = max_field.worst
1284         worst_field = max_field.worst_field
1285         checks = max_field.checks
1286
1287         if worst > 255 or checks:
1288             yield '\n/* Check that field information fits in pb_field_t */\n'
1289
1290             if worst > 65535 or checks:
1291                 yield '#if !defined(PB_FIELD_32BIT)\n'
1292                 if worst > 65535:
1293                     yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
1294                 else:
1295                     assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
1296                     msgs = '_'.join(str(n) for n in checks_msgnames)
1297                     yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
1298                     yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1299                     yield ' * \n'
1300                     yield ' * The reason you need to do this is that some of your messages contain tag\n'
1301                     yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
1302                     yield ' * field descriptors.\n'
1303                     yield ' */\n'
1304                     yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1305                 yield '#endif\n\n'
1306
1307             if worst < 65536:
1308                 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
1309                 if worst > 255:
1310                     yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
1311                 else:
1312                     assertion = ' && '.join(str(c) + ' < 256' for c in checks)
1313                     msgs = '_'.join(str(n) for n in checks_msgnames)
1314                     yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
1315                     yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1316                     yield ' * \n'
1317                     yield ' * The reason you need to do this is that some of your messages contain tag\n'
1318                     yield ' * numbers or field sizes that are larger than what can fit in the default\n'
1319                     yield ' * 8 bit descriptors.\n'
1320                     yield ' */\n'
1321                     yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1322                 yield '#endif\n\n'
1323
1324         # Add check for sizeof(double)
1325         has_double = False
1326         for msg in self.messages:
1327             for field in msg.fields:
1328                 if field.ctype == 'double':
1329                     has_double = True
1330
1331         if has_double:
1332             yield '\n'
1333             yield '/* On some platforms (such as AVR), double is really float.\n'
1334             yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
1335             yield ' * To get rid of this error, remove any double fields from your .proto.\n'
1336             yield ' */\n'
1337             yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
1338
1339         yield '\n'
1340         yield '/* @@protoc_insertion_point(eof) */\n'
1341
1342 # ---------------------------------------------------------------------------
1343 #                    Options parsing for the .proto files
1344 # ---------------------------------------------------------------------------
1345
1346 from fnmatch import fnmatch
1347
1348 def read_options_file(infile):
1349     '''Parse a separate options file to list:
1350         [(namemask, options), ...]
1351     '''
1352     results = []
1353     data = infile.read()
1354     data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE)
1355     data = re.sub('//.*?$', '', data, flags = re.MULTILINE)
1356     data = re.sub('#.*?$', '', data, flags = re.MULTILINE)
1357     for i, line in enumerate(data.split('\n')):
1358         line = line.strip()
1359         if not line:
1360             continue
1361
1362         parts = line.split(None, 1)
1363
1364         if len(parts) < 2:
1365             sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1366                              "Option lines should have space between field name and options. " +
1367                              "Skipping line: '%s'\n" % line)
1368             continue
1369
1370         opts = nanopb_pb2.NanoPBOptions()
1371
1372         try:
1373             text_format.Merge(parts[1], opts)
1374         except Exception as e:
1375             sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1376                              "Unparseable option line: '%s'. " % line +
1377                              "Error: %s\n" % str(e))
1378             continue
1379         results.append((parts[0], opts))
1380
1381     return results
1382
1383 class Globals:
1384     '''Ugly global variables, should find a good way to pass these.'''
1385     verbose_options = False
1386     separate_options = []
1387     matched_namemasks = set()
1388
1389 def get_nanopb_suboptions(subdesc, options, name):
1390     '''Get copy of options, and merge information from subdesc.'''
1391     new_options = nanopb_pb2.NanoPBOptions()
1392     new_options.CopyFrom(options)
1393
1394     if hasattr(subdesc, 'syntax') and subdesc.syntax == "proto3":
1395         new_options.proto3 = True
1396
1397     # Handle options defined in a separate file
1398     dotname = '.'.join(name.parts)
1399     for namemask, options in Globals.separate_options:
1400         if fnmatch(dotname, namemask):
1401             Globals.matched_namemasks.add(namemask)
1402             new_options.MergeFrom(options)
1403
1404     # Handle options defined in .proto
1405     if isinstance(subdesc.options, descriptor.FieldOptions):
1406         ext_type = nanopb_pb2.nanopb
1407     elif isinstance(subdesc.options, descriptor.FileOptions):
1408         ext_type = nanopb_pb2.nanopb_fileopt
1409     elif isinstance(subdesc.options, descriptor.MessageOptions):
1410         ext_type = nanopb_pb2.nanopb_msgopt
1411     elif isinstance(subdesc.options, descriptor.EnumOptions):
1412         ext_type = nanopb_pb2.nanopb_enumopt
1413     else:
1414         raise Exception("Unknown options type")
1415
1416     if subdesc.options.HasExtension(ext_type):
1417         ext = subdesc.options.Extensions[ext_type]
1418         new_options.MergeFrom(ext)
1419
1420     if Globals.verbose_options:
1421         sys.stderr.write("Options for " + dotname + ": ")
1422         sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1423
1424     return new_options
1425
1426
1427 # ---------------------------------------------------------------------------
1428 #                         Command line interface
1429 # ---------------------------------------------------------------------------
1430
1431 import sys
1432 import os.path
1433 from optparse import OptionParser
1434
1435 optparser = OptionParser(
1436     usage = "Usage: nanopb_generator.py [options] file.pb ...",
1437     epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1438              "Output will be written to file.pb.h and file.pb.c.")
1439 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1440     help="Exclude file from generated #include list.")
1441 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1442     help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1443 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1444     help="Set name of a separate generator options file.")
1445 optparser.add_option("-I", "--options-path", dest="options_path", metavar="DIR",
1446     action="append", default = [],
1447     help="Search for .options files additionally in this path")
1448 optparser.add_option("-D", "--output-dir", dest="output_dir",
1449                      metavar="OUTPUTDIR", default=None,
1450                      help="Output directory of .pb.h and .pb.c files")
1451 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1452     metavar="FORMAT", default='#include "%s"\n',
1453     help="Set format string to use for including other .pb.h files. [default: %default]")
1454 optparser.add_option("-L", "--library-include-format", dest="libformat",
1455     metavar="FORMAT", default='#include <%s>\n',
1456     help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1457 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1458     help="Don't add timestamp to .pb.h and .pb.c preambles")
1459 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1460     help="Don't print anything except errors.")
1461 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1462     help="Print more information.")
1463 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1464     help="Set generator option (max_size, max_count etc.).")
1465
1466 def parse_file(filename, fdesc, options):
1467     '''Parse a single file. Returns a ProtoFile instance.'''
1468     toplevel_options = nanopb_pb2.NanoPBOptions()
1469     for s in options.settings:
1470         text_format.Merge(s, toplevel_options)
1471
1472     if not fdesc:
1473         data = open(filename, 'rb').read()
1474         fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1475
1476     # Check if there is a separate .options file
1477     had_abspath = False
1478     try:
1479         optfilename = options.options_file % os.path.splitext(filename)[0]
1480     except TypeError:
1481         # No %s specified, use the filename as-is
1482         optfilename = options.options_file
1483         had_abspath = True
1484
1485     paths = ['.'] + options.options_path
1486     for p in paths:
1487         if os.path.isfile(os.path.join(p, optfilename)):
1488             optfilename = os.path.join(p, optfilename)
1489             if options.verbose:
1490                 sys.stderr.write('Reading options from ' + optfilename + '\n')
1491             Globals.separate_options = read_options_file(open(optfilename, "rU"))
1492             break
1493     else:
1494         # If we are given a full filename and it does not exist, give an error.
1495         # However, don't give error when we automatically look for .options file
1496         # with the same name as .proto.
1497         if options.verbose or had_abspath:
1498             sys.stderr.write('Options file not found: ' + optfilename + '\n')
1499         Globals.separate_options = []
1500
1501     Globals.matched_namemasks = set()
1502
1503     # Parse the file
1504     file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1505     f = ProtoFile(fdesc, file_options)
1506     f.optfilename = optfilename
1507
1508     return f
1509
1510 def process_file(filename, fdesc, options, other_files = {}):
1511     '''Process a single file.
1512     filename: The full path to the .proto or .pb source file, as string.
1513     fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1514     options: Command line options as they come from OptionsParser.
1515
1516     Returns a dict:
1517         {'headername': Name of header file,
1518          'headerdata': Data for the .h header file,
1519          'sourcename': Name of the source code file,
1520          'sourcedata': Data for the .c source code file
1521         }
1522     '''
1523     f = parse_file(filename, fdesc, options)
1524
1525     # Provide dependencies if available
1526     for dep in f.fdesc.dependency:
1527         if dep in other_files:
1528             f.add_dependency(other_files[dep])
1529
1530     # Decide the file names
1531     noext = os.path.splitext(filename)[0]
1532     headername = noext + options.extension + '.h'
1533     sourcename = noext + options.extension + '.c'
1534     headerbasename = os.path.basename(headername)
1535
1536     # List of .proto files that should not be included in the C header file
1537     # even if they are mentioned in the source .proto.
1538     excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1539     includes = [d for d in f.fdesc.dependency if d not in excludes]
1540
1541     headerdata = ''.join(f.generate_header(includes, headerbasename, options))
1542     sourcedata = ''.join(f.generate_source(headerbasename, options))
1543
1544     # Check if there were any lines in .options that did not match a member
1545     unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1546     if unmatched and not options.quiet:
1547         sys.stderr.write("Following patterns in " + f.optfilename + " did not match any fields: "
1548                          + ', '.join(unmatched) + "\n")
1549         if not Globals.verbose_options:
1550             sys.stderr.write("Use  protoc --nanopb-out=-v:.   to see a list of the field names.\n")
1551
1552     return {'headername': headername, 'headerdata': headerdata,
1553             'sourcename': sourcename, 'sourcedata': sourcedata}
1554
1555 def main_cli():
1556     '''Main function when invoked directly from the command line.'''
1557
1558     options, filenames = optparser.parse_args()
1559
1560     if not filenames:
1561         optparser.print_help()
1562         sys.exit(1)
1563
1564     if options.quiet:
1565         options.verbose = False
1566
1567     if options.output_dir and not os.path.exists(options.output_dir):
1568         optparser.print_help()
1569         sys.stderr.write("\noutput_dir does not exist: %s\n" % options.output_dir)
1570         sys.exit(1)
1571
1572
1573     Globals.verbose_options = options.verbose
1574     for filename in filenames:
1575         results = process_file(filename, None, options)
1576
1577         base_dir = options.output_dir or ''
1578         to_write = [
1579             (os.path.join(base_dir, results['headername']), results['headerdata']),
1580             (os.path.join(base_dir, results['sourcename']), results['sourcedata']),
1581         ]
1582
1583         if not options.quiet:
1584             paths = " and ".join([x[0] for x in to_write])
1585             sys.stderr.write("Writing to %s\n" % paths)
1586
1587         for path, data in to_write:
1588             with open(path, 'w') as f:
1589                 f.write(data)
1590
1591 def main_plugin():
1592     '''Main function when invoked as a protoc plugin.'''
1593
1594     import io, sys
1595     if sys.platform == "win32":
1596         import os, msvcrt
1597         # Set stdin and stdout to binary mode
1598         msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1599         msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1600
1601     data = io.open(sys.stdin.fileno(), "rb").read()
1602
1603     request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1604
1605     try:
1606         # Versions of Python prior to 2.7.3 do not support unicode
1607         # input to shlex.split(). Try to convert to str if possible.
1608         params = str(request.parameter)
1609     except UnicodeEncodeError:
1610         params = request.parameter
1611
1612     import shlex
1613     args = shlex.split(params)
1614     options, dummy = optparser.parse_args(args)
1615
1616     Globals.verbose_options = options.verbose
1617
1618     response = plugin_pb2.CodeGeneratorResponse()
1619
1620     # Google's protoc does not currently indicate the full path of proto files.
1621     # Instead always add the main file path to the search dirs, that works for
1622     # the common case.
1623     import os.path
1624     options.options_path.append(os.path.dirname(request.file_to_generate[0]))
1625
1626     # Process any include files first, in order to have them
1627     # available as dependencies
1628     other_files = {}
1629     for fdesc in request.proto_file:
1630         other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options)
1631
1632     for filename in request.file_to_generate:
1633         for fdesc in request.proto_file:
1634             if fdesc.name == filename:
1635                 results = process_file(filename, fdesc, options, other_files)
1636
1637                 f = response.file.add()
1638                 f.name = results['headername']
1639                 f.content = results['headerdata']
1640
1641                 f = response.file.add()
1642                 f.name = results['sourcename']
1643                 f.content = results['sourcedata']
1644
1645     io.open(sys.stdout.fileno(), "wb").write(response.SerializeToString())
1646
1647 if __name__ == '__main__':
1648     # Check if we are running as a plugin under protoc
1649     if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv:
1650         main_plugin()
1651     else:
1652         main_cli()