| 1963 | } |
| 1964 | |
| 1965 | static int parse_narrowing_one(PHPLSPContext *ctx, TSNode cond, php_narrowing_t *out) { |
| 1966 | if (ts_node_is_null(cond)) |
| 1967 | return 0; |
| 1968 | const char *kind = ts_node_type(cond); |
| 1969 | if (strcmp(kind, "parenthesized_expression") == 0) { |
| 1970 | uint32_t nc = ts_node_child_count(cond); |
| 1971 | for (uint32_t i = 0; i < nc; i++) { |
| 1972 | TSNode c = ts_node_child(cond, i); |
| 1973 | if (!ts_node_is_null(c) && ts_node_is_named(c)) { |
| 1974 | return parse_narrowing_one(ctx, c, out); |
| 1975 | } |
| 1976 | } |
| 1977 | return 0; |
| 1978 | } |
| 1979 | |
| 1980 | /* `$x instanceof Foo` — emitted as binary_expression with operator |
| 1981 | * "instanceof" in tree-sitter-php. */ |
| 1982 | if (strcmp(kind, "binary_expression") == 0) { |
| 1983 | TSNode left = ts_node_child_by_field_name(cond, "left", 4); |
| 1984 | TSNode op = ts_node_child_by_field_name(cond, "operator", 8); |
| 1985 | TSNode right = ts_node_child_by_field_name(cond, "right", 5); |
| 1986 | if (ts_node_is_null(left) || ts_node_is_null(right)) |
| 1987 | return false; |
| 1988 | char *opt = !ts_node_is_null(op) ? php_node_text(ctx, op) : NULL; |
| 1989 | if (opt && strcmp(opt, "instanceof") == 0) { |
| 1990 | if (!node_is(left, "variable_name")) |
| 1991 | return false; |
| 1992 | char *vt = php_node_text(ctx, left); |
| 1993 | if (!vt) |
| 1994 | return false; |
| 1995 | const char *vname = (vt[0] == '$') ? vt + 1 : vt; |
| 1996 | char *rt = php_node_text(ctx, right); |
| 1997 | if (!rt) |
| 1998 | return false; |
| 1999 | const char *resolved = php_resolve_class_name(ctx, rt); |
| 2000 | if (!resolved) |
| 2001 | return false; |
| 2002 | out->var_name = cbm_arena_strdup(ctx->arena, vname); |
| 2003 | out->type = cbm_type_named(ctx->arena, resolved); |
| 2004 | return true; |
| 2005 | } |
| 2006 | /* `$x !== null` / `$x != null` / `null !== $x` — narrow to "non-null": |
| 2007 | * we keep the existing scope type, so this is a no-op for type |
| 2008 | * purposes but suppresses null branches downstream. We don't |
| 2009 | * subtract nullable so just return false here. */ |
| 2010 | } |
| 2011 | |
| 2012 | /* `is_string($x)` / `is_int($x)` / `array_key_exists(...)` / |
| 2013 | * `method_exists($x, 'foo')` / `is_a($x, Foo::class)` / ... */ |
| 2014 | if (strcmp(kind, "function_call_expression") == 0) { |
| 2015 | TSNode fn = ts_node_child_by_field_name(cond, "function", 8); |
| 2016 | TSNode args = ts_node_child_by_field_name(cond, "arguments", 9); |
| 2017 | if (ts_node_is_null(fn)) |
| 2018 | return false; |
| 2019 | char *name = php_node_text(ctx, fn); |
| 2020 | if (!name) |
| 2021 | return false; |
| 2022 | /* `is_a($x, Foo::class)` and `is_a($x, 'Foo')` narrow $x to Foo. */ |
no test coverage detected