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