Permalink
Browse files

binary subterms at %a and %b, parent test that uses them now passes

  • Loading branch information...
1 parent 7fd56a8 commit 7fe2fd183e102750e3ec2717b31e5b827b58954b @substack substack committed Jun 12, 2011
Showing with 86 additions and 5 deletions.
  1. +60 −5 index.js
  2. +26 −0 test/parent.js
View
65 index.js
@@ -32,25 +32,80 @@ function wrapNode (state, cb) {
var self = {
name : ann.name,
node : node,
+ start : node[0].start,
+ end : node[0].end,
+ value : node.slice(1),
wrap : function (s) {
var subsrc = deparse(
traverse(node).map(function (x) {
if (!this.isRoot) wrapNode(this, cb)
})
);
- var src = typeof s === 'function'
- ? s(subsrc)
- : s.toString().replace(/%s/g, function () {
+ if (self.name === 'binary') {
+ var a = deparse(traverse(node[2]).map(function (x) {
+ if (!this.isRoot) wrapNode(this, cb)
+ }));
+ var b = deparse(traverse(node[3]).map(function (x) {
+ if (!this.isRoot) wrapNode(this, cb)
+ }));
+ }
+
+ var src = '';
+
+ if (typeof s === 'function') {
+ if (self.name === 'binary') {
+ src = s(subsrc, a, b);
+ }
+ else {
+ src = s(subsrc);
+ }
+ }
+ else {
+ src = s.toString().replace(/%s/g, function () {
return subsrc
- })
- ;
+ });
+
+ if (self.name === 'binary') {
+ src = src
+ .replace(/%a/g, function () { return a })
+ .replace(/%b/g, function () { return b })
+ ;
+ }
+ }
var expr = parse(src);
state.update(expr, true);
},
};
+ var cache = {};
+
+ if (state.isRoot) self.parent = null;
+ else Object.defineProperty(self, 'parent', {
+ get : function () {
+ if (!cache.parent) {
+ var s = state;
+ var x;
+ do {
+ s = s.parent;
+ if (s) x = wrapNode(s);
+ } while (s && !x);
+
+ cache.parent = x;
+ }
+
+ return cache.parent;
+ }
+ });
+
+ Object.defineProperty(self, 'source', {
+ get : function () {
+ if (!cache.source) cache.source = deparse(node);
+ return cache.source;
+ }
+ });
+
if (cb) cb(self);
return self;
View
26 test/parent.js
@@ -0,0 +1,26 @@
+var assert = require('assert');
+var burrito = require('burrito');
+
+exports.checkParent = function () {
+ var src = 'Math.tan(0) + Math.sin(0)';
+
+ var res = burrito.microwave(src, function (node) {
+ if (node.name === 'binary') {
+ node.wrap('%a - %b');
+ }
+ else if (node.name === 'num') {
+ assert.equal(node.parent.value[0][0], 'dot');
+
+ var fn = node.parent.value[0][2];
+ if (fn === 'sin') {
+ node.wrap('Math.PI / 2');
+ }
+ else if (fn === 'tan') {
+ node.wrap('Math.PI / 4');
+ }
+ else assert.fail('Unknown fn');
+ }
+ });
+
+ assert.equal(res, Math.tan(Math.PI / 4) - Math.sin(Math.PI / 2)); // ~ 0
+};

0 comments on commit 7fe2fd1

Please sign in to comment.