1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
pub mod pprint;
pub mod threadpool;
use crate::pprint::pprint_args;
use crate::threadpool::ThreadPool;
use colorful::{Color, Colorful};
use regex::Regex;
use rnix::types::{AttrSet, EntryHolder, Ident, Lambda, TokenWrapper, TypedNode};
use rnix::SyntaxKind::*;
use rnix::{NodeOrToken, SyntaxNode, TextUnit, WalkEvent, AST};
use walkdir::{DirEntry, WalkDir};
use std::ffi::{CStr, CString};
use std::fs;
use std::iter;
use std::os::raw::c_char;
use std::panic;
use std::path::Path;
use std::ptr;
use std::sync::mpsc::channel;
use std::{fmt::Display, str};
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
const DOC_INDENT: usize = 3;
const MAX_FILE_SIZE: u64 = 200_000;
struct SearchResult {
identifier: String,
doc: String,
param_block: String,
defined_at_start: usize,
}
fn find_line(file: &str, pos: usize) -> usize {
file[..pos].lines().count()
}
fn find_pos(file: &str, line: usize, col: usize) -> usize {
let mut lines = 1;
let mut line_start = 0;
for (count, ch) in file.chars().enumerate() {
if ch == '\n' {
lines += 1;
line_start = count;
}
if lines == line && count - line_start == col {
return count;
}
}
unreachable!();
}
impl SearchResult {
fn format<P: Display>(&self, filename: P, line: usize) -> String {
format!(
"{}\n{} = {}\n# {}",
indented(&self.doc, DOC_INDENT),
self.identifier.as_str().white().bold(),
self.param_block,
format!("{}:{}", filename, line).as_str(),
)
}
}
pub fn is_searchable(fname: &Path) -> bool {
fname.to_str().map(|s| s.ends_with(".nix")).unwrap_or(false)
}
fn search_file(file: &Path, matching: &Regex) -> Result<Vec<(SearchResult, usize)>> {
let length = fs::metadata(file)?.len();
if length > MAX_FILE_SIZE {
return Ok(Vec::new());
}
let content = fs::read_to_string(file)?;
let ast = rnix::parse(&content).as_result()?;
let results = search_ast(&matching, &ast);
Ok(results
.into_iter()
.map(|res| {
let line = find_line(&content, res.defined_at_start);
(res, line)
})
.collect::<Vec<_>>())
}
fn is_ignored(entry: &DirEntry) -> bool {
entry
.file_name()
.to_str()
.map(|s| s != "." && s.starts_with('.') || s == "target")
.unwrap_or(true)
}
pub fn search<F>(dir: &Path, matching: Regex, should_search: F)
where
F: Fn(&Path) -> bool,
{
let pool = ThreadPool::default();
let (tx, rx) = channel();
for direntry in WalkDir::new(dir)
.into_iter()
.filter_entry(|e| !is_ignored(e))
.filter_map(|e| e.ok())
.filter(|e| should_search(e.path()) && e.path().is_file())
{
let my_tx = tx.clone();
let matching = matching.clone();
pool.push(move || {
let results = search_file(direntry.path(), &matching);
if let Err(err) = results {
eprintln!("Failure handling {}: {}", direntry.path().display(), err);
return;
}
let results = results.unwrap();
let formatted = results
.iter()
.map(|(result, line)| result.format(direntry.path().display(), *line))
.collect::<Vec<_>>();
if !formatted.is_empty() {
my_tx
.send(formatted)
.expect("failed to send messages to display");
}
});
}
drop(tx);
pool.done();
let line = iter::repeat("─")
.take(45)
.collect::<String>()
.color(Color::Grey27);
let mut is_first = true;
while let Ok(results) = rx.recv() {
for result in results {
if !is_first {
println!("{}", &line);
} else {
is_first = false;
}
println!("{}", result);
}
}
}
fn search_ast(identifier: &Regex, ast: &AST) -> Vec<SearchResult> {
let mut results = Vec::new();
for ev in ast.node().preorder_with_tokens() {
match ev {
WalkEvent::Enter(enter) => {
if let Some(set) = enter.into_node().and_then(AttrSet::cast) {
results.extend(visit_attrset(identifier, &set));
}
}
WalkEvent::Leave(_leave) => {
}
}
}
results
}
fn indented(s: &str, indent: usize) -> String {
let indent_s = iter::repeat(' ').take(indent).collect::<String>();
s.split('\n')
.map(|line| indent_s.clone() + line)
.collect::<Vec<_>>()
.join("\n")
}
fn cleanup_comments<S: AsRef<str>, I: DoubleEndedIterator<Item = S>>(comment: &mut I) -> String {
textwrap::dedent(
&comment
.rev()
.map(|small_comment| {
small_comment
.as_ref()
.trim_start()
.trim_start_matches("/*")
.trim_end()
.trim_end_matches("*/")
.trim()
.split('\n')
.map(|line| {
line.trim_start_matches(|c: char| c.is_whitespace())
.trim_start_matches(|c: char| c == '#' || c == '*')
})
.collect::<Vec<_>>()
.join("\n")
})
.collect::<Vec<_>>()
.join("\n"),
)
}
#[no_mangle]
pub extern "C" fn nd_get_function_docs(
filename: *const c_char,
line: usize,
col: usize,
) -> *const c_char {
let fname = unsafe { CStr::from_ptr(filename) };
fname
.to_str()
.ok()
.and_then(|f| {
panic::catch_unwind(|| get_function_docs(f, line, col))
.map_err(|e| {
eprintln!("panic!! {:#?}", e);
e
})
.ok()
})
.flatten()
.and_then(|s| CString::new(s).ok())
.map(|s| s.into_raw() as *const c_char)
.unwrap_or(ptr::null())
}
#[no_mangle]
pub extern "C" fn nd_free_string(s: *const c_char) {
unsafe {
CString::from_raw(s as *mut c_char);
}
}
fn get_function_docs(filename: &str, line: usize, col: usize) -> Option<String> {
let content = fs::read(filename).ok()?;
let decoded = str::from_utf8(&content).ok()?;
let pos = find_pos(&decoded, line, col);
let rowan_pos = TextUnit::from_usize(pos);
let tree = rnix::parse(decoded);
let mut lambda = None;
for node in tree.node().preorder() {
match node {
WalkEvent::Enter(n) => {
if n.text_range().start() >= rowan_pos && n.kind() == NODE_LAMBDA {
lambda = Lambda::cast(n);
break;
}
}
WalkEvent::Leave(_) => (),
}
}
let lambda = lambda?;
let res = visit_lambda("func".to_string(), pos, &lambda);
Some(res.format(filename, line))
}
fn visit_lambda(name: String, defined_at_start: usize, lambda: &Lambda) -> SearchResult {
let param_block = pprint_args(&lambda);
let comment = find_comment(lambda.node().clone()).unwrap_or_else(|| "".to_string());
SearchResult {
identifier: name,
doc: comment,
param_block,
defined_at_start,
}
}
fn visit_attrset(id_needle: &Regex, set: &AttrSet) -> Vec<SearchResult> {
let mut results = Vec::new();
for entry in set.entries() {
if let Some(lambda) = entry.value().and_then(Lambda::cast) {
if let Some(attr) = entry.key() {
let ident = attr.path().last().and_then(Ident::cast);
let defined_at_start = ident
.as_ref()
.map(|i| i.node().text_range().start().to_usize());
let ident_name = ident.as_ref().map(|id| id.as_str());
if ident_name.map(|id| id_needle.is_match(id)) != Some(true) {
continue;
}
let ident_name = ident_name.unwrap();
let res = visit_lambda(ident_name.to_string(), defined_at_start.unwrap(), &lambda);
if !res.doc.is_empty() {
results.push(res);
}
}
}
}
results
}
fn find_comment(node: SyntaxNode) -> Option<String> {
let mut node = NodeOrToken::Node(node);
let mut comments = Vec::new();
loop {
loop {
if let Some(new) = node.prev_sibling_or_token() {
node = new;
break;
} else {
node = NodeOrToken::Node(node.parent()?);
}
}
match node.kind() {
TOKEN_COMMENT => match &node {
NodeOrToken::Token(token) => comments.push(token.text().clone()),
NodeOrToken::Node(_) => unreachable!(),
},
NODE_IDENT | NODE_KEY | NODE_KEY_VALUE | TOKEN_IDENT | TOKEN_ASSIGN => (),
t if t.is_trivia() => (),
_ => break,
}
}
let doc = cleanup_comments(&mut comments.iter().map(|c| c.as_str()));
Some(doc).filter(|it| !it.is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_bytepos() {
let fakefile = "abc\ndef\nghi";
assert_eq!(find_pos(fakefile, 2, 2), 5);
}
#[test]
fn test_comment_stripping() {
let ex1 = ["/* blah blah blah\n foooo baaar\n */"];
assert_eq!(
cleanup_comments(&mut ex1.iter()),
"blah blah blah\nfoooo baaar"
);
let ex2 = ["# a1", "# a2", "# aa"];
assert_eq!(cleanup_comments(&mut ex2.iter()), "aa\n a2\na1");
}
}