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
use crate::error::{CompilerError};

use ressa::{Parser};

/// A wrapper for JavaScript source code
///
/// ```
/// use jsyc_compiler::JSSourceCode;
///
/// let js_code = jsyc_compiler::JSSourceCode::new("console.log('Hello World')".into());
/// ```
///
pub struct JSSourceCode {
    source_code: String
}

impl JSSourceCode {
    pub fn new(source_code: String) -> Self {
        JSSourceCode { source_code }
    }

    pub fn from_str(js_code: &str) -> Self {
        JSSourceCode::new(js_code.into())
    }
}

/// A wrapper for the AST of the provided JavaScript code
///
/// ```
/// use jsyc_compiler::{JSSourceCode, JSAst};
///
/// let js_code = JSSourceCode::new("console.log('Hello World')".into());
/// let js_ast = JSAst::parse(&js_code).expect("Failed to parse input code");
/// ```
pub struct JSAst {
    pub ast: resast::Program
}

impl JSAst {
    pub fn parse(source: &JSSourceCode) -> Result<Self, CompilerError> {
        let mut parser = match Parser::new(&source.source_code) {
            Ok(parser) => parser,
            Err(e) => { return Err(CompilerError::Parser(e)); }
        };

        match parser.parse() {
            Ok(ast) => Ok(JSAst{ ast }),
            Err(e) => Err(CompilerError::Parser(e))
        }
    }
}