Struct flexi_parse::token::Ident

source ·
pub struct Ident { /* private fields */ }
Expand description

An identifier consisting of alphanumeric characters and underscores, and starting with an alphabetic character or an underscore.

Implementations§

source§

impl Ident

source

pub const fn string(&self) -> &String

Returns the text that makes up the identifier.

Examples found in repository?
examples/lox/resolver.rs (line 40)
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
    fn declare(&mut self, name: &Ident) {
        if let Some(scope) = self.scopes.last_mut() {
            if scope.contains_key(name.string()) {
                self.error(new_error(
                    "Already a variable with this name in scope".to_string(),
                    name,
                    error_codes::SHADOW,
                ));
            } else {
                scope.insert(name.string().to_owned(), false);
            }
        }
    }

    fn define(&mut self, name: &Ident) {
        if let Some(scope) = self.scopes.last_mut() {
            scope.insert(name.string().to_owned(), true);
        }
    }

    fn resolve_local(&self, name: &Ident, distance: &Cell<Option<usize>>) {
        for (i, scope) in self.scopes.iter().enumerate().rev() {
            if scope.contains_key(name.string()) {
                distance.set(Some(self.scopes.len() - 1 - i));
                return;
            }
        }
    }

    fn error(&mut self, error: Error) {
        if let Some(existing_error) = &mut self.error {
            existing_error.add(error);
        } else {
            self.error = Some(error);
        }
    }

    fn begin_scope(&mut self) {
        self.scopes.push(HashMap::new());
    }

    fn end_scope(&mut self) {
        self.scopes.pop();
    }
}

impl Expr {
    fn resolve(&self, state: &mut State) {
        match self {
            Expr::Assign {
                name,
                value,
                distance,
            } => {
                value.resolve(state);
                state.resolve_local(name, distance);
            }
            Expr::Binary(binary) => {
                binary.left().resolve(state);
                binary.right().resolve(state);
            }
            Expr::Call {
                callee,
                paren: _,
                arguments,
            } => {
                callee.resolve(state);
                for argument in arguments {
                    argument.resolve(state);
                }
            }
            Expr::Get { object, name: _ } => object.resolve(state),
            Expr::Group(expr) => expr.resolve(state),
            Expr::Literal(_) => {}
            Expr::Logical(logical) => {
                logical.left().resolve(state);
                logical.right().resolve(state);
            }
            Expr::Set {
                object,
                name: _,
                value,
            } => {
                object.resolve(state);
                value.resolve(state);
            }
            Expr::Super {
                keyword,
                distance,
                dot: _,
                method: _,
            } => {
                if state.current_class == ClassType::None {
                    state.error(new_error(
                        "Can't use 'super' outside of a class".to_string(),
                        keyword,
                        error_codes::INVALID_SUPER,
                    ));
                } else if state.current_class == ClassType::Class {
                    state.error(new_error(
                        "Can't use 'super' in a class with no superclass".to_string(),
                        keyword,
                        error_codes::INVALID_SUPER,
                    ));
                }
                state.resolve_local(keyword.ident(), distance);
            }
            Expr::This { keyword, distance } => {
                if state.current_class == ClassType::None {
                    state.error(new_error(
                        "Can't use 'this' outside of a class".to_string(),
                        keyword,
                        error_codes::THIS_OUTSIDE_CLASS,
                    ));
                }

                state.resolve_local(keyword.ident(), distance);
            }
            Expr::Unary(unary) => unary.right().resolve(state),
            Expr::Variable { name, distance } => {
                if let Some(scope) = state.scopes.last() {
                    if scope.get(name.string()) == Some(&false) {
                        state.error(new_error(
                            "Can't read a variable in its own intialiser".to_string(),
                            name,
                            error_codes::INVALID_INITIALISER,
                        ));
                    }
                }
                state.resolve_local(name, distance);
            }
        }
    }
}

impl Function {
    fn resolve(&self, state: &mut State, kind: FunctionType) {
        let enclosing = state.current_function;
        state.current_function = kind;
        state.begin_scope();
        for param in &self.params {
            state.declare(param);
            state.define(param);
        }
        for stmt in &self.body {
            stmt.resolve(state);
        }
        state.end_scope();
        state.current_function = enclosing;
    }
}

