forked from firefox-devtools/debugger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapScopes.js
More file actions
433 lines (378 loc) · 11.8 KB
/
mapScopes.js
File metadata and controls
433 lines (378 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
// @flow
import { has } from "lodash";
import { getSource } from "../../selectors";
import { loadSourceText } from "../sources/loadSourceText";
import {
getScopes,
type SourceScope,
type BindingData,
type BindingLocation
} from "../../workers/parser";
import type { RenderableScope } from "../../utils/pause/scopes/getScope";
import { PROMISE } from "../utils/middleware/promise";
import { locColumn } from "../../utils/pause/mapScopes/locColumn";
// eslint-disable-next-line max-len
import { findGeneratedBindingFromPosition } from "../../utils/pause/mapScopes/findGeneratedBindingFromPosition";
import { features } from "../../utils/prefs";
import { log } from "../../utils/log";
import { isGeneratedId } from "devtools-source-map";
import type {
Frame,
Scope,
Source,
BindingContents,
ScopeBindings
} from "../../types";
import type { ThunkArgs } from "../types";
export type OriginalScope = RenderableScope;
export type GeneratedBindingLocation = {
name: string,
loc: BindingLocation,
desc: BindingContents | null
};
export function mapScopes(scopes: Promise<Scope>, frame: Frame) {
return async function({ dispatch, getState, client, sourceMaps }: ThunkArgs) {
const generatedSourceRecord = getSource(
getState(),
frame.generatedLocation.sourceId
);
const sourceRecord = getSource(getState(), frame.location.sourceId);
const shouldMapScopes =
features.mapScopes &&
!generatedSourceRecord.isWasm &&
!sourceRecord.isPrettyPrinted &&
!isGeneratedId(frame.location.sourceId);
await dispatch({
type: "MAP_SCOPES",
frame,
[PROMISE]: (async function() {
if (!shouldMapScopes) {
return null;
}
await dispatch(loadSourceText(sourceRecord));
try {
return await buildMappedScopes(
sourceRecord.toJS(),
frame,
await scopes,
sourceMaps,
client
);
} catch (e) {
log(e);
return null;
}
})()
});
};
}
async function buildMappedScopes(
source: Source,
frame: Frame,
scopes: Scope,
sourceMaps: any,
client: any
): Promise<?{
mappings: {
[string]: string
},
scope: OriginalScope
}> {
const originalAstScopes = await getScopes(frame.location);
const generatedAstScopes = await getScopes(frame.generatedLocation);
if (!originalAstScopes || !generatedAstScopes) {
return null;
}
const generatedAstBindings = buildGeneratedBindingList(
scopes,
generatedAstScopes,
frame.this
);
const expressionLookup = {};
const mappedOriginalScopes = [];
for (const item of originalAstScopes) {
const generatedBindings = {};
for (const name of Object.keys(item.bindings)) {
const binding = item.bindings[name];
const result = await findGeneratedBinding(
sourceMaps,
client,
source,
name,
binding,
generatedAstBindings
);
if (result) {
generatedBindings[name] = result.grip;
if (
binding.refs.length !== 0 &&
// These are assigned depth-first, so we don't want shadowed
// bindings in parent scopes overwriting the expression.
!Object.prototype.hasOwnProperty.call(expressionLookup, name)
) {
expressionLookup[name] = result.expression;
}
}
}
mappedOriginalScopes.push({
...item,
generatedBindings
});
}
const mappedGeneratedScopes = generateClientScope(
scopes,
mappedOriginalScopes
);
return isReliableScope(mappedGeneratedScopes)
? { mappings: expressionLookup, scope: mappedGeneratedScopes }
: null;
}
/**
* Consider a scope and its parents reliable if the vast majority of its
* bindings were successfully mapped to generated scope bindings.
*/
function isReliableScope(scope: OriginalScope): boolean {
let totalBindings = 0;
let unknownBindings = 0;
for (let s = scope; s; s = s.parent) {
const vars = (s.bindings && s.bindings.variables) || {};
for (const key of Object.keys(vars)) {
const binding = vars[key];
totalBindings += 1;
if (
binding.value &&
typeof binding.value === "object" &&
(binding.value.type === "unscoped" || binding.value.type === "unmapped")
) {
unknownBindings += 1;
}
}
}
// As determined by fair dice roll.
return totalBindings === 0 || unknownBindings / totalBindings < 0.9;
}
function generateClientScope(
scopes: Scope,
originalScopes: Array<SourceScope & { generatedBindings: ScopeBindings }>
): OriginalScope {
// Pull the root object scope and root lexical scope to reuse them in
// our mapped scopes. This assumes that file file being processed is
// a CommonJS or ES6 module, which might not be ideal. Potentially
// should add some logic to try to detect those cases?
let globalLexicalScope: ?OriginalScope = null;
for (let s = scopes; s.parent; s = s.parent) {
// $FlowIgnore - Flow doesn't like casting 'parent'.
globalLexicalScope = s;
}
if (!globalLexicalScope) {
throw new Error("Assertion failure - there should always be a scope");
}
// Build a structure similar to the client's linked scope object using
// the original AST scopes, but pulling in the generated bindings
// linked to each scope.
const result = originalScopes
.slice(0, -2)
.reverse()
.reduce((acc, orig, i): OriginalScope => {
const {
// The 'this' binding data we have is handled independently, so
// the binding data is not included here.
// eslint-disable-next-line no-unused-vars
this: _this,
...variables
} = orig.generatedBindings;
return {
// Flow doesn't like casting 'parent'.
parent: (acc: any),
actor: `originalActor${i}`,
type: orig.type,
bindings: {
arguments: [],
variables
},
...(orig.type === "function"
? {
function: {
displayName: orig.displayName
}
}
: null),
...(orig.type === "block"
? {
block: {
displayName: orig.displayName
}
}
: null)
};
}, globalLexicalScope);
// The rendering logic in getScope 'this' bindings only runs on the current
// selected frame scope, so we pluck out the 'this' binding that was mapped,
// and put it in a special location
const thisScope = originalScopes.find(scope => scope.bindings.this);
if (thisScope) {
result.bindings.this = thisScope.generatedBindings.this || null;
}
return result;
}
async function findGeneratedBinding(
sourceMaps: any,
client: any,
source: Source,
name: string,
originalBinding: BindingData,
generatedAstBindings: Array<GeneratedBindingLocation>
): Promise<?{
grip: BindingContents,
expression: string | null
}> {
// If there are no references to the implicits, then we have no way to
// even attempt to map it back to the original since there is no location
// data to use. Bail out instead of just showing it as unmapped.
if (
originalBinding.type === "implicit" &&
!originalBinding.refs.some(item => item.type === "ref")
) {
return null;
}
const { refs } = originalBinding;
const genContent = await refs.reduce(async (acc, pos) => {
const result = await acc;
if (result) {
return result;
}
return await findGeneratedBindingFromPosition(
sourceMaps,
client,
source,
pos,
name,
originalBinding.type,
generatedAstBindings
);
}, null);
if (genContent && genContent.desc) {
return {
grip: genContent.desc,
expression: genContent.expression
};
} else if (genContent) {
// If there is no descriptor for 'this', then this is not the top-level
// 'this' that the server gave us a binding for, and we can just ignore it.
if (name === "this") {
return null;
}
// If the location is found but the descriptor is not, then it
// means that the server scope information didn't match the scope
// information from the DevTools parsed scopes.
return {
grip: {
configurable: false,
enumerable: true,
writable: false,
value: {
type: "unscoped",
unscoped: true,
// HACK: Until support for "unscoped" lands in devtools-reps,
// this will make these show as (unavailable).
missingArguments: true
}
},
expression: null
};
}
// If no location mapping is found, then the map is bad, or
// the map is okay but it original location is inside
// of some scope, but the generated location is outside, leading
// us to search for bindings that don't technically exist.
return {
grip: {
configurable: false,
enumerable: true,
writable: false,
value: {
type: "unmapped",
unmapped: true,
// HACK: Until support for "unmapped" lands in devtools-reps,
// this will make these show as (unavailable).
missingArguments: true
}
},
expression: null
};
}
function buildGeneratedBindingList(
scopes: Scope,
generatedAstScopes: SourceScope[],
thisBinding: ?BindingContents
): Array<GeneratedBindingLocation> {
// The server's binding data doesn't include general 'this' binding
// information, so we manually inject the one 'this' binding we have into
// the normal binding data we are working with.
const frameThisOwner = generatedAstScopes.find(
generated => "this" in generated.bindings
);
const clientScopes = [];
for (let s = scopes; s; s = s.parent) {
const bindings = s.bindings
? Object.assign({}, ...s.bindings.arguments, s.bindings.variables)
: {};
clientScopes.push(bindings);
}
const generatedMainScopes = generatedAstScopes.slice(0, -2);
const generatedGlobalScopes = generatedAstScopes.slice(-2);
const clientMainScopes = clientScopes.slice(0, generatedMainScopes.length);
const clientGlobalScopes = clientScopes.slice(generatedMainScopes.length);
// Map the main parsed script body using the nesting hierarchy of the
// generated and client scopes.
const generatedBindings = generatedMainScopes.reduce((acc, generated, i) => {
const bindings = clientMainScopes[i];
if (generated === frameThisOwner && thisBinding) {
bindings.this = {
value: thisBinding
};
}
for (const name of Object.keys(generated.bindings)) {
const { refs } = generated.bindings[name];
for (const loc of refs) {
acc.push({
name,
loc,
desc: bindings[name] || null
});
}
}
return acc;
}, []);
// Bindings in the global/lexical global of the generated code may or
// may not be the real global if the generated code is running inside
// of an evaled context. To handle this, we just look up the client scope
// hierarchy to find the closest binding with that name.
for (const generated of generatedGlobalScopes) {
for (const name of Object.keys(generated.bindings)) {
const { refs } = generated.bindings[name];
for (const loc of refs) {
const bindings = clientGlobalScopes.find(b => has(b, name));
if (bindings) {
generatedBindings.push({
name,
loc,
desc: bindings[name]
});
}
}
}
}
// Sort so we can binary-search.
return generatedBindings.sort((a, b) => {
const aStart = a.loc.start;
const bStart = a.loc.start;
if (aStart.line === bStart.line) {
return locColumn(aStart) - locColumn(bStart);
}
return aStart.line - bStart.line;
});
}