Last active
January 21, 2016 03:40
-
-
Save nmn/e995cce0c9fcab8a7375 to your computer and use it in GitHub Desktop.
A work in progress to make a Babel plugin that compiles VerbalExpression (nice library to create RegEx) into proper RegEx's at compile time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import VerEx from 'verbal-expressions'; | |
const eventualCallIs = name => { | |
// FOR PERF | |
const boundCheck = node => | |
node.type === 'Identifier' && node.name === name || | |
node.type === 'MemberExpression' && boundCheck(node.object) || | |
node.type === 'CallExpression' && boundCheck(node.callee) | |
return boundCheck; | |
}; | |
const allLiteral = (soFar, obj) => soFar && Boolean(obj.type.match(/Literal$/)) | |
const literal = node => | |
node.type === 'Identifier' | |
|| | |
node.type === 'CallExpression' && | |
node.arguments.reduce(allLiteral, true) && | |
literal(node.callee) | |
|| | |
node.type === 'MemberExpression' && | |
node.property.type === 'Identifier' && | |
node.object.type === 'CallExpression' && | |
literal(node.object) | |
const chainToArray = (node) => | |
node.type === 'CallExpression' ? | |
[...chainToArray(node.callee), node.arguments.map(arg => arg.value)] | |
: node.type === 'MemberExpression' ? | |
[...chainToArray(node.object), ...chainToArray(node.property)] | |
: node.type === 'Identifier' ? | |
[node.name] | |
: | |
[]; | |
const chainFn = (obj, [methodName, args, ...rest]) => | |
rest.length ? | |
chainFn(obj[methodName](...args), rest) | |
: obj[methodName](...args); | |
export default function ({types: t}) { | |
return { | |
visitor: { | |
CallExpression(path) { | |
if( path.parent.type !== 'MemberExpression' | |
&& eventualCallIs('VerEx')(path.node.callee) | |
&& literal(path.node) | |
){ | |
var x = chainToArray(path.node); | |
if(x[0] === 'VerEx' && Array.isArray(x[1]) && x[1].length === 0) { | |
let veo = chainFn(VerEx(), x.slice(2)); | |
path.replaceWithSourceString(veo.toString()); | |
} | |
} | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
...And it's done. Seems to work right.
Current limitations:
So this will not work:
http://astexplorer.net/#/TiJfAVumDf/1