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