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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
pub use std::os::raw::c_char;


pub const MAX_IDENTIFIER_LENGTH: usize = 64;
pub const MAX_NUMBER_LENGTH: usize = 256;

#[derive(Clone, Copy)]
pub struct Identifier {
  pub value: [c_char; MAX_IDENTIFIER_LENGTH],
  pub length: usize,
}

impl Identifier {
  pub fn new () -> Self {
    Self {
      value: [ 0 as c_char; MAX_IDENTIFIER_LENGTH ],
      length: 0
    }
  }

  pub fn from_str (new_value: &str) -> Option<Self> {
    let mut value = [ 0 as c_char; MAX_IDENTIFIER_LENGTH ];
    let length = new_value.len();

    for (i, ch) in new_value.chars().enumerate() {
      if ch.is_ascii() {
        value[i] = ch as c_char;
      } else {
        return None;
      }
    }

    Some(Self {
      value,
      length
    })
  }
}

impl std::cmp::PartialEq for Identifier {
  fn eq (&self, r: &Identifier) -> bool {
    if self.length == r.length {
      for i in 0..self.length {
        if self.value[i] != r.value[i] {
          return false
        }
      }

      true
    } else {
      false
    }
  }
}

impl std::fmt::Debug for Identifier {
  fn fmt (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    for i in 0..self.length {
      write!(f, "{}", self.value[i] as u8 as char)?;
    }

    Ok(())
  }
}

impl std::fmt::Display for Identifier {
  fn fmt (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
    std::fmt::Debug::fmt(self, f)
  }
}


#[repr(u8)]
#[derive(Debug, PartialEq, Clone, Copy, FromPrimitive, ToPrimitive)]
pub enum ConstantNumber {
  NaN,
  Infinity,
}

#[repr(u8)]
#[derive(Debug, PartialEq, Clone, Copy, FromPrimitive, ToPrimitive)]
pub enum NumberFormat {
  Binary,
  DecimalInteger,
  DecimalFloatingPoint,
  Hexadecimal,
}

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Number {
  Integer(u64),
  Character(char),
  FloatingPoint(f64),
  Constant(ConstantNumber)
}

impl Number {
  pub fn is_integer (&self) -> bool {
    match self {
      Number::Integer(_) => true,
      _ => false
    }
  }
  
  pub fn is_character (&self) -> bool {
    match self {
      Number::Character(_) => true,
      _ => false
    }
  }
  
  pub fn is_floating_point (&self) -> bool {
    match self {
      Number::FloatingPoint(_) => true,
      _ => false
    }
  }
  
  pub fn is_constant (&self) -> bool {
    match self {
      Number::Constant(_) => true,
      _ => false
    }
  }

  
  pub fn get_integer (&self) -> Option<&u64> {
    match self {
      Number::Integer(i) => Some(i),
      _ => None
    }
  }
  
  pub fn get_character (&self) -> Option<&char> {
    match self {
      Number::Character(c) => Some(c),
      _ => None
    }
  }
  
  pub fn get_floating_point (&self) -> Option<&f64> {
    match self {
      Number::FloatingPoint(f) => Some(f),
      _ => None
    }
  }
  
  pub fn get_constant (&self) -> Option<&ConstantNumber> {
    match self {
      Number::Constant(c) => Some(c),
      _ => None
    }
  }
}

#[derive(Debug, Clone)]
pub enum Literal {
  Nil,
  Boolean(bool),
  Number(Number),
  String(String),
}

impl Literal {
  pub fn is_nil (&self) -> bool {
    match self {
      Literal::Nil => true,
      _ => false
    }
  }

  pub fn is_boolean (&self) -> bool {
    match self {
      Literal::Boolean(_) => true,
      _ => false
    }
  }

  pub fn is_number (&self) -> bool {
    match self {
      Literal::Number(_) => true,
      _ => false
    }
  }

  pub fn is_string (&self) -> bool {
    match self {
      Literal::String(_) => true,
      _ => false
    }
  }


  pub fn get_boolean (&self) -> Option<&bool> {
    match self {
      Literal::Boolean(b) => Some(b),
      _ => None
    }
  }

  pub fn get_number (&self) -> Option<&Number> {
    match self {
      Literal::Number(n) => Some(n),
      _ => None
    }
  }

