run_parser_test_suite/
run-parser-test-suite.rs

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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
//! A YAML parser and formatter using the libyml library.
//!
//! This program reads YAML files, parses them using the libyml library,
//! and outputs a formatted representation of the YAML structure.

#![allow(missing_docs)]
#![warn(clippy::pedantic)]
#![allow(
    clippy::cast_lossless,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    clippy::items_after_statements,
    clippy::let_underscore_untyped,
    clippy::missing_errors_doc,
    clippy::missing_safety_doc,
    clippy::too_many_lines,
    clippy::uninlined_format_args
)]

mod cstr;

use self::cstr::CStr;
use anyhow::{bail, Error, Result};
use libyml::{
    yaml_event_delete, yaml_parser_delete, yaml_parser_initialize,
    yaml_parser_parse, yaml_parser_set_input, YamlAliasEvent,
    YamlDocumentEndEvent, YamlDocumentStartEvent,
    YamlDoubleQuotedScalarStyle, YamlEventT, YamlEventTypeT,
    YamlFoldedScalarStyle, YamlLiteralScalarStyle, YamlMappingEndEvent,
    YamlMappingStartEvent, YamlNoEvent, YamlParserT,
    YamlPlainScalarStyle, YamlScalarEvent, YamlSequenceEndEvent,
    YamlSequenceStartEvent, YamlSingleQuotedScalarStyle,
    YamlStreamEndEvent, YamlStreamStartEvent,
};
use std::env;
use std::ffi::c_void;
use std::fs::File;
use std::io::{self, Read, Write};
use std::mem::MaybeUninit;
use std::path::Path;
use std::process::ExitCode;
use std::ptr::addr_of_mut;
use std::slice;

