Skip to content

Commit abc7910

Browse files
committed
refactor(rust): misc fixes & tidying
1 parent 5825e24 commit abc7910

23 files changed

+131
-121
lines changed

Cargo.lock

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

cli/loader/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ once_cell.workspace = true
2626
regex.workspace = true
2727
serde.workspace = true
2828
serde_json.workspace = true
29+
tempfile.workspace = true
2930

3031
tree-sitter.workspace = true
3132
tree-sitter-highlight.workspace = true

cli/loader/src/lib.rs

+18-10
Original file line numberDiff line numberDiff line change
@@ -130,11 +130,12 @@ pub struct CompileConfig<'a> {
130130
}
131131

132132
impl<'a> CompileConfig<'a> {
133+
#[must_use]
133134
pub fn new(
134135
src_path: &'a Path,
135136
externals: Option<&'a [PathBuf]>,
136137
output_path: Option<PathBuf>,
137-
) -> CompileConfig<'a> {
138+
) -> Self {
138139
Self {
139140
src_path,
140141
header_paths: vec![src_path],
@@ -449,7 +450,7 @@ impl Loader {
449450
let parser_path = config.src_path.join("parser.c");
450451
config.scanner_path = self.get_scanner_path(config.src_path);
451452

452-
let mut paths_to_check = vec![parser_path.clone()];
453+
let mut paths_to_check = vec![parser_path];
453454

454455
if let Some(scanner_path) = config.scanner_path.as_ref() {
455456
paths_to_check.push(scanner_path.clone());
@@ -488,7 +489,9 @@ impl Loader {
488489
}
489490

490491
let lock_path = if env::var("CROSS_RUNNER").is_ok() {
491-
PathBuf::from("/tmp")
492+
tempfile::tempdir()
493+
.unwrap()
494+
.path()
492495
.join("tree-sitter")
493496
.join("lock")
494497
.join(format!("{}.lock", config.name))
@@ -1021,7 +1024,7 @@ impl Loader {
10211024
language_name: grammar_json.name.clone(),
10221025
scope: config_json.scope,
10231026
language_id,
1024-
file_types: config_json.file_types.unwrap_or(Vec::new()),
1027+
file_types: config_json.file_types.unwrap_or_default(),
10251028
content_regex: Self::regex(config_json.content_regex.as_deref()),
10261029
first_line_regex: Self::regex(config_json.first_line_regex.as_deref()),
10271030
injection_regex: Self::regex(config_json.injection_regex.as_deref()),
@@ -1048,8 +1051,11 @@ impl Loader {
10481051
.push(self.language_configurations.len());
10491052
}
10501053

1051-
self.language_configurations
1052-
.push(unsafe { mem::transmute(configuration) });
1054+
self.language_configurations.push(unsafe {
1055+
mem::transmute::<LanguageConfiguration<'_>, LanguageConfiguration<'static>>(
1056+
configuration,
1057+
)
1058+
});
10531059

10541060
if set_current_path_config
10551061
&& self.language_configuration_in_current_path.is_none()
@@ -1088,8 +1094,11 @@ impl Loader {
10881094
highlight_names: &self.highlight_names,
10891095
use_all_highlight_names: self.use_all_highlight_names,
10901096
};
1091-
self.language_configurations
1092-
.push(unsafe { mem::transmute(configuration) });
1097+
self.language_configurations.push(unsafe {
1098+
mem::transmute::<LanguageConfiguration<'_>, LanguageConfiguration<'static>>(
1099+
configuration,
1100+
)
1101+
});
10931102
self.languages_by_id
10941103
.push((parser_path.to_owned(), OnceCell::new(), None));
10951104
}
@@ -1327,8 +1336,7 @@ impl<'a> LanguageConfiguration<'a> {
13271336
.unwrap_or_else(|| ranges.last().unwrap());
13281337
error.offset = offset_within_section - range.start;
13291338
error.row = source[range.start..offset_within_section]
1330-
.chars()
1331-
.filter(|c| *c == '\n')
1339+
.matches(|c| c == '\n')
13321340
.count();
13331341
Error::from(error).context(format!("Error in query file {path:?}"))
13341342
}

cli/src/generate/build_tables/build_parse_table.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ impl<'a> ParseTableBuilder<'a> {
298298
}
299299
}
300300

301-
reduction_info.precedence = precedence.clone();
301+
reduction_info.precedence.clone_from(precedence);
302302
if let Err(i) = reduction_info.symbols.binary_search(&symbol) {
303303
reduction_info.symbols.insert(i, symbol);
304304
}
@@ -604,13 +604,13 @@ impl<'a> ParseTableBuilder<'a> {
604604
write!(&mut msg, " {}", self.symbol_name(symbol)).unwrap();
605605
}
606606

607-
write!(
607+
writeln!(
608608
&mut msg,
609-
" • {} …\n\n",
609+
" • {} …\n",
610610
self.symbol_name(&conflicting_lookahead)
611611
)
612612
.unwrap();
613-
write!(&mut msg, "Possible interpretations:\n\n").unwrap();
613+
writeln!(&mut msg, "Possible interpretations:\n").unwrap();
614614

615615
let mut interpretations = conflicting_items
616616
.iter()
@@ -685,7 +685,7 @@ impl<'a> ParseTableBuilder<'a> {
685685
}
686686

687687
let mut resolution_count = 0;
688-
write!(&mut msg, "\nPossible resolutions:\n\n").unwrap();
688+
writeln!(&mut msg, "\nPossible resolutions:\n").unwrap();
689689
let mut shift_items = Vec::new();
690690
let mut reduce_items = Vec::new();
691691
for item in conflicting_items {
@@ -961,7 +961,7 @@ fn populate_following_tokens(
961961
for entry in result.iter_mut() {
962962
entry.insert(*extra);
963963
}
964-
result[extra.index] = all_tokens.clone();
964+
result[extra.index].clone_from(&all_tokens);
965965
}
966966
}
967967
}

cli/src/generate/build_tables/item.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ impl<'a> ParseItem<'a> {
133133

134134
/// Create an item like this one, but advanced by one step.
135135
#[must_use]
136-
pub const fn successor(&self) -> ParseItem<'a> {
136+
pub const fn successor(&self) -> Self {
137137
ParseItem {
138138
variable_index: self.variable_index,
139139
production: self.production,

cli/src/generate/parse_grammar.rs

+11-12
Original file line numberDiff line numberDiff line change
@@ -166,19 +166,18 @@ fn parse_rule(json: RuleJSON) -> Rule {
166166
RuleJSON::PATTERN { value, flags } => Rule::Pattern(
167167
value,
168168
flags.map_or(String::new(), |f| {
169-
f.chars()
170-
.filter(|c| {
171-
if *c == 'i' {
172-
true
173-
} else {
174-
// silently ignore unicode flags
175-
if *c != 'u' && *c != 'v' {
176-
eprintln!("Warning: unsupported flag {c}");
177-
}
178-
false
169+
f.matches(|c| {
170+
if c == 'i' {
171+
true
172+
} else {
173+
// silently ignore unicode flags
174+
if c != 'u' && c != 'v' {
175+
eprintln!("Warning: unsupported flag {c}");
179176
}
180-
})
181-
.collect()
177+
false
178+
}
179+
})
180+
.collect()
182181
}),
183182
),
184183
RuleJSON::SYMBOL { name } => Rule::NamedSymbol(name),

cli/src/generate/prepare_grammar/process_inlines.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ impl InlinedProductionMapBuilder {
154154
self.productions
155155
.iter()
156156
.position(|p| *p == production)
157-
.unwrap_or({
157+
.unwrap_or_else(|| {
158158
self.productions.push(production);
159159
self.productions.len() - 1
160160
})

cli/src/generate/render.rs

+8-9
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ macro_rules! add {
2929
}
3030

3131
macro_rules! add_whitespace {
32-
($this: tt) => {{
32+
($this:tt) => {{
3333
for _ in 0..$this.indent_level {
3434
write!(&mut $this.buffer, " ").unwrap();
3535
}
@@ -45,13 +45,13 @@ macro_rules! add_line {
4545
}
4646

4747
macro_rules! indent {
48-
($this: tt) => {
48+
($this:tt) => {
4949
$this.indent_level += 1;
5050
};
5151
}
5252

5353
macro_rules! dedent {
54-
($this: tt) => {
54+
($this:tt) => {
5555
assert_ne!($this.indent_level, 0);
5656
$this.indent_level -= 1;
5757
};
@@ -221,9 +221,8 @@ impl Generator {
221221
});
222222

223223
// Some aliases match an existing symbol in the grammar.
224-
let alias_id;
225-
if let Some(existing_symbol) = existing_symbol {
226-
alias_id = self.symbol_ids[&self.symbol_map[&existing_symbol]].clone();
224+
let alias_id = if let Some(existing_symbol) = existing_symbol {
225+
self.symbol_ids[&self.symbol_map[&existing_symbol]].clone()
227226
}
228227
// Other aliases don't match any existing symbol, and need their own
229228
// identifiers.
@@ -232,12 +231,12 @@ impl Generator {
232231
self.unique_aliases.insert(i, alias.clone());
233232
}
234233

235-
alias_id = if alias.is_named {
234+
if alias.is_named {
236235
format!("alias_sym_{}", self.sanitize_identifier(&alias.value))
237236
} else {
238237
format!("anon_alias_sym_{}", self.sanitize_identifier(&alias.value))
239-
};
240-
}
238+
}
239+
};
241240

242241
self.alias_ids.entry(alias.clone()).or_insert(alias_id);
243242
}

cli/src/main.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -870,8 +870,7 @@ fn run() -> Result<()> {
870870
let open_in_browser = !playground_options.quiet;
871871
let grammar_path = playground_options
872872
.grammar_path
873-
.map(PathBuf::from)
874-
.unwrap_or(current_dir);
873+
.map_or(current_dir, PathBuf::from);
875874
playground::serve(&grammar_path, open_in_browser)?;
876875
}
877876

cli/src/playground.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use tiny_http::{Header, Response, Server};
1212
use super::wasm;
1313

1414
macro_rules! optional_resource {
15-
($name: tt, $path: tt) => {
15+
($name:tt, $path:tt) => {
1616
#[cfg(TREE_SITTER_EMBED_WASM_BINDING)]
1717
fn $name(tree_sitter_dir: Option<&Path>) -> Cow<'static, [u8]> {
1818
if let Some(tree_sitter_dir) = tree_sitter_dir {

cli/src/test.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -432,9 +432,9 @@ fn write_tests_to_buffer(
432432
if i > 0 {
433433
writeln!(buffer)?;
434434
}
435-
write!(
435+
writeln!(
436436
buffer,
437-
"{}\n{name}\n{}\n{input}\n{}\n\n{}\n",
437+
"{}\n{name}\n{}\n{input}\n{}\n\n{}",
438438
"=".repeat(*header_delim_len),
439439
"=".repeat(*header_delim_len),
440440
"-".repeat(*divider_delim_len),
@@ -662,7 +662,7 @@ fn parse_test_content(name: String, content: &str, file_path: Option<PathBuf>) -
662662
}
663663
}
664664
prev_attributes = attributes;
665-
prev_name = test_name.unwrap_or(String::new());
665+
prev_name = test_name.unwrap_or_default();
666666
prev_header_len = header_delim_len;
667667
prev_header_end = header_range.end;
668668
}

cli/src/tests/corpus_test.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ fn test_language_corpus(
217217

218218
// Perform a random series of edits and reparse.
219219
let mut undo_stack = Vec::new();
220-
for _ in 0..1 + rand.unsigned(*EDIT_COUNT) {
220+
for _ in 0..=rand.unsigned(*EDIT_COUNT) {
221221
let edit = get_random_edit(&mut rand, &input);
222222
undo_stack.push(invert_edit(&input, &edit));
223223
perform_edit(&mut tree, &mut input, &edit).unwrap();

cli/src/tests/detect_language.rs

+11-12
Original file line numberDiff line numberDiff line change
@@ -33,25 +33,25 @@ fn detect_language_by_first_line_regex() {
3333
assert_eq!(config[0].scope.as_ref().unwrap(), "source.strace");
3434

3535
let file_name = strace_dir.path().join("strace.log");
36-
std::fs::write(&file_name, "execve\nworld").unwrap();
36+
fs::write(&file_name, "execve\nworld").unwrap();
3737
assert_eq!(
3838
get_lang_scope(&loader, &file_name),
3939
Some("source.strace".into())
4040
);
4141

4242
let file_name = strace_dir.path().join("strace.log");
43-
std::fs::write(&file_name, "447845 execve\nworld").unwrap();
43+
fs::write(&file_name, "447845 execve\nworld").unwrap();
4444
assert_eq!(
4545
get_lang_scope(&loader, &file_name),
4646
Some("source.strace".into())
4747
);
4848

4949
let file_name = strace_dir.path().join("strace.log");
50-
std::fs::write(&file_name, "hello\nexecve").unwrap();
50+
fs::write(&file_name, "hello\nexecve").unwrap();
5151
assert!(get_lang_scope(&loader, &file_name).is_none());
5252

5353
let file_name = strace_dir.path().join("strace.log");
54-
std::fs::write(&file_name, "").unwrap();
54+
fs::write(&file_name, "").unwrap();
5555
assert!(get_lang_scope(&loader, &file_name).is_none());
5656

5757
let dummy_dir = tree_sitter_dir(
@@ -76,7 +76,7 @@ fn detect_language_by_first_line_regex() {
7676
.find_language_configurations_at_path(dummy_dir.path(), false)
7777
.unwrap();
7878
let file_name = dummy_dir.path().join("strace.dummy");
79-
std::fs::write(&file_name, "execve").unwrap();
79+
fs::write(&file_name, "execve").unwrap();
8080
assert_eq!(
8181
get_lang_scope(&loader, &file_name),
8282
Some("source.dummy".into())
@@ -85,15 +85,14 @@ fn detect_language_by_first_line_regex() {
8585

8686
fn tree_sitter_dir(package_json: &str, name: &str) -> tempfile::TempDir {
8787
let temp_dir = tempfile::tempdir().unwrap();
88-
std::fs::write(temp_dir.path().join("package.json"), package_json).unwrap();
89-
std::fs::create_dir(temp_dir.path().join("src")).unwrap();
90-
std::fs::create_dir(temp_dir.path().join("src/tree_sitter")).unwrap();
91-
std::fs::write(
88+
fs::write(temp_dir.path().join("package.json"), package_json).unwrap();
89+
fs::create_dir_all(temp_dir.path().join("src/tree_sitter")).unwrap();
90+
fs::write(
9291
temp_dir.path().join("src/grammar.json"),
9392
format!(r#"{{"name":"{name}"}}"#),
9493
)
9594
.unwrap();
96-
std::fs::write(
95+
fs::write(
9796
temp_dir.path().join("src/parser.c"),
9897
format!(
9998
r##"
@@ -108,15 +107,15 @@ fn tree_sitter_dir(package_json: &str, name: &str) -> tempfile::TempDir {
108107
),
109108
)
110109
.unwrap();
111-
std::fs::write(
110+
fs::write(
112111
temp_dir.path().join("src/tree_sitter/parser.h"),
113112
include_str!("../../../lib/src/parser.h"),
114113
)
115114
.unwrap();
116115
temp_dir
117116
}
118117

119-
// if we manage to get the language scope, it means we correctly detected the file-type
118+
// If we manage to get the language scope, it means we correctly detected the file-type
120119
fn get_lang_scope(loader: &Loader, file_name: &Path) -> Option<String> {
121120
loader
122121
.language_configuration_for_file_name(file_name)

cli/src/tests/helpers/edits.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ impl<'a> ReadRecorder<'a> {
3131

3232
pub fn strings_read(&self) -> Vec<&'a str> {
3333
let mut result = Vec::new();
34-
let mut last_range: Option<Range<usize>> = None;
34+
let mut last_range = Option::<Range<usize>>::None;
3535
for index in &self.indices_read {
3636
if let Some(ref mut range) = &mut last_range {
3737
if range.end == *index {

cli/src/tests/helpers/random.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ impl Rand {
1515
}
1616

1717
pub fn unsigned(&mut self, max: usize) -> usize {
18-
self.0.gen_range(0..max + 1)
18+
self.0.gen_range(0..=max)
1919
}
2020

2121
pub fn words(&mut self, max_count: usize) -> Vec<u8> {

cli/src/tests/highlight_test.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -753,8 +753,7 @@ fn to_token_vector<'a>(
753753
for (i, l) in s.split('\n').enumerate() {
754754
let l = l.trim_end_matches('\r');
755755
if i > 0 {
756-
lines.push(line);
757-
line = Vec::new();
756+
lines.push(std::mem::take(&mut line));
758757
}
759758
if !l.is_empty() {
760759
line.push((l, highlights.clone()));

0 commit comments

Comments
 (0)