harn-hostlib 0.10.160

Opt-in code-intelligence and deterministic-tool host builtins for the Harn VM
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Python arm of `move_symbol`: dotted package paths.

use std::collections::{BTreeSet, HashSet};
use std::ops::Range;

use tree_sitter::{Node, Tree};

use super::text::{self, Edit};
use super::{
    Binding, FileModel, ImportRequest, ListStatement, ModuleRef, QualifiedRewrite, Shape, TopItem,
};

pub(crate) struct Workspace {
    files: HashSet<String>,
}

impl Workspace {
    pub(crate) fn new(files: HashSet<String>) -> Self {
        Self { files }
    }

    /// Dotted module name: the enclosing chain of directories that hold an
    /// `__init__.py`, then the file stem (none for `__init__.py`).
    pub(crate) fn module_of(&self, rel: &str) -> String {
        let parts: Vec<&str> = rel.split('/').collect();
        let (file, dirs) = parts.split_last().expect("split yields one part");
        let stem = file
            .strip_suffix(".pyi")
            .or_else(|| file.strip_suffix(".py"))
            .unwrap_or(file);
        let mut depth = dirs.len();
        while depth > 0
            && self
                .files
                .contains(&format!("{}/__init__.py", dirs[..depth].join("/")))
        {
            depth -= 1;
        }
        let mut module: Vec<&str> = dirs[depth..].to_vec();
        if stem != "__init__" {
            module.push(stem);
        }
        module.join(".")
    }

    fn package_of(&self, rel: &str) -> Vec<String> {
        let module: Vec<String> = self.module_of(rel).split('.').map(str::to_string).collect();
        if rel.ends_with("__init__.py") {
            module
        } else {
            module[..module.len().saturating_sub(1)].to_vec()
        }
    }

    fn resolve_from(&self, rel: &str, module_name: Node<'_>, source: &str) -> ModuleRef {
        if module_name.kind() != "relative_import" {
            return ModuleRef::Python(text::text(module_name, source).to_string());
        }
        let raw = text::text(module_name, source);
        let dots = raw.chars().take_while(|c| *c == '.').count();
        let rest = text::slice(raw, dots..).trim();
        let package = self.package_of(rel);
        if dots == 0 || dots - 1 > package.len() {
            return ModuleRef::External(raw.to_string());
        }
        let mut parts = package[..package.len() - (dots - 1)].to_vec();
        if !rest.is_empty() {
            parts.extend(rest.split('.').map(str::to_string));
        }
        ModuleRef::Python(parts.join("."))
    }

    pub(crate) fn model(&mut self, rel: &str, tree: &Tree, source: &str) -> FileModel {
        let mut model = FileModel::default();
        let root = tree.root_node();
        let mut last_import_end = None;
        let mut docstring_end = None;
        for (index, child) in text::members(root).into_iter().enumerate() {
            match child.kind() {
                "import_statement" | "import_from_statement" | "future_import_statement" => {
                    last_import_end = Some(child.end_byte());
                }
                "function_definition" | "class_definition" => {
                    push_item(&mut model, child, child, source);
                }
                "decorated_definition" => {
                    if let Some(definition) = child.child_by_field_name("definition") {
                        push_item(&mut model, child, definition, source);
                    }
                }
                "expression_statement" => {
                    let first = text::members(child).into_iter().next();
                    if index == 0 && first.is_some_and(|n| n.kind() == "string") {
                        docstring_end = Some(child.end_byte());
                    }
                    if let Some(assignment) = first.filter(|n| n.kind() == "assignment") {
                        if let Some(left) = assignment
                            .child_by_field_name("left")
                            .filter(|n| n.kind() == "identifier")
                        {
                            model.items.push(TopItem {
                                name: text::text(left, source).to_string(),
                                range: child.byte_range(),
                                exported: true,
                                type_like: false,
                                movable: false,
                            });
                        }
                    }
                }
                _ => {}
            }
        }
        // Imports anywhere in the file; nested ones are rewritten too.
        text::walk(root, |node| match node.kind() {
            "import_statement" | "import_from_statement" => {
                let top_level = node.parent().is_some_and(|p| p.id() == root.id());
                model.import_ranges.push(node.byte_range());
                self.add_import(rel, node, top_level, source, &mut model);
                false
            }
            "future_import_statement" => {
                model.import_ranges.push(node.byte_range());
                false
            }
            kind => !(kind.contains("comment") || kind == "string"),
        });
        model.has_imports = last_import_end.is_some();
        model.insert_at = match last_import_end.or(docstring_end) {
            Some(end) => text::next_line_start(source, end),
            None => 0,
        };
        model
    }

