gobby-code 1.3.3

Fast Rust CLI for Gobby's code index — AST-aware search, symbol navigation, and dependency graph
Documentation
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
394
395
396
397
398
399
400
401
402
403
use std::path::{Component, Path};

pub(super) fn collapse_whitespace(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

pub(super) fn extract_js_module_specifier(text: &str) -> Option<String> {
    if let Some((_, after_from)) = text.rsplit_once(" from ") {
        return extract_quoted_string(after_from);
    }
    let rest = text.strip_prefix("import ")?;
    extract_quoted_string(rest)
}

pub(super) fn extract_js_import_clause(text: &str) -> Option<&str> {
    let rest = text.strip_prefix("import ")?;
    let (clause, _) = rest.rsplit_once(" from ")?;
    Some(clause)
}

pub(super) fn extract_quoted_string(text: &str) -> Option<String> {
    let quote = text.find(['"', '\'', '`'])?;
    let quote_char = text[quote..].chars().next()?;
    let after_quote = &text[quote + quote_char.len_utf8()..];
    let mut escaped = false;
    let mut idx = 0;
    while idx < after_quote.len() {
        let ch = after_quote[idx..].chars().next()?;
        if escaped {
            escaped = false;
            idx += ch.len_utf8();
            continue;
        }
        if ch == '\\' {
            escaped = true;
            idx += ch.len_utf8();
            continue;
        }
        if quote_char == '`' && ch == '$' && after_quote[idx + ch.len_utf8()..].starts_with('{') {
            idx = skip_template_interpolation(after_quote, idx + ch.len_utf8() + 1)?;
            continue;
        }
        if ch == quote_char {
            return Some(after_quote[..idx].to_string());
        }
        idx += ch.len_utf8();
    }
    None
}

fn skip_template_interpolation(text: &str, mut idx: usize) -> Option<usize> {
    let mut brace_depth = 1usize;
    let mut in_single = false;
    let mut in_double = false;
    let mut in_backtick = false;
    let mut escaped = false;

    while idx < text.len() {
        let ch = text[idx..].chars().next()?;
        if escaped {
            escaped = false;
            idx += ch.len_utf8();
            continue;
        }
        if (in_single || in_double || in_backtick) && ch == '\\' {
            escaped = true;
            idx += ch.len_utf8();
            continue;
        }
        match ch {
            '\'' if !in_double && !in_backtick => in_single = !in_single,
            '"' if !in_single && !in_backtick => in_double = !in_double,
            '`' if !in_single && !in_double => in_backtick = !in_backtick,
            '{' if !in_single && !in_double && !in_backtick => brace_depth += 1,
            '}' if !in_single && !in_double && !in_backtick => {
                brace_depth -= 1;
                idx += ch.len_utf8();
                if brace_depth == 0 {
                    return Some(idx);
                }
                continue;
            }
            _ => {}
        }
        idx += ch.len_utf8();
    }
    None
}

pub(super) fn go_default_package_alias(module: &str) -> String {
    let module = module.trim_end_matches('/');
    let last_segment = module.rsplit('/').next().unwrap_or(module);
    let without_version = last_segment
        .rsplit_once(".v")
        .filter(|(_, version)| !version.is_empty() && version.chars().all(|ch| ch.is_ascii_digit()))
        .map(|(name, _)| name)
        .unwrap_or(last_segment);
    without_version.replace('-', "_")
}

pub(super) fn split_alias(text: &str) -> (&str, Option<&str>) {
    if let Some((name, alias)) = text.split_once(" as ") {
        (name.trim(), Some(alias.trim()))
    } else {
        (text.trim(), None)
    }
}

pub(super) fn split_rust_use_group(text: &str) -> Option<(&str, &str)> {
    let mut depth = 0usize;
    let mut start = None;

    for (idx, ch) in text.char_indices() {
        match ch {
            '{' => {
                if depth == 0 {
                    start = Some(idx);
                }
                depth += 1;
            }
            '}' if depth > 0 => {
                depth -= 1;
                if depth == 0 {
                    let start = start?;
                    if text[idx + ch.len_utf8()..].trim().is_empty() {
                        return Some((text[..start].trim(), text[start + 1..idx].trim()));
                    }
                    return None;
                }
            }
            _ => {}
        }
    }

    None
}

pub(super) fn rust_join_use_path(prefix: &str, item: &str) -> Option<String> {
    let prefix = prefix.trim().trim_end_matches("::").trim();
    let item = item.trim();
    if item.is_empty() {
        return None;
    }

    let (item_path, alias) = split_alias(item);
    let item_path = item_path.trim();
    if item_path.is_empty() {
        return None;
    }

    let path = if item_path == "self" {
        if prefix.is_empty() {
            return None;
        }
        prefix.to_string()
    } else if prefix.is_empty() {
        item_path.to_string()
    } else {
        format!("{prefix}::{item_path}")
    };

    Some(match alias {
        Some(alias) if !alias.is_empty() => format!("{path} as {alias}"),
        _ => path,
    })
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct SplitTopLevelError {
    delimiter: char,
    position: usize,
    kind: &'static str,
    context: String,
}

impl std::fmt::Display for SplitTopLevelError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} while splitting on `{}` at byte {} near `{}`",
            self.kind, self.delimiter, self.position, self.context
        )
    }
}

