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.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
src/extcompat/readers.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""Leitores de extensões: VS Code, Zed e Vim/Neovim. Só lê dados; nada é executado."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import tomllib
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from . import registry, textmate
|
|
11
|
+
from .common import (
|
|
12
|
+
MAX_FILE_BYTES,
|
|
13
|
+
lang_id,
|
|
14
|
+
parse_language_configuration,
|
|
15
|
+
parse_snippets,
|
|
16
|
+
read_bytes,
|
|
17
|
+
read_json,
|
|
18
|
+
)
|
|
19
|
+
from .jsonc import as_dict
|
|
20
|
+
from .model import CodeCommand, CodeInfo, Extension, LanguageSpec
|
|
21
|
+
from .registry import Format
|
|
22
|
+
from .themes import from_nvim_lua, from_vim, from_vscode, from_zed, slug
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"detect_kind", "lang_id", "load_vim", "load_vscode", "load_zed",
|
|
26
|
+
"parse_language_configuration", "parse_snippets", "read_extension",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
# Chaves de ``contributes`` que dependem de código ou de partes do VS Code que o Codis não tem.
|
|
30
|
+
_UNSUPPORTED = {
|
|
31
|
+
"commands": "comandos", "keybindings": "atalhos", "menus": "menus", "views": "painéis",
|
|
32
|
+
"viewsContainers": "contêineres de painéis", "debuggers": "adaptadores de depuração",
|
|
33
|
+
"taskDefinitions": "definições de tarefas", "customEditors": "editores customizados",
|
|
34
|
+
"problemMatchers": "problem matchers", "walkthroughs": "tutoriais",
|
|
35
|
+
"iconThemes": "temas de ícones de arquivo", "productIconThemes": "temas de ícones do produto",
|
|
36
|
+
"colors": "cores novas para o VS Code", "semanticTokenTypes": "tipos de token semântico",
|
|
37
|
+
"authentication": "autenticação", "notebooks": "notebooks", "terminal": "perfis de terminal",
|
|
38
|
+
"jsonValidation": "validação de JSON", "typescriptServerPlugins": "plugins do servidor TypeScript",
|
|
39
|
+
"languageModelTools": "ferramentas de modelo de linguagem", "chatParticipants": "participantes de chat",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _nls(root: Path) -> dict[str, str]:
|
|
44
|
+
data = read_json(root, "package.nls.json")
|
|
45
|
+
if not isinstance(data, dict):
|
|
46
|
+
return {}
|
|
47
|
+
return {k: (v.get("message", "") if isinstance(v, dict) else str(v)) for k, v in data.items()}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _resolve(value: Any, table: dict[str, str]) -> str:
|
|
51
|
+
text = str(value or "")
|
|
52
|
+
m = re.fullmatch(r"%([^%]+)%", text)
|
|
53
|
+
return table.get(m.group(1), m.group(1)) if m else text
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _vscode_theme(root: Path, rel: str, depth: int = 0) -> dict[str, Any] | None:
|
|
57
|
+
data = read_json(root, rel)
|
|
58
|
+
if not isinstance(data, dict):
|
|
59
|
+
return None
|
|
60
|
+
inc = data.get("include")
|
|
61
|
+
if isinstance(inc, str) and depth < 3:
|
|
62
|
+
base_rel = (Path(rel).parent / inc).as_posix()
|
|
63
|
+
base = _vscode_theme(root, base_rel, depth + 1)
|
|
64
|
+
if base:
|
|
65
|
+
merged = dict(base)
|
|
66
|
+
merged["colors"] = {**(base.get("colors") or {}), **(data.get("colors") or {})}
|
|
67
|
+
merged["tokenColors"] = [*(base.get("tokenColors") or []), *(data.get("tokenColors") or [])]
|
|
68
|
+
merged.update({k: v for k, v in data.items() if k not in ("colors", "tokenColors", "include")})
|
|
69
|
+
return merged
|
|
70
|
+
return data
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def load_vscode(root: Path, known: set[str]) -> Extension:
|
|
74
|
+
pkg = read_json(root, "package.json")
|
|
75
|
+
if not isinstance(pkg, dict):
|
|
76
|
+
raise ValueError("package.json ausente ou inválido")
|
|
77
|
+
nls = _nls(root)
|
|
78
|
+
name = str(pkg.get("name") or root.name)
|
|
79
|
+
publisher = str(pkg.get("publisher") or "local")
|
|
80
|
+
ext = Extension(
|
|
81
|
+
id=re.sub(r"[^a-z0-9._-]+", "-", f"{publisher}.{name}".lower()),
|
|
82
|
+
name=_resolve(pkg.get("displayName"), nls) or name,
|
|
83
|
+
version=str(pkg.get("version") or "0"),
|
|
84
|
+
kind="vscode",
|
|
85
|
+
path=root,
|
|
86
|
+
publisher=publisher,
|
|
87
|
+
description=_resolve(pkg.get("description"), nls),
|
|
88
|
+
)
|
|
89
|
+
contributes = as_dict(pkg.get("contributes"))
|
|
90
|
+
|
|
91
|
+
for entry in contributes.get("themes") or []:
|
|
92
|
+
if not isinstance(entry, dict) or not entry.get("path"):
|
|
93
|
+
continue
|
|
94
|
+
data = _vscode_theme(root, str(entry["path"]))
|
|
95
|
+
if data is None:
|
|
96
|
+
ext.warnings.append(f"tema ilegível: {entry.get('path')}")
|
|
97
|
+
continue
|
|
98
|
+
label = _resolve(entry.get("label"), nls) or Path(str(entry["path"])).stem
|
|
99
|
+
ext.themes.append(
|
|
100
|
+
from_vscode(
|
|
101
|
+
data, theme_id=f"{slug(name)}_{slug(label)}", name=label,
|
|
102
|
+
ui_theme=str(entry.get("uiTheme") or ""),
|
|
103
|
+
)
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
for entry in contributes.get("snippets") or []:
|
|
107
|
+
if isinstance(entry, dict) and entry.get("path") and entry.get("language"):
|
|
108
|
+
ext.snippets.extend(
|
|
109
|
+
parse_snippets(read_json(root, str(entry["path"])), lang_id(str(entry["language"])))
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
grammars: dict[str, list[dict[str, Any]]] = {}
|
|
113
|
+
for g in contributes.get("grammars") or []:
|
|
114
|
+
if isinstance(g, dict) and g.get("language") and g.get("path"):
|
|
115
|
+
grammars.setdefault(lang_id(str(g["language"])), []).append(g)
|
|
116
|
+
|
|
117
|
+
for entry in contributes.get("languages") or []:
|
|
118
|
+
if not isinstance(entry, dict) or not entry.get("id"):
|
|
119
|
+
continue
|
|
120
|
+
lid = lang_id(str(entry["id"]))
|
|
121
|
+
if lid in known:
|
|
122
|
+
ext.ignored.append(f"linguagem '{lid}' já existe no Codis (realce nativo mantido)")
|
|
123
|
+
continue
|
|
124
|
+
exts = [e if e.startswith(".") else f".{e}" for e in entry.get("extensions") or [] if isinstance(e, str)]
|
|
125
|
+
if entry.get("filenames"):
|
|
126
|
+
ext.warnings.append(f"'{lid}': nomes de arquivo sem extensão não são associados")
|
|
127
|
+
if not exts:
|
|
128
|
+
continue
|
|
129
|
+
aliases = entry.get("aliases")
|
|
130
|
+
label = str(aliases[0]) if isinstance(aliases, list) and aliases else lid
|
|
131
|
+
spec = LanguageSpec(id=lid, label=label, extensions=[e.lower() for e in exts])
|
|
132
|
+
if entry.get("configuration"):
|
|
133
|
+
conf = read_json(root, str(entry["configuration"]))
|
|
134
|
+
if isinstance(conf, dict):
|
|
135
|
+
spec.comment, spec.comment_block, spec.bracket_pairs = parse_language_configuration(conf)
|
|
136
|
+
for g in grammars.get(lid, [])[:1]:
|
|
137
|
+
raw = read_bytes(root, str(g["path"]))
|
|
138
|
+
if raw is None:
|
|
139
|
+
continue
|
|
140
|
+
try:
|
|
141
|
+
spec.patterns, spec.keywords = textmate.grammar_to_tokens(textmate.load_grammar(raw))
|
|
142
|
+
except Exception as exc:
|
|
143
|
+
ext.warnings.append(f"gramática de '{lid}' não pôde ser lida: {type(exc).__name__}")
|
|
144
|
+
ext.languages.append(spec)
|
|
145
|
+
|
|
146
|
+
for key, label in _UNSUPPORTED.items():
|
|
147
|
+
if contributes.get(key):
|
|
148
|
+
ext.ignored.append(label)
|
|
149
|
+
if pkg.get("main") or pkg.get("browser"):
|
|
150
|
+
ext.ignored.append("código JavaScript da extensão (só roda se a execução de código for liberada)")
|
|
151
|
+
ext.code = _vscode_code(root, pkg, nls)
|
|
152
|
+
if pkg.get("extensionPack"):
|
|
153
|
+
ext.ignored.append("pacote de extensões (instale cada uma separadamente)")
|
|
154
|
+
return ext
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _vscode_code(root: Path, pkg: dict[str, Any], nls: dict[str, str]) -> CodeInfo | None:
|
|
158
|
+
"""Entrada Node e comandos declarados, para quem liberar a execução de código."""
|
|
159
|
+
main = pkg.get("main")
|
|
160
|
+
if not isinstance(main, str) or not main:
|
|
161
|
+
return None
|
|
162
|
+
entry = main.removeprefix("./")
|
|
163
|
+
if not any(read_bytes(root, cand) is not None for cand in (entry, entry + ".js", entry + "/index.js")):
|
|
164
|
+
return None
|
|
165
|
+
commands = []
|
|
166
|
+
for item in as_dict(pkg.get("contributes")).get("commands") or []:
|
|
167
|
+
if isinstance(item, dict) and isinstance(item.get("command"), str):
|
|
168
|
+
title = _resolve(item.get("title"), nls) or item["command"]
|
|
169
|
+
commands.append(CodeCommand(item["command"], title, _resolve(item.get("category"), nls)))
|
|
170
|
+
return CodeInfo(runtime="node", entry=entry, commands=commands)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _scm_tokens(
|
|
174
|
+
scm: str, line_comments: list[str], block: tuple[str, str] | None
|
|
175
|
+
) -> tuple[list[tuple[str, str]], list[str]]:
|
|
176
|
+
"""Extrai de um ``highlights.scm`` do Tree-sitter só as palavras literais capturadas."""
|
|
177
|
+
buckets: dict[str, list[str]] = {}
|
|
178
|
+
for body, cap in re.findall(r'\[((?:\s*"[^"\n]*")+)\s*\]\s*@([\w.]+)', scm):
|
|
179
|
+
buckets.setdefault(cap, []).extend(re.findall(r'"([^"\n]*)"', body))
|
|
180
|
+
for word, cap in re.findall(r'(?m)^\s*"([^"\n]+)"\s*@([\w.]+)', scm):
|
|
181
|
+
buckets.setdefault(cap, []).append(word)
|
|
182
|
+
|
|
183
|
+
def regex_for(words: list[str]) -> str | None:
|
|
184
|
+
uniq = sorted({w for w in words if w and len(w) <= 40}, key=lambda w: (-len(w), w))
|
|
185
|
+
if not uniq:
|
|
186
|
+
return None
|
|
187
|
+
alt = "|".join(re.escape(w) for w in uniq)
|
|
188
|
+
return rf"\b(?:{alt})\b" if all(re.fullmatch(r"\w+", w) for w in uniq) else f"(?:{alt})"
|
|
189
|
+
|
|
190
|
+
tokens: list[tuple[str, str]] = []
|
|
191
|
+
keywords: list[str] = []
|
|
192
|
+
for prefix in line_comments:
|
|
193
|
+
p = prefix.strip()
|
|
194
|
+
if p:
|
|
195
|
+
tokens.append(("comment_line", re.escape(p) + r"[^\n]*"))
|
|
196
|
+
break
|
|
197
|
+
if block:
|
|
198
|
+
tokens.append(("comment_block", re.escape(block[0].strip()) + r"[\s\S]{0,8000}?" + re.escape(block[1].strip())))
|
|
199
|
+
if any(c.startswith("string") for c in buckets) or re.search(r"@string\b", scm):
|
|
200
|
+
tokens.append(("string", r'"(?:[^"\\\n]|\\.)*"|\'(?:[^\'\\\n]|\\.)*\''))
|
|
201
|
+
if re.search(r"@number\b", scm):
|
|
202
|
+
tokens.append(("number", r"\b\d[\d_]*(?:\.\d+)?\b"))
|
|
203
|
+
wanted = (
|
|
204
|
+
("keyword", ("keyword", "keyword.control", "keyword.function", "keyword.return", "conditional", "repeat", "include")),
|
|
205
|
+
("operator", ("operator",)),
|
|
206
|
+
("class_name", ("type", "type.builtin")),
|
|
207
|
+
("bool", ("constant.builtin", "boolean", "constant")),
|
|
208
|
+
("builtin", ("function.builtin", "variable.builtin")),
|
|
209
|
+
)
|
|
210
|
+
for tag, caps in wanted:
|
|
211
|
+
words = [w for c in caps for w in buckets.get(c, [])]
|
|
212
|
+
pattern = regex_for(words)
|
|
213
|
+
if pattern:
|
|
214
|
+
tokens.append((tag, pattern))
|
|
215
|
+
if tag in ("keyword", "bool", "builtin"):
|
|
216
|
+
keywords.extend(w for w in words if w.isidentifier())
|
|
217
|
+
return tokens, sorted(set(keywords))[:500]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def load_zed(root: Path, known: set[str]) -> Extension:
|
|
221
|
+
raw = read_bytes(root, "extension.toml")
|
|
222
|
+
if raw is None:
|
|
223
|
+
raise ValueError("extension.toml ausente")
|
|
224
|
+
meta = tomllib.loads(raw.decode("utf-8", errors="replace"))
|
|
225
|
+
ext_id = str(meta.get("id") or root.name)
|
|
226
|
+
ext = Extension(
|
|
227
|
+
id=re.sub(r"[^a-z0-9._-]+", "-", f"zed.{ext_id}".lower()), name=str(meta.get("name") or ext_id),
|
|
228
|
+
version=str(meta.get("version") or "0"), kind="zed", path=root,
|
|
229
|
+
publisher=", ".join(meta.get("authors") or []) if isinstance(meta.get("authors"), list) else "",
|
|
230
|
+
description=str(meta.get("description") or ""),
|
|
231
|
+
)
|
|
232
|
+
themes_dir = root / "themes"
|
|
233
|
+
if themes_dir.is_dir():
|
|
234
|
+
for f in sorted(themes_dir.glob("*.json")):
|
|
235
|
+
doc = read_json(root, f"themes/{f.name}")
|
|
236
|
+
if isinstance(doc, dict):
|
|
237
|
+
ext.themes.extend(from_zed(doc, prefix=f"zed_{slug(ext_id)}"))
|
|
238
|
+
else:
|
|
239
|
+
ext.warnings.append(f"tema ilegível: {f.name}")
|
|
240
|
+
snippets_dir = root / "snippets"
|
|
241
|
+
if snippets_dir.is_dir():
|
|
242
|
+
for f in sorted(snippets_dir.glob("*.json")):
|
|
243
|
+
ext.snippets.extend(parse_snippets(read_json(root, f"snippets/{f.name}"), lang_id(f.stem)))
|
|
244
|
+
langs_dir = root / "languages"
|
|
245
|
+
if langs_dir.is_dir():
|
|
246
|
+
for conf in sorted(langs_dir.glob("*/config.toml")):
|
|
247
|
+
try:
|
|
248
|
+
cfg = tomllib.loads(conf.read_text(encoding="utf-8", errors="replace"))
|
|
249
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
250
|
+
ext.warnings.append(f"linguagem ilegível: {conf.parent.name}")
|
|
251
|
+
continue
|
|
252
|
+
name = str(cfg.get("name") or conf.parent.name)
|
|
253
|
+
lid = lang_id(name)
|
|
254
|
+
if lid in known:
|
|
255
|
+
ext.ignored.append(f"linguagem '{lid}' já existe no Codis (realce nativo mantido)")
|
|
256
|
+
continue
|
|
257
|
+
suffixes = [f".{s.lstrip('.')}".lower() for s in cfg.get("path_suffixes") or [] if isinstance(s, str)]
|
|
258
|
+
if not suffixes:
|
|
259
|
+
continue
|
|
260
|
+
line_c = [c for c in cfg.get("line_comments") or [] if isinstance(c, str)]
|
|
261
|
+
bc = cfg.get("block_comment")
|
|
262
|
+
block = (str(bc[0]).strip(), str(bc[-1]).strip()) if isinstance(bc, list) and len(bc) >= 2 else None
|
|
263
|
+
brackets = [
|
|
264
|
+
(str(b["start"]), str(b["end"])) for b in cfg.get("brackets") or []
|
|
265
|
+
if isinstance(b, dict) and "start" in b and "end" in b
|
|
266
|
+
]
|
|
267
|
+
spec = LanguageSpec(
|
|
268
|
+
id=lid, label=name, extensions=suffixes,
|
|
269
|
+
comment=line_c[0].strip() if line_c else None, comment_block=block, bracket_pairs=brackets,
|
|
270
|
+
)
|
|
271
|
+
scm = conf.parent / "highlights.scm"
|
|
272
|
+
if scm.is_file() and scm.stat().st_size <= MAX_FILE_BYTES:
|
|
273
|
+
spec.patterns, spec.keywords = _scm_tokens(
|
|
274
|
+
scm.read_text(encoding="utf-8", errors="replace"), line_c, block
|
|
275
|
+
)
|
|
276
|
+
elif line_c or block:
|
|
277
|
+
spec.patterns, spec.keywords = _scm_tokens("", line_c, block)
|
|
278
|
+
ext.languages.append(spec)
|
|
279
|
+
for section, label in (
|
|
280
|
+
("grammars", "gramáticas Tree-sitter (WASM)"),
|
|
281
|
+
("language_servers", "servidores de linguagem"),
|
|
282
|
+
("context_servers", "servidores de contexto"),
|
|
283
|
+
("slash_commands", "comandos de barra"),
|
|
284
|
+
("indexed_docs_providers", "provedores de documentação"),
|
|
285
|
+
):
|
|
286
|
+
if meta.get(section):
|
|
287
|
+
ext.ignored.append(label)
|
|
288
|
+
return ext
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def load_vim(path: Path) -> Extension:
|
|
292
|
+
"""Esquema de cores avulso (``.vim``/``.lua``) ou pasta com ``colors/``."""
|
|
293
|
+
files: list[Path]
|
|
294
|
+
if path.is_file():
|
|
295
|
+
files, base = [path], path.stem
|
|
296
|
+
else:
|
|
297
|
+
files = sorted([*path.glob("colors/*.vim"), *path.glob("colors/*.lua")])[:60]
|
|
298
|
+
base = path.name
|
|
299
|
+
ext = Extension(id=f"vim.{slug(base)}", name=base, version="0", kind="vim", path=path)
|
|
300
|
+
for f in files:
|
|
301
|
+
try:
|
|
302
|
+
if f.stat().st_size > MAX_FILE_BYTES:
|
|
303
|
+
continue
|
|
304
|
+
text = f.read_text(encoding="utf-8", errors="replace")
|
|
305
|
+
except OSError:
|
|
306
|
+
continue
|
|
307
|
+
theme_id = f"vim_{slug(f.stem)}"
|
|
308
|
+
spec = (from_nvim_lua if f.suffix == ".lua" else from_vim)(text, theme_id=theme_id, name=f.stem)
|
|
309
|
+
if spec is None:
|
|
310
|
+
ext.warnings.append(f"{f.name}: nenhuma cor literal encontrada")
|
|
311
|
+
else:
|
|
312
|
+
ext.themes.append(spec)
|
|
313
|
+
return ext
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _is_vscode(path: Path) -> bool:
|
|
317
|
+
return (path / "package.json").is_file()
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _is_zed(path: Path) -> bool:
|
|
321
|
+
return (path / "extension.toml").is_file()
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _is_vim(path: Path) -> bool:
|
|
325
|
+
return any((path / "colors").glob("*.vim")) or any((path / "colors").glob("*.lua"))
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
registry.register(Format(
|
|
329
|
+
"vscode", "VS Code", _is_vscode, lambda p, k: load_vscode(p, k), priority=20,
|
|
330
|
+
suffixes=(".vsix",), provides="temas, snippets, linguagens e gramáticas",
|
|
331
|
+
))
|
|
332
|
+
registry.register(Format(
|
|
333
|
+
"zed", "Zed", _is_zed, lambda p, k: load_zed(p, k), priority=21,
|
|
334
|
+
provides="temas, snippets e linguagens",
|
|
335
|
+
))
|
|
336
|
+
registry.register(Format(
|
|
337
|
+
"vim", "Vim/Neovim", _is_vim, lambda p, k: load_vim(p), priority=90,
|
|
338
|
+
suffixes=(".vim", ".lua"), provides="esquemas de cores",
|
|
339
|
+
))
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def detect_kind(path: Path) -> str | None:
|
|
343
|
+
"""Tipo da extensão na pasta (ou no arquivo avulso) dada, ou ``None`` se não for reconhecida."""
|
|
344
|
+
fmt = registry.detect(path)
|
|
345
|
+
return fmt.kind if fmt else None
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def read_extension(path: Path, known: set[str]) -> Extension:
|
|
349
|
+
fmt = registry.detect(path)
|
|
350
|
+
if fmt is None:
|
|
351
|
+
raise ValueError(
|
|
352
|
+
"formato não reconhecido (esperado: extensão ou tema de VS Code, Zed, Vim/Neovim, "
|
|
353
|
+
"Sublime Text, JetBrains, Emacs, Eclipse, Pulsar/Atom, Brackets, IDLE ou Thonny)"
|
|
354
|
+
)
|
|
355
|
+
ext = fmt.load(path, known)
|
|
356
|
+
if ext.empty and fmt.kind != "generic":
|
|
357
|
+
# O formato foi reconhecido mas não rendeu nada (tema montado por funções, por exemplo):
|
|
358
|
+
# a leitura heurística ainda pode achar as cores.
|
|
359
|
+
generic = registry.get("generic")
|
|
360
|
+
if generic is not None and generic.detect(path):
|
|
361
|
+
return generic.load(path, known)
|
|
362
|
+
return ext
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Registro dos formatos de extensão conhecidos.
|
|
2
|
+
|
|
3
|
+
Cada formato (VS Code, Sublime, JetBrains...) se registra com uma função que reconhece a pasta
|
|
4
|
+
e outra que a lê e devolve um ``Extension``. Adicionar um formato novo não exige mexer no
|
|
5
|
+
instalador nem no diálogo: basta registrar.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from .model import Extension
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Format:
|
|
19
|
+
kind: str
|
|
20
|
+
label: str
|
|
21
|
+
detect: Callable[[Path], bool]
|
|
22
|
+
load: Callable[[Path, set[str]], Extension]
|
|
23
|
+
# Quanto menor, mais cedo o formato é testado (o ``package.json`` do VS Code, do Atom e do
|
|
24
|
+
# Brackets é o mesmo nome de arquivo, então os mais específicos precisam vir antes).
|
|
25
|
+
priority: int = 50
|
|
26
|
+
# Sufixos de arquivo avulso que o instalador aceita (``.vim``, ``.tmtheme``...).
|
|
27
|
+
suffixes: tuple[str, ...] = ()
|
|
28
|
+
# Do que se trata, para o texto do diálogo.
|
|
29
|
+
provides: str = ""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_FORMATS: dict[str, Format] = {}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def register(fmt: Format) -> Format:
|
|
36
|
+
_FORMATS[fmt.kind] = fmt
|
|
37
|
+
return fmt
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def formats() -> list[Format]:
|
|
41
|
+
return sorted(_FORMATS.values(), key=lambda f: (f.priority, f.kind))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def get(kind: str) -> Format | None:
|
|
45
|
+
return _FORMATS.get(kind)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def label(kind: str) -> str:
|
|
49
|
+
fmt = _FORMATS.get(kind)
|
|
50
|
+
return fmt.label if fmt else kind
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def detect(path: Path) -> Format | None:
|
|
54
|
+
"""Formato da pasta (ou do arquivo avulso, quando o sufixo basta para saber)."""
|
|
55
|
+
if path.is_file():
|
|
56
|
+
name = path.name.lower()
|
|
57
|
+
return next((f for f in formats() if any(name.endswith(s) for s in f.suffixes)), None)
|
|
58
|
+
for fmt in formats():
|
|
59
|
+
try:
|
|
60
|
+
if fmt.detect(path):
|
|
61
|
+
return fmt
|
|
62
|
+
except OSError:
|
|
63
|
+
continue
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def file_suffixes() -> list[str]:
|
|
68
|
+
"""Todos os sufixos de arquivo avulso aceitos, sem repetição e em ordem estável."""
|
|
69
|
+
seen: dict[str, None] = {}
|
|
70
|
+
for fmt in formats():
|
|
71
|
+
for suffix in fmt.suffixes:
|
|
72
|
+
seen.setdefault(suffix)
|
|
73
|
+
return list(seen)
|
src/extcompat/safexml.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Leitura de XML de terceiros sem entidades declaradas (proteção contra expansão de entidades)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import xml.etree.ElementTree as ET # noqa: S405 - entradas com ENTITY são recusadas antes de ler
|
|
7
|
+
|
|
8
|
+
_ENTITY = re.compile(rb"<!ENTITY", re.IGNORECASE)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def parse_xml(raw: bytes) -> ET.Element | None:
|
|
12
|
+
"""Raiz do documento, ou ``None`` se for inválido ou declarar entidades."""
|
|
13
|
+
if _ENTITY.search(raw):
|
|
14
|
+
return None
|
|
15
|
+
try:
|
|
16
|
+
return ET.fromstring(raw) # noqa: S314 - ver acima
|
|
17
|
+
except (ET.ParseError, ValueError, RecursionError):
|
|
18
|
+
return None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def local(tag: str) -> str:
|
|
22
|
+
"""Nome do elemento sem o espaço de nomes (``{ns}tag`` vira ``tag``)."""
|
|
23
|
+
return tag.rsplit("}", 1)[-1]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def children(el: ET.Element, name: str) -> list[ET.Element]:
|
|
27
|
+
return [c for c in el if local(c.tag) == name]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def child(el: ET.Element, name: str) -> ET.Element | None:
|
|
31
|
+
return next((c for c in el if local(c.tag) == name), None)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def descendants(el: ET.Element, name: str) -> list[ET.Element]:
|
|
35
|
+
return [c for c in el.iter() if local(c.tag) == name]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
_DOCTYPE = re.compile(rb"<!DOCTYPE[^\[>]*(?:\[(.*?)\])?\s*>", re.DOTALL | re.IGNORECASE)
|
|
39
|
+
_ENTITY_DECL = re.compile(rb"<!ENTITY\s+([\w.-]+)\s+(?:\"([^\"]*)\"|'([^']*)')\s*>")
|
|
40
|
+
MAX_EXPANDED = 8 * 1024 * 1024
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def parse_xml_entities(raw: bytes) -> ET.Element | None:
|
|
44
|
+
"""Como ``parse_xml``, mas aceita entidades simples declaradas no DOCTYPE (as sintaxes do Kate usam).
|
|
45
|
+
|
|
46
|
+
A expansão é feita aqui, em uma passada só e sem entidades dentro de entidades, com limite de
|
|
47
|
+
tamanho; o analisador de XML nunca vê a declaração.
|
|
48
|
+
"""
|
|
49
|
+
m = _DOCTYPE.search(raw)
|
|
50
|
+
if m is None:
|
|
51
|
+
return parse_xml(raw)
|
|
52
|
+
table: dict[bytes, bytes] = {}
|
|
53
|
+
for decl in _ENTITY_DECL.finditer(m.group(1) or b""):
|
|
54
|
+
value = decl.group(2) if decl.group(2) is not None else decl.group(3)
|
|
55
|
+
if b"&" in value or len(table) >= 2000:
|
|
56
|
+
return None
|
|
57
|
+
table[decl.group(1)] = value
|
|
58
|
+
body = raw[: m.start()] + raw[m.end() :]
|
|
59
|
+
if table:
|
|
60
|
+
body = re.sub(rb"&([\w.-]+);", lambda x: table.get(x.group(1), x.group(0)), body)
|
|
61
|
+
if len(body) > MAX_EXPANDED:
|
|
62
|
+
return None
|
|
63
|
+
return parse_xml(body)
|
src/extcompat/sexp.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Leitor de expressões simbólicas do Emacs Lisp (só lê; nada é avaliado).
|
|
2
|
+
|
|
3
|
+
Devolve listas, strings, números e ``Sym`` (símbolos). ``'x`` vira ``[Sym("quote"), x]``, a crase
|
|
4
|
+
e a vírgula viram ``Sym("`")`` e ``Sym(",")``/``Sym(",@")``, e o par pontuado ``(a . b)`` mantém o
|
|
5
|
+
ponto como ``Sym(".")``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
MAX_DEPTH = 120
|
|
13
|
+
_DELIMS = set("()[]\"';` \t\r\n,")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Sym(str):
|
|
17
|
+
"""Símbolo; é uma ``str``, mas se distingue de uma string do código-fonte."""
|
|
18
|
+
|
|
19
|
+
__slots__ = ()
|
|
20
|
+
|
|
21
|
+
def __repr__(self) -> str:
|
|
22
|
+
return f"Sym({str.__repr__(self)})"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
QUOTE, BACKQUOTE, COMMA, COMMA_AT, DOT = Sym("quote"), Sym("`"), Sym(","), Sym(",@"), Sym(".")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _Reader:
|
|
29
|
+
def __init__(self, text: str) -> None:
|
|
30
|
+
self.s = text
|
|
31
|
+
self.i = 0
|
|
32
|
+
self.n = len(text)
|
|
33
|
+
|
|
34
|
+
def skip(self) -> None:
|
|
35
|
+
while self.i < self.n:
|
|
36
|
+
ch = self.s[self.i]
|
|
37
|
+
if ch in " \t\r\n\f":
|
|
38
|
+
self.i += 1
|
|
39
|
+
elif ch == ";":
|
|
40
|
+
while self.i < self.n and self.s[self.i] != "\n":
|
|
41
|
+
self.i += 1
|
|
42
|
+
else:
|
|
43
|
+
break
|
|
44
|
+
|
|
45
|
+
def forms(self) -> list[Any]:
|
|
46
|
+
out: list[Any] = []
|
|
47
|
+
while True:
|
|
48
|
+
self.skip()
|
|
49
|
+
if self.i >= self.n:
|
|
50
|
+
return out
|
|
51
|
+
if self.s[self.i] in ")]":
|
|
52
|
+
self.i += 1 # fecha-parêntese sobrando: ignora e segue
|
|
53
|
+
continue
|
|
54
|
+
out.append(self.form(0))
|
|
55
|
+
|
|
56
|
+
def form(self, depth: int) -> Any:
|
|
57
|
+
if depth > MAX_DEPTH:
|
|
58
|
+
raise ValueError("Lisp aninhado demais")
|
|
59
|
+
self.skip()
|
|
60
|
+
if self.i >= self.n:
|
|
61
|
+
raise ValueError("fim inesperado do arquivo")
|
|
62
|
+
ch = self.s[self.i]
|
|
63
|
+
if ch in "([":
|
|
64
|
+
return self.seq(")" if ch == "(" else "]", depth)
|
|
65
|
+
if ch == "'":
|
|
66
|
+
self.i += 1
|
|
67
|
+
return [QUOTE, self.form(depth + 1)]
|
|
68
|
+
if ch == "`":
|
|
69
|
+
self.i += 1
|
|
70
|
+
return [BACKQUOTE, self.form(depth + 1)]
|
|
71
|
+
if ch == ",":
|
|
72
|
+
self.i += 1
|
|
73
|
+
op = COMMA
|
|
74
|
+
if self.i < self.n and self.s[self.i] == "@":
|
|
75
|
+
self.i += 1
|
|
76
|
+
op = COMMA_AT
|
|
77
|
+
return [op, self.form(depth + 1)]
|
|
78
|
+
if ch == '"':
|
|
79
|
+
return self.string()
|
|
80
|
+
if ch == "#" and self.s.startswith("#'", self.i):
|
|
81
|
+
self.i += 2
|
|
82
|
+
return [Sym("function"), self.form(depth + 1)]
|
|
83
|
+
if ch == "?":
|
|
84
|
+
return self.char()
|
|
85
|
+
return self.atom()
|
|
86
|
+
|
|
87
|
+
def seq(self, close: str, depth: int) -> list[Any]:
|
|
88
|
+
self.i += 1
|
|
89
|
+
items: list[Any] = []
|
|
90
|
+
while True:
|
|
91
|
+
self.skip()
|
|
92
|
+
if self.i >= self.n:
|
|
93
|
+
return items # lista não fechada: devolve o que leu
|
|
94
|
+
if self.s[self.i] in ")]":
|
|
95
|
+
self.i += 1
|
|
96
|
+
return items
|
|
97
|
+
items.append(self.form(depth + 1))
|
|
98
|
+
|
|
99
|
+
def string(self) -> str:
|
|
100
|
+
j = self.i + 1
|
|
101
|
+
out: list[str] = []
|
|
102
|
+
while j < self.n:
|
|
103
|
+
ch = self.s[j]
|
|
104
|
+
if ch == "\\" and j + 1 < self.n:
|
|
105
|
+
nxt = self.s[j + 1]
|
|
106
|
+
if nxt == "\n":
|
|
107
|
+
j += 2
|
|
108
|
+
continue
|
|
109
|
+
out.append({"n": "\n", "t": "\t", "r": "\r", "e": "\x1b"}.get(nxt, nxt))
|
|
110
|
+
j += 2
|
|
111
|
+
elif ch == '"':
|
|
112
|
+
self.i = j + 1
|
|
113
|
+
return "".join(out)
|
|
114
|
+
else:
|
|
115
|
+
out.append(ch)
|
|
116
|
+
j += 1
|
|
117
|
+
self.i = self.n
|
|
118
|
+
raise ValueError("string sem fim")
|
|
119
|
+
|
|
120
|
+
def char(self) -> Sym:
|
|
121
|
+
"""Literal de caractere (``?a``, ``?\\(``): vira um símbolo opaco."""
|
|
122
|
+
j = self.i + 1
|
|
123
|
+
if j < self.n and self.s[j] == "\\":
|
|
124
|
+
j += 2
|
|
125
|
+
else:
|
|
126
|
+
j += 1
|
|
127
|
+
text = self.s[self.i : j]
|
|
128
|
+
self.i = j
|
|
129
|
+
return Sym(text)
|
|
130
|
+
|
|
131
|
+
def atom(self) -> Any:
|
|
132
|
+
j = self.i
|
|
133
|
+
while j < self.n and self.s[j] not in _DELIMS:
|
|
134
|
+
if self.s[j] == "\\" and j + 1 < self.n:
|
|
135
|
+
j += 1
|
|
136
|
+
j += 1
|
|
137
|
+
if j == self.i:
|
|
138
|
+
j += 1 # caractere solto inesperado
|
|
139
|
+
text = self.s[self.i : j]
|
|
140
|
+
self.i = j
|
|
141
|
+
try:
|
|
142
|
+
return int(text)
|
|
143
|
+
except ValueError:
|
|
144
|
+
pass
|
|
145
|
+
try:
|
|
146
|
+
return float(text)
|
|
147
|
+
except ValueError:
|
|
148
|
+
return Sym(text)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def parse_all(text: str) -> list[Any]:
|
|
152
|
+
return _Reader(text).forms()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def walk(node: Any):
|
|
156
|
+
"""Percorre todas as listas do código, de fora para dentro."""
|
|
157
|
+
if isinstance(node, list):
|
|
158
|
+
yield node
|
|
159
|
+
for item in node:
|
|
160
|
+
yield from walk(item)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def head(node: Any) -> str:
|
|
164
|
+
"""Nome do primeiro elemento de uma lista (``''`` se não houver)."""
|
|
165
|
+
if isinstance(node, list) and node and isinstance(node[0], Sym):
|
|
166
|
+
return str(node[0])
|
|
167
|
+
return ""
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def unquote(node: Any) -> Any:
|
|
171
|
+
"""Remove ``'`` e a crase da frente de um valor."""
|
|
172
|
+
while isinstance(node, list) and len(node) == 2 and node[0] in (QUOTE, BACKQUOTE):
|
|
173
|
+
node = node[1]
|
|
174
|
+
return node
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def plist(items: list[Any]) -> dict[str, Any]:
|
|
178
|
+
"""Lista de propriedades ``(:chave valor ...)`` como dicionário."""
|
|
179
|
+
out: dict[str, Any] = {}
|
|
180
|
+
i = 0
|
|
181
|
+
while i < len(items) - 1:
|
|
182
|
+
if isinstance(items[i], Sym) and items[i].startswith(":"):
|
|
183
|
+
out[str(items[i])] = items[i + 1]
|
|
184
|
+
i += 2
|
|
185
|
+
else:
|
|
186
|
+
i += 1
|
|
187
|
+
return out
|