    fn add_import(
        &self,
        rel: &str,
        statement: Node<'_>,
        top_level: bool,
        source: &str,
        model: &mut FileModel,
    ) {
        let mut cursor = statement.walk();
        let names: Vec<Node<'_>> = statement
            .children_by_field_name("name", &mut cursor)
            .collect();
        let ranges: Vec<Range<usize>> = names.iter().map(|n| n.byte_range()).collect();
        let removal = |i: usize| -> (Range<usize>, bool) {
            if names.len() > 1 {
                (text::list_element_removal(&ranges, i), false)
            } else {
                (statement.byte_range(), true)
            }
        };
        if statement.kind() == "import_statement" {
            for (i, name) in names.iter().enumerate() {
                let (dotted, alias) = split_alias(*name, source);
                let local =
                    alias.unwrap_or_else(|| dotted.split('.').next().unwrap_or("").to_string());
                let (removal, sole) = removal(i);
                model.bindings.push(Binding {
                    local,
                    imported: String::new(),
                    target: ModuleRef::Python(dotted),
                    shape: Shape::Namespace,
                    type_only: false,
                    reexport: false,
                    prefix: String::new(),
                    top_level,
                    removal,
                    statement: statement.byte_range(),
                    sole,
                });
            }
            return;
        }
        let Some(module_name) = statement.child_by_field_name("module_name") else {
            return;
        };
        let target = self.resolve_from(rel, module_name, source);
        let mut cursor = statement.walk();
        if statement
            .children(&mut cursor)
            .any(|c| c.kind() == "wildcard_import")
        {
            model.bindings.push(Binding {
                local: String::new(),
                imported: String::new(),
                target,
                shape: Shape::Glob,
                type_only: false,
                reexport: false,
                prefix: String::new(),
                top_level,
                removal: statement.byte_range(),
                statement: statement.byte_range(),
                sole: true,
            });
            return;
        }
        for (i, name) in names.iter().enumerate() {
            let (imported, alias) = split_alias(*name, source);
            let (removal, sole) = removal(i);
            model.bindings.push(Binding {
                local: alias.unwrap_or_else(|| imported.clone()),
                imported,
                target: target.clone(),
                shape: Shape::Named,
                type_only: false,
                reexport: false,
                prefix: String::new(),
                top_level,
                removal,
                statement: statement.byte_range(),
                sole,
            });
        }
        if let (true, Some(last)) = (top_level, names.last()) {
            model.lists.push(ListStatement {
                target,
                type_only: false,
                reexport: false,
                prefix: String::new(),
                append_at: last.end_byte(),
            });
        }
    }
}

fn split_alias(node: Node<'_>, source: &str) -> (String, Option<String>) {
    if node.kind() == "aliased_import" {
        (
            node.child_by_field_name("name")
                .map(|n| text::text(n, source).to_string())
                .unwrap_or_default(),
            node.child_by_field_name("alias")
                .map(|n| text::text(n, source).to_string()),
        )
    } else {
        (text::text(node, source).to_string(), None)
    }
}

fn push_item(model: &mut FileModel, outer: Node<'_>, definition: Node<'_>, source: &str) {
    if let Some(name) = definition.child_by_field_name("name") {
        model.items.push(TopItem {
            name: text::text(name, source).to_string(),
            range: outer.byte_range(),
            exported: true,
            type_like: false,
            movable: true,
        });
    }
}

fn module_text(target: &ModuleRef) -> String {
    match target {
        ModuleRef::Python(dotted) | ModuleRef::External(dotted) => dotted.clone(),
        other => format!("{other:?}"),
    }
}

pub(crate) fn render(req: &ImportRequest) -> String {
    let module = module_text(&req.target);
    match req.shape {
        Shape::Glob => format!("from {module} import *"),
        Shape::Namespace => {
            if module.split('.').next() == Some(req.local.as_str()) {
                format!("import {module}")
            } else {
                format!("import {module} as {}", req.local)
            }
        }
        Shape::Named | Shape::Default => {
            if req.local != req.imported {
                format!("from {module} import {} as {}", req.imported, req.local)
            } else {
                format!("from {module} import {}", req.imported)
            }
        }
    }
}

