Experiments on typescript compiler api features.
npm i https://github.com/Morglod/tsts
npm i ttypescript
Specify in tsconfig.json
"compilerOptions": {
"plugins": [
{ "transform": "tsts/src/transformers/comptime.ts", "type": "checker" }
],
}
Build with ttsc
as:
"scripts": {
"build": "ttsc"
},
Build:
npm run build
- Comptime calculations
- Recursive comptime with generic types
- Compile time communication
- Macro-like eval comptimeEval
- Overload decorator overloadOf
Example of comptime calculations:
Source:
function sum(a: number, b: number) {
return a + b;
}
function comptimeSum() {
const numbers = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
const result = comptime(() => {
return numbers.reduce((total, x) => sum(total, x), 0);
});
console.log(result);
return result;
}
comptime(() => {
return comptimeSum();
});
Result:
function comptimeSum() {
const numbers = [1, 2, 3, 4, 5, 6, 7, 8];
const result = (() => { return (36); })();
console.log(result);
return result;
}
(() => { return (36); })();
__compilerJob($compiler => {
$compiler.setMacro('__inline', ($compiler, node) => {
// inline node here
});
});
function foo(a,b) {
console.log(a + b);
}
__inline(foo, 10, 20);
Result
console.log(10 + 20);
Currently it works by code travel-extraction.
There are a lot of cases where it works bad (like for argument expression eval)
Check if function is pure (without side effects).
May be used for:
- Safe
comptime
calls - Translate TypeScript libraries to other languages (llvm)