Skip to content

Commit

Permalink
Avoid alloc
Browse files Browse the repository at this point in the history
  • Loading branch information
charliermarsh committed Feb 8, 2024
1 parent a247350 commit 65e91b1
Showing 1 changed file with 22 additions and 12 deletions.
34 changes: 22 additions & 12 deletions crates/ruff_python_parser/src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,38 +81,33 @@ type FunctionArgument = (
pub(crate) fn parse_arguments(
function_arguments: Vec<FunctionArgument>,
) -> Result<ArgumentList, LexicalError> {
let mut args = vec![];
let mut keywords = vec![];

let mut keyword_names = FxHashSet::with_capacity_and_hasher(
function_arguments.len(),
BuildHasherDefault::default(),
);
let mut double_starred = false;
for (name, value) in function_arguments {
if let Some((start, end, name)) = name {
let mut num_args = 0;
let mut num_keywords = 0;
for (name, value) in &function_arguments {
if let Some((start, _end, name)) = name {
// Check for duplicate keyword arguments in the call.
if let Some(keyword_name) = &name {
if !keyword_names.insert(keyword_name.to_string()) {
return Err(LexicalError {
error: LexicalErrorType::DuplicateKeywordArgumentError(
keyword_name.to_string(),
),
location: start,
location: *start,
});
}
} else {
double_starred = true;
}

keywords.push(ast::Keyword {
arg: name,
value,
range: TextRange::new(start, end),
});
num_keywords += 1;
} else {
// Positional arguments mustn't follow keyword arguments.
if !keywords.is_empty() && !is_starred(&value) {
if num_keywords > 0 && !is_starred(&value) {
return Err(LexicalError {
error: LexicalErrorType::PositionalArgumentError,
location: value.start(),
Expand All @@ -126,9 +121,24 @@ pub(crate) fn parse_arguments(
});
}

num_args += 1;
}
}

let mut args = Vec::with_capacity(num_args);
let mut keywords = Vec::with_capacity(num_keywords);
for (name, value) in function_arguments {
if let Some((start, end, name)) = name {
keywords.push(ast::Keyword {
arg: name,
value,
range: TextRange::new(start, end),
});
} else {
args.push(value);
}
}

Ok(ArgumentList { args, keywords })
}

Expand Down

0 comments on commit 65e91b1

Please sign in to comment.