@@ -1295,6 +1295,28 @@ def __init__(self, mapper, nested=False):
12951295 self .mapper = mapper
12961296 self .nested = nested
12971297
1298+ def transform (self , o , handle , ** kwargs ):
1299+ if handle is None :
1300+ # None -> drop `o`
1301+ return None
1302+ elif isinstance (handle , Iterable ):
1303+ # Iterable -> inject `handle` into `o`'s children
1304+ if not o .children :
1305+ raise CompilationError ("Cannot inject nodes in a leaf node" )
1306+ if self .nested :
1307+ children = [self ._visit (i , ** kwargs ) for i in o .children ]
1308+ else :
1309+ children = o .children
1310+ children = (tuple (handle ) + children [0 ],) + tuple (children [1 :])
1311+ return o ._rebuild (* children , ** o .args_frozen )
1312+ else :
1313+ # Replace `o` with `handle`
1314+ if self .nested :
1315+ children = [self ._visit (i , ** kwargs ) for i in handle .children ]
1316+ return handle ._rebuild (* children , ** handle .args_frozen )
1317+ else :
1318+ return handle
1319+
12981320 def visit_object (self , o , ** kwargs ):
12991321 return o
13001322
@@ -1307,29 +1329,11 @@ def visit_tuple(self, o, **kwargs):
13071329 def visit_Node (self , o , ** kwargs ):
13081330 if o in self .mapper :
13091331 handle = self .mapper [o ]
1310- if handle is None :
1311- # None -> drop `o`
1312- return None
1313- elif isinstance (handle , Iterable ):
1314- # Iterable -> inject `handle` into `o`'s children
1315- if not o .children :
1316- raise CompilationError ("Cannot inject nodes in a leaf node" )
1317- if self .nested :
1318- children = [self ._visit (i , ** kwargs ) for i in o .children ]
1319- else :
1320- children = o .children
1321- children = (tuple (handle ) + children [0 ],) + tuple (children [1 :])
1322- return o ._rebuild (* children , ** o .args_frozen )
1323- else :
1324- # Replace `o` with `handle`
1325- if self .nested :
1326- children = [self ._visit (i , ** kwargs ) for i in handle .children ]
1327- return handle ._rebuild (* children , ** handle .args_frozen )
1328- else :
1329- return handle
1330- else :
1331- children = [self ._visit (i , ** kwargs ) for i in o .children ]
1332- return o ._rebuild (* children , ** o .args_frozen )
1332+ return self .transform (o , handle , ** kwargs )
1333+ children = [self ._visit (i , ** kwargs ) for i in o .children ]
1334+ if o ._traversable and not any (children ) and any (o .children ):
1335+ return None
1336+ return o ._rebuild (* children , ** o .args_frozen )
13331337
13341338 def visit_Operator (self , o , ** kwargs ):
13351339 raise ValueError ("Cannot apply a Transformer visitor to an Operator directly" )
0 commit comments