Phase 2 · 2 of 5Being built in the open: see the roadmap →

A language for building AI software.

C#-style syntax. Rust-style types. Permissions on every function. Compiled to WebAssembly, so the same code runs in the browser, on servers and at the edge. Easy for people to read, and for coding agents to write.

Runs today: numbers, strings, functions and control flow, plus objects, generics and interfaces. Still to come in Phase 2: standard library core, closures and hashed collections, bytes. Permissions arrive in Phase 5 and the AI library in Phase 6; until then the compiler checks them but can't run them.

$cargo install --git https://github.com/sanjay-bhat/cairn cairn

Needs Rust. Prebuilt downloads are on GitHub Releases.

An enum that refers to itself, walked with match and is.

1// A linked list written as an enum: built, walked, compared and printed (Phase 2, M1).
2enum IntList {
3 Cons(int Head, IntList Tail),
4 Nil,
5}
6
7IntList Range(int from, int to) =>
8 if (from > to) IntList.Nil else IntList.Cons(from, Range(from + 1, to));
9
10int Sum(IntList list) => match list {
11 Cons(head, tail) => head + Sum(tail),
12 Nil => 0,
13};
14
15IntList Reverse(IntList list) {
16 var result = IntList.Nil;
17 var rest = list;
18 while (rest is Cons(head, tail)) {
19 result = IntList.Cons(head, result);
20 rest = tail;
21 }
22 return result;
23}
24
25IntList Map(IntList list, int by) => match list {
26 Cons(head, tail) => IntList.Cons(head * by, Map(tail, by)),
27 Nil => IntList.Nil,
28};
29
30let list = Range(1, 4);
31Console.Print(list);
32Console.Print(Sum(list));
33Console.Print(Reverse(list));
34Console.Print(Map(list, 10));
35Console.Print(list == Range(1, 4));
36Console.Print(list == Reverse(list));
37Console.Print(IntList.Nil == IntList.Nil);
38
39// A long list: building and summing 10 000 nodes.
40Console.Print(Sum(Range(1, 10000)));
linked-list.wasm · 875 B
These programs were compiled to WebAssembly by today's Cairn compiler when this page was built. Press Run to execute one here, with Wasm GC.

LeetCode #1, three ways

Two Sum in C#, Rust and Cairn

Find two numbers in a list that add up to a target, and return their positions. Pick an idea below to see how each language says it, or point at any line to find its match in the others.

