Skip to content

Commit 46a7fce

Browse files
committed
Fix autopatching expressions in return statements
1 parent 312859d commit 46a7fce

File tree

1 file changed

+37
-27
lines changed

1 file changed

+37
-27
lines changed

graalpython/lib-graalpython/modules/autopatch_capi.py

Lines changed: 37 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -81,35 +81,46 @@ def consume_whitespace_forward(idx):
8181

8282
# scan backwards to capture the whole receiver
8383
idx = consume_whitespace_backwards(start - 2)
84-
empty = True
85-
while idx > 1:
84+
85+
def consume_pairwise_backwards(idx, l, r):
86+
level = 1
87+
idx -= 1
88+
while level and idx:
89+
c = contents[idx]
90+
if c == l:
91+
level -= 1
92+
elif c == r:
93+
level += 1
94+
idx -= 1
95+
return idx
96+
97+
def consume_identifier_backwards(idx):
98+
while (contents[idx].isidentifier() or contents[idx].isdigit()) and idx:
99+
idx -= 1
100+
return idx
101+
102+
first = True
103+
while idx:
86104
c = contents[idx]
87-
c2 = contents[idx - 1: idx + 1]
88-
if c == ')' or c == ']' or (c == '>' and c2 != '->'):
89-
if level == 0 and c == ')' and not empty:
105+
if c == ')' and first:
106+
idx = consume_pairwise_backwards(idx, '(', ')')
107+
elif c == ']':
108+
idx = consume_pairwise_backwards(idx, '[', ']')
109+
elif c.isidentifier() or c.isdigit():
110+
id_start = consume_identifier_backwards(idx)
111+
if contents[id_start + 1: idx + 1] == 'return':
90112
idx += 1
91-
break # don't include casts
92-
empty = False
93-
level += 1
113+
break
114+
idx = id_start
115+
elif c == '.':
94116
idx -= 1
95-
elif level > 0 and (c == '(' or c == '[' or c == '<'):
96-
level -= 1
97-
idx = consume_whitespace_backwards(idx - 1)
117+
elif c == '>' and idx > 1 and contents[idx - 1] == '-':
118+
idx -= 2
98119
else:
99-
if level > 0:
100-
idx -= 1
101-
elif c.isidentifier() or c.isdigit():
102-
empty = False
103-
idx -= 1
104-
elif c == '.':
105-
empty = True
106-
idx = consume_whitespace_backwards(idx - 1)
107-
elif c2 == '->':
108-
empty = True
109-
idx = consume_whitespace_backwards(idx - 2)
110-
else:
111-
idx += 1
112-
break
120+
idx += 1
121+
break
122+
first = False
123+
idx = consume_whitespace_backwards(idx)
113124

114125
receiver_start = consume_whitespace_forward(idx)
115126
receiver_string = contents[receiver_start: start - 1]
@@ -122,7 +133,6 @@ def consume_whitespace_forward(idx):
122133
# this looks like an assignment, determine the value
123134
idx = consume_whitespace_forward(idx + 1)
124135
value_start = idx
125-
empty = True
126136
while idx < len(contents) - 2:
127137
c = contents[idx]
128138
c2 = contents[idx: idx + 2]
@@ -134,7 +144,7 @@ def consume_whitespace_forward(idx):
134144
idx += 1
135145
else:
136146
if level == 0 and (c == ')' or c == ';' or c == ','):
137-
break;
147+
break
138148
if c2 == '<=' or c2 == '<<' or c2 == '>='or c2 == '>>' or c2 == '->':
139149
idx += 2
140150
else:

0 commit comments

Comments
 (0)