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        }
724    }
725
726    /// The type keywords, in the printer's order rather than the one they were written in.
727    fn builtin(&mut self, builtin: Builtin) {
728        for &(which, spelling) in BUILTIN_SPELLINGS {
729            if builtin.set.has(which) {
730                self.token(spelling);
731            }
732            // `long` goes where it reads, which is after `short` could have been and before
733            // everything it can qualify.
734            if which == BuiltinSet::SHORT {
735                for _ in 0..builtin.longs {
736                    self.token("long");
737                }
738            }
739        }
740        // `_BitInt` is last because its width follows it, so writing it anywhere else would
741        // put a sign between the keyword and the parenthesis it belongs to.
742        if let Some(width) = builtin.width {
743            self.token("_BitInt");
744            self.token("(");
745            self.expr_at(width, COMMA);
746            self.token(")");
747        }
748    }
749
750    /// The `{ ... }` of a struct or a union.
751    fn members(&mut self, list: MemberList) {
752        let ast = self.ast;
753        let members = &ast[list];
754        self.space();
755        self.token("{");
756        self.depth += 1;
757        let mut index = 0;
758        while index < members.len() {
759            self.newline();
760            match members[index] {
761                Member::StaticAssert { cond, message, .. } => {
762                    self.static_assert(cond, message);
763                    index += 1;
764                }
765                Member::Field(first) => {
766                    self.decl_specs(first.specs);
767                    if first.declarator.is_none() && first.bits.is_none() {
768                        // An anonymous struct or union member, or a tag declared among the
769                        // members. Either way it is a declaration on its own.
770                        index += 1;
771                    } else {
772                        // The members declared together share their specifiers, and they are
773                        // written back together so that an anonymous type in them stays one
774                        // type rather than becoming one per member.
775                        let mut written = 0;
776                        while let Some(&Member::Field(field)) = members.get(index) {
777                            if field.specs != first.specs
778                                || (field.declarator.is_none() && field.bits.is_none())
779                            {
780                                break;
781                            }
782                            if written > 0 {
783                                self.token(",");
784                            }
785                            self.space();
786                            self.field(field);
787                            written += 1;
788                            index += 1;
789                        }
790                    }
791                    self.token(";");
792                }
793            }
794        }
795        self.depth -= 1;
796        self.newline();
797        self.token("}");
798    }
799
800    /// One member, without the specifiers it shares with the members beside it.
801    fn field(&mut self, field: Field) {
802        if let Some(declarator) = field.declarator {
803            let text = self.declarator_text(declarator);
804            self.token(&text);
805        }
806        if let Some(bits) = field.bits {
807            self.space();
808            self.token(":");
809            self.space();
810            self.expr_at(bits, COND);
811        }
812        self.attributes(field.attrs);
813    }
814
815    /// The `{ ... }` of an enumeration, one enumerator to a line.
816    fn enumerators(&mut self, list: EnumeratorList) {
817        let ast = self.ast;
818        self.space();
819        self.token("{");
820        self.depth += 1;
821        for (index, enumerator) in ast[list].iter().enumerate() {
822            if index > 0 {
823                self.token(",");
824            }
825            self.newline();
826            self.name(enumerator.name);
827            self.attributes(enumerator.attrs);
828            if let Some(value) = enumerator.value {
829                self.space();
830                self.token("=");
831                self.space();
832                self.expr_at(value, COND);
833            }
834        }
835        self.depth -= 1;
836        self.newline();
837        self.token("}");
838    }
839
840    /// A declarator, built from the name outward and given back as its own text.
841    ///
842    /// Outward is the direction the type reads in and the wrong direction to write in, so the
843    /// pieces are assembled here rather than streamed: a pointer step wraps what came before it
844    /// on the left, and an array or function step that follows one needs the parentheses that
845    /// tell `int (*p)[4]` from `int *p[4]`.
846    fn declarator_text(&mut self, id: DeclaratorId) -> String {
847        let ast = self.ast;
848        let declarator = ast[id];
849        let mut text = match declarator.name {
850            Some(name) => self.names.resolve(name).to_string(),
851            None => String::new(),
852        };
853        let mut pointered = false;
854        for step in &ast[declarator.derived] {
855            match *step {
856                Derived::Pointer { quals, attrs } => {
857                    let prefix = self.capture(|p| {
858                        p.token("*");
859                        p.quals(quals);
860                        p.attributes(attrs);
861                    });
862                    text = join(prefix, &text);
863                    pointered = true;
864                }
865                Derived::Array { size, quals, has_static } => {
866                    if pointered {
867                        text = format!("({text})");
868                    }
869                    let suffix = self.capture(|p| {
870                        p.token("[");
871                        if has_static {
872                            p.token("static");
873                        }
874                        p.quals(quals);
875                        match size {
876                            ArraySize::Unspecified => {}
877                            ArraySize::Star => p.token("*"),
878                            ArraySize::Expr(expr) => p.expr_at(expr, ASSIGN),
879                        }
880                        p.token("]");
881                    });
882                    text = join(text, &suffix);
883                    pointered = false;
884                }
885                Derived::Function { params, variadic, kind } => {
886                    if pointered {
887                        text = format!("({text})");
888                    }
889                    let suffix = self.capture(|p| p.parameters(params, variadic, kind));
890                    text = join(text, &suffix);
891                    pointered = false;
892                }
893            }
894        }
895        text
896    }
897
898    /// A function declarator's parameter list, parentheses included.
899    fn parameters(&mut self, params: ParamList, variadic: bool, kind: ParamKind) {
900        let ast = self.ast;
901        self.token("(");
902        match kind {
903            ParamKind::Void => self.token("void"),
904            ParamKind::Empty => {}
905            ParamKind::Identifiers => {
906                for (index, param) in ast[params].iter().enumerate() {
907                    if index > 0 {
908                        self.token(",");
909                        self.space();
910                    }
911                    if let Some(name) = ast[param.declarator].name {
912                        self.name(name);
913                    }
914                }
915            }
916            ParamKind::Prototype => {
917                for (index, param) in ast[params].iter().enumerate() {
918                    if index > 0 {
919                        self.token(",");
920                        self.space();
921                    }
922                    self.parameter(*param);
923                }
924                if variadic {
925                    if !params.is_empty() {
926                        self.token(",");
927                        self.space();
928                    }
929                    self.token("...");
930                }
931            }
932        }
933        self.token(")");
934    }
935
936    /// One parameter of a prototype.
937    fn parameter(&mut self, param: Param) {
938        if let Some(specs) = param.specs {
939            self.decl_specs(specs);
940        }
941        let text = self.declarator_text(param.declarator);
942        if !text.is_empty() {
943            self.space();
944            self.token(&text);
945        }
946        self.attributes(param.attrs);
947    }
948
949    /// Every attribute of a list, each in the syntax it was written in.
950    fn attributes(&mut self, list: AttrList) {
951        let ast = self.ast;
952        for attr in &ast[list] {
953            self.space();
954            match attr.syntax {
955                AttrSyntax::Standard => self.token("[["),
956                AttrSyntax::Gnu => self.token("__attribute__(("),
957                AttrSyntax::Declspec => self.token("__declspec("),
958            }
959            if let Some(namespace) = attr.namespace {
960                self.name(namespace);
961                self.token("::");
962            }
963            self.name(attr.name);
964            if !attr.args.is_empty() {
965                self.token("(");
966                for (index, arg) in ast[attr.args].iter().enumerate() {
967                    if index > 0 {
968                        self.token(",");
969                        self.space();
970                    }
971                    match *arg {
972                        AttrArg::Ident(name) => self.name(name),
973                        AttrArg::Expr(expr) => self.expr_at(expr, ASSIGN),
974                    }
975                }
976                self.token(")");
977            }
978            match attr.syntax {
979                AttrSyntax::Standard => self.token("]]"),
980                AttrSyntax::Gnu => self.token("))"),
981                AttrSyntax::Declspec => self.token(")"),
982            }
983            // Whatever comes next reads as part of the attribute without this. Nothing needs it
984            // to lex, and `token` takes it back where what follows is punctuation.
985            self.space();
986        }
987    }
988
989    /// An initializer, which is an expression or a braced list.
990    fn init(&mut self, id: InitId) {
991        let ast = self.ast;
992        match ast[id] {
993            Init::Expr(expr) => self.expr_at(expr, ASSIGN),
994            Init::List(items) => {
995                self.token("{");
996                for (index, item) in ast[items].iter().enumerate() {
997                    if index > 0 {
998                        self.token(",");
999                    }
1000                    self.space();
1001                    let designators = &ast[item.designators];
1002                    for designator in designators {
1003                        self.designator(*designator);
1004                    }
1005                    // The obsolete `name:` form carries its own colon and takes no `=`.
1006                    let obsolete = matches!(designators.last(), Some(Designator::ObsoleteField(_)));
1007                    if !designators.is_empty() && !obsolete {
1008                        self.space();
1009                        self.token("=");
1010                        self.space();
1011                    }
1012                    self.init(item.init);
1013                }
1014                self.space();
1015                self.token("}");
1016            }
1017        }
1018    }
1019
1020    /// One step of a designation, or of a `__builtin_offsetof` path.
1021    fn designator(&mut self, designator: Designator) {
1022        match designator {
1023            Designator::Field(name) => {
1024                self.token(".");
1025                self.name(name);
1026            }
1027            Designator::Index(index) => {
1028                self.token("[");
1029                self.expr_at(index, COMMA);
1030                self.token("]");
1031            }
1032            Designator::Range { lo, hi } => {
1033                self.token("[");
1034                self.expr_at(lo, COND);
1035                self.space();
1036                self.token("...");
1037                self.space();
1038                self.expr_at(hi, COND);
1039                self.token("]");
1040            }
1041            Designator::ObsoleteField(name) => {
1042                self.name(name);
1043                self.token(":");
1044                self.space();
1045            }
1046        }
1047    }
1048
1049    /// An expression, in parentheses when what encloses it binds more tightly than it does.
1050    fn expr_at(&mut self, id: ExprId, min: u8) {
1051        if self.precedence(id) < min {
1052            self.token("(");
1053            self.expression(id);
1054            self.token(")");
1055        } else {
1056            self.expression(id);
1057        }
1058    }
1059
1060    /// How tightly an expression holds together, which decides whether it needs parentheses.
1061    fn precedence(&self, id: ExprId) -> u8 {
1062        match self.ast[id] {
1063            Expr::Comma { .. } => COMMA,
1064            Expr::Assign { .. } => ASSIGN,
1065            Expr::Cond { .. } => COND,
1066            Expr::Binary { op, .. } => binding(op),
1067            Expr::Cast { .. } => CAST,
1068            Expr::Unary { op, .. } => {
1069                if op.is_postfix() {
1070                    POSTFIX
1071                } else {
1072                    UNARY
1073                }
1074            }
1075            Expr::SizeofExpr(_) | Expr::AlignofExpr(_) | Expr::Extension(_) => UNARY,
1076            Expr::Index { .. }
1077            | Expr::Call { .. }
1078            | Expr::Member { .. }
1079            | Expr::CompoundLiteral { .. } => POSTFIX,
1080            _ => PRIMARY,
1081        }
1082    }
1083
1084    /// One expression, with no regard for what encloses it.
1085    fn expression(&mut self, id: ExprId) {
1086        let ast = self.ast;
1087        match ast[id] {
1088            // Poisoned, and written as a constant so that a broken tree still prints to
1089            // something that parses.
1090            Expr::Error => self.token("0"),
1091            Expr::Name(name) => self.name(name),
1092            Expr::Int(constant) => {
1093                let constant = ast[constant];
1094                let text = format!("{}{}", constant.value, constant.ty.suffix());
1095                self.token(&text);
1096            }
1097            Expr::Float(constant) => {
1098                let constant = ast[constant];
1099                let mut text = constant.value.to_hex();
1100                text.push_str(constant.ty.suffix());
1101                if constant.imaginary {
1102                    text.push('i');
1103                }
1104                self.token(&text);
1105            }
1106            Expr::Char(constant) => {
1107                let text = ast[constant].spell();
1108                self.token(&text);
1109            }
1110            Expr::Str(literal) => self.string(literal),
1111            Expr::Bool(value) => self.token(if value { "true" } else { "false" }),
1112            Expr::Nullptr => self.token("nullptr"),
1113            Expr::Index { base, index } => {
1114                self.expr_at(base, POSTFIX);
1115                self.token("[");
1116                self.expr_at(index, COMMA);
1117                self.token("]");
1118            }
1119            Expr::Call { callee, args } => {
1120                self.expr_at(callee, POSTFIX);
1121                self.token("(");
1122                self.arguments(args);
1123                self.token(")");
1124            }
1125            Expr::Member { base, name, arrow } => {
1126                self.expr_at(base, POSTFIX);
1127                self.token(if arrow { "->" } else { "." });
1128                self.name(name);
1129            }
1130            Expr::Unary { op, operand } => {
1131                if op.is_postfix() {
1132                    self.expr_at(operand, POSTFIX);
1133                    self.token(op.spelling());
1134                } else {
1135                    self.token(op.spelling());
1136                    let inner = match op {
1137                        UnaryOp::PreInc | UnaryOp::PreDec => UNARY,
1138                        _ => CAST,
1139                    };
1140                    self.expr_at(operand, inner);
1141                }
1142            }
1143            Expr::Binary { op, lhs, rhs } => {
1144                let at = binding(op);
1145                self.expr_at(lhs, at);
1146                self.space();
1147                self.token(op.spelling());
1148                self.space();
1149                // The right operand needs one more, since every binary operator in C groups to
1150                // the left and `a - (b - c)` is not `a - b - c`.
1151                self.expr_at(rhs, at + 1);
1152            }
1153            Expr::Assign { op, lhs, rhs } => {
1154                self.expr_at(lhs, UNARY);
1155                self.space();
1156                match op {
1157                    Some(op) => {
1158                        let text = format!("{}=", op.spelling());
1159                        self.token(&text);
1160                    }
1161                    None => self.token("="),
1162                }
1163                self.space();
1164                self.expr_at(rhs, ASSIGN);
1165            }
1166            Expr::Cond { cond, then, otherwise } => {
1167                self.expr_at(cond, COND + 1);
1168                self.space();
1169                self.token("?");
1170                if let Some(then) = then {
1171                    self.space();
1172                    self.expr_at(then, COMMA);
1173                }
1174                self.space();
1175                self.token(":");
1176                self.space();
1177                self.expr_at(otherwise, COND);
1178            }
1179            Expr::Comma { lhs, rhs } => {
1180                self.expr_at(lhs, COMMA);
1181                self.token(",");
1182                self.space();
1183                self.expr_at(rhs, ASSIGN);
1184            }
1185            Expr::Cast { ty, operand } => {
1186                self.token("(");
1187                self.type_name(ty);
1188                self.token(")");
1189                self.expr_at(operand, CAST);
1190            }
1191            Expr::CompoundLiteral { ty, init } => {
1192                self.token("(");
1193                self.type_name(ty);
1194                self.token(")");
1195                self.init(init);
1196            }
1197            // The operand is bracketed unless it is already a name or a constant, because
1198            // `sizeof (T){ 0 }` reads as a type in parentheses and is not one.
1199            Expr::SizeofExpr(operand) => {
1200                self.token("sizeof");
1201                self.space();
1202                self.expr_at(operand, PRIMARY);
1203            }
1204            Expr::SizeofType(ty) => {
1205                self.token("sizeof");
1206                self.token("(");
1207                self.type_name(ty);
1208                self.token(")");
1209            }
1210            Expr::AlignofExpr(operand) => {
1211                self.token("__alignof__");
1212                self.space();
1213                self.expr_at(operand, PRIMARY);
1214            }
1215            Expr::AlignofType(ty) => {
1216                self.token("_Alignof");
1217                self.token("(");
1218                self.type_name(ty);
1219                self.token(")");
1220            }
1221            Expr::Generic { control, assocs } => {
1222                self.token("_Generic");
1223                self.token("(");
1224                self.expr_at(control, ASSIGN);
1225                self.associations(assocs);
1226                self.token(")");
1227            }
1228            Expr::StmtExpr(body) => {
1229                self.token("(");
1230                self.stmt(body);
1231                self.token(")");
1232            }
1233            Expr::LabelAddr(name) => {
1234                self.token("&&");
1235                self.name(name);
1236            }
1237            Expr::Offsetof { ty, path } => {
1238                self.token("__builtin_offsetof");
1239                self.token("(");
1240                self.type_name(ty);
1241                self.token(",");
1242                self.space();
1243                self.member_path(path);
1244                self.token(")");
1245            }
1246            Expr::ChooseExpr { cond, then, otherwise } => {
1247                self.token("__builtin_choose_expr");
1248                self.token("(");
1249                self.expr_at(cond, ASSIGN);
1250                self.token(",");
1251                self.space();
1252                self.expr_at(then, ASSIGN);
1253                self.token(",");
1254                self.space();
1255                self.expr_at(otherwise, ASSIGN);
1256                self.token(")");
1257            }
1258            Expr::TypesCompatible { a, b } => {
1259                self.token("__builtin_types_compatible_p");
1260                self.token("(");
1261                self.type_name(a);
1262                self.token(",");
1263                self.space();
1264                self.type_name(b);
1265                self.token(")");
1266            }
1267            Expr::VaArg { list, ty } => {
1268                self.token("__builtin_va_arg");
1269                self.token("(");
1270                self.expr_at(list, ASSIGN);
1271                self.token(",");
1272                self.space();
1273                self.type_name(ty);
1274                self.token(")");
1275            }
1276            Expr::Extension(operand) => {
1277                self.token("__extension__");
1278                self.space();
1279                self.expr_at(operand, CAST);
1280            }
1281        }
1282    }
1283
1284    /// The arguments of a call, which are assignment-expressions so that the commas between
1285    /// them stay separators.
1286    fn arguments(&mut self, args: ExprList) {
1287        let ast = self.ast;
1288        for (index, &arg) in ast[args].iter().enumerate() {
1289            if index > 0 {
1290                self.token(",");
1291                self.space();
1292            }
1293            self.expr_at(arg, ASSIGN);
1294        }
1295    }
1296
1297    /// The arms of a `_Generic`, the leading comma of each included.
1298    fn associations(&mut self, assocs: GenericList) {
1299        let ast = self.ast;
1300        for assoc in &ast[assocs] {
1301            self.token(",");
1302            self.space();
1303            match assoc.ty {
1304                Some(ty) => self.type_name(ty),
1305                None => self.token("default"),
1306            }
1307            self.token(":");
1308            self.space();
1309            self.expr_at(assoc.value, ASSIGN);
1310        }
1311    }
1312
1313    /// The member path of a `__builtin_offsetof`, whose first step is written with no dot.
1314    fn member_path(&mut self, path: DesignatorList) {
1315        let ast = self.ast;
1316        for (index, step) in ast[path].iter().enumerate() {
1317            match (index, *step) {
1318                (0, Designator::Field(name)) => self.name(name),
1319                (_, step) => self.designator(step),
1320            }
1321        }
1322    }
1323
1324    /// A string literal, prefix and quotes included.
1325    fn string(&mut self, id: StrId) {
1326        let ast = self.ast;
1327        let text = ast[id].spell();
1328        self.token(&text);
1329    }
1330
1331    /// An identifier.
1332    fn name(&mut self, symbol: Symbol) {
1333        let names = self.names;
1334        self.token(names.resolve(symbol));
1335    }
1336
1337    /// Writes with the output redirected into a buffer of its own, and gives the buffer back.
1338    fn capture(&mut self, write: impl FnOnce(&mut Printer<'a>)) -> String {
1339        let held = std::mem::take(&mut self.out);
1340        write(self);
1341        std::mem::replace(&mut self.out, held)
1342    }
1343
1344    /// Appends one token, with a space in front of it if it would otherwise join the one before.
1345    fn token(&mut self, text: &str) {
1346        if text.is_empty() {
1347            return;
1348        }
1349        if text.starts_with([';', ',', ')', ']']) {
1350            self.unspace();
1351        }
1352        if let (Some(last), Some(next)) = (self.out.chars().next_back(), text.chars().next()) {
1353            if pastes(last, next) {
1354                self.out.push(' ');
1355            }
1356        }
1357        self.out.push_str(text);
1358    }
1359
1360    /// Takes back a space that was written for reading, where what follows turns out not to want
1361    /// one in front of it. An indent is not one of those spaces and stays.
1362    fn unspace(&mut self) {
1363        let kept = self.out.trim_end_matches(' ');
1364        if !kept.ends_with('\n') {
1365            self.out.truncate(kept.len());
1366        }
1367    }
1368
1369    /// Appends a space, where one is wanted for reading rather than needed for lexing.
1370    fn space(&mut self) {
1371        if !self.out.is_empty() && !self.out.ends_with([' ', '\n']) {
1372            self.out.push(' ');
1373        }
1374    }
1375
1376    /// Ends the line and indents the next one.
1377    fn newline(&mut self) {
1378        while self.out.ends_with(' ') {
1379            self.out.pop();
1380        }
1381        self.out.push('\n');
1382        for _ in 0..self.depth {
1383            self.out.push_str("    ");
1384        }
1385    }
1386}
1387
1388#[cfg(test)]
1389mod tests {
1390    use rucc_diag::Span;
1391    use rucc_lex::{CharConstant, Encoding, StringLiteral};
1392
1393    use super::*;
1394    use crate::decl::Declarator;
1395    use crate::spec::{DeclSpecs, StorageClass};
1396
1397    struct Fixture {
1398        ast: Ast,
1399        names: Interner,
1400    }
1401
1402    impl Fixture {
1403        fn new() -> Fixture {
1404            Fixture { ast: Ast::new(), names: Interner::new() }
1405        }
1406
1407        fn text(&self, write: impl FnOnce(&mut Printer<'_>)) -> String {
1408            let mut printer = Printer::new(&self.ast, &self.names);
1409            write(&mut printer);
1410            printer.finish()
1411        }
1412    }
1413
1414    #[test]
1415    fn two_tokens_that_would_join_get_a_space() {
1416        let mut fixture = Fixture::new();
1417        let one = fixture.ast.expr(Expr::Bool(true), Span::DUMMY);
1418        let minus = fixture.ast.expr(Expr::Unary { op: UnaryOp::Minus, operand: one }, Span::DUMMY);
1419        let twice =
1420            fixture.ast.expr(Expr::Unary { op: UnaryOp::Minus, operand: minus }, Span::DUMMY);
1421        assert_eq!(fixture.text(|p| p.expr(twice)), "- -true");
1422    }
1423
1424    #[test]
1425    fn parentheses_go_where_the_grammar_needs_them_and_nowhere_else() {
1426        let mut fixture = Fixture::new();
1427        let a = fixture.names.intern("a");
1428        let b = fixture.names.intern("b");
1429        let c = fixture.names.intern("c");
1430        let a = fixture.ast.expr(Expr::Name(a), Span::DUMMY);
1431        let b = fixture.ast.expr(Expr::Name(b), Span::DUMMY);
1432        let c = fixture.ast.expr(Expr::Name(c), Span::DUMMY);
1433
1434        let sum = fixture.ast.expr(Expr::Binary { op: BinaryOp::Add, lhs: a, rhs: b }, Span::DUMMY);
1435        let scaled =
1436            fixture.ast.expr(Expr::Binary { op: BinaryOp::Mul, lhs: sum, rhs: c }, Span::DUMMY);
1437        assert_eq!(fixture.text(|p| p.expr(scaled)), "(a + b) * c");
1438
1439        let product =
1440            fixture.ast.expr(Expr::Binary { op: BinaryOp::Mul, lhs: b, rhs: c }, Span::DUMMY);
1441        let total =
1442            fixture.ast.expr(Expr::Binary { op: BinaryOp::Add, lhs: a, rhs: product }, Span::DUMMY);
1443        assert_eq!(fixture.text(|p| p.expr(total)), "a + b * c");
1444
1445        // Left grouping, so the right operand of a subtraction keeps its parentheses.
1446        let inner =
1447            fixture.ast.expr(Expr::Binary { op: BinaryOp::Sub, lhs: b, rhs: c }, Span::DUMMY);
1448        let outer =
1449            fixture.ast.expr(Expr::Binary { op: BinaryOp::Sub, lhs: a, rhs: inner }, Span::DUMMY);
1450        assert_eq!(fixture.text(|p| p.expr(outer)), "a - (b - c)");
1451    }
1452
1453    #[test]
1454    fn a_declarator_reads_outward_from_its_name() {
1455        let mut fixture = Fixture::new();
1456        let f = fixture.names.intern("f");
1457        let three = fixture.ast.expr(Expr::Bool(true), Span::DUMMY);
1458        let derived = fixture.ast.add_derived_list(&[
1459            Derived::Array { size: ArraySize::Expr(three), quals: Quals::NONE, has_static: false },
1460            Derived::Pointer { quals: Quals::NONE, attrs: AttrList::EMPTY },
1461            Derived::Function { params: ParamList::EMPTY, variadic: false, kind: ParamKind::Void },
1462        ]);
1463        let declarator = fixture.ast.add_declarator(Declarator {
1464            name: Some(f),
1465            name_span: Span::DUMMY,
1466            derived,
1467            span: Span::DUMMY,
1468        });
1469        let specs = fixture.ast.add_specs(DeclSpecs::empty(Span::DUMMY));
1470        let ty = fixture.ast.add_type_name(crate::decl::TypeName {
1471            specs,
1472            declarator,
1473            span: Span::DUMMY,
1474        });
1475        assert_eq!(fixture.text(|p| p.type_name(ty)), "(*f[true])(void)");
1476    }
1477
1478    #[test]
1479    fn a_declaration_keeps_its_declarators_together() {
1480        let mut fixture = Fixture::new();
1481        let a = fixture.names.intern("a");
1482        let b = fixture.names.intern("b");
1483        let mut specs = DeclSpecs::empty(Span::DUMMY);
1484        specs.storage = Some(StorageClass::Static);
1485        specs.ty = TypeSpec::Builtin(Builtin { set: BuiltinSet::INT, longs: 0, width: None });
1486        let specs = fixture.ast.add_specs(specs);
1487        let mut declarators = Vec::new();
1488        for (name, stars) in [(a, 0), (b, 1)] {
1489            let derived = if stars == 0 {
1490                crate::ast::DerivedList::EMPTY
1491            } else {
1492                fixture.ast.add_derived_list(&[Derived::Pointer {
1493                    quals: Quals::NONE,
1494                    attrs: AttrList::EMPTY,
1495                }])
1496            };
1497            let declarator = fixture.ast.add_declarator(Declarator {
1498                name: Some(name),
1499                name_span: Span::DUMMY,
1500                derived,
1501                span: Span::DUMMY,
1502            });
1503            declarators.push(crate::decl::InitDeclarator {
1504                declarator,
1505                init: None,
1506                asm_label: None,
1507                attrs: AttrList::EMPTY,
1508                span: Span::DUMMY,
1509            });
1510        }
1511        let declarators = fixture.ast.add_init_declarator_list(&declarators);
1512        let decl = fixture.ast.decl(Decl::Var { specs, declarators }, Span::DUMMY);
1513        assert_eq!(fixture.text(|p| p.decl(decl)), "static int a, *b;");
1514    }
1515
1516    #[test]
1517    fn a_byte_escape_in_a_string_takes_three_octal_digits() {
1518        let literal = StringLiteral {
1519            elements: vec![0xff, u32::from(b'0'), u32::from(b'a')],
1520            encoding: Encoding::Plain,
1521            remarks: rucc_lex::Remarks::NONE,
1522        };
1523        assert_eq!(literal.spell(), "\"\\3770a\"");
1524    }
1525
1526    #[test]
1527    fn a_wide_escape_closes_the_literal_rather_than_swallowing_what_follows() {
1528        let literal = StringLiteral {
1529            elements: vec![0x1234, u32::from(b'a'), u32::from(b'z')],
1530            encoding: Encoding::Utf32,
1531            remarks: rucc_lex::Remarks::NONE,
1532        };
1533        assert_eq!(literal.spell(), "U\"\\x1234\" U\"az\"");
1534    }
1535
1536    #[test]
1537    fn a_character_constant_is_written_as_a_character_where_it_can_be() {
1538        let plain = CharConstant {
1539            value: i64::from(b'a'),
1540            encoding: Encoding::Plain,
1541            remarks: rucc_lex::Remarks::NONE,
1542        };
1543        assert_eq!(plain.spell(), "'a'");
1544
1545        let quote = CharConstant { encoding: Encoding::Plain, value: i64::from(b'\''), ..plain };
1546        assert_eq!(quote.spell(), "'\\''");
1547
1548        let negative = CharConstant { value: -1, ..plain };
1549        assert_eq!(negative.spell(), "'\\xff'");
1550
1551        let many = CharConstant { value: 0x6162, ..plain };
1552        assert_eq!(many.spell(), "'\\x61\\x62'");
1553    }
1554}