impl Stmt {
    fn resolve(&self, state: &mut State) {
        match self {
            Stmt::Block(stmts) => {
                state.begin_scope();
                for stmt in stmts {
                    stmt.resolve(state);
                }
                state.end_scope();
            }
            Stmt::Class {
                name,
                superclass,
                superclass_distance,
                methods,
            } => {
                let enclosing = state.current_class;
                state.current_class = ClassType::Class;

                state.declare(name);
                state.define(name);

                if let Some(superclass) = superclass {
                    if name.string() == superclass.string() {
                        state.error(new_error(
                            "A class can't inherit from itself".to_string(),
                            superclass,
                            error_codes::CYCLICAL_INHERITANCE,
                        ));
                    }

                    state.current_class = ClassType::SubClass;

                    state.resolve_local(superclass, superclass_distance);

                    state.begin_scope();
                    state
                        .scopes
                        .last_mut()
                        .unwrap()
                        .insert("super".to_string(), true);
                }

                state.begin_scope();
                state
                    .scopes
                    .last_mut()
                    .unwrap()
                    .insert("this".to_string(), true);

                for method in methods {
                    let kind = if method.name.string() == "init" {
                        FunctionType::Initialiser
                    } else {
                        FunctionType::Method
                    };
                    method.resolve(state, kind);
                }

                state.end_scope();

                if superclass.is_some() {
                    state.end_scope();
                }

                state.current_class = enclosing;
            }
            Stmt::Expr(expr) | Stmt::Print(expr) => expr.resolve(state),
            Stmt::Function(function) => {
                state.declare(&function.name);
                state.declare(&function.name);
                function.resolve(state, FunctionType::Function);
            }
            Stmt::If {
                condition,
                then_branch,
                else_branch,
            } => {
                condition.resolve(state);
                then_branch.resolve(state);
                if let Some(else_branch) = else_branch {
                    else_branch.resolve(state);
                }
            }
            Stmt::Return { keyword, value } => {
                if state.current_function == FunctionType::None {
                    state.error(new_error(
                        "Can't return from top-level code".to_string(),
                        keyword,
                        error_codes::RETURN_OUTSIDE_FUNCTION,
                    ));
                }
                if let Some(value) = value {
                    value.resolve(state);
                }
            }
            Stmt::Variable { name, initialiser } => {
                state.declare(name);
                if let Some(initialiser) = initialiser {
                    initialiser.resolve(state);
                }
                state.define(name);
            }
            Stmt::While { condition, body } => {
                condition.resolve(state);
                body.resolve(state);
            }
        }
    }
More examples
Hide additional examples
examples/lox/interpreter.rs (line 124)
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
    fn call(&self, arguments: Vec<Value>, parentheses: &Parentheses) -> Result<Value> {
        let state = self.closure.start_scope();
        if self.declaration.params.len() != arguments.len() {
            return Err(arity_error(
                parentheses,
                self.declaration.params.len(),
                arguments.len(),
            ));
        }
        for (name, arg) in self.declaration.params.iter().zip(arguments) {
            state
                .environment
                .borrow_mut()
                .define(name.string().to_owned(), arg);
        }
        for stmt in &self.declaration.body {
            if let Some(value) = stmt.execute(&state)? {
                return Ok(value);
            }
        }
        Ok(Value::Nil)
    }

    fn bind(&self, instance: &'static RefCell<Instance>) -> Function {
        let scope = self.closure.start_scope();
        scope
            .environment
            .borrow_mut()
            .define("this".to_string(), Value::Instance(instance));
        Function {
            declaration: self.declaration.clone(),
            closure: scope,
            is_initialiser: self.is_initialiser,
        }
    }
}

impl PartialEq for Function {
    fn eq(&self, other: &Self) -> bool {
        self.declaration == other.declaration
    }
}

#[derive(Debug, Clone, PartialEq)]
struct Class {
    name: String,
    superclass: Option<Rc<Class>>,
    methods: HashMap<String, Function>,
}

