Coverage for src/debputy/lsp/lsp_dispatch.py: 45%

104 statements  

« prev     ^ index     » next       coverage.py v7.16.1, created at 2026-10-28 20:14 +0000

1import inspect 

2import os.path 

3from typing import ( 

4 Union, 

5 Optional, 

6 TypeVar, 

7 List, 

8 TYPE_CHECKING, 

9 Literal, 

10) 

11from collections.abc import Sequence, Callable 

12 

13from debputy.linting.lint_util import AbortTaskError 

14from debputy.lsp.lsp_features import ( 

15 LSP_DIAGNOSTIC_HANDLERS, 

16 COMPLETER_HANDLERS, 

17 HOVER_HANDLERS, 

18 SEMANTIC_TOKENS_FULL_HANDLERS, 

19 CODE_ACTION_HANDLERS, 

20 SEMANTIC_TOKENS_LEGEND, 

21 WILL_SAVE_WAIT_UNTIL_HANDLERS, 

22 LSP_FORMAT_FILE_HANDLERS, 

23 C, 

24 TEXT_DOC_INLAY_HANDLERS, 

25 HandlerDispatchTable, 

26 DOCUMENT_LINK_HANDLERS, 

27 FOLDING_RANGE_HANDLERS, 

28) 

29from debputy.util import _info, _trace_log 

30from debputy.version import version 

31 

32if TYPE_CHECKING: 

33 import lsprotocol.types as types 

34 

35 try: 

36 from pygls.server import LanguageServer 

37 from pygls.workspace import TextDocument 

38 except ImportError: 

39 pass 

40 

41 from debputy.lsp.debputy_ls import DebputyLanguageServer 

42 

43 DEBPUTY_LANGUAGE_SERVER = DebputyLanguageServer("debputy", f"v{version()}") 

44else: 

45 import debputy.lsprotocol.types as types 

46 

47 try: 

48 from pygls.server import LanguageServer 

49 from pygls.workspace import TextDocument 

50 from debputy.lsp.debputy_ls import DebputyLanguageServer 

51 

52 DEBPUTY_LANGUAGE_SERVER = DebputyLanguageServer("debputy", f"v{version()}") 

53 except ImportError: 

54 

55 class Mock: 

56 

57 def feature(self, *args, **kwargs): 

58 return lambda x: x 

59 

60 DEBPUTY_LANGUAGE_SERVER = Mock() 

61 

62 

63P = TypeVar("P") 

64R = TypeVar("R") 

65L = TypeVar("L", "LanguageServer", "DebputyLanguageServer") 

66 

67 

68@DEBPUTY_LANGUAGE_SERVER.feature(types.INITIALIZE) 

69async def _on_initialize( 

70 ls: "DebputyLanguageServer", 

71 params: types.InitializeParams, 

72) -> None: 

73 await ls.on_initialize(params) 

74 

75 

76@DEBPUTY_LANGUAGE_SERVER.feature(types.TEXT_DOCUMENT_DID_OPEN) 

77async def _open_document( 

78 ls: "DebputyLanguageServer", 

79 params: types.DidChangeTextDocumentParams, 

80) -> None: 

81 await _open_or_changed_document(ls, params, "Opened") 

82 

83 

84@DEBPUTY_LANGUAGE_SERVER.feature(types.TEXT_DOCUMENT_DID_CHANGE) 

85async def _changed_document( 

86 ls: "DebputyLanguageServer", 

87 params: types.DidChangeTextDocumentParams, 

88) -> None: 

89 await _open_or_changed_document(ls, params, "Changed") 

90 

91 

92@DEBPUTY_LANGUAGE_SERVER.feature(types.TEXT_DOCUMENT_DID_CLOSE) 

93def _close_document( 

94 ls: "DebputyLanguageServer", 

95 params: types.DidCloseTextDocumentParams, 

96) -> None: 

97 ls.close_document(params.text_document.uri) 

98 

99 

100async def _open_or_changed_document( 

101 ls: "DebputyLanguageServer", 

102 params: types.DidOpenTextDocumentParams | types.DidChangeTextDocumentParams, 

103 event_name: Literal["Opened", "Changed"], 

104) -> None: 

105 doc_uri = params.text_document.uri 

106 doc = ls.workspace.get_text_document(doc_uri) 

107 

108 await _diagnostics_for( 

109 ls, 

110 doc, 

111 params.text_document.version, 

112 params, 

113 event_name, 

114 ) 

