Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80668 views
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
SuperExpression: ['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
}
243
pushAll(childArray, assignNode);
244
}
245
node[childType] = childArray;
246
} else {
247
assignNode = walker.apply(childNode, null, pathElement);
248
/*istanbul ignore if: paranoid check */
249
if (isArray(assignNode.prepend)) {
250
throw new Error('Internal error: attempt to prepend statements in disallowed (non-array) context');
251
/* if this should be allowed, this is how to solve it
252
tmpNode = { type: 'BlockStatement', body: [] };
253
pushAll(tmpNode.body, assignNode.prepend);
254
pushAll(tmpNode.body, assignNode);
255
node[childType] = tmpNode;
256
delete assignNode.prepend;
257
*/
258
} else {
259
node[childType] = assignNode;
260
}
261
}
262
}
263
}
264
265
postprocessor = ret.postprocessor;
266
if (postprocessor) {
267
delete ret.postprocessor;
268
ret = walker.apply(ret, postprocessor);
269
}
270
271
delete node.walking;
272
273
return ret;
274
}
275
276
Walker.prototype = {
277
startWalk: function (node) {
278
this.path = [];
279
this.apply(node);
280
},
281
282
apply: function (node, walkFn, pathElement) {
283
var ret, i, seq, prefix;
284
285
walkFn = walkFn || defaultWalker;
286
if (this.debug) {
287
this.seq += 1;
288
this.level += 1;
289
seq = this.seq;
290
prefix = '';
291
for (i = 0; i < this.level; i += 1) { prefix += ' '; }
292
console.log(prefix + 'Enter (' + seq + '):' + node.type);
293
}
294
if (pathElement) { this.path.push(pathElement); }
295
ret = walkFn.call(this.scope, node, this);
296
if (pathElement) { this.path.pop(); }
297
if (this.debug) {
298
this.level -= 1;
299
console.log(prefix + 'Return (' + seq + '):' + node.type);
300
}
301
return ret || node;
302
},
303
304
startLineForNode: function (node) {
305
return node && node.loc && node.loc.start ? node.loc.start.line : /* istanbul ignore next: guard */ null;
306
},
307
308
ancestor: function (n) {
309
return this.path.length > n - 1 ? this.path[this.path.length - n] : /* istanbul ignore next: guard */ null;
310
},
311
312
parent: function () {
313
return this.ancestor(1);
314
},
315
316
isLabeled: function () {
317
var el = this.parent();
318
return el && el.node.type === SYNTAX.LabeledStatement.name;
319
}
320
};
321
322
/**
323
* mechanism to instrument code for coverage. It uses the `esprima` and
324
* `escodegen` libraries for JS parsing and code generation respectively.
325
*
326
* Works on `node` as well as the browser.
327
*
328
* Usage on nodejs
329
* ---------------
330
*
331
* var instrumenter = new require('istanbul').Instrumenter(),
332
* changed = instrumenter.instrumentSync('function meaningOfLife() { return 42; }', 'filename.js');
333
*
334
* Usage in a browser
335
* ------------------
336
*
337
* Load `esprima.js`, `escodegen.js` and `instrumenter.js` (this file) using `script` tags or other means.
338
*
339
* Create an instrumenter object as:
340
*
341
* var instrumenter = new Instrumenter(),
342
* changed = instrumenter.instrumentSync('function meaningOfLife() { return 42; }', 'filename.js');
343
*
344
* Aside from demonstration purposes, it is unclear why you would want to instrument code in a browser.
345
*
346
* @class Instrumenter
347
* @constructor
348
* @param {Object} options Optional. Configuration options.
349
* @param {String} [options.coverageVariable] the global variable name to use for
350
* tracking coverage. Defaults to `__coverage__`
351
* @param {Boolean} [options.embedSource] whether to embed the source code of every
352
* file as an array in the file coverage object for that file. Defaults to `false`
353
* @param {Boolean} [options.preserveComments] whether comments should be preserved in the output. Defaults to `false`
354
* @param {Boolean} [options.noCompact] emit readable code when set. Defaults to `false`
355
* @param {Boolean} [options.noAutoWrap] do not automatically wrap the source in
356
* an anonymous function before covering it. By default, code is wrapped in
357
* an anonymous function before it is parsed. This is done because
358
* some nodejs libraries have `return` statements outside of
359
* a function which is technically invalid Javascript and causes the parser to fail.
360
* This construct, however, works correctly in node since module loading
361
* is done in the context of an anonymous function.
362
*
363
* Note that the semantics of the code *returned* by the instrumenter does not change in any way.
364
* The function wrapper is "unwrapped" before the instrumented code is generated.
365
* @param {Object} [options.codeGenerationOptions] an object that is directly passed to the `escodegen`
366
* library as configuration for code generation. The `noCompact` setting is not honored when this
367
* option is specified
368
* @param {Boolean} [options.debug] assist in debugging. Currently, the only effect of
369
* setting this option is a pretty-print of the coverage variable. Defaults to `false`
370
* @param {Boolean} [options.walkDebug] assist in debugging of the AST walker used by this class.
371
*
372
*/
373
function Instrumenter(options) {
374
this.opts = options || {
375
debug: false,
376
walkDebug: false,
377
coverageVariable: '__coverage__',
378
codeGenerationOptions: undefined,
379
noAutoWrap: false,
380
noCompact: false,
381
embedSource: false,
382
preserveComments: false
383
};
384
385
this.walker = new Walker({
386
ArrowFunctionExpression: [ this.arrowBlockConverter ],
387
ExpressionStatement: this.coverStatement,
388
BreakStatement: this.coverStatement,
389
ContinueStatement: this.coverStatement,
390
DebuggerStatement: this.coverStatement,
391
ReturnStatement: this.coverStatement,
392
ThrowStatement: this.coverStatement,
393
TryStatement: [ this.paranoidHandlerCheck, this.coverStatement],
394
VariableDeclaration: this.coverStatement,
395
IfStatement: [ this.ifBlockConverter, this.coverStatement, this.ifBranchInjector ],
396
ForStatement: [ this.skipInit, this.loopBlockConverter, this.coverStatement ],
397
ForInStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
398
ForOfStatement: [ this.skipLeft, this.loopBlockConverter, this.coverStatement ],
399
WhileStatement: [ this.loopBlockConverter, this.coverStatement ],
400
DoWhileStatement: [ this.loopBlockConverter, this.coverStatement ],
401
SwitchStatement: [ this.coverStatement, this.switchBranchInjector ],
402
SwitchCase: [ this.switchCaseInjector ],
403
WithStatement: [ this.withBlockConverter, this.coverStatement ],
404
FunctionDeclaration: [ this.coverFunction, this.coverStatement ],
405
FunctionExpression: this.coverFunction,
406
LabeledStatement: this.coverStatement,
407
ConditionalExpression: this.conditionalBranchInjector,
408
LogicalExpression: this.logicalExpressionBranchInjector,
409
ObjectExpression: this.maybeAddType
410
}, this.extractCurrentHint, this, this.opts.walkDebug);
411
412
//unit testing purposes only
413
if (this.opts.backdoor && this.opts.backdoor.omitTrackerSuffix) {
414
this.omitTrackerSuffix = true;
415
}
416
}
417
418
Instrumenter.prototype = {
419
/**
420
* synchronous instrumentation method. Throws when illegal code is passed to it
421
* @method instrumentSync
422
* @param {String} code the code to be instrumented as a String
423
* @param {String} filename Optional. The name of the file from which
424
* the code was read. A temporary filename is generated when not specified.
425
* Not specifying a filename is only useful for unit tests and demonstrations
426
* of this library.
427
*/
428
instrumentSync: function (code, filename) {
429
var program;
430
431
//protect from users accidentally passing in a Buffer object instead
432
if (typeof code !== 'string') { throw new Error('Code must be string'); }
433
if (code.charAt(0) === '#') { //shebang, 'comment' it out, won't affect syntax tree locations for things we care about
434
code = '//' + code;
435
}
436
if (!this.opts.noAutoWrap) {
437
code = LEADER_WRAP + code + TRAILER_WRAP;
438
}
439
program = ESP.parse(code, {
440
loc: true,
441
range: true,
442
tokens: this.opts.preserveComments,
443
comment: true
444
});
445
if (this.opts.preserveComments) {
446
program = ESPGEN.attachComments(program, program.comments, program.tokens);
447
}
448
if (!this.opts.noAutoWrap) {
449
program = {
450
type: SYNTAX.Program.name,
451
body: program.body[0].expression.callee.body.body,
452
comments: program.comments
453
};
454
}
455
return this.instrumentASTSync(program, filename, code);
456
},
457
filterHints: function (comments) {
458
var ret = [],
459
i,
460
comment,
461
groups;
462
if (!(comments && isArray(comments))) {
463
return ret;
464
}
465
for (i = 0; i < comments.length; i += 1) {
466
comment = comments[i];
467
/* istanbul ignore else: paranoid check */
468
if (comment && comment.value && comment.range && isArray(comment.range)) {
469
groups = String(comment.value).match(COMMENT_RE);
470
if (groups) {
471
ret.push({ type: groups[1], start: comment.range[0], end: comment.range[1] });
472
}
473
}
474
}
475
return ret;
476
},
477
extractCurrentHint: function (node) {
478
if (!node.range) { return; }
479
var i = this.currentState.lastHintPosition + 1,
480
hints = this.currentState.hints,
481
nodeStart = node.range[0],
482
hint;
483
this.currentState.currentHint = null;
484
while (i < hints.length) {
485
hint = hints[i];
486
if (hint.end < nodeStart) {
487
this.currentState.currentHint = hint;
488
this.currentState.lastHintPosition = i;
489
i += 1;
490
} else {
491
break;
492
}
493
}
494
},
495
/**
496
* synchronous instrumentation method that instruments an AST instead.
497
* @method instrumentASTSync
498
* @param {String} program the AST to be instrumented
499
* @param {String} filename Optional. The name of the file from which
500
* the code was read. A temporary filename is generated when not specified.
501
* Not specifying a filename is only useful for unit tests and demonstrations
502
* of this library.
503
* @param {String} originalCode the original code corresponding to the AST,
504
* used for embedding the source into the coverage object
505
*/
506
instrumentASTSync: function (program, filename, originalCode) {
507
var usingStrict = false,
508
codegenOptions,
509
generated,
510
preamble,
511
lineCount,
512
i;
513
filename = filename || String(new Date().getTime()) + '.js';
514
this.sourceMap = null;
515
this.coverState = {
516
path: filename,
517
s: {},
518
b: {},
519
f: {},
520
fnMap: {},
521
statementMap: {},
522
branchMap: {}
523
};
524
this.currentState = {
525
trackerVar: generateTrackerVar(filename, this.omitTrackerSuffix),
526
func: 0,
527
branch: 0,
528
variable: 0,
529
statement: 0,
530
hints: this.filterHints(program.comments),
531
currentHint: null,
532
lastHintPosition: -1,
533
ignoring: 0
534
};
535
if (program.body && program.body.length > 0 && this.isUseStrictExpression(program.body[0])) {
536
//nuke it
537
program.body.shift();
538
//and add it back at code generation time
539
usingStrict = true;
540
}
541
this.walker.startWalk(program);
542
codegenOptions = this.opts.codeGenerationOptions || { format: { compact: !this.opts.noCompact }};
543
codegenOptions.comment = this.opts.preserveComments;
544
//console.log(JSON.stringify(program, undefined, 2));
545
546
generated = ESPGEN.generate(program, codegenOptions);
547
preamble = this.getPreamble(originalCode || '', usingStrict);
548
549
if (generated.map && generated.code) {
550
lineCount = preamble.split(/\r\n|\r|\n/).length;
551
// offset all the generated line numbers by the number of lines in the preamble
552
for (i = 0; i < generated.map._mappings.length; i += 1) {
553
generated.map._mappings[i].generatedLine += lineCount;
554
}
555
this.sourceMap = generated.map;
556
generated = generated.code;
557
}
558
559
return preamble + '\n' + generated + '\n';
560
},
561
/**
562
* Callback based instrumentation. Note that this still executes synchronously in the same process tick
563
* and calls back immediately. It only provides the options for callback style error handling as
564
* opposed to a `try-catch` style and nothing more. Implemented as a wrapper over `instrumentSync`
565
*
566
* @method instrument
567
* @param {String} code the code to be instrumented as a String
568
* @param {String} filename Optional. The name of the file from which
569
* the code was read. A temporary filename is generated when not specified.
570
* Not specifying a filename is only useful for unit tests and demonstrations
571
* of this library.
572
* @param {Function(err, instrumentedCode)} callback - the callback function
573
*/
574
instrument: function (code, filename, callback) {
575
576
if (!callback && typeof filename === 'function') {
577
callback = filename;
578
filename = null;
579
}
580
try {
581
callback(null, this.instrumentSync(code, filename));
582
} catch (ex) {
583
callback(ex);
584
}
585
},
586
/**
587
* returns the file coverage object for the code that was instrumented
588
* just before calling this method. Note that this represents a
589
* "zero-coverage" object which is not even representative of the code
590
* being loaded in node or a browser (which would increase the statement
591
* counts for mainline code).
592
* @method lastFileCoverage
593
* @return {Object} a "zero-coverage" file coverage object for the code last instrumented
594
* by this instrumenter
595
*/
596
lastFileCoverage: function () {
597
return this.coverState;
598
},
599
/**
600
* returns the source map object for the code that was instrumented
601
* just before calling this method.
602
* @method lastSourceMap
603
* @return {Object} a source map object for the code last instrumented
604
* by this instrumenter
605
*/
606
lastSourceMap: function () {
607
return this.sourceMap;
608
},
609
fixColumnPositions: function (coverState) {
610
var offset = LEADER_WRAP.length,
611
fixer = function (loc) {
612
if (loc.start.line === 1) {
613
loc.start.column -= offset;
614
}
615
if (loc.end.line === 1) {
616
loc.end.column -= offset;
617
}
618
},
619
k,
620
obj,
621
i,
622
locations;
623
624
obj = coverState.statementMap;
625
for (k in obj) {
626
/* istanbul ignore else: has own property */
627
if (obj.hasOwnProperty(k)) { fixer(obj[k]); }
628
}
629
obj = coverState.fnMap;
630
for (k in obj) {
631
/* istanbul ignore else: has own property */
632
if (obj.hasOwnProperty(k)) { fixer(obj[k].loc); }
633
}
634
obj = coverState.branchMap;
635
for (k in obj) {
636
/* istanbul ignore else: has own property */
637
if (obj.hasOwnProperty(k)) {
638
locations = obj[k].locations;
639
for (i = 0; i < locations.length; i += 1) {
640
fixer(locations[i]);
641
}
642
}
643
}
644
},
645
646
getPreamble: function (sourceCode, emitUseStrict) {
647
var varName = this.opts.coverageVariable || '__coverage__',
648
file = this.coverState.path.replace(/\\/g, '\\\\'),
649
tracker = this.currentState.trackerVar,
650
coverState,
651
strictLine = emitUseStrict ? '"use strict";' : '',
652
// return replacements using the function to ensure that the replacement is
653
// treated like a dumb string and not as a string with RE replacement patterns
654
replacer = function (s) {
655
return function () { return s; };
656
},
657
code;
658
if (!this.opts.noAutoWrap) {
659
this.fixColumnPositions(this.coverState);
660
}
661
if (this.opts.embedSource) {
662
this.coverState.code = sourceCode.split(/(?:\r?\n)|\r/);
663
}
664
coverState = this.opts.debug ? JSON.stringify(this.coverState, undefined, 4) : JSON.stringify(this.coverState);
665
code = [
666
"%STRICT%",
667
"var %VAR% = (Function('return this'))();",
668
"if (!%VAR%.%GLOBAL%) { %VAR%.%GLOBAL% = {}; }",
669
"%VAR% = %VAR%.%GLOBAL%;",
670
"if (!(%VAR%['%FILE%'])) {",
671
" %VAR%['%FILE%'] = %OBJECT%;",
672
"}",
673
"%VAR% = %VAR%['%FILE%'];"
674
].join("\n")
675
.replace(/%STRICT%/g, replacer(strictLine))
676
.replace(/%VAR%/g, replacer(tracker))
677
.replace(/%GLOBAL%/g, replacer(varName))
678
.replace(/%FILE%/g, replacer(file))
679
.replace(/%OBJECT%/g, replacer(coverState));
680
return code;
681
},
682
683
startIgnore: function () {
684
this.currentState.ignoring += 1;
685
},
686
687
endIgnore: function () {
688
this.currentState.ignoring -= 1;
689
},
690
691
convertToBlock: function (node) {
692
if (!node) {
693
return { type: 'BlockStatement', body: [] };
694
} else if (node.type === 'BlockStatement') {
695
return node;
696
} else {
697
return { type: 'BlockStatement', body: [ node ] };
698
}
699
},
700
701
arrowBlockConverter: function (node) {
702
var retStatement;
703
if (node.expression) { // turn expression nodes into a block with a return statement
704
retStatement = astgen.returnStatement(node.body);
705
// ensure the generated return statement is covered
706
retStatement.loc = node.body.loc;
707
node.body = this.convertToBlock(retStatement);
708
node.expression = false;
709
}
710
},
711
712
paranoidHandlerCheck: function (node) {
713
// if someone is using an older esprima on the browser
714
// convert handlers array to single handler attribute
715
// containing its first element
716
/* istanbul ignore next */
717
if (!node.handler && node.handlers) {
718
node.handler = node.handlers[0];
719
}
720
},
721
722
ifBlockConverter: function (node) {
723
node.consequent = this.convertToBlock(node.consequent);
724
node.alternate = this.convertToBlock(node.alternate);
725
},
726
727
loopBlockConverter: function (node) {
728
node.body = this.convertToBlock(node.body);
729
},
730
731
withBlockConverter: function (node) {
732
node.body = this.convertToBlock(node.body);
733
},
734
735
statementName: function (location, initValue) {
736
var sName,
737
ignoring = !!this.currentState.ignoring;
738
739
location.skip = ignoring || undefined;
740
initValue = initValue || 0;
741
this.currentState.statement += 1;
742
sName = this.currentState.statement;
743
this.coverState.statementMap[sName] = location;
744
this.coverState.s[sName] = initValue;
745
return sName;
746
},
747
748
skipInit: function (node /*, walker */) {
749
if (node.init) {
750
node.init.skipWalk = true;
751
}
752
},
753
754
skipLeft: function (node /*, walker */) {
755
node.left.skipWalk = true;
756
},
757
758
isUseStrictExpression: function (node) {
759
return node && node.type === SYNTAX.ExpressionStatement.name &&
760
node.expression && node.expression.type === SYNTAX.Literal.name &&
761
node.expression.value === 'use strict';
762
},
763
764
maybeSkipNode: function (node, type) {
765
var alreadyIgnoring = !!this.currentState.ignoring,
766
hint = this.currentState.currentHint,
767
ignoreThis = !alreadyIgnoring && hint && hint.type === type;
768
769
if (ignoreThis) {
770
this.startIgnore();
771
node.postprocessor = this.endIgnore;
772
return true;
773
}
774
return false;
775
},
776
777
coverStatement: function (node, walker) {
778
var sName,
779
incrStatementCount,
780
grandParent;
781
782
this.maybeSkipNode(node, 'next');
783
784
if (this.isUseStrictExpression(node)) {
785
grandParent = walker.ancestor(2);
786
/* istanbul ignore else: difficult to test */
787
if (grandParent) {
788
if ((grandParent.node.type === SYNTAX.FunctionExpression.name ||
789
grandParent.node.type === SYNTAX.FunctionDeclaration.name) &&
790
walker.parent().node.body[0] === node) {
791
return;
792
}
793
}
794
}
795
if (node.type === SYNTAX.FunctionDeclaration.name) {
796
sName = this.statementName(node.loc, 1);
797
} else {
798
sName = this.statementName(node.loc);
799
incrStatementCount = astgen.statement(
800
astgen.postIncrement(
801
astgen.subscript(
802
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('s')),
803
astgen.stringLiteral(sName)
804
)
805
)
806
);
807
this.splice(incrStatementCount, node, walker);
808
}
809
},
810
811
splice: function (statements, node, walker) {
812
var targetNode = walker.isLabeled() ? walker.parent().node : node;
813
targetNode.prepend = targetNode.prepend || [];
814
pushAll(targetNode.prepend, statements);
815
},
816
817
functionName: function (node, line, location) {
818
this.currentState.func += 1;
819
var id = this.currentState.func,
820
ignoring = !!this.currentState.ignoring,
821
name = node.id ? node.id.name : '(anonymous_' + id + ')',
822
clone = function (attr) {
823
var obj = location[attr] || /* istanbul ignore next */ {};
824
return { line: obj.line, column: obj.column };
825
};
826
this.coverState.fnMap[id] = {
827
name: name, line: line,
828
loc: {
829
start: clone('start'),
830
end: clone('end')
831
},
832
skip: ignoring || undefined
833
};
834
this.coverState.f[id] = 0;
835
return id;
836
},
837
838
coverFunction: function (node, walker) {
839
var id,
840
body = node.body,
841
blockBody = body.body,
842
popped;
843
844
this.maybeSkipNode(node, 'next');
845
846
id = this.functionName(node, walker.startLineForNode(node), {
847
start: node.loc.start,
848
end: { line: node.body.loc.start.line, column: node.body.loc.start.column }
849
});
850
851
if (blockBody.length > 0 && this.isUseStrictExpression(blockBody[0])) {
852
popped = blockBody.shift();
853
}
854
blockBody.unshift(
855
astgen.statement(
856
astgen.postIncrement(
857
astgen.subscript(
858
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('f')),
859
astgen.stringLiteral(id)
860
)
861
)
862
)
863
);
864
if (popped) {
865
blockBody.unshift(popped);
866
}
867
},
868
869
branchName: function (type, startLine, pathLocations) {
870
var bName,
871
paths = [],
872
locations = [],
873
i,
874
ignoring = !!this.currentState.ignoring;
875
this.currentState.branch += 1;
876
bName = this.currentState.branch;
877
for (i = 0; i < pathLocations.length; i += 1) {
878
pathLocations[i].skip = pathLocations[i].skip || ignoring || undefined;
879
locations.push(pathLocations[i]);
880
paths.push(0);
881
}
882
this.coverState.b[bName] = paths;
883
this.coverState.branchMap[bName] = { line: startLine, type: type, locations: locations };
884
return bName;
885
},
886
887
branchIncrementExprAst: function (varName, branchIndex, down) {
888
var ret = astgen.postIncrement(
889
astgen.subscript(
890
astgen.subscript(
891
astgen.dot(astgen.variable(this.currentState.trackerVar), astgen.variable('b')),
892
astgen.stringLiteral(varName)
893
),
894
astgen.numericLiteral(branchIndex)
895
),
896
down
897
);
898
return ret;
899
},
900
901
locationsForNodes: function (nodes) {
902
var ret = [],
903
i;
904
for (i = 0; i < nodes.length; i += 1) {
905
ret.push(nodes[i].loc);
906
}
907
return ret;
908
},
909
910
ifBranchInjector: function (node, walker) {
911
var alreadyIgnoring = !!this.currentState.ignoring,
912
hint = this.currentState.currentHint,
913
ignoreThen = !alreadyIgnoring && hint && hint.type === 'if',
914
ignoreElse = !alreadyIgnoring && hint && hint.type === 'else',
915
line = node.loc.start.line,
916
col = node.loc.start.column,
917
makeLoc = function () { return { line: line, column: col }; },
918
bName = this.branchName('if', walker.startLineForNode(node), [
919
{ start: makeLoc(), end: makeLoc(), skip: ignoreThen || undefined },
920
{ start: makeLoc(), end: makeLoc(), skip: ignoreElse || undefined }
921
]),
922
thenBody = node.consequent.body,
923
elseBody = node.alternate.body,
924
child;
925
thenBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 0)));
926
elseBody.unshift(astgen.statement(this.branchIncrementExprAst(bName, 1)));
927
if (ignoreThen) { child = node.consequent; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
928
if (ignoreElse) { child = node.alternate; child.preprocessor = this.startIgnore; child.postprocessor = this.endIgnore; }
929
},
930
931
branchLocationFor: function (name, index) {
932
return this.coverState.branchMap[name].locations[index];
933
},
934
935
switchBranchInjector: function (node, walker) {
936
var cases = node.cases,
937
bName,
938
i;
939
940
if (!(cases && cases.length > 0)) {
941
return;
942
}
943
bName = this.branchName('switch', walker.startLineForNode(node), this.locationsForNodes(cases));
944
for (i = 0; i < cases.length; i += 1) {
945
cases[i].branchLocation = this.branchLocationFor(bName, i);
946
cases[i].consequent.unshift(astgen.statement(this.branchIncrementExprAst(bName, i)));
947
}
948
},
949
950
switchCaseInjector: function (node) {
951
var location = node.branchLocation;
952
delete node.branchLocation;
953
if (this.maybeSkipNode(node, 'next')) {
954
location.skip = true;
955
}
956
},
957
958
conditionalBranchInjector: function (node, walker) {
959
var bName = this.branchName('cond-expr', walker.startLineForNode(node), this.locationsForNodes([ node.consequent, node.alternate ])),
960
ast1 = this.branchIncrementExprAst(bName, 0),
961
ast2 = this.branchIncrementExprAst(bName, 1);
962
963
node.consequent.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 0));
964
node.alternate.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, 1));
965
node.consequent = astgen.sequence(ast1, node.consequent);
966
node.alternate = astgen.sequence(ast2, node.alternate);
967
},
968
969
maybeAddSkip: function (branchLocation) {
970
return function (node) {
971
var alreadyIgnoring = !!this.currentState.ignoring,
972
hint = this.currentState.currentHint,
973
ignoreThis = !alreadyIgnoring && hint && hint.type === 'next';
974
if (ignoreThis) {
975
this.startIgnore();
976
node.postprocessor = this.endIgnore;
977
}
978
if (ignoreThis || alreadyIgnoring) {
979
branchLocation.skip = true;
980
}
981
};
982
},
983
984
logicalExpressionBranchInjector: function (node, walker) {
985
var parent = walker.parent(),
986
leaves = [],
987
bName,
988
tuple,
989
i;
990
991
this.maybeSkipNode(node, 'next');
992
993
if (parent && parent.node.type === SYNTAX.LogicalExpression.name) {
994
//already covered
995
return;
996
}
997
998
this.findLeaves(node, leaves);
999
bName = this.branchName('binary-expr',
1000
walker.startLineForNode(node),
1001
this.locationsForNodes(leaves.map(function (item) { return item.node; }))
1002
);
1003
for (i = 0; i < leaves.length; i += 1) {
1004
tuple = leaves[i];
1005
tuple.parent[tuple.property] = astgen.sequence(this.branchIncrementExprAst(bName, i), tuple.node);
1006
tuple.node.preprocessor = this.maybeAddSkip(this.branchLocationFor(bName, i));
1007
}
1008
},
1009
1010
findLeaves: function (node, accumulator, parent, property) {
1011
if (node.type === SYNTAX.LogicalExpression.name) {
1012
this.findLeaves(node.left, accumulator, node, 'left');
1013
this.findLeaves(node.right, accumulator, node, 'right');
1014
} else {
1015
accumulator.push({ node: node, parent: parent, property: property });
1016
}
1017
},
1018
maybeAddType: function (node /*, walker */) {
1019
var props = node.properties,
1020
i,
1021
child;
1022
for (i = 0; i < props.length; i += 1) {
1023
child = props[i];
1024
if (!child.type) {
1025
child.type = SYNTAX.Property.name;
1026
}
1027
}
1028
}
1029
};
1030
1031
if (isNode) {
1032
module.exports = Instrumenter;
1033
} else {
1034
window.Instrumenter = Instrumenter;
1035
}
1036
1037
}(typeof module !== 'undefined' && typeof module.exports !== 'undefined' && typeof exports !== 'undefined'));
1038
1039
1040