impl Class {
    const fn new(
        name: String,
        superclass: Option<Rc<Class>>,
        methods: HashMap<String, Function>,
    ) -> Class {
        Class {
            name,
            superclass,
            methods,
        }
    }

    fn find_method(&self, name: &str) -> Option<&Function> {
        self.methods.get(name).map_or_else(
            || {
                self.superclass
                    .as_ref()
                    .and_then(|superclass| superclass.find_method(name))
            },
            Some,
        )
    }

    fn arity(&self) -> usize {
        self.find_method("init")
            .map_or(0, |f| f.declaration.params.len())
    }
}

#[derive(Clone, PartialEq)]
struct Instance {
    class: Rc<Class>,
    fields: HashMap<String, Value>,
}

impl Instance {
    fn new(class: Rc<Class>) -> Instance {
        Instance {
            class,
            fields: HashMap::new(),
        }
    }

    fn set(&mut self, name: &Ident, value: Value) {
        self.fields.insert(name.string().to_string(), value);
    }
}

fn get(instance: &'static RefCell<Instance>, name: &Ident) -> Result<Value> {
    let this = instance.borrow();
    if let Some(value) = this.fields.get(name.string()) {
        Ok(value.to_owned())
    } else if let Some(function) = this.class.find_method(name.string()) {
        Ok(Value::Function(function.bind(instance)))
    } else {
        Err(new_error(
            format!("Undefined property '{}'", name.string()),
            name,
            error_codes::UNDEFINED_NAME,
        ))
    }
}

impl fmt::Debug for Instance {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Instance")
            .field("class", &self.class.name)
            .field("fields", &self.fields)
            .finish()
    }
}

#[derive(Debug, Clone, PartialEq)]
enum Value {
    Nil,
    String(String),
    Number(f64),
    Bool(bool),
    Native(NativeFunction),
    Function(Function),
    Class(Rc<Class>),
    Instance(&'static RefCell<Instance>),
}

fn arity_error(parentheses: &Parentheses, expected: usize, actual: usize) -> Error {
    new_error(
        format!("Expected {expected} arguments but got {actual}"),
        parentheses.span().to_owned(),
        error_codes::INCORRECT_ARITY,
    )
}

impl Value {
    const fn as_class(&self) -> Option<&Rc<Class>> {
        if let Value::Class(class) = self {
            Some(class)
        } else {
            None
        }
    }

    const fn as_instance(&self) -> Option<&'static RefCell<Instance>> {
        if let Value::Instance(instance) = self {
            Some(*instance)
        } else {
            None
        }
    }

    const fn is_truthy(&self) -> bool {
        !matches!(self, Value::Nil | Value::Bool(false))
    }

    fn add(&self, op: &Punct!["+"], other: &Value) -> Result<Value> {
        match (self, other) {
            (Value::Number(n1), Value::Number(n2)) => Ok(Value::Number(n1 + n2)),
            (Value::String(s1), Value::String(s2)) => Ok(Value::String(s1.to_owned() + s2)),
            _ => Err(new_error(
                format!("Can't add '{self}' to '{other}'"),
                op,
                error_codes::TYPE_ERROR,
            )),
        }
    }

    fn sub(&self, op: &Punct!["-"], other: &Value) -> Result<Value> {
        if let (Value::Number(n1), Value::Number(n2)) = (self, other) {
            Ok(Value::Number(n1 - n2))
        } else {
            Err(new_error(
                format!("Can't subtract '{other}' from '{self}'"),
                op,
                error_codes::TYPE_ERROR,
            ))
        }
    }

    fn mul(&self, op: &Punct!["*"], other: &Value) -> Result<Value> {
        if let (Value::Number(n1), Value::Number(n2)) = (self, other) {
            Ok(Value::Number(n1 * n2))
        } else {
            Err(new_error(
                format!("Can't multiply '{self}' by '{other}'"),
                op,
                error_codes::TYPE_ERROR,
            ))
        }
    }

