|
| 1 | +#!/usr/bin/env python |
| 2 | +# Copyright (c) 2015, Facebook, Inc. |
| 3 | +# All rights reserved. |
| 4 | +# |
| 5 | +# This source code is licensed under the BSD-style license found in the |
| 6 | +# LICENSE file in the root directory of this source tree. An additional grant |
| 7 | +# of patent rights can be found in the PATENTS file in the same directory. |
| 8 | + |
| 9 | +from importlib import import_module |
| 10 | + |
| 11 | + |
| 12 | +def load_lang(lang): |
| 13 | + return import_module(lang).Printer() |
| 14 | + |
| 15 | + |
| 16 | +def print_ast(lang_module, input_file): |
| 17 | + lang_module.start_file() |
| 18 | + line = input_file.readline() |
| 19 | + |
| 20 | + while line: |
| 21 | + line = line.strip() |
| 22 | + if line.startswith('#') or not line: |
| 23 | + line = input_file.readline() |
| 24 | + continue |
| 25 | + |
| 26 | + code, rest = line.split(None, 1) |
| 27 | + |
| 28 | + if code[0] == 'T': |
| 29 | + lang_module.start_type(rest) |
| 30 | + field_line = input_file.readline().strip() |
| 31 | + while field_line: |
| 32 | + if field_line.startswith('#'): |
| 33 | + field_line = input_file.readline().strip() |
| 34 | + continue |
| 35 | + |
| 36 | + field_kind, field_type, field_name = field_line.split() |
| 37 | + nullable = len(field_kind) > 1 and field_kind[1] == '?' |
| 38 | + |
| 39 | + if field_kind[0] == 'S': |
| 40 | + plural = False |
| 41 | + |
| 42 | + elif field_kind[0] == 'P': |
| 43 | + plural = True |
| 44 | + |
| 45 | + else: |
| 46 | + raise Exception('Unknown field kind: ' + field_kind) |
| 47 | + |
| 48 | + lang_module.field(field_type, field_name, nullable, plural) |
| 49 | + field_line = input_file.readline().strip() |
| 50 | + |
| 51 | + lang_module.end_type(rest) |
| 52 | + |
| 53 | + elif code[0] == 'U': |
| 54 | + lang_module.start_union(rest) |
| 55 | + field_line = input_file.readline().strip() |
| 56 | + while field_line: |
| 57 | + option_code, option_type = field_line.split() |
| 58 | + if option_code != 'O': |
| 59 | + raise Exception('Unknown code in union: ' + option_code) |
| 60 | + |
| 61 | + lang_module.union_option(option_type) |
| 62 | + field_line = input_file.readline().strip() |
| 63 | + |
| 64 | + lang_module.end_union(rest) |
| 65 | + |
| 66 | + line = input_file.readline() |
| 67 | + |
| 68 | + lang_module.end_file() |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == '__main__': |
| 72 | + import sys |
| 73 | + |
| 74 | + lang = sys.argv[1] |
| 75 | + filename = sys.argv[2] |
| 76 | + |
| 77 | + lang_module = load_lang(lang) |
| 78 | + |
| 79 | + print_ast(lang_module, open(filename, 'r')) |
0 commit comments