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
(typePosition
): the starting position of the element in the ASTend
(typePosition
): 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 theASTElement
type. As the element checked is set toFunctionCall
, thenode
for our rule will be a typeFunctionCall
. - the
filename
where the code is located (a string). If a user edits the filefoo/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 ofnodeOrPattern
is aFunctionCall
object - If the element type-checked is
If Condition
, the value ofnodeOrPattern
is aIfCondition
- If the element type-checked is
For Loop
, the value ofnodeOrPattern
is aForStatement
object - If the element type-checked is
Function Definition
, the value ofnodeOrPattern
is aFunctionDefinition
object - If the element type-checked is
Try Block
, the value ofnodeOrPattern
is aTryBlock
object - If the element type-checked is
Import
, the value ofnodeOrPattern
is anImport
or anImportFrom
- If the element type-checked is
Assignment
, the value ofnodeOrPattern
is aAssignment
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
- Changing Python format string by f-string
- Check that requests have a timeout parameter
- Avoid
shell=True
when using thesubprocess
module