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
// A hash map of the variables by scope level in the parser.

use std::collections::HashMap;

use crate::ast::{Argument, VarType};

use super::{Function, Statement, Variable};

// A struct to hold the context of the parser.
#[derive(Debug)]
pub struct Context {
  // The current scope level.
  pub scope_level: usize,
  // A hash map of the variables by scope level in the parser.
  pub variables: HashMap<usize, Vec<Variable>>,

  /// Function definitions
  pub functions: HashMap<String, Function>,

  pub optimization_level: u8,
}

impl Context {
  pub fn new(optimization_level: u8) -> Self {
    Self {
      scope_level: 0,
      optimization_level,
      variables: HashMap::new(),
      functions: HashMap::new(),
    }
  }

  pub fn push_scope(&mut self) {
    self.scope_level += 1;
  }

  pub fn pop_scope(&mut self) {
    self.scope_level -= 1;
  }

  pub fn add_variable(&mut self, statement: Statement) {
    let variable = statement.into();

    if let Some(variables) = self.variables.get_mut(&self.scope_level) {
      variables.push(variable);
    } else {
      self.variables.insert(self.scope_level, vec![variable]);
    }
  }

  pub fn get_variable(&self, name: String) -> Option<&Variable> {
    for scope in (0..=self.scope_level).rev() {
      if let Some(variables) = self.variables.get(&scope) {
        for variable in variables {
          if variable.name == name {
            return Some(variable);
          }
        }
      }
    }

    None
  }

  pub fn add_function(&mut self, function: &Function) -> Result<(), String> {
    if self.functions.contains_key(&function.name) {
      return Err(format!("Function `{}` already defined", function.name));
    }

    self
      .functions
      .insert(function.name.clone(), function.clone());

    Ok(())
  }

  pub fn get_function(&self, name: &str) -> Option<Function> {
    self
      .builtins()
      .iter()
      .find(|f| f.name == name)
      .cloned()
      .or_else(|| self.functions.get(name).cloned())
  }

  fn builtins(&self) -> Vec<Function> {
    vec![
      Function {
        name: "write_string".to_string(),
        body: vec![],
        args: vec![Argument {
          name: "message".to_string(),
          var_type: VarType::Str,
        }],
        return_type: VarType::Void,
        location: 0..0,
        is_builtin: true,
      },
      Function {
        name: "write_int".to_string(),
        body: vec![],
        args: vec![Argument {
          name: "number".to_string(),
          var_type: VarType::I32,
        }],
        return_type: VarType::Void,
        location: 0..0,
        is_builtin: true,
      },
      Function {
        name: "read_int".to_string(),
        body: vec![],
        args: vec![],
        return_type: VarType::I32,
        location: 0..0,
        is_builtin: true,
      },
      Function {
        name: "read_string".to_string(),
        body: vec![],
        args: vec![Argument {
          name: "size".to_string(),
          var_type: VarType::U32,
        }],
        return_type: VarType::Str,
        location: 0..0,
        is_builtin: true,
      },
    ]
  }
}

impl Default for Context {
  fn default() -> Self {
    Self::new(0)
  }
}

impl From<Statement> for Variable {
  fn from(statement: Statement) -> Self {
    match statement {
      Statement::VariableDeclaration(var) => var,
      _ => panic!("Cannot convert statement to variable"),
    }
  }
}