Skip to content

Commit 77a6ae4

Browse files
gazayasbyroot
authored andcommitted
Use Prism for ParserExtractor in SourceAnnotationExtractor
1 parent 5544762 commit 77a6ae4

File tree

1 file changed

+31
-14
lines changed

1 file changed

+31
-14
lines changed

railties/lib/rails/source_annotation_extractor.rb

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
# frozen_string_literal: true
22

3-
require "ripper"
3+
begin
4+
require "prism"
5+
rescue LoadError
6+
# If Prism isn't available (because of using an older Ruby version) then we'll
7+
# define a fallback for the ParserExtractor using ripper.
8+
require "ripper"
9+
end
410

511
module Rails
612
# Implements the logic behind +Rails::Command::NotesCommand+. See <tt>rails notes --help</tt> for usage information.
@@ -16,24 +22,35 @@ class SourceAnnotationExtractor
1622
# Wraps a regular expression that will be tested against each of the source
1723
# file's comments.
1824
class ParserExtractor < Struct.new(:pattern)
19-
class Parser < Ripper
20-
attr_reader :comments, :pattern
25+
if defined?(Prism)
26+
def annotations(file)
27+
result = Prism.parse_file(file)
28+
return [] unless result.success?
2129

22-
def initialize(source, pattern:)
23-
super(source)
24-
@pattern = pattern
25-
@comments = []
30+
result.comments.filter_map do |comment|
31+
Annotation.new(comment.location.start_line, $1, $2) if comment.location.slice =~ pattern
32+
end
2633
end
34+
else
35+
class Parser < Ripper
36+
attr_reader :comments, :pattern
37+
38+
def initialize(source, pattern:)
39+
super(source)
40+
@pattern = pattern
41+
@comments = []
42+
end
2743

28-
def on_comment(value)
29-
@comments << Annotation.new(lineno, $1, $2) if value =~ pattern
44+
def on_comment(value)
45+
@comments << Annotation.new(lineno, $1, $2) if value =~ pattern
46+
end
3047
end
31-
end
3248

33-
def annotations(file)
34-
contents = File.read(file, encoding: Encoding::BINARY)
35-
parser = Parser.new(contents, pattern: pattern).tap(&:parse)
36-
parser.error? ? [] : parser.comments
49+
def annotations(file)
50+
contents = File.read(file, encoding: Encoding::BINARY)
51+
parser = Parser.new(contents, pattern: pattern).tap(&:parse)
52+
parser.error? ? [] : parser.comments
53+
end
3754
end
3855
end
3956

0 commit comments

Comments
 (0)