diff options
author | Kevin Newton <[email protected]> | 2023-12-01 12:22:01 -0500 |
---|---|---|
committer | git <[email protected]> | 2023-12-01 20:53:34 +0000 |
commit | 492c82cb417a92d1941f10b52e77ec0c4b2cc8a6 (patch) | |
tree | 3358d814456f46c6adb80921e968d1fb5258ce04 /lib | |
parent | b77551adee831302f22dc7d9fdccd597923511c4 (diff) |
[ruby/prism] Prism.parse_success?(source)
A lot of tools use Ripper/RubyVM::AbstractSyntaxTree to determine
if a source is valid. These tools both create an AST instead of
providing an API that will return a boolean only.
This new API only creates the C structs, but doesn't bother
reifying them into Ruby/the serialization API. Instead it only
returns true/false, which is significantly more efficient.
https://github.com/ruby/prism/commit/7014740118
Diffstat (limited to 'lib')
-rw-r--r-- | lib/prism.rb | 16 | ||||
-rw-r--r-- | lib/prism/ffi.rb | 15 |
2 files changed, 30 insertions, 1 deletions
diff --git a/lib/prism.rb b/lib/prism.rb index 909b71d66d..b9e615df6c 100644 --- a/lib/prism.rb +++ b/lib/prism.rb @@ -64,6 +64,22 @@ module Prism def self.load(source, serialized) Serialize.load(source, serialized) end + + # :call-seq: + # Prism::parse_failure?(source, **options) -> bool + # + # Returns true if the source is invalid Ruby code. + def self.parse_failure?(source, **options) + !parse_success?(source, **options) + end + + # :call-seq: + # Prism::parse_file_failure?(filepath, **options) -> bool + # + # Returns true if the file at filepath is invalid Ruby code. + def self.parse_file_failure?(filepath, **options) + !parse_file_success?(filepath, **options) + end end require_relative "prism/node" diff --git a/lib/prism/ffi.rb b/lib/prism/ffi.rb index 36f1c398de..8324f722a7 100644 --- a/lib/prism/ffi.rb +++ b/lib/prism/ffi.rb @@ -72,7 +72,8 @@ module Prism "pm_serialize_parse", "pm_serialize_parse_comments", "pm_serialize_lex", - "pm_serialize_parse_lex" + "pm_serialize_parse_lex", + "pm_parse_success_p" ) load_exported_functions_from( @@ -268,6 +269,18 @@ module Prism end end + # Mirror the Prism.parse_success? API by using the serialization API. + def parse_success?(code, **options) + LibRubyParser.pm_parse_success_p(code, code.bytesize, dump_options(options)) + end + + # Mirror the Prism.parse_file_success? API by using the serialization API. + def parse_file_success?(filepath, **options) + LibRubyParser::PrismString.with(filepath) do |string| + parse_success?(string.read, **options, filepath: filepath) + end + end + private # Convert the given options into a serialized options string. |