forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction_symbols.rs
More file actions
395 lines (359 loc) · 12.3 KB
/
Copy pathfunction_symbols.rs
File metadata and controls
395 lines (359 loc) · 12.3 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
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
use driver::DriverDataBase;
use hir::analysis::{
semantic::SemanticInstance,
ty::{
ty_check::BodyOwner,
ty_def::{TyBase, TyData, TyId},
},
};
use mir::{
RuntimeFunctionOwner,
runtime::stable_key::{
generic_args_identity, ingot_component_for_scope, module_path_components_for_scope,
semantic_owner_context_identity, stable_identity_hash,
},
};
use rustc_hash::FxHashSet;
use std::collections::BTreeMap;
const GENERIC_SUFFIX_HASH_LEN: usize = 4;
const OWNER_CONTEXT_HASH_LEN: usize = 4;
const CONFLICT_SUFFIX_HASH_LEN: usize = 4;
const SEGMENT_SEPARATOR: &str = "__";
const VARIANT_SEPARATOR: &str = "_";
const FALLBACK_SEPARATOR: &str = "_";
struct OwnerContextCandidates {
primary: Option<String>,
fallback: Option<String>,
}
pub(crate) struct FunctionSymbolInput<'db> {
pub owner: RuntimeFunctionOwner<'db>,
pub fallback_symbol: String,
pub variant_suffix: String,
pub disambiguator: String,
}
pub(crate) fn assign_function_symbols<'db>(
db: &'db DriverDataBase,
inputs: &[FunctionSymbolInput<'db>],
) -> Vec<String> {
let candidates = inputs
.iter()
.map(|input| function_symbol_candidates(db, input))
.collect::<Vec<_>>();
let mut selected = vec![0usize; candidates.len()];
loop {
let conflicts = symbol_conflicts(&candidates, &selected);
if conflicts.values().all(|group| group.len() == 1) {
break;
}
let mut changed = false;
for group in conflicts.values().filter(|group| group.len() > 1) {
for &idx in group {
if selected[idx] + 1 < candidates[idx].len() {
selected[idx] += 1;
changed = true;
}
}
}
if !changed {
break;
}
}
let mut symbols = candidates
.iter()
.zip(selected)
.map(|(candidates, selected)| candidates[selected].clone())
.collect::<Vec<_>>();
uniquify_function_symbols(&mut symbols, &candidates, inputs);
symbols
}
fn function_symbol_candidates<'db>(
db: &'db DriverDataBase,
input: &FunctionSymbolInput<'db>,
) -> Vec<String> {
match &input.owner {
RuntimeFunctionOwner::Semantic(semantic) => {
semantic_function_symbol_candidates(db, *semantic, &input.variant_suffix)
}
RuntimeFunctionOwner::Synthetic(_) => {
vec![render_raw_symbol(
&input.fallback_symbol,
&input.variant_suffix,
)]
}
}
}
fn semantic_function_symbol_candidates<'db>(
db: &'db DriverDataBase,
semantic: SemanticInstance<'db>,
variant_suffix: &str,
) -> Vec<String> {
let owner = semantic.key(db).owner(db);
let leaf = semantic_leaf_component(db, owner);
let generic = generic_component(db, semantic.key(db).subst(db).generic_args(db));
let owner_context = semantic_owner_context_candidates(db, owner);
let module_path = module_path_components_for_scope(db, owner.scope());
let ingot = ingot_component_for_scope(db, owner.scope());
let mut candidates = Vec::new();
push_symbol_candidate(&mut candidates, vec![leaf.clone()], variant_suffix);
if let Some(generic) = &generic {
push_symbol_candidate(
&mut candidates,
vec![leaf.clone(), generic.clone()],
variant_suffix,
);
}
let mut scoped_leaf = vec![leaf];
if let Some(generic) = generic {
scoped_leaf.push(generic);
}
if let Some(owner_context) = &owner_context.primary {
let mut parts = vec![owner_context.clone()];
parts.extend(scoped_leaf.clone());
push_symbol_candidate(&mut candidates, parts, variant_suffix);
}
let mut module_parts = module_path.clone();
if let Some(owner_context) = &owner_context.primary {
module_parts.push(owner_context.clone());
}
module_parts.extend(scoped_leaf.clone());
push_symbol_candidate(&mut candidates, module_parts.clone(), variant_suffix);
let mut ingot_parts = vec![ingot];
ingot_parts.extend(module_parts.clone());
push_symbol_candidate(&mut candidates, ingot_parts, variant_suffix);
if let Some(fallback_context) = &owner_context.fallback {
let mut parts = vec![fallback_context.clone()];
parts.extend(scoped_leaf.clone());
push_symbol_candidate(&mut candidates, parts, variant_suffix);
let mut module_parts = module_path;
module_parts.push(fallback_context.clone());
module_parts.extend(scoped_leaf.clone());
push_symbol_candidate(&mut candidates, module_parts.clone(), variant_suffix);
let mut ingot_parts = vec![ingot_component_for_scope(db, owner.scope())];
ingot_parts.extend(module_parts);
push_symbol_candidate(&mut candidates, ingot_parts, variant_suffix);
}
candidates
}
fn push_symbol_candidate(candidates: &mut Vec<String>, parts: Vec<String>, variant_suffix: &str) {
let symbol = render_symbol(parts, variant_suffix);
if candidates.iter().all(|candidate| *candidate != symbol) {
candidates.push(symbol);
}
}
fn render_symbol(parts: Vec<String>, variant_suffix: &str) -> String {
let mut symbol = parts
.into_iter()
.filter(|part| !part.is_empty())
.map(|part| sanitize_ident_segment(&part))
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(SEGMENT_SEPARATOR);
if symbol.is_empty() {
symbol = sanitize_ident_segment("symbol");
}
if !variant_suffix.is_empty() {
symbol.push_str(VARIANT_SEPARATOR);
symbol.push_str(&sanitize_ident_segment(variant_suffix));
}
symbol
}
fn render_raw_symbol(symbol: &str, variant_suffix: &str) -> String {
render_symbol(vec![symbol.to_string()], variant_suffix)
}
fn sanitize_ident_segment(value: &str) -> String {
let sanitized = value
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || ch == '_' {
ch
} else {
'_'
}
})
.collect::<String>();
if sanitized
.chars()
.next()
.is_some_and(|ch| ch.is_ascii_alphabetic() || ch == '_')
{
sanitized
} else {
format!("_{sanitized}")
}
}
fn symbol_conflicts(
candidates: &[Vec<String>],
selected: &[usize],
) -> BTreeMap<String, Vec<usize>> {
selected
.iter()
.enumerate()
.fold(BTreeMap::new(), |mut conflicts, (idx, selected)| {
conflicts
.entry(candidates[idx][*selected].clone())
.or_insert_with(Vec::new)
.push(idx);
conflicts
})
}
fn uniquify_function_symbols(
symbols: &mut [String],
candidates: &[Vec<String>],
inputs: &[FunctionSymbolInput<'_>],
) {
let conflicts = symbols.iter().enumerate().fold(
BTreeMap::<String, Vec<usize>>::new(),
|mut conflicts, (idx, symbol)| {
conflicts.entry(symbol.clone()).or_default().push(idx);
conflicts
},
);
let mut used = conflicts
.iter()
.filter(|(_, group)| group.len() == 1)
.map(|(symbol, _)| symbol.clone())
.collect::<FxHashSet<_>>();
for group in conflicts.values().filter(|group| group.len() > 1) {
let mut group = group.clone();
group.sort_by(|lhs, rhs| {
candidates[*lhs]
.cmp(&candidates[*rhs])
.then_with(|| inputs[*lhs].disambiguator.cmp(&inputs[*rhs].disambiguator))
.then_with(|| lhs.cmp(rhs))
});
for idx in group {
let base = symbols[idx].clone();
let hash = stable_identity_hash(&inputs[idx].disambiguator);
let candidate = format!(
"{base}{FALLBACK_SEPARATOR}{}",
&hash[..CONFLICT_SUFFIX_HASH_LEN]
);
if used.insert(candidate.clone()) {
symbols[idx] = candidate;
continue;
}
for suffix in 0.. {
let candidate = format!(
"{base}{FALLBACK_SEPARATOR}{}{FALLBACK_SEPARATOR}{suffix}",
&hash[..CONFLICT_SUFFIX_HASH_LEN]
);
if used.insert(candidate.clone()) {
symbols[idx] = candidate;
break;
}
}
}
}
}
fn semantic_leaf_component<'db>(db: &'db DriverDataBase, owner: BodyOwner<'db>) -> String {
match owner {
BodyOwner::Func(func) => func
.name(db)
.to_opt()
.map(|name| name.data(db).to_string())
.unwrap_or_else(|| "__anon".to_string()),
BodyOwner::Const(const_) => const_
.name(db)
.to_opt()
.map(|name| name.data(db).to_string())
.unwrap_or_else(|| "__const".to_string()),
BodyOwner::AnonConstBody { .. } => "__anon_const".to_string(),
BodyOwner::ContractInit { contract } => format!(
"__{}_init",
contract
.name(db)
.to_opt()
.map(|name| name.data(db).to_string())
.unwrap_or_else(|| "contract".to_string())
),
BodyOwner::ContractRecvArm {
contract,
recv_idx,
arm_idx,
} => format!(
"__{}_recv_{}_{}",
contract
.name(db)
.to_opt()
.map(|name| name.data(db).to_string())
.unwrap_or_else(|| "contract".to_string()),
recv_idx,
arm_idx
),
}
}
fn semantic_owner_context_candidates<'db>(
db: &'db DriverDataBase,
owner: BodyOwner<'db>,
) -> OwnerContextCandidates {
let stable = semantic_owner_context_identity(db, owner);
let readable = readable_owner_context(db, owner);
let primary = readable
.clone()
.or_else(|| stable.clone().map(shorten_owner_context_hash));
let fallback = readable
.zip(stable.as_deref().and_then(short_owner_context_hash))
.map(|(readable, hash)| format!("{readable}${hash}"))
.filter(|fallback| Some(fallback) != primary.as_ref());
OwnerContextCandidates { primary, fallback }
}
fn readable_owner_context<'db>(db: &'db DriverDataBase, owner: BodyOwner<'db>) -> Option<String> {
let BodyOwner::Func(func) = owner else {
return None;
};
if let Some(impl_) = func.containing_impl(db) {
return readable_type_component(db, impl_.ty(db)).map(|ty| format!("impl${ty}"));
}
if let Some(impl_trait) = func.containing_impl_trait(db) {
return readable_type_component(db, impl_trait.ty(db)).map(|ty| format!("impl_trait${ty}"));
}
None
}
fn readable_type_component<'db>(db: &'db DriverDataBase, ty: TyId<'db>) -> Option<String> {
let base = ty.base_ty(db);
match base.data(db) {
TyData::TyBase(TyBase::Adt(adt)) => adt
.adt_ref(db)
.name(db)
.map(|name| name.data(db).to_string()),
TyData::TyBase(TyBase::Contract(contract)) => contract
.name(db)
.to_opt()
.map(|name| name.data(db).to_string()),
TyData::TyBase(TyBase::Prim(_) | TyBase::Func(_))
| TyData::TyParam(_)
| TyData::QualifiedTy(_) => {
let component = base.pretty_print(db).to_string();
(!component.is_empty()).then_some(component)
}
TyData::AssocTy(_)
| TyData::ConstTy(_)
| TyData::Never
| TyData::TyVar(_)
| TyData::Invalid(_)
| TyData::TyApp(..) => None,
}
}
fn shorten_owner_context_hash(context: String) -> String {
if let Some(hash) = short_owner_context_hash(&context)
&& let Some((kind, _)) = context.split_once('$')
{
return format!("{kind}${hash}");
}
context
}
fn short_owner_context_hash(context: &str) -> Option<&str> {
if let Some((kind, hash)) = context.split_once('$')
&& matches!(kind, "impl" | "impl_trait")
&& hash.len() > OWNER_CONTEXT_HASH_LEN
{
return Some(&hash[..OWNER_CONTEXT_HASH_LEN]);
}
None
}
fn generic_component<'db>(db: &'db DriverDataBase, args: &[TyId<'db>]) -> Option<String> {
(!args.is_empty()).then(|| {
let hash = stable_identity_hash(&generic_args_identity(db, args));
format!("g{}", &hash[..GENERIC_SUFFIX_HASH_LEN])
})
}