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