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