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/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Mavrix - a small, readable language that transpiles to Python."""
2
+
3
+ __version__ = "0.3.0"
4
+
5
+ from .compiler import Compilation, compile_source, transpile # noqa: E402
6
+ from .diagnostics import CompileError, MavrixError # noqa: E402
7
+
8
+ __all__ = ["Compilation", "CompileError", "MavrixError", "compile_source", "transpile", "__version__"]
mavrix/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
mavrix/checker.py ADDED
@@ -0,0 +1,83 @@
1
+ """Semantic checks that run after parsing: unknown names and risky names."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import builtins
7
+ import difflib
8
+ from typing import List, Set
9
+
10
+ from .diagnostics import MavrixError
11
+ from .parser import STATEMENT_WORDS
12
+
13
+ _MODULE_NAMES = {"__name__", "__file__", "__doc__", "__builtins__", "__package__", "__spec__", "__loader__"}
14
+ _SHADOW_WARN = {
15
+ "print", "input", "len", "list", "dict", "set", "str", "int", "float", "bool", "tuple", "range", "sum",
16
+ "min", "max", "abs", "round", "sorted", "reversed", "type", "id", "map", "filter", "zip", "open", "next",
17
+ "iter", "any", "all", "format", "hash", "object", "enumerate", "chr", "ord", "pow", "divmod", "repr",
18
+ }
19
+ _BUILTINS = set(dir(builtins)) | _MODULE_NAMES
20
+
21
+
22
+ def _bound_names(tree: ast.AST) -> Set[str]:
23
+ names: Set[str] = set()
24
+ for n in ast.walk(tree):
25
+ if isinstance(n, ast.Name) and isinstance(n.ctx, (ast.Store, ast.Del)):
26
+ names.add(n.id)
27
+ elif isinstance(n, (ast.FunctionDef, ast.ClassDef)):
28
+ names.add(n.name)
29
+ elif isinstance(n, ast.arg):
30
+ names.add(n.arg)
31
+ elif isinstance(n, ast.ExceptHandler) and n.name:
32
+ names.add(n.name)
33
+ elif isinstance(n, (ast.Import, ast.ImportFrom)):
34
+ for a in n.names:
35
+ names.add((a.asname or a.name).split(".")[0])
36
+ elif isinstance(n, (ast.Global, ast.Nonlocal)):
37
+ names.update(n.names)
38
+ return names
39
+
40
+
41
+ def check(tree: ast.Module, known_names=()) -> List[MavrixError]:
42
+ """Return a list of diagnostics (errors and warnings) for a parsed program."""
43
+ problems: List[MavrixError] = []
44
+ star = any(isinstance(n, ast.ImportFrom) and any(a.name == "*" for a in n.names) for n in ast.walk(tree))
45
+ bound = _bound_names(tree)
46
+ known = bound | _BUILTINS | set(known_names)
47
+ reported: Set[str] = set()
48
+
49
+ for n in ast.walk(tree):
50
+ if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load) and not star:
51
+ if n.id in known or n.id in reported:
52
+ continue
53
+ reported.add(n.id)
54
+ hint = None
55
+ if n.id in STATEMENT_WORDS:
56
+ hint = f"'{n.id}' is a command - it must be at the start of a line."
57
+ elif n.id in ("null", "none", "nil", "undefined"):
58
+ hint = "Use 'nothing' for 'no value'."
59
+ elif n.id in ("True", "False", "None"):
60
+ hint = "Use lowercase: true, false, nothing."
61
+ else:
62
+ close = difflib.get_close_matches(n.id, sorted(known), n=1, cutoff=0.7)
63
+ hint = f"Did you mean '{close[0]}'?" if close else "Give it a value first, e.g.: set " + n.id + " = 0"
64
+ problems.append(MavrixError(
65
+ f"The name '{n.id}' is not defined", n.lineno, n.col_offset, n.col_offset + len(n.id), hint,
66
+ ))
67
+ # shadowing warnings
68
+ names = []
69
+ if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store):
70
+ names = [(n.id, n)]
71
+ elif isinstance(n, ast.FunctionDef):
72
+ names = [(n.name, n)]
73
+ elif isinstance(n, ast.arg):
74
+ names = [(n.arg, n)]
75
+ for name, node in names:
76
+ if name in _SHADOW_WARN:
77
+ problems.append(MavrixError(
78
+ f"The name '{name}' hides Python's built-in '{name}'", node.lineno, node.col_offset,
79
+ node.col_offset + len(name), f"Use a different name, or '{name}(...)' will stop working later.",
80
+ severity="warning",
81
+ ))
82
+ problems.sort(key=lambda d: (d.line, d.col))
83
+ return problems
mavrix/cli.py ADDED
@@ -0,0 +1,184 @@
1
+ """Command line interface: ``mavrix run | build | check | repl | tokens | ast | version``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import ast
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import List, Optional
10
+
11
+ from . import __version__
12
+ from .compiler import compile_source
13
+ from .diagnostics import CompileError, render
14
+ from .lexer import tokenize
15
+ from .runner import execute
16
+
17
+ HEADER = "# Generated by Mavrix {v} from {name}. Edit the .mvx file, not this one.\n"
18
+
19
+
20
+ def _read(path: str) -> str:
21
+ try:
22
+ return Path(path).read_text(encoding="utf-8")
23
+ except OSError as err:
24
+ print(f"error: cannot read '{path}': {err.strerror}", file=sys.stderr)
25
+ raise SystemExit(2)
26
+
27
+
28
+ def build_parser() -> argparse.ArgumentParser:
29
+ p = argparse.ArgumentParser(prog="mavrix", description="Mavrix - readable code that becomes Python.")
30
+ p.add_argument("--version", action="version", version=f"mavrix {__version__}")
31
+ sub = p.add_subparsers(dest="command")
32
+
33
+ run = sub.add_parser("run", help="run a .mvx program")
34
+ run.add_argument("file")
35
+ run.add_argument("args", nargs=argparse.REMAINDER, help="arguments passed to the program")
36
+ run.add_argument("--debug", action="store_true", help="also show the Python traceback on errors")
37
+ run.add_argument("--no-warnings", action="store_true", help="hide warnings")
38
+
39
+ build = sub.add_parser("build", help="translate .mvx files to .py files")
40
+ build.add_argument("files", nargs="+")
41
+ build.add_argument("-o", "--output", help="output path (single input only)")
42
+ build.add_argument("--print", action="store_true", dest="print_only", help="print the Python instead of saving")
43
+
44
+ check = sub.add_parser("check", help="look for mistakes without running")
45
+ check.add_argument("files", nargs="+")
46
+
47
+ tokens = sub.add_parser("tokens", help="show the tokens of a file (for learning/debugging)")
48
+ tokens.add_argument("file")
49
+ tree = sub.add_parser("ast", help="show the syntax tree of a file (for learning/debugging)")
50
+ tree.add_argument("file")
51
+
52
+ fmt = sub.add_parser("fmt", help="format .mvx files in the standard style")
53
+ fmt.add_argument("paths", nargs="+", help="files or folders")
54
+ fmt.add_argument("--check", action="store_true", help="change nothing; exit 1 if a file needs formatting")
55
+ fmt.add_argument("--diff", action="store_true", help="show what would change instead of writing")
56
+ fmt.add_argument("--stdout", action="store_true", help="print the formatted code instead of writing (one file)")
57
+
58
+ sub.add_parser("lsp", help="start the language server (stdio) for editors")
59
+ sub.add_parser("repl", help="start an interactive prompt")
60
+ sub.add_parser("version", help="show the version")
61
+ return p
62
+
63
+
64
+ def _compile(path: str):
65
+ source = _read(path)
66
+ try:
67
+ return compile_source(source, path), source
68
+ except CompileError as err:
69
+ print(err.render(source, path), file=sys.stderr)
70
+ return None, source
71
+
72
+
73
+ def _collect(paths: List[str]) -> List[Path]:
74
+ files: List[Path] = []
75
+ for raw in paths:
76
+ p = Path(raw)
77
+ if p.is_dir():
78
+ files.extend(sorted(p.rglob("*.mvx")))
79
+ else:
80
+ files.append(p)
81
+ return files
82
+
83
+
84
+ def _fmt(args) -> int:
85
+ import difflib
86
+ from .fmt import FormatError, format_source
87
+
88
+ files = _collect(args.paths)
89
+ if args.stdout and len(files) != 1:
90
+ print("error: --stdout needs exactly one file", file=sys.stderr)
91
+ return 2
92
+ status = 0
93
+ changed = 0
94
+ for path in files:
95
+ source = _read(str(path))
96
+ try:
97
+ result = format_source(source)
98
+ except FormatError as err:
99
+ print(f"error: {path}: {err}", file=sys.stderr)
100
+ status = 1
101
+ continue
102
+ if args.stdout:
103
+ sys.stdout.write(result)
104
+ continue
105
+ if result == source.replace("\r\n", "\n"):
106
+ continue
107
+ changed += 1
108
+ if args.diff:
109
+ sys.stdout.writelines(difflib.unified_diff(
110
+ source.splitlines(True), result.splitlines(True), f"{path} (before)", f"{path} (after)"))
111
+ elif args.check:
112
+ print(f"would reformat {path}")
113
+ else:
114
+ path.write_text(result, encoding="utf-8")
115
+ print(f"formatted {path}")
116
+ if (args.check or args.diff) and changed:
117
+ status = 1
118
+ if not args.stdout and not changed and status == 0:
119
+ print(f"{len(files)} file(s) already formatted.")
120
+ return status
121
+
122
+
123
+ def main(argv: Optional[List[str]] = None) -> int:
124
+ args = build_parser().parse_args(argv)
125
+ cmd = args.command or "repl"
126
+
127
+ if cmd == "version":
128
+ print(f"mavrix {__version__}")
129
+ return 0
130
+ if cmd == "repl":
131
+ from .repl import repl
132
+ return repl()
133
+ if cmd == "lsp":
134
+ from .lsp import serve
135
+ return serve()
136
+ if cmd == "fmt":
137
+ return _fmt(args)
138
+ if cmd == "run":
139
+ return execute(_read(args.file), args.file, debug=args.debug, warnings=not args.no_warnings,
140
+ argv=[args.file] + [a for a in args.args if a != "--"])
141
+ if cmd == "tokens":
142
+ try:
143
+ for t in tokenize(_read(args.file)):
144
+ print(t)
145
+ except Exception as err: # lexer errors
146
+ print(f"error: {err}", file=sys.stderr)
147
+ return 1
148
+ return 0
149
+
150
+ status = 0
151
+ if cmd == "ast":
152
+ comp, _ = _compile(args.file)
153
+ if comp is None:
154
+ return 1
155
+ print(ast.dump(comp.module, indent=2, include_attributes=False))
156
+ return 0
157
+ if cmd == "check":
158
+ for path in args.files:
159
+ comp, source = _compile(path)
160
+ if comp is None:
161
+ status = 1
162
+ continue
163
+ for w in comp.warnings:
164
+ print(render(w, source, path), file=sys.stderr)
165
+ print(f"OK - {path} has no errors" + (f" ({len(comp.warnings)} warning(s))." if comp.warnings else "."))
166
+ return status
167
+ if cmd == "build":
168
+ if args.output and len(args.files) > 1:
169
+ print("error: -o can only be used with one input file", file=sys.stderr)
170
+ return 2
171
+ for path in args.files:
172
+ comp, source = _compile(path)
173
+ if comp is None:
174
+ status = 1
175
+ continue
176
+ text = HEADER.format(v=__version__, name=Path(path).name) + comp.python()
177
+ if args.print_only:
178
+ sys.stdout.write(text)
179
+ continue
180
+ out = Path(args.output) if args.output else Path(path).with_suffix(".py")
181
+ out.write_text(text, encoding="utf-8")
182
+ print(f"Wrote {out}")
183
+ return status
184
+ return 0
mavrix/compiler.py ADDED
@@ -0,0 +1,44 @@
1
+ """Public compile API: source text -> Python AST / Python source / code object."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from dataclasses import dataclass, field
7
+ from typing import List
8
+
9
+ from .checker import check
10
+ from .diagnostics import CompileError, MavrixError
11
+ from .parser import parse
12
+
13
+
14
+ @dataclass
15
+ class Compilation:
16
+ source: str
17
+ filename: str
18
+ module: ast.Module
19
+ warnings: List[MavrixError] = field(default_factory=list)
20
+
21
+ def python(self) -> str:
22
+ """The generated, human-readable Python source."""
23
+ ast.fix_missing_locations(self.module)
24
+ return ast.unparse(self.module) + "\n"
25
+
26
+ def code(self, mode: str = "exec"):
27
+ """A runnable code object whose line numbers are Mavrix line numbers."""
28
+ ast.fix_missing_locations(self.module)
29
+ return compile(self.module, self.filename, mode)
30
+
31
+
32
+ def compile_source(source: str, filename: str = "<string>", known_names=()) -> Compilation:
33
+ """Parse and check ``source``. Raises :class:`CompileError` on errors."""
34
+ module = parse(source)
35
+ problems = check(module, known_names)
36
+ errors = [p for p in problems if p.severity == "error"]
37
+ if errors:
38
+ raise CompileError(errors + [p for p in problems if p.severity != "error"])
39
+ return Compilation(source, filename, module, [p for p in problems if p.severity != "error"])
40
+
41
+
42
+ def transpile(source: str, filename: str = "<string>") -> str:
43
+ """Convenience: Mavrix source in, Python source out."""
44
+ return compile_source(source, filename).python()
mavrix/diagnostics.py ADDED
@@ -0,0 +1,89 @@
1
+ """Error and warning objects, plus a pretty renderer with a caret under the problem."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from typing import List, Optional, Sequence
8
+
9
+
10
+ class MavrixError(Exception):
11
+ """One problem in Mavrix source code (a syntax error, a bad name, ...)."""
12
+
13
+ def __init__(
14
+ self,
15
+ message: str,
16
+ line: int = 0,
17
+ col: int = 0,
18
+ end_col: Optional[int] = None,
19
+ hint: Optional[str] = None,
20
+ severity: str = "error",
21
+ incomplete: bool = False,
22
+ ):
23
+ super().__init__(message)
24
+ self.message = message
25
+ self.line = line # 1-based, 0 = unknown
26
+ self.col = col # 0-based
27
+ self.end_col = end_col if end_col is not None else col + 1
28
+ self.hint = hint
29
+ self.severity = severity
30
+ self.incomplete = incomplete # "ran out of input" - the REPL asks for more lines
31
+
32
+ def __str__(self) -> str:
33
+ where = f" (line {self.line})" if self.line else ""
34
+ return f"{self.message}{where}"
35
+
36
+
37
+ class CompileError(Exception):
38
+ """Raised when a program has one or more errors."""
39
+
40
+ def __init__(self, diagnostics: Sequence[MavrixError]):
41
+ self.diagnostics: List[MavrixError] = list(diagnostics)
42
+ super().__init__(str(self.diagnostics[0]) if self.diagnostics else "compile error")
43
+
44
+ @property
45
+ def incomplete(self) -> bool:
46
+ return bool(self.diagnostics) and all(d.incomplete for d in self.diagnostics)
47
+
48
+ def render(self, source: str, filename: str = "<string>", color: Optional[bool] = None) -> str:
49
+ return "\n\n".join(render(d, source, filename, color) for d in self.diagnostics)
50
+
51
+
52
+ def use_color(stream=None) -> bool:
53
+ stream = stream or sys.stderr
54
+ if os.environ.get("NO_COLOR"):
55
+ return False
56
+ return hasattr(stream, "isatty") and stream.isatty()
57
+
58
+
59
+ def _paint(text: str, code: str, on: bool) -> str:
60
+ return f"\033[{code}m{text}\033[0m" if on else text
61
+
62
+
63
+ def render(diag: MavrixError, source: str, filename: str = "<string>", color: Optional[bool] = None) -> str:
64
+ """Format a diagnostic like this::
65
+
66
+ error: Expected 'then' after the condition
67
+ --> demo.mvx:2:21
68
+ |
69
+ 2 | if age is at least 18
70
+ | ^
71
+ = hint: Add the word 'then'.
72
+ """
73
+ on = use_color() if color is None else color
74
+ red = "1;31" if diag.severity == "error" else "1;33"
75
+ lines = source.splitlines()
76
+ out = [f"{_paint(diag.severity, red, on)}: {_paint(diag.message, '1', on)}"]
77
+ if diag.line:
78
+ width = len(str(diag.line))
79
+ pad = " " * width
80
+ out.append(f"{pad}{_paint('-->', '1;34', on)} {filename}:{diag.line}:{diag.col + 1}")
81
+ out.append(f"{pad} {_paint('|', '1;34', on)}")
82
+ text = lines[diag.line - 1] if 0 < diag.line <= len(lines) else ""
83
+ out.append(f"{_paint(str(diag.line), '1;34', on)} {_paint('|', '1;34', on)} {text}")
84
+ length = max(1, min(diag.end_col, max(len(text), diag.col + 1)) - diag.col)
85
+ out.append(f"{pad} {_paint('|', '1;34', on)} {' ' * diag.col}{_paint('^' * length, red, on)}")
86
+ if diag.hint:
87
+ pad = " " * (len(str(diag.line)) if diag.line else 1)
88
+ out.append(f"{pad} {_paint('=', '1;34', on)} {_paint('hint:', '1;32', on)} {diag.hint}")
89
+ return "\n".join(out)
mavrix/fmt.py ADDED
@@ -0,0 +1,249 @@
1
+ """``mavrix fmt``: one consistent style for every Mavrix program.
2
+
3
+ Rules: 4-space indentation per block, one space around operators and after commas,
4
+ no space inside brackets, two spaces before a trailing comment, at most one blank
5
+ line in a row, no trailing whitespace, one final newline.
6
+
7
+ Safety first: the formatter only runs on programs that compile, and it checks that
8
+ the formatted program has exactly the same syntax tree as the original. If that
9
+ check ever failed it would fall back to a gentler "indent only" mode, and finally
10
+ refuse - it never changes what a program does.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import ast
16
+ from dataclasses import dataclass
17
+ from typing import List, Optional
18
+
19
+ from .diagnostics import CompileError
20
+ from .lexer import COMMENT, EOF, NAME, NEWLINE, OP, STRING, Token, tokenize
21
+ from .parser import ASSIGN_OPS, ALL_END_WORDS, parse
22
+
23
+ INDENT = " "
24
+ OPENERS = {"if", "while", "repeat", "for", "count", "define", "class", "try", "with"}
25
+ # words that are followed by an expression (so '-' after them is a sign, and '(' gets a space)
26
+ EXPR_WORDS = {
27
+ "say", "if", "while", "ensure", "fail", "with", "for", "in", "and", "or", "not", "is", "to", "by", "as",
28
+ "from", "step", "times", "else", "otherwise", "then", "contains", "mod", "of", "each", "back", "delete",
29
+ "than", "least", "most", "equal", "do", "use", "repeat", "set",
30
+ }
31
+
32
+
33
+ class FormatError(Exception):
34
+ """The program cannot be formatted (usually because it has errors)."""
35
+
36
+
37
+ @dataclass
38
+ class _Line:
39
+ toks: List[Token]
40
+ first: int
41
+ last: int
42
+ kind: str = "code" # code | comment
43
+ role: str = "plain" # open | mid | end | plain
44
+ depth: int = 0
45
+
46
+
47
+ # ----------------------------------------------------------------------- roles
48
+ def _role(ts: List[Token]) -> str:
49
+ t0 = ts[0]
50
+ if t0.kind != NAME:
51
+ return "plain"
52
+ w = t0.value
53
+ nxt = ts[1] if len(ts) > 1 else None
54
+ if w == "end":
55
+ if nxt is None or (nxt.kind == NAME and nxt.value in ALL_END_WORDS and len(ts) == 2):
56
+ return "end"
57
+ return "plain"
58
+ if w in ("otherwise", "else"):
59
+ return "mid"
60
+ if w == "on" and nxt is not None and nxt.kind == NAME and nxt.value == "error":
61
+ return "mid"
62
+ if w == "always" and len(ts) == 1:
63
+ return "mid"
64
+ if w in OPENERS:
65
+ if nxt is not None and nxt.kind == OP and nxt.value in ASSIGN_OPS | {".", ","}:
66
+ return "plain"
67
+ if w == "count":
68
+ ok = len(ts) > 2 and nxt.kind == NAME and ts[2].kind == NAME and ts[2].value == "from"
69
+ return "open" if ok else "plain"
70
+ return "open"
71
+ return "plain"
72
+
73
+
74
+ # ------------------------------------------------------------------- spacing
75
+ def _is_word(ts: List[Token], i: int) -> bool:
76
+ t = ts[i]
77
+ if t.kind != NAME or t.value not in EXPR_WORDS:
78
+ return False
79
+ return not (i > 0 and ts[i - 1].kind == OP and ts[i - 1].value == ".") # obj.to(...) is a plain name
80
+
81
+
82
+ def render(ts: List[Token]) -> str:
83
+ """Rebuild one statement from its tokens with canonical spacing."""
84
+ out: List[str] = []
85
+ stack: List[str] = []
86
+ unary_pending = False
87
+ for i, t in enumerate(ts):
88
+ prev = ts[i - 1] if i else None
89
+ v = t.value
90
+ space = prev is not None
91
+ if prev is not None:
92
+ pv = prev.value
93
+ top = stack[-1] if stack else ""
94
+ if unary_pending:
95
+ space = False
96
+ elif t.kind == OP and v in ")]},":
97
+ space = False
98
+ elif prev.kind == OP and pv in "([{":
99
+ space = False
100
+ elif (t.kind == OP and v == ".") or (prev.kind == OP and pv == "."):
101
+ space = False
102
+ elif t.kind == OP and v == ":":
103
+ space = top not in "{[(" or top == ""
104
+ elif prev.kind == OP and pv == ":":
105
+ space = top == "{" or top == ""
106
+ elif t.kind == OP and v in ("(", "["):
107
+ if prev.kind == NAME:
108
+ space = _is_word(ts, i - 1)
109
+ elif prev.kind == STRING or (prev.kind == OP and pv in ")]}"):
110
+ space = False
111
+ elif t.kind == OP and v == "=" and top == "(":
112
+ space = False
113
+ elif prev.kind == OP and pv == "=" and top == "(":
114
+ space = False
115
+ if space:
116
+ out.append(" ")
117
+ out.append(v)
118
+ # bracket stack
119
+ if t.kind == OP and v in "([{":
120
+ stack.append(v)
121
+ elif t.kind == OP and v in ")]}" and stack:
122
+ stack.pop()
123
+ # is this operator a sign / star (unary)?
124
+ unary_pending = False
125
+ if t.kind == OP and v in ("-", "+", "~", "*", "**"):
126
+ if prev is None or (prev.kind == OP and prev.value not in (")", "]", "}")) or _is_word(ts, i - 1):
127
+ unary_pending = True
128
+ return "".join(out)
129
+
130
+
131
+ # ------------------------------------------------------------------ the pass
132
+ def _indent_of(line: str) -> int:
133
+ return len(line.expandtabs(4)) - len(line.expandtabs(4).lstrip())
134
+
135
+
136
+ def _logical_lines(source: str) -> List[_Line]:
137
+ groups: List[List[Token]] = []
138
+ cur: List[Token] = []
139
+ for t in tokenize(source, keep_comments=True):
140
+ if t.kind == NEWLINE:
141
+ if cur:
142
+ groups.append(cur)
143
+ cur = []
144
+ elif t.kind == EOF:
145
+ break
146
+ else:
147
+ cur.append(t)
148
+ if cur:
149
+ groups.append(cur)
150
+ result = []
151
+ for g in groups:
152
+ ln = _Line(g, g[0].line, max(t.end_line for t in g))
153
+ if len(g) == 1 and g[0].kind == COMMENT:
154
+ ln.kind = "comment"
155
+ else:
156
+ code = [t for t in g if t.kind != COMMENT]
157
+ ln.role = _role(code)
158
+ result.append(ln)
159
+ return result
160
+
161
+
162
+ def _format(source: str, full: bool) -> str:
163
+ lines = source.replace("\r\n", "\n").replace("\r", "\n").split("\n")
164
+ items = _logical_lines(source)
165
+
166
+ depth = 0
167
+ for it in items:
168
+ if it.kind != "code":
169
+ continue
170
+ if it.role == "end":
171
+ depth = max(0, depth - 1)
172
+ it.depth = depth
173
+ elif it.role == "mid":
174
+ it.depth = max(0, depth - 1)
175
+ elif it.role == "open":
176
+ it.depth = depth
177
+ depth += 1
178
+ else:
179
+ it.depth = depth
180
+ # comments take the indentation of the code that follows
181
+ for idx, it in enumerate(items):
182
+ if it.kind != "comment":
183
+ continue
184
+ nxt = next((x for x in items[idx + 1:] if x.kind == "code"), None)
185
+ if nxt is None:
186
+ it.depth = depth
187
+ continue
188
+ it.depth = nxt.depth
189
+ if nxt.role in ("end", "mid") and _indent_of(lines[it.first - 1]) > _indent_of(lines[nxt.first - 1]):
190
+ it.depth = nxt.depth + 1 # comment belongs to the block that is closing
191
+
192
+ out: List[str] = []
193
+ prev: Optional[_Line] = None
194
+ for it in items:
195
+ gap = (it.first - prev.last - 1) if prev else 0
196
+ if gap > 0 and prev is not None and not (prev.kind == "code" and prev.role == "open") \
197
+ and not (it.kind == "code" and it.role == "end"):
198
+ out.append("")
199
+ prev = it
200
+ indent = INDENT * it.depth
201
+ if it.kind == "comment":
202
+ out.append(indent + it.toks[0].value.strip())
203
+ continue
204
+ multi = it.last > it.first
205
+ first_text = lines[it.first - 1]
206
+ if multi:
207
+ # keep the layout the author chose for statements that span several lines
208
+ out.append(indent + first_text.strip())
209
+ has_multiline_text = any(t.kind == STRING and t.end_line > t.line for t in it.toks)
210
+ delta = len(indent) - _indent_of(first_text)
211
+ for n in range(it.first + 1, it.last + 1):
212
+ raw = lines[n - 1]
213
+ if has_multiline_text:
214
+ out.append(raw)
215
+ elif raw.strip():
216
+ out.append(" " * max(0, _indent_of(raw) + delta) + raw.strip())
217
+ else:
218
+ out.append("")
219
+ continue
220
+ code = [t for t in it.toks if t.kind != COMMENT]
221
+ comment = it.toks[-1].value if it.toks[-1].kind == COMMENT else ""
222
+ if full:
223
+ text = render(code) + (" " + comment if comment else "")
224
+ else:
225
+ text = first_text.strip()
226
+ out.append(indent + text)
227
+ while out and out[0] == "":
228
+ out.pop(0)
229
+ return ("\n".join(out) + "\n") if out else ""
230
+
231
+
232
+ def _same_tree(a: str, b: str) -> bool:
233
+ return ast.dump(parse(a)) == ast.dump(parse(b))
234
+
235
+
236
+ def format_source(source: str) -> str:
237
+ """Return the formatted program. Raises :class:`FormatError` for programs with errors."""
238
+ try:
239
+ parse(source)
240
+ except CompileError as err:
241
+ raise FormatError(f"cannot format a program with errors (first: {err.diagnostics[0]})") from None
242
+ for full in (True, False):
243
+ try:
244
+ result = _format(source, full)
245
+ if _same_tree(source, result):
246
+ return result
247
+ except CompileError:
248
+ continue
249
+ raise FormatError("internal error: could not format this program safely (it was left unchanged)")