1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | (function (isNode) {
|
8 | "use strict";
|
9 | var SYNTAX,
|
10 | nodeType,
|
11 | ESP = isNode ? require('esprima') : esprima,
|
12 | ESPGEN = isNode ? require('escodegen') : escodegen,
|
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 |
|
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 |
|
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 |
|
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 |
|
70 | AssignmentExpression: ['left', 'right'],
|
71 | AssignmentPattern: ['left', 'right'],
|
72 | ArrayExpression: ['elements'],
|
73 | ArrayPattern: ['elements'],
|
74 | ArrowFunctionExpression: ['params', 'body'],
|
75 | AwaitExpression: ['argument'],
|
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'],
|
85 | ComprehensionExpression: ['blocks', 'filter', 'body'],
|
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'],
|
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 | MetaProperty: ['meta', 'property'],
|
113 | MemberExpression: ['object', 'property'],
|
114 | MethodDefinition: ['key', 'value'],
|
115 | ModuleSpecifier: [],
|
116 | NewExpression: ['callee', 'arguments'],
|
117 | ObjectExpression: ['properties'],
|
118 | ObjectPattern: ['properties'],
|
119 | Program: ['body'],
|
120 | Property: ['key', 'value'],
|
121 | RestElement: [ 'argument' ],
|
122 | ReturnStatement: ['argument'],
|
123 | SequenceExpression: ['expressions'],
|
124 | SpreadElement: ['argument'],
|
125 | Super: [],
|
126 | SwitchStatement: ['discriminant', 'cases'],
|
127 | SwitchCase: ['test', 'consequent'],
|
128 | TaggedTemplateExpression: ['tag', 'quasi'],
|
129 | TemplateElement: [],
|
130 | TemplateLiteral: ['quasis', 'expressions'],
|
131 | ThisExpression: [],
|
132 | ThrowStatement: ['argument'],
|
133 | TryStatement: ['block', 'handler', 'finalizer'],
|
134 | UnaryExpression: ['argument'],
|
135 | UpdateExpression: ['argument'],
|
136 | VariableDeclaration: ['declarations'],
|
137 | VariableDeclarator: ['id', 'init'],
|
138 | WhileStatement: ['test', 'body'],
|
139 | WithStatement: ['object', 'body'],
|
140 | YieldExpression: ['argument']
|
141 | };
|
142 |
|
143 | for (nodeType in SYNTAX) {
|
144 |
|
145 | if (SYNTAX.hasOwnProperty(nodeType)) {
|
146 | SYNTAX[nodeType] = { name: nodeType, children: SYNTAX[nodeType] };
|
147 | }
|
148 | }
|
149 |
|
150 | astgen = {
|
151 | variable: function (name) { return { type: SYNTAX.Identifier.name, name: name }; },
|
152 | stringLiteral: function (str) { return { type: SYNTAX.Literal.name, value: String(str) }; },
|
153 | numericLiteral: function (num) { return { type: SYNTAX.Literal.name, value: Number(num) }; },
|
154 | statement: function (contents) { return { type: SYNTAX.ExpressionStatement.name, expression: contents }; },
|
155 | dot: function (obj, field) { return { type: SYNTAX.MemberExpression.name, computed: false, object: obj, property: field }; },
|
156 | subscript: function (obj, sub) { return { type: SYNTAX.MemberExpression.name, computed: true, object: obj, property: sub }; },
|
157 | postIncrement: function (obj) { return { type: SYNTAX.UpdateExpression.name, operator: '++', prefix: false, argument: obj }; },
|
158 | sequence: function (one, two) { return { type: SYNTAX.SequenceExpression.name, expressions: [one, two] }; },
|
159 | returnStatement: function (expr) { return { type: SYNTAX.ReturnStatement.name, argument: expr }; }
|
160 | };
|
161 |
|
162 | function Walker(walkMap, preprocessor, scope, debug) {
|
163 | this.walkMap = walkMap;
|
164 | this.preprocessor = preprocessor;
|
165 | this.scope = scope;
|
166 | this.debug = debug;
|
167 | if (this.debug) {
|
168 | this.level = 0;
|
169 | this.seq = true;
|
170 | }
|
171 | }
|
172 |
|
173 | function defaultWalker(node, walker) {
|
174 |
|
175 | var type = node.type,
|
176 | preprocessor,
|
177 | postprocessor,
|
178 | children = SYNTAX[type],
|
179 |
|
180 | applyCustomWalker = !!node.loc || node.type === SYNTAX.Program.name,
|
181 | walkerFn = applyCustomWalker ? walker.walkMap[type] : null,
|
182 | i,
|
183 | j,
|
184 | walkFnIndex,
|
185 | childType,
|
186 | childNode,
|
187 | ret,
|
188 | childArray,
|
189 | childElement,
|
190 | pathElement,
|
191 | assignNode,
|
192 | isLast;
|
193 |
|
194 | if (!SYNTAX[type]) {
|
195 | console.error(node);
|
196 | console.error('Unsupported node type:' + type);
|
197 | return;
|
198 | }
|
199 | children = SYNTAX[type].children;
|
200 |
|
201 | if (node.walking) { throw new Error('Infinite regress: Custom walkers may NOT call walker.apply(node)'); }
|
202 | node.walking = true;
|
203 |
|
204 | ret = walker.apply(node, walker.preprocessor);
|
205 |
|
206 | preprocessor = ret.preprocessor;
|
207 | if (preprocessor) {
|
208 | delete ret.preprocessor;
|
209 | ret = walker.apply(node, preprocessor);
|
210 | }
|
211 |
|
212 | if (isArray(walkerFn)) {
|
213 | for (walkFnIndex = 0; walkFnIndex < walkerFn.length; walkFnIndex += 1) {
|
214 | isLast = walkFnIndex === walkerFn.length - 1;
|
215 | ret = walker.apply(ret, walkerFn[walkFnIndex]);
|
216 |
|
217 | if (ret.type !== type && !isLast) {
|
218 | throw new Error('Only the last walker is allowed to change the node type: [type was: ' + type + ' ]');
|
219 | }
|
220 | }
|
221 | } else {
|
222 | if (walkerFn) {
|
223 | ret = walker.apply(node, walkerFn);
|
224 | }
|
225 | }
|
226 |
|
227 | if (node.skipSelf) {
|
228 | return;
|
229 | }
|
230 |
|
231 | for (i = 0; i < children.length; i += 1) {
|
232 | childType = children[i];
|
233 | childNode = node[childType];
|
234 | if (childNode && !childNode.skipWalk) {
|
235 | pathElement = { node: node, property: childType };
|
236 | if (isArray(childNode)) {
|
237 | childArray = [];
|
238 | for (j = 0; j < childNode.length; j += 1) {
|
239 | childElement = childNode[j];
|
240 | pathElement.index = j;
|
241 | if (childElement) {
|
242 | assignNode = walker.apply(childElement, null, pathElement);
|
243 | if (isArray(assignNode.prepend)) {
|
244 | pushAll(childArray, assignNode.prepend);
|
245 | delete assignNode.prepend;
|
246 | }
|
247 | } else {
|
248 | assignNode = undefined;
|
249 | }
|
250 | pushAll(childArray, assignNode);
|
251 | }
|
252 | node[childType] = childArray;
|
253 | } else {
|
254 | assignNode = walker.apply(childNode, null, pathElement);
|
255 |
|
256 | if (isArray(assignNode.prepend)) {
|
257 | throw new Error('Internal error: attempt to prepend statements in disallowed (non-array) context');
|
258 | |
259 |
|
260 |
|
261 |
|
262 |
|
263 |
|
264 |
|
265 | } else {
|
266 | node[childType] = assignNode;
|
267 | }
|
268 | }
|
269 | }
|
270 | }
|
271 |
|
272 | postprocessor = ret.postprocessor;
|
273 | if (postprocessor) {
|
274 | delete ret.postprocessor;
|
275 | ret = walker.apply(ret, postprocessor);
|
276 | }
|
277 |
|
278 | delete node.walking;
|
279 |
|
280 | return ret;
|
281 | }
|
282 |
|
283 | Walker.prototype = {
|
284 | startWalk: function (node) {
|
285 | this.path = [];
|
286 | this.apply(node);
|
287 | },
|
288 |
|
289 | apply: function (node, walkFn, pathElement) {
|
290 | var ret, i, seq, prefix;
|
291 |
|
292 | walkFn = walkFn || defaultWalker;
|
293 | if (this.debug) {
|
294 | this.seq += 1;
|
295 | this.level += 1;
|
296 | seq = this.seq;
|
297 | prefix = '';
|
298 | for (i = 0; i < this.level; i += 1) { prefix += ' '; }
|
299 | console.log(prefix + 'Enter (' + seq + '):' + node.type);
|
300 | }
|
301 | if (pathElement) { this.path.push(pathElement); }
|
302 | ret = walkFn.call(this.scope, node, this);
|
303 | if (pathElement) { this.path.pop(); }
|
304 | if (this.debug) {
|
305 | this.level -= 1;
|
306 | console.log(prefix + 'Return (' + seq + '):' + node.type);
|
307 | }
|
308 | return ret || node;
|
309 | },
|
310 |
|
311 | startLineForNode: function (node) {
|
312 | return node && node.loc && node.loc.start ? node.loc.start.line : null;
|
313 | },
|
314 |
|
315 | ancestor: function (n) {
|
316 | return this.path.length > n - 1 ? this.path[this.path.length - n] : null;
|
317 | },
|
318 |
|
319 | parent: function () {
|
320 | return this.ancestor(1);
|
321 | },
|
322 |
|
323 | isLabeled: function () {
|
324 | var el = this.parent();
|
325 | return el && el.node.type === SYNTAX.LabeledStatement.name;
|
326 | }
|
327 | };
|
328 |
|
329 | |
330 |
|
331 |
|
332 |
|
333 |
|
334 |
|
335 |
|
336 |
|
337 |
|
338 |
|
339 |
|
340 |
|
341 |
|
342 |
|
343 |
|
344 |
|
345 |
|
346 |
|
347 |
|
348 |
|
349 |
|
350 |
|
351 |
|
352 |
|
353 |
|
354 |
|
355 |
|
356 |
|
357 |
|
358 |
|
359 |
|
360 |
|
361 |
|
362 |
|
363 |
|
364 |
|
365 |
|
366 |
|
367 |
|
368 |
|
369 |
|
370 |
|
371 |
|
372 |
|
373 |
|
374 |
|
375 |
|
376 |
|
377 |
|
378 |
|
379 |
|
380 |
|
381 |
|
382 | function Instrumenter(options) {
|
383 | this.opts = options || {
|
384 | debug: false,
|
385 | walkDebug: false,
|
386 | coverageVariable: '__coverage__',
|
387 | codeGenerationOptions: undefined,
|
388 | noAutoWrap: false,
|
389 | noCompact: false,
|
390 | embedSource: false,
|
391 | preserveComments: false,
|
392 | esModules: false
|
393 | };
|
394 |
|
395 | if (this.opts.esModules && !this.opts.noAutoWrap) {
|
396 | this.opts.noAutoWrap = true;
|
397 | if (this.opts.debug) {
|
398 | console.log('Setting noAutoWrap to true as required by esModules');
|
399 | }
|
400 | }
|
401 |
|
402 | this.walker = new Walker({
|
403 | ArrowFunctionExpression: [ this.arrowBlockConverter ],
|
404 | ExpressionStatement: this.coverStatement,
|
405 | ExportNamedDeclaration: this.coverExport,
|
406 | BreakStatement: this.coverStatement,
|
407 | ContinueStatement: this.coverStatement,
|
408 | DebuggerStatement: this.coverStatement,
|
409 | ReturnStatement: this.coverStatement,
|
410 | ThrowStatement: this.coverStatement,
|
411 | TryStatement: [ this.paranoidHandlerCheck, this.coverStatement],
|
412 | VariableDeclaration: this.coverStatement,
|
413 | IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ],
|
414 | ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ],
|
415 | ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
|
416 | ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
|
417 | WhileStatement: [ this.loopBlockConverter, this.coverStatement ],
|
418 | DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ],
|
419 | SwitchStatement: [ this.coverStatement, this.switchBranchInjector ],
|
420 | SwitchCase: [ this.switchCaseInjector ],
|
421 | WithStatement: [ this.withBlockConverter, this.coverStatement ],
|
422 | FunctionDeclaration: [ this.coverFunction, this.coverStatement ],
|
423 | FunctionExpression: this.coverFunction,
|
424 | LabeledStatement: this.coverStatement,
|
425 | ConditionalExpression: this.conditionalBranchInjector,
|
426 | LogicalExpression: this.logicalExpressionBranchInjector,
|
427 | ObjectExpression: this.maybeAddType,
|
428 | MetaProperty: this.coverMetaProperty,
|
429 | }, this.extractCurrentHint, this, this.opts.walkDebug);
|
430 |
|
431 |
|
432 | if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) {
|
433 | this.omitTrackerSuffix = true;
|
434 | }
|
435 | }
|
436 |
|
437 | Instrumenter.prototype = {
|
438 | |
439 |
|
440 |
|
441 |
|
442 |
|
443 |
|
444 |
|
445 |
|
446 |
|
447 | instrumentSync: function (code, filename) {
|
448 | var program;
|
449 |
|
450 |
|
451 | if (typeof code !== 'string') { throw new Error('Code must be string'); }
|
452 | if (code.charAt(0) === '#') {
|
453 | code = '//' + code;
|
454 | }
|
455 | if (!this.opts.noAutoWrap) {
|
456 | code = LEADER_WRAP + code + TRAILER_WRAP;
|
457 | }
|
458 | try {
|
459 | program = ESP.parse(code, {
|
460 | loc: true,
|
461 | range: true,
|
462 | tokens: this.opts.preserveComments,
|
463 | comment: true,
|
464 | sourceType: this.opts.esModules ? 'module' : 'script'
|
465 | });
|
466 | } catch (e) {
|
467 | console.log('Failed to parse file: ' + filename);
|
468 | throw e;
|
469 | }
|
470 | if (this.opts.preserveComments) {
|
471 | program = ESPGEN.attachComments(program, program.comments, program.tokens);
|
472 | }
|
473 | if (!this.opts.noAutoWrap) {
|
474 | program = {
|
475 | type: SYNTAX.Program.name,
|
476 | body: program.body[0].expression.callee.body.body,
|
477 | comments: program.comments
|
478 | };
|
479 | }
|
480 | return this.instrumentASTSync(program, filename, code);
|
481 | },
|
482 | filterHints: function (comments) {
|
483 | var ret = [],
|
484 | i,
|
485 | comment,
|
486 | groups;
|
487 | if (!(comments && isArray(comments))) {
|
488 | return ret;
|
489 | }
|
490 | for (i = 0; i < comments.length; i += 1) {
|
491 | comment = comments[i];
|
492 |
|
493 | if (comment && comment.value && comment.range && isArray(comment.range)) {
|
494 | groups = String(comment.value).match(COMMENT_RE);
|
495 | if (groups) {
|
496 | ret.push({ type: groups[1], start: comment.range[0], end: comment.range[1] });
|
497 | }
|
498 | }
|
499 | }
|
500 | return ret;
|
501 | },
|
502 | extractCurrentHint: function (node) {
|
503 | if (!node.range) { return; }
|
504 | var i = this.currentState.lastHintPosition + 1,
|
505 | hints = this.currentState.hints,
|
506 | nodeStart = node.range[0],
|
507 | hint;
|
508 | this.currentState.currentHint = null;
|
509 | while (i < hints.length) {
|
510 | hint = hints[i];
|
511 | if (hint.end < nodeStart) {
|
512 | this.currentState.currentHint = hint;
|
513 | this.currentState.lastHintPosition = i;
|
514 | i += 1;
|
515 | } else {
|
516 | break;
|
517 | }
|
518 | }
|
519 | },
|
520 | |
521 |
|
522 |
|
523 |
|
524 |
|
525 |
|
526 |
|
527 |
|
528 |
|
529 |
|
530 |
|
531 | instrumentASTSync: function (program, filename, originalCode) {
|
532 | var usingStrict = false,
|
533 | codegenOptions,
|
534 | generated,
|
535 | preamble,
|
536 | lineCount,
|
537 | i;
|
538 | filename = filename || String(new Date().getTime()) + '.js';
|
539 | this.sourceMap = null;
|
540 | this.coverState = {
|
541 | path: filename,
|
542 | s: {},
|
543 | b: {},
|
544 | f: {},
|
545 | fnMap: {},
|
546 | statementMap: {},
|
547 | branchMap: {}
|
548 | };
|
549 | this.currentState = {
|
550 | trackerVar: generateTrackerVar(filename, this.omitTrackerSuffix),
|
551 | func: 0,
|
552 | branch: 0,
|
553 | variable: 0,
|
554 | statement: 0,
|
555 | hints: this.filterHints(program.comments),
|
556 | currentHint: null,
|
557 | lastHintPosition: -1,
|
558 | ignoring: 0
|
559 | };
|
560 | if (program.body && program.body.length > 0 && this.isUseStrictExpression(program.body[0])) {
|
561 |
|
562 | program.body.shift();
|
563 |
|
564 | usingStrict = true;
|
565 | }
|
566 | this.walker.startWalk(program);
|
567 | codegenOptions = this.opts.codeGenerationOptions || { format: { compact: !this.opts.noCompact }};
|
568 | codegenOptions.comment = this.opts.preserveComments;
|
569 |
|
570 |
|
571 | generated = ESPGEN.generate(program, codegenOptions);
|
572 | preamble = this.getPreamble(originalCode || '', usingStrict);
|
573 |
|
574 | if (generated.map && generated.code) {
|
575 | lineCount = preamble.split(/\r\n|\r|\n/).length;
|
576 |
|
577 | for (i = 0; i < generated.map._mappings._array.length; i += 1) {
|
578 | generated.map._mappings._array[i].generatedLine += lineCount;
|
579 | }
|
580 | this.sourceMap = generated.map;
|
581 | generated = generated.code;
|
582 | }
|
583 |
|
584 | return preamble + '\n' + generated + '\n';
|
585 | },
|
586 | |
587 |
|
588 |
|
589 |
|
590 |
|
591 |
|
592 |
|
593 |
|
594 |
|
595 |
|
596 |
|
597 |
|
598 |
|
599 | instrument: function (code, filename, callback) {
|
600 |
|
601 | if (!callback && typeof filename === 'function') {
|
602 | callback = filename;
|
603 | filename = null;
|
604 | }
|
605 | try {
|
606 | callback(null, this.instrumentSync(code, filename));
|
607 | } catch (ex) {
|
608 | callback(ex);
|
609 | }
|
610 | },
|
611 | |
612 |
|
613 |
|
614 |
|
615 |
|
616 |
|
617 |
|
618 |
|
619 |
|
620 |
|
621 | lastFileCoverage: function () {
|
622 | return this.coverState;
|
623 | },
|
624 | |
625 |
|
626 |
|
627 |
|
628 |
|
629 |
|
630 |
|
631 | lastSourceMap: function () {
|
632 | return this.sourceMap;
|
633 | },
|
634 | fixColumnPositions: function (coverState) {
|
635 | var offset = LEADER_WRAP.length,
|
636 | fixer = function (loc) {
|
637 | if (loc.start.line === 1) {
|
638 | loc.start.column -= offset;
|
639 | }
|
640 | if (loc.end.line === 1) {
|
641 | loc.end.column -= offset;
|
642 | }
|
643 | },
|
644 | k,
|
645 | obj,
|
646 | i,
|
647 | locations;
|
648 |
|
649 | obj = coverState.statementMap;
|
650 | for (k in obj) {
|
651 |
|
652 | if (obj.hasOwnProperty(k)) { fixer(obj[k]); }
|
653 | }
|
654 | obj = coverState.fnMap;
|
655 | for (k in obj) {
|
656 |
|
657 | if (obj.hasOwnProperty(k)) { fixer(obj[k].loc); }
|
658 | }
|
659 | obj = coverState.branchMap;
|
660 | for (k in obj) {
|
661 |
|
662 | if (obj.hasOwnProperty(k)) {
|
663 | locations = obj[k].locations;
|
664 | for (i = 0; i < locations.length; i += 1) {
|
665 | fixer(locations[i]);
|
666 | }
|
667 | }
|
668 | }
|
669 | },
|
670 |
|
671 | getPreamble: function (sourceCode, emitUseStrict) {
|
672 | var varName = this.opts.coverageVariable || '__coverage__',
|
673 | file = this.coverState.path.replace(/\\/g, '\\\\'),
|
674 | tracker = this.currentState.trackerVar,
|
675 | coverState,
|
676 | strictLine = emitUseStrict ? '"use strict";' : '',
|
677 |
|
678 |
|
679 | replacer = function (s) {
|
680 | return function () { return s; };
|
681 | },
|
682 | code;
|
683 | if (!this.opts.noAutoWrap) {
|
684 | this.fixColumnPositions(this.coverState);
|
685 | }
|
686 | if (this.opts.embedSource) {
|
687 | this.coverState.code = sourceCode.split(/(?:\r?\n)|\r/);
|
688 | }
|
689 | coverState = this.opts.debug ? JSON.stringify(this.coverState, undefined, 4) : JSON.stringify(this.coverState);
|
690 | code = [
|
691 | "%STRICT%",
|
692 | "var %VAR% = (Function('return this'))();",
|
693 | "if (!%VAR%.%GLOBAL%) { %VAR%.%GLOBAL% = {}; }",
|
694 | "%VAR% = %VAR%.%GLOBAL%;",
|
695 | "if (!(%VAR%['%FILE%'])) {",
|
696 | " %VAR%['%FILE%'] = %OBJECT%;",
|
697 | "}",
|
698 | "%VAR% = %VAR%['%FILE%'];"
|
699 | ].join("\n")
|
700 | .replace(/%STRICT%/g, replacer(strictLine))
|
701 | .replace(/%VAR%/g, replacer(tracker))
|
702 | .replace(/%GLOBAL%/g, replacer(varName))
|
703 | .replace(/%FILE%/g, replacer(file))
|
704 | .replace(/%OBJECT%/g, replacer(coverState));
|
705 | return code;
|
706 | },
|
707 |
|
708 | startIgnore: function () {
|
709 | this.currentState.ignoring += 1;
|
710 | },
|
711 |
|
712 | endIgnore: function () {
|
713 | this.currentState.ignoring -= 1;
|
714 | },
|
715 |
|
716 | convertToBlock: function (node) {
|
717 | if (!node) {
|
718 | return { type: 'BlockStatement', body: [] };
|
719 | } else if (node.type === 'BlockStatement') {
|
720 | return node;
|
721 | } else {
|
722 | return { type: 'BlockStatement', body: [ node ] };
|
723 | }
|
724 | },
|
725 |
|
726 | arrowBlockConverter: function (node) {
|
727 | var retStatement;
|
728 | if (node.expression) {
|
729 | retStatement = astgen.returnStatement(node.body);
|
730 |
|
731 | retStatement.loc = node.body.loc;
|
732 | node.body = this.convertToBlock(retStatement);
|
733 | node.expression = false;
|
734 | }
|
735 | },
|
736 |
|
737 | paranoidHandlerCheck: function (node) {
|
738 |
|
739 |
|
740 |
|
741 |
|
742 | if (!node.handler && node.handlers) {
|
743 | node.handler = node.handlers[0];
|
744 | }
|
745 | },
|
746 |
|
747 | ifBlockConverter: function (node) {
|
748 | node.consequent = this.convertToBlock(node.consequent);
|
749 | node.alternate = this.convertToBlock(node.alternate);
|
750 | },
|
751 |
|
752 | loopBlockConverter: function (node) {
|
753 | node.body = this.convertToBlock(node.body);
|
754 | },
|
755 |
|
756 | withBlockConverter: function (node) {
|
757 | node.body = this.convertToBlock(node.body);
|
758 | },
|
759 |
|
760 | statementName: function (location, initValue) {
|
761 | var sName,
|
762 | ignoring = !!this.currentState.ignoring;
|
763 |
|
764 | location.skip = ignoring || undefined;
|
765 | initValue = initValue || 0;
|
766 | this.currentState.statement += 1;
|
767 | sName = this.currentState.statement;
|
768 | this.coverState.statementMap[sName] = location;
|
769 | this.coverState.s[sName] = initValue;
|
770 | return sName;
|
771 | },
|
772 |
|
773 | skipInit: function (node /*, walker */) {
|
774 | if (node.init) {
|
775 | node.init.skipWalk = true;
|
776 | }
|
777 | },
|
778 |
|
779 | skipLeft: function (node /*, walker */) {
|
780 | node.left.skipWalk = true;
|
781 | },
|
782 |
|
783 | isUseStrictExpression: function (node) {
|
784 | return node && node.type === SYNTAX.ExpressionStatement.name &&
|
785 | node.expression && node.expression.type === SYNTAX.Literal.name &&
|
786 | node.expression.value === 'use strict';
|
787 | },
|
788 |
|
789 | maybeSkipNode: function (node, type) {
|
790 | var alreadyIgnoring = !!this.currentState.ignoring,
|
791 | hint = this.currentState.currentHint,
|
792 | ignoreThis = !alreadyIgnoring && hint && hint.type === type;
|
793 |
|
794 | if (ignoreThis) {
|
795 | this.startIgnore();
|
796 | node.postprocessor = this.endIgnore;
|
797 | return true;
|
798 | }
|
799 | return false;
|
800 | },
|
801 |
|
802 | coverMetaProperty: function(node /* , walker */) {
|
803 | node.skipSelf = true;
|
804 | },
|
805 |
|
806 | coverStatement: function (node, walker) {
|
807 | var sName,
|
808 | incrStatementCount,
|
809 | parent,
|
810 | grandParent;
|
811 |
|
812 | this.maybeSkipNode(node, 'next');
|
813 |
|
814 | if (this.isUseStrictExpression(node)) {
|
815 | grandParent = walker.ancestor(2);
|
816 |
|
817 | if (grandParent) {
|
818 | if ((grandParent.node.type === SYNTAX.FunctionExpression.name ||
|
819 | grandParent.node.type === SYNTAX.FunctionDeclaration.name) &&
|
820 | walker.parent().node.body[0] === node) {
|
821 | return;
|
822 | }
|
823 | }
|
824 | }
|
825 |
|
826 | if (node.type === SYNTAX.FunctionDeclaration.name) {
|
827 |
|
828 | this.statementName(node.loc, 1);
|
829 | } else {
|
830 |
|
831 | parent = walker.parent();
|
832 | if (parent && parent.node.type === SYNTAX.ExportNamedDeclaration.name) {
|
833 | return;
|
834 | }
|
835 |
|
836 | sName = this.statementName(node.loc);
|
837 |
|
838 | incrStatementCount = astgen.statement(
|
839 | astgen.postIncrement(
|
840 | astgen.subscript(
|
841 | astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
|
842 | astgen.stringLiteral(sName)
|
843 | )
|
844 | )
|
845 | );
|
846 |
|
847 | this.splice(incrStatementCount, node, walker);
|
848 | }
|
849 | },
|
850 |
|
851 | coverExport: function (node, walker) {
|
852 | var sName, incrStatementCount;
|
853 |
|
854 | if ( !node.declaration || !node.declaration.declarations ) { return; }
|
855 |
|
856 | this.maybeSkipNode(node, 'next');
|
857 |
|
858 | sName = this.statementName(node.declaration.loc);
|
859 | incrStatementCount = astgen.statement(
|
860 | astgen.postIncrement(
|
861 | astgen.subscript(
|
862 | astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
|
863 | astgen.stringLiteral(sName)
|
864 | )
|
865 | )
|
866 | );
|
867 |
|
868 | this.splice(incrStatementCount, node, walker);
|
869 | },
|
870 |
|
871 | splice: function (statements, node, walker) {
|
872 | var targetNode = walker.isLabeled() ? walker.parent().node : node;
|
873 | targetNode.prepend = targetNode.prepend || [];
|
874 | pushAll(targetNode.prepend, statements);
|
875 | },
|
876 |
|
877 | functionName: function (node, line, location) {
|
878 | this.currentState.func += 1;
|
879 | var id = this.currentState.func,
|
880 | ignoring = !!this.currentState.ignoring,
|
881 | name = node.id ? node.id.name : '(anonymous_' + id + ')',
|
882 | clone = function (attr) {
|
883 | var obj = location[attr] || {};
|
884 | return { line: obj.line, column: obj.column };
|
885 | };
|
886 | this.coverState.fnMap[id] = {
|
887 | name: name, line: line,
|
888 | loc: {
|
889 | start: clone('start'),
|
890 | end: clone('end')
|
891 | },
|
892 | skip: ignoring || undefined
|
893 | };
|
894 | this.coverState.f[id] = 0;
|
895 | return id;
|
896 | },
|
897 |
|
898 | coverFunction: function (node, walker) {
|
899 | var id,
|
900 | body = node.body,
|
901 | blockBody = body.body,
|
902 | popped;
|
903 |
|
904 | this.maybeSkipNode(node, 'next');
|
905 |
|
906 | id = this.functionName(node, walker.startLineForNode(node), {
|
907 | start: node.loc.start,
|
908 | end: { line: node.body.loc.start.line, column: node.body.loc.start.column }
|
909 | });
|
910 |
|
911 | if (blockBody.length > 0 && this.isUseStrictExpression(blockBody[0])) {
|
912 | popped = blockBody.shift();
|
913 | }
|
914 | blockBody.unshift(
|
915 | astgen.statement(
|
916 | astgen.postIncrement(
|
917 | astgen.subscript(
|
918 | astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('f')),
|
919 | astgen.stringLiteral(id)
|
920 | )
|
921 | )
|
922 | )
|
923 | );
|
924 | if (popped) {
|
925 | blockBody.unshift(popped);
|
926 | }
|
927 | },
|
928 |
|
929 | branchName: function (type, startLine, pathLocations) {
|
930 | var bName,
|
931 | paths = [],
|
932 | locations = [],
|
933 | i,
|
934 | ignoring = !!this.currentState.ignoring;
|
935 | this.currentState.branch += 1;
|
936 | bName = this.currentState.branch;
|
937 | for (i = 0; i < pathLocations.length; i += 1) {
|
938 | pathLocations[i].skip = pathLocations[i].skip || ignoring || undefined;
|
939 | locations.push(pathLocations[i]);
|
940 | paths.push(0);
|
941 | }
|
942 | this.coverState.b[bName] = paths;
|
943 | this.coverState.branchMap[bName] = { line: startLine, type: type, locations: locations };
|
944 | return bName;
|
945 | },
|
946 |
|
947 | branchIncrementExprAst: function (varName, branchIndex, down) {
|
948 | var ret = astgen.postIncrement(
|
949 | astgen.subscript(
|
950 | astgen.subscript(
|
951 | astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('b')),
|
952 | astgen.stringLiteral(varName)
|
953 | ),
|
954 | astgen.numericLiteral(branchIndex)
|
955 | ),
|
956 | down
|
957 | );
|
958 | return ret;
|
959 | },
|
960 |
|
961 | locationsForNodes: function (nodes) {
|
962 | var ret = [],
|
963 | i;
|
964 | for (i = 0; i < nodes.length; i += 1) {
|
965 | ret.push(nodes[i].loc);
|
966 | }
|
967 | return ret;
|
968 | },
|
969 |
|
970 | ifBranchInjector: function (node, walker) {
|
971 | var alreadyIgnoring = !!this.currentState.ignoring,
|
972 | hint = this.currentState.currentHint,
|
973 | ignoreThen = !alreadyIgnoring && hint && hint.type === 'if',
|
974 | ignoreElse = !alreadyIgnoring && hint && hint.type === 'else',
|
975 | line = node.loc.start.line,
|
976 | col = node.loc.start.column,
|
977 | makeLoc = function () { return { line: line, column: col }; },
|
978 | bName = this.branchName('if', walker.startLineForNode(node), [
|
979 | { start: makeLoc(), end: makeLoc(), skip: ignoreThen || undefined },
|
980 | { start: makeLoc(), end: makeLoc(), skip: ignoreElse || undefined }
|
981 | ]),
|
982 | thenBody = node.consequent.body,
|
983 | elseBody = node.alternate.body,
|
984 | child;
|
985 | thenBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 0)));
|
986 | elseBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 1)));
|
987 | if (ignoreThen) { child = node.consequent; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
|
988 | if (ignoreElse) { child = node.alternate; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
|
989 | },
|
990 |
|
991 | branchLocationFor: function (name, index) {
|
992 | return this.coverState.branchMap[name].locations[index];
|
993 | },
|
994 |
|
995 | switchBranchInjector: function (node, walker) {
|
996 | var cases = node.cases,
|
997 | bName,
|
998 | i;
|
999 |
|
1000 | if (!(cases && cases.length > 0)) {
|
1001 | return;
|
1002 | }
|
1003 | bName = this.branchName('switch', walker.startLineForNode(node), this.locationsForNodes(cases));
|
1004 | for (i = 0; i < cases.length; i += 1) {
|
1005 | cases[i].branchLocation = this.branchLocationFor(bName, i);
|
1006 | cases[i].consequent.unshift(astgen.statement(this.branchIncrementExprAst(bName, i)));
|
1007 | }
|
1008 | },
|
1009 |
|
1010 | switchCaseInjector: function (node) {
|
1011 | var location = node.branchLocation;
|
1012 | delete node.branchLocation;
|
1013 | if (this.maybeSkipNode(node, 'next')) {
|
1014 | location.skip = true;
|
1015 | }
|
1016 | },
|
1017 |
|
1018 | conditionalBranchInjector: function (node, walker) {
|
1019 | var bName = this.branchName('cond-expr', walker.startLineForNode(node), this.locationsForNodes([ node.consequent, node.alternate ])),
|
1020 | ast1 = this.branchIncrementExprAst(bName, 0),
|
1021 | ast2 = this.branchIncrementExprAst(bName, 1);
|
1022 |
|
1023 | node.consequent.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 0));
|
1024 | node.alternate.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 1));
|
1025 | node.consequent = astgen.sequence(ast1, node.consequent);
|
1026 | node.alternate = astgen.sequence(ast2, node.alternate);
|
1027 | },
|
1028 |
|
1029 | maybeAddSkip: function (branchLocation) {
|
1030 | return function (node) {
|
1031 | var alreadyIgnoring = !!this.currentState.ignoring,
|
1032 | hint = this.currentState.currentHint,
|
1033 | ignoreThis = !alreadyIgnoring && hint && hint.type === 'next';
|
1034 | if (ignoreThis) {
|
1035 | this.startIgnore();
|
1036 | node.postprocessor = this.endIgnore;
|
1037 | }
|
1038 | if (ignoreThis || alreadyIgnoring) {
|
1039 | branchLocation.skip = true;
|
1040 | }
|
1041 | };
|
1042 | },
|
1043 |
|
1044 | logicalExpressionBranchInjector: function (node, walker) {
|
1045 | var parent = walker.parent(),
|
1046 | leaves = [],
|
1047 | bName,
|
1048 | tuple,
|
1049 | i;
|
1050 |
|
1051 | this.maybeSkipNode(node, 'next');
|
1052 |
|
1053 | if (parent && parent.node.type === SYNTAX.LogicalExpression.name) {
|
1054 |
|
1055 | return;
|
1056 | }
|
1057 |
|
1058 | this.findLeaves(node, leaves);
|
1059 | bName = this.branchName('binary-expr',
|
1060 | walker.startLineForNode(node),
|
1061 | this.locationsForNodes(leaves.map(function (item) { return item.node; }))
|
1062 | );
|
1063 | for (i = 0; i < leaves.length; i += 1) {
|
1064 | tuple = leaves[i];
|
1065 | tuple.parent[tuple.property] = astgen.sequence(this.branchIncrementExprAst(bName, i), tuple.node);
|
1066 | tuple.node.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, i));
|
1067 | }
|
1068 | },
|
1069 |
|
1070 | findLeaves: function (node, accumulator, parent, property) {
|
1071 | if (node.type === SYNTAX.LogicalExpression.name) {
|
1072 | this.findLeaves(node.left, accumulator, node, 'left');
|
1073 | this.findLeaves(node.right, accumulator, node, 'right');
|
1074 | } else {
|
1075 | accumulator.push({ node: node, parent: parent, property: property });
|
1076 | }
|
1077 | },
|
1078 | maybeAddType: function (node /*, walker */) {
|
1079 | var props = node.properties,
|
1080 | i,
|
1081 | child;
|
1082 | for (i = 0; i < props.length; i += 1) {
|
1083 | child = props[i];
|
1084 | if (!child.type) {
|
1085 | child.type = SYNTAX.Property.name;
|
1086 | }
|
1087 | }
|
1088 | },
|
1089 | };
|
1090 |
|
1091 | if (isNode) {
|
1092 | module.exports = Instrumenter;
|
1093 | } else {
|
1094 | window.Instrumenter = Instrumenter;
|
1095 | }
|
1096 |
|
1097 | }(typeof module !== 'undefined' && typeof module.exports !== 'undefined' && typeof exports !== 'undefined'));
|