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