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
//! A command-line interpreter and REPL for sljs.
//!
//! It starts a REPL by default.
//! Multiple files can be specified to interpret.
//! Also, `-e` takes a snippet from a commandline (can be specified multple times):
//!
//! ```console
//! $ sljs -e 'var x = 12' -e 'x + x'
//! 24
//! ```
//!
//! If you want to load some files/evaluate snippets **and** start REPL after that,
//! add `-i`:
//!
//! ```console
//! $ sljs ./fib.js -i
//! sljs> fib(20)
//! 10946
//! ```
//!
//! Selecting a parser:
//! - `-E`, `--esprima` select [`EsprimaParser`]
//! - `-N`, `--nodejs` select [`NodejsParser`]
//! - `-J`, `--json` select [`JSONParser`] (deserialization of JSON ESTree)
//! - without flags: if [`NodejsParser::NODE`] works, [`NodejsParser`] is used,
//!   otherwise it falls back to [`EsprimaParser`]. Check the parser with `--debug`.
//!

// TODO: `-j` for JSON output
// TODO: readline, more human-friendly editing
// TODO: tab completion?
// TODO: register native `console.log` and alike

use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::path::PathBuf;

use atty::{
    self,
    Stream,
};

use clap::Parser;

use sljs::runtime::{
    EsprimaParser,
    JSONParser,
    NodejsParser,
    Parser as JSParser,
    Runtime,
};
use sljs::{
    source,
    JSValue,
};

#[derive(clap::Parser)]
#[clap(author, version, about)]
#[clap(name = "sljs")]
struct Args {
    /// The source files to read, may be empty for stdin.
    sources: Vec<PathBuf>,

    /// Evaluate a snippet
    #[clap(short, long)]
    eval: Vec<String>,

    /// Run REPL even if `sources` or `eval` were given
    #[clap(short, long, action)]
    interactive: bool,

    /// Parse sources using Esprima in an external Nodejs process
    #[clap(short = 'N', long, action)]
    nodejs: bool,

    /// Parse sources using an internal Esprima instance \[experimental\]
    #[clap(short = 'E', long, action)]
    esprima: bool,

    /// Expect ESTree AST as JSON input
    #[clap(short = 'J', long, action)]
    json: bool,

    /// Debug output
    #[clap(short, long, action)]
    debug: bool,
}

impl Args {
    fn select_parser(&self) -> io::Result<Box<dyn JSParser>> {
        Ok(match (self.esprima, self.nodejs, self.json) {
            (true, false, false) => EsprimaParser::new(),
            (false, true, false) => NodejsParser::new(),
            (false, false, true) => Box::new(JSONParser),
            (false, false, false) => {
                if NodejsParser::works()? {
                    NodejsParser::new()
                } else {
                    EsprimaParser::new()
                }
            }
            _ => {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    "Only one of -E/-N/-J can be set",
                ))
            }
        })
    }
}

/// Provides a simple command line using stdin/stdout.
fn repl_main(sljs: &mut Runtime) -> io::Result<()> {
    let stdin = io::stdin();
    let mut input_iter = stdin.lock().lines();

    loop {
        // prompt
        eprint!("sljs> ");
        io::stderr().flush()?;

        // get input
        #[allow(clippy::significant_drop_in_scrutinee)]
        let input = match input_iter.next() {
            None => break,
            Some(input) => input?,
        };
        if input.is_empty() {
            continue;
        }

        if let Some(refstr) = input.strip_prefix(":dbg ") {
            sljs.dbg(refstr);
            continue;
        }

        match sljs.evaluate(&input) {
            Ok(result) => println!("{}", sljs.string_from(result)),
            Err(err) => {
                eprintln!("{}", err);
                if let Err(e) = source::print_callstack(&sljs.heap) {
                    eprintln!("   Exception thrown while getting stack trace: {:?}", e);
                }
            }
        }
    }

    Ok(())
}

fn main() -> io::Result<()> {
    let args = Args::parse();

    let parser = args.select_parser()?;
    if args.debug {
        dbg!(&parser);
    }
    let mut sljs = Runtime::load(parser)?;

    let mut interactive = args.sources.is_empty() && args.eval.is_empty();
    let mut result = JSValue::Undefined;

    // handle sources:
    for filepath in args.sources.iter() {
        if args.debug {
            dbg!(filepath);
        };

        let mut input = String::new();
        if filepath.as_os_str() == "-" {
            io::stdin().lock().read_to_string(&mut input)?;
        } else {
            File::open(filepath)?.read_to_string(&mut input)?;
        };

        result = sljs.evaluate(&input)?;
    }

    // handle eval snippets:
    for (_, eval) in args.eval.iter().enumerate() {
        if args.debug {
            dbg!(eval);
        };

        //let name = format!("<eval:{}>", i);
        result = sljs.evaluate(eval)?;
    }

    // if args.interactive, override:
    interactive = interactive || args.interactive;
    if !interactive {
        if result != JSValue::Undefined {
            println!("{}", sljs.string_from(result));
        }
        return Ok(());
    }

    if !atty::is(Stream::Stdin) {
        let mut input = String::new();
        io::stdin().lock().read_to_string(&mut input)?;
        result = sljs.evaluate(&input)?;
        if result != JSValue::Undefined {
            println!("{}", sljs.string_from(result));
        }
        return Ok(());
    }

    repl_main(&mut sljs)
}