Replace substrings of input that are enclosed in parenthesis. Return a new string and a mapping of replacements.
(s)
| 1209 | |
| 1210 | |
| 1211 | def replace_parenthesis(s): |
| 1212 | """Replace substrings of input that are enclosed in parenthesis. |
| 1213 | |
| 1214 | Return a new string and a mapping of replacements. |
| 1215 | """ |
| 1216 | # Find a parenthesis pair that appears first. |
| 1217 | |
| 1218 | # Fortran deliminator are `(`, `)`, `[`, `]`, `(/', '/)`, `/`. |
| 1219 | # We don't handle `/` deliminator because it is not a part of an |
| 1220 | # expression. |
| 1221 | left, right = None, None |
| 1222 | mn_i = len(s) |
| 1223 | for left_, right_ in (('(/', '/)'), |
| 1224 | '()', |
| 1225 | '{}', # to support C literal structs |
| 1226 | '[]'): |
| 1227 | i = s.find(left_) |
| 1228 | if i == -1: |
| 1229 | continue |
| 1230 | if i < mn_i: |
| 1231 | mn_i = i |
| 1232 | left, right = left_, right_ |
| 1233 | |
| 1234 | if left is None: |
| 1235 | return s, {} |
| 1236 | |
| 1237 | i = mn_i |
| 1238 | j = s.find(right, i) |
| 1239 | if j == -1: |
| 1240 | raise ValueError(f'Mismatch of {left + right} parenthesis in {s!r}') |
| 1241 | |
| 1242 | while s.count(left, i + 1, j) != s.count(right, i + 1, j): |
| 1243 | j = s.find(right, j + 1) |
| 1244 | if j == -1: |
| 1245 | raise ValueError(f'Mismatch of {left + right} parenthesis in {s!r}') |
| 1246 | |
| 1247 | p = {'(': 'ROUND', '[': 'SQUARE', '{': 'CURLY', '(/': 'ROUNDDIV'}[left] |
| 1248 | |
| 1249 | k = f'@__f2py_PARENTHESIS_{p}_{COUNTER.__next__()}@' |
| 1250 | v = s[i + len(left):j] |
| 1251 | r, d = replace_parenthesis(s[j + len(right):]) |
| 1252 | d[k] = v |
| 1253 | return s[:i] + k + r, d |
| 1254 | |
| 1255 | |
| 1256 | def _get_parenthesis_kind(s): |