[cfe] Migrate (more) CFE tests

Change-Id: Id460b605bef0cff33c35771f0c2701818d687e0b
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/220201
Reviewed-by: Jens Johansen <jensj@google.com>
Commit-Queue: Johnni Winther <johnniwinther@google.com>
This commit is contained in:
Johnni Winther 2021-11-16 10:00:14 +00:00 committed by commit-bot@chromium.org
parent 8154fff6c0
commit f7815b26da
18 changed files with 209 additions and 251 deletions

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.
// @dart = 2.9
import 'dart:convert' show utf8;
import 'dart:io'
@ -56,7 +54,7 @@ final Uri repoDir = computeRepoDirUri();
Set<Uri> libUris = {};
Component component;
late Component component;
Future<void> main(List<String> args) async {
api.CompilerOptions compilerOptions = getOptions();
@ -100,8 +98,9 @@ Future<void> main(List<String> args) async {
List<Uri> editsPerformed = [];
for (Uri uri in edits.keys) {
print("\n\n\n");
if (edits[uri] != null && edits[uri].isNotEmpty) {
String update;
List<Edit>? theseEdits = edits[uri];
if (theseEdits != null && theseEdits.isNotEmpty) {
String? update;
while (update != "y" &&
update != "yes" &&
update != "n" &&
@ -111,9 +110,8 @@ Future<void> main(List<String> args) async {
}
if (update != "y" && update != "yes") continue;
List<Edit> theseEdits = edits[uri];
theseEdits.sort();
String content = utf8.decode(component.uriToSource[uri].source,
String content = utf8.decode(component.uriToSource[uri]!.source,
allowMalformed: true);
StringBuffer sb = new StringBuffer();
int latest = 0;
@ -128,7 +126,7 @@ Future<void> main(List<String> args) async {
case EditType.Delete:
print(edit);
// We "delete" by skipping...
latest = edit.offset + edit.length;
latest = edit.offset + edit.length!;
break;
}
}
@ -195,19 +193,19 @@ class InvocationVisitor extends RecursiveVisitor {
@override
void visitSuperMethodInvocation(SuperMethodInvocation node) {
super.visitSuperMethodInvocation(node);
note(node.interfaceTargetReference.node, node.arguments, node);
note(node.interfaceTargetReference!.node!, node.arguments, node);
}
@override
void visitStaticInvocation(StaticInvocation node) {
super.visitStaticInvocation(node);
note(node.targetReference.node, node.arguments, node);
note(node.targetReference.node!, node.arguments, node);
}
@override
void visitConstructorInvocation(ConstructorInvocation node) {
super.visitConstructorInvocation(node);
note(node.targetReference.node, node.arguments, node);
note(node.targetReference.node!, node.arguments, node);
}
void note(
@ -223,28 +221,25 @@ class InvocationVisitor extends RecursiveVisitor {
for (int i = 0; i < arguments.positional.length; i++) {
bool wantComment = false;
if (arguments.positional[i] is NullLiteral ||
arguments.positional[i] is BoolLiteral ||
arguments.positional[i] is IntLiteral) {
Expression argument = arguments.positional[i];
if (argument is NullLiteral ||
argument is BoolLiteral ||
argument is IntLiteral) {
wantComment = true;
} else if (arguments.positional[i] is MapLiteral) {
MapLiteral literal = arguments.positional[i];
if (literal.entries.isEmpty) wantComment = true;
} else if (arguments.positional[i] is ListLiteral) {
ListLiteral literal = arguments.positional[i];
if (literal.expressions.isEmpty) wantComment = true;
} else if (arguments.positional[i] is InstanceInvocation) {
InstanceInvocation methodInvocation = arguments.positional[i];
if (methodInvocation.receiver is NullLiteral ||
methodInvocation.receiver is IntLiteral ||
methodInvocation.receiver is BoolLiteral) {
} else if (argument is MapLiteral) {
if (argument.entries.isEmpty) wantComment = true;
} else if (argument is ListLiteral) {
if (argument.expressions.isEmpty) wantComment = true;
} else if (argument is InstanceInvocation) {
if (argument.receiver is NullLiteral ||
argument.receiver is IntLiteral ||
argument.receiver is BoolLiteral) {
wantComment = true;
}
} else if (arguments.positional[i] is DynamicInvocation) {
DynamicInvocation methodInvocation = arguments.positional[i];
if (methodInvocation.receiver is NullLiteral ||
methodInvocation.receiver is IntLiteral ||
methodInvocation.receiver is BoolLiteral) {
} else if (argument is DynamicInvocation) {
if (argument.receiver is NullLiteral ||
argument.receiver is IntLiteral ||
argument.receiver is BoolLiteral) {
wantComment = true;
}
}
@ -269,10 +264,10 @@ void check(
return;
}
if (argumentExpression.fileOffset == -1) return;
Location location = argumentExpression.location;
Token token = cache[location.file];
Location location = argumentExpression.location!;
Token token = cache[location.file]!;
while (token.offset != argumentExpression.fileOffset) {
token = token.next;
token = token.next!;
if (token.isEof) {
throw "Couldn't find token for $argumentExpression "
"(${argumentExpression.fileOffset}).";
@ -280,7 +275,7 @@ void check(
}
bool foundComment = false;
List<CommentToken> badComments = [];
CommentToken commentToken = token.precedingComments;
CommentToken? commentToken = token.precedingComments;
while (commentToken != null) {
if (commentToken.lexeme == expectedComment) {
// Exact match.
@ -291,17 +286,16 @@ void check(
commentToken.lexeme.endsWith("= */")) {
badComments.add(commentToken);
}
commentToken = commentToken.next;
commentToken = commentToken.next as CommentToken?;
}
if (badComments.isNotEmpty) {
for (CommentToken comment in badComments) {
Location calculatedLocation =
component.getLocation(location.file, comment.offset);
component.getLocation(location.file, comment.offset)!;
print("Please remove comment of length ${comment.lexeme.length} at "
"${comment.offset} => "
"${calculatedLocation}");
edits[location.file] ??= [];
edits[location.file]
(edits[location.file] ??= [])
.add(new Edit.delete(comment.offset, comment.lexeme.length));
}
}
@ -309,12 +303,12 @@ void check(
return;
}
Location calculatedLocation =
component.getLocation(location.file, token.offset);
component.getLocation(location.file, token.offset)!;
print("Please add comment $expectedComment at "
"${token.offset} => "
"${calculatedLocation}");
edits[location.file] ??= [];
edits[location.file].add(new Edit.insert(token.offset, expectedComment));
(edits[location.file] ??= [])
.add(new Edit.insert(token.offset, expectedComment));
}
Map<Uri, List<Edit>> edits = {};
@ -323,8 +317,8 @@ enum EditType { Insert, Delete }
class Edit implements Comparable<Edit> {
final int offset;
final int length;
final String insertData;
final int? length;
final String? insertData;
final EditType editType;
Edit.insert(this.offset, this.insertData)
: editType = EditType.Insert,

View file

@ -1,5 +1,3 @@
// @dart = 2.9
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
@ -23,7 +21,7 @@ final Uri benchmarkHelper =
Platform.script.resolve("compile_benchmark_helper.dart");
void main(List<String> args) {
List<String> arguments;
List<String>? arguments;
bool tryToAnnotate = false;
bool tryToSlowDown = false;
bool timeInsteadOfCount = false;
@ -135,7 +133,7 @@ void doWork(Directory tmp, List<int> dillData, List<String> arguments,
if (tryToSlowDown) {
didSomething = true;
for (Procedure p in sortedProcedures) {
Uri busyWaiting = busyWaitProcedure(
Uri? busyWaiting = busyWaitProcedure(
dillData,
tmp.uri,
(lib) => lib.importUri == p.enclosingLibrary.importUri,
@ -245,13 +243,14 @@ class IntPair {
///
/// The annotation is copied from the [preferInlineMe] method in the helper.
Uri preferInlineProcedure(List<int> dillData, Uri tmp,
bool libraryMatcher(Library lib), String className, String procedureName) {
bool libraryMatcher(Library lib), String? className, String procedureName) {
Component component = new Component();
new BinaryBuilder(dillData, disableLazyReading: true)
.readComponent(component);
Procedure preferInlineMeProcedure = getProcedure(component,
(lib) => lib.fileUri == benchmarkHelper, null, "preferInlineMe");
ConstantExpression annotation = preferInlineMeProcedure.annotations.single;
ConstantExpression annotation =
preferInlineMeProcedure.annotations.single as ConstantExpression;
Procedure markProcedure =
getProcedure(component, libraryMatcher, className, procedureName);
markProcedure.addAnnotation(
@ -268,8 +267,8 @@ Uri preferInlineProcedure(List<int> dillData, Uri tmp,
///
/// This will make the procedure busy-wait approximately 0.002 ms for each
/// invocation (+ whatever overhead and imprecision).
Uri busyWaitProcedure(List<int> dillData, Uri tmp,
bool libraryMatcher(Library lib), String className, String procedureName) {
Uri? busyWaitProcedure(List<int> dillData, Uri tmp,
bool libraryMatcher(Library lib), String? className, String procedureName) {
Component component = new Component();
new BinaryBuilder(dillData, disableLazyReading: true)
.readComponent(component);
@ -280,7 +279,7 @@ Uri busyWaitProcedure(List<int> dillData, Uri tmp,
getProcedure(component, libraryMatcher, className, procedureName);
if (markProcedure.function.body == null) return null;
Statement orgBody = markProcedure.function.body;
Statement orgBody = markProcedure.function.body as Statement;
markProcedure.function.body = new Block([
new ExpressionStatement(new StaticInvocation(
busyWaitProcedure, new Arguments([new IntLiteral(2 /* 0.002 ms */)]))),
@ -375,13 +374,13 @@ class RegisterCallTransformer extends RecursiveVisitor {
if (node.function.body == null) return;
int procedureNum = procedures.length;
procedures.add(node);
Statement orgBody = node.function.body;
Statement orgBody = node.function.body as Statement;
node.function.body = new Block([
new ExpressionStatement(new StaticInvocation(registerCallProcedure,
new Arguments([new IntLiteral(procedureNum)]))),
orgBody
]);
node.function.body.parent = node.function;
node.function.body!.parent = node.function;
}
}
@ -408,7 +407,7 @@ class RegisterTimeTransformer extends RecursiveVisitor {
if (node.function.dartAsyncMarker != AsyncMarker.Sync) return;
int procedureNum = procedures.length;
procedures.add(node);
Statement orgBody = node.function.body;
Statement orgBody = node.function.body as Statement;
// Rewrite as
// {
// registerCallStartProcedure(x);
@ -428,12 +427,12 @@ class RegisterTimeTransformer extends RecursiveVisitor {
)
]);
node.function.body = block;
node.function.body.parent = node.function;
node.function.body!.parent = node.function;
}
}
Procedure getProcedure(Component component, bool libraryMatcher(Library lib),
String className, String procedureName) {
String? className, String procedureName) {
Library lib = component.libraries.where(libraryMatcher).single;
List<Procedure> procedures = lib.procedures;
if (className != null) {
@ -444,7 +443,7 @@ Procedure getProcedure(Component component, bool libraryMatcher(Library lib),
return procedures.where((p) => p.name.text == procedureName).single;
}
List<int> runXTimes(int x, List<String> arguments, [List<dynamic> stdout]) {
List<int> runXTimes(int x, List<String> arguments, [List<dynamic>? stdout]) {
List<int> result = [];
Stopwatch stopwatch = new Stopwatch()..start();
for (int i = 0; i < x; i++) {

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.
// @dart = 2.9
import 'dart:convert' show jsonDecode;
import 'dart:io' show File;
@ -20,8 +18,8 @@ import 'crashing_test_case_minimizer_impl.dart';
// parser on it and verifies that no syntax errors have been introduced.
Future<void> main(List<String> arguments) async {
String filename;
Uri loadJson;
String? filename;
Uri? loadJson;
for (String arg in arguments) {
if (arg.startsWith("--json=")) {
String json = arg.substring("--json=".length);
@ -92,7 +90,7 @@ Future<void> main(List<String> arguments) async {
if (settings.noPlatform) {
int i = 0;
while (settings.platformUri == null ||
new File.fromUri(settings.platformUri).existsSync()) {
new File.fromUri(settings.platformUri!).existsSync()) {
settings.platformUri = Uri.base.resolve("nonexisting_$i");
i++;
}
@ -100,7 +98,7 @@ Future<void> main(List<String> arguments) async {
if (settings.platformUri == null) {
throw "No platform given. Use --platform=/path/to/platform.dill";
}
if (!new File.fromUri(settings.platformUri).existsSync()) {
if (!new File.fromUri(settings.platformUri!).existsSync()) {
throw "The platform file '${settings.platformUri}' doesn't exist";
}
}

View file

@ -1,5 +1,3 @@
// @dart = 2.9
import 'dart:convert';
import 'dart:typed_data';
@ -393,7 +391,7 @@ import 'foo.dart';
}
int expectCalls = 0;
String expectCategory;
String? expectCategory;
void expect(dynamic actual, dynamic expected) {
expectCalls++;
@ -461,23 +459,23 @@ bool _expectImpl(dynamic actual, dynamic expected, StringBuffer explainer) {
return false;
}
impl.CommentString extractFirstComment(String test) {
impl.CommentString? extractFirstComment(String test) {
Token firstToken = impl.scanRawBytes(utf8.encode(test) as Uint8List);
Token token = firstToken;
while (true) {
CommentToken comment = token.precedingComments;
CommentToken? comment = token.precedingComments;
if (comment != null) {
return impl.extractComments(comment, test);
}
if (token.isEof) break;
Token next = token.next;
Token? next = token.next;
if (next == null) break;
token = next;
}
return null;
}
List<impl.Test> extractTests(String test, [Uri uri]) {
List<impl.Test> extractTests(String test, [Uri? uri]) {
return impl.extractTests(utf8.encode(test) as Uint8List,
uri ?? new Uri(scheme: "darttest", path: "/foo.dart"));
}

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.
// @dart = 2.9
import 'package:testing/testing.dart'
show Chain, ChainContext, Result, Step, TestDescription, runMe;

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.md file.
// @dart = 2.9
import 'dart:io';
import 'package:_fe_analyzer_shared/src/messages/severity.dart';
@ -75,7 +73,7 @@ Future<void> main() async {
new DillTarget(ticker, uriTranslator, c.options.target);
KernelTarget kernelTarget =
new KernelTarget(c.fileSystem, false, dillTarget, uriTranslator);
Uri platform = c.options.sdkSummary;
Uri? platform = c.options.sdkSummary;
if (platform != null) {
var bytes = new File.fromUri(platform).readAsBytesSync();
var platformComponent = loadComponentFromBytes(bytes);
@ -84,7 +82,7 @@ Future<void> main() async {
}
kernelTarget.setEntryPoints(c.options.inputs);
await dillTarget.buildOutlines();
dillTarget.buildOutlines();
await kernelTarget.loader.buildOutlines();
return new List<Uri>.from(c.dependencies);
});

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.
// @dart = 2.9
/// Test to ensure that desugaring APIs used by clients like dart2js are
/// always up to date.
///
@ -33,13 +31,13 @@ Future<void> main() async {
Future<void> testRedirectingFactoryDirect() async {
var component = await compileUnit(['a.dart'], {'a.dart': aSource});
checkIsRedirectingFactory(component, 'a.dart', 'A', 'foo');
checkIsRedirectingFactory(component!, 'a.dart', 'A', 'foo');
checkIsRedirectingFactory(component, 'core', 'Uri', 'file');
}
Future<void> testRedirectingFactorySerialized() async {
var component = await compileUnit(['a.dart'], {'a.dart': aSource});
var bytes = serializeComponent(component);
var bytes = serializeComponent(component!);
component = new ir.Component();
new BinaryBuilder(bytes).readComponent(component);
checkIsRedirectingFactory(component, 'a.dart', 'A', 'foo');
@ -62,8 +60,8 @@ void checkIsRedirectingFactory(ir.Component component, String uriPath,
var lib =
component.libraries.firstWhere((l) => l.importUri.path.endsWith(uriPath));
var cls = lib.classes.firstWhere((c) => c.name == className);
ir.Procedure member =
cls.members.firstWhere((m) => m.name.text == constructorName);
ir.Procedure member = cls.members
.firstWhere((m) => m.name.text == constructorName) as ir.Procedure;
Expect.isTrue(
member.kind == ir.ProcedureKind.Factory, "$member is not a factory");
Expect.isTrue(api.isRedirectingFactory(member));

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.
// @dart = 2.9
import 'dart:collection';
/// Dijkstra's algorithm for single source shortest path.
@ -21,8 +19,8 @@ class DijkstrasAlgorithm<E> {
DijkstrasAlgorithm(Iterable<GraphNode<E>> graphNodes, GraphNode<E> source,
int Function(E, E) comparator, int Function(E, E) distance) {
SplayTreeSet<GraphNode<E>> q = new SplayTreeSet<GraphNode<E>>((a, b) {
int distA = dist[a];
int distB = dist[b];
int? distA = dist[a];
int? distB = dist[b];
int when0() {
if (identical(a, b)) return 0;
@ -39,7 +37,7 @@ class DijkstrasAlgorithm<E> {
if (distA == null && distB == null) {
return when0();
}
if (distA < distB) return -1;
if (distA! < distB!) return -1;
if (distA > distB) return 1;
return when0();
});
@ -56,7 +54,7 @@ class DijkstrasAlgorithm<E> {
while (q.isNotEmpty) {
GraphNode<E> u = q.first;
int distToU = dist[u];
int? distToU = dist[u];
if (distToU == null) {
// No path to any of the remaining ${q.length} nodes.
break;
@ -68,7 +66,7 @@ class DijkstrasAlgorithm<E> {
int distanceUToV = distance(u.node, v.node);
if (distanceUToV < 0) throw "Got negative distance. That's not allowed";
int alt = distToU + distanceUToV;
int distToV = dist[v];
int? distToV = dist[v];
if (distToV == null || alt < distToV) {
// Decrease length (decrease priority in priority queue).
q.remove(v);
@ -85,7 +83,7 @@ class DijkstrasAlgorithm<E> {
GraphNode<E> u = target;
while (u == source || prev[u] != null) {
path.add(u.node);
u = prev[u];
u = prev[u]!;
}
return path.reversed.toList();
}

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.
// @dart = 2.9
import 'package:front_end/src/fasta/kernel/utils.dart' show serializeComponent;
import 'package:kernel/ast.dart' show Component;

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.
// @dart = 2.9
import 'dart:io';
import 'package:_fe_analyzer_shared/src/messages/severity.dart';
@ -86,15 +84,14 @@ Future<void> main(List<String> args) async {
Stopwatch stopwatch = new Stopwatch()..start();
await CompilerContext.runWithOptions<List<Uri>>(options,
(CompilerContext c) async {
await CompilerContext.runWithOptions(options, (CompilerContext c) async {
UriTranslator uriTranslator = await c.options.getUriTranslator();
DillTarget dillTarget =
new DillTarget(ticker, uriTranslator, c.options.target);
KernelTarget kernelTarget =
new KernelTargetTest(c.fileSystem, false, dillTarget, uriTranslator);
Uri platform = c.options.sdkSummary;
Uri? platform = c.options.sdkSummary;
if (platform != null) {
var bytes = new File.fromUri(platform).readAsBytesSync();
var platformComponent = loadComponentFromBytes(bytes);
@ -103,10 +100,9 @@ Future<void> main(List<String> args) async {
}
kernelTarget.setEntryPoints(c.options.inputs);
await dillTarget.buildOutlines();
dillTarget.buildOutlines();
await kernelTarget.buildOutlines();
await kernelTarget.buildComponent();
return null;
});
print("Done in ${stopwatch.elapsedMilliseconds} ms. "
@ -138,7 +134,7 @@ class SourceLoaderTest extends SourceLoader {
@override
BodyBuilder createBodyBuilderForOutlineExpression(
SourceLibraryBuilder library,
DeclarationBuilder declarationBuilder,
DeclarationBuilder? declarationBuilder,
ModifierBuilder member,
Scope scope,
Uri fileUri) {
@ -162,10 +158,10 @@ class DietListenerTest extends DietListener {
BodyBuilder createListenerInternal(
ModifierBuilder builder,
Scope memberScope,
Scope formalParameterScope,
Scope? formalParameterScope,
bool isDeclarationInstanceMember,
VariableDeclaration extensionThis,
List<TypeParameter> extensionTypeParameters,
VariableDeclaration? extensionThis,
List<TypeParameter>? extensionTypeParameters,
TypeInferrer typeInferrer,
ConstantContext constantContext) {
return new BodyBuilderTest(
@ -221,7 +217,7 @@ class BodyBuilderTest extends BodyBuilder {
@override
BodyBuilderTest.forOutlineExpression(
SourceLibraryBuilder library,
DeclarationBuilder declarationBuilder,
DeclarationBuilder? declarationBuilder,
ModifierBuilder member,
Scope scope,
Uri fileUri)
@ -230,18 +226,18 @@ class BodyBuilderTest extends BodyBuilder {
@override
Expression buildConstructorInvocation(
TypeDeclarationBuilder type,
TypeDeclarationBuilder? type,
Token nameToken,
Token nameLastToken,
Arguments arguments,
Arguments? arguments,
String name,
List<TypeBuilder> typeArguments,
List<TypeBuilder>? typeArguments,
int charOffset,
Constness constness,
{bool isTypeArgumentsInForest = false,
TypeDeclarationBuilder typeAliasBuilder,
UnresolvedKind unresolvedKind}) {
Token maybeNewOrConst = nameToken.previous;
TypeDeclarationBuilder? typeAliasBuilder,
required UnresolvedKind unresolvedKind}) {
Token maybeNewOrConst = nameToken.previous!;
bool doReport = true;
if (maybeNewOrConst is KeywordToken) {
if (maybeNewOrConst.lexeme == "new" ||

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.
// @dart = 2.9
import 'package:expect/expect.dart';
void main() {

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.
// @dart = 2.9
import 'dart:async';
import 'dart:convert';
import 'dart:io';
@ -11,7 +9,7 @@ import 'dart:math';
import "vm_service_heap_helper.dart" as helper;
Completer completer;
late Completer completer;
Set<String> files = {};
@ -36,7 +34,7 @@ Future<void> main(List<String> args) async {
bool quicker = false;
bool alternativeInvalidation = false;
String rootPath;
String? rootPath;
for (String arg in args) {
if (arg == "--quicker") {

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.md file.
// @dart = 2.9
import "dart:io" show File, exitCode;
import "../tool/_fasta/generate_messages.dart" as generateMessages;

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.
// @dart=2.9
import 'dart:io' show File;
import 'dart:typed_data' show Uint8List;
@ -120,15 +118,15 @@ class ParserTestListener implements Listener {
class ParserCreatorListener extends Listener {
final StringSink out;
bool insideListenerClass = false;
String currentMethodName;
String latestSeenParameterTypeToken;
List<String> parameters = <String>[];
List<String> parameterTypes = <String>[];
String? currentMethodName;
String? latestSeenParameterTypeToken;
List<String> parameters = [];
List<String?> parameterTypes = [];
ParserCreatorListener(this.out);
@override
void beginClassDeclaration(Token begin, Token abstractToken, Token name) {
void beginClassDeclaration(Token begin, Token? abstractToken, Token name) {
if (name.lexeme == "Listener") insideListenerClass = true;
}
@ -140,23 +138,23 @@ class ParserCreatorListener extends Listener {
@override
void beginMethod(
DeclarationKind declarationKind,
Token externalToken,
Token staticToken,
Token covariantToken,
Token varFinalOrConst,
Token getOrSet,
Token? externalToken,
Token? staticToken,
Token? covariantToken,
Token? varFinalOrConst,
Token? getOrSet,
Token name) {
currentMethodName = name.lexeme;
}
@override
void endClassMethod(Token getOrSet, Token beginToken, Token beginParam,
Token beginInitializers, Token endToken) {
void endClassMethod(Token? getOrSet, Token beginToken, Token beginParam,
Token? beginInitializers, Token endToken) {
if (insideListenerClass) {
out.writeln(" @override");
out.write(" ");
Token token = beginToken;
Token latestToken;
Token? latestToken;
while (true) {
if (latestToken != null && latestToken.charEnd < token.charOffset) {
out.write(" ");
@ -171,14 +169,14 @@ class ParserCreatorListener extends Listener {
throw token.runtimeType;
}
latestToken = token;
token = token.next;
token = token.next!;
}
if (token is SimpleToken && token.type == TokenType.FUNCTION) {
out.write(" null;");
} else {
out.write("\n ");
if (currentMethodName.startsWith("end")) {
if (currentMethodName!.startsWith("end")) {
out.write("indent--;\n ");
}
for (int i = 0; i < parameterTypes.length; i++) {
@ -196,7 +194,7 @@ class ParserCreatorListener extends Listener {
}
out.write(")');\n ");
if (currentMethodName.startsWith("begin")) {
if (currentMethodName!.startsWith("begin")) {
out.write(" indent++;\n ");
}
@ -224,17 +222,17 @@ class ParserCreatorListener extends Listener {
}
@override
void handleType(Token beginToken, Token questionMark) {
void handleType(Token beginToken, Token? questionMark) {
latestSeenParameterTypeToken = beginToken.lexeme;
}
@override
void endFormalParameter(
Token thisKeyword,
Token periodAfterThis,
Token? thisKeyword,
Token? periodAfterThis,
Token nameToken,
Token initializerStart,
Token initializerEnd,
Token? initializerStart,
Token? initializerEnd,
FormalParameterKind kind,
MemberKind memberKind) {
parameters.add(nameToken.lexeme);

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.
// @dart = 2.9
import 'dart:io';
import 'dart:typed_data';
@ -106,14 +104,14 @@ class TestParser extends Parser {
class ParserCreatorListener extends Listener {
final StringSink out;
bool insideParserClass = false;
String currentMethodName;
List<String> parameters = <String>[];
List<String> parametersNamed = <String>[];
String? currentMethodName;
List<String> parameters = [];
List<String?> parametersNamed = [];
ParserCreatorListener(this.out);
@override
void beginClassDeclaration(Token begin, Token abstractToken, Token name) {
void beginClassDeclaration(Token begin, Token? abstractToken, Token name) {
if (name.lexeme == "Parser") insideParserClass = true;
}
@ -125,29 +123,29 @@ class ParserCreatorListener extends Listener {
@override
void beginMethod(
DeclarationKind declarationKind,
Token externalToken,
Token staticToken,
Token covariantToken,
Token varFinalOrConst,
Token getOrSet,
Token? externalToken,
Token? staticToken,
Token? covariantToken,
Token? varFinalOrConst,
Token? getOrSet,
Token name) {
currentMethodName = name.lexeme;
}
@override
void endClassConstructor(Token getOrSet, Token beginToken, Token beginParam,
Token beginInitializers, Token endToken) {
void endClassConstructor(Token? getOrSet, Token beginToken, Token beginParam,
Token? beginInitializers, Token endToken) {
parameters.clear();
parametersNamed.clear();
currentMethodName = null;
}
@override
void endClassMethod(Token getOrSet, Token beginToken, Token beginParam,
Token beginInitializers, Token endToken) {
if (insideParserClass && !currentMethodName.startsWith("_")) {
void endClassMethod(Token? getOrSet, Token beginToken, Token beginParam,
Token? beginInitializers, Token endToken) {
if (insideParserClass && !currentMethodName!.startsWith("_")) {
Token token = beginToken;
Token latestToken;
Token? latestToken;
out.writeln(" @override");
out.write(" ");
while (true) {
@ -156,7 +154,7 @@ class ParserCreatorListener extends Listener {
out.write(" ");
}
out.write("dynamic");
token = troubleParameterTokens[token];
token = troubleParameterTokens[token]!;
}
if (latestToken != null && latestToken.charEnd < token.charOffset) {
out.write(" ");
@ -169,16 +167,15 @@ class ParserCreatorListener extends Listener {
out.write(token.lexeme);
if (token is BeginToken &&
token.type == TokenType.OPEN_CURLY_BRACKET &&
(beginParam == null ||
beginParam.endGroup == endToken ||
token.charOffset > beginParam.endGroup.charOffset)) {
(beginParam.endGroup == endToken ||
token.charOffset > beginParam.endGroup!.charOffset)) {
break;
}
if (token == endToken) {
throw token.runtimeType;
}
latestToken = token;
token = token.next;
token = token.next!;
}
out.write("\n ");
@ -244,17 +241,17 @@ class ParserCreatorListener extends Listener {
formalParametersNestLevel--;
}
Token currentFormalParameterToken;
Token? currentFormalParameterToken;
@override
void beginFormalParameter(Token token, MemberKind kind, Token requiredToken,
Token covariantToken, Token varFinalOrConst) {
void beginFormalParameter(Token token, MemberKind kind, Token? requiredToken,
Token? covariantToken, Token? varFinalOrConst) {
if (formalParametersNestLevel == 1) {
currentFormalParameterToken = token;
}
}
Map<Token, Token> troubleParameterTokens = {};
Map<Token?, Token?> troubleParameterTokens = {};
@override
void handleIdentifier(Token token, IdentifierContext context) {
@ -265,11 +262,11 @@ class ParserCreatorListener extends Listener {
@override
void endFormalParameter(
Token thisKeyword,
Token periodAfterThis,
Token? thisKeyword,
Token? periodAfterThis,
Token nameToken,
Token initializerStart,
Token initializerEnd,
Token? initializerStart,
Token? initializerEnd,
FormalParameterKind kind,
MemberKind memberKind) {
if (formalParametersNestLevel != 1) {

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.
// @dart = 2.9
import "vm_service_helper.dart" as vmService;
class VMServiceHeapHelperSpecificExactLeakFinder
@ -22,13 +20,13 @@ class VMServiceHeapHelperSpecificExactLeakFinder
}) {
if (interests.isEmpty) throw "Empty list of interests given";
for (Interest interest in interests) {
Map<String, List<String>> classToFields = _interests[interest.uri];
Map<String, List<String>>? classToFields = _interests[interest.uri];
if (classToFields == null) {
classToFields = Map<String, List<String>>();
_interests[interest.uri] = classToFields;
}
_interestsClassNames.add(interest.className);
List<String> fields = classToFields[interest.className];
List<String>? fields = classToFields[interest.className];
if (fields == null) {
fields = <String>[];
classToFields[interest.className] = fields;
@ -36,12 +34,12 @@ class VMServiceHeapHelperSpecificExactLeakFinder
fields.addAll(interest.fieldNames);
}
for (Interest interest in prettyPrints) {
Map<String, List<String>> classToFields = _prettyPrints[interest.uri];
Map<String, List<String>>? classToFields = _prettyPrints[interest.uri];
if (classToFields == null) {
classToFields = Map<String, List<String>>();
_prettyPrints[interest.uri] = classToFields;
}
List<String> fields = classToFields[interest.className];
List<String>? fields = classToFields[interest.className];
if (fields == null) {
fields = <String>[];
classToFields[interest.className] = fields;
@ -51,20 +49,20 @@ class VMServiceHeapHelperSpecificExactLeakFinder
}
Future<void> pause() async {
await serviceClient.pause(_isolateRef.id);
await serviceClient.pause(_isolateRef.id!);
}
vmService.VM _vm;
vmService.IsolateRef _isolateRef;
int _iterationNumber;
late vmService.VM _vm;
late vmService.IsolateRef _isolateRef;
late int _iterationNumber;
int get iterationNumber => _iterationNumber;
/// Best effort check if the isolate is idle.
Future<bool> isIdle() async {
dynamic tmp = await serviceClient.getIsolate(_isolateRef.id);
dynamic tmp = await serviceClient.getIsolate(_isolateRef.id!);
if (tmp is vmService.Isolate) {
vmService.Isolate isolate = tmp;
return isolate.pauseEvent.topFrame == null;
return isolate.pauseEvent!.topFrame == null;
}
return false;
}
@ -72,44 +70,44 @@ class VMServiceHeapHelperSpecificExactLeakFinder
@override
Future<void> run() async {
_vm = await serviceClient.getVM();
if (_vm.isolates.length == 0) {
if (_vm.isolates!.length == 0) {
print("Didn't get any isolates. Will wait 1 second and retry.");
await Future.delayed(new Duration(seconds: 1));
_vm = await serviceClient.getVM();
}
if (_vm.isolates.length != 1) {
throw "Expected 1 isolate, got ${_vm.isolates.length}";
if (_vm.isolates!.length != 1) {
throw "Expected 1 isolate, got ${_vm.isolates!.length}";
}
_isolateRef = _vm.isolates.single;
await forceGC(_isolateRef.id);
_isolateRef = _vm.isolates!.single;
await forceGC(_isolateRef.id!);
assert(await isPausedAtStart(_isolateRef.id));
await serviceClient.resume(_isolateRef.id);
assert(await isPausedAtStart(_isolateRef.id!));
await serviceClient.resume(_isolateRef.id!);
_iterationNumber = 1;
while (true) {
if (!shouldDoAnotherIteration(_iterationNumber)) break;
await waitUntilPaused(_isolateRef.id);
await waitUntilPaused(_isolateRef.id!);
print("Iteration: #$_iterationNumber");
Stopwatch stopwatch = new Stopwatch()..start();
vmService.AllocationProfile allocationProfile =
await forceGC(_isolateRef.id);
await forceGC(_isolateRef.id!);
print("Forced GC in ${stopwatch.elapsedMilliseconds} ms");
stopwatch.reset();
List<Leak> leaks = [];
for (vmService.ClassHeapStats member in allocationProfile.members) {
if (_interestsClassNames.contains(member.classRef.name)) {
vmService.Class c =
await serviceClient.getObject(_isolateRef.id, member.classRef.id);
String uriString = c.location?.script?.uri;
for (vmService.ClassHeapStats member in allocationProfile.members!) {
if (_interestsClassNames.contains(member.classRef!.name)) {
vmService.Class c = (await serviceClient.getObject(
_isolateRef.id!, member.classRef!.id!)) as vmService.Class;
String? uriString = c.location?.script?.uri;
if (uriString == null) continue;
Uri uri = Uri.parse(uriString);
Map<String, List<String>> uriInterest = _interests[uri];
Map<String, List<String>>? uriInterest = _interests[uri];
if (uriInterest == null) continue;
List<String> fieldsForClass = uriInterest[c.name];
List<String>? fieldsForClass = uriInterest[c.name];
if (fieldsForClass == null) continue;
List<String> fieldsForClassPrettyPrint = fieldsForClass;
@ -117,11 +115,11 @@ class VMServiceHeapHelperSpecificExactLeakFinder
uriInterest = _prettyPrints[uri];
if (uriInterest != null) {
if (uriInterest[c.name] != null) {
fieldsForClassPrettyPrint = uriInterest[c.name];
fieldsForClassPrettyPrint = uriInterest[c.name]!;
}
}
leaks.addAll(await _findLeaks(_isolateRef, member.classRef,
leaks.addAll(await _findLeaks(_isolateRef, member.classRef!,
fieldsForClass, fieldsForClassPrettyPrint));
}
}
@ -138,7 +136,7 @@ class VMServiceHeapHelperSpecificExactLeakFinder
print("Looked for leaks in ${stopwatch.elapsedMilliseconds} ms");
await serviceClient.resume(_isolateRef.id);
await serviceClient.resume(_isolateRef.id!);
_iterationNumber++;
}
}
@ -149,7 +147,7 @@ class VMServiceHeapHelperSpecificExactLeakFinder
List<String> fieldsForClass,
List<String> fieldsForClassPrettyPrint) async {
// Use undocumented (/ private?) method to get all instances of this class.
vmService.InstanceRef instancesAsList = await serviceClient.callMethod(
vmService.InstanceRef instancesAsList = (await serviceClient.callMethod(
"_getInstancesAsArray",
isolateId: isolateRef.id,
args: {
@ -157,7 +155,7 @@ class VMServiceHeapHelperSpecificExactLeakFinder
"includeSubclasses": false,
"includeImplementors": false,
},
);
)) as vmService.InstanceRef;
// Create dart code that `toString`s a class instance according to
// the fields given as wanting printed. Both for finding duplicates (1) and
@ -165,14 +163,14 @@ class VMServiceHeapHelperSpecificExactLeakFinder
// them) (2).
// 1:
String fieldsToStringCode = classRef.name +
String fieldsToStringCode = classRef.name! +
"[" +
fieldsForClass
.map((value) => "$value: \"\${element.$value}\"")
.join(", ") +
"]";
// 2:
String fieldsToStringPrettyPrintCode = classRef.name +
String fieldsToStringPrettyPrintCode = classRef.name! +
"[" +
fieldsForClassPrettyPrint
.map((value) => "$value: \"\${element.$value}\"")
@ -182,9 +180,9 @@ class VMServiceHeapHelperSpecificExactLeakFinder
// Expression evaluation to find duplicates: Put all entries into a map
// indexed by the `toString` code created above, mapping to list of that
// data.
vmService.InstanceRef mappedData = await serviceClient.evaluate(
isolateRef.id,
instancesAsList.id,
vmService.InstanceRef mappedData = (await serviceClient.evaluate(
isolateRef.id!,
instancesAsList.id!,
"""
this
.fold({}, (dynamic index, dynamic element) {
@ -194,22 +192,22 @@ class VMServiceHeapHelperSpecificExactLeakFinder
return index;
})
""",
);
)) as vmService.InstanceRef;
// Expression calculation to find if any of the lists created as values
// above contains more than one entry (i.e. there's a duplicate).
vmService.InstanceRef duplicatesLengthRef = await serviceClient.evaluate(
isolateRef.id,
mappedData.id,
vmService.InstanceRef duplicatesLengthRef = (await serviceClient.evaluate(
isolateRef.id!,
mappedData.id!,
"""
this
.values
.where((dynamic element) => (element.length > 1) as bool)
.length
""",
);
vmService.Instance duplicatesLength =
await serviceClient.getObject(isolateRef.id, duplicatesLengthRef.id);
int duplicates = int.tryParse(duplicatesLength.valueAsString);
)) as vmService.InstanceRef;
vmService.Instance duplicatesLength = (await serviceClient.getObject(
isolateRef.id!, duplicatesLengthRef.id!)) as vmService.Instance;
int? duplicates = int.tryParse(duplicatesLength.valueAsString!);
if (duplicates != 0) {
// There are duplicates. Expression calculation to encode the duplication
// data (both the string that caused it to be a duplicate and the pretty
@ -219,9 +217,9 @@ class VMServiceHeapHelperSpecificExactLeakFinder
// e.g. encode the string "string" as "6:string" (length 6, string),
// and the list ["foo", "bar"] as "2:3:foo:3:bar" (2 entries, length 3,
// foo, length 3, bar).
vmService.ObjRef duplicatesDataRef = await serviceClient.evaluate(
isolateRef.id,
mappedData.id,
vmService.ObjRef duplicatesDataRef = (await serviceClient.evaluate(
isolateRef.id!,
mappedData.id!,
"""
this
.entries
@ -237,11 +235,11 @@ class VMServiceHeapHelperSpecificExactLeakFinder
return "\${keyPart}:\${valuePart1}:\${valuePart2}";
}).join(":")
""",
);
)) as vmService.ObjRef;
if (duplicatesDataRef is! vmService.InstanceRef) {
if (duplicatesDataRef is vmService.ErrorRef) {
vmService.Error error = await serviceClient.getObject(
isolateRef.id, duplicatesDataRef.id);
vmService.Error error = (await serviceClient.getObject(
isolateRef.id!, duplicatesDataRef.id!)) as vmService.Error;
throw "Leak found, but trying to evaluate pretty printing "
"didn't go as planned.\n"
"Got error with message "
@ -254,9 +252,9 @@ class VMServiceHeapHelperSpecificExactLeakFinder
}
}
vmService.Instance duplicatesData =
await serviceClient.getObject(isolateRef.id, duplicatesDataRef.id);
String encodedData = duplicatesData.valueAsString;
vmService.Instance duplicatesData = (await serviceClient.getObject(
isolateRef.id!, duplicatesDataRef.id!)) as vmService.Instance;
String encodedData = duplicatesData.valueAsString!;
try {
return parseEncodedLeakString(encodedData);
} catch (e) {

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.
// @dart = 2.9
import "dart:convert";
import "dart:io";
@ -14,7 +12,7 @@ export "package:vm_service/vm_service.dart";
export "package:vm_service/vm_service_io.dart";
class VMServiceHelper {
vmService.VmService _serviceClient;
late vmService.VmService _serviceClient;
vmService.VmService get serviceClient => _serviceClient;
VMServiceHelper();
@ -34,7 +32,7 @@ class VMServiceHelper {
Future<bool> waitUntilPaused(String isolateId) async {
int nulls = 0;
while (true) {
bool result = await isPaused(isolateId);
bool? result = await isPaused(isolateId);
if (result == null) {
nulls++;
if (nulls > 5) {
@ -50,11 +48,11 @@ class VMServiceHelper {
}
}
Future<bool> isPaused(String isolateId) async {
Future<bool?> isPaused(String isolateId) async {
dynamic tmp = await _serviceClient.getIsolate(isolateId);
if (tmp is vmService.Isolate) {
vmService.Isolate isolate = tmp;
if (isolate.pauseEvent.kind != "Resume") return true;
if (isolate.pauseEvent!.kind != "Resume") return true;
return false;
}
return null;
@ -64,7 +62,7 @@ class VMServiceHelper {
dynamic tmp = await _serviceClient.getIsolate(isolateId);
if (tmp is vmService.Isolate) {
vmService.Isolate isolate = tmp;
return isolate.pauseEvent.kind == "PauseStart";
return isolate.pauseEvent!.kind == "PauseStart";
}
return false;
}
@ -73,7 +71,7 @@ class VMServiceHelper {
dynamic tmp = await _serviceClient.getIsolate(isolateId);
if (tmp is vmService.Isolate) {
vmService.Isolate isolate = tmp;
return isolate.pauseEvent.kind == "PauseExit";
return isolate.pauseEvent!.kind == "PauseExit";
}
return false;
}
@ -91,13 +89,13 @@ class VMServiceHelper {
rethrow;
}
if (allocationProfile.dateLastServiceGC != null &&
allocationProfile.dateLastServiceGC >= expectGcAfter) {
allocationProfile.dateLastServiceGC! >= expectGcAfter) {
return allocationProfile;
}
}
}
Future<bool> isIsolateRunnable(String isolateId) async {
Future<bool?> isIsolateRunnable(String isolateId) async {
dynamic tmp = await _serviceClient.getIsolate(isolateId);
if (tmp is vmService.Isolate) {
vmService.Isolate isolate = tmp;
@ -109,7 +107,7 @@ class VMServiceHelper {
Future<void> waitUntilIsolateIsRunnable(String isolateId) async {
int nulls = 0;
while (true) {
bool result = await isIsolateRunnable(isolateId);
bool? result = await isIsolateRunnable(isolateId);
if (result == null) {
nulls++;
if (nulls > 5) {
@ -127,11 +125,11 @@ class VMServiceHelper {
Future<String> getIsolateId() async {
vmService.VM vm = await _serviceClient.getVM();
if (vm.isolates.length != 1) {
throw "Expected 1 isolate, got ${vm.isolates.length}";
if (vm.isolates!.length != 1) {
throw "Expected 1 isolate, got ${vm.isolates!.length}";
}
vmService.IsolateRef isolateRef = vm.isolates.single;
return isolateRef.id;
vmService.IsolateRef isolateRef = vm.isolates!.single;
return isolateRef.id!;
}
}
@ -150,14 +148,14 @@ class StdOutLog implements vmService.Log {
}
abstract class LaunchingVMServiceHelper extends VMServiceHelper {
Process _process;
late Process _process;
Process get process => _process;
bool _started = false;
Future<void> start(List<String> scriptAndArgs,
{void stdoutReceiver(String line),
void stderrReceiver(String line)}) async {
{void Function(String line)? stdoutReceiver,
void Function(String line)? stderrReceiver}) async {
if (_started) throw "Already started";
_started = true;
_process = await Process.start(

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.
// @dart = 2.9
import 'dart:io';
import 'ast_model.dart';
@ -21,7 +19,7 @@ Future<void> main(List<String> args) async {
new File.fromUri(output).writeAsStringSync(result);
}
Future<String> generateAstCoverage(Uri repoDir, [AstModel astModel]) async {
Future<String> generateAstCoverage(Uri repoDir, [AstModel? astModel]) async {
astModel ??= await deriveAstModel(repoDir);
return generateVisitor(astModel, new CoverageVisitorStrategy());
}
@ -47,7 +45,7 @@ class CoverageVisitorStrategy extends Visitor0Strategy {
@override
void handleVisit(AstModel astModel, AstClass astClass, StringBuffer sb) {
AstClass superAstClass = astClass.superclass;
AstClass? superAstClass = astClass.superclass;
while (superAstClass != null && !superAstClass.isInterchangeable) {
superAstClass = superAstClass.superclass;
}
@ -61,13 +59,13 @@ class CoverageVisitorStrategy extends Visitor0Strategy {
@override
void handleVisitReference(
AstModel astModel, AstClass astClass, StringBuffer sb) {
AstClass superAstClass = astClass.superclass;
AstClass? superAstClass = astClass.superclass;
while (superAstClass != null && !superAstClass.isInterchangeable) {
superAstClass = superAstClass.superclass;
}
if (superAstClass == astModel.constantClass) {
// Constants are only visited as references.
String innerName = superAstClass.name;
String innerName = superAstClass!.name;
(nestedClassNames[innerName] ??= {}).add(astClass.name);
sb.writeln('''
visited.add(${innerName}Kind.${astClass.name});