Skip to content

Instantly share code, notes, and snippets.

@galdosd
Created April 15, 2012 18:18
Show Gist options
  • Save galdosd/2394221 to your computer and use it in GitHub Desktop.
Save galdosd/2394221 to your computer and use it in GitHub Desktop.
compilor
{ var lastid=1; function mkid(){return 'r'+lastid++; }
function arrayP(x){ return typeof x === 'object' && Object.prototype.hasOwnProperty.apply(x,['length']);
}
function cat(){ var res=[],
args=Array.prototype.slice.apply(arguments);
while(args.length){ var snip = args.shift();
console.log(snip);
if ( snip && arrayP(snip[0]) ) {
while(snip.length){ res.push(snip.shift()); }
} else {
if(snip) res.push(snip);
}
}
return res;
}
function catall(xs){ return cat.apply(null, xs); }
function asm2txt(ops) { out=''; while(ops.length){ var op = ops.shift(); var remark=''; if(op.length>2) remark=' \t ; '+op[2]; out+= op[0]+" \t > "+op[1]+remark+"\n"; } return out; }
REFS={};
function ref(name) {
return '_'+name;
// if(!hasattr(REFS, name)) REFS[name] = mkid();
// return REFS[name];
}
function hasattr(scope, attr){
return typeof scope === 'object' && Object.prototype.hasOwnProperty.apply(scope,[attr]);}
}
start = ops:assn* { return asm2txt(catall(ops)); }
var = letters:[a-zA-Z_]+ { return letters.join(''); }
assn = v:var "=" e:expr ";" { var sym=ref(v); return cat(e, ['RES', sym, 'set '+v]); }
expr = assn / ternary / additive
additive
= left:multiplicative "+" right:additive {
var fl=mkid(); return cat(
left,
['RES', fl],
right,
[fl, 'OP'],
['ADD', 'RES']);
}
/ multiplicative
multiplicative
= left:primary "*" right:multiplicative {
var fl=mkid(); return cat(
left,
['RES', fl],
right,
[fl, 'OP'],
['MUL', 'RES']);
}
/ primary
ternary
= cond:additive "?" tval:additive ":" fval:additive {
var fval_pc=mkid(), end_pc=mkid();
return cat(
cond,
[fval_pc, 'PCUR'],
tval,
[end_pc, 'PC'],
['LABEL:', fval_pc, 'fval_pc'],
fval,
['LABEL:', end_pc, 'end_pc']
);
}
primary
= integer
/ v:var { return [ref(v), 'RES']; }
/ "(" additive:additive ")" { return additive; }
integer "integer"
= digits:[0-9]+ { return [[digits.join(""), 'RES']]; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment