Skip to main content

rucc_ast/
print.rs

1//! The printer, which turns a tree back into C.
2//!
3//! Design: `spec/06-lexer-and-parser.md` section 6.2.
4//!
5//! What comes out is not the source that went in. Comments are gone, the layout is the
6//! printer's own, and a constant is written in the spelling the printer has rather than the one
7//! the author had. What is guaranteed is that parsing the output gives the same tree back, and
8//! so that printing it a second time gives the same text. That is the property `--emit=ast` is
9//! worth having: a printer that agrees with the parser is a check on both of them, and one that
10//! merely looks right is a check on nothing.
11//!
12//! # What that costs
13//!
14//! Three things are written in a way that reads oddly and round-trips exactly.
15//!
16//! A floating constant comes out in hexadecimal, so `1.0` prints as `0x1p+0`. A decimal
17//! constant that reads back unchanged needs a shortest-round-trip algorithm, and printing one
18//! without such an algorithm quietly changes the program. Hexadecimal is exact by construction.
19//!
20//! A keyword comes out in the spelling that is a keyword in every dialect, so `_Bool` rather
21//! than `bool` and `__asm__` rather than `asm`. The tree does not record which dialect it was
22//! parsed in, and the ugly spelling is the one that survives all of them.
23//!
24//! Parentheses come out where the grammar needs them and not where the author wrote them,
25//! because the tree does not record them. `(a) + (b)` prints as `a + b`, and `a + b * c` keeps
26//! the parentheses it needs and loses the ones it does not.
27//!
28//! # Using it
29//!
30//! ```
31//! use rucc_ast::{Ast, BinaryOp, Expr, Printer};
32//! use rucc_base::Interner;
33//! use rucc_diag::Span;
34//!
35//! let mut interner = Interner::new();
36//! let a = interner.intern("a");
37//! let mut ast = Ast::new();
38//! let left = ast.expr(Expr::Name(a), Span::DUMMY);
39//! let right = ast.expr(Expr::Bool(true), Span::DUMMY);
40//! let both = ast.expr(Expr::Binary { op: BinaryOp::Add, lhs: left, rhs: right }, Span::DUMMY);
41//!
42//! let mut printer = Printer::new(&ast, &interner);
43//! printer.expr(both);
44//! assert_eq!(printer.finish(), "a + true");
45//! ```
46
47use rucc_base::{Interner, Symbol};
48
49use crate::asm::{AsmId, AsmQuals};
50use crate::ast::{
51    AsmOperandList, Ast, AttrList, DesignatorList, EnumeratorList, ExprList, GenericList,
52    MemberList, ParamList, StrId, StrList, SymbolList,
53};
54use crate::attr::{AttrArg, AttrSyntax};
55use crate::decl::{
56    ArraySize, Decl, DeclId, DeclaratorId, Derived, Field, Member, Param, ParamKind, TypeNameId,
57};
58use crate::expr::{BinaryOp, Expr, ExprId, UnaryOp};
59use crate::init::{Designator, Init, InitId};
60use crate::spec::TypeofArg;
61use crate::spec::{AlignSpec, Builtin, BuiltinSet, DeclSpecsId, FuncSpecs, Quals, TypeSpec};
62use crate::stmt::{ForInit, Stmt, StmtId};
63
64/// The comma operator, which binds least of all.
65const COMMA: u8 = 1;
66/// Assignment, and the compound assignments.
67const ASSIGN: u8 = 2;
68/// The conditional operator, which is also what a constant expression is.
69const COND: u8 = 3;
70/// `||`.
71const LOG_OR: u8 = 4;
72/// `&&`.
73const LOG_AND: u8 = 5;
74/// `|`.
75const BIT_OR: u8 = 6;
76/// `^`.
77const BIT_XOR: u8 = 7;
78/// `&`.
79const BIT_AND: u8 = 8;
80/// `==` and `!=`.
81const EQUALITY: u8 = 9;
82/// `<`, `>`, `<=` and `>=`.
83const RELATIONAL: u8 = 10;
84/// `<<` and `>>`.
85const SHIFT: u8 = 11;
86/// `+` and `-`.
87const ADDITIVE: u8 = 12;
88/// `*`, `/` and `%`.
89const MULTIPLICATIVE: u8 = 13;
90/// A cast.
91const CAST: u8 = 14;
92/// The prefix operators.
93const UNARY: u8 = 15;
94/// The postfix operators, which is also where a compound literal sits.
95const POSTFIX: u8 = 16;
96/// A name, a constant, and anything that is bracketed all the way round.
97const PRIMARY: u8 = 17;
98
99/// How tightly a binary operator binds.
100const fn binding(op: BinaryOp) -> u8 {
101    match op {
102        BinaryOp::Mul | BinaryOp::Div | BinaryOp::Rem => MULTIPLICATIVE,
103        BinaryOp::Add | BinaryOp::Sub => ADDITIVE,
104        BinaryOp::Shl | BinaryOp::Shr => SHIFT,
105        BinaryOp::Lt | BinaryOp::Gt | BinaryOp::Le | BinaryOp::Ge => RELATIONAL,
106        BinaryOp::Eq | BinaryOp::Ne => EQUALITY,
107        BinaryOp::BitAnd => BIT_AND,
108        BinaryOp::BitXor => BIT_XOR,
109        BinaryOp::BitOr => BIT_OR,
110        BinaryOp::LogAnd => LOG_AND,
111        BinaryOp::LogOr => LOG_OR,
112    }
113}
114
115/// The type keywords, in the order they are written back out.
116///
117/// `long` is not here because it is the one that may be written twice, so it is counted rather
118/// than held in the set and is put back where it belongs by hand.
119const BUILTIN_SPELLINGS: &[(BuiltinSet, &str)] = &[
120    (BuiltinSet::SIGNED, "signed"),
121    (BuiltinSet::UNSIGNED, "unsigned"),
122    (BuiltinSet::SHORT, "short"),
123    (BuiltinSet::VOID, "void"),
124    (BuiltinSet::BOOL, "_Bool"),
125    (BuiltinSet::CHAR, "char"),
126    (BuiltinSet::INT, "int"),
127    (BuiltinSet::INT128, "__int128"),
128    (BuiltinSet::FLOAT, "float"),
129    (BuiltinSet::DOUBLE, "double"),
130    (BuiltinSet::COMPLEX, "_Complex"),
131    (BuiltinSet::IMAGINARY, "_Imaginary"),
132    (BuiltinSet::FLOAT16, "_Float16"),
133    (BuiltinSet::FLOAT32, "_Float32"),
134    (BuiltinSet::FLOAT64, "_Float64"),
135    (BuiltinSet::FLOAT128, "_Float128"),
136    (BuiltinSet::FLOAT32X, "_Float32x"),
137    (BuiltinSet::FLOAT64X, "_Float64x"),
138    (BuiltinSet::FLOAT128X, "_Float128x"),
139    (BuiltinSet::FLOAT80, "__float80"),
140    (BuiltinSet::DECIMAL32, "_Decimal32"),
141    (BuiltinSet::DECIMAL64, "_Decimal64"),
142    (BuiltinSet::DECIMAL128, "_Decimal128"),
143];
144
145/// Whether writing `next` straight after `last` would make one token out of two.
146///
147/// The check is on the two characters that meet, which is enough: every C token that could be
148/// formed by accident starts with a pair that is listed here or is two identifier characters
149/// running together. Getting this wrong is how a printer turns `a / *p` into a comment.
150fn pastes(last: char, next: char) -> bool {
151    let word = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$';
152    if word(last) && word(next) {
153        return true;
154    }
155    // A pp-number takes a dot on either side of it, which is what makes `case 1 ... 2` need its
156    // spaces and `1 .x` need one too.
157    if (last == '.' && next.is_ascii_digit()) || (last.is_ascii_digit() && next == '.') {
158        return true;
159    }
160    matches!(
161        (last, next),
162        ('+', '+' | '=')
163            | ('-', '-' | '=' | '>')
164            | ('*', '=')
165            | ('/', '=' | '/' | '*')
166            | ('%', '=' | '>' | ':')
167            | ('<', '<' | '=' | ':' | '%')
168            | ('>', '>' | '=')
169            | ('=', '=')
170            | ('!', '=')
171            | ('&', '&' | '=')
172            | ('|', '|' | '=')
173            | ('^', '=')
174            | ('.', '.')
175            | (':', '>' | ':')
176            | ('#', '#')
177    )
178}
179
180/// Joins two pieces of a declarator, keeping them two tokens if they would otherwise be one.
181fn join(mut left: String, right: &str) -> String {
182    if let (Some(last), Some(next)) = (left.chars().next_back(), right.chars().next()) {
183        if pastes(last, next) {
184            left.push(' ');
185        }
186    }
187    left.push_str(right);
188    left
189}
190
191/// The whole translation unit, as text.
192#[must_use]
193pub fn print(ast: &Ast, names: &Interner) -> String {
194    let mut printer = Printer::new(ast, names);
195    printer.unit();
196    printer.finish()
197}
198
199/// A tree being written out as C.
200#[derive(Debug)]
201pub struct Printer<'a> {
202    ast: &'a Ast,
203    names: &'a Interner,
204    out: String,
205    depth: usize,
206}
207
208impl<'a> Printer<'a> {
209    /// A printer over one tree, whose names are in `names`.
210    #[must_use]
211    pub fn new(ast: &'a Ast, names: &'a Interner) -> Printer<'a> {
212        Printer { ast, names, out: String::new(), depth: 0 }
213    }
214
215    /// The text written so far.
216    #[must_use]
217    pub fn finish(self) -> String {
218        self.out
219    }
220
221    /// Every declaration of the translation unit, one after another.
222    pub fn unit(&mut self) {
223        let ast = self.ast;
224        for (index, &decl) in ast.top_level().iter().enumerate() {
225            if index > 0 {
226                self.newline();
227            }
228            self.decl(decl);
229        }
230        if !self.out.is_empty() {
231            self.out.push('\n');
232        }
233    }
234
235    /// One declaration, semicolon included.
236    pub fn decl(&mut self, id: DeclId) {
237        let ast = self.ast;
238        match ast[id] {
239            // A poisoned declaration is written as the empty one, which is what it parses back
240            // as and which keeps a broken tree printing to a fixed point like any other.
241            Decl::Error => self.token(";"),
242            Decl::Var { specs, declarators } => {
243                self.decl_specs(specs);
244                for (index, item) in ast[declarators].iter().enumerate() {
245                    if index > 0 {
246                        self.token(",");
247                    }
248                    self.space();
249                    let text = self.declarator_text(item.declarator);
250                    self.token(&text);
251                    if let Some(label) = item.asm_label {
252                        self.space();
253                        self.token("__asm__");
254                        self.token("(");
255                        self.string(label);
256                        self.token(")");
257                    }
258                    self.attributes(item.attrs);
259                    if let Some(init) = item.init {
260                        self.space();
261                        self.token("=");
262                        self.space();
263                        self.init(init);
264                    }
265                }
266                self.token(";");
267            }
268            Decl::Function { specs, declarator, params, body } => {
269                self.decl_specs(specs);
270                self.space();
271                let text = self.declarator_text(declarator);
272                self.token(&text);
273                self.depth += 1;
274                for &param in &ast[params] {
275                    self.newline();
276                    self.decl(param);
277                }
278                self.depth -= 1;
279                self.newline();
280                self.stmt(body);
281            }
282            Decl::StaticAssert { cond, message } => {
283                self.static_assert(cond, message);
284            }
285            Decl::Asm(asm) => {
286                self.asm(asm);
287                self.token(";");
288            }
289            Decl::Attributes(attrs) => {
290                self.attributes(attrs);
291                self.token(";");
292            }
293        }
294    }
295
296    /// One statement, on the line it was put on.
297    pub fn stmt(&mut self, id: StmtId) {
298        let ast = self.ast;
299        match ast[id] {
300            // Poisoned, and written as the empty statement for the reason a poisoned
301            // declaration is written as the empty one.
302            Stmt::Error | Stmt::Empty => self.token(";"),
303            Stmt::Expr(expr) => {
304                self.expr_at(expr, COMMA);
305                self.token(";");
306            }
307            Stmt::Decl(decl) => self.decl(decl),
308            Stmt::Compound(items) => {
309                self.token("{");
310                self.depth += 1;
311                for &item in &ast[items] {
312                    self.newline();
313                    self.stmt(item);
314                }
315                self.depth -= 1;
316                self.newline();
317                self.token("}");
318            }
319            Stmt::If { cond, then, otherwise } => {
320                self.token("if");
321                self.space();
322                self.token("(");
323                self.expr_at(cond, COMMA);
324                self.token(")");
325                if otherwise.is_some() && self.dangling(then) {
326                    self.braced(then);
327                } else {
328                    self.body(then);
329                }
330                if let Some(otherwise) = otherwise {
331                    self.newline();
332                    self.token("else");
333                    if matches!(ast[otherwise], Stmt::If { .. }) {
334                        self.space();
335                        self.stmt(otherwise);
336                    } else {
337                        self.body(otherwise);
338                    }
339                }
340            }
341            Stmt::Switch { scrutinee, body } => {
342                self.token("switch");
343                self.space();
344                self.token("(");
345                self.expr_at(scrutinee, COMMA);
346                self.token(")");
347                self.body(body);
348            }
349            Stmt::While { cond, body } => {
350                self.token("while");
351                self.space();
352                self.token("(");
353                self.expr_at(cond, COMMA);
354                self.token(")");
355                self.body(body);
356            }
357            Stmt::DoWhile { body, cond } => {
358                self.token("do");
359                self.body(body);
360                self.newline();
361                self.token("while");
362                self.space();
363                self.token("(");
364                self.expr_at(cond, COMMA);
365                self.token(")");
366                self.token(";");
367            }
368            Stmt::For { init, cond, step, body } => {
369                self.token("for");
370                self.space();
371                self.token("(");
372                match init {
373                    ForInit::None => self.token(";"),
374                    ForInit::Expr(expr) => {
375                        self.expr_at(expr, COMMA);
376                        self.token(";");
377                    }
378                    // The declaration writes its own semicolon, since it is a whole declaration
379                    // and not an expression that happens to be in a loop header.
380                    ForInit::Decl(decl) => self.decl(decl),
381                }
382                if let Some(cond) = cond {
383                    self.space();
384                    self.expr_at(cond, COMMA);
385                }
386                self.token(";");
387                if let Some(step) = step {
388                    self.space();
389                    self.expr_at(step, COMMA);
390                }
391                self.token(")");
392                self.body(body);
393            }
394            Stmt::Goto(name) => {
395                self.token("goto");
396                self.space();
397                self.name(name);
398                self.token(";");
399            }
400            Stmt::GotoExpr(expr) => {
401                self.token("goto");
402                self.space();
403                self.token("*");
404                self.expr_at(expr, CAST);
405                self.token(";");
406            }
407            Stmt::Continue => {
408                self.token("continue");
409                self.token(";");
410            }
411            Stmt::Break => {
412                self.token("break");
413                self.token(";");
414            }
415            Stmt::Return(value) => {
416                self.token("return");
417                if let Some(value) = value {
418                    self.space();
419                    self.expr_at(value, COMMA);
420                }
421                self.token(";");
422            }
423            Stmt::Label { name, body, attrs } => {
424                self.attributes(attrs);
425                self.space();
426                self.name(name);
427                self.token(":");
428                self.labelled(body);
429            }
430            Stmt::Case { lo, hi, body } => {
431                self.token("case");
432                self.space();
433                self.expr_at(lo, COND);
434                if let Some(hi) = hi {
435                    self.space();
436                    self.token("...");
437                    self.space();
438                    self.expr_at(hi, COND);
439                }
440                self.token(":");
441                self.labelled(body);
442            }
443            Stmt::Default { body } => {
444                self.token("default");
445                self.token(":");
446                self.labelled(body);
447            }
448            Stmt::LocalLabels(names) => {
449                self.token("__label__");
450                self.name_list(names);
451                self.token(";");
452            }
453            Stmt::Asm(asm) => {
454                self.asm(asm);
455                self.token(";");
456            }
457        }
458    }
459
460    /// One expression, with no parentheses around it that the grammar does not need.
461    pub fn expr(&mut self, id: ExprId) {
462        self.expr_at(id, COMMA);
463    }
464
465    /// One type name, as it would be written in a cast.
466    pub fn type_name(&mut self, id: TypeNameId) {
467        let ast = self.ast;
468        let name = ast[id];
469        self.decl_specs(name.specs);
470        let text = self.declarator_text(name.declarator);
471        if !text.is_empty() {
472            self.space();
473            self.token(&text);
474        }
475    }
476
477    /// The statement a control structure controls, on the same line when it is a block and
478    /// indented on the next line when it is not.
479    fn body(&mut self, id: StmtId) {
480        if matches!(self.ast[id], Stmt::Compound(_)) {
481            self.space();
482            self.stmt(id);
483        } else {
484            self.depth += 1;
485            self.newline();
486            self.stmt(id);
487            self.depth -= 1;
488        }
489    }
490
491    /// A statement in braces it did not have, which is what stops an `else` binding to an `if`
492    /// nested inside the branch before it.
493    fn braced(&mut self, id: StmtId) {
494        self.space();
495        self.token("{");
496        self.depth += 1;
497        self.newline();
498        self.stmt(id);
499        self.depth -= 1;
500        self.newline();
501        self.token("}");
502    }
503
504    /// The statement a label labels, which C23 allows to be missing at the end of a block.
505    fn labelled(&mut self, body: Option<StmtId>) {
506        if let Some(body) = body {
507            self.newline();
508            self.stmt(body);
509        }
510    }
511
512    /// Whether a statement ends in an `if` with no `else`, and so would take one written after
513    /// it.
514    fn dangling(&self, id: StmtId) -> bool {
515        match self.ast[id] {
516            Stmt::If { otherwise: Some(otherwise), .. } => self.dangling(otherwise),
517            Stmt::If { otherwise: None, .. } => true,
518            Stmt::While { body, .. } | Stmt::Switch { body, .. } | Stmt::For { body, .. } => {
519                self.dangling(body)
520            }
521            Stmt::Label { body: Some(body), .. }
522            | Stmt::Case { body: Some(body), .. }
523            | Stmt::Default { body: Some(body) } => self.dangling(body),
524            _ => false,
525        }
526    }
527
528    /// `_Static_assert(cond)` or `_Static_assert(cond, "message")`, semicolon included.
529    fn static_assert(&mut self, cond: ExprId, message: Option<StrId>) {
530        self.token("_Static_assert");
531        self.token("(");
532        self.expr_at(cond, ASSIGN);
533        if let Some(message) = message {
534            self.token(",");
535            self.space();
536            self.string(message);
537        }
538        self.token(")");
539        self.token(";");
540    }
541
542    /// An `asm` statement or a file-scope `asm`, without its semicolon.
543    fn asm(&mut self, id: AsmId) {
544        let ast = self.ast;
545        let asm = ast[id];
546        self.token("__asm__");
547        if asm.quals.has(AsmQuals::VOLATILE) {
548            self.token("volatile");
549        }
550        if asm.quals.has(AsmQuals::INLINE) {
551            self.token("inline");
552        }
553        if asm.quals.has(AsmQuals::GOTO) {
554            self.token("goto");
555        }
556        self.token("(");
557        self.string(asm.template);
558        // A section is only written when something after it has to be, since the colons are
559        // what count the sections and an empty one before a full one cannot be left out.
560        let sections = if !asm.labels.is_empty() {
561            4
562        } else if !asm.clobbers.is_empty() {
563            3
564        } else if !asm.inputs.is_empty() {
565            2
566        } else {
567            usize::from(!asm.outputs.is_empty())
568        };
569        for section in 0..sections {
570            self.space();
571            self.token(":");
572            match section {
573                0 => self.asm_operands(asm.outputs),
574                1 => self.asm_operands(asm.inputs),
575                2 => self.string_list(asm.clobbers),
576                _ => self.name_list(asm.labels),
577            }
578        }
579        self.token(")");
580    }
581
582    /// One section of an `asm` statement's operands.
583    fn asm_operands(&mut self, list: AsmOperandList) {
584        let ast = self.ast;
585        for (index, operand) in ast[list].iter().enumerate() {
586            if index > 0 {
587                self.token(",");
588            }
589            self.space();
590            if let Some(name) = operand.name {
591                self.token("[");
592                self.name(name);
593                self.token("]");
594                self.space();
595            }
596            self.string(operand.constraint);
597            self.space();
598            self.token("(");
599            self.expr_at(operand.value, COMMA);
600            self.token(")");
601        }
602    }
603
604    /// A comma-separated run of string literals.
605    fn string_list(&mut self, list: StrList) {
606        let ast = self.ast;
607        for (index, &item) in ast[list].iter().enumerate() {
608            if index > 0 {
609                self.token(",");
610            }
611            self.space();
612            self.string(item);
613        }
614    }
615
616    /// A comma-separated run of identifiers.
617    fn name_list(&mut self, list: SymbolList) {
618        let ast = self.ast;
619        for (index, &item) in ast[list].iter().enumerate() {
620            if index > 0 {
621                self.token(",");
622            }
623            self.space();
624            self.name(item);
625        }
626    }
627
628    /// Everything a declaration says before its first declarator.
629    fn decl_specs(&mut self, id: DeclSpecsId) {
630        let specs = self.ast[id];
631        self.attributes(specs.attrs);
632        if let Some(storage) = specs.storage {
633            self.token(storage.spelling());
634        }
635        if specs.thread_local {
636            self.token("_Thread_local");
637        }
638        if specs.func.has(FuncSpecs::INLINE) {
639            self.token("inline");
640        }
641        if specs.func.has(FuncSpecs::NORETURN) {
642            self.token("_Noreturn");
643        }
644        if let Some(align) = specs.align {
645            self.token("_Alignas");
646            self.token("(");
647            match align {
648                AlignSpec::Type(ty) => self.type_name(ty),
649                AlignSpec::Expr(expr) => self.expr_at(expr, ASSIGN),
650            }
651            self.token(")");
652        }
653        self.quals(specs.quals);
654        self.type_spec(specs.ty);
655    }
656
657    /// The type qualifiers that were written, in a fixed order.
658    fn quals(&mut self, quals: Quals) {
659        if quals.has(Quals::CONST) {
660            self.token("const");
661        }
662        if quals.has(Quals::VOLATILE) {
663            self.token("volatile");
664        }
665        if quals.has(Quals::RESTRICT) {
666            self.token("restrict");
667        }
668        if quals.has(Quals::ATOMIC) {
669            self.token("_Atomic");
670        }
671    }
672
673    /// What type a declaration named.
674    fn type_spec(&mut self, ty: TypeSpec) {
675        match ty {
676            TypeSpec::None => {}
677            TypeSpec::Builtin(builtin) => self.builtin(builtin),
678            TypeSpec::Record { kind, tag, fields, attrs } => {
679                self.token(kind.spelling());
680                self.attributes(attrs);
681                if let Some(tag) = tag {
682                    self.space();
683                    self.name(tag);
684                }
685                if let Some(fields) = fields {
686                    self.members(fields);
687                }
688            }
689            TypeSpec::Enum { tag, enumerators, underlying, attrs } => {
690                self.token("enum");
691                self.attributes(attrs);
692                if let Some(tag) = tag {
693                    self.space();
694                    self.name(tag);
695                }
696                if let Some(underlying) = underlying {
697                    self.space();
698                    self.token(":");
699                    self.space();
700                    self.type_name(underlying);
701                }
702                if let Some(enumerators) = enumerators {
703                    self.enumerators(enumerators);
704                }
705            }
706            TypeSpec::Typedef(name) => self.name(name),
707            TypeSpec::Typeof { unqual, operand } => {
708                self.token(if unqual { "__typeof_unqual__" } else { "__typeof__" });
709                self.token("(");
710                match operand {
711                    TypeofArg::Expr(expr) => self.expr_at(expr, COMMA),
712                    TypeofArg::Type(ty) => self.type_name(ty),
713                }
714                self.token(")");
715            }
716            TypeSpec::Atomic(ty) => {
717                self.token("_Atomic");
718                self.token("(");
719                self.type_name(ty);
720                self.token(")");
721            }
722            TypeSpec::Auto(which) => self.token(which.spelling()),
723            TypeSpec::VaList => self.token("__builtin_va_list"),
724        }
725    }
726
727    /// The type keywords, in the printer's order rather than the one they were written in.
728    fn builtin(&mut self, builtin: Builtin) {
729        for &(which, spelling) in BUILTIN_SPELLINGS {
730            if builtin.set.has(which) {
731                self.token(spelling);
732            }
733            // `long` goes where it reads, which is after `short` could have been and before
734            // everything it can qualify.
735            if which == BuiltinSet::SHORT {
736                for _ in 0..builtin.longs {
737                    self.token("long");
738                }
739            }
740        }
741        // `_BitInt` is last because its width follows it, so writing it anywhere else would
742        // put a sign between the keyword and the parenthesis it belongs to.
743        if let Some(width) = builtin.width {
744            self.token("_BitInt");
745            self.token("(");
746            self.expr_at(width, COMMA);
747            self.token(")");
748        }
749    }
750
751    /// The `{ ... }` of a struct or a union.
752    fn members(&mut self, list: MemberList) {
753        let ast = self.ast;
754        let members = &ast[list];
755        self.space();
756        self.token("{");
757        self.depth += 1;
758        let mut index = 0;
759        while index < members.len() {
760            self.newline();
761            match members[index] {
762                Member::StaticAssert { cond, message, .. } => {
763                    self.static_assert(cond, message);
764                    index += 1;
765                }
766                Member::Field(first) => {
767                    self.decl_specs(first.specs);
768                    if first.declarator.is_none() && first.bits.is_none() {
769                        // An anonymous struct or union member, or a tag declared among the
770                        // members. Either way it is a declaration on its own.
771                        index += 1;
772                    } else {
773                        // The members declared together share their specifiers, and they are
774                        // written back together so that an anonymous type in them stays one
775                        // type rather than becoming one per member.
776                        let mut written = 0;
777                        while let Some(&Member::Field(field)) = members.get(index) {
778                            if field.specs != first.specs
779                                || (field.declarator.is_none() && field.bits.is_none())
780                            {
781                                break;
782                            }
783                            if written > 0 {
784                                self.token(",");
785                            }
786                            self.space();
787                            self.field(field);
788                            written += 1;
789                            index += 1;
790                        }
791                    }
792                    self.token(";");
793                }
794            }
795        }
796        self.depth -= 1;
797        self.newline();
798        self.token("}");
799    }
800
801    /// One member, without the specifiers it shares with the members beside it.
802    fn field(&mut self, field: Field) {
803        if let Some(declarator) = field.declarator {
804            let text = self.declarator_text(declarator);
805            self.token(&text);
806        }
807        if let Some(bits) = field.bits {
808            self.space();
809            self.token(":");
810            self.space();
811            self.expr_at(bits, COND);
812        }
813        self.attributes(field.attrs);
814    }
815
816    /// The `{ ... }` of an enumeration, one enumerator to a line.
817    fn enumerators(&mut self, list: EnumeratorList) {
818        let ast = self.ast;
819        self.space();
820        self.token("{");
821        self.depth += 1;
822        for (index, enumerator) in ast[list].iter().enumerate() {
823            if index > 0 {
824                self.token(",");
825            }
826            self.newline();
827            self.name(enumerator.name);
828            self.attributes(enumerator.attrs);
829            if let Some(value) = enumerator.value {
830                self.space();
831                self.token("=");
832                self.space();
833                self.expr_at(value, COND);
834            }
835        }
836        self.depth -= 1;
837        self.newline();
838        self.token("}");
839    }
840
841    /// A declarator, built from the name outward and given back as its own text.
842    ///
843    /// Outward is the direction the type reads in and the wrong direction to write in, so the
844    /// pieces are assembled here rather than streamed: a pointer step wraps what came before it
845    /// on the left, and an array or function step that follows one needs the parentheses that
846    /// tell `int (*p)[4]` from `int *p[4]`.
847    fn declarator_text(&mut self, id: DeclaratorId) -> String {
848        let ast = self.ast;
849        let declarator = ast[id];
850        let mut text = match declarator.name {
851            Some(name) => self.names.resolve(name).to_string(),
852            None => String::new(),
853        };
854        let mut pointered = false;
855        for step in &ast[declarator.derived] {
856            match *step {
857                Derived::Pointer { quals, attrs } => {
858                    let prefix = self.capture(|p| {
859                        p.token("*");
860                        p.quals(quals);
861                        p.attributes(attrs);
862                    });
863                    text = join(prefix, &text);
864                    pointered = true;
865                }
866                Derived::Array { size, quals, has_static } => {
867                    if pointered {
868                        text = format!("({text})");
869                    }
870                    let suffix = self.capture(|p| {
871                        p.token("[");
872                        if has_static {
873                            p.token("static");
874                        }
875                        p.quals(quals);
876                        match size {
877                            ArraySize::Unspecified => {}
878                            ArraySize::Star => p.token("*"),
879                            ArraySize::Expr(expr) => p.expr_at(expr, ASSIGN),
880                        }
881                        p.token("]");
882                    });
883                    text = join(text, &suffix);
884                    pointered = false;
885                }
886                Derived::Function { params, variadic, kind } => {
887                    if pointered {
888                        text = format!("({text})");
889                    }
890                    let suffix = self.capture(|p| p.parameters(params, variadic, kind));
891                    text = join(text, &suffix);
892                    pointered = false;
893                }
894            }
895        }
896        text
897    }
898
899    /// A function declarator's parameter list, parentheses included.
900    fn parameters(&mut self, params: ParamList, variadic: bool, kind: ParamKind) {
901        let ast = self.ast;
902        self.token("(");
903        match kind {
904            ParamKind::Void => self.token("void"),
905            ParamKind::Empty => {}
906            ParamKind::Identifiers => {
907                for (index, param) in ast[params].iter().enumerate() {
908                    if index > 0 {
909                        self.token(",");
910                        self.space();
911                    }
912                    if let Some(name) = ast[param.declarator].name {
913                        self.name(name);
914                    }
915                }
916            }
917            ParamKind::Prototype => {
918                for (index, param) in ast[params].iter().enumerate() {
919                    if index > 0 {
920                        self.token(",");
921                        self.space();
922                    }
923                    self.parameter(*param);
924                }
925                if variadic {
926                    if !params.is_empty() {
927                        self.token(",");
928                        self.space();
929                    }
930                    self.token("...");
931                }
932            }
933        }
934        self.token(")");
935    }
936
937    /// One parameter of a prototype.
938    fn parameter(&mut self, param: Param) {
939        if let Some(specs) = param.specs {
940            self.decl_specs(specs);
941        }
942        let text = self.declarator_text(param.declarator);
943        if !text.is_empty() {
944            self.space();
945            self.token(&text);
946        }
947        self.attributes(param.attrs);
948    }
949
950    /// Every attribute of a list, each in the syntax it was written in.
951    fn attributes(&mut self, list: AttrList) {
952        let ast = self.ast;
953        for attr in &ast[list] {
954            self.space();
955            match attr.syntax {
956                AttrSyntax::Standard => self.token("[["),
957                AttrSyntax::Gnu => self.token("__attribute__(("),
958                AttrSyntax::Declspec => self.token("__declspec("),
959            }
960            if let Some(namespace) = attr.namespace {
961                self.name(namespace);
962                self.token("::");
963            }
964            self.name(attr.name);
965            if !attr.args.is_empty() {
966                self.token("(");
967                for (index, arg) in ast[attr.args].iter().enumerate() {
968                    if index > 0 {
969                        self.token(",");
970                        self.space();
971                    }
972                    match *arg {
973                        AttrArg::Ident(name) => self.name(name),
974                        AttrArg::Expr(expr) => self.expr_at(expr, ASSIGN),
975                    }
976                }
977                self.token(")");
978            }
979            match attr.syntax {
980                AttrSyntax::Standard => self.token("]]"),
981                AttrSyntax::Gnu => self.token("))"),
982                AttrSyntax::Declspec => self.token(")"),
983            }
984            // Whatever comes next reads as part of the attribute without this. Nothing needs it
985            // to lex, and `token` takes it back where what follows is punctuation.
986            self.space();
987        }
988    }
989
990    /// An initializer, which is an expression or a braced list.
991    fn init(&mut self, id: InitId) {
992        let ast = self.ast;
993        match ast[id] {
994            Init::Expr(expr) => self.expr_at(expr, ASSIGN),
995            Init::List(items) => {
996                self.token("{");
997                for (index, item) in ast[items].iter().enumerate() {
998                    if index > 0 {
999                        self.token(",");
1000                    }
1001                    self.space();
1002                    let designators = &ast[item.designators];
1003                    for designator in designators {
1004                        self.designator(*designator);
1005                    }
1006                    // The obsolete `name:` form carries its own colon and takes no `=`.
1007                    let obsolete = matches!(designators.last(), Some(Designator::ObsoleteField(_)));
1008                    if !designators.is_empty() && !obsolete {
1009                        self.space();
1010                        self.token("=");
1011                        self.space();
1012                    }
1013                    self.init(item.init);
1014                }
1015                self.space();
1016                self.token("}");
1017            }
1018        }
1019    }
1020
1021    /// One step of a designation, or of a `__builtin_offsetof` path.
1022    fn designator(&mut self, designator: Designator) {
1023        match designator {
1024            Designator::Field(name) => {
1025                self.token(".");
1026                self.name(name);
1027            }
1028            Designator::Index(index) => {
1029                self.token("[");
1030                self.expr_at(index, COMMA);
1031                self.token("]");
1032            }
1033            Designator::Range { lo, hi } => {
1034                self.token("[");
1035                self.expr_at(lo, COND);
1036                self.space();
1037                self.token("...");
1038                self.space();
1039                self.expr_at(hi, COND);
1040                self.token("]");
1041            }
1042            Designator::ObsoleteField(name) => {
1043                self.name(name);
1044                self.token(":");
1045                self.space();
1046            }
1047        }
1048    }
1049
1050    /// An expression, in parentheses when what encloses it binds more tightly than it does.
1051    fn expr_at(&mut self, id: ExprId, min: u8) {
1052        if self.precedence(id) < min {
1053            self.token("(");
1054            self.expression(id);
1055            self.token(")");
1056        } else {
1057            self.expression(id);
1058        }
1059    }
1060
1061    /// How tightly an expression holds together, which decides whether it needs parentheses.
1062    fn precedence(&self, id: ExprId) -> u8 {
1063        match self.ast[id] {
1064            Expr::Comma { .. } => COMMA,
1065            Expr::Assign { .. } => ASSIGN,
1066            Expr::Cond { .. } => COND,
1067            Expr::Binary { op, .. } => binding(op),
1068            Expr::Cast { .. } => CAST,
1069            Expr::Unary { op, .. } => {
1070                if op.is_postfix() {
1071                    POSTFIX
1072                } else {
1073                    UNARY
1074                }
1075            }
1076            Expr::SizeofExpr(_) | Expr::AlignofExpr(_) | Expr::Extension(_) => UNARY,
1077            Expr::Index { .. }
1078            | Expr::Call { .. }
1079            | Expr::Member { .. }
1080            | Expr::CompoundLiteral { .. } => POSTFIX,
1081            _ => PRIMARY,
1082        }
1083    }
1084
1085    /// One expression, with no regard for what encloses it.
1086    fn expression(&mut self, id: ExprId) {
1087        let ast = self.ast;
1088        match ast[id] {
1089            // Poisoned, and written as a constant so that a broken tree still prints to
1090            // something that parses.
1091            Expr::Error => self.token("0"),
1092            Expr::Name(name) => self.name(name),
1093            Expr::Int(constant) => {
1094                let constant = ast[constant];
1095                let text = format!("{}{}", constant.value, constant.ty.suffix());
1096                self.token(&text);
1097            }
1098            Expr::Float(constant) => {
1099                let constant = ast[constant];
1100                let mut text = constant.value.to_hex();
1101                text.push_str(constant.ty.suffix());
1102                if constant.imaginary {
1103                    text.push('i');
1104                }
1105                self.token(&text);
1106            }
1107            Expr::Char(constant) => {
1108                let text = ast[constant].spell();
1109                self.token(&text);
1110            }
1111            Expr::Str(literal) => self.string(literal),
1112            Expr::Bool(value) => self.token(if value { "true" } else { "false" }),
1113            Expr::Nullptr => self.token("nullptr"),
1114            Expr::Index { base, index } => {
1115                self.expr_at(base, POSTFIX);
1116                self.token("[");
1117                self.expr_at(index, COMMA);
1118                self.token("]");
1119            }
1120            Expr::Call { callee, args } => {
1121                self.expr_at(callee, POSTFIX);
1122                self.token("(");
1123                self.arguments(args);
1124                self.token(")");
1125            }
1126            Expr::Member { base, name, arrow } => {
1127                self.expr_at(base, POSTFIX);
1128                self.token(if arrow { "->" } else { "." });
1129                self.name(name);
1130            }
1131            Expr::Unary { op, operand } => {
1132                if op.is_postfix() {
1133                    self.expr_at(operand, POSTFIX);
1134                    self.token(op.spelling());
1135                } else {
1136                    self.token(op.spelling());
1137                    let inner = match op {
1138                        UnaryOp::PreInc | UnaryOp::PreDec => UNARY,
1139                        _ => CAST,
1140                    };
1141                    self.expr_at(operand, inner);
1142                }
1143            }
1144            Expr::Binary { op, lhs, rhs } => {
1145                let at = binding(op);
1146                self.expr_at(lhs, at);
1147                self.space();
1148                self.token(op.spelling());
1149                self.space();
1150                // The right operand needs one more, since every binary operator in C groups to
1151                // the left and `a - (b - c)` is not `a - b - c`.
1152                self.expr_at(rhs, at + 1);
1153            }
1154            Expr::Assign { op, lhs, rhs } => {
1155                self.expr_at(lhs, UNARY);
1156                self.space();
1157                match op {
1158                    Some(op) => {
1159                        let text = format!("{}=", op.spelling());
1160                        self.token(&text);
1161                    }
1162                    None => self.token("="),
1163                }
1164                self.space();
1165                self.expr_at(rhs, ASSIGN);
1166            }
1167            Expr::Cond { cond, then, otherwise } => {
1168                self.expr_at(cond, COND + 1);
1169                self.space();
1170                self.token("?");
1171                if let Some(then) = then {
1172                    self.space();
1173                    self.expr_at(then, COMMA);
1174                }
1175                self.space();
1176                self.token(":");
1177                self.space();
1178                self.expr_at(otherwise, COND);
1179            }
1180            Expr::Comma { lhs, rhs } => {
1181                self.expr_at(lhs, COMMA);
1182                self.token(",");
1183                self.space();
1184                self.expr_at(rhs, ASSIGN);
1185            }
1186            Expr::Cast { ty, operand } => {
1187                self.token("(");
1188                self.type_name(ty);
1189                self.token(")");
1190                self.expr_at(operand, CAST);
1191            }
1192            Expr::CompoundLiteral { ty, init } => {
1193                self.token("(");
1194                self.type_name(ty);
1195                self.token(")");
1196                self.init(init);
1197            }
1198            // The operand is bracketed unless it is already a name or a constant, because
1199            // `sizeof (T){ 0 }` reads as a type in parentheses and is not one.
1200            Expr::SizeofExpr(operand) => {
1201                self.token("sizeof");
1202                self.space();
1203                self.expr_at(operand, PRIMARY);
1204            }
1205            Expr::SizeofType(ty) => {
1206                self.token("sizeof");
1207                self.token("(");
1208                self.type_name(ty);
1209                self.token(")");
1210            }
1211            Expr::AlignofExpr(operand) => {
1212                self.token("__alignof__");
1213                self.space();
1214                self.expr_at(operand, PRIMARY);
1215            }
1216            Expr::AlignofType(ty) => {
1217                self.token("_Alignof");
1218                self.token("(");
1219                self.type_name(ty);
1220                self.token(")");
1221            }
1222            Expr::Generic { control, assocs } => {
1223                self.token("_Generic");
1224                self.token("(");
1225                self.expr_at(control, ASSIGN);
1226                self.associations(assocs);
1227                self.token(")");
1228            }
1229            Expr::StmtExpr(body) => {
1230                self.token("(");
1231                self.stmt(body);
1232                self.token(")");
1233            }
1234            Expr::LabelAddr(name) => {
1235                self.token("&&");
1236                self.name(name);
1237            }
1238            Expr::Offsetof { ty, path } => {
1239                self.token("__builtin_offsetof");
1240                self.token("(");
1241                self.type_name(ty);
1242                self.token(",");
1243                self.space();
1244                self.member_path(path);
1245                self.token(")");
1246            }
1247            Expr::ChooseExpr { cond, then, otherwise } => {
1248                self.token("__builtin_choose_expr");
1249                self.token("(");
1250                self.expr_at(cond, ASSIGN);
1251                self.token(",");
1252                self.space();
1253                self.expr_at(then, ASSIGN);
1254                self.token(",");
1255                self.space();
1256                self.expr_at(otherwise, ASSIGN);
1257                self.token(")");
1258            }
1259            Expr::TypesCompatible { a, b } => {
1260                self.token("__builtin_types_compatible_p");
1261                self.token("(");
1262                self.type_name(a);
1263                self.token(",");
1264                self.space();
1265                self.type_name(b);
1266                self.token(")");
1267            }
1268            Expr::VaArg { list, ty } => {
1269                self.token("__builtin_va_arg");
1270                self.token("(");
1271                self.expr_at(list, ASSIGN);
1272                self.token(",");
1273                self.space();
1274                self.type_name(ty);
1275                self.token(")");
1276            }
1277            Expr::VaStart { list, last } => {
1278                self.token("__builtin_va_start");
1279                self.token("(");
1280                self.expr_at(list, ASSIGN);
1281                if let Some(last) = last {
1282                    self.token(",");
1283                    self.space();
1284                    self.expr_at(last, ASSIGN);
1285                }
1286                self.token(")");
1287            }
1288            Expr::VaEnd { list } => {
1289                self.token("__builtin_va_end");
1290                self.token("(");
1291                self.expr_at(list, ASSIGN);
1292                self.token(")");
1293            }
1294            Expr::VaCopy { dst, src } => {
1295                self.token("__builtin_va_copy");
1296                self.token("(");
1297                self.expr_at(dst, ASSIGN);
1298                self.token(",");
1299                self.space();
1300                self.expr_at(src, ASSIGN);
1301                self.token(")");
1302            }
1303            Expr::Extension(operand) => {
1304                self.token("__extension__");
1305                self.space();
1306                self.expr_at(operand, CAST);
1307            }
1308        }
1309    }
1310
1311    /// The arguments of a call, which are assignment-expressions so that the commas between
1312    /// them stay separators.
1313    fn arguments(&mut self, args: ExprList) {
1314        let ast = self.ast;
1315        for (index, &arg) in ast[args].iter().enumerate() {
1316            if index > 0 {
1317                self.token(",");
1318                self.space();
1319            }
1320            self.expr_at(arg, ASSIGN);
1321        }
1322    }
1323
1324    /// The arms of a `_Generic`, the leading comma of each included.
1325    fn associations(&mut self, assocs: GenericList) {
1326        let ast = self.ast;
1327        for assoc in &ast[assocs] {
1328            self.token(",");
1329            self.space();
1330            match assoc.ty {
1331                Some(ty) => self.type_name(ty),
1332                None => self.token("default"),
1333            }
1334            self.token(":");
1335            self.space();
1336            self.expr_at(assoc.value, ASSIGN);
1337        }
1338    }
1339
1340    /// The member path of a `__builtin_offsetof`, whose first step is written with no dot.
1341    fn member_path(&mut self, path: DesignatorList) {
1342        let ast = self.ast;
1343        for (index, step) in ast[path].iter().enumerate() {
1344            match (index, *step) {
1345                (0, Designator::Field(name)) => self.name(name),
1346                (_, step) => self.designator(step),
1347            }
1348        }
1349    }
1350
1351    /// A string literal, prefix and quotes included.
1352    fn string(&mut self, id: StrId) {
1353        let ast = self.ast;
1354        let text = ast[id].spell();
1355        self.token(&text);
1356    }
1357
1358    /// An identifier.
1359    fn name(&mut self, symbol: Symbol) {
1360        let names = self.names;
1361        self.token(names.resolve(symbol));
1362    }
1363
1364    /// Writes with the output redirected into a buffer of its own, and gives the buffer back.
1365    fn capture(&mut self, write: impl FnOnce(&mut Printer<'a>)) -> String {
1366        let held = std::mem::take(&mut self.out);
1367        write(self);
1368        std::mem::replace(&mut self.out, held)
1369    }
1370
1371    /// Appends one token, with a space in front of it if it would otherwise join the one before.
1372    fn token(&mut self, text: &str) {
1373        if text.is_empty() {
1374            return;
1375        }
1376        if text.starts_with([';', ',', ')', ']']) {
1377            self.unspace();
1378        }
1379        if let (Some(last), Some(next)) = (self.out.chars().next_back(), text.chars().next()) {
1380            if pastes(last, next) {
1381                self.out.push(' ');
1382            }
1383        }
1384        self.out.push_str(text);
1385    }
1386
1387    /// Takes back a space that was written for reading, where what follows turns out not to want
1388    /// one in front of it. An indent is not one of those spaces and stays.
1389    fn unspace(&mut self) {
1390        let kept = self.out.trim_end_matches(' ');
1391        if !kept.ends_with('\n') {
1392            self.out.truncate(kept.len());
1393        }
1394    }
1395
1396    /// Appends a space, where one is wanted for reading rather than needed for lexing.
1397    fn space(&mut self) {
1398        if !self.out.is_empty() && !self.out.ends_with([' ', '\n']) {
1399            self.out.push(' ');
1400        }
1401    }
1402
1403    /// Ends the line and indents the next one.
1404    fn newline(&mut self) {
1405        while self.out.ends_with(' ') {
1406            self.out.pop();
1407        }
1408        self.out.push('\n');
1409        for _ in 0..self.depth {
1410            self.out.push_str("    ");
1411        }
1412    }
1413}
1414
1415#[cfg(test)]
1416mod tests {
1417    use rucc_diag::Span;
1418    use rucc_lex::{CharConstant, Encoding, StringLiteral};
1419
1420    use super::*;
1421    use crate::decl::Declarator;
1422    use crate::spec::{DeclSpecs, StorageClass};
1423
1424    struct Fixture {
1425        ast: Ast,
1426        names: Interner,
1427    }
1428
1429    impl Fixture {
1430        fn new() -> Fixture {
1431            Fixture { ast: Ast::new(), names: Interner::new() }
1432        }
1433
1434        fn text(&self, write: impl FnOnce(&mut Printer<'_>)) -> String {
1435            let mut printer = Printer::new(&self.ast, &self.names);
1436            write(&mut printer);
1437            printer.finish()
1438        }
1439    }
1440
1441    #[test]
1442    fn two_tokens_that_would_join_get_a_space() {
1443        let mut fixture = Fixture::new();
1444        let one = fixture.ast.expr(Expr::Bool(true), Span::DUMMY);
1445        let minus = fixture.ast.expr(Expr::Unary { op: UnaryOp::Minus, operand: one }, Span::DUMMY);
1446        let twice =
1447            fixture.ast.expr(Expr::Unary { op: UnaryOp::Minus, operand: minus }, Span::DUMMY);
1448        assert_eq!(fixture.text(|p| p.expr(twice)), "- -true");
1449    }
1450
1451    #[test]
1452    fn the_variable_argument_family_prints_as_it_was_written() {
1453        let mut fixture = Fixture::new();
1454        let ap = fixture.names.intern("ap");
1455        let copy = fixture.names.intern("copy");
1456        let n = fixture.names.intern("n");
1457        let ap = fixture.ast.expr(Expr::Name(ap), Span::DUMMY);
1458        let copy = fixture.ast.expr(Expr::Name(copy), Span::DUMMY);
1459        let n = fixture.ast.expr(Expr::Name(n), Span::DUMMY);
1460
1461        let start = fixture.ast.expr(Expr::VaStart { list: ap, last: Some(n) }, Span::DUMMY);
1462        assert_eq!(fixture.text(|p| p.expr(start)), "__builtin_va_start(ap, n)");
1463
1464        // The second argument is missing rather than written as nothing, which is what a
1465        // program that leaves it out gets and which is reported later rather than here.
1466        let alone = fixture.ast.expr(Expr::VaStart { list: ap, last: None }, Span::DUMMY);
1467        assert_eq!(fixture.text(|p| p.expr(alone)), "__builtin_va_start(ap)");
1468
1469        let copied = fixture.ast.expr(Expr::VaCopy { dst: copy, src: ap }, Span::DUMMY);
1470        assert_eq!(fixture.text(|p| p.expr(copied)), "__builtin_va_copy(copy, ap)");
1471
1472        let end = fixture.ast.expr(Expr::VaEnd { list: ap }, Span::DUMMY);
1473        assert_eq!(fixture.text(|p| p.expr(end)), "__builtin_va_end(ap)");
1474    }
1475
1476    #[test]
1477    fn parentheses_go_where_the_grammar_needs_them_and_nowhere_else() {
1478        let mut fixture = Fixture::new();
1479        let a = fixture.names.intern("a");
1480        let b = fixture.names.intern("b");
1481        let c = fixture.names.intern("c");
1482        let a = fixture.ast.expr(Expr::Name(a), Span::DUMMY);
1483        let b = fixture.ast.expr(Expr::Name(b), Span::DUMMY);
1484        let c = fixture.ast.expr(Expr::Name(c), Span::DUMMY);
1485
1486        let sum = fixture.ast.expr(Expr::Binary { op: BinaryOp::Add, lhs: a, rhs: b }, Span::DUMMY);
1487        let scaled =
1488            fixture.ast.expr(Expr::Binary { op: BinaryOp::Mul, lhs: sum, rhs: c }, Span::DUMMY);
1489        assert_eq!(fixture.text(|p| p.expr(scaled)), "(a + b) * c");
1490
1491        let product =
1492            fixture.ast.expr(Expr::Binary { op: BinaryOp::Mul, lhs: b, rhs: c }, Span::DUMMY);
1493        let total =
1494            fixture.ast.expr(Expr::Binary { op: BinaryOp::Add, lhs: a, rhs: product }, Span::DUMMY);
1495        assert_eq!(fixture.text(|p| p.expr(total)), "a + b * c");
1496
1497        // Left grouping, so the right operand of a subtraction keeps its parentheses.
1498        let inner =
1499            fixture.ast.expr(Expr::Binary { op: BinaryOp::Sub, lhs: b, rhs: c }, Span::DUMMY);
1500        let outer =
1501            fixture.ast.expr(Expr::Binary { op: BinaryOp::Sub, lhs: a, rhs: inner }, Span::DUMMY);
1502        assert_eq!(fixture.text(|p| p.expr(outer)), "a - (b - c)");
1503    }
1504
1505    #[test]
1506    fn a_declarator_reads_outward_from_its_name() {
1507        let mut fixture = Fixture::new();
1508        let f = fixture.names.intern("f");
1509        let three = fixture.ast.expr(Expr::Bool(true), Span::DUMMY);
1510        let derived = fixture.ast.add_derived_list(&[
1511            Derived::Array { size: ArraySize::Expr(three), quals: Quals::NONE, has_static: false },
1512            Derived::Pointer { quals: Quals::NONE, attrs: AttrList::EMPTY },
1513            Derived::Function { params: ParamList::EMPTY, variadic: false, kind: ParamKind::Void },
1514        ]);
1515        let declarator = fixture.ast.add_declarator(Declarator {
1516            name: Some(f),
1517            name_span: Span::DUMMY,
1518            derived,
1519            span: Span::DUMMY,
1520        });
1521        let specs = fixture.ast.add_specs(DeclSpecs::empty(Span::DUMMY));
1522        let ty = fixture.ast.add_type_name(crate::decl::TypeName {
1523            specs,
1524            declarator,
1525            span: Span::DUMMY,
1526        });
1527        assert_eq!(fixture.text(|p| p.type_name(ty)), "(*f[true])(void)");
1528    }
1529
1530    #[test]
1531    fn a_declaration_keeps_its_declarators_together() {
1532        let mut fixture = Fixture::new();
1533        let a = fixture.names.intern("a");
1534        let b = fixture.names.intern("b");
1535        let mut specs = DeclSpecs::empty(Span::DUMMY);
1536        specs.storage = Some(StorageClass::Static);
1537        specs.ty = TypeSpec::Builtin(Builtin { set: BuiltinSet::INT, longs: 0, width: None });
1538        let specs = fixture.ast.add_specs(specs);
1539        let mut declarators = Vec::new();
1540        for (name, stars) in [(a, 0), (b, 1)] {
1541            let derived = if stars == 0 {
1542                crate::ast::DerivedList::EMPTY
1543            } else {
1544                fixture.ast.add_derived_list(&[Derived::Pointer {
1545                    quals: Quals::NONE,
1546                    attrs: AttrList::EMPTY,
1547                }])
1548            };
1549            let declarator = fixture.ast.add_declarator(Declarator {
1550                name: Some(name),
1551                name_span: Span::DUMMY,
1552                derived,
1553                span: Span::DUMMY,
1554            });
1555            declarators.push(crate::decl::InitDeclarator {
1556                declarator,
1557                init: None,
1558                asm_label: None,
1559                attrs: AttrList::EMPTY,
1560                span: Span::DUMMY,
1561            });
1562        }
1563        let declarators = fixture.ast.add_init_declarator_list(&declarators);
1564        let decl = fixture.ast.decl(Decl::Var { specs, declarators }, Span::DUMMY);
1565        assert_eq!(fixture.text(|p| p.decl(decl)), "static int a, *b;");
1566    }
1567
1568    #[test]
1569    fn a_byte_escape_in_a_string_takes_three_octal_digits() {
1570        let literal = StringLiteral {
1571            elements: vec![0xff, u32::from(b'0'), u32::from(b'a')],
1572            encoding: Encoding::Plain,
1573            remarks: rucc_lex::Remarks::NONE,
1574        };
1575        assert_eq!(literal.spell(), "\"\\3770a\"");
1576    }
1577
1578    #[test]
1579    fn a_wide_escape_closes_the_literal_rather_than_swallowing_what_follows() {
1580        let literal = StringLiteral {
1581            elements: vec![0x1234, u32::from(b'a'), u32::from(b'z')],
1582            encoding: Encoding::Utf32,
1583            remarks: rucc_lex::Remarks::NONE,
1584        };
1585        assert_eq!(literal.spell(), "U\"\\x1234\" U\"az\"");
1586    }
1587
1588    #[test]
1589    fn a_character_constant_is_written_as_a_character_where_it_can_be() {
1590        let plain = CharConstant {
1591            value: i64::from(b'a'),
1592            encoding: Encoding::Plain,
1593            remarks: rucc_lex::Remarks::NONE,
1594        };
1595        assert_eq!(plain.spell(), "'a'");
1596
1597        let quote = CharConstant { encoding: Encoding::Plain, value: i64::from(b'\''), ..plain };
1598        assert_eq!(quote.spell(), "'\\''");
1599
1600        let negative = CharConstant { value: -1, ..plain };
1601        assert_eq!(negative.spell(), "'\\xff'");
1602
1603        let many = CharConstant { value: 0x6162, ..plain };
1604        assert_eq!(many.spell(), "'\\x61\\x62'");
1605    }
1606}