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