candide 0.0.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.
- candide/__init__.py +3 -0
- candide/__main__.py +21 -0
- candide/app.py +44 -0
- candide/core/__init__.py +0 -0
- candide/core/code_model.py +88 -0
- candide/core/commands.py +72 -0
- candide/core/core.py +84 -0
- candide/core/documents.py +108 -0
- candide/core/facts.py +153 -0
- candide/core/languages.py +44 -0
- candide/core/location.py +39 -0
- candide/core/panels.py +54 -0
- candide/core/plugins.py +28 -0
- candide/core/workspace.py +121 -0
- candide/kernel.py +200 -0
- candide/languages/python.toml +4 -0
- candide/lsp/__init__.py +0 -0
- candide/lsp/session.py +653 -0
- candide/mcp_server.py +111 -0
- candide/plugins/__init__.py +0 -0
- candide/plugins/meson.py +87 -0
- candide/plugins/python_lang.py +175 -0
- candide-0.0.1.dist-info/METADATA +70 -0
- candide-0.0.1.dist-info/RECORD +27 -0
- candide-0.0.1.dist-info/WHEEL +4 -0
- candide-0.0.1.dist-info/entry_points.txt +6 -0
- candide-0.0.1.dist-info/licenses/LICENSE +21 -0
candide/__init__.py
ADDED
candide/__main__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""The `candide` command: `candide FILE` opens FILE, creating it on the first save."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import pathlib
|
|
5
|
+
|
|
6
|
+
import prism
|
|
7
|
+
|
|
8
|
+
from candide import __version__
|
|
9
|
+
from candide.app import Editor
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv=None):
|
|
13
|
+
parser = argparse.ArgumentParser(prog="candide", description="A code editor where AI agents are peers.")
|
|
14
|
+
parser.add_argument("file", type=pathlib.Path, help="the file to open")
|
|
15
|
+
parser.add_argument("--version", action="version", version=f"candide {__version__}")
|
|
16
|
+
args = parser.parse_args(argv)
|
|
17
|
+
prism.run(Editor(args.file.resolve()), title=f"Candide - {args.file.name}")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
if __name__ == "__main__":
|
|
21
|
+
main()
|
candide/app.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""The editor window: one file in a code editor, saved with Ctrl+S."""
|
|
2
|
+
|
|
3
|
+
import pathlib
|
|
4
|
+
|
|
5
|
+
import prism
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def load(path: pathlib.Path) -> str:
|
|
9
|
+
return path.read_text(encoding="utf-8") if path.exists() else ""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def language_of(path: pathlib.Path) -> str:
|
|
13
|
+
# PRISM's highlighter takes file extensions as language names ("py", "hpp", "toml").
|
|
14
|
+
return path.suffix.lstrip(".")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def status_line(path: pathlib.Path, saved: bool) -> str:
|
|
18
|
+
return f"{path}" + ("" if saved else " (modified)")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Editor(prism.Model):
|
|
22
|
+
source = prism.document("")
|
|
23
|
+
save = prism.button("Save", shortcut="Ctrl+S")
|
|
24
|
+
status = prism.label("")
|
|
25
|
+
|
|
26
|
+
def __init__(self, path: pathlib.Path):
|
|
27
|
+
super().__init__()
|
|
28
|
+
self.path = path
|
|
29
|
+
self.source.set_text(load(path))
|
|
30
|
+
self.status.value = status_line(path, saved=True)
|
|
31
|
+
self.source.observe(lambda: self._mark(saved=False))
|
|
32
|
+
self.save.observe(lambda _: self.write())
|
|
33
|
+
|
|
34
|
+
def write(self):
|
|
35
|
+
self.path.write_text(self.source.text, encoding="utf-8")
|
|
36
|
+
self._mark(saved=True)
|
|
37
|
+
|
|
38
|
+
def _mark(self, saved: bool):
|
|
39
|
+
self.status.value = status_line(self.path, saved)
|
|
40
|
+
|
|
41
|
+
def view(self, vb):
|
|
42
|
+
vb.widget(self.save)
|
|
43
|
+
vb.code_editor(self.source, language_of(self.path))
|
|
44
|
+
vb.widget(self.status)
|
candide/core/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import concurrent.futures
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Protocol
|
|
4
|
+
|
|
5
|
+
from candide.core.documents import Documents
|
|
6
|
+
from candide.core.location import Location
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class Completion:
|
|
11
|
+
label: str
|
|
12
|
+
insert: str = ""
|
|
13
|
+
detail: str = ""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CodeProvider(Protocol):
|
|
17
|
+
def definition(self, loc: Location) -> list[Location]: ...
|
|
18
|
+
|
|
19
|
+
def hover(self, loc: Location) -> str | None: ...
|
|
20
|
+
|
|
21
|
+
def completions(self, loc: Location) -> list[Completion]: ...
|
|
22
|
+
|
|
23
|
+
def definition_async(
|
|
24
|
+
self, loc: Location
|
|
25
|
+
) -> concurrent.futures.Future[list[Location]]: ...
|
|
26
|
+
|
|
27
|
+
def hover_async(self, loc: Location) -> concurrent.futures.Future[str | None]: ...
|
|
28
|
+
|
|
29
|
+
def completions_async(
|
|
30
|
+
self, loc: Location
|
|
31
|
+
) -> concurrent.futures.Future[list[Completion]]: ...
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class CodeModel:
|
|
35
|
+
def __init__(self, documents: Documents):
|
|
36
|
+
self._documents = documents
|
|
37
|
+
self._providers: dict[str, CodeProvider] = {}
|
|
38
|
+
|
|
39
|
+
def add_provider(self, language: str, provider: CodeProvider) -> None:
|
|
40
|
+
if language in self._providers:
|
|
41
|
+
raise ValueError(f"language {language!r} already has a provider")
|
|
42
|
+
self._providers[language] = provider
|
|
43
|
+
|
|
44
|
+
def definition(self, loc: Location) -> list[Location]:
|
|
45
|
+
provider = self._provider(loc)
|
|
46
|
+
return provider.definition(loc) if provider is not None else []
|
|
47
|
+
|
|
48
|
+
def hover(self, loc: Location) -> str | None:
|
|
49
|
+
provider = self._provider(loc)
|
|
50
|
+
return provider.hover(loc) if provider is not None else None
|
|
51
|
+
|
|
52
|
+
def completions(self, loc: Location) -> list[Completion]:
|
|
53
|
+
provider = self._provider(loc)
|
|
54
|
+
return provider.completions(loc) if provider is not None else []
|
|
55
|
+
|
|
56
|
+
def definition_async(
|
|
57
|
+
self, loc: Location
|
|
58
|
+
) -> concurrent.futures.Future[list[Location]]:
|
|
59
|
+
provider = self._provider(loc)
|
|
60
|
+
if provider is None:
|
|
61
|
+
return _answered([])
|
|
62
|
+
return provider.definition_async(loc)
|
|
63
|
+
|
|
64
|
+
def hover_async(self, loc: Location) -> concurrent.futures.Future[str | None]:
|
|
65
|
+
provider = self._provider(loc)
|
|
66
|
+
if provider is None:
|
|
67
|
+
return _answered(None)
|
|
68
|
+
return provider.hover_async(loc)
|
|
69
|
+
|
|
70
|
+
def completions_async(
|
|
71
|
+
self, loc: Location
|
|
72
|
+
) -> concurrent.futures.Future[list[Completion]]:
|
|
73
|
+
provider = self._provider(loc)
|
|
74
|
+
if provider is None:
|
|
75
|
+
return _answered([])
|
|
76
|
+
return provider.completions_async(loc)
|
|
77
|
+
|
|
78
|
+
def _provider(self, loc: Location) -> CodeProvider | None:
|
|
79
|
+
document = self._documents.get(loc.path)
|
|
80
|
+
if document is None:
|
|
81
|
+
return None
|
|
82
|
+
return self._providers.get(document.language)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _answered(value):
|
|
86
|
+
future: concurrent.futures.Future = concurrent.futures.Future()
|
|
87
|
+
future.set_result(value)
|
|
88
|
+
return future
|
candide/core/commands.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
from typing import Any, Callable
|
|
4
|
+
|
|
5
|
+
import pydantic
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class CommandInfo:
|
|
10
|
+
name: str
|
|
11
|
+
doc: str
|
|
12
|
+
mutating: bool
|
|
13
|
+
schema: dict
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class _Command:
|
|
18
|
+
function: Callable
|
|
19
|
+
model: type[pydantic.BaseModel]
|
|
20
|
+
info: CommandInfo
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _arguments_model(name: str, function: Callable) -> type[pydantic.BaseModel]:
|
|
24
|
+
fields = {}
|
|
25
|
+
for parameter in inspect.signature(function, eval_str=True).parameters.values():
|
|
26
|
+
if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):
|
|
27
|
+
raise TypeError(f"{name}: *args and **kwargs are not supported")
|
|
28
|
+
annotation = (
|
|
29
|
+
Any
|
|
30
|
+
if parameter.annotation is inspect.Parameter.empty
|
|
31
|
+
else parameter.annotation
|
|
32
|
+
)
|
|
33
|
+
default = (
|
|
34
|
+
... if parameter.default is inspect.Parameter.empty else parameter.default
|
|
35
|
+
)
|
|
36
|
+
fields[parameter.name] = (annotation, default)
|
|
37
|
+
return pydantic.create_model(
|
|
38
|
+
f"{name}_arguments",
|
|
39
|
+
__config__=pydantic.ConfigDict(extra="forbid"),
|
|
40
|
+
**fields,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Commands:
|
|
45
|
+
def __init__(self) -> None:
|
|
46
|
+
self._commands: dict[str, _Command] = {}
|
|
47
|
+
|
|
48
|
+
def command(self, name: str, *, mutating: bool = False) -> Callable:
|
|
49
|
+
def register(function: Callable) -> Callable:
|
|
50
|
+
if name in self._commands:
|
|
51
|
+
raise ValueError(f"command {name!r} is already registered")
|
|
52
|
+
model = _arguments_model(name, function)
|
|
53
|
+
self._commands[name] = _Command(
|
|
54
|
+
function,
|
|
55
|
+
model,
|
|
56
|
+
CommandInfo(
|
|
57
|
+
name, function.__doc__ or "", mutating, model.model_json_schema()
|
|
58
|
+
),
|
|
59
|
+
)
|
|
60
|
+
return function
|
|
61
|
+
|
|
62
|
+
return register
|
|
63
|
+
|
|
64
|
+
def run(self, name: str, **args) -> Any:
|
|
65
|
+
command = self._commands[name]
|
|
66
|
+
validated = command.model(**args)
|
|
67
|
+
return command.function(
|
|
68
|
+
**{field: getattr(validated, field) for field in command.model.model_fields}
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def list(self) -> list[CommandInfo]:
|
|
72
|
+
return [command.info for command in self._commands.values()]
|
candide/core/core.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import pathlib
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
|
|
5
|
+
from candide.core.code_model import CodeModel
|
|
6
|
+
from candide.core.commands import Commands
|
|
7
|
+
from candide.core.documents import Documents
|
|
8
|
+
from candide.core.facts import Facts
|
|
9
|
+
from candide.core.languages import Languages
|
|
10
|
+
from candide.core.panels import Panels
|
|
11
|
+
from candide.core.plugins import load_plugins
|
|
12
|
+
from candide.core.workspace import Workspace
|
|
13
|
+
|
|
14
|
+
_LOGGER = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Core:
|
|
18
|
+
"""The services a Candide workspace shares.
|
|
19
|
+
|
|
20
|
+
Documents, the active build and plugin state change on the UI thread only;
|
|
21
|
+
observers may fire on any thread; a UI observer posts to the logic thread.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
workspace: Workspace,
|
|
27
|
+
documents: Documents,
|
|
28
|
+
code_model: CodeModel,
|
|
29
|
+
facts: Facts,
|
|
30
|
+
panels: Panels,
|
|
31
|
+
commands: Commands,
|
|
32
|
+
languages: Languages,
|
|
33
|
+
):
|
|
34
|
+
self.workspace = workspace
|
|
35
|
+
self.documents = documents
|
|
36
|
+
self.code_model = code_model
|
|
37
|
+
self.facts = facts
|
|
38
|
+
self.panels = panels
|
|
39
|
+
self.commands = commands
|
|
40
|
+
self.languages = languages
|
|
41
|
+
self.plugin_failures: list[tuple[str, str]] = []
|
|
42
|
+
self._teardowns: list[Callable[[], None]] = []
|
|
43
|
+
self._closed = False
|
|
44
|
+
commands.command("facts.query")(self._facts_query)
|
|
45
|
+
|
|
46
|
+
def add_teardown(self, teardown: Callable[[], None]) -> None:
|
|
47
|
+
self._teardowns.append(teardown)
|
|
48
|
+
|
|
49
|
+
def close(self) -> None:
|
|
50
|
+
if self._closed:
|
|
51
|
+
return
|
|
52
|
+
self._closed = True
|
|
53
|
+
for teardown in reversed(self._teardowns):
|
|
54
|
+
try:
|
|
55
|
+
teardown()
|
|
56
|
+
except Exception:
|
|
57
|
+
_LOGGER.exception("plugin teardown failed")
|
|
58
|
+
self.workspace.stop()
|
|
59
|
+
self.facts.close()
|
|
60
|
+
|
|
61
|
+
def _facts_query(self, sql: str) -> list[dict]:
|
|
62
|
+
"""Query the facts with read-only SQL."""
|
|
63
|
+
return self.facts.query(sql)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def open_workspace(root: pathlib.Path) -> Core:
|
|
67
|
+
root = pathlib.Path(root).resolve()
|
|
68
|
+
workspace = Workspace(root)
|
|
69
|
+
languages = Languages.load_builtin()
|
|
70
|
+
documents = Documents(languages, workspace)
|
|
71
|
+
facts_dir = root / ".candide"
|
|
72
|
+
facts_dir.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
core = Core(
|
|
74
|
+
workspace,
|
|
75
|
+
documents,
|
|
76
|
+
CodeModel(documents),
|
|
77
|
+
Facts(facts_dir / "facts.duckdb"),
|
|
78
|
+
Panels(),
|
|
79
|
+
Commands(),
|
|
80
|
+
languages,
|
|
81
|
+
)
|
|
82
|
+
_loaded, core.plugin_failures = load_plugins(core)
|
|
83
|
+
workspace.watch()
|
|
84
|
+
return core
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import pathlib
|
|
3
|
+
import threading
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from candide.core.languages import Languages
|
|
8
|
+
from candide.core.workspace import Workspace
|
|
9
|
+
|
|
10
|
+
_LOGGER = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Document:
|
|
15
|
+
path: str
|
|
16
|
+
language: str
|
|
17
|
+
text: str
|
|
18
|
+
version: int
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Documents:
|
|
22
|
+
def __init__(self, languages: Languages, workspace: Workspace):
|
|
23
|
+
self._languages = languages
|
|
24
|
+
self._workspace = workspace
|
|
25
|
+
self._documents: dict[str, Document] = {}
|
|
26
|
+
self._lock = threading.Lock()
|
|
27
|
+
self._observers: list[Callable[[str, Document | None], None]] = []
|
|
28
|
+
|
|
29
|
+
def open(self, path: str) -> Document:
|
|
30
|
+
key = self._require_key(path)
|
|
31
|
+
with self._lock:
|
|
32
|
+
existing = self._documents.get(key)
|
|
33
|
+
if existing is not None:
|
|
34
|
+
return existing
|
|
35
|
+
text = (self._workspace.root / key).read_text(encoding="utf-8")
|
|
36
|
+
language = self._languages.for_path(key)
|
|
37
|
+
document = Document(
|
|
38
|
+
key,
|
|
39
|
+
language.name if language is not None else "",
|
|
40
|
+
text,
|
|
41
|
+
0,
|
|
42
|
+
)
|
|
43
|
+
with self._lock:
|
|
44
|
+
existing = self._documents.get(key)
|
|
45
|
+
if existing is not None:
|
|
46
|
+
return existing
|
|
47
|
+
self._documents[key] = document
|
|
48
|
+
self._notify("open", document)
|
|
49
|
+
return document
|
|
50
|
+
|
|
51
|
+
def change(self, path: str, text: str) -> Document:
|
|
52
|
+
key = self._require_key(path)
|
|
53
|
+
with self._lock:
|
|
54
|
+
current = self._documents[key]
|
|
55
|
+
document = Document(key, current.language, text, current.version + 1)
|
|
56
|
+
self._documents[key] = document
|
|
57
|
+
self._notify("change", document)
|
|
58
|
+
return document
|
|
59
|
+
|
|
60
|
+
def close(self, path: str) -> None:
|
|
61
|
+
key = self._key(path)
|
|
62
|
+
if key is None:
|
|
63
|
+
return
|
|
64
|
+
with self._lock:
|
|
65
|
+
document = self._documents.pop(key, None)
|
|
66
|
+
if document is not None:
|
|
67
|
+
self._notify("close", document)
|
|
68
|
+
|
|
69
|
+
def get(self, path: str) -> Document | None:
|
|
70
|
+
key = self._key(path)
|
|
71
|
+
if key is None:
|
|
72
|
+
return None
|
|
73
|
+
with self._lock:
|
|
74
|
+
return self._documents.get(key)
|
|
75
|
+
|
|
76
|
+
def observe(
|
|
77
|
+
self, callback: Callable[[str, Document | None], None]
|
|
78
|
+
) -> Callable[[], None]:
|
|
79
|
+
self._observers.append(callback)
|
|
80
|
+
|
|
81
|
+
def unsubscribe() -> None:
|
|
82
|
+
if callback in self._observers:
|
|
83
|
+
self._observers.remove(callback)
|
|
84
|
+
|
|
85
|
+
return unsubscribe
|
|
86
|
+
|
|
87
|
+
def _key(self, path: str) -> str | None:
|
|
88
|
+
candidate = pathlib.Path(path)
|
|
89
|
+
if not candidate.is_absolute():
|
|
90
|
+
candidate = self._workspace.root / candidate
|
|
91
|
+
try:
|
|
92
|
+
relative = candidate.resolve().relative_to(self._workspace.root)
|
|
93
|
+
except ValueError:
|
|
94
|
+
return None
|
|
95
|
+
return relative.as_posix()
|
|
96
|
+
|
|
97
|
+
def _require_key(self, path: str) -> str:
|
|
98
|
+
key = self._key(path)
|
|
99
|
+
if key is None:
|
|
100
|
+
raise ValueError(f"{path!r} is outside the workspace")
|
|
101
|
+
return key
|
|
102
|
+
|
|
103
|
+
def _notify(self, event: str, document: Document | None) -> None:
|
|
104
|
+
for callback in list(self._observers):
|
|
105
|
+
try:
|
|
106
|
+
callback(event, document)
|
|
107
|
+
except Exception:
|
|
108
|
+
_LOGGER.exception("document observer failed")
|
candide/core/facts.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import pathlib
|
|
4
|
+
import threading
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
import duckdb
|
|
9
|
+
|
|
10
|
+
from candide.core.location import Location, Position, Range
|
|
11
|
+
|
|
12
|
+
_LOGGER = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Fact:
|
|
17
|
+
kind: str
|
|
18
|
+
location: Location
|
|
19
|
+
source: str
|
|
20
|
+
version: int | None
|
|
21
|
+
message: str = ""
|
|
22
|
+
value: float | None = None
|
|
23
|
+
data: dict | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
_SCHEMA = """
|
|
27
|
+
create table if not exists facts(
|
|
28
|
+
kind varchar, path varchar,
|
|
29
|
+
start_line integer, start_char integer,
|
|
30
|
+
end_line integer, end_char integer,
|
|
31
|
+
source varchar, version integer,
|
|
32
|
+
message varchar, value double, data json
|
|
33
|
+
)
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
_COLUMNS = (
|
|
37
|
+
"kind",
|
|
38
|
+
"path",
|
|
39
|
+
"start_line",
|
|
40
|
+
"start_char",
|
|
41
|
+
"end_line",
|
|
42
|
+
"end_char",
|
|
43
|
+
"source",
|
|
44
|
+
"version",
|
|
45
|
+
"message",
|
|
46
|
+
"value",
|
|
47
|
+
"data",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _checked(sql: str) -> str:
|
|
52
|
+
# DuckDB refuses a read-only connection to a file already open read-write in the same
|
|
53
|
+
# process, so read-only is enforced by DuckDB's own statement classification instead.
|
|
54
|
+
statements = duckdb.extract_statements(sql)
|
|
55
|
+
if any(statement.type != duckdb.StatementType.SELECT for statement in statements):
|
|
56
|
+
raise PermissionError(f"only SELECT statements are allowed: {sql!r}")
|
|
57
|
+
return sql
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _row(fact: Fact) -> tuple:
|
|
61
|
+
start = fact.location.range.start
|
|
62
|
+
end = fact.location.range.end
|
|
63
|
+
return (
|
|
64
|
+
fact.kind,
|
|
65
|
+
fact.location.path,
|
|
66
|
+
start.line,
|
|
67
|
+
start.character,
|
|
68
|
+
end.line,
|
|
69
|
+
end.character,
|
|
70
|
+
fact.source,
|
|
71
|
+
fact.version,
|
|
72
|
+
fact.message,
|
|
73
|
+
fact.value,
|
|
74
|
+
json.dumps(fact.data) if fact.data is not None else None,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _fact(row: tuple) -> Fact:
|
|
79
|
+
return Fact(
|
|
80
|
+
kind=row[0],
|
|
81
|
+
location=Location(
|
|
82
|
+
row[1], Range(Position(row[2], row[3]), Position(row[4], row[5]))
|
|
83
|
+
),
|
|
84
|
+
source=row[6],
|
|
85
|
+
version=row[7],
|
|
86
|
+
message=row[8],
|
|
87
|
+
value=row[9],
|
|
88
|
+
data=json.loads(row[10]) if row[10] is not None else None,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Facts:
|
|
93
|
+
def __init__(self, path: pathlib.Path | None):
|
|
94
|
+
self._connection = duckdb.connect(str(path) if path is not None else ":memory:")
|
|
95
|
+
self._connection.execute("set enable_external_access = false")
|
|
96
|
+
self._connection.execute("set lock_configuration = true")
|
|
97
|
+
self._connection.execute(_SCHEMA)
|
|
98
|
+
self._lock = threading.Lock()
|
|
99
|
+
self._observers: list[Callable[[str], None]] = []
|
|
100
|
+
|
|
101
|
+
def close(self) -> None:
|
|
102
|
+
with self._lock:
|
|
103
|
+
self._connection.close()
|
|
104
|
+
|
|
105
|
+
def replace(self, source: str, path: str, facts: list[Fact]) -> None:
|
|
106
|
+
with self._lock:
|
|
107
|
+
self._connection.execute(
|
|
108
|
+
"delete from facts where source = ? and path = ?", [source, path]
|
|
109
|
+
)
|
|
110
|
+
self._connection.executemany(
|
|
111
|
+
f"insert into facts ({', '.join(_COLUMNS)}) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
112
|
+
[_row(fact) for fact in facts],
|
|
113
|
+
)
|
|
114
|
+
for callback in list(self._observers):
|
|
115
|
+
try:
|
|
116
|
+
callback(path)
|
|
117
|
+
except Exception:
|
|
118
|
+
_LOGGER.exception("facts observer failed")
|
|
119
|
+
|
|
120
|
+
def clear(self, source: str) -> None:
|
|
121
|
+
with self._lock:
|
|
122
|
+
self._connection.execute("delete from facts where source = ?", [source])
|
|
123
|
+
|
|
124
|
+
def of(self, path: str, kind: str | None = None) -> list[Fact]:
|
|
125
|
+
sql = f"select {', '.join(_COLUMNS)} from facts where path = ?"
|
|
126
|
+
parameters = [path]
|
|
127
|
+
if kind is not None:
|
|
128
|
+
sql += " and kind = ?"
|
|
129
|
+
parameters.append(kind)
|
|
130
|
+
with self._lock:
|
|
131
|
+
rows = self._connection.execute(sql, parameters).fetchall()
|
|
132
|
+
return [_fact(row) for row in rows]
|
|
133
|
+
|
|
134
|
+
def query(self, sql: str) -> list[dict]:
|
|
135
|
+
with self._lock:
|
|
136
|
+
cursor = self._connection.execute(_checked(sql))
|
|
137
|
+
if cursor.description is None:
|
|
138
|
+
return []
|
|
139
|
+
names = [column[0] for column in cursor.description]
|
|
140
|
+
return [dict(zip(names, row)) for row in cursor.fetchall()]
|
|
141
|
+
|
|
142
|
+
def to_pandas(self, sql: str):
|
|
143
|
+
with self._lock:
|
|
144
|
+
return self._connection.execute(_checked(sql)).df()
|
|
145
|
+
|
|
146
|
+
def observe(self, callback: Callable[[str], None]) -> Callable[[], None]:
|
|
147
|
+
self._observers.append(callback)
|
|
148
|
+
|
|
149
|
+
def unsubscribe() -> None:
|
|
150
|
+
if callback in self._observers:
|
|
151
|
+
self._observers.remove(callback)
|
|
152
|
+
|
|
153
|
+
return unsubscribe
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import fnmatch
|
|
2
|
+
import pathlib
|
|
3
|
+
import tomllib
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
|
|
6
|
+
_BUNDLED = pathlib.Path(__file__).parent.parent / "languages"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class Language:
|
|
11
|
+
name: str
|
|
12
|
+
patterns: list[str]
|
|
13
|
+
highlight: str
|
|
14
|
+
server: list[str] | None = None
|
|
15
|
+
server_settings: dict = field(default_factory=dict)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _load(path: pathlib.Path) -> Language:
|
|
19
|
+
return Language(**tomllib.loads(path.read_text()))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Languages:
|
|
23
|
+
def __init__(self, languages: list[Language]):
|
|
24
|
+
self._languages = languages
|
|
25
|
+
|
|
26
|
+
@classmethod
|
|
27
|
+
def load_builtin(cls) -> "Languages":
|
|
28
|
+
return cls([_load(path) for path in sorted(_BUNDLED.glob("*.toml"))])
|
|
29
|
+
|
|
30
|
+
def for_path(self, path: str) -> Language | None:
|
|
31
|
+
name = pathlib.Path(path).name
|
|
32
|
+
return next(
|
|
33
|
+
(
|
|
34
|
+
language
|
|
35
|
+
for language in self._languages
|
|
36
|
+
if any(fnmatch.fnmatch(name, pattern) for pattern in language.patterns)
|
|
37
|
+
),
|
|
38
|
+
None,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
def get(self, name: str) -> Language | None:
|
|
42
|
+
return next(
|
|
43
|
+
(language for language in self._languages if language.name == name), None
|
|
44
|
+
)
|
candide/core/location.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass(frozen=True)
|
|
5
|
+
class Position:
|
|
6
|
+
line: int
|
|
7
|
+
character: int
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class Range:
|
|
12
|
+
start: Position
|
|
13
|
+
end: Position
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Location:
|
|
18
|
+
path: str
|
|
19
|
+
range: Range
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def utf16_to_byte(line_text: str, character: int) -> int:
|
|
23
|
+
byte = units = 0
|
|
24
|
+
for char in line_text:
|
|
25
|
+
if units >= character:
|
|
26
|
+
break
|
|
27
|
+
units += 2 if ord(char) > 0xFFFF else 1
|
|
28
|
+
byte += len(char.encode())
|
|
29
|
+
return byte
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def byte_to_utf16(line_text: str, byte: int) -> int:
|
|
33
|
+
consumed = units = 0
|
|
34
|
+
for char in line_text:
|
|
35
|
+
if consumed >= byte:
|
|
36
|
+
break
|
|
37
|
+
consumed += len(char.encode())
|
|
38
|
+
units += 2 if ord(char) > 0xFFFF else 1
|
|
39
|
+
return units
|