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
410
411
412
413
414
415
416
417
418
419
use crate::{
    c_int, c_value, Block, BuiltinMap, CExp, CExpPtr, CompileFunc, DataKind, EvalEnv, Expr, Rc,
    Value,
};

/// Add builtin functions to specified [BuiltinMap].
pub fn standard_builtins(map: &mut BuiltinMap) {
    let list = [
        ("ARG", DataKind::String, CompileFunc::Value(c_arg)),
        ("HEADER", DataKind::Int, CompileFunc::Int(c_header)),
        ("STATUSCODE", DataKind::Int, CompileFunc::Int(c_status_code)),
        ("FILEATTR", DataKind::String, CompileFunc::Value(c_fileattr)),
        (
            "FILECONTENT",
            DataKind::Binary,
            CompileFunc::Value(c_filecontent),
        ),
        ("GLOBAL", DataKind::Int, CompileFunc::Int(c_global)),
        ("REPLACE", DataKind::String, CompileFunc::Value(c_replace)),
        (
            "SUBSTRING",
            DataKind::String,
            CompileFunc::Value(c_substring),
        ),
        (
            "BINSUBSTRING",
            DataKind::Binary,
            CompileFunc::Value(c_binsubstring),
        ),
        ("LEN", DataKind::Int, CompileFunc::Int(c_len)),
        ("BINLEN", DataKind::Int, CompileFunc::Int(c_bin_len)),
        ("PARSEINT", DataKind::Int, CompileFunc::Int(c_parse_int)),
        (
            "PARSEFLOAT",
            DataKind::Float,
            CompileFunc::Float(c_parse_float),
        ),
        (
            "EXCEPTION",
            DataKind::String,
            CompileFunc::Value(c_exception),
        ),
        ("LASTID", DataKind::Int, CompileFunc::Int(c_lastid)),
        #[cfg(feature = "pack")]
        ("REPACKFILE", DataKind::Int, CompileFunc::Int(c_repackfile)),
        #[cfg(feature = "verify")]
        ("VERIFYDB", DataKind::String, CompileFunc::Value(c_verifydb)),
    ];
    for (name, typ, cf) in list {
        map.insert(name.to_string(), (typ, cf));
    }
}
/// Check number and kinds of arguments.
pub fn check_types(b: &Block, args: &mut [Expr], dk: &[DataKind]) {
    if args.len() != dk.len() {
        panic!("wrong number of args");
    }
    for (i, e) in args.iter_mut().enumerate() {
        let k = b.kind(e);
        if k != dk[i] {
            panic!(
                "Builtin function arg {} type mismatch expected {:?} got {:?}",
                i + 1,
                dk[i],
                k
            );
        }
    }
}
/////////////////////////////
/// Compile call to EXCEPTION().
fn c_exception(b: &Block, args: &mut [Expr]) -> CExpPtr<Value> {
    check_types(b, args, &[]);
    Box::new(Exception {})
}
struct Exception {}
impl CExp<Value> for Exception {
    fn eval(&self, e: &mut EvalEnv, _d: &[u8]) -> Value {
        let err = e.tr.get_error();
        Value::String(Rc::new(err))
    }
}
/////////////////////////////
/// Compile call to LEN.
fn c_len(b: &Block, args: &mut [Expr]) -> CExpPtr<i64> {
    check_types(b, args, &[DataKind::String]);
    let s = c_value(b, &mut args[0]);
    Box::new(Len { s })
}
struct Len {
    s: CExpPtr<Value>,
}
impl CExp<i64> for Len {
    fn eval(&self, e: &mut EvalEnv, d: &[u8]) -> i64 {
        let s = self.s.eval(e, d).str();
        s.len() as i64
    }
}
/////////////////////////////
/// Compile call to BINLEN.
fn c_bin_len(b: &Block, args: &mut [Expr]) -> CExpPtr<i64> {
    check_types(b, args, &[DataKind::Binary]);
    let bv = c_value(b, &mut args[0]);
    Box::new(BinLen { bv })
}
struct BinLen {
    bv: CExpPtr<Value>,
}
impl CExp<i64> for BinLen {
    fn eval(&self, e: &mut EvalEnv, d: &[u8]) -> i64 {
        let x = self.bv.eval(e, d);
        match x {
            Value::RcBinary(xx) => xx.len() as i64,
            Value::ArcBinary(xx) => xx.len() as i64,
            _ => panic!(),
        }
    }
}
/////////////////////////////
/// Compile call to LASTID.
fn c_lastid(b: &Block, args: &mut [Expr]) -> CExpPtr<i64> {
    check_types(b, args, &[]);
    Box::new(LastId {})
}
struct LastId {}
impl CExp<i64> for LastId {
    fn eval(&self, ee: &mut EvalEnv, _d: &[u8]) -> i64 {
        ee.db.lastid.get()
    }
}
/////////////////////////////
/// Compile call to GLOBAL.
fn c_global(b: &Block, args: &mut [Expr]) -> CExpPtr<i64> {
    check_types(b, args, &[DataKind::Int]);
    let x = c_int(b, &mut args[0]);
    Box::new(Global { x })
}
struct Global {
    x: CExpPtr<i64>,
}
impl CExp<i64> for Global {
    fn eval(&self, ee: &mut EvalEnv, d: &[u8]) -> i64 {
        let x = self.x.eval(ee, d);
        ee.tr.global(x)
    }
}
/////////////////////////////
/// Compile call to PARSEINT.
fn c_parse_int(b: &Block, args: &mut [Expr]) -> CExpPtr<i64> {
    check_types(b, args, &[DataKind::String]);
    let s = c_value(b, &mut args[0]);
    Box::new(ParseInt { s })
}
struct ParseInt {
    s: CExpPtr<Value>,
}
impl CExp<i64> for ParseInt {
    fn eval(&self, e: &mut EvalEnv, d: &[u8]) -> i64 {
        let s = self.s.eval(e, d).str();
        s.parse().unwrap()
    }
}
/////////////////////////////
/// Compile call to PARSEFLOAT.
fn c_parse_float(b: &Block, args: &mut [Expr]) -> CExpPtr<f64> {
    check_types(b, args, &[DataKind::String]);
    let s = c_value(b, &mut args[0]);
    Box::new(ParseFloat { s })
}
struct ParseFloat {
    s: CExpPtr<Value>,
}
impl CExp<f64> for ParseFloat {
    fn eval(&self, e: &mut EvalEnv, d: &[u8]) -> f64 {
        let s = self.s.eval(e, d).str();
        s.parse().unwrap()
    }
}
/////////////////////////////
/// Compile call to REPLACE.
fn c_replace(b: &Block, args: &mut [Expr]) -> CExpPtr<Value> {
    check_types(
        b,
        args,
        &[DataKind::String, DataKind::String, DataKind::String],
    );
    let s = c_value(b, &mut args[0]);
    let pat = c_value(b, &mut args[1]);
    let sub = c_value(b, &mut args[2]);
    Box::new(Replace { s, pat, sub })
}
struct Replace {
    s: CExpPtr<Value>,
    pat: CExpPtr<Value>,
    sub: CExpPtr<Value>,
}
impl CExp<Value> for Replace {
    fn eval(&self, e: &mut EvalEnv, d: &[u8]) -> Value {
        let s = self.s.eval(e, d).str().to_string();
        let pat = self.pat.eval(e, d).str().to_string();
        let sub = self.sub.eval(e, d).str();
        let result = s.replace(&pat, &sub);
        Value::String(Rc::new(result))
    }
}
/////////////////////////////
/// Compile call to SUBSTRING.
fn c_substring(b: &Block, args: &mut [Expr]) -> CExpPtr<Value> {
    check_types(b, args, &[DataKind::String, DataKind::Int, DataKind::Int]);
    let s = c_value(b, &mut args[0]);
    let f = c_int(b, &mut args[1]);
    let n = c_int(b, &mut args[2]);
    Box::new(Substring { s, f, n })
}
struct Substring {
    s: CExpPtr<Value>,
    f: CExpPtr<i64>,
    n: CExpPtr<i64>,
}
impl CExp<Value> for Substring {
    fn eval(&self, ee: &mut EvalEnv, d: &[u8]) -> Value {
        let s = self.s.eval(ee, d).str();
        let f = self.f.eval(ee, d) as usize - 1;
        let n = self.n.eval(ee, d) as usize;
        let mut lim = s.len();
        if lim > f + n {
            lim = f + n;
        }
        let result = s[f..lim].to_string();
        Value::String(Rc::new(result))
    }
}