    fn div(&self, op: &Punct!["/"], other: &Value) -> Result<Value> {
        if let (Value::Number(n1), Value::Number(n2)) = (self, other) {
            Ok(Value::Number(n1 / n2))
        } else {
            Err(new_error(
                format!("Can't divide '{other}' by '{self}'"),
                op,
                error_codes::TYPE_ERROR,
            ))
        }
    }

    fn neg(&self, op: &Punct!["-"]) -> Result<Value> {
        if let Value::Number(n) = self {
            Ok(Value::Number(-n))
        } else {
            Err(new_error(
                format!("Can't negate '{self}'"),
                op,
                error_codes::TYPE_ERROR,
            ))
        }
    }

    fn cmp<T: Token>(&self, op: &T, other: &Value) -> Result<Ordering> {
        if self == other {
            return Ok(Ordering::Equal);
        }

        match (self, other) {
            (Value::String(s1), Value::String(s2)) => Ok(s1.cmp(s2).into()),
            (Value::Number(n1), Value::Number(n2)) => Ok(n1.partial_cmp(n2).into()),
            (Value::Bool(b1), Value::Bool(b2)) => Ok(b1.cmp(b2).into()),
            _ => Err(new_error(
                format!("Can't compare '{self}' with '{other}'"),
                op,
                error_codes::TYPE_ERROR,
            )),
        }
    }

    fn call(&self, arguments: Vec<Value>, parentheses: &Parentheses) -> Result<Value> {
        match self {
            Value::Native(NativeFunction {
                function, arity, ..
            }) => {
                if *arity != arguments.len() {
                    return Err(arity_error(parentheses, *arity, arguments.len()));
                }
                function(arguments)
            }
            Value::Function(function) => function.call(arguments, parentheses),
            Value::Class(class) => {
                if class.arity() != arguments.len() {
                    return Err(arity_error(parentheses, class.arity(), arguments.len()));
                }

                let instance = allocate(Instance::new(Rc::clone(class)));
                if let Some(initialiser) = class.find_method("init") {
                    initialiser.bind(instance).call(arguments, parentheses)?;
                }
                Ok(Value::Instance(instance))
            }
            Value::Nil
            | Value::String(_)
            | Value::Number(_)
            | Value::Bool(_)
            | Value::Instance(_) => Err(new_error(
                format!("Can't call '{self}'"),
                parentheses.span().clone(),
                error_codes::TYPE_ERROR,
            )),
        }
    }
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Nil => f.write_str("nil"),
            Value::String(s) => f.write_str(s),
            Value::Number(n) => write!(f, "{n}"),
            Value::Bool(b) => write!(f, "{b}"),
            Value::Native(NativeFunction { name, .. }) => write!(f, "<native fn '{name}'>"),
            Value::Function(Function {
                declaration: FunctionDecl { name, .. },
                ..
            }) => write!(f, "<fn {}>", name.string()),
            Value::Class(class) => f.write_str(&class.name),
            Value::Instance(instance) => write!(f, "'{}' instance", instance.borrow().class.name),
        }
    }
}

#[derive(Debug, Clone)]
struct State {
    environment: Rc<RefCell<Environment>>,
    globals: Rc<RefCell<Environment>>,
}

impl State {
    fn new() -> Self {
        let mut values = HashMap::new();

        values.insert(
            "clock".to_string(),
            Value::Native(NativeFunction {
                function: natives::clock,
                arity: 0,
                name: "clock",
            }),
        );

        let environment = Rc::new(RefCell::new(Environment {
            values,
            enclosing: None,
            sub: vec![],
            mark: Cell::new(false),
        }));

        State {
            environment: Rc::clone(&environment),
            globals: environment,
        }
    }

    #[must_use]
    fn start_scope(&self) -> State {
        let environment = Rc::new(RefCell::new(Environment {
            values: HashMap::new(),
            enclosing: Some(Rc::clone(&self.environment)),
            sub: vec![],
            mark: Cell::new(false),
        }));
        self.environment
            .borrow_mut()
            .sub
            .push(Rc::downgrade(&environment));
        State {
            environment,
            globals: Rc::clone(&self.globals),
        }
    }

