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
//! Artichoke CLI entry point.
//!
//! Artichoke's version of the `ruby` CLI. This module is exported as the
//! `artichoke` binary.

use std::error;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use termcolor::WriteColor;

use crate::backend::platform_string::os_str_to_bytes;
use crate::backend::state::parser::Context;
use crate::backend::string::format_unicode_debug_into;
use crate::backtrace;
use crate::filename::INLINE_EVAL_SWITCH;
use crate::prelude::*;

/// Command line arguments for Artichoke `ruby` frontend.
#[derive(Default, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Args {
    /// print the copyright
    copyright: bool,
    /// one line of script. Several -e's allowed. Omit \[programfile\]
    commands: Vec<OsString>,
    /// file whose contents will be read into the `$fixture` global
    fixture: Option<PathBuf>,
    programfile: Option<PathBuf>,
    /// Trailing positional arguments.
    ///
    /// Requires `programfile` to be present.
    argv: Vec<OsString>,
}

impl Args {
    /// Construct a new, empty `Args`.
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            copyright: false,
            commands: Vec::new(),
            fixture: None,
            programfile: None,
            argv: Vec::new(),
        }
    }

    /// Add a parsed copyright flag to this `Args`.
    #[must_use]
    pub fn with_copyright(mut self, copyright: bool) -> Self {
        self.copyright = copyright;
        self
    }

    /// Add a parsed set of `-e` inline eval commands to this `Args`.
    #[must_use]
    pub fn with_commands(mut self, commands: Vec<OsString>) -> Self {
        self.commands = commands;
        self
    }

    /// Add a parsed fixture path to this `Args`.
    #[must_use]
    pub fn with_fixture(mut self, fixture: Option<PathBuf>) -> Self {
        self.fixture = fixture;
        self
    }

    /// Add a parsed program file path to this `Args`.
    #[must_use]
    pub fn with_programfile(mut self, programfile: Option<PathBuf>) -> Self {
        self.programfile = programfile;
        self
    }

    /// Add a parsed ARGV to this `Args`.
    #[must_use]
    pub fn with_argv(mut self, argv: Vec<OsString>) -> Self {
        self.argv = argv;
        self
    }
}

/// Main entry point for Artichoke's version of the `ruby` CLI.
///
/// # Errors
///
/// If an exception is raised on the interpreter, then an error is returned.
pub fn run<R, W>(args: Args, input: R, error: W) -> Result<Result<(), ()>, Box<dyn error::Error>>
where
    R: io::Read,
    W: io::Write + WriteColor,
{
    let mut interp = crate::interpreter()?;
    let result = entrypoint(&mut interp, args, input, error);
    interp.close();
    result
}

/// Main entry point for Artichoke's version of the `ruby` CLI.
///
/// # Errors
///
/// If an exception is raised on the interpreter, then an error is returned.
pub fn entrypoint<R, W>(
    interp: &mut Artichoke,
    args: Args,
    mut input: R,
    error: W,
) -> Result<Result<(), ()>, Box<dyn error::Error>>
where
    R: io::Read,
    W: io::Write + WriteColor,
{
    if args.copyright {
        let _ = interp.eval(b"puts RUBY_COPYRIGHT")?;
        return Ok(Ok(()));
    }

    // Inject ARGV global.
    let mut ruby_program_argv = Vec::new();
    for argument in &args.argv {
        let argument = os_str_to_bytes(argument)?;
        let mut argument = interp.try_convert_mut(argument)?;
        argument.freeze(interp)?;
        ruby_program_argv.push(argument);
    }
    let ruby_program_argv = interp.try_convert_mut(ruby_program_argv)?;
    interp.define_global_constant("ARGV", ruby_program_argv)?;

    if !args.commands.is_empty() {
        execute_inline_eval(interp, error, args.commands, args.fixture.as_deref())
    } else if let Some(programfile) = args.programfile.filter(|file| file != Path::new("-")) {
        execute_program_file(interp, error, programfile.as_path(), args.fixture.as_deref())
    } else {
        let mut program = vec![];
        input
            .read_to_end(&mut program)
            .map_err(|_| IOError::from("Could not read program from STDIN"))?;
        if let Err(ref exc) = interp.eval(program.as_slice()) {
            backtrace::format_cli_trace_into(error, interp, exc)?;
            return Ok(Err(()));
        }
        Ok(Ok(()))
    }
}

