flux_refineck/
lib.rs

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
//! Refinement type checking

#![feature(
    associated_type_defaults,
    box_patterns,
    extract_if,
    if_let_guard,
    let_chains,
    min_specialization,
    never_type,
    rustc_private,
    unwrap_infallible
)]

extern crate rustc_data_structures;
extern crate rustc_errors;

extern crate rustc_hir;
extern crate rustc_index;
extern crate rustc_infer;
extern crate rustc_middle;
extern crate rustc_mir_dataflow;
extern crate rustc_span;
extern crate rustc_target;
extern crate rustc_type_ir;

mod checker;
pub mod compare_impl_item;
mod ghost_statements;
pub mod invariants;
mod primops;
mod queue;
mod type_env;

use checker::{Checker, trait_impl_subtyping};
use flux_common::{dbg, result::ResultExt as _};
use flux_infer::{
    fixpoint_encoding::FixQueryCache,
    infer::{ConstrReason, SubtypeReason, Tag},
};
use flux_macros::fluent_messages;
use flux_middle::{
    def_id::MaybeExternId,
    global_env::GlobalEnv,
    queries::QueryResult,
    rty::{self, ESpan},
};
use itertools::Itertools;
use rustc_errors::ErrorGuaranteed;
use rustc_hir::def_id::LocalDefId;
use rustc_span::Span;

use crate::{checker::errors::ResultExt as _, ghost_statements::compute_ghost_statements};

fluent_messages! { "../locales/en-US.ftl" }

fn report_fixpoint_errors(
    genv: GlobalEnv,
    local_id: LocalDefId,
    errors: Vec<Tag>,
) -> Result<(), ErrorGuaranteed> {
    #[expect(clippy::collapsible_else_if, reason = "it looks better")]
    if genv.should_fail(local_id) {
        if errors.is_empty() { report_expected_neg(genv, local_id) } else { Ok(()) }
    } else {
        if errors.is_empty() { Ok(()) } else { report_errors(genv, errors) }
    }
}

pub fn check_fn(
    genv: GlobalEnv,
    cache: &mut FixQueryCache,
    def_id: MaybeExternId,
) -> Result<(), ErrorGuaranteed> {
    let span = genv.tcx().def_span(def_id);

    // HACK(nilehmann) this will ignore any code generated by a macro. This is a temporary
    // workaround to deal with a `#[derive(..)]` that generates code that flux cannot handle.
    // Note that this is required because code generated by a `#[derive(..)]` cannot be
    // manually trusted or ignored.
    if !genv.tcx().def_span(def_id).ctxt().is_root() {
        return Ok(());
    }

    // Make sure we run conversion and report errors even if we skip the function for any of
    // the reasons below
    force_conv(genv, def_id).emit(&genv)?;

    // If this is a function wrapping an extern spec its body is irrelevant
    let Some(local_id) = def_id.as_local() else { return Ok(()) };

    // Skip trait methods without body
    if genv.tcx().hir_node_by_def_id(local_id).body_id().is_none() {
        return Ok(());
    }

    let opts = genv.infer_opts(local_id);

    // FIXME(nilehmann) we should move this check to `compare_impl_item`
    if let Some(infcx_root) = trait_impl_subtyping(genv, local_id, opts, span)
        .with_span(span)
        .map_err(|err| err.emit(genv, def_id))?
    {
        tracing::info!("check_fn::refine-subtyping");
        let errors = infcx_root
            .execute_fixpoint_query(cache, def_id, "sub.fluxc")
            .emit(&genv)?;
        tracing::info!("check_fn::fixpoint-subtyping");
        report_fixpoint_errors(genv, local_id, errors)?;
    }

    // Skip trusted functions
    if genv.trusted(local_id) {
        return Ok(());
    }

    dbg::check_fn_span!(genv.tcx(), local_id).in_scope(|| -> Result<(), ErrorGuaranteed> {
        let ghost_stmts = compute_ghost_statements(genv, local_id)
            .with_span(span)
            .map_err(|err| err.emit(genv, def_id))?;

        // PHASE 1: infer shape of `TypeEnv` at the entry of join points
        let shape_result = Checker::run_in_shape_mode(genv, local_id, &ghost_stmts, opts)
            .map_err(|err| err.emit(genv, def_id))?;
        tracing::info!("check_fn::shape");

        // PHASE 2: generate refinement tree constraint
        let infcx_root =
            Checker::run_in_refine_mode(genv, local_id, &ghost_stmts, shape_result, opts)
                .map_err(|err| err.emit(genv, def_id))?;
        tracing::info!("check_fn::refine");

        // PHASE 3: invoke fixpoint on the constraint
        let errors = infcx_root
            .execute_fixpoint_query(cache, def_id, "fluxc")
            .emit(&genv)?;
        tracing::info!("check_fn::fixpoint");
        report_fixpoint_errors(genv, local_id, errors)?;
        Ok(())
    })?;

    dbg::check_fn_span!(genv.tcx(), local_id).in_scope(|| Ok(()))
}

fn force_conv(genv: GlobalEnv, def_id: MaybeExternId) -> QueryResult {
    genv.generics_of(def_id)?;
    genv.refinement_generics_of(def_id)?;
    genv.predicates_of(def_id)?;
    genv.fn_sig(def_id)?;
    Ok(())
}

fn call_error(genv: GlobalEnv, span: Span, dst_span: Option<ESpan>) -> ErrorGuaranteed {
    genv.sess()
        .emit_err(errors::RefineError::call(span, dst_span))
}

