sigma 0.1.1

Sigma σ is a Simple, Safe and Fast Template language
Documentation
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
#![warn(missing_docs)]
#![deny(missing_debug_implementations)]
#![doc(html_no_source)]

//! # Sigma: Simple, Safe and Fast Template language.
//!
//! ##### Simple:
//!
//! sigma is a very simple template language, it only tries to solve only one
//! problem. it also extendable, but with simple idea too (_Pure Functions_).
//!
//! ##### Safe:
//!
//! sigma is also typed, that means that it has the idea of built-in validators
//! for your input. and for those how wanna play, it also could be untyped.
//! also it has a good error checking at parse time of your template.
//! the only error that could happen in runtime is that the input data fails to
//! be parsed to your data types in your templates.
//! Here is some error examples:
//! ```ignore
//! --> 1:49
//!   |
//! 1 | my username is {{ username: str |> UPPERCASE |> NO_FUN }} WOW!
//!   |                                                 ^----^
//!   |
//!   = undefined function: NO_FUN
//! ```
//!
//! what if you forgot to bind for some variable in your template ?
//!
//! ```ignore
//!  --> 1:19
//!   |
//! 1 | my username is {{ username: str |> UPPERCASE |> NO_FUN }} WOW!
//!   |                   ^------^
//!   |
//!   = unbinded variable: username consider adding a bind for it
//! ```
//! do you need extra help ? we got your back ;)
//!
//! ```ignore
//! --> 1:35
//!   |
//! 1 | my username is {{ username: u32 | UPPERCAS }} WOW!
//!   |                                   ^------^
//!   |
//!   = undefined function: UPPERCAS did you mean: UPPERCASE ?
//! ```
//!
//! ##### Fast:
//!
//! sigma uses [`pest`](https://pest.rs/), The Elegant Parser under the hood to write it's grammar.
//! that means it will be exteramly fast in parsing your templete, also it uses
//! regex crate to replace your data in the template.
//!
//!
//! ### Examples
//!
//! here is a simple examples of how it works
//!
//! * Simple:
//!
//! ```ignore
//! use sigma::Sigma;
//!
//! let result = Sigma::new("Hello {{ username }}") // using {{ ... }} for the template.
//!  .bind("username", "someone") // bind the vars with values
//!  .parse() // you must parse your template first
//!  .map_err(|e| eprintln!("{}", e))? // for pretty printing the error..
//!  .compile()?;
//! assert_eq!("Hello someone", result);
//! ```
//! * with optinal variables
//! ```ignore
//! use sigma::Sigma;
//!   
//! let result = Sigma::new("Hello {{ username? }}") // using `?` to tell the parser it maybe `null`.
//!  .parse()
//!  .map_err(|e| eprintln!("{}", e))? // for pretty printing the error..
//!  .compile()?;
//! assert_eq!("Hello ", result);
//! ```
//! * what about types ?
//!
//! ```ignore
//! use sigma::Sigma;
//!   
//! let result = Sigma::new("Hello {{ username: str }}") // u8, u32 ? a bool ?.
//!  .bind("username", "someone")
//!  .parse()
//!  .map_err(|e| eprintln!("{}", e))? // for pretty printing the error..
//!  .compile()?;
//! assert_eq!("Hello someone", result);
//! ```
//! * how about functions ?
//! ```ignore
//! use sigma::Sigma;
//!   
//! let result = Sigma::new("Hello {{ username: str | UPPERCASE }}") // functions uses the `|` operator or if you love `|>` you can use it too.
//!  .bind("username", "someone")
//!  .parse()
//!  .map_err(|e| eprintln!("{}", e))? // for pretty printing the error..
//!  .compile()?;
//! assert_eq!("Hello SOMEONE", result);
//! ```
//! * love macros ?
//! ```ignore
//! use sigma::sigma;
//! let username = "someone";
//! let result = sigma!("Hello {{ username }}", username); // the macro return the result so you can check for compile erros.
//! assert_eq!("Hello someone", result.unwrap());
//! ```
mod parser;

use crate::parser::{Rule, SigmaParser};
use pest::{
  error::{Error as PestError, ErrorVariant},
  iterators::{Pair, Pairs},
  Parser, Span,
};
use regex::{NoExpand, Regex};
use std::collections::HashMap;

type SigmaResult<'a, T> = Result<T, PestError<Rule>>;