/// The main parsing function that processes YAML input and writes formatted output.
///
/// # Safety
///
/// This function is unsafe because it deals with raw pointers and FFI.
/// Callers must ensure that the provided `stdin` and `stdout` are valid
/// and that the FFI calls are used correctly.
///
/// # Arguments
///
/// * `stdin` - A mutable reference to a type that implements `Read`, from which YAML will be read.
/// * `stdout` - A mutable reference to a type that implements `Write`, to which formatted output will be written.
///
/// # Returns
///
/// Returns `Ok(())` if parsing and formatting succeed, or an `Error` if any issues occur.
pub(crate) unsafe fn unsafe_main(
    mut stdin: &mut dyn Read,
    stdout: &mut dyn Write,
) -> Result<()> {
    let mut parser = MaybeUninit::<YamlParserT>::uninit();
    let parser = parser.as_mut_ptr();
    if yaml_parser_initialize(parser).fail {
        bail!("Could not initialize the parser object");
    }

    /// Callback function for reading input from stdio.
    ///
    /// This function is called by the YAML parser to read input data.
    ///
    /// # Safety
    ///
    /// This function is unsafe because it deals with raw pointers.
    /// It assumes that `data` is a valid pointer to a `Read` trait object.
    unsafe fn read_from_stdio(
        data: *mut c_void,
        buffer: *mut u8,
        size: u64,
        size_read: *mut u64,
    ) -> i32 {
        let stdin: *mut &mut dyn Read = data.cast();
        let slice =
            slice::from_raw_parts_mut(buffer.cast(), size as usize);
        match (*stdin).read(slice) {
            Ok(n) => {
                *size_read = n as u64;
                1
            }
            Err(_) => 0,
        }
    }

    yaml_parser_set_input(
        parser,
        read_from_stdio,
        addr_of_mut!(stdin).cast(),
    );

    let mut event = MaybeUninit::<YamlEventT>::uninit();
    let event = event.as_mut_ptr();
    loop {
        if yaml_parser_parse(parser, event).fail {
            let error = format!(
                "Parse error: {}",
                CStr::from_ptr((*parser).problem)
            );
            let error = if (*parser).problem_mark.line != 0
                || (*parser).problem_mark.column != 0
            {
                format!(
                    "{}\nLine: {} Column: {}",
                    error,
                    ((*parser).problem_mark.line).wrapping_add(1),
                    ((*parser).problem_mark.column).wrapping_add(1),
                )
            } else {
                error
            };
            yaml_parser_delete(parser);
            return Err(Error::msg(error));
        }

        let type_: YamlEventTypeT = (*event).type_;
        match type_ {
            YamlNoEvent => writeln!(stdout, "???")?,
            YamlStreamStartEvent => writeln!(stdout, "+STR")?,
            YamlStreamEndEvent => writeln!(stdout, "-STR")?,
            YamlDocumentStartEvent => {
                write!(stdout, "+DOC")?;
                if !(*event).data.document_start.implicit {
                    write!(stdout, " ---")?;
                }
                writeln!(stdout)?;
            }
            YamlDocumentEndEvent => {
                write!(stdout, "-DOC")?;
                if !(*event).data.document_end.implicit {
                    write!(stdout, " ...")?;
                }
                writeln!(stdout)?;
            }
            YamlMappingStartEvent => {
                write!(stdout, "+MAP")?;
                if !(*event).data.mapping_start.anchor.is_null() {
                    write!(
                        stdout,
                        " &{}",
                        CStr::from_ptr(
                            (*event).data.mapping_start.anchor
                                as *const i8
                        ),
                    )?;
                }
                if !(*event).data.mapping_start.tag.is_null() {
                    write!(
                        stdout,
                        " <{}>",
                        CStr::from_ptr(
                            (*event).data.mapping_start.tag
                                as *const i8
                        ),
                    )?;
                }
                writeln!(stdout)?;
            }
            YamlMappingEndEvent => writeln!(stdout, "-MAP")?,
            YamlSequenceStartEvent => {
                write!(stdout, "+SEQ")?;
                if !(*event).data.sequence_start.anchor.is_null() {
                    write!(
                        stdout,
                        " &{}",
                        CStr::from_ptr(
                            (*event).data.sequence_start.anchor
                                as *const i8
                        ),
                    )?;
                }
                if !(*event).data.sequence_start.tag.is_null() {
                    write!(
                        stdout,
                        " <{}>",
                        CStr::from_ptr(
                            (*event).data.sequence_start.tag
                                as *const i8
                        ),
                    )?;
                }
                writeln!(stdout)?;
            }
            YamlSequenceEndEvent => writeln!(stdout, "-SEQ")?,
            YamlScalarEvent => {
                write!(stdout, "=VAL")?;
                if !(*event).data.scalar.anchor.is_null() {
                    write!(
                        stdout,
                        " &{}",
                        CStr::from_ptr(
                            (*event).data.scalar.anchor as *const i8
                        ),
                    )?;
                }
                if !(*event).data.scalar.tag.is_null() {
                    write!(
                        stdout,
                        " <{}>",
                        CStr::from_ptr(
                            (*event).data.scalar.tag as *const i8
                        ),
                    )?;
                }
                stdout.write_all(match (*event).data.scalar.style {
                    YamlPlainScalarStyle => b" :",
                    YamlSingleQuotedScalarStyle => b" '",
                    YamlDoubleQuotedScalarStyle => b" \"",
                    YamlLiteralScalarStyle => b" |",
                    YamlFoldedScalarStyle => b" >",
                    _ => {
                        return Err(Error::msg("Unknown scalar style"))
                    }
                })?;
                print_escaped(
                    stdout,
                    (*event).data.scalar.value,
                    (*event).data.scalar.length,
                )?;
                writeln!(stdout)?;
            }
            YamlAliasEvent => writeln!(
                stdout,
                "=ALI *{}",
                CStr::from_ptr((*event).data.alias.anchor as *const i8),
            )?,
            _ => return Err(Error::msg("Unknown event type")),
        }

        yaml_event_delete(event);
        if type_ == YamlStreamEndEvent {
            break;
        }
    }
    yaml_parser_delete(parser);
    Ok(())
}