    fn super_scope(self) -> Option<State> {
        Some(State {
            environment: Rc::clone(self.environment.borrow().enclosing.as_ref()?),
            globals: self.globals,
        })
    }
}

fn allocate<T>(value: T) -> &'static RefCell<T> {
    Box::leak(Box::new(RefCell::new(value)))
}

struct Environment {
    values: HashMap<String, Value>,
    enclosing: Option<Rc<RefCell<Environment>>>,
    sub: Vec<Weak<RefCell<Environment>>>,
    mark: Cell<bool>,
}

impl Environment {
    fn get(&self, name: &Ident) -> Result<Value> {
        self.values.get(name.string()).map_or_else(
            || {
                self.enclosing.as_ref().map_or_else(
                    || {
                        Err(new_error(
                            format!("Undefined variable '{}'", name.string()),
                            name,
                            error_codes::UNDEFINED_NAME,
                        ))
                    },
                    |enclosing| enclosing.borrow().get(name),
                )
            },
            |value| Ok(value.to_owned()),
        )
    }

    fn get_at(&self, name: &Ident, distance: usize) -> Result<Value> {
        if distance == 0 {
            self.get(name)
        } else {
            self.enclosing
                .as_ref()
                .unwrap()
                .borrow()
                .get_at(name, distance - 1)
        }
    }

    fn define(&mut self, name: String, value: Value) {
        self.values.insert(name, value);
    }

    fn assign(&mut self, name: &Ident, value: Value) -> Result<()> {
        if self.values.contains_key(name.string()) {
            self.values.insert(name.string().clone(), value);
            Ok(())
        } else if let Some(enclosing) = &self.enclosing {
            enclosing.borrow_mut().assign(name, value)
        } else {
            Err(new_error(
                format!("Undefined variable '{}'", name.string()),
                name,
                error_codes::UNDEFINED_NAME,
            ))
        }
    }

    fn assign_at(&mut self, name: &Ident, value: Value, distance: usize) -> Result<()> {
        if distance == 0 {
            self.assign(name, value)
        } else {
            self.enclosing
                .as_ref()
                .unwrap()
                .borrow_mut()
                .assign_at(name, value, distance - 1)
        }
    }
}

struct EnvValuesDebug<'a>(&'a HashMap<String, Value>);

impl fmt::Debug for EnvValuesDebug<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_map()
            .entries(self.0.iter().map(|(k, v)| (k, v.to_string())))
            .finish()
    }
}

impl fmt::Debug for Environment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Environment")
            .field("values", &EnvValuesDebug(&self.values))
            .field("enclosing", &self.enclosing)
            .field("sub", &self.sub)
            .field("mark", &self.mark)
            .finish()
    }
}

impl Binary {
    fn evaluate(&self, state: &State) -> Result<Value> {
        match self {
            Binary::Mul(left, op, right) => left.evaluate(state)?.mul(op, &right.evaluate(state)?),
            Binary::Div(left, op, right) => left.evaluate(state)?.div(op, &right.evaluate(state)?),
            Binary::Add(left, op, right) => left.evaluate(state)?.add(op, &right.evaluate(state)?),
            Binary::Sub(left, op, right) => left.evaluate(state)?.sub(op, &right.evaluate(state)?),
            Binary::Equal(left, _, right) => {
                Ok(Value::Bool(left.evaluate(state)? == right.evaluate(state)?))
            }
            Binary::NotEqual(left, _, right) => {
                Ok(Value::Bool(left.evaluate(state)? != right.evaluate(state)?))
            }
            Binary::Greater(left, op, right) => Ok(Value::Bool(
                left.evaluate(state)?.cmp(op, &right.evaluate(state)?)?.gt(),
            )),
            Binary::GreaterEqual(left, op, right) => Ok(Value::Bool(
                left.evaluate(state)?.cmp(op, &right.evaluate(state)?)?.ge(),
            )),
            Binary::Less(left, op, right) => Ok(Value::Bool(
                left.evaluate(state)?.cmp(op, &right.evaluate(state)?)?.lt(),
            )),
            Binary::LessEqual(left, op, right) => Ok(Value::Bool(
                left.evaluate(state)?.cmp(op, &right.evaluate(state)?)?.le(),
            )),
        }
    }
}

