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//! # Semantic Analysis
//!
//! This module performs semantic analysis on the AST, including type checking,
//! symbol resolution, and validation of language semantics. It ensures the
//! program is semantically correct before code generation.
//!
//! ## Analysis Phases
//!
//! 1. **Symbol Collection**: Gather all declarations and build symbol tables
//! 2. **Type Checking**: Verify type compatibility in expressions and assignments
//! 3. **Scope Resolution**: Ensure variables are declared before use
//! 4. **Control Flow Validation**: Check loop and conditional constructs
//!
//! ## Symbol Tables
//!
//! Maintains scoped symbol tables for variables, functions, and types.
//! Handles nested scopes for blocks, functions, and control structures.
use crate::ast::*;
use crate::error::SemanticError;
use std::collections::HashMap;
/// Represents the semantic analyzer.
pub struct SemanticAnalyzer {
/// Global function symbols: name -> (return_type, param_types, is_variadic)
functions: HashMap<String, (Type, Vec<Type>, bool)>,
/// Stack of scopes for variables: each scope is name -> type
scopes: Vec<HashMap<String, Type>>,
/// Collected errors
errors: Vec<SemanticError>,
}
impl Default for SemanticAnalyzer {
fn default() -> Self {
Self::new()
}
}
impl SemanticAnalyzer {
/// Creates a new semantic analyzer.
pub fn new() -> Self {
Self {
functions: HashMap::new(),
scopes: vec![HashMap::new()], // Global scope
errors: Vec::new(),
}
}
/// Analyzes the program and returns any semantic errors.
pub fn analyze(&mut self, program: &Program) -> Vec<SemanticError> {
self.collect_functions(program);
for function in &program.functions {
self.analyze_function(function);
}
self.errors.clone()
}
/// Collects function declarations into the global symbol table.
fn collect_functions(&mut self, program: &Program) {
for function in &program.functions {
let param_types: Vec<Type> = function.params.iter().map(|(ty, _)| *ty).collect();
if self.functions.contains_key(&function.name) {
self.errors
.push(SemanticError::DuplicateVariable(function.name.clone()));
} else {
self.functions.insert(
function.name.clone(),
(function.return_ty, param_types, false),
);
}
}
for extern_func in &program.extern_functions {
if self.functions.contains_key(&extern_func.name) {
self.errors
.push(SemanticError::DuplicateVariable(extern_func.name.clone()));
} else {
self.functions.insert(
extern_func.name.clone(),
(
extern_func.return_ty,
extern_func.param_types.clone(),
extern_func.is_variadic,
),
);
}
}
// Handle includes: map known headers to builtin externs
for header in &program.includes {
if header == "stdio.h" {
// ensure printf is available: extern int printf(string, ...);
if !self.functions.contains_key("printf") {
self.functions
.insert("printf".to_string(), (Type::Int, vec![Type::String], true));
}
}
}
}
/// Analyzes a single function.
fn analyze_function(&mut self, function: &Function) {
// Enter function scope
self.scopes.push(HashMap::new());
// Add parameters to scope
for (ty, name) in &function.params {
self.scopes.last_mut().unwrap().insert(name.clone(), *ty);
}
// Analyze body
self.check_stmt(&function.body);
// Check return type if body has return
// For simplicity, assume functions return correctly
// TODO: Check return statements match function return type
// Pop function scope
self.scopes.pop();
}
/// Checks a statement.
fn check_stmt(&mut self, stmt: &Stmt) {
match stmt {
Stmt::Declaration { ty, name, init } => {
if self.scopes.last().unwrap().contains_key(name) {
self.errors
.push(SemanticError::DuplicateVariable(name.clone()));
} else {
self.scopes.last_mut().unwrap().insert(name.clone(), *ty);
if let Some(expr) = init {
let expr_ty = self.check_expr(expr);
if expr_ty != Some(*ty) {
self.errors.push(SemanticError::TypeMismatch(format!(
"Cannot assign {:?} to {:?}",
expr_ty, ty
)));
}
}
}
}
Stmt::Return(expr) => {
if let Some(e) = expr {
self.check_expr(e);
}
// TODO: Check return type matches function
}
Stmt::Block(stmts) => {
self.scopes.push(HashMap::new());
for stmt in stmts {
self.check_stmt(stmt);
}
self.scopes.pop();
}
Stmt::If { cond, then, else_ } => {
let cond_ty = self.check_expr(cond);
if cond_ty != Some(Type::Int) {
self.errors.push(SemanticError::TypeMismatch(
"Condition must be int".to_string(),
));
}
self.check_stmt(then);
if let Some(else_stmt) = else_ {
self.check_stmt(else_stmt);
}
}
Stmt::For {
init,
cond,
update,
body,
} => {
self.scopes.push(HashMap::new());
if let Some(init_stmt) = init {
self.check_stmt(init_stmt);
}
if let Some(cond_expr) = cond {
let cond_ty = self.check_expr(cond_expr);
if cond_ty != Some(Type::Int) {
self.errors.push(SemanticError::TypeMismatch(
"Condition must be int".to_string(),
));
}
}
if let Some(update_expr) = update {
self.check_expr(update_expr);
}
self.check_stmt(body);
self.scopes.pop();
}
Stmt::Expr(expr) => {
self.check_expr(expr);
}
}
}
/// Checks an expression and returns its type.
fn check_expr(&mut self, expr: &Expr) -> Option<Type> {
match expr {
Expr::Literal(lit) => match lit {
Literal::Int(_) => Some(Type::Int),
Literal::Float(_) => Some(Type::Float),
Literal::String(_) => Some(Type::String),
},
Expr::Identifier(name) => {
if let Some(ty) = self.lookup_variable(name) {
Some(ty)
} else {
self.errors
.push(SemanticError::UndefinedVariable(name.clone()));
None
}
}
Expr::Binary { left, op, right } => {
let left_ty = self.check_expr(left);
let right_ty = self.check_expr(right);
match op {
BinOp::Plus | BinOp::Minus | BinOp::Multiply | BinOp::Divide => {
if left_ty == right_ty && left_ty.is_some() {
left_ty
} else {
self.errors.push(SemanticError::TypeMismatch(
"Arithmetic operands must have same type".to_string(),
));
None
}
}
BinOp::Equal
| BinOp::NotEqual
| BinOp::LessThan
| BinOp::GreaterThan
| BinOp::LessEqual
| BinOp::GreaterEqual => {
if left_ty == right_ty && left_ty.is_some() {
Some(Type::Int) // Comparisons return int
} else {
self.errors.push(SemanticError::TypeMismatch(
"Comparison operands must have same type".to_string(),
));
None
}
}
}
}
Expr::Call { name, args } => {
let func_info = self.functions.get(name).cloned();
if let Some((ret_ty, param_types, is_variadic)) = func_info {
if !is_variadic {
if args.len() != param_types.len() {
self.errors.push(SemanticError::WrongArgumentCount(
name.clone(),
param_types.len(),
args.len(),
));
return Some(ret_ty);
}
} else if args.len() < param_types.len() {
self.errors.push(SemanticError::WrongArgumentCount(
name.clone(),
param_types.len(),
args.len(),
));
return Some(ret_ty);
}
for (i, arg) in args.iter().enumerate().take(param_types.len()) {
let arg_ty = self.check_expr(arg);
if arg_ty != Some(param_types[i]) {
self.errors.push(SemanticError::TypeMismatch(format!(
"Argument {} type mismatch",
i
)));
}
}
Some(ret_ty)
} else {
self.errors
.push(SemanticError::UndefinedFunction(name.clone()));
None
}
}
Expr::Assignment { name, value } => {
let value_ty = self.check_expr(value);
if let Some(var_ty) = self.lookup_variable(name) {
if value_ty != Some(var_ty) {
self.errors.push(SemanticError::TypeMismatch(format!(
"Cannot assign {:?} to {:?}",
value_ty, var_ty
)));
}
Some(var_ty)
} else {
self.errors
.push(SemanticError::UndefinedVariable(name.clone()));
None
}
}
}
}
/// Looks up a variable in the current scopes.
fn lookup_variable(&self, name: &str) -> Option<Type> {
for scope in self.scopes.iter().rev() {
if let Some(ty) = scope.get(name) {
return Some(*ty);
}
}
None
}
}
/// Convenience function to analyze a program.
pub fn analyze(program: &Program) -> Vec<SemanticError> {
let mut analyzer = SemanticAnalyzer::new();
analyzer.analyze(program)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lexer::lex;
use crate::parser::parse;
#[test]
fn test_valid_function() {
let input = "int add(int a, int b) { return a + b; }";
let tokens = lex(input).unwrap();
let ast = parse(&tokens).unwrap();
let errors = analyze(&ast);
assert!(errors.is_empty());
}
#[test]
fn test_undefined_variable() {
let input = "int foo() { return x; }";
let tokens = lex(input).unwrap();
let ast = parse(&tokens).unwrap();
let errors = analyze(&ast);
assert_eq!(errors.len(), 1);
assert!(matches!(errors[0], SemanticError::UndefinedVariable(_)));
}
#[test]
fn test_type_mismatch() {
let input = "int foo() { int x = 5.0; return x; }";
let tokens = lex(input).unwrap();
let ast = parse(&tokens).unwrap();
let errors = analyze(&ast);
assert!(!errors.is_empty()); // Should have type mismatch
}
#[test]
fn test_duplicate_variable() {
let input = "int foo() { int x = 5; int x = 6; return x; }";
let tokens = lex(input).unwrap();
let ast = parse(&tokens).unwrap();
let errors = analyze(&ast);
assert_eq!(errors.len(), 1);
assert!(matches!(errors[0], SemanticError::DuplicateVariable(_)));
}
}