summaryrefslogtreecommitdiffstats
path: root/tools/json_schema_compiler/compiler.py
blob: 4e41e3853ac42da86e2a5d7deec35f9b02870bd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Generator for C++ structs from api json files.

The purpose of this tool is to remove the need for hand-written code that
converts to and from base::Value types when receiving javascript api calls.
Originally written for generating code for extension apis. Reference schemas
are in chrome/common/extensions/api.

Usage example:
  compiler.py --root /home/Work/src --namespace extensions windows.json
    tabs.json
  compiler.py --destdir gen --root /home/Work/src
    --namespace extensions windows.json tabs.json
"""

from cpp_generator import CppGenerator
from cpp_type_generator import CppTypeGenerator
from dart_generator import DartGenerator
from cpp_bundle_generator import CppBundleGenerator
from model import Model
import idl_schema
import json_schema

import optparse
import os.path
import sys

# Names of supported code generators, as specified on the command-line.
# First is default.
GENERATORS = ['cpp', 'cpp-bundle', 'dart']

def load_schema(schema):
  schema_filename, schema_extension = os.path.splitext(schema)

  if schema_extension == '.json':
    api_defs = json_schema.Load(schema)
  elif schema_extension == '.idl':
    api_defs = idl_schema.Load(schema)
  else:
    sys.exit('Did not recognize file extension %s for schema %s' %
             (schema_extension, schema))
  if len(api_defs) != 1:
    sys.exit('File %s has multiple schemas. Files are only allowed to contain a'
             ' single schema.' % schema)

  return api_defs

if __name__ == '__main__':
  parser = optparse.OptionParser(
      description='Generates a C++ model of an API from JSON schema',
      usage='usage: %prog [option]... schema')
  parser.add_option('-r', '--root', default='.',
      help='logical include root directory. Path to schema files from specified'
      'dir will be the include path.')
  parser.add_option('-d', '--destdir',
      help='root directory to output generated files.')
  parser.add_option('-n', '--namespace', default='generated_api_schemas',
      help='C++ namespace for generated files. e.g extensions::api.')
  parser.add_option('-g', '--generator', default=GENERATORS[0],
      choices=GENERATORS,
      help='The generator to use to build the output code. Supported values are'
      ' %s' % GENERATORS)
  parser.add_option('-D', '--dart-overrides-dir', dest='dart_overrides_dir',
      help='Adds custom dart from files in the given directory (Dart only).')

  (opts, filenames) = parser.parse_args()

  if not filenames:
    sys.exit(0) # This is OK as a no-op

  # Unless in bundle mode, only one file should be specified.
  if opts.generator != 'cpp-bundle' and len(filenames) > 1:
    # TODO(sashab): Could also just use filenames[0] here and not complain.
    raise Exception(
        "Unless in bundle mode, only one file can be specified at a time.")

  # Merge the source files into a single list of schemas.
  api_defs = []
  for filename in filenames:
    schema = os.path.normpath(filename)
    schema_filename, schema_extension = os.path.splitext(schema)
    path, short_filename = os.path.split(schema_filename)
    api_def = load_schema(schema)

    # If compiling the C++ model code, delete 'nocompile' nodes.
    if opts.generator == 'cpp':
      api_def = json_schema.DeleteNodes(api_def, 'nocompile')
    api_defs.extend(api_def)

  api_model = Model()

  # Load type dependencies into the model.
  #
  # HACK(kalman): bundle mode doesn't work with dependencies, because not all
  # schemas work in bundle mode.
  #
  # TODO(kalman): load dependencies lazily (get rid of the 'dependencies' list)
  # and this problem will go away.
  if opts.generator != 'cpp-bundle':
    for target_namespace in api_defs:
      for referenced_schema in target_namespace.get('dependencies', []):
        split_schema = referenced_schema.split(':', 1)
        if len(split_schema) > 1:
          if split_schema[0] != 'api':
            continue
          else:
            referenced_schema = split_schema[1]

        referenced_schema_path = os.path.join(
            os.path.dirname(schema), referenced_schema + '.json')
        referenced_api_defs = json_schema.Load(referenced_schema_path)

        for namespace in referenced_api_defs:
          api_model.AddNamespace(
              namespace,
              os.path.relpath(referenced_schema_path, opts.root),
              include_compiler_options=True)

  # For single-schema compilation make sure that the first (i.e. only) schema
  # is the default one.
  default_namespace = None

  # Load the actual namespaces into the model.
  for target_namespace, schema_filename in zip(api_defs, filenames):
    relpath = os.path.relpath(os.path.normpath(schema_filename), opts.root)
    namespace = api_model.AddNamespace(target_namespace,
                                       relpath,
                                       include_compiler_options=True)
    if default_namespace is None:
      default_namespace = namespace

    path, filename = os.path.split(schema_filename)
    short_filename, extension = os.path.splitext(filename)

    # Filenames are checked against the unix_names of the namespaces they
    # generate because the gyp uses the names of the JSON files to generate
    # the names of the .cc and .h files. We want these to be using unix_names.
    if namespace.unix_name != short_filename:
      sys.exit("Filename %s is illegal. Name files using unix_hacker style." %
               schema_filename)

    # The output filename must match the input filename for gyp to deal with it
    # properly.
    out_file = namespace.unix_name

  # Construct the type generator with all the namespaces in this model.
  type_generator = CppTypeGenerator(api_model,
                                    default_namespace=default_namespace)

  if opts.generator == 'cpp-bundle':
    cpp_bundle_generator = CppBundleGenerator(opts.root,
                                              api_model,
                                              api_defs,
                                              type_generator,
                                              opts.namespace)
    generators = [
      ('generated_api.h', cpp_bundle_generator.api_h_generator),
      ('generated_schemas.cc', cpp_bundle_generator.schemas_cc_generator),
      ('generated_schemas.h', cpp_bundle_generator.schemas_h_generator)
    ]
  elif opts.generator == 'cpp':
    cpp_generator = CppGenerator(type_generator, opts.namespace)
    generators = [
      ('%s.h' % namespace.unix_name, cpp_generator.h_generator),
      ('%s.cc' % namespace.unix_name, cpp_generator.cc_generator)
    ]
  elif opts.generator == 'dart':
    generators = [
      ('%s.dart' % namespace.unix_name, DartGenerator(
          opts.dart_overrides_dir))
    ]
  else:
    raise Exception('Unrecognised generator %s' % opts.generator)

  for filename, generator in generators:
    code = generator.Generate(namespace).Render()
    if opts.destdir:
      with open(os.path.join(opts.destdir, namespace.source_file_dir,
          filename), 'w') as f:
        f.write(code)
    else:
      print filename
      print
      print code
      print