rename HintEnum and some cleanup

This commit is contained in:
Simon Gardling 2022-04-12 10:17:04 -04:00
parent d2298e69a2
commit 2b684ecb88
5 changed files with 58 additions and 63 deletions

View File

@ -48,7 +48,7 @@ fn generate_hashmap() {
write!( write!(
&mut file, &mut file,
"static COMPLETION_HASHMAP: phf::Map<&'static str, HintEnum> = {};", "static COMPLETION_HASHMAP: phf::Map<&'static str, Hint> = {};",
hashmap.build() hashmap.build()
) )
.expect("Could not write to file"); .expect("Could not write to file");

View File

@ -34,7 +34,7 @@ pub fn compile_hashmap(data: Vec<String>) -> Vec<(String, String)> {
seen_3.insert(key.clone()); seen_3.insert(key.clone());
if keys.iter().filter(|a| a == &&key).count() == 1 { if keys.iter().filter(|a| a == &&key).count() == 1 {
output.push((key.clone(), format!(r#"HintEnum::Single("{}")"#, value))); output.push((key.clone(), format!(r#"Hint::Single("{}")"#, value)));
} else { } else {
let mut multi_data = tuple_list_1 let mut multi_data = tuple_list_1
.iter() .iter()
@ -42,7 +42,7 @@ pub fn compile_hashmap(data: Vec<String>) -> Vec<(String, String)> {
.map(|(_, b)| b) .map(|(_, b)| b)
.collect::<Vec<&String>>(); .collect::<Vec<&String>>();
multi_data.sort_unstable_by(|a, b| compare_len_reverse_alpha(a, b)); multi_data.sort_unstable_by(|a, b| compare_len_reverse_alpha(a, b));
output.push((key.clone(), format!("HintEnum::Many(&{:?})", multi_data))); output.push((key.clone(), format!("Hint::Many(&{:?})", multi_data)));
} }
} }
println!("Done! {:?}", start.elapsed()); println!("Done! {:?}", start.elapsed());
@ -80,15 +80,15 @@ mod tests {
fn hashmap_gen_test() { fn hashmap_gen_test() {
let data = vec!["time", "text", "test"]; let data = vec!["time", "text", "test"];
let expect = vec![ let expect = vec![
("t", r#"HintEnum::Many(&["ime(", "ext(", "est("])"#), ("t", r#"Hint::Many(&["ime(", "ext(", "est("])"#),
("ti", r#"HintEnum::Single("me(")"#), ("ti", r#"Hint::Single("me(")"#),
("tim", r#"HintEnum::Single("e(")"#), ("tim", r#"Hint::Single("e(")"#),
("time", r#"HintEnum::Single("(")"#), ("time", r#"Hint::Single("(")"#),
("te", r#"HintEnum::Many(&["xt(", "st("])"#), ("te", r#"Hint::Many(&["xt(", "st("])"#),
("tex", r#"HintEnum::Single("t(")"#), ("tex", r#"Hint::Single("t(")"#),
("text", r#"HintEnum::Single("(")"#), ("text", r#"Hint::Single("(")"#),
("tes", r#"HintEnum::Single("t(")"#), ("tes", r#"Hint::Single("t(")"#),
("test", r#"HintEnum::Single("(")"#), ("test", r#"Hint::Single("(")"#),
]; ];
assert_eq!( assert_eq!(

View File

@ -87,7 +87,7 @@ impl Default for FunctionEntry {
impl FunctionEntry { impl FunctionEntry {
/// Create autocomplete ui and handle user input /// Create autocomplete ui and handle user input
pub fn auto_complete(&mut self, ui: &mut egui::Ui, i: i32) { pub fn auto_complete(&mut self, ui: &mut egui::Ui, i: i32) {
self.autocomplete.update(&self.raw_func_str); self.autocomplete.update_string(&self.raw_func_str);
self.autocomplete.ui(ui, i); self.autocomplete.ui(ui, i);
let output_string = self.autocomplete.string.clone(); let output_string = self.autocomplete.string.clone();

View File

@ -1,12 +1,12 @@
use crate::misc::chars_take; use crate::misc::chars_take;
pub const HINTENUM_EMPTY: HintEnum = HintEnum::Single("x^2"); pub const HINT_EMPTY: Hint = Hint::Single("x^2");
const HINTENUM_CLOSED_PARENS: HintEnum = HintEnum::Single(")"); const HINT_CLOSED_PARENS: Hint = Hint::Single(")");
/// Generate a hint based on the input `input`, returns an `Option<String>` /// Generate a hint based on the input `input`, returns an `Option<String>`
pub fn generate_hint<'a>(input: &str) -> &'a HintEnum<'a> { pub fn generate_hint<'a>(input: &str) -> &'a Hint<'a> {
if input.is_empty() { if input.is_empty() {
return &HINTENUM_EMPTY; return &HINT_EMPTY;
} }
let chars: Vec<char> = input.chars().collect::<Vec<char>>(); let chars: Vec<char> = input.chars().collect::<Vec<char>>();
@ -20,7 +20,7 @@ pub fn generate_hint<'a>(input: &str) -> &'a HintEnum<'a> {
}); });
if open_parens > closed_parens { if open_parens > closed_parens {
return &HINTENUM_CLOSED_PARENS; return &HINT_CLOSED_PARENS;
} }
let len = chars.len(); let len = chars.len();
@ -36,49 +36,44 @@ pub fn generate_hint<'a>(input: &str) -> &'a HintEnum<'a> {
} }
} }
&HintEnum::None &Hint::None
} }
#[derive(PartialEq)] #[derive(PartialEq)]
pub enum HintEnum<'a> { pub enum Hint<'a> {
Single(&'a str), Single(&'a str),
Many(&'a [&'a str]), Many(&'a [&'a str]),
None, None,
} }
impl<'a> std::fmt::Debug for HintEnum<'a> { impl<'a> std::fmt::Debug for Hint<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self) } fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self) }
} }
impl<'a> std::fmt::Display for HintEnum<'a> { impl<'a> std::fmt::Display for Hint<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
HintEnum::Single(single_data) => { Hint::Single(single_data) => {
return write!(f, "{}", single_data); return write!(f, "{}", single_data);
} }
HintEnum::Many(multi_data) => { Hint::Many(multi_data) => {
return write!(f, "{:?}", multi_data); return write!(f, "{:?}", multi_data);
} }
HintEnum::None => { Hint::None => {
return write!(f, "None"); return write!(f, "None");
} }
} }
} }
} }
impl<'a> HintEnum<'a> { impl<'a> Hint<'a> {
pub fn is_none(&self) -> bool { matches!(self, HintEnum::None) } pub fn is_none(&self) -> bool { matches!(self, Hint::None) }
#[allow(dead_code)] #[allow(dead_code)]
pub fn is_some(&self) -> bool { !self.is_none() } pub fn is_some(&self) -> bool { !self.is_none() }
#[allow(dead_code)] #[allow(dead_code)]
pub fn is_single(&self) -> bool { pub fn is_single(&self) -> bool { matches!(self, Hint::Single(_)) }
match self {
HintEnum::Single(_) => true,
_ => false,
}
}
} }
include!(concat!(env!("OUT_DIR"), "/codegen.rs")); include!(concat!(env!("OUT_DIR"), "/codegen.rs"));
@ -93,13 +88,13 @@ mod tests {
#[test] #[test]
fn hint_test() { fn hint_test() {
let values = HashMap::from([ let values = HashMap::from([
("", HintEnum::Single("x^2")), ("", Hint::Single("x^2")),
("si", HintEnum::Many(&["n(", "nh(", "gnum("])), ("si", Hint::Many(&["n(", "nh(", "gnum("])),
("log", HintEnum::Many(&["2(", "10("])), ("log", Hint::Many(&["2(", "10("])),
("cos", HintEnum::Many(&["(", "h("])), ("cos", Hint::Many(&["(", "h("])),
("sin(", HintEnum::Single(")")), ("sin(", Hint::Single(")")),
("sqrt", HintEnum::Single("(")), ("sqrt", Hint::Single("(")),
("ln(x)", HintEnum::None), ("ln(x)", Hint::None),
]); ]);
for (key, value) in values { for (key, value) in values {
@ -111,13 +106,13 @@ mod tests {
#[test] #[test]
fn hint_to_string_test() { fn hint_to_string_test() {
let values = HashMap::from([ let values = HashMap::from([
("x^2", HintEnum::Single("x^2")), ("x^2", Hint::Single("x^2")),
( (
r#"["n(", "nh(", "gnum("]"#, r#"["n(", "nh(", "gnum("]"#,
HintEnum::Many(&["n(", "nh(", "gnum("]), Hint::Many(&["n(", "nh(", "gnum("]),
), ),
(r#"["n("]"#, HintEnum::Many(&["n("])), (r#"["n("]"#, Hint::Many(&["n("])),
("None", HintEnum::None), ("None", Hint::None),
]); ]);
for (key, value) in values { for (key, value) in values {

View File

@ -1,4 +1,4 @@
use crate::suggestions::{generate_hint, HintEnum}; use crate::suggestions::{generate_hint, Hint};
use eframe::{egui, epaint}; use eframe::{egui, epaint};
use egui::{text::CCursor, text_edit::CursorRange, Key, Modifiers, TextEdit, Widget}; use egui::{text::CCursor, text_edit::CursorRange, Key, Modifiers, TextEdit, Widget};
use epaint::text::cursor::{Cursor, PCursor, RCursor}; use epaint::text::cursor::{Cursor, PCursor, RCursor};
@ -14,7 +14,7 @@ enum Movement {
#[derive(Clone)] #[derive(Clone)]
pub struct AutoComplete<'a> { pub struct AutoComplete<'a> {
pub i: usize, pub i: usize,
pub hint: &'a HintEnum<'a>, pub hint: &'a Hint<'a>,
pub string: String, pub string: String,
} }
@ -26,14 +26,14 @@ impl<'a> Default for AutoComplete<'a> {
fn default() -> AutoComplete<'a> { fn default() -> AutoComplete<'a> {
AutoComplete { AutoComplete {
i: 0, i: 0,
hint: &crate::suggestions::HINTENUM_EMPTY, hint: &crate::suggestions::HINT_EMPTY,
string: String::new(), string: String::new(),
} }
} }
} }
impl<'a> AutoComplete<'a> { impl<'a> AutoComplete<'a> {
pub fn update(&mut self, string: &str) { pub fn update_string(&mut self, string: &str) {
if &self.string != string { if &self.string != string {
self.i = 0; self.i = 0;
self.string = string.to_string(); self.string = string.to_string();
@ -47,7 +47,7 @@ impl<'a> AutoComplete<'a> {
} }
match self.hint { match self.hint {
HintEnum::Many(hints) => { Hint::Many(hints) => {
if movement == &Movement::Complete { if movement == &Movement::Complete {
self.apply_hint(hints[self.i]); self.apply_hint(hints[self.i]);
return; return;
@ -71,18 +71,18 @@ impl<'a> AutoComplete<'a> {
_ => unreachable!(), _ => unreachable!(),
} }
} }
HintEnum::Single(hint) => { Hint::Single(hint) => {
if movement == &Movement::Complete { if movement == &Movement::Complete {
self.apply_hint(hint); self.apply_hint(hint);
} }
} }
HintEnum::None => {} Hint::None => {}
} }
} }
fn apply_hint(&mut self, hint: &str) { fn apply_hint(&mut self, hint: &str) {
let new_string = self.string.clone() + hint; let new_string = self.string.clone() + hint;
self.update(&new_string); self.update_string(&new_string);
} }
pub fn ui(&mut self, ui: &mut egui::Ui, func_i: i32) { pub fn ui(&mut self, ui: &mut egui::Ui, func_i: i32) {
@ -99,7 +99,7 @@ impl<'a> AutoComplete<'a> {
if self.hint.is_none() { if self.hint.is_none() {
let _ = func_edit.ui(ui); let _ = func_edit.ui(ui);
self.update(&new_string); self.update_string(&new_string);
return; return;
} }
@ -110,7 +110,7 @@ impl<'a> AutoComplete<'a> {
movement = Movement::Complete; movement = Movement::Complete;
} }
if let HintEnum::Single(single_hint) = self.hint { if let Hint::Single(single_hint) = self.hint {
func_edit = func_edit.hint_text(*single_hint); func_edit = func_edit.hint_text(*single_hint);
if ui.input().key_pressed(Key::ArrowDown) { if ui.input().key_pressed(Key::ArrowDown) {
movement = Movement::Down; movement = Movement::Down;
@ -121,11 +121,11 @@ impl<'a> AutoComplete<'a> {
let re = func_edit.ui(ui); let re = func_edit.ui(ui);
self.update(&new_string); self.update_string(&new_string);
self.interact_back(&movement); self.interact_back(&movement);
if movement != Movement::Complete && let HintEnum::Many(hints) = self.hint { if movement != Movement::Complete && let Hint::Many(hints) = self.hint {
// Doesn't need to have a number in id as there should only be 1 autocomplete popup in the entire gui // Doesn't need to have a number in id as there should only be 1 autocomplete popup in the entire gui
let popup_id = ui.make_persistent_id("autocomplete_popup"); let popup_id = ui.make_persistent_id("autocomplete_popup");
@ -205,34 +205,34 @@ mod autocomplete_tests {
} }
} }
Action::AssertHint(target_hint) => match ac.hint { Action::AssertHint(target_hint) => match ac.hint {
HintEnum::None => { Hint::None => {
if !target_hint.is_empty() { if !target_hint.is_empty() {
panic!( panic!(
"AssertHint failed on `HintEnum::None`: Expected: {}", "AssertHint failed on `Hint::None`: Expected: {}",
target_hint target_hint
); );
} }
} }
HintEnum::Many(hints) => { Hint::Many(hints) => {
let hint = hints[ac.i]; let hint = hints[ac.i];
if &hint != target_hint { if &hint != target_hint {
panic!( panic!(
"AssertHint failed on `HintEnum::Many`: Current: '{}' (index: {}) Expected: '{}'", "AssertHint failed on `Hint::Many`: Current: '{}' (index: {}) Expected: '{}'",
hint, ac.i, target_hint hint, ac.i, target_hint
) )
} }
} }
HintEnum::Single(hint) => { Hint::Single(hint) => {
if hint != target_hint { if hint != target_hint {
panic!( panic!(
"AssertHint failed on `HintEnum::Single`: Current: '{}' Expected: '{}'", "AssertHint failed on `Hint::Single`: Current: '{}' Expected: '{}'",
hint, target_hint hint, target_hint
) )
} }
} }
}, },
Action::SetString(target_string) => { Action::SetString(target_string) => {
ac.update(target_string); ac.update_string(target_string);
} }
Action::Move(target_movement) => { Action::Move(target_movement) => {
ac.interact_back(target_movement); ac.interact_back(target_movement);