Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(57)

Side by Side Diff: pkg/docgen/lib/src/models.dart

Issue 209563002: pkg/docgen: the big refactor (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: silly Created 6 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « pkg/docgen/lib/src/model_helpers.dart ('k') | pkg/docgen/lib/src/package_helpers.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a 2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file. 3 // BSD-style license that can be found in the LICENSE file.
4 4
5 library docgen.models; 5 library docgen.models;
6 6
7 import 'dart:io';
8
9 import 'package:markdown/markdown.dart' as markdown;
10
7 import '../../../../sdk/lib/_internal/compiler/implementation/mirrors/source_mir rors.dart'; 11 import '../../../../sdk/lib/_internal/compiler/implementation/mirrors/source_mir rors.dart';
8 import '../../../../sdk/lib/_internal/compiler/implementation/mirrors/mirrors_ut il.dart' 12 import '../../../../sdk/lib/_internal/compiler/implementation/mirrors/mirrors_ut il.dart'
9 as dart2js_util; 13 as dart2js_util;
14 import '../../../../sdk/lib/_internal/compiler/implementation/mirrors/dart2js_mi rrors.dart'
15 as dart2js_mirrors;
16
17 import 'library_helpers.dart';
18 import 'mdn.dart';
19 import 'model_helpers.dart';
20 import 'package_helpers.dart';
10 21
11 /// Docgen representation of an item to be documented, that wraps around a 22 /// Docgen representation of an item to be documented, that wraps around a
12 /// dart2js mirror. 23 /// dart2js mirror.
13 abstract class MirrorBased { 24 abstract class MirrorBased<TMirror extends DeclarationMirror> {
14 /// The original dart2js mirror around which this object wraps. 25 /// The original dart2js mirror around which this object wraps.
15 DeclarationMirror get mirror; 26 TMirror get mirror;
16 } 27 }
17 28
18 /// A Docgen wrapper around the dart2js mirror for a generic type. 29 /// A Docgen wrapper around the dart2js mirror for a generic type.
19 class Generic extends MirrorBased { 30 class Generic extends MirrorBased<TypeVariableMirror> {
20 final TypeVariableMirror mirror; 31 final TypeVariableMirror mirror;
21 32
22 Generic(this.mirror); 33 Generic(this.mirror);
23 34
24 Map toMap() => { 35 Map toMap() => {
25 'name': dart2js_util.nameOf(mirror), 36 'name': dart2js_util.nameOf(mirror),
26 'type': dart2js_util.qualifiedNameOf(mirror.upperBound) 37 'type': dart2js_util.qualifiedNameOf(mirror.upperBound)
27 }; 38 };
28 } 39 }
40
41 /// For types that we do not explicitly create or have not yet created in our
42 /// entity map (like core types).
43 class DummyMirror implements Indexable {
44 DeclarationMirror mirror;
45 /// The library that contains this element, if any. Used as a hint to help
46 /// determine which object we're referring to when looking up this mirror in
47 /// our map.
48 Indexable owner;
49 DummyMirror(this.mirror, [this.owner]);
50
51 String get docName {
52 if (mirror == null) return '';
53 if (mirror is LibraryMirror) {
54 return dart2js_util.qualifiedNameOf(mirror).replaceAll('.','-');
55 }
56 var mirrorOwner = mirror.owner;
57 if (mirrorOwner == null) return dart2js_util.qualifiedNameOf(mirror);
58 var simpleName = dart2js_util.nameOf(mirror);
59 if (mirror is MethodMirror && (mirror as MethodMirror).isConstructor) {
60 // We name constructors specially -- repeating the class name and a
61 // "-" to separate the constructor from its name (if any).
62 simpleName = '${dart2js_util.nameOf(mirrorOwner)}-$simpleName';
63 }
64 return getDocgenObject(mirrorOwner, owner).docName + '.' +
65 simpleName;
66 }
67
68 bool get isPrivate => mirror == null? false : mirror.isPrivate;
69
70 String get packageName {
71 var libMirror = _getOwningLibraryFromMirror(mirror);
72 if (libMirror != null) {
73 return getPackageName(libMirror);
74 }
75 return '';
76 }
77
78 String get packagePrefix => packageName == null || packageName.isEmpty ?
79 '' : '$packageName/';
80
81 LibraryMirror _getOwningLibraryFromMirror(DeclarationMirror mirror) {
82 if (mirror is LibraryMirror) return mirror;
83 if (mirror == null) return null;
84 return _getOwningLibraryFromMirror(mirror.owner);
85 }
86
87 noSuchMethod(Invocation invocation) {
88 throw new UnimplementedError(invocation.memberName.toString());
89 }
90 }
91
92 /// An item that is categorized in our mirrorToDocgen map, as a distinct,
93 /// searchable element.
94 ///
95 /// These are items that refer to concrete entities (a Class, for example,
96 /// but not a Type, which is a "pointer" to a class) that we wish to be
97 /// globally resolvable. This includes things such as class methods and
98 /// variables, but parameters for methods are not "Indexable" as we do not want
99 /// the user to be able to search for a method based on its parameter names!
100 /// The set of indexable items also includes Typedefs, since the user can refer
101 /// to them as concrete entities in a particular scope.
102 abstract class Indexable<TMirror extends DeclarationMirror>
103 extends MirrorBased<TMirror> {
104
105
106 Library get _owningLibrary => owner._owningLibrary;
107
108 String get qualifiedName => fileName;
109 final TMirror mirror;
110 final bool isPrivate;
111 /// The comment text pre-resolution. We keep this around because inherited
112 /// methods need to resolve links differently from the superclass.
113 String _unresolvedComment = '';
114
115 Indexable(TMirror mirror)
116 : this.mirror = mirror,
117 this.isPrivate = isHidden(mirror) {
118
119 var map = mirrorToDocgen[dart2js_util.qualifiedNameOf(this.mirror)];
120 if (map == null) map = new Map<String, Set<Indexable>>();
121
122 var set = map[owner.docName];
123 if (set == null) set = new Set<Indexable>();
124 set.add(this);
125 map[owner.docName] = set;
126 mirrorToDocgen[dart2js_util.qualifiedNameOf(this.mirror)] = map;
127 }
128
129 /// Returns this object's qualified name, but following the conventions
130 /// we're using in Dartdoc, which is that library names with dots in them
131 /// have them replaced with hyphens.
132 String get docName;
133
134 /// Converts all [foo] references in comments to <a>libraryName.foo</a>.
135 markdown.Node fixReference(String name) {
136 // Attempt the look up the whole name up in the scope.
137 String elementName = findElementInScope(name);
138 if (elementName != null) {
139 return new markdown.Element.text('a', elementName);
140 }
141 return fixComplexReference(name);
142 }
143
144 /// Look for the specified name starting with the current member, and
145 /// progressively working outward to the current library scope.
146 String findElementInScope(String name) =>
147 findElementInScopeWithPrefix(name, packagePrefix);
148
149 /// The reference to this element based on where it is printed as a
150 /// documentation file and also the unique URL to refer to this item.
151 ///
152 /// The qualified name (for URL purposes) and the file name are the same,
153 /// of the form packageName/ClassName or packageName/ClassName.methodName.
154 /// This defines both the URL and the directory structure.
155 String get fileName => packagePrefix + ownerPrefix + name;
156
157 /// The full docName of the owner element, appended with a '.' for this
158 /// object's name to be appended.
159 String get ownerPrefix => owner.docName != '' ? owner.docName + '.' : '';
160
161 /// The prefix String to refer to the package that this item is in, for URLs
162 /// and comment resolution.
163 ///
164 /// The prefix can be prepended to a qualified name to get a fully unique
165 /// name among all packages.
166 String get packagePrefix => '';
167
168 /// Documentation comment with converted markdown and all links resolved.
169 String _comment;
170
171 /// Accessor to documentation comment with markdown converted to html and all
172 /// links resolved.
173 String get comment {
174 if (_comment != null) return _comment;
175
176 _comment = _commentToHtml();
177 if (_comment.isEmpty) {
178 _comment = _mdnComment();
179 }
180 return _comment;
181 }
182
183 void set comment(x) {
184 _comment = x;
185 }
186
187 /// The simple name to refer to this item.
188 String get name => dart2js_util.nameOf(mirror);
189
190 /// Accessor to the parent item that owns this item.
191 ///
192 /// "Owning" is defined as the object one scope-level above which this item
193 /// is defined. Ex: The owner for a top level class, would be its enclosing
194 /// library. The owner of a local variable in a method would be the enclosing
195 /// method.
196 Indexable get owner => new DummyMirror(mirror.owner);
197
198 /// Generates MDN comments from database.json.
199 String _mdnComment();
200
201 /// The type of this member to be used in index.txt.
202 String get typeName => '';
203
204 /// Creates a [Map] with this [Indexable]'s name and a preview comment.
205 Map get previewMap {
206 var finalMap = { 'name' : name, 'qualifiedName' : qualifiedName };
207 var preview = _preview;
208 if(preview != null) finalMap['preview'] = preview;
209 return finalMap;
210 }
211
212 String get _preview {
213 if (comment != '') {
214 var index = comment.indexOf('</p>');
215 return index > 0 ?
216 '${comment.substring(0, index)}</p>' :
217 '<p><i>Comment preview not available</i></p>';
218 }
219 return null;
220 }
221
222 /// Accessor to obtain the raw comment text for a given item, _without_ any
223 /// of the links resolved.
224 String get _commentText {
225 String commentText;
226 mirror.metadata.forEach((metadata) {
227 if (metadata is CommentInstanceMirror) {
228 CommentInstanceMirror comment = metadata;
229 if (comment.isDocComment) {
230 if (commentText == null) {
231 commentText = comment.trimmedText;
232 } else {
233 commentText = '$commentText\n${comment.trimmedText}';
234 }
235 }
236 }
237 });
238 return commentText;
239 }
240
241 /// Returns any documentation comments associated with a mirror with
242 /// simple markdown converted to html.
243 ///
244 /// By default we resolve any comment references within our own scope.
245 /// However, if a method is inherited, we want the inherited comments, but
246 /// links to the subclasses's version of the methods.
247 String _commentToHtml([Indexable resolvingScope]) {
248 if (resolvingScope == null) resolvingScope = this;
249 var commentText = _commentText;
250 _unresolvedComment = commentText;
251
252 var linkResolver = (name) => resolvingScope.fixReference(name);
253 commentText = commentText == null ? '' :
254 markdown.markdownToHtml(commentText.trim(), linkResolver: linkResolver,
255 inlineSyntaxes: MARKDOWN_SYNTAXES);
256 return commentText;
257 }
258
259 /// Returns a map of [Variable] objects constructed from [mirrorMap].
260 /// The optional parameter [containingLibrary] is contains data for variables
261 /// defined at the top level of a library (potentially for exporting
262 /// purposes).
263 Map<String, Variable> _createVariables(Iterable<VariableMirror> mirrors,
264 Indexable owner) {
265 var data = {};
266 // TODO(janicejl): When map to map feature is created, replace the below
267 // with a filter. Issue(#9590).
268 mirrors.forEach((dart2js_mirrors.Dart2JsFieldMirror mirror) {
269 if (includePrivateMembers || !isHidden(mirror)) {
270 var mirrorName = dart2js_util.nameOf(mirror);
271 data[mirrorName] = new Variable(mirrorName, mirror, owner);
272 }
273 });
274 return data;
275 }
276
277 /// Returns a map of [Method] objects constructed from [mirrorMap].
278 /// The optional parameter [containingLibrary] is contains data for variables
279 /// defined at the top level of a library (potentially for exporting
280 /// purposes).
281 Map<String, Method> _createMethods(Iterable<MethodMirror> mirrors,
282 Indexable owner) {
283 var group = new Map<String, Method>();
284 mirrors.forEach((MethodMirror mirror) {
285 if (includePrivateMembers || !mirror.isPrivate) {
286 group[dart2js_util.nameOf(mirror)] = new Method(mirror, owner);
287 }
288 });
289 return group;
290 }
291
292 /// Returns a map of [Parameter] objects constructed from [mirrorList].
293 Map<String, Parameter> _createParameters(List<ParameterMirror> mirrorList,
294 Indexable owner) {
295 var data = {};
296 mirrorList.forEach((ParameterMirror mirror) {
297 data[dart2js_util.nameOf(mirror)] =
298 new Parameter(mirror, owner._owningLibrary);
299 });
300 return data;
301 }
302
303 /// Returns a map of [Generic] objects constructed from the class mirror.
304 Map<String, Generic> _createGenerics(TypeMirror mirror) {
305 return new Map.fromIterable(mirror.typeVariables,
306 key: (e) => dart2js_util.nameOf(e),
307 value: (e) => new Generic(e));
308 }
309
310 /// Return an informative [Object.toString] for debugging.
311 String toString() => "${super.toString()}(${name.toString()})";
312
313 /// Return a map representation of this type.
314 Map toMap();
315
316
317 /// Expand the method map [mapToExpand] into a more detailed map that
318 /// separates out setters, getters, constructors, operators, and methods.
319 Map _expandMethodMap(Map<String, Method> mapToExpand) => {
320 'setters': recurseMap(filterMap(mapToExpand,
321 (key, val) => val.mirror.isSetter)),
322 'getters': recurseMap(filterMap(mapToExpand,
323 (key, val) => val.mirror.isGetter)),
324 'constructors': recurseMap(filterMap(mapToExpand,
325 (key, val) => val.mirror.isConstructor)),
326 'operators': recurseMap(filterMap(mapToExpand,
327 (key, val) => val.mirror.isOperator)),
328 'methods': recurseMap(filterMap(mapToExpand,
329 (key, val) => val.mirror.isRegularMethod && !val.mirror.isOperator))
330 };
331
332 /// Accessor to determine if this item and all of its owners are visible.
333 bool get isVisible => isFullChainVisible(this);
334
335 /// Returns true if [mirror] is the correct type of mirror that this Docgen
336 /// object wraps. (Workaround for the fact that Types are not first class.)
337 bool isValidMirror(DeclarationMirror mirror);
338 }
339
340 /// A class containing contents of a Dart library.
341 class Library extends Indexable {
342 final Map<String, Class> classes = {};
343 final Map<String, Typedef> typedefs = {};
344 final Map<String, Class> errors = {};
345
346 /// Top-level variables in the library.
347 Map<String, Variable> variables;
348
349 /// Top-level functions in the library.
350 Map<String, Method> functions;
351
352 String packageName = '';
353 bool _hasBeenCheckedForPackage = false;
354 String packageIntro;
355
356 Library get _owningLibrary => this;
357
358 /// Returns the [Library] for the given [mirror] if it has already been
359 /// created, else creates it.
360 factory Library(LibraryMirror mirror) {
361 var library = getDocgenObject(mirror);
362 if (library is DummyMirror) {
363 library = new Library._(mirror);
364 }
365 return library;
366 }
367
368 Library._(LibraryMirror libraryMirror) : super(libraryMirror) {
369 var exported = _calcExportedItems(libraryMirror);
370 var exportedClasses = _addAll(exported['classes'],
371 dart2js_util.typesOf(libraryMirror.declarations));
372 updateLibraryPackage(mirror);
373 exportedClasses.forEach((String mirrorName, TypeMirror mirror) {
374 if (mirror is TypedefMirror) {
375 // This is actually a Dart2jsTypedefMirror, and it does define value,
376 // but we don't have visibility to that type.
377 if (includePrivateMembers || !mirror.isPrivate) {
378 typedefs[dart2js_util.nameOf(mirror)] = new Typedef(mirror, this);
379 }
380 } else if (mirror is ClassMirror) {
381 var clazz = new Class(mirror, this);
382
383 if (clazz.isError()) {
384 errors[dart2js_util.nameOf(mirror)] = clazz;
385 } else {
386 classes[dart2js_util.nameOf(mirror)] = clazz;
387 }
388 } else {
389 throw new ArgumentError(
390 '${dart2js_util.nameOf(mirror)} - no class type match. ');
391 }
392 });
393 this.functions = _createMethods(_addAll(exported['methods'],
394 libraryMirror.declarations.values.where(
395 (mirror) => mirror is MethodMirror)).values, this);
396 this.variables = _createVariables(_addAll(exported['variables'],
397 dart2js_util.variablesOf(libraryMirror.declarations)).values, this);
398 }
399
400 /// Look for the specified name starting with the current member, and
401 /// progressively working outward to the current library scope.
402 String findElementInScope(String name) {
403 var lookupFunc = determineLookupFunc(name);
404 var libraryScope = lookupFunc(mirror, name);
405 if (libraryScope != null) {
406 var result = getDocgenObject(libraryScope, this);
407 if (result is DummyMirror) return packagePrefix + result.docName;
408 return result.packagePrefix + result.docName;
409 }
410 return super.findElementInScope(name);
411 }
412
413 String _mdnComment() => '';
414
415 /// Helper that maps [mirrors] to their simple name in map.
416 static Map _addAll(Map map, Iterable<DeclarationMirror> mirrors) {
417 for (var mirror in mirrors) {
418 map[dart2js_util.nameOf(mirror)] = mirror;
419 }
420 return map;
421 }
422
423 /// For a library's [mirror], determine the name of the package (if any) we
424 /// believe it came from (because of its file URI).
425 ///
426 /// If no package could be determined, we return an empty string.
427 void updateLibraryPackage(LibraryMirror mirror) {
428 if (mirror == null) return;
429 if (_hasBeenCheckedForPackage) return;
430 _hasBeenCheckedForPackage = true;
431 if (mirror.uri.scheme != 'file') return;
432 packageName = getPackageName(mirror);
433 // Associate the package readme with all the libraries. This is a bit
434 // wasteful, but easier than trying to figure out which partial match
435 // is best.
436 packageIntro = _packageIntro(getPackageDirectory(mirror));
437 }
438
439 String _packageIntro(packageDir) {
440 if (packageDir == null) return null;
441 var dir = new Directory(packageDir);
442 var files = dir.listSync();
443 var readmes = files.where((FileSystemEntity each) => (each is File &&
444 each.path.substring(packageDir.length + 1, each.path.length)
445 .startsWith('README'))).toList();
446 if (readmes.isEmpty) return '';
447 // If there are multiples, pick the shortest name.
448 readmes.sort((a, b) => a.path.length.compareTo(b.path.length));
449 var readme = readmes.first;
450 var linkResolver = (name) => globalFixReference(name);
451 var contents = markdown.markdownToHtml(readme
452 .readAsStringSync(), linkResolver: linkResolver,
453 inlineSyntaxes: MARKDOWN_SYNTAXES);
454 return contents;
455 }
456
457 String get packagePrefix => packageName == null || packageName.isEmpty ?
458 '' : '$packageName/';
459
460 Map get previewMap {
461 var basic = super.previewMap;
462 basic['packageName'] = packageName;
463 if (packageIntro != null) {
464 basic['packageIntro'] = packageIntro;
465 }
466 return basic;
467 }
468
469 String get name => docName;
470
471 String get docName {
472 return dart2js_util.qualifiedNameOf(mirror).replaceAll('.','-');
473 }
474
475 /// For the given library determine what items (if any) are exported.
476 ///
477 /// Returns a Map with three keys: "classes", "methods", and "variables" the
478 /// values of which point to a map of exported name identifiers with values
479 /// corresponding to the actual DeclarationMirror.
480 Map<String, Map<String, DeclarationMirror>> _calcExportedItems(
481 LibrarySourceMirror library) {
482 var exports = {};
483 exports['classes'] = {};
484 exports['methods'] = {};
485 exports['variables'] = {};
486
487 // Determine the classes, variables and methods that are exported for a
488 // specific dependency.
489 void _populateExports(LibraryDependencyMirror export, bool showExport) {
490 if (!showExport) {
491 // Add all items, and then remove the hidden ones.
492 // Ex: "export foo hide bar"
493 _addAll(exports['classes'],
494 dart2js_util.typesOf(export.targetLibrary.declarations));
495 _addAll(exports['methods'],
496 export.targetLibrary.declarations.values.where(
497 (mirror) => mirror is MethodMirror));
498 _addAll(exports['variables'],
499 dart2js_util.variablesOf(export.targetLibrary.declarations));
500 }
501 for (CombinatorMirror combinator in export.combinators) {
502 for (String identifier in combinator.identifiers) {
503 var librarySourceMirror =
504 export.targetLibrary as DeclarationSourceMirror;
505 var declaration = librarySourceMirror.lookupInScope(identifier);
506 if (declaration == null) {
507 // Technically this should be a bug, but some of our packages
508 // (such as the polymer package) are curently broken in this
509 // way, so we just produce a warning.
510 print('Warning identifier $identifier not found in library '
511 '${dart2js_util.qualifiedNameOf(export.targetLibrary)}');
512 } else {
513 var subMap = exports['classes'];
514 if (declaration is MethodMirror) {
515 subMap = exports['methods'];
516 } else if (declaration is VariableMirror) {
517 subMap = exports['variables'];
518 }
519 if (showExport) {
520 subMap[identifier] = declaration;
521 } else {
522 subMap.remove(identifier);
523 }
524 }
525 }
526 }
527 }
528
529 Iterable<LibraryDependencyMirror> exportList =
530 library.libraryDependencies.where((lib) => lib.isExport);
531 for (LibraryDependencyMirror export in exportList) {
532 // If there is a show in the export, add only the show items to the
533 // library. Ex: "export foo show bar"
534 // Otherwise, add all items, and then remove the hidden ones.
535 // Ex: "export foo hide bar"
536 _populateExports(export,
537 export.combinators.any((combinator) => combinator.isShow));
538 }
539 return exports;
540 }
541
542 /// Checks if the given name is a key for any of the Class Maps.
543 bool containsKey(String name) =>
544 classes.containsKey(name) || errors.containsKey(name);
545
546 /// Generates a map describing the [Library] object.
547 Map toMap() => {
548 'name': name,
549 'qualifiedName': qualifiedName,
550 'comment': comment,
551 'variables': recurseMap(variables),
552 'functions': _expandMethodMap(functions),
553 'classes': {
554 'class': classes.values.where((c) => c.isVisible)
555 .map((e) => e.previewMap).toList(),
556 'typedef': recurseMap(typedefs),
557 'error': errors.values.where((e) => e.isVisible)
558 .map((e) => e.previewMap).toList()
559 },
560 'packageName': packageName,
561 'packageIntro' : packageIntro
562 };
563
564 String get typeName => 'library';
565
566 bool isValidMirror(DeclarationMirror mirror) => mirror is LibraryMirror;
567 }
568
569 abstract class OwnedIndexable extends Indexable {
570 /// The object one scope-level above which this item is defined.
571 ///
572 /// Ex: The owner for a top level class, would be its enclosing library.
573 /// The owner of a local variable in a method would be the enclosing method.
574 Indexable owner;
575
576 /// List of the meta annotations on this item.
577 List<Annotation> annotations;
578
579 /// Returns this object's qualified name, but following the conventions
580 /// we're using in Dartdoc, which is that library names with dots in them
581 /// have them replaced with hyphens.
582 String get docName => owner.docName + '.' + dart2js_util.nameOf(mirror);
583
584 OwnedIndexable(DeclarationMirror mirror, this.owner) : super(mirror);
585
586 /// Generates MDN comments from database.json.
587 String _mdnComment() {
588 var domAnnotation = this.annotations.firstWhere(
589 (e) => e.mirror.qualifiedName == #metadata.DomName,
590 orElse: () => null);
591 if (domAnnotation == null) return '';
592 var domName = domAnnotation.parameters.single;
593
594 return mdnComment(rootDirectory, logger, domName);
595 }
596
597 String get packagePrefix => owner.packagePrefix;
598 }
599
600 /// A class containing contents of a Dart class.
601 class Class extends OwnedIndexable implements Comparable {
602
603 /// List of the names of interfaces that this class implements.
604 List<Class> interfaces = [];
605
606 /// Names of classes that extends or implements this class.
607 Set<Class> subclasses = new Set<Class>();
608
609 /// Top-level variables in the class.
610 Map<String, Variable> variables;
611
612 /// Inherited variables in the class.
613 Map<String, Variable> inheritedVariables;
614
615 /// Methods in the class.
616 Map<String, Method> methods;
617
618 Map<String, Method> inheritedMethods;
619
620 /// Generic infomation about the class.
621 Map<String, Generic> generics;
622
623 Class superclass;
624 bool isAbstract;
625
626 /// Make sure that we don't check for inherited comments more than once.
627 bool _commentsEnsured = false;
628
629 /// Returns the [Class] for the given [mirror] if it has already been created,
630 /// else creates it.
631 factory Class(ClassMirror mirror, Library owner) {
632 var clazz = getDocgenObject(mirror, owner);
633 if (clazz is DummyMirror) {
634 clazz = new Class._(mirror, owner);
635 }
636 return clazz;
637 }
638
639 /// Called when we are constructing a superclass or interface class, but it
640 /// is not known if it belongs to the same owner as the original class. In
641 /// this case, we create an object whose owner is what the original mirror
642 /// says it is.
643 factory Class._possiblyDifferentOwner(ClassMirror mirror,
644 Library originalOwner) {
645 if (mirror.owner is LibraryMirror) {
646 var realOwner = getDocgenObject(mirror.owner);
647 if (realOwner is Library) {
648 return new Class(mirror, realOwner);
649 } else {
650 return new Class(mirror, originalOwner);
651 }
652 } else {
653 return new Class(mirror, originalOwner);
654 }
655 }
656
657 Class._(ClassSourceMirror classMirror, Indexable owner) :
658 super(classMirror, owner) {
659 inheritedVariables = {};
660
661 // The reason we do this madness is the superclass and interface owners may
662 // not be this class's owner!! Example: BaseClient in http pkg.
663 var superinterfaces = classMirror.superinterfaces.map(
664 (interface) => new Class._possiblyDifferentOwner(interface, owner));
665 this.superclass = classMirror.superclass == null? null :
666 new Class._possiblyDifferentOwner(classMirror.superclass, owner);
667
668 interfaces = superinterfaces.toList();
669 variables = _createVariables(
670 dart2js_util.variablesOf(classMirror.declarations), this);
671 methods = _createMethods(classMirror.declarations.values.where(
672 (mirror) => mirror is MethodMirror), this);
673 annotations = createAnnotations(classMirror, owner._owningLibrary);
674 generics = _createGenerics(classMirror);
675 isAbstract = classMirror.isAbstract;
676 inheritedMethods = new Map<String, Method>();
677
678 // Tell superclass that you are a subclass, unless you are not
679 // visible or an intermediary mixin class.
680 if (!classMirror.isNameSynthetic && isVisible && superclass != null) {
681 superclass.addSubclass(this);
682 }
683
684 if (this.superclass != null) addInherited(superclass);
685 interfaces.forEach((interface) => addInherited(interface));
686 }
687
688 String _lookupInClassAndSuperclasses(String name) {
689 var lookupFunc = determineLookupFunc(name);
690 var classScope = this;
691 while (classScope != null) {
692 var classFunc = lookupFunc(classScope.mirror, name);
693 if (classFunc != null) {
694 return packagePrefix + getDocgenObject(classFunc, owner).docName;
695 }
696 classScope = classScope.superclass;
697 }
698 return null;
699 }
700
701 /// Look for the specified name starting with the current member, and
702 /// progressively working outward to the current library scope.
703 String findElementInScope(String name) {
704 var lookupFunc = determineLookupFunc(name);
705 var result = _lookupInClassAndSuperclasses(name);
706 if (result != null) {
707 return result;
708 }
709 result = owner.findElementInScope(name);
710 return result == null ? super.findElementInScope(name) : result;
711 }
712
713 String get typeName => 'class';
714
715 /// Add all inherited variables and methods from the provided superclass.
716 /// If [_includePrivate] is true, it also adds the variables and methods from
717 /// the superclass.
718 void addInherited(Class superclass) {
719 inheritedVariables.addAll(superclass.inheritedVariables);
720 inheritedVariables.addAll(_allButStatics(superclass.variables));
721 addInheritedMethod(superclass, this);
722 }
723
724 /** [newParent] refers to the actual class is currently using these methods.
725 * which may be different because with the mirror system, we only point to the
726 * original canonical superclasse's method.
727 */
728 void addInheritedMethod(Class parent, Class newParent) {
729 parent.inheritedMethods.forEach((name, method) {
730 if(!method.mirror.isConstructor){
731 inheritedMethods[name] = new Method(method.mirror, newParent, method);
732 }}
733 );
734 _allButStatics(parent.methods).forEach((name, method) {
735 if (!method.mirror.isConstructor) {
736 inheritedMethods[name] = new Method(method.mirror, newParent, method);
737 }}
738 );
739 }
740
741 /// Remove statics from the map of inherited items before adding them.
742 Map _allButStatics(Map items) {
743 var result = {};
744 items.forEach((name, item) {
745 if (!item.isStatic) {
746 result[name] = item;
747 }
748 });
749 return result;
750 }
751
752 /// Add the subclass to the class.
753 ///
754 /// If [this] is private (or an intermediary mixin class), it will add the
755 /// subclass to the list of subclasses in the superclasses.
756 void addSubclass(Class subclass) {
757 if (docName == 'dart-core.Object') return;
758
759 if (!includePrivateMembers && isPrivate || mirror.isNameSynthetic) {
760 if (superclass != null) superclass.addSubclass(subclass);
761 interfaces.forEach((interface) {
762 interface.addSubclass(subclass);
763 });
764 } else {
765 subclasses.add(subclass);
766 }
767 }
768
769 /// Check if this [Class] is an error or exception.
770 bool isError() {
771 if (qualifiedName == 'dart-core.Error' ||
772 qualifiedName == 'dart-core.Exception')
773 return true;
774 for (var interface in interfaces) {
775 if (interface.isError()) return true;
776 }
777 if (superclass == null) return false;
778 return superclass.isError();
779 }
780
781 /// Makes sure that all methods with inherited equivalents have comments.
782 void ensureComments() {
783 if (_commentsEnsured) return;
784 _commentsEnsured = true;
785 if (superclass != null) superclass.ensureComments();
786 inheritedMethods.forEach((qualifiedName, inheritedMethod) {
787 var method = methods[qualifiedName];
788 if (method != null) {
789 // if we have overwritten this method in this class, we still provide
790 // the opportunity to inherit the comments.
791 method.ensureCommentFor(inheritedMethod);
792 }
793 });
794 // we need to populate the comments for all methods. so that the subclasses
795 // can get for their inherited versions the comments.
796 methods.forEach((qualifiedName, method) {
797 if (!method.mirror.isConstructor) method.ensureCommentFor(method);
798 });
799 }
800
801 /// If a class extends a private superclass, find the closest public
802 /// superclass of the private superclass.
803 String validSuperclass() {
804 if (superclass == null) return 'dart-core.Object';
805 if (superclass.isVisible) return superclass.qualifiedName;
806 return superclass.validSuperclass();
807 }
808
809 /// Generates a map describing the [Class] object.
810 Map toMap() => {
811 'name': name,
812 'qualifiedName': qualifiedName,
813 'comment': comment,
814 'isAbstract' : isAbstract,
815 'superclass': validSuperclass(),
816 'implements': interfaces.where((i) => i.isVisible)
817 .map((e) => e.qualifiedName).toList(),
818 'subclass': (subclasses.toList()..sort())
819 .map((x) => x.qualifiedName).toList(),
820 'variables': recurseMap(variables),
821 'inheritedVariables': recurseMap(inheritedVariables),
822 'methods': _expandMethodMap(methods),
823 'inheritedMethods': _expandMethodMap(inheritedMethods),
824 'annotations': annotations.map((a) => a.toMap()).toList(),
825 'generics': recurseMap(generics)
826 };
827
828 int compareTo(aClass) => name.compareTo(aClass.name);
829
830 bool isValidMirror(DeclarationMirror mirror) => mirror is ClassMirror;
831 }
832
833 class Typedef extends OwnedIndexable {
834 String returnType;
835
836 Map<String, Parameter> parameters;
837
838 /// Generic information about the typedef.
839 Map<String, Generic> generics;
840
841 /// Returns the [Library] for the given [mirror] if it has already been
842 /// created, else creates it.
843 factory Typedef(TypedefMirror mirror, Library owningLibrary) {
844 var aTypedef = getDocgenObject(mirror, owningLibrary);
845 if (aTypedef is DummyMirror) {
846 aTypedef = new Typedef._(mirror, owningLibrary);
847 }
848 return aTypedef;
849 }
850
851 Typedef._(TypedefMirror mirror, Library owningLibrary) :
852 super(mirror, owningLibrary) {
853 returnType = getDocgenObject(mirror.referent.returnType).docName;
854 generics = _createGenerics(mirror);
855 parameters = _createParameters(mirror.referent.parameters, owningLibrary);
856 annotations = createAnnotations(mirror, owningLibrary);
857 }
858
859 Map toMap() {
860 var map = {
861 'name': name,
862 'qualifiedName': qualifiedName,
863 'comment': comment,
864 'return': returnType,
865 'parameters': recurseMap(parameters),
866 'annotations': annotations.map((a) => a.toMap()).toList(),
867 'generics': recurseMap(generics)
868 };
869
870 // Typedef is displayed on the library page as a class, so a preview is
871 // added manually
872 var preview = _preview;
873 if(preview != null) map['preview'] = preview;
874
875 return map;
876 }
877
878 markdown.Node fixReference(String name) => null;
879
880 String get typeName => 'typedef';
881
882 bool isValidMirror(DeclarationMirror mirror) => mirror is TypedefMirror;
883 }
884
885 /// A class containing properties of a Dart variable.
886 class Variable extends OwnedIndexable {
887
888 bool isFinal;
889 bool isStatic;
890 bool isConst;
891 Type type;
892 String _variableName;
893
894 factory Variable(String variableName, VariableMirror mirror,
895 Indexable owner) {
896 var variable = getDocgenObject(mirror);
897 if (variable is DummyMirror) {
898 return new Variable._(variableName, mirror, owner);
899 }
900 return variable;
901 }
902
903 Variable._(this._variableName, VariableMirror mirror, Indexable owner) :
904 super(mirror, owner) {
905 isFinal = mirror.isFinal;
906 isStatic = mirror.isStatic;
907 isConst = mirror.isConst;
908 type = new Type(mirror.type, owner._owningLibrary);
909 annotations = createAnnotations(mirror, owner._owningLibrary);
910 }
911
912 String get name => _variableName;
913
914 /// Generates a map describing the [Variable] object.
915 Map toMap() => {
916 'name': name,
917 'qualifiedName': qualifiedName,
918 'comment': comment,
919 'final': isFinal,
920 'static': isStatic,
921 'constant': isConst,
922 'type': new List.filled(1, type.toMap()),
923 'annotations': annotations.map((a) => a.toMap()).toList()
924 };
925
926 String get typeName => 'property';
927
928 get comment {
929 if (_comment != null) return _comment;
930 if (owner is Class) {
931 (owner as Class).ensureComments();
932 }
933 return super.comment;
934 }
935
936 String findElementInScope(String name) {
937 var lookupFunc = determineLookupFunc(name);
938 var result = lookupFunc(mirror, name);
939 if (result != null) {
940 result = getDocgenObject(result);
941 if (result is DummyMirror) return packagePrefix + result.docName;
942 return result.packagePrefix + result.docName;
943 }
944
945 if (owner != null) {
946 var result = owner.findElementInScope(name);
947 if (result != null) {
948 return result;
949 }
950 }
951 return super.findElementInScope(name);
952 }
953
954 bool isValidMirror(DeclarationMirror mirror) => mirror is VariableMirror;
955 }
956
957 /// A class containing properties of a Dart method.
958 class Method extends OwnedIndexable {
959
960 /// Parameters for this method.
961 Map<String, Parameter> parameters;
962
963 bool isStatic;
964 bool isAbstract;
965 bool isConst;
966 Type returnType;
967 Method methodInheritedFrom;
968
969 /// Qualified name to state where the comment is inherited from.
970 String commentInheritedFrom = "";
971
972 factory Method(MethodMirror mirror, Indexable owner,
973 [Method methodInheritedFrom]) {
974 var method = getDocgenObject(mirror, owner);
975 if (method is DummyMirror) {
976 method = new Method._(mirror, owner, methodInheritedFrom);
977 }
978 return method;
979 }
980
981 Method._(MethodMirror mirror, Indexable owner, this.methodInheritedFrom)
982 : super(mirror, owner) {
983 isStatic = mirror.isStatic;
984 isAbstract = mirror.isAbstract;
985 isConst = mirror.isConstConstructor;
986 returnType = new Type(mirror.returnType, owner._owningLibrary);
987 parameters = _createParameters(mirror.parameters, owner);
988 annotations = createAnnotations(mirror, owner._owningLibrary);
989 }
990
991 Method get originallyInheritedFrom => methodInheritedFrom == null ?
992 this : methodInheritedFrom.originallyInheritedFrom;
993
994 /// Look for the specified name starting with the current member, and
995 /// progressively working outward to the current library scope.
996 String findElementInScope(String name) {
997 var lookupFunc = determineLookupFunc(name);
998
999 var memberScope = lookupFunc(this.mirror, name);
1000 if (memberScope != null) {
1001 // do we check for a dummy mirror returned here and look up with an owner
1002 // higher ooooor in getDocgenObject do we include more things in our
1003 // lookup
1004 var result = getDocgenObject(memberScope, owner);
1005 if (result is DummyMirror && owner.owner != null
1006 && owner.owner is! DummyMirror) {
1007 var aresult = getDocgenObject(memberScope, owner.owner);
1008 if (aresult is! DummyMirror) result = aresult;
1009 }
1010 if (result is DummyMirror) return packagePrefix + result.docName;
1011 return result.packagePrefix + result.docName;
1012 }
1013
1014 if (owner != null) {
1015 var result = owner.findElementInScope(name);
1016 if (result != null) return result;
1017 }
1018 return super.findElementInScope(name);
1019 }
1020
1021 String get docName {
1022 if ((mirror as MethodMirror).isConstructor) {
1023 // We name constructors specially -- including the class name again and a
1024 // "-" to separate the constructor from its name (if any).
1025 return '${owner.docName}.${dart2js_util.nameOf(mirror.owner)}-'
1026 '${dart2js_util.nameOf(mirror)}';
1027 }
1028 return super.docName;
1029 }
1030
1031 String get fileName => packagePrefix + docName;
1032
1033 /// Makes sure that the method with an inherited equivalent have comments.
1034 void ensureCommentFor(Method inheritedMethod) {
1035 if (comment.isNotEmpty) return;
1036
1037 comment = inheritedMethod._commentToHtml(this);
1038 _unresolvedComment = inheritedMethod._unresolvedComment;
1039 commentInheritedFrom = inheritedMethod.commentInheritedFrom == '' ?
1040 new DummyMirror(inheritedMethod.mirror).docName :
1041 inheritedMethod.commentInheritedFrom;
1042 }
1043
1044 /// Generates a map describing the [Method] object.
1045 Map toMap() => {
1046 'name': name,
1047 'qualifiedName': qualifiedName,
1048 'comment': comment,
1049 'commentFrom': (methodInheritedFrom != null &&
1050 commentInheritedFrom == methodInheritedFrom.docName ? ''
1051 : commentInheritedFrom),
1052 'inheritedFrom': (methodInheritedFrom == null? '' :
1053 originallyInheritedFrom.docName),
1054 'static': isStatic,
1055 'abstract': isAbstract,
1056 'constant': isConst,
1057 'return': new List.filled(1, returnType.toMap()),
1058 'parameters': recurseMap(parameters),
1059 'annotations': annotations.map((a) => a.toMap()).toList()
1060 };
1061
1062 String get typeName {
1063 MethodMirror theMirror = mirror;
1064 if (theMirror.isConstructor) return 'constructor';
1065 if (theMirror.isGetter) return 'getter';
1066 if (theMirror.isSetter) return'setter';
1067 if (theMirror.isOperator) return 'operator';
1068 return 'method';
1069 }
1070
1071 get comment {
1072 if (_comment != null) return _comment;
1073 if (owner is Class) {
1074 (owner as Class).ensureComments();
1075 }
1076 var result = super.comment;
1077 if (result == '' && methodInheritedFrom != null) {
1078 // This should be NOT from the MIRROR, but from the COMMENT.
1079 methodInheritedFrom.comment; // Ensure comment field has been populated.
1080 _unresolvedComment = methodInheritedFrom._unresolvedComment;
1081
1082 var linkResolver = (name) => fixReference(name);
1083 comment = _unresolvedComment == null ? '' :
1084 markdown.markdownToHtml(_unresolvedComment.trim(),
1085 linkResolver: linkResolver, inlineSyntaxes: MARKDOWN_SYNTAXES);
1086 commentInheritedFrom = comment != '' ?
1087 methodInheritedFrom.commentInheritedFrom : '';
1088 result = comment;
1089 }
1090 return result;
1091 }
1092
1093 bool isValidMirror(DeclarationMirror mirror) => mirror is MethodMirror;
1094 }
1095
1096 /// Docgen wrapper around the dart2js mirror for a Dart
1097 /// method/function parameter.
1098 class Parameter extends MirrorBased {
1099 final ParameterMirror mirror;
1100 final String name;
1101 final bool isOptional;
1102 final bool isNamed;
1103 final bool hasDefaultValue;
1104 final Type type;
1105 final String defaultValue;
1106 /// List of the meta annotations on the parameter.
1107 final List<Annotation> annotations;
1108
1109 Parameter(ParameterMirror mirror, Library owningLibrary)
1110 : this.mirror = mirror,
1111 name = dart2js_util.nameOf(mirror),
1112 isOptional = mirror.isOptional,
1113 isNamed = mirror.isNamed,
1114 hasDefaultValue = mirror.hasDefaultValue,
1115 defaultValue = '${mirror.defaultValue}',
1116 type = new Type(mirror.type, owningLibrary),
1117 annotations = createAnnotations(mirror, owningLibrary);
1118
1119 /// Generates a map describing the [Parameter] object.
1120 Map toMap() => {
1121 'name': name,
1122 'optional': isOptional,
1123 'named': isNamed,
1124 'default': hasDefaultValue,
1125 'type': new List.filled(1, type.toMap()),
1126 'value': defaultValue,
1127 'annotations': annotations.map((a) => a.toMap()).toList()
1128 };
1129 }
1130
1131 /// Docgen wrapper around the mirror for a return type, and/or its generic
1132 /// type parameters.
1133 ///
1134 /// Return types are of a form [outer]<[inner]>.
1135 /// If there is no [inner] part, [inner] will be an empty list.
1136 ///
1137 /// For example:
1138 /// int size()
1139 /// "return" :
1140 /// - "outer" : "dart-core.int"
1141 /// "inner" :
1142 ///
1143 /// List<String> toList()
1144 /// "return" :
1145 /// - "outer" : "dart-core.List"
1146 /// "inner" :
1147 /// - "outer" : "dart-core.String"
1148 /// "inner" :
1149 ///
1150 /// Map<String, List<int>>
1151 /// "return" :
1152 /// - "outer" : "dart-core.Map"
1153 /// "inner" :
1154 /// - "outer" : "dart-core.String"
1155 /// "inner" :
1156 /// - "outer" : "dart-core.List"
1157 /// "inner" :
1158 /// - "outer" : "dart-core.int"
1159 /// "inner" :
1160 class Type extends MirrorBased {
1161 final TypeMirror mirror;
1162 final Library owningLibrary;
1163
1164 Type(this.mirror, this.owningLibrary);
1165
1166 /// Returns a list of [Type] objects constructed from TypeMirrors.
1167 List<Type> _createTypeGenerics(TypeMirror mirror) {
1168 if (mirror is ClassMirror) {
1169 var innerList = [];
1170 mirror.typeArguments.forEach((e) {
1171 innerList.add(new Type(e, owningLibrary));
1172 });
1173 return innerList;
1174 }
1175 return [];
1176 }
1177
1178 Map toMap() {
1179 var result = getDocgenObject(mirror, owningLibrary);
1180 return {
1181 // We may encounter types whose corresponding library has not been
1182 // processed yet, so look up with the owningLibrary at the last moment.
1183 'outer': result.packagePrefix + result.docName,
1184 'inner': _createTypeGenerics(mirror).map((e) => e.toMap()).toList(),
1185 };
1186 }
1187 }
1188
1189 /// Holds the name of the annotation, and its parameters.
1190 class Annotation extends MirrorBased {
1191 /// The class of this annotation.
1192 final ClassMirror mirror;
1193 final Library owningLibrary;
1194 List<String> parameters;
1195
1196 Annotation(InstanceMirror originalMirror, this.owningLibrary)
1197 : mirror = originalMirror.type {
1198 parameters = dart2js_util.variablesOf(originalMirror.type.declarations)
1199 .where((e) => e.isFinal)
1200 .map((e) => originalMirror.getField(e.simpleName).reflectee)
1201 .where((e) => e != null)
1202 .toList();
1203 }
1204
1205 Map toMap() => {
1206 'name': getDocgenObject(mirror, owningLibrary).docName,
1207 'parameters': parameters
1208 };
1209 }
OLDNEW
« no previous file with comments | « pkg/docgen/lib/src/model_helpers.dart ('k') | pkg/docgen/lib/src/package_helpers.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698