Process a single Python import_from_statement node (from X import Y [as Z]).
| 275 | |
| 276 | // Process a single Python import_from_statement node (from X import Y [as Z]). |
| 277 | static void process_py_import_from(CBMExtractCtx *ctx, TSNode node) { |
| 278 | CBMArena *a = ctx->arena; |
| 279 | // `from __future__ import annotations` is a dedicated node type whose first |
| 280 | // child is the literal `__future__` keyword (an identifier, not a |
| 281 | // dotted_name). Emit a single import for `__future__` and return. |
| 282 | if (strcmp(ts_node_type(node), "future_import_statement") == 0) { |
| 283 | CBMImport imp = {.local_name = cbm_arena_strdup(a, "__future__"), |
| 284 | .module_path = cbm_arena_strdup(a, "__future__")}; |
| 285 | cbm_imports_push(&ctx->result->imports, a, imp); |
| 286 | return; |
| 287 | } |
| 288 | TSNode module_node = resolve_py_module_node(node); |
| 289 | char *mod_path = |
| 290 | ts_node_is_null(module_node) ? NULL : cbm_node_text(a, module_node, ctx->source); |
| 291 | |
| 292 | uint32_t nc = ts_node_child_count(node); |
| 293 | bool emitted = false; |
| 294 | for (uint32_t j = 0; j < nc; j++) { |
| 295 | TSNode child = ts_node_child(node, j); |
| 296 | const char *ck = ts_node_type(child); |
| 297 | if (strcmp(ck, "identifier") == 0 || strcmp(ck, "dotted_name") == 0) { |
| 298 | if (!ts_node_is_null(module_node) && |
| 299 | ts_node_start_byte(child) == ts_node_start_byte(module_node)) { |
| 300 | continue; |
| 301 | } |
| 302 | emit_py_import_from_name(ctx, child, mod_path); |
| 303 | emitted = true; |
| 304 | } else if (strcmp(ck, "aliased_import") == 0) { |
| 305 | emit_py_aliased_import(ctx, child, mod_path); |
| 306 | emitted = true; |
| 307 | } else if (strcmp(ck, "wildcard_import") == 0) { |
| 308 | // `from os.path import *` — the module itself is the import. |
| 309 | if (mod_path && mod_path[0]) { |
| 310 | CBMImport imp = {.local_name = path_last(a, mod_path), .module_path = mod_path}; |
| 311 | cbm_imports_push(&ctx->result->imports, a, imp); |
| 312 | emitted = true; |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | // Defensive: a from-import with a module but no recognized name child |
| 317 | // (grammar variant) still records the module as an import. |
| 318 | if (!emitted && mod_path && mod_path[0]) { |
| 319 | CBMImport imp = {.local_name = path_last(a, mod_path), .module_path = mod_path}; |
| 320 | cbm_imports_push(&ctx->result->imports, a, imp); |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | static void parse_python_imports(CBMExtractCtx *ctx) { |
| 325 | TSTreeCursor cursor = ts_tree_cursor_new(ctx->root); |
no test coverage detected