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
use crate::*;
use crate::syntax::block::Item;
use crate::syntax::block::escape_string;
use crate::syntax::block::constructors::*;
use crate::gen::schema::*;

use convert_case::{Case, Casing};

use lazy_static::lazy_static;

use preserves::value::Map;
use preserves::value::NestedValue;
use preserves::value::Value;

use super::CompilerConfig;
use super::names;
use super::types;

#[derive(Clone, Copy)]
pub enum ModuleContextMode {
    TargetIOValue,
    TargetAny,
}

pub struct ModuleContext<'m> {
    pub module_path: ModulePath,
    pub config: &'m CompilerConfig,
    pub literals: Map<_Any, String>,
    pub typedefs: Vec<Item>,
    pub functiondefs: Vec<Item>,
    pub mode: Option<ModuleContextMode>,
}

pub struct FunctionContext<'a, 'm> {
    pub error_context: String,
    pub m: &'a mut ModuleContext<'m>,
    pub temp_counter: usize,
    pub captures: Vec<Capture>,
    pub capture_mode: CaptureMode,
}

pub struct Capture {
    pub field_name: String,
    pub ty: types::TField,
    pub source_expr: String,
}

pub enum CaptureMode {
    Definite,
    Indefinite(Vec<Item>),
}

lazy_static! {
    static ref ID_RE: regex::Regex = regex::Regex::new(r"^[a-zA-Z][a-zA-Z_0-9]*$").unwrap();
}

impl<'m> ModuleContext<'m> {
    pub fn new(config: &'m CompilerConfig, module_path: &ModulePath) -> Self {
        ModuleContext {
            module_path: module_path.to_owned(),
            config: config,
            literals: Map::new(),
            typedefs: Vec::new(),
            functiondefs: Vec::new(),
            mode: None,
        }
    }

    pub fn define_literal(&mut self, v: &_Any) -> String {
        let prefix = format!("LIT_{}", self.literals.len());
        let next_id = match v.value() {
            Value::Boolean(b) => prefix + "_" + &b.to_string(),
            Value::Symbol(s) => if ID_RE.is_match(&s) { prefix + "_" + s } else { prefix },
            Value::String(s) => if ID_RE.is_match(&s) { prefix + "_" + s } else { prefix },
            Value::SignedInteger(n) => prefix + "_" + &n.to_string(),
            _ => prefix
        };
        let next_id = next_id.to_case(Case::UpperSnake);
        "&*".to_owned() + self.target_prefix() + "::" + self.literals.entry(v.clone()).or_insert(next_id)
    }

    pub fn define_type(&mut self, i: Item) {
        self.typedefs.push(i)
    }

    pub fn define_function<F: FnOnce(FunctionContext) -> Item>(&mut self, error_context: &str, f: F) {
        let i = f(FunctionContext::new(self, error_context));
        self.functiondefs.push(i)
    }

    pub fn render_ref(&self, r: &Ref) -> Item {
        match self.config.module_aliases.get(&r.module.0) {
            None =>
                if r.module.0.is_empty() {
                    item(r.name.to_owned())
                } else {
                    let mut items = Vec::new();
                    items.push(item(self.config.fully_qualified_module_prefix.to_owned()));
                    for p in &r.module.0 { items.push(item(names::render_modname(p))) }
                    items.push(item(r.name.to_owned()));
                    item(name(items))
                }
            Some(s) =>
                item(name![s.to_owned(), r.name.to_owned()])
        }
    }

    pub fn mode(&self) -> ModuleContextMode {
        self.mode.expect("defined ModuleContextMode")
    }

    pub fn target(&self) -> &'static str {
        match self.mode() {
            ModuleContextMode::TargetIOValue => "preserves::value::IOValue",
            ModuleContextMode::TargetAny => "_Any",
        }
    }

    pub fn target_prefix(&self) -> &'static str {
        match self.mode() {
            ModuleContextMode::TargetIOValue => "_io_",
            ModuleContextMode::TargetAny => "_any_",
        }
    }
}

impl<'a, 'm> FunctionContext<'a, 'm> {
    pub fn new(m: &'a mut ModuleContext<'m>, error_context: &str) -> Self {
        FunctionContext {
            error_context: error_context.to_owned(),
            m: m,
            temp_counter: 0,
            captures: Vec::new(),
            capture_mode: CaptureMode::Definite,
        }
    }

    pub fn capture(&mut self, field_name: String, ty: types::TField, source_expr: String) {
        self.captures.push(Capture {
            field_name: field_name,
            ty: ty,
            source_expr: match self.capture_mode {
                CaptureMode::Definite =>
                    source_expr,
                CaptureMode::Indefinite(_) =>
                    format!("{}.ok_or_else(|| {:?})?", source_expr, self.conformance_err_code()),
            }
        })
    }

    pub fn lookup_capture(&self, field_name: &str) -> &Capture {
        for c in &self.captures {
            if c.field_name == field_name {
                return c;
            }
        }
        panic!("No capture for field {:?} available", field_name)
    }

    pub fn gentempname(&mut self) -> String {
        let i = self.temp_counter;
        self.temp_counter += 1;
        format!("_tmp{}", i)
    }

    pub fn declare_compound(&self, body: &mut Vec<Item>, name: &str, init_expr: Item) {
        body.push(item(seq!["let mut ", name.to_owned(), " = ", init_expr, ";"]));
    }

    pub fn define_atom(&mut self, body: &mut Vec<Item>, name: &str, val_expr: Item) {
        body.push(match &mut self.capture_mode {
            CaptureMode::Definite => item(seq!["let ", name.to_owned(), " = ", val_expr, ";"]),
            CaptureMode::Indefinite(items) => {
                items.push(item(seq!["let mut ", name.to_owned(), " = None;"]));
                item(seq![name.to_owned(), " = Some(", val_expr, ");"])
            }
        })
    }

    pub fn with_indefinite_mode<F: FnOnce(&mut Self) -> ()>(&mut self, f: F) -> Vec<Item> {
        let saved_mode = std::mem::replace(&mut self.capture_mode, CaptureMode::Indefinite(Vec::new()));
        f(self);
        match std::mem::replace(&mut self.capture_mode, saved_mode) {
            CaptureMode::Definite => panic!("corrupt capture_mode"),
            CaptureMode::Indefinite(declarations) => declarations,
        }
    }

    pub fn branch<R, F: FnOnce(&mut Self) -> R>(&mut self, f: F) -> R {
        let saved_temp_counter = self.temp_counter;
        let saved_capture_count = self.captures.len();
        let result = f(self);
        self.temp_counter = saved_temp_counter;
        self.captures.truncate(saved_capture_count);
        result
    }

    pub fn err_code(&self) -> Item {
        return item(seq!["Err", parens![self.conformance_err_code()]]);
    }

    pub fn conformance_err_code(&self) -> Item {
        return item(seq!["_support::ParseError::conformance_error", parens![
            escape_string(&(self.m.module_path.0.join(".") + "." + &self.error_context))]]);
    }
}