Skip to main content

parse_named

Function parse_named 

Source
pub fn parse_named(
    source: &str,
    file_name: &str,
    flags: ParseFlags,
) -> Result<ParsedJS, ParseError>
Expand description

Parse source, calling it file_name in diagnostics.

The whole source is parsed eagerly (ParserPass::FullParse) as a Program, in the dialect flags selects. Returns ParseError if the parser reported any error — that is the same success condition the ast-dump bin applies: a Program was produced and the error count is zero.

Diagnostics are recorded in memory rather than printed; nothing is written to stderr.

use hermes_parser::{parse_named, ParseFlags};

let err = parse_named("1 +", "bad.js", ParseFlags::default())
    .expect_err("should not parse");
assert_eq!(err.error_count(), 1);
assert!(err.to_string().contains("bad.js"), "{err}");
Examples found in repository?
examples/parse_to_estree_json.rs (line 45)
21fn main() {
22    let path = std::env::args().nth(1);
23    let (name, source) = match &path {
24        Some(p) => (
25            p.as_str(),
26            std::fs::read_to_string(p).unwrap_or_else(|e| {
27                eprintln!("cannot read '{p}': {e}");
28                std::process::exit(1);
29            }),
30        ),
31        None => (
32            "<builtin>",
33            "function greet(name) { return 'Hello, ' + name; }".to_string(),
34        ),
35    };
36
37    // Plain ECMAScript. A file extension says nothing about the dialect, so
38    // like `hermesc` this example assumes none; set the flags explicitly for
39    // the others, e.g.:
40    //     ParseFlags { parse_flow: true, ..Default::default() }   // Flow
41    //     ParseFlags { parse_ts: true, ..Default::default() }     // TypeScript
42    //     ParseFlags { parse_jsx: true, ..Default::default() }    // JSX
43    let flags = ParseFlags::default();
44
45    match parse_named(&source, name, flags) {
46        Ok(mut parsed) => print!("{}", parsed.to_estree_json(true)),
47        Err(e) => {
48            // `Display` is the one-line summary; `messages()` is the full
49            // LLVM-style rendering, which is what a CLI wants.
50            for m in e.messages() {
51                eprintln!("{m}");
52            }
53            std::process::exit(1);
54        }
55    }
56}