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