1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
use crate::binary_parser_types::SYSTEM_SYMBOL_TABLE;
use log::trace;
use std::collections::HashMap;

/// A table symbol. It can b used together with the "with_shared_table" method
/// in order to define new shared tables.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Symbol {
    Symbol(String),
    Dummy,
}

#[derive(Eq, PartialEq, Debug)]
pub struct LocalSymbolTable(Vec<Symbol>);

impl LocalSymbolTable {
    pub fn new() -> LocalSymbolTable {
        LocalSymbolTable(
            SYSTEM_SYMBOL_TABLE
                .to_vec()
                .iter()
                .map(|s| Symbol::Symbol(s.to_string()))
                .collect(),
        )
    }

    pub fn add_symbol(&mut self, symbol: Symbol) -> usize {
        let id = self.0.len();
        self.0.push(symbol);
        id
    }

    pub fn add_symbols(&mut self, slice: &[Symbol]) {
        for symbol in slice {
            self.add_symbol(symbol.clone());
        }
    }

    pub fn get_symbol_by_id(&self, id: usize) -> Option<&Symbol> {
        self.0.get(id)
    }

    pub fn get_id_by_symbol(&self, symbol: &str) -> Option<usize> {
        match self.0.iter().enumerate().find(|(_, value)| {
            if let Symbol::Symbol(value) = value {
                *value == symbol
            } else {
                false
            }
        }) {
            Some(value) => Some(value.0),
            None => None,
        }
    }

    pub fn insert_dummy_symbols(&mut self, max_len: usize) {
        for _ in 0..max_len {
            self.add_symbol(Symbol::Dummy);
        }
    }

    pub fn list_all_symbols(&self) -> &[Symbol] {
        &self.0
    }
}

#[derive(Debug)]
pub struct SharedSymbolTable {
    name: String,
    version: u32,
    symbols: Vec<Symbol>,
}

impl SharedSymbolTable {
    pub fn is_superset(&self, table: &SharedSymbolTable) -> bool {
        for (index, symbol) in table.symbols.iter().enumerate() {
            match self.symbols.get(index) {
                Some(ref value) if *value == symbol => {}
                _ => {
                    return false;
                }
            }
        }

        true
    }

    pub fn get_symbols_max_len(&self, max_len: usize) -> &[Symbol] {
        if max_len > self.symbols.len() {
            return &self.symbols;
        }

        self.symbols.split_at(max_len).0
    }

    pub fn get_all_symbols(&self) -> &[Symbol] {
        &self.symbols
    }
}

#[derive(Debug)]
pub struct Import {
    pub(crate) name: String,
    pub(crate) version: Option<u32>,
    pub(crate) max_len: Option<usize>,
}

/// Errors that can happen related with the Symbol Table.
#[derive(Eq, PartialEq, Debug)]
pub enum SymbolContextError {
    TableVersionAlreadyThere,
    MaxIdNeededWhenImportingASharedTableWhereVersionIsNotAvailable,
    MaxIdNeededWhenImportingANotFoundSharedTable,
    InternalParserErrorThisIsABug,
    NewTableIsNotSuperSetOfPrevious,
}

#[derive(Debug)]
pub struct SymbolContext {
    current_table: LocalSymbolTable,
    shared_tables: HashMap<String, (u32, HashMap<u32, SharedSymbolTable>)>,
}

impl SymbolContext {
    pub fn new() -> SymbolContext {
        SymbolContext {
            current_table: LocalSymbolTable::new(),
            shared_tables: HashMap::new(),
        }
    }

    pub fn set_new_table_from_current(&mut self, symbols: Vec<Symbol>) {
        for symbol in symbols.into_iter() {
            self.current_table.add_symbol(symbol);
        }
    }