/////////////////////////////
/// Compile call to BINSUBSTRING.
fn c_binsubstring(b: &Block, args: &mut [Expr]) -> CExpPtr<Value> {
    check_types(b, args, &[DataKind::Binary, DataKind::Int, DataKind::Int]);
    let s = c_value(b, &mut args[0]);
    let f = c_int(b, &mut args[1]);
    let n = c_int(b, &mut args[2]);
    Box::new(BinSubstring { s, f, n })
}
struct BinSubstring {
    s: CExpPtr<Value>,
    f: CExpPtr<i64>,
    n: CExpPtr<i64>,
}
impl CExp<Value> for BinSubstring {
    fn eval(&self, ee: &mut EvalEnv, d: &[u8]) -> Value {
        let s = self.s.eval(ee, d).bin();
        let f = self.f.eval(ee, d) as usize - 1;
        let n = self.n.eval(ee, d) as usize;
        let mut lim = s.len();
        if lim > f + n {
            lim = f + n;
        }
        let result = s[f..lim].to_vec();
        Value::RcBinary(Rc::new(result))
    }
}

/////////////////////////////
/// Compile call to ARG.
fn c_arg(b: &Block, args: &mut [Expr]) -> CExpPtr<Value> {
    check_types(b, args, &[DataKind::Int, DataKind::String]);
    let k = c_int(b, &mut args[0]);
    let s = c_value(b, &mut args[1]);
    Box::new(Arg { k, s })
}
struct Arg {
    k: CExpPtr<i64>,
    s: CExpPtr<Value>,
}
impl CExp<Value> for Arg {
    fn eval(&self, ee: &mut EvalEnv, d: &[u8]) -> Value {
        let k = self.k.eval(ee, d);
        let s = self.s.eval(ee, d).str();
        let result = ee.tr.arg(k, &s);
        Value::String(result)
    }
}

