1use 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
64const COMMA: u8 = 1;
66const ASSIGN: u8 = 2;
68const COND: u8 = 3;
70const LOG_OR: u8 = 4;
72const LOG_AND: u8 = 5;
74const BIT_OR: u8 = 6;
76const BIT_XOR: u8 = 7;
78const BIT_AND: u8 = 8;
80const EQUALITY: u8 = 9;
82const RELATIONAL: u8 = 10;
84const SHIFT: u8 = 11;
86const ADDITIVE: u8 = 12;
88const MULTIPLICATIVE: u8 = 13;
90const CAST: u8 = 14;
92const UNARY: u8 = 15;
94const POSTFIX: u8 = 16;
96const PRIMARY: u8 = 17;
98
99const 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
115const 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
145fn 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 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
180fn 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#[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#[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 #[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 #[must_use]
217 pub fn finish(self) -> String {
218 self.out
219 }
220
221 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 pub fn decl(&mut self, id: DeclId) {
237 let ast = self.ast;
238 match ast[id] {
239 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 ¶m 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 pub fn stmt(&mut self, id: StmtId) {
298 let ast = self.ast;
299 match ast[id] {
300 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 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 pub fn expr(&mut self, id: ExprId) {
462 self.expr_at(id, COMMA);
463 }
464
465 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 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 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 fn labelled(&mut self, body: Option<StmtId>) {
506 if let Some(body) = body {
507 self.newline();
508 self.stmt(body);
509 }
510 }
511
512 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 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 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 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 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 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 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 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 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 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 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 if which == BuiltinSet::SHORT {
736 for _ in 0..builtin.longs {
737 self.token("long");
738 }
739 }
740 }
741 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 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 index += 1;
772 } else {
773 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 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 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 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 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 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 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 self.space();
987 }
988 }
989
990 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 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 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 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 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 fn expression(&mut self, id: ExprId) {
1087 let ast = self.ast;
1088 match ast[id] {
1089 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 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 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 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 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 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 fn string(&mut self, id: StrId) {
1353 let ast = self.ast;
1354 let text = ast[id].spell();
1355 self.token(&text);
1356 }
1357
1358 fn name(&mut self, symbol: Symbol) {
1360 let names = self.names;
1361 self.token(names.resolve(symbol));
1362 }
1363
1364 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 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 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 fn space(&mut self) {
1398 if !self.out.is_empty() && !self.out.ends_with([' ', '\n']) {
1399 self.out.push(' ');
1400 }
1401 }
1402
1403 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 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 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}