115 

116 

117async def _diagnostics_for( 

118 ls: "DebputyLanguageServer", 

119 doc: "TextDocument", 

120 expected_version: int, 

121 params: ( 

122 types.DidOpenTextDocumentParams 

123 | types.DidChangeTextDocumentParams 

124 | types.DocumentDiagnosticParams 

125 ), 

126 event_name: Literal["Opened", "Changed"], 

127) -> None: 

128 doc_uri = doc.uri 

129 id_source, language_id, normalized_filename = ls.determine_language_id(doc) 

130 log_func = _info if event_name == "Opened" else _trace_log 

131 handler = _resolve_handler( 

132 LSP_DIAGNOSTIC_HANDLERS, 

133 language_id, 

134 normalized_filename, 

135 log_func, 

136 ) 

137 if handler is None: 

138 log_func( 

139 f"{event_name} document: {doc.path} ({language_id}, {id_source}," 

140 f" normalized filename: {normalized_filename}) - no diagnostics handler" 

141 ) 

142 return 

143 log_func( 

144 f"{event_name} document: {doc.path} ({language_id}, {id_source}, normalized filename: {normalized_filename})" 

145 f" - running diagnostics for doc version {expected_version}" 

146 ) 

147 

148 try: 

149 diagnostics = await handler(ls, params) 

150 except AbortTaskError as e: 

151 _trace_log(f"Aborted lint task: {e.message}") 

152 return 

153 

154 ls.record_diagnostics(doc_uri, expected_version, diagnostics or [], False) 

155 

156 

157@DEBPUTY_LANGUAGE_SERVER.feature(types.TEXT_DOCUMENT_COMPLETION) 

158async def _completions( 

159 ls: "DebputyLanguageServer", 

160 params: types.CompletionParams, 

161) -> types.CompletionList | Sequence[types.CompletionItem] | None: 

162 return await _dispatch_standard_handler( 

163 ls, 

164 params.text_document.uri, 

165 params, 

166 COMPLETER_HANDLERS, 

167 "Complete request", 

168 ) 

169 

170 

171@DEBPUTY_LANGUAGE_SERVER.feature(types.TEXT_DOCUMENT_HOVER) 

172async def _hover( 

173 ls: "DebputyLanguageServer", 

174 params: types.CompletionParams, 

175) -> types.Hover | None: 

176 return await _dispatch_standard_handler( 

177 ls, 

178 params.text_document.uri, 

179 params, 

180 HOVER_HANDLERS, 

181 "Hover doc request", 

182 ) 

183 

184 

185@DEBPUTY_LANGUAGE_SERVER.feature(types.TEXT_DOCUMENT_INLAY_HINT) 

186async def _doc_inlay_hint( 

187 ls: "DebputyLanguageServer", 

188 params: types.InlayHintParams, 

189) -> list[types.InlayHint] | None: 

190 return await _dispatch_standard_handler( 

191 ls, 

192 params.text_document.uri, 

193 params, 

194 TEXT_DOC_INLAY_HANDLERS, 

195 "Inlay hint (doc) request", 

196 ) 

197 

198 

199@DEBPUTY_LANGUAGE_SERVER.feature(types.TEXT_DOCUMENT_CODE_ACTION) 

200async def _code_actions( 

201 ls: "DebputyLanguageServer", 

202 params: types.CodeActionParams, 

203) -> list[types.Command | types.CodeAction] | None: 

204 return await _dispatch_standard_handler( 

205 ls, 

206 params.text_document.uri, 

207 params, 

208 CODE_ACTION_HANDLERS, 

209 "Code action request", 

210 ) 

211 

212 

213@DEBPUTY_LANGUAGE_SERVER.feature(types.TEXT_DOCUMENT_FOLDING_RANGE) 

214async def _folding_ranges( 

215 ls: "DebputyLanguageServer", 

216 params: types.FoldingRangeParams, 

217) -> Sequence[types.FoldingRange] | None: 

218 return await _dispatch_standard_handler( 

219 ls, 

220 params.text_document.uri, 

221 params, 

222 FOLDING_RANGE_HANDLERS, 

223 "Folding range request", 

224 ) 

225 

226 

