Variant that takes the node's parent DIRECTLY. The callers in * extract_defs.c iterate a known parent's children, so they already * have the parent — passing it here avoids ts_node_parent(node), which * is O(n) per call (tree-sitter nodes carry no parent pointer; the * parent is found by rescanning from the root). On a pathologically * large file (e.g. a 583k-line generated/fixture file with
| 1649 | * thousands of top-level statements) the old per-child ts_node_parent |
| 1650 | * made extraction O(n²) and effectively hung. */ |
| 1651 | bool cbm_is_module_level_p(TSNode parent, CBMLanguage lang) { |
| 1652 | if (ts_node_is_null(parent)) { |
| 1653 | return false; |
| 1654 | } |
| 1655 | const char *pk = ts_node_type(parent); |
| 1656 | |
| 1657 | // Languages with wrapper-pattern (expression_statement/export_statement/assignment_statement) |
| 1658 | if (lang == CBM_LANG_PYTHON) { |
| 1659 | return check_script_module_level(parent, pk, "module", "expression_statement"); |
| 1660 | } |
| 1661 | if (lang == CBM_LANG_JAVASCRIPT || lang == CBM_LANG_TYPESCRIPT || lang == CBM_LANG_TSX || |
| 1662 | lang == CBM_LANG_ARKTS) { |
| 1663 | return check_script_module_level(parent, pk, "program", "export_statement"); |
| 1664 | } |
| 1665 | if (lang == CBM_LANG_LUA) { |
| 1666 | return check_script_module_level(parent, pk, "chunk", "assignment_statement"); |
| 1667 | } |
| 1668 | if (lang == CBM_LANG_YAML) { |
| 1669 | return strcmp(pk, "document") == 0 || strcmp(pk, "stream") == 0 || |
| 1670 | strcmp(pk, "block_mapping") == 0; |
| 1671 | } |
| 1672 | |
| 1673 | // Table lookup for the rest |
| 1674 | const char **parents = get_module_parents(lang); |
| 1675 | if (parents) { |
| 1676 | for (const char **p = parents; *p; p++) { |
| 1677 | if (strcmp(pk, *p) == 0) { |
| 1678 | return true; |
| 1679 | } |
| 1680 | } |
| 1681 | } |
| 1682 | return false; |
| 1683 | } |
| 1684 | |
| 1685 | /* Back-compat wrapper: computes the parent via ts_node_parent (O(n)). |
| 1686 | * Prefer cbm_is_module_level_p at call sites that already know the |
no test coverage detected