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 cairnNeeds 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}67IntList Range(int from, int to) =>8 if (from > to) IntList.Nil else IntList.Cons(from, Range(from + 1, to));910int Sum(IntList list) => match list {11 Cons(head, tail) => head + Sum(tail),12 Nil => 0,13};1415IntList 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}2425IntList Map(IntList list, int by) => match list {26 Cons(head, tail) => IntList.Cons(head * by, Map(tail, by)),27 Nil => IntList.Nil,28};2930let 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);3839// A long list: building and summing 10 000 nodes.40Console.Print(Sum(Range(1, 10000)));
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.
1using System;2using System.Collections.Generic;3using Xunit;45public static class Solution6{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 -> index11 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 }2122 public static void Main()23 {24 var answer = TwoSum(new[] { 2, 7, 11, 15 }, 9);25 Console.WriteLine(answer switch26 {27 (int a, int b) => $"indices {a} and {b}",28 null => "no pair",29 });30 }31}3233public class TwoSumTests34{35 [Fact]36 public void FindsThePair() =>37 Assert.Equal((0, 1), Solution.TwoSum(new[] { 2, 7, 11, 15 }, 9));3839 [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}
1use std::collections::HashMap;23/// 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 -> index6 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 None13}1415fn 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}2223#[cfg(test)]24mod tests {25 use super::*;2627 #[test]28 fn finds_the_pair() {29 assert_eq!(two_sum(&[2, 7, 11, 15], 9), Some((0, 1)));30 }3132 #[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}
1// Two Sum: Option instead of null, a Map, tuples, `is` patterns and test blocks.23/// 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 -> index6 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}1415let answer = TwoSum([2, 7, 11, 15], 9);16Console.Print(match answer {17 Some((a, b)) => $"indices {a} and {b}",18 None => "no pair",19});2021test "finds the pair" {22 Assert.Equal(TwoSum([2, 7, 11, 15], 9), Some((0, 1)));23}2425test "uses each number once" {26 Assert.Equal(TwoSum([3, 3], 6), Some((0, 1)));27 Assert.Equal(TwoSum([3], 6), None);28}
| At a glance | C# | Rust | Cairn |
|---|---|---|---|
| "No answer" is | null | None, and the compiler makes you handle it | None, and the compiler makes you handle it. There is no null |
| Memory | Garbage collected (.NET runtime) | Ownership and borrowing | Garbage collected by the host's Wasm GC, so there's no runtime to download |
| Tests | A separate package (xUnit) | Built in: #[test] | Built in: test "name" { ... } next to the code |
| Compiles to | .NET IL | Native code, or Wasm | WebAssembly with GC: browsers, Node, Deno, Bun, edge workers |
| Errors for tools | Text, and SARIF | Text, and JSON | Text, 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.
1// Two Sum: Option instead of null, a Map, tuples, `is` patterns and test blocks.23/// 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 -> index6 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}1415let answer = TwoSum([2, 7, 11, 15], 9);16Console.Print(match answer {17 Some((a, b)) => $"indices {a} and {b}",18 None => "no pair",19});2021test "finds the pair" {22 Assert.Equal(TwoSum([2, 7, 11, 15], 9), Some((0, 1)));23}2425test "uses each number once" {26 Assert.Equal(TwoSum([3, 3], 6), Some((0, 1)));27 Assert.Equal(TwoSum([3], 6), None);28}
Checked 1 file: no errors.
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.
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.45uses Llm;67using Std.Ai;89/// 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}1819record 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);2728async 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);3334let input = "The kettle looks great and boils fast, but the lid broke after a week.";3536match 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}4546// 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}5455test "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.
The full plan, with what each phase delivers and why: the roadmap.
Where Cairn fits
Why not just use…
| Instead of | Why pick Cairn | Why people stay |
|---|---|---|
| TypeScript | Real enums with data, exhaustive match, no undefined, typed model calls without extra libraries | No friction with the DOM and npm; a huge ecosystem |
| Rust + Wasm | No borrow checker; graphs and trees without Rc<RefCell> | Raw speed, SIMD, crates |
| C# and Blazor | Small downloads instead of a shipped .NET runtime | Real C#, NuGet, Microsoft support |
| Kotlin/Wasm | A lighter toolchain; AI building blocks in the language | Compose UI, multiplatform, JetBrains |
| MoonBit | Familiar C#-style syntax; model calls, tools and declared permissions in the language | Already does Rust-style types on Wasm GC with tiny binaries |