forked from dart-lang/webdev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpression_evaluator.dart
549 lines (493 loc) · 18.1 KB
/
expression_evaluator.dart
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:dwds/src/debugging/dart_scope.dart';
import 'package:dwds/src/debugging/debugger.dart';
import 'package:dwds/src/debugging/location.dart';
import 'package:dwds/src/debugging/modules.dart';
import 'package:dwds/src/loaders/strategy.dart';
import 'package:dwds/src/services/expression_compiler.dart';
import 'package:dwds/src/services/javascript_builder.dart';
import 'package:dwds/src/utilities/conversions.dart';
import 'package:dwds/src/utilities/domain.dart';
import 'package:dwds/src/utilities/objects.dart' as chrome;
import 'package:logging/logging.dart';
import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart';
class EvaluationErrorKind {
EvaluationErrorKind._();
static const compilation = 'CompilationError';
static const type = 'TypeError';
static const reference = 'ReferenceError';
static const internal = 'InternalError';
static const asyncFrame = 'AsyncFrameError';
static const invalidInput = 'InvalidInputError';
static const loadModule = 'LoadModuleError';
}
/// ExpressionEvaluator provides functionality to evaluate dart expressions
/// from text user input in the debugger, using chrome remote debugger to
/// collect context for evaluation (scope, types, modules), and using
/// ExpressionCompilerInterface to compile dart expressions to JavaScript.
class ExpressionEvaluator {
final String _entrypoint;
final AppInspectorInterface _inspector;
final Debugger _debugger;
final Locations _locations;
final Modules _modules;
final ExpressionCompiler _compiler;
final _logger = Logger('ExpressionEvaluator');
bool _closed = false;
/// Strip synthetic library name from compiler error messages.
static final _syntheticNameFilterRegex =
RegExp('org-dartlang-debug:synthetic_debug_expression:.*:.*Error: ');
/// Find module path from the XHR call network error message received from chrome.
///
/// Example:
/// NetworkError: Failed to load 'http://<hostname>.com/path/to/module.js?<cache_busting_token>'
static final _loadModuleErrorRegex =
RegExp(r".*Failed to load '.*\.com/(.*\.js).*");
ExpressionEvaluator(
this._entrypoint,
this._inspector,
this._debugger,
this._locations,
this._modules,
this._compiler,
);
/// Create and error with [severity] and [message]
///
/// [severity] is one of kinds in [EvaluationErrorKind]
RemoteObject createError(String severity, String message) {
return RemoteObject(
<String, String>{'type': severity, 'value': message},
);
}
void close() {
_closed = true;
}
/// Evaluate dart expression inside a given library.
///
/// Uses ExpressionCompiler interface to compile the expression to
/// JavaScript and sends evaluate requests to chrome to calculate
/// the final result.
///
/// Returns remote object containing the result of evaluation or error.
///
/// [isolateId] current isolate ID.
/// [libraryUri] dart library to evaluate the expression in.
/// [expression] dart expression to evaluate.
Future<RemoteObject> evaluateExpression(
String isolateId,
String? libraryUri,
String expression,
Map<String, String>? scope,
) async {
if (_closed) {
return createError(
EvaluationErrorKind.internal,
'expression evaluator closed.',
);
}
scope ??= {};
if (expression.isEmpty) {
return createError(
EvaluationErrorKind.invalidInput,
expression,
);
}
if (libraryUri == null) {
return createError(
EvaluationErrorKind.invalidInput,
'no library uri',
);
}
final module = await _modules.moduleForLibrary(libraryUri);
if (module == null) {
return createError(
EvaluationErrorKind.internal,
'no module for $libraryUri',
);
}
// Wrap the expression in a lambda so we can call it as a function.
expression = _createDartLambda(expression, scope.keys);
_logger.finest('Evaluating "$expression" at $module');
// Compile expression using an expression compiler, such as
// frontend server or expression compiler worker.
final compilationResult = await _compiler.compileExpressionToJs(
isolateId,
libraryUri.toString(),
0,
0,
{},
{},
module,
expression,
);
final isError = compilationResult.isError;
final jsResult = compilationResult.result;
if (isError) {
return _formatCompilationError(jsResult);
}
// Strip try/catch incorrectly added by the expression compiler.
final jsCode = _maybeStripTryCatch(jsResult);
// Send JS expression to chrome to evaluate.
var result = await _callJsFunction(jsCode, scope);
result = await _formatEvaluationError(result);
_logger.finest('Evaluated "$expression" to "${result.json}"');
return result;
}
/// Evaluate dart expression inside a given frame (function).
///
/// Gets necessary context (types, scope, module names) data from chrome,
/// uses ExpressionCompiler interface to compile the expression to
/// JavaScript, and sends evaluate requests to chrome to calculate the
/// final result.
///
/// Returns remote object containing the result of evaluation or error.
///
/// [isolateId] current isolate ID.
/// [frameIndex] JavaScript frame to evaluate the expression in.
/// [expression] dart expression to evaluate.
/// [scope] additional scope to use in the expression as a map from
/// variable names to remote object IDs.
///
/// **Example**
///
/// To evaluate a dart expression
/// ```dart
/// this.t + a + x + y
/// ```
/// in a dart scope that defines `a` and `this`, and additional scope
/// `x, y`, we perform the following:
///
/// 1. compile dart function
///
///```dart
/// (x, y, a) { return this.t + a + x + y; }
///```
///
/// to JavaScript function
///
/// ```jsFunc```
///
/// using the expression compiler (i.e. frontend server or expression
/// compiler worker).
///
/// 2. create JavaScript wrapper function, `jsWrapperFunc`, defined as
///
/// ```JavaScript
/// function (x, y, a, __t$this) {
/// try {
/// return function (x, y, a) {
/// return jsFunc(x, y, a);
/// }.bind(__t$this)(x, y, a);
/// } catch (error) {
/// return error.name + ": " + error.message;
/// }
/// }
/// ```
///
/// 3. collect scope variable object IDs for total scope
/// (original frame scope from WipCallFrame + additional scope passed
/// by the user).
///
/// 4. call `jsWrapperFunc` using `Runtime.callFunctionOn` chrome API
/// with scope variable object IDs passed as arguments.
Future<RemoteObject> evaluateExpressionInFrame(
String isolateId,
int frameIndex,
String expression,
Map<String, String>? scope,
) async {
scope ??= {};
if (expression.isEmpty) {
return createError(EvaluationErrorKind.invalidInput, expression);
}
// Get JS scope and current JS location.
final jsFrame = _debugger.jsFrameForIndex(frameIndex);
if (jsFrame == null) {
return createError(
EvaluationErrorKind.asyncFrame,
'Expression evaluation in async frames '
'is not supported. No frame with index $frameIndex.');
}
final functionName = jsFrame.functionName;
final jsLine = jsFrame.location.lineNumber;
final jsScriptId = jsFrame.location.scriptId;
final jsColumn = jsFrame.location.columnNumber;
final jsScope = await _collectLocalJsScope(jsFrame);
// Find corresponding dart location and scope.
final url = _debugger.urlForScriptId(jsScriptId);
if (url == null) {
return createError(
EvaluationErrorKind.internal,
'Cannot find url for JS script: $jsScriptId',
);
}
final locationMap = await _locations.locationForJs(url, jsLine, jsColumn);
if (locationMap == null) {
return createError(
EvaluationErrorKind.internal,
'Cannot find Dart location for JS location: '
'url: $url, '
'function: $functionName, '
'line: $jsLine, '
'column: $jsColumn');
}
final dartLocation = locationMap.dartLocation;
final dartSourcePath = dartLocation.uri.serverPath;
final libraryUri = await _modules.libraryForSource(dartSourcePath);
if (libraryUri == null) {
return createError(
EvaluationErrorKind.internal,
'no libraryUri for $dartSourcePath',
);
}
final module = await _modules.moduleForLibrary(libraryUri.toString());
if (module == null) {
return createError(
EvaluationErrorKind.internal,
'no module for $libraryUri ($dartSourcePath)',
);
}
_logger.finest('Evaluating "$expression" at $module, '
'$libraryUri:${dartLocation.line}:${dartLocation.column} '
'with scope: $scope');
if (scope.isNotEmpty) {
scope.addAll(jsScope);
expression = _createDartLambda(expression, scope.keys);
}
_logger.finest('Compiling "$expression"');
// Compile expression using an expression compiler, such as
// frontend server or expression compiler worker.
//
// TODO(annagrin): map JS locals to dart locals in the expression
// and JS scope before passing them to the dart expression compiler.
// Issue: https://github.com/dart-lang/sdk/issues/40273
final compilationResult = await _compiler.compileExpressionToJs(
isolateId,
libraryUri.toString(),
dartLocation.line,
dartLocation.column,
{},
jsScope.map((key, value) => MapEntry(key, key)),
module,
expression,
);
final isError = compilationResult.isError;
final jsResult = compilationResult.result;
if (isError) {
return _formatCompilationError(jsResult);
}
// Strip try/catch incorrectly added by the expression compiler.
final jsCode = _maybeStripTryCatch(jsResult);
// Send JS expression to chrome to evaluate.
var result = scope.isEmpty
? await _evaluateJsExpressionInFrame(frameIndex, jsCode)
: await _callJsFunctionInFrame(frameIndex, jsCode, scope);
result = await _formatEvaluationError(result);
_logger.finest('Evaluated "$expression" to "${result.json}"');
return result;
}
/// Wrap the [function] in a lambda that takes scope variables as parameters.
/// Send JS expression to chrome to evaluate in frame with [frameIndex]
/// with the provided [scope].
///
/// [frameIndex] is the index of the frame to call the function in.
/// [function] is the JS function to evaluate.
/// [scope] is a map from scope variables to remote object IDs.
Future<RemoteObject> _callJsFunctionInFrame(
int frameIndex,
String function,
Map<String, String> scope,
) async {
final totalJsScope = await _addThisToScope(frameIndex, scope);
return _callJsFunction(function, totalJsScope);
}
/// Wrap the [function] in a lambda that takes scope variables as parameters.
/// Send JS expression to chrome to evaluate with the provided [scope].
///
/// [function] is the JS function to evaluate.
/// [scope] is a map from scope variables to remote object IDs.
Future<RemoteObject> _callJsFunction(
String function,
Map<String, String> scope,
) async {
final jsCode = _createEvalFunction(function, scope.keys);
_logger.finest('Evaluating JS: "$jsCode" with scope: $scope');
return _inspector.callFunction(jsCode, scope.values);
}
/// Wrap the [expression] in a try/catch expression to catch errors.
/// Send JS expression to chrome to evaluate on frame [frameIndex].
///
/// [frameIndex] is the index of the frame to call the function in.
/// [expression] is the JS function to evaluate.
Future<RemoteObject> _evaluateJsExpressionInFrame(
int frameIndex,
String expression,
) async {
final jsCode = _createEvalExpression(expression);
_logger.finest('Evaluating JS: "$jsCode"');
return _debugger.evaluateJsOnCallFrameIndex(frameIndex, jsCode);
}
static String? _getObjectId(RemoteObject? object) =>
object?.objectId ?? dartIdFor(object?.value);
/// Add 'this' variable to scope if it is defined on current frame.
///
/// [frame] is the current frame index.
/// [dartScope] is the scope already collected as a map from variable
/// names to remote object IDs.
///
/// Adds 'this' variable to the scope and returns the updated scope.
Future<Map<String, String>> _addThisToScope(
int frame,
Map<String, String> dartScope,
) async {
final thisObject =
await _debugger.evaluateJsOnCallFrameIndex(frame, 'this');
final thisObjectId = thisObject.objectId;
final totalJsScope = Map<String, String>.from(dartScope);
if (thisObjectId != null) {
totalJsScope['this'] = thisObjectId;
}
return totalJsScope;
}
RemoteObject _formatCompilationError(String error) {
// Frontend currently gives a text message including library name
// and function name on compilation error. Strip this information
// since it shows synthetic names that are only used for temporary
// debug library during expression evaluation.
//
// TODO(annagrin): modify frontend to avoid stripping dummy names
// [issue 40449](https://github.com/dart-lang/sdk/issues/40449)
if (error.startsWith('[')) {
error = error.substring(1);
}
if (error.endsWith(']')) {
error = error.substring(0, error.lastIndexOf(']'));
}
if (error.contains('InternalError: ')) {
error = error.replaceAll('InternalError: ', '');
return createError(EvaluationErrorKind.internal, error);
}
error = error.replaceAll(_syntheticNameFilterRegex, '');
return createError(EvaluationErrorKind.compilation, error);
}
Future<RemoteObject> _formatEvaluationError(RemoteObject result) async {
if (result.type == 'string') {
var error = '${result.value}';
if (error.startsWith('ReferenceError: ')) {
error = error.replaceFirst('ReferenceError: ', '');
return createError(EvaluationErrorKind.reference, error);
} else if (error.startsWith('TypeError: ')) {
error = error.replaceFirst('TypeError: ', '');
return createError(EvaluationErrorKind.type, error);
} else if (error.startsWith('NetworkError: ')) {
var modulePath = _loadModuleErrorRegex.firstMatch(error)?.group(1);
final module = modulePath != null
? await globalLoadStrategy.moduleForServerPath(
_entrypoint,
modulePath,
)
: 'unknown';
modulePath ??= 'unknown';
error = 'Module is not loaded : $module (path: $modulePath). '
'Accessing libraries that have not yet been used in the '
'application is not supported during expression evaluation.';
return createError(EvaluationErrorKind.loadModule, error);
}
}
return result;
}
/// Return local scope as a map from variable names to remote object IDs.
///
/// [frame] is the current frame index.
Future<Map<String, String>> _collectLocalJsScope(WipCallFrame frame) async {
final jsScope = <String, String>{};
void collectVariables(Iterable<chrome.Property> variables) {
for (var p in variables) {
final name = p.name;
final value = p.value;
// TODO: null values represent variables optimized by v8.
// Show that to the user.
if (name != null && value != null && !_isUndefined(value)) {
final objectId = _getObjectId(p.value);
if (objectId != null) {
jsScope[name] = objectId;
}
}
}
}
// skip library and main scope
final scopeChain = filterScopes(frame).reversed;
for (var scope in scopeChain) {
final objectId = scope.object.objectId;
if (objectId != null) {
final scopeProperties = await _inspector.getProperties(objectId);
collectVariables(scopeProperties);
}
}
return jsScope;
}
bool _isUndefined(RemoteObject value) => value.type == 'undefined';
static String _createDartLambda(
String expression,
Iterable<String> params,
) =>
'(${params.join(', ')}) { return $expression; }';
/// Strip try/catch incorrectly added by the expression compiler.
/// TODO: remove adding try/catch block in expression compiler.
/// https://github.com/dart-lang/webdev/issues/1341, then remove
/// this stripping code.
static String _maybeStripTryCatch(String jsCode) {
// Match the wrapping generated by the expression compiler exactly
// so the matching does not succeed naturally after the wrapping is
// removed:
//
// Expression compiler's wrapping:
//
// '\ntry {'
// '\n ($jsExpression('
// '\n $args'
// '\n ))'
// '\n} catch (error) {'
// '\n error.name + ": " + error.message;'
// '\n}';
//
final lines = jsCode.split('\n');
if (lines.length > 5) {
final tryLines = lines.getRange(0, 2).toList();
final bodyLines = lines.getRange(2, lines.length - 3);
final catchLines =
lines.getRange(lines.length - 3, lines.length).toList();
if (tryLines[0].isEmpty &&
tryLines[1] == 'try {' &&
catchLines[0] == '} catch (error) {' &&
catchLines[1] == ' error.name + ": " + error.message;' &&
catchLines[2] == '}') {
return bodyLines.join('\n');
}
}
return jsCode;
}
/// Create JS expression to pass to `Debugger.evaluateOnCallFrame`.
static String _createEvalExpression(String expression) {
final body = expression.split('\n').where((e) => e.isNotEmpty);
final builder = JsBuilder();
builder.createEvalExpression(body);
return builder.build();
}
/// Create JS function to invoke in `Runtime.callFunctionOn`.
static String _createEvalFunction(
String function,
Iterable<String> params,
) {
final body = function.split('\n').where((e) => e.isNotEmpty);
final builder = JsBuilder();
if (params.contains('this')) {
builder.writeEvalBoundFunction(body, params);
} else {
builder.writeEvalStaticFunction(body, params);
}
return builder.build();
}
}