Pointers for sweet.js
ptr test = 5;
console.log(acc test);
function process(testPtr) {
acc testPtr = acc testPtr + 2;
}
process(test);
console.log(acc test);
var realTest = acc test;
console.log(realTest);
syntax ptr = function(ctx) { | |
let ident = ctx.next().value; | |
ctx.next(); // eat `=` | |
let init = ctx.expand('expr').value; | |
let varName = ""; | |
let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; | |
for(let i=0; i < 20; i++) | |
varName += possible.charAt(Math.floor(Math.random() * possible.length)); | |
let dummy = #`dummy`.get(0); | |
return #` | |
let ${dummy.fromIdentifier(varName)} = ${init} | |
let ${ident} = function(val) { | |
if (arguments.length > 0) {${dummy.fromIdentifier(varName)} = val; return;} | |
return ${dummy.fromIdentifier(varName)}; | |
}` | |
} | |
syntax acc = function(ctx) { | |
let pointer = ctx.next().value; | |
let equals = ctx.next().value; | |
let value = ctx.expand('expr').value; | |
let dummy = #`dummy`.get(0); | |
if (equals === null || value === null || (equals.val() === ";" && value === null)) { | |
return #`${dummy.fromIdentifier(pointer.val())}()`; | |
} else if (equals.val() === '+' || equals.val() === '*' || equals.val() === '-' || equals.val() === '/' || equals.val() === '%' || (equals.val() === ";" && value !== null)) { | |
return #`${dummy.fromIdentifier(pointer.val())}() ${equals} ${value}`; | |
} else if (equals.val() !== "=") { | |
throw new TypeError("Operators other than '=' unsupported! Line: " + pointer.lineNumber() + " Operator: " + equals.val()); | |
return #``; | |
} else if (pointer === null || !pointer.isIdentifier()) { | |
throw new TypeError("Must specify pointer! Line: " + pointer.lineNumber()); | |
return #``; | |
} else { | |
return #`${dummy.fromIdentifier(pointer.val())}(${value})`; | |
} | |
} |