cairn check: no errorsruns once lists and maps compile (Phase 2, milestone 4)
C#TwoSum.cs41 lines
1using System;
2using System.Collections.Generic;
3using Xunit;
4
5public static class Solution
6{
7 /// <summary>The indices of the two numbers in nums that add up to target, or null.</summary>
8 public static (int, int)? TwoSum(int[] nums, int target)
9 {
10 var seen = new Dictionary<int, int>(); // value -> index
11 for (int i = 0; i < nums.Length; i++)
12 {
13 if (seen.TryGetValue(target - nums[i], out int j))
14 {
15 return (j, i);
16 }
17 seen[nums[i]] = i;
18 }
19 return null;
20 }
21
22 public static void Main()
23 {
24 var answer = TwoSum(new[] { 2, 7, 11, 15 }, 9);
25 Console.WriteLine(answer switch
26 {
27 (int a, int b) => $"indices {a} and {b}",
28 null => "no pair",
29 });
30 }
31}
32
33public class TwoSumTests
34{
35 [Fact]
36 public void FindsThePair() =>
37 Assert.Equal((0, 1), Solution.TwoSum(new[] { 2, 7, 11, 15 }, 9));
38
39 [Fact]
40 public void UsesEachNumberOnce()
41 {
42 Assert.Equal((0, 1), Solution.TwoSum(new[] { 3, 3 }, 6));
43 Assert.Null(Solution.TwoSum(new[] { 3 }, 6));
44 }
45}
Rusttwo_sum.rs32 lines
1use std::collections::HashMap;
2
3/// The indices of the two numbers in `nums` that add up to `target`, if there are any.
4fn two_sum(nums: &[i32], target: i32) -> Option<(usize, usize)> {
5 let mut seen: HashMap<i32, usize> = HashMap::new(); // value -> index
6 for (i, &n) in nums.iter().enumerate() {
7 if let Some(&j) = seen.get(&(target - n)) {
8 return Some((j, i));
9 }
10 seen.insert(n, i);
11 }
12 None
13}
14
15fn main() {
16 let answer = two_sum(&[2, 7, 11, 15], 9);
17 println!("{}", match answer {
18 Some((a, b)) => format!("indices {a} and {b}"),
19 None => "no pair".to_string(),
20 });
21}
22
23#[cfg(test)]
24mod tests {
25 use super::*;
26
27 #[test]
28 fn finds_the_pair() {
29 assert_eq!(two_sum(&[2, 7, 11, 15], 9), Some((0, 1)));
30 }
31
32 #[test]
33 fn uses_each_number_once() {
34 assert_eq!(two_sum(&[3, 3], 6), Some((0, 1)));
35 assert_eq!(two_sum(&[3], 6), None);
36 }
37}
Cairntwo-sum.crn24 lines
1// Two Sum: Option instead of null, a Map, tuples, `is` patterns and test blocks.
2
3/// The indices of the two numbers in `nums` that add up to `target`, if there are any.
4(int, int)? TwoSum(List<int> nums, int target) {
5 var seen: Map<int, int> = [:]; // value -> index
6 foreach ((i, n) in nums.Indexed()) {
7 if (seen.Get(target - n) is Some(j)) {
8 return Some((j, i));
9 }
10 seen[n] = i;
11 }
12 return None;
13}
14
15let answer = TwoSum([2, 7, 11, 15], 9);
16Console.Print(match answer {
17 Some((a, b)) => $"indices {a} and {b}",
18 None => "no pair",
19});
20
21test "finds the pair" {
22 Assert.Equal(TwoSum([2, 7, 11, 15], 9), Some((0, 1)));
23}
24
25test "uses each number once" {
26 Assert.Equal(TwoSum([3, 3], 6), Some((0, 1)));
27 Assert.Equal(TwoSum([3], 6), None);
28}
At a glanceC#RustCairn
"No answer" isnullNone, and the compiler makes you handle itNone, and the compiler makes you handle it. There is no null
MemoryGarbage collected (.NET runtime)Ownership and borrowingGarbage collected by the host's Wasm GC, so there's no runtime to download
TestsA separate package (xUnit)Built in: #[test]Built in: test "name" { ... } next to the code
Compiles to.NET ILNative code, or WasmWebAssembly with GC: browsers, Node, Deno, Bun, edge workers
Errors for toolsText, and SARIFText, and JSONText, or JSON where every fix is data a tool can apply (below)

Errors built for people and agents

Make a mistake. Get the fix.

Break the Cairn version of Two Sum the way people (and models) often do. Every message below is what cairn check really printed when this page was built, and every fix is data an editor or coding agent can apply without guessing.

two-sum.crn
1// Two Sum: Option instead of null, a Map, tuples, `is` patterns and test blocks.
2
3/// The indices of the two numbers in `nums` that add up to `target`, if there are any.
4(int, int)? TwoSum(List<int> nums, int target) {
5 var seen: Map<int, int> = [:]; // value -> index
6 foreach ((i, n) in nums.Indexed()) {
7 if (seen.Get(target - n) is Some(j)) {
8 return Some((j, i));
9 }
10 seen[n] = i;
11 }
12 return None;
13}
14
15let answer = TwoSum([2, 7, 11, 15], 9);
16Console.Print(match answer {
17 Some((a, b)) => $"indices {a} and {b}",
18 None => "no pair",
19});
20
21test "finds the pair" {
22 Assert.Equal(TwoSum([2, 7, 11, 15], 9), Some((0, 1)));
23}
24
25test "uses each number once" {
26 Assert.Equal(TwoSum([3, 3], 6), Some((0, 1)));
27 Assert.Equal(TwoSum([3], 6), None);
28}
cairn check
Checked 1 file: no errors.
Pick a mistake above.

