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

Side by Side Diff: pkg/docgen/lib/docgen.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/bin/docgen.dart ('k') | pkg/docgen/lib/src/generator.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) 2013, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2013, 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 /// **docgen** is a tool for creating machine readable representations of Dart 5 /// **docgen** is a tool for creating machine readable representations of Dart
6 /// code metadata, including: classes, members, comments and annotations. 6 /// code metadata, including: classes, members, comments and annotations.
7 /// 7 ///
8 /// docgen is run on a `.dart` file or a directory containing `.dart` files. 8 /// docgen is run on a `.dart` file or a directory containing `.dart` files.
9 /// 9 ///
10 /// $ dart docgen.dart [OPTIONS] [FILE/DIR] 10 /// $ dart docgen.dart [OPTIONS] [FILE/DIR]
11 /// 11 ///
12 /// This creates files called `docs/<library_name>.yaml` in your current 12 /// This creates files called `docs/<library_name>.yaml` in your current
13 /// working directory. 13 /// working directory.
14 library docgen; 14 library docgen;
15 15
16 import 'dart:convert';
17 import 'dart:io';
18 import 'dart:async'; 16 import 'dart:async';
19 17
20 import 'package:logging/logging.dart'; 18 import 'src/generator.dart' as gen;
21 import 'package:markdown/markdown.dart' as markdown; 19 import 'src/viewer.dart' as viewer;
22 import 'package:path/path.dart' as path;
23 import 'package:yaml/yaml.dart';
24 20
25 import 'src/dart2yaml.dart'; 21 export 'src/generator.dart' show getMirrorSystem;
26 import 'src/io.dart'; 22 export 'src/library_helpers.dart' show getDocgenObject;
27 import 'src/mdn.dart'; 23 export 'src/models.dart';
28 import 'src/models.dart'; 24 export 'src/package_helpers.dart' show packageNameFor;
29 import 'src/utils.dart';
30
31 import '../../../sdk/lib/_internal/compiler/compiler.dart' as api;
32 import '../../../sdk/lib/_internal/compiler/implementation/filenames.dart';
33 import '../../../sdk/lib/_internal/compiler/implementation/mirrors/dart2js_mirro rs.dart'
34 as dart2js_mirrors;
35 import '../../../sdk/lib/_internal/compiler/implementation/mirrors/analyze.dart'
36 as dart2js;
37 import '../../../sdk/lib/_internal/compiler/implementation/mirrors/source_mirror s.dart';
38 import '../../../sdk/lib/_internal/compiler/implementation/mirrors/mirrors_util. dart'
39 as dart2js_util;
40 import '../../../sdk/lib/_internal/compiler/implementation/source_file_provider. dart';
41 import '../../../sdk/lib/_internal/libraries.dart';
42
43 const _DEFAULT_OUTPUT_DIRECTORY = 'docs';
44
45 /// Annotations that we do not display in the viewer.
46 const List<String> _SKIPPED_ANNOTATIONS = const [
47 'metadata.DocsEditable', '_js_helper.JSName', '_js_helper.Creates',
48 '_js_helper.Returns'];
49
50 /// Support for [:foo:]-style code comments to the markdown parser.
51 final List<markdown.InlineSyntax> _MARKDOWN_SYNTAXES =
52 [new markdown.CodeSyntax(r'\[:\s?((?:.|\n)*?)\s?:\]')];
53
54 /// If we can't find the SDK introduction text, which will happen if running
55 /// from a snapshot and using --parse-sdk or --include-sdk, then use this
56 /// hard-coded version. This should be updated to be consistent with the text
57 /// in docgen/doc/sdk-introduction.md
58 const _DEFAULT_SDK_INTRODUCTION = """
59 Welcome to the Dart API reference documentation,
60 covering the official Dart API libraries.
61 Some of the most fundamental Dart libraries include:
62
63 * [dart:core](#dart:core):
64 Core functionality such as strings, numbers, collections, errors,
65 dates, and URIs.
66 * [dart:html](#dart:html):
67 DOM manipulation for web apps.
68 * [dart:io](#dart:io):
69 I/O for command-line apps.
70
71 Except for dart:core, you must import a library before you can use it.
72 Here's an example of importing dart:html, dart:math, and a
73 third popular library called
74 [polymer.dart](http://www.dartlang.org/polymer-dart/):
75
76 import 'dart:html';
77 import 'dart:math';
78 import 'package:polymer/polymer.dart';
79
80 Polymer.dart is an example of a library that isn't
81 included in the Dart download,
82 but is easy to get and update using the _pub package manager_.
83 For information on finding, using, and publishing libraries (and more)
84 with pub, see
85 [pub.dartlang.org](http://pub.dartlang.org).
86
87 The main site for learning and using Dart is
88 [www.dartlang.org](http://www.dartlang.org).
89 Check out these pages:
90
91 * [Dart homepage](http://www.dartlang.org)
92 * [Tutorials](http://www.dartlang.org/docs/tutorials/)
93 * [Programmer's Guide](http://www.dartlang.org/docs/)
94 * [Samples](http://www.dartlang.org/samples/)
95 * [A Tour of the Dart Libraries](http://www.dartlang.org/docs/dart-up-and-runn ing/contents/ch03.html)
96
97 This API reference is automatically generated from the source code in the
98 [Dart project](https://code.google.com/p/dart/).
99 If you'd like to contribute to this documentation, see
100 [Contributing](https://code.google.com/p/dart/wiki/Contributing)
101 and
102 [Writing API Documentation](https://code.google.com/p/dart/wiki/WritingApiDocume ntation).
103 """;
104 25
105 /// Docgen constructor initializes the link resolver for markdown parsing. 26 /// Docgen constructor initializes the link resolver for markdown parsing.
106 /// Also initializes the command line arguments. 27 /// Also initializes the command line arguments.
107 /// 28 ///
108 /// [packageRoot] is the packages directory of the directory being analyzed. 29 /// [packageRoot] is the packages directory of the directory being analyzed.
109 /// If [includeSdk] is `true`, then any SDK libraries explicitly imported will 30 /// If [includeSdk] is `true`, then any SDK libraries explicitly imported will
110 /// also be documented. 31 /// also be documented.
111 /// If [parseSdk] is `true`, then all Dart SDK libraries will be documented. 32 /// If [parseSdk] is `true`, then all Dart SDK libraries will be documented.
112 /// This option is useful when only the SDK libraries are needed. 33 /// This option is useful when only the SDK libraries are needed.
113 /// If [compile] is `true`, then after generating the documents, compile the 34 /// If [compile] is `true`, then after generating the documents, compile the
114 /// viewer with dart2js. 35 /// viewer with dart2js.
115 /// If [serve] is `true`, then after generating the documents we fire up a 36 /// If [serve] is `true`, then after generating the documents we fire up a
116 /// simple server to view the documentation. 37 /// simple server to view the documentation.
117 /// 38 ///
118 /// Returned Future completes with true if document generation is successful. 39 /// Returned Future completes with true if document generation is successful.
119 Future<bool> docgen(List<String> files, {String packageRoot, 40 Future<bool> docgen(List<String> files, {String packageRoot,
120 bool outputToYaml: false, bool includePrivate: false, bool includeSdk: false , 41 bool outputToYaml: false, bool includePrivate: false,
121 bool parseSdk: false, bool append: false, String introFileName: '', 42 bool includeSdk: false, bool parseSdk: false, bool append: false,
122 String out: _DEFAULT_OUTPUT_DIRECTORY, 43 String introFileName: '', String out: gen.DEFAULT_OUTPUT_DIRECTORY,
123 List<String> excludeLibraries : const [], 44 List<String> excludeLibraries: const [],
124 bool includeDependentPackages: false, bool compile: false, 45 bool includeDependentPackages: false, bool compile: false,
125 bool serve: false, bool noDocs: false, String startPage, String pubScript, 46 bool serve: false, bool noDocs: false, String startPage, String pubScript,
126 String dartBinary}) { 47 String dartBinary}) {
127 var result; 48 var result;
128 if (!noDocs) { 49 if (!noDocs) {
129 _Viewer.ensureMovedViewerCode(); 50 viewer.ensureMovedViewerCode();
130 result = _Generator.generateDocumentation(files, packageRoot: packageRoot, 51 result = gen.generateDocumentation(files, packageRoot: packageRoot,
131 outputToYaml: outputToYaml, includePrivate: includePrivate, 52 outputToYaml: outputToYaml, includePrivate: includePrivate,
132 includeSdk: includeSdk, parseSdk: parseSdk, append: append, 53 includeSdk: includeSdk, parseSdk: parseSdk, append: append,
133 introFileName: introFileName, out: out, 54 introFileName: introFileName, out: out,
134 excludeLibraries: excludeLibraries, 55 excludeLibraries: excludeLibraries,
135 includeDependentPackages: includeDependentPackages, 56 includeDependentPackages: includeDependentPackages,
136 startPage: startPage, pubScript: pubScript, dartBinary: dartBinary); 57 startPage: startPage, pubScript: pubScript, dartBinary: dartBinary);
137 _Viewer.addBackViewerCode(); 58 viewer.addBackViewerCode();
138 if (compile || serve) { 59 if (compile || serve) {
139 result.then((success) { 60 result.then((success) {
140 if (success) { 61 if (success) {
141 _createViewer(serve); 62 viewer.createViewer(serve);
142 } 63 }
143 }); 64 });
144 } 65 }
145 } else if (compile || serve) { 66 } else if (compile || serve) {
146 _createViewer(serve); 67 viewer.createViewer(serve);
147 } 68 }
148 return result; 69 return result;
149 } 70 }
150
151 void _createViewer(bool serve) {
152 _Viewer._clone();
153 _Viewer._compile();
154 if (serve) {
155 _Viewer._runServer();
156 }
157 }
158
159 /// Analyzes set of libraries by getting a mirror system and triggers the
160 /// documentation of the libraries.
161 Future<MirrorSystem> getMirrorSystem(List<Uri> libraries,
162 {String packageRoot, bool parseSdk: false}) {
163 if (libraries.isEmpty) throw new StateError('No Libraries.');
164
165 // Finds the root of SDK library based off the location of docgen.
166 // We have two different places to look, depending if we're in a development
167 // repo or in a built SDK, either sdk or dart-sdk respectively
168 var root = _Generator._rootDirectory;
169 var sdkRoot = path.normalize(path.absolute(path.join(root, 'sdk')));
170 if (!new Directory(sdkRoot).existsSync()) {
171 sdkRoot = path.normalize(path.absolute(path.join(root, 'dart-sdk')));
172 }
173 _Generator.logger.info('SDK Root: ${sdkRoot}');
174 return _Generator._analyzeLibraries(libraries, sdkRoot,
175 packageRoot: packageRoot);
176 }
177
178 /// For types that we do not explicitly create or have not yet created in our
179 /// entity map (like core types).
180 class DummyMirror implements Indexable {
181 DeclarationMirror mirror;
182 /// The library that contains this element, if any. Used as a hint to help
183 /// determine which object we're referring to when looking up this mirror in
184 /// our map.
185 Indexable owner;
186 DummyMirror(this.mirror, [this.owner]);
187
188 String get docName {
189 if (mirror == null) return '';
190 if (mirror is LibraryMirror) {
191 return dart2js_util.qualifiedNameOf(mirror).replaceAll('.','-');
192 }
193 var mirrorOwner = mirror.owner;
194 if (mirrorOwner == null) return dart2js_util.qualifiedNameOf(mirror);
195 var simpleName = dart2js_util.nameOf(mirror);
196 if (mirror is MethodMirror && (mirror as MethodMirror).isConstructor) {
197 // We name constructors specially -- repeating the class name and a
198 // "-" to separate the constructor from its name (if any).
199 simpleName = '${dart2js_util.nameOf(mirrorOwner)}-$simpleName';
200 }
201 return Indexable.getDocgenObject(mirrorOwner, owner).docName + '.' +
202 simpleName;
203 }
204
205 bool get isPrivate => mirror == null? false : mirror.isPrivate;
206
207 String get packageName {
208 var libMirror = _getOwningLibraryFromMirror(mirror);
209 if (libMirror != null) {
210 return Library._packageName(libMirror);
211 }
212 return '';
213 }
214
215 String get packagePrefix => packageName == null || packageName.isEmpty ?
216 '' : '$packageName/';
217
218 LibraryMirror _getOwningLibraryFromMirror(DeclarationMirror mirror) {
219 if (mirror is LibraryMirror) return mirror;
220 if (mirror == null) return null;
221 return _getOwningLibraryFromMirror(mirror.owner);
222 }
223 }
224
225 /// Top level documentation traversal and generation object.
226 ///
227 /// Yes, everything in this class is used statically so this technically doesn't
228 /// need to be its own class, but it's grouped together for semantic separation
229 /// from the other classes and functionality in this library.
230 class _Generator {
231 /// The directory where the output docs are generated.
232 static String _outputDirectory;
233
234 /// This is set from the command line arguments flag --include-private
235 static bool _includePrivate = false;
236
237 /// Library names to explicitly exclude.
238 ///
239 /// Set from the command line option
240 /// --exclude-lib.
241 static List<String> _excluded;
242
243 /// The path of the pub script.
244 static String _pubScript;
245
246 /// The path of Dart binary.
247 static String _dartBinary;
248
249 /// Logger for printing out progress of documentation generation.
250 static Logger logger = new Logger('Docgen');
251
252 /// Docgen constructor initializes the link resolver for markdown parsing.
253 /// Also initializes the command line arguments.
254 ///
255 /// [packageRoot] is the packages directory of the directory being analyzed.
256 /// If [includeSdk] is `true`, then any SDK libraries explicitly imported will
257 /// also be documented.
258 /// If [parseSdk] is `true`, then all Dart SDK libraries will be documented.
259 /// This option is useful when only the SDK libraries are needed.
260 ///
261 /// Returned Future completes with true if document generation is successful.
262 static Future<bool> generateDocumentation(List<String> files,
263 {String packageRoot, bool outputToYaml: true, bool includePrivate: false,
264 bool includeSdk: false, bool parseSdk: false, bool append: false,
265 String introFileName: '', out: _DEFAULT_OUTPUT_DIRECTORY,
266 List<String> excludeLibraries : const [],
267 bool includeDependentPackages: false, String startPage,
268 String dartBinary, String pubScript}) {
269 _excluded = excludeLibraries;
270 _includePrivate = includePrivate;
271 _pubScript = pubScript;
272 _dartBinary = dartBinary;
273
274 logger.onRecord.listen((record) => print(record.message));
275
276 _ensureOutputDirectory(out, append);
277 var updatedPackageRoot = _obtainPackageRoot(packageRoot, parseSdk, files);
278
279 var requestedLibraries = _findLibrariesToDocument(files,
280 includeDependentPackages);
281
282 var allLibraries = []..addAll(requestedLibraries);
283 if (includeSdk) {
284 allLibraries.addAll(_listSdk());
285 }
286
287 return getMirrorSystem(allLibraries, packageRoot: updatedPackageRoot,
288 parseSdk: parseSdk)
289 .then((MirrorSystem mirrorSystem) {
290 if (mirrorSystem.libraries.isEmpty) {
291 throw new StateError('No library mirrors were created.');
292 }
293 Indexable._initializeTopLevelLibraries(mirrorSystem);
294
295 var availableLibraries = mirrorSystem.libraries.values.where(
296 (each) => each.uri.scheme == 'file');
297 var availableLibrariesByPath = new Map.fromIterables(
298 availableLibraries.map((each) => each.uri),
299 availableLibraries);
300 var librariesToDocument = requestedLibraries.map(
301 (each) => availableLibrariesByPath.putIfAbsent(each,
302 () => throw "Missing library $each")).toList();
303 librariesToDocument.addAll(
304 (includeSdk || parseSdk) ? Indexable._sdkLibraries : []);
305 librariesToDocument.removeWhere(
306 (x) => _excluded.contains(dart2js_util.nameOf(x)));
307 _documentLibraries(librariesToDocument, includeSdk: includeSdk,
308 outputToYaml: outputToYaml, append: append, parseSdk: parseSdk,
309 introFileName: introFileName, startPage: startPage);
310 return true;
311 });
312 }
313
314 /// Writes [text] to a file in the output directory.
315 static void _writeToFile(String text, String filename, {bool append: false}) {
316 if (text == null) return;
317 Directory dir = new Directory(_outputDirectory);
318 if (!dir.existsSync()) {
319 dir.createSync();
320 }
321 if (path.split(filename).length > 1) {
322 var splitList = path.split(filename);
323 for (int i = 0; i < splitList.length; i++) {
324 var level = splitList[i];
325 }
326 for (var level in path.split(filename)) {
327 var subdir = new Directory(path.join(_outputDirectory,
328 path.dirname(filename)));
329 if (!subdir.existsSync()) {
330 subdir.createSync();
331 }
332 }
333 }
334 File file = new File(path.join(_outputDirectory, filename));
335 file.writeAsStringSync(text,
336 mode: append ? FileMode.APPEND : FileMode.WRITE);
337 }
338
339 /// Resolve all the links in the introductory comments for a given library or
340 /// package as specified by [filename].
341 static String _readIntroductionFile(String fileName, bool includeSdk) {
342 var linkResolver = (name) => Indexable.globalFixReference(name);
343 var defaultText = includeSdk ? _DEFAULT_SDK_INTRODUCTION : '';
344 var introText = defaultText;
345 if (fileName.isNotEmpty) {
346 var introFile = new File(fileName);
347 introText = introFile.existsSync() ? introFile.readAsStringSync() :
348 defaultText;
349 }
350 return markdown.markdownToHtml(introText,
351 linkResolver: linkResolver, inlineSyntaxes: _MARKDOWN_SYNTAXES);
352 }
353
354 /// Creates documentation for filtered libraries.
355 static void _documentLibraries(List<LibraryMirror> libs,
356 {bool includeSdk: false, bool outputToYaml: true, bool append: false,
357 bool parseSdk: false, String introFileName: '', String startPage}) {
358 libs.forEach((lib) {
359 // Files belonging to the SDK have a uri that begins with 'dart:'.
360 if (includeSdk || !lib.uri.toString().startsWith('dart:')) {
361 generateLibrary(lib);
362 }
363 });
364
365 var filteredEntities = new Set<Indexable>();
366 for (Map<String, Set<Indexable>> firstLevel in
367 Indexable._mirrorToDocgen.values) {
368 for (Set<Indexable> items in firstLevel.values) {
369 for (Indexable item in items) {
370 if (_isFullChainVisible(item)) {
371 if (item is! Method ||
372 (item is Method && item.methodInheritedFrom == null)) {
373 filteredEntities.add(item);
374 }
375 }
376 }
377 }
378 }
379
380 // Outputs a JSON file with all libraries and their preview comments.
381 // This will help the viewer know what libraries are available to read in.
382 Map<String, dynamic> libraryMap;
383
384 if (append) {
385 var docsDir = listDir(_outputDirectory);
386 if (!docsDir.contains('$_outputDirectory/library_list.json')) {
387 throw new StateError('No library_list.json');
388 }
389 libraryMap =
390 JSON.decode(new File(
391 '$_outputDirectory/library_list.json').readAsStringSync());
392 libraryMap['libraries'].addAll(filteredEntities
393 .where((e) => e is Library)
394 .map((e) => e.previewMap));
395 var intro = libraryMap['introduction'];
396 var spacing = intro.isEmpty ? '' : '<br/><br/>';
397 libraryMap['introduction'] =
398 "$intro$spacing${_readIntroductionFile(introFileName, includeSdk)}";
399 outputToYaml = libraryMap['filetype'] == 'yaml';
400 } else {
401 libraryMap = {
402 'libraries' : filteredEntities.where((e) =>
403 e is Library).map((e) => e.previewMap).toList(),
404 'introduction' : _readIntroductionFile(introFileName, includeSdk),
405 'filetype' : outputToYaml ? 'yaml' : 'json'
406 };
407 }
408 _writeOutputFiles(libraryMap, filteredEntities, outputToYaml, append,
409 startPage);
410 }
411
412 /// Output all of the libraries and classes into json or yaml files for
413 /// consumption by a viewer.
414 static void _writeOutputFiles(Map<String, dynamic> libraryMap,
415 Iterable<Indexable> filteredEntities, bool outputToYaml, bool append,
416 String startPage) {
417 if (startPage != null) libraryMap['start-page'] = startPage;
418
419 _writeToFile(JSON.encode(libraryMap), 'library_list.json');
420
421 // Output libraries and classes to file after all information is generated.
422 filteredEntities.where((e) => e is Class || e is Library).forEach((output) {
423 _writeIndexableToFile(output, outputToYaml);
424 });
425
426 // Outputs all the qualified names documented with their type.
427 // This will help generate search results.
428 var sortedEntities = filteredEntities.map((e) =>
429 '${e.qualifiedName} ${e.typeName}').toList()..sort();
430
431 _writeToFile(sortedEntities.join('\n') + '\n',
432 'index.txt', append: append);
433 var index = new Map.fromIterables(
434 filteredEntities.map((e) => e.qualifiedName),
435 filteredEntities.map((e) => e.typeName));
436 if (append) {
437 var previousIndex =
438 JSON.decode(new File(
439 '$_outputDirectory/index.json').readAsStringSync());
440 index.addAll(previousIndex);
441 }
442 _writeToFile(JSON.encode(index), 'index.json');
443 }
444
445 /// Helper method to serialize the given Indexable out to a file.
446 static void _writeIndexableToFile(Indexable result, bool outputToYaml) {
447 var outputFile = result.fileName;
448 var output;
449 if (outputToYaml) {
450 output = getYamlString(result.toMap());
451 outputFile = outputFile + '.yaml';
452 } else {
453 output = JSON.encode(result.toMap());
454 outputFile = outputFile + '.json';
455 }
456 _writeToFile(output, outputFile);
457 }
458
459 /// Set the location of the ouput directory, and ensure that the location is
460 /// available on the file system.
461 static void _ensureOutputDirectory(String outputDirectory, bool append) {
462 _outputDirectory = outputDirectory;
463 if (!append) {
464 var dir = new Directory(_outputDirectory);
465 if (dir.existsSync()) dir.deleteSync(recursive: true);
466 }
467 }
468
469 /// Helper accessor to determine the full pathname of the root of the dart
470 /// checkout. We can be in one of three situations:
471 /// 1) Running from pkg/docgen/bin/docgen.dart
472 /// 2) Running from a snapshot in a build,
473 /// e.g. xcodebuild/ReleaseIA32/dart-sdk/bin
474 /// 3) Running from a built distribution,
475 /// e.g. ...somename/dart-sdk/bin/snapshots
476 static String get _rootDirectory {
477 var scriptDir = path.absolute(path.dirname(Platform.script.toFilePath()));
478 var root = scriptDir;
479 var base = path.basename(root);
480 // When we find dart-sdk or sdk we are one level below the root.
481 while (base != 'dart-sdk' && base != 'sdk' && base != 'pkg') {
482 root = path.dirname(root);
483 base = path.basename(root);
484 if (root == base) {
485 // We have reached the root of the filesystem without finding anything.
486 throw new FileSystemException(
487 "Cannot find SDK directory starting from ",
488 scriptDir);
489 }
490 }
491 return path.dirname(root);
492 }
493
494 /// Analyzes set of libraries and provides a mirror system which can be used
495 /// for static inspection of the source code.
496 static Future<MirrorSystem> _analyzeLibraries(List<Uri> libraries,
497 String libraryRoot, {String packageRoot}) {
498 SourceFileProvider provider = new CompilerSourceFileProvider();
499 api.DiagnosticHandler diagnosticHandler =
500 (new FormattingDiagnosticHandler(provider)
501 ..showHints = false
502 ..showWarnings = false)
503 .diagnosticHandler;
504 Uri libraryUri = new Uri.file(appendSlash(libraryRoot));
505 Uri packageUri = null;
506 if (packageRoot != null) {
507 packageUri = new Uri.file(appendSlash(packageRoot));
508 }
509 return dart2js.analyze(libraries, libraryUri, packageUri,
510 provider.readStringFromUri, diagnosticHandler,
511 ['--preserve-comments', '--categories=Client,Server'])
512 ..catchError((error) {
513 logger.severe('Error: Failed to create mirror system. ');
514 // TODO(janicejl): Use the stack trace package when bug is resolved.
515 // Currently, a string is thrown when it fails to create a mirror
516 // system, and it is not possible to use the stack trace. BUG(#11622)
517 // To avoid printing the stack trace.
518 exit(1);
519 });
520 }
521
522 /// For this run of docgen, determine the packageRoot value.
523 ///
524 /// If packageRoot is not explicitly passed, we examine the files we're
525 /// documenting to attempt to find a package root.
526 static String _obtainPackageRoot(String packageRoot, bool parseSdk,
527 List<String> files) {
528 if (packageRoot == null && !parseSdk) {
529 var type = FileSystemEntity.typeSync(files.first);
530 if (type == FileSystemEntityType.DIRECTORY) {
531 var files2 = listDir(files.first, recursive: true);
532 // Return '' means that there was no pubspec.yaml and therefor no p
533 // ackageRoot.
534 packageRoot = files2.firstWhere((f) =>
535 f.endsWith('${path.separator}pubspec.yaml'), orElse: () => '');
536 if (packageRoot != '') {
537 packageRoot = path.join(path.dirname(packageRoot), 'packages');
538 }
539 } else if (type == FileSystemEntityType.FILE) {
540 logger.warning('WARNING: No package root defined. If Docgen fails, try '
541 'again by setting the --package-root option.');
542 }
543 }
544 logger.info('Package Root: ${packageRoot}');
545 return path.normalize(path.absolute(packageRoot));
546 }
547
548 /// Given the user provided list of items to document, expand all directories
549 /// to document out into specific files and add any dependent packages for
550 /// documentation if desired.
551 static List<Uri> _findLibrariesToDocument(List<String> args,
552 bool includeDependentPackages) {
553 if (includeDependentPackages) {
554 args.addAll(_allDependentPackageDirs(args.first));
555 }
556
557 var libraries = new List<Uri>();
558 for (var arg in args) {
559 if (FileSystemEntity.typeSync(arg) == FileSystemEntityType.FILE) {
560 if (arg.endsWith('.dart')) {
561 var lib = new Uri.file(path.absolute(arg));
562 libraries.add(lib);
563 logger.info('Added to libraries: $lib');
564 }
565 } else {
566 libraries.addAll(_findFilesToDocumentInPackage(arg));
567 }
568 }
569 return libraries;
570 }
571
572 /// Given a package name, explore the directory and pull out all top level
573 /// library files in the "lib" directory to document.
574 static List<Uri> _findFilesToDocumentInPackage(String packageName) {
575 var libraries = [];
576 // To avoid anaylzing package files twice, only files with paths not
577 // containing '/packages' will be added. The only exception is if the file
578 // to analyze already has a '/package' in its path.
579 var files = listDir(packageName, recursive: true, listDir: _packageDirList)
580 .where((f) => f.endsWith('.dart')
581 && (!f.contains('${path.separator}packages')
582 || packageName.contains('${path.separator}packages'))).toList();
583
584 files.forEach((String lib) {
585 // Only include libraries at the top level of "lib"
586 if (path.basename(path.dirname(lib)) == 'lib') {
587 // Only add the file if it does not contain 'part of'
588 // TODO(janicejl): Remove when Issue(12406) is resolved.
589 var contents = new File(lib).readAsStringSync();
590 if (!(contents.contains(new RegExp('\npart of ')) ||
591 contents.startsWith(new RegExp('part of ')))) {
592 libraries.add(new Uri.file(path.normalize(path.absolute(lib))));
593 logger.info('Added to libraries: $lib');
594 }
595 }
596 });
597 return libraries;
598 }
599
600 /// If [dir] contains both a `lib` directory and a `pubspec.yaml` file treat
601 /// it like a package and only return the `lib` dir.
602 ///
603 /// This ensures that packages don't have non-`lib` content documented.
604 static List<FileSystemEntity> _packageDirList(Directory dir) {
605 var entities = dir.listSync();
606
607 var pubspec = entities
608 .firstWhere((e) => e is File &&
609 path.basename(e.path) == 'pubspec.yaml', orElse: () => null);
610
611 var libDir = entities
612 .firstWhere((e) => e is Directory &&
613 path.basename(e.path) == 'lib', orElse: () => null);
614
615 if (pubspec != null && libDir != null) {
616 return [libDir];
617 } else {
618 return entities;
619 }
620 }
621
622 /// All of the directories for our dependent packages
623 /// If this is not a package, return an empty list.
624 static List<String> _allDependentPackageDirs(String packageDirectory) {
625 var packageName = Library.packageNameFor(packageDirectory);
626 if (packageName == '') return [];
627 var dependentsJson = Process.runSync(_pubScript, ['list-package-dirs'],
628 workingDirectory: packageDirectory, runInShell: true);
629 if (dependentsJson.exitCode != 0) {
630 print(dependentsJson.stderr);
631 }
632 var dependents = JSON.decode(dependentsJson.stdout)['packages'];
633 return dependents.values.toList();
634 }
635
636 /// For all the libraries, return a list of the libraries that are part of
637 /// the SDK.
638 static List<Uri> _listSdk() {
639 var sdk = new List<Uri>();
640 LIBRARIES.forEach((String name, LibraryInfo info) {
641 if (info.documented) {
642 sdk.add(Uri.parse('dart:$name'));
643 logger.info('Add to SDK: ${sdk.last}');
644 }
645 });
646 return sdk;
647 }
648
649 /// Return true if this item and all of its owners are all visible.
650 static bool _isFullChainVisible(Indexable item) {
651 return _includePrivate || (!item.isPrivate && (item.owner != null ?
652 _isFullChainVisible(item.owner) : true));
653 }
654
655 /// Currently left public for testing purposes. :-/
656 static void generateLibrary(dart2js_mirrors.Dart2JsLibraryMirror library) {
657 var result = new Library(library);
658 result._updateLibraryPackage(library);
659 logger.fine('Generated library for ${result.name}');
660 }
661 }
662
663 /// Convenience methods wrapped up in a class to pull down the docgen viewer for
664 /// a viewable website, and start up a server for viewing.
665 class _Viewer {
666 static String _dartdocViewerString = path.join(Directory.current.path,
667 'dartdoc-viewer');
668 static Directory _dartdocViewerDir = new Directory(_dartdocViewerString);
669 static Directory _topLevelTempDir;
670 static Directory _webDocsDir;
671 static bool movedViewerCode = false;
672
673 static String _viewerCodePath;
674
675 /*
676 * dartdoc-viewer currently has the web app code under a 'client' directory
677 *
678 * This is confusing for folks that want to clone and modify the code.
679 * It also includes a number of python files and other content related to
680 * app engine hosting that are not needed.
681 *
682 * This logic exists to support the current model and a (future) updated
683 * dartdoc-viewer repo where the 'client' content exists at the root of the
684 * project and the other content is removed.
685 */
686 static String get viewerCodePath {
687 if(_viewerCodePath == null) {
688 var pubspecFileName = 'pubspec.yaml';
689
690 var thePath = _dartdocViewerDir.path;
691
692 if(!FileSystemEntity.isFileSync(path.join(thePath, pubspecFileName))) {
693 thePath = path.join(thePath, 'client');
694 if (!FileSystemEntity.isFileSync(path.join(thePath, pubspecFileName))) {
695 throw new StateError('Could not find a pubspec file');
696 }
697 }
698
699 _viewerCodePath = thePath;
700 }
701 return _viewerCodePath;
702 }
703
704 /// If our dartdoc-viewer code is already checked out, move it to a temporary
705 /// directory outside of the package directory, so we don't try to process it
706 /// for documentation.
707 static void ensureMovedViewerCode() {
708 // TODO(efortuna): This will need to be modified to run on anyone's package
709 // outside of the checkout!
710 if (_dartdocViewerDir.existsSync()) {
711 _topLevelTempDir = new Directory(
712 _Generator._rootDirectory).createTempSync();
713 _dartdocViewerDir.renameSync(_topLevelTempDir.path);
714 }
715 }
716
717 /// Move the dartdoc-viewer code back into place for "webpage deployment."
718 static void addBackViewerCode() {
719 if (movedViewerCode) _dartdocViewerDir.renameSync(_dartdocViewerString);
720 }
721
722 /// Serve up our generated documentation for viewing in a browser.
723 static void _clone() {
724 // If the viewer code is already there, then don't clone again.
725 if (_dartdocViewerDir.existsSync()) {
726 _moveDirectoryAndServe();
727 }
728 else {
729 var processResult = Process.runSync('git', ['clone', '-b', 'master',
730 'https://github.com/dart-lang/dartdoc-viewer.git'],
731 runInShell: true);
732
733 if (processResult.exitCode == 0) {
734 /// Move the generated json/yaml docs directory to the dartdoc-viewer
735 /// directory, to run as a webpage.
736 var processResult = Process.runSync(_Generator._pubScript,
737 ['upgrade'], runInShell: true,
738 workingDirectory: viewerCodePath);
739 print('process output: ${processResult.stdout}');
740 print('process stderr: ${processResult.stderr}');
741
742 var dir = new Directory(_Generator._outputDirectory == null? 'docs' :
743 _Generator._outputDirectory);
744 _webDocsDir = new Directory(path.join(viewerCodePath, 'web', 'docs'));
745 if (dir.existsSync()) {
746 // Move the docs folder to dartdoc-viewer/client/web/docs
747 dir.renameSync(_webDocsDir.path);
748 }
749 } else {
750 print('Error cloning git repository:');
751 print('process output: ${processResult.stdout}');
752 print('process stderr: ${processResult.stderr}');
753 }
754 }
755 }
756
757 /// Move the generated json/yaml docs directory to the dartdoc-viewer
758 /// directory, to run as a webpage.
759 static void _moveDirectoryAndServe() {
760 var processResult = Process.runSync(_Generator._pubScript, ['upgrade'],
761 runInShell: true, workingDirectory: path.join(_dartdocViewerDir.path,
762 'client'));
763 print('process output: ${processResult.stdout}');
764 print('process stderr: ${processResult.stderr}');
765
766 var dir = new Directory(_Generator._outputDirectory == null? 'docs' :
767 _Generator._outputDirectory);
768 var webDocsDir = new Directory(path.join(_dartdocViewerDir.path, 'client',
769 'web', 'docs'));
770 if (dir.existsSync()) {
771 // Move the docs folder to dartdoc-viewer/client/web/docs
772 dir.renameSync(webDocsDir.path);
773 }
774
775 if (webDocsDir.existsSync()) {
776 // Compile the code to JavaScript so we can run on any browser.
777 print('Compile app to JavaScript for viewing.');
778 var processResult = Process.runSync(_Generator._dartBinary,
779 ['deploy.dart'], workingDirectory : path.join(_dartdocViewerDir.path,
780 'client'), runInShell: true);
781 print('process output: ${processResult.stdout}');
782 print('process stderr: ${processResult.stderr}');
783 _runServer();
784 }
785 }
786
787 static void _compile() {
788 if (_webDocsDir.existsSync()) {
789 // Compile the code to JavaScript so we can run on any browser.
790 print('Compile app to JavaScript for viewing.');
791 var processResult = Process.runSync(_Generator._dartBinary,
792 ['deploy.dart'], workingDirectory: viewerCodePath, runInShell: true);
793 print('process output: ${processResult.stdout}');
794 print('process stderr: ${processResult.stderr}');
795 var outputDir = path.join(viewerCodePath, 'out', 'web');
796 print('Docs are available at $outputDir');
797 }
798 }
799
800 /// A simple HTTP server. Implemented here because this is part of the SDK,
801 /// so it shouldn't have any external dependencies.
802 static void _runServer() {
803 // Launch a server to serve out of the directory dartdoc-viewer/client/web.
804 HttpServer.bind(InternetAddress.ANY_IP_V6, 8080).then((HttpServer httpServer ) {
805 print('Server launched. Navigate your browser to: '
806 'http://localhost:${httpServer.port}');
807 httpServer.listen((HttpRequest request) {
808 var response = request.response;
809 var basePath = path.join(viewerCodePath, 'out', 'web');
810 var requestPath = path.join(basePath, request.uri.path.substring(1));
811 bool found = true;
812 var file = new File(requestPath);
813 if (file.existsSync()) {
814 // Set the correct header type.
815 if (requestPath.endsWith('.html')) {
816 response.headers.set('Content-Type', 'text/html');
817 } else if (requestPath.endsWith('.js')) {
818 response.headers.set('Content-Type', 'application/javascript');
819 } else if (requestPath.endsWith('.dart')) {
820 response.headers.set('Content-Type', 'application/dart');
821 } else if (requestPath.endsWith('.css')) {
822 response.headers.set('Content-Type', 'text/css');
823 }
824 } else {
825 if (requestPath == basePath) {
826 response.headers.set('Content-Type', 'text/html');
827 file = new File(path.join(basePath, 'index.html'));
828 } else {
829 print('Path not found: $requestPath');
830 found = false;
831 response.statusCode = HttpStatus.NOT_FOUND;
832 response.close();
833 }
834 }
835
836 if (found) {
837 // Serve up file contents.
838 file.openRead().pipe(response).catchError((e) {
839 print('HttpServer: error while closing the response stream $e');
840 });
841 }
842 },
843 onError: (e) {
844 print('HttpServer: an error occured $e');
845 });
846 });
847 }
848 }
849
850 /// An item that is categorized in our mirrorToDocgen map, as a distinct,
851 /// searchable element.
852 ///
853 /// These are items that refer to concrete entities (a Class, for example,
854 /// but not a Type, which is a "pointer" to a class) that we wish to be
855 /// globally resolvable. This includes things such as class methods and
856 /// variables, but parameters for methods are not "Indexable" as we do not want
857 /// the user to be able to search for a method based on its parameter names!
858 /// The set of indexable items also includes Typedefs, since the user can refer
859 /// to them as concrete entities in a particular scope.
860 abstract class Indexable extends MirrorBased {
861 /// The dart:core library, which contains all types that are always available
862 /// without import.
863 static Library _coreLibrary;
864
865 /// Set of libraries declared in the SDK, so libraries that can be accessed
866 /// when running dart by default.
867 static Iterable<LibraryMirror> _sdkLibraries;
868
869 Library get _owningLibrary => owner._owningLibrary;
870
871 String get qualifiedName => fileName;
872 final DeclarationMirror mirror;
873 final bool isPrivate;
874 /// The comment text pre-resolution. We keep this around because inherited
875 /// methods need to resolve links differently from the superclass.
876 String _unresolvedComment = '';
877
878 /// Index of all the dart2js mirrors examined to corresponding MirrorBased
879 /// docgen objects.
880 ///
881 /// Used for lookup because of the dart2js mirrors exports
882 /// issue. The second level map is indexed by owner docName for faster lookup.
883 /// Why two levels of lookup? Speed, man. Speed.
884 static Map<String, Map<String, Set<Indexable>>> _mirrorToDocgen =
885 new Map<String, Map<String, Set<Indexable>>>();
886
887 Indexable(DeclarationMirror mirror)
888 : this.mirror = mirror,
889 this.isPrivate = isHidden(mirror) {
890
891 var map = _mirrorToDocgen[dart2js_util.qualifiedNameOf(this.mirror)];
892 if (map == null) map = new Map<String, Set<Indexable>>();
893
894 var set = map[owner.docName];
895 if (set == null) set = new Set<Indexable>();
896 set.add(this);
897 map[owner.docName] = set;
898 _mirrorToDocgen[dart2js_util.qualifiedNameOf(this.mirror)] = map;
899 }
900
901 static _initializeTopLevelLibraries(MirrorSystem mirrorSystem) {
902 _sdkLibraries = mirrorSystem.libraries.values.where(
903 (each) => each.uri.scheme == 'dart');
904 _coreLibrary = new Library(_sdkLibraries.singleWhere((lib) =>
905 lib.uri.toString().startsWith('dart:core')));
906 }
907
908 /// Returns this object's qualified name, but following the conventions
909 /// we're using in Dartdoc, which is that library names with dots in them
910 /// have them replaced with hyphens.
911 String get docName;
912
913 /// Converts all [foo] references in comments to <a>libraryName.foo</a>.
914 markdown.Node fixReference(String name) {
915 // Attempt the look up the whole name up in the scope.
916 String elementName = findElementInScope(name);
917 if (elementName != null) {
918 return new markdown.Element.text('a', elementName);
919 }
920 return _fixComplexReference(name);
921 }
922
923 /// Look for the specified name starting with the current member, and
924 /// progressively working outward to the current library scope.
925 String findElementInScope(String name) =>
926 _findElementInScope(name, packagePrefix);
927
928 /// The reference to this element based on where it is printed as a
929 /// documentation file and also the unique URL to refer to this item.
930 ///
931 /// The qualified name (for URL purposes) and the file name are the same,
932 /// of the form packageName/ClassName or packageName/ClassName.methodName.
933 /// This defines both the URL and the directory structure.
934 String get fileName => packagePrefix + ownerPrefix + name;
935
936 /// The full docName of the owner element, appended with a '.' for this
937 /// object's name to be appended.
938 String get ownerPrefix => owner.docName != '' ? owner.docName + '.' : '';
939
940 /// The prefix String to refer to the package that this item is in, for URLs
941 /// and comment resolution.
942 ///
943 /// The prefix can be prepended to a qualified name to get a fully unique
944 /// name among all packages.
945 String get packagePrefix => '';
946
947 /// Documentation comment with converted markdown and all links resolved.
948 String _comment;
949
950 /// Accessor to documentation comment with markdown converted to html and all
951 /// links resolved.
952 String get comment {
953 if (_comment != null) return _comment;
954
955 _comment = _commentToHtml();
956 if (_comment.isEmpty) {
957 _comment = _mdnComment();
958 }
959 return _comment;
960 }
961
962 set comment(x) => _comment = x;
963
964 /// The simple name to refer to this item.
965 String get name => dart2js_util.nameOf(mirror);
966
967 /// Accessor to the parent item that owns this item.
968 ///
969 /// "Owning" is defined as the object one scope-level above which this item
970 /// is defined. Ex: The owner for a top level class, would be its enclosing
971 /// library. The owner of a local variable in a method would be the enclosing
972 /// method.
973 Indexable get owner => new DummyMirror(mirror.owner);
974
975 /// Generates MDN comments from database.json.
976 String _mdnComment();
977
978 /// The type of this member to be used in index.txt.
979 String get typeName => '';
980
981 /// Creates a [Map] with this [Indexable]'s name and a preview comment.
982 Map get previewMap {
983 var finalMap = { 'name' : name, 'qualifiedName' : qualifiedName };
984 var preview = _preview;
985 if(preview != null) finalMap['preview'] = preview;
986 return finalMap;
987 }
988
989 String get _preview {
990 if (comment != '') {
991 var index = comment.indexOf('</p>');
992 return index > 0 ?
993 '${comment.substring(0, index)}</p>' :
994 '<p><i>Comment preview not available</i></p>';
995 }
996 return null;
997 }
998
999 /// Accessor to obtain the raw comment text for a given item, _without_ any
1000 /// of the links resolved.
1001 String get _commentText {
1002 String commentText;
1003 mirror.metadata.forEach((metadata) {
1004 if (metadata is CommentInstanceMirror) {
1005 CommentInstanceMirror comment = metadata;
1006 if (comment.isDocComment) {
1007 if (commentText == null) {
1008 commentText = comment.trimmedText;
1009 } else {
1010 commentText = '$commentText\n${comment.trimmedText}';
1011 }
1012 }
1013 }
1014 });
1015 return commentText;
1016 }
1017
1018 /// Returns any documentation comments associated with a mirror with
1019 /// simple markdown converted to html.
1020 ///
1021 /// By default we resolve any comment references within our own scope.
1022 /// However, if a method is inherited, we want the inherited comments, but
1023 /// links to the subclasses's version of the methods.
1024 String _commentToHtml([Indexable resolvingScope]) {
1025 if (resolvingScope == null) resolvingScope = this;
1026 var commentText = _commentText;
1027 _unresolvedComment = commentText;
1028
1029 var linkResolver = (name) => resolvingScope.fixReference(name);
1030 commentText = commentText == null ? '' :
1031 markdown.markdownToHtml(commentText.trim(), linkResolver: linkResolver,
1032 inlineSyntaxes: _MARKDOWN_SYNTAXES);
1033 return commentText;
1034 }
1035
1036 /// Returns a map of [Variable] objects constructed from [mirrorMap].
1037 /// The optional parameter [containingLibrary] is contains data for variables
1038 /// defined at the top level of a library (potentially for exporting
1039 /// purposes).
1040 Map<String, Variable> _createVariables(Iterable<VariableMirror> mirrors,
1041 Indexable owner) {
1042 var data = {};
1043 // TODO(janicejl): When map to map feature is created, replace the below
1044 // with a filter. Issue(#9590).
1045 mirrors.forEach((VariableMirror mirror) {
1046 if (_Generator._includePrivate || !isHidden(mirror)) {
1047 var mirrorName = dart2js_util.nameOf(mirror);
1048 data[mirrorName] = new Variable(mirrorName, mirror, owner);
1049 }
1050 });
1051 return data;
1052 }
1053
1054 /// Returns a map of [Method] objects constructed from [mirrorMap].
1055 /// The optional parameter [containingLibrary] is contains data for variables
1056 /// defined at the top level of a library (potentially for exporting
1057 /// purposes).
1058 Map<String, Method> _createMethods(Iterable<MethodMirror> mirrors,
1059 Indexable owner) {
1060 var group = new Map<String, Method>();
1061 mirrors.forEach((MethodMirror mirror) {
1062 if (_Generator._includePrivate || !mirror.isPrivate) {
1063 group[dart2js_util.nameOf(mirror)] = new Method(mirror, owner);
1064 }
1065 });
1066 return group;
1067 }
1068
1069 /// Returns a map of [Parameter] objects constructed from [mirrorList].
1070 Map<String, Parameter> _createParameters(List<ParameterMirror> mirrorList,
1071 Indexable owner) {
1072 var data = {};
1073 mirrorList.forEach((ParameterMirror mirror) {
1074 data[dart2js_util.nameOf(mirror)] =
1075 new Parameter(mirror, owner._owningLibrary);
1076 });
1077 return data;
1078 }
1079
1080 /// Returns a map of [Generic] objects constructed from the class mirror.
1081 Map<String, Generic> _createGenerics(TypeMirror mirror) {
1082 return new Map.fromIterable(mirror.typeVariables,
1083 key: (e) => dart2js_util.nameOf(e),
1084 value: (e) => new Generic(e));
1085 }
1086
1087 /// Return an informative [Object.toString] for debugging.
1088 String toString() => "${super.toString()}(${name.toString()})";
1089
1090 /// Return a map representation of this type.
1091 Map toMap();
1092
1093
1094
1095 ////// Top level resolution functions
1096 /// Converts all [foo] references in comments to <a>libraryName.foo</a>.
1097 static markdown.Node globalFixReference(String name) {
1098 // Attempt the look up the whole name up in the scope.
1099 String elementName = _findElementInScope(name, '');
1100 if (elementName != null) {
1101 return new markdown.Element.text('a', elementName);
1102 }
1103 return _fixComplexReference(name);
1104 }
1105
1106 /// This is a more complex reference. Try to break up if its of the form A<B>
1107 /// where A is an alphanumeric string and B is an A, a list of B ("B, B, B"),
1108 /// or of the form A<B>. Note: unlike other the other markdown-style links,
1109 /// all text inside the square brackets is treated as part of the link (aka
1110 /// the * is interpreted literally as a *, not as a indicator for bold <em>.
1111 ///
1112 /// Example: [foo&lt;_bar_>] will produce
1113 /// <a>resolvedFoo</a>&lt;<a>resolved_bar_</a>> rather than an italicized
1114 /// version of resolvedBar.
1115 static markdown.Node _fixComplexReference(String name) {
1116 // Parse into multiple elements we can try to resolve.
1117 var tokens = tokenizeComplexReference(name);
1118
1119 // Produce an html representation of our elements. Group unresolved and
1120 // plain text are grouped into "link" elements so they display as code.
1121 final textElements = [' ', ',', '>', LESS_THAN];
1122 var accumulatedHtml = '';
1123
1124 for (var token in tokens) {
1125 bool added = false;
1126 if (!textElements.contains(token)) {
1127 String elementName = _findElementInScope(token, '');
1128 if (elementName != null) {
1129 accumulatedHtml += markdown.renderToHtml([new markdown.Element.text(
1130 'a', elementName)]);
1131 added = true;
1132 }
1133 }
1134 if (!added) {
1135 accumulatedHtml += token;
1136 }
1137 }
1138 return new markdown.Text(accumulatedHtml);
1139 }
1140
1141 static String _findElementInScope(String name, String packagePrefix) {
1142 var lookupFunc = determineLookupFunc(name);
1143 // Look in the dart core library scope.
1144 var coreScope = _coreLibrary == null? null :
1145 lookupFunc(_coreLibrary.mirror, name);
1146 if (coreScope != null) return packagePrefix + _coreLibrary.docName;
1147
1148 // If it's a reference that starts with a another library name, then it
1149 // looks for a match of that library name in the other sdk libraries.
1150 if(name.contains('.')) {
1151 var index = name.indexOf('.');
1152 var libraryName = name.substring(0, index);
1153 var remainingName = name.substring(index + 1);
1154 foundLibraryName(library) => library.uri.pathSegments[0] == libraryName;
1155
1156 if (_sdkLibraries.any(foundLibraryName)) {
1157 var library = _sdkLibraries.singleWhere(foundLibraryName);
1158 // Look to see if it's a fully qualified library name.
1159 var scope = determineLookupFunc(remainingName)(library, remainingName);
1160 if (scope != null) {
1161 var result = getDocgenObject(scope);
1162 if (result is DummyMirror) {
1163 return packagePrefix + result.docName;
1164 } else {
1165 return result.packagePrefix + result.docName;
1166 }
1167 }
1168 }
1169 }
1170 return null;
1171 }
1172
1173 /// Expand the method map [mapToExpand] into a more detailed map that
1174 /// separates out setters, getters, constructors, operators, and methods.
1175 Map _expandMethodMap(Map<String, Method> mapToExpand) => {
1176 'setters': recurseMap(filterMap(mapToExpand,
1177 (key, val) => val.mirror.isSetter)),
1178 'getters': recurseMap(filterMap(mapToExpand,
1179 (key, val) => val.mirror.isGetter)),
1180 'constructors': recurseMap(filterMap(mapToExpand,
1181 (key, val) => val.mirror.isConstructor)),
1182 'operators': recurseMap(filterMap(mapToExpand,
1183 (key, val) => val.mirror.isOperator)),
1184 'methods': recurseMap(filterMap(mapToExpand,
1185 (key, val) => val.mirror.isRegularMethod && !val.mirror.isOperator))
1186 };
1187
1188 /// Accessor to determine if this item and all of its owners are visible.
1189 bool get _isVisible => _Generator._isFullChainVisible(this);
1190
1191 /// Given a Dart2jsMirror, find the corresponding Docgen [MirrorBased] object.
1192 ///
1193 /// We have this global lookup function to avoid re-implementing looking up
1194 /// the scoping rules for comment resolution here (it is currently done in
1195 /// mirrors). If no corresponding MirrorBased object is found, we return a
1196 /// [DummyMirror] that simply returns the original mirror's qualifiedName
1197 /// while behaving like a MirrorBased object.
1198 static Indexable getDocgenObject(DeclarationMirror mirror,
1199 [Indexable owner]) {
1200 Map<String, Set<Indexable>> docgenObj =
1201 _mirrorToDocgen[dart2js_util.qualifiedNameOf(mirror)];
1202 if (docgenObj == null) {
1203 return new DummyMirror(mirror, owner);
1204 }
1205
1206 var setToExamine = new Set();
1207 if (owner != null) {
1208 var firstSet = docgenObj[owner.docName];
1209 if (firstSet != null) setToExamine.addAll(firstSet);
1210 if (_coreLibrary != null &&
1211 docgenObj[_coreLibrary.docName] != null) {
1212 setToExamine.addAll(docgenObj[_coreLibrary.docName]);
1213 }
1214 } else {
1215 for (var value in docgenObj.values) {
1216 setToExamine.addAll(value);
1217 }
1218 }
1219
1220 Set<Indexable> results = new Set<Indexable>();
1221 for(Indexable indexable in setToExamine) {
1222 if (indexable.mirror.qualifiedName == mirror.qualifiedName &&
1223 indexable._isValidMirror(mirror)) {
1224 results.add(indexable);
1225 }
1226 }
1227
1228 if (results.length > 0) {
1229 // This might occur if we didn't specify an "owner."
1230 return results.first;
1231 }
1232 return new DummyMirror(mirror, owner);
1233 }
1234
1235 /// Returns true if [mirror] is the correct type of mirror that this Docgen
1236 /// object wraps. (Workaround for the fact that Types are not first class.)
1237 bool _isValidMirror(DeclarationMirror mirror);
1238 }
1239
1240 /// A class containing contents of a Dart library.
1241 class Library extends Indexable {
1242 final Map<String, Class> classes = {};
1243 final Map<String, Typedef> typedefs = {};
1244 final Map<String, Class> errors = {};
1245
1246 /// Top-level variables in the library.
1247 Map<String, Variable> variables;
1248
1249 /// Top-level functions in the library.
1250 Map<String, Method> functions;
1251
1252 String packageName = '';
1253 bool _hasBeenCheckedForPackage = false;
1254 String packageIntro;
1255
1256 Library get _owningLibrary => this;
1257
1258 /// Returns the [Library] for the given [mirror] if it has already been
1259 /// created, else creates it.
1260 factory Library(LibraryMirror mirror) {
1261 var library = Indexable.getDocgenObject(mirror);
1262 if (library is DummyMirror) {
1263 library = new Library._(mirror);
1264 }
1265 return library;
1266 }
1267
1268 Library._(LibraryMirror libraryMirror) : super(libraryMirror) {
1269 var exported = _calcExportedItems(libraryMirror);
1270 var exportedClasses = _addAll(exported['classes'],
1271 dart2js_util.typesOf(libraryMirror.declarations));
1272 _updateLibraryPackage(mirror);
1273 exportedClasses.forEach((String mirrorName, TypeMirror mirror) {
1274 if (mirror is TypedefMirror) {
1275 // This is actually a Dart2jsTypedefMirror, and it does define value,
1276 // but we don't have visibility to that type.
1277 if (_Generator._includePrivate || !mirror.isPrivate) {
1278 typedefs[dart2js_util.nameOf(mirror)] = new Typedef(mirror, this);
1279 }
1280 } else if (mirror is ClassMirror) {
1281 var clazz = new Class(mirror, this);
1282
1283 if (clazz.isError()) {
1284 errors[dart2js_util.nameOf(mirror)] = clazz;
1285 } else {
1286 classes[dart2js_util.nameOf(mirror)] = clazz;
1287 }
1288 } else {
1289 throw new ArgumentError(
1290 '${dart2js_util.nameOf(mirror)} - no class type match. ');
1291 }
1292 });
1293 this.functions = _createMethods(_addAll(exported['methods'],
1294 libraryMirror.declarations.values.where(
1295 (mirror) => mirror is MethodMirror)).values, this);
1296 this.variables = _createVariables(_addAll(exported['variables'],
1297 dart2js_util.variablesOf(libraryMirror.declarations)).values, this);
1298 }
1299
1300 /// Look for the specified name starting with the current member, and
1301 /// progressively working outward to the current library scope.
1302 String findElementInScope(String name) {
1303 var lookupFunc = determineLookupFunc(name);
1304 var libraryScope = lookupFunc(mirror, name);
1305 if (libraryScope != null) {
1306 var result = Indexable.getDocgenObject(libraryScope, this);
1307 if (result is DummyMirror) return packagePrefix + result.docName;
1308 return result.packagePrefix + result.docName;
1309 }
1310 return super.findElementInScope(name);
1311 }
1312
1313 String _mdnComment() => '';
1314
1315 /// Helper that maps [mirrors] to their simple name in map.
1316 static Map _addAll(Map map, Iterable<DeclarationMirror> mirrors) {
1317 for (var mirror in mirrors) {
1318 map[dart2js_util.nameOf(mirror)] = mirror;
1319 }
1320 return map;
1321 }
1322
1323 /// For a library's [mirror], determine the name of the package (if any) we
1324 /// believe it came from (because of its file URI).
1325 ///
1326 /// If no package could be determined, we return an empty string.
1327 void _updateLibraryPackage(LibraryMirror mirror) {
1328 if (mirror == null) return;
1329 if (_hasBeenCheckedForPackage) return;
1330 _hasBeenCheckedForPackage = true;
1331 if (mirror.uri.scheme != 'file') return;
1332 packageName = _packageName(mirror);
1333 // Associate the package readme with all the libraries. This is a bit
1334 // wasteful, but easier than trying to figure out which partial match
1335 // is best.
1336 packageIntro = _packageIntro(_getPackageDirectory(mirror));
1337 }
1338
1339 String _packageIntro(packageDir) {
1340 if (packageDir == null) return null;
1341 var dir = new Directory(packageDir);
1342 var files = dir.listSync();
1343 var readmes = files.where((FileSystemEntity each) => (each is File &&
1344 each.path.substring(packageDir.length + 1, each.path.length)
1345 .startsWith('README'))).toList();
1346 if (readmes.isEmpty) return '';
1347 // If there are multiples, pick the shortest name.
1348 readmes.sort((a, b) => a.path.length.compareTo(b.path.length));
1349 var readme = readmes.first;
1350 var linkResolver = (name) => Indexable.globalFixReference(name);
1351 var contents = markdown.markdownToHtml(readme
1352 .readAsStringSync(), linkResolver: linkResolver,
1353 inlineSyntaxes: _MARKDOWN_SYNTAXES);
1354 return contents;
1355 }
1356
1357 /// Given a LibraryMirror that is a library, return the name of the directory
1358 /// holding the package information for that library. If the library is not
1359 /// part of a package, return null.
1360 static String _getPackageDirectory(LibraryMirror mirror) {
1361 var file = mirror.uri.toFilePath();
1362 // Any file that's in a package will be in a directory of the form
1363 // packagename/lib/.../filename.dart, so we know that a possible
1364 // package directory is at least in the directory above the one containing
1365 // [file]
1366 var directoryAbove = path.dirname(path.dirname(file));
1367 var possiblePackage = _packageDirectoryFor(directoryAbove);
1368 // We only want components that are somewhere underneath the lib directory.
1369 var subPath = path.relative(file, from: possiblePackage);
1370 var subPathComponents = path.split(subPath);
1371 if (subPathComponents.isNotEmpty && subPathComponents.first == 'lib') {
1372 return possiblePackage;
1373 } else {
1374 return null;
1375 }
1376 }
1377
1378 /// Read a pubspec and return the library name given a [LibraryMirror].
1379 static String _packageName(LibraryMirror mirror) {
1380 if (mirror.uri.scheme != 'file') return '';
1381 var rootdir = _getPackageDirectory(mirror);
1382 if (rootdir == null) return '';
1383 return packageNameFor(rootdir);
1384 }
1385
1386 /// Recursively walk up from directory name looking for a pubspec. Return
1387 /// the directory that contains it, or null if none is found.
1388 static String _packageDirectoryFor(String directoryName) {
1389 var dir = directoryName;
1390 while (!_pubspecFor(dir).existsSync()) {
1391 var newDir = path.dirname(dir);
1392 if (newDir == dir) return null;
1393 dir = newDir;
1394 }
1395 return dir;
1396 }
1397
1398 static File _pubspecFor(String directoryName) =>
1399 new File(path.join(directoryName, 'pubspec.yaml'));
1400
1401 /// Read a pubspec and return the library name, given a directory
1402 static String packageNameFor(String directoryName) {
1403 var pubspecName = path.join(directoryName, 'pubspec.yaml');
1404 File pubspec = new File(pubspecName);
1405 if (!pubspec.existsSync()) return '';
1406 var contents = pubspec.readAsStringSync();
1407 var spec = loadYaml(contents);
1408 return spec["name"];
1409 }
1410
1411 String get packagePrefix => packageName == null || packageName.isEmpty ?
1412 '' : '$packageName/';
1413
1414 Map get previewMap {
1415 var basic = super.previewMap;
1416 basic['packageName'] = packageName;
1417 if (packageIntro != null) {
1418 basic['packageIntro'] = packageIntro;
1419 }
1420 return basic;
1421 }
1422
1423 String get name => docName;
1424
1425 String get docName {
1426 return dart2js_util.qualifiedNameOf(mirror).replaceAll('.','-');
1427 }
1428
1429 /// For the given library determine what items (if any) are exported.
1430 ///
1431 /// Returns a Map with three keys: "classes", "methods", and "variables" the
1432 /// values of which point to a map of exported name identifiers with values
1433 /// corresponding to the actual DeclarationMirror.
1434 Map<String, Map<String, DeclarationMirror>> _calcExportedItems(
1435 LibrarySourceMirror library) {
1436 var exports = {};
1437 exports['classes'] = {};
1438 exports['methods'] = {};
1439 exports['variables'] = {};
1440
1441 // Determine the classes, variables and methods that are exported for a
1442 // specific dependency.
1443 void _populateExports(LibraryDependencyMirror export, bool showExport) {
1444 if (!showExport) {
1445 // Add all items, and then remove the hidden ones.
1446 // Ex: "export foo hide bar"
1447 _addAll(exports['classes'],
1448 dart2js_util.typesOf(export.targetLibrary.declarations));
1449 _addAll(exports['methods'],
1450 export.targetLibrary.declarations.values.where(
1451 (mirror) => mirror is MethodMirror));
1452 _addAll(exports['variables'],
1453 dart2js_util.variablesOf(export.targetLibrary.declarations));
1454 }
1455 for (CombinatorMirror combinator in export.combinators) {
1456 for (String identifier in combinator.identifiers) {
1457 DeclarationMirror declaration =
1458 export.targetLibrary.lookupInScope(identifier);
1459 if (declaration == null) {
1460 // Technically this should be a bug, but some of our packages
1461 // (such as the polymer package) are curently broken in this
1462 // way, so we just produce a warning.
1463 print('Warning identifier $identifier not found in library '
1464 '${dart2js_util.qualifiedNameOf(export.targetLibrary)}');
1465 } else {
1466 var subMap = exports['classes'];
1467 if (declaration is MethodMirror) {
1468 subMap = exports['methods'];
1469 } else if (declaration is VariableMirror) {
1470 subMap = exports['variables'];
1471 }
1472 if (showExport) {
1473 subMap[identifier] = declaration;
1474 } else {
1475 subMap.remove(identifier);
1476 }
1477 }
1478 }
1479 }
1480 }
1481
1482 Iterable<LibraryDependencyMirror> exportList =
1483 library.libraryDependencies.where((lib) => lib.isExport);
1484 for (LibraryDependencyMirror export in exportList) {
1485 // If there is a show in the export, add only the show items to the
1486 // library. Ex: "export foo show bar"
1487 // Otherwise, add all items, and then remove the hidden ones.
1488 // Ex: "export foo hide bar"
1489 _populateExports(export,
1490 export.combinators.any((combinator) => combinator.isShow));
1491 }
1492 return exports;
1493 }
1494
1495 /// Checks if the given name is a key for any of the Class Maps.
1496 bool containsKey(String name) =>
1497 classes.containsKey(name) || errors.containsKey(name);
1498
1499 /// Generates a map describing the [Library] object.
1500 Map toMap() => {
1501 'name': name,
1502 'qualifiedName': qualifiedName,
1503 'comment': comment,
1504 'variables': recurseMap(variables),
1505 'functions': _expandMethodMap(functions),
1506 'classes': {
1507 'class': classes.values.where((c) => c._isVisible)
1508 .map((e) => e.previewMap).toList(),
1509 'typedef': recurseMap(typedefs),
1510 'error': errors.values.where((e) => e._isVisible)
1511 .map((e) => e.previewMap).toList()
1512 },
1513 'packageName': packageName,
1514 'packageIntro' : packageIntro
1515 };
1516
1517 String get typeName => 'library';
1518
1519 bool _isValidMirror(DeclarationMirror mirror) => mirror is LibraryMirror;
1520 }
1521
1522 abstract class OwnedIndexable extends Indexable {
1523 /// The object one scope-level above which this item is defined.
1524 ///
1525 /// Ex: The owner for a top level class, would be its enclosing library.
1526 /// The owner of a local variable in a method would be the enclosing method.
1527 Indexable owner;
1528
1529 /// List of the meta annotations on this item.
1530 List<Annotation> annotations;
1531
1532 /// Returns this object's qualified name, but following the conventions
1533 /// we're using in Dartdoc, which is that library names with dots in them
1534 /// have them replaced with hyphens.
1535 String get docName => owner.docName + '.' + dart2js_util.nameOf(mirror);
1536
1537 OwnedIndexable(DeclarationMirror mirror, this.owner) : super(mirror);
1538
1539 /// Generates MDN comments from database.json.
1540 String _mdnComment() {
1541 var domAnnotation = this.annotations.firstWhere(
1542 (e) => e.mirror.qualifiedName == #metadata.DomName,
1543 orElse: () => null);
1544 if (domAnnotation == null) return '';
1545 var domName = domAnnotation.parameters.single;
1546
1547 return mdnComment(_Generator._rootDirectory, _Generator.logger, domName);
1548 }
1549
1550 String get packagePrefix => owner.packagePrefix;
1551 }
1552
1553 /// A class containing contents of a Dart class.
1554 class Class extends OwnedIndexable implements Comparable {
1555
1556 /// List of the names of interfaces that this class implements.
1557 List<Class> interfaces = [];
1558
1559 /// Names of classes that extends or implements this class.
1560 Set<Class> subclasses = new Set<Class>();
1561
1562 /// Top-level variables in the class.
1563 Map<String, Variable> variables;
1564
1565 /// Inherited variables in the class.
1566 Map<String, Variable> inheritedVariables;
1567
1568 /// Methods in the class.
1569 Map<String, Method> methods;
1570
1571 Map<String, Method> inheritedMethods;
1572
1573 /// Generic infomation about the class.
1574 Map<String, Generic> generics;
1575
1576 Class superclass;
1577 bool isAbstract;
1578
1579 /// Make sure that we don't check for inherited comments more than once.
1580 bool _commentsEnsured = false;
1581
1582 /// Returns the [Class] for the given [mirror] if it has already been created,
1583 /// else creates it.
1584 factory Class(ClassMirror mirror, Library owner) {
1585 var clazz = Indexable.getDocgenObject(mirror, owner);
1586 if (clazz is DummyMirror) {
1587 clazz = new Class._(mirror, owner);
1588 }
1589 return clazz;
1590 }
1591
1592 /// Called when we are constructing a superclass or interface class, but it
1593 /// is not known if it belongs to the same owner as the original class. In
1594 /// this case, we create an object whose owner is what the original mirror
1595 /// says it is.
1596 factory Class._possiblyDifferentOwner(ClassMirror mirror,
1597 Library originalOwner) {
1598 if (mirror.owner is LibraryMirror) {
1599 var realOwner = Indexable.getDocgenObject(mirror.owner);
1600 if (realOwner is Library) {
1601 return new Class(mirror, realOwner);
1602 } else {
1603 return new Class(mirror, originalOwner);
1604 }
1605 } else {
1606 return new Class(mirror, originalOwner);
1607 }
1608 }
1609
1610 Class._(ClassSourceMirror classMirror, Indexable owner) :
1611 super(classMirror, owner) {
1612 inheritedVariables = {};
1613
1614 // The reason we do this madness is the superclass and interface owners may
1615 // not be this class's owner!! Example: BaseClient in http pkg.
1616 var superinterfaces = classMirror.superinterfaces.map(
1617 (interface) => new Class._possiblyDifferentOwner(interface, owner));
1618 this.superclass = classMirror.superclass == null? null :
1619 new Class._possiblyDifferentOwner(classMirror.superclass, owner);
1620
1621 interfaces = superinterfaces.toList();
1622 variables = _createVariables(
1623 dart2js_util.variablesOf(classMirror.declarations), this);
1624 methods = _createMethods(classMirror.declarations.values.where(
1625 (mirror) => mirror is MethodMirror), this);
1626 annotations = _createAnnotations(classMirror, owner._owningLibrary);
1627 generics = _createGenerics(classMirror);
1628 isAbstract = classMirror.isAbstract;
1629 inheritedMethods = new Map<String, Method>();
1630
1631 // Tell superclass that you are a subclass, unless you are not
1632 // visible or an intermediary mixin class.
1633 if (!classMirror.isNameSynthetic && _isVisible && superclass != null) {
1634 superclass.addSubclass(this);
1635 }
1636
1637 if (this.superclass != null) addInherited(superclass);
1638 interfaces.forEach((interface) => addInherited(interface));
1639 }
1640
1641 String _lookupInClassAndSuperclasses(String name) {
1642 var lookupFunc = determineLookupFunc(name);
1643 var classScope = this;
1644 while (classScope != null) {
1645 var classFunc = lookupFunc(classScope.mirror, name);
1646 if (classFunc != null) {
1647 return packagePrefix + Indexable.getDocgenObject(classFunc, owner).docNa me;
1648 }
1649 classScope = classScope.superclass;
1650 }
1651 return null;
1652 }
1653
1654 /// Look for the specified name starting with the current member, and
1655 /// progressively working outward to the current library scope.
1656 String findElementInScope(String name) {
1657 var lookupFunc = determineLookupFunc(name);
1658 var result = _lookupInClassAndSuperclasses(name);
1659 if (result != null) {
1660 return result;
1661 }
1662 result = owner.findElementInScope(name);
1663 return result == null ? super.findElementInScope(name) : result;
1664 }
1665
1666 String get typeName => 'class';
1667
1668 /// Add all inherited variables and methods from the provided superclass.
1669 /// If [_includePrivate] is true, it also adds the variables and methods from
1670 /// the superclass.
1671 void addInherited(Class superclass) {
1672 inheritedVariables.addAll(superclass.inheritedVariables);
1673 inheritedVariables.addAll(_allButStatics(superclass.variables));
1674 addInheritedMethod(superclass, this);
1675 }
1676
1677 /** [newParent] refers to the actual class is currently using these methods.
1678 * which may be different because with the mirror system, we only point to the
1679 * original canonical superclasse's method.
1680 */
1681 void addInheritedMethod(Class parent, Class newParent) {
1682 parent.inheritedMethods.forEach((name, method) {
1683 if(!method.mirror.isConstructor){
1684 inheritedMethods[name] = new Method(method.mirror, newParent, method);
1685 }}
1686 );
1687 _allButStatics(parent.methods).forEach((name, method) {
1688 if (!method.mirror.isConstructor) {
1689 inheritedMethods[name] = new Method(method.mirror, newParent, method);
1690 }}
1691 );
1692 }
1693
1694 /// Remove statics from the map of inherited items before adding them.
1695 Map _allButStatics(Map items) {
1696 var result = {};
1697 items.forEach((name, item) {
1698 if (!item.isStatic) {
1699 result[name] = item;
1700 }
1701 });
1702 return result;
1703 }
1704
1705 /// Add the subclass to the class.
1706 ///
1707 /// If [this] is private (or an intermediary mixin class), it will add the
1708 /// subclass to the list of subclasses in the superclasses.
1709 void addSubclass(Class subclass) {
1710 if (docName == 'dart-core.Object') return;
1711
1712 if (!_Generator._includePrivate && isPrivate || mirror.isNameSynthetic) {
1713 if (superclass != null) superclass.addSubclass(subclass);
1714 interfaces.forEach((interface) {
1715 interface.addSubclass(subclass);
1716 });
1717 } else {
1718 subclasses.add(subclass);
1719 }
1720 }
1721
1722 /// Check if this [Class] is an error or exception.
1723 bool isError() {
1724 if (qualifiedName == 'dart-core.Error' ||
1725 qualifiedName == 'dart-core.Exception')
1726 return true;
1727 for (var interface in interfaces) {
1728 if (interface.isError()) return true;
1729 }
1730 if (superclass == null) return false;
1731 return superclass.isError();
1732 }
1733
1734 /// Makes sure that all methods with inherited equivalents have comments.
1735 void ensureComments() {
1736 if (_commentsEnsured) return;
1737 _commentsEnsured = true;
1738 if (superclass != null) superclass.ensureComments();
1739 inheritedMethods.forEach((qualifiedName, inheritedMethod) {
1740 var method = methods[qualifiedName];
1741 if (method != null) {
1742 // if we have overwritten this method in this class, we still provide
1743 // the opportunity to inherit the comments.
1744 method.ensureCommentFor(inheritedMethod);
1745 }
1746 });
1747 // we need to populate the comments for all methods. so that the subclasses
1748 // can get for their inherited versions the comments.
1749 methods.forEach((qualifiedName, method) {
1750 if (!method.mirror.isConstructor) method.ensureCommentFor(method);
1751 });
1752 }
1753
1754 /// If a class extends a private superclass, find the closest public
1755 /// superclass of the private superclass.
1756 String validSuperclass() {
1757 if (superclass == null) return 'dart-core.Object';
1758 if (superclass._isVisible) return superclass.qualifiedName;
1759 return superclass.validSuperclass();
1760 }
1761
1762 /// Generates a map describing the [Class] object.
1763 Map toMap() => {
1764 'name': name,
1765 'qualifiedName': qualifiedName,
1766 'comment': comment,
1767 'isAbstract' : isAbstract,
1768 'superclass': validSuperclass(),
1769 'implements': interfaces.where((i) => i._isVisible)
1770 .map((e) => e.qualifiedName).toList(),
1771 'subclass': (subclasses.toList()..sort())
1772 .map((x) => x.qualifiedName).toList(),
1773 'variables': recurseMap(variables),
1774 'inheritedVariables': recurseMap(inheritedVariables),
1775 'methods': _expandMethodMap(methods),
1776 'inheritedMethods': _expandMethodMap(inheritedMethods),
1777 'annotations': annotations.map((a) => a.toMap()).toList(),
1778 'generics': recurseMap(generics)
1779 };
1780
1781 int compareTo(aClass) => name.compareTo(aClass.name);
1782
1783 bool _isValidMirror(DeclarationMirror mirror) => mirror is ClassMirror;
1784 }
1785
1786 class Typedef extends OwnedIndexable {
1787 String returnType;
1788
1789 Map<String, Parameter> parameters;
1790
1791 /// Generic information about the typedef.
1792 Map<String, Generic> generics;
1793
1794 /// Returns the [Library] for the given [mirror] if it has already been
1795 /// created, else creates it.
1796 factory Typedef(TypedefMirror mirror, Library owningLibrary) {
1797 var aTypedef = Indexable.getDocgenObject(mirror, owningLibrary);
1798 if (aTypedef is DummyMirror) {
1799 aTypedef = new Typedef._(mirror, owningLibrary);
1800 }
1801 return aTypedef;
1802 }
1803
1804 Typedef._(TypedefMirror mirror, Library owningLibrary) :
1805 super(mirror, owningLibrary) {
1806 returnType = Indexable.getDocgenObject(mirror.referent.returnType).docName;
1807 generics = _createGenerics(mirror);
1808 parameters = _createParameters(mirror.referent.parameters, owningLibrary);
1809 annotations = _createAnnotations(mirror, owningLibrary);
1810 }
1811
1812 Map toMap() {
1813 var map = {
1814 'name': name,
1815 'qualifiedName': qualifiedName,
1816 'comment': comment,
1817 'return': returnType,
1818 'parameters': recurseMap(parameters),
1819 'annotations': annotations.map((a) => a.toMap()).toList(),
1820 'generics': recurseMap(generics)
1821 };
1822
1823 // Typedef is displayed on the library page as a class, so a preview is
1824 // added manually
1825 var preview = _preview;
1826 if(preview != null) map['preview'] = preview;
1827
1828 return map;
1829 }
1830
1831 markdown.Node fixReference(String name) => null;
1832
1833 String get typeName => 'typedef';
1834
1835 bool _isValidMirror(DeclarationMirror mirror) => mirror is TypedefMirror;
1836 }
1837
1838 /// A class containing properties of a Dart variable.
1839 class Variable extends OwnedIndexable {
1840
1841 bool isFinal;
1842 bool isStatic;
1843 bool isConst;
1844 Type type;
1845 String _variableName;
1846
1847 factory Variable(String variableName, VariableMirror mirror,
1848 Indexable owner) {
1849 var variable = Indexable.getDocgenObject(mirror);
1850 if (variable is DummyMirror) {
1851 return new Variable._(variableName, mirror, owner);
1852 }
1853 return variable;
1854 }
1855
1856 Variable._(this._variableName, VariableMirror mirror, Indexable owner) :
1857 super(mirror, owner) {
1858 isFinal = mirror.isFinal;
1859 isStatic = mirror.isStatic;
1860 isConst = mirror.isConst;
1861 type = new Type(mirror.type, owner._owningLibrary);
1862 annotations = _createAnnotations(mirror, owner._owningLibrary);
1863 }
1864
1865 String get name => _variableName;
1866
1867 /// Generates a map describing the [Variable] object.
1868 Map toMap() => {
1869 'name': name,
1870 'qualifiedName': qualifiedName,
1871 'comment': comment,
1872 'final': isFinal,
1873 'static': isStatic,
1874 'constant': isConst,
1875 'type': new List.filled(1, type.toMap()),
1876 'annotations': annotations.map((a) => a.toMap()).toList()
1877 };
1878
1879 String get typeName => 'property';
1880
1881 get comment {
1882 if (_comment != null) return _comment;
1883 if (owner is Class) {
1884 (owner as Class).ensureComments();
1885 }
1886 return super.comment;
1887 }
1888
1889 String findElementInScope(String name) {
1890 var lookupFunc = determineLookupFunc(name);
1891 var result = lookupFunc(mirror, name);
1892 if (result != null) {
1893 result = Indexable.getDocgenObject(result);
1894 if (result is DummyMirror) return packagePrefix + result.docName;
1895 return result.packagePrefix + result.docName;
1896 }
1897
1898 if (owner != null) {
1899 var result = owner.findElementInScope(name);
1900 if (result != null) {
1901 return result;
1902 }
1903 }
1904 return super.findElementInScope(name);
1905 }
1906
1907 bool _isValidMirror(DeclarationMirror mirror) => mirror is VariableMirror;
1908 }
1909
1910 /// A class containing properties of a Dart method.
1911 class Method extends OwnedIndexable {
1912
1913 /// Parameters for this method.
1914 Map<String, Parameter> parameters;
1915
1916 bool isStatic;
1917 bool isAbstract;
1918 bool isConst;
1919 Type returnType;
1920 Method methodInheritedFrom;
1921
1922 /// Qualified name to state where the comment is inherited from.
1923 String commentInheritedFrom = "";
1924
1925 factory Method(MethodMirror mirror, Indexable owner,
1926 [Method methodInheritedFrom]) {
1927 var method = Indexable.getDocgenObject(mirror, owner);
1928 if (method is DummyMirror) {
1929 method = new Method._(mirror, owner, methodInheritedFrom);
1930 }
1931 return method;
1932 }
1933
1934 Method._(MethodMirror mirror, Indexable owner, this.methodInheritedFrom)
1935 : super(mirror, owner) {
1936 isStatic = mirror.isStatic;
1937 isAbstract = mirror.isAbstract;
1938 isConst = mirror.isConstConstructor;
1939 returnType = new Type(mirror.returnType, owner._owningLibrary);
1940 parameters = _createParameters(mirror.parameters, owner);
1941 annotations = _createAnnotations(mirror, owner._owningLibrary);
1942 }
1943
1944 Method get originallyInheritedFrom => methodInheritedFrom == null ?
1945 this : methodInheritedFrom.originallyInheritedFrom;
1946
1947 /// Look for the specified name starting with the current member, and
1948 /// progressively working outward to the current library scope.
1949 String findElementInScope(String name) {
1950 var lookupFunc = determineLookupFunc(name);
1951
1952 var memberScope = lookupFunc(this.mirror, name);
1953 if (memberScope != null) {
1954 // do we check for a dummy mirror returned here and look up with an owner
1955 // higher ooooor in getDocgenObject do we include more things in our
1956 // lookup
1957 var result = Indexable.getDocgenObject(memberScope, owner);
1958 if (result is DummyMirror && owner.owner != null
1959 && owner.owner is! DummyMirror) {
1960 var aresult = Indexable.getDocgenObject(memberScope, owner.owner);
1961 if (aresult is! DummyMirror) result = aresult;
1962 }
1963 if (result is DummyMirror) return packagePrefix + result.docName;
1964 return result.packagePrefix + result.docName;
1965 }
1966
1967 if (owner != null) {
1968 var result = owner.findElementInScope(name);
1969 if (result != null) return result;
1970 }
1971 return super.findElementInScope(name);
1972 }
1973
1974 String get docName {
1975 if ((mirror as MethodMirror).isConstructor) {
1976 // We name constructors specially -- including the class name again and a
1977 // "-" to separate the constructor from its name (if any).
1978 return '${owner.docName}.${dart2js_util.nameOf(mirror.owner)}-'
1979 '${dart2js_util.nameOf(mirror)}';
1980 }
1981 return super.docName;
1982 }
1983
1984 String get fileName => packagePrefix + docName;
1985
1986 /// Makes sure that the method with an inherited equivalent have comments.
1987 void ensureCommentFor(Method inheritedMethod) {
1988 if (comment.isNotEmpty) return;
1989
1990 comment = inheritedMethod._commentToHtml(this);
1991 _unresolvedComment = inheritedMethod._unresolvedComment;
1992 commentInheritedFrom = inheritedMethod.commentInheritedFrom == '' ?
1993 new DummyMirror(inheritedMethod.mirror).docName :
1994 inheritedMethod.commentInheritedFrom;
1995 }
1996
1997 /// Generates a map describing the [Method] object.
1998 Map toMap() => {
1999 'name': name,
2000 'qualifiedName': qualifiedName,
2001 'comment': comment,
2002 'commentFrom': (methodInheritedFrom != null &&
2003 commentInheritedFrom == methodInheritedFrom.docName ? ''
2004 : commentInheritedFrom),
2005 'inheritedFrom': (methodInheritedFrom == null? '' :
2006 originallyInheritedFrom.docName),
2007 'static': isStatic,
2008 'abstract': isAbstract,
2009 'constant': isConst,
2010 'return': new List.filled(1, returnType.toMap()),
2011 'parameters': recurseMap(parameters),
2012 'annotations': annotations.map((a) => a.toMap()).toList()
2013 };
2014
2015 String get typeName {
2016 MethodMirror theMirror = mirror;
2017 if (theMirror.isConstructor) return 'constructor';
2018 if (theMirror.isGetter) return 'getter';
2019 if (theMirror.isSetter) return'setter';
2020 if (theMirror.isOperator) return 'operator';
2021 return 'method';
2022 }
2023
2024 get comment {
2025 if (_comment != null) return _comment;
2026 if (owner is Class) {
2027 (owner as Class).ensureComments();
2028 }
2029 var result = super.comment;
2030 if (result == '' && methodInheritedFrom != null) {
2031 // This should be NOT from the MIRROR, but from the COMMENT.
2032 methodInheritedFrom.comment; // Ensure comment field has been populated.
2033 _unresolvedComment = methodInheritedFrom._unresolvedComment;
2034
2035 var linkResolver = (name) => fixReference(name);
2036 comment = _unresolvedComment == null ? '' :
2037 markdown.markdownToHtml(_unresolvedComment.trim(),
2038 linkResolver: linkResolver, inlineSyntaxes: _MARKDOWN_SYNTAXES);
2039 commentInheritedFrom = comment != '' ?
2040 methodInheritedFrom.commentInheritedFrom : '';
2041 result = comment;
2042 }
2043 return result;
2044 }
2045
2046 bool _isValidMirror(DeclarationMirror mirror) => mirror is MethodMirror;
2047 }
2048
2049 /// Docgen wrapper around the dart2js mirror for a Dart
2050 /// method/function parameter.
2051 class Parameter extends MirrorBased {
2052 final ParameterMirror mirror;
2053 final String name;
2054 final bool isOptional;
2055 final bool isNamed;
2056 final bool hasDefaultValue;
2057 final Type type;
2058 final String defaultValue;
2059 /// List of the meta annotations on the parameter.
2060 final List<Annotation> annotations;
2061
2062 Parameter(ParameterMirror mirror, Library owningLibrary)
2063 : this.mirror = mirror,
2064 name = dart2js_util.nameOf(mirror),
2065 isOptional = mirror.isOptional,
2066 isNamed = mirror.isNamed,
2067 hasDefaultValue = mirror.hasDefaultValue,
2068 defaultValue = '${mirror.defaultValue}',
2069 type = new Type(mirror.type, owningLibrary),
2070 annotations = _createAnnotations(mirror, owningLibrary);
2071
2072 /// Generates a map describing the [Parameter] object.
2073 Map toMap() => {
2074 'name': name,
2075 'optional': isOptional,
2076 'named': isNamed,
2077 'default': hasDefaultValue,
2078 'type': new List.filled(1, type.toMap()),
2079 'value': defaultValue,
2080 'annotations': annotations.map((a) => a.toMap()).toList()
2081 };
2082 }
2083
2084 /// Docgen wrapper around the mirror for a return type, and/or its generic
2085 /// type parameters.
2086 ///
2087 /// Return types are of a form [outer]<[inner]>.
2088 /// If there is no [inner] part, [inner] will be an empty list.
2089 ///
2090 /// For example:
2091 /// int size()
2092 /// "return" :
2093 /// - "outer" : "dart-core.int"
2094 /// "inner" :
2095 ///
2096 /// List<String> toList()
2097 /// "return" :
2098 /// - "outer" : "dart-core.List"
2099 /// "inner" :
2100 /// - "outer" : "dart-core.String"
2101 /// "inner" :
2102 ///
2103 /// Map<String, List<int>>
2104 /// "return" :
2105 /// - "outer" : "dart-core.Map"
2106 /// "inner" :
2107 /// - "outer" : "dart-core.String"
2108 /// "inner" :
2109 /// - "outer" : "dart-core.List"
2110 /// "inner" :
2111 /// - "outer" : "dart-core.int"
2112 /// "inner" :
2113 class Type extends MirrorBased {
2114 final TypeMirror mirror;
2115 final Library owningLibrary;
2116
2117 Type(this.mirror, this.owningLibrary);
2118
2119 /// Returns a list of [Type] objects constructed from TypeMirrors.
2120 List<Type> _createTypeGenerics(TypeMirror mirror) {
2121 if (mirror is ClassMirror) {
2122 var innerList = [];
2123 mirror.typeArguments.forEach((e) {
2124 innerList.add(new Type(e, owningLibrary));
2125 });
2126 return innerList;
2127 }
2128 return [];
2129 }
2130
2131 Map toMap() {
2132 var result = Indexable.getDocgenObject(mirror, owningLibrary);
2133 return {
2134 // We may encounter types whose corresponding library has not been
2135 // processed yet, so look up with the owningLibrary at the last moment.
2136 'outer': result.packagePrefix + result.docName,
2137 'inner': _createTypeGenerics(mirror).map((e) => e.toMap()).toList(),
2138 };
2139 }
2140 }
2141
2142 /// Holds the name of the annotation, and its parameters.
2143 class Annotation extends MirrorBased {
2144 /// The class of this annotation.
2145 final ClassMirror mirror;
2146 final Library owningLibrary;
2147 List<String> parameters;
2148
2149 Annotation(InstanceMirror originalMirror, this.owningLibrary)
2150 : mirror = originalMirror.type {
2151 parameters = dart2js_util.variablesOf(originalMirror.type.declarations)
2152 .where((e) => e.isFinal)
2153 .map((e) => originalMirror.getField(e.simpleName).reflectee)
2154 .where((e) => e != null)
2155 .toList();
2156 }
2157
2158 Map toMap() => {
2159 'name': Indexable.getDocgenObject(mirror, owningLibrary).docName,
2160 'parameters': parameters
2161 };
2162 }
2163
2164 /// Returns a list of meta annotations assocated with a mirror.
2165 List<Annotation> _createAnnotations(DeclarationMirror mirror,
2166 Library owningLibrary) {
2167 var annotationMirrors = mirror.metadata.where((e) =>
2168 e is dart2js_mirrors.Dart2JsConstructedConstantMirror);
2169 var annotations = [];
2170 annotationMirrors.forEach((annotation) {
2171 var docgenAnnotation = new Annotation(annotation, owningLibrary);
2172 if (!_SKIPPED_ANNOTATIONS.contains(
2173 dart2js_util.qualifiedNameOf(docgenAnnotation.mirror))) {
2174 annotations.add(docgenAnnotation);
2175 }
2176 });
2177 return annotations;
2178 }
OLDNEW
« no previous file with comments | « pkg/docgen/bin/docgen.dart ('k') | pkg/docgen/lib/src/generator.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698