impl Literal {
    fn evaluate(&self) -> Value {
        match self {
            Literal::False(_) => Value::Bool(false),
            Literal::Float(value) => Value::Number(value.value()),
            #[allow(clippy::cast_precision_loss)]
            Literal::Int(value) => Value::Number(value.value() as f64),
            Literal::Nil(_) => Value::Nil,
            Literal::String(string) => Value::String(string.string().clone()),
            Literal::True(_) => Value::Bool(true),
        }
    }
}

impl Logical {
    fn evaluate(&self, state: &State) -> Result<Value> {
        match self {
            Logical::And(left, _, right) => {
                let left = left.evaluate(state)?;
                if left.is_truthy() {
                    Ok(left)
                } else {
                    right.evaluate(state)
                }
            }
            Logical::Or(left, _, right) => {
                let left = left.evaluate(state)?;
                if left.is_truthy() {
                    right.evaluate(state)
                } else {
                    Ok(left)
                }
            }
        }
    }
}

impl Unary {
    fn evaluate(&self, state: &State) -> Result<Value> {
        match self {
            Unary::Neg(op, expr) => expr.evaluate(state)?.neg(op),
            Unary::Not(_, expr) => Ok(Value::Bool(!expr.evaluate(state)?.is_truthy())),
        }
    }
}

impl Expr {
    fn evaluate(&self, state: &State) -> Result<Value> {
        match self {
            Expr::Assign {
                name,
                value,
                distance,
            } => {
                let value = value.evaluate(state)?;
                if let Some(distance) = distance.get() {
                    state
                        .environment
                        .borrow_mut()
                        .assign_at(name, value.clone(), distance)?;
                } else {
                    state.globals.borrow_mut().assign(name, value.clone())?;
                }
                Ok(value)
            }
            Expr::Binary(binary) => binary.evaluate(state),
            Expr::Call {
                callee,
                paren,
                arguments,
            } => {
                let callee = callee.evaluate(state)?;
                let mut evaluated_args = Vec::with_capacity(arguments.len());
                for arg in arguments {
                    evaluated_args.push(arg.evaluate(state)?);
                }
                callee.call(evaluated_args, paren)
            }
            Expr::Get { object, name } => {
                if let Value::Instance(instance) = object.evaluate(state)? {
                    get(instance, name)
                } else {
                    Err(new_error(
                        "Only instances have properties".to_string(),
                        name,
                        error_codes::TYPE_ERROR,
                    ))
                }
            }
            Expr::Group(expr) => expr.evaluate(state),
            Expr::Literal(literal) => Ok(literal.evaluate()),
            Expr::Logical(logical) => logical.evaluate(state),
            Expr::Set {
                object,
                name,
                value,
            } => {
                if let Value::Instance(instance) = object.evaluate(state)? {
                    let value = value.evaluate(state)?;
                    instance.borrow_mut().set(name, value.clone());
                    Ok(value)
                } else {
                    Err(new_error(
                        "Only instances have fields".to_string(),
                        name,
                        error_codes::TYPE_ERROR,
                    ))
                }
            }
            Expr::Super {
                keyword,
                distance,
                dot: _,
                method,
            } => {
                let superclass = state
                    .environment
                    .borrow()
                    .get_at(keyword.ident(), distance.clone().into_inner().unwrap())?;

                let object = state.environment.borrow().get_at(
                    &Ident::new("this".to_string(), keyword.span().clone()),
                    distance.clone().into_inner().unwrap() - 1,
                )?;

                superclass
                    .as_class()
                    .unwrap()
                    .find_method(method.string())
                    .map_or_else(
                        || {
                            Err(new_error(
                                format!("Undefined property '{}'", method.string()),
                                method,
                                error_codes::UNDEFINED_NAME,
                            ))
                        },
                        |method| Ok(Value::Function(method.bind(object.as_instance().unwrap()))),
                    )
            }
            Expr::This { keyword, distance } => distance.get().map_or_else(
                || state.globals.borrow().get(keyword.ident()),
                |distance| state.environment.borrow().get_at(keyword.ident(), distance),
            ),
            Expr::Unary(unary) => unary.evaluate(state),
            Expr::Variable { name, distance } => distance.get().map_or_else(
                || state.globals.borrow().get(name),
                |distance| state.environment.borrow().get_at(name, distance),
            ),
        }
    }
}

