2 import {isArray} from '../utils';
7 /* istanbul ignore next */
8 if (typeof define !== 'function' || !define.amd) {
9 // We don't support this in AMD environments. For these environments, we asusme that
10 // they are running on the browser and thus have no need for the source-map library.
11 let SourceMap = require('source-map');
12 SourceNode = SourceMap.SourceNode;
18 /* istanbul ignore if: tested but not covered in istanbul due to dist build */
20 SourceNode = function(line, column, srcFile, chunks) {
26 /* istanbul ignore next */
27 SourceNode.prototype = {
28 add: function(chunks) {
29 if (isArray(chunks)) {
30 chunks = chunks.join('');
34 prepend: function(chunks) {
35 if (isArray(chunks)) {
36 chunks = chunks.join('');
38 this.src = chunks + this.src;
40 toStringWithSourceMap: function() {
41 return {code: this.toString()};
43 toString: function() {
50 function castChunk(chunk, codeGen, loc) {
54 for (let i = 0, len = chunk.length; i < len; i++) {
55 ret.push(codeGen.wrap(chunk[i], loc));
58 } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
59 // Handle primitives that the SourceNode will throw up on
66 function CodeGen(srcFile) {
67 this.srcFile = srcFile;
73 return !this.source.length;
75 prepend: function(source, loc) {
76 this.source.unshift(this.wrap(source, loc));
78 push: function(source, loc) {
79 this.source.push(this.wrap(source, loc));
83 let source = this.empty();
84 this.each(function(line) {
85 source.add([' ', line, '\n']);
90 each: function(iter) {
91 for (let i = 0, len = this.source.length; i < len; i++) {
97 let loc = this.currentLocation || {start: {}};
98 return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
100 wrap: function(chunk, loc = this.currentLocation || {start: {}}) {
101 if (chunk instanceof SourceNode) {
105 chunk = castChunk(chunk, this, loc);
107 return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
110 functionCall: function(fn, type, params) {
111 params = this.generateList(params);
112 return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
115 quotedString: function(str) {
116 return '"' + (str + '')
117 .replace(/\\/g, '\\\\')
118 .replace(/"/g, '\\"')
119 .replace(/\n/g, '\\n')
120 .replace(/\r/g, '\\r')
121 .replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
122 .replace(/\u2029/g, '\\u2029') + '"';
125 objectLiteral: function(obj) {
128 for (let key in obj) {
129 if (obj.hasOwnProperty(key)) {
130 let value = castChunk(obj[key], this);
131 if (value !== 'undefined') {
132 pairs.push([this.quotedString(key), ':', value]);
137 let ret = this.generateList(pairs);
144 generateList: function(entries) {
145 let ret = this.empty();
147 for (let i = 0, len = entries.length; i < len; i++) {
152 ret.add(castChunk(entries[i], this));
158 generateArray: function(entries) {
159 let ret = this.generateList(entries);
167 export default CodeGen;