diff --git a/README.md b/README.md index 5f74f30050..92933c9313 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 | 101 | 114 | 88% | +| PHP_CodeSniffer | 114 | 114 | 100% | | slevomat | 37 | 132 | 28% | -| **total** | **454** | **562** | **80%** | +| **total** | **467** | **562** | **83%** | diff --git a/blink/README.md b/blink/README.md index b5934cca94..0b43c07088 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 | 101 | 114 | 88% | -| **total** | **417** | **430** | **96%** | +| PHP_CodeSniffer | 114 | 114 | 100% | +| **total** | **430** | **430** | **100%** | -blink runs 460 rules in all, its own extras included. +blink runs 473 rules in all, its own extras included. ### slevomat sniffs diff --git a/blink/internal/fixer/rules/embedded_php.go b/blink/internal/fixer/rules/embedded_php.go new file mode 100644 index 0000000000..148e8fdf79 --- /dev/null +++ b/blink/internal/fixer/rules/embedded_php.go @@ -0,0 +1,312 @@ +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/PHP/EmbeddedPhpSniff.php +// +// EmbeddedPhp lays out PHP blocks embedded in HTML: a multi-line block gets +// its open and close tags on lines of their own, an inline one gets one space +// inside each tag and a closing semicolon, and an empty one is removed. +type EmbeddedPhp struct{} + +func (EmbeddedPhp) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\PHP\EmbeddedPhpSniff` +} + +func (EmbeddedPhp) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/PHP/EmbeddedPhpSniff.php" +} + +type embeddedPhp struct { + f *slvFile + sc *phpcsScope +} + +// phpcsOnePass: ECS stops on a fixer conflict between the open tag indent and +// the first content indent, which a second run would resolve differently. +func (EmbeddedPhp) phpcsOnePass() {} + +func (EmbeddedPhp) Fix(s *tokens.Stream) bool { + for i := range s.Len() { + // ECS runs PHP with short_open_tag off, so "" is inline HTML there + if t := s.At(i); t.Kind == token.OpenTag && t.Value == "" { + return false + } + } + return slvRun(s, func(f *slvFile) { + e := embeddedPhp{f: f, sc: newPhpcsScope(f)} + for i, t := range f.toks { + if t.kind != token.OpenTag { + continue + } + closeTag := e.next(token.CloseTag, i) + if closeTag < 0 || f.toks[i].line != f.toks[closeTag].line { + e.multiline(i, closeTag) + } else { + e.inline(i, closeTag) + } + } + }) +} + +func (e embeddedPhp) next(kind token.Kind, from int) int { + for i := from; i < len(e.f.toks); i++ { + if e.f.toks[i].kind == kind { + return i + } + } + return -1 +} + +func (e embeddedPhp) line(i int) int { return e.f.toks[i].line } + +// isCloser and isOpener tell a token that is its own scope_closer/scope_opener. +func (e embeddedPhp) isCloser(i int) bool { return e.sc.closer[i] == i } +func (e embeddedPhp) isOpener(i int) bool { return e.sc.opener[i] == i } + +// prevNonWhitespace is findPrevious(T_WHITESPACE, start, end, true), with PHP +// reading the false it returns as token 0. +func (e embeddedPhp) prevNonWhitespace(start, end int) int { + for i := start; i >= end; i-- { + if e.f.toks[i].kind != token.Whitespace { + return i + } + } + return 0 +} + +func (e embeddedPhp) multiline(ptr, closingTag int) { + f := e.f + prevTag := -1 + for i := ptr - 1; i >= 0; i-- { + if f.toks[i].kind == token.OpenTag { + prevTag = i + break + } + } + if prevTag < 0 { + return + } + firstContent := f.nextNonWhitespace(ptr+1, len(f.toks)) + if firstContent < 0 { + return + } + if closingTag >= 0 { + if f.nextNonWhitespace(closingTag+1, len(f.toks)) < 0 { + return + } + if firstContent == closingTag { + e.reportEmpty(ptr, closingTag) + return + } + } + + indent, indentSet := 0, false + if e.line(firstContent) == e.line(ptr) { + padding := e.lineIndent(ptr) + f.beginChangeset() + f.replaceToken(ptr, strings.TrimRight(f.toks[ptr].content, phpTrimChars)) + f.addContent(ptr, f.eol) + f.addContent(ptr, strings.Repeat(" ", padding)) + if f.toks[ptr+1].kind == token.Whitespace { + f.replaceToken(ptr+1, "") + } + f.endChangeset() + } else if !e.isCloser(firstContent) { + if e.line(firstContent) > e.line(ptr)+1 { + f.beginChangeset() + for i := ptr + 1; i < firstContent; i++ { + if e.line(i) == e.line(firstContent) || e.line(i) == e.line(ptr) { + continue + } + f.replaceToken(i, "") + } + f.endChangeset() + } + indent, indentSet = e.lineIndent(ptr), true + if contentColumn := f.toks[firstContent].column - 1; contentColumn != indent { + padding := strings.Repeat(" ", indent) + if contentColumn == 0 { + f.addContentBefore(firstContent, padding) + } else { + f.replaceToken(firstContent-1, padding) + } + } + } + + lastBefore := e.prevNonWhitespace(ptr-1, 0) + if e.line(lastBefore) == e.line(ptr) && + (f.toks[lastBefore].kind == token.InlineHTML && strings.Trim(f.toks[lastBefore].content, phpTrimChars) != "" || + lastBefore > 0 && f.toks[lastBefore-1].kind != token.InlineHTML && e.line(lastBefore-1) == e.line(ptr)) { + padding := e.lineIndent(lastBefore) + f.beginChangeset() + f.addContentBefore(ptr, f.eol+strings.Repeat(" ", padding)) + if f.toks[ptr-1].kind == token.InlineHTML && strings.Trim(f.toks[ptr-1].content, phpTrimChars) == "" { + f.replaceToken(ptr-1, "") + } + f.endChangeset() + } else { + first := lastBefore - 1 + for ; first > 0; first-- { + if e.line(first) == e.line(ptr) { + continue + } + if strings.Trim(f.toks[first].content, phpTrimChars) != "" { + first = f.firstOnLine(first) + break + } + } + expected := e.lineIndent(max(first, 0)) + 4 + if found := f.toks[ptr].column - 1; found > expected { + f.replaceToken(ptr-1, strings.Repeat(" ", expected)) + } + } + + if closingTag < 0 { + return + } + lastContent := e.prevNonWhitespace(closingTag-1, ptr+1) + firstAfter := f.nextNonWhitespace(closingTag+1, len(f.toks)) + if e.line(lastContent) == e.line(closingTag) { + closerIndent := 0 + if e.line(firstContent) == e.line(lastContent) && indentSet { + closerIndent = indent + } else { + closerIndent = e.lineIndent(closingTag) + } + f.beginChangeset() + if f.toks[closingTag-1].kind == token.Whitespace { + f.replaceToken(closingTag-1, "") + } + f.addContentBefore(closingTag, strings.Repeat(" ", closerIndent)) + f.addContentBefore(closingTag, f.eol) + f.endChangeset() + } else if firstAfter >= 0 && e.line(firstAfter) == e.line(closingTag) { + padding := e.lineIndent(closingTag) + f.beginChangeset() + f.addContent(closingTag, f.eol) + f.addContent(closingTag, strings.Repeat(" ", padding)) + switch f.toks[firstAfter].kind { + case token.InlineHTML: + f.replaceToken(firstAfter, strings.TrimLeft(f.toks[firstAfter].content, phpTrimChars)) + case token.OpenTag: + f.replaceToken(firstAfter, f.toks[firstAfter].content) + } + f.endChangeset() + } + + if e.next(token.OpenTag, closingTag+1) < 0 { + return + } + lastNonEmpty := 0 + for i := closingTag - 1; i >= ptr+1; i-- { + if !f.isEmpty(i) { + lastNonEmpty = i + break + } + } + if !e.isCloser(lastNonEmpty) && e.line(lastContent) < e.line(closingTag)-1 { + f.beginChangeset() + for i := lastContent + 1; i < closingTag; i++ { + if e.line(i) == e.line(lastContent) || e.line(i) == e.line(closingTag) { + continue + } + f.replaceToken(i, "") + } + f.endChangeset() + } +} + +func (e embeddedPhp) inline(ptr, closeTag int) { + f := e.f + if f.nextNonWhitespace(ptr+1, closeTag) < 0 { + e.reportEmpty(ptr, closeTag) + return + } + leadingSpace := 0 + if f.toks[ptr+1].kind == token.Whitespace { + leadingSpace = f.toks[ptr+1].length + } + if leadingSpace != 1 { + if f.toks[ptr+1].kind == token.Whitespace { + f.replaceToken(ptr+1, " ") + } else { + f.addContent(ptr, " ") + } + } + + prev := 0 + for i := closeTag - 1; i >= ptr; i-- { + if !f.isEmpty(i) { + prev = i + break + } + } + if prev != ptr && !e.isOpener(prev) && !e.isCloser(prev) && !f.is(prev, ";") { + f.addContent(prev, ";") + } + + before := f.toks[closeTag-1] + trailingSpace := 0 + isComment := before.kind == token.Comment + if before.kind == token.Whitespace { + trailingSpace = before.length + } else if isComment && strings.HasSuffix(before.content, " ") { + trailingSpace = len(before.content) - len(strings.TrimRight(before.content, phpTrimChars)) + } + if trailingSpace != 1 { + switch { + case trailingSpace == 0: + f.addContentBefore(closeTag, " ") + case isComment: + f.replaceToken(closeTag-1, strings.TrimRight(before.content, phpTrimChars)+" ") + default: + f.replaceToken(closeTag-1, " ") + } + } +} + +func (e embeddedPhp) reportEmpty(ptr, closeTag int) { + f := e.f + f.beginChangeset() + for i := ptr; i <= closeTag; i++ { + f.replaceToken(i, "") + } + if closeTag+1 < len(f.toks) && e.line(closeTag+1) != e.line(closeTag) && ptr > 0 { + if p := f.toks[ptr-1]; p.kind == token.InlineHTML && p.line == e.line(ptr) && p.column == 1 && + strings.Trim(p.content, phpTrimChars) == "" { + f.replaceToken(ptr-1, "") + } + } + f.endChangeset() +} + +// lineIndent is the sniff's calculateLineIndent. +func (e embeddedPhp) lineIndent(ptr int) int { + f := e.f + first := ptr + for first > 0 && f.toks[first].column != 1 { + first-- + } + for first > 0 && f.toks[first].kind == token.Comment && !phpcsIsAnnotation(f, first) && + f.toks[first].content != strings.TrimLeft(f.toks[first].content, phpTrimChars) { + for first--; first > 0 && f.toks[first].column != 1; first-- { + } + } + t := f.toks[first] + leading := len(t.content) - len(strings.TrimLeft(t.content, phpTrimChars)) + switch { + case t.kind == token.Whitespace: + return f.toks[first+1].column - 1 + case t.kind == token.InlineHTML, t.kind == token.String && t.heredoc && !strings.HasSuffix(t.orig, "\n"): + return leading + case t.doc == slvDocWhitespace: + return leading - 1 + } + return 0 +} diff --git a/blink/internal/fixer/rules/function_declaration_argument_spacing.go b/blink/internal/fixer/rules/function_declaration_argument_spacing.go new file mode 100644 index 0000000000..a2d3f257cd --- /dev/null +++ b/blink/internal/fixer/rules/function_declaration_argument_spacing.go @@ -0,0 +1,450 @@ +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/Functions/FunctionDeclarationArgumentSpacingSniff.php +// +// FunctionDeclarationArgumentSpacing fixes the spacing inside a function's +// parameter list: around "=", after "&", "..." and type hints, around commas +// and inside the parentheses. +type FunctionDeclarationArgumentSpacing struct { + EqualsSpacing int + RequiredSpacesAfterOpen int + RequiredSpacesBeforeClose int +} + +func (FunctionDeclarationArgumentSpacing) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\FunctionDeclarationArgumentSpacingSniff` +} + +func (FunctionDeclarationArgumentSpacing) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Functions/FunctionDeclarationArgumentSpacingSniff.php" +} + +func (r FunctionDeclarationArgumentSpacing) WithConfig(config map[string]any) fixer.Fixer { + r.EqualsSpacing = configInt(config, "equalsSpacing", r.EqualsSpacing) + r.RequiredSpacesAfterOpen = configInt(config, "requiredSpacesAfterOpen", r.RequiredSpacesAfterOpen) + r.RequiredSpacesBeforeClose = configInt(config, "requiredSpacesBeforeClose", r.RequiredSpacesBeforeClose) + return r +} + +func (r FunctionDeclarationArgumentSpacing) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + for i := range f.toks { + if f.isKeyword(i, "function") { + p := f.prevEffective(i - 1) + if f.is(p, "->") || f.is(p, "?->") || f.is(p, "::") { + continue + } + fn, ok := phpcsFunctionAt(f, i) + if !ok { + continue + } + r.processBracket(f, fn.openParen) + if fn.closure { + if open, _ := fn.useParens(f); open >= 0 { + r.processBracket(f, open) + } + } + continue + } + if open := phpcsFnParen(f, i); open >= 0 { + r.processBracket(f, open) + } + } + }) +} + +// phpcsFnParen returns the "(" of the arrow function whose "fn" is at i, or -1. +func phpcsFnParen(f *slvFile, i int) int { + if !f.isKeyword(i, "fn") { + return -1 + } + if p := f.prevEffective(i - 1); f.is(p, "->") || f.is(p, "?->") || f.is(p, "::") || f.isKeyword(p, "function") { + return -1 + } + o := f.nextEffective(i+1, len(f.toks)) + if f.is(o, "&") { + o = f.nextEffective(o+1, len(f.toks)) + } + if !f.is(o, "(") || f.toks[o].closer < 0 { + return -1 + } + return o +} + +func (r FunctionDeclarationArgumentSpacing) gapTo(f *slvFile, from, to int, ws int) (int, bool) { + if f.toks[from].line != f.toks[to].line { + return 0, true + } + if f.isWS(ws) { + return f.toks[ws].length, false + } + return 0, false +} + +// clearAfter replaces the whitespace tokens after i with nothing. +func clearWhitespaceAfter(f *slvFile, i int) { + for j := i + 1; j < len(f.toks) && f.isWS(j); j++ { + f.replaceToken(j, "") + } +} + +func (r FunctionDeclarationArgumentSpacing) processBracket(f *slvFile, open int) { + closeIdx := f.toks[open].closer + multiLine := f.toks[open].line != f.toks[closeIdx].line + params := phpcsMethodParameters(f, open) + + if len(params) == 0 { + if f.nextNot(f.isWS, open+1, closeIdx) < 0 { + if closeIdx-open != 1 { + f.beginChangeset() + for j := open + 1; f.isWS(j); j++ { + f.replaceToken(j, "") + } + f.endChangeset() + } + return + } + } + + for n, p := range params { + if p.referenceToken >= 0 && f.isWS(p.referenceToken+1) { + f.beginChangeset() + clearWhitespaceAfter(f, p.referenceToken) + f.endChangeset() + } + if p.variadicToken >= 0 && f.isWS(p.variadicToken+1) { + f.beginChangeset() + clearWhitespaceAfter(f, p.variadicToken) + f.endChangeset() + } + if p.equalToken >= 0 { + r.equalsSide(f, p.token, p.equalToken, p.token+1, p.equalToken) + r.equalsSide(f, p.equalToken, p.defaultToken, p.equalToken+1, p.defaultToken) + } + if p.typeHintToken >= 0 { + end := p.typeHintEndToken + var gap strings.Builder + for j := end + 1; f.isWS(j); j++ { + gap.WriteString(f.toks[j].content) + } + if gap.String() != " " { + f.beginChangeset() + f.addContent(end, " ") + clearWhitespaceAfter(f, end) + f.endChangeset() + } + } + for _, mod := range []int{p.visibilityToken, p.setVisibilityToken, p.readonlyToken} { + if mod < 0 { + continue + } + after := f.nextNot(f.isWS, mod+1, p.token) + spaces := 0 + if after >= 0 && f.toks[mod].line != f.toks[after].line { + spaces = -1 + } else if f.isWS(mod + 1) { + spaces = f.toks[mod+1].length + } + if spaces != 1 { + f.beginChangeset() + f.addContent(mod, " ") + clearWhitespaceAfter(f, mod) + f.endChangeset() + } + } + + if n == 0 || params[n-1].commaToken < 0 { + continue + } + comma := params[n-1].commaToken + endOfPrev := f.prevEffective(comma - 1) + spaceBefore := 0 + if f.toks[endOfPrev].line != f.toks[comma].line { + spaceBefore = -1 + } else if f.isWS(comma - 1) { + spaceBefore = f.toks[comma-1].length + } + if spaceBefore != 0 { + startOfCurr := f.nextEffective(comma+1, len(f.toks)) + f.beginChangeset() + f.addContent(endOfPrev, ",") + f.replaceToken(comma, "") + if f.toks[comma].line == f.toks[startOfCurr].line { + clearWhitespaceAfter(f, comma) + } else { + for j := comma - 1; f.isWS(j) && f.toks[endOfPrev].line != f.toks[j].line; j-- { + f.replaceToken(j, "") + } + for j := comma + 1; f.isWS(j) && f.toks[comma].line == f.toks[j].line; j++ { + f.replaceToken(j, "") + } + } + f.endChangeset() + } + + if multiLine { + next := f.nextEffective(comma+1, closeIdx) + nextLine := f.toks[0].line + if next >= 0 { + nextLine = f.toks[next].line + } + if nextLine != f.toks[comma].line { + continue + } + } + spacesAfter := 0 + if f.isWS(comma + 1) { + spacesAfter = f.toks[comma+1].length + } + switch { + case spacesAfter == 0: + f.addContent(comma, " ") + case spacesAfter != 1: + f.replaceToken(comma+1, " ") + } + } + + if multiLine { + return + } + gap := 0 + if f.isWS(closeIdx - 1) { + gap = f.toks[closeIdx-1].length + } + if gap != r.RequiredSpacesBeforeClose { + padding := strings.Repeat(" ", r.RequiredSpacesBeforeClose) + if gap == 0 { + f.addContentBefore(closeIdx, padding) + } else { + f.replaceToken(closeIdx-1, padding) + } + } + gap = 0 + if f.isWS(open + 1) { + gap = f.toks[open+1].length + } + if gap != r.RequiredSpacesAfterOpen { + padding := strings.Repeat(" ", r.RequiredSpacesAfterOpen) + if gap == 0 { + f.addContent(open, padding) + } else { + f.replaceToken(open+1, padding) + } + } +} + +// equalsSide checks the spacing between from and to (the parameter and its +// "=", or the "=" and the default value), fixing it when only whitespace sits +// between them. +func (r FunctionDeclarationArgumentSpacing) equalsSide(f *slvFile, from, to, ws, searchEnd int) { + spaces, newline := r.gapTo(f, from, to, ws) + if !newline && spaces == r.EqualsSpacing { + return + } + if f.nextNot(f.isWS, from+1, searchEnd) >= 0 { + return + } + f.beginChangeset() + f.addContent(from, strings.Repeat(" ", r.EqualsSpacing)) + clearWhitespaceAfter(f, from) + f.endChangeset() +} + +// phpcsParam is one entry of File::getMethodParameters; token indexes are -1 +// when unset. +type phpcsParam struct { + token, defaultToken, equalToken, referenceToken, variadicToken int + typeHintToken, typeHintEndToken int + visibilityToken, setVisibilityToken, readonlyToken, commaToken int +} + +// phpcsTypeParen reports whether the "(" or ")" at i belongs to a DNF type in +// a parameter list rather than to an expression. +func phpcsTypeParen(f *slvFile, i, open int) bool { + if f.is(i, ")") { + i = f.toks[i].closer + if i < 0 { + return false + } + } + p := f.prevEffective(i - 1) + if p == open || f.is(p, ",") || f.is(p, "|") || p >= 0 && f.toks[p].kind == token.AttributeEnd { + return true + } + if p < 0 || f.toks[p].kind != token.Keyword { + return false + } + switch kw := strings.ToLower(f.toks[p].orig); { + case kw == "public" || kw == "protected" || kw == "private" || kw == "readonly" || kw == "final", + strings.HasSuffix(kw, "(set)"): + return true + } + return false +} + +// phpcsMethodParameters is File::getMethodParameters for the parameter list +// opening at open. +func phpcsMethodParameters(f *slvFile, open int) []phpcsParam { + closeIdx := f.toks[open].closer + if closeIdx < 0 { + return nil + } + var vars []phpcsParam + reset := func() phpcsParam { + return phpcsParam{token: -1, defaultToken: -1, equalToken: -1, referenceToken: -1, variadicToken: -1, + typeHintToken: -1, typeHintEndToken: -1, visibilityToken: -1, setVisibilityToken: -1, readonlyToken: -1, + commaToken: -1} + } + cur := reset() + defaultStart := -1 + typeTok := func(i int) { + if defaultStart >= 0 { + return + } + if cur.typeHintToken < 0 { + cur.typeHintToken = i + } + cur.typeHintEndToken = i + } + for i := open + 1; i <= closeIdx; i++ { + t := f.toks[i] + if (f.is(i, "(") || f.is(i, ")")) && t.closer >= 0 && i != closeIdx { + if defaultStart < 0 && phpcsTypeParen(f, i, open) { + typeTok(i) + continue + } + if f.is(i, "(") { + i = t.closer + } + continue + } + if (f.is(i, "[") || f.is(i, "{")) && t.closer > i { + i = t.closer + continue + } + if f.isParamName(i) { + continue + } + switch t.kind { + case token.AttributeStart: + if t.closer > i { + i = t.closer + } + case token.Variable: + cur.token = i + case token.Ident: + lower := strings.ToLower(t.orig) + switch lower { + case "self", "parent": + typeTok(i) + continue + case "true", "false", "null": + typeTok(i) + continue + } + prevComma := -1 + for k := i; k >= open; k-- { + if f.is(k, ",") { + prevComma = k + break + } + } + if prevComma >= 0 { + eq := false + for k := prevComma; k < i; k++ { + if f.is(k, "=") { + eq = true + break + } + } + if eq { + continue + } + } + typeTok(i) + case token.Keyword: + kw := strings.ToLower(t.orig) + switch { + case kw == "callable": + if cur.typeHintToken < 0 { + cur.typeHintToken = i + } + cur.typeHintEndToken = i + case kw == "static" || kw == "namespace": + typeTok(i) + case kw == "array" && !f.is(f.nextEffective(i+1, len(f.toks)), "("): + typeTok(i) + case kw == "public" || kw == "protected" || kw == "private": + if defaultStart < 0 { + cur.visibilityToken = i + } + case strings.HasSuffix(kw, "(set)"): + if defaultStart < 0 { + cur.setVisibilityToken = i + } + case kw == "readonly": + if defaultStart < 0 { + cur.readonlyToken = i + } + } + case token.Punct: + switch t.orig { + case "&": + if n := f.nextEffective(i+1, len(f.toks)); n >= 0 && f.toks[n].kind == token.Variable || f.is(n, "...") { + if defaultStart < 0 { + cur.referenceToken = i + } + } else { + typeTok(i) + } + case "|", "\\": + typeTok(i) + case "?": + if defaultStart < 0 { + cur.typeHintEndToken = i + } + case "...": + cur.variadicToken = i + case "=": + defaultStart = f.nextEffective(i+1, len(f.toks)) + cur.equalToken = i + case ")", ",": + if cur.token < 0 { + continue + } + if defaultStart >= 0 { + cur.defaultToken = defaultStart + } else { + cur.equalToken = -1 + } + if t.orig == "," { + cur.commaToken = i + } + vars = append(vars, cur) + cur = reset() + defaultStart = -1 + } + } + } + return vars +} + +// isParamName reports whether the word at i is a named-argument label, which +// PHP_CodeSniffer's tokenizer turns into T_PARAM_NAME: a name followed by ":" +// right after "(" or ",". +func (f *slvFile) isParamName(i int) bool { + k := f.toks[i].kind + if k != token.Ident && k != token.Keyword || strings.Contains(f.toks[i].orig, `\`) { + return false + } + p := f.prevEffective(i - 1) + return f.is(f.nextEffective(i+1, len(f.toks)), ":") && (f.is(p, "(") || f.is(p, ",")) +} diff --git a/blink/internal/fixer/rules/multi_line_function_declaration.go b/blink/internal/fixer/rules/multi_line_function_declaration.go new file mode 100644 index 0000000000..5ad262cc97 --- /dev/null +++ b/blink/internal/fixer/rules/multi_line_function_declaration.go @@ -0,0 +1,128 @@ +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/Squiz/Sniffs/Functions/MultiLineFunctionDeclarationSniff.php +// +// MultiLineFunctionDeclaration is PEAR FunctionDeclaration that also calls a +// declaration multi-line when its parameters span lines, puts each parameter +// of such a declaration on its own line and keeps a single-line one's ")" on +// the last parameter's line. +type MultiLineFunctionDeclaration struct { + Indent int +} + +func (MultiLineFunctionDeclaration) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Functions\MultiLineFunctionDeclarationSniff` +} + +func (MultiLineFunctionDeclaration) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Functions/MultiLineFunctionDeclarationSniff.php" +} + +func (m MultiLineFunctionDeclaration) WithConfig(config map[string]any) fixer.Fixer { + m.Indent = configInt(config, "indent", m.Indent) + return m +} + +func (m MultiLineFunctionDeclaration) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + var sc *phpcsScope + for i := range f.toks { + fn, ok := phpcsFunctionAt(f, i) + if !ok { + continue + } + if sc == nil { + sc = newPhpcsScope(f) + } + m.process(f, sc, fn) + } + }) +} + +func (m MultiLineFunctionDeclaration) process(f *slvFile, sc *phpcsScope, fn phpcsFn) { + pear := PEARFunctionDeclaration(m) + pear.processHead(f, fn) + if !m.isMultiLine(f, sc, fn) { + pearSingleLineBrace(f, fn) + m.closerOnParamLine(f, fn) + return + } + pear.processMultiLine(f, fn) + m.processBracket(f, fn.openParen) + if open, _ := fn.useParens(f); open >= 0 { + m.processBracket(f, open) + } +} + +func (MultiLineFunctionDeclaration) isMultiLine(f *slvFile, sc *phpcsScope, fn phpcsFn) bool { + type bracket struct{ ptr, open int } + check := []bracket{{fn.ptr, fn.openParen}} + if open, _ := fn.useParens(f); open >= 0 { + check = append(check, bracket{fn.use, open}) + } +next: + for _, b := range check { + if n := f.nextEffective(b.open+1, len(f.toks)); n < 0 || f.toks[n].line != f.toks[b.ptr].line { + return true + } + closeIdx := f.toks[b.open].closer + end := sc.endOfStatement(b.open + 1) + for f.is(end, ",") { + n := f.nextEffective(end+1, closeIdx) + if n < 0 { + continue next + } + if f.toks[n].line != f.toks[end].line { + return true + } + end = sc.endOfStatement(n) + } + if n := f.nextEffective(end+1, closeIdx); n >= 0 && f.toks[n].line != f.toks[end].line { + return true + } + } + return false +} + +// closerOnParamLine removes a newline before the ")" of a single-line +// declaration. +func (MultiLineFunctionDeclaration) closerOnParamLine(f *slvFile, fn phpcsFn) { + open, closeIdx := fn.openParen, fn.closeParen + prev := f.prevNot(f.isWS, closeIdx-1, open-1) + if prev < 0 || f.toks[prev].line == f.toks[closeIdx].line || f.isEmpty(prev) { + return + } + f.beginChangeset() + for i := closeIdx - 1; i > open && f.isWS(i); i-- { + f.replaceToken(i, "") + } + f.endChangeset() +} + +func (MultiLineFunctionDeclaration) processBracket(f *slvFile, open int) { + closeIdx := f.toks[open].closer + if f.toks[open].line != f.toks[closeIdx].line { + if n := f.nextEffective(open+1, len(f.toks)); n >= 0 && f.toks[n].line == f.toks[open].line { + f.addContent(open, f.eol) + } + } + for i := open + 1; i < closeIdx; i++ { + t := f.toks[i] + if (f.is(i, "(") || f.is(i, "[") || f.is(i, "{") || t.kind == token.AttributeStart) && t.closer > i { + i = t.closer + continue + } + if !f.is(i, ",") { + continue + } + if n := f.nextEffective(i+1, len(f.toks)); n >= 0 && f.toks[n].line == t.line { + f.addContent(i, f.eol) + } + } +} diff --git a/blink/internal/fixer/rules/operator_bracket.go b/blink/internal/fixer/rules/operator_bracket.go new file mode 100644 index 0000000000..66effee827 --- /dev/null +++ b/blink/internal/fixer/rules/operator_bracket.go @@ -0,0 +1,337 @@ +package rules + +import ( + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/lexer" + "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/Formatting/OperatorBracketSniff.php +// +// OperatorBracket wraps arithmetic and bitwise operations in parentheses: +// "$a = $b + 1;" -> "$a = ($b + 1);". +type OperatorBracket struct{} + +func (OperatorBracket) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Formatting\OperatorBracketSniff` +} + +func (OperatorBracket) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php" +} + +// Tokens::OPERATORS. +var obOperators = phpcsSet("+", "-", "*", "/", "%", "**", "<=>", "??", "&", "|", "^", "<<", ">>") + +var obAssignment = phpcsSet("=", "&=", "|=", ".=", "/=", "-=", "**=", "%=", "*=", "+=", "^=", "double_arrow", + "<<=", ">>=", "??=") + +var obComparison = phpcsSet("==", "!=", "<>", "===", "!==", "<=", ">=", "<", ">", "<=>", "??") + +var obInvalidBefore = phpcsSet(",", "colon", "(", "[", "{", "open_short_array", "case", "exit", "match_arrow") + +// allowed inside a bracketed operation of a function call, besides operators and names +var obAllowedInside = phpcsSet("variable", "lnumber", "whitespace", "self", "static", "parent", "->", "?->", "::", + "[", "]", "~") + +// addMissingBracketsError's allowed tokens, besides empty, operator, cast and name tokens +var obAllowedExpr = phpcsSet("variable", "lnumber", "constant_encapsed_string", "double_quoted_string", "whitespace", + "self", "static", "->", "?->", "::", "isset", "array", "~") + +type obFile struct { + f *slvFile + sc *phpcsScope + code []string + notOpRef map[int]bool // "&" references and "|"/"&" type operators +} + +func (OperatorBracket) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + o := newObFile(f) + for i := range f.toks { + if o.isOperator(i) { + o.process(i) + } + } + }) +} + +func newObFile(f *slvFile) *obFile { + o := &obFile{f: f, sc: newPhpcsScope(f), code: make([]string, len(f.toks)), notOpRef: map[int]bool{}} + for i := range f.toks { + o.code[i] = o.classify(i) + } + o.markReferences() + return o +} + +// markReferences finds the "&" File::isReference accepts and the "|"/"&" the +// tokenizer turns into type operators, on a stream of the same source. +func (o *obFile) markReferences() { + f := o.f + var b strings.Builder + at := map[int]int{} + for i, t := range f.toks { + if t.kind == token.Punct && (t.orig == "&" || t.orig == "|") { + at[b.Len()] = i + } + b.WriteString(t.orig) + } + if len(at) == 0 { + return + } + s := tokens.New(lexer.Lex(b.String())) + ctx := newPhpcsOperatorContext(s) + off := 0 + for i := 0; i < s.Len(); i++ { + t := s.At(i) + if j, ok := at[off]; ok && t.Kind == token.Punct && (t.Value == "&" || t.Value == "|") { + if phpcsTypeOperator(s, i) || t.Value == "&" && ctx.isReference(s, i) { + o.notOpRef[j] = true + } + } + off += len(t.Value) + } +} + +func (o *obFile) classify(i int) string { + f := o.f + t := f.toks[i] + if f.isParamName(i) { + return "param_name" + } + switch t.kind { + case token.Variable: + if t.orig == "$" { + return "dollar_open_curly_braces" + } + case token.Number: + return "lnumber" + case token.String: + switch { + case t.heredoc: + return "heredoc" + case t.interp: + return "double_quoted_string" + } + return "constant_encapsed_string" + case token.Ident: + switch strings.ToLower(t.orig) { + case "true", "false", "null", "self", "parent": + if p := f.prevEffective(i - 1); !f.is(p, "->") && !f.is(p, "?->") && !f.is(p, "::") { + return strings.ToLower(t.orig) + } + } + case token.Keyword: + if p := f.prevEffective(i - 1); f.is(p, "->") || f.is(p, "?->") || f.is(p, "::") { + return "string" + } + case token.Punct: + switch { + case len(t.orig) > 2 && t.orig[0] == '(': + if strings.EqualFold(strings.Trim(t.orig, "( \t)"), "void") { + return "void_cast" + } + return "cast" + case t.orig == "[" && f.isShortArrayOpen(i): + return "open_short_array" + case t.orig == "]" && t.closer >= 0 && f.isShortArrayOpen(t.closer): + return "close_short_array" + case t.orig == "=>": + if c := o.sc.code[i]; c == "match_arrow" || c == "fn_arrow" { + return c + } + return "double_arrow" + case t.orig == ":": + if o.sc.code[i] == "inline_else" { + return "inline_else" + } + return "colon" + } + } + return o.sc.code[i] +} + +func (o *obFile) isEmpty(i int) bool { return o.f.isEmpty(i) } + +func (o *obFile) isName(i int) bool { return o.code[i] == "string" } + +func (o *obFile) isOperator(i int) bool { + return o.f.toks[i].kind == token.Punct && obOperators[o.code[i]] && !o.notOpRef[i] +} + +func (o *obFile) isEquality(i int) bool { + switch o.code[i] { + case "==", "!=", "<>", "===", "!==", "<=", ">=": + return true + } + return false +} + +func (o *obFile) process(ptr int) { + f, code := o.f, o.code + if code[ptr] == "-" { + prev := f.prevEffective(ptr - 1) + if prev >= 0 && code[prev] == "return" { + return + } + number := f.nextNonWhitespace(ptr+1, len(f.toks)) + if number >= 0 && code[number] == "lnumber" { + if previous := f.prevNonWhitespace(ptr - 1); previous >= 0 { + if obAssignment[code[previous]] || o.isEquality(previous) || obComparison[code[previous]] || o.isOperator(previous) { + return + } + } + } + } + + if prevTok := f.prevNonWhitespace(ptr - 1); prevTok >= 0 && obInvalidBefore[code[prevTok]] { + return + } + + if code[ptr] == "|" { + if p := o.sc.nested[ptr]; p >= 0 && o.sc.pOwner[p] >= 0 && code[o.sc.pOwner[p]] == "catch" { + return + } + } + + allowed := func(i int) bool { + c := code[i] + return o.isName(i) || o.isOperator(i) || obAllowedInside[c] + } + + lastBracket := -1 + for bracket := o.sc.nested[ptr]; bracket >= 0; bracket = o.sc.nested[bracket] { + endBracket := f.toks[bracket].closer + prevToken := f.prevNonWhitespace(bracket - 1) + prevCode := "" + if prevToken >= 0 { + prevCode = code[prevToken] + } + if prevCode == "isset" { + break + } + if prevToken >= 0 && o.isName(prevToken) || prevCode == "switch" || prevCode == "match" { + prev := ptr - 1 + for ; prev > bracket; prev-- { + if allowed(prev) { + continue + } + if code[prev] == ")" && f.toks[prev].closer >= 0 { + prev = f.toks[prev].closer + } else { + break + } + } + if prev != bracket { + break + } + next := ptr + 1 + for ; next < endBracket; next++ { + if allowed(next) { + continue + } + if code[next] == "(" && f.toks[next].closer >= 0 { + next = f.toks[next].closer + } else { + break + } + } + if next != endBracket { + break + } + } + if phpcsScopeOpenerCodes[prevCode] && prevCode != "switch" && prevCode != "match" { + break + } + if prevCode == "(" && endBracket < ptr { + continue + } + lastBracket = bracket + break + } + + if lastBracket < 0 || f.toks[lastBracket].closer < ptr { + o.addMissingBrackets(ptr) + return + } + square := -1 + for j := ptr - 1; j >= lastBracket; j-- { + if code[j] == "[" || code[j] == "]" { + square = j + break + } + } + if square >= 0 && code[square] == "[" { + for j := ptr + 1; j < len(f.toks); j++ { + if code[j] == "[" || code[j] == "]" { + if code[j] == "]" { + o.addMissingBrackets(ptr) + } + break + } + } + } +} + +func (o *obFile) exprToken(i int, after bool) bool { + c := o.code[i] + return o.isEmpty(i) || o.isOperator(i) || c == "cast" || c == "void_cast" || o.isName(i) || obAllowedExpr[c] || + after && (c == "=" || c == "new") +} + +func (o *obFile) addMissingBrackets(ptr int) { + f, code := o.f, o.code + before := ptr - 1 + for ; before > 0; before-- { + if o.exprToken(before, false) { + continue + } + c := code[before] + if (c == ")" || c == "]" || c == "close_short_array") && f.toks[before].closer >= 0 { + before = f.toks[before].closer + continue + } + break + } + before = f.nextEffective(before+1, len(f.toks)) + if before < 0 || code[before] == "void_cast" || o.isVoidCastParen(before) { + return + } + + after := ptr + 1 + for ; after < len(f.toks); after++ { + if o.exprToken(after, true) { + continue + } + c := code[after] + if c == "(" || c == "[" || c == "open_short_array" { + if f.toks[after].closer < 0 { + return + } + after = f.toks[after].closer + continue + } + break + } + after = f.prevEffective(after - 1) + if before == after || before == ptr || after == ptr { + return + } + f.beginChangeset() + f.replaceToken(before, "("+f.toks[before].content) + f.replaceToken(after, f.toks[after].content+")") + f.endChangeset() +} + +// isVoidCastParen reports whether the "(" at i opens "(void)", a cast PHP +// 8.5 lexes as T_VOID_CAST. +func (o *obFile) isVoidCastParen(i int) bool { + f := o.f + if !f.is(i, "(") || f.toks[i].closer < 0 { + return false + } + return strings.EqualFold(strings.Trim(f.content(i+1, f.toks[i].closer-1), " \t"), "void") +} diff --git a/blink/internal/fixer/rules/pear_function_comment.go b/blink/internal/fixer/rules/pear_function_comment.go index 333785f05f..9bdf6aae01 100644 --- a/blink/internal/fixer/rules/pear_function_comment.go +++ b/blink/internal/fixer/rules/pear_function_comment.go @@ -56,8 +56,17 @@ func pearIsMethodModifier(f *slvFile, i int) bool { } func pearFunctionComment(f *slvFile, ptr int) { + if commentEnd, tags, ok := pearFunctionCommentPreamble(f, ptr); ok { + pearProcessParams(f, commentEnd, tags) + } +} + +// pearFunctionCommentPreamble is the part of PEAR's process() before the +// processReturn/processThrows/processParams calls: it finds the docblock and +// removes blank lines after it, returning its closer and tags. +func pearFunctionCommentPreamble(f *slvFile, ptr int) (commentEnd int, tags []int, ok bool) { ignored := func(i int) bool { return f.toks[i].kind == token.Whitespace || pearIsMethodModifier(f, i) } - commentEnd := ptr - 1 + commentEnd = ptr - 1 for ; commentEnd >= 0; commentEnd-- { if ignored(commentEnd) { continue @@ -69,7 +78,7 @@ func pearFunctionComment(f *slvFile, ptr int) { break } if commentEnd < 0 { - return + return 0, nil, false } isComment := func(i int) bool { return f.toks[i].kind == token.Comment && !phpcsIsAnnotation(f, i) } if isComment(commentEnd) { @@ -82,7 +91,7 @@ func pearFunctionComment(f *slvFile, ptr int) { } } if f.toks[commentEnd].doc != slvDocClose { - return + return 0, nil, false } if f.toks[commentEnd].line != f.toks[ptr].line-1 { @@ -112,13 +121,12 @@ func pearFunctionComment(f *slvFile, ptr int) { for commentStart > 0 && f.toks[commentStart].doc != slvDocOpen { commentStart-- } - var tags []int for i := commentStart + 1; i < commentEnd; i++ { if f.toks[i].doc == slvDocTag { tags = append(tags, i) } } - pearProcessParams(f, commentEnd, tags) + return commentEnd, tags, true } // phpcsAttributeCloser is the attribute_closer PHP_CodeSniffer gives every diff --git a/blink/internal/fixer/rules/pear_function_declaration.go b/blink/internal/fixer/rules/pear_function_declaration.go index e9cdacd8a3..cd6411d2ef 100644 --- a/blink/internal/fixer/rules/pear_function_declaration.go +++ b/blink/internal/fixer/rules/pear_function_declaration.go @@ -119,6 +119,29 @@ func phpcsSpacesAt(f *slvFile, i int) int { } func (d PEARFunctionDeclaration) process(f *slvFile, fn phpcsFn) { + d.processHead(f, fn) + if d.isMultiLine(f, fn) { + d.processMultiLine(f, fn) + return + } + pearSingleLineBrace(f, fn) +} + +// pearSingleLineBrace is processSingleLineDeclaration: K&R braces for a +// closure, BSD/Allman for a function. +func pearSingleLineBrace(f *slvFile, fn phpcsFn) { + if fn.scopeOpener < 0 { + return + } + if fn.closure { + openingFunctionBraceKernighanRitchie(f, fn.scopeOpener) + return + } + openingFunctionBraceBsdAllman(f, fn.ptr, fn.closeParen, fn.scopeOpener) +} + +// processHead is the part of process before the single/multi-line split. +func (d PEARFunctionDeclaration) processHead(f *slvFile, fn phpcsFn) { stackPtr := fn.ptr if strings.ToLower(f.toks[stackPtr].orig) == "function" { if spaces := phpcsSpacesAt(f, stackPtr+1); spaces != 1 { @@ -166,18 +189,6 @@ func (d PEARFunctionDeclaration) process(f *slvFile, fn phpcsFn) { } } - if d.isMultiLine(f, fn) { - d.processMultiLine(f, fn) - return - } - if fn.scopeOpener < 0 { - return - } - if fn.closure { - openingFunctionBraceKernighanRitchie(f, fn.scopeOpener) - return - } - openingFunctionBraceBsdAllman(f, stackPtr, fn.closeParen, fn.scopeOpener) } func phpcsUseGap(f *slvFile, i int) int { diff --git a/blink/internal/fixer/rules/phpcs_scope.go b/blink/internal/fixer/rules/phpcs_scope.go index 286278050f..faeb34b1f3 100644 --- a/blink/internal/fixer/rules/phpcs_scope.go +++ b/blink/internal/fixer/rules/phpcs_scope.go @@ -1,6 +1,7 @@ package rules import ( + "slices" "strings" "github.com/ecsphp/ecs-src/blink/internal/token" @@ -20,6 +21,10 @@ type phpcsScope struct { pOwner []int // parenthesis_owner of a "(" nested []int // the innermost "(" holding the token scopes []phpcsScopeRange + // the scope map as createLevelMap sees it, before processAdditional + preCond, preOpener, preCloser []int + // CASE/DEFAULT statements fixCases gave a braced body: case, new closer, old closer + caseFixes [][3]int } // phpcsScopeRange is a scope the level map counts: the tokens strictly @@ -94,6 +99,7 @@ func newPhpcsScope(f *slvFile) *phpcsScope { i = sc.recurse(i, 1, &ignore) } } + sc.preCond, sc.preOpener, sc.preCloser = slices.Clone(sc.cond), slices.Clone(sc.opener), slices.Clone(sc.closer) sc.fixCases() for i := range n { if sc.cond[i] == i && sc.opener[i] > i && sc.closer[i] > sc.opener[i] { @@ -163,7 +169,13 @@ func (sc *phpcsScope) isEnd(i int) bool { // startOfStatement is File::findStartOfStatement. func (sc *phpcsScope) startOfStatement(start int) int { + return sc.startOfStatementIgnoring(start) +} + +// startOfStatementIgnoring is File::findStartOfStatement with its $ignore codes. +func (sc *phpcsScope) startOfStatementIgnoring(start int, ignore ...string) int { f := sc.f + isEnd := func(i int) bool { return sc.isEnd(i) && !slices.Contains(ignore, sc.code[i]) } if conds := sc.conditions(start); len(conds) > 0 { match := conds[len(conds)-1] if sc.code[match] == "match" && sc.nested[match] == sc.nested[start] { @@ -172,7 +184,7 @@ func (sc *phpcsScope) startOfStatement(start int) int { } } } - for sc.isEnd(start) || sc.cond[start] >= 0 && start == sc.closer[start] { + for isEnd(start) || sc.cond[start] >= 0 && start == sc.closer[start] { if sc.cond[start] >= 0 { start = sc.cond[start] } else { @@ -183,9 +195,11 @@ func (sc *phpcsScope) startOfStatement(start int) int { for i := start; i >= 0; i-- { switch sc.code[i] { case "{", "[", "(", "open_tag": - return lastNotEmpty + if !slices.Contains(ignore, sc.code[i]) { + return lastNotEmpty + } } - if sc.isEnd(i) { + if isEnd(i) { return lastNotEmpty } if sc.opener[i] >= 0 && i == sc.closer[i] { @@ -667,6 +681,7 @@ func (sc *phpcsScope) fixCases() { continue } newCloser := f.toks[x].closer + sc.caseFixes = append(sc.caseFixes, [3]int{i, newCloser, scopeCloser}) for _, idx := range []int{i, x, newCloser} { sc.set(idx, i, x, newCloser) } @@ -684,3 +699,129 @@ func (sc *phpcsScope) fixCases() { } } } + +func phpcsFirstEnd(code string) string { + switch code { + case "case", "default": + return "break" + case "start_heredoc": + return "end_heredoc" + } + return "}" +} + +// phpcsCond is one entry of a token's conditions: the scope condition's +// token, or, with caseIndex, the entry PHP::processAdditional appends to the +// old closer of a CASE it gives a braced body, which holds the CASE's index +// instead of its code. +type phpcsCond struct { + key int + caseIndex bool +} + +// levelMap is Tokenizer::createLevelMap plus the condition fixes of +// PHP::processAdditional: each token's conditions, outermost first, and level, +// which a shared closer can leave apart from len(conditions). +func (sc *phpcsScope) levelMap() (conds [][]phpcsCond, levels []int) { + n := len(sc.code) + conds, levels = make([][]phpcsCond, n), make([]int, n) + nextFree := make([]int, n) + remove := func(list []phpcsCond, key int) []phpcsCond { + out := list[:0:0] + for _, c := range list { + if c.key != key || c.caseIndex { + out = append(out, c) + } + } + return out + } + level, free := 0, 0 + var conditions []phpcsCond + var openers []int + lastOpener := -1 + for i := range n { + levels[i], conds[i], nextFree[i] = level, conditions, free + if sc.preCond[i] < 0 { + continue + } + if sc.preOpener[i] == i { + stackPtr := sc.preCond[i] + if lastOpener >= 0 && sc.preCloser[lastOpener] == sc.preCloser[i] { + thisType := sc.code[sc.preCond[i]] + opener := sc.preCond[lastOpener] + isShared := phpcsScopeOpeners[thisType].with[sc.code[opener]] + if isShared && phpcsFirstEnd(thisType) == phpcsFirstEnd(sc.code[opener]) { + for x := sc.preCond[i]; x <= i; x++ { + levels[x]-- + conds[x] = remove(conds[x], opener) + } + conditions = remove(conditions, opener) + if k := slices.Index(openers, lastOpener); k >= 0 { + openers = slices.Delete(openers, k, k+1) + } + level-- + } + } + level++ + if !slices.Contains(conditions, phpcsCond{key: stackPtr}) { + conditions = append(slices.Clone(conditions), phpcsCond{key: stackPtr}) + free = max(free, stackPtr+1) + } + lastOpener = sc.preOpener[i] + if !slices.Contains(openers, lastOpener) { + openers = append(openers, lastOpener) + } + continue + } + if lastOpener < 0 || sc.preCloser[lastOpener] != i { + continue + } + reversed := slices.Clone(openers) + slices.Reverse(reversed) + for _, opener := range reversed { + if sc.preCloser[opener] != i { + continue + } + oldOpener := openers[len(openers)-1] + openers = openers[:len(openers)-1] + lastOpener = -1 + if len(openers) > 0 { + lastOpener = openers[len(openers)-1] + } + oldCondition := "" + if len(conditions) > 0 { + last := conditions[len(conditions)-1] + oldCondition = sc.code[last.key] + if last.key == free-1 { + free-- + } + conditions = slices.Clone(conditions[:len(conditions)-1]) + } + condition := sc.code[sc.preCond[i]] + if condition != oldCondition && !phpcsScopeOpeners[oldCondition].with[condition] { + badToken := sc.preCond[oldOpener] + for x := oldOpener + 1; x <= i; x++ { + levels[x]-- + conds[x] = remove(conds[x], badToken) + } + } + level-- + levels[i], conds[i], nextFree[i] = level, conditions, free + } + } + for _, fix := range sc.caseFixes { + i, newCloser, scopeCloser := fix[0], fix[1], fix[2] + conds[scopeCloser] = append(slices.Clone(conds[scopeCloser]), phpcsCond{key: nextFree[scopeCloser], caseIndex: true}) + nextFree[scopeCloser]++ + for x := newCloser; x < scopeCloser; x++ { + out := conds[x][:0:0] + for _, c := range conds[x] { + if c.caseIndex || sc.code[c.key] != sc.code[i] { + out = append(out, c) + } + } + conds[x] = out + } + } + return conds, levels +} diff --git a/blink/internal/fixer/rules/priorities.go b/blink/internal/fixer/rules/priorities.go index 3c3eb2776a..6f9bc9511a 100644 --- a/blink/internal/fixer/rules/priorities.go +++ b/blink/internal/fixer/rules/priorities.go @@ -75,6 +75,7 @@ var fixerPriority = map[string]int{ "FunctionSpacingSniff": 0, "MemberVarSpacingSniff": 0, "SelfMemberReferenceSniff": 0, + "ControlSignatureSniff": 0, "EmptyPHPStatementSniff": 0, "DisallowMultipleStatementsSniff": 0, "InlineControlStructureSniff": 0, @@ -138,6 +139,10 @@ var fixerPriority = map[string]int{ "ConcatenationSpacingSniff": 0, "InlineIfDeclarationSniff": 0, "IncrementDecrementSpacingSniff": 0, + "OperatorBracketSniff": 0, + "FunctionDeclarationArgumentSpacingSniff": 0, + "MultiLineFunctionDeclarationSniff": 0, + "ScopeIndentSniff": 0, "MethodDeclarationSniff": 0, "UseDeclarationSniff": 0, "PropertyDeclarationSniff": 0, @@ -160,6 +165,7 @@ var fixerPriority = map[string]int{ "DisallowSpaceIndentSniff": 0, "ArrayIndentSniff": 0, "ClassDeclarationSniff": 0, + "ArrayDeclarationSniff": 0, "AnonClassDeclarationSniff": 0, "ScopeClosingBraceSniff": 0, "SwitchDeclarationSniff": 0, @@ -186,9 +192,13 @@ var fixerPriority = map[string]int{ "FileCommentSniff": 0, "LongConditionClosingCommentSniff": 0, "VariableCommentSniff": 0, + "BlockCommentSniff": 0, "DocCommentAlignmentSniff": 0, + "EmbeddedPhpSniff": 0, "UselessParenthesesSniff": 0, - "UselessSemicolonSniff": 0, + // raised from 0 so an empty statement is gone before whitespace sniffs look + // past a closing brace, as NoEmptyStatementFixer (40) does + "UselessSemicolonSniff": 1, // 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 4c67ccbb74..0b98e331f2 100644 --- a/blink/internal/fixer/rules/registry.go +++ b/blink/internal/fixer/rules/registry.go @@ -306,6 +306,8 @@ func ConstructFixers() []fixer.Fixer { EmptyPHPStatement{}, DisallowMultipleStatements{}, InlineControlStructure{}, + SquizControlSignature{RequiredSpacesBeforeColon: 1}, + SquizSwitchDeclaration{Indent: 4}, LowercaseDeclaration{}, EndFileNewline{}, EndFileNoNewline{}, @@ -341,6 +343,10 @@ func ConstructFixers() []fixer.Fixer { ConcatenationSpacing{}, InlineIfDeclaration{}, IncrementDecrementSpacing{}, + OperatorBracket{}, + FunctionDeclarationArgumentSpacing{}, + MultiLineFunctionDeclaration{Indent: 4}, + ScopeIndent{Indent: 4}, MethodDeclaration{}, TraitUseDeclaration{}, PropertyDeclaration{}, @@ -375,16 +381,23 @@ func ConstructFixers() []fixer.Fixer { LongConditionClosingComment{LineLimit: 20, CommentFormat: "//end %s"}, VariableComment{}, DocCommentAlignment{}, + SquizBlockComment{}, PEARClassDeclaration{}, PSR2ClassDeclaration{Indent: 4}, + SquizClassDeclaration{Indent: 4}, + SquizArrayDeclaration{}, PSR12AnonClassDeclaration{Indent: 4}, PSR2ControlStructureSpacing{}, PSR12ControlStructureSpacing{Indent: 4}, BooleanOperatorPlacement{}, MultiLineCondition{Indent: 4}, PearScopeClosingBrace{Indent: 4}, + SquizScopeClosingBrace{}, PSR2SwitchDeclaration{Indent: 4}, PearObjectOperatorIndent{Indent: 4}, + SquizFunctionComment{}, + EmbeddedPhp{}, + SquizControlStructureSpacing{}, SlevomatArrowFunctionDeclaration{}, SlevomatDisallowTrailingCommaInCall{}, SlevomatDisallowTrailingCommaInClosureUse{}, diff --git a/blink/internal/fixer/rules/scope_indent.go b/blink/internal/fixer/rules/scope_indent.go new file mode 100644 index 0000000000..15549fee9d --- /dev/null +++ b/blink/internal/fixer/rules/scope_indent.go @@ -0,0 +1,780 @@ +package rules + +import ( + "math" + "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" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/WhiteSpace/ScopeIndentSniff.php +// +// ScopeIndent indents every line by Indent spaces per scope level, a line-by-line +// port of the sniff's single pass from the first open tag. +type ScopeIndent struct { + Indent int + Exact bool + TabIndent bool +} + +func (ScopeIndent) Name() string { + return `PHP_CodeSniffer\Standards\Generic\Sniffs\WhiteSpace\ScopeIndentSniff` +} + +func (ScopeIndent) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Generic/Sniffs/WhiteSpace/ScopeIndentSniff.php" +} + +func (r ScopeIndent) WithConfig(config map[string]any) fixer.Fixer { + r.Indent = configInt(config, "indent", r.Indent) + if v, ok := config["exact"].(bool); ok { + r.Exact = v + } + if v, ok := config["tabIndent"].(bool); ok { + r.TabIndent = v + } + return r +} + +func (ScopeIndent) phpcsOnePass() {} + +func (r ScopeIndent) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + m := newSiModel(f) + for i := range f.toks { + if m.code[i] == "open_tag" { + r.process(m, i) + return + } + } + }) +} + +// siModel is the PHP_CodeSniffer token data the sniff reads: refined token +// codes, conditions and parenthesis owners on top of the scope map. +type siModel struct { + f *slvFile + sc *phpcsScope + code []string + conds [][]phpcsCond + levels []int + pOwner []int + docEnd []int +} + +func newSiModel(f *slvFile) *siModel { + sc := newPhpcsScope(f) + n := len(f.toks) + m := &siModel{f: f, sc: sc, code: make([]string, n), pOwner: make([]int, n), docEnd: make([]int, n)} + for i := range n { + m.code[i] = m.classify(i) + m.pOwner[i] = -1 + m.docEnd[i] = -1 + } + m.conds, m.levels = sc.levelMap() + for i := range n { + if !f.is(i, "(") || f.toks[i].closer < 0 { + continue + } + owner := sc.pOwner[i] + if owner < 0 { + p := f.prevEffective(i - 1) + if f.is(p, "&") { + p = f.prevEffective(p - 1) + } + if p >= 0 && (sc.code[p] == "fn" || m.code[p] == "anon_class" || siCallOwners[strings.ToLower(f.toks[p].orig)] && !siIsMember(f, p)) { + owner = p + } + } + m.pOwner[i], m.pOwner[f.toks[i].closer] = owner, owner + } + open := -1 + for i := range n { + switch f.toks[i].doc { + case slvDocOpen: + open = i + case slvDocClose: + if open >= 0 { + m.docEnd[open] = i + open = -1 + } + } + } + return m +} + +func (m *siModel) classify(i int) string { + f := m.f + t := f.toks[i] + switch t.kind { + case token.String: + switch { + case t.heredoc && (i == 0 || !f.toks[i-1].heredoc): + return "start_heredoc" + case t.heredoc && (i+1 == len(f.toks) || !f.toks[i+1].heredoc): + return "end_heredoc" + case t.heredoc: + return "heredoc" + case t.interp: + return "double_quoted_string" + } + return "constant_encapsed_string" + case token.DocComment: + switch t.doc { + case slvDocOpen: + return "doc_open" + case slvDocWhitespace: + return "doc_whitespace" + } + return "doc" + case token.OpenTag: + if strings.HasPrefix(t.orig, "=") { + return "open_tag_with_echo" + } + return "open_tag" + case token.Punct: + switch { + case t.orig == "[" && f.isShortArrayOpen(i): + return "open_short_array" + case t.orig == "]" && t.closer >= 0 && f.isShortArrayOpen(t.closer): + return "close_short_array" + } + case token.Keyword: + switch strings.ToLower(t.orig) { + case "function": + if f.isClosure(i) { + return "closure" + } + case "class": + if phpcsIsAnonClassKeyword(f, i) { + return "anon_class" + } + } + } + return m.sc.code[i] +} + +// siCallOwners are the language constructs PHP_CodeSniffer gives the +// parentheses after them, whatever blink lexes them as. +var siCallOwners = phpcsSet("eval", "isset", "empty", "unset", "array", "list") + +func siIsMember(f *slvFile, i int) bool { + p := f.prevEffective(i - 1) + return f.is(p, "->") || f.is(p, "?->") || f.is(p, "::") || f.isKeyword(p, "function") +} + +var siScopeOpeners = phpcsSet("class", "anon_class", "interface", "trait", "enum", "namespace", "function", "closure", + "if", "switch", "case", "declare", "default", "while", "else", "elseif", "for", "foreach", "do", "try", "catch", + "finally", "use", "match") + +var siMethodModifiers = phpcsSet("private", "public", "protected", "abstract", "static", "final") + +func (m *siModel) lastCond(i int) int { + if c := m.conds[i]; len(c) > 0 { + return c[len(c)-1].key + } + return -1 +} + +// firstOnLine is File::findFirstOnLine with exclude: the first token on the +// line of start whose code is not in skip, or -1. +func (m *siModel) firstOnLine(start int, skip ...string) int { + found := -1 + for i := start; i >= 0; i-- { + if m.f.toks[i].line < m.f.toks[start].line { + break + } + if !slices.Contains(skip, m.code[i]) { + found = i + } + } + return found +} + +// siAt maps PHP's $tokens[false] to the first token. +func siAt(i int) int { return max(i, 0) } + +func (m *siModel) nextNonEmpty(i int) int { + for ; i < len(m.f.toks); i++ { + if !m.f.isEmpty(i) { + return i + } + } + return -1 +} + +// prevLocal is File::findPrevious with local set. +func (m *siModel) prevLocal(start int, types ...string) int { + f, sc := m.f, m.sc + for i := start; i >= 0; i-- { + if slices.Contains(types, m.code[i]) { + return i + } + t := f.toks[i] + switch { + case sc.opener[i] >= 0 && i == sc.closer[i]: + i = sc.opener[i] + case (f.is(i, "]") || f.is(i, "}")) && t.closer >= 0 && t.closer < i: + i = t.closer + case f.is(i, ")") && t.closer >= 0 && t.closer < i: + i = t.closer + case m.code[i] == ";": + return -1 + } + } + return -1 +} + +func (r ScopeIndent) ceil(v int) int { + return int(math.Ceil(float64(v)/float64(r.Indent))) * r.Indent +} + +func (r ScopeIndent) floor(v int) int { + return int(math.Floor(float64(v)/float64(r.Indent))) * r.Indent +} + +// siOrdered is a PHP array keyed by scope closer, kept in insertion order. +type siOrdered struct { + keys []int + vals map[int]int +} + +func (o *siOrdered) set(k, v int) { + if _, ok := o.vals[k]; !ok { + o.keys = append(o.keys, k) + } + o.vals[k] = v +} + +func (o *siOrdered) has(k int) bool { + _, ok := o.vals[k] + return ok +} + +func (o *siOrdered) pop() int { + if len(o.keys) == 0 { + return -1 + } + k := o.keys[len(o.keys)-1] + o.keys = o.keys[:len(o.keys)-1] + v := o.vals[k] + delete(o.vals, k) + return v +} + +func (o *siOrdered) last() int { + if len(o.keys) == 0 { + return -1 + } + return o.vals[o.keys[len(o.keys)-1]] +} + +func (r ScopeIndent) process(m *siModel, stackPtr int) { + f, sc, code := m.f, m.sc, m.code + toks := f.toks + n := len(toks) + tabWidth := slvTabWidth + + lastOpenTag := stackPtr + lastCloseTag := -1 + openScopes := &siOrdered{vals: map[int]int{}} + adjustments := map[int]int{} + setIndents := map[int]int{} + disableExactStack := map[int]bool{} + disableExactEnd := 0 + + currentIndent := 0 + first := -1 + for i := stackPtr; i >= 0 && toks[i].line == toks[stackPtr].line; i-- { + if code[i] == "inline_html" { + first = i + } + } + first = siAt(first) + if trimmed := phpcsLtrim(toks[first].content); trimmed == "" { + currentIndent = toks[stackPtr].column - 1 + } else { + currentIndent = len(toks[first].content) - len(trimmed) + } + + tokenIndent := 0 + for i := stackPtr + 1; i < n; i++ { + checkToken := -1 + checkIndent := -1 + hasCheckIndent := false + exact := r.Exact + + if f.is(i, "(") && toks[i].closer >= 0 { + disableExactStack[toks[i].closer] = true + disableExactEnd = max(disableExactEnd, toks[i].closer) + } + if exact && i < disableExactEnd { + exact = false + } + + if toks[i].column == 1 { + trimmed := phpcsLtrim(toks[i].content) + if trimmed == "" { + if i+1 < n && toks[i].line == toks[i+1].line { + checkToken = i + 1 + tokenIndent = toks[i+1].column - 1 + } + } else { + checkToken = i + tokenIndent = len(toks[i].content) - len(trimmed) + } + } + + if checkToken >= 0 && f.is(checkToken, ")") && toks[checkToken].closer >= 0 || + f.is(i, ")") && toks[i].closer >= 0 { + parenCloser := i + if checkToken >= 0 { + parenCloser = checkToken + } + parenOpener := toks[parenCloser].closer + if toks[parenCloser].line != toks[parenOpener].line { + parens := 0 + if nested := sc.nested[parenCloser]; nested >= 0 { + parens = nested + } + condition := 0 + if lc := m.lastCond(parenCloser); lc >= 0 && (m.pOwner[parenCloser] < 0 || parens > 0) { + condition = lc + } + if parens > condition { + parenOpener = parens + condition = 0 + } else if condition > 0 { + parenOpener = condition + parens = 0 + } + exact = false + + lastOpenTagCondition := m.lastCond(lastOpenTag) + switch { + case condition > 0 && lastOpenTagCondition == condition: + first = siAt(m.firstOnLine(lastOpenTag, "whitespace", "inline_html")) + checkIndent, hasCheckIndent = toks[first].column-1, true + checkIndent += adjustments[condition] + currentIndent = checkIndent + case condition > 0 && sc.opener[condition] >= 0 && siHas(setIndents, sc.opener[condition]): + checkIndent, hasCheckIndent = setIndents[sc.opener[condition]], true + checkIndent += adjustments[condition] + currentIndent = checkIndent + default: + first = siAt(m.firstOnLine(parenOpener, "whitespace")) + checkIndent, hasCheckIndent = toks[first].column-1, true + checkIndent += adjustments[first] + if first == toks[parenCloser].closer && toks[siAt(first-1)].line == toks[first].line { + first-- + } + prev := sc.startOfStatementIgnoring(first, ",") + if prev != first { + first = m.firstOnLine(prev, "whitespace", "inline_html") + if first >= 0 { + prev = sc.startOfStatementIgnoring(first, ",") + first = siAt(m.firstOnLine(prev, "whitespace", "inline_html")) + } else { + first = prev + } + } + if sc.closer[first] >= 0 && sc.closer[first] == first { + if sc.cond[first] >= 0 { + scopeCloser := first + first = siAt(m.firstOnLine(sc.cond[scopeCloser], "whitespace")) + currentIndent = toks[first].column - 1 + currentIndent += adjustments[first] + if code[sc.cond[scopeCloser]] != "closure" { + currentIndent = r.ceil(currentIndent) + } + setIndents[first] = currentIndent + } + } else { + currentIndent = toks[first].column - 1 + currentIndent += adjustments[first] + setIndents[first] = currentIndent + } + } + } + } + + if code[i] == "close_short_array" || checkToken >= 0 && code[checkToken] == "close_short_array" { + arrayCloser := i + if checkToken >= 0 { + arrayCloser = checkToken + } + arrayOpener := toks[arrayCloser].closer + if toks[arrayCloser].line != toks[arrayOpener].line { + first = siAt(m.firstOnLine(arrayOpener, "whitespace")) + exact = false + if first == arrayOpener { + first-- + } + prev := sc.startOfStatementIgnoring(first, ",", "=>") + if prev != first { + first = siAt(m.firstOnLine(prev, "whitespace")) + prev = sc.startOfStatementIgnoring(first, ",", "=>") + first = siAt(m.firstOnLine(prev, "whitespace")) + } else if code[first] == "whitespace" { + first = siAt(m.nextNonWhitespace(first + 1)) + } + checkIndent, hasCheckIndent = toks[first].column-1, true + checkIndent += adjustments[first] + if sc.closer[first] >= 0 && sc.closer[first] == first { + if v, ok := setIndents[first]; ok { + currentIndent = v + } + } else { + currentIndent = toks[first].column - 1 + currentIndent += adjustments[first] + setIndents[first] = currentIndent + } + } + } + + if checkToken >= 0 && !exact && (len(m.conds[checkToken]) > 0 || sc.opener[checkToken] >= 0 && sc.opener[checkToken] == checkToken) { + condition := sc.cond[checkToken] + if len(m.conds[checkToken]) > 0 { + condition = m.lastCond(checkToken) + } + first = siAt(m.firstOnLine(condition, "whitespace")) + // the sniff re-indents the line here only when $fixer->enabled, which + // ECS never sets + if adj, ok := adjustments[first]; ok && (adj < 0 && tokenIndent > currentIndent || adj > 0 && tokenIndent < currentIndent) { + adjustments[checkToken] = adj + } + } + + if checkToken >= 0 && (openScopes.has(checkToken) || + sc.cond[checkToken] >= 0 && sc.closer[checkToken] == checkToken && sc.opener[checkToken] >= 0 && + toks[checkToken].line != toks[sc.opener[checkToken]].line) || + checkToken < 0 && openScopes.has(i) { + scopeCloser := checkToken + if scopeCloser < 0 { + scopeCloser = i + } + openScopes.pop() + if sc.cond[scopeCloser] >= 0 { + first = siAt(m.firstOnLine(sc.cond[scopeCloser], "whitespace", "inline_html")) + for code[first] == "constant_encapsed_string" && first > 0 && code[first-1] == "constant_encapsed_string" { + first = siAt(m.firstOnLine(first-1, "whitespace")) + } + currentIndent = toks[first].column - 1 + currentIndent += adjustments[first] + setIndents[scopeCloser] = currentIndent + if f.is(scopeCloser, "}") { + exact = true + } else { + checkToken = -1 + } + } + } + + if checkToken >= 0 && siScopeOpeners[code[checkToken]] && sc.opener[checkToken] >= 0 { + exact = true + if disableExactEnd > checkToken { + for end := range disableExactStack { + if end < checkToken { + continue + } + if slices.Equal(m.conds[checkToken], m.conds[end]) { + exact = false + break + } + } + } + lastOpener := openScopes.last() + if lastOpener >= 0 && sc.closer[lastOpener] >= 0 && + m.levels[lastOpener] == m.levels[checkToken] && + sc.closer[lastOpener] == sc.closer[checkToken] { + currentIndent -= r.Indent + setIndents[lastOpener] = currentIndent + } + if code[checkToken] == "closure" && tokenIndent > currentIndent { + checkIndent, hasCheckIndent = r.ceil(tokenIndent), true + exact = false + } + } + + if checkToken >= 0 && siMethodModifiers[code[checkToken]] && (checkToken+1 >= n || code[checkToken+1] != "::") { + next := m.nextNonEmpty(checkToken + 1) + if next < 0 || code[next] != "closure" && code[next] != "variable" && code[next] != "fn" { + isMethodPrefix := true + if deepest := sc.nested[checkToken]; deepest >= 0 { + if owner := m.pOwner[deepest]; owner >= 0 && code[owner] == "function" { + isMethodPrefix = false + } + } + if isMethodPrefix { + exact = true + } + } + } + + if checkToken >= 0 && (code[checkToken] == "open_tag" || code[checkToken] == "open_tag_with_echo") { + checkIndent, hasCheckIndent = toks[checkToken].column-1, true + if len(m.conds[checkToken]) > 0 { + closeTag := -1 + for j := checkToken - 1; j >= 0; j-- { + if code[j] == "close_tag" { + closeTag = j + break + } + } + if closeTag >= 0 && slices.Equal(m.conds[checkToken], m.conds[closeTag]) { + lastCondition := m.lastCond(checkToken) + lastOpener, lastCloser := sc.opener[lastCondition], sc.closer[lastCondition] + if v, ok := setIndents[lastOpener]; ok && toks[siAt(lastCloser)].line != toks[checkToken].line { + checkIndent = v + } + } + } + } + + if checkToken >= 0 && code[checkToken] == "close_tag" { + exact = true + checkIndent, hasCheckIndent = r.ceil(currentIndent), true + } + + if checkToken >= 0 && code[checkToken] == "else" { + exact = true + } + + if checkToken >= 0 && (code[checkToken] == "->" || code[checkToken] == "?->") && exact { + exact = false + } + + if !hasCheckIndent { + checkIndent = currentIndent + } + + if checkToken >= 0 && code[checkToken] != "inline_html" && + (tokenIndent != checkIndent && exact || tokenIndent < checkIndent && !exact) { + adjustments[checkToken] = checkIndent - tokenIndent + r.adjustIndent(m, checkToken, checkIndent, checkIndent-tokenIndent, tabWidth) + } + + if checkToken >= 0 { + i = checkToken + } + + if code[i] == "open_short_array" { + disableExactStack[toks[i].closer] = true + disableExactEnd = max(disableExactEnd, toks[i].closer) + } + + if code[i] == "start_heredoc" { + end := -1 + for j := i + 1; j < n; j++ { + if code[j] == "end_heredoc" { + end = j + break + } + } + if end < 0 { + return + } + i = end + if next := m.nextNonEmpty(i + 1); code[siAt(next)] == "," { + i = siAt(next) + } + continue + } + + if code[i] == "constant_encapsed_string" || code[i] == "double_quoted_string" { + for j := i + 1; j < n; j++ { + if code[j] != code[i] { + i = j - 1 + break + } + } + continue + } + + if code[i] == "doc_open" { + if m.docEnd[i] >= 0 { + i = m.docEnd[i] + } + continue + } + + if code[i] == "open_tag" || code[i] == "open_tag_with_echo" { + if checkToken < 0 { + first = siAt(m.firstOnLine(i, "whitespace")) + currentIndent = len(toks[first].content) - len(phpcsLtrim(toks[first].content)) + } else { + currentIndent = toks[i].column - 1 + } + lastOpenTag = i + currentIndent += adjustments[i] + currentIndent = r.ceil(currentIndent) + setIndents[i] = currentIndent + continue + } + + if code[i] == "close_tag" { + if toks[lastOpenTag].line != toks[i].line { + currentIndent = toks[i].column - 1 + lastCloseTag = i + } else if lastCloseTag < 0 { + currentIndent = 0 + } else { + currentIndent = toks[lastCloseTag].column - 1 + } + currentIndent += adjustments[i] + currentIndent = r.ceil(currentIndent) + setIndents[i] = currentIndent + continue + } + + if code[i] == "closure" || code[i] == "anon_class" { + closer := sc.closer[i] + if closer < 0 { + continue + } + if toks[i].line == toks[closer].line { + i = closer + continue + } + first = siAt(m.firstOnLine(i, "whitespace")) + for code[first] == "constant_encapsed_string" && first > 0 && code[first-1] == "constant_encapsed_string" { + first = siAt(m.firstOnLine(first-1, "whitespace")) + } + currentIndent = toks[first].column - 1 + r.Indent + openScopes.set(closer, sc.cond[i]) + currentIndent += adjustments[first] + currentIndent = r.floor(currentIndent) + i = sc.opener[i] + setIndents[i] = currentIndent + continue + } + + if sc.cond[i] >= 0 && sc.opener[i] >= 0 && sc.opener[i] == i { + closer := sc.closer[i] + if toks[i].line == toks[siAt(closer)].line { + i = closer + continue + } + if siScopeOpeners[code[sc.cond[i]]] { + currentIndent += r.Indent + setIndents[i] = currentIndent + openScopes.set(closer, sc.cond[i]) + continue + } + } + + if sc.cond[i] >= 0 && sc.closer[i] == i { + switch code[sc.cond[i]] { + case "closure", "anon_class", "match", "fn": + default: + continue + } + prev := -1 + parens := 0 + if nested := sc.nested[i]; nested >= 0 { + parens = nested + } + condition := 0 + if lc := m.lastCond(i); lc >= 0 { + condition = lc + } + if parens > condition { + prev = f.prevEffective(parens - 1) + condition = 0 + } else if condition > 0 { + prev = condition + parens = 0 + } + if prev < 0 { + prev = m.prevLocal(sc.cond[i]-1, "=", "return") + if prev < 0 { + prev = i + } + } + first = siAt(m.firstOnLine(prev, "whitespace")) + prev = sc.startOfStatementIgnoring(first) + if prev != first { + first = siAt(m.firstOnLine(prev, "whitespace")) + } + currentIndent = toks[first].column - 1 + if condition > 0 { + currentIndent += r.Indent + } + if sc.closer[first] >= 0 && sc.closer[first] == first { + if condition == 0 || sc.opener[condition] < first { + currentIndent = setIndents[first] + } + } + currentIndent = r.ceil(currentIndent) + setIndents[first] = currentIndent + } + } +} + +func siHas(m map[int]int, k int) bool { + _, ok := m[k] + return ok +} + +func (m *siModel) nextNonWhitespace(i int) int { + for ; i < len(m.code); i++ { + if m.code[i] != "whitespace" { + return i + } + } + return -1 +} + +func (r ScopeIndent) padding(length, tabWidth int) string { + if length <= 0 { + return "" + } + if !r.TabIndent { + return strings.Repeat(" ", length) + } + numTabs := length / tabWidth + if numTabs == 0 { + return "" + } + return strings.Repeat("\t", numTabs) + strings.Repeat(" ", length-numTabs*tabWidth) +} + +func (r ScopeIndent) adjustIndent(m *siModel, stackPtr, length, change, tabWidth int) { + f := m.f + toks := f.toks + if m.code[stackPtr] == "inline_html" { + return + } + padding := r.padding(length, tabWidth) + var accepted bool + if toks[stackPtr].column == 1 { + accepted = f.replaceToken(stackPtr, padding+phpcsLtrim(toks[stackPtr].content)) + } else { + accepted = f.replaceToken(stackPtr-1, padding) + } + if !accepted || m.code[stackPtr] != "doc_open" { + return + } + for x := stackPtr + 1; x < m.docEnd[stackPtr]; x++ { + if toks[x].column != 1 { + continue + } + l := 0 + if m.code[x] == "doc_whitespace" { + l = toks[x].length + } + pad := "" + if p := l + change; p > 0 { + if r.TabIndent { + numTabs := p / tabWidth + pad = strings.Repeat("\t", numTabs) + strings.Repeat(" ", p-numTabs*tabWidth) + } else { + pad = strings.Repeat(" ", p) + } + } + f.replaceToken(x, pad) + } +} diff --git a/blink/internal/fixer/rules/slevomat.go b/blink/internal/fixer/rules/slevomat.go index 9f392199a7..fa0b3ea478 100644 --- a/blink/internal/fixer/rules/slevomat.go +++ b/blink/internal/fixer/rules/slevomat.go @@ -114,6 +114,7 @@ func newSlvFile(toks []token.Token) *slvFile { func slvSplit(toks []token.Token) []slvTok { var out []slvTok eol := slvRawEOL(toks) + toks = slvSplitYieldFrom(toks) add := func(k token.Kind, v string, heredoc bool) { for v != "" { n := strings.IndexByte(v, '\n') @@ -187,6 +188,41 @@ func slvSplit(toks []token.Token) []slvTok { return out } +var slvYieldFromOneLine = regexp.MustCompile(`(?i)^yield[ \t]+from$`) + +// slvSplitYieldFrom splits a "yield from" holding a newline or a comment, which +// PHP lexes as one T_YIELD_FROM, into "yield", the tokens between and "from", +// like PHP_CodeSniffer's PHP tokenizer. +func slvSplitYieldFrom(toks []token.Token) []token.Token { + var out []token.Token + for n, t := range toks { + v := t.Value + if t.Kind != token.Keyword || len(v) <= 9 || !strings.EqualFold(v[:5], "yield") || slvYieldFromOneLine.MatchString(v) { + if out != nil { + out = append(out, t) + } + continue + } + if out == nil { + out = append(out, toks[:n]...) + } + out = append(out, token.Token{Kind: token.Keyword, Value: v[:5]}) + inner := lexer.Lex(" 0 { + inner[0].Value = strings.TrimPrefix(inner[0].Value, "\n") + if inner[0].Value == "" { + inner = inner[1:] + } + } + out = append(out, inner...) + out = append(out, token.Token{Kind: token.Keyword, Value: v[len(v)-4:]}) + } + if out == nil { + return toks + } + return out +} + // slvNameEnd returns the last token of a qualified name starting at i // ("Foo\Bar", "\Foo", "namespace\Foo"), which PHP lexes as one token, or -1. func slvNameEnd(toks []token.Token, i int) int { diff --git a/blink/internal/fixer/rules/squiz_array_declaration.go b/blink/internal/fixer/rules/squiz_array_declaration.go new file mode 100644 index 0000000000..38b61382fd --- /dev/null +++ b/blink/internal/fixer/rules/squiz_array_declaration.go @@ -0,0 +1,500 @@ +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/Arrays/ArrayDeclarationSniff.php +// +// SquizArrayDeclaration lays out array declarations: a single-line array +// keeps one value, a multi-line one puts each value on its own line ending in +// a comma, with keys, double arrows and values aligned. +type SquizArrayDeclaration struct{} + +func (SquizArrayDeclaration) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Arrays\ArrayDeclarationSniff` +} + +func (SquizArrayDeclaration) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Arrays/ArrayDeclarationSniff.php" +} + +func (SquizArrayDeclaration) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + a := &squizArrays{f: f, sc: newPhpcsScope(f)} + for i := range f.toks { + if a.isArray(i) || f.isShortArrayOpen(i) { + a.process(i) + } + } + }) +} + +type squizArrays struct { + f *slvFile + sc *phpcsScope +} + +type squizArrayEntry struct { + value, index, arrow int // -1 when unset + indexLength int +} + +// isArray tells T_ARRAY: the "array" keyword that owns parentheses. +func (a *squizArrays) isArray(i int) bool { + return a.f.isKeyword(i, "array") && a.sc.pCloser[i] >= 0 +} + +func (a *squizArrays) depth(i int) int { + n := 0 + for p := a.sc.nested[i]; p >= 0; p = a.sc.nested[p] { + n++ + } + return n +} + +// nextNot is File::findNext with exclude=true: the first token in +// [start, end) that skip rejects, or -1. +func (a *squizArrays) nextNot(skip func(int) bool, start, end int) int { + end = min(end, len(a.f.toks)) + for i := max(start, 0); i < end; i++ { + if !skip(i) { + return i + } + } + return -1 +} + +// prevNot is File::findPrevious with exclude=true: the first token in +// [end, start] going down that skip rejects, or -1. +func (a *squizArrays) prevNot(skip func(int) bool, start, end int) int { + for i := min(start, len(a.f.toks)-1); i >= max(end, 0); i-- { + if !skip(i) { + return i + } + } + return -1 +} + +func (a *squizArrays) isCast(i int) bool { + t := a.f.toks[i] + return t.kind == token.Punct && len(t.orig) > 1 && t.orig[0] == '(' +} + +func (a *squizArrays) isClosureOrFn(i int) bool { + return a.f.isKeyword(i, "function") && a.f.isClosure(i) || a.sc.code[i] == "fn" +} + +func (a *squizArrays) isEndHeredoc(i int) bool { return a.sc.code[i] == "end_heredoc" } + +func (a *squizArrays) process(stackPtr int) { + f, sc := a.f, a.sc + if f.is(stackPtr, "[") { + if p := sc.nested[stackPtr]; p >= 0 { + if owner := sc.pOwner[p]; owner >= 0 && sc.code[owner] == "foreach" { + closer := f.toks[p].closer + for j := p + 1; j < closer; j++ { + if f.isKeyword(j, "as") { + if j < stackPtr { + return + } + break + } + } + } + } + } + + var arrayStart, arrayEnd int + if !f.is(stackPtr, "[") { + if f.toks[stackPtr].orig != strings.ToLower(f.toks[stackPtr].orig) { + f.replaceToken(stackPtr, "array") + } + arrayEnd = sc.pCloser[stackPtr] + arrayStart = f.toks[arrayEnd].closer + if arrayStart != stackPtr+1 { + next := a.nextNot(f.isWS, stackPtr+1, arrayStart) + if next < 0 || !f.isCommentToken(next) { + f.beginChangeset() + for i := stackPtr + 1; i < arrayStart; i++ { + f.replaceToken(i, "") + } + f.endChangeset() + } + } + } else { + arrayStart, arrayEnd = stackPtr, f.toks[stackPtr].closer + } + + if a.nextNot(f.isWS, arrayStart+1, arrayEnd+1) == arrayEnd { + if arrayEnd-arrayStart != 1 { + f.beginChangeset() + for i := arrayStart + 1; i < arrayEnd; i++ { + f.replaceToken(i, "") + } + f.endChangeset() + } + return + } + + if f.toks[arrayStart].line == f.toks[arrayEnd].line { + a.singleLine(stackPtr, arrayStart, arrayEnd) + } else { + a.multiLine(stackPtr, arrayStart, arrayEnd) + } +} + +func (a *squizArrays) singleLine(stackPtr, arrayStart, arrayEnd int) { + f, sc := a.f, a.sc + valueCount := 0 + var commas []int + for i := arrayStart + 1; i < arrayEnd; i++ { + if f.is(i, "(") { + if f.toks[i].closer > i { + i = f.toks[i].closer + } + continue + } + if f.is(i, ",") { + if a.nextNot(f.isWS, i+1, arrayEnd) >= 0 { + valueCount++ + commas = append(commas, i) + } else { + f.replaceToken(i, "") + } + } + } + + for arrow := arrayStart + 1; arrow < arrayEnd; arrow++ { + if sc.code[arrow] != "=>" { + continue + } + if !f.isWS(arrow - 1) { + f.addContentBefore(arrow, " ") + } else if f.toks[arrow-1].length != 1 { + f.replaceToken(arrow-1, " ") + } + if !f.isWS(arrow + 1) { + f.addContent(arrow, " ") + } else if f.toks[arrow+1].length != 1 { + f.replaceToken(arrow+1, " ") + } + } + + if valueCount == 0 { + return + } + p := sc.nested[stackPtr] + if p < 0 || f.toks[f.toks[p].closer].line != f.toks[stackPtr].line { + f.beginChangeset() + f.addContent(arrayStart, f.eol) + if f.isWS(arrayEnd - 1) { + f.replaceToken(arrayEnd-1, f.eol) + } else { + f.addContentBefore(arrayEnd, f.eol) + } + f.endChangeset() + return + } + for _, comma := range commas { + if !f.isWS(comma + 1) { + f.addContent(comma, " ") + } else if f.toks[comma+1].length != 1 { + f.replaceToken(comma+1, " ") + } + if f.isWS(comma - 1) { + f.replaceToken(comma-1, "") + } + } +} + +func (a *squizArrays) multiLine(stackPtr, arrayStart, arrayEnd int) { + f, sc := a.f, a.sc + col := func(i int) int { return f.toks[i].column } + line := func(i int) int { return f.toks[i].line } + spaces := func(n int) string { return strings.Repeat(" ", max(n, 0)) } + keywordStart := col(stackPtr) + + lastContent := a.prevNot(f.isWS, arrayEnd-1, arrayStart) + if line(lastContent) == line(arrayEnd) { + f.addContentBefore(arrayEnd, f.eol) + } else if col(arrayEnd) != keywordStart { + expected, found := keywordStart-1, col(arrayEnd)-1 + if found == 0 { + f.addContent(arrayEnd-1, spaces(expected)) + } else { + f.replaceToken(arrayEnd-1, spaces(expected)) + } + } + + keyUsed, singleUsed := false, false + var indices []squizArrayEntry + maxLength := 0 + lastToken := stackPtr + if !f.is(stackPtr, "[") { + lastToken = arrayStart + } + + for next := stackPtr + 1; next < arrayEnd; next++ { + if f.is(next, "(") && sc.pOwner[next] != stackPtr { + if f.toks[next].closer > next { + next = f.toks[next].closer + } + continue + } + + if a.isArray(next) || f.isShortArrayOpen(next) || a.isClosureOrFn(next) || sc.code[next] == "match" { + if sc.code[lastToken] != "=>" { + indices = append(indices, squizArrayEntry{value: next, index: -1, arrow: -1}) + lastToken = next + } + switch { + case a.isArray(next): + next = sc.pCloser[next] + case f.is(next, "["): + next = f.toks[next].closer + default: + if sc.closer[next] < 0 { + continue + } + next = sc.closer[next] + } + next = a.nextNot(f.isWS, next+1, len(f.toks)) + if next < 0 { + break + } + if !f.is(next, ",") { + next-- + } else { + lastToken = next + } + continue + } + + if sc.code[next] != "=>" && !f.is(next, ",") { + continue + } + + if f.is(next, ",") { + stackPtrCount := a.depth(stackPtr) + commaCount := a.depth(next) + if commaCount > 0 && !f.is(stackPtr, "[") { + commaCount-- + } + if commaCount > stackPtrCount { + continue + } + if keyUsed && f.is(lastToken, ",") { + next = a.nextNot(f.isEmpty, lastToken+1, len(f.toks)) + if next < 0 || !f.is(next, "...") { + return + } + } + if !keyUsed { + if f.isWS(next - 1) { + prev := a.prevNot(f.isEmpty, next-1, 0) + if !a.isEndHeredoc(prev) || line(next-1) == line(next) { + if prev == a.prevNot(f.isWS, next-1, 0) { + f.replaceToken(next-1, "") + } + } + } + valueContent := a.nextNot(f.isEmpty, lastToken+1, next) + indices = append(indices, squizArrayEntry{value: valueContent, index: -1, arrow: -1}) + unpack := a.prevNot(f.isEmpty, next-2, 0) + if unpack < 0 || !f.is(unpack, "...") { + singleUsed = true + } + } + lastToken = next + continue + } + + if singleUsed { + return + } + keyUsed = true + indexEnd := a.prevNot(f.isWS, next-1, arrayStart) + indexStart := sc.startOfStatement(indexEnd) + entry := squizArrayEntry{arrow: next, index: indexEnd, indexLength: f.toks[indexEnd].length} + if indexStart != indexEnd { + entry.index, entry.indexLength = indexStart, 0 + for i := indexStart; i <= indexEnd; i++ { + entry.indexLength += f.toks[i].length + } + } + maxLength = max(maxLength, entry.indexLength) + entry.value = a.nextNot(f.isEmpty, next+1, arrayEnd) + indices = append(indices, entry) + lastToken = next + } + + singleValue := false + if len(indices) == 0 { + singleValue = true + } else if len(indices) == 1 && f.is(lastToken, ",") { + skip := func(i int) bool { return f.isEmpty(i) || f.is(i, ",") } + if a.nextNot(skip, max(indices[0].value, 0)+1, arrayEnd) < 0 { + singleValue = true + } + } + if singleValue && a.nextNot(func(i int) bool { return !f.toks[i].heredoc }, arrayStart+1, arrayEnd-1) < 0 { + notComment := func(i int) bool { return f.toks[i].kind != token.Comment && !phpcsIsAnnotation(f, i) } + if a.nextNot(notComment, arrayStart+1, arrayEnd) < 0 { + f.beginChangeset() + for i := arrayStart + 1; i < arrayEnd && f.isWS(i); i++ { + f.replaceToken(i, "") + } + for i := arrayEnd - 1; i > arrayStart && f.isWS(i); i-- { + f.replaceToken(i, "") + } + f.endChangeset() + } + return + } + + if !keyUsed && len(indices) > 0 { + lastIndex := max(indices[len(indices)-1].value, 0) + trailing := max(a.prevNot(f.isEmpty, arrayEnd-1, lastIndex), 0) + if !f.is(trailing, ",") { + f.addContent(trailing, ",") + } + ignore := func(i int) bool { return f.isWS(i) || f.is(i, ",") || a.isCast(i) } + for _, v := range indices { + valuePointer := v.value + if valuePointer <= 0 { + continue + } + if a.isClosureOrFn(valuePointer) { + if st := a.prevNot(ignore, valuePointer-1, arrayStart+1); st >= 0 && f.isKeyword(st, "static") { + valuePointer = st + } + } + previous := a.prevNot(ignore, valuePointer-1, arrayStart+1) + if previous < 0 { + previous = stackPtr + } + prevIsWS := f.isWS(valuePointer - 1) + if line(previous) == line(valuePointer) { + if prevIsWS { + f.replaceToken(valuePointer-1, f.eol) + } else { + f.addContentBefore(valuePointer, f.eol) + } + } else if prevIsWS { + first := f.firstNonWhitespaceOnLine(valuePointer) + if found := col(first) - 1; found != keywordStart { + if found == 0 { + f.addContent(first-1, spaces(keywordStart)) + } else { + f.replaceToken(first-1, spaces(keywordStart)) + } + } + } + } + } + + indicesStart := keywordStart + 1 + for _, index := range indices { + valuePointer := index.value + if valuePointer < 0 || index.index < 0 { + continue + } + indexPointer := index.index + indexLine := line(indexPointer) + previous := a.prevNot(func(i int) bool { return f.isWS(i) || f.is(i, ",") }, indexPointer-1, arrayStart+1) + if previous < 0 { + previous = stackPtr + } + if line(previous) == indexLine { + if f.isWS(indexPointer - 1) { + f.replaceToken(indexPointer-1, f.eol) + } else { + f.addContentBefore(indexPointer, f.eol) + } + continue + } + + if col(indexPointer) != indicesStart && indexPointer-1 != arrayStart { + expected, found := indicesStart-1, col(indexPointer)-1 + if found == 0 || !f.isWS(indexPointer-1) { + f.addContent(indexPointer-1, spaces(expected)) + } else { + f.replaceToken(indexPointer-1, spaces(expected)) + } + } + + arrowStart := col(indexPointer) + maxLength + 1 + if col(index.arrow) != arrowStart { + base := index.indexLength + col(indexPointer) + expected, found := arrowStart-base, col(index.arrow)-base + if found == 0 { + f.addContent(index.arrow-1, spaces(expected)) + } else { + f.replaceToken(index.arrow-1, spaces(expected)) + } + continue + } + + valueStart := arrowStart + 3 + if col(valuePointer) != valueStart { + base := f.toks[index.arrow].length + col(index.arrow) + expected, found := valueStart-base, col(valuePointer)-base + switch { + case found < 0: + prev := a.prevNot(f.isWS, valuePointer-1, 0) + f.beginChangeset() + for i := prev + 1; i < valuePointer; i++ { + f.replaceToken(i, "") + } + f.replaceToken(valuePointer-1, spaces(expected)) + f.endChangeset() + case found == 0: + f.addContent(valuePointer-1, spaces(expected)) + default: + f.replaceToken(valuePointer-1, spaces(expected)) + } + } + + nextComma := -1 + var valueEnd int + end := sc.endOfStatement(valuePointer) + if f.is(end, ",") { + valueEnd = a.prevNot(f.isEmpty, end-1, valuePointer) + nextComma = end + } else { + valueEnd = end + if n := a.nextNot(f.isEmpty, end+1, arrayEnd); n >= 0 && f.is(n, ",") { + nextComma = n + } + } + valueLine := line(valueEnd) + if a.isEndHeredoc(valueEnd) { + valueLine++ + } + + if nextComma < 0 || line(nextComma) != valueLine { + i := valuePointer + 1 + for ; i <= arrayEnd; i++ { + if line(i) > valueLine { + break + } + } + f.beginChangeset() + f.addContentBefore(i-1, ",") + if nextComma >= 0 { + f.replaceToken(nextComma, "") + } + f.endChangeset() + } + + if nextComma >= 0 && f.isWS(nextComma-1) { + if prev := a.prevNot(f.isEmpty, nextComma-1, 0); !a.isEndHeredoc(prev) { + f.replaceToken(nextComma-1, "") + } + } + } +} diff --git a/blink/internal/fixer/rules/squiz_block_comment.go b/blink/internal/fixer/rules/squiz_block_comment.go new file mode 100644 index 0000000000..dfdadbfc23 --- /dev/null +++ b/blink/internal/fixer/rules/squiz_block_comment.go @@ -0,0 +1,196 @@ +package rules + +import ( + "regexp" + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/token" + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +const phpTrimChars = " \t\n\r\x00\x0B" + +// phpcsIsPlainComment reports whether i is a T_COMMENT: a comment that is +// neither a docblock piece nor a phpcs: annotation. +func phpcsIsPlainComment(f *slvFile, i int) bool { + return f.toks[i].kind == token.Comment && !phpcsIsAnnotation(f, i) +} + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/BlockCommentSniff.php +// +// SquizBlockComment turns an inline "/** */" docblock into "/* */", a +// one-line "/* text */" ending its line into "// text", drops empty block +// comments and aligns the lines of a multi-line block comment to its star. +type SquizBlockComment struct{} + +func (SquizBlockComment) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\BlockCommentSniff` +} + +func (SquizBlockComment) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/BlockCommentSniff.php" +} + +func (SquizBlockComment) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + for i := range f.toks { + switch { + case f.toks[i].doc == slvDocOpen: + squizBlockDocComment(f, i) + case phpcsIsPlainComment(f, i): + squizBlockComment(f, i) + } + } + }) +} + +// squizBlockCommentSkip lists the tokens a docblock may document; one before +// any other is an inline docblock. +var squizBlockCommentSkip = phpcsSet("public", "private", "protected", "public(set)", "protected(set)", "private(set)", + "class", "interface", "trait", "enum", "final", "static", "abstract", "const", "var", "readonly") + +func squizBlockDocComment(f *slvFile, ptr int) { + next := ptr + for { + next = f.nextEffective(next+1, len(f.toks)) + if next >= 0 && f.toks[next].kind == token.AttributeStart && f.toks[next].closer > next { + next = f.toks[next].closer + continue + } + break + } + if next >= 0 && f.toks[next].kind == token.Keyword { + if squizBlockCommentSkip[strings.ToLower(f.toks[next].orig)] || phpcsIsNamedFunction(f, next) { + return + } + } + if prev := max(f.prevEffective(ptr-1), 0); f.toks[prev].kind == token.OpenTag && !phpcsIsEchoTag(f, prev) { + return + } + f.replaceToken(ptr, "/*") + end := ptr + 1 + for end < len(f.toks) && f.toks[end].doc != slvDocClose { + end++ + } + if end < len(f.toks) && f.toks[end].content != "*/" { + f.replaceToken(end, "*/") + } +} + +func phpcsIsEchoTag(f *slvFile, i int) bool { + return strings.HasPrefix(f.toks[i].orig, "=") +} + +var squizBlockCommentOpener = regexp.MustCompile(`^(\s*/\*\*?)`) + +func squizBlockComment(f *slvFile, ptr int) { + if !strings.HasPrefix(f.toks[ptr].content, "/*") { + return + } + commentLines := []int{ptr} + lastLine := f.toks[ptr].line + var commentString strings.Builder + commentString.WriteString(f.toks[ptr].content) + for next := ptr; ; { + next = f.nextNot(func(i int) bool { return f.isWS(i) }, next+1, len(f.toks)) + if next < 0 || f.toks[next].kind != token.Comment || f.toks[next].line-1 != lastLine { + break + } + lastLine = f.toks[next].line + commentLines = append(commentLines, next) + commentString.WriteString(f.toks[next].content) + if strings.HasSuffix(f.toks[next].content, "*/") { + break + } + } + + commentText := strings.Trim(strings.ReplaceAll(commentString.String(), f.eol, ""), "/* \t") + if commentText == "" { + f.beginChangeset() + f.replaceToken(ptr, "") + for i := ptr + 1; i <= commentLines[len(commentLines)-1]; i++ { + f.replaceToken(i, "") + } + f.endChangeset() + return + } + + if len(commentLines) == 1 { + next := max(f.nextEffective(ptr+1, len(f.toks)), 0) + if f.toks[ptr].line != f.toks[next].line { + f.replaceToken(ptr, "// "+commentText+f.eol) + } + return + } + + if content := strings.Trim(f.toks[ptr].content, phpTrimChars); content != "/*" && content != "/**" { + indent := "" + if ptr > 0 && f.isWS(ptr-1) { + indent = f.toks[ptr-1].orig + } + comment := f.toks[ptr].content + if m := squizBlockCommentOpener.FindStringIndex(comment); m != nil { + comment = comment[:m[1]] + f.eol + indent + comment[m[1]:] + } + f.replaceToken(ptr, comment) + return + } + + starColumn := f.toks[ptr].column + hasStars := false + padding := func(line, expected int) string { + if strings.HasPrefix(f.toks[line].orig, "\t") { + return strings.Repeat("\t", expected/phpcsTabStop) + strings.Repeat(" ", expected%phpcsTabStop) + } + return strings.Repeat(" ", expected) + } + expectedFor := func(text string) int { + if text[0] == '*' { + hasStars = true + return starColumn + } + return starColumn + 3 + } + + first := commentLines[1] + if strings.Trim(f.toks[first].content, phpTrimChars) == "" { + f.replaceToken(first, "") + } else { + content := f.toks[first].content + text := strings.TrimLeft(content, phpTrimChars) + expected := expectedFor(text) + if len(content)-len(text) != expected { + f.replaceToken(first, padding(first, expected)+text) + } + } + + lastIndex := len(commentLines) - 1 + for n, line := range commentLines { + if n == 0 || n == 1 || n == lastIndex { + continue + } + content := f.toks[line].content + if strings.Trim(content, phpTrimChars) == "" { + continue + } + text := strings.TrimLeft(content, phpTrimChars) + expected := expectedFor(text) + if len(content)-len(text) < expected { + f.replaceToken(line, padding(line, expected)+text) + } + } + + last := commentLines[lastIndex] + content := f.toks[last].content + text := strings.TrimLeft(content, phpTrimChars) + if text != "*/" && text != "**/" { + return + } + expected := starColumn - 1 + if hasStars { + expected = starColumn + } + if len(content)-len(text) != expected { + f.replaceToken(last, padding(last, expected)+text) + } +} diff --git a/blink/internal/fixer/rules/squiz_class_declaration.go b/blink/internal/fixer/rules/squiz_class_declaration.go new file mode 100644 index 0000000000..a3d54f711a --- /dev/null +++ b/blink/internal/fixer/rules/squiz_class_declaration.go @@ -0,0 +1,134 @@ +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/Squiz/Sniffs/Classes/ClassDeclarationSniff.php +// +// SquizClassDeclaration runs PSR2's opening checks, puts the keyword of an +// unmodified declaration at column 1, and wants the closing brace alone on its +// line, at column 1, followed by one blank line. +type SquizClassDeclaration struct { + Indent int +} + +func (SquizClassDeclaration) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Classes\ClassDeclarationSniff` +} + +func (SquizClassDeclaration) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Classes/ClassDeclarationSniff.php" +} + +func (r SquizClassDeclaration) WithConfig(config map[string]any) fixer.Fixer { + r.Indent = configInt(config, "indent", r.Indent) + return r +} + +func (r SquizClassDeclaration) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + for i := range f.toks { + if open := phpcsClassyOpener(f, i); open >= 0 { + pearClassDeclaration(f, i, open) + d := classDecl{keyword: i, open: open, parenOpen: -1, indent: r.Indent} + d.processOpen(f) + squizSpaceBeforeKeyword(f, i) + squizClassClose(f, open) + } + } + }) +} + +func squizSpaceBeforeKeyword(f *slvFile, stackPtr int) { + if stackPtr < 1 || !f.isWS(stackPtr-1) || f.toks[stackPtr-1].content == f.eol { + return + } + if f.isKeyword(stackPtr-2, "abstract") || f.isKeyword(stackPtr-2, "final") || f.isKeyword(stackPtr-2, "readonly") { + return + } + f.replaceToken(stackPtr-1, "") +} + +func squizClassClose(f *slvFile, open int) { + closeBrace := f.toks[open].closer + if closeBrace < 0 { + return + } + n := len(f.toks) + line := func(i int) int { return f.toks[i].line } + + nextContent := closeBrace + 1 + for ; nextContent < n; nextContent++ { + if line(nextContent) == line(closeBrace) && + (f.isWS(nextContent) || f.toks[nextContent].kind == token.Comment || phpcsIsAnnotation(f, nextContent)) { + continue + } + if !f.isWS(nextContent) { + break + } + } + + difference := 1 + if nextContent < n { + difference = line(nextContent) - line(closeBrace) - 1 + } + + lastContent := f.prevNonWhitespace(closeBrace - 1) + + if difference == -1 || line(lastContent) == line(closeBrace) { + if difference == -1 { + f.addContentBefore(nextContent, f.eol) + } + if line(lastContent) == line(closeBrace) { + f.addContentBefore(closeBrace, f.eol) + } + } else if f.isWS(closeBrace - 1) { + if f.toks[closeBrace-1].content != f.eol && line(closeBrace-1) == line(closeBrace) { + f.replaceToken(closeBrace-1, "") + } + } + + if difference == -1 || difference == 1 { + return + } + + next := nextContent + for ; next < n; next++ { + if f.isWS(next) { + continue + } + if f.toks[next].doc == slvDocOpen { + for next < n && f.toks[next].doc != slvDocClose { + next++ + } + continue + } + if f.toks[next].kind == token.AttributeStart && f.toks[next].closer >= 0 { + next = f.toks[next].closer + continue + } + break + } + if next < n && f.isKeyword(next, "function") { + return + } + + if difference == 0 { + f.addContentBefore(f.firstOnLine(nextContent), f.eol) + return + } + f.beginChangeset() + for i := closeBrace + 1; i < nextContent; i++ { + if line(i) <= line(closeBrace)+1 { + continue + } + if line(i) == line(nextContent) { + break + } + f.replaceToken(i, "") + } + f.endChangeset() +} diff --git a/blink/internal/fixer/rules/squiz_control_structure_spacing.go b/blink/internal/fixer/rules/squiz_control_structure_spacing.go new file mode 100644 index 0000000000..241d3d68aa --- /dev/null +++ b/blink/internal/fixer/rules/squiz_control_structure_spacing.go @@ -0,0 +1,209 @@ +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/WhiteSpace/ControlStructureSpacingSniff.php +// +// SquizControlStructureSpacing removes the spaces inside a control structure's +// parentheses and the blank lines at the start and end of its body, and wants +// one blank line after it. +type SquizControlStructureSpacing struct{} + +func (SquizControlStructureSpacing) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ControlStructureSpacingSniff` +} + +func (SquizControlStructureSpacing) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php" +} + +var squizControlStructures = phpcsSet("if", "while", "foreach", "for", "switch", "do", "else", "elseif", "try", + "catch", "finally", "match") + +func (SquizControlStructureSpacing) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + sc := newPhpcsScope(f) + for i := range f.toks { + if f.toks[i].kind == token.Keyword && squizControlStructures[sc.code[i]] { + squizControlStructureSpacing(sc, i) + } + } + }) +} + +// squizIgnoredStructure tells the structures whose spacing other sniffs check: +// named functions, classes, interfaces, traits, enums and docblocks. +func squizIgnoredStructure(sc *phpcsScope, i int) bool { + f := sc.f + switch sc.code[i] { + case "function": + return squizFunctionCode(sc, i) == "function" + case "class": + return !phpcsIsAnonClassKeyword(f, i) + case "interface", "trait", "enum": + return true + } + return f.toks[i].kind == token.DocComment && f.toks[i].doc == slvDocOpen +} + +// squizIsComment is T_COMMENT or a phpcs: annotation. +func squizIsComment(f *slvFile, i int) bool { + return f.toks[i].kind == token.Comment || phpcsIsAnnotation(f, i) +} + +func squizControlStructureSpacing(sc *phpcsScope, stackPtr int) { + f := sc.f + n := len(f.toks) + if pc := sc.pCloser[stackPtr]; pc >= 0 && f.toks[pc].closer >= 0 { + po := f.toks[pc].closer + if f.toks[po+1].kind == token.Whitespace { + f.replaceToken(po+1, "") + } + if f.toks[po].line == f.toks[pc].line && f.toks[pc-1].kind == token.Whitespace { + f.replaceToken(pc-1, "") + } + } + scopeCloser := squizScopeCloser(sc, stackPtr) + if scopeCloser < 0 { + return + } + scopeOpener := sc.opener[stackPtr] + firstContent := scopeOpener + 1 + for ; firstContent < n; firstContent++ { + t := f.toks[firstContent] + if t.kind == token.Whitespace || t.kind == token.InlineHTML && strings.TrimSpace(t.content) == "" { + continue + } + if t.line == f.toks[scopeOpener].line && (f.isEmpty(firstContent) || t.kind == token.CloseTag) { + continue + } + break + } + if firstContent >= n { + return + } + if !squizIgnoredStructure(sc, firstContent) && f.toks[firstContent].line >= f.toks[scopeOpener].line+2 { + f.beginChangeset() + for i := scopeOpener + 1; f.toks[i].line != f.toks[firstContent].line; i++ { + if f.toks[i].line != f.toks[scopeOpener].line { + f.replaceToken(i, "") + } + } + f.endChangeset() + } + if firstContent != scopeCloser { + lastContent := max(f.prevNonWhitespace(scopeCloser-1), 0) + lastNonEmpty := max(f.prevEffective(scopeCloser-1), 0) + checkToken := lastContent + if sc.cond[lastNonEmpty] >= 0 { + checkToken = sc.cond[lastNonEmpty] + } + if !squizIgnoredStructure(sc, checkToken) && f.toks[lastContent].line <= f.toks[scopeCloser].line-2 { + f.beginChangeset() + for i := scopeCloser - 1; i > lastContent; i-- { + if f.toks[i].line == f.toks[scopeCloser].line { + continue + } + if f.toks[i].line == f.toks[lastContent].line { + break + } + f.replaceToken(i, "") + } + f.endChangeset() + } + } + if sc.code[stackPtr] == "match" { + if next := f.nextEffective(scopeCloser+1, n); next >= 0 && (f.is(next, ";") || f.is(next, ",")) { + scopeCloser = next + } + } + trailing := max(f.nextNonWhitespace(scopeCloser+1, n), 0) + if squizIsComment(f, trailing) { + nextCode := max(f.nextEffective(scopeCloser+1, n), 0) + if f.isKeyword(nextCode, "else") || f.isKeyword(nextCode, "elseif") || + f.toks[trailing].line == f.toks[scopeCloser].line { + trailing = nextCode + } + } + code := sc.code[stackPtr] + switch { + case f.isKeyword(trailing, "else") && code == "if", + f.isKeyword(trailing, "while") && code == "do", + f.toks[trailing].kind == token.CloseTag: + return + } + if c := sc.cond[trailing]; c >= 0 && c != trailing && sc.opener[trailing] >= 0 && sc.opener[trailing] != trailing { + switch squizFunctionCode(sc, c) { + case "function": + return + case "closure": + if squizInFunction(sc, stackPtr) || sc.nested[stackPtr] >= 0 { + return + } + } + if f.toks[trailing].line != f.toks[scopeCloser].line+1 { + f.beginChangeset() + for i := scopeCloser + 1; f.toks[i].line != f.toks[trailing].line; i++ { + f.replaceToken(i, "") + } + f.addContent(scopeCloser, f.eol) + f.endChangeset() + } + return + } + switch sc.code[trailing] { + case "else", "elseif", "catch", "finally": + return + } + if f.toks[trailing].line != f.toks[scopeCloser].line+1 { + return + } + trailing = max(f.nextNonWhitespace(scopeCloser+1, n), 0) + if squizIsComment(f, trailing) && f.toks[trailing].line == f.toks[scopeCloser].line { + f.addContent(trailing, f.eol) + } else { + f.addContent(scopeCloser, f.eol) + } +} + +// squizFunctionCode is "function" for PHP_CodeSniffer's T_FUNCTION, "closure" +// for T_CLOSURE, else "": the tokenizer only retags a "function (" with a scope +// opener as T_CLOSURE. +func squizFunctionCode(sc *phpcsScope, i int) string { + f := sc.f + switch { + case !f.isKeyword(i, "function"): + return "" + case f.isClosure(i): + if squizScopeCloser(sc, i) >= 0 { + return "closure" + } + return "function" + case phpcsIsNamedFunction(f, i): + return "function" + } + return "" +} + +// squizScopeCloser is the scope_closer of the scope owner at i, or -1. +func squizScopeCloser(sc *phpcsScope, i int) int { + if sc.cond[i] != i || sc.opener[i] < 0 || sc.closer[i] < 0 { + return -1 + } + return sc.closer[i] +} + +// squizInFunction is File::hasCondition(i, [T_FUNCTION, T_CLOSURE]). +func squizInFunction(sc *phpcsScope, i int) bool { + for _, c := range sc.conditions(i) { + if sc.code[c] == "function" { + return true + } + } + return false +} diff --git a/blink/internal/fixer/rules/squiz_control_structures.go b/blink/internal/fixer/rules/squiz_control_structures.go new file mode 100644 index 0000000000..ac24ae4982 --- /dev/null +++ b/blink/internal/fixer/rules/squiz_control_structures.go @@ -0,0 +1,412 @@ +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" +) + +// phpcsNewline marks a PHP_CodeSniffer spacing count: a number of spaces, or -1 +// for "newline". +const phpcsNewline = -1 + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/ControlStructures/ControlSignatureSniff.php +// +// SquizControlSignature puts one space after a control keyword and after its +// condition, the body on the line after the opening brace and one space +// between a closing brace and else, elseif, catch, finally or do-while. +type SquizControlSignature struct { + RequiredSpacesBeforeColon int +} + +func (SquizControlSignature) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\ControlSignatureSniff` +} + +func (SquizControlSignature) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/ControlStructures/ControlSignatureSniff.php" +} + +func (r SquizControlSignature) WithConfig(config map[string]any) fixer.Fixer { + r.RequiredSpacesBeforeColon = configInt(config, "requiredSpacesBeforeColon", r.RequiredSpacesBeforeColon) + return r +} + +var squizControlSignatureCodes = phpcsSet("try", "catch", "finally", "do", "while", "for", "if", "foreach", + "else", "elseif", "switch", "match") + +func (r SquizControlSignature) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + sc := newPhpcsScope(f) + for i := range f.toks { + if squizControlSignatureCodes[sc.code[i]] { + r.process(sc, i) + } + } + }) +} + +// phpcsWhitespaceFound counts the whitespace token at i the way the sniffs +// report it: 0 when it is not whitespace, -1 when it holds a newline. +func phpcsWhitespaceFound(f *slvFile, i int) int { + if i >= len(f.toks) || f.toks[i].kind != token.Whitespace { + return 0 + } + if strings.Contains(f.toks[i].content, f.eol) { + return phpcsNewline + } + return f.toks[i].length +} + +func (r SquizControlSignature) process(sc *phpcsScope, stackPtr int) { + f := sc.f + if f.nextEffective(stackPtr+1, len(f.toks)) < 0 { + return + } + opener := sc.opener[stackPtr] + isAlternative := opener >= 0 && sc.code[opener] == ":" + parenCloser := sc.pCloser[stackPtr] + + expected := 1 + if parenCloser < 0 && isAlternative { + expected = r.RequiredSpacesBeforeColon + } + found := 1 + if stackPtr+1 < len(f.toks) && (f.toks[stackPtr+1].kind != token.Whitespace || f.toks[stackPtr+1].content != " ") { + found = phpcsWhitespaceFound(f, stackPtr+1) + } + if found != expected { + if found == 0 { + f.addContent(stackPtr, strings.Repeat(" ", expected)) + } else { + f.replaceToken(stackPtr+1, strings.Repeat(" ", expected)) + } + } + + if parenCloser >= 0 && opener >= 0 { + r.afterCloseParenthesis(f, parenCloser, opener, isAlternative) + } + + if opener >= 0 { + squizNewlineAfterOpener(sc, opener) + } else if sc.code[stackPtr] == "while" && parenCloser >= 0 { + if next := f.nextEffective(parenCloser+1, len(f.toks)); next >= 0 && sc.code[next] == ";" { + if phpcsWhitespaceFound(f, parenCloser+1) != 0 { + f.replaceToken(parenCloser+1, "") + } + } + } + + var closer int + switch sc.code[stackPtr] { + case "while": + if sc.closer[stackPtr] >= 0 { + return + } + closer = f.prevEffective(stackPtr - 1) + if closer < 0 || sc.code[closer] != "}" || sc.cond[closer] < 0 || sc.code[sc.cond[closer]] != "do" { + return + } + case "else", "elseif", "catch", "finally": + if isAlternative { + return + } + closer = f.prevEffective(stackPtr - 1) + if closer < 0 || sc.code[closer] != "}" { + return + } + default: + return + } + + found = 1 + switch { + case f.toks[closer+1].kind != token.Whitespace: + found = 0 + case f.toks[closer].line != f.toks[stackPtr].line: + found = phpcsNewline + case f.toks[closer+1].content != " ": + found = f.toks[closer+1].length + } + if found == 1 { + return + } + for i := closer + 1; i < stackPtr; i++ { + if f.isPhpcsComment(i) { + return + } + } + if found == 0 { + f.addContent(closer, " ") + } else { + f.replaceToken(closer+1, " ") + } +} + +func (r SquizControlSignature) afterCloseParenthesis(f *slvFile, closer, opener int, isAlternative bool) { + expected := 1 + if isAlternative { + expected = r.RequiredSpacesBeforeColon + } + var b strings.Builder + for i := closer + 1; i < opener; i++ { + b.WriteString(f.toks[i].content) + } + content := b.String() + blank := strings.TrimSpace(content) == "" + found := -2 + if blank { + found = len(content) + if strings.Contains(content, f.eol) { + found = phpcsNewline + } + } + if found == expected { + return + } + padding := strings.Repeat(" ", expected) + if closer == opener-1 { + f.addContent(closer, padding) + return + } + f.beginChangeset() + if blank { + f.addContent(closer, padding) + if found != 0 { + for i := closer + 1; i < opener; i++ { + f.replaceToken(i, "") + } + } + } else { + f.addContent(closer, padding+f.toks[opener].content) + f.replaceToken(opener, "") + if f.toks[opener].line != f.toks[closer].line { + if next := f.nextNonWhitespace(opener+1, len(f.toks)); next >= 0 && f.toks[next].line != f.toks[opener].line { + for i := opener + 1; i < next; i++ { + f.replaceToken(i, "") + } + } + } + } + f.endChangeset() +} + +func squizNewlineAfterOpener(sc *phpcsScope, opener int) { + f := sc.f + next := opener + 1 + for ; next < len(f.toks); next++ { + t := f.toks[next] + if t.kind == token.Whitespace || t.kind == token.InlineHTML && strings.TrimSpace(t.content) == "" { + continue + } + if t.line == f.toks[opener].line && (f.isEmpty(next) || t.kind == token.CloseTag) { + continue + } + break + } + if next >= len(f.toks) { + next = len(f.toks) - 1 + } + if f.toks[next].line != f.toks[opener].line { + return + } + f.beginChangeset() + for i := opener + 1; i < next; i++ { + if strings.TrimSpace(f.toks[i].content) != "" { + break + } + f.replaceToken(i, "") + } + f.addContent(opener, f.eol) + f.endChangeset() +} + +// phpcsPrevNonWS is File::findPrevious(T_WHITESPACE, start, end, true), stopping +// above end. +func phpcsPrevNonWS(f *slvFile, start, end int) int { + for i := start; i > end; i-- { + if f.toks[i].kind != token.Whitespace { + return i + } + } + return 0 +} + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/ControlStructures/SwitchDeclarationSniff.php +// +// SquizSwitchDeclaration lays out a switch: lowercase CASE and DEFAULT on +// their own lines Indent spaces in, no space before the colon, the breaking +// statement aligned with the CASE and followed by one blank line. +type SquizSwitchDeclaration struct { + Indent int +} + +func (SquizSwitchDeclaration) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\ControlStructures\SwitchDeclarationSniff` +} + +func (SquizSwitchDeclaration) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/ControlStructures/SwitchDeclarationSniff.php" +} + +func (r SquizSwitchDeclaration) WithConfig(config map[string]any) fixer.Fixer { + r.Indent = configInt(config, "indent", r.Indent) + return r +} + +func (r SquizSwitchDeclaration) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + sc := newPhpcsScope(f) + for i := range f.toks { + if sc.code[i] == "switch" { + r.process(sc, i) + } + } + }) +} + +var squizCaseBreakers = phpcsSet("break", "return", "continue", "throw", "exit", "goto") + +// phpcsLineBreakAfter starts a new line at padding after prev, replacing the +// whitespace after it or appending to it. +func phpcsLineBreakAfter(f *slvFile, prev int, padding string) { + if f.toks[prev+1].kind == token.Whitespace { + f.replaceToken(prev+1, f.eol+padding) + } else { + f.addContent(prev, f.eol+padding) + } +} + +// phpcsAlign indents tok, the first on its line, to column-1 spaces. +func phpcsAlign(f *slvFile, tok int, padding string) { + if f.toks[tok].column == 1 || f.toks[tok-1].kind != token.Whitespace { + f.addContentBefore(tok, padding) + } else { + f.replaceToken(tok-1, padding) + } +} + +func (r SquizSwitchDeclaration) process(sc *phpcsScope, stackPtr int) { + f := sc.f + if sc.opener[stackPtr] < 0 || sc.closer[stackPtr] < 0 { + return + } + switchCloser := sc.closer[stackPtr] + caseAlignment := f.toks[stackPtr].column + r.Indent + padding := strings.Repeat(" ", caseAlignment-1) + for nextCase := phpcsNextCase(sc, stackPtr+1, switchCloser); nextCase >= 0; nextCase = phpcsNextCase(sc, nextCase+1, switchCloser) { + isCase := sc.code[nextCase] == "case" + if content := f.toks[nextCase].content; content != strings.ToLower(content) { + f.replaceToken(nextCase, strings.ToLower(content)) + } + if isCase && (f.toks[nextCase+1].kind != token.Whitespace || f.toks[nextCase+1].content != " ") { + if f.toks[nextCase+1].kind != token.Whitespace { + f.addContent(nextCase, " ") + } else { + f.replaceToken(nextCase+1, " ") + } + } + + beforeCase := phpcsPrevNonWS(f, nextCase-1, -1) + if f.toks[beforeCase].line == f.toks[nextCase].line { + phpcsLineBreakAfter(f, beforeCase, padding) + } else if f.toks[nextCase].column != caseAlignment { + phpcsAlign(f, nextCase, padding) + } + + opener := sc.opener[nextCase] + if opener < 0 { + continue + } + if sc.code[opener] == "close_tag" { + f.addContent(phpcsPrevNonWS(f, opener-1, -1), ":") + } + if f.toks[opener-1].kind == token.Whitespace { + f.replaceToken(opener-1, "") + } + + nextBreak := sc.closer[nextCase] + if nextBreak < 0 || !squizCaseBreakers[sc.code[nextBreak]] { + continue + } + if sc.cond[nextBreak] == nextCase { + r.breakLayout(sc, stackPtr, nextCase, opener, nextBreak, caseAlignment, isCase) + } + } +} + +func (r SquizSwitchDeclaration) breakLayout(sc *phpcsScope, stackPtr, nextCase, opener, nextBreak, caseAlignment int, isCase bool) { + f := sc.f + padding := strings.Repeat(" ", caseAlignment-1) + beforeBreak := phpcsPrevNonWS(f, nextBreak-1, -1) + if f.toks[beforeBreak].line == f.toks[nextBreak].line { + phpcsLineBreakAfter(f, beforeBreak, padding) + } else if f.toks[nextBreak].column != caseAlignment { + phpcsAlign(f, nextBreak, padding) + } + + switchCloser := sc.closer[stackPtr] + nextLine := f.toks[switchCloser].line + semicolon := sc.endOfStatement(nextBreak) + nextRelevant := semicolon + 1 + for ; nextRelevant < switchCloser; nextRelevant++ { + if !f.isEmpty(nextRelevant) { + nextLine = f.toks[nextRelevant].line + break + } + if f.toks[nextRelevant].kind != token.Whitespace && f.toks[nextBreak].line != f.toks[nextRelevant].line { + nextLine = f.toks[nextRelevant].line + break + } + } + + if isCase && nextLine != f.toks[semicolon].line+2 && nextRelevant != switchCloser { + f.beginChangeset() + if nextLine == f.toks[semicolon].line { + replacement := f.eol + f.eol + padding + if f.toks[nextRelevant-1].kind == token.Whitespace { + f.replaceToken(nextRelevant-1, replacement) + } else { + f.addContentBefore(nextRelevant, replacement) + } + } else { + for i := semicolon + 1; i < nextRelevant; i++ { + if f.toks[semicolon].line == f.toks[i].line { + if f.toks[i].line != f.toks[i+1].line { + f.addContent(i, f.eol) + } + continue + } + if f.toks[i].line == f.toks[nextRelevant].line { + break + } + f.replaceToken(i, "") + } + } + f.endChangeset() + } + + caseLine := f.toks[nextCase].line + nextLine = f.toks[nextBreak].line + i := opener + 1 + for ; i < nextBreak; i++ { + if !f.isEmpty(i) { + nextLine = f.toks[i].line + break + } + if f.toks[i].kind != token.Whitespace && f.toks[opener].line != f.toks[i].line { + nextLine = f.toks[i].line + break + } + } + if nextLine == caseLine { + pad := f.eol + strings.Repeat(" ", caseAlignment-1+r.Indent) + if f.toks[i-1].kind == token.Whitespace { + f.replaceToken(i-1, pad) + } else { + f.addContentBefore(i, pad) + } + } +} diff --git a/blink/internal/fixer/rules/squiz_function_comment.go b/blink/internal/fixer/rules/squiz_function_comment.go new file mode 100644 index 0000000000..cf8e2857a7 --- /dev/null +++ b/blink/internal/fixer/rules/squiz_function_comment.go @@ -0,0 +1,191 @@ +package rules + +import ( + "regexp" + "slices" + "strings" + + "github.com/ecsphp/ecs-src/blink/internal/tokens" +) + +// PHP_CodeSniffer: https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentSniff.php +// +// SquizFunctionComment is PEARFunctionComment's blank-line fix plus the Squiz +// type spellings of @param and @return ("int" -> "integer") and the alignment +// of @param types and names. +type SquizFunctionComment struct{} + +func (SquizFunctionComment) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\Commenting\FunctionCommentSniff` +} + +func (SquizFunctionComment) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentSniff.php" +} + +func (SquizFunctionComment) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + for i := range f.toks { + if !phpcsIsNamedFunction(f, i) { + continue + } + if commentEnd, tags, ok := pearFunctionCommentPreamble(f, i); ok { + squizProcessReturn(f, tags) + squizProcessParams(f, commentEnd, tags) + } + } + }) +} + +var squizReturnParts = regexp.MustCompile(`(?i)^((?:\|?(?:array\([^\)]*\)|[\\a-z0-9_\[\]]+))*)( .*)?`) + +func squizSuggestTypes(typ string) string { + var names []string + for name := range strings.SplitSeq(typ, "|") { + if s := phpcsSuggestType(name); !slices.Contains(names, s) { + names = append(names, s) + } + } + return strings.Join(names, "|") +} + +func squizProcessReturn(f *slvFile, tags []int) { + ret := -1 + for _, tag := range tags { + if f.toks[tag].content == "@return" { + if ret >= 0 { + return + } + ret = tag + } + } + if ret < 0 || ret+2 >= len(f.toks) { + return + } + content := f.toks[ret+2].content + if content == "" || content == "0" || f.toks[ret+2].doc != slvDocString { + return + } + m := squizReturnParts.FindStringSubmatch(content) + if want := squizSuggestTypes(m[1]); want != m[1] { + f.replaceToken(ret+2, want+m[2]) + } +} + +type squizCommentLine struct { + comment string + token int + indent int +} + +type squizParam struct { + tag int + typ, varName string + comment string + lines []squizCommentLine + typeSpace, varSpace int +} + +func squizProcessParams(f *slvFile, commentCloser int, tags []int) { + var params []squizParam + maxType, maxVar := 0, 0 + for pos, tag := range tags { + if f.toks[tag].content != "@param" { + continue + } + p := squizParam{tag: tag} + if tag+2 < len(f.toks) && f.toks[tag+2].doc == slvDocString { + content := f.toks[tag+2].content + m := pearParseParam(content) + typeLen := len(m.typ) + p.typ = strings.Trim(m.typ, " \t\n\r\x00\x0B") + p.typeSpace = typeLen - len(p.typ) + maxType = max(maxType, len(p.typ)) + if content[0] != '$' && m.hasVar { + p.varName = m.varName + maxVar = max(maxVar, len(p.varName)) + if m.hasComment { + p.varSpace = len(m.space) + p.comment = m.comment + p.lines = append(p.lines, squizCommentLine{comment: m.comment, token: tag + 2, indent: p.varSpace}) + end := commentCloser + if pos+1 < len(tags) { + end = tags[pos+1] + } + for i := tag + 3; i < end; i++ { + if f.toks[i].doc != slvDocString { + continue + } + indent := 0 + if f.toks[i-1].doc == slvDocWhitespace { + indent = f.toks[i-1].length + } + p.comment += " " + f.toks[i].content + p.lines = append(p.lines, squizCommentLine{comment: f.toks[i].content, token: i, indent: indent}) + } + } else { + p.lines = append(p.lines, squizCommentLine{token: -1}) + } + } + } + params = append(params, p) + } + + for _, p := range params { + if p.typ == "" { + continue + } + var suggested []string + for name := range strings.SplitSeq(p.typ, "|") { + if name == "" { + continue + } + suggested = append(suggested, phpcsSuggestType(strings.TrimPrefix(name, "?"))) + } + if want := strings.Join(suggested, "|"); want != p.typ { + first := "" + if len(p.lines) > 0 { + first = p.lines[0].comment + } + diff := len(p.typ) - len(want) + f.beginChangeset() + f.replaceToken(p.tag+2, want+strings.Repeat(" ", p.typeSpace)+p.varName+strings.Repeat(" ", p.varSpace)+first) + squizReindentLines(f, p.lines, diff, false) + f.endChangeset() + } + if p.varName == "" { + continue + } + if spaces := maxType - len(p.typ) + 1; p.typeSpace != spaces { + f.beginChangeset() + f.replaceToken(p.tag+2, p.typ+strings.Repeat(" ", spaces)+p.varName+strings.Repeat(" ", p.varSpace)+p.lines[0].comment) + squizReindentLines(f, p.lines, p.typeSpace-spaces, true) + f.endChangeset() + } + if p.comment == "" { + continue + } + if spaces := maxVar - len(p.varName) + 1; p.varSpace != spaces { + f.beginChangeset() + f.replaceToken(p.tag+2, p.typ+strings.Repeat(" ", p.typeSpace)+p.varName+strings.Repeat(" ", spaces)+p.lines[0].comment) + squizReindentLines(f, p.lines, p.varSpace-spaces, true) + f.endChangeset() + } + } +} + +// squizReindentLines shifts the indent of a param comment's continuation +// lines by diff; skipNonPositive mirrors the checks that leave an indent +// that would drop to zero or below alone. +func squizReindentLines(f *slvFile, lines []squizCommentLine, diff int, skipNonPositive bool) { + for n, l := range lines { + if n == 0 || l.indent == 0 { + continue + } + indent := l.indent - diff + if indent <= 0 && skipNonPositive { + continue + } + f.replaceToken(l.token-1, strings.Repeat(" ", max(indent, 0))) + } +} diff --git a/blink/internal/fixer/rules/squiz_scope_closing_brace.go b/blink/internal/fixer/rules/squiz_scope_closing_brace.go new file mode 100644 index 0000000000..9b60f426f6 --- /dev/null +++ b/blink/internal/fixer/rules/squiz_scope_closing_brace.go @@ -0,0 +1,103 @@ +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/WhiteSpace/ScopeClosingBraceSniff.php +// +// SquizScopeClosingBrace puts a scope's closing brace on its own line, in the +// column of the first content on the line that opens the scope. +type SquizScopeClosingBrace struct{} + +func (SquizScopeClosingBrace) Name() string { + return `PHP_CodeSniffer\Standards\Squiz\Sniffs\WhiteSpace\ScopeClosingBraceSniff` +} + +func (SquizScopeClosingBrace) SourceURL() string { + return "https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/4.x/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php" +} + +func (r SquizScopeClosingBrace) Fix(s *tokens.Stream) bool { + return slvRun(s, func(f *slvFile) { + sc := newPhpcsScope(f) + for i := range f.toks { + if phpcsScopeOpenerCodes[sc.code[i]] { + r.process(sc, i) + } + } + }) +} + +func (SquizScopeClosingBrace) process(sc *phpcsScope, stackPtr int) { + f := sc.f + scopeEnd := sc.closer[stackPtr] + if scopeEnd < 0 { + return + } + scopeStart := sc.opener[stackPtr] + lineStart := squizFirstOnLine(sc, stackPtr) + for squizConstantString(f, lineStart) && squizConstantString(f, lineStart-1) { + lineStart = squizFirstOnLine(sc, lineStart-1) + } + startColumn := f.toks[lineStart].column + + lastContent := 0 + for i := scopeEnd - 1; i >= scopeStart && i >= 0; i-- { + if c := sc.code[i]; c != "inline_html" && c != "whitespace" && c != "open_tag" { + lastContent = i + break + } + } + lineStart = scopeEnd + for lineStart > 0 && f.toks[lineStart].column > 1 { + lineStart-- + } + if f.toks[lastContent].line == f.toks[scopeEnd].line || + sc.code[lineStart] == "inline_html" && strings.TrimSpace(f.toks[lineStart].content) != "" { + at := lineStart + 1 + if f.toks[lastContent].line == f.toks[scopeEnd].line { + at = scopeEnd + } + f.replaceToken(at, f.eol+f.tokenContent(at)) + return + } + + lineStart = squizFirstOnLine(sc, scopeEnd) + braceIndent := f.toks[lineStart].column + if c := sc.code[stackPtr]; c == "default" || c == "case" || braceIndent == startColumn { + return + } + if diff := startColumn - braceIndent; diff > 0 { + f.replaceToken(lineStart, strings.Repeat(" ", diff)+f.tokenContent(lineStart)) + } else if lineStart > 0 { + v := f.tokenContent(lineStart - 1) + f.replaceToken(lineStart-1, v[:max(0, len(v)+diff)]) + } +} + +// squizFirstOnLine is File::findFirstOnLine([T_WHITESPACE, T_INLINE_HTML], +// start, true): the first token on start's line that is neither, or 0 for +// none (PHP reads $tokens[false] as $tokens[0]). +func squizFirstOnLine(sc *phpcsScope, start int) int { + found := 0 + line := sc.f.toks[start].line + for i := start; i >= 0 && sc.f.toks[i].line == line; i-- { + if c := sc.code[i]; c != "whitespace" && c != "inline_html" { + found = i + } + } + return found +} + +// squizConstantString reports a T_CONSTANT_ENCAPSED_STRING token. +func squizConstantString(f *slvFile, i int) bool { + if i < 0 || i >= len(f.toks) { + return false + } + t := f.toks[i] + return t.kind == token.String && !t.heredoc && !t.interp +} diff --git a/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.1.inc b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.1.inc new file mode 100644 index 0000000000..eafa67896a --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Generic/WhiteSpace/ScopeIndentUnitTest.1.inc @@ -0,0 +1,1687 @@ +phpcs:set Generic.WhiteSpace.ScopeIndent tabIndent false + +hello(); + } + + function hello() + { + echo 'hello'; +}//end hello() + + function hello2() + { + if (TRUE) { + echo 'hello'; // no error here as its more than 4 spaces. + } else { + echo 'bye'; + } + + while (TRUE) { + echo 'hello'; + } + + do { + echo 'hello'; + } while (TRUE); + } + + function hello3() + { + switch ($hello) { + case 'hello': + break; + } + } + +} + +?> +
+
+
+validate()) {
+ $safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here
+ }
+
+ public function open()
+ {
+ // Some inline stuff that shouldn't error
+ if (TRUE) echo 'hello';
+ foreach ($tokens as $token) echo $token;
+ }
+
+ /**
+ * This is a comment 1.
+ * This is a comment 2.
+ * This is a comment 3.
+ * This is a comment 4.
+ */
+ public function close()
+ {
+ // All ok.
+ if (TRUE) {
+ if (TRUE) {
+ } else if (FALSE) {
+ foreach ($tokens as $token) {
+ switch ($token) {
+ case '1':
+ case '2':
+ if (true) {
+ if (false) {
+ if (false) {
+ if (false) {
+ echo 'hello';
+ }
+ }
+ }
+ }
+ break;
+ case '5':
+ break;
+ }
+ do {
+ while (true) {
+ foreach ($tokens as $token) {
+ for ($i = 0; $i < $token; $i++) {
+ echo 'hello';
+ }
+ }
+ }
+ } while (true);
+ }
+ }
+ }
+ }
+
+ /*
+ This is another c style comment 1.
+ This is another c style comment 2.
+ This is another c style comment 3.
+ This is another c style comment 4.
+ This is another c style comment 5.
+ */
+
+ /* This is a T_COMMENT
+ *
+ *
+ *
+ */
+
+ /** This is a T_DOC_COMMENT
+ */
+
+ /*
+ This T_COMMENT has a newline in it.
+
+ */
+
+ public function read()
+ {
+ echo 'hello';
+
+ // no errors below.
+ $array = array(
+ 'this',
+ 'that' => array(
+ 'hello',
+ 'hello again' => array(
+ 'hello',
+ ),
+ ),
+ );
+ }
+}
+
+abstract class Test3
+{
+ public function parse()
+ {
+
+ foreach ($t as $ndx => $token) {
+ if (is_array($token)) {
+ echo 'here';
+ } else {
+ $ts[] = array("token" => $token, "value" => '');
+
+ $last = count($ts) - 1;
+
+ switch ($token) {
+ case '(':
+
+ if ($last >= 3 &&
+ $ts[0]['token'] != T_CLASS &&
+ $ts[$last - 2]['token'] == T_OBJECT_OPERATOR &&
+ $ts[$last - 3]['token'] == T_VARIABLE ) {
+
+
+ if (true) {
+ echo 'hello';
+ }
+ }
+ array_push($braces, $token);
+ break;
+ }
+ }
+ }
+ }
+}
+
+function test()
+{
+ $o = <<
+
+
+validate()) {
+ $safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here
+ }
+
+ public function open()
+ {
+ // Some inline stuff that shouldn't error
+ if (TRUE) echo 'hello';
+ foreach ($tokens as $token) echo $token;
+ }
+
+ /**
+ * This is a comment 1.
+ * This is a comment 2.
+ * This is a comment 3.
+ * This is a comment 4.
+ */
+ public function close()
+ {
+ // All ok.
+ if (TRUE) {
+ if (TRUE) {
+ } else if (FALSE) {
+ foreach ($tokens as $token) {
+ switch ($token) {
+ case '1':
+ case '2':
+ if (true) {
+ if (false) {
+ if (false) {
+ if (false) {
+ echo 'hello';
+ }
+ }
+ }
+ }
+ break;
+ case '5':
+ break;
+ }
+ do {
+ while (true) {
+ foreach ($tokens as $token) {
+ for ($i = 0; $i < $token; $i++) {
+ echo 'hello';
+ }
+ }
+ }
+ } while (true);
+ }
+ }
+ }
+ }
+
+ /*
+ This is another c style comment 1.
+ This is another c style comment 2.
+ This is another c style comment 3.
+ This is another c style comment 4.
+ This is another c style comment 5.
+ */
+
+ /* This is a T_COMMENT
+ *
+ *
+ *
+ */
+
+ /** This is a T_DOC_COMMENT
+ */
+
+ /*
+ This T_COMMENT has a newline in it.
+
+ */
+
+ public function read()
+ {
+ echo 'hello';
+
+ // no errors below.
+ $array = array(
+ 'this',
+ 'that' => array(
+ 'hello',
+ 'hello again' => array(
+ 'hello',
+ ),
+ ),
+ );
+ }
+}
+
+abstract class Test3
+{
+ public function parse()
+ {
+
+ foreach ($t as $ndx => $token) {
+ if (is_array($token)) {
+ echo 'here';
+ } else {
+ $ts[] = array("token" => $token, "value" => '');
+
+ $last = count($ts) - 1;
+
+ switch ($token) {
+ case '(':
+
+ if ($last >= 3 &&
+ $ts[0]['token'] != T_CLASS &&
+ $ts[$last - 2]['token'] == T_OBJECT_OPERATOR &&
+ $ts[$last - 3]['token'] == T_VARIABLE ) {
+
+
+ if (true) {
+ echo 'hello';
+ }
+ }
+ array_push($braces, $token);
+ break;
+ }
+ }
+ }
+ }
+}
+
+function test()
+{
+ $o = <<
+
+
+validate()) {
+ $safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here
+ }
+
+ public function open()
+ {
+ // Some inline stuff that shouldn't error
+ if (TRUE) echo 'hello';
+ foreach ($tokens as $token) echo $token;
+ }
+
+ /**
+ * This is a comment 1.
+ * This is a comment 2.
+ * This is a comment 3.
+ * This is a comment 4.
+ */
+ public function close()
+ {
+ // All ok.
+ if (TRUE) {
+ if (TRUE) {
+ } else if (FALSE) {
+ foreach ($tokens as $token) {
+ switch ($token) {
+ case '1':
+ case '2':
+ if (true) {
+ if (false) {
+ if (false) {
+ if (false) {
+ echo 'hello';
+ }
+ }
+ }
+ }
+ break;
+ case '5':
+ break;
+ }
+ do {
+ while (true) {
+ foreach ($tokens as $token) {
+ for ($i = 0; $i < $token; $i++) {
+ echo 'hello';
+ }
+ }
+ }
+ } while (true);
+ }
+ }
+ }
+ }
+
+ /*
+ This is another c style comment 1.
+ This is another c style comment 2.
+ This is another c style comment 3.
+ This is another c style comment 4.
+ This is another c style comment 5.
+ */
+
+ /* This is a T_COMMENT
+ *
+ *
+ *
+ */
+
+ /** This is a T_DOC_COMMENT
+ */
+
+ /*
+ This T_COMMENT has a newline in it.
+
+ */
+
+ public function read()
+ {
+ echo 'hello';
+
+ // no errors below.
+ $array = array(
+ 'this',
+ 'that' => array(
+ 'hello',
+ 'hello again' => array(
+ 'hello',
+ ),
+ ),
+ );
+ }
+}
+
+abstract class Test3
+{
+ public function parse()
+ {
+
+ foreach ($t as $ndx => $token) {
+ if (is_array($token)) {
+ echo 'here';
+ } else {
+ $ts[] = array("token" => $token, "value" => '');
+
+ $last = count($ts) - 1;
+
+ switch ($token) {
+ case '(':
+
+ if ($last >= 3 &&
+ $ts[0]['token'] != T_CLASS &&
+ $ts[$last - 2]['token'] == T_OBJECT_OPERATOR &&
+ $ts[$last - 3]['token'] == T_VARIABLE ) {
+
+
+ if (true) {
+ echo 'hello';
+ }
+ }
+ array_push($braces, $token);
+ break;
+ }
+ }
+ }
+ }
+}
+
+function test()
+{
+ $o = <<
+
+
+validate()) {
+ $safe = $form->getSubmitValues();
+}
+?>
+
+open(); // error here
+ }
+
+ public function open()
+ {
+ // Some inline stuff that shouldn't error
+ if (TRUE) echo 'hello';
+ foreach ($tokens as $token) echo $token;
+ }
+
+ /**
+ * This is a comment 1.
+ * This is a comment 2.
+ * This is a comment 3.
+ * This is a comment 4.
+ */
+ public function close()
+ {
+ // All ok.
+ if (TRUE) {
+ if (TRUE) {
+ } else if (FALSE) {
+ foreach ($tokens as $token) {
+ switch ($token) {
+ case '1':
+ case '2':
+ if (true) {
+ if (false) {
+ if (false) {
+ if (false) {
+ echo 'hello';
+ }
+ }
+ }
+ }
+ break;
+ case '5':
+ break;
+ }
+ do {
+ while (true) {
+ foreach ($tokens as $token) {
+ for ($i = 0; $i < $token; $i++) {
+ echo 'hello';
+ }
+ }
+ }
+ } while (true);
+ }
+ }
+ }
+ }
+
+ /*
+ This is another c style comment 1.
+ This is another c style comment 2.
+ This is another c style comment 3.
+ This is another c style comment 4.
+ This is another c style comment 5.
+ */
+
+ /* This is a T_COMMENT
+ *
+ *
+ *
+ */
+
+ /** This is a T_DOC_COMMENT
+ */
+
+ /*
+ This T_COMMENT has a newline in it.
+
+ */
+
+ public function read()
+ {
+ echo 'hello';
+
+ // no errors below.
+ $array = array(
+ 'this',
+ 'that' => array(
+ 'hello',
+ 'hello again' => array(
+ 'hello',
+ ),
+ ),
+ );
+ }
+}
+
+abstract class Test3
+{
+ public function parse()
+ {
+
+ foreach ($t as $ndx => $token) {
+ if (is_array($token)) {
+ echo 'here';
+ } else {
+ $ts[] = array("token" => $token, "value" => '');
+
+ $last = count($ts) - 1;
+
+ switch ($token) {
+ case '(':
+
+ if ($last >= 3 &&
+ $ts[0]['token'] != T_CLASS &&
+ $ts[$last - 2]['token'] == T_OBJECT_OPERATOR &&
+ $ts[$last - 3]['token'] == T_VARIABLE ) {
+
+
+ if (true) {
+ echo 'hello';
+ }
+ }
+ array_push($braces, $token);
+ break;
+ }
+ }
+ }
+ }
+}
+
+function test()
+{
+ $o = <<= $val ?>
+ + + +| + + |
= $val ?>
+ + + + + + + + hello + + + + hello + + 1, +}; + +$r = match($x){1 => 1}; + +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 2 +if ($a == 5): + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +// Reset property. +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 1 diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.1.inc.fixed b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.1.inc.fixed new file mode 100644 index 0000000000..bc37e70bca --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.1.inc.fixed @@ -0,0 +1,324 @@ + 0); + +do { + echo $i; +} while ($i > 0); + +do { + echo $i; +} while ($i > 0); + +do { +echo $i; } while ($i > 0); + +do { + echo $i; +} while ($i > 0); + +while ($i < 1) { + echo $i; +} + +while ($i < 1) { + echo $i; +} + +while ($i < 1) { +echo $i; } + +for ($i = 1; $i < 1; $i++) { + echo $i; +} + +for ($i = 1; $i < 1; $i++) { + echo $i; +} + +for ($i = 1; $i < 1; $i++) { +echo $i; } + +if ($i == 0) { + $i = 1; +} + +if ($i == 0) { + $i = 1; +} + +if ($i == 0) { +$i = 1; } + +if ($i == 0) { + $i = 1; +} else { + $i = 0; +} + +if ($i == 0) { + $i = 1; +} else { + $i = 0; +} + +if ($i == 0) { +$i = 1; } else { +$i = 0; } + +if ($i == 0) { + $i = 1; +} else if ($i == 2) { + $i = 0; +} + +if ($i == 0) { + $i = 1; +} else if ($i == 2) { + $i = 0; +} + +if ($i == 0) { +$i = 1; } else if ($i == 2) { +$i = 0; } + +if ($i == 0) { // comments are allowed + $i = 1; +} + +if ($i == 0) {// comments are allowed + $i = 1; +} + +if ($i == 0) { /* comments are allowed*/ + $i = 1; +} + +if ($i == 0) { // this is ok + $i = 1; +} + +if ($i == 0) { /* this is ok */ +} + +try { + $code = 'this'; +} catch (Exception $e) { + // Caught! +} + +try { +$code = 'this'; } catch (Exception $e) { + // Caught! +} + +do { +echo $i; +} while ($i > 0); + +if ($i === 0) { + + $i = 1 +} + +if ($a) { + +} elseif ($b) { +} + +foreach ($items as $item) { + echo $item; +} + +foreach ($items as $item) { + echo $item; +} + +if ($a && $b) { // && $c) +} + +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +try { + // try body +} catch (FirstExceptionType $e) { + // catch body +} catch (OtherExceptionType $e) { + // catch body +} + +switch ($foo) { + + case 'bar': + break; + +} + +if ($foo) : +endif; + +?> + +getRow()) : ?> += $val ?>
+ + + +| + + |
= $val ?>
+ + + + + + + + hello + + + + hello + + 1, +}; + +$r = match ($x) { +1 => 1}; + +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 2 +if ($a == 5) : + echo "a equals 5"; + echo "..."; +elseif ($a == 6) : + echo "a equals 6"; + echo "!!!"; +else : + echo "a is neither 5 nor 6"; +endif; + +// Reset property. +// phpcs:set Squiz.ControlStructures.ControlSignature requiredSpacesBeforeColon 1 diff --git a/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.2.inc b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.2.inc new file mode 100644 index 0000000000..ef99b1a223 --- /dev/null +++ b/blink/internal/fixer/rules/testdata/phpcs/Squiz/ControlStructures/ControlSignatureUnitTest.2.inc @@ -0,0 +1,5 @@ + +