| 1 | #!/usr/bin/env python2
 | 
| 2 | """
 | 
| 3 | asdl_main.py - Generate Python and C from ASDL schemas.
 | 
| 4 | """
 | 
| 5 | from __future__ import print_function
 | 
| 6 | 
 | 
| 7 | import optparse
 | 
| 8 | import os
 | 
| 9 | import sys
 | 
| 10 | 
 | 
| 11 | from asdl import ast
 | 
| 12 | from asdl import front_end
 | 
| 13 | from asdl import gen_cpp
 | 
| 14 | from asdl import gen_python
 | 
| 15 | #from asdl.util import log
 | 
| 16 | 
 | 
| 17 | ARG_0 = os.path.basename(sys.argv[0])
 | 
| 18 | 
 | 
| 19 | 
 | 
| 20 | def Options():
 | 
| 21 |     """Returns an option parser instance."""
 | 
| 22 | 
 | 
| 23 |     p = optparse.OptionParser()
 | 
| 24 |     p.add_option('--no-pretty-print-methods',
 | 
| 25 |                  dest='pretty_print_methods',
 | 
| 26 |                  action='store_false',
 | 
| 27 |                  default=True,
 | 
| 28 |                  help='Whether to generate pretty printing methods')
 | 
| 29 | 
 | 
| 30 |     # Control Python constructors
 | 
| 31 | 
 | 
| 32 |     # for hnode.asdl
 | 
| 33 |     p.add_option('--py-init-N',
 | 
| 34 |                  dest='py_init_n',
 | 
| 35 |                  action='store_true',
 | 
| 36 |                  default=False,
 | 
| 37 |                  help='Generate Python __init__ that requires every field')
 | 
| 38 | 
 | 
| 39 |     # The default, which matches C++
 | 
| 40 |     p.add_option(
 | 
| 41 |         '--init-zero-N',
 | 
| 42 |         dest='init_zero_n',
 | 
| 43 |         action='store_true',
 | 
| 44 |         default=True,
 | 
| 45 |         help='Generate 0 arg and N arg constructors, in Python and C++')
 | 
| 46 | 
 | 
| 47 |     return p
 | 
| 48 | 
 | 
| 49 | 
 | 
| 50 | class UserType(object):
 | 
| 51 |     """TODO: Delete this class after we have modules with 'use'?"""
 | 
| 52 | 
 | 
| 53 |     def __init__(self, mod_name, type_name):
 | 
| 54 |         self.mod_name = mod_name
 | 
| 55 |         self.type_name = type_name
 | 
| 56 | 
 | 
| 57 |     def __repr__(self):
 | 
| 58 |         return '<UserType %s %s>' % (self.mod_name, self.type_name)
 | 
| 59 | 
 | 
| 60 | 
 | 
| 61 | def main(argv):
 | 
| 62 |     o = Options()
 | 
| 63 |     opts, argv = o.parse_args(argv)
 | 
| 64 | 
 | 
| 65 |     try:
 | 
| 66 |         action = argv[1]
 | 
| 67 |     except IndexError:
 | 
| 68 |         raise RuntimeError('Action required')
 | 
| 69 | 
 | 
| 70 |     try:
 | 
| 71 |         schema_path = argv[2]
 | 
| 72 |     except IndexError:
 | 
| 73 |         raise RuntimeError('Schema path required')
 | 
| 74 | 
 | 
| 75 |     schema_filename = os.path.basename(schema_path)
 | 
| 76 |     if schema_filename in ('syntax.asdl', 'runtime.asdl'):
 | 
| 77 |         app_types = {'id': UserType('id_kind_asdl', 'Id_t')}
 | 
| 78 |     else:
 | 
| 79 |         app_types = {}
 | 
| 80 | 
 | 
| 81 |     if action == 'c':  # Generate C code for the lexer
 | 
| 82 |         with open(schema_path) as f:
 | 
| 83 |             schema_ast = front_end.LoadSchema(f, app_types)
 | 
| 84 | 
 | 
| 85 |         v = gen_cpp.CEnumVisitor(sys.stdout)
 | 
| 86 |         v.VisitModule(schema_ast)
 | 
| 87 | 
 | 
| 88 |     elif action == 'cpp':  # Generate C++ code for ASDL schemas
 | 
| 89 |         out_prefix = argv[3]
 | 
| 90 | 
 | 
| 91 |         with open(schema_path) as f:
 | 
| 92 |             schema_ast = front_end.LoadSchema(f, app_types)
 | 
| 93 | 
 | 
| 94 |         # asdl/typed_arith.asdl -> typed_arith_asdl
 | 
| 95 |         ns = os.path.basename(schema_path).replace('.', '_')
 | 
| 96 | 
 | 
| 97 |         with open(out_prefix + '.h', 'w') as f:
 | 
| 98 |             guard = ns.upper()
 | 
| 99 |             f.write("""\
 | 
| 100 | // %s.h is generated by %s
 | 
| 101 | 
 | 
| 102 | #ifndef %s
 | 
| 103 | #define %s
 | 
| 104 | 
 | 
| 105 | """ % (out_prefix, ARG_0, guard, guard))
 | 
