-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathmod.rs
More file actions
287 lines (249 loc) · 8.74 KB
/
Copy pathmod.rs
File metadata and controls
287 lines (249 loc) · 8.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
//! Parse result types for the prism parser.
//!
//! This module contains types related to the result of parsing, including
//! the main `ParseResult` struct, location tracking, comments, and diagnostics.
mod comments;
mod diagnostics;
use std::ptr::NonNull;
use ruby_prism_sys::{pm_arena_free, pm_arena_t, pm_comment_t, pm_diagnostic_t, pm_line_offset_list_line_column, pm_location_t, pm_magic_comment_t, pm_node_t, pm_parser_free, pm_parser_t};
pub use self::comments::{Comment, CommentType, Comments, MagicComment, MagicComments};
pub use self::diagnostics::{Diagnostic, Diagnostics};
use crate::Node;
/// A range in the source file, represented as a start offset and length.
pub struct Location<'pr> {
pub(crate) parser: NonNull<pm_parser_t>,
pub(crate) start: u32,
pub(crate) length: u32,
marker: std::marker::PhantomData<&'pr [u8]>,
}
impl<'pr> Location<'pr> {
/// Returns a byte slice for the range.
#[must_use]
pub fn as_slice(&self) -> &'pr [u8] {
unsafe {
let parser_start = (*self.parser.as_ptr()).start;
std::slice::from_raw_parts(parser_start.add(self.start as usize), self.length as usize)
}
}
/// Return a Location from the given `pm_location_t`.
#[must_use]
pub(crate) const fn new(parser: NonNull<pm_parser_t>, location: &'pr pm_location_t) -> Self {
Location {
parser,
start: location.start,
length: location.length,
marker: std::marker::PhantomData,
}
}
/// Returns the start offset from the beginning of the parsed source.
#[must_use]
pub const fn start(&self) -> u32 {
self.start
}
/// Returns the end offset from the beginning of the parsed source.
#[must_use]
pub const fn end(&self) -> u32 {
self.start + self.length
}
/// Return a Location starting at self and ending at the end of other.
/// Returns None if both locations did not originate from the same parser,
/// or if self starts after other.
#[must_use]
pub fn join(&self, other: &Self) -> Option<Self> {
if self.parser != other.parser || self.start > other.start {
None
} else {
Some(Location {
parser: self.parser,
start: self.start,
length: other.end() - self.start,
marker: std::marker::PhantomData,
})
}
}
/// Returns a new location that is the result of chopping off the last byte.
#[must_use]
pub const fn chop(&self) -> Self {
Location {
parser: self.parser,
start: self.start,
length: if self.length == 0 { 0 } else { self.length - 1 },
marker: std::marker::PhantomData,
}
}
}
impl Location<'_> {
/// Returns the line number where this location starts.
#[must_use]
pub fn start_line(&self) -> i32 {
self.line_column(self.start).0
}
/// Returns the column number in bytes where this location starts from the
/// start of the line.
#[must_use]
pub fn start_column(&self) -> u32 {
self.line_column(self.start).1
}
/// Returns the line number where this location ends.
#[must_use]
pub fn end_line(&self) -> i32 {
self.line_column(self.end()).0
}
/// Returns the column number in bytes where this location ends from the
/// start of the line.
#[must_use]
pub fn end_column(&self) -> u32 {
self.line_column(self.end()).1
}
/// Returns the line and column number for the given byte offset.
fn line_column(&self, cursor: u32) -> (i32, u32) {
// SAFETY: We read the line_offsets and start_line from the parser,
// which is valid for the lifetime of this Location.
unsafe {
let parser = self.parser.as_ptr();
let result = pm_line_offset_list_line_column(&raw const (*parser).line_offsets, cursor, (*parser).start_line);
(result.line, result.column)
}
}
}
impl std::fmt::Debug for Location<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let slice: &[u8] = self.as_slice();
let mut visible = String::new();
visible.push('"');
for &byte in slice {
let part: Vec<u8> = std::ascii::escape_default(byte).collect();
visible.push_str(std::str::from_utf8(&part).unwrap());
}
visible.push('"');
write!(f, "{visible}")
}
}
/// The result of parsing a source string.
#[derive(Debug)]
pub struct ParseResult<'pr> {
source: &'pr [u8],
arena: Box<pm_arena_t>,
parser: NonNull<pm_parser_t>,
node: NonNull<pm_node_t>,
}
impl<'pr> ParseResult<'pr> {
pub(crate) const unsafe fn new(source: &'pr [u8], arena: Box<pm_arena_t>, parser: NonNull<pm_parser_t>, node: NonNull<pm_node_t>) -> Self {
ParseResult { source, arena, parser, node }
}
/// Returns the source string that was parsed.
#[must_use]
pub const fn source(&self) -> &'pr [u8] {
self.source
}
/// Returns whether we found a `frozen_string_literal` magic comment with a true value.
#[must_use]
pub fn frozen_string_literals(&self) -> bool {
unsafe { (*self.parser.as_ptr()).frozen_string_literal == 1 }
}
/// Returns a slice of the source string that was parsed using the given
/// slice range.
#[must_use]
pub fn as_slice(&self, location: &Location<'pr>) -> &'pr [u8] {
let start = location.start as usize;
let end = start + location.length as usize;
&self.source[start..end]
}
/// Returns a slice containing the offsets of the start of each line in the source string
/// that was parsed.
#[must_use]
pub fn line_offsets(&self) -> &'pr [u32] {
unsafe {
let list = &(*self.parser.as_ptr()).line_offsets;
std::slice::from_raw_parts(list.offsets, list.size)
}
}
/// Returns an iterator that can be used to iterate over the errors in the
/// parse result.
#[must_use]
pub fn errors(&self) -> Diagnostics<'_> {
unsafe {
let list = &mut (*self.parser.as_ptr()).error_list;
Diagnostics::new(list.head.cast::<pm_diagnostic_t>(), self.parser)
}
}
/// Returns an iterator that can be used to iterate over the warnings in the
/// parse result.
#[must_use]
pub fn warnings(&self) -> Diagnostics<'_> {
unsafe {
let list = &mut (*self.parser.as_ptr()).warning_list;
Diagnostics::new(list.head.cast::<pm_diagnostic_t>(), self.parser)
}
}
/// Returns an iterator that can be used to iterate over the comments in the
/// parse result.
#[must_use]
pub fn comments(&self) -> Comments<'_> {
unsafe {
let list = &mut (*self.parser.as_ptr()).comment_list;
Comments::new(list.head.cast::<pm_comment_t>(), self.parser)
}
}
/// Returns an iterator that can be used to iterate over the magic comments in the
/// parse result.
#[must_use]
pub fn magic_comments(&self) -> MagicComments<'_> {
unsafe {
let list = &mut (*self.parser.as_ptr()).magic_comment_list;
MagicComments::new(self.parser, list.head.cast::<pm_magic_comment_t>())
}
}
/// Returns an optional location of the __END__ marker and the rest of the content of the file.
#[must_use]
pub fn data_loc(&self) -> Option<Location<'_>> {
let location = unsafe { &(*self.parser.as_ptr()).data_loc };
if location.length == 0 {
None
} else {
Some(Location::new(self.parser, location))
}
}
/// Returns the root node of the parse result.
#[must_use]
pub fn node(&self) -> Node<'_> {
Node::new(self.parser, self.node.as_ptr())
}
/// Returns true if there were no errors during parsing and false if there
/// were.
#[must_use]
pub fn is_success(&self) -> bool {
self.errors().next().is_none()
}
/// Returns true if there were errors during parsing and false if there were
/// not.
#[must_use]
pub fn is_failure(&self) -> bool {
!self.is_success()
}
}
impl Drop for ParseResult<'_> {
fn drop(&mut self) {
unsafe {
pm_parser_free(self.parser.as_ptr());
drop(Box::from_raw(self.parser.as_ptr()));
pm_arena_free(self.arena.as_mut());
}
}
}
#[cfg(test)]
mod tests {
use crate::parse;
#[test]
fn test_is_success() {
let result = parse(b"1 + 1");
assert!(result.is_success());
assert!(!result.is_failure());
}
#[test]
fn test_is_failure() {
let result = parse(b"<>");
assert!(result.is_failure());
assert!(!result.is_success());
}
}