Scope (3)
Use the second argument of ASTPattern to match node metadata:
Match only nodes that start on a particular line:
Bind parts of metadata in pattern names:
Applications (2)
Parse a Wolfram Language file to get an abstract syntax tree:
Extract all nodes from the AST that correspond to a pattern:
Convert to expressions:
Extract source positions:
Extract the corresponding parts of the file as strings:
Create a CodeCases function:
Compare to string matching:
This incorrectly matched part of the usage message as code:
When matching against the AST, there's no need to account for different types of input syntax:
Properties and Relations (4)
The single-argument form of ASTPattern is effectively invisible to an outer ASTPattern:
The two-argument form inserts the corresponding metadata patterns:
Get an AST node corresponding to a simple expression:
For simple patterns, the performance of matching an ASTPattern is comparable to normal pattern matching:
Matching patterns that require evaluation typically incur significant cost as an ASTPattern:
Compare to normal pattern matching:
Some pattern tests allow for optimized patterns:
This will only work for certain pattern tests that appear literally:
Pattern bindings that stay within ASTPattern correspond to expressions:
Once a value passes outside of ASTPattern, the binding corresponds to the AST node:
Note that all instances of the pattern symbol appear below ASTPattern in this case:
In this case, there is an x that's "lifted" out of the ASTPattern, which is why it appears as an AST node:
Possible Issues (4)
ASTPattern cannot generalize to all possible WL patterns:
In this case, the pattern binding prevents matching, since the metadata will always be different between nodes:
Without any repeated binding this pattern will match:
Not all raw patterns are supported by ASTPattern:
Unsupported patterns are represented verbatim:
ASTPattern ignores the Unevaluated wrapper:
Use HoldPattern instead:
ASTPattern must evaluate in order to create the desired pattern, so it should not be wrapped in HoldPattern:
Use HoldPattern within ASTPattern instead: