From bf6aa6aeb277fb534567f62813145dca8c1a362b Mon Sep 17 00:00:00 2001 From: Andy Chu Date: Sun, 13 Dec 2020 15:40:43 -0800 Subject: [PATCH] [mycpp] Generate the new GLOBAL_LIST macro --- mycpp/cppgen_pass.py | 23 ++++++++++------------- mycpp/examples/containers.py | 7 +++++++ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/mycpp/cppgen_pass.py b/mycpp/cppgen_pass.py index 514e1bbab7..965555ef74 100644 --- a/mycpp/cppgen_pass.py +++ b/mycpp/cppgen_pass.py @@ -975,11 +975,12 @@ def visit_unary_expr(self, o: 'mypy.nodes.UnaryExpr') -> T: self.write(op_str) self.accept(o.expr) - def _WriteListElements(self, o): + def _WriteListElements(self, o, sep=', '): + # sep may be 'COMMA' for a macro self.write('{') for i, item in enumerate(o.items): if i != 0: - self.write(', ') + self.write(sep) self.accept(item) self.write('}') @@ -1215,19 +1216,15 @@ def visit_assignment_stmt(self, o: 'mypy.nodes.AssignmentStmt') -> T: item_type = lval_type.args[0] item_c_type = get_c_type(item_type) - # Create a value first - - temp_name = 'glist%d' % self.unique_id - self.unique_id += 1 - - self.write('List<%s> %s = ', item_c_type, temp_name) - self._WriteListElements(o.rvalue) - self.write(';\n') - # Then a pointer to it - self.write('List<%s>* %s = &%s;\n', item_c_type, lval.name, - temp_name) + self.write('GLOBAL_LIST(%s, %d, %s, ', + item_c_type, len(o.rvalue.items), lval.name) + + # TODO: Assert that every item is a constant? + # COMMA for macro + self._WriteListElements(o.rvalue, sep=' COMMA ') + self.write(');\n') return if isinstance(o.rvalue, DictExpr): diff --git a/mycpp/examples/containers.py b/mycpp/examples/containers.py index 32d438fd83..f09c703740 100755 --- a/mycpp/examples/containers.py +++ b/mycpp/examples/containers.py @@ -10,6 +10,13 @@ from typing import List, Tuple, Dict, Optional +mystr = 'foo' # type: str +mylist = [1, 2] # type: List[int] +mylist2 = ['spam', 'eggs'] # type: List[str] + +#mydict = {'a': 42, 'b': 43} # type: Dict[str, int] + + def ListDemo(): # type: () -> None intlist = [] # type: List[int]