Skip to main content

rucc_sema/
check.rs

1//! The pass: what walks the untyped tree and builds the typed one.
2//!
3//! Design: `spec/07-types-and-semantics.md`.
4//!
5//! The shape is the parser's, because the job is the same shape: a context of the things that do
6//! not change, a walk that holds the things that do, and one structure handed back at the end.
7//! What is different is that this walk has two trees, one it reads and one it writes, and the
8//! reason a node is copied across rather than annotated in place is that the two are not the
9//! same tree. A `p->x` is one node in the source and two here, an `int` meeting a `long` is
10//! three, and an array used as a pointer is a node that the source does not contain at all.
11//!
12//! # What is here so far
13//!
14//! Expressions, which is where the constraints of 6.5 live. The ones that name a type are in
15//! `check/expr/typeop.rs` and the rest are in `check/expr.rs`, which is a split by what the two
16//! do rather than by size: an operator that names a type asks the type builder a question first
17//! and most of them answer with a constant. The two that build an object rather than producing a
18//! value, which are the compound literal and GNU's cast to a union type, are in `check/init.rs`
19//! with the rest of initialization.
20//!
21//! Declarations, in `check/decl.rs`, which is what decides the linkage, the storage duration and
22//! the definition state of each name and what reconciles the declarations that share one. The
23//! type a declaration declares comes from `check/ty.rs`, through [`Checker::declared_type`] and
24//! [`Checker::type_name`], which fold a declarator onto the type a specifier list named.
25//!
26//! Statements, in `check/stmt.rs`, which is the one walk here that carries state: what encloses
27//! a statement is what decides whether it is allowed. The function definition is there too, since
28//! a body is the only thing a statement list is ever part of, and so is [`Checker::check_unit`],
29//! which walks a whole translation unit.
30//!
31//! Initialization, in `check/init.rs`, which turns the tree an initializer was parsed into
32//! into a flat list of what goes where. It is its own module because it is its own algorithm:
33//! a cursor over the object being initialized rather than a walk over the source, which is what
34//! makes brace elision, designation and a string literal filling an array all the same thing
35//! seen from different places. The compound literal is there too, since an unnamed object with
36//! an initializer is what it is.
37//!
38//! Folding is reachable from here through [`Checker::eval_constant`] and
39//! [`Checker::eval_integer`], and the checking asks for it in seven places: a narrowing
40//! conversion that changes the value, an `alignas`, a `static_assert`, the initializer of a
41//! `constexpr` object, a case label, the index of a designation, and each element of an
42//! initializer for an object that exists before the program runs.
43//!
44//! # Poisoning
45//!
46//! The rule is the parser's, in `spec/06-lexer-and-parser.md` section 6.8, and it is the same
47//! rule for the same reason. An expression that has been diagnosed becomes
48//! [`ExprKind::Error`](crate::ExprKind::Error), and an operator whose operand is poisoned is
49//! poisoned in turn without a word said about it. That is what keeps one undeclared name from
50//! producing an error for every operator it appears under, and it is why nothing below asks
51//! whether an error has already been reported: it asks whether the node in its hand is one.
52
53use rucc_ast::Ast;
54use rucc_base::{Interner, Symbol};
55use rucc_diag::{DEFAULT_ERROR_LIMIT, Diagnostic, Errors, Span};
56use rucc_session::Std;
57use rucc_target::TargetInfo;
58use rucc_types::{ArrayLen, IntKind, TypeId, TypeKind, Types, int_width};
59
60use crate::convert::Conv;
61use crate::decl::{Decl, DeclId, DeclKind, DeclList, Definition, Linkage, StorageDuration};
62use crate::eval::{Eval, NotConstant};
63use crate::expr::{Category, Expr, ExprId, ExprKind};
64use crate::scope::Scopes;
65use crate::tast::{Const, Tast};
66
67mod attr;
68mod builtin;
69mod decl;
70mod expr;
71mod init;
72mod stmt;
73mod ty;
74
75pub use crate::check::builtin::{library_name, unimplemented_builtin};
76
77/// What the checking needs and does not change.
78#[derive(Debug, Clone, Copy)]
79pub struct Context<'a> {
80    /// The spellings, for the diagnostics that name an identifier.
81    pub names: &'a Interner,
82    /// What the target's types are, which every layout and every promotion is decided by.
83    pub target: &'a TargetInfo,
84    /// The dialect.
85    pub std: Std,
86    /// Whether the GNU extensions are on.
87    pub gnu: bool,
88    /// Whether `-pedantic` was given.
89    pub pedantic: bool,
90    /// How many errors to report before stopping, with zero meaning no limit.
91    pub error_limit: usize,
92}
93
94impl<'a> Context<'a> {
95    /// A context with the defaults, for a caller that has an interner and a target to hand.
96    #[must_use]
97    pub fn new(names: &'a Interner, target: &'a TargetInfo, std: Std) -> Context<'a> {
98        Context { names, target, std, gnu: true, pedantic: false, error_limit: DEFAULT_ERROR_LIMIT }
99    }
100}
101
102/// What one run of the checking produced.
103#[derive(Debug)]
104pub struct Checked {
105    /// The typed tree, which holds poisoned nodes where the source did not check.
106    pub tast: Tast,
107    /// The types, which the tree points into and which outlive it.
108    pub types: Types,
109    /// What went wrong, in the order it was found.
110    pub diagnostics: Vec<Diagnostic>,
111}
112
113impl Checked {
114    /// Whether anything was reported at an error severity.
115    #[must_use]
116    pub fn failed(&self) -> bool {
117        self.diagnostics.iter().any(|d| d.severity.is_fatal())
118    }
119}
120
121/// The checking pass.
122#[derive(Debug)]
123pub struct Checker<'a> {
124    pub(crate) ast: &'a Ast,
125    pub(crate) tast: Tast,
126    pub(crate) types: Types,
127    pub(crate) scopes: Scopes,
128    pub(crate) errors: Errors,
129    pub(crate) cx: Context<'a>,
130    /// What the type builder has already worked out, which is in `check/ty.rs` with the code
131    /// that fills it in.
132    pub(crate) built: ty::Built,
133    /// The function body being checked, absent everywhere else. What is in it is in
134    /// `check/stmt.rs`, which is the only code that reads it.
135    pub(in crate::check) body: Option<stmt::Body>,
136    /// The declarations whose initializers are being checked and whose types or values are not
137    /// known until that finishes, which is what C23 calls underspecified. A name is in scope
138    /// inside its own initializer, so this is what tells a reference to one from a use of the
139    /// object it will become. Nested, because a statement expression may declare another.
140    pub(in crate::check) underspecified: Vec<DeclId>,
141    /// The builtins this compiler declared for a program that called one without declaring it,
142    /// which is what `check/builtin.rs` does the first time it sees one.
143    ///
144    /// It is here to tell that declaration from one the program wrote, which the families that
145    /// are answered rather than called have to be able to do. `__builtin_nan("1")` is a constant
146    /// and `__builtin_nan(p)` is a call, so a file with both leaves a declaration behind, and
147    /// without this the answer to the second one written would depend on the first.
148    pub(in crate::check) declared_builtins: Vec<Symbol>,
149}
150
151impl<'a> Checker<'a> {
152    /// A checker over one untyped tree.
153    #[must_use]
154    pub fn new(ast: &'a Ast, cx: Context<'a>) -> Checker<'a> {
155        Checker {
156            ast,
157            tast: Tast::new(),
158            types: Types::new(),
159            scopes: Scopes::new(),
160            errors: Errors::new(cx.error_limit),
161            cx,
162            built: ty::Built::default(),
163            body: None,
164            underspecified: Vec::new(),
165            declared_builtins: Vec::new(),
166        }
167    }
168
169    /// Checks a whole translation unit, which is what a compilation does.
170    ///
171    /// The declarations are checked in the order they were written, since that is the order the
172    /// scopes are built in and the order the diagnostics belong in.
173    pub fn check_unit(&mut self) {
174        // Copied out because it is a shared reference with the checker's own lifetime, so holding
175        // it does not borrow the checker that each declaration is checked through.
176        let ast = self.ast;
177        for &decl in ast.top_level() {
178            self.check_decl(decl);
179        }
180    }
181
182    /// Checks one expression and gives back the node it became.
183    ///
184    /// Always gives back a node. An expression that does not check is poisoned rather than
185    /// absent, so that the operators around it are still checked and the diagnostics they would
186    /// produce are still held back.
187    pub fn check_expr(&mut self, id: rucc_ast::ExprId) -> ExprId {
188        self.expr(id)
189    }
190
191    /// Folds a checked expression, reporting whatever the folding itself found wrong.
192    ///
193    /// # Errors
194    ///
195    /// [`NotConstant`] when the expression is not one. It is handed back rather than reported
196    /// because the message names the context: `case label does not reduce to an integer
197    /// constant` and `enumerator value for 'x' is not an integer constant` are two sentences
198    /// about the same failure, and only the caller knows which one to write.
199    pub fn eval_constant(&mut self, expr: ExprId) -> Result<Const, NotConstant> {
200        let mut eval = self.eval();
201        let value = eval.constant(expr);
202        self.absorb(eval.finish());
203        value
204    }
205
206    /// The same, for a context that needs an integer constant expression.
207    ///
208    /// # Errors
209    ///
210    /// [`NotConstant`] when the expression is not one, or is a constant of some other type.
211    pub fn eval_integer(&mut self, expr: ExprId) -> Result<i128, NotConstant> {
212        let mut eval = self.eval();
213        let value = eval.integer(expr);
214        self.absorb(eval.finish());
215        value
216    }
217
218    /// The tree, the types and the diagnostics.
219    #[must_use]
220    pub fn finish(self) -> Checked {
221        Checked { tast: self.tast, types: self.types, diagnostics: self.errors.finish() }
222    }
223
224    /// Declares an object in the current scope without a declaration to read it from.
225    ///
226    /// [`Checker::check_decl`] is what a translation unit goes through. This is for the caller
227    /// that wants to check one expression against names it has decided on itself, which is what
228    /// [`Checker::check_expr`] is for and what the tests here are built on.
229    pub fn declare_object(&mut self, name: Symbol, ty: TypeId, span: Span) -> DeclId {
230        let decl = self.object_decl(Some(name), ty, span);
231        self.scopes.declare(name, crate::scope::Binding::Decl(decl));
232        decl
233    }
234
235    /// An object with automatic storage that nothing can name.
236    ///
237    /// A parameter a definition left unnamed is the one of these there is, C23 6.7.7.4p1. The
238    /// object is there and the call passes it, and what it has no way of is being mentioned in
239    /// the body, so there is nothing to put in a scope and a declaration is all it is.
240    pub(crate) fn unnamed_object(&mut self, ty: TypeId, span: Span) -> DeclId {
241        self.object_decl(None, ty, span)
242    }
243
244    /// The declaration both of those are, which differ only in whether anything can say the name.
245    fn object_decl(&mut self, name: Option<Symbol>, ty: TypeId, span: Span) -> DeclId {
246        let kind = if rucc_types::is_function(&self.types, ty) {
247            DeclKind::Function
248        } else {
249            DeclKind::Object
250        };
251        self.tast.decl(
252            Decl {
253                name,
254                ty,
255                kind,
256                linkage: Linkage::None,
257                duration: StorageDuration::Automatic,
258                state: Definition::Defined,
259                alignment: None,
260                constant: false,
261                retained: false,
262                init: None,
263                params: DeclList::EMPTY,
264                body: None,
265            },
266            span,
267        )
268    }
269
270    /// The conversions, over this tree and these types.
271    pub(crate) fn conv(&mut self) -> Conv<'_> {
272        // The target is copied out first because it is a shared reference living as long as the
273        // context, so taking it does not borrow the checker the two mutable ones are taken from.
274        let target = self.cx.target;
275        Conv { tast: &mut self.tast, types: &mut self.types, target }
276    }
277
278    /// The constant folding, over this tree and these types.
279    pub(crate) fn eval(&self) -> Eval<'_> {
280        Eval::new(&self.tast, &self.types, self.cx.target, self.cx.names)
281    }
282
283    /// Reports a diagnostic.
284    pub(crate) fn report(&mut self, diagnostic: Diagnostic) {
285        self.errors.push(diagnostic);
286    }
287
288    /// Reports everything the folding found, which it collects rather than pushing itself
289    /// because it holds the tree while it runs and the error list is beside the tree.
290    pub(crate) fn absorb(&mut self, diagnostics: Vec<Diagnostic>) {
291        for diagnostic in diagnostics {
292            self.errors.push(diagnostic);
293        }
294    }
295
296    /// Whether a checked expression is one that was already the subject of a diagnostic.
297    pub(crate) fn is_poisoned(&self, id: ExprId) -> bool {
298        matches!(self.tast[id].kind, ExprKind::Error)
299    }
300
301    /// A poisoned expression, for the operand that did not check.
302    ///
303    /// Its type is `int` because every node has a type and there is no type meaning "no idea".
304    /// Nothing reads it, since every operator that meets a poisoned operand poisons itself
305    /// before it looks at what type the operand had.
306    pub(crate) fn poison(&mut self, span: Span) -> ExprId {
307        let int = self.types.int(IntKind::Int);
308        self.tast.expr(Expr::new(ExprKind::Error, int, Category::Rvalue), span)
309    }
310
311    /// How a type is written, for a diagnostic that names one.
312    pub(crate) fn spell(&self, ty: TypeId) -> String {
313        rucc_types::spell(&self.types, self.cx.names, ty)
314    }
315
316    /// What a name is spelled, for a diagnostic that quotes one.
317    pub(crate) fn text(&self, name: Symbol) -> &str {
318        self.cx.names.resolve(name)
319    }
320
321    /// `int`, which is the type of every comparison and of `!`.
322    pub(crate) fn int(&self) -> TypeId {
323        self.types.int(IntKind::Int)
324    }
325
326    /// The type `sizeof` and `alignof` answer in, and the one an offset is measured in.
327    ///
328    /// Derived the same way [`Checker::ptrdiff`] is and for the same reason, since `size_t` is
329    /// the unsigned type as wide as a pointer on every target this compiles for and asking the
330    /// widths keeps the two from disagreeing about which one that is.
331    pub(crate) fn size_type(&self) -> TypeId {
332        let width = self.cx.target.pointer_width;
333        for kind in [IntKind::UInt, IntKind::ULong, IntKind::ULongLong] {
334            if int_width(kind, self.cx.target) >= width {
335                return self.types.int(kind);
336            }
337        }
338        self.types.int(IntKind::ULongLong)
339    }
340
341    /// Whether a type's size is worked out where it is reached rather than here.
342    ///
343    /// True for an array whose length is an expression, however deep it is: `int a[n][3]` is one
344    /// and so is `int a[3][n]`. Shared between the operator that measures a type and the
345    /// declaration that has to decide whether the object can live anywhere but the stack.
346    pub(crate) fn is_variable_length(&self, ty: TypeId) -> bool {
347        match self.types.kind(self.types.canonical(ty)) {
348            TypeKind::Array { elem, len } => {
349                matches!(len, ArrayLen::Variable(_)) || self.is_variable_length(elem)
350            }
351            _ => false,
352        }
353    }
354
355    /// Whether a type is variably modified, which is a variable length array or anything built
356    /// out of one.
357    ///
358    /// `int a[n]` is one and so is `int (*p)[n]`, which is where this differs from
359    /// [`Checker::is_variable_length`]: the pointer has the size every pointer has, and the
360    /// thing it points at has a size the program worked out where the declaration was. That is
361    /// why C says a jump may not enter the scope of either of them.
362    pub(crate) fn is_variably_modified(&self, ty: TypeId) -> bool {
363        match self.types.kind(self.types.canonical(ty)) {
364            TypeKind::Array { elem, len } => {
365                matches!(len, ArrayLen::Variable(_)) || self.is_variably_modified(elem)
366            }
367            TypeKind::Pointer(pointee) => self.is_variably_modified(pointee),
368            _ => false,
369        }
370    }
371
372    /// The type of the difference between two pointers.
373    ///
374    /// Derived rather than stored, because `ptrdiff_t` is whatever signed type is as wide as a
375    /// pointer and that is `long` on every LP64 target and `long long` on Windows, which is the
376    /// same fact `long_width` already records. Asking the widths keeps the two from disagreeing.
377    pub(crate) fn ptrdiff(&self) -> TypeId {
378        let width = self.cx.target.pointer_width;
379        for kind in [IntKind::Int, IntKind::Long, IntKind::LongLong] {
380            if int_width(kind, self.cx.target) >= width {
381                return self.types.int(kind);
382            }
383        }
384        self.types.int(IntKind::LongLong)
385    }
386}