Last active
November 21, 2023 12:54
-
-
Save ritwickdey/26457775a9ade8cbca528a7f30f6f8fd to your computer and use it in GitHub Desktop.
Infinite loop detection via AST transformation
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
export default function (babel) { | |
const { types: t } = babel; | |
const infiniteLoopDetector = babel.parse(` | |
function __infiniteLoopDetector() { | |
loopdetector.count += 1; | |
if(loopdetector.count > 10000) { | |
throw new Error("Infinte loop detected.") | |
} | |
} | |
function __infiniteLoopDetector__reset() { | |
loopdetector.count = 0; | |
} | |
`); | |
//Todo: Need diff approch; | |
let isGlobalFNsAreAdded = false; | |
function injectDetectorIntoLoop(path) { | |
const detectorFn = babel.parse(` | |
/** Injected loop detector*/ | |
__infiniteLoopDetector() | |
`); | |
const resetFn = babel.parse(` | |
/** Reset Counter before loop start*/ | |
__infiniteLoopDetector__reset() | |
`); | |
path.node.body.body.unshift(detectorFn); | |
const thisIndex = path.parent.body.findIndex((e) => e === path.node); | |
path.parent.body.splice(thisIndex, 0, resetFn); | |
} | |
return { | |
name: "ast-transform", // not required | |
visitor: { | |
Program(path) { | |
if (isGlobalFNsAreAdded) return; | |
path.node.body.unshift(infiniteLoopDetector); | |
isGlobalFNsAreAdded = true; | |
}, | |
ForStatement(path) { | |
injectDetectorIntoLoop(path); | |
}, | |
WhileStatement(path) { | |
injectDetectorIntoLoop(path); | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DEMO: https://astexplorer.net/#/gist/61b6f2e1bd64913c5a3502b80fbb571b/5ec1f4ccf90aba38cb4bdb6acf0d4d5969cce2ce
Input: file1.js
Output: file1.transpiled.js