forked from dart-lang/dartdoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel_element.dart
1720 lines (1540 loc) · 61.3 KB
/
model_element.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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2014, 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.
/// The models used to represent Dart code.
library dartdoc.models;
import 'dart:async';
import 'dart:collection' show UnmodifiableListView;
import 'dart:convert';
import 'dart:io';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/source/line_info.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/member.dart'
show ExecutableMember, Member, ParameterMember;
import 'package:args/args.dart';
import 'package:collection/collection.dart';
import 'package:crypto/crypto.dart';
import 'package:dartdoc/src/dartdoc_options.dart';
import 'package:dartdoc/src/element_type.dart';
import 'package:dartdoc/src/logging.dart';
import 'package:dartdoc/src/model/feature_set.dart';
import 'package:dartdoc/src/model/model.dart';
import 'package:dartdoc/src/model_utils.dart' as utils;
import 'package:dartdoc/src/render/model_element_renderer.dart';
import 'package:dartdoc/src/render/parameter_renderer.dart';
import 'package:dartdoc/src/render/source_code_renderer.dart';
import 'package:dartdoc/src/source_linker.dart';
import 'package:dartdoc/src/tuple.dart';
import 'package:dartdoc/src/utils.dart';
import 'package:dartdoc/src/warnings.dart';
import 'package:path/path.dart' as path;
/// Items mapped less than zero will sort before custom annotations.
/// Items mapped above zero are sorted after custom annotations.
/// Items mapped to zero will sort alphabetically among custom annotations.
/// Custom annotations are assumed to be any annotation or feature not in this
/// map.
const Map<String, int> featureOrder = {
'read-only': 1,
'write-only': 1,
'read / write': 1,
'covariant': 2,
'final': 2,
'late': 2,
'inherited': 3,
'inherited-getter': 3,
'inherited-setter': 3,
'override': 3,
'override-getter': 3,
'override-setter': 3,
'extended': 3,
};
int byFeatureOrdering(String a, String b) {
var scoreA = 0;
var scoreB = 0;
if (featureOrder.containsKey(a)) scoreA = featureOrder[a];
if (featureOrder.containsKey(b)) scoreB = featureOrder[b];
if (scoreA < scoreB) return -1;
if (scoreA > scoreB) return 1;
return compareAsciiLowerCaseNatural(a, b);
}
/// This doc may need to be processed in case it has a template or html
/// fragment.
final needsPrecacheRegExp = RegExp(r'{@(template|tool|inject-html)');
final templateRegExp = RegExp(
r'[ ]*{@template\s+(.+?)}([\s\S]+?){@endtemplate}[ ]*\n?',
multiLine: true);
final htmlRegExp = RegExp(
r'[ ]*{@inject-html\s*}([\s\S]+?){@end-inject-html}[ ]*\n?',
multiLine: true);
final htmlInjectRegExp = RegExp(r'<dartdoc-html>([a-f0-9]+)</dartdoc-html>');
// Matches all tool directives (even some invalid ones). This is so
// we can give good error messages if the directive is malformed, instead of
// just silently emitting it as-is.
final basicToolRegExp = RegExp(
r'[ ]*{@tool\s+([^}]+)}\n?([\s\S]+?)\n?{@end-tool}[ ]*\n?',
multiLine: true);
/// Regexp to take care of splitting arguments, and handling the quotes
/// around arguments, if any.
///
/// Match group 1 is the "foo=" (or "--foo=") part of the option, if any.
/// Match group 2 contains the quote character used (which is discarded).
/// Match group 3 is a quoted arg, if any, without the quotes.
/// Match group 4 is the unquoted arg, if any.
final RegExp argMatcher = RegExp(r'([a-zA-Z\-_0-9]+=)?' // option name
r'(?:' // Start a new non-capture group for the two possibilities.
r'''(["'])((?:\\{2})*|(?:.*?[^\\](?:\\{2})*))\2|''' // with quotes.
r'([^ ]+))'); // without quotes.
final macroRegExp = RegExp(r'{@macro\s+([^}]+)}');
// TODO(jcollins-g): Implement resolution per ECMA-408 4th edition, page 39 #22.
/// Resolves this very rare case incorrectly by picking the closest element in
/// the inheritance and interface chains from the analyzer.
ModelElement resolveMultiplyInheritedElement(
MultiplyInheritedExecutableElement e,
Library library,
PackageGraph packageGraph,
Class enclosingClass) {
var inheritables = e.inheritedElements
.map((ee) => ModelElement.fromElement(ee, packageGraph) as Inheritable);
Inheritable foundInheritable;
var lowIndex = enclosingClass.inheritanceChain.length;
for (var inheritable in inheritables) {
var index =
enclosingClass.inheritanceChain.indexOf(inheritable.enclosingElement);
if (index < lowIndex) {
foundInheritable = inheritable;
lowIndex = index;
}
}
return ModelElement.from(foundInheritable.element, library, packageGraph,
enclosingContainer: enclosingClass);
}
/// This class is the foundation of Dartdoc's model for source code.
/// All ModelElements are contained within a [PackageGraph], and laid out in a
/// structure that mirrors the availability of identifiers in the various
/// namespaces within that package. For example, multiple [Class] objects
/// for a particular identifier ([ModelElement.element]) may show up in
/// different [Library]s as the identifier is reexported.
///
/// However, ModelElements have an additional concept vital to generating
/// documentation: canonicalization.
///
/// A ModelElement is canonical if it is the element in the namespace where that
/// element 'comes from' in the public interface to this [PackageGraph]. That often
/// means the [ModelElement.library] is contained in [PackageGraph.libraries], but
/// there are many exceptions and ambiguities the code tries to address here.
///
/// Non-canonical elements should refer to their canonical counterparts, making
/// it easy to calculate links via [ModelElement.href] without having to
/// know in a particular namespace which elements are canonical or not.
/// A number of [PackageGraph] methods, such as [PackageGraph.findCanonicalModelElementFor]
/// can help with this.
///
/// When documenting, Dartdoc should only write out files corresponding to
/// canonical instances of ModelElement ([ModelElement.isCanonical]). This
/// helps prevent subtle bugs as generated output for a non-canonical
/// ModelElement will reference itself as part of the "wrong" [Library]
/// from the public interface perspective.
abstract class ModelElement extends Canonicalization
with
Privacy,
Warnable,
Locatable,
Nameable,
SourceCodeMixin,
Indexable,
FeatureSet
implements Comparable, Documentable {
final Element _element;
// TODO(jcollins-g): This really wants a "member that has a type" class.
final Member _originalMember;
final Library _library;
ElementType _modelType;
String _rawDocs;
Documentation __documentation;
UnmodifiableListView<Parameter> _parameters;
String _linkedName;
String _fullyQualifiedName;
String _fullyQualifiedNameWithoutLibrary;
// TODO(jcollins-g): make _originalMember optional after dart-lang/sdk#15101
// is fixed.
ModelElement(
this._element, this._library, this._packageGraph, this._originalMember);
factory ModelElement.fromElement(Element e, PackageGraph p) {
var lib = p.findButDoNotCreateLibraryFor(e);
Accessor getter;
Accessor setter;
if (e is PropertyInducingElement) {
getter = e.getter != null ? ModelElement.from(e.getter, lib, p) : null;
setter = e.setter != null ? ModelElement.from(e.setter, lib, p) : null;
}
return ModelElement.from(e, lib, p, getter: getter, setter: setter);
}
// TODO(jcollins-g): this way of using the optional parameter is messy,
// clean that up.
// TODO(jcollins-g): Refactor this into class-specific factories that
// call this one.
// TODO(jcollins-g): Enforce construction restraint.
// TODO(jcollins-g): Allow e to be null and drop extraneous null checks.
// TODO(jcollins-g): Auto-vivify element's defining library for library
// parameter when given a null.
/// Do not construct any ModelElements unless they are from this constructor.
/// Specify enclosingContainer if and only if this is to be an inherited or
/// extended object.
factory ModelElement.from(
Element e, Library library, PackageGraph packageGraph,
{Container enclosingContainer, Accessor getter, Accessor setter}) {
assert(packageGraph != null && e != null);
assert(library != null ||
e is ParameterElement ||
e is TypeParameterElement ||
e is GenericFunctionTypeElementImpl ||
e.kind == ElementKind.DYNAMIC ||
e.kind == ElementKind.NEVER);
Member originalMember;
// TODO(jcollins-g): Refactor object model to instantiate 'ModelMembers'
// for members?
if (e is Member) {
originalMember = e;
e = e.declaration;
}
var key =
Tuple3<Element, Library, Container>(e, library, enclosingContainer);
ModelElement newModelElement;
if (e.kind != ElementKind.DYNAMIC &&
e.kind != ElementKind.NEVER &&
packageGraph.allConstructedModelElements.containsKey(key)) {
newModelElement = packageGraph.allConstructedModelElements[key];
assert(newModelElement.element is! MultiplyInheritedExecutableElement);
} else {
if (e.kind == ElementKind.DYNAMIC) {
newModelElement = Dynamic(e, packageGraph);
}
if (e.kind == ElementKind.NEVER) {
newModelElement = NeverType(e, packageGraph);
}
if (e is MultiplyInheritedExecutableElement) {
newModelElement = resolveMultiplyInheritedElement(
e, library, packageGraph, enclosingContainer);
} else {
if (e is LibraryElement) {
newModelElement = Library(e, packageGraph);
}
// Also handles enums
if (e is ClassElement) {
if (e.isMixin) {
newModelElement = Mixin(e, library, packageGraph);
} else if (e.isEnum) {
newModelElement = Enum(e, library, packageGraph);
} else {
newModelElement = Class(e, library, packageGraph);
}
}
if (e is ExtensionElement) {
newModelElement = Extension(e, library, packageGraph);
}
if (e is FunctionElement) {
newModelElement = ModelFunction(e, library, packageGraph);
} else if (e is GenericFunctionTypeElement) {
assert(e.enclosingElement is GenericTypeAliasElement);
assert(e.enclosingElement.name != '');
newModelElement = ModelFunctionTypedef(e, library, packageGraph);
}
if (e is FunctionTypeAliasElement) {
newModelElement = Typedef(e, library, packageGraph);
}
if (e is FieldElement) {
if (enclosingContainer == null) {
if (e.isEnumConstant) {
var index =
e.computeConstantValue().getField(e.name).toIntValue();
newModelElement = EnumField.forConstant(
index, e, library, packageGraph, getter);
// ignore: unnecessary_cast
} else if (e.enclosingElement is ExtensionElement) {
newModelElement = Field(e, library, packageGraph, getter, setter);
} else if (e.enclosingElement is ClassElement &&
(e.enclosingElement as ClassElement).isEnum) {
newModelElement =
EnumField(e, library, packageGraph, getter, setter);
} else {
newModelElement = Field(e, library, packageGraph, getter, setter);
}
} else {
// EnumFields can't be inherited, so this case is simpler.
newModelElement = Field.inherited(
e, enclosingContainer, library, packageGraph, getter, setter);
}
}
if (e is ConstructorElement) {
newModelElement = Constructor(e, library, packageGraph);
}
if (e is MethodElement && e.isOperator) {
if (enclosingContainer == null) {
newModelElement = Operator(e, library, packageGraph);
} else {
newModelElement = Operator.inherited(
e, enclosingContainer, library, packageGraph,
originalMember: originalMember);
}
}
if (e is MethodElement && !e.isOperator) {
if (enclosingContainer == null) {
newModelElement = Method(e, library, packageGraph);
} else {
newModelElement = Method.inherited(
e, enclosingContainer, library, packageGraph,
originalMember: originalMember);
}
}
if (e is TopLevelVariableElement) {
assert(getter != null || setter != null);
newModelElement =
TopLevelVariable(e, library, packageGraph, getter, setter);
}
if (e is PropertyAccessorElement) {
// TODO(jcollins-g): why test for ClassElement in enclosingElement?
if (e.enclosingElement is ClassElement ||
e is MultiplyInheritedExecutableElement) {
if (enclosingContainer == null) {
newModelElement = ContainerAccessor(e, library, packageGraph);
} else {
newModelElement = ContainerAccessor.inherited(
e, library, packageGraph, enclosingContainer,
originalMember: originalMember);
}
} else {
newModelElement = Accessor(e, library, packageGraph, null);
}
}
if (e is TypeParameterElement) {
newModelElement = TypeParameter(e, library, packageGraph);
}
if (e is ParameterElement) {
newModelElement = Parameter(e, library, packageGraph,
originalMember: originalMember);
}
}
}
if (newModelElement == null) throw 'Unknown type ${e.runtimeType}';
if (enclosingContainer != null) assert(newModelElement is Inheritable);
// TODO(jcollins-g): Reenable Parameter caching when dart-lang/sdk#30146
// is fixed?
if (library != null && newModelElement is! Parameter) {
library.packageGraph.allConstructedModelElements[key] = newModelElement;
if (newModelElement is Inheritable) {
var iKey = Tuple2<Element, Library>(e, library);
library.packageGraph.allInheritableElements.putIfAbsent(iKey, () => {});
library.packageGraph.allInheritableElements[iKey].add(newModelElement);
}
}
if (newModelElement is GetterSetterCombo) {
assert(getter == null || newModelElement?.getter?.enclosingCombo != null);
assert(setter == null || newModelElement?.setter?.enclosingCombo != null);
}
assert(newModelElement.element is! MultiplyInheritedExecutableElement);
return newModelElement;
}
/// Stub for mustache4dart, or it will search enclosing elements to find
/// names for members.
bool get hasCategoryNames => false;
Set<Library> get exportedInLibraries {
return library.packageGraph.libraryElementReexportedBy[element.library];
}
ModelNode _modelNode;
@override
ModelNode get modelNode =>
_modelNode ??= packageGraph.getModelNodeFor(element);
List<String> get annotations => annotationsFromMetadata(element.metadata);
/// Returns linked annotations from a given metadata set, with escaping.
List<String> annotationsFromMetadata(List<ElementAnnotation> md) {
var annotationStrings = <String>[];
if (md == null) return annotationStrings;
for (var a in md) {
var annotation = (const HtmlEscape()).convert(a.toSource());
var annotationElement = a.element;
ClassElement annotationClassElement;
if (annotationElement is ExecutableElement) {
annotationElement =
(annotationElement as ExecutableElement).returnType.element;
}
if (annotationElement is ClassElement) {
annotationClassElement = annotationElement;
}
var annotationModelElement =
packageGraph.findCanonicalModelElementFor(annotationElement);
// annotationElement can be null if the element can't be resolved.
var annotationClass = packageGraph
.findCanonicalModelElementFor(annotationClassElement) as Class;
if (annotationClass == null &&
annotationElement != null &&
annotationClassElement != null) {
annotationClass =
ModelElement.fromElement(annotationClassElement, packageGraph)
as Class;
}
// Some annotations are intended to be invisible (@pragma)
if (annotationClass == null ||
!packageGraph.invisibleAnnotations.contains(annotationClass)) {
if (annotationModelElement != null) {
annotation = annotation.replaceFirst(
annotationModelElement.name, annotationModelElement.linkedName);
}
annotationStrings.add(annotation);
}
}
return annotationStrings;
}
bool _isPublic;
@override
bool get isPublic {
if (_isPublic == null) {
if (name == '') {
_isPublic = false;
} else if (this is! Library && (library == null || !library.isPublic)) {
_isPublic = false;
} else if (enclosingElement is Class &&
!(enclosingElement as Class).isPublic) {
_isPublic = false;
} else if (enclosingElement is Extension &&
!(enclosingElement as Extension).isPublic) {
_isPublic = false;
} else {
var docComment = documentationComment;
if (docComment == null) {
_isPublic = utils.hasPublicName(element);
} else {
_isPublic = utils.hasPublicName(element) &&
!(docComment.contains('@nodoc') ||
docComment.contains('<nodoc>'));
}
}
}
return _isPublic;
}
List<ModelCommentReference> _commentRefs;
@override
List<ModelCommentReference> get commentRefs {
if (_commentRefs == null) {
_commentRefs = [];
for (var from in documentationFrom) {
var checkReferences = <ModelElement>[from];
if (from is Accessor) {
checkReferences.add(from.enclosingCombo);
}
for (var e in checkReferences) {
_commentRefs.addAll(e.modelNode.commentRefs ?? []);
}
}
}
return _commentRefs;
}
DartdocOptionContext _config;
@override
DartdocOptionContext get config {
_config ??=
DartdocOptionContext.fromContextElement(packageGraph.config, element);
return _config;
}
@override
Set<String> get locationPieces {
return Set.from(element.location
.toString()
.split(locationSplitter)
.where((s) => s.isNotEmpty));
}
Set<String> get features {
var allFeatures = <String>{};
allFeatures.addAll(annotations);
// Replace the @override annotation with a feature that explicitly
// indicates whether an override has occurred.
allFeatures.remove('@override');
// Drop the plain "deprecated" annotation, that's indicated via
// strikethroughs. Custom @Deprecated() will still appear.
allFeatures.remove('@deprecated');
// const and static are not needed here because const/static elements get
// their own sections in the doc.
if (isFinal) allFeatures.add('final');
if (isLate) allFeatures.add('late');
return allFeatures;
}
String get featuresAsString {
var allFeatures = features.toList()..sort(byFeatureOrdering);
return allFeatures.join(', ');
}
bool get canHaveParameters =>
element is ExecutableElement ||
element is FunctionTypedElement ||
element is FunctionTypeAliasElement;
ModelElement buildCanonicalModelElement() {
Container preferredClass;
if (enclosingElement is Class || enclosingElement is Extension) {
preferredClass = enclosingElement;
}
return packageGraph.findCanonicalModelElementFor(element,
preferredClass: preferredClass);
}
// Returns the canonical ModelElement for this ModelElement, or null
// if there isn't one.
ModelElement _canonicalModelElement;
ModelElement get canonicalModelElement =>
_canonicalModelElement ??= buildCanonicalModelElement();
List<ModelElement> _documentationFrom;
// TODO(jcollins-g): untangle when mixins can call super
@override
List<ModelElement> get documentationFrom {
_documentationFrom ??= computeDocumentationFrom;
return _documentationFrom;
}
bool get hasSourceHref => sourceHref.isNotEmpty;
String _sourceHref;
String get sourceHref {
_sourceHref ??= SourceLinker.fromElement(this).href();
return _sourceHref;
}
/// Returns the ModelElement(s) from which we will get documentation.
/// Can be more than one if this is a Field composing documentation from
/// multiple Accessors.
///
/// This getter will walk up the inheritance hierarchy
/// to find docs, if the current class doesn't have docs
/// for this element.
List<ModelElement> get computeDocumentationFrom {
List<ModelElement> docFrom;
if (documentationComment == null &&
canOverride() &&
this is Inheritable &&
(this as Inheritable).overriddenElement != null) {
docFrom = (this as Inheritable).overriddenElement.documentationFrom;
} else if (this is Inheritable && (this as Inheritable).isInherited) {
var thisInheritable = (this as Inheritable);
var fromThis = ModelElement.fromElement(
element, thisInheritable.definingEnclosingContainer.packageGraph);
docFrom = fromThis.documentationFrom;
} else {
docFrom = [this];
}
return docFrom;
}
String _buildDocumentationLocal() => _buildDocumentationBaseSync();
/// Override this to add more features to the documentation builder in a
/// subclass.
String buildDocumentationAddition(String docs) => docs ??= '';
/// Separate from _buildDocumentationLocal for overriding.
String _buildDocumentationBaseSync() {
assert(_rawDocs == null,
'reentrant calls to _buildDocumentation* not allowed');
// Do not use the sync method if we need to evaluate tools or templates.
assert(!isCanonical ||
!needsPrecacheRegExp.hasMatch(documentationComment ?? ''));
if (config.dropTextFrom.contains(element.library.name)) {
_rawDocs = '';
} else {
_rawDocs = documentationComment ?? '';
_rawDocs = stripComments(_rawDocs) ?? '';
_rawDocs = _injectExamples(_rawDocs);
_rawDocs = _injectYouTube(_rawDocs);
_rawDocs = _injectAnimations(_rawDocs);
_rawDocs = _stripHtmlAndAddToIndex(_rawDocs);
}
_rawDocs = buildDocumentationAddition(_rawDocs);
return _rawDocs;
}
/// Separate from _buildDocumentationLocal for overriding. Can only be
/// used as part of [PackageGraph.setUpPackageGraph].
Future<String> _buildDocumentationBase() async {
assert(_rawDocs == null,
'reentrant calls to _buildDocumentation* not allowed');
// Do not use the sync method if we need to evaluate tools or templates.
if (config.dropTextFrom.contains(element.library.name)) {
_rawDocs = '';
} else {
_rawDocs = documentationComment ?? '';
_rawDocs = stripComments(_rawDocs) ?? '';
// Must evaluate tools first, in case they insert any other directives.
_rawDocs = await _evaluateTools(_rawDocs);
_rawDocs = _injectExamples(_rawDocs);
_rawDocs = _injectYouTube(_rawDocs);
_rawDocs = _injectAnimations(_rawDocs);
_rawDocs = _stripMacroTemplatesAndAddToIndex(_rawDocs);
_rawDocs = _stripHtmlAndAddToIndex(_rawDocs);
}
_rawDocs = buildDocumentationAddition(_rawDocs);
return _rawDocs;
}
/// Returns the documentation for this literal element unless
/// [config.dropTextFrom] indicates it should not be returned. Macro
/// definitions are stripped, but macros themselves are not injected. This
/// is a two stage process to avoid ordering problems.
String _documentationLocal;
String get documentationLocal =>
_documentationLocal ??= _buildDocumentationLocal();
/// Returns the docs, stripped of their leading comments syntax.
@override
String get documentation {
return _injectMacros(
documentationFrom.map((e) => e.documentationLocal).join('<p>'));
}
Library get definingLibrary =>
packageGraph.findButDoNotCreateLibraryFor(element);
Library _canonicalLibrary;
// _canonicalLibrary can be null so we can't check against null to see whether
// we tried to compute it before.
bool _canonicalLibraryIsSet = false;
@override
Library get canonicalLibrary {
if (!_canonicalLibraryIsSet) {
// This is not accurate if we are constructing the Package.
assert(packageGraph.allLibrariesAdded);
// Since we're looking for a library, find the [Element] immediately
// contained by a [CompilationUnitElement] in the tree.
var topLevelElement = element;
while (topLevelElement != null &&
topLevelElement.enclosingElement is! LibraryElement &&
topLevelElement.enclosingElement is! CompilationUnitElement &&
topLevelElement.enclosingElement != null) {
topLevelElement = topLevelElement.enclosingElement;
}
// Privately named elements can never have a canonical library, so
// just shortcut them out.
if (!utils.hasPublicName(element)) {
_canonicalLibrary = null;
} else if (!packageGraph.localPublicLibraries.contains(definingLibrary)) {
var candidateLibraries = definingLibrary.exportedInLibraries
?.where((l) =>
l.isPublic &&
l.package.documentedWhere != DocumentLocation.missing)
?.toList();
if (candidateLibraries != null) {
candidateLibraries = candidateLibraries.where((l) {
var lookup =
l.element.exportNamespace.definedNames[topLevelElement?.name];
if (lookup is PropertyAccessorElement) {
lookup = (lookup as PropertyAccessorElement).variable;
}
if (topLevelElement == lookup) return true;
return false;
}).toList();
// Avoid claiming canonicalization for elements outside of this element's
// defining package.
// TODO(jcollins-g): Make the else block unconditional.
if (candidateLibraries.isNotEmpty &&
!candidateLibraries
.any((l) => l.package == definingLibrary.package)) {
warn(PackageWarning.reexportedPrivateApiAcrossPackages,
message: definingLibrary.package.fullyQualifiedName,
referredFrom: candidateLibraries);
} else {
candidateLibraries
.removeWhere((l) => l.package != definingLibrary.package);
}
// Start with our top-level element.
var warnable =
ModelElement.fromElement(topLevelElement, packageGraph);
if (candidateLibraries.length > 1) {
// Heuristic scoring to determine which library a human likely
// considers this element to be primarily 'from', and therefore,
// canonical. Still warn if the heuristic isn't that confident.
var scoredCandidates =
warnable.scoreCanonicalCandidates(candidateLibraries);
candidateLibraries =
scoredCandidates.map((s) => s.library).toList();
var secondHighestScore =
scoredCandidates[scoredCandidates.length - 2].score;
var highestScore = scoredCandidates.last.score;
var confidence = highestScore - secondHighestScore;
var message =
'${candidateLibraries.map((l) => l.name)} -> ${candidateLibraries.last.name} (confidence ${confidence.toStringAsPrecision(4)})';
var debugLines = <String>[];
debugLines.addAll(scoredCandidates.map((s) => '${s.toString()}'));
if (confidence < config.ambiguousReexportScorerMinConfidence) {
warnable.warn(PackageWarning.ambiguousReexport,
message: message, extendedDebug: debugLines);
}
}
if (candidateLibraries.isNotEmpty) {
_canonicalLibrary = candidateLibraries.last;
}
}
} else {
_canonicalLibrary = definingLibrary;
}
// Only pretend when not linking to remote packages.
if (this is Inheritable && !config.linkToRemote) {
if ((this as Inheritable).isInherited &&
_canonicalLibrary == null &&
packageGraph.publicLibraries.contains(library)) {
// 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;
}
assert(_canonicalLibrary == null ||
packageGraph.publicLibraries.contains(_canonicalLibrary));
return _canonicalLibrary;
}
@override
bool get isCanonical {
if (!isPublic) return false;
if (library == canonicalLibrary) {
if (this is Inheritable) {
var i = (this as Inheritable);
// If we're the defining element, or if the defining element is not
// in the set of libraries being documented, then this element
// should be treated as canonical (given library == canonicalLibrary).
if (i.enclosingElement == i.canonicalEnclosingContainer) {
return true;
} else {
return false;
}
}
// If there's no inheritance to deal with, we're done.
return true;
}
return false;
}
String _htmlDocumentation;
@override
String get documentationAsHtml {
if (_htmlDocumentation != null) return _htmlDocumentation;
_htmlDocumentation = _injectHtmlFragments(_documentation.asHtml);
return _htmlDocumentation;
}
@override
Element get element => _element;
@override
String get location {
// Call nothing from here that can emit warnings or you'll cause stack overflows.
if (characterLocation != null) {
return '(${path.toUri(sourceFileName)}:${characterLocation.toString()})';
}
return '(${path.toUri(sourceFileName)})';
}
/// Returns a link to extended documentation, or the empty string if that
/// does not exist.
String get extendedDocLink {
if (hasExtendedDocumentation) {
return _modelElementRenderer.renderExtendedDocLink(this);
}
return '';
}
String get fileName => '$name.$fileType';
String get fileType => package.fileType;
String get filePath;
/// Returns the fully qualified name.
///
/// For example: libraryName.className.methodName
@override
String get fullyQualifiedName {
return (_fullyQualifiedName ??= _buildFullyQualifiedName());
}
String get fullyQualifiedNameWithoutLibrary {
// Remember, periods are legal in library names.
_fullyQualifiedNameWithoutLibrary ??=
fullyQualifiedName.replaceFirst('${library.fullyQualifiedName}.', '');
return _fullyQualifiedNameWithoutLibrary;
}
String get sourceFileName => element.source.fullName;
CharacterLocation _characterLocation;
bool _characterLocationIsSet = false;
@override
CharacterLocation get characterLocation {
if (!_characterLocationIsSet) {
var lineInfo = compilationUnitElement.lineInfo;
_characterLocationIsSet = true;
assert(element.nameOffset >= 0,
'Invalid location data for element: $fullyQualifiedName');
assert(lineInfo != null,
'No lineInfo data available for element: $fullyQualifiedName');
if (element.nameOffset >= 0) {
_characterLocation = lineInfo?.getLocation(element.nameOffset);
}
}
return _characterLocation;
}
CompilationUnitElement get compilationUnitElement =>
element.thisOrAncestorOfType<CompilationUnitElement>();
bool get hasAnnotations => annotations.isNotEmpty;
@override
bool get hasDocumentation =>
documentation != null && documentation.isNotEmpty;
@override
bool get hasExtendedDocumentation =>
href != null && _documentation.hasExtendedDocs;
bool get hasParameters => parameters.isNotEmpty;
/// If canonicalLibrary (or canonicalEnclosingElement, for Inheritable
/// subclasses) is null, href should be null.
@override
String get href;
String get htmlId => name;
bool get isAsynchronous =>
isExecutable && (element as ExecutableElement).isAsynchronous;
bool get isConst => false;
bool get isDeprecated {
// If element.metadata is empty, it might be because this is a property
// where the metadata belongs to the individual getter/setter
if (element.metadata.isEmpty && element is PropertyInducingElement) {
var pie = element as PropertyInducingElement;
// The getter or the setter might be null – so the stored value may be
// `true`, `false`, or `null`
var getterDeprecated = pie.getter?.metadata?.any((a) => a.isDeprecated);
var setterDeprecated = pie.setter?.metadata?.any((a) => a.isDeprecated);
var deprecatedValues =
[getterDeprecated, setterDeprecated].where((a) => a != null).toList();
// At least one of these should be non-null. Otherwise things are weird
assert(deprecatedValues.isNotEmpty);
// If there are both a setter and getter, only show the property as
// deprecated if both are deprecated.
return deprecatedValues.every((d) => d);
}
return element.metadata.any((a) => a.isDeprecated);
}
@override
bool get isDocumented => isCanonical && isPublic;
bool get isExecutable => element is ExecutableElement;
bool get isFinal => false;
bool get isLate => false;
bool get isLocalElement => element is LocalElement;
bool get isPropertyAccessor => element is PropertyAccessorElement;
bool get isPropertyInducer => element is PropertyInducingElement;
bool get isStatic {
if (isPropertyInducer) {
return (element as PropertyInducingElement).isStatic;
}
return false;
}
/// A human-friendly name for the kind of element this is.
@override
String get kind;
@override
Library get library => _library;
String get linkedName {
_linkedName ??= _calculateLinkedName();
return _linkedName;
}
ModelElementRenderer get _modelElementRenderer =>
packageGraph.rendererFactory.modelElementRenderer;
ParameterRenderer get _parameterRenderer =>
packageGraph.rendererFactory.parameterRenderer;
ParameterRenderer get _parameterRendererDetailed =>
packageGraph.rendererFactory.parameterRendererDetailed;
SourceCodeRenderer get _sourceCodeRenderer =>
packageGraph.rendererFactory.sourceCodeRenderer;
String get linkedParams => _parameterRenderer.renderLinkedParams(parameters);
String get linkedParamsLines =>
_parameterRendererDetailed.renderLinkedParams(parameters).trim();
String get linkedParamsNoMetadata =>
_parameterRenderer.renderLinkedParams(parameters, showMetadata: false);
String get linkedParamsNoMetadataOrNames => _parameterRenderer
.renderLinkedParams(parameters, showMetadata: false, showNames: false);
ElementType get modelType {
if (_modelType == null) {
// TODO(jcollins-g): Need an interface for a "member with a type" (or changed object model).
if (_originalMember != null &&
(_originalMember is ExecutableMember ||
_originalMember is ParameterMember)) {
if (_originalMember is ExecutableMember) {
_modelType = ElementType.from(
(_originalMember as ExecutableMember).type,
library,
packageGraph);
} else {
// ParameterMember
_modelType = ElementType.from(
(_originalMember as ParameterMember).type, library, packageGraph);
}
} else if (element is ExecutableElement ||
element is FunctionTypedElement ||
element is ParameterElement ||
element is TypeDefiningElement ||
element is PropertyInducingElement) {
_modelType =
ElementType.from((element as dynamic).type, library, packageGraph);
}
}
return _modelType;
}
void setModelType(ElementType type) {
_modelType = type;
}
@override
String get name => element.name;
@override
String get oneLineDoc => _documentation.asOneLiner;
Member get originalMember => _originalMember;
final PackageGraph _packageGraph;
@override
PackageGraph get packageGraph => _packageGraph;
@override
Package get package => library.package;
bool get isPublicAndPackageDocumented =>
isPublic && library.packageGraph.packageDocumentedFor(this);
List<Parameter> _allParameters;
// TODO(jcollins-g): This is in the wrong place. Move parts to GetterSetterCombo,