kartta-lang-python 0.0.0

Python extraction for the kartta code graph: functions, classes, fields, calls and imports
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! What a Python file extracts to from its bytes alone: its symbols qualified by their classes, the calls its
//! functions make, and the directives its imports leave for the resolver.
#![expect(
    clippy::panic,
    reason = "clippy's allow-panic-in-tests covers #[test] functions and #[cfg(test)] modules, and the lookup \
              helpers of an integration test crate are neither; a failed lookup is the assertion"
)]

use kartta_lang::{Language, RawExtraction, Symbol, SymbolId, SymbolKind};
use kartta_lang_python::Python;

const SAMPLE: &[u8] = br#"
import os
import numpy as np
from collections import OrderedDict, defaultdict
from . import sibling

VERSION = "1.0"

def free_function(x):
    return helper(x)


def helper(v):
    return v


@lru_cache
def decorated(x):
    return x


class Service(Base, mixins.Loggable):
    name: str = ""
    count: int

    def greet(self):
        return helper(self.name)

    def _private(self):
        outer = self.greet()

        def nested():
            return outer

        return nested
"#;

fn extract(source: &[u8]) -> RawExtraction {
    Python::new().extract(source)
}

fn named<'r>(raw: &'r RawExtraction, name: &str) -> &'r Symbol {
    raw.symbols
        .iter()
        .find(|symbol| symbol.name == name)
        .unwrap_or_else(|| panic!("no symbol {name}"))
}

fn qualified<'r>(raw: &'r RawExtraction, name: &str) -> &'r Symbol {
    raw.symbols
        .iter()
        .find(|symbol| symbol.qualified_name == name)
        .unwrap_or_else(|| panic!("no symbol {name}"))
}

fn id_of(raw: &RawExtraction, name: &str) -> SymbolId {
    let at = raw
        .symbols
        .iter()
        .position(|symbol| symbol.name == name)
        .unwrap_or_else(|| panic!("no symbol {name}"));
    SymbolId(u32::try_from(at).unwrap_or(u32::MAX))
}

fn generated(source: &[u8]) -> Vec<bool> {
    extract(source)
        .symbols
        .iter()
        .map(|symbol| symbol.flags.is_generated())
        .collect()
}

#[test]
fn symbols_are_qualified_by_their_classes_in_source_order() {
    let raw = extract(SAMPLE);
    let names: Vec<&str> = raw
        .symbols
        .iter()
        .map(|symbol| symbol.qualified_name.as_str())
        .collect();

    assert_eq!(
        names,
        [
            "VERSION",
            "free_function",
            "helper",
            "decorated",
            "Service",
            "Service.name",
            "Service.count",
            "Service.greet",
            "Service._private",
            "nested",
        ]
    );
    assert_eq!(named(&raw, "VERSION").kind, SymbolKind::Variable);
    assert!(named(&raw, "VERSION").exported);
}

#[test]
fn a_decorated_definition_starts_at_its_first_decorator() {
    let raw = extract(SAMPLE);
    let decorator = SAMPLE
        .split(|&byte| byte == b'\n')
        .position(|line| line.starts_with(b"@lru_cache"))
        .expect("decorator line");

    assert_eq!(
        named(&raw, "decorated").line,
        u32::try_from(decorator + 1).unwrap_or(u32::MAX)
    );
}

#[test]
fn an_annotated_class_attribute_is_a_field_and_a_method_local_is_nothing() {
    let raw = extract(SAMPLE);
    let field = qualified(&raw, "Service.name");

    assert_eq!(field.kind, SymbolKind::Field);
    assert_eq!(field.owner.as_deref(), Some("Service"));
    assert!(raw.symbols.iter().all(|symbol| symbol.name != "outer"));
}

#[test]
fn only_the_first_name_of_a_chained_assignment_and_no_tuple_or_unannotated_attribute_is_a_symbol() {
    let raw = extract(b"a = b = 1\nc, d = 1, 2\nclass K:\n    state = 0\n    typed: int = 0\n");
    let names: Vec<&str> = raw
        .symbols
        .iter()
        .map(|symbol| symbol.qualified_name.as_str())
        .collect();

    assert_eq!(names, ["a", "K", "K.typed"]);
}

#[test]
fn a_function_carries_its_declaration_as_its_signature() {
    let raw = extract(b"def greet(name, count=1):\n    return name\n");

    assert_eq!(
        named(&raw, "greet").signature.as_deref(),
        Some("def greet(name, count=1):")
    );
}

#[test]
fn a_method_is_owned_by_its_class_and_an_underscore_hides_it() {
    let raw = extract(SAMPLE);
    let service = named(&raw, "Service");
    let greet = named(&raw, "greet");

    assert_eq!((service.kind, service.exported), (SymbolKind::Class, true));
    assert_eq!(greet.kind, SymbolKind::Method);
    assert_eq!(greet.owner.as_deref(), Some("Service"));
    assert!(!named(&raw, "_private").exported);
}

#[test]
fn a_function_nested_in_a_method_is_no_member_of_the_class() {
    let raw = extract(SAMPLE);
    let nested = named(&raw, "nested");

    assert_eq!(nested.kind, SymbolKind::Function);
    assert_eq!(nested.owner, None);
    assert_eq!(nested.qualified_name, "nested");
}

#[test]
fn a_definition_inside_a_function_body_is_local_to_it() {
    let raw = extract(
        b"def outer():\n    def helper():\n        pass\n    class Local:\n        tag: str = \"\"\n        \
          def run(self):\n            pass\n    return helper()\n\nclass Top:\n    def method(self):\n        pass\n",
    );
    let locals: Vec<SymbolId> = ["helper", "Local", "tag", "run"]
        .into_iter()
        .map(|name| id_of(&raw, name))
        .collect();

    assert_eq!(raw.local_symbols, locals);
}

#[test]
fn a_nested_class_is_qualified_by_the_classes_around_it() {
    let raw = extract(b"class A:\n    class Worker:\n        def run(self):\n            pass\n");
    let run = named(&raw, "run");

    assert_eq!(qualified(&raw, "A.Worker").kind, SymbolKind::Class);
    assert_eq!(run.owner.as_deref(), Some("A.Worker"));
    assert_eq!(run.qualified_name, "A.Worker.run");
}

#[test]
fn superclasses_are_parents_as_written() {
    let raw = extract(SAMPLE);

    assert_eq!(named(&raw, "Service").parents, ["Base", "mixins.Loggable"]);
}

#[test]
fn a_call_belongs_to_the_function_around_it() {
    let raw = extract(SAMPLE);

    let callers: Vec<SymbolId> = raw
        .calls
        .iter()
        .filter(|call| call.callee == "helper" && call.receiver.is_none())
        .map(|call| call.caller_id)
        .collect();
    assert_eq!(
        callers,
        [id_of(&raw, "free_function"), id_of(&raw, "greet")]
    );
}

#[test]
fn a_member_call_on_a_name_records_the_name_as_its_receiver() {
    let raw = extract(SAMPLE);
    let greet = raw
        .calls
        .iter()
        .find(|call| call.callee == "greet")
        .expect("greet call");

    assert_eq!(greet.receiver.as_deref(), Some("self"));
    assert_eq!(greet.caller_id, id_of(&raw, "_private"));
}

#[test]
fn a_member_call_on_an_unnamed_expression_keeps_an_empty_receiver() {
    let raw = extract(b"def f():\n    items[0].close()\n    self.pool.get()\n    make().run()\n");
    let calls: Vec<(&str, Option<&str>)> = raw
        .calls
        .iter()
        .map(|call| (call.callee.as_str(), call.receiver.as_deref()))
        .collect();

    assert_eq!(
        calls,
        [
            ("close", Some("")),
            ("get", Some("")),
            ("run", Some("")),
            ("make", None)
        ]
    );
}

#[test]
fn a_call_before_the_first_definition_or_of_a_computed_callee_is_dropped() {
    let raw = extract(b"setup()\ndef f():\n    handlers[0]()\n    run()\n");
    let callees: Vec<&str> = raw.calls.iter().map(|call| call.callee.as_str()).collect();

    assert_eq!(callees, ["run"]);
}

#[test]
fn every_import_leaves_one_directive_with_its_names() {
    let raw = extract(SAMPLE);
    let directives: Vec<(&str, Vec<&str>)> = raw
        .directives
        .iter()
        .map(|directive| {
            (
                directive.spec.as_str(),
                directive.names.iter().map(String::as_str).collect(),
            )
        })
        .collect();

    assert_eq!(
        directives,
        [
            ("os", vec![]),
            ("numpy", vec![]),
            ("collections", vec!["OrderedDict", "defaultdict"]),
            (".", vec!["sibling"]),
        ]
    );
}

#[test]
fn an_aliased_name_is_recorded_by_the_name_it_imports() {
    let raw =
        extract(b"import a.b as ab, c\nfrom . import sibling, name as aliased\nfrom x import *\n");
    let directives: Vec<(&str, Vec<&str>)> = raw
        .directives
        .iter()
        .map(|directive| {
            (
                directive.spec.as_str(),
                directive.names.iter().map(String::as_str).collect(),
            )
        })
        .collect();

    assert_eq!(
        directives,
        [
            ("a.b", vec![]),
            ("c", vec![]),
            (".", vec!["sibling", "name"]),
            ("x", vec![])
        ]
    );
}

