mavrix 0.3.0__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.
mavrix/importer.py ADDED
@@ -0,0 +1,52 @@
1
+ """Lets Mavrix and Python programs ``use`` other ``.mvx`` files as modules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.abc
6
+ import importlib.util
7
+ import os
8
+ import sys
9
+ from typing import Optional
10
+
11
+ from .compiler import compile_source
12
+ from .diagnostics import CompileError, render
13
+
14
+
15
+ class _MavrixLoader(importlib.abc.Loader):
16
+ def __init__(self, path: str):
17
+ self.path = path
18
+
19
+ def create_module(self, spec):
20
+ return None
21
+
22
+ def exec_module(self, module) -> None:
23
+ with open(self.path, encoding="utf-8") as fh:
24
+ source = fh.read()
25
+ try:
26
+ comp = compile_source(source, self.path)
27
+ except CompileError as err:
28
+ raise ImportError(
29
+ f"Cannot use '{module.__name__}': it has errors\n{err.render(source, self.path)}"
30
+ ) from None
31
+ exec(comp.code(), module.__dict__)
32
+
33
+
34
+ class MavrixFinder(importlib.abc.MetaPathFinder):
35
+ def find_spec(self, fullname: str, path=None, target=None):
36
+ name = fullname.rpartition(".")[2]
37
+ for base in (path if path is not None else sys.path) or [""]:
38
+ base = base or os.getcwd()
39
+ candidate = os.path.join(base, name + ".mvx")
40
+ if os.path.isfile(candidate):
41
+ return importlib.util.spec_from_file_location(fullname, candidate, loader=_MavrixLoader(candidate))
42
+ pkg = os.path.join(base, name, "__init__.mvx")
43
+ if os.path.isfile(pkg):
44
+ return importlib.util.spec_from_file_location(
45
+ fullname, pkg, loader=_MavrixLoader(pkg), submodule_search_locations=[os.path.dirname(pkg)]
46
+ )
47
+ return None
48
+
49
+
50
+ def install() -> None:
51
+ if not any(isinstance(f, MavrixFinder) for f in sys.meta_path):
52
+ sys.meta_path.append(MavrixFinder())
mavrix/lexer.py ADDED
@@ -0,0 +1,177 @@
1
+ """Lexer: turns Mavrix source text into a flat list of tokens.
2
+
3
+ Layout is *not* significant: newlines end statements (except inside brackets) and
4
+ indentation is ignored. Blocks are delimited by keywords and ``end`` in the parser.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import dataclass
11
+ from typing import List
12
+
13
+ from .diagnostics import MavrixError
14
+
15
+ NAME, NUMBER, STRING, OP, NEWLINE, EOF = "NAME", "NUMBER", "STRING", "OP", "NEWLINE", "EOF"
16
+ COMMENT = "COMMENT" # only produced when tokenize(..., keep_comments=True) (used by the formatter)
17
+
18
+
19
+ @dataclass
20
+ class Token:
21
+ kind: str
22
+ value: str
23
+ line: int
24
+ col: int
25
+ end_line: int
26
+ end_col: int
27
+
28
+ def __repr__(self) -> str: # compact for `mavrix tokens`
29
+ return f"{self.kind}({self.value!r}) @{self.line}:{self.col + 1}"
30
+
31
+
32
+ _NUMBER_RE = re.compile(
33
+ r"0[xX][0-9a-fA-F_]+|0[oO][0-7_]+|0[bB][01_]+|"
34
+ r"(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?[jJ]?"
35
+ )
36
+ _STRING_PREFIXES = {"r", "u", "b", "f", "br", "rb", "fr", "rf"}
37
+ _OPS3 = {"**=", "//=", "<<=", ">>="}
38
+ _OPS2 = {"==", "!=", "<=", ">=", "+=", "-=", "*=", "/=", "%=", "//", "**", "<<", ">>", "&=", "|=", "^="}
39
+ _OPS1 = set("+-*/%<>=()[]{},:.&|^~@")
40
+ _OPEN = {"(": ")", "[": "]", "{": "}"}
41
+
42
+
43
+ def tokenize(source: str, keep_comments: bool = False) -> List[Token]:
44
+ source = source.replace("\r\n", "\n").replace("\r", "\n")
45
+ toks: List[Token] = []
46
+ stack: List[Token] = [] # open brackets
47
+ i, n = 0, len(source)
48
+ line, line_start = 1, 0
49
+
50
+ def add(kind: str, value: str, start: int, sline: int, sstart: int) -> None:
51
+ toks.append(Token(kind, value, sline, start - sstart, line, i - line_start))
52
+
53
+ while i < n:
54
+ c = source[i]
55
+ if c in " \t\f":
56
+ i += 1
57
+ elif c == "\n":
58
+ if not stack and toks and toks[-1].kind != NEWLINE:
59
+ toks.append(Token(NEWLINE, "\n", line, i - line_start, line, i - line_start + 1))
60
+ i += 1
61
+ line += 1
62
+ line_start = i
63
+ elif c == "#":
64
+ start = i
65
+ while i < n and source[i] != "\n":
66
+ i += 1
67
+ if keep_comments:
68
+ toks.append(Token(COMMENT, source[start:i].rstrip(), line, start - line_start, line, i - line_start))
69
+ elif c == "\\" and source[i + 1 : i + 2] == "\n":
70
+ i += 2
71
+ line += 1
72
+ line_start = i
73
+ elif c.isalpha() or c == "_":
74
+ j = i
75
+ while j < n and (source[j].isalnum() or source[j] == "_"):
76
+ j += 1
77
+ word = source[i:j]
78
+ if j < n and source[j] in "\"'" and word.lower() in _STRING_PREFIXES:
79
+ i, line, line_start = _string(source, toks, i, j, line, line_start)
80
+ else:
81
+ start, i = i, j
82
+ add(NAME, word, start, line, line_start)
83
+ elif c in "\"'":
84
+ i, line, line_start = _string(source, toks, i, i, line, line_start)
85
+ elif c.isdigit() or (c == "." and source[i + 1 : i + 2].isdigit()):
86
+ m = _NUMBER_RE.match(source, i)
87
+ text = m.group(0)
88
+ j = m.end()
89
+ if j < n and (source[j].isalpha() or source[j] == "_"):
90
+ raise MavrixError(
91
+ f"'{source[i:j + 1]}' is not a valid number", line, i - line_start, j + 1 - line_start,
92
+ "Names cannot start with a digit, and numbers cannot contain letters.",
93
+ )
94
+ start, i = i, j
95
+ add(NUMBER, text, start, line, line_start)
96
+ else:
97
+ three, two = source[i : i + 3], source[i : i + 2]
98
+ if three in _OPS3:
99
+ op = three
100
+ elif two in _OPS2:
101
+ op = two
102
+ elif c in _OPS1:
103
+ op = c
104
+ else:
105
+ hints = {
106
+ ";": "Mavrix uses one statement per line, so no ';' is needed.",
107
+ "!": "To say 'not equal', use != (or write: is not equal to).",
108
+ "$": "Names can only contain letters, digits and '_'.",
109
+ "?": "Names can only contain letters, digits and '_'.",
110
+ }
111
+ raise MavrixError(
112
+ f"Unexpected character '{c}'", line, i - line_start, i - line_start + 1, hints.get(c)
113
+ )
114
+ start = i
115
+ i += len(op)
116
+ tok_line, tok_col = line, start - line_start
117
+ if op in _OPEN:
118
+ stack.append(Token(OP, op, tok_line, tok_col, line, i - line_start))
119
+ elif op in ")]}":
120
+ if not stack or _OPEN[stack[-1].value] != op:
121
+ raise MavrixError(
122
+ f"Unmatched '{op}'", tok_line, tok_col, tok_col + 1,
123
+ "Check that every bracket is closed in the right order.",
124
+ )
125
+ stack.pop()
126
+ add(OP, op, start, line, line_start)
127
+ if stack:
128
+ t = stack[-1]
129
+ raise MavrixError(
130
+ f"The '{t.value}' on this line is never closed", t.line, t.col, t.end_col,
131
+ f"Add a matching '{_OPEN[t.value]}'.", incomplete=True,
132
+ )
133
+ if toks and toks[-1].kind != NEWLINE:
134
+ toks.append(Token(NEWLINE, "\n", line, n - line_start, line, n - line_start))
135
+ toks.append(Token(EOF, "", line, n - line_start, line, n - line_start))
136
+ return toks
137
+
138
+
139
+ def _string(source: str, toks: List[Token], start: int, qpos: int, line: int, line_start: int):
140
+ """Scan a string literal starting at ``start`` (quote at ``qpos``)."""
141
+ n = len(source)
142
+ quote = source[qpos]
143
+ triple = source.startswith(quote * 3, qpos)
144
+ j = qpos + (3 if triple else 1)
145
+ sline, sstart = line, line_start
146
+ while True:
147
+ if j >= n:
148
+ raise MavrixError(
149
+ "Text is missing its closing quote", sline, start - sstart, start - sstart + (qpos - start) + 1,
150
+ f"Add a matching {quote * (3 if triple else 1)} at the end of the text.", incomplete=triple,
151
+ )
152
+ c = source[j]
153
+ if c == "\\":
154
+ if source[j + 1 : j + 2] == "\n":
155
+ line += 1
156
+ line_start = j + 2
157
+ j += 2
158
+ continue
159
+ if c == "\n":
160
+ if not triple:
161
+ raise MavrixError(
162
+ "Text is missing its closing quote", sline, start - sstart, qpos - sstart + 1,
163
+ f"Add a matching {quote} at the end of the text. (For text over several lines use three quotes.)",
164
+ )
165
+ line += 1
166
+ line_start = j + 1
167
+ j += 1
168
+ continue
169
+ if triple and source.startswith(quote * 3, j):
170
+ j += 3
171
+ break
172
+ if not triple and c == quote:
173
+ j += 1
174
+ break
175
+ j += 1
176
+ toks.append(Token(STRING, source[start:j], sline, start - sstart, line, j - line_start))
177
+ return j, line, line_start
mavrix/lsp.py ADDED
@@ -0,0 +1,316 @@
1
+ """A small Language Server (LSP over stdio) for Mavrix: ``mavrix lsp``.
2
+
3
+ Gives any LSP-capable editor live error/warning squiggles, formatting, completion,
4
+ hover help and a document outline - with no third-party dependencies.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ import json
11
+ import re
12
+ import sys
13
+ from typing import Any, Dict, List, Optional
14
+
15
+ from . import __version__
16
+ from .compiler import compile_source
17
+ from .diagnostics import CompileError, MavrixError
18
+ from .fmt import FormatError, format_source
19
+
20
+ ERROR, WARNING = 1, 2
21
+ KIND_FUNCTION, KIND_CLASS, KIND_VARIABLE, KIND_KEYWORD, KIND_SNIPPET = 3, 7, 6, 14, 15
22
+
23
+ # (label, snippet, documentation)
24
+ SNIPPETS = [
25
+ ("if", "if ${1:condition} then\n\t$0\nend", "Run code only when a condition is true."),
26
+ ("otherwise if", "otherwise if ${1:condition} then\n\t$0", "Another condition for an 'if'."),
27
+ ("otherwise", "otherwise\n\t$0", "What to do when no condition matched."),
28
+ ("repeat times", "repeat ${1:3} times\n\t$0\nend", "Repeat a block a fixed number of times."),
29
+ ("repeat forever", "repeat forever\n\t$0\nend", "Repeat until 'stop loop'."),
30
+ ("while", "while ${1:condition}\n\t$0\nend", "Repeat while a condition is true."),
31
+ ("for each", "for each ${1:item} in ${2:items}\n\t$0\nend", "Go through every item of a list."),
32
+ ("count", "count ${1:i} from ${2:1} to ${3:10}\n\t$0\nend", "Count from one number to another (last included)."),
33
+ ("define", "define ${1:name}(${2:inputs})\n\t$0\nend", "Create a function."),
34
+ ("class", "class ${1:Name}\n\tdefine __init__(self${2})\n\t\t$0\n\tend\nend", "Create a class."),
35
+ ("try", "try\n\t$1\non error as ${2:problem}\n\t$0\nend", "Run code and handle errors."),
36
+ ("say", "say ${1:\"text\"}", "Show something on the screen."),
37
+ ("ask", "ask ${1:name} \"${2:Question? }\"", "Ask the user to type something."),
38
+ ("ask number", "ask number ${1:n} \"${2:Number? }\"", "Ask for a whole number."),
39
+ ("set", "set ${1:name} = ${2:value}", "Create or change a variable."),
40
+ ]
41
+ KEYWORDS = {
42
+ "say": "**say** *values* – show values on the screen (Python `print`).",
43
+ "ask": "**ask** [number|decimal] *name* \"prompt\" – read what the user types into a variable.",
44
+ "set": "**set** *name* = *value* – create or change a variable.",
45
+ "change": "**change** *name* **by** *amount* – add to a variable (`increase` is the same).",
46
+ "increase": "**increase** *name* **by** *amount* – add to a variable.",
47
+ "decrease": "**decrease** *name* **by** *amount* – subtract from a variable.",
48
+ "multiply": "**multiply** *name* **by** *amount*.",
49
+ "divide": "**divide** *name* **by** *amount*.",
50
+ "if": "**if** *condition* **then** … **otherwise if** … **otherwise** … **end**",
51
+ "otherwise": "Alternative branch of an `if` (also: `otherwise if condition then`).",
52
+ "while": "**while** *condition* … **end** – repeat while the condition is true.",
53
+ "repeat": "**repeat** *N* **times** … **end**, or **repeat forever** … **end**.",
54
+ "for": "**for each** *item* **in** *collection* … **end**",
55
+ "each": "Used in `for each item in collection`.",
56
+ "count": "**count** *i* **from** *a* **to** *b* [**step** *s*] … **end** – the last number is included.",
57
+ "define": "**define** *name*(*inputs*) … **end** – create a function. Use **give back** to return a result.",
58
+ "give": "**give back** *value* – send a result out of a function.",
59
+ "class": "**class** *Name*[(*Parent*)] … **end**",
60
+ "try": "**try** … **on error** [*Type*] [**as** *e*] … **always** … **end**",
61
+ "always": "Part of `try` that always runs.",
62
+ "fail": "**fail** \"message\" – raise an error.",
63
+ "ensure": "**ensure** *condition*[, \"message\"] – stop with an error when the condition is false.",
64
+ "use": "**use** *module* · **use** *a, b* **from** *module* – import code.",
65
+ "with": "**with** *thing* [**as** *name*] … **end** – e.g. open a file and close it automatically.",
66
+ "end": "Closes the block opened by `if`, `repeat`, `define`, … (may be written `end if`).",
67
+ "stop": "**stop loop** – leave the loop now.",
68
+ "skip": "**skip** – jump to the next round of the loop.",
69
+ "do": "**do nothing** – an empty statement.",
70
+ "contains": "*list* **contains** *x* – true when *x* is in the list or text.",
71
+ "length": "**length of** *x* – the number of items (Python `len`).",
72
+ "mod": "*a* **mod** *b* – the remainder of a division.",
73
+ "true": "The value *true*.",
74
+ "false": "The value *false*.",
75
+ "nothing": "The value *nothing* (no value).",
76
+ "global": "**global** *name* – let a function change a variable defined outside.",
77
+ "delete": "**delete** *name* – remove a variable or an item.",
78
+ }
79
+ _WORD = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
80
+
81
+
82
+ def _u16(text: str, col: int) -> int:
83
+ """Convert a character column to an LSP (UTF-16) column."""
84
+ return len(text[:col].encode("utf-16-le")) // 2
85
+
86
+
87
+ def _from_u16(text: str, units: int) -> int:
88
+ n = 0
89
+ for i, ch in enumerate(text):
90
+ if n >= units:
91
+ return i
92
+ n += 2 if ord(ch) > 0xFFFF else 1
93
+ return len(text)
94
+
95
+
96
+ class Server:
97
+ def __init__(self, stdin=None, stdout=None):
98
+ self.inp = stdin or sys.stdin.buffer
99
+ self.out = stdout or sys.stdout.buffer
100
+ self.docs: Dict[str, str] = {}
101
+ self.trees: Dict[str, ast.Module] = {} # last version that parsed
102
+ self.shutdown = False
103
+
104
+ # ---------------------------------------------------------------- transport
105
+ def read(self) -> Optional[Dict[str, Any]]:
106
+ length = None
107
+ while True:
108
+ line = self.inp.readline()
109
+ if not line:
110
+ return None
111
+ line = line.decode("ascii", "replace").strip()
112
+ if not line:
113
+ break
114
+ if line.lower().startswith("content-length:"):
115
+ length = int(line.split(":", 1)[1])
116
+ if length is None:
117
+ return None
118
+ return json.loads(self.inp.read(length).decode("utf-8"))
119
+
120
+ def send(self, msg: Dict[str, Any]) -> None:
121
+ body = json.dumps({"jsonrpc": "2.0", **msg}).encode("utf-8")
122
+ self.out.write(b"Content-Length: " + str(len(body)).encode("ascii") + b"\r\n\r\n" + body)
123
+ self.out.flush()
124
+
125
+ def reply(self, req_id, result=None) -> None:
126
+ self.send({"id": req_id, "result": result})
127
+
128
+ def notify(self, method: str, params: Any) -> None:
129
+ self.send({"method": method, "params": params})
130
+
131
+ def run(self) -> int:
132
+ while True:
133
+ msg = self.read()
134
+ if msg is None:
135
+ return 0 if self.shutdown else 1
136
+ if self.handle(msg) is False:
137
+ return 0 if self.shutdown else 1
138
+
139
+ # ----------------------------------------------------------------- dispatch
140
+ def handle(self, msg: Dict[str, Any]):
141
+ method = msg.get("method")
142
+ params = msg.get("params") or {}
143
+ req_id = msg.get("id")
144
+ handler = getattr(self, "on_" + (method or "").replace("/", "_").replace("$", ""), None)
145
+ if method == "exit":
146
+ return False
147
+ if handler is None:
148
+ if req_id is not None: # unknown request
149
+ self.send({"id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}})
150
+ return None
151
+ result = handler(params)
152
+ if req_id is not None:
153
+ self.reply(req_id, result)
154
+ return None
155
+
156
+ # ----------------------------------------------------------------- lifecycle
157
+ def on_initialize(self, params):
158
+ return {
159
+ "capabilities": {
160
+ "textDocumentSync": {"openClose": True, "change": 1, "save": {"includeText": False}},
161
+ "documentFormattingProvider": True,
162
+ "completionProvider": {"triggerCharacters": []},
163
+ "hoverProvider": True,
164
+ "documentSymbolProvider": True,
165
+ },
166
+ "serverInfo": {"name": "mavrix", "version": __version__},
167
+ }
168
+
169
+ def on_initialized(self, params):
170
+ return None
171
+
172
+ def on_shutdown(self, params):
173
+ self.shutdown = True
174
+ return None
175
+
176
+ # ---------------------------------------------------------------- documents
177
+ def on_textDocument_didOpen(self, params):
178
+ doc = params["textDocument"]
179
+ self.docs[doc["uri"]] = doc["text"]
180
+ self.analyse(doc["uri"])
181
+
182
+ def on_textDocument_didChange(self, params):
183
+ uri = params["textDocument"]["uri"]
184
+ changes = params.get("contentChanges") or []
185
+ if changes:
186
+ self.docs[uri] = changes[-1]["text"] # full-document sync
187
+ self.analyse(uri)
188
+
189
+ def on_textDocument_didSave(self, params):
190
+ self.analyse(params["textDocument"]["uri"])
191
+
192
+ def on_textDocument_didClose(self, params):
193
+ uri = params["textDocument"]["uri"]
194
+ self.docs.pop(uri, None)
195
+ self.trees.pop(uri, None)
196
+ self.notify("textDocument/publishDiagnostics", {"uri": uri, "diagnostics": []})
197
+
198
+ # -------------------------------------------------------------- diagnostics
199
+ def diagnostics(self, uri: str) -> List[Dict[str, Any]]:
200
+ source = self.docs.get(uri, "")
201
+ lines = source.split("\n")
202
+ try:
203
+ comp = compile_source(source, uri)
204
+ problems: List[MavrixError] = list(comp.warnings)
205
+ self.trees[uri] = comp.module
206
+ except CompileError as err:
207
+ problems = err.diagnostics
208
+ result = []
209
+ for d in problems:
210
+ line = max(d.line - 1, 0)
211
+ text = lines[line] if line < len(lines) else ""
212
+ result.append({
213
+ "range": {
214
+ "start": {"line": line, "character": _u16(text, d.col)},
215
+ "end": {"line": line, "character": _u16(text, max(d.end_col, d.col + 1))},
216
+ },
217
+ "severity": ERROR if d.severity == "error" else WARNING,
218
+ "source": "mavrix",
219
+ "message": d.message + (f"\nHint: {d.hint}" if d.hint else ""),
220
+ })
221
+ return result
222
+
223
+ def analyse(self, uri: str) -> None:
224
+ self.notify("textDocument/publishDiagnostics", {"uri": uri, "diagnostics": self.diagnostics(uri)})
225
+
226
+ # --------------------------------------------------------------- formatting
227
+ def on_textDocument_formatting(self, params):
228
+ uri = params["textDocument"]["uri"]
229
+ source = self.docs.get(uri, "")
230
+ try:
231
+ formatted = format_source(source)
232
+ except FormatError:
233
+ return [] # never touch a program that has errors
234
+ if formatted == source:
235
+ return []
236
+ lines = source.split("\n")
237
+ end = {"line": len(lines) - 1, "character": _u16(lines[-1], len(lines[-1]))}
238
+ return [{"range": {"start": {"line": 0, "character": 0}, "end": end}, "newText": formatted}]
239
+
240
+ # --------------------------------------------------------------- completion
241
+ def names(self, uri: str):
242
+ tree = self.trees.get(uri)
243
+ found: Dict[str, int] = {}
244
+ if tree is not None:
245
+ for n in ast.walk(tree):
246
+ if isinstance(n, ast.FunctionDef):
247
+ found.setdefault(n.name, KIND_FUNCTION)
248
+ elif isinstance(n, ast.ClassDef):
249
+ found.setdefault(n.name, KIND_CLASS)
250
+ elif isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store):
251
+ found.setdefault(n.id, KIND_VARIABLE)
252
+ return found
253
+
254
+ def on_textDocument_completion(self, params):
255
+ uri = params["textDocument"]["uri"]
256
+ items: List[Dict[str, Any]] = []
257
+ for label, snippet, doc in SNIPPETS:
258
+ items.append({"label": label, "kind": KIND_SNIPPET, "insertText": snippet, "insertTextFormat": 2,
259
+ "documentation": {"kind": "markdown", "value": doc}})
260
+ for w in ("and", "or", "not", "in", "is", "then", "to", "by", "step", "times", "contains", "mod", "length of",
261
+ "is at least", "is at most", "is greater than", "is less than", "is equal to", "is not equal to",
262
+ "give back", "stop loop", "skip", "do nothing", "fail", "ensure", "use", "with", "always",
263
+ "on error", "end", "true", "false", "nothing", "change", "increase", "decrease"):
264
+ items.append({"label": w, "kind": KIND_KEYWORD})
265
+ for name, kind in sorted(self.names(uri).items()):
266
+ items.append({"label": name, "kind": kind})
267
+ return {"isIncomplete": False, "items": items}
268
+
269
+ # -------------------------------------------------------------------- hover
270
+ def on_textDocument_hover(self, params):
271
+ uri = params["textDocument"]["uri"]
272
+ pos = params["position"]
273
+ lines = self.docs.get(uri, "").split("\n")
274
+ if pos["line"] >= len(lines):
275
+ return None
276
+ text = lines[pos["line"]]
277
+ col = _from_u16(text, pos["character"])
278
+ for m in _WORD.finditer(text):
279
+ if m.start() <= col <= m.end():
280
+ doc = KEYWORDS.get(m.group(0))
281
+ if doc:
282
+ return {"contents": {"kind": "markdown", "value": doc}}
283
+ return None
284
+
285
+ # ------------------------------------------------------------------ outline
286
+ def on_textDocument_documentSymbol(self, params):
287
+ uri = params["textDocument"]["uri"]
288
+ tree = self.trees.get(uri)
289
+ if tree is None:
290
+ return []
291
+ lines = self.docs.get(uri, "").split("\n")
292
+
293
+ def rng(node):
294
+ end_line = (getattr(node, "end_lineno", None) or node.lineno) - 1
295
+ end_text = lines[end_line] if end_line < len(lines) else ""
296
+ return {"start": {"line": node.lineno - 1, "character": 0},
297
+ "end": {"line": end_line, "character": _u16(end_text, len(end_text))}}
298
+
299
+ def symbols(body):
300
+ out = []
301
+ for node in body:
302
+ if isinstance(node, (ast.FunctionDef, ast.ClassDef)):
303
+ r = rng(node)
304
+ out.append({
305
+ "name": node.name,
306
+ "kind": 12 if isinstance(node, ast.FunctionDef) else 5,
307
+ "range": r, "selectionRange": r,
308
+ "children": symbols(node.body),
309
+ })
310
+ return out
311
+
312
+ return symbols(tree.body)
313
+
314
+
315
+ def serve() -> int:
316
+ return Server().run()