1use super::*;
5use crate::syntax::canon;
6
7mod decl;
8mod layout;
9pub(crate) mod migrations;
10mod stmt;
11
12#[derive(Debug)]
14pub enum FormatError {
15 Syntax(Vec<Diagnostic>),
17 Unverified,
19}
20
21enum Out {
22 Blank,
23 Line(usize, String),
25 Text(usize, String),
27 Keep(usize, String),
29 Opt {
31 depth: usize,
32 group: usize,
33 head: String,
34 width: usize,
35 body: String,
36 },
37}
38
39enum Ctx {
40 Block,
41 Match,
42 Choice(usize),
43}
44
45pub(super) struct Formatter<'a> {
46 p: Parser<'a>,
47 out: Vec<Out>,
48 ctx: Vec<Ctx>,
49 groups: usize,
50 layout: Option<(layout::Layout, Vec<usize>)>,
52}
53
54type FResult<T> = Result<T, FormatError>;
55
56fn syntax<T>(r: PResult<T>) -> FResult<T> {
57 r.map_err(|e| {
58 FormatError::Syntax(vec![Diagnostic {
59 module: String::new(),
60 line: e.pos.line,
61 col: e.pos.col,
62 severity: Severity::Error,
63 code: e.code,
64 args: e.args,
65 }])
66 })
67}
68
69fn comment_of(raw: &str) -> Option<String> {
71 let rest = &raw[strip_comment(raw).len()..];
72 (!rest.is_empty()).then(|| rest.trim_end().to_string())
73}
74
75fn with_comment(text: String, comment: Option<String>) -> String {
76 match comment {
77 Some(c) => format!("{text} {c}"),
78 None => text,
79 }
80}
81
82pub(super) fn display_width(s: &str) -> usize {
84 use unicode_width::UnicodeWidthChar;
85 s.chars().map(|c| c.width().unwrap_or(0)).sum()
86}
87
88impl<'a> Formatter<'a> {
89 pub(super) fn new(source: &'a str, module: &'a str, idents: &'a IdentMap) -> Self {
90 Formatter {
91 p: Parser::new(source, module, idents),
92 out: Vec::new(),
93 ctx: Vec::new(),
94 groups: 0,
95 layout: None,
96 }
97 }
98
99 fn depth(&self) -> usize {
100 self.ctx.len()
101 }
102
103 fn line(&mut self, text: String) {
104 let d = self.depth();
105 let Some((mut lay, used)) = self.layout.take() else {
106 self.out.push(Out::Line(d, text));
107 return;
108 };
109 let mut lines = lay.expand(&text, &used).unwrap_or_else(|_| vec![text]);
110 let mut rest = Vec::new();
111 for (c, only) in lay.leftovers() {
112 if only {
113 rest.push(c);
114 } else {
115 let last = lines.len() - 1;
116 lines[last] = format!("{} {c}", lines[last]);
117 }
118 }
119 for l in lines {
120 self.out.push(Out::Line(d, l));
121 }
122 for c in rest {
123 self.out.push(Out::Line(d, c));
124 }
125 }
126
127 pub(super) fn run(&mut self) -> FResult<()> {
128 while self.p.i < self.p.lines.len() {
129 let raw = self.p.lines[self.p.i];
130 let no = self.p.i as u32 + 1;
131 self.p.i += 1;
132 let off = indent_len(raw);
133 let t = &raw[off..];
134 if t.is_empty() {
135 self.out.push(Out::Blank);
136 continue;
137 }
138 if t.starts_with("//") {
139 self.line(t.trim_end().to_string());
140 continue;
141 }
142 match self.ctx.last() {
143 None => self.top_line(raw, no, off)?,
144 Some(Ctx::Block) => self.block_line(raw, no, off)?,
145 Some(Ctx::Match) => self.arm_line(raw, no, off)?,
146 Some(Ctx::Choice(_)) => self.option_line(raw, no, off)?,
147 }
148 }
149 Ok(())
150 }
151
152 fn block_line(&mut self, raw: &'a str, no: u32, off: usize) -> FResult<()> {
154 let t = &raw[off..];
155 if t.starts_with('}') {
156 return self.close_line(raw, no, off);
157 }
158 self.statement_line(raw, no, off)
159 }
160
161 fn close_line(&mut self, raw: &'a str, no: u32, off: usize) -> FResult<()> {
163 let comment = comment_of(raw);
164 let tail = strip_comment(&raw[off + 1..]).trim();
165 let closed = self.ctx.pop();
166 if let Some(Ctx::Choice(g)) = closed {
167 self.finish_choice(g);
168 }
169 if tail.is_empty() || tail == "," {
170 let d = self.depth();
171 self.out
172 .push(Out::Line(d, with_comment("}".to_string(), comment)));
173 return Ok(());
174 }
175 let line = Line::new(raw, no);
176 let mut ep = ExprParser::new(&line, off + 1);
177 ep.skip_ws().ok();
178 let kw = off + 1 + (raw[off + 1..].len() - raw[off + 1..].trim_start().len());
179 let after_else = kw + "else".len();
180 let rest = raw[after_else..].trim_start();
181 let text = if rest.starts_with("if") {
182 let at = raw.len() - rest.len() + 2;
183 let cond = syntax(self.header_cond(&line, at))?;
184 format!("}} else if {} {{", canon::expr(&cond))
185 } else {
186 "} else {".to_string()
187 };
188 let d = self.depth();
189 self.out.push(Out::Line(d, with_comment(text, comment)));
190 self.ctx.push(Ctx::Block);
191 Ok(())
192 }
193
194 fn header_cond(&mut self, line: &Line<'_>, after_kw: usize) -> PResult<Expr> {
196 let mut ep = ExprParser::new_header(line, after_kw);
197 let cond = ep.parse_expr()?;
198 ep.expect_char('{')?;
199 Ok(cond)
200 }
201
202 fn finish_choice(&mut self, group: usize) {
204 let max = self
205 .out
206 .iter()
207 .filter_map(|o| match o {
208 Out::Opt {
209 group: g, width, ..
210 } if *g == group => Some(*width),
211 _ => None,
212 })
213 .max()
214 .unwrap_or(0);
215 for o in &mut self.out {
216 if let Out::Opt {
217 depth,
218 group: g,
219 head,
220 width,
221 body,
222 } = o
223 && *g == group
224 {
225 let pad = if *width == usize::MAX {
226 0
227 } else {
228 max - *width
229 };
230 let text = format!("{head}{} => {body}", " ".repeat(pad));
231 *o = Out::Line(*depth, text);
232 }
233 }
234 }
235
236 pub(super) fn finish(self) -> String {
238 let mut s = String::new();
239 let mut blank_pending = false;
240 let mut prev_opens = true;
241 for o in self.out {
242 match o {
243 Out::Blank => blank_pending = true,
244 Out::Line(d, t) => {
245 if blank_pending && !prev_opens && !t.starts_with('}') {
246 s.push('\n');
247 }
248 blank_pending = false;
249 prev_opens = code_ends_with_open(&t);
250 s.push_str(&" ".repeat(d));
251 s.push_str(&t);
252 s.push('\n');
253 }
254 Out::Text(d, t) => {
255 if blank_pending && !prev_opens {
256 s.push('\n');
257 }
258 blank_pending = false;
259 prev_opens = false;
260 s.push_str(&" ".repeat(d));
261 s.push_str(&t);
262 s.push('\n');
263 }
264 Out::Keep(d, t) => {
265 blank_pending = false;
266 prev_opens = false;
267 if !t.is_empty() {
268 s.push_str(&" ".repeat(d));
269 s.push_str(&t);
270 }
271 s.push('\n');
272 }
273 Out::Opt { .. } => unreachable!("選択肢のそろえは終わっている"),
274 }
275 }
276 s
277 }
278}
279
280fn code_ends_with_open(t: &str) -> bool {
282 strip_comment(t).trim_end().ends_with('{')
283}
284
285pub(super) fn scrub_positions(debug: &str) -> String {
287 let mut out = String::with_capacity(debug.len());
288 let mut rest = debug;
289 while let Some(i) = rest.find("Pos {") {
290 out.push_str(&rest[..i]);
291 let tail = &rest[i..];
292 match tail.find('}') {
293 Some(j) => rest = &tail[j + 1..],
294 None => break,
295 }
296 }
297 out.push_str(rest);
298 out
299}
300
301pub(crate) fn format_module(
303 source: &str,
304 module: &str,
305 idents: &IdentMap,
306) -> Result<String, FormatError> {
307 let (before, diags) = parse_with(source, module, idents);
308 if diags.iter().any(|d| d.severity == Severity::Error) {
309 return Err(FormatError::Syntax(diags));
310 }
311 let mut f = Formatter::new(source, module, idents);
312 f.run()?;
313 let text = f.finish();
314 let (after, diags) = parse_with(&text, module, idents);
315 if diags.iter().any(|d| d.severity == Severity::Error)
316 || scrub_positions(&format!("{before:?}")) != scrub_positions(&format!("{after:?}"))
317 {
318 return Err(FormatError::Unverified);
319 }
320 Ok(text)
321}