227@DEBPUTY_LANGUAGE_SERVER.feature( 

228 types.TEXT_DOCUMENT_SEMANTIC_TOKENS_FULL, 

229 types.SemanticTokensRegistrationOptions( 

230 SEMANTIC_TOKENS_LEGEND, 

231 full=True, 

232 ), 

233) 

234async def semantic_tokens_full( 

235 ls: "DebputyLanguageServer", 

236 params: types.SemanticTokensParams, 

237) -> types.SemanticTokens | None: 

238 return await _dispatch_standard_handler( 

239 ls, 

240 params.text_document.uri, 

241 params, 

242 SEMANTIC_TOKENS_FULL_HANDLERS, 

243 "Semantic tokens request", 

244 ) 

245 

246 

247@DEBPUTY_LANGUAGE_SERVER.feature(types.TEXT_DOCUMENT_WILL_SAVE_WAIT_UNTIL) 

248async def _will_save_wait_until( 

249 ls: "DebputyLanguageServer", 

250 params: types.WillSaveTextDocumentParams, 

251) -> Sequence[types.TextEdit] | None: 

252 return await _dispatch_standard_handler( 

253 ls, 

254 params.text_document.uri, 

255 params, 

256 WILL_SAVE_WAIT_UNTIL_HANDLERS, 

257 "On-save formatting", 

258 ) 

259 

260 

261@DEBPUTY_LANGUAGE_SERVER.feature(types.TEXT_DOCUMENT_FORMATTING) 

262async def _format_document( 

263 ls: "DebputyLanguageServer", 

264 params: types.WillSaveTextDocumentParams, 

265) -> Sequence[types.TextEdit] | None: 

266 return await _dispatch_standard_handler( 

267 ls, 

268 params.text_document.uri, 

269 params, 

270 LSP_FORMAT_FILE_HANDLERS, 

271 "Full document formatting", 

272 ) 

273 

274 

275@DEBPUTY_LANGUAGE_SERVER.feature(types.TEXT_DOCUMENT_DOCUMENT_LINK) 

276async def _document_link( 

277 ls: "DebputyLanguageServer", 

278 params: types.DocumentLinkParams, 

279) -> Optional[Sequence[types.DocumentLink]]: 

280 return await _dispatch_standard_handler( 

281 ls, 

282 params.text_document.uri, 

283 params, 

284 DOCUMENT_LINK_HANDLERS, 

285 "Document links request", 

286 ) 

287 

288 

289async def _dispatch_standard_handler( 

290 ls: "DebputyLanguageServer", 

291 doc_uri: str, 

292 params: P, 

293 handler_table: HandlerDispatchTable[C], 

294 request_type: str, 

295) -> R | None: 

296 doc = ls.workspace.get_text_document(doc_uri) 

297 

298 id_source, language_id, normalized_filename = ls.determine_language_id(doc) 

299 handler = _resolve_handler(handler_table, language_id, normalized_filename, _info) 

300 if handler is None: 

301 _info( 

302 f"{request_type} for document: {doc.path} ({language_id}, {id_source}," 

303 f" normalized filename: {normalized_filename}) - no handler" 

304 ) 

305 return None 

306 _info( 

307 f"{request_type} for document: {doc.path} ({language_id}, {id_source}," 

308 f" normalized filename: {normalized_filename}) - delegating to handler {handler.__qualname__}" 

309 ) 

310 

311 if inspect.iscoroutinefunction(handler): 

312 return await handler(ls, params) 

313 return handler(ls, params) 

314 

315 

316def _resolve_handler( 

317 handler_table: HandlerDispatchTable[C], 

318 language_id: str, 

319 normalized_filename: str, 

320 log_func: Callable[[str], None], 

321) -> C | None: 

322 dispatch_table = handler_table.get(language_id) if language_id != "" else None 

323 log_func(f"resolve_handler({language_id=}, {normalized_filename=})") 

324 if dispatch_table is None: 

325 filename_based_table = handler_table[""] 

326 m = filename_based_table.basename_based_lookups.get( 

327 os.path.basename(normalized_filename) 

328 ) 

329 if m is not None: 

330 return m 

331 return filename_based_table.path_name_based_lookups.get(normalized_filename) 

332 m = dispatch_table.basename_based_lookups.get( 

333 os.path.basename(normalized_filename), 

334 dispatch_table.default_handler, 

335 ) 

336 if m is not None: 

337 return m 

338 return dispatch_table.path_name_based_lookups.get( 

339 normalized_filename, dispatch_table.default_handler 

340 )