/// Writes an escaped version of a byte slice to the given output.
///
/// This function handles proper escaping of special characters and
/// preserves UTF-8 encoded characters.
///
/// # Safety
///
/// This function is unsafe because it works with raw pointers.
/// The caller must ensure that `str` points to a valid memory location
/// containing at least `length` bytes.
///
/// # Arguments
///
/// * `stdout` - A mutable reference to a type that implements `Write`, to which the escaped output will be written.
/// * `str` - A raw pointer to the start of the byte slice to be escaped.
/// * `length` - The length of the byte slice.
///
/// # Returns
///
/// Returns `Ok(())` if writing succeeds, or an `io::Error` if any issues occur during writing.
unsafe fn print_escaped(
    stdout: &mut dyn Write,
    str: *const u8,
    length: u64,
) -> io::Result<()> {
    let slice = slice::from_raw_parts(str, length as usize);
    let mut chars = slice.iter().peekable();

    while let Some(&byte) = chars.next() {
        if byte >= 128 {
            // Start of a UTF-8 sequence
            stdout.write_all(slice::from_ref(&byte))?;
            while let Some(&&next_byte) = chars.peek() {
                if !(128..192).contains(&next_byte) {
                    break;
                }
                stdout.write_all(slice::from_ref(&next_byte))?;
                let _ = chars.next();
            }
        } else {
            let repr = match byte {
                b'\\' => "\\\\",
                b'\0' => "\\0",
                b'\x08' => "\\b",
                b'\n' => "\\n",
                b'\r' => "\\r",
                b'\t' => "\\t",
                _ if byte.is_ascii_graphic() || byte == b' ' => {
                    stdout.write_all(slice::from_ref(&byte))?;
                    continue;
                }
                _ => {
                    write!(stdout, "\\x{:02x}", byte)?;
                    continue;
                }
            };
            stdout.write_all(repr.as_bytes())?;
        }
    }
    Ok(())
}

/// The entry point of the program.
///
/// This function processes command-line arguments, reads YAML files,
/// and calls the parsing function for each file.
///
/// # Returns
///
/// Returns `ExitCode::SUCCESS` if all files are processed successfully,
/// or `ExitCode::FAILURE` if any errors occur.
fn main() -> ExitCode {
    let args: Vec<_> = env::args_os().skip(1).collect();
    if args.is_empty() {
        eprintln!("Error: No input files provided.");
        eprintln!(
            "Usage: {} <in.yaml>...",
            env::args().next().unwrap_or_default()
        );
        eprintln!("Please provide one or more YAML files to parse.");
        return ExitCode::FAILURE;
    }

    for arg in args {
        let path = Path::new(&arg);
        if !path.exists() {
            eprintln!("Error: File {:?} does not exist.", path);
            return ExitCode::FAILURE;
        }
        if !path.is_file() {
            eprintln!("Error: {:?} is not a file.", path);
            return ExitCode::FAILURE;
        }

        match File::open(path) {
            Ok(mut file) => {
                let mut stdout = io::stdout();
                eprintln!("Processing file: {:?}", path);
                match unsafe { unsafe_main(&mut file, &mut stdout) } {
                    Ok(()) => eprintln!(
                        "Successfully processed file: {:?}",
                        path
                    ),
                    Err(err) => {
                        eprintln!(
                            "Error processing file {:?}: {}",
                            path, err
                        );
                        eprintln!("The parser encountered an error. Please check if the file contains valid YAML.");
                        return ExitCode::FAILURE;
                    }
                }
            }
            Err(err) => {
                eprintln!("Error opening file {:?}: {}", path, err);
                eprintln!("Please check if you have the necessary permissions to read the file.");
                return ExitCode::FAILURE;
            }
        }
    }

    eprintln!("All files processed successfully.");
    ExitCode::SUCCESS
}