Add support for packed structures on IAR and MSVC.
[apps/agl-service-can-low-level.git] / generator / nanopb_generator.py
1 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
2 nanopb_version = "nanopb-0.2.1-dev"
3
4 try:
5     import google.protobuf.descriptor_pb2 as descriptor
6     import google.protobuf.text_format as text_format
7 except:
8     print
9     print "*************************************************************"
10     print "*** Could not import the Google protobuf Python libraries ***"
11     print "*** Try installing package 'python-protobuf' or similar.  ***"
12     print "*************************************************************"
13     print
14     raise
15
16 try:
17     import nanopb_pb2
18 except:
19     print
20     print "***************************************************************"
21     print "*** Could not import the precompiled nanopb_pb2.py.         ***"
22     print "*** Run 'make' in the 'generator' folder to update the file.***"
23     print "***************************************************************"
24     print
25     raise
26
27
28
29
30
31
32 # ---------------------------------------------------------------------------
33 #                     Generation of single fields
34 # ---------------------------------------------------------------------------
35
36 import time
37 import os.path
38
39 # Values are tuple (c type, pb type)
40 FieldD = descriptor.FieldDescriptorProto
41 datatypes = {
42     FieldD.TYPE_BOOL:       ('bool',     'BOOL'),
43     FieldD.TYPE_DOUBLE:     ('double',   'DOUBLE'),
44     FieldD.TYPE_FIXED32:    ('uint32_t', 'FIXED32'),
45     FieldD.TYPE_FIXED64:    ('uint64_t', 'FIXED64'),
46     FieldD.TYPE_FLOAT:      ('float',    'FLOAT'),
47     FieldD.TYPE_INT32:      ('int32_t',  'INT32'),
48     FieldD.TYPE_INT64:      ('int64_t',  'INT64'),
49     FieldD.TYPE_SFIXED32:   ('int32_t',  'SFIXED32'),
50     FieldD.TYPE_SFIXED64:   ('int64_t',  'SFIXED64'),
51     FieldD.TYPE_SINT32:     ('int32_t',  'SINT32'),
52     FieldD.TYPE_SINT64:     ('int64_t',  'SINT64'),
53     FieldD.TYPE_UINT32:     ('uint32_t', 'UINT32'),
54     FieldD.TYPE_UINT64:     ('uint64_t', 'UINT64')
55 }
56
57 class Names:
58     '''Keeps a set of nested names and formats them to C identifier.'''
59     def __init__(self, parts = ()):
60         if isinstance(parts, Names):
61             parts = parts.parts
62         self.parts = tuple(parts)
63     
64     def __str__(self):
65         return '_'.join(self.parts)
66
67     def __add__(self, other):
68         if isinstance(other, (str, unicode)):
69             return Names(self.parts + (other,))
70         elif isinstance(other, tuple):
71             return Names(self.parts + other)
72         else:
73             raise ValueError("Name parts should be of type str")
74     
75     def __eq__(self, other):
76         return isinstance(other, Names) and self.parts == other.parts
77     
78 def names_from_type_name(type_name):
79     '''Parse Names() from FieldDescriptorProto type_name'''
80     if type_name[0] != '.':
81         raise NotImplementedError("Lookup of non-absolute type names is not supported")
82     return Names(type_name[1:].split('.'))
83
84 class Enum:
85     def __init__(self, names, desc, enum_options):
86         '''desc is EnumDescriptorProto'''
87         
88         self.options = enum_options
89         self.names = names + desc.name
90         
91         if enum_options.long_names:
92             self.values = [(self.names + x.name, x.number) for x in desc.value]            
93         else:
94             self.values = [(names + x.name, x.number) for x in desc.value] 
95         
96         self.value_longnames = [self.names + x.name for x in desc.value]
97     
98     def __str__(self):
99         result = 'typedef enum _%s {\n' % self.names
100         result += ',\n'.join(["    %s = %d" % x for x in self.values])
101         result += '\n} %s;' % self.names
102         return result
103
104 class Field:
105     def __init__(self, struct_name, desc, field_options):
106         '''desc is FieldDescriptorProto'''
107         self.tag = desc.number
108         self.struct_name = struct_name
109         self.name = desc.name
110         self.default = None
111         self.max_size = None
112         self.max_count = None
113         self.array_decl = ""
114         
115         # Parse field options
116         if field_options.HasField("max_size"):
117             self.max_size = field_options.max_size
118         
119         if field_options.HasField("max_count"):
120             self.max_count = field_options.max_count
121         
122         if desc.HasField('default_value'):
123             self.default = desc.default_value
124            
125         # Check field rules, i.e. required/optional/repeated.
126         can_be_static = True
127         if desc.label == FieldD.LABEL_REQUIRED:
128             self.rules = 'REQUIRED'
129         elif desc.label == FieldD.LABEL_OPTIONAL:
130             self.rules = 'OPTIONAL'
131         elif desc.label == FieldD.LABEL_REPEATED:
132             self.rules = 'REPEATED'
133             if self.max_count is None:
134                 can_be_static = False
135             else:
136                 self.array_decl = '[%d]' % self.max_count
137         else:
138             raise NotImplementedError(desc.label)
139         
140         # Decide the C data type to use in the struct.
141         if datatypes.has_key(desc.type):
142             self.ctype, self.pbtype = datatypes[desc.type]
143         elif desc.type == FieldD.TYPE_ENUM:
144             self.pbtype = 'ENUM'
145             self.ctype = names_from_type_name(desc.type_name)
146             if self.default is not None:
147                 self.default = self.ctype + self.default
148         elif desc.type == FieldD.TYPE_STRING:
149             self.pbtype = 'STRING'
150             if self.max_size is None:
151                 can_be_static = False
152             else:
153                 self.ctype = 'char'
154                 self.array_decl += '[%d]' % self.max_size
155         elif desc.type == FieldD.TYPE_BYTES:
156             self.pbtype = 'BYTES'
157             if self.max_size is None:
158                 can_be_static = False
159             else:
160                 self.ctype = self.struct_name + self.name + 't'
161         elif desc.type == FieldD.TYPE_MESSAGE:
162             self.pbtype = 'MESSAGE'
163             self.ctype = self.submsgname = names_from_type_name(desc.type_name)
164         else:
165             raise NotImplementedError(desc.type)
166         
167         if field_options.type == nanopb_pb2.FT_DEFAULT:
168             if can_be_static:
169                 field_options.type = nanopb_pb2.FT_STATIC
170             else:
171                 field_options.type = nanopb_pb2.FT_CALLBACK
172         
173         if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
174             raise Exception("Field %s is defined as static, but max_size or max_count is not given." % self.name)
175         
176         if field_options.type == nanopb_pb2.FT_STATIC:
177             self.allocation = 'STATIC'
178         elif field_options.type == nanopb_pb2.FT_CALLBACK:
179             self.allocation = 'CALLBACK'
180             self.ctype = 'pb_callback_t'
181             self.array_decl = ''
182         else:
183             raise NotImplementedError(field_options.type)
184     
185     def __cmp__(self, other):
186         return cmp(self.tag, other.tag)
187     
188     def __str__(self):
189         if self.rules == 'OPTIONAL':
190             result = '    bool has_' + self.name + ';\n'
191         elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
192             result = '    size_t ' + self.name + '_count;\n'
193         else:
194             result = ''
195         result += '    %s %s%s;' % (self.ctype, self.name, self.array_decl)
196         return result
197     
198     def types(self):
199         '''Return definitions for any special types this field might need.'''
200         if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
201             result = 'typedef struct {\n'
202             result += '    size_t size;\n'
203             result += '    uint8_t bytes[%d];\n' % self.max_size
204             result += '} %s;\n' % self.ctype
205         else:
206             result = None
207         return result
208     
209     def default_decl(self, declaration_only = False):
210         '''Return definition for this field's default value.'''
211         if self.default is None:
212             return None
213
214         ctype, default = self.ctype, self.default
215         array_decl = ''
216         
217         if self.pbtype == 'STRING':
218             if self.allocation != 'STATIC':
219                 return None # Not implemented
220         
221             array_decl = '[%d]' % self.max_size
222             default = str(self.default).encode('string_escape')
223             default = default.replace('"', '\\"')
224             default = '"' + default + '"'
225         elif self.pbtype == 'BYTES':
226             if self.allocation != 'STATIC':
227                 return None # Not implemented
228
229             data = self.default.decode('string_escape')
230             data = ['0x%02x' % ord(c) for c in data]
231             default = '{%d, {%s}}' % (len(data), ','.join(data))
232         
233         if declaration_only:
234             return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
235         else:
236             return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
237     
238     def pb_field_t(self, prev_field_name):
239         '''Return the pb_field_t initializer to use in the constant array.
240         prev_field_name is the name of the previous field or None.
241         '''
242         result  = '    PB_FIELD(%3d, ' % self.tag
243         result += '%-8s, ' % self.pbtype
244         result += '%s, ' % self.rules
245         result += '%s, ' % self.allocation
246         result += '%s, ' % self.struct_name
247         result += '%s, ' % self.name
248         result += '%s, ' % (prev_field_name or self.name)
249         
250         if self.pbtype == 'MESSAGE':
251             result += '&%s_fields)' % self.submsgname
252         elif self.default is None:
253             result += '0)'
254         elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
255             result += '0)' # Arbitrary size default values not implemented
256         else:
257             result += '&%s_default)' % (self.struct_name + self.name)
258         
259         return result
260     
261     def largest_field_value(self):
262         '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
263         Returns numeric value or a C-expression for assert.'''
264         if self.pbtype == 'MESSAGE':
265             if self.rules == 'REPEATED' and self.allocation == 'STATIC':
266                 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
267             else:
268                 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
269
270         return max(self.tag, self.max_size, self.max_count)        
271
272
273
274
275
276
277 # ---------------------------------------------------------------------------
278 #                   Generation of messages (structures)
279 # ---------------------------------------------------------------------------
280
281
282 class Message:
283     def __init__(self, names, desc, message_options):
284         self.name = names
285         self.fields = []
286         
287         for f in desc.field:
288             field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
289             if field_options.type != nanopb_pb2.FT_IGNORE:
290                 self.fields.append(Field(self.name, f, field_options))
291         
292         self.packed = message_options.packed_struct
293         self.ordered_fields = self.fields[:]
294         self.ordered_fields.sort()
295
296     def get_dependencies(self):
297         '''Get list of type names that this structure refers to.'''
298         return [str(field.ctype) for field in self.fields]
299     
300     def __str__(self):
301         result = 'typedef struct _%s {\n' % self.name
302
303         if not self.ordered_fields:
304             # Empty structs are not allowed in C standard.
305             # Therefore add a dummy field if an empty message occurs.
306             result += '    uint8_t dummy_field;'
307
308         result += '\n'.join([str(f) for f in self.ordered_fields])
309         result += '\n}'
310         
311         if self.packed:
312             result += ' pb_packed'
313         
314         result += ' %s;' % self.name
315         
316         if self.packed:
317             result = 'PB_PACKED_STRUCT_START\n' + result
318             result += '\nPB_PACKED_STRUCT_END'
319         
320         return result
321     
322     def types(self):
323         result = ""
324         for field in self.fields:
325             types = field.types()
326             if types is not None:
327                 result += types + '\n'
328         return result
329     
330     def default_decl(self, declaration_only = False):
331         result = ""
332         for field in self.fields:
333             default = field.default_decl(declaration_only)
334             if default is not None:
335                 result += default + '\n'
336         return result
337
338     def fields_declaration(self):
339         result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
340         return result
341
342     def fields_definition(self):
343         result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
344         
345         prev = None
346         for field in self.ordered_fields:
347             result += field.pb_field_t(prev)
348             result += ',\n'
349             prev = field.name
350         
351         result += '    PB_LAST_FIELD\n};'
352         return result
353
354
355
356
357
358
359 # ---------------------------------------------------------------------------
360 #                    Processing of entire .proto files
361 # ---------------------------------------------------------------------------
362
363
364 def iterate_messages(desc, names = Names()):
365     '''Recursively find all messages. For each, yield name, DescriptorProto.'''
366     if hasattr(desc, 'message_type'):
367         submsgs = desc.message_type
368     else:
369         submsgs = desc.nested_type
370     
371     for submsg in submsgs:
372         sub_names = names + submsg.name
373         yield sub_names, submsg
374         
375         for x in iterate_messages(submsg, sub_names):
376             yield x
377
378 def parse_file(fdesc, file_options):
379     '''Takes a FileDescriptorProto and returns tuple (enum, messages).'''
380     
381     enums = []
382     messages = []
383     
384     if fdesc.package:
385         base_name = Names(fdesc.package.split('.'))
386     else:
387         base_name = Names()
388     
389     for enum in fdesc.enum_type:
390         enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
391         enums.append(Enum(base_name, enum, enum_options))
392     
393     for names, message in iterate_messages(fdesc, base_name):
394         message_options = get_nanopb_suboptions(message, file_options, names)
395         messages.append(Message(names, message, message_options))
396         for enum in message.enum_type:
397             enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
398             enums.append(Enum(names, enum, enum_options))
399     
400     # Fix field default values where enum short names are used.
401     for enum in enums:
402         if not enum.options.long_names:
403             for message in messages:
404                 for field in message.fields:
405                     if field.default in enum.value_longnames:
406                         idx = enum.value_longnames.index(field.default)
407                         field.default = enum.values[idx][0]
408     
409     return enums, messages
410
411 def toposort2(data):
412     '''Topological sort.
413     From http://code.activestate.com/recipes/577413-topological-sort/
414     This function is under the MIT license.
415     '''
416     for k, v in data.items():
417         v.discard(k) # Ignore self dependencies
418     extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
419     data.update(dict([(item, set()) for item in extra_items_in_deps]))
420     while True:
421         ordered = set(item for item,dep in data.items() if not dep)
422         if not ordered:
423             break
424         for item in sorted(ordered):
425             yield item
426         data = dict([(item, (dep - ordered)) for item,dep in data.items()
427                 if item not in ordered])
428     assert not data, "A cyclic dependency exists amongst %r" % data
429
430 def sort_dependencies(messages):
431     '''Sort a list of Messages based on dependencies.'''
432     dependencies = {}
433     message_by_name = {}
434     for message in messages:
435         dependencies[str(message.name)] = set(message.get_dependencies())
436         message_by_name[str(message.name)] = message
437     
438     for msgname in toposort2(dependencies):
439         if msgname in message_by_name:
440             yield message_by_name[msgname]
441
442 def make_identifier(headername):
443     '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
444     result = ""
445     for c in headername.upper():
446         if c.isalnum():
447             result += c
448         else:
449             result += '_'
450     return result
451
452 def generate_header(dependencies, headername, enums, messages, options):
453     '''Generate content for a header file.
454     Generates strings, which should be concatenated and stored to file.
455     '''
456     
457     yield '/* Automatically generated nanopb header */\n'
458     yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
459     
460     symbol = make_identifier(headername)
461     yield '#ifndef _PB_%s_\n' % symbol
462     yield '#define _PB_%s_\n' % symbol
463     try:
464         yield options.libformat % ('pb.h')
465     except TypeError:
466         # no %s specified - use whatever was passed in as options.libformat
467         yield options.libformat
468     yield '\n'
469     
470     for dependency in dependencies:
471         noext = os.path.splitext(dependency)[0]
472         yield options.genformat % (noext + '.' + options.extension + '.h')
473         yield '\n'
474
475     yield '#ifdef __cplusplus\n'
476     yield 'extern "C" {\n'
477     yield '#endif\n\n'
478     
479     yield '/* Enum definitions */\n'
480     for enum in enums:
481         yield str(enum) + '\n\n'
482     
483     yield '/* Struct definitions */\n'
484     for msg in sort_dependencies(messages):
485         yield msg.types()
486         yield str(msg) + '\n\n'
487         
488     yield '/* Default values for struct fields */\n'
489     for msg in messages:
490         yield msg.default_decl(True)
491     yield '\n'
492     
493     yield '/* Struct field encoding specification for nanopb */\n'
494     for msg in messages:
495         yield msg.fields_declaration() + '\n'
496     
497     yield '\n#ifdef __cplusplus\n'
498     yield '} /* extern "C" */\n'
499     yield '#endif\n'
500     
501     # End of header
502     yield '\n#endif\n'
503
504 def generate_source(headername, enums, messages):
505     '''Generate content for a source file.'''
506     
507     yield '/* Automatically generated nanopb constant definitions */\n'
508     yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
509     yield options.genformat % (headername)
510     yield '\n'
511     
512     for msg in messages:
513         yield msg.default_decl(False)
514     
515     yield '\n\n'
516     
517     for msg in messages:
518         yield msg.fields_definition() + '\n\n'
519         
520     if messages:
521         count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
522         largest_msg = max(messages, key = count_required_fields)
523         largest_count = count_required_fields(largest_msg)
524         if largest_count > 64:
525             yield '\n/* Check that missing required fields will be properly detected */\n'
526             yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
527             yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
528             yield '       setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
529             yield '#endif\n'
530     
531     # Add checks for numeric limits
532     worst = 0
533     worst_field = ''
534     checks = []
535     checks_msgnames = []
536     for msg in messages:
537         checks_msgnames.append(msg.name)
538         for field in msg.fields:
539             status = field.largest_field_value()
540             if isinstance(status, (str, unicode)):
541                 checks.append(status)
542             elif status > worst:
543                 worst = status
544                 worst_field = str(field.struct_name) + '.' + str(field.name)
545
546     if worst > 255 or checks:
547         yield '\n/* Check that field information fits in pb_field_t */\n'
548         
549         if worst < 65536:
550             yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
551             if worst > 255:
552                 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
553             else:
554                 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
555                 msgs = '_'.join(str(n) for n in checks_msgnames)
556                 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
557             yield '#endif\n\n'
558         
559         if worst > 65535 or checks:
560             yield '#if !defined(PB_FIELD_32BIT)\n'
561             if worst > 65535:
562                 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
563             else:
564                 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
565                 msgs = '_'.join(str(n) for n in checks_msgnames)
566                 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
567             yield '#endif\n'
568     
569     # Add check for sizeof(double)
570     has_double = False
571     for msg in messages:
572         for field in msg.fields:
573             if field.ctype == 'double':
574                 has_double = True
575     
576     if has_double:
577         yield '\n'
578         yield '/* On some platforms (such as AVR), double is really float.\n'
579         yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
580         yield ' * To get rid of this error, remove any double fields from your .proto.\n'
581         yield ' */\n'
582         yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
583     
584     yield '\n'
585
586 # ---------------------------------------------------------------------------
587 #                    Options parsing for the .proto files
588 # ---------------------------------------------------------------------------
589
590 from fnmatch import fnmatch
591
592 def read_options_file(infile):
593     '''Parse a separate options file to list:
594         [(namemask, options), ...]
595     '''
596     results = []
597     for line in infile:
598         line = line.strip()
599         if not line or line.startswith('//') or line.startswith('#'):
600             continue
601         
602         parts = line.split(None, 1)
603         opts = nanopb_pb2.NanoPBOptions()
604         text_format.Merge(parts[1], opts)
605         results.append((parts[0], opts))
606
607     return results
608
609 class Globals:
610     '''Ugly global variables, should find a good way to pass these.'''
611     verbose_options = False
612     separate_options = []
613
614 def get_nanopb_suboptions(subdesc, options, name):
615     '''Get copy of options, and merge information from subdesc.'''
616     new_options = nanopb_pb2.NanoPBOptions()
617     new_options.CopyFrom(options)
618     
619     # Handle options defined in a separate file
620     dotname = '.'.join(name.parts)
621     for namemask, options in Globals.separate_options:
622         if fnmatch(dotname, namemask):
623             new_options.MergeFrom(options)
624     
625     # Handle options defined in .proto
626     if isinstance(subdesc.options, descriptor.FieldOptions):
627         ext_type = nanopb_pb2.nanopb
628     elif isinstance(subdesc.options, descriptor.FileOptions):
629         ext_type = nanopb_pb2.nanopb_fileopt
630     elif isinstance(subdesc.options, descriptor.MessageOptions):
631         ext_type = nanopb_pb2.nanopb_msgopt
632     elif isinstance(subdesc.options, descriptor.EnumOptions):
633         ext_type = nanopb_pb2.nanopb_enumopt
634     else:
635         raise Exception("Unknown options type")
636     
637     if subdesc.options.HasExtension(ext_type):
638         ext = subdesc.options.Extensions[ext_type]
639         new_options.MergeFrom(ext)
640     
641     if Globals.verbose_options:
642         print "Options for " + dotname + ":"
643         print text_format.MessageToString(new_options)
644     
645     return new_options
646
647
648 # ---------------------------------------------------------------------------
649 #                         Command line interface
650 # ---------------------------------------------------------------------------
651
652 import sys
653 import os.path    
654 from optparse import OptionParser
655
656 optparser = OptionParser(
657     usage = "Usage: nanopb_generator.py [options] file.pb ...",
658     epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
659              "Output will be written to file.pb.h and file.pb.c.")
660 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
661     help="Exclude file from generated #include list.")
662 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
663     help="Set extension to use instead of 'pb' for generated files. [default: %default]")
664 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
665     help="Set name of a separate generator options file.")
666 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
667     metavar="FORMAT", default='#include "%s"\n',
668     help="Set format string to use for including other .pb.h files. [default: %default]")
669 optparser.add_option("-L", "--library-include-format", dest="libformat",
670     metavar="FORMAT", default='#include <%s>\n',
671     help="Set format string to use for including the nanopb pb.h header. [default: %default]")
672 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
673     help="Don't print anything except errors.")
674 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
675     help="Print more information.")
676 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
677     help="Set generator option (max_size, max_count etc.).")
678
679 def process(filenames, options):
680     '''Process the files given on the command line.'''
681     
682     if not filenames:
683         optparser.print_help()
684         return False
685     
686     if options.quiet:
687         options.verbose = False
688
689     Globals.verbose_options = options.verbose
690     
691     toplevel_options = nanopb_pb2.NanoPBOptions()
692     for s in options.settings:
693         text_format.Merge(s, toplevel_options)
694     
695     for filename in filenames:
696         data = open(filename, 'rb').read()
697         fdesc = descriptor.FileDescriptorSet.FromString(data)
698         
699         # Check if any separate options are specified
700         try:
701             optfilename = options.options_file % os.path.splitext(filename)[0]
702         except TypeError:
703             # No %s specified, use the filename as-is
704             optfilename = options.options_file
705         
706         if options.verbose:
707             print 'Reading options from ' + optfilename
708         
709         if os.path.isfile(optfilename):
710             Globals.separate_options = read_options_file(open(optfilename, "rU"))
711         else:
712             Globals.separate_options = []
713         
714         # Parse the file
715         file_options = get_nanopb_suboptions(fdesc.file[0], toplevel_options, Names([filename]))
716         enums, messages = parse_file(fdesc.file[0], file_options)
717         
718         noext = os.path.splitext(filename)[0]
719         headername = noext + '.' + options.extension + '.h'
720         sourcename = noext + '.' + options.extension + '.c'
721         headerbasename = os.path.basename(headername)
722         
723         if not options.quiet:
724             print "Writing to " + headername + " and " + sourcename
725         
726         # List of .proto files that should not be included in the C header file
727         # even if they are mentioned in the source .proto.
728         excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
729         dependencies = [d for d in fdesc.file[0].dependency if d not in excludes]
730         
731         header = open(headername, 'w')
732         for part in generate_header(dependencies, headerbasename, enums, messages, options):
733             header.write(part)
734
735         source = open(sourcename, 'w')
736         for part in generate_source(headerbasename, enums, messages):
737             source.write(part)
738
739     return True
740
741 if __name__ == '__main__':
742     options, filenames = optparser.parse_args()
743     status = process(filenames, options)
744     
745     if not status:
746         sys.exit(1)
747