-
Notifications
You must be signed in to change notification settings - Fork 30
/
abbreviations.jl
613 lines (485 loc) · 14.9 KB
/
abbreviations.jl
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
#
# Abstract Interface.
#
"""
Abbreviation objects are used to automatically generate context-dependent markdown content
within documentation strings. Objects of this type interpolated into docstrings will be
expanded automatically before parsing the text to markdown.
$(:FIELDS)
"""
abstract type Abbreviation end
"""
$(:SIGNATURES)
Expand the [`Abbreviation`](@ref) `abbr` in the context of the `DocStr` `doc` and write
the resulting markdown-formatted text to the `IOBuffer` `buf`.
"""
format(abbr, buf, doc) = error("`format` not implemented for `$typeof(abbr)`.")
# Only extend `formatdoc` once with our abstract type. Within the package use a different
# `format` function instead to keep things decoupled from `Base` as much as possible.
Docs.formatdoc(buf::IOBuffer, doc::Docs.DocStr, part::Abbreviation) = format(part, buf, doc)
#
# Implementations.
#
#
# `TypeFields`
#
"""
The type for [`FIELDS`](@ref) abbreviations.
$(:FIELDS)
"""
struct TypeFields <: Abbreviation
types::Bool
end
"""
An [`Abbreviation`](@ref) to include the names of the fields of a type as well as any
documentation that may be attached to the fields.
# Examples
The generated markdown text should look similar to to following example where a
type has three fields (`x`, `y`, and `z`) and the last two have documentation
attached.
```markdown
- `x`
- `y`
Unlike the `x` field this field has been documented.
- `z`
Another documented field.
```
"""
const FIELDS = TypeFields(false)
"""
Identical to [`FIELDS`](@ref) except that it includes the field types.
# Examples
The generated markdown text should look similar to to following example where
a type has three fields; `x` of type `String`, `y` of type `Int`, and `z` of
type `Vector{Any}`.
```markdown
- `x::String`
- `y::Int`
Unlike the `x` field this field has been documented.
- `z::Array{Any, 1}`
Another documented field.
```
"""
const TYPEDFIELDS = TypeFields(true)
function format(abbrv::TypeFields, buf, doc)
local docs = get(doc.data, :fields, Dict())
local binding = doc.data[:binding]
local object = Docs.resolve(binding)
# On 0.7 fieldnames() on an abstract type throws an error. We then explicitly return
# an empty vector to be consistent with the behaviour on v0.6.
local fields = isabstracttype(object) ? Symbol[] : fieldnames(object)
if !isempty(fields)
println(buf)
for field in fields
if abbrv.types
println(buf, " - `", field, "::", fieldtype(object, field), "`")
else
println(buf, " - `", field, "`")
end
# Print the field docs if they exist and aren't a `doc"..."` docstring.
if haskey(docs, field) && isa(docs[field], AbstractString)
println(buf)
for line in split(docs[field], "\n")
println(buf, isempty(line) ? "" : " ", rstrip(line))
end
end
println(buf)
end
println(buf)
end
return nothing
end
#
# `ModuleExports`
#
"""
The singleton type for [`EXPORTS`](@ref) abbreviations.
$(:FIELDS)
"""
struct ModuleExports <: Abbreviation end
"""
An [`Abbreviation`](@ref) to include all the exported names of a module is a sorted list of
`Documenter.jl`-style `@ref` links.
!!! note
The names are sorted alphabetically and ignore leading `@` characters so that macros are
*not* sorted before other names.
# Examples
The markdown text generated by the `EXPORTS` abbreviation looks similar to the following:
```markdown
- [`bar`](@ref)
- [`@baz`](@ref)
- [`foo`](@ref)
```
"""
const EXPORTS = ModuleExports()
function format(::ModuleExports, buf, doc)
local binding = doc.data[:binding]
local object = Docs.resolve(binding)
local exports = names(object)
if !isempty(exports)
println(buf)
# Sorting ignores the `@` in macro names and sorts them in with others.
for sym in sort(exports, by = s -> lstrip(string(s), '@'))
# Skip the module itself, since that's always exported.
sym === nameof(object) && continue
# We print linked names using Documenter.jl cross-reference syntax
# for ease of integration with that package.
println(buf, " - [`", sym, "`](@ref)")
end
println(buf)
end
return nothing
end
#
# `ModuleImports`
#
"""
The singleton type for [`IMPORTS`](@ref) abbreviations.
$(:FIELDS)
"""
struct ModuleImports <: Abbreviation end
"""
An [`Abbreviation`](@ref) to include all the imported modules in a sorted list.
# Examples
The markdown text generated by the `IMPORTS` abbreviation looks similar to the following:
```markdown
- `Foo`
- `Bar`
- `Baz`
```
"""
const IMPORTS = ModuleImports()
function format(::ModuleImports, buf, doc)
local binding = doc.data[:binding]
local object = Docs.resolve(binding)
local imports = unique(ccall(:jl_module_usings, Any, (Any,), object))
if !isempty(imports)
println(buf)
for mod in sort(imports, by = string)
println(buf, " - `", mod, "`")
end
println(buf)
end
end
#
# `MethodList`
#
"""
The singleton type for [`METHODLIST`](@ref) abbreviations.
$(:FIELDS)
"""
struct MethodList <: Abbreviation end
"""
An [`Abbreviation`](@ref) for including a list of all the methods that match a documented
`Method`, `Function`, or `DataType` within the current module.
# Examples
The generated markdown text will look similar to the following example where a function
`f` defines two different methods (one that takes a number, and the other a string):
````markdown
```julia
f(num)
```
defined at [`<path>:<line>`](<github-url>).
```julia
f(str)
```
defined at [`<path>:<line>`](<github-url>).
````
"""
const METHODLIST = MethodList()
function format(::MethodList, buf, doc)
local binding = doc.data[:binding]
local typesig = doc.data[:typesig]
local modname = doc.data[:module]
local func = Docs.resolve(binding)
local groups = methodgroups(func, typesig, modname; exact = false)
if !isempty(groups)
println(buf)
for group in groups
println(buf, "```julia")
for method in group
printmethod(buf, binding, func, method)
println(buf)
end
println(buf, "```\n")
if !isempty(group)
local method = group[1]
local file = string(method.file)
local line = method.line
local path = cleanpath(file)
local URL = url(method)
isempty(URL) || println(buf, "defined at [`$path:$line`]($URL).")
end
println(buf)
end
println(buf)
end
return nothing
end
#
# `MethodSignatures`
#
"""
The singleton type for [`SIGNATURES`](@ref) abbreviations.
$(:FIELDS)
"""
struct MethodSignatures <: Abbreviation end
"""
An [`Abbreviation`](@ref) for including a simplified representation of all the method
signatures that match the given docstring. See [`printmethod`](@ref) for details on
the simplifications that are applied.
# Examples
The generated markdown text will look similar to the following example where a function `f`
defines method taking two positional arguments, `x` and `y`, and two keywords, `a` and the `b`.
````markdown
```julia
f(x, y; a, b...)
```
````
"""
const SIGNATURES = MethodSignatures()
function format(::MethodSignatures, buf, doc)
local binding = doc.data[:binding]
local typesig = doc.data[:typesig]
local modname = doc.data[:module]
local func = Docs.resolve(binding)
local groups = methodgroups(func, typesig, modname)
if !isempty(groups)
println(buf)
println(buf, "```julia")
for group in groups
for method in group
printmethod(buf, binding, func, method)
println(buf)
end
end
println(buf, "\n```\n")
end
end
#
# `TypedMethodSignatures`
#
"""
The singleton type for [`TYPEDSIGNATURES`](@ref) abbreviations.
$(:FIELDS)
"""
struct TypedMethodSignatures <: Abbreviation end
"""
An [`Abbreviation`](@ref) for including a simplified representation of all the method
signatures with types that match the given docstring. See [`printmethod`](@ref) for details on
the simplifications that are applied.
# Examples
The generated markdown text will look similar to the following example where a function `f`
defines method taking two positional arguments, `x` and `y`, and two keywords, `a` and the `b`.
````markdown
```julia
f(x::Int, y::Int; a, b...)
```
````
"""
const TYPEDSIGNATURES = TypedMethodSignatures()
function format(::TypedMethodSignatures, buf, doc)
local binding = doc.data[:binding]
local typesig = doc.data[:typesig]
local modname = doc.data[:module]
local func = Docs.resolve(binding)
local groups = methodgroups(func, typesig, modname)
if !isempty(groups)
println(buf)
println(buf, "```julia")
for group in groups
if length(group) == 1
for method in group
printmethod(buf, binding, func, method, typesig)
println(buf)
end
else
for (i, method) in enumerate(group)
if i == length(group)
t = typesig
else
t = typesig.a
typesig = typesig.b
end
printmethod(buf, binding, func, method, t)
println(buf)
end
end
end
println(buf, "\n```\n")
end
end
#
# `FunctionName`
#
"""
The singleton type for [`FUNCTIONNAME`](@ref) abbreviations.
$(:FIELDS)
"""
struct FunctionName <: Abbreviation end
"""
An [`Abbreviation`](@ref) for including the function name matching the method of
the docstring.
# Usage
This is mostly useful for not repeating the function name in docstrings where
the user wants to retain full control of the argument list, or the latter does
not exist (eg generic functions).
Note that the generated docstring snippet is not quoted, use indentation or
explicit quoting.
# Example
```julia
\"""
\$(FUNCTIONNAME)(d, θ)
Calculate the logdensity `d` at `θ`.
Users should define their own methods for `$(FUNCTIONNAME)`.
\"""
function logdensity end
```
"""
const FUNCTIONNAME = FunctionName()
format(::FunctionName, buf, doc) = print(buf, doc.data[:binding].var)
#
# `TypeSignature`
#
"""
The singleton type for [`TYPEDEF`](@ref) abbreviations.
"""
struct TypeDefinition <: Abbreviation end
"""
An [`Abbreviation`](@ref) for including a summary of the signature of a type definition.
Some of the following information may be included in the output:
* whether the object is an `abstract` type or a `bitstype`;
* mutability (either `type` or `struct` is printed);
* the unqualified name of the type;
* any type parameters;
* the supertype of the type if it is not `Any`.
# Examples
The generated output for a type definition such as:
```julia
\"""
\$(TYPEDEF)
\"""
struct MyType{S, T <: Integer} <: AbstractArray
# ...
end
```
will look similar to the following:
````markdown
```julia
struct MyType{S, T<:Integer} <: AbstractArray
```
````
!!! note
No information about the fields of the type is printed. Use the [`FIELDS`](@ref)
abbreviation to include information about the fields of a type.
"""
const TYPEDEF = TypeDefinition()
function print_supertype(buf, object)
super = supertype(object)
super != Any && print(buf, " <: ", super)
end
function print_params(buf, object)
if !isempty(object.parameters)
print(buf, "{")
join(buf, object.parameters, ", ")
print(buf, "}")
end
end
function print_primitive_type(buf, object)
print(buf, "primitive type ", object.name.name)
print_supertype(buf, object)
print(buf, " ", sizeof(object) * 8)
println(buf)
end
function print_abstract_type(buf, object)
print(buf, "abstract type ", object.name.name)
print_supertype(buf, object)
println(buf)
end
function print_mutable_struct_or_struct(buf, object)
object.mutable && print(buf, "mutable ")
print(buf, "struct ", object.name.name)
print_params(buf, object)
print_supertype(buf, object)
println(buf)
end
@static if VERSION < v"0.7.0"
isprimitivetype(x) = isbitstype(x)
end
function format(::TypeDefinition, buf, doc)
local binding = doc.data[:binding]
local object = gettype(Docs.resolve(binding))
if isa(object, DataType)
println(buf, "\n```julia")
if isprimitivetype(object)
print_primitive_type(buf, object)
elseif isabstracttype(object)
print_abstract_type(buf, object)
else
print_mutable_struct_or_struct(buf, object)
end
println(buf, "```\n")
end
end
"""
The singleton type for [`README`](@ref) abbreviations.
"""
struct Readme <: Abbreviation end
"""
README
An [`Abbreviation`](@ref) for including the package README.md.
!!! note
The README.md file is interpreted as ["Julia flavored Markdown"]
(https://docs.julialang.org/en/v1/manual/documentation/#Markdown-syntax-1),
which has some differences compared to GitHub flavored markdown, and,
for example, [][] link shortcuts are not supported.
"""
const README = Readme()
"""
The singleton type for [`LICENSE`](@ref) abbreviations.
"""
struct License <: Abbreviation end
"""
LICENSE
An [`Abbreviation`](@ref) for including the package LICENSE.md.
!!! note
The LICENSE.md file is interpreted as ["Julia flavored Markdown"]
(https://docs.julialang.org/en/v1/manual/documentation/#Markdown-syntax-1),
which has some differences compared to GitHub flavored markdown, and,
for example, [][] link shortcuts are not supported.
"""
const LICENSE = License()
function format(::T, buf, doc) where T <: Union{Readme,License}
m = get(doc.data, :module, nothing)
m === nothing && return
path = pathof(m)
path === nothing && return
try # wrap in try/catch since we shouldn't error in case some IO operation goes wrong
r = T === Readme ? r"(?i)readme(?-i)" : r"(?i)license(?-i)"
# assume README/LICENSE is located in the root of the repo
root = normpath(joinpath(path, "..", ".."))
for file in readdir(root)
if occursin(r, file)
str = read(joinpath(root, file), String)
write(buf, str)
return
end
end
catch
end
end
#
# `DocStringTemplate`
#
"""
The singleton type for [`DOCSTRING`](@ref) abbreviations.
"""
struct DocStringTemplate <: Abbreviation end
"""
An [`Abbreviation`](@ref) used in [`@template`](@ref) definitions to represent the location
of the docstring body that should be spliced into a template.
!!! warning
This abbreviation must only ever be used in template strings; never normal docstrings.
"""
const DOCSTRING = DocStringTemplate()
# NOTE: no `format` needed for this 'mock' abbreviation.