feat(ast, ir. sema): Add storage class

This commit is contained in:
2026-06-12 18:33:54 +08:00
parent 5099bbaab7
commit e3aa2e21c0
11 changed files with 217 additions and 45 deletions
+31
View File
@@ -0,0 +1,31 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Debug executable 'compiler'",
"type": "lldb",
"request": "launch",
"cargo": {
"args": [
"run",
"--bin=compiler"
]
},
"args": []
},
{
"name": "Debug unit tests in executable 'compiler'",
"type": "lldb",
"request": "launch",
"cargo": {
"args": [
"test",
"--bin=compiler"
]
}
}
]
}
+32
View File
@@ -0,0 +1,32 @@
use crate::diagnostic::span::Span;
pub struct Type {
span: Span,
kind: TypeKind,
}
pub enum TypeKind {
Builtin(BuiltinType),
Array(ArrayType),
}
pub struct BuiltinType {
span: Span,
kind: BuiltinTypeKind,
}
pub enum BuiltinTypeKind {
Int,
Void,
}
pub struct ArrayType {
span: Span,
element_type: Box<Type>,
dimensions: Vec<ArrayDimension>,
}
pub struct ArrayDimension {
span: Span,
size: Option<Expr>,
}
+14 -28
View File
@@ -1,8 +1,8 @@
use crate::{ use crate::{
ast::err::ParseError, ast::err::ParseError,
ast::types::{ ast::types::{
ArrayDimension, CompileUnit, Expr, FuncDeclStmt, GlobalDeclStmt, Param, VarDeclStmt, ArrayDimension, CompileUnit, Expr, FuncDeclStmt, GlobalDeclStmt, Param, StorageClass,
VarDeclStmtValue, VarDeclStmt, VarDeclStmtValue,
}, },
diagnostic::span::Span, diagnostic::span::Span,
lexer::types::{TokenValue, TypeIdent}, lexer::types::{TokenValue, TypeIdent},
@@ -10,13 +10,8 @@ use crate::{
use super::{ParseProcessError, ParseType, Parser}; use super::{ParseProcessError, ParseType, Parser};
#[derive(Clone, Copy)]
enum StorageClass {
Static,
}
struct DeclSpecifiers { struct DeclSpecifiers {
_storage_class: Option<StorageClass>, storage_class: Option<StorageClass>,
type_specifier: TypeIdent, type_specifier: TypeIdent,
type_span: Span, type_span: Span,
} }
@@ -111,7 +106,7 @@ impl Parser {
}; };
Ok(DeclSpecifiers { Ok(DeclSpecifiers {
_storage_class: storage_class, storage_class,
type_specifier, type_specifier,
type_span: type_token.span, type_span: type_token.span,
}) })
@@ -183,13 +178,13 @@ impl Parser {
self.advance(1); self.advance(1);
span span
} }
TokenValue::Eof => { // TokenValue::Eof => {
self.diagnostics.add_from_frontend_error( // self.diagnostics.add_from_frontend_error(
ParseError::ExpectedBefore(TokenValue::Eof, "`]`"), // ParseError::ExpectedBefore(TokenValue::Eof, "`]`"),
start_span, // start_span,
); // );
return Err(ParseProcessError::ErrorInMatch); // return Err(ParseProcessError::ErrorInMatch);
} // }
_ => { _ => {
let token = self.next(); let token = self.next();
self.diagnostics.add_from_frontend_error( self.diagnostics.add_from_frontend_error(
@@ -279,6 +274,7 @@ impl Parser {
let body = self.parse_block_stmt(ParseType::MustParse)?; let body = self.parse_block_stmt(ParseType::MustParse)?;
Ok(FuncDeclStmt { Ok(FuncDeclStmt {
return_type: specifiers.type_specifier.into(), return_type: specifiers.type_specifier.into(),
storage_class: specifiers.storage_class,
name, name,
params, params,
body, body,
@@ -292,21 +288,10 @@ impl Parser {
specifiers: DeclSpecifiers, specifiers: DeclSpecifiers,
first_declarator: Declarator, first_declarator: Declarator,
consume_semicolon: bool, consume_semicolon: bool,
allow_empty_declarator_list: bool, _allow_empty_declarator_list: bool,
) -> Result<VarDeclStmt, ParseProcessError> { ) -> Result<VarDeclStmt, ParseProcessError> {
let mut values = vec![]; let mut values = vec![];
if self.peek().value == TokenValue::Semicolon && allow_empty_declarator_list {
if consume_semicolon {
self.advance(1);
}
return Ok(VarDeclStmt {
values,
type_span: specifiers.type_span,
data_type: specifiers.type_specifier.into(),
});
}
let initializer = self.parse_initializer()?; let initializer = self.parse_initializer()?;
values.push(self.init_declarator_to_var_value(InitDeclarator { values.push(self.init_declarator_to_var_value(InitDeclarator {
declarator: first_declarator, declarator: first_declarator,
@@ -328,6 +313,7 @@ impl Parser {
} }
Ok(VarDeclStmt { Ok(VarDeclStmt {
storage_class: specifiers.storage_class,
values, values,
type_span: specifiers.type_span, type_span: specifiers.type_span,
data_type: specifiers.type_specifier.into(), data_type: specifiers.type_specifier.into(),
+2 -2
View File
@@ -133,8 +133,8 @@ impl Parser {
} else { } else {
IncDecOp::Dec IncDecOp::Dec
}; };
let end_span = self.peek_n(1).span; let end_span = self.peek().span;
self.advance(2); self.advance(1);
expr = Expr { expr = Expr {
span: Span::from_two(expr.span, end_span), span: Span::from_two(expr.span, end_span),
value: ExprValue::IncDec { value: ExprValue::IncDec {
+6 -1
View File
@@ -8,9 +8,13 @@ pub enum GlobalDeclStmt {
VarDecl(VarDeclStmt), VarDecl(VarDeclStmt),
FuncDecl(FuncDeclStmt), FuncDecl(FuncDeclStmt),
} }
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum StorageClass {
Static,
}
pub struct VarDeclStmt { pub struct VarDeclStmt {
pub values: Vec<VarDeclStmtValue>, pub values: Vec<VarDeclStmtValue>,
pub storage_class: Option<StorageClass>,
pub data_type: Type, pub data_type: Type,
pub type_span: Span, pub type_span: Span,
} }
@@ -28,6 +32,7 @@ pub struct ArrayDimension {
pub struct FuncDeclStmt { pub struct FuncDeclStmt {
pub name: String, pub name: String,
pub storage_class: Option<StorageClass>,
pub return_type: Type, pub return_type: Type,
pub params: Vec<Param>, pub params: Vec<Param>,
pub body: BlockStmt, pub body: BlockStmt,
+51 -4
View File
@@ -1,6 +1,6 @@
use std::{collections::BTreeMap, vec}; use std::{collections::BTreeMap, vec};
use crate::{ir::types::{BinaryOp as IRBinaryOp, CmpOp, Function, IRInstr, IRType, MoveRValue, UnaryOp, Variable, VariableOrIntLit, VariableType}, sema::{analyzer::Analyzer as SemaAnalyzer, hir::{HirBlockStmt, HirBreakStmt, HirCompileUnit, HirContinueStmt, HirExpr, HirExprValue, HirForInit, HirForStmt, HirFuncDeclStmt, HirGlobalDeclStmt, HirIfElseBranch, HirIfStmt, HirReturnStmt, HirStatement, HirVarDeclStmt, HirWhileStmt}, symbol::{FunctionId, SymbolId}}}; use crate::{ir::types::{BinaryOp as IRBinaryOp, CmpOp, Function, IRInstr, IRType, MoveRValue, UnaryOp, Variable, VariableOrIntLit, VariableType}, sema::{analyzer::Analyzer as SemaAnalyzer, hir::{HirBlockStmt, HirBreakStmt, HirCompileUnit, HirContinueStmt, HirExpr, HirExprValue, HirForInit, HirForStmt, HirFuncDeclStmt, HirGlobalDeclStmt, HirIfElseBranch, HirIfStmt, HirReturnStmt, HirStatement, HirVarDeclStmt, HirWhileStmt}, symbol::{FunctionId, SymbolId, SymbolKind}}};
use crate::ast::types::BinaryOp as AstBinaryOp; use crate::ast::types::BinaryOp as AstBinaryOp;
use crate::ast::types::UnaryOp as AstUnaryOp; use crate::ast::types::UnaryOp as AstUnaryOp;
pub struct Generator<'a> { pub struct Generator<'a> {
@@ -14,6 +14,7 @@ pub struct Generator<'a> {
// if child expr isn't logical, we need to do cmp to decide which label to goto // if child expr isn't logical, we need to do cmp to decide which label to goto
while_exit_label: Vec<(usize, usize)>, // continue exit, break exit while_exit_label: Vec<(usize, usize)>, // continue exit, break exit
func_exit: Option<(usize, Option<Variable>)>, // (label, return_var) func_exit: Option<(usize, Option<Variable>)>, // (label, return_var)
extra_global_instrs: Vec<IRInstr>,
label_counter: usize label_counter: usize
} }
@@ -25,6 +26,7 @@ impl<'a> Generator<'a> {
current_exit_label: vec![], current_exit_label: vec![],
while_exit_label: vec![], while_exit_label: vec![],
func_exit: None, func_exit: None,
extra_global_instrs: vec![],
label_counter: 0, label_counter: 0,
} }
} }
@@ -55,7 +57,10 @@ impl<'a> Generator<'a> {
instrs.extend(self.generate_var_decl(var_decl, true)); instrs.extend(self.generate_var_decl(var_decl, true));
} }
FuncDecl(func_decl) => { FuncDecl(func_decl) => {
instrs.extend(self.generate_func_decl(func_decl)); let extra_global_start = self.extra_global_instrs.len();
let func_instrs = self.generate_func_decl(func_decl);
instrs.extend(self.extra_global_instrs.drain(extra_global_start..));
instrs.extend(func_instrs);
} }
} }
} }
@@ -65,10 +70,18 @@ impl<'a> Generator<'a> {
fn generate_var_decl(&mut self, var_decl: HirVarDeclStmt, is_global: bool) -> Vec<IRInstr> { fn generate_var_decl(&mut self, var_decl: HirVarDeclStmt, is_global: bool) -> Vec<IRInstr> {
let mut instrs = vec![]; let mut instrs = vec![];
for value in var_decl.values { for value in var_decl.values {
let var_type = if is_global { VariableType::Global } else { VariableType::Local }; let symbol_kind = self.sema.get_symbol_kind(value.symbol);
let has_static_storage = is_global || symbol_kind == SymbolKind::StaticLocal || value.is_static_local;
let var_type = if has_static_storage { VariableType::Global } else { VariableType::Local };
let var = self.var_manager.declare_symbol(value.symbol, var_type, self.sema.get_symbol_type(value.symbol).into()); let var = self.var_manager.declare_symbol(value.symbol, var_type, self.sema.get_symbol_type(value.symbol).into());
if has_static_storage {
let init = value.value.as_ref().and_then(|expr| Self::const_init_value(expr));
let decl = IRInstr::DeclareGlobal(var, init);
if is_global { if is_global {
instrs.push(IRInstr::Declare(var)); instrs.push(decl);
} else {
self.extra_global_instrs.push(decl);
}
} else if let Some(init) = value.value { } else if let Some(init) = value.value {
self.current_exit_label.push(None); self.current_exit_label.push(None);
let (init_instrs, init_var) = match self.generate_expr(init) { let (init_instrs, init_var) = match self.generate_expr(init) {
@@ -88,6 +101,40 @@ impl<'a> Generator<'a> {
instrs instrs
} }
fn const_init_value(expr: &HirExpr) -> Option<i32> {
match &expr.value {
HirExprValue::IntLit(value) => Some(*value as i32),
HirExprValue::UnaryOp { op, operand } => {
let value = Self::const_init_value(operand)?;
match op {
AstUnaryOp::Add => Some(value),
AstUnaryOp::Sub => value.checked_neg(),
AstUnaryOp::Not => Some((value == 0) as i32),
}
}
HirExprValue::BinaryOp { lhs, op, rhs } => {
let lhs = Self::const_init_value(lhs)?;
let rhs = Self::const_init_value(rhs)?;
match op {
AstBinaryOp::Add => lhs.checked_add(rhs),
AstBinaryOp::Sub => lhs.checked_sub(rhs),
AstBinaryOp::Mul => lhs.checked_mul(rhs),
AstBinaryOp::Div => lhs.checked_div(rhs),
AstBinaryOp::Mod => lhs.checked_rem(rhs),
AstBinaryOp::Equal => Some((lhs == rhs) as i32),
AstBinaryOp::NotEqual => Some((lhs != rhs) as i32),
AstBinaryOp::Less => Some((lhs < rhs) as i32),
AstBinaryOp::LessEqual => Some((lhs <= rhs) as i32),
AstBinaryOp::Greater => Some((lhs > rhs) as i32),
AstBinaryOp::GreaterEqual => Some((lhs >= rhs) as i32),
AstBinaryOp::And => Some((lhs != 0 && rhs != 0) as i32),
AstBinaryOp::Or => Some((lhs != 0 || rhs != 0) as i32),
}
}
_ => None,
}
}
fn generate_func_decl(&mut self, func_decl: HirFuncDeclStmt) -> Vec<IRInstr> { fn generate_func_decl(&mut self, func_decl: HirFuncDeclStmt) -> Vec<IRInstr> {
let parameters: Vec<Variable> = func_decl.params.iter() let parameters: Vec<Variable> = func_decl.params.iter()
.map(|param| self.var_manager.declare_symbol(param.symbol, VariableType::Local, param.param_type.clone().into())) .map(|param| self.var_manager.declare_symbol(param.symbol, VariableType::Local, param.param_type.clone().into()))
+3
View File
@@ -21,6 +21,7 @@ impl Display for VariableOrIntLit {
#[derive(Clone)] #[derive(Clone)]
pub enum IRInstr { pub enum IRInstr {
Declare(Variable), Declare(Variable),
DeclareGlobal(Variable, Option<i32>),
DefineFunc(Function, Vec<Variable>, Vec<IRInstr>), DefineFunc(Function, Vec<Variable>, Vec<IRInstr>),
Entry, Entry,
Binary(Variable, Variable, BinaryOp, Variable), Binary(Variable, Variable, BinaryOp, Variable),
@@ -54,6 +55,8 @@ impl Display for IRInstr {
IRInstr::Load(dest, addr) => write!(f, "{} = *{}", dest, addr), IRInstr::Load(dest, addr) => write!(f, "{} = *{}", dest, addr),
IRInstr::Store(addr, value) => write!(f, "*{} = {}", addr, value), IRInstr::Store(addr, value) => write!(f, "*{} = {}", addr, value),
IRInstr::Declare(var) => write!(f, "declare {}", var.to_decl_string()), IRInstr::Declare(var) => write!(f, "declare {}", var.to_decl_string()),
IRInstr::DeclareGlobal(var, Some(init)) => write!(f, "declare {} = {}", var.to_decl_string(), init),
IRInstr::DeclareGlobal(var, None) => write!(f, "declare {}", var.to_decl_string()),
IRInstr::DefineFunc(func, args, body) => { IRInstr::DefineFunc(func, args, body) => {
let body_str = body.iter().map(|instr| format!(" {}", instr)).collect::<Vec<_>>().join("\n"); let body_str = body.iter().map(|instr| format!(" {}", instr)).collect::<Vec<_>>().join("\n");
write!(f, "define {} {{\n{}\n}}", func.to_decl_string(args), body_str) write!(f, "define {} {{\n{}\n}}", func.to_decl_string(args), body_str)
+73 -9
View File
@@ -3,7 +3,7 @@ use std::collections::BTreeMap;
use crate::{ use crate::{
ast::types::{ ast::types::{
ArrayDimension, BinaryOp, BlockStmt, BreakStmt, CompileUnit, ContinueStmt, Expr, ExprValue, ForInit, ForStmt, FuncDeclStmt, ArrayDimension, BinaryOp, BlockStmt, BreakStmt, CompileUnit, ContinueStmt, Expr, ExprValue, ForInit, ForStmt, FuncDeclStmt,
GlobalDeclStmt, IfElseBranch, IfStmt, ReturnStmt, Statement, VarDeclStmt, WhileStmt, GlobalDeclStmt, IfElseBranch, IfStmt, ReturnStmt, Statement, StorageClass, VarDeclStmt, WhileStmt,
}, },
diagnostic::{span::Span, Diagnositics}, diagnostic::{span::Span, Diagnositics},
sema::{ sema::{
@@ -41,6 +41,7 @@ impl Analyzer {
analyzer.declare_builtin_func("putch", vec![SemaType::I32], SemaType::Void); analyzer.declare_builtin_func("putch", vec![SemaType::I32], SemaType::Void);
analyzer.declare_builtin_func("putarray", vec![SemaType::I32, SemaType::Array(Box::new(SemaType::I32), vec![0])], SemaType::Void); analyzer.declare_builtin_func("putarray", vec![SemaType::I32, SemaType::Array(Box::new(SemaType::I32), vec![0])], SemaType::Void);
analyzer.declare_builtin_func("getint", vec![], SemaType::I32); analyzer.declare_builtin_func("getint", vec![], SemaType::I32);
analyzer.declare_builtin_func("getch", vec![], SemaType::I32);
analyzer.declare_builtin_func("getarray", vec![SemaType::Array(Box::new(SemaType::I32), vec![0])], SemaType::I32); analyzer.declare_builtin_func("getarray", vec![SemaType::Array(Box::new(SemaType::I32), vec![0])], SemaType::I32);
analyzer analyzer
} }
@@ -100,13 +101,33 @@ impl Analyzer {
fn analyze_var_decl(&mut self, var_decl: VarDeclStmt, kind: SymbolKind) -> HirVarDeclStmt { fn analyze_var_decl(&mut self, var_decl: VarDeclStmt, kind: SymbolKind) -> HirVarDeclStmt {
let base_type: SemaType = var_decl.data_type.into(); let base_type: SemaType = var_decl.data_type.into();
let is_static_local = kind == SymbolKind::Local && var_decl.storage_class == Some(StorageClass::Static);
let has_static_storage = kind == SymbolKind::Global || is_static_local;
let actual_kind = if is_static_local {
SymbolKind::StaticLocal
} else {
kind
};
let mut values = vec![]; let mut values = vec![];
for value in var_decl.values { for value in var_decl.values {
let data_type = self.build_var_type(base_type.clone(), &value.dimensions, false); let data_type = self.build_var_type(base_type.clone(), &value.dimensions, false);
match self.symbols.declare_variable(&value.name, kind, data_type) { let initializer_is_not_constant = has_static_storage
&& value
.value
.as_ref()
.is_some_and(|expr| Self::eval_const_expr(expr).is_none());
if initializer_is_not_constant {
if let Some(expr) = &value.value {
self.add_error(SemaError::InitializerNotConstant, expr.span);
}
}
match self.symbols.declare_variable(&value.name, actual_kind, data_type) {
Ok(symbol) => { Ok(symbol) => {
let symbol_type = self.symbols.get_symbol(symbol).ty.clone(); let symbol_type = self.symbols.get_symbol(symbol).ty.clone();
let init = value.value.and_then(|expr| { let init = if initializer_is_not_constant {
None
} else {
value.value.and_then(|expr| {
let span = expr.span; let span = expr.span;
let init = self.analyze_expr(expr)?; let init = self.analyze_expr(expr)?;
if init.ty == SemaType::Void { if init.ty == SemaType::Void {
@@ -115,11 +136,13 @@ impl Analyzer {
self.add_error(SemaError::TypeMismatch(symbol_type.clone(), init.ty.clone()), span); self.add_error(SemaError::TypeMismatch(symbol_type.clone(), init.ty.clone()), span);
} }
Some(init) Some(init)
}); })
};
values.push(HirVarDeclStmtValue { values.push(HirVarDeclStmtValue {
symbol, symbol,
name_span: value.name_span, name_span: value.name_span,
value: init, value: init,
is_static_local,
}); });
} }
Err(e) => self.add_error(e, value.name_span), Err(e) => self.add_error(e, value.name_span),
@@ -183,6 +206,40 @@ impl Analyzer {
}) })
} }
fn eval_const_expr(expr: &Expr) -> Option<i32> {
match &expr.value {
ExprValue::IntLit(value) => i32::try_from(*value).ok(),
ExprValue::UnaryOp { op, operand } => {
let value = Self::eval_const_expr(operand)?;
match op {
crate::ast::types::UnaryOp::Add => Some(value),
crate::ast::types::UnaryOp::Sub => value.checked_neg(),
crate::ast::types::UnaryOp::Not => Some((value == 0) as i32),
}
}
ExprValue::BinaryOp { lhs, op, rhs } => {
let lhs = Self::eval_const_expr(lhs)?;
let rhs = Self::eval_const_expr(rhs)?;
match op {
BinaryOp::Add => lhs.checked_add(rhs),
BinaryOp::Sub => lhs.checked_sub(rhs),
BinaryOp::Mul => lhs.checked_mul(rhs),
BinaryOp::Div => lhs.checked_div(rhs),
BinaryOp::Mod => lhs.checked_rem(rhs),
BinaryOp::Equal => Some((lhs == rhs) as i32),
BinaryOp::NotEqual => Some((lhs != rhs) as i32),
BinaryOp::Less => Some((lhs < rhs) as i32),
BinaryOp::LessEqual => Some((lhs <= rhs) as i32),
BinaryOp::Greater => Some((lhs > rhs) as i32),
BinaryOp::GreaterEqual => Some((lhs >= rhs) as i32),
BinaryOp::And => Some((lhs != 0 && rhs != 0) as i32),
BinaryOp::Or => Some((lhs != 0 || rhs != 0) as i32),
}
}
_ => None,
}
}
fn build_var_type(&mut self, base_type: SemaType, dimensions: &[ArrayDimension], is_param: bool) -> SemaType { fn build_var_type(&mut self, base_type: SemaType, dimensions: &[ArrayDimension], is_param: bool) -> SemaType {
if dimensions.is_empty() { if dimensions.is_empty() {
return base_type; return base_type;
@@ -218,6 +275,13 @@ impl Analyzer {
HirBlockStmt { statements } HirBlockStmt { statements }
} }
fn analyze_scoped_block_stmt(&mut self, block_stmt: BlockStmt) -> HirBlockStmt {
self.symbols.enter_scope();
let block = self.analyze_block_stmt(block_stmt);
self.symbols.exit_scope();
block
}
fn analyze_statement(&mut self, stmt: Statement) -> Option<HirStatement> { fn analyze_statement(&mut self, stmt: Statement) -> Option<HirStatement> {
match stmt { match stmt {
Statement::Return(stmt) => Some(HirStatement::Return(self.analyze_return_stmt(stmt))), Statement::Return(stmt) => Some(HirStatement::Return(self.analyze_return_stmt(stmt))),
@@ -273,16 +337,16 @@ impl Analyzer {
fn analyze_if_stmt(&mut self, if_stmt: IfStmt) -> HirIfStmt { fn analyze_if_stmt(&mut self, if_stmt: IfStmt) -> HirIfStmt {
let condition = self.analyze_condition_expr(if_stmt.condition); let condition = self.analyze_condition_expr(if_stmt.condition);
let then_branch = self.analyze_block_stmt(if_stmt.then_branch); let then_branch = self.analyze_scoped_block_stmt(if_stmt.then_branch);
let mut ifelse_branch = vec![]; let mut ifelse_branch = vec![];
for branch in if_stmt.ifelse_branch { for branch in if_stmt.ifelse_branch {
let IfElseBranch { condition, then_branch } = branch; let IfElseBranch { condition, then_branch } = branch;
ifelse_branch.push(HirIfElseBranch { ifelse_branch.push(HirIfElseBranch {
condition: self.analyze_condition_expr(condition), condition: self.analyze_condition_expr(condition),
then_branch: self.analyze_block_stmt(then_branch), then_branch: self.analyze_scoped_block_stmt(then_branch),
}); });
} }
let else_branch = if_stmt.else_branch.map(|block| self.analyze_block_stmt(block)); let else_branch = if_stmt.else_branch.map(|block| self.analyze_scoped_block_stmt(block));
HirIfStmt { HirIfStmt {
condition, condition,
then_branch, then_branch,
@@ -294,7 +358,7 @@ impl Analyzer {
fn analyze_while_stmt(&mut self, while_stmt: WhileStmt) -> HirWhileStmt { fn analyze_while_stmt(&mut self, while_stmt: WhileStmt) -> HirWhileStmt {
let condition = self.analyze_condition_expr(while_stmt.condition); let condition = self.analyze_condition_expr(while_stmt.condition);
self.loop_depth += 1; self.loop_depth += 1;
let body = self.analyze_block_stmt(while_stmt.body); let body = self.analyze_scoped_block_stmt(while_stmt.body);
self.loop_depth -= 1; self.loop_depth -= 1;
HirWhileStmt { HirWhileStmt {
condition, condition,
@@ -311,7 +375,7 @@ impl Analyzer {
let condition = for_stmt.condition.map(|expr| self.analyze_condition_expr(expr)); let condition = for_stmt.condition.map(|expr| self.analyze_condition_expr(expr));
let update = for_stmt.update.and_then(|expr| self.analyze_expr(expr)); let update = for_stmt.update.and_then(|expr| self.analyze_expr(expr));
self.loop_depth += 1; self.loop_depth += 1;
let body = self.analyze_block_stmt(for_stmt.body); let body = self.analyze_scoped_block_stmt(for_stmt.body);
self.loop_depth -= 1; self.loop_depth -= 1;
self.symbols.exit_scope(); self.symbols.exit_scope();
HirForStmt { HirForStmt {
+2
View File
@@ -36,4 +36,6 @@ pub enum SemaError {
InvalidArrayDimension, InvalidArrayDimension,
#[error("subscripted value is not an array or pointer")] #[error("subscripted value is not an array or pointer")]
NotSubscriptable, NotSubscriptable,
#[error("initializer element is not constant")]
InitializerNotConstant,
} }
+1
View File
@@ -19,6 +19,7 @@ pub struct HirVarDeclStmtValue {
pub symbol: SymbolId, pub symbol: SymbolId,
pub name_span: Span, pub name_span: Span,
pub value: Option<HirExpr>, pub value: Option<HirExpr>,
pub is_static_local: bool,
} }
pub struct HirFuncDeclStmt { pub struct HirFuncDeclStmt {
+1
View File
@@ -10,6 +10,7 @@ pub enum SymbolKind {
Global, Global,
Local, Local,
Param, Param,
StaticLocal,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]