|
| 1 | +#------------------------------------------------------------------------------- |
| 2 | +# identifierreplace.py |
| 3 | +# |
| 4 | +# Replaces identifier names based on a given dict |
| 5 | +# |
| 6 | +# Copyright (C) 2015, Shinya Takamaeda-Yamazaki |
| 7 | +# License: Apache 2.0 |
| 8 | +#------------------------------------------------------------------------------- |
| 9 | + |
| 10 | +import sys |
| 11 | +import os |
| 12 | + |
| 13 | +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) ) |
| 14 | + |
| 15 | +import pyverilog.vparser.ast as vast |
| 16 | +from pyverilog.vparser.ast import Node |
| 17 | + |
| 18 | +def replaceIdentifiers(node, ids): |
| 19 | + v = IdentifierReplace(ids) |
| 20 | + return v.visit(node) |
| 21 | + |
| 22 | +def ischild(node, attr): |
| 23 | + if not isinstance(node, Node): return False |
| 24 | + excludes = ('coord', 'attr_names',) |
| 25 | + if attr.startswith('__'): return False |
| 26 | + if attr in excludes: return False |
| 27 | + attr_names = getattr(node, 'attr_names') |
| 28 | + if attr in attr_names: return False |
| 29 | + attr_test = getattr(node, attr) |
| 30 | + if hasattr(attr_test, '__call__'): return False |
| 31 | + return True |
| 32 | + |
| 33 | +def children_items(node): |
| 34 | + children = [ attr for attr in dir(node) if ischild(node, attr) ] |
| 35 | + ret = [] |
| 36 | + for c in children: |
| 37 | + ret.append( (c, getattr(node, c)) ) |
| 38 | + return ret |
| 39 | + |
| 40 | +class IdentifierReplace(object): |
| 41 | + def __init__(self, ids): |
| 42 | + self.ids = ids |
| 43 | + |
| 44 | + def visit(self, node): |
| 45 | + method = 'visit_' + node.__class__.__name__ |
| 46 | + visitor = getattr(self, method, self.generic_visit) |
| 47 | + ret = visitor(node) |
| 48 | + if ret is None: return node |
| 49 | + return ret |
| 50 | + |
| 51 | + def generic_visit(self, node): |
| 52 | + for name, child in children_items(node): |
| 53 | + ret = None |
| 54 | + if child is None: continue |
| 55 | + if (isinstance(child, list) or isinstance(child, tuple)): |
| 56 | + r = [] |
| 57 | + for c in child: |
| 58 | + r.append( self.visit(c) ) |
| 59 | + ret = tuple(r) |
| 60 | + else: |
| 61 | + ret = self.visit(child) |
| 62 | + setattr(node, name, ret) |
| 63 | + return node |
| 64 | + |
| 65 | + def visit_Identifier(self, node): |
| 66 | + if node.name in self.ids: |
| 67 | + return vast.Identifier(self.ids[node.name]) |
| 68 | + return node |
| 69 | + |
| 70 | +if __name__ == '__main__': |
| 71 | + a = vast.Identifier('a') |
| 72 | + b = vast.Identifier('b') |
| 73 | + c = vast.Plus(a, b) |
| 74 | + |
| 75 | + ids = {'a' : 'x', |
| 76 | + 'b' : 'y'} |
| 77 | + |
| 78 | + d = replaceIdentifiers(c, ids) |
| 79 | + print(d) |
0 commit comments