-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanalyze.rs
More file actions
278 lines (242 loc) · 8.63 KB
/
Copy pathanalyze.rs
File metadata and controls
278 lines (242 loc) · 8.63 KB
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
//! Analysis of Rust MIR to generate a CHC system.
//!
//! The [`Analyzer`] generates subtyping constraints in the form of CHCs ([`chc::System`]).
//! The entry point is [`crate_::Analyzer::run`], followed by [`local_def::Analyzer::run`]
//! and [`basic_block::Analyzer::run`], while accumulating the necessary information in
//! [`Analyzer`]. Once [`chc::System`] is collected for the entire input, it invokes an external
//! CHC solver with the [`Analyzer::solve`] and subsequently reports the result.
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use rustc_hir::lang_items::LangItem;
use rustc_middle::mir::{self, BasicBlock, Local};
use rustc_middle::ty::{self as mir_ty, TyCtxt};
use rustc_span::def_id::{DefId, LocalDefId};
use crate::chc;
use crate::pretty::PrettyDisplayExt as _;
use crate::refine::{self, BasicBlockType};
use crate::rty;
mod annot;
mod basic_block;
mod crate_;
mod did_cache;
mod local_def;
pub fn local_of_function_param(idx: rty::FunctionParamIdx) -> Local {
Local::from(idx.index() + 1)
}
pub fn resolve_discr(tcx: TyCtxt<'_>, discr: mir_ty::VariantDiscr) -> u32 {
match discr {
mir_ty::VariantDiscr::Relative(i) => i,
mir_ty::VariantDiscr::Explicit(did) => {
let val = tcx.const_eval_poly(did).unwrap();
val.try_to_scalar_int().unwrap().try_to_u32().unwrap()
}
}
}
pub struct ReplacePlacesVisitor<'tcx> {
replacements: HashMap<(Local, &'tcx [mir::PlaceElem<'tcx>]), mir::Place<'tcx>>,
tcx: TyCtxt<'tcx>,
}
impl<'tcx> mir::visit::MutVisitor<'tcx> for ReplacePlacesVisitor<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn visit_place(
&mut self,
place: &mut mir::Place<'tcx>,
_: mir::visit::PlaceContext,
_: mir::Location,
) {
let proj = place.projection.as_slice();
for i in 0..=proj.len() {
if let Some(to) = self.replacements.get(&(place.local, &proj[0..i])) {
place.local = to.local;
place.projection = self.tcx.mk_place_elems_from_iter(
to.projection.iter().chain(proj.iter().skip(i).cloned()),
);
return;
}
}
}
}
impl<'tcx> ReplacePlacesVisitor<'tcx> {
pub fn new(tcx: TyCtxt<'tcx>) -> Self {
Self {
tcx,
replacements: Default::default(),
}
}
pub fn with_replacement(
tcx: TyCtxt<'tcx>,
from: mir::Place<'tcx>,
to: mir::Place<'tcx>,
) -> Self {
let mut visitor = Self::new(tcx);
visitor.add_replacement(from, to);
visitor
}
pub fn add_replacement(&mut self, from: mir::Place<'tcx>, to: mir::Place<'tcx>) {
self.replacements
.insert((from.local, from.projection.as_slice()), to);
}
pub fn visit_statement(&mut self, stmt: &mut mir::Statement<'tcx>) {
// dummy location
mir::visit::MutVisitor::visit_statement(self, stmt, mir::Location::START);
}
pub fn visit_terminator(&mut self, term: &mut mir::Terminator<'tcx>) {
// dummy location
mir::visit::MutVisitor::visit_terminator(self, term, mir::Location::START);
}
}
#[derive(Clone)]
pub struct Analyzer<'tcx> {
tcx: TyCtxt<'tcx>,
/// Collection of refined known def types.
///
/// currently contains only local-def templates,
/// but will be extended to contain externally known def's refinement types
/// (at least for every defs referenced by local def bodies)
defs: HashMap<DefId, rty::RefinedType>,
/// Resulting CHC system.
system: Rc<RefCell<chc::System>>,
basic_blocks: HashMap<LocalDefId, HashMap<BasicBlock, BasicBlockType>>,
def_ids: did_cache::DefIdCache<'tcx>,
enum_defs: Rc<RefCell<HashMap<DefId, rty::EnumDatatypeDef>>>,
}
impl<'tcx> crate::refine::TemplateRegistry for Analyzer<'tcx> {
fn register_template<V>(&mut self, tmpl: rty::Template<V>) -> rty::RefinedType<V> {
tmpl.into_refined_type(|pred_sig| self.generate_pred_var(pred_sig))
}
}
impl<'tcx> Analyzer<'tcx> {
pub fn generate_pred_var(&mut self, sig: chc::PredSig) -> chc::PredVarId {
self.system
.borrow_mut()
.new_pred_var(sig, chc::DebugInfo::from_current_span())
}
}
impl<'tcx> Analyzer<'tcx> {
pub fn new(tcx: TyCtxt<'tcx>) -> Self {
let defs = Default::default();
let system = Default::default();
let basic_blocks = Default::default();
let enum_defs = Default::default();
Self {
tcx,
defs,
system,
basic_blocks,
def_ids: did_cache::DefIdCache::new(tcx),
enum_defs,
}
}
pub fn add_clause(&mut self, clause: chc::Clause) {
self.system.borrow_mut().push_clause(clause);
}
pub fn extend_clauses(&mut self, clauses: impl IntoIterator<Item = chc::Clause>) {
for clause in clauses {
self.add_clause(clause);
}
}
pub fn register_enum_def(&mut self, def_id: DefId, enum_def: rty::EnumDatatypeDef) {
tracing::debug!(def_id = ?def_id, enum_def = ?enum_def, "register_enum_def");
let ctors = enum_def
.variants
.iter()
.map(|v| chc::DatatypeCtor {
symbol: v.name.clone(),
selectors: v
.field_tys
.clone()
.into_iter()
.enumerate()
.map(|(idx, ty)| chc::DatatypeSelector {
symbol: chc::DatatypeSymbol::new(format!("_get{}.{}", v.name, idx)),
sort: ty.to_sort(),
})
.collect(),
discriminant: v.discr,
})
.collect();
let datatype = chc::Datatype {
symbol: enum_def.name.clone(),
params: enum_def.ty_params,
ctors,
};
self.enum_defs.borrow_mut().insert(def_id, enum_def);
self.system.borrow_mut().datatypes.push(datatype);
}
pub fn find_enum_variant(
&self,
ty_sym: &chc::DatatypeSymbol,
v_sym: &chc::DatatypeSymbol,
) -> Option<rty::EnumVariantDef> {
self.enum_defs
.borrow()
.iter()
.find(|(_, d)| &d.name == ty_sym)
.and_then(|(_, d)| d.variants.iter().find(|v| &v.name == v_sym))
.cloned()
}
pub fn register_def(&mut self, def_id: DefId, rty: rty::RefinedType) {
tracing::info!(def_id = ?def_id, rty = %rty.display(), "register_def");
self.defs.insert(def_id, rty);
}
pub fn def_ty(&self, def_id: DefId) -> Option<&rty::RefinedType> {
self.defs.get(&def_id)
}
pub fn register_basic_block_ty(
&mut self,
def_id: LocalDefId,
bb: BasicBlock,
rty: BasicBlockType,
) {
tracing::debug!(def_id = ?def_id, ?bb, rty = %rty.display(), "register_basic_block_ty");
self.basic_blocks.entry(def_id).or_default().insert(bb, rty);
}
pub fn basic_block_ty(&self, def_id: LocalDefId, bb: BasicBlock) -> &BasicBlockType {
&self.basic_blocks[&def_id][&bb]
}
pub fn register_well_known_defs(&mut self) {
let panic_ty = {
let param = rty::RefinedType::new(
rty::PointerType::immut_to(rty::Type::string()).into(),
rty::Refinement::bottom(),
);
let ret = rty::RefinedType::new(rty::Type::never(), rty::Refinement::bottom());
rty::FunctionType::new([param.vacuous()].into_iter().collect(), ret)
};
let panic_def_id = self.tcx.require_lang_item(LangItem::Panic, None);
self.register_def(panic_def_id, rty::RefinedType::unrefined(panic_ty.into()));
}
pub fn new_env(&self) -> refine::Env {
let defs = self
.enum_defs
.borrow()
.values()
.map(|def| (def.name.clone(), def.clone()))
.collect();
refine::Env::new(defs)
}
pub fn crate_analyzer(&mut self) -> crate_::Analyzer<'tcx, '_> {
crate_::Analyzer::new(self)
}
pub fn local_def_analyzer(
&mut self,
local_def_id: LocalDefId,
) -> local_def::Analyzer<'tcx, '_> {
local_def::Analyzer::new(self, local_def_id)
}
pub fn basic_block_analyzer(
&mut self,
local_def_id: LocalDefId,
bb: BasicBlock,
) -> basic_block::Analyzer<'tcx, '_> {
basic_block::Analyzer::new(self, local_def_id, bb)
}
pub fn solve(&mut self) {
if let Err(err) = self.system.borrow().solve() {
self.tcx.dcx().err(format!("verification error: {:?}", err));
}
}
}