From cadf6dba18af3ebe91e514791e762886a3964c16 Mon Sep 17 00:00:00 2001 From: Neven Sajko Date: Sat, 15 Mar 2025 10:47:14 +0100 Subject: [PATCH] restrict dispatch of some custrom string macros to `String` Restricts the dispatch for these macros so that only `String` (literal) arguments are accepted: * `int128_str` * `uint128_str` * `big_str` * `ip_str` from the Sockets stdlib * `dateformat_str` from the Dates stdlib Some of these changes make the code in the sysimage less vulnerable to invalidation. The `big_str` and `ip_str` changes, to be specific. The number of invalidations on running the following code is decreased from 167 to 153: ```julia struct I <: Integer end Base.Int(::I) = 7 ``` As far as I understand this change can't break any existing code, because: * the macro definitions in question require `AbstractString` * the way Julia's macros work, the argument is either a literal or an `Expr` * `String` is the only `AbstractString` with literals --- base/int.jl | 6 +++--- stdlib/Dates/src/io.jl | 2 +- stdlib/Sockets/src/IPAddr.jl | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/base/int.jl b/base/int.jl index 8a80f90f7e2c1..fe11f57eae547 100644 --- a/base/int.jl +++ b/base/int.jl @@ -642,7 +642,7 @@ ERROR: LoadError: ArgumentError: invalid base 10 digit '.' in "123456789123.4" [...] ``` """ -macro int128_str(s) +macro int128_str(s::String) return parse(Int128, s) end @@ -662,7 +662,7 @@ ERROR: LoadError: ArgumentError: invalid base 10 digit '-' in "-123456789123" [...] ``` """ -macro uint128_str(s) +macro uint128_str(s::String) return parse(UInt128, s) end @@ -695,7 +695,7 @@ ERROR: ArgumentError: invalid number format _ for BigInt or BigFloat depends on the value of the precision at the point when the function is defined, **not** at the precision at the time when the function is called. """ -macro big_str(s) +macro big_str(s::String) message = "invalid number format $s for BigInt or BigFloat" throw_error = :(throw(ArgumentError($message))) if '_' in s diff --git a/stdlib/Dates/src/io.jl b/stdlib/Dates/src/io.jl index aa7019566093c..88c32bf064bf0 100644 --- a/stdlib/Dates/src/io.jl +++ b/stdlib/Dates/src/io.jl @@ -478,7 +478,7 @@ but creates the DateFormat object once during macro expansion. See [`DateFormat`](@ref) for details about format specifiers. """ -macro dateformat_str(str) +macro dateformat_str(str::String) DateFormat(str) end diff --git a/stdlib/Sockets/src/IPAddr.jl b/stdlib/Sockets/src/IPAddr.jl index d3834a8b8bf73..e324dee712b71 100644 --- a/stdlib/Sockets/src/IPAddr.jl +++ b/stdlib/Sockets/src/IPAddr.jl @@ -286,7 +286,7 @@ julia> @ip_str "2001:db8:0:0:0:0:2:1" ip"2001:db8::2:1" ``` """ -macro ip_str(str) +macro ip_str(str::String) return parse(IPAddr, str) end