Cleanly separate IDL annotations from OVSDB schema information.
[cascardo/ovs.git] / ovsdb / ovsdb-idlc.in
1 #! @PYTHON@
2
3 import getopt
4 import os
5 import re
6 import sys
7
8 sys.path.insert(0, "@abs_top_srcdir@/ovsdb")
9 import simplejson as json
10
11 argv0 = sys.argv[0]
12
13 class Error(Exception):
14     def __init__(self, msg):
15         Exception.__init__(self)
16         self.msg = msg
17
18 def getMember(json, name, validTypes, description, default=None):
19     if name in json:
20         member = json[name]
21         if type(member) not in validTypes:
22             raise Error("%s: type mismatch for '%s' member"
23                         % (description, name))
24         return member
25     return default
26
27 def mustGetMember(json, name, expectedType, description):
28     member = getMember(json, name, expectedType, description)
29     if member == None:
30         raise Error("%s: missing '%s' member" % (description, name))
31     return member
32
33 class DbSchema:
34     def __init__(self, name, comment, tables, idlPrefix, idlHeader):
35         self.name = name
36         self.comment = comment
37         self.tables = tables
38         self.idlPrefix = idlPrefix
39         self.idlHeader = idlHeader
40
41     @staticmethod
42     def fromJson(json):
43         name = mustGetMember(json, 'name', [unicode], 'database')
44         comment = getMember(json, 'comment', [unicode], 'database')
45         tablesJson = mustGetMember(json, 'tables', [dict], 'database')
46         tables = {}
47         for tableName, tableJson in tablesJson.iteritems():
48             tables[tableName] = TableSchema.fromJson(tableJson,
49                                                      "%s table" % tableName)
50         idlPrefix = mustGetMember(json, 'idlPrefix', [unicode], 'database')
51         idlHeader = mustGetMember(json, 'idlHeader', [unicode], 'database')
52         return DbSchema(name, comment, tables, idlPrefix, idlHeader)
53
54     def toJson(self):
55         d = {"name": self.name,
56              "tables": {}}
57         for name, table in self.tables.iteritems():
58             d["tables"][name] = table.toJson()
59         if self.comment != None:
60             d["comment"] = self.comment
61         return d
62
63 class TableSchema:
64     def __init__(self, comment, columns):
65         self.comment = comment
66         self.columns = columns
67
68     @staticmethod
69     def fromJson(json, description):
70         comment = getMember(json, 'comment', [unicode], description)
71         columnsJson = mustGetMember(json, 'columns', [dict], description)
72         columns = {}
73         for name, json in columnsJson.iteritems():
74             columns[name] = ColumnSchema.fromJson(
75                 json, "column %s in %s" % (name, description))
76         return TableSchema(comment, columns)
77
78     def toJson(self):
79         d = {"columns": {}}
80         for name, column in self.columns.iteritems():
81             d["columns"][name] = column.toJson()
82         if self.comment != None:
83             d["comment"] = self.comment
84         return d
85
86 class ColumnSchema:
87     def __init__(self, comment, type, persistent):
88         self.comment = comment
89         self.type = type
90         self.persistent = persistent
91
92     @staticmethod
93     def fromJson(json, description):
94         comment = getMember(json, 'comment', [unicode], description)
95         type = Type.fromJson(mustGetMember(json, 'type', [dict, unicode],
96                                            description),
97                              'type of %s' % description)
98         ephemeral = getMember(json, 'ephemeral', [bool], description)
99         persistent = ephemeral != True
100         return ColumnSchema(comment, type, persistent)
101
102     def toJson(self):
103         d = {"type": self.type.toJson()}
104         if self.persistent == False:
105             d["ephemeral"] = True
106         if self.comment != None:
107             d["comment"] = self.comment
108         return d
109
110 class Type:
111     def __init__(self, key, keyRefTable=None, value=None, valueRefTable=None,
112                  min=1, max=1):
113         self.key = key
114         self.keyRefTable = keyRefTable
115         self.value = value
116         self.valueRefTable = valueRefTable
117         self.min = min
118         self.max = max
119     
120     @staticmethod
121     def fromJson(json, description):
122         if type(json) == unicode:
123             return Type(json)
124         else:
125             key = mustGetMember(json, 'key', [unicode], description)
126             keyRefTable = getMember(json, 'keyRefTable', [unicode], description)
127             value = getMember(json, 'value', [unicode], description)
128             valueRefTable = getMember(json, 'valueRefTable', [unicode], description)
129             min = getMember(json, 'min', [int], description, 1)
130             max = getMember(json, 'max', [int, unicode], description, 1)
131             return Type(key, keyRefTable, value, valueRefTable, min, max)
132
133     def toJson(self):
134         if self.value == None and self.min == 1 and self.max == 1:
135             return self.key
136         else:
137             d = {"key": self.key}
138             if self.value != None:
139                 d["value"] = self.value
140             if self.min != 1:
141                 d["min"] = self.min
142             if self.max != 1:
143                 d["max"] = self.max
144             return d
145
146     def isScalar(self):
147         return self.min == 1 and self.max == 1 and not self.value
148
149     def isOptional(self):
150         return self.min == 0 and self.max == 1
151
152     def toEnglish(self):
153         keyName = atomicTypeToEnglish(self.key, self.keyRefTable)
154         if self.value:
155             valueName = atomicTypeToEnglish(self.value, self.valueRefTable)
156
157         if self.isScalar():
158             return atomicTypeToEnglish(self.key, self.keyRefTable)
159         elif self.isOptional():
160             if self.value:
161                 return "optional %s-%s pair" % (keyName, valueName)
162             else:
163                 return "optional %s" % keyName
164         else:
165             if self.max == "unlimited":
166                 if self.min:
167                     quantity = "%d or more " % self.min
168                 else:
169                     quantity = ""
170             elif self.min:
171                 quantity = "%d to %d " % (self.min, self.max)
172             else:
173                 quantity = "up to %d " % self.max
174
175             if self.value:
176                 return "map of %s%s-%s pairs" % (quantity, keyName, valueName)
177             else:
178                 return "set of %s%s" % (quantity, keyName)
179                 
180
181 def atomicTypeToEnglish(base, refTable):
182     if base == 'uuid' and refTable:
183         return refTable
184     else:
185         return base
186
187 def parseSchema(filename):
188     return DbSchema.fromJson(json.load(open(filename, "r")))
189
190 def annotateSchema(schemaFile, annotationFile):
191     schemaJson = json.load(open(schemaFile, "r"))
192     execfile(annotationFile, globals(), {"s": schemaJson})
193     json.dump(schemaJson, sys.stdout)
194
195 def cBaseType(prefix, type, refTable=None):
196     if type == 'uuid' and refTable:
197         return "struct %s%s *" % (prefix, refTable.lower())
198     else:
199         return {'integer': 'int64_t ',
200                 'real': 'double ',
201                 'uuid': 'struct uuid ',
202                 'boolean': 'bool ',
203                 'string': 'char *'}[type]
204
205 def cCopyType(indent, dstVar, dst, src, type, refTable=None):
206     args = {'indent': indent,
207             'dstVar': dstVar,
208             'dst': dst,
209             'src': src}
210     if type == 'uuid' and refTable:
211         return ("%(indent)s%(dstVar)s = %(src)s;\n" +
212                 "%(indent)s%(dst)s = %(src)s->header_.uuid;") % args
213     elif type == 'string':
214         return "%(indent)s%(dstVar)s = %(dst)s = xstrdup(%(src)s);" % args
215     else:
216         return "%(dstVar)s = %(dst)s = %(src)s;" % args
217
218 def typeIsOptionalPointer(type):
219     return (type.min == 0 and type.max == 1 and not type.value
220             and (type.key == 'string'
221                  or (type.key == 'uuid' and type.keyRefTable)))
222
223 def cDeclComment(type):
224     if type.min == 1 and type.max == 1 and type.key == "string":
225         return "\t/* Always nonnull. */"
226     else:
227         return ""
228
229 def constify(cType, const):
230     if (const
231         and cType.endswith('*') and not cType.endswith('**')
232         and (cType.startswith('struct uuid') or cType.startswith('char'))):
233         return 'const %s' % cType
234     else:
235         return cType
236
237 def cMembers(prefix, columnName, column, const):
238     type = column.type
239     if type.min == 1 and type.max == 1:
240         singleton = True
241         pointer = ''
242     else:
243         singleton = False
244         if typeIsOptionalPointer(type):
245             pointer = ''
246         else:
247             pointer = '*'
248
249     if type.value:
250         key = {'name': "key_%s" % columnName,
251                'type': constify(cBaseType(prefix, type.key, type.keyRefTable) + pointer, const),
252                'comment': ''}
253         value = {'name': "value_%s" % columnName,
254                  'type': constify(cBaseType(prefix, type.value, type.valueRefTable) + pointer, const),
255                  'comment': ''}
256         members = [key, value]
257     else:
258         m = {'name': columnName,
259              'type': constify(cBaseType(prefix, type.key, type.keyRefTable) + pointer, const),
260              'comment': cDeclComment(type)}
261         members = [m]
262
263     if not singleton and not typeIsOptionalPointer(type):
264         members.append({'name': 'n_%s' % columnName,
265                         'type': 'size_t ',
266                         'comment': ''})
267     return members
268
269 def printCIDLHeader(schemaFile):
270     schema = parseSchema(schemaFile)
271     prefix = schema.idlPrefix
272     print '''\
273 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
274
275 #ifndef %(prefix)sIDL_HEADER
276 #define %(prefix)sIDL_HEADER 1
277
278 #include <stdbool.h>
279 #include <stddef.h>
280 #include <stdint.h>
281 #include "ovsdb-idl-provider.h"
282 #include "uuid.h"''' % {'prefix': prefix.upper()}
283     for tableName, table in schema.tables.iteritems():
284         print
285         print "/* %s table. */" % tableName
286         structName = "%s%s" % (prefix, tableName.lower())
287         print "struct %s {" % structName
288         print "\tstruct ovsdb_idl_row header_;"
289         for columnName, column in table.columns.iteritems():
290             print "\n\t/* %s column. */" % columnName
291             for member in cMembers(prefix, columnName, column, False):
292                 print "\t%(type)s%(name)s;%(comment)s" % member
293         print '''\
294 };
295
296 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
297 const struct %(s)s *%(s)s_next(const struct %(s)s *);
298 #define %(S)s_FOR_EACH(ROW, IDL) for ((ROW) = %(s)s_first(IDL); (ROW); (ROW) = %(s)s_next(ROW))
299
300 void %(s)s_delete(const struct %(s)s *);
301 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
302 ''' % {'s': structName, 'S': structName.upper()}
303
304         for columnName, column in table.columns.iteritems():
305             print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
306
307         print
308         for columnName, column in table.columns.iteritems():
309
310             print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
311             args = ['%(type)s%(name)s' % member for member
312                     in cMembers(prefix, columnName, column, True)]
313             print '%s);' % ', '.join(args)
314
315     print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
316     print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
317
318 def printEnum(members):
319     if len(members) == 0:
320         return
321
322     print "\nenum {";
323     for member in members[:-1]:
324         print "    %s," % member
325     print "    %s" % members[-1]
326     print "};"
327
328 def printCIDLSource(schemaFile):
329     schema = parseSchema(schemaFile)
330     prefix = schema.idlPrefix
331     print '''\
332 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
333
334 #include <config.h>
335 #include %s
336 #include <limits.h>
337 #include "ovsdb-data.h"''' % schema.idlHeader
338
339     # Table indexes.
340     printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in schema.tables] + ["%sN_TABLES" % prefix.upper()])
341     print "\nstatic struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
342
343     # Cast functions.
344     for tableName, table in schema.tables.iteritems():
345         structName = "%s%s" % (prefix, tableName.lower())
346         print '''
347 static struct %(s)s *
348 %(s)s_cast(struct ovsdb_idl_row *row)
349 {
350     return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
351 }\
352 ''' % {'s': structName}
353
354
355     for tableName, table in schema.tables.iteritems():
356         structName = "%s%s" % (prefix, tableName.lower())
357         print "\f"
358         if table.comment != None:
359             print "/* %s table (%s). */" % (tableName, table.comment)
360         else:
361             print "/* %s table. */" % (tableName)
362
363         # Column indexes.
364         printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
365                    for columnName in table.columns]
366                   + ["%s_N_COLUMNS" % structName.upper()])
367
368         print "\nstatic struct ovsdb_idl_column %s_columns[];" % structName
369
370         # Parse function.
371         print '''
372 static void
373 %s_parse(struct ovsdb_idl_row *row_)
374 {
375     struct %s *row = %s_cast(row_);
376     const struct ovsdb_datum *datum;
377     size_t i UNUSED;
378
379     memset(row_ + 1, 0, sizeof *row - sizeof *row_);''' % (structName, structName, structName)
380
381
382         for columnName, column in table.columns.iteritems():
383             type = column.type
384             refKey = type.key == "uuid" and type.keyRefTable
385             refValue = type.value == "uuid" and type.valueRefTable
386             print
387             print "    datum = &row_->old[%s_COL_%s];" % (structName.upper(), columnName.upper())
388             if type.value:
389                 keyVar = "row->key_%s" % columnName
390                 valueVar = "row->value_%s" % columnName
391             else:
392                 keyVar = "row->%s" % columnName
393                 valueVar = None
394
395             if (type.min == 1 and type.max == 1) or typeIsOptionalPointer(type):
396                 print "    if (datum->n >= 1) {"
397                 if not refKey:
398                     print "        %s = datum->keys[0].%s;" % (keyVar, type.key)
399                 else:
400                     print "        %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[0].uuid));" % (keyVar, prefix, type.keyRefTable.lower(), prefix, prefix.upper(), type.keyRefTable.upper())
401
402                 if valueVar:
403                     if refValue:
404                         print "        %s = datum->values[0].%s;" % (valueVar, type.value)
405                     else:
406                         print "        %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[0].uuid));" % (valueVar, prefix, type.valueRefTable.lower(), prefix, prefix.upper(), type.valueRefTable.upper())
407                 if (not typeIsOptionalPointer(type) and
408                     (type.key == "string" or type.value == "string")):
409                     print "    } else {"
410                     if type.key == "string":
411                         print "        %s = \"\";" % keyVar
412                     if type.value == "string":
413                         print "        %s = \"\";" % valueVar
414                 print "    }"
415
416             else:
417                 if type.max != 'unlimited':
418                     nMax = "MIN(%d, datum->n)" % type.max
419                 else:
420                     nMax = "datum->n"
421                 print "    for (i = 0; i < %s; i++) {" % nMax
422                 refs = []
423                 if refKey:
424                     print "        struct %s%s *keyRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[i].uuid));" % (prefix, type.keyRefTable.lower(), prefix, type.keyRefTable.lower(), prefix, prefix.upper(), type.keyRefTable.upper())
425                     keySrc = "keyRow"
426                     refs.append('keyRow')
427                 else:
428                     keySrc = "datum->keys[i].%s" % type.key
429                 if refValue:
430                     print "        struct %s%s *valueRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[i].uuid));" % (prefix, type.valueRefTable.lower(), prefix, type.valueRefTable.lower(), prefix, prefix.upper(), type.valueRefTable.upper())
431                     valueSrc = "valueRow"
432                     refs.append('valueRow')
433                 elif valueVar:
434                     valueSrc = "datum->values[i].%s" % type.value
435                 if refs:
436                     print "        if (%s) {" % ' && '.join(refs)
437                     indent = "            "
438                 else:
439                     indent = "        "
440                 print "%sif (!row->n_%s) {" % (indent, columnName)
441                 print "%s    %s = xmalloc(%s * sizeof *%s);" % (indent, keyVar, nMax, keyVar)
442                 if valueVar:
443                     print "%s    %s = xmalloc(%s * sizeof %s);" % (indent, valueVar, nMax, valueVar)
444                 print "%s}" % indent
445                 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
446                 if valueVar:
447                     print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
448                 print "%srow->n_%s++;" % (indent, columnName)
449                 if refs:
450                     print "        }"
451                 print "    }"
452         print "}"
453
454         # Unparse function.
455         nArrays = 0
456         for columnName, column in table.columns.iteritems():
457             type = column.type
458             if (type.min != 1 or type.max != 1) and not typeIsOptionalPointer(type):
459                 if not nArrays:
460                     print '''
461 static void
462 %s_unparse(struct ovsdb_idl_row *row_)
463 {
464     struct %s *row = %s_cast(row_);
465 ''' % (structName, structName, structName)
466                 if type.value:
467                     keyVar = "row->key_%s" % columnName
468                     valueVar = "row->value_%s" % columnName
469                 else:
470                     keyVar = "row->%s" % columnName
471                     valueVar = None
472                 print "    free(%s);" % keyVar
473                 if valueVar:
474                     print "    free(%s);" % valueVar
475                 nArrays += 1
476         if not nArrays:
477             print '''
478 static void
479 %s_unparse(struct ovsdb_idl_row *row UNUSED)
480 {''' % (structName)
481         print "}"
482
483         # First, next functions.
484         print '''
485 const struct %(s)s *
486 %(s)s_first(const struct ovsdb_idl *idl)
487 {
488     return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
489 }
490
491 const struct %(s)s *
492 %(s)s_next(const struct %(s)s *row)
493 {
494     return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
495 }''' % {'s': structName,
496         'p': prefix,
497         'P': prefix.upper(),
498         'T': tableName.upper()}
499
500         print '''
501 void
502 %(s)s_delete(const struct %(s)s *row_)
503 {
504     struct %(s)s *row = (struct %(s)s *) row_;
505     ovsdb_idl_txn_delete(&row->header_);
506 }
507
508 struct %(s)s *
509 %(s)s_insert(struct ovsdb_idl_txn *txn)
510 {
511     return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
512 }
513 ''' % {'s': structName,
514        'p': prefix,
515        'P': prefix.upper(),
516        'T': tableName.upper()}
517
518         # Verify functions.
519         for columnName, column in table.columns.iteritems():
520             print '''
521 void
522 %(s)s_verify_%(c)s(const struct %(s)s *row)
523 {
524     ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
525 }''' % {'s': structName,
526         'S': structName.upper(),
527         'c': columnName,
528         'C': columnName.upper()}
529
530         # Set functions.
531         for columnName, column in table.columns.iteritems():
532             type = column.type
533             print '\nvoid'
534             members = cMembers(prefix, columnName, column, True)
535             keyVar = members[0]['name']
536             nVar = None
537             valueVar = None
538             if type.value:
539                 valueVar = members[1]['name']
540                 if len(members) > 2:
541                     nVar = members[2]['name']
542             else:
543                 if len(members) > 1:
544                     nVar = members[1]['name']
545             print '%(s)s_set_%(c)s(const struct %(s)s *row_, %(args)s)' % \
546                 {'s': structName, 'c': columnName,
547                  'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
548             print "{"
549             print "    struct %(s)s *row = (struct %(s)s *) row_;" % {'s': structName}
550             print "    struct ovsdb_datum datum;"
551             if type.min == 1 and type.max == 1:
552                 print
553                 print "    datum.n = 1;"
554                 print "    datum.keys = xmalloc(sizeof *datum.keys);"
555                 print cCopyType("    ", "row->%s" % keyVar, "datum.keys[0].%s" % type.key, keyVar, type.key, type.keyRefTable)
556                 if type.value:
557                     print "    datum.values = xmalloc(sizeof *datum.values);"
558                     print cCopyType("    ", "row->%s" % valueVar, "datum.values[0].%s" % type.value, valueVar, type.value, type.valueRefTable)
559                 else:
560                     print "    datum.values = NULL;"
561             elif typeIsOptionalPointer(type):
562                 print
563                 print "    if (%s) {" % keyVar
564                 print "        datum.n = 1;"
565                 print "        datum.keys = xmalloc(sizeof *datum.keys);"
566                 print cCopyType("        ", "row->%s" % keyVar, "datum.keys[0].%s" % type.key, keyVar, type.key, type.keyRefTable)
567                 print "    } else {"
568                 print "        datum.n = 0;"
569                 print "        datum.keys = NULL;"
570                 print "        row->%s = NULL;" % keyVar
571                 print "    }"
572                 print "    datum.values = NULL;"
573             else:
574                 print "    size_t i;"
575                 print
576                 print "    free(row->%s);" % keyVar
577                 print "    row->%s = %s ? xmalloc(%s * sizeof *row->%s) : NULL;" % (keyVar, nVar, nVar, keyVar)
578                 print "    row->%s = %s;" % (nVar, nVar)
579                 if type.value:
580                     print "    free(row->%s);" % valueVar
581                     print "    row->%s = xmalloc(%s * sizeof *row->%s);" % (valueVar, nVar, valueVar)
582                 print "    datum.n = %s;" % nVar
583                 print "    datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
584                 if type.value:
585                     print "    datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
586                 else:
587                     print "    datum.values = NULL;"
588                 print "    for (i = 0; i < %s; i++) {" % nVar
589                 print cCopyType("        ", "row->%s[i]" % keyVar, "datum.keys[i].%s" % type.key, "%s[i]" % keyVar, type.key, type.keyRefTable)
590                 if type.value:
591                     print cCopyType("        ", "row->%s[i]" % valueVar, "datum.values[i].%s" % type.value, "%s[i]" % valueVar, type.value, type.valueRefTable)
592                 print "    }"
593             print "    ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
594                 % {'s': structName,
595                    'S': structName.upper(),
596                    'C': columnName.upper()}
597             print "}"
598
599         # Table columns.
600         print "\nstatic struct ovsdb_idl_column %s_columns[%s_N_COLUMNS] = {" % (
601             structName, structName.upper())
602         for columnName, column in table.columns.iteritems():
603             type = column.type
604             
605             if type.value:
606                 valueTypeName = type.value.upper()
607             else:
608                 valueTypeName = "VOID"
609             if type.max == "unlimited":
610                 max = "UINT_MAX"
611             else:
612                 max = type.max
613             print "    {\"%s\", {OVSDB_TYPE_%s, OVSDB_TYPE_%s, %d, %s}}," % (
614                 columnName, type.key.upper(), valueTypeName,
615                 type.min, max)
616         print "};"
617
618     # Table classes.
619     print "\f"
620     print "static struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
621     for tableName, table in schema.tables.iteritems():
622         structName = "%s%s" % (prefix, tableName.lower())
623         print "    {\"%s\"," % tableName
624         print "     %s_columns, ARRAY_SIZE(%s_columns)," % (
625             structName, structName)
626         print "     sizeof(struct %s)," % structName
627         print "     %s_parse," % structName
628         print "     %s_unparse}," % structName
629     print "};"
630
631     # IDL class.
632     print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
633     print "    %stable_classes, ARRAY_SIZE(%stable_classes)" % (prefix, prefix)
634     print "};"
635
636 def ovsdb_escape(string):
637     def escape(match):
638         c = match.group(0)
639         if c == '\0':
640             raise Error("strings may not contain null bytes")
641         elif c == '\\':
642             return '\\\\'
643         elif c == '\n':
644             return '\\n'
645         elif c == '\r':
646             return '\\r'
647         elif c == '\t':
648             return '\\t'
649         elif c == '\b':
650             return '\\b'
651         elif c == '\a':
652             return '\\a'
653         else:
654             return '\\x%02x' % ord(c)
655     return re.sub(r'["\\\000-\037]', escape, string)
656
657 def printDoc(schemaFile):
658     schema = parseSchema(schemaFile)
659     print schema.name
660     if schema.comment:
661         print schema.comment
662
663     for tableName, table in sorted(schema.tables.iteritems()):
664         title = "%s table" % tableName
665         print
666         print title
667         print '-' * len(title)
668         if table.comment:
669             print table.comment
670
671         for columnName, column in sorted(table.columns.iteritems()):
672             print
673             print "%s (%s)" % (columnName, column.type.toEnglish())
674             if column.comment:
675                 print "\t%s" % column.comment
676
677 def usage():
678     print """\
679 %(argv0)s: ovsdb schema compiler
680 usage: %(argv0)s [OPTIONS] COMMAND ARG...
681
682 The following commands are supported:
683   annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
684   c-idl-header IDL            print C header file for IDL
685   c-idl-source IDL            print C source file for IDL implementation
686   doc IDL                     print schema documentation
687
688 The following options are also available:
689   -h, --help                  display this help message
690   -V, --version               display version information\
691 """ % {'argv0': argv0}
692     sys.exit(0)
693
694 if __name__ == "__main__":
695     try:
696         try:
697             options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
698                                               ['directory',
699                                                'help',
700                                                'version'])
701         except getopt.GetoptError, geo:
702             sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
703             sys.exit(1)
704             
705         for key, value in options:
706             if key in ['-h', '--help']:
707                 usage()
708             elif key in ['-V', '--version']:
709                 print "ovsdb-idlc (Open vSwitch) @VERSION@"
710             elif key in ['-C', '--directory']:
711                 os.chdir(value)
712             else:
713                 sys.exit(0)
714             
715         optKeys = [key for key, value in options]
716
717         if not args:
718             sys.stderr.write("%s: missing command argument "
719                              "(use --help for help)\n" % argv0)
720             sys.exit(1)
721
722         commands = {"annotate": (annotateSchema, 2),
723                     "c-idl-header": (printCIDLHeader, 1),
724                     "c-idl-source": (printCIDLSource, 1),
725                     "doc": (printDoc, 1)}
726
727         if not args[0] in commands:
728             sys.stderr.write("%s: unknown command \"%s\" "
729                              "(use --help for help)\n" % (argv0, args[0]))
730             sys.exit(1)
731
732         func, n_args = commands[args[0]]
733         if len(args) - 1 != n_args:
734             sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
735                              "provided\n"
736                              % (argv0, args[0], n_args, len(args) - 1))
737             sys.exit(1)
738
739         func(*args[1:])
740     except Error, e:
741         sys.stderr.write("%s: %s\n" % (argv0, e.msg))
742         sys.exit(1)
743
744 # Local variables:
745 # mode: python
746 # End: