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

JuliaLang / julia / #37666

04 Nov 2023 02:27AM UTC coverage: 87.924% (+0.09%) from 87.831%
#37666

push

local

web-flow
Simplify, 16bit PDP-11 isn't going to be supported (#45763)

PDP_ENDIAN isn't used.

Co-authored-by: Viral B. Shah <ViralBShah@users.noreply.github.com>

74550 of 84789 relevant lines covered (87.92%)

15319904.67 hits per line

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

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

3
module InteractiveUtils
8✔
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 public 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-public 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))
138✔
48
                continue
10✔
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
69✔
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"
13✔
74
        end
75
        sort!(rows; by=r->r[col], rev)
190✔
76
    end
77
    pushfirst!(rows, Any["name", "size", "summary"])
22✔
78

79
    return Markdown.MD(Any[Markdown.Table(map(r->r[1:3], rows), Symbol[:l, :r, :l])])
143✔
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
4✔
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)
529✔
166
        return occursin(r"^JULIA_|^DYLD_|^LD_", k)
523✔
167
    end
168
    function is_verbose_env(k::String)
132✔
169
        return occursin(r"PATH|FLAG|^TERM$|HOME", k) && !is_nonverbose_env(k)
234✔
170
    end
171
    env_strs = String[
12✔
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))
69,046✔
187
    x == t && return true
69,046✔
188
    # TODO: handle UnionAll properly
189
    return (isa(x, DataType) && isa(t, DataType) && x.name === t.name && x <: t) ||
68,684✔
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
See also: [`methods`](@ref).
206
"""
207
function methodswith(@nospecialize(t::Type), @nospecialize(f::Base.Callable), meths = Method[]; supertypes::Bool=false)
5,830✔
208
    for d in methods(f)
5,734✔
209
        if any(function (x)
83,572✔
210
                   let x = rewrap_unionall(x, d.sig)
72,162✔
211
                       (type_close_enough(x, t) ||
61,178✔
212
                        (supertypes ? (isa(x, Type) && t <: x && (!isa(x,TypeVar) || x.ub != Any)) :
213
                         (isa(x,TypeVar) && x.ub != Any && t == x.ub)) &&
214
                        x != Any)
215
                   end
216
               end,
217
               unwrap_unionall(d.sig).parameters)
218
            push!(meths, d)
362✔
219
        end
220
    end
41,969✔
221
    return meths
2,915✔
222
end
223

224
function _methodswith(@nospecialize(t::Type), m::Module, supertypes::Bool)
46✔
225
    meths = Method[]
46✔
226
    for nm in names(m)
46✔
227
        if isdefined(m, nm)
3,133✔
228
            f = getfield(m, nm)
3,133✔
229
            if isa(f, Base.Callable)
3,133✔
230
                methodswith(t, f, meths; supertypes = supertypes)
3,550✔
231
            end
232
        end
233
    end
3,133✔
234
    return unique(meths)
46✔
235
end
236

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

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

247
# subtypes
248
function _subtypes_in!(mods::Array, x::Type)
24✔
249
    xt = unwrap_unionall(x)
24✔
250
    if !isabstracttype(x) || !isa(xt, DataType)
36✔
251
        # Fast path
252
        return Type[]
12✔
253
    end
254
    sts = Vector{Any}()
12✔
255
    while !isempty(mods)
1,185✔
256
        m = pop!(mods)
1,173✔
257
        xt = xt::DataType
1,173✔
258
        for s in names(m, all = true)
1,173✔
259
            if isdefined(m, s) && !isdeprecated(m, s)
253,646✔
260
                t = getfield(m, s)
253,610✔
261
                dt = isa(t, UnionAll) ? unwrap_unionall(t) : t
253,610✔
262
                if isa(dt, DataType)
253,610✔
263
                    if dt.name.name === s && dt.name.module == m && supertype(dt).name == xt.name
126,208✔
264
                        ti = typeintersect(t, x)
33✔
265
                        ti != Bottom && push!(sts, ti)
33✔
266
                    end
267
                elseif isa(t, Module) && nameof(t) === s && parentmodule(t) === m && t !== m
127,402✔
268
                    t === Base || push!(mods, t) # exclude Base, since it also parented by Main
924✔
269
                end
270
            end
271
        end
253,646✔
272
    end
1,173✔
273
    return permute!(sts, sortperm(map(string, sts)))
12✔
274
end
275

276
subtypes(m::Module, x::Type) = _subtypes_in!([m], x)
×
277

278
"""
279
    subtypes(T::DataType)
280

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

284
See also [`supertype`](@ref), [`supertypes`](@ref), [`methodswith`](@ref).
285

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

297
"""
298
    supertypes(T::Type)
299

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

304
See also [`subtypes`](@ref).
305

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

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

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

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

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

370
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

© 2026 Coveralls, Inc