From ab2ecb34a4801fb586d6d502a212ecb13d114652 Mon Sep 17 00:00:00 2001 From: Tomas Votruba Date: Sun, 15 Nov 2026 23:47:50 +0100 Subject: [PATCH] Skip parameters with an unresolved argument or a conflicting @param doc type A single literal call site typed the parameter even when other call sites pass values argtyper cannot resolve, e.g. setCookie($name, '') next to setCookie('id', $lead->getId()) typed $value as string. An existing @param doc type naming a union or another type is now respected too. --- internal/aggregate/aggregate.go | 16 +++++- internal/aggregate/aggregate_test.go | 5 +- internal/apply/apply.go | 86 +++++++++++++++++++++++++++- internal/apply/apply_test.go | 45 ++++++++++++++- internal/phpast/phpast.go | 69 ++++++++++++++++++++++ 5 files changed, 213 insertions(+), 8 deletions(-) diff --git a/internal/aggregate/aggregate.go b/internal/aggregate/aggregate.go index f553da73..3db7b2a6 100644 --- a/internal/aggregate/aggregate.go +++ b/internal/aggregate/aggregate.go @@ -14,7 +14,8 @@ 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. +// types observed for the same parameter are ambiguous and left unresolved, as is +// a parameter with any argument whose type could not be resolved. type Resolved struct { Types []valuetype.Type // exactly one type, never Null Nullable bool @@ -33,6 +34,9 @@ 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 + unresolved bool } // Types holds resolved parameter types keyed for fast lookup during apply. @@ -55,7 +59,8 @@ 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 are skipped. +// type, with null captured as nullability. Unions and parameters with an +// unresolved argument are skipped. func Resolve(records []collect.Record) Types { methodTypes := map[string]*group{} functionTypes := map[string]*group{} @@ -80,6 +85,12 @@ 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) @@ -130,6 +141,7 @@ func addRecord(groups map[string]*group, key string, record collect.Record) { switch { case record.Type == valuetype.Unknown: groups[key].nonLiterals = true + groups[key].unresolved = true case record.IsLiteral: groups[key].types[record.Type] = struct{}{} groups[key].literals[record.Literal] = struct{}{} diff --git a/internal/aggregate/aggregate_test.go b/internal/aggregate/aggregate_test.go index dcbf1d7a..127aa2df 100644 --- a/internal/aggregate/aggregate_test.go +++ b/internal/aggregate/aggregate_test.go @@ -51,13 +51,12 @@ func TestResolveMethod(t *testing.T) { wantFound: false, }, { - name: "unresolved argument keeps the resolved type", + name: "unresolved argument is skipped", records: []collect.Record{ {Class: "A", Name: "m", Type: "int"}, {Class: "A", Name: "m"}, }, - wantType: "int", - wantFound: true, + wantFound: false, }, { name: "class name differing in case shares the key", diff --git a/internal/apply/apply.go b/internal/apply/apply.go index 9912241e..a40eed6f 100644 --- a/internal/apply/apply.go +++ b/internal/apply/apply.go @@ -4,6 +4,7 @@ package apply import ( "slices" + "strconv" "strings" "github.com/rectorphp/argtyper/internal/aggregate" @@ -138,6 +139,9 @@ func (a *applier) applyParams(node ast.Vertex, params []ast.Vertex, lookup func( continue } if resolved, ok := lookup(position); ok { + if !docAllows(node, param, resolved) { + continue + } docType := literalDocType(param, resolved) if !a.options.allows(resolved, docType) { continue @@ -149,7 +153,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, "") { + if resolved, ok := a.defaultType(param, enclosingFQCN); ok && a.options.allows(resolved, "") && docAllows(node, param, resolved) { added[phpast.VariableName(param.Var)] = a.setType(param, resolved) } } @@ -310,6 +314,86 @@ func takeVarLeading(param *ast.Parameter) []*token.Token { return leading } +// docPseudoTypes maps doc-only types onto the native type they narrow. +var docPseudoTypes = map[string]string{ + "integer": "int", + "positive-int": "int", + "negative-int": "int", + "non-positive-int": "int", + "non-negative-int": "int", + "non-zero-int": "int", + "double": "float", + "boolean": "bool", + "true": "bool", + "false": "bool", + "non-empty-string": "string", + "non-falsy-string": "string", + "truthy-string": "string", + "numeric-string": "string", + "literal-string": "string", + "lowercase-string": "string", + "uppercase-string": "string", + "class-string": "string", + "interface-string": "string", + "trait-string": "string", + "enum-string": "string", + "list": "array", + "non-empty-list": "array", + "non-empty-array": "array", +} + +// docAllows reports whether an existing `@param` doc type agrees with the +// resolved type. A doc type naming another type, or a union, says the parameter +// takes more than the call sites show, so it is left untyped. No doc tag, or +// `mixed`, carries no such information. +func docAllows(node ast.Vertex, param *ast.Parameter, resolved aggregate.Resolved) bool { + docType, ok := phpast.DocParamType(node, phpast.VariableName(param.Var)) + if !ok { + return true + } + want := docTypeBase(typeText(resolved.Types[0])) + for _, member := range phpast.SplitDocUnion(strings.TrimPrefix(strings.TrimSpace(docType), "?")) { + base := docTypeBase(member) + if base == "mixed" { + return true + } + if base != "null" && base != want { + return false + } + } + return true +} + +// 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, +// and class names to their lowercased short name. +func docTypeBase(member string) string { + member = strings.TrimSpace(member) + if index := strings.IndexAny(member, "<{("); index >= 0 { + member = member[:index] + } + if member == "" { + return "" + } + if member[0] == '\'' || member[0] == '"' { + return "string" + } + if _, err := strconv.ParseInt(member, 10, 64); err == nil { + return "int" + } + if _, err := strconv.ParseFloat(member, 64); err == nil { + return "float" + } + if index := strings.LastIndex(member, "\\"); index >= 0 { + member = member[index+1:] + } + member = strings.ToLower(member) + if native, ok := docPseudoTypes[member]; ok { + return native + } + return member +} + // typeText turns a resolved type into the text written into source. The trailing // space that separates the type from the variable is added by the caller. func typeText(resolved valuetype.Type) string { diff --git a/internal/apply/apply_test.go b/internal/apply/apply_test.go index c22c468b..8684bbb4 100644 --- a/internal/apply/apply_test.go +++ b/internal/apply/apply_test.go @@ -129,6 +129,47 @@ func TestApply(t *testing.T) { target: "set(\"x\"); }\n}", want: "set(\"x\"); }\n}", }, + { + name: "skips type when the param doc is a union", + target: "set(\"x\"); }\n}", + want: "set(\"x\"); }\n}", + }, + { + name: "skips type when the param doc names another type", + target: "set(\"x\"); }\n}", + want: "set(\"x\"); }\n}", + }, + { + name: "skips default type when the param doc is a union", + target: "set(1); }\n}", + want: "set(1); }\n}", + }, + { + name: "types when the param doc narrows the same type", + target: " $items\n * @param non-empty-string $name\n */\nfunction take($items, $name) {}", + callers: []string{ + " $items\n * @param non-empty-string $name\n */\nfunction take(array $items, string $name) {}", + }, + { + name: "types when the param doc is the same class", + target: "set(new Foo()); }\n}", + want: "set(new Foo()); }\n}", + }, + { + name: "skips type when a property-call site passes an unresolved value", + target: "setCookie('a', ''); }\n}", + callers: []string{ + "cookieHelper->setCookie('mtc_id', $lead->getId()); }\n}", + }, + want: "setCookie('a', ''); }\n}", + }, { name: "skips multiple observed types", target: "set(1); $this->set(\"x\"); }\n}", @@ -399,12 +440,12 @@ func TestApply(t *testing.T) { want: "` or `int|null`. +func DocParamType(node ast.Vertex, name string) (string, bool) { + leading := leadingToken(node) + if leading == nil { + return "", false + } + for _, free := range leading.FreeFloating { + if free.ID != token.T_DOC_COMMENT { + continue + } + for line := range strings.SplitSeq(string(free.Value), "\n") { + rest, ok := afterParamTag(line) + if !ok { + continue + } + docType, variable := splitDocType(strings.TrimSpace(rest)) + if strings.TrimPrefix(variable, "...") == "$"+name { + return docType, true + } + } + } + return "", false +} + +// splitDocType splits ` $name ...` into the type and the word after it, +// keeping spaces inside generics and shapes like `array`. +func splitDocType(text string) (string, string) { + depth := 0 + for i, char := range text { + switch char { + case '<', '{', '(': + depth++ + case '>', '}', ')': + depth-- + case ' ', '\t': + if depth == 0 { + fields := strings.Fields(text[i:]) + if len(fields) == 0 { + return text[:i], "" + } + return text[:i], fields[0] + } + } + } + return text, "" +} + +// SplitDocUnion splits a doc type into its top-level union members, leaving +// `|` inside generics and shapes alone. +func SplitDocUnion(docType string) []string { + var members []string + depth, start := 0, 0 + for i, char := range docType { + switch char { + case '<', '{', '(': + depth++ + case '>', '}', ')': + depth-- + case '|': + if depth == 0 { + members = append(members, docType[start:i]) + start = i + 1 + } + } + } + return append(members, docType[start:]) +}