-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathexpression_compiler_service.dart
301 lines (266 loc) · 9.02 KB
/
expression_compiler_service.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
// 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 'dart:async';
import 'dart:isolate';
import 'package:async/async.dart';
import 'package:dwds/src/services/expression_compiler.dart';
import 'package:dwds/src/utilities/sdk_configuration.dart';
import 'package:logging/logging.dart';
class _Compiler {
static final _logger = Logger('ExpressionCompilerService');
final StreamQueue<dynamic> _responseQueue;
final ReceivePort _receivePort;
final SendPort _sendPort;
Future<void>? _dependencyUpdate;
_Compiler._(
this._responseQueue,
this._receivePort,
this._sendPort,
);
/// Sends [request] on [_sendPort] and returns the next event from the
/// response stream.
Future<Map<String, dynamic>> _send(Map<String, Object> request) async {
_sendPort.send(request);
if (!await _responseQueue.hasNext) {
return {
'succeeded': false,
'errors': ['compilation worker response stream closed'],
};
}
final response = await _responseQueue.next;
if (response is! Map<String, dynamic>) {
return {
'succeeded': false,
'errors': ['compilation worker returned invalid response: $response'],
};
}
return response;
}
/// Starts expression compilation service.
///
/// Starts expression compiler worker in an isolate and creates the
/// expression compilation service that communicates to the worker.
///
/// [sdkConfiguration] describes the locations of SDK files used in
/// expression compilation (summaries, libraries spec, compiler worker
/// snapshot).
///
/// [soundNullSafety] indicates if the compiler should support sound
/// null safety.
///
/// Performs handshake with the isolate running expression compiler
/// worker to establish communication via send/receive ports, returns
/// the service after the communication is established.
///
/// Users need to stop the service by calling [stop].
static Future<_Compiler> start(
String address,
int port,
SdkConfiguration sdkConfiguration,
CompilerOptions compilerOptions,
bool verbose,
) async {
sdkConfiguration.validateSdkDir();
if (compilerOptions.soundNullSafety) {
sdkConfiguration.validateSoundSummaries();
} else {
sdkConfiguration.validateWeakSummaries();
}
final workerUri = sdkConfiguration.compilerWorkerUri!;
final sdkSummaryUri = compilerOptions.soundNullSafety
? sdkConfiguration.soundSdkSummaryUri!
: sdkConfiguration.weakSdkSummaryUri!;
final args = [
'--experimental-expression-compiler',
'--dart-sdk-summary',
'$sdkSummaryUri',
'--asset-server-address',
address,
'--asset-server-port',
'$port',
'--module-format',
compilerOptions.moduleFormat,
if (verbose) '--verbose',
compilerOptions.soundNullSafety
? '--sound-null-safety'
: '--no-sound-null-safety',
for (final experiment in compilerOptions.experiments)
'--enable-experiment=$experiment',
if (compilerOptions.canaryFeatures) '--canary',
];
_logger.info('Starting...');
_logger.finest('$workerUri ${args.join(' ')}');
final receivePort = ReceivePort();
await Isolate.spawnUri(
workerUri,
args,
receivePort.sendPort,
// Note(annagrin): ddc snapshot is generated with no asserts, so we have
// to run it unchecked in case the calling isolate is checked, as it
// happens, for example, when debugging webdev in VSCode or running tests
// using 'dart run'
checked: false,
);
final responseQueue = StreamQueue(receivePort);
final sendPort = await responseQueue.next as SendPort;
final service = _Compiler._(responseQueue, receivePort, sendPort);
return service;
}
Future<bool> updateDependencies(Map<String, ModuleInfo> modules) async {
final updateCompleter = Completer();
_dependencyUpdate = updateCompleter.future;
_logger.info('Updating dependencies...');
_logger.finest('Dependencies: $modules');
final response = await _send({
'command': 'UpdateDeps',
'inputs': [
for (var moduleName in modules.keys)
{
'path': modules[moduleName]!.fullDillPath,
'summaryPath': modules[moduleName]!.summaryPath,
'moduleName': moduleName,
},
],
});
final result = (response['succeeded'] as bool?) ?? false;
if (result) {
_logger.info('Updated dependencies.');
} else {
final errors = response['errors'];
final exception = response['exception'];
final s = response['stackTrace'] as String?;
final stackTrace = s == null ? null : StackTrace.fromString(s);
_logger.severe(
'Failed to update dependencies: $errors',
exception,
stackTrace,
);
}
updateCompleter.complete();
return result;
}
Future<ExpressionCompilationResult> compileExpressionToJs(
String libraryUri,
String scriptUri,
int line,
int column,
Map<String, String> jsModules,
Map<String, String> jsFrameValues,
String moduleName,
String expression,
) async {
_logger.finest('Waiting for dependencies to update');
if (_dependencyUpdate == null) {
_logger
.warning('Dependencies are not updated before compiling expressions');
return ExpressionCompilationResult('<compiler is not ready>', true);
}
await _dependencyUpdate;
_logger.finest('Compiling "$expression" at $libraryUri:$line');
final response = await _send({
'command': 'CompileExpression',
'expression': expression,
'line': line,
'column': column,
'jsModules': jsModules,
'jsScope': jsFrameValues,
'libraryUri': libraryUri,
'moduleName': moduleName,
});
final error = _createErrorMsg(response);
final procedure = (response['compiledProcedure'] as String?) ?? '';
final succeeded = (response['succeeded'] as bool?) ?? false;
final result = succeeded ? procedure : error;
if (succeeded) {
_logger.finest('Compiled "$expression" to: $result');
} else {
_logger.finest('Failed to compile "$expression": $result');
}
return ExpressionCompilationResult(result, !succeeded);
}
String _createErrorMsg(Map<String, dynamic> response) {
final errors = response['errors'] as List<String>?;
if (errors != null && errors.isNotEmpty) return errors.first;
final e = response['exception'];
final s = response['stackTrace'];
return e != null ? '$e:$s' : '<unknown error>';
}
/// Stops the service.
///
/// Terminates the isolate running expression compiler worker
/// and marks the service as stopped.
void stop() {
_sendPort.send({'command': 'Shutdown'});
_receivePort.close();
_logger.info('Stopped.');
}
}
/// Service that handles expression compilation requests.
///
/// Expression compiler service spawns a dartdevc in expression compilation
/// mode in an isolate and communicates with the isolate via send/receive
/// ports. It also handles full dill file read requests from the isolate
/// and redirects them to the asset server.
///
/// Uses [_address] and [_port] to communicate and to redirect asset
/// requests to the asset server.
///
/// Configuration created by [_sdkConfigurationProvider] describes the
/// locations of SDK files used in expression compilation (summaries,
/// libraries spec, compiler worker snapshot).
///
/// Users need to stop the service by calling [stop].
class ExpressionCompilerService implements ExpressionCompiler {
final _compiler = Completer<_Compiler>();
final String _address;
final FutureOr<int> _port;
final bool _verbose;
final SdkConfigurationProvider sdkConfigurationProvider;
ExpressionCompilerService(
this._address,
this._port, {
bool verbose = false,
required this.sdkConfigurationProvider,
}) : _verbose = verbose;
@override
Future<ExpressionCompilationResult> compileExpressionToJs(
String isolateId,
String libraryUri,
String scriptUri,
int line,
int column,
Map<String, String> jsModules,
Map<String, String> jsFrameValues,
String moduleName,
String expression,
) async =>
(await _compiler.future).compileExpressionToJs(
libraryUri,
scriptUri,
line,
column,
jsModules,
jsFrameValues,
moduleName,
expression,
);
@override
Future<void> initialize(CompilerOptions options) async {
if (_compiler.isCompleted) return;
final compiler = await _Compiler.start(
_address,
await _port,
await sdkConfigurationProvider.configuration,
options,
_verbose,
);
_compiler.complete(compiler);
}
@override
Future<bool> updateDependencies(Map<String, ModuleInfo> modules) async =>
(await _compiler.future).updateDependencies(modules);
Future<void> stop() async {
if (_compiler.isCompleted) return (await _compiler.future).stop();
}
}