|
| 1 | +use crate::compiler::Compiler; |
| 2 | +use crate::errors::{Severity, SourceError}; |
| 3 | +use crate::parser::{AstNode, NodeId}; |
| 4 | +use nu_protocol::ast::{Math, Operator}; |
| 5 | +use nu_protocol::ir::{Instruction, IrBlock, Literal}; |
| 6 | +use nu_protocol::{RegId, Span}; |
| 7 | + |
| 8 | +/// Generates IR (Intermediate Representation) from nu AST. |
| 9 | +pub struct IrGenerator<'a> { |
| 10 | + // Immutable reference to a compiler after the typechecker pass |
| 11 | + compiler: &'a Compiler, |
| 12 | + errors: Vec<SourceError>, |
| 13 | + block: IrBlock, |
| 14 | +} |
| 15 | + |
| 16 | +impl<'a> IrGenerator<'a> { |
| 17 | + pub fn new(compiler: &'a Compiler) -> Self { |
| 18 | + Self { |
| 19 | + compiler, |
| 20 | + errors: Default::default(), |
| 21 | + block: IrBlock { |
| 22 | + instructions: Default::default(), |
| 23 | + spans: Default::default(), |
| 24 | + data: Default::default(), |
| 25 | + ast: Default::default(), |
| 26 | + comments: Default::default(), |
| 27 | + register_count: 0, |
| 28 | + file_count: 0, |
| 29 | + }, |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + /// Generates the IR from the given state of the compiler. |
| 34 | + /// After this is called, use `block` and `errors` to get the result. |
| 35 | + pub fn generate(&mut self) { |
| 36 | + if self.compiler.ast_nodes.is_empty() { |
| 37 | + return; |
| 38 | + } |
| 39 | + let node_id = NodeId(self.compiler.ast_nodes.len() - 1); |
| 40 | + let Some(reg) = self.generate_node(node_id) else { |
| 41 | + return; |
| 42 | + }; |
| 43 | + self.add_instruction(node_id, Instruction::Return { src: reg }); |
| 44 | + } |
| 45 | + |
| 46 | + /// Returns generated IR block. |
| 47 | + /// |
| 48 | + /// Call `generate` before using this method and ensure there are no errors. |
| 49 | + pub fn block(self) -> IrBlock { |
| 50 | + self.block |
| 51 | + } |
| 52 | + |
| 53 | + /// Returns errors encountered during IR generation step. |
| 54 | + /// |
| 55 | + /// Call `generate` before using this method. |
| 56 | + pub fn errors(&self) -> &Vec<SourceError> { |
| 57 | + &self.errors |
| 58 | + } |
| 59 | + |
| 60 | + /// Prints the internal state to standard output. |
| 61 | + pub fn print(&self) { |
| 62 | + let output = self.display_state(); |
| 63 | + print!("{output}"); |
| 64 | + } |
| 65 | + |
| 66 | + /// Displays the state of the IR generator. |
| 67 | + /// The output can be used for human debugging and for snapshot tests. |
| 68 | + pub fn display_state(&self) -> String { |
| 69 | + let mut result = String::new(); |
| 70 | + result.push_str("==== IR ====\n"); |
| 71 | + result.push_str(&format!("register_count: {}\n", self.block.register_count)); |
| 72 | + result.push_str(&format!("file_count: {}\n", self.block.file_count)); |
| 73 | + |
| 74 | + for (idx, instruction) in self.block.instructions.iter().enumerate() { |
| 75 | + result.push_str(&format!("{}: {:?}\n", idx, instruction)); |
| 76 | + } |
| 77 | + |
| 78 | + if !self.errors.is_empty() { |
| 79 | + result.push_str("==== IR ERRORS ====\n"); |
| 80 | + for error in &self.errors { |
| 81 | + result.push_str(&format!( |
| 82 | + "{:?} (NodeId {}): {}\n", |
| 83 | + error.severity, error.node_id.0, error.message |
| 84 | + )); |
| 85 | + } |
| 86 | + } |
| 87 | + result |
| 88 | + } |
| 89 | + |
| 90 | + // Returns unused register. |
| 91 | + fn next_register(&mut self) -> RegId { |
| 92 | + let r = RegId::new(self.block.register_count); |
| 93 | + self.block.register_count += 1; |
| 94 | + r |
| 95 | + } |
| 96 | + |
| 97 | + fn generate_node(&mut self, node_id: NodeId) -> Option<RegId> { |
| 98 | + let ast_node = &self.compiler.ast_nodes[node_id.0]; |
| 99 | + match ast_node { |
| 100 | + AstNode::Int => { |
| 101 | + let next_reg = self.next_register(); |
| 102 | + let val = self.compiler.node_as_i64(node_id); |
| 103 | + self.add_instruction( |
| 104 | + node_id, |
| 105 | + Instruction::LoadLiteral { |
| 106 | + dst: next_reg, |
| 107 | + lit: Literal::Int(val), |
| 108 | + }, |
| 109 | + ); |
| 110 | + Some(next_reg) |
| 111 | + } |
| 112 | + AstNode::Block(block_id) => { |
| 113 | + let block = &self.compiler.blocks[block_id.0]; |
| 114 | + let mut last = None; |
| 115 | + for id in &block.nodes { |
| 116 | + last = self.generate_node(*id); |
| 117 | + last?; |
| 118 | + } |
| 119 | + last |
| 120 | + } |
| 121 | + AstNode::BinaryOp { lhs, op, rhs } => { |
| 122 | + let l = self.generate_node(*lhs)?; |
| 123 | + let r = self.generate_node(*rhs)?; |
| 124 | + let o = self.node_to_operator(*op)?; |
| 125 | + self.add_instruction( |
| 126 | + node_id, |
| 127 | + Instruction::BinaryOp { |
| 128 | + lhs_dst: l, |
| 129 | + op: o, |
| 130 | + rhs: r, |
| 131 | + }, |
| 132 | + ); |
| 133 | + Some(l) |
| 134 | + } |
| 135 | + _ => { |
| 136 | + self.error(format!("node {:?} not suported yet", ast_node), node_id); |
| 137 | + None |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + fn add_instruction(&mut self, node_id: NodeId, instruction: Instruction) { |
| 143 | + let span = self.compiler.get_span(node_id); |
| 144 | + self.block.spans.push(Span { |
| 145 | + start: span.start, |
| 146 | + end: span.end, |
| 147 | + }); |
| 148 | + self.block.ast.push(None); |
| 149 | + self.block.instructions.push(instruction); |
| 150 | + } |
| 151 | + |
| 152 | + fn node_to_operator(&mut self, node_id: NodeId) -> Option<Operator> { |
| 153 | + match self.compiler.get_node(node_id) { |
| 154 | + AstNode::Plus => Some(Operator::Math(Math::Plus)), |
| 155 | + AstNode::Multiply => Some(Operator::Math(Math::Multiply)), |
| 156 | + node => { |
| 157 | + self.error(format!("unrecognized operator {:?}", node), node_id); |
| 158 | + None |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + fn error(&mut self, message: impl Into<String>, node_id: NodeId) { |
| 164 | + self.errors.push(SourceError { |
| 165 | + message: message.into(), |
| 166 | + node_id, |
| 167 | + severity: Severity::Error, |
| 168 | + }); |
| 169 | + } |
| 170 | +} |
0 commit comments