1
0
mirror of https://github.com/dart-lang/sdk synced 2024-07-01 07:14:29 +00:00

add package:_macros (SDK vendored) and package:macros (pub published)

add sdk_packages.yaml file (describes SDK vendored package locations)

delete old macro code in _fe_analyzer_shared, move tests/benchmarks

adds a top level `pkg` directory to the Dart SDK, which is where vendored packages live

BUG: https://github.com/dart-lang/sdk/issues/54976
Change-Id: Ib3503a27fb5644fa8a39ab5a3e5b568df330cfd6
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/359040
Auto-Submit: Jake Macdonald <jakemac@google.com>
Reviewed-by: Konstantin Shcheglov <scheglov@google.com>
Reviewed-by: Jonas Termansen <sortie@google.com>
Reviewed-by: Johnni Winther <johnniwinther@google.com>
Reviewed-by: Bob Nystrom <rnystrom@google.com>
Commit-Queue: Jake Macdonald <jakemac@google.com>
Reviewed-by: Devon Carew <devoncarew@google.com>
This commit is contained in:
Konstantin Shcheglov 2024-03-26 18:40:00 +00:00 committed by Commit Queue
parent 0bcb0c934d
commit 36c0788137
192 changed files with 3216 additions and 1095 deletions

2
OWNERS
View File

@ -15,7 +15,7 @@ per-file DEPS=file:/tools/OWNERS_ENG
per-file CHANGELOG.md,AUTHORS,WATCHLISTS,.gitattributes,.gitconfig,.gitignore,sdk.code-workspace=* per-file CHANGELOG.md,AUTHORS,WATCHLISTS,.gitattributes,.gitconfig,.gitignore,sdk.code-workspace=*
# Product documentation # Product documentation
per-file CONTRIBUTING.md,LICENSE,PATENT_GRANT,README.*,SECURITY.md=file:/tools/OWNERS_PRODUCT per-file CONTRIBUTING.md,LICENSE,PATENT_GRANT,README.*,SECURITY.md,sdk_packages.yaml=file:/tools/OWNERS_PRODUCT
# Top level build files # Top level build files
per-file .clang-format,.gn,BUILD.gn,sdk_args.gni=file:/tools/OWNERS_BUILD per-file .clang-format,.gn,BUILD.gn,sdk_args.gni=file:/tools/OWNERS_BUILD

View File

@ -0,0 +1,554 @@
// Copyright (c) 2021, 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:typed_data';
/// A push based object serialization interface.
abstract class Serializer {
/// Serializes a [String].
void addString(String value);
/// Serializes a nullable [String].
void addNullableString(String? value) =>
value == null ? addNull() : addString(value);
/// Serializes a [double].
void addDouble(double value);
/// Serializes a nullable [double].
void addNullableDouble(double? value) =>
value == null ? addNull() : addDouble(value);
/// Serializes an [int].
void addInt(int value);
/// Serializes a nullable [int].
void addNullableInt(int? value) => value == null ? addNull() : addInt(value);
/// Serializes a [bool].
void addBool(bool value);
/// Serializes a nullable [bool].
void addNullableBool(bool? value) =>
value == null ? addNull() : addBool(value);
/// Serializes a `null` literal.
void addNull();
/// Used to signal the start of an arbitrary length list of items.
void startList();
/// Used to signal the end of an arbitrary length list of items.
void endList();
/// Returns the resulting serialized object.
Object get result;
}
/// A pull based object deserialization interface.
///
/// You must call [moveNext] before reading any items, and in order to advance
/// to the next item.
abstract class Deserializer {
/// Checks if the current value is a null, returns `true` if so and `false`
/// otherwise.
bool checkNull();
/// Reads the current value as a non-nullable [String].
bool expectBool();
/// Reads the current value as a nullable [bool].
bool? expectNullableBool() => checkNull() ? null : expectBool();
/// Reads the current value as a non-nullable [double].
double expectDouble();
/// Reads the current value as a nullable [double].
double? expectNullableDouble() => checkNull() ? null : expectDouble();
/// Reads the current value as a non-nullable [int].
int expectInt();
/// Reads the current value as a nullable [int].
int? expectNullableInt() => checkNull() ? null : expectInt();
/// Reads the current value as a non-nullable [String].
String expectString();
/// Reads the current value as a nullable [String].
String? expectNullableString() => checkNull() ? null : expectString();
/// Asserts that the current item is the start of a list.
///
/// An example for how to read from a list is as follows:
///
/// var json = JsonReader.fromString(source);
/// I know it's a list of strings.
///
/// ```
/// var result = <String>[];
/// deserializer.moveNext();
/// deserializer.expectList();
/// while (json.moveNext()) {
/// result.add(json.expectString());
/// }
/// // Can now read later items, but need to call `moveNext` again to move
/// // past the list.
/// deserializer.moveNext();
/// deserializer.expectBool();
/// ```
void expectList();
/// Moves to the next item, returns `false` if there are no more items to
/// read.
///
/// If inside of a list, this returns `false` when the end of the list is
/// reached, and moves back to the parent, but does not advance it, so another
/// call to `moveNext` is needed. See example in the [expectList] docs.
bool moveNext();
}
class ByteDataSerializer extends Serializer {
final BytesBuilder _builder = new BytesBuilder();
// Re-usable 8 byte list and view for encoding doubles.
final Uint8List _eightByteList = new Uint8List(8);
late final ByteData _eightByteListData =
new ByteData.sublistView(_eightByteList);
@override
void addBool(bool value) => _builder
.addByte(value ? DataKind.boolTrue.index : DataKind.boolFalse.index);
@override
void addDouble(double value) {
_eightByteListData.setFloat64(0, value);
_builder
..addByte(DataKind.float64.index)
..add(_eightByteList);
}
@override
void addNull() => _builder.addByte(DataKind.nil.index);
@override
void addInt(int value) {
if (value >= 0x0) {
assert(DataKind.values.length < 0xff);
if (value <= 0xff - DataKind.values.length) {
_builder.addByte(value + DataKind.values.length);
} else if (value <= 0xff) {
_builder
..addByte(DataKind.uint8.index)
..addByte(value);
} else if (value <= 0xffff) {
_builder
..addByte(DataKind.uint16.index)
..addByte(value >> 8)
..addByte(value);
} else if (value <= 0xffffffff) {
_builder
..addByte(DataKind.uint32.index)
..addByte(value >> 24)
..addByte(value >> 16)
..addByte(value >> 8)
..addByte(value);
} else {
_builder
..addByte(DataKind.uint64.index)
..addByte(value >> 56)
..addByte(value >> 48)
..addByte(value >> 40)
..addByte(value >> 32)
..addByte(value >> 24)
..addByte(value >> 16)
..addByte(value >> 8)
..addByte(value);
}
} else {
if (value >= -0x80) {
_builder
..addByte(DataKind.int8.index)
..addByte(value);
} else if (value >= -0x8000) {
_builder
..addByte(DataKind.int16.index)
..addByte(value >> 8)
..addByte(value);
} else if (value >= -0x8000000) {
_builder
..addByte(DataKind.int32.index)
..addByte(value >> 24)
..addByte(value >> 16)
..addByte(value >> 8)
..addByte(value);
} else {
_builder
..addByte(DataKind.int64.index)
..addByte(value >> 56)
..addByte(value >> 48)
..addByte(value >> 40)
..addByte(value >> 32)
..addByte(value >> 24)
..addByte(value >> 16)
..addByte(value >> 8)
..addByte(value);
}
}
}
@override
void addString(String value) {
for (int i = 0; i < value.length; i++) {
if (value.codeUnitAt(i) > 0xff) {
_addTwoByteString(value);
return;
}
}
_addOneByteString(value);
}
void _addOneByteString(String value) {
_builder.addByte(DataKind.oneByteString.index);
addInt(value.length);
for (int i = 0; i < value.length; i++) {
_builder.addByte(value.codeUnitAt(i));
}
}
void _addTwoByteString(String value) {
_builder.addByte(DataKind.twoByteString.index);
addInt(value.length);
for (int i = 0; i < value.length; i++) {
int codeUnit = value.codeUnitAt(i);
switch (Endian.host) {
case Endian.little:
_builder
..addByte(codeUnit)
..addByte(codeUnit >> 8);
break;
case Endian.big:
_builder
..addByte(codeUnit >> 8)
..addByte(codeUnit);
break;
}
}
}
@override
void startList() => _builder.addByte(DataKind.startList.index);
@override
void endList() => _builder.addByte(DataKind.endList.index);
/// Used to signal the start of an arbitrary length list of map entries.
void startMap() => _builder.addByte(DataKind.startMap.index);
/// Used to signal the end of an arbitrary length list of map entries.
void endMap() => _builder.addByte(DataKind.endMap.index);
/// Serializes a [Uint8List].
void addUint8List(Uint8List value) {
_builder.addByte(DataKind.uint8List.index);
addInt(value.length);
_builder.add(value);
}
/// Serializes an object with arbitrary structure. It supports `bool`,
/// `int`, `String`, `null`, `Uint8List`, `List`, `Map`.
void addAny(Object? value) {
if (value == null) {
addNull();
} else if (value is bool) {
addBool(value);
} else if (value is int) {
addInt(value);
} else if (value is String) {
addString(value);
} else if (value is Uint8List) {
addUint8List(value);
} else if (value is List) {
startList();
value.forEach(addAny);
endList();
} else if (value is Map) {
startMap();
for (MapEntry<Object?, Object?> entry in value.entries) {
addAny(entry.key);
addAny(entry.value);
}
endMap();
} else {
throw new ArgumentError('(${value.runtimeType}) $value');
}
}
@override
Uint8List get result => _builder.takeBytes();
}
class ByteDataDeserializer extends Deserializer {
final ByteData _bytes;
int _byteOffset = 0;
int? _byteOffsetIncrement = 0;
ByteDataDeserializer(this._bytes);
/// Reads the next [DataKind] and advances [_byteOffset].
DataKind _readKind([int offset = 0]) {
int value = _bytes.getUint8(_byteOffset + offset);
if (value < DataKind.values.length) {
return DataKind.values[value];
} else {
return DataKind.directEncodedUint8;
}
}
@override
bool checkNull() {
_byteOffsetIncrement = 1;
return _readKind() == DataKind.nil;
}
@override
bool expectBool() {
DataKind kind = _readKind();
_byteOffsetIncrement = 1;
if (kind == DataKind.boolTrue) {
return true;
} else if (kind == DataKind.boolFalse) {
return false;
} else {
throw new StateError('Expected a bool but found a $kind');
}
}
@override
double expectDouble() {
DataKind kind = _readKind();
if (kind != DataKind.float64) {
throw new StateError('Expected a double but found a $kind');
}
_byteOffsetIncrement = 9;
return _bytes.getFloat64(_byteOffset + 1);
}
@override
int expectInt() => _expectInt(0);
int _expectInt(int offset) {
DataKind kind = _readKind(offset);
if (kind == DataKind.directEncodedUint8) {
_byteOffsetIncrement = offset + 1;
return _bytes.getUint8(_byteOffset + offset) - DataKind.values.length;
}
offset += 1;
int result;
switch (kind) {
case DataKind.int8:
result = _bytes.getInt8(_byteOffset + offset);
_byteOffsetIncrement = 1 + offset;
break;
case DataKind.int16:
result = _bytes.getInt16(_byteOffset + offset);
_byteOffsetIncrement = 2 + offset;
break;
case DataKind.int32:
result = _bytes.getInt32(_byteOffset + offset);
_byteOffsetIncrement = 4 + offset;
break;
case DataKind.int64:
result = _bytes.getInt64(_byteOffset + offset);
_byteOffsetIncrement = 8 + offset;
break;
case DataKind.uint8:
result = _bytes.getUint8(_byteOffset + offset);
_byteOffsetIncrement = 1 + offset;
break;
case DataKind.uint16:
result = _bytes.getUint16(_byteOffset + offset);
_byteOffsetIncrement = 2 + offset;
break;
case DataKind.uint32:
result = _bytes.getUint32(_byteOffset + offset);
_byteOffsetIncrement = 4 + offset;
break;
case DataKind.uint64:
result = _bytes.getUint64(_byteOffset + offset);
_byteOffsetIncrement = 8 + offset;
break;
default:
throw new StateError('Expected an int but found a $kind');
}
return result;
}
@override
void expectList() {
DataKind kind = _readKind();
if (kind != DataKind.startList) {
throw new StateError('Expected the start to a list but found a $kind');
}
_byteOffsetIncrement = 1;
}
/// Asserts that the current item is the start of a map.
///
/// An example for how to read from a map is as follows:
///
/// I know it's a map of ints to strings.
///
/// ```
/// var result = <int, String>[];
/// deserializer.expectMap();
/// while (deserializer.moveNext()) {
/// var key = deserializer.expectInt();
/// deserializer.next();
/// var value = deserializer.expectString();
/// result[key] = value;
/// }
/// // We have already called `moveNext` to move past the map.
/// deserializer.expectBool();
/// ```
void expectMap() {
DataKind kind = _readKind();
if (kind != DataKind.startMap) {
throw new StateError('Expected the start to a map but found a $kind');
}
_byteOffsetIncrement = 1;
}
@override
String expectString() {
DataKind kind = _readKind();
int length = _expectInt(1);
int offset = _byteOffsetIncrement! + _byteOffset;
if (kind == DataKind.oneByteString) {
_byteOffsetIncrement = _byteOffsetIncrement! + length;
return new String.fromCharCodes(
_bytes.buffer.asUint8List(offset, length));
} else if (kind == DataKind.twoByteString) {
length = length * 2;
_byteOffsetIncrement = _byteOffsetIncrement! + length;
Uint8List bytes =
new Uint8List.fromList(_bytes.buffer.asUint8List(offset, length));
return new String.fromCharCodes(bytes.buffer.asUint16List());
} else {
throw new StateError('Expected a string but found a $kind');
}
}
/// Reads the current value as [Uint8List].
Uint8List expectUint8List() {
_byteOffsetIncrement = 1;
moveNext();
int length = expectInt();
int offset = _byteOffset + _byteOffsetIncrement!;
_byteOffsetIncrement = _byteOffsetIncrement! + length;
return _bytes.buffer.asUint8List(offset, length);
}
/// Reads the current value as an object of arbitrary structure.
Object? expectAny() {
const Set<DataKind> boolKinds = {
DataKind.boolFalse,
DataKind.boolTrue,
};
const Set<DataKind> intKinds = {
DataKind.directEncodedUint8,
DataKind.int8,
DataKind.int16,
DataKind.int32,
DataKind.int64,
DataKind.uint8,
DataKind.uint16,
DataKind.uint32,
DataKind.uint64,
};
const Set<DataKind> stringKinds = {
DataKind.oneByteString,
DataKind.twoByteString,
};
DataKind kind = _readKind();
if (boolKinds.contains(kind)) {
return expectBool();
} else if (kind == DataKind.nil) {
checkNull();
return null;
} else if (intKinds.contains(kind)) {
return expectInt();
} else if (stringKinds.contains(kind)) {
return expectString();
} else if (kind == DataKind.startList) {
List<Object?> result = [];
expectList();
while (moveNext()) {
Object? element = expectAny();
result.add(element);
}
return result;
} else if (kind == DataKind.startMap) {
Map<Object?, Object?> result = {};
expectMap();
while (moveNext()) {
Object? key = expectAny();
moveNext();
Object? value = expectAny();
result[key] = value;
}
return result;
} else if (kind == DataKind.uint8List) {
return expectUint8List();
} else {
throw new StateError('Expected: $kind');
}
}
@override
bool moveNext() {
int? increment = _byteOffsetIncrement;
_byteOffsetIncrement = null;
if (increment == null) {
throw new StateError("Can't move until consuming the current element");
}
_byteOffset += increment;
if (_byteOffset >= _bytes.lengthInBytes) {
return false;
} else if (_readKind() == DataKind.endList ||
_readKind() == DataKind.endMap) {
// You don't explicitly consume list/map end markers.
_byteOffsetIncrement = 1;
return false;
} else {
return true;
}
}
}
enum DataKind {
nil,
boolTrue,
boolFalse,
directEncodedUint8, // Encoded in the kind byte.
startList,
endList,
startMap,
endMap,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float64,
oneByteString,
twoByteString,
uint8List,
}

View File

@ -6,8 +6,8 @@ import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:_fe_analyzer_shared/src/macros/executor/message_grouper.dart'; import 'message_grouper.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'; import 'byte_data_serializer.dart';
/// Channel for exchanging requests and responses over [Socket]. /// Channel for exchanging requests and responses over [Socket].
class RequestChannel { class RequestChannel {

View File

@ -15,6 +15,7 @@ dependencies:
# See also https://dart.dev/tools/pub/dependencies. # See also https://dart.dev/tools/pub/dependencies.
dev_dependencies: dev_dependencies:
checks: any checks: any
macros: any
test: any test: any
dependency_overrides: dependency_overrides:

View File

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
const Map<String, ClassData> expectedClassData = { const Map<String, ClassData> expectedClassData = {
'Class1': ClassData(fieldsOf: ['field1'], constructorsOf: ['']), 'Class1': ClassData(fieldsOf: ['field1'], constructorsOf: ['']),

View File

@ -3,7 +3,7 @@
// BSD-style license that can be found in the LICENSE file. // BSD-style license that can be found in the LICENSE file.
import 'dart:async'; import 'dart:async';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
import 'api_test_expectations.dart'; import 'api_test_expectations.dart';
macro macro

View File

@ -11,8 +11,14 @@
"packageUri": "lib/" "packageUri": "lib/"
}, },
{ {
"name": "_fe_analyzer_shared", "name": "macros",
"rootUri": "../../../../_fe_analyzer_shared/lib/" "rootUri": "../../../../macros/",
"packageUri": "lib/"
},
{
"name": "_macros",
"rootUri": "../../../../_macros/",
"packageUri": "lib/"
} }
] ]
} }

View File