impl std::error::Error for SplitTopLevelError {}

impl SplitTopLevelError {
    fn new(text: &str, delimiter: char, position: usize, kind: &'static str) -> Self {
        Self {
            delimiter,
            position,
            kind,
            context: split_error_context(text, position),
        }
    }
}

fn split_error_context(text: &str, position: usize) -> String {
    const CONTEXT_CHARS: usize = 24;
    let position = position.min(text.len());
    let start = text[..position]
        .char_indices()
        .rev()
        .nth(CONTEXT_CHARS)
        .map(|(idx, _)| idx)
        .unwrap_or(0);
    let end = text[position..]
        .char_indices()
        .nth(CONTEXT_CHARS)
        .map(|(idx, _)| position + idx)
        .unwrap_or(text.len());
    text[start..end].replace('\n', "\\n")
}

pub(super) fn split_top_level(
    text: &str,
    delimiter: char,
) -> Result<Vec<&str>, SplitTopLevelError> {
    let mut parts = Vec::new();
    let mut start = 0;
    let mut paren_depth = 0usize;
    let mut brace_depth = 0usize;
    let mut bracket_depth = 0usize;
    let mut in_single = false;
    let mut in_double = false;
    let mut escaped = false;

    for (idx, ch) in text.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        if (in_single || in_double) && ch == '\\' {
            escaped = true;
            continue;
        }
        match ch {
            '\'' if !in_double => in_single = !in_single,
            '"' if !in_single => in_double = !in_double,
            '(' if !in_single && !in_double => paren_depth += 1,
            ')' if !in_single && !in_double && paren_depth > 0 => paren_depth -= 1,
            ')' if !in_single && !in_double => {
                return Err(SplitTopLevelError::new(
                    text,
                    delimiter,
                    idx,
                    "unbalanced closing parenthesis",
                ));
            }
            '{' if !in_single && !in_double => brace_depth += 1,
            '}' if !in_single && !in_double && brace_depth > 0 => brace_depth -= 1,
            '}' if !in_single && !in_double => {
                return Err(SplitTopLevelError::new(
                    text,
                    delimiter,
                    idx,
                    "unbalanced closing brace",
                ));
            }
            '[' if !in_single && !in_double => bracket_depth += 1,
            ']' if !in_single && !in_double && bracket_depth > 0 => bracket_depth -= 1,
            ']' if !in_single && !in_double => {
                return Err(SplitTopLevelError::new(
                    text,
                    delimiter,
                    idx,
                    "unbalanced closing bracket",
                ));
            }
            ch if ch == delimiter
                && !in_single
                && !in_double
                && paren_depth == 0
                && brace_depth == 0
                && bracket_depth == 0 =>
            {
                parts.push(text[start..idx].trim());
                start = idx + ch.len_utf8();
            }
            _ => {}
        }
    }

    parts.push(text[start..].trim());

    if in_single || in_double {
        return Err(SplitTopLevelError::new(
            text,
            delimiter,
            text.len(),
            "unterminated string literal",
        ));
    }
    if paren_depth != 0 || brace_depth != 0 || bracket_depth != 0 {
        return Err(SplitTopLevelError::new(
            text,
            delimiter,
            text.len(),
            "unbalanced opening delimiter",
        ));
    }

    Ok(parts)
}

