1#[cfg(test)]
4mod tests;
5
6mod format;
7mod output;
8
9use core::fmt;
10
11use crate::alloc;
12use crate::alloc::prelude::*;
13use crate::ast::{Delimiter, Kind, Span};
14use crate::compile::{Error, ParseOptionError, Result, WithSpan};
15use crate::grammar::{Node, Remaining, Stream, Tree};
16use crate::{Diagnostics, Options, SourceId, Sources};
17
18use self::output::Comments;
19pub(crate) use self::output::Formatter;
20
21const WS: &str = " ";
22const NL: &str = "\n";
23const NL_CHAR: char = '\n';
24const TAB: &str = "\t";
25
26#[derive(Debug)]
27enum FormatErrorKind {
28 Build,
29 ParseOptionError(ParseOptionError),
30 Alloc(alloc::Error),
31}
32
33#[non_exhaustive]
35pub struct FormatError {
36 kind: FormatErrorKind,
37}
38
39impl fmt::Debug for FormatError {
40 #[inline]
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 self.kind.fmt(f)
43 }
44}
45
46impl fmt::Display for FormatError {
47 #[inline]
48 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
49 match &self.kind {
50 FormatErrorKind::Build => write!(f, "Failed to format source"),
51 FormatErrorKind::ParseOptionError(error) => error.fmt(f),
52 FormatErrorKind::Alloc(error) => error.fmt(f),
53 }
54 }
55}
56
57impl From<ParseOptionError> for FormatError {
58 fn from(value: ParseOptionError) -> Self {
59 Self {
60 kind: FormatErrorKind::ParseOptionError(value),
61 }
62 }
63}
64
65impl From<alloc::Error> for FormatError {
66 fn from(value: alloc::Error) -> Self {
67 Self {
68 kind: FormatErrorKind::Alloc(value),
69 }
70 }
71}
72
73impl core::error::Error for FormatError {}
74
75pub fn prepare(sources: &Sources) -> Prepare<'_> {
77 Prepare {
78 sources,
79 options: None,
80 diagnostics: None,
81 }
82}
83
84pub struct Prepare<'a> {
88 sources: &'a Sources,
89 options: Option<&'a Options>,
90 diagnostics: Option<&'a mut Diagnostics>,
91}
92
93impl<'a> Prepare<'a> {
94 pub fn with_diagnostics(mut self, diagnostics: &'a mut Diagnostics) -> Self {
96 self.diagnostics = Some(diagnostics);
97 self
98 }
99
100 pub fn with_options(mut self, options: &'a Options) -> Self {
102 self.options = Some(options);
103 self
104 }
105
106 pub fn format(self) -> Result<Vec<(SourceId, String)>, FormatError> {
108 let mut local;
109
110 let diagnostics = match self.diagnostics {
111 Some(diagnostics) => diagnostics,
112 None => {
113 local = Diagnostics::new();
114 &mut local
115 }
116 };
117
118 let default_options;
119
120 let options = match self.options {
121 Some(options) => options,
122 None => {
123 default_options = Options::from_default_env()?;
124 &default_options
125 }
126 };
127
128 let mut files = Vec::new();
129
130 for id in self.sources.source_ids() {
131 let Some(source) = self.sources.get(id) else {
132 continue;
133 };
134
135 let declaration = source.is_declaration();
136
137 match layout_source_as(source.as_str(), id, declaration, options, diagnostics) {
138 Ok(output) => {
139 files.try_push((id, output))?;
140 }
141 Err(error) => {
142 diagnostics.error(id, error)?;
143 }
144 }
145 }
146
147 if diagnostics.has_error() {
148 return Err(FormatError {
149 kind: FormatErrorKind::Build,
150 });
151 }
152
153 Ok(files)
154 }
155}
156
157#[cfg(all(test, not(miri)))]
159pub(crate) fn layout_source_with(
160 source: &str,
161 source_id: SourceId,
162 options: &Options,
163 diagnostics: &mut Diagnostics,
164) -> Result<String> {
165 layout_source_as(source, source_id, false, options, diagnostics)
166}
167
168pub(crate) fn layout_source_as(
171 source: &str,
172 source_id: SourceId,
173 declaration: bool,
174 options: &Options,
175 diagnostics: &mut Diagnostics,
176) -> Result<String> {
177 let tree = crate::grammar::text(source_id, source)
178 .declaration(declaration)
179 .without_processing()
180 .include_whitespace()
181 .max_nesting(options.max_depth)
182 .root()?;
183
184 check_delimiters(&tree)?;
185
186 #[cfg(feature = "std")]
187 if options.print_tree {
188 tree.print_with_source(
189 &Span::empty(),
190 format_args!("Formatting source #{source_id}"),
191 source,
192 )?;
193 }
194
195 let mut o = String::new();
196
197 {
198 let mut o = Formatter::new(
199 Span::new(0, 0),
200 source,
201 source_id,
202 &mut o,
203 &options.fmt,
204 declaration,
205 diagnostics,
206 );
207
208 o.flush_prefix_comments(&tree)?;
209 format::root(&mut o, &tree)?;
210 o.comments(Comments::Line)?;
211 o.trim_line_end();
212 }
213
214 if options.fmt.force_newline && !o.ends_with(NL) {
215 o.try_push_str(NL)
216 .with_span(Span::new(source.len(), source.len()))?;
217 }
218
219 Ok(o)
220}
221
222fn check_delimiters(tree: &Tree) -> Result<()> {
230 let mut stack = Vec::<(Delimiter, Span)>::new();
231
232 for node in tree.walk().filter(|node| node.is_token()) {
233 match node.kind() {
234 Kind::Open(delimiter) if delimiter != Delimiter::Empty => {
235 stack.try_push((delimiter, node.span()))?;
236 }
237 Kind::Close(delimiter) if delimiter != Delimiter::Empty => match stack.pop() {
238 Some((open, _)) if open == delimiter => {}
239 Some((open, span)) => {
240 return Err(Error::msg(
241 span.join(node.span()),
242 format_args!(
243 "Mismatched delimiter `{}`, expected `{}` to close `{}`",
244 delimiter.close(),
245 open.close(),
246 open.open()
247 ),
248 ));
249 }
250 None => {
251 return Err(Error::msg(
252 node.span(),
253 format_args!("Unexpected closing delimiter `{}`", delimiter.close()),
254 ));
255 }
256 },
257 _ => {}
258 }
259 }
260
261 if let Some((open, span)) = stack.pop() {
262 return Err(Error::msg(
263 span,
264 format_args!("Unclosed delimiter `{}`", open.open()),
265 ));
266 }
267
268 Ok(())
269}