Recently, I was working on a project of detecting plagiarism in python code. I learned an interesting method from an literature (https://www.researchgate.net/publication/221554617). In this article, authors created a characteristic vector which is a numerical approximation of a particular sub-tree. Each vector consists of the sum of the node’s children’s vectors.
characteristic vectors with an AST
To do this, I need to create a 8-length list for each sub-tree in order to record information. The problem is that there must be a correspondence between the list and the subtree, otherwise it will be meaningless. Using a dictionary may not be a good way because I need to traverse the tree.
Ideally I want to get a new storage structure like newnode which has attributes like below:
#Points to the current node(or sub-tree)
newnode.node
#The list corresponding to the node
newnode.vector
Here is my attempt (you can ignore if you want):
import ast
import numpy as np
class NewNode:
def __init__(self, node):
self.node = node
self.vector = np.zeros(8)
class Operation(ast.NodeTransformer):
def generic_visit(self, node):
ast.NodeTransformer.generic_visit(self, node)
new_node = NewNode(node)
print(type(node).__name__)
# the code below is an example of record ast.Store node-type
if isinstance(new_node.node, ast.Store):
new_node.vector[5] += 1
source = \
"""
a = 10
b = "test"
print(a)
"""
node = ast.parse(source)
k = Operation()
k.generic_visit(node)