macro_rules! propagate_return {
    ( $expr:expr ) => {
        if let Some(_tmp) = $expr {
            return Ok(Some(_tmp));
        }
    };
}

impl Stmt {
    fn execute(&self, state: &State) -> Result<Option<Value>> {
        match self {
            Stmt::Block(stmts) => {
                let inner_state = state.start_scope();
                for stmt in stmts {
                    propagate_return!(stmt.execute(&inner_state)?);
                }
            }
            Stmt::Class {
                name,
                superclass,
                superclass_distance,
                methods,
            } => {
                let superclass = if let Some(superclass_name) = superclass {
                    let superclass = Expr::Variable {
                        name: superclass_name.clone(),
                        distance: superclass_distance.clone(),
                    }
                    .evaluate(state)?;
                    if let Value::Class(superclass) = superclass {
                        Some(superclass)
                    } else {
                        return Err(new_error(
                            "Superclass must be a class".to_string(),
                            superclass_name,
                            error_codes::INHERIT_FROM_VALUE,
                        ));
                    }
                } else {
                    None
                };

                state
                    .environment
                    .borrow_mut()
                    .define(name.string().to_owned(), Value::Nil);

                let superclass_is_some = superclass.is_some();
                let mut state = superclass.as_ref().map_or_else(
                    || state.clone(),
                    |superclass| {
                        let state = state.start_scope();
                        state
                            .environment
                            .borrow_mut()
                            .define("super".to_string(), Value::Class(Rc::clone(superclass)));
                        state
                    },
                );

                let methods = methods
                    .iter()
                    .map(|declaration| {
                        (
                            declaration.name.string().to_owned(),
                            Function::new(
                                declaration.clone(),
                                state.clone(),
                                declaration.name.string() == "init",
                            ),
                        )
                    })
                    .collect();
                let class = Class::new(name.string().to_owned(), superclass, methods);

                if superclass_is_some {
                    state = state.super_scope().unwrap();
                }

                state
                    .environment
                    .borrow_mut()
                    .assign(name, Value::Class(Rc::new(class)))?;
            }
            Stmt::Expr(expr) => {
                expr.evaluate(state)?;
            }
            Stmt::Function(function) => {
                let value =
                    Value::Function(Function::new(function.to_owned(), state.clone(), false));
                state
                    .environment
                    .borrow_mut()
                    .define(function.name.string().to_owned(), value);
            }
            Stmt::If {
                condition,
                then_branch,
                else_branch,
            } => {
                if condition.evaluate(state)?.is_truthy() {
                    propagate_return!(then_branch.execute(state)?);
                } else if let Some(else_branch) = else_branch {
                    propagate_return!(else_branch.execute(state)?);
                }
            }
            Stmt::Print(expr) => {
                let value = expr.evaluate(state)?;
                println!("{value}");
            }
            Stmt::Return { keyword: _, value } => {
                return Ok(Some(
                    value
                        .as_ref()
                        .map_or(Ok(Value::Nil), |v| v.evaluate(state))?,
                ));
            }
            Stmt::Variable { name, initialiser } => {
                let value = if let Some(initialiser) = initialiser {
                    initialiser.evaluate(state)?
                } else {
                    Value::Nil
                };
                state
                    .environment
                    .borrow_mut()
                    .define(name.string().to_owned(), value);
            }
            Stmt::While { condition, body } => {
                while condition.evaluate(state)?.is_truthy() {
                    propagate_return!(body.execute(state)?);
                }
            }
        }

        Ok(None)
    }
source

pub const fn new(string: String, span: Span) -> Ident

Creates a new identifier in the given ParseStream with the given string.

Examples found in repository?
examples/lox/interpreter.rs (line 708)
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
    fn evaluate(&self, state: &State) -> Result<Value> {
        match self {
            Expr::Assign {
                name,
                value,
                distance,
            } => {
                let value = value.evaluate(state)?;
                if let Some(distance) = distance.get() {
                    state
                        .environment
                        .borrow_mut()
                        .assign_at(name, value.clone(), distance)?;
                } else {
                    state.globals.borrow_mut().assign(name, value.clone())?;
                }
                Ok(value)
            }
            Expr::Binary(binary) => binary.evaluate(state),
            Expr::Call {
                callee,
                paren,
                arguments,
            } => {
                let callee = callee.evaluate(state)?;
                let mut evaluated_args = Vec::with_capacity(arguments.len());
                for arg in arguments {
                    evaluated_args.push(arg.evaluate(state)?);
                }
                callee.call(evaluated_args, paren)
            }
            Expr::Get { object, name } => {
                if let Value::Instance(instance) = object.evaluate(state)? {
                    get(instance, name)
                } else {
                    Err(new_error(
                        "Only instances have properties".to_string(),
                        name,
                        error_codes::TYPE_ERROR,
                    ))
                }
            }
            Expr::Group(expr) => expr.evaluate(state),
            Expr::Literal(literal) => Ok(literal.evaluate()),
            Expr::Logical(logical) => logical.evaluate(state),
            Expr::Set {
                object,
                name,
                value,
            } => {
                if let Value::Instance(instance) = object.evaluate(state)? {
                    let value = value.evaluate(state)?;
                    instance.borrow_mut().set(name, value.clone());
                    Ok(value)
                } else {
                    Err(new_error(
                        "Only instances have fields".to_string(),
                        name,
                        error_codes::TYPE_ERROR,
                    ))
                }
            }
            Expr::Super {
                keyword,
                distance,
                dot: _,
                method,
            } => {
                let superclass = state
                    .environment
                    .borrow()
                    .get_at(keyword.ident(), distance.clone().into_inner().unwrap())?;

                let object = state.environment.borrow().get_at(
                    &Ident::new("this".to_string(), keyword.span().clone()),
                    distance.clone().into_inner().unwrap() - 1,
                )?;

                superclass
                    .as_class()
                    .unwrap()
                    .find_method(method.string())
                    .map_or_else(
                        || {
                            Err(new_error(
                                format!("Undefined property '{}'", method.string()),
                                method,
                                error_codes::UNDEFINED_NAME,
                            ))
                        },
                        |method| Ok(Value::Function(method.bind(object.as_instance().unwrap()))),
                    )
            }
            Expr::This { keyword, distance } => distance.get().map_or_else(
                || state.globals.borrow().get(keyword.ident()),
                |distance| state.environment.borrow().get_at(keyword.ident(), distance),
            ),
            Expr::Unary(unary) => unary.evaluate(state),
            Expr::Variable { name, distance } => distance.get().map_or_else(
                || state.globals.borrow().get(name),
                |distance| state.environment.borrow().get_at(name, distance),
            ),
        }
    }

Trait Implementations§

source§

impl Clone for Ident

source§

fn clone(&self) -> Ident

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Ident

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Hash for Ident

source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl Ord for Ident

source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl Parse for Ident

source§

fn parse(input: ParseStream<'_>) -> Result<Self>

Parses the input into this type. Read more
source§

impl PartialEq for Ident

source§

fn eq(&self, other: &Self) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd for Ident

source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl ToTokens for Ident

source§

fn to_tokens(&self, tokens: &mut TokenStream)

Append self to the given TokenStream.
source§

fn into_token_stream(self) -> TokenStream

Convert self directly into a TokenStream.
source§

fn to_token_stream(&self) -> TokenStream

Convert self directly into a TokenStream.
source§

impl Token for Ident

source§

fn span(&self) -> &Span

Returns the span covered by this token.
source§

impl Eq for Ident

Auto Trait Implementations§

§

impl RefUnwindSafe for Ident

§

impl Send for Ident

§

impl Sync for Ident

§

impl Unpin for Ident

§

impl UnwindSafe for Ident

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.