  pub fn get_string (&self) -> Option<&String> {
    match self {
      Literal::String(s) => Some(s),
      _ => None
    }
  }
}


#[derive(Debug, Clone)]
pub enum Primary {
  Literal(Literal),
  Identifier(Identifier),
}

impl Primary {
  pub fn is_literal (&self) -> bool {
    match self {
      Primary::Literal(_) => true,
      _ => false
    }
  }

  pub fn is_ident (&self) -> bool {
    match self {
      Primary::Identifier(_) => true,
      _ => false
    }
  }

  
  pub fn get_literal (&self) -> Option<&Literal> {
    match self {
      Primary::Literal(lit) => Some(lit),
      _ => None
    }
  }

  pub fn get_ident (&self) -> Option<&Identifier> {
    match self {
      Primary::Identifier(ident) => Some(ident),
      _ => None
    }
  }
}

#[derive(Debug, Clone)]
pub enum MaybeIgnore<T: std::fmt::Debug + Clone> {
  Ignore,
  Value(T)
}

impl<T: std::fmt::Debug + Clone> MaybeIgnore<T> {
  pub fn is_ignore (&self) -> bool {
    match self {
      MaybeIgnore::Ignore => true,
      _ => false
    }
  }

  pub fn is_value (&self) -> bool {
    match self {
      MaybeIgnore::Value(_) => true,
      _ => false
    }
  }


  pub fn to_option (self) -> Option<T> {
    match self {
      MaybeIgnore::Value(v) => Some(v),
      _ => None
    }
  }
}

#[repr(u8)]
#[derive(Debug, PartialEq, Clone, Copy, FromPrimitive, ToPrimitive)]
pub enum OperatorType {
  Add, Sub, Mul, Div, Rem,
  AddAssign, SubAssign, MulAssign, DivAssign, RemAssign,

  Assign,

  AddressOf,
  Dereference,

  Mutable,

  Arrow,
  WideArrow,

  Dot,
  Semi,
  Colon,
  Comma,

  ExclusiveRange,
  InclusiveRange,

  LesserOrEqual, GreaterOrEqual, Equal, NotEqual,

  LogicalNot, LogicalAnd, LogicalOr, LogicalXor,

  BitwiseNot, BitwiseAnd, BitwiseOr, BitwiseXor,
  BitwiseLeftShift, BitwiseRightShift,

  LeftParen, RightParen,
  LeftBrace, RightBrace,
  LeftBracket, RightBracket,
  LeftAngle, RightAngle,

  SizeOf, AlignOf, OffsetOf,

  Cast,

  OpenMetaTag,
}

#[repr(u8)]
#[derive(Debug, PartialEq, Clone, Copy, FromPrimitive, ToPrimitive)]
pub enum KeywordType {
  Mod,

  Import, Export, Use,

  Type, Struct, Union, Enum, Sum,
  
  Impl,

  Function,
  
  Let,

  If, Else,

  Match,

  For, While, Loop, Until,

  In,

  Break, Continue,

  Return,
}


macro_rules! op {
  ( $( $($op: expr), * => $ov_op: ident ), * $(,)? ) => {
    &[ $( (&[ $( $op ), * ], OperatorType::$ov_op) ), * ]
  };
}

pub const OPERATOR_TYPE_SYMS: &[(&[char], OperatorType)] = op! [
  '+' => Add,
  '-' => Sub,
  '*' => Mul,
  '/' => Div,
  '%' => Rem,
  '+','=' => AddAssign,
  '-','=' => SubAssign,
  '*','=' => MulAssign,
  '/','=' => DivAssign,
  '%','=' => RemAssign,
  '=' => Assign,
  '^' => AddressOf,
  '@' => Dereference,
  '-','>' => Arrow,
  '=','>' => WideArrow,
  '.' => Dot,
  ';' => Semi,
  ':' => Colon,
  ',' => Comma,
  '.','.' => ExclusiveRange,
  '.','.','.' => InclusiveRange,
  '<','=' => LesserOrEqual,
  '>','=' => GreaterOrEqual,
  '=','=' => Equal,
  '!','=' => NotEqual,
  '!' => BitwiseNot,
  '&' => BitwiseAnd,
  '|' => BitwiseOr,
  '~' => BitwiseXor,
  '(' => LeftParen,
  ')' => RightParen,
  '[' => LeftBrace,
  ']' => RightBrace,
  '{' => LeftBracket,
  '}' => RightBracket,
  '<' => LeftAngle,
  '>' => RightAngle,
  ':', '<' => OpenMetaTag,
];


