Skip to content

Instantly share code, notes, and snippets.

@leo60228
Last active March 26, 2017 01:34
Show Gist options
  • Save leo60228/cbb02854b6481b4809500cb6c8fc9e44 to your computer and use it in GitHub Desktop.
Save leo60228/cbb02854b6481b4809500cb6c8fc9e44 to your computer and use it in GitHub Desktop.
Pointers for sweet.js

Pointers for sweet.js

Usage

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})`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment