-
Notifications
You must be signed in to change notification settings - Fork 221
/
main.rs
1337 lines (1057 loc) · 40.5 KB
/
main.rs
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This is an example of the [Kaleidoscope tutorial](https://llvm.org/docs/tutorial/)
//! made in Rust, using Inkwell.
//! Currently, all features up to the [7th chapter](https://llvm.org/docs/tutorial/LangImpl07.html)
//! are available.
//! This example is supposed to be ran as a executable, which launches a REPL.
//! The source code is in the following order:
//! - Lexer,
//! - Parser,
//! - Compiler,
//! - Program.
//!
//! Both the `Parser` and the `Compiler` may fail, in which case they would return
//! an error represented by `Result<T, &'static str>`, for easier error reporting.
extern crate inkwell;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::io::{self, Write};
use std::iter::Peekable;
use std::str::Chars;
use std::ops::DerefMut;
use self::inkwell::basic_block::BasicBlock;
use self::inkwell::builder::Builder;
use self::inkwell::context::Context;
use self::inkwell::module::Module;
use self::inkwell::passes::PassManager;
use self::inkwell::targets::{InitializationConfig, Target};
use self::inkwell::types::BasicTypeEnum;
use self::inkwell::values::{BasicValueEnum, FloatValue, FunctionValue, PointerValue};
use self::inkwell::{OptimizationLevel, FloatPredicate};
use Token::*;
const ANONYMOUS_FUNCTION_NAME: &str = "anonymous";
// ======================================================================================
// LEXER ================================================================================
// ======================================================================================
/// Represents a primitive syntax token.
#[derive(Debug, Clone)]
pub enum Token {
Binary,
Comma,
Comment,
Def,
Else,
EOF,
Extern,
For,
Ident(String),
If,
In,
LParen,
Number(f64),
Op(char),
RParen,
Then,
Unary,
Var
}
/// Defines an error encountered by the `Lexer`.
pub struct LexError {
pub error: &'static str,
pub index: usize
}
impl LexError {
pub fn new(msg: &'static str) -> LexError {
LexError { error: msg, index: 0 }
}
pub fn with_index(msg: &'static str, index: usize) -> LexError {
LexError { error: msg, index: index }
}
}
/// Defines the result of a lexing operation; namely a
/// `Token` on success, or a `LexError` on failure.
pub type LexResult = Result<Token, LexError>;
/// Defines a lexer which transforms an input `String` into
/// a `Token` stream.
pub struct Lexer<'a> {
input: &'a str,
chars: Box<Peekable<Chars<'a>>>,
pos: usize
}
impl<'a> Lexer<'a> {
/// Creates a new `Lexer`, given its source `input`.
pub fn new(input: &'a str) -> Lexer<'a> {
Lexer { input: input, chars: Box::new(input.chars().peekable()), pos: 0 }
}
/// Lexes and returns the next `Token` from the source code.
pub fn lex(&mut self) -> LexResult {
let chars = self.chars.deref_mut();
let src = self.input;
let mut pos = self.pos;
// Skip whitespaces
loop {
// Note: the following lines are in their own scope to
// limit how long 'chars' is borrowed, and in order to allow
// it to be borrowed again in the loop by 'chars.next()'.
{
let ch = chars.peek();
if ch.is_none() {
self.pos = pos;
return Ok(Token::EOF);
}
if !ch.unwrap().is_whitespace() {
break;
}
}
chars.next();
pos += 1;
}
let start = pos;
let next = chars.next();
if next.is_none() {
return Ok(Token::EOF);
}
pos += 1;
// Actually get the next token.
let result = match next.unwrap() {
'(' => Ok(Token::LParen),
')' => Ok(Token::RParen),
',' => Ok(Token::Comma),
'#' => {
// Comment
loop {
let ch = chars.next();
pos += 1;
if ch == Some('\n') {
break;
}
}
Ok(Token::Comment)
},
'.' | '0' ... '9' => {
// Parse number literal
loop {
let ch = match chars.peek() {
Some(ch) => *ch,
None => return Ok(Token::EOF)
};
// Parse float.
if ch != '.' && !ch.is_digit(16) {
break;
}
chars.next();
pos += 1;
}
Ok(Token::Number(src[start..pos].parse().unwrap()))
},
'a' ... 'z' | 'A' ... 'Z' | '_' => {
// Parse identifier
loop {
let ch = match chars.peek() {
Some(ch) => *ch,
None => return Ok(Token::EOF)
};
// A word-like identifier only contains underscores and alphanumeric characters.
if ch != '_' && !ch.is_alphanumeric() {
break;
}
chars.next();
pos += 1;
}
match &src[start..pos] {
"def" => Ok(Token::Def),
"extern" => Ok(Token::Extern),
"if" => Ok(Token::If),
"then" => Ok(Token::Then),
"else" => Ok(Token::Else),
"for" => Ok(Token::For),
"in" => Ok(Token::In),
"unary" => Ok(Token::Unary),
"binary" => Ok(Token::Binary),
"var" => Ok(Token::Var),
ident => Ok(Token::Ident(ident.to_string()))
}
},
op => {
// Parse operator
Ok(Token::Op(op))
}
};
// Update stored position, and return
self.pos = pos;
result
}
}
impl<'a> Iterator for Lexer<'a> {
type Item = Token;
/// Lexes the next `Token` and returns it.
/// On EOF or failure, `None` will be returned.
fn next(&mut self) -> Option<Self::Item> {
match self.lex() {
Ok(EOF) | Err(_) => None,
Ok(token) => Some(token)
}
}
}
// ======================================================================================
// PARSER ===============================================================================
// ======================================================================================
/// Defines a primitive expression.
#[derive(Debug)]
pub enum Expr {
Binary {
op: char,
left: Box<Expr>,
right: Box<Expr>
},
Call {
fn_name: String,
args: Vec<Expr>
},
Conditional {
cond: Box<Expr>,
consequence: Box<Expr>,
alternative: Box<Expr>
},
For {
var_name: String,
start: Box<Expr>,
end: Box<Expr>,
step: Option<Box<Expr>>,
body: Box<Expr>
},
Number(f64),
Variable(String),
VarIn {
variables: Vec<(String, Option<Expr>)>,
body: Box<Expr>
}
}
/// Defines the prototype (name and parameters) of a function.
#[derive(Debug)]
pub struct Prototype {
pub name: String,
pub args: Vec<String>,
pub is_op: bool,
pub prec: usize
}
/// Defines a user-defined function.
#[derive(Debug)]
pub struct Function {
pub prototype: Prototype,
pub body: Expr,
pub is_anon: bool
}
/// Represents the `Expr` parser.
pub struct Parser<'a> {
tokens: Vec<Token>,
pos: usize,
prec: &'a mut HashMap<char, i32>
}
// I'm ignoring the 'must_use' lint in order to call 'self.advance' without checking
// the result when an EOF is acceptable.
#[allow(unused_must_use)]
impl<'a> Parser<'a> {
/// Creates a new parser, given an input `str` and a `HashMap` binding
/// an operator and its precedence in binary expressions.
pub fn new(input: String, op_precedence: &'a mut HashMap<char, i32>) -> Self {
let mut lexer = Lexer::new(input.as_str());
let tokens = lexer.by_ref().collect();
Parser {
tokens: tokens,
prec: op_precedence,
pos: 0
}
}
/// Parses the content of the parser.
pub fn parse(&mut self) -> Result<Function, &'static str> {
let result = match self.current()? {
Def => self.parse_def(),
Extern => self.parse_extern(),
_ => self.parse_toplevel_expr()
};
match result {
Ok(result) => {
if !self.at_end() {
Err("Unexpected token after parsed expression.")
} else {
Ok(result)
}
},
err => err
}
}
/// Returns the current `Token`, without performing safety checks beforehand.
fn curr(&self) -> Token {
self.tokens[self.pos].clone()
}
/// Returns the current `Token`, or an error that
/// indicates that the end of the file has been unexpectedly reached if it is the case.
fn current(&self) -> Result<Token, &'static str> {
if self.pos >= self.tokens.len() {
Err("Unexpected end of file.")
} else {
Ok(self.tokens[self.pos].clone())
}
}
/// Advances the position, and returns an empty `Result` whose error
/// indicates that the end of the file has been unexpectedly reached.
/// This allows to use the `self.advance()?;` syntax.
fn advance(&mut self) -> Result<(), &'static str> {
let npos = self.pos + 1;
self.pos = npos;
if npos < self.tokens.len() {
Ok(())
} else {
Err("Unexpected end of file.")
}
}
/// Returns a value indicating whether or not the `Parser`
/// has reached the end of the input.
fn at_end(&self) -> bool {
self.pos >= self.tokens.len()
}
/// Returns the precedence of the current `Token`, or 0 if it is not recognized as a binary operator.
fn get_tok_precedence(&self) -> i32 {
if let Ok(Op(op)) = self.current() {
*self.prec.get(&op).unwrap_or(&100)
} else {
-1
}
}
/// Parses the prototype of a function, whether external or user-defined.
fn parse_prototype(&mut self) -> Result<Prototype, &'static str> {
let (id, is_operator, precedence) = match self.curr() {
Ident(id) => {
self.advance()?;
(id, false, 0)
},
Binary => {
self.advance()?;
let op = match self.curr() {
Op(ch) => ch,
_ => return Err("Expected operator in custom operator declaration.")
};
self.advance()?;
let mut name = String::from("binary");
name.push(op);
let prec = if let Number(prec) = self.curr() {
self.advance()?;
prec as usize
} else {
0
};
self.prec.insert(op, prec as i32);
(name, true, prec)
},
Unary => {
self.advance()?;
let op = match self.curr() {
Op(ch) => ch,
_ => return Err("Expected operator in custom operator declaration.")
};
let mut name = String::from("unary");
name.push(op);
self.advance()?;
(name, true, 0)
},
_ => return Err("Expected identifier in prototype declaration.")
};
match self.curr() {
LParen => (),
_ => return Err("Expected '(' character in prototype declaration.")
}
self.advance()?;
if let RParen = self.curr() {
self.advance();
return Ok(Prototype {
name: id,
args: vec![],
is_op: is_operator,
prec: precedence
});
}
let mut args = vec![];
loop {
match self.curr() {
Ident(name) => args.push(name),
_ => return Err("Expected identifier in parameter declaration.")
}
self.advance()?;
match self.curr() {
RParen => {
self.advance();
break;
},
Comma => {
self.advance();
},
_ => return Err("Expected ',' or ')' character in prototype declaration.")
}
}
Ok(Prototype {
name: id,
args: args,
is_op: is_operator,
prec: precedence
})
}
/// Parses a user-defined function.
fn parse_def(&mut self) -> Result<Function, &'static str> {
// Eat 'def' keyword
self.pos += 1;
// Parse signature of function
let proto = self.parse_prototype()?;
// Parse body of function
let body = self.parse_expr()?;
// Return new function
Ok(Function {
prototype: proto,
body: body,
is_anon: false
})
}
/// Parses an external function declaration.
fn parse_extern(&mut self) -> Result<Function, &'static str> {
// Eat 'extern' keyword
self.pos += 1;
// Parse signature of extern function
let proto = self.parse_prototype()?;
// Return signature of extern function
Ok(Function {
prototype: proto,
body: Expr::Number(std::f64::NAN),
is_anon: false
})
}
/// Parses any expression.
fn parse_expr(&mut self) -> Result<Expr, &'static str> {
match self.parse_unary_expr() {
Ok(left) => self.parse_binary_expr(0, left),
err => err
}
}
/// Parses a literal number.
fn parse_nb_expr(&mut self) -> Result<Expr, &'static str> {
// Simply convert Token::Number to Expr::Number
match self.curr() {
Number(nb) => {
self.advance();
Ok(Expr::Number(nb))
},
_ => Err("Expected number literal.")
}
}
/// Parses an expression enclosed in parenthesis.
fn parse_paren_expr(&mut self) -> Result<Expr, &'static str> {
match self.current()? {
LParen => (),
_ => return Err("Expected '(' character at start of parenthesized expression.")
}
self.advance()?;
let expr = self.parse_expr()?;
match self.current()? {
RParen => (),
_ => return Err("Expected ')' character at end of parenthesized expression.")
}
self.advance();
Ok(expr)
}
/// Parses an expression that starts with an identifier (either a variable or a function call).
fn parse_id_expr(&mut self) -> Result<Expr, &'static str> {
let id = match self.curr() {
Ident(id) => id,
_ => return Err("Expected identifier.")
};
if self.advance().is_err() {
return Ok(Expr::Variable(id));
}
match self.curr() {
LParen => {
self.advance()?;
if let RParen = self.curr() {
return Ok(Expr::Call { fn_name: id, args: vec![] });
}
let mut args = vec![];
loop {
args.push(self.parse_expr()?);
match self.current()? {
Comma => (),
RParen => break,
_ => return Err("Expected ',' character in function call.")
}
self.advance()?;
}
self.advance();
Ok(Expr::Call { fn_name: id, args: args })
},
_ => Ok(Expr::Variable(id))
}
}
/// Parses an unary expression.
fn parse_unary_expr(&mut self) -> Result<Expr, &'static str> {
let op = match self.current()? {
Op(ch) => {
self.advance()?;
ch
},
_ => return self.parse_primary()
};
let mut name = String::from("unary");
name.push(op);
Ok(Expr::Call {
fn_name: name,
args: vec![ self.parse_unary_expr()? ]
})
}
/// Parses a binary expression, given its left-hand expression.
fn parse_binary_expr(&mut self, prec: i32, mut left: Expr) -> Result<Expr, &'static str> {
loop {
let curr_prec = self.get_tok_precedence();
if curr_prec < prec || self.at_end() {
return Ok(left);
}
let op = match self.curr() {
Op(op) => op,
_ => return Err("Invalid operator.")
};
self.advance()?;
let mut right = self.parse_unary_expr()?;
let next_prec = self.get_tok_precedence();
if curr_prec < next_prec {
right = self.parse_binary_expr(curr_prec + 1, right)?;
}
left = Expr::Binary {
op: op,
left: Box::new(left),
right: Box::new(right)
};
}
}
/// Parses a conditional if..then..else expression.
fn parse_conditional_expr(&mut self) -> Result<Expr, &'static str> {
// eat 'if' token
self.advance()?;
let cond = self.parse_expr()?;
// eat 'then' token
match self.current() {
Ok(Then) => self.advance()?,
_ => return Err("Expected 'then' keyword.")
}
let then = self.parse_expr()?;
// eat 'else' token
match self.current() {
Ok(Else) => self.advance()?,
_ => return Err("Expected 'else' keyword.")
}
let otherwise = self.parse_expr()?;
Ok(Expr::Conditional {
cond: Box::new(cond),
consequence: Box::new(then),
alternative: Box::new(otherwise)
})
}
/// Parses a loop for..in.. expression.
fn parse_for_expr(&mut self) -> Result<Expr, &'static str> {
// eat 'for' token
self.advance()?;
let name = match self.curr() {
Ident(n) => n,
_ => return Err("Expected identifier in for loop.")
};
// eat identifier
self.advance()?;
// eat '=' token
match self.curr() {
Op('=') => self.advance()?,
_ => return Err("Expected '=' character in for loop.")
}
let start = self.parse_expr()?;
// eat ',' token
match self.current()? {
Comma => self.advance()?,
_ => return Err("Expected ',' character in for loop.")
}
let end = self.parse_expr()?;
// parse (optional) step expression
let step = match self.current()? {
Comma => {
self.advance()?;
Some(self.parse_expr()?)
},
_ => None
};
// eat 'in' token
match self.current()? {
In => self.advance()?,
_ => return Err("Expected 'in' keyword in for loop.")
}
let body = self.parse_expr()?;
Ok(Expr::For {
var_name: name,
start: Box::new(start),
end: Box::new(end),
step: step.map(Box::new),
body: Box::new(body)
})
}
/// Parses a var..in expression.
fn parse_var_expr(&mut self) -> Result<Expr, &'static str> {
// eat 'var' token
self.advance()?;
let mut variables = Vec::new();
// parse variables
loop {
let name = match self.curr() {
Ident(name) => name,
_ => return Err("Expected identifier in 'var..in' declaration.")
};
self.advance()?;
// read (optional) initializer
let initializer = match self.curr() {
Op('=') => Some({
self.advance()?;
self.parse_expr()?
}),
_ => None
};
variables.push((name, initializer));
match self.curr() {
Comma => {
self.advance()?;
},
In => {
self.advance()?;
break;
}
_ => {
return Err("Expected comma or 'in' keyword in variable declaration.")
}
}
}
// parse body
let body = self.parse_expr()?;
Ok(Expr::VarIn {
variables: variables,
body: Box::new(body)
})
}
/// Parses a primary expression (an identifier, a number or a parenthesized expression).
fn parse_primary(&mut self) -> Result<Expr, &'static str> {
match self.curr() {
Ident(_) => self.parse_id_expr(),
Number(_) => self.parse_nb_expr(),
LParen => self.parse_paren_expr(),
If => self.parse_conditional_expr(),
For => self.parse_for_expr(),
Var => self.parse_var_expr(),
_ => Err("Unknown expression.")
}
}
/// Parses a top-level expression and makes an anonymous function out of it,
/// for easier compilation.
fn parse_toplevel_expr(&mut self) -> Result<Function, &'static str> {
match self.parse_expr() {
Ok(expr) => {
Ok(Function {
prototype: Prototype {
name: ANONYMOUS_FUNCTION_NAME.to_string(),
args: vec![],
is_op: false,
prec: 0
},
body: expr,
is_anon: true
})
},
Err(err) => Err(err)
}
}
}
// ======================================================================================
// COMPILER =============================================================================
// ======================================================================================
/// Defines the `Expr` compiler.
pub struct Compiler<'a> {
pub context: &'a Context,
pub builder: &'a Builder,
pub fpm: &'a PassManager,
pub module: &'a Module,
pub function: &'a Function,
variables: HashMap<String, PointerValue>,
fn_value_opt: Option<FunctionValue>
}
impl<'a> Compiler<'a> {
/// Gets a defined function given its name.
#[inline]
fn get_function(&self, name: &str) -> Option<FunctionValue> {
self.module.get_function(name)
}
/// Returns the `FunctionValue` representing the function being compiled.
#[inline]
fn fn_value(&self) -> FunctionValue {
self.fn_value_opt.unwrap()
}
/// Cretes a new stack allocation instruction in the entry block of the function.
fn create_entry_block_alloca(&self, name: &str, entry: Option<&BasicBlock>) -> PointerValue {
let builder = self.context.create_builder();
let owned_entry = self.fn_value().get_entry_basic_block();
let entry = owned_entry.as_ref().or(entry).unwrap();
match entry.get_first_instruction() {
Some(first_instr) => builder.position_before(&first_instr),
None => builder.position_at_end(entry)
}
builder.build_alloca(self.context.f64_type(), name)
}
/// Compiles the specified `Expr` into an LLVM `FloatValue`.
fn compile_expr(&mut self, expr: &Expr) -> Result<FloatValue, &'static str> {
match *expr {
Expr::Number(nb) => Ok(self.context.f64_type().const_float(nb)),
Expr::Variable(ref name) => {
match self.variables.get(name.as_str()) {
Some(var) => Ok(self.builder.build_load(*var, name.as_str()).into_float_value()),
None => Err("Could not find a matching variable.")
}
},
Expr::VarIn { ref variables, ref body } => {
let mut old_bindings = Vec::new();
for &(ref var_name, ref initializer) in variables {
let var_name = var_name.as_str();
let initial_val = match *initializer {
Some(ref init) => self.compile_expr(init)?,
None => self.context.f64_type().const_float(0.)
};
let alloca = self.create_entry_block_alloca(var_name, None);
self.builder.build_store(alloca, initial_val);
if let Some(old_binding) = self.variables.remove(var_name) {
old_bindings.push(old_binding);
}
self.variables.insert(var_name.to_string(), alloca);
}
let body = self.compile_expr(body)?;
for binding in old_bindings {
self.variables.insert(binding.get_name().to_str().unwrap().to_string(), binding);
}
Ok(body)
},
Expr::Binary { op, ref left, ref right } => {
if op == '=' {
// handle assignement
let var_name = match *left.borrow() {
Expr::Variable(ref var_name) => var_name,
_ => {
return Err("Expected variable as left-hand operator of assignement.");
}
};
let var_val = self.compile_expr(right)?;
let var = self.variables.get(var_name.as_str()).ok_or("Undefined variable.")?;
self.builder.build_store(*var, var_val);
Ok(var_val)
} else {
let lhs = self.compile_expr(left)?;
let rhs = self.compile_expr(right)?;
match op {
'+' => Ok(self.builder.build_float_add(lhs, rhs, "tmpadd")),
'-' => Ok(self.builder.build_float_sub(lhs, rhs, "tmpsub")),
'*' => Ok(self.builder.build_float_mul(lhs, rhs, "tmpmul")),
'/' => Ok(self.builder.build_float_div(lhs, rhs, "tmpdiv")),
'<' => Ok({
let cmp = self.builder.build_float_compare(FloatPredicate::ULT, lhs, rhs, "tmpcmp");
self.builder.build_unsigned_int_to_float(cmp, self.context.f64_type(), "tmpbool")
}),
'>' => Ok({
let cmp = self.builder.build_float_compare(FloatPredicate::ULT, rhs, lhs, "tmpcmp");
self.builder.build_unsigned_int_to_float(cmp, self.context.f64_type(), "tmpbool")
}),
custom => {
let mut name = String::from("binary");
name.push(custom);
match self.get_function(name.as_str()) {
Some(fun) => {
match self.builder.build_call(fun, &[lhs.into(), rhs.into()], "tmpbin").try_as_basic_value().left() {
Some(value) => Ok(value.into_float_value()),
None => Err("Invalid call produced.")
}
},
None => Err("Undefined binary operator.")
}
}
}
}
},
Expr::Call { ref fn_name, ref args } => {
match self.get_function(fn_name.as_str()) {
Some(fun) => {
let mut compiled_args = Vec::with_capacity(args.len());
for arg in args {
compiled_args.push(self.compile_expr(arg)?);
}
let argsv: Vec<BasicValueEnum> = compiled_args.iter().by_ref().map(|&val| val.into()).collect();
match self.builder.build_call(fun, argsv.as_slice(), "tmp").try_as_basic_value().left() {
Some(value) => Ok(value.into_float_value()),
None => Err("Invalid call produced.")
}
},
None => Err("Unknown function.")
}
},
Expr::Conditional { ref cond, ref consequence, ref alternative } => {
let parent = self.fn_value();