13 Commits

Author SHA1 Message Date
Martin Vogel 87a0e3f74f fix: preserve semantic graph relationships
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-07-18 15:52:50 +02:00
Martin Vogel df7cae4d83 style: restore original test_php_lsp.c formatting
DCO / dco (push) Has been cancelled
The previous commit's clang-format pass reformatted the whole file
(tests are not in the lint-enforced LINT_SRCS set, so the committed
file was never format-clean under the local formatter). Restore the
original formatting; the branch's net diff against main is now exactly
the two new regression guards.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-07-09 22:32:26 +02:00
Martin Vogel 7f5d2d8bcc test(php-lsp): regression guards for aliased-trait name-collision OOMs
Two reported indexer OOMs reduce to the same self-flattening loop the
trait-uses-itself fix closed (self-flatten short-circuit + snapshotted
loop bound in flatten_trait_into_class):

- a trait whose name collides with an aliased `use ... as` import it
  composes (#765's exact single-file reproducer) — the alias
  canonicalizes onto the enclosing trait via the short-name fallback
- a class sharing its short name with an aliased trait import (#951's
  reproducer, reduced to one file: the trait definition being
  unavailable is what forces the short-name fallback onto the class)

Both fixtures were verified RED against the pre-guard code (each hangs
the suite within the 90s alarm when the two guards are reverted, each
independently as the first test run) and GREEN with the guards in
place. Landing them as permanent regression guards; the issues close as
fixed-by-the-#920-pair.

Closes #765
Closes #951

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
2026-07-09 22:24:11 +02:00
Mubariz 2154edf590 fix(lsp/php): prevent OOM when a trait uses itself
flatten_trait_into_class() iterated reg->funcs with a live upper bound
(reg->func_count) while cbm_registry_add_func() appended to that same
array inside the loop. Each copied method is tagged with
receiver_type = class_qn, so when a trait adopts itself -- directly
(`trait T { use T; }`) or via an alias that resolves back to the trait
by short name (`use X\T as A; use A;`) -- class_qn equals
canonical_trait_qn and every appended method re-matches the loop filter,
extending the iteration. The loop never terminates: it arena-allocates a
fresh method each pass until the process exhausts all memory (observed:
40 GB+, freezing the host).

Fix:
- Short-circuit self-flattening: a trait cannot meaningfully use itself
  (PHP itself rejects it), so return early when class_qn equals the
  resolved trait QN.
- Snapshot reg->func_count before the loop so entries appended during
  iteration are never revisited (defensive against the mutate-while-
  iterating hazard in general).

Add regression test phplsp_trait_self_use_terminates: it hangs/OOMs on
the pre-fix code and passes after. Verified end to end -- the prod binary
now indexes the triggering file in <0.5s at ~6 MB RSS instead of running
away.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Signed-off-by: Mubariz <mubariz@sportimport.de>
2026-07-06 18:14:47 +02:00
Martin Vogel 89531c7501 feat(php-lsp): @phpstan-type aliases + Closure::bind + variance + 30 tests
Phase 5f, 4ac, 4ad: closing the long-tail gaps toward LSP-server parity.

  - @phpstan-type / @psalm-type / @phan-type aliases parsed from class
    docblocks and applied during PHPDoc type resolution. References to
    the alias name in @var/@param/@return are rewritten to the aliased
    type. Aliases live on PHPLSPContext (per-file).
  - @phpstan-import-type accepted without crash (cross-file alias
    resolution deferred — same root cause as Composer PSR-4).
  - @template-covariant T and @template-contravariant T now register T
    as a proper type-param (previously skipped along with
    @template-extends).
  - Closure binding: \\Closure::bind($f, $obj) and $f->bindTo($obj),
    when invoked with an inline closure literal as the first arg, walk
    the closure body with $this rebound to the second arg's class.
    Resolves the Laravel-macroable / VarDumper / encapsulation patterns.
  - @return ($x is string ? int : bool) conditional return-type syntax
    accepted without crash (parsed leftmost segment as fallback).
  - Long PHPDoc blocks with mixed @param/@return/@throws/@internal
    parsed without misattributing tags.

Stdlib unchanged.

Tests: 248 → 278 covering:
  - phpstan-type alias basic / via @param / union / array-shape
  - psalm-type alternate spelling
  - phpstan-import-type (no-crash)
  - Closure::bind / ::bindTo / static-bind on arrow fn
  - conditional return / template-covariant / -contravariant (no-crash)
  - class-string<T>, int<0,100>, literal-string (no-crash on phpstan
    types we don't fully model)
  - 8 realistic patterns: repository, event listener, console command,
    form handler, mail sender, cached service, logger w/ context,
    Carbon chains in methods, Eloquent model.

Total tests: 3061 → 3091 / 0 failed.
2026-05-09 16:05:45 +02:00
Martin Vogel 149d2831b8 test(php-lsp): 50 more edge-case tests (200 → 248)
Real-world PHP patterns covered:
  - Constructor property promotion + chain
  - Enum method dispatch with backed values
  - assert + 2-level chain
  - Negative narrowing through throw
  - Closure::fromCallable via [\$this, 'method']
  - Late assignment chain ($a = null; $a = new A(); $a->go())
  - Callable typed parameter
  - Nullable param chain via if-truthy narrowing
  - Attribute (#[...]) above class
  - Method with reference param
  - Abstract methods (no body)
  - Interface only (no impl)
  - Nested match expressions
  - Long static chain (Carbon)
  - Iterable typed parameter
  - array<T> via @var
  - Two traits in one class
  - Enum implementing interface
  - Constructor with readonly + private + promotion
  - Anonymous class (graceful no-resolve)
  - Arrow function implicit capture
  - 5-deep namespace path
  - PSR-7 full lifecycle
  - DateTimeImmutable chain
  - Throwable getMessage/getCode/getFile/getLine
  - PSR Container has/get
  - Long nullsafe chain
  - self/static in constructor
  - parent:: method dispatch
  - private/protected/public method visibility
  - final class
  - Property with default value
  - Private static factory + chain

Total: 3013 → 3061 / 0 failed (php_lsp 200 → 248).
2026-05-09 15:02:12 +02:00
Martin Vogel d8646dae91 feat(php-lsp): trait self substitution + 2-pass class processing
When a trait method declares `: self` as its return type, flattening
that method into a using class now substitutes the trait's QN with the
using class's QN in the return type. This fixes fluent chains like:

    trait T { public function tap(): self { return $this; } }
    class C { use T; public function ok(): int { return 1; } }
    $c->tap()->ok();   // resolves through to C.ok now

Implementation:
  - flatten_trait_into_class scans the source method's signature for
    NAMED(trait_qn) in the return type and rewrites it to
    NAMED(using_class_qn) when registering the flattened method.
  - php_lsp_collect_class_fields now does TWO passes — pass 0 for
    trait/interface declarators (so their declared-return-types get
    re-parsed before any consumer), pass 1 for class/enum (which may
    `use Trait;` and need the trait's signatures already up-to-date).

Total tests: 3013 / 0 failed (200 php_lsp).
2026-05-09 14:50:06 +02:00
Martin Vogel 20dd651a2e feat(php-lsp): @return $this/static, if-condition call walk, +50 tests
Phase 4aa, 4ab partial, 4y/z best-effort, 5e: more stdlib + tests.

  - @return $this / @return static / @return self in PHPDoc all bind to
    the enclosing class type, enabling fluent-builder chains.
  - Declared return-type re-parse uses ctx->enclosing_class_qn so the
    `: self` shorthand on a method correctly returns NAMED(class).
  - php_resolve_class_name now checks self/static/parent BEFORE the
    builtin-name guard, fixing a long-standing miss where these
    pseudo-types were rejected as builtins.
  - if-condition walk: calls inside `if ($it->valid())` are now
    resolved (they previously only got narrowing analysis).
  - Removed duplicate Generator type registration in stdlib data.

Stdlib expansion (Phase 5e):
  - Symfony Cache (CacheInterface, ItemInterface) + PSR Cache pool/item
  - Symfony EventDispatcher (EventDispatcherInterface, Event)
  - Symfony Mailer (MailerInterface) + Mime\\Email fluent builder
  - Symfony Validator (ValidatorInterface, ConstraintViolationListInterface)
  - Laravel Http\\Request, JsonResponse, Response with method chains
  - Laravel Auth\\Guard, Authenticatable contracts
  - Laravel Session, View
  - ReactPHP / GuzzleHttp Promise interfaces
  - Monolog Logger (extends PSR LoggerInterface)
  - Reflection API (ReflectionClass/Method/Property/Function)

Tests: 150 -> 200 covering @return $this fluent chains, Symfony
Cache/Mailer/Validator, Laravel Request/Auth/View, Promise chains,
Monolog, Reflection, multi-interface impl, deep parent chains, foreach
key-value chains, and a realistic Laravel UserController integration.

Total tests: 2963 -> 3013 / 0 failed.
2026-05-09 14:31:26 +02:00
Martin Vogel 090fdb8935 feat(php-lsp): cover Phases 4t/4v/5d + 25 more tests, 100→150 tests
- Generic substitution end-to-end (T<->concrete-arg) for any class with
  @template + @return T, including ancestor walks via belt-and-suspenders
  AST-extracted base_clause / class_interface_clause.
- Block-form `namespace App { class Foo {} }` — robust child traversal
  through declaration_list / compound_statement variants; also collects
  `use` clauses from inside the block.
- Declared method return types re-parsed via php_parse_type_node so
  `function f(): \Generator<int, User>` becomes a proper TEMPLATE.
- Stdlib expansion: Symfony Console (SymfonyStyle, In/OutputInterface),
  Doctrine ORM (EntityManagerInterface, QueryBuilder, Query, Repository),
  Guzzle (Client, ClientInterface), Twig (Environment, TemplateWrapper),
  Eloquent Model magic-static methods (where/whereIn/orderBy/...).
- Pipeline bridge unchanged; resolution all happens at LSP level.

Test coverage: 125 -> 150 tests; total 2938 -> 2963 / 0 failed.
2026-05-09 11:45:11 +02:00
Martin Vogel a3a64fc009 feat(php-lsp): generic substitution + 25 more features toward LSP parity
Phase 4m–w in one push, plus 25 new tests (100 → 125, all green).

New capabilities:

  - Generic @template substitution:
    @template T on a class records T as a type-param;
    @return T on a method gets parsed as NAMED("T");
    when receiver is TEMPLATE("Container", [User]), method-call return
    types are substituted T → User so chains like
    `$container->get()->name()` resolve through to the element type.
  - Closure use(...) capture: typed variables in `use ($a, $b)` clauses
    of `function () use (...) {}` are inherited from the parent scope.
  - Multi-conjunction narrowing: `if ($x instanceof A && $y instanceof B)`
    narrows BOTH $x and $y in the if-body. Up to 8 simultaneous narrowings.
  - is_a($x, Foo::class) narrowing — both the ::class and string forms.
  - Subscript inference: $arr[$k] on `array<T>` returns T;
    on `array<K, V>` returns V;
    on a NAMED ArrayAccess class consults registered offsetGet.
  - Enum case access: Suit::Hearts evaluates to NAMED(Suit) so
    Suit::Hearts->label() resolves to Suit::label.
  - @extends ParentClass<X>: appends ParentClass to embedded_types so
    the inheritance walk picks up methods from generic ancestors.
  - PHPDoc @return on methods with no declared return type updates
    the registry signature.
  - foreach key=>value: handles tree-sitter-php's `pair` node so
    `foreach ($users as $idx => $user)` binds $user to the element type.
  - Class-level @template-extends, @template-implements parsed without
    crashing.
  - Don't override TEMPLATE/NAMED bindings with `null` literal —
    preserves @var-typed variables across `$x = null` initialization.

Stdlib expansion (Phase 5d):
  - Symfony Console: SymfonyStyle, InputInterface, OutputInterface
  - Doctrine ORM: EntityManagerInterface, QueryBuilder chain, Query,
    EntityRepository
  - Guzzle HTTP: Client and ClientInterface (returning PSR-7 responses)
  - Twig: Environment, TemplateWrapper
  - Eloquent Model: forwarded static methods (where, whereIn, etc.)
    so `User::where()->first()` chains resolve immediately.

Test coverage: 100 -> 125 tests; total 2913 -> 2938 / 0 failed.
2026-05-09 11:10:28 +02:00
Martin Vogel da9f20d55a feat(php-lsp): generic templates, negative narrowing, expanded stdlib
Phase 4g+ / 4l / 5b additions toward LSP-server type-resolution parity:

  - Generic template parsing in PHPDoc: parse `Collection<User>`,
    `array<int, User>`, `iterable<T>`, `list<T>`, etc. Bind variables
    to CBM_TYPE_TEMPLATE; method dispatch on a TEMPLATE receiver
    resolves against the template's base class.
  - Foreach element-type propagation: `foreach ($users as $u)` where
    $users: array<User> binds $u to User. Two-arg array<K,V> takes
    V. Falls back to Iterator::current() return type for NAMED types
    that implement the iterator interface.
  - Negative narrowing: `if (!($x instanceof Foo)) return;` (or throw)
    narrows $x to Foo for the rest of the enclosing scope.
  - Foreach iterable can be an arbitrary expression (variable_name,
    member call, function call) — fixed earlier-too-narrow filter.
  - PHPDoc @var/@param accept generic syntax: type token now spans
    angle brackets so `array<User> $users` parses correctly.
  - Stdlib expansion (Laravel + Symfony): full Eloquent Builder
    method chain (where/orderBy/limit/get/first/...), Eloquent Model
    static factories, Illuminate\Support\Collection chains
    (map/filter/sort/...), Symfony HttpFoundation Request/Response,
    Carbon date methods, PSR-7 with*() builders.

Test suite: 81 -> 100 tests, all passing. Total: 2913 / 0.
2026-05-09 02:53:55 +02:00
Martin Vogel 82d0935fbd feat(php-lsp): Phase 4 — depth toward LSP-server parity
Adds the resolver passes that close most of the gap to a real PHP language
server's type inference, while staying in-process and PHP-runtime-free.

New capabilities:
  - Type narrowing: instanceof, is_string/int/float/bool/array/object/...
    is_callable, is_iterable, is_numeric. Active inside if/elseif bodies
    and after assert(...) (sequential narrowing)
  - Property type tracking: typed property declarations, constructor
    property promotion (public X $foo), and constructor-body inference
    ($this->bar = $bar where $bar is typed)
  - Late-static-binding chain depth: full ancestor walk with cycle
    detection for $obj->method() and Class::method() resolution
  - Trait flattening: methods from `use Trait;` inside a class body are
    re-registered with the using class as receiver; basic `as` aliasing
    is honored
  - PHPDoc class-level tags: @property TYPE $name binds a virtual field
    on the class; @method TYPE name() registers a virtual method
    (Eloquent-style dynamic dispatch)
  - Match expression result type: union over arm result expressions,
    first concrete type wins
  - Ternary result type: prefers the consequent, falls back to alternative
  - Variadic parameter binding: $args bound to `array`
  - `use Vendor\\Helper as H;` two-name form correctly maps H -> Vendor.Helper
  - Static-call unindexed fallback: when class is resolved from `use`
    but methods unindexed, emit php_static_unindexed for the bridge
  - Stdlib expansion: full Eloquent Builder + Model + Collection method
    chains, Symfony HttpFoundation Request/Response, Carbon date/time,
    PSR-7 with*() builders

Test suite expanded from 16 to 81 tests (2829 -> 2893 total).
2026-05-09 02:05:39 +02:00
Martin Vogel f0905589cf test(php-lsp): add 16 single-file regression tests
Covers parameter binding (typed param, arrow function, $this, catch),
method dispatch (typed receiver, chain, self/parent), static calls,
namespace + use resolution, PHPDoc @var, magic methods, and the
ConfiguresPrompts $prompt->value() regression from PHP_LSP_PRE_FLIGHT.md.

Wired into ALL_TEST_SRCS and suite_php_lsp invocation in test_main.c.
All 16 tests pass; total suite is now 2829/0 passing.
2026-05-08 23:33:16 +02:00