Library canonicalLibrary

Source

Library get canonicalLibrary {
  // This is not accurate if we are constructing the Package.
  assert(package.allLibrariesAdded);
  // Since we're looking for a library, find the [Element] immediately
  // contained by a [CompilationUnitElement] in the tree.
  Element topLevelElement = element;
  while (topLevelElement != null &&
      topLevelElement.enclosingElement is! CompilationUnitElement) {
    topLevelElement = topLevelElement.enclosingElement;
  }

  if (!_canonicalLibraryIsSet) {
    if (!package.libraries.contains(definingLibrary)) {
      List<Library> candidateLibraries = package
          .libraryElementReexportedBy[definingLibrary.element]
          ?.toList();
      if (candidateLibraries != null) {
        candidateLibraries = candidateLibraries.where((l) {
          Element lookup = (l.element as LibraryElement)
              .exportNamespace
              .definedNames[topLevelElement?.name];
          if (lookup is PropertyAccessorElement)
            lookup = (lookup as PropertyAccessorElement).variable;
          if (topLevelElement == lookup) return true;
          return false;
        }).toList();
        // If path inspection or other disambiguation heuristics are needed,
        // they should go here.
        if (candidateLibraries.length > 1) {
          warn(PackageWarning.ambiguousReexport,
              message: "${candidateLibraries.map((l) => l.name)}");
        }
        if (candidateLibraries.isNotEmpty)
          _canonicalLibrary = candidateLibraries.first;
      }
    } else {
      _canonicalLibrary = definingLibrary;
    }
    if (this is Inheritable) {
      if ((this as Inheritable).isInherited && _canonicalLibrary == null) {
        // In the event we've inherited a field from an object that isn't directly reexported,
        // we may need to pretend we are canonical for this.
        _canonicalLibrary = library;
      }
    }
    _canonicalLibraryIsSet = true;
  }
  return _canonicalLibrary;
}