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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use crate::*;
use Instruction::{DataOp, ForNext, ForSortNext, Jump, JumpIfFalse};

/// Holds function name, line, column and message.
#[derive(Clone)]
pub(crate) struct SqlError {
    pub rname: String,
    pub line: usize,
    pub column: usize,
    pub msg: String,
}
/// Table Expression ( not yet type-checked or compiled against database ).
pub enum TableExpression {
    // Select( SelectExpression ),
    ///
    Base(ObjRef),
    ///
    Values(Vec<Vec<Expr>>),
}
/// Assign or Append.
#[derive(Clone, Copy)]
#[non_exhaustive]
pub enum AssignOp {
    ///
    Assign,
    ///
    Append,
}
/// Vector of local variable numbers and AssignOp( assign or append ).
pub type Assigns = Vec<(usize, AssignOp)>;

/// Select Expression ( not yet compiled ).
#[non_exhaustive]
pub struct SelectExpression {
    ///
    pub colnames: Vec<String>,
    ///
    pub assigns: Assigns,
    ///
    pub exps: Vec<Expr>,
    ///
    pub from: Option<Box<TableExpression>>,
    ///
    pub wher: Option<Expr>,
    ///
    pub orderby: Vec<(Expr, bool)>,
}

/// Parsing token.
#[derive(Debug, PartialEq, PartialOrd, Clone, Copy)]
pub enum Token {
    /* Note: order is significant */
    ///
    Less,
    ///
    LessEqual,
    ///
    GreaterEqual,
    ///
    Greater,
    ///
    Equal,
    ///
    NotEqual,
    ///
    In,
    ///
    Plus,
    ///
    Minus,
    ///
    Times,
    ///
    Divide,
    ///
    Percent,
    ///
    VBar,
    ///
    And,
    ///
    Or,
    ///
    VBarEqual,
    ///
    Id,
    ///
    Number,
    ///
    Hex,
    ///
    String,
    ///
    LBra,
    ///
    RBra,
    ///
    Comma,
    ///
    Colon,
    ///
    Dot,
    ///
    Exclamation,
    ///
    Unknown,
    ///
    EndOfFile,
}

impl Token {
    ///
    pub fn precedence(self) -> i8 {
        const PA: [i8; 15] = [10, 10, 10, 10, 10, 10, 10, 20, 20, 30, 30, 30, 15, 8, 5];
        PA[self as usize]
    }
}

/// Scalar Expression (uncompiled).
#[non_exhaustive]
pub struct Expr {
    ///
    pub exp: ExprIs,
    ///
    pub data_type: DataType,
    /// Doesn't depend on FROM clause.
    pub is_constant: bool,
    /// Has been type-checked.
    pub checked: bool,
    ///
    pub col: usize,
}

impl Expr {
    ///
    pub fn new(exp: ExprIs) -> Self {
        Expr {
            exp,
            data_type: NONE,
            is_constant: false,
            checked: false,
            col: 0,
        }
    }
}

/// Scalar Expression variants.
#[non_exhaustive]
pub enum ExprIs {
    ///
    Const(Value),
    ///
    Local(usize),
    ///
    ColName(String),
    ///
    Binary(Token, Box<Expr>, Box<Expr>),
    ///
    Not(Box<Expr>),
    ///
    Minus(Box<Expr>),
    ///
    Case(Vec<(Expr, Expr)>, Box<Expr>),
    ///
    FuncCall(ObjRef, Vec<Expr>),
    ///
    BuiltinCall(String, Vec<Expr>),
    ///
    ScalarSelect(Box<SelectExpression>),
    ///
    List(Vec<Expr>),
}

/// Object reference ( Schema.Name ).
#[derive(PartialEq, PartialOrd, Eq, Hash, Clone)]
#[non_exhaustive]
pub struct ObjRef {
    ///
    pub schema: String,
    ///
    pub name: String,
}

impl ObjRef {
    /// Construct from string references.
    pub fn new(s: &str, n: &str) -> Self {
        Self {
            schema: s.to_string(),
            name: n.to_string(),
        }
    }
    /// Used for error messages.
    pub fn str(&self) -> String {
        format!("[{}].[{}]", &self.schema, &self.name)
    }
}

/// Binary=1, String=2, Int=3, Float=4, Bool=5.
#[derive(Debug, PartialEq, PartialOrd, Clone, Copy)]
#[non_exhaustive]
pub enum DataKind {
    ///
    None = 0,
    ///
    Binary = 1,
    ///
    String = 2,
    ///
    Int = 3,
    ///
    Float = 4,
    ///
    Bool = 5,
}

/// Low 3 (KBITS) bits are DataKind, rest is size in bytes.
pub type DataType = usize;

pub(crate) const KBITS: usize = 3;
pub(crate) const NONE: DataType = DataKind::None as usize;
pub(crate) const BINARY: DataType = DataKind::Binary as usize + (16 << KBITS);
pub(crate) const STRING: DataType = DataKind::String as usize + (16 << KBITS);
pub(crate) const NAMESTR: DataType = DataKind::String as usize + (32 << KBITS);
pub(crate) const BIGSTR: DataType = DataKind::String as usize + (250 << KBITS);
pub(crate) const INT: DataType = DataKind::Int as usize + (8 << KBITS);
pub(crate) const FLOAT: DataType = DataKind::Float as usize + (4 << KBITS);
pub(crate) const DOUBLE: DataType = DataKind::Float as usize + (8 << KBITS);
pub(crate) const BOOL: DataType = DataKind::Bool as usize + (1 << KBITS);

