Skip to main content

AST Rules for Python

info

If you are starting with Rosie and want to start writing rules, follow the Python AST rule tutorial first.

Python AST Rules

An AST rule is a rule that browses the AST and reports an error (along with a potential fix).

Every single node in the AST inherits the ASTElement type has the following properties:

  • astType (type string): the type of the element. The value depends in what element you are on.
  • start (type Position): the starting position of the element in the AST
  • end (type Position): the starting position of the element in the AST

The visit function

The rule code has a visit function that is the entrypoint of your rule.

function visit(node, filename, code) {
// code
}

It has the following parameter:

  • the node you rule matches on. The exact type of this argument depends on the element type being checked. All types inherit the ASTElement type. As the element checked is set to FunctionCall, the node for our rule will be a type FunctionCall.
  • the filename where the code is located (a string). If a user edits the file foo/bar.py in VS Code, this is the value that will be passed to the function.
  • the code being checked (a string)

Value of the node parameter

The value of the node parameter depends on the element type checked:

  • If the element type-checked is Function Call, the value of nodeOrPattern is a FunctionCall object
  • If the element type-checked is If Condition, the value of nodeOrPattern is a IfCondition
  • If the element type-checked is For Loop, the value of nodeOrPattern is a ForStatement object
  • If the element type-checked is Function Definition, the value of nodeOrPattern is a FunctionDefinition object
  • If the element type-checked is Try Block, the value of nodeOrPattern is a TryBlock object
  • If the element type-checked is Import, the value of nodeOrPattern is an Import or an ImportFrom
  • If the element type-checked is Assignment, the value of nodeOrPattern is a Assignment object

Examples of Python AST Rules

Browse the Codiga Hub to find interesting rulesets to reuse. The following rules are available publicly and can be used as a starter. We list the rules by the element checked type.

Function Call

For loop

If condition

Try Block

Function Definition