Dino compiler: language, formatter, language server, docs, editor support
Compiler in Rust (lexer, parser, checker, C codegen), maps, chars, dino fmt, dino lsp (diagnostics, formatting, outline, definition, hover, completion, signature help), docs, examples, VS Code/Vim files. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3e2779f447
commit
eaf9567a36
117 files changed
+19970
No files matched your search
+106
@@ -0,0 +1,106 @@
|
||||
//! Tests of `dino fmt`.
|
||||
|
||||
use dino::fmt::format;
|
||||
|
||||
fn fmt(src: &str) -> String {
|
||||
format(src).unwrap_or_else(|d| panic!("{}", d.render("test.dino", src)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixes_indentation_and_spaces() {
|
||||
let messy = "func add( a:int,b :int ):int{\nreturn a+b\n}\n\n\n\nfunc main(){\nvar x=add(1,2)*3 -1\nif x>3{print( \"big\" )}else{print(-x)}\nfor i in 0..10 step 2{ print(i)}\n}\n";
|
||||
// line breaks stay where they are: a block written on one line stays on one line
|
||||
let want = "func add(a: int, b: int): int {\n return a + b\n}\n\nfunc main() {\n var x = add(1, 2) * 3 - 1\n if x > 3 { print(\"big\") } else { print(-x) }\n for i in 0..10 step 2 { print(i) }\n}\n";
|
||||
assert_eq!(fmt(messy), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literals_and_types_stay_tight() {
|
||||
let src = "struct P{x,y:float}\nfunc main(){\nvar p=P{x:1.0,y:2.0}\nvar m=map[string,int]{}\nvar n={\"a\":1,\"b\":2}\nvar xs:[]int=[1,2,3]\nvar o:int?=nil\nvar s=Stack[int]{}\nprint(p,m,n,xs,o,s)\n}\n";
|
||||
let out = fmt(src);
|
||||
// struct bodies are blocks; literals have no inner spaces
|
||||
assert!(out.contains("var p = P{x: 1.0, y: 2.0}"), "{out}");
|
||||
assert!(out.contains("var m = map[string, int]{}"), "{out}");
|
||||
assert!(out.contains("var n = {\"a\": 1, \"b\": 2}"), "{out}");
|
||||
assert!(out.contains("var xs: []int = [1, 2, 3]"), "{out}");
|
||||
assert!(out.contains("var o: int? = nil"), "{out}");
|
||||
assert!(out.contains("var s = Stack[int]{}"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_and_blank_lines_survive() {
|
||||
let src = "// top\nfunc main() {\n\n\n var a = 1 // one\n var bbb = 2 // two\n\n // standalone\n print(a, bbb)\n\n}\n";
|
||||
let want = "// top\nfunc main() {\n var a = 1 // one\n var bbb = 2 // two\n\n // standalone\n print(a, bbb)\n}\n";
|
||||
assert_eq!(fmt(src), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closures_and_continuation_lines() {
|
||||
let src = "func main() {\nrun(func() {\nprint(1)\n})\nvar total = 1 +\n2 +\n3\nvar xs = [\n1,\n2,\n]\n}\n";
|
||||
let want = "func main() {\n run(func() {\n print(1)\n })\n var total = 1 +\n 2 +\n 3\n var xs = [\n 1,\n 2,\n ]\n}\n";
|
||||
assert_eq!(fmt(src), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strings_are_left_alone() {
|
||||
let src = "func main() {\nprint(\"a {x+1} b\", 'x', '\\n')\n}\n";
|
||||
let out = fmt(src);
|
||||
assert!(out.contains("\"a {x+1} b\""), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn already_formatted_code_does_not_change() {
|
||||
let src = "func main() {\n var s = \"é\"\n for i, c in s {\n match c {\n 'a' => print(i)\n _ => {\n print(-i)\n }\n }\n }\n}\n";
|
||||
assert_eq!(fmt(src), src);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_code_is_refused() {
|
||||
assert!(format("func main( {").is_err());
|
||||
}
|
||||
|
||||
fn dino_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
|
||||
for e in std::fs::read_dir(dir).unwrap() {
|
||||
let p = e.unwrap().path();
|
||||
if p.is_dir() {
|
||||
dino_files(&p, out);
|
||||
} else if p.extension().map_or(false, |x| x == "dino") {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn examples_are_formatted_and_formatting_is_stable() {
|
||||
let mut files = Vec::new();
|
||||
dino_files(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("examples"), &mut files);
|
||||
assert!(files.len() > 30);
|
||||
for f in files {
|
||||
let src = std::fs::read_to_string(&f).unwrap();
|
||||
let once = fmt(&src);
|
||||
assert_eq!(once, src, "{} is not formatted (run `dino fmt examples`)", f.display());
|
||||
assert_eq!(fmt(&once), once, "formatting {} twice differs", f.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_examples_are_stable() {
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("docs");
|
||||
let mut n = 0;
|
||||
for e in std::fs::read_dir(dir).unwrap() {
|
||||
let p = e.unwrap().path();
|
||||
let text = std::fs::read_to_string(&p).unwrap();
|
||||
let mut rest = text.as_str();
|
||||
while let Some(start) = rest.find("```dino\n") {
|
||||
let after = &rest[start + 8..];
|
||||
let end = after.find("```").unwrap();
|
||||
let code = &after[..end];
|
||||
rest = &after[end + 3..];
|
||||
if let Ok(once) = format(code) {
|
||||
assert_eq!(once, code, "doc example in {} is not formatted:\n{code}", p.display());
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(n > 20, "only {n} doc examples were formattable");
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
//! Tests of the language server: feed it editor messages, read what it answers.
|
||||
|
||||
use dino::json::{self, Json};
|
||||
use dino::lsp;
|
||||
|
||||
fn frame(v: &Json) -> Vec<u8> {
|
||||
let body = v.to_string();
|
||||
format!("Content-Length: {}\r\n\r\n{}", body.len(), body).into_bytes()
|
||||
}
|
||||
|
||||
fn request(id: i64, method: &str, params: Json) -> Json {
|
||||
Json::obj(vec![("jsonrpc", Json::str("2.0")), ("id", Json::Num(id as f64)), ("method", Json::str(method)), ("params", params)])
|
||||
}
|
||||
|
||||
fn notify(method: &str, params: Json) -> Json {
|
||||
Json::obj(vec![("jsonrpc", Json::str("2.0")), ("method", Json::str(method)), ("params", params)])
|
||||
}
|
||||
|
||||
fn open(uri: &str, text: &str) -> Json {
|
||||
notify(
|
||||
"textDocument/didOpen",
|
||||
Json::obj(vec![("textDocument", Json::obj(vec![("uri", Json::str(uri)), ("text", Json::str(text))]))]),
|
||||
)
|
||||
}
|
||||
|
||||
/// Run a whole conversation and return every message the server sent.
|
||||
fn talk(messages: Vec<Json>) -> (Vec<Json>, i32) {
|
||||
let mut input = Vec::new();
|
||||
for m in &messages {
|
||||
input.extend(frame(m));
|
||||
}
|
||||
let mut output = Vec::new();
|
||||
let code = lsp::run(std::io::Cursor::new(input), &mut output);
|
||||
let text = String::from_utf8(output).unwrap();
|
||||
let mut out = Vec::new();
|
||||
let mut rest = text.as_str();
|
||||
while let Some(i) = rest.find("\r\n\r\n") {
|
||||
let len: usize = rest[..i].trim().strip_prefix("Content-Length: ").unwrap().parse().unwrap();
|
||||
out.push(json::parse(&rest[i + 4..i + 4 + len]).unwrap());
|
||||
rest = &rest[i + 4 + len..];
|
||||
}
|
||||
(out, code)
|
||||
}
|
||||
|
||||
fn exit_messages() -> Vec<Json> {
|
||||
vec![request(99, "shutdown", Json::Null), notify("exit", Json::Null)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_round_trip() {
|
||||
let src = r#"{"a":[1,2.5,"x\n\"y\" é 😀"],"b":null,"c":true}"#;
|
||||
let v = json::parse(src).unwrap();
|
||||
assert_eq!(json::parse(&v.to_string()).unwrap(), v);
|
||||
assert_eq!(v.get("a"), Some(&Json::Arr(vec![Json::Num(1.0), Json::Num(2.5), Json::str("x\n\"y\" é 😀")])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialize_announces_features() {
|
||||
let mut msgs = vec![request(1, "initialize", Json::obj(vec![]))];
|
||||
msgs.extend(exit_messages());
|
||||
let (out, code) = talk(msgs);
|
||||
assert_eq!(code, 0);
|
||||
let caps = out[0].path(&["result", "capabilities"]).unwrap();
|
||||
assert_eq!(caps.get("documentFormattingProvider"), Some(&Json::Bool(true)));
|
||||
assert_eq!(out[0].get("id"), Some(&Json::Num(1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_show_up_as_diagnostics() {
|
||||
let src = "func main() {\n var x: int = \"no\"\n}\n";
|
||||
let mut msgs = vec![open("file:///tmp/dino-lsp-test/a.dino", src)];
|
||||
msgs.extend(exit_messages());
|
||||
let (out, _) = talk(msgs);
|
||||
let d = match out[0].path(&["params", "diagnostics"]) {
|
||||
Some(Json::Arr(items)) => items.clone(),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert_eq!(d.len(), 1);
|
||||
let line = d[0].path(&["range", "start", "line"]).and_then(Json::as_i64).unwrap();
|
||||
assert_eq!(line, 1);
|
||||
assert!(d[0].get("message").and_then(Json::as_str).unwrap().contains("string"), "{:?}", d[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixing_the_code_clears_the_diagnostics() {
|
||||
let uri = "file:///tmp/dino-lsp-test/b.dino";
|
||||
let change = notify(
|
||||
"textDocument/didChange",
|
||||
Json::obj(vec![
|
||||
("textDocument", Json::obj(vec![("uri", Json::str(uri))])),
|
||||
("contentChanges", Json::Arr(vec![Json::obj(vec![("text", Json::str("func main() {\n print(1)\n}\n"))])])),
|
||||
]),
|
||||
);
|
||||
let mut msgs = vec![open(uri, "func main() {\n print(nope)\n}\n"), change];
|
||||
msgs.extend(exit_messages());
|
||||
let (out, _) = talk(msgs);
|
||||
assert_eq!(out[0].path(&["params", "diagnostics"]).map(|d| matches!(d, Json::Arr(a) if a.len() == 1)), Some(true));
|
||||
assert_eq!(out[1].path(&["params", "diagnostics"]), Some(&Json::Arr(vec![])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_columns_count_utf16_units() {
|
||||
// the emoji takes two units in the editor's counting
|
||||
let src = "func main() {\n print(\"😀\", nope)\n}\n";
|
||||
let mut msgs = vec![open("file:///tmp/dino-lsp-test/c.dino", src)];
|
||||
msgs.extend(exit_messages());
|
||||
let (out, _) = talk(msgs);
|
||||
let d = match out[0].path(&["params", "diagnostics"]) {
|
||||
Some(Json::Arr(items)) => items[0].clone(),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let start = d.path(&["range", "start", "character"]).and_then(Json::as_i64).unwrap();
|
||||
let end = d.path(&["range", "end", "character"]).and_then(Json::as_i64).unwrap();
|
||||
// ` print("😀", ` is 4 + 6 + 4 + 2 = 16 units before `nope`
|
||||
assert_eq!((start, end), (16, 20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatting_returns_the_tidy_text() {
|
||||
let uri = "file:///tmp/dino-lsp-test/d.dino";
|
||||
let fmt_req = request(
|
||||
2,
|
||||
"textDocument/formatting",
|
||||
Json::obj(vec![("textDocument", Json::obj(vec![("uri", Json::str(uri))]))]),
|
||||
);
|
||||
let mut msgs = vec![open(uri, "func main(){\nprint( 1 )\n}\n"), fmt_req];
|
||||
msgs.extend(exit_messages());
|
||||
let (out, _) = talk(msgs);
|
||||
let reply = out.iter().find(|m| m.get("id") == Some(&Json::Num(2.0))).unwrap();
|
||||
let edit = match reply.get("result") {
|
||||
Some(Json::Arr(e)) => e[0].clone(),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert_eq!(edit.get("newText").and_then(Json::as_str), Some("func main() {\n print(1)\n}\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_are_read_next_to_the_file() {
|
||||
let dir = std::env::temp_dir().join(format!("dino-lsp-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("util.dino"), "pub func twice(x: int): int { return x * 2 }\n").unwrap();
|
||||
let uri = format!("file://{}/main.dino", dir.display());
|
||||
let src = "import util\nfunc main() {\n print(util.twice(2))\n}\n";
|
||||
let mut msgs = vec![open(&uri, src)];
|
||||
msgs.extend(exit_messages());
|
||||
let (out, _) = talk(msgs);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(out[0].path(&["params", "diagnostics"]), Some(&Json::Arr(vec![])), "{:?}", out[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_requests_get_an_error() {
|
||||
let mut msgs = vec![request(5, "textDocument/codeLens", Json::obj(vec![]))];
|
||||
msgs.extend(exit_messages());
|
||||
let (out, _) = talk(msgs);
|
||||
assert!(out[0].path(&["error", "message"]).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editor_files_are_valid_json() {
|
||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("editors/vscode");
|
||||
for f in ["package.json", "language-configuration.json", "syntaxes/dino.tmLanguage.json"] {
|
||||
let text = std::fs::read_to_string(dir.join(f)).unwrap();
|
||||
json::parse(&text).unwrap_or_else(|e| panic!("{f}: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- code intelligence ----------
|
||||
|
||||
const SRC: &str = "// Adds two numbers.\nfunc add(a: int, b: int): int {\n var sum = a + b\n return sum\n}\n\nstruct P {\n x: int\n}\n\nfunc main() {\n var t = add(1, 2)\n print(t)\n}\n";
|
||||
|
||||
fn at(uri: &str, line: i64, ch: i64) -> Json {
|
||||
Json::obj(vec![
|
||||
("textDocument", Json::obj(vec![("uri", Json::str(uri))])),
|
||||
("position", Json::obj(vec![("line", Json::Num(line as f64)), ("character", Json::Num(ch as f64))])),
|
||||
])
|
||||
}
|
||||
|
||||
fn ask(method: &str, params: Json) -> Json {
|
||||
let mut msgs = vec![request(1, "initialize", Json::obj(vec![])), open("file:///x/a.dino", SRC), request(2, method, params)];
|
||||
msgs.extend(exit_messages());
|
||||
let (out, _) = talk(msgs);
|
||||
out.into_iter().find(|m| m.get("id") == Some(&Json::Num(2.0))).unwrap().get("result").cloned().unwrap_or(Json::Null)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_lists_top_level_names() {
|
||||
let r = ask("textDocument/documentSymbol", Json::obj(vec![("textDocument", Json::obj(vec![("uri", Json::str("file:///x/a.dino"))]))]));
|
||||
let text = r.to_string();
|
||||
assert!(text.contains("\"add\"") && text.contains("\"P\"") && text.contains("\"main\"") && text.contains("\"x\""), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn definition_jumps_to_the_function() {
|
||||
let r = ask("textDocument/definition", at("file:///x/a.dino", 11, 14));
|
||||
assert_eq!(r.path(&["range", "start", "line"]).and_then(Json::as_i64), Some(1), "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn definition_finds_a_local() {
|
||||
let r = ask("textDocument/definition", at("file:///x/a.dino", 3, 12));
|
||||
assert_eq!(r.path(&["range", "start", "line"]).and_then(Json::as_i64), Some(2), "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_shows_the_signature_and_comment() {
|
||||
let r = ask("textDocument/hover", at("file:///x/a.dino", 11, 14));
|
||||
let v = r.path(&["contents", "value"]).and_then(Json::as_str).unwrap_or("").to_string();
|
||||
assert!(v.contains("func add(a: int, b: int): int") && v.contains("Adds two numbers."), "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_offers_names_and_keywords() {
|
||||
let r = ask("textDocument/completion", at("file:///x/a.dino", 12, 4)).to_string();
|
||||
assert!(r.contains("\"add\"") && r.contains("\"t\"") && r.contains("\"func\"") && r.contains("\"string\""), "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signature_help_marks_the_parameter() {
|
||||
let src = "func add(a: int, b: int): int {\n return a + b\n}\nfunc main() {\n add(1, \n}\n";
|
||||
let mut msgs = vec![request(1, "initialize", Json::obj(vec![])), open("file:///x/b.dino", src), request(2, "textDocument/signatureHelp", at("file:///x/b.dino", 4, 11))];
|
||||
msgs.extend(exit_messages());
|
||||
let (out, _) = talk(msgs);
|
||||
let r = out.into_iter().find(|m| m.get("id") == Some(&Json::Num(2.0))).unwrap().get("result").cloned().unwrap();
|
||||
assert_eq!(r.get("activeParameter").and_then(Json::as_i64), Some(1), "{r:?}");
|
||||
assert!(r.to_string().contains("add(a: int, b: int): int"), "{r:?}");
|
||||
}
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
use dino::ast::*;
|
||||
use dino::parser::parse;
|
||||
|
||||
fn body_of(src: &str) -> Vec<Stmt> {
|
||||
let p = parse(src).unwrap_or_else(|d| panic!("{}", d.render("test", src)));
|
||||
match &p.items[0] {
|
||||
Item::Func(f) => f.body.clone().unwrap().stmts,
|
||||
other => panic!("expected func, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn first_expr(src: &str) -> Expr {
|
||||
match body_of(&format!("func f() {{\n{src}\n}}")).remove(0) {
|
||||
Stmt::Expr(e) => e,
|
||||
Stmt::Return { mut values, .. } => values.remove(0),
|
||||
other => panic!("unexpected {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_examples_parse() {
|
||||
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples");
|
||||
let mut n = 0;
|
||||
for entry in std::fs::read_dir(dir).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().map_or(false, |e| e == "dino") {
|
||||
let src = std::fs::read_to_string(&path).unwrap();
|
||||
parse(&src).unwrap_or_else(|d| panic!("{}", d.render(path.to_str().unwrap(), &src)));
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
assert!(n >= 4, "expected the example programs, found {n}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn precedence() {
|
||||
// 1 + 2 * 3 => 1 + (2 * 3)
|
||||
let e = first_expr("1 + 2 * 3");
|
||||
match e.kind {
|
||||
ExprKind::Binary { op: BinOp::Add, rhs, .. } => {
|
||||
assert!(matches!(rhs.kind, ExprKind::Binary { op: BinOp::Mul, .. }))
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// a || b && c => a || (b && c)
|
||||
let e = first_expr("a || b && c");
|
||||
match e.kind {
|
||||
ExprKind::Binary { op: BinOp::Or, rhs, .. } => {
|
||||
assert!(matches!(rhs.kind, ExprKind::Binary { op: BinOp::And, .. }))
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// subtraction is left-associative: 10 - 3 - 2 => (10 - 3) - 2
|
||||
let e = first_expr("10 - 3 - 2");
|
||||
match e.kind {
|
||||
ExprKind::Binary { op: BinOp::Sub, lhs, .. } => {
|
||||
assert!(matches!(lhs.kind, ExprKind::Binary { op: BinOp::Sub, .. }))
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges() {
|
||||
assert!(matches!(first_expr("0..10").kind, ExprKind::Range { start: Some(_), end: Some(_) }));
|
||||
assert!(matches!(first_expr("args[1..]").kind, ExprKind::Index { .. }));
|
||||
let e = first_expr("xs[..3]");
|
||||
match e.kind {
|
||||
ExprKind::Index { index, .. } => {
|
||||
assert!(matches!(index.kind, ExprKind::Range { start: None, end: Some(_) }))
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_vs_range() {
|
||||
assert!(matches!(first_expr("1.5").kind, ExprKind::Float(_)));
|
||||
assert!(matches!(first_expr("1..5").kind, ExprKind::Range { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpolation() {
|
||||
let e = first_expr(r#""hi {name}, you are {age + 1}!""#);
|
||||
match e.kind {
|
||||
ExprKind::Str(parts) => {
|
||||
assert_eq!(parts.len(), 5);
|
||||
assert!(matches!(parts[0], StrPart::Text(_)));
|
||||
assert!(matches!(parts[1], StrPart::Expr(_)));
|
||||
assert!(matches!(&parts[4], StrPart::Text(t) if t == "!"));
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escaped_brace_is_plain_text() {
|
||||
let e = first_expr(r#""\{ not code \}""#);
|
||||
match e.kind {
|
||||
ExprKind::Str(parts) => assert_eq!(parts, vec![StrPart::Text("{ not code }".into())]),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn struct_literal_vs_block() {
|
||||
// `if a == b {` must be a block, not `b { ... }` as a struct literal.
|
||||
let stmts = body_of("func f() {\nif a == b { x = 1 }\n}");
|
||||
assert!(matches!(stmts[0], Stmt::If { .. }));
|
||||
// But a literal is fine on the right of `=` and inside parens in a header.
|
||||
let stmts = body_of("func f() {\nvar p = Point{1, 2}\nif p == (Point{1, 2}) { x = 1 }\n}");
|
||||
assert!(matches!(stmts[0], Stmt::Var(_)));
|
||||
assert!(matches!(stmts[1], Stmt::If { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_forms() {
|
||||
let stmts = body_of(
|
||||
"func f() {\nfor { break }\nfor x < 3 { x += 1 }\nfor i in 0..10 step 2 { }\nfor i, x in xs { }\n}",
|
||||
);
|
||||
assert!(matches!(&stmts[0], Stmt::For { kind: ForKind::Infinite, .. }));
|
||||
assert!(matches!(&stmts[1], Stmt::For { kind: ForKind::While(_), .. }));
|
||||
match &stmts[2] {
|
||||
Stmt::For { kind: ForKind::In { vars, step, .. }, .. } => {
|
||||
assert_eq!(vars.len(), 1);
|
||||
assert!(step.is_some());
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
match &stmts[3] {
|
||||
Stmt::For { kind: ForKind::In { vars, .. }, .. } => assert_eq!(vars, &["i", "x"]),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouped_params() {
|
||||
let p = parse("func f(a, b: int, s: string) {}").unwrap();
|
||||
let Item::Func(f) = &p.items[0] else { panic!() };
|
||||
let names: Vec<_> = f.params.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(names, ["a", "b", "s"]);
|
||||
assert_eq!(f.params[0].ty, f.params[1].ty);
|
||||
assert_ne!(f.params[1].ty, f.params[2].ty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn struct_with_methods() {
|
||||
let p = parse("pub struct P {\n x, y: f32\n pub func len(): f32 { return x }\n}").unwrap();
|
||||
let Item::Struct(s) = &p.items[0] else { panic!() };
|
||||
assert!(s.is_pub);
|
||||
assert_eq!(s.fields.len(), 2);
|
||||
assert_eq!(s.methods.len(), 1);
|
||||
assert!(s.methods[0].is_pub);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn types() {
|
||||
let p = parse("struct E {\n a: shared Doc\n b: weak Win?\n c: []int\n d: Stack[int]\n e: ui.Key\n}").unwrap();
|
||||
let Item::Struct(s) = &p.items[0] else { panic!() };
|
||||
assert!(matches!(s.fields[0].ty, Type::Shared(_)));
|
||||
assert!(matches!(s.fields[1].ty, Type::Optional(_)));
|
||||
assert!(matches!(s.fields[2].ty, Type::Slice(_)));
|
||||
assert!(matches!(&s.fields[3].ty, Type::Named { args, .. } if args.len() == 1));
|
||||
assert!(matches!(&s.fields[4].ty, Type::Named { path, .. } if path.len() == 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_returns() {
|
||||
let p = parse("func f(): (int, error) { return 1, nil }").unwrap();
|
||||
let Item::Func(f) = &p.items[0] else { panic!() };
|
||||
assert!(matches!(&f.ret, Some(Type::Tuple(t)) if t.len() == 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_line_call_and_literal() {
|
||||
parse("func f() {\n g(\n 1,\n 2,\n)\n var p = P{\n x: 1,\n y: 2,\n }\n}").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn else_if_chain() {
|
||||
let stmts = body_of("func f() {\nif a { } else if b { } else { }\n}");
|
||||
let Stmt::If { else_: Some(e), .. } = &stmts[0] else { panic!() };
|
||||
assert!(matches!(**e, Stmt::If { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semicolons_work() {
|
||||
parse("func f() { var a = 1; var b = 2 }").unwrap();
|
||||
}
|
||||
|
||||
// ---------- error messages ----------
|
||||
|
||||
fn err(src: &str) -> dino::error::Diag {
|
||||
parse(src).unwrap_err()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_unclosed_brace_points_at_opener() {
|
||||
let d = err("func main() {\n var x = 1\n");
|
||||
assert!(d.msg.contains("never closed"), "{}", d.msg);
|
||||
assert_eq!((d.span.line, d.span.col), (1, 13));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_unterminated_string() {
|
||||
let d = err("func main() {\n var x = \"oops\n}");
|
||||
assert!(d.msg.contains("never closed"), "{}", d.msg);
|
||||
assert_eq!(d.span.line, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_missing_param_type() {
|
||||
let d = err("func f(a) {}");
|
||||
assert!(d.msg.contains("`a` needs a type"), "{}", d.msg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_global_var() {
|
||||
let d = err("var x = 1");
|
||||
assert!(d.msg.contains("global `var`"), "{}", d.msg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_const_needs_value() {
|
||||
assert!(err("func f() { const x: int }").msg.contains("const"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_single_ampersand() {
|
||||
assert!(err("func f() { var a = b & c }").msg.contains("&&"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_two_statements_on_one_line() {
|
||||
let d = err("func f() { var a = 1 var b = 2 }");
|
||||
assert!(d.msg.contains("end of line"), "{}", d.msg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_shows_caret() {
|
||||
let src = "func main() {\n var x = \n}";
|
||||
let out = err(src).render("t.dino", src);
|
||||
assert!(out.contains("t.dino:3:1"), "{out}");
|
||||
assert!(out.contains("^"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_bound_uses_a_colon() {
|
||||
let p = parse("func max[T: Ordered](a, b: T): T { return a }").unwrap();
|
||||
let Item::Func(f) = &p.items[0] else { panic!() };
|
||||
assert_eq!(f.type_params[0].name, "T");
|
||||
assert!(f.type_params[0].constraint.is_some());
|
||||
assert!(parse("func max[T](a: T) { }").is_ok());
|
||||
let e = parse("func max[T Ordered](a: T) { }").unwrap_err();
|
||||
assert!(e.msg.contains("`:` and then the rule"), "{}", e.msg);
|
||||
}
|
||||
+2250
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user