codis 1.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
src/editor/kdocs.py ADDED
@@ -0,0 +1,3376 @@
1
+ """Codis - KDocs - Universal Documentation Engine.
2
+
3
+ KDocs é um sistema de documentação universal que:
4
+ - Cobre JSDoc e outros formatos de documentação
5
+ - Suporta 20+ linguagens com parsers nativos (Python, Rust, Go, Ruby,
6
+ Lua, Doxygen/C/C++, C#/XML, Kotlin, Swift, PHP, Dart, R, Julia, etc.)
7
+ Sphinx/reST, Rust ///, Go godoc, YARD, LDoc, Doxygen, Roxygen2, Haddock
8
+ - Implementa anotações @kdocs: semânticas em qualquer comentário de qualquer
9
+ linguagem, incluindo HTML <!-- -->, Lua --[[-]], SQL --
10
+ - Metadados KDocs: [!due:YYYY-MM-DD], [!ticket:ID], URLs automáticas
11
+ - Hover balloon rico com badge de linguagem, anti-debounce e prioridades
12
+ - Cache LRU integrado para performance em arquivos grandes
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import contextlib
18
+ import logging
19
+ import re
20
+ import textwrap
21
+ import tkinter as tk
22
+ from collections import OrderedDict
23
+ from dataclasses import dataclass, field
24
+ from enum import Enum
25
+ from typing import Any
26
+
27
+ from src.i18n import _t
28
+
29
+ logger = logging.getLogger("Codis")
30
+
31
+ _MAX_USAGES: int = 200
32
+ _CACHE_MAX_SIZE: int = 64
33
+ _SCOPE_SCAN_LIMIT: int = 600
34
+
35
+ _DEF_PATTERNS: list[re.Pattern] = [
36
+ re.compile(
37
+ r"^\s*(?:export\s+)?(?:const|let|var)\s+([$\w]+)\s*(?:[:,=]|$)"),
38
+ re.compile(
39
+ r"^\s*(?:export\s+)?(?:async\s+)?function\s*\*?([$\w]+)\s*[\(<]"),
40
+ re.compile(r"^\s*(?:export\s+)?(?:abstract\s+)?class\s+([$\w]+)"),
41
+ re.compile(r"^\s*([$\w]+)\s*=\s*(?:function|class|\(|async)"),
42
+ re.compile(r"^\s*([$\w]+)\s*:\s*[a-zA-Z]"),
43
+ re.compile(r"^\s*(?:async\s+)?def\s+([$\w]+)\s*\("),
44
+ re.compile(r"^\s*class\s+([$\w]+)\s*[:(]"),
45
+ re.compile(r"^\s*([$\w]+)\s*=\s*"),
46
+ re.compile(r"^\s*import\s+([$\w]+)\s+from"),
47
+ re.compile(r"^\s*from\s+\S+\s+import\s+.*([$\w]+)"),
48
+ re.compile(r"^\s*(?:pub\s+)?(?:async\s+)?fn\s+([a-zA-Z_]\w*)"),
49
+ re.compile(
50
+ r"^\s*(?:pub\s+)?(?:struct|enum|trait|type|union)\s+([a-zA-Z_]\w*)"),
51
+ re.compile(r"^\s*(?:pub\s+)?(?:static|const)\s+([A-Z_][A-Z0-9_]*)"),
52
+ re.compile(r"^\s*func\s+(?:\([^)]*\)\s+)?([a-zA-Z_]\w*)"),
53
+ re.compile(r"^\s*type\s+([a-zA-Z_]\w*)\s+(?:struct|interface)"),
54
+ re.compile(r"^\s*(?:var|const)\s+([a-zA-Z_]\w*)"),
55
+ re.compile(r"^\s*def\s+([a-zA-Z_]\w*[?!]?)"),
56
+ re.compile(r"^\s*(?:class|module)\s+([A-Z]\w*)"),
57
+ re.compile(r"^\s*(?:local\s+)?function\s+([a-zA-Z_][\w.]*)"),
58
+ re.compile(r"^\s*([a-zA-Z_][\w.]*)\s*=\s*function"),
59
+ ]
60
+
61
+
62
+ class DocStyle(Enum):
63
+ """Estilo de documentação de uma linguagem."""
64
+
65
+ JSDOC = "jsdoc"
66
+ PYTHON = "python"
67
+ RUST = "rust"
68
+ GO = "go"
69
+ DOXYGEN = "doxygen"
70
+ RDOC = "rdoc"
71
+ LDOC = "ldoc"
72
+ HASH = "hash"
73
+ DASH = "dash"
74
+ HTML = "html"
75
+ UNKNOWN = "unknown"
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class LanguageProfile:
80
+ """Perfil de uma linguagem: sintaxe de comentários e estilo de doc."""
81
+
82
+ name: str
83
+ extensions: tuple[str, ...]
84
+ line_comments: tuple[str, ...]
85
+ block_open: str
86
+ block_close: str
87
+ doc_style: DocStyle
88
+ doc_block_open: str = "/**"
89
+ uses_indent_scope: bool = False
90
+
91
+
92
+ def _build_lang_map() -> dict[str, LanguageProfile]:
93
+ profiles = [
94
+ LanguageProfile(
95
+ "javascript",
96
+ (".js", ".mjs", ".cjs"),
97
+ ("//",),
98
+ "/*",
99
+ "*/",
100
+ DocStyle.JSDOC,
101
+ "/**",
102
+ ),
103
+ LanguageProfile(
104
+ "typescript",
105
+ (".ts", ".tsx", ".d.ts"),
106
+ ("//",),
107
+ "/*",
108
+ "*/",
109
+ DocStyle.JSDOC,
110
+ "/**",
111
+ ),
112
+ LanguageProfile("jsx", (".jsx",), ("//",), "/*",
113
+ "*/", DocStyle.JSDOC, "/**"),
114
+ LanguageProfile(
115
+ "python",
116
+ (".py", ".pyw", ".pyi"),
117
+ ("#",),
118
+ '"""',
119
+ '"""',
120
+ DocStyle.PYTHON,
121
+ '"""',
122
+ True,
123
+ ),
124
+ LanguageProfile(
125
+ "rust", (".rs",), ("///", "//!",
126
+ "//"), "/*", "*/", DocStyle.RUST, "/**"
127
+ ),
128
+ LanguageProfile("go", (".go",), ("//",), "/*",
129
+ "*/", DocStyle.GO, "/**"),
130
+ LanguageProfile("java", (".java",), ("//",), "/*",
131
+ "*/", DocStyle.JSDOC, "/**"),
132
+ LanguageProfile(
133
+ "kotlin", (".kt", ".kts"), ("//",
134
+ ), "/*", "*/", DocStyle.JSDOC, "/**"
135
+ ),
136
+ LanguageProfile(
137
+ "swift", (".swift",), ("//",), "/*", "*/", DocStyle.JSDOC, "/**"
138
+ ),
139
+ LanguageProfile(
140
+ "csharp", (".cs",), ("//",
141
+ "///"), "/*", "*/", DocStyle.DOXYGEN, "///"
142
+ ),
143
+ LanguageProfile(
144
+ "cpp",
145
+ (".cpp", ".cc", ".cxx", ".hpp", ".h"),
146
+ ("//",),
147
+ "/*",
148
+ "*/",
149
+ DocStyle.DOXYGEN,
150
+ "/**",
151
+ ),
152
+ LanguageProfile("c", (".c",), ("//",), "/*",
153
+ "*/", DocStyle.DOXYGEN, "/**"),
154
+ LanguageProfile(
155
+ "ruby",
156
+ (".rb", ".rake"),
157
+ ("#",),
158
+ "=begin",
159
+ "=end",
160
+ DocStyle.RDOC,
161
+ "##",
162
+ True,
163
+ ),
164
+ LanguageProfile("lua", (".lua",), ("--",),
165
+ "--[[", "]]", DocStyle.LDOC, "---"),
166
+ LanguageProfile("sql", (".sql",), ("--",), "/*",
167
+ "*/", DocStyle.DASH, "--"),
168
+ LanguageProfile(
169
+ "shell", (".sh", ".bash", ".zsh"), ("#",
170
+ ), "#", "", DocStyle.HASH, "##"
171
+ ),
172
+ LanguageProfile("yaml", (".yml", ".yaml"), ("#",),
173
+ "#", "", DocStyle.HASH, "#"),
174
+ LanguageProfile(
175
+ "html", (".html", ".htm"), ("<!--",
176
+ ), "<!--", "-->", DocStyle.HTML, "<!--"
177
+ ),
178
+ LanguageProfile("css", (".css",), (), "/*",
179
+ "*/", DocStyle.JSDOC, "/**"),
180
+ LanguageProfile(
181
+ "scss", (".scss", ".sass"), ("//",
182
+ ), "/*", "*/", DocStyle.JSDOC, "/**"
183
+ ),
184
+ LanguageProfile(
185
+ "php", (".php",), ("//", "#"), "/*", "*/", DocStyle.JSDOC, "/**"
186
+ ),
187
+ LanguageProfile("dart", (".dart",), ("//",), "/*",
188
+ "*/", DocStyle.JSDOC, "/**"),
189
+ LanguageProfile(
190
+ "elixir", (".ex", ".exs"), ("#",
191
+ ), '"""', '"""', DocStyle.PYTHON, '"""'
192
+ ),
193
+ LanguageProfile("r", (".r", ".R"), ("#",),
194
+ "#", "", DocStyle.HASH, "#'"),
195
+ LanguageProfile("julia", (".jl",), ("#",), "#=",
196
+ "=#", DocStyle.PYTHON, '"""'),
197
+ LanguageProfile(
198
+ "haskell", (".hs", ".lhs"), ("--",
199
+ ), "{-", "-}", DocStyle.DASH, "{-|"
200
+ ),
201
+ LanguageProfile("toml", (".toml",), ("#",),
202
+ "#", "", DocStyle.HASH, "#"),
203
+ ]
204
+ mapping: dict[str, LanguageProfile] = {}
205
+ for p in profiles:
206
+ for ext in p.extensions:
207
+ mapping[ext] = p
208
+ return mapping
209
+
210
+
211
+ _LANG_MAP: dict[str, LanguageProfile] = _build_lang_map()
212
+ _GENERIC_PROFILE = LanguageProfile(
213
+ "generic", (), ("//", "#", "--"), "/*", "*/", DocStyle.UNKNOWN
214
+ )
215
+
216
+
217
+ def get_language_profile(filename: str) -> LanguageProfile:
218
+ """Retorna o perfil de linguagem para a extensão do arquivo."""
219
+ if not filename:
220
+ return _GENERIC_PROFILE
221
+ dot = filename.rfind(".")
222
+ if dot == -1:
223
+ return _GENERIC_PROFILE
224
+ return _LANG_MAP.get(filename[dot:].lower(), _GENERIC_PROFILE)
225
+
226
+
227
+ class _DocCache:
228
+ """
229
+ Cache LRU (Least Recently Used) para armazenar resultados de parsing de documentação.
230
+
231
+ Esta classe implementa um cache simples baseado em `OrderedDict` que mantém
232
+ os itens mais recentemente acessados no final. Quando o limite de tamanho é
233
+ atingido, o item menos recentemente usado (no início) é removido.
234
+
235
+ Atributos:
236
+ _maxsize (int): Número máximo de itens no cache.
237
+ _store (OrderedDict): Dicionário ordenado que armazena os itens.
238
+ _hits (int): Contador de acessos com sucesso (cache hit).
239
+ _misses (int): Contador de acessos sem sucesso (cache miss).
240
+
241
+ Uso típico:
242
+ cache = _DocCache(maxsize=64)
243
+ resultado = cache.get(conteudo, "tag")
244
+ if resultado is None:
245
+ resultado = processar(conteudo)
246
+ cache.put(conteudo, "tag", resultado)
247
+ """
248
+
249
+ __slots__ = ("_maxsize", "_store", "_hits", "_misses")
250
+
251
+ def __init__(self, maxsize: int = _CACHE_MAX_SIZE) -> None:
252
+ """
253
+ Inicializa o cache com um tamanho máximo.
254
+
255
+ Args:
256
+ maxsize (int): Capacidade máxima do cache. Padrão: _CACHE_MAX_SIZE (64).
257
+ """
258
+ self._maxsize = maxsize
259
+ self._store: OrderedDict = OrderedDict()
260
+ self._hits = 0
261
+ self._misses = 0
262
+
263
+ @staticmethod
264
+ def _key(content: str, tag: str) -> int:
265
+ """
266
+ Gera uma chave hash única para identificar um conteúdo no cache.
267
+
268
+ A chave é composta pelo comprimento do conteúdo, pelos primeiros 64 caracteres,
269
+ pelos últimos 64 caracteres e pela tag. Isso equilibra unicidade e desempenho.
270
+
271
+ Args:
272
+ content (str): Conteúdo do arquivo ou texto a ser cacheado.
273
+ tag (str): Identificador adicional (ex.: tipo de parsing, linguagem).
274
+
275
+ Returns:
276
+ int: Valor hash que servirá como chave no dicionário.
277
+ """
278
+ return hash((len(content), content[:64], content[-64:], tag))
279
+
280
+ def get(self, content: str, tag: str) -> Any | None:
281
+ """
282
+ Recupera um valor do cache, se existir.
283
+
284
+ Se a chave estiver presente, o item é movido para o final do OrderedDict
285
+ (marcado como recentemente usado) e o contador de hits é incrementado.
286
+ Caso contrário, incrementa misses e retorna None.
287
+
288
+ Args:
289
+ content (str): Conteúdo associado à chave.
290
+ tag (str): Tag associada à chave.
291
+
292
+ Returns:
293
+ Any | None: O valor armazenado, ou None se não encontrado.
294
+ """
295
+ k = self._key(content, tag)
296
+ if k in self._store:
297
+ self._store.move_to_end(k)
298
+ self._hits += 1
299
+ return self._store[k]
300
+ self._misses += 1
301
+ return None
302
+
303
+ def put(self, content: str, tag: str, value: Any) -> None:
304
+ """
305
+ Insere ou atualiza um valor no cache.
306
+
307
+ Se a chave já existir, o valor é substituído e movido para o final.
308
+ Após a inserção, se o número de itens ultrapassar _maxsize, o item
309
+ menos recentemente usado (primeiro do OrderedDict) é removido.
310
+
311
+ Args:
312
+ content (str): Conteúdo associado à chave.
313
+ tag (str): Tag associada à chave.
314
+ value (Any): Valor a ser armazenado (geralmente o resultado do parsing).
315
+ """
316
+ k = self._key(content, tag)
317
+ self._store[k] = value
318
+ self._store.move_to_end(k)
319
+ while len(self._store) > self._maxsize:
320
+ self._store.popitem(last=False)
321
+
322
+
323
+ _cache = _DocCache()
324
+
325
+
326
+ @dataclass
327
+ class KDocsNotes:
328
+ """
329
+ Representa uma anotação @kdocs: extraída do código-fonte.
330
+
331
+ Atributos clássicos (KDocs 2.0):
332
+ line: Número da linha (base 1).
333
+ content: Texto principal da anotação.
334
+ file_ref, line_ref: Referência para @kdocs:link / @kdocs:see.
335
+ tags: Lista de tags [#tag1,tag2].
336
+ assignee: Responsável [@usuario].
337
+ priority: Prioridade (0=low, 1=normal, 2=high, 3=critical).
338
+ type_name: Nome do tipo para @kdocs:type.
339
+ symbols: Lista de símbolos vinculados [simbolo].
340
+ scope_start, scope_end: Escopo do símbolo seguinte (base 1).
341
+ icon, color: Calculados automaticamente.
342
+
343
+ Atributos KDocs:
344
+ body_lines: Linhas de continuação multi-linha.
345
+ severity: Severidade computada (0=info, 1=low, 2=med, 3=high).
346
+ language: Linguagem detectada.
347
+ due_date: Prazo [!due:YYYY-MM-DD].
348
+ ticket: ID de ticket [!ticket:ID].
349
+ url: URL extraída automaticamente do conteúdo.
350
+ """
351
+
352
+ line: int
353
+ kind: str
354
+ content: str
355
+ file_ref: str = ""
356
+ line_ref: int = 0
357
+ tags: list[str] = field(default_factory=list)
358
+ assignee: str = ""
359
+ priority: int = 0
360
+ type_name: str = ""
361
+ symbols: list[str] = field(default_factory=list)
362
+ scope_start: int = 0
363
+ scope_end: int = 0
364
+ icon: str = ""
365
+ color: str = ""
366
+ body_lines: list[str] = field(default_factory=list)
367
+ severity: int = 0
368
+ language: str = ""
369
+ due_date: str = ""
370
+ ticket: str = ""
371
+ url: str = ""
372
+
373
+ def __post_init__(self) -> None:
374
+ """Executa validação e ajustes pós-inicialização do dataclass."""
375
+ self.icon = KDocsParser.icon(self.kind)
376
+ self.color = KDocsParser.color(self.kind)
377
+ self.severity = self._compute_severity()
378
+
379
+ def _compute_severity(self) -> int:
380
+ """Calcula e retorna o nível de severidade do bloco IrisDoc atual."""
381
+ _sev = {
382
+ "note": 0,
383
+ "context": 0,
384
+ "step": 0,
385
+ "example": 0,
386
+ "param": 0,
387
+ "return": 0,
388
+ "returns": 0,
389
+ "type": 0,
390
+ "link": 0,
391
+ "see": 0,
392
+ "symbol": 0,
393
+ "doc": 0,
394
+ "todo": 1,
395
+ "question": 1,
396
+ "debug": 1,
397
+ "refactor": 1,
398
+ "test": 1,
399
+ "hack": 2,
400
+ "perf": 2,
401
+ "fixme": 2,
402
+ "warn": 2,
403
+ "deprecated": 2,
404
+ "throws": 2,
405
+ "review": 2,
406
+ "important": 3,
407
+ "security": 3,
408
+ "breaking": 3,
409
+ "mutex": 3,
410
+ }
411
+ return min(3, _sev.get(self.kind, 1) + max(0, self.priority - 1))
412
+
413
+ @property
414
+ def full_text(self) -> str:
415
+ """Texto completo incluindo linhas de continuação."""
416
+ parts = [self.content] + self.body_lines
417
+ return "\n".join(p for p in parts if p)
418
+
419
+ def to_dict(self) -> dict[str, Any]:
420
+ """Serializa a anotação em um dicionário plano (persistência e exportação)."""
421
+ return {
422
+ "line": self.line,
423
+ "kind": self.kind,
424
+ "content": self.content,
425
+ "file_ref": self.file_ref,
426
+ "line_ref": self.line_ref,
427
+ "tags": self.tags,
428
+ "assignee": self.assignee,
429
+ "priority": self.priority,
430
+ "severity": self.severity,
431
+ "type_name": self.type_name,
432
+ "symbols": self.symbols,
433
+ "scope_start": self.scope_start,
434
+ "scope_end": self.scope_end,
435
+ "due_date": self.due_date,
436
+ "ticket": self.ticket,
437
+ "url": self.url,
438
+ "body_lines": self.body_lines,
439
+ }
440
+
441
+
442
+ class KDocsParser:
443
+ """
444
+ Analisador de anotações @kdocs: para qualquer linguagem.
445
+
446
+ KDocs suporta:
447
+ - Prefixos de linha: //, #, --, ---, *, <!--
448
+ - Blocos: /* ... */, <!-- ... -->
449
+ - Multi-linha: linhas de continuação com mesmo prefixo
450
+ - Metadados avançados: [!due:YYYY-MM-DD], [!ticket:ID], URLs automáticas
451
+ - Cache LRU integrado
452
+
453
+ Exemplos válidos em qualquer linguagem:
454
+ // @kdocs:warn [fs] Não use sync em produção! [@alice] [!high] [#nosync]
455
+ -- @kdocs:note Consulta lenta, verificar índice
456
+ <!-- @kdocs:deprecated Esta API será removida -->
457
+ """
458
+
459
+ _LINE_RE: re.Pattern = re.compile(
460
+ r"(?:<!--|(?://+|#{1,2}|--{1,3}|\*)\s*)@kdocs:([\w]+)\s*(.*?)(?:-->)?\s*$",
461
+ re.MULTILINE,
462
+ )
463
+
464
+ _BLOCK_RE: re.Pattern = re.compile(
465
+ r"/\*+\s*@kdocs:([\w]+)\s*(.*?)\*/|<!--\s*@kdocs:([\w]+)\s*(.*?)-->",
466
+ re.DOTALL,
467
+ )
468
+
469
+ _CONT_RE: re.Pattern = re.compile(
470
+ r"^\s*(?://+|#{1,2}|--{1,3}|\*)\s{0,2}(.*)")
471
+
472
+ _ASSIGNEE_RE: re.Pattern = re.compile(r"\[@([\w.\-]+)\]")
473
+ _PRIORITY_RE: re.Pattern = re.compile(
474
+ r"\[!(low|normal|high|critical)\]", re.I)
475
+ _TAGS_RE: re.Pattern = re.compile(r"\[#([\w,.\-]+)\]")
476
+ _SYMBOL_RE: re.Pattern = re.compile(r"\[([a-zA-Z_$][\w$]*)\]")
477
+ _TYPE_NAME_RE: re.Pattern = re.compile(r"^([a-zA-Z_][\w]*)(?:\s+)?(.*?)$")
478
+ _DUE_RE: re.Pattern = re.compile(r"\[!due:([\d\-]+)\]", re.I)
479
+ _TICKET_RE: re.Pattern = re.compile(r"\[!ticket:([\w\-]+)\]", re.I)
480
+ _URL_RE: re.Pattern = re.compile(r"https?://\S+")
481
+
482
+ KIND_ICONS: dict[str, str] = {
483
+ "note": "💬",
484
+ "todo": "✅",
485
+ "warn": "⚠️",
486
+ "deprecated": "🚫",
487
+ "link": "🔗",
488
+ "see": "👁",
489
+ "param": "📥",
490
+ "return": "📤",
491
+ "returns": "📤",
492
+ "fixme": "🔧",
493
+ "hack": "🩹",
494
+ "perf": "⚡",
495
+ "security": "🔒",
496
+ "context": "📋",
497
+ "test": "🧪",
498
+ "debug": "🐛",
499
+ "refactor": "♻️",
500
+ "question": "❓",
501
+ "important": "❗",
502
+ "step": "🪜",
503
+ "example": "📖",
504
+ "throws": "💥",
505
+ "type": "🔠",
506
+ "symbol": "🔤",
507
+ "api": "🌐",
508
+ "breaking": "💔",
509
+ "review": "👀",
510
+ "doc": "📄",
511
+ "measure": "📏",
512
+ "mutex": "🔐",
513
+ "invariant": "📐",
514
+ }
515
+
516
+ KIND_COLORS: dict[str, str] = {
517
+ "note": "#89b4fa",
518
+ "todo": "#a6e3a1",
519
+ "warn": "#fab387",
520
+ "deprecated": "#f38ba8",
521
+ "link": "#7dcfff",
522
+ "see": "#cba6f7",
523
+ "param": "#89dceb",
524
+ "return": "#f9e2af",
525
+ "returns": "#f9e2af",
526
+ "fixme": "#ff9e64",
527
+ "hack": "#e0af68",
528
+ "perf": "#f9e2af",
529
+ "security": "#f38ba8",
530
+ "context": "#cdd6f4",
531
+ "test": "#94e2d5",
532
+ "debug": "#f38ba8",
533
+ "refactor": "#cba6f7",
534
+ "question": "#f9e2af",
535
+ "important": "#f38ba8",
536
+ "step": "#a6e3a1",
537
+ "example": "#89b4fa",
538
+ "throws": "#f38ba8",
539
+ "type": "#89dceb",
540
+ "symbol": "#89dceb",
541
+ "api": "#89b4fa",
542
+ "breaking": "#f38ba8",
543
+ "review": "#cba6f7",
544
+ "doc": "#89b4fa",
545
+ "measure": "#f9e2af",
546
+ "mutex": "#f38ba8",
547
+ "invariant": "#94e2d5",
548
+ }
549
+
550
+ _PRIORITY_MAP: dict[str, int] = {
551
+ "low": 0,
552
+ "normal": 1,
553
+ "high": 2,
554
+ "critical": 3,
555
+ }
556
+
557
+ @classmethod
558
+ def parse(cls, content: str, language: str = "") -> list[KDocsNotes]:
559
+ """
560
+ Extrai todas as anotações @kdocs: do conteúdo.
561
+
562
+ Suporta qualquer linguagem. Detecção automática de:
563
+ - Comentários de linha (//, #, --, ---, <!--)
564
+ - Blocos /* ... */ e <!-- ... -->
565
+ - Continuação multi-linha (linhas seguintes com mesmo prefixo)
566
+ [symbol], [!due:date], [!ticket:id]
567
+
568
+ Returns:
569
+ Lista de KDocsNotes ordenada por linha.
570
+ """
571
+ cache_key = f"kdocs3:{language}"
572
+ cached = _cache.get(content, cache_key)
573
+ if cached is not None:
574
+ return cached
575
+
576
+ lines = content.splitlines()
577
+ annotations: list[KDocsNotes] = []
578
+ seen: set[int] = set()
579
+
580
+ i = 0
581
+ while i < len(lines):
582
+ raw_line = lines[i]
583
+
584
+ bm = cls._BLOCK_RE.search(raw_line)
585
+ if bm and (i + 1) not in seen:
586
+ kind = (bm.group(1) or bm.group(3) or "").lower()
587
+ text = (bm.group(2) or bm.group(4) or "").strip()
588
+ ann = cls._build(kind, text, i + 1, lines, [], language)
589
+ if ann:
590
+ annotations.append(ann)
591
+ seen.add(i + 1)
592
+ i += 1
593
+ continue
594
+
595
+ lm = cls._LINE_RE.search(raw_line)
596
+ if lm and (i + 1) not in seen:
597
+ kind = lm.group(1).lower()
598
+ text = (lm.group(2) or "").strip()
599
+
600
+ body: list[str] = []
601
+ j = i + 1
602
+ while j < len(lines) and j - i < 9:
603
+ cm = cls._CONT_RE.match(lines[j])
604
+ if cm and "@kdocs:" not in lines[j] and "@" not in lines[j][:20]:
605
+ ct = cm.group(1).strip()
606
+ if ct and ct not in ("", "/", "*", "-", "--"):
607
+ body.append(ct)
608
+ j += 1
609
+ continue
610
+ break
611
+
612
+ ann = cls._build(kind, text, i + 1, lines, body, language)
613
+ if ann:
614
+ annotations.append(ann)
615
+ seen.add(i + 1)
616
+
617
+ i += 1
618
+
619
+ result = sorted(annotations, key=lambda a: a.line)
620
+ _cache.put(content, cache_key, result)
621
+ return result
622
+
623
+ @classmethod
624
+ def _build(
625
+ cls,
626
+ kind: str,
627
+ raw: str,
628
+ lineno: int,
629
+ lines: list[str],
630
+ body: list[str],
631
+ lang: str,
632
+ ) -> KDocsNotes | None:
633
+ """Constrói KDocsNotes a partir de texto bruto."""
634
+
635
+ raw, symbols = cls._pop(cls._SYMBOL_RE, raw, multi=True)
636
+ kind_n, raw = cls._type_name(kind, raw)
637
+ raw, due = cls._pop_single(cls._DUE_RE, raw)
638
+ raw, ticket = cls._pop_single(cls._TICKET_RE, raw)
639
+ raw, assignee = cls._pop_single(cls._ASSIGNEE_RE, raw)
640
+ raw, priority = cls._pop_priority(raw)
641
+ raw, tags = cls._pop_tags(raw)
642
+ url = cls._url(raw)
643
+ file_ref, lr = cls._link_ref(kind, raw)
644
+ ss, se = cls._scope(lines, lineno)
645
+
646
+ return KDocsNotes(
647
+ line=lineno,
648
+ kind=kind,
649
+ content=raw,
650
+ file_ref=file_ref,
651
+ line_ref=lr,
652
+ tags=tags,
653
+ assignee=assignee,
654
+ priority=priority,
655
+ type_name=kind_n,
656
+ symbols=symbols,
657
+ scope_start=ss,
658
+ scope_end=se,
659
+ body_lines=body,
660
+ language=lang,
661
+ due_date=due,
662
+ ticket=ticket,
663
+ url=url,
664
+ )
665
+
666
+ @classmethod
667
+ def _pop(
668
+ cls, pattern: re.Pattern, text: str, multi: bool = False
669
+ ) -> tuple[str, Any]:
670
+ """Remove matches do texto; retorna (cleaned, values)."""
671
+ if multi:
672
+ vals: list[str] = []
673
+ for m in pattern.finditer(text):
674
+ v = m.group(1)
675
+ if v not in vals:
676
+ vals.append(v)
677
+ return pattern.sub("", text).strip(), vals
678
+ m = pattern.search(text)
679
+ if m:
680
+ return pattern.sub("", text).strip(), m.group(1)
681
+ return text, ""
682
+
683
+ @classmethod
684
+ def _pop_single(cls, pattern: re.Pattern, text: str) -> tuple[str, str]:
685
+ m = pattern.search(text)
686
+ if m:
687
+ return pattern.sub("", text).strip(), m.group(1)
688
+ return text, ""
689
+
690
+ @classmethod
691
+ def _pop_priority(cls, text: str) -> tuple[str, int]:
692
+ m = cls._PRIORITY_RE.search(text)
693
+ if m:
694
+ p = cls._PRIORITY_MAP.get(m.group(1).lower(), 0)
695
+ return cls._PRIORITY_RE.sub("", text).strip(), p
696
+ return text, 0
697
+
698
+ @classmethod
699
+ def _pop_tags(cls, text: str) -> tuple[str, list[str]]:
700
+ m = cls._TAGS_RE.search(text)
701
+ if m:
702
+ tags = [t.strip() for t in m.group(1).split(",") if t.strip()]
703
+ return cls._TAGS_RE.sub("", text).strip(), tags
704
+ return text, []
705
+
706
+ @classmethod
707
+ def _type_name(cls, kind: str, text: str) -> tuple[str, str]:
708
+ if kind != "type":
709
+ return "", text
710
+ m = cls._TYPE_NAME_RE.match(text)
711
+ if m:
712
+ return m.group(1).strip(), m.group(2).strip()
713
+ return "", text
714
+
715
+ @classmethod
716
+ def _url(cls, text: str) -> str:
717
+ m = cls._URL_RE.search(text)
718
+ return m.group(0) if m else ""
719
+
720
+ @classmethod
721
+ def _link_ref(cls, kind: str, text: str) -> tuple[str, int]:
722
+ if kind not in ("link", "see") or not text:
723
+ return "", 0
724
+ parts = text.split("#", 1)
725
+ fr = parts[0].strip()
726
+ lr = 0
727
+ if len(parts) > 1:
728
+ with contextlib.suppress(ValueError):
729
+ lr = int(parts[1])
730
+ return fr, lr
731
+
732
+ @classmethod
733
+ def _scope(cls, lines: list[str], lineno: int) -> tuple[int, int]:
734
+ """Determina o escopo do símbolo seguinte à anotação."""
735
+ idx = lineno
736
+ while idx < len(lines):
737
+ s = lines[idx].strip()
738
+ if s and not s.startswith(("//", "#", "*", "/*", "--", "<!--")):
739
+ break
740
+ idx += 1
741
+ if idx >= len(lines):
742
+ return 0, 0
743
+ ss = idx + 1
744
+ se = cls._scope_end(lines, idx) + 1
745
+ return ss, max(ss, se)
746
+
747
+ @classmethod
748
+ def _scope_end(cls, lines: list[str], start: int) -> int:
749
+ """Fecha escopo por indentação (Python) ou chaves (C-family)."""
750
+ ln = lines[start] if start < len(lines) else ""
751
+
752
+ if ln.rstrip().endswith(":"):
753
+ base = len(ln) - len(ln.lstrip())
754
+ limit = min(start + _SCOPE_SCAN_LIMIT, len(lines))
755
+ for k in range(start + 1, limit):
756
+ row = lines[k]
757
+ if not row.strip():
758
+ continue
759
+ if len(row) - len(row.lstrip()) <= base:
760
+ return k - 1
761
+ return limit - 1
762
+
763
+ depth = found = 0
764
+ limit = min(start + _SCOPE_SCAN_LIMIT, len(lines))
765
+ for k in range(start, limit):
766
+ for ch in lines[k]:
767
+ if ch == "{":
768
+ depth += 1
769
+ found = 1
770
+ elif ch == "}":
771
+ depth -= 1
772
+ if found and depth == 0:
773
+ return k
774
+ return start
775
+
776
+ @classmethod
777
+ def resolve_hover(
778
+ cls,
779
+ word: str,
780
+ cursor_line: int,
781
+ annotations: list[KDocsNotes],
782
+ _: str,
783
+ ) -> KDocsNotes | None:
784
+ """
785
+ Resolve qual anotação exibir no hover.
786
+
787
+ Prioridade:
788
+ 1. Cursor na linha da anotação
789
+ 2. Cursor na linha imediatamente após
790
+ 3. word nos símbolos vinculados E cursor no escopo
791
+ 4. Cursor dentro do escopo de qualquer anotação
792
+ """
793
+ if not annotations:
794
+ return None
795
+
796
+ for ann in annotations:
797
+ if ann.line in (cursor_line, cursor_line - 1):
798
+ return ann
799
+
800
+ for ann in annotations:
801
+ if word and word in ann.symbols and (
802
+ ann.scope_start == 0
803
+ or ann.scope_start <= cursor_line <= ann.scope_end
804
+ ):
805
+ return ann
806
+
807
+ for ann in annotations:
808
+ if ann.scope_start and ann.scope_end:
809
+ if ann.scope_start <= cursor_line <= ann.scope_end:
810
+ return ann
811
+
812
+ return None
813
+
814
+ @classmethod
815
+ def icon(cls, kind: str) -> str:
816
+ """Retorna o ícone do tipo de anotação (``"📌"`` se o tipo for desconhecido)."""
817
+ return cls.KIND_ICONS.get(kind, "📌")
818
+
819
+ @classmethod
820
+ def color(cls, kind: str) -> str:
821
+ """Retorna a cor hexadecimal associada ao tipo de anotação.
822
+
823
+ Args:
824
+ kind (str): Tipo da anotação (ex.: ``"security"``, ``"note"``).
825
+
826
+ Returns:
827
+ str: Cor no formato ``"#rrggbb"``, ou ``"#cdd6f4"`` como fallback.
828
+ """
829
+ return cls.KIND_COLORS.get(kind, "#cdd6f4")
830
+
831
+
832
+ class JSDocParser:
833
+ """
834
+ Parser universal de documentação (KDocs).
835
+
836
+ Suporta JSDoc/TSDoc e, adicionalmente:
837
+
838
+ - JSDoc 3 / TSDoc completo (JS/TS/PHP/Dart/Kotlin/Swift)
839
+ - Python docstrings: Google style, NumPy style, Sphinx/reST
840
+ - Rust doc comments (///)
841
+ - Go godoc (// antes de declarações)
842
+ - Doxygen (C/C++ /** ... */ com @param / \\brief)
843
+ - C# XML doc comments (/// <summary>)
844
+ - YARD / RDoc (Ruby ##)
845
+ - LDoc (Lua ---)
846
+ - R Roxygen2 (#')
847
+ - Haddock (Haskell {-|)
848
+
849
+ Uso básico:
850
+ docs = JSDocParser.parse(content)
851
+ docs = JSDocParser.parse_file(content, "main.py")
852
+ result = JSDocParser.resolve_hover(word, line, docs)
853
+ sections = JSDocParser.format_sections_for_mode(name, doc, mode)
854
+ """
855
+
856
+ JSDOC_BLOCK: re.Pattern = re.compile(r"/\*\*([\s\S]*?)\*/", re.MULTILINE)
857
+ TAG_RE: re.Pattern = re.compile(
858
+ r"@([\w.\-]+)((?:\s+|\{)[^\n@]*)?", re.MULTILINE)
859
+ TYPE_RE: re.Pattern = re.compile(r"^\{([^}]+)\}")
860
+ OPT_TYPE_RE: re.Pattern = re.compile(r"^\{[=?]?([^}]+)[=?]?\}")
861
+ UNION_RE: re.Pattern = re.compile(r"^\{([^}]+\|[^}]+)\}")
862
+
863
+ _NAME_TAGS = frozenset(
864
+ {
865
+ "param",
866
+ "arg",
867
+ "argument",
868
+ "prop",
869
+ "property",
870
+ "typedef",
871
+ "callback",
872
+ "event",
873
+ "name",
874
+ "alias",
875
+ "borrows",
876
+ "lends",
877
+ "memberof",
878
+ "template",
879
+ "tparam",
880
+ }
881
+ )
882
+ _TYPE_ONLY_TAGS = frozenset(
883
+ {
884
+ "type",
885
+ "returns",
886
+ "return",
887
+ "yields",
888
+ "yield",
889
+ "throws",
890
+ "exception",
891
+ "error",
892
+ }
893
+ )
894
+ _FLAG_TAGS = frozenset(
895
+ {
896
+ "private",
897
+ "protected",
898
+ "public",
899
+ "readonly",
900
+ "static",
901
+ "abstract",
902
+ "virtual",
903
+ "override",
904
+ "deprecated",
905
+ "ignore",
906
+ "hideconstructor",
907
+ "generator",
908
+ "async",
909
+ "inner",
910
+ "instance",
911
+ "global",
912
+ "package",
913
+ "pure",
914
+ "const",
915
+ "unsafe",
916
+ "inline",
917
+ "final",
918
+ "sealed",
919
+ "nocollapse",
920
+ }
921
+ )
922
+
923
+ _SYMBOL_PATTERNS: list[str] = [
924
+ (
925
+ r"^(?:export\s+)?(?:default\s+)?(?:declare\s+)?"
926
+ r"(?:async\s+)?function\s*\*?([a-zA-Z_$][\w$]*)"
927
+ ),
928
+ r"^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([a-zA-Z_$][\w$]*)",
929
+ (
930
+ r"^(?:export\s+)?(?:declare\s+)?"
931
+ r"(?:interface|type|enum)\s+([a-zA-Z_$][\w$]*)"
932
+ ),
933
+ (
934
+ r"^(?:export\s+)?(?:declare\s+)?(?:const|let|var)\s+([a-zA-Z_$][\w$]*)"
935
+ r"(?::[^=]*)?\s*=\s*(?:async\s+)?(?:function|\(|class)"
936
+ ),
937
+ r"^(?:export\s+)?(?:declare\s+)?(?:const|let|var)\s+([a-zA-Z_$][\w$]*)",
938
+ (
939
+ r"^(?:(?:public|private|protected|static|async|override|abstract)\s+)*"
940
+ r"(?:async\s+)?([a-zA-Z_$][\w$]*)\s*\("
941
+ ),
942
+ r"^([a-zA-Z_$][\w$]*)\s*(?:=[^=]|\:)",
943
+ r"^(?:async\s+)?def\s+([a-zA-Z_][\w]*)",
944
+ r"^class\s+([a-zA-Z_][\w]*)",
945
+ r"^(?:pub\s+)?(?:pub\(crate\)\s+)?(?:async\s+)?fn\s+([a-zA-Z_][\w]*)",
946
+ r"^(?:pub\s+)?(?:struct|enum|trait|type|union|impl)\s+([a-zA-Z_][\w]*)",
947
+ r"^(?:pub\s+)?(?:static|const)\s+([A-Z_][A-Z0-9_]*)",
948
+ r"^func\s+(?:\([^)]*\)\s+)?([a-zA-Z_][\w]*)",
949
+ r"^type\s+([a-zA-Z_][\w]*)\s+(?:struct|interface)",
950
+ r"^(?:var|const)\s+([a-zA-Z_][\w]*)",
951
+ r"^def\s+([a-zA-Z_][\w]*[?!]?)",
952
+ r"^(?:class|module)\s+([A-Z][\w]*)",
953
+ r"^(?:attr_reader|attr_writer|attr_accessor)\s+:([a-z_][\w]*)",
954
+ (
955
+ r"^(?:(?:public|private|protected|static|final|async|"
956
+ r"override|sealed|virtual|abstract)\s+)*"
957
+ r"[\w<>\[\],\s]+\s+([a-zA-Z_$][\w$]*)\s*\("
958
+ ),
959
+ (
960
+ r"^(?:(?:static|inline|extern|virtual|explicit|constexpr)\s+)*"
961
+ r"[\w:*&<>]+\s+([a-zA-Z_][\w]*)\s*\("
962
+ ),
963
+ (
964
+ r"^(?:public|private|protected|static|abstract|final)?"
965
+ r"\s*function\s+([a-zA-Z_][\w]*)"
966
+ ),
967
+ r"^(?:local\s+)?function\s+([a-zA-Z_][\w.]*)",
968
+ r"^([a-zA-Z_][\w.]*)\s*=\s*function",
969
+ r"^(?:function\s+)?([a-zA-Z_][\w]*)\s*\(\)",
970
+ r"^([a-zA-Z_.][a-zA-Z0-9_.]*)\s*<-\s*function",
971
+ ]
972
+ _COMPILED_PATTERNS: list[re.Pattern] = [
973
+ re.compile(p) for p in _SYMBOL_PATTERNS]
974
+
975
+ _GOOGLE_SECT_RE: re.Pattern = re.compile(
976
+ r"^\s{0,4}([A-Z][A-Za-z\s]+):\s*$", re.MULTILINE
977
+ )
978
+ _NUMPY_SECT_RE: re.Pattern = re.compile(
979
+ r"^([A-Z][A-Za-z\s]+)\n[-=]+\s*$", re.MULTILINE
980
+ )
981
+ _SPHINX_PARAM_RE: re.Pattern = re.compile(
982
+ r":param\s+(?:([^:]+)\s+)?(\w+):\s*(.*?)(?=\n\s*:|$)", re.DOTALL
983
+ )
984
+ _SPHINX_TYPE_RE: re.Pattern = re.compile(
985
+ r":type\s+(\w+):\s*(.*?)(?=\n\s*:|$)", re.DOTALL
986
+ )
987
+ _SPHINX_RET_RE: re.Pattern = re.compile(
988
+ r":returns?:\s*(.*?)(?=\n\s*:|$)", re.DOTALL
989
+ )
990
+ _SPHINX_RTYPE_RE: re.Pattern = re.compile(
991
+ r":rtype:\s*(.*?)(?=\n\s*:|$)", re.DOTALL)
992
+ _SPHINX_RAISE_RE: re.Pattern = re.compile(
993
+ r":raises?\s+(\w+):\s*(.*?)(?=\n\s*:|$)", re.DOTALL
994
+ )
995
+ _DOXYGEN_TAG_RE: re.Pattern = re.compile(
996
+ r"[@\\](param|tparam|returns?|throws?|brief|details|note|warning|"
997
+ r"deprecated|since|author|version|see|pre|post|invariant|"
998
+ r"todo|bug|attention|code|endcode)\b\s*(.*?)(?=[@\\]|\*/|$)",
999
+ re.DOTALL,
1000
+ )
1001
+ _XML_TAG_RE: re.Pattern = re.compile(
1002
+ r"<(\w+)(?:\s+[^>]*)?>([^<]*)</\1>", re.DOTALL)
1003
+ _RUST_DOC_RE: re.Pattern = re.compile(
1004
+ r"^[ \t]*(?:///!?|//!)\s?(.*)", re.MULTILINE)
1005
+
1006
+ @classmethod
1007
+ def parse(cls, content: str) -> dict[str, dict]:
1008
+ """
1009
+ Analisa documentação no estilo JSDoc/TSDoc.
1010
+ """
1011
+ cached = _cache.get(content, "jsdoc")
1012
+ if cached is not None:
1013
+ return cached
1014
+ lines = content.splitlines()
1015
+ result = cls._parse_jsdoc_file(content, lines)
1016
+ _cache.put(content, "jsdoc", result)
1017
+ return result
1018
+
1019
+ @classmethod
1020
+ def parse_file(cls, content: str, filename: str) -> dict[str, dict]:
1021
+ """
1022
+ Analisa documentação detectando automaticamente o estilo
1023
+ de acordo com a extensão do arquivo.
1024
+
1025
+ Suporta Python, Rust, Go, Ruby, Lua, C/C++, C#, e mais.
1026
+ Para linguagens sem suporte específico, usa JSDoc.
1027
+
1028
+ Args:
1029
+ content: Conteúdo do arquivo.
1030
+ filename: Nome/caminho do arquivo para detecção de linguagem.
1031
+
1032
+ Returns:
1033
+ Dicionário {symbol: doc_dict}.
1034
+ """
1035
+ profile = get_language_profile(filename)
1036
+ cache_key = f"udoc:{profile.name}"
1037
+ cached = _cache.get(content, cache_key)
1038
+ if cached is not None:
1039
+ return cached
1040
+
1041
+ lines = content.splitlines()
1042
+ style = profile.doc_style
1043
+
1044
+ if style == DocStyle.PYTHON:
1045
+ result = cls._parse_python_file(content, lines)
1046
+ elif style == DocStyle.RUST:
1047
+ result = cls._parse_rust_file(content, lines)
1048
+ elif style == DocStyle.GO:
1049
+ result = cls._parse_go_file(content, lines)
1050
+ elif style == DocStyle.DOXYGEN:
1051
+ result = cls._parse_doxygen_file(content, lines)
1052
+ elif style == DocStyle.RDOC:
1053
+ result = cls._parse_ruby_file(content, lines)
1054
+ elif style == DocStyle.LDOC:
1055
+ result = cls._parse_lua_file(content, lines)
1056
+ else:
1057
+ result = cls._parse_jsdoc_file(content, lines)
1058
+
1059
+ for doc in result.values():
1060
+ doc.setdefault("_lang", profile.name)
1061
+ doc.setdefault("_style", style.value)
1062
+
1063
+ _cache.put(content, cache_key, result)
1064
+ return result
1065
+
1066
+ @classmethod
1067
+ def _parse_jsdoc_file(cls, _: str, lines: list[str]) -> dict[str, dict]:
1068
+ docs: dict[str, dict] = {}
1069
+ i = 0
1070
+ while i < len(lines):
1071
+ if not lines[i].strip().startswith("/**"):
1072
+ i += 1
1073
+ continue
1074
+ block_lines: list[str] = []
1075
+ while i < len(lines):
1076
+ block_lines.append(lines[i])
1077
+ if "*/" in lines[i]:
1078
+ break
1079
+ i += 1
1080
+ block = "\n".join(block_lines)
1081
+ symbol, sym_idx = cls._next_symbol(lines, i + 1)
1082
+ parsed = cls._parse_block(block)
1083
+ body_end = cls._body_end(lines, sym_idx)
1084
+ parsed["_symbol_line"] = sym_idx + 1
1085
+ parsed["_body_start"] = sym_idx + 1
1086
+ parsed["_body_end"] = body_end + 1
1087
+ if symbol:
1088
+ key = f"{symbol}__line_{sym_idx + 1}" if symbol in docs else symbol
1089
+ docs[key] = parsed
1090
+ for e in parsed.get("tags", {}).get("name", []):
1091
+ alt = (e.get("description") or "").strip()
1092
+ if alt and alt != symbol and alt not in docs:
1093
+ docs[alt] = parsed
1094
+ else:
1095
+ docs[f"__line_{i + 1}"] = parsed
1096
+ i += 1
1097
+ return docs
1098
+
1099
+ @classmethod
1100
+ def _parse_block(cls, block: str) -> dict:
1101
+ """Analisa um bloco /** ... */ em estrutura rica."""
1102
+ raw_lines = block.strip().splitlines()
1103
+ cleaned: list[str] = []
1104
+ for line in raw_lines:
1105
+ line = line.strip()
1106
+ line = re.sub(r"^/\*\*", "", line)
1107
+ line = re.sub(r"\*/$", "", line)
1108
+ line = re.sub(r"^\*\s?", "", line)
1109
+ cleaned.append(line.rstrip())
1110
+
1111
+ desc_parts: list[str] = []
1112
+ tags: dict[str, list[dict]] = {}
1113
+ cur_tag: str | None = None
1114
+ cur_entry: dict | None = None
1115
+
1116
+ for line in cleaned:
1117
+ if not line:
1118
+ if cur_tag is None:
1119
+ desc_parts.append("")
1120
+ elif cur_entry is not None:
1121
+ cur_entry["description"] += "\n"
1122
+ continue
1123
+
1124
+ if line.lstrip().startswith("@"):
1125
+ m = re.match(r"@([\w.\-]+)\s*(.*)", line.lstrip())
1126
+ if not m:
1127
+ if cur_entry is not None:
1128
+ cur_entry["description"] += " " + line
1129
+ continue
1130
+
1131
+ tag = m.group(1).lower()
1132
+ rest = m.group(2).strip()
1133
+ if tag not in tags:
1134
+ tags[tag] = []
1135
+
1136
+ entry: dict[str, Any] = {
1137
+ "type": "",
1138
+ "name": "",
1139
+ "description": "",
1140
+ "optional": False,
1141
+ "default": None,
1142
+ }
1143
+
1144
+ if tag in cls._FLAG_TAGS:
1145
+ entry["description"] = rest
1146
+ tags[tag].append(entry)
1147
+ cur_tag, cur_entry = tag, entry
1148
+ continue
1149
+
1150
+ tm = cls.OPT_TYPE_RE.match(rest)
1151
+ if tm:
1152
+ raw_t = tm.group(0)
1153
+ inner = tm.group(1).strip()
1154
+ if raw_t.startswith(("{=", "{?")) or raw_t.endswith(("=}", "?}")):
1155
+ entry["optional"] = True
1156
+ entry["type"] = inner
1157
+ rest = rest[len(raw_t):].strip()
1158
+
1159
+ if tag in cls._NAME_TAGS:
1160
+ om = re.match(r"\[([^\]=]+)(?:=([^\]]+))?\]", rest)
1161
+ if om:
1162
+ entry["name"] = om.group(1)
1163
+ entry["optional"] = True
1164
+ if om.group(2) is not None:
1165
+ entry["default"] = om.group(2)
1166
+ rest = rest[om.end():].strip()
1167
+ rest = re.sub(r"^[-:]\s*", "", rest)
1168
+ entry["description"] = rest
1169
+ else:
1170
+ parts = rest.split(None, 1)
1171
+ if parts:
1172
+ entry["name"] = parts[0].lstrip(".")
1173
+ r2 = parts[1] if len(parts) > 1 else ""
1174
+ entry["description"] = re.sub(r"^[-:]\s*", "", r2)
1175
+ elif tag in cls._TYPE_ONLY_TAGS:
1176
+ entry["description"] = rest
1177
+ else:
1178
+ entry["description"] = rest
1179
+
1180
+ tags[tag].append(entry)
1181
+ cur_tag, cur_entry = tag, entry
1182
+
1183
+ else:
1184
+ if cur_entry is not None:
1185
+ sep = "\n" if line.startswith(" ") else " "
1186
+ cur_entry["description"] = (
1187
+ cur_entry["description"].rstrip() + sep + line
1188
+ ).strip()
1189
+ else:
1190
+ desc_parts.append(line)
1191
+
1192
+ desc = "\n".join(desc_parts).strip()
1193
+ desc = re.sub(r"\n{3,}", "\n\n", desc)
1194
+ return {"description": desc, "tags": tags}
1195
+
1196
+ @classmethod
1197
+ def _parse_python_file(cls, _: str, lines: list[str]) -> dict[str, dict]:
1198
+ """Analisa docstrings Python (Google, NumPy, Sphinx)."""
1199
+ docs: dict[str, dict] = {}
1200
+ i = 0
1201
+ while i < len(lines):
1202
+ stripped = lines[i].strip()
1203
+ sym_m = None
1204
+ for pat in cls._COMPILED_PATTERNS[7:9]:
1205
+ m = pat.match(stripped)
1206
+ if m:
1207
+ sym_m = m
1208
+ break
1209
+ if sym_m:
1210
+ symbol = sym_m.group(1)
1211
+ sym_idx = i
1212
+
1213
+ j = i + 1
1214
+ while j < len(lines) and not lines[j].strip():
1215
+ j += 1
1216
+ if j < len(lines):
1217
+ ds = lines[j].strip()
1218
+ quote = None
1219
+ if ds.startswith(('"""', 'r"""')):
1220
+ quote = '"""'
1221
+ elif ds.startswith(("'''", "r'''")):
1222
+ quote = "'''"
1223
+ if quote:
1224
+ inner, j = cls._collect_docstring(lines, j, quote)
1225
+ parsed = cls._parse_python_docstring(inner)
1226
+ be = cls._body_end(lines, sym_idx)
1227
+ parsed["_symbol_line"] = sym_idx + 1
1228
+ parsed["_body_start"] = sym_idx + 1
1229
+ parsed["_body_end"] = be + 1
1230
+ key = (
1231
+ f"{symbol}__line_{sym_idx + 1}"
1232
+ if symbol in docs
1233
+ else symbol
1234
+ )
1235
+ docs[key] = parsed
1236
+ i += 1
1237
+ return docs
1238
+
1239
+ @classmethod
1240
+ def _collect_docstring(
1241
+ cls, lines: list[str], start: int, quote: str
1242
+ ) -> tuple[str, int]:
1243
+ """Coleta linhas de uma docstring multi-linha."""
1244
+ first = lines[start].strip()
1245
+ after_open = first[first.index(quote) + 3:]
1246
+ j = start + 1
1247
+
1248
+ if quote in after_open:
1249
+ inner = after_open[: after_open.index(quote)]
1250
+ return inner.strip(), j
1251
+
1252
+ collected = [after_open]
1253
+ while j < len(lines):
1254
+ ln = lines[j]
1255
+ if quote in ln:
1256
+ collected.append(ln[: ln.index(quote)])
1257
+ j += 1
1258
+ break
1259
+ collected.append(ln)
1260
+ j += 1
1261
+ return "\n".join(collected).strip(), j
1262
+
1263
+ @classmethod
1264
+ def _parse_python_docstring(cls, raw: str) -> dict:
1265
+ """Auto-detecta Google, NumPy, ou Sphinx e analisa."""
1266
+ raw = textwrap.dedent(raw).strip()
1267
+ if cls._NUMPY_SECT_RE.search(raw):
1268
+ return cls._parse_numpy(raw)
1269
+ if cls._SPHINX_PARAM_RE.search(raw):
1270
+ return cls._parse_sphinx(raw)
1271
+ if cls._GOOGLE_SECT_RE.search(raw):
1272
+ return cls._parse_google(raw)
1273
+ return {"description": raw, "tags": {}}
1274
+
1275
+ @classmethod
1276
+ def _parse_google(cls, raw: str) -> dict:
1277
+ """Analisa Google-style docstring."""
1278
+ _map = {
1279
+ "Args": "param",
1280
+ "Arguments": "param",
1281
+ "Parameters": "param",
1282
+ "Params": "param",
1283
+ "Returns": "returns",
1284
+ "Return": "returns",
1285
+ "Yields": "yields",
1286
+ "Yield": "yields",
1287
+ "Raises": "throws",
1288
+ "Raise": "throws",
1289
+ "Except": "throws",
1290
+ "Attributes": "property",
1291
+ "Note": "remarks",
1292
+ "Notes": "remarks",
1293
+ "Example": "example",
1294
+ "Examples": "example",
1295
+ "Todo": "todo",
1296
+ "References": "see",
1297
+ }
1298
+ sections = cls._split_google_sections(raw)
1299
+ tags: dict[str, list[dict]] = {}
1300
+ desc = sections.pop("__desc__", "").strip()
1301
+ for name, body in sections.items():
1302
+ key = _map.get(name, name.lower())
1303
+ if key in ("example", "remarks", "see", "todo"):
1304
+ tags.setdefault(key, []).append(
1305
+ {
1306
+ "type": "",
1307
+ "name": "",
1308
+ "description": body.strip(),
1309
+ "optional": False,
1310
+ "default": None,
1311
+ }
1312
+ )
1313
+ continue
1314
+ for line in body.splitlines():
1315
+ line = line.strip()
1316
+ if not line:
1317
+ continue
1318
+ m = re.match(r"^(\w+)\s*(?:\(([^)]+)\))?\s*:\s*(.*)", line)
1319
+ if m:
1320
+ tags.setdefault(key, []).append(
1321
+ {
1322
+ "type": (m.group(2) or "").strip(),
1323
+ "name": m.group(1),
1324
+ "description": m.group(3).strip(),
1325
+ "optional": "optional" in (m.group(2) or "").lower(),
1326
+ "default": None,
1327
+ }
1328
+ )
1329
+ elif tags.get(key):
1330
+ tags[key][-1]["description"] += " " + line
1331
+ return {"description": desc, "tags": tags}
1332
+
1333
+ @classmethod
1334
+ def _split_google_sections(cls, raw: str) -> dict[str, str]:
1335
+ result: dict[str, str] = {"__desc__": ""}
1336
+ current, buf = "__desc__", []
1337
+ for line in raw.splitlines():
1338
+ m = re.match(r"^\s{0,4}([A-Z][A-Za-z\s]+):\s*$", line)
1339
+ if m:
1340
+ result[current] = "\n".join(buf).strip()
1341
+ current, buf = m.group(1).strip(), []
1342
+ else:
1343
+ buf.append(line)
1344
+ result[current] = "\n".join(buf).strip()
1345
+ return result
1346
+
1347
+ @classmethod
1348
+ def _parse_numpy(cls, raw: str) -> dict:
1349
+ """Analisa NumPy-style docstring."""
1350
+ _map = {
1351
+ "Parameters": "param",
1352
+ "Returns": "returns",
1353
+ "Yields": "yields",
1354
+ "Raises": "throws",
1355
+ "Attributes": "property",
1356
+ "Notes": "remarks",
1357
+ "Examples": "example",
1358
+ "References": "see",
1359
+ "See Also": "see",
1360
+ "Other Parameters": "param",
1361
+ }
1362
+ sections = cls._split_numpy_sections(raw)
1363
+ tags: dict[str, list[dict]] = {}
1364
+ desc = sections.pop("__desc__", "").strip()
1365
+ for name, body in sections.items():
1366
+ key = _map.get(name, name.lower())
1367
+ lines = body.splitlines()
1368
+ i = 0
1369
+ while i < len(lines):
1370
+ line = lines[i].strip()
1371
+ if not line:
1372
+ i += 1
1373
+ continue
1374
+ m = re.match(r"^(\w+)\s*:\s*(.*)", line)
1375
+ if m:
1376
+ typ = m.group(2).strip()
1377
+ desc_l: list[str] = []
1378
+ i += 1
1379
+ while i < len(lines) and lines[i].startswith(" "):
1380
+ desc_l.append(lines[i].strip())
1381
+ i += 1
1382
+ tags.setdefault(key, []).append(
1383
+ {
1384
+ "type": typ,
1385
+ "name": m.group(1),
1386
+ "description": " ".join(desc_l),
1387
+ "optional": "optional" in typ.lower(),
1388
+ "default": None,
1389
+ }
1390
+ )
1391
+ else:
1392
+ if key in ("example", "remarks", "see"):
1393
+ tags.setdefault(key, []).append(
1394
+ {
1395
+ "type": "",
1396
+ "name": "",
1397
+ "description": body.strip(),
1398
+ "optional": False,
1399
+ "default": None,
1400
+ }
1401
+ )
1402
+ break
1403
+ i += 1
1404
+ return {"description": desc, "tags": tags}
1405
+
1406
+ @classmethod
1407
+ def _split_numpy_sections(cls, raw: str) -> dict[str, str]:
1408
+ result: dict[str, str] = {"__desc__": ""}
1409
+ current, buf = "__desc__", []
1410
+ lines = raw.splitlines()
1411
+ i = 0
1412
+ while i < len(lines):
1413
+ if i + 1 < len(lines) and re.match(r"^[-=]+\s*$", lines[i + 1]):
1414
+ result[current] = "\n".join(buf).strip()
1415
+ current, buf = lines[i].strip(), []
1416
+ i += 2
1417
+ continue
1418
+ buf.append(lines[i])
1419
+ i += 1
1420
+ result[current] = "\n".join(buf).strip()
1421
+ return result
1422
+
1423
+ @classmethod
1424
+ def _parse_sphinx(cls, raw: str) -> dict:
1425
+ """Analisa Sphinx/reST docstring."""
1426
+ tags: dict[str, list[dict]] = {}
1427
+ fd = re.search(r"\n\s*:", raw)
1428
+ desc = raw[: fd.start()].strip() if fd else raw
1429
+
1430
+ types: dict[str, str] = {}
1431
+ for m in cls._SPHINX_TYPE_RE.finditer(raw):
1432
+ types[m.group(1)] = m.group(2).strip()
1433
+
1434
+ for m in cls._SPHINX_PARAM_RE.finditer(raw):
1435
+ typ = (m.group(1) or types.get(m.group(2), "")).strip()
1436
+ tags.setdefault("param", []).append(
1437
+ {
1438
+ "type": typ,
1439
+ "name": m.group(2),
1440
+ "description": m.group(3).strip(),
1441
+ "optional": False,
1442
+ "default": None,
1443
+ }
1444
+ )
1445
+
1446
+ for m in cls._SPHINX_RET_RE.finditer(raw):
1447
+ rt = ""
1448
+ rtm = cls._SPHINX_RTYPE_RE.search(raw)
1449
+ if rtm:
1450
+ rt = rtm.group(1).strip()
1451
+ tags.setdefault("returns", []).append(
1452
+ {
1453
+ "type": rt,
1454
+ "name": "",
1455
+ "description": m.group(1).strip(),
1456
+ "optional": False,
1457
+ "default": None,
1458
+ }
1459
+ )
1460
+
1461
+ for m in cls._SPHINX_RAISE_RE.finditer(raw):
1462
+ tags.setdefault("throws", []).append(
1463
+ {
1464
+ "type": m.group(1),
1465
+ "name": "",
1466
+ "description": m.group(2).strip(),
1467
+ "optional": False,
1468
+ "default": None,
1469
+ }
1470
+ )
1471
+
1472
+ return {"description": desc, "tags": tags}
1473
+
1474
+ @classmethod
1475
+ def _parse_rust_file(cls, _: str, lines: list[str]) -> dict[str, dict]:
1476
+ docs: dict[str, dict] = {}
1477
+ i = 0
1478
+ while i < len(lines):
1479
+ s = lines[i].strip()
1480
+ if not (s.startswith("///") or s.startswith("//!")):
1481
+ i += 1
1482
+ continue
1483
+ doc_lines: list[str] = []
1484
+ j = i
1485
+ while j < len(lines):
1486
+ sl = lines[j].strip()
1487
+ if sl.startswith("///") or sl.startswith("//!"):
1488
+ doc_lines.append(re.sub(r"^///!?|^//!", "", sl).strip())
1489
+ j += 1
1490
+ else:
1491
+ break
1492
+ raw = "\n".join(doc_lines)
1493
+ parsed = cls._parse_rust_doc(raw)
1494
+ symbol, sym_idx = cls._next_symbol(lines, j)
1495
+ be = cls._body_end(lines, sym_idx)
1496
+ parsed["_symbol_line"] = sym_idx + 1
1497
+ parsed["_body_start"] = sym_idx + 1
1498
+ parsed["_body_end"] = be + 1
1499
+ if symbol:
1500
+ key = f"{symbol}__line_{sym_idx + 1}" if symbol in docs else symbol
1501
+ docs[key] = parsed
1502
+ else:
1503
+ docs[f"__line_{i + 1}"] = parsed
1504
+ i = j
1505
+ return docs
1506
+
1507
+ @classmethod
1508
+ def _parse_rust_doc(cls, raw: str) -> dict:
1509
+ """Analisa markdown em doc comments Rust."""
1510
+ sections = cls._split_md_sections(raw)
1511
+ desc = sections.pop("__desc__", "").strip()
1512
+ tags: dict[str, list[dict]] = {}
1513
+ _map = {
1514
+ "Arguments": "param",
1515
+ "Parameters": "param",
1516
+ "Returns": "returns",
1517
+ "Return Value": "returns",
1518
+ "Errors": "throws",
1519
+ "Panics": "throws",
1520
+ "Examples": "example",
1521
+ "Example": "example",
1522
+ "Safety": "remarks",
1523
+ "Notes": "remarks",
1524
+ "Note": "remarks",
1525
+ }
1526
+ for name, body in sections.items():
1527
+ key = _map.get(name, name.lower())
1528
+ items = cls._parse_bullets(body)
1529
+ if items:
1530
+ tags.setdefault(key, []).extend(items)
1531
+ else:
1532
+ tags.setdefault(key, []).append(
1533
+ {
1534
+ "type": "",
1535
+ "name": "",
1536
+ "description": body.strip(),
1537
+ "optional": False,
1538
+ "default": None,
1539
+ }
1540
+ )
1541
+ return {"description": desc, "tags": tags}
1542
+
1543
+ @classmethod
1544
+ def _parse_go_file(cls, _: str, lines: list[str]) -> dict[str, dict]:
1545
+ docs: dict[str, dict] = {}
1546
+ i = 0
1547
+ while i < len(lines):
1548
+ if not lines[i].strip().startswith("//"):
1549
+ i += 1
1550
+ continue
1551
+ dl: list[str] = []
1552
+ j = i
1553
+ while j < len(lines):
1554
+ s = lines[j].strip()
1555
+ if s.startswith("//") and not s.startswith("//go:"):
1556
+ dl.append(re.sub(r"^//\s?", "", s))
1557
+ j += 1
1558
+ elif not s:
1559
+ j += 1
1560
+ break
1561
+ break
1562
+
1563
+ k = j
1564
+ while k < len(lines) and not lines[k].strip():
1565
+ k += 1
1566
+ symbol, sym_idx = cls._next_symbol(lines, k)
1567
+ if symbol:
1568
+ raw = "\n".join(dl)
1569
+ parsed = cls._parse_go_doc(raw)
1570
+ be = cls._body_end(lines, sym_idx)
1571
+ parsed["_symbol_line"] = sym_idx + 1
1572
+ parsed["_body_start"] = sym_idx + 1
1573
+ parsed["_body_end"] = be + 1
1574
+ key = f"{symbol}__line_{sym_idx + 1}" if symbol in docs else symbol
1575
+ docs[key] = parsed
1576
+ i = j
1577
+ return docs
1578
+
1579
+ @classmethod
1580
+ def _parse_go_doc(cls, raw: str) -> dict:
1581
+ """Analisa godoc (texto puro + Deprecated:)."""
1582
+ tags: dict[str, list[dict]] = {}
1583
+ if re.search(r"^Deprecated:", raw, re.MULTILINE):
1584
+ tags["deprecated"] = [
1585
+ {
1586
+ "type": "",
1587
+ "name": "",
1588
+ "description": "",
1589
+ "optional": False,
1590
+ "default": None,
1591
+ }
1592
+ ]
1593
+ return {"description": raw.strip(), "tags": tags}
1594
+
1595
+ @classmethod
1596
+ def _parse_doxygen_file(cls, _: str, lines: list[str]) -> dict[str, dict]:
1597
+ docs: dict[str, dict] = {}
1598
+ i = 0
1599
+ while i < len(lines):
1600
+ s = lines[i].strip()
1601
+ if not (s.startswith("/**") or s.startswith("///")):
1602
+ i += 1
1603
+ continue
1604
+ if s.startswith("///"):
1605
+ dl: list[str] = []
1606
+ j = i
1607
+ while j < len(lines) and lines[j].strip().startswith("///"):
1608
+ dl.append(re.sub(r"^///\s?", "", lines[j].strip()))
1609
+ j += 1
1610
+ parsed = cls._parse_xml_doc("\n".join(dl))
1611
+ else:
1612
+ bl: list[str] = []
1613
+ while i < len(lines):
1614
+ bl.append(lines[i])
1615
+ if "*/" in lines[i]:
1616
+ break
1617
+ i += 1
1618
+ j = i + 1
1619
+ parsed = cls._parse_doxygen_block("\n".join(bl))
1620
+ symbol, sym_idx = cls._next_symbol(lines, j)
1621
+ be = cls._body_end(lines, sym_idx)
1622
+ parsed["_symbol_line"] = sym_idx + 1
1623
+ parsed["_body_start"] = sym_idx + 1
1624
+ parsed["_body_end"] = be + 1
1625
+ if symbol:
1626
+ key = f"{symbol}__line_{sym_idx + 1}" if symbol in docs else symbol
1627
+ docs[key] = parsed
1628
+ else:
1629
+ docs[f"__line_{i + 1}"] = parsed
1630
+ i = j
1631
+ return docs
1632
+
1633
+ @classmethod
1634
+ def _parse_doxygen_block(cls, block: str) -> dict:
1635
+ lines = block.strip().splitlines()
1636
+ cleaned: list[str] = []
1637
+ for ln in lines:
1638
+ ln = re.sub(r"^\s*/\*\*?\s?", "", ln)
1639
+ ln = re.sub(r"\*/\s*$", "", ln)
1640
+ ln = re.sub(r"^\s*\*\s?", "", ln)
1641
+ cleaned.append(ln)
1642
+ raw = "\n".join(cleaned)
1643
+
1644
+ _dox_map = {
1645
+ "brief": "summary",
1646
+ "details": "remarks",
1647
+ "param": "param",
1648
+ "tparam": "template",
1649
+ "returns": "returns",
1650
+ "return": "returns",
1651
+ "throws": "throws",
1652
+ "throw": "throws",
1653
+ "note": "remarks",
1654
+ "warning": "warn",
1655
+ "deprecated": "deprecated",
1656
+ "since": "since",
1657
+ "author": "author",
1658
+ "version": "version",
1659
+ "see": "see",
1660
+ "pre": "remarks",
1661
+ "post": "remarks",
1662
+ "invariant": "remarks",
1663
+ "todo": "todo",
1664
+ "bug": "fixme",
1665
+ "attention": "important",
1666
+ "code": "example",
1667
+ "endcode": "_skip",
1668
+ }
1669
+ tags: dict[str, list[dict]] = {}
1670
+ desc_parts: list[str] = []
1671
+ last = 0
1672
+
1673
+ for m in cls._DOXYGEN_TAG_RE.finditer(raw):
1674
+ if m.start() > last:
1675
+ desc_parts.append(raw[last: m.start()].strip())
1676
+ tag = m.group(1).lower()
1677
+ body = (m.group(2) or "").strip()
1678
+ mapped = _dox_map.get(tag, tag)
1679
+ last = m.end()
1680
+ if mapped == "_skip":
1681
+ continue
1682
+ entry: dict[str, Any] = {
1683
+ "type": "",
1684
+ "name": "",
1685
+ "description": body,
1686
+ "optional": False,
1687
+ "default": None,
1688
+ }
1689
+ if mapped in ("param", "template"):
1690
+ parts = body.split(None, 1)
1691
+ if parts:
1692
+ entry["name"] = parts[0]
1693
+ entry["description"] = parts[1] if len(parts) > 1 else ""
1694
+ tags.setdefault(mapped, []).append(entry)
1695
+
1696
+ desc = "\n".join(p for p in desc_parts if p).strip()
1697
+ return {"description": desc, "tags": tags}
1698
+
1699
+ @classmethod
1700
+ def _parse_xml_doc(cls, raw: str) -> dict:
1701
+ """C# XML doc comments (/// <summary> etc.)."""
1702
+ tags: dict[str, list[dict]] = {}
1703
+ desc = ""
1704
+ for m in cls._XML_TAG_RE.finditer(raw):
1705
+ tag = m.group(1).lower()
1706
+ body = m.group(2).strip()
1707
+ if tag == "summary":
1708
+ desc = body
1709
+ elif tag == "remarks":
1710
+ tags.setdefault("remarks", []).append(
1711
+ {
1712
+ "type": "",
1713
+ "name": "",
1714
+ "description": body,
1715
+ "optional": False,
1716
+ "default": None,
1717
+ }
1718
+ )
1719
+ elif tag == "param":
1720
+ nm = re.search(r'name="([^"]+)"', m.group(0))
1721
+ tags.setdefault("param", []).append(
1722
+ {
1723
+ "type": "",
1724
+ "name": nm.group(1) if nm else "",
1725
+ "description": body,
1726
+ "optional": False,
1727
+ "default": None,
1728
+ }
1729
+ )
1730
+ elif tag == "returns":
1731
+ tags.setdefault("returns", []).append(
1732
+ {
1733
+ "type": "",
1734
+ "name": "",
1735
+ "description": body,
1736
+ "optional": False,
1737
+ "default": None,
1738
+ }
1739
+ )
1740
+ elif tag == "exception":
1741
+ cr = re.search(r'cref="([^"]+)"', m.group(0))
1742
+ tags.setdefault("throws", []).append(
1743
+ {
1744
+ "type": cr.group(1) if cr else "",
1745
+ "name": "",
1746
+ "description": body,
1747
+ "optional": False,
1748
+ "default": None,
1749
+ }
1750
+ )
1751
+ return {"description": desc, "tags": tags}
1752
+
1753
+ @classmethod
1754
+ def _parse_ruby_file(cls, _: str, lines: list[str]) -> dict[str, dict]:
1755
+ docs: dict[str, dict] = {}
1756
+ i = 0
1757
+ while i < len(lines):
1758
+ if not lines[i].strip().startswith("#"):
1759
+ i += 1
1760
+ continue
1761
+ dl: list[str] = []
1762
+ j = i
1763
+ while j < len(lines) and lines[j].strip().startswith("#"):
1764
+ dl.append(re.sub(r"^##?\s?", "", lines[j].strip()))
1765
+ j += 1
1766
+ k = j
1767
+ while k < len(lines) and not lines[k].strip():
1768
+ k += 1
1769
+ symbol, sym_idx = cls._next_symbol(lines, k)
1770
+ if symbol:
1771
+ parsed = cls._parse_yard("\n".join(dl))
1772
+ be = cls._body_end(lines, sym_idx)
1773
+ parsed["_symbol_line"] = sym_idx + 1
1774
+ parsed["_body_start"] = sym_idx + 1
1775
+ parsed["_body_end"] = be + 1
1776
+ key = f"{symbol}__line_{sym_idx + 1}" if symbol in docs else symbol
1777
+ docs[key] = parsed
1778
+ i = j
1779
+ return docs
1780
+
1781
+ @classmethod
1782
+ def _parse_yard(cls, raw: str) -> dict:
1783
+ """Analisa YARD (@param, @return, @raise)."""
1784
+ _map = {
1785
+ "param": "param",
1786
+ "return": "returns",
1787
+ "returns": "returns",
1788
+ "raise": "throws",
1789
+ "raises": "throws",
1790
+ "see": "see",
1791
+ "since": "since",
1792
+ "deprecated": "deprecated",
1793
+ "example": "example",
1794
+ "note": "remarks",
1795
+ "author": "author",
1796
+ "version": "version",
1797
+ "overload": "remarks",
1798
+ }
1799
+ tags: dict[str, list[dict]] = {}
1800
+ desc_lines: list[str] = []
1801
+ for line in raw.splitlines():
1802
+ m = re.match(r"@(\w+)\s*(.*)", line.strip())
1803
+ if m:
1804
+ tag = m.group(1).lower()
1805
+ rest = m.group(2).strip()
1806
+ entry: dict[str, Any] = {
1807
+ "type": "",
1808
+ "name": "",
1809
+ "description": rest,
1810
+ "optional": False,
1811
+ "default": None,
1812
+ }
1813
+ tm = re.match(r"\[([^\]]+)\]\s*(\w+)?\s*(.*)", rest)
1814
+ if tm:
1815
+ entry["type"] = tm.group(1)
1816
+ entry["name"] = tm.group(2) or ""
1817
+ entry["description"] = tm.group(3).strip()
1818
+ mapped = _map.get(tag, tag)
1819
+ tags.setdefault(mapped, []).append(entry)
1820
+ else:
1821
+ desc_lines.append(line)
1822
+ return {"description": "\n".join(desc_lines).strip(), "tags": tags}
1823
+
1824
+ @classmethod
1825
+ def _parse_lua_file(cls, _: str, lines: list[str]) -> dict[str, dict]:
1826
+ docs: dict[str, dict] = {}
1827
+ i = 0
1828
+ while i < len(lines):
1829
+ if not lines[i].strip().startswith("---"):
1830
+ i += 1
1831
+ continue
1832
+ dl: list[str] = []
1833
+ j = i
1834
+ while j < len(lines):
1835
+ sl = lines[j].strip()
1836
+ if sl.startswith("---") or sl.startswith("-- ") or sl == "--":
1837
+ dl.append(re.sub(r"^-{2,3}\s?", "", sl))
1838
+ j += 1
1839
+ else:
1840
+ break
1841
+ symbol, sym_idx = cls._next_symbol(lines, j)
1842
+ if symbol:
1843
+ parsed = cls._parse_ldoc("\n".join(dl))
1844
+ be = cls._body_end(lines, sym_idx)
1845
+ parsed["_symbol_line"] = sym_idx + 1
1846
+ parsed["_body_start"] = sym_idx + 1
1847
+ parsed["_body_end"] = be + 1
1848
+ key = f"{symbol}__line_{sym_idx + 1}" if symbol in docs else symbol
1849
+ docs[key] = parsed
1850
+ i = j
1851
+ return docs
1852
+
1853
+ @classmethod
1854
+ def _parse_ldoc(cls, raw: str) -> dict:
1855
+ """Analisa LDoc (--- style, similar a JSDoc)."""
1856
+ _map = {
1857
+ "tparam": "param",
1858
+ "treturn": "returns",
1859
+ "return": "returns",
1860
+ "raise": "throws",
1861
+ "see": "see",
1862
+ "usage": "example",
1863
+ }
1864
+ tags: dict[str, list[dict]] = {}
1865
+ desc_lines: list[str] = []
1866
+ for line in raw.splitlines():
1867
+ m = re.match(r"@(\w+)\s*(.*)", line.strip())
1868
+ if m:
1869
+ tag, rest = m.group(1).lower(), m.group(2).strip()
1870
+ mapped = _map.get(tag, tag)
1871
+ entry: dict[str, Any] = {
1872
+ "type": "",
1873
+ "name": "",
1874
+ "description": rest,
1875
+ "optional": False,
1876
+ "default": None,
1877
+ }
1878
+ parts = rest.split(None, 2)
1879
+ if tag in ("tparam",) and len(parts) >= 2:
1880
+ entry["type"] = parts[0]
1881
+ entry["name"] = parts[1]
1882
+ entry["description"] = parts[2] if len(parts) > 2 else ""
1883
+ tags.setdefault(mapped, []).append(entry)
1884
+ else:
1885
+ desc_lines.append(line)
1886
+ return {"description": "\n".join(desc_lines).strip(), "tags": tags}
1887
+
1888
+ @classmethod
1889
+ def _split_md_sections(cls, raw: str) -> dict[str, str]:
1890
+ """Divide texto markdown por # headings."""
1891
+ result: dict[str, str] = {"__desc__": ""}
1892
+ current, buf = "__desc__", []
1893
+ for line in raw.splitlines():
1894
+ m = re.match(r"^#{1,3}\s+(.*)", line)
1895
+ if m:
1896
+ result[current] = "\n".join(buf).strip()
1897
+ current, buf = m.group(1).strip(), []
1898
+ else:
1899
+ buf.append(line)
1900
+ result[current] = "\n".join(buf).strip()
1901
+ return result
1902
+
1903
+ @classmethod
1904
+ def _parse_bullets(cls, content: str) -> list[dict[str, Any]]:
1905
+ """Analisa lista de bullets como itens de doc."""
1906
+ entries = []
1907
+ for line in content.splitlines():
1908
+ m = re.match(r"^[-*]\s+`?(\w+)`?\s*[-:]\s*(.*)", line.strip())
1909
+ if m:
1910
+ entries.append(
1911
+ {
1912
+ "type": "",
1913
+ "name": m.group(1),
1914
+ "description": m.group(2).strip(),
1915
+ "optional": False,
1916
+ "default": None,
1917
+ }
1918
+ )
1919
+ return entries
1920
+
1921
+ @classmethod
1922
+ def _next_symbol(cls, lines: list[str], start: int) -> tuple[str | None, int]:
1923
+ """Encontra o próximo símbolo após start (pula decorators)."""
1924
+ limit = min(start + 15, len(lines))
1925
+ for j in range(start, limit):
1926
+ line = lines[j].strip()
1927
+ if not line or line.startswith(("//", "#", "*", "/*", "--")):
1928
+ continue
1929
+ for pat in cls._COMPILED_PATTERNS:
1930
+ m = pat.match(line)
1931
+ if m:
1932
+ return m.group(1), j
1933
+ if line and not line.startswith(("@", '"', "'")):
1934
+ break
1935
+ return None, start
1936
+
1937
+ @classmethod
1938
+ def _body_end(cls, lines: list[str], decl_idx: int) -> int:
1939
+ """Encontra o fim do corpo de uma declaração."""
1940
+ if decl_idx >= len(lines):
1941
+ return decl_idx + 1
1942
+ decl = lines[decl_idx]
1943
+
1944
+ if decl.rstrip().endswith(":"):
1945
+ base = len(decl) - len(decl.lstrip())
1946
+ limit = min(decl_idx + 300, len(lines))
1947
+ for k in range(decl_idx + 1, limit):
1948
+ ln = lines[k]
1949
+ if not ln.strip():
1950
+ continue
1951
+ if len(ln) - len(ln.lstrip()) <= base:
1952
+ return k - 1
1953
+ return limit - 1
1954
+
1955
+ if decl.strip().endswith(";"):
1956
+ return decl_idx
1957
+
1958
+ depth = found = 0
1959
+ limit = min(decl_idx + 500, len(lines))
1960
+ for k in range(decl_idx, limit):
1961
+ for ch in lines[k]:
1962
+ if ch == "{":
1963
+ depth += 1
1964
+ found = 1
1965
+ elif ch == "}":
1966
+ depth -= 1
1967
+ if found and depth == 0:
1968
+ return k
1969
+ return decl_idx + 1
1970
+
1971
+ @classmethod
1972
+ def resolve_hover(
1973
+ cls, word: str, cursor_line: int, docs: dict[str, dict]
1974
+ ) -> tuple[str, dict, str] | None:
1975
+ """
1976
+ Resolve documentação para o hover.
1977
+
1978
+ Returns:
1979
+ (nome, doc_dict, modo) onde modo é "full"|"param"|"return"
1980
+ """
1981
+ if word in docs:
1982
+ return (word, docs[word], "full")
1983
+
1984
+ for sym, doc in docs.items():
1985
+ base = sym.split("__line_")[0]
1986
+ if base == word:
1987
+ sl = doc.get("_symbol_line", 0)
1988
+ if sl and abs(cursor_line - sl) <= 2:
1989
+ return (word, doc, "full")
1990
+
1991
+ for sym, doc in docs.items():
1992
+ if sym.startswith("__"):
1993
+ continue
1994
+ bs = doc.get("_body_start", 0)
1995
+ be = doc.get("_body_end", 0)
1996
+ if bs and be and bs < cursor_line <= be:
1997
+ res = cls._check_param_match(word, doc, sym)
1998
+ if res:
1999
+ return res
2000
+ return (sym, doc, "full")
2001
+
2002
+ for sym, doc in docs.items():
2003
+ if sym.startswith("__"):
2004
+ continue
2005
+ sl = doc.get("_symbol_line", 0)
2006
+ if sl and abs(cursor_line - sl) <= 2:
2007
+ return (sym, doc, "full")
2008
+
2009
+ for key, doc in docs.items():
2010
+ if not key.startswith("__line_"):
2011
+ continue
2012
+ with contextlib.suppress(ValueError):
2013
+ dl = int(key.split("_")[-1])
2014
+ if abs(cursor_line - dl) <= 3:
2015
+ return (word or key, doc, "full")
2016
+
2017
+ return None
2018
+
2019
+ @classmethod
2020
+ def _check_param_match(
2021
+ cls, word: str, doc: dict, func_name: str
2022
+ ) -> tuple[str, dict, str] | None:
2023
+ tags = doc.get("tags", {})
2024
+ for key in ("param", "arg", "argument"):
2025
+ for entry in tags.get(key, []):
2026
+ if entry.get("name") == word:
2027
+ pd = {
2028
+ "description": "",
2029
+ "tags": {key: [entry]},
2030
+ "_symbol_line": doc.get("_symbol_line", 0),
2031
+ "_body_start": doc.get("_body_start", 0),
2032
+ "_body_end": doc.get("_body_end", 0),
2033
+ "_param_of": func_name,
2034
+ "_lang": doc.get("_lang", ""),
2035
+ }
2036
+ return (word, pd, "param")
2037
+ return None
2038
+
2039
+ @classmethod
2040
+ def format_sections(
2041
+ cls, symbol: str, doc: dict, source: str = "jsdoc"
2042
+ ) -> list[dict]:
2043
+ """
2044
+ Converte doc_dict em seções para o popup.
2045
+ """
2046
+ sections: list[dict] = []
2047
+ tags = doc.get("tags", {})
2048
+ lang = doc.get("_lang", "")
2049
+
2050
+ badge_source = f"{lang}" if lang else source
2051
+
2052
+ ret_type = cls._ret_type(tags)
2053
+ type_tag = (tags.get("type") or [{}])[0].get("type", "")
2054
+ tpl = [e.get("name", "")
2055
+ for e in tags.get("template", []) if e.get("name")]
2056
+ mods = [
2057
+ f
2058
+ for f in (
2059
+ "static",
2060
+ "async",
2061
+ "abstract",
2062
+ "readonly",
2063
+ "private",
2064
+ "protected",
2065
+ "public",
2066
+ "unsafe",
2067
+ "final",
2068
+ "override",
2069
+ )
2070
+ if tags.get(f)
2071
+ ]
2072
+
2073
+ sections.append(
2074
+ {
2075
+ "kind": "title",
2076
+ "symbol": symbol,
2077
+ "ret_type": ret_type,
2078
+ "type_tag": type_tag,
2079
+ "modifiers": mods,
2080
+ "tpl_params": tpl,
2081
+ "source": badge_source,
2082
+ }
2083
+ )
2084
+
2085
+ if tags.get("deprecated"):
2086
+ msg = (tags["deprecated"][0].get("description") or "").strip()
2087
+ sections.append(
2088
+ {
2089
+ "kind": "deprecated",
2090
+ "lines": [f"⚠ Depreciado{(': ' + msg) if msg else ''}"],
2091
+ }
2092
+ )
2093
+ sections.append({"kind": "sep"})
2094
+
2095
+ for key in ("summary", "brief", "remarks"):
2096
+ if tags.get(key):
2097
+ text = (tags[key][0].get("description") or "").strip()
2098
+ if text:
2099
+ sections.append({"kind": "remarks", "lines": [text]})
2100
+ sections.append({"kind": "sep"})
2101
+ break
2102
+
2103
+ desc = (doc.get("description") or "").strip()
2104
+ for k in ("desc", "description"):
2105
+ if tags.get(k):
2106
+ extra = (tags[k][0].get("description") or "").strip()
2107
+ if extra:
2108
+ desc = (desc + "\n\n" + extra).strip() if desc else extra
2109
+ if desc:
2110
+ sections.append({"kind": "desc", "lines": cls._wrap(desc)})
2111
+ sections.append({"kind": "sep"})
2112
+
2113
+ if tags.get("template") or tags.get("tparam"):
2114
+ rows = []
2115
+ for e in tags.get("template") or tags.get("tparam") or []:
2116
+ rows.append(
2117
+ {
2118
+ "name": e.get("name") or e.get("description") or "",
2119
+ "type": e.get("type", ""),
2120
+ "desc": e.get("description", ""),
2121
+ "optional": False,
2122
+ }
2123
+ )
2124
+ if rows:
2125
+ sections.append({"kind": "template", "rows": rows})
2126
+ sections.append({"kind": "sep"})
2127
+
2128
+ param_rows = []
2129
+ for key in ("param", "arg", "argument", "property", "prop"):
2130
+ for p in tags.get(key, []):
2131
+ param_rows.append(
2132
+ {
2133
+ "name": p.get("name", ""),
2134
+ "type": p.get("type", ""),
2135
+ "desc": (p.get("description") or "").strip(),
2136
+ "optional": p.get("optional", False),
2137
+ "default": p.get("default"),
2138
+ }
2139
+ )
2140
+ if param_rows:
2141
+ sections.append({"kind": "params", "rows": param_rows})
2142
+ sections.append({"kind": "sep"})
2143
+
2144
+ for key in ("returns", "return", "yields", "yield"):
2145
+ if tags.get(key):
2146
+ ret = tags[key][0]
2147
+ sections.append(
2148
+ {
2149
+ "kind": "returns",
2150
+ "type": (ret.get("type") or "").strip(),
2151
+ "desc": (ret.get("description") or "").strip(),
2152
+ "yields": key in ("yields", "yield"),
2153
+ }
2154
+ )
2155
+ sections.append({"kind": "sep"})
2156
+ break
2157
+
2158
+ throw_rows = []
2159
+ for key in ("throws", "throw", "exception", "error", "raise", "raises"):
2160
+ for e in tags.get(key, []):
2161
+ throw_rows.append(
2162
+ {
2163
+ "type": (e.get("type") or "").strip(),
2164
+ "desc": (e.get("description") or "").strip(),
2165
+ }
2166
+ )
2167
+ if throw_rows:
2168
+ sections.append({"kind": "throws", "rows": throw_rows})
2169
+ sections.append({"kind": "sep"})
2170
+
2171
+ ex_lines: list[str] = []
2172
+ for ex in tags.get("example", []) + tags.get("usage", []):
2173
+ raw = ex.get("description") or ex.get("type") or ""
2174
+ ex_lines.extend(raw.splitlines())
2175
+ if ex_lines:
2176
+ sections.append({"kind": "example", "lines": ex_lines[:30]})
2177
+ sections.append({"kind": "sep"})
2178
+
2179
+ if tags.get("type"):
2180
+ ts = (tags["type"][0].get("type") or "").strip()
2181
+ if ts:
2182
+ sections.append({"kind": "type", "type": ts})
2183
+ sections.append({"kind": "sep"})
2184
+
2185
+ meta: list[str] = []
2186
+ for tag_key, label in (
2187
+ ("since", "Desde"),
2188
+ ("version", "Versão"),
2189
+ ("author", "Autor"),
2190
+ ("license", "Licença"),
2191
+ ("todo", "TODO"),
2192
+ ("bug", "Bug"),
2193
+ ("fixme", "FIXME"),
2194
+ ):
2195
+ if tags.get(tag_key):
2196
+ v = (
2197
+ tags[tag_key][0].get("description")
2198
+ or tags[tag_key][0].get("name")
2199
+ or ""
2200
+ ).strip()
2201
+ if v:
2202
+ meta.append(f"{label}: {v}")
2203
+ for key in ("see", "link", "tutorial"):
2204
+ for item in tags.get(key, []):
2205
+ v = (item.get("description") or item.get("name") or "").strip()
2206
+ if v:
2207
+ meta.append(f"Veja: {v}")
2208
+ for key in ("fires", "emits", "listens"):
2209
+ for item in tags.get(key, []):
2210
+ v = (item.get("description") or item.get("name") or "").strip()
2211
+ lbl = "Emite" if key in ("fires", "emits") else "Escuta"
2212
+ if v:
2213
+ meta.append(f"{lbl}: {v}")
2214
+ for item in tags.get("requires", []):
2215
+ v = (item.get("description") or item.get("name") or "").strip()
2216
+ if v:
2217
+ meta.append(f"Requer: {v}")
2218
+ if meta:
2219
+ sections.append({"kind": "meta", "lines": meta})
2220
+ sections.append({"kind": "sep"})
2221
+
2222
+ while sections and sections[-1].get("kind") == "sep":
2223
+ sections.pop()
2224
+ return sections
2225
+
2226
+ @classmethod
2227
+ def format_sections_for_mode(cls, display: str, doc: dict, mode: str) -> list[dict]:
2228
+ """
2229
+ Constrói seções do popup de acordo com o modo de hover.
2230
+ """
2231
+ if mode == "full":
2232
+ return cls.format_sections(display, doc, source="jsdoc")
2233
+ if mode == "param":
2234
+ return cls._build_param_sections(display, doc)
2235
+ return cls.format_sections(display, doc, source="jsdoc")
2236
+
2237
+ @classmethod
2238
+ def _build_param_sections(cls, display: str, doc: dict) -> list[dict]:
2239
+ tags = doc.get("tags", {})
2240
+ entry = None
2241
+ parent = doc.get("_param_of", "")
2242
+ for key in ("param", "arg", "argument"):
2243
+ for e in tags.get(key, []):
2244
+ if e.get("name") == display:
2245
+ entry = e
2246
+ break
2247
+ if entry:
2248
+ break
2249
+
2250
+ sections: list[dict] = []
2251
+ typ = (entry.get("type") or "") if entry else ""
2252
+ desc = (entry.get("description") or "") if entry else ""
2253
+ opt = entry.get("optional", False) if entry else False
2254
+
2255
+ sections.append(
2256
+ {
2257
+ "kind": "title",
2258
+ "symbol": display + ("?" if opt else ""),
2259
+ "ret_type": "",
2260
+ "type_tag": typ,
2261
+ "modifiers": ["param"],
2262
+ "tpl_params": [],
2263
+ "source": doc.get("_lang", "jsdoc"),
2264
+ }
2265
+ )
2266
+ if parent:
2267
+ sections.append({"kind": "meta", "lines": [
2268
+ f"parâmetro de {parent}()"]})
2269
+ if desc:
2270
+ sections.append({"kind": "sep"})
2271
+ sections.append({"kind": "desc", "lines": cls._wrap(desc[:180])})
2272
+ return sections
2273
+
2274
+ @classmethod
2275
+ def _ret_type(cls, tags: dict) -> str:
2276
+ for key in ("returns", "return", "yields", "yield"):
2277
+ if tags.get(key):
2278
+ return (tags[key][0].get("type") or "").strip()
2279
+ return ""
2280
+
2281
+ @classmethod
2282
+ def _wrap(cls, text: str, width: int = 72) -> list[str]:
2283
+ """Envolve ou formata o conteúdo.
2284
+
2285
+ Args:
2286
+ text: Dado textual a processar.
2287
+ """
2288
+ result: list[str] = []
2289
+ for para in text.split("\n\n"):
2290
+ lines = textwrap.wrap(para.replace("\n", " "), width) or [""]
2291
+ result.extend(lines)
2292
+ result.append("")
2293
+ while result and not result[-1]:
2294
+ result.pop()
2295
+ return result
2296
+
2297
+
2298
+ class KDocsBalloon:
2299
+ """
2300
+ Popup flutuante rico para documentação (KDocs + JSDoc + LSP).
2301
+
2302
+ - Badge de linguagem colorido (Python, Rust, Go, etc.)
2303
+ - Seção de prazo/ticket para anotações @kdocs: avançadas
2304
+ - Renderização de URL clicável
2305
+ - Anti-flicker: mesmo símbolo+linha não redesenha
2306
+ - Scroll automático se conteúdo ultrapassar 80% da tela
2307
+ - Auto-ocultar configurável (padrão 6 s)
2308
+ """
2309
+
2310
+ def __init__(self, theme: Any) -> None:
2311
+ """Balloon unificado de documentação (LSP + KDocs + JSDoc + Peek)."""
2312
+ self._theme = theme
2313
+ self._win: tk.Toplevel | None = None
2314
+ self._anchor: tk.Widget | None = None
2315
+ self._job: str | None = None
2316
+ self._last_key: tuple = ()
2317
+ self._pinned: bool = False
2318
+ self._poll_job: str | None = None
2319
+
2320
+ def show(
2321
+ self,
2322
+ anchor: tk.Widget,
2323
+ screen_x: int,
2324
+ screen_y: int,
2325
+ sections: list[dict],
2326
+ ) -> None:
2327
+ """Exibe o balloon unificado.
2328
+
2329
+ Regras de vida útil
2330
+ -------------------
2331
+ - Nunca fecha automaticamente; fecha só quando o mouse sai da área
2332
+ (balloon + âncora) por mais de 400 ms.
2333
+ - Ctrl pressionado -> modo interativo: remove overrideredirect, adiciona
2334
+ barra de título nativa, permite resize, não fecha pelo mouse.
2335
+ - Balloon já visível com mesmo conteúdo -> ignora (anti-flicker).
2336
+ """
2337
+ new_key = (
2338
+ screen_x // 8,
2339
+ screen_y // 8,
2340
+ len(sections),
2341
+ sections[0].get("symbol", "") if sections else "",
2342
+ )
2343
+ if new_key == self._last_key and self.is_visible():
2344
+ return
2345
+ self._last_key = new_key
2346
+
2347
+ try:
2348
+ ctrl_held = bool(anchor.tk.call("set", "_codis_ctrl_held") == "1")
2349
+ except Exception:
2350
+ ctrl_held = False
2351
+
2352
+ self.hide()
2353
+ self._anchor = anchor
2354
+ self._pinned = ctrl_held
2355
+
2356
+ colors = self._extract_theme_colors()
2357
+
2358
+ if ctrl_held:
2359
+ win = self._create_pinned_window(anchor, screen_x, screen_y)
2360
+ else:
2361
+ win = self._create_hover_window(anchor)
2362
+
2363
+ self._build_content(win, sections, colors, ctrl_held)
2364
+ self._win = win
2365
+
2366
+ if ctrl_held:
2367
+ self._position_window(win, screen_x, screen_y)
2368
+ else:
2369
+ self._position_window(win, screen_x, screen_y)
2370
+ self._start_mouse_poll()
2371
+
2372
+ @staticmethod
2373
+ def _create_hover_window(anchor: tk.Widget) -> tk.Toplevel:
2374
+ """Toplevel sem bordas para modo hover normal."""
2375
+ try:
2376
+ root = anchor.winfo_toplevel()
2377
+ except tk.TclError:
2378
+ root = anchor
2379
+ win = tk.Toplevel(root)
2380
+ win.wm_overrideredirect(True)
2381
+ win.wm_attributes("-topmost", True)
2382
+ win.geometry("+9999+9999")
2383
+ with contextlib.suppress(tk.TclError):
2384
+ win.wm_attributes("-alpha", 0.97)
2385
+ return win
2386
+
2387
+ @staticmethod
2388
+ def _create_pinned_window(anchor: tk.Widget, sx: int, sy: int) -> tk.Toplevel:
2389
+ """Toplevel com decorações nativas para modo interativo (Ctrl-pin)."""
2390
+ try:
2391
+ root = anchor.winfo_toplevel()
2392
+ except tk.TclError:
2393
+ root = anchor
2394
+ win = tk.Toplevel(root)
2395
+
2396
+ win.wm_overrideredirect(False)
2397
+ win.title("📚 Documentação")
2398
+ win.wm_attributes("-topmost", True)
2399
+ win.geometry(f"500x380+{sx}+{sy}")
2400
+ win.minsize(360, 220)
2401
+ win.resizable(True, True)
2402
+ with contextlib.suppress(tk.TclError):
2403
+ win.wm_attributes("-alpha", 0.98)
2404
+ return win
2405
+
2406
+ def _build_content(
2407
+ self, win: tk.Toplevel, sections: list[dict], colors: dict, pinned: bool
2408
+ ) -> None:
2409
+ """Constrói header + área scrollável com todas as seções."""
2410
+ win.configure(bg=colors["bg"])
2411
+
2412
+ header = tk.Frame(win, bg=colors["bg"])
2413
+ header.pack(fill="x")
2414
+
2415
+ tk.Button(
2416
+ header,
2417
+ text="✕",
2418
+ bg=colors["bg"],
2419
+ fg=colors["fg_dim"],
2420
+ relief="flat",
2421
+ bd=0,
2422
+ cursor="hand2",
2423
+ font=("Segoe UI", 8),
2424
+ command=self.hide,
2425
+ ).pack(side="right", padx=(0, 4), pady=2)
2426
+
2427
+ mode_icon = "📌 Interativo" if pinned else "🔗 Hover"
2428
+ tk.Label(
2429
+ header,
2430
+ text=mode_icon,
2431
+ bg=colors["bg"],
2432
+ fg=colors["fg_dim"],
2433
+ font=("Segoe UI", 7),
2434
+ ).pack(side="left", padx=4, pady=2)
2435
+
2436
+ if not pinned:
2437
+ tk.Label(
2438
+ header,
2439
+ text=_t("kdocs.ctrl_hint"),
2440
+ bg=colors["bg"],
2441
+ fg=colors["dim"],
2442
+ font=("Segoe UI", 7),
2443
+ ).pack(side="left", padx=4, pady=2)
2444
+
2445
+ tk.Frame(win, bg=colors["dim"], height=1).pack(fill="x")
2446
+
2447
+ outer = tk.Frame(win, bg=colors["bg"])
2448
+ outer.pack(fill="both", expand=True)
2449
+
2450
+ canvas = tk.Canvas(
2451
+ outer,
2452
+ bg=colors["bg"],
2453
+ highlightthickness=0,
2454
+ width=460,
2455
+ height=min(420, 36 * len(sections) + 50),
2456
+ )
2457
+ vsb = tk.Scrollbar(outer, orient="vertical", command=canvas.yview)
2458
+ cf = tk.Frame(canvas, bg=colors["bg"], padx=12, pady=8)
2459
+
2460
+ cf_id = canvas.create_window((0, 0), window=cf, anchor="nw")
2461
+
2462
+ def _on_cf(_: tk.Event) -> None:
2463
+ canvas.configure(scrollregion=canvas.bbox("all"))
2464
+ rh = cf.winfo_reqheight()
2465
+ canvas.configure(height=min(420, max(60, rh)))
2466
+ canvas.itemconfig(cf_id, width=canvas.winfo_width())
2467
+
2468
+ def _on_cv(e: tk.Event) -> None:
2469
+ canvas.itemconfig(cf_id, width=e.width)
2470
+
2471
+ cf.bind("<Configure>", _on_cf)
2472
+ canvas.bind("<Configure>", _on_cv)
2473
+
2474
+ def _wheel(e: tk.Event) -> None:
2475
+ d = -1 * (e.delta // 120) if e.delta else (1 if e.num == 5 else -1)
2476
+ canvas.yview_scroll(d, "units")
2477
+
2478
+ for w in (canvas, cf, outer, win):
2479
+ with contextlib.suppress(tk.TclError):
2480
+ w.bind("<MouseWheel>", _wheel, add=True)
2481
+ w.bind("<Button-4>", _wheel, add=True)
2482
+ w.bind("<Button-5>", _wheel, add=True)
2483
+
2484
+ vsb.pack(side="right", fill="y")
2485
+ canvas.pack(side="left", fill="both", expand=True)
2486
+ canvas.configure(yscrollcommand=vsb.set)
2487
+
2488
+ self._render_all_sections(cf, sections, colors)
2489
+
2490
+ win.bind("<Escape>", lambda _: self.hide())
2491
+
2492
+ @staticmethod
2493
+ def _position_window(win: tk.Toplevel, screen_x: int, screen_y: int) -> None:
2494
+ """Posiciona o balloon próximo ao cursor, evitando sair da tela."""
2495
+ win.update_idletasks()
2496
+ sw = win.winfo_screenwidth()
2497
+ sh = win.winfo_screenheight()
2498
+ rw = win.winfo_reqwidth()
2499
+ rh = win.winfo_reqheight()
2500
+ x = screen_x + 12
2501
+ y = screen_y + 4
2502
+ if x + rw > sw - 10:
2503
+ x = max(4, screen_x - rw - 12)
2504
+ if y + rh > sh - 40:
2505
+ y = max(4, screen_y - rh - 4)
2506
+ win.geometry(f"+{x}+{y}")
2507
+
2508
+ def _start_mouse_poll(self) -> None:
2509
+ """Inicia polling periódico para detectar quando o mouse saiu da área."""
2510
+ self._stop_mouse_poll()
2511
+ self._poll_mouse()
2512
+
2513
+ def _stop_mouse_poll(self) -> None:
2514
+ if self._poll_job and self._anchor:
2515
+ with contextlib.suppress(tk.TclError):
2516
+ self._anchor.after_cancel(self._poll_job)
2517
+ self._poll_job = None
2518
+
2519
+ def _poll_mouse(self) -> None:
2520
+ """Verifica a cada 120 ms se o mouse ainda está sobre o balloon ou âncora."""
2521
+ if self._pinned or not self._win or not self._anchor:
2522
+ return
2523
+ with contextlib.suppress(tk.TclError, AttributeError):
2524
+ if not self._win.winfo_exists():
2525
+ return
2526
+ mx = self._win.winfo_pointerx()
2527
+ my = self._win.winfo_pointery()
2528
+ over_balloon = self._pointer_inside(self._win, mx, my)
2529
+ over_anchor = self._pointer_inside(self._anchor, mx, my)
2530
+ if over_balloon or over_anchor:
2531
+ self._cancel_job()
2532
+ self._poll_job = self._anchor.after(120, self._poll_mouse)
2533
+ else:
2534
+ self._stop_mouse_poll()
2535
+ self._job = self._anchor.after(350, self.hide)
2536
+
2537
+ @staticmethod
2538
+ def _pointer_inside(widget: tk.Widget, mx: int, my: int) -> bool:
2539
+ """True se o ponto (mx, my) está dentro do bounding box do widget."""
2540
+ try:
2541
+ wx = widget.winfo_rootx()
2542
+ wy = widget.winfo_rooty()
2543
+ ww = widget.winfo_width()
2544
+ wh = widget.winfo_height()
2545
+ return wx <= mx <= wx + ww and wy <= my <= wy + wh
2546
+ except tk.TclError:
2547
+ return False
2548
+
2549
+ def _cancel_job(self) -> None:
2550
+ """Cancela o after-job pendente de fechamento automático do balloon."""
2551
+ if self._job and self._anchor:
2552
+ with contextlib.suppress(tk.TclError):
2553
+ self._anchor.after_cancel(self._job)
2554
+ self._job = None
2555
+
2556
+ def _schedule_hide(self, delay: int = 500) -> None:
2557
+ """Agenda fechamento após delay ms."""
2558
+ self._cancel_job()
2559
+ if self._anchor:
2560
+ self._job = self._anchor.after(delay, self.hide)
2561
+
2562
+ def _extract_theme_colors(self) -> dict[str, Any]:
2563
+ """Extrai e retorna as cores do tema ativo para uso no balloon de documentação."""
2564
+ t = self._theme
2565
+
2566
+ def _g(names, default):
2567
+ for n in [names] if isinstance(names, str) else names:
2568
+ v = getattr(t, n, None)
2569
+ if isinstance(v, str):
2570
+ return v
2571
+ return default
2572
+
2573
+ colors = {
2574
+ "bg": _g(["floating_bg", "editor_bg"], "#1e1e2e"),
2575
+ "fg": _g("fg", "#cdd6f4"),
2576
+ "muted": _g("fg_muted", "#a6adc8"),
2577
+ "dim": _g("fg_dim", "#6c7086"),
2578
+ "sel": _g("sel_bg", "#313244"),
2579
+ "acc": _g("t_func", "#89b4fa"),
2580
+ "kw": _g("t_keyword", "#cba6f7"),
2581
+ "typ": _g("t_type", "#89dceb"),
2582
+ "str_": _g("t_string", "#a6e3a1"),
2583
+ "mono": _g("font_mono", "Consolas"),
2584
+ "ui": _g("font_ui", "Segoe UI"),
2585
+ }
2586
+
2587
+ colors["fg_dim"] = colors["dim"]
2588
+ colors["vp_borda"] = colors["sel"]
2589
+ return colors
2590
+
2591
+ def _render_all_sections(
2592
+ self, parent: tk.Widget, sections: list[dict], colors: dict
2593
+ ) -> None:
2594
+ renderers = {
2595
+ "title": self._render_title,
2596
+ "type_definition": self._render_type_definition,
2597
+ "deprecated": self._render_badge,
2598
+ "desc": self._render_desc,
2599
+ "remarks": self._render_remarks,
2600
+ "params": self._render_params,
2601
+ "template": self._render_template,
2602
+ "returns": self._render_returns,
2603
+ "throws": self._render_throws,
2604
+ "example": self._render_example,
2605
+ "type": self._render_type,
2606
+ "meta": self._render_meta,
2607
+ "kdocs_title": self._render_kdocs_title,
2608
+ "sep": self._render_separator,
2609
+ "source_label": self._render_source_label,
2610
+ }
2611
+ for section in sections:
2612
+ fn = renderers.get(section.get("kind", ""))
2613
+ if fn:
2614
+ fn(parent, section, colors)
2615
+
2616
+ @staticmethod
2617
+ def _render_title(parent: tk.Widget, section: dict, colors: dict) -> None:
2618
+ row = tk.Frame(parent, bg=colors["bg"])
2619
+ row.pack(fill="x", pady=(0, 4))
2620
+
2621
+ src = section.get("source", "jsdoc")
2622
+
2623
+ _lang_colors: dict[str, str] = {
2624
+ "python": "#3572a5",
2625
+ "rust": "#dea584",
2626
+ "go": "#00add8",
2627
+ "javascript": "#f7df1e",
2628
+ "typescript": "#3178c6",
2629
+ "ruby": "#cc342d",
2630
+ "kotlin": "#a97bff",
2631
+ "swift": "#f05138",
2632
+ "java": "#b07219",
2633
+ "lua": "#000080",
2634
+ "php": "#4f5d95",
2635
+ "dart": "#00b4ab",
2636
+ "elixir": "#6e4a7e",
2637
+ "csharp": "#178600",
2638
+ "cpp": "#f34b7d",
2639
+ "c": "#555555",
2640
+ "r": "#198ce7",
2641
+ "haskell": "#5e5086",
2642
+ "julia": "#a270ba",
2643
+ "lsp": "#89b4fa",
2644
+ "jsdoc": "#cba6f7",
2645
+ }
2646
+ src_lower = src.lower()
2647
+ src_color = _lang_colors.get(src_lower, "#cba6f7")
2648
+ label = (
2649
+ src.upper()[:6]
2650
+ if src not in ("lsp", "jsdoc")
2651
+ else ("LSP" if src == "lsp" else "Doc")
2652
+ )
2653
+ tk.Label(
2654
+ row,
2655
+ text=label,
2656
+ bg=src_color,
2657
+ fg="#1e1e2e",
2658
+ font=(colors["ui"], 7, "bold"),
2659
+ padx=4,
2660
+ pady=1,
2661
+ ).pack(side="left", padx=(0, 6))
2662
+
2663
+ for mod in section.get("modifiers", []):
2664
+ tk.Label(
2665
+ row,
2666
+ text=mod,
2667
+ bg=colors["sel"],
2668
+ fg=colors["muted"],
2669
+ font=(colors["ui"], 8, "italic"),
2670
+ padx=3,
2671
+ ).pack(side="left", padx=2)
2672
+
2673
+ tk.Label(
2674
+ row,
2675
+ text=section.get("symbol", ""),
2676
+ bg=colors["bg"],
2677
+ fg=colors["acc"],
2678
+ font=(colors["mono"], 10, "bold"),
2679
+ ).pack(side="left")
2680
+
2681
+ tpl = section.get("tpl_params", [])
2682
+ if tpl:
2683
+ tk.Label(
2684
+ row,
2685
+ text=f"<{', '.join(tpl)}>",
2686
+ bg=colors["bg"],
2687
+ fg=colors["typ"],
2688
+ font=(colors["mono"], 9),
2689
+ ).pack(side="left")
2690
+
2691
+ ret_type = section.get("ret_type", "")
2692
+ type_tag = section.get("type_tag", "")
2693
+ if ret_type:
2694
+ tk.Label(
2695
+ row,
2696
+ text=_t("hc.kdocs.arrow_sep"),
2697
+ bg=colors["bg"],
2698
+ fg=colors["dim"],
2699
+ font=(colors["mono"], 9),
2700
+ ).pack(side="left")
2701
+ tk.Label(
2702
+ row,
2703
+ text=ret_type,
2704
+ bg=colors["bg"],
2705
+ fg=colors["typ"],
2706
+ font=(colors["mono"], 9),
2707
+ ).pack(side="left")
2708
+ elif type_tag:
2709
+ tk.Label(
2710
+ row,
2711
+ text=f": {type_tag}",
2712
+ bg=colors["bg"],
2713
+ fg=colors["typ"],
2714
+ font=(colors["mono"], 9),
2715
+ ).pack(side="left")
2716
+
2717
+ @staticmethod
2718
+ def _render_type_definition(parent: tk.Widget, section: dict, colors: dict) -> None:
2719
+ frame = tk.Frame(parent, bg=colors["bg"])
2720
+ frame.pack(fill="x", pady=(0, 4))
2721
+ badge = tk.Frame(frame, bg=colors["typ"], padx=4, pady=1)
2722
+ badge.pack(side="left", padx=(0, 6))
2723
+ tk.Label(
2724
+ badge,
2725
+ text=_t("hc.kdocs.tipo"),
2726
+ bg=colors["typ"],
2727
+ fg=colors["bg"],
2728
+ font=(colors["ui"], 7, "bold"),
2729
+ ).pack()
2730
+ tk.Label(
2731
+ frame,
2732
+ text=section.get("type_name", ""),
2733
+ bg=colors["bg"],
2734
+ fg=colors["acc"],
2735
+ font=(colors["mono"], 9, "bold"),
2736
+ ).pack(side="left", padx=(0, 6))
2737
+ desc = section.get("description", "")
2738
+ if desc:
2739
+ tk.Label(
2740
+ frame,
2741
+ text=desc,
2742
+ bg=colors["bg"],
2743
+ fg=colors["fg"],
2744
+ font=(colors["ui"], 9),
2745
+ anchor="w",
2746
+ wraplength=350,
2747
+ ).pack(side="left")
2748
+
2749
+ def _render_kdocs_title(
2750
+ self, parent: tk.Widget, section: dict, colors: dict
2751
+ ) -> None:
2752
+ row = tk.Frame(parent, bg=colors["bg"])
2753
+ row.pack(fill="x", pady=(0, 6))
2754
+
2755
+ badge_color = section.get("color", "#89b4fa")
2756
+ badge = tk.Frame(row, bg=badge_color, padx=6, pady=2)
2757
+ badge.pack(side="left", padx=(0, 8))
2758
+ lbl_text = (
2759
+ f"{section.get('icon', '📌')} @kdocs:{section.get('kind_name', 'note')}"
2760
+ )
2761
+ tk.Label(
2762
+ badge,
2763
+ text=lbl_text,
2764
+ bg=badge_color,
2765
+ fg="#1e1e2e",
2766
+ font=(colors["mono"], 9, "bold"),
2767
+ ).pack()
2768
+
2769
+ priority = section.get("priority", 0)
2770
+ if priority >= 3:
2771
+ self._priority_badge(row, "CRÍTICA", "#f38ba8", colors)
2772
+ elif priority == 2:
2773
+ self._priority_badge(row, "ALTA", "#fab387", colors)
2774
+ elif priority == 1:
2775
+ self._priority_badge(row, "NORMAL", "#f9e2af", colors)
2776
+
2777
+ assignee = section.get("assignee", "")
2778
+ if assignee:
2779
+ tk.Label(
2780
+ row,
2781
+ text=f"@{assignee}",
2782
+ bg=colors["bg"],
2783
+ fg=colors["acc"],
2784
+ font=(colors["ui"], 8),
2785
+ ).pack(side="left", padx=(0, 4))
2786
+
2787
+ for tag in section.get("tags", [])[:4]:
2788
+ tb = tk.Frame(row, bg=colors["sel"], padx=3)
2789
+ tb.pack(side="left", padx=2)
2790
+ tk.Label(
2791
+ tb,
2792
+ text=f"#{tag}",
2793
+ bg=colors["sel"],
2794
+ fg=colors["muted"],
2795
+ font=(colors["ui"], 7),
2796
+ ).pack()
2797
+
2798
+ due = section.get("due_date", "")
2799
+ if due:
2800
+ tk.Label(
2801
+ row,
2802
+ text=f"📅 {due}",
2803
+ bg=colors["bg"],
2804
+ fg=colors["dim"],
2805
+ font=(colors["ui"], 7),
2806
+ ).pack(side="left", padx=(6, 0))
2807
+ ticket = section.get("ticket", "")
2808
+ if ticket:
2809
+ tk.Label(
2810
+ row,
2811
+ text=f"🎫 {ticket}",
2812
+ bg=colors["bg"],
2813
+ fg=colors["dim"],
2814
+ font=(colors["ui"], 7),
2815
+ ).pack(side="left", padx=(4, 0))
2816
+
2817
+ @staticmethod
2818
+ def _priority_badge(parent: tk.Frame, text: str, color: str, colors: dict) -> None:
2819
+ pb = tk.Frame(parent, bg=color, padx=4, pady=1)
2820
+ pb.pack(side="left", padx=(0, 4))
2821
+ tk.Label(
2822
+ pb, text=text, bg=color, fg="#1e1e2e", font=(colors["ui"], 7, "bold")
2823
+ ).pack()
2824
+
2825
+ @staticmethod
2826
+ def _render_badge(parent: tk.Widget, section: dict, colors: dict) -> None:
2827
+ for line in section.get("lines", []):
2828
+ f = tk.Frame(parent, bg="#3d2228", pady=2, padx=4)
2829
+ f.pack(fill="x", pady=2)
2830
+ tk.Label(
2831
+ f,
2832
+ text=line,
2833
+ bg="#3d2228",
2834
+ fg="#f38ba8",
2835
+ font=(colors["ui"], 9, "bold"),
2836
+ anchor="w",
2837
+ ).pack(anchor="w")
2838
+
2839
+ @staticmethod
2840
+ def _render_desc(parent: tk.Widget, section: dict, colors: dict) -> None:
2841
+ text = "\n".join(section.get("lines", []))
2842
+ tk.Label(
2843
+ parent,
2844
+ text=text,
2845
+ bg=colors["bg"],
2846
+ fg=colors["fg"],
2847
+ font=(colors["ui"], 9),
2848
+ justify="left",
2849
+ anchor="w",
2850
+ wraplength=440,
2851
+ ).pack(anchor="w", pady=(0, 2))
2852
+
2853
+ @staticmethod
2854
+ def _render_remarks(parent: tk.Widget, section: dict, colors: dict) -> None:
2855
+ text = "\n".join(section.get("lines", []))
2856
+ tk.Label(
2857
+ parent,
2858
+ text=text,
2859
+ bg=colors["sel"],
2860
+ fg=colors["muted"],
2861
+ font=(colors["ui"], 9, "italic"),
2862
+ justify="left",
2863
+ anchor="w",
2864
+ wraplength=440,
2865
+ padx=6,
2866
+ pady=3,
2867
+ ).pack(fill="x", pady=(0, 2))
2868
+
2869
+ @staticmethod
2870
+ def _render_params(parent: tk.Widget, section: dict, colors: dict) -> None:
2871
+ hdr = tk.Frame(parent, bg=colors["bg"])
2872
+ hdr.pack(fill="x", pady=(0, 2))
2873
+ tk.Label(
2874
+ hdr,
2875
+ text=_t("hc.kdocs.par_metros"),
2876
+ bg=colors["bg"],
2877
+ fg=colors["muted"],
2878
+ font=(colors["ui"], 8, "bold"),
2879
+ anchor="w",
2880
+ ).pack(anchor="w")
2881
+
2882
+ for row in section.get("rows", []):
2883
+ r = tk.Frame(parent, bg=colors["bg"])
2884
+ r.pack(fill="x", padx=4, pady=1)
2885
+
2886
+ name = row.get("name", "")
2887
+ if row.get("optional"):
2888
+ name += "?"
2889
+ tk.Label(
2890
+ r,
2891
+ text=name,
2892
+ bg=colors["bg"],
2893
+ fg=colors["acc"],
2894
+ font=(colors["mono"], 9),
2895
+ width=14,
2896
+ anchor="w",
2897
+ ).pack(side="left")
2898
+
2899
+ typ = row.get("type", "")
2900
+ if typ:
2901
+ pill = tk.Frame(r, bg=colors["sel"], padx=4)
2902
+ pill.pack(side="left", padx=(0, 6))
2903
+ tk.Label(
2904
+ pill,
2905
+ text=typ[:32],
2906
+ bg=colors["sel"],
2907
+ fg=colors["typ"],
2908
+ font=(colors["mono"], 8),
2909
+ ).pack()
2910
+
2911
+ desc = row.get("desc", "")
2912
+ if row.get("default") is not None:
2913
+ desc += f" (padrão: {row['default']})"
2914
+ tk.Label(
2915
+ r,
2916
+ text=desc,
2917
+ bg=colors["bg"],
2918
+ fg=colors["fg"],
2919
+ font=(colors["ui"], 9),
2920
+ anchor="w",
2921
+ wraplength=270,
2922
+ justify="left",
2923
+ ).pack(side="left", fill="x")
2924
+
2925
+ @staticmethod
2926
+ def _render_template(parent: tk.Widget, section: dict, colors: dict) -> None:
2927
+ hdr = tk.Frame(parent, bg=colors["bg"])
2928
+ hdr.pack(fill="x", pady=(0, 2))
2929
+ tk.Label(
2930
+ hdr,
2931
+ text=_t("hc.kdocs.par_metros_de_tipo"),
2932
+ bg=colors["bg"],
2933
+ fg=colors["muted"],
2934
+ font=(colors["ui"], 8, "bold"),
2935
+ anchor="w",
2936
+ ).pack(anchor="w")
2937
+ for row in section.get("rows", []):
2938
+ r = tk.Frame(parent, bg=colors["bg"])
2939
+ r.pack(fill="x", padx=4, pady=1)
2940
+ tk.Label(
2941
+ r,
2942
+ text=row.get("name", ""),
2943
+ bg=colors["bg"],
2944
+ fg=colors["kw"],
2945
+ font=(colors["mono"], 9),
2946
+ width=14,
2947
+ anchor="w",
2948
+ ).pack(side="left")
2949
+ tk.Label(
2950
+ r,
2951
+ text=row.get("desc", ""),
2952
+ bg=colors["bg"],
2953
+ fg=colors["fg"],
2954
+ font=(colors["ui"], 9),
2955
+ anchor="w",
2956
+ ).pack(side="left")
2957
+
2958
+ @staticmethod
2959
+ def _render_returns(parent: tk.Widget, section: dict, colors: dict) -> None:
2960
+ label = _t("hc.kdocs.produz") if section.get("yields") else "Retorna"
2961
+ typ = section.get("type", "")
2962
+ desc = section.get("desc", "")
2963
+ r = tk.Frame(parent, bg=colors["bg"])
2964
+ r.pack(fill="x", pady=(0, 2))
2965
+ tk.Label(
2966
+ r,
2967
+ text=label,
2968
+ bg=colors["bg"],
2969
+ fg=colors["muted"],
2970
+ font=(colors["ui"], 8, "bold"),
2971
+ width=10,
2972
+ anchor="w",
2973
+ ).pack(side="left")
2974
+ if typ:
2975
+ pill = tk.Frame(r, bg=colors["sel"], padx=4)
2976
+ pill.pack(side="left", padx=(0, 6))
2977
+ tk.Label(
2978
+ pill,
2979
+ text=typ[:40],
2980
+ bg=colors["sel"],
2981
+ fg=colors["typ"],
2982
+ font=(colors["mono"], 8),
2983
+ ).pack()
2984
+ if desc:
2985
+ tk.Label(
2986
+ r,
2987
+ text=desc,
2988
+ bg=colors["bg"],
2989
+ fg=colors["fg"],
2990
+ font=(colors["ui"], 9),
2991
+ anchor="w",
2992
+ wraplength=290,
2993
+ justify="left",
2994
+ ).pack(side="left")
2995
+
2996
+ @staticmethod
2997
+ def _render_throws(parent: tk.Widget, section: dict, colors: dict) -> None:
2998
+ hdr = tk.Frame(parent, bg=colors["bg"])
2999
+ hdr.pack(fill="x", pady=(0, 2))
3000
+ tk.Label(
3001
+ hdr,
3002
+ text=_t("hc.kdocs.lan_amentos"),
3003
+ bg=colors["bg"],
3004
+ fg="#f38ba8",
3005
+ font=(colors["ui"], 8, "bold"),
3006
+ anchor="w",
3007
+ ).pack(anchor="w")
3008
+ for row in section.get("rows", []):
3009
+ r = tk.Frame(parent, bg=colors["bg"])
3010
+ r.pack(fill="x", padx=4, pady=1)
3011
+ typ = row.get("type", "")
3012
+ if typ:
3013
+ pill = tk.Frame(r, bg="#3d2228", padx=4)
3014
+ pill.pack(side="left", padx=(0, 6))
3015
+ tk.Label(
3016
+ pill,
3017
+ text=typ[:30],
3018
+ bg="#3d2228",
3019
+ fg="#f38ba8",
3020
+ font=(colors["mono"], 8),
3021
+ ).pack()
3022
+ tk.Label(
3023
+ r,
3024
+ text=row.get("desc", ""),
3025
+ bg=colors["bg"],
3026
+ fg=colors["fg"],
3027
+ font=(colors["ui"], 9),
3028
+ anchor="w",
3029
+ wraplength=310,
3030
+ justify="left",
3031
+ ).pack(side="left")
3032
+
3033
+ def _render_example(self, parent: tk.Widget, section: dict, colors: dict) -> None:
3034
+ hdr = tk.Frame(parent, bg=colors["bg"])
3035
+ hdr.pack(fill="x", pady=(0, 2))
3036
+ tk.Label(
3037
+ hdr,
3038
+ text=_t("hc.kdocs.exemplo"),
3039
+ bg=colors["bg"],
3040
+ fg=colors["muted"],
3041
+ font=(colors["ui"], 8, "bold"),
3042
+ anchor="w",
3043
+ ).pack(anchor="w")
3044
+ code_bg = getattr(self._theme, "gutter_bg", "#181825")
3045
+ code = tk.Frame(parent, bg=code_bg, padx=8, pady=4)
3046
+ code.pack(fill="x", pady=2)
3047
+ text = "\n".join(section.get("lines", [])[:25])
3048
+ tk.Label(
3049
+ code,
3050
+ text=text,
3051
+ bg=code_bg,
3052
+ fg=colors["str_"],
3053
+ font=(colors["mono"], 8),
3054
+ justify="left",
3055
+ anchor="w",
3056
+ ).pack(anchor="w")
3057
+
3058
+ @staticmethod
3059
+ def _render_type(parent: tk.Widget, section: dict, colors: dict) -> None:
3060
+ r = tk.Frame(parent, bg=colors["bg"])
3061
+ r.pack(fill="x", pady=(0, 2))
3062
+ tk.Label(
3063
+ r,
3064
+ text=_t("hc.kdocs.tipo_2"),
3065
+ bg=colors["bg"],
3066
+ fg=colors["muted"],
3067
+ font=(colors["ui"], 8, "bold"),
3068
+ ).pack(side="left")
3069
+ pill = tk.Frame(r, bg=colors["sel"], padx=4)
3070
+ pill.pack(side="left")
3071
+ tk.Label(
3072
+ pill,
3073
+ text=section.get("type", "")[:50],
3074
+ bg=colors["sel"],
3075
+ fg=colors["typ"],
3076
+ font=(colors["mono"], 9),
3077
+ ).pack()
3078
+
3079
+ @staticmethod
3080
+ def _render_meta(parent: tk.Widget, section: dict, colors: dict) -> None:
3081
+ for line in section.get("lines", []):
3082
+ tk.Label(
3083
+ parent,
3084
+ text=line,
3085
+ bg=colors["bg"],
3086
+ fg=colors["dim"],
3087
+ font=(colors["ui"], 8),
3088
+ anchor="w",
3089
+ ).pack(anchor="w")
3090
+
3091
+ @staticmethod
3092
+ @staticmethod
3093
+ def _render_source_label(parent: tk.Widget, section: dict, colors: dict) -> None:
3094
+ """Renderiza um rótulo de separação de fonte (LSP / KDocs / JSDoc).
3095
+
3096
+ Exibido como uma linha fina + badge colorido indicando a origem
3097
+ das seções que se seguem - permite identificar visualmente de onde
3098
+ vem cada bloco de documentação no balloon unificado.
3099
+ """
3100
+ label = section.get("label", "")
3101
+ if not label:
3102
+ return
3103
+
3104
+ source_colors: dict[str, str] = {
3105
+ "LSP": "#7c4dff",
3106
+ "KDocs": "#ff6d00",
3107
+ "JSDoc": "#00bfa5",
3108
+ }
3109
+ badge_color = source_colors.get(label, colors["acc"])
3110
+
3111
+ frame = tk.Frame(parent, bg=colors["bg"])
3112
+ frame.pack(fill="x", pady=(6, 2))
3113
+
3114
+ tk.Frame(frame, bg=colors["dim"], height=1, width=12).pack(
3115
+ side="left", anchor="center", padx=(0, 4), pady=4
3116
+ )
3117
+
3118
+ badge = tk.Label(
3119
+ frame,
3120
+ text=f" {label} ",
3121
+ bg=badge_color,
3122
+ fg="#ffffff",
3123
+ font=("Segoe UI", 7, "bold"),
3124
+ padx=3,
3125
+ pady=1,
3126
+ )
3127
+ badge.pack(side="left")
3128
+
3129
+ tk.Frame(frame, bg=colors["dim"], height=1).pack(
3130
+ side="left", fill="x", expand=True, anchor="center", pady=4, padx=(4, 0)
3131
+ )
3132
+
3133
+ @staticmethod
3134
+ def _render_separator(parent: tk.Widget, _: dict, colors: dict) -> None:
3135
+ tk.Frame(parent, bg=colors["dim"], height=1).pack(fill="x", pady=4)
3136
+
3137
+ def hide(self) -> None:
3138
+ """Oculta o balloon e cancela jobs/polls pendentes."""
3139
+ self._stop_mouse_poll()
3140
+ self._cancel_job()
3141
+ self._pinned = False
3142
+ if self._job and self._anchor:
3143
+ with contextlib.suppress(tk.TclError):
3144
+ self._anchor.after_cancel(self._job)
3145
+ self._job = None
3146
+ self._last_key = ()
3147
+ if self._win:
3148
+ with contextlib.suppress(tk.TclError):
3149
+ if self._win.winfo_exists():
3150
+ self._win.destroy()
3151
+ self._win = None
3152
+
3153
+ def is_visible(self) -> bool:
3154
+ """Retorna ``True`` se o popup estiver criado e visível na tela."""
3155
+ return bool(self._win) and self._win.winfo_exists()
3156
+
3157
+
3158
+ def kdocs_annotation_to_sections(ann: KDocsNotes) -> list[dict]:
3159
+ """
3160
+ Converte KDocsNotes em seções para o popup.
3161
+ Inclui os campos KDocs (due_date, ticket, url, body_lines).
3162
+ """
3163
+ sections: list[dict] = []
3164
+
3165
+ sections.append(
3166
+ {
3167
+ "kind": "kdocs_title",
3168
+ "icon": ann.icon,
3169
+ "kind_name": ann.kind,
3170
+ "color": ann.color,
3171
+ "priority": ann.priority,
3172
+ "assignee": ann.assignee,
3173
+ "tags": ann.tags,
3174
+ "due_date": ann.due_date,
3175
+ "ticket": ann.ticket,
3176
+ }
3177
+ )
3178
+
3179
+ body = ann.full_text.strip()
3180
+ if body:
3181
+ wrapped = textwrap.wrap(body, 72) or [body]
3182
+ sections.append({"kind": "desc", "lines": wrapped})
3183
+
3184
+ if ann.kind == "link" and ann.file_ref:
3185
+ ref = ann.file_ref + (f":{ann.line_ref}" if ann.line_ref else "")
3186
+ sections.append({"kind": "meta", "lines": [f"→ {ref}"]})
3187
+
3188
+ elif ann.kind == "see" and body:
3189
+ sections.append({"kind": "meta", "lines": [f"Veja também: {body}"]})
3190
+
3191
+ elif ann.kind == "type" and ann.type_name:
3192
+ sections.append({"kind": "type", "type": ann.type_name})
3193
+
3194
+ elif ann.kind == "param":
3195
+ alt = _parse_kdocs_param(ann, body)
3196
+ if alt:
3197
+ return alt
3198
+
3199
+ elif ann.kind in ("return", "returns"):
3200
+ alt = _parse_kdocs_return(ann, body)
3201
+ if alt:
3202
+ return alt
3203
+
3204
+ if ann.url:
3205
+ sections.append({"kind": "meta", "lines": [f"🔗 {ann.url}"]})
3206
+
3207
+ meta = _build_kdocs_meta(ann)
3208
+ if meta:
3209
+ if sections and sections[-1].get("kind") != "sep":
3210
+ sections.append({"kind": "sep"})
3211
+ sections.append({"kind": "meta", "lines": meta})
3212
+
3213
+ return sections
3214
+
3215
+
3216
+ def _parse_kdocs_param(ann: KDocsNotes, body: str) -> list[dict] | None:
3217
+ m = re.match(r"^\{([^}]+)\}\s*(\S+)?\s*[-–]?\s*(.*)", body)
3218
+ if m:
3219
+ return [
3220
+ {
3221
+ "kind": "kdocs_title",
3222
+ "icon": ann.icon,
3223
+ "kind_name": ann.kind,
3224
+ "color": ann.color,
3225
+ "priority": ann.priority,
3226
+ "assignee": ann.assignee,
3227
+ "tags": ann.tags,
3228
+ "due_date": ann.due_date,
3229
+ "ticket": ann.ticket,
3230
+ },
3231
+ {
3232
+ "kind": "params",
3233
+ "rows": [
3234
+ {
3235
+ "name": m.group(2) or "",
3236
+ "type": m.group(1) or "",
3237
+ "desc": (m.group(3) or "").strip(),
3238
+ "optional": False,
3239
+ "default": None,
3240
+ }
3241
+ ],
3242
+ },
3243
+ ]
3244
+ return None
3245
+
3246
+
3247
+ def _parse_kdocs_return(ann: KDocsNotes, body: str) -> list[dict] | None:
3248
+ m = re.match(r"^\{([^}]+)\}\s*(.*)", body)
3249
+ if m:
3250
+ return [
3251
+ {
3252
+ "kind": "kdocs_title",
3253
+ "icon": ann.icon,
3254
+ "kind_name": ann.kind,
3255
+ "color": ann.color,
3256
+ "priority": ann.priority,
3257
+ "assignee": ann.assignee,
3258
+ "tags": ann.tags,
3259
+ "due_date": ann.due_date,
3260
+ "ticket": ann.ticket,
3261
+ },
3262
+ {
3263
+ "kind": "returns",
3264
+ "type": m.group(1).strip(),
3265
+ "desc": m.group(2).strip(),
3266
+ "yields": False,
3267
+ },
3268
+ ]
3269
+ return None
3270
+
3271
+
3272
+ def _build_kdocs_meta(ann: KDocsNotes) -> list[str]:
3273
+ meta: list[str] = []
3274
+ if ann.assignee:
3275
+ meta.append(f"Responsável: @{ann.assignee}")
3276
+ if ann.tags:
3277
+ meta.append(f"Tags: {', '.join(ann.tags)}")
3278
+ if ann.priority == 3:
3279
+ meta.append("Prioridade: ⚠ CRÍTICA")
3280
+ elif ann.priority == 2:
3281
+ meta.append("Prioridade: ALTA")
3282
+ elif ann.priority == 1:
3283
+ meta.append("Prioridade: NORMAL")
3284
+ if ann.due_date:
3285
+ meta.append(f"Prazo: {ann.due_date}")
3286
+ if ann.ticket:
3287
+ meta.append(f"Ticket: {ann.ticket}")
3288
+ return meta
3289
+
3290
+
3291
+ def lsp_hover_to_sections(symbol: str, markdown: str) -> list[dict]:
3292
+ """
3293
+ Converte markdown do LSP em seções para o popup.
3294
+ """
3295
+ sections: list[dict] = [
3296
+ {
3297
+ "kind": "title",
3298
+ "symbol": symbol,
3299
+ "ret_type": "",
3300
+ "type_tag": "",
3301
+ "modifiers": [],
3302
+ "tpl_params": [],
3303
+ "source": "lsp",
3304
+ }
3305
+ ]
3306
+
3307
+ if not markdown:
3308
+ return sections
3309
+
3310
+ fence_re = re.compile(r"```(\w*)\n(.*?)```", re.DOTALL)
3311
+ last_end = 0
3312
+
3313
+ for match in fence_re.finditer(markdown):
3314
+ text_before = markdown[last_end: match.start()].strip()
3315
+ if text_before:
3316
+ lines = textwrap.wrap(text_before.replace(
3317
+ "\n", " "), 72) or [text_before]
3318
+ sections.append({"kind": "desc", "lines": lines})
3319
+ sections.append({"kind": "sep"})
3320
+ sections.append(
3321
+ {"kind": "example", "lines": match.group(2).splitlines()})
3322
+ sections.append({"kind": "sep"})
3323
+ last_end = match.end()
3324
+
3325
+ tail = markdown[last_end:].strip()
3326
+ if tail:
3327
+ lines = textwrap.wrap(tail.replace("\n", " "), 72) or [tail]
3328
+ sections.append({"kind": "desc", "lines": lines})
3329
+
3330
+ while sections and sections[-1].get("kind") == "sep":
3331
+ sections.pop()
3332
+
3333
+ return sections
3334
+
3335
+
3336
+ def find_definition_line(word: str, content: str, current_line: int) -> int | None:
3337
+ """
3338
+ Encontra a linha de definição de um símbolo.
3339
+ """
3340
+ if not word or not content:
3341
+ return None
3342
+ lines = content.splitlines()
3343
+ candidates: list[int] = []
3344
+ for i, line in enumerate(lines):
3345
+ if i + 1 == current_line:
3346
+ continue
3347
+ for pattern in _DEF_PATTERNS:
3348
+ if m := pattern.match(line):
3349
+ for g in m.groups():
3350
+ if g == word:
3351
+ candidates.append(i + 1)
3352
+ break
3353
+ if not candidates:
3354
+ return None
3355
+ before = [c for c in candidates if c < current_line]
3356
+ after = [c for c in candidates if c > current_line]
3357
+ if before:
3358
+ return max(before)
3359
+ return min(after) if after else None
3360
+
3361
+
3362
+ def find_all_usages(word: str, content: str) -> list[int]:
3363
+ """
3364
+ Encontra todas as ocorrências de um símbolo.
3365
+ """
3366
+ if not word or not content:
3367
+ return []
3368
+ pattern = re.compile(r"(?<![a-zA-Z0-9_$])" +
3369
+ re.escape(word) + r"(?![a-zA-Z0-9_$])")
3370
+ results: list[int] = []
3371
+ for i, line in enumerate(content.splitlines()):
3372
+ if pattern.search(line):
3373
+ results.append(i + 1)
3374
+ if len(results) >= _MAX_USAGES:
3375
+ break
3376
+ return results