-
Notifications
You must be signed in to change notification settings - Fork 1
/
dartdoc.dart
1102 lines (916 loc) · 31.3 KB
/
dartdoc.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
/**
* To use it, from this directory, run:
*
* $ ./dartdoc <path to .dart file>
*
* This will create a "docs" directory with the docs for your libraries. To
* create these beautiful docs, dartdoc parses your library and every library
* it imports (recursively). From each library, it parses all classes and
* members, finds the associated doc comments and builds crosslinked docs from
* them.
*/
#library('dartdoc');
#import('dart:json');
#import('../../frog/lang.dart');
#import('../../frog/file_system.dart');
#import('../../frog/file_system_node.dart');
#import('../../frog/lib/node/node.dart');
#import('classify.dart');
#import('markdown.dart', prefix: 'md');
#source('comment_map.dart');
#source('files.dart');
#source('utils.dart');
#source('search.dart');
/**
* Generates completely static HTML containing everything you need to browse
* the docs. The only client side behavior is trivial stuff like syntax
* highlighting code.
*/
final MODE_STATIC = 0;
/**
* Generated docs do not include baked HTML navigation. Instead, a single
* `nav.json` file is created and the appropriate navigation is generated
* client-side by parsing that and building HTML.
*
* This dramatically reduces the generated size of the HTML since a large
* fraction of each static page is just redundant navigation links.
*
* In this mode, the browser will do a XHR for nav.json which means that to
* preview docs locally, you will need to enable requesting file:// links in
* your browser or run a little local server like `python -m SimpleHTTPServer`.
*/
final MODE_LIVE_NAV = 1;
/**
* Run this from the `utils/dartdoc` directory.
*/
void main() {
// The entrypoint of the library to generate docs for.
final entrypoint = process.argv[process.argv.length - 1];
// Parse the dartdoc options.
bool includeSource = true;
bool enableSearch = true;
var mode = MODE_LIVE_NAV;
for (int i = 2; i < process.argv.length - 1; i++) {
final arg = process.argv[i];
switch (arg) {
case '--no-code':
includeSource = false;
break;
case '--no-search':
enableSearch = false;
break;
case '--mode=static':
mode = MODE_STATIC;
break;
case '--mode=live-nav':
mode = MODE_LIVE_NAV;
break;
default:
print('Unknown option: $arg');
}
}
final files = new NodeFileSystem();
parseOptions('../../frog', [] /* args */, files);
initializeWorld(files);
var dartdoc;
final elapsed = time(() {
dartdoc = new Dartdoc();
dartdoc.includeSource = includeSource;
dartdoc.enableSearch = enableSearch;
dartdoc.mode = mode;
dartdoc.document(entrypoint);
});
print('Documented ${dartdoc._totalLibraries} libraries, ' +
'${dartdoc._totalTypes} types, and ' +
'${dartdoc._totalMembers} members in ${elapsed}msec.');
}
class Dartdoc {
/** Set to `false` to not include the source code in the generated docs. */
bool includeSource = true;
/** Set to `false` to not include the search widget in the generated docs. */
bool enableSearch = true;
/**
* Dartdoc can generate docs in a few different ways based on how dynamic you
* want the client-side behavior to be. The value for this should be one of
* the `MODE_` constants.
*/
int mode = MODE_LIVE_NAV;
/**
* The title used for the overall generated output. Set this to change it.
*/
String mainTitle = 'Dart Documentation';
/**
* The URL that the Dart logo links to. Defaults "index.html", the main
* page for the generated docs, but can be anything.
*/
String mainUrl = 'index.html';
/** Set this to add footer text to each generated page. */
String footerText = '';
CommentMap _comments;
/** The library that we're currently generating docs for. */
Library _currentLibrary;
/** The type that we're currently generating docs for. */
Type _currentType;
/** The member that we're currently generating docs for. */
Member _currentMember;
/** Search backend */
Search search;
int _totalLibraries = 0;
int _totalTypes = 0;
int _totalMembers = 0;
Dartdoc()
: _comments = new CommentMap(),
search = new Search() {
// Patch in support for [:...:]-style code to the markdown parser.
// TODO(rnystrom): Markdown already has syntax for this. Phase this out?
md.InlineParser.syntaxes.insertRange(0, 1,
new md.CodeSyntax(@'\[\:((?:.|\n)*?)\:\]'));
md.setImplicitLinkResolver((name) => resolveNameReference(name,
library: _currentLibrary, type: _currentType,
member: _currentMember));
}
document(String entrypoint) {
var oldDietParse = options.dietParse;
try {
options.dietParse = true;
// Handle the built-in entrypoints.
switch (entrypoint) {
case 'corelib':
world.getOrAddLibrary('dart:core');
world.getOrAddLibrary('dart:coreimpl');
world.getOrAddLibrary('dart:json');
world.process();
break;
case 'dom':
world.getOrAddLibrary('dart:core');
world.getOrAddLibrary('dart:coreimpl');
world.getOrAddLibrary('dart:json');
world.getOrAddLibrary('dart:dom');
world.process();
break;
case 'html':
world.getOrAddLibrary('dart:core');
world.getOrAddLibrary('dart:coreimpl');
world.getOrAddLibrary('dart:json');
world.getOrAddLibrary('dart:dom');
world.getOrAddLibrary('dart:html');
world.process();
break;
default:
// Normal entrypoint script.
world.processDartScript(entrypoint);
}
world.resolveAll();
// Generate the docs.
//if (mode == MODE_LIVE_NAV) docNavigationJson();
if (mode == MODE_LIVE_NAV) docNavigationDart();
if (enableSearch) docSearchNavigation();
docIndex();
for (final library in world.libraries.getValues()) {
docLibrary(library);
}
// Write dart source file.
search.contents2dart(enableSearch);
} finally {
options.dietParse = oldDietParse;
}
}
/**
* Writes the page header with the given [title] and [breadcrumbs]. The
* breadcrumbs are an interleaved list of links and titles. If a link is null,
* then no link will be generated. For example, given:
*
* ['foo', 'foo.html', 'bar', null]
*
* It will output:
*
* <a href="foo.html">foo</a> › bar
*/
writeHeader(String title, List<String> breadcrumbs) {
write(
'''
<!DOCTYPE html>
<html>
<head>
''');
writeHeadContents(title);
// Add data attributes describing what the page documents.
var data = '';
if (_currentLibrary != null) {
data += ' data-library="${md.escapeHtml(_currentLibrary.name)}"';
}
if (_currentType != null) {
data += ' data-type="${md.escapeHtml(typeName(_currentType))}"';
}
// [data-path] is used to compute the urls in the search navigation.
data += ' data-path="' + relativePath('.') + '"';
write(
'''
</head>
<body$data>
<div class="page">
<div class="header">
${a(mainUrl, '<div class="logo"></div>')}
${a('index.html', mainTitle)}
''');
// Write the breadcrumb trail.
for (int i = 0; i < breadcrumbs.length; i += 2) {
if (breadcrumbs[i + 1] == null) {
write(' › ${breadcrumbs[i]}');
} else {
write(' › ${a(breadcrumbs[i + 1], breadcrumbs[i])}');
}
}
writeln('</div>');
docNavigation();
writeln('<div class="content">');
}
String get clientScript() {
switch (mode) {
case MODE_STATIC: return 'client-static';
case MODE_LIVE_NAV: return 'client-live-nav';
default: throw 'Unknown mode $mode.';
}
}
writeHeadContents(String title) {
writeln(
'''
<meta charset="utf-8">
<title>$title</title>
<link rel="stylesheet" type="text/css"
href="${relativePath('styles.css')}" />
<link rel="stylesheet" type="text/css" media="print"
href="${relativePath('print.css')}" />
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,600,700,800" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="${relativePath('favicon.ico')}" />
<script src="${relativePath('$clientScript.js')}"></script>
''');
}
writeFooter() {
writeln(
'''
</div>
<div class="clear"></div>
</div>
<div class="footer">$footerText</div>
</body></html>
''');
}
docIndex() {
startFile('index.html');
writeHeader(mainTitle, []);
writeln('<h2>$mainTitle</h2>');
writeln('<h3>Libraries</h3>');
for (final library in orderByName(world.libraries)) {
writeln(
'''
<h4>${a(libraryUrl(library), library.name)}</h4>
''');
}
writeFooter();
endFile();
}
/**
* Walks the libraries and creates a JSON object containing the data needed
* to generate navigation for them.
*/
docNavigationJson() {
startFile('nav.json');
final libraries = {};
for (final library in orderByName(world.libraries)) {
final types = [];
for (final type in orderByName(library.types)) {
if (type.isTop) continue;
if (type.name.startsWith('_')) continue;
final kind = type.isClass ? 'class' : 'interface';
final url = typeUrl(type);
types.add({ 'name': typeName(type), 'kind': kind, 'url': url });
}
libraries[library.name] = types;
}
writeln(JSON.stringify(libraries));
endFile();
}
docNavigationDart() {
startFile('navigating.dart');
final libraries = {};
for (final library in orderByName(world.libraries)) {
final types = [];
for (final type in orderByName(library.types)) {
if (type.isTop) continue;
if (type.name.startsWith('_')) continue;
final kind = type.isClass ? 'class' : 'interface';
final url = typeUrl(type);
types.add({ 'name': typeName(type), 'kind': kind, 'url': url });
}
libraries[library.name] = types;
}
// Enclosing function start.
writeln('_libraries() {');
writeln('var libraries = ');
search.writeMap(libraries);
writeln(';');
// Enclosing function end.
writeln('return libraries;');
writeln('}');
// Write to the current directory.
search.endLocalFile();
}
docNavigation() {
if (mode == MODE_STATIC) {
writeln(
'''
<div class="nav built">
''');
var map = {};
for (var library in orderByName(world.libraries)) {
map[library.name] = library;
}
for (final library in orderByName(map)) {
write('<h2><div class="icon-library"></div>');
if ((_currentLibrary == library) && (_currentType == null)) {
write('<strong>${library.name}</strong>');
} else {
write('${a(libraryUrl(library), library.name)}');
}
write('</h2>');
// Only expand classes in navigation for current library.
if (_currentLibrary == library) docLibraryNavigation(library);
}
} else {
writeln(
'''
<div class="nav">
''');
}
writeln('</div>');
}
/** Writes the navigation for the types contained by the given library. */
docLibraryNavigation(Library library) {
// Show the exception types separately.
final types = <Type>[];
final exceptions = <Type>[];
for (final type in orderByName(library.types)) {
if (type.isTop) continue;
if (type.name.startsWith('_')) continue;
if (type.name.endsWith('Exception')) {
exceptions.add(type);
} else {
types.add(type);
}
}
if ((types.length == 0) && (exceptions.length == 0)) return;
writeType(String icon, Type type) {
write('<li>');
if (_currentType == type) {
write(
'<div class="icon-$icon"></div><strong>${typeName(type)}</strong>');
} else {
write(a(typeUrl(type),
'<div class="icon-$icon"></div>${typeName(type)}'));
}
writeln('</li>');
}
writeln('<ul>');
types.forEach((type) => writeType(type.isClass ? 'class' : 'interface',
type));
exceptions.forEach((type) => writeType('exception', type));
writeln('</ul>');
}
/** Stores the navigation for the types contained by the given library. */
docSearchNavigation() {
assert(enableSearch == true);
var map = {};
for (var library in orderByName(world.libraries)) {
map[library.name] = library;
}
for (final library in orderByName(map)) {
// Show the exception types separately.
final types = <Type>[];
final exceptions = <Type>[];
// Add search navigation entry for libraries
search.addNav([libraryUrl(library), 'library', library.name]);
for (final type in orderByName(library.types)) {
if (type.isTop) continue;
if (type.name.startsWith('_')) continue;
if (type.name.endsWith('Exception')) {
exceptions.add(type);
} else {
types.add(type);
}
}
if ((types.length == 0) && (exceptions.length == 0)) return;
writeType(String icon, Type type) {
search.addNav([typeUrl(type), icon, typeName(type)]);
}
types.forEach((type) => writeType(type.isClass ? 'class' : 'interface',
type));
exceptions.forEach((type) => writeType('exception', type));
}
}
docLibrary(Library library) {
_totalLibraries++;
_currentLibrary = library;
_currentType = null;
startFile(libraryUrl(library));
writeHeader(library.name, [library.name, libraryUrl(library)]);
writeln('<h2>Library <strong>${library.name}</strong></h2>');
// Look for a comment for the entire library.
final comment = _comments.findLibrary(library.baseSource);
if (comment != null) {
final html = md.markdownToHtml(comment);
writeln('<div class="doc">$html</div>');
}
// Document the top-level members.
docMembers(library.topType);
// Document the types.
final classes = <Type>[];
final interfaces = <Type>[];
final exceptions = <Type>[];
for (final type in orderByName(library.types)) {
if (type.isTop) continue;
if (type.name.startsWith('_')) continue;
if (type.name.endsWith('Exception')) {
exceptions.add(type);
} else if (type.isClass) {
classes.add(type);
} else {
interfaces.add(type);
}
}
docTypes(classes, 'Classes');
docTypes(interfaces, 'Interfaces');
docTypes(exceptions, 'Exceptions');
writeFooter();
endFile();
for (final type in library.types.getValues()) {
if (!type.isTop) docType(type);
}
}
docTypes(List<Type> types, String header) {
if (types.length == 0) return;
writeln('<div>');
writeln('<h3>$header</h3>');
for (final type in types) {
writeln(
'''
<div class="type">
<h4>
${a(typeUrl(type), "<strong>${typeName(type)}</strong>")}
</h4>
</div>
''');
}
writeln('</div>');
}
docType(Type type) {
_totalTypes++;
_currentType = type;
startFile(typeUrl(type));
final typeTitle =
'${type.isClass ? "Class" : "Interface"} ${typeName(type)}';
writeHeader('Library ${type.library.name} / $typeTitle',
[type.library.name, libraryUrl(type.library),
typeName(type), typeUrl(type)]);
writeln(
'''
<h2>${type.isClass ? "Class" : "Interface"}
<strong>${typeName(type, showBounds: true)}</strong></h2>
''');
docInheritance(type);
docCode(type.span, getTypeComment(type));
docConstructors(type);
docMembers(type);
writeFooter();
endFile();
}
/** Document the superclass, superinterfaces and default class of [Type]. */
docInheritance(Type type) {
final isSubclass = (type.parent != null) && !type.parent.isObject;
Type defaultType;
if (type.definition is TypeDefinition) {
TypeDefinition definition = type.definition;
if (definition.defaultType != null) {
defaultType = definition.defaultType.type;
}
}
if (isSubclass ||
(type.interfaces != null && type.interfaces.length > 0) ||
(defaultType != null)) {
writeln('<p>');
if (isSubclass) {
write('Extends ${typeReference(type.parent)}. ');
}
if (type.interfaces != null && type.interfaces.length > 0) {
var interfaceStr = joinWithCommas(map(type.interfaces, typeReference));
write('Implements ${interfaceStr}. ');
}
if (defaultType != null) {
write('Has default class ${typeReference(defaultType)}.');
}
}
}
/** Document the constructors for [Type], if any. */
docConstructors(Type type) {
final names = type.constructors.getKeys().filter(
(name) => !name.startsWith('_'));
if (names.length > 0) {
writeln('<div>');
writeln('<h3>Constructors</h3>');
names.sort((x, y) => x.toUpperCase().compareTo(y.toUpperCase()));
for (final name in names) {
docMethod(type, type.constructors[name], constructorName: name);
}
writeln('</div>');
}
}
void docMembers(Type type) {
// Collect the different kinds of members.
final staticMethods = [];
final staticFields = [];
final instanceMethods = [];
final instanceFields = [];
for (final member in orderByName(type.members)) {
if (member.name.startsWith('_')) continue;
final methods = member.isStatic ? staticMethods : instanceMethods;
final fields = member.isStatic ? staticFields : instanceFields;
if (member.isProperty) {
if (member.canGet) methods.add(member.getter);
if (member.canSet) methods.add(member.setter);
} else if (member.isMethod) {
methods.add(member);
} else if (member.isField) {
fields.add(member);
}
}
if (staticMethods.length > 0) {
final title = type.isTop ? 'Functions' : 'Static Methods';
writeln('<div>');
writeln('<h3>$title</h3>');
for (final method in staticMethods) docMethod(type, method);
writeln('</div>');
}
if (staticFields.length > 0) {
final title = type.isTop ? 'Variables' : 'Static Fields';
writeln('<div>');
writeln('<h3>$title</h3>');
for (final field in staticFields) docField(type, field);
writeln('</div>');
}
if (instanceMethods.length > 0) {
writeln('<div>');
writeln('<h3>Methods</h3>');
for (final method in instanceMethods) docMethod(type, method);
writeln('</div>');
}
if (instanceFields.length > 0) {
writeln('<div>');
writeln('<h3>Fields</h3>');
for (final field in instanceFields) docField(type, field);
writeln('</div>');
}
}
/**
* Documents the [method] in type [type]. Handles all kinds of methods
* including getters, setters, and constructors.
*/
docMethod(Type type, MethodMember method, [String constructorName = null]) {
_totalMembers++;
_currentMember = method;
writeln('<div class="method"><h4 id="${memberAnchor(method)}">');
if (includeSource) {
writeln('<span class="show-code">Code</span>');
}
if (method.isConstructor) {
write(method.isConst ? 'const ' : 'new ');
}
if (constructorName == null) {
annotateType(type, method.returnType);
}
// Translate specially-named methods: getters, setters, operators.
var name = method.name;
if (name.startsWith('get:')) {
// Getter.
name = 'get ${name.substring(4)}';
} else if (name.startsWith('set:')) {
// Setter.
name = 'set ${name.substring(4)}';
} else if (name == ':negate') {
// Dart uses 'negate' for prefix negate operators, not '!'.
name = 'operator negate';
} else {
// See if it's an operator.
name = TokenKind.rawOperatorFromMethod(name);
if (name == null) {
name = method.name;
} else {
name = 'operator $name';
}
}
write('<strong>$name</strong>');
// Named constructors.
if (constructorName != null && constructorName != '') {
write('.');
write(constructorName);
}
docParamList(type, method);
// Add serch term entries.
if (enableSearch == true) {
if (typeName(type) == null) {
search.addTerm(memberAnchor(method), [libraryUrl(type.library),
memberAnchor(method)]);
} else {
search.addTerm(memberAnchor(method), [typeUrl(type),
memberAnchor(method)]);
}
}
write(''' <a class="anchor-link" href="#${memberAnchor(method)}"
title="Permalink to ${typeName(type)}.$name">#</a>''');
writeln('</h4>');
docCode(method.span, getMethodComment(method), showCode: true);
writeln('</div>');
}
/** Documents the field [field] of type [type]. */
docField(Type type, FieldMember field) {
_totalMembers++;
_currentMember = field;
writeln('<div class="field"><h4 id="${memberAnchor(field)}">');
if (includeSource) {
writeln('<span class="show-code">Code</span>');
}
if (field.isFinal) {
write('final ');
} else if (field.type.name == 'Dynamic') {
write('var ');
}
annotateType(type, field.type);
// Add serch term entries.
if (enableSearch == true) {
if (typeName(type) == null) {
search.addTerm(memberAnchor(field), [libraryUrl(type.library),
memberAnchor(field)]);
} else {
search.addTerm(memberAnchor(field), [typeUrl(type),
memberAnchor(field)]);
}
}
write(
'''
<strong>${field.name}</strong> <a class="anchor-link"
href="#${memberAnchor(field)}"
title="Permalink to ${typeName(type)}.${field.name}">#</a>
</h4>
''');
docCode(field.span, getFieldComment(field), showCode: true);
writeln('</div>');
}
docParamList(Type enclosingType, MethodMember member) {
write('(');
bool first = true;
bool inOptionals = false;
for (final parameter in member.parameters) {
if (!first) write(', ');
if (!inOptionals && parameter.isOptional) {
write('[');
inOptionals = true;
}
annotateType(enclosingType, parameter.type, parameter.name);
// Show the default value for named optional parameters.
if (parameter.isOptional && parameter.hasDefaultValue) {
write(' = ');
// TODO(rnystrom): Using the definition text here is a bit cheap.
// We really should be pretty-printing the AST so that if you have:
// foo([arg = 1 + /* comment */ 2])
// the docs should just show:
// foo([arg = 1 + 2])
// For now, we'll assume you don't do that.
write(parameter.definition.value.span.text);
}
first = false;
}
if (inOptionals) write(']');
write(')');
}
/**
* Documents the code contained within [span] with [comment]. If [showCode]
* is `true` (and [includeSource] is set), also includes the source code.
*/
docCode(SourceSpan span, String comment, [bool showCode = false]) {
writeln('<div class="doc">');
if (comment != null) {
writeln(md.markdownToHtml(comment));
}
if (includeSource && showCode) {
writeln('<pre class="source">');
writeln(md.escapeHtml(unindentCode(span)));
writeln('</pre>');
}
writeln('</div>');
}
/** Get the doc comment associated with the given type. */
String getTypeComment(Type type) => _comments.find(type.span);
/** Get the doc comment associated with the given method. */
String getMethodComment(MethodMember method) => _comments.find(method.span);
/** Get the doc comment associated with the given field. */
String getFieldComment(FieldMember field) => _comments.find(field.span);
/**
* Creates a hyperlink. Handles turning the [href] into an appropriate
* relative path from the current file.
*/
String a(String href, String contents, [String css]) {
final cssClass = css == null ? '' : ' class="$css"';
return '<a href="${relativePath(href)}"$cssClass>$contents</a>';
}
/**
* Writes a type annotation for the given type and (optional) parameter name.
*/
annotateType(Type enclosingType, Type type, [String paramName = null]) {
// Don't bother explicitly displaying Dynamic.
if (type.isVar) {
if (paramName !== null) write(paramName);
return;
}
// For parameters, handle non-typedefed function types.
if (paramName !== null) {
final call = type.getCallMethod();
if (call != null) {
annotateType(enclosingType, call.returnType);
write(paramName);
docParamList(enclosingType, call);
return;
}
}
linkToType(enclosingType, type);
write(' ');
if (paramName !== null) write(paramName);
}
/** Writes a link to a human-friendly string representation for a type. */
linkToType(Type enclosingType, Type type) {
if (type is ParameterType) {
// If we're using a type parameter within the body of a generic class then
// just link back up to the class.
write(a(typeUrl(enclosingType), type.name));
return;
}
// Link to the type.
// Use .genericType to avoid writing the <...> here.
write(a(typeUrl(type), type.genericType.name));
// See if it's a generic type.
if (type.isGeneric) {
// TODO(rnystrom): This relies on a weird corner case of frog. Currently,
// the only time we get into this case is when we have a "raw" generic
// that's been instantiated with Dynamic for all type arguments. It's kind
// of strange that frog works that way, but we take advantage of it to
// show raw types without any type arguments.
return;
}
// See if it's an instantiation of a generic type.
final typeArgs = type.typeArgsInOrder;
if (typeArgs != null) {
write('<');
bool first = true;
for (final arg in typeArgs) {
if (!first) write(', ');
first = false;
linkToType(enclosingType, arg);
}
write('>');
}
}
/** Creates a linked cross reference to [type]. */
typeReference(Type type) {
// TODO(rnystrom): Do we need to handle ParameterTypes here like
// annotation() does?
return a(typeUrl(type), typeName(type), css: 'crossref');
}
/** Generates a human-friendly string representation for a type. */
typeName(Type type, [bool showBounds = false]) {
// See if it's a generic type.
if (type.isGeneric) {
final typeParams = [];
for (final typeParam in type.genericType.typeParameters) {
if (showBounds &&
(typeParam.extendsType != null) &&
!typeParam.extendsType.isObject) {
final bound = typeName(typeParam.extendsType, showBounds: true);
typeParams.add('${typeParam.name} extends $bound');
} else {
typeParams.add(typeParam.name);
}
}
final params = Strings.join(typeParams, ', ');
return '${type.name}<$params>';
}
// See if it's an instantiation of a generic type.
final typeArgs = type.typeArgsInOrder;
if (typeArgs != null) {
final args = Strings.join(map(typeArgs, (arg) => typeName(arg)), ', ');
return '${type.genericType.name}<$args>';
}
// Regular type.
return type.name;
}
/**
* Remove leading indentation to line up with first line.
*/
unindentCode(SourceSpan span) {
final column = getSpanColumn(span);
final lines = span.text.split('\n');
// TODO(rnystrom): Dirty hack.
for (final i = 1; i < lines.length; i++) {
lines[i] = unindent(lines[i], column);
}
final code = Strings.join(lines, '\n');
return code;