px_wsdom_ts_convert/
lib.rs1use parser::{comment::WithComment, item::Item};
2use quote::quote;
3
4pub(crate) mod generator;
5pub(crate) use px_wsdom_ts_parse::parser;
6
7struct ParseError {
8 content: String,
9 error: winnow::error::ContextError,
10}
11
12impl std::fmt::Debug for ParseError {
13 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14 f.debug_struct("ParseError")
15 .field("content", &self.content)
16 .field("error", &self.error)
17 .finish()
18 }
19}
20
21impl std::fmt::Display for ParseError {
22 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23 std::fmt::Debug::fmt(&self, f)
24 }
25}
26
27impl std::error::Error for ParseError {}
28
29fn parse_str(content: &str) -> Result<Vec<WithComment<'_, Item<'_>>>, Box<dyn std::error::Error>> {
30 use winnow::Parser;
31 let mut input = content;
32
33 let _imports = match parser::parse_imports.parse_next(&mut input) {
34 Ok(i) => i,
35 Err(e) => {
36 return Err(ParseError {
37 error: e
38 .into_inner()
39 .expect("complete parsers should not report `ErrMode::Incomplete(_)`"),
40 content: content.to_string(),
41 }
42 .into())
43 }
44 };
45
46 parser::parse_all.parse(input).map_err(|e| {
47 ParseError {
48 error: e.into_inner(),
49 content: content.to_string(),
50 }
51 .into()
52 })
53}
54
55pub fn convert(
56 file: std::fs::File,
57) -> Result<proc_macro2::TokenStream, Box<dyn std::error::Error>> {
58 let content = std::io::read_to_string(file)?;
59 let parsed = parse_str(&*content)?;
60 let out = generator::generate_all(&parsed, &[]);
61
62 Ok(out)
63}
64
65pub fn convert_custom(
66 file: std::fs::File,
67) -> Result<proc_macro2::TokenStream, Box<dyn std::error::Error>> {
68 let custom_content = std::io::read_to_string(file)?;
69 let custom_parsed = parse_str(&*custom_content)?;
70
71 let out = generator::generate_all(&custom_parsed, &[]);
72
73 Ok(quote! {
74 use wsdom::__wsdom_load_ts_macro;
75 use wsdom::dom::*;
76 use wsdom::js::*;
77 #out
78 })
79}