clove/code4dyslexia
src/python_adapter.py
# src/python_adapter.py
import ast
import codecs
import io
import json
import re
import sys
import tokenize
if sys.version_info < (3, 11):
raise SystemExit("C4D requires Python 3.11 or newer")
INDENT = "formatting.indentSize"
NEWLINES = "formatting.newLineSize"
HEADER = "formatting.filePathHeader"
COMPOUND = (
ast.FunctionDef,
ast.AsyncFunctionDef,
ast.ClassDef,
ast.If,
ast.For,
ast.AsyncFor,
ast.While,
ast.Try,
ast.TryStar,
ast.With,
ast.AsyncWith,
ast.Match,
)
ENCODING = re.compile(r"^[ \t\f]*#.*?coding[:=][ \t]*[-\w.]+")
def document_lines(source):
# CPython normalizes physical CRLF line endings on parsing.
return re.findall(r"[^\n]*\n|[^\n]+$", source)
def indentation(tokens, lines, starts, width):
depth = 0
at_start = True
for token in tokens:
kind = token.type
if kind == tokenize.INDENT:
depth += 1
elif kind == tokenize.DEDENT:
depth -= 1
elif kind == tokenize.NEWLINE:
at_start = True
elif kind in (tokenize.NL, tokenize.COMMENT, tokenize.ENCODING, tokenize.ENDMARKER):
continue
elif at_start:
at_start = False
row, column = token.start
start = starts[row - 1]
prefix = lines[row - 1][:column]
wanted = " " * (depth * width)
if prefix != wanted and not prefix.strip(" \t"):
yield (start, start + column, wanted, INDENT, f"Expected {len(wanted)} space(s) of indentation")
def statement_start(statement):
decorators = getattr(statement, "decorator_list", ())
return min((decorator.lineno for decorator in decorators), default=statement.lineno)
def block_spacing(tree, source, starts, width):
for node in ast.walk(tree):
for _, field in ast.iter_fields(node):
if not isinstance(field, list) or not field or not isinstance(field[0], ast.stmt):
continue
for left, right in zip(field, field[1:]):
if not isinstance(left, COMPOUND) and not isinstance(right, COMPOUND):
continue
right_line = statement_start(right)
if left.end_lineno >= right_line:
continue
line_start = starts[left.end_lineno - 1]
end = starts[right_line - 1]
left_line = source[line_start:starts[left.end_lineno]]
start = line_start + len(left_line.encode()[:left.end_col_offset].decode())
gap = source[start:end]
count = gap.count("\n")
if count and count != width and not gap.strip(" \t\r\n"):
ending = "\r\n" if gap.partition("\n")[0].endswith("\r") else "\n"
yield (start, end, ending * width, NEWLINES, f"Expected {width} newline character(s) between logical blocks")
def file_header(lines, starts, path):
comment = "# " + path
if ENCODING.match(comment):
comment = comment.replace("coding:", r"coding\:").replace("coding=", r"coding\=")
for line in lines:
text = line.strip()
if text == comment:
return None
if text and not text.startswith("#"):
break
count = int(bool(lines and lines[0].startswith("#!")))
for index, line in enumerate(lines[:2]):
if ENCODING.match(line) and (index == 0 or lines[0].lstrip().startswith("#") or not lines[0].strip()):
count = index + 1
break
leading = "\r\n" if lines and lines[0].endswith("\r\n") else "\n"
separation = leading if count and not lines[count - 1].endswith("\n") else ""
return (starts[count], starts[count], separation + comment + leading, HEADER, f"Expected file path header {comment}")
def naming(tree, lines, starts, tokens):
token_names = {}
previous = None
for token in tokens:
if previous and previous.string in ("def", "class") and token.type == tokenize.NAME:
row, column = token.start
token_names[previous.start[0]] = starts[row - 1] + column
previous = token
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
category = "classes" if isinstance(node, ast.ClassDef) else "functions"
yield (token_names.get(node.lineno, starts[node.lineno - 1]), category, node.name)
elif isinstance(node, ast.arg) or (isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store)):
name = node.arg if isinstance(node, ast.arg) else node.id
column = len(lines[node.lineno - 1].encode()[:node.col_offset].decode())
yield (starts[node.lineno - 1] + column, "variables", name)
def analyze(request):
original = request["source"]
source = original.removeprefix("\ufeff")
bom = original[:len(original) - len(source)]
if re.search(r"\r(?!\n)", source):
raise SyntaxError("Python source must use LF or CRLF line endings")
raw = original.encode()
encoding, _ = tokenize.detect_encoding(io.BytesIO(raw).readline)
if codecs.lookup(encoding).name not in ("utf-8", "utf-8-sig", "ascii"):
raise SyntaxError("C4D supports only UTF-8 Python source")
tree = ast.parse(raw, type_comments=True)
tokens = list(tokenize.tokenize(io.BytesIO(raw).readline))
lines = document_lines(source)
starts = [0]
for line in lines:
starts.append(starts[-1] + len(line))
edits = []
if request["indent"]:
edits.extend(indentation(tokens, lines, starts, request["indent"]))
if request["newlines"]:
edits.extend(block_spacing(tree, source, starts, request["newlines"]))
if request["header"]:
header = file_header(lines, starts, request["path"])
if header:
edits.append(header)
sections = [bom]
previous = 0
for start, end, replacement, _, _ in sorted(edits):
sections.extend((source[previous:start], replacement))
previous = end
sections.append(source[previous:])
formatted = "".join(sections)
if edits:
proposed = ast.parse(formatted.encode(), type_comments=True)
for item in (*tree.type_ignores, *proposed.type_ignores):
item.lineno = 0
if ast.dump(tree) != ast.dump(proposed):
raise SyntaxError("Formatting would change the Python syntax tree")
names = list(naming(tree, lines, starts, tokens)) if request["names"] else []
positions = {start for start, _, _, _, _ in edits}
positions.update(offset for offset, _, _ in names)
byte_offsets = {}
position = 0
total = len(bom.encode())
for offset in sorted(positions):
total += len(source[position:offset].encode())
byte_offsets[offset] = total
position = offset
return {
"formatted": formatted,
"issues": [
{"offset": byte_offsets[start], "rule": rule, "message": message}
for start, _, _, rule, message in edits
],
"names": [
(byte_offsets[offset], category, name)
for offset, category, name in names
],
}
try:
print(json.dumps(analyze(json.load(sys.stdin))))
except (SyntaxError, tokenize.TokenError, UnicodeError) as error:
print(json.dumps({
"error": getattr(error, "msg", str(error)),
"line": getattr(error, "lineno", None) or 1,
"column": getattr(error, "offset", None) or 1,
}))