Version 2.18.0-151.0.dev

Merge commit 'd0d39bac4446990a14269162e03f210be50500fd' into 'dev'
diff --git a/pkg/analyzer/lib/dart/sdk/build_sdk_summary.dart b/pkg/analyzer/lib/dart/sdk/build_sdk_summary.dart
index 4cebed9..d3f0b35 100644
--- a/pkg/analyzer/lib/dart/sdk/build_sdk_summary.dart
+++ b/pkg/analyzer/lib/dart/sdk/build_sdk_summary.dart
@@ -4,26 +4,18 @@
 
 import 'dart:typed_data';
 
-import 'package:_fe_analyzer_shared/src/sdk/allowed_experiments.dart';
-import 'package:analyzer/dart/analysis/declared_variables.dart';
-import 'package:analyzer/dart/analysis/features.dart';
-import 'package:analyzer/dart/analysis/utilities.dart';
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/dart/analysis/results.dart';
 import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/src/context/context.dart';
+import 'package:analyzer/src/context/packages.dart';
+import 'package:analyzer/src/dart/analysis/byte_store.dart';
 import 'package:analyzer/src/dart/analysis/driver.dart';
-import 'package:analyzer/src/dart/analysis/session.dart';
-import 'package:analyzer/src/dart/ast/ast.dart';
+import 'package:analyzer/src/dart/analysis/performance_logger.dart';
+import 'package:analyzer/src/dart/element/element.dart';
 import 'package:analyzer/src/dart/sdk/sdk.dart';
 import 'package:analyzer/src/generated/engine.dart';
 import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/summary2/link.dart';
-import 'package:analyzer/src/summary2/linked_element_factory.dart';
+import 'package:analyzer/src/summary2/bundle_writer.dart';
 import 'package:analyzer/src/summary2/package_bundle_format.dart';
-import 'package:analyzer/src/summary2/reference.dart';
-import 'package:analyzer/src/util/performance/operation_performance.dart';
-import 'package:pub_semver/pub_semver.dart';
 import 'package:yaml/yaml.dart';
 
 /// Build summary for SDK at the given [sdkPath].
@@ -58,196 +50,51 @@
     }
   }
 
-  var librarySources = sdk.sdkLibraries.map((e) {
-    return sdk.mapDartUri(e.shortName)!;
-  }).toList();
-
-  var analysisContext = AnalysisContextImpl(
-    SynchronousSession(AnalysisOptionsImpl(), DeclaredVariables()),
-    SourceFactory([DartUriResolver(sdk)]),
+  final logger = PerformanceLog(StringBuffer());
+  final scheduler = AnalysisDriverScheduler(logger);
+  final analysisDriver = AnalysisDriver(
+    scheduler: scheduler,
+    logger: logger,
+    resourceProvider: resourceProvider,
+    byteStore: MemoryByteStore(),
+    sourceFactory: SourceFactory([
+      DartUriResolver(sdk),
+    ]),
+    analysisOptions: AnalysisOptionsImpl(),
+    packages: Packages({}),
   );
+  scheduler.start();
 
-  return _Builder(
-    analysisContext,
-    sdk.allowedExperimentsJson,
-    sdk.languageVersion,
-    librarySources,
-  ).build();
-}
+  final analysisSession = analysisDriver.currentSession;
+  final elementFactory = analysisDriver.libraryContext.elementFactory;
 
