|
| 1 | +/** |
| 2 | + * Created by mauricio on 5/12/15. |
| 3 | + */ |
| 4 | +'use strict'; |
| 5 | + |
| 6 | +var esprima = require('esprima'); |
| 7 | +var Interpreter = require('./Interpreter'); |
| 8 | +var extend = require('extend'); |
| 9 | + |
| 10 | +function CodeGenerator(options, defs) { |
| 11 | + this.statements = []; |
| 12 | + this.options = extend({ |
| 13 | + factory: 'ns.factory', |
| 14 | + raw: false, |
| 15 | + rawArrayExpressionElements: true, |
| 16 | + rawCallExpressionElements: false |
| 17 | + }, options); |
| 18 | + this.defs = defs || {}; |
| 19 | + this.interpreter = new Interpreter(this); |
| 20 | +} |
| 21 | + |
| 22 | +CodeGenerator.prototype.setDefs = function (defs) { |
| 23 | + this.defs = extend(this.defs, defs); |
| 24 | + return this; |
| 25 | +}; |
| 26 | + |
| 27 | +CodeGenerator.prototype.compile = function () { |
| 28 | + if (typeof this.defs.ns !== 'object') { |
| 29 | + throw Error('"ns" property needs to be defined on defs'); |
| 30 | + } |
| 31 | + |
| 32 | + // default process scope hook |
| 33 | + this.defs._processScope = this.defs._processScope || function () {}; |
| 34 | + |
| 35 | + var defsCode = Object.keys(this.defs).map(function (name) { |
| 36 | + return 'var ' + name + ' = defs["' + name + '"];'; |
| 37 | + }); |
| 38 | + |
| 39 | + // statement join |
| 40 | + if (!this.statements.length) { |
| 41 | + throw Error('there are no statements saved in this generator'); |
| 42 | + } |
| 43 | + |
| 44 | + // last statement is always a return statement |
| 45 | + this.statements[this.statements.length - 1] = 'return ' + this.statements[this.statements.length - 1]; |
| 46 | + |
| 47 | + var code = this.statements.join(';\n'); |
| 48 | + var factoryCode = |
| 49 | + defsCode.join(' ') + |
| 50 | + 'return {' + |
| 51 | + ' eval: function (scope) {' + |
| 52 | + ' scope = scope || {};' + |
| 53 | + ' _processScope(scope);' + |
| 54 | + ' ' + code + |
| 55 | + ' },' + |
| 56 | + ' code: \'' + code + '\'' + |
| 57 | + '};'; |
| 58 | + |
| 59 | + /* eslint-disable */ |
| 60 | + var factory = new Function('defs', factoryCode); |
| 61 | + /* eslint-enable */ |
| 62 | + return factory(this.defs); |
| 63 | +}; |
| 64 | + |
| 65 | +CodeGenerator.prototype.parse = function (code) { |
| 66 | + var self = this; |
| 67 | + var program = esprima.parse(code); |
| 68 | + this.statements = program.body.map(function (statement) { |
| 69 | + return self.interpreter.next(statement); |
| 70 | + }); |
| 71 | + return this; |
| 72 | +}; |
| 73 | + |
| 74 | +module.exports = CodeGenerator; |
0 commit comments