@ -6,7 +6,7 @@ import 'dart:io';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:_fe_analyzer_shared/src/macros/compiler/request_channel.dart'; import 'package:_fe_analyzer_shared/src/macros/compiler/request_channel.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'; import 'package:_fe_analyzer_shared/src/macros/compiler/byte_data_serializer.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
main() { main() {

3
pkg/_macros/CHANGELOG.md Normal file
View File

@ -0,0 +1,3 @@
## 0.1.0
Initial release, copied from `_fe_analyzer_shared/lib/src/macros`.

View File

@ -0,0 +1,44 @@
## Required steps when updating this package
Whenever any change to the `lib` directory of this package is made, the
following procedure **must** be followed.
### Update pubspec/changelog for each release.
Because this is an SDK vendored package, every change is treated as a release,
and must have a stable version number and CHANGELOG.md entry.
### Update and publish `package:macros`
Additionally, the pub package `macros`, which lives at `pkg/macros`, must have
a corresponding release on pub for each version of this package.
The version of the `_macros` dependency in its pubspec must be updated to match
the new version of this package, and the pubspec version and changelog should be
updated.
These changes to the `macros` package should be landed in the same CL as the
changes to this package, and it should be immediately published when the CL is
merged. These should be marked as pre-release versions (with the `-main.x`
suffix), and stable versions will only be published when the beta SDK has been
released (exact process is TBD, possibly could do it as a hotfix, or publish
from a branch).
It is possible that multiple breaking changes can land within the same major
version of this package, during the pre-release period. Version compatibility is
thus **not** guaranteed on the dev or main channels, only the beta and stable
channels.
## Special considerations for this package
This package should generally be treated like a `dart:` library, since only
exactly one version of it ships with any SDK. That has several implications.
### Must follow breaking change process
Any breaking change to this package should follow the same breaking change
process as any change to the `dart:` libraries.
In general any breaking change made here can result in users not being able to
get a version solve on the newest SDK, if their macro dependencies have not yet
updated to the latest version.

27
pkg/_macros/LICENSE Normal file
View File

@ -0,0 +1,27 @@
Copyright 2024, the Dart project authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

1
pkg/_macros/OWNERS Normal file
View File

@ -0,0 +1 @@
file:/tools/OWNERS_FOUNDATION

View File

@ -8,8 +8,8 @@ import 'dart:io';
import 'dart:isolate'; import 'dart:isolate';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:_fe_analyzer_shared/src/macros/executor/message_grouper.dart'; import 'package:_macros/src/executor/message_grouper.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'; import 'package:_macros/src/executor/serialization.dart';
void main() async { void main() async {
for (var serializationMode in [ for (var serializationMode in [
@ -51,7 +51,7 @@ Future<void> _isolateSpawnBenchmarks() async {
final sendPortCompleter = Completer<SendPort>(); final sendPortCompleter = Completer<SendPort>();
receivePort.listen((data) { receivePort.listen((data) {
if (!sendPortCompleter.isCompleted) { if (!sendPortCompleter.isCompleted) {
sendPortCompleter.complete(data); sendPortCompleter.complete(data as SendPort);
} else { } else {
responseCompleter!.complete(data); responseCompleter!.complete(data);
} }
@ -97,7 +97,7 @@ Future<void> _isolateSpawnUriBenchmarks() async {
final sendPortCompleter = Completer<SendPort>(); final sendPortCompleter = Completer<SendPort>();
receivePort.listen((data) { receivePort.listen((data) {
if (!sendPortCompleter.isCompleted) { if (!sendPortCompleter.isCompleted) {
sendPortCompleter.complete(data); sendPortCompleter.complete(data as SendPort);
} else { } else {
responseCompleter!.complete(data); responseCompleter!.complete(data);
} }
@ -137,7 +137,7 @@ Future<void> _separateProcessStdioBenchmarks() async {
var file = File(tmpDir.uri.resolve('main.dart').toFilePath()); var file = File(tmpDir.uri.resolve('main.dart').toFilePath());
file.writeAsStringSync(childProgram(serializationMode)); file.writeAsStringSync(childProgram(serializationMode));
var process = await Process.start(Platform.resolvedExecutable, [ var process = await Process.start(Platform.resolvedExecutable, [
'--packages=' + (await Isolate.packageConfig)!.toFilePath(), '--packages=${(await Isolate.packageConfig)!.toFilePath()}',
file.path, file.path,
]); ]);
@ -184,7 +184,9 @@ Future<void> _separateProcessStdioBenchmarks() async {
} }
print('Separate process + Stdio + $serializationMode: ${watch.elapsed}'); print('Separate process + Stdio + $serializationMode: ${watch.elapsed}');
listeners.forEach((l) => l.cancel()); for (var listener in listeners) {
listener.cancel();
}
process.kill(); process.kill();
} catch (e, s) { } catch (e, s) {
print('Error running benchmark \n$e\n\n$s'); print('Error running benchmark \n$e\n\n$s');
@ -215,7 +217,7 @@ Future<void> _separateProcessSocketBenchmarks() async {
}); });
var process = await Process.start(Platform.resolvedExecutable, [ var process = await Process.start(Platform.resolvedExecutable, [
'--packages=' + (await Isolate.packageConfig)!.toFilePath(), '--packages=${(await Isolate.packageConfig)!.toFilePath()}',
file.path, file.path,
serverSocket.address.address, serverSocket.address.address,
serverSocket.port.toString(), serverSocket.port.toString(),
@ -270,7 +272,9 @@ Future<void> _separateProcessSocketBenchmarks() async {
} }
print('Separate process + Socket + $serializationMode: ${watch.elapsed}'); print('Separate process + Socket + $serializationMode: ${watch.elapsed}');
listeners.forEach((l) => l.cancel()); for (var listener in listeners) {
listener.cancel();
}
process.kill(); process.kill();
await serverSocket.close(); await serverSocket.close();
client.destroy(); client.destroy();
@ -284,7 +288,7 @@ Future<void> _separateProcessSocketBenchmarks() async {
void _writeLength(List<int> result, BytesBuilder bytesBuilder) { void _writeLength(List<int> result, BytesBuilder bytesBuilder) {
int length = (result as Uint8List).lengthInBytes; int length = (result as Uint8List).lengthInBytes;
if (length > 0xffffffff) { if (length > 0xffffffff) {
throw new StateError('Message was larger than the allowed size!'); throw StateError('Message was larger than the allowed size!');
} }
bytesBuilder.add([ bytesBuilder.add([
length >> 24 & 0xff, length >> 24 & 0xff,

View File

@ -139,8 +139,7 @@ sealed class TypeAnnotationCode implements Code, TypeAnnotation {
/// of this one. /// of this one.
/// ///
/// Returns the current instance if it is already nullable. /// Returns the current instance if it is already nullable.
NullableTypeAnnotationCode get asNullable => NullableTypeAnnotationCode get asNullable => NullableTypeAnnotationCode(this);
new NullableTypeAnnotationCode(this);
/// Whether or not this type is nullable. /// Whether or not this type is nullable.
@override @override
@ -352,8 +351,7 @@ final class RawTypeAnnotationCode extends RawCode
/// ///
/// Returns the current instance if it is already nullable. /// Returns the current instance if it is already nullable.
@override @override
NullableTypeAnnotationCode get asNullable => NullableTypeAnnotationCode get asNullable => NullableTypeAnnotationCode(this);
new NullableTypeAnnotationCode(this);
RawTypeAnnotationCode._(super.parts) : super.fromParts(); RawTypeAnnotationCode._(super.parts) : super.fromParts();
@ -368,7 +366,7 @@ final class RawTypeAnnotationCode extends RawCode
static TypeAnnotationCode fromParts(List<Object> parts) { static TypeAnnotationCode fromParts(List<Object> parts) {
bool wasNullable; bool wasNullable;
(wasNullable, parts) = _makeNonNullable(parts); (wasNullable, parts) = _makeNonNullable(parts);
TypeAnnotationCode code = new RawTypeAnnotationCode._(parts); TypeAnnotationCode code = RawTypeAnnotationCode._(parts);
if (wasNullable) code = code.asNullable; if (wasNullable) code = code.asNullable;
return code; return code;
} }
@ -394,7 +392,7 @@ final class RawTypeAnnotationCode extends RawCode
switch (current) { switch (current) {
case String(): case String():
if (current.trimRight() != current) { if (current.trimRight() != current) {
throw new ArgumentError( throw ArgumentError(
'Invalid type annotation, type annotations should not end with ' 'Invalid type annotation, type annotations should not end with '
'whitespace but got `$current`.'); 'whitespace but got `$current`.');
} else if (current.isEmpty) { } else if (current.isEmpty) {
@ -421,7 +419,7 @@ final class RawTypeAnnotationCode extends RawCode
return (false, parts); return (false, parts);
} }
} }
throw new ArgumentError('The empty string is not a valid type annotation.'); throw ArgumentError('The empty string is not a valid type annotation.');
} }
} }

View File

@ -26,7 +26,7 @@ class Diagnostic {
Diagnostic(this.message, this.severity, Diagnostic(this.message, this.severity,
{List<DiagnosticMessage> contextMessages = const [], {List<DiagnosticMessage> contextMessages = const [],
this.correctionMessage}) this.correctionMessage})
: contextMessages = new UnmodifiableListView(contextMessages); : contextMessages = UnmodifiableListView(contextMessages);
} }
/// A message and optional target for a [Diagnostic] reported by a [Macro]. /// A message and optional target for a [Diagnostic] reported by a [Macro].
@ -60,7 +60,7 @@ final class DeclarationDiagnosticTarget extends DiagnosticTarget {
/// [Declaration]. /// [Declaration].
extension DeclarationAsTarget on Declaration { extension DeclarationAsTarget on Declaration {
DeclarationDiagnosticTarget get asDiagnosticTarget => DeclarationDiagnosticTarget get asDiagnosticTarget =>
new DeclarationDiagnosticTarget(this); DeclarationDiagnosticTarget(this);
} }
/// A [DiagnosticMessage] target which is a [TypeAnnotation]. /// A [DiagnosticMessage] target which is a [TypeAnnotation].
@ -74,7 +74,7 @@ final class TypeAnnotationDiagnosticTarget extends DiagnosticTarget {
/// [TypeAnnotation]. /// [TypeAnnotation].
extension TypeAnnotationAsTarget on TypeAnnotation { extension TypeAnnotationAsTarget on TypeAnnotation {
TypeAnnotationDiagnosticTarget get asDiagnosticTarget => TypeAnnotationDiagnosticTarget get asDiagnosticTarget =>
new TypeAnnotationDiagnosticTarget(this); TypeAnnotationDiagnosticTarget(this);
} }
/// A [DiagnosticMessage] target which is a [MetadataAnnotation]. /// A [DiagnosticMessage] target which is a [MetadataAnnotation].
@ -86,7 +86,7 @@ final class MetadataAnnotationDiagnosticTarget extends DiagnosticTarget {
extension MetadataAnnotationAsTarget on MetadataAnnotation { extension MetadataAnnotationAsTarget on MetadataAnnotation {
MetadataAnnotationDiagnosticTarget get asDiagnosticTarget => MetadataAnnotationDiagnosticTarget get asDiagnosticTarget =>
new MetadataAnnotationDiagnosticTarget(this); MetadataAnnotationDiagnosticTarget(this);
} }
/// The severities supported for [Diagnostic]s. /// The severities supported for [Diagnostic]s.

View File

@ -16,8 +16,8 @@ import 'executor/serialization.dart'
String bootstrapMacroIsolate( String bootstrapMacroIsolate(
Map<String, Map<String, List<String>>> macroDeclarations, Map<String, Map<String, List<String>>> macroDeclarations,
SerializationMode serializationMode) { SerializationMode serializationMode) {
StringBuffer imports = new StringBuffer(); StringBuffer imports = StringBuffer();
StringBuffer constructorEntries = new StringBuffer(); StringBuffer constructorEntries = StringBuffer();
macroDeclarations macroDeclarations
.forEach((String macroImport, Map<String, List<String>> macroClasses) { .forEach((String macroImport, Map<String, List<String>> macroClasses) {
imports.writeln('import \'$macroImport\';'); imports.writeln('import \'$macroImport\';');
@ -47,8 +47,8 @@ const String template = '''
import 'dart:io'; import 'dart:io';
import 'dart:isolate'; import 'dart:isolate';
import 'package:_fe_analyzer_shared/src/macros/executor/client.dart'; import 'package:_macros/src/executor/client.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'; import 'package:_macros/src/executor/serialization.dart';
$_importMarker $_importMarker

View File

@ -0,0 +1,6 @@
// Copyright (c) 2024, 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.
export 'executor/client.dart';
export 'executor/serialization.dart';

View File

@ -2,12 +2,9 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/executor/serialization_extensions.dart'; import 'executor/serialization_extensions.dart';
import 'package:meta/meta.dart';
import 'api.dart'; import 'api.dart';
// ignore: unused_import
import 'bootstrap.dart'; // For doc comments only.
import 'executor/cast.dart'; import 'executor/cast.dart';
import 'executor/introspection_impls.dart'; import 'executor/introspection_impls.dart';
import 'executor/serialization.dart'; import 'executor/serialization.dart';

View File

@ -23,34 +23,32 @@ sealed class Argument implements Serializable {
final ArgumentKind kind = ArgumentKind.values[deserializer.expectInt()]; final ArgumentKind kind = ArgumentKind.values[deserializer.expectInt()];
return switch (kind) { return switch (kind) {
ArgumentKind.string => ArgumentKind.string =>
new StringArgument((deserializer..moveNext()).expectString()), StringArgument((deserializer..moveNext()).expectString()),
ArgumentKind.bool => ArgumentKind.bool =>
new BoolArgument((deserializer..moveNext()).expectBool()), BoolArgument((deserializer..moveNext()).expectBool()),
ArgumentKind.double => ArgumentKind.double =>
new DoubleArgument((deserializer..moveNext()).expectDouble()), DoubleArgument((deserializer..moveNext()).expectDouble()),
ArgumentKind.int => ArgumentKind.int => IntArgument((deserializer..moveNext()).expectInt()),
new IntArgument((deserializer..moveNext()).expectInt()),
ArgumentKind.list || ArgumentKind.list ||
ArgumentKind.set => ArgumentKind.set =>
new _IterableArgument._deserialize(kind, deserializer), _IterableArgument._deserialize(kind, deserializer),
ArgumentKind.map => new MapArgument._deserialize(deserializer), ArgumentKind.map => MapArgument._deserialize(deserializer),
ArgumentKind.nil => new NullArgument(), ArgumentKind.nil => NullArgument(),
ArgumentKind.typeAnnotation => new TypeAnnotationArgument( ArgumentKind.typeAnnotation => TypeAnnotationArgument(
(deserializer..moveNext()).expectRemoteInstance()), (deserializer..moveNext()).expectRemoteInstance()),
ArgumentKind.code => ArgumentKind.code =>
new CodeArgument((deserializer..moveNext()).expectCode()), CodeArgument((deserializer..moveNext()).expectCode()),
// These are just for type arguments and aren't supported as actual args. // These are just for type arguments and aren't supported as actual args.
ArgumentKind.object || ArgumentKind.object ||
ArgumentKind.dynamic || ArgumentKind.dynamic ||
ArgumentKind.num || ArgumentKind.num ||
ArgumentKind.nullable => ArgumentKind.nullable =>
throw new StateError('Argument kind $kind is not deserializable'), throw StateError('Argument kind $kind is not deserializable'),
}; };
} }
/// All subtypes should override this and call super.
@override @override
@mustBeOverridden
@mustCallSuper
void serialize(Serializer serializer) { void serialize(Serializer serializer) {
serializer.addInt(kind.index); serializer.addInt(kind.index);
} }
@ -113,9 +111,6 @@ final class NullArgument extends Argument {
@override @override
Null get value => null; Null get value => null;
@override
void serialize(Serializer serializer) => super.serialize(serializer);
} }
final class StringArgument extends Argument { final class StringArgument extends Argument {
@ -251,13 +246,13 @@ abstract base class _IterableArgument<T extends Iterable<Object?>>
..expectList(); ..expectList();
final List<Argument> values = [ final List<Argument> values = [
for (; deserializer.moveNext();) for (; deserializer.moveNext();)
new Argument.deserialize(deserializer, alreadyMoved: true), Argument.deserialize(deserializer, alreadyMoved: true),
]; ];
return switch (kind) { return switch (kind) {
ArgumentKind.list => new ListArgument(values, typeArguments), ArgumentKind.list => ListArgument(values, typeArguments),
ArgumentKind.set => new SetArgument(values, typeArguments), ArgumentKind.set => SetArgument(values, typeArguments),
_ => throw new UnsupportedError( _ =>
'Could not deserialize argument of kind $kind'), throw UnsupportedError('Could not deserialize argument of kind $kind'),
} as _IterableArgument<T>; } as _IterableArgument<T>;
} }
@ -284,9 +279,6 @@ final class ListArgument extends _IterableArgument<List<Object?>> {
]); ]);
ListArgument(super._arguments, super._typeArguments); ListArgument(super._arguments, super._typeArguments);
@override
void serialize(Serializer serializer) => super.serialize(serializer);
} }
final class SetArgument extends _IterableArgument<Set<Object?>> { final class SetArgument extends _IterableArgument<Set<Object?>> {
@ -301,9 +293,6 @@ final class SetArgument extends _IterableArgument<Set<Object?>> {
}); });
SetArgument(super._arguments, super._typeArguments); SetArgument(super._arguments, super._typeArguments);
@override
void serialize(Serializer serializer) => super.serialize(serializer);
} }
final class MapArgument extends _CollectionArgument { final class MapArgument extends _CollectionArgument {
@ -340,10 +329,10 @@ final class MapArgument extends _CollectionArgument {
..expectList(); ..expectList();
final Map<Argument, Argument> arguments = { final Map<Argument, Argument> arguments = {
for (; deserializer.moveNext();) for (; deserializer.moveNext();)
new Argument.deserialize(deserializer, alreadyMoved: true): Argument.deserialize(deserializer, alreadyMoved: true):
new Argument.deserialize(deserializer), Argument.deserialize(deserializer),
}; };
return new MapArgument(arguments, typeArguments); return MapArgument(arguments, typeArguments);
} }
@override @override
@ -375,16 +364,16 @@ class Arguments implements Serializable {
..expectList(); ..expectList();
final List<Argument> positionalArgs = [ final List<Argument> positionalArgs = [
for (; deserializer.moveNext();) for (; deserializer.moveNext();)
new Argument.deserialize(deserializer, alreadyMoved: true), Argument.deserialize(deserializer, alreadyMoved: true),
]; ];
deserializer deserializer
..moveNext() ..moveNext()
..expectList(); ..expectList();
final Map<String, Argument> namedArgs = { final Map<String, Argument> namedArgs = {
for (; deserializer.moveNext();) for (; deserializer.moveNext();)
deserializer.expectString(): new Argument.deserialize(deserializer), deserializer.expectString(): Argument.deserialize(deserializer),
}; };
return new Arguments(positionalArgs, namedArgs); return Arguments(positionalArgs, namedArgs);
} }
@override @override

View File

@ -18,8 +18,8 @@ mixin AugmentationLibraryBuilder on MacroExecutor {
TypeAnnotation? Function(OmittedTypeAnnotation) typeInferrer, TypeAnnotation? Function(OmittedTypeAnnotation) typeInferrer,
{Map<OmittedTypeAnnotation, String>? omittedTypes, {Map<OmittedTypeAnnotation, String>? omittedTypes,
List<Span>? spans}) { List<Span>? spans}) {
return new _Builder(augmentedLibraryUri, resolveDeclaration, return _Builder(augmentedLibraryUri, resolveDeclaration, resolveIdentifier,
resolveIdentifier, typeInferrer, omittedTypes) typeInferrer, omittedTypes)
.build(macroResults, spans: spans); .build(macroResults, spans: spans);
} }
} }
@ -66,7 +66,7 @@ class _Builder {
} }
void _buildString(Key parent, int index, String part) { void _buildString(Key parent, int index, String part) {
_writeDirectiveStringPart(new ContentKey.string(parent, index), part); _writeDirectiveStringPart(ContentKey.string(parent, index), part);
} }
void _buildIdentifier(Key parent, int index, Identifier part) { void _buildIdentifier(Key parent, int index, Identifier part) {
@ -75,14 +75,13 @@ class _Builder {
Uri? resolvedUri = resolved.uri; Uri? resolvedUri = resolved.uri;
if (resolvedUri != null) { if (resolvedUri != null) {
prefix = _importNames.putIfAbsent(resolvedUri, () { prefix = _importNames.putIfAbsent(resolvedUri, () {
_SynthesizedNamePart prefix = new _SynthesizedNamePart(); _SynthesizedNamePart prefix = _SynthesizedNamePart();
_importParts.add(_AppliedPart.string( _importParts.add(_AppliedPart.string(
new UriKey.importPrefix(resolvedUri), UriKey.importPrefix(resolvedUri), "import '$resolvedUri' as "));
"import '${resolvedUri}' as "));
_importParts.add(_AppliedPart.synthesized( _importParts.add(_AppliedPart.synthesized(
new UriKey.prefixDefinition(resolvedUri), prefix)); UriKey.prefixDefinition(resolvedUri), prefix));
_importParts.add( _importParts
_AppliedPart.string(new UriKey.importSuffix(resolvedUri), ";\n")); .add(_AppliedPart.string(UriKey.importSuffix(resolvedUri), ";\n"));
return prefix; return prefix;
}); });
} }
@ -90,32 +89,32 @@ class _Builder {
// Qualify with `this.` if we don't have a receiver. // Qualify with `this.` if we don't have a receiver.
if (!_lastDirectivePart.trimRight().endsWith('.')) { if (!_lastDirectivePart.trimRight().endsWith('.')) {
_writeDirectiveStringPart( _writeDirectiveStringPart(
new ContentKey.implicitThis(parent, index), 'this.'); ContentKey.implicitThis(parent, index), 'this.');
} }
} else if (prefix != null) { } else if (prefix != null) {
_writeDirectiveSynthesizedNamePart( _writeDirectiveSynthesizedNamePart(
new PrefixUseKey(parent, index, resolvedUri!), prefix); PrefixUseKey(parent, index, resolvedUri!), prefix);
_writeDirectiveStringPart(new ContentKey.prefixDot(parent, index), '.'); _writeDirectiveStringPart(ContentKey.prefixDot(parent, index), '.');
} }
if (resolved.kind == IdentifierKind.staticInstanceMember) { if (resolved.kind == IdentifierKind.staticInstanceMember) {
_writeDirectiveStringPart(new ContentKey.staticScope(parent, index), _writeDirectiveStringPart(
'${resolved.staticScope!}.'); ContentKey.staticScope(parent, index), '${resolved.staticScope!}.');
} }
_writeDirectiveStringPart( _writeDirectiveStringPart(
new ContentKey.identifierName(parent, index), '${part.name}'); ContentKey.identifierName(parent, index), part.name);
} }
void _buildOmittedTypeAnnotation( void _buildOmittedTypeAnnotation(
Key parent, int index, OmittedTypeAnnotation part) { Key parent, int index, OmittedTypeAnnotation part) {
TypeAnnotation? type = _typeInferrer(part); TypeAnnotation? type = _typeInferrer(part);
Key typeAnnotationKey = new OmittedTypeAnnotationKey(parent, index, part); Key typeAnnotationKey = OmittedTypeAnnotationKey(parent, index, part);
if (type == null) { if (type == null) {
if (_omittedTypes != null) { if (_omittedTypes != null) {
_SynthesizedNamePart name = _SynthesizedNamePart name =
_typeNames.putIfAbsent(part, () => new _SynthesizedNamePart()); _typeNames.putIfAbsent(part, () => _SynthesizedNamePart());
_writeDirectiveSynthesizedNamePart(typeAnnotationKey, name); _writeDirectiveSynthesizedNamePart(typeAnnotationKey, name);
} else { } else {
throw new ArgumentError("No type inferred for $part"); throw ArgumentError("No type inferred for $part");
} }
} else { } else {
_buildCode(typeAnnotationKey, type.code); _buildCode(typeAnnotationKey, type.code);
@ -129,13 +128,13 @@ class _Builder {
if (part is String) { if (part is String) {
_buildString(parent, index, part); _buildString(parent, index, part);
} else if (part is Code) { } else if (part is Code) {
_buildCode(new ContentKey.code(parent, index), part); _buildCode(ContentKey.code(parent, index), part);
} else if (part is Identifier) { } else if (part is Identifier) {
_buildIdentifier(parent, index, part); _buildIdentifier(parent, index, part);
} else if (part is OmittedTypeAnnotation) { } else if (part is OmittedTypeAnnotation) {
_buildOmittedTypeAnnotation(parent, index, part); _buildOmittedTypeAnnotation(parent, index, part);
} else { } else {
throw new ArgumentError( throw ArgumentError(
'Code objects only support String, Identifier, and Code ' 'Code objects only support String, Identifier, and Code '
'instances but got $part which was not one of those.'); 'instances but got $part which was not one of those.');
} }
@ -150,27 +149,26 @@ class _Builder {
{}; {};
Map<Identifier, List<(Key, TypeAnnotationCode)>> mergedMixinResults = {}; Map<Identifier, List<(Key, TypeAnnotationCode)>> mergedMixinResults = {};
for (MacroExecutionResult result in macroResults) { for (MacroExecutionResult result in macroResults) {
Key key = new MacroExecutionResultKey(result); Key key = MacroExecutionResultKey(result);
int index = 0; int index = 0;
for (DeclarationCode augmentation in result.libraryAugmentations) { for (DeclarationCode augmentation in result.libraryAugmentations) {
_buildCode( _buildCode(ContentKey.libraryAugmentation(key, index), augmentation);
new ContentKey.libraryAugmentation(key, index), augmentation);
_writeDirectiveStringPart( _writeDirectiveStringPart(
new ContentKey.libraryAugmentationSeparator(key, index), '\n'); ContentKey.libraryAugmentationSeparator(key, index), '\n');
index++; index++;
} }
result.enumValueAugmentations.forEach((identifier, value) { result.enumValueAugmentations.forEach((identifier, value) {
int index = 0; int index = 0;
final Iterable<(Key, DeclarationCode)> values = value final Iterable<(Key, DeclarationCode)> values = value
.map((e) => (new IdentifierKey.enum_(key, index++, identifier), e)); .map((e) => (IdentifierKey.enum_(key, index++, identifier), e));
mergedEntryResults.update( mergedEntryResults.update(
identifier, (enumValues) => enumValues..addAll(values), identifier, (enumValues) => enumValues..addAll(values),
ifAbsent: () => values.toList()); ifAbsent: () => values.toList());
}); });
result.interfaceAugmentations.forEach((identifier, value) { result.interfaceAugmentations.forEach((identifier, value) {
int index = 0; int index = 0;
final Iterable<(Key, TypeAnnotationCode)> values = value.map( final Iterable<(Key, TypeAnnotationCode)> values = value
(e) => (new IdentifierKey.interface(key, index++, identifier), e)); .map((e) => (IdentifierKey.interface(key, index++, identifier), e));
mergedInterfaceResults.update( mergedInterfaceResults.update(
identifier, (declarations) => declarations..addAll(values), identifier, (declarations) => declarations..addAll(values),
ifAbsent: () => values.toList()); ifAbsent: () => values.toList());
@ -178,15 +176,15 @@ class _Builder {
result.mixinAugmentations.forEach((identifier, value) { result.mixinAugmentations.forEach((identifier, value) {
int index = 0; int index = 0;
final Iterable<(Key, TypeAnnotationCode)> values = value final Iterable<(Key, TypeAnnotationCode)> values = value
.map((e) => (new IdentifierKey.mixin(key, index++, identifier), e)); .map((e) => (IdentifierKey.mixin(key, index++, identifier), e));
mergedMixinResults.update( mergedMixinResults.update(
identifier, (declarations) => declarations..addAll(values), identifier, (declarations) => declarations..addAll(values),
ifAbsent: () => values.toList()); ifAbsent: () => values.toList());
}); });
result.typeAugmentations.forEach((identifier, value) { result.typeAugmentations.forEach((identifier, value) {
int index = 0; int index = 0;
final Iterable<(Key, DeclarationCode)> values = value.map( final Iterable<(Key, DeclarationCode)> values = value
(e) => (new IdentifierKey.member(key, index++, identifier), e)); .map((e) => (IdentifierKey.member(key, index++, identifier), e));
mergedTypeResults.update( mergedTypeResults.update(
identifier, (declarations) => declarations..addAll(values), identifier, (declarations) => declarations..addAll(values),
ifAbsent: () => values.toList()); ifAbsent: () => values.toList());
@ -200,13 +198,13 @@ class _Builder {
}; };
for (Identifier type in mergedAugmentedTypes) { for (Identifier type in mergedAugmentedTypes) {
final TypeDeclaration typeDeclaration = _resolveDeclaration(type); final TypeDeclaration typeDeclaration = _resolveDeclaration(type);
final TypeDeclarationKey key = new TypeDeclarationKey(typeDeclaration); final TypeDeclarationKey key = TypeDeclarationKey(typeDeclaration);
String declarationKind = switch (typeDeclaration) { String declarationKind = switch (typeDeclaration) {
ClassDeclaration() => 'class', ClassDeclaration() => 'class',
EnumDeclaration() => 'enum', EnumDeclaration() => 'enum',
ExtensionDeclaration() => 'extension', ExtensionDeclaration() => 'extension',
MixinDeclaration() => 'mixin', MixinDeclaration() => 'mixin',
_ => throw new UnsupportedError( _ => throw UnsupportedError(
'Unsupported augmentation type $typeDeclaration'), 'Unsupported augmentation type $typeDeclaration'),
}; };
final List<String> keywords = [ final List<String> keywords = [
@ -224,11 +222,11 @@ class _Builder {
]; ];
// Has the effect of adding a space after the keywords // Has the effect of adding a space after the keywords
if (keywords.isNotEmpty) keywords.add(''); if (keywords.isNotEmpty) keywords.add('');
_writeDirectiveStringPart(new TypeDeclarationContentKey.declaration(key), _writeDirectiveStringPart(TypeDeclarationContentKey.declaration(key),
'augment ${keywords.join(' ')}$declarationKind ${type.name} '); 'augment ${keywords.join(' ')}$declarationKind ${type.name} ');
if (mergedMixinResults[type] case var mixins? when mixins.isNotEmpty) { if (mergedMixinResults[type] case var mixins? when mixins.isNotEmpty) {
Key mixinsKey = new TypeDeclarationContentKey.mixins(key); Key mixinsKey = TypeDeclarationContentKey.mixins(key);
int index = 0; int index = 0;
_buildString(mixinsKey, index++, 'with '); _buildString(mixinsKey, index++, 'with ');
bool needsComma = false; bool needsComma = false;
@ -244,7 +242,7 @@ class _Builder {
if (mergedInterfaceResults[type] case var interfaces? if (mergedInterfaceResults[type] case var interfaces?
when interfaces.isNotEmpty) { when interfaces.isNotEmpty) {
Key interfacesKey = new TypeDeclarationContentKey.interfaces(key); Key interfacesKey = TypeDeclarationContentKey.interfaces(key);
int index = 0; int index = 0;
_buildString(interfacesKey, index++, 'implements '); _buildString(interfacesKey, index++, 'implements ');
bool needsComma = false; bool needsComma = false;
@ -259,23 +257,22 @@ class _Builder {
} }
_writeDirectiveStringPart( _writeDirectiveStringPart(
new TypeDeclarationContentKey.bodyStart(key), '{\n'); TypeDeclarationContentKey.bodyStart(key), '{\n');
if (typeDeclaration is EnumDeclaration) { if (typeDeclaration is EnumDeclaration) {
for (var (Key key, DeclarationCode entryAugmentation) for (var (Key key, DeclarationCode entryAugmentation)
in mergedEntryResults[type] ?? []) { in mergedEntryResults[type] ?? []) {
_buildCode(key, entryAugmentation); _buildCode(key, entryAugmentation);
} }
_writeDirectiveStringPart( _writeDirectiveStringPart(
new TypeDeclarationContentKey.enumValueEnd(key), ';\n'); TypeDeclarationContentKey.enumValueEnd(key), ';\n');
} }
for (var (Key key, DeclarationCode augmentation) for (var (Key key, DeclarationCode augmentation)
in mergedTypeResults[type] ?? []) { in mergedTypeResults[type] ?? []) {
_buildCode(key, augmentation); _buildCode(key, augmentation);
_writeDirectiveStringPart( _writeDirectiveStringPart(
new TypeDeclarationContentKey.declarationSeparator(key), '\n'); TypeDeclarationContentKey.declarationSeparator(key), '\n');
} }
_writeDirectiveStringPart( _writeDirectiveStringPart(TypeDeclarationContentKey.bodyEnd(key), '}\n');
new TypeDeclarationContentKey.bodyEnd(key), '}\n');
} }
_flushStringParts(); _flushStringParts();
@ -297,10 +294,10 @@ class _Builder {
}); });
} }
StringBuffer sb = new StringBuffer(); StringBuffer sb = StringBuffer();
void addText(Key key, String text) { void addText(Key key, String text) {
spans?.add(new Span(key, sb.length, text)); spans?.add(Span(key, sb.length, text));
sb.write(text); sb.write(text);
} }
@ -328,11 +325,11 @@ class _AppliedPart<T extends _Part> {
_AppliedPart(this.key, this.part); _AppliedPart(this.key, this.part);
static _AppliedPart<_StringPart> string(Key key, String part) => static _AppliedPart<_StringPart> string(Key key, String part) =>
new _AppliedPart<_StringPart>(key, new _StringPart(part)); _AppliedPart<_StringPart>(key, _StringPart(part));
static _AppliedPart<_SynthesizedNamePart> synthesized( static _AppliedPart<_SynthesizedNamePart> synthesized(
Key key, _SynthesizedNamePart part) => Key key, _SynthesizedNamePart part) =>
new _AppliedPart<_SynthesizedNamePart>(key, part); _AppliedPart<_SynthesizedNamePart>(key, part);
} }
abstract class _Part { abstract class _Part {

View File

@ -4,11 +4,10 @@
import 'dart:async'; import 'dart:async';
import 'package:_fe_analyzer_shared/src/macros/executor/introspection_impls.dart';
import '../api.dart'; import '../api.dart';
import '../executor.dart'; import '../executor.dart';
import 'exception_impls.dart'; import 'exception_impls.dart';
import 'introspection_impls.dart';
import 'response_impls.dart'; import 'response_impls.dart';
abstract class TypeBuilderBase implements TypePhaseIntrospector, Builder { abstract class TypeBuilderBase implements TypePhaseIntrospector, Builder {
@ -44,7 +43,7 @@ abstract class TypeBuilderBase implements TypePhaseIntrospector, Builder {
/// Creates and returns a [MacroExecutionResult] out of the [_augmentations] /// Creates and returns a [MacroExecutionResult] out of the [_augmentations]
/// created by this builder. /// created by this builder.
MacroExecutionResult get result => new MacroExecutionResultImpl( MacroExecutionResult get result => MacroExecutionResultImpl(
diagnostics: _diagnostics, diagnostics: _diagnostics,
exception: _exception, exception: _exception,
enumValueAugmentations: _enumValueAugmentations, enumValueAugmentations: _enumValueAugmentations,
@ -71,7 +70,7 @@ abstract class TypeBuilderBase implements TypePhaseIntrospector, Builder {
void report(Diagnostic diagnostic) => _diagnostics.add(diagnostic); void report(Diagnostic diagnostic) => _diagnostics.add(diagnostic);
void failWithException(MacroExceptionImpl exception) { void failWithException(MacroExceptionImpl exception) {
if (_exception != null) throw new StateError('Already set exception'); if (_exception != null) throw StateError('Already set exception');
_exception = exception; _exception = exception;
} }
@ -288,7 +287,7 @@ class TypeDefinitionBuilderImpl extends DefinitionBuilderBase
.constructorsOf(declaration)) .constructorsOf(declaration))
.firstWhere((constructor) => constructor.identifier == identifier) .firstWhere((constructor) => constructor.identifier == identifier)
as ConstructorDeclarationImpl; as ConstructorDeclarationImpl;
return new ConstructorDefinitionBuilderImpl(constructor, introspector, return ConstructorDefinitionBuilderImpl(constructor, introspector,
parentTypeAugmentations: _typeAugmentations, parentTypeAugmentations: _typeAugmentations,
parentLibraryAugmentations: _libraryAugmentations); parentLibraryAugmentations: _libraryAugmentations);
} }
@ -297,7 +296,7 @@ class TypeDefinitionBuilderImpl extends DefinitionBuilderBase
Future<VariableDefinitionBuilder> buildField(Identifier identifier) async { Future<VariableDefinitionBuilder> buildField(Identifier identifier) async {
FieldDeclaration field = (await introspector.fieldsOf(declaration)) FieldDeclaration field = (await introspector.fieldsOf(declaration))
.firstWhere((field) => field.identifier == identifier); .firstWhere((field) => field.identifier == identifier);
return new VariableDefinitionBuilderImpl(field, introspector, return VariableDefinitionBuilderImpl(field, introspector,
parentTypeAugmentations: _typeAugmentations, parentTypeAugmentations: _typeAugmentations,
parentLibraryAugmentations: _libraryAugmentations); parentLibraryAugmentations: _libraryAugmentations);
} }
@ -307,7 +306,7 @@ class TypeDefinitionBuilderImpl extends DefinitionBuilderBase
MethodDeclarationImpl method = (await introspector.methodsOf(declaration)) MethodDeclarationImpl method = (await introspector.methodsOf(declaration))
.firstWhere((method) => method.identifier == identifier) .firstWhere((method) => method.identifier == identifier)
as MethodDeclarationImpl; as MethodDeclarationImpl;
return new FunctionDefinitionBuilderImpl(method, introspector, return FunctionDefinitionBuilderImpl(method, introspector,
parentTypeAugmentations: _typeAugmentations, parentTypeAugmentations: _typeAugmentations,
parentLibraryAugmentations: _libraryAugmentations); parentLibraryAugmentations: _libraryAugmentations);
} }
@ -334,7 +333,7 @@ class EnumDefinitionBuilderImpl extends TypeDefinitionBuilderImpl
EnumValueDeclarationImpl entry = (await introspector.valuesOf(declaration)) EnumValueDeclarationImpl entry = (await introspector.valuesOf(declaration))
.firstWhere((entry) => entry.identifier == identifier) .firstWhere((entry) => entry.identifier == identifier)
as EnumValueDeclarationImpl; as EnumValueDeclarationImpl;
return new EnumValueDefinitionBuilderImpl( return EnumValueDefinitionBuilderImpl(
entry, entry,
introspector, introspector,
parentEnumValueAugmentations: _enumValueAugmentations, parentEnumValueAugmentations: _enumValueAugmentations,
@ -419,10 +418,10 @@ class ConstructorDefinitionBuilderImpl extends DefinitionBuilderBase
CommentCode? docComments}) { CommentCode? docComments}) {
if (body != null && declaration.hasBody) { if (body != null && declaration.hasBody) {
// TODO: https://github.com/dart-lang/language/issues/3555 // TODO: https://github.com/dart-lang/language/issues/3555
throw new UnsupportedError( throw UnsupportedError(
'Augmenting existing constructor bodies is not allowed.'); 'Augmenting existing constructor bodies is not allowed.');
} }
body ??= new FunctionBodyCode.fromString(';'); body ??= FunctionBodyCode.fromString(';');
DeclarationCode augmentation = _buildFunctionAugmentation(body, declaration, DeclarationCode augmentation = _buildFunctionAugmentation(body, declaration,
initializers: initializers, docComments: docComments); initializers: initializers, docComments: docComments);
_typeAugmentations.update( _typeAugmentations.update(
@ -488,7 +487,7 @@ class LibraryDefinitionBuilderImpl extends DefinitionBuilderBase
.topLevelDeclarationsOf(library)) .topLevelDeclarationsOf(library))
.firstWhere((declaration) => declaration.identifier == identifier) .firstWhere((declaration) => declaration.identifier == identifier)
as FunctionDeclarationImpl; as FunctionDeclarationImpl;
return new FunctionDefinitionBuilderImpl(function, introspector, return FunctionDefinitionBuilderImpl(function, introspector,
parentTypeAugmentations: _typeAugmentations, parentTypeAugmentations: _typeAugmentations,
parentLibraryAugmentations: _libraryAugmentations); parentLibraryAugmentations: _libraryAugmentations);
} }
@ -498,7 +497,7 @@ class LibraryDefinitionBuilderImpl extends DefinitionBuilderBase
TypeDeclaration type = (await introspector.topLevelDeclarationsOf(library)) TypeDeclaration type = (await introspector.topLevelDeclarationsOf(library))
.firstWhere((declaration) => declaration.identifier == identifier) .firstWhere((declaration) => declaration.identifier == identifier)
as TypeDeclaration; as TypeDeclaration;
return new TypeDefinitionBuilderImpl(type, introspector, return TypeDefinitionBuilderImpl(type, introspector,
parentTypeAugmentations: _typeAugmentations, parentTypeAugmentations: _typeAugmentations,
parentLibraryAugmentations: _libraryAugmentations); parentLibraryAugmentations: _libraryAugmentations);
} }
@ -509,7 +508,7 @@ class LibraryDefinitionBuilderImpl extends DefinitionBuilderBase
.topLevelDeclarationsOf(library)) .topLevelDeclarationsOf(library))
.firstWhere((declaration) => declaration.identifier == identifier) .firstWhere((declaration) => declaration.identifier == identifier)
as VariableDeclarationImpl; as VariableDeclarationImpl;
return new VariableDefinitionBuilderImpl(variable, introspector, return VariableDefinitionBuilderImpl(variable, introspector,
parentTypeAugmentations: _typeAugmentations, parentTypeAugmentations: _typeAugmentations,
parentLibraryAugmentations: _libraryAugmentations); parentLibraryAugmentations: _libraryAugmentations);
} }
@ -523,13 +522,13 @@ List<DeclarationCode> _buildVariableAugmentations(
ExpressionCode? initializer, ExpressionCode? initializer,
CommentCode? initializerDocComments}) { CommentCode? initializerDocComments}) {
if (initializerDocComments != null && initializer == null) { if (initializerDocComments != null && initializer == null) {
throw new ArgumentError( throw ArgumentError(
'initializerDocComments cannot be provided if an initializer is not ' 'initializerDocComments cannot be provided if an initializer is not '
'provided.'); 'provided.');
} }
List<DeclarationCode> augmentations = []; List<DeclarationCode> augmentations = [];
if (getter != null) { if (getter != null) {
augmentations.add(new DeclarationCode.fromParts([ augmentations.add(DeclarationCode.fromParts([
if (declaration is FieldDeclaration) ' ', if (declaration is FieldDeclaration) ' ',
'augment ', 'augment ',
if (declaration is FieldDeclaration && declaration.hasStatic) 'static ', if (declaration is FieldDeclaration && declaration.hasStatic) 'static ',
@ -537,7 +536,7 @@ List<DeclarationCode> _buildVariableAugmentations(
])); ]));
} }
if (setter != null) { if (setter != null) {
augmentations.add(new DeclarationCode.fromParts([ augmentations.add(DeclarationCode.fromParts([
if (declaration is FieldDeclaration) ' ', if (declaration is FieldDeclaration) ' ',
'augment ', 'augment ',
if (declaration is FieldDeclaration && declaration.hasStatic) 'static ', if (declaration is FieldDeclaration && declaration.hasStatic) 'static ',
@ -545,7 +544,7 @@ List<DeclarationCode> _buildVariableAugmentations(
])); ]));
} }
if (initializer != null) { if (initializer != null) {
augmentations.add(new DeclarationCode.fromParts([ augmentations.add(DeclarationCode.fromParts([
if (initializerDocComments != null) initializerDocComments, if (initializerDocComments != null) initializerDocComments,
if (declaration is FieldDeclaration) ' ', if (declaration is FieldDeclaration) ' ',
'augment ', 'augment ',
@ -573,7 +572,7 @@ DeclarationCode _buildFunctionAugmentation(
{List<Code>? initializers, CommentCode? docComments}) { {List<Code>? initializers, CommentCode? docComments}) {
assert(initializers == null || declaration is ConstructorDeclaration); assert(initializers == null || declaration is ConstructorDeclaration);
return new DeclarationCode.fromParts([ return DeclarationCode.fromParts([
if (docComments != null) ...[docComments, '\n'], if (docComments != null) ...[docComments, '\n'],
if (declaration is MethodDeclaration) ' ', if (declaration is MethodDeclaration) ' ',
'augment ', 'augment ',

View File

@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:meta/meta.dart';
/// Enables building up dynamic schemas with deep casts. /// Enables building up dynamic schemas with deep casts.
/// ///
/// These schemas are built up "inside out" using [getAsTypedCast] to extract /// These schemas are built up "inside out" using [getAsTypedCast] to extract
@ -14,16 +12,14 @@ class Cast<T> {
/// All casts happen in this method, custom [Cast] implementations must /// All casts happen in this method, custom [Cast] implementations must
/// override this method, and no other methods. /// override this method, and no other methods.
@mustBeOverridden
T _cast(Object? from) => from is T T _cast(Object? from) => from is T
? from ? from
: throw new FailedCast( : throw FailedCast(
'expected type $T but got type ${from.runtimeType} for: $from'); 'expected type $T but got type ${from.runtimeType} for: $from');
@nonVirtual
T cast(Object? from) => _cast(from); T cast(Object? from) => _cast(from);
Cast<T?> get nullable => new NullableCast._(this); Cast<T?> get nullable => NullableCast._(this);
/// Enables building up deeply nested generic types without requiring any /// Enables building up deeply nested generic types without requiring any
/// static knowledge or type inference. /// static knowledge or type inference.
@ -33,7 +29,6 @@ class Cast<T> {
/// Cast<dynamic> x = Cast<int>(); /// Cast<dynamic> x = Cast<int>();
/// final y = x.getAsTypedCast(<T>(_) => Cast<Foo<T>>()); /// final y = x.getAsTypedCast(<T>(_) => Cast<Foo<T>>());
/// print(y.runtimeType); // Cast<Foo<int>> /// print(y.runtimeType); // Cast<Foo<int>>
@nonVirtual
R getAsTypedCast<R>(R Function<CastType>(Cast<CastType> self) callback) => R getAsTypedCast<R>(R Function<CastType>(Cast<CastType> self) callback) =>
callback<T>(this); callback<T>(this);
} }
@ -71,7 +66,7 @@ class MapCast<K, V> extends Cast<Map<K, V>> {
static MapCast<Object?, Object?> from( static MapCast<Object?, Object?> from(
Cast<Object?> keyCast, Cast<Object?> valueCast) => Cast<Object?> keyCast, Cast<Object?> valueCast) =>
keyCast.getAsTypedCast(<K>(keyCast) => valueCast.getAsTypedCast( keyCast.getAsTypedCast(<K>(keyCast) => valueCast.getAsTypedCast(
<V>(valueCast) => new MapCast<K, V>._(keyCast, valueCast))); <V>(valueCast) => MapCast<K, V>._(keyCast, valueCast)));
@override @override
Map<K, V> _cast(Object? from) { Map<K, V> _cast(Object? from) {
@ -106,7 +101,7 @@ class ListCast<E> extends Cast<List<E>> {
if (from is! List) { if (from is! List) {
return super._cast(from); return super._cast(from);
} }
return new List<E>.generate(from.length, (i) => _entryCast._cast(from[i])); return List<E>.generate(from.length, (i) => _entryCast._cast(from[i]));
} }
} }

View File

@ -8,15 +8,15 @@ import 'dart:io';
import 'dart:isolate'; import 'dart:isolate';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import '../api.dart';
import 'package:_fe_analyzer_shared/src/macros/executor.dart'; import '../executor.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/exception_impls.dart'; import 'exception_impls.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/execute_macro.dart'; import 'execute_macro.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/message_grouper.dart'; import 'message_grouper.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/protocol.dart'; import 'protocol.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/remote_instance.dart'; import 'remote_instance.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/response_impls.dart'; import 'response_impls.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'; import 'serialization.dart';
/// Implements the client side of the macro instantiation/expansion protocol. /// Implements the client side of the macro instantiation/expansion protocol.
final class MacroExpansionClient { final class MacroExpansionClient {
@ -57,7 +57,7 @@ final class MacroExpansionClient {
int? socketPort; int? socketPort;
if (arguments.isNotEmpty) { if (arguments.isNotEmpty) {
if (arguments.length != 2) { if (arguments.length != 2) {
throw new ArgumentError( throw ArgumentError(
'Expected exactly two or zero arguments, got $arguments.'); 'Expected exactly two or zero arguments, got $arguments.');
} }
socketAddress = arguments.first; socketAddress = arguments.first;
@ -65,7 +65,7 @@ final class MacroExpansionClient {
} }
if (sendPort != null) { if (sendPort != null) {
ReceivePort receivePort = new ReceivePort(); ReceivePort receivePort = ReceivePort();
messageStream = receivePort; messageStream = receivePort;
sendResult = sendResult =
(Serializer serializer) => _sendIsolateResult(serializer, sendPort); (Serializer serializer) => _sendIsolateResult(serializer, sendPort);
@ -85,20 +85,20 @@ final class MacroExpansionClient {
inputStream = stdin; inputStream = stdin;
} }
if (serializationMode == SerializationMode.byteData) { if (serializationMode == SerializationMode.byteData) {
messageStream = new MessageGrouper(inputStream).messageStream; messageStream = MessageGrouper(inputStream).messageStream;
} else if (serializationMode == SerializationMode.json) { } else if (serializationMode == SerializationMode.json) {
messageStream = const Utf8Decoder() messageStream = const Utf8Decoder()
.bind(inputStream) .bind(inputStream)
.transform(const LineSplitter()) .transform(const LineSplitter())
.map((line) => jsonDecode(line)!); .map((line) => jsonDecode(line)!);
} else { } else {
throw new UnsupportedError( throw UnsupportedError(
'Unsupported serialization mode $serializationMode for ' 'Unsupported serialization mode $serializationMode for '
'ProcessExecutor'); 'ProcessExecutor');
} }
} }
return new MacroExpansionClient._( return MacroExpansionClient._(
sendResult, messageStream, macroConstructors); sendResult, messageStream, macroConstructors);
}); });
} }
@ -116,49 +116,47 @@ final class MacroExpansionClient {
Deserializer deserializer = deserializerFactory(message)..moveNext(); Deserializer deserializer = deserializerFactory(message)..moveNext();
int zoneId = deserializer.expectInt(); int zoneId = deserializer.expectInt();
await withRemoteInstanceZone(zoneId, () async { await withRemoteInstanceZone(zoneId, () async {
deserializer..moveNext(); deserializer.moveNext();
MessageType type = MessageType.values[deserializer.expectInt()]; MessageType type = MessageType.values[deserializer.expectInt()];
Serializer serializer = serializerFactory(); Serializer serializer = serializerFactory();
switch (type) { switch (type) {
case MessageType.instantiateMacroRequest: case MessageType.instantiateMacroRequest:
InstantiateMacroRequest request = InstantiateMacroRequest request =
new InstantiateMacroRequest.deserialize(deserializer, zoneId); InstantiateMacroRequest.deserialize(deserializer, zoneId);
(await _instantiateMacro(request)).serialize(serializer); (await _instantiateMacro(request)).serialize(serializer);
case MessageType.disposeMacroRequest: case MessageType.disposeMacroRequest:
DisposeMacroRequest request = DisposeMacroRequest request =
new DisposeMacroRequest.deserialize(deserializer, zoneId); DisposeMacroRequest.deserialize(deserializer, zoneId);
_macroInstances.remove(request.identifier); _macroInstances.remove(request.identifier);
return; return;
case MessageType.executeDeclarationsPhaseRequest: case MessageType.executeDeclarationsPhaseRequest:
ExecuteDeclarationsPhaseRequest request = ExecuteDeclarationsPhaseRequest request =
new ExecuteDeclarationsPhaseRequest.deserialize( ExecuteDeclarationsPhaseRequest.deserialize(deserializer, zoneId);
deserializer, zoneId);
(await _executeDeclarationsPhase(request, sendRequest)) (await _executeDeclarationsPhase(request, sendRequest))
.serialize(serializer); .serialize(serializer);
case MessageType.executeDefinitionsPhaseRequest: case MessageType.executeDefinitionsPhaseRequest:
ExecuteDefinitionsPhaseRequest request = ExecuteDefinitionsPhaseRequest request =
new ExecuteDefinitionsPhaseRequest.deserialize( ExecuteDefinitionsPhaseRequest.deserialize(deserializer, zoneId);
deserializer, zoneId);
(await _executeDefinitionsPhase(request, sendRequest)) (await _executeDefinitionsPhase(request, sendRequest))
.serialize(serializer); .serialize(serializer);
case MessageType.executeTypesPhaseRequest: case MessageType.executeTypesPhaseRequest:
ExecuteTypesPhaseRequest request = ExecuteTypesPhaseRequest request =
new ExecuteTypesPhaseRequest.deserialize(deserializer, zoneId); ExecuteTypesPhaseRequest.deserialize(deserializer, zoneId);
(await _executeTypesPhase(request, sendRequest)) (await _executeTypesPhase(request, sendRequest))
.serialize(serializer); .serialize(serializer);
case MessageType.response: case MessageType.response:
SerializableResponse response = SerializableResponse response =
new SerializableResponse.deserialize(deserializer, zoneId); SerializableResponse.deserialize(deserializer, zoneId);
_responseCompleters.remove(response.requestId)!.complete(response); _responseCompleters.remove(response.requestId)!.complete(response);
return; return;
case MessageType.destroyRemoteInstanceZoneRequest: case MessageType.destroyRemoteInstanceZoneRequest:
DestroyRemoteInstanceZoneRequest request = DestroyRemoteInstanceZoneRequest request =
new DestroyRemoteInstanceZoneRequest.deserialize( DestroyRemoteInstanceZoneRequest.deserialize(
deserializer, zoneId); deserializer, zoneId);
destroyRemoteInstanceZone(request.serializationZoneId); destroyRemoteInstanceZone(request.serializationZoneId);
return; return;
default: default:
throw new StateError('Unhandled event type $type'); throw StateError('Unhandled event type $type');
} }
sendResult(serializer); sendResult(serializer);
}, createIfMissing: true); }, createIfMissing: true);
@ -170,14 +168,14 @@ final class MacroExpansionClient {
try { try {
Map<String, Map<String, Function>> classes = Map<String, Map<String, Function>> classes =
_macroConstructors[request.library] ?? _macroConstructors[request.library] ??
(throw new ArgumentError( (throw ArgumentError(
'Unrecognized macro library ${request.library}')); 'Unrecognized macro library ${request.library}'));
Map<String, Function> constructors = classes[request.name] ?? Map<String, Function> constructors = classes[request.name] ??
(throw new ArgumentError( (throw ArgumentError(
'Unrecognized macro class ${request.name} for library ' 'Unrecognized macro class ${request.name} for library '
'${request.library}')); '${request.library}'));
Function constructor = constructors[request.constructor] ?? Function constructor = constructors[request.constructor] ??
(throw new ArgumentError( (throw ArgumentError(
'Unrecognized constructor name "${request.constructor}" for ' 'Unrecognized constructor name "${request.constructor}" for '
'macro class "${request.name}".')); 'macro class "${request.name}".'));
@ -186,20 +184,20 @@ final class MacroExpansionClient {
], { ], {
for (MapEntry<String, Argument> entry for (MapEntry<String, Argument> entry
in request.arguments.named.entries) in request.arguments.named.entries)
new Symbol(entry.key): entry.value.value, Symbol(entry.key): entry.value.value,
}) as Macro; }) as Macro;
MacroInstanceIdentifierImpl identifier = MacroInstanceIdentifierImpl identifier =
new MacroInstanceIdentifierImpl(instance, request.instanceId); MacroInstanceIdentifierImpl(instance, request.instanceId);
_macroInstances[identifier] = instance; _macroInstances[identifier] = instance;
return new SerializableResponse( return SerializableResponse(
responseType: MessageType.macroInstanceIdentifier, responseType: MessageType.macroInstanceIdentifier,
response: identifier, response: identifier,
requestId: request.id, requestId: request.id,
serializationZoneId: request.serializationZoneId); serializationZoneId: request.serializationZoneId);
} catch (e, s) { } catch (e, s) {
return new SerializableResponse( return SerializableResponse(
responseType: MessageType.exception, responseType: MessageType.exception,
exception: new MacroExceptionImpl.from(e, s), exception: MacroExceptionImpl.from(e, s),
requestId: request.id, requestId: request.id,
serializationZoneId: request.serializationZoneId); serializationZoneId: request.serializationZoneId);
} }
@ -210,24 +208,24 @@ final class MacroExpansionClient {
Future<Response> Function(Request request) sendRequest) async { Future<Response> Function(Request request) sendRequest) async {
try { try {
Macro instance = _macroInstances[request.macro] ?? Macro instance = _macroInstances[request.macro] ??
(throw new StateError('Unrecognized macro instance ${request.macro}\n' (throw StateError('Unrecognized macro instance ${request.macro}\n'
'Known instances: $_macroInstances)')); 'Known instances: $_macroInstances)'));
TypePhaseIntrospector introspector = new ClientTypePhaseIntrospector( TypePhaseIntrospector introspector = ClientTypePhaseIntrospector(
sendRequest, sendRequest,
remoteInstance: request.introspector, remoteInstance: request.introspector,
serializationZoneId: request.serializationZoneId); serializationZoneId: request.serializationZoneId);
MacroExecutionResult result = MacroExecutionResult result =
await executeTypesMacro(instance, request.target, introspector); await executeTypesMacro(instance, request.target, introspector);
return new SerializableResponse( return SerializableResponse(
responseType: MessageType.macroExecutionResult, responseType: MessageType.macroExecutionResult,
response: result, response: result,
requestId: request.id, requestId: request.id,
serializationZoneId: request.serializationZoneId); serializationZoneId: request.serializationZoneId);
} catch (e, s) { } catch (e, s) {
return new SerializableResponse( return SerializableResponse(
responseType: MessageType.exception, responseType: MessageType.exception,
exception: new MacroExceptionImpl.from(e, s), exception: MacroExceptionImpl.from(e, s),
requestId: request.id, requestId: request.id,
serializationZoneId: request.serializationZoneId); serializationZoneId: request.serializationZoneId);
} }
@ -238,25 +236,25 @@ final class MacroExpansionClient {
Future<Response> Function(Request request) sendRequest) async { Future<Response> Function(Request request) sendRequest) async {
try { try {
Macro instance = _macroInstances[request.macro] ?? Macro instance = _macroInstances[request.macro] ??
(throw new StateError('Unrecognized macro instance ${request.macro}\n' (throw StateError('Unrecognized macro instance ${request.macro}\n'
'Known instances: $_macroInstances)')); 'Known instances: $_macroInstances)'));
DeclarationPhaseIntrospector introspector = DeclarationPhaseIntrospector introspector =
new ClientDeclarationPhaseIntrospector(sendRequest, ClientDeclarationPhaseIntrospector(sendRequest,
remoteInstance: request.introspector, remoteInstance: request.introspector,
serializationZoneId: request.serializationZoneId); serializationZoneId: request.serializationZoneId);
MacroExecutionResult result = await executeDeclarationsMacro( MacroExecutionResult result = await executeDeclarationsMacro(
instance, request.target, introspector); instance, request.target, introspector);
return new SerializableResponse( return SerializableResponse(
responseType: MessageType.macroExecutionResult, responseType: MessageType.macroExecutionResult,
response: result, response: result,
requestId: request.id, requestId: request.id,
serializationZoneId: request.serializationZoneId); serializationZoneId: request.serializationZoneId);
} catch (e, s) { } catch (e, s) {
return new SerializableResponse( return SerializableResponse(
responseType: MessageType.exception, responseType: MessageType.exception,
exception: new MacroExceptionImpl.from(e, s), exception: MacroExceptionImpl.from(e, s),
requestId: request.id, requestId: request.id,
serializationZoneId: request.serializationZoneId); serializationZoneId: request.serializationZoneId);
} }
@ -267,24 +265,24 @@ final class MacroExpansionClient {
Future<Response> Function(Request request) sendRequest) async { Future<Response> Function(Request request) sendRequest) async {
try { try {
Macro instance = _macroInstances[request.macro] ?? Macro instance = _macroInstances[request.macro] ??
(throw new StateError('Unrecognized macro instance ${request.macro}\n' (throw StateError('Unrecognized macro instance ${request.macro}\n'
'Known instances: $_macroInstances)')); 'Known instances: $_macroInstances)'));
DefinitionPhaseIntrospector introspector = DefinitionPhaseIntrospector introspector =
new ClientDefinitionPhaseIntrospector(sendRequest, ClientDefinitionPhaseIntrospector(sendRequest,
remoteInstance: request.introspector, remoteInstance: request.introspector,
serializationZoneId: request.serializationZoneId); serializationZoneId: request.serializationZoneId);
MacroExecutionResult result = MacroExecutionResult result =
await executeDefinitionMacro(instance, request.target, introspector); await executeDefinitionMacro(instance, request.target, introspector);
return new SerializableResponse( return SerializableResponse(
responseType: MessageType.macroExecutionResult, responseType: MessageType.macroExecutionResult,
response: result, response: result,
requestId: request.id, requestId: request.id,
serializationZoneId: request.serializationZoneId); serializationZoneId: request.serializationZoneId);
} catch (e, s) { } catch (e, s) {
return new SerializableResponse( return SerializableResponse(
responseType: MessageType.exception, responseType: MessageType.exception,
exception: new MacroExceptionImpl.from(e, s), exception: MacroExceptionImpl.from(e, s),
requestId: request.id, requestId: request.id,
serializationZoneId: request.serializationZoneId); serializationZoneId: request.serializationZoneId);
} }
@ -294,7 +292,7 @@ final class MacroExpansionClient {
/// in [_responseCompleters] to handle the response. /// in [_responseCompleters] to handle the response.
Future<Response> _sendRequest( Future<Response> _sendRequest(
Request request, void Function(Serializer serializer) sendResult) { Request request, void Function(Serializer serializer) sendResult) {
Completer<Response> completer = new Completer(); Completer<Response> completer = Completer();
_responseCompleters[request.id] = completer; _responseCompleters[request.id] = completer;
Serializer serializer = serializerFactory(); Serializer serializer = serializerFactory();
serializer.addInt(request.serializationZoneId); serializer.addInt(request.serializationZoneId);
@ -308,8 +306,8 @@ final class MacroExpansionClient {
/// [TransferableTypedData] object. /// [TransferableTypedData] object.
void _sendIsolateResult(Serializer serializer, SendPort sendPort) { void _sendIsolateResult(Serializer serializer, SendPort sendPort) {
if (serializationMode == SerializationMode.byteData) { if (serializationMode == SerializationMode.byteData) {
sendPort.send( sendPort
new TransferableTypedData.fromList([serializer.result as Uint8List])); .send(TransferableTypedData.fromList([serializer.result as Uint8List]));
} else { } else {
sendPort.send(serializer.result); sendPort.send(serializer.result);
} }
@ -326,7 +324,7 @@ void Function(Serializer) _sendIOSinkResultFactory(IOSink sink) =>
} else if (serializationMode == SerializationMode.byteData) { } else if (serializationMode == SerializationMode.byteData) {
Uint8List result = (serializer as ByteDataSerializer).result; Uint8List result = (serializer as ByteDataSerializer).result;
int length = result.lengthInBytes; int length = result.lengthInBytes;
BytesBuilder bytesBuilder = new BytesBuilder(copy: false); BytesBuilder bytesBuilder = BytesBuilder(copy: false);
bytesBuilder.add([ bytesBuilder.add([
length >> 24 & 0xff, length >> 24 & 0xff,
length >> 16 & 0xff, length >> 16 & 0xff,
@ -336,7 +334,7 @@ void Function(Serializer) _sendIOSinkResultFactory(IOSink sink) =>
bytesBuilder.add(result); bytesBuilder.add(result);
sink.add(bytesBuilder.takeBytes()); sink.add(bytesBuilder.takeBytes());
} else { } else {
throw new UnsupportedError( throw UnsupportedError(
'Unsupported serialization mode $serializationMode for ' 'Unsupported serialization mode $serializationMode for '
'ProcessExecutor'); 'ProcessExecutor');
} }

View File

@ -35,17 +35,17 @@ abstract base class MacroExceptionImpl extends RemoteInstance
String? stackTrace}) { String? stackTrace}) {
switch (kind) { switch (kind) {
case RemoteInstanceKind.unexpectedMacroException: case RemoteInstanceKind.unexpectedMacroException:
return new UnexpectedMacroExceptionImpl(message, return UnexpectedMacroExceptionImpl(message,
id: id, stackTrace: stackTrace); id: id, stackTrace: stackTrace);
case RemoteInstanceKind.macroImplementationException: case RemoteInstanceKind.macroImplementationException:
return new MacroImplementationExceptionImpl(message, return MacroImplementationExceptionImpl(message,
id: id, stackTrace: stackTrace); id: id, stackTrace: stackTrace);
case RemoteInstanceKind.macroIntrospectionCycleException: case RemoteInstanceKind.macroIntrospectionCycleException:
return new MacroIntrospectionCycleExceptionImpl(message, return MacroIntrospectionCycleExceptionImpl(message,
id: id, stackTrace: stackTrace); id: id, stackTrace: stackTrace);
default: default:
throw new ArgumentError.value(kind, 'kind'); throw ArgumentError.value(kind, 'kind');
} }
} }
@ -55,7 +55,7 @@ abstract base class MacroExceptionImpl extends RemoteInstance
/// Otherwise it's an unexpected type, return an [UnexpectedMacroException]. /// Otherwise it's an unexpected type, return an [UnexpectedMacroException].
factory MacroExceptionImpl.from(Object throwable, StackTrace stackTrace) { factory MacroExceptionImpl.from(Object throwable, StackTrace stackTrace) {
if (throwable is MacroExceptionImpl) return throwable; if (throwable is MacroExceptionImpl) return throwable;
return new UnexpectedMacroExceptionImpl(throwable.toString(), return UnexpectedMacroExceptionImpl(throwable.toString(),
stackTrace: stackTrace.toString()); stackTrace: stackTrace.toString());
} }

View File

@ -2,11 +2,11 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import '../api.dart';
import 'package:_fe_analyzer_shared/src/macros/executor.dart'; import '../executor.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/builder_impls.dart'; import 'builder_impls.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/exception_impls.dart'; import 'exception_impls.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/introspection_impls.dart'; import 'introspection_impls.dart';
/// Runs [macro] in the types phase and returns a [MacroExecutionResult]. /// Runs [macro] in the types phase and returns a [MacroExecutionResult].
Future<MacroExecutionResult> executeTypesMacro( Future<MacroExecutionResult> executeTypesMacro(
@ -19,7 +19,7 @@ Future<MacroExecutionResult> executeTypesMacro(
// Shared code for most branches. If we do create it, assign it to // Shared code for most branches. If we do create it, assign it to
// `builder`. // `builder`.
late final TypeBuilderImpl typeBuilder = late final TypeBuilderImpl typeBuilder =
builder = new TypeBuilderImpl(introspector); builder = TypeBuilderImpl(introspector);
switch ((target, macro)) { switch ((target, macro)) {
case (Library target, LibraryTypesMacro macro): case (Library target, LibraryTypesMacro macro):
await macro.buildTypesForLibrary(target, typeBuilder); await macro.buildTypesForLibrary(target, typeBuilder);
@ -36,12 +36,12 @@ Future<MacroExecutionResult> executeTypesMacro(
case (ClassDeclaration target, ClassTypesMacro macro): case (ClassDeclaration target, ClassTypesMacro macro):
await macro.buildTypesForClass( await macro.buildTypesForClass(
target, target,
builder = new ClassTypeBuilderImpl( builder = ClassTypeBuilderImpl(
target.identifier as IdentifierImpl, introspector)); target.identifier as IdentifierImpl, introspector));
case (EnumDeclaration target, EnumTypesMacro macro): case (EnumDeclaration target, EnumTypesMacro macro):
await macro.buildTypesForEnum( await macro.buildTypesForEnum(
target, target,
builder = new EnumTypeBuilderImpl( builder = EnumTypeBuilderImpl(
target.identifier as IdentifierImpl, introspector)); target.identifier as IdentifierImpl, introspector));
case (ExtensionDeclaration target, ExtensionTypesMacro macro): case (ExtensionDeclaration target, ExtensionTypesMacro macro):
await macro.buildTypesForExtension(target, typeBuilder); await macro.buildTypesForExtension(target, typeBuilder);
@ -50,14 +50,14 @@ Future<MacroExecutionResult> executeTypesMacro(
case (MixinDeclaration target, MixinTypesMacro macro): case (MixinDeclaration target, MixinTypesMacro macro):
await macro.buildTypesForMixin( await macro.buildTypesForMixin(
target, target,
builder = new MixinTypeBuilderImpl( builder = MixinTypeBuilderImpl(
target.identifier as IdentifierImpl, introspector)); target.identifier as IdentifierImpl, introspector));
case (EnumValueDeclaration target, EnumValueTypesMacro macro): case (EnumValueDeclaration target, EnumValueTypesMacro macro):
await macro.buildTypesForEnumValue(target, typeBuilder); await macro.buildTypesForEnumValue(target, typeBuilder);
case (TypeAliasDeclaration target, TypeAliasTypesMacro macro): case (TypeAliasDeclaration target, TypeAliasTypesMacro macro):
await macro.buildTypesForTypeAlias(target, typeBuilder); await macro.buildTypesForTypeAlias(target, typeBuilder);
default: default:
throw new UnsupportedError('Unsupported macro type or invalid target:\n' throw UnsupportedError('Unsupported macro type or invalid target:\n'
'macro: $macro\ntarget: $target'); 'macro: $macro\ntarget: $target');
} }
} catch (e, s) { } catch (e, s) {
@ -82,23 +82,23 @@ Future<MacroExecutionResult> executeDeclarationsMacro(Macro macro,
// At most one of these will be used below. // At most one of these will be used below.
late MemberDeclarationBuilderImpl memberBuilder = late MemberDeclarationBuilderImpl memberBuilder =
builder = new MemberDeclarationBuilderImpl( builder = MemberDeclarationBuilderImpl(
switch (target) { switch (target) {
MemberDeclaration() => target.definingType as IdentifierImpl, MemberDeclaration() => target.definingType as IdentifierImpl,
TypeDeclarationImpl() => target.identifier, TypeDeclarationImpl() => target.identifier,
_ => throw new StateError( _ => throw StateError(
'Can only create member declaration builders for types or ' 'Can only create member declaration builders for types or '
'member declarations, but got $target'), 'member declarations, but got $target'),
}, },
introspector); introspector);
late DeclarationBuilderImpl topLevelBuilder = late DeclarationBuilderImpl topLevelBuilder =
builder = new DeclarationBuilderImpl(introspector); builder = DeclarationBuilderImpl(introspector);
late EnumDeclarationBuilderImpl enumBuilder = late EnumDeclarationBuilderImpl enumBuilder =
builder = new EnumDeclarationBuilderImpl( builder = EnumDeclarationBuilderImpl(
switch (target) { switch (target) {
EnumDeclarationImpl() => target.identifier, EnumDeclarationImpl() => target.identifier,
EnumValueDeclarationImpl() => target.definingEnum, EnumValueDeclarationImpl() => target.definingEnum,
_ => throw new StateError( _ => throw StateError(
'Can only create enum declaration builders for enum or enum ' 'Can only create enum declaration builders for enum or enum '
'value declarations, but got $target'), 'value declarations, but got $target'),
}, },
@ -137,7 +137,7 @@ Future<MacroExecutionResult> executeDeclarationsMacro(Macro macro,
case (TypeAliasDeclaration target, TypeAliasDeclarationsMacro macro): case (TypeAliasDeclaration target, TypeAliasDeclarationsMacro macro):
await macro.buildDeclarationsForTypeAlias(target, topLevelBuilder); await macro.buildDeclarationsForTypeAlias(target, topLevelBuilder);
default: default:
throw new UnsupportedError('Unsupported macro type or invalid target:\n' throw UnsupportedError('Unsupported macro type or invalid target:\n'
'macro: $macro\ntarget: $target'); 'macro: $macro\ntarget: $target');
} }
} catch (e, s) { } catch (e, s) {
@ -162,26 +162,26 @@ Future<MacroExecutionResult> executeDefinitionMacro(Macro macro, Object target,
// At most one of these will be used below. // At most one of these will be used below.
late FunctionDefinitionBuilderImpl functionBuilder = builder = late FunctionDefinitionBuilderImpl functionBuilder = builder =
new FunctionDefinitionBuilderImpl( FunctionDefinitionBuilderImpl(
target as FunctionDeclarationImpl, introspector); target as FunctionDeclarationImpl, introspector);
late VariableDefinitionBuilderImpl variableBuilder = builder = late VariableDefinitionBuilderImpl variableBuilder = builder =
new VariableDefinitionBuilderImpl( VariableDefinitionBuilderImpl(
target as VariableDeclaration, introspector); target as VariableDeclaration, introspector);
late TypeDefinitionBuilderImpl typeBuilder = builder = late TypeDefinitionBuilderImpl typeBuilder = builder =
new TypeDefinitionBuilderImpl(target as TypeDeclaration, introspector); TypeDefinitionBuilderImpl(target as TypeDeclaration, introspector);
// TODO(jakemac): More robust handling for unawaited async errors? // TODO(jakemac): More robust handling for unawaited async errors?
try { try {
switch ((target, macro)) { switch ((target, macro)) {
case (Library target, LibraryDefinitionMacro macro): case (Library target, LibraryDefinitionMacro macro):
LibraryDefinitionBuilderImpl libraryBuilder = LibraryDefinitionBuilderImpl libraryBuilder =
builder = new LibraryDefinitionBuilderImpl(target, introspector); builder = LibraryDefinitionBuilderImpl(target, introspector);
await macro.buildDefinitionForLibrary(target, libraryBuilder); await macro.buildDefinitionForLibrary(target, libraryBuilder);
case (ClassDeclaration target, ClassDefinitionMacro macro): case (ClassDeclaration target, ClassDefinitionMacro macro):
await macro.buildDefinitionForClass(target, typeBuilder); await macro.buildDefinitionForClass(target, typeBuilder);
case (EnumDeclaration target, EnumDefinitionMacro macro): case (EnumDeclaration target, EnumDefinitionMacro macro):
EnumDefinitionBuilderImpl enumBuilder = EnumDefinitionBuilderImpl enumBuilder =
builder = new EnumDefinitionBuilderImpl(target, introspector); builder = EnumDefinitionBuilderImpl(target, introspector);
await macro.buildDefinitionForEnum(target, enumBuilder); await macro.buildDefinitionForEnum(target, enumBuilder);
case (ExtensionDeclaration target, ExtensionDefinitionMacro macro): case (ExtensionDeclaration target, ExtensionDefinitionMacro macro):
await macro.buildDefinitionForExtension(target, typeBuilder); await macro.buildDefinitionForExtension(target, typeBuilder);
@ -194,12 +194,12 @@ Future<MacroExecutionResult> executeDefinitionMacro(Macro macro, Object target,
await macro.buildDefinitionForMixin(target, typeBuilder); await macro.buildDefinitionForMixin(target, typeBuilder);
case (EnumValueDeclaration target, EnumValueDefinitionMacro macro): case (EnumValueDeclaration target, EnumValueDefinitionMacro macro):
EnumValueDefinitionBuilderImpl enumValueBuilder = builder = EnumValueDefinitionBuilderImpl enumValueBuilder = builder =
new EnumValueDefinitionBuilderImpl( EnumValueDefinitionBuilderImpl(
target as EnumValueDeclarationImpl, introspector); target as EnumValueDeclarationImpl, introspector);
await macro.buildDefinitionForEnumValue(target, enumValueBuilder); await macro.buildDefinitionForEnumValue(target, enumValueBuilder);
case (ConstructorDeclaration target, ConstructorDefinitionMacro macro): case (ConstructorDeclaration target, ConstructorDefinitionMacro macro):
ConstructorDefinitionBuilderImpl constructorBuilder = builder = ConstructorDefinitionBuilderImpl constructorBuilder = builder =
new ConstructorDefinitionBuilderImpl( ConstructorDefinitionBuilderImpl(
target as ConstructorDeclarationImpl, introspector); target as ConstructorDeclarationImpl, introspector);
await macro.buildDefinitionForConstructor(target, constructorBuilder); await macro.buildDefinitionForConstructor(target, constructorBuilder);
case (MethodDeclaration target, MethodDefinitionMacro macro): case (MethodDeclaration target, MethodDefinitionMacro macro):
@ -212,7 +212,7 @@ Future<MacroExecutionResult> executeDefinitionMacro(Macro macro, Object target,
case (VariableDeclaration target, VariableDefinitionMacro macro): case (VariableDeclaration target, VariableDefinitionMacro macro):
await macro.buildDefinitionForVariable(target, variableBuilder); await macro.buildDefinitionForVariable(target, variableBuilder);
default: default:
throw new UnsupportedError('Unsupported macro type or invalid target:\n' throw UnsupportedError('Unsupported macro type or invalid target:\n'
'macro: $macro\ntarget: $target'); 'macro: $macro\ntarget: $target');
} }
} catch (e, s) { } catch (e, s) {
@ -233,11 +233,11 @@ Future<MacroExecutionResult> executeDefinitionMacro(Macro macro, Object target,
// debug detail in a context message and suggest reporting to the author. // debug detail in a context message and suggest reporting to the author.
Diagnostic _unexpectedExceptionDiagnostic( Diagnostic _unexpectedExceptionDiagnostic(
Object thrown, StackTrace stackTrace) => Object thrown, StackTrace stackTrace) =>
new Diagnostic( Diagnostic(
new DiagnosticMessage( DiagnosticMessage(
'Macro application failed due to a bug in the macro.'), 'Macro application failed due to a bug in the macro.'),
Severity.error, Severity.error,
contextMessages: [ contextMessages: [
new DiagnosticMessage('$thrown\n$stackTrace'), DiagnosticMessage('$thrown\n$stackTrace'),
], ],
correctionMessage: 'Try reporting the failure to the macro author.'); correctionMessage: 'Try reporting the failure to the macro author.');

View File

@ -5,15 +5,14 @@
import 'dart:async'; import 'dart:async';
import 'dart:isolate'; import 'dart:isolate';
import 'package:_fe_analyzer_shared/src/macros/executor/exception_impls.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/remote_instance.dart';
import '../api.dart'; import '../api.dart';
import '../executor.dart'; import '../executor.dart';
import '../executor/introspection_impls.dart'; import 'exception_impls.dart';
import '../executor/protocol.dart'; import 'introspection_impls.dart';
import '../executor/serialization.dart'; import 'protocol.dart';
import '../executor/span.dart'; import 'remote_instance.dart';
import 'serialization.dart';
import 'span.dart';
/// Base implementation for macro executors which communicate with some external /// Base implementation for macro executors which communicate with some external
/// process to run macros. /// process to run macros.
@ -51,12 +50,11 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
// the client. // the client.
if (messageType == MessageType.response) { if (messageType == MessageType.response) {
SerializableResponse response = SerializableResponse response =
new SerializableResponse.deserialize(deserializer, zoneId); SerializableResponse.deserialize(deserializer, zoneId);
Completer<Response>? completer = Completer<Response>? completer =
_responseCompleters.remove(response.requestId); _responseCompleters.remove(response.requestId);
if (completer == null) { if (completer == null) {
throw new StateError( throw StateError('Got a response for an unrecognized request id '
'Got a response for an unrecognized request id '
'${response.requestId}'); '${response.requestId}');
} }
completer.complete(response); completer.complete(response);
@ -74,8 +72,7 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
switch (messageType) { switch (messageType) {
case MessageType.resolveIdentifierRequest: case MessageType.resolveIdentifierRequest:
ResolveIdentifierRequest request = ResolveIdentifierRequest request =
new ResolveIdentifierRequest.deserialize( ResolveIdentifierRequest.deserialize(deserializer, zoneId);
deserializer, zoneId);
requestId = request.id; requestId = request.id;
result = await (request.introspector.instance result = await (request.introspector.instance
as TypePhaseIntrospector) as TypePhaseIntrospector)
@ -85,12 +82,12 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
resultType = MessageType.remoteInstance; resultType = MessageType.remoteInstance;
case MessageType.resolveTypeRequest: case MessageType.resolveTypeRequest:
ResolveTypeRequest request = ResolveTypeRequest request =
new ResolveTypeRequest.deserialize(deserializer, zoneId); ResolveTypeRequest.deserialize(deserializer, zoneId);
requestId = request.id; requestId = request.id;
StaticType instance = await (request.introspector.instance StaticType instance = await (request.introspector.instance
as DeclarationPhaseIntrospector) as DeclarationPhaseIntrospector)
.resolve(request.typeAnnotationCode); .resolve(request.typeAnnotationCode);
result = new RemoteInstanceImpl( result = RemoteInstanceImpl(
id: RemoteInstance.uniqueId, id: RemoteInstance.uniqueId,
instance: instance, instance: instance,
kind: instance is NamedStaticType kind: instance is NamedStaticType
@ -101,7 +98,7 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
: MessageType.staticType; : MessageType.staticType;
case MessageType.inferTypeRequest: case MessageType.inferTypeRequest:
InferTypeRequest request = InferTypeRequest request =
new InferTypeRequest.deserialize(deserializer, zoneId); InferTypeRequest.deserialize(deserializer, zoneId);
requestId = request.id; requestId = request.id;
result = await (request.introspector.instance result = await (request.introspector.instance
as DefinitionPhaseIntrospector) as DefinitionPhaseIntrospector)
@ -109,25 +106,23 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
resultType = MessageType.remoteInstance; resultType = MessageType.remoteInstance;
case MessageType.isExactlyTypeRequest: case MessageType.isExactlyTypeRequest:
IsExactlyTypeRequest request = IsExactlyTypeRequest request =
new IsExactlyTypeRequest.deserialize(deserializer, zoneId); IsExactlyTypeRequest.deserialize(deserializer, zoneId);
requestId = request.id; requestId = request.id;
StaticType leftType = request.leftType.instance as StaticType; StaticType leftType = request.leftType.instance as StaticType;
StaticType rightType = request.rightType.instance as StaticType; StaticType rightType = request.rightType.instance as StaticType;
result = new BooleanValue(await leftType.isExactly(rightType)); result = BooleanValue(await leftType.isExactly(rightType));
resultType = MessageType.boolean; resultType = MessageType.boolean;
case MessageType.isSubtypeOfRequest: case MessageType.isSubtypeOfRequest:
IsSubtypeOfRequest request = IsSubtypeOfRequest request =
new IsSubtypeOfRequest.deserialize(deserializer, zoneId); IsSubtypeOfRequest.deserialize(deserializer, zoneId);
requestId = request.id; requestId = request.id;
StaticType leftType = request.leftType.instance as StaticType; StaticType leftType = request.leftType.instance as StaticType;
StaticType rightType = request.rightType.instance as StaticType; StaticType rightType = request.rightType.instance as StaticType;
result = result = BooleanValue(await leftType.isSubtypeOf(rightType));
new BooleanValue(await leftType.isSubtypeOf(rightType));
resultType = MessageType.boolean; resultType = MessageType.boolean;
case MessageType.declarationOfRequest: case MessageType.declarationOfRequest:
DeclarationOfRequest request = DeclarationOfRequest request = DeclarationOfRequest.deserialize(
new DeclarationOfRequest.deserialize( deserializer, zoneId, messageType);
deserializer, zoneId, messageType);
requestId = request.id; requestId = request.id;
DefinitionPhaseIntrospector introspector = request DefinitionPhaseIntrospector introspector = request
.introspector.instance as DefinitionPhaseIntrospector; .introspector.instance as DefinitionPhaseIntrospector;
@ -137,9 +132,8 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
as Serializable; as Serializable;
resultType = MessageType.remoteInstance; resultType = MessageType.remoteInstance;
case MessageType.typeDeclarationOfRequest: case MessageType.typeDeclarationOfRequest:
DeclarationOfRequest request = DeclarationOfRequest request = DeclarationOfRequest.deserialize(
new DeclarationOfRequest.deserialize( deserializer, zoneId, messageType);
deserializer, zoneId, messageType);
requestId = request.id; requestId = request.id;
DeclarationPhaseIntrospector introspector = request DeclarationPhaseIntrospector introspector = request
.introspector.instance as DeclarationPhaseIntrospector; .introspector.instance as DeclarationPhaseIntrospector;
@ -151,23 +145,23 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
resultType = MessageType.remoteInstance; resultType = MessageType.remoteInstance;
case MessageType.constructorsOfRequest: case MessageType.constructorsOfRequest:
TypeIntrospectorRequest request = TypeIntrospectorRequest request =
new TypeIntrospectorRequest.deserialize( TypeIntrospectorRequest.deserialize(
deserializer, messageType, zoneId); deserializer, messageType, zoneId);
requestId = request.id; requestId = request.id;
DeclarationPhaseIntrospector introspector = request DeclarationPhaseIntrospector introspector = request
.introspector.instance as DeclarationPhaseIntrospector; .introspector.instance as DeclarationPhaseIntrospector;
result = new DeclarationList((await introspector result = DeclarationList((await introspector
.constructorsOf(request.declaration as TypeDeclaration)) .constructorsOf(request.declaration as TypeDeclaration))
// TODO: Consider refactoring to avoid the need for this. // TODO: Consider refactoring to avoid the need for this.
.cast<ConstructorDeclarationImpl>()); .cast<ConstructorDeclarationImpl>());
resultType = MessageType.declarationList; resultType = MessageType.declarationList;
case MessageType.topLevelDeclarationsOfRequest: case MessageType.topLevelDeclarationsOfRequest:
DeclarationsOfRequest request = DeclarationsOfRequest request =
new DeclarationsOfRequest.deserialize(deserializer, zoneId); DeclarationsOfRequest.deserialize(deserializer, zoneId);
requestId = request.id; requestId = request.id;
DefinitionPhaseIntrospector introspector = request DefinitionPhaseIntrospector introspector = request
.introspector.instance as DefinitionPhaseIntrospector; .introspector.instance as DefinitionPhaseIntrospector;
result = new DeclarationList(// force newline result = DeclarationList(// force newline
(await introspector.topLevelDeclarationsOf(request.library)) (await introspector.topLevelDeclarationsOf(request.library))
// TODO: Consider refactoring to avoid the need for // TODO: Consider refactoring to avoid the need for
// this. // this.
@ -175,56 +169,56 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
resultType = MessageType.declarationList; resultType = MessageType.declarationList;
case MessageType.fieldsOfRequest: case MessageType.fieldsOfRequest:
TypeIntrospectorRequest request = TypeIntrospectorRequest request =
new TypeIntrospectorRequest.deserialize( TypeIntrospectorRequest.deserialize(
deserializer, messageType, zoneId); deserializer, messageType, zoneId);
requestId = request.id; requestId = request.id;
DeclarationPhaseIntrospector introspector = request DeclarationPhaseIntrospector introspector = request
.introspector.instance as DeclarationPhaseIntrospector; .introspector.instance as DeclarationPhaseIntrospector;
result = new DeclarationList((await introspector result = DeclarationList((await introspector
.fieldsOf(request.declaration as TypeDeclaration)) .fieldsOf(request.declaration as TypeDeclaration))
// TODO: Consider refactoring to avoid the need for this. // TODO: Consider refactoring to avoid the need for this.
.cast<FieldDeclarationImpl>()); .cast<FieldDeclarationImpl>());
resultType = MessageType.declarationList; resultType = MessageType.declarationList;
case MessageType.methodsOfRequest: case MessageType.methodsOfRequest:
TypeIntrospectorRequest request = TypeIntrospectorRequest request =
new TypeIntrospectorRequest.deserialize( TypeIntrospectorRequest.deserialize(
deserializer, messageType, zoneId); deserializer, messageType, zoneId);
requestId = request.id; requestId = request.id;
DeclarationPhaseIntrospector introspector = request DeclarationPhaseIntrospector introspector = request
.introspector.instance as DeclarationPhaseIntrospector; .introspector.instance as DeclarationPhaseIntrospector;
result = new DeclarationList((await introspector result = DeclarationList((await introspector
.methodsOf(request.declaration as TypeDeclaration)) .methodsOf(request.declaration as TypeDeclaration))
// TODO: Consider refactoring to avoid the need for this. // TODO: Consider refactoring to avoid the need for this.
.cast<MethodDeclarationImpl>()); .cast<MethodDeclarationImpl>());
resultType = MessageType.declarationList; resultType = MessageType.declarationList;
case MessageType.typesOfRequest: case MessageType.typesOfRequest:
TypeIntrospectorRequest request = TypeIntrospectorRequest request =
new TypeIntrospectorRequest.deserialize( TypeIntrospectorRequest.deserialize(
deserializer, messageType, zoneId); deserializer, messageType, zoneId);
requestId = request.id; requestId = request.id;
DeclarationPhaseIntrospector introspector = request DeclarationPhaseIntrospector introspector = request
.introspector.instance as DeclarationPhaseIntrospector; .introspector.instance as DeclarationPhaseIntrospector;
result = new DeclarationList((await introspector result = DeclarationList((await introspector
.typesOf(request.declaration as Library)) .typesOf(request.declaration as Library))
// TODO: Consider refactoring to avoid the need for this. // TODO: Consider refactoring to avoid the need for this.
.cast<TypeDeclarationImpl>()); .cast<TypeDeclarationImpl>());
resultType = MessageType.declarationList; resultType = MessageType.declarationList;
case MessageType.valuesOfRequest: case MessageType.valuesOfRequest:
TypeIntrospectorRequest request = TypeIntrospectorRequest request =
new TypeIntrospectorRequest.deserialize( TypeIntrospectorRequest.deserialize(
deserializer, messageType, zoneId); deserializer, messageType, zoneId);
requestId = request.id; requestId = request.id;
DeclarationPhaseIntrospector introspector = request DeclarationPhaseIntrospector introspector = request
.introspector.instance as DeclarationPhaseIntrospector; .introspector.instance as DeclarationPhaseIntrospector;
result = new DeclarationList((await introspector result = DeclarationList((await introspector
.valuesOf(request.declaration as EnumDeclaration)) .valuesOf(request.declaration as EnumDeclaration))
// TODO: Consider refactoring to avoid the need for this. // TODO: Consider refactoring to avoid the need for this.
.cast<EnumValueDeclarationImpl>()); .cast<EnumValueDeclarationImpl>());
resultType = MessageType.declarationList; resultType = MessageType.declarationList;
default: default:
throw new StateError('Unexpected message type $messageType'); throw StateError('Unexpected message type $messageType');
} }
response = new SerializableResponse( response = SerializableResponse(
response: result, response: result,
requestId: requestId, requestId: requestId,
responseType: resultType, responseType: resultType,
@ -232,8 +226,8 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
} catch (error, stackTrace) { } catch (error, stackTrace) {
// TODO: Something better here. // TODO: Something better here.
if (requestId == null) rethrow; if (requestId == null) rethrow;
response = new SerializableResponse( response = SerializableResponse(
exception: new MacroExceptionImpl.from(error, stackTrace), exception: MacroExceptionImpl.from(error, stackTrace),
requestId: requestId, requestId: requestId,
responseType: MessageType.exception, responseType: MessageType.exception,
serializationZoneId: zoneId); serializationZoneId: zoneId);
@ -256,17 +250,17 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
TypeAnnotation? Function(OmittedTypeAnnotation) inferOmittedType, TypeAnnotation? Function(OmittedTypeAnnotation) inferOmittedType,
{Map<OmittedTypeAnnotation, String>? omittedTypes, {Map<OmittedTypeAnnotation, String>? omittedTypes,
List<Span>? spans}) => List<Span>? spans}) =>
throw new StateError('Unreachable'); throw StateError('Unreachable');
@override @override
Future<MacroExecutionResult> executeDeclarationsPhase( Future<MacroExecutionResult> executeDeclarationsPhase(
MacroInstanceIdentifier macro, MacroInstanceIdentifier macro,
MacroTarget target, MacroTarget target,
DeclarationPhaseIntrospector introspector) => DeclarationPhaseIntrospector introspector) =>
_sendRequest((zoneId) => new ExecuteDeclarationsPhaseRequest( _sendRequest((zoneId) => ExecuteDeclarationsPhaseRequest(
macro, macro,
target as RemoteInstance, target as RemoteInstance,
new RemoteInstanceImpl( RemoteInstanceImpl(
instance: introspector, instance: introspector,
id: RemoteInstance.uniqueId, id: RemoteInstance.uniqueId,
kind: RemoteInstanceKind.declarationPhaseIntrospector), kind: RemoteInstanceKind.declarationPhaseIntrospector),
@ -277,10 +271,10 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
MacroInstanceIdentifier macro, MacroInstanceIdentifier macro,
MacroTarget target, MacroTarget target,
DefinitionPhaseIntrospector introspector) => DefinitionPhaseIntrospector introspector) =>
_sendRequest((zoneId) => new ExecuteDefinitionsPhaseRequest( _sendRequest((zoneId) => ExecuteDefinitionsPhaseRequest(
macro, macro,
target as RemoteInstance, target as RemoteInstance,
new RemoteInstanceImpl( RemoteInstanceImpl(
instance: introspector, instance: introspector,
id: RemoteInstance.uniqueId, id: RemoteInstance.uniqueId,
kind: RemoteInstanceKind.definitionPhaseIntrospector), kind: RemoteInstanceKind.definitionPhaseIntrospector),
@ -289,10 +283,10 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
@override @override
Future<MacroExecutionResult> executeTypesPhase(MacroInstanceIdentifier macro, Future<MacroExecutionResult> executeTypesPhase(MacroInstanceIdentifier macro,
MacroTarget target, TypePhaseIntrospector introspector) => MacroTarget target, TypePhaseIntrospector introspector) =>
_sendRequest((zoneId) => new ExecuteTypesPhaseRequest( _sendRequest((zoneId) => ExecuteTypesPhaseRequest(
macro, macro,
target as RemoteInstance, target as RemoteInstance,
new RemoteInstanceImpl( RemoteInstanceImpl(
instance: introspector, instance: introspector,
id: RemoteInstance.uniqueId, id: RemoteInstance.uniqueId,
kind: RemoteInstanceKind.typePhaseIntrospector), kind: RemoteInstanceKind.typePhaseIntrospector),
@ -301,14 +295,13 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
@override @override
Future<MacroInstanceIdentifier> instantiateMacro( Future<MacroInstanceIdentifier> instantiateMacro(
Uri library, String name, String constructor, Arguments arguments) => Uri library, String name, String constructor, Arguments arguments) =>
_sendRequest((zoneId) => new InstantiateMacroRequest( _sendRequest((zoneId) => InstantiateMacroRequest(
library, name, constructor, arguments, RemoteInstance.uniqueId, library, name, constructor, arguments, RemoteInstance.uniqueId,
serializationZoneId: zoneId)); serializationZoneId: zoneId));
@override @override
void disposeMacro(MacroInstanceIdentifier instance) => void disposeMacro(MacroInstanceIdentifier instance) => _sendRequest(
_sendRequest((zoneId) => (zoneId) => DisposeMacroRequest(instance, serializationZoneId: zoneId));
new DisposeMacroRequest(instance, serializationZoneId: zoneId));
/// Sends [serializer.result] to [sendPort], possibly wrapping it in a /// Sends [serializer.result] to [sendPort], possibly wrapping it in a
/// [TransferableTypedData] object. /// [TransferableTypedData] object.
@ -318,8 +311,8 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
/// response, casting it to the expected type or throwing the error provided. /// response, casting it to the expected type or throwing the error provided.
Future<T> _sendRequest<T>(Request Function(int) requestFactory) { Future<T> _sendRequest<T>(Request Function(int) requestFactory) {
if (isClosed) { if (isClosed) {
throw new UnexpectedMacroExceptionImpl( throw UnexpectedMacroExceptionImpl(
"Can't send request - ${this.runtimeType} is closed!"); "Can't send request - $runtimeType is closed!");
} }
return withSerializationMode(serializationMode, () { return withSerializationMode(serializationMode, () {
final int zoneId = newRemoteInstanceZone(); final int zoneId = newRemoteInstanceZone();
@ -330,7 +323,7 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
serializer.addInt(zoneId); serializer.addInt(zoneId);
request.serialize(serializer); request.serialize(serializer);
sendResult(serializer); sendResult(serializer);
Completer<Response> completer = new Completer<Response>(); Completer<Response> completer = Completer<Response>();
_responseCompleters[request.id] = completer; _responseCompleters[request.id] = completer;
try { try {
Response response = await completer.future; Response response = await completer.future;
@ -343,7 +336,7 @@ abstract class ExternalMacroExecutorBase extends MacroExecutor {
// Tell the remote client to clean it up as well. // Tell the remote client to clean it up as well.
Serializer serializer = serializerFactory(); Serializer serializer = serializerFactory();
serializer.addInt(zoneId); serializer.addInt(zoneId);
new DestroyRemoteInstanceZoneRequest(serializationZoneId: zoneId) DestroyRemoteInstanceZoneRequest(serializationZoneId: zoneId)
.serialize(serializer); .serialize(serializer);
sendResult(serializer); sendResult(serializer);
} }

View File

@ -50,7 +50,7 @@ class NamedTypeAnnotationImpl extends TypeAnnotationImpl
@override @override
TypeAnnotationCode get code { TypeAnnotationCode get code {
NamedTypeAnnotationCode underlyingType = NamedTypeAnnotationCode underlyingType =
new NamedTypeAnnotationCode(name: identifier, typeArguments: [ NamedTypeAnnotationCode(name: identifier, typeArguments: [
for (TypeAnnotation typeArg in typeArguments) typeArg.code, for (TypeAnnotation typeArg in typeArguments) typeArg.code,
]); ]);
return isNullable ? underlyingType.asNullable : underlyingType; return isNullable ? underlyingType.asNullable : underlyingType;
@ -89,7 +89,7 @@ class RecordTypeAnnotationImpl extends TypeAnnotationImpl
implements RecordTypeAnnotation { implements RecordTypeAnnotation {
@override @override
TypeAnnotationCode get code { TypeAnnotationCode get code {
RecordTypeAnnotationCode underlyingType = new RecordTypeAnnotationCode( RecordTypeAnnotationCode underlyingType = RecordTypeAnnotationCode(
namedFields: [for (RecordFieldImpl field in namedFields) field.code], namedFields: [for (RecordFieldImpl field in namedFields) field.code],
positionalFields: [ positionalFields: [
for (RecordFieldImpl field in positionalFields) field.code for (RecordFieldImpl field in positionalFields) field.code
@ -135,7 +135,7 @@ class RecordTypeAnnotationImpl extends TypeAnnotationImpl
class RecordFieldImpl extends RemoteInstance implements RecordField { class RecordFieldImpl extends RemoteInstance implements RecordField {
@override @override
RecordFieldCode get code { RecordFieldCode get code {
return new RecordFieldCode(type: type.code, name: name); return RecordFieldCode(type: type.code, name: name);
} }
@override @override
@ -166,7 +166,7 @@ class FunctionTypeAnnotationImpl extends TypeAnnotationImpl
implements FunctionTypeAnnotation { implements FunctionTypeAnnotation {
@override @override
TypeAnnotationCode get code { TypeAnnotationCode get code {
FunctionTypeAnnotationCode underlyingType = new FunctionTypeAnnotationCode( FunctionTypeAnnotationCode underlyingType = FunctionTypeAnnotationCode(
returnType: returnType.code, returnType: returnType.code,
typeParameters: [ typeParameters: [
for (TypeParameter typeParam in typeParameters) typeParam.code, for (TypeParameter typeParam in typeParameters) typeParam.code,
@ -241,7 +241,7 @@ class OmittedTypeAnnotationImpl extends TypeAnnotationImpl
OmittedTypeAnnotationImpl({required super.id}) : super(isNullable: false); OmittedTypeAnnotationImpl({required super.id}) : super(isNullable: false);
@override @override
TypeAnnotationCode get code => new OmittedTypeAnnotationCode(this); TypeAnnotationCode get code => OmittedTypeAnnotationCode(this);
@override @override
RemoteInstanceKind get kind => RemoteInstanceKind.omittedTypeAnnotation; RemoteInstanceKind get kind => RemoteInstanceKind.omittedTypeAnnotation;
@ -381,21 +381,21 @@ class FormalParameterDeclarationImpl extends DeclarationImpl
required super.identifier, required super.identifier,
required super.library, required super.library,
required super.metadata, required super.metadata,
required BitMask<_ParameterIntrospectionBit> bitMask, required BitMask<ParameterIntrospectionBit> bitMask,
required this.type, required this.type,
}) : isNamed = bitMask.has(_ParameterIntrospectionBit.isNamed), }) : isNamed = bitMask.has(ParameterIntrospectionBit.isNamed),
isRequired = bitMask.has(_ParameterIntrospectionBit.isRequired); isRequired = bitMask.has(ParameterIntrospectionBit.isRequired);
/// If subclasses have their own values to add to [bitMask], they must do so /// If subclasses have their own values to add to [bitMask], they must do so
/// before calling this function, and pass the mask here. /// before calling this function, and pass the mask here.
@override @override
void serializeUncached(Serializer serializer, void serializeUncached(Serializer serializer,
{BitMask<_ParameterIntrospectionBit>? bitMask}) { {BitMask<ParameterIntrospectionBit>? bitMask}) {
super.serializeUncached(serializer); super.serializeUncached(serializer);
bitMask ??= new BitMask(); bitMask ??= BitMask();
if (isNamed) bitMask.add(_ParameterIntrospectionBit.isNamed); if (isNamed) bitMask.add(ParameterIntrospectionBit.isNamed);
if (isRequired) bitMask.add(_ParameterIntrospectionBit.isRequired); if (isRequired) bitMask.add(ParameterIntrospectionBit.isRequired);
bitMask.freeze(); bitMask.freeze();
serializer.addInt(bitMask._mask); serializer.addInt(bitMask._mask);
type.serialize(serializer); type.serialize(serializer);
@ -403,7 +403,7 @@ class FormalParameterDeclarationImpl extends DeclarationImpl
@override @override
ParameterCode get code => ParameterCode get code =>
new ParameterCode(name: identifier.name, type: type.code, keywords: [ ParameterCode(name: identifier.name, type: type.code, keywords: [
if (isNamed && isRequired) 'required', if (isNamed && isRequired) 'required',
]); ]);
} }
@ -438,24 +438,24 @@ class FormalParameterImpl extends RemoteInstance implements FormalParameter {
FormalParameterImpl.fromBitMask({ FormalParameterImpl.fromBitMask({
required int id, required int id,
required BitMask<_ParameterIntrospectionBit> bitMask, required BitMask<ParameterIntrospectionBit> bitMask,
required this.metadata, required this.metadata,
required this.name, required this.name,
required this.type, required this.type,
}) : isNamed = bitMask.has(_ParameterIntrospectionBit.isNamed), }) : isNamed = bitMask.has(ParameterIntrospectionBit.isNamed),
isRequired = bitMask.has(_ParameterIntrospectionBit.isRequired), isRequired = bitMask.has(ParameterIntrospectionBit.isRequired),
super(id); super(id);
/// If subclasses have their own values to add to [bitMask], they must do so /// If subclasses have their own values to add to [bitMask], they must do so
/// before calling this function, and pass the mask here. /// before calling this function, and pass the mask here.
@override @override
void serializeUncached(Serializer serializer, void serializeUncached(Serializer serializer,
{BitMask<_ParameterIntrospectionBit>? bitMask}) { {BitMask<ParameterIntrospectionBit>? bitMask}) {
super.serializeUncached(serializer); super.serializeUncached(serializer);
bitMask ??= new BitMask(); bitMask ??= BitMask();
if (isNamed) bitMask.add(_ParameterIntrospectionBit.isNamed); if (isNamed) bitMask.add(ParameterIntrospectionBit.isNamed);
if (isRequired) bitMask.add(_ParameterIntrospectionBit.isRequired); if (isRequired) bitMask.add(ParameterIntrospectionBit.isRequired);
bitMask.freeze(); bitMask.freeze();
serializer serializer
..addInt(bitMask._mask) ..addInt(bitMask._mask)
@ -470,7 +470,7 @@ class FormalParameterImpl extends RemoteInstance implements FormalParameter {
@override @override
ParameterCode get code => ParameterCode get code =>
new ParameterCode(name: name, type: type.code, keywords: [ ParameterCode(name: name, type: type.code, keywords: [
if (isNamed && isRequired) 'required', if (isNamed && isRequired) 'required',
]); ]);
} }
@ -487,7 +487,7 @@ class TypeParameterImpl extends RemoteInstance implements TypeParameter {
@override @override
TypeParameterCode get code => TypeParameterCode get code =>
new TypeParameterCode(name: name, bound: bound?.code); TypeParameterCode(name: name, bound: bound?.code);
@override @override
RemoteInstanceKind get kind => RemoteInstanceKind.typeParameter; RemoteInstanceKind get kind => RemoteInstanceKind.typeParameter;
@ -541,7 +541,7 @@ class TypeParameterDeclarationImpl extends DeclarationImpl
@override @override
TypeParameterCode get code => TypeParameterCode get code =>
new TypeParameterCode(name: identifier.name, bound: bound?.code); TypeParameterCode(name: identifier.name, bound: bound?.code);
} }
class FunctionDeclarationImpl extends DeclarationImpl class FunctionDeclarationImpl extends DeclarationImpl
@ -599,30 +599,30 @@ class FunctionDeclarationImpl extends DeclarationImpl
required super.identifier, required super.identifier,
required super.library, required super.library,
required super.metadata, required super.metadata,
required BitMask<_FunctionIntrospectionBit> bitMask, required BitMask<FunctionIntrospectionBit> bitMask,
required this.namedParameters, required this.namedParameters,
required this.positionalParameters, required this.positionalParameters,
required this.returnType, required this.returnType,
required this.typeParameters, required this.typeParameters,
}) : hasBody = bitMask.has(_FunctionIntrospectionBit.hasBody), }) : hasBody = bitMask.has(FunctionIntrospectionBit.hasBody),
hasExternal = bitMask.has(_FunctionIntrospectionBit.hasExternal), hasExternal = bitMask.has(FunctionIntrospectionBit.hasExternal),
isGetter = bitMask.has(_FunctionIntrospectionBit.isGetter), isGetter = bitMask.has(FunctionIntrospectionBit.isGetter),
isOperator = bitMask.has(_FunctionIntrospectionBit.isOperator), isOperator = bitMask.has(FunctionIntrospectionBit.isOperator),
isSetter = bitMask.has(_FunctionIntrospectionBit.isSetter); isSetter = bitMask.has(FunctionIntrospectionBit.isSetter);
/// If subclasses have their own values to add to [bitMask], they must do so /// If subclasses have their own values to add to [bitMask], they must do so
/// before calling this function, and pass the mask here. /// before calling this function, and pass the mask here.
@override @override
void serializeUncached(Serializer serializer, void serializeUncached(Serializer serializer,
{BitMask<_FunctionIntrospectionBit>? bitMask}) { {BitMask<FunctionIntrospectionBit>? bitMask}) {
super.serializeUncached(serializer); super.serializeUncached(serializer);
bitMask ??= new BitMask(); bitMask ??= BitMask();
if (hasBody) bitMask.add(_FunctionIntrospectionBit.hasBody); if (hasBody) bitMask.add(FunctionIntrospectionBit.hasBody);
if (hasExternal) bitMask.add(_FunctionIntrospectionBit.hasExternal); if (hasExternal) bitMask.add(FunctionIntrospectionBit.hasExternal);
if (isGetter) bitMask.add(_FunctionIntrospectionBit.isGetter); if (isGetter) bitMask.add(FunctionIntrospectionBit.isGetter);
if (isOperator) bitMask.add(_FunctionIntrospectionBit.isOperator); if (isOperator) bitMask.add(FunctionIntrospectionBit.isOperator);
if (isSetter) bitMask.add(_FunctionIntrospectionBit.isSetter); if (isSetter) bitMask.add(FunctionIntrospectionBit.isSetter);
bitMask.freeze(); bitMask.freeze();
serializer serializer
..addInt(bitMask._mask) ..addInt(bitMask._mask)
@ -692,16 +692,16 @@ class MethodDeclarationImpl extends FunctionDeclarationImpl
required super.typeParameters, required super.typeParameters,
// Method fields. // Method fields.
required this.definingType, required this.definingType,
}) : hasStatic = bitMask.has(_FunctionIntrospectionBit.hasStatic), }) : hasStatic = bitMask.has(FunctionIntrospectionBit.hasStatic),
super.fromBitMask(); super.fromBitMask();
/// If subclasses have their own values to add to [bitMask], they must do so /// If subclasses have their own values to add to [bitMask], they must do so
/// before calling this function, and pass the mask here. /// before calling this function, and pass the mask here.
@override @override
void serializeUncached(Serializer serializer, void serializeUncached(Serializer serializer,
{BitMask<_FunctionIntrospectionBit>? bitMask}) { {BitMask<FunctionIntrospectionBit>? bitMask}) {
bitMask ??= new BitMask(); bitMask ??= BitMask();
if (hasStatic) bitMask.add(_FunctionIntrospectionBit.hasStatic); if (hasStatic) bitMask.add(FunctionIntrospectionBit.hasStatic);
super.serializeUncached(serializer, bitMask: bitMask); super.serializeUncached(serializer, bitMask: bitMask);
definingType.serialize(serializer); definingType.serialize(serializer);
@ -754,16 +754,16 @@ class ConstructorDeclarationImpl extends MethodDeclarationImpl
required super.typeParameters, required super.typeParameters,
// Method fields. // Method fields.
required super.definingType, required super.definingType,
}) : isFactory = bitMask.has(_FunctionIntrospectionBit.isFactory), }) : isFactory = bitMask.has(FunctionIntrospectionBit.isFactory),
super.fromBitMask(); super.fromBitMask();
/// If subclasses have their own values to add to [bitMask], they must do so /// If subclasses have their own values to add to [bitMask], they must do so
/// before calling this function, and pass the mask here. /// before calling this function, and pass the mask here.
@override @override
void serializeUncached(Serializer serializer, void serializeUncached(Serializer serializer,
{BitMask<_FunctionIntrospectionBit>? bitMask}) { {BitMask<FunctionIntrospectionBit>? bitMask}) {
bitMask ??= new BitMask(); bitMask ??= BitMask();
if (isFactory) bitMask.add(_FunctionIntrospectionBit.isFactory); if (isFactory) bitMask.add(FunctionIntrospectionBit.isFactory);
super.serializeUncached(serializer, bitMask: bitMask); super.serializeUncached(serializer, bitMask: bitMask);
} }
} }
@ -811,27 +811,27 @@ class VariableDeclarationImpl extends DeclarationImpl
required super.identifier, required super.identifier,
required super.library, required super.library,
required super.metadata, required super.metadata,
required BitMask<_VariableIntrospectionBit> bitMask, required BitMask<VariableIntrospectionBit> bitMask,
required this.type, required this.type,
}) : hasConst = bitMask.has(_VariableIntrospectionBit.hasConst), }) : hasConst = bitMask.has(VariableIntrospectionBit.hasConst),
hasExternal = bitMask.has(_VariableIntrospectionBit.hasExternal), hasExternal = bitMask.has(VariableIntrospectionBit.hasExternal),
hasFinal = bitMask.has(_VariableIntrospectionBit.hasFinal), hasFinal = bitMask.has(VariableIntrospectionBit.hasFinal),
hasInitializer = bitMask.has(_VariableIntrospectionBit.hasInitializer), hasInitializer = bitMask.has(VariableIntrospectionBit.hasInitializer),
hasLate = bitMask.has(_VariableIntrospectionBit.hasLate); hasLate = bitMask.has(VariableIntrospectionBit.hasLate);
/// If subclasses have their own values to add to [bitMask], they must do so /// If subclasses have their own values to add to [bitMask], they must do so
/// before calling this function, and pass the mask here. /// before calling this function, and pass the mask here.
@override @override
void serializeUncached(Serializer serializer, void serializeUncached(Serializer serializer,
{BitMask<_VariableIntrospectionBit>? bitMask}) { {BitMask<VariableIntrospectionBit>? bitMask}) {
super.serializeUncached(serializer); super.serializeUncached(serializer);
bitMask ??= new BitMask(); bitMask ??= BitMask();
if (hasConst) bitMask.add(_VariableIntrospectionBit.hasConst); if (hasConst) bitMask.add(VariableIntrospectionBit.hasConst);
if (hasExternal) bitMask.add(_VariableIntrospectionBit.hasExternal); if (hasExternal) bitMask.add(VariableIntrospectionBit.hasExternal);
if (hasFinal) bitMask.add(_VariableIntrospectionBit.hasFinal); if (hasFinal) bitMask.add(VariableIntrospectionBit.hasFinal);
if (hasInitializer) bitMask.add(_VariableIntrospectionBit.hasInitializer); if (hasInitializer) bitMask.add(VariableIntrospectionBit.hasInitializer);
if (hasLate) bitMask.add(_VariableIntrospectionBit.hasLate); if (hasLate) bitMask.add(VariableIntrospectionBit.hasLate);
bitMask.freeze(); bitMask.freeze();
serializer.addInt(bitMask._mask); serializer.addInt(bitMask._mask);
type.serialize(serializer); type.serialize(serializer);
@ -879,8 +879,8 @@ class FieldDeclarationImpl extends VariableDeclarationImpl
required super.type, required super.type,
// Field fields. // Field fields.
required this.definingType, required this.definingType,
}) : hasAbstract = bitMask.has(_VariableIntrospectionBit.hasAbstract), }) : hasAbstract = bitMask.has(VariableIntrospectionBit.hasAbstract),
hasStatic = bitMask.has(_VariableIntrospectionBit.hasStatic), hasStatic = bitMask.has(VariableIntrospectionBit.hasStatic),
super.fromBitMask(); super.fromBitMask();
@override @override
@ -890,10 +890,10 @@ class FieldDeclarationImpl extends VariableDeclarationImpl
/// before calling this function, and pass the mask here. /// before calling this function, and pass the mask here.
@override @override
void serializeUncached(Serializer serializer, void serializeUncached(Serializer serializer,
{BitMask<_VariableIntrospectionBit>? bitMask}) { {BitMask<VariableIntrospectionBit>? bitMask}) {
bitMask ??= new BitMask(); bitMask ??= BitMask();
if (hasAbstract) bitMask.add(_VariableIntrospectionBit.hasAbstract); if (hasAbstract) bitMask.add(VariableIntrospectionBit.hasAbstract);
if (hasStatic) bitMask.add(_VariableIntrospectionBit.hasStatic); if (hasStatic) bitMask.add(VariableIntrospectionBit.hasStatic);
super.serializeUncached(serializer, bitMask: bitMask); super.serializeUncached(serializer, bitMask: bitMask);
definingType.serialize(serializer); definingType.serialize(serializer);
@ -920,7 +920,7 @@ abstract class ParameterizedTypeDeclarationImpl extends DeclarationImpl
void serializeUncached(Serializer serializer) { void serializeUncached(Serializer serializer) {
super.serializeUncached(serializer); super.serializeUncached(serializer);
serializer..startList(); serializer.startList();
for (TypeParameterDeclarationImpl param in typeParameters) { for (TypeParameterDeclarationImpl param in typeParameters) {
param.serialize(serializer); param.serialize(serializer);
} }
@ -993,17 +993,17 @@ class ClassDeclarationImpl extends ParameterizedTypeDeclarationImpl
// TypeDeclaration fields. // TypeDeclaration fields.
required super.typeParameters, required super.typeParameters,
// ClassDeclaration fields. // ClassDeclaration fields.
required BitMask<_ClassIntrospectionBit> bitMask, required BitMask<ClassIntrospectionBit> bitMask,
required this.interfaces, required this.interfaces,
required this.mixins, required this.mixins,
required this.superclass, required this.superclass,
}) : hasAbstract = bitMask.has(_ClassIntrospectionBit.hasAbstract), }) : hasAbstract = bitMask.has(ClassIntrospectionBit.hasAbstract),
hasBase = bitMask.has(_ClassIntrospectionBit.hasBase), hasBase = bitMask.has(ClassIntrospectionBit.hasBase),
hasExternal = bitMask.has(_ClassIntrospectionBit.hasExternal), hasExternal = bitMask.has(ClassIntrospectionBit.hasExternal),
hasFinal = bitMask.has(_ClassIntrospectionBit.hasFinal), hasFinal = bitMask.has(ClassIntrospectionBit.hasFinal),
hasInterface = bitMask.has(_ClassIntrospectionBit.hasInterface), hasInterface = bitMask.has(ClassIntrospectionBit.hasInterface),
hasMixin = bitMask.has(_ClassIntrospectionBit.hasMixin), hasMixin = bitMask.has(ClassIntrospectionBit.hasMixin),
hasSealed = bitMask.has(_ClassIntrospectionBit.hasSealed); hasSealed = bitMask.has(ClassIntrospectionBit.hasSealed);
/// If subclasses have their own values to add to [bitMask], they must do so /// If subclasses have their own values to add to [bitMask], they must do so
/// before calling this function, and pass the mask here. /// before calling this function, and pass the mask here.
@ -1011,14 +1011,14 @@ class ClassDeclarationImpl extends ParameterizedTypeDeclarationImpl
void serializeUncached(Serializer serializer, {BitMask? bitMask}) { void serializeUncached(Serializer serializer, {BitMask? bitMask}) {
super.serializeUncached(serializer); super.serializeUncached(serializer);
bitMask ??= new BitMask(); bitMask ??= BitMask();
if (hasAbstract) bitMask.add(_ClassIntrospectionBit.hasAbstract); if (hasAbstract) bitMask.add(ClassIntrospectionBit.hasAbstract);
if (hasBase) bitMask.add(_ClassIntrospectionBit.hasBase); if (hasBase) bitMask.add(ClassIntrospectionBit.hasBase);
if (hasExternal) bitMask.add(_ClassIntrospectionBit.hasExternal); if (hasExternal) bitMask.add(ClassIntrospectionBit.hasExternal);
if (hasFinal) bitMask.add(_ClassIntrospectionBit.hasFinal); if (hasFinal) bitMask.add(ClassIntrospectionBit.hasFinal);
if (hasInterface) bitMask.add(_ClassIntrospectionBit.hasInterface); if (hasInterface) bitMask.add(ClassIntrospectionBit.hasInterface);
if (hasMixin) bitMask.add(_ClassIntrospectionBit.hasMixin); if (hasMixin) bitMask.add(ClassIntrospectionBit.hasMixin);
if (hasSealed) bitMask.add(_ClassIntrospectionBit.hasSealed); if (hasSealed) bitMask.add(ClassIntrospectionBit.hasSealed);
bitMask.freeze(); bitMask.freeze();
serializer serializer
..addInt(bitMask._mask) ..addInt(bitMask._mask)
@ -1032,7 +1032,7 @@ class ClassDeclarationImpl extends ParameterizedTypeDeclarationImpl
for (NamedTypeAnnotationImpl mixin in mixins) { for (NamedTypeAnnotationImpl mixin in mixins) {
mixin.serialize(serializer); mixin.serialize(serializer);
} }
serializer..endList(); serializer.endList();
superclass.serializeNullable(serializer); superclass.serializeNullable(serializer);
} }
} }
@ -1075,7 +1075,7 @@ class EnumDeclarationImpl extends ParameterizedTypeDeclarationImpl
for (NamedTypeAnnotationImpl mixin in mixins) { for (NamedTypeAnnotationImpl mixin in mixins) {
mixin.serialize(serializer); mixin.serialize(serializer);
} }
serializer..endList(); serializer.endList();
} }
} }
@ -1203,7 +1203,7 @@ class MixinDeclarationImpl extends ParameterizedTypeDeclarationImpl
for (NamedTypeAnnotationImpl constraint in superclassConstraints) { for (NamedTypeAnnotationImpl constraint in superclassConstraints) {
constraint.serialize(serializer); constraint.serialize(serializer);
} }
serializer..endList(); serializer.endList();
} }
} }
@ -1303,7 +1303,7 @@ final class BitMask<T extends Enum> {
); );
void add(T bit) { void add(T bit) {
if (_frozen) throw new StateError('Cannot modify a frozen BitMask'); if (_frozen) throw StateError('Cannot modify a frozen BitMask');
_mask |= bit.mask; _mask |= bit.mask;
} }
@ -1315,7 +1315,7 @@ final class BitMask<T extends Enum> {
} }
/// Defines the bits for the bit mask for all boolean class fields. /// Defines the bits for the bit mask for all boolean class fields.
enum _ClassIntrospectionBit { enum ClassIntrospectionBit {
hasAbstract, hasAbstract,
hasBase, hasBase,
hasExternal, hasExternal,
@ -1326,7 +1326,7 @@ enum _ClassIntrospectionBit {
} }
/// Defines the bits for the bit mask for all boolean function fields. /// Defines the bits for the bit mask for all boolean function fields.
enum _FunctionIntrospectionBit { enum FunctionIntrospectionBit {
hasBody, hasBody,
hasExternal, hasExternal,
hasStatic, hasStatic,
@ -1337,13 +1337,13 @@ enum _FunctionIntrospectionBit {
} }
/// Defines the bits for the bit mask for all boolean parameter fields. /// Defines the bits for the bit mask for all boolean parameter fields.
enum _ParameterIntrospectionBit { enum ParameterIntrospectionBit {
isNamed, isNamed,
isRequired, isRequired,
} }
/// Defines the bits for the bit mask for all boolean variable fields. /// Defines the bits for the bit mask for all boolean variable fields.
enum _VariableIntrospectionBit { enum VariableIntrospectionBit {
hasAbstract, hasAbstract,
hasConst, hasConst,
hasExternal, hasExternal,

View File

@ -45,14 +45,14 @@ class _SingleIsolatedMacroExecutor extends ExternalMacroExecutorBase {
SerializationMode serializationMode, SerializationMode serializationMode,
List<String> arguments, List<String> arguments,
Uri? packageConfig) async { Uri? packageConfig) async {
ReceivePort receivePort = new ReceivePort(); ReceivePort receivePort = ReceivePort();
Isolate isolate = await Isolate.spawnUri( Isolate isolate = await Isolate.spawnUri(
uriToSpawn, arguments, receivePort.sendPort, uriToSpawn, arguments, receivePort.sendPort,
packageConfig: packageConfig, packageConfig: packageConfig,
debugName: 'macro-executor ($uriToSpawn)'); debugName: 'macro-executor ($uriToSpawn)');
Completer<SendPort> sendPortCompleter = new Completer(); Completer<SendPort> sendPortCompleter = Completer();
StreamController<Object> messageStreamController = StreamController<Object> messageStreamController =
new StreamController(sync: true); StreamController(sync: true);
receivePort.listen((message) { receivePort.listen((message) {
if (!sendPortCompleter.isCompleted) { if (!sendPortCompleter.isCompleted) {
sendPortCompleter.complete(message as SendPort); sendPortCompleter.complete(message as SendPort);
@ -61,11 +61,11 @@ class _SingleIsolatedMacroExecutor extends ExternalMacroExecutorBase {
message = message =
(message as TransferableTypedData).materialize().asUint8List(); (message as TransferableTypedData).materialize().asUint8List();
} }
messageStreamController.add(message); messageStreamController.add(message as Object);
} }
}).onDone(messageStreamController.close); }).onDone(messageStreamController.close);
return new _SingleIsolatedMacroExecutor( return _SingleIsolatedMacroExecutor(
onClose: () { onClose: () {
receivePort.close(); receivePort.close();
isolate.kill(); isolate.kill();
@ -77,9 +77,9 @@ class _SingleIsolatedMacroExecutor extends ExternalMacroExecutorBase {
@override @override
Future<void> close() { Future<void> close() {
if (isClosed) return new Future.value(); if (isClosed) return Future.value();
isClosed = true; isClosed = true;
return new Future.sync(onClose); return Future.sync(onClose);
} }
/// Sends the [Serializer.result] to [sendPort], possibly wrapping it in a /// Sends the [Serializer.result] to [sendPort], possibly wrapping it in a
@ -88,7 +88,7 @@ class _SingleIsolatedMacroExecutor extends ExternalMacroExecutorBase {
void sendResult(Serializer serializer) { void sendResult(Serializer serializer) {
if (serializationMode == SerializationMode.byteData) { if (serializationMode == SerializationMode.byteData) {
sendPort.send( sendPort.send(
new TransferableTypedData.fromList([serializer.result as Uint8List])); TransferableTypedData.fromList([serializer.result as Uint8List]));
} else { } else {
sendPort.send(serializer.result); sendPort.send(serializer.result);
} }

View File

@ -4,8 +4,9 @@
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import '../../util/runtimes.dart' as runtimes;
import '../executor.dart'; import '../executor.dart';
import '../executor/serialization.dart'; import '../executor/serialization.dart';
import 'isolated_executor.dart' as isolated_executor; import 'isolated_executor.dart' as isolated_executor;
@ -20,21 +21,21 @@ import 'process_executor.dart' as process_executor;
/// This is the only public api exposed by this library. /// This is the only public api exposed by this library.
Future<MacroExecutor> start(SerializationMode serializationMode, Uri uriToSpawn, Future<MacroExecutor> start(SerializationMode serializationMode, Uri uriToSpawn,
{List<String> arguments = const [], Uri? packageConfigUri}) { {List<String> arguments = const [], Uri? packageConfigUri}) {
if (runtimes.isKernelRuntime) { if (_isKernelRuntime) {
return isolated_executor.start(serializationMode, uriToSpawn, return isolated_executor.start(serializationMode, uriToSpawn,
arguments: arguments, packageConfigUri: packageConfigUri); arguments: arguments, packageConfigUri: packageConfigUri);
} }
// Not running on the JIT, assume `dartaotruntime` or some other executable // Not running on the JIT, assume `dartaotruntime` or some other executable
// in the SDK `bin` folder. // in the SDK `bin` folder.
File dartAotRuntime = new File(Platform.resolvedExecutable); File dartAotRuntime = File(Platform.resolvedExecutable);
List<File> dartExecutables = ['dart', 'dart.exe'] List<File> dartExecutables = ['dart', 'dart.exe']
.map((name) => new File.fromUri(dartAotRuntime.parent.uri.resolve(name))) .map((name) => File.fromUri(dartAotRuntime.parent.uri.resolve(name)))
.where((f) => f.existsSync()) .where((f) => f.existsSync())
.toList(); .toList();
if (dartExecutables.isEmpty) { if (dartExecutables.isEmpty) {
throw new StateError('Failed to start macro executor from kernel: ' throw StateError('Failed to start macro executor from kernel: '
"can't launch isolate and can't find dart executable next to " "can't launch isolate and can't find dart executable next to "
'${dartAotRuntime.path}.'); '${dartAotRuntime.path}.');
} }
@ -45,3 +46,22 @@ Future<MacroExecutor> start(SerializationMode serializationMode, Uri uriToSpawn,
dartExecutables.first.path, dartExecutables.first.path,
['run', uriToSpawn.path, ...arguments]); ['run', uriToSpawn.path, ...arguments]);
} }
/// Note that this is lazy, by nature of being a final top level variable.
final bool _isKernelRuntime = _checkForKernelRuntime();
bool _checkForKernelRuntime() {
// `createUriForKernelBlob` throws `UnsupportedError` if kernel blobs are not
// supported at all. We don't actually want to register kernel so pass
// invalid kernel, an empty list, resulting in an `ArgumentError` if kernel
// blobs are supported.
try {
(Isolate.current as dynamic)
.createUriForKernelBlob(Uint8List.fromList(const []));
throw StateError('Expected failure.');
} on UnsupportedError {
return false;
} on ArgumentError {
return true;
}
}

View File

@ -0,0 +1,107 @@
// Copyright (c) 2022, 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:math' as math;
import 'dart:typed_data';
/// Collects messages from an input stream of bytes.
///
/// Each message should start with a 32 bit big endian uint indicating its size,
/// followed by that many bytes.
class MessageGrouper {
/// The input bytes stream subscription.
late final StreamSubscription _inputStreamSubscription;
/// The buffer to store the length bytes in.
final _FixedBuffer _lengthBuffer = _FixedBuffer(4);
/// If reading raw data, buffer for the data.
_FixedBuffer? _messageBuffer;
late final StreamController<Uint8List> _messageStreamController =
StreamController<Uint8List>(onCancel: () {
_inputStreamSubscription.cancel();
});
Stream<Uint8List> get messageStream => _messageStreamController.stream;
MessageGrouper(Stream<List<int>> inputStream) {
_inputStreamSubscription = inputStream.listen(_handleBytes, onDone: cancel);
}
/// Stop listening to the input stream for further updates, and close the
/// output stream.
void cancel() {
_inputStreamSubscription.cancel();
_messageStreamController.close();
}
void _handleBytes(List<int> bytes, [int offset = 0]) {
final _FixedBuffer? messageBuffer = _messageBuffer;
if (messageBuffer == null) {
while (offset < bytes.length && !_lengthBuffer.isReady) {
_lengthBuffer.addByte(bytes[offset++]);
}
if (_lengthBuffer.isReady) {
int length = _lengthBuffer[0] << 24 |
_lengthBuffer[1] << 16 |
_lengthBuffer[2] << 8 |
_lengthBuffer[3];
// Reset the length reading state.
_lengthBuffer.reset();
// Switch to the message payload reading state.
_messageBuffer = _FixedBuffer(length);
_handleBytes(bytes, offset);
} else {
// Continue reading the length.
return;
}
} else {
// Read the data from `bytes`.
offset += messageBuffer.addBytes(bytes, offset);
// If we completed a message, add it to the output stream.
if (messageBuffer.isReady) {
_messageStreamController.add(messageBuffer.bytes);
// Switch to the length reading state.
_messageBuffer = null;
_handleBytes(bytes, offset);
}
}
}
}
/// A buffer of fixed length.
class _FixedBuffer {
final Uint8List bytes;
/// The offset in [bytes].
int _offset = 0;
_FixedBuffer(int length) : bytes = Uint8List(length);
/// Return `true` when the required number of bytes added.
bool get isReady => _offset == bytes.length;
int operator [](int index) => bytes[index];
void addByte(int byte) {
bytes[_offset++] = byte;
}
/// Consume at most as many bytes from [source] as required by fill [bytes].
/// Return the number of consumed bytes.
int addBytes(List<int> source, int offset) {
int toConsume = math.min(source.length - offset, bytes.length - _offset);
bytes.setRange(_offset, _offset + toConsume, source, offset);
_offset += toConsume;
return toConsume;
}
/// Reset the number of added bytes to zero.
void reset() {
_offset = 0;
}
}

View File

@ -15,7 +15,7 @@ class MultiMacroExecutor extends MacroExecutor with AugmentationLibraryBuilder {
/// ///
/// Using an expando means we don't have to worry about cleaning up instances /// Using an expando means we don't have to worry about cleaning up instances
/// for executors that were shut down. /// for executors that were shut down.
final Expando<ExecutorFactoryToken> _instanceExecutors = new Expando(); final Expando<ExecutorFactoryToken> _instanceExecutors = Expando();
/// Registered factories for starting up a new macro executor for a library. /// Registered factories for starting up a new macro executor for a library.
final Map<Uri, ExecutorFactoryToken> _libraryExecutorFactories = {}; final Map<Uri, ExecutorFactoryToken> _libraryExecutorFactories = {};
@ -37,11 +37,11 @@ class MultiMacroExecutor extends MacroExecutor with AugmentationLibraryBuilder {
/// this way via [unregisterExecutorFactory]. /// this way via [unregisterExecutorFactory].
ExecutorFactoryToken registerExecutorFactory( ExecutorFactoryToken registerExecutorFactory(
FutureOr<MacroExecutor> Function() factory, Set<Uri> libraries) { FutureOr<MacroExecutor> Function() factory, Set<Uri> libraries) {
ExecutorFactoryToken token = new ExecutorFactoryToken._(factory, libraries); ExecutorFactoryToken token = ExecutorFactoryToken._(factory, libraries);
_executorFactoryTokens.add(token); _executorFactoryTokens.add(token);
for (Uri library in libraries) { for (Uri library in libraries) {
if (_libraryExecutorFactories.containsKey(library)) { if (_libraryExecutorFactories.containsKey(library)) {
throw new ArgumentError( throw ArgumentError(
'Attempted to register a macro executor factory for library ' 'Attempted to register a macro executor factory for library '
'$library which already has one assigned.'); '$library which already has one assigned.');
} }
@ -127,8 +127,7 @@ class MultiMacroExecutor extends MacroExecutor with AugmentationLibraryBuilder {
Uri library, String name, String constructor, Arguments arguments) { Uri library, String name, String constructor, Arguments arguments) {
ExecutorFactoryToken? token = _libraryExecutorFactories[library]; ExecutorFactoryToken? token = _libraryExecutorFactories[library];
if (token == null) { if (token == null) {
throw new ArgumentError( throw ArgumentError('No executor registered to run macros from $library');
'No executor registered to run macros from $library');
} }
return token._withInstance((executor) async { return token._withInstance((executor) async {
MacroInstanceIdentifier instance = await executor.instantiateMacro( MacroInstanceIdentifier instance = await executor.instantiateMacro(

View File

@ -71,12 +71,12 @@ class _SingleProcessMacroExecutor extends ExternalMacroExecutorBase {
rethrow; rethrow;
} }
process.stderr.transform(const Utf8Decoder()).listen((content) => process.stderr.transform(const Utf8Decoder()).listen((content) =>
throw new UnexpectedMacroExceptionImpl( throw UnexpectedMacroExceptionImpl(
'stderr output by macro process: $content')); 'stderr output by macro process: $content'));
process.stdout.transform(const Utf8Decoder()).listen( process.stdout.transform(const Utf8Decoder()).listen(
(event) => print('Stdout from MacroExecutor at $programPath:\n$event')); (event) => print('Stdout from MacroExecutor at $programPath:\n$event'));
Completer<Socket> clientCompleter = new Completer(); Completer<Socket> clientCompleter = Completer();
serverSocket.listen((client) { serverSocket.listen((client) {
clientCompleter.complete(client); clientCompleter.complete(client);
}); });
@ -87,19 +87,19 @@ class _SingleProcessMacroExecutor extends ExternalMacroExecutorBase {
Stream<Object> messageStream; Stream<Object> messageStream;
if (serializationMode == SerializationMode.byteData) { if (serializationMode == SerializationMode.byteData) {
messageStream = new MessageGrouper(client).messageStream; messageStream = MessageGrouper(client).messageStream;
} else if (serializationMode == SerializationMode.json) { } else if (serializationMode == SerializationMode.json) {
messageStream = const Utf8Decoder() messageStream = const Utf8Decoder()
.bind(client) .bind(client)
.transform(const LineSplitter()) .transform(const LineSplitter())
.map((line) => jsonDecode(line)!); .map((line) => jsonDecode(line) as Object);
} else { } else {
throw new UnsupportedError( throw UnsupportedError(
'Unsupported serialization mode \$serializationMode for ' 'Unsupported serialization mode \$serializationMode for '
'ProcessExecutor'); 'ProcessExecutor');
} }
return new _SingleProcessMacroExecutor( return _SingleProcessMacroExecutor(
onClose: () { onClose: () {
try { try {
client.close(); client.close();
@ -121,25 +121,25 @@ class _SingleProcessMacroExecutor extends ExternalMacroExecutorBase {
List<String> arguments) async { List<String> arguments) async {
Process process = await Process.start(programPath, arguments); Process process = await Process.start(programPath, arguments);
process.stderr.transform(const Utf8Decoder()).listen((content) => process.stderr.transform(const Utf8Decoder()).listen((content) =>
throw new UnexpectedMacroExceptionImpl( throw UnexpectedMacroExceptionImpl(
'stderr output by macro process: $content')); 'stderr output by macro process: $content'));
Stream<Object> messageStream; Stream<Object> messageStream;
if (serializationMode == SerializationMode.byteData) { if (serializationMode == SerializationMode.byteData) {
messageStream = new MessageGrouper(process.stdout).messageStream; messageStream = MessageGrouper(process.stdout).messageStream;
} else if (serializationMode == SerializationMode.json) { } else if (serializationMode == SerializationMode.json) {
messageStream = process.stdout messageStream = process.stdout
.transform(const Utf8Decoder()) .transform(const Utf8Decoder())
.transform(const LineSplitter()) .transform(const LineSplitter())
.map((line) => jsonDecode(line)!); .map((line) => jsonDecode(line) as Object);
} else { } else {
throw new UnsupportedError( throw UnsupportedError(
'Unsupported serialization mode \$serializationMode for ' 'Unsupported serialization mode \$serializationMode for '
'ProcessExecutor'); 'ProcessExecutor');
} }
return new _SingleProcessMacroExecutor( return _SingleProcessMacroExecutor(
onClose: () { onClose: () {
process.kill(); process.kill();
}, },
@ -150,9 +150,9 @@ class _SingleProcessMacroExecutor extends ExternalMacroExecutorBase {
@override @override
Future<void> close() { Future<void> close() {
if (isClosed) return new Future.value(); if (isClosed) return Future.value();
isClosed = true; isClosed = true;
return new Future.sync(onClose); return Future.sync(onClose);
} }
/// Sends the [Serializer.result] to [stdin]. /// Sends the [Serializer.result] to [stdin].
@ -166,9 +166,9 @@ class _SingleProcessMacroExecutor extends ExternalMacroExecutorBase {
Uint8List result = (serializer as ByteDataSerializer).result; Uint8List result = (serializer as ByteDataSerializer).result;
int length = result.lengthInBytes; int length = result.lengthInBytes;
if (length > 0xffffffff) { if (length > 0xffffffff) {
throw new StateError('Message was larger than the allowed size!'); throw StateError('Message was larger than the allowed size!');
} }
BytesBuilder bytesBuilder = new BytesBuilder(copy: false); BytesBuilder bytesBuilder = BytesBuilder(copy: false);
bytesBuilder.add([ bytesBuilder.add([
length >> 24 & 0xff, length >> 24 & 0xff,
length >> 16 & 0xff, length >> 16 & 0xff,
@ -178,7 +178,7 @@ class _SingleProcessMacroExecutor extends ExternalMacroExecutorBase {
bytesBuilder.add(result); bytesBuilder.add(result);
outSink.add(bytesBuilder.takeBytes()); outSink.add(bytesBuilder.takeBytes());
} else { } else {
throw new UnsupportedError( throw UnsupportedError(
'Unsupported serialization mode $serializationMode for ' 'Unsupported serialization mode $serializationMode for '
'ProcessExecutor'); 'ProcessExecutor');
} }

View File

@ -6,14 +6,12 @@
/// the isolate or process doing the work of macro loading and execution. /// the isolate or process doing the work of macro loading and execution.
library _fe_analyzer_shared.src.macros.executor_shared.protocol; library _fe_analyzer_shared.src.macros.executor_shared.protocol;
import 'package:_fe_analyzer_shared/src/macros/executor/exception_impls.dart';
import 'package:meta/meta.dart';
import '../api.dart'; import '../api.dart';
import '../executor.dart'; import '../executor.dart';
import '../executor/response_impls.dart'; import 'exception_impls.dart';
import 'introspection_impls.dart'; import 'introspection_impls.dart';
import 'remote_instance.dart'; import 'remote_instance.dart';
import 'response_impls.dart';
import 'serialization.dart'; import 'serialization.dart';
import 'serialization_extensions.dart'; import 'serialization_extensions.dart';
@ -23,8 +21,7 @@ abstract class Request implements Serializable {
final int serializationZoneId; final int serializationZoneId;
Request({int? id, required this.serializationZoneId}) Request({int? id, required this.serializationZoneId}) : id = id ?? _next++;
: this.id = id ?? _next++;
/// The [serializationZoneId] is a part of the header and needs to be parsed /// The [serializationZoneId] is a part of the header and needs to be parsed
/// before deserializing objects, and then passed in here. /// before deserializing objects, and then passed in here.
@ -35,7 +32,6 @@ abstract class Request implements Serializable {
/// rest of the object. This is not done by the instances themselves but by /// rest of the object. This is not done by the instances themselves but by
/// the macro implementations. /// the macro implementations.
@override @override
@mustCallSuper
void serialize(Serializer serializer) => serializer.addInt(id); void serialize(Serializer serializer) => serializer.addInt(id);
static int _next = 0; static int _next = 0;
@ -93,20 +89,20 @@ class SerializableResponse implements Response, Serializable {
exception = deserializer.expectRemoteInstance(); exception = deserializer.expectRemoteInstance();
break; break;
case MessageType.macroInstanceIdentifier: case MessageType.macroInstanceIdentifier:
response = new MacroInstanceIdentifierImpl.deserialize(deserializer); response = MacroInstanceIdentifierImpl.deserialize(deserializer);
break; break;
case MessageType.macroExecutionResult: case MessageType.macroExecutionResult:
response = new MacroExecutionResultImpl.deserialize(deserializer); response = MacroExecutionResultImpl.deserialize(deserializer);
break; break;
case MessageType.staticType: case MessageType.staticType:
case MessageType.namedStaticType: case MessageType.namedStaticType:
response = RemoteInstance.deserialize(deserializer); response = RemoteInstance.deserialize(deserializer);
break; break;
case MessageType.boolean: case MessageType.boolean:
response = new BooleanValue.deserialize(deserializer); response = BooleanValue.deserialize(deserializer);
break; break;
case MessageType.declarationList: case MessageType.declarationList:
response = new DeclarationList.deserialize(deserializer); response = DeclarationList.deserialize(deserializer);
break; break;
case MessageType.remoteInstance: case MessageType.remoteInstance:
deserializer.moveNext(); deserializer.moveNext();
@ -115,10 +111,10 @@ class SerializableResponse implements Response, Serializable {
} }
break; break;
default: default:
throw new StateError('Unexpected response type $responseType'); throw StateError('Unexpected response type $responseType');
} }
return new SerializableResponse( return SerializableResponse(
responseType: responseType, responseType: responseType,
response: response, response: response,
exception: exception, exception: exception,
@ -225,7 +221,7 @@ class InstantiateMacroRequest extends Request {
: library = (deserializer..moveNext()).expectUri(), : library = (deserializer..moveNext()).expectUri(),
name = (deserializer..moveNext()).expectString(), name = (deserializer..moveNext()).expectString(),
constructor = (deserializer..moveNext()).expectString(), constructor = (deserializer..moveNext()).expectString(),
arguments = new Arguments.deserialize(deserializer), arguments = Arguments.deserialize(deserializer),
instanceId = (deserializer..moveNext()).expectInt(), instanceId = (deserializer..moveNext()).expectInt(),
super.deserialize(); super.deserialize();
@ -249,13 +245,14 @@ class DisposeMacroRequest extends Request {
DisposeMacroRequest(this.identifier, {required super.serializationZoneId}); DisposeMacroRequest(this.identifier, {required super.serializationZoneId});
DisposeMacroRequest.deserialize(super.deserializer, super.serializationZoneId) DisposeMacroRequest.deserialize(super.deserializer, super.serializationZoneId)
: identifier = new MacroInstanceIdentifierImpl.deserialize(deserializer), : identifier = MacroInstanceIdentifierImpl.deserialize(deserializer),
super.deserialize(); super.deserialize();
@override @override
void serialize(Serializer serializer) { void serialize(Serializer serializer) {
serializer.addInt(MessageType.disposeMacroRequest.index); serializer
serializer..addSerializable(identifier); ..addInt(MessageType.disposeMacroRequest.index)
..addSerializable(identifier);
super.serialize(serializer); super.serialize(serializer);
} }
} }
@ -274,7 +271,7 @@ abstract class ExecutePhaseRequest extends Request {
/// When deserializing we have already consumed the message type, so we don't /// When deserializing we have already consumed the message type, so we don't
/// consume it again. /// consume it again.
ExecutePhaseRequest.deserialize(super.deserializer, super.serializationZoneId) ExecutePhaseRequest.deserialize(super.deserializer, super.serializationZoneId)
: macro = new MacroInstanceIdentifierImpl.deserialize(deserializer), : macro = MacroInstanceIdentifierImpl.deserialize(deserializer),
target = RemoteInstance.deserialize(deserializer), target = RemoteInstance.deserialize(deserializer),
introspector = RemoteInstance.deserialize(deserializer), introspector = RemoteInstance.deserialize(deserializer),
super.deserialize(); super.deserialize();
@ -588,7 +585,7 @@ final class ClientTypePhaseIntrospector extends ClientIntrospector
@override @override
Future<Identifier> resolveIdentifier(Uri library, String name) async { Future<Identifier> resolveIdentifier(Uri library, String name) async {
ResolveIdentifierRequest request = new ResolveIdentifierRequest( ResolveIdentifierRequest request = ResolveIdentifierRequest(
library, name, remoteInstance, library, name, remoteInstance,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse(await _sendRequest(request)); return _handleResponse(await _sendRequest(request));
@ -604,19 +601,19 @@ final class ClientDeclarationPhaseIntrospector
@override @override
Future<StaticType> resolve(TypeAnnotationCode typeAnnotation) async { Future<StaticType> resolve(TypeAnnotationCode typeAnnotation) async {
ResolveTypeRequest request = new ResolveTypeRequest( ResolveTypeRequest request = ResolveTypeRequest(
typeAnnotation, remoteInstance, typeAnnotation, remoteInstance,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
RemoteInstanceImpl remoteType = RemoteInstanceImpl remoteType =
_handleResponse(await _sendRequest(request)); _handleResponse(await _sendRequest(request));
return switch (remoteType.kind) { return switch (remoteType.kind) {
RemoteInstanceKind.namedStaticType => new ClientNamedStaticTypeImpl( RemoteInstanceKind.namedStaticType => ClientNamedStaticTypeImpl(
_sendRequest, _sendRequest,
remoteInstance: remoteType, remoteInstance: remoteType,
serializationZoneId: serializationZoneId), serializationZoneId: serializationZoneId),
RemoteInstanceKind.staticType => new ClientStaticTypeImpl(_sendRequest, RemoteInstanceKind.staticType => ClientStaticTypeImpl(_sendRequest,
remoteInstance: remoteType, serializationZoneId: serializationZoneId), remoteInstance: remoteType, serializationZoneId: serializationZoneId),
_ => throw new StateError( _ => throw StateError(
'Expected either a StaticType or NamedStaticType but got ' 'Expected either a StaticType or NamedStaticType but got '
'${remoteType.kind}'), '${remoteType.kind}'),
}; };
@ -625,7 +622,7 @@ final class ClientDeclarationPhaseIntrospector
@override @override
Future<List<ConstructorDeclaration>> constructorsOf( Future<List<ConstructorDeclaration>> constructorsOf(
TypeDeclaration type) async { TypeDeclaration type) async {
TypeIntrospectorRequest request = new TypeIntrospectorRequest( TypeIntrospectorRequest request = TypeIntrospectorRequest(
type, remoteInstance, MessageType.constructorsOfRequest, type, remoteInstance, MessageType.constructorsOfRequest,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<DeclarationList>(await _sendRequest(request)) return _handleResponse<DeclarationList>(await _sendRequest(request))
@ -636,7 +633,7 @@ final class ClientDeclarationPhaseIntrospector
@override @override
Future<List<EnumValueDeclaration>> valuesOf(EnumDeclaration enumType) async { Future<List<EnumValueDeclaration>> valuesOf(EnumDeclaration enumType) async {
TypeIntrospectorRequest request = new TypeIntrospectorRequest( TypeIntrospectorRequest request = TypeIntrospectorRequest(
enumType, remoteInstance, MessageType.valuesOfRequest, enumType, remoteInstance, MessageType.valuesOfRequest,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<DeclarationList>(await _sendRequest(request)) return _handleResponse<DeclarationList>(await _sendRequest(request))
@ -647,7 +644,7 @@ final class ClientDeclarationPhaseIntrospector
@override @override
Future<List<FieldDeclaration>> fieldsOf(TypeDeclaration type) async { Future<List<FieldDeclaration>> fieldsOf(TypeDeclaration type) async {
TypeIntrospectorRequest request = new TypeIntrospectorRequest( TypeIntrospectorRequest request = TypeIntrospectorRequest(
type, remoteInstance, MessageType.fieldsOfRequest, type, remoteInstance, MessageType.fieldsOfRequest,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<DeclarationList>(await _sendRequest(request)) return _handleResponse<DeclarationList>(await _sendRequest(request))
@ -658,7 +655,7 @@ final class ClientDeclarationPhaseIntrospector
@override @override
Future<List<MethodDeclaration>> methodsOf(TypeDeclaration type) async { Future<List<MethodDeclaration>> methodsOf(TypeDeclaration type) async {
TypeIntrospectorRequest request = new TypeIntrospectorRequest( TypeIntrospectorRequest request = TypeIntrospectorRequest(
type, remoteInstance, MessageType.methodsOfRequest, type, remoteInstance, MessageType.methodsOfRequest,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<DeclarationList>(await _sendRequest(request)) return _handleResponse<DeclarationList>(await _sendRequest(request))
@ -669,7 +666,7 @@ final class ClientDeclarationPhaseIntrospector
@override @override
Future<List<TypeDeclaration>> typesOf(Library library) async { Future<List<TypeDeclaration>> typesOf(Library library) async {
TypeIntrospectorRequest request = new TypeIntrospectorRequest( TypeIntrospectorRequest request = TypeIntrospectorRequest(
library, remoteInstance, MessageType.typesOfRequest, library, remoteInstance, MessageType.typesOfRequest,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<DeclarationList>(await _sendRequest(request)) return _handleResponse<DeclarationList>(await _sendRequest(request))
@ -680,7 +677,7 @@ final class ClientDeclarationPhaseIntrospector
@override @override
Future<TypeDeclaration> typeDeclarationOf(IdentifierImpl identifier) async { Future<TypeDeclaration> typeDeclarationOf(IdentifierImpl identifier) async {
DeclarationOfRequest request = new DeclarationOfRequest( DeclarationOfRequest request = DeclarationOfRequest(
identifier, MessageType.typeDeclarationOfRequest, remoteInstance, identifier, MessageType.typeDeclarationOfRequest, remoteInstance,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<TypeDeclaration>(await _sendRequest(request)); return _handleResponse<TypeDeclaration>(await _sendRequest(request));
@ -695,15 +692,15 @@ base class ClientStaticTypeImpl extends ClientIntrospector
@override @override
Future<bool> isExactly(ClientStaticTypeImpl other) async { Future<bool> isExactly(ClientStaticTypeImpl other) async {
IsExactlyTypeRequest request = new IsExactlyTypeRequest( IsExactlyTypeRequest request = IsExactlyTypeRequest(
this.remoteInstance, other.remoteInstance, remoteInstance, other.remoteInstance,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<BooleanValue>(await _sendRequest(request)).value; return _handleResponse<BooleanValue>(await _sendRequest(request)).value;
} }
@override @override
Future<bool> isSubtypeOf(ClientStaticTypeImpl other) async { Future<bool> isSubtypeOf(ClientStaticTypeImpl other) async {
IsSubtypeOfRequest request = new IsSubtypeOfRequest( IsSubtypeOfRequest request = IsSubtypeOfRequest(
remoteInstance, other.remoteInstance, remoteInstance, other.remoteInstance,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<BooleanValue>(await _sendRequest(request)).value; return _handleResponse<BooleanValue>(await _sendRequest(request)).value;
@ -726,7 +723,7 @@ final class ClientDefinitionPhaseIntrospector
@override @override
Future<Declaration> declarationOf(IdentifierImpl identifier) async { Future<Declaration> declarationOf(IdentifierImpl identifier) async {
DeclarationOfRequest request = new DeclarationOfRequest( DeclarationOfRequest request = DeclarationOfRequest(
identifier, MessageType.declarationOfRequest, remoteInstance, identifier, MessageType.declarationOfRequest, remoteInstance,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<Declaration>(await _sendRequest(request)); return _handleResponse<Declaration>(await _sendRequest(request));
@ -735,14 +732,14 @@ final class ClientDefinitionPhaseIntrospector
@override @override
Future<TypeAnnotation> inferType( Future<TypeAnnotation> inferType(
OmittedTypeAnnotationImpl omittedType) async { OmittedTypeAnnotationImpl omittedType) async {
InferTypeRequest request = new InferTypeRequest(omittedType, remoteInstance, InferTypeRequest request = InferTypeRequest(omittedType, remoteInstance,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<TypeAnnotation>(await _sendRequest(request)); return _handleResponse<TypeAnnotation>(await _sendRequest(request));
} }
@override @override
Future<List<Declaration>> topLevelDeclarationsOf(LibraryImpl library) async { Future<List<Declaration>> topLevelDeclarationsOf(LibraryImpl library) async {
DeclarationsOfRequest request = new DeclarationsOfRequest( DeclarationsOfRequest request = DeclarationsOfRequest(
library, remoteInstance, library, remoteInstance,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<DeclarationList>(await _sendRequest(request)) return _handleResponse<DeclarationList>(await _sendRequest(request))
@ -751,7 +748,7 @@ final class ClientDefinitionPhaseIntrospector
@override @override
Future<TypeDeclaration> typeDeclarationOf(IdentifierImpl identifier) async { Future<TypeDeclaration> typeDeclarationOf(IdentifierImpl identifier) async {
DeclarationOfRequest request = new DeclarationOfRequest( DeclarationOfRequest request = DeclarationOfRequest(
identifier, MessageType.typeDeclarationOfRequest, remoteInstance, identifier, MessageType.typeDeclarationOfRequest, remoteInstance,
serializationZoneId: serializationZoneId); serializationZoneId: serializationZoneId);
return _handleResponse<TypeDeclaration>(await _sendRequest(request)); return _handleResponse<TypeDeclaration>(await _sendRequest(request));

View File

@ -4,8 +4,6 @@
import 'dart:async'; import 'dart:async';
import 'package:meta/meta.dart';
import 'serialization.dart'; import 'serialization.dart';
import 'serialization_extensions.dart'; import 'serialization_extensions.dart';
@ -48,7 +46,6 @@ abstract class RemoteInstance implements Serializable {
/// This method should be overridden by any subclasses, they should instead /// This method should be overridden by any subclasses, they should instead
/// implement [serializeUncached]. /// implement [serializeUncached].
@override @override
@nonVirtual
void serialize(Serializer serializer) { void serialize(Serializer serializer) {
serializer.addInt(id); serializer.addInt(id);
// We only send the ID if it's in the cache, it's only in our cache if it is // We only send the ID if it's in the cache, it's only in our cache if it is
@ -66,7 +63,6 @@ abstract class RemoteInstance implements Serializable {
/// ///
/// Only new fields added by the subtype should be serialized here, rely on /// Only new fields added by the subtype should be serialized here, rely on
/// super classes to have their own implementations for their fields. /// super classes to have their own implementations for their fields.
@mustCallSuper
void serializeUncached(Serializer serializer) { void serializeUncached(Serializer serializer) {
serializer.addInt(kind.index); serializer.addInt(kind.index);
@ -77,6 +73,9 @@ abstract class RemoteInstance implements Serializable {
@override @override
bool operator ==(Object other) => other is RemoteInstance && id == other.id; bool operator ==(Object other) => other is RemoteInstance && id == other.id;
@override
int get hashCode => id;
} }
/// A remote instance which is just a pointer to some server side instance of /// A remote instance which is just a pointer to some server side instance of
@ -164,7 +163,7 @@ T withRemoteInstanceZone<T>(int zoneId, T Function() fn,
Zone? zone = _remoteInstanceCacheZones[zoneId]; Zone? zone = _remoteInstanceCacheZones[zoneId];
if (zone == null) { if (zone == null) {
if (!createIfMissing) { if (!createIfMissing) {
throw new StateError('No remote instance zone with id `$zoneId` exists.'); throw StateError('No remote instance zone with id `$zoneId` exists.');
} }
zone = _remoteInstanceCacheZones[zoneId] = Zone.current.fork(zoneValues: { zone = _remoteInstanceCacheZones[zoneId] = Zone.current.fork(zoneValues: {
_remoteInstanceZoneCacheKey: <int, RemoteInstance>{}, _remoteInstanceZoneCacheKey: <int, RemoteInstance>{},
@ -180,7 +179,7 @@ T withRemoteInstanceZone<T>(int zoneId, T Function() fn,
void destroyRemoteInstanceZone(int zoneId) { void destroyRemoteInstanceZone(int zoneId) {
final Zone? zone = _remoteInstanceCacheZones.remove(zoneId); final Zone? zone = _remoteInstanceCacheZones.remove(zoneId);
if (zone == null) { if (zone == null) {
throw new StateError('No remote instance zone with id `$zoneId` exists.'); throw StateError('No remote instance zone with id `$zoneId` exists.');
} }
(zone[_remoteInstanceZoneCacheKey] as Map<int, RemoteInstance>).clear(); (zone[_remoteInstanceZoneCacheKey] as Map<int, RemoteInstance>).clear();
} }
@ -194,8 +193,8 @@ const Symbol _remoteInstanceZoneCacheKey = #_remoteInstanceCache;
/// These are a part of the current remote instance cache zone, which all /// These are a part of the current remote instance cache zone, which all
/// serialization and deserialization of remote instances must be done in. /// serialization and deserialization of remote instances must be done in.
Map<int, RemoteInstance> get _remoteInstanceCache => Map<int, RemoteInstance> get _remoteInstanceCache =>
Zone.current[_remoteInstanceZoneCacheKey] ?? Zone.current[_remoteInstanceZoneCacheKey] as Map<int, RemoteInstance>? ??
(throw new StateError('Not running in a remote instance cache zone, call ' (throw StateError('Not running in a remote instance cache zone, call '
'`withRemoteInstanceZone` to set one up.')); '`withRemoteInstanceZone` to set one up.'));
/// Remote instance cache zones by ID. /// Remote instance cache zones by ID.

View File

@ -226,7 +226,7 @@ class MacroInstanceIdentifierImpl implements MacroInstanceIdentifier {
} }
} }
return new MacroInstanceIdentifierImpl._(instanceId, interfaces); return MacroInstanceIdentifierImpl._(instanceId, interfaces);
} }
MacroInstanceIdentifierImpl.deserialize(Deserializer deserializer) MacroInstanceIdentifierImpl.deserialize(Deserializer deserializer)
@ -400,7 +400,7 @@ class MacroExecutionResultImpl implements MacroExecutionResult {
] ]
}; };
return new MacroExecutionResultImpl( return MacroExecutionResultImpl(
diagnostics: diagnostics, diagnostics: diagnostics,
exception: exception, exception: exception,
enumValueAugmentations: enumValueAugmentations, enumValueAugmentations: enumValueAugmentations,

View File

@ -134,7 +134,7 @@ class JsonSerializer implements Serializer {
final _result = <Object?>[]; final _result = <Object?>[];
/// A path to the current list we are modifying. /// A path to the current list we are modifying.
late List<List<Object?>> _path = [_result]; late final List<List<Object?>> _path = [_result];
/// Returns the result as an unmodifiable [Iterable]. /// Returns the result as an unmodifiable [Iterable].
/// ///
@ -186,7 +186,7 @@ class JsonDeserializer implements Deserializer {
final Iterable<Object?> _source; final Iterable<Object?> _source;
/// The path to the current iterator we are reading from. /// The path to the current iterator we are reading from.
late List<Iterator<Object?>> _path = []; late final List<Iterator<Object?>> _path = [];
/// Whether we have received our first [moveNext] call. /// Whether we have received our first [moveNext] call.
bool _initialized = false; bool _initialized = false;
@ -223,12 +223,11 @@ class JsonDeserializer implements Deserializer {
/// Reads the current value and casts it to [T]. /// Reads the current value and casts it to [T].
T _expectValue<T>() { T _expectValue<T>() {
if (!_initialized) { if (!_initialized) {
throw new StateError( throw StateError('You must call `moveNext()` before reading any values.');
'You must call `moveNext()` before reading any values.');
} }
Object? current = _path.last.current; Object? current = _path.last.current;
if (current is! T) { if (current is! T) {
throw new StateError('Expected $T, got: ${_path.last.current}'); throw StateError('Expected $T, got: ${_path.last.current}');
} }
return current; return current;
} }
@ -252,12 +251,11 @@ class JsonDeserializer implements Deserializer {
} }
class ByteDataSerializer extends Serializer { class ByteDataSerializer extends Serializer {
final BytesBuilder _builder = new BytesBuilder(); final BytesBuilder _builder = BytesBuilder();
// Re-usable 8 byte list and view for encoding doubles. // Re-usable 8 byte list and view for encoding doubles.
final Uint8List _eightByteList = new Uint8List(8); final Uint8List _eightByteList = Uint8List(8);
late final ByteData _eightByteListData = late final ByteData _eightByteListData = ByteData.sublistView(_eightByteList);
new ByteData.sublistView(_eightByteList);
@override @override
void addBool(bool value) => _builder void addBool(bool value) => _builder
@ -279,7 +277,7 @@ class ByteDataSerializer extends Serializer {
if (value >= 0x0) { if (value >= 0x0) {
assert(DataKind.values.length < 0xff); assert(DataKind.values.length < 0xff);
if (value <= 0xff - DataKind.values.length) { if (value <= 0xff - DataKind.values.length) {
_builder..addByte(value + DataKind.values.length); _builder.addByte(value + DataKind.values.length);
} else if (value <= 0xff) { } else if (value <= 0xff) {
_builder _builder
..addByte(DataKind.uint8.index) ..addByte(DataKind.uint8.index)
@ -423,7 +421,7 @@ class ByteDataSerializer extends Serializer {
} }
endMap(); endMap();
} else { } else {
throw new ArgumentError('(${value.runtimeType}) $value'); throw ArgumentError('(${value.runtimeType}) $value');
} }
} }
@ -463,7 +461,7 @@ class ByteDataDeserializer extends Deserializer {
} else if (kind == DataKind.boolFalse) { } else if (kind == DataKind.boolFalse) {
return false; return false;
} else { } else {
throw new StateError('Expected a bool but found a $kind'); throw StateError('Expected a bool but found a $kind');
} }
} }
@ -471,7 +469,7 @@ class ByteDataDeserializer extends Deserializer {
double expectDouble() { double expectDouble() {
DataKind kind = _readKind(); DataKind kind = _readKind();
if (kind != DataKind.float64) { if (kind != DataKind.float64) {
throw new StateError('Expected a double but found a $kind'); throw StateError('Expected a double but found a $kind');
} }
_byteOffsetIncrement = 9; _byteOffsetIncrement = 9;
return _bytes.getFloat64(_byteOffset + 1); return _bytes.getFloat64(_byteOffset + 1);
@ -522,7 +520,7 @@ class ByteDataDeserializer extends Deserializer {
_byteOffsetIncrement = 8 + offset; _byteOffsetIncrement = 8 + offset;
break; break;
default: default:
throw new StateError('Expected an int but found a $kind'); throw StateError('Expected an int but found a $kind');
} }
return result; return result;
} }
@ -531,7 +529,7 @@ class ByteDataDeserializer extends Deserializer {
void expectList() { void expectList() {
DataKind kind = _readKind(); DataKind kind = _readKind();
if (kind != DataKind.startList) { if (kind != DataKind.startList) {
throw new StateError('Expected the start to a list but found a $kind'); throw StateError('Expected the start to a list but found a $kind');
} }
_byteOffsetIncrement = 1; _byteOffsetIncrement = 1;
} }
@ -557,7 +555,7 @@ class ByteDataDeserializer extends Deserializer {
void expectMap() { void expectMap() {
DataKind kind = _readKind(); DataKind kind = _readKind();
if (kind != DataKind.startMap) { if (kind != DataKind.startMap) {
throw new StateError('Expected the start to a map but found a $kind'); throw StateError('Expected the start to a map but found a $kind');
} }
_byteOffsetIncrement = 1; _byteOffsetIncrement = 1;
} }
@ -569,16 +567,15 @@ class ByteDataDeserializer extends Deserializer {
int offset = _byteOffsetIncrement! + _byteOffset; int offset = _byteOffsetIncrement! + _byteOffset;
if (kind == DataKind.oneByteString) { if (kind == DataKind.oneByteString) {
_byteOffsetIncrement = _byteOffsetIncrement! + length; _byteOffsetIncrement = _byteOffsetIncrement! + length;
return new String.fromCharCodes( return String.fromCharCodes(_bytes.buffer.asUint8List(offset, length));
_bytes.buffer.asUint8List(offset, length));
} else if (kind == DataKind.twoByteString) { } else if (kind == DataKind.twoByteString) {
length = length * 2; length = length * 2;
_byteOffsetIncrement = _byteOffsetIncrement! + length; _byteOffsetIncrement = _byteOffsetIncrement! + length;
Uint8List bytes = Uint8List bytes =
new Uint8List.fromList(_bytes.buffer.asUint8List(offset, length)); Uint8List.fromList(_bytes.buffer.asUint8List(offset, length));
return new String.fromCharCodes(bytes.buffer.asUint16List()); return String.fromCharCodes(bytes.buffer.asUint16List());
} else { } else {
throw new StateError('Expected a string but found a $kind'); throw StateError('Expected a string but found a $kind');
} }
} }
@ -647,7 +644,7 @@ class ByteDataDeserializer extends Deserializer {
} else if (kind == DataKind.uint8List) { } else if (kind == DataKind.uint8List) {
return expectUint8List(); return expectUint8List();
} else { } else {
throw new StateError('Expected: $kind'); throw StateError('Expected: $kind');
} }
} }
@ -656,7 +653,7 @@ class ByteDataDeserializer extends Deserializer {
int? increment = _byteOffsetIncrement; int? increment = _byteOffsetIncrement;
_byteOffsetIncrement = null; _byteOffsetIncrement = null;
if (increment == null) { if (increment == null) {
throw new StateError("Can't move until consuming the current element"); throw StateError("Can't move until consuming the current element");
} }
_byteOffset += increment; _byteOffset += increment;
if (_byteOffset >= _bytes.lengthInBytes) { if (_byteOffset >= _bytes.lengthInBytes) {
@ -701,7 +698,7 @@ SerializationMode get serializationMode {
SerializationMode? mode = SerializationMode? mode =
Zone.current[#serializationMode] as SerializationMode?; Zone.current[#serializationMode] as SerializationMode?;
if (mode == null) { if (mode == null) {
throw new StateError('No SerializationMode set, you must do all ' throw StateError('No SerializationMode set, you must do all '
'serialization inside a call to `withSerializationMode`.'); 'serialization inside a call to `withSerializationMode`.');
} }
return mode; return mode;
@ -711,10 +708,9 @@ SerializationMode get serializationMode {
Deserializer Function(Object?) get deserializerFactory => Deserializer Function(Object?) get deserializerFactory =>
switch (serializationMode) { switch (serializationMode) {
SerializationMode.byteData => (Object? message) => SerializationMode.byteData => (Object? message) =>
new ByteDataDeserializer( ByteDataDeserializer(ByteData.sublistView(message as Uint8List)),
new ByteData.sublistView(message as Uint8List)),
SerializationMode.json => (Object? message) => SerializationMode.json => (Object? message) =>
new JsonDeserializer(message as Iterable<Object?>), JsonDeserializer(message as Iterable<Object?>),
}; };
/// Returns the current serializer factory for the zone. /// Returns the current serializer factory for the zone.
@ -732,7 +728,7 @@ enum SerializationMode {
factory SerializationMode.fromOption(String option) => switch (option) { factory SerializationMode.fromOption(String option) => switch (option) {
'json' => SerializationMode.json, 'json' => SerializationMode.json,
'bytedata' => SerializationMode.byteData, 'bytedata' => SerializationMode.byteData,
_ => throw new ArgumentError('Unrecognized macro serialization mode ' _ => throw ArgumentError('Unrecognized macro serialization mode '
'$option'), '$option'),
}; };
} }

View File

@ -27,7 +27,7 @@ extension DeserializerExtensions on Deserializer {
RemoteInstanceKind.namedStaticType || RemoteInstanceKind.namedStaticType ||
RemoteInstanceKind.staticType => RemoteInstanceKind.staticType =>
// These are simple wrappers, just pass in the kind // These are simple wrappers, just pass in the kind
new RemoteInstanceImpl(id: id, kind: kind), RemoteInstanceImpl(id: id, kind: kind),
RemoteInstanceKind.classDeclaration => RemoteInstanceKind.classDeclaration =>
(this..moveNext())._expectClassDeclaration(id), (this..moveNext())._expectClassDeclaration(id),
RemoteInstanceKind.constructorMetadataAnnotation => RemoteInstanceKind.constructorMetadataAnnotation =>
@ -117,7 +117,7 @@ extension DeserializerExtensions on Deserializer {
} }
NamedTypeAnnotationImpl _expectNamedTypeAnnotation(int id) => NamedTypeAnnotationImpl _expectNamedTypeAnnotation(int id) =>
new NamedTypeAnnotationImpl( NamedTypeAnnotationImpl(
id: id, id: id,
isNullable: expectBool(), isNullable: expectBool(),
identifier: RemoteInstance.deserialize(this), identifier: RemoteInstance.deserialize(this),
@ -126,13 +126,13 @@ extension DeserializerExtensions on Deserializer {
OmittedTypeAnnotationImpl _expectOmittedTypeAnnotation(int id) { OmittedTypeAnnotationImpl _expectOmittedTypeAnnotation(int id) {
expectBool(); // Always `false`. expectBool(); // Always `false`.
return new OmittedTypeAnnotationImpl( return OmittedTypeAnnotationImpl(
id: id, id: id,
); );
} }
FunctionTypeAnnotationImpl _expectFunctionTypeAnnotation(int id) => FunctionTypeAnnotationImpl _expectFunctionTypeAnnotation(int id) =>
new FunctionTypeAnnotationImpl( FunctionTypeAnnotationImpl(
id: id, id: id,
isNullable: expectBool(), isNullable: expectBool(),
returnType: RemoteInstance.deserialize(this), returnType: RemoteInstance.deserialize(this),
@ -142,43 +142,43 @@ extension DeserializerExtensions on Deserializer {
); );
FormalParameterImpl _expectFormalParameter(int id) => FormalParameterImpl _expectFormalParameter(int id) =>
new FormalParameterImpl.fromBitMask( FormalParameterImpl.fromBitMask(
id: id, id: id,
bitMask: new BitMask(expectInt()), bitMask: BitMask(expectInt()),
metadata: (this..moveNext())._expectRemoteInstanceList(), metadata: (this..moveNext())._expectRemoteInstanceList(),
name: (this..moveNext()).expectNullableString(), name: (this..moveNext()).expectNullableString(),
type: RemoteInstance.deserialize(this), type: RemoteInstance.deserialize(this),
); );
IdentifierImpl _expectIdentifier(int id) => new IdentifierImpl( IdentifierImpl _expectIdentifier(int id) => IdentifierImpl(
id: id, id: id,
name: expectString(), name: expectString(),
); );
FormalParameterDeclarationImpl _expectFormalParameterDeclaration(int id) => FormalParameterDeclarationImpl _expectFormalParameterDeclaration(int id) =>
new FormalParameterDeclarationImpl.fromBitMask( FormalParameterDeclarationImpl.fromBitMask(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
metadata: (this..moveNext())._expectRemoteInstanceList(), metadata: (this..moveNext())._expectRemoteInstanceList(),
bitMask: new BitMask((this..moveNext()).expectInt()), bitMask: BitMask((this..moveNext()).expectInt()),
type: RemoteInstance.deserialize(this), type: RemoteInstance.deserialize(this),
); );
RecordFieldImpl _expectRecordField(int id) => new RecordFieldImpl( RecordFieldImpl _expectRecordField(int id) => RecordFieldImpl(
id: id, id: id,
name: expectNullableString(), name: expectNullableString(),
type: (this..moveNext()).expectRemoteInstance()); type: (this..moveNext()).expectRemoteInstance());
RecordTypeAnnotationImpl _expectRecordTypeAnnotation(int id) => RecordTypeAnnotationImpl _expectRecordTypeAnnotation(int id) =>
new RecordTypeAnnotationImpl( RecordTypeAnnotationImpl(
id: id, id: id,
isNullable: expectBool(), isNullable: expectBool(),
namedFields: (this..moveNext())._expectRemoteInstanceList(), namedFields: (this..moveNext())._expectRemoteInstanceList(),
positionalFields: (this..moveNext())._expectRemoteInstanceList(), positionalFields: (this..moveNext())._expectRemoteInstanceList(),
); );
TypeParameterImpl _expectTypeParameter(int id) => new TypeParameterImpl( TypeParameterImpl _expectTypeParameter(int id) => TypeParameterImpl(
id: id, id: id,
bound: checkNull() ? null : expectRemoteInstance(), bound: checkNull() ? null : expectRemoteInstance(),
metadata: (this..moveNext())._expectRemoteInstanceList(), metadata: (this..moveNext())._expectRemoteInstanceList(),
@ -186,7 +186,7 @@ extension DeserializerExtensions on Deserializer {
); );
TypeParameterDeclarationImpl _expectTypeParameterDeclaration(int id) => TypeParameterDeclarationImpl _expectTypeParameterDeclaration(int id) =>
new TypeParameterDeclarationImpl( TypeParameterDeclarationImpl(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
@ -195,12 +195,12 @@ extension DeserializerExtensions on Deserializer {
); );
FunctionDeclarationImpl _expectFunctionDeclaration(int id) => FunctionDeclarationImpl _expectFunctionDeclaration(int id) =>
new FunctionDeclarationImpl.fromBitMask( FunctionDeclarationImpl.fromBitMask(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
metadata: (this..moveNext())._expectRemoteInstanceList(), metadata: (this..moveNext())._expectRemoteInstanceList(),
bitMask: new BitMask((this..moveNext()).expectInt()), bitMask: BitMask((this..moveNext()).expectInt()),
namedParameters: (this..moveNext())._expectRemoteInstanceList(), namedParameters: (this..moveNext())._expectRemoteInstanceList(),
positionalParameters: (this..moveNext())._expectRemoteInstanceList(), positionalParameters: (this..moveNext())._expectRemoteInstanceList(),
returnType: RemoteInstance.deserialize(this), returnType: RemoteInstance.deserialize(this),
@ -208,12 +208,12 @@ extension DeserializerExtensions on Deserializer {
); );
MethodDeclarationImpl _expectMethodDeclaration(int id) => MethodDeclarationImpl _expectMethodDeclaration(int id) =>
new MethodDeclarationImpl.fromBitMask( MethodDeclarationImpl.fromBitMask(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
metadata: (this..moveNext())._expectRemoteInstanceList(), metadata: (this..moveNext())._expectRemoteInstanceList(),
bitMask: new BitMask((this..moveNext()).expectInt()), bitMask: BitMask((this..moveNext()).expectInt()),
namedParameters: (this..moveNext())._expectRemoteInstanceList(), namedParameters: (this..moveNext())._expectRemoteInstanceList(),
positionalParameters: (this..moveNext())._expectRemoteInstanceList(), positionalParameters: (this..moveNext())._expectRemoteInstanceList(),
returnType: RemoteInstance.deserialize(this), returnType: RemoteInstance.deserialize(this),
@ -222,12 +222,12 @@ extension DeserializerExtensions on Deserializer {
); );
ConstructorDeclarationImpl _expectConstructorDeclaration(int id) => ConstructorDeclarationImpl _expectConstructorDeclaration(int id) =>
new ConstructorDeclarationImpl.fromBitMask( ConstructorDeclarationImpl.fromBitMask(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
metadata: (this..moveNext())._expectRemoteInstanceList(), metadata: (this..moveNext())._expectRemoteInstanceList(),
bitMask: new BitMask((this..moveNext()).expectInt()), bitMask: BitMask((this..moveNext()).expectInt()),
namedParameters: (this..moveNext())._expectRemoteInstanceList(), namedParameters: (this..moveNext())._expectRemoteInstanceList(),
positionalParameters: (this..moveNext())._expectRemoteInstanceList(), positionalParameters: (this..moveNext())._expectRemoteInstanceList(),
returnType: RemoteInstance.deserialize(this), returnType: RemoteInstance.deserialize(this),
@ -236,36 +236,36 @@ extension DeserializerExtensions on Deserializer {
); );
VariableDeclarationImpl _expectVariableDeclaration(int id) => VariableDeclarationImpl _expectVariableDeclaration(int id) =>
new VariableDeclarationImpl.fromBitMask( VariableDeclarationImpl.fromBitMask(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
metadata: (this..moveNext())._expectRemoteInstanceList(), metadata: (this..moveNext())._expectRemoteInstanceList(),
bitMask: new BitMask((this..moveNext()).expectInt()), bitMask: BitMask((this..moveNext()).expectInt()),
type: RemoteInstance.deserialize(this), type: RemoteInstance.deserialize(this),
); );
FieldDeclarationImpl _expectFieldDeclaration(int id) => FieldDeclarationImpl _expectFieldDeclaration(int id) =>
new FieldDeclarationImpl.fromBitMask( FieldDeclarationImpl.fromBitMask(
id: id, id: id,
// Declaration fields. // Declaration fields.
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
metadata: (this..moveNext())._expectRemoteInstanceList(), metadata: (this..moveNext())._expectRemoteInstanceList(),
bitMask: new BitMask((this..moveNext()).expectInt()), bitMask: BitMask((this..moveNext()).expectInt()),
type: RemoteInstance.deserialize(this), type: RemoteInstance.deserialize(this),
// FieldDeclaration fields // FieldDeclaration fields
definingType: RemoteInstance.deserialize(this), definingType: RemoteInstance.deserialize(this),
); );
ClassDeclarationImpl _expectClassDeclaration(int id) => ClassDeclarationImpl _expectClassDeclaration(int id) =>
new ClassDeclarationImpl.fromBitMask( ClassDeclarationImpl.fromBitMask(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
metadata: (this..moveNext())._expectRemoteInstanceList(), metadata: (this..moveNext())._expectRemoteInstanceList(),
typeParameters: (this..moveNext())._expectRemoteInstanceList(), typeParameters: (this..moveNext())._expectRemoteInstanceList(),
bitMask: new BitMask((this..moveNext()).expectInt()), bitMask: BitMask((this..moveNext()).expectInt()),
interfaces: (this..moveNext())._expectRemoteInstanceList(), interfaces: (this..moveNext())._expectRemoteInstanceList(),
mixins: (this..moveNext())._expectRemoteInstanceList(), mixins: (this..moveNext())._expectRemoteInstanceList(),
superclass: superclass:
@ -274,7 +274,7 @@ extension DeserializerExtensions on Deserializer {
ConstructorMetadataAnnotationImpl _expectConstructorMetadataAnnotation( ConstructorMetadataAnnotationImpl _expectConstructorMetadataAnnotation(
int id) => int id) =>
new ConstructorMetadataAnnotationImpl( ConstructorMetadataAnnotationImpl(
id: id, id: id,
constructor: expectRemoteInstance(), constructor: expectRemoteInstance(),
type: RemoteInstance.deserialize(this), type: RemoteInstance.deserialize(this),
@ -283,12 +283,12 @@ extension DeserializerExtensions on Deserializer {
IdentifierMetadataAnnotationImpl _expectIdentifierMetadataAnnotation( IdentifierMetadataAnnotationImpl _expectIdentifierMetadataAnnotation(
int id) => int id) =>
new IdentifierMetadataAnnotationImpl( IdentifierMetadataAnnotationImpl(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
); );
EnumDeclarationImpl _expectEnumDeclaration(int id) => new EnumDeclarationImpl( EnumDeclarationImpl _expectEnumDeclaration(int id) => EnumDeclarationImpl(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
@ -298,8 +298,7 @@ extension DeserializerExtensions on Deserializer {
mixins: (this..moveNext())._expectRemoteInstanceList(), mixins: (this..moveNext())._expectRemoteInstanceList(),
); );
MixinDeclarationImpl _expectMixinDeclaration(int id) => MixinDeclarationImpl _expectMixinDeclaration(int id) => MixinDeclarationImpl(
new MixinDeclarationImpl(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
@ -311,7 +310,7 @@ extension DeserializerExtensions on Deserializer {
); );
EnumValueDeclarationImpl _expectEnumValueDeclaration(int id) => EnumValueDeclarationImpl _expectEnumValueDeclaration(int id) =>
new EnumValueDeclarationImpl( EnumValueDeclarationImpl(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
@ -320,7 +319,7 @@ extension DeserializerExtensions on Deserializer {
); );
MacroExceptionImpl _expectException(RemoteInstanceKind kind, int id) => MacroExceptionImpl _expectException(RemoteInstanceKind kind, int id) =>
new MacroExceptionImpl( MacroExceptionImpl(
id: id, id: id,
kind: kind, kind: kind,
message: expectString(), message: expectString(),
@ -328,7 +327,7 @@ extension DeserializerExtensions on Deserializer {
); );
ExtensionDeclarationImpl _expectExtensionDeclaration(int id) => ExtensionDeclarationImpl _expectExtensionDeclaration(int id) =>
new ExtensionDeclarationImpl( ExtensionDeclarationImpl(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
@ -338,7 +337,7 @@ extension DeserializerExtensions on Deserializer {
); );
ExtensionTypeDeclarationImpl _expectExtensionTypeDeclaration(int id) => ExtensionTypeDeclarationImpl _expectExtensionTypeDeclaration(int id) =>
new ExtensionTypeDeclarationImpl( ExtensionTypeDeclarationImpl(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
@ -348,7 +347,7 @@ extension DeserializerExtensions on Deserializer {
); );
TypeAliasDeclarationImpl _expectTypeAliasDeclaration(int id) => TypeAliasDeclarationImpl _expectTypeAliasDeclaration(int id) =>
new TypeAliasDeclarationImpl( TypeAliasDeclarationImpl(
id: id, id: id,
identifier: expectRemoteInstance(), identifier: expectRemoteInstance(),
library: RemoteInstance.deserialize(this), library: RemoteInstance.deserialize(this),
@ -357,10 +356,10 @@ extension DeserializerExtensions on Deserializer {
aliasedType: RemoteInstance.deserialize(this), aliasedType: RemoteInstance.deserialize(this),
); );
LibraryImpl _expectLibrary(int id) => new LibraryImpl( LibraryImpl _expectLibrary(int id) => LibraryImpl(
id: id, id: id,
languageVersion: new LanguageVersionImpl( languageVersion:
this.expectInt(), (this..moveNext()).expectInt()), LanguageVersionImpl(expectInt(), (this..moveNext()).expectInt()),
metadata: (this..moveNext())._expectRemoteInstanceList(), metadata: (this..moveNext())._expectRemoteInstanceList(),
uri: (this..moveNext()).expectUri(), uri: (this..moveNext()).expectUri(),
); );
@ -411,37 +410,36 @@ extension DeserializerExtensions on Deserializer {
CodeKind kind = CodeKind.values[expectInt()]; CodeKind kind = CodeKind.values[expectInt()];
return switch (kind) { return switch (kind) {
CodeKind.raw => new RawCode.fromParts(_readParts()) as T, CodeKind.raw => RawCode.fromParts(_readParts()) as T,
CodeKind.rawTypeAnnotation => CodeKind.rawTypeAnnotation =>
RawTypeAnnotationCode.fromParts(_readParts()) as T, RawTypeAnnotationCode.fromParts(_readParts()) as T,
CodeKind.comment => new CommentCode.fromParts(_readParts()) as T, CodeKind.comment => CommentCode.fromParts(_readParts()) as T,
CodeKind.declaration => new DeclarationCode.fromParts(_readParts()) as T, CodeKind.declaration => DeclarationCode.fromParts(_readParts()) as T,
CodeKind.expression => new ExpressionCode.fromParts(_readParts()) as T, CodeKind.expression => ExpressionCode.fromParts(_readParts()) as T,
CodeKind.functionBody => CodeKind.functionBody => FunctionBodyCode.fromParts(_readParts()) as T,
new FunctionBodyCode.fromParts(_readParts()) as T, CodeKind.functionTypeAnnotation => FunctionTypeAnnotationCode(
CodeKind.functionTypeAnnotation => new FunctionTypeAnnotationCode(
namedParameters: _readCodeList(), namedParameters: _readCodeList(),
positionalParameters: _readCodeList(), positionalParameters: _readCodeList(),
returnType: (this..moveNext()).expectNullableCode(), returnType: (this..moveNext()).expectNullableCode(),
typeParameters: _readCodeList()) as T, typeParameters: _readCodeList()) as T,
CodeKind.namedTypeAnnotation => new NamedTypeAnnotationCode( CodeKind.namedTypeAnnotation => NamedTypeAnnotationCode(
name: RemoteInstance.deserialize(this) as Identifier, name: RemoteInstance.deserialize(this) as Identifier,
typeArguments: _readCodeList()) as T, typeArguments: _readCodeList()) as T,
CodeKind.nullableTypeAnnotation => CodeKind.nullableTypeAnnotation =>
new NullableTypeAnnotationCode((this..moveNext()).expectCode()) as T, NullableTypeAnnotationCode((this..moveNext()).expectCode()) as T,
CodeKind.omittedTypeAnnotation => CodeKind.omittedTypeAnnotation =>
new OmittedTypeAnnotationCode(RemoteInstance.deserialize(this)) as T, OmittedTypeAnnotationCode(RemoteInstance.deserialize(this)) as T,
CodeKind.parameter => new ParameterCode( CodeKind.parameter => ParameterCode(
defaultValue: (this..moveNext()).expectNullableCode(), defaultValue: (this..moveNext()).expectNullableCode(),
keywords: _readStringList(), keywords: _readStringList(),
name: (this..moveNext()).expectNullableString(), name: (this..moveNext()).expectNullableString(),
type: (this..moveNext()).expectNullableCode()) as T, type: (this..moveNext()).expectNullableCode()) as T,
CodeKind.recordField => new RecordFieldCode( CodeKind.recordField => RecordFieldCode(
name: (this..moveNext()).expectNullableString(), name: (this..moveNext()).expectNullableString(),
type: (this..moveNext()).expectCode()) as T, type: (this..moveNext()).expectCode()) as T,
CodeKind.recordTypeAnnotation => new RecordTypeAnnotationCode( CodeKind.recordTypeAnnotation => RecordTypeAnnotationCode(
namedFields: _readCodeList(), positionalFields: _readCodeList()) as T, namedFields: _readCodeList(), positionalFields: _readCodeList()) as T,
CodeKind.typeParameter => new TypeParameterCode( CodeKind.typeParameter => TypeParameterCode(
bound: (this..moveNext()).expectNullableCode(), bound: (this..moveNext()).expectNullableCode(),
name: (this..moveNext()).expectString()) as T, name: (this..moveNext()).expectString()) as T,
}; };
@ -462,7 +460,7 @@ extension DeserializerExtensions on Deserializer {
DiagnosticMessage message = (this..moveNext()).expectDiagnosticMessage(); DiagnosticMessage message = (this..moveNext()).expectDiagnosticMessage();
Severity severity = Severity.values[(this..moveNext()).expectInt()]; Severity severity = Severity.values[(this..moveNext()).expectInt()];
return new Diagnostic(message, severity, return Diagnostic(message, severity,
contextMessages: context, correctionMessage: correctionMessage); contextMessages: context, correctionMessage: correctionMessage);
} }
@ -473,14 +471,14 @@ extension DeserializerExtensions on Deserializer {
RemoteInstance? target = checkNull() ? null : expectRemoteInstance(); RemoteInstance? target = checkNull() ? null : expectRemoteInstance();
return switch (target) { return switch (target) {
null => new DiagnosticMessage(message), null => DiagnosticMessage(message),
DeclarationImpl() => DeclarationImpl() =>
new DiagnosticMessage(message, target: target.asDiagnosticTarget), DiagnosticMessage(message, target: target.asDiagnosticTarget),
TypeAnnotationImpl() => TypeAnnotationImpl() =>
new DiagnosticMessage(message, target: target.asDiagnosticTarget), DiagnosticMessage(message, target: target.asDiagnosticTarget),
MetadataAnnotationImpl() => MetadataAnnotationImpl() =>
new DiagnosticMessage(message, target: target.asDiagnosticTarget), DiagnosticMessage(message, target: target.asDiagnosticTarget),
_ => throw new UnsupportedError( _ => throw UnsupportedError(
'Unsupported target type ${target.runtimeType}, only Declarations, ' 'Unsupported target type ${target.runtimeType}, only Declarations, '
'TypeAnnotations, and Metadata are allowed.'), 'TypeAnnotations, and Metadata are allowed.'),
}; };
@ -536,7 +534,7 @@ extension SerializeCode on Code {
for (ParameterCode positional in self.positionalParameters) { for (ParameterCode positional in self.positionalParameters) {
positional.serialize(serializer); positional.serialize(serializer);
} }
serializer..endList(); serializer.endList();
self.returnType.serializeNullable(serializer); self.returnType.serializeNullable(serializer);
serializer.startList(); serializer.startList();
for (TypeParameterCode typeParam in self.typeParameters) { for (TypeParameterCode typeParam in self.typeParameters) {
@ -608,7 +606,7 @@ extension SerializeCode on Code {
serializer.addInt(_CodePartKind.identifier.index); serializer.addInt(_CodePartKind.identifier.index);
part.serialize(serializer); part.serialize(serializer);
} else { } else {
throw new StateError('Unrecognized code part $part'); throw StateError('Unrecognized code part $part');
} }
} }
serializer.endList(); serializer.endList();

View File

@ -71,61 +71,61 @@ sealed class Key {
} }
enum _ContentKind { enum _ContentKind {
Code, code,
String, string,
ImplicitThis, implicitThis,
PrefixDot, prefixDot,
StaticScope, staticScope,
IdentifierName, identifierName,
LibraryAugmentation, libraryAugmentation,
LibraryAugmentationSeparator, libraryAugmentationSeparator,
} }
/// Content defined by its [kind] and [index] within the [parent] key. /// Content defined by its [_kind] and [index] within the [parent] key.
class ContentKey implements Key { class ContentKey implements Key {
@override @override
final Key parent; final Key parent;
final int index; final int index;
final _ContentKind kind; final _ContentKind _kind;
ContentKey._(this.parent, this.index, this.kind); ContentKey._(this.parent, this.index, this._kind);
/// Create the key for a [Code] object occurring as the [index]th part of /// Create the key for a [Code] object occurring as the [index]th part of
/// [parent]. /// [parent].
ContentKey.code(Key parent, int index) ContentKey.code(Key parent, int index)
: this._(parent, index, _ContentKind.Code); : this._(parent, index, _ContentKind.code);
/// Create the key for a [String] occurring as the [index]th part of [parent]. /// Create the key for a [String] occurring as the [index]th part of [parent].
ContentKey.string(Key parent, int index) ContentKey.string(Key parent, int index)
: this._(parent, index, _ContentKind.String); : this._(parent, index, _ContentKind.string);
/// Create the key for a `this.` occurring as the [index]th part of [parent]. /// Create the key for a `this.` occurring as the [index]th part of [parent].
ContentKey.implicitThis(Key parent, int index) ContentKey.implicitThis(Key parent, int index)
: this._(parent, index, _ContentKind.ImplicitThis); : this._(parent, index, _ContentKind.implicitThis);
/// Create the key for a `.` after a prefix occurring as the [index]th part /// Create the key for a `.` after a prefix occurring as the [index]th part
/// of [parent]. /// of [parent].
ContentKey.prefixDot(Key parent, int index) ContentKey.prefixDot(Key parent, int index)
: this._(parent, index, _ContentKind.PrefixDot); : this._(parent, index, _ContentKind.prefixDot);
/// Create the key for a static qualifier `Foo.` of a static member access in /// Create the key for a static qualifier `Foo.` of a static member access in
/// `Foo` occurring as the [index]th part of [parent]. /// `Foo` occurring as the [index]th part of [parent].
ContentKey.staticScope(Key parent, int index) ContentKey.staticScope(Key parent, int index)
: this._(parent, index, _ContentKind.StaticScope); : this._(parent, index, _ContentKind.staticScope);
/// Create the key for an [Identifier] after a prefix occurring as the /// Create the key for an [Identifier] after a prefix occurring as the
/// [index]th part of [parent]. /// [index]th part of [parent].
ContentKey.identifierName(Key parent, int index) ContentKey.identifierName(Key parent, int index)
: this._(parent, index, _ContentKind.IdentifierName); : this._(parent, index, _ContentKind.identifierName);
/// Create the key the [index]th library augmentation in [parent]. /// Create the key the [index]th library augmentation in [parent].
ContentKey.libraryAugmentation(Key parent, int index) ContentKey.libraryAugmentation(Key parent, int index)
: this._(parent, index, _ContentKind.LibraryAugmentation); : this._(parent, index, _ContentKind.libraryAugmentation);
/// Create the key the separator text after the [index]th library augmentation /// Create the key the separator text after the [index]th library augmentation
/// in [parent]. /// in [parent].
ContentKey.libraryAugmentationSeparator(Key parent, int index) ContentKey.libraryAugmentationSeparator(Key parent, int index)
: this._(parent, index, _ContentKind.LibraryAugmentationSeparator); : this._(parent, index, _ContentKind.libraryAugmentationSeparator);
@override @override
bool operator ==(Object other) => bool operator ==(Object other) =>
@ -134,40 +134,40 @@ class ContentKey implements Key {
runtimeType == other.runtimeType && runtimeType == other.runtimeType &&
parent == other.parent && parent == other.parent &&
index == other.index && index == other.index &&
kind == other.kind; _kind == other._kind;
@override @override
int get hashCode => Object.hash(parent, index, kind); int get hashCode => Object.hash(parent, index, _kind);
} }
enum _UriKind { enum _UriKind {
Prefix, prefix,
ImportPrefix, importPrefix,
ImportSuffix, importSuffix,
} }
/// Use of a [Uri] defined by the [uri] and the [kind] of use. /// Use of a [Uri] defined by the [uri] and the [_kind] of use.
class UriKey implements Key { class UriKey implements Key {
final Uri uri; final Uri uri;
final _UriKind kind; final _UriKind _kind;
UriKey._(this.uri, this.kind); UriKey._(this.uri, this._kind);
/// Creates a key for the definition of the prefix for [uri], that is, /// Creates a key for the definition of the prefix for [uri], that is,
/// "prefix" in `import 'foo.dart' as prefix;`. /// "prefix" in `import 'foo.dart' as prefix;`.
UriKey.prefixDefinition(Uri uri) : this._(uri, _UriKind.Prefix); UriKey.prefixDefinition(Uri uri) : this._(uri, _UriKind.prefix);
/// Creates a key for the prefix of the import of [uri], that is, /// Creates a key for the prefix of the import of [uri], that is,
/// "import 'foo.dart' as" in `import 'foo.dart' as prefix;`. /// "import 'foo.dart' as" in `import 'foo.dart' as prefix;`.
UriKey.importPrefix(Uri uri) : this._(uri, _UriKind.ImportPrefix); UriKey.importPrefix(Uri uri) : this._(uri, _UriKind.importPrefix);
/// Creates a key for the suffix of the import of [uri], that is, /// Creates a key for the suffix of the import of [uri], that is,
/// ";\n" in /// ";\n" in
/// ///
/// import 'foo.dart' as prefix; /// import 'foo.dart' as prefix;
/// ///
UriKey.importSuffix(Uri uri) : this._(uri, _UriKind.ImportSuffix); UriKey.importSuffix(Uri uri) : this._(uri, _UriKind.importSuffix);
@override @override
Key? get parent => null; Key? get parent => null;
@ -178,10 +178,10 @@ class UriKey implements Key {
other is UriKey && other is UriKey &&
runtimeType == other.runtimeType && runtimeType == other.runtimeType &&
uri == other.uri && uri == other.uri &&
kind == other.kind; _kind == other._kind;
@override @override
int get hashCode => Object.hash(uri, kind); int get hashCode => Object.hash(uri, _kind);
} }
/// A reference to the prefix of [uri] occurring as the [index]th part of /// A reference to the prefix of [uri] occurring as the [index]th part of
@ -310,13 +310,13 @@ class TypeDeclarationKey implements Key {
} }
enum _TypeDeclarationContentKind { enum _TypeDeclarationContentKind {
Declaration, declaration,
Mixins, mixins,
Interfaces, interfaces,
BodyStart, bodyStart,
EnumValueEnd, enumValueEnd,
DeclarationSeparator, declarationSeparator,
BodyEnd, bodyEnd,
} }
/// Content of a [TypeDeclaration]. /// Content of a [TypeDeclaration].
@ -324,24 +324,24 @@ class TypeDeclarationContentKey implements Key {
@override @override
final Key parent; final Key parent;
final _TypeDeclarationContentKind kind; final _TypeDeclarationContentKind _kind;
TypeDeclarationContentKey._(this.parent, this.kind); TypeDeclarationContentKey._(this.parent, this._kind);
/// The declaration of the type declaration, that is, "augment class Foo " in /// The declaration of the type declaration, that is, "augment class Foo " in
/// `augment class Foo { }`. /// `augment class Foo { }`.
TypeDeclarationContentKey.declaration(Key parent) TypeDeclarationContentKey.declaration(Key parent)
: this._(parent, _TypeDeclarationContentKind.Declaration); : this._(parent, _TypeDeclarationContentKind.declaration);
/// The fixed parts of a with-clause, that is, "with " and ", " in /// The fixed parts of a with-clause, that is, "with " and ", " in
/// `augment class Foo with Bar, Baz { }`. /// `augment class Foo with Bar, Baz { }`.
TypeDeclarationContentKey.mixins(Key parent) TypeDeclarationContentKey.mixins(Key parent)
: this._(parent, _TypeDeclarationContentKind.Mixins); : this._(parent, _TypeDeclarationContentKind.mixins);
/// The fixed parts of an implements-clause, that is, "implements " and ", " /// The fixed parts of an implements-clause, that is, "implements " and ", "
/// in `augment class Foo implements Bar, Baz { }`. /// in `augment class Foo implements Bar, Baz { }`.
TypeDeclarationContentKey.interfaces(Key parent) TypeDeclarationContentKey.interfaces(Key parent)
: this._(parent, _TypeDeclarationContentKind.Interfaces); : this._(parent, _TypeDeclarationContentKind.interfaces);
/// The start of the declaration body, that is, "{\n" in /// The start of the declaration body, that is, "{\n" in
/// ///
@ -349,7 +349,7 @@ class TypeDeclarationContentKey implements Key {
/// } /// }
/// ///
TypeDeclarationContentKey.bodyStart(Key parent) TypeDeclarationContentKey.bodyStart(Key parent)
: this._(parent, _TypeDeclarationContentKind.BodyStart); : this._(parent, _TypeDeclarationContentKind.bodyStart);
/// The end of element values, that is, ";\n" /// The end of element values, that is, ";\n"
/// ///
@ -361,11 +361,11 @@ class TypeDeclarationContentKey implements Key {
/// } /// }
/// ///
TypeDeclarationContentKey.enumValueEnd(Key parent) TypeDeclarationContentKey.enumValueEnd(Key parent)
: this._(parent, _TypeDeclarationContentKind.EnumValueEnd); : this._(parent, _TypeDeclarationContentKind.enumValueEnd);
/// The space between member declarations. /// The space between member declarations.
TypeDeclarationContentKey.declarationSeparator(Key parent) TypeDeclarationContentKey.declarationSeparator(Key parent)
: this._(parent, _TypeDeclarationContentKind.DeclarationSeparator); : this._(parent, _TypeDeclarationContentKind.declarationSeparator);
/// The end of the declaration body, that is, "}\n" in /// The end of the declaration body, that is, "}\n" in
/// ///
@ -373,7 +373,7 @@ class TypeDeclarationContentKey implements Key {
/// } /// }
/// ///
TypeDeclarationContentKey.bodyEnd(Key parent) TypeDeclarationContentKey.bodyEnd(Key parent)
: this._(parent, _TypeDeclarationContentKind.BodyEnd); : this._(parent, _TypeDeclarationContentKind.bodyEnd);
@override @override
bool operator ==(Object other) => bool operator ==(Object other) =>
@ -381,45 +381,45 @@ class TypeDeclarationContentKey implements Key {
other is TypeDeclarationContentKey && other is TypeDeclarationContentKey &&
runtimeType == other.runtimeType && runtimeType == other.runtimeType &&
parent == other.parent && parent == other.parent &&
kind == other.kind; _kind == other._kind;
@override @override
int get hashCode => Object.hash(parent, kind); int get hashCode => Object.hash(parent, _kind);
} }
enum _IdentifierKind { enum _IdentifierKind {
Enum, enuum, // `uu` because `enum` is reserved
Mixin, mixin,
Interface, interface,
Type, type,
} }
/// Key defined be the [identifier] its use [kind] occurring as the [index]th /// Key defined be the [identifier] its use [_kind] occurring as the [index]th
/// part of [parent]. /// part of [parent].
class IdentifierKey implements Key { class IdentifierKey implements Key {
@override @override
final Key parent; final Key parent;
final Identifier identifier; final Identifier identifier;
final int index; final int index;
final _IdentifierKind kind; final _IdentifierKind _kind;
IdentifierKey._(this.parent, this.index, this.identifier, this.kind); IdentifierKey._(this.parent, this.index, this.identifier, this._kind);
/// Identifier for an enum value. /// Identifier for an enum value.
IdentifierKey.enum_(Key parent, int index, Identifier identifier) IdentifierKey.enum_(Key parent, int index, Identifier identifier)
: this._(parent, index, identifier, _IdentifierKind.Enum); : this._(parent, index, identifier, _IdentifierKind.enuum);
/// Identifier for a mixed in type. /// Identifier for a mixed in type.
IdentifierKey.mixin(Key parent, int index, Identifier identifier) IdentifierKey.mixin(Key parent, int index, Identifier identifier)
: this._(parent, index, identifier, _IdentifierKind.Mixin); : this._(parent, index, identifier, _IdentifierKind.mixin);
/// Identifier for an implemented type. /// Identifier for an implemented type.
IdentifierKey.interface(Key parent, int index, Identifier identifier) IdentifierKey.interface(Key parent, int index, Identifier identifier)
: this._(parent, index, identifier, _IdentifierKind.Interface); : this._(parent, index, identifier, _IdentifierKind.interface);
/// Identifier for an augmented member. /// Identifier for an augmented member.
IdentifierKey.member(Key parent, int index, Identifier identifier) IdentifierKey.member(Key parent, int index, Identifier identifier)
: this._(parent, index, identifier, _IdentifierKind.Type); : this._(parent, index, identifier, _IdentifierKind.type);
@override @override
bool operator ==(Object other) => bool operator ==(Object other) =>
@ -429,10 +429,10 @@ class IdentifierKey implements Key {
parent == other.parent && parent == other.parent &&
index == other.index && index == other.index &&
identifier == other.identifier && identifier == other.identifier &&
kind == other.kind; _kind == other._kind;
@override @override
int get hashCode => Object.hash(parent, index, identifier, kind); int get hashCode => Object.hash(parent, index, identifier, _kind);
} }
/// Key for the separation between imports and declarations. /// Key for the separation between imports and declarations.

View File

@ -1,5 +1,5 @@
name: _macros name: _macros
version: 0.0.1 version: 0.1.0
description: >- description: >-
This is a private SDK vendored package, which is re-exported by the public This is a private SDK vendored package, which is re-exported by the public
`macros` package, which is a pub package. Every change to this package is `macros` package, which is a pub package. Every change to this package is
@ -9,3 +9,8 @@ repository: https://github.com/dart-lang/sdk/tree/main/pkg/_macros
environment: environment:
sdk: ^3.3.0 sdk: ^3.3.0
# Note that as an SDK vendored package, pub package dependencies are only
# allowed in the dev_dependencies section.
dev_dependencies:
test: any

View File

@ -2,15 +2,15 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/executor/introspection_impls.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/remote_instance.dart';
import 'package:test/fake.dart'; import 'package:test/fake.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:_fe_analyzer_shared/src/macros/executor.dart'; import 'package:_macros/src/api.dart';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:_macros/src/executor.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/augmentation_library.dart'; import 'package:_macros/src/executor/augmentation_library.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/response_impls.dart'; import 'package:_macros/src/executor/introspection_impls.dart';
import 'package:_macros/src/executor/remote_instance.dart';
import 'package:_macros/src/executor/response_impls.dart';
import '../util.dart'; import '../util.dart';

View File

@ -4,7 +4,7 @@
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/cast.dart'; import 'package:_macros/src/executor/cast.dart';
void main() { void main() {
test("dynamic casts", () { test("dynamic casts", () {

View File

@ -5,16 +5,15 @@
import 'dart:io'; import 'dart:io';
import 'dart:isolate'; import 'dart:isolate';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:_macros/src/api.dart';
import 'package:_fe_analyzer_shared/src/macros/bootstrap.dart'; import 'package:_macros/src/bootstrap.dart';
import 'package:_fe_analyzer_shared/src/macros/executor.dart'; import 'package:_macros/src/executor.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/isolated_executor.dart' import 'package:_macros/src/executor/isolated_executor.dart'
as isolatedExecutor; as isolated_executor;
import 'package:_fe_analyzer_shared/src/macros/executor/process_executor.dart' import 'package:_macros/src/executor/process_executor.dart' as process_executor
as processExecutor show start; show start;
import 'package:_fe_analyzer_shared/src/macros/executor/process_executor.dart' import 'package:_macros/src/executor/process_executor.dart' hide start;
hide start; import 'package:_macros/src/executor/serialization.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import '../util.dart'; import '../util.dart';
@ -67,7 +66,7 @@ void main() {
'-o', '-o',
kernelOutputFile.uri.toFilePath(), kernelOutputFile.uri.toFilePath(),
], ],
'--packages=${packageConfigPath}', '--packages=$packageConfigPath',
bootstrapFile.uri.toFilePath(), bootstrapFile.uri.toFilePath(),
]); ]);
expect(buildSnapshotResult.exitCode, 0, expect(buildSnapshotResult.exitCode, 0,
@ -75,11 +74,11 @@ void main() {
'stderr: ${buildSnapshotResult.stderr}'); 'stderr: ${buildSnapshotResult.stderr}');
executor = executorKind == 'Isolated' executor = executorKind == 'Isolated'
? await isolatedExecutor.start(mode, kernelOutputFile.uri) ? await isolated_executor.start(mode, kernelOutputFile.uri)
: executorKind == 'ProcessSocket' : executorKind == 'ProcessSocket'
? await processExecutor.start(mode, ? await process_executor.start(mode,
CommunicationChannel.socket, kernelOutputFile.path) CommunicationChannel.socket, kernelOutputFile.path)
: await processExecutor.start(mode, : await process_executor.start(mode,
CommunicationChannel.stdio, kernelOutputFile.path); CommunicationChannel.stdio, kernelOutputFile.path);
simpleMacroInstanceId = await executor.instantiateMacro( simpleMacroInstanceId = await executor.instantiateMacro(
@ -549,7 +548,7 @@ class LibraryInfo {
.debugString() .debugString()
.toString(), .toString(),
equalsIgnoringWhitespace(''' equalsIgnoringWhitespace('''
static const List<String> valuesByName = {\'a\': a}; static const List<String> valuesByName = {'a': a};
''')); '''));
expect(result.libraryAugmentations, isEmpty); expect(result.libraryAugmentations, isEmpty);
}); });
@ -1018,7 +1017,7 @@ final fieldDefinitionMatchers = [
augmented = value; augmented = value;
}'''), }'''),
equalsIgnoringWhitespace(''' equalsIgnoringWhitespace('''
augment String myField = \'new initial value\' + augmented;'''), augment String myField = 'new initial value' + augmented;'''),
]; ];
final methodDefinitionMatchers = [ final methodDefinitionMatchers = [

View File

@ -2,10 +2,10 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:_macros/src/api.dart';
import 'package:_fe_analyzer_shared/src/macros/executor.dart'; import 'package:_macros/src/executor.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/remote_instance.dart'; import 'package:_macros/src/executor/remote_instance.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/response_impls.dart'; import 'package:_macros/src/executor/response_impls.dart';
import 'package:test/fake.dart'; import 'package:test/fake.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';

View File

@ -4,12 +4,12 @@
import 'dart:math'; import 'dart:math';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:_macros/src/api.dart';
import 'package:_fe_analyzer_shared/src/macros/executor.dart'; import 'package:_macros/src/executor.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/exception_impls.dart'; import 'package:_macros/src/executor/exception_impls.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/introspection_impls.dart'; import 'package:_macros/src/executor/introspection_impls.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/remote_instance.dart'; import 'package:_macros/src/executor/remote_instance.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'; import 'package:_macros/src/executor/serialization.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import '../util.dart'; import '../util.dart';
@ -680,7 +680,7 @@ void main() {
/// Serializes [serializable] in server mode, then deserializes it in client /// Serializes [serializable] in server mode, then deserializes it in client
/// mode, and checks that all the fields are the same. /// mode, and checks that all the fields are the same.
void expectSerializationEquality<T extends Serializable>(T serializable, void expectSerializationEquality<T extends Serializable>(T serializable,
SerializationMode mode, T deserialize(Deserializer deserializer)) { SerializationMode mode, T Function(Deserializer deserializer) deserialize) {
withSerializationMode(mode, () { withSerializationMode(mode, () {
late Object? serialized; late Object? serialized;
final int zoneId = newRemoteInstanceZone(); final int zoneId = newRemoteInstanceZone();
@ -706,8 +706,8 @@ void expectSerializationEquality<T extends Serializable>(T serializable,
MacroExceptionImpl() => deepEqualsMacroException(deserialized), MacroExceptionImpl() => deepEqualsMacroException(deserialized),
MetadataAnnotation() => MetadataAnnotation() =>
deepEqualsMetadataAnnotation(deserialized as MetadataAnnotation), deepEqualsMetadataAnnotation(deserialized as MetadataAnnotation),
_ => throw new UnsupportedError( _ =>
'Unsupported object type $deserialized'), throw UnsupportedError('Unsupported object type $deserialized'),
}); });
}, createIfMissing: true); }, createIfMissing: true);
}); });

View File

@ -4,7 +4,7 @@
import 'dart:async'; import 'dart:async';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:_macros/src/api.dart';
/// A macro for testing diagnostics reporting, including error handling. /// A macro for testing diagnostics reporting, including error handling.
class DiagnosticMacro implements ClassTypesMacro { class DiagnosticMacro implements ClassTypesMacro {
@ -162,7 +162,7 @@ class SimpleMacro
], ],
')', ')',
], ],
' => ${functionName}', ' => $functionName',
function.isGetter function.isGetter
? '' ? ''
: function.isSetter : function.isSetter
@ -177,7 +177,7 @@ class SimpleMacro
MethodDeclaration method, MemberDeclarationBuilder builder) { MethodDeclaration method, MemberDeclarationBuilder builder) {
if (method.positionalParameters.isNotEmpty || if (method.positionalParameters.isNotEmpty ||
method.namedParameters.isNotEmpty) { method.namedParameters.isNotEmpty) {
throw new UnsupportedError('Can only run on method with no parameters!'); throw UnsupportedError('Can only run on method with no parameters!');
} }
var methodName = method.identifier.name; var methodName = method.identifier.name;
builder.declareInLibrary(DeclarationCode.fromParts([ builder.declareInLibrary(DeclarationCode.fromParts([
@ -302,14 +302,14 @@ class SimpleMacro
if (!(await resolvedType.isExactly(stringType))) { if (!(await resolvedType.isExactly(stringType))) {
throw StateError('Expected only string parameters'); throw StateError('Expected only string parameters');
} }
parts..add("'${positional.identifier.name}', "); parts.add("'${positional.identifier.name}', ");
} }
for (var named in constructor.namedParameters) { for (var named in constructor.namedParameters) {
final resolvedType = await builder.resolve(named.type.code); final resolvedType = await builder.resolve(named.type.code);
if (!(await resolvedType.isExactly(stringType))) { if (!(await resolvedType.isExactly(stringType))) {
throw StateError('Expected only string parameters'); throw StateError('Expected only string parameters');
} }
parts..add("${named.identifier.name}: '${named.identifier.name}', "); parts.add("${named.identifier.name}: '${named.identifier.name}', ");
} }
parts.add('),'); parts.add('),');
builder.augment(DeclarationCode.fromParts(parts)); builder.augment(DeclarationCode.fromParts(parts));
@ -468,7 +468,7 @@ class SimpleMacro
@override @override
FutureOr<void> buildTypesForClass( FutureOr<void> buildTypesForClass(
ClassDeclaration clazz, ClassTypeBuilder builder) { ClassDeclaration clazz, ClassTypeBuilder builder) {
List<Object> _buildTypeParam( List<Object> buildTypeParam(
TypeParameterDeclaration typeParam, bool isFirst) { TypeParameterDeclaration typeParam, bool isFirst) {
return [ return [
if (!isFirst) ', ', if (!isFirst) ', ',
@ -487,9 +487,9 @@ class SimpleMacro
'class $name', 'class $name',
if (clazz.typeParameters.isNotEmpty) ...[ if (clazz.typeParameters.isNotEmpty) ...[
'<', '<',
..._buildTypeParam(clazz.typeParameters.first, true), ...buildTypeParam(clazz.typeParameters.first, true),
for (var typeParam in clazz.typeParameters.skip(1)) for (var typeParam in clazz.typeParameters.skip(1))
..._buildTypeParam(typeParam, false), ...buildTypeParam(typeParam, false),
'>', '>',
], ],
' implements Builder<', ' implements Builder<',
@ -798,6 +798,6 @@ Future<FunctionBodyCode> _buildFunctionAugmentation(
]); ]);
} }
extension _ on String { extension on String {
String capitalize() => '${this[0].toUpperCase()}${substring(1)}'; String capitalize() => '${this[0].toUpperCase()}${substring(1)}';
} }

View File

@ -4,10 +4,10 @@
import 'dart:mirrors'; import 'dart:mirrors';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:_macros/src/api.dart';
import 'package:_fe_analyzer_shared/src/macros/executor.dart'; import 'package:_macros/src/executor.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/introspection_impls.dart'; import 'package:_macros/src/executor/introspection_impls.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/remote_instance.dart'; import 'package:_macros/src/executor/remote_instance.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
class TestTypePhaseIntrospector implements TypePhaseIntrospector { class TestTypePhaseIntrospector implements TypePhaseIntrospector {

View File

@ -93,23 +93,15 @@ mixin ConfigurationFilesMixin on MockPackagesMixin {
final packageRoot = final packageRoot =
physical.pathContext.normalize(package_root.packageRoot); physical.pathContext.normalize(package_root.packageRoot);
// Copy _fe_analyzer_shared from local SDK into the resource provider. for (var package in ['macros', '_macros']) {
final testSharedFolder = resourceProvider final destination = resourceProvider
.getFolder(convertPath('$packagesRootPath/_fe_analyzer_shared')); .getFolder(convertPath('$packagesRootPath/$package'));
physical physical
.getFolder(packageRoot) .getFolder(packageRoot)
.getChildAssumingFolder('_fe_analyzer_shared/lib/src/macros') .getChildAssumingFolder(package)
.copyTo(testSharedFolder.getChildAssumingFolder('lib/src')); .copyTo(destination.parent);
config.add(name: '_fe_analyzer_shared', rootPath: testSharedFolder.path); config.add(name: package, rootPath: destination.path);
}
// Copy dart_internal from local SDK into the memory FS.
final testInternalFolder = resourceProvider
.getFolder(convertPath('$packagesRootPath/dart_internal'));
physical
.getFolder(packageRoot)
.getChildAssumingFolder('dart_internal')
.copyTo(testInternalFolder);
config.add(name: 'dart_internal', rootPath: testInternalFolder.path);
} }
_newPackageConfigJsonFile( _newPackageConfigJsonFile(

View File

@ -26,7 +26,7 @@ mixin TestMacros on ConfigurationFilesMixin {
[ [
''' '''
// There is no public API exposed yet, the in-progress API lives here. // There is no public API exposed yet, the in-progress API lives here.
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
''', ''',
...macros ...macros
].join('\n'), ].join('\n'),

View File

@ -5,7 +5,6 @@
import 'dart:collection'; import 'dart:collection';
import 'package:_fe_analyzer_shared/src/flow_analysis/flow_analysis.dart'; import 'package:_fe_analyzer_shared/src/flow_analysis/flow_analysis.dart';
import 'package:_fe_analyzer_shared/src/macros/api.dart' as macro;
import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/syntactic_entity.dart'; import 'package:analyzer/dart/ast/syntactic_entity.dart';
import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/token.dart';
@ -56,6 +55,7 @@ import 'package:analyzer/src/utilities/extensions/element.dart';
import 'package:analyzer/src/utilities/extensions/object.dart'; import 'package:analyzer/src/utilities/extensions/object.dart';
import 'package:analyzer/src/utilities/extensions/string.dart'; import 'package:analyzer/src/utilities/extensions/string.dart';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'package:macros/macros.dart' as macro;
class EnclosingExecutableContext { class EnclosingExecutableContext {
final ExecutableElement? element; final ExecutableElement? element;

View File

@ -4,7 +4,6 @@
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:_fe_analyzer_shared/src/macros/api.dart' as macro;
import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart';
@ -37,6 +36,7 @@ import 'package:analyzer/src/utilities/extensions/collection.dart';
import 'package:analyzer/src/utilities/extensions/element.dart'; import 'package:analyzer/src/utilities/extensions/element.dart';
import 'package:analyzer/src/utilities/extensions/string.dart'; import 'package:analyzer/src/utilities/extensions/string.dart';
import 'package:analyzer/src/utilities/uri_cache.dart'; import 'package:analyzer/src/utilities/uri_cache.dart';
import 'package:macros/macros.dart' as macro;
import 'package:pub_semver/pub_semver.dart'; import 'package:pub_semver/pub_semver.dart';
class BundleReader { class BundleReader {

View File

@ -4,7 +4,6 @@
import 'package:_fe_analyzer_shared/src/field_promotability.dart'; import 'package:_fe_analyzer_shared/src/field_promotability.dart';
import 'package:_fe_analyzer_shared/src/macros/code_optimizer.dart' as macro; import 'package:_fe_analyzer_shared/src/macros/code_optimizer.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor.dart' as macro;
import 'package:analyzer/dart/analysis/features.dart'; import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/error/listener.dart'; import 'package:analyzer/error/listener.dart';
@ -36,6 +35,7 @@ import 'package:analyzer/src/summary2/types_builder.dart';
import 'package:analyzer/src/util/performance/operation_performance.dart'; import 'package:analyzer/src/util/performance/operation_performance.dart';
import 'package:analyzer/src/utilities/extensions/collection.dart'; import 'package:analyzer/src/utilities/extensions/collection.dart';
import 'package:analyzer/src/utilities/extensions/object.dart'; import 'package:analyzer/src/utilities/extensions/object.dart';
import 'package:macros/src/executor.dart' as macro;
class AugmentedClassDeclarationBuilder class AugmentedClassDeclarationBuilder
extends AugmentedInstanceDeclarationBuilder { extends AugmentedInstanceDeclarationBuilder {

View File

@ -4,8 +4,6 @@
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:_fe_analyzer_shared/src/macros/executor/multi_executor.dart'
as macro;
import 'package:analyzer/dart/analysis/declared_variables.dart'; import 'package:analyzer/dart/analysis/declared_variables.dart';
import 'package:analyzer/dart/ast/ast.dart' as ast; import 'package:analyzer/dart/ast/ast.dart' as ast;
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
@ -29,6 +27,7 @@ import 'package:analyzer/src/summary2/types_builder.dart';
import 'package:analyzer/src/summary2/variance_builder.dart'; import 'package:analyzer/src/summary2/variance_builder.dart';
import 'package:analyzer/src/util/performance/operation_performance.dart'; import 'package:analyzer/src/util/performance/operation_performance.dart';
import 'package:analyzer/src/utilities/uri_cache.dart'; import 'package:analyzer/src/utilities/uri_cache.dart';
import 'package:macros/src/executor/multi_executor.dart' as macro;
Future<LinkResult> link({ Future<LinkResult> link({
required LinkedElementFactory elementFactory, required LinkedElementFactory elementFactory,

View File

@ -6,17 +6,14 @@ import 'dart:io' as io;
import 'dart:isolate'; import 'dart:isolate';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:_fe_analyzer_shared/src/macros/bootstrap.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/isolated_executor.dart'
as isolated_executor;
import 'package:_fe_analyzer_shared/src/macros/executor/multi_executor.dart'
as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/process_executor.dart'
as process_executor;
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'
as macro;
import 'package:analyzer/src/summary2/kernel_compilation_service.dart'; import 'package:analyzer/src/summary2/kernel_compilation_service.dart';
import 'package:macros/src/bootstrap.dart' as macro;
import 'package:macros/src/executor.dart' as macro;
import 'package:macros/src/executor/isolated_executor.dart'
as isolated_executor;
import 'package:macros/src/executor/multi_executor.dart' as macro;
import 'package:macros/src/executor/process_executor.dart' as process_executor;
import 'package:macros/src/executor/serialization.dart' as macro;
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import 'package:path/path.dart' as package_path; import 'package:path/path.dart' as package_path;

View File

@ -2,11 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/exception_impls.dart'
as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/multi_executor.dart';
import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart';
@ -22,6 +17,10 @@ import 'package:analyzer/src/summary2/macro_declarations.dart';
import 'package:analyzer/src/utilities/extensions/collection.dart'; import 'package:analyzer/src/utilities/extensions/collection.dart';
import 'package:analyzer/src/utilities/extensions/object.dart'; import 'package:analyzer/src/utilities/extensions/object.dart';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'package:macros/macros.dart' as macro;
import 'package:macros/src/executor.dart' as macro;
import 'package:macros/src/executor/exception_impls.dart' as macro;
import 'package:macros/src/executor/multi_executor.dart';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
/// The full list of [macro.ArgumentKind]s for this dart type, with type /// The full list of [macro.ArgumentKind]s for this dart type, with type

View File

@ -2,9 +2,9 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart' as macro;
import 'package:analyzer/src/dart/element/element.dart'; import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/summary2/macro_type_location.dart'; import 'package:analyzer/src/summary2/macro_type_location.dart';
import 'package:macros/macros.dart' as macro;
/// Base for all macro related diagnostics. /// Base for all macro related diagnostics.
sealed class AnalyzerMacroDiagnostic {} sealed class AnalyzerMacroDiagnostic {}

View File

@ -2,14 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/exception_impls.dart'
as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/introspection_impls.dart'
as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/remote_instance.dart'
as macro;
import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart';
@ -23,6 +15,11 @@ import 'package:analyzer/src/utilities/extensions/collection.dart';
import 'package:analyzer/src/utilities/extensions/element.dart'; import 'package:analyzer/src/utilities/extensions/element.dart';
import 'package:analyzer/src/utilities/extensions/object.dart'; import 'package:analyzer/src/utilities/extensions/object.dart';
import 'package:collection/collection.dart'; import 'package:collection/collection.dart';
import 'package:macros/macros.dart' as macro;
import 'package:macros/src/executor.dart' as macro;
import 'package:macros/src/executor/exception_impls.dart' as macro;
import 'package:macros/src/executor/introspection_impls.dart' as macro;
import 'package:macros/src/executor/remote_instance.dart' as macro;
class ClassDeclarationImpl extends macro.ClassDeclarationImpl class ClassDeclarationImpl extends macro.ClassDeclarationImpl
implements HasElement { implements HasElement {

View File

@ -2,8 +2,8 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart' as macro;
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:macros/macros.dart' as macro;
final class AliasedTypeLocation extends TypeAnnotationLocation { final class AliasedTypeLocation extends TypeAnnotationLocation {
final TypeAnnotationLocation parent; final TypeAnnotationLocation parent;

View File

@ -13,6 +13,7 @@ dependencies:
convert: ^3.0.0 convert: ^3.0.0
crypto: ^3.0.0 crypto: ^3.0.0
glob: ^2.0.0 glob: ^2.0.0
macros: '>=0.1.0 <0.1.1'
meta: ^1.11.0 meta: ^1.11.0
package_config: ^2.0.0 package_config: ^2.0.0
path: ^1.9.0 path: ^1.9.0

View File

@ -15,8 +15,7 @@ import 'package:collection/collection.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
class AnalyzerStatePrinter { class AnalyzerStatePrinter {
static const String _macroApiUriStr = static const String _macroApiUriStr = 'package:macros/macros.dart';
'package:_fe_analyzer_shared/src/macros/api.dart';
static const String _macroApiUriRewrite = 'package:macro/api.dart'; static const String _macroApiUriRewrite = 'package:macro/api.dart';
@ -67,6 +66,9 @@ class AnalyzerStatePrinter {
if (isSdkLibrary) { if (isSdkLibrary) {
if (cycle.libraries.any((e) => e.file.uriStr == 'dart:core')) { if (cycle.libraries.any((e) => e.file.uriStr == 'dart:core')) {
return 'dart:core'; return 'dart:core';
} else if (cycle.libraries
.any((e) => e.file.uriStr == 'dart:collection')) {
return 'dart:collection';
} else { } else {
throw UnimplementedError('$cycle'); throw UnimplementedError('$cycle');
} }

View File

@ -420,7 +420,7 @@ String getClassName() => 'MacroA';
'''); ''');
newFile('$testPackageLibPath/my_macro.dart', r''' newFile('$testPackageLibPath/my_macro.dart', r'''
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
import 'a.dart'; import 'a.dart';
macro class MyMacro implements ClassTypesMacro { macro class MyMacro implements ClassTypesMacro {
@ -477,7 +477,7 @@ String getClassName() => 'MacroA';
'''); ''');
newFile('$testPackageLibPath/my_macro.dart', r''' newFile('$testPackageLibPath/my_macro.dart', r'''
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
part 'a.dart'; part 'a.dart';
macro class MyMacro implements ClassTypesMacro { macro class MyMacro implements ClassTypesMacro {
@ -570,7 +570,7 @@ String getClassName() => 'MacroA';
newFile('$testPackageLibPath/my_macro.dart', r''' newFile('$testPackageLibPath/my_macro.dart', r'''
import 'dart:async'; import 'dart:async';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
import 'a.dart'; import 'a.dart';
macro class MyMacro implements ClassTypesMacro { macro class MyMacro implements ClassTypesMacro {
@ -659,7 +659,7 @@ String getClassName() => 'MacroB';
File _newFileWithFixedNameMacro(String className) { File _newFileWithFixedNameMacro(String className) {
return newFile('$testPackageLibPath/my_macro.dart', ''' return newFile('$testPackageLibPath/my_macro.dart', '''
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
macro class MyMacro implements ClassTypesMacro { macro class MyMacro implements ClassTypesMacro {
const MyMacro(); const MyMacro();

View File

@ -487,15 +487,15 @@ class PubPackageResolutionTest extends ContextResolutionTest {
if (macrosEnvironment != null) { if (macrosEnvironment != null) {
var packagesRootFolder = getFolder(packagesRootPath); var packagesRootFolder = getFolder(packagesRootPath);
macrosEnvironment.packageSharedFolder.copyTo(packagesRootFolder); macrosEnvironment.publicMacrosFolder.copyTo(packagesRootFolder);
macrosEnvironment.packageDartInternalFolder.copyTo(packagesRootFolder); macrosEnvironment.privateMacrosFolder.copyTo(packagesRootFolder);
config.add( config.add(
name: '_fe_analyzer_shared', name: '_macros',
rootPath: getFolder('$packagesRootPath/_fe_analyzer_shared').path, rootPath: getFolder('$packagesRootPath/_macros').path,
); );
config.add( config.add(
name: 'dart_internal', name: 'macros',
rootPath: getFolder('$packagesRootPath/dart_internal').path, rootPath: getFolder('$packagesRootPath/macros').path,
); );
} }

View File

@ -69,7 +69,7 @@ void f(B b) {}
test_diagnostic_compilesWithError() async { test_diagnostic_compilesWithError() async {
newFile('$testPackageLibPath/a.dart', r''' newFile('$testPackageLibPath/a.dart', r'''
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
macro class MyMacro implements ClassTypesMacro { macro class MyMacro implements ClassTypesMacro {
const MyMacro(); const MyMacro();
@ -250,7 +250,7 @@ class A3 {}
test_diagnostic_definitionApplication_sameLibrary() async { test_diagnostic_definitionApplication_sameLibrary() async {
await assertErrorsInCode(''' await assertErrorsInCode('''
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
macro class MyMacro implements ClassDefinitionMacro { macro class MyMacro implements ClassDefinitionMacro {
const MyMacro(); const MyMacro();
@ -264,14 +264,14 @@ class A {}
''', [ ''', [
error( error(
CompileTimeErrorCode.MACRO_DEFINITION_APPLICATION_SAME_LIBRARY_CYCLE, CompileTimeErrorCode.MACRO_DEFINITION_APPLICATION_SAME_LIBRARY_CYCLE,
206, 185,
7), 7),
]); ]);
} }
test_diagnostic_definitionApplication_sameLibraryCycle() async { test_diagnostic_definitionApplication_sameLibraryCycle() async {
newFile('$testPackageLibPath/a.dart', r''' newFile('$testPackageLibPath/a.dart', r'''
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
import 'test.dart'; import 'test.dart';
macro class MyMacro implements ClassDefinitionMacro { macro class MyMacro implements ClassDefinitionMacro {
@ -910,7 +910,7 @@ class A {}
test_diagnostic_throwsException() async { test_diagnostic_throwsException() async {
newFile('$testPackageLibPath/a.dart', r''' newFile('$testPackageLibPath/a.dart', r'''
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
macro class MyMacro implements ClassTypesMacro { macro class MyMacro implements ClassTypesMacro {
const MyMacro(); const MyMacro();

View File

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
import 'append.dart'; import 'append.dart';

View File

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
/// Resolves top-level identifier references of form `{{uri@name}}`. /// Resolves top-level identifier references of form `{{uri@name}}`.
Future<List<Object>> resolveIdentifiers( Future<List<Object>> resolveIdentifiers(

View File

@ -4,7 +4,7 @@
import 'dart:async'; import 'dart:async';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
/// Does not do anything useful, just augments the target in the definitions /// Does not do anything useful, just augments the target in the definitions
/// phase, so that any omitted types are written into the augmentation. /// phase, so that any omitted types are written into the augmentation.

View File

@ -4,7 +4,7 @@
import 'dart:async'; import 'dart:async';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
/*macro*/ class AskFieldsWillThrow implements ClassDefinitionMacro { /*macro*/ class AskFieldsWillThrow implements ClassDefinitionMacro {
const AskFieldsWillThrow(); const AskFieldsWillThrow();

View File

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
/*macro*/ class AutoToString implements MethodDefinitionMacro { /*macro*/ class AutoToString implements MethodDefinitionMacro {
const AutoToString(); const AutoToString();

View File

@ -7,7 +7,7 @@
// ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: deprecated_member_use_from_same_package
// There is no public API exposed yet, the in-progress API lives here. // There is no public API exposed yet, the in-progress API lives here.
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
final _dartCore = Uri.parse('dart:core'); final _dartCore = Uri.parse('dart:core');
@ -639,7 +639,8 @@ extension on FieldDeclaration {
for (var annotation in metadata) { for (var annotation in metadata) {
if (annotation is! ConstructorMetadataAnnotation) continue; if (annotation is! ConstructorMetadataAnnotation) continue;
if (annotation.type.identifier.name != 'JsonKey') continue; if (annotation.type.identifier.name != 'JsonKey') continue;
var declaration = await builder.typeDeclarationOf(annotation.type.identifier); var declaration =
await builder.typeDeclarationOf(annotation.type.identifier);
if (declaration.library.uri != jsonKeyUri) continue; if (declaration.library.uri != jsonKeyUri) continue;
if (jsonKey != null) { if (jsonKey != null) {

View File

@ -5,7 +5,7 @@
// There is no public API exposed yet, the in-progress API lives here. // There is no public API exposed yet, the in-progress API lives here.
import 'dart:async'; import 'dart:async';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
/*macro*/ class Observable implements FieldDeclarationsMacro { /*macro*/ class Observable implements FieldDeclarationsMacro {
const Observable(); const Observable();

View File

@ -4,7 +4,7 @@
import 'dart:async'; import 'dart:async';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
/*macro*/ class Introspect /*macro*/ class Introspect
implements implements

View File

@ -4,7 +4,7 @@
import 'dart:async'; import 'dart:async';
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
/*macro*/ class AddClass /*macro*/ class AddClass
implements implements

View File

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
/*macro*/ class AddClassB implements ClassTypesMacro { /*macro*/ class AddClassB implements ClassTypesMacro {
const AddClassB(); const AddClassB();

View File

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
/*macro*/ class IsExactly implements FunctionDefinitionMacro { /*macro*/ class IsExactly implements FunctionDefinitionMacro {
const IsExactly(); const IsExactly();

File diff suppressed because it is too large Load Diff

View File

@ -22,27 +22,21 @@ class MacrosEnvironment {
var physical = PhysicalResourceProvider.INSTANCE; var physical = PhysicalResourceProvider.INSTANCE;
var packageRoot = physical.pathContext.normalize(package_root.packageRoot); var packageRoot = physical.pathContext.normalize(package_root.packageRoot);
physical physical.getFolder(packageRoot).getChildAssumingFolder('_macros').copyTo(
.getFolder(packageRoot) privateMacrosFolder.parent,
.getChildAssumingFolder('_fe_analyzer_shared/lib/src/macros')
.copyTo(
packageSharedFolder.getChildAssumingFolder('lib/src'),
); );
physical physical.getFolder(packageRoot).getChildAssumingFolder('macros').copyTo(
.getFolder(packageRoot) publicMacrosFolder.parent,
.getChildAssumingFolder('dart_internal')
.copyTo(
_resourceProvider.getFolder('/packages'),
); );
packageAnalyzerFolder = packageAnalyzerFolder =
physical.getFolder(packageRoot).getChildAssumingFolder('analyzer'); physical.getFolder(packageRoot).getChildAssumingFolder('analyzer');
} }
Folder get packageDartInternalFolder { Folder get privateMacrosFolder {
return _resourceProvider.getFolder('/packages/dart_internal'); return _resourceProvider.getFolder('/packages/_macros');
} }
Folder get packageSharedFolder { Folder get publicMacrosFolder {
return _resourceProvider.getFolder('/packages/_fe_analyzer_shared'); return _resourceProvider.getFolder('/packages/macros');
} }
} }

View File

@ -166,7 +166,7 @@ const simpleBreakpointProgram = '''
/// `hello()` method to a class that prints "Hello". /// `hello()` method to a class that prints "Hello".
const withHelloMacroImplementation = ''' const withHelloMacroImplementation = '''
// There is no public API exposed yet, the in-progress API lives here. // There is no public API exposed yet, the in-progress API lives here.
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
macro class WithHello implements ClassDeclarationsMacro { macro class WithHello implements ClassDeclarationsMacro {
const WithHello(); const WithHello();

View File

@ -202,10 +202,8 @@ foo() {
final sdkRoot = final sdkRoot =
path.normalize(path.join(dapIntegrationTestFolder, '../../../../..')); path.normalize(path.join(dapIntegrationTestFolder, '../../../../..'));
final feSharedPath = path.join(sdkRoot, 'pkg', '_fe_analyzer_shared'); final macrosPath = path.join(sdkRoot, 'pkg', 'macros');
await addPackageDependency(testAppDir, 'macros', Uri.file(macrosPath));
await addPackageDependency(
testAppDir, '_fe_analyzer_shared', Uri.file(feSharedPath));
createTestFile( createTestFile(
filename: 'analysis_options.yaml', filename: 'analysis_options.yaml',

View File

@ -30,6 +30,7 @@ dev_dependencies:
http_multi_server: any http_multi_server: any
js: any js: any
lints: any lints: any
macros: any
modular_test: any modular_test: any
reload_test: any reload_test: any
shelf: any shelf: any

View File

@ -4,11 +4,11 @@
import 'dart:io'; import 'dart:io';
import 'package:_fe_analyzer_shared/src/macros/bootstrap.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart';
import 'package:bazel_worker/bazel_worker.dart'; import 'package:bazel_worker/bazel_worker.dart';
import 'package:dev_compiler/ddc.dart' as ddc; import 'package:dev_compiler/ddc.dart' as ddc;
import 'package:frontend_server/compute_kernel.dart'; import 'package:frontend_server/compute_kernel.dart';
import 'package:macros/src/bootstrap.dart';
import 'package:macros/src/executor/serialization.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
Directory tmp = Directory.systemTemp.createTempSync('ddc_worker_test'); Directory tmp = Directory.systemTemp.createTempSync('ddc_worker_test');
@ -39,7 +39,7 @@ void main() {
testMacroDart = file('lib/test_macro.dart') testMacroDart = file('lib/test_macro.dart')
..createSync(recursive: true) ..createSync(recursive: true)
..writeAsStringSync(''' ..writeAsStringSync('''
import 'package:_fe_analyzer_shared/src/macros/api.dart'; import 'package:macros/macros.dart';
macro class TestMacro implements ClassDeclarationsMacro { macro class TestMacro implements ClassDeclarationsMacro {
const TestMacro(); const TestMacro();
@ -63,8 +63,13 @@ macro class TestMacro implements ClassDeclarationsMacro {
"packageUri": "lib/" "packageUri": "lib/"
}, },
{ {
"name": "_fe_analyzer_shared", "name": "_macros",
"rootUri": "${Platform.script.resolve('../../../_fe_analyzer_shared')}", "rootUri": "${Platform.script.resolve('../../../_macros')}",
"packageUri": "lib/"
},
{
"name": "macros",
"rootUri": "${Platform.script.resolve('../../../macros')}",
"packageUri": "lib/" "packageUri": "lib/"
}, },
{ {

View File

@ -4,9 +4,6 @@
library front_end.compiler_options; library front_end.compiler_options;
import 'package:_fe_analyzer_shared/src/macros/executor/multi_executor.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'
as macros show SerializationMode;
import 'package:_fe_analyzer_shared/src/messages/diagnostic_message.dart' import 'package:_fe_analyzer_shared/src/messages/diagnostic_message.dart'
show DiagnosticMessage, DiagnosticMessageHandler; show DiagnosticMessage, DiagnosticMessageHandler;
import 'package:_fe_analyzer_shared/src/messages/severity.dart' show Severity; import 'package:_fe_analyzer_shared/src/messages/severity.dart' show Severity;
@ -14,6 +11,9 @@ import 'package:kernel/ast.dart' show Component, Version;
import 'package:kernel/default_language_version.dart' as kernel import 'package:kernel/default_language_version.dart' as kernel
show defaultLanguageVersion; show defaultLanguageVersion;
import 'package:kernel/target/targets.dart' show Target; import 'package:kernel/target/targets.dart' show Target;
import 'package:macros/src/executor/multi_executor.dart';
import 'package:macros/src/executor/serialization.dart' as macros
show SerializationMode;
import '../api_unstable/util.dart'; import '../api_unstable/util.dart';
import '../base/nnbd_mode.dart'; import '../base/nnbd_mode.dart';

View File

@ -5,13 +5,12 @@
/// API needed by `utils/front_end/summary_worker.dart`, a tool used to compute /// API needed by `utils/front_end/summary_worker.dart`, a tool used to compute
/// summaries in build systems like bazel, pub-build, and package-build. /// summaries in build systems like bazel, pub-build, and package-build.
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'
show SerializationMode;
import 'package:_fe_analyzer_shared/src/messages/diagnostic_message.dart' import 'package:_fe_analyzer_shared/src/messages/diagnostic_message.dart'
show DiagnosticMessageHandler; show DiagnosticMessageHandler;
import 'package:front_end/src/api_prototype/compiler_options.dart'; import 'package:front_end/src/api_prototype/compiler_options.dart';
import 'package:kernel/kernel.dart' show Component, Library, dummyComponent; import 'package:kernel/kernel.dart' show Component, Library, dummyComponent;
import 'package:kernel/target/targets.dart' show Target; import 'package:kernel/target/targets.dart' show Target;
import 'package:macros/src/executor/serialization.dart' show SerializationMode;
import '../api_prototype/experimental_flags.dart' show ExperimentalFlag; import '../api_prototype/experimental_flags.dart' show ExperimentalFlag;
import '../api_prototype/file_system.dart' show FileSystem; import '../api_prototype/file_system.dart' show FileSystem;

View File

@ -2,13 +2,12 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'
show SerializationMode;
import 'package:_fe_analyzer_shared/src/messages/diagnostic_message.dart' import 'package:_fe_analyzer_shared/src/messages/diagnostic_message.dart'
show DiagnosticMessageHandler; show DiagnosticMessageHandler;
import 'package:kernel/class_hierarchy.dart'; import 'package:kernel/class_hierarchy.dart';
import 'package:kernel/kernel.dart' show Component, Library; import 'package:kernel/kernel.dart' show Component, Library;
import 'package:kernel/target/targets.dart' show Target; import 'package:kernel/target/targets.dart' show Target;
import 'package:macros/src/executor/serialization.dart' show SerializationMode;
import '../api_prototype/compiler_options.dart' show CompilerOptions; import '../api_prototype/compiler_options.dart' show CompilerOptions;
import '../api_prototype/experimental_flags.dart' show ExperimentalFlag; import '../api_prototype/experimental_flags.dart' show ExperimentalFlag;

View File

@ -2,10 +2,9 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'
show SerializationMode;
import 'package:kernel/kernel.dart' show Component, CanonicalName, Library; import 'package:kernel/kernel.dart' show Component, CanonicalName, Library;
import 'package:kernel/target/targets.dart' show Target; import 'package:kernel/target/targets.dart' show Target;
import 'package:macros/src/executor/serialization.dart' show SerializationMode;
import '../api_prototype/compiler_options.dart' show CompilerOptions; import '../api_prototype/compiler_options.dart' show CompilerOptions;
import '../api_prototype/experimental_flags.dart' show ExperimentalFlag; import '../api_prototype/experimental_flags.dart' show ExperimentalFlag;

View File

@ -5,13 +5,6 @@
import 'dart:io' show exitCode; import 'dart:io' show exitCode;
import 'dart:typed_data' show Uint8List; import 'dart:typed_data' show Uint8List;
import 'package:_fe_analyzer_shared/src/macros/executor/isolated_executor.dart'
as isolated_executor;
import 'package:_fe_analyzer_shared/src/macros/executor/multi_executor.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/process_executor.dart'
as process_executor;
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'
show SerializationMode;
import 'package:_fe_analyzer_shared/src/messages/severity.dart' show Severity; import 'package:_fe_analyzer_shared/src/messages/severity.dart' show Severity;
import 'package:_fe_analyzer_shared/src/util/libraries_specification.dart' import 'package:_fe_analyzer_shared/src/util/libraries_specification.dart'
show show
@ -28,6 +21,11 @@ import 'package:kernel/kernel.dart'
Version; Version;
import 'package:kernel/target/targets.dart' import 'package:kernel/target/targets.dart'
show NoneTarget, Target, TargetFlags; show NoneTarget, Target, TargetFlags;
import 'package:macros/src/executor/isolated_executor.dart'
as isolated_executor;
import 'package:macros/src/executor/multi_executor.dart';
import 'package:macros/src/executor/process_executor.dart' as process_executor;
import 'package:macros/src/executor/serialization.dart' show SerializationMode;
import 'package:package_config/package_config.dart'; import 'package:package_config/package_config.dart';
import '../api_prototype/compiler_options.dart' import '../api_prototype/compiler_options.dart'

View File

@ -7,8 +7,7 @@ library fasta.incremental_compiler;
import 'dart:async' show Completer; import 'dart:async' show Completer;
import 'dart:convert' show JsonEncoder; import 'dart:convert' show JsonEncoder;
import 'package:_fe_analyzer_shared/src/macros/executor/multi_executor.dart' import 'package:macros/src/executor/multi_executor.dart' as macros;
as macros;
import 'package:_fe_analyzer_shared/src/scanner/abstract_scanner.dart' import 'package:_fe_analyzer_shared/src/scanner/abstract_scanner.dart'
show ScannerConfiguration; show ScannerConfiguration;
import 'package:front_end/src/fasta/kernel/benchmarker.dart' import 'package:front_end/src/fasta/kernel/benchmarker.dart'

View File

@ -3,7 +3,7 @@
// BSD-style license that can be found in the LICENSE file. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/experiments/flags.dart'; import 'package:_fe_analyzer_shared/src/experiments/flags.dart';
import 'package:_fe_analyzer_shared/src/macros/executor.dart' as macro; import 'package:macros/src/executor.dart' as macro;
import 'package:_fe_analyzer_shared/src/messages/codes.dart'; import 'package:_fe_analyzer_shared/src/messages/codes.dart';
import 'package:_fe_analyzer_shared/src/parser/parser.dart'; import 'package:_fe_analyzer_shared/src/parser/parser.dart';
import 'package:_fe_analyzer_shared/src/parser/quote.dart'; import 'package:_fe_analyzer_shared/src/parser/quote.dart';

View File

@ -2,12 +2,10 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart' as macro; import 'package:macros/macros.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor.dart' as macro; import 'package:macros/src/executor.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/exception_impls.dart' import 'package:macros/src/executor/exception_impls.dart' as macro;
as macro; import 'package:macros/src/executor/introspection_impls.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/introspection_impls.dart'
as macro;
import 'package:kernel/ast.dart'; import 'package:kernel/ast.dart';
import '../../builder/declaration_builders.dart'; import '../../builder/declaration_builders.dart';

View File

@ -2,14 +2,11 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart' as macro; import 'package:macros/macros.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor.dart' as macro; import 'package:macros/src/executor.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/exception_impls.dart' import 'package:macros/src/executor/exception_impls.dart' as macro;
as macro; import 'package:macros/src/executor/introspection_impls.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/introspection_impls.dart' import 'package:macros/src/executor/remote_instance.dart' as macro;
as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/remote_instance.dart'
as macro;
import 'package:kernel/ast.dart'; import 'package:kernel/ast.dart';
import '../../builder/builder.dart'; import '../../builder/builder.dart';

View File

@ -2,9 +2,9 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart' as macro; import 'package:macros/macros.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor.dart' as macro; import 'package:macros/src/executor.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/span.dart' as macro; import 'package:macros/src/executor/span.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/uri.dart'; import 'package:_fe_analyzer_shared/src/macros/uri.dart';
import 'package:_fe_analyzer_shared/src/scanner/scanner.dart'; import 'package:_fe_analyzer_shared/src/scanner/scanner.dart';
import 'package:front_end/src/fasta/uri_offset.dart'; import 'package:front_end/src/fasta/uri_offset.dart';
@ -37,8 +37,7 @@ import 'offsets.dart';
const String intermediateAugmentationScheme = 'org-dartlang-augmentation'; const String intermediateAugmentationScheme = 'org-dartlang-augmentation';
final Uri macroLibraryUri = final Uri macroLibraryUri = Uri.parse('package:_macros/src/api.dart');
Uri.parse('package:_fe_analyzer_shared/src/macros/api.dart');
const String macroClassName = 'Macro'; const String macroClassName = 'Macro';
class MacroDeclarationData { class MacroDeclarationData {

View File

@ -2,11 +2,9 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart' as macro; import 'package:macros/macros.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/introspection_impls.dart' import 'package:macros/src/executor/introspection_impls.dart' as macro;
as macro; import 'package:macros/src/executor/remote_instance.dart' as macro;
import 'package:_fe_analyzer_shared/src/macros/executor/remote_instance.dart'
as macro;
import 'package:kernel/ast.dart'; import 'package:kernel/ast.dart';
import 'package:kernel/src/types.dart'; import 'package:kernel/src/types.dart';
import 'package:kernel/type_environment.dart' show SubtypeCheckMode; import 'package:kernel/type_environment.dart' show SubtypeCheckMode;

View File

@ -5,16 +5,15 @@
/// Defines the front-end API for converting source code to Dart Kernel objects. /// Defines the front-end API for converting source code to Dart Kernel objects.
library front_end.kernel_generator_impl; library front_end.kernel_generator_impl;
import 'package:_fe_analyzer_shared/src/macros/bootstrap.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/kernel_executor.dart'
as kernelExecutor;
import 'package:_fe_analyzer_shared/src/macros/executor/multi_executor.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart';
import 'package:_fe_analyzer_shared/src/messages/severity.dart' show Severity; import 'package:_fe_analyzer_shared/src/messages/severity.dart' show Severity;
import 'package:kernel/ast.dart'; import 'package:kernel/ast.dart';
import 'package:kernel/class_hierarchy.dart'; import 'package:kernel/class_hierarchy.dart';
import 'package:kernel/core_types.dart'; import 'package:kernel/core_types.dart';
import 'package:kernel/verifier.dart' show VerificationStage; import 'package:kernel/verifier.dart' show VerificationStage;
import 'package:macros/src/bootstrap.dart';
import 'package:macros/src/executor/kernel_executor.dart' as kernelExecutor;
import 'package:macros/src/executor/multi_executor.dart';
import 'package:macros/src/executor/serialization.dart';
import 'api_prototype/file_system.dart' show FileSystem; import 'api_prototype/file_system.dart' show FileSystem;
import 'api_prototype/front_end.dart' show CompilerOptions, CompilerResult; import 'api_prototype/front_end.dart' show CompilerOptions, CompilerResult;

View File

@ -12,6 +12,7 @@ environment:
dependencies: dependencies:
_fe_analyzer_shared: any _fe_analyzer_shared: any
kernel: any kernel: any
macros: any
package_config: any package_config: any
vm: any vm: any

View File

@ -94,12 +94,15 @@ Future<bool> main() async {
Set<Uri> vmModularUris = new Set<Uri>(); Set<Uri> vmModularUris = new Set<Uri>();
Set<Uri> feAnalyzerSharedUris = new Set<Uri>(); Set<Uri> feAnalyzerSharedUris = new Set<Uri>();
Set<Uri> dartPlatformUris = new Set<Uri>(); Set<Uri> dartPlatformUris = new Set<Uri>();
Set<Uri> macrosUris = new Set<Uri>();
Uri kernelUri = repoDir.resolve("pkg/kernel/"); Uri kernelUri = repoDir.resolve("pkg/kernel/");
Uri vmModularUri = repoDir.resolve("pkg/vm/lib/modular/"); Uri vmModularUri = repoDir.resolve("pkg/vm/lib/modular/");
Uri feAnalyzerSharedUri = repoDir.resolve("pkg/_fe_analyzer_shared/"); Uri feAnalyzerSharedUri = repoDir.resolve("pkg/_fe_analyzer_shared/");
Uri platformUri1 = repoDir.resolve("sdk/lib/"); Uri platformUri1 = repoDir.resolve("sdk/lib/");
Uri platformUri2 = repoDir.resolve("runtime/lib/"); Uri platformUri2 = repoDir.resolve("runtime/lib/");
Uri platformUri3 = repoDir.resolve("runtime/bin/"); Uri platformUri3 = repoDir.resolve("runtime/bin/");
Uri macrosUri = repoDir.resolve("pkg/macros");
Uri _macrosUri = repoDir.resolve("pkg/_macros");
for (Uri uri in result) { for (Uri uri in result) {
if (uri.toString().startsWith(frontendLibUri.toString())) { if (uri.toString().startsWith(frontendLibUri.toString())) {
frontEndUris.add(uri); frontEndUris.add(uri);
@ -114,6 +117,9 @@ Future<bool> main() async {
uri.toString().startsWith(platformUri2.toString()) || uri.toString().startsWith(platformUri2.toString()) ||
uri.toString().startsWith(platformUri3.toString())) { uri.toString().startsWith(platformUri3.toString())) {
dartPlatformUris.add(uri); dartPlatformUris.add(uri);
} else if (uri.toString().startsWith(_macrosUri.toString()) ||
uri.toString().startsWith(macrosUri.toString())) {
macrosUris.add(uri);
} else if (uri.toString().endsWith(".dart")) { } else if (uri.toString().endsWith(".dart")) {
otherDartUris.add(uri); otherDartUris.add(uri);
} else { } else {

View File

@ -16,8 +16,12 @@
"languageVersion": "2.12" "languageVersion": "2.12"
}, },
{ {
"name": "_fe_analyzer_shared", "name": "macros",
"rootUri": "../../../../../_fe_analyzer_shared/lib/" "rootUri": "../../../../../macros/lib/"
},
{
"name": "_macros",
"rootUri": "../../../../../_macros/lib/"
} }
] ]
} }

Some files were not shown because too many files have changed in this diff Show More