fn execute_inline_eval<W>(
    interp: &mut Artichoke,
    error: W,
    commands: Vec<OsString>,
    fixture: Option<&Path>,
) -> Result<Result<(), ()>, Box<dyn error::Error>>
where
    W: io::Write + WriteColor,
{
    interp.pop_context()?;
    // Safety:
    //
    // - `Context::new_unchecked` requires that its argument has no NUL bytes.
    // - `INLINE_EVAL_SWITCH` is controlled by this crate.
    // - A test asserts that `INLINE_EVAL_SWITCH` has no NUL bytes.
    let context = unsafe { Context::new_unchecked(INLINE_EVAL_SWITCH) };
    interp.push_context(context)?;
    if let Some(fixture) = fixture {
        setup_fixture_hack(interp, fixture)?;
    }
    let mut commands = commands.into_iter();
    let mut buf = if let Some(command) = commands.next() {
        command
    } else {
        return Ok(Ok(()));
    };
    for command in commands {
        buf.push("\n");
        buf.push(command);
    }
    if let Err(ref exc) = interp.eval_os_str(&buf) {
        backtrace::format_cli_trace_into(error, interp, exc)?;
        // short circuit, but don't return an error since we already printed it
        return Ok(Err(()));
    }
    Ok(Ok(()))
}

fn execute_program_file<W>(
    interp: &mut Artichoke,
    error: W,
    programfile: &Path,
    fixture: Option<&Path>,
) -> Result<Result<(), ()>, Box<dyn error::Error>>
where
    W: io::Write + WriteColor,
{
    if let Some(fixture) = fixture {
        setup_fixture_hack(interp, fixture)?;
    }
    if let Err(ref exc) = interp.eval_file(programfile) {
        backtrace::format_cli_trace_into(error, interp, exc)?;
        return Ok(Err(()));
    }
    Ok(Ok(()))
}

fn load_error<P: AsRef<OsStr>>(file: P, message: &str) -> Result<String, Error> {
    let mut buf = String::from(message);
    buf.push_str(" -- ");
    let path = os_str_to_bytes(file.as_ref())?;
    format_unicode_debug_into(&mut buf, path)?;
    Ok(buf)
}

// This function exists to provide a workaround for Artichoke not being able to
// read from the local filesystem.
//
// By passing the `--with-fixture PATH` argument, this function loads the file
// at `PATH` into memory and stores it in the interpreter bound to the
// `$fixture` global.
#[inline]
fn setup_fixture_hack<P: AsRef<Path>>(interp: &mut Artichoke, fixture: P) -> Result<(), Error> {
    let data = if let Ok(data) = fs::read(fixture.as_ref()) {
        data
    } else {
        return Err(LoadError::from(load_error(fixture.as_ref(), "No such file or directory")?).into());
    };
    let value = interp.convert_mut(data);
    interp.set_global_variable(&b"$fixture"[..], &value)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::ffi::OsString;
    use std::path::PathBuf;
    use termcolor::Ansi;

    use super::{run, Args};

    #[test]
    fn run_with_copyright() {
        let args = Args::empty().with_copyright(true);
        let input = Vec::<u8>::new();
        let mut err = Ansi::new(Vec::new());
        assert!(matches!(run(args, &input[..], &mut err), Ok(Ok(_))));
    }

    #[test]
    fn run_with_programfile_from_stdin() {
        let args = Args::empty().with_programfile(Some(PathBuf::from("-")));
        let input = b"2 + 7";
        let mut err = Ansi::new(Vec::new());
        assert!(matches!(run(args, &input[..], &mut err), Ok(Ok(_))));
    }

    #[test]
    fn run_with_programfile_from_stdin_raise_exception() {
        let args = Args::empty().with_programfile(Some(PathBuf::from("-")));
        let input = b"raise ArgumentError";
        let mut err = Ansi::new(Vec::new());
        assert!(matches!(run(args, &input[..], &mut err), Ok(Err(_))));
    }

    #[test]
    fn run_with_stdin() {
        let args = Args::empty();
        let input = b"2 + 7";
        let mut err = Ansi::new(Vec::new());
        assert!(matches!(run(args, &input[..], &mut err), Ok(Ok(_))));
    }

    #[test]
    fn run_with_stdin_raise_exception() {
        let args = Args::empty();
        let input = b"raise ArgumentError";
        let mut err = Ansi::new(Vec::new());
        assert!(matches!(run(args, &input[..], &mut err), Ok(Err(_))));
    }

    #[test]
    fn run_with_inline_eval() {
        let args = Args::empty().with_commands(vec![OsString::from("2 + 7")]);
        let input = Vec::<u8>::new();
        let mut err = Ansi::new(Vec::new());
        assert!(matches!(run(args, input.as_slice(), &mut err), Ok(Ok(_))));
    }

    #[test]
    fn run_with_inline_eval_raise_exception() {
        let args = Args::empty().with_commands(vec![OsString::from("raise ArgumentError")]);
        let input = Vec::<u8>::new();
        let mut err = Ansi::new(Vec::new());
        assert!(matches!(run(args, &input[..], &mut err), Ok(Err(_))));
    }
}