webots_proto_ast/proto/
mod.rs1pub mod ast;
2pub(crate) mod lexer;
3pub mod parser;
4pub mod span;
5pub mod writer;
6
7use self::parser::Parser;
8use self::writer::ProtoWriter as Writer;
9use std::path::Path;
10use thiserror::Error;
11
12pub type ProtoResult<T> = Result<T, ProtoError>;
13
14#[derive(Error, Debug)]
15pub enum ProtoError {
16 #[error("Parsing error: {0}")]
17 ParseError(String),
18 #[error("Serialization error: {0}")]
19 SerializationError(String),
20 #[error("I/O error: {0}")]
21 IoError(#[from] std::io::Error),
22 #[error("Format error: {0}")]
23 FormatError(#[from] std::fmt::Error),
24}
25
26impl std::str::FromStr for ast::Proto {
27 type Err = ProtoError;
28
29 fn from_str(s: &str) -> Result<Self, Self::Err> {
30 let mut parser = Parser::new(s);
31 parser
32 .parse_document()
33 .map_err(|error| ProtoError::ParseError(format!("{error:?}")))
34 }
35}
36
37impl std::fmt::Display for ast::Proto {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 Writer::new().write_document_canonical(f, self)
40 }
41}
42
43impl ast::Proto {
44 pub fn from_file(path: impl AsRef<Path>) -> ProtoResult<Self> {
45 let path = path.as_ref();
46 let content = std::fs::read_to_string(path)?;
47 let mut document: ast::Proto = content.parse()?;
48 document.source_path = Some(path.to_path_buf());
49 Ok(document)
50 }
51
52 pub fn to_lossless_string(&self) -> ProtoResult<String> {
53 Writer::new().write_lossless(self)
54 }
55
56 pub fn to_canonical_string(&self) -> ProtoResult<String> {
57 Ok(Writer::new().write_canonical(self))
58 }
59}