/// Primitive Data Types
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DataType {
  /// The 8-bit unsigned integer type.
  ///
  /// ex: `{{ data: u8 }}`
  U8,
  /// The 8-bit signed integer type.
  ///
  /// ex: `{{ data: i8 }}`
  I8,
  /// The 16-bit unsigned integer type.
  ///
  /// ex: `{{ data: u16 }}`
  U16,
  /// The 16-bit signed integer type.
  ///
  /// ex: `{{ data: i16 }}`
  I16,
  /// The 32-bit unsigned integer type.
  ///
  /// ex: `{{ data: u32 }}`
  U32,
  /// The 32-bit signed integer type.
  ///
  /// ex: `{{ data: i32 }}`
  I32,
  /// The 64-bit unsigned integer type.
  ///
  /// ex: `{{ data: u64 }}`
  U64,
  /// The 64-bit signed integer type.
  ///
  /// ex: `{{ data: i64 }}`
  I64,
  /// The 32-bit floating point type.
  ///
  /// ex: `{{ data: f32 }}`
  F32,
  /// The 64-bit floating point type.
  ///
  /// ex: `{{ data: f64 }}`
  F64,
  /// The boolean type.
  ///
  /// ex: `{{ data: bool }}`
  Bool,
  /// String.
  ///
  /// ex: `{{ data: str }}`
  Str,
}

#[doc(hidden)]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Variable<'a> {
  pub name: &'a str,
  pub nullable: bool,
  pub typed: bool,
  pub data_type: Option<(DataType, Span<'a>)>,
  pub location: (usize, usize),
  pub functions: Vec<(&'a str, Span<'a>)>,
  pub name_span: Option<Span<'a>>,
  pub pair_str: &'a str,
}

#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Function {
  pub name: String,
  pub call: fn(String) -> String,
}

/// Sigma, Template Language made simple !
///
/// Example:
/// ```
/// # use sigma::{Sigma, sigma};
/// # fn main() -> Result<(), ()> {
/// let result = Sigma::new("Hello {{ username }}") // using {{ ... }} for the template.
///     .bind("username", "someone") // bind the vars with values
///     .parse() // you must parse your template first
///     .map_err(|e| eprintln!("{}", e))? // for pretty printing the error..
///     .compile()
///     .map_err(|e| eprintln!("{}", e))?;
/// assert_eq!("Hello someone", result);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Sigma<'s> {
  vars: HashMap<&'s str, Variable<'s>>,
  registry: HashMap<&'s str, &'s str>,
  input: &'s str,
  is_parsed: bool,
  ignore_unbinded: bool,
  functions: HashMap<&'s str, Function>,
}

impl<'s> Sigma<'s> {
  /// Create new Sigma with some template
  pub fn new(input: &'s str) -> Self {
    let sigma = Self {
      input,
      vars: HashMap::new(),
      functions: HashMap::new(),
      is_parsed: false,
      ignore_unbinded: false,
      registry: HashMap::new(),
    };

    let sigma = sigma.register_fn("UPPERCASE", |input| input.to_uppercase());
    let sigma =
      sigma.register_fn("TRIM_END", |input| input.trim_end().to_owned());
    let sigma =
      sigma.register_fn("TRIM_START", |input| input.trim_start().to_owned());
    let sigma =
      sigma.register_fn("TRIM_START", |input| input.trim_start().to_owned());
    let sigma = sigma.register_fn("TRIM", |input| input.trim().to_owned());

    sigma.register_fn("LOWERRCASE", |input| input.to_lowercase())
  }

  /// bind some key in the template for some value
  pub fn bind(mut self, key: &'s str, value: &'s str) -> Self {
    self.registry.insert(key, value);
    self
  }

  /// bind one or more keys with values in one run.
  pub fn bind_map(mut self, map: HashMap<&'s str, &'s str>) -> Self {
    self.registry.extend(map);
    self
  }

  /// remove all the previous binded keys, and use that one
  pub fn override_bind(mut self, map: HashMap<&'s str, &'s str>) -> Self {
    self.registry = map;
    self
  }

  /// ignore parse error for unbinded variables
  pub fn ignore_unbinded(mut self) -> Self {
    self.ignore_unbinded = true;
    self
  }

  /// register a helper function
  ///
  /// The Function Name Must be in UPPERCASE
  pub fn register_fn(
    mut self,
    func_name: &'static str,
    func: fn(String) -> String,
  ) -> Self {
    self.functions.insert(
      func_name,
      Function {
        name: func_name.to_uppercase(),
        call: func,
      },
    );
    self
  }

