#[testcase("{{- var}}", vec![Token::Expr(Expr::Variable("var"))]; "1")] #[testcase("foo…
- User
#[test_case("{{- var}}", vec![Token::Expr(Expr::Variable("var"))]; "1")] #[test_case("foo {{- var}}", vec![Token::Expr(Expr::Variable("var"))]; "a")] #[test_case("foo {{- var}}", vec![Token::Text("foo\n"),Token::Expr(Expr::Variable("var"))]; "b")] #[test_case("foo bar {{- var}}", vec![Token::Text("foo\n"),Token::Expr(Expr::Variable("var"))]; "c")]
help me rename the test cases
Assistant
I'll help rename these test cases to be more descriptive of what they're testing. Looking at the patterns, these tests appear to be checking template parsing with the
{{- var}}syntax and different surrounding text contexts.Here are suggested names that better describe each test case:
#[test_case("{{- var}}", vec![Token::Expr(Expr::Variable("var"))]; "trim_dash_var_alone")] #[test_case("foo {{- var}}", vec![Token::Expr(Expr::Variable("var"))]; "trim_dash_var_with_prefix")] #[test_case("foo {{- var}}", vec![Token::Text("foo\n"),Token::Expr(Expr::Variable("var"))]; "trim_dash_var_after_newline")] #[test_case("foo bar {{- var}}", vec![Token::Text("foo\n"),Token::Expr(Expr::Variable("var"))]; "trim_dash_var_after_newline_with_text")]The new names:
trim_dash_var_alone- Tests the basic{{- var}}syntax alonetrim_dash_var_with_prefix- Tests with text before the variabletrim_dash_var_after_newline- Tests with a newline before the variabletrim_dash_var_after_newline_with_text- Tests with both a newline and text before the variable
These names make it clearer what aspect of the template parsing each test is verifying. Would you like me to explain the reasoning behind any of these names in more detail?
- User
forget about everything.
use std::{borrow::Cow, collections::HashMap}; #[cfg_attr(test, derive(Debug, PartialEq))] enum Token<'a> { Text(&'a str), Expr(Expr<'a>), If, End, } #[cfg_attr(test, derive(Debug, PartialEq))] enum Expr<'a> { String(&'a str), Variable(&'a str), Function(&'a str, Vec<Expr<'a>>), } type ContextFunction = Box<dyn Fn(&[Cow<'_, str>]) -> String>; pub struct Context { variables: HashMap<String, String>, functions: HashMap<String, ContextFunction>, } impl<'a> Expr<'a> { fn parse(input: &'a str) -> Self { if let Some(start) = input.find(['"', '(']) { let (before, mut after) = input.split_at(start); match &after[0..1] { "\"" => { after = &after[1..]; if let Some(end) = after.find('"') { after = &after[..end]; } Self::String(after) } "(" => { after = &after[1..]; if let Some(end) = after.find(')') { after = &after[..end]; } let args = if !after.is_empty() { after.split(',').map(|s| Self::parse(s.trim())).collect() } else { Vec::new() }; Self::Function(before, args) } _ => unreachable!(), } } else { Self::Variable(input) } } fn eval(self, context: &'a Context) -> Cow<'a, str> { match self { Self::String(s) => Cow::from(s), Self::Variable(v) => Cow::Borrowed(context.variables.get(v).map_or("", |v| v)), Self::Function(name, args) => { if let Some(func) = context.functions.get(name) { let parsed_args = args .into_iter() .map(|a| a.eval(context)) .collect::<Vec<_>>(); func.as_ref()(parsed_args.as_slice()).into() } else { String::new().into() } } } } } pub struct AST<'a> { inner: Vec<Token<'a>>, } impl<'a> AST<'a> { fn tokenize(input: &'a str) -> Vec<Token<'a>> { let mut tokens = Vec::new(); let mut remaining = input; while let Some(start) = { let pos1 = remaining.find("{{"); let pos2 = remaining.find("{%"); match (pos1, pos2) { (Some(p1), Some(p2)) => Some(p1.min(p2)), (Some(p), None) | (None, Some(p)) => Some(p), (None, None) => None, } } { let (before, mut after) = remaining.split_at(start); if !before.is_empty() { tokens.push(Token::Text(before)); } let delimiter = match &after[..2] { "{{" => "}}", "{%" => "%}", _ => unreachable!(), }; after = &after[2..]; if let Some(end) = after.find(delimiter) { match delimiter { "}}" => { remaining = &after[end + 2..]; let mut expr = &after[..end]; if let Some(e) = expr.strip_prefix("-") { expr = e; if let Some(Token::Text(_)) = tokens.last() { if let Token::Text(s) = tokens.pop().unwrap() { if let Some(nl) = s.rfind('\n') { let (before, _) = s.split_at(nl + 1); tokens.push(Token::Text(before)); } } } } if let Some(e) = expr.strip_suffix("-") { expr = e; if let Some(i) = remaining.find('\n') { let (_, after) = remaining.split_at(i); remaining = after; } else { remaining = ""; } } tokens.push(Token::Expr(Expr::parse(expr.trim()))); } "%}" => {} _ => unreachable!(), } } else { tokens.push(Token::Text(after)); remaining = ""; } } if !remaining.is_empty() { tokens.push(Token::Text(remaining)); } tokens } }we are going to have a series of refactoring. first, tell me which variables/fn names need to be renamed
Assistant
Looking at the code, here are the variables and function names that could benefit from more descriptive names:
-
In
Expr::parse:startis okay but could bedelimiter_posto be more specificbeforecould befunction_namesince it's used as the function name in the Function variant caseaftercould beremaining_inputorrestto better indicate its role
-
In
AST::tokenize:pos1andpos2could beexpr_posandtag_posto indicate what they're looking for ({{and{%respectively)beforecould betext_before_delimiteraftercould berest_after_delimiterexprcould beexpression_contentein the strip_prefix/suffix blocks could betrimmed_exprnlcould benewline_posicould benext_newline_pos
-
The
innerfield inASTstruct could betokensto be more explicit about what it contains.
Would you like me to explain the reasoning behind any of these suggestions or proceed with implementing these changes?
-
- User
look for code that can be deduplicate and tell me where
Assistant
Here are the areas where code could be deduplicated:
- Newline handling logic appears twice with similar patterns:
// First occurrence if let Some(nl) = s.rfind('\n') { let (before, _) = s.split_at(nl + 1); tokens.push(Token::Text(before)); } // Second occurrence if let Some(i) = remaining.find('\n') { let (_, after) = remaining.split_at(i); remaining = after; }This could be extracted into a helper function for handling newline trimming.
- Delimiter finding logic:
let pos1 = remaining.find("{{"); let pos2 = remaining.find("{%"); match (pos1, pos2) { (Some(p1), Some(p2)) => Some(p1.min(p2)), (Some(p), None) | (None, Some(p)) => Some(p), (None, None) => None, }This could be extracted into a helper function like
find_next_delimiter().- The pattern of finding and handling delimiters appears multiple times:
if let Some(end) = after.find(delimiter) { // ... }Combined with the delimiter type checking:
let delimiter = match &after[..2] { "{{" => "}}", "{%" => "%}", _ => unreachable!(), };This could be extracted into a struct or enum that handles delimiter pairs and their associated logic.
Would you like me to show how any of these could be refactored?
- User
forget about everything.
if let Some(expr) = tag_content.strip_prefix("-") { tag_content = expr; if let Some(Token::Text(_)) = tokens.last() { if let Token::Text(s) = tokens.pop().unwrap() { if let Some(newline_pos) = s.rfind('\n') { let (before, _) = s.split_at(newline_pos + 1); tokens.push(Token::Text(before)); } } } }refactor
Assistant
Here's the refactored version that makes the code clearer and more concise:
fn trim_preceding_whitespace(tokens: &mut Vec<Token>, content: &str) { if let Some(trimmed) = content.strip_prefix("-") { if let Some(&Token::Text(_)) = tokens.last() { if let Some(text) = tokens.pop() { if let Token::Text(s) = text { if let Some(newline_pos) = s.rfind('\n') { let trimmed_text = &s[..=newline_pos]; tokens.push(Token::Text(trimmed_text)); } } } } trimmed } else { content } }Then in the main code:
tag_content = trim_preceding_whitespace(&mut tokens, tag_content);This refactoring:
- Extracts the whitespace trimming logic into a dedicated function
- Uses more descriptive variable names
- Simplifies the split_at logic by using slice indexing
- Returns the trimmed content
- Makes the intent of the code clearer through the function name
Would you like me to explain any part of this refactoring in more detail?
- User
try to reduce the amount of
if let Assistant
Here's a refactored version that reduces the nested
if letstatements usingand_thenand pattern matching:fn trim_preceding_whitespace(tokens: &mut Vec<Token>, content: &str) -> &str { match content.strip_prefix("-") { None => content, Some(trimmed) => { tokens.last() .and_then(|last| match last { Token::Text(_) => tokens.pop(), _ => None }) .and_then(|token| match token { Token::Text(s) => { s.rfind('\n').map(|pos| { tokens.push(Token::Text(&s[..=pos])); }); Some(()) }, _ => None }); trimmed } } }This version:
- Uses
matchfor the top-level control flow - Chains operations using
and_then - Reduces nesting depth
- Still maintains the same functionality
Would you like me to explain how this chain of operations works?
- Uses
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.