Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions internal/aggregate/aggregate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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{}
Expand All @@ -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)
Expand Down Expand Up @@ -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{}{}
Expand Down
5 changes: 2 additions & 3 deletions internal/aggregate/aggregate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
86 changes: 85 additions & 1 deletion internal/apply/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package apply

import (
"slices"
"strconv"
"strings"

"github.com/rectorphp/argtyper/internal/aggregate"
Expand Down Expand Up @@ -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
Expand All @@ -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)
}
}
Expand Down Expand Up @@ -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 {
Expand Down
45 changes: 43 additions & 2 deletions internal/apply/apply_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,47 @@ func TestApply(t *testing.T) {
target: "<?php\nfinal class A {\n /**\n * @param string $v the value\n */\n public function set($v) {}\n public function go() { $this->set(\"x\"); }\n}",
want: "<?php\nfinal class A {\n /**\n * @param string $v the value\n */\n public function set(string $v) {}\n public function go() { $this->set(\"x\"); }\n}",
},
{
name: "skips type when the param doc is a union",
target: "<?php\nfinal class A {\n /**\n * @param int|string|null $v\n */\n public function set($v) {}\n public function go() { $this->set(\"x\"); }\n}",
want: "<?php\nfinal class A {\n /**\n * @param int|string|null $v\n */\n public function set($v) {}\n public function go() { $this->set(\"x\"); }\n}",
},
{
name: "skips type when the param doc names another type",
target: "<?php\nfinal class A {\n /**\n * @param array $v\n */\n public function set($v) {}\n public function go() { $this->set(\"x\"); }\n}",
want: "<?php\nfinal class A {\n /**\n * @param array $v\n */\n public function set($v) {}\n public function go() { $this->set(\"x\"); }\n}",
},
{
name: "skips default type when the param doc is a union",
target: "<?php\n/**\n * @param string|int $v\n */\nfunction take($v = '') {}",
want: "<?php\n/**\n * @param string|int $v\n */\nfunction take($v = '') {}",
},
{
name: "types when the param doc is the same type plus null",
target: "<?php\nfinal class A {\n /**\n * @param int|null $v the value\n */\n public function set($v) {}\n public function go() { $this->set(1); }\n}",
want: "<?php\nfinal class A {\n /**\n * @param int|null $v the value\n */\n public function set(int $v) {}\n public function go() { $this->set(1); }\n}",
},
{
name: "types when the param doc narrows the same type",
target: "<?php\n/**\n * @param array<string, int|float> $items\n * @param non-empty-string $name\n */\nfunction take($items, $name) {}",
callers: []string{
"<?php\ntake([1], 'a');",
},
want: "<?php\n/**\n * @param array<string, int|float> $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: "<?php\nnamespace App;\nfinal class Foo {}\nfinal class A {\n /**\n * @param \\App\\Foo $v the foo\n */\n public function set($v) {}\n public function go() { $this->set(new Foo()); }\n}",
want: "<?php\nnamespace App;\nfinal class Foo {}\nfinal class A {\n /**\n * @param \\App\\Foo $v the foo\n */\n public function set(\\App\\Foo $v) {}\n public function go() { $this->set(new Foo()); }\n}",
},
{
name: "skips type when a property-call site passes an unresolved value",
target: "<?php\nfinal class CookieHelper {\n public function setCookie($name, $value) {}\n public function deleteCookie() { $this->setCookie('a', ''); }\n}",
callers: []string{
"<?php\nfinal class Tracker {\n public function __construct(private CookieHelper $cookieHelper) {}\n public function track($lead) { $this->cookieHelper->setCookie('mtc_id', $lead->getId()); }\n}",
},
want: "<?php\nfinal class CookieHelper {\n /**\n * @param 'a'|'mtc_id' $name\n */\n public function setCookie(string $name, $value) {}\n public function deleteCookie() { $this->setCookie('a', ''); }\n}",
},
{
name: "skips multiple observed types",
target: "<?php\nfinal class A {\n public function set($v) {}\n public function go() { $this->set(1); $this->set(\"x\"); }\n}",
Expand Down Expand Up @@ -399,12 +440,12 @@ func TestApply(t *testing.T) {
want: "<?php\nfunction pick(string $v) {}",
},
{
name: "skips string literals doc when an unresolved value is passed",
name: "skips type when an unresolved value is passed",
target: "<?php\nfunction pick($v) {}",
callers: []string{
"<?php\npick('a');\npick('b');\npick($value);",
},
want: "<?php\nfunction pick(string $v) {}",
want: "<?php\nfunction pick($v) {}",
},
{
name: "same-named class in another namespace does not share types",
Expand Down
69 changes: 69 additions & 0 deletions internal/phpast/phpast.go
Original file line number Diff line number Diff line change
Expand Up @@ -471,3 +471,72 @@ func VariableName(node ast.Vertex) string {
}
return strings.TrimPrefix(string(identifier.Value), "$")
}

// DocParamType returns the type of the `@param` tag for the named parameter in
// a function or method's doc comment, e.g. `array<string, int>` 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 `<type> $name ...` into the type and the word after it,
// keeping spaces inside generics and shapes like `array<string, int>`.
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:])
}
Loading