diff --git a/README.md b/README.md index ee8998227d..8af585537b 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ 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 | 54 | 114 | 47% | +| PHP_CodeSniffer | 66 | 114 | 57% | | slevomat | 28 | 132 | 21% | -| **total** | **398** | **562** | **70%** | +| **total** | **410** | **562** | **72%** | diff --git a/blink/README.md b/blink/README.md index 46ea1724aa..a1fbcfaae6 100644 --- a/blink/README.md +++ b/blink/README.md @@ -24,10 +24,10 @@ those expectations can differ from upstream's `.inc.fixed`. Regenerate them with |---|---:|---:|---:| | PHP-CS-Fixer | 282 | 282 | 100% | | Symplify | 34 | 34 | 100% | -| PHP_CodeSniffer | 54 | 114 | 47% | -| **total** | **370** | **430** | **86%** | +| PHP_CodeSniffer | 66 | 114 | 57% | +| **total** | **382** | **430** | **88%** | -blink runs 404 rules in all, its own extras included. +blink runs 416 rules in all, its own extras included. ### slevomat sniffs diff --git a/blink/internal/fixer/rules/class_instantiation.go b/blink/internal/fixer/rules/class_instantiation.go new file mode 100644 index 0000000000..8e65123966 --- /dev/null +++ b/blink/internal/fixer/rules/class_instantiation.go @@ -0,0 +1,78 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/PSR12/Sniffs/Classes/ClassInstantiationSniff.php +// +// ClassInstantiation adds the missing parentheses to "new Foo" -> "new Foo()". +// Anonymous classes are left alone. +type ClassInstantiation struct{} + +func (ClassInstantiation) Name() string { + return `PHP_CodeSniffer\Standards\PSR12\Sniffs\Classes\ClassInstantiationSniff` +} + +func (ClassInstantiation) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/PSR12/Sniffs/Classes/ClassInstantiationSniff.php" +} + +func (ClassInstantiation) Fix(s *tokens.Stream) bool { + changed := false + for i := 0; i < s.Len(); i++ { + if t := s.At(i); t.Kind != token.Keyword || !strings.EqualFold(t.Value, "new") { + continue + } + end := classInstantiationNameEnd(s, i) + if end < 0 || s.At(end).Kind == token.Punct && s.At(end).Value == "(" { + continue + } + prev := phpcsPrevNonEmpty(s, end-1) + if prev <= i { + continue + } + s.InsertSliceAt(prev+1, []token.Token{{Kind: token.Punct, Value: "("}, {Kind: token.Punct, Value: ")"}}) + changed = true + } + return changed +} + +// classInstantiationNameEnd is the first token after the class name of the +// "new" at i, -1 for an anonymous class or when the file ends first. +func classInstantiationNameEnd(s *tokens.Stream, i int) int { + for j := i + 1; j < s.Len(); j++ { + t := s.At(j) + switch { + case isPhpcsEmpty(t), t.Kind == token.Ident, t.Kind == token.Variable: + continue + case t.Kind == token.Keyword: + switch strings.ToLower(t.Value) { + case "static": + continue + case "class", "readonly": + return -1 + } + return j + case t.Kind == token.AttributeStart: + return -1 + case t.Kind == token.Punct: + switch t.Value { + case `\`, "$", "->", "?->", "::": + continue + case "[", "{": + m := s.MatchForward(j) + if m < 0 { + return -1 + } + j = m + continue + } + } + return j + } + return -1 +} diff --git a/blink/internal/fixer/rules/closing_declaration_comment.go b/blink/internal/fixer/rules/closing_declaration_comment.go new file mode 100644 index 0000000000..e6a7c0afc9 --- /dev/null +++ b/blink/internal/fixer/rules/closing_declaration_comment.go @@ -0,0 +1,184 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/ClosingDeclarationCommentSniff.php +// +// ClosingDeclarationComment puts "//end class", "//end foo()" and the like +// right after the closing brace of a class, interface, trait, enum or named +// function. A matching comment further down is pulled up to the brace. +type ClosingDeclarationComment struct{} + +func (ClosingDeclarationComment) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\ClosingDeclarationCommentSniff` +} + +func (ClosingDeclarationComment) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/ClosingDeclarationCommentSniff.php" +} + +func (ClosingDeclarationComment) Fix(s *tokens.Stream) bool { + changed := false + eol := phpcsEolChar(s) + for i := 0; i < s.Len(); i++ { + closeIdx, comment := closingDeclaration(s, i) + if closeIdx < 0 { + continue + } + if closingCommentFix(s, closeIdx, comment, eol) { + changed = true + } + } + return changed +} + +// closingDeclaration returns the closing brace and expected comment of the +// declaration whose keyword is at i, closeIdx -1 when i starts none. +func closingDeclaration(s *tokens.Stream, i int) (closeIdx int, comment string) { + t := s.At(i) + if t.Kind != token.Keyword { + return -1, "" + } + kw := strings.ToLower(t.Value) + if kw == "function" { + name := phpcsNextNonEmpty(s, i+1) + if name < s.Len() && s.At(name).Value == "&" { + name = phpcsNextNonEmpty(s, name+1) + } + if name >= s.Len() || s.At(name).Kind != token.Ident { + return -1, "" + } + _, c, ok := phpcsFunctionBody(s, i) + if !ok || inInterfaceBody(s, i) { + return -1, "" + } + return c, "//end " + s.At(name).Value + "()" + } + if !cdIsClassy(s, i) || (kw == "class" && anonClassNewIndex(s, i) >= 0) { + return -1, "" + } + open := phpcsOOScopeOpener(s, i) + if open < 0 { + return -1, "" + } + c := s.MatchForward(open) + if c < 0 { + return -1, "" + } + return c, "//end " + kw +} + +// inInterfaceBody reports whether i lies inside an interface body, at any depth. +func inInterfaceBody(s *tokens.Stream, i int) bool { + depth := 0 + for j := i - 1; j >= 0; j-- { + if s.At(j).Kind != token.Punct { + continue + } + switch s.At(j).Value { + case "}": + depth++ + case "{": + if depth > 0 { + depth-- + continue + } + for k := j - 1; k >= 0; k-- { + if phpcsOOScopeOpener(s, k) == j { + if strings.EqualFold(s.At(k).Value, "interface") { + return true + } + break + } + if s.At(k).Value == "{" || s.At(k).Value == "}" || s.At(k).Value == ";" { + break + } + } + } + } + return false +} + +// closingCommentFix makes the token right after the brace at c the comment. +func closingCommentFix(s *tokens.Stream, c int, comment, eol string) bool { + if n := c + 1; n < s.Len() && isPhpcsComment(s.At(n)) { + if phpRtrim(s.At(n).Value) == comment { + return false + } + setClosingComment(s, n, comment, eol) + return true + } + next := c + 1 + for next < s.Len() && s.At(next).Kind == token.Whitespace { + next++ + } + if next < s.Len() && s.At(next).Kind == token.Comment && phpRtrim(s.At(next).Value) == comment { + for k := next - 1; k > c; k-- { + s.RemoveAt(k) + } + setClosingComment(s, c+1, comment, eol) + return true + } + s.InsertAt(c+1, token.Token{Kind: token.Comment, Value: comment}) + swallowLineIntoComment(s, c+1, eol) + return true +} + +// swallowLineIntoComment mirrors the next pass after a comment is glued to a +// brace: PHP lexes the rest of the line into that "//" comment, and the sniff +// then replaces the whole comment with itself plus eol. Trailing whitespace +// alone is left as is, since the comment then still matches. +func swallowLineIntoComment(s *tokens.Stream, n int, eol string) { + end, rest, cut := n+1, "", -1 + for ; end < s.Len(); end++ { + t := s.At(end) + if t.Kind == token.CloseTag { + break + } + if k := strings.IndexAny(t.Value, "\r\n"); k >= 0 && t.Kind == token.Whitespace { + rest += t.Value[:k] + cut = k + break + } + rest += t.Value + } + if phpRtrim(rest) == "" { + return + } + if cut >= 0 { + s.SetValue(end, s.At(end).Value[cut:]) + } + for k := end - 1; k > n; k-- { + s.RemoveAt(k) + } + if cut < 0 { + s.InsertAt(n+1, token.Token{Kind: token.Whitespace, Value: eol}) + } +} + +// setClosingComment replaces the comment at n the way PHP_CodeSniffer +// replaces it with comment + eol: its own newline (part of a line comment +// there) is kept, any other comment gains one. +func setClosingComment(s *tokens.Stream, n int, comment, eol string) { + keepsNewline := isLineComment(s.At(n)) && n+1 < s.Len() && s.At(n+1).Kind == token.Whitespace && + strings.HasPrefix(s.At(n+1).Value, eol) + s.SetValue(n, comment) + if !keepsNewline { + s.InsertAt(n+1, token.Token{Kind: token.Whitespace, Value: eol}) + } +} + +// isPhpcsComment reports whether PHP_CodeSniffer tokenizes t as T_COMMENT. +func isPhpcsComment(t token.Token) bool { + return t.Kind == token.Comment && !strings.HasPrefix(t.Value, "#[") && !isPhpcsAnnotationComment(t.Value) +} + +// phpRtrim is PHP's rtrim() with its default character list. +func phpRtrim(v string) string { + return strings.TrimRight(v, " \t\n\r\x00\x0B") +} diff --git a/blink/internal/fixer/rules/doc_comment_alignment.go b/blink/internal/fixer/rules/doc_comment_alignment.go new file mode 100644 index 0000000000..034520cc53 --- /dev/null +++ b/blink/internal/fixer/rules/doc_comment_alignment.go @@ -0,0 +1,155 @@ +package rules + +import ( + "slices" + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/DocCommentAlignmentSniff.php +// +// DocCommentAlignment aligns the stars of a declaration or file docblock one +// column right of its "/**" and puts one space after each star: none or +// several before a tag become one, a star glued to text gets one. +type DocCommentAlignment struct{} + +func (DocCommentAlignment) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\DocCommentAlignmentSniff` +} + +func (DocCommentAlignment) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/DocCommentAlignmentSniff.php" +} + +func (DocCommentAlignment) Fix(s *tokens.Stream) bool { + changed := false + eol := phpcsEolChar(s) + for i := 0; i < s.Len(); i++ { + if s.At(i).Kind != token.DocComment || !docAlignmentTarget(s, i) { + continue + } + if fixed := alignDocComment(s.At(i).Value, eol, phpcsColumn(s, i)+1); fixed != s.At(i).Value { + s.SetValue(i, fixed) + changed = true + } + } + return changed +} + +// docAlignmentTarget reports whether the docblock at i documents a declaration +// the sniff checks, or is a file comment right after "= 0 && isPhpcsEmpty(s.At(p)) { + p-- + } + return p >= 0 && s.At(p).Kind == token.OpenTag && strings.EqualFold(s.At(p).Value, "= 0; j-- { + switch s.At(j).Value { + case "}": + depth++ + case "{": + if depth > 0 { + depth-- + continue + } + for k := j - 1; k >= 0 && s.At(k).Value != ";" && s.At(k).Value != "}" && s.At(k).Value != "{"; k-- { + if phpcsOOScopeOpener(s, k) == j { + return strings.EqualFold(s.At(k).Value, "enum") + } + } + return false + } + } + return false +} + +// alignDocComment fixes the star columns and star spacing of doc, following +// PHP_CodeSniffer's docblock tokenizer: the open tag is the leading "/*" run, +// the close tag the trailing one, and each line after the first is indent, +// optional "*", padding, then a tag or text. +func alignDocComment(doc, eol string, required int) string { + open := len(doc) - len(strings.TrimLeft(doc, "/*")) + if open == len(doc) { + return doc + } + rest := doc[open:] + body := strings.TrimRight(rest, "/*") + closeTag := rest[len(body):] + lines := strings.Split(body, eol) + padding := strings.Repeat(" ", required-1) + for n := 1; n < len(lines); n++ { + line := lines[n] + indent := line[:len(line)-len(strings.TrimLeft(line, " \t"))] + content := line[len(indent):] + if content == "" { + // the close tag, alone on the last line + if n == len(lines)-1 && strings.TrimSpace(closeTag) != "" && 1+expandedWidth(indent, 0) != required { + lines[n] = padding + } + continue + } + if content[0] != '*' { + continue + } + if 1+expandedWidth(indent, 0) != required { + indent = padding + } + after := content[1:] + gap := after[:len(after)-len(strings.TrimLeft(after, " \t"))] + text := after[len(gap):] + switch { + case after == "": + // an empty line + case gap == "": + after = " " + after + case docTagStart(text) && gap != " ": + after = " " + text + } + lines[n] = indent + "*" + after + } + return doc[:open] + strings.Join(lines, eol) + closeTag +} + +// docTagStart reports whether text starts with a docblock tag as PHP_CodeSniffer +// tokenizes one: "@" plus non-space characters, other than "@phpcs:". +func docTagStart(text string) bool { + return len(text) > 1 && text[0] == '@' && !strings.ContainsAny(text[1:2], " \t\r\n") && + !strings.HasPrefix(strings.ToLower(text), "@phpcs:") +} + +// phpcsColumn is the 1-based column PHP_CodeSniffer gives the token at i, tabs +// expanded to ECS's tab width of 4. +func phpcsColumn(s *tokens.Stream, i int) int { + var parts []string + for j := i - 1; j >= 0; j-- { + v := s.At(j).Value + if nl := strings.LastIndexAny(v, "\r\n"); nl >= 0 { + parts = append(parts, v[nl+1:]) + break + } + parts = append(parts, v) + } + slices.Reverse(parts) + return 1 + expandedWidth(strings.Join(parts, ""), 0) +} diff --git a/blink/internal/fixer/rules/double_quote_usage.go b/blink/internal/fixer/rules/double_quote_usage.go new file mode 100644 index 0000000000..61785d0671 --- /dev/null +++ b/blink/internal/fixer/rules/double_quote_usage.go @@ -0,0 +1,62 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// doubleQuoteEscapes keep a double-quoted string as is: escape sequences single +// quotes cannot express, and a literal "'". +var doubleQuoteEscapes = []string{ + `\0`, `\1`, `\2`, `\3`, `\4`, `\5`, `\6`, `\7`, + `\n`, `\r`, `\f`, `\t`, `\v`, `\x`, `\b`, `\e`, `\u`, `'`, +} + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Strings/DoubleQuoteUsageSniff.php +// +// DoubleQuoteUsage turns a double-quoted string without interpolation or +// special escapes into a single-quoted one: "abc" -> 'abc', "\"x\$" -> '"x$'. +type DoubleQuoteUsage struct{} + +func (DoubleQuoteUsage) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Strings\DoubleQuoteUsageSniff` +} + +func (DoubleQuoteUsage) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Strings/DoubleQuoteUsageSniff.php" +} + +func (DoubleQuoteUsage) Fix(s *tokens.Stream) bool { + changed := false + for i := range s.Len() { + t := s.At(i) + if t.Kind != token.String || t.Part != token.Whole { + continue + } + // PHP_CodeSniffer splits a lowercase "b" prefix off as a binary cast; + // with "B" the string keeps its prefix and is not double-quoted to it + prefix, v := token.SplitBinaryPrefix(t.Value) + if prefix == "B" || len(v) < 2 || v[0] != '"' || v[len(v)-1] != '"' { + continue + } + if slicesContainsSub(v, doubleQuoteEscapes) { + continue + } + inner := strings.ReplaceAll(v[1:len(v)-1], `\"`, `"`) + inner = strings.ReplaceAll(inner, `\$`, `$`) + s.SetValue(i, prefix+"'"+inner+"'") + changed = true + } + return changed +} + +func slicesContainsSub(v string, subs []string) bool { + for _, sub := range subs { + if strings.Contains(v, sub) { + return true + } + } + return false +} diff --git a/blink/internal/fixer/rules/line_endings.go b/blink/internal/fixer/rules/line_endings.go new file mode 100644 index 0000000000..996b579950 --- /dev/null +++ b/blink/internal/fixer/rules/line_endings.go @@ -0,0 +1,63 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/fixer" + "github.com/ecsphp/ecs-src/blink/internal/lexer" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/Files/LineEndingsSniff.php +// +// LineEndings rewrites every line ending to EolChar ("\n" by default) when the +// file's first line ending differs. Like the sniff, it trims all trailing CR/LF +// of each line and also terminates the last line. +type LineEndings struct { + EolChar string +} + +func (LineEndings) Name() string { + return `PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineEndingsSniff` +} + +func (LineEndings) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/Files/LineEndingsSniff.php" +} + +func (f LineEndings) WithConfig(config map[string]any) fixer.Fixer { + if v, ok := config["eolChar"].(string); ok { + f.EolChar = strings.NewReplacer(`\r`, "\r", `\n`, "\n").Replace(v) + } + return f +} + +func (f LineEndings) Fix(s *tokens.Stream) bool { + want := f.EolChar + if want == "" { + want = "\n" + } + if !phpcsHasOpenTag(s, true) { + return false + } + found := phpcsEolChar(s) + text := s.Render() + // a one-line file without a line ending reads as "\n" and is left alone + if found == want || (found == "\n" && !strings.Contains(text, "\n")) { + return false + } + lines := strings.Split(text, found) + var b strings.Builder + for i, line := range lines { + if i == len(lines)-1 && line == "" { + break + } + b.WriteString(strings.TrimRight(line, "\r\n")) + b.WriteString(want) + } + if b.String() == text { + return false + } + s.ReplaceRange(0, s.Len()-1, lexer.Lex(b.String())) + return true +} diff --git a/blink/internal/fixer/rules/object_operator_spacing.go b/blink/internal/fixer/rules/object_operator_spacing.go new file mode 100644 index 0000000000..0f48f10e99 --- /dev/null +++ b/blink/internal/fixer/rules/object_operator_spacing.go @@ -0,0 +1,62 @@ +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" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/ObjectOperatorSpacingSniff.php +// +// ObjectOperatorSpacing removes whitespace around "->", "?->" and "::": +// "$a -> b" -> "$a->b". With IgnoreNewlines a line break on either side is kept. +type ObjectOperatorSpacing struct { + IgnoreNewlines bool +} + +func (ObjectOperatorSpacing) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ObjectOperatorSpacingSniff` +} + +func (ObjectOperatorSpacing) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/ObjectOperatorSpacingSniff.php" +} + +func (f ObjectOperatorSpacing) WithConfig(config map[string]any) fixer.Fixer { + if v, ok := config["ignoreNewlines"].(bool); ok { + f.IgnoreNewlines = v + } + return f +} + +func (f ObjectOperatorSpacing) Fix(s *tokens.Stream) bool { + changed := false + for i := 0; i < s.Len(); i++ { + if t := s.At(i); t.Kind != token.Punct || (t.Value != "->" && t.Value != "?->" && t.Value != "::") { + continue + } + // before: a line comment's newline is part of the comment for PHPCS, so + // whitespace after one starts a new line + if w := i - 1; phpcsWhitespaceAt(s, w) { + newline := strings.ContainsAny(s.At(w).Value, "\r\n") || (w > 0 && isLineComment(s.At(w-1))) + if !newline || !f.IgnoreNewlines { + if dropPhpcsWhitespace(s, w) { + i-- + } + changed = true + } + } + if i+2 >= s.Len() { + continue + } + if w := i + 1; s.At(w).Kind == token.Whitespace { + if !strings.ContainsAny(s.At(w).Value, "\r\n") || !f.IgnoreNewlines { + s.RemoveAt(w) + changed = true + } + } + } + return changed +} diff --git a/blink/internal/fixer/rules/phpcs_operator.go b/blink/internal/fixer/rules/phpcs_operator.go new file mode 100644 index 0000000000..874f3c188b --- /dev/null +++ b/blink/internal/fixer/rules/phpcs_operator.go @@ -0,0 +1,481 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// phpcsOperatorPuncts are the operator tokens Squiz OperatorSpacing registers: +// PHP_CodeSniffer's COMPARISON_TOKENS, OPERATORS and ASSIGNMENT_TOKENS. +var phpcsOperatorPuncts = map[string]bool{ + "==": true, "!=": true, "<>": true, "===": true, "!==": true, + "<": true, ">": true, "<=": true, ">=": true, "<=>": true, "??": true, + "+": true, "-": true, "*": true, "/": true, "%": true, "**": true, + "&": true, "|": true, "^": true, "<<": true, ">>": true, + "=": true, "+=": true, "-=": true, "*=": true, "/=": true, ".=": true, + "%=": true, "**=": true, "&=": true, "|=": true, "^=": true, + "<<=": true, ">>=": true, "??=": true, "=>": true, +} + +// phpcsOperatorContext is the per-file token classification PHP_CodeSniffer's +// tokenizer would produce for OperatorSpacing. +type phpcsOperatorContext struct { + inlineElse map[int]bool // ":" of a ternary (T_INLINE_ELSE) + notArrow map[int]bool // "=>" of a match arm or arrow function + paramParens map[int]bool // "(" opening function/closure/fn parameters + useParens map[int]bool // "(" opening a closure use list + declare map[int]int // declare keyword -> its ")" (or -1 when unclosed) +} + +func newPhpcsOperatorContext(s *tokens.Stream) phpcsOperatorContext { + o := phpcsOperatorContext{ + inlineElse: map[int]bool{}, + notArrow: map[int]bool{}, + paramParens: map[int]bool{}, + useParens: map[int]bool{}, + declare: map[int]int{}, + } + type pending struct{ depth int } + var ternaries []pending + depth := 0 + for i := 0; i < s.Len(); i++ { + t := s.At(i) + switch t.Kind { + case token.Keyword: + switch strings.ToLower(t.Value) { + case "declare": + if open := phpcsNextNonEmpty(s, i+1); open < s.Len() && s.At(open).Value == "(" { + o.declare[i] = s.MatchForward(open) + } else { + o.declare[i] = -1 + } + case "function", "fn": + o.markFunction(s, i) + case "match": + o.markMatch(s, i) + } + case token.Punct: + switch t.Value { + case "(", "[", "{": + depth++ + case ")", "]", "}": + depth-- + for len(ternaries) > 0 && ternaries[len(ternaries)-1].depth > depth { + ternaries = ternaries[:len(ternaries)-1] + } + case "?": + if !phpcsIsNullable(s, i) { + ternaries = append(ternaries, pending{depth}) + } + case ":": + if n := len(ternaries); n > 0 && ternaries[n-1].depth == depth { + o.inlineElse[i] = true + ternaries = ternaries[:n-1] + } + case ";": + for len(ternaries) > 0 && ternaries[len(ternaries)-1].depth >= depth { + ternaries = ternaries[:len(ternaries)-1] + } + } + } + } + return o +} + +// markFunction records the parameter (and closure use) parentheses of the +// function, closure or arrow function at i, and the "=>" of an arrow function. +func (o phpcsOperatorContext) markFunction(s *tokens.Stream, i int) { + isFn := strings.EqualFold(s.At(i).Value, "fn") + j := phpcsNextNonEmpty(s, i+1) + if j < s.Len() && s.At(j).Value == "&" { + j = phpcsNextNonEmpty(s, j+1) + } + if j < s.Len() && s.At(j).Kind != token.Punct { + j = phpcsNextNonEmpty(s, j+1) + } + if j >= s.Len() || s.At(j).Value != "(" { + return + } + closeIdx := s.MatchForward(j) + if closeIdx < 0 { + return + } + o.paramParens[j] = true + next := phpcsNextNonEmpty(s, closeIdx+1) + if next < s.Len() && s.At(next).Kind == token.Keyword && strings.EqualFold(s.At(next).Value, "use") { + if open := phpcsNextNonEmpty(s, next+1); open < s.Len() && s.At(open).Value == "(" { + o.useParens[open] = true + } + } + if !isFn { + return + } + depth := 0 + for k := closeIdx + 1; k < s.Len(); k++ { + switch v := s.At(k).Value; { + case s.At(k).Kind != token.Punct: + case v == "(" || v == "[" || v == "{": + depth++ + case v == ")" || v == "]" || v == "}": + depth-- + if depth < 0 { + return + } + case v == "=>" && depth == 0: + o.notArrow[k] = true + return + case v == ";" && depth == 0: + return + } + } +} + +// markMatch records the arm arrows of the match expression at i. +func (o phpcsOperatorContext) markMatch(s *tokens.Stream, i int) { + open := phpcsNextNonEmpty(s, i+1) + if open >= s.Len() || s.At(open).Value != "(" { + return + } + closeIdx := s.MatchForward(open) + if closeIdx < 0 { + return + } + body := phpcsNextNonEmpty(s, closeIdx+1) + if body >= s.Len() || s.At(body).Value != "{" { + return + } + end := s.MatchForward(body) + if end < 0 { + return + } + depth := 0 + for k := body + 1; k < end; k++ { + if s.At(k).Kind != token.Punct { + continue + } + switch v := s.At(k).Value; v { + case "(", "[", "{": + depth++ + case ")", "]", "}": + depth-- + case "=>": + if depth == 0 { + o.notArrow[k] = true + } + } + } +} + +// isOperatorToken reports whether the token at i is one Squiz OperatorSpacing +// registers (PSR12 also adds boolean operators and "." via withPSR12). +func (o phpcsOperatorContext) isOperatorToken(s *tokens.Stream, i int, withPSR12 bool) bool { + t := s.At(i) + switch t.Kind { + case token.Keyword: + switch strings.ToLower(t.Value) { + case "instanceof": + return true + case "and", "or", "xor": + return withPSR12 + } + case token.Punct: + switch t.Value { + case "?": + return !phpcsIsNullable(s, i) + case ":": + return o.inlineElse[i] + case "=>": + return !o.notArrow[i] + case "&&", "||", ".": + return withPSR12 + } + return phpcsOperatorPuncts[t.Value] + } + return false +} + +// isOperator ports Squiz OperatorSpacingSniff::isOperator: parameter defaults, +// "=&", references, type operators and unary "+"/"-" are not operators. +func (o phpcsOperatorContext) isOperator(s *tokens.Stream, i int) bool { + switch s.At(i).Value { + case "=": + if o.paramParens[phpcsInnermostParen(s, i)] { + return false + } + if i+1 < s.Len() && s.At(i+1).Value == "&" { + return false + } + case "&": + if o.isReference(s, i) || phpcsTypeOperator(s, i) { + return false + } + case "|": + if phpcsTypeOperator(s, i) { + return false + } + case "-", "+": + if p := phpcsPrevNonEmpty(s, i-1); p >= 0 && phpcsNonOperand(s, p, o) { + return false + } + } + return true +} + +// isReference ports File::isReference for the "&" at i. +func (o phpcsOperatorContext) isReference(s *tokens.Stream, i int) bool { + before := phpcsPrevNonEmpty(s, i-1) + if before < 0 { + return false + } + b := s.At(before) + lower := strings.ToLower(b.Value) + if b.Kind == token.Keyword && (lower == "function" || lower == "fn" || lower == "as") { + return true + } + if b.Kind == token.Punct && (phpcsAssignment[b.Value] || b.Value == "=>") { + return true + } + after := phpcsNextNonEmpty(s, i+1) + if after < s.Len() && s.At(after).Kind == token.Keyword && strings.EqualFold(s.At(after).Value, "new") { + return true + } + // a parameter passed by reference: "&" before the variable, ahead of any default + if open := phpcsInnermostParen(s, i); open >= 0 && (o.paramParens[open] || o.useParens[open]) && !phpcsInParamDefault(s, open, i) { + return true + } + if b.Kind == token.Punct && (b.Value == "(" || b.Value == "," || (b.Value == "[" && phpcsShortArrayOpen(s, before))) { + k := after + for k < s.Len() { + t := s.At(k) + if isPhpcsEmpty(t) || t.Kind == token.Ident || t.Value == `\` || t.Value == "::" || + (t.Kind == token.Keyword && (strings.EqualFold(t.Value, "static") || strings.EqualFold(t.Value, "namespace"))) { + k++ + continue + } + break + } + return k < s.Len() && s.At(k).Kind == token.Variable + } + return false +} + +var phpcsAssignment = map[string]bool{ + "=": true, "+=": true, "-=": true, "*=": true, "/=": true, ".=": true, + "%=": true, "**=": true, "&=": true, "|=": true, "^=": true, + "<<=": true, ">>=": true, "??=": true, +} + +// phpcsNonOperand reports whether the token at p makes a following "+"/"-" a +// sign rather than an operator (Squiz OperatorSpacing's nonOperandTokens). +func phpcsNonOperand(s *tokens.Stream, p int, o phpcsOperatorContext) bool { + t := s.At(p) + switch t.Kind { + case token.Keyword: + switch strings.ToLower(t.Value) { + case "and", "or", "xor", "return", "echo", "print", "yield", "case": + return true + } + case token.Ident: + lower := strings.ToLower(t.Value) + return lower == "exit" || lower == "die" + case token.Punct: + switch t.Value { + case "&&", "||", ":", ",", "?", "{", "(", "[", ".", "=>": + return true + case ")": + if open := s.MatchBackward(p); open >= 0 { + if _, _, ok := phpCastAt(s, open); ok { + return true + } + } + return false + } + return phpcsOperatorPuncts[t.Value] + } + return false +} + +// phpcsInnermostParen is the "(" of the innermost parentheses around i, or -1. +func phpcsInnermostParen(s *tokens.Stream, i int) int { + depth := 0 + for j := i - 1; j >= 0; j-- { + t := s.At(j) + if t.Kind != token.Punct { + continue + } + switch t.Value { + case ")": + depth++ + case "(": + if depth == 0 { + return j + } + depth-- + } + } + return -1 +} + +// phpcsInParamDefault reports whether i sits after the "=" of its parameter +// within the parameter list opened at open. +func phpcsInParamDefault(s *tokens.Stream, open, i int) bool { + depth := 0 + for j := i - 1; j > open; j-- { + t := s.At(j) + if t.Kind != token.Punct { + continue + } + switch t.Value { + case ")", "]", "}": + depth++ + case "(", "[", "{": + depth-- + case ",": + if depth == 0 { + return false + } + case "=": + if depth == 0 { + return true + } + } + } + return false +} + +// phpcsTypeName reports whether t can be part of a type name for the +// tokenizer's union/intersection detection. +func phpcsTypeName(s *tokens.Stream, i int, allowStatic bool) bool { + t := s.At(i) + switch t.Kind { + case token.Ident: + return true + case token.Punct: + return t.Value == `\` + case token.Keyword: + switch strings.ToLower(t.Value) { + case "callable", "namespace": + return true + case "static": + return allowStatic + case "array": + n := phpcsNextNonEmpty(s, i+1) + return n >= s.Len() || s.At(n).Value != "(" + } + } + return false +} + +// phpcsTypeOperator ports the tokenizer's retokenizing of "|" and "&" into +// T_TYPE_UNION / T_TYPE_INTERSECTION in parameter, property, constant and +// return types. +func phpcsTypeOperator(s *tokens.Stream, i int) bool { + suspected := "" + after := 0 + // parentheses of a DNF group ahead count towards the pairing check: PHPCS + // converts the whole type once it reaches the operator after the group + parens := 0 + for x := i + 1; x < s.Len() && suspected == ""; x++ { + t := s.At(x) + if isPhpcsEmpty(t) { + continue + } + if phpcsTypeName(s, x, true) { + after++ + continue + } + if after > 0 && (t.Value == "&" || t.Value == "..." || t.Value == "|") { + continue + } + if t.Kind == token.Punct && (t.Value == "(" || t.Value == ")") { + parens++ + continue + } + switch { + case t.Kind == token.Variable: + suspected = "param" + case t.Value == "=>" || t.Value == ";" || t.Value == "{": + suspected = "return" + case t.Value == "=": + suspected = "constant" + default: + return false + } + } + if after == 0 || suspected == "" { + return false + } + confirmed := false +loop: + for x := i - 1; x >= 0; x-- { + t := s.At(x) + lower := strings.ToLower(t.Value) + if isPhpcsEmpty(t) { + continue + } + if suspected == "param" && t.Value == "(" { + if p := phpcsPrevNonEmpty(s, x-1); p >= 0 && phpcsOwnsParams(s, p) { + confirmed = true + break + } + } + if phpcsTypeName(s, x, suspected != "param") { + continue + } + switch { + case t.Value == "?" || t.Value == "|" || t.Value == "&": + continue + case t.Value == "(" || t.Value == ")": + parens++ + continue + case suspected == "return" && t.Value == ":": + if p := phpcsPrevNonEmpty(s, x-1); p >= 0 && s.At(p).Value == ")" { + if open := s.MatchBackward(p); open >= 0 { + if q := phpcsPrevNonEmpty(s, open-1); q >= 0 && (phpcsOwnsParams(s, q) || (s.At(q).Kind == token.Keyword && strings.EqualFold(s.At(q).Value, "use"))) { + confirmed = true + } + } + } + break loop + case suspected == "constant" && t.Kind == token.Keyword && lower == "const": + confirmed = true + case suspected == "param" && t.Kind == token.Keyword && phpcsNullableModifier(lower) && lower != "function" && lower != "fn": + confirmed = true + } + break + } + if !confirmed && suspected == "param" { + if open := phpcsInnermostParen(s, i); open >= 0 { + if p := phpcsPrevNonEmpty(s, open-1); p >= 0 && phpcsOwnsParams(s, p) { + confirmed = true + } + } + } + return confirmed && parens%2 == 0 +} + +// phpcsOwnsParams reports whether the token at p (just before a "(") makes +// that parenthesis a parameter list: a function name, "function", "fn" or "fn&". +func phpcsOwnsParams(s *tokens.Stream, p int) bool { + t := s.At(p) + if t.Value == "&" { + if p = phpcsPrevNonEmpty(s, p-1); p < 0 { + return false + } + t = s.At(p) + } + if t.Kind == token.Keyword { + lower := strings.ToLower(t.Value) + return lower == "function" || lower == "fn" + } + if t.Kind == token.Ident { + q := phpcsPrevNonEmpty(s, p-1) + if q >= 0 && s.At(q).Value == "&" { + q = phpcsPrevNonEmpty(s, q-1) + } + return q >= 0 && s.At(q).Kind == token.Keyword && strings.EqualFold(s.At(q).Value, "function") + } + return false +} diff --git a/blink/internal/fixer/rules/phpcs_whitespace.go b/blink/internal/fixer/rules/phpcs_whitespace.go index e99e898d9e..5caf7949c9 100644 --- a/blink/internal/fixer/rules/phpcs_whitespace.go +++ b/blink/internal/fixer/rules/phpcs_whitespace.go @@ -81,3 +81,18 @@ func phpcsSpaceAfter(s *tokens.Stream, op, spacing int, ignoreNewlines bool) boo } return true } + +// isPhpcsAnnotationComment reports whether PHP_CodeSniffer's tokenizer turns +// the comment v into a T_PHPCS_* token (phpcs:set, :ignoreFile, :disable, +// :enable, :ignore, optionally "@"-prefixed). It does so even with annotations +// off, as ECS runs, so such comments are never T_COMMENT to a sniff. +func isPhpcsAnnotationComment(v string) bool { + text := strings.ToLower(strings.TrimRight(strings.TrimLeft(v, " \t/*#"), " */\t\r\n")) + text = strings.TrimPrefix(text, "@") + for _, p := range []string{"phpcs:set", "phpcs:ignorefile", "phpcs:disable", "phpcs:enable", "phpcs:ignore"} { + if strings.HasPrefix(text, p) { + return true + } + } + return false +} diff --git a/blink/internal/fixer/rules/post_statement_comment.go b/blink/internal/fixer/rules/post_statement_comment.go new file mode 100644 index 0000000000..b5672ec22a --- /dev/null +++ b/blink/internal/fixer/rules/post_statement_comment.go @@ -0,0 +1,106 @@ +package rules + +import ( + "regexp" + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// postStatementCommentOwners are the control structures whose multi-line +// conditions may carry trailing comments. +var postStatementCommentOwners = map[string]bool{ + "if": true, "elseif": true, "switch": true, "while": true, "for": true, "foreach": true, "match": true, +} + +var postStatementAnnotation = regexp.MustCompile(`^//[ \t]*@[^\s]+`) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/PostStatementCommentSniff.php +// +// PostStatementComment moves a "//" comment that trails a statement onto the +// next line. Comments after "}", inside control structure conditions and +// annotations ("// @phpstan-ignore") stay put. +type PostStatementComment struct{} + +func (PostStatementComment) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\PostStatementCommentSniff` +} + +func (PostStatementComment) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/PostStatementCommentSniff.php" +} + +func (PostStatementComment) Fix(s *tokens.Stream) bool { + changed := false + eol := phpcsEolChar(s) + for i := 0; i < s.Len(); i++ { + t := s.At(i) + if t.Kind != token.Comment || !strings.HasPrefix(t.Value, "//") || isPhpcsAnnotationComment(t.Value) { + continue + } + last, sameLine := postStatementLastContent(s, i) + if last < 0 || !sameLine || s.At(last).Value == "}" { + continue + } + if v := s.At(last).Value; v == "," || v == ";" { + before, _ := postStatementLastContent(s, last) + if before < 0 || s.At(before).Value == "}" { + continue + } + } + if inControlCondition(s, i) || postStatementAnnotation.MatchString(t.Value) { + continue + } + if i > 0 && s.At(i-1).Kind == token.Whitespace { + s.SetValue(i-1, s.At(i-1).Value+eol) + } else { + s.InsertAt(i, token.Token{Kind: token.Whitespace, Value: eol}) + i++ + } + changed = true + } + return changed +} + +// postStatementLastContent is the last non-whitespace token before i and +// whether no line break separates it from i. +func postStatementLastContent(s *tokens.Stream, i int) (int, bool) { + sameLine := true + for j := i - 1; j >= 0; j-- { + t := s.At(j) + if t.Kind != token.Whitespace { + return j, sameLine + } + if strings.ContainsAny(t.Value, "\r\n") { + sameLine = false + } + } + return -1, false +} + +// inControlCondition reports whether i sits inside the parentheses of an +// if/elseif/switch/while/for/foreach/match condition, at any depth. +func inControlCondition(s *tokens.Stream, i int) bool { + depth := 0 + for j := i - 1; j >= 0; j-- { + t := s.At(j) + if t.Kind != token.Punct { + continue + } + switch t.Value { + case ")": + depth++ + case "(": + if depth > 0 { + depth-- + continue + } + if p := prevSignificantIndex(s, j); p >= 0 && s.At(p).Kind == token.Keyword && + postStatementCommentOwners[strings.ToLower(s.At(p).Value)] { + return true + } + } + } + return false +} diff --git a/blink/internal/fixer/rules/priorities.go b/blink/internal/fixer/rules/priorities.go index 1045ba61e0..bdaae6542e 100644 --- a/blink/internal/fixer/rules/priorities.go +++ b/blink/internal/fixer/rules/priorities.go @@ -120,6 +120,7 @@ var fixerPriority = map[string]int{ "SemicolonSpacingSniff": 0, "SingleLineArrayWhitespaceSniff": 0, "SpaceAfterNotSniff": 0, + "ClassInstantiationSniff": 0, "IncrementDecrementSpacingSniff": 0, "OpeningBraceSameLineSniff": 0, "OpeningFunctionBraceBsdAllmanSniff": 0, @@ -138,6 +139,17 @@ var fixerPriority = map[string]int{ "TrailingArrayCommaSniff": 0, "UnusedInheritedVariablePassedToClosureSniff": 0, "UselessParameterDefaultValueSniff": 0, + "RequireStrictTypesSniff": 0, + "LineEndingsSniff": 0, + "UnnecessaryHeredocSniff": 0, + "DoubleQuoteUsageSniff": 0, + "SpreadOperatorSpacingAfterSniff": 0, + "ObjectOperatorSpacingSniff": 0, + "ReturnTypeDeclarationSniff": 0, + "OperatorSpacingSniff": 0, + "PostStatementCommentSniff": 0, + "ClosingDeclarationCommentSniff": 0, + "DocCommentAlignmentSniff": 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/psr12_operator_spacing.go b/blink/internal/fixer/rules/psr12_operator_spacing.go new file mode 100644 index 0000000000..f09bb242e2 --- /dev/null +++ b/blink/internal/fixer/rules/psr12_operator_spacing.go @@ -0,0 +1,65 @@ +package rules + +import ( + "slices" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/PSR12/Sniffs/Operators/OperatorSpacingSniff.php +// +// PSR12OperatorSpacing requires at least one space around binary, assignment, +// comparison, boolean, ternary and concatenation operators: "$a+$b" -> "$a + $b". +// Extra spaces are kept; a short ternary "?:" stays together, and an operator +// right after a line comment keeps its position. +type PSR12OperatorSpacing struct{} + +func (PSR12OperatorSpacing) Name() string { + return `PHP_CodeSniffer\Standards\PSR12\Sniffs\Operators\OperatorSpacingSniff` +} + +func (PSR12OperatorSpacing) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/PSR12/Sniffs/Operators/OperatorSpacingSniff.php" +} + +func (PSR12OperatorSpacing) Fix(s *tokens.Stream) bool { + ops := newPhpcsOperatorContext(s) + var inserts []int + for i := 0; i < s.Len(); i++ { + if end, ok := ops.declare[i]; ok { + if end < 0 { + break + } + i = end + continue + } + if !ops.isOperatorToken(s, i, true) || !ops.isOperator(s, i) { + continue + } + v := s.At(i).Value + checkBefore := i > 0 + if v == ":" && i > 0 && s.At(i-1).Value == "?" { + checkBefore = false + } + // a line comment's newline belongs to the comment for PHPCS: an + // operator starting the next line has no whitespace before it + if i > 0 && !phpcsWhitespaceAt(s, i-1) && (isLineComment(s.At(i-1)) || (s.At(i-1).Kind == token.Whitespace && i > 1 && isLineComment(s.At(i-2)))) { + checkBefore = false + } + checkAfter := i+1 < s.Len() + if v == "?" && checkAfter && s.At(i+1).Value == ":" { + checkAfter = false + } + if checkBefore && !phpcsWhitespaceAt(s, i-1) { + inserts = append(inserts, i) + } + if checkAfter && s.At(i+1).Kind != token.Whitespace { + inserts = append(inserts, i+1) + } + } + for _, at := range slices.Backward(slices.Compact(inserts)) { + s.InsertAt(at, token.Token{Kind: token.Whitespace, Value: " "}) + } + return len(inserts) > 0 +} diff --git a/blink/internal/fixer/rules/registry.go b/blink/internal/fixer/rules/registry.go index 52ed71a8ce..1c1a63077a 100644 --- a/blink/internal/fixer/rules/registry.go +++ b/blink/internal/fixer/rules/registry.go @@ -325,6 +325,7 @@ func ConstructFixers() []fixer.Fixer { ArrayBracketSpacing{}, SemicolonSpacing{}, SpaceAfterNot{Spacing: 1}, + ClassInstantiation{}, IncrementDecrementSpacing{}, OpeningBraceSameLine{}, OpeningFunctionBraceBsdAllman{}, @@ -338,6 +339,17 @@ func ConstructFixers() []fixer.Fixer { DisallowTabIndent{}, DisallowSpaceIndent{}, ArrayIndent{Indent: 4}, + RequireStrictTypes{}, + LineEndings{}, + UnnecessaryHeredoc{}, + DoubleQuoteUsage{}, + SpreadOperatorSpacingAfter{}, + ObjectOperatorSpacing{}, + ReturnTypeDeclarationSniff{}, + PSR12OperatorSpacing{}, + PostStatementComment{}, + ClosingDeclarationComment{}, + DocCommentAlignment{}, SlevomatArrowFunctionDeclaration{}, SlevomatDisallowTrailingCommaInCall{}, SlevomatDisallowTrailingCommaInClosureUse{}, diff --git a/blink/internal/fixer/rules/regression_test.go b/blink/internal/fixer/rules/regression_test.go index 9a6a9a6c46..abc795a97a 100644 --- a/blink/internal/fixer/rules/regression_test.go +++ b/blink/internal/fixer/rules/regression_test.go @@ -57,7 +57,7 @@ func TestTernaryLeavesNullableTypes(t *testing.T) { func TestOperatorLinebreakKeepsNullFirstParenAssignment(t *testing.T) { t.Parallel() src := "getPolicyFor($arguments[0])) &&\n $callback = $this->resolvePolicyCallback($user, $ability, $arguments, $policy)) {\n return $callback;\n }\n }\n}\n" - want := "getPolicyFor($arguments[0]))\n && $callback = $this->resolvePolicyCallback($user, $ability, $arguments, $policy)) {\n return $callback;\n }\n }\n}\n" + want := "getPolicyFor($arguments[0]))\n && $callback = $this->resolvePolicyCallback($user, $ability, $arguments, $policy)) {\n return $callback;\n }\n }//end resolve()\n}\n" if got := runAll(src); got != want { t.Fatalf("parenthesized assignment must stay null-first\n got: %q\nwant: %q", got, want) } diff --git a/blink/internal/fixer/rules/require_strict_types.go b/blink/internal/fixer/rules/require_strict_types.go new file mode 100644 index 0000000000..836242009e --- /dev/null +++ b/blink/internal/fixer/rules/require_strict_types.go @@ -0,0 +1,21 @@ +package rules + +import "github.com/ecsphp/ecs-src/blink/internal/tokens" + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/PHP/RequireStrictTypesSniff.php +// +// RequireStrictTypes is a no-op: the sniff's only fix ("strict_types=0" -> "1") +// is an addFixableWarning, which ECS drops, so under ECS it never changes code. +type RequireStrictTypes struct{} + +func (RequireStrictTypes) Name() string { + return `PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\RequireStrictTypesSniff` +} + +func (RequireStrictTypes) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/PHP/RequireStrictTypesSniff.php" +} + +func (RequireStrictTypes) Fix(*tokens.Stream) bool { + return false +} diff --git a/blink/internal/fixer/rules/return_type_declaration_sniff.go b/blink/internal/fixer/rules/return_type_declaration_sniff.go new file mode 100644 index 0000000000..ef23d290c2 --- /dev/null +++ b/blink/internal/fixer/rules/return_type_declaration_sniff.go @@ -0,0 +1,106 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/PSR12/Sniffs/Functions/ReturnTypeDeclarationSniff.php +// +// ReturnTypeDeclarationSniff formats a return type as "): type": no space +// before the colon, one space after it. A comment in either gap is left alone. +type ReturnTypeDeclarationSniff struct{} + +func (ReturnTypeDeclarationSniff) Name() string { + return `PHP_CodeSniffer\Standards\PSR12\Sniffs\Functions\ReturnTypeDeclarationSniff` +} + +func (ReturnTypeDeclarationSniff) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/PSR12/Sniffs/Functions/ReturnTypeDeclarationSniff.php" +} + +func (ReturnTypeDeclarationSniff) Fix(s *tokens.Stream) bool { + changed := false + for i := 0; i < s.Len(); i++ { + colon, ok := phpcsReturnTypeColon(s, i) + if !ok { + continue + } + typ := phpcsNextNonEmpty(s, colon+1) + if typ >= s.Len() { + continue + } + // one space between the colon and the type, unless a comment sits there + if (typ != colon+2 || s.At(colon+1).Value != " ") && !hasNonWhitespace(s, colon+1, typ) { + for j := typ - 1; j > colon; j-- { + s.RemoveAt(j) + } + s.InsertAt(colon+1, token.Token{Kind: token.Whitespace, Value: " "}) + changed = true + } + // no space before the colon, unless a comment sits there + if prev := colon - 1; s.At(prev).Kind == token.Whitespace { + p := prev + for p >= 0 && s.At(p).Kind == token.Whitespace { + p-- + } + if p >= 0 && s.At(p).Kind == token.Punct && s.At(p).Value == ")" { + for j := colon - 1; j > p; j-- { + s.RemoveAt(j) + } + changed = true + } + } + } + return changed +} + +// phpcsReturnTypeColon finds the return type colon of the function, closure or +// arrow function whose keyword is at i. +func phpcsReturnTypeColon(s *tokens.Stream, i int) (int, bool) { + t := s.At(i) + if t.Kind != token.Keyword || (!strings.EqualFold(t.Value, "function") && !strings.EqualFold(t.Value, "fn")) { + return 0, false + } + j := phpcsNextNonEmpty(s, i+1) + if j < s.Len() && s.At(j).Value == "&" { + j = phpcsNextNonEmpty(s, j+1) + } + if j < s.Len() && s.At(j).Kind != token.Punct { + j = phpcsNextNonEmpty(s, j+1) + } + if j >= s.Len() || s.At(j).Kind != token.Punct || s.At(j).Value != "(" { + return 0, false + } + closeIdx := s.MatchForward(j) + if closeIdx < 0 { + return 0, false + } + next := phpcsNextNonEmpty(s, closeIdx+1) + // closure "use (...)" comes before the return type + if next < s.Len() && s.At(next).Kind == token.Keyword && strings.EqualFold(s.At(next).Value, "use") { + open := phpcsNextNonEmpty(s, next+1) + if open >= s.Len() || s.At(open).Value != "(" { + return 0, false + } + if closeIdx = s.MatchForward(open); closeIdx < 0 { + return 0, false + } + next = phpcsNextNonEmpty(s, closeIdx+1) + } + if next >= s.Len() || s.At(next).Kind != token.Punct || s.At(next).Value != ":" { + return 0, false + } + return next, true +} + +func hasNonWhitespace(s *tokens.Stream, from, to int) bool { + for j := from; j < to; j++ { + if s.At(j).Kind != token.Whitespace { + return true + } + } + return false +} diff --git a/blink/internal/fixer/rules/spread_operator_spacing_after.go b/blink/internal/fixer/rules/spread_operator_spacing_after.go new file mode 100644 index 0000000000..80396ac116 --- /dev/null +++ b/blink/internal/fixer/rules/spread_operator_spacing_after.go @@ -0,0 +1,48 @@ +package rules + +import ( + "github.com/ecsphp/ecs-src/blink/internal/fixer" + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/WhiteSpace/SpreadOperatorSpacingAfterSniff.php +// +// SpreadOperatorSpacingAfter puts exactly Spacing spaces (default 0) after "...": +// "... $args" -> "...$args". First-class callables ("foo(...)") are left alone. +type SpreadOperatorSpacingAfter struct { + Spacing int + IgnoreNewlines bool +} + +func (SpreadOperatorSpacingAfter) Name() string { + return `PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\SpreadOperatorSpacingAfterSniff` +} + +func (SpreadOperatorSpacingAfter) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/WhiteSpace/SpreadOperatorSpacingAfterSniff.php" +} + +func (f SpreadOperatorSpacingAfter) WithConfig(config map[string]any) fixer.Fixer { + f.Spacing = configInt(config, "spacing", f.Spacing) + if v, ok := config["ignoreNewlines"].(bool); ok { + f.IgnoreNewlines = v + } + return f +} + +func (f SpreadOperatorSpacingAfter) Fix(s *tokens.Stream) bool { + changed := false + for i := 0; i < s.Len(); i++ { + if t := s.At(i); t.Kind != token.Punct || t.Value != "..." { + continue + } + if next := phpcsNextNonEmpty(s, i+1); next < s.Len() && s.At(next).Kind == token.Punct && s.At(next).Value == ")" { + continue + } + if phpcsSpaceAfter(s, i, f.Spacing, f.IgnoreNewlines) { + changed = true + } + } + return changed +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.1.inc b/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.1.inc new file mode 100644 index 0000000000..a2d3ed2093 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.1.inc @@ -0,0 +1,18 @@ + + + + + +group('a.id, + uc.name, + ag.title, + ua.name' + ); +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.1.inc.fixed new file mode 100644 index 0000000000..b143fb4cf0 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.1.inc.fixed @@ -0,0 +1,18 @@ + + + + + +group('a.id, + uc.name, + ag.title, + ua.name' + ); +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.2.inc new file mode 100644 index 0000000000..3723b5adbf --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.2.inc @@ -0,0 +1,5 @@ + + + +
...more HTML...
+ diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.2.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.2.inc.fixed new file mode 100644 index 0000000000..260d7fd2fe --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/Files/LineEndingsUnitTest.2.inc.fixed @@ -0,0 +1,5 @@ + + + +
...more HTML...
+ diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/PHP/RequireStrictTypesUnitTest.1.inc b/blink/internal/fixer/rules/testdata/phpcs/Generic/PHP/RequireStrictTypesUnitTest.1.inc new file mode 100644 index 0000000000..387cec240d --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/PHP/RequireStrictTypesUnitTest.1.inc @@ -0,0 +1,8 @@ +bar} +END; + +$heredoc = <<< "END" +some ${beers::softdrink} +END; + +$heredoc = <<< END +{${$object->getName()}} text +END; + +$heredoc = <<<"END" +some {${getName()}} +END; + +$heredoc = <<baz()()} +END; + +$heredoc = <<values[3]->name} text +END; + +$heredoc = <<<"END" +some ${$bar} +END; + +$heredoc = <<bar} text +END; + +$heredoc = <<<"END" +${foo["${bar}"]} text +END; + +$heredoc = <<{${'a'}}} text +END; + +$heredoc = <<{$baz[1]}} +END; + +$heredoc = <<john's wife greeted $people->robert. +END; + +$heredoc = <<bar} + END; + +$heredoc = <<< "END" + some ${beers::softdrink} + END; + +$heredoc = <<< END + {${$object->getName()}} text + END; + +$heredoc = <<<"END" + some {${getName()}} + END; + +$heredoc = <<baz()()} + END; + +$heredoc = <<values[3]->name} text + END; + +$heredoc = <<<"END" + some ${$bar} + END; + +$heredoc = <<bar} text + END; + +$heredoc = <<<"END" + ${foo["${bar}"]} text + END; + +$heredoc = <<{${'a'}}} text + END; + +$heredoc = <<{$baz[1]}} + END; + +$heredoc = <<john's wife greeted $people->robert. + END; + +$heredoc = <<bar} +END; + +$heredoc = <<< "END" + some ${beers::softdrink} +END; + +$heredoc = <<< END + {${$object->getName()}} text +END; + +$heredoc = <<<"END" + some {${getName()}} +END; + +$heredoc = <<baz()()} +END; + +$heredoc = <<values[3]->name} text +END; + +$heredoc = <<<"END" + some ${$bar} +END; + +$heredoc = <<bar} text +END; + +$heredoc = <<<"END" + ${foo["${bar}"]} text +END; + +$heredoc = <<{${'a'}}} text +END; + +$heredoc = <<{$baz[1]}} +END; + +$heredoc = <<john's wife greeted $people->robert. +END; + +$heredoc = <<bar} +END; + +$heredoc = <<< "END" + some ${beers::softdrink} +END; + +$heredoc = <<< END + {${$object->getName()}} text +END; + +$heredoc = <<<"END" + some {${getName()}} +END; + +$heredoc = <<baz()()} +END; + +$heredoc = <<values[3]->name} text +END; + +$heredoc = <<<"END" + some ${$bar} +END; + +$heredoc = <<bar} text +END; + +$heredoc = <<<"END" + ${foo["${bar}"]} text +END; + +$heredoc = <<{${'a'}}} text +END; + +$heredoc = <<{$baz[1]}} +END; + +$heredoc = <<john's wife greeted $people->robert. +END; + +$heredoc = <<bar} + END; + +$heredoc = <<< "END" + some ${beers::softdrink} + END; + +$heredoc = <<< END + {${$object->getName()}} text + END; + +$heredoc = <<<"END" + some {${getName()}} + END; + +$heredoc = <<baz()()} + END; + +$heredoc = <<values[3]->name} text + END; + +$heredoc = <<<"END" + some ${$bar} + END; + +$heredoc = <<bar} text + END; + +$heredoc = <<<"END" + ${foo["${bar}"]} text + END; + +$heredoc = <<{${'a'}}} text + END; + +$heredoc = <<{$baz[1]}} + END; + +$heredoc = <<john's wife greeted $people->robert. + END; + +$heredoc = <<bar(); +echo (new Foo)->bar(); +echo (new Foo((new Bar)->getBaz()))->bar(); +$foo = (new Foo)::$bar; + +echo (new Foo((new Bar//comment +)->getBaz(new Baz /* comment */)))->bar(); + +$foo = new $bar['a'](); +$foo = new $bar['a']['b'](); +$foo = new $bar['a'][$baz['a']['b']]['b'](); +$foo = new $bar['a'] [$baz['a']/* comment */ ['b']]['b']; + +$a = new self::$transport[$cap_string]; +$renderer = new $this->inline_diff_renderer; +$a = new ${$varHoldingClassName}; + +$class = new $obj?->classname(); +$class = new $obj?->classname; +$class = new ${$obj?->classname}; + +// Issue 3456. +// Anon classes should be skipped, even when there is an attribute between the new and the class keywords. +$anonWithAttribute = new #[SomeAttribute('summary')] class { + public const SOME_STUFF = 'foo'; +}; + +$foo = new parent(); +$foo = new parent; + +// PHP 8.3: safeguard that the sniff ignores anonymous classes, even when declared as readonly. +$anon = new readonly class {}; +$anon = new #[MyAttribute] readonly class {}; + +$foo = new \FQN\Bar(); +$foo = new namespace\Bar(); +$foo = new \FQN\Bar; +$foo = new namespace\Bar; diff --git a/blink/internal/fixer/rules/testdata/phpcs/PSR12/Classes/ClassInstantiationUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Classes/ClassInstantiationUnitTest.inc.fixed new file mode 100644 index 0000000000..cf6233d53f --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Classes/ClassInstantiationUnitTest.inc.fixed @@ -0,0 +1,56 @@ +bar(); +echo (new Foo())->bar(); +echo (new Foo((new Bar())->getBaz()))->bar(); +$foo = (new Foo())::$bar; + +echo (new Foo((new Bar()//comment +)->getBaz(new Baz() /* comment */)))->bar(); + +$foo = new $bar['a'](); +$foo = new $bar['a']['b'](); +$foo = new $bar['a'][$baz['a']['b']]['b'](); +$foo = new $bar['a'] [$baz['a']/* comment */ ['b']]['b'](); + +$a = new self::$transport[$cap_string](); +$renderer = new $this->inline_diff_renderer(); +$a = new ${$varHoldingClassName}(); + +$class = new $obj?->classname(); +$class = new $obj?->classname(); +$class = new ${$obj?->classname}(); + +// Issue 3456. +// Anon classes should be skipped, even when there is an attribute between the new and the class keywords. +$anonWithAttribute = new #[SomeAttribute('summary')] class { + public const SOME_STUFF = 'foo'; +}; + +$foo = new parent(); +$foo = new parent(); + +// PHP 8.3: safeguard that the sniff ignores anonymous classes, even when declared as readonly. +$anon = new readonly class {}; +$anon = new #[MyAttribute] readonly class {}; + +$foo = new \FQN\Bar(); +$foo = new namespace\Bar(); +$foo = new \FQN\Bar(); +$foo = new namespace\Bar(); diff --git a/blink/internal/fixer/rules/testdata/phpcs/PSR12/Functions/ReturnTypeDeclarationUnitTest.1.inc b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Functions/ReturnTypeDeclarationUnitTest.1.inc new file mode 100644 index 0000000000..78c4b953a8 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Functions/ReturnTypeDeclarationUnitTest.1.inc @@ -0,0 +1,74 @@ + $arg; + +return (!$a ? [ new class { public function b(): c {} } ] : []); + +// This should be fixed in one fixer loop iteration. +function multipleWhitespaceTokens(): + + + + + ?int {} diff --git a/blink/internal/fixer/rules/testdata/phpcs/PSR12/Functions/ReturnTypeDeclarationUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Functions/ReturnTypeDeclarationUnitTest.1.inc.fixed new file mode 100644 index 0000000000..5c3c03d3ea --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Functions/ReturnTypeDeclarationUnitTest.1.inc.fixed @@ -0,0 +1,65 @@ + $arg; + +return (!$a ? [ new class { public function b(): c {} } ] : []); + +// This should be fixed in one fixer loop iteration. +function multipleWhitespaceTokens(): ?int {} diff --git a/blink/internal/fixer/rules/testdata/phpcs/PSR12/Functions/ReturnTypeDeclarationUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Functions/ReturnTypeDeclarationUnitTest.2.inc new file mode 100644 index 0000000000..e1029fa0be --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Functions/ReturnTypeDeclarationUnitTest.2.inc @@ -0,0 +1,4 @@ + $b) { + $variable =$foo ? 'foo' :'bar'; + $variable.='text'.'text'; +} + +$foo+= $a&$b; +$foo = $a|$b; +$foo =$a^$b; +$foo = ~$a; +$foo *=$a<<$b; +$foo = $a>>$b; + +function foo(&$a,& $b) {} + +$foo = $a and$b; +$foo = $a or $b; +$foo = $a xor$b; +$foo = !$a; +$foo = $a&&$b; +$foo = $a||$b; + +$foo = $a instanceof Foo; +$foo = $a instanceof$b; + +$foo .= 'hi' + .= 'there'; + +$foo .= 'hi' +.= 'there'; + +$foo .= 'hi' // comment +.= 'there'; + +$foo/*comment*/=/*comment*/$a/*comment*/and/*comment*/$b; + +$foo .=//comment +'string' .=/*comment*/ +'string'; + +$foo = $foo ?: 'bar'; +$foo = $foo?:'bar'; + +try { +} catch (ExceptionType1|ExceptionType2 $e) { +} + +if (strpos($tokenContent, 'b"') === 0 && substr($tokenContent, -1) === '"') {} + +$oldConstructorPos = +1; +return -$content; + +function name($a = -1) {} + +$a =& $ref; +$a = [ 'a' => &$something ]; + +$fn = fn(array &$one) => 1; +$fn = fn(array & $one) => 1; + +$fn = static fn(DateTime $a, DateTime $b): int => -($a->getTimestamp() <=> $b->getTimestamp()); + +function issue3267(string|int ...$values) {} + +function setDefault(#[ImportValue( + constraints: [ + [ + Assert\Type::class, + ['type' => 'bool'], + ], + ] + )] ?bool $value = null): void + { + // Do something + } + +declare(strict_types=1); diff --git a/blink/internal/fixer/rules/testdata/phpcs/PSR12/Operators/OperatorSpacingUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Operators/OperatorSpacingUnitTest.1.inc.fixed new file mode 100644 index 0000000000..0f52f1cf74 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Operators/OperatorSpacingUnitTest.1.inc.fixed @@ -0,0 +1,79 @@ + $b) { + $variable = $foo ? 'foo' : 'bar'; + $variable .= 'text' . 'text'; +} + +$foo += $a & $b; +$foo = $a | $b; +$foo = $a ^ $b; +$foo = ~$a; +$foo *= $a << $b; +$foo = $a >> $b; + +function foo(&$a,& $b) {} + +$foo = $a and $b; +$foo = $a or $b; +$foo = $a xor $b; +$foo = !$a; +$foo = $a && $b; +$foo = $a || $b; + +$foo = $a instanceof Foo; +$foo = $a instanceof $b; + +$foo .= 'hi' + .= 'there'; + +$foo .= 'hi' +.= 'there'; + +$foo .= 'hi' // comment +.= 'there'; + +$foo/*comment*/ = /*comment*/$a/*comment*/ and /*comment*/$b; + +$foo .= //comment +'string' .= /*comment*/ +'string'; + +$foo = $foo ?: 'bar'; +$foo = $foo ?: 'bar'; + +try { +} catch (ExceptionType1 | ExceptionType2 $e) { +} + +if (strpos($tokenContent, 'b"') === 0 && substr($tokenContent, -1) === '"') {} + +$oldConstructorPos = +1; +return -$content; + +function name($a = -1) {} + +$a =& $ref; +$a = [ 'a' => &$something ]; + +$fn = fn(array &$one) => 1; +$fn = fn(array & $one) => 1; + +$fn = static fn(DateTime $a, DateTime $b): int => -($a->getTimestamp() <=> $b->getTimestamp()); + +function issue3267(string|int ...$values) {} + +function setDefault(#[ImportValue( + constraints: [ + [ + Assert\Type::class, + ['type' => 'bool'], + ], + ] + )] ?bool $value = null): void + { + // Do something + } + +declare(strict_types=1); diff --git a/blink/internal/fixer/rules/testdata/phpcs/PSR12/Operators/OperatorSpacingUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Operators/OperatorSpacingUnitTest.2.inc new file mode 100644 index 0000000000..3a0dbac3e9 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/PSR12/Operators/OperatorSpacingUnitTest.2.inc @@ -0,0 +1,3 @@ + $a; + +trait TestTrait { +}//end trait + +trait TestTrait { +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/ClosingDeclarationCommentUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/ClosingDeclarationCommentUnitTest.1.inc.fixed new file mode 100644 index 0000000000..c3b6e68898 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/ClosingDeclarationCommentUnitTest.1.inc.fixed @@ -0,0 +1,117 @@ + $a; + +trait TestTrait { +}//end trait + +trait TestTrait { +}//end trait diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/ClosingDeclarationCommentUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/ClosingDeclarationCommentUnitTest.2.inc new file mode 100644 index 0000000000..7597555087 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/ClosingDeclarationCommentUnitTest.2.inc @@ -0,0 +1,7 @@ + line numbers for each token. + * + * Long description with some points: + * - one + * - two + * - three + * + * @param array &$tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to + * process this file. + * @param string $eolChar The EOL character to use for splitting strings. + * + * @return void + */ +function myFunction() {} + +class MyClass2 +{ + /** + * Some info about the variable here. + */ + var $x; +} + +abstract class MyClass +{ + /** +* Property comment + */ + readonly public string $prop; +} + +/** + * Some info about the enum here + * +*/ +enum Suits: string +{ + /** + * Some info about the case here. + */ + case HEARTS; +} + +/** ************************************************************************ + * Example with no errors. + **************************************************************************/ +function example() {} + +/** + * Some info about the class here. + */ +final class FinalClassWithFinalProp +{ + /** + *Some info about the property here. + * + * @var int + */ + final $property = 10; +} + +class AsymVisibility { + /** + * Stars should be aligned. + */ + public(set) int $prop = 1; + + /** + * Stars should be aligned. + */ + protected(set) int $prop = 1; + + /** + * Stars should be aligned. + */ + private(set) int $prop = 1; +} + +/** + * Some info about the class here. + */ +abstract class AbstractClassWithAbstractProp +{ + /** + *Some info about the property here. + * + * @var int + */ + abstract $property {get;} +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/DocCommentAlignmentUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/DocCommentAlignmentUnitTest.inc.fixed new file mode 100644 index 0000000000..0b50530747 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/DocCommentAlignmentUnitTest.inc.fixed @@ -0,0 +1,146 @@ + line numbers for each token. + * + * Long description with some points: + * - one + * - two + * - three + * + * @param array &$tokens The array of tokens to process. + * @param object $tokenizer The tokenizer being used to + * process this file. + * @param string $eolChar The EOL character to use for splitting strings. + * + * @return void + */ +function myFunction() {} + +class MyClass2 +{ + /** + * Some info about the variable here. + */ + var $x; +} + +abstract class MyClass +{ + /** + * Property comment + */ + readonly public string $prop; +} + +/** + * Some info about the enum here + * + */ +enum Suits: string +{ + /** + * Some info about the case here. + */ + case HEARTS; +} + +/** ************************************************************************ + * Example with no errors. + **************************************************************************/ +function example() {} + +/** + * Some info about the class here. + */ +final class FinalClassWithFinalProp +{ + /** + * Some info about the property here. + * + * @var int + */ + final $property = 10; +} + +class AsymVisibility { + /** + * Stars should be aligned. + */ + public(set) int $prop = 1; + + /** + * Stars should be aligned. + */ + protected(set) int $prop = 1; + + /** + * Stars should be aligned. + */ + private(set) int $prop = 1; +} + +/** + * Some info about the class here. + */ +abstract class AbstractClassWithAbstractProp +{ + /** + * Some info about the property here. + * + * @var int + */ + abstract $property {get;} +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/PostStatementCommentUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/PostStatementCommentUnitTest.inc new file mode 100644 index 0000000000..3374c4760a --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/PostStatementCommentUnitTest.inc @@ -0,0 +1,64 @@ + function($b) { + }, // comment. + 'key' => 'value', // phpcs:ignore Standard.Category.SniffName -- for reasons. + 'key' => 'value', // comment. +]; + +// Verify that multi-line control structure with comments and annotations are left alone. +for ( + $i = 0; /* Start */ + $i < 10; /* phpcs:ignore Standard.Category.SniffName -- for reasons. */ + $i++ // comment + +) {} + +if ( $condition === true // comment + && $anotherCondition === false +) {} + +$match = match($foo // comment + && $bar +) { + 1 => 1, // comment +}; + +// Issue #560: Annotations should be reported separately and be non-auto-fixable as their meaning may change when moved. +$a = 1; //@codeCoverageIgnore +$b = 2; // @phpstan-ignore variable.undefined +$c = 3; // @phpstan-ignore variable.undefined +$d = 4; // @tabInsteadOfSpace + +// Comments that include `@`, but are not recognized as annotations by this sniff. +$a = 1; // @ = add tag. +$b = 2; // Some comment. // @username diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/PostStatementCommentUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/PostStatementCommentUnitTest.inc.fixed new file mode 100644 index 0000000000..bd6b171b04 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Commenting/PostStatementCommentUnitTest.inc.fixed @@ -0,0 +1,71 @@ + function($b) { + }, // comment. + 'key' => 'value', // phpcs:ignore Standard.Category.SniffName -- for reasons. + 'key' => 'value', +// comment. +]; + +// Verify that multi-line control structure with comments and annotations are left alone. +for ( + $i = 0; /* Start */ + $i < 10; /* phpcs:ignore Standard.Category.SniffName -- for reasons. */ + $i++ // comment + +) {} + +if ( $condition === true // comment + && $anotherCondition === false +) {} + +$match = match($foo // comment + && $bar +) { + 1 => 1, +// comment +}; + +// Issue #560: Annotations should be reported separately and be non-auto-fixable as their meaning may change when moved. +$a = 1; //@codeCoverageIgnore +$b = 2; // @phpstan-ignore variable.undefined +$c = 3; // @phpstan-ignore variable.undefined +$d = 4; // @tabInsteadOfSpace + +// Comments that include `@`, but are not recognized as annotations by this sniff. +$a = 1; +// @ = add tag. +$b = 2; +// Some comment. // @username diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/DoubleQuoteUsageUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/DoubleQuoteUsageUnitTest.inc new file mode 100644 index 0000000000..c8cc638369 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/DoubleQuoteUsageUnitTest.inc @@ -0,0 +1,37 @@ +"; +$string = "Value: $var[test]"; +$string = "\0"; +$string = "\$var"; + +$x = "bar = '$z', +baz = '" . $a . "'...$x"; + +$string = "Hello +there"; +$string = 'Hello +there'; + +$string = "\123 \234"."\u123"."\e"; + +echo "window.location = \"".$url."\";\n"; +echo "" + +$string = "Hello + there"; + +function test() { + echo "It Worked'; +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/DoubleQuoteUsageUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/DoubleQuoteUsageUnitTest.inc.fixed new file mode 100644 index 0000000000..97309194ee --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/Strings/DoubleQuoteUsageUnitTest.inc.fixed @@ -0,0 +1,37 @@ +"; +$string = "Value: $var[test]"; +$string = "\0"; +$string = '$var'; + +$x = "bar = '$z', +baz = '" . $a . "'...$x"; + +$string = 'Hello +there'; +$string = 'Hello +there'; + +$string = "\123 \234"."\u123"."\e"; + +echo 'window.location = "'.$url."\";\n"; +echo '' + +$string = 'Hello + there'; + +function test() { + echo "It Worked'; +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ObjectOperatorSpacingUnitTest.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ObjectOperatorSpacingUnitTest.inc new file mode 100644 index 0000000000..67f8ee1447 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ObjectOperatorSpacingUnitTest.inc @@ -0,0 +1,52 @@ +testThis(); +$this-> testThis(); +$this -> testThis(); +$this-> /* comment here */testThis(); +$this/* comment here */ -> testThis(); +$this + ->testThis(); +$this-> + testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines true + +$this->testThis(); +$this-> testThis(); +$this -> testThis(); +$this->/* comment here */testThis(); +$this/* comment here */ -> testThis(); +$this + ->testThis(); +$this-> + testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines false + +thisObject::testThis(); +thisObject:: testThis(); +thisObject :: testThis(); +thisObject::/* comment here */testThis(); +thisObject/* comment here */ :: testThis(); +thisObject + ::testThis(); +thisObject:: + testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines true + +thisObject::testThis(); +thisObject:: testThis(); +thisObject :: testThis(); +thisObject::/* comment here */testThis(); +thisObject/* comment here */ :: testThis(); +thisObject + ::testThis(); +thisObject:: + testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines false + +$this?->testThis(); +$this?-> testThis(); +$this ?-> testThis(); diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ObjectOperatorSpacingUnitTest.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ObjectOperatorSpacingUnitTest.inc.fixed new file mode 100644 index 0000000000..3c0c22afbb --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/WhiteSpace/ObjectOperatorSpacingUnitTest.inc.fixed @@ -0,0 +1,44 @@ +testThis(); +$this->testThis(); +$this->testThis(); +$this->/* comment here */testThis(); +$this/* comment here */->testThis(); +$this->testThis(); +$this->testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines true + +$this->testThis(); +$this->testThis(); +$this->testThis(); +$this->/* comment here */testThis(); +$this/* comment here */->testThis(); +$this->testThis(); +$this->testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines false + +thisObject::testThis(); +thisObject::testThis(); +thisObject::testThis(); +thisObject::/* comment here */testThis(); +thisObject/* comment here */::testThis(); +thisObject::testThis(); +thisObject::testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines true + +thisObject::testThis(); +thisObject::testThis(); +thisObject::testThis(); +thisObject::/* comment here */testThis(); +thisObject/* comment here */::testThis(); +thisObject::testThis(); +thisObject::testThis(); + +// phpcs:set Squiz.WhiteSpace.ObjectOperatorSpacing ignoreNewlines false + +$this?->testThis(); +$this?->testThis(); +$this?->testThis(); diff --git a/blink/internal/fixer/rules/unnecessary_heredoc.go b/blink/internal/fixer/rules/unnecessary_heredoc.go new file mode 100644 index 0000000000..b531213160 --- /dev/null +++ b/blink/internal/fixer/rules/unnecessary_heredoc.go @@ -0,0 +1,21 @@ +package rules + +import "github.com/ecsphp/ecs-src/blink/internal/tokens" + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/Strings/UnnecessaryHeredocSniff.php +// +// UnnecessaryHeredoc is a no-op: the sniff turns a heredoc without +// interpolation into a nowdoc through addFixableWarning, which ECS drops. +type UnnecessaryHeredoc struct{} + +func (UnnecessaryHeredoc) Name() string { + return `PHP_CodeSniffer\Standards\Generic\Sniffs\Strings\UnnecessaryHeredocSniff` +} + +func (UnnecessaryHeredoc) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/Strings/UnnecessaryHeredocSniff.php" +} + +func (UnnecessaryHeredoc) Fix(*tokens.Stream) bool { + return false +} diff --git a/blink/phpcs-not-ported.txt b/blink/phpcs-not-ported.txt index 93d22e15e2..621aa4e248 100644 --- a/blink/phpcs-not-ported.txt +++ b/blink/phpcs-not-ported.txt @@ -1,8 +1,4 @@ -PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineEndingsSniff -PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\RequireStrictTypesSniff -PHP_CodeSniffer\Standards\Generic\Sniffs\Strings\UnnecessaryHeredocSniff PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\ScopeIndentSniff -PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\SpreadOperatorSpacingAfterSniff PHP_CodeSniffer\Standards\PEAR\Sniffs\Classes\ClassDeclarationSniff PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting\FunctionCommentSniff PHP_CodeSniffer\Standards\PEAR\Sniffs\ControlStructures\MultiLineConditionSniff @@ -12,13 +8,10 @@ PHP_CodeSniffer\Standards\PEAR\Sniffs\Functions\FunctionDeclarationSniff PHP_CodeSniffer\Standards\PEAR\Sniffs\WhiteSpace\ObjectOperatorIndentSniff PHP_CodeSniffer\Standards\PEAR\Sniffs\WhiteSpace\ScopeClosingBraceSniff PHP_CodeSniffer\Standards\PSR12\Sniffs\Classes\AnonClassDeclarationSniff -PHP_CodeSniffer\Standards\PSR12\Sniffs\Classes\ClassInstantiationSniff PHP_CodeSniffer\Standards\PSR12\Sniffs\ControlStructures\BooleanOperatorPlacementSniff PHP_CodeSniffer\Standards\PSR12\Sniffs\ControlStructures\ControlStructureSpacingSniff PHP_CodeSniffer\Standards\PSR12\Sniffs\Files\DeclareStatementSniff PHP_CodeSniffer\Standards\PSR12\Sniffs\Files\FileHeaderSniff -PHP_CodeSniffer\Standards\PSR12\Sniffs\Functions\ReturnTypeDeclarationSniff -PHP_CodeSniffer\Standards\PSR12\Sniffs\Operators\OperatorSpacingSniff PHP_CodeSniffer\Standards\PSR12\Sniffs\Traits\UseDeclarationSniff PHP_CodeSniffer\Standards\PSR2\Sniffs\Classes\ClassDeclarationSniff PHP_CodeSniffer\Standards\PSR2\Sniffs\Classes\PropertyDeclarationSniff @@ -30,13 +23,10 @@ PHP_CodeSniffer\Standards\Squiz\Sniffs\Arrays\ArrayDeclarationSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\ClassDeclarationSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\SelfMemberReferenceSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\BlockCommentSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\ClosingDeclarationCommentSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\DocCommentAlignmentSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FileCommentSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FunctionCommentSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\InlineCommentSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\LongConditionClosingCommentSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\PostStatementCommentSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\VariableCommentSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ControlSignatureSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ForEachLoopDeclarationSniff @@ -49,12 +39,10 @@ PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\MultiLineFunctionDeclarationSni PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\EmbeddedPhpSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\LowercasePHPFunctionsSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\Strings\ConcatenationSpacingSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\Strings\DoubleQuoteUsageSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ControlStructureSpacingSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\FunctionClosingBraceSpaceSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\FunctionSpacingSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\MemberVarSpacingSniff -PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ObjectOperatorSpacingSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\OperatorSpacingSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ScopeClosingBraceSniff PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ScopeKeywordSpacingSniff