Handle CommonJS `require("path")` call_expression nodes. The local name * is derived from the enclosing variable_declarator / assignment when * possible (so `const foo = require('./foo')` emits local_name="foo"), * otherwise falls back to the last path component. */
| 952 | * possible (so `const foo = require('./foo')` emits local_name="foo"), |
| 953 | * otherwise falls back to the last path component. */ |
| 954 | static bool process_commonjs_require(CBMExtractCtx *ctx, TSNode call) { |
| 955 | CBMArena *a = ctx->arena; |
| 956 | if (ts_node_child_count(call) < MIN_WOLFRAM_CHILDREN) { |
| 957 | return false; |
| 958 | } |
| 959 | /* Callee must be the identifier "require". */ |
| 960 | TSNode fn = ts_node_child_by_field_name(call, TS_FIELD("function")); |
| 961 | if (ts_node_is_null(fn)) { |
| 962 | fn = ts_node_child(call, 0); |
| 963 | } |
| 964 | if (ts_node_is_null(fn)) { |
| 965 | return false; |
| 966 | } |
| 967 | const char *fn_kind = ts_node_type(fn); |
| 968 | if (strcmp(fn_kind, "identifier") != 0) { |
| 969 | return false; |
| 970 | } |
| 971 | char *fn_name = cbm_node_text(a, fn, ctx->source); |
| 972 | if (!fn_name || strcmp(fn_name, "require") != 0) { |
| 973 | return false; |
| 974 | } |
| 975 | |
| 976 | /* First string literal child of the argument list is the module path. */ |
| 977 | TSNode args = ts_node_child_by_field_name(call, TS_FIELD("arguments")); |
| 978 | if (ts_node_is_null(args)) { |
| 979 | return false; |
| 980 | } |
| 981 | uint32_t argc = ts_node_named_child_count(args); |
| 982 | char *path = NULL; |
| 983 | for (uint32_t i = 0; i < argc; i++) { |
| 984 | TSNode arg = ts_node_named_child(args, i); |
| 985 | const char *ak = ts_node_type(arg); |
| 986 | if (strcmp(ak, "string") == 0 || strcmp(ak, "string_literal") == 0 || |
| 987 | strcmp(ak, "template_string") == 0) { |
| 988 | path = strip_quotes(a, cbm_node_text(a, arg, ctx->source)); |
| 989 | break; |
| 990 | } |
| 991 | } |
| 992 | if (!path || !path[0]) { |
| 993 | return false; |
| 994 | } |
| 995 | |
| 996 | /* Infer local name from enclosing variable_declarator. Tree-sitter's JS |
| 997 | * grammar wraps `const foo = require(..)` as |
| 998 | * lexical_declaration → variable_declarator { name: identifier, value: call } */ |
| 999 | const char *local_name = NULL; |
| 1000 | TSNode parent = ts_node_parent(call); |
| 1001 | if (!ts_node_is_null(parent) && strcmp(ts_node_type(parent), "variable_declarator") == 0) { |
| 1002 | TSNode name_node = ts_node_child_by_field_name(parent, TS_FIELD("name")); |
| 1003 | if (!ts_node_is_null(name_node) && strcmp(ts_node_type(name_node), "identifier") == 0) { |
| 1004 | local_name = cbm_node_text(a, name_node, ctx->source); |
| 1005 | } |
| 1006 | } |
| 1007 | if (!local_name) { |
| 1008 | local_name = path_last(a, path); |
| 1009 | } |
| 1010 | |
| 1011 | CBMImport imp = {.local_name = local_name, .module_path = path}; |
no test coverage detected