Skip to content

Commit

Permalink
at-[s]printf to Printf stdlib
Browse files Browse the repository at this point in the history
  • Loading branch information
fredrikekre committed Dec 16, 2017
1 parent 3eb5544 commit 8ab6f01
Show file tree
Hide file tree
Showing 28 changed files with 118 additions and 55 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,8 @@ Deprecated or removed
* The functions `eigs` and `svds` have been moved to the `IterativeEigensolvers` standard
library module ([#24714]).

* `@printf` and `@sprintf` have been moved to the `Printf` standard library ([#23929],[#25056]).

* `isnumber` has been deprecated in favor of `isnumeric`, `is_assigned_char`
in favor of `isassigned` and `normalize_string` in favor of `normalize`, all three
in the new `Unicode` standard library module ([#25021]).
Expand Down
3 changes: 3 additions & 0 deletions base/deprecated.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1315,6 +1315,9 @@ export conv, conv2, deconv, filt, filt!, xcorr
@deprecate_moved eigs "IterativeEigensolvers" true true
@deprecate_moved svds "IterativeEigensolvers" true true

@eval @deprecate_moved $(Symbol("@printf")) "Printf" true true
@eval @deprecate_moved $(Symbol("@sprintf")) "Printf" true true

# PR #21709
@deprecate cov(x::AbstractVector, corrected::Bool) cov(x, corrected=corrected)
@deprecate cov(x::AbstractMatrix, vardim::Int, corrected::Bool) cov(x, vardim, corrected=corrected)
Expand Down
2 changes: 0 additions & 2 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1171,8 +1171,6 @@ export

# output
@show,
@printf,
@sprintf,

# profiling
@time,
Expand Down
8 changes: 4 additions & 4 deletions base/interactiveutil.jl
Original file line number Diff line number Diff line change
Expand Up @@ -226,20 +226,20 @@ function _show_cpuinfo(io::IO, info::Sys.CPUinfo, header::Bool=true, prefix::Abs
println(io, info.model, ": ")
print(io, " "^length(prefix))
if tck > 0
@printf(io, " %5s %9s %9s %9s %9s %9s\n",
Printf.@printf(io, " %5s %9s %9s %9s %9s %9s\n",
"speed", "user", "nice", "sys", "idle", "irq")
else
@printf(io, " %5s %9s %9s %9s %9s %9s ticks\n",
Printf.@printf(io, " %5s %9s %9s %9s %9s %9s ticks\n",
"speed", "user", "nice", "sys", "idle", "irq")
end
end
print(io, prefix)
if tck > 0
@printf(io, "%5d MHz %9d s %9d s %9d s %9d s %9d s",
Printf.@printf(io, "%5d MHz %9d s %9d s %9d s %9d s %9d s",
info.speed, info.cpu_times!user / tck, info.cpu_times!nice / tck,
info.cpu_times!sys / tck, info.cpu_times!idle / tck, info.cpu_times!irq / tck)
else
@printf(io, "%5d MHz %9d %9d %9d %9d %9d ticks",
Printf.@printf(io, "%5d MHz %9d %9d %9d %9d %9d ticks",
info.speed, info.cpu_times!user, info.cpu_times!nice,
info.cpu_times!sys, info.cpu_times!idle, info.cpu_times!irq)
end
Expand Down
1 change: 1 addition & 0 deletions base/libgit2/libgit2.jl
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ module LibGit2

import Base: ==
using Base: coalesce, notnothing
using Base.Printf.@printf

export with, GitRepo, GitConfig

Expand Down
1 change: 1 addition & 0 deletions base/pkg/entry.jl
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import ..Reqs, ..Read, ..Query, ..Resolve, ..Cache, ..Write, ..Dir
using ...LibGit2
import ...Pkg.PkgError
using ..Types
using Base.Printf.@printf

macro recover(ex)
quote
Expand Down
35 changes: 0 additions & 35 deletions base/printf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
module Printf
using Base: Grisu, GMP
using Base.Unicode: lowercase, textwidth, isupper
export @printf, @sprintf

### printf formatter generation ###
const SmallFloatingPoint = Union{Float64,Float32,Float16}
Expand Down Expand Up @@ -1193,27 +1192,6 @@ function _printf(macroname, io, fmt, args)
Expr(:let, Expr(:block), blk)
end

"""
@printf([io::IOStream], "%Fmt", args...)
Print `args` using C `printf` style format specification string, with some caveats:
`Inf` and `NaN` are printed consistently as `Inf` and `NaN` for flags `%a`, `%A`,
`%e`, `%E`, `%f`, `%F`, `%g`, and `%G`. Furthermore, if a floating point number is
equally close to the numeric values of two possible output strings, the output
string further away from zero is chosen.
Optionally, an `IOStream`
may be passed as the first argument to redirect output.
# Examples
```jldoctest
julia> @printf("%f %F %f %F\\n", Inf, Inf, NaN, NaN)
Inf Inf NaN NaN\n
julia> @printf "%.0f %.1f %f\\n" 0.5 0.025 -0.0078125
1 0.0 -0.007813
```
"""
macro printf(args...)
isempty(args) && throw(ArgumentError("@printf: called with no arguments"))
if isa(args[1], AbstractString) || is_str_expr(args[1])
Expand All @@ -1225,19 +1203,6 @@ macro printf(args...)
end
end

"""
@sprintf("%Fmt", args...)
Return `@printf` formatted output as string.
# Examples
```jldoctest
julia> s = @sprintf "this is a %s %15.1f" "test" 34.567;
julia> println(s)
this is a test 34.6
```
"""
macro sprintf(args...)
isempty(args) && throw(ArgumentError("@sprintf: called with zero arguments"))
isa(args[1], AbstractString) || is_str_expr(args[1]) ||
Expand Down
1 change: 1 addition & 0 deletions base/stacktraces.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ module StackTraces

import Base: hash, ==, show
import Base.Serializer: serialize, deserialize
using Base.Printf.@printf

export StackTrace, StackFrame, stacktrace, catch_stacktrace

Expand Down
3 changes: 2 additions & 1 deletion base/sysimg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ import .Random: rand, rand!

# (s)printf macros
include("printf.jl")
using .Printf
# import .Printf

# metaprogramming
include("meta.jl")
Expand Down Expand Up @@ -495,6 +495,7 @@ Base.require(:SuiteSparse)
Base.require(:Test)
Base.require(:Unicode)
Base.require(:Distributed)
Base.require(:Printf)

@eval Base begin
@deprecate_binding Test root_module(:Test) true ", run `using Test` instead"
Expand Down
14 changes: 7 additions & 7 deletions base/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -99,28 +99,28 @@ end
function format_bytes(bytes)
bytes, mb = prettyprint_getunits(bytes, length(_mem_units), Int64(1024))
if mb == 1
@sprintf("%d %s%s", bytes, _mem_units[mb], bytes==1 ? "" : "s")
Printf.@sprintf("%d %s%s", bytes, _mem_units[mb], bytes==1 ? "" : "s")
else
@sprintf("%.3f %s", bytes, _mem_units[mb])
Printf.@sprintf("%.3f %s", bytes, _mem_units[mb])
end
end

function time_print(elapsedtime, bytes, gctime, allocs)
@printf("%10.6f seconds", elapsedtime/1e9)
Printf.@printf("%10.6f seconds", elapsedtime/1e9)
if bytes != 0 || allocs != 0
allocs, ma = prettyprint_getunits(allocs, length(_cnt_units), Int64(1000))
if ma == 1
@printf(" (%d%s allocation%s: ", allocs, _cnt_units[ma], allocs==1 ? "" : "s")
Printf.@printf(" (%d%s allocation%s: ", allocs, _cnt_units[ma], allocs==1 ? "" : "s")
else
@printf(" (%.2f%s allocations: ", allocs, _cnt_units[ma])
Printf.@printf(" (%.2f%s allocations: ", allocs, _cnt_units[ma])
end
print(format_bytes(bytes))
if gctime > 0
@printf(", %.2f%% gc time", 100*gctime/elapsedtime)
Printf.@printf(", %.2f%% gc time", 100*gctime/elapsedtime)
end
print(")")
elseif gctime > 0
@printf(", %.2f%% gc time", 100*gctime/elapsedtime)
Printf.@printf(", %.2f%% gc time", 100*gctime/elapsedtime)
end
println()
end
Expand Down
7 changes: 5 additions & 2 deletions doc/make.jl
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ if Sys.iswindows()
cp_q("../stdlib/IterativeEigensolvers/docs/src/index.md", "src/stdlib/iterativeeigensolvers.md")
cp_q("../stdlib/Unicode/docs/src/index.md", "src/stdlib/unicode.md")
cp_q("../stdlib/Distributed/docs/src/index.md", "src/stdlib/distributed.md")
cp_q("../stdlib/Printf/docs/src/index.md", "src/stdlib/printf.md")
else
symlink_q("../../../stdlib/DelimitedFiles/docs/src/index.md", "src/stdlib/delimitedfiles.md")
symlink_q("../../../stdlib/Test/docs/src/index.md", "src/stdlib/test.md")
Expand All @@ -46,6 +47,7 @@ else
symlink_q("../../../stdlib/IterativeEigensolvers/docs/src/index.md", "src/stdlib/iterativeeigensolvers.md")
symlink_q("../../../stdlib/Unicode/docs/src/index.md", "src/stdlib/unicode.md")
symlink_q("../../../stdlib/Distributed/docs/src/index.md", "src/stdlib/distributed.md")
symlink_q("../../../stdlib/Printf/docs/src/index.md", "src/stdlib/printf.md")
end

const PAGES = [
Expand Down Expand Up @@ -125,6 +127,7 @@ const PAGES = [
"stdlib/crc32c.md",
"stdlib/iterativeeigensolvers.md",
"stdlib/unicode.md",
"stdlib/printf.md",
],
"Developer Documentation" => [
"devdocs/reflection.md",
Expand Down Expand Up @@ -160,12 +163,12 @@ const PAGES = [
]

using DelimitedFiles, Test, Mmap, SharedArrays, Profile, Base64, FileWatching, CRC32c,
Dates, IterativeEigensolvers, Unicode, Distributed
Dates, IterativeEigensolvers, Unicode, Distributed, Printf

makedocs(
build = joinpath(pwd(), "_build/html/en"),
modules = [Base, Core, BuildSysImg, DelimitedFiles, Test, Mmap, SharedArrays, Profile,
Base64, FileWatching, Dates, IterativeEigensolvers, Unicode, Distributed],
Base64, FileWatching, Dates, IterativeEigensolvers, Unicode, Distributed, Printf],
clean = false,
doctest = "doctest" in ARGS,
linkcheck = "linkcheck" in ARGS,
Expand Down
1 change: 1 addition & 0 deletions doc/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
* [File Events](@ref lib-filewatching)
* [Iterative Eigensolvers](@ref lib-itereigen)
* [Unicode](@ref)
* [Printf](@ref)

## Developer Documentation

Expand Down
2 changes: 2 additions & 0 deletions doc/src/stdlib/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ filewatching.md
crc32c.md
dates.md
unicode.md
iterativeeigensolvers.md
printf.md
1 change: 1 addition & 0 deletions doc/src/stdlib/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@
* [Base64](@ref)
* [File Events](@ref lib-filewatching)
* [Iterative Eigensolvers](@ref lib-itereigen)
* [Printf](@ref)
2 changes: 0 additions & 2 deletions doc/src/stdlib/io-network.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,6 @@ Base.summary
Base.print
Base.println
Base.print_with_color
Base.Printf.@printf
Base.Printf.@sprintf
Base.sprint
Base.showerror
Base.dump
Expand Down
1 change: 1 addition & 0 deletions stdlib/Dates/src/Dates.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ module Dates

import ..Base: ==, div, fld, mod, rem, gcd, lcm, +, -, *, /, %
import ..Base.broadcast
using Base.Printf.@sprintf

using Base.Iterators

Expand Down
6 changes: 6 additions & 0 deletions stdlib/Printf/docs/src/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Printf

```@docs
Printf.@printf
Printf.@sprintf
```
69 changes: 69 additions & 0 deletions stdlib/Printf/src/Printf.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# This file is a part of Julia. License is MIT: https://julialang.org/license

__precompile__(true)

module Printf
# the macro implementations here exactly mirrors the
# macros left in base/printf.jl, and uses the utility there

export @printf, @sprintf
using Base.Printf: _printf, is_str_expr, fix_dec, DIGITS, print_fixed, decode_dec, decode_hex,
ini_hex, ini_HEX, print_exp_a, decode_0ct, decode_HEX, ini_dec, print_exp_e,
decode_oct, _limit
using Unicode.textwidth

"""
@printf([io::IOStream], "%Fmt", args...)
Print `args` using C `printf` style format specification string, with some caveats:
`Inf` and `NaN` are printed consistently as `Inf` and `NaN` for flags `%a`, `%A`,
`%e`, `%E`, `%f`, `%F`, `%g`, and `%G`. Furthermore, if a floating point number is
equally close to the numeric values of two possible output strings, the output
string further away from zero is chosen.
Optionally, an `IOStream`
may be passed as the first argument to redirect output.
# Examples
```jldoctest
julia> @printf("%f %F %f %F\\n", Inf, Inf, NaN, NaN)
Inf Inf NaN NaN\n
julia> @printf "%.0f %.1f %f\\n" 0.5 0.025 -0.0078125
1 0.0 -0.007813
```
"""
macro printf(args...)
isempty(args) && throw(ArgumentError("@printf: called with no arguments"))
if isa(args[1], AbstractString) || is_str_expr(args[1])
_printf("@printf", :STDOUT, args[1], args[2:end])
else
(length(args) >= 2 && (isa(args[2], AbstractString) || is_str_expr(args[2]))) ||
throw(ArgumentError("@printf: first or second argument must be a format string"))
_printf("@printf", esc(args[1]), args[2], args[3:end])
end
end

"""
@sprintf("%Fmt", args...)
Return `@printf` formatted output as string.
# Examples
```jldoctest
julia> s = @sprintf "this is a %s %15.1f" "test" 34.567;
julia> println(s)
this is a test 34.6
```
"""
macro sprintf(args...)
isempty(args) && throw(ArgumentError("@sprintf: called with zero arguments"))
isa(args[1], AbstractString) || is_str_expr(args[1]) ||
throw(ArgumentError("@sprintf: first argument must be a format string"))
letexpr = _printf("@sprintf", :(IOBuffer()), args[1], args[2:end])
push!(letexpr.args[2].args, :(String(take!(out))))
letexpr
end

end # module
2 changes: 2 additions & 0 deletions test/printf.jl → stdlib/Printf/test/runtests.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# This file is a part of Julia. License is MIT: https://julialang.org/license

using Test, Printf

macro test_throws(ty, ex)
return quote
Test.@test_throws $(esc(ty)) try
Expand Down
1 change: 1 addition & 0 deletions stdlib/Profile/src/Profile.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ module Profile

import Base.StackTraces: lookup, UNKNOWN, show_spec_linfo
using Base: iszero
using Base.Printf.@sprintf

export @profile

Expand Down
1 change: 1 addition & 0 deletions stdlib/SharedArrays/src/SharedArrays.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import Base.Random
import Base.Serializer: serialize_cycle_header, serialize_type, writetag, UNDEFREF_TAG
import Distributed: RRID, procs
import Base.Filesystem: JL_O_CREAT, JL_O_RDWR, S_IRUSR, S_IWUSR
using Base.Printf.@sprintf

export SharedArray, SharedVector, SharedMatrix, sdata, indexpids, localindices

Expand Down
1 change: 1 addition & 0 deletions stdlib/SuiteSparse/src/cholmod.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import Base.LinAlg: (\),
Adjoint, Transpose

using ..SparseArrays
using Base.Printf.@printf

export
Dense,
Expand Down
2 changes: 1 addition & 1 deletion test/choosetests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function choosetests(choices = [])
testnames = [
"linalg", "subarray", "core", "inference", "worlds",
"keywordargs", "numbers", "subtype",
"printf", "char", "strings", "triplequote", "unicode", "intrinsics",
"char", "strings", "triplequote", "unicode", "intrinsics",
"dict", "hashing", "iobuffer", "staged", "offsetarray",
"arrayops", "tuple", "reduce", "reducedim", "random", "abstractarray",
"intfuncs", "simdloop", "vecelement", "sparse",
Expand Down
2 changes: 1 addition & 1 deletion test/compile.jl
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ try
# plus modules included in the system image
Dict(s => Base.module_uuid(Base.root_module(s)) for s in
[:Base64, :CRC32c, :Dates, :DelimitedFiles, :FileWatching,
:IterativeEigensolvers, :Logging, :Mmap, :Profile, :SharedArrays,
:IterativeEigensolvers, :Logging, :Mmap, :Printf, :Profile, :SharedArrays,
:SuiteSparse, :Test, :Unicode, :Distributed]))
@test discard_module.(deps) == deps1

Expand Down
1 change: 1 addition & 0 deletions test/logging.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Base.CoreLogging: BelowMinLevel, Debug, Info, Warn, Error,
handle_message, shouldlog, min_enabled_level

import Test: collect_test_logs, TestLogger
using Base.Printf.@sprintf

#-------------------------------------------------------------------------------
@testset "Logging" begin
Expand Down
Loading

0 comments on commit 8ab6f01

Please sign in to comment.