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
//! Scope driven symbol tables
//!
use std;
use std::borrow::{Borrow, BorrowMut};
use std::cell::{RefMut, RefCell, Cell};
use std::collections::{HashSet, HashMap, VecDeque};
use std::convert::TryFrom;
use std::hash::{Hash, Hasher};

use serde::{Serialize, Serializer};
use serde::ser::{SerializeSeq};

use python_ast::fmt;

use ::compiler::graph::{DiGraph, Graph, Node};
use ::compiler::scope::ScopeHint::{BaseScope, ModuleScope, FunctionScope};
use ::compiler::scope::{ScopeNode, ScopeHint, ManageScope};
use ::api::result::Error;
use ::system::primitives::{Instr, Native};
use ::system::primitives as rs;
use ::runtime::OpCode;


pub trait TrackSymbol {
    fn use_symbol(&self, symbol: &Symbol) -> Result<(), Error>;
    fn define_symbol(&self, def: &Definition) -> Result<(), Error>;
}


#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug, Serialize)]
pub struct Symbol(pub String);

#[derive(Clone, Debug, Serialize)]
pub struct Definition(pub String, pub Native);


impl Ord for Definition {
    fn cmp(&self, rhs: &Self) -> std::cmp::Ordering {
        self.0.cmp(&rhs.0)
    }
}


impl Hash for Definition {
    fn hash<H: Hasher>(&self, state: &mut H) where H: Hasher{
        self.0.hash(state)
    }
}


impl Eq for Definition {}


impl PartialEq for Definition {
    fn eq(&self, rhs: &Self) -> bool {
        self.0.eq(&rhs.0)
    }
}


impl PartialOrd for Definition {
    fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> {
        self.0.partial_cmp(&rhs.0)
    }
}


impl<'a> TryFrom<&'a Native> for Symbol {
    type Error = Error;

    fn try_from(n: &Native) -> Result<Symbol, Error> {
        match n {
            &Native::Str(ref string) => Ok(Symbol(string.clone())),
            _ => Err(Error::system(&
                format!("Name types can only be created from Native::String variants, not {:?}; file: {}, line: {}", n, file!(), line!())))
        }
    }
}


impl<T> Serialize for SymIndex<T> where T: Serialize + Hash + Eq + Ord {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where
        S: Serializer {
        serializer.collect_seq(self.0.iter())
    }
}


#[derive(Debug, Clone)]
struct SymIndex<T>(HashMap<ScopeNode, RefCell<HashSet<T>>>) where T: Hash + Eq + Ord;


impl<T> SymIndex<T> where T: Hash + Eq + Ord {
    fn new () -> Self {
        SymIndex(HashMap::new())
    }

    fn get_or_create(&mut self, scope: &ScopeNode) -> RefMut<HashSet<T>> {
        if !self.0.contains_key(&scope) {
            self.0.insert(*scope, RefCell::new(HashSet::new()));
        }

        self.0[scope].borrow_mut()
    }
}

#[derive(Debug, Clone, Serialize)]
struct SymTable<T>(RefCell<SymIndex<T>>) where T: Hash + Eq + Ord;


impl<T> SymTable<T> where T: Clone + Hash + Eq + Ord {
    fn new() -> Self {
        SymTable(RefCell::new(SymIndex::new()))
    }

    fn index(&self) -> RefMut<SymIndex<T>> {
        self.0.borrow_mut()
    }

    fn add(&self, scope: &ScopeNode, value: &T) -> Result<(), Error> {
        let mut index: RefMut<SymIndex<T>> = self.index();
        let mut row: RefMut<HashSet<T>> = index.get_or_create(scope);
        row.insert((*value).clone());
        Ok(())
    }
}


#[derive(Debug, Clone, Serialize)]
pub struct SymbolMetadata {
    graph: DiGraph<ScopeNode>,
    curr_scope_id: Cell<usize>,
    definitions: SymTable<Definition>,
    usages: SymTable<Symbol>
}



impl SymbolMetadata {
    pub fn new() -> Self {
        SymbolMetadata {
            graph: DiGraph::new(ScopeNode::new(0, 0, BaseScope)),
            curr_scope_id: Cell::new(0),
            definitions: SymTable::new(),
            usages: SymTable::new()
        }
    }

    pub fn graph(&self) -> &Graph<Node=ScopeNode> {
        &self.graph
    }
}

impl TrackSymbol for SymbolMetadata {
    fn define_symbol(&self, symbol: &Definition) -> Result<(), Error> {
        let scope = self.current_scope();
        trace!("SymbolMetadata";
            "action" => "define_symbol",
            "scope" => format!("{:?}", scope),
            "symbol" => format!("{:?}", symbol));

        self.definitions.add(&scope, symbol)
    }

    fn use_symbol(&self, symbol: &Symbol) -> Result<(), Error> {
        let scope = self.current_scope();
        trace!("SymbolMetadata";
            "action" => "add_usage",
            "scope" => format!("{:?}", scope),
            "symbol" => format!("{:?}", symbol));

        self.usages.add(&scope, symbol)
    }
}


impl ManageScope for SymbolMetadata {

    fn current_scope(&self) -> Box<ScopeNode> {
        self.graph.get_node(self.curr_scope_id.get())
    }

    fn enter_scope(&self, hint: ScopeHint) {
        let parent = self.current_scope();

        let new_scope = ScopeNode::new(parent.id(), self.graph.count(), hint);

        trace!("SymbolMetadata";
        "action" => "enter_scope",
        "scope_hint" => format!("{:?}", hint),
        "prev_scope" => format!("{:?}", parent),
        "next_scope" => format!("{:?}", new_scope));

        self.curr_scope_id.set(new_scope.id());
        self.graph.add_node(new_scope)
    }

    fn exit_scope<T>(&self, result: T) -> T {
        let prev_scope = self.current_scope();
        self.curr_scope_id.set(prev_scope.parent_id());
        let next_scope = self.current_scope();

        trace!("SymbolMetadata";
        "action" => "exit_scope",
        "prev_scope" => format!("{:?}", prev_scope),
        "next_scope" => format!("{:?}", next_scope));
        result
    }
}