From 1220d040811955ea51159e6f897d7c71aaff03f7 Mon Sep 17 00:00:00 2001 From: Quinton Miller Date: Sat, 14 Jan 2023 00:17:14 +0800 Subject: [PATCH 1/3] Formatter: add `&` to yielding methods without a block parameter --- spec/compiler/formatter/formatter_spec.cr | 172 ++++++++++++++++++++++ src/compiler/crystal/tools/formatter.cr | 22 ++- 2 files changed, 189 insertions(+), 5 deletions(-) diff --git a/spec/compiler/formatter/formatter_spec.cr b/spec/compiler/formatter/formatter_spec.cr index 4d1549b45a1f..467f25a44a2c 100644 --- a/spec/compiler/formatter/formatter_spec.cr +++ b/spec/compiler/formatter/formatter_spec.cr @@ -548,6 +548,178 @@ describe Crystal::Formatter do assert_format "with foo yield bar" + context "adds `&` to yielding methods that don't have a block parameter (#8764)" do + assert_format <<-CRYSTAL, + def foo + yield + end + CRYSTAL + <<-CRYSTAL + def foo(&) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo() + yield + end + CRYSTAL + <<-CRYSTAL + def foo(&) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo( + ) + yield + end + CRYSTAL + <<-CRYSTAL + def foo(&) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo(x) + yield + end + CRYSTAL + <<-CRYSTAL + def foo(x, &) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo(x ,) + yield + end + CRYSTAL + <<-CRYSTAL + def foo(x, &) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo(x, + y) + yield + end + CRYSTAL + <<-CRYSTAL + def foo(x, + y, &) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo(x, + y,) + yield + end + CRYSTAL + <<-CRYSTAL + def foo(x, + y, &) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo(x + ) + yield + end + CRYSTAL + <<-CRYSTAL + def foo(x, + &) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo(x, + ) + yield + end + CRYSTAL + <<-CRYSTAL + def foo(x, + &) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo( + x) + yield + end + CRYSTAL + <<-CRYSTAL + def foo( + x, & + ) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo( + x, y) + yield + end + CRYSTAL + <<-CRYSTAL + def foo( + x, y, & + ) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo( + x, + y) + yield + end + CRYSTAL + <<-CRYSTAL + def foo( + x, + y, & + ) + yield + end + CRYSTAL + + assert_format <<-CRYSTAL, + def foo( + x, + ) + yield + end + CRYSTAL + <<-CRYSTAL + def foo( + x, + & + ) + yield + end + CRYSTAL + + assert_format "macro f\n yield\n {{ yield }}\nend" + end + assert_format "1 + 2", "1 + 2" assert_format "1 &+ 2", "1 &+ 2" assert_format "1 > 2", "1 > 2" diff --git a/src/compiler/crystal/tools/formatter.cr b/src/compiler/crystal/tools/formatter.cr index 9650696f8f23..5f476d5e1a7a 100644 --- a/src/compiler/crystal/tools/formatter.cr +++ b/src/compiler/crystal/tools/formatter.cr @@ -1504,12 +1504,15 @@ module Crystal end def format_def_args(node : Def | Macro) - format_def_args node.args, node.block_arg, node.splat_index, false, node.double_splat + block_arg = node.block_arg + yields = node.is_a?(Def) && !node.block_arity.nil? + format_def_args node.args, node.block_arg, node.splat_index, false, node.double_splat, yields end - def format_def_args(args : Array, block_arg, splat_index, variadic, double_splat) + def format_def_args(args : Array, block_arg, splat_index, variadic, double_splat, yields) # If there are no args, remove extra "()" if args.empty? && !block_arg && !double_splat && !variadic + write "(&)" if yields if @token.type.op_lparen? next_token_skip_space_or_newline check :OP_RPAREN @@ -1541,7 +1544,7 @@ module Crystal end args.each_with_index do |arg, i| - has_more = !last?(i, args) || double_splat || block_arg || variadic + has_more = !last?(i, args) || double_splat || block_arg || yields || variadic wrote_newline = format_def_arg(wrote_newline, has_more) do if i == splat_index write_token :OP_STAR @@ -1557,7 +1560,7 @@ module Crystal end if double_splat - wrote_newline = format_def_arg(wrote_newline, block_arg) do + wrote_newline = format_def_arg(wrote_newline, block_arg || yields) do write_token :OP_STAR_STAR skip_space_or_newline @@ -1575,6 +1578,11 @@ module Crystal to_skip += 1 if at_skip? block_arg.accept self end + elsif yields + wrote_newline = format_def_arg(wrote_newline, false) do + write "&" + skip_space_or_newline + end end if variadic @@ -1653,6 +1661,10 @@ module Crystal else write " " if has_more && !just_wrote_newline end + elsif @token.type.op_rparen? && has_more && !just_wrote_newline + # if we found a `)` and there are still more parameters to write, it + # must have been a missing `&` for a def that yields + write " " end just_wrote_newline @@ -1689,7 +1701,7 @@ module Crystal end end - format_def_args node.args, nil, nil, node.varargs?, nil + format_def_args node.args, nil, nil, node.varargs?, nil, false if return_type = node.return_type skip_space From 0a4474a38f8e550072bc2ec5f863f2fafbc988b4 Mon Sep 17 00:00:00 2001 From: Quinton Miller Date: Sat, 14 Jan 2023 00:26:23 +0800 Subject: [PATCH 2/3] `make format` --- samples/2048.cr | 6 +-- samples/meteor.cr | 4 +- samples/red_black_tree.cr | 10 ++--- samples/sdl/fire.cr | 2 +- samples/sdl/sdl/sdl.cr | 2 +- spec/compiler/crystal/tools/context_spec.cr | 2 +- spec/compiler/crystal/tools/expand_spec.cr | 6 +-- spec/compiler/crystal/tools/init_spec.cr | 4 +- .../crystal/tools/table_print_spec.cr | 2 +- spec/compiler/crystal/types_spec.cr | 2 +- spec/compiler/semantic/concrete_types_spec.cr | 2 +- spec/compiler/semantic/def_overload_spec.cr | 2 +- spec/spec_helper.cr | 6 +-- spec/std/big/big_float_spec.cr | 2 +- spec/std/deque_spec.cr | 4 +- spec/std/dir_spec.cr | 2 +- spec/std/enumerable_spec.cr | 2 +- spec/std/http/client/client_spec.cr | 4 +- spec/std/http/spec_helper.cr | 6 +-- spec/std/http/web_socket_spec.cr | 2 +- spec/std/io/buffered_spec.cr | 2 +- spec/std/json/builder_spec.cr | 2 +- spec/std/json/pull_parser_spec.cr | 6 +-- spec/std/spec/junit_formatter_spec.cr | 4 +- spec/std/spec/tap_formatter_spec.cr | 2 +- spec/std/spec_helper.cr | 6 +-- spec/std/time/span_spec.cr | 2 +- spec/std/time/spec_helper.cr | 4 +- spec/std/xml/builder_spec.cr | 2 +- spec/std/yaml/builder_spec.cr | 2 +- spec/std/yaml/nodes/builder_spec.cr | 2 +- spec/support/env.cr | 4 +- spec/support/finalize.cr | 2 +- spec/support/retry.cr | 2 +- spec/support/tempfile.cr | 6 +-- src/array.cr | 12 ++--- src/base64.cr | 4 +- src/benchmark.cr | 10 ++--- src/big/big_decimal.cr | 2 +- src/big/big_float.cr | 2 +- src/big/big_int.cr | 2 +- src/big/big_rational.cr | 2 +- src/bit_array.cr | 2 +- src/channel.cr | 4 +- src/char.cr | 8 ++-- src/char/reader.cr | 2 +- src/colorize.cr | 6 +-- src/compiler/crystal/codegen/codegen.cr | 18 ++++---- src/compiler/crystal/codegen/context.cr | 4 +- src/compiler/crystal/codegen/debug.cr | 2 +- src/compiler/crystal/codegen/phi.cr | 2 +- src/compiler/crystal/codegen/primitives.cr | 2 +- src/compiler/crystal/command/cursor.cr | 2 +- src/compiler/crystal/compiler.cr | 4 +- .../crystal/interpreter/class_vars.cr | 2 +- src/compiler/crystal/interpreter/compiler.cr | 12 ++--- .../crystal/interpreter/pry_reader.cr | 6 +-- src/compiler/crystal/macros/interpreter.cr | 4 +- src/compiler/crystal/macros/macros.cr | 2 +- src/compiler/crystal/macros/methods.cr | 14 +++--- src/compiler/crystal/progress_tracker.cr | 2 +- src/compiler/crystal/semantic/bindings.cr | 2 +- src/compiler/crystal/semantic/call.cr | 8 ++-- src/compiler/crystal/semantic/call_error.cr | 6 +-- .../crystal/semantic/cleanup_transformer.cr | 4 +- src/compiler/crystal/semantic/conversions.cr | 2 +- src/compiler/crystal/semantic/cover.cr | 6 +-- src/compiler/crystal/semantic/filters.cr | 2 +- src/compiler/crystal/semantic/main_visitor.cr | 12 ++--- src/compiler/crystal/semantic/match.cr | 2 +- .../semantic/recursive_struct_checker.cr | 2 +- src/compiler/crystal/semantic/restrictions.cr | 2 +- .../crystal/semantic/semantic_visitor.cr | 8 ++-- .../crystal/semantic/top_level_visitor.cr | 2 +- src/compiler/crystal/semantic/type_lookup.cr | 2 +- src/compiler/crystal/semantic/type_merge.cr | 2 +- src/compiler/crystal/syntax/ast.cr | 8 ++-- src/compiler/crystal/syntax/lexer.cr | 6 +-- src/compiler/crystal/syntax/parser.cr | 20 ++++----- src/compiler/crystal/syntax/to_s.cr | 10 ++--- src/compiler/crystal/tools/context.cr | 2 +- src/compiler/crystal/tools/formatter.cr | 20 ++++----- .../crystal/tools/playground/agent.cr | 4 +- .../agent_instrumentor_transformer.cr | 2 +- .../crystal/tools/playground/server.cr | 2 +- src/compiler/crystal/tools/print_hierarchy.cr | 2 +- src/compiler/crystal/tools/table_print.cr | 6 +-- src/compiler/crystal/types.cr | 14 +++--- src/compress/deflate/reader.cr | 4 +- src/compress/deflate/writer.cr | 2 +- src/compress/gzip/reader.cr | 4 +- src/compress/gzip/writer.cr | 4 +- src/compress/zip/file.cr | 6 +-- src/compress/zip/reader.cr | 6 +-- src/compress/zip/writer.cr | 8 ++-- src/compress/zlib/reader.cr | 2 +- src/compress/zlib/writer.cr | 4 +- src/crystal/dwarf/info.cr | 2 +- src/crystal/elf.cr | 4 +- src/crystal/hasher.cr | 2 +- src/crystal/iconv.cr | 2 +- src/crystal/mach_o.cr | 8 ++-- src/crystal/main.cr | 2 +- src/crystal/pointer_linked_list.cr | 4 +- src/crystal/spin_lock.cr | 4 +- src/crystal/system/thread_linked_list.cr | 2 +- src/crystal/system/unix.cr | 2 +- src/crystal/system/unix/pthread.cr | 4 +- src/crystal/system/unix/pthread_mutex.cr | 2 +- src/crystal/system/unix/socket.cr | 8 ++-- src/crystal/system/wasi/thread_mutex.cr | 2 +- src/crystal/system/win32/file_descriptor.cr | 2 +- src/crystal/system/win32/socket.cr | 12 ++--- src/crystal/system/win32/thread.cr | 4 +- src/crystal/system/win32/thread_mutex.cr | 2 +- src/crystal/system/win32/windows_registry.cr | 2 +- src/crystal/system/windows.cr | 2 +- src/crystal/thread_local_value.cr | 2 +- src/csv.cr | 10 ++--- src/csv/builder.cr | 6 +-- src/csv/parser.cr | 2 +- src/deque.cr | 8 ++-- src/dir/glob.cr | 2 +- src/enumerable.cr | 26 +++++------ src/exception/call_stack/dwarf.cr | 2 +- src/exception/call_stack/mach_o.cr | 2 +- src/fiber.cr | 2 +- src/file.cr | 4 +- src/file/tempfile.cr | 4 +- src/file_utils.cr | 2 +- src/hash.cr | 14 +++--- src/http/client.cr | 18 ++++---- src/http/client/response.cr | 2 +- src/http/common.cr | 2 +- src/http/cookie.cr | 2 +- src/http/formdata.cr | 8 ++-- src/http/formdata/parser.cr | 2 +- src/http/headers.cr | 4 +- .../server/handlers/static_file_handler.cr | 2 +- src/http/web_socket.cr | 2 +- src/http/web_socket/protocol.cr | 2 +- src/humanize.cr | 2 +- src/indexable.cr | 22 +++++----- src/int.cr | 2 +- src/io.cr | 6 +-- src/io/evented.cr | 10 ++--- src/io/file_descriptor.cr | 6 +-- src/io/overlapped.cr | 20 ++++----- src/io/stapled.cr | 2 +- src/iterator.cr | 2 +- src/json/builder.cr | 14 +++--- src/json/from_json.cr | 8 ++-- src/json/lexer.cr | 2 +- src/json/parser.cr | 2 +- src/json/pull_parser.cr | 10 ++--- src/kernel.cr | 2 +- src/levenshtein.cr | 4 +- src/llvm/abi/x86_64.cr | 2 +- src/llvm/basic_block_collection.cr | 4 +- src/llvm/context.cr | 2 +- src/llvm/function_collection.cr | 4 +- src/llvm/function_pass_manager.cr | 2 +- src/llvm/instruction_collection.cr | 2 +- src/llvm/jit_compiler.cr | 2 +- src/llvm/module.cr | 2 +- src/llvm/pass_builder_options.cr | 2 +- src/llvm/target.cr | 2 +- src/log/builder.cr | 2 +- src/log/main.cr | 8 ++-- src/log/metadata.cr | 2 +- src/log/setup.cr | 2 +- src/log/spec.cr | 4 +- src/mime/media_type.cr | 2 +- src/mime/multipart.cr | 8 ++-- src/mime/multipart/builder.cr | 8 ++-- src/mime/multipart/parser.cr | 2 +- src/mutex.cr | 2 +- src/named_tuple.cr | 10 ++--- src/oauth/consumer.cr | 4 +- src/oauth2/client.cr | 2 +- src/object.cr | 4 +- src/openssl/ssl/server.cr | 2 +- src/openssl/ssl/socket.cr | 4 +- src/option_parser.cr | 6 +-- src/path.cr | 2 +- src/pretty_print.cr | 12 ++--- src/process.cr | 4 +- src/process/executable_path.cr | 2 +- src/raise.cr | 2 +- src/range.cr | 4 +- src/reference.cr | 4 +- src/regex/pcre.cr | 4 +- src/regex/pcre2.cr | 6 +-- src/slice.cr | 2 +- src/socket.cr | 4 +- src/socket/addrinfo.cr | 8 ++-- src/socket/server.cr | 4 +- src/socket/tcp_server.cr | 4 +- src/socket/tcp_socket.cr | 2 +- src/socket/unix_server.cr | 2 +- src/socket/unix_socket.cr | 4 +- src/spec/expectations.cr | 2 +- src/string.cr | 44 +++++++++---------- src/string/builder.cr | 2 +- src/string/utf16.cr | 4 +- src/time/location/loader.cr | 4 +- src/tuple.cr | 10 ++--- src/unicode/unicode.cr | 6 +-- src/uri/encoding.cr | 2 +- src/uri/params.cr | 6 +-- src/va_list.cr | 2 +- src/xml/attributes.cr | 2 +- src/xml/builder.cr | 24 +++++----- src/xml/node_set.cr | 2 +- src/xml/reader.cr | 2 +- src/yaml/builder.cr | 12 ++--- src/yaml/from_yaml.cr | 8 ++-- src/yaml/nodes/builder.cr | 6 +-- src/yaml/nodes/nodes.cr | 4 +- src/yaml/nodes/parser.cr | 2 +- src/yaml/parse_context.cr | 4 +- src/yaml/parser.cr | 6 +-- src/yaml/pull_parser.cr | 10 ++--- src/yaml/schema/core.cr | 8 ++-- src/yaml/schema/core/parser.cr | 2 +- 225 files changed, 553 insertions(+), 553 deletions(-) diff --git a/samples/2048.cr b/samples/2048.cr index ef5ef3111d8f..75f37aa17c11 100644 --- a/samples/2048.cr +++ b/samples/2048.cr @@ -32,7 +32,7 @@ module Screen 65536 => {Colorize::ColorANSI::White, Colorize::ColorANSI::Black}, } - def self.colorize_for(tile) + def self.colorize_for(tile, &) fg_color, bg_color = TILES[tile] color = Colorize.with.fore(fg_color) color = color.back(bg_color) if bg_color @@ -241,7 +241,7 @@ class Game end end - def each_cell_with_index + def each_cell_with_index(&) 0.upto(@grid.size - 1) do |row| 0.upto(@grid.size - 1) do |col| yield @grid[row][col], row, col @@ -295,7 +295,7 @@ class Game end end - def movable_tiles(direction, drow, dcol) + def movable_tiles(direction, drow, dcol, &) max = @grid.size - 1 from_row, to_row, from_column, to_column = case direction diff --git a/samples/meteor.cr b/samples/meteor.cr index e6c91281ec03..65a1b8e5cb84 100644 --- a/samples/meteor.cr +++ b/samples/meteor.cr @@ -9,7 +9,7 @@ class MyIterator(T) def initialize(@data : T, &@block : T -> T) end - def each + def each(&) while true yield @data @data = @block.call(@data) @@ -145,7 +145,7 @@ class SolutionNode getter :x getter :prev - def each + def each(&) yield @x p = prev while y = p diff --git a/samples/red_black_tree.cr b/samples/red_black_tree.cr index fb56828a5b76..6ea240448d16 100644 --- a/samples/red_black_tree.cr +++ b/samples/red_black_tree.cr @@ -167,7 +167,7 @@ class RedBlackTree y end - def inorder_walk(x = root) + def inorder_walk(x = root, &) x = self.minimum while !x.nil_node? yield x.key @@ -175,11 +175,11 @@ class RedBlackTree end end - def each(x = root) + def each(x = root, &) inorder_walk(x) { |k| yield k } end - def reverse_inorder_walk(x = root) + def reverse_inorder_walk(x = root, &) x = self.maximum while !x.nil_node? yield x.key @@ -187,7 +187,7 @@ class RedBlackTree end end - def reverse_each(x = root) + def reverse_each(x = root, &) reverse_inorder_walk(x) { |k| yield k } end @@ -382,7 +382,7 @@ class RedBlackTreeRunner end end -def bench(name, n = 1) +def bench(name, n = 1, &) start = Time.monotonic print "#{name}: " res = nil diff --git a/samples/sdl/fire.cr b/samples/sdl/fire.cr index c3af69631398..7476b190984b 100644 --- a/samples/sdl/fire.cr +++ b/samples/sdl/fire.cr @@ -233,7 +233,7 @@ class Points end end - def each + def each(&) @points.each do |point| yield point unless point.dead? end diff --git a/samples/sdl/sdl/sdl.cr b/samples/sdl/sdl/sdl.cr index e601b027ea62..eb3a14b31620 100644 --- a/samples/sdl/sdl/sdl.cr +++ b/samples/sdl/sdl/sdl.cr @@ -35,7 +35,7 @@ module SDL LibSDL.quit end - def self.poll_events + def self.poll_events(&) while LibSDL.poll_event(out event) == 1 yield event end diff --git a/spec/compiler/crystal/tools/context_spec.cr b/spec/compiler/crystal/tools/context_spec.cr index c3f839033ac9..84c711e8af53 100644 --- a/spec/compiler/crystal/tools/context_spec.cr +++ b/spec/compiler/crystal/tools/context_spec.cr @@ -11,7 +11,7 @@ private def processed_context_visitor(code, cursor_location) {visitor, process_result} end -private def run_context_tool(code) +private def run_context_tool(code, &) cursor_location = nil code.lines.each_with_index do |line, line_number_0| diff --git a/spec/compiler/crystal/tools/expand_spec.cr b/spec/compiler/crystal/tools/expand_spec.cr index a4eccdea49d4..40a122587afd 100644 --- a/spec/compiler/crystal/tools/expand_spec.cr +++ b/spec/compiler/crystal/tools/expand_spec.cr @@ -13,7 +13,7 @@ private def processed_expand_visitor(code, cursor_location) {visitor, process_result} end -private def run_expand_tool(code) +private def run_expand_tool(code, &) cursor_location = nil code.lines.each_with_index do |line, line_number_0| @@ -41,7 +41,7 @@ private def assert_expand(code, expected_result) assert_expand(code, expected_result) { } end -private def assert_expand(code, expected_result) +private def assert_expand(code, expected_result, &) run_expand_tool code do |result| result.status.should eq("ok") result.message.should eq("#{expected_result.size} expansion#{expected_result.size >= 2 ? "s" : ""} found") @@ -59,7 +59,7 @@ private def assert_expand_simple(code, expanded, original = code.delete('‸')) assert_expand_simple(code, expanded, original) { } end -private def assert_expand_simple(code, expanded, original = code.delete('‸')) +private def assert_expand_simple(code, expanded, original = code.delete('‸'), &) assert_expand(code, [[original, expanded]]) { |result| yield result.expansions.not_nil![0] } end diff --git a/spec/compiler/crystal/tools/init_spec.cr b/spec/compiler/crystal/tools/init_spec.cr index 1408b0d4e0af..80b800b62dd8 100644 --- a/spec/compiler/crystal/tools/init_spec.cr +++ b/spec/compiler/crystal/tools/init_spec.cr @@ -22,7 +22,7 @@ end # Creates a temporary directory, cd to it and run the block inside it. # The directory and its content is deleted when the block return. -private def within_temporary_directory +private def within_temporary_directory(&) with_tempfile "init_spec_tmp" do |tmp_path| Dir.mkdir_p(tmp_path) Dir.cd(tmp_path) do @@ -31,7 +31,7 @@ private def within_temporary_directory end end -private def with_file(name) +private def with_file(name, &) yield File.read(name) end diff --git a/spec/compiler/crystal/tools/table_print_spec.cr b/spec/compiler/crystal/tools/table_print_spec.cr index eda496bb6c9c..44e335296090 100644 --- a/spec/compiler/crystal/tools/table_print_spec.cr +++ b/spec/compiler/crystal/tools/table_print_spec.cr @@ -1,7 +1,7 @@ require "spec" require "compiler/crystal/tools/table_print" -private def assert_table(expected) +private def assert_table(expected, &) actual = String::Builder.build do |builder| Crystal::TablePrint.new(builder).build do |tp| with tp yield diff --git a/spec/compiler/crystal/types_spec.cr b/spec/compiler/crystal/types_spec.cr index 307d341192e8..68106cf8edb8 100644 --- a/spec/compiler/crystal/types_spec.cr +++ b/spec/compiler/crystal/types_spec.cr @@ -1,6 +1,6 @@ require "../../spec_helper" -private def assert_type_to_s(expected) +private def assert_type_to_s(expected, &) p = Program.new t = with p yield p t.to_s.should eq(expected) diff --git a/spec/compiler/semantic/concrete_types_spec.cr b/spec/compiler/semantic/concrete_types_spec.cr index 6473505aa69e..cc8e4159b93c 100644 --- a/spec/compiler/semantic/concrete_types_spec.cr +++ b/spec/compiler/semantic/concrete_types_spec.cr @@ -1,6 +1,6 @@ require "../../spec_helper" -private def assert_concrete_types(str) +private def assert_concrete_types(str, &) result = semantic("struct Witness;end\n\n#{str}") program = result.program diff --git a/spec/compiler/semantic/def_overload_spec.cr b/spec/compiler/semantic/def_overload_spec.cr index f0e2a93864dc..2b8786550c29 100644 --- a/spec/compiler/semantic/def_overload_spec.cr +++ b/spec/compiler/semantic/def_overload_spec.cr @@ -1674,7 +1674,7 @@ describe "Semantic: def overload" do end end -private def each_union_variant(t1, t2) +private def each_union_variant(t1, t2, &) yield "#{t1} | #{t2}" yield "#{t2} | #{t1}" # yield "Union(#{t1}, #{t2})" diff --git a/spec/spec_helper.cr b/spec/spec_helper.cr index b3f1a13e7444..655cae7e333e 100644 --- a/spec/spec_helper.cr +++ b/spec/spec_helper.cr @@ -35,7 +35,7 @@ record SemanticResult, program : Program, node : ASTNode -def assert_type(str, *, inject_primitives = false, flags = nil, file = __FILE__, line = __LINE__) +def assert_type(str, *, inject_primitives = false, flags = nil, file = __FILE__, line = __LINE__, &) result = semantic(str, flags: flags, inject_primitives: inject_primitives) program = result.program expected_type = with program yield program @@ -166,7 +166,7 @@ def assert_macro_error(macro_body, message = nil, *, flags = nil, file = __FILE_ end end -def prepare_macro_call(macro_body, flags = nil) +def prepare_macro_call(macro_body, flags = nil, &) program = new_program program.flags.concat(flags.split) if flags args = yield program @@ -280,7 +280,7 @@ def run(code, filename = nil, inject_primitives = true, debug = Crystal::Debug:: end end -def test_c(c_code, crystal_code, *, file = __FILE__) +def test_c(c_code, crystal_code, *, file = __FILE__, &) with_temp_c_object_file(c_code, file: file) do |o_filename| yield run(%( require "prelude" diff --git a/spec/std/big/big_float_spec.cr b/spec/std/big/big_float_spec.cr index a8fbeb506563..50a234ffb408 100644 --- a/spec/std/big/big_float_spec.cr +++ b/spec/std/big/big_float_spec.cr @@ -9,7 +9,7 @@ private def it_converts_to_s(value : BigFloat, str, *, file = __FILE__, line = _ end end -private def with_precision(precision) +private def with_precision(precision, &) old_precision = BigFloat.default_precision BigFloat.default_precision = precision diff --git a/spec/std/deque_spec.cr b/spec/std/deque_spec.cr index 62012587ccbf..e1bc24bd4ed0 100644 --- a/spec/std/deque_spec.cr +++ b/spec/std/deque_spec.cr @@ -9,7 +9,7 @@ private class DequeTester @i : Int32 @c : Array(Int32) | Deque(Int32) | Nil - def step + def step(&) @c = @deque yield @c = @array @@ -30,7 +30,7 @@ private class DequeTester @c.not_nil! end - def test + def test(&) with self yield end end diff --git a/spec/std/dir_spec.cr b/spec/std/dir_spec.cr index c521c2faa4a0..47d95806e72a 100644 --- a/spec/std/dir_spec.cr +++ b/spec/std/dir_spec.cr @@ -1,7 +1,7 @@ require "./spec_helper" require "../support/env" -private def unset_tempdir +private def unset_tempdir(&) {% if flag?(:windows) %} old_tempdirs = {ENV["TMP"]?, ENV["TEMP"]?, ENV["USERPROFILE"]?} begin diff --git a/spec/std/enumerable_spec.cr b/spec/std/enumerable_spec.cr index a7bac45abd48..3383f5ad3f9c 100644 --- a/spec/std/enumerable_spec.cr +++ b/spec/std/enumerable_spec.cr @@ -3,7 +3,7 @@ require "spec" private class SpecEnumerable include Enumerable(Int32) - def each + def each(&) yield 1 yield 2 yield 3 diff --git a/spec/std/http/client/client_spec.cr b/spec/std/http/client/client_spec.cr index 1f35c086e9af..d23b3376e043 100644 --- a/spec/std/http/client/client_spec.cr +++ b/spec/std/http/client/client_spec.cr @@ -6,7 +6,7 @@ require "http/server" require "http/log" require "log/spec" -private def test_server(host, port, read_time = 0, content_type = "text/plain", write_response = true) +private def test_server(host, port, read_time = 0, content_type = "text/plain", write_response = true, &) server = TCPServer.new(host, port) begin spawn do @@ -475,7 +475,7 @@ module HTTP end class SubClient < HTTP::Client - def around_exec(request) + def around_exec(request, &) raise "from subclass" yield end diff --git a/spec/std/http/spec_helper.cr b/spec/std/http/spec_helper.cr index d7829553aeda..9bf88c82763f 100644 --- a/spec/std/http/spec_helper.cr +++ b/spec/std/http/spec_helper.cr @@ -2,7 +2,7 @@ require "spec" require "../spec_helper" require "../../support/fibers" -private def wait_for +private def wait_for(&) timeout = {% if flag?(:interpreted) %} # TODO: it's not clear why some interpreter specs # take more than 5 seconds to bind to a server. @@ -31,7 +31,7 @@ end # shut down before continuing execution in the current fiber. # 6. If the listening fiber raises an exception, it is rescued and re-raised # in the current fiber. -def run_server(server) +def run_server(server, &) server_done = Channel(Exception?).new f = spawn do @@ -58,7 +58,7 @@ end # Helper method which runs a *handler* # Similar to `run_server` but doesn't go through the network stack. -def run_handler(handler) +def run_handler(handler, &) done = Channel(Exception?).new begin diff --git a/spec/std/http/web_socket_spec.cr b/spec/std/http/web_socket_spec.cr index 3610e524d56e..75a54e91fb2e 100644 --- a/spec/std/http/web_socket_spec.cr +++ b/spec/std/http/web_socket_spec.cr @@ -565,7 +565,7 @@ describe HTTP::WebSocket do typeof(HTTP::WebSocket.new(URI.parse("ws://localhost"), headers: HTTP::Headers{"X-TEST_HEADER" => "some-text"})) end -private def integration_setup +private def integration_setup(&) bin_ch = Channel(Bytes).new txt_ch = Channel(String).new ws_handler = HTTP::WebSocketHandler.new do |ws, ctx| diff --git a/spec/std/io/buffered_spec.cr b/spec/std/io/buffered_spec.cr index ca092219c7c7..d8ef8ff3b979 100644 --- a/spec/std/io/buffered_spec.cr +++ b/spec/std/io/buffered_spec.cr @@ -12,7 +12,7 @@ private class BufferedWrapper < IO @called_unbuffered_read = false end - def self.new(io) + def self.new(io, &) buffered_io = new(io) yield buffered_io buffered_io.flush diff --git a/spec/std/json/builder_spec.cr b/spec/std/json/builder_spec.cr index 5a8ab0836f6d..66f9be33b741 100644 --- a/spec/std/json/builder_spec.cr +++ b/spec/std/json/builder_spec.cr @@ -2,7 +2,7 @@ require "spec" require "json" require "../../support/string" -private def assert_built(expected, *, file = __FILE__, line = __LINE__) +private def assert_built(expected, *, file = __FILE__, line = __LINE__, &) assert_prints JSON.build { |json| with json yield json }, expected, file: file, line: line end diff --git a/spec/std/json/pull_parser_spec.cr b/spec/std/json/pull_parser_spec.cr index 5ab6b34608b4..8cf4127237bf 100644 --- a/spec/std/json/pull_parser_spec.cr +++ b/spec/std/json/pull_parser_spec.cr @@ -36,7 +36,7 @@ class JSON::PullParser read_next end - def assert(value : String) + def assert(value : String, &) kind.should eq(JSON::PullParser::Kind::String) string_value.should eq(value) read_next @@ -61,7 +61,7 @@ class JSON::PullParser end end - def assert_array + def assert_array(&) kind.should eq(JSON::PullParser::Kind::BeginArray) read_next yield @@ -73,7 +73,7 @@ class JSON::PullParser assert_array { } end - def assert_object + def assert_object(&) kind.should eq(JSON::PullParser::Kind::BeginObject) read_next yield diff --git a/spec/std/spec/junit_formatter_spec.cr b/spec/std/spec/junit_formatter_spec.cr index 36591f816f5b..39e0841362a9 100644 --- a/spec/std/spec/junit_formatter_spec.cr +++ b/spec/std/spec/junit_formatter_spec.cr @@ -168,7 +168,7 @@ describe "JUnit Formatter" do end end -private def build_report(timestamp = nil) +private def build_report(timestamp = nil, &) output = String::Builder.new formatter = Spec::JUnitFormatter.new(output) formatter.started_at = timestamp if timestamp @@ -177,7 +177,7 @@ private def build_report(timestamp = nil) output.to_s.chomp end -private def build_report_with_no_timestamp +private def build_report_with_no_timestamp(&) output = build_report do |formatter| yield formatter end diff --git a/spec/std/spec/tap_formatter_spec.cr b/spec/std/spec/tap_formatter_spec.cr index daf8e04a08c8..8e84ce36cb7d 100644 --- a/spec/std/spec/tap_formatter_spec.cr +++ b/spec/std/spec/tap_formatter_spec.cr @@ -1,6 +1,6 @@ require "spec" -private def build_report +private def build_report(&) String.build do |io| formatter = Spec::TAPFormatter.new(io) yield formatter diff --git a/spec/std/spec_helper.cr b/spec/std/spec_helper.cr index 19d035cab142..246762432c04 100644 --- a/spec/std/spec_helper.cr +++ b/spec/std/spec_helper.cr @@ -75,7 +75,7 @@ def spawn_and_check(before : Proc(_), file = __FILE__, line = __LINE__, &block : end end -def compile_file(source_file, *, bin_name = "executable_file", flags = %w(), file = __FILE__) +def compile_file(source_file, *, bin_name = "executable_file", flags = %w(), file = __FILE__, &) with_temp_executable(bin_name, file: file) do |executable_file| compiler = ENV["CRYSTAL_SPEC_COMPILER_BIN"]? || "bin/crystal" Process.run(compiler, ["build"] + flags + ["-o", executable_file, source_file], env: { @@ -89,7 +89,7 @@ def compile_file(source_file, *, bin_name = "executable_file", flags = %w(), fil end end -def compile_source(source, flags = %w(), file = __FILE__) +def compile_source(source, flags = %w(), file = __FILE__, &) with_tempfile("source_file", file: file) do |source_file| File.write(source_file, source) compile_file(source_file, flags: flags, file: file) do |executable_file| @@ -114,7 +114,7 @@ def compile_and_run_source(source, flags = %w(), file = __FILE__) end end -def compile_and_run_source_with_c(c_code, crystal_code, flags = %w(--debug), file = __FILE__) +def compile_and_run_source_with_c(c_code, crystal_code, flags = %w(--debug), file = __FILE__, &) with_temp_c_object_file(c_code, file: file) do |o_filename| yield compile_and_run_source(%( require "prelude" diff --git a/spec/std/time/span_spec.cr b/spec/std/time/span_spec.cr index 3ea26728998e..e59ece5a66d8 100644 --- a/spec/std/time/span_spec.cr +++ b/spec/std/time/span_spec.cr @@ -1,7 +1,7 @@ require "spec" require "spec/helpers/iterate" -private def expect_overflow +private def expect_overflow(&) expect_raises ArgumentError, "Time::Span too big or too small" do yield end diff --git a/spec/std/time/spec_helper.cr b/spec/std/time/spec_helper.cr index 507a210eff5e..00ee69632852 100644 --- a/spec/std/time/spec_helper.cr +++ b/spec/std/time/spec_helper.cr @@ -10,7 +10,7 @@ class Time::Location end end -def with_env(name, value) +def with_env(name, value, &) previous = ENV[name]? begin ENV[name] = value @@ -25,7 +25,7 @@ end ZONEINFO_ZIP = datapath("zoneinfo.zip") -def with_zoneinfo(path = ZONEINFO_ZIP) +def with_zoneinfo(path = ZONEINFO_ZIP, &) with_env("ZONEINFO", path) do Time::Location.__clear_location_cache diff --git a/spec/std/xml/builder_spec.cr b/spec/std/xml/builder_spec.cr index be4e8ecff665..0fd7450b0104 100644 --- a/spec/std/xml/builder_spec.cr +++ b/spec/std/xml/builder_spec.cr @@ -2,7 +2,7 @@ require "spec" require "xml" require "../../support/string" -private def assert_built(expected, quote_char = nil, *, file = __FILE__, line = __LINE__) +private def assert_built(expected, quote_char = nil, *, file = __FILE__, line = __LINE__, &) assert_prints XML.build(quote_char: quote_char) { |xml| with xml yield xml }, expected, file: file, line: line end diff --git a/spec/std/yaml/builder_spec.cr b/spec/std/yaml/builder_spec.cr index c86909e886af..e225a745587d 100644 --- a/spec/std/yaml/builder_spec.cr +++ b/spec/std/yaml/builder_spec.cr @@ -2,7 +2,7 @@ require "spec" require "yaml" require "../../support/string" -private def assert_built(expected, expect_document_end = false, *, file = __FILE__, line = __LINE__) +private def assert_built(expected, expect_document_end = false, *, file = __FILE__, line = __LINE__, &) # libyaml 0.2.1 removed the erroneously written document end marker (`...`) after some scalars in root context (see https://github.com/yaml/libyaml/pull/18). # Earlier libyaml releases still write the document end marker and this is hard to fix on Crystal's side. # So we just ignore it and adopt the specs accordingly to coincide with the used libyaml version. diff --git a/spec/std/yaml/nodes/builder_spec.cr b/spec/std/yaml/nodes/builder_spec.cr index 8f1778dcb629..16a589f4be5e 100644 --- a/spec/std/yaml/nodes/builder_spec.cr +++ b/spec/std/yaml/nodes/builder_spec.cr @@ -1,7 +1,7 @@ require "spec" require "yaml" -private def assert_built(expected, expect_document_end = false) +private def assert_built(expected, expect_document_end = false, &) # libyaml 0.2.1 removed the erroneously written document end marker (`...`) after some scalars in root context (see https://github.com/yaml/libyaml/pull/18). # Earlier libyaml releases still write the document end marker and this is hard to fix on Crystal's side. # So we just ignore it and adopt the specs accordingly to coincide with the used libyaml version. diff --git a/spec/support/env.cr b/spec/support/env.cr index 66f1549c5bea..616f1cc60cd5 100644 --- a/spec/support/env.cr +++ b/spec/support/env.cr @@ -1,4 +1,4 @@ -def with_env(values : Hash) +def with_env(values : Hash, &) old_values = {} of String => String? begin values.each do |key, value| @@ -15,6 +15,6 @@ def with_env(values : Hash) end end -def with_env(**values) +def with_env(**values, &) with_env(values.to_h) { yield } end diff --git a/spec/support/finalize.cr b/spec/support/finalize.cr index 115f036d1993..967b3c78bf9f 100644 --- a/spec/support/finalize.cr +++ b/spec/support/finalize.cr @@ -30,7 +30,7 @@ module FinalizeCounter end end -def assert_finalizes(key : String) +def assert_finalizes(key : String, &) FinalizeState.reset FinalizeState.count(key).should eq(0) diff --git a/spec/support/retry.cr b/spec/support/retry.cr index 1c368dee0134..638804c4be81 100644 --- a/spec/support/retry.cr +++ b/spec/support/retry.cr @@ -1,4 +1,4 @@ -def retry(n = 5) +def retry(n = 5, &) exception = nil n.times do |i| yield diff --git a/spec/support/tempfile.cr b/spec/support/tempfile.cr index 1d62cc33ff87..41aa209abde9 100644 --- a/spec/support/tempfile.cr +++ b/spec/support/tempfile.cr @@ -21,7 +21,7 @@ SPEC_TEMPFILE_CLEANUP = ENV["SPEC_TEMPFILE_CLEANUP"]? != "0" # # If the environment variable `SPEC_TEMPFILE_CLEANUP` is set to `0`, no paths # will be cleaned up, enabling easier debugging. -def with_tempfile(*paths, file = __FILE__) +def with_tempfile(*paths, file = __FILE__, &) calling_spec = File.basename(file).rchop("_spec.cr") paths = paths.map { |path| File.join(SPEC_TEMPFILE_PATH, calling_spec, path) } FileUtils.mkdir_p(File.join(SPEC_TEMPFILE_PATH, calling_spec)) @@ -37,7 +37,7 @@ def with_tempfile(*paths, file = __FILE__) end end -def with_temp_executable(name, file = __FILE__) +def with_temp_executable(name, file = __FILE__, &) {% if flag?(:win32) %} name += ".exe" {% end %} @@ -46,7 +46,7 @@ def with_temp_executable(name, file = __FILE__) end end -def with_temp_c_object_file(c_code, *, filename = "temp_c", file = __FILE__) +def with_temp_c_object_file(c_code, *, filename = "temp_c", file = __FILE__, &) obj_ext = {{ flag?(:msvc) ? ".obj" : ".o" }} with_tempfile("#{filename}.c", "#{filename}#{obj_ext}", file: file) do |c_filename, o_filename| File.write(c_filename, c_code) diff --git a/src/array.cr b/src/array.cr index 31ab55075464..7b283aaf13f2 100644 --- a/src/array.cr +++ b/src/array.cr @@ -1121,7 +1121,7 @@ class Array(T) # `reject!` and `delete` implementation: returns a tuple {x, y} # with x being self/nil (modified, not modified) # and y being the last matching element, or nil - private def internal_delete + private def internal_delete(&) i1 = 0 i2 = 0 match = nil @@ -1214,13 +1214,13 @@ class Array(T) # *arrays* as `Array`s. # Traversal of elements starts from the last given array. @[Deprecated("Use `Indexable.each_cartesian(indexables : Indexable(Indexable), reuse = false, &block)` instead")] - def self.each_product(arrays : Array(Array), reuse = false) + def self.each_product(arrays : Array(Array), reuse = false, &) Indexable.each_cartesian(arrays, reuse: reuse) { |r| yield r } end # :ditto: @[Deprecated("Use `Indexable.each_cartesian(indexables : Indexable(Indexable), reuse = false, &block)` instead")] - def self.each_product(*arrays : Array, reuse = false) + def self.each_product(*arrays : Array, reuse = false, &) Indexable.each_cartesian(arrays, reuse: reuse) { |r| yield r } end @@ -1232,7 +1232,7 @@ class Array(T) ary end - def each_repeated_permutation(size : Int = self.size, reuse = false) : Nil + def each_repeated_permutation(size : Int = self.size, reuse = false, &) : Nil n = self.size return if size != 0 && n == 0 raise ArgumentError.new("Size must be positive") if size < 0 @@ -1269,7 +1269,7 @@ class Array(T) # ``` # # See also: `#truncate`. - def pop + def pop(&) if @size == 0 yield else @@ -1461,7 +1461,7 @@ class Array(T) # ``` # # See also: `#truncate`. - def shift + def shift(&) if @size == 0 yield else diff --git a/src/base64.cr b/src/base64.cr index 10ef444f08f1..241d00c57bda 100644 --- a/src/base64.cr +++ b/src/base64.cr @@ -68,7 +68,7 @@ module Base64 count end - private def encode_with_new_lines(data) + private def encode_with_new_lines(data, &) inc = 0 to_base64(data.to_slice, CHARS_STD, pad: true) do |byte| yield byte @@ -199,7 +199,7 @@ module Base64 (str_size * 3 / 4.0).to_i + 4 end - private def to_base64(data, chars, pad = false) + private def to_base64(data, chars, pad = false, &) bytes = chars.to_unsafe size = data.size cstr = data.to_unsafe diff --git a/src/benchmark.cr b/src/benchmark.cr index da2a10be9def..59cad44ba13e 100644 --- a/src/benchmark.cr +++ b/src/benchmark.cr @@ -85,7 +85,7 @@ module Benchmark # Main interface of the `Benchmark` module. Yields a `Job` to which # one can report the benchmarks. See the module's description. - def bm + def bm(&) {% if !flag?(:release) %} puts "Warning: benchmarking without the `--release` flag won't yield useful results" {% end %} @@ -103,7 +103,7 @@ module Benchmark # those stages in seconds. For more detail on these stages see # `Benchmark::IPS`. When the *interactive* parameter is `true`, results are # displayed and updated as they are calculated, otherwise all at once after they finished. - def ips(calculation = 5, warmup = 2, interactive = STDOUT.tty?) + def ips(calculation = 5, warmup = 2, interactive = STDOUT.tty?, &) {% if !flag?(:release) %} puts "Warning: benchmarking without the `--release` flag won't yield useful results" {% end %} @@ -116,7 +116,7 @@ module Benchmark end # Returns the time used to execute the given block. - def measure(label = "") : BM::Tms + def measure(label = "", &) : BM::Tms t0, r0 = Process.times, Time.monotonic yield t1, r1 = Process.times, Time.monotonic @@ -133,7 +133,7 @@ module Benchmark # ``` # Benchmark.realtime { "a" * 100_000 } # => 00:00:00.0005840 # ``` - def realtime : Time::Span + def realtime(&) : Time::Span Time.measure { yield } end @@ -142,7 +142,7 @@ module Benchmark # ``` # Benchmark.memory { Array(Int32).new } # => 32 # ``` - def memory + def memory(&) bytes_before_measure = GC.stats.total_bytes yield (GC.stats.total_bytes - bytes_before_measure).to_i64 diff --git a/src/big/big_decimal.cr b/src/big/big_decimal.cr index 1cb44c0b1657..b5d9e93f2d29 100644 --- a/src/big/big_decimal.cr +++ b/src/big/big_decimal.cr @@ -398,7 +398,7 @@ struct BigDecimal < Number round_impl { |rem, rem_range| rem.abs >= rem_range // 2 } end - private def round_impl + private def round_impl(&) return self if @scale <= 0 || zero? # `self == @value / 10 ** @scale == mantissa + (rem / 10 ** @scale)` diff --git a/src/big/big_float.cr b/src/big/big_float.cr index 6a9a7dbe0862..7c90a6985207 100644 --- a/src/big/big_float.cr +++ b/src/big/big_float.cr @@ -76,7 +76,7 @@ struct BigFloat < Float def initialize(@mpf : LibGMP::MPF) end - def self.new + def self.new(&) LibGMP.mpf_init(out mpf) yield pointerof(mpf) new(mpf) diff --git a/src/big/big_int.cr b/src/big/big_int.cr index f703a6854126..aaae48999938 100644 --- a/src/big/big_int.cr +++ b/src/big/big_int.cr @@ -93,7 +93,7 @@ struct BigInt < Int end # :nodoc: - def self.new + def self.new(&) LibGMP.init(out mpz) yield pointerof(mpz) new(mpz) diff --git a/src/big/big_rational.cr b/src/big/big_rational.cr index 9c16d1577c69..c87273788fef 100644 --- a/src/big/big_rational.cr +++ b/src/big/big_rational.cr @@ -74,7 +74,7 @@ struct BigRational < Number end # :nodoc: - def self.new + def self.new(&) LibGMP.mpq_init(out mpq) yield pointerof(mpq) new(mpq) diff --git a/src/bit_array.cr b/src/bit_array.cr index 9003de5d396f..080c8475765b 100644 --- a/src/bit_array.cr +++ b/src/bit_array.cr @@ -643,7 +643,7 @@ struct BitArray bit_index_and_sub_index(index) { raise IndexError.new } end - private def bit_index_and_sub_index(index) + private def bit_index_and_sub_index(index, &) index = check_index_out_of_bounds(index) do return yield end diff --git a/src/channel.cr b/src/channel.cr index 5a7a5957c786..30ff68ec6412 100644 --- a/src/channel.cr +++ b/src/channel.cr @@ -288,7 +288,7 @@ class Channel(T) receive_impl { return nil } end - private def receive_impl + private def receive_impl(&) receiver = Receiver(T).new @lock.lock @@ -474,7 +474,7 @@ class Channel(T) raise "BUG: Fiber was awaken from select but no action was activated" end - private def self.each_skip_duplicates(ops_locks) + private def self.each_skip_duplicates(ops_locks, &) # Avoid deadlocks from trying to lock the same lock twice. # `ops_lock` is sorted by `lock_object_id`, so identical onces will be in # a row and we skip repeats while iterating. diff --git a/src/char.cr b/src/char.cr index cb8afeb83230..f64b247efd9c 100644 --- a/src/char.cr +++ b/src/char.cr @@ -409,7 +409,7 @@ struct Char # This method takes into account the possibility that an downcase # version of a char might result in multiple chars, like for # 'İ', which results in 'i' and a dot mark. - def downcase(options : Unicode::CaseOptions = :none) + def downcase(options : Unicode::CaseOptions = :none, &) Unicode.downcase(self, options) { |char| yield char } end @@ -441,7 +441,7 @@ struct Char # 'z'.upcase { |v| puts v } # prints 'Z' # 'ffl'.upcase { |v| puts v } # prints 'F', 'F', 'L' # ``` - def upcase(options : Unicode::CaseOptions = :none) + def upcase(options : Unicode::CaseOptions = :none, &) Unicode.upcase(self, options) { |char| yield char } end @@ -615,7 +615,7 @@ struct Char io << dump end - private def dump_or_inspect + private def dump_or_inspect(&) case self when '\'' then "'\\''" when '\\' then "'\\\\'" @@ -804,7 +804,7 @@ struct Char # 129 # 130 # ``` - def each_byte : Nil + def each_byte(&) : Nil # See http://en.wikipedia.org/wiki/UTF-8#Sample_code c = ord diff --git a/src/char/reader.cr b/src/char/reader.cr index 22bb978b5669..6213883cdc3a 100644 --- a/src/char/reader.cr +++ b/src/char/reader.cr @@ -176,7 +176,7 @@ struct Char # B # C # ``` - def each : Nil + def each(&) : Nil while has_next? yield current_char @pos += @current_char_width diff --git a/src/colorize.cr b/src/colorize.cr index 429795087779..8cdd6648e8ff 100644 --- a/src/colorize.cr +++ b/src/colorize.cr @@ -294,7 +294,7 @@ module Colorize end end -private def each_code(mode : Colorize::Mode) +private def each_code(mode : Colorize::Mode, &) yield '1' if mode.bold? yield '2' if mode.dim? yield '4' if mode.underline? @@ -436,7 +436,7 @@ struct Colorize::Object(T) # # io.to_s # returns a colorful string where "colorful" is red, "hello" green, "world" blue and " string" red again # ``` - def surround(io = STDOUT) + def surround(io = STDOUT, &) return yield io unless @enabled Object.surround(io, to_named_tuple) do |io| @@ -458,7 +458,7 @@ struct Colorize::Object(T) mode: Mode::None, } - protected def self.surround(io, color) + protected def self.surround(io, color, &) last_color = @@last_color must_append_end = append_start(io, color) @@last_color = color diff --git a/src/compiler/crystal/codegen/codegen.cr b/src/compiler/crystal/codegen/codegen.cr index 058108a25710..371df0592767 100644 --- a/src/compiler/crystal/codegen/codegen.cr +++ b/src/compiler/crystal/codegen/codegen.cr @@ -1401,7 +1401,7 @@ module Crystal codegen_type_filter node, &.filter_by_responds_to(node.name) end - def codegen_type_filter(node) + def codegen_type_filter(node, &) accept node.obj obj_type = node.obj.type @@ -1635,7 +1635,7 @@ module Crystal make_fun type, null, null end - def in_main + def in_main(&) old_builder = self.builder old_position = old_builder.insert_block old_llvm_mod = @llvm_mod @@ -1681,7 +1681,7 @@ module Crystal block_value end - def define_main_function(name, arg_types, return_type, needs_alloca = false) + def define_main_function(name, arg_types, return_type, needs_alloca = false, &) if @llvm_mod != @main_mod raise "wrong usage of define_main_function: you must put it inside an `in_main` block" end @@ -1920,7 +1920,7 @@ module Crystal in_alloca_block { builder.alloca type, name } end - def in_alloca_block + def in_alloca_block(&) old_block = insert_block position_at_end alloca_block value = yield @@ -1949,7 +1949,7 @@ module Crystal # debug_codegen_log { {"Lorem %d", [an_int_llvm_value] of LLVM::Value} } # ``` # - def debug_codegen_log(file = __FILE__, line = __LINE__) + def debug_codegen_log(file = __FILE__, line = __LINE__, &) return unless ENV["CRYSTAL_DEBUG_CODEGEN"]? printf_args = yield || "" printf_args = {printf_args, [] of LLVM::Value} if printf_args.is_a?(String) @@ -1986,7 +1986,7 @@ module Crystal @last = type_ptr end - def allocate_tuple(type) + def allocate_tuple(type, &) struct_type = alloca llvm_type(type) type.tuple_types.each_with_index do |tuple_type, i| exp_type, value = yield tuple_type, i @@ -2037,7 +2037,7 @@ module Crystal generic_malloc(type) { crystal_malloc_atomic_fun } end - def generic_malloc(type) + def generic_malloc(type, &) size = type.size if malloc_fun = yield @@ -2057,7 +2057,7 @@ module Crystal generic_array_malloc(type, count) { crystal_malloc_atomic_fun } end - def generic_array_malloc(type, count) + def generic_array_malloc(type, count, &) size = builder.mul type.size, count if malloc_fun = yield @@ -2245,7 +2245,7 @@ module Crystal end end - def request_value(request : Bool = true) + def request_value(request : Bool = true, &) old_needs_value = @needs_value @needs_value = request begin diff --git a/src/compiler/crystal/codegen/context.cr b/src/compiler/crystal/codegen/context.cr index d89f8c0e199d..595306476b34 100644 --- a/src/compiler/crystal/codegen/context.cr +++ b/src/compiler/crystal/codegen/context.cr @@ -61,11 +61,11 @@ class Crystal::CodeGenVisitor end end - def with_cloned_context(new_context = @context) + def with_cloned_context(new_context = @context, &) with_context(new_context.clone) { |ctx| yield ctx } end - def with_context(new_context) + def with_context(new_context, &) old_context = @context @context = new_context value = yield old_context diff --git a/src/compiler/crystal/codegen/debug.cr b/src/compiler/crystal/codegen/debug.cr index 04d9aef2876d..6124840113c3 100644 --- a/src/compiler/crystal/codegen/debug.cr +++ b/src/compiler/crystal/codegen/debug.cr @@ -340,7 +340,7 @@ module Crystal end end - private def declare_local(type, alloca, location, basic_block : LLVM::BasicBlock? = nil) + private def declare_local(type, alloca, location, basic_block : LLVM::BasicBlock? = nil, &) location = location.try &.expanded_location return false unless location diff --git a/src/compiler/crystal/codegen/phi.cr b/src/compiler/crystal/codegen/phi.cr index 2a0b81d2f5b4..168f30d26293 100644 --- a/src/compiler/crystal/codegen/phi.cr +++ b/src/compiler/crystal/codegen/phi.cr @@ -6,7 +6,7 @@ class Crystal::CodeGenVisitor property? force_exit_block = false - def self.open(codegen, node, needs_value = true) + def self.open(codegen, node, needs_value = true, &) block = new codegen, node, needs_value yield block block.close diff --git a/src/compiler/crystal/codegen/primitives.cr b/src/compiler/crystal/codegen/primitives.cr index bc71b573e889..da368301015a 100644 --- a/src/compiler/crystal/codegen/primitives.cr +++ b/src/compiler/crystal/codegen/primitives.cr @@ -818,7 +818,7 @@ class Crystal::CodeGenVisitor end end - def set_aggregate_field(node, target_def, call_args) + def set_aggregate_field(node, target_def, call_args, &) call_arg = call_args[1] original_call_arg = call_arg diff --git a/src/compiler/crystal/command/cursor.cr b/src/compiler/crystal/command/cursor.cr index 6ea2d3be0317..cf8d9a0b2803 100644 --- a/src/compiler/crystal/command/cursor.cr +++ b/src/compiler/crystal/command/cursor.cr @@ -23,7 +23,7 @@ class Crystal::Command end end - private def cursor_command(command, no_cleanup = false, wants_doc = false) + private def cursor_command(command, no_cleanup = false, wants_doc = false, &) config, result = compile_no_codegen command, cursor_command: true, no_cleanup: no_cleanup, diff --git a/src/compiler/crystal/compiler.cr b/src/compiler/crystal/compiler.cr index 0baaf2db0c08..a639e2506def 100644 --- a/src/compiler/crystal/compiler.cr +++ b/src/compiler/crystal/compiler.cr @@ -285,7 +285,7 @@ module Crystal result end - private def with_file_lock(output_dir) + private def with_file_lock(output_dir, &) File.open(File.join(output_dir, "compiler.lock"), "w") do |file| file.flock_exclusive do yield @@ -604,7 +604,7 @@ module Crystal end end - private def process_wrapper(command, args = nil) + private def process_wrapper(command, args = nil, &) print_command(command, args) if verbose? status = yield command, args diff --git a/src/compiler/crystal/interpreter/class_vars.cr b/src/compiler/crystal/interpreter/class_vars.cr index fd7d4549e11e..a5f9da19294e 100644 --- a/src/compiler/crystal/interpreter/class_vars.cr +++ b/src/compiler/crystal/interpreter/class_vars.cr @@ -64,7 +64,7 @@ class Crystal::Repl::ClassVars # Yields each index of every class variable that is trivially "initialized" # when the program starts: those that don't have initializers. - def each_initialized_index + def each_initialized_index(&) @data.each_value do |value| yield value.index unless value.compiled_def end diff --git a/src/compiler/crystal/interpreter/compiler.cr b/src/compiler/crystal/interpreter/compiler.cr index 5f480e7d18ab..7787c63b73e6 100644 --- a/src/compiler/crystal/interpreter/compiler.cr +++ b/src/compiler/crystal/interpreter/compiler.cr @@ -30,7 +30,7 @@ class Crystal::Repl::Compiler < Crystal::Visitor # This is different than `compiling_block`. Consider this code: # # ``` - # def foo + # def foo(&) # # When this is called from the top-level, `compiled_block` # # will be the block given to `foo`, but `compiling_block` # # will be `nil` because we are not compiling a block. @@ -44,7 +44,7 @@ class Crystal::Repl::Compiler < Crystal::Visitor # end # end # - # def bar + # def bar(&) # yield # end # @@ -1084,7 +1084,7 @@ class Crystal::Repl::Compiler < Crystal::Visitor false end - private def dispatch_class_var(node : ClassVar) + private def dispatch_class_var(node : ClassVar, &) var = node.var owner = var.owner @@ -1102,7 +1102,7 @@ class Crystal::Repl::Compiler < Crystal::Visitor end end - private def dispatch_class_var(owner : Type, metaclass : Bool, node : ASTNode) + private def dispatch_class_var(owner : Type, metaclass : Bool, node : ASTNode, &) types = owner.all_subclasses.select { |t| t.is_a?(ClassVarContainer) } types.push(owner) types.sort_by! { |type| -type.depth } @@ -3046,7 +3046,7 @@ class Crystal::Repl::Compiler < Crystal::Visitor false end - private def with_scope(scope : Type) + private def with_scope(scope : Type, &) old_scope = @scope @scope = scope begin @@ -3409,7 +3409,7 @@ class Crystal::Repl::Compiler < Crystal::Visitor private macro nop end - private def with_node_override(node_override : ASTNode) + private def with_node_override(node_override : ASTNode, &) old_node_override = @node_override @node_override = node_override value = yield diff --git a/src/compiler/crystal/interpreter/pry_reader.cr b/src/compiler/crystal/interpreter/pry_reader.cr index d7b57fcfaded..4e0a9f64d33b 100644 --- a/src/compiler/crystal/interpreter/pry_reader.cr +++ b/src/compiler/crystal/interpreter/pry_reader.cr @@ -20,15 +20,15 @@ class Crystal::PryReader < Crystal::ReplReader end end - def on_ctrl_down + def on_ctrl_down(&) yield "next" end - def on_ctrl_left + def on_ctrl_left(&) yield "finish" end - def on_ctrl_right + def on_ctrl_right(&) yield "step" end end diff --git a/src/compiler/crystal/macros/interpreter.cr b/src/compiler/crystal/macros/interpreter.cr index 5d56f5320c3c..7da3a4dac39d 100644 --- a/src/compiler/crystal/macros/interpreter.cr +++ b/src/compiler/crystal/macros/interpreter.cr @@ -238,7 +238,7 @@ module Crystal visit_macro_for_array_like node, exp, exp.elements, &.itself end - def visit_macro_for_array_like(node, exp, entries) + def visit_macro_for_array_like(node, exp, entries, &) element_var = node.vars[0] index_var = node.vars[1]? @@ -254,7 +254,7 @@ module Crystal @vars.delete index_var.name if index_var end - def visit_macro_for_hash_like(node, exp, entries) + def visit_macro_for_hash_like(node, exp, entries, &) key_var = node.vars[0] value_var = node.vars[1]? index_var = node.vars[2]? diff --git a/src/compiler/crystal/macros/macros.cr b/src/compiler/crystal/macros/macros.cr index 17388305f8be..c74a482f9d03 100644 --- a/src/compiler/crystal/macros/macros.cr +++ b/src/compiler/crystal/macros/macros.cr @@ -34,7 +34,7 @@ class Crystal::Program parse_macro_source generated_source, macro_expansion_pragmas, the_macro, node, vars, current_def, inside_type, inside_exp, visibility, &.parse(mode) end - def parse_macro_source(generated_source, macro_expansion_pragmas, the_macro, node, vars, current_def = nil, inside_type = false, inside_exp = false, visibility : Visibility = :public) + def parse_macro_source(generated_source, macro_expansion_pragmas, the_macro, node, vars, current_def = nil, inside_type = false, inside_exp = false, visibility : Visibility = :public, &) parser = @program.new_parser(generated_source, var_scopes: [vars.dup]) parser.filename = VirtualFile.new(the_macro, generated_source, node.location) parser.macro_expansion_pragmas = macro_expansion_pragmas diff --git a/src/compiler/crystal/macros/methods.cr b/src/compiler/crystal/macros/methods.cr index 2ecdd2c141c8..ff5279bfa022 100644 --- a/src/compiler/crystal/macros/methods.cr +++ b/src/compiler/crystal/macros/methods.cr @@ -4,7 +4,7 @@ require "semantic_version" module Crystal class MacroInterpreter - private def find_source_file(filename) + private def find_source_file(filename, &) # Support absolute paths if filename.starts_with?('/') filename = "#{filename}.cr" unless filename.ends_with?(".cr") @@ -518,21 +518,21 @@ module Crystal to_number <=> other.to_number end - def bool_bin_op(method, args, named_args, block) + def bool_bin_op(method, args, named_args, block, &) interpret_check_args do |other| raise "can't #{method} with #{other}" unless other.is_a?(NumberLiteral) BoolLiteral.new(yield to_number, other.to_number) end end - def num_bin_op(method, args, named_args, block) + def num_bin_op(method, args, named_args, block, &) interpret_check_args do |other| raise "can't #{method} with #{other}" unless other.is_a?(NumberLiteral) NumberLiteral.new(yield to_number, other.to_number) end end - def int_bin_op(method, args, named_args, block) + def int_bin_op(method, args, named_args, block, &) interpret_check_args do |other| raise "can't #{method} with #{other}" unless other.is_a?(NumberLiteral) me = to_number @@ -1073,7 +1073,7 @@ module Crystal end end - def interpret_map(interpreter) + def interpret_map(interpreter, &) ArrayLiteral.map(interpret_to_range(interpreter)) do |num| yield num end @@ -2683,7 +2683,7 @@ private def filter(object, klass, block, interpreter, keep = true) end) end -private def fetch_annotation(node, method, args, named_args, block) +private def fetch_annotation(node, method, args, named_args, block, &) interpret_check_args(node: node) do |arg| unless arg.is_a?(Crystal::TypeNode) args[0].raise "argument to '#{node.class_desc}#annotation' must be a TypeNode, not #{arg.class_desc}" @@ -2699,7 +2699,7 @@ private def fetch_annotation(node, method, args, named_args, block) end end -private def fetch_annotations(node, method, args, named_args, block) +private def fetch_annotations(node, method, args, named_args, block, &) interpret_check_args(node: node, min_count: 0) do |arg| unless arg return yield(nil) || Crystal::NilLiteral.new diff --git a/src/compiler/crystal/progress_tracker.cr b/src/compiler/crystal/progress_tracker.cr index fb49adaa8bd5..cfbe1e1293af 100644 --- a/src/compiler/crystal/progress_tracker.cr +++ b/src/compiler/crystal/progress_tracker.cr @@ -12,7 +12,7 @@ module Crystal getter stage_progress = 0 getter stage_progress_total : Int32? - def stage(name) + def stage(name, &) @current_stage_name = name print_stats diff --git a/src/compiler/crystal/semantic/bindings.cr b/src/compiler/crystal/semantic/bindings.cr index bba14d9be92b..e2a24f00bdff 100644 --- a/src/compiler/crystal/semantic/bindings.cr +++ b/src/compiler/crystal/semantic/bindings.cr @@ -122,7 +122,7 @@ module Crystal end end - def bind(from = nil) + def bind(from = nil, &) # Quick check to provide a better error message when assigning a type # to a variable whose type is frozen if self.is_a?(MetaTypeVar) && (freeze_type = self.freeze_type) && from && diff --git a/src/compiler/crystal/semantic/call.cr b/src/compiler/crystal/semantic/call.cr index 83fe5f7f88e0..dec1f0bc7dc0 100644 --- a/src/compiler/crystal/semantic/call.cr +++ b/src/compiler/crystal/semantic/call.cr @@ -488,7 +488,7 @@ class Crystal::Call end end - def tuple_indexer_helper(args, arg_types, owner, instance_type, nilable) + def tuple_indexer_helper(args, arg_types, owner, instance_type, nilable, &) index = tuple_indexer_helper_index(args.first, owner, instance_type, nilable) return unless index @@ -559,7 +559,7 @@ class Crystal::Call index end - def named_tuple_indexer_helper(args, arg_types, owner, instance_type, nilable) + def named_tuple_indexer_helper(args, arg_types, owner, instance_type, nilable, &) arg = args.first # Make it work with constants too @@ -754,7 +754,7 @@ class Crystal::Call end end - def in_macro_target + def in_macro_target(&) if with_scope = @with_scope macros = yield with_scope return macros if macros @@ -1099,7 +1099,7 @@ class Crystal::Call context.defining_type.lookup_type?(node, self_type: context.instantiated_type.instance_type, free_vars: context.free_vars, allow_typeof: false) end - def bubbling_exception + def bubbling_exception(&) yield rescue ex : Crystal::CodeError if obj = @obj diff --git a/src/compiler/crystal/semantic/call_error.cr b/src/compiler/crystal/semantic/call_error.cr index 875fd5269380..e62ce819dd88 100644 --- a/src/compiler/crystal/semantic/call_error.cr +++ b/src/compiler/crystal/semantic/call_error.cr @@ -241,7 +241,7 @@ class Crystal::Call end end - private def gather_names_in_all_overloads(call_errors, error_type : T.class) forall T + private def gather_names_in_all_overloads(call_errors, error_type : T.class, &) forall T return unless call_errors.all?(T) call_errors = call_errors.map &.as(T) @@ -379,7 +379,7 @@ class Crystal::Call end end - private def raise_no_overload_matches(node, defs, arg_types, inner_exception) + private def raise_no_overload_matches(node, defs, arg_types, inner_exception, &) error_message = String.build do |str| yield str @@ -977,7 +977,7 @@ class Crystal::Call end end - def check_recursive_splat_call(a_def, args) + def check_recursive_splat_call(a_def, args, &) if a_def.splat_index previous_splat_types = program.splat_expansions[a_def] ||= [] of Type previous_splat_types.push(args.values.last.type) diff --git a/src/compiler/crystal/semantic/cleanup_transformer.cr b/src/compiler/crystal/semantic/cleanup_transformer.cr index 0d7aa41ced5b..0126c62d1166 100644 --- a/src/compiler/crystal/semantic/cleanup_transformer.cr +++ b/src/compiler/crystal/semantic/cleanup_transformer.cr @@ -120,7 +120,7 @@ module Crystal @last_is_falsey = false end - def compute_last_truthiness + def compute_last_truthiness(&) reset_last_status yield {@last_is_truthy, @last_is_falsey} @@ -877,7 +877,7 @@ module Crystal transform_is_a_or_responds_to node, &.filter_by_responds_to(node.name) end - def transform_is_a_or_responds_to(node) + def transform_is_a_or_responds_to(node, &) obj = node.obj if obj_type = obj.type? diff --git a/src/compiler/crystal/semantic/conversions.cr b/src/compiler/crystal/semantic/conversions.cr index 98e014bdb0ec..8c8449441e50 100644 --- a/src/compiler/crystal/semantic/conversions.cr +++ b/src/compiler/crystal/semantic/conversions.cr @@ -33,7 +33,7 @@ module Crystal::Conversions unsafe_call end - def self.try_to_unsafe(target, visitor) + def self.try_to_unsafe(target, visitor, &) unsafe_call = Call.new(target, "to_unsafe").at(target) begin unsafe_call.accept visitor diff --git a/src/compiler/crystal/semantic/cover.cr b/src/compiler/crystal/semantic/cover.cr index 4674d0a12248..b58515737892 100644 --- a/src/compiler/crystal/semantic/cover.cr +++ b/src/compiler/crystal/semantic/cover.cr @@ -178,7 +178,7 @@ module Crystal end class Type - def each_cover + def each_cover(&) yield self end @@ -214,7 +214,7 @@ module Crystal end class UnionType - def each_cover + def each_cover(&) @union_types.each do |union_type| yield union_type end @@ -236,7 +236,7 @@ module Crystal end class VirtualType - def each_cover + def each_cover(&) subtypes.each do |subtype| yield subtype end diff --git a/src/compiler/crystal/semantic/filters.cr b/src/compiler/crystal/semantic/filters.cr index 86938b7e7b77..66d1a728804b 100644 --- a/src/compiler/crystal/semantic/filters.cr +++ b/src/compiler/crystal/semantic/filters.cr @@ -346,7 +346,7 @@ module Crystal new_filters end - def each + def each(&) pos.each do |key, value| yield key, value end diff --git a/src/compiler/crystal/semantic/main_visitor.cr b/src/compiler/crystal/semantic/main_visitor.cr index e3c710134e1e..f92f61589f28 100644 --- a/src/compiler/crystal/semantic/main_visitor.cr +++ b/src/compiler/crystal/semantic/main_visitor.cr @@ -1507,7 +1507,7 @@ module Crystal end end - def check_lib_call_arg(method, arg_index) + def check_lib_call_arg(method, arg_index, &) method_arg = method.args[arg_index]? return unless method_arg @@ -2179,7 +2179,7 @@ module Crystal filter_vars(filters) { |filter| filter } end - def filter_vars(filters) + def filter_vars(filters, &) filters.try &.each do |name, filter| existing_var = @vars[name] filtered_var = MetaVar.new(name) @@ -2249,7 +2249,7 @@ module Crystal @unreachable = true end - def with_block_kind(kind : BlockKind) + def with_block_kind(kind : BlockKind, &) old_block_kind, @last_block_kind = last_block_kind, kind old_inside_ensure, @inside_ensure = @inside_ensure, @inside_ensure || kind.ensure? yield @@ -3011,7 +3011,7 @@ module Crystal expand(node) { @program.literal_expander.expand_named node, generic_type } end - def expand(node) + def expand(node, &) expanded = yield expanded.accept self node.expanded = expanded @@ -3226,7 +3226,7 @@ module Crystal @needs_type_filters > 0 end - def request_type_filters + def request_type_filters(&) @type_filters = nil @needs_type_filters += 1 begin @@ -3236,7 +3236,7 @@ module Crystal end end - def ignoring_type_filters + def ignoring_type_filters(&) needs_type_filters, @needs_type_filters = @needs_type_filters, 0 begin yield diff --git a/src/compiler/crystal/semantic/match.cr b/src/compiler/crystal/semantic/match.cr index f18572f69291..b42c80be7818 100644 --- a/src/compiler/crystal/semantic/match.cr +++ b/src/compiler/crystal/semantic/match.cr @@ -153,7 +153,7 @@ module Crystal end end - def each + def each(&) @success && @matches.try &.each do |match| yield match end diff --git a/src/compiler/crystal/semantic/recursive_struct_checker.cr b/src/compiler/crystal/semantic/recursive_struct_checker.cr index a9c558c6dcad..e7f64913789f 100644 --- a/src/compiler/crystal/semantic/recursive_struct_checker.cr +++ b/src/compiler/crystal/semantic/recursive_struct_checker.cr @@ -183,7 +183,7 @@ class Crystal::RecursiveStructChecker type.struct? && type.is_a?(InstanceVarContainer) && !type.is_a?(PrimitiveType) && !type.is_a?(ProcInstanceType) && !type.abstract? end - def push(path, type) + def push(path, type, &) if path.last? == type yield else diff --git a/src/compiler/crystal/semantic/restrictions.cr b/src/compiler/crystal/semantic/restrictions.cr index 9b7ac5c19613..5eea71ecfb03 100644 --- a/src/compiler/crystal/semantic/restrictions.cr +++ b/src/compiler/crystal/semantic/restrictions.cr @@ -288,7 +288,7 @@ module Crystal end # Yields each pair of corresponding parameters between `self` and *other*. - def each_corresponding_param(other : DefWithMetadata, self_named_args, other_named_args) + def each_corresponding_param(other : DefWithMetadata, self_named_args, other_named_args, &) self_arg_index = 0 other_arg_index = 0 diff --git a/src/compiler/crystal/semantic/semantic_visitor.cr b/src/compiler/crystal/semantic/semantic_visitor.cr index 88164a36f914..62dd21a6092d 100644 --- a/src/compiler/crystal/semantic/semantic_visitor.cr +++ b/src/compiler/crystal/semantic/semantic_visitor.cr @@ -328,7 +328,7 @@ abstract class Crystal::SemanticVisitor < Crystal::Visitor true end - def expand_macro(the_macro, node, mode = nil, *, visibility : Visibility, accept = true) + def expand_macro(the_macro, node, mode = nil, *, visibility : Visibility, accept = true, &) expanded_macro, macro_expansion_pragmas = eval_macro(node) do yield @@ -447,7 +447,7 @@ abstract class Crystal::SemanticVisitor < Crystal::Visitor generated_nodes end - def eval_macro(node) + def eval_macro(node, &) yield rescue ex : MacroRaiseException node.raise ex.message, exception_type: MacroRaiseException @@ -455,7 +455,7 @@ abstract class Crystal::SemanticVisitor < Crystal::Visitor node.raise "expanding macro", ex end - def process_annotations(annotations) + def process_annotations(annotations, &) annotations.try &.each do |ann| annotation_type = lookup_annotation(ann) validate_annotation(annotation_type, ann) @@ -556,7 +556,7 @@ abstract class Crystal::SemanticVisitor < Crystal::Visitor @exp_nest > 0 end - def pushing_type(type : ModuleType) + def pushing_type(type : ModuleType, &) old_type = @current_type @current_type = type read_annotations diff --git a/src/compiler/crystal/semantic/top_level_visitor.cr b/src/compiler/crystal/semantic/top_level_visitor.cr index d92a2d5895d5..c42956a34fba 100644 --- a/src/compiler/crystal/semantic/top_level_visitor.cr +++ b/src/compiler/crystal/semantic/top_level_visitor.cr @@ -1164,7 +1164,7 @@ class Crystal::TopLevelVisitor < Crystal::SemanticVisitor annotations.try(&.first?).try &.doc end - def process_def_annotations(node, annotations) + def process_def_annotations(node, annotations, &) process_annotations(annotations) do |annotation_type, ann| case annotation_type when @program.no_inline_annotation diff --git a/src/compiler/crystal/semantic/type_lookup.cr b/src/compiler/crystal/semantic/type_lookup.cr index 64c3b319cf6e..0db48a0298aa 100644 --- a/src/compiler/crystal/semantic/type_lookup.cr +++ b/src/compiler/crystal/semantic/type_lookup.cr @@ -426,7 +426,7 @@ class Crystal::Type Crystal.check_type_can_be_stored(ident, type, message) end - def in_generic_args + def in_generic_args(&) @in_generic_args += 1 value = yield @in_generic_args -= 1 diff --git a/src/compiler/crystal/semantic/type_merge.cr b/src/compiler/crystal/semantic/type_merge.cr index 0d79faee06b1..d68cdeb38a99 100644 --- a/src/compiler/crystal/semantic/type_merge.cr +++ b/src/compiler/crystal/semantic/type_merge.cr @@ -66,7 +66,7 @@ module Crystal compact_types(types) { |type| type } end - def compact_types(objects) : Array(Type) + def compact_types(objects, &) : Array(Type) all_types = Array(Type).new(objects.size) objects.each { |obj| add_type all_types, yield(obj) } all_types.reject! &.no_return? if all_types.size > 1 diff --git a/src/compiler/crystal/syntax/ast.cr b/src/compiler/crystal/syntax/ast.cr index 859d479bde48..84fe9bb69404 100644 --- a/src/compiler/crystal/syntax/ast.cr +++ b/src/compiler/crystal/syntax/ast.cr @@ -418,11 +418,11 @@ module Crystal def initialize(@elements = [] of ASTNode, @of = nil, @name = nil) end - def self.map(values, of = nil) + def self.map(values, of = nil, &) new(values.map { |value| (yield value).as(ASTNode) }, of: of) end - def self.map_with_index(values) + def self.map_with_index(values, &) new(values.map_with_index { |value, idx| (yield value, idx).as(ASTNode) }, of: nil) end @@ -533,11 +533,11 @@ module Crystal def initialize(@elements) end - def self.map(values) + def self.map(values, &) new(values.map { |value| (yield value).as(ASTNode) }) end - def self.map_with_index(values) + def self.map_with_index(values, &) new(values.map_with_index { |value, idx| (yield value, idx).as(ASTNode) }) end diff --git a/src/compiler/crystal/syntax/lexer.cr b/src/compiler/crystal/syntax/lexer.cr index 008c4ff1f9ee..92e4f1377f01 100644 --- a/src/compiler/crystal/syntax/lexer.cr +++ b/src/compiler/crystal/syntax/lexer.cr @@ -2008,7 +2008,7 @@ module Crystal @token end - def lookahead(preserve_token_on_fail = false) + def lookahead(preserve_token_on_fail = false, &) old_pos, old_line, old_column = current_pos, @line_number, @column_number @temp_token.copy_from(@token) if preserve_token_on_fail @@ -2020,7 +2020,7 @@ module Crystal result end - def peek_ahead + def peek_ahead(&) result = uninitialized typeof(yield) lookahead(preserve_token_on_fail: true) do result = yield @@ -2391,7 +2391,7 @@ module Crystal @token end - def char_to_hex(char) + def char_to_hex(char, &) if '0' <= char <= '9' char - '0' elsif 'a' <= char <= 'f' diff --git a/src/compiler/crystal/syntax/parser.cr b/src/compiler/crystal/syntax/parser.cr index 4e85bc738f84..859c1b138f46 100644 --- a/src/compiler/crystal/syntax/parser.cr +++ b/src/compiler/crystal/syntax/parser.cr @@ -344,7 +344,7 @@ module Crystal atomic end - def parse_expression_suffix(location) + def parse_expression_suffix(location, &) slash_is_regex! next_token_skip_statement_end exp = parse_op_assign_no_control @@ -1226,7 +1226,7 @@ module Crystal end end - def check_type_declaration + def check_type_declaration(&) if next_comes_colon_space? name = @token.value.to_s var = Var.new(name).at(@token.location).at_end(token_end_location) @@ -1321,7 +1321,7 @@ module Crystal type end - def check_not_inside_def(message) + def check_not_inside_def(message, &) if @def_nest == 0 && @fun_nest == 0 yield else @@ -4400,7 +4400,7 @@ module Crystal comes_plus_or_minus end - def preserve_stop_on_do(new_value = false) + def preserve_stop_on_do(new_value = false, &) old_stop_on_do = @stop_on_do @stop_on_do = new_value value = yield @@ -4436,7 +4436,7 @@ module Crystal end end - def parse_block2 + def parse_block2(&) location = @token.location block_params = [] of Var @@ -5177,7 +5177,7 @@ module Crystal named_args end - def parse_type_splat + def parse_type_splat(&) location = @token.location splat = false @@ -6199,7 +6199,7 @@ module Crystal # If *create_scope* is true, creates an isolated variable scope and returns # the yield result, resetting the scope afterwards. Otherwise simply returns # the yield result without touching the scopes. - def with_isolated_var_scope(create_scope = true) + def with_isolated_var_scope(create_scope = true, &) return yield unless create_scope begin @@ -6212,7 +6212,7 @@ module Crystal # Creates a new variable scope with the same variables as the current scope, # and then returns the yield result, resetting the scope afterwards. - def with_lexical_var_scope + def with_lexical_var_scope(&) current_scope = @var_scopes.last.dup @var_scopes.push current_scope yield @@ -6254,7 +6254,7 @@ module Crystal @var_scopes.last.includes? name end - def open(symbol, location = @token.location) + def open(symbol, location = @token.location, &) @unclosed_stack.push Unclosed.new(symbol, location) begin value = yield @@ -6325,7 +6325,7 @@ module Crystal name == "self" || var_in_scope?(name) end - def push_visibility + def push_visibility(&) old_visibility = @visibility @visibility = nil value = yield diff --git a/src/compiler/crystal/syntax/to_s.cr b/src/compiler/crystal/syntax/to_s.cr index 405c21b32159..c6cd759d57dd 100644 --- a/src/compiler/crystal/syntax/to_s.cr +++ b/src/compiler/crystal/syntax/to_s.cr @@ -110,7 +110,7 @@ module Crystal false end - def visit_interpolation(node) + def visit_interpolation(node, &) node.expressions.each do |exp| if exp.is_a?(StringLiteral) @str << yield exp.value @@ -476,7 +476,7 @@ module Crystal end end - def in_parenthesis(need_parens) + def in_parenthesis(need_parens, &) if need_parens @str << '(' yield @@ -1509,7 +1509,7 @@ module Crystal end end - def with_indent + def with_indent(&) @indent += 1 yield @indent -= 1 @@ -1534,13 +1534,13 @@ module Crystal newline end - def inside_macro + def inside_macro(&) @inside_macro += 1 yield @inside_macro -= 1 end - def outside_macro + def outside_macro(&) old_inside_macro = @inside_macro @inside_macro = 0 yield diff --git a/src/compiler/crystal/tools/context.cr b/src/compiler/crystal/tools/context.cr index 5bc6dd43e0e9..5be3a349530e 100644 --- a/src/compiler/crystal/tools/context.cr +++ b/src/compiler/crystal/tools/context.cr @@ -112,7 +112,7 @@ module Crystal @found_untyped_def = false end - def inside_typed_def + def inside_typed_def(&) @inside_typed_def = true yield.tap { @inside_typed_def = false } end diff --git a/src/compiler/crystal/tools/formatter.cr b/src/compiler/crystal/tools/formatter.cr index 5f476d5e1a7a..c9b08363e212 100644 --- a/src/compiler/crystal/tools/formatter.cr +++ b/src/compiler/crystal/tools/formatter.cr @@ -1628,7 +1628,7 @@ module Crystal end end - def format_def_arg(wrote_newline, has_more) + def format_def_arg(wrote_newline, has_more, &) write_indent if wrote_newline yield @@ -4457,7 +4457,7 @@ module Crystal false end - def visit_asm_parts(parts, colon_column) : Nil + def visit_asm_parts(parts, colon_column, &) : Nil write " " column = @column @@ -4776,7 +4776,7 @@ module Crystal end end - def indent + def indent(&) @indent += 2 value = yield @indent -= 2 @@ -4787,7 +4787,7 @@ module Crystal indent { accept node } end - def indent(indent : Int) + def indent(indent : Int, &) old_indent = @indent @indent = indent value = yield @@ -4804,7 +4804,7 @@ module Crystal no_indent { accept node } end - def no_indent + def no_indent(&) old_indent = @indent @indent = 0 yield @@ -4824,7 +4824,7 @@ module Crystal indent(indent, node) end - def write_indent(indent = @indent) + def write_indent(indent = @indent, &) write_indent(indent) indent(indent) { yield } end @@ -5161,13 +5161,13 @@ module Crystal index == collection.size - 1 end - def inside_macro + def inside_macro(&) @inside_macro += 1 yield @inside_macro -= 1 end - def outside_macro + def outside_macro(&) old_inside_macro = @inside_macro @inside_macro = 0 yield @@ -5191,13 +5191,13 @@ module Crystal end end - def inside_cond + def inside_cond(&) @inside_cond += 1 yield @inside_cond -= 1 end - def inside_call_or_assign + def inside_call_or_assign(&) @inside_call_or_assign += 1 yield @inside_call_or_assign -= 1 diff --git a/src/compiler/crystal/tools/playground/agent.cr b/src/compiler/crystal/tools/playground/agent.cr index 8e005a8b1263..265bf6be7214 100644 --- a/src/compiler/crystal/tools/playground/agent.cr +++ b/src/compiler/crystal/tools/playground/agent.cr @@ -8,7 +8,7 @@ class Crystal::Playground::Agent @ws = HTTP::WebSocket.new(URI.parse(url)) end - def i(line, names = nil) + def i(line, names = nil, &) value = begin yield rescue ex @@ -58,7 +58,7 @@ class Crystal::Playground::Agent HTML.escape(value.pretty_inspect) end - private def send(message_type) + private def send(message_type, &) message = JSON.build do |json| json.object do json.field "tag", @tag diff --git a/src/compiler/crystal/tools/playground/agent_instrumentor_transformer.cr b/src/compiler/crystal/tools/playground/agent_instrumentor_transformer.cr index 05ca77bffab7..18c02fbe490a 100644 --- a/src/compiler/crystal/tools/playground/agent_instrumentor_transformer.cr +++ b/src/compiler/crystal/tools/playground/agent_instrumentor_transformer.cr @@ -227,7 +227,7 @@ module Crystal node end - def ignoring_line_of_node(node) + def ignoring_line_of_node(node, &) old_ignore_line = @ignore_line @ignore_line = node.location.try(&.line_number) res = yield diff --git a/src/compiler/crystal/tools/playground/server.cr b/src/compiler/crystal/tools/playground/server.cr index 654d0863faba..56d3779b225a 100644 --- a/src/compiler/crystal/tools/playground/server.cr +++ b/src/compiler/crystal/tools/playground/server.cr @@ -124,7 +124,7 @@ module Crystal::Playground Log.warn { "Unable to send message (session=#{@session_key})." } end - def send_with_json_builder + def send_with_json_builder(&) send(JSON.build do |json| json.object do yield json diff --git a/src/compiler/crystal/tools/print_hierarchy.cr b/src/compiler/crystal/tools/print_hierarchy.cr index 75258dbf058f..b6fcb7a76fdc 100644 --- a/src/compiler/crystal/tools/print_hierarchy.cr +++ b/src/compiler/crystal/tools/print_hierarchy.cr @@ -239,7 +239,7 @@ module Crystal end end - def with_indent + def with_indent(&) @indents.push true yield @indents.pop diff --git a/src/compiler/crystal/tools/table_print.cr b/src/compiler/crystal/tools/table_print.cr index c8e53156289c..2c1846010f57 100644 --- a/src/compiler/crystal/tools/table_print.cr +++ b/src/compiler/crystal/tools/table_print.cr @@ -65,7 +65,7 @@ module Crystal @columns = [] of Column end - def build + def build(&) with self yield self render end @@ -74,7 +74,7 @@ module Crystal @data << Separator.new end - def row + def row(&) @last_string_row = [] of Cell @data << last_string_row with self yield @@ -86,7 +86,7 @@ module Crystal column_for_last_cell.will_render(cell) end - def cell(align : Alignment = :left, colspan = 1) + def cell(align : Alignment = :left, colspan = 1, &) cell(String::Builder.build { |io| yield io }, align, colspan) end diff --git a/src/compiler/crystal/types.cr b/src/compiler/crystal/types.cr index a1cdb71c9d7f..04573c1c65c9 100644 --- a/src/compiler/crystal/types.cr +++ b/src/compiler/crystal/types.cr @@ -751,7 +751,7 @@ module Crystal # Yields self and returns true if the block returns a truthy value. # UnionType overrides it and yields all types in turn and returns # true if for each of them the block returns true. - def all? + def all?(&) (yield self) ? true : false end @@ -1569,7 +1569,7 @@ module Crystal generic_types.values end - def each_instantiated_type + def each_instantiated_type(&) if types = @generic_types types.each_value { |type| yield type } end @@ -2521,7 +2521,7 @@ module Crystal @instantiations.values end - def each_instantiated_type + def each_instantiated_type(&) @instantiations.each_value { |type| yield type } end @@ -3143,7 +3143,7 @@ module Crystal program.type_merge_union_of filtered_types end - def each_concrete_type + def each_concrete_type(&) union_types.each do |type| if type.is_a?(VirtualType) || type.is_a?(VirtualMetaclassType) type.each_concrete_type do |concrete_type| @@ -3209,7 +3209,7 @@ module Crystal union_types.any? &.unbound? end - def all? + def all?(&) union_types.all? { |union_type| yield union_type } end @@ -3389,7 +3389,7 @@ module Crystal @metaclass ||= VirtualMetaclassType.new(program, self) end - def each_concrete_type + def each_concrete_type(&) subtypes.each do |subtype| yield subtype unless subtype.abstract? end @@ -3488,7 +3488,7 @@ module Crystal base_type.replace_type_parameters(instance).virtual_type.metaclass end - def each_concrete_type + def each_concrete_type(&) instance_type.subtypes.each do |type| yield type.metaclass end diff --git a/src/compress/deflate/reader.cr b/src/compress/deflate/reader.cr index cdb84bbe6a18..d4c6d13d21cf 100644 --- a/src/compress/deflate/reader.cr +++ b/src/compress/deflate/reader.cr @@ -33,7 +33,7 @@ class Compress::Deflate::Reader < IO # Creates a new reader from the given *io*, yields it to the given block, # and closes it at its end. - def self.open(io : IO, sync_close : Bool = false, dict : Bytes? = nil) + def self.open(io : IO, sync_close : Bool = false, dict : Bytes? = nil, &) reader = new(io, sync_close: sync_close, dict: dict) yield reader ensure reader.close end @@ -46,7 +46,7 @@ class Compress::Deflate::Reader < IO # Creates an instance of Flate::Reader for the gzip format, yields it to the given block, and closes # it at its end. - def self.gzip(input, sync_close : Bool = false) + def self.gzip(input, sync_close : Bool = false, &) reader = gzip input, sync_close: sync_close yield reader ensure reader.close end diff --git a/src/compress/deflate/writer.cr b/src/compress/deflate/writer.cr index d72ef4586886..f9a5adeb366f 100644 --- a/src/compress/deflate/writer.cr +++ b/src/compress/deflate/writer.cr @@ -32,7 +32,7 @@ class Compress::Deflate::Writer < IO # and closes it at its end. def self.open(io : IO, level : Int32 = Compress::Deflate::DEFAULT_COMPRESSION, strategy : Compress::Deflate::Strategy = Compress::Deflate::Strategy::DEFAULT, - sync_close : Bool = false, dict : Bytes? = nil) + sync_close : Bool = false, dict : Bytes? = nil, &) writer = new(io, level: level, strategy: strategy, sync_close: sync_close, dict: dict) yield writer ensure writer.close end diff --git a/src/compress/gzip/reader.cr b/src/compress/gzip/reader.cr index 56dac99326d9..0371439acf77 100644 --- a/src/compress/gzip/reader.cr +++ b/src/compress/gzip/reader.cr @@ -65,14 +65,14 @@ class Compress::Gzip::Reader < IO # Creates a new reader from the given *io*, yields it to the given block, # and closes it at the end. - def self.open(io : IO, sync_close = false) + def self.open(io : IO, sync_close = false, &) reader = new(io, sync_close: sync_close) yield reader ensure reader.close end # Creates a new reader from the given *filename*, yields it to the given block, # and closes it at the end. - def self.open(filename : String) + def self.open(filename : String, &) reader = new(filename) yield reader ensure reader.close end diff --git a/src/compress/gzip/writer.cr b/src/compress/gzip/writer.cr index 3d82548e2d2c..f02a320805f6 100644 --- a/src/compress/gzip/writer.cr +++ b/src/compress/gzip/writer.cr @@ -50,14 +50,14 @@ class Compress::Gzip::Writer < IO # Creates a new writer to the given *io*, yields it to the given block, # and closes it at the end. - def self.open(io : IO, level = Compress::Gzip::DEFAULT_COMPRESSION, sync_close = false) + def self.open(io : IO, level = Compress::Gzip::DEFAULT_COMPRESSION, sync_close = false, &) writer = new(io, level: level, sync_close: sync_close) yield writer ensure writer.close end # Creates a new writer to the given *filename*, yields it to the given block, # and closes it at the end. - def self.open(filename : String, level = Compress::Gzip::DEFAULT_COMPRESSION) + def self.open(filename : String, level = Compress::Gzip::DEFAULT_COMPRESSION, &) writer = new(filename, level: level) yield writer ensure writer.close end diff --git a/src/compress/zip/file.cr b/src/compress/zip/file.cr index 166626a0b73f..cea1101c9f30 100644 --- a/src/compress/zip/file.cr +++ b/src/compress/zip/file.cr @@ -50,14 +50,14 @@ class Compress::Zip::File # Opens a `Zip::File` for reading from the given *io*, yields # it to the given block, and closes it at the end. - def self.open(io : IO, sync_close = false) + def self.open(io : IO, sync_close = false, &) zip = new io, sync_close yield zip ensure zip.close end # Opens a `Zip::File` for reading from the given *filename*, yields # it to the given block, and closes it at the end. - def self.open(filename : Path | String) + def self.open(filename : Path | String, &) zip = new filename yield zip ensure zip.close end @@ -166,7 +166,7 @@ class Compress::Zip::File # Yields an `IO` to read this entry's contents. # Multiple entries can be opened and read concurrently. - def open + def open(&) @io.read_at(data_offset.to_i32, compressed_size.to_i32) do |io| io = decompressor_for(io, is_sized: true) checksum_reader = ChecksumReader.new(io, filename, verify: crc32) diff --git a/src/compress/zip/reader.cr b/src/compress/zip/reader.cr index 349216f5d14f..e866bf2c0d0e 100644 --- a/src/compress/zip/reader.cr +++ b/src/compress/zip/reader.cr @@ -42,14 +42,14 @@ class Compress::Zip::Reader # Creates a new reader from the given *io*, yields it to the given block, # and closes it at the end. - def self.open(io : IO, sync_close = false) + def self.open(io : IO, sync_close = false, &) reader = new(io, sync_close: sync_close) yield reader ensure reader.close end # Creates a new reader from the given *filename*, yields it to the given block, # and closes it at the end. - def self.open(filename : Path | String) + def self.open(filename : Path | String, &) reader = new(filename) yield reader ensure reader.close end @@ -94,7 +94,7 @@ class Compress::Zip::Reader end # Yields each entry in the zip to the given block. - def each_entry + def each_entry(&) while entry = next_entry yield entry end diff --git a/src/compress/zip/writer.cr b/src/compress/zip/writer.cr index 87d3495c8fb4..52ddee7400a5 100644 --- a/src/compress/zip/writer.cr +++ b/src/compress/zip/writer.cr @@ -51,14 +51,14 @@ class Compress::Zip::Writer # Creates a new writer to the given *io*, yields it to the given block, # and closes it at the end. - def self.open(io : IO, sync_close = false) + def self.open(io : IO, sync_close = false, &) writer = new(io, sync_close: sync_close) yield writer ensure writer.close end # Creates a new writer to the given *filename*, yields it to the given block, # and closes it at the end. - def self.open(filename : Path | String) + def self.open(filename : Path | String, &) writer = new(filename) yield writer ensure writer.close end @@ -66,7 +66,7 @@ class Compress::Zip::Writer # Adds an entry that will have the given *filename* and current # time (`Time.utc`) and yields an `IO` to write that entry's # contents. - def add(filename : Path | String) + def add(filename : Path | String, &) add(Entry.new(filename.to_s)) do |io| yield io end @@ -85,7 +85,7 @@ class Compress::Zip::Writer # # You can also set the Entry's time (which is `Time.utc` by default) # and extra data before adding it to the zip stream. - def add(entry : Entry) + def add(entry : Entry, &) # bit 3: unknown compression size (not needed for STORED, by if left out it doesn't work...) entry.general_purpose_bit_flag |= (1 << 3) # bit 11: require UTF-8 set diff --git a/src/compress/zlib/reader.cr b/src/compress/zlib/reader.cr index 953e313e255a..36c65ca25716 100644 --- a/src/compress/zlib/reader.cr +++ b/src/compress/zlib/reader.cr @@ -22,7 +22,7 @@ class Compress::Zlib::Reader < IO # Creates a new reader from the given *io*, yields it to the given block, # and closes it at the end. - def self.open(io : IO, sync_close = false, dict : Bytes? = nil) + def self.open(io : IO, sync_close = false, dict : Bytes? = nil, &) reader = new(io, sync_close: sync_close, dict: dict) yield reader ensure reader.close end diff --git a/src/compress/zlib/writer.cr b/src/compress/zlib/writer.cr index bb711be40dc0..909123a13d90 100644 --- a/src/compress/zlib/writer.cr +++ b/src/compress/zlib/writer.cr @@ -26,14 +26,14 @@ class Compress::Zlib::Writer < IO # Creates a new writer to the given *io*, yields it to the given block, # and closes it at the end. - def self.open(io : IO, level = Zlib::DEFAULT_COMPRESSION, sync_close = false, dict : Bytes? = nil) + def self.open(io : IO, level = Zlib::DEFAULT_COMPRESSION, sync_close = false, dict : Bytes? = nil, &) writer = new(io, level: level, sync_close: sync_close, dict: dict) yield writer ensure writer.close end # Creates a new writer to the given *filename*, yields it to the given block, # and closes it at the end. - def self.open(filename : String, level = Zlib::DEFAULT_COMPRESSION, dict : Bytes? = nil) + def self.open(filename : String, level = Zlib::DEFAULT_COMPRESSION, dict : Bytes? = nil, &) writer = new(filename, level: level, dict: dict) yield writer ensure writer.close end diff --git a/src/crystal/dwarf/info.cr b/src/crystal/dwarf/info.cr index 884236a1286b..e4799d9af8bd 100644 --- a/src/crystal/dwarf/info.cr +++ b/src/crystal/dwarf/info.cr @@ -54,7 +54,7 @@ module Crystal @abbreviations = Abbrev.read(io, debug_abbrev_offset) end - def each + def each(&) end_offset = @offset + @unit_length attributes = [] of {AT, FORM, Value} diff --git a/src/crystal/elf.cr b/src/crystal/elf.cr index 160ebf379195..365d88fb59b0 100644 --- a/src/crystal/elf.cr +++ b/src/crystal/elf.cr @@ -146,7 +146,7 @@ module Crystal property! shnum : UInt16 property! shstrndx : UInt16 - def self.open(path) + def self.open(path, &) File.open(path, "r") do |file| yield new(file) end @@ -229,7 +229,7 @@ module Crystal # Searches for a section then yield the `SectionHeader` and the IO object # ready for parsing if the section was found. Returns the valure returned by # the block or nil if the section wasn't found. - def read_section?(name : String) + def read_section?(name : String, &) if sh = section_headers.find { |sh| sh_name(sh.name) == name } @io.seek(sh.offset) do yield sh, @io diff --git a/src/crystal/hasher.cr b/src/crystal/hasher.cr index 4d82fdd0330b..d5b6c863d4ca 100644 --- a/src/crystal/hasher.cr +++ b/src/crystal/hasher.cr @@ -155,7 +155,7 @@ struct Crystal::Hasher {x, exp} end - private def float_normalize_wrap(value) + private def float_normalize_wrap(value, &) return HASH_NAN if value.nan? if value.infinite? return value > 0 ? HASH_INF_PLUS : HASH_INF_MINUS diff --git a/src/crystal/iconv.cr b/src/crystal/iconv.cr index 684cca8745f7..64d4e17f8112 100644 --- a/src/crystal/iconv.cr +++ b/src/crystal/iconv.cr @@ -46,7 +46,7 @@ struct Crystal::Iconv end end - def self.new(from : String, to : String, invalid : Symbol? = nil) + def self.new(from : String, to : String, invalid : Symbol? = nil, &) iconv = new(from, to, invalid) begin yield iconv diff --git a/src/crystal/mach_o.cr b/src/crystal/mach_o.cr index 8a5d3a105549..4a51e1e2d38f 100644 --- a/src/crystal/mach_o.cr +++ b/src/crystal/mach_o.cr @@ -90,7 +90,7 @@ module Crystal @stabs : Array(StabEntry)? @symbols : Array(Nlist64)? - def self.open(path) + def self.open(path, &) File.open(path, "r") do |file| yield new(file) end @@ -366,14 +366,14 @@ module Crystal # Seek to the first matching load command, yields, then returns the value of # the block. - private def seek_to(load_command : LoadCommand) + private def seek_to(load_command : LoadCommand, &) seek_to_each(load_command) do |cmd, cmdsize| return yield cmdsize end end # Seek to each matching load command, yielding each of them. - private def seek_to_each(load_command : LoadCommand) : Nil + private def seek_to_each(load_command : LoadCommand, &) : Nil @io.seek(@ldoff) ncmds.times do @@ -498,7 +498,7 @@ module Crystal String.new(bytes.to_unsafe, len) end - def read_section?(name) + def read_section?(name, &) if sh = sections.find { |s| s.sectname == name } @io.seek(sh.offset) do yield sh, @io diff --git a/src/crystal/main.cr b/src/crystal/main.cr index 7ac9f4da0693..fb95c9930fb4 100644 --- a/src/crystal/main.cr +++ b/src/crystal/main.cr @@ -61,7 +61,7 @@ module Crystal end # :nodoc: - def self.ignore_stdio_errors + def self.ignore_stdio_errors(&) yield rescue IO::Error end diff --git a/src/crystal/pointer_linked_list.cr b/src/crystal/pointer_linked_list.cr index b9476210a542..0ce17b071bd0 100644 --- a/src/crystal/pointer_linked_list.cr +++ b/src/crystal/pointer_linked_list.cr @@ -55,7 +55,7 @@ struct Crystal::PointerLinkedList(T) end # Removes and returns head from the list, yields if empty - def shift + def shift(&) unless empty? @head.tap { |t| delete(t) } else @@ -69,7 +69,7 @@ struct Crystal::PointerLinkedList(T) end # Iterates the list. - def each : Nil + def each(&) : Nil return if empty? node = @head diff --git a/src/crystal/spin_lock.cr b/src/crystal/spin_lock.cr index c5939f884d06..f0b4b2df4ab6 100644 --- a/src/crystal/spin_lock.cr +++ b/src/crystal/spin_lock.cr @@ -20,7 +20,7 @@ class Crystal::SpinLock {% end %} end - def sync + def sync(&) lock begin yield @@ -29,7 +29,7 @@ class Crystal::SpinLock end end - def unsync + def unsync(&) unlock begin yield diff --git a/src/crystal/system/thread_linked_list.cr b/src/crystal/system/thread_linked_list.cr index 035ecdee52c8..b6f3ccf65d4e 100644 --- a/src/crystal/system/thread_linked_list.cr +++ b/src/crystal/system/thread_linked_list.cr @@ -15,7 +15,7 @@ class Thread # stop-the-world situations, where a paused thread could have acquired the # lock to push/delete a node, while still being "safe" to iterate (but only # during a stop-the-world). - def unsafe_each : Nil + def unsafe_each(&) : Nil node = @head while node diff --git a/src/crystal/system/unix.cr b/src/crystal/system/unix.cr index 0d6407487a8c..136472b79535 100644 --- a/src/crystal/system/unix.cr +++ b/src/crystal/system/unix.cr @@ -1,6 +1,6 @@ # :nodoc: module Crystal::System - def self.retry_with_buffer(function_name, max_buffer) + def self.retry_with_buffer(function_name, max_buffer, &) initial_buf = uninitialized UInt8[1024] buf = initial_buf diff --git a/src/crystal/system/unix/pthread.cr b/src/crystal/system/unix/pthread.cr index 4af585abe272..bedf2f456aa5 100644 --- a/src/crystal/system/unix/pthread.cr +++ b/src/crystal/system/unix/pthread.cr @@ -16,7 +16,7 @@ class Thread # :nodoc: property previous : Thread? - def self.unsafe_each + def self.unsafe_each(&) threads.unsafe_each { |thread| yield thread } end @@ -44,7 +44,7 @@ class Thread Thread.threads.push(self) end - private def detach + private def detach(&) if @detached.compare_and_set(0, 1).last yield end diff --git a/src/crystal/system/unix/pthread_mutex.cr b/src/crystal/system/unix/pthread_mutex.cr index 41069c02b561..f7b522d8fcdd 100644 --- a/src/crystal/system/unix/pthread_mutex.cr +++ b/src/crystal/system/unix/pthread_mutex.cr @@ -36,7 +36,7 @@ class Thread raise RuntimeError.from_os_error("pthread_mutex_unlock", Errno.new(ret)) unless ret == 0 end - def synchronize + def synchronize(&) lock yield self ensure diff --git a/src/crystal/system/unix/socket.cr b/src/crystal/system/unix/socket.cr index b48f383d5226..277d1c11aeb0 100644 --- a/src/crystal/system/unix/socket.cr +++ b/src/crystal/system/unix/socket.cr @@ -22,7 +22,7 @@ module Crystal::System::Socket {% end %} end - private def system_connect(addr, timeout = nil) + private def system_connect(addr, timeout = nil, &) timeout = timeout.seconds unless timeout.is_a? ::Time::Span | Nil loop do if LibC.connect(fd, addr, addr.size) == 0 @@ -43,13 +43,13 @@ module Crystal::System::Socket # Tries to bind the socket to a local address. # Yields an `Socket::BindError` if the binding failed. - private def system_bind(addr, addrstr) + private def system_bind(addr, addrstr, &) unless LibC.bind(fd, addr, addr.size) == 0 yield ::Socket::BindError.from_errno("Could not bind to '#{addrstr}'") end end - private def system_listen(backlog) + private def system_listen(backlog, &) unless LibC.listen(fd, backlog) == 0 yield ::Socket::Error.from_errno("Listen failed") end @@ -156,7 +156,7 @@ module Crystal::System::Socket val end - private def system_getsockopt(fd, optname, optval, level = LibC::SOL_SOCKET) + private def system_getsockopt(fd, optname, optval, level = LibC::SOL_SOCKET, &) optsize = LibC::SocklenT.new(sizeof(typeof(optval))) ret = LibC.getsockopt(fd, level, optname, pointerof(optval), pointerof(optsize)) yield optval if ret == 0 diff --git a/src/crystal/system/wasi/thread_mutex.cr b/src/crystal/system/wasi/thread_mutex.cr index 0d90bebb67f8..1ff9de139651 100644 --- a/src/crystal/system/wasi/thread_mutex.cr +++ b/src/crystal/system/wasi/thread_mutex.cr @@ -10,7 +10,7 @@ class Thread def unlock end - def synchronize + def synchronize(&) yield end end diff --git a/src/crystal/system/win32/file_descriptor.cr b/src/crystal/system/win32/file_descriptor.cr index 9c065551f0ce..f9c0d525bc72 100644 --- a/src/crystal/system/win32/file_descriptor.cr +++ b/src/crystal/system/win32/file_descriptor.cr @@ -207,7 +207,7 @@ module Crystal::System::FileDescriptor end @[AlwaysInline] - private def system_console_mode(enable, on_mask, off_mask) + private def system_console_mode(enable, on_mask, off_mask, &) windows_handle = self.windows_handle if LibC.GetConsoleMode(windows_handle, out old_mode) == 0 raise IO::Error.from_winerror("GetConsoleMode") diff --git a/src/crystal/system/win32/socket.cr b/src/crystal/system/win32/socket.cr index 8b2adfea6164..339f28648200 100644 --- a/src/crystal/system/win32/socket.cr +++ b/src/crystal/system/win32/socket.cr @@ -92,7 +92,7 @@ module Crystal::System::Socket end end - private def system_connect(addr, timeout = nil) + private def system_connect(addr, timeout = nil, &) if type.stream? system_connect_stream(addr, timeout) { |error| yield error } else @@ -100,7 +100,7 @@ module Crystal::System::Socket end end - private def system_connect_stream(addr, timeout) + private def system_connect_stream(addr, timeout, &) address = LibC::SockaddrIn6.new address.sin6_family = family address.sin6_port = 0 @@ -131,20 +131,20 @@ module Crystal::System::Socket end end - private def system_connect_connectionless(addr, timeout) + private def system_connect_connectionless(addr, timeout, &) ret = LibC.connect(fd, addr, addr.size) if ret == LibC::SOCKET_ERROR yield ::Socket::Error.from_wsa_error("connect") end end - private def system_bind(addr, addrstr) + private def system_bind(addr, addrstr, &) unless LibC.bind(fd, addr, addr.size) == 0 yield ::Socket::BindError.from_errno("Could not bind to '#{addrstr}'") end end - private def system_listen(backlog) + private def system_listen(backlog, &) unless LibC.listen(fd, backlog) == 0 yield ::Socket::Error.from_errno("Listen failed") end @@ -281,7 +281,7 @@ module Crystal::System::Socket val end - def system_getsockopt(handle, optname, optval, level = LibC::SOL_SOCKET) + def system_getsockopt(handle, optname, optval, level = LibC::SOL_SOCKET, &) optsize = sizeof(typeof(optval)) ret = LibC.getsockopt(handle, level, optname, pointerof(optval).as(UInt8*), pointerof(optsize)) diff --git a/src/crystal/system/win32/thread.cr b/src/crystal/system/win32/thread.cr index 5e7ae49b30fc..aeb7a6749b5a 100644 --- a/src/crystal/system/win32/thread.cr +++ b/src/crystal/system/win32/thread.cr @@ -16,7 +16,7 @@ class Thread # :nodoc: property previous : Thread? - def self.unsafe_each + def self.unsafe_each(&) threads.unsafe_each { |thread| yield thread } end @@ -48,7 +48,7 @@ class Thread Thread.threads.push(self) end - private def detach + private def detach(&) if @detached.compare_and_set(0, 1).last yield end diff --git a/src/crystal/system/win32/thread_mutex.cr b/src/crystal/system/win32/thread_mutex.cr index afd4cb1fbdcb..559af6acb4f0 100644 --- a/src/crystal/system/win32/thread_mutex.cr +++ b/src/crystal/system/win32/thread_mutex.cr @@ -43,7 +43,7 @@ class Thread LibC.LeaveCriticalSection(self) end - def synchronize + def synchronize(&) lock yield self ensure diff --git a/src/crystal/system/win32/windows_registry.cr b/src/crystal/system/win32/windows_registry.cr index bd043e0d47bd..19097652415a 100644 --- a/src/crystal/system/win32/windows_registry.cr +++ b/src/crystal/system/win32/windows_registry.cr @@ -22,7 +22,7 @@ module Crystal::System::WindowsRegistry end end - def self.open?(handle : LibC::HKEY, name : Slice(UInt16), sam = LibC::REGSAM::READ) + def self.open?(handle : LibC::HKEY, name : Slice(UInt16), sam = LibC::REGSAM::READ, &) key_handle = open?(handle, name, sam) return unless key_handle diff --git a/src/crystal/system/windows.cr b/src/crystal/system/windows.cr index 5fcbf7a96503..b303d4d61f6d 100644 --- a/src/crystal/system/windows.cr +++ b/src/crystal/system/windows.cr @@ -1,6 +1,6 @@ # :nodoc: module Crystal::System - def self.retry_wstr_buffer + def self.retry_wstr_buffer(&) buffer_arr = uninitialized LibC::WCHAR[256] buffer_size = yield buffer_arr.to_slice, true diff --git a/src/crystal/thread_local_value.cr b/src/crystal/thread_local_value.cr index 776ae16c90de..5d0b8ca3f438 100644 --- a/src/crystal/thread_local_value.cr +++ b/src/crystal/thread_local_value.cr @@ -24,7 +24,7 @@ struct Crystal::ThreadLocalValue(T) end end - def consume_each + def consume_each(&) @mutex.sync do @values.each_value { |t| yield t } @values.clear diff --git a/src/csv.cr b/src/csv.cr index 494931d8f10e..92fdd4f4dd87 100644 --- a/src/csv.cr +++ b/src/csv.cr @@ -94,7 +94,7 @@ class CSV # ["one", "two"] # ["three"] # ``` - def self.each_row(string_or_io : String | IO, separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR) + def self.each_row(string_or_io : String | IO, separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR, &) Parser.new(string_or_io, separator, quote_char).each_row do |row| yield row end @@ -135,7 +135,7 @@ class CSV # ``` # # See: `CSV::Builder::Quoting` - def self.build(separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR, quoting : Builder::Quoting = Builder::Quoting::RFC) : String + def self.build(separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR, quoting : Builder::Quoting = Builder::Quoting::RFC, &) : String String.build do |io| build(io, separator, quote_char, quoting) { |builder| yield builder } end @@ -155,7 +155,7 @@ class CSV # end # io.to_s # => "HEADER\none,two\nthree\n" # ``` - def self.build(io : IO, separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR, quoting : Builder::Quoting = Builder::Quoting::RFC) : Nil + def self.build(io : IO, separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR, quoting : Builder::Quoting = Builder::Quoting::RFC, &) : Nil builder = Builder.new(io, separator, quote_char, quoting) yield builder io.flush @@ -194,7 +194,7 @@ class CSV # Headers are always stripped. # # See `CSV.parse` about the *separator* and *quote_char* arguments. - def self.new(string_or_io : String | IO, headers = false, strip = false, separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR) + def self.new(string_or_io : String | IO, headers = false, strip = false, separator : Char = DEFAULT_SEPARATOR, quote_char : Char = DEFAULT_QUOTE_CHAR, &) csv = new(string_or_io, headers, strip, separator, quote_char) csv.each do yield csv @@ -209,7 +209,7 @@ class CSV end # Invokes the block once for each row in this CSV, yielding `self`. - def each : Nil + def each(&) : Nil while self.next yield self end diff --git a/src/csv/builder.cr b/src/csv/builder.cr index 9a9c1457b263..d0fae5cf6dfe 100644 --- a/src/csv/builder.cr +++ b/src/csv/builder.cr @@ -53,7 +53,7 @@ class CSV::Builder # Yields a `CSV::Row` to append a row. A newline is appended # to `IO` after the block exits. - def row + def row(&) yield Row.new(self, @separator, @quote_char, @quoting) @io << '\n' @first_cell_in_row = true @@ -74,7 +74,7 @@ class CSV::Builder end # :nodoc: - def cell + def cell(&) append_cell do yield @io end @@ -96,7 +96,7 @@ class CSV::Builder end end - private def append_cell + private def append_cell(&) @io << @separator unless @first_cell_in_row yield @first_cell_in_row = false diff --git a/src/csv/parser.cr b/src/csv/parser.cr index ae3ec7c890d8..57491b726dce 100644 --- a/src/csv/parser.cr +++ b/src/csv/parser.cr @@ -20,7 +20,7 @@ class CSV::Parser end # Yields each of the remaining rows as an `Array(String)`. - def each_row : Nil + def each_row(&) : Nil while row = next_row yield row end diff --git a/src/deque.cr b/src/deque.cr index 214e550447a1..938f60d993af 100644 --- a/src/deque.cr +++ b/src/deque.cr @@ -257,7 +257,7 @@ class Deque(T) # `reject!` and `delete` implementation: # returns the last matching element, or nil - private def internal_delete + private def internal_delete(&) match = nil i = 0 while i < @size @@ -439,7 +439,7 @@ class Deque(T) # Removes and returns the last item, if not empty, otherwise executes # the given block and returns its value. - def pop + def pop(&) if @size == 0 yield else @@ -517,7 +517,7 @@ class Deque(T) # Removes and returns the first item, if not empty, otherwise executes # the given block and returns its value. - def shift + def shift(&) if @size == 0 yield else @@ -564,7 +564,7 @@ class Deque(T) self end - private def halfs + private def halfs(&) # For [----] yields nothing # For contiguous [-012] yields 1...4 # For separated [234---01] yields 6...8, 0...3 diff --git a/src/dir/glob.cr b/src/dir/glob.cr index 5d39de127866..38c52253e330 100644 --- a/src/dir/glob.cr +++ b/src/dir/glob.cr @@ -322,7 +322,7 @@ class Dir File.join(path, entry) end - private def self.each_child(path) + private def self.each_child(path, &) Dir.open(path || Dir.current) do |dir| while entry = read_entry(dir) next if entry.name.in?(".", "..") diff --git a/src/enumerable.cr b/src/enumerable.cr index a74e39baa616..5476e2b55433 100644 --- a/src/enumerable.cr +++ b/src/enumerable.cr @@ -10,7 +10,7 @@ # class Three # include Enumerable(Int32) # -# def each +# def each(&) # yield 1 # yield 2 # yield 3 @@ -201,7 +201,7 @@ module Enumerable(T) end end - private def chunks_internal(original_block : T -> U) forall U + private def chunks_internal(original_block : T -> U, &) forall U acc = Chunk::Accumulator(T, U).new each do |val| key = original_block.call(val) @@ -299,7 +299,7 @@ module Enumerable(T) # Chunks of two items can be iterated using `#each_cons_pair`, an optimized # implementation for the special case of `count == 2` which avoids heap # allocations. - def each_cons(count : Int, reuse = false) + def each_cons(count : Int, reuse = false, &) raise ArgumentError.new "Invalid cons size: #{count}" if count <= 0 if reuse.nil? || reuse.is_a?(Bool) # we use an initial capacity of double the count, because a second @@ -310,7 +310,7 @@ module Enumerable(T) end end - private def each_cons_internal(count : Int, reuse, cons) + private def each_cons_internal(count : Int, reuse, cons, &) each do |elem| cons << elem cons.shift if cons.size > count @@ -385,11 +385,11 @@ module Enumerable(T) # # This can be used to prevent many memory allocations when each slice of # interest is to be used in a read-only fashion. - def each_slice(count : Int, reuse = false) + def each_slice(count : Int, reuse = false, &) each_slice_internal(count, Array(T), reuse) { |slice| yield slice } end - private def each_slice_internal(count : Int, type, reuse) + private def each_slice_internal(count : Int, type, reuse, &) if reuse unless reuse.is_a?(Array) reuse = type.new(count) @@ -446,7 +446,7 @@ module Enumerable(T) # User # 1: Alice # User # 2: Bob # ``` - def each_with_index(offset = 0) + def each_with_index(offset = 0, &) i = offset each do |elem| yield elem, i @@ -730,7 +730,7 @@ module Enumerable(T) # [1, 2, 3, 4, 5].reduce { |acc, i| "#{acc}-#{i}" } # => "1-2-3-4-5" # [1].reduce { |acc, i| "#{acc}-#{i}" } # => 1 # ``` - def reduce + def reduce(&) memo = uninitialized typeof(reduce(Enumerable.element_type(self)) { |acc, i| yield acc, i }) found = false @@ -748,7 +748,7 @@ module Enumerable(T) # [1, 2, 3, 4, 5].reduce(10) { |acc, i| acc + i } # => 25 # [1, 2, 3].reduce([] of Int32) { |memo, i| memo.unshift(i) } # => [3, 2, 1] # ``` - def reduce(memo) + def reduce(memo, &) each do |elem| memo = yield memo, elem end @@ -761,7 +761,7 @@ module Enumerable(T) # ``` # ([] of Int32).reduce? { |acc, i| acc + i } # => nil # ``` - def reduce? + def reduce?(&) memo = uninitialized typeof(reduce(Enumerable.element_type(self)) { |acc, i| yield acc, i }) found = false @@ -933,7 +933,7 @@ module Enumerable(T) # (1), (2), (3), (4), (5) # ``` @[Deprecated(%(Use `#join(io : IO, separator = "", & : T, IO ->) instead`))] - def join(separator, io : IO) + def join(separator, io : IO, &) join(io, separator) do |elem, io| yield elem, io end @@ -1763,7 +1763,7 @@ module Enumerable(T) # words.each { |word| word.chars.tally_by(hash, &.downcase) } # hash # => {'c' => 1, 'r' => 2, 'y' => 2, 's' => 1, 't' => 1, 'a' => 1, 'l' => 1, 'u' => 1, 'b' => 1} # ``` - def tally_by(hash) + def tally_by(hash, &) each_with_object(hash) do |item, hash| value = yield item @@ -1939,7 +1939,7 @@ module Enumerable(T) # 2 -- 5 -- 8 # 3 -- nil -- nil # ``` - def zip?(*others : Indexable | Iterable | Iterator) + def zip?(*others : Indexable | Iterable | Iterator, &) Enumerable.zip?(self, others) do |elems| yield elems end diff --git a/src/exception/call_stack/dwarf.cr b/src/exception/call_stack/dwarf.cr index bf5a91c687e8..e8c9e3b98c18 100644 --- a/src/exception/call_stack/dwarf.cr +++ b/src/exception/call_stack/dwarf.cr @@ -45,7 +45,7 @@ struct Exception::CallStack end end - protected def self.parse_function_names_from_dwarf(info, strings, line_strings) + protected def self.parse_function_names_from_dwarf(info, strings, line_strings, &) info.each do |code, abbrev, attributes| next unless abbrev && abbrev.tag.subprogram? name = low_pc = high_pc = nil diff --git a/src/exception/call_stack/mach_o.cr b/src/exception/call_stack/mach_o.cr index 5646511541a7..27902e32b894 100644 --- a/src/exception/call_stack/mach_o.cr +++ b/src/exception/call_stack/mach_o.cr @@ -61,7 +61,7 @@ struct Exception::CallStack # or within a `foo.dSYM` bundle for a program named `foo`. # # See for details. - private def self.locate_dsym_bundle + private def self.locate_dsym_bundle(&) program = Process.executable_path return unless program diff --git a/src/fiber.cr b/src/fiber.cr index 156a318dc58f..c0bf3ae4292d 100644 --- a/src/fiber.cr +++ b/src/fiber.cr @@ -76,7 +76,7 @@ class Fiber end # :nodoc: - def self.unsafe_each + def self.unsafe_each(&) fibers.unsafe_each { |fiber| yield fiber } end diff --git a/src/file.cr b/src/file.cr index cec57c03efae..7551a65f34f7 100644 --- a/src/file.cr +++ b/src/file.cr @@ -659,7 +659,7 @@ class File < IO::FileDescriptor # file as an argument, the file will be automatically closed when the block returns. # # See `self.new` for what *mode* can be. - def self.open(filename : Path | String, mode = "r", perm = DEFAULT_CREATE_PERMISSIONS, encoding = nil, invalid = nil) + def self.open(filename : Path | String, mode = "r", perm = DEFAULT_CREATE_PERMISSIONS, encoding = nil, invalid = nil, &) file = new filename, mode, perm, encoding, invalid begin yield file @@ -703,7 +703,7 @@ class File < IO::FileDescriptor # end # array # => ["foo", "bar"] # ``` - def self.each_line(filename : Path | String, encoding = nil, invalid = nil, chomp = true) + def self.each_line(filename : Path | String, encoding = nil, invalid = nil, chomp = true, &) open(filename, "r", encoding: encoding, invalid: invalid) do |file| file.each_line(chomp: chomp) do |line| yield line diff --git a/src/file/tempfile.cr b/src/file/tempfile.cr index 3d9fb922b2b9..e1b764f35dbf 100644 --- a/src/file/tempfile.cr +++ b/src/file/tempfile.cr @@ -108,7 +108,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, invalid = nil, &) tempfile = tempfile(prefix: prefix, suffix: suffix, dir: dir, encoding: encoding, invalid: invalid) begin yield tempfile @@ -139,7 +139,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, invalid = nil, &) tempfile(prefix: nil, suffix: suffix, dir: dir, encoding: encoding, invalid: invalid) do |tempfile| yield tempfile end diff --git a/src/file_utils.cr b/src/file_utils.cr index d416ed05bff7..21c3041cfc74 100644 --- a/src/file_utils.cr +++ b/src/file_utils.cr @@ -24,7 +24,7 @@ module FileUtils # ``` # # NOTE: Alias of `Dir.cd` with block - def cd(path : Path | String) + def cd(path : Path | String, &) Dir.cd(path) { yield } end diff --git a/src/hash.cr b/src/hash.cr index d29064f57b8c..a8213aa478dd 100644 --- a/src/hash.cr +++ b/src/hash.cr @@ -842,7 +842,7 @@ class Hash(K, V) end # Yields each non-deleted Entry with its index inside `@entries`. - protected def each_entry_with_index : Nil + protected def each_entry_with_index(&) : Nil return if @size == 0 @first.upto(entries_size - 1) do |i| @@ -1012,7 +1012,7 @@ class Hash(K, V) # h.put(1, "uno") { "didn't exist" } # => "one" # h.put(2, "two") { |key| key.to_s } # => "2" # ``` - def put(key : K, value : V) + def put(key : K, value : V, &) updated_entry = upsert(key, value) updated_entry ? updated_entry.value : yield key end @@ -1181,7 +1181,7 @@ class Hash(K, V) # h.fetch("bar") { "default value" } # => "default value" # h.fetch("bar") { |key| key.upcase } # => "BAR" # ``` - def fetch(key) + def fetch(key, &) entry = find_entry(key) entry ? entry.value : yield key end @@ -1227,7 +1227,7 @@ class Hash(K, V) # hash.key_for("bar") { |value| value.upcase } # => "foo" # hash.key_for("qux") { |value| value.upcase } # => "QUX" # ``` - def key_for(value) + def key_for(value, &) each do |k, v| return k if v == value end @@ -1253,7 +1253,7 @@ class Hash(K, V) # h.fetch("foo", nil) # => nil # h.delete("baz") { |key| "#{key} not found" } # => "baz not found" # ``` - def delete(key) + def delete(key, &) entry = delete_impl(key) entry ? entry.value : yield key end @@ -1779,7 +1779,7 @@ class Hash(K, V) # hash.shift { true } # => true # hash # => {} # ``` - def shift + def shift(&) first_entry = first_entry? if first_entry delete_entry_and_update_counts(@first) @@ -2025,7 +2025,7 @@ class Hash(K, V) @index = @hash.@first end - def base_next + def base_next(&) while true if @index < @hash.entries_size entry = @hash.entries[@index] diff --git a/src/http/client.cr b/src/http/client.cr index eeb6300f4f5d..c9b9e1d699da 100644 --- a/src/http/client.cr +++ b/src/http/client.cr @@ -229,7 +229,7 @@ class HTTP::Client # # This constructor will raise an exception if any scheme but HTTP or HTTPS # is used. - def self.new(uri : URI, tls : TLSContext = nil) + def self.new(uri : URI, tls : TLSContext = nil, &) tls = tls_flag(uri, tls) host = validate_host(uri) client = new(host, uri.port, tls) @@ -250,7 +250,7 @@ class HTTP::Client # client.get "/" # end # ``` - def self.new(host : String, port = nil, tls : TLSContext = nil) + def self.new(host : String, port = nil, tls : TLSContext = nil, &) client = new(host, port, tls) begin yield client @@ -651,7 +651,7 @@ class HTTP::Client raise IO::EOFError.new("Unexpected end of http response") end - private def exec_internal_single(request, ignore_io_error = false, implicit_compression = false) + private def exec_internal_single(request, ignore_io_error = false, implicit_compression = false, &) begin send_request(request) rescue ex : IO::Error @@ -663,7 +663,7 @@ class HTTP::Client end end - private def handle_response(response) + private def handle_response(response, &) yield ensure response.body_io?.try &.close @@ -730,7 +730,7 @@ class HTTP::Client # response.body_io.gets # => "..." # end # ``` - def exec(method : String, path, headers : HTTP::Headers? = nil, body : BodyType = nil) + def exec(method : String, path, headers : HTTP::Headers? = nil, body : BodyType = nil, &) exec(new_request(method, path, headers, body)) do |response| yield response end @@ -762,7 +762,7 @@ class HTTP::Client # response.body_io.gets # => "..." # end # ``` - def self.exec(method, url : String | URI, headers : HTTP::Headers? = nil, body : BodyType = nil, tls : TLSContext = nil) + def self.exec(method, url : String | URI, headers : HTTP::Headers? = nil, body : BodyType = nil, tls : TLSContext = nil, &) headers = default_one_shot_headers(headers) exec(url, tls) do |client, path| client.exec(method, path, headers, body) do |response| @@ -821,7 +821,7 @@ class HTTP::Client end end - private def self.exec(string : String, tls : TLSContext = nil) + private def self.exec(string : String, tls : TLSContext = nil, &) uri = URI.parse(string) unless uri.scheme && uri.host @@ -866,7 +866,7 @@ class HTTP::Client raise ArgumentError.new "Request URI must have host (URI is: #{uri})" end - private def self.exec(uri : URI, tls : TLSContext = nil) + private def self.exec(uri : URI, tls : TLSContext = nil, &) tls = tls_flag(uri, tls) host = validate_host(uri) @@ -886,7 +886,7 @@ class HTTP::Client # This method is called when executing the request. Although it can be # redefined, it is recommended to use the `def_around_exec` macro to be # able to add new behaviors without losing prior existing ones. - protected def around_exec(request) + protected def around_exec(request, &) yield end diff --git a/src/http/client/response.cr b/src/http/client/response.cr index da1a797a98f2..cfb03c736127 100644 --- a/src/http/client/response.cr +++ b/src/http/client/response.cr @@ -110,7 +110,7 @@ class HTTP::Client end end - def self.from_io(io, ignore_body = false, decompress = true) + def self.from_io(io, ignore_body = false, decompress = true, &) from_io?(io, ignore_body, decompress) do |response| if response yield response diff --git a/src/http/common.cr b/src/http/common.cr index 5cda70bbfe51..b2139194b045 100644 --- a/src/http/common.cr +++ b/src/http/common.cr @@ -26,7 +26,7 @@ module HTTP record HeaderLine, name : String, value : String, bytesize : Int32 # :nodoc: - def self.parse_headers_and_body(io, body_type : BodyType = BodyType::OnDemand, decompress = true, *, max_headers_size : Int32 = MAX_HEADERS_SIZE) : HTTP::Status? + def self.parse_headers_and_body(io, body_type : BodyType = BodyType::OnDemand, decompress = true, *, max_headers_size : Int32 = MAX_HEADERS_SIZE, &) : HTTP::Status? headers = Headers.new max_size = max_headers_size diff --git a/src/http/cookie.cr b/src/http/cookie.cr index f6199cf42484..5b672ca2238a 100644 --- a/src/http/cookie.cr +++ b/src/http/cookie.cr @@ -225,7 +225,7 @@ module HTTP CookieString = /(?:^|; )#{Regex::CookiePair}/ SetCookieString = /^#{Regex::CookiePair}(?:;\s*#{Regex::CookieAV})*$/ - def parse_cookies(header) + def parse_cookies(header, &) header.scan(CookieString).each do |pair| value = pair["value"] if value.starts_with?('"') diff --git a/src/http/formdata.cr b/src/http/formdata.cr index ca26eb01c715..433ee494b3de 100644 --- a/src/http/formdata.cr +++ b/src/http/formdata.cr @@ -90,7 +90,7 @@ module HTTP::FormData # ``` # # See: `FormData::Parser` - def self.parse(io, boundary) + def self.parse(io, boundary, &) parser = Parser.new(io, boundary) while parser.has_next? parser.next { |part| yield part } @@ -113,7 +113,7 @@ module HTTP::FormData # ``` # # See: `FormData::Parser` - def self.parse(request : HTTP::Request) + def self.parse(request : HTTP::Request, &) body = request.body raise Error.new "Cannot extract form-data from HTTP request: body is empty" unless body @@ -186,7 +186,7 @@ module HTTP::FormData # ``` # # See: `FormData::Builder` - def self.build(io, boundary = MIME::Multipart.generate_boundary) + def self.build(io, boundary = MIME::Multipart.generate_boundary, &) builder = Builder.new(io, boundary) yield builder builder.finish @@ -212,7 +212,7 @@ module HTTP::FormData # ``` # # See: `FormData::Builder` - def self.build(response : HTTP::Server::Response, boundary = MIME::Multipart.generate_boundary) + def self.build(response : HTTP::Server::Response, boundary = MIME::Multipart.generate_boundary, &) builder = Builder.new(response, boundary) yield builder builder.finish diff --git a/src/http/formdata/parser.cr b/src/http/formdata/parser.cr index e93f2b029e6c..9aec54f1a64e 100644 --- a/src/http/formdata/parser.cr +++ b/src/http/formdata/parser.cr @@ -27,7 +27,7 @@ module HTTP::FormData # part.headers["Content-Type"] # => "text/plain" # end # ``` - def next + def next(&) raise FormData::Error.new("Parser has already finished parsing") unless has_next? while @multipart.has_next? diff --git a/src/http/headers.cr b/src/http/headers.cr index 97cdcf95ab8b..f3ad07d402c5 100644 --- a/src/http/headers.cr +++ b/src/http/headers.cr @@ -146,7 +146,7 @@ struct HTTP::Headers fetch(wrap(key)) { default } end - def fetch(key) + def fetch(key, &) values = @hash[wrap(key)]? values ? concat(values) : yield key end @@ -227,7 +227,7 @@ struct HTTP::Headers result.hash(hasher) end - def each + def each(&) @hash.each do |key, value| yield({key.name, cast(value)}) end diff --git a/src/http/server/handlers/static_file_handler.cr b/src/http/server/handlers/static_file_handler.cr index 8b4041903aed..d38b462e7a3e 100644 --- a/src/http/server/handlers/static_file_handler.cr +++ b/src/http/server/handlers/static_file_handler.cr @@ -146,7 +146,7 @@ class HTTP::StaticFileHandler end record DirectoryListing, request_path : String, path : String do - def each_entry + def each_entry(&) Dir.each_child(path) do |entry| yield entry end diff --git a/src/http/web_socket.cr b/src/http/web_socket.cr index 6516dee2bbb8..9359c6c194bf 100644 --- a/src/http/web_socket.cr +++ b/src/http/web_socket.cr @@ -98,7 +98,7 @@ class HTTP::WebSocket @ws.pong(message) end - def stream(binary = true, frame_size = 1024) + def stream(binary = true, frame_size = 1024, &) check_open @ws.stream(binary: binary, frame_size: frame_size) do |io| yield io diff --git a/src/http/web_socket/protocol.cr b/src/http/web_socket/protocol.cr index 307ff74be24b..2ae1c9e81ce9 100644 --- a/src/http/web_socket/protocol.cr +++ b/src/http/web_socket/protocol.cr @@ -94,7 +94,7 @@ class HTTP::WebSocket::Protocol send(data, Opcode::BINARY) end - def stream(binary = true, frame_size = 1024) + def stream(binary = true, frame_size = 1024, &) stream_io = StreamIO.new(self, binary, frame_size) yield(stream_io) stream_io.flush diff --git a/src/humanize.cr b/src/humanize.cr index 73974b6448df..76f4fc3b2a12 100644 --- a/src/humanize.cr +++ b/src/humanize.cr @@ -260,7 +260,7 @@ struct Number end # :ditto: - def humanize(precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true) : String + def humanize(precision = 3, separator = '.', delimiter = ',', *, base = 10 ** 3, significant = true, &) : String String.build do |io| humanize(io, precision, separator, delimiter, base: base, significant: significant) do |magnitude, number| yield magnitude, number diff --git a/src/indexable.cr b/src/indexable.cr index f47c5ab441c2..ce493eec2001 100644 --- a/src/indexable.cr +++ b/src/indexable.cr @@ -34,7 +34,7 @@ module Indexable(T) # a.fetch(2) { :default_value } # => :default_value # a.fetch(2) { |index| index * 3 } # => 6 # ``` - def fetch(index : Int) + def fetch(index : Int, &) index = check_index_out_of_bounds(index) do return yield index end @@ -595,7 +595,7 @@ module Indexable(T) # ```text # 2 -- 3 -- # ``` - def each_index(*, start : Int, count : Int) + def each_index(*, start : Int, count : Int, &) # We cannot use `normalize_start_and_count` here because `self` may be # mutated to contain enough elements during iteration even if there weren't # initially `count` elements. @@ -720,7 +720,7 @@ module Indexable(T) # a.equals?(b) { |x, y| x == y.size } # => true # a.equals?(b) { |x, y| x == y } # => false # ``` - def equals?(other) + def equals?(other, &) return false if size != other.size each_with_index do |item, i| return false unless yield(item, other[i]) @@ -729,7 +729,7 @@ module Indexable(T) end # :inherited: - def first + def first(&) size == 0 ? yield : unsafe_fetch(0) end @@ -809,7 +809,7 @@ module Indexable(T) # ([1, 2, 3]).last { 4 } # => 3 # ([] of Int32).last { 4 } # => 4 # ``` - def last + def last(&) size == 0 ? yield : unsafe_fetch(size - 1) end @@ -928,7 +928,7 @@ module Indexable(T) check_index_out_of_bounds(index) { raise IndexError.new } end - private def check_index_out_of_bounds(index) + private def check_index_out_of_bounds(index, &) index += size if index < 0 if 0 <= index < size index @@ -941,12 +941,12 @@ module Indexable(T) Indexable.normalize_start_and_count(start, count, size) end - private def normalize_start_and_count(start, count) + private def normalize_start_and_count(start, count, &) Indexable.normalize_start_and_count(start, count, size) { yield } end # :nodoc: - def self.normalize_start_and_count(start, count, collection_size) + def self.normalize_start_and_count(start, count, collection_size, &) raise ArgumentError.new "Negative count: #{count}" if count < 0 start += collection_size if start < 0 if 0 <= start <= collection_size @@ -1021,7 +1021,7 @@ module Indexable(T) # the method will create a new array and reuse it. This can be # used to prevent many memory allocations when each slice of # interest is to be used in a read-only fashion. - def each_permutation(size : Int = self.size, reuse = false) : Nil + def each_permutation(size : Int = self.size, reuse = false, &) : Nil n = self.size return if size > n @@ -1114,7 +1114,7 @@ module Indexable(T) # the method will create a new array and reuse it. This can be # used to prevent many memory allocations when each slice of # interest is to be used in a read-only fashion. - def each_combination(size : Int = self.size, reuse = false) : Nil + def each_combination(size : Int = self.size, reuse = false, &) : Nil n = self.size return if size > n raise ArgumentError.new("Size must be positive") if size < 0 @@ -1224,7 +1224,7 @@ module Indexable(T) # the method will create a new array and reuse it. This can be # used to prevent many memory allocations when each slice of # interest is to be used in a read-only fashion. - def each_repeated_combination(size : Int = self.size, reuse = false) : Nil + def each_repeated_combination(size : Int = self.size, reuse = false, &) : Nil n = self.size return if size > n && n == 0 raise ArgumentError.new("Size must be positive") if size < 0 diff --git a/src/int.cr b/src/int.cr index 7de873b9c008..8ede6465cd03 100644 --- a/src/int.cr +++ b/src/int.cr @@ -728,7 +728,7 @@ struct Int end end - private def internal_to_s(base, precision, upcase = false) + private def internal_to_s(base, precision, upcase = false, &) # Given sizeof(self) <= 128 bits, we need at most 128 bytes for a base 2 # representation, plus one byte for the negative sign (possibly used by the # string-returning overload). diff --git a/src/io.cr b/src/io.cr index 54162972af1f..7197f0b8316c 100644 --- a/src/io.cr +++ b/src/io.cr @@ -152,7 +152,7 @@ abstract class IO # reader.gets # => "world" # end # ``` - def self.pipe(read_blocking = false, write_blocking = false) + def self.pipe(read_blocking = false, write_blocking = false, &) r, w = IO.pipe(read_blocking, write_blocking) begin yield r, w @@ -976,7 +976,7 @@ abstract class IO # あ # め # ``` - def each_char : Nil + def each_char(&) : Nil while char = read_char yield char end @@ -1011,7 +1011,7 @@ abstract class IO # 129 # 130 # ``` - def each_byte : Nil + def each_byte(&) : Nil while byte = read_byte yield byte end diff --git a/src/io/evented.cr b/src/io/evented.cr index c9ba8fa273e7..c490f3b5939f 100644 --- a/src/io/evented.cr +++ b/src/io/evented.cr @@ -47,7 +47,7 @@ module IO::Evented write_timeout end - def evented_read(slice : Bytes, errno_msg : String) : Int32 + def evented_read(slice : Bytes, errno_msg : String, &) : Int32 loop do bytes_read = yield slice if bytes_read != -1 @@ -65,7 +65,7 @@ module IO::Evented resume_pending_readers end - def evented_write(slice : Bytes, errno_msg : String) : Nil + def evented_write(slice : Bytes, errno_msg : String, &) : Nil return if slice.empty? begin @@ -88,7 +88,7 @@ module IO::Evented end end - def evented_send(slice : Bytes, errno_msg : String) : Int32 + def evented_send(slice : Bytes, errno_msg : String, &) : Int32 bytes_written = yield slice raise Socket::Error.from_errno(errno_msg) if bytes_written == -1 # `to_i32` is acceptable because `Slice#size` is an Int32 @@ -121,7 +121,7 @@ module IO::Evented end # :nodoc: - def wait_readable(timeout = @read_timeout, *, raise_if_closed = true) : Nil + def wait_readable(timeout = @read_timeout, *, raise_if_closed = true, &) : Nil readers = @readers.get { Deque(Fiber).new } readers << Fiber.current add_read_event(timeout) @@ -146,7 +146,7 @@ module IO::Evented end # :nodoc: - def wait_writable(timeout = @write_timeout) : Nil + def wait_writable(timeout = @write_timeout, &) : Nil writers = @writers.get { Deque(Fiber).new } writers << Fiber.current add_write_event(timeout) diff --git a/src/io/file_descriptor.cr b/src/io/file_descriptor.cr index ecbcc6cebf88..2f6cf02ec4a0 100644 --- a/src/io/file_descriptor.cr +++ b/src/io/file_descriptor.cr @@ -118,7 +118,7 @@ class IO::FileDescriptor < IO # Same as `seek` but yields to the block after seeking and eventually seeks # back to the original position when the block returns. - def seek(offset, whence : Seek = Seek::Set) + def seek(offset, whence : Seek = Seek::Set, &) original_pos = tell begin seek(offset, whence) @@ -176,7 +176,7 @@ class IO::FileDescriptor < IO # TODO: use fcntl/lockf instead of flock (which doesn't lock over NFS) - def flock_shared(blocking = true) + def flock_shared(blocking = true, &) flock_shared blocking begin yield @@ -191,7 +191,7 @@ class IO::FileDescriptor < IO system_flock_shared(blocking) end - def flock_exclusive(blocking = true) + def flock_exclusive(blocking = true, &) flock_exclusive blocking begin yield diff --git a/src/io/overlapped.cr b/src/io/overlapped.cr index 75570feae1a8..011b25b06398 100644 --- a/src/io/overlapped.cr +++ b/src/io/overlapped.cr @@ -38,19 +38,19 @@ module IO::Overlapped write_timeout end - def overlapped_write(socket, method) + def overlapped_write(socket, method, &) overlapped_operation(socket, method, write_timeout) do |operation| yield operation end end - def overlapped_read(socket, method) + def overlapped_read(socket, method, &) overlapped_operation(socket, method, read_timeout) do |operation| yield operation end end - def self.wait_queued_completions(timeout) + def self.wait_queued_completions(timeout, &) overlapped_entries = uninitialized LibC::OVERLAPPED_ENTRY[1] if timeout > UInt64::MAX @@ -94,7 +94,7 @@ module IO::Overlapped property previous : OverlappedOperation? @@canceled = Thread::LinkedList(OverlappedOperation).new - def self.run(socket) + def self.run(socket, &) operation = OverlappedOperation.new begin yield operation @@ -103,7 +103,7 @@ module IO::Overlapped end end - def self.schedule(overlapped : LibC::WSAOVERLAPPED*) + def self.schedule(overlapped : LibC::WSAOVERLAPPED*, &) start = overlapped.as(Pointer(UInt8)) - offsetof(OverlappedOperation, @overlapped) operation = Box(OverlappedOperation).unbox(start.as(Pointer(Void))) operation.schedule { |fiber| yield fiber } @@ -116,7 +116,7 @@ module IO::Overlapped pointerof(@overlapped) end - def result(socket) + def result(socket, &) raise Exception.new("Invalid state #{@state}") unless @state.done? || @state.started? flags = 0_u32 result = LibC.WSAGetOverlappedResult(socket, pointerof(@overlapped), out bytes, false, pointerof(flags)) @@ -130,7 +130,7 @@ module IO::Overlapped bytes end - protected def schedule + protected def schedule(&) case @state when .started? yield @fiber.not_nil! @@ -170,7 +170,7 @@ module IO::Overlapped Crystal::Scheduler.event_loop.dequeue(timeout_event) end - def overlapped_operation(socket, method, timeout, connreset_is_error = true) + def overlapped_operation(socket, method, timeout, connreset_is_error = true, &) OverlappedOperation.run(socket) do |operation| result = yield operation.start @@ -195,7 +195,7 @@ module IO::Overlapped end end - def overlapped_connect(socket, method) + def overlapped_connect(socket, method, &) OverlappedOperation.run(socket) do |operation| yield operation.start @@ -215,7 +215,7 @@ module IO::Overlapped end end - def overlapped_accept(socket, method) + def overlapped_accept(socket, method, &) OverlappedOperation.run(socket) do |operation| yield operation.start diff --git a/src/io/stapled.cr b/src/io/stapled.cr index 774873476fb6..2dfcd4c6ed08 100644 --- a/src/io/stapled.cr +++ b/src/io/stapled.cr @@ -107,7 +107,7 @@ class IO::Stapled < IO # # Both endpoints and the underlying `IO`s are closed after the block # (even if `sync_close?` is `false`). - def self.pipe(read_blocking : Bool = false, write_blocking : Bool = false) + def self.pipe(read_blocking : Bool = false, write_blocking : Bool = false, &) IO.pipe(read_blocking, write_blocking) do |a_read, a_write| IO.pipe(read_blocking, write_blocking) do |b_read, b_write| a, b = new(a_read, b_write, true), new(b_read, a_write, true) diff --git a/src/iterator.cr b/src/iterator.cr index 3cc614a84194..6bcc926b50d0 100644 --- a/src/iterator.cr +++ b/src/iterator.cr @@ -1314,7 +1314,7 @@ module Iterator(T) end # Yields each element in this iterator together with its index. - def with_index(offset : Int = 0) + def with_index(offset : Int = 0, &) index = offset each do |value| yield value, index diff --git a/src/json/builder.cr b/src/json/builder.cr index 9f7a97c50673..893970e31f1c 100644 --- a/src/json/builder.cr +++ b/src/json/builder.cr @@ -56,7 +56,7 @@ class JSON::Builder flush end - def document + def document(&) start_document yield.tap { end_document } end @@ -187,7 +187,7 @@ class JSON::Builder # Writes the start of an array, invokes the block, # and the writes the end of it. - def array + def array(&) start_array yield.tap { end_array } end @@ -219,7 +219,7 @@ class JSON::Builder # Writes the start of an object, invokes the block, # and the writes the end of it. - def object + def object(&) start_object yield.tap { end_object } end @@ -255,7 +255,7 @@ class JSON::Builder # Writes an object's field and then invokes the block. # This is equivalent of invoking `string(value)` and then # invoking the block. - def field(name) + def field(name, &) string(name) yield end @@ -290,7 +290,7 @@ class JSON::Builder state.is_a?(ObjectState) && state.name end - private def scalar(string = false) + private def scalar(string = false, &) start_scalar(string) yield.tap { end_scalar(string) } end @@ -400,7 +400,7 @@ module JSON # end # string # => %<{"name":"foo","values":[1,2,3]}> # ``` - def self.build(indent = nil) + def self.build(indent = nil, &) String.build do |str| build(str, indent) do |json| yield json @@ -409,7 +409,7 @@ module JSON end # Writes JSON into the given `IO`. A `JSON::Builder` is yielded to the block. - def self.build(io : IO, indent = nil) : Nil + def self.build(io : IO, indent = nil, &) : Nil builder = JSON::Builder.new(io) builder.indent = indent if indent builder.document do diff --git a/src/json/from_json.cr b/src/json/from_json.cr index 13d8e066a444..08e870b5122a 100644 --- a/src/json/from_json.cr +++ b/src/json/from_json.cr @@ -50,7 +50,7 @@ end # ``` # # To parse and get an `Array`, use the block-less overload. -def Array.from_json(string_or_io) : Nil +def Array.from_json(string_or_io, &) : Nil parser = JSON::PullParser.new(string_or_io) new(parser) do |element| yield element @@ -58,7 +58,7 @@ def Array.from_json(string_or_io) : Nil nil end -def Deque.from_json(string_or_io) : Nil +def Deque.from_json(string_or_io, &) : Nil parser = JSON::PullParser.new(string_or_io) new(parser) do |element| yield element @@ -204,7 +204,7 @@ def Array.new(pull : JSON::PullParser) ary end -def Array.new(pull : JSON::PullParser) +def Array.new(pull : JSON::PullParser, &) pull.read_array do yield T.new(pull) end @@ -218,7 +218,7 @@ def Deque.new(pull : JSON::PullParser) ary end -def Deque.new(pull : JSON::PullParser) +def Deque.new(pull : JSON::PullParser, &) pull.read_array do yield T.new(pull) end diff --git a/src/json/lexer.cr b/src/json/lexer.cr index 6769a0f91657..3e61179b9844 100644 --- a/src/json/lexer.cr +++ b/src/json/lexer.cr @@ -146,7 +146,7 @@ abstract class JSON::Lexer consume_string_with_buffer { } end - private def consume_string_with_buffer + private def consume_string_with_buffer(&) @buffer.clear yield while true diff --git a/src/json/parser.cr b/src/json/parser.cr index 37a9ded44cae..865dcd124459 100644 --- a/src/json/parser.cr +++ b/src/json/parser.cr @@ -125,7 +125,7 @@ class JSON::Parser raise ParseException.new(msg, token.line_number, token.column_number) end - private def nest + private def nest(&) @nest += 1 if @nest > @max_nesting parse_exception "Nesting of #{@nest} is too deep" diff --git a/src/json/pull_parser.cr b/src/json/pull_parser.cr index 482e17c01108..4716c7f8f79e 100644 --- a/src/json/pull_parser.cr +++ b/src/json/pull_parser.cr @@ -154,7 +154,7 @@ class JSON::PullParser # You have to consumes the values, if any, so the pull parser does not fail when reading the end of the array. # # If the array is empty, it does not yield. - def read_array + def read_array(&) read_begin_array until kind.end_array? yield @@ -185,7 +185,7 @@ class JSON::PullParser # You have to consumes the values, if any, so the pull parser does not fail when reading the end of the object. # # If the object is empty, it does not yield. - def read_object + def read_object(&) read_begin_object until kind.end_object? key_location = location @@ -332,17 +332,17 @@ class JSON::PullParser end # Reads an array or a null value, and returns it. - def read_array_or_null + def read_array_or_null(&) read_null_or { read_array { yield } } end # Reads an object or a null value, and returns it. - def read_object_or_null + def read_object_or_null(&) read_null_or { read_object { |key| yield key } } end # Reads a null value and returns it, or executes the given block if the value is not null. - def read_null_or + def read_null_or(&) if @kind.null? read_next nil diff --git a/src/kernel.cr b/src/kernel.cr index 154ef5df3d84..fe7595ddcc96 100644 --- a/src/kernel.cr +++ b/src/kernel.cr @@ -98,7 +98,7 @@ ARGF = IO::ARGF.new(ARGV, STDIN) # # ... # end # ``` -def loop +def loop(&) while true yield end diff --git a/src/levenshtein.cr b/src/levenshtein.cr index 2a7eb805b85d..571e0ab830e6 100644 --- a/src/levenshtein.cr +++ b/src/levenshtein.cr @@ -108,7 +108,7 @@ module Levenshtein @best_entry.try &.value end - def self.find(name, tolerance = nil) + def self.find(name, tolerance = nil, &) sn = new name, tolerance yield sn sn.best_match @@ -137,7 +137,7 @@ module Levenshtein # end # best_match # => "ello" # ``` - def self.find(name, tolerance = nil) + def self.find(name, tolerance = nil, &) Finder.find(name, tolerance) do |sn| yield sn end diff --git a/src/llvm/abi/x86_64.cr b/src/llvm/abi/x86_64.cr index 418c8f672eea..e1e996f178e7 100644 --- a/src/llvm/abi/x86_64.cr +++ b/src/llvm/abi/x86_64.cr @@ -44,7 +44,7 @@ class LLVM::ABI::X86_64 < LLVM::ABI # returns the LLVM type (with attributes) and the number of integer and SSE # registers needed to pass this value directly (ie. not using the stack) - def x86_64_type(type, ind_attr, context) : Tuple(ArgType, Int32, Int32) + def x86_64_type(type, ind_attr, context, &) : Tuple(ArgType, Int32, Int32) if int_register?(type) attr = type == context.int1 ? Attribute::ZExt : nil {ArgType.direct(type, attr: attr), 1, 0} diff --git a/src/llvm/basic_block_collection.cr b/src/llvm/basic_block_collection.cr index ba5b961f3a8b..a6218a015d83 100644 --- a/src/llvm/basic_block_collection.cr +++ b/src/llvm/basic_block_collection.cr @@ -11,7 +11,7 @@ struct LLVM::BasicBlockCollection BasicBlock.new LibLLVM.append_basic_block_in_context(context, @function, name) end - def append(name = "") + def append(name = "", &) context = LibLLVM.get_module_context(LibLLVM.get_global_parent(@function)) block = append name # builder = Builder.new(LibLLVM.create_builder_in_context(context), LLVM::Context.new(context, dispose_on_finalize: false)) @@ -21,7 +21,7 @@ struct LLVM::BasicBlockCollection block end - def each : Nil + def each(&) : Nil bb = LibLLVM.get_first_basic_block(@function) while bb yield LLVM::BasicBlock.new bb diff --git a/src/llvm/context.cr b/src/llvm/context.cr index 4e8a986c1155..d349e3045bf0 100644 --- a/src/llvm/context.cr +++ b/src/llvm/context.cr @@ -68,7 +68,7 @@ class LLVM::Context int8.pointer end - def struct(name : String, packed = false) : Type + def struct(name : String, packed = false, &) : Type llvm_struct = LibLLVM.struct_create_named(self, name) the_struct = Type.new llvm_struct element_types = (yield the_struct).as(Array(LLVM::Type)) diff --git a/src/llvm/function_collection.cr b/src/llvm/function_collection.cr index d4e6663fb2d4..a7fcc7cbfcd7 100644 --- a/src/llvm/function_collection.cr +++ b/src/llvm/function_collection.cr @@ -10,7 +10,7 @@ struct LLVM::FunctionCollection Function.new(func) end - def add(name, arg_types : Array(LLVM::Type), ret_type, varargs = false) + def add(name, arg_types : Array(LLVM::Type), ret_type, varargs = false, &) func = add(name, arg_types, ret_type, varargs) yield func func @@ -26,7 +26,7 @@ struct LLVM::FunctionCollection func ? Function.new(func) : nil end - def each : Nil + def each(&) : Nil f = LibLLVM.get_first_function(@mod) while f yield LLVM::Function.new f diff --git a/src/llvm/function_pass_manager.cr b/src/llvm/function_pass_manager.cr index 834d72a20966..50095838626e 100644 --- a/src/llvm/function_pass_manager.cr +++ b/src/llvm/function_pass_manager.cr @@ -12,7 +12,7 @@ class LLVM::FunctionPassManager changed end - def run + def run(&) LibLLVM.initialize_function_pass_manager(self) runner = Runner.new(self) diff --git a/src/llvm/instruction_collection.cr b/src/llvm/instruction_collection.cr index 81f0993bddc7..a442c4b74753 100644 --- a/src/llvm/instruction_collection.cr +++ b/src/llvm/instruction_collection.cr @@ -8,7 +8,7 @@ struct LLVM::InstructionCollection first?.nil? end - def each : Nil + def each(&) : Nil inst = LibLLVM.get_first_instruction @basic_block while inst diff --git a/src/llvm/jit_compiler.cr b/src/llvm/jit_compiler.cr index b881e06ee8d7..ee0c92803102 100644 --- a/src/llvm/jit_compiler.cr +++ b/src/llvm/jit_compiler.cr @@ -12,7 +12,7 @@ class LLVM::JITCompiler @finalized = false end - def self.new(mod) + def self.new(mod, &) jit = new(mod) yield jit ensure jit.dispose end diff --git a/src/llvm/module.cr b/src/llvm/module.cr index f39e672d81fa..162422b752e9 100644 --- a/src/llvm/module.cr +++ b/src/llvm/module.cr @@ -128,7 +128,7 @@ class LLVM::Module @unwrap end - def take_ownership + def take_ownership(&) if @owned yield else diff --git a/src/llvm/pass_builder_options.cr b/src/llvm/pass_builder_options.cr index 955fd4287527..3134acb0b93a 100644 --- a/src/llvm/pass_builder_options.cr +++ b/src/llvm/pass_builder_options.cr @@ -6,7 +6,7 @@ class LLVM::PassBuilderOptions @disposed = false end - def self.new + def self.new(&) options = new begin yield options diff --git a/src/llvm/target.cr b/src/llvm/target.cr index 06ba42c6950a..53bae819296b 100644 --- a/src/llvm/target.cr +++ b/src/llvm/target.cr @@ -1,5 +1,5 @@ struct LLVM::Target - def self.each + def self.each(&) target = LibLLVM.get_first_target while target yield Target.new target diff --git a/src/log/builder.cr b/src/log/builder.cr index 4201a436f656..7be6f10285d3 100644 --- a/src/log/builder.cr +++ b/src/log/builder.cr @@ -84,7 +84,7 @@ class Log::Builder end # :nodoc: - private def each_log + private def each_log(&) @logs.reject! { |_, log_ref| log_ref.value.nil? } @logs.each_value do |log_ref| diff --git a/src/log/main.cr b/src/log/main.cr index b2adecaee1bb..3ff86e169ba4 100644 --- a/src/log/main.cr +++ b/src/log/main.cr @@ -93,7 +93,7 @@ class Log # end # Log.info { %(message with {"a" => 1} context) } # ``` - def self.with_context(**kwargs) + def self.with_context(**kwargs, &) previous = Log.context Log.context.set(**kwargs) unless kwargs.empty? begin @@ -104,7 +104,7 @@ class Log end # :ditto: - def self.with_context(values) + def self.with_context(values, &) previous = Log.context Log.context.set(values) unless values.empty? begin @@ -115,14 +115,14 @@ class Log end # :ditto: - def with_context(**kwargs) + def with_context(**kwargs, &) self.class.with_context(**kwargs) do yield end end # :ditto: - def with_context(values) + def with_context(values, &) self.class.with_context(values) do yield end diff --git a/src/log/metadata.cr b/src/log/metadata.cr index 9ddada2198dd..258b1b817c52 100644 --- a/src/log/metadata.cr +++ b/src/log/metadata.cr @@ -136,7 +136,7 @@ class Log::Metadata fetch(key) { nil } end - def fetch(key) + def fetch(key, &) entry = find_entry(key) entry ? entry[:value] : yield key end diff --git a/src/log/setup.cr b/src/log/setup.cr index 7371f8876b40..ecd2aa154cce 100644 --- a/src/log/setup.cr +++ b/src/log/setup.cr @@ -1,6 +1,6 @@ class Log # Setups logging bindings discarding all previous configurations. - def self.setup(*, builder : Log::Builder = Log.builder) + def self.setup(*, builder : Log::Builder = Log.builder, &) builder.clear yield builder.as(Configuration) end diff --git a/src/log/spec.cr b/src/log/spec.cr index e776705dc359..f2fdfafb2aab 100644 --- a/src/log/spec.cr +++ b/src/log/spec.cr @@ -52,7 +52,7 @@ class Log # # Invocations can be nested in order to capture each source in their own `EntriesChecker`. # - def self.capture(source : String = "*", level : Severity = Log::Severity::Trace, *, builder = Log.builder) + def self.capture(source : String = "*", level : Severity = Log::Severity::Trace, *, builder = Log.builder, &) mem_backend = Log::MemoryBackend.new builder.bind(source, level, mem_backend) begin @@ -66,7 +66,7 @@ class Log # :ditto: def self.capture(level : Log::Severity = Log::Severity::Trace, - *, builder : Log::Builder = Log.builder) + *, builder : Log::Builder = Log.builder, &) capture("*", level, builder: builder) do |dsl| yield dsl end diff --git a/src/mime/media_type.cr b/src/mime/media_type.cr index 4255e50a9b74..e563f2aa27da 100644 --- a/src/mime/media_type.cr +++ b/src/mime/media_type.cr @@ -354,7 +354,7 @@ module MIME MediaType.new mediatype, params end - private def self.parse_parameter_value(reader) + private def self.parse_parameter_value(reader, &) reader = consume_whitespace(reader) # Quoted value. diff --git a/src/mime/multipart.cr b/src/mime/multipart.cr index 179a7b92790e..89175b763ca9 100644 --- a/src/mime/multipart.cr +++ b/src/mime/multipart.cr @@ -24,7 +24,7 @@ module MIME::Multipart # ``` # # See: `Multipart::Parser` - def self.parse(io, boundary) + def self.parse(io, boundary, &) parser = Parser.new(io, boundary) while parser.has_next? parser.next { |headers, io| yield headers, io } @@ -68,7 +68,7 @@ module MIME::Multipart # ``` # # See: `Multipart::Parser` - def self.parse(request : HTTP::Request) + def self.parse(request : HTTP::Request, &) boundary = parse_boundary(request.headers["Content-Type"]) return nil unless boundary @@ -79,7 +79,7 @@ module MIME::Multipart # Yields a `Multipart::Builder` to the given block, writing to *io* and # using *boundary*. `#finish` is automatically called on the builder. - def self.build(io : IO, boundary : String = Multipart.generate_boundary) + def self.build(io : IO, boundary : String = Multipart.generate_boundary, &) builder = Builder.new(io, boundary) yield builder builder.finish @@ -87,7 +87,7 @@ module MIME::Multipart # Yields a `Multipart::Builder` to the given block, returning the generated # message as a `String`. - def self.build(boundary : String = Multipart.generate_boundary) + def self.build(boundary : String = Multipart.generate_boundary, &) String.build do |io| build(io, boundary) { |g| yield g } end diff --git a/src/mime/multipart/builder.cr b/src/mime/multipart/builder.cr index 3f3f4d3aeeae..59d38d766da1 100644 --- a/src/mime/multipart/builder.cr +++ b/src/mime/multipart/builder.cr @@ -65,7 +65,7 @@ module MIME::Multipart # message. Throws if `#body_part` is called before this method. # # Can be called multiple times to append to the preamble multiple times. - def preamble + def preamble(&) fail "Cannot generate preamble: body already started" unless @state.start? || @state.preamble? yield @io @state = State::PREAMBLE @@ -95,7 +95,7 @@ module MIME::Multipart # Yields an IO that can be used to write to a body part which is appended # to the multipart message with the given *headers*. Throws if `#finish` or # `#epilogue` is called before this method. - def body_part(headers : HTTP::Headers) + def body_part(headers : HTTP::Headers, &) body_part_impl(headers) { |io| yield io } end @@ -106,7 +106,7 @@ module MIME::Multipart body_part_impl(headers, empty: true) { } end - private def body_part_impl(headers, empty = false) + private def body_part_impl(headers, empty = false, &) fail "Cannot generate body part: already finished" if @state.finished? fail "Cannot generate body part: after epilogue" if @state.epilogue? @@ -158,7 +158,7 @@ module MIME::Multipart # parts have been appended. # # Can be called multiple times to append to the preamble multiple times. - def epilogue + def epilogue(&) case @state in .start?, .preamble? fail "Cannot generate epilogue: no body parts" diff --git a/src/mime/multipart/parser.cr b/src/mime/multipart/parser.cr index ec3123b4c602..262f500119f0 100644 --- a/src/mime/multipart/parser.cr +++ b/src/mime/multipart/parser.cr @@ -47,7 +47,7 @@ module MIME::Multipart # io.gets_to_end # => "body" # end # ``` - def next + def next(&) raise Multipart::Error.new "Multipart parser already finished parsing" if @state.finished? raise Multipart::Error.new "Multipart parser is in an errored state" if @state.errored? diff --git a/src/mutex.cr b/src/mutex.cr index f659811d2928..6bdd9a98fd25 100644 --- a/src/mutex.cr +++ b/src/mutex.cr @@ -128,7 +128,7 @@ class Mutex nil end - def synchronize + def synchronize(&) lock begin yield diff --git a/src/named_tuple.cr b/src/named_tuple.cr index 6497504b04ed..4708d93d3bef 100644 --- a/src/named_tuple.cr +++ b/src/named_tuple.cr @@ -499,7 +499,7 @@ struct NamedTuple # name = Crystal # year = 2011 # ``` - def each : Nil + def each(&) : Nil {% for key in T %} yield {{key.symbolize}}, self[{{key.symbolize}}] {% end %} @@ -520,7 +520,7 @@ struct NamedTuple # name # year # ``` - def each_key : Nil + def each_key(&) : Nil {% for key in T %} yield {{key.symbolize}} {% end %} @@ -541,7 +541,7 @@ struct NamedTuple # Crystal # 2011 # ``` - def each_value : Nil + def each_value(&) : Nil {% for key in T %} yield self[{{key.symbolize}}] {% end %} @@ -562,7 +562,7 @@ struct NamedTuple # 1) name = Crystal # 2) year = 2011 # ``` - def each_with_index(offset = 0) + def each_with_index(offset = 0, &) i = offset each do |key, value| yield key, value, i @@ -577,7 +577,7 @@ struct NamedTuple # tuple = {name: "Crystal", year: 2011} # tuple.map { |k, v| "#{k}: #{v}" } # => ["name: Crystal", "year: 2011"] # ``` - def map + def map(&) {% if T.size == 0 %} [] of NoReturn {% else %} diff --git a/src/oauth/consumer.cr b/src/oauth/consumer.cr index 58340b981c97..14ba9407bd41 100644 --- a/src/oauth/consumer.cr +++ b/src/oauth/consumer.cr @@ -130,7 +130,7 @@ class OAuth::Consumer authenticate client, token.token, token.secret, nil end - private def post(oauth_token, token_shared_secret, extra_params, target_uri) + private def post(oauth_token, token_shared_secret, extra_params, target_uri, &) uri = URI.parse(target_uri) # If the target uri is absolute, we use that instead of the default values @@ -155,7 +155,7 @@ class OAuth::Consumer OAuth.authenticate(client, token, token_secret, @consumer_key, @consumer_secret, extra_params) end - private def handle_response(response) + private def handle_response(response, &) case response.status_code when 200, 201 yield diff --git a/src/oauth2/client.cr b/src/oauth2/client.cr index e2709ec04053..9718c7b9e3ed 100644 --- a/src/oauth2/client.cr +++ b/src/oauth2/client.cr @@ -159,7 +159,7 @@ class OAuth2::Client end end - private def get_access_token : AccessToken + private def get_access_token(&) : AccessToken headers = HTTP::Headers{ "Accept" => "application/json", "Content-Type" => "application/x-www-form-urlencoded", diff --git a/src/object.cr b/src/object.cr index 608dcf618bda..e0933d5a7bb1 100644 --- a/src/object.cr +++ b/src/object.cr @@ -175,7 +175,7 @@ class Object # .select { |x| x % 2 == 0 }.tap { |x| puts "evens: #{x.inspect}" } # .map { |x| x*x }.tap { |x| puts "squares: #{x.inspect}" } # ``` - def tap + def tap(&) yield self self end @@ -189,7 +189,7 @@ class Object # # First program argument in downcase, or nil # ARGV[0]?.try &.downcase # ``` - def try + def try(&) yield self end diff --git a/src/openssl/ssl/server.cr b/src/openssl/ssl/server.cr index f5e99ead39d6..97132f8c4810 100644 --- a/src/openssl/ssl/server.cr +++ b/src/openssl/ssl/server.cr @@ -49,7 +49,7 @@ class OpenSSL::SSL::Server # *context* configures the SSL options, see `OpenSSL::SSL::Context::Server` for details # # The server is closed after the block returns. - def self.open(wrapped : ::Socket::Server, context : OpenSSL::SSL::Context::Server = OpenSSL::SSL::Context::Server.new, sync_close : Bool = true) + def self.open(wrapped : ::Socket::Server, context : OpenSSL::SSL::Context::Server = OpenSSL::SSL::Context::Server.new, sync_close : Bool = true, &) server = new(wrapped, context, sync_close) begin diff --git a/src/openssl/ssl/socket.cr b/src/openssl/ssl/socket.cr index 742ad8f78eea..461185e342d2 100644 --- a/src/openssl/ssl/socket.cr +++ b/src/openssl/ssl/socket.cr @@ -39,7 +39,7 @@ abstract class OpenSSL::SSL::Socket < IO end end - def self.open(io, context : Context::Client = Context::Client.new, sync_close : Bool = false, hostname : String? = nil) + def self.open(io, context : Context::Client = Context::Client.new, sync_close : Bool = false, hostname : String? = nil, &) socket = new(io, context, sync_close, hostname) begin @@ -78,7 +78,7 @@ abstract class OpenSSL::SSL::Socket < IO end end - def self.open(io, context : Context::Server = Context::Server.new, sync_close : Bool = false) + def self.open(io, context : Context::Server = Context::Server.new, sync_close : Bool = false, &) socket = new(io, context, sync_close) begin diff --git a/src/option_parser.cr b/src/option_parser.cr index f82a8a42d607..175926a8c730 100644 --- a/src/option_parser.cr +++ b/src/option_parser.cr @@ -110,7 +110,7 @@ class OptionParser # and uses it to parse the passed *args* (defaults to `ARGV`). # # Refer to `#gnu_optional_args?` for the behaviour of the named parameter. - def self.parse(args = ARGV, *, gnu_optional_args : Bool = false) : self + def self.parse(args = ARGV, *, gnu_optional_args : Bool = false, &) : self parser = OptionParser.new(gnu_optional_args: gnu_optional_args) yield parser parser.parse(args) @@ -131,7 +131,7 @@ class OptionParser # Creates a new parser, with its configuration specified in the block. # # Refer to `#gnu_optional_args?` for the behaviour of the named parameter. - def self.new(*, gnu_optional_args : Bool = false) + def self.new(*, gnu_optional_args : Bool = false, &) new(gnu_optional_args: gnu_optional_args).tap { |parser| yield parser } end @@ -332,7 +332,7 @@ class OptionParser end end - private def with_preserved_state + private def with_preserved_state(&) old_flags = @flags.clone old_handlers = @handlers.clone old_banner = @banner diff --git a/src/path.cr b/src/path.cr index e7397079f3f7..2af60279ded5 100644 --- a/src/path.cr +++ b/src/path.cr @@ -528,7 +528,7 @@ struct Path PartIterator.new(self) end - private def each_part_separator_index + private def each_part_separator_index(&) reader = Char::Reader.new(@name) start_pos = reader.pos diff --git a/src/pretty_print.cr b/src/pretty_print.cr index 038da9d3eb4a..acc52f91dad6 100644 --- a/src/pretty_print.cr +++ b/src/pretty_print.cr @@ -109,7 +109,7 @@ class PrettyPrint # Creates a group of objects. Inside a group all breakable # objects are either turned into newlines or are output # as is, depending on the available width. - def group(indent = 0, open_obj = "", close_obj = "") + def group(indent = 0, open_obj = "", close_obj = "", &) text open_obj group_sub do nest(indent) do @@ -119,7 +119,7 @@ class PrettyPrint text close_obj end - private def group_sub + private def group_sub(&) group = Group.new(@group_stack.last.depth + 1) @group_stack.push group @group_queue.enq group @@ -134,7 +134,7 @@ class PrettyPrint end # Increases the indentation for breakables inside the current group. - def nest(indent = 1) + def nest(indent = 1, &) @indent += indent begin yield @@ -157,7 +157,7 @@ class PrettyPrint # Appends a group that is surrounded by the given *left* and *right* # objects, and optionally is surrounded by the given breakable # objects. - def surround(left, right, left_break = "", right_break = "") : Nil + def surround(left, right, left_break = "", right_break = "", &) : Nil group(1, left, right) do breakable left_break if left_break yield @@ -167,7 +167,7 @@ class PrettyPrint # Appends a list of elements surrounded by *left* and *right* # and separated by commas, yielding each element to the given block. - def list(left, elements, right) : Nil + def list(left, elements, right, &) : Nil group(1, left, right) do elements.each_with_index do |elem, i| comma if i > 0 @@ -298,7 +298,7 @@ class PrettyPrint # Creates a pretty printer and yields it to the block, # appending any output to the given *io*. - def self.format(io : IO, width : Int32, newline = "\n", indent = 0) + def self.format(io : IO, width : Int32, newline = "\n", indent = 0, &) printer = PrettyPrint.new(io, width, newline, indent) yield printer printer.flush diff --git a/src/process.cr b/src/process.cr index 44365f6fe715..3c0ce80cfdac 100644 --- a/src/process.cr +++ b/src/process.cr @@ -65,7 +65,7 @@ class Process # returns a `Process` representing the new child process. # # Available only on Unix-like operating systems. - def self.fork : Process + def self.fork(&) : Process if process = fork process else @@ -136,7 +136,7 @@ class Process # # Raises `IO::Error` if executing the command fails (for example if the executable doesn't exist). def self.run(command : String, args = nil, env : Env = nil, clear_env : Bool = false, shell : Bool = false, - input : Stdio = Redirect::Pipe, output : Stdio = Redirect::Pipe, error : Stdio = Redirect::Pipe, chdir : Path | String? = nil) + input : Stdio = Redirect::Pipe, output : Stdio = Redirect::Pipe, error : Stdio = Redirect::Pipe, chdir : Path | String? = nil, &) process = new(command, args, env, clear_env, shell, input, output, error, chdir) begin value = yield process diff --git a/src/process/executable_path.cr b/src/process/executable_path.cr index 67f253cdd291..cf2dd091c6ab 100644 --- a/src/process/executable_path.cr +++ b/src/process/executable_path.cr @@ -60,7 +60,7 @@ class Process nil end - private def self.find_executable_possibilities(name, path, pwd) + private def self.find_executable_possibilities(name, path, pwd, &) return if name.to_s.empty? {% if flag?(:win32) %} diff --git a/src/raise.cr b/src/raise.cr index f3d505ebe94e..62f56a1d38a8 100644 --- a/src/raise.cr +++ b/src/raise.cr @@ -37,7 +37,7 @@ private struct LEBReader end end -private def traverse_eh_table(leb, start, ip, actions) +private def traverse_eh_table(leb, start, ip, actions, &) # Ref: https://chromium.googlesource.com/native_client/pnacl-libcxxabi/+/master/src/cxa_personality.cpp throw_offset = ip - 1 - start diff --git a/src/range.cr b/src/range.cr index df6c51284c04..d09b91380b3f 100644 --- a/src/range.cr +++ b/src/range.cr @@ -108,7 +108,7 @@ struct Range(B, E) # (10..15).each { |n| print n, ' ' } # # prints: 10 11 12 13 14 15 # ``` - def each : Nil + def each(&) : Nil {% if B == Nil %} {% raise "Can't each beginless range" %} {% end %} @@ -160,7 +160,7 @@ struct Range(B, E) # (10...15).reverse_each { |n| print n, ' ' } # # prints: 14 13 12 11 10 # ``` - def reverse_each : Nil + def reverse_each(&) : Nil {% if E == Nil %} {% raise "Can't reverse_each endless range" %} {% end %} diff --git a/src/reference.cr b/src/reference.cr index f57923e107dd..4f5f9f5571e3 100644 --- a/src/reference.cr +++ b/src/reference.cr @@ -152,7 +152,7 @@ class Reference end end - private def exec_recursive(method) + private def exec_recursive(method, &) hash = ExecRecursive.hash key = {object_id, method} if hash[key]? @@ -202,7 +202,7 @@ class Reference # end # end # ``` - private def exec_recursive_clone + private def exec_recursive_clone(&) hash = ExecRecursiveClone.hash clone_object_id = hash[object_id]? unless clone_object_id diff --git a/src/regex/pcre.cr b/src/regex/pcre.cr index ff68509bed9e..b1eb227c3cae 100644 --- a/src/regex/pcre.cr +++ b/src/regex/pcre.cr @@ -120,7 +120,7 @@ module Regex::PCRE end end - private def fetch_impl(group_name : String) + private def fetch_impl(group_name : String, &) max_start = -1 match = nil exists = false @@ -139,7 +139,7 @@ module Regex::PCRE end end - private def each_named_capture_number(group_name) + private def each_named_capture_number(group_name, &) name_entry_size = LibPCRE.get_stringtable_entries(@code, group_name, out first, out last) return if name_entry_size < 0 diff --git a/src/regex/pcre2.cr b/src/regex/pcre2.cr index 176a479bbb57..08b823083086 100644 --- a/src/regex/pcre2.cr +++ b/src/regex/pcre2.cr @@ -25,7 +25,7 @@ module Regex::PCRE2 end end - protected def self.compile(source, options) + protected def self.compile(source, options, &) if res = LibPCRE2.compile(source, source.bytesize, options, out errorcode, out erroroffset, nil) res else @@ -96,7 +96,7 @@ module Regex::PCRE2 end # :nodoc: - def each_capture_group + def each_capture_group(&) name_table = uninitialized UInt8* pattern_info(LibPCRE2::INFO_NAMETABLE, pointerof(name_table)) @@ -189,7 +189,7 @@ module Regex::PCRE2 end end - private def fetch_impl(group_name : String) + private def fetch_impl(group_name : String, &) selected_range = nil exists = false @regex.each_capture_group do |number, name_entry| diff --git a/src/slice.cr b/src/slice.cr index c944de299560..ebdd7c5f4cc8 100644 --- a/src/slice.cr +++ b/src/slice.cr @@ -102,7 +102,7 @@ struct Slice(T) # slice = Slice.new(3) { |i| i + 10 } # slice # => Slice[10, 11, 12] # ``` - def self.new(size : Int, *, read_only = false) + def self.new(size : Int, *, read_only = false, &) pointer = Pointer.malloc(size) { |i| yield i } new(pointer, size, read_only: read_only) end diff --git a/src/socket.cr b/src/socket.cr index 508f76f08e9b..df736a561503 100644 --- a/src/socket.cr +++ b/src/socket.cr @@ -140,7 +140,7 @@ class Socket < IO # Tries to listen for connections on the previously bound socket. # Yields an `Socket::Error` on failure. - def listen(backlog : Int = SOMAXCONN) + def listen(backlog : Int = SOMAXCONN, &) system_listen(backlog) { |err| yield err } end @@ -387,7 +387,7 @@ class Socket < IO raise Socket::Error.from_errno("getsockopt") end - protected def getsockopt(optname, optval, level = LibC::SOL_SOCKET) + protected def getsockopt(optname, optval, level = LibC::SOL_SOCKET, &) system_getsockopt(fd, optname, optval, level) { |value| yield value } end diff --git a/src/socket/addrinfo.cr b/src/socket/addrinfo.cr index 1667ebb7ae91..01415d9b642c 100644 --- a/src/socket/addrinfo.cr +++ b/src/socket/addrinfo.cr @@ -56,7 +56,7 @@ class Socket # # The iteration will be stopped once the block returns something that isn't # an `Exception` (e.g. a `Socket` or `nil`). - def self.resolve(domain, service, family : Family? = nil, type : Type = nil, protocol : Protocol = Protocol::IP, timeout = nil) + def self.resolve(domain, service, family : Family? = nil, type : Type = nil, protocol : Protocol = Protocol::IP, timeout = nil, &) getaddrinfo(domain, service, family, type, protocol, timeout) do |addrinfo| loop do value = yield addrinfo.not_nil! @@ -128,7 +128,7 @@ class Socket end end - private def self.getaddrinfo(domain, service, family, type, protocol, timeout) + private def self.getaddrinfo(domain, service, family, type, protocol, timeout, &) {% if flag?(:wasm32) %} raise NotImplementedError.new "Socket::Addrinfo.getaddrinfo" {% else %} @@ -202,7 +202,7 @@ class Socket # Resolves a domain for the TCP protocol with STREAM type, and yields each # possible `Addrinfo`. See `#resolve` for details. - def self.tcp(domain, service, family = Family::UNSPEC, timeout = nil) + def self.tcp(domain, service, family = Family::UNSPEC, timeout = nil, &) resolve(domain, service, family, Type::STREAM, Protocol::TCP) { |addrinfo| yield addrinfo } end @@ -221,7 +221,7 @@ class Socket # Resolves a domain for the UDP protocol with DGRAM type, and yields each # possible `Addrinfo`. See `#resolve` for details. - def self.udp(domain, service, family = Family::UNSPEC, timeout = nil) + def self.udp(domain, service, family = Family::UNSPEC, timeout = nil, &) resolve(domain, service, family, Type::DGRAM, Protocol::UDP) { |addrinfo| yield addrinfo } end diff --git a/src/socket/server.cr b/src/socket/server.cr index 8d282b4c56dd..253593b330f4 100644 --- a/src/socket/server.cr +++ b/src/socket/server.cr @@ -45,7 +45,7 @@ class Socket # socket.puts Time.utc # end # ``` - def accept + def accept(&) sock = accept begin yield sock @@ -68,7 +68,7 @@ class Socket # socket.puts Time.utc # end # ``` - def accept? + def accept?(&) sock = accept? return unless sock diff --git a/src/socket/tcp_server.cr b/src/socket/tcp_server.cr index 4d72259d2ade..51d828d45426 100644 --- a/src/socket/tcp_server.cr +++ b/src/socket/tcp_server.cr @@ -64,7 +64,7 @@ class TCPServer < TCPSocket # server socket when the block returns. # # Returns the value of the block. - def self.open(host, port, backlog = SOMAXCONN, reuse_port = false) + def self.open(host, port, backlog = SOMAXCONN, reuse_port = false, &) server = new(host, port, backlog, reuse_port: reuse_port) begin yield server @@ -77,7 +77,7 @@ class TCPServer < TCPSocket # block. Eventually closes the server socket when the block returns. # # Returns the value of the block. - def self.open(port : Int, backlog = SOMAXCONN, reuse_port = false) + def self.open(port : Int, backlog = SOMAXCONN, reuse_port = false, &) server = new(port, backlog, reuse_port: reuse_port) begin yield server diff --git a/src/socket/tcp_socket.cr b/src/socket/tcp_socket.cr index 09ac37fab531..980f0b338cff 100644 --- a/src/socket/tcp_socket.cr +++ b/src/socket/tcp_socket.cr @@ -51,7 +51,7 @@ class TCPSocket < IPSocket # eventually closes the socket when the block returns. # # Returns the value of the block. - def self.open(host, port) + def self.open(host, port, &) sock = new(host, port) begin yield sock diff --git a/src/socket/unix_server.cr b/src/socket/unix_server.cr index f77fbdfee514..98425e86cc54 100644 --- a/src/socket/unix_server.cr +++ b/src/socket/unix_server.cr @@ -55,7 +55,7 @@ class UNIXServer < UNIXSocket # server socket when the block returns. # # Returns the value of the block. - def self.open(path, type : Type = Type::STREAM, backlog = 128) + def self.open(path, type : Type = Type::STREAM, backlog = 128, &) server = new(path, type, backlog) begin yield server diff --git a/src/socket/unix_socket.cr b/src/socket/unix_socket.cr index 4efbd1c1c4bd..6a4dbb3d340a 100644 --- a/src/socket/unix_socket.cr +++ b/src/socket/unix_socket.cr @@ -37,7 +37,7 @@ class UNIXSocket < Socket # eventually closes the socket when the block returns. # # Returns the value of the block. - def self.open(path, type : Type = Type::STREAM) + def self.open(path, type : Type = Type::STREAM, &) sock = new(path, type) begin yield sock @@ -85,7 +85,7 @@ class UNIXSocket < Socket # block. Eventually closes both sockets when the block returns. # # Returns the value of the block. - def self.pair(type : Type = Type::STREAM) + def self.pair(type : Type = Type::STREAM, &) left, right = pair(type) begin yield left, right diff --git a/src/spec/expectations.cr b/src/spec/expectations.cr index 3313bb43aaa9..ac93de54975e 100644 --- a/src/spec/expectations.cr +++ b/src/spec/expectations.cr @@ -387,7 +387,7 @@ module Spec # TODO: Enable "expect_raises" for wasm32 after exceptions are working. end {% else %} - def expect_raises(klass : T.class, message : String | Regex | Nil = nil, file = __FILE__, line = __LINE__) forall T + def expect_raises(klass : T.class, message : String | Regex | Nil = nil, file = __FILE__, line = __LINE__, &) forall T yield rescue ex : T # We usually bubble Spec::AssertionFailed, unless this is the expected exception diff --git a/src/string.cr b/src/string.cr index 0d25eb667eec..44a811c4ba91 100644 --- a/src/string.cr +++ b/src/string.cr @@ -241,7 +241,7 @@ class String # end # str # => "ab" # ``` - def self.new(capacity : Int) + def self.new(capacity : Int, &) check_capacity_in_bounds(capacity) str = GC.malloc_atomic(capacity.to_u32 + HEADER_SIZE + 1).as(UInt8*) @@ -275,7 +275,7 @@ class String # end # str # => "hello 1" # ``` - def self.build(capacity = 64) : self + def self.build(capacity = 64, &) : self String::Builder.build(capacity) do |builder| yield builder end @@ -735,7 +735,7 @@ class String end end - private def to_f_impl(whitespace : Bool = true, strict : Bool = true) + private def to_f_impl(whitespace : Bool = true, strict : Bool = true, &) return unless whitespace || '0' <= self[0] <= '9' || self[0].in?('-', '+') v, endptr = yield @@ -2340,7 +2340,7 @@ class String # ``` # "hello".sub(/./) { |s| s[0].ord.to_s + ' ' } # => "104 ello" # ``` - def sub(pattern : Regex) : String + def sub(pattern : Regex, &) : String sub_append(pattern) do |str, match, buffer| $~ = match buffer << yield str, match @@ -2468,7 +2468,7 @@ class String end end - private def sub_append(pattern : Regex) + private def sub_append(pattern : Regex, &) match = pattern.match(self) return self unless match @@ -2511,7 +2511,7 @@ class String end end - private def sub_index(index, replacement) + private def sub_index(index, replacement, &) index += size if index < 0 byte_index = char_index_to_byte_index(index) @@ -2561,7 +2561,7 @@ class String end end - private def sub_range(range, replacement) + private def sub_range(range, replacement, &) start, count = Indexable.range_to_index_and_count(range, size) || raise IndexError.new from_index = char_index_to_byte_index(start) @@ -2698,7 +2698,7 @@ class String # ``` # "hello".gsub(/./) { |s| s[0].ord.to_s + ' ' } # => "104 101 108 108 111 " # ``` - def gsub(pattern : Regex) : String + def gsub(pattern : Regex, &) : String gsub_append(pattern) do |string, match, buffer| $~ = match buffer << yield string, match @@ -2840,7 +2840,7 @@ class String end end - private def gsub_append(pattern : Regex) + private def gsub_append(pattern : Regex, &) byte_offset = 0 match = pattern.match_at_byte_index(self, byte_offset) return self unless match @@ -2879,7 +2879,7 @@ class String # ``` # "aabbcc".count &.in?('a', 'b') # => 4 # ``` - def count : Int32 + def count(&) : Int32 count = 0 each_char do |char| count += 1 if yield char @@ -2910,7 +2910,7 @@ class String # ``` # "aabbcc".delete &.in?('a', 'b') # => "cc" # ``` - def delete : String + def delete(&) : String String.build(bytesize) do |buffer| each_char do |char| buffer << char unless yield char @@ -2947,7 +2947,7 @@ class String # "aaabbbccc".squeeze &.in?('a', 'b') # => "abccc" # "aaabbbccc".squeeze &.in?('a', 'c') # => "abbbc" # ``` - def squeeze : String + def squeeze(&) : String previous = nil String.build(bytesize) do |buffer| each_char do |char| @@ -4572,7 +4572,7 @@ class String # Searches the string for instances of *pattern*, # yielding a `Regex::MatchData` for each match. - def scan(pattern : Regex) : self + def scan(pattern : Regex, &) : self byte_offset = 0 while match = pattern.match_at_byte_index(self, byte_offset) @@ -4599,7 +4599,7 @@ class String # Searches the string for instances of *pattern*, # yielding the matched string for each match. - def scan(pattern : String) : self + def scan(pattern : String, &) : self return self if pattern.empty? index = 0 while index = byte_index(pattern, index) @@ -4628,7 +4628,7 @@ class String # end # array # => ['a', 'b', '☃'] # ``` - def each_char : Nil + def each_char(&) : Nil if single_byte_optimizable? each_byte do |byte| yield (byte < 0x80 ? byte.unsafe_chr : Char::REPLACEMENT) @@ -4664,7 +4664,7 @@ class String # # Accepts an optional *offset* parameter, which tells it to start counting # from there. - def each_char_with_index(offset = 0) + def each_char_with_index(offset = 0, &) each_char do |char| yield char, offset offset += 1 @@ -4695,7 +4695,7 @@ class String # ``` # # See also: `Char#ord`. - def each_codepoint + def each_codepoint(&) each_char do |char| yield char.ord end @@ -4739,7 +4739,7 @@ class String # end # array # => [97, 98, 226, 152, 131] # ``` - def each_byte + def each_byte(&) to_slice.each do |byte| yield byte end @@ -4899,7 +4899,7 @@ class String end end - private def dump_or_inspect(io) + private def dump_or_inspect(io, &) io << '"' dump_or_inspect_unquoted(io) do |char, error| yield char, error @@ -4907,7 +4907,7 @@ class String io << '"' end - private def dump_or_inspect_unquoted(io) + private def dump_or_inspect_unquoted(io, &) reader = Char::Reader.new(self) while reader.has_next? current_char = reader.current_char @@ -4959,7 +4959,7 @@ class String end end - private def dump_or_inspect_char(char, error, io) + private def dump_or_inspect_char(char, error, io, &) if error dump_hex(error, io) elsif yield @@ -5218,7 +5218,7 @@ class String @bytesize == 0 || @length > 0 end - protected def each_byte_index_and_char_index + protected def each_byte_index_and_char_index(&) byte_index = 0 char_index = 0 diff --git a/src/string/builder.cr b/src/string/builder.cr index 373b6a7da0c2..d1add8dc9be2 100644 --- a/src/string/builder.cr +++ b/src/string/builder.cr @@ -22,7 +22,7 @@ class String::Builder < IO @finished = false end - def self.build(capacity : Int = 64) : String + def self.build(capacity : Int = 64, &) : String builder = new(capacity) yield builder builder.to_s diff --git a/src/string/utf16.cr b/src/string/utf16.cr index bf79b073a2fd..b3fdc09301af 100644 --- a/src/string/utf16.cr +++ b/src/string/utf16.cr @@ -129,7 +129,7 @@ class String end # Yields each decoded char in the given slice. - private def self.each_utf16_char(slice : Slice(UInt16)) + private def self.each_utf16_char(slice : Slice(UInt16), &) i = 0 while i < slice.size byte = slice[i].to_i @@ -154,7 +154,7 @@ class String end # Yields each decoded char in the given pointer, stopping at the first null byte. - private def self.each_utf16_char(pointer : Pointer(UInt16)) : Pointer(UInt16) + private def self.each_utf16_char(pointer : Pointer(UInt16), &) : Pointer(UInt16) loop do byte = pointer.value.to_i break if byte == 0 diff --git a/src/time/location/loader.cr b/src/time/location/loader.cr index 5386f1570ef0..ffda4929f0c2 100644 --- a/src/time/location/loader.cr +++ b/src/time/location/loader.cr @@ -41,7 +41,7 @@ class Time::Location end end - private def self.open_file_cached(name : String, path : String) + private def self.open_file_cached(name : String, path : String, &) return nil unless File.exists?(path) mtime = File.info(path).modification_time @@ -173,7 +173,7 @@ class Time::Location # This method loads an entry from an uncompressed zip file. # See http://www.onicos.com/staff/iz/formats/zip.html for ZIP format layout - private def self.read_zip_file(name : String, file : File) + private def self.read_zip_file(name : String, file : File, &) file.seek -ZIP_TAIL_SIZE, IO::Seek::End if file.read_bytes(Int32, IO::ByteFormat::LittleEndian) != END_OF_CENTRAL_DIRECTORY_HEADER_SIGNATURE diff --git a/src/tuple.cr b/src/tuple.cr index 16d2675243c8..0191aab76037 100644 --- a/src/tuple.cr +++ b/src/tuple.cr @@ -339,7 +339,7 @@ struct Tuple # tuple.at(0) { 10 } # => 1 # tuple.at(3) { 10 } # => 10 # ``` - def at(index : Int) + def at(index : Int, &) index += size if index < 0 {% for i in 0...T.size %} return self[{{i}}] if {{i}} == index @@ -589,7 +589,7 @@ struct Tuple # # Accepts an optional *offset* parameter, which tells it to start counting # from there. - def map_with_index(offset = 0) + def map_with_index(offset = 0, &) {% begin %} Tuple.new( {% for i in 0...T.size %} @@ -639,7 +639,7 @@ struct Tuple end # :inherit: - def reduce + def reduce(&) {% if T.empty? %} raise Enumerable::EmptyError.new {% else %} @@ -652,7 +652,7 @@ struct Tuple end # :inherit: - def reduce(memo) + def reduce(memo, &) {% for i in 0...T.size %} memo = yield memo, self[{{ i }}] {% end %} @@ -660,7 +660,7 @@ struct Tuple end # :inherit: - def reduce? + def reduce?(&) {% unless T.empty? %} reduce { |memo, elem| yield memo, elem } {% end %} diff --git a/src/unicode/unicode.cr b/src/unicode/unicode.cr index 6a9a7698c3d4..3918b7a1efe6 100644 --- a/src/unicode/unicode.cr +++ b/src/unicode/unicode.cr @@ -161,7 +161,7 @@ module Unicode end # :nodoc: - def self.upcase(char : Char, options : CaseOptions) + def self.upcase(char : Char, options : CaseOptions, &) result = check_upcase_ascii(char, options) if result yield result @@ -231,7 +231,7 @@ module Unicode end # :nodoc: - def self.downcase(char : Char, options : CaseOptions) + def self.downcase(char : Char, options : CaseOptions, &) result = check_downcase_ascii(char, options) if result yield result @@ -555,7 +555,7 @@ module Unicode end end - private def self.search_ranges(haystack, needle) + private def self.search_ranges(haystack, needle, &) value = haystack.bsearch { |v| needle <= v[1] } if value && value[0] <= needle <= value[1] yield value diff --git a/src/uri/encoding.cr b/src/uri/encoding.cr index 3f6041e128ac..a7c5be7f1fb9 100644 --- a/src/uri/encoding.cr +++ b/src/uri/encoding.cr @@ -330,7 +330,7 @@ class URI # :nodoc: # Unencodes one character. Private API - def self.decode_one(string, bytesize, i, byte, char, io, plus_to_space = false) + def self.decode_one(string, bytesize, i, byte, char, io, plus_to_space = false, &) if plus_to_space && char == '+' io.write_byte ' '.ord.to_u8 i += 1 diff --git a/src/uri/params.cr b/src/uri/params.cr index f3cc92dcac11..aa4f5eb30511 100644 --- a/src/uri/params.cr +++ b/src/uri/params.cr @@ -32,7 +32,7 @@ class URI # # ... # end # ``` - def self.parse(query : String) + def self.parse(query : String, &) return if query.empty? key = nil @@ -284,7 +284,7 @@ class URI # params.fetch("email") { raise "Email is missing" } # raises "Email is missing" # params.fetch("non_existent_param") { "default computed value" } # => "default computed value" # ``` - def fetch(name) + def fetch(name, &) return yield name unless has_key?(name) raw_params[name].first end @@ -324,7 +324,7 @@ class URI # # item => keychain # # item => keynote # ``` - def each + def each(&) raw_params.each do |name, values| values.each do |value| yield({name, value}) diff --git a/src/va_list.cr b/src/va_list.cr index b24304c32e4c..9f389089c83d 100644 --- a/src/va_list.cr +++ b/src/va_list.cr @@ -8,7 +8,7 @@ struct VaList def initialize(@to_unsafe : LibC::VaList) end - def self.open + def self.open(&) ap = uninitialized LibC::VaList Intrinsics.va_start pointerof(ap) begin diff --git a/src/xml/attributes.cr b/src/xml/attributes.cr index 7964a89faabf..1df5aea55483 100644 --- a/src/xml/attributes.cr +++ b/src/xml/attributes.cr @@ -49,7 +49,7 @@ class XML::Attributes value if res == 0 end - def each : Nil + def each(&) : Nil return unless @node.element? props = self.props diff --git a/src/xml/builder.cr b/src/xml/builder.cr index 5265a07feb9f..1ebe23efcd47 100644 --- a/src/xml/builder.cr +++ b/src/xml/builder.cr @@ -40,7 +40,7 @@ class XML::Builder # Emits the start of the document, invokes the block, # and then emits the end of the document. - def document(version = nil, encoding = nil) + def document(version = nil, encoding = nil, &) start_document version, encoding yield.tap { end_document } end @@ -70,14 +70,14 @@ class XML::Builder # Emits the start of an element with the given *attributes*, # invokes the block and then emits the end of the element. - def element(__name__ : String, **attributes) + def element(__name__ : String, **attributes, &) element(__name__, attributes) do yield end end # :ditto: - def element(__name__ : String, attributes : Hash | NamedTuple) + def element(__name__ : String, attributes : Hash | NamedTuple, &) start_element __name__ attributes(attributes) yield.tap { end_element } @@ -95,14 +95,14 @@ class XML::Builder # Emits the start of an element with namespace info with the given *attributes*, # invokes the block and then emits the end of the element. - def element(__prefix__ : String?, __name__ : String, __namespace_uri__ : String?, **attributes) + def element(__prefix__ : String?, __name__ : String, __namespace_uri__ : String?, **attributes, &) element(__prefix__, __name__, __namespace_uri__, attributes) do yield end end # :ditto: - def element(__prefix__ : String?, __name__ : String, __namespace_uri__ : String?, attributes : Hash | NamedTuple) + def element(__prefix__ : String?, __name__ : String, __namespace_uri__ : String?, attributes : Hash | NamedTuple, &) start_element __prefix__, __name__, __namespace_uri__ attributes(attributes) yield.tap { end_element } @@ -137,7 +137,7 @@ class XML::Builder # Emits the start of an attribute, invokes the block, # and then emits the end of the attribute. - def attribute(*args, **nargs) + def attribute(*args, **nargs, &) start_attribute *args, **nargs yield.tap { end_attribute } end @@ -208,7 +208,7 @@ class XML::Builder # Emits the start of a comment, invokes the block # and then emits the end of the comment. - def comment + def comment(&) start_comment yield.tap { end_comment } end @@ -230,7 +230,7 @@ class XML::Builder # Emits the start of a `DTD`, invokes the block # and then emits the end of the `DTD`. - def dtd(name : String, pubid : String, sysid : String) : Nil + def dtd(name : String, pubid : String, sysid : String, &) : Nil start_dtd name, pubid, sysid yield.tap { end_dtd } end @@ -322,7 +322,7 @@ module XML # # string # => "\n\n Jane\n Doe\n\n" # ``` - def self.build(version : String? = nil, encoding : String? = nil, indent = nil, quote_char = nil) + def self.build(version : String? = nil, encoding : String? = nil, indent = nil, quote_char = nil, &) String.build do |str| build(str, version, encoding, indent, quote_char) do |xml| yield xml @@ -346,7 +346,7 @@ module XML # # string # => "\n Jane\n Doe\n\n" # ``` - def self.build_fragment(*, indent = nil, quote_char = nil) + def self.build_fragment(*, indent = nil, quote_char = nil, &) String.build do |str| build_fragment(str, indent: indent, quote_char: quote_char) do |xml| yield xml @@ -357,7 +357,7 @@ module XML # Writes XML document into the given `IO`. An `XML::Builder` is yielded to the block. # # Builds an XML document (see `#document`) including XML declaration (``). - def self.build(io : IO, version : String? = nil, encoding : String? = nil, indent = nil, quote_char = nil) : Nil + def self.build(io : IO, version : String? = nil, encoding : String? = nil, indent = nil, quote_char = nil, &) : Nil build_fragment(io, indent: indent, quote_char: quote_char) do |xml| xml.start_document version, encoding yield xml @@ -368,7 +368,7 @@ module XML # Writes XML fragment into the given `IO`. An `XML::Builder` is yielded to the block. # # Builds an XML fragment without XML declaration (``). - def self.build_fragment(io : IO, *, indent = nil, quote_char = nil) : Nil + def self.build_fragment(io : IO, *, indent = nil, quote_char = nil, &) : Nil xml = XML::Builder.new(io) xml.indent = indent if indent xml.quote_char = quote_char if quote_char diff --git a/src/xml/node_set.cr b/src/xml/node_set.cr index 971c7bc63ec4..0263facbfd55 100644 --- a/src/xml/node_set.cr +++ b/src/xml/node_set.cr @@ -18,7 +18,7 @@ class XML::NodeSet internal_at(index) end - def each : Nil + def each(&) : Nil size.times do |i| yield internal_at(i) end diff --git a/src/xml/reader.cr b/src/xml/reader.cr index 684d3ed28871..9d1de3ed4c9e 100644 --- a/src/xml/reader.cr +++ b/src/xml/reader.cr @@ -195,7 +195,7 @@ class XML::Reader @reader end - private def collect_errors + private def collect_errors(&) Error.collect(@errors) { yield }.tap do Error.add_errors(@errors) end diff --git a/src/yaml/builder.cr b/src/yaml/builder.cr index 6fc5dac4272e..2764580dde13 100644 --- a/src/yaml/builder.cr +++ b/src/yaml/builder.cr @@ -67,7 +67,7 @@ class YAML::Builder end # Starts a YAML stream, invokes the block, and ends it. - def stream + def stream(&) start_stream yield.tap { end_stream } end @@ -83,7 +83,7 @@ class YAML::Builder end # Starts a document, invokes the block, and then ends it. - def document + def document(&) start_document yield.tap { end_document } end @@ -109,7 +109,7 @@ class YAML::Builder end # Starts a sequence, invokes the block, and the ends it. - def sequence(anchor : String? = nil, tag : String? = nil, style : YAML::SequenceStyle = YAML::SequenceStyle::ANY) + def sequence(anchor : String? = nil, tag : String? = nil, style : YAML::SequenceStyle = YAML::SequenceStyle::ANY, &) start_sequence(anchor, tag, style) yield.tap { end_sequence } end @@ -128,7 +128,7 @@ class YAML::Builder end # Starts a mapping, invokes the block, and then ends it. - def mapping(anchor : String? = nil, tag : String? = nil, style : YAML::MappingStyle = YAML::MappingStyle::ANY) + def mapping(anchor : String? = nil, tag : String? = nil, style : YAML::MappingStyle = YAML::MappingStyle::ANY, &) start_mapping(anchor, tag, style) yield.tap { end_mapping } end @@ -239,7 +239,7 @@ module YAML # end # string # => "---\nfoo:\n- 1\n- 2\n" # ``` - def self.build + def self.build(&) String.build do |str| build(str) do |yaml| yield yaml @@ -248,7 +248,7 @@ module YAML end # Writes YAML into the given `IO`. A `YAML::Builder` is yielded to the block. - def self.build(io : IO) : Nil + def self.build(io : IO, &) : Nil YAML::Builder.build(io) do |yaml| yaml.stream do yaml.document do diff --git a/src/yaml/from_yaml.cr b/src/yaml/from_yaml.cr index 4895467e8638..741ddcd98228 100644 --- a/src/yaml/from_yaml.cr +++ b/src/yaml/from_yaml.cr @@ -12,7 +12,7 @@ def Object.from_yaml(string_or_io : String | IO) new(YAML::ParseContext.new, parse_yaml(string_or_io)) end -def Array.from_yaml(string_or_io : String | IO) +def Array.from_yaml(string_or_io : String | IO, &) new(YAML::ParseContext.new, parse_yaml(string_or_io)) do |element| yield element end @@ -103,7 +103,7 @@ def Array.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) ary end -def Array.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) +def Array.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node, &) unless node.is_a?(YAML::Nodes::Sequence) node.raise "Expected sequence, not #{node.kind}" end @@ -128,7 +128,7 @@ def Set.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) ary end -def Set.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) +def Set.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node, &) unless node.is_a?(YAML::Nodes::Sequence) node.raise "Expected sequence, not #{node.kind}" end @@ -153,7 +153,7 @@ def Hash.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) hash end -def Hash.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) +def Hash.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node, &) unless node.is_a?(YAML::Nodes::Mapping) node.raise "Expected mapping, not #{node.kind}" end diff --git a/src/yaml/nodes/builder.cr b/src/yaml/nodes/builder.cr index 50e684530dda..9445cb6485d4 100644 --- a/src/yaml/nodes/builder.cr +++ b/src/yaml/nodes/builder.cr @@ -85,7 +85,7 @@ class YAML::Nodes::Builder def sequence(anchor : String? = nil, tag : String? = nil, style : YAML::SequenceStyle = YAML::SequenceStyle::ANY, - reference = nil) : Nil + reference = nil, &) : Nil node = Sequence.new node.anchor = anchor node.tag = tag @@ -102,7 +102,7 @@ class YAML::Nodes::Builder def mapping(anchor : String? = nil, tag : String? = nil, style : YAML::MappingStyle = YAML::MappingStyle::ANY, - reference = nil) : Nil + reference = nil, &) : Nil node = Mapping.new node.anchor = anchor node.tag = tag @@ -130,7 +130,7 @@ class YAML::Nodes::Builder end end - private def push_to_stack(node) + private def push_to_stack(node, &) push_node(node) old_current = @current diff --git a/src/yaml/nodes/nodes.cr b/src/yaml/nodes/nodes.cr index 919554cefa2a..a035a9dae2ab 100644 --- a/src/yaml/nodes/nodes.cr +++ b/src/yaml/nodes/nodes.cr @@ -96,7 +96,7 @@ module YAML::Nodes @nodes << node end - def each + def each(&) @nodes.each do |node| yield node end @@ -132,7 +132,7 @@ module YAML::Nodes end # Yields each key-value pair in this mapping. - def each + def each(&) 0.step(by: 2, to: @nodes.size - 1) do |i| yield({@nodes[i], @nodes[i + 1]}) end diff --git a/src/yaml/nodes/parser.cr b/src/yaml/nodes/parser.cr index d63cf093196c..93fc94e46e51 100644 --- a/src/yaml/nodes/parser.cr +++ b/src/yaml/nodes/parser.cr @@ -5,7 +5,7 @@ class YAML::Nodes::Parser < YAML::Parser @anchors = {} of String => Node end - def self.new(content) + def self.new(content, &) parser = new(content) yield parser ensure parser.close end diff --git a/src/yaml/parse_context.cr b/src/yaml/parse_context.cr index 5ff86c46988a..da1608136d32 100644 --- a/src/yaml/parse_context.cr +++ b/src/yaml/parse_context.cr @@ -30,7 +30,7 @@ class YAML::ParseContext # Tries to read an alias from `node` of type `T`. Invokes # the block if successful, and invokers must return this object # instead of deserializing their members. - def read_alias(node, type : T.class) forall T + def read_alias(node, type : T.class, &) forall T if ptr = read_alias_impl(node, T.crystal_instance_type_id, raise_on_alias: true) yield ptr.unsafe_as(T) end @@ -38,7 +38,7 @@ class YAML::ParseContext # Similar to `read_alias` but doesn't raise if an alias exists # but an instance of type T isn't associated with the current anchor. - def read_alias?(node, type : T.class) forall T + def read_alias?(node, type : T.class, &) forall T if ptr = read_alias_impl(node, T.crystal_instance_type_id, raise_on_alias: false) yield ptr.unsafe_as(T) end diff --git a/src/yaml/parser.cr b/src/yaml/parser.cr index 5b27cee2a3b9..2035f6cd67a6 100644 --- a/src/yaml/parser.cr +++ b/src/yaml/parser.cr @@ -4,7 +4,7 @@ abstract class YAML::Parser @pull_parser = PullParser.new(content) end - def self.new(content) + def self.new(content, &) parser = new(content) yield parser ensure parser.close end @@ -122,7 +122,7 @@ abstract class YAML::Parser sequence end - protected def parse_sequence(sequence) + protected def parse_sequence(sequence, &) @pull_parser.read_sequence_start until @pull_parser.kind.sequence_end? @@ -144,7 +144,7 @@ abstract class YAML::Parser mapping end - protected def parse_mapping(mapping) + protected def parse_mapping(mapping, &) @pull_parser.read_mapping_start until @pull_parser.kind.mapping_end? diff --git a/src/yaml/pull_parser.cr b/src/yaml/pull_parser.cr index 1cdfa8131d92..33ae6bfa07f1 100644 --- a/src/yaml/pull_parser.cr +++ b/src/yaml/pull_parser.cr @@ -36,7 +36,7 @@ class YAML::PullParser # Creates a parser, yields it to the block, and closes # the parser at the end of it. - def self.new(content) + def self.new(content, &) parser = new(content) yield parser ensure parser.close end @@ -126,7 +126,7 @@ class YAML::PullParser # Reads a "stream start" event, yields to the block, # and then reads a "stream end" event. - def read_stream + def read_stream(&) read_stream_start value = yield read_stream_end @@ -135,7 +135,7 @@ class YAML::PullParser # Reads a "document start" event, yields to the block, # and then reads a "document end" event. - def read_document + def read_document(&) read_document_start value = yield read_document_end @@ -144,7 +144,7 @@ class YAML::PullParser # Reads a "sequence start" event, yields to the block, # and then reads a "sequence end" event. - def read_sequence + def read_sequence(&) read_sequence_start value = yield read_sequence_end @@ -153,7 +153,7 @@ class YAML::PullParser # Reads a "mapping start" event, yields to the block, # and then reads a "mapping end" event. - def read_mapping + def read_mapping(&) read_mapping_start value = yield read_mapping_end diff --git a/src/yaml/schema/core.cr b/src/yaml/schema/core.cr index 7ae71fccd83a..b7504f4590e6 100644 --- a/src/yaml/schema/core.cr +++ b/src/yaml/schema/core.cr @@ -128,7 +128,7 @@ module YAML::Schema::Core # If `node` parses to a null value, returns `nil`, otherwise # invokes the given block. - def self.parse_null_or(node : YAML::Nodes::Node) + def self.parse_null_or(node : YAML::Nodes::Node, &) if node.is_a?(YAML::Nodes::Scalar) && parse_null?(node) nil else @@ -140,7 +140,7 @@ module YAML::Schema::Core # values, resolving merge keys (<<) when found (keys and # values of the resolved merge mappings are yielded, # recursively). - def self.each(node : YAML::Nodes::Mapping) + def self.each(node : YAML::Nodes::Mapping, &) # We can't just traverse the nodes and invoke yield because # yield can't recurse. So, we use a stack of {Mapping, index}. # We pop from the stack and traverse the mapping values. @@ -266,13 +266,13 @@ module YAML::Schema::Core raise(YAML::ParseException.new("Invalid timestamp", *location)) end - protected def self.process_scalar_tag(scalar) + protected def self.process_scalar_tag(scalar, &) process_scalar_tag(scalar, scalar.tag) do |value| yield value end end - protected def self.process_scalar_tag(source, tag) + protected def self.process_scalar_tag(source, tag, &) case tag when "tag:yaml.org,2002:binary" yield parse_binary(source.value, source.location) diff --git a/src/yaml/schema/core/parser.cr b/src/yaml/schema/core/parser.cr index 2eaabd7aaa18..d3d205f497f0 100644 --- a/src/yaml/schema/core/parser.cr +++ b/src/yaml/schema/core/parser.cr @@ -86,7 +86,7 @@ class YAML::Schema::Core::Parser < YAML::Parser mapping end - def process_tag(tag) + def process_tag(tag, &) if value = process_collection_tag(@pull_parser, tag) yield value end From e984a0ccac4907e67f23f8f794a1e7b279e2500c Mon Sep 17 00:00:00 2001 From: Quinton Miller Date: Sun, 15 Jan 2023 00:59:10 +0800 Subject: [PATCH 3/3] fixup --- src/compiler/crystal/tools/formatter.cr | 1 - 1 file changed, 1 deletion(-) diff --git a/src/compiler/crystal/tools/formatter.cr b/src/compiler/crystal/tools/formatter.cr index c9b08363e212..4ac5e9ee37aa 100644 --- a/src/compiler/crystal/tools/formatter.cr +++ b/src/compiler/crystal/tools/formatter.cr @@ -1504,7 +1504,6 @@ module Crystal end def format_def_args(node : Def | Macro) - block_arg = node.block_arg yields = node.is_a?(Def) && !node.block_arity.nil? format_def_args node.args, node.block_arg, node.splat_index, false, node.double_splat, yields end