From 9072e14686d0578b71e77426dd06c7270deb2267 Mon Sep 17 00:00:00 2001 From: T6 Date: Mon, 26 Feb 2024 09:33:03 -0500 Subject: [PATCH] add `Host::encode_tree` api, skipping intermediate `Def` representation (#64) --- src/host.rs | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/src/host.rs b/src/host.rs index 2edcd684..fe879034 100644 --- a/src/host.rs +++ b/src/host.rs @@ -3,7 +3,7 @@ use crate::{ ast::{Book, Net, Tree}, - run::{self, Addr, Def, Instruction, InterpretedDef, LabSet, Mode, Port, Tag, TrgId, Wire}, + run::{self, Addr, Def, Instruction, InterpretedDef, LabSet, Mode, Port, Tag, Trg, TrgId, Wire}, util::create_var, }; use std::{ @@ -102,6 +102,51 @@ impl Host { net } + + pub fn encode_tree(&self, net: &mut run::Net, trg: Trg, tree: &Tree) { + EncodeState { host: self, net, vars: Default::default() }.encode(trg, tree); + + struct EncodeState<'c, 'n, M: Mode> { + host: &'c Host, + net: &'c mut run::Net<'n, M>, + vars: HashMap<&'c str, Trg>, + } + + impl<'c, 'n, M: Mode> EncodeState<'c, 'n, M> { + fn encode(&mut self, trg: Trg, tree: &'c Tree) { + match tree { + Tree::Era => self.net.link_trg_port(trg, Port::ERA), + Tree::Num { val } => self.net.link_trg_port(trg, Port::new_num(*val)), + Tree::Ref { nam } => self.net.link_trg_port(trg, Port::new_ref(&self.host.defs[nam])), + Tree::Ctr { lab, lft, rgt } => { + let (l, r) = self.net.do_ctr(*lab, trg); + self.encode(l, lft); + self.encode(r, rgt); + } + Tree::Op2 { opr, lft, rgt } => { + let (l, r) = self.net.do_op2(*opr, trg); + self.encode(l, lft); + self.encode(r, rgt); + } + Tree::Op1 { opr, lft, rgt } => { + let r = self.net.do_op1(*opr, *lft, trg); + self.encode(r, rgt); + } + Tree::Mat { sel, ret } => { + let (s, r) = self.net.do_mat(trg); + self.encode(s, sel); + self.encode(r, ret); + } + Tree::Var { nam } => match self.vars.entry(nam) { + Entry::Occupied(e) => self.net.link_trg(e.remove(), trg), + Entry::Vacant(e) => { + e.insert(trg); + } + }, + } + } + } + } } /// See [`Host::readback`].