lsp-bjolang/test/smoke.py
Linus Björnstam 78d18c9854 Hover on fields, and on locals of record types
A field read shows the field's type and its declaration; a local of a
record, struct or union type shows the type. Structs and opaque types get
their symbols, and the file's own types drop their module qualifier.
2026-11-03 14:45:55 +01:00

1323 lines
49 KiB
Python
Executable file

#!/usr/bin/env python3
"""Talks to the server as an editor would, over stdin and stdout, and checks
what it answers. One server process for every case, so that a second check
in the same process is tested too.
test/smoke.py # builds nothing; run `dotnet build -c Release` first
"""
import json
import os
import subprocess
import sys
import tempfile
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SERVER = os.path.join(ROOT, "bin", "Release", "net10.0", "BjolangLsp.dll")
def frame(message):
body = json.dumps(message).encode()
return b"Content-Length: %d\r\n\r\n" % len(body) + body
def read(stream):
length = None
while True:
line = stream.readline()
if not line:
raise EOFError("server closed stdout")
line = line.strip()
if not line:
break
name, _, value = line.decode().partition(":")
if name.lower() == "content-length":
length = int(value)
return json.loads(stream.read(length))
class Server:
def __init__(self):
self.proc = subprocess.Popen(
["dotnet", SERVER], stdin=subprocess.PIPE, stdout=subprocess.PIPE
)
self.next_id = 0
# Notifications read while waiting for something else: a check that
# fell due can publish between a request and its answer.
self.pending = []
def send(self, method, params=None, request=False):
message = {"jsonrpc": "2.0", "method": method, "params": params or {}}
if request:
self.next_id += 1
message["id"] = self.next_id
self.proc.stdin.write(frame(message))
self.proc.stdin.flush()
if not request:
return None
while True:
answer = read(self.proc.stdout)
if answer.get("id") == self.next_id:
return answer
self.pending.append(answer)
def change(self, uri, text, version):
self.send(
"textDocument/didChange",
{"textDocument": {"uri": uri, "version": version}, "contentChanges": [{"text": text}]},
)
def published(self, uri):
"""The diagnostics for `uri` among the notifications already read, as
a list of their diagnostics lists, and takes them out."""
mine = [
m for m in self.pending
if m.get("method") == "textDocument/publishDiagnostics" and m["params"]["uri"] == uri
]
self.pending = [m for m in self.pending if m not in mine]
return [m["params"]["diagnostics"] for m in mine]
def next_diagnostics(self, uri):
"""The next diagnostics published for `uri`, waiting for them if
none has come yet."""
earlier = self.published(uri)
if earlier:
return earlier[0]
while True:
message = read(self.proc.stdout)
if message.get("method") == "textDocument/publishDiagnostics" and message["params"]["uri"] == uri:
return message["params"]["diagnostics"]
self.pending.append(message)
def diagnostics_after(self, method, uri, text=None):
doc = {"uri": uri}
if text is not None:
doc.update(languageId="bjolang", version=1, text=text)
self.published(uri) # anything older is not the answer to this
self.send(method, {"textDocument": doc})
return self.next_diagnostics(uri)
failures = 0
def expect(name, ok, detail=""):
global failures
print(("ok: " if ok else "FAIL: ") + name + ("" if ok else f"\n {detail}"))
if not ok:
failures += 1
BROKEN = """(import (std prelude))
(: main (-> (Vec string) int))
(defun (main args)
(+ 1 "two"))
"""
FIXED = """(import (std prelude))
(: main (-> (Vec string) int))
(defun (main args)
(+ 1 2))
"""
UNCLOSED = """(import (std prelude))
(defun (main args)
(+ 1 2)
"""
SYMBOLS = """(import (std prelude))
(type (: Shape (Union (Circle int) (Square int) Empty)))
(type (: Point (Record (: x int) (: y int))))
(def/trait (Area %a)
(: area (-> %a int)))
(impl (Area Shape)
(defun (area s)
(match s
((Circle r) (* 3 (* r r)))
((Square a) (* a a))
(Empty 0))))
(def unit-size 1)
(: double (-> int int))
(defun (double n) (* 2 n))
(: main (-> (Vec string) int))
(defun (main args)
(double (area (Circle unit-size)))
(list-map double (list 1 2 3))
0)
"""
def position_of(text, needle, nth=0, offset=1):
"""The LSP position `offset` characters into the `nth` occurrence of
`needle` in `text`."""
at = -1
for _ in range(nth + 1):
at = text.index(needle, at + 1)
at += offset
line = text.count("\n", 0, at)
return {"line": line, "character": at - (text.rfind("\n", 0, at) + 1)}
def line_of(text, needle):
return text.count("\n", 0, text.index(needle))
def names(symbols):
return [(s["name"], names(s.get("children", []))) for s in symbols]
def symbols_and_definitions(server, tmp):
path = os.path.join(tmp, "symbols.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(SYMBOLS)
server.diagnostics_after("textDocument/didOpen", uri, SYMBOLS)
found = server.send("textDocument/documentSymbol", {"textDocument": {"uri": uri}}, request=True)["result"]
expect(
"the outline",
names(found)
== [
("Shape", [("Circle", []), ("Square", []), ("Empty", [])]),
("Point", [("x", []), ("y", [])]),
("Area", [("area", [])]),
("impl (Area Shape)", [("area", [])]),
("unit-size", []),
("double", []),
("main", []),
],
names(found),
)
def definition(text, needle, offset=1):
answer = server.send(
"textDocument/definition",
{"textDocument": {"uri": uri}, "position": position_of(text, needle, 0, offset)},
request=True,
)
return answer["result"]
d = definition(SYMBOLS, "(double (area")
expect(
"a name defined in the file",
d and d["uri"] == uri and d["range"]["start"]["line"] == line_of(SYMBOLS, "(defun (double"),
d,
)
d = definition(SYMBOLS, "(Circle unit-size")
expect(
"a constructor",
d and d["range"]["start"]["line"] == line_of(SYMBOLS, "(type (: Shape"),
d,
)
d = definition(SYMBOLS, "(list-map")
expect("a name from the prelude", d and d["uri"].endswith("/lib/std/prelude.bjo"), d)
# `n` is a parameter: it goes to where the parameter is written.
d = definition(SYMBOLS, "(* 2 n)", 5)
expect(
"a parameter goes to the parameter",
d and d["range"]["start"] == position_of(SYMBOLS, "(defun (double n)", 0, 15),
d,
)
def hover(text, needle, offset=1):
answer = server.send(
"textDocument/hover",
{"textDocument": {"uri": uri}, "position": position_of(text, needle, 0, offset)},
request=True,
)
result = answer["result"]
return result["contents"]["value"] if result else None
h = hover(SYMBOLS, "(double (area")
expect(
"hover: the declaration and the head",
h and "(: double (-> int int))" in h and "(defun (double n))" in h,
h,
)
h = hover(SYMBOLS, "(Circle unit-size")
expect("hover: a constructor's case and type", h and "(Circle int)" in h and "A case of `Shape`" in h, h)
h = hover(SYMBOLS, "(list-map")
expect(
"hover: the prelude's doc",
h and "Applies a function to each element of a list." in h and "**Parameters**" in h,
h,
)
h = hover(SYMBOLS, "(* 2 n)", 5)
expect("hover: a parameter says whose", h and "*A parameter of `double`.*" in h, h)
# Unsaved: the buffer gains a definition the file on disk does not have.
changed = SYMBOLS + "\n(defun (triple n) (* 3 n))\n(def nine (triple 3))\n"
server.send(
"textDocument/didChange",
{"textDocument": {"uri": uri, "version": 2}, "contentChanges": [{"text": changed}]},
)
d = definition(changed, "(triple 3)")
expect(
"the buffer, not the file",
d and d["range"]["start"]["line"] == line_of(changed, "(defun (triple"),
d,
)
found = server.send("textDocument/documentSymbol", {"textDocument": {"uri": uri}}, request=True)["result"]
expect("the outline follows the buffer", [n for n, _ in names(found)][-2:] == ["triple", "nine"], names(found))
# Half typed: the outline stays as it was rather than emptying.
server.send(
"textDocument/didChange",
{"textDocument": {"uri": uri, "version": 3}, "contentChanges": [{"text": changed + "(defun (half"}]},
)
found = server.send("textDocument/documentSymbol", {"textDocument": {"uri": uri}}, request=True)["result"]
expect(
"a half-typed form is read as if closed",
[n for n, _ in names(found)][-3:] == ["triple", "nine", "half"],
names(found),
)
# A stray closer cannot be mended by closing: the last outline stays.
server.send(
"textDocument/didChange",
{"textDocument": {"uri": uri, "version": 4}, "contentChanges": [{"text": changed + ")"}]},
)
found = server.send("textDocument/documentSymbol", {"textDocument": {"uri": uri}}, request=True)["result"]
expect(
"text that does not read keeps the last outline",
[n for n, _ in names(found)][-3:] == ["triple", "nine", "half"],
names(found),
)
server.diagnostics_after("textDocument/didClose", uri)
DOCUMENTED = """(import (std prelude))
(:doc #:file "documented.bjodoc")
(: squeeze (-> int int int int))
(defun (squeeze lo hi x) (max lo (min hi x)))
(: main (-> (Vec string) int))
(defun (main args) (squeeze 0 10 12))
"""
DOCUMENTED_DOC = '''(:doc squeeze
(summary "@code{x}, kept @strong{between} @em{lo} and hi.")
(arg lo "The least.")
(arg hi "The most.")
(arg x "The value.")
(returns "One of: @itemlist{@item{@code{lo}} @item{@code{hi}} @item{x}}")
(example """
(squeeze 0 10 12) ; 10
"""))
'''
def documented(server, tmp):
path = os.path.join(tmp, "documented.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(DOCUMENTED)
with open(os.path.join(tmp, "documented.bjodoc"), "w") as f:
f.write(DOCUMENTED_DOC)
found = server.diagnostics_after("textDocument/didOpen", uri, DOCUMENTED)
expect("the documented file checks", found == [], found)
answer = server.send(
"textDocument/hover",
{"textDocument": {"uri": uri}, "position": position_of(DOCUMENTED, "(squeeze 0")},
request=True,
)
h = answer["result"]["contents"]["value"] if answer["result"] else None
expect(
"hover: a doc from a .bjodoc, its markup as Markdown",
h
and "`x`, kept **between** *lo* and hi." in h
and "- `lo`: The least." in h
and "**Returns** One of:\n- `lo`\n- `hi`\n- x" in h
and "(squeeze 0 10 12) ; 10" in h,
h,
)
server.diagnostics_after("textDocument/didClose", uri)
CONSTRAINED = """(import (std prelude)
(std datetime))
(def/trait (Sized %a)
(: size (-> %a int)))
(impl (Sized string)
(defun (size s) (string-length s)))
(: (-> %a int) (where (Sized %a)))
(defun (twice x) (* 2 (size x)))
(: main (-> (Vec string) int))
(defun (main args)
(ignore (+milliseconds (now) 5L))
(twice "ab"))
"""
def constrained(server, tmp):
path = os.path.join(tmp, "constrained.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(CONSTRAINED)
found = server.diagnostics_after("textDocument/didOpen", uri, CONSTRAINED)
expect("the constrained file checks", found == [], found)
def hover(needle):
answer = server.send(
"textDocument/hover",
{"textDocument": {"uri": uri}, "position": position_of(CONSTRAINED, needle)},
request=True,
)
return answer["result"]["contents"]["value"] if answer["result"] else None
h = hover("(twice \"ab")
expect(
"hover: a nameless signature with a where clause, named",
h and "(: twice (-> %a int) (where (Sized %a)))" in h and "(defun (twice x))" in h,
h,
)
h = hover("(+milliseconds")
expect(
"hover: an imported one with a where clause",
h and "(: +milliseconds (-> %a long %a) (where (TimeArith %a)))" in h,
h,
)
server.diagnostics_after("textDocument/didClose", uri)
COMPLETING = """(import (std prelude))
(defun (list-unwind xs) xs)
(: main (-> (Vec string) int))
(defun (main args)
;; list-u
(list-u
"""
def completing(server, tmp):
path = os.path.join(tmp, "completing.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(COMPLETING)
server.diagnostics_after("textDocument/didOpen", uri, COMPLETING)
def complete(needle, nth=0):
at = position_of(COMPLETING, needle, nth, len(needle))
answer = server.send(
"textDocument/completion", {"textDocument": {"uri": uri}, "position": at}, request=True
)
return at, answer["result"]["items"]
at, items = complete("(list-u", 0)
labels = {i["label"]: i for i in items}
expect(
"completion: the file's own name and the prelude's",
"list-unwind" in labels and "list-unfold" in labels,
sorted(labels)[:20],
)
expect(
"completion: only names starting with the word's first letter, in either case",
all(l[0] in "lL" for l in labels),
sorted(labels)[:20],
)
own = labels.get("list-unwind", {})
expect(
"completion: the item replaces the whole word",
own.get("textEdit", {}).get("range", {}).get("start") == {"line": at["line"], "character": at["character"] - 6},
own,
)
expect(
"completion: the file's own names sort first",
own.get("sortText", "").startswith("1") and labels["list-unfold"]["sortText"].startswith("2"),
(own.get("sortText"), labels.get("list-unfold", {}).get("sortText")),
)
resolved = server.send("completionItem/resolve", labels["list-unfold"], request=True)["result"]
doc = resolved.get("documentation", {}).get("value", "")
expect("completion: resolve adds the doc", "A list generated from a state." in doc, doc)
_, items = complete(";; list-u")
expect("completion: none in a comment", items == [], [i["label"] for i in items][:10])
# A builtin: no source to define it, but a type and a doc.
seq_text = COMPLETING.replace("(list-u\n", "(seq-unfold\n")
server.send(
"textDocument/didChange",
{"textDocument": {"uri": uri, "version": 2}, "contentChanges": [{"text": seq_text}]},
)
answer = server.send(
"textDocument/hover",
{"textDocument": {"uri": uri}, "position": position_of(seq_text, "(seq-unfold")},
request=True,
)
h = answer["result"]["contents"]["value"] if answer["result"] else None
expect(
"hover: a builtin's type and doc",
h and "(: seq-unfold (->" in h and "A sequence generated from a state, lazily." in h,
h,
)
server.diagnostics_after("textDocument/didClose", uri)
LOCALS = """(import (std prelude))
(: total (-> (List int) int int))
(defun (total xs (: bonus int))
(def base 10)
(let ((doubled (list-map (fun (x) (* 2 x)) xs))
(count 0))
(match doubled
((Cons first rest) (+ first bonus base count))
(Nil (loop (:for y xs)
(:acc sum (summing (+ y bonus)))
=> sum)))))
(: shadow (-> int int))
(defun (shadow v)
(let ((v (+ v 1)))
v))
(: typing (-> int int))
(defun (typing amount)
(let ((amplified (* amount 2)))
(+ am
"""
def locals_(server, tmp):
path = os.path.join(tmp, "locals.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(LOCALS)
server.diagnostics_after("textDocument/didOpen", uri, LOCALS)
def ask(method, needle, offset=1, nth=0):
at = position_of(LOCALS, needle, nth, offset)
return server.send(method, {"textDocument": {"uri": uri}, "position": at}, request=True)["result"]
def goes_to(needle, target, target_offset, offset=1, nth=0):
d = ask("textDocument/definition", needle, offset, nth)
return d and d["range"]["start"] == position_of(LOCALS, target, 0, target_offset), d
cases = [
("a parameter", "bonus base", "(: bonus int)", 3),
("a def in the body", "base count", "(def base", 5),
("a let binding", "doubled\n", "(doubled (list-map", 1),
("a fun's parameter", "x)) xs", "(fun (x)", 6),
("a match pattern's variable", "first bonus", "(Cons first", 6),
("a loop variable, from its :acc", "y bonus", "(:for y", 6),
("an accumulator, from =>", "sum)))))", "(:acc sum", 6),
("the inner of two of a name", "v))\n", "((v (+ v 1)))", 2),
("the outer, in the inner's value", "v 1)", "(shadow v)", 8),
]
for name, needle, target, target_offset in cases:
ok, d = goes_to(needle, target, target_offset, 0)
expect("local definition: " + name, ok, d)
h = ask("textDocument/hover", "bonus base", 0)
h = h and h["contents"]["value"]
expect("local hover: a typed parameter shows its type", h and "(: bonus int)" in h and "A parameter of `total`" in h, h)
h = ask("textDocument/hover", "first bonus", 0)
h = h and h["contents"]["value"]
expect("local hover: a pattern shows the pattern", h and "(Cons first rest)" in h and "`match` pattern" in h, h)
# Completion while the form is being typed: the locals of `typing`, and
# nothing of `total`'s.
at = position_of(LOCALS, "(+ am", 0, 5)
items = server.send("textDocument/completion", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"]["items"]
labels = {i["label"]: i for i in items}
expect(
"local completion: what is in scope, first",
labels.get("amount", {}).get("sortText", "").startswith("0")
and labels.get("amplified", {}).get("sortText", "").startswith("0"),
sorted((l, i["sortText"]) for l, i in labels.items())[:10],
)
expect("local completion: another function's locals are not", "doubled" not in labels and "bonus" not in labels, sorted(labels)[:10])
doc = labels.get("amplified", {}).get("documentation", {}).get("value", "")
expect("local completion: its doc comes along", "(amplified (* amount 2))" in doc, doc)
server.diagnostics_after("textDocument/didClose", uri)
INFERRED = """(import (std prelude))
(: total (-> (List int) int))
(defun (total xs)
(let ((pairs (list-map (fun (x) (Tuple x "s")) xs)))
(match (first pairs)
((Some (Tuple n label)) (+ n (string-count label)))
(None (loop (:for y xs) (:acc sum (summing y)) => sum)))))
(: lengths (-> (Vec string) (Vec int)))
(defun (lengths names)
(defun (twice s) (* 2 (string-count s)))
(vec-map twice names))
(: annotated (-> int int))
(defun (annotated k)
(def (: m int) (+ k 1))
(def bumped (+ m 1))
bumped)
(def numbers (list 4 5 6))
"""
# One declaration that does not check, and one that does.
INFERRED_BROKEN = INFERRED.replace('(Tuple x "s")', '(+ x "s")')
# The same, with what `pairs` holds changed and not saved.
INFERRED_EDITED = INFERRED.replace('(Tuple x "s")', '(Tuple x 2.5)').replace("(string-count label)", "1")
def inferred(server, tmp):
path = os.path.join(tmp, "inferred.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(INFERRED)
found = server.diagnostics_after("textDocument/didOpen", uri, INFERRED)
# Warnings there are: its functions are not exported, and nothing calls them.
errors = [d for d in found if d["severity"] == 1]
expect("inferred: the file checks", errors == [], json.dumps(errors, indent=1))
def hover(text, needle, offset=1, nth=0):
at = position_of(text, needle, nth, offset)
h = server.send("textDocument/hover", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"]
return h and h["contents"]["value"]
cases = [
("a parameter without a type", "xs)\n", "(: xs (List int))"),
("a let binding", "pairs (list-map", "(: pairs (List (Tuple int string)))"),
("a fun's parameter, at a use", "x \"s\"", "(: x int)"),
("a match pattern's variable", "n label)", "(: n int)"),
("another, at a use", "label)))", "(: label string)"),
("a loop variable", "y xs)", "(: y int)"),
("a local defun, at a use", "twice names", "(: twice (-?-> string int))"),
("a local defun's parameter", "s)))\n (vec-map", "(: s string)"),
]
for name, needle, wanted in cases:
h = hover(INFERRED, needle, 0)
expect("inferred hover: " + name, h and wanted in h, h)
h = hover(INFERRED, "(def numbers", 5)
expect("inferred hover: a top-level def with no signature shows the type inferred",
h and "(: numbers (List int))" in h, h)
# The status bar shows a hover's first line, so it has to be the type. The
# prelude writes its signatures nameless, above the definition.
h = hover(INFERRED, "(list-map")
expect(
"hover: a nameless signature, shown with the name, first",
h and h.split("\n")[1].startswith("(: list-map (-> (-?-> %a %b) (List %a) (List %b)))"),
h,
)
expect(
"inferred hover: a generic function, at this use",
h and "At this use" in h and "(: list-map (-> (-> int (Tuple int string)) (List int) (List (Tuple int string))))" in h,
h,
)
def hints(text):
"""Each hint as (the text before it on its line, its label)."""
lines = text.split("\n")
whole = {"start": {"line": 0, "character": 0}, "end": {"line": len(lines), "character": 0}}
found = server.send("textDocument/inlayHint", {"textDocument": {"uri": uri}, "range": whole}, request=True)["result"]
return [(lines[h["position"]["line"]][: h["position"]["character"]], h["label"]) for h in found]
found = hints(INFERRED)
labels = {before.split()[-1].lstrip("("): label for before, label in found}
expect(
"inlay hints: a type after each local's binding",
labels.get("pairs") == ": (List (Tuple int string))"
and labels.get("x") == ": int"
and labels.get("n") == ": int"
and labels.get("label") == ": string"
and labels.get("y") == ": int"
and labels.get("s") == ": string",
found,
)
expect(
"inlay hints: a def and a defun in a body, at their names",
labels.get("bumped") == ": int" and labels.get("twice") == ": (-?-> string int)",
found,
)
expect(
"inlay hints: none for a top-level function's parameters",
"xs" not in labels and "names" not in labels and "k" not in labels,
found,
)
expect("inlay hints: none where the type is written", "m" not in labels, found)
# An edit not checked yet, between `y` and `s`: the hints before it
# stay, and the one after it waits for the check.
edited = INFERRED.replace("(defun (lengths names)", "(defun (lengths names)")
server.change(uri, edited, 2)
labels = {before.split()[-1].lstrip("("): label for before, label in hints(edited)}
expect(
"inlay hints: before an unchecked edit they stay, after it they wait",
labels.get("y") == ": int" and "s" not in labels,
labels,
)
server.next_diagnostics(uri)
labels = {before.split()[-1].lstrip("("): label for before, label in hints(edited)}
expect("inlay hints: after the check, all of them", labels.get("s") == ": string", labels)
# A type error in `total`: `lengths` still has its types, and `total`'s
# names have none rather than wrong ones.
server.change(uri, INFERRED_BROKEN, 3)
server.next_diagnostics(uri)
h = hover(INFERRED_BROKEN, "twice names", 0)
expect("inferred hover: another declaration's error leaves this one's", h and "(: twice (-?-> string int))" in h, h)
h = hover(INFERRED_BROKEN, "pairs (list-map", 0)
expect("inferred hover: a declaration that failed has none", h and "(: pairs" not in h, h)
# Hovered straight after typing, before the check would have run: the
# hover checks first, and the types are of the text as it stands.
server.change(uri, INFERRED_EDITED, 4)
h = hover(INFERRED_EDITED, "pairs (list-map", 0)
expect("inferred hover: an unsaved edit is checked first", h and "(: pairs (List (Tuple int double)))" in h, h)
server.diagnostics_after("textDocument/didClose", uri)
FIELDS = """(type (: Leg (Record (: distance double) (: name string))))
(type (: Pos (Struct (: x int) (: y int))))
(:doc Leg
(summary "A part of a trip.")
(field distance "How far it goes.")
(field name "Where it ends."))
(: far? (-> Leg bool))
(defun (far? leg) (> (.distance leg) 10.0))
(: across (-> Pos int))
(defun (across p) (+ (.x p) (.y p)))
"""
def fields(server, tmp):
path = os.path.join(tmp, "fields.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(FIELDS)
found = server.diagnostics_after("textDocument/didOpen", uri, FIELDS)
errors = [d for d in found if d["severity"] == 1]
expect("fields: the file checks", errors == [], json.dumps(errors, indent=1))
def hover(needle, offset=1):
at = position_of(FIELDS, needle, 0, offset)
h = server.send("textDocument/hover", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"]
return h and h["contents"]["value"]
h = hover("(.distance leg)", 2)
expect(
"fields hover: a record field's type, its declaration and its doc",
h
and "(: .distance double)" in h
and "(: distance double)" in h
and "How far it goes." in h
and "A field of `Leg`" in h,
h,
)
h = hover("(.y p)", 2)
expect("fields hover: a struct's field", h and "(: .y int)" in h and "A field of `Pos`" in h, h)
h = hover("leg) 10.0", 0)
expect(
"fields hover: a local of a record type shows the record",
h and "(: leg Leg)" in h and "(: Leg (Record (: distance double) (: name string)))" in h and "A part of a trip." in h,
h,
)
h = hover("p) (.y", 0)
expect("fields hover: a local of a struct type shows the struct", h and "(: Pos (Struct" in h, h)
server.diagnostics_after("textDocument/didClose", uri)
RENAMING = """(export area)
(:doc helper
(summary "Twice the number.")
(arg x "A number.")
(returns "Twice x."))
(: helper (-> int int))
(defun (helper x) (* 2 x))
(: area (-> int int string))
(defun (area w h)
(def product (* w h))
(defun (twice s) (* 2 s))
(let ((n (helper 3))
(xs (list 1 2 3)))
(println #"n is ${n}")
(println '(n xs))
(let ((count 10))
(println count))
(str (displayed (twice product)) (displayed (+ n (length xs))))))
(: greet (-> string (#:greeting string) string))
(defun (greet who #:greeting "hello") (str greeting ", " who))
(defun (main) (println (area 2 3)) (println (greet "x")) 0)
"""
def renaming(server, tmp):
path = os.path.join(tmp, "renaming.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(RENAMING)
found = server.diagnostics_after("textDocument/didOpen", uri, RENAMING)
expect("rename: the file checks", [d for d in found if d["severity"] == 1] == [], found)
def ask(method, needle, offset, new=None):
params = {"textDocument": {"uri": uri}, "position": position_of(RENAMING, needle, 0, offset)}
if new is not None:
params["newName"] = new
return server.send(method, params, request=True)
def renamed(needle, offset, new):
"""The text with the rename applied, or the refusal's message."""
answer = ask("textDocument/rename", needle, offset, new)
if "error" in answer:
return None, answer["error"]["message"]
lines = RENAMING.split("\n")
edits = answer["result"]["changes"].get(uri, [])
for e in sorted(edits, key=lambda e: (-e["range"]["start"]["line"], -e["range"]["start"]["character"])):
a, b = e["range"]["start"], e["range"]["end"]
line = lines[a["line"]]
lines[a["line"]] = line[: a["character"]] + e["newText"] + line[b["character"] :]
return "\n".join(lines), None
prepared = ask("textDocument/prepareRename", "((n (helper", 2)["result"]
expect(
"rename: prepareRename gives the name and where it is",
prepared and prepared["placeholder"] == "n"
and prepared["range"]["start"] == position_of(RENAMING, "((n (helper", 0, 2),
prepared,
)
text, why = renamed("((n (helper", 2, "num")
expect(
"rename: a local, in an interpolation too, and not in quoted data",
text is not None
and "((num (helper 3))" in text
and "${num}" in text
and "'(n xs)" in text
and "(+ num (length xs))" in text,
why or text,
)
text, why = renamed("(def product", 5, "prod")
expect("rename: a def in a body", text is not None and "(def prod (* w h))" in text and "(displayed (twice prod))" in text,
why or text)
text, why = renamed("(defun (helper x)", 8, "double")
expect(
"rename: a top-level defun the module does not export, its signature and doc too",
text is not None
and "(:doc double" in text
and "(: double (-> int int))" in text
and "(defun (double x)" in text
and "((n (double 3))" in text,
why or text,
)
text, why = renamed("(defun (helper x)", 15, "k")
expect("rename: a parameter, and the (arg ...) of its function's doc",
text is not None and '(arg k "A number.")' in text and "(defun (helper k) (* 2 k))" in text,
why or text)
for label, needle, offset, new, wanted in [
("a binding the new name would take a use from", "((n (helper", 2, "xs", "'xs' is bound at"),
("a use of the new name the renamed binding would take", "((n (helper", 2, "count", "'count' is used at"),
("an exported name", "(defun (area w", 8, "size", "is exported at"),
("a name defined elsewhere", "(length xs)", 1, "len", "is defined in prelude.bjo"),
("a keyword parameter", "(str greeting", 5, "hi", "keyword parameter"),
("main", "(defun (main)", 8, "start", "entry point"),
("a name of a definition the module sees", "(defun (helper x)", 8, "length", "is already defined"),
("a name that is not one", "((n (helper", 2, "two words", "is not a name"),
("a rename the check refuses", "(defun (twice s)", 8, "when", "would give the program an error"),
]:
text, why = renamed(needle, offset, new)
expect(f"rename refused: {label}", text is None and why and wanted in why, why or text)
# The renamed text is what the editor ends up with, and it checks.
text, _ = renamed("((n (helper", 2, "num")
server.change(uri, text, 2)
found = server.next_diagnostics(uri)
expect("rename: the renamed text checks", [d for d in found if d["severity"] == 1] == [], found)
server.diagnostics_after("textDocument/didClose", uri)
SHAPES = """(type (: Shape (Union (: Circle int) (: Square int))))
(: size (-> Shape int))
(defun (size s)
(match s
((Circle r) r)
((Square w) w)))
(defun (main) (println (int->string (size (Circle 2)))) 0)
"""
def referencing(server, tmp):
path = os.path.join(tmp, "renaming.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(RENAMING)
server.diagnostics_after("textDocument/didOpen", uri, RENAMING)
def ask(method, text, file_uri, needle, offset, nth=0, definition=True):
params = {"textDocument": {"uri": file_uri}, "position": position_of(text, needle, nth, offset)}
if method == "textDocument/references":
params["context"] = {"includeDeclaration": definition}
return server.send(method, params, request=True)["result"]
def at(text, found):
"""Each location as the line it is on and what it covers."""
lines = text.split("\n")
return sorted(
(l["range"]["start"]["line"],
lines[l["range"]["start"]["line"]][l["range"]["start"]["character"]:l["range"]["end"]["character"]])
for l in found or [])
def lines(text, *needles):
return sorted(line_of(text, n) for n in needles)
found = ask("textDocument/references", RENAMING, uri, "(+ n", 3)
expect("references: a local's binding and uses, in an interpolation too, not in quoted data",
[l for l, _ in at(RENAMING, found)] == lines(RENAMING, "((n (helper", "${n}", "(+ n")
and all(name == "n" for _, name in at(RENAMING, found)),
at(RENAMING, found))
found = ask("textDocument/references", RENAMING, uri, "(+ n", 3, definition=False)
expect("references: without the declaration, a local's uses only",
[l for l, _ in at(RENAMING, found)] == lines(RENAMING, "${n}", "(+ n"), at(RENAMING, found))
found = ask("textDocument/references", RENAMING, uri, "(helper 3)", 1)
expect("references: a top-level defun, in its doc and signature too",
[l for l, _ in at(RENAMING, found)]
== lines(RENAMING, "(:doc helper", "(: helper", "(defun (helper", "(helper 3)"),
at(RENAMING, found))
found = ask("textDocument/references", RENAMING, uri, "(defun (area", 8)
expect("references: an exported name, in this module",
[l for l, _ in at(RENAMING, found)]
== lines(RENAMING, "(export area)", "(: area", "(defun (area", "(println (area"),
at(RENAMING, found))
found = ask("textDocument/references", RENAMING, uri, "(length xs)", 1)
expect("references: an imported name, where this module uses it",
at(RENAMING, found) == [(line_of(RENAMING, "(length xs)"), "length")], at(RENAMING, found))
found = ask("textDocument/references", RENAMING, uri, "(str greeting", 5)
expect("references: a keyword parameter, in its function",
[l for l, _ in at(RENAMING, found)] == lines(RENAMING, "#:greeting \"hello\"", "(str greeting"),
at(RENAMING, found))
found = ask("textDocument/documentHighlight", RENAMING, uri, "(+ n", 3)
kinds = sorted((h["range"]["start"]["line"], h["kind"]) for h in found or [])
expect("highlight: the binding as a write, the uses as reads",
kinds == sorted([(line_of(RENAMING, "((n (helper"), 3), (line_of(RENAMING, "${n}"), 2),
(line_of(RENAMING, "(+ n"), 2)]),
kinds)
server.diagnostics_after("textDocument/didClose", uri)
path = os.path.join(tmp, "shapes.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(SHAPES)
server.diagnostics_after("textDocument/didOpen", uri, SHAPES)
found = ask("textDocument/references", SHAPES, uri, "(-> Shape", 4)
expect("references: a type, its declaration and the signature that names it",
at(SHAPES, found) == sorted([(0, "Shape"), (line_of(SHAPES, "(-> Shape"), "Shape")]), at(SHAPES, found))
found = ask("textDocument/references", SHAPES, uri, "(Circle 2)", 1)
expect("references: a constructor, its case, a pattern and a use",
at(SHAPES, found)
== sorted([(0, "Circle"), (line_of(SHAPES, "((Circle r)"), "Circle"), (line_of(SHAPES, "(Circle 2)"), "Circle")]),
at(SHAPES, found))
server.diagnostics_after("textDocument/didClose", uri)
INCOMPLETE = """(type (: Shape (Union (: Circle int) (: Square int) Empty)))
(: size (-> Shape int))
(defun (size s)
(match s
((Circle r) r)))
(: pick (-> (Option Shape) int))
(defun (pick o)
(match o
((Some (Circle r)) r)
(None 0)))
(defun (main) (println (int->string (+ (size Empty) (pick None)))) 0)
"""
HOLES = """(type (: Shape (Union (: Circle int) (: Square int) Empty)))
(: add-size (-> Shape int int))
(defun (add-size s n) n)
(: total-size (-> (List Shape) int))
(defun (total-size shapes)
(list-foldl _ 0 shapes))
(: default-shape (-> Shape))
(defun (default-shape) _)
(defun (main) (println (int->string (total-size (list (default-shape))))) 0)
"""
EMPTY_MATCH = """(type (: Shape (Union (: Circle int) (: Square int) Empty)))
(: size (-> Shape int))
(defun (size s)
(match s))
(: pick (-> (Option Shape) int))
(defun (pick o)
(match o
(x #:when (some? x) 1)))
(defun (main) (println (int->string (+ (size Empty) (pick None)))) 0)
"""
def applied(text, edits):
"""`text` with LSP text edits made, the last first."""
lines = text.split("\n")
offsets = [0]
for line in lines:
offsets.append(offsets[-1] + len(line) + 1)
def offset(p):
return offsets[p["line"]] + p["character"]
for e in sorted(edits, key=lambda e: -offset(e["range"]["start"])):
a, b = offset(e["range"]["start"]), offset(e["range"]["end"])
text = text[:a] + e["newText"] + text[b:]
return text
def acting(server, tmp):
def open_(name, text):
path = os.path.join(tmp, name)
uri = "file://" + path
with open(path, "w") as f:
f.write(text)
return uri, server.diagnostics_after("textDocument/didOpen", uri, text)
def actions(uri, text, needle, offset=1):
at = position_of(text, needle, 0, offset)
params = {"textDocument": {"uri": uri}, "range": {"start": at, "end": at}, "context": {"diagnostics": []}}
return server.send("textDocument/codeAction", params, request=True)["result"] or []
def edit_of(found, title, uri):
chosen = [a for a in found if a["title"] == title]
return chosen[0]["edit"]["changes"][uri] if chosen else None
uri, found = open_("incomplete.bjo", INCOMPLETE)
expect("actions: the incomplete matches are reported",
len([d for d in found if "does not cover every value" in d["message"]]) == 2, found)
found = actions(uri, INCOMPLETE, "(match s", 1)
first = edit_of(found, "Add the 2 missing clauses", uri)
expect("actions: a match lacking two cases is offered both", first is not None, [a["title"] for a in found])
fixed = applied(INCOMPLETE, first or [])
expect("actions: the clauses go after the last one, lined up with it",
" ((Circle r) r)\n ((Square _) _)\n (Empty _))" in fixed, fixed)
# Both actions are of the text as checked, so both go into it together.
found = actions(uri, INCOMPLETE, "(match o", 1)
second = edit_of(found, "Add the 2 missing clauses", uri)
fixed = applied(INCOMPLETE, (first or []) + (second or []))
expect("actions: a nested case is spelled out",
" (None 0)\n ((Some (Square _)) _)\n ((Some Empty) _))" in fixed, fixed)
server.change(uri, fixed, 2)
after = server.next_diagnostics(uri)
expect("actions: with the clauses added, every match covers its type and the bodies are holes",
not any("does not cover" in d["message"] for d in after)
and len([d for d in after if d["message"].startswith("Hole at")]) == 4,
[d["message"].splitlines()[0] for d in after])
server.diagnostics_after("textDocument/didClose", uri)
uri, found = open_("holes.bjo", HOLES)
found = actions(uri, HOLES, "(list-foldl _", 12)
titles = [a["title"] for a in found]
expect("actions: a hole is offered the binding that fits it, and a fun",
"Fill with add-size" in titles and "Fill with (fun (x y) _)" in titles, titles)
filled = applied(HOLES, edit_of(found, "Fill with add-size", uri) or [])
expect("actions: filling replaces the hole", "(list-foldl add-size 0 shapes)" in filled, filled)
found = actions(uri, HOLES, "(defun (default-shape) _", 23)
titles = [a["title"] for a in found]
expect("actions: a hole of a union's type is offered its cases, each once",
sorted(titles) == ["Fill with (Circle _)", "Fill with (Square _)", "Fill with Empty"], titles)
expect("actions: nothing is offered away from a hole", actions(uri, HOLES, "(defun (add-size", 8) == [],
actions(uri, HOLES, "(defun (add-size", 8))
# A match with no clauses yet lacks every case, each its own clause, not
# one `_`; so does one whose clauses all have a guard.
uri, found = open_("empty-match.bjo", EMPTY_MATCH)
found = actions(uri, EMPTY_MATCH, "(match s", 1)
empty = edit_of(found, "Add the 3 missing clauses", uri)
expect("actions: a match with no clauses is offered every case",
empty is not None, [a["title"] for a in found])
fixed = applied(EMPTY_MATCH, empty or [])
expect("actions: each case a clause, under the match",
" (match s\n ((Circle _) _)\n ((Square _) _)\n (Empty _)))" in fixed, fixed)
found = actions(uri, EMPTY_MATCH, "(match o", 1)
guarded = edit_of(found, "Add the 2 missing clauses", uri)
fixed = applied(EMPTY_MATCH, guarded or [])
expect("actions: clauses that all have a guard cover nothing, so every case is offered",
" (x #:when (some? x) 1)\n (None _)\n ((Some _) _)))" in fixed, fixed)
server.diagnostics_after("textDocument/didClose", uri)
CHAIN_MACROS = """;; Two macros, one expanding to the other.
(import (std syntax-match))
(def/macro (twice form inject compare)
(syntax-match form
((_ e) #'(both ,e ,e))))
(def/macro (both form inject compare)
(syntax-match form
((_ a b) #'(let ((tmp ,a)) (+ tmp ,b)))))
"""
CHAIN = """(import "chain-macros.bjo")
(: main (-> (Vec string) int))
(defun (main args)
(twice 21))
"""
def expanding(server, tmp):
with open(os.path.join(tmp, "chain-macros.bjo"), "w") as f:
f.write(CHAIN_MACROS)
path = os.path.join(tmp, "chain.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(CHAIN)
found = server.diagnostics_after("textDocument/didOpen", uri, CHAIN)
expect("expansion: a file with an imported macro module checks", found == [], found)
expect(
"expansion: the import was built by the installed compiler",
os.path.exists(os.path.join(tmp, "chain-macros.dll")),
os.listdir(tmp),
)
def expand(needle, **flags):
at = position_of(CHAIN, needle, 0, 2)
answer = server.send(
"bjolang/expandMacro", dict(textDocument={"uri": uri}, position=at, **flags), request=True
)
return answer["result"]
r = expand("(twice", full=False)
expect("expansion: one step", r and r["macro"] == "twice" and r["text"] == "(both 21 21)", r)
r = expand("(twice")
expect("expansion: all the way", r and r["text"] == "(let ((tmp 21)) (+ tmp 21))", r)
r = expand("(twice", hygienic=True)
expect("expansion: hygienic names kept", r and "tmp__" in r["text"], r)
r = expand("(defun (main", full=False)
expect("expansion: none where there is no macro call", r is None, r)
# An unsaved change is expanded as it stands, without waiting for the pause.
changed = CHAIN.replace("(twice 21)", "(twice (twice 1))")
server.change(uri, changed, 2)
at = position_of(changed, "(twice (twice", 0, 2)
r = server.send("bjolang/expandMacro", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"]
expect(
"expansion: of the buffer, nested calls expanded too",
r and r["text"].count("(+ tmp") == 3 and "twice" not in r["text"] and "both" not in r["text"],
r,
)
server.diagnostics_after("textDocument/didClose", uri)
GREET = """(import (std prelude))
(export greet)
;; Says hello.
(: greet (-> string string))
(defun (greet name) (string-append "hello, " name))
"""
USES_GREET = """(import (std prelude))
(import (mylib greet))
(: main (-> (Vec string) int))
(defun (main args)
(println (greet "you"))
0)
"""
def packages():
"""A project's packages, as `bjo` wrote them into its `.bjo/roots`. Each
case has a server of its own, as one serves the project of the first file
it is asked about."""
def started():
server = Server()
server.send("initialize", {"processId": None, "rootUri": None, "capabilities": {}}, request=True)
server.send("initialized")
return server
def stopped(server):
server.send("shutdown", request=True)
server.send("exit")
server.proc.wait(timeout=10)
with tempfile.TemporaryDirectory() as tmp:
lib = os.path.join(tmp, "mylib", "src")
project = os.path.join(tmp, "app")
os.makedirs(lib)
os.makedirs(os.path.join(project, "src"))
os.makedirs(os.path.join(project, ".bjo"))
with open(os.path.join(lib, "greet.bjo"), "w") as f:
f.write(GREET)
with open(os.path.join(project, "manifest.bjodat"), "w") as f:
f.write('(package (name (app)) (version "0.1.0"))\n')
with open(os.path.join(project, ".bjo", "roots"), "w") as f:
f.write(f'(roots (root (mylib) "{lib}"))\n')
path = os.path.join(project, "src", "main.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(USES_GREET)
server = started()
found = server.diagnostics_after("textDocument/didOpen", uri, USES_GREET)
expect("packages: an import from the project's packages checks", found == [], json.dumps(found, indent=1))
at = position_of(USES_GREET, '(greet "you")')
d = server.send(
"textDocument/definition", {"textDocument": {"uri": uri}, "position": at}, request=True
)["result"]
expect(
"packages: go to definition reaches the package",
d and d["uri"] == "file://" + os.path.join(lib, "greet.bjo"),
d,
)
items = server.send(
"textDocument/completion",
{"textDocument": {"uri": uri}, "position": position_of(USES_GREET, '(greet "you")', 0, 4)},
request=True,
)["result"]["items"]
expect("packages: completion offers the package's names", any(i["label"] == "greet" for i in items))
stopped(server)
# The same project before `bjo fetch`: the server says what to do.
os.remove(os.path.join(project, ".bjo", "roots"))
server = started()
found = server.diagnostics_after("textDocument/didOpen", uri, USES_GREET)
expect(
"packages: unfetched, a warning says to run bjo fetch",
any(d["severity"] == 2 and "bjo fetch" in d["message"] for d in found),
json.dumps(found, indent=1),
)
stopped(server)
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "smoke.bjo")
uri = "file://" + path
server = Server()
answer = server.send("initialize", {"processId": None, "rootUri": None, "capabilities": {}}, request=True)
expect("initialize answers capabilities", "capabilities" in answer.get("result", {}), answer)
server.send("initialized")
with open(path, "w") as f:
f.write(BROKEN)
found = server.diagnostics_after("textDocument/didOpen", uri, BROKEN)
expect("a type error is reported", len(found) >= 1 and found[0]["severity"] == 1, found)
expect(
"on the line it is on",
any(d["range"]["start"]["line"] == 4 for d in found),
json.dumps(found, indent=1),
)
# `(+ 1 "two")`: the compiler says the column of the `1`, and the form
# there is what is marked.
expect(
"at its column, marking the form there",
any(
d["range"]["start"] == {"line": 4, "character": 5}
and d["range"]["end"] == {"line": 4, "character": 6}
for d in found
),
json.dumps(found, indent=1),
)
for d in found:
print(" ", d["range"]["start"], d["message"].splitlines()[0])
# Saved: the editor sends the change, writes the file, and says so.
server.change(uri, FIXED, 2)
with open(path, "w") as f:
f.write(FIXED)
found = server.diagnostics_after("textDocument/didSave", uri)
expect("the fixed file has none", found == [], json.dumps(found, indent=1))
# Not saved: the check follows the buffer once typing pauses, while the
# file on disk stays fixed.
server.change(uri, UNCLOSED, 3)
found = server.next_diagnostics(uri)
expect("a parse error in an unsaved buffer is reported", len(found) >= 1, found)
for d in found:
print(" ", d["range"]["start"], d["message"].splitlines()[0])
# A burst of typing is checked once, after it, not once per change.
for version in range(4, 9):
server.change(uri, FIXED if version % 2 else BROKEN, version)
found = server.next_diagnostics(uri)
expect("a burst is checked as its last text", len(found) >= 1, found)
import time
time.sleep(1.0)
server.send("textDocument/documentSymbol", {"textDocument": {"uri": uri}}, request=True)
expect("and only once", server.published(uri) == [], "more than one check published")
found = server.diagnostics_after("textDocument/didClose", uri)
expect("closing clears them", found == [], found)
symbols_and_definitions(server, tmp)
documented(server, tmp)
constrained(server, tmp)
completing(server, tmp)
locals_(server, tmp)
inferred(server, tmp)
fields(server, tmp)
renaming(server, tmp)
referencing(server, tmp)
acting(server, tmp)
expanding(server, tmp)
answer = server.send("shutdown", request=True)
expect("shutdown answers", "result" in answer, answer)
server.send("exit")
expect("exit ends the process with 0", server.proc.wait(timeout=10) == 0)
packages()
sys.exit(1 if failures else 0)