Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::iter::Iterator;
- use std::collections::HashMap;
- /// My attempt at abstracting it into a seperate struct
- #[derive(Clone, Debug, PartialEq)]
- pub struct StandartValuedHashMap<K, V> where
- K: std::clone::Clone + std::fmt::Debug + std::cmp::Eq + std::hash::Hash + std::cmp::PartialEq,
- V: std::clone::Clone + std::fmt::Debug + std::cmp::Eq + std::cmp::PartialEq {
- hashmap: HashMap<K, V>,
- pub generator: Box<Iterator<Item=V>>
- }
- impl<K, V> StandartValuedHashMap<K, V> where
- K: std::clone::Clone + std::fmt::Debug + std::cmp::Eq + std::hash::Hash + std::cmp::PartialEq,
- V: std::clone::Clone + std::fmt::Debug + std::cmp::Eq + std::cmp::PartialEq {
- pub fn new(generator: Box<Iterator<Item=V>>) -> Self {
- let hashmap = HashMap::new();
- StandartValuedHashMap{hashmap, generator}
- }
- pub fn get(&mut self, key: K) -> &V {
- let key2 = key.clone();
- if self.hashmap.get(&key).is_none() {
- self.hashmap.insert(key, self.generator.next().unwrap());
- }
- self.hashmap.get(&key2).unwrap()
- }
- }
- // Original attempts
- pub struct Translator {
- // Tokenizer is an iterator for later use
- /// source Token stream
- source: Tokenizer,
- /// Number(!) of registers in target program
- ramend: usize,
- /// Jump marker identifier generator
- jmp_id_gen: Box<Iterator<Item=String>>,
- /// Instruction operand identifier generator
- inst_id_gen: Box<Iterator<Item=String>>,
- // Mapping the original identifiers to the translated ones
- global_scope: HashMap<String, String>
- }
- impl Translator {
- pub fn new(source: Tokenizer) -> Self {
- let ramend = 0;
- let inst_id_gen = (0..0).map(|n| n.to_string());
- let inst_id_gen = Box::new(inst_id_gen);
- // all single ascii letters; lowercase alphabet followed by uppercase alphabet
- let jmp_id_gen = ASCII_LOWER.iter().chain(ASCII_UPPER.iter()).map(|c| c.to_string());
- let jmp_id_gen = Box::new(jmp_id_gen);
- let global_scope = HashMap::new();
- Translator{source, ramend, jmp_id_gen, inst_id_gen, global_scope}
- }
- /// Set the instruction operator identifier generator to use a given ramend
- fn set_inst_id_gen(&mut self, ramend: usize) {
- // numbers from ramend-1 to 1
- let inst_id_gen = (0..ramend).map(|n| n.to_string()).rev();
- self.ramend = ramend;
- self.inst_id_gen = Box::new(inst_id_gen);
- }
- // attempt 2
- fn instruction_operand(&mut self, index: String) -> String {
- let key = index.clone();
- self.global_scope.entry(index).or_insert_with(|| self.inst_id_gen.next().unwrap());
- self.global_scope.get(&key).unwrap().to_string()
- }
- // attempt 1
- fn jump_marker(&mut self, index: String) -> String {
- match self.global_scope.get(&index) {
- Some(id) => id.to_string(),
- None => {
- self.global_scope.insert(
- index, self.jmp_id_gen.next().unwrap());
- self.global_scope.get(&index).unwrap().to_string()
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement