Skip to content

Commit

Permalink
Assume :foldable in isuppercase/islowercase for Char (#54346)
Browse files Browse the repository at this point in the history
With this, `isuppercase`/`islowercase` are evaluated at compile-time for
`Char` arguments:
```julia
julia> @code_typed (() -> isuppercase('A'))()
CodeInfo(
1 ─     return true
) => Bool

julia> @code_typed (() -> islowercase('A'))()
CodeInfo(
1 ─     return false
) => Bool
```
This would be useful in #54303,
where the case of the character indicates which triangular half of a
matrix is filled, and may be constant-propagated downstream.

---------

Co-authored-by: Shuhei Kadowaki <40514306+aviatesk@users.noreply.github.com>
  • Loading branch information
jishnub and aviatesk committed May 7, 2024
1 parent 99bda02 commit d2399e6
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
9 changes: 6 additions & 3 deletions base/strings/unicode.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ module Unicode

import Base: show, ==, hash, string, Symbol, isless, length, eltype,
convert, isvalid, ismalformed, isoverlong, iterate,
AnnotatedString, AnnotatedChar, annotated_chartransform
AnnotatedString, AnnotatedChar, annotated_chartransform,
@assume_effects

# whether codepoints are valid Unicode scalar values, i.e. 0-0xd7ff, 0xe000-0x10ffff

Expand Down Expand Up @@ -385,7 +386,8 @@ julia> islowercase('❤')
false
```
"""
islowercase(c::AbstractChar) = ismalformed(c) ? false : Bool(ccall(:utf8proc_islower, Cint, (UInt32,), UInt32(c)))
islowercase(c::AbstractChar) = ismalformed(c) ? false :
Bool(@assume_effects :foldable @ccall utf8proc_islower(UInt32(c)::UInt32)::Cint)

# true for Unicode upper and mixed case

Expand All @@ -409,7 +411,8 @@ julia> isuppercase('❤')
false
```
"""
isuppercase(c::AbstractChar) = ismalformed(c) ? false : Bool(ccall(:utf8proc_isupper, Cint, (UInt32,), UInt32(c)))
isuppercase(c::AbstractChar) = ismalformed(c) ? false :
Bool(@assume_effects :foldable @ccall utf8proc_isupper(UInt32(c)::UInt32)::Cint)

"""
iscased(c::AbstractChar) -> Bool
Expand Down
18 changes: 18 additions & 0 deletions test/char.jl
Original file line number Diff line number Diff line change
Expand Up @@ -360,3 +360,21 @@ end
@test Base.IteratorSize(Char) == Base.HasShape{0}()
@test convert(ASCIIChar, 1) == Char(1)
end

@testset "foldable isuppercase/islowercase" begin
v = @inferred (() -> Val(isuppercase('C')))()
@test v isa Val{true}
v = @inferred (() -> Val(islowercase('C')))()
@test v isa Val{false}

struct MyChar <: AbstractChar
x :: Char
end
Base.codepoint(m::MyChar) = codepoint(m.x)
MyChar(x::UInt32) = MyChar(Char(x))

v = @inferred (() -> Val(isuppercase(MyChar('C'))))()
@test v isa Val{true}
v = @inferred (() -> Val(islowercase(MyChar('C'))))()
@test v isa Val{false}
end

0 comments on commit d2399e6

Please sign in to comment.