diff --git a/README.md b/README.md index abf7468..ec5596b 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,6 @@ ncc [OPTIONS] ... | `--no-iced` | Use text-based asm building instead of iced (deprecated) | | `-o`, `--output ` | Override output file location | | `-h`, `--help` | Print help | -| `-V`, `--version` | Print version | Note: `--lex`, `--parse`, `--validate`, `--codegen`, `--tacky`, `-S`, `--run`, `-c` are mutually exclusive options. @@ -177,6 +176,32 @@ Note: `--lex`, `--parse`, `--validate`, `--codegen`, `--tacky`, `-S`, `--run`, ` | 20 | Parser error (syntax error) | | 30 | Validation error (semantic error) | +## Architecture + +NCC follows a classic multi-pass compiler pipeline: + +```mermaid +flowchart LR + A[Source .c] --> B[Lexer] + B -->|Tokens| C[Parser] + C -->|Abstract AST| D[Validator] + D -->|Typechecked AST & Symbol Table| E[Tackifier] + E -->|TACKY IR| F[Codegen] + F -->|Assembly AST| G[Emitter] + G -->|Object File| H[Linker] + H --> I[Executable] +``` + +| Pass | Description | +|------|-------------| +| **Lexer** | Converts source text into tokens using regex patterns with maximal munch. Each token carries a span (file, line, column) for error reporting. | +| **Parser** | Recursive descent with precedence climbing. Builds an abstract syntax tree while handling operator precedence and associativity. | +| **Validator** | Two-pass semantic analysis: (1) resolves variables to unique names, labels loops/switches, validates gotos; (2) type checks, builds symbol table, evaluates constant expressions. | +| **Tackifier** | Lowers the AST to TACKY, a three-address code IR. Flattens nested expressions into sequences of simple operations and makes control flow explicit with jumps and labels. | +| **Codegen** | Converts TACKY to an x86-64 assembly AST. Assigns pseudo-registers to stack slots, fixes invalid instructions, and implements the System V AMD64 calling convention. | +| **Emitter** | Encodes instructions to machine code using [iced-x86](https://github.com/icedland/iced) and writes ELF/Mach-O object files via the [object](https://github.com/gimli-rs/object) crate. | +| **Linker** | Resolves external symbols and produces the final executable. Uses [wild](https://github.com/nicholasbishop/wild) on Linux; shells out to `ld` on macOS. | + ## Language Grammar The compiler currently implements a subset of C with the following grammar: diff --git a/src/main.rs b/src/main.rs index be36e93..d7afa4c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -237,6 +237,18 @@ fn link_with_libwild(obj_files: &[String], out_file: &str, static_link: bool) { fn main() { let args = Args::parse(); + // Only enable colors if stderr and stdout are TTYs (terminals) + use std::io::IsTerminal; + let is_tty = std::io::stderr().is_terminal() && std::io::stdout().is_terminal(); + if is_tty { + colored::control::set_override(true); + // Enable TrueColor support for better color accuracy + // Safety: Setting COLORTERM is safe at program startup before any threads are spawned + unsafe { + std::env::set_var("COLORTERM", "truecolor"); + } + } + // On macOS, always use external linker since libwild doesn't support it let use_external_linker = args.external_linker || cfg!(target_os = "macos"); @@ -285,6 +297,7 @@ fn main() { if args.validate { println!("Program Valid"); + println!("{}", ast.itf_string()); std::process::exit(0); } @@ -292,7 +305,6 @@ fn main() { let tacky_ast = tacky::tackify_program(&ast, &mut name_gen, &symbols); if args.tacky { - println!("{tacky_ast:?}"); println!("{}", tacky_ast.itf_string()); std::process::exit(0); } diff --git a/src/pretty.rs b/src/pretty.rs index eef63e9..1250027 100644 --- a/src/pretty.rs +++ b/src/pretty.rs @@ -15,6 +15,60 @@ use crate::tacky::{ StaticVariable, TopLevel, Val, VarInit, }; +// ============================================================================= +// Color Scheme: vitesse-dark theme (TrueColor 24-bit RGB) +// ============================================================================= +// +// This module uses the vitesse-dark color palette to provide rich syntax +// highlighting for the compiler's AST pretty printer across all stages: +// Parser, Tacky IR, and Codegen. +// +// Color Mapping: +// +// 1. TEAL (93, 169, 148) - Instructions & Declarations +// - Instructions: Mov, Binary, Copy, Jump, Call, Label, Return (Tacky), etc. +// - Declarations: Program, FunctionDefinition, VarDeclaration, FunDeclaration +// - Expression types: PostFix, Assignment, Conditional, Unary, Binary (Parser) +// +// 2. TEAL_GREEN (77, 147, 117) - Control Flow & Registers +// - Control flow keywords: Return, If, While, For, Break, Continue, Switch, etc. +// - CPU Registers: AX, R10, SP, BP, etc. +// +// 3. MUTED_RED (203, 118, 118) - Operators & Type Qualifiers +// - Operators: Add, Multiply, NotEqual, BitwiseAnd, Increment, etc. +// - Operand type keywords: Imm, Stack, Data, Pseudo +// - Condition codes: E, NE, L, LE, G, GE, etc. +// +// 4. YELLOW_GREEN (128, 166, 101) - Names & Labels +// - Function names and identifiers +// - Jump target labels (.Lstart_loop, .Lbreak, etc.) +// - Data labels (global variable names) +// +// 5. CREAM (219, 215, 202) - Variables +// - Local variable names +// - Temporary variables (temp.1, binary_left.2, etc.) +// - Pseudo register names +// +// 6. CYAN_TEAL (76, 154, 145) - Numeric Values +// - Integer literals +// - Immediate values +// - Stack offsets (-4, -8, etc.) +// - Memory offsets and allocation sizes +// +// 7. YELLOW_GOLD (230, 204, 119) - String Constants +// - Constant expressions in Parser AST +// - String literal values +// +// ============================================================================= + +const TEAL_GREEN: (u8, u8, u8) = (77, 147, 117); // s5: #4d9375 +const TEAL: (u8, u8, u8) = (93, 169, 148); // s12: #5da994 +const MUTED_RED: (u8, u8, u8) = (203, 118, 118); // s6: #cb7676 +const YELLOW_GREEN: (u8, u8, u8) = (128, 166, 101); // s3: #80a665 +const CREAM: (u8, u8, u8) = (219, 215, 202); // s4: #dbd7caee +const CYAN_TEAL: (u8, u8, u8) = (76, 154, 145); // s18: #4c9a91 +const YELLOW_GOLD: (u8, u8, u8) = (230, 204, 119); // s17: #e6cc77 + #[derive(Clone)] pub struct Node { pub text: String, @@ -70,48 +124,66 @@ pub trait ItfDisplay { } } -macro_rules! simple_node { - ($($ty:ty),* $(,)?) => { +macro_rules! colored_node { + ($r:expr, $g:expr, $b:expr; $($ty:ty),* $(,)?) => { $( impl ItfDisplay for $ty { fn itf_node(&self) -> Node { - Node::leaf(format!("{:?}", self).cyan().to_string()) + Node::leaf(format!("{:?}", self).truecolor($r, $g, $b).to_string()) } } )* }; } -// All simple Debug-based display types -simple_node!( +// Operators and condition codes (muted red) +colored_node!( + MUTED_RED.0, MUTED_RED.1, MUTED_RED.2; ParserUnaryOp, ParserBinOp, AssignOp, - IncDec, // Parser - BinOp, // Tacky - Reg, + IncDec, // Parser + BinOp, // Tacky UnaryOp, BinaryOp, - CondCode, // Codegen + CondCode, // Codegen ); -// Macro for types with `name` and `body` fields (FunctionDefinition pattern) -macro_rules! impl_function_def { - ($($ty:ty),* $(,)?) => { - $( - impl ItfDisplay for $ty { - fn itf_node(&self) -> Node { - let name_line = Node::leaf(format!("name: {}", self.name.itf_node().text)); - let body_children: Vec = self.body.iter().map(|i| i.itf_node()).collect(); - let body_node = Node::branch("body".cyan().to_string(), body_children); - Node::branch("FunctionDefinition".cyan().to_string(), vec![name_line, body_node]) - } - } - )* - }; +// Registers (teal-green) +colored_node!( + TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2; + Reg, +); + +// TACKY function definition - compact format +impl ItfDisplay for TackyFunctionDefinition { + fn itf_node(&self) -> Node { + let body_children: Vec = self.body.iter().map(|i| i.itf_node()).collect(); + Node::branch( + format!( + "{}: {}", + "FunctionDefinition".truecolor(TEAL.0, TEAL.1, TEAL.2), + self.name + ), + body_children, + ) + } } -impl_function_def!(TackyFunctionDefinition, CodegenFunctionDefinition); +// Codegen function definition - compact format +impl ItfDisplay for CodegenFunctionDefinition { + fn itf_node(&self) -> Node { + let body_children: Vec = self.body.iter().map(|i| i.itf_node()).collect(); + Node::branch( + format!( + "{}: {}", + "FunctionDefinition".truecolor(TEAL.0, TEAL.1, TEAL.2), + self.name + ), + body_children, + ) + } +} // Macro for types with `top_level` field (Program pattern) macro_rules! impl_program { @@ -120,7 +192,7 @@ macro_rules! impl_program { impl ItfDisplay for $ty { fn itf_node(&self) -> Node { let children: Vec = self.top_level.iter().map(|t| t.itf_node()).collect(); - Node::branch("Program".cyan().to_string(), children) + Node::branch("Program".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), children) } } )* @@ -133,14 +205,14 @@ impl ItfDisplay for CodegenProgram { fn itf_node(&self) -> Node { let mut children: Vec = self.functions.iter().map(|f| f.itf_node()).collect(); children.extend(self.static_vars.iter().map(|v| v.itf_node())); - Node::branch("Program".cyan().to_string(), children) + Node::branch("Program".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), children) } } impl ItfDisplay for ParserProgram { fn itf_node(&self) -> Node { let children: Vec = self.declarations.iter().map(|d| d.itf_node()).collect(); - Node::branch("Program".cyan().to_string(), children) + Node::branch("Program".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), children) } } @@ -182,13 +254,13 @@ delegate_field!(SpannedStmt => stmt); impl ItfDisplay for String { fn itf_node(&self) -> Node { - Node::leaf(self.green().to_string()) + Node::leaf(self.truecolor(CREAM.0, CREAM.1, CREAM.2).to_string()) } } impl ItfDisplay for &str { fn itf_node(&self) -> Node { - Node::leaf(self.green().to_string()) + Node::leaf(self.truecolor(CREAM.0, CREAM.1, CREAM.2).to_string()) } } @@ -198,7 +270,7 @@ macro_rules! impl_itf_display_for_int { $( impl ItfDisplay for $t { fn itf_node(&self) -> Node { - Node::leaf(self.to_string().magenta().to_string()) + Node::leaf(self.to_string().truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2).to_string()) } } )* @@ -211,7 +283,12 @@ impl_itf_display_for_int!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u12 impl ItfDisplay for Vec { fn itf_node(&self) -> Node { let children: Vec = self.iter().map(|item| item.itf_node()).collect(); - Node::branch(format!("[{}]", self.len()).cyan().to_string(), children) + Node::branch( + format!("[{}]", self.len()) + .truecolor(TEAL.0, TEAL.1, TEAL.2) + .to_string(), + children, + ) } } @@ -225,7 +302,7 @@ impl ItfDisplay for ForInit { ForInit::InitDecl(decl) => decl.itf_node(), ForInit::InitExp(opt_expr) => match opt_expr { Some(expr) => expr.itf_node(), - None => Node::leaf("None".cyan().to_string()), + None => Node::leaf("None".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string()), }, } } @@ -233,35 +310,53 @@ impl ItfDisplay for ForInit { impl ItfDisplay for Identifier { fn itf_node(&self) -> Node { - Node::leaf(format!("Identifier(\"{}\")", self.0).green().to_string()) + Node::leaf( + format!("Identifier(\"{}\")", self.0) + .truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2) + .to_string(), + ) } } impl ItfDisplay for Expr { fn itf_node(&self) -> Node { match self { - Expr::Constant(c) => Node::leaf(format!("Constant({c})").yellow().to_string()), + Expr::Constant(c) => Node::leaf( + format!("Constant({c})") + .truecolor(YELLOW_GOLD.0, YELLOW_GOLD.1, YELLOW_GOLD.2) + .to_string(), + ), Expr::Var(id, _span) => id.itf_node(), - Expr::Unary(op, e) => Node::branch(format!("Unary ({op:?})").cyan().to_string(), vec![e.itf_node()]), + Expr::Unary(op, e) => Node::branch( + format!("Unary ({op:?})").truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![e.itf_node()], + ), Expr::Binary(op, e1, e2) => Node::branch( - format!("Binary ({op:?})").cyan().to_string(), + format!("Binary ({op:?})").truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), vec![e1.itf_node(), e2.itf_node()], ), - Expr::Assignment(lhs, rhs, _span) => { - Node::branch("Assignment".cyan().to_string(), vec![lhs.itf_node(), rhs.itf_node()]) - } + Expr::Assignment(lhs, rhs, _span) => Node::branch( + "Assignment".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![lhs.itf_node(), rhs.itf_node()], + ), Expr::CompoundAssignment(op, lhs, rhs, _span) => Node::branch( - format!("CompoundAssignment ({op:?})").cyan().to_string(), + format!("CompoundAssignment ({op:?})") + .truecolor(TEAL.0, TEAL.1, TEAL.2) + .to_string(), vec![lhs.itf_node(), rhs.itf_node()], ), - Expr::PostFixOp(op, e, _span) => { - Node::branch(format!("PostFix ({op:?})").cyan().to_string(), vec![e.itf_node()]) - } - Expr::PreFixOp(op, e, _span) => { - Node::branch(format!("PreFix ({op:?})").cyan().to_string(), vec![e.itf_node()]) - } + Expr::PostFixOp(op, e, _span) => Node::branch( + format!("PostFix ({op:?})") + .truecolor(TEAL.0, TEAL.1, TEAL.2) + .to_string(), + vec![e.itf_node()], + ), + Expr::PreFixOp(op, e, _span) => Node::branch( + format!("PreFix ({op:?})").truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![e.itf_node()], + ), Expr::Conditional(condition, then_expr, else_expr) => Node::branch( - "Conditional".cyan().to_string(), + "Conditional".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), vec![ Node::branch("condition:", vec![condition.itf_node()]), Node::branch("then:", vec![then_expr.itf_node()]), @@ -274,7 +369,7 @@ impl ItfDisplay for Expr { let arg_nodes: Vec = args.iter().map(|a| a.itf_node()).collect(); children.push(Node::branch("args:", arg_nodes)); } - Node::branch("FunctionCall".cyan().to_string(), children) + Node::branch("FunctionCall".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), children) } } } @@ -283,8 +378,16 @@ impl ItfDisplay for Expr { impl ItfDisplay for Stmt { fn itf_node(&self) -> Node { match self { - Stmt::Return(expr) => Node::branch("Return".cyan().to_string(), vec![expr.itf_node()]), - Stmt::Expression(expr) => Node::branch("Expression".cyan().to_string(), vec![expr.itf_node()]), + Stmt::Return(expr) => Node::branch( + "Return".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string(), + vec![expr.itf_node()], + ), + Stmt::Expression(expr) => Node::branch( + "Expression" + .truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2) + .to_string(), + vec![expr.itf_node()], + ), Stmt::If(condition, then_stmt, else_stmt) => { let mut children = vec![ Node::branch("condition:", vec![condition.itf_node()]), @@ -293,35 +396,80 @@ impl ItfDisplay for Stmt { if let Some(else_s) = else_stmt.as_ref() { children.push(Node::branch("else:", vec![else_s.stmt.itf_node()])); } - Node::branch("If".cyan().to_string(), children) + Node::branch( + "If".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string(), + children, + ) } - Stmt::Null => Node::leaf("Null".cyan().to_string()), - Stmt::Goto(label) => Node::branch("Goto".cyan().to_string(), vec![label.itf_node()]), + Stmt::Null => Node::leaf("Null".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string()), + Stmt::Goto(label) => Node::branch( + "Goto".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string(), + vec![label.itf_node()], + ), Stmt::Labeled(label, stmt) => Node::branch( - "Labeled".cyan().to_string(), + "Labeled" + .truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2) + .to_string(), vec![label.itf_node(), stmt.stmt.itf_node()], ), Stmt::Compound(block) => { let children: Vec = block.iter().map(|item| item.itf_node()).collect(); - Node::branch("Compound".cyan().to_string(), children) + Node::branch( + "Compound" + .truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2) + .to_string(), + children, + ) + } + Stmt::Break(target) => { + let label_str = if target.0.is_empty() { + "Break".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string() + } else { + format!( + "{} [{}]", + "Break".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + target.0 + ) + }; + Node::leaf(label_str) + } + Stmt::Continue(target) => { + let label_str = if target.0.is_empty() { + "Continue" + .truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2) + .to_string() + } else { + format!( + "{} [{}]", + "Continue".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + target.0 + ) + }; + Node::leaf(label_str) } - Stmt::Break(..) => Node::leaf("Break".cyan().to_string()), - Stmt::Continue(..) => Node::leaf("Continue".cyan().to_string()), - Stmt::While(condition, body, _) => Node::branch( - "While".cyan().to_string(), + Stmt::While(condition, body, label) => Node::branch( + format!( + "{} [label: {}]", + "While".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label + ), vec![ Node::branch("condition:", vec![condition.itf_node()]), Node::branch("body:", vec![body.stmt.itf_node()]), ], ), - Stmt::DoWhile(body, condition, _) => Node::branch( - "DoWhile".cyan().to_string(), + Stmt::DoWhile(body, condition, label) => Node::branch( + format!( + "{} [label: {}]", + "DoWhile".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label + ), vec![ Node::branch("body:", vec![body.stmt.itf_node()]), Node::branch("condition:", vec![condition.itf_node()]), ], ), - Stmt::For(init, condition, post, body, _) => { + Stmt::For(init, condition, post, body, label) => { let mut children = vec![Node::branch("init:", vec![init.itf_node()])]; if let Some(cond) = condition { children.push(Node::branch("condition:", vec![cond.itf_node()])); @@ -330,23 +478,58 @@ impl ItfDisplay for Stmt { children.push(Node::branch("post:", vec![post_expr.itf_node()])); } children.push(Node::branch("body:", vec![body.stmt.itf_node()])); - Node::branch("For".cyan().to_string(), children) + Node::branch( + format!( + "{} [label: {}]", + "For".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label + ), + children, + ) } - Stmt::Switch(expr, body, ..) => Node::branch( - "Switch".cyan().to_string(), + Stmt::Switch(expr, body, label, _) => Node::branch( + format!( + "{} [label: {}]", + "Switch".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label + ), vec![ Node::branch("expr:", vec![expr.itf_node()]), Node::branch("body:", vec![body.stmt.itf_node()]), ], ), - Stmt::Case(expr, stmt, _) => Node::branch( - "Case".cyan().to_string(), - vec![ - Node::branch("expr:", vec![expr.itf_node()]), - Node::branch("stmt:", vec![stmt.stmt.itf_node()]), - ], - ), - Stmt::Default(stmt, ..) => Node::branch("Default".cyan().to_string(), vec![stmt.stmt.itf_node()]), + Stmt::Case(expr, stmt, label) => { + let header = if label.0.is_empty() { + "Case".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2).to_string() + } else { + format!( + "{} [{}]", + "Case".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label.0 + ) + }; + Node::branch( + header, + vec![ + Node::branch("expr:", vec![expr.itf_node()]), + Node::branch("stmt:", vec![stmt.stmt.itf_node()]), + ], + ) + } + Stmt::Default(stmt, label) => { + let header = if label.0.is_empty() { + "Default" + .truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2) + .to_string() + } else { + format!( + "{} [{}]", + "Default".truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2), + label.0 + ) + }; + Node::branch(header, vec![stmt.stmt.itf_node()]) + } } } } @@ -357,9 +540,15 @@ impl ItfDisplay for VarDeclaration { match &self.init { Some(init_expr) => { let init_node = Node::branch("init:", vec![init_expr.itf_node()]); - Node::branch("VarDeclaration".cyan().to_string(), vec![name_node, init_node]) + Node::branch( + "VarDeclaration".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![name_node, init_node], + ) } - None => Node::branch("VarDeclaration".cyan().to_string(), vec![name_node]), + None => Node::branch( + "VarDeclaration".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), + vec![name_node], + ), } } } @@ -375,7 +564,7 @@ impl ItfDisplay for FunDeclaration { let body_nodes: Vec = body.iter().map(|b| b.itf_node()).collect(); children.push(Node::branch("body:", body_nodes)); } - Node::branch("FunDeclaration".cyan().to_string(), children) + Node::branch("FunDeclaration".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string(), children) } } @@ -386,42 +575,85 @@ impl ItfDisplay for FunDeclaration { impl ItfDisplay for Val { fn itf_node(&self) -> Node { match self { - Val::Constant(c) => Node::branch("Const".cyan().to_string(), vec![c.itf_node()]), - Val::Var(s) => Node::branch("Var".cyan().to_string(), vec![s.itf_node()]), + Val::Constant(c) => Node::leaf( + c.to_string() + .truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) + .to_string(), + ), + Val::Var(s) => Node::leaf(s.truecolor(CREAM.0, CREAM.1, CREAM.2).to_string()), } } } +// Helper to format Val compactly as string +fn val_str(v: &Val) -> String { + match v { + Val::Constant(c) => c + .to_string() + .truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) + .to_string(), + Val::Var(s) => s.truecolor(CREAM.0, CREAM.1, CREAM.2).to_string(), + } +} + impl ItfDisplay for TackyInstruction { fn itf_node(&self) -> Node { match self { - TackyInstruction::Return(v) => Node::branch("Return".cyan().to_string(), vec![v.itf_node()]), - TackyInstruction::Unary { op, src, dst } => Node::branch( - "Unary".cyan().to_string(), - vec![op.itf_node(), src.itf_node(), dst.itf_node()], - ), - TackyInstruction::Binary { op, src1, src2, dst } => Node::branch( - "Binary".cyan().to_string(), - vec![op.itf_node(), src1.itf_node(), src2.itf_node(), dst.itf_node()], - ), - TackyInstruction::Copy { src, dst } => { - Node::branch("Copy".cyan().to_string(), vec![src.itf_node(), dst.itf_node()]) + TackyInstruction::Return(v) => { + Node::leaf(format!("{} {}", "Return".truecolor(TEAL.0, TEAL.1, TEAL.2), val_str(v))) } - TackyInstruction::Jump { target } => Node::branch("Jump".cyan().to_string(), vec![target.itf_node()]), - TackyInstruction::JumpIfZero { condition, target } => Node::branch( - "JumpIfZero".cyan().to_string(), - vec![condition.itf_node(), target.itf_node()], - ), - TackyInstruction::JumpIfNotZero { condition, target } => Node::branch( - "JumpIfNotZero".cyan().to_string(), - vec![condition.itf_node(), target.itf_node()], - ), - TackyInstruction::Label(lbl) => Node::branch("Label".cyan().to_string(), vec![lbl.itf_node()]), + TackyInstruction::Unary { op, src, dst } => Node::leaf(format!( + "{} {:?} {} -> {}", + "Unary".truecolor(TEAL.0, TEAL.1, TEAL.2), + op, + val_str(src), + val_str(dst) + )), + TackyInstruction::Binary { op, src1, src2, dst } => Node::leaf(format!( + "{} {:?} {}, {} -> {}", + "Binary".truecolor(TEAL.0, TEAL.1, TEAL.2), + op, + val_str(src1), + val_str(src2), + val_str(dst) + )), + TackyInstruction::Copy { src, dst } => Node::leaf(format!( + "{} {} -> {}", + "Copy".truecolor(TEAL.0, TEAL.1, TEAL.2), + val_str(src), + val_str(dst) + )), + TackyInstruction::Jump { target } => Node::leaf(format!( + "{} -> {}", + "Jump".truecolor(TEAL.0, TEAL.1, TEAL.2), + target.0.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2) + )), + TackyInstruction::JumpIfZero { condition, target } => Node::leaf(format!( + "{} {} -> {}", + "JumpIfZero".truecolor(TEAL.0, TEAL.1, TEAL.2), + val_str(condition), + target.0.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2) + )), + TackyInstruction::JumpIfNotZero { condition, target } => Node::leaf(format!( + "{} {} -> {}", + "JumpIfNotZero".truecolor(TEAL.0, TEAL.1, TEAL.2), + val_str(condition), + target.0.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2) + )), + TackyInstruction::Label(lbl) => Node::leaf(format!( + "{}({})", + "Label".truecolor(TEAL.0, TEAL.1, TEAL.2), + lbl.0.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2) + )), TackyInstruction::FunCall { fun_name, args, dst } => { - let mut children = vec![fun_name.itf_node()]; - children.extend(args.iter().map(|a| a.itf_node())); - children.push(dst.itf_node()); - Node::branch("FunCall".cyan().to_string(), children) + let args_str = args.iter().map(val_str).collect::>().join(", "); + Node::leaf(format!( + "{} {}({}) -> {}", + "FunCall".truecolor(TEAL.0, TEAL.1, TEAL.2), + fun_name.0.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2), + args_str, + val_str(dst) + )) } } } @@ -430,17 +662,17 @@ impl ItfDisplay for TackyInstruction { impl ItfDisplay for StaticVariable { fn itf_node(&self) -> Node { let init_str = match &self.init { - VarInit::Defined(v) => v.to_string(), + VarInit::Defined(v) => format!("init: {}", v), VarInit::Extern => "extern".to_string(), }; - Node::branch( - "StaticVariable".cyan().to_string(), - vec![ - Node::leaf(format!("name: {}", self.name.green())), - Node::leaf(format!("global: {}", self.global)), - Node::leaf(format!("init: {}", init_str.magenta())), - ], - ) + let global_str = if self.global { ", global" } else { "" }; + Node::leaf(format!( + "{}: {} ({}{})", + "StaticVariable".truecolor(TEAL.0, TEAL.1, TEAL.2), + self.name, + init_str, + global_str + )) } } @@ -448,53 +680,118 @@ impl ItfDisplay for StaticVariable { // Codegen types // ============================================================================= +// Helper to format Operand compactly as string +fn operand_str(op: &Operand) -> String { + match op { + Operand::Imm(i) => format!( + "{}({})", + "Imm".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2), + i.to_string().truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) + ), + Operand::Reg(r) => format!("{:?}", r) + .truecolor(TEAL_GREEN.0, TEAL_GREEN.1, TEAL_GREEN.2) + .to_string(), + Operand::Pseudo(s) => format!( + "{}({})", + "Pseudo".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2), + s.truecolor(CREAM.0, CREAM.1, CREAM.2) + ), + Operand::Stack(o) => format!( + "{}({})", + "Stack".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2), + o.to_string().truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) + ), + Operand::Data(s) => format!( + "{}({})", + "Data".truecolor(MUTED_RED.0, MUTED_RED.1, MUTED_RED.2), + s.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2) + ), + } +} + impl ItfDisplay for Operand { fn itf_node(&self) -> Node { - match self { - Operand::Imm(i) => Node::branch("Imm".cyan().to_string(), vec![i.itf_node()]), - Operand::Reg(r) => Node::branch("Reg".cyan().to_string(), vec![r.itf_node()]), - Operand::Pseudo(s) => Node::branch("Pseudo".cyan().to_string(), vec![s.itf_node()]), - Operand::Stack(o) => Node::branch("Stack".cyan().to_string(), vec![o.itf_node()]), - Operand::Data(s) => Node::branch("Data".cyan().to_string(), vec![s.itf_node()]), - } + Node::leaf(operand_str(self)) } } impl ItfDisplay for CodegenInstruction { fn itf_node(&self) -> Node { match self { - CodegenInstruction::Mov { src, dst } => { - Node::branch("Mov".cyan().to_string(), vec![src.itf_node(), dst.itf_node()]) - } - CodegenInstruction::Unary { op, dst } => { - Node::branch("Unary".cyan().to_string(), vec![op.itf_node(), dst.itf_node()]) - } - CodegenInstruction::Binary { op, src, dst } => Node::branch( - "Binary".cyan().to_string(), - vec![op.itf_node(), src.itf_node(), dst.itf_node()], - ), - CodegenInstruction::Cmp { v1, v2 } => { - Node::branch("Cmp".cyan().to_string(), vec![v1.itf_node(), v2.itf_node()]) - } - CodegenInstruction::Idiv(op) => Node::branch("Idiv".cyan().to_string(), vec![op.itf_node()]), - CodegenInstruction::Cdq => Node::leaf("Cdq".cyan().to_string()), - CodegenInstruction::Jmp(label) => Node::branch("Jmp".cyan().to_string(), vec![label.itf_node()]), - CodegenInstruction::JmpCC { code, label } => { - Node::branch("JmpCC".cyan().to_string(), vec![code.itf_node(), label.itf_node()]) - } - CodegenInstruction::SetCC { code, op } => { - Node::branch("SetCC".cyan().to_string(), vec![code.itf_node(), op.itf_node()]) - } - CodegenInstruction::Label(l) => Node::branch("Label".cyan().to_string(), vec![l.itf_node()]), - CodegenInstruction::AllocateStack(off) => { - Node::branch("AllocateStack".cyan().to_string(), vec![off.itf_node()]) - } - CodegenInstruction::Ret => Node::leaf("Ret".cyan().to_string()), - CodegenInstruction::DeallocateStack(off) => { - Node::branch("DeallocateStack".cyan().to_string(), vec![off.itf_node()]) - } - CodegenInstruction::Push(op) => Node::branch("Push".cyan().to_string(), vec![op.itf_node()]), - CodegenInstruction::Call(name) => Node::branch("Call".cyan().to_string(), vec![name.itf_node()]), + CodegenInstruction::Mov { src, dst } => Node::leaf(format!( + "{} {} -> {}", + "Mov".truecolor(TEAL.0, TEAL.1, TEAL.2), + operand_str(src), + operand_str(dst) + )), + CodegenInstruction::Unary { op, dst } => Node::leaf(format!( + "{} {:?} {}", + "Unary".truecolor(TEAL.0, TEAL.1, TEAL.2), + op, + operand_str(dst) + )), + CodegenInstruction::Binary { op, src, dst } => Node::leaf(format!( + "{} {:?} {} -> {}", + "Binary".truecolor(TEAL.0, TEAL.1, TEAL.2), + op, + operand_str(src), + operand_str(dst) + )), + CodegenInstruction::Cmp { v1, v2 } => Node::leaf(format!( + "{} {}, {}", + "Cmp".truecolor(TEAL.0, TEAL.1, TEAL.2), + operand_str(v1), + operand_str(v2) + )), + CodegenInstruction::Idiv(op) => Node::leaf(format!( + "{} {}", + "Idiv".truecolor(TEAL.0, TEAL.1, TEAL.2), + operand_str(op) + )), + CodegenInstruction::Cdq => Node::leaf("Cdq".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string()), + CodegenInstruction::Jmp(label) => Node::leaf(format!( + "{} -> {}", + "Jmp".truecolor(TEAL.0, TEAL.1, TEAL.2), + label.0.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2) + )), + CodegenInstruction::JmpCC { code, label } => Node::leaf(format!( + "{} {:?} -> {}", + "JmpCC".truecolor(TEAL.0, TEAL.1, TEAL.2), + code, + label.0.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2) + )), + CodegenInstruction::SetCC { code, op } => Node::leaf(format!( + "{} {:?} {}", + "SetCC".truecolor(TEAL.0, TEAL.1, TEAL.2), + code, + operand_str(op) + )), + CodegenInstruction::Label(l) => Node::leaf(format!( + "{}({})", + "Label".truecolor(TEAL.0, TEAL.1, TEAL.2), + l.0.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2) + )), + CodegenInstruction::AllocateStack(off) => Node::leaf(format!( + "{} {}", + "AllocateStack".truecolor(TEAL.0, TEAL.1, TEAL.2), + off.to_string().truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) + )), + CodegenInstruction::Ret => Node::leaf("Ret".truecolor(TEAL.0, TEAL.1, TEAL.2).to_string()), + CodegenInstruction::DeallocateStack(off) => Node::leaf(format!( + "{} {}", + "DeallocateStack".truecolor(TEAL.0, TEAL.1, TEAL.2), + off.to_string().truecolor(CYAN_TEAL.0, CYAN_TEAL.1, CYAN_TEAL.2) + )), + CodegenInstruction::Push(op) => Node::leaf(format!( + "{} {}", + "Push".truecolor(TEAL.0, TEAL.1, TEAL.2), + operand_str(op) + )), + CodegenInstruction::Call(name) => Node::leaf(format!( + "{} {}", + "Call".truecolor(TEAL.0, TEAL.1, TEAL.2), + name.0.truecolor(YELLOW_GREEN.0, YELLOW_GREEN.1, YELLOW_GREEN.2) + )), } } }