Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions spec/compiler/macro/macro_methods_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,18 @@ module Crystal
assert_macro %({{"1234".to_i(16)}}), %(4660)
end

it "adds correct number kind on to_i (#16467)" do
assert_macro %({{"0".to_i.kind}}), %(:i32)
assert_macro %({{"2147483647".to_i.kind}}), %(:i32)
assert_macro %({{"2147483648".to_i.kind}}), %(:i64)
assert_macro %({{"123456789012345".to_i.kind}}), %(:i64)
assert_macro %({{"7fffffffffffffff".to_i(16).kind}}), %(:i64)
assert_macro %({{"-2147483648".to_i.kind}}), %(:i32)
assert_macro %({{"-2147483649".to_i.kind}}), %(:i64)
assert_macro %({{"-123456789012345".to_i.kind}}), %(:i64)
assert_macro %({{"-8000000000000000".to_i(16).kind}}), %(:i64)
end

it "executes string includes? char (true)" do
assert_macro %({{"spice".includes?('s')}}), %(true)
assert_macro %({{"spice".includes?('p')}}), %(true)
Expand Down
8 changes: 6 additions & 2 deletions src/compiler/crystal/macros.cr
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,12 @@ private macro def_string_methods(klass)
def titleize : {{klass}}
end

# Similar to `String#to_i`.
def to_i(base = 10)
# Similar to `String#to_i64`.
#
# The returned `NumberLiteral` has the `:i32` kind if it fits into `Int32`'s
# range, and the `:i64` kind otherwise. This matches the behavior of
# suffix-less number literals in Crystal.
def to_i(base : NumberLiteral = 10) : NumberLiteral
end

# Returns an expression that evaluates to a slice literal containing the
Expand Down
6 changes: 5 additions & 1 deletion src/compiler/crystal/macros/methods.cr
Original file line number Diff line number Diff line change
Expand Up @@ -900,7 +900,11 @@ module Crystal
end

if value
NumberLiteral.new(value.to_s, :i32)
if value.in?(Int32::MIN..Int32::MAX)
NumberLiteral.new(value.to_s, :i32)
else
NumberLiteral.new(value.to_s, :i64)
end
else
raise "StringLiteral#to_i: #{@value} is not an integer"
end
Expand Down