-
Notifications
You must be signed in to change notification settings - Fork 649
Port formatter, enable in LSP #1052
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
07f6366
formatSpan wip
weswigham 9d4581c
Add range helpers, do start/fullstart audit on ported code
weswigham f5523dd
progress on smart indent, procesnode
weswigham 8c5bb6e
Complete up to the rule system that does the bulk of the formatting l…
weswigham ff01a40
And everything but the formatting rules themselves
weswigham 8e15688
Formatter rules
weswigham 055cdcc
Add wrappers of FormatSpan used by LS
weswigham 8bc6923
Shuffling
weswigham 86b9d6d
Fixes, simple smoke test/bench
weswigham a36c183
Definitely some perf work to do - edit application in particular is a…
weswigham 7c51f0f
Build formatting out up to the LS and server
weswigham fc85b0d
Merge branch 'main' into fmtr
weswigham bddaf04
Add capabilities to init
weswigham 8d93e02
Fix incorrect config mapping
weswigham 8a10f38
Fix lints
weswigham bc8d50b
Remove parens
weswigham e1ef529
Lowercase
weswigham f4d13a8
Rename
weswigham ebe11b2
Use helper for extracting from context
weswigham f9c777d
Add bulk edit application helper
weswigham 03015d6
Reduce GC pressure caused by scanner temporary strings
weswigham 24bbe7d
One visitor per execute
weswigham 2d519b3
Remove closure in getRules
weswigham File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package core | ||
|
||
type TextChange struct { | ||
TextRange | ||
NewText string | ||
} | ||
|
||
func (t TextChange) ApplyTo(text string) string { | ||
return text[:t.Pos()] + t.NewText + text[t.End():] | ||
jakebailey marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
# How does TypeScript formatting work? | ||
|
||
To format code you need to have a formatting context and a `SourceFile`. The formatting context contains | ||
all user settings like tab size, newline character, etc. | ||
|
||
The end result of formatting is represented by TextChange objects which hold the new string content, and | ||
the text to replace it with. | ||
|
||
## Internals | ||
|
||
Most of the exposed APIs internally are `Format*` and they all set up and configure `FormatSpan` which could be considered the root call for formatting. Span in this case refers to the range of | ||
the sourcefile which should be formatted. | ||
|
||
The formatSpan then uses a scanner (either with or without JSX support) which starts at the highest | ||
node the covers the span of text and recurses down through the node's children. | ||
|
||
As it recurses, `processNode` is called on the children setting the indentation is decided and passed | ||
through into each of that node's children. | ||
|
||
The meat of formatting decisions is made via `processPair`, the pair here being the current node and the previous node. `processPair` which mutates the formatting context to represent the current place in the scanner and requests a set of rules which can be applied to the items via `createRulesMap`. | ||
|
||
There are a lot of rules, which you can find in [rules.ts](./rules.ts) each one has a left and right reference to nodes or token ranges and note of what action should be applied by the formatter. | ||
|
||
### Where is this used? | ||
|
||
The formatter is used mainly from any language service operation that inserts or modifies code. The formatter is not exported publicly, and so all usage can only come through the language server. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,166 @@ | ||
package format | ||
|
||
import ( | ||
"context" | ||
"unicode/utf8" | ||
|
||
"github.com/microsoft/typescript-go/internal/ast" | ||
"github.com/microsoft/typescript-go/internal/core" | ||
"github.com/microsoft/typescript-go/internal/scanner" | ||
"github.com/microsoft/typescript-go/internal/stringutil" | ||
) | ||
|
||
type FormatRequestKind int | ||
|
||
const ( | ||
FormatRequestKindFormatDocument FormatRequestKind = iota | ||
FormatRequestKindFormatSelection | ||
FormatRequestKindFormatOnEnter | ||
FormatRequestKindFormatOnSemicolon | ||
FormatRequestKindFormatOnOpeningCurlyBrace | ||
FormatRequestKindFormatOnClosingCurlyBrace | ||
) | ||
|
||
type formatContextKey int | ||
|
||
const ( | ||
formatOptionsKey formatContextKey = iota | ||
formatNewlineKey | ||
) | ||
|
||
func WithFormatCodeSettings(ctx context.Context, options *FormatCodeSettings, newLine string) context.Context { | ||
ctx = context.WithValue(ctx, formatOptionsKey, options) | ||
ctx = context.WithValue(ctx, formatNewlineKey, newLine) | ||
// In strada, the rules map was both globally cached *and* cached into the context, for some reason. We skip that here and just use the global one. | ||
return ctx | ||
} | ||
|
||
func GetFormatCodeSettingsFromContext(ctx context.Context) *FormatCodeSettings { | ||
opt := ctx.Value(formatOptionsKey).(*FormatCodeSettings) | ||
return opt | ||
} | ||
|
||
func GetNewLineOrDefaultFromContext(ctx context.Context) string { // TODO: Move into broader LS - more than just the formatter uses the newline editor setting/host new line | ||
opt := GetFormatCodeSettingsFromContext(ctx) | ||
if opt != nil && len(opt.NewLineCharacter) > 0 { | ||
return opt.NewLineCharacter | ||
} | ||
host := ctx.Value(formatNewlineKey).(string) | ||
if len(host) > 0 { | ||
return host | ||
} | ||
return "\n" | ||
} | ||
|
||
func FormatSpan(ctx context.Context, span core.TextRange, file *ast.SourceFile, kind FormatRequestKind) []core.TextChange { | ||
// find the smallest node that fully wraps the range and compute the initial indentation for the node | ||
enclosingNode := findEnclosingNode(span, file) | ||
opts := GetFormatCodeSettingsFromContext(ctx) | ||
|
||
return newFormattingScanner( | ||
file.Text(), | ||
file.LanguageVariant, | ||
getScanStartPosition(enclosingNode, span, file), | ||
span.End(), | ||
newFormatSpanWorker( | ||
ctx, | ||
span, | ||
enclosingNode, | ||
GetIndentationForNode(enclosingNode, &span, file, opts), | ||
getOwnOrInheritedDelta(enclosingNode, opts, file), | ||
kind, | ||
prepareRangeContainsErrorFunction(file.Diagnostics(), span), | ||
file, | ||
), | ||
) | ||
} | ||
|
||
func formatNodeLines(ctx context.Context, sourceFile *ast.SourceFile, node *ast.Node, requestKind FormatRequestKind) []core.TextChange { | ||
if node == nil { | ||
return nil | ||
} | ||
tokenStart := scanner.GetTokenPosOfNode(node, sourceFile, false) | ||
lineStart := getLineStartPositionForPosition(tokenStart, sourceFile) | ||
span := core.NewTextRange(lineStart, node.End()) | ||
return FormatSpan(ctx, span, sourceFile, requestKind) | ||
} | ||
|
||
func FormatDocument(ctx context.Context, sourceFile *ast.SourceFile) []core.TextChange { | ||
return FormatSpan(ctx, core.NewTextRange(0, sourceFile.End()), sourceFile, FormatRequestKindFormatDocument) | ||
} | ||
|
||
func FormatSelection(ctx context.Context, sourceFile *ast.SourceFile, start int, end int) []core.TextChange { | ||
return FormatSpan(ctx, core.NewTextRange(getLineStartPositionForPosition(start, sourceFile), end), sourceFile, FormatRequestKindFormatSelection) | ||
} | ||
|
||
func FormatOnOpeningCurly(ctx context.Context, sourceFile *ast.SourceFile, position int) []core.TextChange { | ||
openingCurly := findImmediatelyPrecedingTokenOfKind(position, ast.KindOpenBraceToken, sourceFile) | ||
if openingCurly == nil { | ||
return nil | ||
} | ||
curlyBraceRange := openingCurly.Parent | ||
outermostNode := findOutermostNodeWithinListLevel(curlyBraceRange) | ||
/** | ||
* We limit the span to end at the opening curly to handle the case where | ||
* the brace matched to that just typed will be incorrect after further edits. | ||
* For example, we could type the opening curly for the following method | ||
* body without brace-matching activated: | ||
* ``` | ||
* class C { | ||
* foo() | ||
* } | ||
* ``` | ||
* and we wouldn't want to move the closing brace. | ||
*/ | ||
textRange := core.NewTextRange(getLineStartPositionForPosition(scanner.GetTokenPosOfNode(outermostNode, sourceFile, false), sourceFile), position) | ||
return FormatSpan(ctx, textRange, sourceFile, FormatRequestKindFormatOnOpeningCurlyBrace) | ||
} | ||
|
||
func FormatOnClosingCurly(ctx context.Context, sourceFile *ast.SourceFile, position int) []core.TextChange { | ||
precedingToken := findImmediatelyPrecedingTokenOfKind(position, ast.KindCloseBraceToken, sourceFile) | ||
return formatNodeLines(ctx, sourceFile, findOutermostNodeWithinListLevel(precedingToken), FormatRequestKindFormatOnClosingCurlyBrace) | ||
} | ||
|
||
func FormatOnSemicolon(ctx context.Context, sourceFile *ast.SourceFile, position int) []core.TextChange { | ||
semicolon := findImmediatelyPrecedingTokenOfKind(position, ast.KindSemicolonToken, sourceFile) | ||
return formatNodeLines(ctx, sourceFile, findOutermostNodeWithinListLevel(semicolon), FormatRequestKindFormatOnSemicolon) | ||
} | ||
|
||
func FormatOnEnter(ctx context.Context, sourceFile *ast.SourceFile, position int) []core.TextChange { | ||
line, _ := scanner.GetLineAndCharacterOfPosition(sourceFile, position) | ||
if line == 0 { | ||
return nil | ||
} | ||
// get start position for the previous line | ||
startPos := int(scanner.GetLineStarts(sourceFile)[line-1]) | ||
// After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters. | ||
// If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as | ||
// trailing whitespaces. So the end of the formatting span should be the later one between: | ||
// 1. the end of the previous line | ||
// 2. the last non-whitespace character in the current line | ||
endOfFormatSpan := scanner.GetEndLinePosition(sourceFile, line) | ||
for endOfFormatSpan > startPos { | ||
jakebailey marked this conversation as resolved.
Show resolved
Hide resolved
|
||
ch, s := utf8.DecodeRuneInString(sourceFile.Text()[endOfFormatSpan:]) | ||
if s == 0 || stringutil.IsWhiteSpaceSingleLine(ch) { // on multibyte character keep backing up | ||
endOfFormatSpan-- | ||
continue | ||
} | ||
break | ||
} | ||
|
||
// if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to | ||
// touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the | ||
// previous character before the end of format span is line break character as well. | ||
ch, _ := utf8.DecodeRuneInString(sourceFile.Text()[endOfFormatSpan:]) | ||
if stringutil.IsLineBreak(ch) { | ||
endOfFormatSpan-- | ||
} | ||
|
||
span := core.NewTextRange( | ||
startPos, | ||
// end value is exclusive so add 1 to the result | ||
endOfFormatSpan+1, | ||
) | ||
|
||
return FormatSpan(ctx, span, sourceFile, FormatRequestKindFormatOnEnter) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.