fn ret_error(genv: GlobalEnv, span: Span, dst_span: Option<ESpan>) -> ErrorGuaranteed {
    genv.sess()
        .emit_err(errors::RefineError::ret(span, dst_span))
}

fn report_errors(genv: GlobalEnv, errors: Vec<Tag>) -> Result<(), ErrorGuaranteed> {
    let mut e = None;
    for err in errors {
        let span = err.src_span;
        e = Some(match err.reason {
            ConstrReason::Call
            | ConstrReason::Subtype(SubtypeReason::Input)
            | ConstrReason::Subtype(SubtypeReason::Requires) => {
                call_error(genv, span, err.dst_span)
            }
            ConstrReason::Assign => genv.sess().emit_err(errors::AssignError { span }),
            ConstrReason::Ret
            | ConstrReason::Subtype(SubtypeReason::Output)
            | ConstrReason::Subtype(SubtypeReason::Ensures) => ret_error(genv, span, err.dst_span),
            ConstrReason::Div => genv.sess().emit_err(errors::DivError { span }),
            ConstrReason::Rem => genv.sess().emit_err(errors::RemError { span }),
            ConstrReason::Goto(_) => genv.sess().emit_err(errors::GotoError { span }),
            ConstrReason::Assert(msg) => genv.sess().emit_err(errors::AssertError { span, msg }),
            ConstrReason::Fold | ConstrReason::FoldLocal => {
                genv.sess().emit_err(errors::FoldError { span })
            }
            ConstrReason::Overflow => genv.sess().emit_err(errors::OverflowError { span }),
            ConstrReason::Other => genv.sess().emit_err(errors::UnknownError { span }),
        });
    }

    if let Some(e) = e { Err(e) } else { Ok(()) }
}

fn report_expected_neg(genv: GlobalEnv, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
    Err(genv.sess().emit_err(errors::ExpectedNeg {
        span: genv.tcx().def_span(def_id),
        def_descr: genv.tcx().def_descr(def_id.to_def_id()),
    }))
}

mod errors {
    use flux_errors::E0999;
    use flux_macros::{Diagnostic, Subdiagnostic};
    use flux_middle::rty::ESpan;
    use rustc_span::Span;

    #[derive(Diagnostic)]
    #[diag(refineck_goto_error, code = E0999)]
    pub struct GotoError {
        #[primary_span]
        pub span: Span,
    }

    #[derive(Diagnostic)]
    #[diag(refineck_assign_error, code = E0999)]
    pub struct AssignError {
        #[primary_span]
        pub span: Span,
    }

    #[derive(Subdiagnostic)]
    #[note(refineck_condition_span_note)]
    pub(crate) struct ConditionSpanNote {
        #[primary_span]
        pub span: Span,
    }

    #[derive(Subdiagnostic)]
    #[note(refineck_call_span_note)]
    pub(crate) struct CallSpanNote {
        #[primary_span]
        pub span: Span,
    }

    #[derive(Diagnostic)]
    #[diag(refineck_refine_error, code = E0999)]
    pub struct RefineError {
        #[primary_span]
        #[label]
        pub span: Span,
        cond: &'static str,
        #[subdiagnostic]
        span_note: Option<ConditionSpanNote>,
        #[subdiagnostic]
        call_span_note: Option<CallSpanNote>,
    }

    impl RefineError {
        pub fn call(span: Span, espan: Option<ESpan>) -> Self {
            RefineError::new("precondition", span, espan)
        }

        pub fn ret(span: Span, espan: Option<ESpan>) -> Self {
            RefineError::new("postcondition", span, espan)
        }

        fn new(cond: &'static str, span: Span, espan: Option<ESpan>) -> RefineError {
            match espan {
                Some(dst_span) => {
                    let span_note = Some(ConditionSpanNote { span: dst_span.span });
                    let call_span_note = dst_span.base.map(|span| CallSpanNote { span });
                    RefineError { span, cond, span_note, call_span_note }
                }
                None => RefineError { span, cond, span_note: None, call_span_note: None },
            }
        }
    }

    #[derive(Diagnostic)]
    #[diag(refineck_div_error, code = E0999)]
    pub struct DivError {
        #[primary_span]
        pub span: Span,
    }

    #[derive(Diagnostic)]
    #[diag(refineck_rem_error, code = E0999)]
    pub struct RemError {
        #[primary_span]
        pub span: Span,
    }

    #[derive(Diagnostic)]
    #[diag(refineck_assert_error, code = E0999)]
    pub struct AssertError {
        #[primary_span]
        pub span: Span,
        pub msg: &'static str,
    }

    #[derive(Diagnostic)]
    #[diag(refineck_fold_error, code = E0999)]
    pub struct FoldError {
        #[primary_span]
        pub span: Span,
    }

    #[derive(Diagnostic)]
    #[diag(refineck_overflow_error, code = E0999)]
    pub struct OverflowError {
        #[primary_span]
        pub span: Span,
    }

    #[derive(Diagnostic)]
    #[diag(refineck_unknown_error, code = E0999)]
    pub struct UnknownError {
        #[primary_span]
        pub span: Span,
    }

    #[derive(Diagnostic)]
    #[diag(refineck_expected_neg, code = E0999)]
    pub struct ExpectedNeg {
        #[primary_span]
        pub span: Span,
        pub def_descr: &'static str,
    }
}