bebraw
5/17/2011 - 7:12 AM

Operator overloading question (cloning).

Operator overloading question (cloning).

"use strict"; "use restrict";

var Shaper = Shaper || require("shaper.js") || Shaper;

Shaper("op-overloading", function(root) {
    var prefix = 'ops.';
    var ops = {
        '+': 'add',
        '-': 'sub',
        '/': 'div',
        '*': 'mul'
    };
    var exprs = function() {
        var ret = [];
        
        for(var op in ops) {
            var func = ops[op];
            
            ret.push({
                from: Shaper.parseExpression('$ ' + op + ' $'),
                to: Shaper.parseExpression(prefix + func + '($, $)')
            });
        }
        
        return ret;
    }();
    
    return Shaper.traverseTree(root, {
        pre: function(node, ref) {
            for(var i = 0; i < exprs.length; i++) {
                var expr = exprs[i];
                
                if(Shaper.match(expr.from, node)) {
                    var call = expr.to;

                    // XXXXX: need to clone call somehow since it mutates the original object now
                    // Is there some nice way to do this?
                    Shaper.replace(call, node.children[0], node.children[1]);
                    Shaper.cloneComments(call, node);

                    return ref.set(call);
                }
            }       
        }
    });
});