@rushstack/tree-pattern
0.3.4 • Public • PublishedThis is a simple, fast pattern matcher for JavaScript tree structures. It was designed for ESLint rules andtransforms that match parse trees such as produced byEsprima. However, it can be usedwith any JSON-like data structure.
Suppose we are fixing up obsoletePromise
calls, and we need to match an input like this:
Promise.fulfilled(123);
The parsed subtree looks like this:
{"type":"Program","body":[{"type":"ExpressionStatement","expression":{// <---- expressionNode"type":"CallExpression","callee":{"type":"MemberExpression","object":{"type":"Identifier","name":"Promise"},"property":{"type":"Identifier","name":"fulfilled"},"computed":false,"optional":false},"arguments":[{"type":"Literal","value":123,"raw":"123"}],"optional":false}}],"sourceType":"module"}
Throwing away the details that we don't care about, we can specify a pattern expression with the partsthat need to be present:
constpattern1:TreePattern=newTreePattern({type:'CallExpression',callee:{type:'MemberExpression',object:{type:'Identifier',name:'Promise'},property:{type:'Identifier',name:'fulfilled'},computed:false}});
Then when our visitor encounters anExpressionStatement
, we can match theexpressionNode
like this:
if(pattern1.match(expressionNode)){console.log('Success!');}
Suppose we want to generalize this to match any API such asPromise.thing(123);
orPromise.otherThing(123);
.We can use a "tag" to extract the matching identifier:
constpattern2:TreePattern=newTreePattern({type:'CallExpression',callee:{type:'MemberExpression',object:{type:'Identifier',name:'Promise'},property:TreePattern.tag('promiseMethod',{type:'Identifier'}),computed:false}});
On a successful match, the taggedpromiseMethod
subtree can be retrieved like this:
interfaceIMyCaptures{// Captures the "promiseMethod" tag specified using TreePattern.tag()promiseMethod?:{name?:string};// <--- substitute your real AST interface here}constcaptures:IMyCaptures={};if(pattern2.match(node,captures)){// Prints: "Matched fulfilled"console.log('Matched '+captures?.promiseMethod?.name);}
TheoneOf
API enables you to write patterns that match alternative subtrees.
constpattern3:TreePattern=newTreePattern({animal:TreePattern.oneOf([{kind:'dog',bark:'loud'},{kind:'cat',meow:'quiet'}])});if(pattern3.match({animal:{kind:'dog',bark:'loud'}})){console.log('I can match dog.');}if(pattern3.match({animal:{kind:'cat',meow:'quiet'}})){console.log('I can match cat, too.');}
For example, maybe we want to matchPromise['fulfilled'](123);
as well asPromise.fulfilled(123);
.If the structure of the expressions is similar enough,TreePattern.oneOf
avoids having to create twoseparate patterns.
- CHANGELOG.md - Findout what's new in the latest version
- API Reference
@rushstack/tree-pattern
is part of theRush Stack family of projects.
Readme
Keywords
nonePackage Sidebar
Install
npm i @rushstack/tree-pattern
Repository
Weekly Downloads
74,763
Version
0.3.4
License
MIT
Unpacked Size
42.1 kB
Total Files
18