tergo_lib/
lib.rs

1pub use formatter::config::Config;
2pub use formatter::config::FunctionLineBreaks;
3use formatter::format_code;
4use log::trace;
5use parser::{
6    ast::{Expression, TermExpr},
7    parse, pre_parse,
8};
9use tokenizer::Tokenizer;
10
11/// Format the input code with the given configuration.
12///
13/// # Arguments
14///
15/// * `input` - The input code to format.
16/// * `config` - The configuration to use for formatting.
17///   If not provided, the default configuration will be used.
18///   An instance of [Config].
19///
20/// # Returns
21///
22/// The formatted code.
23///
24/// # Example
25///
26/// ```rust
27/// use tergo_lib::tergo_format;
28/// use tergo_lib::Config;
29///
30/// let input = "a <- function(x, y){x+y}";
31/// let config = Config::default();
32///
33/// let formatted = tergo_format(input, Some(&config)).unwrap();
34/// ```
35pub fn tergo_format(input: &str, config: Option<&Config>) -> Result<String, String> {
36    let default_config = Config::default();
37    let config = config.unwrap_or(&default_config);
38    trace!("Formatting with config: {config}");
39    let mut tokenizer = Tokenizer::new(input);
40    trace!("Tokenizer created");
41    let mut commented_tokens = tokenizer.tokenize().map_err(|e| format!("{e}"))?;
42    trace!("Tokens with comments: {commented_tokens:?}",);
43    let tokens_without_comments = pre_parse(&mut commented_tokens);
44    let tokens_without_comments = parser::Input(&tokens_without_comments);
45    trace!("Tokens without comments: {}", &tokens_without_comments);
46    let cst = parse(tokens_without_comments).map_err(|e| {
47        format!(
48            "Parsing error: {}{}",
49            &e[..120.min(e.len())],
50            if 120 > e.len() { "" } else { "..." }
51        )
52    })?;
53    let top_node = Expression::Term(Box::new(TermExpr::new(None, cst, None)));
54    trace!("CST: {:?}", top_node);
55    Ok(format_code(top_node, config))
56}