-class _Builder {
-  final AnalysisContextImpl context;
-  final String allowedExperimentsJson;
-  final Iterable<Source> librarySources;
+  final bundleWriter = BundleWriter(
+    elementFactory.dynamicRef,
+  );
+  final packageBuilder = PackageBundleBuilder();
 
-  final Set<String> libraryUris = <String>{};
-  final List<LinkInputLibrary> inputLibraries = [];
+  for (final uriStr in sdk.uris) {
+    final libraryResult = await analysisSession.getLibraryByUri(uriStr);
+    libraryResult as LibraryElementResult;
+    final libraryElement = libraryResult.element as LibraryElementImpl;
+    bundleWriter.writeLibraryElement(libraryElement);
 
-  late final AllowedExperiments allowedExperiments;
-  Version languageVersion;
-
-  _Builder(
-    this.context,
-    this.allowedExperimentsJson,
-    this.languageVersion,
-    this.librarySources,
-  ) {
-    allowedExperiments = parseAllowedExperiments(allowedExperimentsJson);
-  }
-
-  /// Build the linked bundle and return its bytes.
-  Future<Uint8List> build() async {
-    librarySources.forEach(_addLibrary);
-
-    var elementFactory = LinkedElementFactory(
-      context,
-      AnalysisSessionImpl(
-        _FakeAnalysisDriver(),
-      ),
-      Reference.root(),
-    );
-
-    var linkResult = await link2(
-      elementFactory: elementFactory,
-      inputLibraries: inputLibraries,
-      performance: OperationPerformanceImpl('link'),
-    );
-
-    var bundleBuilder = PackageBundleBuilder();
-    for (var library in inputLibraries) {
-      bundleBuilder.addLibrary(
-        library.uriStr,
-        library.units.map((e) => e.uriStr).toList(),
-      );
-    }
-    return bundleBuilder.finish(
-      resolutionBytes: linkResult.resolutionBytes,
-      sdk: PackageBundleSdk(
-        languageVersionMajor: languageVersion.major,
-        languageVersionMinor: languageVersion.minor,
-        allowedExperimentsJson: allowedExperimentsJson,
-      ),
+    packageBuilder.addLibrary(
+      uriStr,
+      libraryElement.units.map((e) {
+        return e.source.uri.toString();
+      }).toList(),
     );
   }
 
-  void _addLibrary(Source source) {
-    String uriStr = source.uri.toString();
-    if (!libraryUris.add(uriStr)) {
-      return;
-    }
+  final writeWriterResult = bundleWriter.finish();
 
-    var inputUnits = <LinkInputUnit>[];
-
-    CompilationUnit definingUnit = _parse(source);
-    inputUnits.add(
-      LinkInputUnit(
-        partDirectiveIndex: null,
-        source: source,
-        isSynthetic: false,
-        unit: definingUnit,
-      ),
-    );
-
-    var partDirectiveIndex = 0;
-    for (Directive directive in definingUnit.directives) {
-      if (directive is NamespaceDirective) {
-        String libUri = directive.uri.stringValue!;
-        Source libSource = context.sourceFactory.resolveUri(source, libUri)!;
-        _addLibrary(libSource);
-      } else if (directive is PartDirective) {
-        String partUri = directive.uri.stringValue!;
-        Source partSource = context.sourceFactory.resolveUri(source, partUri)!;
-        CompilationUnit partUnit = _parse(partSource);
-        inputUnits.add(
-          LinkInputUnit(
-            partUriStr: partUri,
-            partDirectiveIndex: partDirectiveIndex++,
-            source: partSource,
-            isSynthetic: false,
-            unit: partUnit,
-          ),
-        );
-      }
-    }
-
-    inputLibraries.add(
-      LinkInputLibrary(
-        source: source,
-        units: inputUnits,
-      ),
-    );
-  }
-
-  /// Return the [FeatureSet] for the given [uri], must be a `dart:` URI.
-  FeatureSet _featureSet(Uri uri) {
-    if (uri.isScheme('dart')) {
-      var pathSegments = uri.pathSegments;
-      if (pathSegments.isNotEmpty) {
-        var libraryName = pathSegments.first;
-        var experiments = allowedExperiments.forSdkLibrary(libraryName);
-        return FeatureSet.fromEnableFlags2(
-          sdkLanguageVersion: languageVersion,
-          flags: experiments,
-        );
-      }
-    }
-    throw StateError('Expected a valid dart: URI: $uri');
-  }
-
-  String _getContent(Source source) {
-    var uriStr = '${source.uri}';
-    var content = source.contents.data;
-
-    // https://github.com/google/json_serializable.dart/issues/692
-    // SDK 2.9 was released with the syntax that we later decided to remove.
-    // But the current analyzer still says that it supports SDK 2.9, so we
-    // have to be able to handle this code. We do this by rewriting it into
-    // the syntax that we support now.
-    if (uriStr == 'dart:core/uri.dart') {
-      return content.replaceAll(
-        'String? charsetName = parameters?.["charset"];',
-        'String? charsetName = parameters? ["charset"];',
-      );
-    }
-    if (uriStr == 'dart:_http/http_headers.dart') {
-      return content.replaceAll(
-        'return _originalHeaderNames?.[name] ?? name;',
-        'return _originalHeaderNames? [name] ?? name;',
-      );
-    }
-
-    return content;
-  }
-
-  CompilationUnit _parse(Source source) {
-    var result = parseString(
-      content: _getContent(source),
-      featureSet: _featureSet(source.uri),
-      throwIfDiagnostics: false,
-      path: source.fullName,
-    );
-
-    if (result.errors.isNotEmpty) {
-      var errorsStr = result.errors.map((e) {
-        var location = result.lineInfo.getLocation(e.offset);
-        return '${source.fullName}:$location - ${e.message}';
-      }).join('\n');
-      throw StateError(
-        'Unexpected diagnostics:\n$errorsStr',
-      );
-    }
-
-    var unit = result.unit as CompilationUnitImpl;
-    unit.languageVersion = LibraryLanguageVersion(
-      package: languageVersion,
-      override: null,
-    );
-
-    return result.unit;
-  }
-}
-
-class _FakeAnalysisDriver implements AnalysisDriver {
-  @override
-  noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+  return packageBuilder.finish(
+    resolutionBytes: writeWriterResult.resolutionBytes,
+    sdk: PackageBundleSdk(
+      languageVersionMajor: sdk.languageVersion.major,
+      languageVersionMinor: sdk.languageVersion.minor,
+      allowedExperimentsJson: sdk.allowedExperimentsJson,
+    ),
+  );
 }
diff --git a/pkg/analyzer/lib/src/dart/sdk/sdk.dart b/pkg/analyzer/lib/src/dart/sdk/sdk.dart
index bf547a3..a8f9db7 100644
--- a/pkg/analyzer/lib/src/dart/sdk/sdk.dart
+++ b/pkg/analyzer/lib/src/dart/sdk/sdk.dart
@@ -146,6 +146,32 @@
 
   /// TODO(scheglov) This name is misleading, returns `dart:foo/bar.dart`.
   String? _getPath(File file) {
+    // TODO(scheglov) Ideally, all `SdkLibrary` should have `File`, with
+    // an absolute path, not a relative `path`. For now, we do this only
+    // for building SDK summary with `dart:ui`, included from outside
+    // of the SDK root.
+    for (final library in libraryMap.sdkLibraries) {
+      final pathContext = resourceProvider.pathContext;
+      if (pathContext.isAbsolute(library.path)) {
+        if (library.path == file.path) {
+          return library.shortName;
+        }
+      }
+    }
+    for (final library in libraryMap.sdkLibraries) {
+      final pathContext = resourceProvider.pathContext;
+      if (pathContext.isAbsolute(library.path)) {
+        final libraryFile = resourceProvider.getFile(library.path);
+        final libraryFolder = libraryFile.parent;
+        if (libraryFolder.contains(file.path)) {
+          final relPath = pathContext
+              .relative(file.path, from: libraryFolder.path)
+              .replaceAll(separator, '/');
+          return '${library.shortName}/$relPath';
+        }
+      }
+    }
+
     List<SdkLibrary> libraries = libraryMap.sdkLibraries;
     int length = libraries.length;
     String? filePath = getRelativePathFromFile(file);
diff --git a/pkg/analyzer/test/dart/sdk/build_sdk_summary_test.dart b/pkg/analyzer/test/dart/sdk/build_sdk_summary_test.dart
index ea020f8..c48c7c7 100644
--- a/pkg/analyzer/test/dart/sdk/build_sdk_summary_test.dart
+++ b/pkg/analyzer/test/dart/sdk/build_sdk_summary_test.dart
@@ -36,8 +36,14 @@
 class NotObject {}
 ''');
     newFile('${skyEngineLib.path}/ui/ui.dart', r'''
+library dart.ui;
+part 'text.dart';
 class Offset {}
 ''');
+    newFile('${skyEngineLib.path}/ui/text.dart', r'''
+part of dart.ui;
+class FontStyle {}
+''');
     final embedderFile = newFile('${skyEngineLib.path}/_embedder.yaml', r'''
 embedded_libs:
   "dart:core": "core/core.dart"
@@ -83,6 +89,7 @@
     expect(dartAsync.getType('Stream'), isNotNull);
     expect(dartCore.getType('String'), isNotNull);
     expect(dartMath.getType('Random'), isNotNull);
+    expect(dartUi.getType('FontStyle'), isNotNull);
     expect(dartUi.getType('Offset'), isNotNull);
   }
 
diff --git a/tools/VERSION b/tools/VERSION
index e8c8999..2690193 100644
--- a/tools/VERSION
+++ b/tools/VERSION
@@ -27,5 +27,5 @@
 MAJOR 2
 MINOR 18
 PATCH 0
-PRERELEASE 150
+PRERELEASE 151
 PRERELEASE_PATCH 0
\ No newline at end of file