Skip to main content

ruby_prism/
lib.rs

1//! # ruby-prism
2//!
3//! Rustified version of Ruby's prism parser.
4//!
5#![warn(clippy::all, clippy::nursery, clippy::pedantic, future_incompatible, missing_docs, nonstandard_style, rust_2018_idioms, trivial_casts, trivial_numeric_casts, unreachable_pub, unused_qualifications)]
6
7// Most of the code in this file is generated, so sometimes it generates code
8// that doesn't follow the clippy rules. We don't want to see those warnings.
9#[allow(clippy::too_many_lines, clippy::use_self)]
10mod bindings {
11    use std::ptr::NonNull;
12
13    // In `build.rs`, we generate bindings based on the config.yml file. Here is
14    // where we pull in those bindings and make them part of our library.
15    include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
16}
17
18mod node;
19mod node_ext;
20mod parse_result;
21mod string_query;
22
23use std::ffi::CString;
24use std::ptr::NonNull;
25
26pub use self::bindings::*;
27pub use self::node::{ConstantId, ConstantList, ConstantListIter, Integer, NodeList, NodeListIter};
28pub use self::node_ext::{ConstantPathError, FullName};
29pub use self::parse_result::{Comment, CommentType, Comments, Diagnostic, Diagnostics, Location, MagicComment, MagicComments, NodeComments, ParseResult};
30pub use self::string_query::{InvalidEncodingError, StringQuery};
31
32use ruby_prism_sys::{
33    pm_arena_new, pm_options_attach_comments_set, pm_options_command_line_set, pm_options_encoding_locked_set, pm_options_encoding_set, pm_options_filepath_set, pm_options_free, pm_options_frozen_string_literal_set, pm_options_line_set, pm_options_main_script_set, pm_options_new,
34    pm_options_partial_script_set, pm_options_scope_forwarding_set, pm_options_scope_init, pm_options_scope_local_mut, pm_options_scope_mut, pm_options_scopes_init, pm_options_t, pm_options_version_set, pm_parse, pm_parser_new, pm_string_init,
35};
36
37/// The version of Ruby syntax to parse with.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Version {
40    /// Use the latest version of prism.
41    Latest,
42    /// The vendored version of prism in `CRuby` 3.3.x.
43    CRuby3_3,
44    /// The vendored version of prism in `CRuby` 3.4.x.
45    CRuby3_4,
46    /// The vendored version of prism in `CRuby` 4.0.x, formerly known as 3.5.x.
47    #[deprecated(note = "Use Version::CRuby4_0 instead", since = "2.1.0")]
48    CRuby3_5,
49    /// The vendored version of prism in `CRuby` 4.0.x.
50    CRuby4_0,
51    /// The vendored version of prism in `CRuby` 4.1.x.
52    CRuby4_1,
53}
54
55impl Version {
56    /// Returns the version string that prism's C functions take for this
57    /// version, or `None` for `Latest`, which they take as `NULL`.
58    const fn as_str(self) -> Option<&'static str> {
59        match self {
60            Self::Latest => None,
61            Self::CRuby3_3 => Some("3.3"),
62            Self::CRuby3_4 => Some("3.4"),
63            #[allow(deprecated)]
64            Self::CRuby3_5 | Self::CRuby4_0 => Some("4.0"),
65            Self::CRuby4_1 => Some("4.1"),
66        }
67    }
68
69    /// Calls `pm_options_version_set` with the appropriate version string.
70    /// `Latest` needs no call, since the parser uses the latest version when
71    /// none is set.
72    unsafe fn set_on(self, opts: *mut pm_options_t) {
73        if let Some(version) = self.as_str() {
74            pm_options_version_set(opts, version.as_ptr().cast(), version.len());
75        }
76    }
77}
78
79/// A command line option that affects parsing behavior.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
81pub enum CommandLineFlag {
82    /// `-a`: splits the input line `$_` into `$F`.
83    A,
84    /// `-e`: specifies a script to be executed.
85    E,
86    /// `-l`: chomps the input line by default.
87    L,
88    /// `-n`: wraps the script in a `while gets` loop.
89    N,
90    /// `-p`: prints the value of `$_` at the end of each loop.
91    P,
92    /// `-x`: searches the input file for a shebang.
93    X,
94}
95
96impl From<CommandLineFlag> for u8 {
97    fn from(flag: CommandLineFlag) -> Self {
98        match flag {
99            CommandLineFlag::A => ruby_prism_sys::PM_OPTIONS_COMMAND_LINE_A,
100            CommandLineFlag::E => ruby_prism_sys::PM_OPTIONS_COMMAND_LINE_E,
101            CommandLineFlag::L => ruby_prism_sys::PM_OPTIONS_COMMAND_LINE_L,
102            CommandLineFlag::N => ruby_prism_sys::PM_OPTIONS_COMMAND_LINE_N,
103            CommandLineFlag::P => ruby_prism_sys::PM_OPTIONS_COMMAND_LINE_P,
104            CommandLineFlag::X => ruby_prism_sys::PM_OPTIONS_COMMAND_LINE_X,
105        }
106    }
107}
108
109/// A forwarding parameter for a scope.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
111pub enum ScopeForwardingFlag {
112    /// Forwarding with the `*` parameter.
113    Positionals,
114    /// Forwarding with the `**` parameter.
115    Keywords,
116    /// Forwarding with the `&` parameter.
117    Block,
118    /// Forwarding with the `...` parameter.
119    All,
120}
121
122impl From<ScopeForwardingFlag> for u8 {
123    fn from(flag: ScopeForwardingFlag) -> Self {
124        match flag {
125            ScopeForwardingFlag::Positionals => ruby_prism_sys::PM_OPTIONS_SCOPE_FORWARDING_POSITIONALS,
126            ScopeForwardingFlag::Keywords => ruby_prism_sys::PM_OPTIONS_SCOPE_FORWARDING_KEYWORDS,
127            ScopeForwardingFlag::Block => ruby_prism_sys::PM_OPTIONS_SCOPE_FORWARDING_BLOCK,
128            ScopeForwardingFlag::All => ruby_prism_sys::PM_OPTIONS_SCOPE_FORWARDING_ALL,
129        }
130    }
131}
132
133/// A scope of locals surrounding the code that is being parsed.
134#[derive(Debug, Clone, Default)]
135pub struct Scope {
136    locals: Vec<Vec<u8>>,
137    forwarding: Vec<ScopeForwardingFlag>,
138}
139
140impl Scope {
141    /// Sets the local variable names in this scope.
142    #[must_use]
143    pub fn locals(mut self, locals: Vec<Vec<u8>>) -> Self {
144        self.locals = locals;
145        self
146    }
147
148    /// Sets the forwarding parameters in this scope.
149    #[must_use]
150    pub fn forwarding(mut self, forwarding: Vec<ScopeForwardingFlag>) -> Self {
151        self.forwarding = forwarding;
152        self
153    }
154}
155
156/// Options that can be passed to the parser.
157#[allow(clippy::struct_excessive_bools)]
158#[derive(Debug, Clone, Default)]
159pub struct Options {
160    filepath: Option<String>,
161    line: Option<i32>,
162    encoding: Option<String>,
163    encoding_locked: bool,
164    frozen_string_literal: Option<bool>,
165    command_line: Vec<CommandLineFlag>,
166    version: Option<Version>,
167    main_script: bool,
168    partial_script: bool,
169    attach_comments: bool,
170    scopes: Vec<Scope>,
171}
172
173impl Options {
174    /// Sets the filepath option.
175    #[must_use]
176    pub fn filepath(mut self, filepath: &str) -> Self {
177        self.filepath = Some(filepath.to_string());
178        self
179    }
180
181    /// Sets the line option.
182    #[must_use]
183    pub const fn line(mut self, line: i32) -> Self {
184        self.line = Some(line);
185        self
186    }
187
188    /// Sets the encoding option.
189    #[must_use]
190    pub fn encoding(mut self, encoding: &str) -> Self {
191        self.encoding = Some(encoding.to_string());
192        self
193    }
194
195    /// Sets the encoding locked option.
196    #[must_use]
197    pub const fn encoding_locked(mut self, locked: bool) -> Self {
198        self.encoding_locked = locked;
199        self
200    }
201
202    /// Sets the frozen string literal option. `Some(true)` freezes string
203    /// literals, `Some(false)` keeps them mutable, and `None` leaves the
204    /// option unset.
205    #[must_use]
206    pub const fn frozen_string_literal(mut self, frozen: Option<bool>) -> Self {
207        self.frozen_string_literal = frozen;
208        self
209    }
210
211    /// Sets the command line flags.
212    #[must_use]
213    pub fn command_line(mut self, command_line: Vec<CommandLineFlag>) -> Self {
214        self.command_line = command_line;
215        self
216    }
217
218    /// Sets the version option.
219    #[must_use]
220    pub const fn version(mut self, version: Version) -> Self {
221        self.version = Some(version);
222        self
223    }
224
225    /// Sets the main script option.
226    #[must_use]
227    pub const fn main_script(mut self, main_script: bool) -> Self {
228        self.main_script = main_script;
229        self
230    }
231
232    /// Sets the partial script option.
233    #[must_use]
234    pub const fn partial_script(mut self, partial_script: bool) -> Self {
235        self.partial_script = partial_script;
236        self
237    }
238
239    /// Sets the attach comments option. When enabled, comments are attached to
240    /// the nodes they belong to and can be read with [`Node::comments`].
241    #[must_use]
242    pub const fn attach_comments(mut self, attach_comments: bool) -> Self {
243        self.attach_comments = attach_comments;
244        self
245    }
246
247    /// Adds a scope to the options.
248    #[must_use]
249    pub fn scope(mut self, scope: Scope) -> Self {
250        self.scopes.push(scope);
251        self
252    }
253
254    /// Sets the scopes, replacing any previously added scopes.
255    #[must_use]
256    pub fn scopes(mut self, scopes: Vec<Scope>) -> Self {
257        self.scopes = scopes;
258        self
259    }
260
261    /// Builds the C-level parse options from these options. The returned
262    /// `ParseOptions` must outlive any `ParseResult` created from it.
263    ///
264    /// # Panics
265    ///
266    /// Panics if `filepath` or `encoding` contain interior null bytes.
267    #[must_use]
268    pub fn build(self) -> ParseOptions {
269        let opts = unsafe { pm_options_new() };
270
271        let c_filepath = self.filepath.map(|filepath| {
272            let cstring = CString::new(filepath).unwrap();
273            unsafe { pm_options_filepath_set(opts, cstring.as_ptr(), cstring.as_bytes().len()) };
274            cstring
275        });
276
277        if let Some(line) = self.line {
278            unsafe { pm_options_line_set(opts, line) };
279        }
280
281        let c_encoding = self.encoding.map(|encoding| {
282            let cstring = CString::new(encoding).unwrap();
283            unsafe { pm_options_encoding_set(opts, cstring.as_ptr(), cstring.as_bytes().len()) };
284            cstring
285        });
286
287        if self.encoding_locked {
288            unsafe { pm_options_encoding_locked_set(opts, true) };
289        }
290
291        if let Some(frozen) = self.frozen_string_literal {
292            unsafe { pm_options_frozen_string_literal_set(opts, frozen) };
293        }
294
295        let command_line = self.command_line.iter().fold(0u8, |acc, &flag| acc | u8::from(flag));
296        if command_line != 0 {
297            unsafe { pm_options_command_line_set(opts, command_line) };
298        }
299
300        if let Some(version) = self.version {
301            unsafe { version.set_on(opts) };
302        }
303
304        if self.main_script {
305            unsafe { pm_options_main_script_set(opts, true) };
306        }
307
308        if self.partial_script {
309            unsafe { pm_options_partial_script_set(opts, true) };
310        }
311
312        if self.attach_comments {
313            unsafe { pm_options_attach_comments_set(opts, true) };
314        }
315
316        if !self.scopes.is_empty() {
317            unsafe { pm_options_scopes_init(opts, self.scopes.len()) };
318
319            for (scope_index, scope) in self.scopes.iter().enumerate() {
320                let pm_scope = unsafe { pm_options_scope_mut(opts, scope_index) };
321                unsafe { pm_options_scope_init(pm_scope, scope.locals.len()) };
322
323                for (local_index, local) in scope.locals.iter().enumerate() {
324                    let pm_local = unsafe { pm_options_scope_local_mut(pm_scope, local_index) };
325                    unsafe { pm_string_init(pm_local, local.as_ptr(), local.len()) };
326                }
327
328                let forwarding = scope.forwarding.iter().fold(0u8, |acc, &flag| acc | u8::from(flag));
329                if forwarding != 0 {
330                    unsafe { pm_options_scope_forwarding_set(pm_scope, forwarding) };
331                }
332            }
333        }
334
335        ParseOptions {
336            options: opts,
337            _filepath: c_filepath,
338            _encoding: c_encoding,
339            _scopes: self.scopes,
340        }
341    }
342}
343
344/// The C-level parse options. Created from [`Options::build`]. Must outlive
345/// any [`ParseResult`] created with [`parse_with_options`].
346pub struct ParseOptions {
347    options: *mut pm_options_t,
348    // These CStrings back the pm_string_t values inside `options`, which only
349    // view their bytes.
350    // They must not be dropped before `options` is freed.
351    _filepath: Option<CString>,
352    _encoding: Option<CString>,
353    // The scopes data that pm_string_t values point into.
354    _scopes: Vec<Scope>,
355}
356
357impl Drop for ParseOptions {
358    fn drop(&mut self) {
359        unsafe { pm_options_free(self.options) };
360    }
361}
362
363/// Initializes a parser, parses the source, and returns the result.
364///
365/// # Safety
366///
367/// `options` must be a valid pointer to a `pm_options_t` or null.
368unsafe fn parse_impl(source: &[u8], options: *const pm_options_t) -> ParseResult<'_> {
369    let arena = pm_arena_new();
370    let parser = pm_parser_new(arena, source.as_ptr(), source.len(), options);
371    let node = NonNull::new_unchecked(pm_parse(parser));
372    ParseResult::new(source, arena, parser, node)
373}
374
375/// Parses the given source string and returns a parse result.
376///
377/// # Panics
378///
379/// Panics if the parser fails to initialize.
380///
381#[must_use]
382pub fn parse(source: &[u8]) -> ParseResult<'_> {
383    unsafe { parse_impl(source, std::ptr::null()) }
384}
385
386/// Parses the given source string with the given options and returns a parse
387/// result. The `options` must outlive the returned `ParseResult`.
388///
389/// # Panics
390///
391/// Panics if the parser fails to initialize.
392///
393#[must_use]
394pub fn parse_with_options<'a>(source: &'a [u8], options: &'a ParseOptions) -> ParseResult<'a> {
395    unsafe { parse_impl(source, options.options) }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::{parse, parse_with_options, Options};
401
402    #[test]
403    fn attach_comments_test() {
404        let source = "foo # comment 1\nbar # comment 2\n";
405
406        let options = Options::default().attach_comments(true).build();
407        let result = parse_with_options(source.as_ref(), &options);
408        let statements = result.node().as_program_node().unwrap().statements();
409        let body: Vec<_> = statements.body().iter().collect();
410
411        assert_eq!(body.len(), 2);
412        assert_eq!(body[0].comments().len(), 1);
413
414        let comments: Vec<_> = body[0].comments().collect();
415        assert_eq!(comments.len(), 1);
416        assert_eq!(comments[0].text(), b"# comment 1");
417
418        let comments: Vec<_> = body[1].comments().collect();
419        assert_eq!(comments.len(), 1);
420        assert_eq!(comments[0].text(), b"# comment 2");
421
422        // Without the option, no comments are attached to the nodes.
423        let result = parse(source.as_ref());
424        let statements = result.node().as_program_node().unwrap().statements();
425        let body: Vec<_> = statements.body().iter().collect();
426        assert_eq!(body[0].comments().len(), 0);
427        assert_eq!(body[1].comments().len(), 0);
428    }
429
430    #[test]
431    fn comments_test() {
432        let source = "# comment 1\n# comment 2\n# comment 3\n";
433        let result = parse(source.as_ref());
434
435        for comment in result.comments() {
436            assert_eq!(super::CommentType::InlineComment, comment.type_());
437            let text = std::str::from_utf8(comment.text()).unwrap();
438            assert!(text.starts_with("# comment"));
439        }
440    }
441
442    #[test]
443    fn line_offsets_test() {
444        let source = "";
445        let result = parse(source.as_ref());
446
447        let expected: [u32; 1] = [0];
448        assert_eq!(expected, result.line_offsets());
449
450        let source = "1 + 1";
451        let result = parse(source.as_ref());
452
453        let expected: [u32; 1] = [0];
454        assert_eq!(expected, result.line_offsets());
455
456        let source = "begin\n1 + 1\n2 + 2\nend";
457        let result = parse(source.as_ref());
458
459        let expected: [u32; 4] = [0, 6, 12, 18];
460        assert_eq!(expected, result.line_offsets());
461    }
462
463    #[test]
464    fn magic_comments_test() {
465        use crate::MagicComment;
466
467        let source = "# typed: ignore\n# typed:true\n#typed: strict\n";
468        let result = parse(source.as_ref());
469
470        let comments: Vec<MagicComment<'_>> = result.magic_comments().collect();
471        assert_eq!(3, comments.len());
472
473        assert_eq!(b"typed", comments[0].key());
474        assert_eq!(b"ignore", comments[0].value());
475
476        assert_eq!(b"typed", comments[1].key());
477        assert_eq!(b"true", comments[1].value());
478
479        assert_eq!(b"typed", comments[2].key());
480        assert_eq!(b"strict", comments[2].value());
481    }
482
483    #[test]
484    fn data_loc_test() {
485        let source = "1";
486        let result = parse(source.as_ref());
487        let data_loc = result.data_loc();
488        assert!(data_loc.is_none());
489
490        let source = "__END__\nabc\n";
491        let result = parse(source.as_ref());
492        let data_loc = result.data_loc().unwrap();
493        let slice = std::str::from_utf8(result.as_slice(&data_loc)).unwrap();
494        assert_eq!(slice, "__END__\nabc\n");
495
496        let source = "1\n2\n3\n__END__\nabc\ndef\n";
497        let result = parse(source.as_ref());
498        let data_loc = result.data_loc().unwrap();
499        let slice = std::str::from_utf8(result.as_slice(&data_loc)).unwrap();
500        assert_eq!(slice, "__END__\nabc\ndef\n");
501    }
502
503    #[test]
504    fn location_slice_test() {
505        let source = "111 + 222 + 333";
506        let result = parse(source.as_ref());
507
508        let node = result.node();
509        let node = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
510        let node = node.as_call_node().unwrap().receiver().unwrap();
511        let plus = node.as_call_node().unwrap();
512        let node = plus.arguments().unwrap().arguments().iter().next().unwrap();
513
514        let location = node.as_integer_node().unwrap().location();
515        let slice = std::str::from_utf8(result.as_slice(&location)).unwrap();
516
517        assert_eq!(slice, "222");
518        assert_eq!(6, location.start);
519        assert_eq!(location.start, location.start());
520        assert_eq!(9, location.end());
521
522        let recv_loc = plus.receiver().unwrap().location();
523        assert_eq!(recv_loc.as_slice(), b"111");
524        assert_eq!(0, recv_loc.start);
525        assert_eq!(3, recv_loc.end());
526
527        let joined = recv_loc.join(&location).unwrap();
528        assert_eq!(joined.as_slice(), b"111 + 222");
529
530        let not_joined = location.join(&recv_loc);
531        assert!(not_joined.is_none());
532
533        {
534            let result = parse(source.as_ref());
535            let node = result.node();
536            let node = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
537            let node = node.as_call_node().unwrap().receiver().unwrap();
538            let plus = node.as_call_node().unwrap();
539            let node = plus.arguments().unwrap().arguments().iter().next().unwrap();
540
541            let location = node.as_integer_node().unwrap().location();
542            let not_joined = recv_loc.join(&location);
543            assert!(not_joined.is_none());
544
545            let not_joined = location.join(&recv_loc);
546            assert!(not_joined.is_none());
547        }
548
549        let location = node.location();
550        let slice = std::str::from_utf8(result.as_slice(&location)).unwrap();
551
552        assert_eq!(slice, "222");
553
554        let slice = std::str::from_utf8(location.as_slice()).unwrap();
555
556        assert_eq!(slice, "222");
557    }
558
559    #[test]
560    fn location_line_column_test() {
561        let source = "first\nsecond\nthird";
562        let result = parse(source.as_ref());
563
564        let node = result.node();
565        let program = node.as_program_node().unwrap();
566        let statements = program.statements().body();
567        let mut iter = statements.iter();
568
569        let _first = iter.next().unwrap();
570        let second = iter.next().unwrap();
571        let third = iter.next().unwrap();
572
573        let second_loc = second.location();
574        assert_eq!(second_loc.start_line(), 2);
575        assert_eq!(second_loc.end_line(), 2);
576        assert_eq!(second_loc.start_column(), 0);
577        assert_eq!(second_loc.end_column(), 6);
578
579        let third_loc = third.location();
580        assert_eq!(third_loc.start_line(), 3);
581        assert_eq!(third_loc.end_line(), 3);
582        assert_eq!(third_loc.start_column(), 0);
583        assert_eq!(third_loc.end_column(), 5);
584    }
585
586    #[test]
587    fn location_chop_test() {
588        let result = parse(b"foo");
589        let mut location = result.node().as_program_node().unwrap().location();
590
591        assert_eq!(location.chop().as_slice(), b"fo");
592        assert_eq!(location.chop().chop().chop().as_slice(), b"");
593
594        // Check that we don't go negative.
595        for _ in 0..10 {
596            location = location.chop();
597        }
598        assert_eq!(location.as_slice(), b"");
599    }
600
601    #[test]
602    fn visitor_test() {
603        use super::{visit_interpolated_regular_expression_node, visit_regular_expression_node, InterpolatedRegularExpressionNode, RegularExpressionNode, Visit};
604
605        struct RegularExpressionVisitor {
606            count: usize,
607        }
608
609        impl Visit<'_> for RegularExpressionVisitor {
610            fn visit_interpolated_regular_expression_node(&mut self, node: &InterpolatedRegularExpressionNode<'_>) {
611                self.count += 1;
612                visit_interpolated_regular_expression_node(self, node);
613            }
614
615            fn visit_regular_expression_node(&mut self, node: &RegularExpressionNode<'_>) {
616                self.count += 1;
617                visit_regular_expression_node(self, node);
618            }
619        }
620
621        let source = "# comment 1\n# comment 2\nmodule Foo; class Bar; /abc #{/def/}/; end; end";
622        let result = parse(source.as_ref());
623
624        let mut visitor = RegularExpressionVisitor { count: 0 };
625        visitor.visit(&result.node());
626
627        assert_eq!(visitor.count, 2);
628    }
629
630    #[test]
631    fn node_upcast_test() {
632        use super::Node;
633
634        let source = "module Foo; end";
635        let result = parse(source.as_ref());
636
637        let node = result.node();
638        let upcast_node = node.as_program_node().unwrap().as_node();
639        assert!(matches!(upcast_node, Node::ProgramNode { .. }));
640
641        let node = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
642        let upcast_node = node.as_module_node().unwrap().as_node();
643        assert!(matches!(upcast_node, Node::ModuleNode { .. }));
644    }
645
646    #[test]
647    fn constant_id_test() {
648        let source = "module Foo; x = 1; y = 2; end";
649        let result = parse(source.as_ref());
650
651        let node = result.node();
652        assert_eq!(node.as_program_node().unwrap().statements().body().len(), 1);
653        assert!(!node.as_program_node().unwrap().statements().body().is_empty());
654        let module = node.as_program_node().and_then(|pn| pn.statements().body().first()).unwrap();
655        let module = module.as_module_node().unwrap();
656
657        assert_eq!(module.locals().len(), 2);
658        assert!(!module.locals().is_empty());
659
660        assert_eq!(module.locals().first().unwrap().as_slice(), b"x");
661        assert_eq!(module.locals().last().unwrap().as_slice(), b"y");
662
663        let source = "module Foo; end";
664        let result = parse(source.as_ref());
665
666        let node = result.node();
667        assert_eq!(node.as_program_node().unwrap().statements().body().len(), 1);
668        assert!(!node.as_program_node().unwrap().statements().body().is_empty());
669        let module = node.as_program_node().and_then(|pn| pn.statements().body().first()).unwrap();
670        let module = module.as_module_node().unwrap();
671
672        assert_eq!(module.locals().len(), 0);
673        assert!(module.locals().is_empty());
674    }
675
676    #[test]
677    fn optional_loc_test() {
678        let source = r"
679module Example
680  x = call_func(3, 4)
681  y = x.call_func 5, 6
682end
683";
684        let result = parse(source.as_ref());
685
686        let node = result.node();
687        let module = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
688        let module = module.as_module_node().unwrap();
689        let body = module.body();
690        let writes = body.iter().next().unwrap().as_statements_node().unwrap().body().iter().collect::<Vec<_>>();
691        assert_eq!(writes.len(), 2);
692
693        let asgn = &writes[0];
694        let call = asgn.as_local_variable_write_node().unwrap().value();
695        let call = call.as_call_node().unwrap();
696
697        let call_operator_loc = call.call_operator_loc();
698        assert!(call_operator_loc.is_none());
699        let closing_loc = call.closing_loc();
700        assert!(closing_loc.is_some());
701
702        let asgn = &writes[1];
703        let call = asgn.as_local_variable_write_node().unwrap().value();
704        let call = call.as_call_node().unwrap();
705
706        let call_operator_loc = call.call_operator_loc();
707        assert!(call_operator_loc.is_some());
708        let closing_loc = call.closing_loc();
709        assert!(closing_loc.is_none());
710    }
711
712    #[test]
713    fn frozen_strings_test() {
714        let source = r#"
715# frozen_string_literal: true
716"foo"
717"#;
718        let result = parse(source.as_ref());
719        assert!(result.frozen_string_literals());
720
721        let source = "3";
722        let result = parse(source.as_ref());
723        assert!(!result.frozen_string_literals());
724    }
725
726    #[test]
727    fn string_flags_test() {
728        let source = r#"
729# frozen_string_literal: true
730"foo"
731"#;
732        let result = parse(source.as_ref());
733
734        let node = result.node();
735        let string = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
736        let string = string.as_string_node().unwrap();
737        assert!(string.is_frozen());
738
739        let source = r#"
740"foo"
741"#;
742        let result = parse(source.as_ref());
743
744        let node = result.node();
745        let string = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
746        let string = string.as_string_node().unwrap();
747        assert!(!string.is_frozen());
748    }
749
750    #[test]
751    fn call_flags_test() {
752        let source = r"
753x
754";
755        let result = parse(source.as_ref());
756
757        let node = result.node();
758        let call = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
759        let call = call.as_call_node().unwrap();
760        assert!(call.is_variable_call());
761
762        let source = r"
763x&.foo
764";
765        let result = parse(source.as_ref());
766
767        let node = result.node();
768        let call = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
769        let call = call.as_call_node().unwrap();
770        assert!(call.is_safe_navigation());
771    }
772
773    #[test]
774    fn integer_flags_test() {
775        let source = r"
7760b1
777";
778        let result = parse(source.as_ref());
779
780        let node = result.node();
781        let i = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
782        let i = i.as_integer_node().unwrap();
783        assert!(i.is_binary());
784        assert!(!i.is_decimal());
785        assert!(!i.is_octal());
786        assert!(!i.is_hexadecimal());
787
788        let source = r"
7891
790";
791        let result = parse(source.as_ref());
792
793        let node = result.node();
794        let i = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
795        let i = i.as_integer_node().unwrap();
796        assert!(!i.is_binary());
797        assert!(i.is_decimal());
798        assert!(!i.is_octal());
799        assert!(!i.is_hexadecimal());
800
801        let source = r"
8020o1
803";
804        let result = parse(source.as_ref());
805
806        let node = result.node();
807        let i = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
808        let i = i.as_integer_node().unwrap();
809        assert!(!i.is_binary());
810        assert!(!i.is_decimal());
811        assert!(i.is_octal());
812        assert!(!i.is_hexadecimal());
813
814        let source = r"
8150x1
816";
817        let result = parse(source.as_ref());
818
819        let node = result.node();
820        let i = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
821        let i = i.as_integer_node().unwrap();
822        assert!(!i.is_binary());
823        assert!(!i.is_decimal());
824        assert!(!i.is_octal());
825        assert!(i.is_hexadecimal());
826    }
827
828    #[test]
829    fn range_flags_test() {
830        let source = r"
8310..1
832";
833        let result = parse(source.as_ref());
834
835        let node = result.node();
836        let range = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
837        let range = range.as_range_node().unwrap();
838        assert!(!range.is_exclude_end());
839
840        let source = r"
8410...1
842";
843        let result = parse(source.as_ref());
844
845        let node = result.node();
846        let range = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
847        let range = range.as_range_node().unwrap();
848        assert!(range.is_exclude_end());
849    }
850
851    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
852    #[test]
853    fn regex_flags_test() {
854        let source = r"
855/a/i
856";
857        let result = parse(source.as_ref());
858
859        let node = result.node();
860        let regex = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
861        let regex = regex.as_regular_expression_node().unwrap();
862        assert!(regex.is_ignore_case());
863        assert!(!regex.is_extended());
864        assert!(!regex.is_multi_line());
865        assert!(!regex.is_euc_jp());
866        assert!(!regex.is_ascii_8bit());
867        assert!(!regex.is_windows_31j());
868        assert!(!regex.is_utf_8());
869        assert!(!regex.is_once());
870
871        let source = r"
872/a/x
873";
874        let result = parse(source.as_ref());
875
876        let node = result.node();
877        let regex = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
878        let regex = regex.as_regular_expression_node().unwrap();
879        assert!(!regex.is_ignore_case());
880        assert!(regex.is_extended());
881        assert!(!regex.is_multi_line());
882        assert!(!regex.is_euc_jp());
883        assert!(!regex.is_ascii_8bit());
884        assert!(!regex.is_windows_31j());
885        assert!(!regex.is_utf_8());
886        assert!(!regex.is_once());
887
888        let source = r"
889/a/m
890";
891        let result = parse(source.as_ref());
892
893        let node = result.node();
894        let regex = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
895        let regex = regex.as_regular_expression_node().unwrap();
896        assert!(!regex.is_ignore_case());
897        assert!(!regex.is_extended());
898        assert!(regex.is_multi_line());
899        assert!(!regex.is_euc_jp());
900        assert!(!regex.is_ascii_8bit());
901        assert!(!regex.is_windows_31j());
902        assert!(!regex.is_utf_8());
903        assert!(!regex.is_once());
904
905        let source = r"
906/a/e
907";
908        let result = parse(source.as_ref());
909
910        let node = result.node();
911        let regex = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
912        let regex = regex.as_regular_expression_node().unwrap();
913        assert!(!regex.is_ignore_case());
914        assert!(!regex.is_extended());
915        assert!(!regex.is_multi_line());
916        assert!(regex.is_euc_jp());
917        assert!(!regex.is_ascii_8bit());
918        assert!(!regex.is_windows_31j());
919        assert!(!regex.is_utf_8());
920        assert!(!regex.is_once());
921
922        let source = r"
923/a/n
924";
925        let result = parse(source.as_ref());
926
927        let node = result.node();
928        let regex = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
929        let regex = regex.as_regular_expression_node().unwrap();
930        assert!(!regex.is_ignore_case());
931        assert!(!regex.is_extended());
932        assert!(!regex.is_multi_line());
933        assert!(!regex.is_euc_jp());
934        assert!(regex.is_ascii_8bit());
935        assert!(!regex.is_windows_31j());
936        assert!(!regex.is_utf_8());
937        assert!(!regex.is_once());
938
939        let source = r"
940/a/s
941";
942        let result = parse(source.as_ref());
943
944        let node = result.node();
945        let regex = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
946        let regex = regex.as_regular_expression_node().unwrap();
947        assert!(!regex.is_ignore_case());
948        assert!(!regex.is_extended());
949        assert!(!regex.is_multi_line());
950        assert!(!regex.is_euc_jp());
951        assert!(!regex.is_ascii_8bit());
952        assert!(regex.is_windows_31j());
953        assert!(!regex.is_utf_8());
954        assert!(!regex.is_once());
955
956        let source = r"
957/a/u
958";
959        let result = parse(source.as_ref());
960
961        let node = result.node();
962        let regex = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
963        let regex = regex.as_regular_expression_node().unwrap();
964        assert!(!regex.is_ignore_case());
965        assert!(!regex.is_extended());
966        assert!(!regex.is_multi_line());
967        assert!(!regex.is_euc_jp());
968        assert!(!regex.is_ascii_8bit());
969        assert!(!regex.is_windows_31j());
970        assert!(regex.is_utf_8());
971        assert!(!regex.is_once());
972
973        let source = r"
974/a/o
975";
976        let result = parse(source.as_ref());
977
978        let node = result.node();
979        let regex = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
980        let regex = regex.as_regular_expression_node().unwrap();
981        assert!(!regex.is_ignore_case());
982        assert!(!regex.is_extended());
983        assert!(!regex.is_multi_line());
984        assert!(!regex.is_euc_jp());
985        assert!(!regex.is_ascii_8bit());
986        assert!(!regex.is_windows_31j());
987        assert!(!regex.is_utf_8());
988        assert!(regex.is_once());
989    }
990
991    #[test]
992    fn visitor_traversal_test() {
993        use crate::{Node, Visit};
994
995        #[derive(Default)]
996        struct NodeCounts {
997            pre_parent: usize,
998            post_parent: usize,
999            pre_leaf: usize,
1000            post_leaf: usize,
1001        }
1002
1003        #[derive(Default)]
1004        struct CountingVisitor {
1005            counts: NodeCounts,
1006        }
1007
1008        impl Visit<'_> for CountingVisitor {
1009            fn visit_branch_node_enter(&mut self, _node: Node<'_>) {
1010                self.counts.pre_parent += 1;
1011            }
1012
1013            fn visit_branch_node_leave(&mut self) {
1014                self.counts.post_parent += 1;
1015            }
1016
1017            fn visit_leaf_node_enter(&mut self, _node: Node<'_>) {
1018                self.counts.pre_leaf += 1;
1019            }
1020
1021            fn visit_leaf_node_leave(&mut self) {
1022                self.counts.post_leaf += 1;
1023            }
1024        }
1025
1026        let source = r"
1027module Example
1028  x = call_func(3, 4)
1029  y = x.call_func 5, 6
1030end
1031";
1032        let result = parse(source.as_ref());
1033        let node = result.node();
1034        let mut visitor = CountingVisitor::default();
1035        visitor.visit(&node);
1036
1037        assert_eq!(7, visitor.counts.pre_parent);
1038        assert_eq!(7, visitor.counts.post_parent);
1039        assert_eq!(6, visitor.counts.pre_leaf);
1040        assert_eq!(6, visitor.counts.post_leaf);
1041    }
1042
1043    #[test]
1044    fn visitor_lifetime_test() {
1045        use crate::{Node, Visit};
1046
1047        #[derive(Default)]
1048        struct StackingNodeVisitor<'a> {
1049            stack: Vec<Node<'a>>,
1050            max_depth: usize,
1051        }
1052
1053        impl<'pr> Visit<'pr> for StackingNodeVisitor<'pr> {
1054            fn visit_branch_node_enter(&mut self, node: Node<'pr>) {
1055                self.stack.push(node);
1056            }
1057
1058            fn visit_branch_node_leave(&mut self) {
1059                self.stack.pop();
1060            }
1061
1062            fn visit_leaf_node_leave(&mut self) {
1063                self.max_depth = self.max_depth.max(self.stack.len());
1064            }
1065        }
1066
1067        let source = r"
1068module Example
1069  x = call_func(3, 4)
1070  y = x.call_func 5, 6
1071end
1072";
1073        let result = parse(source.as_ref());
1074        let node = result.node();
1075        let mut visitor = StackingNodeVisitor::default();
1076        visitor.visit(&node);
1077
1078        assert_eq!(0, visitor.stack.len());
1079        assert_eq!(5, visitor.max_depth);
1080    }
1081
1082    #[test]
1083    fn integer_value_test() {
1084        let result = parse("0xA".as_ref());
1085        let integer = result.node().as_program_node().unwrap().statements().body().iter().next().unwrap().as_integer_node().unwrap().value();
1086        let value: i32 = integer.try_into().unwrap();
1087
1088        assert_eq!(value, 10);
1089    }
1090
1091    #[test]
1092    fn integer_zero_value_test() {
1093        for source in ["0", "-0"] {
1094            let result = parse(source.as_ref());
1095            let integer = result.node().as_program_node().unwrap().statements().body().iter().next().unwrap().as_integer_node().unwrap().value();
1096            let value: i32 = integer.try_into().unwrap();
1097
1098            assert_eq!(value, 0);
1099        }
1100    }
1101
1102    #[test]
1103    fn integer_small_value_to_u32_digits_test() {
1104        let result = parse("0xA".as_ref());
1105        let integer = result.node().as_program_node().unwrap().statements().body().iter().next().unwrap().as_integer_node().unwrap().value();
1106        let (negative, digits) = integer.to_u32_digits();
1107
1108        assert!(!negative);
1109        assert_eq!(digits, &[10]);
1110    }
1111
1112    #[test]
1113    fn integer_zero_to_u32_digits_test() {
1114        let result = parse("0".as_ref());
1115        let integer = result.node().as_program_node().unwrap().statements().body().iter().next().unwrap().as_integer_node().unwrap().value();
1116        let (negative, digits) = integer.to_u32_digits();
1117
1118        assert!(!negative);
1119        assert_eq!(digits, &[0]);
1120    }
1121
1122    #[test]
1123    fn integer_two_digit_value_to_u32_digits_test() {
1124        let result = parse("0xFFFFFFFF00000001".as_ref());
1125        let integer = result.node().as_program_node().unwrap().statements().body().iter().next().unwrap().as_integer_node().unwrap().value();
1126        let (negative, digits) = integer.to_u32_digits();
1127
1128        assert!(!negative);
1129        assert_eq!(digits, &[1, 4_294_967_295]);
1130    }
1131
1132    #[test]
1133    fn integer_large_value_to_u32_digits_test() {
1134        let result = parse("0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF".as_ref());
1135        let integer = result.node().as_program_node().unwrap().statements().body().iter().next().unwrap().as_integer_node().unwrap().value();
1136        let (negative, digits) = integer.to_u32_digits();
1137
1138        assert!(!negative);
1139        assert_eq!(digits, &[4_294_967_295, 4_294_967_295, 4_294_967_295, 2_147_483_647]);
1140    }
1141
1142    #[test]
1143    fn float_value_test() {
1144        let result = parse("1.0".as_ref());
1145        let value: f64 = result.node().as_program_node().unwrap().statements().body().iter().next().unwrap().as_float_node().unwrap().value();
1146
1147        assert!((value - 1.0).abs() < f64::EPSILON);
1148    }
1149
1150    #[test]
1151    fn regex_value_test() {
1152        let result = parse(b"//");
1153        let node = result.node().as_program_node().unwrap().statements().body().iter().next().unwrap().as_regular_expression_node().unwrap();
1154        assert_eq!(node.unescaped(), b"");
1155    }
1156
1157    #[test]
1158    fn node_field_lifetime_test() {
1159        // The code below wouldn't typecheck prior to https://github.com/ruby/prism/pull/2519,
1160        // but we need to stop clippy from complaining about it.
1161        #![allow(clippy::needless_pass_by_value)]
1162
1163        use crate::Node;
1164
1165        #[derive(Default)]
1166        struct Extract<'pr> {
1167            scopes: Vec<crate::ConstantId<'pr>>,
1168        }
1169
1170        impl<'pr> Extract<'pr> {
1171            fn push_scope(&mut self, path: Node<'pr>) {
1172                if let Some(cread) = path.as_constant_read_node() {
1173                    self.scopes.push(cread.name());
1174                } else if let Some(cpath) = path.as_constant_path_node() {
1175                    if let Some(parent) = cpath.parent() {
1176                        self.push_scope(parent);
1177                    }
1178                    self.scopes.push(cpath.name().unwrap());
1179                } else {
1180                    panic!("Wrong node kind!");
1181                }
1182            }
1183        }
1184
1185        let source = "Some::Random::Constant";
1186        let result = parse(source.as_ref());
1187        let node = result.node();
1188        let mut extractor = Extract::default();
1189        extractor.push_scope(node.as_program_node().unwrap().statements().body().iter().next().unwrap());
1190        assert_eq!(3, extractor.scopes.len());
1191    }
1192
1193    #[test]
1194    fn parse_with_options_frozen_string_literal_test() {
1195        use super::{parse_with_options, Options};
1196
1197        let source = b"\"foo\"";
1198        let options = Options::default().frozen_string_literal(Some(true)).build();
1199        let result = parse_with_options(source, &options);
1200
1201        let node = result.node();
1202        let string = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
1203        let string = string.as_string_node().unwrap();
1204        assert!(string.is_frozen());
1205    }
1206
1207    #[test]
1208    fn parse_with_options_filepath_test() {
1209        use super::{parse_with_options, Options};
1210
1211        let source = b"__FILE__";
1212        let options = Options::default().filepath("test.rb").build();
1213        let result = parse_with_options(source, &options);
1214        assert!(result.errors().next().is_none());
1215    }
1216
1217    #[test]
1218    fn parse_with_options_line_test() {
1219        use super::{parse_with_options, Options};
1220
1221        let source = b"1 + 2";
1222        let options = Options::default().line(10).build();
1223        let result = parse_with_options(source, &options);
1224        assert!(result.errors().next().is_none());
1225    }
1226
1227    #[test]
1228    #[allow(deprecated)]
1229    fn parse_with_options_cruby4_0_test() {
1230        use super::{parse_with_options, Options, Version};
1231
1232        let source = b"private def foo = puts 'Hello'";
1233        let newer_source = b"def foo(&nil); end";
1234
1235        for version in [Version::CRuby4_0, Version::CRuby3_5] {
1236            let options = Options::default().version(version).build();
1237            let result = parse_with_options(source, &options);
1238            assert!(result.errors().next().is_none());
1239
1240            let call = result.node().as_program_node().unwrap().statements().body().first().unwrap().as_call_node().unwrap();
1241            assert_eq!(call.name().as_slice(), b"private");
1242            let method = call.arguments().unwrap().arguments().first().unwrap().as_def_node().unwrap();
1243            assert_eq!(method.name().as_slice(), b"foo");
1244
1245            assert!(parse_with_options(newer_source, &options).errors().next().is_some());
1246        }
1247
1248        let earlier_options = Options::default().version(Version::CRuby3_4).build();
1249        assert!(parse_with_options(source, &earlier_options).errors().next().is_some());
1250
1251        let later_options = Options::default().version(Version::CRuby4_1).build();
1252        assert!(parse_with_options(newer_source, &later_options).errors().next().is_none());
1253    }
1254
1255    #[test]
1256    fn parse_with_options_default_line_test() {
1257        use super::{parse_with_options, Options};
1258
1259        let source = b"foo\nbar";
1260        let options = Options::default().filepath("test.rb").build();
1261        let result = parse_with_options(source, &options);
1262
1263        let node = result.node();
1264        let statements: Vec<_> = node.as_program_node().unwrap().statements().body().iter().collect();
1265        assert_eq!(statements[0].location().start_line(), 1);
1266        assert_eq!(statements[1].location().start_line(), 2);
1267    }
1268
1269    #[test]
1270    fn parse_with_options_scopes_test() {
1271        use super::{parse_with_options, Options, Scope};
1272
1273        let source = b"x";
1274        let scope = Scope::default().locals(vec![b"x".to_vec()]);
1275        let options = Options::default().scope(scope).build();
1276        let result = parse_with_options(source, &options);
1277        assert!(result.errors().next().is_none());
1278
1279        let node = result.node();
1280        let stmt = node.as_program_node().unwrap().statements().body().iter().next().unwrap();
1281        assert!(stmt.as_local_variable_read_node().is_some());
1282    }
1283
1284    #[test]
1285    fn diagnostic_message_test() {
1286        let source = b"# encoding: shift_jis\nx = <<~\x82\xA0\n";
1287        let result = parse(source);
1288        let error = result.errors().next().unwrap();
1289
1290        let message = error.message();
1291        assert!(std::str::from_utf8(message).is_err());
1292        assert!(message.windows(2).any(|window| window == b"\x82\xA0"));
1293    }
1294
1295    #[test]
1296    fn malformed_shebang() {
1297        let source = "#!\x00";
1298        let result = parse(source.as_ref());
1299        assert!(result.errors().next().is_none());
1300        assert!(result.warnings().next().is_none());
1301    }
1302}