  /// Parse the template before compiling it to ensure no runtime erros.
  pub fn parse(mut self) -> SigmaResult<'s, Self> {
    for sigma in SigmaParser::parse(Rule::sigma, &self.input)? {
      if sigma.as_rule() == Rule::var_pair {
        self.parse_var_pair(sigma)?;
      }
    }
    self.is_parsed = true;
    Ok(self)
  }

  /// Compile the template with the binded values
  ///
  /// ## Panics
  /// this will panic if the current template
  /// not parsed yet.
  pub fn compile(self) -> SigmaResult<'s, String> {
    assert!(self.is_parsed, "The template must be parsed first");
    let mut output = self.input.to_owned(); // copy the input
    for var in self.vars.values() {
      let var_regex = Regex::new(&regex::escape(var.pair_str)).unwrap();
      if let Some(value) = self.registry.get(var.name) {
        let mut current_data = (*value).to_owned();
        for function in &var.functions {
          let f = &self.functions[&function.0]; // we are sure it will be there.
          current_data = (f.call)(current_data);
        }
        self.validate_data_type(&var, &current_data)?;
        output = var_regex
          .replace_all(&output, NoExpand(&current_data))
          .to_string();
      } else if var.nullable {
        // it must be nullable then
        output = var_regex.replace_all(&output, NoExpand("")).to_string();
      }
    }
    Ok(output)
  }

  // TODO: Refactor this function
  fn parse_var_pair(&mut self, pair: Pair<'s, Rule>) -> SigmaResult<()> {
    let mut variable = Variable::default();
    variable.pair_str = pair.as_str();
    let mut inner_rules = pair.into_inner();
    let open_pairs = inner_rules.next().unwrap();
    let var = inner_rules.next().unwrap();
    let var_inner = var.into_inner();
    for var_rules in var_inner {
      match var_rules.as_rule() {
        Rule::nullable => {
          variable.nullable = true;
        },
        Rule::var_name => {
          variable.name = var_rules.as_str();
          variable.name_span = Some(var_rules.as_span());
        },
        Rule::data_type_sep => {
          // it must has data type then
          variable.typed = true;
        },
        Rule::data_type => {
          let data_type = var_rules;
          variable.data_type =
            Some((self.parse_data_type(&data_type)?, data_type.as_span()));
        },
        _ => {},
      };
    }
    // data type check
    if variable.typed && variable.data_type.is_none() {
      return Err(PestError::new_from_span(
        ErrorVariant::ParsingError {
          positives: vec![Rule::data_type],
          negatives: vec![],
        },
        variable.name_span.clone().unwrap(),
      ));
    }
    let mut variable = self.parse_function(inner_rules, variable)?;
    variable.location = (open_pairs.as_span().start(), variable.location.1);
    // check if we have a back value for this variable ?
    if !self.registry.contains_key(variable.name)
      && !variable.nullable
      && !self.ignore_unbinded
    {
      let extra_help;
      if let Some(matches) =
        parser::did_you_mean(variable.name, self.registry.keys())
      {
        extra_help = format!("did you mean: `{}` ?", matches);
      } else {
        extra_help = "consider adding a bind for it".to_owned();
      }
      return Err(PestError::new_from_span(
        ErrorVariant::CustomError {
          message: format!(
            "unbinded variable: `{}` {}",
            variable.name, extra_help
          ),
        },
        variable.name_span.clone().unwrap(),
      ));
    }
    self.vars.insert(variable.name, variable);
    Ok(())
  }

  #[inline(always)]
  fn parse_data_type<'b>(
    &self,
    pair: &Pair<Rule>,
  ) -> SigmaResult<'b, DataType> {
    use self::DataType::*;
    let val = pair.as_str();
    let result = match val {
      "u8" => U8,
      "i8" => I8,
      "u16" => U16,
      "i16" => I16,
      "u32" => U32,
      "i32" => I32,
      "u64" => U64,
      "i64" => I64,
      "f32" => F32,
      "f64" => F64,
      "bool" => Bool,
      "str" => Str,
      _ => {
        let p_vals = [
          "u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "f32", "f64",
          "str", "bool",
        ];
        let mut extra_help = String::new();
        if let Some(matches) = parser::did_you_mean(val, p_vals.iter()) {
          extra_help = format!("did you mean: `{}` ?", matches);
        }
        return Err(PestError::new_from_span(
          ErrorVariant::CustomError {
            message: format!("unknown data type: `{}` {}", val, extra_help),
          },
          pair.as_span(),
        ));
      },
    };
    Ok(result)
  }

  fn parse_function<'f>(
    &self,
    pairs: Pairs<'f, Rule>,
    mut var: Variable<'f>,
  ) -> SigmaResult<'f, Variable<'f>> {
    for pair in pairs {
      let rule = pair.as_rule();
      match rule {
        Rule::function => {
          if var.data_type.is_none() || !var.typed {
            return Err(PestError::new_from_span(
              ErrorVariant::ParsingError {
                positives: vec![Rule::data_type],
                negatives: vec![],
              },
              var.name_span.unwrap(),
            ));
          }
          let mut function = pair.into_inner();
          let _sep = function.next().unwrap();
          let function_name = function.next().unwrap();
          if !self.functions.contains_key(function_name.as_str()) {
            let mut extra_help = String::new();
            if let Some(matches) = parser::did_you_mean(
              function_name.as_str(),
              self.functions.keys(),
            ) {
              extra_help = format!("did you mean: `{}` ?", matches);
            }
            return Err(PestError::new_from_span(
              ErrorVariant::CustomError {
                message: format!(
                  "undefined function: {} {}",
                  function_name.as_str(),
                  extra_help
                ),
              },
              function_name.as_span(),
            ));
          }
          var
            .functions
            .push((function_name.as_str(), function_name.as_span()));
        },
        Rule::pair_close => {
          var.location = (0, pair.as_span().end());
          break;
        },
        _ => {},
      };
    }
    Ok(var)
  }

  #[inline]
  fn validate_data_type(
    &self,
    var: &Variable,
    data: &str,
  ) -> SigmaResult<'s, ()> {
    if let Some(data_type) = &var.data_type {
      use self::DataType::*;
      let data_type_error = {
        let extra = if data.len() > 15 { "..." } else { "" };
        PestError::<Rule>::new_from_span(
          ErrorVariant::CustomError {
            message: format!(
              "cannot parse input `{}{}` into `{:?}` for var `{}` !",
              data.chars().take(15).collect::<String>(),
              extra,
              data_type.0,
              var.name
            ),
          },
          data_type.1.clone(),
        )
      };
      match data_type.0 {
        U8 => {
          data.parse::<u8>().map_err(|_| data_type_error)?;
        },
        I8 => {
          data.parse::<i8>().map_err(|_| data_type_error)?;
        },
        U16 => {
          data.parse::<u16>().map_err(|_| data_type_error)?;
        },
        I16 => {
          data.parse::<i16>().map_err(|_| data_type_error)?;
        },
        U32 => {
          data.parse::<u32>().map_err(|_| data_type_error)?;
        },
        I32 => {
          data.parse::<i32>().map_err(|_| data_type_error)?;
        },
        U64 => {
          data.parse::<u64>().map_err(|_| data_type_error)?;
        },
        I64 => {
          data.parse::<i64>().map_err(|_| data_type_error)?;
        },
        F32 => {
          data.parse::<f32>().map_err(|_| data_type_error)?;
        },
        F64 => {
          data.parse::<f64>().map_err(|_| data_type_error)?;
        },
        Bool => {
          data.parse::<bool>().map_err(|_| data_type_error)?;
        },
        _ => {
          // it must be a string then
        },
      };
      return Ok(());
    }
    Ok(())
  }
}

