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