macro_rules! Overloads {
  ( $( $op: ident $( => $value: ident $(, $extras: ident ),* )? );* $(;)? ) => {
    #[repr(u8)]
    #[derive(Debug, PartialEq, Clone, Copy, FromPrimitive, ToPrimitive)]
    pub enum OverloadableOperatorType { $(
      $op $( = OperatorType::$value as _ )?
    ),* }

    pub const OVERLOADABLE_OPERATOR_TYPE_SYMS: &[(&[OperatorType], OverloadableOperatorType)] = &[ $(
      (&[$( OperatorType::$value $( , OperatorType::$extras )* )?], OverloadableOperatorType::$op)
    ),* ];
  };
}

Overloads! {
  Add; Sub; Mul; Div; Rem;

  Assign;

  AddressOf; Dereference;

  Arrow; Dot;

  ExclusiveRange; InclusiveRange;

  LesserOrEqual; GreaterOrEqual; Equal;  NotEqual;

  LogicalNot; LogicalAnd; LogicalOr; LogicalXor;

  BitwiseNot; BitwiseAnd; BitwiseOr; BitwiseXor;
  BitwiseLeftShift; BitwiseRightShift;

  Subscript => LeftBrace, RightBrace;
  Call => LeftParen, RightParen;

  Cast;
}


pub const MOD_ASSIGN_OPS: &[OperatorType] = &[
  OperatorType::AddAssign,
  OperatorType::SubAssign,
  OperatorType::MulAssign,
  OperatorType::DivAssign,
  OperatorType::RemAssign,
];

pub const TERMINATOR_OPS: &[OperatorType] = &[
  OperatorType::Semi,
  OperatorType::Comma,
  OperatorType::RightParen,
  OperatorType::RightBrace,
  OperatorType::RightBracket,
  OperatorType::RightAngle,
];


#[repr(u8)]
#[derive(PartialEq, Clone, Copy, FromPrimitive, ToPrimitive)]
pub enum InternalIdentifierType {
  Nil,
  Ignore,
  Boolean,
  ConstantNumber,
  Operator,
  Keyword,
}


macro_rules! id {
  ( $( $ty: ident [ $( $($id: expr),* => $val: expr ),* $(,)? ] ),* $(,)? ) => {
    &[ $( $(
      (&[$( $id as c_char ),*], InternalIdentifierType::$ty, $val as u8)
    ),* ),* ]
  };
}

pub const INTERNAL_IDENTIFIERS: &[(&[c_char], InternalIdentifierType, u8)] = id! [
  Nil [ 'n','i','l' => 0 ],
  Ignore [ '_' => 0 ],
  Boolean [
    't','r','u','e' => true,
    'f','a','l','s','e' => false,
  ],
  ConstantNumber [
    'n','a','n' => ConstantNumber::NaN,
    'i','n','f' => ConstantNumber::Infinity,
  ],
  Operator [
    'm','u','t' => OperatorType::Mutable,
    'n','o','t' => OperatorType::LogicalNot,
    'a','n','d' => OperatorType::LogicalAnd,
    'o','r' => OperatorType::LogicalOr,
    'x','o','r' => OperatorType::LogicalXor,
    'l','s','h','i','f','t' => OperatorType::BitwiseLeftShift,
    'r','s','h','i','f','t' => OperatorType::BitwiseRightShift,
    's','i','z','e','o','f' => OperatorType::SizeOf,
    'a','l','i','g','n','o','f' => OperatorType::AlignOf,
    'o','f','f','s','e','t','o','f' => OperatorType::OffsetOf,
    'a','s' => OperatorType::Cast,
  ],
  Keyword [
    'm','o','d' => KeywordType::Mod,
    'i','m','p','o','r','t' => KeywordType::Import,
    'e','x','p','o','r','t' => KeywordType::Export,
    'u','s','e' => KeywordType::Use,
    't','y','p','e' => KeywordType::Type,
    's','t','r','u','c','t' => KeywordType::Struct,
    'u','n','i','o','n' => KeywordType::Union,
    'e','n','u','m' => KeywordType::Enum,
    's','u','m' => KeywordType::Sum,
    'i','m','p','l' => KeywordType::Impl,
    'f','n' => KeywordType::Function,
    'l','e','t' => KeywordType::Let,
    'i','f' => KeywordType::If,
    'e','l','s','e' => KeywordType::Else,
    'm','a','t','c','h' => KeywordType::Match,
    'f','o','r' => KeywordType::For,
    'w','h','i','l','e' => KeywordType::While,
    'l','o','o','p' => KeywordType::Loop,
    'u','n','t','i','l' => KeywordType::Until,
    'i','n' => KeywordType::In,
    'b','r','e','a','k' => KeywordType::Break,
    'c','o','n','t','i','n','u','e' => KeywordType::Continue,
    'r','e','t','u','r','n' => KeywordType::Return,
  ],
];

