babel / notes

♬ Notes from the @Babel Team (discuss in PRs)
https://github.com/babel/notes#meetings
122 stars 16 forks source link

Plugins: Selector support for visitors #118

Open hzoo opened 4 years ago

hzoo commented 4 years ago

Writing down some idea(s):

https://eslint.org/docs/developer-guide/selectors

{
  "IfStatement > BlockStatement": function(blockStatementNode) {
    // ...your logic here
  },
}
"no-restricted-syntax": ["error", "IfStatement > :not(BlockStatement).consequent"]

Not sure if a lot of people use this, but it could be convenient for simpler transforms. ESLint uses https://github.com/estools/esquery but not sure if we can just use it or we need to change something based on the AST (ideally it would be generic enough). (also found https://github.com/phenomnomnominal/tsquery)

We sorta have something you can do with "virtual ast nodes"/"aliases" but not sure how that works.

https://github.com/babel/babel/blob/a3f00896f710a95ed38f2f9fb3a6e048148b0b98/packages/babel-traverse/src/path/lib/virtual-types.js#L80-L84

export const BlockScoped = {
  checkPath(path: NodePath): boolean {
    return t.isBlockScoped(path.node);
  },
};

Was just sorta thinking if you wanted to target an IIFE for example (give the thing a name, it's not a normal AST node), you could do this (assuming you defined what an IIFE was somewhere):

visitor: {
    IIFE(path) {
        // code here
    }
}

Could certainly add this as a feature but I would just implement this as a babel plugin for people to try out before actually adding it in? Just seems better to do it this way. Would be something like this for the input/output:

visitor: {
-    "FunctionDeclaration[params.length>3]"(path) {
-        // code
-    },
+    FunctionDeclaration(path) {
+        if (path.node.params.length > 3) {
+            // code
+        }
    }
}

I see there's also https://github.com/dfilatov/jspath

ljharb commented 4 years ago

(If you can't use esquery because the AST is different, please make a reusable babyquery package that can traverse babylon trees)