Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
debug(lambda: 'Initial ast:\n{}'.format(dump(tree)))
tree = ast.parse(code, path)
debug(lambda: 'Initial ast:\n{}'.format(dump(tree)))
for transformer in transformers:
if transformer.target < target:
debug(lambda: 'Skip transformer "{}"'.format(transformer.__name__))
continue
debug(lambda: 'Use transformer "{}"'.format(transformer.__name__))
working_tree = deepcopy(tree)
try:
result = transformer.transform(working_tree)
except:
raise TransformationError(path, transformer,
dump(tree), format_exc())
if not result.tree_changed:
debug(lambda: 'Tree not changed')
continue
tree = working_tree
debug(lambda: 'Tree changed:\n{}'.format(dump(tree)))
dependencies.extend(result.dependencies)
try:
code = unparse(tree)
debug(lambda: 'Code changed:\n{}'.format(code))
except:
raise TransformationError(path, transformer,
dump(tree), format_exc())
debug(lambda: 'Tree changed:\n{}'.format(dump(tree)))
dependencies.extend(result.dependencies)
# bug = BUG_NAME_EXPR
# bug = BUG_ATTR_BASE
# bug = BUG_FUNCT
# Mutation here
done, lineno, col = mutate(tree, bug)
if done:
print(f"Chose to mutate {target} out of {len(targets)} targets")
print(f"Bug chosen: {BUG_STR[bug]}")
print(f"Mutation happened on line {lineno}, col {col}")
# Post-mutation AST dump
if not opts.no_astdump:
with open( target + ".post-ast", "w" ) as fd:
fd.write(astunparse.dump(tree))
# Write mutated source code to a temporary file
with open( target + ".tmp", "w" ) as fd:
fd.write(astunparse.unparse(tree))
# Rename the tmp file to overwrite the target
if not opts.no_overwrite:
os.rename( target + ".tmp", target )
print()
break
n_tried += 1
dump(tree), format_exc())
if not result.tree_changed:
debug(lambda: 'Tree not changed')
continue
tree = working_tree
debug(lambda: 'Tree changed:\n{}'.format(dump(tree)))
dependencies.extend(result.dependencies)
try:
code = unparse(tree)
debug(lambda: 'Code changed:\n{}'.format(code))
except:
raise TransformationError(path, transformer,
dump(tree), format_exc())
return fix_code(code), dependencies
# Loop until a valid bug is generated
while True:
if n_tried > 100:
print(f"Failed to produce a bug after 100 trials!")
break
target = targets[randint(0, len(targets)-1)]
with open( target, "r" ) as fd:
tree = ast.parse(fd.read())
# Pre-mutation AST dump
if not opts.no_astdump:
with open( target + ".pre-ast", "w" ) as fd:
fd.write(astunparse.dump(tree))
# Randomly pick a bug
if not opts.functional:
bug = randint(0, BUG_SENTINEL-1)
else:
bug = BUG_FUNCT
# bug = BUG_BITWIDTH
# bug = BUG_COMP_ATTR
# bug = BUG_PORT_DIR
# bug = BUG_NAME_EXPR
# bug = BUG_ATTR_BASE
# bug = BUG_FUNCT
# Mutation here
done, lineno, col = mutate(tree, bug)
def print_dumped(source):
"""Pretty print the AST"""
if isinstance(source, str):
module = extast.parse(source)
if len(module.body) == 1:
node = module.body[0]
else:
node = module
else:
node = source
print(astunparse.dump(node))