From e18d4565c0733f7b8fb909c3f47592b1143d6053 Mon Sep 17 00:00:00 2001 From: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Wed, 14 Aug 2024 18:31:38 +0200 Subject: [PATCH] Fix parsing erb with bare `yield` (#2444) Parse erb documents in an eval context Some things that are valid in erb would not be valid in a standalone ruby file. This particularly impacts `yield`. Instead treat the provided code as being evaled Closes #2442 --- lib/ruby_lsp/erb_document.rb | 3 ++- test/erb_document_test.rb | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/ruby_lsp/erb_document.rb b/lib/ruby_lsp/erb_document.rb index 7efc158fb..1a65e72b3 100644 --- a/lib/ruby_lsp/erb_document.rb +++ b/lib/ruby_lsp/erb_document.rb @@ -12,7 +12,8 @@ def parse @needs_parsing = false scanner = ERBScanner.new(@source) scanner.scan - @parse_result = Prism.parse(scanner.ruby) + # assigning empty scopes to turn Prism into eval mode + @parse_result = Prism.parse(scanner.ruby, scopes: [[]]) end sig { override.returns(T::Boolean) } diff --git a/test/erb_document_test.rb b/test/erb_document_test.rb index c445c207d..83f859fe2 100644 --- a/test/erb_document_test.rb +++ b/test/erb_document_test.rb @@ -23,6 +23,27 @@ def test_erb_file_is_properly_parsed ) end + def test_erb_file_parses_in_eval_context + document = RubyLsp::ERBDocument.new(source: +<<~ERB, version: 1, uri: URI("file:///foo.erb")) + + + <%= yield :head %> + + + <%= yield %> + + + ERB + + document.parse + + refute_predicate(document, :syntax_error?) + assert_equal( + " \n \n yield :head \n \n \n yield \n \n \n", + document.parse_result.source.source, + ) + end + def test_erb_document_handles_windows_newlines document = RubyLsp::ERBDocument.new(source: "<%=\r\nbar %>", version: 1, uri: URI("file:///foo.erb")) document.parse