/// The module a binding loads when its statement runs.
pub(crate) fn binding_module(binding: &Binding) -> Option<ModuleRef> {
    match &binding.target {
        ModuleRef::Python(_) => Some(binding.target.clone()),
        _ => None,
    }
}

/// The module `qualifier` names through this file's imports.
fn qualifier_module(model: &FileModel, qualifier: &str) -> Option<String> {
    let first = qualifier.split('.').next()?;
    let rest = text::slice(qualifier, first.len()..);
    let binding = model
        .bindings
        .iter()
        .find(|b| b.local == first && b.shape != Shape::Glob)?;
    let ModuleRef::Python(target) = &binding.target else {
        return None;
    };
    match binding.shape {
        Shape::Namespace if target.split('.').next() == Some(first) => Some(qualifier.to_string()),
        Shape::Namespace => Some(format!("{target}{rest}")),
        Shape::Named => Some(format!("{target}.{}{rest}", binding.imported)),
        _ => None,
    }
}

/// `m.name` where `m` resolves through an import to the source module.
pub(crate) fn qualified(
    source: &str,
    model: &FileModel,
    node: Node<'_>,
    from: &ModuleRef,
    to: &ModuleRef,
    bare: bool,
) -> Option<QualifiedRewrite> {
    let parent = node.parent()?;
    if parent.kind() != "attribute" || !text::is_field_child(parent, "attribute", node) {
        return None;
    }
    let object = parent.child_by_field_name("object")?;
    let qualifier = text::text(object, source);
    if !qualifier
        .split('.')
        .all(super::super::refactor_core::is_identifier_token)
    {
        return None;
    }
    let ModuleRef::Python(from_module) = from else {
        return None;
    };
    if qualifier_module(model, qualifier).as_deref() != Some(from_module.as_str()) {
        return None;
    }
    if bare {
        return Some(QualifiedRewrite {
            edit: Edit::replace(object.start_byte()..node.start_byte(), ""),
            import: None,
        });
    }
    let ModuleRef::Python(to_module) = to else {
        return None;
    };
    let existing = model.bindings.iter().find_map(|b| {
        let ModuleRef::Python(target) = &b.target else {
            return None;
        };
        match b.shape {
            Shape::Namespace if target == to_module => {
                Some(if target.split('.').next() == Some(b.local.as_str()) {
                    target.clone()
                } else {
                    b.local.clone()
                })
            }
            Shape::Named if &format!("{target}.{}", b.imported) == to_module => {
                Some(b.local.clone())
            }
            _ => None,
        }
    });
    let (replacement, import) = match existing {
        Some(reference) => (reference, None),
        None => (
            to_module.clone(),
            Some(ImportRequest {
                target: to.clone(),
                shape: Shape::Namespace,
                imported: String::new(),
                local: to_module.split('.').next().unwrap_or_default().to_string(),
                type_only: false,
                reexport: false,
                prefix: String::new(),
                anchor: None,
            }),
        ),
    };
    Some(QualifiedRewrite {
        edit: Edit::replace(object.byte_range(), replacement),
        import,
    })
}

/// Names the moved item reads, excluding attribute members, keyword
/// argument names, parameter names, and its own name.
pub(crate) fn free_names(
    item: Node<'_>,
    source: &str,
    own: &str,
) -> (BTreeSet<String>, BTreeSet<String>) {
    let mut names = BTreeSet::new();
    text::walk(item, |node| {
        let kind = node.kind();
        if kind != "identifier" {
            return true;
        }
        let Some(parent) = node.parent() else {
            return true;
        };
        let declares = match parent.kind() {
            "attribute" => text::is_field_child(parent, "attribute", node),
            "keyword_argument" => text::is_field_child(parent, "name", node),
            "parameters" | "lambda_parameters" => true,
            "typed_parameter" => text::members(parent).first().map(|n| n.id()) == Some(node.id()),
            "default_parameter" | "typed_default_parameter" => {
                text::is_field_child(parent, "name", node)
            }
            "function_definition" | "class_definition" => {
                text::is_field_child(parent, "name", node)
            }
            _ => false,
        };
        if !declares {
            names.insert(text::text(node, source).to_string());
        }
        true
    });
    names.remove(own);
    (names, BTreeSet::new())
}