From 70a61574240543277652e1b7a85c218580da3c15 Mon Sep 17 00:00:00 2001 From: Tomas Votruba Date: Sun, 15 Nov 2026 20:48:54 +0100 Subject: [PATCH] Skip parameters with unresolved, test-only or conflicting evidence; nullable entity setters Typing from literal call sites alone broke Mautic at runtime: variables passed null, the DI container and forms called methods argtyper never saw, and child classes overrode the newly typed methods. - an unresolved argument (a variable) blocks the parameter - calls on an unresolved receiver count by method name and must agree - a call on a child class counts for the parent method it inherits - call sites only in tests do not add a type - a default value of another type blocks the parameter - a wider @param doc type, instanceof or === false in the body block it - trait methods count as ancestors, and methods a child class, anonymous class or implementation overrides are skipped - setters of Doctrine entities always get a nullable type --- CLAUDE.md | 26 ++++-- internal/aggregate/aggregate.go | 47 ++++++---- internal/aggregate/aggregate_test.go | 41 ++++++--- internal/apply/apply.go | 117 ++++++++++++++++++++---- internal/apply/apply_test.go | 95 ++++++++++++++++++++ internal/collect/collect.go | 13 ++- internal/collect/collect_test.go | 24 +++-- internal/finder/finder.go | 11 +++ internal/finder/finder_test.go | 15 ++++ internal/inherit/inherit.go | 128 ++++++++++++++++++++++++--- internal/inherit/inherit_test.go | 28 ++++++ internal/phpast/entity.go | 34 +++++++ main.go | 17 +++- 13 files changed, 513 insertions(+), 83 deletions(-) create mode 100644 internal/phpast/entity.go diff --git a/CLAUDE.md b/CLAUDE.md index 8afebc2d..78327787 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -23,9 +23,17 @@ The run in `main.go` is a three-stage pipeline over the project's PHP files: reprint the file, leaving untouched code byte-for-byte. Skip rules: parameters that already have a type; parameters with conflicting -types (ambiguous); parameters passed into a type check like `is_array($param)` -or `gettype($param)` in the body, as they accept more than one type; magic methods except `__construct`; methods that may override -a parent or interface (including vendor), unless private or a constructor. +types (ambiguous) or any unresolved argument (a variable); parameters seen only +from call sites in tests; a default value of another type; a wider `@param` doc +type; parameters type checked in the body (`is_array($param)`, `gettype()`, +`instanceof`, `=== false`), as they accept more than one type; magic methods +except `__construct`; methods that may override a parent, interface or trait +(including vendor), or that a child class overrides, unless private or a +constructor. + +Setters (`set*`) of Doctrine entities, marked by `#[ORM\Entity]` or +`@ORM\Entity`, always get a nullable type, since forms and hydrators may pass +null. ## Packages (`internal/`) @@ -80,9 +88,15 @@ Run the same command locally before pushing. `valuetype.Object(fqcn)` checked with `IsObject()` and read with `Class()`. `Null` becomes nullability, `Callable` (from a closure argument) poisons the parameter so it is never typed. `apply.typeText` turns an object into `\X`. -- **Unresolved arguments** produce a record with an empty `Type`. It never adds - a type, but marks the group as not fully literal, which blocks the - `'a'|'b'` docblock (`aggregate.group.nonLiterals`). +- **Unresolved arguments** produce a record with an empty `Type`. It blocks + the parameter: `aggregate.Types` returns it found with no `Types`, so apply + skips it and does not fall back to the default value type either. +- **Unresolved receivers** (`$x->m(1)`, `parent::m(1)`) record by method name + only (empty `Class`). `aggregate.Types.Method` requires them to agree with + the class type, else the parameter is blocked. +- **Inherited calls** - `main.go` rewrites a record's class to the class that + declares the method (`inherit.DeclaringClass`), so `$this->m()` in a child + counts for the parent method. - **Lookup keys use fully qualified, lowercased class names** (`app\entity\foo`, via `phpast.ClassKey`): `collect` records carry the fully qualified name, and `aggregate.Types` keys, `symbols` enums/class consts and diff --git a/internal/aggregate/aggregate.go b/internal/aggregate/aggregate.go index c55fefd7..a5237939 100644 --- a/internal/aggregate/aggregate.go +++ b/internal/aggregate/aggregate.go @@ -14,10 +14,10 @@ import ( ) // Resolved is the final type decision for one parameter position. Two or more -// types observed for the same parameter are ambiguous and left unresolved, as is -// a parameter with any argument whose type could not be resolved. +// types, a callable or an unresolved argument leave Types empty: the parameter +// was seen at a call site but must stay untyped. type Resolved struct { - Types []valuetype.Type // exactly one type, never Null + Types []valuetype.Type // exactly one type, never Null; empty when blocked Nullable bool Literals []string // sorted string literal values, set only for a plain string type, see literalValues } @@ -34,9 +34,12 @@ type group struct { // set when a string other than a plain literal, or an unresolved value, was // passed - the literals then no longer cover every argument nonLiterals bool - // set when an argument type could not be resolved - it may be any type, so - // the parameter is left untyped + // set when an argument type could not be resolved, e.g. a variable - it may + // be anything, so the parameter must stay untyped unresolved bool + // set when a call site lies outside tests; tests pass fixture values while + // production may call through a container, form or hydrator instead + production bool } // Types holds resolved parameter types keyed for fast lookup during apply. @@ -46,10 +49,19 @@ type Types struct { functions map[string]Resolved // function \x00 position } -// Method returns the resolved type for a method/constructor parameter. +// Method returns the resolved type for a method/constructor parameter. Calls on +// an unresolved receiver, recorded by method name only, may target this method +// too, so they must agree with its type, else the parameter is blocked. func (t Types) Method(class, method string, position int) (Resolved, bool) { resolved, ok := t.methods[methodKey(class, method, position)] - return resolved, ok + byName, byNameOK := t.methods[methodKey("", method, position)] + if !byNameOK { + return resolved, ok + } + if !ok || len(resolved.Types) == 0 || len(byName.Types) == 0 || resolved.Types[0] != byName.Types[0] { + return Resolved{}, true + } + return Resolved{Types: resolved.Types, Nullable: resolved.Nullable || byName.Nullable}, true } // Function returns the resolved type for a function parameter. @@ -60,7 +72,7 @@ func (t Types) Function(name string, position int) (Resolved, bool) { // Resolve groups records per parameter into a resolved type: a single observed // type, with null captured as nullability. Unions and parameters with an -// unresolved argument are skipped. +// unresolved argument are blocked. func Resolve(records []collect.Record) Types { methodTypes := map[string]*group{} functionTypes := map[string]*group{} @@ -85,12 +97,6 @@ func resolveGroups(groups map[string]*group) map[string]Resolved { resolved := map[string]Resolved{} for key, group := range groups { - // an unresolved argument may pass any type, narrowing to the literal - // ones seen elsewhere would break that call site - if group.unresolved { - continue - } - types := make([]valuetype.Type, 0, len(group.types)) for typeName := range group.types { types = append(types, typeName) @@ -98,15 +104,18 @@ func resolveGroups(groups map[string]*group) map[string]Resolved { slices.Sort(types) types = dedupeClasses(types) - // a callable argument (a closure) leaves the parameter untyped, since a - // callable can take many shapes that must not be narrowed - if contains(types, valuetype.Callable) { + // an unresolved argument may be anything, a parameter seen only from + // tests may get other values in production, and a callable argument (a + // closure) can take many shapes - all leave the parameter untyped + if group.unresolved || !group.production || contains(types, valuetype.Callable) { + resolved[key] = Resolved{} continue } // a DateTime argument leaves the parameter untyped, as it often accepts a // string or any DateTimeInterface too if slices.ContainsFunc(types, isDateTime) { + resolved[key] = Resolved{} continue } @@ -114,6 +123,7 @@ func resolveGroups(groups map[string]*group) map[string]Resolved { members := without(types, valuetype.Null) // only a single type is added, unions are left untyped if len(members) != 1 { + resolved[key] = Resolved{} continue } resolved[key] = Resolved{Types: members, Nullable: nullable, Literals: literalValues(members, group)} @@ -144,6 +154,9 @@ func addRecord(groups map[string]*group, key string, record collect.Record) { if groups[key] == nil { groups[key] = &group{types: map[valuetype.Type]struct{}{}, literals: map[string]struct{}{}} } + if !record.InTest { + groups[key].production = true + } switch { case record.Type == valuetype.Unknown: groups[key].nonLiterals = true diff --git a/internal/aggregate/aggregate_test.go b/internal/aggregate/aggregate_test.go index 2a384d59..bf6e7b17 100644 --- a/internal/aggregate/aggregate_test.go +++ b/internal/aggregate/aggregate_test.go @@ -15,7 +15,7 @@ func TestResolveMethod(t *testing.T) { records []collect.Record wantType string // members joined by "|" wantNullable bool - wantFound bool + wantFound bool // found with an empty wantType means blocked }{ { name: "single type", @@ -39,7 +39,7 @@ func TestResolveMethod(t *testing.T) { {Class: "A", Name: "m", Type: "int"}, {Class: "A", Name: "m", Type: "string"}, }, - wantFound: false, + wantFound: true, }, { name: "two real types with null are skipped", @@ -48,15 +48,15 @@ func TestResolveMethod(t *testing.T) { {Class: "A", Name: "m", Type: "string"}, {Class: "A", Name: "m", Type: "null"}, }, - wantFound: false, + wantFound: true, }, { - name: "unresolved argument is skipped", + name: "unresolved argument blocks the type", records: []collect.Record{ {Class: "A", Name: "m", Type: "int"}, {Class: "A", Name: "m"}, }, - wantFound: false, + wantFound: true, }, { name: "class name differing in case shares the key", @@ -74,27 +74,42 @@ func TestResolveMethod(t *testing.T) { wantFound: true, }, { - name: "DateTime is skipped", + name: "DateTime blocks the type", records: []collect.Record{{Class: "A", Name: "m", Type: valuetype.Object("DateTime")}}, - wantFound: false, + wantFound: true, }, { - name: "DateTimeImmutable with null is skipped", + name: "DateTimeImmutable with null blocks the type", records: []collect.Record{ {Class: "A", Name: "m", Type: valuetype.Object("DateTimeImmutable")}, {Class: "A", Name: "m", Type: "null"}, }, - wantFound: false, + wantFound: true, }, { - name: "only unresolved resolves to nothing", + name: "only unresolved blocks the type", records: []collect.Record{{Class: "A", Name: "m"}}, - wantFound: false, + wantFound: true, + }, + { + name: "only test call sites block the type", + records: []collect.Record{{Class: "A", Name: "m", Type: "int", InTest: true}}, + wantFound: true, }, { - name: "only null resolves to nothing", + name: "test call site adds to a production one", + records: []collect.Record{ + {Class: "A", Name: "m", Type: "int"}, + {Class: "A", Name: "m", Type: "null", InTest: true}, + }, + wantType: "int", + wantNullable: true, + wantFound: true, + }, + { + name: "only null blocks the type", records: []collect.Record{{Class: "A", Name: "m", Type: "null"}}, - wantFound: false, + wantFound: true, }, } diff --git a/internal/apply/apply.go b/internal/apply/apply.go index a40eed6f..27cf98fb 100644 --- a/internal/apply/apply.go +++ b/internal/apply/apply.go @@ -84,7 +84,7 @@ func (a *applier) walk(node ast.Vertex, class ast.Vertex) { } switch typed := node.(type) { - case *ast.StmtClass, *ast.StmtEnum, *ast.StmtTrait: + case *ast.StmtClass, *ast.StmtEnum, *ast.StmtTrait, *ast.StmtInterface: class = typed case *ast.StmtFunction: a.applyFunction(typed) @@ -102,7 +102,7 @@ func (a *applier) applyFunction(function *ast.StmtFunction) { lookup := func(position int) (aggregate.Resolved, bool) { return a.types.Function(name, position) } - a.applyParams(function, function.Params, lookup, "") + a.applyParams(function, function.Params, lookup, "", false) } func (a *applier) applyMethod(method *ast.StmtClassMethod, class ast.Vertex) { @@ -122,13 +122,14 @@ func (a *applier) applyMethod(method *ast.StmtClassMethod, class ast.Vertex) { lookup := func(position int) (aggregate.Resolved, bool) { return a.types.Method(classFQCN, name, position) } - a.applyParams(method, method.Params, lookup, classFQCN) + a.applyParams(method, method.Params, lookup, classFQCN, isEntitySetter(name, class)) } // applyParams types the params of a function or method node: from the call-site // type found by lookup, else from a literal default value. enclosingFQCN names -// the class, empty for a plain function. -func (a *applier) applyParams(node ast.Vertex, params []ast.Vertex, lookup func(position int) (aggregate.Resolved, bool), enclosingFQCN string) { +// the class, empty for a plain function. nullable makes every added type +// nullable. +func (a *applier) applyParams(node ast.Vertex, params []ast.Vertex, lookup func(position int) (aggregate.Resolved, bool), enclosingFQCN string, nullable bool) { added := map[string]string{} docs := map[string]string{} var order []string @@ -139,6 +140,12 @@ func (a *applier) applyParams(node ast.Vertex, params []ast.Vertex, lookup func( continue } if resolved, ok := lookup(position); ok { + // call sites passed mixed or unresolved values, or one that + // conflicts with the default value + if len(resolved.Types) == 0 || a.defaultConflicts(param, resolved, enclosingFQCN) { + continue + } + resolved.Nullable = resolved.Nullable || nullable if !docAllows(node, param, resolved) { continue } @@ -154,6 +161,7 @@ func (a *applier) applyParams(node ast.Vertex, params []ast.Vertex, lookup func( continue } if resolved, ok := a.defaultType(param, enclosingFQCN); ok && a.options.allows(resolved, "") && docAllows(node, param, resolved) { + resolved.Nullable = nullable added[phpast.VariableName(param.Var)] = a.setType(param, resolved) } } @@ -162,8 +170,9 @@ func (a *applier) applyParams(node ast.Vertex, params []ast.Vertex, lookup func( } // typeCheckFunctions inspect the type of a value at runtime. A parameter passed -// into one of them is expected to take more than one type, even when every -// resolved call site passes the same one. +// into one of them, checked with instanceof or compared to true or false, is +// expected to take more than one type, even when every resolved call site +// passes the same one. var typeCheckFunctions = map[string]bool{ "is_array": true, "is_bool": true, @@ -183,8 +192,9 @@ var typeCheckFunctions = map[string]bool{ "get_debug_type": true, } -// typeCheckedVariables returns the names of variables passed directly into a -// type check function anywhere in the node, e.g. `is_array($sendTo)`. +// typeCheckedVariables returns the names of variables type checked anywhere in +// the node, e.g. `is_array($sendTo)`, `$error instanceof Exception` or +// `false === $id`. func typeCheckedVariables(node ast.Vertex) map[string]bool { checked := map[string]bool{} var walk func(node ast.Vertex) @@ -192,14 +202,21 @@ func typeCheckedVariables(node ast.Vertex) map[string]bool { if node == nil { return } - if call, ok := node.(*ast.ExprFunctionCall); ok && typeCheckFunctions[strings.ToLower(phpast.ShortName(call.Function))] { - for _, argNode := range call.Args { - if arg, ok := argNode.(*ast.Argument); ok { - if name := phpast.VariableName(arg.Expr); name != "" { - checked[name] = true + switch typed := node.(type) { + case *ast.ExprFunctionCall: + if typeCheckFunctions[strings.ToLower(phpast.ShortName(typed.Function))] { + for _, argNode := range typed.Args { + if arg, ok := argNode.(*ast.Argument); ok { + markVariable(checked, arg.Expr) } } } + case *ast.ExprInstanceOf: + markVariable(checked, typed.Expr) + case *ast.ExprBinaryIdentical: + markBoolCompared(checked, typed.Left, typed.Right) + case *ast.ExprBinaryNotIdentical: + markBoolCompared(checked, typed.Left, typed.Right) } for _, child := range phpast.Children(node) { walk(child) @@ -209,6 +226,31 @@ func typeCheckedVariables(node ast.Vertex) map[string]bool { return checked } +func markVariable(checked map[string]bool, expr ast.Vertex) { + if name := phpast.VariableName(expr); name != "" { + checked[name] = true + } +} + +// markBoolCompared marks a variable compared to true or false, the other side. +func markBoolCompared(checked map[string]bool, left, right ast.Vertex) { + if isBoolLiteral(right) { + markVariable(checked, left) + } + if isBoolLiteral(left) { + markVariable(checked, right) + } +} + +func isBoolLiteral(node ast.Vertex) bool { + constFetch, ok := node.(*ast.ExprConstFetch) + if !ok { + return false + } + name := strings.ToLower(phpast.ShortName(constFetch.Const)) + return name == "true" || name == "false" +} + // defaultType infers a parameter type from its literal default value, so // `$page = 1` becomes `int $page = 1` even with no call site. A `null` default // carries no type of its own; enclosingFQCN resolves `self::` constants and @@ -229,6 +271,39 @@ func (a *applier) defaultType(param *ast.Parameter, enclosingFQCN string) (aggre return aggregate.Resolved{Types: []valuetype.Type{typeName}}, true } +// defaultConflicts reports whether a literal default value has another type than +// the call sites pass, e.g. `$code = '200'` with `int` from calls. An int +// default still fits a float type. +func (a *applier) defaultConflicts(param *ast.Parameter, resolved aggregate.Resolved, enclosingFQCN string) bool { + fromDefault, ok := a.defaultType(param, enclosingFQCN) + if !ok { + return false + } + defaultType, callType := fromDefault.Types[0], resolved.Types[0] + switch { + case defaultType == callType: + return false + case defaultType == valuetype.Int && callType == valuetype.Float: + return false + case defaultType.IsObject() && callType.IsObject(): + return phpast.ClassKey(defaultType.Class()) != phpast.ClassKey(callType.Class()) + } + return true +} + +// isEntitySetter reports whether a method is a setter of a Doctrine entity. +// Entity setters are also called by forms, serializers and hydrators, which may +// pass null, so their types are always nullable. +func isEntitySetter(method string, class ast.Vertex) bool { + if len(method) < 4 || !strings.EqualFold(method[:3], "set") { + return false + } + if next := method[3]; next < 'A' || next > 'Z' { + return false + } + return phpast.IsEntity(class) +} + // literalDocType returns a `'a'|'b'` doc type for a parameter that only ever // receives a few string literals. Empty when there are none, or when a default // value falls outside them. @@ -340,6 +415,7 @@ var docPseudoTypes = map[string]string{ "list": "array", "non-empty-list": "array", "non-empty-array": "array", + "callable-string": "string", } // docAllows reports whether an existing `@param` doc type agrees with the @@ -365,10 +441,13 @@ func docAllows(node ast.Vertex, param *ast.Parameter, resolved aggregate.Resolve } // docTypeBase reduces a single doc type to the native type it narrows: -// generics and shapes are cut, literals and pseudo types map to their scalar, +// generics and shapes are cut, `int[]` is an array, literals and pseudo types map to their scalar, // and class names to their lowercased short name. func docTypeBase(member string) string { member = strings.TrimSpace(member) + if strings.HasSuffix(member, "[]") { + return "array" + } if index := strings.IndexAny(member, "<{("); index >= 0 { member = member[:index] } @@ -410,8 +489,9 @@ func typeable(param *ast.Parameter) bool { } // methodTypeable reports whether typing this method is safe: it must not change -// the signature of a method inherited from an ancestor. Constructors and private -// methods never override, and a class or enum with no parent or interface has +// the signature of a method inherited from an ancestor, nor of one a child class +// overrides. Constructors and private methods never override, and a class or +// enum with no parent or interface has // nothing to override. Otherwise the inheritance table is consulted, and the // method is only typed when the whole ancestor chain is resolved and none of it // declares the method - an unresolved chain (an ancestor in /vendor the scan @@ -428,6 +508,9 @@ func (a *applier) methodTypeable(method *ast.StmtClassMethod, class ast.Vertex) } } } + if classFQCN := a.names[class]; classFQCN != "" && a.inheritance.OverriddenByChild(classFQCN, phpast.ShortName(method.Name)) { + return false + } switch typed := class.(type) { case nil: return true diff --git a/internal/apply/apply_test.go b/internal/apply/apply_test.go index 8684bbb4..01662a50 100644 --- a/internal/apply/apply_test.go +++ b/internal/apply/apply_test.go @@ -22,6 +22,11 @@ func run(target string, sources ...string) (string, int) { for _, source := range sources { records = append(records, collect.FromSource([]byte(source), table)...) } + for i, record := range records { + if !record.IsFunction && record.Class != "" { + records[i].Class = inheritance.DeclaringClass(record.Class, record.Name) + } + } types := aggregate.Resolve(records) output, added, _ := apply.Source([]byte(target), types, table, inheritance, apply.Options{}) return output, len(added) @@ -447,6 +452,96 @@ func TestApply(t *testing.T) { }, want: "save(1); $this->load(1); }\n}\nclass Child extends Base {\n public function save($v) {}\n}", + want: "save(1); $this->load(1); }\n}\nclass Child extends Base {\n public function save($v) {}\n}", + }, + { + name: "skips interface method an implementation overrides", + target: "save(1); }\n}\nnew class extends Base {\n public function save($v) {}\n};", + want: "save(1); }\n}\nnew class extends Base {\n public function save($v) {}\n};", + }, + { + name: "skips method a child class gets from a trait", + target: "save(1); }\n}\nclass Child extends Base {\n use Saves;\n}", + want: "save(1); }\n}\nclass Child extends Base {\n use Saves;\n}", + }, + { + name: "call on a child class counts for the parent method", + target: "property('label'); }\n}\nclass Child extends Base {\n public function run() { $this->property(5); }\n}", + want: "property('label'); }\n}\nclass Child extends Base {\n public function run() { $this->property(5); }\n}", + }, + { + name: "call on an unresolved receiver blocks a conflicting type", + target: "handle(new Fatal()); }\n}\nfunction run($handler) { $handler->handle(new Runtime()); }", + want: "handle(new Fatal()); }\n}\nfunction run($handler) { $handler->handle(new Runtime()); }", + }, + { + name: "call on an unresolved receiver adds null", + target: "put(1); }\n}\nfunction run($box) { $box->put(null); $box->put(2); }", + want: "put(1); }\n}\nfunction run($box) { $box->put(null); $box->put(2); }", + }, + { + name: "skips parameter checked with instanceof", + target: "|null $map\n */\nfunction load($map) {}\nload([]);", + want: "|null $map\n */\nfunction load(array $map) {}\nload([]);", + }, + { + name: "skips type when the default value conflicts with call sites", + target: "setTitle('Mr'); $this->rename('Mr'); }\n}", + want: "setTitle('Mr'); $this->rename('Mr'); }\n}", + }, + { + name: "adds nullable type to entity setter with annotation and default value", + target: "setTitle('Mr'); }\n}", + want: "setTitle('Mr'); }\n}", + }, { name: "same-named class in another namespace does not share types", target: "method()` call whose target // class and method name are statically known. +// recordMethodCall records a call by its receiver class; an unresolved receiver +// records by method name only, so the call still counts for every method of +// that name. func (c *collector) recordMethodCall(varNode, methodNode ast.Vertex, args []ast.Vertex, sc scope) { target := argClass(varNode, sc) - if target == "" { - return - } method, ok := methodNode.(*ast.Identifier) if !ok { return diff --git a/internal/collect/collect_test.go b/internal/collect/collect_test.go index 6512d676..6efbb30e 100644 --- a/internal/collect/collect_test.go +++ b/internal/collect/collect_test.go @@ -60,9 +60,9 @@ func TestFromSource(t *testing.T) { want: []collect.Record{{IsFunction: true, Name: "f", Position: 0}}, }, { - name: "skips method call on untyped variable", + name: "method call on untyped variable records by name only", src: "set(1); }\n}", - want: nil, + want: []collect.Record{{Name: "set", Position: 0, Type: "int"}}, }, { name: "typed parameter variable resolves target class", @@ -77,7 +77,7 @@ func TestFromSource(t *testing.T) { { name: "scalar typed parameter is not a call target", src: "set(1); }\n}", - want: nil, + want: []collect.Record{{Name: "set", Position: 0, Type: "int"}}, }, { name: "declared property resolves this-property call", @@ -115,12 +115,18 @@ func TestFromSource(t *testing.T) { { name: "method chain rooted at new resolves to receiver class", src: "set(new \\DateTime()->modify('+2 hours')); }\n}", - want: []collect.Record{{Class: "A", Name: "set", Position: 0, Type: valuetype.Object("DateTime")}}, + want: []collect.Record{ + {Class: "A", Name: "set", Position: 0, Type: valuetype.Object("DateTime")}, + {Name: "modify", Position: 0, Type: "string"}, + }, }, { name: "nullsafe method chain rooted at new resolves to receiver class", src: "set(new \\DateTime()?->modify('+2 hours')); }\n}", - want: []collect.Record{{Class: "A", Name: "set", Position: 0, Type: valuetype.Object("DateTime")}}, + want: []collect.Record{ + {Class: "A", Name: "set", Position: 0, Type: valuetype.Object("DateTime")}, + {Name: "modify", Position: 0, Type: "string"}, + }, }, { name: "coalesce contributes both sides", @@ -185,9 +191,9 @@ func TestFromSource(t *testing.T) { want: []collect.Record{{Class: "Lib\\Repo", Name: "find", Position: 0, Type: "int"}}, }, { - name: "skips parent static call", + name: "parent static call records by name only", src: " classes that extend, implement or use it } // New returns an empty table ready for CollectSource. @@ -56,13 +63,20 @@ func (t *Table) walk(node ast.Vertex, names map[ast.Vertex]string) { switch typed := node.(type) { case *ast.StmtClass: - t.add(names[typed], names[typed.Extends], typed.Implements, typed, names) + name := names[typed] + if typed.Name == nil { + // an anonymous class has no name, but may still override a method + name = fmt.Sprintf("class@anonymous%p", typed) + } + t.add(name, names[typed.Extends], typed.Implements, typed, names) case *ast.StmtInterface: // interface parents are declared with `extends`; treat them like // implemented interfaces so method lookups walk them too. t.add(names[typed], "", typed.Extends, typed, names) case *ast.StmtEnum: t.add(names[typed], "", typed.Implements, typed, names) + case *ast.StmtTrait: + t.add(names[typed], "", nil, typed, names) } for _, child := range phpast.Children(node) { @@ -82,10 +96,17 @@ func (t *Table) add(fqcn, parent string, interfaces []ast.Vertex, body ast.Verte } } for _, member := range phpast.Children(body) { - if method, ok := member.(*ast.StmtClassMethod); ok { - if name := phpast.ShortName(method.Name); name != "" { + switch typed := member.(type) { + case *ast.StmtClassMethod: + if name := phpast.ShortName(typed.Name); name != "" { entry.methods[strings.ToLower(name)] = true } + case *ast.StmtTraitUse: + for _, traitNode := range typed.Traits { + if name := names[traitNode]; name != "" { + entry.traits = append(entry.traits, phpast.ClassKey(name)) + } + } } } @@ -93,7 +114,7 @@ func (t *Table) add(fqcn, parent string, interfaces []ast.Vertex, body ast.Verte } // Overrides reports whether a method of the given class is also declared by an -// ancestor (a parent class or interface, transitively), and whether the whole +// ancestor (a parent class, interface or used trait, transitively), and whether the whole // ancestor chain was resolved. When resolved is false, an unknown ancestor - a // class the scan never saw, typically in /vendor - may still declare it, so the // caller should treat the method as unsafe to change. @@ -122,15 +143,98 @@ func (t *Table) Overrides(fqcn, method string) (overrides bool, resolved bool) { if ancestor.methods[method] { overrides = true } - visit(ancestor.parent) - for _, interfaceName := range ancestor.interfaces { - visit(interfaceName) - } + visitAncestors(ancestor, visit) } + visitAncestors(entry, visit) + return overrides, resolved +} + +func visitAncestors(entry *class, visit func(name string)) { visit(entry.parent) for _, interfaceName := range entry.interfaces { visit(interfaceName) } - return overrides, resolved + for _, traitName := range entry.traits { + visit(traitName) + } +} + +// OverriddenByChild reports whether a class that extends, implements or uses the +// given class, transitively, declares the method again. Typing the method would +// then change a signature the child relies on. +func (t *Table) OverriddenByChild(fqcn, method string) bool { + t.childrenOnce.Do(t.buildChildren) + method = strings.ToLower(method) + + seen := map[string]bool{} + var visit func(name string) bool + visit = func(name string) bool { + for _, childName := range t.children[name] { + if seen[childName] { + continue + } + seen[childName] = true + if t.declares(childName, method, map[string]bool{}) || visit(childName) { + return true + } + } + return false + } + return visit(phpast.ClassKey(fqcn)) +} + +// DeclaringClass returns the class that declares a method called on fqcn: fqcn +// itself, a used trait or the closest parent class. A call on a child class +// then counts for the method its parent declares. Unknown ones return fqcn. +func (t *Table) DeclaringClass(fqcn, method string) string { + method = strings.ToLower(method) + seen := map[string]bool{} + for name := phpast.ClassKey(fqcn); name != "" && !seen[name]; { + seen[name] = true + entry, ok := t.classes[name] + if !ok { + break + } + if entry.methods[method] { + return name + } + for _, traitName := range entry.traits { + if t.declares(traitName, method, map[string]bool{}) { + return traitName + } + } + name = entry.parent + } + return fqcn +} + +// declares reports whether a class or trait declares a method itself or through +// the traits it uses. +func (t *Table) declares(name, method string, seen map[string]bool) bool { + entry, ok := t.classes[name] + if !ok || seen[name] { + return false + } + seen[name] = true + if entry.methods[method] { + return true + } + for _, traitName := range entry.traits { + if t.declares(traitName, method, seen) { + return true + } + } + return false +} + +func (t *Table) buildChildren() { + t.children = map[string][]string{} + for name, entry := range t.classes { + visitAncestors(entry, func(ancestor string) { + if ancestor != "" { + t.children[ancestor] = append(t.children[ancestor], name) + } + }) + } } diff --git a/internal/inherit/inherit_test.go b/internal/inherit/inherit_test.go index 9fbe46ca..2b60c887 100644 --- a/internal/inherit/inherit_test.go +++ b/internal/inherit/inherit_test.go @@ -14,6 +14,7 @@ func TestOverrides(t *testing.T) { table.CollectSource([]byte("