diff --git a/src/base64.cr b/src/base64.cr index 951684afc7ef..d0caf05c21bb 100644 --- a/src/base64.cr +++ b/src/base64.cr @@ -41,7 +41,7 @@ module Base64 # Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g # Q3J5c3RhbA== # ``` - def encode(data) : String + def encode(data : String | Slice(UInt8) | StaticArray(UInt8, 5)) : String slice = data.to_slice String.new(encode_size(slice.size, new_lines: true)) do |buf| appender = buf.appender @@ -58,7 +58,7 @@ module Base64 # ``` # Base64.encode("Now is the time for all good coders\nto learn Crystal", STDOUT) # ``` - def encode(data, io : IO) + def encode(data : String | Slice(UInt8) | StaticArray(UInt8, 5), io : IO) : Int32 count = 0 encode_with_new_lines(data.to_slice) do |byte| io << byte.unsafe_chr @@ -95,11 +95,11 @@ module Base64 # ```text # Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4gQ3J5c3RhbA== # ``` - def strict_encode(data) : String + def strict_encode(data : Slice(UInt8) | StaticArray(UInt8, 5) | String | StaticArray(UInt8, 20) | StaticArray(UInt8, 16)) : String strict_encode data, CHARS_STD, pad: true end - private def strict_encode(data, alphabet, pad = false) + private def strict_encode(data : Slice(UInt8) | StaticArray(UInt8, 5) | String | StaticArray(UInt8, 20) | StaticArray(UInt8, 16), alphabet : String, pad : Bool = false) : String slice = data.to_slice String.new(encode_size(slice.size)) do |buf| appender = buf.appender @@ -115,11 +115,11 @@ module Base64 # ``` # Base64.strict_encode("Now is the time for all good coders\nto learn Crystal", STDOUT) # ``` - def strict_encode(data, io : IO) + def strict_encode(data : Slice(UInt8) | StaticArray(UInt8, 5) | String, io : IO) : Int32 strict_encode_to_io_internal(data, io, CHARS_STD, pad: true) end - private def strict_encode_to_io_internal(data, io, alphabet, pad) + private def strict_encode_to_io_internal(data : Slice(UInt8) | StaticArray(UInt8, 5) | String, io : String::Builder | IO::Memory, alphabet : String, pad : Bool) : Int32 count = 0 to_base64(data.to_slice, alphabet, pad: pad) do |byte| count += 1 @@ -137,7 +137,7 @@ module Base64 # # The *padding* parameter defaults to `true`. When `false`, enough `=` characters # are not added to make the output divisible by 4. - def urlsafe_encode(data, padding = true) : String + def urlsafe_encode(data : String | Slice(UInt8), padding : Bool = true) : String slice = data.to_slice String.new(encode_size(slice.size)) do |buf| appender = buf.appender @@ -152,13 +152,13 @@ module Base64 # Alphabet" in [RFC 4648](https://tools.ietf.org/html/rfc4648). # # The alphabet uses `'-'` instead of `'+'` and `'_'` instead of `'/'`. - def urlsafe_encode(data, io : IO) + def urlsafe_encode(data : String, io : IO) : Int32 strict_encode_to_io_internal(data, io, CHARS_SAFE, pad: true) end # Returns the base64-decoded version of *data* as a `Bytes`. # This will decode either the normal or urlsafe alphabets. - def decode(data) : Bytes + def decode(data : String) : Bytes slice = data.to_slice buf = Pointer(UInt8).malloc(decode_size(slice.size)) appender = buf.appender @@ -168,7 +168,7 @@ module Base64 # Writes the base64-decoded version of *data* to *io*. # This will decode either the normal or urlsafe alphabets. - def decode(data, io : IO) + def decode(data : String, io : IO) : Int32 count = 0 from_base64(data.to_slice) do |byte| io.write_byte byte @@ -180,7 +180,7 @@ module Base64 # Returns the base64-decoded version of *data* as a string. # This will decode either the normal or urlsafe alphabets. - def decode_string(data) : String + def decode_string(data : String) : String slice = data.to_slice String.new(decode_size(slice.size)) do |buf| appender = buf.appender @@ -189,13 +189,13 @@ module Base64 end end - private def encode_size(str_size, new_lines = false) + private def encode_size(str_size : Int32, new_lines : Bool = false) : Int32 size = (str_size * 4 / 3.0).to_i + 4 size += size // LINE_SIZE if new_lines size end - private def decode_size(str_size) + private def decode_size(str_size : Int32) : Int32 (str_size * 3 / 4.0).to_i + 4 end diff --git a/src/benchmark/bm.cr b/src/benchmark/bm.cr index 4b94e4ca6eee..f9844b5b4307 100644 --- a/src/benchmark/bm.cr +++ b/src/benchmark/bm.cr @@ -44,13 +44,13 @@ module Benchmark end # Reports a single benchmark unit. - def report(label = " ", &block) + def report(label : String = " ", &block) : Array(Tuple(String, Proc(Nil))) @label_width = label.size if label.size > @label_width @reports << {label, block} end # :nodoc: - def execute + def execute : Nil if @label_width > 0 print " " * @label_width end diff --git a/src/benchmark/ips.cr b/src/benchmark/ips.cr index def5b09c7c66..2f0f856ae0c2 100644 --- a/src/benchmark/ips.cr +++ b/src/benchmark/ips.cr @@ -31,7 +31,7 @@ module Benchmark end # Adds code to be benchmarked - def report(label = "", &action) : Benchmark::IPS::Entry + def report(label : String = "", &action) : Benchmark::IPS::Entry item = Entry.new(label, action) @items << item item @@ -61,7 +61,7 @@ module Benchmark # The warmup stage gathers information about the items that is later used # in the calculation stage - private def run_warmup + private def run_warmup : Nil @items.each do |item| GC.collect @@ -79,7 +79,7 @@ module Benchmark end end - private def run_calculation + private def run_calculation : Nil @items.each do |item| GC.collect @@ -113,11 +113,11 @@ module Benchmark end end - private def ran_items + private def ran_items : Array(Benchmark::IPS::Entry) @items.select(&.ran?) end - private def run_comparison + private def run_comparison : Nil fastest = ran_items.max_by(&.mean) ran_items.each do |item| item.slower = (fastest.mean / item.mean).to_f @@ -175,12 +175,12 @@ module Benchmark cycles.times { action.call } end - def set_cycles(duration, iterations) : Nil + def set_cycles(duration : Time::Span, iterations : Int32) : Nil @cycles = (iterations / duration.total_milliseconds * 100).to_i @cycles = 1 if cycles <= 0 end - def calculate_stats(samples) : Nil + def calculate_stats(samples : Array(Float64) | Array(Int32)) : Nil @ran = true @size = samples.size @mean = samples.sum.to_f / size.to_f diff --git a/src/bit_array.cr b/src/bit_array.cr index 4f4eb5726055..d3ce01f0f405 100644 --- a/src/bit_array.cr +++ b/src/bit_array.cr @@ -51,7 +51,7 @@ struct BitArray arr end - def ==(other : BitArray) + def ==(other : BitArray) : Bool return false if size != other.size # NOTE: If BitArray implements resizing, there may be more than 1 binary # representation and their hashes for equivalent BitArrays after a downsize as the @@ -366,7 +366,7 @@ struct BitArray end @[AlwaysInline] - private def set_bits(bytes : Slice(UInt8), value, index, mask) + private def set_bits(bytes : Slice(UInt8), value : Bool, index : Int32, mask : UInt8) : UInt8 if value bytes[index] |= mask else @@ -376,7 +376,7 @@ struct BitArray # returns (1 << from) | (1 << (from + 1)) | ... | (1 << to) @[AlwaysInline] - private def uint8_mask(from, to) + private def uint8_mask(from : Int32, to : Int32) : UInt8 (Int8::MIN >> (to - from)).to_u8! >> (7 - to) end @@ -396,7 +396,7 @@ struct BitArray # ba.toggle(3) # ba[3] # => true # ``` - def toggle(index) : Nil + def toggle(index : Int32) : Nil bit_index, sub_index = bit_index_and_sub_index(index) @bits[bit_index] ^= 1 << sub_index end @@ -417,7 +417,7 @@ struct BitArray # ba.toggle(1..-2) # ba.to_s # => "BitArray[01110]" # ``` - def toggle(range : Range) + def toggle(range : Range) : UInt32? toggle(*Indexable.range_to_index_and_count(range, size) || raise IndexError.new) end @@ -438,7 +438,7 @@ struct BitArray # ba.toggle(1, 3) # ba.to_s # => "BitArray[01110]" # ``` - def toggle(start : Int, count : Int) + def toggle(start : Int, count : Int) : UInt32? start, count = normalize_start_and_count(start, count) return if count == 0 @@ -459,7 +459,7 @@ struct BitArray # returns (1 << from) | (1 << (from + 1)) | ... | (1 << to) @[AlwaysInline] - private def uint32_mask(from, to) + private def uint32_mask(from : Int32, to : Int32) : UInt32 (Int32::MIN >> (to - from)).to_u32! >> (31 - to) end @@ -641,7 +641,7 @@ struct BitArray bit_array end - private def bit_index_and_sub_index(index) + private def bit_index_and_sub_index(index : Int32) : Tuple(Int32, Int32) bit_index_and_sub_index(index) { raise IndexError.new } end @@ -652,17 +652,17 @@ struct BitArray index.divmod(32) end - protected def clear_unused_bits + protected def clear_unused_bits : UInt32? # There are no unused bits if `size` is a multiple of 32. bit_index, sub_index = @size.divmod(32) @bits[bit_index] &= ~(UInt32::MAX << sub_index) unless sub_index == 0 end - private def bytesize + private def bytesize : Int32 (@size - 1) // 8 + 1 end - private def malloc_size + private def malloc_size : Int32 (@size - 1) // 32 + 1 end end diff --git a/src/channel.cr b/src/channel.cr index 4e23f8bb9b09..933eccf7e232 100644 --- a/src/channel.cr +++ b/src/channel.cr @@ -31,7 +31,7 @@ class Channel(T) record UseDefault class ClosedError < Exception - def initialize(msg = "Channel is closed") + def initialize(msg : String = "Channel is closed") super(msg) end end @@ -290,20 +290,20 @@ class Channel(T) pp.text inspect end - def self.receive_first(*channels) + def self.receive_first(*channels) : Int32 receive_first channels end - def self.receive_first(channels : Enumerable(Channel)) + def self.receive_first(channels : Enumerable(Channel)) : Int32 _, value = self.select(channels.map(&.receive_select_action)) value end - def self.send_first(value, *channels) : Nil + def self.send_first(value : Int32, *channels) : Nil send_first value, channels end - def self.send_first(value, channels : Enumerable(Channel)) : Nil + def self.send_first(value : Int32, channels : Enumerable(Channel)) : Nil self.select(channels.map(&.send_select_action(value))) nil end diff --git a/src/channel/select.cr b/src/channel/select.cr index 05db47a79a4c..db05f7cb5d3d 100644 --- a/src/channel/select.cr +++ b/src/channel/select.cr @@ -48,28 +48,28 @@ class Channel(T) end # :nodoc: - def self.select(*ops : SelectAction) + def self.select(*ops : SelectAction) : Tuple(Int32, String) | Tuple(Int32, Nil) | Tuple(Int32, Bool | String) | Tuple(Int32, String | Nil) | Tuple(Int32, Bool | String | Nil) | Tuple(Int32, Int32) self.select ops end # :nodoc: - def self.select(ops : Indexable(SelectAction)) + def self.select(ops : Indexable(SelectAction)) : Tuple(Int32, Int32) | Tuple(Int32, Nil) | Tuple(Int32, String) | Tuple(Int32, Bool | String) | Tuple(Int32, String | Nil) | Tuple(Int32, Bool | String | Nil) | Tuple(Int32, Bool | Nil) | Tuple(Int32, Int32 | Nil) i, m = select_impl(ops, false) raise "BUG: Blocking select returned not ready status" if m.is_a?(NotReady) return i, m end # :nodoc: - def self.non_blocking_select(*ops : SelectAction) + def self.non_blocking_select(*ops : SelectAction) : Tuple(Int32, Channel::NotReady | String) | Tuple(Int32, Bool | Channel::NotReady | String) | Tuple(Int32, Channel::NotReady | String | Nil) | Tuple(Int32, Channel::NotReady | Nil) self.non_blocking_select ops end # :nodoc: - def self.non_blocking_select(ops : Indexable(SelectAction)) + def self.non_blocking_select(ops : Indexable(SelectAction)) : Tuple(Int32, Channel::NotReady | String) | Tuple(Int32, Bool | Channel::NotReady | String) | Tuple(Int32, Channel::NotReady | String | Nil) | Tuple(Int32, Channel::NotReady | Nil) | Tuple(Int32, Bool | Channel::NotReady) | Tuple(Int32, Bool | Channel::NotReady | String | Nil) | Tuple(Int32, Channel::NotReady | Exception | Nil) select_impl(ops, true) end - private def self.select_impl(ops : Indexable(SelectAction), non_blocking) + private def self.select_impl(ops : Indexable(SelectAction), non_blocking : Bool) : Tuple(Int32, Channel::NotReady | Int32) | Tuple(Int32, Channel::NotReady | Nil) | Tuple(Int32, Channel::NotReady | String) | Tuple(Int32, Bool | Channel::NotReady | String) | Tuple(Int32, Channel::NotReady | String | Nil) | Tuple(Int32, Bool | Channel::NotReady | String | Nil) | Tuple(Int32, Bool | Channel::NotReady) | Tuple(Int32, Bool | Channel::NotReady | Nil) | Tuple(Int32, Channel::NotReady | Int32 | Nil) | Tuple(Int32, Channel::NotReady | Exception | Nil) # ops_locks is a duplicate of ops that can be sorted without disturbing the # index positions of ops if ops.responds_to?(:unstable_sort_by!) diff --git a/src/char.cr b/src/char.cr index 62189a0d8ceb..74365edb7731 100644 --- a/src/char.cr +++ b/src/char.cr @@ -140,7 +140,7 @@ struct Char end # :ditto: - def step(*, to limit = nil, exclusive : Bool = false) + def step(*, to limit : Char? = nil, exclusive : Bool = false) : Steppable::StepIterator(Char, Char, Int32) if limit direction = limit <=> self end @@ -681,7 +681,7 @@ struct Char # # This means characters which are `control?` or `whitespace?` (except for ` `) # are non-printable. - def printable? + def printable? : Bool !control? && (!whitespace? || self == ' ') end @@ -746,7 +746,7 @@ struct Char end # :ditto: - def dump(io) + def dump(io : String::Builder | IO::Memory) : String::Builder | IO::Memory io << dump end @@ -1050,11 +1050,11 @@ struct Char # 'c' === 99 # => true # 'z' === 99 # => false # ``` - def ===(byte : Int) + def ===(byte : Int) : Bool ord === byte end - def clone + def clone : Char self end end diff --git a/src/char/reader.cr b/src/char/reader.cr index bde6de53b4c3..b9523c8b6e95 100644 --- a/src/char/reader.cr +++ b/src/char/reader.cr @@ -80,7 +80,7 @@ struct Char # Creates a reader with the specified *string* positioned at # byte index *pos*. - def initialize(@string : String, pos = 0) + def initialize(@string : String, pos : Int32 | UInt64 | Int64 | UInt8 | UInt32 = 0) @pos = pos.to_i @current_char = '\0' @current_char_width = 0 @@ -239,7 +239,7 @@ struct Char # reader.pos = 0 # reader.current_char # => 'a' # ``` - def pos=(pos) + def pos=(pos : Int32) : Int32 if pos > @string.bytesize raise IndexError.new end @@ -335,7 +335,7 @@ struct Char end @[AlwaysInline] - private def decode_current_char + private def decode_current_char : Char decode_char_at(@pos) do |code_point, width, error| @current_char_width = width @error = error @@ -423,7 +423,7 @@ struct Char end @[AlwaysInline] - private def decode_previous_char + private def decode_previous_char : Char? return nil if @pos == 0 decode_char_before(@pos) do |code_point, width, error| @@ -434,7 +434,7 @@ struct Char end end - private def byte_at(i) + private def byte_at(i : Int32) : UInt32 @string.to_unsafe[i].to_u32 end end diff --git a/src/colorize.cr b/src/colorize.cr index 60ab17a28718..ff0d4d4a46d6 100644 --- a/src/colorize.cr +++ b/src/colorize.cr @@ -137,7 +137,7 @@ module Colorize # This is determined by the environment variable called `TERM`. # If `TERM=dumb`, color won't be enabled. # If `NO_COLOR` contains any value color won't be enabled conforming to https://no-color.org - def self.on_tty_only! + def self.on_tty_only! : Bool self.enabled = STDOUT.tty? && STDERR.tty? && ENV["TERM"]? != "dumb" && !ENV.has_key?("NO_COLOR") end @@ -177,13 +177,13 @@ module Colorize::ObjectExtensions # Wraps `self` in a `Colorize::Object` and colors it with the given `Color256` # made up from the single *fore* byte. - def colorize(fore : UInt8) + def colorize(fore : UInt8) : Colorize::Object(String) Colorize::Object.new(self).fore(fore) end # Wraps `self` in a `Colorize::Object` and colors it with the given `ColorRGB` made # up from the given *r*ed, *g*reen and *b*lue values. - def colorize(r : UInt8, g : UInt8, b : UInt8) + def colorize(r : UInt8, g : UInt8, b : UInt8) : Colorize::Object(String) Colorize::Object.new(self).fore(r, g, b) end @@ -193,7 +193,7 @@ module Colorize::ObjectExtensions end # Wraps `self` in a `Colorize::Object` and colors it with the given *fore* color. - def colorize(fore : Symbol) + def colorize(fore : Symbol) : Colorize::Object(Char) | Colorize::Object(String) Colorize::Object.new(self).fore(fore) end end @@ -513,7 +513,7 @@ struct Colorize::Object(T) end end - private def self.append_start(io, color) + private def self.append_start(io : IO::FileDescriptor | String::Builder | IO | IO::Memory, color : NamedTuple(fore: Colorize::Color256 | Colorize::ColorANSI | Colorize::ColorRGB, back: Colorize::Color256 | Colorize::ColorANSI | Colorize::ColorRGB, mode: Colorize::Mode)) : Bool last_color_is_default = @@last_color[:fore] == ColorANSI::Default && @@last_color[:back] == ColorANSI::Default && diff --git a/src/complex.cr b/src/complex.cr index e2a5830b395a..e1d92c5904e6 100644 --- a/src/complex.cr +++ b/src/complex.cr @@ -26,17 +26,17 @@ struct Complex @imag = imag.to_f end - def self.new(c : Complex) + def self.new(c : Complex) : Complex c end # Determines whether `self` equals *other* or not. - def ==(other : Complex) + def ==(other : Complex) : Bool @real == other.real && @imag == other.imag end # :ditto: - def ==(other : Number) + def ==(other : Number) : Bool @real == other && @imag.zero? end @@ -267,7 +267,7 @@ struct Complex Complex.new(@real / other, @imag / other) end - def clone + def clone : Complex self end @@ -306,7 +306,7 @@ struct Complex end # Rounds to the nearest *digits*. - def round(digits = 0) : Complex + def round(digits : Int32 = 0) : Complex Complex.new(@real.round(digits), @imag.round(digits)) end end @@ -322,7 +322,7 @@ struct Number Complex.new(0, self) end - def ==(other : Complex) + def ==(other : Complex) : Bool other == self end diff --git a/src/compress/deflate/deflate.cr b/src/compress/deflate/deflate.cr index 58479f503fbf..af19e0774817 100644 --- a/src/compress/deflate/deflate.cr +++ b/src/compress/deflate/deflate.cr @@ -23,7 +23,7 @@ module Compress::Deflate end class Error < Exception - def initialize(ret, stream) + def initialize(ret : LibZ::Error, stream : LibZ::ZStream) msg = stream.msg msg = LibZ.zError(ret) if msg.null? diff --git a/src/compress/deflate/writer.cr b/src/compress/deflate/writer.cr index f9a5adeb366f..7d9cf8c56467 100644 --- a/src/compress/deflate/writer.cr +++ b/src/compress/deflate/writer.cr @@ -85,7 +85,7 @@ class Compress::Deflate::Writer < IO to_s(io) end - private def consume_output(flush) + private def consume_output(flush : LibZ::Flush) : Nil loop do @stream.next_out = @buf.to_unsafe @stream.avail_out = @buf.size.to_u32 diff --git a/src/compress/gzip/writer.cr b/src/compress/gzip/writer.cr index f02a320805f6..130197852733 100644 --- a/src/compress/gzip/writer.cr +++ b/src/compress/gzip/writer.cr @@ -109,7 +109,7 @@ class Compress::Gzip::Writer < IO @io.close if @sync_close end - private def write_header + private def write_header : Compress::Deflate::Writer flate_io = @flate_io unless flate_io flate_io = @flate_io = Compress::Deflate::Writer.new(@io, level: @level) diff --git a/src/compress/zip/checksum_writer.cr b/src/compress/zip/checksum_writer.cr index da5a33351c97..317ba6795fd6 100644 --- a/src/compress/zip/checksum_writer.cr +++ b/src/compress/zip/checksum_writer.cr @@ -21,7 +21,7 @@ module Compress::Zip io.write(slice) end - def io=(@io) + def io=(@io : IO | Compress::Deflate::Writer) : UInt32 @count = 0_u32 @crc32 = ::Digest::CRC32.initial end diff --git a/src/compress/zip/file.cr b/src/compress/zip/file.cr index cea1101c9f30..df2434415832 100644 --- a/src/compress/zip/file.cr +++ b/src/compress/zip/file.cr @@ -44,7 +44,7 @@ class Compress::Zip::File end # Opens a `Zip::File` for reading from the given *filename*. - def self.new(filename : Path | String) + def self.new(filename : Path | String) : Compress::Zip::File new(::File.new(filename), sync_close: true) end @@ -85,14 +85,14 @@ class Compress::Zip::File # Tries to find the directory end offset (by searching its signature) # in the last 64, 1024 and 65K bytes (in that order) - private def find_directory_end_offset + private def find_directory_end_offset : Int32 | Int64 find_directory_end_offset(64) || find_directory_end_offset(1024) || find_directory_end_offset(65 * 1024) || raise Compress::Zip::Error.new("Couldn't find directory end signature in the last 65KB") end - private def find_directory_end_offset(buf_size) + private def find_directory_end_offset(buf_size : Int32) : Int32 | Int64 | Nil @io.seek(0, IO::Seek::End) size = @io.pos @@ -113,7 +113,7 @@ class Compress::Zip::File i == -1 ? nil : size - buf_size + i end - private def read_directory_end(directory_end_offset) + private def read_directory_end(directory_end_offset : Int32 | Int64) : Tuple(UInt16, UInt32) @io.pos = directory_end_offset signature = read UInt32 @@ -134,7 +134,7 @@ class Compress::Zip::File {entries_size, directory_offset} end - private def read_entries(directory_offset, entries_size) + private def read_entries(directory_offset : UInt32, entries_size : UInt16) : Nil @io.pos = directory_offset entries_size.times do @@ -149,7 +149,7 @@ class Compress::Zip::File end end - private def read(type) + private def read(type : UInt32.class | UInt16.class) : UInt32 | UInt16 @io.read_bytes(type, IO::ByteFormat::LittleEndian) end diff --git a/src/compress/zip/file_info.cr b/src/compress/zip/file_info.cr index db503ea6a048..0998c05c2985 100644 --- a/src/compress/zip/file_info.cr +++ b/src/compress/zip/file_info.cr @@ -51,7 +51,7 @@ module Compress::Zip::FileInfo end # :nodoc: - def initialize_meta(io : IO) + def initialize_meta(io : IO) : Tuple(UInt16, UInt16, Time) @general_purpose_bit_flag = read(io, UInt16) @compression_method = CompressionMethod.new(read(io, UInt16)) time = read(io, UInt16) @@ -65,7 +65,7 @@ module Compress::Zip::FileInfo {file_name_length, extra_field_length, time} end - def initialize(@filename : String, @time = Time.utc, @comment = "", @extra = Bytes.empty) + def initialize(@filename : String, @time : Time = Time.utc, @comment : String = "", @extra : Slice(UInt8) = Bytes.empty) end # Returns `true` if this entry is a directory. @@ -78,7 +78,7 @@ module Compress::Zip::FileInfo !dir? end - protected def to_io(io : IO) + protected def to_io(io : IO) : Int32 write io, SIGNATURE # 4 write io, @version # 2 meta_count = meta_to_io(io) @@ -87,7 +87,7 @@ module Compress::Zip::FileInfo meta_count + 6 + @filename.bytesize + extra.size end - protected def meta_to_io(io : IO) + protected def meta_to_io(io : IO) : Int32 write io, @general_purpose_bit_flag # 2 write io, @compression_method.value # 2 date, time = to_dos @@ -101,7 +101,7 @@ module Compress::Zip::FileInfo 24 # the 24 bytes we just wrote end - protected def write_data_descriptor(io : IO) + protected def write_data_descriptor(io : IO) : Int32 io.write FileInfo::DEFLATE_END_SIGNATURE # 4 write io, @crc32 # 4 write io, @compressed_size # 4 @@ -109,7 +109,7 @@ module Compress::Zip::FileInfo 16 # the 16 bytes we just wrote end - protected def decompressor_for(io, is_sized = false) + protected def decompressor_for(io : IO | IO::Memory, is_sized : Bool = false) : IO case compression_method when .stored? io = IO::Sized.new(io, compressed_size) unless is_sized @@ -129,7 +129,7 @@ module Compress::Zip::FileInfo io end - protected def bit_3_set? + protected def bit_3_set? : Bool (general_purpose_bit_flag & 0b1000) != 0 end @@ -142,7 +142,7 @@ module Compress::Zip::FileInfo # - 6 bits for minute # - 5 bits for seconds (0..29), precision of two seconds - private def from_dos(date, time) + private def from_dos(date : UInt16, time : UInt16) : Time year = 1980 + (date >> 9) month = (date >> 5) & 0b1111 day = date & 0b11111 @@ -154,7 +154,7 @@ module Compress::Zip::FileInfo Time.utc(year.to_i, month.to_i, day.to_i, hour.to_i, minute.to_i, second.to_i) end - private def to_dos + private def to_dos : Tuple(UInt16, UInt16) date = ((@time.year - 1980) << 9) | (@time.month << 5) | @time.day @@ -166,11 +166,11 @@ module Compress::Zip::FileInfo {date.to_u16, time.to_u16} end - private def read(io, type) + private def read(io : IO | IO::Memory, type : UInt16.class | UInt32.class) : UInt16 | UInt32 io.read_bytes(type, IO::ByteFormat::LittleEndian) end - private def write(io, value) + private def write(io : IO, value : Int32 | UInt16 | UInt32) : Nil io.write_bytes(value, IO::ByteFormat::LittleEndian) end end diff --git a/src/compress/zip/writer.cr b/src/compress/zip/writer.cr index 52ddee7400a5..5a88b900f015 100644 --- a/src/compress/zip/writer.cr +++ b/src/compress/zip/writer.cr @@ -45,7 +45,7 @@ class Compress::Zip::Writer end # Creates a new writer to the given *filename*. - def self.new(filename : Path | String) + def self.new(filename : Path | String) : Compress::Zip::Writer new(::File.new(filename, "w"), sync_close: true) end @@ -175,7 +175,7 @@ class Compress::Zip::Writer end # Adds a directory entry that will have the given *name*. - def add_dir(name) : Nil + def add_dir(name : String) : Nil name = name + '/' unless name.ends_with?('/') add(Entry.new(name)) { } end @@ -192,7 +192,7 @@ class Compress::Zip::Writer @io.close if @sync_close end - private def write_central_directory + private def write_central_directory : Nil @entries.each do |entry| write Zip::CENTRAL_DIRECTORY_HEADER_SIGNATURE # 4 write Zip::VERSION # version made by (2) @@ -219,7 +219,7 @@ class Compress::Zip::Writer end end - private def write_end_of_central_directory(offset, size) + private def write_end_of_central_directory(offset : UInt32, size : UInt32) : IO write Zip::END_OF_CENTRAL_DIRECTORY_HEADER_SIGNATURE write 0_u16 # number of this disk write 0_u16 # disk start @@ -231,7 +231,7 @@ class Compress::Zip::Writer @io << @comment # comment end - private def write(value) + private def write(value : Int32 | UInt16 | UInt32) : Nil @io.write_bytes(value, IO::ByteFormat::LittleEndian) end diff --git a/src/compress/zlib/reader.cr b/src/compress/zlib/reader.cr index 36c65ca25716..b1b1bdfcfe6c 100644 --- a/src/compress/zlib/reader.cr +++ b/src/compress/zlib/reader.cr @@ -27,7 +27,7 @@ class Compress::Zlib::Reader < IO yield reader ensure reader.close end - protected def self.read_header(io, dict) + protected def self.read_header(io : IO | IO::Memory, dict : Slice(UInt8)?) : Nil cmf = io.read_byte || invalid_header cm = cmf & 0xF @@ -105,7 +105,7 @@ class Compress::Zlib::Reader < IO initialize(@io, @sync_close, @flate_io.dict) end - protected def self.invalid_header + protected def self.invalid_header : Nil raise Compress::Zlib::Error.new("Invalid header") end end diff --git a/src/compress/zlib/writer.cr b/src/compress/zlib/writer.cr index 909123a13d90..795634bf76b8 100644 --- a/src/compress/zlib/writer.cr +++ b/src/compress/zlib/writer.cr @@ -80,7 +80,7 @@ class Compress::Zlib::Writer < IO @io.close if @sync_close end - private def write_header + private def write_header : Nil @wrote_header = true # CMF byte: 7 for window size, 8 for compression method (deflate) diff --git a/src/crypto/bcrypt.cr b/src/crypto/bcrypt.cr index 92d90495c1df..40cb6edea55f 100644 --- a/src/crypto/bcrypt.cr +++ b/src/crypto/bcrypt.cr @@ -56,7 +56,7 @@ class Crypto::Bcrypt # # Crypto::Bcrypt.hash_secret "secret" # ``` - def self.hash_secret(password, cost = DEFAULT_COST) : String + def self.hash_secret(password : String, cost : Int32 = DEFAULT_COST) : String # We make a clone here to we don't keep a mutable reference to the original string passwordb = password.to_unsafe.to_slice(password.bytesize + 1).clone # include leading 0 saltb = Random::Secure.random_bytes(SALT_SIZE) @@ -71,7 +71,7 @@ class Crypto::Bcrypt # password = Crypto::Bcrypt.new "secret", "salt_of_16_chars" # password.digest # ``` - def self.new(password : String, salt : String, cost = DEFAULT_COST) + def self.new(password : String, salt : String, cost : Int32 = DEFAULT_COST) : Crypto::Bcrypt # We make a clone here to we don't keep a mutable reference to the original string passwordb = password.to_unsafe.to_slice(password.bytesize + 1).clone # include leading 0 saltb = Base64.decode(salt, SALT_SIZE) @@ -122,7 +122,7 @@ class Crypto::Bcrypt delegate to_slice, to: to_s - private def hash_password + private def hash_password : Slice(UInt8) blowfish = Blowfish.new(BLOWFISH_ROUNDS) blowfish.enhance_key_schedule(salt, password, cost) diff --git a/src/crypto/bcrypt/base64.cr b/src/crypto/bcrypt/base64.cr index 01c59f237d62..bbf26bb19fc9 100644 --- a/src/crypto/bcrypt/base64.cr +++ b/src/crypto/bcrypt/base64.cr @@ -20,7 +20,7 @@ module Crypto::Bcrypt::Base64 51, 52, 53, -1, -1, -1, -1, -1, ] - def self.encode(d, len) : String + def self.encode(d : Slice(UInt8) | Array(UInt8), len : Int32) : String off = 0 String.build do |str| @@ -57,7 +57,7 @@ module Crypto::Bcrypt::Base64 end end - def self.decode(string, maxolen) : Bytes + def self.decode(string : String, maxolen : Int32) : Bytes off, slen, olen = 0, string.size, 0 i = -1 @@ -87,7 +87,7 @@ module Crypto::Bcrypt::Base64 str[0, olen] end - private def self.char64(x) + private def self.char64(x : Char) : Int32 | Int8 TABLE[x.ord]? || -1 end end diff --git a/src/crypto/bcrypt/blowfish.cr b/src/crypto/bcrypt/blowfish.cr index 4a608c502811..6a09d4eab243 100644 --- a/src/crypto/bcrypt/blowfish.cr +++ b/src/crypto/bcrypt/blowfish.cr @@ -3,7 +3,7 @@ require "../blowfish" # :nodoc: class Crypto::Bcrypt::Blowfish < Crypto::Blowfish - def enhance_key_schedule(data, key, cost) : Nil + def enhance_key_schedule(data : Slice(UInt8), key : Slice(UInt8), cost : Int32) : Nil enhance_key_schedule(data, key) (1_u32 << cost).times do @@ -12,7 +12,7 @@ class Crypto::Bcrypt::Blowfish < Crypto::Blowfish end end - def enhance_key_schedule(data, key) : Nil + def enhance_key_schedule(data : Slice(UInt8), key : Slice(UInt8)) : Nil pos = 0 0.upto(17) do |i| diff --git a/src/crypto/bcrypt/password.cr b/src/crypto/bcrypt/password.cr index b98658c9e22f..e1526c369bfb 100644 --- a/src/crypto/bcrypt/password.cr +++ b/src/crypto/bcrypt/password.cr @@ -27,7 +27,7 @@ class Crypto::Bcrypt::Password # password = Crypto::Bcrypt::Password.create("super secret", cost: 10) # # => $2a$10$rI4xRiuAN2fyiKwynO6PPuorfuoM4L2PVv6hlnVJEmNLjqcibAfHq # ``` - def self.create(password, cost = DEFAULT_COST) : self + def self.create(password : String, cost : Int32 = DEFAULT_COST) : self new(Bcrypt.hash_secret(password, cost).to_s) end diff --git a/src/crypto/blowfish.cr b/src/crypto/blowfish.cr index fc9734ad28aa..60e1c06ff262 100644 --- a/src/crypto/blowfish.cr +++ b/src/crypto/blowfish.cr @@ -15,7 +15,7 @@ class Crypto::Blowfish @s3 = @s.to_unsafe + 768 end - def expand_key(key) : Nil + def expand_key(key : Array(UInt8) | Slice(UInt8)) : Nil pos = 0 0.upto(17) do |i| @@ -37,7 +37,7 @@ class Crypto::Blowfish end end - def encrypt_pair(l : UInt32, r : UInt32) + def encrypt_pair(l : UInt32, r : UInt32) : Tuple(UInt32, UInt32) 0.upto(@rounds - 1) do |i| l ^= @p.to_unsafe[i] r ^= f(l) @@ -68,7 +68,7 @@ class Crypto::Blowfish end @[AlwaysInline] - private def f(x : UInt32) + private def f(x : UInt32) : UInt32 d = x.to_u8! c = (x >> 8).to_u8! b = (x >> 16).to_u8! @@ -76,7 +76,7 @@ class Crypto::Blowfish ((@s.to_unsafe[a] &+ @s1[b]) ^ @s2[c]) &+ @s3[d] end - private def next_word(data, pos) + private def next_word(data : Array(UInt8) | Slice(UInt8), pos : Pointer(Int32)) : UInt32 word = 0_u32 4.times do diff --git a/src/crypto/subtle.cr b/src/crypto/subtle.cr index 41b572e5e4c4..e6c94779a93b 100644 --- a/src/crypto/subtle.cr +++ b/src/crypto/subtle.cr @@ -9,7 +9,7 @@ module Crypto::Subtle # ``` # # NOTE: *x* and *y* must be able to respond to `to_slice`. - def self.constant_time_compare(x, y) : Bool + def self.constant_time_compare(x : Slice(Int32) | String | Slice(UInt8), y : Slice(Int32) | String | Slice(UInt8)) : Bool x = x.to_slice y = y.to_slice return false if x.size != y.size @@ -23,7 +23,7 @@ module Crypto::Subtle constant_time_byte_eq(v, 0) == 1 end - def self.constant_time_byte_eq(x, y) + def self.constant_time_byte_eq(x : UInt8 | Int32, y : Int32 | UInt8) : UInt8 | Int32 z = ~(x ^ y) z &= z >> 4 z &= z >> 2 diff --git a/src/csv/error.cr b/src/csv/error.cr index 866cb6e7be7e..4a7a44880114 100644 --- a/src/csv/error.cr +++ b/src/csv/error.cr @@ -10,7 +10,7 @@ class CSV getter line_number : Int32 getter column_number : Int32 - def initialize(message, @line_number, @column_number) + def initialize(message : String, @line_number : Int32, @column_number : Int32) super("#{message} at line #{@line_number}, column #{@column_number}") end end diff --git a/src/csv/lexer.cr b/src/csv/lexer.cr index 9d3d04c68c0f..36da66d263c1 100644 --- a/src/csv/lexer.cr +++ b/src/csv/lexer.cr @@ -15,12 +15,12 @@ require "csv" # ``` abstract class CSV::Lexer # Creates a CSV lexer from a `String`. - def self.new(string : String, separator = DEFAULT_SEPARATOR, quote_char = DEFAULT_QUOTE_CHAR) + def self.new(string : String, separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR) : CSV::Lexer::StringBased StringBased.new(string, separator, quote_char) end # Creates a CSV lexer from an `IO`. - def self.new(io : IO, separator = DEFAULT_SEPARATOR, quote_char = DEFAULT_QUOTE_CHAR) + def self.new(io : IO, separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR) : CSV::Lexer::IOBased IOBased.new(io, separator, quote_char) end @@ -101,7 +101,7 @@ abstract class CSV::Lexer @token end - private def consume_quoted_cell + private def consume_quoted_cell : String @buffer.clear while true case char = next_char @@ -126,7 +126,7 @@ abstract class CSV::Lexer @buffer.to_s end - private def check_last_empty_column + private def check_last_empty_column : Bool? case next_char when '\r', '\n', '\0' @last_empty_column = true @@ -135,7 +135,7 @@ abstract class CSV::Lexer end end - private def next_char + private def next_char : Char @column_number += 1 char = next_char_no_column_increment if char.in?('\n', '\r') @@ -145,7 +145,7 @@ abstract class CSV::Lexer char end - private def raise(msg) + private def raise(msg : String) : Nil ::raise CSV::MalformedCSVError.new(msg, @line_number, @column_number) end end diff --git a/src/csv/lexer/io_based.cr b/src/csv/lexer/io_based.cr index f33e83d99d9e..ab68f85056b3 100644 --- a/src/csv/lexer/io_based.cr +++ b/src/csv/lexer/io_based.cr @@ -2,7 +2,7 @@ require "csv" # :nodoc: class CSV::Lexer::IOBased < CSV::Lexer - def initialize(@io : IO, separator = DEFAULT_SEPARATOR, quote_char = DEFAULT_QUOTE_CHAR) + def initialize(@io : IO, separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR) super(separator, quote_char) @current_char = @io.read_char || '\0' end diff --git a/src/csv/lexer/string_based.cr b/src/csv/lexer/string_based.cr index c9d1193adc34..b1ab6521b0f2 100644 --- a/src/csv/lexer/string_based.cr +++ b/src/csv/lexer/string_based.cr @@ -2,7 +2,7 @@ require "csv" # :nodoc: class CSV::Lexer::StringBased < CSV::Lexer - def initialize(string, separator = DEFAULT_SEPARATOR, quote_char = DEFAULT_QUOTE_CHAR) + def initialize(string : String, separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR) super(separator, quote_char) @reader = Char::Reader.new(string) if @reader.current_char == '\n' diff --git a/src/deque.cr b/src/deque.cr index d2154bb462e6..9ab23f605939 100644 --- a/src/deque.cr +++ b/src/deque.cr @@ -96,7 +96,7 @@ class Deque(T) # ``` # Deque.new([1, 2, 3]) # => Deque{1, 2, 3} # ``` - def self.new(array : Array(T)) + def self.new(array : Array(T)) : Deque(Int32) | Deque(String) Deque(T).new(array.size) { |i| array[i] } end diff --git a/src/digest/adler32.cr b/src/digest/adler32.cr index 0b31e52a80b1..49d314d617af 100644 --- a/src/digest/adler32.cr +++ b/src/digest/adler32.cr @@ -17,16 +17,16 @@ class Digest::Adler32 < ::Digest LibZ.adler32(0, nil, 0).to_u32 end - def self.checksum(data) : UInt32 + def self.checksum(data : Slice(UInt8) | String) : UInt32 update(data, initial) end - def self.update(data, adler32 : UInt32) : UInt32 + def self.update(data : Slice(UInt8) | String, adler32 : UInt32) : UInt32 slice = data.to_slice LibZ.adler32(adler32, slice, slice.size).to_u32 end - def self.combine(adler1 : UInt32, adler2 : UInt32, len) : UInt32 + def self.combine(adler1 : UInt32, adler2 : UInt32, len : Int32) : UInt32 LibZ.adler32_combine(adler1, adler2, len).to_u32 end diff --git a/src/digest/crc32.cr b/src/digest/crc32.cr index b32ecd68e41f..807ba630e19f 100644 --- a/src/digest/crc32.cr +++ b/src/digest/crc32.cr @@ -17,16 +17,16 @@ class Digest::CRC32 < ::Digest LibZ.crc32(0, nil, 0).to_u32 end - def self.checksum(data) : UInt32 + def self.checksum(data : String) : UInt32 update(data, initial) end - def self.update(data, crc32 : UInt32) : UInt32 + def self.update(data : Slice(UInt8) | String, crc32 : UInt32) : UInt32 slice = data.to_slice LibZ.crc32(crc32, slice, slice.size).to_u32 end - def self.combine(crc1 : UInt32, crc2 : UInt32, len) : UInt32 + def self.combine(crc1 : UInt32, crc2 : UInt32, len : Int32) : UInt32 LibZ.crc32_combine(crc1, crc2, len).to_u32 end diff --git a/src/digest/digest.cr b/src/digest/digest.cr index c55d2a84ead1..6ddfec3af84c 100644 --- a/src/digest/digest.cr +++ b/src/digest/digest.cr @@ -21,7 +21,7 @@ abstract class Digest # The modules adds convenient class methods as `Digest::MD5.digest`, `Digest::MD5.hexdigest`. module ClassMethods # Returns the hash of *data*. *data* must respond to `#to_slice`. - def digest(data) : Bytes + def digest(data : String) : Bytes digest do |ctx| ctx.update(data.to_slice) end @@ -52,7 +52,7 @@ abstract class Digest # # Digest::MD5.hexdigest("foo") # => "acbd18db4cc2f85cedef654fccc4a4d8" # ``` - def hexdigest(data) : String + def hexdigest(data : String | Slice(UInt8) | StaticArray(UInt8, 1)) : String hexdigest &.update(data) end @@ -85,7 +85,7 @@ abstract class Digest # # Digest::SHA1.base64digest("foo") # => "C+7Hteo/D9vJXQ3UfzxbwnXaijM=" # ``` - def base64digest(data) : String + def base64digest(data : String) : String base64digest &.update(data) end @@ -113,7 +113,7 @@ abstract class Digest @finished = false - def update(data) : self + def update(data : StaticArray(UInt8, 16) | String | StaticArray(UInt8, 1)) : self update data.to_slice end @@ -229,7 +229,7 @@ abstract class Digest end # :ditto: - def <<(data) : self + def <<(data : File | Slice(UInt8) | String | IO::FileDescriptor) : self update(data) end diff --git a/src/dir.cr b/src/dir.cr index 121a77172789..5754704091c2 100644 --- a/src/dir.cr +++ b/src/dir.cr @@ -284,14 +284,14 @@ class Dir # Dir.mkdir("testdir") # Dir.exists?("testdir") # => true # ``` - def self.mkdir(path : Path | String, mode = 0o777) : Nil + def self.mkdir(path : Path | String, mode : Int32 = 0o777) : Nil Crystal::System::Dir.create(path.to_s, mode) end # Creates a new directory at the given path, including any non-existing # intermediate directories. The linux-style permission mode can be specified, # with a default of 777 (0o777). - def self.mkdir_p(path : Path | String, mode = 0o777) : Nil + def self.mkdir_p(path : Path | String, mode : Int32 = 0o777) : Nil return if Dir.exists?(path) path = Path.new path diff --git a/src/dir/glob.cr b/src/dir/glob.cr index 8b49bf3cb307..af7f2bb41889 100644 --- a/src/dir/glob.cr +++ b/src/dir/glob.cr @@ -64,7 +64,7 @@ class Dir # equivalent to # `match: File::MatchOptions.glob_default | File::MatchOptions::DotFiles`. @[Deprecated("Use the overload with a `match` parameter instead")] - def self.glob(*patterns : Path | String, match_hidden, follow_symlinks = false) : Array(String) + def self.glob(*patterns : Path | String, match_hidden : Bool, follow_symlinks : Bool = false) : Array(String) glob(patterns, match: match_hidden_to_options(match_hidden), follow_symlinks: follow_symlinks) end @@ -127,7 +127,7 @@ class Dir end end - private def self.match_hidden_to_options(match_hidden) + private def self.match_hidden_to_options(match_hidden : Bool) : File::MatchOptions options = File::MatchOptions.glob_default options |= File::MatchOptions::DotFiles if match_hidden options @@ -138,7 +138,7 @@ class Dir record DirectoriesOnly record ConstantEntry, path : String, merged : Bool record EntryMatch, pattern : String do - def matches?(string) : Bool + def matches?(string : String) : Bool File.match?(pattern, string) end end @@ -146,7 +146,7 @@ class Dir record ConstantDirectory, path : String record RootDirectory record DirectoryMatch, pattern : String do - def matches?(string) : Bool + def matches?(string : String) : Bool File.match?(pattern, string) end end @@ -173,7 +173,7 @@ class Dir end end - private def self.compile(pattern) + private def self.compile(pattern : String) : Array(Array(Dir::Globber::ConstantDirectory | Dir::Globber::ConstantEntry | Dir::Globber::DirectoriesOnly | Dir::Globber::DirectoryMatch | Dir::Globber::EntryMatch | Dir::Globber::RecursiveDirectories | Dir::Globber::RootDirectory)) expanded_patterns = [] of String expand_brace_pattern(pattern, expanded_patterns) @@ -182,7 +182,7 @@ class Dir end end - private def self.single_compile(glob) + private def self.single_compile(glob : String) : Array(Dir::Globber::ConstantDirectory | Dir::Globber::ConstantEntry | Dir::Globber::DirectoriesOnly | Dir::Globber::DirectoryMatch | Dir::Globber::EntryMatch | Dir::Globber::RecursiveDirectories | Dir::Globber::RootDirectory) list = [] of PatternType return list if glob.empty? @@ -225,7 +225,7 @@ class Dir list end - private def self.constant_entry?(file) + private def self.constant_entry?(file : String) : Bool file.each_char do |char| return false if char.in?('*', '?', '[', '\\') end @@ -378,11 +378,11 @@ class Dir end end - private def self.root + private def self.root : String Path[Dir.current].anchor.not_nil!.to_s end - private def self.dir?(path, follow_symlinks) + private def self.dir?(path : String, follow_symlinks : Bool) : Bool if info = File.info?(path, follow_symlinks: follow_symlinks) info.type.directory? else @@ -390,7 +390,7 @@ class Dir end end - private def self.join(path, entry) + private def self.join(path : String?, entry : String) : String return entry unless path return "#{root}#{entry}" if path == File::SEPARATOR_STRING @@ -407,7 +407,7 @@ class Dir rescue exc : File::NotFoundError end - private def self.read_entry(dir) + private def self.read_entry(dir : Dir) : Crystal::System::Dir::Entry? return unless dir # By doing this we get an Entry struct which already tells us @@ -416,7 +416,7 @@ class Dir Crystal::System::Dir.next_entry(dir.@dir, dir.path) end - private def self.matches_file?(entry, match) + private def self.matches_file?(entry : Crystal::System::Dir::Entry, match : File::MatchOptions) : Bool return false if entry.name.starts_with?('.') && !match.dot_files? return false if entry.native_hidden? && !match.native_hidden? return false if entry.os_hidden? && !match.os_hidden? @@ -425,7 +425,7 @@ class Dir # :nodoc: # FIXME: The expansion mechanism does not work for complex brace patterns. - private def self.expand_brace_pattern(pattern : String, expanded) : Array(String)? + private def self.expand_brace_pattern(pattern : String, expanded : Array(String)) : Array(String)? reader = Char::Reader.new(pattern) lbrace = nil diff --git a/src/ecr/lexer.cr b/src/ecr/lexer.cr index 81fedac17087..bb6508785d5e 100644 --- a/src/ecr/lexer.cr +++ b/src/ecr/lexer.cr @@ -29,12 +29,12 @@ class ECR::Lexer getter line_number : Int32 getter column_number : Int32 - def initialize(message, @line_number, @column_number) + def initialize(message : String, @line_number : Int32, @column_number : Int32) super(message) end end - def initialize(string) + def initialize(string : String) @reader = Char::Reader.new(string) @token = Token.new @line_number = 1 @@ -78,7 +78,7 @@ class ECR::Lexer consume_string end - private def consume_string + private def consume_string : ECR::Lexer::Token start_pos = current_pos while true case current_char @@ -102,7 +102,7 @@ class ECR::Lexer @token end - private def consume_control(is_output, is_escape, suppress_leading) + private def consume_control(is_output : Bool?, is_escape : Bool?, suppress_leading : Bool) : ECR::Lexer::Token start_pos = current_pos while true case current_char @@ -158,7 +158,7 @@ class ECR::Lexer @token end - private def setup_control_token(start_pos, is_escape, suppress_leading, suppress_trailing) + private def setup_control_token(start_pos : Int32, is_escape : Bool?, suppress_leading : Bool, suppress_trailing : Bool) : Char @token.suppress_leading = !is_escape && suppress_leading @token.suppress_trailing = !is_escape && suppress_trailing @token.value = @@ -174,41 +174,41 @@ class ECR::Lexer next_char end - private def copy_location_info_to_token + private def copy_location_info_to_token : Int32 @token.line_number = @line_number @token.column_number = @column_number end - private def current_char + private def current_char : Char @reader.current_char end - private def next_char + private def next_char : Char @column_number += 1 next_char_no_column_increment end - private def next_char_no_column_increment + private def next_char_no_column_increment : Char @reader.next_char end - private def peek_next_char + private def peek_next_char : Char @reader.peek_next_char end - private def current_pos + private def current_pos : Int32 @reader.pos end - private def string_range(start_pos) + private def string_range(start_pos : Int32) : String string_range(start_pos, current_pos) end - private def string_range(start_pos, end_pos) + private def string_range(start_pos : Int32, end_pos : Int32) : String @reader.string.byte_slice(start_pos, end_pos - start_pos) end - private def raise(message : String) + private def raise(message : String) : Nil raise SyntaxException.new(message, @line_number, @column_number) end end diff --git a/src/ecr/processor.cr b/src/ecr/processor.cr index 786879e94273..058801dd56e0 100644 --- a/src/ecr/processor.cr +++ b/src/ecr/processor.cr @@ -11,7 +11,7 @@ module ECR end # :nodoc: - def process_string(string, filename, buffer_name = DefaultBufferName) : String + def process_string(string : String, filename : String, buffer_name : String = DefaultBufferName) : String lexer = Lexer.new string token = lexer.next_token @@ -65,7 +65,7 @@ module ECR end end - private def suppress_leading_indentation(token, string) + private def suppress_leading_indentation(token : ECR::Lexer::Token, string : String) : String # To suppress leading indentation we find the last index of a newline and # then check if all chars after that are whitespace. # We use a Char::Reader for this for maximum efficiency. @@ -85,14 +85,14 @@ module ECR string end - private def suppress_trailing_whitespace(token, suppress_trailing) + private def suppress_trailing_whitespace(token : ECR::Lexer::Token, suppress_trailing : Bool) : String? if suppress_trailing && token.type.string? newline_index = token.value.index('\n') token.value = token.value[newline_index + 1..-1] if newline_index end end - private def append_loc(str, filename, line_number, column_number) + private def append_loc(str : String::Builder, filename : String, line_number : Int32, column_number : Int32) : String::Builder str << %(#= 0 %} # %rdi , %rsi asm(" diff --git a/src/fiber/stack.cr b/src/fiber/stack.cr index 9666b506db0c..2fde3633c5a9 100644 --- a/src/fiber/stack.cr +++ b/src/fiber/stack.cr @@ -5,7 +5,7 @@ class Fiber getter bottom : Void* getter? reusable : Bool - def initialize(@pointer, @bottom, *, @reusable = false) + def initialize(@pointer : Pointer(Void), @bottom : Pointer(Void), *, @reusable : Bool = false) end def first_addressable_pointer : Void** diff --git a/src/fiber/stack_pool.cr b/src/fiber/stack_pool.cr index 4a36f47f4abd..f1bf302d4803 100644 --- a/src/fiber/stack_pool.cr +++ b/src/fiber/stack_pool.cr @@ -24,7 +24,7 @@ class Fiber {% end %} end - def finalize + def finalize : Nil @deque.each do |stack| Crystal::System::Fiber.free_stack(stack.pointer, STACK_SIZE) end @@ -32,7 +32,7 @@ class Fiber # Removes and frees at most *count* stacks from the top of the pool, # returning memory to the operating system. - def collect(count = lazy_size // 2) : Nil + def collect(count : Int32 = lazy_size // 2) : Nil count.times do if stack = shift? Crystal::System::Fiber.free_stack(stack.pointer, STACK_SIZE) @@ -42,7 +42,7 @@ class Fiber end end - def collect_loop(every = 5.seconds) : Nil + def collect_loop(every : Time::Span = 5.seconds) : Nil loop do sleep every collect @@ -77,7 +77,7 @@ class Fiber @deque.size end - private def shift? + private def shift? : Fiber::Stack? {% if flag?(:execution_context) %} @lock.sync { @deque.shift? } unless @deque.empty? {% else %} @@ -85,7 +85,7 @@ class Fiber {% end %} end - private def pop? + private def pop? : Fiber::Stack? {% if flag?(:execution_context) %} if (stack = Thread.current.dead_fiber_stack?) && stack.reusable? stack diff --git a/src/file/error.cr b/src/file/error.cr index 355496488bc4..c242b04adaa4 100644 --- a/src/file/error.cr +++ b/src/file/error.cr @@ -8,7 +8,7 @@ class File::Error < IO::Error target.not_nil! end - private def self.new_from_os_error(message, os_error, **opts) + private def self.new_from_os_error(message : String, os_error : Errno, **opts) : File::Error case os_error when Errno::ENOENT, WinError::ERROR_FILE_NOT_FOUND, WinError::ERROR_PATH_NOT_FOUND File::NotFoundError.new(message, **opts) @@ -23,15 +23,15 @@ class File::Error < IO::Error end end - def initialize(message, *, file : String | Path, @other : String? = nil) + def initialize(message : String, *, file : String | Path, @other : String? = nil) super message, target: file end - protected def self.build_message(message, *, file : String) : String + protected def self.build_message(message : String, *, file : String) : String "#{message}: '#{file.inspect_unquoted}'" end - protected def self.build_message(message, *, file : String, other : String) : String + protected def self.build_message(message : String, *, file : String, other : String) : String "#{message}: '#{file.inspect_unquoted}' -> '#{other.inspect_unquoted}'" end diff --git a/src/file/info.cr b/src/file/info.cr index ea5ed2ac82f6..0784d63ccead 100644 --- a/src/file/info.cr +++ b/src/file/info.cr @@ -56,7 +56,7 @@ class File OwnerRead = 0o400 OwnerAll = 0o700 - def self.new(int : Int) + def self.new(int : Int) : File::Permissions new(int.to_i16) end @@ -127,13 +127,13 @@ class File # Returns true if this `Info` represents a standard file. Shortcut for # `type.file?`. - def file? + def file? : Bool type.file? end # Returns true if this `Info` represents a directory. Shortcut for # `type.directory?`. - def directory? + def directory? : Bool type.directory? end diff --git a/src/file/tempfile.cr b/src/file/tempfile.cr index e1b764f35dbf..6e67405d81a2 100644 --- a/src/file/tempfile.cr +++ b/src/file/tempfile.cr @@ -13,7 +13,7 @@ class File # user-provided values that would result in navigating the directory tree. # # The path will be placed in *dir* which defaults to the standard temporary directory `Dir.tempdir`. - def self.tempname(prefix : String?, suffix : String?, *, dir : String = Dir.tempdir) + def self.tempname(prefix : String?, suffix : String?, *, dir : String = Dir.tempdir) : String name = String.build do |io| if prefix io << prefix @@ -41,7 +41,7 @@ class File # File.tempname # => "/tmp/20171206-1234-449386" # File.tempname(".sock") # => "/tmp/20171206-1234-449386.sock" # ``` - def self.tempname(suffix : String? = nil, *, dir : String = Dir.tempdir) + def self.tempname(suffix : String? = nil, *, dir : String = Dir.tempdir) : String tempname(prefix: nil, suffix: suffix, dir: dir) end @@ -63,7 +63,7 @@ class File # *encoding* and *invalid* are passed to `IO#set_encoding`. # # It is the caller's responsibility to remove the file when no longer needed. - def self.tempfile(prefix : String?, suffix : String?, *, dir : String = Dir.tempdir, encoding = nil, invalid = nil) + def self.tempfile(prefix : String?, suffix : String?, *, dir : String = Dir.tempdir, encoding : Nil = nil, invalid : Nil = nil) : File fileno, path = Crystal::System::File.mktemp(prefix, suffix, dir) new(path, fileno, blocking: true, encoding: encoding, invalid: invalid) end @@ -86,7 +86,7 @@ class File # *encoding* and *invalid* are passed to `IO#set_encoding`. # # It is the caller's responsibility to remove the file when no longer needed. - def self.tempfile(suffix : String? = nil, *, dir : String = Dir.tempdir, encoding = nil, invalid = nil) + def self.tempfile(suffix : String? = nil, *, dir : String = Dir.tempdir, encoding : Nil = nil, invalid : Nil = nil) : File tempfile(prefix: nil, suffix: suffix, dir: dir, encoding: encoding, invalid: invalid) end diff --git a/src/file_utils.cr b/src/file_utils.cr index 292d911b1630..91774db423c5 100644 --- a/src/file_utils.cr +++ b/src/file_utils.cr @@ -124,7 +124,7 @@ module FileUtils cp_recursive(src_path, dest_path) end - private def cp_recursive(src_path : Path | String, dest_path : Path | String) + private def cp_recursive(src_path : Path | String, dest_path : Path | String) : Nil if Dir.exists?(src_path) Dir.mkdir(dest_path) unless Dir.exists?(dest_path) Dir.each_child(src_path) do |entry| @@ -257,7 +257,7 @@ module FileUtils # ``` # # NOTE: Alias of `Dir.mkdir` - def mkdir(path : Path | String, mode = 0o777) : Nil + def mkdir(path : Path | String, mode : Int32 = 0o777) : Nil Dir.mkdir(path, mode) end @@ -269,7 +269,7 @@ module FileUtils # # FileUtils.mkdir(["foo", "bar"]) # ``` - def mkdir(paths : Enumerable(Path | String), mode = 0o777) : Nil + def mkdir(paths : Enumerable(Path | String), mode : Int32 = 0o777) : Nil paths.each do |path| Dir.mkdir(path, mode) end @@ -286,7 +286,7 @@ module FileUtils # ``` # # NOTE: Alias of `Dir.mkdir_p` - def mkdir_p(path : Path | String, mode = 0o777) : Nil + def mkdir_p(path : Path | String, mode : Int32 = 0o777) : Nil Dir.mkdir_p(path, mode) end @@ -299,7 +299,7 @@ module FileUtils # # FileUtils.mkdir_p(["foo", "bar", "baz", "dir1", "dir2", "dir3"]) # ``` - def mkdir_p(paths : Enumerable(Path | String), mode = 0o777) : Nil + def mkdir_p(paths : Enumerable(Path | String), mode : Int32 = 0o777) : Nil paths.each do |path| Dir.mkdir_p(path, mode) end diff --git a/src/float/fast_float/fast_table.cr b/src/float/fast_float/fast_table.cr index a2c2b2e9d1c9..c59d8fa30e3a 100644 --- a/src/float/fast_float/fast_table.cr +++ b/src/float/fast_float/fast_table.cr @@ -28,7 +28,7 @@ module Float::FastFloat # in LLVM, which makes LLVM really slow. The compiler should # try to avoid/reuse temporary allocas. # Explanation: https://github.com/crystal-lang/crystal/issues/4516#issuecomment-306226171 - private def self.put(array, value) : Nil + private def self.put(array : Array(UInt64), value : UInt64) : Nil array << value end diff --git a/src/float/printer.cr b/src/float/printer.cr index 8fa64dd5072c..eb47a2d3a6ce 100644 --- a/src/float/printer.cr +++ b/src/float/printer.cr @@ -16,7 +16,7 @@ module Float::Printer # # *point_range* designates the boundaries of scientific notation which is used # for all values whose decimal point position is outside that range. - def shortest(v : Float::Primitive, io : IO, *, point_range = -3..15) : Nil + def shortest(v : Float::Primitive, io : IO, *, point_range : Range(Nil, Nil) | Range(Int32, Int32) = -3..15) : Nil check_finite_float(v, io) do |pos_v| if pos_v.zero? io << "0.0" diff --git a/src/float/printer/cached_powers.cr b/src/float/printer/cached_powers.cr index 71139f5bf5fa..0bc3b5b9f38f 100644 --- a/src/float/printer/cached_powers.cr +++ b/src/float/printer/cached_powers.cr @@ -141,7 +141,7 @@ module Float::Printer::CachedPowers Pow10Cache = {0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000} - def self.largest_pow10(n, n_bits) : {Int32, Int32} + def self.largest_pow10(n : UInt32, n_bits : Int32) : {Int32, Int32} # 1233/4096 is approximately 1/lg(10). # We increment to skip over the first entry in the powers cache. guess = ((n_bits + 1) * 1233 >> 12) + 1 @@ -154,7 +154,7 @@ module Float::Printer::CachedPowers # Returns a cached power-of-ten with a binary exponent in the range # around *exp* (boundaries included). - def self.get_cached_power_for_binary_exponent(exp) : {DiyFP, Int32} + def self.get_cached_power_for_binary_exponent(exp : Int32) : {DiyFP, Int32} min_exp = MIN_TARGET_EXP - (exp + DiyFP::SIGNIFICAND_SIZE) max_exp = MAX_TARGET_EXP - (exp + DiyFP::SIGNIFICAND_SIZE) k = ((min_exp + DiyFP::SIGNIFICAND_SIZE - 1) * D_1_LOG2_10).ceil diff --git a/src/float/printer/dragonbox.cr b/src/float/printer/dragonbox.cr index 65e090e5d0cc..fc29aaee2842 100644 --- a/src/float/printer/dragonbox.cr +++ b/src/float/printer/dragonbox.cr @@ -116,17 +116,17 @@ module Float::Printer::Dragonbox # Utilities for fast log computation. private module Log - def self.floor_log10_pow2(e : Int) + def self.floor_log10_pow2(e : Int) : Int32 # Precondition: `-2620 <= e <= 2620` (e &* 315653) >> 20 end - def self.floor_log2_pow10(e : Int) + def self.floor_log2_pow10(e : Int) : Int32 # Precondition: `-1233 <= e <= 1233` (e &* 1741647) >> 19 end - def self.floor_log10_pow2_minus_log10_4_over_3(e : Int) + def self.floor_log10_pow2_minus_log10_4_over_3(e : Int) : Int32 # Precondition: `-2985 <= e <= 2936` (e &* 631305 &- 261663) >> 21 end @@ -199,7 +199,7 @@ module Float::Printer::Dragonbox end # N == 1 - def self.check_divisibility_and_divide_by_pow10_k1(n : UInt32) + def self.check_divisibility_and_divide_by_pow10_k1(n : UInt32) : Tuple(UInt32, Bool) n &*= DIVIDE_BY_POW10_INFO_F32::MAGIC_NUMBER # Mask for the lowest (divisibility_check_bits)-bits. @@ -212,7 +212,7 @@ module Float::Printer::Dragonbox end # N == 2 - def self.check_divisibility_and_divide_by_pow10_k2(n : UInt32) + def self.check_divisibility_and_divide_by_pow10_k2(n : UInt32) : Tuple(UInt32, Bool) n &*= DIVIDE_BY_POW10_INFO_F64::MAGIC_NUMBER # Mask for the lowest (divisibility_check_bits)-bits. @@ -226,20 +226,20 @@ module Float::Printer::Dragonbox end private module ImplInfoMethods(D) - def extract_exponent_bits(u : D::CarrierUInt) + def extract_exponent_bits(u : D::CarrierUInt) : UInt32 exponent_bits_mask = ~(UInt32::MAX << D::EXPONENT_BITS) ((u >> D::SIGNIFICAND_BITS) & exponent_bits_mask).to_u32! end - def remove_exponent_bits(u : D::CarrierUInt, exponent_bits) + def remove_exponent_bits(u : D::CarrierUInt, exponent_bits : UInt32) : UInt32 | UInt64 u ^ (D::CarrierUInt.new!(exponent_bits) << D::SIGNIFICAND_BITS) end - def remove_sign_bit_and_shift(u : D::CarrierUInt) + def remove_sign_bit_and_shift(u : D::CarrierUInt) : UInt32 | UInt64 u << 1 end - def check_divisibility_and_divide_by_pow10(n : UInt32) + def check_divisibility_and_divide_by_pow10(n : UInt32) : Tuple(UInt32, Bool) {% if D::KAPPA == 1 %} Div.check_divisibility_and_divide_by_pow10_k1(n) {% elsif D::KAPPA == 2 %} diff --git a/src/float/printer/grisu3.cr b/src/float/printer/grisu3.cr index d68cf2b7b287..8de06ab1f766 100644 --- a/src/float/printer/grisu3.cr +++ b/src/float/printer/grisu3.cr @@ -54,7 +54,7 @@ module Float::Printer::Grisu3 # representable number to the input. # # Modifies the generated digits in the buffer to approach (round towards) *w*. - def round_weed(buffer_ptr, length, distance_too_high_w, unsafe_interval, rest, ten_kappa, unit) : Bool + def round_weed(buffer_ptr : Pointer(UInt8), length : Int32, distance_too_high_w : UInt64, unsafe_interval : UInt64, rest : UInt64, ten_kappa : UInt64, unit : UInt64) : Bool buffer = buffer_ptr.to_slice(128) small_distance = distance_too_high_w - unit big_distance = distance_too_high_w + unit @@ -209,7 +209,7 @@ module Float::Printer::Grisu3 # represent 'w' we can stop. Everything inside the interval low - high # represents w. However we have to pay attention to low, high and w's # imprecision. - def digit_gen(low : DiyFP, w : DiyFP, high : DiyFP, buffer_p) : {Bool, Int32, Int32} + def digit_gen(low : DiyFP, w : DiyFP, high : DiyFP, buffer_p : Pointer(UInt8)) : {Bool, Int32, Int32} buffer = buffer_p.to_slice(128) # low, w and high are imprecise, but by less than one ulp (unit in the last # place). @@ -314,7 +314,7 @@ module Float::Printer::Grisu3 # The last digit will be closest to the actual *v*. That is, even if several # digits might correctly yield *v* when read again, the closest will be # computed. - def grisu3(v : Float64 | Float32, buffer_p) : {Bool, Int32, Int32} + def grisu3(v : Float64 | Float32, buffer_p : Pointer(UInt8)) : {Bool, Int32, Int32} w = DiyFP.from_f_normalized(v) # boundary_minus and boundary_plus are the boundaries between v and its diff --git a/src/float/printer/ieee.cr b/src/float/printer/ieee.cr index b56b3d5bb454..b36586cb8676 100644 --- a/src/float/printer/ieee.cr +++ b/src/float/printer/ieee.cr @@ -82,11 +82,11 @@ module Float::Printer::IEEE special?(d32) && (d32 & SIGNIFICAND_MASK_32 == 0) end - def nan?(d64 : UInt64) + def nan?(d64 : UInt64) : Bool special?(d64) && (d64 & SIGNIFICAND_MASK_64 != 0) end - def nan?(d32 : UInt32) + def nan?(d32 : UInt32) : Bool special?(d32) && (d32 & SIGNIFICAND_MASK_32 != 0) end @@ -176,13 +176,13 @@ module Float::Printer::IEEE (d32 & EXPONENT_MASK_32) == 0 end - private def exponent(d64 : UInt64) + private def exponent(d64 : UInt64) : Int32 return DENORMAL_EXPONENT_64 if denormal?(d64) biased_e = ((d64 & EXPONENT_MASK_64) >> PHYSICAL_SIGNIFICAND_SIZE_64).to_i biased_e - EXPONENT_BIAS_64 end - private def exponent(d32 : UInt32) + private def exponent(d32 : UInt32) : Int32 return DENORMAL_EXPONENT_32 if denormal?(d32) biased_e = ((d32 & EXPONENT_MASK_32) >> PHYSICAL_SIGNIFICAND_SIZE_32).to_i biased_e - EXPONENT_BIAS_32 diff --git a/src/float/printer/ryu_printf.cr b/src/float/printer/ryu_printf.cr index feffb98fdb0e..868b49c8f007 100644 --- a/src/float/printer/ryu_printf.cr +++ b/src/float/printer/ryu_printf.cr @@ -63,12 +63,12 @@ module Float::Printer::RyuPrintf end # Returns true if value is divisible by 5^p. - private def self.multiple_of_power_of_5?(value : UInt64, p : UInt32) + private def self.multiple_of_power_of_5?(value : UInt64, p : UInt32) : Bool pow5_factor(value) >= p end # Returns true if value is divisible by 2^p. - private def self.multiple_of_power_of_2?(value : UInt64, p : UInt32) + private def self.multiple_of_power_of_2?(value : UInt64, p : UInt32) : Bool value & ~(UInt64::MAX << p) == 0 end @@ -103,7 +103,7 @@ module Float::Printer::RyuPrintf end # Returns the low 64 bits of the high 128 bits of the 256-bit product of a and b. - private def self.umul256_hi128_lo64(a_hi : UInt64, a_lo : UInt64, b_hi : UInt64, b_lo : UInt64) + private def self.umul256_hi128_lo64(a_hi : UInt64, a_lo : UInt64, b_hi : UInt64, b_lo : UInt64) : UInt64 b00_hi, _ = umul128(a_lo, b_lo) b01_hi, b01_lo = umul128(a_lo, b_hi) b10_hi, b10_lo = umul128(a_hi, b_lo) @@ -143,17 +143,17 @@ module Float::Printer::RyuPrintf uint128_mod1e9(shiftedhigh, shiftedlow) end - private def self.index_for_exponent(e : UInt32) + private def self.index_for_exponent(e : UInt32) : UInt32 (e &+ 15) // 16 end private ADDITIONAL_BITS_2 = 120 - private def self.pow10_bits_for_index(idx : UInt32) + private def self.pow10_bits_for_index(idx : UInt32) : UInt32 idx &* 16 &+ ADDITIONAL_BITS_2 end - private def self.length_for_index(idx : UInt32) + private def self.length_for_index(idx : UInt32) : UInt32 # +1 for ceil, +16 for mantissa, +8 to round up when dividing by 9 (log10_pow2(16 &* idx.to_i32!) &+ 25) // 9 end @@ -162,7 +162,7 @@ module Float::Printer::RyuPrintf # The caller has to guarantee that: # 10^(olength-1) <= digits < 10^olength # e.g., by passing `olength` as `decimalLength9(digits)`. - private def self.append_n_digits(olength : UInt32, digits : UInt32, result : UInt8*) + private def self.append_n_digits(olength : UInt32, digits : UInt32, result : UInt8*) : Pointer(UInt8) | UInt8 i = 0_u32 while digits >= 10000 c = digits &- 10000 &* (digits // 10000) @@ -191,7 +191,7 @@ module Float::Printer::RyuPrintf # dot '.' followed by the remaining digits. The caller has to guarantee that: # 10^(olength-1) <= digits < 10^olength # e.g., by passing `olength` as `decimalLength9(digits)`. - private def self.append_d_digits(olength : UInt32, digits : UInt32, result : UInt8*) + private def self.append_d_digits(olength : UInt32, digits : UInt32, result : UInt8*) : UInt8 i = 0_u32 while digits >= 10000 c = digits &- 10000 &* (digits // 10000) @@ -221,7 +221,7 @@ module Float::Printer::RyuPrintf # Convert `digits` to decimal and write the last `count` decimal digits to result. # If `digits` contains additional digits, then those are silently ignored. - private def self.append_c_digits(count : UInt32, digits : UInt32, result : UInt8*) + private def self.append_c_digits(count : UInt32, digits : UInt32, result : UInt8*) : UInt8? i = 0_u32 # Copy pairs of digits from DIGIT_TABLE. @@ -241,7 +241,7 @@ module Float::Printer::RyuPrintf # Convert `digits` to decimal and write the last 9 decimal digits to result. # If `digits` contains additional digits, then those are silently ignored. - private def self.append_nine_digits(digits : UInt32, result : UInt8*) + private def self.append_nine_digits(digits : UInt32, result : UInt8*) : UInt8? if digits == 0 Slice.new(result, 9).fill('0'.ord.to_u8!) return @@ -268,7 +268,7 @@ module Float::Printer::RyuPrintf EXPONENT_BITS = 11 # NOTE: in Crystal *d* must be positive and finite - private def self.extract_float(d : Float64) + private def self.extract_float(d : Float64) : Tuple(Int32, UInt64) bits = d.unsafe_as(UInt64) ieee_mantissa = bits & ~(UInt64::MAX << MANTISSA_BITS) @@ -285,7 +285,7 @@ module Float::Printer::RyuPrintf {e2, m2} end - def self.d2fixed_buffered_n(d : Float64, precision : UInt32, result : UInt8*) + def self.d2fixed_buffered_n(d : Float64, precision : UInt32, result : UInt8*) : Int32 e2, m2 = extract_float(d) index = 0 nonzero = false @@ -424,7 +424,7 @@ module Float::Printer::RyuPrintf index end - def self.d2exp_buffered_n(d : Float64, precision : UInt32, result : UInt8*) + def self.d2exp_buffered_n(d : Float64, precision : UInt32, result : UInt8*) : Int32 if d == 0 result[0] = '0'.ord.to_u8! index = 1 @@ -620,7 +620,7 @@ module Float::Printer::RyuPrintf # * https://github.com/ulfjack/ryu/pull/185/files # * https://github.com/microsoft/STL/blob/a8888806c6960f1687590ffd4244794c753aa819/stl/inc/charconv#L2324 # * https://github.com/llvm/llvm-project/blob/701f64790520790f75b1f948a752472d421ddaa3/libcxx/src/include/to_chars_floating_point.h#L836 - def self.d2gen_buffered_n(d : Float64, precision : UInt32, result : UInt8*, alternative : Bool = false) + def self.d2gen_buffered_n(d : Float64, precision : UInt32, result : UInt8*, alternative : Bool = false) : Tuple(Int32, Int32) if d == 0 result[0] = '0'.ord.to_u8! return {1, 0} @@ -682,21 +682,21 @@ module Float::Printer::RyuPrintf {(significand_last - result + (exponent_last - exponent_first)).to_i32!, extra_zeros.to_i32!} end - def self.d2fixed(d : Float64, precision : Int) + def self.d2fixed(d : Float64, precision : Int) : String String.new(2000) do |buffer| len = d2fixed_buffered_n(d, precision.to_u32, buffer) {len, len} end end - def self.d2exp(d : Float64, precision : Int) + def self.d2exp(d : Float64, precision : Int) : String String.new(2000) do |buffer| len = d2exp_buffered_n(d, precision.to_u32, buffer) {len, len} end end - def self.d2gen(d : Float64, precision : Int) + def self.d2gen(d : Float64, precision : Int) : String String.new(773) do |buffer| len, _ = d2gen_buffered_n(d, precision.to_u32, buffer) {len, len} diff --git a/src/float/printer/ryu_printf_table.cr b/src/float/printer/ryu_printf_table.cr index aa52d9b6fdd6..42386a95459d 100644 --- a/src/float/printer/ryu_printf_table.cr +++ b/src/float/printer/ryu_printf_table.cr @@ -11,7 +11,7 @@ module Float::Printer::RyuPrintf # in LLVM, which makes LLVM really slow. The compiler should # try to avoid/reuse temporary allocas. # Explanation: https://github.com/crystal-lang/crystal/issues/4516#issuecomment-306226171 - private def self.put(array : Array, values) : Nil + private def self.put(array : Array, values : UInt64) : Nil array << values end diff --git a/src/gc/boehm.cr b/src/gc/boehm.cr index 3541359b39a9..316b06607944 100644 --- a/src/gc/boehm.cr +++ b/src/gc/boehm.cr @@ -303,13 +303,13 @@ module GC end {% end %} - def self.collect + def self.collect : Nil Crystal.trace :gc, "collect" do LibGC.collect end end - def self.enable + def self.enable : Nil unless LibGC.is_disabled != 0 raise "GC is not disabled" end @@ -335,7 +335,7 @@ module GC # Nothing end - private def self.add_finalizer_impl(object : T) forall T + private def self.add_finalizer_impl(object : T) : Nil forall T LibGC.register_finalizer_ignore_self(object.as(Void*), ->(obj, data) { obj.as(T).finalize }, nil, nil, nil) @@ -347,16 +347,16 @@ module GC roots << Pointer(Void).new(object.object_id) end - def self.register_disappearing_link(pointer : Void**) + def self.register_disappearing_link(pointer : Void**) : Int32 base = LibGC.base(pointer.value) LibGC.general_register_disappearing_link(pointer, base) end - def self.is_heap_ptr(pointer : Void*) + def self.is_heap_ptr(pointer : Void*) : Bool LibGC.is_heap_ptr(pointer) != 0 end - def self.stats + def self.stats : GC::Stats LibGC.get_heap_usage_safe(out heap_size, out free_bytes, out unmapped_bytes, out bytes_since_gc, out total_bytes) # collections = LibGC.gc_no - 1 # bytes_found = LibGC.bytes_found @@ -372,7 +372,7 @@ module GC ) end - def self.prof_stats + def self.prof_stats : GC::ProfStats LibGC.get_prof_stats(out stats, sizeof(LibGC::ProfStats)) ProfStats.new( @@ -415,7 +415,7 @@ module GC {% end %} # :nodoc: - def self.current_thread_stack_bottom + def self.current_thread_stack_bottom : Tuple(Pointer(Void), Pointer(Void)) {% if LibGC.has_method?(:get_my_stackbottom) %} th = LibGC.get_my_stackbottom(out sb) {th, sb.mem_base} @@ -458,28 +458,28 @@ module GC end # :nodoc: - def self.unlock_read + def self.unlock_read : Nil {% if flag?(:preview_mt) %} @@lock.read_unlock {% end %} end # :nodoc: - def self.lock_write + def self.lock_write : Nil {% if flag?(:preview_mt) %} @@lock.write_lock {% end %} end # :nodoc: - def self.unlock_write + def self.unlock_write : Nil {% if flag?(:preview_mt) %} @@lock.write_unlock {% end %} end # :nodoc: - def self.push_stack(stack_top, stack_bottom) : Nil + def self.push_stack(stack_top : Pointer(Void), stack_bottom : Pointer(Void)) : Nil LibGC.push_all_eager(stack_top, stack_bottom) end diff --git a/src/hash.cr b/src/hash.cr index c145bda36309..fb9c516af26d 100644 --- a/src/hash.cr +++ b/src/hash.cr @@ -1797,7 +1797,7 @@ class Hash(K, V) # Hash.zip(["key1", "key2", "key3"], ["value1", "value2", "value3"]) # # => {"key1" => "value1", "key2" => "value2", "key3" => "value3"} # ``` - def self.zip(ary1 : Array(K), ary2 : Array(V)) + def self.zip(ary1 : Array(K), ary2 : Array(V)) : Hash(Int32, Char) hash = {} of K => V ary1.each_with_index do |key, i| hash[key] = ary2[i] diff --git a/src/html.cr b/src/html.cr index 2d1d69926153..cb2c0bb1cebb 100644 --- a/src/html.cr +++ b/src/html.cr @@ -121,7 +121,7 @@ module HTML end end - private def self.unescape(slice, io) + private def self.unescape(slice : Slice(UInt8), io : String::Builder) : Nil while bytesize = slice.index('&'.ord) io.write(slice[0, bytesize]) slice += bytesize &+ 1 @@ -133,7 +133,7 @@ module HTML io.write slice end - private def self.unescape_entity(ptr, io) + private def self.unescape_entity(ptr : Pointer(UInt8), io : String::Builder) : Pointer(UInt8) if '#' === ptr.value unescape_numbered_entity(ptr, io) else @@ -141,7 +141,7 @@ module HTML end end - private def self.unescape_numbered_entity(ptr, io) + private def self.unescape_numbered_entity(ptr : Pointer(UInt8), io : String::Builder) : Pointer(UInt8) start_ptr = ptr ptr += 1 @@ -194,7 +194,7 @@ module HTML end # see https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state - private def self.decode_codepoint(codepoint) + private def self.decode_codepoint(codepoint : UInt32) : Char? case codepoint when 0x80..0x9F # Replace characters from Windows-1252 with UTF-8 equivalents. @@ -218,7 +218,7 @@ module HTML end end - private def self.unescape_named_entity(ptr, io) + private def self.unescape_named_entity(ptr : Pointer(UInt8), io : String::Builder) : Pointer(UInt8) # Consume the maximum number of characters possible, with the # consumed characters matching one of the named references. start_ptr = ptr diff --git a/src/http/content.cr b/src/http/content.cr index 828015549d3b..4ec83cc2a2a5 100644 --- a/src/http/content.cr +++ b/src/http/content.cr @@ -8,12 +8,12 @@ module HTTP @continue_sent = false setter expects_continue : Bool = false - def close + def close : Nil @expects_continue = false super end - protected def ensure_send_continue + protected def ensure_send_continue : Bool? return unless @expects_continue return if @continue_sent @io << CONTINUE @@ -73,7 +73,7 @@ module HTTP @io.peek end - def skip(bytes_count) : Nil + def skip(bytes_count : Int32 | UInt32) : Nil ensure_send_continue @io.skip(bytes_count) end @@ -164,7 +164,7 @@ module HTTP peek end - def skip(bytes_count) : Nil + def skip(bytes_count : Int32 | UInt32) : Nil ensure_send_continue if bytes_count <= @chunk_remaining @io.skip(bytes_count) @@ -176,7 +176,7 @@ module HTTP # Checks if the last read consumed a chunk and we # need to start consuming the next one. - private def next_chunk + private def next_chunk : Bool? return if @chunk_remaining > 0 || @received_final_chunk # As soon as we finish reading a chunk we return, @@ -191,7 +191,7 @@ module HTTP end end - private def read_crlf + private def read_crlf : Nil char = @io.read_byte if char === '\r' char = @io.read_byte @@ -201,7 +201,7 @@ module HTTP end end - private def read_chunk_size + private def read_chunk_size : Int32 line = @io.read_line(@max_headers_size, chomp: true) if index = line.byte_index(';'.ord) @@ -213,7 +213,7 @@ module HTTP chunk_size.to_i?(16) || raise IO::Error.new("Invalid HTTP chunked content: invalid chunk size") end - private def read_trailer + private def read_trailer : Nil max_size = @max_headers_size while true diff --git a/src/http/formdata.cr b/src/http/formdata.cr index 7bb32b7519f0..eb01cd764fa9 100644 --- a/src/http/formdata.cr +++ b/src/http/formdata.cr @@ -130,7 +130,7 @@ module HTTP::FormData # `multipart/form-data` is not compatible with the original definition in # [RFC 2183](https://tools.ietf.org/html/rfc2183), but are instead specified # in [RFC 2388](https://tools.ietf.org/html/rfc2388). - def self.parse_content_disposition(content_disposition) : {String, FileMetadata} + def self.parse_content_disposition(content_disposition : String) : {String, FileMetadata} filename = nil creation_time = nil modification_time = nil diff --git a/src/http/headers.cr b/src/http/headers.cr index dacae7e9ec88..9a3612954858 100644 --- a/src/http/headers.cr +++ b/src/http/headers.cr @@ -39,7 +39,7 @@ struct HTTP::Headers true end - private def normalize_byte(byte) + private def normalize_byte(byte : UInt8) : Int32 | UInt8 char = byte.unsafe_chr return byte if char.ascii_lowercase? || char == '-' # Optimize the common case @@ -57,24 +57,24 @@ struct HTTP::Headers @hash = Hash(Key, String | Array(String)).new end - def []=(key, value : String) + def []=(key : String | HTTP::Headers::Key, value : String) : String check_invalid_header_content(value) @hash[wrap(key)] = value end - def []=(key, value : Array(String)) + def []=(key : String, value : Array(String)) : Array(String) value.each { |val| check_invalid_header_content val } @hash[wrap(key)] = value end - def [](key) : String + def [](key : String) : String values = @hash[wrap(key)] concat values end - def []?(key) : String? + def []?(key : String) : String? fetch(key, nil) end @@ -87,7 +87,7 @@ struct HTTP::Headers # headers = HTTP::Headers{"Connection" => "keep-alive, Upgrade"} # headers.includes_word?("Connection", "Upgrade") # => true # ``` - def includes_word?(key, word) : Bool + def includes_word?(key : String, word : String) : Bool return false if word.empty? values = @hash[wrap(key)]? @@ -104,7 +104,7 @@ struct HTTP::Headers end end - private def includes_word_in_header_value?(word, value) + private def includes_word_in_header_value?(word : String, value : String) : Bool offset = 0 while true start = value.index(word, offset) @@ -132,31 +132,31 @@ struct HTTP::Headers # headers.add("Connection", "Upgrade") # headers["Connection"] # => "keep-alive,Upgrade" # ``` - def add(key, value : String) : self + def add(key : String, value : String) : self check_invalid_header_content value unsafe_add(key, value) self end - def add(key, value : Array(String)) : self + def add(key : String, value : Array(String)) : self value.each { |val| check_invalid_header_content val } unsafe_add(key, value) self end - def add?(key, value : String) : Bool + def add?(key : String, value : String) : Bool return false unless valid_value?(value) unsafe_add(key, value) true end - def add?(key, value : Array(String)) : Bool + def add?(key : String, value : Array(String)) : Bool value.each { |val| return false unless valid_value?(val) } unsafe_add(key, value) true end - def fetch(key, default) : String? + def fetch(key : String, default : String?) : String? fetch(wrap(key)) { default } end @@ -165,7 +165,7 @@ struct HTTP::Headers values ? concat(values) : yield key end - def has_key?(key) : Bool + def has_key?(key : String) : Bool @hash.has_key? wrap(key) end @@ -173,12 +173,12 @@ struct HTTP::Headers @hash.empty? end - def delete(key) : String? + def delete(key : String) : String? values = @hash.delete wrap(key) values ? concat(values) : nil end - def merge!(other) : self + def merge!(other : Hash(String, String)) : self other.each do |key, value| self[wrap(key)] = value end @@ -199,7 +199,7 @@ struct HTTP::Headers # HTTP::Headers{"Foo" => "bar"} == HTTP::Headers{"Foo" => ["bar"]} # => true # HTTP::Headers{"Foo" => "bar"} == HTTP::Headers{"Foo" => "baz"} # => false # ``` - def ==(other : self) + def ==(other : self) : Bool # Adapts `Hash#==` to treat string values equal to a single element array. return false unless @hash.size == other.@hash.size @@ -247,11 +247,11 @@ struct HTTP::Headers end end - def get(key) : Array(String) + def get(key : HTTP::Headers::Key | String) : Array(String) cast @hash[wrap(key)] end - def get?(key) : Array(String)? + def get?(key : String) : Array(String)? @hash[wrap(key)]?.try { |value| cast(value) } end @@ -263,7 +263,7 @@ struct HTTP::Headers dup end - def clone + def clone : HTTP::Headers dup end @@ -339,13 +339,13 @@ struct HTTP::Headers end end - def valid_value?(value) : Bool + def valid_value?(value : String) : Bool invalid_value_char(value).nil? end forward_missing_to @hash - private def unsafe_add(key, value : String) + private def unsafe_add(key : String, value : String) : Array(String) | String key = wrap(key) existing = @hash[key]? if existing @@ -359,7 +359,7 @@ struct HTTP::Headers end end - private def unsafe_add(key, value : Array(String)) + private def unsafe_add(key : String, value : Array(String)) : Array(String) key = wrap(key) existing = @hash[key]? if existing @@ -375,23 +375,23 @@ struct HTTP::Headers end end - private def wrap(key) + private def wrap(key : String | HTTP::Headers::Key) : HTTP::Headers::Key key.is_a?(Key) ? key : Key.new(key) end - private def cast(value : String) + private def cast(value : String) : Array(String) [value] end - private def cast(value : Array(String)) + private def cast(value : Array(String)) : Array(String) value end - private def concat(values : String) + private def concat(values : String) : String values end - private def concat(values : Array(String)) + private def concat(values : Array(String)) : String case values.size when 0 "" @@ -402,13 +402,13 @@ struct HTTP::Headers end end - private def check_invalid_header_content(value) + private def check_invalid_header_content(value : String) : Nil if char = invalid_value_char(value) raise ArgumentError.new("Header content contains invalid character #{char.inspect}") end end - private def valid_char?(char) + private def valid_char?(char : Char) : Bool # According to RFC 7230, characters accepted as HTTP header # are '\t', ' ', all US-ASCII printable characters and # range from '\x80' to '\xff' (but the last is obsoleted.) @@ -419,7 +419,7 @@ struct HTTP::Headers true end - private def invalid_value_char(value) + private def invalid_value_char(value : String) : Char? value.each_byte do |byte| unless valid_char?(char = byte.unsafe_chr) return char diff --git a/src/http/log.cr b/src/http/log.cr index 7f16c4c63e90..77fd6fe04404 100644 --- a/src/http/log.cr +++ b/src/http/log.cr @@ -8,7 +8,7 @@ class HTTP::Client yield end - protected def emit_log(request) + protected def emit_log(request : HTTP::Request) : Nil Log.debug &.emit("Performing request", method: request.method, host: host, diff --git a/src/http/server/handler.cr b/src/http/server/handler.cr index 792879fc949d..069747fc084e 100644 --- a/src/http/server/handler.cr +++ b/src/http/server/handler.cr @@ -25,7 +25,7 @@ module HTTP::Handler abstract def call(context : HTTP::Server::Context) - def call_next(context : HTTP::Server::Context) + def call_next(context : HTTP::Server::Context) : Nil if next_handler = @next next_handler.call(context) else diff --git a/src/http/server/handlers/compress_handler.cr b/src/http/server/handlers/compress_handler.cr index e059b697649c..f0969a1fa1b1 100644 --- a/src/http/server/handlers/compress_handler.cr +++ b/src/http/server/handlers/compress_handler.cr @@ -10,7 +10,7 @@ class HTTP::CompressHandler include HTTP::Handler - def call(context) + def call(context : HTTP::Server::Context) : Nil {% if flag?(:without_zlib) %} call_next(context) {% else %} diff --git a/src/http/server/handlers/error_handler.cr b/src/http/server/handlers/error_handler.cr index f92b1a8d0c7a..916f85a12d15 100644 --- a/src/http/server/handlers/error_handler.cr +++ b/src/http/server/handlers/error_handler.cr @@ -14,7 +14,7 @@ class HTTP::ErrorHandler def initialize(@verbose : Bool = false, @log = Log.for("http.server")) end - def call(context) : Nil + def call(context : HTTP::Server::Context) : Nil call_next(context) rescue ex : HTTP::Server::ClientError @log.debug(exception: ex.cause) { ex.message } diff --git a/src/http/server/handlers/log_handler.cr b/src/http/server/handlers/log_handler.cr index 6aa82f6d911a..3bc8428f8fd1 100644 --- a/src/http/server/handlers/log_handler.cr +++ b/src/http/server/handlers/log_handler.cr @@ -10,7 +10,7 @@ class HTTP::LogHandler def initialize(@log = Log.for("http.server")) end - def call(context) : Nil + def call(context : HTTP::Server::Context) : Nil start = Time.monotonic begin @@ -36,7 +36,7 @@ class HTTP::LogHandler end end - private def elapsed_text(elapsed) + private def elapsed_text(elapsed : Time::Span) : String minutes = elapsed.total_minutes return "#{minutes.round(2)}m" if minutes >= 1 diff --git a/src/http/server/handlers/static_file_handler.cr b/src/http/server/handlers/static_file_handler.cr index 665f466c7e46..2f0150d727f5 100644 --- a/src/http/server/handlers/static_file_handler.cr +++ b/src/http/server/handlers/static_file_handler.cr @@ -41,7 +41,7 @@ class HTTP::StaticFileHandler new(public_dir, fallthrough: !!fallthrough, listing: !!listing) end - def call(context) : Nil + def call(context : HTTP::Server::Context) : Nil unless context.request.method.in?("GET", "HEAD") if @fallthrough call_next(context) @@ -180,7 +180,7 @@ class HTTP::StaticFileHandler end # TODO: Optimize without lots of intermediary strings - private def parse_ranges(header, file_size) + private def parse_ranges(header : String, file_size : Int64) : Array(Range(Int64, Int64))? ranges = [] of Range(Int64, Int64) header.split(",") do |range| start_string, dash, finish_string = range.lchop(' ').partition("-") @@ -224,7 +224,7 @@ class HTTP::StaticFileHandler path end - private def redirect_to(context, url) + private def redirect_to(context : HTTP::Server::Context, url : Path) : Nil context.response.redirect url.to_s end @@ -251,7 +251,7 @@ class HTTP::StaticFileHandler end end - private def etag(modification_time) + private def etag(modification_time : Time) : String %{W/"#{modification_time.to_unix}"} end @@ -265,7 +265,7 @@ class HTTP::StaticFileHandler ECR.def_to_s "#{__DIR__}/static_file_handler.html" end - private def directory_listing(io, request_path, path) + private def directory_listing(io : HTTP::Server::Response, request_path : Path, path : Path) : Nil DirectoryListing.new(request_path.to_s, path.to_s).to_s(io) end end diff --git a/src/http/server/handlers/websocket_handler.cr b/src/http/server/handlers/websocket_handler.cr index 8652a828c1e7..10847056d0c7 100644 --- a/src/http/server/handlers/websocket_handler.cr +++ b/src/http/server/handlers/websocket_handler.cr @@ -20,7 +20,7 @@ class HTTP::WebSocketHandler def initialize(&@proc : WebSocket, Server::Context ->) end - def call(context) : Nil + def call(context : HTTP::Server::Context) : Nil unless websocket_upgrade_request? context.request return call_next context end @@ -54,7 +54,7 @@ class HTTP::WebSocketHandler end end - private def websocket_upgrade_request?(request) + private def websocket_upgrade_request?(request : HTTP::Request) : Bool return false unless upgrade = request.headers["Upgrade"]? return false unless upgrade.compare("websocket", case_insensitive: true) == 0 diff --git a/src/http/server/response.cr b/src/http/server/response.cr index 4dd6968ac560..ccd5199b6569 100644 --- a/src/http/server/response.cr +++ b/src/http/server/response.cr @@ -27,7 +27,7 @@ class HTTP::Server property output : IO # :nodoc: - def version=(version : String) + def version=(version : String) : String check_headers @version = version end @@ -36,7 +36,7 @@ class HTTP::Server # body. If not set, the default value is 200 (OK). getter status : HTTP::Status - def status=(status : HTTP::Status) + def status=(status : HTTP::Status) : HTTP::Status check_headers @status = status end @@ -56,7 +56,7 @@ class HTTP::Server end # :nodoc: - def reset + def reset : Nil # This method is called by RequestProcessor to avoid allocating a new instance for each iteration. @headers.clear @cookies = nil @@ -68,13 +68,13 @@ class HTTP::Server end # Convenience method to set the `Content-Type` header. - def content_type=(content_type : String) + def content_type=(content_type : String) : String check_headers headers["Content-Type"] = content_type end # Convenience method to set the `Content-Length` header. - def content_length=(content_length : Int) + def content_length=(content_length : Int) : String check_headers headers["Content-Length"] = content_length.to_s end @@ -85,7 +85,7 @@ class HTTP::Server end # Convenience method to set the HTTP status code. - def status_code=(status_code : Int32) + def status_code=(status_code : Int32) : Int32 self.status = HTTP::Status.new(status_code) status_code end @@ -133,7 +133,7 @@ class HTTP::Server end # Sets the status message. - def status_message=(status_message : String?) + def status_message=(status_message : String?) : String check_headers @status_message = status_message end @@ -183,7 +183,7 @@ class HTTP::Server # # Raises `IO::Error` if the response is closed or headers were already # sent. - def redirect(location : String | URI, status : HTTP::Status = :found) + def redirect(location : String | URI, status : HTTP::Status = :found) : Nil check_headers self.status = status @@ -199,14 +199,14 @@ class HTTP::Server close end - private def check_headers + private def check_headers : Nil raise IO::Error.new "Closed stream" if @original_output.closed? if wrote_headers? raise IO::Error.new("Headers already sent") end end - protected def write_headers + protected def write_headers : Bool @io << @version << ' ' << @status.code << ' ' << status_message << "\r\n" headers.each do |name, values| values.each do |value| @@ -217,11 +217,11 @@ class HTTP::Server @wrote_headers = true end - protected def wrote_headers? + protected def wrote_headers? : Bool @wrote_headers end - protected def has_cookies? + protected def has_cookies? : Bool !@cookies.nil? end @@ -305,7 +305,7 @@ class HTTP::Server end end - private def ensure_headers_written + private def ensure_headers_written : Bool? unless response.wrote_headers? if response.has_cookies? response.cookies.add_response_headers(response.headers) diff --git a/src/http/status.cr b/src/http/status.cr index a02299f9fed7..02b17c2f905e 100644 --- a/src/http/status.cr +++ b/src/http/status.cr @@ -81,7 +81,7 @@ enum HTTP::Status # HTTP::Status.new(123) # => 123 # HTTP::Status.new(1000) # raises ArgumentError # ``` - def self.new(status_code : Int32) + def self.new(status_code : Int32) : HTTP::Status raise ArgumentError.new("Invalid HTTP status code: #{status_code}") unless 100 <= status_code <= 999 previous_def(status_code) end diff --git a/src/http/web_socket.cr b/src/http/web_socket.cr index e2d56b8a7610..1eeff5901771 100644 --- a/src/http/web_socket.cr +++ b/src/http/web_socket.cr @@ -6,7 +6,7 @@ class HTTP::WebSocket getter? closed = false # :nodoc: - def initialize(io : IO, sync_close = true) + def initialize(io : IO, sync_close : Bool = true) initialize(Protocol.new(io, sync_close: sync_close)) end @@ -34,7 +34,7 @@ class HTTP::WebSocket # HTTP::WebSocket.new( # URI.parse("ws://user:password@websocket.example.com/chat")) # Creates a new WebSocket to `websocket.example.com` with an HTTP basic auth Authorization header # ``` - def self.new(uri : URI | String, headers = HTTP::Headers.new) + def self.new(uri : URI | String, headers : HTTP::Headers = HTTP::Headers.new) : HTTP::WebSocket new(Protocol.new(uri, headers: headers)) end @@ -47,7 +47,7 @@ class HTTP::WebSocket # HTTP::WebSocket.new("websocket.example.com", "/chat") # Creates a new WebSocket to `websocket.example.com` # HTTP::WebSocket.new("websocket.example.com", "/chat", tls: true) # Creates a new WebSocket with TLS to `ẁebsocket.example.com` # ``` - def self.new(host : String, path : String, port = nil, tls : HTTP::Client::TLSContext = nil, headers = HTTP::Headers.new) + def self.new(host : String, path : String, port : Int32? = nil, tls : HTTP::Client::TLSContext = nil, headers : HTTP::Headers = HTTP::Headers.new) : HTTP::WebSocket new(Protocol.new(host, path, port, tls, headers)) end @@ -62,23 +62,23 @@ class HTTP::WebSocket end # Called when a text message is received. - def on_message(&@on_message : String ->) + def on_message(&@on_message : String ->) : Proc(String, Nil) end # Called when a binary message is received. - def on_binary(&@on_binary : Bytes ->) + def on_binary(&@on_binary : Bytes ->) : Proc(Slice(UInt8), Nil) end # Called when the connection is closed by the other party. - def on_close(&@on_close : CloseCode, String ->) + def on_close(&@on_close : CloseCode, String ->) : Proc(HTTP::WebSocket::CloseCode, String, Nil) end - protected def check_open + protected def check_open : Nil raise IO::Error.new "Closed socket" if closed? end # Sends a message payload (message). - def send(message) : Nil + def send(message : String) : Nil check_open @ws.send(message) end @@ -92,7 +92,7 @@ class HTTP::WebSocket end # Sends a PONG frame, which must be in response to a previously received PING frame from `#on_ping`. - def pong(message = nil) : Nil + def pong(message : String? = nil) : Nil check_open @ws.pong(message) end @@ -126,7 +126,7 @@ class HTTP::WebSocket # Sends a close frame, and closes the connection. # The close frame may contain a body (message) that indicates the reason for closing. - def close(code : CloseCode | Int? = nil, message = nil) : Nil + def close(code : CloseCode | Int? = nil, message : String? = nil) : Nil return if closed? @closed = true @ws.close(code, message) diff --git a/src/http/web_socket/close_code.cr b/src/http/web_socket/close_code.cr index 78b469051e4a..e6d2079c91a9 100644 --- a/src/http/web_socket/close_code.cr +++ b/src/http/web_socket/close_code.cr @@ -17,7 +17,7 @@ enum HTTP::WebSocket::CloseCode # Create a new instance with the given close code, or raise an # error if the close code given is not inside 0..4999. - def self.new(close_code : Int32) + def self.new(close_code : Int32) : HTTP::WebSocket::CloseCode unless 0 <= close_code <= 4999 raise ArgumentError.new("Invalid HTTP::WebSocket::CloseCode: #{close_code}") end diff --git a/src/humanize.cr b/src/humanize.cr index e3e4ed4428c7..c1b7cbc4c26e 100644 --- a/src/humanize.cr +++ b/src/humanize.cr @@ -92,7 +92,7 @@ struct Number end # :ditto: - def format(separator = '.', delimiter = ',', decimal_places : Int? = nil, *, group : Int = 3, only_significant : Bool = false) : String + def format(separator : Char | String = '.', delimiter : Char | String = ',', decimal_places : Int? = nil, *, group : Int = 3, only_significant : Bool = false) : String String.build do |io| format(io, separator, delimiter, decimal_places, group: group, only_significant: only_significant) end @@ -113,14 +113,14 @@ struct Number # ``` # Number.si_prefix(3) # => 'k' # ``` - def self.si_prefix(magnitude : Int, prefixes = SI_PREFIXES) : Char? + def self.si_prefix(magnitude : Int, prefixes : Tuple(Tuple(Char, Char, Char, Char, Char, Char, Char, Char, Char, Char), Tuple(Nil, Char, Char, Char, Char, Char, Char, Char, Char, Char, Char)) | Array(Array(Char)) = SI_PREFIXES) : Char? index = (magnitude // 3) prefixes = prefixes[magnitude < 0 ? 0 : 1] prefixes[index.clamp((-prefixes.size)..(prefixes.size - 1))] end # :nodoc: - def self.prefix_index(i : Int32, *, group : Int32 = 3, prefixes = SI_PREFIXES) : Int32 + def self.prefix_index(i : Int32, *, group : Int32 = 3, prefixes : Tuple(Tuple(Char, Char, Char, Char, Char, Char, Char, Char, Char, Char), Tuple(Nil, Char, Char, Char, Char, Char, Char, Char, Char, Char, Char)) | Array(Array(Char)) = SI_PREFIXES) : Int32 prefixes = prefixes[i < 0 ? 0 : 1] ((i - (i > 0 ? 1 : 0)) // group).clamp((-prefixes.size)..(prefixes.size - 1)) * group end @@ -155,7 +155,7 @@ struct Number # Users are encouraged to use a non-breaking space ('\u00A0') to prevent output being split across lines. # # See `Int#humanize_bytes` to format a file size. - def humanize(io : IO, precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, unit_separator = nil, prefixes : Indexable = SI_PREFIXES) : Nil + def humanize(io : IO, precision : Int32 = 3, separator : Char = '.', delimiter : Char = ',', *, base : Int32 = 10 ** 3, significant : Bool = true, unit_separator : Nil | Char | String | Int32 = nil, prefixes : Indexable = SI_PREFIXES) : Nil humanize(io, precision, separator, delimiter, base: base, significant: significant, unit_separator: unit_separator) do |magnitude, _| magnitude = Number.prefix_index(magnitude, prefixes: prefixes) {magnitude, Number.si_prefix(magnitude, prefixes)} @@ -163,7 +163,7 @@ struct Number end # :ditto: - def humanize(precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, unit_separator = nil, prefixes = SI_PREFIXES) : String + def humanize(precision : Int32 = 3, separator : Char = '.', delimiter : Char = ',', *, base : Int32 = 10 ** 3, significant : Bool = true, unit_separator : Char | String | Int32 | Nil = nil, prefixes : Proc(Int32, Float64, Tuple(Int32, String)) | Proc(Int32, Float64, Tuple(Int32, Char | String | Nil)) | Array(Array(Char)) | Tuple(Tuple(Char, Char, Char, Char, Char, Char, Char, Char, Char, Char), Tuple(Nil, Char, Char, Char, Char, Char, Char, Char, Char, Char, Char)) = SI_PREFIXES) : String String.build do |io| humanize(io, precision, separator, delimiter, base: base, significant: significant, unit_separator: unit_separator, prefixes: prefixes) end @@ -276,7 +276,7 @@ struct Number end # :ditto: - def humanize(io : IO, precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, unit_separator = nil, prefixes : Proc) : Nil + def humanize(io : IO, precision : Int32 = 3, separator : Char = '.', delimiter : Char = ',', *, base : Int32 = 10 ** 3, significant : Bool = true, unit_separator : Nil = nil, prefixes : Proc) : Nil humanize(io, precision, separator, delimiter, base: base, significant: significant, unit_separator: unit_separator) do |magnitude, number| prefixes.call(magnitude, number) end @@ -325,7 +325,7 @@ struct Int # ``` # # See `Number#humanize` for more details on the behaviour and arguments. - def humanize_bytes(io : IO, precision : Int = 3, separator = '.', *, significant : Bool = true, unit_separator = nil, format : BinaryPrefixFormat = :IEC) : Nil + def humanize_bytes(io : IO, precision : Int = 3, separator : Char = '.', *, significant : Bool = true, unit_separator : Char? = nil, format : BinaryPrefixFormat = :IEC) : Nil humanize(io, precision, separator, nil, base: 1024, significant: significant) do |magnitude| magnitude = Number.prefix_index(magnitude) @@ -344,7 +344,7 @@ struct Int end # :ditto: - def humanize_bytes(precision : Int = 3, separator = '.', *, significant : Bool = true, unit_separator = nil, format : BinaryPrefixFormat = :IEC) : String + def humanize_bytes(precision : Int = 3, separator : Char = '.', *, significant : Bool = true, unit_separator : Char? = nil, format : BinaryPrefixFormat = :IEC) : String String.build do |io| humanize_bytes(io, precision, separator, significant: significant, unit_separator: unit_separator, format: format) end diff --git a/src/ini.cr b/src/ini.cr index d9cea1c82e82..265d205a628e 100644 --- a/src/ini.cr +++ b/src/ini.cr @@ -5,7 +5,7 @@ module INI getter line_number : Int32 getter column_number : Int32 - def initialize(message, @line_number, @column_number) + def initialize(message : String, @line_number : Int32, @column_number : Int32) super "#{message} at line #{@line_number}, column #{@column_number}" end @@ -66,12 +66,12 @@ module INI # # INI.build({"foo" => {"a" => "1"}}, true) # => "[foo]\na = 1\n\n" # ``` - def self.build(ini, space : Bool = false) : String + def self.build(ini : Hash(String, Hash(String, Char) | Hash(String, Float64 | Int32) | Hash(String, String)) | NamedTuple(general: NamedTuple(log_level: Char), section1: NamedTuple(foo: Float64, bar: Int32), section2: NamedTuple("x.y.z": String)) | Hash(String, Hash(String, String)), space : Bool = false) : String String.build { |str| build str, ini, space } end # Appends INI data to the given IO. - def self.build(io : IO, ini, space : Bool = false) : Nil + def self.build(io : IO, ini : Hash(String, Hash(String, Char) | Hash(String, Float64 | Int32) | Hash(String, String)) | NamedTuple(general: NamedTuple(log_level: Char), section1: NamedTuple(foo: Float64, bar: Int32), section2: NamedTuple("x.y.z": String)) | Hash(String, Hash(String, String)), space : Bool = false) : Nil # An empty section has to be at first, to prevent being included in another one. ini[""]?.try &.each do |key, value| io << key << (space ? " = " : '=') << value << '\n' diff --git a/src/intrinsics.cr b/src/intrinsics.cr index 05c89a47f4c2..b6c834adccab 100644 --- a/src/intrinsics.cr +++ b/src/intrinsics.cr @@ -187,7 +187,7 @@ module Intrinsics ::LibIntrinsics.debugtrap end - def self.pause + def self.pause : Nil {% if flag?(:i386) || flag?(:x86_64) %} LibIntrinsics.pause {% elsif flag?(:aarch64) %} @@ -211,59 +211,59 @@ module Intrinsics LibIntrinsics.read_cycle_counter end - def self.bitreverse8(id) : UInt8 + def self.bitreverse8(id : UInt8 | Int8) : UInt8 LibIntrinsics.bitreverse8(id) end - def self.bitreverse16(id) : UInt16 + def self.bitreverse16(id : UInt16 | Int16) : UInt16 LibIntrinsics.bitreverse16(id) end - def self.bitreverse32(id) : UInt32 + def self.bitreverse32(id : UInt32 | Int32) : UInt32 LibIntrinsics.bitreverse32(id) end - def self.bitreverse64(id) : UInt64 + def self.bitreverse64(id : UInt64 | Int64) : UInt64 LibIntrinsics.bitreverse64(id) end - def self.bitreverse128(id) : UInt128 + def self.bitreverse128(id : UInt128 | Int128) : UInt128 LibIntrinsics.bitreverse128(id) end - def self.bswap16(id) : UInt16 + def self.bswap16(id : UInt16 | Int16) : UInt16 LibIntrinsics.bswap16(id) end - def self.bswap32(id) : UInt32 + def self.bswap32(id : UInt32 | Int32) : UInt32 LibIntrinsics.bswap32(id) end - def self.bswap64(id) : UInt64 + def self.bswap64(id : UInt64 | Int64) : UInt64 LibIntrinsics.bswap64(id) end - def self.bswap128(id) : UInt128 + def self.bswap128(id : UInt128 | Int128) : UInt128 LibIntrinsics.bswap128(id) end - def self.popcount8(src) : Int8 + def self.popcount8(src : Int8 | UInt8) : Int8 LibIntrinsics.popcount8(src) end - def self.popcount16(src) : Int16 + def self.popcount16(src : Int16 | UInt16) : Int16 LibIntrinsics.popcount16(src) end - def self.popcount32(src) : Int32 + def self.popcount32(src : UInt32 | Int32) : Int32 LibIntrinsics.popcount32(src) end - def self.popcount64(src) : Int64 + def self.popcount64(src : Int64 | UInt64) : Int64 LibIntrinsics.popcount64(src) end - def self.popcount128(src) + def self.popcount128(src : Int128 | UInt128) : Int128 LibIntrinsics.popcount128(src) end @@ -307,43 +307,43 @@ module Intrinsics ::LibIntrinsics.counttrailing128({{src}}, {{zero_is_undef}}) end - def self.fshl8(a, b, count) : UInt8 + def self.fshl8(a : Int8 | UInt8, b : Int8 | UInt8, count : Int8 | UInt8) : UInt8 LibIntrinsics.fshl8(a, b, count) end - def self.fshl16(a, b, count) : UInt16 + def self.fshl16(a : Int16 | UInt16, b : Int16 | UInt16, count : Int16 | UInt16) : UInt16 LibIntrinsics.fshl16(a, b, count) end - def self.fshl32(a, b, count) : UInt32 + def self.fshl32(a : UInt32 | Int32, b : UInt32 | Int32, count : UInt32 | Int32) : UInt32 LibIntrinsics.fshl32(a, b, count) end - def self.fshl64(a, b, count) : UInt64 + def self.fshl64(a : UInt64 | Int64, b : UInt64 | Int64, count : UInt64 | Int64) : UInt64 LibIntrinsics.fshl64(a, b, count) end - def self.fshl128(a, b, count) : UInt128 + def self.fshl128(a : Int128 | UInt128, b : Int128 | UInt128, count : Int128 | UInt128) : UInt128 LibIntrinsics.fshl128(a, b, count) end - def self.fshr8(a, b, count) : UInt8 + def self.fshr8(a : Int8 | UInt8, b : Int8 | UInt8, count : Int8 | UInt8) : UInt8 LibIntrinsics.fshr8(a, b, count) end - def self.fshr16(a, b, count) : UInt16 + def self.fshr16(a : Int16 | UInt16, b : Int16 | UInt16, count : Int16 | UInt16) : UInt16 LibIntrinsics.fshr16(a, b, count) end - def self.fshr32(a, b, count) : UInt32 + def self.fshr32(a : UInt32 | Int32, b : UInt32 | Int32, count : UInt32 | Int32) : UInt32 LibIntrinsics.fshr32(a, b, count) end - def self.fshr64(a, b, count) : UInt64 + def self.fshr64(a : Int64 | UInt64, b : Int64 | UInt64, count : Int64 | UInt64) : UInt64 LibIntrinsics.fshr64(a, b, count) end - def self.fshr128(a, b, count) : UInt128 + def self.fshr128(a : Int128 | UInt128, b : Int128 | UInt128, count : Int128 | UInt128) : UInt128 LibIntrinsics.fshr128(a, b, count) end diff --git a/src/io/argf.cr b/src/io/argf.cr index afa92c2a545b..ba05a5b28d48 100644 --- a/src/io/argf.cr +++ b/src/io/argf.cr @@ -44,7 +44,7 @@ class IO::ARGF < IO end end - private def peek_next + private def peek_next : Slice(UInt8)? if !@read_from_stdin && !@argv.empty? read_next_argv self.peek @@ -61,7 +61,7 @@ class IO::ARGF < IO @path || @argv.first? || "-" end - private def first_initialize + private def first_initialize : IO # This is the moment where we decide # whether we are going to use STDIN or ARGV @initialized = true @@ -73,7 +73,7 @@ class IO::ARGF < IO end end - private def read_from_current_io(current_io, slice) + private def read_from_current_io(current_io : IO, slice : Slice(UInt8)) : Int32 read_count = current_io.read slice if read_count.zero? unless @read_from_stdin @@ -89,7 +89,7 @@ class IO::ARGF < IO read_count end - private def read_next_argv + private def read_next_argv : File path = @path = @argv.shift @current_io = File.open(path) end diff --git a/src/io/delimited.cr b/src/io/delimited.cr index 4da7074b52bb..4754c3f40527 100644 --- a/src/io/delimited.cr +++ b/src/io/delimited.cr @@ -25,7 +25,7 @@ class IO::Delimited < IO # byte sequence *read_delimiter* (interpreted as UTF-8) is found. If # *sync_close* is set, calling `#close` calls `#close` on the underlying # `IO`. - def self.new(io : IO, read_delimiter : String, sync_close : Bool = false) + def self.new(io : IO, read_delimiter : String, sync_close : Bool = false) : IO::Delimited new(io, read_delimiter.to_slice, sync_close) end diff --git a/src/io/file_descriptor.cr b/src/io/file_descriptor.cr index 82c2b8ac232f..c10a09a3dce4 100644 --- a/src/io/file_descriptor.cr +++ b/src/io/file_descriptor.cr @@ -39,7 +39,7 @@ class IO::FileDescriptor < IO write_timeout end - def initialize(fd : Handle, blocking = nil, *, @close_on_finalize = true) + def initialize(fd : Handle, blocking : Bool? = nil, *, @close_on_finalize : Bool = true) @volatile_fd = Atomic.new(fd) @closed = true # This is necessary so we can reference `self` in `system_closed?` (in case of an exception) @@ -72,13 +72,13 @@ class IO::FileDescriptor < IO # This might be different from the internal file descriptor. For example, when # `STDIN` is a terminal on Windows, this returns `false` since the underlying # blocking reads are done on a completely separate thread. - def blocking + def blocking : Bool emulated = emulated_blocking? return emulated unless emulated.nil? system_blocking? end - def blocking=(value) + def blocking=(value : Bool) : Int32? self.system_blocking = value end @@ -86,7 +86,7 @@ class IO::FileDescriptor < IO system_close_on_exec? end - def close_on_exec=(value : Bool) + def close_on_exec=(value : Bool) : Bool self.system_close_on_exec = value end @@ -94,7 +94,7 @@ class IO::FileDescriptor < IO Crystal::System::FileDescriptor.fcntl(fd, cmd, arg) end - def fcntl(cmd, arg = 0) + def fcntl(cmd : Int32, arg : Int32 = 0) : Int32 Crystal::System::FileDescriptor.fcntl(fd, cmd, arg) end @@ -199,7 +199,7 @@ class IO::FileDescriptor < IO # # NOTE: Metadata is flushed even when *flush_metadata* is false on Windows # and DragonFly BSD. - def fsync(flush_metadata = true) : Nil + def fsync(flush_metadata : Bool = true) : Nil flush system_fsync(flush_metadata) end @@ -217,7 +217,7 @@ class IO::FileDescriptor < IO # Places a shared advisory lock. More than one process may hold a shared lock for a given file descriptor at a given time. # `IO::Error` is raised if *blocking* is set to `false` and an existing exclusive lock is set. - def flock_shared(blocking = true) : Nil + def flock_shared(blocking : Bool = true) : Nil system_flock_shared(blocking) end @@ -232,7 +232,7 @@ class IO::FileDescriptor < IO # Places an exclusive advisory lock. Only one process may hold an exclusive lock for a given file descriptor at a given time. # `IO::Error` is raised if *blocking* is set to `false` and any existing lock is set. - def flock_exclusive(blocking = true) : Nil + def flock_exclusive(blocking : Bool = true) : Nil system_flock_exclusive(blocking) end @@ -252,7 +252,7 @@ class IO::FileDescriptor < IO # Resource release can be disabled with `close_on_finalize = false`. # # This method is a no-op if the file descriptor has already been closed. - def finalize + def finalize : Nil return if closed? || !close_on_finalize? Crystal::EventLoop.remove(self) @@ -267,7 +267,7 @@ class IO::FileDescriptor < IO system_tty? end - def reopen(other : IO::FileDescriptor) + def reopen(other : IO::FileDescriptor) : File return other if self.fd == other.fd system_reopen(other) diff --git a/src/io/memory.cr b/src/io/memory.cr index bd486f0cbdc2..22f0115e8045 100644 --- a/src/io/memory.cr +++ b/src/io/memory.cr @@ -45,7 +45,7 @@ class IO::Memory < IO # io.read(slice) # => 6 # String.new(slice) # => "abcdef" # ``` - def initialize(slice : Bytes, writeable = true) + def initialize(slice : Bytes, writeable : Bool = true) @buffer = slice.to_unsafe @bytesize = @capacity = slice.size.to_i @pos = 0 @@ -65,7 +65,7 @@ class IO::Memory < IO # io.gets(2) # => "he" # io.print "hi" # raises IO::Error # ``` - def self.new(string : String) + def self.new(string : String) : IO::Memory new string.to_slice, writeable: false end @@ -123,7 +123,7 @@ class IO::Memory < IO end # :nodoc: - def gets(delimiter : Char, limit : Int32, chomp = false) : String? + def gets(delimiter : Char, limit : Int32, chomp : Bool = false) : String? return super if @encoding || delimiter.ord >= 128 check_open @@ -182,7 +182,7 @@ class IO::Memory < IO end # :nodoc: - def skip(bytes_count) : Nil + def skip(bytes_count : Int32 | UInt32) : Nil check_open available = @bytesize - @pos @@ -438,19 +438,19 @@ class IO::Memory < IO end end - private def check_writeable + private def check_writeable : Nil unless @writeable raise IO::Error.new "Read-only stream" end end - private def check_resizeable + private def check_resizeable : Nil unless @resizeable raise IO::Error.new "Non-resizeable stream" end end - private def increase_capacity_by(count) + private def increase_capacity_by(count : Int32) : Pointer(UInt8)? raise IO::EOFError.new if count >= Int32::MAX - bytesize new_bytesize = @pos + count @@ -462,7 +462,7 @@ class IO::Memory < IO resize_to_capacity(new_capacity) end - private def calculate_new_capacity(new_bytesize : Int32) + private def calculate_new_capacity(new_bytesize : Int32) : Int32 # If the new bytesize is bigger than 1 << 30, the next power of two would # be 1 << 31, which is out of range for Int32. # So we limit the capacity to Int32::MAX in order to be able to use the @@ -472,7 +472,7 @@ class IO::Memory < IO Math.pw2ceil(new_bytesize) end - private def resize_to_capacity(capacity) + private def resize_to_capacity(capacity : Int32) : Pointer(UInt8) @capacity = capacity @buffer = GC.realloc(@buffer, @capacity) end diff --git a/src/json.cr b/src/json.cr index f55aca854c00..2db984dc0a4d 100644 --- a/src/json.cr +++ b/src/json.cr @@ -123,7 +123,7 @@ module JSON getter line_number : Int32 getter column_number : Int32 - def initialize(message, @line_number, @column_number, cause = nil) + def initialize(message : String?, @line_number : Int32, @column_number : Int32, cause : Nil | Exception | JSON::ParseException = nil) super "#{message} at line #{@line_number}, column #{@column_number}", cause end diff --git a/src/json/any.cr b/src/json/any.cr index 61a4118ee932..e4ae1cab35e6 100644 --- a/src/json/any.cr +++ b/src/json/any.cr @@ -21,7 +21,7 @@ struct JSON::Any alias Type = Nil | Bool | Int64 | Float64 | String | Array(JSON::Any) | Hash(String, JSON::Any) # Reads a `JSON::Any` value from the given pull parser. - def self.new(pull : JSON::PullParser) + def self.new(pull : JSON::PullParser) : JSON::Any case pull.kind when .null? new pull.read_null @@ -58,13 +58,13 @@ struct JSON::Any end # :ditto: - def self.new(raw : Int) + def self.new(raw : Int) : JSON::Any # FIXME: Workaround for https://github.com/crystal-lang/crystal/issues/11645 new(raw.to_i64) end # :ditto: - def self.new(raw : Float) + def self.new(raw : Float) : JSON::Any # FIXME: Workaround for https://github.com/crystal-lang/crystal/issues/11645 new(raw.to_f64) end @@ -305,7 +305,7 @@ struct JSON::Any def_hash raw # :nodoc: - def to_json(json : JSON::Builder) + def to_json(json : JSON::Builder) : Nil raw.to_json(json) end @@ -319,7 +319,7 @@ struct JSON::Any end # Returns a new JSON::Any instance with the `raw` value `clone`ed. - def clone + def clone : JSON::Any JSON::Any.new(raw.clone) end end diff --git a/src/json/lexer.cr b/src/json/lexer.cr index 3e61179b9844..a7d1f719c30a 100644 --- a/src/json/lexer.cr +++ b/src/json/lexer.cr @@ -1,11 +1,11 @@ require "string_pool" abstract class JSON::Lexer - def self.new(string : String) + def self.new(string : String) : JSON::Lexer::StringBased StringBased.new(string) end - def self.new(io : IO) + def self.new(io : IO) : JSON::Lexer::IOBased IOBased.new(io) end @@ -76,7 +76,7 @@ abstract class JSON::Lexer @token end - private def skip_whitespace + private def skip_whitespace : Nil while whitespace?(current_char) if current_char == '\n' @line_number += 1 @@ -86,7 +86,7 @@ abstract class JSON::Lexer end end - private def whitespace?(char) + private def whitespace?(char : Char) : Bool case char when ' ', '\t', '\n', '\r' true @@ -95,7 +95,7 @@ abstract class JSON::Lexer end end - private def consume_true + private def consume_true : JSON::Token::Kind if next_char == 'r' && next_char == 'u' && next_char == 'e' next_char @token.kind = :true @@ -104,7 +104,7 @@ abstract class JSON::Lexer end end - private def consume_false + private def consume_false : JSON::Token::Kind if next_char == 'a' && next_char == 'l' && next_char == 's' && next_char == 'e' next_char @token.kind = :false @@ -113,7 +113,7 @@ abstract class JSON::Lexer end end - private def consume_null + private def consume_null : JSON::Token::Kind if next_char == 'u' && next_char == 'l' && next_char == 'l' next_char @token.kind = :null @@ -124,7 +124,7 @@ abstract class JSON::Lexer # Since we are skipping we don't care about a # string's contents, so we just move forward. - private def consume_string_skip + private def consume_string_skip : Nil while true case next_char when '\0' @@ -142,7 +142,7 @@ abstract class JSON::Lexer end end - private def consume_string_with_buffer + private def consume_string_with_buffer : String consume_string_with_buffer { } end @@ -173,7 +173,7 @@ abstract class JSON::Lexer end end - private def consume_string_escape_sequence + private def consume_string_escape_sequence : Char case char = next_char when '\\', '"', '/' char @@ -208,7 +208,7 @@ abstract class JSON::Lexer end end - private def read_hex_number + private def read_hex_number : Int32 hexnum = 0 4.times do char = next_char @@ -217,7 +217,7 @@ abstract class JSON::Lexer hexnum end - private def consume_number + private def consume_number : String number_start if current_char == '-' @@ -262,7 +262,7 @@ abstract class JSON::Lexer end end - private def consume_float + private def consume_float : String append_number_char char = next_char @@ -283,7 +283,7 @@ abstract class JSON::Lexer end end - private def consume_exponent + private def consume_exponent : String append_number_char char = next_char @@ -309,25 +309,25 @@ abstract class JSON::Lexer number_end end - private def next_char + private def next_char : Char @column_number += 1 next_char_no_column_increment end - private def next_char(kind : Token::Kind) + private def next_char(kind : Token::Kind) : Char @token.kind = kind next_char end - private def number_end + private def number_end : String @token.raw_value = number_string end - private def unexpected_char(char = current_char) + private def unexpected_char(char : Char = current_char) : Nil raise "Unexpected char '#{char}'" end - private def raise(msg) + private def raise(msg : String) : Nil ::raise ParseException.new(msg, @line_number, @column_number) end end diff --git a/src/json/lexer/string_based.cr b/src/json/lexer/string_based.cr index 5696bc6f78b2..89de32d3201c 100644 --- a/src/json/lexer/string_based.cr +++ b/src/json/lexer/string_based.cr @@ -1,6 +1,6 @@ # :nodoc: class JSON::Lexer::StringBased < JSON::Lexer - def initialize(string) + def initialize(string : String) super() @reader = Char::Reader.new(string) @number_start = 0 @@ -39,22 +39,22 @@ class JSON::Lexer::StringBased < JSON::Lexer end end - private def consume_string_slow_path(start_pos) + private def consume_string_slow_path(start_pos : Int32) : String consume_string_with_buffer do @buffer.write slice_range(start_pos + 1, current_pos) @buffer << consume_string_escape_sequence end end - private def current_pos + private def current_pos : Int32 @reader.pos end - def string_range(start_pos, end_pos) : String + def string_range(start_pos : Int32, end_pos : Int32) : String @reader.string.byte_slice(start_pos, end_pos - start_pos) end - def slice_range(start_pos, end_pos) : Bytes + def slice_range(start_pos : Int32, end_pos : Int32) : Bytes @reader.string.to_slice[start_pos, end_pos - start_pos] end diff --git a/src/json/parser.cr b/src/json/parser.cr index 865dcd124459..bac4e0f2b79c 100644 --- a/src/json/parser.cr +++ b/src/json/parser.cr @@ -15,7 +15,7 @@ class JSON::Parser json end - private def parse_value + private def parse_value : JSON::Any case token.kind when .int? value_and_next_token token.int_value @@ -38,7 +38,7 @@ class JSON::Parser end end - private def parse_array + private def parse_array : JSON::Any next_token ary = [] of Any @@ -66,7 +66,7 @@ class JSON::Parser Any.new(ary) end - private def parse_object + private def parse_object : JSON::Any next_token_expect_object_key object = {} of String => Any @@ -108,20 +108,20 @@ class JSON::Parser private delegate next_token, to: @lexer private delegate next_token_expect_object_key, to: @lexer - private def value_and_next_token(value) + private def value_and_next_token(value : Int64 | Float64 | String | Nil | Bool) : JSON::Any next_token Any.new(value) end - private def check(kind : Token::Kind) + private def check(kind : Token::Kind) : Nil unexpected_token unless token.kind == kind end - private def unexpected_token + private def unexpected_token : Nil parse_exception "unexpected token '#{token}'" end - private def parse_exception(msg) + private def parse_exception(msg : String) : Nil raise ParseException.new(msg, token.line_number, token.column_number) end diff --git a/src/json/serialization.cr b/src/json/serialization.cr index 15d948f02f40..6b8675d96b37 100644 --- a/src/json/serialization.cr +++ b/src/json/serialization.cr @@ -268,14 +268,14 @@ module JSON protected def after_initialize end - protected def on_unknown_json_attribute(pull, key, key_location) + protected def on_unknown_json_attribute(pull : JSON::PullParser, key : String, key_location : Tuple(Int32, Int32)) : Nil pull.skip end - protected def on_to_json(json : ::JSON::Builder) + protected def on_to_json(json : ::JSON::Builder) : Nil end - def to_json(json : ::JSON::Builder) + def to_json(json : ::JSON::Builder) : Nil {% begin %} {% options = @type.annotation(::JSON::Serializable::Options) %} {% emit_nulls = options && options[:emit_nulls] %} @@ -352,7 +352,7 @@ module JSON end module Strict - protected def on_unknown_json_attribute(pull, key, key_location) + protected def on_unknown_json_attribute(pull : JSON::PullParser, key : String, key_location : Tuple(Int32, Int32)) : Nil raise ::JSON::SerializableError.new("Unknown JSON attribute: #{key}", self.class.to_s, nil, *key_location, nil) end end @@ -361,7 +361,7 @@ module JSON @[JSON::Field(ignore: true)] property json_unmapped = Hash(String, JSON::Any).new - protected def on_unknown_json_attribute(pull, key, key_location) + protected def on_unknown_json_attribute(pull : JSON::PullParser, key : String, key_location : Tuple(Int32, Int32)) : JSON::Any json_unmapped[key] = begin JSON::Any.new(pull) rescue exc : ::JSON::ParseException @@ -369,7 +369,7 @@ module JSON end end - protected def on_to_json(json) + protected def on_to_json(json : JSON::Builder) : Nil json_unmapped.each do |key, value| json.field(key) { value.to_json(json) } end @@ -480,7 +480,7 @@ module JSON getter klass : String getter attribute : String? - def initialize(message : String?, @klass : String, @attribute : String?, line_number : Int32, column_number : Int32, cause) + def initialize(message : String?, @klass : String, @attribute : String?, line_number : Int32, column_number : Int32, cause : JSON::ParseException?) message = String.build do |io| io << message io << "\n parsing " diff --git a/src/kernel.cr b/src/kernel.cr index 054705c55e5b..a29fb3e24760 100644 --- a/src/kernel.cr +++ b/src/kernel.cr @@ -168,12 +168,12 @@ end # Prints a formatted string to `STDOUT`. # # For details on the format string, see `sprintf`. -def printf(format_string, *args) : Nil +def printf(format_string : String, *args) : Nil printf format_string, args end # :ditto: -def printf(format_string, args : Array | Tuple) : Nil +def printf(format_string : String, args : Array | Tuple) : Nil STDOUT.printf format_string, args end @@ -433,12 +433,12 @@ end # sprintf "%+g:% g:%-g", 1.23, 1.23, 1.23 # => "+1.23: 1.23:1.23" # sprintf "%-3$*1$.*2$s", 10, 5, "abcdefghij" # => "abcde " # ``` -def sprintf(format_string, *args) : String +def sprintf(format_string : String, *args) : String sprintf format_string, args end # :ditto: -def sprintf(format_string, args : Array | Tuple) : String +def sprintf(format_string : String, args : Array | Tuple) : String String.build(format_string.bytesize) do |str| String::Formatter(typeof(args)).new(format_string, args, str).format end @@ -456,7 +456,7 @@ end # by a newline. Returns *object*. # # See also: `Object#inspect(io)`. -def p(object) +def p(object : Tuple(Int32, Int32)) : Tuple(Int32, Int32) object.inspect(STDOUT) puts object @@ -489,7 +489,7 @@ end # by a newline. Returns *object*. # # See also: `Object#pretty_print(pp)`. -def pp(object) +def pp(object : Tuple(Int32, Int32)) : Tuple(Int32, Int32) PrettyPrint.format(object, STDOUT, 79) puts object @@ -563,7 +563,7 @@ end # to the invoking environment. # # Registered `at_exit` procs are executed. -def exit(status = 0) : NoReturn +def exit(status : Int32 = 0) : NoReturn status = Crystal::AtExitHandlers.run status Crystal.ignore_stdio_errors { STDOUT.flush } Crystal.ignore_stdio_errors { STDERR.flush } @@ -572,7 +572,7 @@ end # Terminates execution immediately, printing *message* to `STDERR` and # then calling `exit(status)`. -def abort(message = nil, status = 1) : NoReturn +def abort(message = nil, status : Int32 = 1) : NoReturn Crystal.ignore_stdio_errors { STDERR.puts message } if message exit status end diff --git a/src/levenshtein.cr b/src/levenshtein.cr index 01ad1bc40784..bcd62e8061ef 100644 --- a/src/levenshtein.cr +++ b/src/levenshtein.cr @@ -93,7 +93,7 @@ module Levenshtein @tolerance = tolerance || (target.size / 5.0).ceil.to_i end - def test(name : String, value : String = name) + def test(name : String, value : String = name) : Levenshtein::Finder::Entry? distance = Levenshtein.distance(@target, name) if distance <= @tolerance if best_entry = @best_entry diff --git a/src/llvm.cr b/src/llvm.cr index 170073b9cb56..b3bda7cbde30 100644 --- a/src/llvm.cr +++ b/src/llvm.cr @@ -11,7 +11,7 @@ module LLVM # information, so the value falls back to `LibLLVM::VERSION` which is # determined at compile time and might slightly be out of sync to the # dynamic library loaded at runtime. - def self.version + def self.version : String {% if LibLLVM.has_method?(:get_version) %} LibLLVM.get_version(out major, out minor, out patch) "#{major}.#{minor}.#{patch}" @@ -169,12 +169,12 @@ module LLVM normalized end - def self.to_io(chars, io) : Nil + def self.to_io(chars : Pointer(UInt8), io : String::Builder) : Nil io.write_string Slice.new(chars, LibC.strlen(chars)) LibLLVM.dispose_message(chars) end - def self.string_and_dispose(chars) : String + def self.string_and_dispose(chars : Pointer(UInt8)) : String string = String.new(chars) LibLLVM.dispose_message(chars) string diff --git a/src/math/math.cr b/src/math/math.cr index efeef9ad9e12..6a363884887a 100644 --- a/src/math/math.cr +++ b/src/math/math.cr @@ -113,7 +113,7 @@ module Math end # :ditto: - def atan2(y, x) : Float64 + def atan2(y : Int32, x : Int32) : Float64 atan2(y.to_f, x.to_f) end @@ -263,7 +263,7 @@ module Math end # :ditto: - def log(value) : Float64 + def log(value : Int32) : Float64 log(value.to_f) end @@ -293,7 +293,7 @@ module Math end # :ditto: - def log2(value) : Float64 + def log2(value : Int32) : Float64 log2(value.to_f) end @@ -308,12 +308,12 @@ module Math end # :ditto: - def log10(value) + def log10(value : UInt64 | Int32 | Int64 | BigInt) : Float64 log10(value.to_f) end # Calculates the logarithm of *value* to the given *base*. - def log(value, base) + def log(value : Float32 | Float64, base : Int32) : Float64 log(value) / log(base) end @@ -328,12 +328,12 @@ module Math end # :ditto: - def sqrt(value) : Float64 + def sqrt(value : Int32) : Float64 sqrt(value.to_f) end # Calculates the integer square root of *value*. - def isqrt(value : Int::Primitive) + def isqrt(value : Int::Primitive) : Int32 | UInt8 | UInt16 | UInt32 | UInt64 | UInt128 | Int8 | Int16 | Int64 | Int128 raise ArgumentError.new "Input must be non-negative integer" if value < 0 return value if value < 2 res = value.class.zero @@ -410,7 +410,7 @@ module Math end # :ditto: - def gamma(value) : Float64 + def gamma(value : Int32 | Int8) : Float64 gamma(value.to_f) end @@ -423,7 +423,7 @@ module Math # ``` # Math.log(Math.gamma(2.96).abs) # ``` - def lgamma(value : Float32) + def lgamma(value : Float32) : Float32 {% if flag?(:darwin) %} LibM.gamma_f64(value).to_f32 {% else %} @@ -437,12 +437,12 @@ module Math end # :ditto: - def lgamma(value) : Float64 + def lgamma(value : Int32 | Int8) : Float64 lgamma(value.to_f) end # Calculates the cylindrical Bessel function of the first kind of *value* for the given *order*. - def besselj(order : Int32, value : Float32) + def besselj(order : Int32, value : Float32) : Float32 {% if flag?(:darwin) || flag?(:win32) %} LibM.besselj_f64(order, value).to_f32 {% else %} @@ -461,7 +461,7 @@ module Math end # Calculates the cylindrical Bessel function of the first kind of *value* for order 0. - def besselj0(value : Float32) + def besselj0(value : Float32) : Float32 {% if flag?(:darwin) || flag?(:win32) %} LibM.besselj0_f64(value).to_f32 {% else %} @@ -480,7 +480,7 @@ module Math end # Calculates the cylindrical Bessel function of the first kind of *value* for order 1. - def besselj1(value : Float32) + def besselj1(value : Float32) : Float32 {% if flag?(:darwin) || flag?(:win32) %} LibM.besselj1_f64(value).to_f32 {% else %} @@ -499,7 +499,7 @@ module Math end # Calculates the cylindrical Bessel function of the second kind of *value* for the given *order*. - def bessely(order : Int32, value : Float32) + def bessely(order : Int32, value : Float32) : Float32 {% if flag?(:darwin) || flag?(:win32) %} LibM.bessely_f64(order, value).to_f32 {% else %} @@ -518,7 +518,7 @@ module Math end # Calculates the cylindrical Bessel function of the second kind of *value* for order 0. - def bessely0(value : Float32) + def bessely0(value : Float32) : Float32 {% if flag?(:darwin) || flag?(:win32) %} LibM.bessely0_f64(value).to_f32 {% else %} @@ -537,7 +537,7 @@ module Math end # Calculates the cylindrical Bessel function of the second kind of *value* for order 1. - def bessely1(value : Float32) + def bessely1(value : Float32) : Float32 {% if flag?(:darwin) || flag?(:win32) %} LibM.bessely1_f64(value).to_f32 {% else %} @@ -676,7 +676,7 @@ module Math end # :ditto: - def scalbln(value, exp) : Float64 + def scalbln(value : Float32 | Float64, exp : Int32) : Float64 scalbln(value.to_f, exp.to_i64) end @@ -714,7 +714,7 @@ module Math end # :ditto: - def copysign(value1, value2) + def copysign(value1 : Float64 | Int32 | Float32, value2 : Int32 | Float64 | Float32) : Float64 copysign(value1.to_f, value2.to_f) end @@ -729,7 +729,7 @@ module Math end # :ditto: - def max(value1, value2) + def max(value1 : Int32 | Int64, value2 : UInt32 | UInt64 | Int32) : Int32 | UInt32 | UInt64 | Int64 value1 >= value2 ? value1 : value2 end @@ -744,7 +744,7 @@ module Math end # :ditto: - def min(value1, value2) + def min(value1 : Int32 | UInt32 | UInt64 | Int16 | Int64, value2 : Int32 | Int64 | Int16 | UInt8 | UInt32) : Int32 | Int64 | UInt32 | UInt64 | Int16 | UInt8 value1 <= value2 ? value1 : value2 end @@ -759,7 +759,7 @@ module Math # Math.pw2ceil(64) # => 64 # Math.pw2ceil(-5) # => 1 # ``` - def pw2ceil(v : Int::Primitive) + def pw2ceil(v : Int::Primitive) : Int32 | Int8 | Int16 | Int64 | Int128 | UInt8 | UInt16 | UInt32 | UInt64 | UInt128 v.next_power_of_two end end diff --git a/src/mime.cr b/src/mime.cr index 7eb65f23818b..b99393b5a35e 100644 --- a/src/mime.cr +++ b/src/mime.cr @@ -140,7 +140,7 @@ module MIME end end - private def self.initialize_types + private def self.initialize_types : Nil init unless @@initialized end @@ -148,7 +148,7 @@ module MIME # # A case-sensitive search is tried first, if this yields no result, it is # matched case-insensitive. Returns *default* if *extension* is not registered. - def self.from_extension(extension : String, default) : String + def self.from_extension(extension : String, default : String) : String from_extension(extension) { default } end @@ -182,7 +182,7 @@ module MIME # # A case-sensitive search is tried first, if this yields no result, it is # matched case-insensitive. Returns *default* if extension is not registered. - def self.from_filename(filename : String | Path, default) : String + def self.from_filename(filename : String | Path, default : String) : String from_extension(File.extname(filename.to_s), default) end diff --git a/src/mime/media_type.cr b/src/mime/media_type.cr index e563f2aa27da..9a50a84c93bd 100644 --- a/src/mime/media_type.cr +++ b/src/mime/media_type.cr @@ -64,7 +64,7 @@ module MIME # mime_type["foo"] = "bar" # mime_type["foo"] # => "bar" # ``` - def []=(key : String, value : String) + def []=(key : String, value : String) : String raise Error.new("Invalid parameter name") unless MIME::MediaType.token? key @params[key] = value end @@ -446,7 +446,7 @@ module MIME return reader, value end - private def self.decode_rfc2231(encoded : String) + private def self.decode_rfc2231(encoded : String) : String? encoding, _, rest = encoded.partition('\'') _lang, _, value = rest.partition('\'') @@ -475,7 +475,7 @@ module MIME end.rewind.gets_to_end end - private def self.consume_whitespace(reader) + private def self.consume_whitespace(reader : Char::Reader) : Char::Reader while reader.current_char.ascii_whitespace? reader.next_char end @@ -488,12 +488,12 @@ module MIME end # :nodoc: - def self.token?(string) : Bool + def self.token?(string : String) : Bool string.each_char.all? { |char| token? char } end # :nodoc: - def self.quote_string(string, io) : Nil + def self.quote_string(string : String, io : String::Builder | IO::Memory) : Nil string.each_char do |char| case char when '"', '\\' diff --git a/src/mime/multipart.cr b/src/mime/multipart.cr index 943af6a15167..6df5d87c3298 100644 --- a/src/mime/multipart.cr +++ b/src/mime/multipart.cr @@ -39,7 +39,7 @@ module MIME::Multipart # # MIME::Multipart.parse_boundary("multipart/mixed; boundary=\"abcde\"") # => "abcde" # ``` - def self.parse_boundary(content_type) : String? + def self.parse_boundary(content_type : String) : String? type = MIME::MediaType.parse?(content_type) if type && type.type == "multipart" diff --git a/src/mime/multipart/builder.cr b/src/mime/multipart/builder.cr index 59d38d766da1..18f4608e000a 100644 --- a/src/mime/multipart/builder.cr +++ b/src/mime/multipart/builder.cr @@ -33,7 +33,7 @@ module MIME::Multipart # builder = MIME::Multipart::Builder.new(io, "a4VF") # builder.content_type("mixed") # => "multipart/mixed; boundary=a4VF" # ``` - def content_type(subtype = "mixed") : String + def content_type(subtype : String = "mixed") : String MIME::MediaType.new("multipart/#{subtype}", {"boundary" => @boundary}).to_s end @@ -199,7 +199,7 @@ module MIME::Multipart @io.flush end - private def fail(msg) + private def fail(msg : String) : Nil raise Multipart::Error.new msg end end diff --git a/src/mime/multipart/parser.cr b/src/mime/multipart/parser.cr index 262f500119f0..775f0ff2d1f3 100644 --- a/src/mime/multipart/parser.cr +++ b/src/mime/multipart/parser.cr @@ -83,7 +83,7 @@ module MIME::Multipart !@state.finished? && !@state.errored? end - private def parse_headers(io) + private def parse_headers(io : IO::Delimited) : HTTP::Headers headers = HTTP::Headers.new while line = io.gets(chomp: false) @@ -104,7 +104,7 @@ module MIME::Multipart # # If it's not a close delimiter, it eats the transport padding and crlf # after a delimiter. - private def close_delimiter? + private def close_delimiter? : Bool transport_padding_crlf = @io.gets("\r\n") fail("EOF reading delimiter") unless transport_padding_crlf @@ -122,7 +122,7 @@ module MIME::Multipart false end - private def fail(msg) + private def fail(msg : String) : Nil raise Multipart::Error.new "Failed to parse multipart message: " + msg end end diff --git a/src/mutex.cr b/src/mutex.cr index 14d1aedf7923..fff44ae51e4c 100644 --- a/src/mutex.cr +++ b/src/mutex.cr @@ -83,7 +83,7 @@ class Mutex @mutex_fiber = Fiber.current unless @protection.unchecked? end - private def try_lock + private def try_lock : Bool i = 1000 while @state.swap(LOCKED, :acquire) != UNLOCKED while @state.get(:relaxed) != UNLOCKED diff --git a/src/nil.cr b/src/nil.cr index 7b97b5f00d3c..d60ddfb109ff 100644 --- a/src/nil.cr +++ b/src/nil.cr @@ -55,12 +55,12 @@ struct Nil end # Returns `true`: `Nil` has only one singleton value: `nil`. - def ==(other : Nil) + def ==(other : Nil) : Bool true end # Returns `true`: `Nil` has only one singleton value: `nil`. - def same?(other : Nil) + def same?(other : Nil) : Bool true end @@ -127,7 +127,7 @@ struct Nil self end - def clone + def clone : Nil self end end diff --git a/src/oauth/authorization_header.cr b/src/oauth/authorization_header.cr index ad5f2428ef5e..1fe2df4629d5 100644 --- a/src/oauth/authorization_header.cr +++ b/src/oauth/authorization_header.cr @@ -6,7 +6,7 @@ struct OAuth::AuthorizationHeader @first = true end - def add(key, value) + def add(key : String, value : String?) : Bool? return unless value @str << ", " unless @first diff --git a/src/oauth/consumer.cr b/src/oauth/consumer.cr index 14ba9407bd41..8d1079792751 100644 --- a/src/oauth/consumer.cr +++ b/src/oauth/consumer.cr @@ -72,7 +72,7 @@ class OAuth::Consumer # [RFC 5849, Section 2.1](https://tools.ietf.org/html/rfc5849#section-2.1). # # Raises `OAuth::Error` if there was an error getting the request token. - def get_request_token(oauth_callback = "oob") # : RequestToken + def get_request_token(oauth_callback : String = "oob") : OAuth::RequestToken post(nil, nil, {"oauth_callback" => oauth_callback}, @request_token_uri) do |response| RequestToken.from_response(response.body) end @@ -81,7 +81,7 @@ class OAuth::Consumer # Returns an authorize URI from a given request token to redirect the user # to obtain an access token, as specified by # [RFC 5849, Section 2.2](https://tools.ietf.org/html/rfc5849#section-2.2). - def get_authorize_uri(request_token, oauth_callback = nil) : String + def get_authorize_uri(request_token : OAuth::RequestToken, oauth_callback : String? = nil) : String get_authorize_uri(request_token, oauth_callback) { } end @@ -116,7 +116,7 @@ class OAuth::Consumer # [RFC 5849, Section 2.3](https://tools.ietf.org/html/rfc5849#section-2.3). # # Raises `OAuth::Error` if there was an error getting the access token. - def get_access_token(request_token, oauth_verifier, extra_params = nil) : AccessToken + def get_access_token(request_token : OAuth::RequestToken, oauth_verifier : String, extra_params : Hash(String, String)? = nil) : AccessToken extra_params ||= {} of String => String extra_params["oauth_verifier"] = oauth_verifier post(request_token.token, request_token.secret, extra_params, @access_token_uri) do |response| @@ -151,7 +151,7 @@ class OAuth::Consumer end end - private def authenticate(client, token, token_secret, extra_params) + private def authenticate(client : HTTP::Client, token : String?, token_secret : String?, extra_params : Hash(String, String)?) : Nil OAuth.authenticate(client, token, token_secret, @consumer_key, @consumer_secret, extra_params) end diff --git a/src/oauth/oauth.cr b/src/oauth/oauth.cr index 292055cfc777..c5a0e40a6b10 100644 --- a/src/oauth/oauth.cr +++ b/src/oauth/oauth.cr @@ -40,17 +40,17 @@ module OAuth # Sets up an `HTTP::Client` to add an OAuth authorization header to every request performed. # Check this module's docs for an example usage. - def self.authenticate(client : HTTP::Client, token, token_secret, consumer_key, consumer_secret, extra_params = nil) : Nil + def self.authenticate(client : HTTP::Client, token : String?, token_secret : String?, consumer_key : String, consumer_secret : String, extra_params : Hash(String, String)? = nil) : Nil client.before_request do |request| authenticate client, request, token, token_secret, consumer_key, consumer_secret, extra_params end end - private def self.authenticate(client, request, token, token_secret, consumer_key, consumer_secret, extra_params) + private def self.authenticate(client : HTTP::Client, request : HTTP::Request, token : String?, token_secret : String?, consumer_key : String, consumer_secret : String, extra_params : Hash(String, String)?) : String request.headers["Authorization"] = oauth_header(client, request, token, token_secret, consumer_key, consumer_secret, extra_params) end - private def self.oauth_header(client, request, token, token_secret, consumer_key, consumer_secret, extra_params) + private def self.oauth_header(client : HTTP::Client, request : HTTP::Request, token : String?, token_secret : String?, consumer_key : String, consumer_secret : String, extra_params : Hash(String, String)?) : String ts = Time.utc.to_unix.to_s nonce = Random::Secure.hex diff --git a/src/oauth/params.cr b/src/oauth/params.cr index 9689d4ac479c..637c39905bda 100644 --- a/src/oauth/params.cr +++ b/src/oauth/params.cr @@ -4,13 +4,13 @@ struct OAuth::Params @params = [] of {String, String} end - def add(key, value) : Nil + def add(key : String, value : String?) : Nil if value @params << {URI.encode_www_form(key, space_to_plus: false), URI.encode_www_form(value, space_to_plus: false)} end end - def add_query(query) : Nil + def add_query(query : String) : Nil URI::Params.parse(query) do |key, value| add key, value end diff --git a/src/oauth/request_token.cr b/src/oauth/request_token.cr index 0fa79c36fc9c..bbcc6b9b171f 100644 --- a/src/oauth/request_token.cr +++ b/src/oauth/request_token.cr @@ -5,7 +5,7 @@ class OAuth::RequestToken def initialize(@token : String, @secret : String) end - def self.from_response(response) : self + def self.from_response(response : String) : self token = nil secret = nil diff --git a/src/oauth/signature.cr b/src/oauth/signature.cr index 2038243f25fa..77c57ed4e1fe 100644 --- a/src/oauth/signature.cr +++ b/src/oauth/signature.cr @@ -3,7 +3,7 @@ struct OAuth::Signature def initialize(@consumer_key : String, @client_shared_secret : String, @oauth_token : String? = nil, @token_shared_secret : String? = nil, @extra_params : Hash(String, String)? = nil) end - def base_string(request, tls, ts, nonce) : String + def base_string(request : HTTP::Request, tls : Nil | OpenSSL::SSL::Context::Client | Bool, ts : String, nonce : String) : String base_string request, tls, gather_params(request, ts, nonce) end @@ -17,12 +17,12 @@ struct OAuth::Signature end end - def compute(request, tls, ts, nonce) : String + def compute(request : HTTP::Request, tls : Nil | OpenSSL::SSL::Context::Client | Bool, ts : String, nonce : String) : String base_string = base_string(request, tls, ts, nonce) Base64.strict_encode(OpenSSL::HMAC.digest :sha1, key, base_string) end - def authorization_header(request, tls, ts, nonce) : String + def authorization_header(request : HTTP::Request, tls : Nil | OpenSSL::SSL::Context::Client | Bool, ts : String, nonce : String) : String oauth_signature = compute request, tls, ts, nonce auth_header = AuthorizationHeader.new @@ -39,7 +39,7 @@ struct OAuth::Signature auth_header.to_s end - private def base_string(request, tls, params) + private def base_string(request : HTTP::Request, tls : Nil | OpenSSL::SSL::Context::Client | Bool, params : OAuth::Params) : String host, port = host_and_port(request, tls) String.build do |str| @@ -59,7 +59,7 @@ struct OAuth::Signature end end - private def gather_params(request, ts, nonce) + private def gather_params(request : HTTP::Request, ts : String, nonce : String) : OAuth::Params params = Params.new params.add "oauth_consumer_key", @consumer_key params.add "oauth_nonce", nonce @@ -87,7 +87,7 @@ struct OAuth::Signature params end - private def host_and_port(request, tls) + private def host_and_port(request : HTTP::Request, tls : Nil | OpenSSL::SSL::Context::Client | Bool) : Tuple(String, Int32 | Nil) host_header = request.headers["Host"] if colon_index = host_header.index ':' host = host_header[0...colon_index] diff --git a/src/oauth2/access_token/access_token.cr b/src/oauth2/access_token/access_token.cr index 2fe2566aea80..229f8a900787 100644 --- a/src/oauth2/access_token/access_token.cr +++ b/src/oauth2/access_token/access_token.cr @@ -2,7 +2,7 @@ # # Use `#authenticate` to authenticate an `HTTP::Client`. abstract class OAuth2::AccessToken - def self.new(pull : JSON::PullParser) + def self.new(pull : JSON::PullParser) : OAuth2::AccessToken token_type = nil access_token = nil expires_in = nil diff --git a/src/oauth2/access_token/bearer.cr b/src/oauth2/access_token/bearer.cr index c586dbb2cd47..025586dab9a4 100644 --- a/src/oauth2/access_token/bearer.cr +++ b/src/oauth2/access_token/bearer.cr @@ -1,7 +1,7 @@ require "./access_token" class OAuth2::AccessToken::Bearer < OAuth2::AccessToken - def self.new(pull : JSON::PullParser) + def self.new(pull : JSON::PullParser) : OAuth2::AccessToken::Bearer OAuth2::AccessToken.new(pull).as(self) end diff --git a/src/oauth2/access_token/mac.cr b/src/oauth2/access_token/mac.cr index 6f7a8f44cbf4..e5d1cb45cda3 100644 --- a/src/oauth2/access_token/mac.cr +++ b/src/oauth2/access_token/mac.cr @@ -4,7 +4,7 @@ require "base64" require "./access_token" class OAuth2::AccessToken::Mac < OAuth2::AccessToken - def self.new(pull : JSON::PullParser) + def self.new(pull : JSON::PullParser) : OAuth2::AccessToken::Mac OAuth2::AccessToken.new(pull).as(self) end @@ -12,7 +12,7 @@ class OAuth2::AccessToken::Mac < OAuth2::AccessToken property mac_key : String property issued_at : Int64 - def initialize(access_token, expires_in, @mac_algorithm, @mac_key, refresh_token = nil, scope = nil, @issued_at = Time.utc.to_unix, extra = nil) + def initialize(access_token : String, expires_in : Int64 | Nil | Int32, @mac_algorithm : String, @mac_key : String, refresh_token : String? = nil, scope : String? = nil, @issued_at : Int64 = Time.utc.to_unix, extra : Hash(String, String)? = nil) super(access_token, expires_in, refresh_token, scope, extra) end @@ -34,7 +34,7 @@ class OAuth2::AccessToken::Mac < OAuth2::AccessToken request.headers["Authorization"] = header end - def self.signature(ts, nonce, method, uri, host, port, ext, mac_algorithm, mac_key) : String + def self.signature(ts : Int64 | Int32, nonce : String, method : String, uri : String, host : String, port : Int32 | String, ext : String, mac_algorithm : String, mac_key : String) : String normalized_request_string = "#{ts}\n#{nonce}\n#{method}\n#{uri}\n#{host}\n#{port}\n#{ext}\n" digest = case mac_algorithm @@ -59,7 +59,7 @@ class OAuth2::AccessToken::Mac < OAuth2::AccessToken def_equals_and_hash access_token, expires_in, mac_algorithm, mac_key, refresh_token, scope - private def host_and_port(request, tls) + private def host_and_port(request : HTTP::Request, tls : Bool | Nil | OpenSSL::SSL::Context::Client) : Tuple(String, Int32) host_header = request.headers["Host"] if colon_index = host_header.index ':' host = host_header[0...colon_index] diff --git a/src/oauth2/client.cr b/src/oauth2/client.cr index df30eafd8a3b..7cfcc0c622da 100644 --- a/src/oauth2/client.cr +++ b/src/oauth2/client.cr @@ -95,7 +95,7 @@ class OAuth2::Client # Builds an authorize URI, as specified by # [RFC 6749, Section 4.1.1](https://tools.ietf.org/html/rfc6749#section-4.1.1). - def get_authorize_uri(scope = nil, state = nil) : String + def get_authorize_uri(scope : String? = nil, state : String? = nil) : String get_authorize_uri(scope, state) { } end @@ -139,7 +139,7 @@ class OAuth2::Client # Gets an access token using the resource owner credentials, as specified by # [RFC 6749, Section 4.3.2](https://tools.ietf.org/html/rfc6749#section-4.3.2). - def get_access_token_using_resource_owner_credentials(username : String, password : String, scope = nil) : AccessToken + def get_access_token_using_resource_owner_credentials(username : String, password : String, scope : String? = nil) : AccessToken get_access_token do |form| form.add("grant_type", "password") form.add("username", username) @@ -150,7 +150,7 @@ class OAuth2::Client # Gets an access token using client credentials, as specified by # [RFC 6749, Section 4.4.2](https://tools.ietf.org/html/rfc6749#section-4.4.2). - def get_access_token_using_client_credentials(scope = nil) : AccessToken + def get_access_token_using_client_credentials(scope : String? = nil) : AccessToken get_access_token do |form| form.add("grant_type", "client_credentials") form.add("scope", scope) unless scope.nil? @@ -159,7 +159,7 @@ class OAuth2::Client # Gets an access token using a refresh token, as specified by # [RFC 6749, Section 6](https://tools.ietf.org/html/rfc6749#section-6). - def get_access_token_using_refresh_token(refresh_token, scope = nil) : AccessToken + def get_access_token_using_refresh_token(refresh_token : String?, scope : String? = nil) : AccessToken get_access_token do |form| form.add("grant_type", "refresh_token") form.add("refresh_token", refresh_token) diff --git a/src/oauth2/session.cr b/src/oauth2/session.cr index 1ba9ec088cee..8334dfee5adf 100644 --- a/src/oauth2/session.cr +++ b/src/oauth2/session.cr @@ -18,12 +18,12 @@ class OAuth2::Session # Authenticates an `HTTP::Client`, refreshing the access token if it is expired. # # Invoke this method on an `HTTP::Client` before executing an HTTP request. - def authenticate(http_client) : Nil + def authenticate(http_client : HTTP::Client) : Nil check_refresh_token @access_token.authenticate http_client end - private def check_refresh_token + private def check_refresh_token : Nil if access_token_expired? refresh_access_token @@ -31,7 +31,7 @@ class OAuth2::Session end end - private def access_token_expired? + private def access_token_expired? : Bool if expires_at = @expires_at Time.utc >= expires_at else @@ -39,7 +39,7 @@ class OAuth2::Session end end - private def refresh_access_token + private def refresh_access_token : String? old_access_token = @access_token @access_token = @oauth2_client.get_access_token_using_refresh_token(@access_token.refresh_token) diff --git a/src/openssl.cr b/src/openssl.cr index 986cd5d29fc9..6f72c13e4d20 100644 --- a/src/openssl.cr +++ b/src/openssl.cr @@ -110,7 +110,7 @@ module OpenSSL getter error : ErrorType getter? underlying_eof : Bool = false - def initialize(ssl : LibSSL::SSL, return_code : LibSSL::Int, func = nil) + def initialize(ssl : LibSSL::SSL, return_code : LibSSL::Int, func : String? = nil) @error = LibSSL.ssl_get_error(ssl, return_code) case @error diff --git a/src/openssl/algorithm.cr b/src/openssl/algorithm.cr index 8ad843eb8e40..db2ea4915063 100644 --- a/src/openssl/algorithm.cr +++ b/src/openssl/algorithm.cr @@ -17,7 +17,7 @@ module OpenSSL # # The internal bindings to the `LibCrypto` digest operations sometimes require a hash algorithm # implementation to be passed as one of the arguments. - def to_evp + def to_evp : LibCrypto::EVP_MD case self when MD4 then LibCrypto.evp_md4 when MD5 then LibCrypto.evp_md5 diff --git a/src/openssl/bio.cr b/src/openssl/bio.cr index 705bbab0a05c..2e0c27d3c468 100644 --- a/src/openssl/bio.cr +++ b/src/openssl/bio.cr @@ -2,7 +2,7 @@ require "./lib_crypto" # :nodoc: struct OpenSSL::BIO - def self.get_data(bio) : Void* + def self.get_data(bio : Pointer(LibCrypto::Bio)) : Void* {% if LibCrypto.has_method?(:BIO_get_data) %} LibCrypto.BIO_get_data(bio) {% else %} @@ -10,7 +10,7 @@ struct OpenSSL::BIO {% end %} end - def self.set_data(bio, data : Void*) + def self.set_data(bio : Pointer(LibCrypto::Bio), data : Void*) : Nil {% if LibCrypto.has_method?(:BIO_set_data) %} LibCrypto.BIO_set_data(bio, data) {% else %} @@ -129,7 +129,7 @@ struct OpenSSL::BIO getter io - def to_unsafe + def to_unsafe : Pointer(LibCrypto::Bio) @bio end end diff --git a/src/openssl/cipher.cr b/src/openssl/cipher.cr index c24c821d54dc..1455b57ab257 100644 --- a/src/openssl/cipher.cr +++ b/src/openssl/cipher.cr @@ -45,7 +45,7 @@ class OpenSSL::Cipher class Error < OpenSSL::Error end - def initialize(name) + def initialize(name : String) cipher = LibCrypto.evp_get_cipherbyname name raise ArgumentError.new "Unsupported cipher algorithm #{name.inspect}" unless cipher @@ -67,13 +67,13 @@ class OpenSSL::Cipher cipherinit enc: 0 end - def key=(key) + def key=(key : String) : String raise ArgumentError.new "Key length too short: wanted #{key_len}, got #{key.bytesize}" if key.bytesize < key_len cipherinit key: key key end - def iv=(iv) + def iv=(iv : String) : String raise ArgumentError.new "IV length too short: wanted #{iv_len}, got #{iv.bytesize}" if iv.bytesize < iv_len cipherinit iv: iv iv @@ -97,7 +97,7 @@ class OpenSSL::Cipher end # Add the data to be encrypted or decrypted to this cipher's buffer. - def update(data) + def update(data : String | Slice(UInt8)) : Slice(UInt8) slice = data.to_slice buffer_length = slice.size + block_size buffer = Bytes.new(buffer_length) @@ -148,7 +148,7 @@ class OpenSSL::Cipher LibCrypto.evp_cipher_iv_length cipher end - def finalize + def finalize : Pointer(Void) LibCrypto.evp_cipher_ctx_free(@ctx) if @ctx @ctx = typeof(@ctx).null end @@ -157,7 +157,7 @@ class OpenSSL::Cipher LibCrypto.evp_cipher_flags(cipher).includes?(LibCrypto::CipherFlags::EVP_CIPH_FLAG_AEAD_CIPHER) end - private def cipherinit(cipher = nil, engine = nil, key = nil, iv = nil, enc = -1) + private def cipherinit(cipher : Pointer(Void)? = nil, engine : Nil = nil, key : String? = nil, iv : String? = nil, enc : Int32 = -1) : Nil if LibCrypto.evp_cipherinit_ex(@ctx, cipher, engine, key, iv, enc) != 1 raise Error.new "EVP_CipherInit_ex" end @@ -165,7 +165,7 @@ class OpenSSL::Cipher nil end - private def cipher + private def cipher : Pointer(Void) LibCrypto.evp_cipher_ctx_cipher @ctx end end diff --git a/src/openssl/digest.cr b/src/openssl/digest.cr index 9d0e2523c178..2c7b0fb81c1f 100644 --- a/src/openssl/digest.cr +++ b/src/openssl/digest.cr @@ -18,7 +18,7 @@ module OpenSSL protected def initialize(@name : String, @ctx : LibCrypto::EVP_MD_CTX) end - private def new_evp_mt_ctx(name) + private def new_evp_mt_ctx(name : String) : Pointer(LibCrypto::EVP_MD_CTX_Struct) md = LibCrypto.evp_get_digestbyname(name) unless md raise UnsupportedError.new("Unsupported digest algorithm: #{name}") @@ -34,7 +34,7 @@ module OpenSSL ctx end - def finalize + def finalize : Nil LibCrypto.evp_md_ctx_free(self) end @@ -42,7 +42,7 @@ module OpenSSL Digest.new(@name, dup_ctx) end - protected def dup_ctx + protected def dup_ctx : Pointer(LibCrypto::EVP_MD_CTX_Struct) ctx = LibCrypto.evp_md_ctx_new if LibCrypto.evp_md_ctx_copy(ctx, @ctx) == 0 LibCrypto.evp_md_ctx_free(ctx) @@ -81,11 +81,11 @@ module OpenSSL LibCrypto.evp_md_block_size(to_unsafe_md).to_i end - def to_unsafe_md + def to_unsafe_md : LibCrypto::EVP_MD LibCrypto.evp_md_ctx_md(self) end - def to_unsafe + def to_unsafe : Pointer(LibCrypto::EVP_MD_CTX_Struct) @ctx end end diff --git a/src/openssl/error.cr b/src/openssl/error.cr index ff12c33812ab..fd5a9cf2db2f 100644 --- a/src/openssl/error.cr +++ b/src/openssl/error.cr @@ -5,7 +5,7 @@ module OpenSSL class Error < Exception getter! code : LibCrypto::ULong - def initialize(message = nil, fetched = false, cause : Exception? = nil) + def initialize(message : String? = nil, fetched : Bool = false, cause : Exception? = nil) @code ||= LibCrypto::ULong.new(0) if fetched @@ -16,13 +16,13 @@ module OpenSSL end end - protected def fetch_error_details + protected def fetch_error_details : Tuple(UInt64, String) code = LibCrypto.err_get_error message = String.new(LibCrypto.err_error_string(code, nil)) unless code == 0 {code, message || "Unknown or no error"} end - protected def get_reason(code) + protected def get_reason(code : UInt64) : Int32 {% if LibCrypto.has_constant?(:ERR_REASON_MASK) %} if (code & LibCrypto::ERR_SYSTEM_FLAG) != 0 (code & LibCrypto::ERR_SYSTEM_MASK).to_i diff --git a/src/openssl/hmac.cr b/src/openssl/hmac.cr index 187cbe40bd6e..eb51e46a0841 100644 --- a/src/openssl/hmac.cr +++ b/src/openssl/hmac.cr @@ -15,7 +15,7 @@ class OpenSSL::HMAC # It may contain non-ASCII bytes, including NUL bytes. # # *algorithm* specifies which `OpenSSL::Algorithm` is to be used. - def self.digest(algorithm : OpenSSL::Algorithm, key, data) : Bytes + def self.digest(algorithm : OpenSSL::Algorithm, key : String, data : String) : Bytes evp = algorithm.to_evp key_slice = key.to_slice data_slice = data.to_slice @@ -29,7 +29,7 @@ class OpenSSL::HMAC # the digest where binary messages are not allowed. # # See also `#digest`. - def self.hexdigest(algorithm : OpenSSL::Algorithm, key, data) : String + def self.hexdigest(algorithm : OpenSSL::Algorithm, key : String, data : String) : String digest(algorithm, key, data).hexstring end end diff --git a/src/openssl/pkcs5.cr b/src/openssl/pkcs5.cr index d1bca87d2095..a432b1753f0d 100644 --- a/src/openssl/pkcs5.cr +++ b/src/openssl/pkcs5.cr @@ -2,7 +2,7 @@ require "openssl" require "openssl/algorithm" module OpenSSL::PKCS5 - def self.pbkdf2_hmac_sha1(secret, salt, iterations = 2**16, key_size = 64) : Bytes + def self.pbkdf2_hmac_sha1(secret : String, salt : String, iterations : Int32 = 2**16, key_size : Int32 = 64) : Bytes buffer = Bytes.new(key_size) if LibCrypto.pkcs5_pbkdf2_hmac_sha1(secret, secret.bytesize, salt, salt.bytesize, iterations, key_size, buffer) != 1 raise OpenSSL::Error.new "pkcs5_pbkdf2_hmac" @@ -10,7 +10,7 @@ module OpenSSL::PKCS5 buffer end - def self.pbkdf2_hmac(secret, salt, iterations = 2**16, algorithm : OpenSSL::Algorithm = OpenSSL::Algorithm::SHA1, key_size = 64) : Bytes + def self.pbkdf2_hmac(secret : String, salt : String, iterations : Int32 = 2**16, algorithm : OpenSSL::Algorithm = OpenSSL::Algorithm::SHA1, key_size : Int32 = 64) : Bytes {% if LibCrypto.has_method?(:pkcs5_pbkdf2_hmac) %} evp = algorithm.to_evp buffer = Bytes.new(key_size) diff --git a/src/openssl/sha1.cr b/src/openssl/sha1.cr index 54c45817739e..7e5e186ef231 100644 --- a/src/openssl/sha1.cr +++ b/src/openssl/sha1.cr @@ -7,11 +7,11 @@ require "./lib_crypto" # `Crypto::Bcrypt::Password`. For a generic cryptographic hash, use SHA-256 via # `OpenSSL::Digest.new("SHA256")`. class OpenSSL::SHA1 - def self.hash(data : String) + def self.hash(data : String) : StaticArray(UInt8, 20) hash(data.to_unsafe, LibC::SizeT.new(data.bytesize)) end - def self.hash(data : UInt8*, bytesize : LibC::SizeT) + def self.hash(data : UInt8*, bytesize : LibC::SizeT) : StaticArray(UInt8, 20) buffer = uninitialized UInt8[20] LibCrypto.sha1(data, bytesize, buffer) buffer diff --git a/src/openssl/ssl/context.cr b/src/openssl/ssl/context.cr index 38e0054cba17..ad4c61c8f53d 100644 --- a/src/openssl/ssl/context.cr +++ b/src/openssl/ssl/context.cr @@ -11,7 +11,7 @@ require "log" # appropriately. abstract class OpenSSL::SSL::Context # :nodoc: - def self.default_method + def self.default_method : LibSSL::SSLMethod {% if LibSSL.has_method?(:tls_method) %} LibSSL.tls_method {% else %} @@ -73,7 +73,7 @@ abstract class OpenSSL::SSL::Context # * `ca`: Path to a file containing the CA certificate chain or a directory containing all CA certificates. # See `#ca_certificates=` and `#ca_certificates_path=`, respectively. # Required if `verify_mode` is `peer`, `force-peer` or empty. - def self.from_hash(params) : self + def self.from_hash(params : Hash(String, String)) : self super(params) end @@ -98,7 +98,7 @@ abstract class OpenSSL::SSL::Context }, hostname.as(Void*)) end - private def alpn_protocol=(protocol : Bytes) + private def alpn_protocol=(protocol : Bytes) : Int32 {% if LibSSL.has_method?(:ssl_ctx_set_alpn_protos) %} LibSSL.ssl_ctx_set_alpn_protos(@handle, protocol, protocol.size) {% else %} @@ -156,7 +156,7 @@ abstract class OpenSSL::SSL::Context # * `ca`: Path to a file containing the CA certificate chain or a directory containing all CA certificates. # See `#ca_certificates=` and `#ca_certificates_path=`, respectively. # Required if `verify_mode` is `peer` or `force-peer`. - def self.from_hash(params) : self + def self.from_hash(params : URI::Params | Hash(String, String)) : self super(params) end @@ -174,7 +174,7 @@ abstract class OpenSSL::SSL::Context {% end %} end - private def alpn_protocol=(protocol : Bytes) + private def alpn_protocol=(protocol : Bytes) : Nil {% if LibSSL.has_method?(:ssl_ctx_set_alpn_select_cb) %} alpn_cb = ->(ssl : LibSSL::SSL, o : LibC::Char**, olen : LibC::Char*, i : LibC::Char*, ilen : LibC::Int, data : Void*) { proto = Box(Bytes).unbox(data) @@ -228,7 +228,7 @@ abstract class OpenSSL::SSL::Context # versions public too. So to provide insecure in the child classes, we need # a second constructor that we call from there without getting the # overridden ones of the childs. - protected def _initialize_insecure(method : LibSSL::SSLMethod) + protected def _initialize_insecure(method : LibSSL::SSLMethod) : Nil @handle = LibSSL.ssl_ctx_new(method) raise OpenSSL::Error.new("SSL_CTX_new") if @handle.null? @@ -239,25 +239,25 @@ abstract class OpenSSL::SSL::Context {% end %} end - protected def self.insecure(method : LibSSL::SSLMethod) + protected def self.insecure(method : LibSSL::SSLMethod) : OpenSSL::SSL::Context::Client | OpenSSL::SSL::Context::Server obj = allocate obj._initialize_insecure(method) GC.add_finalizer(obj) obj end - def finalize + def finalize : Nil LibSSL.ssl_ctx_free(@handle) end # Sets the default paths for `ca_certificates=` and `ca_certificates_path=`. - def set_default_verify_paths + def set_default_verify_paths : Int32 LibSSL.ssl_ctx_set_default_verify_paths(@handle) end # Sets the path to a file containing all CA certificates, in PEM format, used to # validate the peers certificate. - def ca_certificates=(file_path : String) + def ca_certificates=(file_path : String) : Nil ret = LibSSL.ssl_ctx_load_verify_locations(@handle, file_path, nil) raise OpenSSL::Error.new("SSL_CTX_load_verify_locations") unless ret == 1 end @@ -265,21 +265,21 @@ abstract class OpenSSL::SSL::Context # Sets the path to a directory containing all CA certificates used to # validate the peers certificate. The certificates should be in PEM format # and the `c_rehash(1)` utility must have been run in the directory. - def ca_certificates_path=(dir_path : String) + def ca_certificates_path=(dir_path : String) : Nil ret = LibSSL.ssl_ctx_load_verify_locations(@handle, nil, dir_path) raise OpenSSL::Error.new("SSL_CTX_load_verify_locations") unless ret == 1 end # Specify the path to the certificate chain file to use. In server mode this # is presented to the client, in client mode this used as client certificate. - def certificate_chain=(file_path : String) + def certificate_chain=(file_path : String) : Nil ret = LibSSL.ssl_ctx_use_certificate_chain_file(@handle, file_path) raise OpenSSL::Error.new("SSL_CTX_use_certificate_chain_file") unless ret == 1 end # Specify the path to the private key to use. The key must in PEM format. # The key must correspond to the entity certificate set by `certificate_chain=`. - def private_key=(file_path : String) + def private_key=(file_path : String) : Nil ret = LibSSL.ssl_ctx_use_privatekey_file(@handle, file_path, LibSSL::SSLFileType::PEM) raise OpenSSL::Error.new("SSL_CTX_use_PrivateKey_file") unless ret == 1 end @@ -295,7 +295,7 @@ abstract class OpenSSL::SSL::Context # linked version of the system SSL library. A comprehensive list # of ciphers can be found in the # [OpenSSL Cipher documentation](https://www.openssl.org/docs/man3.0/man1/openssl-ciphers.html#CIPHER-STRINGS). - def ciphers=(ciphers : String) + def ciphers=(ciphers : String) : String ret = LibSSL.ssl_ctx_set_cipher_list(@handle, ciphers) raise OpenSSL::Error.new("SSL_CTX_set_cipher_list") if ret == 0 ciphers @@ -309,7 +309,7 @@ abstract class OpenSSL::SSL::Context # linked version of the system SSL library. A comprehensive list # of ciphersuites can be found in the # [OpenSSL Cipher documentation](https://www.openssl.org/docs/man3.0/man1/openssl-ciphers.html#TLS-v1.3-cipher-suites). - def cipher_suites=(cipher_suites : String) + def cipher_suites=(cipher_suites : String) : String {% if LibSSL.has_method?(:ssl_ctx_set_ciphersuites) %} ret = LibSSL.ssl_ctx_set_ciphersuites(@handle, cipher_suites) raise OpenSSL::Error.new("SSL_CTX_set_ciphersuites") if ret == 0 @@ -325,7 +325,7 @@ abstract class OpenSSL::SSL::Context # WARNING: Does nothing as of Crystal 1.13. # WARNING: Didn't work as expected as of OpenSSL 1.1 (didn't configure TLSv1.2 and below). @[Deprecated("Deprecated with no replacement. Prefer #security_level, global system configuration or build your own from https://wiki.mozilla.org/Security/Server_Side_TLS")] - def set_modern_ciphers + def set_modern_ciphers : Nil end # Sets the current ciphers and ciphers suites to **intermediate** compatibility level as per Mozilla @@ -334,7 +334,7 @@ abstract class OpenSSL::SSL::Context # WARNING: Does nothing as of Crystal 1.13. # WARNING: Didn't work as expected as of OpenSSL 1.1 (didn't configure TLSv1.2 and below). @[Deprecated("Deprecated with no replacement. Prefer #security_level, global system configuration or build your own from https://wiki.mozilla.org/Security/Server_Side_TLS")] - def set_intermediate_ciphers + def set_intermediate_ciphers : Nil end # Sets the current ciphers and ciphers suites to **old** compatibility level as per Mozilla @@ -343,7 +343,7 @@ abstract class OpenSSL::SSL::Context # WARNING: Does nothing as of Crystal 1.13. # WARNING: Didn't work as expected as of OpenSSL 1.1 (didn't configure TLSv1.2 and below). @[Deprecated("Deprecated with no replacement. Prefer #security_level, global system configuration or build your own from https://wiki.mozilla.org/Security/Server_Side_TLS")] - def set_old_ciphers + def set_old_ciphers : Nil end # Returns the security level used by this TLS context. @@ -361,7 +361,7 @@ abstract class OpenSSL::SSL::Context # # * https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set_security_level.html # * https://wiki.debian.org/ContinuousIntegration/TriagingTips/openssl-1.1.1 - def security_level=(value : Int32) + def security_level=(value : Int32) : Int32 {% if LibSSL.has_method?(:ssl_ctx_set_security_level) %} LibSSL.ssl_ctx_set_security_level(@handle, value) {% else %} @@ -372,7 +372,7 @@ abstract class OpenSSL::SSL::Context # Adds a temporary ECDH key curve to the TLS context. This is required to # enable the EECDH cipher suites. By default the prime256 curve will be used. - def set_tmp_ecdh_key(curve = LibCrypto::NID_X9_62_prime256v1) : Nil + def set_tmp_ecdh_key(curve : Int32 = LibCrypto::NID_X9_62_prime256v1) : Nil key = LibCrypto.ec_key_new_by_curve_name(curve) raise OpenSSL::Error.new("ec_key_new_by_curve_name") if key.null? LibSSL.ssl_ctx_ctrl(@handle, LibSSL::SSL_CTRL_SET_TMP_ECDH, 0, key) @@ -385,12 +385,12 @@ abstract class OpenSSL::SSL::Context end # Adds modes to the TLS context. - def add_modes(mode : OpenSSL::SSL::Modes) + def add_modes(mode : OpenSSL::SSL::Modes) : LibSSL::Modes OpenSSL::SSL::Modes.new LibSSL.ssl_ctx_ctrl(@handle, LibSSL::SSL_CTRL_MODE, mode, nil) end # Removes modes from the TLS context. - def remove_modes(mode : OpenSSL::SSL::Modes) + def remove_modes(mode : OpenSSL::SSL::Modes) : LibSSL::Modes OpenSSL::SSL::Modes.new LibSSL.ssl_ctx_ctrl(@handle, LibSSL::SSL_CTRL_CLEAR_MODE, mode, nil) end @@ -414,7 +414,7 @@ abstract class OpenSSL::SSL::Context # OpenSSL::SSL::Options::NO_SSL_V3 # disable deprecated SSLv3 # ) # ``` - def add_options(options : OpenSSL::SSL::Options) + def add_options(options : OpenSSL::SSL::Options) : LibSSL::Options opts = {% if LibSSL.has_method?(:ssl_ctx_set_options) %} LibSSL.ssl_ctx_set_options(@handle, options) {% else %} @@ -429,7 +429,7 @@ abstract class OpenSSL::SSL::Context # ``` # context.remove_options(OpenSSL::SSL::Options::NO_SSL_V3) # ``` - def remove_options(options : OpenSSL::SSL::Options) + def remove_options(options : OpenSSL::SSL::Options) : LibSSL::Options opts = {% if LibSSL.has_method?(:ssl_ctx_clear_options) %} LibSSL.ssl_ctx_clear_options(@handle, options) {% else %} @@ -444,7 +444,7 @@ abstract class OpenSSL::SSL::Context end # Sets the verify mode. See the `SSL_CTX_set_verify(3)` manpage for more details. - def verify_mode=(mode : OpenSSL::SSL::VerifyMode) + def verify_mode=(mode : OpenSSL::SSL::VerifyMode) : Nil LibSSL.ssl_ctx_set_verify(@handle, mode, nil) end @@ -458,7 +458,7 @@ abstract class OpenSSL::SSL::Context # ``` # context.alpn_protocol = "h2" # ``` - def alpn_protocol=(protocol : String) + def alpn_protocol=(protocol : String) : Int32? proto = Bytes.new(protocol.bytesize + 1) proto[0] = protocol.bytesize.to_u8 protocol.to_slice.copy_to(proto.to_unsafe + 1, protocol.bytesize) @@ -492,11 +492,11 @@ abstract class OpenSSL::SSL::Context {% end %} end - def to_unsafe + def to_unsafe : LibSSL::SSLContext @handle end - private def self.from_hash(params) + private def self.from_hash(params : Hash(String, String) | URI::Params) : OpenSSL::SSL::Context::Client | OpenSSL::SSL::Context::Server context = new if key = params["key"]? context.private_key = key diff --git a/src/openssl/ssl/hostname_validation.cr b/src/openssl/ssl/hostname_validation.cr index 8c0a787e6541..190f130328ba 100644 --- a/src/openssl/ssl/hostname_validation.cr +++ b/src/openssl/ssl/hostname_validation.cr @@ -27,7 +27,7 @@ module OpenSSL::SSL::HostnameValidation # Matches hostname against Subject Alternate Name (SAN) entries of certificate. # # Adapted from https://wiki.openssl.org/index.php/Hostname_validation - def self.matches_subject_alternative_name(hostname, server_cert : LibCrypto::X509) : Result + def self.matches_subject_alternative_name(hostname : String, server_cert : LibCrypto::X509) : Result san_names = LibCrypto.x509_get_ext_d2i(server_cert, LibCrypto::NID_subject_alt_name, nil, nil) return Result::NoSANPresent if san_names.null? @@ -78,7 +78,7 @@ module OpenSSL::SSL::HostnameValidation # called if no SAN entries could be found in certificate. # # Adapted from https://wiki.openssl.org/index.php/Hostname_validation - def self.matches_common_name(hostname, server_cert : LibCrypto::X509) : Result + def self.matches_common_name(hostname : String, server_cert : LibCrypto::X509) : Result subject = LibCrypto.x509_get_subject_name(server_cert) index = LibCrypto.x509_name_get_index_by_nid(subject, LibCrypto::NID_commonName, -1) @@ -121,7 +121,7 @@ module OpenSSL::SSL::HostnameValidation # Adapted from cURL: # Copyright (C) 1998 - 2014, Daniel Stenberg, , et al. # https://github.com/curl/curl/blob/curl-7_41_0/lib/hostcheck.c - def self.matches_hostname?(pattern, hostname) : Bool + def self.matches_hostname?(pattern : String, hostname : String) : Bool pattern = pattern.chomp('.').downcase hostname = hostname.chomp('.').downcase diff --git a/src/openssl/ssl/server.cr b/src/openssl/ssl/server.cr index 97132f8c4810..1784ac823f8b 100644 --- a/src/openssl/ssl/server.cr +++ b/src/openssl/ssl/server.cr @@ -75,7 +75,7 @@ class OpenSSL::SSL::Server end end - private def new_ssl_socket(io) + private def new_ssl_socket(io : IO) : OpenSSL::SSL::Socket::Server OpenSSL::SSL::Socket::Server.new(io, @context, sync_close: @sync_close, accept: @start_immediately) end diff --git a/src/openssl/ssl/socket.cr b/src/openssl/ssl/socket.cr index 8bff5a131410..42b2d5c4500d 100644 --- a/src/openssl/ssl/socket.cr +++ b/src/openssl/ssl/socket.cr @@ -1,6 +1,6 @@ abstract class OpenSSL::SSL::Socket < IO class Client < Socket - def initialize(io, context : Context::Client = Context::Client.new, sync_close : Bool = false, hostname : String? = nil) + def initialize(io : TCPSocket, context : Context::Client = Context::Client.new, sync_close : Bool = false, hostname : String? = nil) super(io, context, sync_close) begin if hostname @@ -56,7 +56,7 @@ abstract class OpenSSL::SSL::Socket < IO end class Server < Socket - def initialize(io, context : Context::Server = Context::Server.new, + def initialize(io : IO | TCPSocket, context : Context::Server = Context::Server.new, sync_close : Bool = false, accept : Bool = true) super(io, context, sync_close) @@ -97,7 +97,7 @@ abstract class OpenSSL::SSL::Socket < IO getter? closed : Bool - protected def initialize(io, context : Context, @sync_close : Bool = false) + protected def initialize(io : TCPSocket | IO, context : Context, @sync_close : Bool = false) @closed = false @ssl = LibSSL.ssl_new(context) @@ -116,7 +116,7 @@ abstract class OpenSSL::SSL::Socket < IO LibSSL.ssl_set_bio(@ssl, @bio, @bio) end - def finalize + def finalize : Nil LibSSL.ssl_free(@ssl) end @@ -157,7 +157,7 @@ abstract class OpenSSL::SSL::Socket < IO # Returns the negotiated ALPN protocol (eg: `"h2"`) of `nil` if no protocol was # negotiated. - def alpn_protocol + def alpn_protocol : String? {% if LibSSL.has_method?(:ssl_get0_alpn_selected) %} LibSSL.ssl_get0_alpn_selected(@ssl, out protocol, out len) String.new(protocol, len) unless protocol.null? diff --git a/src/openssl/x509/certificate.cr b/src/openssl/x509/certificate.cr index 593f3fb4dc4b..1d6fe9344bed 100644 --- a/src/openssl/x509/certificate.cr +++ b/src/openssl/x509/certificate.cr @@ -16,7 +16,7 @@ module OpenSSL::X509 raise Error.new("X509_dup") if @cert.null? end - def finalize + def finalize : Nil LibCrypto.x509_free(@cert) end @@ -24,7 +24,7 @@ module OpenSSL::X509 self.class.new(@cert) end - def to_unsafe + def to_unsafe : LibCrypto::X509 @cert end @@ -50,11 +50,11 @@ module OpenSSL::X509 # Sets the subject. # # Refer to `Name.parse` for the format. - def subject=(subject : String) + def subject=(subject : String) : OpenSSL::X509::Name self.subject = Name.parse(subject) end - def subject=(subject : Name) + def subject=(subject : Name) : OpenSSL::X509::Name ret = LibCrypto.x509_set_subject_name(@cert, subject) raise Error.new("X509_set_subject_name") if ret == 0 subject @@ -67,7 +67,7 @@ module OpenSSL::X509 end end - def add_extension(extension : Extension) + def add_extension(extension : Extension) : OpenSSL::X509::Extension ret = LibCrypto.x509_add_ext(@cert, extension, -1) raise Error.new("X509_add_ext") if ret.null? extension diff --git a/src/openssl/x509/extension.cr b/src/openssl/x509/extension.cr index b326a35f8309..ddf841813444 100644 --- a/src/openssl/x509/extension.cr +++ b/src/openssl/x509/extension.cr @@ -4,14 +4,14 @@ require "openssl/lib_crypto" module OpenSSL::X509 # :nodoc: class Extension - def self.new(oid : String, value : String, critical = false) + def self.new(oid : String, value : String, critical : Bool = false) : OpenSSL::X509::Extension nid = LibCrypto.obj_ln2nid(oid) nid = LibCrypto.obj_sn2nid(oid) if nid == LibCrypto::NID_undef raise Error.new("OBJ_sn2nid") if nid == LibCrypto::NID_undef new(nid, value, critical) end - def initialize(nid : Int32, value : String, critical = false) + def initialize(nid : Int32, value : String, critical : Bool = false) valstr = String.build do |str| str << "critical," if critical str << value @@ -25,7 +25,7 @@ module OpenSSL::X509 raise Error.new("X509_EXTENSION_dup") if @ext.null? end - def finalize + def finalize : Nil LibCrypto.x509_extension_free(@ext) end @@ -33,7 +33,7 @@ module OpenSSL::X509 self.class.new(@ext) end - def to_unsafe + def to_unsafe : LibCrypto::X509_EXTENSION @ext end diff --git a/src/openssl/x509/name.cr b/src/openssl/x509/name.cr index dacb04d67c2c..1582da47eb41 100644 --- a/src/openssl/x509/name.cr +++ b/src/openssl/x509/name.cr @@ -31,7 +31,7 @@ module OpenSSL::X509 raise Error.new("X509_NAME_dup") if @name.null? end - def finalize + def finalize : Nil LibCrypto.x509_name_free(@name) end @@ -39,7 +39,7 @@ module OpenSSL::X509 self.class.new(@name) end - def to_unsafe + def to_unsafe : LibCrypto::X509_NAME @name end diff --git a/src/option_parser.cr b/src/option_parser.cr index 5f61e73cd58d..031c23d9ff94 100644 --- a/src/option_parser.cr +++ b/src/option_parser.cr @@ -85,13 +85,13 @@ class OptionParser end class InvalidOption < Exception - def initialize(option) + def initialize(option : String) super("Invalid option: #{option}") end end class MissingOption < Exception - def initialize(option) + def initialize(option : String) super("Missing option: #{option}") end end @@ -207,7 +207,7 @@ class OptionParser # Examples of valid subcommands: # # * `foo`, `run` - def on(flag : String, description : String, &block : String ->) + def on(flag : String, description : String, &block : String ->) : OptionParser::Handler append_flag flag, description flag, value_type = parse_flag_definition(flag) @@ -218,7 +218,7 @@ class OptionParser # # See the other definition of `on` for examples. This method does not support # subcommands. - def on(short_flag : String, long_flag : String, description : String, &block : String ->) + def on(short_flag : String, long_flag : String, description : String, &block : String ->) : OptionParser::Handler check_starts_with_dash short_flag, "short_flag", allow_empty: true check_starts_with_dash long_flag, "long_flag" @@ -240,7 +240,7 @@ class OptionParser @handlers[short_flag] = @handlers[long_flag] = handler end - private def parse_flag_definition(flag : String) + private def parse_flag_definition(flag : String) : Tuple(String, OptionParser::FlagValue) case flag when /\A--(\S+)\s+\[\S+\]\z/ {"--#{$1}", FlagValue::Optional} @@ -264,7 +264,7 @@ class OptionParser # before, and the flags registered after the call. # # This way, you can group the different options in an easier to read way. - def separator(message = "") : Nil + def separator(message : String = "") : Nil @flags << message.to_s end @@ -274,21 +274,21 @@ class OptionParser # that your program expects (for example, filenames). The default behaviour # is to do nothing. The arguments can also be extracted from the *args* array # passed to `#parse` after parsing. - def unknown_args(&@unknown_args : Array(String), Array(String) ->) + def unknown_args(&@unknown_args : Array(String), Array(String) ->) : Proc(Array(String), Array(String), Nil) end # Sets a handler for when a option that expects an argument wasn't given any. # # You typically use this to display a help message. # The default behaviour is to raise `MissingOption`. - def missing_option(&@missing_option : String ->) + def missing_option(&@missing_option : String ->) : Proc(String, Nil) end # Sets a handler for option arguments that didn't match any of the setup options. # # You typically use this to display a help message. # The default behaviour is to raise `InvalidOption`. - def invalid_option(&@invalid_option : String ->) + def invalid_option(&@invalid_option : String ->) : Proc(String, Nil) end # Sets a handler which runs before each argument is parsed. This callback is @@ -297,7 +297,7 @@ class OptionParser # # You typically use this to implement advanced option parsing behaviour such # as treating all options after a filename differently (along with `#stop`). - def before_each(&@before_each : String ->) + def before_each(&@before_each : String ->) : Proc(String, Nil) end # Stops the current parse and returns immediately, leaving the remaining flags @@ -316,7 +316,7 @@ class OptionParser @flags.join io, '\n' end - private def append_flag(flag, description) + private def append_flag(flag : String, description : String) : Array(String) indent = " " * 37 description = description.gsub("\n", "\n#{indent}") if flag.size >= 33 @@ -326,7 +326,7 @@ class OptionParser end end - private def check_starts_with_dash(arg, name, allow_empty = false) + private def check_starts_with_dash(arg : String, name : String, allow_empty : Bool = false) : Nil return if allow_empty && arg.empty? unless arg.starts_with?('-') @@ -358,7 +358,7 @@ class OptionParser end # Parses the passed *args* (defaults to `ARGV`), running the handlers associated to each option. - def parse(args = ARGV) : Nil + def parse(args : Array(String) = ARGV) : Nil with_preserved_state do # List of indexes in `args` which have been handled and must be deleted handled_args = [] of Int32 diff --git a/src/path.cr b/src/path.cr index f9cd35efaeaf..f4e1e965766c 100644 --- a/src/path.cr +++ b/src/path.cr @@ -83,7 +83,7 @@ struct Path SEPARATORS = separators(Kind.native) # :nodoc: - def self.separators(kind) + def self.separators(kind : Path::Kind) : Tuple(Char) | Tuple(Char, Char) if kind.windows? {'\\', '/'} else @@ -169,7 +169,7 @@ struct Path end # Internal helper method to create a new `Path` of the same kind as `self`. - private def new_instance(string : String, kind = @kind) : Path + private def new_instance(string : String, kind : Path::Kind = @kind) : Path Path.new(string, kind) end @@ -556,7 +556,7 @@ struct Path end # :nodoc: - def self.next_part_separator_index(reader : Char::Reader, last_was_separator, separators) + def self.next_part_separator_index(reader : Char::Reader, last_was_separator : Bool, separators : Tuple(Char) | Tuple(Char, Char)) : Tuple(Char::Reader, Bool, Int32)? start_pos = reader.pos reader.each do |char| @@ -596,7 +596,7 @@ struct Path @path.@name.byte_slice(start_pos, @reader.pos - start_pos) end - private def next_pos + private def next_pos : Int32? unless @anchor_processed @anchor_processed = true if anchor_pos = process_anchor @@ -612,7 +612,7 @@ struct Path start_pos end - private def process_anchor + private def process_anchor : Int32? anchor = @path.anchor return unless anchor @@ -629,7 +629,7 @@ struct Path end end - private def windows_drive? + private def windows_drive? : Bool @name.byte_at?(1) === ':' && @name.char_at(0).ascii_letter? end @@ -714,7 +714,7 @@ struct Path # See `#to_windows` and `#to_posix` for details. # # * `#to_native` converts to the native path semantics. - def to_kind(kind, *, mappings : Bool = true) : Path + def to_kind(kind : Path::Kind, *, mappings : Bool = true) : Path if kind.posix? to_posix(mappings: mappings) else @@ -740,7 +740,7 @@ struct Path # If *expand_base* is `true`, *base* itself will be expanded in `Dir.current` # if it is not an absolute path. This guarantees the method returns an absolute # path (assuming that `Dir.current` is absolute). - def expand(base : Path | String = Dir.current, *, home : Path | String | Bool = false, expand_base = true) : Path + def expand(base : Path | String = Dir.current, *, home : Path | String | Bool = false, expand_base : Bool = true) : Path base = Path.new(base) unless base.is_a?(Path) base = base.to_kind(@kind) if base == self @@ -809,7 +809,7 @@ struct Path expanded.normalize(remove_final_separator: false) end - private def resolve_home(home) + private def resolve_home(home : Bool | String | Path) : Path case home when String then home = Path[home] when Bool then home = Path.home @@ -836,7 +836,7 @@ struct Path # Path["a/b/"].join("") # => Path["a/b/"] # Path["a/b/"].join("c") # => Path["a/b/c"] # ``` - def join(part) : Path + def join(part : String | Path) : Path # If we are joining a single part we can use `String.new` instead of # `String.build` which avoids an extra allocation. # Given that `File.join(arg1, arg2)` is the most common usage @@ -954,7 +954,7 @@ struct Path end end - private def empty? + private def empty? : Bool @name.empty? || @name == "." end @@ -1096,7 +1096,7 @@ struct Path # Path.posix("foo") == Path.posix("FOO") # => false # Path.windows("foo") == Path.windows("FOO") # => true # ``` - def ==(other : self) + def ==(other : self) : Bool return false if @kind != other.@kind @name.compare(other.@name, case_insensitive: windows? || other.windows?) == 0 @@ -1205,7 +1205,7 @@ struct Path end end - private def unc_share? + private def unc_share? : Tuple(Int32, Int32 | Nil)? # Test for UNC share # path: //share/share # part: 1122222 33333 @@ -1322,7 +1322,7 @@ struct Path end # :nodoc: - def separators + def separators : Tuple(Char) | Tuple(Char, Char) Path.separators(@kind) end @@ -1330,11 +1330,11 @@ struct Path ends_with_separator?(@name) end - private def ends_with_separator?(name) + private def ends_with_separator?(name : String) : Bool separators.any? { |separator| name.ends_with?(separator) } end - private def starts_with_separator?(name = @name) + private def starts_with_separator?(name : String = @name) : Bool separators.any? { |separator| name.starts_with?(separator) } end diff --git a/src/process/executable_path.cr b/src/process/executable_path.cr index 1a7b0c44d55d..dbb15f5fc831 100644 --- a/src/process/executable_path.cr +++ b/src/process/executable_path.cr @@ -41,7 +41,7 @@ class Process end end - private def self.file_executable?(path) + private def self.file_executable?(path : Path) : Bool unless File.info?(path, follow_symlinks: true).try &.file? return false end diff --git a/src/process/shell.cr b/src/process/shell.cr index e206c6c19a5a..80a3c844cc0e 100644 --- a/src/process/shell.cr +++ b/src/process/shell.cr @@ -64,7 +64,7 @@ class Process String.build { |io| quote_windows(io, args) } end - private def self.quote_windows(io : IO, args) + private def self.quote_windows(io : IO, args : Tuple(String) | Array(String)) : Nil args.join(io, ' ') do |arg| need_quotes = arg.empty? || arg.includes?(' ') || arg.includes?('\t') diff --git a/src/process/status.cr b/src/process/status.cr index 32b26c735146..979106967651 100644 --- a/src/process/status.cr +++ b/src/process/status.cr @@ -95,7 +95,7 @@ enum Process::ExitReason # Returns `true` if the process exited abnormally. # # This includes all values except `Normal`. - def abnormal? + def abnormal? : Bool !normal? end @@ -107,7 +107,7 @@ enum Process::ExitReason # ``` # # `Status#description` provides more detail for a specific process status. - def description + def description : String case self in .normal? "Process exited normally" @@ -309,7 +309,7 @@ class Process::Status exit_code? == 0 end - private def signal_code + private def signal_code : Int32 # define __WTERMSIG(status) ((status) & 0x7f) @exit_status & 0x7f end @@ -412,7 +412,7 @@ class Process::Status # ``` # # `ExitReason#description` provides the specific messages for non-signal exits. - def description + def description : String if exit_reason.signal? && (signal = exit_signal?) "Process received and didn't handle signal #{signal}" else diff --git a/src/random/isaac.cr b/src/random/isaac.cr index 294d439fb82d..c5c675fa8a36 100644 --- a/src/random/isaac.cr +++ b/src/random/isaac.cr @@ -12,11 +12,11 @@ class Random::ISAAC private getter bb private getter cc - private def random_seeds + private def random_seeds : StaticArray(UInt32, 8) Random::Secure.rand(StaticArray(UInt32, 8)) end - def initialize(seeds = random_seeds) + def initialize(seeds : Array(Int32) | StaticArray(UInt32, 8) = random_seeds) @rsl = StaticArray(UInt32, 256).new { 0_u32 } @mm = StaticArray(UInt32, 256).new { 0_u32 } @counter = 0 @@ -37,7 +37,7 @@ class Random::ISAAC @rsl[counter] end - private def isaac + private def isaac : Nil @cc &+= 1 @bb &+= cc @@ -55,7 +55,7 @@ class Random::ISAAC end end - private def init_by_array(seeds) + private def init_by_array(seeds : Array(Int32) | StaticArray(UInt32, 8)) : Int32 seed_len = seeds.size 256.times { |i| @rsl[i] = i < seed_len ? seeds[i].to_u32 : 0_u32 } diff --git a/src/random/pcg32.cr b/src/random/pcg32.cr index bc34f736b282..d38d8f950581 100644 --- a/src/random/pcg32.cr +++ b/src/random/pcg32.cr @@ -39,11 +39,11 @@ class Random::PCG32 @state : UInt64 @inc : UInt64 - def self.new + def self.new : Random::PCG32 new(Random::Secure.rand(UInt64::MIN..UInt64::MAX), Random::Secure.rand(UInt64::MIN..UInt64::MAX)) end - def initialize(initstate : UInt64, initseq = 0_u64) + def initialize(initstate : UInt64, initseq : UInt64 = 0_u64) # initialize to zeros to prevent compiler complains @state = 0_u64 @inc = 0_u64 @@ -54,7 +54,7 @@ class Random::PCG32 new_seed(Random::Secure.rand(UInt64::MIN..UInt64::MAX), Random::Secure.rand(UInt64::MIN..UInt64::MAX)) end - def new_seed(initstate : UInt64, initseq = 0_u64) : UInt32 + def new_seed(initstate : UInt64, initseq : UInt64 = 0_u64) : UInt32 @state = 0_u64 @inc = (initseq << 1) | 1 next_u @@ -70,7 +70,7 @@ class Random::PCG32 UInt32.new!(xorshifted.rotate_right(rot)) end - def jump(delta) + def jump(delta : Int32) : UInt64 deltau64 = UInt64.new!(delta) acc_mult = 1u64 acc_plus = 0u64 diff --git a/src/random/secure.cr b/src/random/secure.cr index a6b9df03063f..36c0db191c08 100644 --- a/src/random/secure.cr +++ b/src/random/secure.cr @@ -19,7 +19,7 @@ module Random::Secure extend Random extend self - def next_u + def next_u : UInt8 Crystal::System::Random.next_u end diff --git a/src/reference.cr b/src/reference.cr index 42bdcba2327a..eb035519959b 100644 --- a/src/reference.cr +++ b/src/reference.cr @@ -73,7 +73,7 @@ class Reference end # Returns `false`: a reference is never `nil`. - def same?(other : Nil) + def same?(other : Nil) : Bool false end diff --git a/src/regex/lib_pcre2.cr b/src/regex/lib_pcre2.cr index 6f45a4465219..65cb3b825f74 100644 --- a/src/regex/lib_pcre2.cr +++ b/src/regex/lib_pcre2.cr @@ -191,7 +191,7 @@ lib LibPCRE2 INTERNAL_DUPMATCH = -65 DFA_UINVALID_UTF = -66 - def utf8_validity? + def utf8_validity? : Bool in?(UTF8_ERR21..UTF8_ERR1) end end diff --git a/src/regex/match_data.cr b/src/regex/match_data.cr index 3fcbc5c424ac..141e788919ca 100644 --- a/src/regex/match_data.cr +++ b/src/regex/match_data.cr @@ -67,7 +67,7 @@ class Regex # "Crystal".match!(/r/).begin(1) # IndexError: Invalid capture group index: 1 # "Crystal".match!(/r(x)?/).begin(1) # IndexError: Capture group 1 was not matched # ``` - def begin(n = 0) : Int32 + def begin(n : Int32 = 0) : Int32 @string.byte_index_to_char_index(byte_begin(n)).not_nil! end @@ -86,7 +86,7 @@ class Regex # "Crystal".match!(/r/).end(1) # IndexError: Invalid capture group index: 1 # "Crystal".match!(/r(x)?/).end(1) # IndexError: Capture group 1 was not matched # ``` - def end(n = 0) : Int32 + def end(n : Int32 = 0) : Int32 @string.byte_index_to_char_index(byte_end(n)).not_nil! end @@ -105,7 +105,7 @@ class Regex # "Crystal".match!(/r/).byte_begin(1) # IndexError: Invalid capture group index: 1 # "Crystal".match!(/r(x)?/).byte_begin(1) # IndexError: Capture group 1 was not matched # ``` - def byte_begin(n = 0) : Int32 + def byte_begin(n : Int32 = 0) : Int32 check_index_out_of_bounds n byte_range(n) { |normalized_n| raise_capture_group_was_not_matched(normalized_n) }.begin end @@ -125,7 +125,7 @@ class Regex # "Crystal".match!(/r/).byte_end(1) # IndexError: Invalid capture group index: 1 # "Crystal".match!(/r(x)?/).byte_end(1) # IndexError: Capture group 1 was not matched # ``` - def byte_end(n = 0) : Int32 + def byte_end(n : Int32 = 0) : Int32 check_index_out_of_bounds n byte_range(n) { |normalized_n| raise_capture_group_was_not_matched(normalized_n) }.end end @@ -390,7 +390,7 @@ class Regex self end - def ==(other : Regex::MatchData) + def ==(other : Regex::MatchData) : Bool return false unless size == other.size return false unless regex == other.regex return false unless string == other.string @@ -405,19 +405,19 @@ class Regex Slice.new(@ovector, size * 2).hash(hasher) end - private def check_index_out_of_bounds(index) + private def check_index_out_of_bounds(index : Int32) : Nil raise_invalid_group_index(index) unless valid_group?(index) end - private def valid_group?(index) + private def valid_group?(index : Int32) : Bool -size <= index < size end - private def raise_invalid_group_index(index) + private def raise_invalid_group_index(index : Int32) : Nil raise IndexError.new("Invalid capture group index: #{index}") end - private def raise_capture_group_was_not_matched(index) + private def raise_capture_group_was_not_matched(index : Int32) : Nil raise IndexError.new("Capture group #{index} was not matched") end end diff --git a/src/regex/pcre2.cr b/src/regex/pcre2.cr index b56a4ea68839..81adc7f33508 100644 --- a/src/regex/pcre2.cr +++ b/src/regex/pcre2.cr @@ -22,7 +22,7 @@ module Regex::PCRE2 end # :nodoc: - def initialize(*, _source @source : String, _options @options) + def initialize(*, _source @source : String, _options @options : Regex::Options) options = pcre2_compile_options(options) | LibPCRE2::UTF | LibPCRE2::DUPNAMES | LibPCRE2::UCP @re = PCRE2.compile(source, options) do |error_message| raise ArgumentError.new(error_message) @@ -54,14 +54,14 @@ module Regex::PCRE2 end end - protected def self.get_error_message(errorcode) + protected def self.get_error_message(errorcode : Int32 | LibPCRE2::Error) : String String.new(256) do |buffer| bytesize = LibPCRE2.get_error_message(errorcode, buffer, 256) {bytesize, 0} end end - private def pcre2_compile_options(options) + private def pcre2_compile_options(options : Regex::Options) : Int32 flag = 0 Regex::CompileOptions.each do |option| if options.includes?(option) @@ -92,11 +92,11 @@ module Regex::PCRE2 flag end - def self.supports_compile_flag?(options) + def self.supports_compile_flag?(options : Regex::Options) : Bool true end - private def pcre2_match_options(options) + private def pcre2_match_options(options : Regex::Options) : Int32 flag = 0 Regex::Options.each do |option| if options.includes?(option) @@ -125,7 +125,7 @@ module Regex::PCRE2 flag end - private def pcre2_match_options(options : Regex::MatchOptions) + private def pcre2_match_options(options : Regex::MatchOptions) : Int32 flag = 0 Regex::MatchOptions.each do |option| if options.includes?(option) @@ -146,11 +146,11 @@ module Regex::PCRE2 flag end - def self.supports_match_flag?(options) + def self.supports_match_flag?(options : Regex::MatchOptions) : Bool true end - protected def self.error_impl(source) + protected def self.error_impl(source : String) : String? code = PCRE2.compile(source, LibPCRE2::UTF | LibPCRE2::DUPNAMES | LibPCRE2::UCP) do |error_message| return error_message end @@ -160,20 +160,20 @@ module Regex::PCRE2 nil end - private def pattern_info(what) + private def pattern_info(what : Int32) : UInt32 value = uninitialized UInt32 pattern_info(what, pointerof(value)) value end - private def pattern_info(what, where) + private def pattern_info(what : Int32, where : Pointer(Pointer(UInt8)) | Pointer(UInt32)) : Nil ret = LibPCRE2.pattern_info(@re, what, where) if ret != 0 raise "Error pattern_info #{what}: #{ret}" end end - private def name_table_impl + private def name_table_impl : Hash(Int32, String) lookup = Hash(Int32, String).new each_named_capture_group do |capture_number, name_entry| @@ -200,11 +200,11 @@ module Regex::PCRE2 end end - private def capture_count_impl + private def capture_count_impl : Int32 pattern_info(LibPCRE2::INFO_CAPTURECOUNT).to_i32 end - private def match_impl(str, byte_index, options) + private def match_impl(str : String, byte_index : Int32, options : Regex::MatchOptions | Regex::Options) : Regex::MatchData? match_data = match_data(str, byte_index, options) || return ovector_count = LibPCRE2.get_ovector_count(match_data) @@ -218,7 +218,7 @@ module Regex::PCRE2 ::Regex::MatchData.new(self, @re, str, byte_index, ovector.to_unsafe, ovector_count.to_i32 &- 1) end - private def matches_impl(str, byte_index, options) + private def matches_impl(str : String, byte_index : Int32, options : Regex::MatchOptions | Regex::Options) : Bool if match_data = match_data(str, byte_index, options) true else @@ -238,7 +238,7 @@ module Regex::PCRE2 # can't be any concurrent access to the JIT stack. @@jit_stack = Crystal::ThreadLocalValue(LibPCRE2::JITStack*).new - def self.jit_stack + def self.jit_stack : Pointer(LibPCRE2::JITStack) @@jit_stack.get do LibPCRE2.jit_stack_create(32_768, 1_048_576, nil) || raise "Error allocating JIT stack" end @@ -250,20 +250,20 @@ module Regex::PCRE2 # This buffer is heap-allocated and should be re-used for subsequent matches. @match_data = Crystal::ThreadLocalValue(LibPCRE2::MatchData*).new - private def match_data + private def match_data : Pointer(LibPCRE2::MatchData) @match_data.get do LibPCRE2.match_data_create_from_pattern(@re, nil) end end - def finalize + def finalize : Nil @match_data.consume_each do |match_data| LibPCRE2.match_data_free(match_data) end LibPCRE2.code_free @re end - private def match_data(str, byte_index, options) + private def match_data(str : String, byte_index : Int32, options : Regex::MatchOptions | Regex::Options) : Pointer(LibPCRE2::MatchData)? match_data = self.match_data match_count = LibPCRE2.match(@re, str, str.bytesize, byte_index, pcre2_match_options(options), match_data, PCRE2.match_context) diff --git a/src/semantic_version.cr b/src/semantic_version.cr index 476360b32a0e..5ea060e16bb6 100644 --- a/src/semantic_version.cr +++ b/src/semantic_version.cr @@ -92,7 +92,7 @@ struct SemanticVersion # current_version.copy_with(patch: 2) # => SemanticVersion(@build=nil, @major=1, @minor=1, @patch=2, @prerelease=SemanticVersion::Prerelease(@identifiers=["rc"])) # current_version.copy_with(prerelease: nil) # => SemanticVersion(@build=nil, @major=1, @minor=1, @patch=1, @prerelease=SemanticVersion::Prerelease(@identifiers=[])) # ``` - def copy_with(major : Int32 = @major, minor : Int32 = @minor, patch : Int32 = @patch, prerelease : String | Prerelease | Nil = @prerelease, build : String? = @build) + def copy_with(major : Int32 = @major, minor : Int32 = @minor, patch : Int32 = @patch, prerelease : String | Prerelease | Nil = @prerelease, build : String? = @build) : SemanticVersion SemanticVersion.new major, minor, patch, prerelease, build end @@ -104,7 +104,7 @@ struct SemanticVersion # current_version = SemanticVersion.new 1, 1, 1, "rc" # current_version.bump_major # => SemanticVersion(@build=nil, @major=2, @minor=0, @patch=0, @prerelease=SemanticVersion::Prerelease(@identifiers=[])) # ``` - def bump_major + def bump_major : SemanticVersion copy_with(major: major + 1, minor: 0, patch: 0, prerelease: nil, build: nil) end @@ -116,7 +116,7 @@ struct SemanticVersion # current_version = SemanticVersion.new 1, 1, 1, "rc" # current_version.bump_minor # => SemanticVersion(@build=nil, @major=1, @minor=2, @patch=0, @prerelease=SemanticVersion::Prerelease(@identifiers=[])) # ``` - def bump_minor + def bump_minor : SemanticVersion copy_with(minor: minor + 1, patch: 0, prerelease: nil, build: nil) end @@ -130,7 +130,7 @@ struct SemanticVersion # next_patch = current_version.bump_patch # => SemanticVersion(@build=nil, @major=1, @minor=1, @patch=1, @prerelease=SemanticVersion::Prerelease(@identifiers=[])) # next_patch.bump_patch # => SemanticVersion(@build=nil, @major=1, @minor=1, @patch=2, @prerelease=SemanticVersion::Prerelease(@identifiers=[])) # ``` - def bump_patch + def bump_patch : SemanticVersion if prerelease.identifiers.empty? copy_with(patch: patch + 1, prerelease: nil, build: nil) else @@ -245,19 +245,19 @@ struct SemanticVersion 0 end - private def compare(x : Int32, y : String) + private def compare(x : Int32, y : String) : Int32 -1 end - private def compare(x : String, y : Int32) + private def compare(x : String, y : Int32) : Int32 1 end - private def compare(x : Int32, y : Int32) + private def compare(x : Int32, y : Int32) : Int32 x <=> y end - private def compare(x : String, y : String) + private def compare(x : String, y : String) : Int32 x <=> y end end diff --git a/src/signal.cr b/src/signal.cr index 37999c76b9e1..7093abcbd11e 100644 --- a/src/signal.cr +++ b/src/signal.cr @@ -128,7 +128,7 @@ enum Signal : Int32 # # ... # end # ``` - def trap_handler? + def trap_handler? : Proc(Signal, Nil)? {% if @type.has_constant?("CHLD") %} return Crystal::System::Signal.child_handler if self == CHLD {% end %} diff --git a/src/slice.cr b/src/slice.cr index 266d7bb31249..791e78b18893 100644 --- a/src/slice.cr +++ b/src/slice.cr @@ -67,7 +67,7 @@ struct Slice(T) # # String.new(slice) # => "abc" # ``` - def initialize(@pointer : Pointer(T), size : Int, *, @read_only = false) + def initialize(@pointer : Pointer(T), size : Int, *, @read_only : Bool = false) @size = size.to_i32 end @@ -118,7 +118,7 @@ struct Slice(T) # slice = Slice.new(3, 10) # slice # => Slice[10, 10, 10] # ``` - def self.new(size : Int, value : T, *, read_only = false) + def self.new(size : Int, value : T, *, read_only : Bool = false) : Slice(Int32) | Slice(UInt8) new(size, read_only: read_only) { value } end diff --git a/src/socket/address.cr b/src/socket/address.cr index c07505ad43ab..aaa0190bacf0 100644 --- a/src/socket/address.cr +++ b/src/socket/address.cr @@ -8,7 +8,7 @@ class Socket # Returns either an `IPAddress` or `UNIXAddress` from the internal OS # representation. Only INET, INET6 and UNIX families are supported. - def self.from(sockaddr : LibC::Sockaddr*, addrlen) : Address + def self.from(sockaddr : LibC::Sockaddr*, addrlen : UInt32) : Address case family = Family.new(sockaddr.value.sa_family) when Family::INET6 IPAddress.new(sockaddr.as(LibC::SockaddrIn6*), addrlen.to_i) @@ -106,7 +106,7 @@ class Socket # Socket::IPAddress.new("127.0.0.1", 8080) # => Socket::IPAddress(127.0.0.1:8080) # Socket::IPAddress.new("fe80::2ab2:bdff:fe59:8e2c", 1234) # => Socket::IPAddress([fe80::2ab2:bdff:fe59:8e2c]:1234) # ``` - def self.new(address : String, port : Int32) + def self.new(address : String, port : Int32) : Socket::IPAddress raise Error.new("Invalid port number: #{port}") unless IPAddress.valid_port?(port) if v4_fields = parse_v4_fields?(address) @@ -122,7 +122,7 @@ class Socket # Creates an `IPAddress` from the internal OS representation. Supports both # INET and INET6 families. - def self.from(sockaddr : LibC::Sockaddr*, addrlen) : IPAddress + def self.from(sockaddr : LibC::Sockaddr*, addrlen : UInt32 | Int32) : IPAddress case family = Family.new(sockaddr.value.sa_family) when Family::INET6 new(sockaddr.as(LibC::SockaddrIn6*), addrlen.to_i) @@ -201,7 +201,7 @@ class Socket parse_v4_fields?(str.to_slice) end - private def self.parse_v4_fields?(bytes : Bytes) + private def self.parse_v4_fields?(bytes : Bytes) : StaticArray(UInt8, 4)? # port of https://git.musl-libc.org/cgit/musl/tree/src/network/inet_pton.c?id=7e13e5ae69a243b90b90d2f4b79b2a150f806335 fields = StaticArray(UInt8, 4).new(0) ptr = bytes.to_unsafe @@ -252,7 +252,7 @@ class Socket parse_v6_fields?(str.to_slice) end - private def self.parse_v6_fields?(bytes : Bytes) + private def self.parse_v6_fields?(bytes : Bytes) : StaticArray(UInt16, 8)? # port of https://git.musl-libc.org/cgit/musl/tree/src/network/inet_pton.c?id=7e13e5ae69a243b90b90d2f4b79b2a150f806335 ptr = bytes.to_unsafe finish = ptr + bytes.size @@ -323,7 +323,7 @@ class Socket fields end - private def self.from_hex(ch : UInt8) + private def self.from_hex(ch : UInt8) : UInt8 if 0x30 <= ch <= 0x39 ch &- 0x30 elsif 0x41 <= ch <= 0x46 @@ -360,7 +360,7 @@ class Socket v4(fields, port) end - private def self.to_v4_field(field) + private def self.to_v4_field(field : Int32) : UInt8 0 <= field <= 0xff ? field.to_u8! : raise Error.new("Invalid IPv4 field: #{field}") end @@ -385,7 +385,7 @@ class Socket v6(fields, port) end - private def self.to_v6_field(field) + private def self.to_v6_field(field : Int32) : UInt16 0 <= field <= 0xffff ? field.to_u16! : raise Error.new("Invalid IPv6 field: #{field}") end @@ -409,7 +409,7 @@ class Socket v4_mapped_v6(v4_fields, port) end - private def self.ipv6_from_addr16(bytes : UInt16[8]) + private def self.ipv6_from_addr16(bytes : UInt16[8]) : LibC::In6Addr addr = LibC::In6Addr.new {% if flag?(:darwin) || flag?(:bsd) %} addr.__u6_addr.__u6_addr16 = bytes @@ -432,13 +432,13 @@ class Socket addr end - protected def initialize(sockaddr : LibC::SockaddrIn6*, @size) + protected def initialize(sockaddr : LibC::SockaddrIn6*, @size : Int32) @family = Family::INET6 @addr = sockaddr.value.sin6_addr @port = IPAddress.endian_swap(sockaddr.value.sin6_port).to_i end - protected def initialize(sockaddr : LibC::SockaddrIn*, @size) + protected def initialize(sockaddr : LibC::SockaddrIn*, @size : Int32) @family = Family::INET @addr = sockaddr.value.sin_addr @port = IPAddress.endian_swap(sockaddr.value.sin_port).to_i @@ -548,7 +548,7 @@ class Socket # # IPv4 addresses in `169.254.0.0/16` reserved by [RFC 3927](https://www.rfc-editor.org/rfc/rfc3927) and Link-Local IPv6 # Unicast Addresses in `fe80::/10` reserved by [RFC 4291](https://tools.ietf.org/html/rfc4291) are considered link-local. - def link_local? + def link_local? : Bool case addr = @addr in LibC::InAddr addr.s_addr & 0x000000ffff_u32 == 0x0000fea9_u32 # 169.254.0.0/16 @@ -557,7 +557,7 @@ class Socket end end - private def ipv6_addr8(addr : LibC::In6Addr) + private def ipv6_addr8(addr : LibC::In6Addr) : StaticArray(UInt8, 16) {% if flag?(:darwin) || flag?(:bsd) %} addr.__u6_addr.__u6_addr8 {% elsif flag?(:linux) && flag?(:musl) %} @@ -577,7 +577,7 @@ class Socket def_equals_and_hash family, port, address_value - protected def address_value + protected def address_value : UInt128 | UInt32 case addr = @addr in LibC::InAddr addr.s_addr @@ -609,14 +609,14 @@ class Socket end end - private def address_to_s(io : IO, addr : LibC::InAddr) + private def address_to_s(io : IO, addr : LibC::InAddr) : String::Builder | IO::Memory io << (addr.s_addr & 0xFF) io << '.' << (addr.s_addr >> 8 & 0xFF) io << '.' << (addr.s_addr >> 16 & 0xFF) io << '.' << (addr.s_addr >> 24) end - private def address_to_s(io : IO, addr : LibC::In6Addr) + private def address_to_s(io : IO, addr : LibC::In6Addr) : Nil | String::Builder | IO::Memory bytes = ipv6_addr8(addr) if Slice.new(bytes.to_unsafe, 10).all?(&.zero?) && bytes[10] == 0xFF && bytes[11] == 0xFF io << "::ffff:" << bytes[12] << '.' << bytes[13] << '.' << bytes[14] << '.' << bytes[15] @@ -712,7 +712,7 @@ class Socket end end - private def to_sockaddr_in6(addr) + private def to_sockaddr_in6(addr : LibC::In6Addr) : Pointer(LibC::Sockaddr) sockaddr = Pointer(LibC::SockaddrIn6).malloc sockaddr.value.sin6_family = family sockaddr.value.sin6_port = IPAddress.endian_swap(port.to_u16!) @@ -720,7 +720,7 @@ class Socket sockaddr.as(LibC::Sockaddr*) end - private def to_sockaddr_in(addr) + private def to_sockaddr_in(addr : LibC::InAddr) : Pointer(LibC::Sockaddr) sockaddr = Pointer(LibC::SockaddrIn).malloc sockaddr.value.sin_family = family sockaddr.value.sin_port = IPAddress.endian_swap(port.to_u16!) @@ -779,7 +779,7 @@ class Socket end # Creates an `UNIXSocket` from the internal OS representation. - def self.from(sockaddr : LibC::Sockaddr*, addrlen) : UNIXAddress + def self.from(sockaddr : LibC::Sockaddr*, addrlen : Int32) : UNIXAddress {% if flag?(:wasm32) %} raise NotImplementedError.new "Socket::UNIXAddress.from" {% else %} @@ -865,7 +865,7 @@ class Socket # Returns `true` if the string represents a valid IPv4 or IPv6 address. @[Deprecated("Use `IPAddress.valid?` instead")] - def self.ip?(string : String) + def self.ip?(string : String) : Bool IPAddress.valid?(string) end end diff --git a/src/socket/addrinfo.cr b/src/socket/addrinfo.cr index 411c09143411..62b11d237b5d 100644 --- a/src/socket/addrinfo.cr +++ b/src/socket/addrinfo.cr @@ -46,7 +46,7 @@ class Socket # # addrinfos = Socket::Addrinfo.resolve("example.org", "http", type: Socket::Type::STREAM, protocol: Socket::Protocol::TCP) # ``` - def self.resolve(domain : String, service, family : Family? = nil, type : Type = nil, protocol : Protocol = Protocol::IP, timeout = nil) : Array(Addrinfo) + def self.resolve(domain : String, service : Int32, family : Family? = nil, type : Type = nil, protocol : Protocol = Protocol::IP, timeout : Nil = nil) : Array(Addrinfo) addrinfos = [] of Addrinfo getaddrinfo(domain, service, family, type, protocol, timeout) do |addrinfo| @@ -102,7 +102,7 @@ class Socket end @[Deprecated("Use `.from_os_error` instead")] - def self.new(error_code : Int32, message, domain) + def self.new(error_code : Int32, message : String, domain : String) : Socket::Addrinfo::Error from_os_error(message, Errno.new(error_code), domain: domain, type: nil, service: nil, protocol: nil) end @@ -111,19 +111,19 @@ class Socket new error_code, nil, domain: domain end - protected def self.new_from_os_error(message : String?, os_error, *, domain, type, service, protocol, **opts) + protected def self.new_from_os_error(message : String?, os_error : Errno, *, domain : String, type : Socket::Type?, service : Int32?, protocol : Socket::Protocol?, **opts) : Socket::Addrinfo::Error new(message, **opts) end - protected def self.new_from_os_error(message : String?, os_error, *, domain, **opts) + protected def self.new_from_os_error(message : String?, os_error : Errno, *, domain : String, **opts) : Socket::Addrinfo::Error new(message, **opts) end - def self.build_message(message, *, domain, **opts) + def self.build_message(message : String?, *, domain : String, **opts) : String "Hostname lookup for #{domain} failed" end - def self.os_error_message(os_error : Errno | WinError, *, type, service, protocol, **opts) + def self.os_error_message(os_error : Errno | WinError, *, type : Socket::Type?, service : Int32?, protocol : Socket::Protocol?, **opts) : String # when `EAI_NONAME` etc. is an integer then only `os_error.value` can # match; when `EAI_NONAME` is a `WinError` then `os_error` itself can # match @@ -168,7 +168,7 @@ class Socket # # addrinfos = Socket::Addrinfo.tcp("example.org", 80) # ``` - def self.tcp(domain : String, service, family = Family::UNSPEC, timeout = nil) : Array(Addrinfo) + def self.tcp(domain : String, service : Int32, family : Socket::Family = Family::UNSPEC, timeout : Nil = nil) : Array(Addrinfo) resolve(domain, service, family, Type::STREAM, Protocol::TCP, timeout) end @@ -187,7 +187,7 @@ class Socket # # addrinfos = Socket::Addrinfo.udp("example.org", 53) # ``` - def self.udp(domain : String, service, family = Family::UNSPEC, timeout = nil) : Array(Addrinfo) + def self.udp(domain : String, service : Int32, family : Socket::Family = Family::UNSPEC, timeout : Nil = nil) : Array(Addrinfo) resolve(domain, service, family, Type::DGRAM, Protocol::UDP, timeout) end diff --git a/src/socket/common.cr b/src/socket/common.cr index 19f1700a2cbd..8d937c4104f3 100644 --- a/src/socket/common.cr +++ b/src/socket/common.cr @@ -50,7 +50,7 @@ class Socket < IO end class Error < IO::Error - private def self.new_from_os_error(message, os_error, **opts) + private def self.new_from_os_error(message : String?, os_error : Errno | WasiError | WinError | Nil, **opts) : Socket::Error case os_error when Errno::ECONNREFUSED Socket::ConnectError.new(message, **opts) diff --git a/src/socket/ip_socket.cr b/src/socket/ip_socket.cr index 918b4d2b8591..a961fc64931a 100644 --- a/src/socket/ip_socket.cr +++ b/src/socket/ip_socket.cr @@ -20,7 +20,7 @@ class IPSocket < Socket @remote_address = nil end - def bind(addr) + def bind(addr : Socket::IPAddress | Int32) : Nil super(addr) ensure @local_address = nil diff --git a/src/socket/tcp_server.cr b/src/socket/tcp_server.cr index c5cf3e1fcef0..a4ca0b5eb388 100644 --- a/src/socket/tcp_server.cr +++ b/src/socket/tcp_server.cr @@ -33,7 +33,7 @@ class TCPServer < TCPSocket end # Binds a socket to the *host* and *port* combination. - def initialize(host : String, port : Int, backlog : Int = SOMAXCONN, dns_timeout = nil, reuse_port : Bool = false) + def initialize(host : String, port : Int, backlog : Int = SOMAXCONN, dns_timeout : Nil = nil, reuse_port : Bool = false) Addrinfo.tcp(host, port, timeout: dns_timeout) do |addrinfo| super(addrinfo.family, addrinfo.type, addrinfo.protocol) diff --git a/src/socket/tcp_socket.cr b/src/socket/tcp_socket.cr index 4edcb3d08e5f..9425b16c5cbc 100644 --- a/src/socket/tcp_socket.cr +++ b/src/socket/tcp_socket.cr @@ -15,7 +15,7 @@ require "./ip_socket" # ``` class TCPSocket < IPSocket # Creates a new `TCPSocket`, waiting to be connected. - def self.new(family : Family = Family::INET, blocking = false) + def self.new(family : Family = Family::INET, blocking : Bool = false) : TCPSocket super(family, Type::STREAM, Protocol::TCP, blocking) end @@ -26,7 +26,7 @@ class TCPSocket < IPSocket # must be in seconds (integers or floats). # # NOTE: *dns_timeout* is currently only supported on Windows. - def initialize(host : String, port, dns_timeout = nil, connect_timeout = nil, blocking = false) + def initialize(host : String, port : Int32, dns_timeout : Time::Span? = nil, connect_timeout : Time::Span? = nil, blocking : Bool = false) Addrinfo.tcp(host, port, timeout: dns_timeout) do |addrinfo| super(addrinfo.family, addrinfo.type, addrinfo.protocol, blocking) connect(addrinfo, timeout: connect_timeout) do |error| @@ -36,11 +36,11 @@ class TCPSocket < IPSocket end end - protected def initialize(family : Family, type : Type, protocol : Protocol = Protocol::IP, blocking = false) + protected def initialize(family : Family, type : Type, protocol : Protocol = Protocol::IP, blocking : Bool = false) super family, type, protocol, blocking end - protected def initialize(fd : Handle, family : Family, type : Type, protocol : Protocol = Protocol::IP, blocking = false) + protected def initialize(fd : Handle, family : Family, type : Type, protocol : Protocol = Protocol::IP, blocking : Bool = false) super fd, family, type, protocol, blocking end @@ -68,35 +68,35 @@ class TCPSocket < IPSocket end # Disables the Nagle algorithm when set to `true`, otherwise enables it. - def tcp_nodelay=(val : Bool) + def tcp_nodelay=(val : Bool) : Bool setsockopt_bool LibC::TCP_NODELAY, val, level: Protocol::TCP end # The amount of time in seconds the connection must be idle before sending keepalive probes. - def tcp_keepalive_idle + def tcp_keepalive_idle : Int32 system_tcp_keepalive_idle end - def tcp_keepalive_idle=(val : Int) + def tcp_keepalive_idle=(val : Int) : Int32 self.system_tcp_keepalive_idle = val end # The amount of time in seconds between keepalive probes. - def tcp_keepalive_interval + def tcp_keepalive_interval : Int32 system_tcp_keepalive_interval end - def tcp_keepalive_interval=(val : Int) + def tcp_keepalive_interval=(val : Int) : Int32 self.system_tcp_keepalive_interval = val val end # The number of probes sent, without response before dropping the connection. - def tcp_keepalive_count + def tcp_keepalive_count : Int32 system_tcp_keepalive_count end - def tcp_keepalive_count=(val : Int) + def tcp_keepalive_count=(val : Int) : Int32 self.system_tcp_keepalive_count = val end end diff --git a/src/socket/udp_socket.cr b/src/socket/udp_socket.cr index bba9d1aea39a..782e7fe74cfc 100644 --- a/src/socket/udp_socket.cr +++ b/src/socket/udp_socket.cr @@ -107,7 +107,7 @@ class UDPSocket < IPSocket # Sets whether transmitted multicast packets should be copied and sent back # to the originator, if the host has joined the multicast group. - def multicast_loopback=(val : Bool) + def multicast_loopback=(val : Bool) : Bool case @family when Family::INET setsockopt_bool LibC::IP_MULTICAST_LOOP, val, LibC::IPPROTO_IP @@ -142,7 +142,7 @@ class UDPSocket < IPSocket # Multicast datagrams with a `hoplimit` of `0` will not be transmitted on any # network, but may be delivered locally if the sending host belongs to the # destination group and multicast loopback is enabled. - def multicast_hops=(val : Int) + def multicast_hops=(val : Int) : Int32 case @family when Family::INET setsockopt LibC::IP_MULTICAST_TTL, val, LibC::IPPROTO_IP @@ -159,7 +159,7 @@ class UDPSocket < IPSocket # IPv4 interface address for subsequent transmissions. Setting the interface # to `0.0.0.0` will select the default interface. # Raises `Socket::Error` unless the socket is IPv4 and an IPv4 address is provided. - def multicast_interface(address : IPAddress) + def multicast_interface(address : IPAddress) : Int32 if @family == Family::INET addr = address.@addr if addr.is_a?(LibC::InAddr) @@ -176,7 +176,7 @@ class UDPSocket < IPSocket # from the primary network interface. This function overrides the default # IPv6 interface for subsequent transmissions. Setting the interface to # index `0` will select the default interface. - def multicast_interface(index : UInt32) + def multicast_interface(index : UInt32) : Int32 if @family == Family::INET6 setsockopt LibC::IPV6_MULTICAST_IF, index, LibC::IPPROTO_IPV6 else @@ -187,7 +187,7 @@ class UDPSocket < IPSocket # A host must become a member of a multicast group before it can receive # datagrams sent to the group. # Raises `Socket::Error` if an incompatible address is provided. - def join_group(address : IPAddress) + def join_group(address : IPAddress) : Int32 case @family when Family::INET group_modify(address, LibC::IP_ADD_MEMBERSHIP) @@ -201,7 +201,7 @@ class UDPSocket < IPSocket # Drops membership to the specified group. Memberships are automatically # dropped when the socket is closed or the process exits. # Raises `Socket::Error` if an incompatible address is provided. - def leave_group(address : IPAddress) + def leave_group(address : IPAddress) : Int32 case @family when Family::INET group_modify(address, LibC::IP_DROP_MEMBERSHIP) @@ -212,7 +212,7 @@ class UDPSocket < IPSocket end end - private def group_modify(ip, operation) + private def group_modify(ip : Socket::IPAddress, operation : Int32) : Int32 ip_addr = ip.@addr case @family diff --git a/src/spec.cr b/src/spec.cr index 474aa7c5a0dc..0c87a71de7cc 100644 --- a/src/spec.cr +++ b/src/spec.cr @@ -96,7 +96,7 @@ module Spec # :nodoc: # # Implement formatter configuration. - def configure_formatter(formatter, output_path = nil) + def configure_formatter(formatter : String, output_path : String? = nil) : Array(Spec::Formatter) | Spec::DotFormatter | Spec::VerboseFormatter | Spec::JUnitFormatter | Spec::TAPFormatter | Nil case formatter when "junit" junit_formatter = Spec::JUnitFormatter.file(Path.new(output_path.not_nil!)) @@ -108,7 +108,7 @@ module Spec end end - def main(args) + def main(args : Array(String)) : Nil Colorize.on_tty_only! begin diff --git a/src/steppable.cr b/src/steppable.cr index b7301b7e1414..c8b6a7e97233 100644 --- a/src/steppable.cr +++ b/src/steppable.cr @@ -70,7 +70,7 @@ module Steppable end # :ditto: - def step(*, to limit = nil, by step, exclusive : Bool = false) + def step(*, to limit : Char | Int8 | Nil | Int32 | UInt8 | Int16 | Float64 | Time | BigInt | Time::Span = nil, by step : Int32 | Float64 | Time::Span, exclusive : Bool = false) : Steppable::StepIterator(Char, Char, Int32) | Steppable::StepIterator(Int8, Int8, Int32) | Steppable::StepIterator(Int8, Nil, Int32) | Steppable::StepIterator(UInt8, Int32, Int32) | Steppable::StepIterator(UInt8, UInt8, Int32) | Steppable::StepIterator(Int16, Int16, Int32) | Steppable::StepIterator(Int32, Int32, Int32) | Steppable::StepIterator(Float64, Int32, Float64) | Steppable::StepIterator(Int32, Float64, Int32) | Steppable::StepIterator(Int32, Nil, Int32) | Steppable::StepIterator(Float64, Float64, Int32) | Steppable::StepIterator(Float64, Float64, Float64) | Steppable::StepIterator(Float64, Int32, Int32) | Steppable::StepIterator(Time, Time, Time::Span) | Steppable::StepIterator(BigInt, BigInt, Int32) | Steppable::StepIterator(Time::Span, Time::Span, Time::Span) raise ArgumentError.new("Zero step size") if step.zero? && limit != self StepIterator.new(self + (step - step), limit, step, exclusive: exclusive) diff --git a/src/string_pool.cr b/src/string_pool.cr index a4f2553a8d2e..546a5669a4b1 100644 --- a/src/string_pool.cr +++ b/src/string_pool.cr @@ -46,7 +46,7 @@ class StringPool # pool = StringPool.new(256) # pool.size # => 0 # ``` - def initialize(initial_capacity = 8) + def initialize(initial_capacity : Int32 = 8) @capacity = initial_capacity >= 8 ? Math.pw2ceil(initial_capacity) : 8 @hashes = Pointer(UInt64).malloc(@capacity, 0_u64) @values = Pointer(String).malloc(@capacity, "") @@ -116,7 +116,7 @@ class StringPool # pool.get("hey".to_unsafe, 3) # pool.size # => 1 # ``` - def get(str : UInt8*, len) : String + def get(str : UInt8*, len : Int32) : String hash = hash(str, len) get(hash, str, len) do |index| rehash if @size >= @capacity // 4 * 3 @@ -141,7 +141,7 @@ class StringPool # pool.empty? # => false # pool.get?("hey".to_unsafe, 3) # => "hey" # ``` - def get?(str : UInt8*, len) : String? + def get?(str : UInt8*, len : Int32) : String? hash = hash(str, len) get(hash, str, len) { nil } end @@ -163,7 +163,7 @@ class StringPool yield index end - private def put_on_rehash(hash : UInt64, entry : String) + private def put_on_rehash(hash : UInt64, entry : String) : String mask = (@capacity - 1).to_u64 index = hash & mask next_probe_offset = 1_u64 @@ -272,7 +272,7 @@ class StringPool end end - private def hash(str, len) + private def hash(str : Pointer(UInt8), len : Int32) : UInt64 hasher = Crystal::Hasher.new hasher = str.to_slice(len).hash(hasher) # hash should be non-zero, so `or` it with high bit diff --git a/src/string_scanner.cr b/src/string_scanner.cr index 5e0654bb60b2..7d78833ec3e2 100644 --- a/src/string_scanner.cr +++ b/src/string_scanner.cr @@ -68,7 +68,7 @@ class StringScanner end # Sets the *position* of the scan offset. - def offset=(position : Int) + def offset=(position : Int) : Int32 raise IndexError.new unless position >= 0 @byte_offset = @str.char_index_to_byte_index(position) || @str.bytesize end @@ -134,7 +134,7 @@ class StringScanner match(pattern, advance: true, anchored: false) end - private def match(pattern : Regex, advance = true, options = Regex::MatchOptions::ANCHORED) + private def match(pattern : Regex, advance : Bool = true, options : Regex::MatchOptions = Regex::MatchOptions::ANCHORED) : String? match = pattern.match_at_byte_index(@str, @byte_offset, options) @last_match = match if match @@ -148,7 +148,7 @@ class StringScanner end end - private def match(pattern : String | Char, advance = true, anchored = true) + private def match(pattern : String | Char, advance : Bool = true, anchored : Bool = true) : String? @last_match = nil if pattern.bytesize > @str.bytesize - @byte_offset nil @@ -295,7 +295,7 @@ class StringScanner # s["month"] # => "Dec" # s["day"] # => "12" # ``` - def [](n) : String + def [](n : Int32 | String) : String @last_match.not_nil![n] end @@ -321,7 +321,7 @@ class StringScanner # s.scan(/more/) # => nil # s[0]? # => nil # ``` - def []?(n) : String? + def []?(n : Int32 | String) : String? @last_match.try(&.[n]?) end @@ -340,13 +340,13 @@ class StringScanner end # Resets the scan offset to the beginning and clears the last match. - def reset + def reset : Int32 @last_match = nil @byte_offset = 0 end # Moves the scan offset to the end of the string and clears the last match. - def terminate + def terminate : Int32 @last_match = nil @byte_offset = @str.bytesize end @@ -358,7 +358,7 @@ class StringScanner # Extracts a string corresponding to string[offset,*len*], without advancing # the scan offset. - def peek(len) : String + def peek(len : Int32) : String @str[offset, len] end diff --git a/src/symbol.cr b/src/symbol.cr index 88b9d0db904e..6a6e40b066bb 100644 --- a/src/symbol.cr +++ b/src/symbol.cr @@ -62,7 +62,7 @@ struct Symbol # Symbol.needs_quotes? "string" # => false # Symbol.needs_quotes? "long string" # => true # ``` - def self.needs_quotes?(string) : Bool + def self.needs_quotes?(string : String) : Bool case string when "+", "-", "*", "&+", "&-", "&*", "/", "//", "==", "<", "<=", ">", ">=", "!", "!=", "=~", "!~" false @@ -78,7 +78,7 @@ struct Symbol # :nodoc: # Determines if a string needs to be quoted to be used for an external # parameter name or a named argument's key. - def self.needs_quotes_for_named_argument?(string) : Bool + def self.needs_quotes_for_named_argument?(string : String) : Bool case string when "", "_" true @@ -119,7 +119,7 @@ struct Symbol end end - def clone + def clone : Symbol self end end diff --git a/src/system/group.cr b/src/system/group.cr index 47b9768cca52..f7a38829b665 100644 --- a/src/system/group.cr +++ b/src/system/group.cr @@ -59,7 +59,7 @@ class System::Group Crystal::System::Group.from_id?(id) end - def to_s(io) + def to_s(io : String::Builder) : String::Builder io << name << " (" << id << ')' end end diff --git a/src/system/user.cr b/src/system/user.cr index 01c8d11d9e1c..2af3b8592a35 100644 --- a/src/system/user.cr +++ b/src/system/user.cr @@ -82,7 +82,7 @@ class System::User Crystal::System::User.from_id?(id) end - def to_s(io) + def to_s(io : String::Builder) : String::Builder io << username << " (" << id << ')' end end diff --git a/src/time.cr b/src/time.cr index 4b29114dd190..2fb19e59db7c 100644 --- a/src/time.cr +++ b/src/time.cr @@ -714,7 +714,7 @@ struct Time # If the resulting date-time is ambiguous due to time zone transitions, # a correct time will be returned, but it does not guarantee which. def shift(*, years : Int = 0, months : Int = 0, weeks : Int = 0, days : Int = 0, - hours : Int = 0, minutes : Int = 0, seconds : Int = 0, nanoseconds : Int = 0) + hours : Int = 0, minutes : Int = 0, seconds : Int = 0, nanoseconds : Int = 0) : Time seconds = seconds.to_i64 # Skip the entire month-based calculations if year and month are zero @@ -1122,7 +1122,7 @@ struct Time # # Number of seconds decimals can be selected with *fraction_digits*. # Values accepted are 0 (the default, no decimals), 3 (milliseconds), 6 (microseconds) or 9 (nanoseconds). - def to_rfc3339(*, fraction_digits : Int = 0) + def to_rfc3339(*, fraction_digits : Int = 0) : String Format::RFC_3339.format(to_utc, fraction_digits) end @@ -1174,7 +1174,7 @@ struct Time # into the given *io*. # # This is also compatible to [RFC 882](https://tools.ietf.org/html/rfc882) and [RFC 1123](https://tools.ietf.org/html/rfc1123#page-55). - def to_rfc2822(io : IO) + def to_rfc2822(io : IO) : String::Builder | IO::Memory Format::RFC_2822.format(to_utc, io) end @@ -1473,7 +1473,7 @@ struct Time # The valid range for *year* is `1..9999` and for *month* `1..12`. The value # of *day* is not validated and can exceed the number of days in the specified # month or even a year. - protected def self.absolute_days(year, month, day) : Int32 + protected def self.absolute_days(year : Int32, month : Int32, day : Int32) : Int32 days_per_month = leap_year?(year) ? DAYS_MONTH_LEAP : DAYS_MONTH days_in_year = day - 1 @@ -1488,11 +1488,11 @@ struct Time year * 365 + year // 4 - year // 100 + year // 400 + days_in_year end - protected def total_seconds + protected def total_seconds : Int64 @seconds end - protected def offset_seconds + protected def offset_seconds : Int64 @seconds + offset end @@ -1545,7 +1545,7 @@ struct Time {year, month, day, ordinal_day_in_year} end - protected def self.zone_offset_at(seconds, location) + protected def self.zone_offset_at(seconds : Int64, location : Time::Location) : Int32 unix = seconds - UNIX_EPOCH.total_seconds zone, range = location.lookup_with_boundaries(unix) diff --git a/src/time/format.cr b/src/time/format.cr index 6f09a1c90229..825a09e63e0d 100644 --- a/src/time/format.cr +++ b/src/time/format.cr @@ -80,7 +80,7 @@ struct Time::Format end # Parses a string into a `Time`. - def parse(string, location = @location) : Time + def parse(string : String, location : Time::Location? = @location) : Time parser = Parser.new(string) parser.visit(pattern) parser.time(location) diff --git a/src/time/format/custom/http_date.cr b/src/time/format/custom/http_date.cr index 25847b21aa00..e01b01a758e8 100644 --- a/src/time/format/custom/http_date.cr +++ b/src/time/format/custom/http_date.cr @@ -19,7 +19,7 @@ struct Time::Format # ``` module HTTP_DATE # Parses a string into a `Time`. - def self.parse(string, location = Time::Location::UTC) : Time + def self.parse(string : String, location : Time::Location = Time::Location::UTC) : Time parser = Parser.new(string) parser.http_date parser.time(location) @@ -28,7 +28,7 @@ struct Time::Format # Formats a `Time` into the given *io*. # # *time* is always converted to UTC. - def self.format(time : Time, io : IO) + def self.format(time : Time, io : IO) : String::Builder formatter = Formatter.new(time.to_utc, io) formatter.rfc_2822(time_zone_gmt: true, two_digit_day: true) io diff --git a/src/time/format/custom/iso_8601.cr b/src/time/format/custom/iso_8601.cr index b6e634c7a4de..36af3808c9c9 100644 --- a/src/time/format/custom/iso_8601.cr +++ b/src/time/format/custom/iso_8601.cr @@ -123,14 +123,14 @@ struct Time::Format # ``` module ISO_8601_DATE # Parses a string into a `Time`. - def self.parse(string, location : Time::Location? = Time::Location::UTC) : Time + def self.parse(string : String, location : Time::Location? = Time::Location::UTC) : Time parser = Parser.new(string) parser.year_month_day_iso_8601 parser.time(location) end # Formats a `Time` into the given *io*. - def self.format(time : Time, io : IO) + def self.format(time : Time, io : IO) : String::Builder formatter = Formatter.new(time, io) formatter.year_month_day_iso_8601 io @@ -152,14 +152,14 @@ struct Time::Format # ``` module ISO_8601_DATE_TIME # Parses a string into a `Time`. - def self.parse(string, location : Time::Location? = Time::Location::UTC) : Time + def self.parse(string : String, location : Time::Location? = Time::Location::UTC) : Time parser = Parser.new(string) parser.date_time_iso_8601 parser.time(location) end # Formats a `Time` into the given *io*. - def self.format(time : Time, io : IO) + def self.format(time : Time, io : IO) : String::Builder formatter = Formatter.new(time, io) formatter.rfc_3339 io diff --git a/src/time/format/custom/rfc_2822.cr b/src/time/format/custom/rfc_2822.cr index 3397cce8e471..6c436b642984 100644 --- a/src/time/format/custom/rfc_2822.cr +++ b/src/time/format/custom/rfc_2822.cr @@ -11,14 +11,14 @@ struct Time::Format # ``` module RFC_2822 # Parses a string into a `Time`. - def self.parse(string, kind = Time::Location::UTC) : Time + def self.parse(string : String, kind : Time::Location = Time::Location::UTC) : Time parser = Parser.new(string) parser.rfc_2822 parser.time(kind) end # Formats a `Time` into the given *io*. - def self.format(time : Time, io : IO) + def self.format(time : Time, io : IO) : String::Builder | IO::Memory formatter = Formatter.new(time, io) formatter.rfc_2822 io @@ -33,7 +33,7 @@ struct Time::Format end module Pattern - def rfc_2822(time_zone_gmt = false, two_digit_day = false) + def rfc_2822(time_zone_gmt : Bool = false, two_digit_day : Bool = false) : Bool? cfws? short_day_name_with_comma? if two_digit_day @@ -70,7 +70,7 @@ struct Time::Format end struct Parser - def short_day_name_with_comma? + def short_day_name_with_comma? : Bool? return unless current_char.ascii_letter? short_day_name @@ -79,7 +79,7 @@ struct Time::Format cfws end - def seconds_with_colon? + def seconds_with_colon? : Int32? if current_char == ':' next_char cfws? @@ -88,7 +88,7 @@ struct Time::Format end # comment or folding whitespace - def cfws? + def cfws? : Bool in_comment = false seen_whitespace = false loop do @@ -108,29 +108,29 @@ struct Time::Format seen_whitespace end - def cfws + def cfws : Bool cfws? || raise "Invalid format" end - def folding_white_space + def folding_white_space : Char? skip_space end end struct Formatter - def seconds_with_colon? + def seconds_with_colon? : Nil char ':' second end - def cfws? + def cfws? : Nil end - def cfws + def cfws : IO folding_white_space end - def folding_white_space + def folding_white_space : IO io << ' ' end end diff --git a/src/time/format/custom/yaml_date.cr b/src/time/format/custom/yaml_date.cr index ea5e081ecb1d..6e8606db9792 100644 --- a/src/time/format/custom/yaml_date.cr +++ b/src/time/format/custom/yaml_date.cr @@ -11,7 +11,7 @@ struct Time::Format # custom time parser, probably for this same reason. module YAML_DATE # Parses a string into a `Time`. - def self.parse?(string) : Time? + def self.parse?(string : String) : Time? parser = Parser.new(string) if parser.yaml_date_time? parser.time(Time::Location::UTC) rescue nil @@ -21,7 +21,7 @@ struct Time::Format end # Formats a `Time` into the given *io*. - def self.format(time : Time, io : IO) + def self.format(time : Time, io : IO) : Nil formatter = Formatter.new(time, io) if time.hour == 0 && time.minute == 0 && time.second == 0 && time.nanosecond == 0 @@ -40,7 +40,7 @@ struct Time::Format end struct Parser - def yaml_date_time? + def yaml_date_time? : Bool if (year = consume_number?(4)) && char?('-') @year = year else @@ -78,7 +78,7 @@ struct Time::Format true end - def yaml_time? + def yaml_time? : Bool if (hour = consume_number?(2)) && char?(':') @hour = hour else @@ -116,7 +116,7 @@ struct Time::Format end struct Formatter - def yaml_date_time + def yaml_date_time : Nil year_month_day char ' ' twenty_four_hour_time_with_seconds diff --git a/src/time/format/parser.cr b/src/time/format/parser.cr index 95bac1a5799d..02765aba429d 100644 --- a/src/time/format/parser.cr +++ b/src/time/format/parser.cr @@ -24,7 +24,7 @@ struct Time::Format @day_of_week : Time::DayOfWeek? @day_of_year : Int32? - def initialize(string) + def initialize(string : String) @reader = Char::Reader.new(string) @year = 1 @month = 1 @@ -89,11 +89,11 @@ struct Time::Format time end - def year + def year : Int32 @year = consume_number(4) end - def year_modulo_100 + def year_modulo_100 : Int32 year = consume_number(2) if 69 <= year <= 99 @year = year + 1900 @@ -104,11 +104,11 @@ struct Time::Format end end - def year_divided_by_100 + def year_divided_by_100 : Int32 @year = consume_number(2) * 100 end - def full_or_short_year + def full_or_short_year : Int32 @year = case year = consume_number(4) when 0..49 year + 2000 @@ -119,27 +119,27 @@ struct Time::Format end end - def calendar_week_year + def calendar_week_year : Int32 @calendar_week_year = consume_number(4) end - def calendar_week_year_modulo100 + def calendar_week_year_modulo100 : Int32 @calendar_week_year = consume_number(2) end - def month + def month : Int32 @month = consume_number(2) end - def month_zero_padded + def month_zero_padded : Int32 month end - def month_blank_padded + def month_blank_padded : Int32 @month = consume_number_blank_padded(2) end - def month_name + def month_name : Int32 string = consume_string if string.size < 3 raise "Invalid month" @@ -154,11 +154,11 @@ struct Time::Format end end - def month_name_upcase + def month_name_upcase : Int32 month_name end - def short_month_name + def short_month_name : Int32 string = consume_string if string.size != 3 raise "Invalid month" @@ -173,27 +173,27 @@ struct Time::Format end end - def short_month_name_upcase + def short_month_name_upcase : Int32 month_name end - def calendar_week_week + def calendar_week_week : Int32 @calendar_week_week = consume_number(2) end - def day_of_month + def day_of_month : Int32 @day = consume_number(2) end - def day_of_month_zero_padded + def day_of_month_zero_padded : Int32 @day = consume_number(2) end - def day_of_month_blank_padded + def day_of_month_blank_padded : Int32 @day = consume_number_blank_padded(2) end - def day_name + def day_name : Nil string = consume_string if string.size < 3 raise "Invalid day name" @@ -206,15 +206,15 @@ struct Time::Format end end - def day_name_upcase + def day_name_upcase : Nil day_name end - def short_day_name + def short_day_name : Nil day_name end - def short_day_name_upcase + def short_day_name_upcase : Nil day_name end @@ -226,51 +226,51 @@ struct Time::Format whitespace end - def day_of_year_zero_padded + def day_of_year_zero_padded : Int32 @day_of_year = consume_number(3) end - def hour_24_zero_padded + def hour_24_zero_padded : Int32 @hour_is_12 = false @hour = consume_number(2) end - def hour_24_blank_padded + def hour_24_blank_padded : Int32 @hour_is_12 = false @hour = consume_number_blank_padded(2) end - def hour_12_zero_padded + def hour_12_zero_padded : Bool hour_24_zero_padded @hour_is_12 = true end - def hour_12_blank_padded + def hour_12_blank_padded : Int32 @hour_is_12 = true @hour = consume_number_blank_padded(2) end - def minute + def minute : Int32 @minute = consume_number(2) end - def second + def second : Int32 @second = consume_number(2) end - def milliseconds + def milliseconds : Int32 second_decimals 3 end - def microseconds + def microseconds : Int32 second_decimals 6 end - def nanoseconds + def nanoseconds : Int32 second_decimals 9 end - def second_fraction + def second_fraction : Nil second_decimals 9 # consume trailing numbers while current_char.ascii_number? @@ -278,7 +278,7 @@ struct Time::Format end end - private def second_decimals(precision) + private def second_decimals(precision : Int32) : Int32 pos = @reader.pos # Consume at most *precision* digits as i64 decimals = consume_number_i64(precision) @@ -290,14 +290,14 @@ struct Time::Format @nanosecond = (decimals * 10 ** (precision_shift + nanoseconds_shift)).to_i end - def second_fraction?(fraction_digits = nil) + def second_fraction?(fraction_digits : Int32? = nil) : Int32? if current_char == '.' next_char nanoseconds end end - def am_pm + def am_pm : Bool string = consume_string case string.downcase when "am" @@ -309,19 +309,19 @@ struct Time::Format end end - def am_pm_upcase + def am_pm_upcase : Bool am_pm end - def day_of_week_monday_1_7 + def day_of_week_monday_1_7 : Time::DayOfWeek @day_of_week = Time::DayOfWeek.from_value(consume_number(1)) end - def day_of_week_sunday_0_6 + def day_of_week_sunday_0_6 : Time::DayOfWeek @day_of_week = Time::DayOfWeek.from_value(consume_number(1)) end - def unix_seconds + def unix_seconds : Int64 negative = false case current_char when '-' @@ -336,7 +336,7 @@ struct Time::Format @unix_seconds = consume_number_i64(19) * (negative ? -1 : 1) end - def time_zone(with_seconds = false) + def time_zone(with_seconds : Bool = false) : Char | Time::Location case current_char when 'Z' time_zone_z @@ -354,7 +354,7 @@ struct Time::Format end end - def time_zone_z_or_offset(**options) + def time_zone_z_or_offset(**options) : Char | Time::Location case current_char when 'Z', 'z' time_zone_z @@ -365,14 +365,14 @@ struct Time::Format end end - def time_zone_z + def time_zone_z : Char raise "Invalid timezone" unless current_char.in?('Z', 'z') @location = Location::UTC next_char end - def time_zone_offset(force_colon = false, allow_colon = true, format_seconds = false, parse_seconds = true, force_zero_padding = true, force_minutes = true) + def time_zone_offset(force_colon : Bool = false, allow_colon : Bool = true, format_seconds : Bool = false, parse_seconds : Bool = true, force_zero_padding : Bool = true, force_minutes : Bool = true) : Time::Location case current_char when '-' sign = -1 @@ -445,11 +445,11 @@ struct Time::Format @location = Location.fixed(sign * (3600 * hours + 60 * minutes + seconds)) end - def time_zone_colon + def time_zone_colon : Char | Time::Location time_zone end - def time_zone_colon_with_seconds + def time_zone_colon_with_seconds : Char | Time::Location time_zone(with_seconds: true) end @@ -458,7 +458,7 @@ struct Time::Format @location = Location::UTC end - def time_zone_rfc2822 + def time_zone_rfc2822 : Time::Location case current_char when '-', '+' time_zone_offset(allow_colon: false) @@ -469,11 +469,11 @@ struct Time::Format end end - def time_zone_gmt_or_rfc2822(**options) + def time_zone_gmt_or_rfc2822(**options) : Time::Location time_zone_rfc2822 end - def time_zone_name(zone = false) + def time_zone_name(zone : Bool = false) : Time::Location case current_char when '-', '+' time_zone_offset @@ -492,7 +492,7 @@ struct Time::Format end end - def char?(char, *alternatives) + def char?(char : Char, *alternatives) : Bool if current_char == char || alternatives.includes?(current_char) next_char true @@ -501,7 +501,7 @@ struct Time::Format end end - def char(char, *alternatives) + def char(char : Char, *alternatives) : Nil unless @reader.has_next? if alternatives.empty? raise "Expected #{char.inspect} but the end of the input was reached" @@ -515,19 +515,19 @@ struct Time::Format end end - def consume_number(max_digits) + def consume_number(max_digits : Int32) : Int32 consume_number_i64(max_digits).to_i end - def consume_number?(max_digits) + def consume_number?(max_digits : Int32) : Int32? consume_number_i64?(max_digits).try(&.to_i) end - def consume_number_i64(max_digits) + def consume_number_i64(max_digits : Int32) : Int64 consume_number_i64?(max_digits) || raise "Invalid number" end - def consume_number_i64?(max_digits) + def consume_number_i64?(max_digits : Int32) : Int64? n = 0_i64 char = current_char @@ -549,7 +549,7 @@ struct Time::Format n end - def consume_number_blank_padded(max_digits) + def consume_number_blank_padded(max_digits : Int32) : Int32 if current_char.ascii_whitespace? max_digits -= 1 next_char @@ -558,7 +558,7 @@ struct Time::Format consume_number(max_digits) end - def consume_string + def consume_string : String start_pos = @reader.pos while current_char.ascii_letter? next_char @@ -566,32 +566,32 @@ struct Time::Format @reader.string.byte_slice(start_pos, @reader.pos - start_pos) end - def skip_space + def skip_space : Char? next_char if current_char.ascii_whitespace? end - def skip_spaces + def skip_spaces : Nil while current_char.ascii_whitespace? next_char end end - def whitespace + def whitespace : Char unless current_char.ascii_whitespace? ::raise "Unexpected char: #{current_char.inspect}" end next_char end - def current_char + def current_char : Char @reader.current_char end - def next_char + def next_char : Char @reader.next_char end - def raise(message, pos = @reader.pos) + def raise(message : String | ArgumentError, pos : Int32 | Bool = @reader.pos) : Nil string = @reader.string if pos.is_a?(Int) string = "#{string.byte_slice(0, pos)}>>#{string.byte_slice(pos, string.bytesize - pos)}" diff --git a/src/time/format/pattern.cr b/src/time/format/pattern.cr index 4e63e22f5e78..aaee06925b9a 100644 --- a/src/time/format/pattern.cr +++ b/src/time/format/pattern.cr @@ -1,7 +1,7 @@ struct Time::Format # :nodoc: module Pattern - def visit(pattern) + def visit(pattern : String) : Nil reader = Char::Reader.new(pattern) while reader.has_next? char = reader.current_char @@ -10,7 +10,7 @@ struct Time::Format end end - private def check_char(reader, char) + private def check_char(reader : Char::Reader, char : Char) : Char::Reader case char when '%' case char = reader.next_char @@ -171,7 +171,7 @@ struct Time::Format reader end - def date_and_time + def date_and_time : Int32? short_day_name char ' ' short_month_name @@ -183,7 +183,7 @@ struct Time::Format year end - def date + def date : Int32? month_zero_padded char '/' day_of_month_zero_padded @@ -191,7 +191,7 @@ struct Time::Format year_modulo_100 end - def year_month_day + def year_month_day : Int32? year char '-' month_zero_padded @@ -199,7 +199,7 @@ struct Time::Format day_of_month_zero_padded end - def twelve_hour_time + def twelve_hour_time : Bool? hour_12_zero_padded char ':' minute @@ -209,13 +209,13 @@ struct Time::Format am_pm_upcase end - def twenty_four_hour_time + def twenty_four_hour_time : Int32? hour_24_zero_padded char ':' minute end - def twenty_four_hour_time_with_seconds + def twenty_four_hour_time_with_seconds : Int32? hour_24_zero_padded char ':' minute diff --git a/src/time/location/loader.cr b/src/time/location/loader.cr index 6a104101405c..a6357106085b 100644 --- a/src/time/location/loader.cr +++ b/src/time/location/loader.cr @@ -212,11 +212,11 @@ class Time::Location end end - private def self.read_int32(io : IO) + private def self.read_int32(io : IO) : Int32 io.read_bytes(Int32, IO::ByteFormat::BigEndian) end - private def self.read_buffer(io : IO, size : Int) + private def self.read_buffer(io : IO, size : Int) : IO::Memory buffer = Bytes.new(size) io.read_fully(buffer) IO::Memory.new(buffer) diff --git a/src/time/span.cr b/src/time/span.cr index 34910a7ed92e..6c23df490c73 100644 --- a/src/time/span.cr +++ b/src/time/span.cr @@ -89,7 +89,7 @@ struct Time::Span # Time::Span.new(nanoseconds: 500_000_000) # => 00:00:00.500000000 # Time::Span.new(nanoseconds: 5_500_000_000) # => 00:00:05.500000000 # ``` - def self.new(*, nanoseconds : Int) + def self.new(*, nanoseconds : Int) : Time::Span new(seconds: 0, nanoseconds: nanoseconds) end @@ -102,14 +102,14 @@ struct Time::Span # Time::Span.new(days: 1, hours: 2, minutes: 3) # => 1.02:03:00 # Time::Span.new(days: 1, hours: 2, minutes: 3, seconds: 4, nanoseconds: 5) # => 1.02:03:04.000000005 # ``` - def self.new(*, days : Int = 0, hours : Int = 0, minutes : Int = 0, seconds : Int = 0, nanoseconds : Int = 0) + def self.new(*, days : Int = 0, hours : Int = 0, minutes : Int = 0, seconds : Int = 0, nanoseconds : Int = 0) : Time::Span new( seconds: compute_seconds(days, hours, minutes, seconds), nanoseconds: nanoseconds, ) end - private def self.compute_seconds(days, hours, minutes, seconds) + private def self.compute_seconds(days : Int32 | Int64, hours : Int32, minutes : Int32, seconds : Int32 | Int64) : Int64 days_to_seconds = SECONDS_PER_DAY.to_i64 * days hours_to_seconds = SECONDS_PER_HOUR.to_i64 * hours minutes_to_seconds = SECONDS_PER_MINUTE.to_i64 * minutes @@ -322,7 +322,7 @@ struct Time::Span total_nanoseconds.to_f64 / other.total_nanoseconds.to_f64 end - def <=>(other : self) + def <=>(other : self) : Int32 cmp = to_i <=> other.to_i cmp = nanoseconds <=> other.nanoseconds if cmp == 0 cmp diff --git a/src/unicode/data.cr b/src/unicode/data.cr index ccb7d702e892..e5082c0289eb 100644 --- a/src/unicode/data.cr +++ b/src/unicode/data.cr @@ -14993,7 +14993,7 @@ module Unicode hash[key] = value end - private def self.put(hash : Hash, key, *values) : Nil + private def self.put(hash : Hash, key : Int32, *values) : Nil hash[key] = values end end diff --git a/src/unicode/unicode.cr b/src/unicode/unicode.cr index ab49ea31368b..e3402865c395 100644 --- a/src/unicode/unicode.cr +++ b/src/unicode/unicode.cr @@ -141,7 +141,7 @@ module Unicode x end - private def self.put1(array : Array, value) : Nil + private def self.put1(array : Array, value : UInt64) : Nil array << value end @@ -196,7 +196,7 @@ module Unicode yield check_upcase_ranges(char) end - private def self.check_upcase_ascii(char, options) + private def self.check_upcase_ascii(char : Char, options : Unicode::CaseOptions) : Char? if (char.ascii? && options.none?) || options.ascii? if char.ascii_lowercase? return (char.ord - 32).unsafe_chr @@ -207,7 +207,7 @@ module Unicode nil end - private def self.check_upcase_turkic(char, options) + private def self.check_upcase_turkic(char : Char, options : Unicode::CaseOptions) : Char? if options.turkic? case char when 'ı' then 'I' @@ -219,7 +219,7 @@ module Unicode end end - private def self.check_upcase_ranges(char) + private def self.check_upcase_ranges(char : Char) : Char result = search_ranges(upcase_ranges, char.ord) return char + result if result @@ -263,7 +263,7 @@ module Unicode yield check_downcase_ranges(char) end - private def self.check_downcase_ascii(char, options) + private def self.check_downcase_ascii(char : Char, options : Unicode::CaseOptions) : Char? if (char.ascii? && options.none?) || options.ascii? if char.ascii_uppercase? return (char.ord + 32).unsafe_chr @@ -275,7 +275,7 @@ module Unicode nil end - private def self.check_downcase_turkic(char, options) + private def self.check_downcase_turkic(char : Char, options : Unicode::CaseOptions) : Char? if options.turkic? case char when 'I' then 'ı' @@ -287,7 +287,7 @@ module Unicode end end - private def self.check_downcase_ranges(char) + private def self.check_downcase_ranges(char : Char) : Char result = search_ranges(downcase_ranges, char.ord) return char + result if result @@ -362,7 +362,7 @@ module Unicode yield char end - private def self.check_foldcase(char, options) + private def self.check_foldcase(char : Char, options : Unicode::CaseOptions) : Tuple(Int32) | Tuple(Int32, Int32, Int32) | Nil if options.fold? result = search_ranges(casefold_ranges, char.ord) return {char.ord + result} if result @@ -638,19 +638,19 @@ module Unicode end end - private def self.search_ranges(haystack, needle) + private def self.search_ranges(haystack : Array(Tuple(Int32, Int32, Int32)), needle : Int32) : Int32? search_ranges(haystack, needle) { |value| value[2] } end - private def self.search_alternate(haystack, needle) + private def self.search_alternate(haystack : Array(Tuple(Int32, Int32)), needle : Int32) : Int32? search_ranges(haystack, needle) { |value| value[0] } end - private def self.in_category?(needle, haystack) + private def self.in_category?(needle : Int32, haystack : Array(Tuple(Int32, Int32, Int32))) : Bool !!search_ranges(haystack, needle) { |value| (needle - value[0]).divisible_by?(value[2]) } end - private def self.in_any_category?(needle, *haystacks) : Bool + private def self.in_any_category?(needle : Int32, *haystacks) : Bool haystacks.any? { |haystack| in_category?(needle, haystack) } end end diff --git a/src/uri/encoding.cr b/src/uri/encoding.cr index a7c5be7f1fb9..ea18bb43277d 100644 --- a/src/uri/encoding.cr +++ b/src/uri/encoding.cr @@ -220,19 +220,19 @@ class URI # # Reserved characters are ':', '/', '?', '#', '[', ']', '@', '!', # '$', '&', "'", '(', ')', '*', '+', ',', ';' and '='. - def self.reserved?(byte) : Bool + def self.reserved?(byte : UInt8) : Bool sub_delim?(byte) || gen_delim?(byte) end # :nodoc: # Returns `true` if the byte is URI gen-delims (https://datatracker.ietf.org/doc/html/rfc3986#section-2.2). - def self.gen_delim?(byte) + def self.gen_delim?(byte : UInt8) : Bool byte.unsafe_chr.in?('#', '/', ':', '?', '@', '[', ']') end # :nodoc: # Returns `true` if the byte is URI sub-delims (https://datatracker.ietf.org/doc/html/rfc3986#section-2.2). - def self.sub_delim?(byte) : Bool + def self.sub_delim?(byte : UInt8) : Bool char = byte.unsafe_chr '&' <= char <= ',' || char.in?('!', '$', ';', '=') @@ -242,7 +242,7 @@ class URI # [RFC 3986 §2.3](https://datatracker.ietf.org/doc/html/rfc3986#section-2.3). # # Unreserved characters are ASCII letters, ASCII digits, `_`, `.`, `-` and `~`. - def self.unreserved?(byte) : Bool + def self.unreserved?(byte : UInt8) : Bool char = byte.unsafe_chr char.ascii_alphanumeric? || char.in?('_', '.', '-', '~') @@ -324,7 +324,7 @@ class URI end # :nodoc: - def self.decode_one(string, bytesize, i, byte, char, io, plus_to_space = false) + def self.decode_one(string : String, bytesize : Int32, i : Int32, byte : UInt8, char : Char, io : IO::Memory, plus_to_space : Bool = false) : Int32 self.decode_one(string, bytesize, i, byte, char, io, plus_to_space) { false } end diff --git a/src/uri/json.cr b/src/uri/json.cr index 00b58f419be5..73f58ebc4e30 100644 --- a/src/uri/json.cr +++ b/src/uri/json.cr @@ -11,7 +11,7 @@ class URI # uri.scheme # => "http" # uri.host # => "crystal-lang.org" # ``` - def self.new(parser : JSON::PullParser) + def self.new(parser : JSON::PullParser) : URI parse parser.read_string end @@ -22,7 +22,7 @@ class URI # # URI.parse("http://example.com").to_json # => %("http://example.com") # ``` - def to_json(builder : JSON::Builder) + def to_json(builder : JSON::Builder) : Nil builder.string self end diff --git a/src/uri/params.cr b/src/uri/params.cr index 4670c2725681..2ef7f08e3e1f 100644 --- a/src/uri/params.cr +++ b/src/uri/params.cr @@ -240,7 +240,7 @@ class URI # params["email"] # => "john@example.org" # params["non_existent_param"] # KeyError # ``` - def [](name) : String + def [](name : String) : String fetch(name) { raise KeyError.new "Missing param name: #{name.inspect}" } end @@ -250,7 +250,7 @@ class URI # params["email"]? # => "john@example.org" # params["non_existent_param"]? # nil # ``` - def []?(name) : String? + def []?(name : String) : String? fetch(name, nil) end @@ -284,7 +284,7 @@ class URI # params["a"] # => "e" # params.fetch_all("a") # => ["e", "f"] # ``` - def []=(name, value : String | Array(String)) + def []=(name : String, value : String | Array(String)) : Array(String) raw_params[name] = case value in String then [value] @@ -298,7 +298,7 @@ class URI # params.set_all("item", ["pencil", "book", "workbook"]) # params.fetch_all("item") # => ["pencil", "book", "workbook"] # ``` - def fetch_all(name) : Array(String) + def fetch_all(name : String) : Array(String) raw_params.fetch(name) { [] of String } end @@ -310,7 +310,7 @@ class URI # params.fetch("email", "none@example.org") # => "john@example.org" # params.fetch("non_existent_param", "default value") # => "default value" # ``` - def fetch(name, default) + def fetch(name : String, default : String?) : String? fetch(name) { default } end @@ -334,7 +334,7 @@ class URI # params.add("item", "keychain") # params.fetch_all("item") # => ["pencil", "book", "workbook", "keychain"] # ``` - def add(name, value) + def add(name : String, value : String) : Array(String) params = raw_params.put_if_absent(name) { [] of String } params.clear if params.size == 1 && params[0] == "" params << value @@ -346,7 +346,7 @@ class URI # params.set_all("item", ["keychain", "keynote"]) # params.fetch_all("item") # => ["keychain", "keynote"] # ``` - def set_all(name, values) + def set_all(name : String, values : Array(String)) : Array(String) raw_params[name] = values end @@ -382,7 +382,7 @@ class URI # # params.delete("non_existent_param") # KeyError # ``` - def delete(name) : String + def delete(name : String) : String value = raw_params[name].shift raw_params.delete(name) if raw_params[name].size == 0 value @@ -396,7 +396,7 @@ class URI # params.delete_all("comments") # => ["hello, world!", ":+1:"] # params.has_key?("comments") # => false # ``` - def delete_all(name) : Array(String)? + def delete_all(name : String) : Array(String)? raw_params.delete(name) end @@ -456,7 +456,7 @@ class URI # params = URI::Params.parse("item=keychain&greeting=hello+world&email=john@example.org") # params.to_s(space_to_plus: false) # => "item=keychain&greeting=hello%20world&email=john%40example.org" # ``` - def to_s(*, space_to_plus : Bool = true) + def to_s(*, space_to_plus : Bool = true) : String String.build do |io| to_s(io, space_to_plus: space_to_plus) end @@ -476,7 +476,7 @@ class URI end # :nodoc: - def self.decode_one_www_form_component(query, bytesize, i, byte, char, buffer) + def self.decode_one_www_form_component(query : String, bytesize : Int32, i : Int32, byte : UInt8, char : Char, buffer : IO::Memory) : Int32 URI.decode_one query, bytesize, i, byte, char, buffer, true end @@ -494,7 +494,7 @@ class URI end # Adds a key-value pair to the params being built. - def add(key, value : String?) + def add(key : String, value : String?) : URI::Params::Builder @io << '&' unless @first @first = false URI.encode_www_form key, @io, space_to_plus: @space_to_plus @@ -504,7 +504,7 @@ class URI end # Adds all of the given *values* as key-value pairs to the params being built. - def add(key, values : Array) + def add(key : String, values : Array) : URI::Params::Builder values.each { |value| add(key, value) } self end diff --git a/src/uri/params/from_www_form.cr b/src/uri/params/from_www_form.cr index 819c9fc9d82e..e4f176243794 100644 --- a/src/uri/params/from_www_form.cr +++ b/src/uri/params/from_www_form.cr @@ -1,5 +1,5 @@ # :nodoc: -def Object.from_www_form(params : URI::Params, name : String) +def Object.from_www_form(params : URI::Params, name : String) : Nil | Bool | UInt8 | Int32 | Float64 | String return unless value = params[name]? self.from_www_form value @@ -19,7 +19,7 @@ def Array.from_www_form(params : URI::Params, name : String) end # :nodoc: -def Bool.from_www_form(value : String) +def Bool.from_www_form(value : String) : Bool? case value when "true", "1", "yes", "on" then true when "false", "0", "no", "off" then false @@ -27,12 +27,12 @@ def Bool.from_www_form(value : String) end # :nodoc: -def Number.from_www_form(value : String) +def Number.from_www_form(value : String) : UInt8 | Int16 | Int32 | Int64 | Float32 | Float64 new value, whitespace: false end # :nodoc: -def String.from_www_form(value : String) +def String.from_www_form(value : String) : String value end @@ -42,7 +42,7 @@ def Enum.from_www_form(value : String) end # :nodoc: -def Time.from_www_form(value : String) +def Time.from_www_form(value : String) : Time Time::Format::ISO_8601_DATE_TIME.parse value end diff --git a/src/uri/params/serializable.cr b/src/uri/params/serializable.cr index 54d3b970e53c..11dacf5d8d68 100644 --- a/src/uri/params/serializable.cr +++ b/src/uri/params/serializable.cr @@ -117,7 +117,7 @@ struct URI::Params end # :nodoc: - def to_www_form(builder : URI::Params::Builder, name : String) + def to_www_form(builder : URI::Params::Builder, name : String) : Nil {% for ivar in @type.instance_vars %} @{{ivar.name.id}}.to_www_form builder, "#{name}[#{{{ivar.name.stringify}}}]" {% end %} diff --git a/src/uri/punycode.cr b/src/uri/punycode.cr index b31574d2fbe2..397dbfeb7ee2 100644 --- a/src/uri/punycode.cr +++ b/src/uri/punycode.cr @@ -15,7 +15,7 @@ class URI private BASE36 = "abcdefghijklmnopqrstuvwxyz0123456789" - private def self.adapt(delta, numpoints, firsttime) + private def self.adapt(delta : UInt32 | Int32, numpoints : Int32, firsttime : Bool) : Int32 delta //= firsttime ? DAMP : 2 delta += delta // numpoints k = 0 @@ -26,11 +26,11 @@ class URI k + (((BASE - TMIN + 1) * delta) // (delta + SKEW)) end - def self.encode(string) : String + def self.encode(string : String) : String String.build { |io| encode string, io } end - def self.encode(string, io) : Nil + def self.encode(string : String, io : String::Builder) : Nil others = [] of Char string.each_char do |c| @@ -87,7 +87,7 @@ class URI end end - def self.decode(string) : String + def self.decode(string : String) : String output, _, rest = string.rpartition(DELIMITER) output = output.chars @@ -138,7 +138,7 @@ class URI output.join end - def self.to_ascii(string) : String + def self.to_ascii(string : String) : String return string if string.ascii_only? String.build do |io| diff --git a/src/uri/uri_parser.cr b/src/uri/uri_parser.cr index 3c70aebff668..47be96c83f39 100644 --- a/src/uri/uri_parser.cr +++ b/src/uri/uri_parser.cr @@ -12,7 +12,7 @@ class URI @input : UInt8* - def initialize(input) + def initialize(input : String) @uri = URI.new @input = input.strip.to_unsafe @ptr = 0 @@ -32,7 +32,7 @@ class URI self end - private def parse_scheme_start + private def parse_scheme_start : Nil if alpha? parse_scheme elsif c === '/' && @input[@ptr + 1] === '/' @@ -44,7 +44,7 @@ class URI end end - private def parse_scheme + private def parse_scheme : Nil start = @ptr loop do if alpha? || numeric? || c === '-' || c === '.' || c === '+' @@ -65,7 +65,7 @@ class URI end end - private def parse_path_or_authority + private def parse_path_or_authority : Nil if c === '/' @uri.host = "" parse_authority @@ -75,7 +75,7 @@ class URI end end - private def parse_no_scheme + private def parse_no_scheme : Nil case c when '#' parse_fragment @@ -84,7 +84,7 @@ class URI end end - private def parse_authority + private def parse_authority : Nil @ptr += 1 start = @ptr loop do @@ -100,7 +100,7 @@ class URI end end - private def parse_userinfo + private def parse_userinfo : Nil start = @ptr password_flag = false loop do @@ -123,7 +123,7 @@ class URI end end - private def parse_host + private def parse_host : Nil start = @ptr bracket_flag = false return parse_path if c === '/' @@ -143,7 +143,7 @@ class URI end end - private def parse_port + private def parse_port : Nil start = @ptr loop do if numeric? @@ -161,7 +161,7 @@ class URI end end - private def parse_relative + private def parse_relative : Nil case c when '\0' nil @@ -174,7 +174,7 @@ class URI end end - private def parse_path + private def parse_path : Nil start = @ptr loop do case c @@ -193,7 +193,7 @@ class URI end end - private def parse_query + private def parse_query : Nil @ptr += 1 start = @ptr loop do @@ -210,7 +210,7 @@ class URI end end - private def parse_fragment + private def parse_fragment : Nil @ptr += 1 start = @ptr loop do @@ -224,20 +224,20 @@ class URI end end - private def from_input(start) + private def from_input(start : Int32) : String String.new(@input + start, @ptr - start) end - private def alpha? + private def alpha? : Bool ('a'.ord <= c && c <= 'z'.ord) || ('A'.ord <= c && c <= 'Z'.ord) end - private def numeric? + private def numeric? : Bool '0'.ord <= c && c <= '9'.ord end - private def end_of_host? + private def end_of_host? : Bool c === '\0' || c === '/' || c === '?' || c === '#' end end diff --git a/src/uri/yaml.cr b/src/uri/yaml.cr index c6b53ed0221c..1e76fb52c1b3 100644 --- a/src/uri/yaml.cr +++ b/src/uri/yaml.cr @@ -11,7 +11,7 @@ class URI # uri.scheme # => "http" # uri.host # => "crystal-lang.org" # ``` - def self.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) + def self.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) : URI parse String.new(ctx, node) end @@ -22,7 +22,7 @@ class URI # # URI.parse("http://example.com").to_yaml # => "--- http://example.com\n" # ``` - def to_yaml(yaml : YAML::Nodes::Builder) + def to_yaml(yaml : YAML::Nodes::Builder) : Nil yaml.scalar to_s end end diff --git a/src/uuid.cr b/src/uuid.cr index b1a043785472..1906ae4cdf55 100644 --- a/src/uuid.cr +++ b/src/uuid.cr @@ -102,7 +102,7 @@ struct UUID # Creates UUID from 16-bytes slice. Raises if *slice* isn't 16 bytes long. See # `#initialize` for *variant* and *version*. - def self.new(slice : Slice(UInt8), variant : Variant? = nil, version : Version? = nil) + def self.new(slice : Slice(UInt8), variant : Variant? = nil, version : Version? = nil) : UUID raise ArgumentError.new "Invalid bytes length #{slice.size}, expected 16" unless slice.size == 16 bytes = uninitialized UInt8[16] @@ -113,14 +113,14 @@ struct UUID # Creates another `UUID` which is a copy of *uuid*, but allows overriding # *variant* or *version*. - def self.new(uuid : UUID, variant : Variant? = nil, version : Version? = nil) + def self.new(uuid : UUID, variant : Variant? = nil, version : Version? = nil) : UUID new(uuid.bytes, variant, version) end # Creates new UUID by decoding `value` string from hyphenated (ie `ba714f86-cac6-42c7-8956-bcf5105e1b81`), # hexstring (ie `89370a4ab66440c8add39e06f2bb6af6`) or URN (ie `urn:uuid:3f9eaf9e-cdb0-45cc-8ecb-0e5b2bfb0c20`) # format, raising an `ArgumentError` if the string does not match any of these formats. - def self.new(value : String, variant : Variant? = nil, version : Version? = nil) + def self.new(value : String, variant : Variant? = nil, version : Version? = nil) : UUID bytes = uninitialized UInt8[16] case value.size @@ -193,13 +193,13 @@ struct UUID # Raises `ArgumentError` if string `value` at index `i` doesn't contain hex # digit followed by another hex digit. - private def self.hex_pair_at(value : String, i) : UInt8 + private def self.hex_pair_at(value : String, i : Int32) : UInt8 hex_pair_at?(value, i) || raise ArgumentError.new "Invalid hex character at position #{i * 2} or #{i * 2 + 1}, expected '0' to '9', 'a' to 'f' or 'A' to 'F'" end # Parses 2 hex digits from `value` at index `i` and `i + 1`, returning `nil` # if one or both are not actually hex digits. - private def self.hex_pair_at?(value : String, i) : UInt8? + private def self.hex_pair_at?(value : String, i : Int32) : UInt8? if (ch1 = value[i].to_u8?(16)) && (ch2 = value[i + 1].to_u8?(16)) ch1 * 16 + ch2 end @@ -328,7 +328,7 @@ struct UUID # Generates an RFC9562-compatible v7 UUID, allowing the values to be sorted # chronologically (with 1ms precision) by their raw or hexstring # representation. - def self.v7(random r : Random = Random::Secure) + def self.v7(random r : Random = Random::Secure) : UUID buffer = uninitialized UInt8[18] value = buffer.to_slice diff --git a/src/uuid/json.cr b/src/uuid/json.cr index 966ee0cabfc9..c131c2ad1cf9 100644 --- a/src/uuid/json.cr +++ b/src/uuid/json.cr @@ -20,7 +20,7 @@ struct UUID # example = Example.from_json(%({"id": "ba714f86-cac6-42c7-8956-bcf5105e1b81"})) # example.id # => UUID(ba714f86-cac6-42c7-8956-bcf5105e1b81) # ``` - def self.new(pull : JSON::PullParser) + def self.new(pull : JSON::PullParser) : UUID new(pull.read_string) end @@ -44,7 +44,7 @@ struct UUID # Deserializes the given JSON *key* into a `UUID`. # # NOTE: `require "uuid/json"` is required to opt-in to this feature. - def self.from_json_object_key?(key : String) + def self.from_json_object_key?(key : String) : UUID UUID.new(key) end end diff --git a/src/uuid/yaml.cr b/src/uuid/yaml.cr index 2c7eec1f5a45..f2fac6329a39 100644 --- a/src/uuid/yaml.cr +++ b/src/uuid/yaml.cr @@ -20,7 +20,7 @@ struct UUID # example = Example.from_yaml("id: 50a11da6-377b-4bdf-b9f0-076f9db61c93") # example.id # => UUID(50a11da6-377b-4bdf-b9f0-076f9db61c93) # ``` - def self.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) + def self.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) : UUID ctx.read_alias(node, String) do |obj| return UUID.new(obj) end @@ -42,7 +42,7 @@ struct UUID # uuid = UUID.new("50a11da6-377b-4bdf-b9f0-076f9db61c93") # uuid.to_yaml # => "--- 50a11da6-377b-4bdf-b9f0-076f9db61c93\n" # ``` - def to_yaml(yaml : YAML::Nodes::Builder) + def to_yaml(yaml : YAML::Nodes::Builder) : Nil yaml.scalar self.to_s end end diff --git a/src/wait_group.cr b/src/wait_group.cr index 003921bd9f46..da1713449cd1 100644 --- a/src/wait_group.cr +++ b/src/wait_group.cr @@ -135,7 +135,7 @@ class WaitGroup raise RuntimeError.new("Positive WaitGroup counter (early wake up?)") end - private def done? + private def done? : Bool counter = @counter.get(:acquire) raise RuntimeError.new("Negative WaitGroup counter") if counter < 0 counter == 0 diff --git a/src/winerror.cr b/src/winerror.cr index ae4eceb1f18e..8cf490950627 100644 --- a/src/winerror.cr +++ b/src/winerror.cr @@ -23,7 +23,7 @@ enum WinError : UInt32 # which signifies the error code of the previously called win32 function. # # Raises `NotImplementedError` on non-win32 platforms. - def self.value=(winerror : self) + def self.value=(winerror : self) : Nil {% if flag?(:win32) %} LibC.SetLastError(winerror.value) {% else %} @@ -35,7 +35,7 @@ enum WinError : UInt32 # which is used to retrieve the error code of the previously called Windows Socket API function. # # Raises `NotImplementedError` on non-win32 platforms. - def self.wsa_value + def self.wsa_value : Nil {% if flag?(:win32) %} WinError.new LibC.WSAGetLastError.to_u32! {% else %} @@ -47,7 +47,7 @@ enum WinError : UInt32 # which signifies the error code of the previously called Windows Socket API function. # # Raises `NotImplementedError` on non-win32 platforms. - def self.wsa_value=(winerror : self) + def self.wsa_value=(winerror : self) : Nil {% if flag?(:win32) %} LibC.WSASetLastError(winerror.value) {% else %} diff --git a/src/xml/attributes.cr b/src/xml/attributes.cr index 1df5aea55483..257ae9276e93 100644 --- a/src/xml/attributes.cr +++ b/src/xml/attributes.cr @@ -38,7 +38,7 @@ class XML::Attributes find { |node| node.name == name } end - def []=(name : String, value) + def []=(name : String, value : String | Int32) : String | Int32 LibXML.xmlSetProp(@node, name, value.to_s) value end @@ -69,7 +69,7 @@ class XML::Attributes to_s(io) end - protected def props + protected def props : Pointer(LibXML::Attr) @node.to_unsafe.value.properties end end diff --git a/src/xml/builder.cr b/src/xml/builder.cr index 54e5f45adddc..089a9ee4f555 100644 --- a/src/xml/builder.cr +++ b/src/xml/builder.cr @@ -29,7 +29,7 @@ class XML::Builder end # Emits the start of the document. - def start_document(version = nil, encoding = nil) : Nil + def start_document(version : Nil = nil, encoding : Nil = nil) : Nil call StartDocument, string_to_unsafe(version), string_to_unsafe(encoding), nil end @@ -84,7 +84,7 @@ class XML::Builder end # Emits an element with the given *attributes*. - def element(__name__ : String, **attributes) + def element(__name__ : String, **attributes) : Nil element(__name__, attributes) end @@ -143,12 +143,12 @@ class XML::Builder end # Emits an attribute with a *value*. - def attribute(name : String, value) : Nil + def attribute(name : String, value : Int32 | String) : Nil call WriteAttribute, string_to_unsafe(name), string_to_unsafe(value.to_s) end # Emits an attribute with namespace info and a *value*. - def attribute(prefix : String?, name : String, namespace_uri : String?, value) : Nil + def attribute(prefix : String?, name : String, namespace_uri : String?, value : Int32 | String) : Nil call WriteAttributeNS, string_to_unsafe(prefix), string_to_unsafe(name), string_to_unsafe(namespace_uri), string_to_unsafe(value.to_s) end @@ -241,7 +241,7 @@ class XML::Builder end # Emits a namespace. - def namespace(prefix, uri) : Nil + def namespace(prefix : String, uri : String) : Nil attribute "xmlns", prefix, nil, uri end @@ -254,7 +254,7 @@ class XML::Builder end # Sets the indent string. - def indent=(str : String) + def indent=(str : String) : Nil if str.empty? call SetIndent, 0 else @@ -264,7 +264,7 @@ class XML::Builder end # Sets the indent *level* (number of spaces). - def indent=(level : Int) + def indent=(level : Int) : Nil if level <= 0 call SetIndent, 0 else @@ -274,7 +274,7 @@ class XML::Builder end # Sets the quote char to use, either `'` or `"`. - def quote_char=(char : Char) + def quote_char=(char : Char) : Nil unless char.in?('\'', '"') raise ArgumentError.new("Quote char must be ' or \", not #{char}") end @@ -287,7 +287,7 @@ class XML::Builder check ret, {{@def.name.stringify}} end - private def check(ret, msg) + private def check(ret : Int32, msg : String) : Nil raise XML::Error.new("Error in #{msg}", 0) if ret < 0 end @@ -295,12 +295,12 @@ class XML::Builder raise XML::Error.new("Invalid #{element_type}: '#{name}'", 0) if LibXML.xmlValidateNameValue(unsafe_name).zero? end - private def string_to_unsafe(string : String) + private def string_to_unsafe(string : String) : Pointer(UInt8) raise XML::Error.new("String cannot contain null character", 0) if string.includes? '\0' string.to_unsafe end - private def string_to_unsafe(string : Nil) + private def string_to_unsafe(string : Nil) : Pointer(UInt8) Pointer(UInt8).null end end diff --git a/src/xml/error.cr b/src/xml/error.cr index 389aa53910c2..44530a4d77c2 100644 --- a/src/xml/error.cr +++ b/src/xml/error.cr @@ -3,11 +3,11 @@ require "./libxml2" class XML::Error < Exception getter line_number : Int32 - def self.new(error : LibXML::Error*) + def self.new(error : LibXML::Error*) : XML::Error new String.new(error.value.message).chomp, error.value.line end - def initialize(message, @line_number) + def initialize(message : String, @line_number : Int32) super(message) end diff --git a/src/xml/node.cr b/src/xml/node.cr index 45878e762b0f..296dc10abba5 100644 --- a/src/xml/node.cr +++ b/src/xml/node.cr @@ -29,7 +29,7 @@ class XML::Node # Sets *attribute* of this node to *value*. # Raises `XML::Error` if this node does not support attributes. - def []=(name : String, value) + def []=(name : String, value : String | Int32) : String | Int32 raise XML::Error.new("Can't set attribute of #{type}", 0) unless element? attributes[name] = value end @@ -41,7 +41,7 @@ class XML::Node end # Compares with *other*. - def ==(other : Node) + def ==(other : Node) : Bool @node == other.@node end @@ -91,7 +91,7 @@ class XML::Node # Sets the Node's content to a Text node containing string. # The string gets XML escaped, not interpreted as markup. - def content=(content) + def content=(content : String) : Nil check_no_null_byte(content) LibXML.xmlNodeSetContent(self, content) end @@ -265,7 +265,7 @@ class XML::Node end # Sets the name for this Node. - def name=(name) + def name=(name : String) : Nil if document? || text? || cdata? || fragment? raise XML::Error.new("Can't set name of XML #{type}", 0) end @@ -406,7 +406,7 @@ class XML::Node end # Same as `#content=`. - def text=(text) + def text=(text : String) : Nil self.content = text end @@ -425,7 +425,7 @@ class XML::Node # Serialize this Node as XML and return a `String` using default options. # # See `XML::SaveOptions.xml_default` for default options. - def to_xml(indent : Int = 2, indent_text = " ", options : SaveOptions = SaveOptions.xml_default) : String + def to_xml(indent : Int = 2, indent_text : String = " ", options : SaveOptions = SaveOptions.xml_default) : String String.build do |str| to_xml str, indent, indent_text, options end @@ -437,7 +437,7 @@ class XML::Node # Serialize this Node as XML to *io* using default options. # # See `XML::SaveOptions.xml_default` for default options. - def to_xml(io : IO, indent = 2, indent_text = " ", options : SaveOptions = SaveOptions.xml_default) + def to_xml(io : IO, indent : Int32 = 2, indent_text : String = " ", options : SaveOptions = SaveOptions.xml_default) : String::Builder | IO::Memory # We need to use a mutex because we modify global libxml variables SAVE_MUTEX.synchronize do XML.with_indent_tree_output(true) do @@ -464,7 +464,7 @@ class XML::Node end # Returns underlying `LibXML::Node*` instance. - def to_unsafe + def to_unsafe : Pointer(LibXML::Node) @node end @@ -487,7 +487,7 @@ class XML::Node # (`Bool | Float64 | String | XML::NodeSet`). # # Raises `XML::Error` on evaluation error. - def xpath(path, namespaces = nil, variables = nil) + def xpath(path : String, namespaces : Nil | Hash(String, String) | Hash(String, String | Nil) = nil, variables : Hash(String, Int32)? = nil) : Bool | Float64 | String | XML::NodeSet ctx = XPathContext.new(self) if namespaces @@ -511,7 +511,7 @@ class XML::Node # # doc.xpath_bool("count(//person) > 0") # => true # ``` - def xpath_bool(path, namespaces = nil, variables = nil) + def xpath_bool(path : String, namespaces : Nil = nil, variables : Hash(String, Int32)? = nil) : Bool xpath(path, namespaces, variables).as(Bool) end @@ -524,7 +524,7 @@ class XML::Node # # doc.xpath_float("count(//person)") # => 1.0 # ``` - def xpath_float(path, namespaces = nil, variables = nil) + def xpath_float(path : String, namespaces : Nil = nil, variables : Hash(String, Int32)? = nil) : Float64 xpath(path, namespaces, variables).as(Float64) end @@ -539,7 +539,7 @@ class XML::Node # nodes.class # => XML::NodeSet # nodes.map(&.name) # => ["person"] # ``` - def xpath_nodes(path, namespaces = nil, variables = nil) + def xpath_nodes(path : String, namespaces : Nil = nil, variables : Hash(String, Int32)? = nil) : XML::NodeSet xpath(path, namespaces, variables).as(NodeSet) end @@ -554,7 +554,7 @@ class XML::Node # doc.xpath_node("//person") # => # # doc.xpath_node("//invalid") # => nil # ``` - def xpath_node(path, namespaces = nil, variables = nil) + def xpath_node(path : String, namespaces : Nil = nil, variables : Hash(String, Int32)? = nil) : XML::Node? xpath_nodes(path, namespaces, variables).first? end @@ -567,7 +567,7 @@ class XML::Node # # doc.xpath_string("string(/persons/person[1])") # ``` - def xpath_string(path, namespaces = nil, variables = nil) + def xpath_string(path : String, namespaces : Nil = nil, variables : Hash(String, Int32)? = nil) : String xpath(path, namespaces, variables).as(String) end @@ -577,7 +577,7 @@ class XML::Node return @errors unless @errors.try &.empty? end - private def check_no_null_byte(string) + private def check_no_null_byte(string : String) : Nil if string.includes? Char::ZERO raise XML::Error.new("Cannot escape string containing null character", 0) end diff --git a/src/xml/node_set.cr b/src/xml/node_set.cr index 0263facbfd55..0ee4472c10bb 100644 --- a/src/xml/node_set.cr +++ b/src/xml/node_set.cr @@ -4,7 +4,7 @@ class XML::NodeSet def initialize(@doc : Node, @set : LibXML::NodeSet*) end - def self.new(doc : Node) + def self.new(doc : Node) : XML::NodeSet new doc, LibXML.xmlXPathNodeSetCreate(nil) end @@ -53,7 +53,7 @@ class XML::NodeSet @set end - private def internal_at(index) + private def internal_at(index : Int32) : XML::Node Node.new(@set.value.node_tab[index]) end end diff --git a/src/xml/reader.cr b/src/xml/reader.cr index d4dbe91f7eeb..abf8ce064114 100644 --- a/src/xml/reader.cr +++ b/src/xml/reader.cr @@ -193,7 +193,7 @@ class XML::Reader end # Returns a reference to the underlying `LibXML::XMLTextReader`. - def to_unsafe + def to_unsafe : Pointer(Void) @reader end @@ -201,7 +201,7 @@ class XML::Reader Error.collect(@errors) { yield } end - private def check_no_null_byte(attribute) + private def check_no_null_byte(attribute : String) : Nil if attribute.byte_index(0) raise XML::Error.new("Invalid attribute name: #{attribute.inspect} (contains null character)", 0) end diff --git a/src/xml/xpath_context.cr b/src/xml/xpath_context.cr index 53ede8aeb929..6f3a87ae4bbf 100644 --- a/src/xml/xpath_context.cr +++ b/src/xml/xpath_context.cr @@ -6,7 +6,7 @@ class XML::XPathContext @ctx.value.node = node.to_unsafe end - def evaluate(search_path : String) + def evaluate(search_path : String) : Bool | Float64 | String | XML::NodeSet xpath = XML::Error.collect_generic(@errors) { LibXML.xmlXPathEvalExpression(search_path, self) } raise XML::Error.new("Error in '#{search_path}' expression", 0) unless xpath @@ -29,24 +29,24 @@ class XML::XPathContext end end - def register_namespaces(namespaces) : Nil + def register_namespaces(namespaces : Hash(String, String) | Hash(String, String | Nil)) : Nil namespaces.each do |prefix, uri| register_namespace prefix, uri end end - def register_namespace(prefix : String, uri : String?) + def register_namespace(prefix : String, uri : String?) : Int32 prefix = prefix.lchop("xmlns:") LibXML.xmlXPathRegisterNs(self, prefix, uri.to_s) end - def register_variables(variables) : Nil + def register_variables(variables : Hash(String, Int32)) : Nil variables.each do |name, value| register_variable name, value end end - def register_variable(name, value) + def register_variable(name : String, value : Int32) : Int32 case value when Bool obj = LibXML.xmlXPathNewBoolean(value ? 1 : 0) @@ -59,7 +59,7 @@ class XML::XPathContext LibXML.xmlXPathRegisterVariable(self, name, obj) end - def to_unsafe + def to_unsafe : Pointer(LibXML::XPathContext) @ctx end end diff --git a/src/yaml.cr b/src/yaml.cr index c9ecb746ee69..bf731ec69cc0 100644 --- a/src/yaml.cr +++ b/src/yaml.cr @@ -85,7 +85,7 @@ module YAML getter line_number : Int32 getter column_number : Int32 - def initialize(message, line_number, column_number, context_info = nil) + def initialize(message : String | ArgumentError, line_number : Int32 | UInt64, column_number : Int32 | UInt64, context_info : Tuple(String, UInt64, UInt64)? = nil) @line_number = line_number.to_i @column_number = column_number.to_i if context_info @@ -152,12 +152,12 @@ module YAML end # Serializes an object to YAML, returning it as a `String`. - def self.dump(object) : String + def self.dump(object : Array(String)) : String object.to_yaml end # Serializes an object to YAML, writing it to *io*. - def self.dump(object, io : IO) : Nil + def self.dump(object : Array(String), io : IO) : Nil object.to_yaml(io) end