Skip to content

Commit

Permalink
Fix an error when parsing non UTF-8 frozen string
Browse files Browse the repository at this point in the history
This PR fixes the following `FrozenError` when parsing non UTF-8 frozen string:

```console
$ cat example.rb
# encoding: ascii-8bit
# frozen_string_literal: true

require 'rubocop-ast'

RuboCop::AST::ProcessedSource.new('true', 3.2)
```

```console
$ ruby example.rb
/Users/koic/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/rubocop-ast-1.28.0/lib/rubocop/ast/processed_source.rb:30:
in `force_encoding': can't modify frozen String: "true" (FrozenError)
from /Users/koic/.rbenv/versions/3.2.1/lib/ruby/gems/3.2.0/gems/rubocop-ast-1.28.0/lib/rubocop/ast/processed_source.rb:30:
in `initialize'
from example.rb:6:in `new'
from example.rb:6:in `<main>'
```
  • Loading branch information
koic authored and marcandre committed May 2, 2023
1 parent 94a202e commit 934fc2c
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
@@ -0,0 +1 @@
* [#262](https://github.com/rubocop/rubocop-ast/pull/262): Fix an error when parsing non UTF-8 frozen string. ([@koic][])
2 changes: 1 addition & 1 deletion lib/rubocop/ast/processed_source.rb
Expand Up @@ -27,7 +27,7 @@ def initialize(source, ruby_version, path = nil)
# Defaults source encoding to UTF-8, regardless of the encoding it has
# been read with, which could be non-utf8 depending on the default
# external encoding.
source.force_encoding(Encoding::UTF_8) unless source.encoding == Encoding::UTF_8
(+source).force_encoding(Encoding::UTF_8) unless source.encoding == Encoding::UTF_8

@raw_source = source
@path = path
Expand Down
10 changes: 10 additions & 0 deletions spec/rubocop/ast/processed_source_spec.rb
Expand Up @@ -17,6 +17,16 @@ def some_method
let(:source) { "# \xf9" }
end

describe '#initialize' do
context 'when parsing non UTF-8 frozen string' do
let(:source) { (+'true').force_encoding(Encoding::ASCII_8BIT).freeze }

it 'returns an instance of ProcessedSource' do
is_expected.to be_a(described_class)
end
end
end

describe '.from_file' do
describe 'when the file exists' do
around do |example|
Expand Down

0 comments on commit 934fc2c

Please sign in to comment.