| 106 | 
 | 
| 107 |             f.write("""\
 | 
| 108 | #include <cstdint>
 | 
| 109 | """)
 | 
| 110 |             f.write("""
 | 
| 111 | #include "mycpp/runtime.h"
 | 
| 112 | """)
 | 
| 113 |             if opts.pretty_print_methods:
 | 
| 114 |                 f.write("""\
 | 
| 115 | #include "_gen/asdl/hnode.asdl.h"
 | 
| 116 | using hnode_asdl::hnode_t;
 | 
| 117 | 
 | 
| 118 | """)
 | 
| 119 | 
 | 
| 120 |             if app_types:
 | 
| 121 |                 f.write("""\
 | 
| 122 | #include "_gen/frontend/id_kind.asdl.h"
 | 
| 123 | using id_kind_asdl::Id_t;
 | 
| 124 | 
 | 
| 125 | """)
 | 
| 126 | 
 | 
| 127 |             for use in schema_ast.uses:
 | 
| 128 |                 # Forward declarations in the header, like
 | 
| 129 |                 # namespace syntax_asdl { class command_t; }
 | 
| 130 |                 # must come BEFORE namespace, so it can't be in the visitor.
 | 
| 131 | 
 | 
| 132 |                 # assume sum type for now!
 | 
| 133 |                 cpp_names = [
 | 
| 134 |                     'class %s;' % ast.TypeNameHeuristic(n)
 | 
| 135 |                     for n in use.type_names
 | 
| 136 |                 ]
 | 
| 137 |                 f.write('namespace %s_asdl { %s }\n' %
 | 
| 138 |                         (use.module_parts[-1], ' '.join(cpp_names)))
 | 
| 139 |                 f.write('\n')
 | 
| 140 | 
 | 
| 141 |             f.write("""\
 | 
| 142 | namespace %s {
 | 
| 143 | 
 | 
| 144 | // use struct instead of namespace so 'using' works consistently
 | 
| 145 | #define ASDL_NAMES struct
 | 
| 146 | 
 | 
| 147 | """ % ns)
 | 
| 148 | 
 | 
| 149 |             v = gen_cpp.ForwardDeclareVisitor(f)
 | 
| 150 |             v.VisitModule(schema_ast)
 | 
| 151 | 
 | 
| 152 |             debug_info = {}
 | 
| 153 |             v2 = gen_cpp.ClassDefVisitor(
 | 
| 154 |                 f,
 | 
| 155 |                 pretty_print_methods=opts.pretty_print_methods,
 | 
| 156 |                 debug_info=debug_info)
 | 
| 157 |             v2.VisitModule(schema_ast)
 | 
| 158 | 
 | 
| 159 |             f.write("""
 | 
| 160 | }  // namespace %s
 | 
| 161 | 
 | 
| 162 | #endif  // %s
 | 
| 163 | """ % (ns, guard))
 | 
| 164 | 
 | 
| 165 |             try:
 | 
| 166 |                 debug_info_path = argv[4]
 | 
| 167 |             except IndexError:
 | 
| 168 |                 pass
 | 
| 169 |             else:
 | 
| 170 |                 with open(debug_info_path, 'w') as f:
 | 
| 171 |                     from pprint import pformat
 | 
| 172 |                     f.write('''\
 | 
| 173 | cpp_namespace = %r
 | 
| 174 | tags_to_types = \\
 | 
| 175 | %s
 | 
| 176 | ''' % (ns, pformat(debug_info)))
 | 
| 177 | 
 | 
| 178 |             if not opts.pretty_print_methods:
 | 
| 179 |                 return
 | 
| 180 | 
 | 
| 181 |             with open(out_prefix + '.cc', 'w') as f:
 | 
| 182 |                 f.write("""\
 | 
| 183 | // %s.cc is generated by %s
 | 
| 184 | 
 | 
| 185 | #include "%s.h"
 | 
| 186 | #include <assert.h>
 | 
| 187 | """ % (out_prefix, ARG_0, out_prefix))
 | 
| 188 | 
 | 
| 189 |                 f.write("""\
 | 
| 190 | #include "prebuilt/asdl/runtime.mycpp.h"  // generated code uses wrappers here
 | 
| 191 | """)
 | 
| 192 | 
 | 
| 193 |                 # To call pretty-printing methods
 | 
| 194 |                 for use in schema_ast.uses:
 | 
| 195 |                     f.write('#include "_gen/%s.asdl.h"  // "use" in ASDL \n' %
 | 
| 196 |                             '/'.join(use.module_parts))
 | 
| 197 | 
 | 
| 198 |                 f.write("""\
 | 
| 199 | 
 | 
| 200 | // Generated code uses these types
 | 
| 201 | using hnode_asdl::hnode;
 | 
| 202 | using hnode_asdl::Field;
 | 
| 203 | using hnode_asdl::color_e;
 | 
| 204 | 
 | 
| 205 | """)
 | 
| 206 | 
 | 
| 207 |                 if app_types:
 | 
| 208 |                     f.write('using id_kind_asdl::Id_str;\n')
 | 
| 209 | 
 | 
| 210 |                 f.write("""
 | 
| 211 | namespace %s {
 | 
| 212 | 
 | 
| 213 | """ % ns)
 | 
| 214 | 
 | 
| 215 |                 v3 = gen_cpp.MethodDefVisitor(f)
 | 
| 216 |                 v3.VisitModule(schema_ast)
 | 
| 217 | 
 | 
| 218 |                 f.write("""
 | 
| 219 | }  // namespace %s
 | 
| 220 | """ % ns)
 | 
| 221 | 
 | 
| 222 |     elif action == 'mypy':  # Generated typed MyPy code
 | 
| 223 |         with open(schema_path) as f:
 | 
| 224 |             schema_ast = front_end.LoadSchema(f, app_types)
 | 
| 225 | 
 | 
| 226 |         try:
 | 
| 227 |             abbrev_module_name = argv[3]
 | 
| 228 |         except IndexError:
 | 
| 229 |             abbrev_mod = None
 | 
| 230 |         else:
 | 
| 231 |             # Weird Python rule for importing: fromlist needs to be non-empty.
 | 
| 232 |             abbrev_mod = __import__(abbrev_module_name, fromlist=['.'])
 | 
| 233 | 
 | 
| 234 |         f = sys.stdout
 | 
| 235 | 
 | 
| 236 |         # TODO: Remove Any once we stop using it
 | 
| 237 |         f.write("""\
 | 
| 238 | from asdl import pybase
 | 
| 239 | from mycpp import mops
 | 
| 240 | from typing import Optional, List, Tuple, Dict, Any, cast, TYPE_CHECKING
 | 
| 241 | """)
 | 
| 242 | 
 | 
| 243 |         if schema_ast.uses:
 | 
| 244 |             f.write('\n')
 | 
| 245 |             f.write('if TYPE_CHECKING:\n')
 | 
| 246 |         for use in schema_ast.uses:
 | 
| 247 |             py_names = [ast.TypeNameHeuristic(n) for n in use.type_names]
 | 
| 248 |             # indented
 | 
| 249 |             f.write('  from _devbuild.gen.%s_asdl import %s\n' %
 | 
| 250 |                     (use.module_parts[-1], ', '.join(py_names)))
 | 
| 251 |         f.write('\n')
 | 
| 252 | 
 | 
| 253 |         for typ in app_types.itervalues():
 | 
| 254 |             if isinstance(typ, UserType):
 | 
| 255 |                 f.write('from _devbuild.gen.%s import %s\n' %
 | 
| 256 |                         (typ.mod_name, typ.type_name))
 | 
| 257 |                 # HACK
 | 
| 258 |                 f.write('from _devbuild.gen.%s import Id_str\n' % typ.mod_name)
 | 
| 259 |                 f.write('\n')
 | 
| 260 | 
 | 
| 261 |         if opts.pretty_print_methods:
 | 
| 262 |             f.write("""
 | 
| 263 | from asdl import runtime  # For runtime.NO_SPID
 | 
| 264 | from asdl.runtime import NewRecord, NewLeaf, TraversalState
 | 
| 265 | from _devbuild.gen.hnode_asdl import color_e, hnode, hnode_e, hnode_t, Field
 | 
| 266 | 
 | 
| 267 | """)
 | 
| 268 | 
 | 
| 269 |         abbrev_mod_entries = dir(abbrev_mod) if abbrev_mod else []
 | 
| 270 |         v = gen_python.GenMyPyVisitor(
 | 
| 271 |             f,
 | 
| 272 |             abbrev_mod_entries,
 | 
| 273 |             pretty_print_methods=opts.pretty_print_methods,
 | 
| 274 |             py_init_n=opts.py_init_n)
 | 
| 275 |         v.VisitModule(schema_ast)
 | 
| 276 | 
 | 
| 277 |         if abbrev_mod:
 | 
| 278 |             f.write("""\
 | 
| 279 | #
 | 
| 280 | # CONCATENATED FILE
 | 
| 281 | #
 | 
| 282 | 
 | 
| 283 | """)
 | 
| 284 |             first, module = abbrev_module_name.rsplit('.', 1)
 | 
| 285 |             dir_name = first.replace('.', '/')
 | 
| 286 |             path = os.path.join(dir_name, module + '.py')
 | 
| 287 |             with open(path) as in_f:
 | 
| 288 |                 f.write(in_f.read())
 | 
| 289 | 
 | 
| 290 |     else:
 | 
| 291 |         raise RuntimeError('Invalid action %r' % action)
 | 
| 292 | 
 | 
| 293 | 
 | 
| 294 | if __name__ == '__main__':
 | 
| 295 |     try:
 | 
| 296 |         main(sys.argv)
 | 
| 297 |     except RuntimeError as e:
 | 
| 298 |         print('%s: FATAL: %s' % (ARG_0, e), file=sys.stderr)
 | 
| 299 |         sys.exit(1)
 |