diff --git a/README.md b/README.md index 8af585537b..4d979e8102 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,6 @@ Rules blink runs natively, per source. Regenerate with `blink/bin/rule-counts.sh | PHP-CS-Fixer | 282 | 282 | 100% | | Symplify | 34 | 34 | 100% | | PHP_CodeSniffer | 66 | 114 | 57% | -| slevomat | 28 | 132 | 21% | -| **total** | **410** | **562** | **72%** | +| slevomat | 37 | 132 | 28% | +| **total** | **419** | **562** | **74%** | diff --git a/blink/README.md b/blink/README.md index a1fbcfaae6..3aa08bd743 100644 --- a/blink/README.md +++ b/blink/README.md @@ -27,7 +27,7 @@ those expectations can differ from upstream's `.inc.fixed`. Regenerate them with | PHP_CodeSniffer | 66 | 114 | 57% | | **total** | **382** | **430** | **88%** | -blink runs 416 rules in all, its own extras included. +blink runs 425 rules in all, its own extras included. ### slevomat sniffs @@ -50,11 +50,11 @@ measured against every fixable slevomat sniff in `slevomat-fixable-sniffs.txt` | Namespaces | 0 | 13 | 0% | | Numbers | 0 | 1 | 0% | | Operators | 4 | 4 | 100% | -| PHP | 0 | 9 | 0% | +| PHP | 9 | 9 | 100% | | TypeHints | 0 | 15 | 0% | | Variables | 0 | 1 | 0% | | Whitespaces | 0 | 1 | 0% | -| **total** | **28** | **132** | **21%** | +| **total** | **37** | **132** | **28%** | ## Build diff --git a/blink/internal/fixer/rules/priorities.go b/blink/internal/fixer/rules/priorities.go index bdaae6542e..3f4a3783c1 100644 --- a/blink/internal/fixer/rules/priorities.go +++ b/blink/internal/fixer/rules/priorities.go @@ -100,24 +100,30 @@ var fixerPriority = map[string]int{ "AttributeAndTargetSpacingSniff": 0, "AttributesOrderSniff": 0, "DisallowAttributesJoiningSniff": 0, + "DisallowDirectMagicInvokeCallSniff": 0, "DisallowEqualOperatorsSniff": 0, "DisallowMultipleAttributesPerLineSniff": 0, "DisallowTrailingCommaInCallSniff": 0, "DisallowTrailingCommaInClosureUseSniff": 0, "DisallowTrailingCommaInDeclarationSniff": 0, + "ForbiddenClassesSniff": 0, "LogicalOperatorSpacingSniff": 0, "MultiLineArrayEndBracketPlacementSniff": 0, "NamedArgumentSpacingSniff": 0, "NegationOperatorSpacingSniff": 0, + "ReferenceSpacingSniff": 0, "RequireArrowFunctionSniff": 0, "RequireAttributeAfterDocCommentSniff": 0, "RequireCombinedAssignmentOperatorSniff": 0, + "RequireExplicitAssertionSniff": 0, "RequireMultiLineCallSniff": 0, + "RequireNowdocSniff": 0, "RequireSingleLineCallSniff": 0, "RequireTrailingCommaInCallSniff": 0, "RequireTrailingCommaInClosureUseSniff": 0, "RequireTrailingCommaInDeclarationSniff": 0, "SemicolonSpacingSniff": 0, + "ShortListSniff": 0, "SingleLineArrayWhitespaceSniff": 0, "SpaceAfterNotSniff": 0, "ClassInstantiationSniff": 0, @@ -137,6 +143,7 @@ var fixerPriority = map[string]int{ "SpreadOperatorSpacingSniff": 0, "StaticClosureSniff": 0, "TrailingArrayCommaSniff": 0, + "TypeCastSniff": 0, "UnusedInheritedVariablePassedToClosureSniff": 0, "UselessParameterDefaultValueSniff": 0, "RequireStrictTypesSniff": 0, @@ -150,6 +157,8 @@ var fixerPriority = map[string]int{ "PostStatementCommentSniff": 0, "ClosingDeclarationCommentSniff": 0, "DocCommentAlignmentSniff": 0, + "UselessParenthesesSniff": 0, + "UselessSemicolonSniff": 0, // getPriority() is 0 upstream; raised to run before blank_line_after_opening_tag // so blink reaches the same output in a single pass (PHP-CS-Fixer loops to fixpoint) "LinebreakAfterOpeningTagFixer": 2, diff --git a/blink/internal/fixer/rules/registry.go b/blink/internal/fixer/rules/registry.go index 1c1a63077a..9c346f8a7a 100644 --- a/blink/internal/fixer/rules/registry.go +++ b/blink/internal/fixer/rules/registry.go @@ -373,6 +373,15 @@ func ConstructFixers() []fixer.Fixer { SlevomatDisallowAttributesJoining{}, SlevomatDisallowMultipleAttributesPerLine{}, SlevomatRequireAttributeAfterDocComment{}, + SlevomatDisallowDirectMagicInvokeCall{}, + SlevomatForbiddenClasses{}, + SlevomatReferenceSpacing{}, + SlevomatRequireExplicitAssertion{}, + SlevomatRequireNowdoc{}, + SlevomatShortList{}, + SlevomatTypeCast{}, + SlevomatUselessParentheses{}, + SlevomatUselessSemicolon{}, OperatorLinebreak{}, PhpdocSeparation{}, PhpdocToComment{}, diff --git a/blink/internal/fixer/rules/slevomat.go b/blink/internal/fixer/rules/slevomat.go index 59bb37b5c6..7cae0093ab 100644 --- a/blink/internal/fixer/rules/slevomat.go +++ b/blink/internal/fixer/rules/slevomat.go @@ -763,14 +763,17 @@ func (f *slvFile) enclosingScope(i int) int { func (f *slvFile) braceOwner(open int) int { for j := open - 1; j >= 0; j-- { t := f.toks[j] + if t.kind == token.Variable { + return -1 + } if t.kind == token.Punct { switch t.orig { - case ")", "]", "}": + case ")", "]": if t.closer >= 0 { j = t.closer continue } - case ";", "{", "(", "[": + case ";", "{", "}", "(", "[", "->", "?->", "::", "=": return -1 } } @@ -786,6 +789,40 @@ func (f *slvFile) braceOwner(open int) int { return -1 } +// isTraitUseBlock tells the "{" of a trait use's block. +func (f *slvFile) isTraitUseBlock(open int) bool { + for j := open - 1; j >= 0; j-- { + switch { + case f.isEmpty(j), f.isName(j), f.is(j, ","): + continue + case f.isKeyword(j, "use"): + return true + } + return false + } + return false +} + +// scopeCondition is PHP_CodeSniffer's scope_condition: it returns the owner of the brace at i: "use" for a +// trait use block, else the keyword braceOwner finds, or -1. +func (f *slvFile) scopeCondition(i int) int { + open := i + if f.is(i, "}") { + open = f.toks[i].closer + } + if open < 0 { + return -1 + } + if f.isTraitUseBlock(open) { + for j := open - 1; j >= 0; j-- { + if f.isKeyword(j, "use") { + return j + } + } + } + return f.braceOwner(open) +} + // isClosure tells a closure's "function" from a named function's. func (f *slvFile) isClosure(fn int) bool { n := f.nextEffective(fn+1, len(f.toks)) diff --git a/blink/internal/fixer/rules/slevomat_php.go b/blink/internal/fixer/rules/slevomat_php.go new file mode 100644 index 0000000000..6936d65e08 --- /dev/null +++ b/blink/internal/fixer/rules/slevomat_php.go @@ -0,0 +1,343 @@ +package rules + +import ( + "regexp" + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/fixer" + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// Slevomat: https://github.com/slevomat/coding-standard/blob/master/SlevomatCodingStandard/Sniffs/PHP/DisallowDirectMagicInvokeCallSniff.php +// +// SlevomatDisallowDirectMagicInvokeCall turns "$a->__invoke()" into "$a()". +type SlevomatDisallowDirectMagicInvokeCall struct{} + +func (SlevomatDisallowDirectMagicInvokeCall) Name() string { + return `SlevomatCodingStandard\Sniffs\PHP\DisallowDirectMagicInvokeCallSniff` +} + +func (SlevomatDisallowDirectMagicInvokeCall) SourceURL() string { + return fixer.SourceURLFor(SlevomatDisallowDirectMagicInvokeCall{}.Name()) +} + +func (SlevomatDisallowDirectMagicInvokeCall) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + f.eachToken(func(i int) bool { + return f.toks[i].kind == token.Ident && strings.EqualFold(f.toks[i].orig, "__invoke") + }, func(i int) int { + open := f.nextEffective(i+1, len(f.toks)) + if !f.is(open, "(") { + return 0 + } + op := f.prevEffective(i - 1) + if !f.is(op, "->") { + return 0 + } + f.beginChangeset() + f.removeBetweenIncluding(op, open-1) + f.endChangeset() + return 0 + }) + }) +} + +// Slevomat: https://github.com/slevomat/coding-standard/blob/master/SlevomatCodingStandard/Sniffs/PHP/ReferenceSpacingSniff.php +// +// SlevomatReferenceSpacing sets the spaces after a reference "&" +// (spacesCountAfterReference, 0 by default). +type SlevomatReferenceSpacing struct { + spaces int +} + +func (SlevomatReferenceSpacing) Name() string { + return `SlevomatCodingStandard\Sniffs\PHP\ReferenceSpacingSniff` +} + +func (SlevomatReferenceSpacing) SourceURL() string { + return fixer.SourceURLFor(SlevomatReferenceSpacing{}.Name()) +} + +func (r SlevomatReferenceSpacing) WithConfig(config map[string]any) fixer.Fixer { + r.spaces = configInt(config, "spacesCountAfterReference", r.spaces) + return r +} + +func (r SlevomatReferenceSpacing) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + f.eachToken(func(i int) bool { return f.is(i, "&") }, func(i int) int { + if !f.isReference(i) { + return 0 + } + after := f.nextNonWhitespace(i+1, len(f.toks)) + if after < 0 || len(f.content(i+1, after-1)) == r.spaces { + return 0 + } + f.beginChangeset() + f.add(i, strings.Repeat(" ", r.spaces)) + f.removeBetweenIncluding(i+1, after-1) + f.endChangeset() + return 0 + }) + }) +} + +// isReference is ReferenceSpacingSniff::isReference. +func (f *slvFile) isReference(i int) bool { + prev := f.prevEffective(i - 1) + if f.isKeyword(prev, "function") || f.isKeyword(prev, "fn") { + return true + } + open := -1 + for j := i - 1; j >= 0; j-- { + if f.is(j, "(") { + open = j + break + } + } + if open >= 0 && f.toks[open].closer > i { + if f.isFunctionParams(open) { + return true + } + if f.isKeyword(f.prevEffective(open-1), "use") { + return true + } + } + if f.identEnd(f.nextEffective(i+1, len(f.toks))) < 0 { + return false + } + return f.is(prev, "=") || f.is(prev, "=>") || f.isShortArrayOpen(prev) || f.is(prev, ",") || f.isKeyword(prev, "as") +} + +// isFunctionParams tells the "(" of a function, closure or arrow function's +// parameters, the parentheses PHP_CodeSniffer gives such an owner. +func (f *slvFile) isFunctionParams(open int) bool { + p := f.prevEffective(open - 1) + if f.is(p, "&") { + p = f.prevEffective(p - 1) + } + if f.isKeyword(p, "function") || f.isKeyword(p, "fn") { + return true + } + if p < 0 || f.toks[p].kind != token.Ident && f.toks[p].kind != token.Keyword { + return false + } + q := f.prevEffective(p - 1) + if f.is(q, "&") { + q = f.prevEffective(q - 1) + } + return f.isKeyword(q, "function") +} + +// Slevomat: https://github.com/slevomat/coding-standard/blob/master/SlevomatCodingStandard/Sniffs/PHP/RequireNowdocSniff.php +// +// SlevomatRequireNowdoc turns a heredoc without variables or escapes into a +// nowdoc. +type SlevomatRequireNowdoc struct{} + +func (SlevomatRequireNowdoc) Name() string { + return `SlevomatCodingStandard\Sniffs\PHP\RequireNowdocSniff` +} + +func (SlevomatRequireNowdoc) SourceURL() string { + return fixer.SourceURLFor(SlevomatRequireNowdoc{}.Name()) +} + +var ( + slvHeredocPlain = regexp.MustCompile(`^([^\\$]|\\[^nrtvef0-7xu])*$`) + slvHeredocStart = regexp.MustCompile(`^<<<"?(\w+)"?`) + slvHeredocUnescape = regexp.MustCompile(`\\(\\[nrtvef]|\$|\\|\\[0-7]{1,3}|\\x[0-9A-Fa-f]{1,2}|\\u\{[0-9A-Fa-f]+\})`) +) + +func (SlevomatRequireNowdoc) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + f.eachToken(func(i int) bool { + t := f.toks[i] + return t.kind == token.String && t.heredoc && strings.HasPrefix(t.orig, "<<<") && + !strings.HasPrefix(strings.TrimLeft(t.orig[3:], " \t"), "'") + }, func(start int) int { + end := start + 1 + for end < len(f.toks) && f.toks[end].heredoc && strings.HasSuffix(f.toks[end].orig, "\n") { + end++ + } + if end >= len(f.toks) || !f.toks[end].heredoc { + return 0 + } + for i := start + 1; i < end; i++ { + if !slvHeredocPlain.MatchString(strings.TrimSuffix(f.toks[i].content, "\n")) { + return 0 + } + } + f.beginChangeset() + f.replace(start, slvHeredocStart.ReplaceAllString(f.toks[start].content, "<<<'$1'")) + for i := start + 1; i < end; i++ { + f.replace(i, slvHeredocUnescape.ReplaceAllString(f.toks[i].content, "$1")) + } + f.endChangeset() + return 0 + }) + }) +} + +// Slevomat: https://github.com/slevomat/coding-standard/blob/master/SlevomatCodingStandard/Sniffs/PHP/ShortListSniff.php +// +// SlevomatShortList turns "list($a, $b)" into "[$a, $b]". +type SlevomatShortList struct{} + +func (SlevomatShortList) Name() string { + return `SlevomatCodingStandard\Sniffs\PHP\ShortListSniff` +} + +func (SlevomatShortList) SourceURL() string { + return fixer.SourceURLFor(SlevomatShortList{}.Name()) +} + +func (SlevomatShortList) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + f.eachToken(func(i int) bool { return f.isKeyword(i, "list") }, func(i int) int { + open := -1 + for j := i + 1; j < len(f.toks); j++ { + if f.is(j, "(") { + open = j + break + } + } + if open < 0 || f.toks[open].closer < 0 { + return 0 + } + f.beginChangeset() + f.removeBetweenIncluding(i, open-1) + f.replace(open, "[") + f.replace(f.toks[open].closer, "]") + f.endChangeset() + return 0 + }) + }) +} + +// Slevomat: https://github.com/slevomat/coding-standard/blob/master/SlevomatCodingStandard/Sniffs/PHP/TypeCastSniff.php +// +// SlevomatTypeCast replaces the (boolean), (double), (integer) and (real) +// casts and drops (binary). +type SlevomatTypeCast struct{} + +func (SlevomatTypeCast) Name() string { + return `SlevomatCodingStandard\Sniffs\PHP\TypeCastSniff` +} + +func (SlevomatTypeCast) SourceURL() string { + return fixer.SourceURLFor(SlevomatTypeCast{}.Name()) +} + +var ( + slvCastName = regexp.MustCompile(`(?i)^\(\s*(\S+)\s*\)$`) + slvInvalidCasts = map[string]string{"boolean": "bool", "double": "float", "integer": "int", "real": "float", "binary": ""} +) + +func (SlevomatTypeCast) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + f.eachToken(func(i int) bool { + t := f.toks[i] + return t.kind == token.Punct && len(t.orig) > 2 && t.orig[0] == '(' && t.orig[len(t.orig)-1] == ')' + }, func(i int) int { + m := slvCastName.FindStringSubmatch(f.toks[i].content) + if m == nil { + return 0 + } + name := strings.ToLower(m[1]) + replacement, ok := slvInvalidCasts[name] + if !ok { + return 0 + } + f.beginChangeset() + if name == "binary" { + f.removeBetweenIncluding(i, f.nextEffective(i+1, len(f.toks))-1) + } else { + f.replace(i, "("+replacement+")") + } + f.endChangeset() + return 0 + }) + }) +} + +// Slevomat: https://github.com/slevomat/coding-standard/blob/master/SlevomatCodingStandard/Sniffs/PHP/UselessSemicolonSniff.php +// +// SlevomatUselessSemicolon removes doubled semicolons, ones opening a scope +// and ones after a block. +type SlevomatUselessSemicolon struct{} + +func (SlevomatUselessSemicolon) Name() string { + return `SlevomatCodingStandard\Sniffs\PHP\UselessSemicolonSniff` +} + +func (SlevomatUselessSemicolon) SourceURL() string { + return fixer.SourceURLFor(SlevomatUselessSemicolon{}.Name()) +} + +func (SlevomatUselessSemicolon) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + f.eachToken(func(i int) bool { return f.is(i, ";") }, func(i int) int { + prev := f.prevEffective(i - 1) + if prev < 0 { + return 0 + } + if f.is(prev, ";") && !f.inForHeader(i) { + f.removeUselessSemicolon(i) + } + if f.toks[prev].kind == token.OpenTag || f.is(prev, "{") { + f.removeUselessSemicolon(i) + } + if f.is(prev, "}") && f.toks[prev].closer >= 0 { + owner := f.scopeCondition(prev) + if owner >= 0 && !f.isExpressionScope(owner) { + f.removeUselessSemicolon(i) + } + } + return 0 + }) + }) +} + +// isExpressionScope tells a closure, anonymous class or match, whose block +// ends an expression rather than a statement. +func (f *slvFile) isExpressionScope(owner int) bool { + switch { + case f.isKeyword(owner, "match"): + return true + case f.isKeyword(owner, "function"): + return f.isClosure(owner) + case f.isKeyword(owner, "class"): + return f.isKeyword(f.prevEffective(owner-1), "new") + } + return false +} + +// inForHeader tells a ";" inside the parentheses of a "for". +func (f *slvFile) inForHeader(semicolon int) bool { + for j := semicolon + 1; j < len(f.toks) && !f.is(j, ";"); j++ { + if f.is(j, ")") { + open := f.toks[j].closer + return open >= 0 && open < semicolon && f.isKeyword(f.prevEffective(open-1), "for") + } + } + return false +} + +func (f *slvFile) removeUselessSemicolon(semicolon int) { + start := semicolon + for start > 0 && f.toks[start-1].kind == token.Whitespace { + start-- + if f.toks[start].content == f.eol { + break + } + } + end := semicolon + for end < len(f.toks)-1 && f.toks[end+1].kind == token.Whitespace && f.toks[end+1].content != f.eol { + end++ + } + f.beginChangeset() + f.removeBetweenIncluding(start, end) + f.endChangeset() +} diff --git a/blink/internal/fixer/rules/slevomat_php_explicit_assertion.go b/blink/internal/fixer/rules/slevomat_php_explicit_assertion.go new file mode 100644 index 0000000000..3ee341222b --- /dev/null +++ b/blink/internal/fixer/rules/slevomat_php_explicit_assertion.go @@ -0,0 +1,685 @@ +package rules + +import ( + "regexp" + "slices" + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/fixer" + "github.com/ecsphp/ecs-src/blink/internal/lexer" + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// Slevomat: https://github.com/slevomat/coding-standard/blob/master/SlevomatCodingStandard/Sniffs/PHP/RequireExplicitAssertionSniff.php +// +// SlevomatRequireExplicitAssertion turns an inline "@var" doc comment into an +// assert() call (enableIntegerRanges, enableAdvancedStringTypes). +type SlevomatRequireExplicitAssertion struct { + integerRanges bool + advancedStringTypes bool +} + +func (SlevomatRequireExplicitAssertion) Name() string { + return `SlevomatCodingStandard\Sniffs\PHP\RequireExplicitAssertionSniff` +} + +func (SlevomatRequireExplicitAssertion) SourceURL() string { + return fixer.SourceURLFor(SlevomatRequireExplicitAssertion{}.Name()) +} + +func (r SlevomatRequireExplicitAssertion) WithConfig(config map[string]any) fixer.Fixer { + if v, ok := config["enableIntegerRanges"].(bool); ok { + r.integerRanges = v + } + if v, ok := config["enableAdvancedStringTypes"].(bool); ok { + r.advancedStringTypes = v + } + return r +} + +func (r SlevomatRequireExplicitAssertion) Fix(s *tokens.Stream) bool { + src := s.Render() + crashed := false + changed := slvRun(s, func(f *slvFile) { + var scopes []int + f.eachToken(f.assertionIsDocOpen, func(open int) int { + if crashed { + return len(f.toks) + } + closeIdx := f.assertionDocClose(open) + code := f.assertionFirstOnNextLine(closeIdx) + if code < 0 || !f.assertionIsCode(code) { + code = f.assertionFirstOnPreviousLine(open) + if code < 0 || !f.assertionIsCode(code) { + return 0 + } + } + annotations := f.assertionVarAnnotations(open, closeIdx) + for _, a := range slices.Backward(annotations) { + if a.invalid || a.variable == "" || !r.isValid(a.typ) { + continue + } + assertion := r.createAssert(a.variable, a.typ) + if assertion == "" { + continue + } + if scopes == nil { + scopes = slvcFunctionScopes(f) + } + add, indentation := f.assertionTarget(code, a.variable, open, scopes) + if add == assertionNoSemicolon { + // upstream passes null to ScopeHelper::isInSameScope and + // the TypeError leaves the whole file unfixed + crashed = true + return len(f.toks) + } + if add < 0 { + continue + } + f.beginChangeset() + f.removeBetweenIncluding(a.start, a.end) + useful := false + for i := open + 1; i < closeIdx; i++ { + v := strings.Trim(f.tokenContent(i), " \t\n\r\x00\x0B") + if v != "" && v != "*" { + useful = true + break + } + } + before := -1 + for i := open - 1; i >= 0; i-- { + if f.toks[i].kind == token.Whitespace && f.toks[i].content == f.eol { + before = i + break + } + } + after := -1 + for i := closeIdx + 1; i < len(f.toks); i++ { + if f.toks[i].kind == token.Whitespace && f.toks[i].content == f.eol { + after = i + break + } + } + if !useful { + f.removeBetweenIncluding(before+1, after) + } + if add < closeIdx && after >= 0 && after+1 < len(f.toks) { + f.addBefore(after+1, indentation+assertion+f.eol) + } else { + f.add(add, f.eol+indentation+assertion) + } + f.endChangeset() + } + return 0 + }) + }) + if crashed { + if changed { + s.ReplaceRange(0, s.Len()-1, lexer.Lex(src)) + } + return false + } + return changed +} + +const assertionNoSemicolon = -2 + +// assertionTarget returns the token the assertion goes after and its +// indentation, or -1 when the code does not assign the variable. +func (f *slvFile) assertionTarget(code int, variable string, open int, scopes []int) (int, string) { + n := len(f.toks) + switch { + case f.isVariable(code): + if !f.is(f.nextEffective(code+1, n), "=") || f.toks[code].content != variable { + return -1, "" + } + return f.assertionNextSemicolon(code, code+1, scopes), f.indentation(open) + case f.isKeyword(code, "list"): + paren := f.nextEffective(code+1, n) + if !f.is(paren, "(") || f.toks[paren].closer < 0 || f.assertionFindVariable(variable, paren+1, f.toks[paren].closer) < 0 { + return -1, "" + } + return f.assertionNextSemicolon(code, code+1, scopes), f.indentation(open) + case f.isShortArrayOpen(code): + closeIdx := f.toks[code].closer + if !f.is(f.nextEffective(closeIdx+1, n), "=") || f.assertionFindVariable(variable, code+1, closeIdx) < 0 { + return -1, "" + } + return f.assertionNextSemicolon(code, closeIdx+1, scopes), f.indentation(open) + } + paren := f.nextEffective(code+1, n) + if !f.is(paren, "(") || f.toks[paren].closer < 0 { + return -1, "" + } + closeIdx := f.toks[paren].closer + if f.isKeyword(code, "while") { + v := f.assertionFindVariable(variable, paren+1, closeIdx) + if v < 0 || !f.is(f.nextEffective(v+1, n), "=") { + return -1, "" + } + } else { + as := -1 + for i := paren + 1; i < closeIdx; i++ { + if f.isKeyword(i, "as") { + as = i + break + } + } + if as < 0 || f.assertionFindVariable(variable, as+1, closeIdx) < 0 { + return -1, "" + } + } + opener := f.nextEffective(closeIdx+1, n) + if !f.is(opener, "{") && !f.is(opener, ":") { + return -1, "" + } + return opener, f.indentation(code) + " " +} + +func (f *slvFile) assertionFindVariable(name string, start, end int) int { + for i := start; i < end; i++ { + if f.isVariable(i) && f.toks[i].content == name { + return i + } + } + return -1 +} + +// assertionNextSemicolon is getNextSemicolonInSameScope, or -1. +func (f *slvFile) assertionNextSemicolon(scope, from int, scopes []int) int { + for i := from; i < len(f.toks); i++ { + if f.is(i, ";") && scopes[i] == scopes[scope] { + return i + } + } + return assertionNoSemicolon +} + +func (f *slvFile) assertionIsCode(i int) bool { + return f.isVariable(i) || f.isKeyword(i, "foreach") || f.isKeyword(i, "while") || + f.isKeyword(i, "list") || f.isShortArrayOpen(i) +} + +func (f *slvFile) assertionIsDocOpen(i int) bool { + return f.toks[i].kind == token.DocComment && strings.HasPrefix(f.toks[i].orig, "/**") && + (i == 0 || f.toks[i-1].kind != token.DocComment) +} + +func (f *slvFile) assertionDocClose(open int) int { + closeIdx := open + for closeIdx+1 < len(f.toks) && f.toks[closeIdx+1].kind == token.DocComment { + closeIdx++ + } + return closeIdx +} + +// assertionIsWhitespace tells T_WHITESPACE and T_DOC_COMMENT_WHITESPACE. +func (f *slvFile) assertionIsWhitespace(i int) bool { + t := f.toks[i] + return t.kind == token.Whitespace || t.kind == token.DocComment && t.orig != "" && strings.TrimSpace(t.orig) == "" +} + +func (f *slvFile) assertionIsNewline(i int) bool { + return f.assertionIsWhitespace(i) && f.toks[i].content == f.eol +} + +// assertionFirstOnNextLine is TokenHelper::findFirstNonWhitespaceOnNextLine. +func (f *slvFile) assertionFirstOnNextLine(i int) int { + nl := i + for nl < len(f.toks) && !f.assertionIsNewline(nl) { + nl++ + } + if nl >= len(f.toks) { + return -1 + } + next := nl + 1 + for next < len(f.toks) && f.assertionIsWhitespace(next) { + next++ + } + if next < len(f.toks) && f.toks[i].line == f.toks[next].line-1 { + return next + } + return -1 +} + +// assertionFirstOnPreviousLine is TokenHelper::findFirstNonWhitespaceOnPreviousLine. +func (f *slvFile) assertionFirstOnPreviousLine(i int) int { + nl := i + for nl >= 0 && !f.assertionIsNewline(nl) { + nl-- + } + if nl < 0 { + return -1 + } + before := nl - 1 + for before >= 0 && !f.assertionIsNewline(before) { + before-- + } + next := before + 1 + if before < 0 { + next = 1 + } + for next < len(f.toks) && f.assertionIsWhitespace(next) { + next++ + } + if next < len(f.toks) && f.toks[i].line == f.toks[next].line+1 { + return next + } + return -1 +} + +// slveaAnnotation is a parsed "@var" annotation and its tokens. +type slveaAnnotation struct { + start, end int + invalid bool + variable string + typ *slveaType +} + +const ( + slveaIdentifier = iota + slveaThis + slveaIntRange + slveaUnion + slveaIntersection + slveaOther +) + +// slveaType is the part of phpdoc-parser's type tree the sniff reads. +type slveaType struct { + kind int + name string // identifier name + args [2]string // int bounds: "min", "max" or an integer + types []slveaType // union or intersection members +} + +// assertionVarAnnotations is AnnotationHelper::getAnnotations(..., '@var') +// for the doc comment open..closeIdx. +func (f *slvFile) assertionVarAnnotations(open, closeIdx int) []slveaAnnotation { + var tags []int + for i := open + 1; i < closeIdx; i++ { + if strings.HasPrefix(f.toks[i].orig, "@") { + tags = append(tags, i) + } + } + var out []slveaAnnotation + for n, tag := range tags { + if f.toks[tag].orig != "@var" { + continue + } + limit := closeIdx + if n+1 < len(tags) { + limit = tags[n+1] + } + end := tag + for i := tag + 1; i < limit; i++ { + if f.assertionIsDocString(i) { + end = i + } + } + a := slveaAnnotation{start: tag, end: end} + value := "" + if tag+2 < limit && f.assertionIsWhitespace(tag+1) && f.assertionIsDocString(tag+2) { + value = f.toks[tag+2].orig + } + if value == "" { + a.invalid = true + } else { + a.typ, a.variable, a.invalid = slveaParseVarValue(value) + } + out = append(out, a) + } + return out +} + +func (f *slvFile) assertionIsDocString(i int) bool { + v := f.toks[i].orig + return f.toks[i].kind == token.DocComment && strings.TrimSpace(v) != "" && v != "*" && + !strings.HasPrefix(v, "@") && !strings.HasPrefix(v, "/**") && !strings.HasSuffix(v, "*/") +} + +var ( + slveaIdentRe = regexp.MustCompile(`^(?:\\?[a-zA-Z_\x80-\xff][0-9a-zA-Z_\x80-\xff-]*)+`) + slveaVariableRe = regexp.MustCompile(`^\$[a-zA-Z_\x80-\xff][0-9a-zA-Z_\x80-\xff]*`) + slveaIntegerRe = regexp.MustCompile(`^-?(?:0[bB][01]+(?:_[01]+)*|0[oO][0-7]+(?:_[0-7]+)*|0[xX][0-9a-fA-F]+(?:_[0-9a-fA-F]+)*|[0-9]+(?:_[0-9]+)*)`) +) + +// slveaParseVarValue parses "Type $variable description" of an "@var" tag. +func slveaParseVarValue(v string) (*slveaType, string, bool) { + p := &slveaParser{s: v} + typ := p.parseType() + if typ == nil { + return nil, "", true + } + p.skipSpaces() + variable := "" + if strings.HasPrefix(p.s[p.i:], "$this") && !slveaIsIdentChar(p.peekAt(5)) { + variable = "$this" + p.i += 5 + } else if m := slveaVariableRe.FindString(p.s[p.i:]); m != "" { + variable = m + p.i += len(m) + } + return typ, variable, false +} + +type slveaParser struct { + s string + i int +} + +func (p *slveaParser) peekAt(n int) byte { + if p.i+n < len(p.s) { + return p.s[p.i+n] + } + return 0 +} + +func (p *slveaParser) skipSpaces() { + for p.i < len(p.s) && (p.s[p.i] == ' ' || p.s[p.i] == '\t') { + p.i++ + } +} + +// parseType parses an atomic type or a union or intersection of them, or +// returns nil on a syntax error. Types the sniff never asserts parse as other. +func (p *slveaParser) parseType() *slveaType { + p.skipSpaces() + if p.i < len(p.s) && p.s[p.i] == '?' { + p.i++ + if p.parseAtomic() == nil { + return nil + } + return &slveaType{kind: slveaOther} + } + first := p.parseAtomic() + if first == nil { + return nil + } + save := p.i + p.skipSpaces() + if p.i >= len(p.s) || (p.s[p.i] != '|' && p.s[p.i] != '&') { + p.i = save + return first + } + op := p.s[p.i] + kind := slveaUnion + if op == '&' { + kind = slveaIntersection + } + t := &slveaType{kind: kind, types: []slveaType{*first}} + for { + save = p.i + p.skipSpaces() + if p.i >= len(p.s) || p.s[p.i] != op { + p.i = save + break + } + p.i++ + p.skipSpaces() + next := p.parseAtomic() + if next == nil { + return nil + } + t.types = append(t.types, *next) + } + save = p.i + p.skipSpaces() + if p.i < len(p.s) && (p.s[p.i] == '|' || p.s[p.i] == '&') { + return nil + } + p.i = save + return t +} + +func (p *slveaParser) parseAtomic() *slveaType { + rest := p.s[p.i:] + var t *slveaType + switch { + case strings.HasPrefix(rest, "$this") && !slveaIsIdentChar(p.peekAt(5)): + p.i += 5 + t = &slveaType{kind: slveaThis, name: "$this"} + case slveaIdentRe.MatchString(rest): + name := slveaIdentRe.FindString(rest) + p.i += len(name) + t = &slveaType{kind: slveaIdentifier, name: name} + if p.i < len(p.s) && p.s[p.i] == '<' { + return p.parseGeneric(name) + } + case rest != "" && rest[0] == '(': + // phpdoc-parser returns the type inside parentheses as is + p.i++ + inner := p.parseType() + p.skipSpaces() + if inner == nil || p.i >= len(p.s) || p.s[p.i] != ')' { + return nil + } + p.i++ + if p.i < len(p.s) && p.s[p.i] == '[' { + return p.skipOther() + } + return inner + case rest != "" && strings.ContainsRune("[{'\"", rune(rest[0])), slveaIntegerRe.MatchString(rest): + return p.skipOther() + default: + return nil + } + if p.i < len(p.s) && strings.ContainsRune("[({:<", rune(p.s[p.i])) { + return p.skipOther() + } + return t +} + +// parseGeneric parses int; other generics are "other". +func (p *slveaParser) parseGeneric(name string) *slveaType { + start := p.i + depth := 0 + end := -1 + for j := p.i; j < len(p.s); j++ { + switch p.s[j] { + case '<': + depth++ + case '>': + depth-- + if depth == 0 { + end = j + } + } + if end >= 0 { + break + } + } + if end < 0 { + return nil + } + p.i = end + 1 + if p.i < len(p.s) && strings.ContainsRune("[({:<", rune(p.s[p.i])) { + return p.skipOther() + } + if name != "int" { + return &slveaType{kind: slveaOther} + } + parts := strings.Split(p.s[start+1:end], ",") + if len(parts) != 2 { + return &slveaType{kind: slveaOther} + } + t := &slveaType{kind: slveaIntRange, name: name} + for k, part := range parts { + part = strings.TrimSpace(part) + if part != "min" && part != "max" && slveaIntegerRe.FindString(part) != part { + return &slveaType{kind: slveaOther} + } + t.args[k] = part + } + return t +} + +// skipOther consumes a type the sniff never asserts, up to the next space +// outside brackets. +func (p *slveaParser) skipOther() *slveaType { + depth := 0 + for p.i < len(p.s) { + c := p.s[p.i] + switch { + case strings.ContainsRune("([{<", rune(c)): + depth++ + case strings.ContainsRune(")]}>", rune(c)): + depth-- + case depth == 0 && (slveaIsSpace(c) || c == '|' || c == '&'): + return &slveaType{kind: slveaOther} + } + p.i++ + } + return &slveaType{kind: slveaOther} +} + +func slveaIsSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' } + +func slveaIsIdentChar(c byte) bool { + return c == '_' || c == '-' || c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= 0x80 +} + +func (r SlevomatRequireExplicitAssertion) isValid(t *slveaType) bool { + if t.kind == slveaUnion || t.kind == slveaIntersection { + for k := range t.types { + if !r.isValidAtomic(&t.types[k]) { + return false + } + } + return true + } + return r.isValidAtomic(t) +} + +func (r SlevomatRequireExplicitAssertion) isValidAtomic(t *slveaType) bool { + switch t.kind { + case slveaThis, slveaIdentifier: + return true + case slveaIntRange: + return r.integerRanges + } + return false +} + +func (r SlevomatRequireExplicitAssertion) createAssert(variable string, t *slveaType) string { + if t.kind != slveaUnion && t.kind != slveaIntersection { + conditions := r.createConditions(variable, t) + if len(conditions) == 0 { + return "" + } + return `\assert(` + strings.Join(conditions, " || ") + ");" + } + var conditions []string + for k := range t.types { + inner := r.createConditions(variable, &t.types[k]) + if len(inner) == 0 { + return "" + } + conditions = append(conditions, inner...) + } + operator := "||" + if t.kind == slveaIntersection { + operator = "&&" + } + var formatted []string + seen := map[string]bool{} + for _, c := range conditions { + if seen[c] { + continue + } + seen[c] = true + if operator == "||" && strings.Contains(c, "&&") { + c = "(" + c + ")" + } + formatted = append(formatted, c) + } + return `\assert(` + strings.Join(formatted, " "+operator+" ") + ");" +} + +var ( + slveaSimpleTypes = map[string]bool{ + "int": true, "integer": true, "false": true, "float": true, "string": true, "bool": true, + "boolean": true, "callable": true, "self": true, "array": true, "iterable": true, "void": true, "never": true, + } + slveaUnofficialTypes = map[string]bool{ + "null": true, "mixed": true, "scalar": true, "numeric": true, "true": true, "object": true, + "resource": true, "static": true, "$this": true, "array-key": true, "list": true, + "non-empty-array": true, "non-empty-list": true, "empty": true, "positive-int": true, + "non-positive-int": true, "negative-int": true, "non-negative-int": true, "literal-int": true, + "int-mask": true, "min": true, "max": true, "callable-array": true, "callable-string": true, + } + slveaClassStringRe = regexp.MustCompile(`^(?:class|trait|enum)-string$`) +) + +func (r SlevomatRequireExplicitAssertion) createConditions(v string, t *slveaType) []string { + if t.kind == slveaIntRange { + conditions := []string{`\is_int(` + v + ")"} + if t.args[0] != "min" && t.args[0] != "max" { + conditions = append(conditions, v+" >= "+t.args[0]) + } + if t.args[1] != "min" && t.args[1] != "max" { + conditions = append(conditions, v+" <= "+t.args[1]) + } + return []string{strings.Join(conditions, " && ")} + } + if t.kind == slveaThis { + return []string{v + " instanceof $this"} + } + name := t.name + switch { + case name == "self": + return []string{v + " instanceof " + name} + case name == "static": + return []string{v + " instanceof static"} + case name == "true" || name == "false" || name == "null": + return []string{v + " === " + name} + case name == "mixed" || name == "void" || name == "never" || name == "never-return" || + name == "never-returns" || name == "no-return": + return nil + case slveaSimpleTypes[name]: + short := name + switch name { + case "integer": + short = "int" + case "boolean": + short = "bool" + } + return []string{`\is_` + short + "(" + v + ")"} + case name == "resource" || name == "object": + return []string{`\is_` + name + "(" + v + ")"} + case name == "numeric": + return []string{`\is_numeric(` + v + ")"} + case name == "scalar": + return []string{`\is_int(` + v + ")", `\is_float(` + v + ")", `\is_bool(` + v + ")", `\is_string(` + v + ")"} + } + if r.integerRanges { + switch name { + case "positive-int", "non-negative-int": + return []string{`\is_int(` + v + ") && " + v + " > 0"} + case "negative-int", "non-positive-int": + return []string{`\is_int(` + v + ") && " + v + " < 0"} + case "literal-int": + return []string{`\is_int(` + v + ")"} + } + } + if r.advancedStringTypes && strings.HasSuffix(name, "-string") && !slveaClassStringRe.MatchString(name) { + conditions := []string{`\is_string(` + v + ")"} + lower := strings.ToLower(name) + switch { + case name == "callable-string": + conditions = append(conditions, `\is_callable(`+v+")") + case name == "numeric-string": + conditions = append(conditions, `\is_numeric(`+v+")") + case strings.HasPrefix(lower, "non-empty-"): + conditions = append(conditions, v+" !== ''") + case strings.HasPrefix(lower, "non-falsy-"): + conditions = append(conditions, "(bool) "+v+" === true") + } + return []string{strings.Join(conditions, " && ")} + } + if slveaUnofficialTypes[name] || strings.HasSuffix(strings.ToLower(name), "-string") { + return nil + } + return []string{v + " instanceof " + name} +} diff --git a/blink/internal/fixer/rules/slevomat_php_forbidden_classes.go b/blink/internal/fixer/rules/slevomat_php_forbidden_classes.go new file mode 100644 index 0000000000..5bc611525f --- /dev/null +++ b/blink/internal/fixer/rules/slevomat_php_forbidden_classes.go @@ -0,0 +1,222 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/fixer" + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// Slevomat: https://github.com/slevomat/coding-standard/blob/master/SlevomatCodingStandard/Sniffs/PHP/ForbiddenClassesSniff.php +// +// SlevomatForbiddenClasses replaces forbidden classes, parents, interfaces +// and traits with their configured alternatives. +type SlevomatForbiddenClasses struct { + classes, extends, interfaces, traits map[string]*string +} + +func (SlevomatForbiddenClasses) Name() string { + return `SlevomatCodingStandard\Sniffs\PHP\ForbiddenClassesSniff` +} + +func (SlevomatForbiddenClasses) SourceURL() string { + return fixer.SourceURLFor(SlevomatForbiddenClasses{}.Name()) +} + +func (r SlevomatForbiddenClasses) WithConfig(config map[string]any) fixer.Fixer { + r.classes = slvfcOption(config["forbiddenClasses"], r.classes) + r.extends = slvfcOption(config["forbiddenExtends"], r.extends) + r.interfaces = slvfcOption(config["forbiddenInterfaces"], r.interfaces) + r.traits = slvfcOption(config["forbiddenTraits"], r.traits) + return r +} + +// slvfcOption is normalizeInputOption: fully qualified names mapped to their +// fully qualified alternative, nil when there is none. +func slvfcOption(v any, def map[string]*string) map[string]*string { + m, ok := v.(map[string]any) + if !ok { + return def + } + out := map[string]*string{} + for name, alt := range m { + key := slvfcNormalize(name) + if key == nil { + continue + } + s, _ := alt.(string) + out[*key] = slvfcNormalize(s) + } + return out +} + +func slvfcNormalize(name string) *string { + if name == "" || strings.EqualFold(name, "null") { + return nil + } + if !strings.HasPrefix(name, `\`) { + name = `\` + name + } + return &name +} + +func (r SlevomatForbiddenClasses) Fix(s *tokens.Stream) bool { + if len(r.classes)+len(r.extends)+len(r.interfaces)+len(r.traits) == 0 { + return false + } + return slvRun(s, func(f *slvFile) { + uses := f.useStatements() + n := len(f.toks) + f.eachToken(func(i int) bool { + switch { + case len(r.classes) > 0 && (f.isKeyword(i, "new") || f.is(i, "::")): + return true + case len(r.extends) > 0 && f.isKeyword(i, "extends"), + len(r.interfaces) > 0 && f.isKeyword(i, "implements"), + len(r.traits) > 0 && f.isKeyword(i, "use"): + return true + } + return false + }, func(i int) int { + switch { + case f.isKeyword(i, "implements") || f.isKeyword(i, "use") && f.forbiddenIsTraitUse(i): + end := i + for end < n && !f.is(end, ";") && !f.is(end, "{") { + end++ + } + refs := f.forbiddenReferences(uses, i, end) + if f.isKeyword(i, "implements") { + f.forbiddenCheck(refs, r.interfaces, true) + } else { + // upstream does not fix a trait use with aliases + f.forbiddenCheck(refs, r.traits, end >= n || !f.is(end, "{")) + } + case f.isKeyword(i, "new") || f.isKeyword(i, "extends"): + end := i + 1 + for end < n && (f.isName(end) || f.isEmpty(end)) { + end++ + } + refs := f.forbiddenReferences(uses, i, end) + if f.isKeyword(i, "new") { + f.forbiddenCheck(refs, r.classes, true) + } else { + f.forbiddenCheck(refs, r.extends, true) + } + case f.is(i, "::") && !f.forbiddenInTraitUseBlock(i): + start := i - 1 + for start >= 0 && (f.isName(start) || f.isEmpty(start)) { + start-- + } + f.forbiddenCheck(f.forbiddenReferences(uses, start, i), r.classes, true) + } + return 0 + }) + }) +} + +type slvfcReference struct { + name string + pointer int +} + +// forbiddenReferences is getAllReferences: the names after start (exclusive) +// while the search pointer is before end. Like upstream, the search for the +// next name is not bounded by end. +func (f *slvFile) forbiddenReferences(uses *slvUseStatements, start, end int) []slvfcReference { + var refs []slvfcReference + for start++; start < end; { + ref := -1 + for j := start; j < len(f.toks); j++ { + if f.isName(j) || f.isClassKeyword(j) { + ref = j + break + } + } + if ref < 0 { + break + } + if !f.isClassKeyword(ref) { + content := f.toks[ref].content + switch strings.ToLower(content) { + case "", "self", "parent", "static": + default: + refs = append(refs, slvfcReference{uses.resolveClassName(f, content, start), ref}) + } + } + start = ref + 1 + } + return refs +} + +func (f *slvFile) forbiddenCheck(refs []slvfcReference, forbidden map[string]*string, fixable bool) { + for _, ref := range refs { + alt, ok := forbidden[ref.name] + if !ok || alt == nil || !fixable { + continue + } + f.beginChangeset() + f.change(ref.pointer, ref.pointer, *alt) + f.endChangeset() + } +} + +// forbiddenInTraitUseBlock tells a "::" whose innermost scope is the block of +// a trait use ("use A, B { A::x insteadof B; }"). +func (f *slvFile) forbiddenInTraitUseBlock(i int) bool { + o := f.enclosing(i) + for o >= 0 && !f.is(o, "{") { + o = f.enclosing(o) + } + return o >= 0 && f.isTraitUseBlock(o) +} + +// forbiddenIsTraitUse is UseStatementHelper::isTraitUse. +func (f *slvFile) forbiddenIsTraitUse(use int) bool { + next := f.nextEffective(use+1, len(f.toks)) + if next < 0 || f.is(next, "(") { + return false + } + switch strings.ToLower(f.toks[next].orig) { + case "function", "const": + return false + } + prev := -1 + for j := use; j >= 0; j-- { + if f.toks[j].kind == token.OpenTag && !strings.HasPrefix(f.toks[j].orig, "= 0; o = f.enclosing(o) { + if f.is(o, "{") && f.isOOScopeOwner(f.braceOwner(o)) { + return true + } + } + return false +} diff --git a/blink/internal/fixer/rules/slevomat_php_useless_parentheses.go b/blink/internal/fixer/rules/slevomat_php_useless_parentheses.go new file mode 100644 index 0000000000..dc60baa1f0 --- /dev/null +++ b/blink/internal/fixer/rules/slevomat_php_useless_parentheses.go @@ -0,0 +1,395 @@ +package rules + +import ( + "slices" + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/fixer" + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// Slevomat: https://github.com/slevomat/coding-standard/blob/master/SlevomatCodingStandard/Sniffs/PHP/UselessParenthesesSniff.php +// +// SlevomatUselessParentheses removes parentheses that change nothing: around +// a ternary condition, a case value, a variable or call, a string, an +// expression of one operator group, or "new" (ignoreComplexTernaryConditions, +// enableCheckAroundNew). +type SlevomatUselessParentheses struct { + ignoreComplexTernary bool + checkAroundNew bool +} + +func (SlevomatUselessParentheses) Name() string { + return `SlevomatCodingStandard\Sniffs\PHP\UselessParenthesesSniff` +} + +func (SlevomatUselessParentheses) SourceURL() string { + return fixer.SourceURLFor(SlevomatUselessParentheses{}.Name()) +} + +func (r SlevomatUselessParentheses) WithConfig(config map[string]any) fixer.Fixer { + if v, ok := config["ignoreComplexTernaryConditions"].(bool); ok { + r.ignoreComplexTernary = v + } + if v, ok := config["enableCheckAroundNew"].(bool); ok { + r.checkAroundNew = v + } + return r +} + +// slvupOperatorGroups are the sniff's OPERATORS with their OPERATOR_GROUPS. +var slvupOperatorGroups = map[string]int{ + "**": 1, "*": 2, "/": 2, "%": 3, "+": 4, "-": 4, ".": 5, +} + +// slvupComparison is PHP_CodeSniffer's Tokens::COMPARISON_TOKENS. +var slvupComparison = map[string]bool{ + "==": true, "!=": true, "<>": true, "===": true, "!==": true, "<=": true, ">=": true, + "<": true, ">": true, "<=>": true, "??": true, +} + +// slvupSkippedBefore are the keywords after which "(" is never checked. +var slvupSkippedBefore = map[string]bool{ + "isset": true, "unset": true, "empty": true, "function": true, "fn": true, "use": true, + "class": true, "new": true, "static": true, "exit": true, "die": true, "eval": true, + "list": true, "include": true, "include_once": true, "require": true, "require_once": true, + "match": true, +} + +// slvupOwners are PHP_CodeSniffer's Tokens::PARENTHESIS_OPENERS keywords. +var slvupOwners = map[string]bool{ + "array": true, "list": true, "function": true, "fn": true, "use": true, "class": true, + "while": true, "for": true, "foreach": true, "switch": true, "if": true, "elseif": true, + "catch": true, "declare": true, "match": true, "isset": true, "empty": true, "unset": true, + "eval": true, "exit": true, "die": true, +} + +// slvupSkippedCasts are the casts after which "(" is never checked. +var slvupSkippedCasts = map[string]bool{ + "int": true, "integer": true, "double": true, "float": true, "real": true, "string": true, + "array": true, "object": true, "bool": true, "boolean": true, "unset": true, +} + +func (r SlevomatUselessParentheses) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + kinds := slvcStringKinds(f) + f.eachToken(func(i int) bool { return f.is(i, "(") }, func(open int) int { + closeIdx := f.toks[open].closer + if closeIdx < 0 || f.parenHasOwner(open) { + return 0 + } + before := f.prevEffective(open - 1) + if f.parenSkippedBefore(before) { + return 0 + } + after := f.nextEffective(open+1, len(f.toks)) + if f.parenIsKeyword(after, "clone", "yield", "yield from", "require", "require_once", "include", "include_once") || + f.parenCast(after) == "array" { + return 0 + } + for j := open + 1; j < closeIdx; j++ { + if f.is(j, "=") { + return 0 + } + } + if f.is(f.nextEffective(closeIdx+1, len(f.toks)), "(") { + return 0 + } + if f.identStart(before) >= 0 { + return 0 + } + r.parenTernaryCondition(f, open) + r.parenCaseInSwitch(f, open) + r.parenVariableOrCall(f, open, kinds) + r.parenString(f, open, kinds) + r.parenOperators(f, open) + r.parenNew(f, open) + return 0 + }) + }) +} + +func (r SlevomatUselessParentheses) parenTernaryCondition(f *slvFile, open int) { + closeIdx := f.toks[open].closer + if !f.parenIsInlineThen(f.nextEffective(closeIdx+1, len(f.toks))) { + return + } + for j := open + 1; j < closeIdx; j++ { + if f.parenIsKeyword(j, "and", "or", "xor") { + return + } + } + before := f.prevEffective(open - 1) + if f.is(before, "!") || f.parenIsComparison(before) || f.parenIsBoolean(before) { + return + } + if r.ignoreComplexTernary { + for j := open + 1; j < closeIdx; j++ { + if f.parenIsBoolean(j) || f.toks[j].kind == token.Whitespace && f.toks[j].content == f.eol { + return + } + } + } + start := f.nextEffective(open+1, len(f.toks)) + end := f.prevEffective(closeIdx - 1) + for j := start; j <= end; j++ { + if f.parenIsInlineThen(j) { + return + } + } + f.parenRemove(open, start, end) +} + +func (SlevomatUselessParentheses) parenCaseInSwitch(f *slvFile, open int) { + closeIdx := f.toks[open].closer + if !f.isKeyword(f.prevEffective(open-1), "case") || !f.is(f.nextEffective(closeIdx+1, len(f.toks)), ":") { + return + } + f.parenRemove(open, f.nextEffective(open+1, len(f.toks)), f.prevEffective(closeIdx-1)) +} + +func (SlevomatUselessParentheses) parenVariableOrCall(f *slvFile, open int, kinds []uint8) { + closeIdx := f.toks[open].closer + n := len(f.toks) + start := f.nextEffective(open+1, n) + if start < 0 || f.isKeyword(start, "new") || f.is(start, "(") { + return + } + for j := open + 1; j < closeIdx; j++ { + if f.parenIsOperator(j) { + return + } + } + before := f.prevEffective(open - 1) + if f.isKeyword(before, "case") || f.parenIsBoolean(before) { + return + } + after := f.nextEffective(closeIdx+1, n) + if f.parenIsInlineThen(after) || f.is(after, "(") || f.is(after, ">>") { + return + } + if f.parenIsConstantString(start, kinds) { + return + } + operand := start + if f.is(start, "!") { + operand = f.nextEffective(start+1, n) + } + var end int + if f.isClassKeyword(operand) || f.isVariable(operand) || f.isDollar(operand) || f.isName(operand) { + end = f.identEnd(operand) + if end < 0 && f.isName(operand) && f.is(f.nextEffective(start+1, n), "(") { + end = start + } + if end < 0 { + return + } + for { + next := f.nextEffective(end+1, n) + if !f.is(next, "(") || f.toks[next].closer < 0 { + break + } + end = f.toks[next].closer + } + } else { + next := -1 + for j := operand + 1; j < n; j++ { + if f.is(j, "(") { + next = j + break + } + } + if next < 0 || f.toks[next].closer < 0 { + return + } + end = f.toks[next].closer + } + if f.nextEffective(end+1, n) != closeIdx { + return + } + f.parenRemove(open, start, end) +} + +func (SlevomatUselessParentheses) parenString(f *slvFile, open int, kinds []uint8) { + closeIdx := f.toks[open].closer + str := f.nextEffective(open+1, len(f.toks)) + if !f.parenIsConstantString(str, kinds) || f.nextEffective(str+1, len(f.toks)) != closeIdx { + return + } + f.parenRemove(open, str, str) +} + +func (SlevomatUselessParentheses) parenOperators(f *slvFile, open int) { + closeIdx := f.toks[open].closer + n := len(f.toks) + if f.isKeyword(f.nextEffective(open+1, n), "new") { + return + } + before := f.prevEffective(open - 1) + after := f.nextEffective(closeIdx+1, n) + if f.is(before, "-") { + if p := f.prevEffective(before - 1); p < 0 || f.toks[p].kind != token.Number { + return + } + } + if f.parenIsBoolean(before) || f.parenIsBoolean(after) || f.is(before, "!") { + return + } + var operators []int + for j := open + 1; j < closeIdx; j++ { + switch { + case f.parenIsInlineThen(j), f.is(j, "??"), f.is(j, "&"), f.is(j, "|"), f.is(j, "^"), + f.is(j, "<<"), f.is(j, ">>"), f.parenIsComparison(j): + return + case f.is(j, "(") && f.toks[j].closer >= 0: + j = f.toks[j].closer + case f.parenIsOperator(j): + operators = append(operators, j) + } + } + if len(operators) == 0 { + return + } + if (!f.is(before, "=") || !f.is(after, ";")) && len(operators) > 1 { + return + } + group := func(i int) int { return slvupOperatorGroups[f.toks[i].orig] } + first, last := operators[0], operators[len(operators)-1] + if f.parenIsOperator(before) { + if group(first) != group(before) { + return + } + if f.is(before, "-") && (f.is(first, "+") || f.is(first, "-")) { + return + } + if f.is(before, "/") && (f.is(first, "/") || f.is(first, "*")) { + return + } + if f.is(before, "%") && f.is(first, "%") { + return + } + } + if f.parenIsOperator(after) && group(last) != group(after) { + return + } + f.parenRemove(open, f.nextEffective(open+1, n), f.prevEffective(closeIdx-1)) +} + +func (r SlevomatUselessParentheses) parenNew(f *slvFile, open int) { + closeIdx := f.toks[open].closer + n := len(f.toks) + if !f.isKeyword(f.nextEffective(open+1, n), "new") { + return + } + after := f.nextEffective(closeIdx+1, n) + closesShortArray := f.is(after, "]") && f.toks[after].closer >= 0 && f.isShortArrayOpen(f.toks[after].closer) + if !f.is(after, ",") && !f.is(after, ";") && !closesShortArray { + if !f.is(after, "->") && !f.is(after, "?->") || !r.checkAroundNew { + return + } + if !f.is(f.prevEffective(closeIdx-1), ")") { + return + } + } + f.parenRemove(open, f.nextEffective(open+1, n), f.prevEffective(closeIdx-1)) +} + +func (f *slvFile) parenRemove(open, start, end int) { + closeIdx := f.toks[open].closer + f.beginChangeset() + f.removeBetweenIncluding(open, start-1) + f.removeBetweenIncluding(end+1, closeIdx) + f.endChangeset() +} + +// parenHasOwner tells a "(" PHP_CodeSniffer gives a parenthesis_owner. +func (f *slvFile) parenHasOwner(open int) bool { + p := f.prevEffective(open - 1) + if f.is(p, "&") { + q := f.prevEffective(p - 1) + return f.isKeyword(q, "function") || f.isKeyword(q, "fn") + } + if p >= 0 && f.toks[p].kind == token.Ident { + q := f.prevEffective(p - 1) + if f.is(q, "&") { + q = f.prevEffective(q - 1) + } + if f.isKeyword(q, "function") { + return true + } + if f.is(q, "->") || f.is(q, "?->") || f.is(q, "::") { + return false + } + } + return p >= 0 && (f.toks[p].kind == token.Keyword || f.toks[p].kind == token.Ident) && + slvupOwners[strings.ToLower(f.toks[p].orig)] +} + +func (f *slvFile) parenSkippedBefore(p int) bool { + if p < 0 { + return false + } + t := f.toks[p] + switch { + case t.kind == token.Ident, f.isVariable(p), f.is(p, ")"), f.is(p, "~"): + return true + case t.kind == token.Keyword: + return slvupSkippedBefore[strings.ToLower(t.orig)] + } + return slvupSkippedCasts[f.parenCast(p)] +} + +// parenCast returns the lowercased type of a cast token, or "". +func (f *slvFile) parenCast(i int) string { + if i < 0 || i >= len(f.toks) || f.toks[i].kind != token.Punct { + return "" + } + v := f.toks[i].orig + if len(v) < 3 || v[0] != '(' || v[len(v)-1] != ')' { + return "" + } + return strings.ToLower(strings.TrimSpace(v[1 : len(v)-1])) +} + +func (f *slvFile) parenIsKeyword(i int, words ...string) bool { + if i < 0 || i >= len(f.toks) || f.toks[i].kind != token.Keyword { + return false + } + v := strings.ToLower(strings.Join(strings.Fields(f.toks[i].orig), " ")) + return slices.Contains(words, v) +} + +func (f *slvFile) parenIsComparison(i int) bool { + return i >= 0 && f.toks[i].kind == token.Punct && slvupComparison[f.toks[i].orig] +} + +// parenIsBoolean tells PHP_CodeSniffer's Tokens::BOOLEAN_OPERATORS. +func (f *slvFile) parenIsBoolean(i int) bool { + return f.is(i, "&&") || f.is(i, "||") || f.parenIsKeyword(i, "and", "or", "xor") +} + +func (f *slvFile) parenIsOperator(i int) bool { + if i < 0 || f.toks[i].kind != token.Punct { + return false + } + _, ok := slvupOperatorGroups[f.toks[i].orig] + return ok +} + +// parenIsInlineThen tells a ternary "?" from a nullable type's. +func (f *slvFile) parenIsInlineThen(i int) bool { + if !f.is(i, "?") { + return false + } + p := f.prevEffective(i - 1) + if p < 0 || f.is(p, "(") || f.is(p, ",") || f.is(p, ":") || f.toks[p].kind == token.AttributeEnd { + return false + } + return !f.parenIsKeyword(p, "public", "protected", "private", "readonly", "static", "var", "const", "final", "abstract") +} + +// parenIsConstantString tells a T_CONSTANT_ENCAPSED_STRING. +func (f *slvFile) parenIsConstantString(i int, kinds []uint8) bool { + return i >= 0 && f.toks[i].kind == token.String && !f.toks[i].heredoc && kinds[i] != slvcDoubleQuoted +} diff --git a/blink/internal/fixer/rules/slevomat_test.go b/blink/internal/fixer/rules/slevomat_test.go index 67f04cfcc2..989c7b2658 100644 --- a/blink/internal/fixer/rules/slevomat_test.go +++ b/blink/internal/fixer/rules/slevomat_test.go @@ -49,7 +49,11 @@ func TestSlevomatFixtures(t *testing.T) { t.Fatalf("%s is not registered", c.Sniff) } if c.Config != nil { - f = f.(fixer.ConfigurableFixer).WithConfig(c.Config) + configurable, ok := f.(fixer.ConfigurableFixer) + if !ok { + t.Fatalf("%s takes no configuration", c.Sniff) + } + f = configurable.WithConfig(c.Config) } input := readFixture(t, filepath.Join(dir, c.File)) expected := input diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/disallowDirectMagicInvokeCallErrors.fixed.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/disallowDirectMagicInvokeCallErrors.fixed.php new file mode 100644 index 0000000000..3dbd6f7b31 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/disallowDirectMagicInvokeCallErrors.fixed.php @@ -0,0 +1,9 @@ +{$propertyName} = $value; +}, $instance, null)($instance, $this->getName(), $value); + +$anything(null, false, true); diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/disallowDirectMagicInvokeCallErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/disallowDirectMagicInvokeCallErrors.php new file mode 100644 index 0000000000..b315d529c1 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/disallowDirectMagicInvokeCallErrors.php @@ -0,0 +1,9 @@ +__invoke(); + +Closure::bind(function ($instance, string $propertyName, $value) : void { + $instance->{$propertyName} = $value; +}, $instance, null)->__invoke($instance, $this->getName(), $value); + +$anything->__invoke(null, false, true); diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/disallowDirectMagicInvokeCallNoErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/disallowDirectMagicInvokeCallNoErrors.php new file mode 100644 index 0000000000..f350b85fa3 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/disallowDirectMagicInvokeCallNoErrors.php @@ -0,0 +1,11 @@ +someMethod(); + + $testNewSelf = new self("foo"); + + $anonClass = new class () extends \BarNamespace\BaseClass implements \ImplementedInterface, \SecondImplementedInterface + { + use \DatabaseTrait; + }; + } + + public function doubleCollonCases($testClass) + { + $constant = $testClass::ACCESS_CONSTANT; + $staticVar = \TypeORM\DB::$variable; + + $user = \MyApp\Models\User::getQuery(); + + $user->where(function (DB $query) { + return \MyApp\Models\User::addNotBlockedToQuery($query); + }); + + $queryParts = [ + \TypeORM\DB::select('id'), + \TypeORM\DB::from(\TypeORM\DB::raw('users')), + \TypeORM\DB::where(\MyApp\Models\User::class, 'active', true), + ]; + + \TypeORM\DB::query('INSERT INTO ...'); + + $this->getModel()::query(); + + parent::doubleCollonCases(); + + return \TypeORM\DB::exec($queryParts); + } + } +} + +namespace BarNamespace { + trait FooTrait + { + use \TotallyDifferentTrait; + } + + class Foo + { + public static function create(): self + { + return new self(); + } + } + + class Boo + { + public static function create(string $class): self + { + return new $class(); + } + } + +} diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/forbiddenClasses.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/forbiddenClasses.php new file mode 100644 index 0000000000..ff53da4c73 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/forbiddenClasses.php @@ -0,0 +1,85 @@ +someMethod(); + + $testNewSelf = new self("foo"); + + $anonClass = new class () extends ForbiddenExtendedClass implements \ImplementedInterface, \SecondImplementedInterface + { + use \FullyQualified\SometTotallyDifferentTrait; + }; + } + + public function doubleCollonCases($testClass) + { + $constant = $testClass::ACCESS_CONSTANT; + $staticVar = DB::$variable; + + $user = UserModel::getQuery(); + + $user->where(function (DB $query) { + return UserModel::addNotBlockedToQuery($query); + }); + + $queryParts = [ + DB::select('id'), + DB::from(DB::raw('users')), + DB::where(UserModel::class, 'active', true), + ]; + + DB::query('INSERT INTO ...'); + + $this->getModel()::query(); + + parent::doubleCollonCases(); + + return DB::exec($queryParts); + } + } +} + +namespace BarNamespace { + trait FooTrait + { + use \SomeTraitB; + } + + class Foo + { + public static function create(): self + { + return new self(); + } + } + + class Boo + { + public static function create(string $class): self + { + return new $class(); + } + } + +} diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingDefaultSettingsErrors.fixed.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingDefaultSettingsErrors.fixed.php new file mode 100644 index 0000000000..4ee3aee014 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingDefaultSettingsErrors.fixed.php @@ -0,0 +1,36 @@ += 7.4 + +function &() { + $a = true; + return $a; +}; + +function &foo() { + $a = true; + return $a; +} + +function ($no, &$a) { + +}; + +function boo($no, &$a) { + +} + +$b = false; +function () use (&$b) { + +}; + +$c = &$b; +$d = [ + &$b, + 1 => &$c, + &$b, +]; + +foreach ([] as &$e) { +} + +fn &(array &$f) => $f; diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingDefaultSettingsErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingDefaultSettingsErrors.php new file mode 100644 index 0000000000..3f04d29bad --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingDefaultSettingsErrors.php @@ -0,0 +1,36 @@ += 7.4 + +function & () { + $a = true; + return $a; +}; + +function & foo() { + $a = true; + return $a; +} + +function ($no, & $a) { + +}; + +function boo($no, & $a) { + +} + +$b = false; +function () use (& $b) { + +}; + +$c = & $b; +$d = [ + & $b, + 1 => & $c, + & $b, +]; + +foreach ([] as & $e) { +} + +fn & (array & $f) => $f; diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingDefaultSettingsNoErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingDefaultSettingsNoErrors.php new file mode 100644 index 0000000000..3308a28427 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingDefaultSettingsNoErrors.php @@ -0,0 +1,39 @@ += 7.4 + +$a = 1 & 0; +$b = $a & $a; + +function &() { + $a = true; + return $a; +}; + +function &foo() { + $a = true; + return $a; +} + +function ($no, &$a) { + +}; + +function boo($no, &$a) { + +} + +$b = false; +function () use (&$b) { + +}; + +$c = &$b; +$d = [ + &$b, + 1 => &$c, + &$b, +]; + +foreach ([] as &$e) { +} + +fn &(array &$f) => $f; diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingModifiedSettingsErrors.fixed.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingModifiedSettingsErrors.fixed.php new file mode 100644 index 0000000000..fa4acf2a0d --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingModifiedSettingsErrors.fixed.php @@ -0,0 +1,34 @@ + & $c, + & $b, +]; + +foreach ([] as & $e) { +} diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingModifiedSettingsErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingModifiedSettingsErrors.php new file mode 100644 index 0000000000..309d075a54 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingModifiedSettingsErrors.php @@ -0,0 +1,34 @@ + &$c, + & $b, +]; + +foreach ([] as & $e) { +} diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingModifiedSettingsNoErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingModifiedSettingsNoErrors.php new file mode 100644 index 0000000000..c96f0dea4d --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/referenceSpacingModifiedSettingsNoErrors.php @@ -0,0 +1,37 @@ + & $c, + & $b, +]; + +foreach ([] as & $e) { +} diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionAdvancedStringTypesErrors.fixed.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionAdvancedStringTypesErrors.fixed.php new file mode 100644 index 0000000000..401f78fc38 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionAdvancedStringTypesErrors.fixed.php @@ -0,0 +1,19 @@ +formCreator->create(['inputs' => array_map(static function (Config $config): array { + return $config->toArray(); + }, $this->config->inputs)]); + \assert($form instanceof Form); +}; + +$z = new ArrayObject(); +\assert($z instanceof \Traversable && $z instanceof \Countable); + +$aa = true; +\assert(\is_bool($aa)); + +$bb = 0; +\assert(\is_int($bb)); diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionErrors.php new file mode 100644 index 0000000000..623da93385 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionErrors.php @@ -0,0 +1,121 @@ +formCreator->create(['inputs' => array_map(static function (Config $config): array { + return $config->toArray(); + }, $this->config->inputs)]); +}; + +$z = new ArrayObject(); +/** @var \Traversable&\Countable $z */ + +/** @var boolean $aa */ +$aa = true; + +/** @var integer $bb */ +$bb = 0; diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionIntegerRangesErrors.fixed.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionIntegerRangesErrors.fixed.php new file mode 100644 index 0000000000..7d01dc5525 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionIntegerRangesErrors.fixed.php @@ -0,0 +1,34 @@ + 0); + +$aa = null; +\assert((\is_int($aa) && $aa > 0) || $aa === null); + +$b = -1; +\assert(\is_int($b) && $b < 0); + +$bb = null; +\assert((\is_int($bb) && $bb < 0) || $bb === null); + +$c = 0; +\assert(\is_int($c) && $c >= 0 && $c <= 100); + +$cc = null; +\assert((\is_int($cc) && $cc >= 0 && $cc <= 100) || $cc === null); + +$d = 0; +\assert(\is_int($d) && $d <= 100); + +$dd = null; +\assert((\is_int($dd) && $dd <= 100) || $dd === null); + +$e = 0; +\assert(\is_int($e) && $e >= 50); + +$ee = null; +\assert((\is_int($ee) && $ee >= 50) || $ee === null); + +$f = 100; +\assert(\is_int($f)); diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionIntegerRangesErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionIntegerRangesErrors.php new file mode 100644 index 0000000000..c2fff00be6 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionIntegerRangesErrors.php @@ -0,0 +1,34 @@ + $c */ +$c = 0; + +/** @var int<0, 100>|null $cc */ +$cc = null; + +/** @var int $d */ +$d = 0; + +/** @var int|null $dd */ +$dd = null; + +/** @var int<50, max> $e */ +$e = 0; + +/** @var int<50, max>|null $ee */ +$ee = null; + +/** @var literal-int $f */ +$f = 100; diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionIntegerRangesNoErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionIntegerRangesNoErrors.php new file mode 100644 index 0000000000..0323e575f1 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionIntegerRangesNoErrors.php @@ -0,0 +1,5 @@ + $a */ +$a = 0; + diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionNoErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionNoErrors.php new file mode 100644 index 0000000000..ac29c8425b --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/requireExplicitAssertionNoErrors.php @@ -0,0 +1,65 @@ + [ + 'b' => [$b], + ], +] = foo(); + +foreach ($foo as [$a]) {} +foreach ( + $foo as [ + $a, + [ + $b, + [$c] + ] + ] +) {} + +[$b] = $a; diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/shortListErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/shortListErrors.php new file mode 100644 index 0000000000..6549f3c6f0 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/shortListErrors.php @@ -0,0 +1,34 @@ + list( + 'b' => list($b), + ), +) = foo(); + +foreach ($foo as list($a)) {} +foreach ( + $foo as list( + $a, + list( + $b, + list($c) + ) + ) +) {} + +list ($b) = $a; diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/shortListNoErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/shortListNoErrors.php new file mode 100644 index 0000000000..ffd0ebbcdd --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/shortListNoErrors.php @@ -0,0 +1,14 @@ += 8.4 + +$response = new Response()->withStatus(200); +$response = (new Response)->withStatus(200); +$ip = new RemoteAddress()?->getIpAddress(); diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesCheckAroundNewErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesCheckAroundNewErrors.php new file mode 100644 index 0000000000..b93cfec02a --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesCheckAroundNewErrors.php @@ -0,0 +1,5 @@ += 8.4 + +$response = (new Response())->withStatus(200); +$response = (new Response)->withStatus(200); +$ip = (new RemoteAddress())?->getIpAddress(); diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesErrors.fixed.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesErrors.fixed.php new file mode 100644 index 0000000000..6c4d011eae --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesErrors.fixed.php @@ -0,0 +1,77 @@ +a; + $x = $this->$$parameter; + $x = $this->{'a'}; + $x = $$parameter; + $x = $this->${'a'}[0]->$$b[1][2]::$c[3][4][5]->{" $d"}; + $x = $this->${'a'}[0]->$$b[1][2]::$c[3][4][5]->{" $d"}(); + $x = $this->${'a'}[0]->$$b[1][2]::$c[3][4][5]->{" $d"}()()()(); + $x = !$this->${'a'}[0]->$$b[1][2]::$c[3][4][5]->{" $d"}()()()(); + $x = isset($xxx); + $x = !isset($xxx); + $x = empty($xxx); + $x = !empty($xxx); + $x = ! in_array($foo, ['bar', 'foo']); + $x = intval($foo); + } + +} + +$x = $y !== null ? true : false; +$a = $b ? 1 : 0; +$c = $d ? 1 : 0; + +switch (true) { + case $boo: + case $boo === true: + case $boo ? true : false: + case $boo ? true : false: +} + +function () { + return [ + 'a' => 'aa', + ]; +}; + +$x = $x + 1; + +$x = $y + $yy - $z; +$x = $y * $yy / $z; +$x = 100 / 50 * 100; +$x = $a + $b * 3; +$x = $b + 100 - $c; +$x = $b * 100 / $c; + +echo 'Hello' . $foo ? ' There' : $fn(); +echo 'Hello' . ($foo ? ' There' : $fn()); + +$remoteAddress = new RemoteAddress(); +$remotedAddresses = [ + new RemoteAddress() +]; +$remotedAddresses = [ + new RemoteAddress(), +]; + +function () { + return [ + 'a' => 'aa' . 'bb', + ]; +}; diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesErrors.php new file mode 100644 index 0000000000..90724db1f4 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesErrors.php @@ -0,0 +1,77 @@ +a); + $x = ($this->$$parameter); + $x = ($this->{'a'}); + $x = ($$parameter); + $x = ($this->${'a'}[0]->$$b[1][2]::$c[3][4][5]->{" $d"}); + $x = ($this->${'a'}[0]->$$b[1][2]::$c[3][4][5]->{" $d"}()); + $x = ($this->${'a'}[0]->$$b[1][2]::$c[3][4][5]->{" $d"}()()()()); + $x = (!$this->${'a'}[0]->$$b[1][2]::$c[3][4][5]->{" $d"}()()()()); + $x = (isset($xxx)); + $x = (!isset($xxx)); + $x = (empty($xxx)); + $x = (!empty($xxx)); + $x = ! (in_array($foo, ['bar', 'foo'])); + $x = (intval($foo)); + } + +} + +$x = ($y !== null) ? true : false; +$a = ($b) ? 1 : 0; +$c = ( $d ) ? 1 : 0; + +switch (true) { + case ($boo): + case ($boo === true): + case ($boo ? true : false): + case ($boo) ? true : false: +} + +function () { + return [ + 'a' => ('aa'), + ]; +}; + +$x = ($x + 1); + +$x = ($y + $yy) - $z; +$x = ($y * $yy) / $z; +$x = ((100 / 50) * 100); +$x = ($a + $b * 3); +$x = $b + (100 - $c); +$x = $b * (100 / $c); + +echo 'Hello' . ($foo) ? ' There' : $fn(); +echo 'Hello' . (($foo) ? ' There' : $fn()); + +$remoteAddress = (new RemoteAddress()); +$remotedAddresses = [ + (new RemoteAddress()) +]; +$remotedAddresses = [ + (new RemoteAddress()), +]; + +function () { + return [ + 'a' => ('aa' . 'bb'), + ]; +}; diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesLiveCoding.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesLiveCoding.php new file mode 100644 index 0000000000..b642f6bf05 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesLiveCoding.php @@ -0,0 +1,5 @@ += 99.0 + +// Live coding/parse error. +// This must be the last test in the file. +if ($a = 1 diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesNoErrors.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesNoErrors.php new file mode 100644 index 0000000000..c7c332e8d8 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesNoErrors.php @@ -0,0 +1,187 @@ += 8.0 + +function doSomething($parameter) { + +} + +while ($current) { + +} + +if ($true) { + +} + +$a = 10 ? 1 : 0; + +$b = $c + $d ? 1 : 0; + +$closure = function ($parameter) use ($inheritedVariable) { + +}; + +$closure(10); + +max($a, $b); + +if (isset($a)) { + +} + +if (empty($a)) { + +} + +unset($a); + +$class = new class ($number) { +}; + +(bool) $a; + +$b = $array['function']($parameter); + +$foo = new Foo(); +new self($a); +new static($b); +new parent($c); + +$z = ($a ? '0' : '1') ? '2' : '3'; +$zzz = !($a) ? true : false; +$zzzz = null !== ($a = 'a') ? true : false; +$zzzzz = null !== ($a === 'a') ? true : false; + +exit($a); +die($a); + +(function ($b): void { + // Do something +})($b); + +eval($c); + +list($c) = []; + +switch (true) { + case !($boo !== null): +} + +class ClassWithClosure +{ + private $closure; + + public function __construct() + { + $this->closure = function () { + echo 123; + }; + + ($this->closure)(); + } +} + +$a = $b / (100 + $c); +$a = (100 - $b) * $c; +$a = ('100' . '000') * $c; + +$a = 'a' . '/' . (32 - ($b * 8)); + +$var = $foo && ($bar > 0 || $baz > 0) ? true : false; + +include($file); +include_once($file); +require($file); +require_once($file); + +(require 'file.php')(); + +if ($a + && (null === $b || null === $c)) { +} + +$a = ($b * $c) - $d; +$a = ($b * 60 * 60) + ($c * 60) + $d; + +$c = (clone $a->foo())->bar($b); + +$d = (10 - ($x % 10)) % 10; +$e = (($x % 10) - 10) % 10; +$f = !($x % 10); + +$x = (object) ([ + 'a', +] + $defaults('b')); + +function () { + $y = (yield whatever()) ?? $y; + $y = (yield from whatever()) ?? $y; +}; + +$x = ($y - $yy) ** $z; + +$hue = 60 * (($blueFraction - $redFraction) / $delta + 2); + +if ($hit === true || (is_array($hit) && count(array_filter($hit)) >= count($keys) * 0.5)) { +} + +$hitRatio = (int) round($hitCount / ($loadCount / 100 ?: 1), 1); + +$a = 10 + 1 - (5 + 4); + +$a = 10 / (5 / 2); + +$a = 10 / (5 * 2); + +$a = 10 - (5 - 2); + +$a = 6 % (5 % 3); + +pow(10, -($x + 1)); + +if (! ($i === $j - 1)) { +} + +function ($value) { + return ($value & $value - 1) === 0; +}; + +$x = fn ($a, $b) => $a . $b; + +(static function () : void { + echo $_SERVER['argv'][1]; +})(); + +(static function () : void { + echo $_SERVER['argv'][1 + 1]; +})(); + +$output = (($a and $b) ? 'yes' : 'nope'); +$output = (($a or $b) ? 'yes' : 'nope'); +$output = (($a xor $b) ? 'yes' : 'nope'); + +$whatever = (null !== $a = $b->call()); + +$key = ((array) $table->getPrimaryKey())[0]; + +match ($code) { + 1 => 'one', + 2 => 'owo', +}; + +$char = (0xF0 & ord('1')) >> 4; + +$char = ($ord - 0xc0 << 6) + ord($char[1]) - 0x80; +$char = ($ord - 0xc0 >> 6) + ord($char[1]) - 0x80; + +$anotherObject = new ($object->getClassName()); + +echo 'Hello' . ($foo ? ' There' : $fn()); + +doSomething((new Response())); + +echo ~(1 - 1); + +// Must be last +return true + ? 100 + : (int) ((100 <=> 50) * 100); diff --git a/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesNoErrorsWithIgnoredComplexTernaryConditions.php b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesNoErrorsWithIgnoredComplexTernaryConditions.php new file mode 100644 index 0000000000..d293c2955e --- /dev/null +++ b/blink/internal/fixer/rules/testdata/slevomat/PHP/uselessParenthesesNoErrorsWithIgnoredComplexTernaryConditions.php @@ -0,0 +1,9 @@ += 8.0 + +use Foo\{ Boo, Doo }; + +foo(); + +$foo = foo(); + +function () { + return false; +}; + +$x = 'x'; + +$anonymous = function () { + return null; +}; + +fn ($a) => $a; + +for (;;) { + +} + +new class extends Whatever { + +}; + +$fooPropertyValue = $foo->{$fooProperty}; + +function witMatch($a) +{ + return match ($a) { + 'foo' => 'bar', + }; +} diff --git a/blink/internal/fixer/rules/testdata/slevomat/cases.json b/blink/internal/fixer/rules/testdata/slevomat/cases.json index 91952d9c30..6ebe52abf8 100644 --- a/blink/internal/fixer/rules/testdata/slevomat/cases.json +++ b/blink/internal/fixer/rules/testdata/slevomat/cases.json @@ -92,5 +92,32 @@ {"sniff": "SlevomatCodingStandard\\Sniffs\\Attributes\\DisallowMultipleAttributesPerLineSniff", "file": "Attributes/disallowedMultipleAttributesPerLinesInvalidAttribute.php"}, {"sniff": "SlevomatCodingStandard\\Sniffs\\Attributes\\RequireAttributeAfterDocCommentSniff", "file": "Attributes/requireAttributeAfterDocCommentNoErrors.php"}, {"sniff": "SlevomatCodingStandard\\Sniffs\\Attributes\\RequireAttributeAfterDocCommentSniff", "file": "Attributes/requireAttributeAfterDocCommentErrors.php"}, - {"sniff": "SlevomatCodingStandard\\Sniffs\\Attributes\\RequireAttributeAfterDocCommentSniff", "file": "Attributes/requireAttributeAfterDocCommentInvalidAttribute.php"} + {"sniff": "SlevomatCodingStandard\\Sniffs\\Attributes\\RequireAttributeAfterDocCommentSniff", "file": "Attributes/requireAttributeAfterDocCommentInvalidAttribute.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\DisallowDirectMagicInvokeCallSniff", "file": "PHP/disallowDirectMagicInvokeCallNoErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\DisallowDirectMagicInvokeCallSniff", "file": "PHP/disallowDirectMagicInvokeCallErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\ForbiddenClassesSniff", "file": "PHP/forbiddenClasses.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\ForbiddenClassesSniff", "file": "PHP/forbiddenClasses.php", "config": {"forbiddenClasses": {"\\UserModel": "\\MyApp\\Models\\User", "\\DB": "\\TypeORM\\DB", "\\SomeClass": "NULL", "\\FullyQualified\\Nested\\SomeClass": "\\FullyQualified\\SomeClass"}, "forbiddenExtends": {"\\FooNamespace\\ForbiddenExtendedClass": "\\BarNamespace\\BaseClass"}, "forbiddenInterfaces": {"\\FooNamespace\\SecondImplementedInterface": "\\BarNamespace\\SecondImplementedInterface", "\\SecondImplementedInterface": null, "\\ThirdImplementedInterface": ""}, "forbiddenTraits": {"\\SomeTraitB": "\\TotallyDifferentTrait", "\\FullyQualified\\SometTotallyDifferentTrait": "\\DatabaseTrait"}}, "variant": "configured"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\ReferenceSpacingSniff", "file": "PHP/referenceSpacingDefaultSettingsNoErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\ReferenceSpacingSniff", "file": "PHP/referenceSpacingDefaultSettingsErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\ReferenceSpacingSniff", "file": "PHP/referenceSpacingModifiedSettingsNoErrors.php", "config": {"spacesCountAfterReference": 2}}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\ReferenceSpacingSniff", "file": "PHP/referenceSpacingModifiedSettingsErrors.php", "config": {"spacesCountAfterReference": 2}}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\RequireExplicitAssertionSniff", "file": "PHP/requireExplicitAssertionNoErrors.php", "config": {"enableIntegerRanges": false, "enableAdvancedStringTypes": false}}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\RequireExplicitAssertionSniff", "file": "PHP/requireExplicitAssertionErrors.php", "config": {"enableIntegerRanges": false, "enableAdvancedStringTypes": false}}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\RequireExplicitAssertionSniff", "file": "PHP/requireExplicitAssertionIntegerRangesNoErrors.php", "config": {"enableIntegerRanges": true, "enableAdvancedStringTypes": false}}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\RequireExplicitAssertionSniff", "file": "PHP/requireExplicitAssertionIntegerRangesErrors.php", "config": {"enableIntegerRanges": true, "enableAdvancedStringTypes": false}}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\RequireExplicitAssertionSniff", "file": "PHP/requireExplicitAssertionAdvancedStringTypesErrors.php", "config": {"enableIntegerRanges": false, "enableAdvancedStringTypes": true}}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\RequireNowdocSniff", "file": "PHP/requireNowdocNoErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\RequireNowdocSniff", "file": "PHP/requireNowdocErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\ShortListSniff", "file": "PHP/shortListNoErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\ShortListSniff", "file": "PHP/shortListErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\TypeCastSniff", "file": "PHP/typeCastNoErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\TypeCastSniff", "file": "PHP/typeCastErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\UselessParenthesesSniff", "file": "PHP/uselessParenthesesNoErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\UselessParenthesesSniff", "file": "PHP/uselessParenthesesErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\UselessParenthesesSniff", "file": "PHP/uselessParenthesesCheckAroundNewErrors.php", "config": {"enableCheckAroundNew": false}, "variant": "disabled"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\UselessParenthesesSniff", "file": "PHP/uselessParenthesesCheckAroundNewErrors.php", "config": {"enableCheckAroundNew": true}, "variant": "enabled"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\UselessParenthesesSniff", "file": "PHP/uselessParenthesesNoErrorsWithIgnoredComplexTernaryConditions.php", "config": {"ignoreComplexTernaryConditions": true}}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\UselessParenthesesSniff", "file": "PHP/uselessParenthesesLiveCoding.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\UselessSemicolonSniff", "file": "PHP/uselessSemicolonNoErrors.php"}, + {"sniff": "SlevomatCodingStandard\\Sniffs\\PHP\\UselessSemicolonSniff", "file": "PHP/uselessSemicolonErrors.php"} ]