Skip to content

Commit 51d24ef

Browse files
committed
Handle parse errors more gracefully in the language server
1 parent 5c02d72 commit 51d24ef

File tree

2 files changed

+38
-14
lines changed

2 files changed

+38
-14
lines changed

lib/syntax_tree/language_server.rb

+20-14
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,10 @@ def run
5656
store.delete(uri)
5757
in { method: "textDocument/formatting", id:, params: { textDocument: { uri: } } }
5858
contents = store[uri]
59-
write(id: id, result: contents ? [format(store[uri], uri.split(".").last)] : nil)
59+
write(id: id, result: contents ? format(contents, uri.split(".").last) : nil)
6060
in { method: "textDocument/inlayHint", id:, params: { textDocument: { uri: } } }
6161
contents = store[uri]
62-
write(id: id, result: contents ? inlay_hints(store[uri]) : nil)
62+
write(id: id, result: contents ? inlay_hints(contents) : nil)
6363
in { method: "syntaxTree/visualizing", id:, params: { textDocument: { uri: } } }
6464
write(id: id, result: PP.pp(SyntaxTree.parse(store[uri]), +""))
6565
in { method: %r{\$/.+} }
@@ -89,19 +89,25 @@ def capabilities
8989
def format(source, extension)
9090
text = SyntaxTree::HANDLERS[".#{extension}"].format(source, print_width)
9191

92-
{
93-
range: {
94-
start: {
95-
line: 0,
96-
character: 0
92+
[
93+
{
94+
range: {
95+
start: {
96+
line: 0,
97+
character: 0
98+
},
99+
end: {
100+
line: source.lines.size + 1,
101+
character: 0
102+
}
97103
},
98-
end: {
99-
line: source.lines.size + 1,
100-
character: 0
101-
}
102-
},
103-
newText: text
104-
}
104+
newText: text
105+
}
106+
]
107+
rescue Parser::ParseError
108+
# If there is a parse error, then we're not going to return any formatting
109+
# changes for this source.
110+
nil
105111
end
106112

107113
def inlay_hints(source)

test/language_server_test.rb

+18
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,24 @@ def test_formatting
120120
end
121121
end
122122

123+
def test_formatting_failure
124+
messages = [
125+
Initialize.new(1),
126+
TextDocumentDidOpen.new("file:///path/to/file.rb", "<>"),
127+
TextDocumentFormatting.new(2, "file:///path/to/file.rb"),
128+
Shutdown.new(3)
129+
]
130+
131+
case run_server(messages)
132+
in [
133+
{ id: 1, result: { capabilities: Hash } },
134+
{ id: 2, result: },
135+
{ id: 3, result: {} }
136+
]
137+
assert_nil(result)
138+
end
139+
end
140+
123141
def test_formatting_print_width
124142
contents = "#{"a" * 40} + #{"b" * 40}\n"
125143
messages = [

0 commit comments

Comments
 (0)