SMAT-Lab / Scalpel

Scalpel: The Python Static Analysis Framework
Apache License 2.0
286 stars 43 forks source link

Constant propagation class: instance variables are not covered #39

Closed simisimon closed 2 years ago

simisimon commented 2 years ago

Instance variables, as you can see in the code snippet below, are currently not covered by the constant propagation class. That is, when applying Scalpel, I cannot identify the values of self.x. However, I would expect Scalpel to be able to do this.

class Test:
    def __init__(self):
        self.x = 2

    def change_x(self):
        self.x = 5

There are two parts in the source code that need to be modified. First, Scalpel needs to cover the ast.Attribute object. https://github.com/SMAT-Lab/Scalpel/blob/2ba6cab3c7d613ed6e2dfe936f98b3b759a2347c/scalpel/SSA/const.py#L195-L197 Here, we just need to add two lines:

left_name = ast.unparse(stmt.targets[0])
const_dict[left_name] = stmt.value  

Second, we need to modify the last code block of the method get_stmt_idents_ctx. As the name and attr attribute of ast.Attribute objects are usually connected by a dot, we need to remove "." in r["name"] in the first if condition (Line 316). https://github.com/SMAT-Lab/Scalpel/blob/2ba6cab3c7d613ed6e2dfe936f98b3b759a2347c/scalpel/SSA/const.py#L314-L324

With these two changes, Scalpel is able to identify all the values for self.x.

Jarvx commented 2 years ago

Thanks for raising this, this was the todo comment for ourselves. In fact, the attribute name is now supported in terms of variable extraction . In the initial stage , I removed the dotted name because we will provide a better way to model attribute object. At the moment, we will support this one using its simple string name.