Language Essentials
Datascript is a typed scripting language designed for data workflows.
Variables are declared with declare; constants use
declare const. Assignments require an initializer for
constants.
declare count = 0;
declare const greeting = "hello";
count = count + 1;
Comments use //. Statements end with semicolons, except
block constructs like if, while, and
func bodies.
Data Types
Primitive and structural types are supported:
- Number — double precision (
42) - String — double quoted (
"text") - Boolean —
trueorfalse - Null —
null - Array —
[1, 2, 3] - Object —
{ key: value }
declare profile = {
name: "Ada",
skills: ["analysis", "automation"],
active: true,
};
Control Flow
Datascript provides the familiar branching and looping constructs plus
try/catch for exception handling.
if (count > 10) {
print("large");
} else if (count == 10) {
print("equal");
} else {
print("small");
}
while (count < 5) {
count = count + 1;
}
try {
riskyTask();
} catch (error) {
print("Recovering:", error);
}
Functions
Functions are defined with func. Parameters can include
default values and optional type annotations.
func formatUser(name: string, email: string = "n/a") {
return name + " <" + email + ">";
}
print(formatUser("Ada", "ada@example.com"));
Anonymous functions can be assigned to variables, and native
await is available inside async-aware contexts.
Objects & Arrays
Object literals support shorthand and string keys. Arrays provide the
standard iteration and indexing capabilities. Utilities like
entries(), keys(), values(),
and len() are available as native functions.
declare metrics = [1, 3, 5];
declare index = 0;
while (index < len(metrics)) {
print(metrics[index]);
index = index + 1;
}
declare config = {
"x-api-key": "demo",
retries: 3,
};
Classes & Schemas
Schemas extend the language with lightweight data models. Declare
required and optional fields, provide defaults, and even add methods.
Instances automatically gain a save() helper for
inspection or persistence hooks.
schema User create(username: string, email: string) {
required username: string;
required email: string;
optional roles: array = ["user"];
describe() {
print(username, roles);
}
}
declare admin = User({ username: "admin", email: "admin@example.com" });
admin.describe();
admin.save();
For heavier logic, use class declarations (similar
syntax) to define behaviors without schema semantics.
Modules
Organize code with import and export. Modules
support namespace, named, and default exports.
// math.ds
export declare answer = 42;
export func double(x) { return x * 2; }
// consumer.ds
import "./math.ds" exposing { double };
print(double(21));
The runtime caches modules, ensuring imports are evaluated once per execution.
Async & Promises
Use await to resolve promises. Native helpers like
sleep(ms) return promises for timing and scheduling.
func pingService(url: string) {
declare response = await fetch(url);
return await response.json();
}
await sleep(500);
Error Handling
Throw values of any type. Catch blocks can optionally bind the error to an identifier.
func ensurePositive(value: number) {
if (value <= 0) {
throw "Value must be positive.";
}
return value;
}
try {
ensurePositive(-5);
} catch (error) {
print("Validation failed:", error);
}
Mongo DSL
The Mongo DSL adds ergonomic syntax for connections, collection defaults, CRUD operators, query pipelines, and session scopes.
Scoped Connections
using mongo from mongoUri database "analytics" as db with {
collections: {
users: {
projection: { email: 1, createdAt: 1 },
sort: { createdAt: -1 },
limit: 25,
},
},
} {
use collection users;
users <- { email: "demo@example.com" };
}
Operators & Queries
<-insert?find one,??find many!delete one,!!delete many|>aggregate pipelineupdate where ... set ...updates
declare marker = "demo-" + toString(time());
users <- {
email: marker + "@example.com",
createdAt: time(),
};
declare fetched = (users ? query { email == marker + "@example.com" }).value;
users update where query { email == fetched.email } set {
"$set": { lastSeenAt: time() },
};
Aggregation Helpers
declare summary = (activity_logs |> [
match(eq("email", marker + "@example.com")),
sort({ at: -1 }),
limit(5),
project({ email: 1, at: 1 }),
]).value;
Schemas in Mongo Workflows
schema DemoUser create(name: string, email: string) {
required name: string;
required email: string;
optional tier: string = "free";
}
declare userDoc = DemoUser({
name: "Schema Example",
email: "schema@example.com",
tier: "gold",
});
users <- {
email: userDoc.email,
name: userDoc.name,
tier: userDoc.tier,
createdAt: time(),
};
CLI & Tooling
Run Datascript files via deno run main.ts path/to/script.ds.
Helpful native utilities:
print(),debug(),info()— loggingassert(condition, message)— runtime checkstime(),sleep(ms),schedule()— timingclone(),deepClone()— data helpersenv(key)— environment variables
For linting and type checks, run deno lint and
deno check at the repository root.
Reference & Files
Frontend
frontend/lexer.ts— tokenizationfrontend/parser.ts— AST builderfrontend/ast.ts— node definitions
Runtime
runtime/interpreter.ts— dispatchruntime/eval/expressions.tsruntime/eval/statements.tsruntime/mongo.ts&mongoState.tsruntime/functions.ts— native APIs
Samples
scripts/mongo_test.dsscripts/schemas.dsscripts/diagnostics.dsscripts/all.ds