-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Docs.jl
690 lines (555 loc) · 17.3 KB
/
Docs.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
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
# This file is a part of Julia. License is MIT: http://julialang.org/license
module Docs
import Base.Markdown: @doc_str, MD
export doc
# Basic API / Storage
const modules = Module[]
const META′ = gensym("META")
@eval meta(mod) = mod.$META′
meta() = meta(current_module())
macro init()
META = esc(META′)
quote
if !isdefined($(Expr(:quote, META′)))
const $META = ObjectIdDict()
doc!($META, @doc_str $("Documentation metadata for `$(current_module())`."))
push!(modules, current_module())
nothing
end
end
end
function doc!(obj, data)
meta()[obj] = data
end
function doc(obj)
for mod in modules
haskey(meta(mod), obj) && return meta(mod)[obj]
end
end
# Function / Method support
function newmethod(defs)
keylen = -1
key = nothing
for def in defs
length(def.sig.parameters) > keylen && (keylen = length(def.sig.parameters); key = def)
end
return key
end
function newmethod(funcs, f)
applicable = Method[]
for def in methods(f)
(!haskey(funcs, def) || funcs[def] != def.func) && push!(applicable, def)
end
return newmethod(applicable)
end
def_dict(f) = [def => def.func for def in methods(f)]
function trackmethod(def)
name = uncurly(unblock(def).args[1].args[1])
f = esc(name)
quote
funcs = nothing
if $(isexpr(name, Symbol)) && isdefined($(Expr(:quote, name))) && isgeneric($f)
funcs = def_dict($f)
end
$(esc(def))
if funcs !== nothing
$f, newmethod(funcs, $f)
else
$f, newmethod(methods($f))
end
end
end
type FuncDoc
main
order::Vector{Method}
meta::ObjectIdDict
source::ObjectIdDict
end
FuncDoc() = FuncDoc(nothing, [], ObjectIdDict(), ObjectIdDict())
function doc!(f::Function, data)
fd = get!(meta(), f, FuncDoc())
fd.main = data
end
function doc!(f::Function, m::Method, data, source)
fd = get!(meta(), f, FuncDoc())
isa(fd, FuncDoc) || error("Can't document a method when the function already has metadata")
!haskey(fd.meta, m) && push!(fd.order, m)
fd.meta[m] = data
fd.source[m] = source
end
function doc(f::Function)
docs = []
for mod in modules
if haskey(meta(mod), f)
fd = meta(mod)[f]
length(docs) == 0 && fd.main != nothing && push!(docs, fd.main)
if isa(fd, FuncDoc)
for m in fd.order
push!(docs, fd.meta[m])
end
elseif length(docs) == 0
return fd
end
end
end
return catdoc(docs...)
end
function doc(f::Function, m::Method)
for mod in modules
haskey(meta(mod), f) && isa(meta(mod)[f], FuncDoc) && haskey(meta(mod)[f].meta, m) &&
return meta(mod)[f].meta[m]
end
end
catdoc() = nothing
catdoc(xs...) = vcat(xs...)
# Type Documentation
isdoc(x) = isexpr(x, :string, AbstractString) ||
(isexpr(x, :macrocall) && endswith(string(x.args[1]), "_str"))
dict_expr(d) = :(Dict($([:($(Expr(:quote, f)) => $d) for (f, d) in d]...)))
function field_meta(def)
meta = Dict()
doc = nothing
for l in def.args[3].args
if isdoc(l)
doc = mdify(l)
elseif doc != nothing && isexpr(l, Symbol, :(::))
meta[namify(l)] = doc
doc = nothing
end
end
return dict_expr(meta)
end
type TypeDoc
main
fields::Dict{Symbol, Any}
order::Vector{Method}
meta::ObjectIdDict
end
TypeDoc() = TypeDoc(nothing, Dict(), [], ObjectIdDict())
function doc!(t::DataType, data, fields)
td = get!(meta(), t, TypeDoc())
td.main = data
td.fields = fields
end
function doc!(f::DataType, m::Method, data, source)
td = get!(meta(), f, TypeDoc())
isa(td, TypeDoc) || error("Can't document a method when the type already has metadata")
!haskey(td.meta, m) && push!(td.order, m)
td.meta[m] = data
end
function doc(f::DataType)
docs = []
for mod in modules
if haskey(meta(mod), f)
fd = meta(mod)[f]
if isa(fd, TypeDoc)
length(docs) == 0 && fd.main != nothing && push!(docs, fd.main)
for m in fd.order
push!(docs, fd.meta[m])
end
elseif length(docs) == 0
return fd
end
end
end
return catdoc(docs...)
end
isfield(x) = isexpr(x, :.) &&
(isexpr(x.args[1], Symbol) || isfield(x.args[1])) &&
isexpr(x.args[2], QuoteNode, :quote)
function fielddoc(T, k)
for mod in modules
if haskey(meta(mod), T) && isa(meta(mod)[T], TypeDoc) && haskey(meta(mod)[T].fields, k)
return meta(mod)[T].fields[k]
end
end
Text(sprint(io -> (print(io, "$T has fields: ");
print_joined(io, fieldnames(T), ", ", " and "))))
end
# Generic Callables
doc(f, ::Method) = doc(f)
# Modules
function doc(m::Module)
md = invoke(doc, Tuple{Any}, m)
md == nothing || return md
readme = Pkg.dir(string(m), "README.md")
if isfile(readme)
return Markdown.parse_file(readme)
end
end
# Keywords
const keywords = Dict{Symbol,Any}()
# Usage macros
isexpr(x::Expr) = true
isexpr(x) = false
isexpr(x::Expr, ts...) = x.head in ts
isexpr(x, ts...) = any(T->isa(T, Type) && isa(x, T), ts)
function unblock(ex)
isexpr(ex, :block) || return ex
exs = filter(ex->!isexpr(ex, :line), ex.args)
length(exs) == 1 || return ex
# Recursive unblock'ing for macro expansion
return unblock(exs[1])
end
uncurly(ex) = isexpr(ex, :curly) ? ex.args[1] : ex
namify(ex::Expr) = isexpr(ex, :.) ? ex : namify(ex.args[1])
namify(ex::QuoteNode) = ex.value
namify(sy::Symbol) = sy
function mdify(ex)
if isexpr(ex, AbstractString, :string)
:(Markdown.parse($(esc(ex))))
else
esc(ex)
end
end
function namedoc(meta, def, name)
quote
@init
$(esc(def))
doc!($(esc(name)), $(mdify(meta)))
nothing
end
end
function funcdoc(meta, def)
quote
@init
f, m = $(trackmethod(def))
doc!(f, m, $(mdify(meta)), $(esc(Expr(:quote, def))))
f
end
end
function typedoc(meta, def, name)
quote
@init
$(esc(def))
doc!($(esc(name)), $(mdify(meta)), $(field_meta(unblock(def))))
nothing
end
end
function objdoc(meta, def)
quote
@init
f = $(esc(def))
doc!(f, $(mdify(meta)))
f
end
end
fexpr(ex) = isexpr(ex, :function, :(=)) && isexpr(ex.args[1], :call)
function docm(meta, def)
# Quote, Unblock and Macroexpand
# * Always do macro expansion unless it's a quote (for consistency)
# * Unblock before checking for Expr(:quote) to support `->` syntax
# * Unblock after macro expansion to recognize structures of
# the generated AST
def′ = unblock(def)
if !isexpr(def′, :quote)
def = macroexpand(def)
def′ = unblock(def)
elseif length(def′.args) == 1 && isexpr(def′.args[1], :macrocall)
# Special case for documenting macros after definition with
# `@doc "<doc string>" :@macro` or
# `@doc "<doc string>" :(str_macro"")` syntax.
#
# Allow more general macrocall for now unless it causes confusion.
return objdoc(meta, namify(def′.args[1]))
end
isexpr(def′, :macro) && return namedoc(meta, def, symbol("@", namify(def′)))
isexpr(def′, :type) && return typedoc(meta, def, namify(def′.args[2]))
isexpr(def′, :bitstype) && return namedoc(meta, def, def′.args[2])
isexpr(def′, :abstract) && return namedoc(meta, def, namify(def′))
isexpr(def′, :module) && return namedoc(meta, def, def′.args[2])
fexpr(def′) && return funcdoc(meta, def)
return objdoc(meta, def)
end
function docm(ex)
isa(ex,Symbol) && haskey(keywords, ex) && return keywords[ex]
isexpr(ex, :->) && return docm(ex.args...)
isexpr(ex, :call) && return :(doc($(esc(ex.args[1])), @which $(esc(ex))))
isexpr(ex, :macrocall) && (ex = namify(ex))
:(doc($(esc(ex))))
end
# Not actually used; bootstrap version in bootstrap.jl
macro doc(args...)
docm(args...)
end
# Swap out the bootstrap macro with the real one
Base.DocBootstrap.setexpand!(docm)
# Names are resolved relative to the DocBootstrap module, so
# inject the ones we need there.
eval(Base.DocBootstrap,
:(import ..Docs: @init, doc!, doc, newmethod, def_dict, @doc_str))
# Metametadata
"""
The Docs module provides the `@doc` macro which can be used
to set and retreive documentation metadata for Julia objects.
Please see docs for the `@doc` macro for more info.
"""
Docs
"""
# Documentation
Functions, methods and types can be documented by placing a string before the
definition:
\"""
# The Foo Function
`foo(x)`: Foo the living hell out of `x`.
\"""
foo(x) = ...
The `@doc` macro can be used directly to both set and retrieve documentation /
metadata. By default, documentation is written as Markdown, but any object can
be placed before the arrow. For example:
@doc "blah" ->
function foo() ...
The `->` is not required if the object is on the same line, e.g.
@doc "foo" foo
# Documenting objects after they are defined
You can document an object after its definition by
@doc "foo" function_to_doc
@doc "bar" TypeToDoc
For functions, this currently only support documenting the whole function
Instead of a specific method. See Functions & Methods section below
For macros, the syntax is `@doc "macro doc" :(@Module.macro)` or
`@doc "macro doc" :(string_macro"")` for string macros. Without the quote `:()`
the expansion of the macro will be documented.
# Retrieving Documentation
You can retrieve docs for functions, macros and other objects as
follows:
@doc foo
@doc @time
@doc md""
# Functions & Methods
Placing documentation before a method definition (e.g. `function foo()
...` or `foo() = ...`) will cause that specific method to be
documented, as opposed to the whole function. Method docs are
concatenated together in the order they were defined to provide docs
for the function.
"""
:@Base.DocBootstrap.doc
"`doc(obj)`: Get the doc metadata for `obj`."
doc
"""
`catdoc(xs...)`: Combine the documentation metadata `xs` into a single meta
object.
"""
catdoc
# Text / HTML objects
import Base: print, writemime
export HTML, @html_str
export HTML, Text
"""
`HTML(s)`: Create an object that renders `s` as html.
HTML("<div>foo</div>")
You can also use a stream for large amounts of data:
HTML() do io
println(io, "<div>foo</div>")
end
"""
type HTML{T}
content::T
end
function HTML(xs...)
HTML() do io
for x in xs
writemime(io, MIME"text/html"(), x)
end
end
end
writemime(io::IO, ::MIME"text/html", h::HTML) = print(io, h.content)
writemime(io::IO, ::MIME"text/html", h::HTML{Function}) = h.content(io)
"Create an `HTML` object from a literal string."
macro html_str(s)
:(HTML($s))
end
function catdoc(xs::HTML...)
HTML() do io
for x in xs
writemime(io, MIME"text/html"(), x)
end
end
end
export Text, @text_str
"""
`Text(s)`: Create an object that renders `s` as plain text.
Text("foo")
You can also use a stream for large amounts of data:
Text() do io
println(io, "foo")
end
"""
type Text{T}
content::T
end
print(io::IO, t::Text) = print(io, t.content)
print(io::IO, t::Text{Function}) = t.content(io)
writemime(io::IO, ::MIME"text/plain", t::Text) = print(io, t)
@doc "Create a `Text` object from a literal string." ->
macro text_str(s)
:(Text($s))
end
function catdoc(xs::Text...)
Text() do io
for x in xs
writemime(io, MIME"text/plain"(), x)
end
end
end
# MD support
catdoc(md::MD...) = MD(md...)
# REPL help
function repl_search(io::IO, s)
pre = "search:"
print(io, pre)
printmatches(io, s, completions(s), cols=Base.tty_size()[2]-length(pre))
println(io, "\n")
end
repl_search(s) = repl_search(STDOUT, s)
function repl_corrections(io::IO, s)
print(io, "Couldn't find ")
Markdown.with_output_format(:cyan, io) do io
println(io, s)
end
print_correction(io, s)
end
repl_corrections(s) = repl_corrections(STDOUT, s)
macro repl(ex)
quote
# Fuzzy Searching
$(isexpr(ex, Symbol)) && repl_search($(string(ex)))
if $(isa(ex, Symbol)) &&
!(isdefined($(current_module()), $(Expr(:quote, ex))) ||
haskey(keywords, $(Expr(:quote, ex))))
repl_corrections($(string(ex)))
else
if $(isfield(ex) ? :(isa($(esc(ex.args[1])), DataType)) : false)
$(isfield(ex) ? :(fielddoc($(esc(ex.args[1])), $(ex.args[2]))) : nothing)
else
# Backwards-compatible with the previous help system, for now
let doc = @doc $(esc(ex))
doc ≠ nothing ? doc : Base.Help.@help_ $(esc(ex))
end
end
end
end
end
# Search & Rescue
# Utilities for correcting user mistakes and (eventually)
# doing full documentation searches from the repl.
# Fuzzy Search Algorithm
function matchinds(needle, haystack; acronym = false)
chars = collect(needle)
is = Int[]
lastc = '\0'
for (i, char) in enumerate(haystack)
isempty(chars) && break
while chars[1] == ' ' shift!(chars) end # skip spaces
if lowercase(char) == lowercase(chars[1]) && (!acronym || !isalpha(lastc))
push!(is, i)
shift!(chars)
end
lastc = char
end
return is
end
longer(x, y) = length(x) ≥ length(y) ? (x, true) : (y, false)
bestmatch(needle, haystack) =
longer(matchinds(needle, haystack, acronym = true),
matchinds(needle, haystack))
avgdistance(xs) =
isempty(xs) ? 0 :
(xs[end] - xs[1] - length(xs)+1)/length(xs)
function fuzzyscore(needle, haystack)
score = 0.
is, acro = bestmatch(needle, haystack)
score += (acro?2:1)*length(is) # Matched characters
score -= 2(length(needle)-length(is)) # Missing characters
!acro && (score -= avgdistance(is)/10) # Contiguous
!isempty(is) && (score -= mean(is)/100) # Closer to beginning
return score
end
function fuzzysort(search, candidates)
scores = map(cand -> (fuzzyscore(search, cand), -levenshtein(search, cand)), candidates)
candidates[sortperm(scores)] |> reverse
end
# Levenshtein Distance
function levenshtein(s1, s2)
a, b = collect(s1), collect(s2)
m = length(a)
n = length(b)
d = Array(Int, m+1, n+1)
d[1:m+1, 1] = 0:m
d[1, 1:n+1] = 0:n
for i = 1:m, j = 1:n
d[i+1,j+1] = min(d[i , j+1] + 1,
d[i+1, j ] + 1,
d[i , j ] + (a[i] != b[j]))
end
return d[m+1, n+1]
end
function levsort(search, candidates)
scores = map(cand -> (levenshtein(search, cand), -fuzzyscore(search, cand)), candidates)
candidates = candidates[sortperm(scores)]
i = 0
for i = 1:length(candidates)
levenshtein(search, candidates[i]) > 3 && break
end
return candidates[1:i]
end
# Result printing
function printmatch(io::IO, word, match)
is, _ = bestmatch(word, match)
Markdown.with_output_format(:fade, io) do io
for (i, char) = enumerate(match)
if i in is
Markdown.with_output_format(print, :bold, io, char)
else
print(io, char)
end
end
end
end
printmatch(args...) = printfuzzy(STDOUT, args...)
function printmatches(io::IO, word, matches; cols = Base.tty_size()[2])
total = 0
for match in matches
total + length(match) + 1 > cols && break
fuzzyscore(word, match) < 0 && break
print(io, " ")
printmatch(io, word, match)
total += length(match) + 1
end
end
printmatches(args...; cols = Base.tty_size()[2]) = printmatches(STDOUT, args..., cols = cols)
function print_joined_cols(io::IO, ss, delim = "", last = delim; cols = Base.tty_size()[2])
i = 0
total = 0
for i = 1:length(ss)
total += length(ss[i])
total + max(i-2,0)*length(delim) + (i>1?1:0)*length(last) > cols && (i-=1; break)
end
print_joined(io, ss[1:i], delim, last)
end
print_joined_cols(args...; cols = Base.tty_size()[2]) = print_joined_cols(STDOUT, args...; cols=cols)
function print_correction(io, word)
cors = levsort(word, accessible(current_module()))
pre = "Perhaps you meant "
print(io, pre)
print_joined_cols(io, cors, ", ", " or "; cols = Base.tty_size()[2]-length(pre))
println(io)
return
end
print_correction(word) = print_correction(STDOUT, word)
# Completion data
const builtins = ["abstract", "baremodule", "begin", "bitstype", "break",
"catch", "ccall", "const", "continue", "do", "else",
"elseif", "end", "export", "finally", "for", "function",
"global", "if", "immutable", "import", "importall", "let",
"local", "macro", "module", "quote", "return", "try", "type",
"typealias", "using", "while"]
moduleusings(mod) = ccall(:jl_module_usings, Any, (Any,), mod)
filtervalid(names) = filter(x->!ismatch(r"#", x), map(string, names))
accessible(mod::Module) =
[names(mod, true, true);
map(names, moduleusings(mod))...;
builtins] |> unique |> filtervalid
completions(name) = fuzzysort(name, accessible(current_module()))
completions(name::Symbol) = completions(string(name))
end