class ast_pattern

An AST Pattern.

Patterns are constructs that describe ast properties, much like specialized regular expressions for ASTs. They are used for testing whether a specific ast object conforms to those properties (“matches the pattern”), particularly in traversal with an ast_iterator .

A successful match results in a dictionary mapping pattern variable names (str) to the values in the matched AST fields (analogous to regular expression “tags”).

ast_pattern Details

class cs.ast_pattern

An AST Pattern.

__init__(rhs)

Copy constructor.

Parameters:rhs (ast_pattern) – The ast_pattern to copy.
>>> v0 = ast_pattern('?foo')
>>> ast_pattern(v0)
<cs.ast_pattern ...>
__init__(pattern)

Constructor: given a string representation of a pattern, construct a corresponding ast_pattern .

Parameters:pattern (str) – The string representation of the pattern.
Raises:ast_pattern_compilation_error if pattern is not properly formed, or includes an operation on a value of incorrect type.

For more information, see AST Patterns.

>>> ast_pattern('?foo')
<cs.ast_pattern ...>
__hash__()

Get a hash value for a ast_pattern .

Return type:int
>>> mypat = ast_pattern('(?cls)')
>>> hash(mypat)
166678432
__repr__()

Get a representation of a ast_pattern object that includes information useful for debugging.

Return type:str
Returns:The string representation.
>>> v0 = ast_pattern('?foo')
>>> repr(v0)
'<cs.ast_pattern ...>'
__str__()

Get a simple string representation of a ast_pattern object.

Return type:str
Returns:The string representation.
>>> v0 = ast_pattern('?foo')
>>> str(v0)
'<cs.ast_pattern ...>'
match(node)

Check: does the specified ast match the pattern?

Parameters:node (ast) – The ast to match.
Return type:bool | {str: ast | ast_class | sfileinst | symbol | bool | float| int | str | bytes}
Returns:
  • True if if node matches the pattern without binding any pattern variables
  • A dictionary mapping pattern variable names (str) to the values in the matched AST fields if node matches the pattern and binds one or more pattern variables.
  • False if if node does not match the pattern
>>> v0 = ast_pattern('?foo')
>>> v1 = project.current()
>>> v2 = v1.lookup_symbol('foo')
>>> v3 = v2.get_type()
>>> v0.match(v3)
{'foo': <cs.ast [c:routine-type] const char* ()>}