Skip to content

Commit 32445b2

Browse files
authored
Merge pull request DeusData#2706 from DeusData/fix/php-trait-flatten-index
fix(php): index trait methods by receiver while flattening (DeusData#1265)
2 parents efe007e + e9b334e commit 32445b2

3 files changed

Lines changed: 287 additions & 32 deletions

File tree

‎internal/cbm/lsp/php_lsp.c‎

Lines changed: 161 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@
1919

2020
#include "php_lsp.h"
2121
#include "lsp_node_iter.h"
22+
#include "lsp_work.h"
2223
#include "../helpers.h"
24+
#include "../../../src/foundation/hash_table.h"
2325
#include <ctype.h>
2426
#include <stdio.h>
2527
#include <stdlib.h>
@@ -3745,6 +3747,126 @@ static void apply_phpdoc_class_tags(PHPLSPContext *ctx, CBMTypeRegistry *reg, co
37453747
* - handle `as` aliasing: register method under the alias name too
37463748
* - skip insteadof (rare in practice; full support deferred)
37473749
*/
3750+
/* The registry indices of each receiver's methods, in registration order.
3751+
* Flattening a trait used to visit EVERY registered function to find the
3752+
* trait's own, so a file whose classes use traits paid O(uses x functions),
3753+
* and the functions grow with every class flattened before: quadratic in the
3754+
* trait-using classes of one file (#1265). The registry is append-only, so
3755+
* the index catches up incrementally (indexed_upto) and never misses a
3756+
* function registered between two flattens. */
3757+
typedef struct {
3758+
int *items;
3759+
int count;
3760+
int cap;
3761+
} php_func_ids_t;
3762+
3763+
struct php_trait_index {
3764+
CBMHashTable *by_receiver; /* receiver_type (borrowed) -> php_func_ids_t* */
3765+
int indexed_upto; /* reg->funcs[0, indexed_upto) are indexed */
3766+
bool failed; /* allocation failed: callers use the full scan */
3767+
};
3768+
3769+
static bool php_func_ids_push(CBMArena *arena, php_func_ids_t *ids, int func_index) {
3770+
if (ids->count == ids->cap) {
3771+
int cap = ids->cap ? ids->cap * 2 : 4;
3772+
int *items = (int *)cbm_arena_alloc(arena, (size_t)cap * sizeof(*items));
3773+
if (!items) {
3774+
return false;
3775+
}
3776+
if (ids->count > 0) {
3777+
memcpy(items, ids->items, (size_t)ids->count * sizeof(*items));
3778+
}
3779+
ids->items = items;
3780+
ids->cap = cap;
3781+
}
3782+
ids->items[ids->count++] = func_index;
3783+
return true;
3784+
}
3785+
3786+
/* Index every function registered since the last call. Returns false (and
3787+
* marks the index failed for good) on an allocation failure. */
3788+
static bool php_trait_index_sync(PHPLSPContext *ctx, struct php_trait_index *ix,
3789+
const CBMTypeRegistry *reg) {
3790+
if (ix->failed) {
3791+
return false;
3792+
}
3793+
if (!ix->by_receiver) {
3794+
ix->by_receiver = cbm_ht_create(0);
3795+
if (!ix->by_receiver) {
3796+
ix->failed = true;
3797+
return false;
3798+
}
3799+
}
3800+
for (; ix->indexed_upto < reg->func_count; ix->indexed_upto++) {
3801+
CBM_LSP_WORK(1);
3802+
const char *receiver = reg->funcs[ix->indexed_upto].receiver_type;
3803+
if (!receiver) {
3804+
continue;
3805+
}
3806+
php_func_ids_t *ids = (php_func_ids_t *)cbm_ht_get(ix->by_receiver, receiver);
3807+
if (!ids) {
3808+
ids = (php_func_ids_t *)cbm_arena_alloc(ctx->arena, sizeof(*ids));
3809+
if (!ids) {
3810+
ix->failed = true;
3811+
return false;
3812+
}
3813+
memset(ids, 0, sizeof(*ids));
3814+
cbm_ht_set(ix->by_receiver, receiver, ids);
3815+
}
3816+
if (!php_func_ids_push(ctx->arena, ids, ix->indexed_upto)) {
3817+
ix->failed = true;
3818+
return false;
3819+
}
3820+
}
3821+
return true;
3822+
}
3823+
3824+
static void php_trait_index_free(struct php_trait_index *ix) {
3825+
if (ix->by_receiver) {
3826+
cbm_ht_free(ix->by_receiver);
3827+
ix->by_receiver = NULL;
3828+
}
3829+
}
3830+
3831+
/* Copy one method `src` of the trait into class_qn (see
3832+
* flatten_trait_into_class). Reads src before registering, because
3833+
* cbm_registry_add_func may move reg->funcs. */
3834+
static void flatten_trait_method(PHPLSPContext *ctx, CBMTypeRegistry *reg, const char *class_qn,
3835+
const char *canonical_trait_qn, const CBMRegisteredFunc *src,
3836+
const char *alias_for_method, const char *only_method_name) {
3837+
if (only_method_name && src->short_name && strcmp(src->short_name, only_method_name) != 0) {
3838+
return;
3839+
}
3840+
const char *new_short = alias_for_method ? alias_for_method : src->short_name;
3841+
if (!new_short)
3842+
return;
3843+
CBMRegisteredFunc rf;
3844+
memset(&rf, 0, sizeof(rf));
3845+
rf.qualified_name = cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, new_short);
3846+
rf.short_name = cbm_arena_strdup(ctx->arena, new_short);
3847+
rf.receiver_type = class_qn;
3848+
rf.min_params = src->min_params;
3849+
3850+
/* Self-substitute the return type: any NAMED(trait_qn) in the
3851+
* signature's return becomes NAMED(class_qn). */
3852+
const CBMType *new_sig = src->signature;
3853+
if (src->signature && src->signature->kind == CBM_TYPE_FUNC &&
3854+
src->signature->data.func.return_types) {
3855+
const CBMType *ret0 = src->signature->data.func.return_types[0];
3856+
if (ret0 && ret0->kind == CBM_TYPE_NAMED && ret0->data.named.qualified_name &&
3857+
strcmp(ret0->data.named.qualified_name, canonical_trait_qn) == 0) {
3858+
const CBMType **rets = (const CBMType **)cbm_arena_alloc(ctx->arena, 2 * sizeof(*rets));
3859+
if (rets) {
3860+
rets[0] = cbm_type_named(ctx->arena, class_qn);
3861+
rets[1] = NULL;
3862+
new_sig = cbm_type_func_replace_returns(ctx->arena, src->signature, rets);
3863+
}
3864+
}
3865+
}
3866+
rf.signature = new_sig;
3867+
cbm_registry_add_func(reg, rf);
3868+
}
3869+
37483870
static void flatten_trait_into_class(PHPLSPContext *ctx, CBMTypeRegistry *reg, const char *class_qn,
37493871
const char *trait_qn, const char *alias_for_method,
37503872
const char *only_method_name) {
@@ -3780,43 +3902,36 @@ static void flatten_trait_into_class(PHPLSPContext *ctx, CBMTypeRegistry *reg, c
37803902
* appends to reg->funcs, so the loop must never visit entries it adds
37813903
* during iteration (a mutate-while-iterating hazard). */
37823904
const int func_count_before = reg->func_count;
3905+
struct php_trait_index *ix = ctx->trait_index;
3906+
if (ix && php_trait_index_sync(ctx, ix, reg)) {
3907+
/* Only the trait's own methods, in registration order; the ids are
3908+
* ascending, so the snapshot bound ends the walk. No sync runs inside
3909+
* the loop, so the list cannot change under it. */
3910+
const php_func_ids_t *ids =
3911+
(const php_func_ids_t *)cbm_ht_get(ix->by_receiver, canonical_trait_qn);
3912+
for (int j = 0; ids && j < ids->count && ids->items[j] < func_count_before; j++) {
3913+
CBM_LSP_WORK(1);
3914+
if (CBM_LSP_WORK_CEILING_HIT()) {
3915+
break; /* test seam only (#765, #1265): see lsp_work.h */
3916+
}
3917+
flatten_trait_method(ctx, reg, class_qn, canonical_trait_qn, &reg->funcs[ids->items[j]],
3918+
alias_for_method, only_method_name);
3919+
}
3920+
return;
3921+
}
3922+
/* No index (no owning pass, or it could not allocate): the full scan,
3923+
* which yields the same methods in the same order. */
37833924
for (int i = 0; i < func_count_before; i++) {
3925+
CBM_LSP_WORK(1);
3926+
if (CBM_LSP_WORK_CEILING_HIT()) {
3927+
break; /* test seam only (#765, #1265): see lsp_work.h */
3928+
}
37843929
const CBMRegisteredFunc *src = &reg->funcs[i];
37853930
if (!src->receiver_type || strcmp(src->receiver_type, canonical_trait_qn) != 0) {
37863931
continue;
37873932
}
3788-
if (only_method_name && src->short_name && strcmp(src->short_name, only_method_name) != 0) {
3789-
continue;
3790-
}
3791-
const char *new_short = alias_for_method ? alias_for_method : src->short_name;
3792-
if (!new_short)
3793-
continue;
3794-
CBMRegisteredFunc rf;
3795-
memset(&rf, 0, sizeof(rf));
3796-
rf.qualified_name = cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, new_short);
3797-
rf.short_name = cbm_arena_strdup(ctx->arena, new_short);
3798-
rf.receiver_type = class_qn;
3799-
rf.min_params = src->min_params;
3800-
3801-
/* Self-substitute the return type: any NAMED(trait_qn) in the
3802-
* signature's return becomes NAMED(class_qn). */
3803-
const CBMType *new_sig = src->signature;
3804-
if (src->signature && src->signature->kind == CBM_TYPE_FUNC &&
3805-
src->signature->data.func.return_types) {
3806-
const CBMType *ret0 = src->signature->data.func.return_types[0];
3807-
if (ret0 && ret0->kind == CBM_TYPE_NAMED && ret0->data.named.qualified_name &&
3808-
strcmp(ret0->data.named.qualified_name, canonical_trait_qn) == 0) {
3809-
const CBMType **rets =
3810-
(const CBMType **)cbm_arena_alloc(ctx->arena, 2 * sizeof(*rets));
3811-
if (rets) {
3812-
rets[0] = cbm_type_named(ctx->arena, class_qn);
3813-
rets[1] = NULL;
3814-
new_sig = cbm_type_func_replace_returns(ctx->arena, src->signature, rets);
3815-
}
3816-
}
3817-
}
3818-
rf.signature = new_sig;
3819-
cbm_registry_add_func(reg, rf);
3933+
flatten_trait_method(ctx, reg, class_qn, canonical_trait_qn, src, alias_for_method,
3934+
only_method_name);
38203935
}
38213936
}
38223937

@@ -4217,6 +4332,16 @@ static void php_lsp_collect_class_fields(PHPLSPContext *ctx, CBMTypeRegistry *re
42174332
* Pass 2: classes and enums (which may `use Trait;` and need the
42184333
* trait's signatures already patched).
42194334
*/
4335+
/* The index lives in the call's arena, not on this stack frame: ctx keeps
4336+
* a pointer to it for the duration of the pass. On an allocation failure
4337+
* it stays NULL and flatten_trait_into_class runs the full scan. */
4338+
struct php_trait_index *trait_index =
4339+
(struct php_trait_index *)cbm_arena_alloc(ctx->arena, sizeof(*trait_index));
4340+
if (trait_index) {
4341+
memset(trait_index, 0, sizeof(*trait_index));
4342+
}
4343+
struct php_trait_index *outer_index = ctx->trait_index;
4344+
ctx->trait_index = trait_index;
42204345
for (int pass = 0; pass < 2; pass++) {
42214346
TSNode stack[256];
42224347
int top = 0;
@@ -4241,6 +4366,10 @@ static void php_lsp_collect_class_fields(PHPLSPContext *ctx, CBMTypeRegistry *re
42414366
}
42424367
}
42434368
}
4369+
if (trait_index) {
4370+
php_trait_index_free(trait_index);
4371+
}
4372+
ctx->trait_index = outer_index;
42444373
}
42454374

42464375
void cbm_php_refine_lsp_registry(PHPLSPContext *ctx, CBMTypeRegistry *reg, TSNode root) {

‎internal/cbm/lsp/php_lsp.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,11 @@ typedef struct {
7171
* Zero via memset. */
7272
int walk_depth;
7373

74+
/* Receiver -> registered-method index used while traits are flattened
75+
* (php_lsp.c, php_trait_index_t). Owned by the class-field pass, NULL
76+
* outside it. Zero via memset. */
77+
struct php_trait_index *trait_index;
78+
7479
/* Debug mode (CBM_LSP_DEBUG env). */
7580
bool debug;
7681
} PHPLSPContext;

‎tests/test_php_lsp.c‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,125 @@ static uint64_t phplsp_counted_work(const char *src, int *ceiling_hit, CBMFileRe
653653
return work;
654654
}
655655

656+
/* Every reported collision shape, in one file: #765's aliased import that
657+
* shares the trait's name, the v0.9.0 variant where the alias TARGET's short
658+
* name equals the local trait (owen-it/laravel-auditing wrapper), #951's
659+
* class named like its aliased trait, a self-using trait and a mutual pair. A
660+
* model using the wrapper trait still sees the flattened method. */
661+
TEST(phplsp_trait_collision_shapes_bounded_work_issue765) {
662+
const char *src = "<?php\n"
663+
"namespace App\\Models\\Traits;\n"
664+
"\n"
665+
"use OwenIt\\Auditing\\Auditable as AuditableBase;\n"
666+
"use App\\Functions\\Delivery as Delivery_Trait;\n"
667+
"\n"
668+
"trait Auditable {\n"
669+
" use AuditableBase;\n"
670+
" public function auditTag(): string { $x = 'a'; return $x; }\n"
671+
"}\n"
672+
"trait Selfish {\n"
673+
" use Selfish;\n"
674+
" public function me(): int { return 1; }\n"
675+
"}\n"
676+
"trait Ping {\n"
677+
" use Pong;\n"
678+
" public function ping(): int { return 1; }\n"
679+
"}\n"
680+
"trait Pong {\n"
681+
" use Ping;\n"
682+
" public function pong(): int { return 2; }\n"
683+
"}\n"
684+
"class Delivery {\n"
685+
" use Delivery_Trait;\n"
686+
" public function run(): void { }\n"
687+
"}\n"
688+
"class User {\n"
689+
" use Auditable, Ping;\n"
690+
" public function label(): string { return $this->auditTag(); }\n"
691+
" public function both(): int { return $this->ping() + $this->pong(); }\n"
692+
"}\n";
693+
int hit = 0;
694+
CBMFileResult *r = NULL;
695+
uint64_t work = phplsp_counted_work(src, &hit, &r);
696+
printf(" collision shapes: work=%llu\n", (unsigned long long)work);
697+
ASSERT_NOT_NULL(r);
698+
ASSERT_FALSE(hit);
699+
/* The flattened trait method is still found through the using class. */
700+
ASSERT(find_resolved(r, "label", "auditTag") >= 0);
701+
cbm_free_result(r);
702+
PASS();
703+
}
704+
705+
/* n classes in one file, each composing the same two traits, and one probe
706+
* class calling a flattened method through $this. */
707+
static char *phplsp_trait_users_source(int n) {
708+
size_t sz = (size_t)n * 256 + 1024;
709+
char *src = malloc(sz);
710+
if (!src) {
711+
return NULL;
712+
}
713+
size_t pos = (size_t)snprintf(src, sz,
714+
"<?php\nnamespace App\\Bulk;\n\n"
715+
"trait Stamps {\n"
716+
" public function stamp(): int { return 1; }\n"
717+
" public function touch(): int { return 2; }\n"
718+
" public function fresh(): int { return 3; }\n"
719+
"}\n"
720+
"trait Flags {\n"
721+
" use Stamps;\n"
722+
" public function flag(): int { return 4; }\n"
723+
"}\n");
724+
for (int i = 0; i < n; i++) {
725+
pos += (size_t)snprintf(src + pos, sz - pos,
726+
"class M%d {\n"
727+
" use Flags;\n"
728+
" public function own%d(): int { return %d; }\n"
729+
"}\n",
730+
i, i, i);
731+
}
732+
/* One call through a flattened method, so the lookup cost stays constant
733+
* and the gate measures flattening (F12: the single-file registry is not
734+
* finalized, so every lookup is a linear scan; that is its own defect). */
735+
snprintf(src + pos, sz - pos,
736+
"class Probe {\n"
737+
" use Flags;\n"
738+
" public function probe(): int { return $this->stamp(); }\n"
739+
"}\n");
740+
return src;
741+
}
742+
743+
/* Deterministic complexity gate: twice the trait-using classes must cost about
744+
* twice the counted work. Each flatten visits the registry; if that visit grows
745+
* with the classes already flattened, the ratio drifts toward 4 (main before the
746+
* per-trait method index: 3.22 at 150 -> 300). Both sizes stay below the 256
747+
* top-level declarations the class-field walk visits (#2388), so every class
748+
* is flattened. */
749+
TEST(phplsp_trait_flatten_work_is_linear_issue1265) {
750+
enum { N1 = 100, N2 = 200 };
751+
char *s1 = phplsp_trait_users_source(N1);
752+
char *s2 = phplsp_trait_users_source(N2);
753+
ASSERT_NOT_NULL(s1);
754+
ASSERT_NOT_NULL(s2);
755+
int hit1 = 0;
756+
int hit2 = 0;
757+
CBMFileResult *r2 = NULL;
758+
uint64_t w1 = phplsp_counted_work(s1, &hit1, NULL);
759+
uint64_t w2 = phplsp_counted_work(s2, &hit2, &r2);
760+
free(s1);
761+
free(s2);
762+
printf(" trait users %d -> %d: work %llu -> %llu (ratio %.2f)\n", N1, N2,
763+
(unsigned long long)w1, (unsigned long long)w2, w1 ? (double)w2 / (double)w1 : 0.0);
764+
ASSERT_NOT_NULL(r2);
765+
ASSERT_FALSE(hit1);
766+
ASSERT_FALSE(hit2);
767+
ASSERT(w1 > 0);
768+
/* The flattened method still resolves through the probe class. */
769+
ASSERT(find_resolved(r2, "Probe.probe", "stamp") >= 0);
770+
cbm_free_result(r2);
771+
ASSERT(w2 * 10 <= w1 * 25); /* ratio <= 2.5 */
772+
PASS();
773+
}
774+
656775
/* F12: the single-file PHP LSP (cbm_run_php_lsp) never indexed its registry,
657776
* so every type and method lookup was a linear scan over the stdlib plus every
658777
* definition of the file. Each class here looks up the previous class and its
@@ -5747,6 +5866,8 @@ SUITE(php_lsp) {
57475866
RUN_TEST(phplsp_trait_self_use_terminates);
57485867
RUN_TEST(phplsp_trait_aliased_import_name_collision_terminates);
57495868
RUN_TEST(phplsp_class_aliased_trait_name_collision_terminates);
5869+
RUN_TEST(phplsp_trait_collision_shapes_bounded_work_issue765);
5870+
RUN_TEST(phplsp_trait_flatten_work_is_linear_issue1265);
57505871
RUN_TEST(phplsp_single_file_lookup_work_is_linear_f12);
57515872
RUN_TEST(phplsp_match_result_type);
57525873
RUN_TEST(phplsp_ternary_result_type);

0 commit comments

Comments
 (0)