Why Cairn

Made for the software AI is changing

Model calls, tools and evals are part of the language, so the compiler can check them. These programs pass cairn check today; the features they use compile in the phases shown.

examples/08-ai-triage.crn
1// AI 1 of 3: typed structured output.
2// The JSON schema sent to the model is generated from `Review`, including the doc comments.
3// The reply is parsed into a Review, or the call returns a typed ModelError.
4
5uses Llm;
6
7using Std.Ai;
8
9/// How the customer feels about the product.
10enum Sentiment {
11 Positive,
12 Negative,
13 /// Both good and bad points.
14 Mixed(
15 /// What is good and what is bad, in a few words.
16 string Reason),
17}
18
19record Review(
20 /// Star rating the review implies, 1 to 5.
21 [Range(1, 5)] int Stars,
22 Sentiment Sentiment,
23 /// One sentence, under 30 words.
24 [MaxLength(200)] string Summary,
25 /// Product problems mentioned, if any.
26 List<string> Problems);
27
28async Result<Review, ModelError> Triage(string text) uses Llm =>
29 await Llm.Ask<Review>(
30 $"Classify this product review.\n\n{text}",
31 model: "fast",
32 temperature: 0.0);
33
34let input = "The kettle looks great and boils fast, but the lid broke after a week.";
35
36match await Triage(input) {
37 Ok(review) => {
38 Console.Print($"{review.Stars} stars, {review.Sentiment}");
39 Console.Print(review.Summary);
40 foreach (problem in review.Problems) Console.Print($" - {problem}");
41 },
42 Err(ModelError.InvalidOutput(raw, problem)) => Console.Print($"model reply didn't fit the schema: {problem}"),
43 Err(e) => Console.Print($"model call failed: {e}"),
44}
45
46// Tests answer from a recording, so they run offline and cost nothing.
47// `cairn test --record` makes the real call once and writes the file.
48[Replay("cassettes/08-mixed-review.jsonl")]
49test "a mixed review is Mixed and lists the problem" {
50 let review = (await Triage(input)).Unwrap();
51 Assert.True(review.Sentiment is Sentiment.Mixed(_));
52 Assert.True(review.Problems.Any(p => p.Contains("lid")));
53}
54
55test "the schema matches the type" {
56 let schema = Schema.Of<Review>();
57 Assert.Equal(schema.Required, ["Stars", "Sentiment", "Summary", "Problems"]);
58 Assert.Equal(schema.Property("Stars").Maximum, Some(5.0));
59}

Where it's at

Built in the open, phase by phase

Each phase ends on a test you can run. Phases 9 to 13 (notebooks, UI, WebGPU, data tables, native mobile apps) come after the v0.1 release.

PHASE 0Spec and decisions✓ done
PHASE 1Language core✓ done
PHASE 2Heap data on Wasm GC● now
PHASE 3Tooling and playgroundplanned
PHASE 4Runs everywhereplanned
PHASE 5Permissionsplanned
PHASE 6AI standard libraryplanned
PHASE 7Evals and replayplanned
PHASE 8Packages, docs and releaseplanned
M1. Objectsdone
M2. Generics and interfacesdone
M3. Standard library corenot started
M4. Closures and hashed collectionsnot started
M5. Bytesnot started

The full plan, with what each phase delivers and why: the roadmap.

Where Cairn fits

Why not just use…

Instead ofWhy pick CairnWhy people stay
TypeScriptReal enums with data, exhaustive match, no undefined, typed model calls without extra librariesNo friction with the DOM and npm; a huge ecosystem
Rust + WasmNo borrow checker; graphs and trees without Rc<RefCell>Raw speed, SIMD, crates
C# and BlazorSmall downloads instead of a shipped .NET runtimeReal C#, NuGet, Microsoft support
Kotlin/WasmA lighter toolchain; AI building blocks in the languageCompose UI, multiplatform, JetBrains
MoonBitFamiliar C#-style syntax; model calls, tools and declared permissions in the languageAlready does Rust-style types on Wasm GC with tiny binaries