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

Side by Side Diff: utils/dartdoc/dartdoc.dart

Issue 9555013: Get dartdoc in the SDK and working correctly. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Update copyright date. Created 8 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
OLDNEW
(Empty)
1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
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.
4
5 /**
6 * To use it, from this directory, run:
7 *
8 * $ ./dartdoc <path to .dart file>
9 *
10 * This will create a "docs" directory with the docs for your libraries. To
11 * create these beautiful docs, dartdoc parses your library and every library
12 * it imports (recursively). From each library, it parses all classes and
13 * members, finds the associated doc comments and builds crosslinked docs from
14 * them.
15 */
16 #library('dartdoc');
17
18 #import('dart:io');
19 #import('dart:json');
20 #import('../../frog/lang.dart');
21 #import('../../frog/file_system.dart');
22 #import('../../frog/file_system_vm.dart');
23 #import('classify.dart');
24 #import('markdown.dart', prefix: 'md');
25
26 #source('comment_map.dart');
27 #source('utils.dart');
28
29 /** Path to generate HTML files into. */
30 final _outdir = 'docs';
31
32 /**
33 * Generates completely static HTML containing everything you need to browse
34 * the docs. The only client side behavior is trivial stuff like syntax
35 * highlighting code.
36 */
37 final MODE_STATIC = 0;
38
39 /**
40 * Generated docs do not include baked HTML navigation. Instead, a single
41 * `nav.json` file is created and the appropriate navigation is generated
42 * client-side by parsing that and building HTML.
43 *
44 * This dramatically reduces the generated size of the HTML since a large
45 * fraction of each static page is just redundant navigation links.
46 *
47 * In this mode, the browser will do a XHR for nav.json which means that to
48 * preview docs locally, you will need to enable requesting file:// links in
49 * your browser or run a little local server like `python -m SimpleHTTPServer`.
50 */
51 final MODE_LIVE_NAV = 1;
52
53 /**
54 * Run this from the `utils/dartdoc` directory.
55 */
56 void main() {
57 final args = new Options().arguments;
58
59 // The entrypoint of the library to generate docs for.
60 final entrypoint = args[args.length - 1];
61
62 // Parse the dartdoc options.
63 bool includeSource = true;
64 var mode = MODE_LIVE_NAV;
65
66 for (int i = 2; i < args.length - 1; i++) {
67 final arg = args[i];
68 switch (arg) {
69 case '--no-code':
70 includeSource = false;
71 break;
72
73 case '--mode=static':
74 mode = MODE_STATIC;
75 break;
76
77 case '--mode=live-nav':
78 mode = MODE_LIVE_NAV;
79 break;
80
81 default:
82 print('Unknown option: $arg');
83 }
84 }
85
86 final files = new VMFileSystem();
87 parseOptions('../../frog', ['', '', '--libdir=../../frog/lib'], files);
88 initializeWorld(files);
89
90 var dartdoc;
91 final elapsed = time(() {
92 dartdoc = new Dartdoc();
93 dartdoc.includeSource = includeSource;
94 dartdoc.mode = mode;
95
96 dartdoc.document(entrypoint);
97 });
98
99 print('Documented ${dartdoc._totalLibraries} libraries, ' +
100 '${dartdoc._totalTypes} types, and ' +
101 '${dartdoc._totalMembers} members in ${elapsed}msec.');
102 }
103
104 class Dartdoc {
105 /** Set to `false` to not include the source code in the generated docs. */
106 bool includeSource = true;
107
108 /**
109 * Dartdoc can generate docs in a few different ways based on how dynamic you
110 * want the client-side behavior to be. The value for this should be one of
111 * the `MODE_` constants.
112 */
113 int mode = MODE_LIVE_NAV;
114
115 /**
116 * The title used for the overall generated output. Set this to change it.
117 */
118 String mainTitle = 'Dart Documentation';
119
120 /**
121 * The URL that the Dart logo links to. Defaults "index.html", the main
122 * page for the generated docs, but can be anything.
123 */
124 String mainUrl = 'index.html';
125
126 /**
127 * The Google Custom Search ID that should be used for the search box. If
128 * this is `null` then no search box will be shown.
129 */
130 String searchEngineId = null;
131
132 /* The URL that the embedded search results should be displayed on. */
133 String searchResultsUrl = 'results.html';
134
135 /** Set this to add footer text to each generated page. */
136 String footerText = '';
137
138 /**
139 * From exposes the set of libraries in `world.libraries`. That maps library
140 * *keys* to [Library] objects. The keys are *not* exactly the same as their
141 * names. This means if we order by key, we won't actually have them sorted
142 * correctly. This list contains the libraries in correct order by their
143 * *name*.
144 */
145 List<Library> _sortedLibraries;
146
147 CommentMap _comments;
148
149 /** The library that we're currently generating docs for. */
150 Library _currentLibrary;
151
152 /** The type that we're currently generating docs for. */
153 Type _currentType;
154
155 /** The member that we're currently generating docs for. */
156 Member _currentMember;
157
158 /** The path to the file currently being written to, relative to [outdir]. */
159 String _filePath;
160
161 /** The file currently being written to. */
162 StringBuffer _file;
163
164 int _totalLibraries = 0;
165 int _totalTypes = 0;
166 int _totalMembers = 0;
167
168 Dartdoc()
169 : _comments = new CommentMap() {
170 // Patch in support for [:...:]-style code to the markdown parser.
171 // TODO(rnystrom): Markdown already has syntax for this. Phase this out?
172 md.InlineParser.syntaxes.insertRange(0, 1,
173 new md.CodeSyntax(@'\[\:((?:.|\n)*?)\:\]'));
174
175 md.setImplicitLinkResolver((name) => resolveNameReference(name,
176 library: _currentLibrary, type: _currentType,
177 member: _currentMember));
178 }
179
180 void document(String entrypoint) {
181 var oldDietParse = options.dietParse;
182 try {
183 options.dietParse = true;
184
185 // Handle the built-in entrypoints.
186 switch (entrypoint) {
187 case 'corelib':
188 world.getOrAddLibrary('dart:core');
189 world.getOrAddLibrary('dart:coreimpl');
190 world.getOrAddLibrary('dart:json');
191 world.getOrAddLibrary('dart:isolate');
192 world.process();
193 break;
194
195 case 'dom':
196 world.getOrAddLibrary('dart:core');
197 world.getOrAddLibrary('dart:coreimpl');
198 world.getOrAddLibrary('dart:json');
199 world.getOrAddLibrary('dart:dom');
200 world.getOrAddLibrary('dart:isolate');
201 world.process();
202 break;
203
204 case 'html':
205 world.getOrAddLibrary('dart:core');
206 world.getOrAddLibrary('dart:coreimpl');
207 world.getOrAddLibrary('dart:json');
208 world.getOrAddLibrary('dart:dom');
209 world.getOrAddLibrary('dart:html');
210 world.getOrAddLibrary('dart:isolate');
211 world.process();
212 break;
213
214 default:
215 // Normal entrypoint script.
216 world.processDartScript(entrypoint);
217 }
218
219 world.resolveAll();
220
221 // Sort the libraries by name (not key).
222 _sortedLibraries = world.libraries.getValues();
223 _sortedLibraries.sort((a, b) {
224 return a.name.toUpperCase().compareTo(b.name.toUpperCase());
225 });
226
227 // Generate the docs.
228 if (mode == MODE_LIVE_NAV) docNavigationJson();
229
230 docIndex();
231 for (final library in _sortedLibraries) {
232 docLibrary(library);
233 }
234 } finally {
235 options.dietParse = oldDietParse;
236 }
237 }
238
239 void startFile(String path) {
240 _filePath = path;
241 _file = new StringBuffer();
242 }
243
244 void endFile() {
245 final outPath = '$_outdir/$_filePath';
246 final dir = new Directory(dirname(outPath));
247 if (!dir.existsSync()) {
248 dir.createSync();
249 }
250
251 world.files.writeString(outPath, _file.toString());
252 _filePath = null;
253 _file = null;
254 }
255
256 void write(String s) {
257 _file.add(s);
258 }
259
260 void writeln(String s) {
261 write(s);
262 write('\n');
263 }
264
265 /**
266 * Writes the page header with the given [title] and [breadcrumbs]. The
267 * breadcrumbs are an interleaved list of links and titles. If a link is null,
268 * then no link will be generated. For example, given:
269 *
270 * ['foo', 'foo.html', 'bar', null]
271 *
272 * It will output:
273 *
274 * <a href="foo.html">foo</a> &rsaquo; bar
275 */
276 void writeHeader(String title, List<String> breadcrumbs) {
277 write(
278 '''
279 <!DOCTYPE html>
280 <html>
281 <head>
282 ''');
283 writeHeadContents(title);
284
285 // Add data attributes describing what the page documents.
286 var data = '';
287 if (_currentLibrary != null) {
288 data += ' data-library="${md.escapeHtml(_currentLibrary.name)}"';
289 }
290
291 if (_currentType != null) {
292 data += ' data-type="${md.escapeHtml(typeName(_currentType))}"';
293 }
294
295 write(
296 '''
297 </head>
298 <body$data>
299 <div class="page">
300 <div class="header">
301 ${a(mainUrl, '<div class="logo"></div>')}
302 ${a('index.html', mainTitle)}
303 ''');
304
305 // Write the breadcrumb trail.
306 for (int i = 0; i < breadcrumbs.length; i += 2) {
307 if (breadcrumbs[i + 1] == null) {
308 write(' &rsaquo; ${breadcrumbs[i]}');
309 } else {
310 write(' &rsaquo; ${a(breadcrumbs[i + 1], breadcrumbs[i])}');
311 }
312 }
313
314 if (searchEngineId != null) {
315 writeln(
316 '''
317 <form action="$searchResultsUrl" id="search-box">
318 <input type="hidden" name="cx" value="$searchEngineId">
319 <input type="hidden" name="ie" value="UTF-8">
320 <input type="hidden" name="hl" value="en">
321 <input type="search" name="q" id="q" autocomplete="off"
322 placeholder="Search">
323 </form>
324 ''');
325 }
326
327 writeln('</div>');
328
329 docNavigation();
330 writeln('<div class="content">');
331 }
332
333 String get clientScript() {
334 switch (mode) {
335 case MODE_STATIC: return 'client-static';
336 case MODE_LIVE_NAV: return 'client-live-nav';
337 default: throw 'Unknown mode $mode.';
338 }
339 }
340
341 void writeHeadContents(String title) {
342 writeln(
343 '''
344 <meta charset="utf-8">
345 <title>$title</title>
346 <link rel="stylesheet" type="text/css"
347 href="${relativePath('styles.css')}" />
348 <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,600,700 ,800" rel="stylesheet" type="text/css">
349 <link rel="shortcut icon" href="${relativePath('favicon.ico')}" />
350 <script src="${relativePath('$clientScript.js')}"></script>
351 ''');
352 }
353
354 void writeFooter() {
355 writeln(
356 '''
357 </div>
358 <div class="clear"></div>
359 </div>
360 <div class="footer">$footerText</div>
361 </body></html>
362 ''');
363 }
364
365 void docIndex() {
366 startFile('index.html');
367
368 writeHeader(mainTitle, []);
369
370 writeln('<h2>$mainTitle</h2>');
371 writeln('<h3>Libraries</h3>');
372
373 for (final library in _sortedLibraries) {
374 docIndexLibrary(library);
375 }
376
377 writeFooter();
378 endFile();
379 }
380
381 void docIndexLibrary(Library library) {
382 writeln('<h4>${a(libraryUrl(library), library.name)}</h4>');
383 }
384
385 /**
386 * Walks the libraries and creates a JSON object containing the data needed
387 * to generate navigation for them.
388 */
389 void docNavigationJson() {
390 startFile('nav.json');
391
392 final libraries = {};
393
394 for (final library in _sortedLibraries) {
395 docLibraryNavigationJson(library, libraries);
396 }
397
398 writeln(JSON.stringify(libraries));
399 endFile();
400 }
401
402 void docLibraryNavigationJson(Library library, Map libraries) {
403 final types = [];
404
405 for (final type in orderByName(library.types)) {
406 if (type.isTop) continue;
407 if (type.name.startsWith('_')) continue;
408
409 final kind = type.isClass ? 'class' : 'interface';
410 final url = typeUrl(type);
411 types.add({ 'name': typeName(type), 'kind': kind, 'url': url });
412 }
413
414 libraries[library.name] = types;
415 }
416
417 void docNavigation() {
418 writeln(
419 '''
420 <div class="nav">
421 ''');
422
423 if (mode == MODE_STATIC) {
424 for (final library in _sortedLibraries) {
425 write('<h2><div class="icon-library"></div>');
426
427 if ((_currentLibrary == library) && (_currentType == null)) {
428 write('<strong>${library.name}</strong>');
429 } else {
430 write('${a(libraryUrl(library), library.name)}');
431 }
432 write('</h2>');
433
434 // Only expand classes in navigation for current library.
435 if (_currentLibrary == library) docLibraryNavigation(library);
436 }
437 }
438
439 writeln('</div>');
440 }
441
442 /** Writes the navigation for the types contained by the given library. */
443 void docLibraryNavigation(Library library) {
444 // Show the exception types separately.
445 final types = <Type>[];
446 final exceptions = <Type>[];
447
448 for (final type in orderByName(library.types)) {
449 if (type.isTop) continue;
450 if (type.name.startsWith('_')) continue;
451
452 if (type.name.endsWith('Exception')) {
453 exceptions.add(type);
454 } else {
455 types.add(type);
456 }
457 }
458
459 if ((types.length == 0) && (exceptions.length == 0)) return;
460
461 writeln('<ul class="icon">');
462 types.forEach(docTypeNavigation);
463 exceptions.forEach(docTypeNavigation);
464 writeln('</ul>');
465 }
466
467 /** Writes a linked navigation list item for the given type. */
468 void docTypeNavigation(Type type) {
469 var icon = 'interface';
470 if (type.name.endsWith('Exception')) {
471 icon = 'exception';
472 } else if (type.isClass) {
473 icon = 'class';
474 }
475
476 write('<li>');
477 if (_currentType == type) {
478 write(
479 '<div class="icon-$icon"></div><strong>${typeName(type)}</strong>');
480 } else {
481 write(a(typeUrl(type),
482 '<div class="icon-$icon"></div>${typeName(type)}'));
483 }
484 writeln('</li>');
485 }
486
487 void docLibrary(Library library) {
488 _totalLibraries++;
489 _currentLibrary = library;
490 _currentType = null;
491
492 startFile(libraryUrl(library));
493 writeHeader(library.name, [library.name, libraryUrl(library)]);
494 writeln('<h2>Library <strong>${library.name}</strong></h2>');
495
496 // Look for a comment for the entire library.
497 final comment = _comments.findLibrary(library.baseSource);
498 if (comment != null) {
499 final html = md.markdownToHtml(comment);
500 writeln('<div class="doc">$html</div>');
501 }
502
503 // Document the top-level members.
504 docMembers(library.topType);
505
506 // Document the types.
507 final classes = <Type>[];
508 final interfaces = <Type>[];
509 final exceptions = <Type>[];
510
511 for (final type in orderByName(library.types)) {
512 if (type.isTop) continue;
513 if (type.name.startsWith('_')) continue;
514
515 if (type.name.endsWith('Exception')) {
516 exceptions.add(type);
517 } else if (type.isClass) {
518 classes.add(type);
519 } else {
520 interfaces.add(type);
521 }
522 }
523
524 docTypes(classes, 'Classes');
525 docTypes(interfaces, 'Interfaces');
526 docTypes(exceptions, 'Exceptions');
527
528 writeFooter();
529 endFile();
530
531 for (final type in library.types.getValues()) {
532 if (!type.isTop) docType(type);
533 }
534 }
535
536 void docTypes(List<Type> types, String header) {
537 if (types.length == 0) return;
538
539 writeln('<h3>$header</h3>');
540
541 for (final type in types) {
542 writeln(
543 '''
544 <div class="type">
545 <h4>
546 ${a(typeUrl(type), "<strong>${typeName(type)}</strong>")}
547 </h4>
548 </div>
549 ''');
550 }
551 }
552
553 void docType(Type type) {
554 _totalTypes++;
555 _currentType = type;
556
557 startFile(typeUrl(type));
558
559 final typeTitle =
560 '${type.isClass ? "Class" : "Interface"} ${typeName(type)}';
561 writeHeader('Library ${type.library.name} / $typeTitle',
562 [type.library.name, libraryUrl(type.library),
563 typeName(type), typeUrl(type)]);
564 writeln(
565 '''
566 <h2>${type.isClass ? "Class" : "Interface"}
567 <strong>${typeName(type, showBounds: true)}</strong></h2>
568 ''');
569
570 docCode(type.span, getTypeComment(type));
571 docInheritance(type);
572 docConstructors(type);
573 docMembers(type);
574
575 writeTypeFooter();
576 writeFooter();
577 endFile();
578 }
579
580 /** Override this to write additional content at the end of a type's page. */
581 void writeTypeFooter() {
582 // Do nothing.
583 }
584
585 /**
586 * Writes an inline type span for the given type. This is a little box with
587 * an icon and the type's name. It's similar to how types appear in the
588 * navigation, but is suitable for inline (as opposed to in a `<ul>`) use.
589 */
590 void typeSpan(Type type) {
591 var icon = 'interface';
592 if (type.name.endsWith('Exception')) {
593 icon = 'exception';
594 } else if (type.isClass) {
595 icon = 'class';
596 }
597
598 write('<span class="type-box"><span class="icon-$icon"></span>');
599 if (_currentType == type) {
600 write('<strong>${typeName(type)}</strong>');
601 } else {
602 write(a(typeUrl(type), typeName(type)));
603 }
604 write('</span>');
605 }
606
607 /**
608 * Document the other types that touch [Type] in the inheritance hierarchy:
609 * subclasses, superclasses, subinterfaces, superinferfaces, and default
610 * class.
611 */
612 void docInheritance(Type type) {
613 // Don't show the inheritance details for Object. It doesn't have any base
614 // class (obviously) and it has too many subclasses to be useful.
615 if (type.isObject) return;
616
617 // Writes an unordered list of references to types with an optional header.
618 listTypes(types, header) {
619 if (types == null) return;
620
621 // Skip private types.
622 final publicTypes = types.filter((type) => !type.name.startsWith('_'));
623 if (publicTypes.length == 0) return;
624
625 writeln('<h3>$header</h3>');
626 writeln('<p>');
627 bool first = true;
628 for (final type in publicTypes) {
629 if (!first) write(', ');
630 typeSpan(type);
631 first = false;
632 }
633 writeln('</p>');
634 }
635
636 if (type.isClass) {
637 // Show the chain of superclasses.
638 if (!type.parent.isObject) {
639 final supertypes = [];
640 var thisType = type.parent;
641 // As a sanity check, only show up to five levels of nesting, otherwise
642 // the box starts to get hideous.
643 do {
644 supertypes.add(thisType);
645 thisType = thisType.parent;
646 } while (!thisType.isObject);
647
648 writeln('<h3>Extends</h3>');
649 writeln('<p>');
650 for (var i = supertypes.length - 1; i >= 0; i--) {
651 typeSpan(supertypes[i]);
652 write('&nbsp;&gt;&nbsp;');
653 }
654
655 // Write this class.
656 typeSpan(type);
657 writeln('</p>');
658 }
659
660 // Find the immediate declared subclasses (Type.subtypes includes many
661 // transitive subtypes).
662 final subtypes = [];
663 for (final subtype in type.subtypes) {
664 if (subtype.parent == type) subtypes.add(subtype);
665 }
666 subtypes.sort((a, b) => a.name.compareTo(b.name));
667
668 listTypes(subtypes, 'Subclasses');
669 listTypes(type.interfaces, 'Implements');
670 } else {
671 // Show the default class.
672 if (type.genericType.defaultType != null) {
673 listTypes([type.genericType.defaultType], 'Default class');
674 }
675
676 // List extended interfaces.
677 listTypes(type.interfaces, 'Extends');
678
679 // List subinterfaces and implementing classes.
680 final subinterfaces = [];
681 final implementing = [];
682
683 for (final subtype in type.subtypes) {
684 // We only want explicitly declared subinterfaces, so check that this
685 // type is a superinterface.
686 for (final supertype in subtype.interfaces) {
687 if (supertype == type) {
688 if (subtype.isClass) {
689 implementing.add(subtype);
690 } else {
691 subinterfaces.add(subtype);
692 }
693 break;
694 }
695 }
696 }
697
698 listTypes(subinterfaces, 'Subinterfaces');
699 listTypes(implementing, 'Implemented by');
700 }
701 }
702
703 /** Document the constructors for [Type], if any. */
704 void docConstructors(Type type) {
705 final names = type.constructors.getKeys().filter(
706 (name) => !name.startsWith('_'));
707
708 if (names.length > 0) {
709 writeln('<h3>Constructors</h3>');
710 names.sort((x, y) => x.toUpperCase().compareTo(y.toUpperCase()));
711
712 for (final name in names) {
713 docMethod(type, type.constructors[name], constructorName: name);
714 }
715 }
716 }
717
718 void docMembers(Type type) {
719 // Collect the different kinds of members.
720 final staticMethods = [];
721 final staticFields = [];
722 final instanceMethods = [];
723 final instanceFields = [];
724
725 for (final member in orderByName(type.members)) {
726 if (member.name.startsWith('_')) continue;
727
728 final methods = member.isStatic ? staticMethods : instanceMethods;
729 final fields = member.isStatic ? staticFields : instanceFields;
730
731 if (member.isProperty) {
732 if (member.canGet) methods.add(member.getter);
733 if (member.canSet) methods.add(member.setter);
734 } else if (member.isMethod) {
735 methods.add(member);
736 } else if (member.isField) {
737 fields.add(member);
738 }
739 }
740
741 if (staticMethods.length > 0) {
742 final title = type.isTop ? 'Functions' : 'Static Methods';
743 writeln('<h3>$title</h3>');
744 for (final method in staticMethods) docMethod(type, method);
745 }
746
747 if (staticFields.length > 0) {
748 final title = type.isTop ? 'Variables' : 'Static Fields';
749 writeln('<h3>$title</h3>');
750 for (final field in staticFields) docField(type, field);
751 }
752
753 if (instanceMethods.length > 0) {
754 writeln('<h3>Methods</h3>');
755 for (final method in instanceMethods) docMethod(type, method);
756 }
757
758 if (instanceFields.length > 0) {
759 writeln('<h3>Fields</h3>');
760 for (final field in instanceFields) docField(type, field);
761 }
762 }
763
764 /**
765 * Documents the [method] in type [type]. Handles all kinds of methods
766 * including getters, setters, and constructors.
767 */
768 void docMethod(Type type, MethodMember method,
769 [String constructorName = null]) {
770 _totalMembers++;
771 _currentMember = method;
772
773 writeln('<div class="method"><h4 id="${memberAnchor(method)}">');
774
775 if (includeSource) {
776 writeln('<span class="show-code">Code</span>');
777 }
778
779 if (method.isConstructor) {
780 write(method.isConst ? 'const ' : 'new ');
781 }
782
783 if (constructorName == null) {
784 annotateType(type, method.returnType);
785 }
786
787 // Translate specially-named methods: getters, setters, operators.
788 var name = method.name;
789 if (name.startsWith('get:')) {
790 // Getter.
791 name = 'get ${name.substring(4)}';
792 } else if (name.startsWith('set:')) {
793 // Setter.
794 name = 'set ${name.substring(4)}';
795 } else if (name == ':negate') {
796 // Dart uses 'negate' for prefix negate operators, not '!'.
797 name = 'operator negate';
798 } else if (name == ':call') {
799 name = 'operator call';
800 } else {
801 // See if it's an operator.
802 name = TokenKind.rawOperatorFromMethod(name);
803 if (name == null) {
804 name = method.name;
805 } else {
806 name = 'operator $name';
807 }
808 }
809
810 write('<strong>$name</strong>');
811
812 // Named constructors.
813 if (constructorName != null && constructorName != '') {
814 write('.');
815 write(constructorName);
816 }
817
818 docParamList(type, method);
819
820 write(''' <a class="anchor-link" href="#${memberAnchor(method)}"
821 title="Permalink to ${typeName(type)}.$name">#</a>''');
822 writeln('</h4>');
823
824 docCode(method.span, getMethodComment(method), showCode: true);
825
826 writeln('</div>');
827 }
828
829 /** Documents the field [field] of type [type]. */
830 void docField(Type type, FieldMember field) {
831 _totalMembers++;
832 _currentMember = field;
833
834 writeln('<div class="field"><h4 id="${memberAnchor(field)}">');
835
836 if (includeSource) {
837 writeln('<span class="show-code">Code</span>');
838 }
839
840 if (field.isFinal) {
841 write('final ');
842 } else if (field.type.name == 'Dynamic') {
843 write('var ');
844 }
845
846 annotateType(type, field.type);
847 write(
848 '''
849 <strong>${field.name}</strong> <a class="anchor-link"
850 href="#${memberAnchor(field)}"
851 title="Permalink to ${typeName(type)}.${field.name}">#</a>
852 </h4>
853 ''');
854
855 docCode(field.span, getFieldComment(field), showCode: true);
856 writeln('</div>');
857 }
858
859 void docParamList(Type enclosingType, MethodMember member) {
860 write('(');
861 bool first = true;
862 bool inOptionals = false;
863 for (final parameter in member.parameters) {
864 if (!first) write(', ');
865
866 if (!inOptionals && parameter.isOptional) {
867 write('[');
868 inOptionals = true;
869 }
870
871 annotateType(enclosingType, parameter.type, parameter.name);
872
873 // Show the default value for named optional parameters.
874 if (parameter.isOptional && parameter.hasDefaultValue) {
875 write(' = ');
876 // TODO(rnystrom): Using the definition text here is a bit cheap.
877 // We really should be pretty-printing the AST so that if you have:
878 // foo([arg = 1 + /* comment */ 2])
879 // the docs should just show:
880 // foo([arg = 1 + 2])
881 // For now, we'll assume you don't do that.
882 write(parameter.definition.value.span.text);
883 }
884
885 first = false;
886 }
887
888 if (inOptionals) write(']');
889 write(')');
890 }
891
892 /**
893 * Documents the code contained within [span] with [comment]. If [showCode]
894 * is `true` (and [includeSource] is set), also includes the source code.
895 */
896 void docCode(SourceSpan span, String comment, [bool showCode = false]) {
897 writeln('<div class="doc">');
898 if (comment != null) {
899 writeln(comment);
900 }
901
902 if (includeSource && showCode) {
903 writeln('<pre class="source">');
904 writeln(md.escapeHtml(unindentCode(span)));
905 writeln('</pre>');
906 }
907
908 writeln('</div>');
909 }
910
911 /** Get the doc comment associated with the given type. */
912 String getTypeComment(Type type) {
913 String comment = _comments.find(type.span);
914 if (comment == null) return null;
915 return md.markdownToHtml(comment);
916 }
917
918 /** Get the doc comment associated with the given method. */
919 String getMethodComment(MethodMember method) {
920 String comment = _comments.find(method.span);
921 if (comment == null) return null;
922 return md.markdownToHtml(comment);
923 }
924
925 /** Get the doc comment associated with the given field. */
926 String getFieldComment(FieldMember field) {
927 String comment = _comments.find(field.span);
928 if (comment == null) return null;
929 return md.markdownToHtml(comment);
930 }
931
932 /**
933 * Converts [fullPath] which is understood to be a full path from the root of
934 * the generated docs to one relative to the current file.
935 */
936 String relativePath(String fullPath) {
937 // Don't make it relative if it's an absolute path.
938 if (isAbsolute(fullPath)) return fullPath;
939
940 // TODO(rnystrom): Walks all the way up to root each time. Shouldn't do
941 // this if the paths overlap.
942 return repeat('../', countOccurrences(_filePath, '/')) + fullPath;
943 }
944
945 /** Gets whether or not the given URL is absolute or relative. */
946 bool isAbsolute(String url) {
947 // TODO(rnystrom): Why don't we have a nice type in the platform for this?
948 // TODO(rnystrom): This is a bit hackish. We consider any URL that lacks
949 // a scheme to be relative.
950 return const RegExp(@'^\w+:').hasMatch(url);
951 }
952
953 /** Gets the URL to the documentation for [library]. */
954 String libraryUrl(Library library) {
955 return '${sanitize(library.name)}.html';
956 }
957
958 /** Gets the URL for the documentation for [type]. */
959 String typeUrl(Type type) {
960 if (type.isTop) return '${sanitize(type.library.name)}.html';
961 // Always get the generic type to strip off any type parameters or
962 // arguments. If the type isn't generic, genericType returns `this`, so it
963 // works for non-generic types too.
964 return '${sanitize(type.library.name)}/${type.genericType.name}.html';
965 }
966
967 /** Gets the URL for the documentation for [member]. */
968 String memberUrl(Member member) {
969 final typeUrl = typeUrl(member.declaringType);
970 if (!member.isConstructor) return '$typeUrl#${member.name}';
971 if (member.constructorName == '') return '$typeUrl#new:${member.name}';
972 return '$typeUrl#new:${member.name}.${member.constructorName}';
973 }
974
975 /** Gets the anchor id for the document for [member]. */
976 String memberAnchor(Member member) {
977 return '${member.name}';
978 }
979
980 /**
981 * Creates a hyperlink. Handles turning the [href] into an appropriate
982 * relative path from the current file.
983 */
984 String a(String href, String contents, [String css]) {
985 // Mark outgoing external links, mainly so we can style them.
986 final rel = isAbsolute(href) ? ' ref="external"' : '';
987 final cssClass = css == null ? '' : ' class="$css"';
988 return '<a href="${relativePath(href)}"$cssClass$rel>$contents</a>';
989 }
990
991 /**
992 * Writes a type annotation for the given type and (optional) parameter name.
993 */
994 annotateType(Type enclosingType, Type type, [String paramName = null]) {
995 // Don't bother explicitly displaying Dynamic.
996 if (type.isVar) {
997 if (paramName !== null) write(paramName);
998 return;
999 }
1000
1001 // For parameters, handle non-typedefed function types.
1002 if (paramName !== null) {
1003 final call = type.getCallMethod();
1004 if (call != null) {
1005 annotateType(enclosingType, call.returnType);
1006 write(paramName);
1007
1008 docParamList(enclosingType, call);
1009 return;
1010 }
1011 }
1012
1013 linkToType(enclosingType, type);
1014
1015 write(' ');
1016 if (paramName !== null) write(paramName);
1017 }
1018
1019 /** Writes a link to a human-friendly string representation for a type. */
1020 linkToType(Type enclosingType, Type type) {
1021 if (type is ParameterType) {
1022 // If we're using a type parameter within the body of a generic class then
1023 // just link back up to the class.
1024 write(a(typeUrl(enclosingType), type.name));
1025 return;
1026 }
1027
1028 // Link to the type.
1029 // Use .genericType to avoid writing the <...> here.
1030 write(a(typeUrl(type), type.genericType.name));
1031
1032 // See if it's a generic type.
1033 if (type.isGeneric) {
1034 // TODO(rnystrom): This relies on a weird corner case of frog. Currently,
1035 // the only time we get into this case is when we have a "raw" generic
1036 // that's been instantiated with Dynamic for all type arguments. It's kind
1037 // of strange that frog works that way, but we take advantage of it to
1038 // show raw types without any type arguments.
1039 return;
1040 }
1041
1042 // See if it's an instantiation of a generic type.
1043 final typeArgs = type.typeArgsInOrder;
1044 if (typeArgs.length > 0) {
1045 write('&lt;');
1046 bool first = true;
1047 for (final arg in typeArgs) {
1048 if (!first) write(', ');
1049 first = false;
1050 linkToType(enclosingType, arg);
1051 }
1052 write('&gt;');
1053 }
1054 }
1055
1056 /** Creates a linked cross reference to [type]. */
1057 typeReference(Type type) {
1058 // TODO(rnystrom): Do we need to handle ParameterTypes here like
1059 // annotation() does?
1060 return a(typeUrl(type), typeName(type), css: 'crossref');
1061 }
1062
1063 /** Generates a human-friendly string representation for a type. */
1064 typeName(Type type, [bool showBounds = false]) {
1065 // See if it's a generic type.
1066 if (type.isGeneric) {
1067 final typeParams = [];
1068 for (final typeParam in type.genericType.typeParameters) {
1069 if (showBounds &&
1070 (typeParam.extendsType != null) &&
1071 !typeParam.extendsType.isObject) {
1072 final bound = typeName(typeParam.extendsType, showBounds: true);
1073 typeParams.add('${typeParam.name} extends $bound');
1074 } else {
1075 typeParams.add(typeParam.name);
1076 }
1077 }
1078
1079 final params = Strings.join(typeParams, ', ');
1080 return '${type.name}&lt;$params&gt;';
1081 }
1082
1083 // See if it's an instantiation of a generic type.
1084 final typeArgs = type.typeArgsInOrder;
1085 if (typeArgs.length > 0) {
1086 final args = Strings.join(map(typeArgs, (arg) => typeName(arg)), ', ');
1087 return '${type.genericType.name}&lt;$args&gt;';
1088 }
1089
1090 // Regular type.
1091 return type.name;
1092 }
1093
1094 /**
1095 * Remove leading indentation to line up with first line.
1096 */
1097 unindentCode(SourceSpan span) {
1098 final column = getSpanColumn(span);
1099 final lines = span.text.split('\n');
1100 // TODO(rnystrom): Dirty hack.
1101 for (var i = 1; i < lines.length; i++) {
1102 lines[i] = unindent(lines[i], column);
1103 }
1104
1105 final code = Strings.join(lines, '\n');
1106 return code;
1107 }
1108
1109 /**
1110 * Takes a string of Dart code and turns it into sanitized HTML.
1111 */
1112 formatCode(SourceSpan span) {
1113 final code = unindentCode(span);
1114
1115 // Syntax highlight.
1116 return classifySource(new SourceFile('', code));
1117 }
1118
1119 /**
1120 * This will be called whenever a doc comment hits a `[name]` in square
1121 * brackets. It will try to figure out what the name refers to and link or
1122 * style it appropriately.
1123 */
1124 md.Node resolveNameReference(String name, [Member member = null,
1125 Type type = null, Library library = null]) {
1126 makeLink(String href) {
1127 final anchor = new md.Element.text('a', name);
1128 anchor.attributes['href'] = relativePath(href);
1129 anchor.attributes['class'] = 'crossref';
1130 return anchor;
1131 }
1132
1133 findMember(Type type, String memberName) {
1134 final member = type.members[memberName];
1135 if (member == null) return null;
1136
1137 // Special case: if the member we've resolved is a property (i.e. it wraps
1138 // a getter and/or setter then *that* member itself won't be on the docs,
1139 // just the getter or setter will be. So pick one of those to link to.
1140 if (member.isProperty) {
1141 return member.canGet ? member.getter : member.setter;
1142 }
1143
1144 return member;
1145 }
1146
1147 // See if it's a parameter of the current method.
1148 if (member != null) {
1149 for (final parameter in member.parameters) {
1150 if (parameter.name == name) {
1151 final element = new md.Element.text('span', name);
1152 element.attributes['class'] = 'param';
1153 return element;
1154 }
1155 }
1156 }
1157
1158 // See if it's another member of the current type.
1159 if (type != null) {
1160 final member = findMember(type, name);
1161 if (member != null) {
1162 return makeLink(memberUrl(member));
1163 }
1164 }
1165
1166 // See if it's another type or a member of another type in the current
1167 // library.
1168 if (library != null) {
1169 // See if it's a constructor
1170 final constructorLink = (() {
1171 final match = new RegExp(@'new (\w+)(?:\.(\w+))?').firstMatch(name);
1172 if (match == null) return;
1173 final type = library.types[match[1]];
1174 if (type == null) return;
1175 final constructor = type.getConstructor(
1176 match[2] == null ? '' : match[2]);
1177 if (constructor == null) return;
1178 return makeLink(memberUrl(constructor));
1179 })();
1180 if (constructorLink != null) return constructorLink;
1181
1182 // See if it's a member of another type
1183 final foreignMemberLink = (() {
1184 final match = new RegExp(@'(\w+)\.(\w+)').firstMatch(name);
1185 if (match == null) return;
1186 final type = library.types[match[1]];
1187 if (type == null) return;
1188 final member = findMember(type, match[2]);
1189 if (member == null) return;
1190 return makeLink(memberUrl(member));
1191 })();
1192 if (foreignMemberLink != null) return foreignMemberLink;
1193
1194 final type = library.types[name];
1195 if (type != null) {
1196 return makeLink(typeUrl(type));
1197 }
1198
1199 // See if it's a top-level member in the current library.
1200 final member = findMember(library.topType, name);
1201 if (member != null) {
1202 return makeLink(memberUrl(member));
1203 }
1204 }
1205
1206 // TODO(rnystrom): Should also consider:
1207 // * Names imported by libraries this library imports.
1208 // * Type parameters of the enclosing type.
1209
1210 return new md.Element.text('code', name);
1211 }
1212
1213 // TODO(rnystrom): Move into SourceSpan?
1214 int getSpanColumn(SourceSpan span) {
1215 final line = span.file.getLine(span.start);
1216 return span.file.getColumn(line, span.start);
1217 }
1218 }
OLDNEW
« frog/presubmit.py ('K') | « utils/dartdoc/dartdoc ('k') | utils/dartdoc/html_renderer.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698