diff --git a/ext/prism/extension.c b/ext/prism/extension.c index 5b9fedfa8d..b0276bc578 100644 --- a/ext/prism/extension.c +++ b/ext/prism/extension.c @@ -226,18 +226,26 @@ options_version_set_nearest(pm_options_t *options) { } } +struct build_options_data { + pm_options_t *options; + VALUE keywords; + VALUE filepath; +}; + /** * An iterator function that is called for each key-value in the keywords hash. */ static int build_options_i(VALUE key, VALUE value, VALUE argument) { - pm_options_t *options = (pm_options_t *) argument; + struct build_options_data *data = (struct build_options_data *) argument; + pm_options_t *options = data->options; ID key_id = SYM2ID(key); if (key_id == rb_id_option_filepath) { if (!NIL_P(value)) { - const char *filepath = check_string(value); - pm_options_filepath_set(options, filepath, RSTRING_LEN(value)); + check_string(value); + /* A positional filepath takes precedence over the keyword. */ + if (NIL_P(data->filepath)) data->filepath = value; } } else if (key_id == rb_id_option_encoding) { if (!NIL_P(value)) { @@ -342,62 +350,50 @@ build_options_i(VALUE key, VALUE value, VALUE argument) { } /** - * We need a struct here to pass through rb_protect and it has to be a single - * value. Because the sizeof(VALUE) == sizeof(void *), we're going to pass this - * through as an opaque pointer and cast it on both sides. - */ -struct build_options_data { - pm_options_t *options; - VALUE keywords; -}; - -/** - * Build the set of options from the given keywords. Note that this can raise a - * Ruby error if the options are not valid. + * Build the options and return the Ruby string that owns the filepath bytes. */ static VALUE build_options(VALUE argument) { struct build_options_data *data = (struct build_options_data *) argument; - rb_hash_foreach(data->keywords, build_options_i, (VALUE) data->options); - return Qnil; + if (!NIL_P(data->keywords)) rb_hash_foreach(data->keywords, build_options_i, argument); + if (NIL_P(data->filepath)) return Qnil; + + /* + * Option conversions can change the string. Take its bytes once they have + * finished, and keep them stable across any callbacks during parsing. + */ + VALUE filepath = rb_str_new_frozen(data->filepath); + pm_options_filepath_set(data->options, RSTRING_PTR(filepath), RSTRING_LEN(filepath)); + return filepath; } /** * Extract the options from the given keyword arguments. */ -static void +static VALUE extract_options(pm_options_t *options, VALUE filepath, VALUE keywords) { pm_options_line_set(options, 1); /* default */ options_version_set_nearest(options); /* default */ - if (!NIL_P(keywords)) { - struct build_options_data data = { .options = options, .keywords = keywords }; - struct build_options_data *argument = &data; + if (NIL_P(keywords) && NIL_P(filepath)) return Qnil; - int state = 0; - rb_protect(build_options, (VALUE) argument, &state); + struct build_options_data data = { .options = options, .keywords = keywords, .filepath = filepath }; + int state = 0; - if (state != 0) { - pm_options_free(options); - rb_jump_tag(state); - } + VALUE snapshot = rb_protect(build_options, (VALUE) &data, &state); + if (state != 0) { + pm_options_free(options); + rb_jump_tag(state); } - if (!NIL_P(filepath)) { - if (!RB_TYPE_P(filepath, T_STRING)) { - pm_options_free(options); - rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected String)", rb_obj_class(filepath)); - } - - pm_options_filepath_set(options, RSTRING_PTR(filepath), RSTRING_LEN(filepath)); - } + return snapshot; } /** * Read options for methods that look like (source, **options). */ static VALUE -string_options(int argc, VALUE *argv, pm_options_t *options) { +string_options(int argc, VALUE *argv, pm_options_t *options, VALUE *filepath) { VALUE string; VALUE keywords; rb_scan_args(argc, argv, "1:", &string, &keywords); @@ -407,7 +403,7 @@ string_options(int argc, VALUE *argv, pm_options_t *options) { rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected String)", rb_obj_class(string)); } - extract_options(options, Qnil, keywords); + *filepath = extract_options(options, Qnil, keywords); return string; } @@ -427,8 +423,7 @@ file_options(int argc, VALUE *argv, pm_options_t *options, VALUE *encoded_filepa rb_jump_tag(state); } - *encoded_filepath = rb_str_encode_ospath(filepath); - extract_options(options, *encoded_filepath, keywords); + *encoded_filepath = extract_options(options, rb_str_encode_ospath(filepath), keywords); const char *source = (const char *) pm_string_source(pm_options_filepath(options)); pm_source_init_result_t result; @@ -565,7 +560,8 @@ dump_input(const uint8_t *input, size_t input_length, const pm_options_t *option static VALUE dump(int argc, VALUE *argv, VALUE self) { pm_options_t *options = pm_options_new(); - VALUE string = string_options(argc, argv, options); + VALUE filepath; + VALUE string = string_options(argc, argv, options, &filepath); const uint8_t *source = (const uint8_t *) RSTRING_PTR(string); size_t length = RSTRING_LEN(string); @@ -587,6 +583,7 @@ dump(int argc, VALUE *argv, VALUE self) { #endif pm_options_free(options); + RB_GC_GUARD(filepath); return result_get(result); } @@ -608,6 +605,7 @@ dump_file(int argc, VALUE *argv, VALUE self) { result_t result = dump_input(pm_source_source(src), pm_source_length(src), options, rb_enc_get(encoded_filepath)); pm_source_free(src); pm_options_free(options); + RB_GC_GUARD(encoded_filepath); return result_get(result); } @@ -1039,10 +1037,12 @@ parse_lex_input(const uint8_t *input, size_t input_length, const pm_options_t *o static VALUE lex(int argc, VALUE *argv, VALUE self) { pm_options_t *options = pm_options_new(); - VALUE string = string_options(argc, argv, options); + VALUE filepath; + VALUE string = string_options(argc, argv, options, &filepath); result_t result = parse_lex_input((const uint8_t *) RSTRING_PTR(string), RSTRING_LEN(string), options, NULL, false); pm_options_free(options); + RB_GC_GUARD(filepath); return result_get(result); } @@ -1065,6 +1065,7 @@ lex_file(int argc, VALUE *argv, VALUE self) { result_t result = parse_lex_input(pm_source_source(src), pm_source_length(src), options, rb_enc_get(encoded_filepath), false); pm_source_free(src); pm_options_free(options); + RB_GC_GUARD(encoded_filepath); return result_get(result); } @@ -1173,7 +1174,8 @@ parse_input(const uint8_t *input, size_t input_length, const pm_options_t *optio static VALUE parse(int argc, VALUE *argv, VALUE self) { pm_options_t *options = pm_options_new(); - VALUE string = string_options(argc, argv, options); + VALUE filepath; + VALUE string = string_options(argc, argv, options, &filepath); const uint8_t *source = (const uint8_t *) RSTRING_PTR(string); size_t length = RSTRING_LEN(string); @@ -1195,6 +1197,7 @@ parse(int argc, VALUE *argv, VALUE self) { #endif pm_options_free(options); + RB_GC_GUARD(filepath); return result_get(result); } @@ -1216,6 +1219,7 @@ parse_file(int argc, VALUE *argv, VALUE self) { result_t result = parse_input(pm_source_source(src), pm_source_length(src), options, rb_enc_get(encoded_filepath)); pm_source_free(src); pm_options_free(options); + RB_GC_GUARD(encoded_filepath); return result_get(result); } @@ -1249,10 +1253,12 @@ profile_input(const uint8_t *input, size_t input_length, const pm_options_t *opt static VALUE profile(int argc, VALUE *argv, VALUE self) { pm_options_t *options = pm_options_new(); - VALUE string = string_options(argc, argv, options); + VALUE filepath; + VALUE string = string_options(argc, argv, options, &filepath); result_t result = profile_input((const uint8_t *) RSTRING_PTR(string), RSTRING_LEN(string), options, NULL); pm_options_free(options); + RB_GC_GUARD(filepath); result_get(result); return Qnil; @@ -1277,6 +1283,7 @@ profile_file(int argc, VALUE *argv, VALUE self) { result_t result = profile_input(pm_source_source(src), pm_source_length(src), options, rb_enc_get(encoded_filepath)); pm_source_free(src); pm_options_free(options); + RB_GC_GUARD(encoded_filepath); result_get(result); return Qnil; @@ -1364,7 +1371,7 @@ parse_stream(int argc, VALUE *argv, VALUE self) { rb_scan_args(argc, argv, "1:", &stream, &keywords); pm_options_t *options = pm_options_new(); - extract_options(options, Qnil, keywords); + VALUE filepath = extract_options(options, Qnil, keywords); pm_source_t *src = pm_source_stream_new((void *) stream, parse_stream_fgets, parse_stream_eof); pm_arena_t *arena = pm_arena_new(); @@ -1393,6 +1400,7 @@ parse_stream(int argc, VALUE *argv, VALUE self) { pm_parser_free(parser); pm_arena_free(arena); pm_options_free(options); + RB_GC_GUARD(filepath); return result_get(result); } @@ -1439,10 +1447,12 @@ parse_input_comments(const uint8_t *input, size_t input_length, const pm_options static VALUE parse_comments(int argc, VALUE *argv, VALUE self) { pm_options_t *options = pm_options_new(); - VALUE string = string_options(argc, argv, options); + VALUE filepath; + VALUE string = string_options(argc, argv, options, &filepath); result_t result = parse_input_comments((const uint8_t *) RSTRING_PTR(string), RSTRING_LEN(string), options, NULL); pm_options_free(options); + RB_GC_GUARD(filepath); return result_get(result); } @@ -1465,6 +1475,7 @@ parse_file_comments(int argc, VALUE *argv, VALUE self) { result_t result = parse_input_comments(pm_source_source(src), pm_source_length(src), options, rb_enc_get(encoded_filepath)); pm_source_free(src); pm_options_free(options); + RB_GC_GUARD(encoded_filepath); return result_get(result); } @@ -1487,10 +1498,12 @@ parse_file_comments(int argc, VALUE *argv, VALUE self) { static VALUE parse_lex(int argc, VALUE *argv, VALUE self) { pm_options_t *options = pm_options_new(); - VALUE string = string_options(argc, argv, options); + VALUE filepath; + VALUE string = string_options(argc, argv, options, &filepath); result_t result = parse_lex_input((const uint8_t *) RSTRING_PTR(string), RSTRING_LEN(string), options, NULL, true); pm_options_free(options); + RB_GC_GUARD(filepath); return result_get(result); } @@ -1520,6 +1533,7 @@ parse_lex_file(int argc, VALUE *argv, VALUE self) { result_t result = parse_lex_input(pm_source_source(src), pm_source_length(src), options, rb_enc_get(encoded_filepath), true); pm_source_free(src); pm_options_free(options); + RB_GC_GUARD(encoded_filepath); return result_get(result); } @@ -1555,10 +1569,12 @@ parse_input_success_p(const uint8_t *input, size_t input_length, const pm_option static VALUE parse_success_p(int argc, VALUE *argv, VALUE self) { pm_options_t *options = pm_options_new(); - VALUE string = string_options(argc, argv, options); + VALUE filepath; + VALUE string = string_options(argc, argv, options, &filepath); result_t result = parse_input_success_p((const uint8_t *) RSTRING_PTR(string), RSTRING_LEN(string), options, NULL); pm_options_free(options); + RB_GC_GUARD(filepath); return result_get(result); } @@ -1594,6 +1610,7 @@ parse_file_success_p(int argc, VALUE *argv, VALUE self) { result_t result = parse_input_success_p(pm_source_source(src), pm_source_length(src), options, rb_enc_get(encoded_filepath)); pm_source_free(src); pm_options_free(options); + RB_GC_GUARD(encoded_filepath); return result_get(result); } diff --git a/lib/prism/ffi.rb b/lib/prism/ffi.rb index 205042b16f..f11ec66f87 100644 --- a/lib/prism/ffi.rb +++ b/lib/prism/ffi.rb @@ -210,8 +210,6 @@ def read # Yields a PrismSource backed by the given string to the block. def self.with_string(string) - raise TypeError unless string.is_a?(String) - length = string.bytesize # + 1 to never get an address of 0, which pm_parser_init() asserts FFI::MemoryPointer.new(:char, length + 1, false) do |pointer| @@ -222,22 +220,22 @@ def self.with_string(string) end end - # Yields a PrismSource to the given block, backed by a pm_source_t. - def self.with_file(filepath, options) - # File.path applies the same coercion and validation as the C - # extension's rb_get_path: it accepts to_path/to_str objects and - # rejects paths containing a NUL byte, which would otherwise truncate - # the path when it is handed to C as a NUL-terminated string. - filepath = File.path(filepath) - options[:filepath] = filepath - - # On Windows and Mac, it's expected that filepaths will be encoded in - # UTF-8. If they are not, we need to convert them to UTF-8 before - # passing them into pm_source_mapped_new. + # Coerce the positional path and encode it for the filesystem. + def self.encode_filepath(filepath) + # File.path can return the caller's mutable string. String.new gives us + # a plain String whose path checks use the built-in methods and whose + # contents stay stable while we convert the keyword options. + filepath = String.new(File.path(filepath)) + raise ArgumentError, "path name contains null byte" if filepath.include?("\0") + if PLATFORM_EXPECTS_UTF8 && (encoding = filepath.encoding) != Encoding::ASCII_8BIT && encoding != Encoding::UTF_8 filepath = filepath.encode(Encoding::UTF_8) end + filepath + end + # Yields a PrismSource to the given block, backed by a pm_source_t. + def self.with_file(filepath) FFI::MemoryPointer.new(:int) do |result_ptr| pm_source = LibRubyParser.pm_source_mapped_new(filepath, 0, result_ptr) @@ -274,39 +272,39 @@ def self.with_file(filepath, options) class << self # Mirror the Prism.dump API by using the serialization API. def dump(source, **options) - LibRubyParser::PrismSource.with_string(source) { |string| dump_common(string, options) } + with_string_options(source, options) { |string, serialized| dump_common(string, serialized) } end # Mirror the Prism.dump_file API by using the serialization API. def dump_file(filepath, **options) - LibRubyParser::PrismSource.with_file(filepath, options) { |string| dump_common(string, options) } + with_file_options(filepath, options) { |string, serialized| dump_common(string, serialized) } end # Mirror the Prism.lex API by using the serialization API. def lex(code, **options) - LibRubyParser::PrismSource.with_string(code) { |string| lex_common(string, code, options) } + with_string_options(code, options) { |string, serialized| lex_common(string, code, serialized) } end # Mirror the Prism.lex_file API by using the serialization API. def lex_file(filepath, **options) - LibRubyParser::PrismSource.with_file(filepath, options) { |string| lex_common(string, string.read, options) } + with_file_options(filepath, options) { |string, serialized| lex_common(string, string.read, serialized) } end # Mirror the Prism.parse API by using the serialization API. def parse(code, **options) - LibRubyParser::PrismSource.with_string(code) { |string| parse_common(string, code, options) } + with_string_options(code, options) { |string, serialized| parse_common(string, code, serialized) } end # Mirror the Prism.parse_file API by using the serialization API. This uses # native strings instead of Ruby strings because it allows us to use mmap # when it is available. def parse_file(filepath, **options) - LibRubyParser::PrismSource.with_file(filepath, options) { |string| parse_common(string, string.read, options) } + with_file_options(filepath, options) { |string, serialized| parse_common(string, string.read, serialized) } end # Mirror the Prism.parse_stream API by using the serialization API. def parse_stream(stream, **options) - format_type = raise_error_format_type(options) + serialized = serialize_options(options) LibRubyParser::PrismBuffer.with do |buffer| # The largest number of bytes a single character can occupy in any @@ -335,12 +333,12 @@ def parse_stream(stream, **options) pm_source = LibRubyParser.pm_source_stream_new(nil, callback, eof_callback) begin - LibRubyParser.pm_serialize_parse_stream(buffer.pointer, pm_source, dump_options(options)) - result = Prism.load(source, buffer.read, options.fetch(:freeze, false)) + LibRubyParser.pm_serialize_parse_stream(buffer.pointer, pm_source, serialized.bytes) + result = Prism.load(source, buffer.read, serialized.freeze_result) - if format_type && result.failure? + if serialized.error_format && result.failure? LibRubyParser::PrismSource.with_string(source) do |string| - raise_error(string, options, format_type) + raise_error(string, serialized) end end @@ -353,29 +351,29 @@ def parse_stream(stream, **options) # Mirror the Prism.parse_comments API by using the serialization API. def parse_comments(code, **options) - LibRubyParser::PrismSource.with_string(code) { |string| parse_comments_common(string, code, options) } + with_string_options(code, options) { |string, serialized| parse_comments_common(string, code, serialized) } end # Mirror the Prism.parse_file_comments API by using the serialization # API. This uses native strings instead of Ruby strings because it allows us # to use mmap when it is available. def parse_file_comments(filepath, **options) - LibRubyParser::PrismSource.with_file(filepath, options) { |string| parse_comments_common(string, string.read, options) } + with_file_options(filepath, options) { |string, serialized| parse_comments_common(string, string.read, serialized) } end # Mirror the Prism.parse_lex API by using the serialization API. def parse_lex(code, **options) - LibRubyParser::PrismSource.with_string(code) { |string| parse_lex_common(string, code, options) } + with_string_options(code, options) { |string, serialized| parse_lex_common(string, code, serialized) } end # Mirror the Prism.parse_lex_file API by using the serialization API. def parse_lex_file(filepath, **options) - LibRubyParser::PrismSource.with_file(filepath, options) { |string| parse_lex_common(string, string.read, options) } + with_file_options(filepath, options) { |string, serialized| parse_lex_common(string, string.read, serialized) } end # Mirror the Prism.parse_success? API by using the serialization API. def parse_success?(code, **options) - LibRubyParser::PrismSource.with_string(code) { |string| parse_file_success_common(string, options) } + with_string_options(code, options) { |string, serialized| parse_file_success_common(string, serialized) } end # Mirror the Prism.parse_failure? API by using the serialization API. @@ -385,7 +383,7 @@ def parse_failure?(code, **options) # Mirror the Prism.parse_file_success? API by using the serialization API. def parse_file_success?(filepath, **options) - LibRubyParser::PrismSource.with_file(filepath, options) { |string| parse_file_success_common(string, options) } + with_file_options(filepath, options) { |string, serialized| parse_file_success_common(string, serialized) } end # Mirror the Prism.parse_file_failure? API by using the serialization API. @@ -395,107 +393,100 @@ def parse_file_failure?(filepath, **options) # Mirror the Prism.profile API by using the serialization API. def profile(source, **options) - LibRubyParser::PrismSource.with_string(source) do |string| - if (format_type = raise_error_format_type(options)) - raise_error(string, options, format_type) - end - - LibRubyParser::PrismBuffer.with do |buffer| - LibRubyParser.pm_serialize_parse(buffer.pointer, string.pointer, string.length, dump_options(options)) - nil - end - end + with_string_options(source, options) { |string, serialized| profile_common(string, serialized) } end # Mirror the Prism.profile_file API by using the serialization API. def profile_file(filepath, **options) - LibRubyParser::PrismSource.with_file(filepath, options) do |string| - if (format_type = raise_error_format_type(options)) - raise_error(string, options, format_type) - end - - LibRubyParser::PrismBuffer.with do |buffer| - LibRubyParser.pm_serialize_parse(buffer.pointer, string.pointer, string.length, dump_options(options)) - nil - end - end + with_file_options(filepath, options) { |string, serialized| profile_common(string, serialized) } end private - def dump_common(string, options) # :nodoc: - if (format_type = raise_error_format_type(options)) - raise_error(string, options, format_type) - end + def with_string_options(source, options) + check_option_type(source, String) + serialized = serialize_options(options) + LibRubyParser::PrismSource.with_string(source) { |string| yield string, serialized } + end - LibRubyParser::PrismBuffer.with do |buffer| - LibRubyParser.pm_serialize_parse(buffer.pointer, string.pointer, string.length, dump_options(options)) + def with_file_options(path, options) + filepath = LibRubyParser::PrismSource.encode_filepath(path) + serialized = serialize_options(options, filepath) + LibRubyParser::PrismSource.with_file(serialized.filepath) { |string| yield string, serialized } + end - dumped = buffer.read - dumped.freeze if options.fetch(:freeze, false) + def profile_common(string, serialized) # :nodoc: + raise_error(string, serialized) if serialized.error_format - dumped + LibRubyParser::PrismBuffer.with do |buffer| + LibRubyParser.pm_serialize_parse(buffer.pointer, string.pointer, string.length, serialized.bytes) + nil end end - def lex_common(string, code, options) # :nodoc: - format_type = raise_error_format_type(options) + def serialize_parse(string, bytes) + LibRubyParser::PrismBuffer.with do |buffer| + LibRubyParser.pm_serialize_parse(buffer.pointer, string.pointer, string.length, bytes) + buffer.read + end + end + + def dump_common(string, serialized) # :nodoc: + raise_error(string, serialized) if serialized.error_format + dumped = serialize_parse(string, serialized.bytes) + dumped.freeze if serialized.freeze_result + dumped + end + + def lex_common(string, code, serialized) # :nodoc: LibRubyParser::PrismBuffer.with do |buffer| - LibRubyParser.pm_serialize_lex(buffer.pointer, string.pointer, string.length, dump_options(options)) - result = Serialize.load_lex(code, buffer.read, options.fetch(:freeze, false)) + LibRubyParser.pm_serialize_lex(buffer.pointer, string.pointer, string.length, serialized.bytes) + result = Serialize.load_lex(code, buffer.read, serialized.freeze_result) - raise_error(string, options, format_type) if format_type && result.failure? + raise_error(string, serialized) if serialized.error_format && result.failure? result end end - def parse_common(string, code, options) # :nodoc: - format_type = raise_error_format_type(options) - serialized = dump_common(string, options) - result = Serialize.load_parse(code, serialized, options.fetch(:freeze, false)) + def parse_common(string, code, serialized) # :nodoc: + dumped = serialize_parse(string, serialized.bytes) + result = Serialize.load_parse(code, dumped, serialized.freeze_result) - raise_error(string, options, format_type) if format_type && result.failure? + raise_error(string, serialized) if serialized.error_format && result.failure? result end - def parse_comments_common(string, code, options) # :nodoc: - if (format_type = raise_error_format_type(options)) - raise_error(string, options, format_type) - end + def parse_comments_common(string, code, serialized) # :nodoc: + raise_error(string, serialized) if serialized.error_format LibRubyParser::PrismBuffer.with do |buffer| - LibRubyParser.pm_serialize_parse_comments(buffer.pointer, string.pointer, string.length, dump_options(options)) - Serialize.load_parse_comments(code, buffer.read, options.fetch(:freeze, false)) + LibRubyParser.pm_serialize_parse_comments(buffer.pointer, string.pointer, string.length, serialized.bytes) + Serialize.load_parse_comments(code, buffer.read, serialized.freeze_result) end end - def parse_lex_common(string, code, options) # :nodoc: - format_type = raise_error_format_type(options) - + def parse_lex_common(string, code, serialized) # :nodoc: LibRubyParser::PrismBuffer.with do |buffer| - LibRubyParser.pm_serialize_parse_lex(buffer.pointer, string.pointer, string.length, dump_options(options)) - result = Serialize.load_parse_lex(code, buffer.read, options.fetch(:freeze, false)) + LibRubyParser.pm_serialize_parse_lex(buffer.pointer, string.pointer, string.length, serialized.bytes) + result = Serialize.load_parse_lex(code, buffer.read, serialized.freeze_result) - raise_error(string, options, format_type) if format_type && result.failure? + raise_error(string, serialized) if serialized.error_format && result.failure? result end end - def parse_file_success_common(string, options) # :nodoc: - format_type = raise_error_format_type(options) - success = LibRubyParser.pm_serialize_parse_success_p(string.pointer, string.length, dump_options(options)) + def parse_file_success_common(string, serialized) # :nodoc: + success = LibRubyParser.pm_serialize_parse_success_p(string.pointer, string.length, serialized.bytes) - raise_error(string, options, format_type) if format_type && !success + raise_error(string, serialized) if serialized.error_format && !success success end - # Extract the raise_error option from the given options hash and convert - # it into the format type that should be used when formatting errors, or - # nil if raising is disabled. - def raise_error_format_type(options) # :nodoc: - case (value = options.delete(:raise_error)) - when nil, false + # Return the format for errors, or nil if raising is disabled. + def raise_error_format_type(value) # :nodoc: + case value + when nil nil when true # When given true, mirror the behavior of CRuby itself: color when @@ -525,9 +516,9 @@ def raise_error_format_type(options) # :nodoc: # Parse the given source and format any errors that are encountered into # an appropriate exception, then raise it. If the source parses without # any errors, then return nil. - def raise_error(string, options, format_type) # :nodoc: + def raise_error(string, serialized) # :nodoc: LibRubyParser::PrismBuffer.with do |buffer| - level = LibRubyParser.pm_serialize_parse_errors_format(buffer.pointer, string.pointer, string.length, dump_options(options), format_type) + level = LibRubyParser.pm_serialize_parse_errors_format(buffer.pointer, string.pointer, string.length, serialized.bytes, serialized.error_format) return if level == -1 encoding_name, _, message = buffer.read.partition("\0") @@ -535,7 +526,7 @@ def raise_error(string, options, format_type) # :nodoc: case level when 0 # syntax error = SyntaxError.new(message.force_encoding(encoding_name)) - error.instance_variable_set(:@path, options.fetch(:filepath, "")) + error.instance_variable_set(:@path, serialized.filepath) raise error when 1 # argument raise ArgumentError, message.force_encoding(encoding_name) @@ -554,10 +545,7 @@ def raise_error(string, options, format_type) # :nodoc: end # Return the value that should be dumped for the command_line option. - def dump_options_command_line(options) - command_line = options.fetch(:command_line, "") - raise ArgumentError, "command_line must be a string" unless command_line.is_a?(String) - + def dump_options_command_line(command_line) command_line.each_char.inject(0) do |value, char| case char when "a" then value | 0b000001 @@ -606,111 +594,160 @@ def version_string_to_number(version) end end - # The set of options that are understood by the parsing APIs. Note that - # raise_error is not listed here because it is deleted from the options - # hash by raise_error_format_type before the options are dumped. - DUMP_OPTIONS_KEYS = [:attach_comments, :command_line, :encoding, :filepath, :freeze, :frozen_string_literal, :line, :main_script, :partial_script, :scopes, :version].freeze - private_constant :DUMP_OPTIONS_KEYS - - # Convert the given options into a serialized options string. - def dump_options(options) - unknown_keys = options.keys - DUMP_OPTIONS_KEYS - raise ArgumentError, "unknown keyword: #{unknown_keys.first}" unless unknown_keys.empty? - - template = +"" - values = [] - - template << "L" - if (filepath = options[:filepath]) - values.push(filepath.bytesize, filepath.b) - template << "A*" - else - values << 0 + def check_option_type(value, type) + unless type === value + actual = Kernel.instance_method(:class).bind_call(value) + raise TypeError, "wrong argument type #{actual} (expected #{type})" end + value + end - template << "l" - values << options.fetch(:line, 1) - - template << "L" - if (encoding = options[:encoding]) - name = encoding.is_a?(Encoding) ? encoding.name : encoding - values.push(name.bytesize, name.b) - template << "A*" - else - values << 0 - end - - template << "C" - values << (options.fetch(:frozen_string_literal, false) ? 1 : 0) - - template << "C" - values << dump_options_command_line(options) - - template << "C" - values << dump_options_version(options[:version]) + def option_string_bytes(value) + String.instance_method(:b).bind_call(check_option_type(value, String)) + end - template << "C" - values << (options[:encoding] == false ? 1 : 0) + def options_line(value) + line = + if Integer === value + value + elsif Integer.respond_to?(:try_convert) + Integer.try_convert(value) + elsif Kernel.instance_method(:respond_to?).bind_call(value, :to_int, true) # Ruby < 3.1 + value.__send__(:to_int) + end - template << "C" - values << (options.fetch(:main_script, false) ? 1 : 0) + if nil.equal?(line) + actual = Kernel.instance_method(:class).bind_call(value) + raise TypeError, "no implicit conversion of #{actual} into Integer" + end - template << "C" - values << (options.fetch(:partial_script, false) ? 1 : 0) + check_option_type(line, Integer) + raise RangeError, "line number out of range: #{line}" unless (-2**31...2**31).cover?(line) - template << "C" - values << (options.fetch(:freeze, false) ? 1 : 0) + line + end - template << "C" - values << (options.fetch(:attach_comments, false) ? 1 : 0) + def dump_options_scopes(scopes) + scopes = Array.new(check_option_type(scopes, Array)) + bytes = [scopes.length].pack("L") - template << "L" - if (scopes = options[:scopes]) - values << scopes.length + scopes.each do |scope| + forwarding = 0 - scopes.each do |scope| - locals = nil - forwarding = 0 + case scope + when Array + locals = scope + when Scope + locals = check_option_type(Scope.instance_method(:locals).bind_call(scope), Array) + names = check_option_type(Scope.instance_method(:forwarding).bind_call(scope), Array) - case scope - when Array - locals = scope - when Scope - locals = scope.locals + Array.new(names).each do |forward| + check_option_type(forward, Symbol) - scope.forwarding.each do |forward| - case forward - when :* then forwarding |= 0x1 - when :** then forwarding |= 0x2 - when :& then forwarding |= 0x4 - when :"..." then forwarding |= 0x8 - else raise ArgumentError, "invalid forwarding value: #{forward}" - end + case forward + when :* then forwarding |= 0x1 + when :** then forwarding |= 0x2 + when :& then forwarding |= 0x4 + when :"..." then forwarding |= 0x8 + else raise ArgumentError, "invalid forwarding value: #{forward}" end - else - raise TypeError, "wrong argument type #{scope.class.inspect} (expected Array or Prism::Scope)" end + else + raise TypeError, "wrong argument type #{scope.class} (expected Array or Prism::Scope)" + end - template << "L" - values << locals.length - - template << "C" - values << forwarding + locals = Array.new(locals) + bytes << [locals.length, forwarding].pack("LC") - locals.each do |local| - name = local.name - template << "L" - values << name.bytesize + locals.each do |local| + name = check_option_type(local, Symbol).to_s + bytes << [name.bytesize, name].pack("La*") + end + end - template << "A*" - values << name.b + bytes + end + + SerializedOptions = Struct.new(:bytes, :error_format, :filepath, :freeze_result) + private_constant :SerializedOptions + + # Convert each option when it is visited, just as build_options_i does in + # the native extension. The wire format has its own fixed field order. + def serialize_options(options, filepath = nil) + line = 1 + encoding = "" + encoding_locked = 0 + frozen_string_literal = 0 + command_line = 0 + version = nil + main_script = 0 + partial_script = 0 + freeze_result = false + attach_comments = 0 + scopes = nil + format_type = nil + + options.each do |key, value| + case key + when :filepath + unless nil.equal?(value) + check_option_type(value, String) + filepath ||= value end + when :line + line = options_line(value) unless nil.equal?(value) + when :encoding + if false.equal?(value) + encoding_locked = 1 + elsif !nil.equal?(value) + encoding = Encoding.find(value)&.name || "" + end + when :frozen_string_literal + frozen_string_literal = value ? 1 : -1 unless nil.equal?(value) + when :command_line + command_line = dump_options_command_line(option_string_bytes(value)) unless nil.equal?(value) + when :version + version = dump_options_version(option_string_bytes(value)) unless nil.equal?(value) + when :scopes + scopes = dump_options_scopes(value) unless nil.equal?(value) + when :raise_error + format_type = raise_error_format_type(value) + when :main_script + main_script = value ? 1 : 0 + when :partial_script + partial_script = value ? 1 : 0 + when :freeze + freeze_result = value ? true : false + when :attach_comments + attach_comments = value ? 1 : 0 + else + check_option_type(key, Symbol) + raise ArgumentError, "unknown keyword: #{key}" end - else - values << 0 end - values.pack(template) + # Option conversions may have changed the filepath. Snapshot it now with + # String.new so packing uses the built-in bytesize even if the caller's + # String subclass overrides it. + filepath = filepath ? String.new(filepath) : "" + bytes = [ + filepath.bytesize, + filepath, + line, + encoding.bytesize, + encoding, + frozen_string_literal, + command_line, + version || dump_options_version(nil), + encoding_locked, + main_script, + partial_script, + freeze_result ? 1 : 0, + attach_comments + ].pack("L a* l L a* c C7") + + bytes << (scopes || [0].pack("L")) + SerializedOptions.new(bytes, format_type, filepath, freeze_result) end end diff --git a/test/prism/api/parse_test.rb b/test/prism/api/parse_test.rb index 06993ff12c..e6d36e084d 100644 --- a/test/prism/api/parse_test.rb +++ b/test/prism/api/parse_test.rb @@ -93,6 +93,22 @@ def test_parse_preserves_embedded_nul_in_filepath assert_equal filepath, Prism.parse_statement("__FILE__", filepath: filepath).filepath end + def test_filepath_reflects_changes_during_option_conversion + filepath = +"" + line = Object.new + line.define_singleton_method(:to_int) do + filepath << "test.rb" + 7 + end + + [{ filepath: filepath, line: line }, { line: line, filepath: filepath }].each do |options| + filepath.clear + node = Prism.parse_statement("__FILE__", **options) + assert_equal "test.rb", node.filepath + assert_equal 7, node.location.start_line + end + end + def test_parse_takes_line line = 4 result = Prism.parse("def foo\n __FILE__\nend", line: line) @@ -104,6 +120,67 @@ def test_parse_takes_line assert_equal line, result.value.first.location.start_line end + def test_encoding_conversion_observes_earlier_options + name = +"US-ASCII" + calls = [] + encoding = Object.new + encoding.define_singleton_method(:to_str) do + calls << :to_str + name + end + line = Object.new + line.define_singleton_method(:to_int) do + calls << :to_int + name.replace("UTF-8") + 1 + end + + assert_equal Encoding::US_ASCII, Prism.parse("1", encoding: encoding, line: line).source.source.encoding + assert_equal [:to_str, :to_int], calls + + calls.clear + name.replace("US-ASCII") + assert_equal Encoding::UTF_8, Prism.parse("1", line: line, encoding: encoding).source.source.encoding + assert_equal [:to_int, :to_str], calls + end + + def test_invalid_keyword_stops_option_conversion + calls = 0 + line = Object.new + line.define_singleton_method(:to_int) { calls += 1 } + + assert_raise(ArgumentError) { Prism.parse("1", unknown: nil, line: line) } + assert_equal 0, calls + assert_raise(ArgumentError) { Prism.parse("1", line: line, unknown: nil) } + assert_equal 1, calls + end + + def test_positional_source_is_read_after_option_conversion + source = +"1" + line = Object.new + line.define_singleton_method(:to_int) do + source.replace("2") + 1 + end + + assert_equal 2, Prism.parse_statement(source, line: line).value + end + + def test_line_conversion_checks_the_signed_32_bit_range + line = Object.new + line.define_singleton_method(:to_int) { 2**31 } + assert_raise(RangeError) { Prism.parse("1", line: line) } + assert_raise(TypeError) { Prism.parse("1", line: "7") } + assert_equal 1, Prism.parse("1", line: nil).value.location.start_line + end + + def test_file_options_are_checked_before_opening_the_file + Dir.mktmpdir do |dir| + missing = File.join(dir, "missing.rb") + assert_raise(TypeError) { Prism.parse_file(missing, filepath: 42) } + end + end + def test_parse_takes_negative_lines line = -2 result = Prism.parse("def foo\n __FILE__\nend", line: line) diff --git a/test/prism/api/raise_error_test.rb b/test/prism/api/raise_error_test.rb index b72a92f29b..5f03736d86 100644 --- a/test/prism/api/raise_error_test.rb +++ b/test/prism/api/raise_error_test.rb @@ -28,6 +28,24 @@ def test_syntax_error_single assert_syntax_error_path "single.rb", error end + def test_stream_error_uses_the_original_parse_options + filepath = +"one.rb" + calls = 0 + line = Object.new + line.define_singleton_method(:to_int) { calls += 1 } + + stream = StringIO.new(")\n") + stream.define_singleton_method(:gets) do |limit| + filepath.upcase! + super(limit) + end + + error = assert_raise(SyntaxError) { Prism.parse_stream(stream, filepath: filepath, line: line, raise_error: :plain) } + assert_include error.message, "one.rb:1:" + assert_syntax_error_path "one.rb", error + assert_equal 1, calls + end + def test_syntax_error_multiple error = assert_raise(SyntaxError) { Prism.parse("foo = 1 +\n", raise_error: :plain, filepath: "test.rb") } assert_includes error.message, "syntax errors found" @@ -52,6 +70,35 @@ def test_syntax_error_true assert_raise(SyntaxError) { Prism.parse("foo = 1 +\n", raise_error: true) } end + def test_line_and_raise_error_callbacks_follow_keyword_order + original_stderr = $stderr + $stderr = StringIO.new + calls = [] + number = 7 + $stderr.define_singleton_method(:tty?) do + calls << :tty? + number = 9 + false + end + line = Object.new + line.define_singleton_method(:to_int) do + calls << :to_int + number + end + + result = Prism.parse("1", line: line, raise_error: true) + assert_equal [:to_int, :tty?], calls + assert_equal 7, result.value.location.start_line + + number = 7 + calls.clear + result = Prism.parse("1", raise_error: true, line: line) + assert_equal [:tty?, :to_int], calls + assert_equal 9, result.value.location.start_line + ensure + $stderr = original_stderr + end + def test_syntax_error_style error = assert_raise(SyntaxError) { Prism.parse("foo = 1 +\n", raise_error: :style) } assert_include error.message, "\e[m"