Bug:Fix file validation issue
[vnfsdk/refrepo.git] / vnfmarket / src / main / webapp / vnfmarket / node_modules / istanbul / lib / instrumenter.js
1 /*
2  Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
3  Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
4  */
5
6 /*global esprima, escodegen, window */
7 (function (isNode) {
8     "use strict";
9     var SYNTAX,
10         nodeType,
11         ESP = isNode ? require('esprima') : esprima,
12         ESPGEN = isNode ? require('escodegen') : escodegen,  //TODO - package as dependency
13         crypto = isNode ? require('crypto') : null,
14         LEADER_WRAP = '(function () { ',
15         TRAILER_WRAP = '\n}());',
16         COMMENT_RE = /^\s*istanbul\s+ignore\s+(if|else|next)(?=\W|$)/,
17         astgen,
18         preconditions,
19         cond,
20         isArray = Array.isArray;
21
22     /* istanbul ignore if: untestable */
23     if (!isArray) {
24         isArray = function (thing) { return thing &&  Object.prototype.toString.call(thing) === '[object Array]'; };
25     }
26
27     if (!isNode) {
28         preconditions = {
29             'Could not find esprima': ESP,
30             'Could not find escodegen': ESPGEN,
31             'JSON object not in scope': JSON,
32             'Array does not implement push': [].push,
33             'Array does not implement unshift': [].unshift
34         };
35         /* istanbul ignore next: untestable */
36         for (cond in preconditions) {
37             if (preconditions.hasOwnProperty(cond)) {
38                 if (!preconditions[cond]) { throw new Error(cond); }
39             }
40         }
41     }
42
43     function generateTrackerVar(filename, omitSuffix) {
44         var hash, suffix;
45         if (crypto !== null) {
46             hash = crypto.createHash('md5');
47             hash.update(filename);
48             suffix = hash.digest('base64');
49             //trim trailing equal signs, turn identifier unsafe chars to safe ones + => _ and / => $
50             suffix = suffix.replace(new RegExp('=', 'g'), '')
51                 .replace(new RegExp('\\+', 'g'), '_')
52                 .replace(new RegExp('/', 'g'), '$');
53         } else {
54             window.__cov_seq = window.__cov_seq || 0;
55             window.__cov_seq += 1;
56             suffix = window.__cov_seq;
57         }
58         return '__cov_' + (omitSuffix ? '' : suffix);
59     }
60
61     function pushAll(ary, thing) {
62         if (!isArray(thing)) {
63             thing = [ thing ];
64         }
65         Array.prototype.push.apply(ary, thing);
66     }
67
68     SYNTAX = {
69         // keep in sync with estraverse's VisitorKeys
70         AssignmentExpression: ['left', 'right'],
71         AssignmentPattern: ['left', 'right'],
72         ArrayExpression: ['elements'],
73         ArrayPattern: ['elements'],
74         ArrowFunctionExpression: ['params', 'body'],
75         AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.
76         BlockStatement: ['body'],
77         BinaryExpression: ['left', 'right'],
78         BreakStatement: ['label'],
79         CallExpression: ['callee', 'arguments'],
80         CatchClause: ['param', 'body'],
81         ClassBody: ['body'],
82         ClassDeclaration: ['id', 'superClass', 'body'],
83         ClassExpression: ['id', 'superClass', 'body'],
84         ComprehensionBlock: ['left', 'right'],  // CAUTION: It's deferred to ES7.
85         ComprehensionExpression: ['blocks', 'filter', 'body'],  // CAUTION: It's deferred to ES7.
86         ConditionalExpression: ['test', 'consequent', 'alternate'],
87         ContinueStatement: ['label'],
88         DebuggerStatement: [],
89         DirectiveStatement: [],
90         DoWhileStatement: ['body', 'test'],
91         EmptyStatement: [],
92         ExportAllDeclaration: ['source'],
93         ExportDefaultDeclaration: ['declaration'],
94         ExportNamedDeclaration: ['declaration', 'specifiers', 'source'],
95         ExportSpecifier: ['exported', 'local'],
96         ExpressionStatement: ['expression'],
97         ForStatement: ['init', 'test', 'update', 'body'],
98         ForInStatement: ['left', 'right', 'body'],
99         ForOfStatement: ['left', 'right', 'body'],
100         FunctionDeclaration: ['id', 'params', 'body'],
101         FunctionExpression: ['id', 'params', 'body'],
102         GeneratorExpression: ['blocks', 'filter', 'body'],  // CAUTION: It's deferred to ES7.
103         Identifier: [],
104         IfStatement: ['test', 'consequent', 'alternate'],
105         ImportDeclaration: ['specifiers', 'source'],
106         ImportDefaultSpecifier: ['local'],
107         ImportNamespaceSpecifier: ['local'],
108         ImportSpecifier: ['imported', 'local'],
109         Literal: [],
110         LabeledStatement: ['label', 'body'],
111         LogicalExpression: ['left', 'right'],
112         MemberExpression: ['object', 'property'],
113         MethodDefinition: ['key', 'value'],
114         ModuleSpecifier: [],
115         NewExpression: ['callee', 'arguments'],
116         ObjectExpression: ['properties'],
117         ObjectPattern: ['properties'],
118         Program: ['body'],
119         Property: ['key', 'value'],
120         RestElement: [ 'argument' ],
121         ReturnStatement: ['argument'],
122         SequenceExpression: ['expressions'],
123         SpreadElement: ['argument'],
124         Super: [],
125         SwitchStatement: ['discriminant', 'cases'],
126         SwitchCase: ['test', 'consequent'],
127         TaggedTemplateExpression: ['tag', 'quasi'],
128         TemplateElement: [],
129         TemplateLiteral: ['quasis', 'expressions'],
130         ThisExpression: [],
131         ThrowStatement: ['argument'],
132         TryStatement: ['block', 'handler', 'finalizer'],
133         UnaryExpression: ['argument'],
134         UpdateExpression: ['argument'],
135         VariableDeclaration: ['declarations'],
136         VariableDeclarator: ['id', 'init'],
137         WhileStatement: ['test', 'body'],
138         WithStatement: ['object', 'body'],
139         YieldExpression: ['argument']
140     };
141
142     for (nodeType in SYNTAX) {
143         /* istanbul ignore else: has own property */
144         if (SYNTAX.hasOwnProperty(nodeType)) {
145             SYNTAX[nodeType] = { name: nodeType, children: SYNTAX[nodeType] };
146         }
147     }
148
149     astgen = {
150         variable: function (name) { return { type: SYNTAX.Identifier.name, name: name }; },
151         stringLiteral: function (str) { return { type: SYNTAX.Literal.name, value: String(str) }; },
152         numericLiteral: function (num) { return { type: SYNTAX.Literal.name, value: Number(num) }; },
153         statement: function (contents) { return { type: SYNTAX.ExpressionStatement.name, expression: contents }; },
154         dot: function (obj, field) { return { type: SYNTAX.MemberExpression.name, computed: false, object: obj, property: field }; },
155         subscript: function (obj, sub) { return { type: SYNTAX.MemberExpression.name, computed: true, object: obj, property: sub }; },
156         postIncrement: function (obj) { return { type: SYNTAX.UpdateExpression.name, operator: '++', prefix: false, argument: obj }; },
157         sequence: function (one, two) { return { type: SYNTAX.SequenceExpression.name, expressions: [one, two] }; },
158         returnStatement: function (expr) { return { type: SYNTAX.ReturnStatement.name, argument: expr }; }
159     };
160
161     function Walker(walkMap, preprocessor, scope, debug) {
162         this.walkMap = walkMap;
163         this.preprocessor = preprocessor;
164         this.scope = scope;
165         this.debug = debug;
166         if (this.debug) {
167             this.level = 0;
168             this.seq = true;
169         }
170     }
171
172     function defaultWalker(node, walker) {
173
174         var type = node.type,
175             preprocessor,
176             postprocessor,
177             children = SYNTAX[type],
178             // don't run generated nodes thru custom walks otherwise we will attempt to instrument the instrumentation code :)
179             applyCustomWalker = !!node.loc || node.type === SYNTAX.Program.name,
180             walkerFn = applyCustomWalker ? walker.walkMap[type] : null,
181             i,
182             j,
183             walkFnIndex,
184             childType,
185             childNode,
186             ret,
187             childArray,
188             childElement,
189             pathElement,
190             assignNode,
191             isLast;
192
193         if (!SYNTAX[type]) {
194             console.error(node);
195             console.error('Unsupported node type:' + type);
196             return;
197         }
198         children = SYNTAX[type].children;
199         /* istanbul ignore if: guard */
200         if (node.walking) { throw new Error('Infinite regress: Custom walkers may NOT call walker.apply(node)'); }
201         node.walking = true;
202
203         ret = walker.apply(node, walker.preprocessor);
204
205         preprocessor = ret.preprocessor;
206         if (preprocessor) {
207             delete ret.preprocessor;
208             ret = walker.apply(node, preprocessor);
209         }
210
211         if (isArray(walkerFn)) {
212             for (walkFnIndex = 0; walkFnIndex < walkerFn.length; walkFnIndex += 1) {
213                 isLast = walkFnIndex === walkerFn.length - 1;
214                 ret = walker.apply(ret, walkerFn[walkFnIndex]);
215                 /*istanbul ignore next: paranoid check */
216                 if (ret.type !== type && !isLast) {
217                     throw new Error('Only the last walker is allowed to change the node type: [type was: ' + type + ' ]');
218                 }
219             }
220         } else {
221             if (walkerFn) {
222                 ret = walker.apply(node, walkerFn);
223             }
224         }
225
226         for (i = 0; i < children.length; i += 1) {
227             childType = children[i];
228             childNode = node[childType];
229             if (childNode && !childNode.skipWalk) {
230                 pathElement = { node: node, property: childType };
231                 if (isArray(childNode)) {
232                     childArray = [];
233                     for (j = 0; j < childNode.length; j += 1) {
234                         childElement = childNode[j];
235                         pathElement.index = j;
236                         if (childElement) {
237                           assignNode = walker.apply(childElement, null, pathElement);
238                           if (isArray(assignNode.prepend)) {
239                               pushAll(childArray, assignNode.prepend);
240                               delete assignNode.prepend;
241                           }
242                         } else {
243                             assignNode = undefined;
244                         }
245                         pushAll(childArray, assignNode);
246                     }
247                     node[childType] = childArray;
248                 } else {
249                     assignNode = walker.apply(childNode, null, pathElement);
250                     /*istanbul ignore if: paranoid check */
251                     if (isArray(assignNode.prepend)) {
252                         throw new Error('Internal error: attempt to prepend statements in disallowed (non-array) context');
253                         /* if this should be allowed, this is how to solve it
254                         tmpNode = { type: 'BlockStatement', body: [] };
255                         pushAll(tmpNode.body, assignNode.prepend);
256                         pushAll(tmpNode.body, assignNode);
257                         node[childType] = tmpNode;
258                         delete assignNode.prepend;
259                         */
260                     } else {
261                         node[childType] = assignNode;
262                     }
263                 }
264             }
265         }
266
267         postprocessor = ret.postprocessor;
268         if (postprocessor) {
269             delete ret.postprocessor;
270             ret = walker.apply(ret, postprocessor);
271         }
272
273         delete node.walking;
274
275         return ret;
276     }
277
278     Walker.prototype = {
279         startWalk: function (node) {
280             this.path = [];
281             this.apply(node);
282         },
283
284         apply: function (node, walkFn, pathElement) {
285             var ret, i, seq, prefix;
286
287             walkFn = walkFn || defaultWalker;
288             if (this.debug) {
289                 this.seq += 1;
290                 this.level += 1;
291                 seq = this.seq;
292                 prefix = '';
293                 for (i = 0; i < this.level; i += 1) { prefix += '    '; }
294                 console.log(prefix + 'Enter (' + seq + '):' + node.type);
295             }
296             if (pathElement) { this.path.push(pathElement); }
297             ret = walkFn.call(this.scope, node, this);
298             if (pathElement) { this.path.pop(); }
299             if (this.debug) {
300                 this.level -= 1;
301                 console.log(prefix + 'Return (' + seq + '):' + node.type);
302             }
303             return ret || node;
304         },
305
306         startLineForNode: function (node) {
307             return node && node.loc && node.loc.start ? node.loc.start.line : /* istanbul ignore next: guard */ null;
308         },
309
310         ancestor: function (n) {
311             return this.path.length > n - 1 ? this.path[this.path.length - n] : /* istanbul ignore next: guard */ null;
312         },
313
314         parent: function () {
315             return this.ancestor(1);
316         },
317
318         isLabeled: function () {
319             var el = this.parent();
320             return el && el.node.type === SYNTAX.LabeledStatement.name;
321         }
322     };
323
324     /**
325      * mechanism to instrument code for coverage. It uses the `esprima` and
326      * `escodegen` libraries for JS parsing and code generation respectively.
327      *
328      * Works on `node` as well as the browser.
329      *
330      * Usage on nodejs
331      * ---------------
332      *
333      *      var instrumenter = new require('istanbul').Instrumenter(),
334      *          changed = instrumenter.instrumentSync('function meaningOfLife() { return 42; }', 'filename.js');
335      *
336      * Usage in a browser
337      * ------------------
338      *
339      * Load `esprima.js`, `escodegen.js` and `instrumenter.js` (this file) using `script` tags or other means.
340      *
341      * Create an instrumenter object as:
342      *
343      *      var instrumenter = new Instrumenter(),
344      *          changed = instrumenter.instrumentSync('function meaningOfLife() { return 42; }', 'filename.js');
345      *
346      * Aside from demonstration purposes, it is unclear why you would want to instrument code in a browser.
347      *
348      * @class Instrumenter
349      * @constructor
350      * @param {Object} options Optional. Configuration options.
351      * @param {String} [options.coverageVariable] the global variable name to use for
352      *      tracking coverage. Defaults to `__coverage__`
353      * @param {Boolean} [options.embedSource] whether to embed the source code of every
354      *      file as an array in the file coverage object for that file. Defaults to `false`
355      * @param {Boolean} [options.preserveComments] whether comments should be preserved in the output. Defaults to `false`
356      * @param {Boolean} [options.noCompact] emit readable code when set. Defaults to `false`
357      * @param {Boolean} [options.noAutoWrap] do not automatically wrap the source in
358      *      an anonymous function before covering it. By default, code is wrapped in
359      *      an anonymous function before it is parsed. This is done because
360      *      some nodejs libraries have `return` statements outside of
361      *      a function which is technically invalid Javascript and causes the parser to fail.
362      *      This construct, however, works correctly in node since module loading
363      *      is done in the context of an anonymous function.
364      *
365      * Note that the semantics of the code *returned* by the instrumenter does not change in any way.
366      * The function wrapper is "unwrapped" before the instrumented code is generated.
367      * @param {Object} [options.codeGenerationOptions] an object that is directly passed to the `escodegen`
368      *      library as configuration for code generation. The `noCompact` setting is not honored when this
369      *      option is specified
370      * @param {Boolean} [options.debug] assist in debugging. Currently, the only effect of
371      *      setting this option is a pretty-print of the coverage variable. Defaults to `false`
372      * @param {Boolean} [options.walkDebug] assist in debugging of the AST walker used by this class.
373      *
374      */
375     function Instrumenter(options) {
376         this.opts = options || {
377             debug: false,
378             walkDebug: false,
379             coverageVariable: '__coverage__',
380             codeGenerationOptions: undefined,
381             noAutoWrap: false,
382             noCompact: false,
383             embedSource: false,
384             preserveComments: false
385         };
386
387         this.walker = new Walker({
388             ArrowFunctionExpression: [ this.arrowBlockConverter ],
389             ExpressionStatement: this.coverStatement,
390             BreakStatement: this.coverStatement,
391             ContinueStatement: this.coverStatement,
392             DebuggerStatement: this.coverStatement,
393             ReturnStatement: this.coverStatement,
394             ThrowStatement: this.coverStatement,
395             TryStatement: [ this.paranoidHandlerCheck, this.coverStatement],
396             VariableDeclaration: this.coverStatement,
397             IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ],
398             ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ],
399             ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
400             ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
401             WhileStatement: [ this.loopBlockConverter, this.coverStatement ],
402             DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ],
403             SwitchStatement: [ this.coverStatement, this.switchBranchInjector ],
404             SwitchCase: [ this.switchCaseInjector ],
405             WithStatement: [ this.withBlockConverter, this.coverStatement ],
406             FunctionDeclaration: [ this.coverFunction, this.coverStatement ],
407             FunctionExpression: this.coverFunction,
408             LabeledStatement: this.coverStatement,
409             ConditionalExpression: this.conditionalBranchInjector,
410             LogicalExpression: this.logicalExpressionBranchInjector,
411             ObjectExpression: this.maybeAddType
412         }, this.extractCurrentHint, this, this.opts.walkDebug);
413
414         //unit testing purposes only
415         if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) {
416             this.omitTrackerSuffix = true;
417         }
418     }
419
420     Instrumenter.prototype = {
421         /**
422          * synchronous instrumentation method. Throws when illegal code is passed to it
423          * @method instrumentSync
424          * @param {String} code the code to be instrumented as a String
425          * @param {String} filename Optional. The name of the file from which
426          *  the code was read. A temporary filename is generated when not specified.
427          *  Not specifying a filename is only useful for unit tests and demonstrations
428          *  of this library.
429          */
430         instrumentSync: function (code, filename) {
431             var program;
432
433             //protect from users accidentally passing in a Buffer object instead
434             if (typeof code !== 'string') { throw new Error('Code must be string'); }
435             if (code.charAt(0) === '#') { //shebang, 'comment' it out, won't affect syntax tree locations for things we care about
436                 code = '//' + code;
437             }
438             if (!this.opts.noAutoWrap) {
439                 code = LEADER_WRAP + code + TRAILER_WRAP;
440             }
441             program = ESP.parse(code, {
442                 loc: true,
443                 range: true,
444                 tokens: this.opts.preserveComments,
445                 comment: true
446             });
447             if (this.opts.preserveComments) {
448                 program = ESPGEN.attachComments(program, program.comments, program.tokens);
449             }
450             if (!this.opts.noAutoWrap) {
451                 program = {
452                     type: SYNTAX.Program.name,
453                     body: program.body[0].expression.callee.body.body,
454                     comments: program.comments
455                 };
456             }
457             return this.instrumentASTSync(program, filename, code);
458         },
459         filterHints: function (comments) {
460             var ret = [],
461                 i,
462                 comment,
463                 groups;
464             if (!(comments && isArray(comments))) {
465                 return ret;
466             }
467             for (i = 0; i < comments.length; i += 1) {
468                 comment = comments[i];
469                 /* istanbul ignore else: paranoid check */
470                 if (comment && comment.value && comment.range && isArray(comment.range)) {
471                     groups = String(comment.value).match(COMMENT_RE);
472                     if (groups) {
473                         ret.push({ type: groups[1], start: comment.range[0], end: comment.range[1] });
474                     }
475                 }
476             }
477             return ret;
478         },
479         extractCurrentHint: function (node) {
480             if (!node.range) { return; }
481             var i = this.currentState.lastHintPosition + 1,
482                 hints = this.currentState.hints,
483                 nodeStart = node.range[0],
484                 hint;
485             this.currentState.currentHint = null;
486             while (i < hints.length) {
487                 hint = hints[i];
488                 if (hint.end < nodeStart) {
489                     this.currentState.currentHint = hint;
490                     this.currentState.lastHintPosition = i;
491                     i += 1;
492                 } else {
493                     break;
494                 }
495             }
496         },
497         /**
498          * synchronous instrumentation method that instruments an AST instead.
499          * @method instrumentASTSync
500          * @param {String} program the AST to be instrumented
501          * @param {String} filename Optional. The name of the file from which
502          *  the code was read. A temporary filename is generated when not specified.
503          *  Not specifying a filename is only useful for unit tests and demonstrations
504          *  of this library.
505          *  @param {String} originalCode the original code corresponding to the AST,
506          *  used for embedding the source into the coverage object
507          */
508         instrumentASTSync: function (program, filename, originalCode) {
509             var usingStrict = false,
510                 codegenOptions,
511                 generated,
512                 preamble,
513                 lineCount,
514                 i;
515             filename = filename || String(new Date().getTime()) + '.js';
516             this.sourceMap = null;
517             this.coverState = {
518                 path: filename,
519                 s: {},
520                 b: {},
521                 f: {},
522                 fnMap: {},
523                 statementMap: {},
524                 branchMap: {}
525             };
526             this.currentState = {
527                 trackerVar: generateTrackerVar(filename, this.omitTrackerSuffix),
528                 func: 0,
529                 branch: 0,
530                 variable: 0,
531                 statement: 0,
532                 hints: this.filterHints(program.comments),
533                 currentHint: null,
534                 lastHintPosition: -1,
535                 ignoring: 0
536             };
537             if (program.body && program.body.length > 0 && this.isUseStrictExpression(program.body[0])) {
538                 //nuke it
539                 program.body.shift();
540                 //and add it back at code generation time
541                 usingStrict = true;
542             }
543             this.walker.startWalk(program);
544             codegenOptions = this.opts.codeGenerationOptions || { format: { compact: !this.opts.noCompact }};
545             codegenOptions.comment = this.opts.preserveComments;
546             //console.log(JSON.stringify(program, undefined, 2));
547
548             generated = ESPGEN.generate(program, codegenOptions);
549             preamble = this.getPreamble(originalCode || '', usingStrict);
550
551             if (generated.map && generated.code) {
552                 lineCount = preamble.split(/\r\n|\r|\n/).length;
553                 // offset all the generated line numbers by the number of lines in the preamble
554                 for (i = 0; i < generated.map._mappings._array.length; i += 1) {
555                     generated.map._mappings._array[i].generatedLine += lineCount;
556                 }
557                 this.sourceMap = generated.map;
558                 generated = generated.code;
559             }
560
561             return preamble + '\n' + generated + '\n';
562         },
563         /**
564          * Callback based instrumentation. Note that this still executes synchronously in the same process tick
565          * and calls back immediately. It only provides the options for callback style error handling as
566          * opposed to a `try-catch` style and nothing more. Implemented as a wrapper over `instrumentSync`
567          *
568          * @method instrument
569          * @param {String} code the code to be instrumented as a String
570          * @param {String} filename Optional. The name of the file from which
571          *  the code was read. A temporary filename is generated when not specified.
572          *  Not specifying a filename is only useful for unit tests and demonstrations
573          *  of this library.
574          * @param {Function(err, instrumentedCode)} callback - the callback function
575          */
576         instrument: function (code, filename, callback) {
577
578             if (!callback && typeof filename === 'function') {
579                 callback = filename;
580                 filename = null;
581             }
582             try {
583                 callback(null, this.instrumentSync(code, filename));
584             } catch (ex) {
585                 callback(ex);
586             }
587         },
588         /**
589          * returns the file coverage object for the code that was instrumented
590          * just before calling this method. Note that this represents a
591          * "zero-coverage" object which is not even representative of the code
592          * being loaded in node or a browser (which would increase the statement
593          * counts for mainline code).
594          * @method lastFileCoverage
595          * @return {Object} a "zero-coverage" file coverage object for the code last instrumented
596          * by this instrumenter
597          */
598         lastFileCoverage: function () {
599             return this.coverState;
600         },
601         /**
602          * returns the source map object for the code that was instrumented
603          * just before calling this method.
604          * @method lastSourceMap
605          * @return {Object} a source map object for the code last instrumented
606          * by this instrumenter
607          */
608         lastSourceMap: function () {
609             return this.sourceMap;
610         },
611         fixColumnPositions: function (coverState) {
612             var offset = LEADER_WRAP.length,
613                 fixer = function (loc) {
614                     if (loc.start.line === 1) {
615                         loc.start.column -= offset;
616                     }
617                     if (loc.end.line === 1) {
618                         loc.end.column -= offset;
619                     }
620                 },
621                 k,
622                 obj,
623                 i,
624                 locations;
625
626             obj = coverState.statementMap;
627             for (k in obj) {
628                 /* istanbul ignore else: has own property */
629                 if (obj.hasOwnProperty(k)) { fixer(obj[k]); }
630             }
631             obj = coverState.fnMap;
632             for (k in obj) {
633                 /* istanbul ignore else: has own property */
634                 if (obj.hasOwnProperty(k)) { fixer(obj[k].loc); }
635             }
636             obj = coverState.branchMap;
637             for (k in obj) {
638                 /* istanbul ignore else: has own property */
639                 if (obj.hasOwnProperty(k)) {
640                     locations = obj[k].locations;
641                     for (i = 0; i < locations.length; i += 1) {
642                         fixer(locations[i]);
643                     }
644                 }
645             }
646         },
647
648         getPreamble: function (sourceCode, emitUseStrict) {
649             var varName = this.opts.coverageVariable || '__coverage__',
650                 file = this.coverState.path.replace(/\\/g, '\\\\'),
651                 tracker = this.currentState.trackerVar,
652                 coverState,
653                 strictLine = emitUseStrict ? '"use strict";' : '',
654                 // return replacements using the function to ensure that the replacement is
655                 // treated like a dumb string and not as a string with RE replacement patterns
656                 replacer = function (s) {
657                     return function () { return s; };
658                 },
659                 code;
660             if (!this.opts.noAutoWrap) {
661                 this.fixColumnPositions(this.coverState);
662             }
663             if (this.opts.embedSource) {
664                 this.coverState.code = sourceCode.split(/(?:\r?\n)|\r/);
665             }
666             coverState = this.opts.debug ? JSON.stringify(this.coverState, undefined, 4) : JSON.stringify(this.coverState);
667             code = [
668                 "%STRICT%",
669                 "var %VAR% = (Function('return this'))();",
670                 "if (!%VAR%.%GLOBAL%) { %VAR%.%GLOBAL% = {}; }",
671                 "%VAR% = %VAR%.%GLOBAL%;",
672                 "if (!(%VAR%['%FILE%'])) {",
673                 "   %VAR%['%FILE%'] = %OBJECT%;",
674                 "}",
675                 "%VAR% = %VAR%['%FILE%'];"
676             ].join("\n")
677                 .replace(/%STRICT%/g, replacer(strictLine))
678                 .replace(/%VAR%/g, replacer(tracker))
679                 .replace(/%GLOBAL%/g, replacer(varName))
680                 .replace(/%FILE%/g, replacer(file))
681                 .replace(/%OBJECT%/g, replacer(coverState));
682             return code;
683         },
684
685         startIgnore: function () {
686             this.currentState.ignoring += 1;
687         },
688
689         endIgnore: function () {
690             this.currentState.ignoring -= 1;
691         },
692
693         convertToBlock: function (node) {
694             if (!node) {
695                 return { type: 'BlockStatement', body: [] };
696             } else if (node.type === 'BlockStatement') {
697                 return node;
698             } else {
699                 return { type: 'BlockStatement', body: [ node ] };
700             }
701         },
702
703         arrowBlockConverter: function (node) {
704             var retStatement;
705             if (node.expression) { // turn expression nodes into a block with a return statement
706                 retStatement = astgen.returnStatement(node.body);
707                 // ensure the generated return statement is covered
708                 retStatement.loc = node.body.loc;
709                 node.body = this.convertToBlock(retStatement);
710                 node.expression = false;
711             }
712         },
713
714         paranoidHandlerCheck: function (node) {
715             // if someone is using an older esprima on the browser
716             // convert handlers array to single handler attribute
717             // containing its first element
718             /* istanbul ignore next */
719             if (!node.handler && node.handlers) {
720                 node.handler = node.handlers[0];
721             }
722         },
723
724         ifBlockConverter: function (node) {
725             node.consequent = this.convertToBlock(node.consequent);
726             node.alternate = this.convertToBlock(node.alternate);
727         },
728
729         loopBlockConverter: function (node) {
730             node.body = this.convertToBlock(node.body);
731         },
732
733         withBlockConverter: function (node) {
734             node.body = this.convertToBlock(node.body);
735         },
736
737         statementName: function (location, initValue) {
738             var sName,
739                 ignoring = !!this.currentState.ignoring;
740
741             location.skip = ignoring || undefined;
742             initValue = initValue || 0;
743             this.currentState.statement += 1;
744             sName = this.currentState.statement;
745             this.coverState.statementMap[sName] = location;
746             this.coverState.s[sName] = initValue;
747             return sName;
748         },
749
750         skipInit: function (node /*, walker */) {
751             if (node.init) {
752                 node.init.skipWalk = true;
753             }
754         },
755
756         skipLeft: function (node /*, walker */) {
757             node.left.skipWalk = true;
758         },
759
760         isUseStrictExpression: function (node) {
761             return node && node.type === SYNTAX.ExpressionStatement.name &&
762                 node.expression  && node.expression.type === SYNTAX.Literal.name &&
763                 node.expression.value === 'use strict';
764         },
765
766         maybeSkipNode: function (node, type) {
767             var alreadyIgnoring = !!this.currentState.ignoring,
768                 hint = this.currentState.currentHint,
769                 ignoreThis = !alreadyIgnoring && hint && hint.type === type;
770
771             if (ignoreThis) {
772                 this.startIgnore();
773                 node.postprocessor = this.endIgnore;
774                 return true;
775             }
776             return false;
777         },
778
779         coverStatement: function (node, walker) {
780             var sName,
781                 incrStatementCount,
782                 grandParent;
783
784             this.maybeSkipNode(node, 'next');
785
786             if (this.isUseStrictExpression(node)) {
787                 grandParent = walker.ancestor(2);
788                 /* istanbul ignore else: difficult to test */
789                 if (grandParent) {
790                     if ((grandParent.node.type === SYNTAX.FunctionExpression.name ||
791                         grandParent.node.type === SYNTAX.FunctionDeclaration.name)  &&
792                         walker.parent().node.body[0] === node) {
793                         return;
794                     }
795                 }
796             }
797             if (node.type === SYNTAX.FunctionDeclaration.name) {
798                 sName = this.statementName(node.loc, 1);
799             } else {
800                 sName = this.statementName(node.loc);
801                 incrStatementCount = astgen.statement(
802                     astgen.postIncrement(
803                         astgen.subscript(
804                             astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
805                             astgen.stringLiteral(sName)
806                         )
807                     )
808                 );
809                 this.splice(incrStatementCount, node, walker);
810             }
811         },
812
813         splice: function (statements, node, walker) {
814             var targetNode = walker.isLabeled() ? walker.parent().node : node;
815             targetNode.prepend = targetNode.prepend || [];
816             pushAll(targetNode.prepend, statements);
817         },
818
819         functionName: function (node, line, location) {
820             this.currentState.func += 1;
821             var id = this.currentState.func,
822                 ignoring = !!this.currentState.ignoring,
823                 name = node.id ? node.id.name : '(anonymous_' + id + ')',
824                 clone = function (attr) {
825                     var obj = location[attr] || /* istanbul ignore next */ {};
826                     return { line: obj.line, column: obj.column };
827                 };
828             this.coverState.fnMap[id] = {
829                 name: name, line: line,
830                 loc: {
831                     start: clone('start'),
832                     end: clone('end')
833                 },
834                 skip: ignoring || undefined
835             };
836             this.coverState.f[id] = 0;
837             return id;
838         },
839
840         coverFunction: function (node, walker) {
841             var id,
842                 body = node.body,
843                 blockBody = body.body,
844                 popped;
845
846             this.maybeSkipNode(node, 'next');
847
848             id = this.functionName(node, walker.startLineForNode(node), {
849                 start: node.loc.start,
850                 end: { line: node.body.loc.start.line, column: node.body.loc.start.column }
851             });
852
853             if (blockBody.length > 0 && this.isUseStrictExpression(blockBody[0])) {
854                 popped = blockBody.shift();
855             }
856             blockBody.unshift(
857                 astgen.statement(
858                     astgen.postIncrement(
859                         astgen.subscript(
860                             astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('f')),
861                             astgen.stringLiteral(id)
862                         )
863                     )
864                 )
865             );
866             if (popped) {
867                 blockBody.unshift(popped);
868             }
869         },
870
871         branchName: function (type, startLine, pathLocations) {
872             var bName,
873                 paths = [],
874                 locations = [],
875                 i,
876                 ignoring = !!this.currentState.ignoring;
877             this.currentState.branch += 1;
878             bName = this.currentState.branch;
879             for (i = 0; i < pathLocations.length; i += 1) {
880                 pathLocations[i].skip = pathLocations[i].skip || ignoring || undefined;
881                 locations.push(pathLocations[i]);
882                 paths.push(0);
883             }
884             this.coverState.b[bName] = paths;
885             this.coverState.branchMap[bName] = { line: startLine, type: type, locations: locations };
886             return bName;
887         },
888
889         branchIncrementExprAst: function (varName, branchIndex, down) {
890             var ret = astgen.postIncrement(
891                 astgen.subscript(
892                     astgen.subscript(
893                         astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('b')),
894                         astgen.stringLiteral(varName)
895                     ),
896                     astgen.numericLiteral(branchIndex)
897                 ),
898                 down
899             );
900             return ret;
901         },
902
903         locationsForNodes: function (nodes) {
904             var ret = [],
905                 i;
906             for (i = 0; i < nodes.length; i += 1) {
907                 ret.push(nodes[i].loc);
908             }
909             return ret;
910         },
911
912         ifBranchInjector: function (node, walker) {
913             var alreadyIgnoring = !!this.currentState.ignoring,
914                 hint = this.currentState.currentHint,
915                 ignoreThen = !alreadyIgnoring && hint && hint.type === 'if',
916                 ignoreElse = !alreadyIgnoring && hint && hint.type === 'else',
917                 line = node.loc.start.line,
918                 col = node.loc.start.column,
919                 makeLoc = function () { return  { line: line, column: col }; },
920                 bName = this.branchName('if', walker.startLineForNode(node), [
921                     { start: makeLoc(), end: makeLoc(), skip: ignoreThen || undefined },
922                     { start: makeLoc(), end: makeLoc(), skip: ignoreElse || undefined }
923                 ]),
924                 thenBody = node.consequent.body,
925                 elseBody = node.alternate.body,
926                 child;
927             thenBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 0)));
928             elseBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 1)));
929             if (ignoreThen) { child = node.consequent; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
930             if (ignoreElse) { child = node.alternate; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
931         },
932
933         branchLocationFor: function (name, index) {
934             return this.coverState.branchMap[name].locations[index];
935         },
936
937         switchBranchInjector: function (node, walker) {
938             var cases = node.cases,
939                 bName,
940                 i;
941
942             if (!(cases && cases.length > 0)) {
943                 return;
944             }
945             bName = this.branchName('switch', walker.startLineForNode(node), this.locationsForNodes(cases));
946             for (i = 0; i < cases.length; i += 1) {
947                 cases[i].branchLocation = this.branchLocationFor(bName, i);
948                 cases[i].consequent.unshift(astgen.statement(this.branchIncrementExprAst(bName, i)));
949             }
950         },
951
952         switchCaseInjector: function (node) {
953             var location = node.branchLocation;
954             delete node.branchLocation;
955             if (this.maybeSkipNode(node, 'next')) {
956                 location.skip = true;
957             }
958         },
959
960         conditionalBranchInjector: function (node, walker) {
961             var bName = this.branchName('cond-expr', walker.startLineForNode(node), this.locationsForNodes([ node.consequent, node.alternate ])),
962                 ast1 = this.branchIncrementExprAst(bName, 0),
963                 ast2 = this.branchIncrementExprAst(bName, 1);
964
965             node.consequent.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 0));
966             node.alternate.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 1));
967             node.consequent = astgen.sequence(ast1, node.consequent);
968             node.alternate = astgen.sequence(ast2, node.alternate);
969         },
970
971         maybeAddSkip: function (branchLocation) {
972             return function (node) {
973                 var alreadyIgnoring = !!this.currentState.ignoring,
974                     hint = this.currentState.currentHint,
975                     ignoreThis = !alreadyIgnoring && hint && hint.type === 'next';
976                 if (ignoreThis) {
977                     this.startIgnore();
978                     node.postprocessor = this.endIgnore;
979                 }
980                 if (ignoreThis || alreadyIgnoring) {
981                     branchLocation.skip = true;
982                 }
983             };
984         },
985
986         logicalExpressionBranchInjector: function (node, walker) {
987             var parent = walker.parent(),
988                 leaves = [],
989                 bName,
990                 tuple,
991                 i;
992
993             this.maybeSkipNode(node, 'next');
994
995             if (parent && parent.node.type === SYNTAX.LogicalExpression.name) {
996                 //already covered
997                 return;
998             }
999
1000             this.findLeaves(node, leaves);
1001             bName = this.branchName('binary-expr',
1002                 walker.startLineForNode(node),
1003                 this.locationsForNodes(leaves.map(function (item) { return item.node; }))
1004             );
1005             for (i = 0; i < leaves.length; i += 1) {
1006                 tuple = leaves[i];
1007                 tuple.parent[tuple.property] = astgen.sequence(this.branchIncrementExprAst(bName, i), tuple.node);
1008                 tuple.node.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, i));
1009             }
1010         },
1011
1012         findLeaves: function (node, accumulator, parent, property) {
1013             if (node.type === SYNTAX.LogicalExpression.name) {
1014                 this.findLeaves(node.left, accumulator, node, 'left');
1015                 this.findLeaves(node.right, accumulator, node, 'right');
1016             } else {
1017                 accumulator.push({ node: node, parent: parent, property: property });
1018             }
1019         },
1020         maybeAddType: function (node /*, walker */) {
1021             var props = node.properties,
1022                 i,
1023                 child;
1024             for (i = 0; i < props.length; i += 1) {
1025                 child = props[i];
1026                 if (!child.type) {
1027                     child.type = SYNTAX.Property.name;
1028                 }
1029             }
1030         }
1031     };
1032
1033     if (isNode) {
1034         module.exports = Instrumenter;
1035     } else {
1036         window.Instrumenter = Instrumenter;
1037     }
1038
1039 }(typeof module !== 'undefined' && typeof module.exports !== 'undefined' && typeof exports !== 'undefined'));
1040