1
0
mirror of https://github.com/dart-lang/sdk synced 2024-06-29 06:15:22 +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=*
# 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
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:typed_data';
import 'package:_fe_analyzer_shared/src/macros/executor/message_grouper.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart';
import 'message_grouper.dart';
import 'byte_data_serializer.dart';
/// Channel for exchanging requests and responses over [Socket].
class RequestChannel {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -139,8 +139,7 @@ sealed class TypeAnnotationCode implements Code, TypeAnnotation {
/// of this one.
///
/// Returns the current instance if it is already nullable.
NullableTypeAnnotationCode get asNullable =>
new NullableTypeAnnotationCode(this);
NullableTypeAnnotationCode get asNullable => NullableTypeAnnotationCode(this);
/// Whether or not this type is nullable.
@override
@ -352,8 +351,7 @@ final class RawTypeAnnotationCode extends RawCode
///
/// Returns the current instance if it is already nullable.
@override
NullableTypeAnnotationCode get asNullable =>
new NullableTypeAnnotationCode(this);
NullableTypeAnnotationCode get asNullable => NullableTypeAnnotationCode(this);
RawTypeAnnotationCode._(super.parts) : super.fromParts();
@ -368,7 +366,7 @@ final class RawTypeAnnotationCode extends RawCode
static TypeAnnotationCode fromParts(List<Object> parts) {
bool wasNullable;
(wasNullable, parts) = _makeNonNullable(parts);
TypeAnnotationCode code = new RawTypeAnnotationCode._(parts);
TypeAnnotationCode code = RawTypeAnnotationCode._(parts);
if (wasNullable) code = code.asNullable;
return code;
}
@ -394,7 +392,7 @@ final class RawTypeAnnotationCode extends RawCode
switch (current) {
case String():
if (current.trimRight() != current) {
throw new ArgumentError(
throw ArgumentError(
'Invalid type annotation, type annotations should not end with '
'whitespace but got `$current`.');
} else if (current.isEmpty) {
@ -421,7 +419,7 @@ final class RawTypeAnnotationCode extends RawCode
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,
{List<DiagnosticMessage> contextMessages = const [],
this.correctionMessage})
: contextMessages = new UnmodifiableListView(contextMessages);
: contextMessages = UnmodifiableListView(contextMessages);
}
/// A message and optional target for a [Diagnostic] reported by a [Macro].
@ -60,7 +60,7 @@ final class DeclarationDiagnosticTarget extends DiagnosticTarget {
/// [Declaration].
extension DeclarationAsTarget on Declaration {
DeclarationDiagnosticTarget get asDiagnosticTarget =>
new DeclarationDiagnosticTarget(this);
DeclarationDiagnosticTarget(this);
}
/// A [DiagnosticMessage] target which is a [TypeAnnotation].
@ -74,7 +74,7 @@ final class TypeAnnotationDiagnosticTarget extends DiagnosticTarget {
/// [TypeAnnotation].
extension TypeAnnotationAsTarget on TypeAnnotation {
TypeAnnotationDiagnosticTarget get asDiagnosticTarget =>
new TypeAnnotationDiagnosticTarget(this);
TypeAnnotationDiagnosticTarget(this);
}
/// A [DiagnosticMessage] target which is a [MetadataAnnotation].
@ -86,7 +86,7 @@ final class MetadataAnnotationDiagnosticTarget extends DiagnosticTarget {
extension MetadataAnnotationAsTarget on MetadataAnnotation {
MetadataAnnotationDiagnosticTarget get asDiagnosticTarget =>
new MetadataAnnotationDiagnosticTarget(this);
MetadataAnnotationDiagnosticTarget(this);
}
/// The severities supported for [Diagnostic]s.

View File

@ -16,8 +16,8 @@ import 'executor/serialization.dart'
String bootstrapMacroIsolate(
Map<String, Map<String, List<String>>> macroDeclarations,
SerializationMode serializationMode) {
StringBuffer imports = new StringBuffer();
StringBuffer constructorEntries = new StringBuffer();
StringBuffer imports = StringBuffer();
StringBuffer constructorEntries = StringBuffer();
macroDeclarations
.forEach((String macroImport, Map<String, List<String>> macroClasses) {
imports.writeln('import \'$macroImport\';');
@ -47,8 +47,8 @@ const String template = '''
import 'dart:io';
import 'dart:isolate';
import 'package:_fe_analyzer_shared/src/macros/executor/client.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart';
import 'package:_macros/src/executor/client.dart';
import 'package:_macros/src/executor/serialization.dart';
$_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
// BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/executor/serialization_extensions.dart';
import 'package:meta/meta.dart';
import 'executor/serialization_extensions.dart';
import 'api.dart';
// ignore: unused_import
import 'bootstrap.dart'; // For doc comments only.
import 'executor/cast.dart';
import 'executor/introspection_impls.dart';
import 'executor/serialization.dart';

View File

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

View File

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

View File

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

View File

@ -2,8 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:meta/meta.dart';
/// Enables building up dynamic schemas with deep casts.
///
/// 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
/// override this method, and no other methods.
@mustBeOverridden
T _cast(Object? from) => from is T
? from
: throw new FailedCast(
: throw FailedCast(
'expected type $T but got type ${from.runtimeType} for: $from');
@nonVirtual
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
/// static knowledge or type inference.
@ -33,7 +29,6 @@ class Cast<T> {
/// Cast<dynamic> x = Cast<int>();
/// final y = x.getAsTypedCast(<T>(_) => Cast<Foo<T>>());
/// print(y.runtimeType); // Cast<Foo<int>>
@nonVirtual
R getAsTypedCast<R>(R Function<CastType>(Cast<CastType> self) callback) =>
callback<T>(this);
}
@ -71,7 +66,7 @@ class MapCast<K, V> extends Cast<Map<K, V>> {
static MapCast<Object?, Object?> from(
Cast<Object?> keyCast, Cast<Object?> valueCast) =>
keyCast.getAsTypedCast(<K>(keyCast) => valueCast.getAsTypedCast(
<V>(valueCast) => new MapCast<K, V>._(keyCast, valueCast)));
<V>(valueCast) => MapCast<K, V>._(keyCast, valueCast)));
@override
Map<K, V> _cast(Object? from) {
@ -106,7 +101,7 @@ class ListCast<E> extends Cast<List<E>> {
if (from is! List) {
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:typed_data';
import 'package:_fe_analyzer_shared/src/macros/api.dart';
import 'package:_fe_analyzer_shared/src/macros/executor.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/exception_impls.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/execute_macro.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/message_grouper.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/protocol.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/remote_instance.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/response_impls.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart';
import '../api.dart';
import '../executor.dart';
import 'exception_impls.dart';
import 'execute_macro.dart';
import 'message_grouper.dart';
import 'protocol.dart';
import 'remote_instance.dart';
import 'response_impls.dart';
import 'serialization.dart';
/// Implements the client side of the macro instantiation/expansion protocol.
final class MacroExpansionClient {
@ -57,7 +57,7 @@ final class MacroExpansionClient {
int? socketPort;
if (arguments.isNotEmpty) {
if (arguments.length != 2) {
throw new ArgumentError(
throw ArgumentError(
'Expected exactly two or zero arguments, got $arguments.');
}
socketAddress = arguments.first;
@ -65,7 +65,7 @@ final class MacroExpansionClient {
}
if (sendPort != null) {
ReceivePort receivePort = new ReceivePort();
ReceivePort receivePort = ReceivePort();
messageStream = receivePort;
sendResult =
(Serializer serializer) => _sendIsolateResult(serializer, sendPort);
@ -85,20 +85,20 @@ final class MacroExpansionClient {
inputStream = stdin;
}
if (serializationMode == SerializationMode.byteData) {
messageStream = new MessageGrouper(inputStream).messageStream;
messageStream = MessageGrouper(inputStream).messageStream;
} else if (serializationMode == SerializationMode.json) {
messageStream = const Utf8Decoder()
.bind(inputStream)
.transform(const LineSplitter())
.map((line) => jsonDecode(line)!);
} else {
throw new UnsupportedError(
throw UnsupportedError(
'Unsupported serialization mode $serializationMode for '
'ProcessExecutor');
}
}
return new MacroExpansionClient._(
return MacroExpansionClient._(
sendResult, messageStream, macroConstructors);
});
}
@ -116,49 +116,47 @@ final class MacroExpansionClient {
Deserializer deserializer = deserializerFactory(message)..moveNext();
int zoneId = deserializer.expectInt();
await withRemoteInstanceZone(zoneId, () async {
deserializer..moveNext();
deserializer.moveNext();
MessageType type = MessageType.values[deserializer.expectInt()];
Serializer serializer = serializerFactory();
switch (type) {
case MessageType.instantiateMacroRequest:
InstantiateMacroRequest request =
new InstantiateMacroRequest.deserialize(deserializer, zoneId);
InstantiateMacroRequest.deserialize(deserializer, zoneId);
(await _instantiateMacro(request)).serialize(serializer);
case MessageType.disposeMacroRequest:
DisposeMacroRequest request =
new DisposeMacroRequest.deserialize(deserializer, zoneId);
DisposeMacroRequest.deserialize(deserializer, zoneId);
_macroInstances.remove(request.identifier);
return;
case MessageType.executeDeclarationsPhaseRequest:
ExecuteDeclarationsPhaseRequest request =
new ExecuteDeclarationsPhaseRequest.deserialize(
deserializer, zoneId);
ExecuteDeclarationsPhaseRequest.deserialize(deserializer, zoneId);
(await _executeDeclarationsPhase(request, sendRequest))
.serialize(serializer);
case MessageType.executeDefinitionsPhaseRequest:
ExecuteDefinitionsPhaseRequest request =
new ExecuteDefinitionsPhaseRequest.deserialize(
deserializer, zoneId);
ExecuteDefinitionsPhaseRequest.deserialize(deserializer, zoneId);
(await _executeDefinitionsPhase(request, sendRequest))
.serialize(serializer);
case MessageType.executeTypesPhaseRequest:
ExecuteTypesPhaseRequest request =
new ExecuteTypesPhaseRequest.deserialize(deserializer, zoneId);
ExecuteTypesPhaseRequest.deserialize(deserializer, zoneId);
(await _executeTypesPhase(request, sendRequest))
.serialize(serializer);
case MessageType.response:
SerializableResponse response =
new SerializableResponse.deserialize(deserializer, zoneId);
SerializableResponse.deserialize(deserializer, zoneId);
_responseCompleters.remove(response.requestId)!.complete(response);
return;
case MessageType.destroyRemoteInstanceZoneRequest:
DestroyRemoteInstanceZoneRequest request =
new DestroyRemoteInstanceZoneRequest.deserialize(
DestroyRemoteInstanceZoneRequest.deserialize(
deserializer, zoneId);
destroyRemoteInstanceZone(request.serializationZoneId);
return;
default:
throw new StateError('Unhandled event type $type');
throw StateError('Unhandled event type $type');
}
sendResult(serializer);
}, createIfMissing: true);
@ -170,14 +168,14 @@ final class MacroExpansionClient {
try {
Map<String, Map<String, Function>> classes =
_macroConstructors[request.library] ??
(throw new ArgumentError(
(throw ArgumentError(
'Unrecognized macro library ${request.library}'));
Map<String, Function> constructors = classes[request.name] ??
(throw new ArgumentError(
(throw ArgumentError(
'Unrecognized macro class ${request.name} for library '
'${request.library}'));
Function constructor = constructors[request.constructor] ??
(throw new ArgumentError(
(throw ArgumentError(
'Unrecognized constructor name "${request.constructor}" for '
'macro class "${request.name}".'));
@ -186,20 +184,20 @@ final class MacroExpansionClient {
], {
for (MapEntry<String, Argument> entry
in request.arguments.named.entries)
new Symbol(entry.key): entry.value.value,
Symbol(entry.key): entry.value.value,
}) as Macro;
MacroInstanceIdentifierImpl identifier =
new MacroInstanceIdentifierImpl(instance, request.instanceId);
MacroInstanceIdentifierImpl(instance, request.instanceId);
_macroInstances[identifier] = instance;
return new SerializableResponse(
return SerializableResponse(
responseType: MessageType.macroInstanceIdentifier,
response: identifier,
requestId: request.id,
serializationZoneId: request.serializationZoneId);
} catch (e, s) {
return new SerializableResponse(
return SerializableResponse(
responseType: MessageType.exception,
exception: new MacroExceptionImpl.from(e, s),
exception: MacroExceptionImpl.from(e, s),
requestId: request.id,
serializationZoneId: request.serializationZoneId);
}
@ -210,24 +208,24 @@ final class MacroExpansionClient {
Future<Response> Function(Request request) sendRequest) async {
try {
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)'));
TypePhaseIntrospector introspector = new ClientTypePhaseIntrospector(
TypePhaseIntrospector introspector = ClientTypePhaseIntrospector(
sendRequest,
remoteInstance: request.introspector,
serializationZoneId: request.serializationZoneId);
MacroExecutionResult result =
await executeTypesMacro(instance, request.target, introspector);
return new SerializableResponse(
return SerializableResponse(
responseType: MessageType.macroExecutionResult,
response: result,
requestId: request.id,
serializationZoneId: request.serializationZoneId);
} catch (e, s) {
return new SerializableResponse(
return SerializableResponse(
responseType: MessageType.exception,
exception: new MacroExceptionImpl.from(e, s),
exception: MacroExceptionImpl.from(e, s),
requestId: request.id,
serializationZoneId: request.serializationZoneId);
}
@ -238,25 +236,25 @@ final class MacroExpansionClient {
Future<Response> Function(Request request) sendRequest) async {
try {
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)'));
DeclarationPhaseIntrospector introspector =
new ClientDeclarationPhaseIntrospector(sendRequest,
ClientDeclarationPhaseIntrospector(sendRequest,
remoteInstance: request.introspector,
serializationZoneId: request.serializationZoneId);
MacroExecutionResult result = await executeDeclarationsMacro(
instance, request.target, introspector);
return new SerializableResponse(
return SerializableResponse(
responseType: MessageType.macroExecutionResult,
response: result,
requestId: request.id,
serializationZoneId: request.serializationZoneId);
} catch (e, s) {
return new SerializableResponse(
return SerializableResponse(
responseType: MessageType.exception,
exception: new MacroExceptionImpl.from(e, s),
exception: MacroExceptionImpl.from(e, s),
requestId: request.id,
serializationZoneId: request.serializationZoneId);
}
@ -267,24 +265,24 @@ final class MacroExpansionClient {
Future<Response> Function(Request request) sendRequest) async {
try {
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)'));
DefinitionPhaseIntrospector introspector =
new ClientDefinitionPhaseIntrospector(sendRequest,
ClientDefinitionPhaseIntrospector(sendRequest,
remoteInstance: request.introspector,
serializationZoneId: request.serializationZoneId);
MacroExecutionResult result =
await executeDefinitionMacro(instance, request.target, introspector);
return new SerializableResponse(
return SerializableResponse(
responseType: MessageType.macroExecutionResult,
response: result,
requestId: request.id,
serializationZoneId: request.serializationZoneId);
} catch (e, s) {
return new SerializableResponse(
return SerializableResponse(
responseType: MessageType.exception,
exception: new MacroExceptionImpl.from(e, s),
exception: MacroExceptionImpl.from(e, s),
requestId: request.id,
serializationZoneId: request.serializationZoneId);
}
@ -294,7 +292,7 @@ final class MacroExpansionClient {
/// in [_responseCompleters] to handle the response.
Future<Response> _sendRequest(
Request request, void Function(Serializer serializer) sendResult) {
Completer<Response> completer = new Completer();
Completer<Response> completer = Completer();
_responseCompleters[request.id] = completer;
Serializer serializer = serializerFactory();
serializer.addInt(request.serializationZoneId);
@ -308,8 +306,8 @@ final class MacroExpansionClient {
/// [TransferableTypedData] object.
void _sendIsolateResult(Serializer serializer, SendPort sendPort) {
if (serializationMode == SerializationMode.byteData) {
sendPort.send(
new TransferableTypedData.fromList([serializer.result as Uint8List]));
sendPort
.send(TransferableTypedData.fromList([serializer.result as Uint8List]));
} else {
sendPort.send(serializer.result);
}
@ -326,7 +324,7 @@ void Function(Serializer) _sendIOSinkResultFactory(IOSink sink) =>
} else if (serializationMode == SerializationMode.byteData) {
Uint8List result = (serializer as ByteDataSerializer).result;
int length = result.lengthInBytes;
BytesBuilder bytesBuilder = new BytesBuilder(copy: false);
BytesBuilder bytesBuilder = BytesBuilder(copy: false);
bytesBuilder.add([
length >> 24 & 0xff,
length >> 16 & 0xff,
@ -336,7 +334,7 @@ void Function(Serializer) _sendIOSinkResultFactory(IOSink sink) =>
bytesBuilder.add(result);
sink.add(bytesBuilder.takeBytes());
} else {
throw new UnsupportedError(
throw UnsupportedError(
'Unsupported serialization mode $serializationMode for '
'ProcessExecutor');
}

View File

@ -35,17 +35,17 @@ abstract base class MacroExceptionImpl extends RemoteInstance
String? stackTrace}) {
switch (kind) {
case RemoteInstanceKind.unexpectedMacroException:
return new UnexpectedMacroExceptionImpl(message,
return UnexpectedMacroExceptionImpl(message,
id: id, stackTrace: stackTrace);
case RemoteInstanceKind.macroImplementationException:
return new MacroImplementationExceptionImpl(message,
return MacroImplementationExceptionImpl(message,
id: id, stackTrace: stackTrace);
case RemoteInstanceKind.macroIntrospectionCycleException:
return new MacroIntrospectionCycleExceptionImpl(message,
return MacroIntrospectionCycleExceptionImpl(message,
id: id, stackTrace: stackTrace);
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].
factory MacroExceptionImpl.from(Object throwable, StackTrace stackTrace) {
if (throwable is MacroExceptionImpl) return throwable;
return new UnexpectedMacroExceptionImpl(throwable.toString(),
return UnexpectedMacroExceptionImpl(throwable.toString(),
stackTrace: stackTrace.toString());
}

View File

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

View File

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

View File

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

View File

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

View File

@ -4,8 +4,9 @@
import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import '../../util/runtimes.dart' as runtimes;
import '../executor.dart';
import '../executor/serialization.dart';
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.
Future<MacroExecutor> start(SerializationMode serializationMode, Uri uriToSpawn,
{List<String> arguments = const [], Uri? packageConfigUri}) {
if (runtimes.isKernelRuntime) {
if (_isKernelRuntime) {
return isolated_executor.start(serializationMode, uriToSpawn,
arguments: arguments, packageConfigUri: packageConfigUri);
}
// Not running on the JIT, assume `dartaotruntime` or some other executable
// in the SDK `bin` folder.
File dartAotRuntime = new File(Platform.resolvedExecutable);
File dartAotRuntime = File(Platform.resolvedExecutable);
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())
.toList();
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 "
'${dartAotRuntime.path}.');
}
@ -45,3 +46,22 @@ Future<MacroExecutor> start(SerializationMode serializationMode, Uri uriToSpawn,
dartExecutables.first.path,
['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
/// 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.
final Map<Uri, ExecutorFactoryToken> _libraryExecutorFactories = {};
@ -37,11 +37,11 @@ class MultiMacroExecutor extends MacroExecutor with AugmentationLibraryBuilder {
/// this way via [unregisterExecutorFactory].
ExecutorFactoryToken registerExecutorFactory(
FutureOr<MacroExecutor> Function() factory, Set<Uri> libraries) {
ExecutorFactoryToken token = new ExecutorFactoryToken._(factory, libraries);
ExecutorFactoryToken token = ExecutorFactoryToken._(factory, libraries);
_executorFactoryTokens.add(token);
for (Uri library in libraries) {
if (_libraryExecutorFactories.containsKey(library)) {
throw new ArgumentError(
throw ArgumentError(
'Attempted to register a macro executor factory for library '
'$library which already has one assigned.');
}
@ -127,8 +127,7 @@ class MultiMacroExecutor extends MacroExecutor with AugmentationLibraryBuilder {
Uri library, String name, String constructor, Arguments arguments) {
ExecutorFactoryToken? token = _libraryExecutorFactories[library];
if (token == null) {
throw new ArgumentError(
'No executor registered to run macros from $library');
throw ArgumentError('No executor registered to run macros from $library');
}
return token._withInstance((executor) async {
MacroInstanceIdentifier instance = await executor.instantiateMacro(

View File

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

View File

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

View File

@ -4,8 +4,6 @@
import 'dart:async';
import 'package:meta/meta.dart';
import 'serialization.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
/// implement [serializeUncached].
@override
@nonVirtual
void serialize(Serializer serializer) {
serializer.addInt(id);
// 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
/// super classes to have their own implementations for their fields.
@mustCallSuper
void serializeUncached(Serializer serializer) {
serializer.addInt(kind.index);
@ -77,6 +73,9 @@ abstract class RemoteInstance implements Serializable {
@override
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
@ -164,7 +163,7 @@ T withRemoteInstanceZone<T>(int zoneId, T Function() fn,
Zone? zone = _remoteInstanceCacheZones[zoneId];
if (zone == null) {
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: {
_remoteInstanceZoneCacheKey: <int, RemoteInstance>{},
@ -180,7 +179,7 @@ T withRemoteInstanceZone<T>(int zoneId, T Function() fn,
void destroyRemoteInstanceZone(int zoneId) {
final Zone? zone = _remoteInstanceCacheZones.remove(zoneId);
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();
}
@ -194,8 +193,8 @@ const Symbol _remoteInstanceZoneCacheKey = #_remoteInstanceCache;
/// These are a part of the current remote instance cache zone, which all
/// serialization and deserialization of remote instances must be done in.
Map<int, RemoteInstance> get _remoteInstanceCache =>
Zone.current[_remoteInstanceZoneCacheKey] ??
(throw new StateError('Not running in a remote instance cache zone, call '
Zone.current[_remoteInstanceZoneCacheKey] as Map<int, RemoteInstance>? ??
(throw StateError('Not running in a remote instance cache zone, call '
'`withRemoteInstanceZone` to set one up.'));
/// 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)
@ -400,7 +400,7 @@ class MacroExecutionResultImpl implements MacroExecutionResult {
]
};
return new MacroExecutionResultImpl(
return MacroExecutionResultImpl(
diagnostics: diagnostics,
exception: exception,
enumValueAugmentations: enumValueAugmentations,

View File

@ -134,7 +134,7 @@ class JsonSerializer implements Serializer {
final _result = <Object?>[];
/// 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].
///
@ -186,7 +186,7 @@ class JsonDeserializer implements Deserializer {
final Iterable<Object?> _source;
/// 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.
bool _initialized = false;
@ -223,12 +223,11 @@ class JsonDeserializer implements Deserializer {
/// Reads the current value and casts it to [T].
T _expectValue<T>() {
if (!_initialized) {
throw new StateError(
'You must call `moveNext()` before reading any values.');
throw StateError('You must call `moveNext()` before reading any values.');
}
Object? current = _path.last.current;
if (current is! T) {
throw new StateError('Expected $T, got: ${_path.last.current}');
throw StateError('Expected $T, got: ${_path.last.current}');
}
return current;
}
@ -252,12 +251,11 @@ class JsonDeserializer implements Deserializer {
}
class ByteDataSerializer extends Serializer {
final BytesBuilder _builder = new BytesBuilder();
final BytesBuilder _builder = 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);
final Uint8List _eightByteList = Uint8List(8);
late final ByteData _eightByteListData = ByteData.sublistView(_eightByteList);
@override
void addBool(bool value) => _builder
@ -279,7 +277,7 @@ class ByteDataSerializer extends Serializer {
if (value >= 0x0) {
assert(DataKind.values.length < 0xff);
if (value <= 0xff - DataKind.values.length) {
_builder..addByte(value + DataKind.values.length);
_builder.addByte(value + DataKind.values.length);
} else if (value <= 0xff) {
_builder
..addByte(DataKind.uint8.index)
@ -423,7 +421,7 @@ class ByteDataSerializer extends Serializer {
}
endMap();
} 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) {
return false;
} 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() {
DataKind kind = _readKind();
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;
return _bytes.getFloat64(_byteOffset + 1);
@ -522,7 +520,7 @@ class ByteDataDeserializer extends Deserializer {
_byteOffsetIncrement = 8 + offset;
break;
default:
throw new StateError('Expected an int but found a $kind');
throw StateError('Expected an int but found a $kind');
}
return result;
}
@ -531,7 +529,7 @@ class ByteDataDeserializer extends Deserializer {
void expectList() {
DataKind kind = _readKind();
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;
}
@ -557,7 +555,7 @@ class ByteDataDeserializer extends Deserializer {
void expectMap() {
DataKind kind = _readKind();
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;
}
@ -569,16 +567,15 @@ class ByteDataDeserializer extends Deserializer {
int offset = _byteOffsetIncrement! + _byteOffset;
if (kind == DataKind.oneByteString) {
_byteOffsetIncrement = _byteOffsetIncrement! + length;
return new String.fromCharCodes(
_bytes.buffer.asUint8List(offset, length));
return 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());
Uint8List.fromList(_bytes.buffer.asUint8List(offset, length));
return String.fromCharCodes(bytes.buffer.asUint16List());
} 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) {
return expectUint8List();
} else {
throw new StateError('Expected: $kind');
throw StateError('Expected: $kind');
}
}
@ -656,7 +653,7 @@ class ByteDataDeserializer extends Deserializer {
int? increment = _byteOffsetIncrement;
_byteOffsetIncrement = 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;
if (_byteOffset >= _bytes.lengthInBytes) {
@ -701,7 +698,7 @@ SerializationMode get serializationMode {
SerializationMode? mode =
Zone.current[#serializationMode] as SerializationMode?;
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`.');
}
return mode;
@ -711,10 +708,9 @@ SerializationMode get serializationMode {
Deserializer Function(Object?) get deserializerFactory =>
switch (serializationMode) {
SerializationMode.byteData => (Object? message) =>
new ByteDataDeserializer(
new ByteData.sublistView(message as Uint8List)),
ByteDataDeserializer(ByteData.sublistView(message as Uint8List)),
SerializationMode.json => (Object? message) =>
new JsonDeserializer(message as Iterable<Object?>),
JsonDeserializer(message as Iterable<Object?>),
};
/// Returns the current serializer factory for the zone.
@ -732,7 +728,7 @@ enum SerializationMode {
factory SerializationMode.fromOption(String option) => switch (option) {
'json' => SerializationMode.json,
'bytedata' => SerializationMode.byteData,
_ => throw new ArgumentError('Unrecognized macro serialization mode '
_ => throw ArgumentError('Unrecognized macro serialization mode '
'$option'),
};
}

View File

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

View File

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

View File

@ -1,5 +1,5 @@
name: _macros
version: 0.0.1
version: 0.1.0
description: >-
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
@ -9,3 +9,8 @@ repository: https://github.com/dart-lang/sdk/tree/main/pkg/_macros
environment:
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
// 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/test.dart';
import 'package:_fe_analyzer_shared/src/macros/executor.dart';
import 'package:_fe_analyzer_shared/src/macros/api.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/augmentation_library.dart';
import 'package:_fe_analyzer_shared/src/macros/executor/response_impls.dart';
import 'package:_macros/src/api.dart';
import 'package:_macros/src/executor.dart';
import 'package:_macros/src/executor/augmentation_library.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';

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -26,7 +26,7 @@ mixin TestMacros on ConfigurationFilesMixin {
[
'''
// 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
].join('\n'),

View File

@ -5,7 +5,6 @@
import 'dart:collection';
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/ast/syntactic_entity.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/string.dart';
import 'package:collection/collection.dart';
import 'package:macros/macros.dart' as macro;
class EnclosingExecutableContext {
final ExecutableElement? element;

View File

@ -4,7 +4,6 @@
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/element/element.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/string.dart';
import 'package:analyzer/src/utilities/uri_cache.dart';
import 'package:macros/macros.dart' as macro;
import 'package:pub_semver/pub_semver.dart';
class BundleReader {

View File

@ -4,7 +4,6 @@
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/executor.dart' as macro;
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/element/element.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/utilities/extensions/collection.dart';
import 'package:analyzer/src/utilities/extensions/object.dart';
import 'package:macros/src/executor.dart' as macro;
class AugmentedClassDeclarationBuilder
extends AugmentedInstanceDeclarationBuilder {

View File

@ -4,8 +4,6 @@
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/ast/ast.dart' as ast;
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/util/performance/operation_performance.dart';
import 'package:analyzer/src/utilities/uri_cache.dart';
import 'package:macros/src/executor/multi_executor.dart' as macro;
Future<LinkResult> link({
required LinkedElementFactory elementFactory,

View File

@ -6,17 +6,14 @@ import 'dart:io' as io;
import 'dart:isolate';
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: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: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
// 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/element/element.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/object.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';
/// 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
// 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/summary2/macro_type_location.dart';
import 'package:macros/macros.dart' as macro;
/// Base for all macro related diagnostics.
sealed class AnalyzerMacroDiagnostic {}

View File

@ -2,14 +2,6 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:_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/element/element.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/object.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
implements HasElement {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,7 +4,7 @@
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
/// phase, so that any omitted types are written into the augmentation.

View File

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

View File

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

View File

@ -7,7 +7,7 @@
// ignore_for_file: deprecated_member_use_from_same_package
// 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');
@ -639,7 +639,8 @@ extension on FieldDeclaration {
for (var annotation in metadata) {
if (annotation is! ConstructorMetadataAnnotation) 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 (jsonKey != null) {

View File

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

View File

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

View File

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

View File

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

View File

@ -2,7 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:_fe_analyzer_shared/src/macros/api.dart';
import 'package:macros/macros.dart';
/*macro*/ class IsExactly implements FunctionDefinitionMacro {
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 packageRoot = physical.pathContext.normalize(package_root.packageRoot);
physical
.getFolder(packageRoot)
.getChildAssumingFolder('_fe_analyzer_shared/lib/src/macros')
.copyTo(
packageSharedFolder.getChildAssumingFolder('lib/src'),
physical.getFolder(packageRoot).getChildAssumingFolder('_macros').copyTo(
privateMacrosFolder.parent,
);
physical
.getFolder(packageRoot)
.getChildAssumingFolder('dart_internal')
.copyTo(
_resourceProvider.getFolder('/packages'),
physical.getFolder(packageRoot).getChildAssumingFolder('macros').copyTo(
publicMacrosFolder.parent,
);
packageAnalyzerFolder =
physical.getFolder(packageRoot).getChildAssumingFolder('analyzer');
}
Folder get packageDartInternalFolder {
return _resourceProvider.getFolder('/packages/dart_internal');
Folder get privateMacrosFolder {
return _resourceProvider.getFolder('/packages/_macros');
}
Folder get packageSharedFolder {
return _resourceProvider.getFolder('/packages/_fe_analyzer_shared');
Folder get publicMacrosFolder {
return _resourceProvider.getFolder('/packages/macros');
}
}

View File

@ -166,7 +166,7 @@ const simpleBreakpointProgram = '''
/// `hello()` method to a class that prints "Hello".
const withHelloMacroImplementation = '''
// 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 {
const WithHello();

View File

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

View File

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

View File

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

View File

@ -4,9 +4,6 @@
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'
show DiagnosticMessage, DiagnosticMessageHandler;
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
show defaultLanguageVersion;
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 '../base/nnbd_mode.dart';

View File

@ -5,13 +5,12 @@
/// 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.
import 'package:_fe_analyzer_shared/src/macros/executor/serialization.dart'
show SerializationMode;
import 'package:_fe_analyzer_shared/src/messages/diagnostic_message.dart'
show DiagnosticMessageHandler;
import 'package:front_end/src/api_prototype/compiler_options.dart';
import 'package:kernel/kernel.dart' show Component, Library, dummyComponent;
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/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
// 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'
show DiagnosticMessageHandler;
import 'package:kernel/class_hierarchy.dart';
import 'package:kernel/kernel.dart' show Component, Library;
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/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
// 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/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/experimental_flags.dart' show ExperimentalFlag;

View File

@ -5,13 +5,6 @@
import 'dart:io' show exitCode;
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/util/libraries_specification.dart'
show
@ -28,6 +21,11 @@ import 'package:kernel/kernel.dart'
Version;
import 'package:kernel/target/targets.dart'
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 '../api_prototype/compiler_options.dart'

View File

@ -7,8 +7,7 @@ library fasta.incremental_compiler;
import 'dart:async' show Completer;
import 'dart:convert' show JsonEncoder;
import 'package:_fe_analyzer_shared/src/macros/executor/multi_executor.dart'
as macros;
import 'package:macros/src/executor/multi_executor.dart' as macros;
import 'package:_fe_analyzer_shared/src/scanner/abstract_scanner.dart'
show ScannerConfiguration;
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.
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/parser/parser.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
// 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: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:kernel/ast.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
// 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: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;
import 'package:kernel/ast.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
// 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/span.dart' as macro;
import 'package:macros/macros.dart' as macro;
import 'package:macros/src/executor.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/scanner/scanner.dart';
import 'package:front_end/src/fasta/uri_offset.dart';
@ -37,8 +37,7 @@ import 'offsets.dart';
const String intermediateAugmentationScheme = 'org-dartlang-augmentation';
final Uri macroLibraryUri =
Uri.parse('package:_fe_analyzer_shared/src/macros/api.dart');
final Uri macroLibraryUri = Uri.parse('package:_macros/src/api.dart');
const String macroClassName = 'Macro';
class MacroDeclarationData {

View File

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

View File

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

View File

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

View File

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

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