Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeGuard for all nodes with a .expression? #187

Closed
gregjacobs opened this issue Dec 20, 2017 · 3 comments
Closed

TypeGuard for all nodes with a .expression? #187

gregjacobs opened this issue Dec 20, 2017 · 3 comments

Comments

@gregjacobs
Copy link

Hey David,

Was just working on some AST transforms, and I noticed a pattern that I want to try to take advantage of.

I'm basically trying to replace identifiers such as myVar with this.myVar. I noticed that I basically need to find compiler nodes which have an expression property that contain an Identifier node.

For example, CallExpression, PropertyAccessExpression, IfStatement, and probably many more have an expression property. Was thinking I could transform them with something like this:

// ...traversing nodes
if( TypeGuards.isExpressionableNode( node ) ) {  // <-- does this name make sense?
    if( TypeGuards.isIdentifier( node.getExpression() ) { 
        node.getExpression().replaceWithText( 'this.' + node.getExpression().getText() );
    }
}

Btw, any general thoughts on this? Is there a better way to go about this?

@dsherret
Copy link
Owner

dsherret commented Jan 9, 2018

You're right, this is very common. I'll make all the nodes that have this an ExpressionableNode. Then yes, you will be able to just do TypeGuards.isExpressionableNode(node)

dsherret added a commit that referenced this issue Jan 14, 2018
This can be used to tell if a node has a .getExpression function or not.
@dsherret
Copy link
Owner

dsherret commented Jan 14, 2018

@gregjacobs I added TypeGuards.hasExpression. This will return true when the node has a .getExpression() method and that method returns a node.

The second check is necessary because .getExpression() could possibly return undefined for certain statements like ReturnStatement (return 5; vs return;) and YieldStatement (yield 5; vs yield;).

I'm running a new release now.

@gregjacobs
Copy link
Author

Awesome, thanks man!

dsherret added a commit that referenced this issue May 14, 2019
This can be used to tell if a node has a .getExpression function or not.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants