• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / #37490

pending completion
#37490

push

local

web-flow
Update Allocs.jl (#49169)

For most applications the sample rate of 1/1000 is way too low. This will require manually setting a rate for production use, but IMO it's a lot better to make the default be taylored towards interactive/beginner use rather than deployment.

71810 of 82795 relevant lines covered (86.73%)

32016522.05 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

19.61
/stdlib/InteractiveUtils/src/InteractiveUtils.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
module InteractiveUtils
4

5
Base.Experimental.@optlevel 1
6

7
export apropos, edit, less, code_warntype, code_llvm, code_native, methodswith, varinfo,
8
    versioninfo, subtypes, supertypes, @which, @edit, @less, @functionloc, @code_warntype,
9
    @code_typed, @code_lowered, @code_llvm, @code_native, @time_imports, clipboard
10

11
import Base.Docs.apropos
12

13
using Base: unwrap_unionall, rewrap_unionall, isdeprecated, Bottom, show_unquoted, summarysize,
14
    signature_type, format_bytes
15

16
using Markdown
17

18
include("editless.jl")
19
include("codeview.jl")
20
include("macros.jl")
21
include("clipboard.jl")
22

23
"""
24
    varinfo(m::Module=Main, pattern::Regex=r""; all::Bool = false, imported::Bool = false, recursive::Bool = false, sortby::Symbol = :name, minsize::Int = 0)
25

26
Return a markdown table giving information about exported global variables in a module, optionally restricted
27
to those matching `pattern`.
28

29
The memory consumption estimate is an approximate lower bound on the size of the internal structure of the object.
30

31
- `all` : also list non-exported objects defined in the module, deprecated objects, and compiler-generated objects.
32
- `imported` : also list objects explicitly imported from other modules.
33
- `recursive` : recursively include objects in sub-modules, observing the same settings in each.
34
- `sortby` : the column to sort results by. Options are `:name` (default), `:size`, and `:summary`.
35
- `minsize` : only includes objects with size at least `minsize` bytes. Defaults to `0`.
36

37
The output of `varinfo` is intended for display purposes only.  See also [`names`](@ref) to get an array of symbols defined in
38
a module, which is suitable for more general manipulations.
39
"""
40
function varinfo(m::Module=Base.active_module(), pattern::Regex=r""; all::Bool = false, imported::Bool = false, sortby::Symbol = :name, recursive::Bool = false, minsize::Int=0)
×
41
    sortby in (:name, :size, :summary) || throw(ArgumentError("Unrecognized `sortby` value `:$sortby`. Possible options are `:name`, `:size`, and `:summary`"))
×
42
    rows = Vector{Any}[]
×
43
    workqueue = [(m, ""),]
×
44
    while !isempty(workqueue)
×
45
        m2, prep = popfirst!(workqueue)
×
46
        for v in names(m2; all, imported)
×
47
            if !isdefined(m2, v) || !occursin(pattern, string(v))
×
48
                continue
×
49
            end
50
            value = getfield(m2, v)
×
51
            isbuiltin = value === Base || value === Base.active_module() || value === Core
×
52
            if recursive && !isbuiltin && isa(value, Module) && value !== m2 && nameof(value) === v && parentmodule(value) === m2
×
53
                push!(workqueue, (value, "$prep$v."))
×
54
            end
55
            ssize_str, ssize = if isbuiltin
×
56
                    ("", typemax(Int))
×
57
                else
58
                    ss = summarysize(value)
×
59
                    (format_bytes(ss), ss)
×
60
                end
61
            if ssize >= minsize
×
62
                push!(rows, Any[string(prep, v), ssize_str, summary(value), ssize])
×
63
            end
64
        end
×
65
    end
×
66
    let (col, rev) = if sortby === :name
×
67
            1, false
×
68
        elseif sortby === :size
×
69
            4, true
×
70
        elseif sortby === :summary
×
71
            3, false
×
72
        else
73
            @assert "unreachable"
×
74
        end
75
        sort!(rows; by=r->r[col], rev)
×
76
    end
77
    pushfirst!(rows, Any["name", "size", "summary"])
×
78

79
    return Markdown.MD(Any[Markdown.Table(map(r->r[1:3], rows), Symbol[:l, :r, :l])])
×
80
end
81
varinfo(pat::Regex; kwargs...) = varinfo(Base.active_module(), pat; kwargs...)
×
82

83
"""
84
    versioninfo(io::IO=stdout; verbose::Bool=false)
85

86
Print information about the version of Julia in use. The output is
87
controlled with boolean keyword arguments:
88

89
- `verbose`: print all additional information
90

91
!!! warning "Warning"
92
    The output of this function may contain sensitive information. Before sharing the output,
93
    please review the output and remove any data that should not be shared publicly.
94

95
See also: [`VERSION`](@ref).
96
"""
97
function versioninfo(io::IO=stdout; verbose::Bool=false)
7✔
98
    println(io, "Julia Version $VERSION")
3✔
99
    if !isempty(Base.GIT_VERSION_INFO.commit_short)
3✔
100
        println(io, "Commit $(Base.GIT_VERSION_INFO.commit_short) ($(Base.GIT_VERSION_INFO.date_string))")
3✔
101
    end
102
    if Base.isdebugbuild()
3✔
103
        println(io, "DEBUG build")
×
104
    end
105
    println(io, "Platform Info:")
3✔
106
    println(io, "  OS: ", Sys.iswindows() ? "Windows" : Sys.isapple() ?
3✔
107
        "macOS" : Sys.KERNEL, " (", Sys.MACHINE, ")")
108

109
    if verbose
3✔
110
        lsb = ""
×
111
        if Sys.islinux()
×
112
            try lsb = readchomp(pipeline(`lsb_release -ds`, stderr=devnull)); catch; end
×
113
        end
114
        if Sys.iswindows()
×
115
            try lsb = strip(read(`$(ENV["COMSPEC"]) /c ver`, String)); catch; end
×
116
        end
117
        if !isempty(lsb)
×
118
            println(io, "      ", lsb)
×
119
        end
120
        if Sys.isunix()
×
121
            println(io, "  uname: ", readchomp(`uname -mprsv`))
×
122
        end
123
    end
124

125
    if verbose
3✔
126
        cpuio = IOBuffer() # print cpu_summary with correct alignment
×
127
        Sys.cpu_summary(cpuio)
×
128
        for (i, line) in enumerate(split(chomp(String(take!(cpuio))), "\n"))
×
129
            prefix = i == 1 ? "  CPU: " : "       "
×
130
            println(io, prefix, line)
×
131
        end
×
132
    else
133
        cpu = Sys.cpu_info()
3✔
134
        println(io, "  CPU: ", length(cpu), " × ", cpu[1].model)
3✔
135
    end
136

137
    if verbose
3✔
138
        println(io, "  Memory: $(Sys.total_memory()/2^30) GB ($(Sys.free_memory()/2^20) MB free)")
×
139
        try println(io, "  Uptime: $(Sys.uptime()) sec"); catch; end
×
140
        print(io, "  Load Avg: ")
×
141
        Base.print_matrix(io, Sys.loadavg()')
×
142
        println(io)
×
143
    end
144
    println(io, "  WORD_SIZE: ", Sys.WORD_SIZE)
3✔
145
    println(io, "  LIBM: ",Base.libm_name)
3✔
146
    println(io, "  LLVM: libLLVM-",Base.libllvm_version," (", Sys.JIT, ", ", Sys.CPU_NAME, ")")
3✔
147
    println(io, "  Threads: ", Threads.maxthreadid(), " on ", Sys.CPU_THREADS, " virtual cores")
3✔
148

149
    function is_nonverbose_env(k::String)
380✔
150
        return occursin(r"^JULIA_|^DYLD_|^LD_", k)
377✔
151
    end
152
    function is_verbose_env(k::String)
3✔
153
        return occursin(r"PATH|FLAG|^TERM$|HOME", k) && !is_nonverbose_env(k)
×
154
    end
155
    env_strs = String[
6✔
156
        String["  $(k) = $(v)" for (k,v) in ENV if is_nonverbose_env(uppercase(k))];
157
        (verbose ?
158
         String["  $(k) = $(v)" for (k,v) in ENV if is_verbose_env(uppercase(k))] :
159
         String[]);
160
    ]
161
    if !isempty(env_strs)
3✔
162
        println(io, "Environment:")
3✔
163
        for str in env_strs
3✔
164
            println(io, str)
13✔
165
        end
13✔
166
    end
167
end
168

169

170
function type_close_enough(@nospecialize(x), @nospecialize(t))
×
171
    x == t && return true
×
172
    # TODO: handle UnionAll properly
173
    return (isa(x, DataType) && isa(t, DataType) && x.name === t.name && x <: t) ||
×
174
           (isa(x, Union) && isa(t, DataType) && (type_close_enough(x.a, t) || type_close_enough(x.b, t)))
175
end
176

177
# `methodswith` -- shows a list of methods using the type given
178
"""
179
    methodswith(typ[, module or function]; supertypes::Bool=false])
180

181
Return an array of methods with an argument of type `typ`.
182

183
The optional second argument restricts the search to a particular module or function
184
(the default is all top-level modules).
185

186
If keyword `supertypes` is `true`, also return arguments with a parent type of `typ`,
187
excluding type `Any`.
188
"""
189
function methodswith(@nospecialize(t::Type), @nospecialize(f::Base.Callable), meths = Method[]; supertypes::Bool=false)
×
190
    for d in methods(f)
×
191
        if any(function (x)
×
192
                   let x = rewrap_unionall(x, d.sig)
×
193
                       (type_close_enough(x, t) ||
×
194
                        (supertypes ? (isa(x, Type) && t <: x && (!isa(x,TypeVar) || x.ub != Any)) :
195
                         (isa(x,TypeVar) && x.ub != Any && t == x.ub)) &&
196
                        x != Any)
197
                   end
198
               end,
199
               unwrap_unionall(d.sig).parameters)
200
            push!(meths, d)
×
201
        end
202
    end
×
203
    return meths
×
204
end
205

206
function _methodswith(@nospecialize(t::Type), m::Module, supertypes::Bool)
×
207
    meths = Method[]
×
208
    for nm in names(m)
×
209
        if isdefined(m, nm)
×
210
            f = getfield(m, nm)
×
211
            if isa(f, Base.Callable)
×
212
                methodswith(t, f, meths; supertypes = supertypes)
×
213
            end
214
        end
215
    end
×
216
    return unique(meths)
×
217
end
218

219
methodswith(@nospecialize(t::Type), m::Module; supertypes::Bool=false) = _methodswith(t, m, supertypes)
×
220

221
function methodswith(@nospecialize(t::Type); supertypes::Bool=false)
×
222
    meths = Method[]
×
223
    for mod in Base.loaded_modules_array()
×
224
        append!(meths, _methodswith(t, mod, supertypes))
×
225
    end
×
226
    return unique(meths)
×
227
end
228

229
# subtypes
230
function _subtypes_in!(mods::Array, x::Type)
1✔
231
    xt = unwrap_unionall(x)
1✔
232
    if !isabstracttype(x) || !isa(xt, DataType)
1✔
233
        # Fast path
234
        return Type[]
1✔
235
    end
236
    sts = Vector{Any}()
×
237
    while !isempty(mods)
×
238
        m = pop!(mods)
×
239
        xt = xt::DataType
×
240
        for s in names(m, all = true)
×
241
            if isdefined(m, s) && !isdeprecated(m, s)
×
242
                t = getfield(m, s)
×
243
                dt = isa(t, UnionAll) ? unwrap_unionall(t) : t
×
244
                if isa(dt, DataType)
×
245
                    if dt.name.name === s && dt.name.module == m && supertype(dt).name == xt.name
×
246
                        ti = typeintersect(t, x)
×
247
                        ti != Bottom && push!(sts, ti)
×
248
                    end
249
                elseif isa(t, Module) && nameof(t) === s && parentmodule(t) === m && t !== m
×
250
                    t === Base || push!(mods, t) # exclude Base, since it also parented by Main
×
251
                end
252
            end
253
        end
×
254
    end
×
255
    return permute!(sts, sortperm(map(string, sts)))
×
256
end
257

258
subtypes(m::Module, x::Type) = _subtypes_in!([m], x)
×
259

260
"""
261
    subtypes(T::DataType)
262

263
Return a list of immediate subtypes of DataType `T`. Note that all currently loaded subtypes
264
are included, including those not visible in the current module.
265

266
See also [`supertype`](@ref), [`supertypes`](@ref), [`methodswith`](@ref).
267

268
# Examples
269
```jldoctest
270
julia> subtypes(Integer)
271
3-element Vector{Any}:
272
 Bool
273
 Signed
274
 Unsigned
275
```
276
"""
277
subtypes(x::Type) = _subtypes_in!(Base.loaded_modules_array(), x)
1✔
278

279
"""
280
    supertypes(T::Type)
281

282
Return a tuple `(T, ..., Any)` of `T` and all its supertypes, as determined by
283
successive calls to the [`supertype`](@ref) function, listed in order of `<:`
284
and terminated by `Any`.
285

286
See also [`subtypes`](@ref).
287

288
# Examples
289
```jldoctest
290
julia> supertypes(Int)
291
(Int64, Signed, Integer, Real, Number, Any)
292
```
293
"""
294
function supertypes(T::Type)
×
295
    S = supertype(T)
×
296
    # note: we return a tuple here, not an Array as for subtypes, because in
297
    #       the future we could evaluate this function statically if desired.
298
    return S === T ? (T,) : (T, supertypes(S)...)
×
299
end
300

301
# TODO: @deprecate peakflops to LinearAlgebra
302
export peakflops
303
"""
304
    peakflops(n::Integer=2000; parallel::Bool=false)
305

306
`peakflops` computes the peak flop rate of the computer by using double precision
307
[`gemm!`](@ref LinearAlgebra.BLAS.gemm!). For more information see
308
[`LinearAlgebra.peakflops`](@ref).
309

310
!!! compat "Julia 1.1"
311
    This function will be moved from `InteractiveUtils` to `LinearAlgebra` in the
312
    future. In Julia 1.1 and later it is available as `LinearAlgebra.peakflops`.
313
"""
314
function peakflops(n::Integer=2000; parallel::Bool=false)
×
315
    # Base.depwarn("`peakflop`s have moved to the LinearAlgebra module, " *
316
    #              "add `using LinearAlgebra` to your imports.", :peakflops)
317
    let LinearAlgebra = Base.require(Base.PkgId(
×
318
            Base.UUID((0x37e2e46d_f89d_539d,0xb4ee_838fcccc9c8e)), "LinearAlgebra"))
319
        return LinearAlgebra.peakflops(n; parallel = parallel)
×
320
    end
321
end
322

323
function report_bug(kind)
×
324
    @info "Loading BugReporting package..."
×
325
    BugReportingId = Base.PkgId(
×
326
        Base.UUID((0xbcf9a6e7_4020_453c,0xb88e_690564246bb8)), "BugReporting")
327
    # Check if the BugReporting package exists in the current environment
328
    local BugReporting
×
329
    if Base.locate_package(BugReportingId) === nothing
×
330
        @info "Package `BugReporting` not found - attempting temporary installation"
×
331
        # Create a temporary environment and add BugReporting
332
        let Pkg = Base.require(Base.PkgId(
×
333
            Base.UUID((0x44cfe95a_1eb2_52ea,0xb672_e2afdf69b78f)), "Pkg"))
334
            mktempdir() do tmp
×
335
                old_load_path = copy(LOAD_PATH)
×
336
                push!(empty!(LOAD_PATH), joinpath(tmp, "Project.toml"))
×
337
                old_active_project = Base.ACTIVE_PROJECT[]
×
338
                Base.ACTIVE_PROJECT[] = nothing
×
339
                Pkg.add(Pkg.PackageSpec(BugReportingId.name, BugReportingId.uuid))
×
340
                BugReporting = Base.require(BugReportingId)
×
341
                append!(empty!(LOAD_PATH), old_load_path)
×
342
                Base.ACTIVE_PROJECT[] = old_active_project
×
343
            end
344
        end
345
    else
346
        BugReporting = Base.require(BugReportingId)
×
347
    end
348
    return Base.invokelatest(BugReporting.make_interactive_report, kind, ARGS)
×
349
end
350

351
end
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc