Skip to content

Commit 2edd1d5

Browse files
committed
Implement keyword suggestion routine
`suggestions.rs` is almost porting of implementation of [this](python/cpython#16856) and [this](python/cpython#25397). Signed-off-by: snowapril <[email protected]>
1 parent 273729d commit 2edd1d5

File tree

3 files changed

+174
-1
lines changed

3 files changed

+174
-1
lines changed

vm/src/builtins/code.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ impl PyRef<PyCode> {
256256
}
257257

258258
#[pyproperty]
259-
fn co_varnames(self, vm: &VirtualMachine) -> PyTupleRef {
259+
pub fn co_varnames(self, vm: &VirtualMachine) -> PyTupleRef {
260260
let varnames = self
261261
.code
262262
.varnames

vm/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ mod signal;
7171
pub mod sliceable;
7272
pub mod slots;
7373
pub mod stdlib;
74+
pub mod suggestions;
7475
pub mod types;
7576
pub mod utils;
7677
pub mod version;

vm/src/suggestions.rs

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
use crate::common::lock::PyRwLock;
2+
use crate::{
3+
builtins::{PyBaseObject, PyList, PyStrRef},
4+
exceptions::types::PyBaseExceptionRef,
5+
sliceable::PySliceableSequence,
6+
IdProtocol, PyObjectRef, TryFromObject, TypeProtocol, VirtualMachine,
7+
};
8+
9+
const MAX_CANDIDATE_ITEMS: usize = 750;
10+
const MAX_STRING_SIZE: usize = 40;
11+
12+
const MOVE_COST: usize = 2;
13+
const CASE_COST: usize = 1;
14+
15+
fn substitution_cost(mut a: u8, mut b: u8) -> usize {
16+
if (a & 31) != (b & 31) {
17+
return MOVE_COST;
18+
}
19+
if a == b {
20+
return 0usize;
21+
}
22+
if (b'A'..=b'Z').contains(&a) {
23+
a += b'a' - b'A';
24+
}
25+
if (b'A'..=b'Z').contains(&b) {
26+
b += b'a' - b'A';
27+
}
28+
if a == b {
29+
CASE_COST
30+
} else {
31+
MOVE_COST
32+
}
33+
}
34+
35+
fn global_levelshtein_buffer() -> &'static PyRwLock<[usize; MAX_STRING_SIZE]> {
36+
rustpython_common::static_cell! {
37+
static BUFFER: PyRwLock<[usize; MAX_STRING_SIZE]>;
38+
};
39+
BUFFER.get_or_init(|| PyRwLock::new([0usize; MAX_STRING_SIZE]))
40+
}
41+
42+
fn levelshtein_distance(a: &str, b: &str, max_cost: usize) -> usize {
43+
if a == b {
44+
return 0;
45+
}
46+
47+
let (mut a_bytes, mut b_bytes) = (a.as_bytes(), b.as_bytes());
48+
let (mut a_begin, mut a_end) = (0usize, a.len());
49+
let (mut b_begin, mut b_end) = (0usize, b.len());
50+
51+
while a_end > 0 && b_end > 0 && a_bytes[a_begin] == b_bytes[b_begin] {
52+
a_begin += 1;
53+
b_begin += 1;
54+
a_end -= 1;
55+
b_end -= 1;
56+
}
57+
while a_end > 0 && b_end > 0 && a_bytes[a_begin + a_end - 1] == b_bytes[b_begin + b_end - 1] {
58+
a_end -= 1;
59+
b_end -= 1;
60+
}
61+
if a_end == 0 || b_end == 0 {
62+
return (a_end + b_end) * MOVE_COST;
63+
}
64+
if a_end > MAX_STRING_SIZE || b_end > MAX_STRING_SIZE {
65+
return max_cost + 1;
66+
}
67+
68+
if b_end < a_end {
69+
std::mem::swap(&mut a_bytes, &mut b_bytes);
70+
std::mem::swap(&mut a_begin, &mut b_begin);
71+
std::mem::swap(&mut a_end, &mut b_end);
72+
}
73+
74+
if (b_end - a_end) * MOVE_COST > max_cost {
75+
return max_cost + 1;
76+
}
77+
78+
for i in 0..a_end {
79+
global_levelshtein_buffer().write()[i] = (i + 1) * MOVE_COST;
80+
}
81+
82+
let mut result = 0usize;
83+
for (b_index, b_code) in b_bytes[b_begin..(b_begin + b_end)].iter().enumerate() {
84+
result = b_index * MOVE_COST;
85+
let mut distance = result;
86+
let mut minimum = usize::MAX;
87+
for (a_index, a_code) in a_bytes[a_begin..(a_begin + a_end)].iter().enumerate() {
88+
let substitute = distance + substitution_cost(*b_code, *a_code);
89+
distance = global_levelshtein_buffer().read()[a_index];
90+
let insert_delete = usize::min(result, distance) + MOVE_COST;
91+
result = usize::min(insert_delete, substitute);
92+
93+
global_levelshtein_buffer().write()[a_index] = result;
94+
if result < minimum {
95+
minimum = result;
96+
}
97+
}
98+
if minimum > max_cost {
99+
return max_cost + 1;
100+
}
101+
}
102+
result
103+
}
104+
105+
fn calculate_suggestions(dir: PyList, name: &PyObjectRef, vm: &VirtualMachine) -> Option<PyStrRef> {
106+
let dir = dir.borrow_vec();
107+
if dir.len() >= MAX_CANDIDATE_ITEMS {
108+
return None;
109+
}
110+
111+
let mut suggestion: Option<PyStrRef> = None;
112+
let mut suggestion_distance = usize::MAX;
113+
let name = match PyStrRef::try_from_object(vm, name.clone()) {
114+
Ok(name) => name,
115+
Err(_) => return None,
116+
};
117+
118+
for item in dir.iter() {
119+
let item_name = match PyStrRef::try_from_object(vm, item.clone()) {
120+
Ok(name) => name,
121+
Err(_) => return None,
122+
};
123+
if name.to_string() == item_name.to_string() {
124+
continue;
125+
}
126+
let max_distance = usize::min(
127+
(name.len() + item_name.len() + 3) * MOVE_COST / 6,
128+
suggestion_distance - 1,
129+
);
130+
let current_distance =
131+
levelshtein_distance(name.as_str(), item_name.as_str(), max_distance);
132+
if current_distance > max_distance {
133+
continue;
134+
}
135+
if suggestion.is_none() || current_distance < suggestion_distance {
136+
suggestion = Some(item_name);
137+
suggestion_distance = current_distance;
138+
}
139+
}
140+
suggestion
141+
}
142+
143+
pub fn offer_suggestions(exc: &PyBaseExceptionRef, vm: &VirtualMachine) -> Option<PyStrRef> {
144+
if exc.class().is(&vm.ctx.exceptions.attribute_error) {
145+
let name = vm.get_attribute(exc.as_object().clone(), "name").unwrap();
146+
let obj = vm.get_attribute(exc.as_object().clone(), "obj").unwrap();
147+
calculate_suggestions(PyBaseObject::dir(obj, vm).unwrap(), &name, vm)
148+
} else if exc.class().is(&vm.ctx.exceptions.name_error) {
149+
let name = vm.get_attribute(exc.as_object().clone(), "name").unwrap();
150+
let mut tb = exc.traceback().unwrap();
151+
while let Some(traceback) = tb.next.clone() {
152+
tb = traceback;
153+
}
154+
155+
let frame = tb.frame.clone();
156+
let code = frame.code.clone();
157+
let varnames = PyList::from(code.co_varnames(vm).as_slice().to_vec());
158+
if let Some(suggestions) = calculate_suggestions(varnames, &name, vm) {
159+
return Some(suggestions);
160+
};
161+
162+
let globals = PyList::from(vm.extract_elements(frame.globals.as_object()).unwrap());
163+
if let Some(suggestions) = calculate_suggestions(globals, &name, vm) {
164+
return Some(suggestions);
165+
};
166+
167+
let builtins = PyList::from(vm.extract_elements(frame.builtins.as_object()).unwrap());
168+
calculate_suggestions(builtins, &name, vm)
169+
} else {
170+
None
171+
}
172+
}

0 commit comments

Comments
 (0)