Return code, with new name, expressions, and replacements applied.
(self, names, version, shader)
| 414 | return template_vars |
| 415 | |
| 416 | def _get_replaced_code(self, names, version, shader): |
| 417 | """Return code, with new name, expressions, and replacements applied.""" |
| 418 | code = self._code |
| 419 | |
| 420 | # Modify name |
| 421 | fname = names[self] |
| 422 | code = code.replace(" " + self.name + "(", " " + fname + "(") |
| 423 | |
| 424 | # Apply string replacements first -- these may contain $placeholders |
| 425 | for key, val in self._replacements.items(): |
| 426 | code = code.replace(key, val) |
| 427 | |
| 428 | # Apply assignments to the end of the function |
| 429 | |
| 430 | # Collect post lines |
| 431 | post_lines = [] |
| 432 | for key, val in self._assignments.items(): |
| 433 | if isinstance(key, Variable): |
| 434 | key = names[key] |
| 435 | if isinstance(val, ShaderObject): |
| 436 | val = val.expression(names) |
| 437 | line = ' %s = %s;' % (key, val) |
| 438 | post_lines.append(line) |
| 439 | |
| 440 | # Add a default $post placeholder if needed |
| 441 | if 'post' in self._expressions: |
| 442 | post_lines.append(' $post') |
| 443 | |
| 444 | # Apply placeholders for hooks |
| 445 | post_text = '\n'.join(post_lines) |
| 446 | if post_text: |
| 447 | post_text = '\n' + post_text + '\n' |
| 448 | code = code.rpartition('}') |
| 449 | code = code[0] + post_text + code[1] + code[2] |
| 450 | |
| 451 | # Add a default $pre placeholder if needed |
| 452 | if 'pre' in self._expressions: |
| 453 | m = re.search(fname + r'\s*\([^{]*\)\s*{', code) |
| 454 | if m is None: |
| 455 | raise RuntimeError("Cound not find beginning of function '%s'" |
| 456 | % fname) |
| 457 | ind = m.span()[1] |
| 458 | code = code[:ind] + "\n $pre\n" + code[ind:] |
| 459 | |
| 460 | # Apply template variables |
| 461 | for key, val in self._expressions.items(): |
| 462 | val = val.expression(names) |
| 463 | search = r'\$' + key + r'($|[^a-zA-Z0-9_])' |
| 464 | code = re.sub(search, val+r'\1', code) |
| 465 | |
| 466 | # Done |
| 467 | if '$' in code: |
| 468 | v = parsing.find_template_variables(code) |
| 469 | logger.warning('Unsubstituted placeholders in code: %s\n' |
| 470 | ' replacements made: %s', |
| 471 | v, list(self._expressions.keys())) |
| 472 | |
| 473 | return code + '\n' |
no test coverage detected