/// Compute the DataKind of a DataType.
pub fn data_kind(x: DataType) -> DataKind {
    const DKLOOK: [DataKind; 6] = [
        DataKind::None,
        DataKind::Binary,
        DataKind::String,
        DataKind::Int,
        DataKind::Float,
        DataKind::Bool,
    ];
    DKLOOK[x % (1 << KBITS)]
}

/// Compute the number of bytes required to store a value of the specified DataType.
#[must_use]
pub fn data_size(x: DataType) -> usize {
    x >> KBITS
}

/// Compilation block ( body of function or batch section ).
pub struct Block<'a> {
    ///
    pub param_count: usize,
    ///
    pub return_type: DataType,
    ///
    pub local_typ: Vec<DataType>,
    ///
    pub ilist: Vec<Instruction>,
    ///
    pub break_id: usize,
    /// Database.
    pub db: DB,
    /// Current table in scope by FROM clause( or UPDATE statment ).
    pub from: Option<CTableExpression>,
    ///
    pub parse_only: bool,
    jumps: Vec<usize>,
    labels: HashMap<&'a [u8], usize>,
    local_map: HashMap<&'a [u8], usize>,
    locals: Vec<&'a [u8]>,
}

impl<'a> Block<'a> {
    /// Construct a new block.
    pub fn new(db: DB) -> Self {
        Block {
            ilist: Vec::new(),
            jumps: Vec::new(),
            labels: HashMap::default(),
            local_map: HashMap::default(),
            locals: Vec::new(),
            local_typ: Vec::new(),
            break_id: 0,
            param_count: 0,
            return_type: NONE,
            from: None,
            db,
            parse_only: false,
        }
    }

    /// Check labels are all defined and patch jump instructions.
    pub fn resolve_jumps(&mut self) {
        for (k, v) in &self.labels {
            if self.jumps[*v] == usize::MAX {
                panic!("undefined label: {}", parse::tos(k));
            }
        }
        for i in &mut self.ilist {
            match i {
                JumpIfFalse(x, _) | Jump(x) | ForNext(x, _) | ForSortNext(x, _) => {
                    *x = self.jumps[*x]
                }
                _ => {}
            }
        }
    }

    /// Add an instruction to the instruction list.
    pub fn add(&mut self, s: Instruction) {
        if !self.parse_only {
            self.ilist.push(s);
        }
    }

    /// Add a Data Operation (DO) to the instruction list.
    pub fn dop(&mut self, dop: DO) {
        if !self.parse_only {
            self.add(DataOp(Box::new(dop)));
        }
    }

    /// Check the parameter kinds match the function.
    pub fn check_types(&self, r: &Rc<Function>, pkinds: &[DataKind]) {
        if pkinds.len() != r.param_count {
            panic!("param count mismatch");
        }
        for (i, pk) in pkinds.iter().enumerate() {
            let ft = data_kind(r.local_typ[i]);
            let et = *pk;
            if ft != et {
                panic!("param type mismatch expected {:?} got {:?}", ft, et);
            }
        }
    }

    // Helper functions for other statements.

    /// Define a local variable ( parameter or declared ).
    pub fn def_local(&mut self, name: &'a [u8], dt: DataType) {
        let local_id = self.local_typ.len();
        self.local_typ.push(dt);
        self.locals.push(name);
        if self.local_map.contains_key(name) {
            panic!("duplicate variable name");
        }
        self.local_map.insert(name, local_id);
    }

    /// Get the number of a local variable from a name.
    pub fn get_local(&self, name: &[u8]) -> Option<&usize> {
        self.local_map.get(name)
    }

    /// Get the name of a local variable from a number.
    pub fn local_name(&self, num: usize) -> &[u8] {
        self.locals[num]
    }

    /// Get a local jump id.
    pub fn get_jump_id(&mut self) -> usize {
        let result = self.jumps.len();
        self.jumps.push(usize::MAX);
        result
    }

    /// Set instruction location of jump id.
    pub fn set_jump(&mut self, jump_id: usize) {
        self.jumps[jump_id] = self.ilist.len();
    }

    /// Get a local jump id to current location.
    pub fn get_loop_id(&mut self) -> usize {
        let result = self.get_jump_id();
        self.set_jump(result);
        result
    }

    /// Get a number for a local goto label.
    pub fn get_goto_label(&mut self, s: &'a [u8]) -> usize {
        if let Some(jump_id) = self.labels.get(s) {
            *jump_id
        } else {
            let jump_id = self.get_jump_id();
            self.labels.insert(s, jump_id);
            jump_id
        }
    }

    /// Set the local for a local goto lable.
    pub fn set_goto_label(&mut self, s: &'a [u8]) {
        if let Some(jump_id) = self.labels.get(s) {
            let j = *jump_id;
            if self.jumps[j] != usize::MAX {
                panic!("label already set");
            }
            self.set_jump(j);
        } else {
            let jump_id = self.get_loop_id();
            self.labels.insert(s, jump_id);
        }
    }

    /// Get the DataKind of an expression.
    pub fn kind(&self, e: &mut Expr) -> DataKind {
        compile::c_check(self, e);
        data_kind(e.data_type)
    }
}