-
Notifications
You must be signed in to change notification settings - Fork 121
/
Copy pathlibrary.dart
665 lines (579 loc) · 20.6 KB
/
library.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
// Copyright (c) 2019, 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 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type_system.dart';
import 'package:analyzer/dart/element/visitor.dart';
import 'package:analyzer/source/line_info.dart';
import 'package:analyzer/src/dart/analysis/driver.dart';
import 'package:analyzer/src/dart/element/inheritance_manager3.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:dartdoc/src/model/model.dart';
import 'package:dartdoc/src/package_meta.dart' show PackageMeta;
import 'package:dartdoc/src/warnings.dart';
import 'package:path/path.dart' as path;
import 'package:quiver/iterables.dart' as quiver;
/// Find all hashable children of a given element that are defined in the
/// [LibraryElement] given at initialization.
class _HashableChildLibraryElementVisitor
extends GeneralizingElementVisitor<void> {
final void Function(Element) libraryProcessor;
_HashableChildLibraryElementVisitor(this.libraryProcessor);
@override
void visitElement(Element element) {
libraryProcessor(element);
super.visitElement(element);
return null;
}
@override
void visitExportElement(ExportElement element) {
// [ExportElement]s are not always hashable; skip them.
return null;
}
@override
void visitImportElement(ImportElement element) {
// [ImportElement]s are not always hashable; skip them.
return null;
}
@override
void visitParameterElement(ParameterElement element) {
// [ParameterElement]s without names do not provide sufficiently distinct
// hashes / comparison, so just skip them all. (dart-lang/sdk#30146)
return null;
}
}
class Library extends ModelElement with Categorization, TopLevelContainer {
List<TopLevelVariable> _variables;
List<Element> _exportedAndLocalElements;
String _name;
factory Library(LibraryElement element, PackageGraph packageGraph) {
return packageGraph.findButDoNotCreateLibraryFor(element);
}
Library.fromLibraryResult(ResolvedLibraryResult libraryResult,
PackageGraph packageGraph, this._package)
: super(libraryResult.element, null, packageGraph, null) {
if (element == null) throw ArgumentError.notNull('element');
// Initialize [packageGraph]'s cache of ModelNodes for relevant
// elements in this library.
Map<String, CompilationUnit> _compilationUnitMap = Map();
_compilationUnitMap.addEntries(libraryResult.units
.map((ResolvedUnitResult u) => MapEntry(u.path, u.unit)));
_HashableChildLibraryElementVisitor((Element e) =>
packageGraph.populateModelNodeFor(e, _compilationUnitMap))
.visitElement(element);
// Initialize the list of elements defined in this library and
// exported via its export directives.
Set<Element> exportedAndLocalElements =
element.exportNamespace.definedNames.values.toSet();
// TODO(jcollins-g): Consider switch to [_libraryElement.topLevelElements].
exportedAndLocalElements
.addAll(getDefinedElements(element.definingCompilationUnit));
for (CompilationUnitElement cu in element.parts) {
exportedAndLocalElements.addAll(getDefinedElements(cu));
}
_exportedAndLocalElements = exportedAndLocalElements.toList();
_package.allLibraries.add(this);
}
static Iterable<Element> getDefinedElements(
CompilationUnitElement compilationUnit) {
return quiver.concat([
compilationUnit.accessors,
compilationUnit.enums,
compilationUnit.extensions,
compilationUnit.functions,
compilationUnit.functionTypeAliases,
compilationUnit.mixins,
compilationUnit.topLevelVariables,
compilationUnit.types,
]);
}
List<String> _allOriginalModelElementNames;
bool get isInSdk => element.isInSdk;
final Package _package;
@override
Package get package {
// Everything must be in a package. TODO(jcollins-g): Support other things
// that look like packages.
assert(_package != null);
return _package;
}
/// [allModelElements] resolved to their original names.
///
/// A collection of [ModelElement.fullyQualifiedName]s for [ModelElement]s
/// documented with this library, but these ModelElements and names correspond
/// to the defining library where each originally came from with respect
/// to inheritance and reexporting. Most useful for error reporting.
Iterable<String> get allOriginalModelElementNames {
if (_allOriginalModelElementNames == null) {
_allOriginalModelElementNames = allModelElements.map((e) {
Accessor getter;
Accessor setter;
if (e is GetterSetterCombo) {
if (e.hasGetter) {
getter = ModelElement.fromElement(e.getter.element, packageGraph);
}
if (e.hasSetter) {
setter = ModelElement.fromElement(e.setter.element, packageGraph);
}
}
return ModelElement.from(
e.element,
packageGraph.findButDoNotCreateLibraryFor(e.element),
packageGraph,
getter: getter,
setter: setter)
.fullyQualifiedName;
}).toList();
}
return _allOriginalModelElementNames;
}
@override
CharacterLocation get characterLocation {
if (element.nameOffset == -1) {
assert(isAnonymous,
'Only anonymous libraries are allowed to have no declared location');
return CharacterLocation(1, 1);
}
return super.characterLocation;
}
@override
CompilationUnitElement get compilationUnitElement =>
element.definingCompilationUnit;
@override
Iterable<Class> get classes => allClasses.where((c) => !c.isErrorOrException);
@override
LibraryElement get element => super.element;
List<Extension> _extensions;
@override
Iterable<Extension> get extensions {
if (_extensions == null) {
_extensions = _exportedAndLocalElements
.whereType<ExtensionElement>()
.map((e) => ModelElement.from(e, this, packageGraph) as Extension)
.toList(growable: false)
..sort(byName);
}
return _extensions;
}
SdkLibrary get sdkLib {
if (packageGraph.sdkLibrarySources.containsKey(element.librarySource)) {
return packageGraph.sdkLibrarySources[element.librarySource];
}
return null;
}
@override
bool get isPublic {
if (!super.isPublic) return false;
if (sdkLib != null && (sdkLib.isInternal || !sdkLib.isDocumented)) {
return false;
}
if (config.isLibraryExcluded(name) ||
config.isLibraryExcluded(element.librarySource.uri.toString())) {
return false;
}
return true;
}
List<TopLevelVariable> _constants;
@override
Iterable<TopLevelVariable> get constants {
if (_constants == null) {
// _getVariables() is already sorted.
_constants =
_getVariables().where((v) => v.isConst).toList(growable: false);
}
return _constants;
}
Set<Library> _packageImportedExportedLibraries;
/// Returns all libraries either imported by or exported by any public library
/// this library's package. (Not [PackageGraph], but sharing a package name).
///
/// Note: will still contain non-public libraries because those can be
/// imported or exported.
// TODO(jcollins-g): move this to [Package] once it really knows about
// more than one package.
Set<Library> get packageImportedExportedLibraries {
if (_packageImportedExportedLibraries == null) {
_packageImportedExportedLibraries = Set();
packageGraph.publicLibraries
.where((l) => l.packageName == packageName)
.forEach((l) {
_packageImportedExportedLibraries.addAll(l.importedExportedLibraries);
});
}
return _packageImportedExportedLibraries;
}
Set<Library> _importedExportedLibraries;
/// Returns all libraries either imported by or exported by this library,
/// recursively.
Set<Library> get importedExportedLibraries {
if (_importedExportedLibraries == null) {
_importedExportedLibraries = Set();
Set<LibraryElement> importedExportedLibraryElements = Set();
importedExportedLibraryElements.addAll(element.importedLibraries);
importedExportedLibraryElements.addAll(element.exportedLibraries);
for (LibraryElement l in importedExportedLibraryElements) {
Library lib = ModelElement.from(l, library, packageGraph);
_importedExportedLibraries.add(lib);
_importedExportedLibraries.addAll(lib.importedExportedLibraries);
}
}
return _importedExportedLibraries;
}
Map<String, Set<Library>> _prefixToLibrary;
/// Map of import prefixes ('import "foo" as prefix;') to [Library].
Map<String, Set<Library>> get prefixToLibrary {
if (_prefixToLibrary == null) {
_prefixToLibrary = {};
// It is possible to have overlapping prefixes.
for (ImportElement i in element.imports) {
// Ignore invalid imports.
if (i.prefix?.name != null && i.importedLibrary != null) {
_prefixToLibrary.putIfAbsent(i.prefix?.name, () => Set());
_prefixToLibrary[i.prefix?.name]
.add(ModelElement.from(i.importedLibrary, library, packageGraph));
}
}
}
return _prefixToLibrary;
}
String _dirName;
String get dirName {
if (_dirName == null) {
_dirName = name;
if (isAnonymous) {
_dirName = nameFromPath;
}
_dirName = _dirName.replaceAll(':', '-').replaceAll('/', '_');
}
return _dirName;
}
Set<String> _canonicalFor;
Set<String> get canonicalFor {
if (_canonicalFor == null) {
// TODO(jcollins-g): restructure to avoid using side effects.
buildDocumentationAddition(documentationComment);
}
return _canonicalFor;
}
/// Hide canonicalFor from doc while leaving a note to ourselves to
/// help with ambiguous canonicalization determination.
///
/// Example:
/// {@canonicalFor libname.ClassName}
@override
String buildDocumentationAddition(String rawDocs) {
rawDocs = super.buildDocumentationAddition(rawDocs);
Set<String> newCanonicalFor = Set();
Set<String> notFoundInAllModelElements = Set();
final canonicalRegExp = RegExp(r'{@canonicalFor\s([^}]+)}');
rawDocs = rawDocs.replaceAllMapped(canonicalRegExp, (Match match) {
newCanonicalFor.add(match.group(1));
notFoundInAllModelElements.add(match.group(1));
return '';
});
if (notFoundInAllModelElements.isNotEmpty) {
notFoundInAllModelElements.removeAll(allOriginalModelElementNames);
}
for (String notFound in notFoundInAllModelElements) {
warn(PackageWarning.ignoredCanonicalFor, message: notFound);
}
// TODO(jcollins-g): warn if a macro/tool _does_ generate an unexpected
// canonicalFor?
if (_canonicalFor == null) {
_canonicalFor = newCanonicalFor;
}
return rawDocs;
}
/// Libraries are not enclosed by anything.
@override
ModelElement get enclosingElement => null;
List<Enum> _enums;
@override
List<Enum> get enums {
if (_enums == null) {
_enums = _exportedAndLocalElements
.whereType<ClassElement>()
.where((element) => element.isEnum)
.map((e) => ModelElement.from(e, this, packageGraph) as Enum)
.toList(growable: false)
..sort(byName);
}
return _enums;
}
List<Mixin> _mixins;
@override
List<Mixin> get mixins {
if (_mixins == null) {
/// Can not be [MixinElementImpl] because [ClassHandle]s are sometimes
/// returned from _exportedElements.
_mixins = _exportedAndLocalElements
.whereType<ClassElement>()
.where((ClassElement c) => c.isMixin)
.map((e) => ModelElement.from(e, this, packageGraph) as Mixin)
.toList(growable: false)
..sort(byName);
}
return _mixins;
}
List<Class> _exceptions;
@override
List<Class> get exceptions {
if (_exceptions == null) {
_exceptions =
allClasses.where((c) => c.isErrorOrException).toList(growable: false);
}
return _exceptions;
}
@override
String get fileName => '$dirName-library.$fileType';
@override
String get filePath => '${library.dirName}/$fileName';
List<ModelFunction> _functions;
@override
List<ModelFunction> get functions {
if (_functions == null) {
_functions =
_exportedAndLocalElements.whereType<FunctionElement>().map((e) {
return ModelElement.from(e, this, packageGraph) as ModelFunction;
}).toList(growable: false)
..sort(byName);
}
return _functions;
}
@override
String get href {
if (!identical(canonicalModelElement, this)) {
return canonicalModelElement?.href;
}
return '${package.baseHref}$filePath';
}
InheritanceManager3 _inheritanceManager;
InheritanceManager3 get inheritanceManager {
if (_inheritanceManager == null) {
_inheritanceManager = InheritanceManager3();
}
return _inheritanceManager;
}
bool get isAnonymous => element.name == null || element.name.isEmpty;
@override
String get kind => 'library';
@override
Library get library => this;
@override
String get name {
if (_name == null) {
_name = getLibraryName(element);
}
return _name;
}
String _nameFromPath;
/// Generate a name for this library based on its location.
///
/// nameFromPath provides filename collision-proofing for anonymous libraries
/// by incorporating more from the location of the anonymous library into
/// the name calculation. Simple cases (such as an anonymous library in
/// 'lib') are the same, but this will include slashes and possibly colons
/// for anonymous libraries in subdirectories or other packages.
String get nameFromPath {
if (_nameFromPath == null) {
_nameFromPath = getNameFromPath(element, packageGraph.driver, package);
}
return _nameFromPath;
}
/// The real package, as opposed to the package we are documenting it with,
/// [PackageGraph.name]
String get packageName => packageMeta?.name ?? '';
/// The real packageMeta, as opposed to the package we are documenting with.
PackageMeta _packageMeta;
PackageMeta get packageMeta {
if (_packageMeta == null) {
_packageMeta = PackageMeta.fromElement(element, config.sdkDir);
}
return _packageMeta;
}
List<TopLevelVariable> _properties;
/// All variables ("properties") except constants.
@override
Iterable<TopLevelVariable> get properties {
if (_properties == null) {
_properties =
_getVariables().where((v) => !v.isConst).toList(growable: false);
}
return _properties;
}
List<Typedef> _typedefs;
@override
List<Typedef> get typedefs {
if (_typedefs == null) {
_typedefs = _exportedAndLocalElements
.whereType<FunctionTypeAliasElement>()
.map((e) => ModelElement.from(e, this, packageGraph) as Typedef)
.toList(growable: false)
..sort(byName);
}
return _typedefs;
}
TypeSystem get typeSystem => element.typeSystem;
List<Class> _classes;
List<Class> get allClasses {
if (_classes == null) {
_classes = _exportedAndLocalElements
.whereType<ClassElement>()
.where((e) => !e.isMixin && !e.isEnum)
.map((e) => ModelElement.from(e, this, packageGraph) as Class)
.toList(growable: false)
..sort(byName);
}
return _classes;
}
Class getClassByName(String name) {
return allClasses.firstWhere((it) => it.name == name, orElse: () => null);
}
List<TopLevelVariable> _getVariables() {
if (_variables == null) {
Set<TopLevelVariableElement> elements = _exportedAndLocalElements
.whereType<TopLevelVariableElement>()
.toSet();
elements.addAll(_exportedAndLocalElements
.whereType<PropertyAccessorElement>()
.map((a) => a.variable));
_variables = [];
for (TopLevelVariableElement element in elements) {
Accessor getter;
if (element.getter != null) {
getter = ModelElement.from(element.getter, this, packageGraph);
}
Accessor setter;
if (element.setter != null) {
setter = ModelElement.from(element.setter, this, packageGraph);
}
ModelElement me = ModelElement.from(element, this, packageGraph,
getter: getter, setter: setter);
_variables.add(me);
}
_variables.sort(byName);
}
return _variables;
}
/// Reverses URIs if needed to get a package URI.
/// Not the same as [PackageGraph.name] because there we always strip all
/// path components; this function only strips the package prefix if the
/// library is part of the default package or if it is being documented
/// remotely.
static String getNameFromPath(
LibraryElement element, AnalysisDriver driver, Package package) {
String name;
if (element.source.uri.toString().startsWith('dart:')) {
name = element.source.uri.toString();
} else {
name = driver.sourceFactory.restoreUri(element.source).toString();
}
PackageMeta hidePackage;
if (package.documentedWhere == DocumentLocation.remote) {
hidePackage = package.packageMeta;
} else {
hidePackage = package.packageGraph.packageMeta;
}
// restoreUri must not result in another file URI.
assert(!name.startsWith('file:'));
String defaultPackagePrefix = 'package:$hidePackage/';
if (name.startsWith(defaultPackagePrefix)) {
name = name.substring(defaultPackagePrefix.length, name.length);
}
if (name.endsWith('.dart')) {
name = name.substring(0, name.length - '.dart'.length);
}
assert(!name.startsWith('file:'));
return name;
}
static String getLibraryName(LibraryElement element) {
var source = element.source;
if (source.uri.isScheme('dart')) {
return '${source.uri}';
}
var name = element.name;
if (name != null && name.isNotEmpty) {
return name;
}
name = path.basename(source.fullName);
if (name.endsWith('.dart')) {
name = name.substring(0, name.length - '.dart'.length);
}
return name;
}
Map<String, Set<ModelElement>> _modelElementsNameMap;
/// Map of [fullyQualifiedNameWithoutLibrary] to all matching [ModelElement]s
/// in this library. Used for code reference lookups.
Map<String, Set<ModelElement>> get modelElementsNameMap {
if (_modelElementsNameMap == null) {
_modelElementsNameMap = Map<String, Set<ModelElement>>();
allModelElements.forEach((ModelElement modelElement) {
_modelElementsNameMap.putIfAbsent(
modelElement.fullyQualifiedNameWithoutLibrary, () => Set());
_modelElementsNameMap[modelElement.fullyQualifiedNameWithoutLibrary]
.add(modelElement);
});
}
return _modelElementsNameMap;
}
Map<Element, Set<ModelElement>> _modelElementsMap;
Map<Element, Set<ModelElement>> get modelElementsMap {
if (_modelElementsMap == null) {
Iterable<ModelElement> results = quiver.concat([
library.constants,
library.functions,
library.properties,
library.typedefs,
library.extensions.expand((e) {
return quiver.concat([
[e],
e.allModelElements
]);
}),
library.allClasses.expand((c) {
return quiver.concat([
[c],
c.allModelElements
]);
}),
library.enums.expand((e) {
return quiver.concat([
[e],
e.allModelElements
]);
}),
library.mixins.expand((m) {
return quiver.concat([
[m],
m.allModelElements
]);
}),
]);
_modelElementsMap = Map<Element, Set<ModelElement>>();
results.forEach((modelElement) {
_modelElementsMap.putIfAbsent(modelElement.element, () => Set());
_modelElementsMap[modelElement.element].add(modelElement);
});
_modelElementsMap.putIfAbsent(element, () => Set());
_modelElementsMap[element].add(this);
}
return _modelElementsMap;
}
List<ModelElement> _allModelElements;
Iterable<ModelElement> get allModelElements {
if (_allModelElements == null) {
_allModelElements = [];
for (Set<ModelElement> modelElements in modelElementsMap.values) {
_allModelElements.addAll(modelElements);
}
}
return _allModelElements;
}
List<ModelElement> _allCanonicalModelElements;
Iterable<ModelElement> get allCanonicalModelElements {
return (_allCanonicalModelElements ??=
allModelElements.where((e) => e.isCanonical).toList());
}
}