Skip to content

Commit 244e6c7

Browse files
Infer package URIs
Closes #33076 Change-Id: I73db84eadaf3ba723c2f1323f9b883077a4df9df Reviewed-on: https://dart-review.googlesource.com/c/78246 Commit-Queue: Peter von der Ahé <[email protected]> Reviewed-by: Jens Johansen <[email protected]>
1 parent cc884b3 commit 244e6c7

15 files changed

+154
-159
lines changed

pkg/front_end/lib/src/base/processed_options.dart

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,6 @@ import '../fasta/ticker.dart' show Ticker;
5959

6060
import '../fasta/uri_translator.dart' show UriTranslator;
6161

62-
import '../fasta/uri_translator_impl.dart' show UriTranslatorImpl;
63-
6462
import 'libraries_specification.dart'
6563
show
6664
LibrariesSpecification,
@@ -95,7 +93,7 @@ class ProcessedOptions {
9593

9694
/// The object that knows how to resolve "package:" and "dart:" URIs,
9795
/// or `null` if it has not been computed yet.
98-
UriTranslatorImpl _uriTranslator;
96+
UriTranslator _uriTranslator;
9997

10098
/// The SDK summary, or `null` if it has not been read yet.
10199
///
@@ -382,7 +380,7 @@ class ProcessedOptions {
382380
///
383381
/// This is an asynchronous method since file system operations may be
384382
/// required to locate/read the packages file as well as SDK metadata.
385-
Future<UriTranslatorImpl> getUriTranslator({bool bypassCache: false}) async {
383+
Future<UriTranslator> getUriTranslator({bool bypassCache: false}) async {
386384
if (bypassCache) {
387385
_uriTranslator = null;
388386
_packages = null;
@@ -393,7 +391,7 @@ class ProcessedOptions {
393391
ticker.logMs("Read libraries file");
394392
var packages = await _getPackages();
395393
ticker.logMs("Read packages file");
396-
_uriTranslator = new UriTranslatorImpl(libraries, packages);
394+
_uriTranslator = new UriTranslator(libraries, packages);
397395
}
398396
return _uriTranslator;
399397
}

pkg/front_end/lib/src/fasta/dill/dill_target.dart

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,6 @@ class DillTarget extends TargetImplementation {
3737
unsupported("addSourceInformation", -1, null);
3838
}
3939

40-
@override
41-
void read(Uri uri) {
42-
unsupported("read", -1, null);
43-
}
44-
4540
@override
4641
Future<Null> buildComponent() {
4742
return new Future<Null>.sync(() => unsupported("buildComponent", -1, null));

pkg/front_end/lib/src/fasta/fasta_codes_generated.dart

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4294,6 +4294,26 @@ const MessageCode messageIncorrectTypeArgumentVariable = const MessageCode(
42944294
severity: Severity.context,
42954295
message: r"""Bound of this variable is violated.""");
42964296

4297+
// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
4298+
const Template<Message Function(Uri uri_)> templateInferredPackageUri =
4299+
const Template<Message Function(Uri uri_)>(
4300+
messageTemplate: r"""Interpreting this as package URI, '#uri'.""",
4301+
withArguments: _withArgumentsInferredPackageUri);
4302+
4303+
// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
4304+
const Code<Message Function(Uri uri_)> codeInferredPackageUri =
4305+
const Code<Message Function(Uri uri_)>(
4306+
"InferredPackageUri", templateInferredPackageUri,
4307+
severity: Severity.warning);
4308+
4309+
// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
4310+
Message _withArgumentsInferredPackageUri(Uri uri_) {
4311+
String uri = relativizeUri(uri_);
4312+
return new Message(codeInferredPackageUri,
4313+
message: """Interpreting this as package URI, '${uri}'.""",
4314+
arguments: {'uri': uri_});
4315+
}
4316+
42974317
// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
42984318
const Code<Null> codeInheritedMembersConflict = messageInheritedMembersConflict;
42994319

pkg/front_end/lib/src/fasta/get_dependencies.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ Future<List<Uri>> getDependencies(Uri script,
5353
fileSystem, false, dillTarget, uriTranslator,
5454
uriToSource: c.uriToSource);
5555

56-
kernelTarget.read(script);
56+
kernelTarget.setEntryPoints(<Uri>[script]);
5757
await dillTarget.buildOutlines();
5858
await kernelTarget.loader.buildOutlines();
5959
return new List<Uri>.from(c.dependencies);

pkg/front_end/lib/src/fasta/incremental_compiler.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ class IncrementalCompiler implements IncrementalKernelGenerator {
251251

252252
Component componentWithDill;
253253
try {
254-
userCode.read(entryPoint);
254+
userCode.setEntryPoints(<Uri>[entryPoint]);
255255
await userCode.buildOutlines();
256256

257257
// This is not the full component. It is the component including all

pkg/front_end/lib/src/fasta/kernel/kernel_target.dart

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ import '../messages.dart'
6363
noLength,
6464
templateFinalFieldNotInitialized,
6565
templateFinalFieldNotInitializedByConstructor,
66+
templateInferredPackageUri,
6667
templateMissingImplementationCause,
6768
templateSuperclassHasNoDefaultConstructor;
6869

@@ -152,8 +153,40 @@ class KernelTarget extends TargetImplementation {
152153
uriToSource[uri] = new Source(lineStarts, sourceCode);
153154
}
154155

155-
void read(Uri uri) {
156-
loader.read(uri, -1, accessor: loader.first);
156+
void setEntryPoints(List<Uri> entryPoints) {
157+
Map<String, Uri> packagesMap;
158+
for (Uri entryPoint in entryPoints) {
159+
String scheme = entryPoint.scheme;
160+
Uri fileUri;
161+
switch (scheme) {
162+
case "package":
163+
case "dart":
164+
case "data":
165+
break;
166+
default:
167+
// Attempt to reverse-lookup [entryPoint] in package config.
168+
String asString = "$entryPoint";
169+
packagesMap ??= uriTranslator.packages.asMap();
170+
for (String packageName in packagesMap.keys) {
171+
String prefix = "${packagesMap[packageName]}";
172+
if (asString.startsWith(prefix)) {
173+
Uri reversed = Uri.parse(
174+
"package:$packageName/${asString.substring(prefix.length)}");
175+
if (entryPoint == uriTranslator.translate(reversed)) {
176+
loader.addProblem(
177+
templateInferredPackageUri.withArguments(reversed),
178+
-1,
179+
1,
180+
entryPoint);
181+
fileUri = entryPoint;
182+
entryPoint = reversed;
183+
break;
184+
}
185+
}
186+
}
187+
}
188+
loader.read(entryPoint, -1, accessor: loader.first, fileUri: fileUri);
189+
}
157190
}
158191

159192
@override

pkg/front_end/lib/src/fasta/rewrite_severity.dart

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,6 @@ Severity rewriteSeverity(
4444
switch (path.substring(fastaPath.length + index)) {
4545
case "command_line.dart":
4646
case "deprecated_problems.dart":
47-
case "entry_points.dart":
4847
case "kernel/body_builder.dart":
4948
case "source/diet_listener.dart":
5049
return severity;

pkg/front_end/lib/src/fasta/target.dart

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,6 @@ abstract class Target {
2020

2121
Target(this.ticker);
2222

23-
/// Instructs this target to include [uri] in its result.
24-
void read(Uri uri);
25-
2623
/// Build and return outlines for all libraries.
2724
Future<Component> buildOutlines();
2825

pkg/front_end/lib/src/fasta/uri_translator.dart

Lines changed: 77 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,29 +4,81 @@
44

55
library fasta.uri_translator;
66

7-
/// Instances of [UriTranslator] translate absolute URIs into corresponding
8-
/// file URIs in a [FileSystem]. Translated URIs are typically `file:` URIs,
9-
/// but may use a different scheme depending on the used custom file system.
10-
abstract class UriTranslator {
11-
/// Return the URIs of patches that should be applied to the platform library
12-
/// with the given [libraryName], or `null` if there are no patches to apply.
13-
List<Uri> getDartPatches(String libraryName);
14-
15-
/// Returns `true` if [uri] is private to the platform libraries (and thus
16-
/// not accessible from user code).
17-
bool isPlatformImplementation(Uri uri);
18-
19-
/// Return the corresponding file URI for the given absolute [uri], or `null`
20-
/// if there is no corresponding file URI, or the given [uri] is already a
21-
/// file URI.
22-
///
23-
/// Note: this only translates the URI, there is no guarantee that the
24-
/// corresponding file exists in the file system.
25-
///
26-
/// If [reportMessage] is true a message will be reported via
27-
/// [CompilerContext.current].
28-
Uri translate(Uri uri, [bool reportMessage = true]);
29-
30-
/// Whether the given [libraryName] is supported by the underlying target.
31-
bool isLibrarySupported(String libraryName);
7+
import 'package:package_config/packages.dart' show Packages;
8+
9+
import '../base/libraries_specification.dart' show TargetLibrariesSpecification;
10+
import 'compiler_context.dart' show CompilerContext;
11+
import 'fasta_codes.dart';
12+
import 'severity.dart' show Severity;
13+
14+
class UriTranslator {
15+
final TargetLibrariesSpecification dartLibraries;
16+
17+
final Packages packages;
18+
19+
UriTranslator(this.dartLibraries, this.packages);
20+
21+
List<Uri> getDartPatches(String libraryName) =>
22+
dartLibraries.libraryInfoFor(libraryName)?.patches;
23+
24+
bool isPlatformImplementation(Uri uri) {
25+
if (uri.scheme != "dart") return false;
26+
String path = uri.path;
27+
return dartLibraries.libraryInfoFor(path) == null || path.startsWith("_");
28+
}
29+
30+
// TODO(sigmund, ahe): consider expanding this API to include an error
31+
// callback, so we can provide an error location when one is available. For
32+
// example, if the error occurs in an `import`.
33+
Uri translate(Uri uri, [bool reportMessage = true]) {
34+
if (uri.scheme == "dart") return _translateDartUri(uri);
35+
if (uri.scheme == "package") {
36+
return _translatePackageUri(uri, reportMessage);
37+
}
38+
return null;
39+
}
40+
41+
bool isLibrarySupported(String libraryName) {
42+
// TODO(sigmund): change this to `?? false` when all backends provide the
43+
// `libraries.json` file by default (Issue #32657).
44+
return dartLibraries.libraryInfoFor(libraryName)?.isSupported ?? true;
45+
}
46+
47+
Uri _translateDartUri(Uri uri) {
48+
if (!uri.isScheme('dart')) return null;
49+
return dartLibraries.libraryInfoFor(uri.path)?.uri;
50+
}
51+
52+
Uri _translatePackageUri(Uri uri, bool reportMessage) {
53+
try {
54+
// TODO(sigmund): once we remove the `parse` API, we can ensure that
55+
// packages will never be null and get rid of `?` below.
56+
return packages?.resolve(uri,
57+
notFound: reportMessage
58+
? _packageUriNotFound
59+
: _packageUriNotFoundNoReport);
60+
} on ArgumentError catch (e) {
61+
// TODO(sigmund): catch a more precise error when
62+
// https://github.com/dart-lang/package_config/issues/40 is fixed.
63+
if (reportMessage) {
64+
CompilerContext.current.reportWithoutLocation(
65+
templateInvalidPackageUri.withArguments(uri, '$e'), Severity.error);
66+
}
67+
return null;
68+
}
69+
}
70+
71+
static Uri _packageUriNotFound(Uri uri) {
72+
String name = uri.pathSegments.first;
73+
CompilerContext.current.reportWithoutLocation(
74+
templatePackageNotFound.withArguments(name, uri), Severity.error);
75+
// TODO(sigmund, ahe): ensure we only report an error once,
76+
// this null result will likely cause another error further down in the
77+
// compiler.
78+
return null;
79+
}
80+
81+
static Uri _packageUriNotFoundNoReport(Uri uri) {
82+
return null;
83+
}
3284
}

pkg/front_end/lib/src/fasta/uri_translator_impl.dart

Lines changed: 0 additions & 97 deletions
This file was deleted.

pkg/front_end/lib/src/kernel_generator_impl.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ Future<CompilerResult> generateKernelInternal(
106106
var kernelTarget =
107107
new KernelTarget(fs, false, dillTarget, uriTranslator);
108108
sourceLoader = kernelTarget.loader;
109-
options.inputs.forEach(kernelTarget.read);
109+
kernelTarget.setEntryPoints(options.inputs);
110110
Component summaryComponent =
111111
await kernelTarget.buildOutlines(nameRoot: nameRoot);
112112
List<int> summary = null;

pkg/front_end/messages.yaml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3213,3 +3213,13 @@ IncorrectTypeArgumentInSupertypeInferred:
32133213
IncorrectTypeArgumentVariable:
32143214
template: "Bound of this variable is violated."
32153215
severity: CONTEXT
3216+
3217+
InferredPackageUri:
3218+
template: "Interpreting this as package URI, '#uri'."
3219+
severity: WARNING
3220+
frontendInternal: true
3221+
script:
3222+
"main.dart": |
3223+
main() {}
3224+
".packages": |
3225+
example:./

0 commit comments

Comments
 (0)