Skip to content

Commit b5415da

Browse files
committed
[function-grep] fixed tests, fixed grammar
also simplified passing list of langauges
1 parent 8910896 commit b5415da

File tree

5 files changed

+70
-52
lines changed

5 files changed

+70
-52
lines changed

function-grep/README.md

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ To see help run `function-grep --help`.
1717
# Examples
1818
## When you know the language
1919
```rust
20-
use function_grep::{supported_languages::Rust, ParsedFile};
20+
use function_grep::{supported_languages::{Rust, SupportedLanguage}, ParsedFile};
2121
use tree_sitter::Point;
2222
use tree_sitter::Range;
2323

24-
let results = ParsedFile::search_file("foo", "fn foo() {}\n fn bar()\n", &Rust).unwrap();
24+
let results = ParsedFile::search_file( "fn foo() {}\n fn bar()\n", &Rust.to_language("foo")).unwrap();
2525
println!("{:?}", results.results());
2626
assert_eq!(results.results(), &[Range { start_byte: 0, end_byte: 11, start_point: Point { row: 0, column: 0 }, end_point: Point { row: 0, column: 11 } }]);
2727
assert_eq!(results.to_string(), "1: fn foo() {}".to_string())
@@ -30,14 +30,26 @@ assert_eq!(results.to_string(), "1: fn foo() {}".to_string())
3030
## When you don't know the language
3131

3232
```rust
33-
use function_grep::{supported_languages, ParsedFile};
33+
use function_grep::{supported_languages::*, ParsedFile};
3434
use tree_sitter::Point;
3535
use tree_sitter::Range;
36-
37-
let results = ParsedFile::search_file_with_name("foo", "fn foo() {}\n fn bar()\n", "test.rs", supported_languages::predefined_languages()).unwrap();
36+
let results = ParsedFile::search_file_with_name(
37+
"fn foo() {}\n fn bar()\n",
38+
"test.rs",
39+
&predefined_languages().instantiate_map("foo").unwrap(),
40+
)
41+
.unwrap();
3842
println!("{:?}", results.results());
39-
assert_eq!(results.results(), &[Range { start_byte: 0, end_byte: 11, start_point: Point { row: 0, column: 0 }, end_point: Point { row: 0, column: 11 } }]);
40-
assert_eq!(results.to_string(), "1: fn foo() {}".to_string())
43+
44+
assert_eq!(
45+
results.results(),
46+
&[Range {
47+
start_byte: 0,
48+
end_byte: 11,
49+
start_point: Point { row: 0, column: 0 },
50+
end_point: Point { row: 0, column: 11 }
51+
}]
52+
);
4153
```
4254

4355
## More Examples
@@ -54,7 +66,7 @@ use tree_sitter::Language;
5466

5567

5668
#[cfg(feature = "rust")]
57-
construct_language!(Rust(tree_sitter_rust::language()).[rs]?=name->
69+
construct_language!(Rust(tree_sitter_rust::LANGUAGE).[rs]?=name->
5870

5971
"((function_item
6072
name: (identifier) @method-name)
@@ -73,7 +85,7 @@ construct_language!(Rust(tree_sitter_rust::language()).[rs]?=name->
7385
value: (closure_expression)) @method-definition
7486
(#eq? @method-name {name}))"
7587
);
76-
let results = ParsedFile::search_file("foo", "fn foo() {}\n fn bar()\n", &Rust).unwrap();
88+
let results = ParsedFile::search_file( "fn foo() {}\n fn bar()\n", &Rust.to_language("foo")).unwrap();
7789
println!("{:?}", results.results());
7890
assert_eq!(results.results(), &[Range { start_byte: 0, end_byte: 11, start_point: Point { row: 0, column: 0 }, end_point: Point { row: 0, column: 11 } }]);
7991
assert_eq!(results.to_string(), "1: fn foo() {}".to_string())

function-grep/examples/main.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
#![deny(missing_debug_implementations, clippy::missing_panics_doc)]
44
#![warn(clippy::pedantic, clippy::nursery, clippy::cargo)]
55
#![deny(clippy::use_self, rust_2018_idioms)]
6-
use function_grep::supported_languages::InstatiateMap;
6+
use function_grep::supported_languages::InstantiateMap;
77
use function_grep::{supported_languages::predefined_languages, ParsedFile};
88

99
use clap::Parser;
@@ -37,14 +37,13 @@ pub fn main() -> Result<(), Error> {
3737
// read the file in
3838
let mut code = String::new();
3939
let languages = predefined_languages()
40-
.instatiate_map(&args.name)
40+
.instantiate_map(&args.name)
4141
.map_err(Error::QueryError)?;
42-
let languages = &*languages.as_slice().iter().collect::<Box<[_]>>();
4342
file.read_to_string(&mut code)
4443
.map_err(Error::CouldNotReadFile)?;
4544
let file_name = &args.file.to_string_lossy();
4645
// search the file for function with the given name
47-
let found = ParsedFile::search_file_with_name(&code, file_name, languages)
46+
let found = ParsedFile::search_file_with_name(&code, file_name, &languages)
4847
.map_err(Error::LibraryError)?;
4948
// and print the results
5049
println!("{found}");

function-grep/src/lib.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
use core::fmt;
88

99
use filter::InstantiatedFilter;
10-
use supported_languages::InstatiatedLanguage;
10+
use supported_languages::InstantiatedLanguage;
1111
use tree_sitter::{LanguageError, QueryError, Range, Tree};
1212
#[allow(missing_debug_implementations)]
1313
#[derive(Hash, PartialEq, Eq, Debug, Clone)]
@@ -68,12 +68,12 @@ pub enum Error {
6868
/// If there is no language for this file extension in the provided language list.
6969
pub fn get_file_type_from_file_ext<'a>(
7070
ext: &str,
71-
langs: &'a [&'a InstatiatedLanguage<'a>],
72-
) -> Result<&'a InstatiatedLanguage<'a>, Error> {
71+
langs: &'a [InstantiatedLanguage<'a>],
72+
) -> Result<&'a InstantiatedLanguage<'a>, Error> {
7373
langs
7474
.iter()
7575
.find(|lang| lang.file_exts().contains(&ext))
76-
.copied()
76+
//.copied()
7777
.ok_or_else(|| Error::FileTypeUnkown(ext.to_string()))
7878
}
7979

@@ -86,8 +86,8 @@ pub fn get_file_type_from_file_ext<'a>(
8686
/// If there is no file extension for this file name, or there is no language for this file in the provided language list.
8787
pub fn get_file_type_from_file<'a>(
8888
file_name: &str,
89-
langs: &'a [&'a InstatiatedLanguage<'a>],
90-
) -> Result<&'a InstatiatedLanguage<'a>, Error> {
89+
langs: &'a [ InstantiatedLanguage<'a>],
90+
) -> Result<&'a InstantiatedLanguage<'a>, Error> {
9191
file_name
9292
.rsplit_once('.')
9393
.ok_or_else(|| Error::FileTypeUnkown(file_name.to_string()))
@@ -106,7 +106,7 @@ pub struct ParsedFile {
106106
file_name: Option<Box<str>>,
107107
function_name: Box<str>,
108108
// TODO: maybe each supported language could define filters
109-
// if so we would store InstatiatedLanguage here
109+
// if so we would store InstantiatedLanguage here
110110
language_type: Box<str>,
111111
tree: Tree,
112112
results: Box<[Range]>,
@@ -197,7 +197,7 @@ impl ParsedFile {
197197
/// If something with tree sitter goes wrong.
198198
/// If the code cannot be parsed properly.
199199
/// If no results are found for this function name.
200-
pub fn search_file(code: &str, language: &InstatiatedLanguage<'_>) -> Result<Self, Error> {
200+
pub fn search_file(code: &str, language: &InstantiatedLanguage<'_>) -> Result<Self, Error> {
201201
let code_bytes = code.as_bytes();
202202
let mut parser = tree_sitter::Parser::new();
203203
let ts_lang = language.language();
@@ -234,7 +234,7 @@ impl ParsedFile {
234234
pub fn search_file_with_name(
235235
code: &str,
236236
file_name: &str,
237-
langs: &[&InstatiatedLanguage<'_>],
237+
langs: &[InstantiatedLanguage<'_>],
238238
) -> Result<Self, Error> {
239239
get_file_type_from_file(file_name, langs)
240240
.and_then(|language| Self::search_file(code, language))

function-grep/src/supported_languages.rs

Lines changed: 31 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use tree_sitter::{Language as TsLanguage, Node, Query, QueryError, Range};
77
// TODO: we could probably use tree sitter tags?
88

99
#[allow(missing_debug_implementations)]
10-
pub struct InstatiatedLanguage<'a> {
10+
pub struct InstantiatedLanguage<'a> {
1111
search_name: &'a str,
1212
language: LanguageInformation,
1313
run_query: QueryFunction,
@@ -79,15 +79,15 @@ pub struct Identifier;
7979
pub struct TreeSitter;
8080
// TODO: hide in docs?
8181
trait InstantiateHelper<Type> {
82-
fn instiate(&self, search: Box<str>) -> QueryFunction;
82+
fn instantiate(&self, search: Box<str>) -> QueryFunction;
8383
}
8484

8585
// TODO: hide in docs?
8686
pub trait Assoc {
8787
type Type;
8888
}
8989
impl<T: IdentifierQuery> InstantiateHelper<Identifier> for T {
90-
fn instiate(
90+
fn instantiate(
9191
&self,
9292
search: Box<str>,
9393
) -> Box<dyn for<'x, 'y> Fn(Node<'x>, &'y [u8]) -> Box<[Range]> + Send + Sync> {
@@ -112,7 +112,7 @@ impl<T: IdentifierQuery> InstantiateHelper<Identifier> for T {
112112
}
113113
}
114114
impl<T: TreeSitterQuery> InstantiateHelper<TreeSitter> for T {
115-
fn instiate(
115+
fn instantiate(
116116
&self,
117117
search: Box<str>,
118118
) -> Box<dyn for<'x, 'y> Fn(Node<'x>, &'y [u8]) -> Box<[Range]> + Send + Sync> {
@@ -131,35 +131,42 @@ impl<T: TreeSitterQuery> InstantiateHelper<TreeSitter> for T {
131131
}
132132

133133
impl<T: Assoc + InstantiateHelper<T::Type> + HasLanguageInformation> SupportedLanguage for T {
134-
fn instiate(
134+
fn instantiate(
135135
&self,
136136
search: Box<str>,
137137
) -> Box<dyn for<'x, 'y> Fn(Node<'x>, &'y [u8]) -> Box<[Range]> + Send + Sync> {
138-
self.instiate(search)
138+
self.instantiate(search)
139139
}
140140
}
141141
type QueryFunction = Box<dyn for<'x, 'y> Fn(Node<'x>, &'y [u8]) -> Box<[Range]> + Send + Sync>;
142142

143143
pub trait SupportedLanguage: HasLanguageInformation {
144-
fn instiate(&self, search: Box<str>) -> QueryFunction;
144+
fn instantiate(&self, search: Box<str>) -> QueryFunction;
145+
fn to_language<'a>(&self, search: &'a str) -> InstantiatedLanguage<'a> {
146+
InstantiatedLanguage::new(
147+
search,
148+
self.language_info(),
149+
self.instantiate(search.into()),
150+
)
151+
}
145152
}
146153

147-
pub trait InstatiateMap<'a> {
148-
fn instatiate_map(self, name: &'a str) -> Result<Vec<InstatiatedLanguage<'a>>, QueryError>;
154+
pub trait InstantiateMap<'a> {
155+
fn instantiate_map(self, name: &'a str) -> Result<Vec<InstantiatedLanguage<'a>>, QueryError>;
149156
}
150-
impl<'a, T, U> InstatiateMap<'a> for T
157+
impl<'a, T, U> InstantiateMap<'a> for T
151158
where
152159
T: IntoIterator<Item = U>,
153160
U: Deref<Target = &'a dyn SupportedLanguage>,
154161
{
155-
fn instatiate_map(self, name: &'a str) -> Result<Vec<InstatiatedLanguage<'a>>, QueryError> {
162+
fn instantiate_map(self, name: &'a str) -> Result<Vec<InstantiatedLanguage<'a>>, QueryError> {
156163
Ok(self
157164
.into_iter()
158-
.map(|l| InstatiatedLanguage::new(name, l.language_info(), l.instiate(name.into())))
165+
.map(|l| InstantiatedLanguage::new(name, l.language_info(), l.instantiate(name.into())))
159166
.collect())
160167
}
161168
}
162-
impl<'a> InstatiatedLanguage<'a> {
169+
impl<'a> InstantiatedLanguage<'a> {
163170
pub(crate) fn new(
164171
search_name: &'a str,
165172
language: LanguageInformation,
@@ -208,7 +215,7 @@ impl<'a> InstatiatedLanguage<'a> {
208215
/// use function_grep::construct_language;
209216
/// use function_grep::supported_languages::SupportedLanguage;
210217
/// use tree_sitter::Language;
211-
/// construct_language!(C(tree_sitter_c::language()).[c h]?=
218+
/// construct_language!(C(tree_sitter_c::LANGUAGE).[c h]?=
212219
/// name -> "((function_definition
213220
/// declarator:
214221
/// (function_declarator declarator: (identifier) @method-name))
@@ -224,7 +231,7 @@ macro_rules! construct_language {
224231
($name:ident($tslang:expr).[$($ext:ident)+]?=$query_name:literal=>$query:literal ) => {
225232
#[derive(Debug, Clone, Copy)]
226233
pub struct $name;
227-
impl HasLanguageInformation for $name {
234+
impl $crate::supported_languages::HasLanguageInformation for $name {
228235

229236
fn language_name(&self) -> &'static str {
230237
stringify!($name)
@@ -234,14 +241,14 @@ macro_rules! construct_language {
234241
&[$(stringify!($ext)),+]
235242
}
236243

237-
fn language(&self) -> TsLanguage {
244+
fn language(&self) -> tree_sitter::Language {
238245
$tslang.into()
239246
}
240247
}
241-
impl Assoc for $name {
242-
type Type = Identifier;
248+
impl $crate::supported_languages::Assoc for $name {
249+
type Type = $crate::supported_languages::Identifier;
243250
}
244-
impl IdentifierQuery for $name {
251+
impl $crate::supported_languages::IdentifierQuery for $name {
245252
fn query_name(&self) -> impl ToString {
246253
$query_name
247254
}
@@ -255,7 +262,7 @@ macro_rules! construct_language {
255262
#[derive(Debug, Clone, Copy)]
256263
pub struct $name;
257264

258-
impl HasLanguageInformation for $name {
265+
impl $crate::supported_languages::HasLanguageInformation for $name {
259266

260267
fn language_name(&self) -> &'static str {
261268
stringify!($name)
@@ -265,14 +272,14 @@ macro_rules! construct_language {
265272
&[$(stringify!($ext)),+]
266273
}
267274

268-
fn language(&self) -> TsLanguage {
275+
fn language(&self) -> tree_sitter::Language {
269276
$tslang.into()
270277
}
271278
}
272-
impl Assoc for $name {
273-
type Type = TreeSitter;
279+
impl $crate::supported_languages::Assoc for $name {
280+
type Type = $crate::supported_languages::TreeSitter;
274281
}
275-
impl TreeSitterQuery for $name {
282+
impl $crate::supported_languages::TreeSitterQuery for $name {
276283
fn query_string_function(&self, $query_name: &str) -> String {
277284
format!($query)
278285
}

git-function-history-lib/src/lib.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ macro_rules! get_item_from_oid_option {
3838
}
3939
use chrono::{DateTime, Utc};
4040
use function_grep::{
41-
supported_languages::{InstatiateMap, InstatiatedLanguage, SupportedLanguage},
41+
supported_languages::{InstantiateMap, InstantiatedLanguage, SupportedLanguage},
4242
ParsedFile,
4343
};
4444
use git_function_history_proc_macro::enumstuff;
@@ -229,8 +229,8 @@ pub fn get_function_history(
229229
let metadata = (message, commit, author, email, time);
230230
Some((tree, metadata))
231231
});
232-
let langs = langs.instatiate_map(name).unwrap();
233-
let langs = &*langs.as_slice().iter().collect::<Box<[_]>>();
232+
let langs = langs.instantiate_map(name).unwrap();
233+
let langs = langs.as_slice();
234234
if let Filter::Date(date) = filter {
235235
let date = DateTime::parse_from_rfc2822(date)?.with_timezone(&Utc);
236236
let commit = commits.min_by_key(|commit| (commit.1 .4.sub(date).num_seconds().abs()));
@@ -320,7 +320,7 @@ fn sender(
320320
id: ObjectId,
321321
repo: gix::Repository,
322322
file_exts: &[&str],
323-
langs: &[&InstatiatedLanguage<'_>],
323+
langs: &[InstantiatedLanguage<'_>],
324324
file: &FileFilterType,
325325
) -> Result<Vec<ParsedFile>, String> {
326326
let object = repo.find_object(id).map_err(|_| "failed to find object")?;
@@ -335,7 +335,7 @@ fn traverse_tree(
335335
repo: &gix::Repository,
336336
path: String,
337337
file_exts: &[&str],
338-
langs: &[&InstatiatedLanguage<'_>],
338+
langs: &[InstantiatedLanguage<'_>],
339339
filetype: &FileFilterType,
340340
) -> Result<Vec<ParsedFile>, String> {
341341
let files_exts_iter = file_exts.iter();
@@ -534,7 +534,7 @@ pub struct CommitInfo {
534534
// function that takes a vec of files paths and there contents and a function name and uses find_function_in_file_with_commit to find the function in each file and returns a vec of the functions
535535
fn find_function_in_files_with_commit(
536536
files: Vec<(String, String)>,
537-
langs: &[&InstatiatedLanguage<'_>],
537+
langs: &[InstantiatedLanguage<'_>],
538538
) -> Vec<ParsedFile> {
539539
// commenting out this parallelization seems to net a gain in performance with tree sitter
540540
//#[cfg(feature = "parallel")]

0 commit comments

Comments
 (0)