/////////////////////////////
/// Compile call to HEADER.
fn c_header(b: &Block, args: &mut [Expr]) -> CExpPtr<i64> {
    check_types(b, args, &[DataKind::String, DataKind::String]);
    let n = c_value(b, &mut args[0]);
    let v = c_value(b, &mut args[1]);
    Box::new(Header { n, v })
}
struct Header {
    n: CExpPtr<Value>,
    v: CExpPtr<Value>,
}
impl CExp<i64> for Header {
    fn eval(&self, ee: &mut EvalEnv, d: &[u8]) -> i64 {
        let n = self.n.eval(ee, d).str();
        let v = self.v.eval(ee, d).str();
        ee.tr.header(&n, &v);
        0
    }
}

/////////////////////////////
/// Compile call to STATUSCODE.
fn c_status_code(b: &Block, args: &mut [Expr]) -> CExpPtr<i64> {
    check_types(b, args, &[DataKind::Int]);
    let code = c_int(b, &mut args[0]);
    Box::new(StatusCode { code })
}
struct StatusCode {
    code: CExpPtr<i64>,
}
impl CExp<i64> for StatusCode {
    fn eval(&self, ee: &mut EvalEnv, d: &[u8]) -> i64 {
        let code = self.code.eval(ee, d);
        ee.tr.status_code(code);
        0
    }
}

/////////////////////////////
/// Compile call to FILEATTR.
fn c_fileattr(b: &Block, args: &mut [Expr]) -> CExpPtr<Value> {
    check_types(b, args, &[DataKind::Int, DataKind::Int]);
    let k = c_int(b, &mut args[0]);
    let x = c_int(b, &mut args[1]);
    Box::new(FileAttr { k, x })
}
struct FileAttr {
    k: CExpPtr<i64>,
    x: CExpPtr<i64>,
}
impl CExp<Value> for FileAttr {
    fn eval(&self, ee: &mut EvalEnv, d: &[u8]) -> Value {
        let k = self.k.eval(ee, d);
        let x = self.x.eval(ee, d);
        let result = ee.tr.file_attr(k, x);
        Value::String(result)
    }
}

/////////////////////////////
/// Compile call to FILECONTENT.
fn c_filecontent(b: &Block, args: &mut [Expr]) -> CExpPtr<Value> {
    check_types(b, args, &[DataKind::Int]);
    let k = c_int(b, &mut args[0]);
    Box::new(FileContent { k })
}
struct FileContent {
    k: CExpPtr<i64>,
}
impl CExp<Value> for FileContent {
    fn eval(&self, ee: &mut EvalEnv, d: &[u8]) -> Value {
        let k = self.k.eval(ee, d);
        let result = ee.tr.file_content(k);
        Value::ArcBinary(result)
    }
}

/////////////////////////////
/// Compile call to REPACKFILE.
#[cfg(feature = "pack")]
fn c_repackfile(b: &Block, args: &mut [Expr]) -> CExpPtr<i64> {
    check_types(
        b,
        args,
        &[DataKind::Int, DataKind::String, DataKind::String],
    );
    let k = c_int(b, &mut args[0]);
    let s = c_value(b, &mut args[1]);
    let n = c_value(b, &mut args[2]);
    Box::new(RepackFile { k, s, n })
}
#[cfg(feature = "pack")]
struct RepackFile {
    k: CExpPtr<i64>,
    s: CExpPtr<Value>,
    n: CExpPtr<Value>,
}
#[cfg(feature = "pack")]
impl CExp<i64> for RepackFile {
    fn eval(&self, ee: &mut EvalEnv, d: &[u8]) -> i64 {
        let k = self.k.eval(ee, d);
        let s = self.s.eval(ee, d).str();
        let n = self.n.eval(ee, d).str();
        ee.db.repack_file(k, &s, &n)
    }
}

#[cfg(feature = "verify")]
/// SQL to load every table ( required for database::verify to work correctly ).
const LOADALLTABLES: &str = "  
  DECLARE sid int, sname string, tname string
  FOR sid = Id, sname = Name FROM sys.Schema
  BEGIN
    FOR tname = Name FROM sys.Table WHERE Schema = sid
    BEGIN
      EXECUTE( 'IF false SELECT Id FROM ' | sys.Dot( sname, tname ) )
    END
  END";

#[cfg(feature = "verify")]
/////////////////////////////
/// Compile call to VERIFYDB.
fn c_verifydb(b: &Block, args: &mut [Expr]) -> CExpPtr<Value> {
    check_types(b, args, &[]);
    Box::new(VerifyDb {})
}
#[cfg(feature = "verify")]
struct VerifyDb {}
#[cfg(feature = "verify")]
impl CExp<Value> for VerifyDb {
    fn eval(&self, ee: &mut EvalEnv, _d: &[u8]) -> Value {
        ee.db.run(LOADALLTABLES, ee.tr);
        let s = ee.db.verify();
        Value::String(Rc::new(s))
    }
}