    pub fn add_shared_table(
        &mut self,
        name: String,
        version: u32,
        symbols: &[Symbol],
    ) -> Result<(), SymbolContextError> {
        let new_table = SharedSymbolTable {
            name: name.clone(),
            version,
            symbols: symbols.to_vec(),
        };

        match self.shared_tables.get_mut(&name) {
            Some(table_collection) => match table_collection.1.get_mut(&version) {
                Some(_) => Err(SymbolContextError::TableVersionAlreadyThere),
                None => {
                    SymbolContext::assert_new_table_is_superset(
                        &new_table,
                        &version,
                        &table_collection.1,
                    )?;

                    if table_collection.0 < version {
                        table_collection.0 = version;
                    }

                    trace!("New shared table imported {:?}", new_table);

                    table_collection.1.insert(version, new_table);
                    Ok(())
                }
            },
            None => {
                trace!("New shared table imported {:?}", new_table);

                let mut new_hashmap = HashMap::new();
                new_hashmap.insert(version, new_table);
                let new_tuple = (version, new_hashmap);
                self.shared_tables.insert(name, new_tuple);

                Ok(())
            }
        }
    }

    pub fn assert_new_table_is_superset(
        table: &SharedSymbolTable,
        version: &u32,
        tables: &HashMap<u32, SharedSymbolTable>,
    ) -> Result<(), SymbolContextError> {
        for index in (*version - 1)..=0 {
            if let Some(existing_table) = tables.get(&index) {
                if !table.is_superset(existing_table) {
                    return Err(SymbolContextError::NewTableIsNotSuperSetOfPrevious);
                } else {
                    return Ok(());
                }
            }
        }

        Ok(())
    }

    pub fn set_new_table(
        &mut self,
        imports: &[Import],
        symbols: &[Symbol],
    ) -> Result<(), SymbolContextError> {
        let mut new_table = LocalSymbolTable::new();

        let symbols: Vec<Symbol> = symbols.to_vec();

        for import in imports {
            if import.name == "$ion" {
                continue;
            }

            let version = if let Some(version) = import.version {
                std::cmp::max(1, version)
            } else {
                1
            };

            match self.shared_tables.get(&import.name) {
                Some(table_collection) => match table_collection.1.get(&version) {
                    Some(table) => {
                        let symbols = match import.max_len {
                            Some(len) => table.get_symbols_max_len(len),
                            None => table.get_all_symbols(),
                        };

                        new_table.add_symbols(symbols);
                    }
                    None => {
                        if let Some(max_len) = import.max_len {
                            let table = match table_collection.1.get(&table_collection.0) {
                                Some(table) => table,
                                None => {
                                    return Err(SymbolContextError::InternalParserErrorThisIsABug)
                                }
                            };

                            let symbols = table.get_symbols_max_len(max_len);
                            new_table.add_symbols(symbols);
                        } else {
                            return Err(SymbolContextError::MaxIdNeededWhenImportingASharedTableWhereVersionIsNotAvailable);
                        }
                    }
                },
                None => {
                    if let Some(len) = import.max_len {
                        new_table.insert_dummy_symbols(len);
                    } else {
                        return Err(
                            SymbolContextError::MaxIdNeededWhenImportingANotFoundSharedTable,
                        );
                    }
                }
            }
        }

        new_table.add_symbols(&symbols);

        trace!(
            "New local table importing {:?} resulting in: {:?}",
            imports,
            new_table
        );

        self.current_table = new_table;

        Ok(())
    }

    pub fn get_symbol_by_id(&self, id: usize) -> Option<&Symbol> {
        self.current_table.get_symbol_by_id(id)
    }

    pub fn insert_symbol(&mut self, symbol: &str) -> usize {
        match self.current_table.get_id_by_symbol(symbol) {
            Some(id) => id,
            None => self
                .current_table
                .add_symbol(Symbol::Symbol(symbol.to_string())),
        }
    }

    pub fn dump_all_local_symbols(&self) -> Vec<String> {
        self.current_table.list_all_symbols()[10..]
            .iter()
            .map(|s| match s {
                Symbol::Symbol(name) => name.clone(),
                _ => "".to_string(),
            })
            .collect()
    }
}

impl Default for SymbolContext {
    fn default() -> Self {
        Self::new()
    }
}