1#![forbid(unsafe_code)]
2use std::error::Error as StdError;
25use std::fmt;
26
27pub use draxl_ast as ast;
28pub use draxl_lower_rust as lower_rust;
29pub use draxl_parser as parser;
30pub use draxl_patch as patch;
31pub use draxl_printer as printer;
32pub use draxl_validate as validate;
33
34pub type Result<T> = std::result::Result<T, Error>;
36
37#[derive(Debug)]
39pub enum Error {
40 Parse(parser::ParseError),
42 Validation(Vec<validate::ValidationError>),
44}
45
46impl Error {
47 pub fn validation_errors(&self) -> Option<&[validate::ValidationError]> {
49 match self {
50 Self::Validation(errors) => Some(errors),
51 Self::Parse(_) => None,
52 }
53 }
54}
55
56impl fmt::Display for Error {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 match self {
59 Self::Parse(error) => error.fmt(f),
60 Self::Validation(errors) => {
61 f.write_str("validation failed:")?;
62 for error in errors {
63 f.write_str("\n- ")?;
64 f.write_str(&error.message)?;
65 }
66 Ok(())
67 }
68 }
69 }
70}
71
72impl StdError for Error {
73 fn source(&self) -> Option<&(dyn StdError + 'static)> {
74 match self {
75 Self::Parse(error) => Some(error),
76 Self::Validation(_) => None,
77 }
78 }
79}
80
81impl From<parser::ParseError> for Error {
82 fn from(error: parser::ParseError) -> Self {
83 Self::Parse(error)
84 }
85}
86
87pub fn parse_file(source: &str) -> std::result::Result<ast::File, parser::ParseError> {
89 parser::parse_file(source)
90}
91
92pub fn validate_file(file: &ast::File) -> std::result::Result<(), Vec<validate::ValidationError>> {
94 validate::validate_file(file)
95}
96
97pub fn parse_and_validate(source: &str) -> Result<ast::File> {
99 let file = parse_file(source)?;
100 validate_file(&file).map_err(Error::Validation)?;
101 Ok(file)
102}
103
104pub fn format_file(file: &ast::File) -> String {
106 printer::print_file(file)
107}
108
109pub fn format_source(source: &str) -> Result<String> {
111 let file = parse_and_validate(source)?;
112 Ok(format_file(&file))
113}
114
115pub fn dump_json_file(file: &ast::File) -> String {
117 printer::canonicalize_file(file).to_json_pretty()
118}
119
120pub fn dump_json_source(source: &str) -> Result<String> {
122 let file = parse_and_validate(source)?;
123 Ok(dump_json_file(&file))
124}
125
126pub fn lower_rust_file(file: &ast::File) -> String {
128 lower_rust::lower_file(file)
129}
130
131pub fn lower_rust_source(source: &str) -> Result<String> {
133 let file = parse_and_validate(source)?;
134 Ok(lower_rust_file(&file))
135}
136
137pub fn apply_patch(
139 file: &mut ast::File,
140 op: patch::PatchOp,
141) -> std::result::Result<(), patch::PatchError> {
142 patch::apply_op(file, op)
143}
144
145pub fn apply_patches(
147 file: &mut ast::File,
148 ops: impl IntoIterator<Item = patch::PatchOp>,
149) -> std::result::Result<(), patch::PatchError> {
150 patch::apply_ops(file, ops)
151}