impl<'s> From<&'s str> for Sigma<'s> {
  fn from(template: &'s str) -> Sigma<'s> {
    Sigma::new(template)
      .parse()
      .map_err(|e| eprintln!("Parse Error:\n{}", e))
      .unwrap()
  }
}

#[macro_export]
/// A helper macro to create a sigma with multi key-value
macro_rules! sigma {
  ($template:expr, $($k:expr), *) => {
    {
      let mut map = std::collections::HashMap::new();
      let s = $crate::Sigma::new($template);
      $(
        map.insert(stringify!($k), $k);
      )*
      let s = s.bind_map(map);
      let s = s.parse().map_err(|e| eprintln!("Parse Error:\n{}", e)).unwrap();
      s.compile()
    }
  };
}

// TODO: Add more tests here.
#[cfg(test)]
mod tests {
  use super::*;
  #[test]
  #[should_panic]
  fn missing_data_type() {
    let input = "{{ username: }}";
    let _ = Sigma::new(input)
      .bind("username", "test")
      .parse()
      .unwrap()
      .compile();
  }

  #[test]
  #[should_panic]
  fn unknown_data_type() {
    let input = "{{ username: unknown }}";
    let output = Sigma::new(input)
      .bind("username", "test")
      .parse()
      .unwrap()
      .compile();
    println!("{:?}", output);
  }

  #[test]
  fn test_sigma_macro() {
    let username = "someone";
    let s = sigma!("{{ username }}", username);
    assert_eq!("someone", s.unwrap());
  }
}