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

JuliaLang / julia / #37596

pending completion
#37596

push

local

web-flow
🤖 [master] Bump the Pkg stdlib from 2c04d5a98 to b044bf6a2 (#50851)

Co-authored-by: Dilum Aluthge <dilum@aluthge.com>

71913 of 84418 relevant lines covered (85.19%)

32144286.87 hits per line

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

79.25
/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
using Base.Libc
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=false, imported=false, recursive=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, recursive::Bool = false, sortby::Symbol = :name, minsize::Int=0)
32✔
41
    sortby in (:name, :size, :summary) || throw(ArgumentError("Unrecognized `sortby` value `:$sortby`. Possible options are `:name`, `:size`, and `:summary`"))
11✔
42
    rows = Vector{Any}[]
11✔
43
    workqueue = [(m, ""),]
11✔
44
    while !isempty(workqueue)
23✔
45
        m2, prep = popfirst!(workqueue)
12✔
46
        for v in names(m2; all, imported)
12✔
47
            if !isdefined(m2, v) || !occursin(pattern, string(v))
144✔
48
                continue
13✔
49
            end
50
            value = getfield(m2, v)
59✔
51
            isbuiltin = value === Base || value === Base.active_module() || value === Core
118✔
52
            if recursive && !isbuiltin && isa(value, Module) && value !== m2 && nameof(value) === v && parentmodule(value) === m2
59✔
53
                push!(workqueue, (value, "$prep$v."))
1✔
54
            end
55
            ssize_str, ssize = if isbuiltin
59✔
56
                    ("", typemax(Int))
×
57
                else
58
                    ss = summarysize(value)
59✔
59
                    (format_bytes(ss), ss)
118✔
60
                end
61
            if ssize >= minsize
59✔
62
                push!(rows, Any[string(prep, v), ssize_str, summary(value), ssize])
55✔
63
            end
64
        end
84✔
65
    end
12✔
66
    let (col, rev) = if sortby === :name
11✔
67
            1, false
9✔
68
        elseif sortby === :size
2✔
69
            4, true
1✔
70
        elseif sortby === :summary
1✔
71
            3, false
1✔
72
        else
73
            @assert "unreachable"
14✔
74
        end
75
        sort!(rows; by=r->r[col], rev)
190✔
76
    end
77
    pushfirst!(rows, Any["name", "size", "summary"])
33✔
78

79
    return Markdown.MD(Any[Markdown.Table(map(r->r[1:3], rows), Symbol[:l, :r, :l])])
77✔
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)
15✔
98
    println(io, "Julia Version $VERSION")
6✔
99
    if !isempty(Base.GIT_VERSION_INFO.commit_short)
6✔
100
        println(io, "Commit $(Base.GIT_VERSION_INFO.commit_short) ($(Base.GIT_VERSION_INFO.date_string))")
6✔
101
    end
102
    official_release = Base.TAGGED_RELEASE_BANNER == "Official https://julialang.org/ release"
6✔
103
    if Base.isdebugbuild() || !isempty(Base.TAGGED_RELEASE_BANNER) || (Base.GIT_VERSION_INFO.tagged_commit && !official_release)
12✔
104
        println(io, "Build Info:")
×
105
        if Base.isdebugbuild()
×
106
            println(io, "  DEBUG build")
×
107
        end
108
        if !isempty(Base.TAGGED_RELEASE_BANNER)
×
109
            println(io, "  ", Base.TAGGED_RELEASE_BANNER)
×
110
        end
111
        if Base.GIT_VERSION_INFO.tagged_commit && !official_release
×
112
            println(io,
×
113
                """
114

115
                    Note: This is an unofficial build, please report bugs to the project
116
                    responsible for this build and not to the Julia project unless you can
117
                    reproduce the issue using official builds available at https://julialang.org/downloads
118
                """
119
            )
120
        end
121
    end
122
    println(io, "Platform Info:")
6✔
123
    println(io, "  OS: ", Sys.iswindows() ? "Windows" : Sys.isapple() ?
6✔
124
        "macOS" : Sys.KERNEL, " (", Sys.MACHINE, ")")
125

126
    if verbose
6✔
127
        lsb = ""
1✔
128
        if Sys.islinux()
1✔
129
            try lsb = readchomp(pipeline(`lsb_release -ds`, stderr=devnull)); catch; end
3✔
130
        end
131
        if Sys.iswindows()
1✔
132
            try lsb = strip(read(`$(ENV["COMSPEC"]) /c ver`, String)); catch; end
×
133
        end
134
        if !isempty(lsb)
2✔
135
            println(io, "      ", lsb)
×
136
        end
137
        if Sys.isunix()
1✔
138
            println(io, "  uname: ", readchomp(`uname -mprsv`))
1✔
139
        end
140
    end
141

142
    if verbose
6✔
143
        cpuio = IOBuffer() # print cpu_summary with correct alignment
1✔
144
        Sys.cpu_summary(cpuio)
1✔
145
        for (i, line) in enumerate(split(chomp(String(take!(cpuio))), "\n"))
2✔
146
            prefix = i == 1 ? "  CPU: " : "       "
3✔
147
            println(io, prefix, line)
3✔
148
        end
5✔
149
    else
150
        cpu = Sys.cpu_info()
5✔
151
        println(io, "  CPU: ", length(cpu), " × ", cpu[1].model)
5✔
152
    end
153

154
    if verbose
6✔
155
        println(io, "  Memory: $(Sys.total_memory()/2^30) GB ($(Sys.free_memory()/2^20) MB free)")
2✔
156
        try println(io, "  Uptime: $(Sys.uptime()) sec"); catch; end
2✔
157
        print(io, "  Load Avg: ")
1✔
158
        Base.print_matrix(io, Sys.loadavg()')
1✔
159
        println(io)
1✔
160
    end
161
    println(io, "  WORD_SIZE: ", Sys.WORD_SIZE)
6✔
162
    println(io, "  LLVM: libLLVM-",Base.libllvm_version," (", Sys.JIT, ", ", Sys.CPU_NAME, ")")
6✔
163
    println(io, "  Threads: ", Threads.maxthreadid(), " on ", Sys.CPU_THREADS, " virtual cores")
6✔
164

165
    function is_nonverbose_env(k::String)
537✔
166
        return occursin(r"^JULIA_|^DYLD_|^LD_", k)
531✔
167
    end
168
    function is_verbose_env(k::String)
134✔
169
        return occursin(r"PATH|FLAG|^TERM$|HOME", k) && !is_nonverbose_env(k)
128✔
170
    end
171
    env_strs = String[
11✔
172
        String["  $(k) = $(v)" for (k,v) in ENV if is_nonverbose_env(uppercase(k))];
173
        (verbose ?
174
         String["  $(k) = $(v)" for (k,v) in ENV if is_verbose_env(uppercase(k))] :
175
         String[]);
176
    ]
177
    if !isempty(env_strs)
6✔
178
        println(io, "Environment:")
5✔
179
        for str in env_strs
5✔
180
            println(io, str)
35✔
181
        end
36✔
182
    end
183
end
184

185

186
function type_close_enough(@nospecialize(x), @nospecialize(t))
77,399✔
187
    x == t && return true
77,399✔
188
    # TODO: handle UnionAll properly
189
    return (isa(x, DataType) && isa(t, DataType) && x.name === t.name && x <: t) ||
76,965✔
190
           (isa(x, Union) && isa(t, DataType) && (type_close_enough(x.a, t) || type_close_enough(x.b, t)))
191
end
192

193
# `methodswith` -- shows a list of methods using the type given
194
"""
195
    methodswith(typ[, module or function]; supertypes::Bool=false])
196

197
Return an array of methods with an argument of type `typ`.
198

199
The optional second argument restricts the search to a particular module or function
200
(the default is all top-level modules).
201

202
If keyword `supertypes` is `true`, also return arguments with a parent type of `typ`,
203
excluding type `Any`.
204
"""
205
function methodswith(@nospecialize(t::Type), @nospecialize(f::Base.Callable), meths = Method[]; supertypes::Bool=false)
6,546✔
206
    for d in methods(f)
6,452✔
207
        if any(function (x)
93,036✔
208
                   let x = rewrap_unionall(x, d.sig)
80,549✔
209
                       (type_close_enough(x, t) ||
67,910✔
210
                        (supertypes ? (isa(x, Type) && t <: x && (!isa(x,TypeVar) || x.ub != Any)) :
211
                         (isa(x,TypeVar) && x.ub != Any && t == x.ub)) &&
212
                        x != Any)
213
                   end
214
               end,
215
               unwrap_unionall(d.sig).parameters)
216
            push!(meths, d)
434✔
217
        end
218
    end
47,073✔
219
    return meths
3,273✔
220
end
221

222
function _methodswith(@nospecialize(t::Type), m::Module, supertypes::Bool)
82✔
223
    meths = Method[]
82✔
224
    for nm in names(m)
82✔
225
        if isdefined(m, nm)
5,425✔
226
            f = getfield(m, nm)
5,425✔
227
            if isa(f, Base.Callable)
5,425✔
228
                methodswith(t, f, meths; supertypes = supertypes)
4,086✔
229
            end
230
        end
231
    end
5,507✔
232
    return unique(meths)
82✔
233
end
234

235
methodswith(@nospecialize(t::Type), m::Module; supertypes::Bool=false) = _methodswith(t, m, supertypes)
4✔
236

237
function methodswith(@nospecialize(t::Type); supertypes::Bool=false)
4✔
238
    meths = Method[]
2✔
239
    for mod in Base.loaded_modules_array()
2✔
240
        append!(meths, _methodswith(t, mod, supertypes))
80✔
241
    end
82✔
242
    return unique(meths)
2✔
243
end
244

245
# subtypes
246
function _subtypes_in!(mods::Array, x::Type)
9✔
247
    xt = unwrap_unionall(x)
9✔
248
    if !isabstracttype(x) || !isa(xt, DataType)
16✔
249
        # Fast path
250
        return Type[]
2✔
251
    end
252
    sts = Vector{Any}()
7✔
253
    while !isempty(mods)
948✔
254
        m = pop!(mods)
941✔
255
        xt = xt::DataType
941✔
256
        for s in names(m, all = true)
941✔
257
            if isdefined(m, s) && !isdeprecated(m, s)
194,516✔
258
                t = getfield(m, s)
194,502✔
259
                dt = isa(t, UnionAll) ? unwrap_unionall(t) : t
194,502✔
260
                if isa(dt, DataType)
194,502✔
261
                    if dt.name.name === s && dt.name.module == m && supertype(dt).name == xt.name
94,199✔
262
                        ti = typeintersect(t, x)
20✔
263
                        ti != Bottom && push!(sts, ti)
20✔
264
                    end
265
                elseif isa(t, Module) && nameof(t) === s && parentmodule(t) === m && t !== m
100,303✔
266
                    t === Base || push!(mods, t) # exclude Base, since it also parented by Main
665✔
267
                end
268
            end
269
        end
195,457✔
270
    end
941✔
271
    return permute!(sts, sortperm(map(string, sts)))
7✔
272
end
273

274
subtypes(m::Module, x::Type) = _subtypes_in!([m], x)
×
275

276
"""
277
    subtypes(T::DataType)
278

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

282
See also [`supertype`](@ref), [`supertypes`](@ref), [`methodswith`](@ref).
283

284
# Examples
285
```jldoctest
286
julia> subtypes(Integer)
287
3-element Vector{Any}:
288
 Bool
289
 Signed
290
 Unsigned
291
```
292
"""
293
subtypes(x::Type) = _subtypes_in!(Base.loaded_modules_array(), x)
9✔
294

295
"""
296
    supertypes(T::Type)
297

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

302
See also [`subtypes`](@ref).
303

304
# Examples
305
```jldoctest
306
julia> supertypes(Int)
307
(Int64, Signed, Integer, Real, Number, Any)
308
```
309
"""
310
function supertypes(T::Type)
10✔
311
    S = supertype(T)
16✔
312
    # note: we return a tuple here, not an Array as for subtypes, because in
313
    #       the future we could evaluate this function statically if desired.
314
    return S === T ? (T,) : (T, supertypes(S)...)
10✔
315
end
316

317
# TODO: @deprecate peakflops to LinearAlgebra
318
export peakflops
319
"""
320
    peakflops(n::Integer=4096; eltype::DataType=Float64, ntrials::Integer=3, parallel::Bool=false)
321

322
`peakflops` computes the peak flop rate of the computer by using double precision
323
[`gemm!`](@ref LinearAlgebra.BLAS.gemm!). For more information see
324
[`LinearAlgebra.peakflops`](@ref).
325

326
!!! compat "Julia 1.1"
327
    This function will be moved from `InteractiveUtils` to `LinearAlgebra` in the
328
    future. In Julia 1.1 and later it is available as `LinearAlgebra.peakflops`.
329
"""
330
function peakflops(n::Integer=4096; eltype::DataType=Float64, ntrials::Integer=3, parallel::Bool=false)
×
331
    # Base.depwarn("`peakflops` has moved to the LinearAlgebra module, " *
332
    #              "add `using LinearAlgebra` to your imports.", :peakflops)
333
    let LinearAlgebra = Base.require(Base.PkgId(
×
334
            Base.UUID((0x37e2e46d_f89d_539d,0xb4ee_838fcccc9c8e)), "LinearAlgebra"))
335
        return LinearAlgebra.peakflops(n, eltype=eltype, ntrials=ntrials, parallel=parallel)
×
336
    end
337
end
338

339
function report_bug(kind)
×
340
    @info "Loading BugReporting package..."
×
341
    BugReportingId = Base.PkgId(
×
342
        Base.UUID((0xbcf9a6e7_4020_453c,0xb88e_690564246bb8)), "BugReporting")
343
    # Check if the BugReporting package exists in the current environment
344
    local BugReporting
×
345
    if Base.locate_package(BugReportingId) === nothing
×
346
        @info "Package `BugReporting` not found - attempting temporary installation"
×
347
        # Create a temporary environment and add BugReporting
348
        let Pkg = Base.require(Base.PkgId(
×
349
            Base.UUID((0x44cfe95a_1eb2_52ea,0xb672_e2afdf69b78f)), "Pkg"))
350
            mktempdir() do tmp
×
351
                old_load_path = copy(LOAD_PATH)
×
352
                push!(empty!(LOAD_PATH), joinpath(tmp, "Project.toml"))
×
353
                old_active_project = Base.ACTIVE_PROJECT[]
×
354
                Base.ACTIVE_PROJECT[] = nothing
×
355
                Pkg.add(Pkg.PackageSpec(BugReportingId.name, BugReportingId.uuid))
×
356
                BugReporting = Base.require(BugReportingId)
×
357
                append!(empty!(LOAD_PATH), old_load_path)
×
358
                Base.ACTIVE_PROJECT[] = old_active_project
×
359
            end
360
        end
361
    else
362
        BugReporting = Base.require(BugReportingId)
×
363
    end
364
    return Base.invokelatest(BugReporting.make_interactive_report, kind, ARGS)
×
365
end
366

367
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