| 1 | #!/usr/bin/env python
 | 
| 2 | from __future__ import print_function
 | 
| 3 | """
 | 
| 4 | asdl_demo.py
 | 
| 5 | """
 | 
| 6 | 
 | 
| 7 | import sys
 | 
| 8 | from asdl import asdl_ as asdl
 | 
| 9 | from asdl import arith_parse
 | 
| 10 | from asdl import py_meta
 | 
| 11 | from asdl import encode
 | 
| 12 | from asdl import format as fmt
 | 
| 13 | 
 | 
| 14 | from osh.meta import Id
 | 
| 15 | from core import util
 | 
| 16 | 
 | 
| 17 | log = util.log
 | 
| 18 | 
 | 
| 19 | 
 | 
| 20 | def main(argv):
 | 
| 21 |   try:
 | 
| 22 |     action = argv[1]
 | 
| 23 |   except IndexError:
 | 
| 24 |     raise RuntimeError('Action required')
 | 
| 25 | 
 | 
| 26 |   if action == 'py':  # Prints the module
 | 
| 27 |     schema_path = argv[2]
 | 
| 28 | 
 | 
| 29 |     with open(schema_path) as f:
 | 
| 30 |       module = asdl.parse(f)
 | 
| 31 | 
 | 
| 32 |     app_types = {'id': asdl.UserType(Id)}
 | 
| 33 |     type_lookup = asdl.ResolveTypes(module, app_types)
 | 
| 34 | 
 | 
| 35 |     # Note this is a big tree.  But we really want a graph of pointers to
 | 
| 36 |     # instances.
 | 
| 37 |     # Type(name, Product(...))
 | 
| 38 |     # Type(name, Sum([Constructor(...), ...]))
 | 
| 39 |     #print(module)
 | 
| 40 | 
 | 
| 41 |     root = sys.modules[__name__]
 | 
| 42 |     # NOTE: We shouldn't pass in app_types for arith.asdl, but this is just a
 | 
| 43 |     # demo.
 | 
| 44 |     py_meta.MakeTypes(module, root, type_lookup)
 | 
| 45 | 
 | 
| 46 |     log('Dynamically created a Python module with these types:')
 | 
| 47 |     for name in dir(root):
 | 
| 48 |       print('\t' + name)
 | 
| 49 | 
 | 
| 50 |   elif action == 'arith-encode':  # oheap encoding
 | 
| 51 |     expr = argv[2]
 | 
| 52 |     out_path = argv[3]
 | 
| 53 | 
 | 
| 54 |     obj = arith_parse.ParseShell(expr)
 | 
| 55 |     print('Encoding %r into binary:' % expr)
 | 
| 56 |     print(obj)
 | 
| 57 | 
 | 
| 58 |     enc = encode.Params()
 | 
| 59 |     with open(out_path, 'wb') as f:
 | 
| 60 |       out = encode.BinOutput(f)
 | 
| 61 |       encode.EncodeRoot(obj, enc, out)
 | 
| 62 | 
 | 
| 63 |   elif action == 'arith-format':  # pretty printing
 | 
| 64 |     expr = argv[2]
 | 
| 65 | 
 | 
| 66 |     obj = arith_parse.ParseShell(expr)
 | 
| 67 |     #out = fmt.TextOutput(sys.stdout)
 | 
| 68 |     tree = fmt.MakeTree(obj)
 | 
| 69 |     #treee= ['hi', 'there', ['a', 'b'], 'c']
 | 
| 70 |     f = fmt.DetectConsoleOutput(sys.stdout)
 | 
| 71 |     fmt.PrintTree(tree, f)
 | 
| 72 |     print()
 | 
| 73 | 
 | 
| 74 |     # Might need to print the output?
 | 
| 75 |     # out.WriteToFile?
 | 
| 76 | 
 | 
| 77 |   else:
 | 
| 78 |     raise RuntimeError('Invalid action %r' % action)
 | 
| 79 | 
 | 
| 80 | 
 | 
| 81 | if __name__ == '__main__':
 | 
| 82 |   try:
 | 
| 83 |     main(sys.argv)
 | 
| 84 |   except RuntimeError as e:
 | 
| 85 |     print('FATAL: %r' % e, file=sys.stderr)
 | 
| 86 |     sys.exit(1)
 |