pub const LOOP_CONTROL_KWS: &[KeywordType] = &[
  KeywordType::Break,
  KeywordType::Continue,
];


pub const UNARY_POWER: usize = 70;
pub const UNARY_OPERATORS: &[OperatorType] = &[
  OperatorType::Dereference,

  OperatorType::LogicalNot,
  OperatorType::BitwiseNot,

  OperatorType::Add,
  OperatorType::Sub,

  OperatorType::SizeOf,
  OperatorType::AlignOf,
  OperatorType::OffsetOf,
];

macro_rules! bin_ops {
  ( $( ( $op: expr, $prec: expr ) ), * $(,)? ) => {
    pub const BINARY_OPERATORS: &[OperatorType] = &[
      $( $op ), *
    ];

    pub const BINARY_PRECEDENCES: &[usize] = &[
      $( $prec ), *
    ];
  };
}

bin_ops! [
  (OperatorType::LogicalAnd, 20),
  (OperatorType::LogicalOr, 20),
  (OperatorType::LogicalXor, 20),
  
  (OperatorType::LeftAngle, 30),
  (OperatorType::RightAngle, 30),
  (OperatorType::LesserOrEqual, 30),
  (OperatorType::GreaterOrEqual, 30),
  (OperatorType::NotEqual, 30),
  (OperatorType::Equal, 30),

  (OperatorType::InclusiveRange, 40),
  (OperatorType::ExclusiveRange, 40),

  (OperatorType::Add, 50),
  (OperatorType::Sub, 50),
  (OperatorType::BitwiseAnd, 50),
  (OperatorType::BitwiseOr, 50),
  (OperatorType::BitwiseXor, 50),

  (OperatorType::Mul, 60),
  (OperatorType::Div, 60),
  (OperatorType::Rem, 60),
  (OperatorType::BitwiseLeftShift, 60),
  (OperatorType::BitwiseRightShift, 60),
];

pub fn get_bin_op_precedence (op: OperatorType) -> usize {
  for (i, bop) in BINARY_OPERATORS.iter().enumerate() {
    if op == *bop {
      return BINARY_PRECEDENCES[i];
    }
  }

  panic!("Tried to get precedence for unregistered binary operator {:?}", op);
}


impl OperatorType {
  pub fn as_text (self) -> String {
    for sym in OPERATOR_TYPE_SYMS {
      if sym.1 == self {
        return sym.0.iter().collect();
      }
    }

    for ident in INTERNAL_IDENTIFIERS {
      if ident.1 == InternalIdentifierType::Operator
      && ident.2 == self as _ {
        let mut out = String::new();

        for c in ident.0 {
          out.push(*c as u8 as _);
        }

        return out;
      }
    }

    panic!("Could not find text value for OperatorType {:?}", self);
  }
}

impl KeywordType {
  pub fn as_text (self) -> String {
    for ident in INTERNAL_IDENTIFIERS {
      if ident.1 == InternalIdentifierType::Keyword
      && ident.2 == self as _ {
        let mut out = String::new();

        for c in ident.0 {
          out.push(*c as u8 as _);
        }

        return out;
      }
    }

    panic!("Could not find text value for KeywordType {:?}", self);
  }
}