Skip to content

Commit

Permalink
[mycpp] Generate the new GLOBAL_LIST macro
Browse files Browse the repository at this point in the history
  • Loading branch information
Andy Chu committed Dec 13, 2020
1 parent 6ae6a74 commit bf6aa6a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 13 deletions.
23 changes: 10 additions & 13 deletions mycpp/cppgen_pass.py
Expand Up @@ -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('}')

Expand Down Expand Up @@ -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):
Expand Down
7 changes: 7 additions & 0 deletions mycpp/examples/containers.py
Expand Up @@ -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]
Expand Down

0 comments on commit bf6aa6a

Please sign in to comment.