pub(super) fn is_ruby_constant_name(name: &str) -> bool {
    is_uppercase_ascii_alnum_underscore_name(name)
}

fn is_uppercase_ascii_alnum_underscore_name(name: &str) -> bool {
    name.chars()
        .next()
        .is_some_and(|ch| ch.is_ascii_uppercase())
        && name
            .chars()
            .all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
}

pub(super) fn dart_import_alias(text: &str) -> Option<String> {
    let after_as = text.split_once(" as ")?.1;
    let alias = after_as
        .split_whitespace()
        .next()
        .unwrap_or_default()
        .trim_end_matches(';');
    if alias.is_empty() {
        None
    } else {
        Some(alias.to_string())
    }
}

/// Resolves a *local* Dart import URI to the project-relative `.dart` file it
/// refers to. `package:<self>/<p>` maps to `lib/<p>`; a relative URI resolves
/// against the importing file's directory, collapsing `.`/`..`. Returns `None`
/// for URIs that are not local project files — `dart:` SDK imports, external
/// `package:` dependencies, a `package:` URI naming no path, or any other URI
/// scheme. Pure path logic, no filesystem access; a path that points nowhere
/// simply matches no indexed symbol in the post-write pass.
pub(super) fn dart_local_import_target(
    uri: &str,
    rel_path: &str,
    self_package: Option<&str>,
) -> Option<String> {
    if let Some(rest) = uri.strip_prefix("package:") {
        let (package, within) = rest.split_once('/')?;
        if within.is_empty() || Some(package) != self_package {
            return None;
        }
        return Some(normalize_relative_dart_path(&Path::new("lib").join(within)));
    }
    // `dart:` SDK imports (and any other URI scheme) are never project files.
    if uri.contains(':') {
        return None;
    }
    let dir = Path::new(rel_path)
        .parent()
        .unwrap_or_else(|| Path::new(""));
    let resolved = normalize_relative_dart_path(&dir.join(uri));
    (!resolved.is_empty()).then_some(resolved)
}

/// Collapses `.`/`..` and redundant separators in a project-relative path,
/// preserving the file extension (unlike the JS module normalizer, which strips
/// it). A `..` that would escape the root is dropped, matching how an
/// out-of-tree import resolves to no indexed file.
fn normalize_relative_dart_path(path: &Path) -> String {
    let mut parts: Vec<String> = Vec::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                parts.pop();
            }
            Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
            Component::RootDir | Component::Prefix(_) => {}
        }
    }
    parts.join("/")
}

pub(super) fn is_elixir_alias(name: &str) -> bool {
    is_uppercase_ascii_alnum_underscore_name(name)
}

pub(super) fn is_elixir_alias_path(path: &str) -> bool {
    path.split('.').all(is_elixir_alias)
}

pub(super) fn elixir_alias_as(text: &str) -> Option<String> {
    let after = text.split_once(" as: ")?.1;
    let alias = after
        .split([',', ' ', ')', ']'])
        .next()
        .unwrap_or_default()
        .trim();
    if is_elixir_alias(alias) {
        Some(alias.to_string())
    } else {
        None
    }
}