#[test]
fn a_future_import_names_the_future_module_and_its_features() {
    let raw = extract(b"from __future__ import annotations, division\n");

    assert_eq!(raw.directives.len(), 1);
    assert_eq!(raw.directives[0].spec, "__future__");
    assert_eq!(raw.directives[0].names, ["annotations", "division"]);
    assert_ne!(
        raw.directives[0].form,
        extract(b"import os\n").directives[0].form
    );
}

#[test]
fn only_a_free_module_level_main_is_the_entry_point() {
    let raw = extract(
        b"def main():\n    run()\n\n\ndef helper():\n    pass\n\n\n\
          class App:\n    def main(self):\n        pass\n\n\n\
          def outer():\n    def main():\n        pass\n    return main\n",
    );

    assert!(qualified(&raw, "main").flags.is_entry());
    assert!(!qualified(&raw, "App.main").flags.is_entry());
    assert!(!named(&raw, "helper").flags.is_entry());
    let nested = raw
        .symbols
        .iter()
        .filter(|symbol| symbol.qualified_name == "main")
        .nth(1)
        .expect("nested main");
    assert!(!nested.flags.is_entry());
}

#[test]
fn a_decorated_main_is_still_the_entry_point() {
    let raw = extract(b"@click.command()\ndef main():\n    pass\n");

    assert!(named(&raw, "main").flags.is_entry());
}

#[test]
fn a_marker_in_a_header_comment_or_the_module_docstring_marks_the_file_generated() {
    for source in [
        b"# Generated by codegen. DO NOT EDIT.\n\ndef emitted():\n    pass\n".as_slice(),
        b"#!/usr/bin/env python\n\"\"\"\nModule summary.\n\n@generated by a tool.\n\"\"\"\n\n\
          def emitted():\n    pass\n",
        b"r\"\"\"\n@generated by a tool.\n\"\"\"\n\ndef emitted():\n    pass\n",
        b"u\"\"\"DO NOT EDIT.\"\"\"\n\ndef emitted():\n    pass\n",
        b"\"\"\"\nsummary\n\"\"\"\n# @generated\ndef emitted():\n    pass\n",
        b"\"\"\"Summary.\"\"\"  # @generated\ndef emitted():\n    pass\n",
        b"\"\"\"Quotes \\\"\"\" stay inside.\n@generated\n\"\"\"\ndef emitted():\n    pass\n",
        b"r'''Raw \\''' too. @generated'''\ndef emitted():\n    pass\n",
        b"\xEF\xBB\xBF# @generated\ndef emitted():\n    pass\n",
    ] {
        assert_eq!(
            generated(source),
            [true],
            "{}",
            String::from_utf8_lossy(source)
        );
    }
}

#[test]
fn a_plain_header_a_mention_or_a_marker_after_code_marks_nothing() {
    for source in [
        b"def from_proto():\n    pass\n".as_slice(),
        b"\"\"\"Module summary, hand written.\"\"\"\n\ndef f():\n    pass\n",
        b"\"\"\"Codegen helpers.\n\nEmitted files carry a `@generated` / `DO NOT EDIT` header.\n\"\"\"\n\n\
          def f():\n    pass\n",
        b"\"\"\"\nmodule summary\n\"\"\" ; CONST = 1\n# DO NOT EDIT\ndef real():\n    pass\n",
        b"\"\"\"summary\"\"\"; S = \"DO NOT EDIT\"\n\ndef coded():\n    pass\n",
        b"\"\"\"summary\"\"\"; S = 1\n# @generated\ndef coded():\n    pass\n",
        b"r\"\"\"Raw module summary.\"\"\"\n\ndef f():\n    pass\n",
        b"# a `@generated` / `DO NOT EDIT` marker\ndef f():\n    pass\n",
        b"import os\n# @generated\ndef f():\n    pass\n",
    ] {
        let flags = generated(source);

        assert_ne!(flags.len(), 0, "{}", String::from_utf8_lossy(source));
        assert!(!flags.contains(&true), "{}", String::from_utf8_lossy(source));
    }
}

#[test]
fn python_claims_its_extensions_in_any_case() {
    let python = Python::new();

    assert!(python.claims("pkg/service.py"));
    assert!(python.claims("pkg/stub.PYI"));
    assert!(!python.claims("notes.md"));
    assert!(!python.claims("py"));
}

#[test]
fn the_fingerprint_names_the_crate_and_stays_put() {
    let first = Python::new().fingerprint().to_vec();

    assert!(first.starts_with(b"kartta-lang-python\0"));
    assert_eq!(Python::new().fingerprint(), first.as_slice());
}