Compare commits

..

No commits in common. "main" and "to_janet" have entirely different histories.

32 changed files with 838 additions and 2389 deletions

1
.gitignore vendored
View File

@ -33,4 +33,3 @@ target/repl-port
.repl-buffer.janet .repl-buffer.janet
.env .env
src/jpm_tree src/jpm_tree
.zig-cache

View File

@ -2,37 +2,48 @@
## Ludus: A friendly, dynamic, functional language ## Ludus: A friendly, dynamic, functional language
Ludus is a scripting programming language that is designed to be friendly, dynamic, and functional. Ludus is a scripting programming language that is designed to be friendly, dynamic, and functional.
This repo currently contains a work-in-progress implementation of an interpreter for the Ludus programming language, using [Janet](https://janet-lang.org) as a host language. This repo currently contains an in-progress reference implementation of an interpreter for the Ludus programming language, using Clojure as a host language.
Ludus is part of the [_Thinking with Computers_ project](https://alea.ludus.dev/twc/), run by Scott Richmond at the University of Toronto, with collaborator Matt Nish-Lapidus; Bree Lohman and Mynt Marsellus are the RAs for the project. Ludus is our research language, which aspires to be a free translation of Logo for the 2020s.
Ludus is part of the [_Thinking with Computers_ project](https://thinking-with-computers.github.io), run by Scott Richmond at the University of Toronto, with collaborator Matt Nish-Lapidus; Bree Lohman and Mynt Marsellus are the RAs for the project. Ludus is our research language, which aspires to be a free translation of Logo for the 2020s.
Here are our design goals: Here are our design goals:
#### Friendly #### Friendly
Ludus, like Logo, is meant to be a teaching language, often for students who don't think of themselves as "computer people." Our intended audience are humanities and art people at the university level (undergrads, grads, faculty). Everything is kept as simple as possible, but no simpler. Everything is consistent as possible. We aspire to the best error messages we can muster, which is important for a language to be teachable. That means being as strict as we can muster, _in order to be friendlier_. Ludus, like Logo, is meant to be a teaching language, often for students who don't think of themselves as "computer people." Our intended audience are humanities and art people at the University level (undergrads, grads, faculty). Everything is kept as simple as possible, but no simpler. Everything is consistent as possible. We aspire to the best error messages we can muster, which is important for a language to be teachable. That means being as strict as we can muster, _in order to be friendlier_.
Our current development target is Ludus on the web: https://web.ludus.dev. That wires what we do on the langauge interpreter (here in this repo) to a web frontend. Our current development target is Ludus on the web: https://thinking-with-computers/ludus-web. That wires what we do on the langauge interpreter (here in this repo) to a web frontent.
Naturally, it starts with Logo's famed turtle graphics. Naturally, it starts with Logo's famed turtle graphics.
#### Dynamic #### Dynamic
Statically typed programming languages generally give more helpful error messages than dynamic ones, but learning a type system (even one with robust type inference) requires learning two parallel systems: the type system and the expression system (well, and the pattern system). Type systems only really make sense once you've learned why they're necessary. And their benefits seem (to us, anyway) to be largely necessary when writing long-lived, maintainable, multi-author code. Ludus code is likely to be one-off, expressive, and single-authored. Statically typed programming languages generally give more helpful error messages than dynamic ones, but learning a type system (even one with robust type inference) requires learning two parallel systems: the type system and the expression system. Type systems only really make sense once you've learned why they're necessary. And their benefits seem (to us, anyway) to be largely necessary when writing long-lived, maintainable, multiauthor code. Ludus code is likely to be one-off, expressive, and single-authored.
To stay friendly, Ludus is dynamic. But: despite the dynamism, we aim to be as strict as possible. Certainly, we want to avoid the type conversion shenanigans of a language like JavaScript. To stay friendly, Ludus is dynamic. But: despite the dynamism, we aim to be as strict as possible. Certainly, we want to avoid the type conversion shenanigans of a language like JavaScript.
#### Functional #### Functional
Ludus is emphatically functional: it uses functions for just about everything. This is both because your humble PI had his world reordered when he learned his first functional language (Elixir), and because the research into Logo and the programming cultures of MIT in the 1970s revolve around extremely functional Lisp code (i.e., Scheme). Logo is a weird little language, but it is a descendant of Lisp. So is Ludus. Ludus is emphatically functional: it uses functions for just about everything. This is both because your humble PI had his world reordered when he learned his first functional language (Elixir), and because the research into Logo and the programming cultures of MIT in the 1970s revolve around extremely functional Lisp code (i.e., Scheme). Logo is a weird little language, but it is a descendant of Lisp. So is Ludus.
Also, we believe that Ludus's immutable bindings and persistent or immutable data structures and careful approach to manipulating state lead to a lot of good pedagogical results. Learning a programming language involves learning how to model what's going on inside the computer; Ludus, we think, makes that both simpler and easier. Also, we believe that Ludus's immutable bindings and persistent or immutable data structures and careful approach to manipulating state lead to a lot of good pedagogical results. Learning a programming language involves learning how to model what's going on inside the computer; Ludus, we think, makes that simpler and easier.
If you're looking for cognate languages, Ludus takes a _lot_ of design inspiration from Clojure and Elixir (which itself took a lot from Clojure). (The current--quick, dirty, and slow--version of Ludus is written in [Janet](https://janet-lang.org).) Clojure and Elixir are great! If you're asking why you should use Ludus instead of them, you're already at the point where you should be using them. Ludus is, maybe, for the people whom you'd like to work with in 5 years at your Pheonix shop (but even then, probably not). If you're looking for cognate languages, Ludus takes a _lot_ of design inspiration from Clojure and Elixir (which itself took a lot from Clojure). (The current--quick, dirty, and slow--version of LUdus written in Clojure, in no small part to have access to persistent data structures that compile to JS.) Clojure and Elixir are great! If you're asking why you should use Ludus instead of them, you're already at the point where you should be using them. Ludus is, maybe, for the people whom you'd like to work with in 5 years at your Pheonix shop.
### Status ### Status
Pre-alpha, still under active development. Lots of things change all the time. Pre-alpha, still under active development. Lots of things change all the time. See [the ludus-spec repo for progress notes and additional documentation](https://github.com/thinking-with-computers/ludus-spec/blob/main/todo.md).
The current version of Ludus is a pure function that runs in JavaScript as a WASM blob. We have plans for more and better things. The current version of Ludus is a pure function that runs in JavaScript. We have plans for more and better things.
### Use ### Use
Current emphasis is on the web version: https://web.ludus.dev. Current emphasis is on the web version: see https://github.com/thinking-with-computers/ludus-web/.
Or, if you're on a Mac and want to open a terminal:
* Clone this repo.
- `git clone https://github.com/thinking-with-computers/ludus`
* Have Clojure and Leiningen installed.
- On a Mac: `brew install clojure leiningen`
* `lein run {script}`, it runs your script.
* `lein run`, it runs a REPL.
~Or, download a binary on the [releases page](https://github.com/thinking-with-computers/ludus/releases). (At current: M1 Mac only.)~
### Main features ### Main features
* Expression-oriented: everything returns a value * Expression-oriented: everything returns a value
@ -41,14 +52,17 @@ Current emphasis is on the web version: https://web.ludus.dev.
* Easy-peasy partial application with placeholders * Easy-peasy partial application with placeholders
* Function pipelines * Function pipelines
* Persistent or immutable data structures * Persistent or immutable data structures
* Careful, explicit state management using `box`es * Careful, explicit state management using `ref`erences
* Clean, concise, expressive syntax * Clean, concise, expressive syntax
* Value-based equality; only functions are reference types * Value-based equality; only functions are reference types
#### Under construction #### Under construction
* Actor-model style concurrency. * Tail call optimization
* Faster, bytecode-based VM written in a systems language, for better performance. * Actor model style concurrency?
* Performant persistent, immutable data structures, à la Clojure. * ~Strong nominal data typing, including tagged unions~
- ~Exhaustiveness-checking in `match` expressions in dynamically-typed code~
* Faster, bytecode-based VM written in a systems language, compiled to WASM for web use.
* Recursive descent parser with excellent parsing error message, just as soon as the syntax is fully stabilized.
### `Hello, world!` ### `Hello, world!`
Ludus is a scripting language. At current it does not have a good REPL. Our aim is to get interactive coding absolutely correct, and our efforts in [ludus-web](https://github.com/thinking-with-computers/ludus-web) are currently under way to surface the right interactivity models for Ludus. Ludus is a scripting language. At current it does not have a good REPL. Our aim is to get interactive coding absolutely correct, and our efforts in [ludus-web](https://github.com/thinking-with-computers/ludus-web) are currently under way to surface the right interactivity models for Ludus.
@ -70,7 +84,7 @@ print! ("Hello, world!")
=> :ok => :ok
``` ```
Here, we use the `print!` function, which sends a string to a console (`stdout` on Unix, or a little console box on the web). Because `print!` returns the keyword `:ok` when it completes, that is the result of the last expression in the script--and so Ludus also prints this. Or, you can use a the `print!` function, which sends a string to a console (`stdout` on Unix, or a little console box on the web). Because `print!` returns the keyword `:ok` when it completes, that is the result of the last expression in the script--and so Ludus also prints this.
### Some code ### Some code
Fibonacci numbers: Fibonacci numbers:
@ -90,4 +104,4 @@ fib (10) &=> 55
``` ```
### More on Ludus ### More on Ludus
See the [language reference](language.md) and [the documentation for the prelude](prelude.md). See the [language reference](/language.md) and [the documentation for the prelude](/prelude.md).

View File

@ -9,6 +9,7 @@ using std::string;
// set all our exported Janet functions as null pointers // set all our exported Janet functions as null pointers
static JanetFunction *janet_ludus = NULL; static JanetFunction *janet_ludus = NULL;
static JanetFunction *janet_hello = NULL;
// these let us look up functions // these let us look up functions
Janet env_lookup(JanetTable *env, const char *name) { Janet env_lookup(JanetTable *env, const char *name) {
@ -64,6 +65,14 @@ unsigned char *read_file(const char *filename, size_t *length) {
return src; return src;
} }
// these are the C++ functions that wrap our Janet functions
// simplest case: takes nothing, returns nothing
void hello() {
Janet result; // we need a place to put the result
// args are: fn ptr, argc, argv, result
call_fn(janet_hello, 0, {}, &result);
}
// finally, getting a string back // finally, getting a string back
// this is our result type // this is our result type
struct StringResult { struct StringResult {
@ -114,6 +123,9 @@ int main() {
// no namespacing // no namespacing
janet_ludus = env_lookup_function(janet_unwrap_table(env), "ludus"); janet_ludus = env_lookup_function(janet_unwrap_table(env), "ludus");
janet_gcroot(janet_wrap_function(janet_ludus)); janet_gcroot(janet_wrap_function(janet_ludus));
janet_hello = env_lookup_function(janet_unwrap_table(env), "hello");
janet_gcroot(janet_wrap_function(janet_hello));
} }
// these bindings are exported into javascript // these bindings are exported into javascript
@ -122,6 +134,7 @@ EMSCRIPTEN_BINDINGS(module) {
// these are the functions that will be available // these are the functions that will be available
function("ludus", &ludus, allow_raw_pointers()); function("ludus", &ludus, allow_raw_pointers());
function("hello", &hello, allow_raw_pointers());
// we also want a wrapper for our StringResult // we also want a wrapper for our StringResult
// we won't access it directly, but emcc makes it nice // we won't access it directly, but emcc makes it nice

View File

@ -1,4 +1,6 @@
build: build:
# compile the janet into an image
# janet -c src/ludus.janet build/ludus.jimage
# the complex emscripten invocation # the complex emscripten invocation
# note we have the stack size set to 1024*1024 (1 MB) # note we have the stack size set to 1024*1024 (1 MB)
emcc \ emcc \

Binary file not shown.

View File

@ -4,6 +4,5 @@ const mod = await init()
export function run (source) { export function run (source) {
const result = mod.ludus(source).value const result = mod.ludus(source).value
console.log(result)
return JSON.parse(result) return JSON.parse(result)
} }

View File

@ -6489,7 +6489,7 @@ var __emscripten_stack_alloc = (a0) => (__emscripten_stack_alloc = wasmExports['
var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports['emscripten_stack_get_current'])(); var _emscripten_stack_get_current = () => (_emscripten_stack_get_current = wasmExports['emscripten_stack_get_current'])();
var ___cxa_is_pointer_type = createExportWrapper('__cxa_is_pointer_type', 1); var ___cxa_is_pointer_type = createExportWrapper('__cxa_is_pointer_type', 1);
var dynCall_jiji = Module['dynCall_jiji'] = createExportWrapper('dynCall_jiji', 5); var dynCall_jiji = Module['dynCall_jiji'] = createExportWrapper('dynCall_jiji', 5);
var ___emscripten_embedded_file_data = Module['___emscripten_embedded_file_data'] = 1840592; var ___emscripten_embedded_file_data = Module['___emscripten_embedded_file_data'] = 1783292;
function invoke_i(index) { function invoke_i(index) {
var sp = stackSave(); var sp = stackSave();
try { try {

Binary file not shown.

View File

@ -1,3 +1,11 @@
import {run} from "./ludus.mjs" console.log("Starting wasm test run.")
console.log(run(`let foo = 42; "{foo} bar"`)) import init from "./out.mjs"
console.log("Imported module")
const mod = await init()
console.log("Initted module")
console.log(mod.ludus(":hello_from_ludus").value)

3
doc/intro.md Normal file
View File

@ -0,0 +1,3 @@
# Introduction to cludus
TODO: write [great documentation](http://jacobian.org/writing/what-to-write/)

View File

@ -3,7 +3,6 @@ repl:
kitten @ launch --type=os-window --allow-remote-control --cwd=current --title=hx_repl:ludus --keep-focus kitten @ launch --type=os-window --allow-remote-control --cwd=current --title=hx_repl:ludus --keep-focus
kitten @ send-text -m "title:hx_repl:ludus" "janet -s\n" kitten @ send-text -m "title:hx_repl:ludus" "janet -s\n"
# restart the repl server
restart: restart:
kitten @ send-text -m "title:hx_repl:ludus" "\04" kitten @ send-text -m "title:hx_repl:ludus" "\04"
kitten @ send-text -m "title:hx_repl:ludus" "janet -s\n" kitten @ send-text -m "title:hx_repl:ludus" "janet -s\n"
@ -12,20 +11,10 @@ restart:
eval: eval:
sd "$" "\n" | sd "\n\n" "\n" | kitten @ send-text -m "title:hx_repl:ludus" --stdin sd "$" "\n" | sd "\n\n" "\n" | kitten @ send-text -m "title:hx_repl:ludus" --stdin
# get documentation for a symbol in janet/clojure # send what's selected to a buffer, and then evaluate what's in the buffer
buffer:
sd "$" "\n" | sd "\n\n" "\n" > .repl-buffer.janet
kitten @ send-text -m "title:hx_repl:ludus" "(import ./.repl-buffer :prefix \"\")"
doc: doc:
sd "$" "\n" | sd "\n\n" "\n" | xargs -I _ echo "(doc " _ ")" | kitten @ send-text -m "title:hx_repl:ludus" --stdin sd "$" "\n" | sd "\n\n" "\n" | xargs -I _ echo "(doc " _ ")" | kitten @ send-text -m "title:hx_repl:ludus" --stdin
# publish to npm (did you build things first?)
publish:
npm version patch
npm publish
# build the ludus jimage
build:
rm build/out.mjs
rm build/out.wasm
rm build/ludus.jimage
janet -c src/ludus.janet build/ludus.jimage
cd build && just build
git commit -am "build"

View File

@ -1,6 +1,6 @@
# Ludus language reference # Ludus language reference
This is not intended for beginners, but to be a language overview for experienced programmers. That said, it may help beginners orient themselves in the language. This is not intended for beginners, but to be a language overview for experienced users. That said, it may help beginners orient themselves in the language.
## Comments ## Comments
Ludus's comment character is `&`. Anything after an ampersand on a line is ignored. There are no multiline comments. Ludus's comment character is `&`. Anything after an ampersand on a line is ignored. There are no multiline comments.
@ -9,15 +9,15 @@ Ludus's comment character is `&`. Anything after an ampersand on a line is ignor
Ludus has four types of atomic values. Ludus has four types of atomic values.
### `nil` ### `nil`
`nil` is Ludus's representation of nothing. In the grand Lisp tradition, Ludus can, and occasionally does, use `nil`-punning. Its type is `:nil`. `nil` is Ludus's representation of nothing. In the grand Lisp tradition, Ludus can, and frequently does, use `nil`-punning. Its type is `:nil`.
### Booleans ### Booleans
`true` and `false`. That said, in all conditional constructs, `nil` and `false` are "falsy," and everything else is "truthy." Their type is `:boolean`. `true` and `false`. That said, in all conditional constructs, `nil` and `false` are "falsy," and everything else is "truthy." Their type is `:boolean`.
### Numbers ### Numbers
Ludus has numbers, which are IEEE-754 64-bit floats. Numbers are more complicated than you think, probably. Ludus has numbers. At current, they rely on underlying number types. When Ludus runs in the browser, numbers are Javascript 64-bit floats. When Ludus runs at the command line in JVM-based Clojure, Ludus numbers could be ints, floats, or ratios, depending. Numbers are more complicated than you think.
Number literals in Ludus are either integers or decimal floating point numbers, e.g. `32.34`, `42`, `-0.23`. Underscores in numbers are ignored, and can be used to separate long numbers, e.g. `1_234_567_890`. Number literals in Ludus are either integers or decimal floating point numbers.
Numbers' type is `:number`. Numbers' type is `:number`.
@ -27,42 +27,21 @@ Ludus keywords begin with a colon and a letter, e.g. `:keyword`. Types are repre
Keywords must begin with an ASCII upper- or lower-case letter, and can then include any letter character, as well as `_`, `/`, `!`, `?`, and `*`. Keywords must begin with an ASCII upper- or lower-case letter, and can then include any letter character, as well as `_`, `/`, `!`, `?`, and `*`.
## Strings ## Strings
Ludus strings are UTF-8 strings, and only use double quotes. Strings may be multiline. For example, this is a string: `"foo"`. So is this: Ludus strings are dependent on the host platform. Given that Ludus either runs in Javascript or the JVM, strings are UTF-16 strings. Eventually, Ludus will use UTF-8 strings. Strings are much more complicated than you think. Strings are emphatically not a collection type.
```
"foo
bar baz"
```
Strings use backslashes for escapes, including `\n` for newline, `\t` for tab, `\"` for a double quote, and `\{` for an open curly brace (see below on interpolation).
Strings' type is `:string`. Strings' type is `:string`.
### String interpolation
Strings may also insert a string representation of any Ludus value that is bound to a name, by inserting that name in curly braces. To wit,
```
let foo = :foo
let bar = 42
let baz = [1, 2, 3]
"{foo} {bar} {baz}" &=> ":foo 42 1, 2, 3"
```
Interpolations may _not_ be arbitrary expressions: only bound names may be used in interpolations.
## Collections ## Collections
Ludus has a few different types of collections, in increasing order of complexity: tuples, lists, sets, dicts, and packages. All collections are immutable. Ludus has a few different types of collections, in increasing order of complexity: tuples, lists, sets, dicts, and namespaces.
#### Separators ### Separators
In all collection literals, members are written with a separator between them. On the same line, use a comma; or a newline will also separate elements. You may use as many separators as you wish at any point inside a collection or pattern. `(,,,,,,,3,,4,,,,,,)` and `(3, 4)` are the same value. In all collection literals, members are written with a separator between them. On the same line, use a comma; or a newline will also separate elements. You may use as many separators as you wish at any point inside a collection or pattern. `(,,,,,,,3,,4,,,,,,)` and `(3, 4)` are the same value.
#### Efficiency
At the current moment, Ludus collections are all copy-on-write; this means that Ludus is _not_ performant with large collections. Eventually, Ludus will have Clojure-style persistent, immutable collections.
### Tuples ### Tuples
Tuples are fully-immutable, ordered collections of any kinds of values, delimited by parentheses, e.g. `(1, :a, "foo")`. At current, they have no length limit (although they eventually will). Unlike in some languages, tuples can be empty or contain a single element: `()` and `(:foo)` are both just fine. Tuples largely cannot be manipulated functionally; they must be written as literals and unpacked using pattern matching. They can, however, be converted to lists, either through pattern matching or the `list` function. Their type is `:tuple`. Tuples are fully-immutable, ordered collections of any kinds of values, delimited by parentheses, e.g. `(1, :a, "foo")`. At current, they have no length limit (although they eventually will). Unlike in some languages, tuples can be empty or contain a single element: `()` and `(:foo)` are both just fine. Tuples largely cannot be manipulated functionally; they must be written as literals and unpacked using pattern matching. They can, however, be converted to lists, either through pattern matching or the `list` function. Their type is `:tuple`.
### Lists ### Lists
Lists are persistent and immutable ordered collections of any kinds of values, delimited by square braces, e.g. `[1, :a, "foo"]`. Their type is `:list`. Lists are persistent and immutable ordered collections of any kinds of values, delimited by square braces, e.g. `[1, :a, "foo"]`. They are currently implemented using Clojure's persistent vectors. Their type is `:list`.
Lists may be combined using splats, written with ellipses, e.g., `[...foo, ...bar]`. Lists may be combined using splats, written with ellipses, e.g., `[...foo, ...bar]`.
@ -72,13 +51,13 @@ Sets are persistent and immutable unordered collections of any kinds of values,
### Dictionaries, or dicts ### Dictionaries, or dicts
Dicts are persistent and immutable associative collections of any kinds of values. Dicts use keywords as keys (and cannot use any other kind of Ludus value as a key, not even strings), but can store any values. Dict literals are written as keyword-value pairs: `#{:a 1, :b false}`. Single words may be used as a shorthand for a key-value pair. Accessing a key that holds no value returns `nil`. Their type is `:dict`. Dicts are persistent and immutable associative collections of any kinds of values. Dicts use keywords as keys (and cannot use any other kind of Ludus value as a key, not even strings), but can store any values. Dict literals are written as keyword-value pairs: `#{:a 1, :b false}`. Single words may be used as a shorthand for a key-value pair. Accessing a key that holds no value returns `nil`. Their type is `:dict`.
### Packages ### Namespaces
Packages are immutable collections of bindings. They may only be described at the top level of a script, and their names must begin with a capital letter. Accessing a key that has no value on a package results in a validation error. They may not be accessed using functions, but only direct keyword access. Their type is `:pkg`. Namespaces are immutable collections of bindings. They may only be described at the top level of a script. Accessing a key that has no value on a namepsace results in a panic. Their type is `:ns`.
They are written with the form `pkg`, then a package name, beginning with a capital letter, that will be bound as their name, and then an associative structure (pairs or word shorthands), delimited by `{}`, e.g.: They are written with the form `ns`, then a word that will be bound as their name, and then an associative structure (pairs or word shorthands), delimited by `{}`, e.g.:
``` ```
pkg Foo { ns foo {
:bar "bar" :bar "bar"
:baz 42 :baz 42
quux quux
@ -86,33 +65,28 @@ pkg Foo {
``` ```
### Working with collections ### Working with collections
Ludus names are bound permanently and immutably. Collections are immutable. How do you add something to a list or a dict? How do you get things out of them? Ludus names are bound permanently and immutably. How do you add something to a list or a dict? How do you get things out of them?
Ludus provides functions that allow working with persistent collections. They're detailed in [the Prelude](prelude.md). That said, all functions that modify collections take a collection and produce the modified collection _as a return value_, without changing the original collection. E.g., `append ([1, 2, 3], 4)` will produce `[1, 2, 3, 4]`, but the original list is unchanged. (For dicts, the equivalent is `assoc`.) Ludus provides functions that allow working with persistent collections. They're detailed in [the Prelude](/prelude.md). That said, all functions that modify collections take a collection and produce the modified collection _as a return value_, without changing the original collection. E.g., `append ([1, 2, 3], 4)` will produce `[1, 2, 3, 4]`. (For dicts, the equivalent is `assoc`.)
## Expressions ## Expressions
Ludus is an expression-based language: all forms in the language are expressions and return values, except `panic!`. That said, not all expressions may be used everywhere. Ludus is an expression-based language: all forms in the language are expressions and return values, except `panic!`. That said, not all expressions may be used everywhere.
### Terminating expressions
Expressions in scripts and blocks are terminated by a newline or a semicolon. In compound forms, like, `if`, the terminator comes after the `else` expression.
In forms with multiple clauses surrounded by curly braces (i.e., function bodies, `match`, `when`, etc.), you may separate clauses with semicolons as well as newlines.
### Toplevel expressions ### Toplevel expressions
Some expressions may only be used in the "top level" of a script. Because they are the toplevel, they are assured to be statically knowable. These include: `pkg`, `ns`, `use`, `import`, and `test`. (NB: not all of these are yet implemented.) Some expressions may only be used in the "top level" of a script. Because they are the toplevel, they are assured to be statically knowable. These include: `ns`, `use`, `import`, and `test`.
### Non-binding expressions ### Non-binding expressions
Some forms may take any expression that does _not_ [bind a name](#words-and-bindings), for example, any entry in a collection, or the right-hand side of a `let` binding. This is because binding a name in some positions is ambiguous, or nonsensical, or leads to unwarranted complications. Some forms may take any expression that does _not_ [bind a name](#Words-and-bindings), for example, any entry in a collection, or the right-hand side of a `let` binding. This is because binding a name in some positions is ambiguous, or nonsensical, or leads to unwarranted complications.
### Simple expressions ### Simple expressions
Many compound forms will only accept "simple" expressions. Formally, simple expressions are either literal (atomic, string, or collection literals) or synthetic expressions. They are expressions which do not take sub-expressions: no `if`, `when`, `match`, etc. (`do` expressions are currently not simple, but that may be revised.) Many complex forms will only accept "simple" expressions. Formally, simple expressions are either literal (atomic, string, or collection literals) or synthetic expressions. They are expressions which do not take sub-expressions: no `if`, `when`, `match`, etc. (`do` expressions are currently not simple, but that may be revised.)
## Words and bindings ## Words and bindings
Ludus uses _words_ to bind values to names. Words must start with a lower case ASCII letter, and can subsequently include any letter character (modulo backing character encoding), as well as , `_`, `/`, `?`, `!`, and `*`. Ludus uses _words_ to bind values to names. Words must start with a lower case ASCII letter, and can subsequently include any letter character (modulo backing character encoding), as well as , `_`, `/`, `?`, `!`, and `*`.
Ludus binds values to names immutably and permanently: no name in the same scope may ever be re-bound to a different value. (Although see [boxes](#boxes-and-state), below. Ludus binds values to names immutably and permanently: no name in the same scope may ever be re-bound to a different value. (Although see [refs](#references-and-state), below.
Attempting to use an unbound name (a word that has not had a value bound to it) will result in a validation error, and the script will not run. Attempting to use an unbound name (a word that has not had a value bound to it) will result in a panic.
### `let` bindings: a very short introduction ### `let` bindings: a very short introduction
Ludus's basic binding form is `let`: Ludus's basic binding form is `let`:
@ -120,7 +94,7 @@ Ludus's basic binding form is `let`:
``` ```
let foo = :bar & `foo` is now bound to `bar` for the rest of the scope. let foo = :bar & `foo` is now bound to `bar` for the rest of the scope.
let foo = :baz & Validation error: name foo was bound in line 1 let foo = :baz & panic!
``` ```
`let` bindings are more complex; we will return to these below. `let` bindings are more complex; we will return to these below.
@ -132,10 +106,10 @@ Ludus makes extensive use of pattern-matching. Patterns do two jobs at once: the
The simplest pattern is the placeholder: it matches against anything, and does not bind a name. It is written as a single underscore: `_`, e.g., `let _ = :foo`. The simplest pattern is the placeholder: it matches against anything, and does not bind a name. It is written as a single underscore: `_`, e.g., `let _ = :foo`.
#### Ignored names #### Ignored names
If you wish to be a bit more explict than using a placeholder, you can use an ignored name, which is a name that starts with an underscore: `_foo`. This is not bound, is not a valid name, and can be used however much you wish, even multiple times in the same pattern. It is, in fact, a placeholder, plus a reader-facing description. If you wish to be a bit more explict than using a placeholder, you can use an ignored name, which is a name that starts with an underscore: `_foo`. This is not bound, is not a valid name, and can be used however much you wish, even multiple times in the same pattern. It's a placeholder, plus a reader-facing description.
### Literal patterns ### Literal patterns
Patterns can be literal atomic values or strings: `0`, `false`, `nil`, `:foo`, etc. That means you can write `let 0 = 0` or `let :foo = :foo`, and, while nothing will happen, everything will be just fine. Patterns can be literal atomic values or strings: `0`, `false`, `nil`, `"foo"`, etc. That means you can write `let 0 = 0` or `let :foo = :foo`, and everything will be jsut fine.
Literals match against, well, literal values: if the pattern and the value are the same, they match! If not, they don't match. Literals match against, well, literal values: if the pattern and the value are the same, they match! If not, they don't match.
@ -147,24 +121,6 @@ Word patterns match against any value, and bind that value to the word as a name
#### Typed patterns #### Typed patterns
Word patterns can, optionally, take a type, using the `as` reserved word, and the keyword representing the desired type: `let foo as :number = 42`. Word patterns can, optionally, take a type, using the `as` reserved word, and the keyword representing the desired type: `let foo as :number = 42`.
### String patterns
Ludus has a simple but powerful form of string pattern matching that mirrors string interpolation. Any word inside curly braces in a string will match against a substring of a string passed into a pattern.
```
let i_am = "I am the walrus"
let "I {verb} the {noun}" = i_am
(verb, noun) &=> ("am", "walrus")
```
Note that such names may well be bound to empty strings: a match does not guarantee that there will be anything in the string. This is particularly relevant at the beginning and end of string patterns:
```
let we_are = "We are the eggmen"
let "{first}We {what}" = we_are
(first, what) &=> ("", "are the eggmen")
```
### Collection patterns ### Collection patterns
Tuples, lists, and dicts can be destructured using patterns. They are written nearly identically to their literal counterparts. Collection patterns are composed of any number of simpler patterns or other collection patterns. They bind any names nested in them, match literals in them, etc. Tuples, lists, and dicts can be destructured using patterns. They are written nearly identically to their literal counterparts. Collection patterns are composed of any number of simpler patterns or other collection patterns. They bind any names nested in them, match literals in them, etc.
@ -185,15 +141,11 @@ let () = () & empty tuples are also patterns
#### List patterns #### List patterns
List patterns are identical to tuple patterns, but they are written using square braces. They also match against a specific number of members, and may take a splat in the last position, e.g. `let [first, ...rest] = [1, 2, 3]`. List patterns are identical to tuple patterns, but they are written using square braces. They also match against a specific number of members, and may take a splat in the last position, e.g. `let [first, ...rest] = [1, 2, 3]`.
Note that list patterns, like tuple patterns, match on explicit length. That means that if you are matching only the first items of a list, you must explicitly include a splat pattern, e.g. `let [first, second, ...] = [1, 2, 3, 4]`.
#### Dict patterns #### Dict patterns
Dict patterns are written either with shorthand words, or keyword-pattern pairs. Consider: `let #{:a foo, :b 12, c} = #{:a 1, :b 12, :c 4}`. `foo` is now 1; `b` is now 12, `c` is now 4. If a dict does not hold a value at a particular key, there is no match. Dict patterns are written either with shorthand words, or keyword-pattern pairs. Consider: `let #{:a foo, :b 12, c} = #{:a 1, :b 12, :c 4}`. `foo` is now 1; `b` is now 12, `c` is now 4. If a dict does not hold a value at a particular key, there is no match.
Dict patterns may also use a splat as their last member: `let #{:a 1, ...b} = #{:a 1, :b 2, :c 3}` will bind `b` to `#{:b 2, :c 3}`. Dict patterns may also use a splat as their last member: `let #{:a 1, ...b} = #{:a 1, :b 2, :c 3}` will bind `b` to `#{:b 2, :c 3}`.
Like tuple and list patterns, dict patterns without a splat at the end match only on exact equivalence on all keys.
## `let` bindings ## `let` bindings
`let` bindings are the basic form of matching and binding in Ludus. It is written `let {pattern} = {non-binding expression}`. The pattern can be arbitrarily complex. If the left-hand side of a `let` binding does not match, Ludus will raise a panic, halting evaluation of the script. `let` bindings are the basic form of matching and binding in Ludus. It is written `let {pattern} = {non-binding expression}`. The pattern can be arbitrarily complex. If the left-hand side of a `let` binding does not match, Ludus will raise a panic, halting evaluation of the script.
@ -210,7 +162,7 @@ let first = {
add (outer, inner) add (outer, inner)
} & first is now bound to 65 } & first is now bound to 65
inner & Validation error: unbound name inner inner & panic! unbound name inner
``` ```
@ -230,28 +182,37 @@ let y = {
``` ```
## Conditional forms ## Conditional forms
Ludus has a robust set of conditional forms, all of which are expressions and resolve to a single value. Ludus has a robust set of conditionoal forms, all of which are expressions and resolve to a single value.
### `if` ### `if`
`if` evaluates a condition; if the result of the condition is truthy, it evaluates is `then` branch; if the condition is falsy, it evaluates its `else` branch. Both branches must always be present. Newlines may come before `then` and `else`. `if` evaluates a condition; if the result of the condition is truthy, it evaluates is `then` branch; if the condition is falsy, it evaluates its `else` branch. Both branches must always be present. Newlines may come before `then` and `else`.
`if {simple expression} then {non-binding expression} else {non-binding expression}` `if {simple expression} then {non-binding expression} else {non-binding expression}`
#### `if let`
There is one exception to the above: a single `let` form can be used as the condition. In that case, if the `let` binding is successful--the pattern matches--the `then` branch is evaluated with any resulting bindings. If the pattern does not match, in place of a panic, the `else` branch is evaluated. Note that if the right-hand value of the `let` expression is falsy, the `else` branch will also be evaluated.
```
if let (:ok, value) = might_fail ()
then do_something_with (value)
else recover
```
### `when` ### `when`
`when` is like Lisp's `cond`: it takes a series of clauses, separated by semicolons or newlines, delimited by curly braces. Clauses are written `lhs -> rhs`. `when` expressions are extremely useful for avoiding nested `if`s. `when` is like Lisp's `cond`: it takes a series of clauses, separated by semicolons or newlines, delimited by curly braces. Clauses are written `lhs -> rhs`. `when` expressions are extremely useful for avoiding nested `if`s.
The left hand of a clause is a simple expression; the right hand of a clause is any expression. When the left hand is truthy, the right hand is evaluated, and the result of that evaluation is returned; no further clauses are evaluated. If no clause has a truthy left-hand value, then a panic is raised. In the example below, not the use of literal `true` as an always-matching clause. The left hand of a clause is a simple expression; the right hand of a clause is any expression. When the left hand is truthy, the right hand is evaluated, and the result of that evaluation is returned; no further clauses are evaluated. If no clause has a truthy left-hand value, then a panic is raised. `else` and `_` are valid left-hand expressions, which are always truthy in this context.
``` ```
when { when {
maybe () -> :something maybe () -> :something
mabye_not () -> :something_else mabye_not () -> :something_else
true -> :always else -> :always
} }
``` ```
### `match` ### `match`
A `match` form is the most powerful conditional form in Ludus. It consists of a test expression, and a series of clauses. The test expression must be a simple expression, followed by `with`, and then a series of clauses separated by a semicolon or newline, delimited by curly braces. A `match` form is the most powerful conditional form in Ludus (for now). It consists of a test expression, and a series of clauses. The test expression must be a simple expression, followed by `with`, and then a series of clauses separated by a semicolon or newline, delimited by curly braces.
``` ```
match may_fail () with { match may_fail () with {
@ -262,20 +223,9 @@ match may_fail () with {
The left hand of a match clause is a pattern; the right hand is an expression: `pattern -> expression`. If the pattern matches the test expression of a clause, the expression is evaluated with any bindings from the pattern, and `match` form evaluates to the result of that expression. The left hand of a match clause is a pattern; the right hand is an expression: `pattern -> expression`. If the pattern matches the test expression of a clause, the expression is evaluated with any bindings from the pattern, and `match` form evaluates to the result of that expression.
If a test expression does not match against any clause's pattern, a panic is raised. If a test expression does not match against any clause's pattern, a panic is raised. As with `when` expressions, `_` and `else` always match.
Ludus does not attempt to do any exhaustiveness checking on match forms; match errors are always runtime errors. Ludus does not attempt to do any exhaustiveness checking on match forms.
#### Guards
`match` clauses may have a _guard expression_, which allows a clause only to match if the expression's result is truthy. In the previous example, consider that we might want different behaviour depending on the value of the number:
```
match may_fail () with {
(:ok, value) if pos? (value) -> calculate_positive_result (value)
(:ok, value) if neg? (value) -> calculate_negative_result (value)
(:ok, 0) -> do_something_with_zero ()
(:err, msg) -> { log! (msg); recover_somehow () }
}
```
## Functions ## Functions
Ludus is an emphatically functional language. Almost everything in Ludus is accomplished by applying functions to values, or calling functions with arguments. (These are precise synonyms.) Ludus is an emphatically functional language. Almost everything in Ludus is accomplished by applying functions to values, or calling functions with arguments. (These are precise synonyms.)
@ -297,7 +247,7 @@ A named function is identical to a lambda, with the one change that a word follo
#### Compound functions #### Compound functions
Compound functions are functions that have multiple clauses. They must be named, and in place of a single clause after a name, they consist in one or more clauses, separated by semicolons or newlines, delimited by curly braces. Optionally, compound functions may have a docstring as their first element after the opening curly brace. The docstring explains the function's purpose and use, before any of the function clauses. Compound functions are functions that have multiple clauses. They must be named, and in place of a single clause after a name, they consist in one or more clauses, separated by semicolons or newlines, delimited by curly braces. Optionally, compound functions may have a docstring as their first element after the opening curly brace. The docstring explains the function's purpose and use, before any of the function clauses.
An example from Ludus's Prelude: An exampele from Ludus's Prelude:
``` ```
fn some { fn some {
@ -308,29 +258,10 @@ fn some {
``` ```
### Closures ### Closures
Functions in Ludus are closures: function bodies have access not only to their specific scope, but any enclosing scope. That said, functions only have access to names bound _before_ they are defined; nothing is hoisted in Ludus. Functions in Ludus are closures: function bodies have access not only to their specific scope, but any enclosing scope. Note that function bodies may have access to names bound after them in their scope, so long as the function is _called_ after any names it accesses are bound.
### Mutual recursion and forward declaration
If you try the following, you'll get a validation error:
```
fn stupid_odd? {
(0) -> false
(x) -> supid_even? (dec (x)) & Validation error: unbound name stupid_even?
}
fn stupid_even? {
(0) -> true
(x) -> stupid_odd? (dec (x))
}
```
To allow for mutual recursion, Ludus allows forward declarations, which are written `fn name` without any clauses. In the example above, we would simply put `fn stupid_even?` before we define `stupid_odd?`.
If you declare a function without defining it, however, Ludus will raise a validation error.
### The Prelude ### The Prelude
The Prelude is a substantial set of functions that is available in any given Ludus script. (It is, itself, just a Ludus file that has special access to host functions.) Because of that, a large number of functions are always available. The prelude documentation is [here](prelude.md). The Prelude is a substantial set of functions that is available in any given Ludus script. (It is, itself, just a Ludus file that has special access to host functions.) Because of that, a large number of functions are always available. The prelude documentation is [here](/prelude.md).
### Partial application ### Partial application
Functions in Ludus can be partially applied by using a placeholder in the arguments. Partial application may only use a single placeholder (partially applied functions are always unary), but it can be anywhere in the arguments: `let add_1 = add(1, _)` or `let double = mult(_, 2)`. Functions in Ludus can be partially applied by using a placeholder in the arguments. Partial application may only use a single placeholder (partially applied functions are always unary), but it can be anywhere in the arguments: `let add_1 = add(1, _)` or `let double = mult(_, 2)`.
@ -343,11 +274,11 @@ Because of "partial application," Ludus has a concept of an "argument tuple" (wh
In place of nesting function calls inside other function calls, Ludus allows for a more streamlined version of function application: the `do` form or function pipeline. `do` is followed by an initial expression. `do` expressions use `>` as an operator: whatever is on the left hand side of the `>` is passed in as a single argument to whatever is on its right hand side. For example: In place of nesting function calls inside other function calls, Ludus allows for a more streamlined version of function application: the `do` form or function pipeline. `do` is followed by an initial expression. `do` expressions use `>` as an operator: whatever is on the left hand side of the `>` is passed in as a single argument to whatever is on its right hand side. For example:
``` ```
let silly_result = do 23 > let silly_result = do 23
mult (_, 2) > add (1, _) > > mult (_, 2) > add (1, _)
sub (_, 2) > div (_, 9) & silly_result is 5 > sub (_, 2) > div (_, 9) & silly_result is 5
``` ```
Newlines may appear after any instance of `>` in a `do` expression. That does, however, mean that you must be careful not to accidentally include any trailing `>`s. Newlines may appear before any instance of `>` in a `do` expression.
### Called keywords ### Called keywords
Keywords may be called as functions, in which case they extract the value stored at that key in the value passed in: Keywords may be called as functions, in which case they extract the value stored at that key in the value passed in:
@ -359,16 +290,8 @@ let bar = :a (foo) & `bar` is now 1
Called keywords can be used in pipelines. Called keywords can be used in pipelines.
In addition, keywords may be called when they are bound to names:
```
let foo = #{:a 1, :b 2}
let bar = :a
bar (foo) & => 1
```
## Synthetic expressions ## Synthetic expressions
Synthetic expressions are valid combinations of words, keywords, package names, and argument tuples which allow for calling functions and extracting values from associative collections. The root--first term--of a synthetic expression must be a word or a keyword; subsequent terms must be either argument tuples or keywords. Synthetic expressions are valid combinations of words, keywords, and argument tuples which allow for calling functions and extracting values from associative collections. The root--first term--of a synthetic expression must be a word or a keyword; subsequent terms must be either argument tuples or keywords.
``` ```
let foo = #{:a 1, :b #{:c "bar" :d "baz"}} let foo = #{:a 1, :b #{:c "bar" :d "baz"}}
@ -380,7 +303,7 @@ let baz = :b (foo) :d & `baz` is now "baz"
``` ```
## Looping forms ## Looping forms
Ludus has optimized tail calls--the most straightforward way to accomplish repeating behaviour is function recursion. There are two additional looping forms, `repeat` and `loop`. Ludus will have optimized tail calls--the most straightforward way to accomplish repeating behaviour is function recursion. There are two additional looping forms, `repeat` and `loop`.
### `repeat` ### `repeat`
`repeat` is a help to learners, and is useful for executing side effects multiple times. It is written `repeat {number|word} { {exprs} }`. From turtle graphics: `repeat` is a help to learners, and is useful for executing side effects multiple times. It is written `repeat {number|word} { {exprs} }`. From turtle graphics:
@ -393,8 +316,8 @@ repeat 4 {
``` ```
Note that `repeat` does two interesting things: Note that `repeat` does two interesting things:
1. It never returns a value other than `nil`. If it's in the block, it disappears. This is a unique (and frankly, undesirable) property in Ludus. 1. It never returns a value other than `nil`. If it's in the block, it disappears.
2. Unlike everything else in Ludus, repeate _requires_ a block, and not simply an expression. You cannot write `repeat 4 forward! (100)`. 2. Unlike everything else in Ludus, it requires a block. You cannot write `repeat 4 forward! (100)`. (But: watch this space.)
### `loop`/`recur` ### `loop`/`recur`
`loop` and `recur` are largely identical to recursive functions for repetition, but use a special form to allow an anonymous construction and a few guard rails. `loop` and `recur` are largely identical to recursive functions for repetition, but use a special form to allow an anonymous construction and a few guard rails.
@ -409,9 +332,7 @@ loop (xs, 0) with {
} &=> 10 } &=> 10
``` ```
`recur` is the recursive call. It must be in tail position--`recur` must be the root of a synthetic expression, in return position. If `recur` is not in tail position, a validation error will be raised. `recur` is the recursive call. It must be in tail position--`recur` must be the root of a synthetic expression, in return position. (At present, this is not checked. It will be statically verified, eventually.)
In addition, `recur` calls must have the same number of arguments as the original tuple passed to `loop`. While Ludus will allow you to write clauses in `loop` forms with a different arity than the original tuple, those will never match.
`recur` calls return to the nearest `loop`. Nested `loop`s are probably a bad idea and should be avoided when possible. `recur` calls return to the nearest `loop`. Nested `loop`s are probably a bad idea and should be avoided when possible.
@ -421,18 +342,14 @@ The "toplevel" of a script are the expressions that are not embedded in other ex
### `import` ### `import`
`import` allows for the evaluation of other Ludus scripts: `import "path/to/file" as name`. `import` just evaluates that file, and then binds a name to the result of evaluating that script. This, right now, is quite basic: circular imports are currently allowed but will lead to endless recursion; results are not cached, so each `import` in a chain re-evaluates the file; and so on. `import` allows for the evaluation of other Ludus scripts: `import "path/to/file" as name`. `import` just evaluates that file, and then binds a name to the result of evaluating that script. This, right now, is quite basic: circular imports are currently allowed but will lead to endless recursion; results are not cached, so each `import` in a chain re-evaluates the file; and so on.
Status: not yet implemented.
### `use` ### `use`
`use` loads the contents of a namespace into a script's context. To ensure that this is statically checkable, this must be at the toplevel. `use` loads the contents of a namespace into a script's context. To ensure that this is statically checkable, this must be at the toplevel.
Status: not yet implemented. ### `ns`
Namespaces, `ns`es, may only be described at the toplevel of a script. This is to ensure they can be statically evaluatable.
### `pkg`
Packages, `pkg`es, may only be described at the toplevel of a script. This is to ensure they can be statically evaluatable.
### `test` ### `test`
A `test` expression is a way of ensuring things behave the way you want them to. Run the script in test mode, and these are evaluated. If the expression under `test` returns a truthy value, you're all good! If the expression under `test` returns a falsy value or raises a panic, then Ludus will report which test(s) failed. A `test` expression (currently not working!--it will blow up your script, although it parses properly) is a way of ensuring things behave the way you want them to. Run the script in test mode (how?--that doesn't exist yet), and these are evaluated. If the expression under `test` returns a truthy value, you're all good! If the expression under `test` returns a falsy value or raises a panic, then Ludus will report which test(s) failed.
``` ```
test "something goes right" eq? (:foo, :foo) test "something goes right" eq? (:foo, :foo)
@ -448,32 +365,26 @@ test "something goes wrong" {
Formally: `test <string> <expression>`. Formally: `test <string> <expression>`.
Status: not yet implemented. ## Changing things: `ref`s
Ludus does not let you re-bind names. It does, however, have a type that allows for changing values over time: `ref` (short for reference--they are references to values). `ref`s are straightforward, but do require a bit more overhead than `let` bindings. The idea is that Ludus makes it obvious where mutable state is in a program, as well as where that mutable state may change. It does so elegantly, but with some guardrails that may take a little getting used to.
## Changing things: `box`es The type of a `ref` is, predictably, `:ref`.
Ludus does not let you re-bind names. It does, however, have a type that allows for changing values over time: `box`. A box is a place to put things, it has its own identity, it can store whatever you put in it, but to get what's in it, you have to `unbox` it.
Syntactically and semantically, `box`es are straightforward, but do require a bit more overhead than `let` bindings. The idea is that Ludus makes it obvious where mutable state is in a program, as well as where that mutable state may change. It does so elegantly, but with some guardrails that may take a little getting used to.
The type of a `box` is, predictably, `:box`.
``` ```
box foo = 42 & foo is now bound to a _box that contains 42_ ref foo = 42 & foo is now bound to a _ref that contains 42_
add (1, foo) & panic! no match: foo is _not_ a number add (1, foo) & panic! no match: foo is _not_ a number
store! (foo, 23) & foo is now a box containing 23 make! (foo, 23) & foo is now a ref containing 23
update! (foo, inc) & foo is now a ref containing 24 update! (foo, inc) & foo is now a ref containing 24
unbox (foo) &=> 23; use unbox to get the value contained in a box value_of (foo) &=> 23; use value_of to get the value contained in a ref
``` ```
### Ending with a bang! ### Ending with a bang!
Ludus has a strong naming convention that functions that change state or could cause an explicit panic end in an exclamation point (or, in computer nerd parlance, a "bang"). So anything function that mutates the value held in a reference ends with a bang: `store!` and `update!` take bangs; `unbox` does not. Ludus has a strong naming convention that functions that change state or could cause an explicit panic end in an exclamation point (or, in computer nerd parlance, a "bang"). So anything function that mutates the value held in a reference ends with a bang: `make!` and `update!` take bangs; `value_of` does not.
This convention also includes anything that prints to the console: `print!`, `report!`, `doc!`, `update!`, `store!`, etc. This convention also includes anything that prints to the console: `print!`, `report!`, `doc!`, `update!`, `make!`, etc.
(Note that there are a few counter-examples to this: math functions that could cause a panic [in place of returning NaN] do not end with bangs: `div`, `inv`, and `mod`; each of these has variants that allow for more graceful error handling).
### Ending with a whimper? ### Ending with a whimper?
Relatedly, just about any function that returns a boolean value is a predicate function--and has a name that ends with a question mark: `eq?` tests for equality; `box?` tells you if something is a ref or not; `lte?` is less-than-or-equal. Relatedly, just about any function that returns a boolean value is a predicate function--and has a name that ends with a question mark: `eq?` tests for equality; `ref?` tells you if something is a ref or not; `lte?` is less-than-or-equal.
## Errors: panic! in the Ludus script ## Errors: panic! in the Ludus script
A special form, `panic!`, halts script execution with the expression that follows as an error message. A special form, `panic!`, halts script execution with the expression that follows as an error message.
@ -490,14 +401,13 @@ Panics also happen in the following cases:
* a function is called with arguments that do not match any of its clauses * a function is called with arguments that do not match any of its clauses
* something that is not a function or keyword is called as a function * something that is not a function or keyword is called as a function
* a called keyword is partially applied * a called keyword is partially applied
* `div`, `inv`, or `mod` divides by zero * `div` divides by zero
* `sqrt` takes the square root of a negative number
* certain error handling functions, like `unwrap!` or `assert!`, are invoked on values that cause them to panic * certain error handling functions, like `unwrap!` or `assert!`, are invoked on values that cause them to panic
In fact, the only functions in the Prelude which explicitly cause panics are, at current, `div`, `inv`, `mod`, `sqrt`, `unwrap!`, and `assert!`. In fact, the only functions in the Prelude which can cause panics are, at current, `div`, `unwrap!`, and `assert!`.
### `nil`s, not errors ### `nil`s, not errors
Ludus, however, tries to return `nil` instead of panicking where it seems prudent. So, for example, attempting to get access a value at a keyword off a number or `nil`, while nonsensical, will return `nil` rather than panicking: Ludus, however, tries to return `nil` instead of panicking a lot of the time. So, for example, attempting to get access a value at a keyword off a number, while nonsensical, will return `nil` rather than panicking:
``` ```
let a = true let a = true
@ -508,6 +418,6 @@ at (b, 12) &=> nil
``` ```
### Result tuples ### Result tuples
Operations that could fail--especially when you want some information about why--don't always return `nil` on failures. Instead of exceptions or special error values, recoverable errors in Ludus are handled instead by result tuples: `(:ok, value)` and `(:err, msg)`. So, for example, `unwrap!` takes a result tuple and either returns the value in the `:ok` case, or panics in the `:err` case. Operations that could fail--especially when you want some information about why--don't always return `nil` on failures. Instead of exceptions or special error values, recoverable errors in Ludus are handled instead by result tuples: `(:ok, value)` and `(:err, msg)`. So, for example, `unwrap!` takes a result tuple and either returns the value in the `:ok` case, or panics in the `:err` case. Or `assert!` will panic on a falsy value; `assert`, instead, returns a result tuple.
Variants of some functions that may have undesirably inexplicit behaviour are written as `{name}/safe`. So, for example, you can get a variant of `div` that returns a result tuple in `div/safe`, which returns `(:ok, result)` when everything's good; and `(:err, "division by zero")` when the divisor is 0. Variants of some functions that may have undesirably inexplicit behaviour are written as `{name}/safe`. So, for example, you can get a variant of `div` that returns a result tuple in `div/safe`, which returns `(:ok, result)` when everything's good; and `(:err, "division by zero")` when the divisor is 0. Or, `get/safe` will give you a result rather than returning `nil`. (Althougn `nil` punning makes this mostly unncessary. Mostly.)

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{ {
"name": "@ludus/ludus-js-pure", "name": "@ludus/ludus-js-pure",
"version": "0.1.26", "version": "0.1.0-alpha.7.9",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@ludus/ludus-js-pure", "name": "@ludus/ludus-js-pure",
"version": "0.1.26", "version": "0.1.0-alpha.7.9",
"license": "GPL-3.0", "license": "GPL-3.0",
"devDependencies": { "devDependencies": {
"shadow-cljs": "^2.26.0", "shadow-cljs": "^2.26.0",

View File

@ -1,6 +1,6 @@
{ {
"name": "@ludus/ludus-js-pure", "name": "@ludus/ludus-js-pure",
"version": "0.1.26", "version": "0.1.0-alpha.10",
"description": "A Ludus interpreter in a pure JS function.", "description": "A Ludus interpreter in a pure JS function.",
"type": "module", "type": "module",
"main": "build/ludus.mjs", "main": "build/ludus.mjs",
@ -11,7 +11,6 @@
"files": [ "files": [
"build/out.wasm", "build/out.wasm",
"build/out.mjs", "build/out.mjs",
"build/ludus.mjs" "build/ludus.mjs"],
],
"devDependencies": {} "devDependencies": {}
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,285 +0,0 @@
let input = "I remember my mother"
print! ("DOCTOR")
print! ("> ", input)
let sanitized = do input > trim > downcase
& ensuring we have spaces at the beginning and end
& this lets us match patterns as written below
let padded = join ([" ", sanitized, " "])
fn switch_persons {
("i") -> "you"
("you") -> "i"
("am") -> "are"
("me") -> "you"
("my") -> "your"
(x) -> x
}
fn repersonalize (x) -> do x >
trim >
split (_, " ") >
map (switch_persons, _) >
join (_, " ")
fn one_of {
(str as :string) -> str
(strs as :list) -> random (strs)
}
let output = match padded with {
"{x} hello {y}" -> "How do you do. Please state your problem"
"{x} hi {y}" -> "How do you do. Please state your problem"
"{x} computer {y}" -> [
"Do computers worry you"
"What do you think about machines"
"Why do you mention computers"
"What do you think machines have to do with your problem"
]
"{x} name {y}" -> "I am not interested in names"
"{x} sorry {y}" -> [
"Please don't apologize"
"Apologies are not necessary"
"What feelings do you have when you apologize"
]
"{x} i remember {y}" -> {
let switched = repersonalize (y)
[
"Do you often think of {switched}"
"Does thinking of {switched} bring anything else to mind"
"What else do you remember"
"Why do you recall {switched} right now"
"What in the present situation reminds you of {switched}"
"What is the connection between me and {switched}"
]
}
"{x} do you remember {y}" -> {
let switched = repersonalize (y)
[
"Did you think I would forget {switched}"
"Why do you think I should recall {switched} now"
"What about {switched}"
"You mentioned {switched}"
]
}
"{x} if {y}" -> {
let switched = repersonalize (y)
[
"Do you reall think that its likely that {switched}"
"Do you wish that {switched}"
"What do you think about {switched}"
"Really--if {switched}"
]
}
"{x} i dreamt {y}" -> {
let switched = repersonalize (y)
[
"Really--{y}"
"Have you ever fantasized {y} while you were awake"
"Have you dreamt {y} before"
]
}
"{x} dream about {y}" -> {
let switched = repersonalize (y)
"How do you feel about {switched} in reality"
}
"{x} dream {y}" -> [
"What does this dream suggest to you"
"Do you dream often"
"What persons appear in your dreams"
"Don't you believe that dream has to do with your problem"
]
"{x} my mother {y}" -> {
let switched = repersonalize (y)
[
"Who else in your family {y}"
"Tell me more about your family"
]
}
"{x} my father {y}" -> [
"Your father"
"Does he influence you strongly"
"What else comes to mind when you think of your father"
]
"{x} i want {y}" -> {
let switched = repersonalize (y)
[
"What would it mean if you got {y}"
"Why do you want {y}"
"Suppose you got {y} soon"
]
}
"{x} i am glad {y}" -> {
let switched = repersonalize (y)
[
"How have I helped you to be {y}"
"What makes you happy just now"
"Can you explain why you are suddenly {y}"
]
}
"{x} i am sad {y}" -> {
let switched = repersonalize (y)
[
"I am sorry to hear you are depressed"
"I'm sure it's not pleasant to be sad"
]
}
"{x} are like {y}" -> {
let switched_x = repersonalize (x)
let switched_y = repersonalize (y)
"What resemblance to you see between {switched_x} and {switched_y}"
}
"{x} is like {y}" -> {
let switched_x = repersonalize (x)
let switched_y = repersonalize (y)
[
"In what way is it that {switched_x} is like {switched_y}"
"What resemblance do you see"
"Could there really be some connection"
"How"
]
}
"{x} alike {y}" -> [
"In what way"
"What similarities are there"
]
"{x} same {y}" -> "What other connections do you see"
"{x} i was {y}" -> {
let switched = repersonalize (y)
[
"Were you really"
"Perhaps I already knew you were {switched}"
"Why do you tell me you were {switched} now"
]
}
"{x} was i {y}" -> {
let switched = repersonalize (y)
[
"What if you were {switched}"
"Do you think you were {switched}"
"What wouuld it mean if you were {switched}"
]
}
"{x} i am {y}" -> {
let switched = repersonalize (y)
[
"In what way are you {switched}"
"Do you want to be {switched}"
]
}
"{x} am i {y}" -> {
let switched = repersonalize (y)
[
"Do you believe you are {switched}"
"Would you want to be {switched}"
"You wish I would tell you you are {switched}"
"What would it mean if you were {switched}"
]
}
"{x} am {y}" -> [
"Why do you say *AM*"
"I don't understand that"
]
"{x} are you {y}" -> {
let switched = repersonalize (y)
[
"Why are you interested in whether I am {switched} or not"
"Would you prefer if I weren't {switched}"
"Perhaps I am {switched} in your fantasies"
]
}
"{x} you are {y}" -> {
let switched = repersonalize (y)
"What makes you think I am {y}"
}
"{x} because {y}" -> [
"Is that the real reason"
"What other reasons might there be"
"Does that reason seem to explain anything else"
]
"{x} were you {y}" -> {
let switched = repersonalize (y)
[
"Perhaps I was {switched}"
"What od you think"
"What if I had been {switched}"
]
}
"{x} i can't {y}" -> {
let switched = repersonalize (y)
[
"Maybe you could {switched} now"
"What if you could {switched}"
]
}
"{x} i feel {y}" -> {
let switched = repersonalize (y)
"Do you often feel {switched}"
}
"{x} i felt {y}" -> "What other feelings do you have"
"{x} i {y} you {z}" -> {
let switched = repersonalize (y)
"Perhaps in your fantasy we {switched} each other"
}
"{x} why don't you {y}" -> {
let switched = repersonalize (y)
[
"Should you {y} yourself"
"Do you believe I don't {y}"
"Perhaps I will {y} in good time"
]
}
"{x} yes {y}" -> [
"You seem quite positive"
"You are sure"
"I understand"
]
"{x} no {y}" -> [
"Why not"
"You are being a bit negative"
"Are you saying *NO* just to be negative"
]
"{x} someone {y}" -> "Can you be more specific"
"{x} everyone {y}" -> [
"Surely not everyone"
"Can you think of anyone in particular"
"Who for example"
"You are thinking of a special person"
]
"{x} always {y}" -> [
"Can you think of a specific example"
"When"
"What incident are you thinking of"
"Really--always"
]
"{x} what {y}" -> [
"Why do you ask"
"Does that question interest you"
"What is it you really want to know"
"What do you think"
"What comes to your mind when you ask that"
]
"{x} perhaps {y}" -> "You do not seem quite certain"
"{x} are {y}" -> {
let switched = repersonalize (y)
[
"Did you think they might not be {switched}"
"Possibly they are {switched}"
]
}
_ -> [
"Very interesting"
"I am not sure I understand you fully"
"What does that suggest to you"
"Please continue"
"Go on"
"Do you feel strongly about discussing such things"
]
}
print! (">>> ", do output > one_of > upcase)

View File

@ -8,7 +8,6 @@
(defn ludus/or [& args] (some bool args)) (defn ludus/or [& args] (some bool args))
(defn ludus/type [value] (defn ludus/type [value]
(when (= :^nil value) (break :nil))
(def typed? (when (dictionary? value) (value :^type))) (def typed? (when (dictionary? value) (value :^type)))
(def the-type (if typed? typed? (type value))) (def the-type (if typed? typed? (type value)))
(case the-type (case the-type
@ -53,8 +52,6 @@
(set stringify stringify*) (set stringify stringify*)
(var show nil)
(defn- show-pkg [x] (defn- show-pkg [x]
(def tab (struct/to-table x)) (def tab (struct/to-table x))
(set (tab :^name) nil) (set (tab :^name) nil)
@ -62,57 +59,41 @@
(string "pkg " (x :^name) " {" (stringify tab) "}") (string "pkg " (x :^name) " {" (stringify tab) "}")
) )
(defn- dict-show [dict] (defn show [x]
(string/join
(map
(fn [[k v]] (string (show k) " " (show v)))
(pairs dict))
", "))
(defn- set-show [sett]
(def prepped (merge sett))
(set (prepped :^type) nil)
(def shown (map show (keys prepped)))
(string/join shown ", ")
)
(defn- show* [x]
(case (ludus/type x) (case (ludus/type x)
:nil "nil" :nil "nil"
:string (string "\"" x "\"") :string (string "\"" x "\"")
:tuple (string "(" (string/join (map show x) ", ") ")") :tuple (string "(" (stringify x) ")")
:list (string "[" (string/join (map show x) ", ") "]") :list (string "[" (stringify x) "]")
:dict (string "#{" (dict-show x) "}") :dict (string "#{" (stringify x) "}")
:set (string "${" (set-show x) "}") :set (string "${" (stringify x) "}")
:box (string "box " (x :name) " [ " (show (x :^value)) " ]") :box (string "box " (x :name) " [ " (stringify x) " ]")
:pkg (show-pkg x) :pkg (show-pkg x)
(stringify x))) (stringify x)))
(set show show*) (var json nil)
# (var json nil) (defn- dict-json [dict]
(string/join
(map
(fn [[k v]] (string (json k) ": " (json v)))
(pairs dict))
", "))
# (defn- dict-json [dict] (defn- json* [x]
# (string/join (case (ludus/type x)
# (map :nil "null"
# (fn [[k v]] (string (json k) ": " (json v))) :number (string x)
# (pairs dict)) :bool (if true "true" "false")
# ", ")) :string (string "\"" x "\"")
:keyword (string "\"" x "\"")
:tuple (string "[" (string/join (map json x) ", ") "]")
:list (string "[" (string/join (map json x) ", ")"]")
:dict (string "{" (dict-json x) "}")
:set (string "[" (string/join (map json (keys x)) ", ") "]")
(show x)))
# (defn- json* [x] (set json json*)
# (case (ludus/type x)
# :nil "\"null\""
# :number (string x)
# :bool (if true "\"true\"" "\"false\"")
# :string (string "\"" x "\"")
# :keyword (string "\"" x "\"")
# :tuple (string "[" (string/join (map json x) ", ") "]")
# :list (string "[" (string/join (map json x) ", ")"]")
# :dict (string "{" (dict-json x) "}")
# :set (string "[" (string/join (map json (keys x)) ", ") "]")
# (show x)))
# (set json json*)
(defn show-patt [x] (defn show-patt [x]
(case (x :type) (case (x :type)
@ -129,20 +110,16 @@
:typed (string (show-patt (get-in x [:data 1])) " as " (show-patt (get-in x [:data 0]))) :typed (string (show-patt (get-in x [:data 1])) " as " (show-patt (get-in x [:data 0])))
:interpolated (get-in x [:token :lexeme]) :interpolated (get-in x [:token :lexeme])
:string (get-in x [:token :lexeme]) :string (get-in x [:token :lexeme])
:splat (string "..." (when (x :data) (show-patt (x :data)))) :splat (string "..." (when (x :splatted) (show-patt (x :splatted))))
(error (string "cannot show pattern of unknown type " (x :type))))) (error (string "cannot show pattern of unknown type " (x :type)))))
(defn pretty-patterns [fnn] (defn pretty-patterns [fnn]
(def {:body clauses} fnn) (def {:body clauses} fnn)
(string/join (map (fn [x] (-> x first show-patt)) clauses) "\n")) (string/join (map (fn [x] (-> x first show-patt)) clauses) " "))
(defn doc [fnn] (defn doc [fnn]
(when (not= :fn (ludus/type fnn)) (break "No documentation available.")) (def {:name name :doc doc} fnn)
(def {:name name :doc docstring} fnn) (string/join [name (pretty-patterns fnn) doc] "\n"))
(string/join [name
(pretty-patterns fnn)
(if docstring docstring "No docstring available.")]
"\n"))
(defn- conj!-set [sett value] (defn- conj!-set [sett value]
(set (sett value) true) (set (sett value) true)
@ -210,13 +187,8 @@
:set (-> x (dissoc :^type) keys) :set (-> x (dissoc :^type) keys)
@[x])) @[x]))
(defn showprint [x]
(if (= :string (ludus/type x))
x
(show x)))
(defn print! [args] (defn print! [args]
(print ;(map showprint args))) (print ;(map show args)))
(defn prn [x] (defn prn [x]
(pp x) (pp x)
@ -232,89 +204,66 @@
(defn store! [b x] (set (b :^value) x)) (defn store! [b x] (set (b :^value) x))
(defn mod [x y]
(% x y))
(defn- byte->ascii [c i]
(if (< c 128)
(string/from-bytes c)
(error (string "non-ASCII character at index" i))))
(defn chars [str]
(def out @[])
(try
(for i 0 (length str)
(array/push out (byte->ascii (str i) i)))
([e] (break [:err e])))
[:ok out])
(def ctx { (def ctx {
"add" +
"and" ludus/and
"assoc!" assoc!
"assoc" assoc
"atan_2" math/atan2
"bool" bool
"ceil" math/ceil
"chars" chars
"concat" concat
"conj!" conj!
"conj" conj
"cos" math/cos
"count" length
"dec" dec
"disj!" disj!
"disj" disj
"dissoc!" dissoc!
"dissoc" dissoc
"div" /
"doc" doc
"downcase" string/ascii-lower
"eq?" deep=
"first" first
"floor" math/floor
"get" ludus/get
"gt" >
"gte" >=
"inc" inc
"last" last
"lt" <
"lte" <=
"mod" mod
"mult" *
"not" not
"nth" ludus/get
"or" ludus/or
"pi" math/pi
"print!" print! "print!" print!
"prn" prn "prn" prn
"push" array/push "eq?" deep=
"random" math/random "bool" bool
"range" range "and" ludus/and
"rest" rest "or" ludus/or
"round" math/round "add" +
"show" show
"sin" math/sin
"slice" array/slice
"split" string/split
"sqrt" math/sqrt
"store!" store!
"str_slice" string/slice
"stringify" stringify
"sub" - "sub" -
"tan" math/tan "mult" *
"to_list" to_list "div" /
"trim" string/trim "mod" %
"triml" string/triml "gt" >
"trimr" string/trimr "gte" >=
"lt" <
"lte" <=
"inc" inc
"dec" dec
"not" not
"type" ludus/type "type" ludus/type
"stringify" stringify
"show" show
"doc" doc
"concat" concat
"conj" conj
"conj!" conj!
"disj" disj
"disj!" disj!
"push" array/push
"assoc" assoc
"assoc!" assoc!
"dissoc" dissoc
"dissoc!" dissoc!
"get" ludus/get
"nth" ludus/get
"first" first
"rest" rest
"last" last
"slice" slice
"to_list" to_list
"count" length
"pi" math/pi
"sin" math/sin
"cos" math/cos
"tan" math/tan
"atan_2" math/atan2
"sqrt" math/sqrt
"random" math/random
"floor" math/floor
"ceil" math/ceil
"round" math/round
"range" range
"unbox" unbox "unbox" unbox
"upcase" string/ascii-upper "store!" store!
}) })
(def base (let [b @{:^type :dict}] (def base (let [b @{}]
(each [k v] (pairs ctx) (each [k v] (pairs ctx)
(set (b (keyword k)) v)) (set (b (keyword k)) v))
b)) b))
(set (base :^type) :dict)

View File

@ -1,130 +0,0 @@
(import /src/base :as base)
(import /src/prelude :as prelude)
(defn map-values [f dict]
(from-pairs (map (fn [[k v]] [k (f v)]) (pairs dict))))
(def with-docs (map-values base/doc prelude/ctx))
(def sorted-names (-> with-docs keys sort))
(defn escape-underscores [str] (string/replace "_" "\\_" str))
(defn escape-punctuation [str] (->> str
(string/replace "?" "")
(string/replace "!" "")))
(defn toc-entry [name]
(def escaped (escape-underscores name))
(string "[" escaped "](#" (escape-punctuation escaped) ")"))
(def alphabetical-list
(string/join (map toc-entry sorted-names) "&nbsp;&nbsp;&nbsp; "))
(def topics {
"math" ["abs" "add" "angle" "atan/2" "between?" "ceil" "cos" "dec" "deg/rad" "deg/turn" "dist" "div" "div/0" "div/safe" "even?" "floor" "gt?" "gte?" "heading/vector" "inc" "inv" "inv/0" "inv/safe" "lt?" "lte?" "max" "min" "mod" "mod/0" "mod/safe" "mult" "neg" "neg?" "odd?" "pi" "pos?" "rad/deg" "rad/turn" "random" "random_int" "range" "round" "sin" "sqrt" "sqrt/safe" "square" "sub" "sum_of_squares" "tan" "tau" "turn/deg" "turn/rad" "zero?"]
"boolean" ["and" "bool" "bool?" "false?" "not" "or" "true?"]
"dicts" ["any?" "assoc" "assoc?" "coll?" "count" "dict" "dict?" "diff" "dissoc" "empty?" "get" "keys" "random" "update" "values"]
"lists" ["any?" "append" "at" "butlast" "coll?" "concat" "count" "each!" "empty?" "filter" "first" "fold" "join" "keep" "last" "list" "list?" "map" "ordered?" "random" "range" "rest" "second" "sentence" "slice"]
"sets" ["any?" "append" "coll?" "concat" "contains?" "count" "empty?" "omit" "random" "set" "set?"]
"tuples" ["any?" "at" "coll?" "count" "empty?" "first" "last" "ordered?" "rest" "second" "tuple?"]
"strings" ["any?" "chars" "chars/safe" "concat" "count" "downcase" "empty?" "join" "sentence" "show" "slice" "split" "string" "string?" "strip" "trim" "upcase" "words"]
"types and values" ["assoc?" "bool?" "box?" "coll?" "dict?" "eq?" "fn?" "keyword?" "list?" "neq?" "nil?" "number?" "ordered?" "set?" "show" "some" "some?" "string?" "tuple?" "type"]
"boxes and state" ["box?" "unbox" "store!" "update!"]
"results" ["err" "err?" "ok" "ok?" "unwrap!" "unwrap_or"]
"errors" ["assert!"]
"turtle graphics" ["back!" "background!" "bk!" "clear!" "colors" "fd!" "forward!" "goto!" "heading" "heading/vector" "home!" "left!" "lt!" "pc!" "pd!" "pencolor" "pencolor!" "pendown!" "pendown?" "penup!" "penwidth" "penwidth!" "position" "pu!" "pw!" "render_turtle!" "reset_turtle!" "right!" "rt!" "turtle_state"]
"environment and i/o" ["doc!" "print!" "report!" "state"]
})
(defn capitalize [str]
(def fst (slice str 0 1))
(def rest (slice str 1))
(def init_cap (string/ascii-upper fst))
(def lower_rest (string/ascii-lower rest))
(string init_cap lower_rest))
(defn topic-entry [topic]
(string "### " (capitalize topic) "\n"
(as-> topic _ (topics _) (array/slice _) (sort _) (map toc-entry _)
(string/join _ "&nbsp;&nbsp;&nbsp; "))
"\n"))
(def by-topic (let [the-topics (-> topics keys sort)
topics-entries (map topic-entry the-topics)]
(string/join topics-entries "\n")))
(defn compose-entry [name]
(def header (string "\n### " name "\n"))
(def the-doc (get with-docs name))
(when (= "No documentation available." the-doc)
(break (string header the-doc "\n")))
(def lines (string/split "\n" the-doc))
(def description (last lines))
(def patterns (string/join (slice lines 1 (-> lines length dec)) "\n"))
(def backto "[Back to top.](#ludus-prelude-documentation)\n")
(string header description "\n```\n" patterns "\n```\n" backto))
(compose-entry "update")
(def entries (string/join (map compose-entry sorted-names) "\n---"))
(def doc-file (string
```
# Ludus prelude documentation
These functions are available in every Ludus script.
The documentation for any function can be found within Ludus by passing the function to `doc!`,
e.g., running `doc! (add)` will send the documentation for `add` to the console.
For more information on the syntax & semantics of the Ludus language, see [language.md](./language.md).
The prelude itself is just a Ludus file, which you can see at [prelude.ld](./prelude.ld).
## A few notes
**Naming conventions.** Functions whose name ends with a question mark, e.g., `eq?`, return booleans.
Functions whose name ends with an exclamation point, e.g., `make!`, change state in some way.
In other words, they _do things_ rather than _calculating values_.
Functions whose name includes a slash either convert from one value to another, e.g. `deg/rad`,
or they are variations on a function, e.g. `div/0` as a variation on `div`.
**How entries are formatted.** Each entry has a brief (sometimes too brief!) description of what it does.
It is followed by the patterns for each of its function clauses.
This should be enough to indicate order of arguments, types, and so on.
**Patterns often, but do not always, indicate types.** Typed patterns are written as `foo as :bar`,
where the type is indicated by the keyword.
Possible ludus types are: `:nil`, `:boolean`, `:number`, `:keyword` (atomic values);
`:string` (strings are their own beast); `:tuple` and `:list` (ordered collections), `:set`s, and `:dict`ionaries (the other collection types); `:pkg` (packages, which are quasi-collections); `:fn` (functions); and `:box`es.
**Conventional types.** Ludus has two types based on conventions.
* _Result tuples._ Results are a way of modeling the result of a calculation that might fail.
The two possible values are `(:ok, value)` and `(:err, msg)`.
`msg` is usually a string describing what went wrong.
To work with result tuples, see [`unwrap!`](#unwrap) and [`unwrap_or`](#unwrap_or).
That said, usually you work with these using pattern matching.
* _Vectors._ Vectors are 2-element tuples of x and y coordinates.
The origin is `(0, 0)`.
Many math functions take vectors as well as numbers, e.g., `add` and `mult`.
You will see vectors indicated in patterns by an `(x, y)` tuple.
You can see what this looks like in the last clause of `add`: `((x1, y1), (x2, y2))`.
## Functions by topic
```
by-topic
```
## All functions, alphabetically
```
alphabetical-list
```
## Function documentation
```
entries
))
(spit "prelude.md" doc-file)

View File

@ -3,138 +3,78 @@
(defn- get-line [source line] (defn- get-line [source line]
((string/split "\n" source) (dec line))) ((string/split "\n" source) (dec line)))
(defn- caret [source line start] (defn scan-error [e] (pp e) e)
(def lines (string/split "\n" source))
(def the-line (lines (dec line)))
(def prev-lines (slice lines 0 (dec line)))
(def char-counts (map (fn [x] (-> x length inc)) prev-lines))
(def prev-line-chars (sum char-counts))
(def offset (- start prev-line-chars))
(def indent (string/repeat "." (+ 6 offset)))
(string indent "^")
)
(defn scan-error [e]
(def {:line line-num :input input :source source :start start :msg msg} e)
(print "Syntax error: " msg)
(print " on line " line-num " in " input ":")
(def source-line (get-line source line-num))
(print " >>> " source-line)
(print (caret source line-num start))
e)
(defn parse-error [e] (defn parse-error [e]
(def msg (e :msg)) (def msg (e :msg))
(def {:line line-num :input input :source source :start start} (e :token)) (def {:line line-num :input input :soure source} (e :token))
(def source-line (get-line source line-num)) (def source-line (get-line source line-num))
(print "Syntax error: " msg) (print "Parsing error: " msg)
(print " on line " line-num " in " input ":") (print "On line " line-num " in " input)
(print " >>> " source-line) (print source-line)
(print (caret source line-num start))
e) e)
(defn validation-error [e] (defn validation-error [e]
(def msg (e :msg)) (def msg (e :msg))
(def {:line line-num :input input :source source :start start} (get-in e [:node :token])) (def {:line line-num :input input :source source} (get-in e [:node :token]))
(def source-line (get-line source line-num)) (def source-line (get-line source line-num))
(case msg (case msg
"unbound name" "unbound name"
(do (do
(print "Validation error: " msg " " (get-in e [:node :data])) (print "Validation error: " msg " " (get-in e [:node :data]))
(print " on line " line-num " in " input ":") (print "on line " line-num " in " input)
(print " >>> " source-line) (print source-line))
(print (caret source line-num start)))
(do (do
(print "Validation error: " msg) (print "Validation error: " msg)
(print " on line " line-num " in " input ":") (print "on line " line-num)
(print " >>> " source-line) (print source-line)))
(print (caret source line-num start))))
e) e)
(defn- fn-no-match [e] (defn- fn-no-match [e]
(print "Ludus panicked! no match") (print "Ludus panicked! no match")
(def {:line line-num :source source :input input :start start} (get-in e [:node :token])) (def {:line line-num :source source :input input} (get-in e [:node :token]))
(def source-line (get-line source line-num)) (def source-line (get-line source line-num))
(print " on line " line-num " in " input ", ") (print "on line " line-num " in " input)
(def called (e :called)) (def called (e :called))
(print " calling: " (slice (b/show called) 3)) (print "calling " (b/show called))
(def value (e :value)) (def value (e :value))
(print " with arguments: " (b/show value)) (print "with " (b/show value))
(print " expected match with one of:") (print "expecting to match one of")
(def patterns (b/pretty-patterns called)) (print (b/pretty-patterns called))
(def fmt-patt (do (print source-line))
(def lines (string/split "\n" patterns))
(def indented (map (fn [x] (string " " x)) lines))
(string/join indented "\n")
))
(print fmt-patt)
(print " >>> " source-line)
(print (caret source line-num start))
)
(defn- let-no-match [e] (defn- let-no-match [e]
(print "Ludus panicked! no match") (print "Ludus panicked! no match")
(def {:line line-num :source source :input input :start start} (get-in e [:node :token])) (def {:line line-num :source source :input input} (get-in e [:node :token]))
(def source-line (get-line source line-num)) (def source-line (get-line source line-num))
(print " on line " line-num " in " input ", ") (print "on line " line-num " in " input)
(print " matching: " (b/show (e :value))) (print "binding " (b/show (e :value)))
(def pattern (get-in e [:node :data 0])) (def pattern (get-in e [:node :data 0]))
(print " with pattern: " (b/show-patt pattern)) (print "to " (b/show-patt pattern))
(print " >>> " source-line) (print source-line))
(print (caret source line-num start))
e)
(defn- match-no-match [e]
(print "Ludus panicked! no match")
(def {:line line-num :source source :input input :start start} (get-in e [:node :token]))
(print " on line " line-num " in " input ", ")
(def value (e :value))
(print " matching: " (b/show value))
(print " with patterns:")
(def clauses (get-in e [:node :data 1]))
(def patterns (b/pretty-patterns {:body clauses}))
(def fmt-patt (do
(def lines (string/split "\n" patterns))
(def indented (map (fn [x] (string " " x)) lines))
(string/join indented "\n")
))
(print fmt-patt)
(def source-line (get-line source line-num))
(print " >>> " source-line)
(print (caret source line-num start))
e)
(defn- generic-panic [e] (defn- generic-panic [e]
(def msg (e :msg)) (def msg (e :msg))
(def {:line line-num :source source :input input :start start} (get-in e [:node :token])) (def {:line line-num :source source :input input} (get-in e [:node :token]))
(def source-line (get-line source line-num)) (def source-line (get-line source line-num))
(print "Ludus panicked! " msg) (print "Ludus panicked! " msg)
(print " on line " line-num " in " input ":") (print "on line " line-num " in " input)
(print " >>> " source-line) (print source-line))
(print (caret source line-num start))
e)
(defn- unbound-name [e] (defn- unbound-name [e]
(def {:line line-num :source source :lexeme name :input input :start start} (get-in e [:node :token])) (def {:line line-num :source source :lexeme name :input input} (get-in e [:node :token]))
(def source-line (get-line source line-num)) (def source-line (get-line source line-num))
(print "Ludus panicked! unbound name " name) (print "Ludus panicked! unbound name " name)
(print " on line " line-num " in " input ":") (print "on line " line-num " in " input)
(print " >>> " source-line) (print source-line))
(print (caret source line-num start))
e)
(defn runtime-error [e] (defn runtime-error [e]
(when (= :string (type e)) (when (= :string (type e)) (print e) (break e))
(print (string "Internal Ludus error: " e))
(print "Please file an issue at https://alea.ludus.dev/twc/ludus/issues")
(break e))
(def msg (e :msg)) (def msg (e :msg))
(case msg (case msg
"no match: function call" (fn-no-match e) "no match: function call" (fn-no-match e)
"no match: let binding" (let-no-match e) "no match: let binding" (let-no-match e)
"no match: match form" (match-no-match e)
"no match: when form" (generic-panic e)
"unbound name" (unbound-name e) "unbound name" (unbound-name e)
(generic-panic e)) (generic-panic e))
e) e)

View File

@ -183,7 +183,7 @@
:word (match-word pattern value ctx) :word (match-word pattern value ctx)
# match on equality # match on equality
:nil {:success (= :^nil value) :ctx ctx} :nil {:success (nil? value) :ctx ctx}
:bool {:success (= data value) :ctx ctx} :bool {:success (= data value) :ctx ctx}
:number {:success (= data value) :ctx ctx} :number {:success (= data value) :ctx ctx}
:string {:success (= data value) :ctx ctx} :string {:success (= data value) :ctx ctx}
@ -251,9 +251,7 @@
(interpret last-line ctx)) (interpret last-line ctx))
(defn- to_string [ctx] (fn [x] (defn- to_string [ctx] (fn [x]
(if (buffer? x) (b/stringify (interpret x ctx))))
(string x)
(b/stringify (interpret x ctx)))))
(defn- interpolated [ast ctx] (defn- interpolated [ast ctx]
(def terms (ast :data)) (def terms (ast :data))
@ -345,7 +343,7 @@
(set (the-dict key) value)))) (set (the-dict key) value))))
the-dict) the-dict)
(defn- box [ast ctx] (defn- ref [ast ctx]
(def {:data value-ast :name name} ast) (def {:data value-ast :name name} ast)
(def value (interpret value-ast ctx)) (def value (interpret value-ast ctx))
(def box @{:^type :box :^value value :name name}) (def box @{:^type :box :^value value :name name})
@ -423,8 +421,8 @@
(when (= :function (type clauses)) (when (= :function (type clauses))
(break (clauses root-ast ;args))) (break (clauses root-ast ;args)))
(def len (length clauses)) (def len (length clauses))
(when (the-fn :match) (break ((the-fn :match) root-ast 0 args))) (when (the-fn :match) (break ((the-fn :match) 0 args)))
(defn match-fn [root-ast i args] (defn match-fn [i args]
(when (= len i) (when (= len i)
(error {:node root-ast :called the-fn :value args :msg "no match: function call"})) (error {:node root-ast :called the-fn :value args :msg "no match: function call"}))
(def clause (clauses i)) (def clause (clauses i))
@ -432,17 +430,17 @@
(def match? (def match?
(match-pattern patt args @{:^parent (the-fn :ctx)})) (match-pattern patt args @{:^parent (the-fn :ctx)}))
(when (not (match? :success)) (when (not (match? :success))
(break (match-fn root-ast (inc i) args))) (break (match-fn (inc i) args)))
# (print "matched!") # (print "matched!")
(def body-ctx (match? :ctx)) (def body-ctx (match? :ctx))
(def guard? (if guard (def guard? (if guard
(b/bool (interpret guard body-ctx)) true)) (b/bool (interpret guard body-ctx)) true))
# (print "passed guard") # (print "passed guard")
(when (not guard?) (when (not guard?)
(break (match-fn root-ast (inc i) args))) (break (match-fn (inc i) args)))
(interpret expr body-ctx)) (interpret expr body-ctx))
(set (the-fn :match) match-fn) (set (the-fn :match) match-fn)
(match-fn root-ast 0 args)) (match-fn 0 args))
(set call-fn call-fn*) (set call-fn call-fn*)
@ -460,12 +458,10 @@
[:function :tuple] (call-fn root-ast prev curr) [:function :tuple] (call-fn root-ast prev curr)
# [:applied :tuple] (call-partial root-ast prev curr) # [:applied :tuple] (call-partial root-ast prev curr)
[:keyword :args] (get (first curr) prev :^nil) [:keyword :args] (get (first curr) prev :^nil)
[:keyword :tuple] (get (first curr) prev :^nil)
[:dict :keyword] (get prev curr :^nil) [:dict :keyword] (get prev curr :^nil)
[:nil :keyword] :^nil [:nil :keyword] :^nil
[:pkg :keyword] (get prev curr :^nil) [:pkg :keyword] (get prev curr :^nil)
[:pkg :pkg-kw] (get prev curr :^nil) [:pkg :pkg-kw] (get prev curr :^nil)))
(error (string "cannot call " (b/ludus/type prev) " `" (b/show prev) "`"))))
(defn- synthetic [ast ctx] (defn- synthetic [ast ctx]
(def terms (ast :data)) (def terms (ast :data))
@ -474,7 +470,7 @@
# (pp terms) # (pp terms)
(def first-term (first terms)) (def first-term (first terms))
(def last-term (last terms)) (def last-term (last terms))
(var prev (interpret first-term ctx)) (var prev (interpret first-term ctx))
# (print "root term: ") # (print "root term: ")
# (pp prev) # (pp prev)
(for i 1 (-> terms length dec) (for i 1 (-> terms length dec)
@ -490,9 +486,9 @@
(def last-term (last terms)) (def last-term (last terms))
(for i 1 (-> terms length dec) (for i 1 (-> terms length dec)
(def curr (interpret (terms i) ctx)) (def curr (interpret (terms i) ctx))
(set prev (apply-synth-term (first terms) curr [prev]))) (set prev (call-fn (first terms) curr [prev])))
(def last-fn (interpret last-term ctx)) (def last-fn (interpret last-term ctx))
(apply-synth-term (first terms) last-fn [prev])) (call-fn (first terms) last-fn [prev]))
(defn- pkg [ast ctx] (defn- pkg [ast ctx]
(def members (ast :data)) (def members (ast :data))
@ -595,7 +591,7 @@
# named/naming forms # named/naming forms
:word (word ast ctx) :word (word ast ctx)
:interpolated (interpolated ast ctx) :interpolated (interpolated ast ctx)
:box (box ast ctx) :ref (ref ast ctx)
:pkg (pkg ast ctx) :pkg (pkg ast ctx)
:pkg-name (word ast ctx) :pkg-name (word ast ctx)
@ -624,9 +620,9 @@
(set interpret interpret*) (set interpret interpret*)
# # repl # # repl
# (import /src/scanner :as s) # (import ./scanner :as s)
# (import /src/parser :as p) # (import ./parser :as p)
# (import /src/validate :as v) # (import ./validate :as v)
# (var source nil) # (var source nil)
@ -641,16 +637,14 @@
# # (when (has-errors? validated) (break (validated :errors))) # # (when (has-errors? validated) (break (validated :errors)))
# # (def cleaned (get-in parsed [:ast :data 1])) # # (def cleaned (get-in parsed [:ast :data 1]))
# # # (pp cleaned) # # # (pp cleaned)
# (interpret (parsed :ast) @{:^parent b/lett}) # # (interpret (parsed :ast) @{:^parent b/ctx})
# # (try (interpret (parsed :ast) @{:^parent b/ctx}) # (try (interpret (parsed :ast) @{:^parent b/ctx})
# # ([e] (if (struct? e) (error (e :msg)) (error e)))) # ([e] (if (struct? e) (error (e :msg)) (error e)))))
# )
# # (do # # (do
# (comment # (comment
# (set source ` # (set source `
# let foo = 42
# "{foo} bar baz"
# `) # `)
# (def result (run)) # (def result (run))
# ) # )

View File

@ -1,131 +0,0 @@
# pulled from cfiggers/jayson
(defmacro- letv [bindings & body]
~(do ,;(seq [[k v] :in (partition 2 bindings)] ['var k v]) ,;body))
(defn- read-hex [n]
(scan-number (string "0x" n)))
(defn- check-utf-16 [capture]
(let [u (read-hex capture)]
(if (and (>= u 0xD800)
(<= u 0xDBFF))
capture
false)))
(def- utf-8->bytes
(peg/compile
~{:double-u-esc (/ (* "\\u" (cmt (<- 4) ,|(check-utf-16 $)) "\\u" (<- 4))
,|(+ (blshift (- (read-hex $0) 0xD800) 10)
(- (read-hex $1) 0xDC00) 0x10000))
:single-u-esc (/ (* "\\u" (<- 4)) ,|(read-hex $))
:unicode-esc (/ (+ :double-u-esc :single-u-esc)
,|(string/from-bytes
;(cond
(<= $ 0x7f) [$]
(<= $ 0x7ff)
[(bor (band (brshift $ 6) 0x1F) 0xC0)
(bor (band (brshift $ 0) 0x3F) 0x80)]
(<= $ 0xffff)
[(bor (band (brshift $ 12) 0x0F) 0xE0)
(bor (band (brshift $ 6) 0x3F) 0x80)
(bor (band (brshift $ 0) 0x3F) 0x80)]
# Otherwise
[(bor (band (brshift $ 18) 0x07) 0xF0)
(bor (band (brshift $ 12) 0x3F) 0x80)
(bor (band (brshift $ 6) 0x3F) 0x80)
(bor (band (brshift $ 0) 0x3F) 0x80)])))
:escape (/ (* "\\" (<- (set "avbnfrt\"\\/")))
,|(get {"a" "\a" "v" "\v" "b" "\b"
"n" "\n" "f" "\f" "r" "\r"
"t" "\t"} $ $))
:main (+ (some (+ :unicode-esc :escape (<- 1))) -1)}))
(defn decode
``
Returns a janet object after parsing JSON. If `keywords` is truthy,
string keys will be converted to keywords. If `nils` is truthy, `null`
will become `nil` instead of the keyword `:json/null`.
``
[json-source &opt keywords nils]
(def json-parser
{:null (if nils
~(/ (<- (+ "null" "Null")) nil)
~(/ (<- (+ "null" "Null")) :json/null))
:bool-t ~(/ (<- (+ "true")) true)
:bool-f ~(/ (<- (+ "false")) false)
:number ~(/ (<- (* (? "-") :d+ (? (* "." :d+)))) ,|(scan-number $))
:string ~(/ (* "\"" (<- (to (* (> -1 (not "\\")) "\"")))
(* (> -1 (not "\\")) "\""))
,|(string/join (peg/match utf-8->bytes $)))
:array ~(/ (* "[" :s* (? (* :value (any (* :s* "," :value)))) "]") ,|(array ;$&))
:key-value (if keywords
~(* :s* (/ :string ,|(keyword $)) :s* ":" :value)
~(* :s* :string :s* ":" :value))
:object ~(/ (* "{" :s* (? (* :key-value (any (* :s* "," :key-value)))) "}")
,|(from-pairs (partition 2 $&)))
:value ~(* :s* (+ :null :bool-t :bool-f :number :string :array :object) :s*)
:unmatched ~(/ (<- (to (+ :value -1))) ,|[:unmatched $])
:main ~(some (+ :value "\n" :unmatched))})
(first (peg/match (peg/compile json-parser) json-source)))
(def- bytes->utf-8
(peg/compile
~{:four-byte (/ (* (<- (range "\xf0\xff")) (<- 1) (<- 1) (<- 1))
,|(bor (blshift (band (first $0) 0x07) 18)
(blshift (band (first $1) 0x3F) 12)
(blshift (band (first $2) 0x3F) 6)
(blshift (band (first $3) 0x3F) 0)))
:three-byte (/ (* (<- (range "\xe0\xef")) (<- 1) (<- 1))
,|(bor (blshift (band (first $0) 0x0F) 12)
(blshift (band (first $1) 0x3F) 6)
(blshift (band (first $2) 0x3F) 0)))
:two-byte (/ (* (<- (range "\x80\xdf")) (<- 1))
,|(bor (blshift (band (first $0) 0x1F) 6)
(blshift (band (first $1) 0x3F) 0)))
:multi-byte (/ (+ :two-byte :three-byte :four-byte)
,|(if (< $ 0x10000)
(string/format "\\u%04X" $)
(string/format "\\u%04X\\u%04X"
(+ (brshift (- $ 0x10000) 10) 0xD800)
(+ (band (- $ 0x10000) 0x3FF) 0xDC00))))
:one-byte (<- (range "\x20\x7f"))
:0to31 (/ (<- (range "\0\x1F"))
,|(or ({"\a" "\\u0007" "\b" "\\u0008"
"\t" "\\u0009" "\n" "\\u000A"
"\v" "\\u000B" "\f" "\\u000C"
"\r" "\\u000D"} $)
(string/format "\\u%04X" (first $))))
:backslash (/ (<- "\\") "\\\\")
:quote (/ (<- "\"") "\\\"")
:main (+ (some (+ :0to31 :backslash :quote :one-byte :multi-byte)) -1)}))
(defn- encodeone [x depth]
(if (> depth 1024) (error "recurred too deeply"))
(cond
(= x :json/null) "null"
(= x nil) "null"
(bytes? x) (string "\"" (string/join (peg/match bytes->utf-8 x)) "\"")
(indexed? x) (string "[" (string/join (map |(encodeone $ (inc depth)) x) ",") "]")
(dictionary? x) (string "{" (string/join
(seq [[k v] :in (pairs x)]
(string "\"" (string/join (peg/match bytes->utf-8 k)) "\"" ":" (encodeone v (inc depth)))) ",") "}")
(case (type x)
:nil "null"
:boolean (string x)
:number (string x)
(error "type not supported"))))
(defn encode
``
Encodes a janet value in JSON (utf-8). If `buf` is provided, the formated
JSON is append to `buf` instead of a new buffer. Returns the modifed buffer.
``
[x &opt buf]
(letv [ret (encodeone x 0)]
(if (and buf (buffer? buf))
(buffer/push ret)
(thaw ret))))

1
src/judge Symbolic link
View File

@ -0,0 +1 @@
./jpm_tree/bin/judge

View File

@ -9,7 +9,6 @@
(import /src/errors :as e) (import /src/errors :as e)
(import /src/base :as b) (import /src/base :as b)
(import /src/prelude :as prelude) (import /src/prelude :as prelude)
(import /src/json :as j)
(defn ludus [source] (defn ludus [source]
(when (= :error prelude/pkg) (error "could not load prelude")) (when (= :error prelude/pkg) (error "could not load prelude"))
@ -18,28 +17,32 @@
(def draw @[]) (def draw @[])
(var result @"") (var result @"")
(def console @"") (def console @"")
(setdyn :out console)
(def out @{:errors errors :draw draw :result result :console console}) (def out @{:errors errors :draw draw :result result :console console})
(def scanned (s/scan source)) (def scanned (s/scan source))
(when (any? (scanned :errors)) (when (any? (scanned :errors))
(set (out :errors) (scanned :errors))
(each err (scanned :errors) (each err (scanned :errors)
(e/scan-error err)) (e/scan-error err))
(break (-> out j/encode string))) (break out))
(def parsed (p/parse scanned)) (def parsed (p/parse scanned))
(when (any? (parsed :errors)) (when (any? (parsed :errors))
(set (out :errors) (parsed :errors))
(each err (parsed :errors) (each err (parsed :errors)
(e/parse-error err)) (e/parse-error err))
(break (-> out j/encode string))) (break out))
(def validated (v/valid parsed ctx)) (def validated (v/valid parsed ctx))
(when (any? (validated :errors)) (when (any? (validated :errors))
(set (out :errors) (validated :errors))
(each err (validated :errors) (each err (validated :errors)
(e/validation-error err)) (e/validation-error err))
(break (-> out j/encode string))) (break out))
(setdyn :out console)
(try (try
(set result (i/interpret (parsed :ast) ctx)) (set result (i/interpret (parsed :ast) ctx))
([err] ([err]
(e/runtime-error err) (e/runtime-error err)
(break (-> out j/encode string)))) (set (out :errors) [err])
(break out)))
(setdyn :out stdout) (setdyn :out stdout)
(set (out :result) (b/show result)) (set (out :result) (b/show result))
(var post @{}) (var post @{})
@ -47,29 +50,7 @@
(set post (i/interpret prelude/post/ast ctx)) (set post (i/interpret prelude/post/ast ctx))
([err] (e/runtime-error err))) ([err] (e/runtime-error err)))
(set (out :draw) (post :draw)) (set (out :draw) (post :draw))
# out (b/json out))
(-> out j/encode string)
)
(comment (defn hello [] (print "hello"))
# (do
# (def start (os/clock))
(def source `
box foo = :bar
store! (foo, :baz)
unbox (foo)
`)
(def out (-> source
ludus
j/decode
))
# (def end (os/clock))
(setdyn :out stdout)
(pp out)
(def console (out "console"))
(print console)
(def result (out "result"))
(print result)
# (print (- end start))
)

View File

@ -3,9 +3,6 @@
### We still need to scan some things ### We still need to scan some things
(import /src/scanner :as s) (import /src/scanner :as s)
# stash janet type
(def janet-type type)
(defmacro declare (defmacro declare
"Forward-declares a function name, so that it can be called in a mutually recursive manner." "Forward-declares a function name, so that it can be called in a mutually recursive manner."
[& names] [& names]
@ -21,26 +18,6 @@
(if-not (dyn name) (error "recursive functions must be declared before they are defined")) (if-not (dyn name) (error "recursive functions must be declared before they are defined"))
~(set ,name (defn- ,name ,;forms))) ~(set ,name (defn- ,name ,;forms)))
### Some more human-readable formatting
(defn- pp-tok [token]
(if (not token) (break "nil"))
(def {:line line :lexeme lex :type type :start start} token)
(string "<" line "[" start "]" ": " type ": " lex ">"))
(defn- pp-ast [ast &opt indent]
(default indent 0)
(def {:token token :data data :type type} ast)
(def pretty-tok (pp-tok token))
(def data-rep (if (= :array (janet-type data))
(string "[\n"
(string/join (map (fn [x] (pp-ast x (inc indent))) data)
(string (string/repeat " " indent) "\n"))
"\n" (string/repeat " " indent) "]")
data
))
(string (string/repeat " " indent) type ": " pretty-tok " " data-rep)
)
### Next: a data structure for a parser ### Next: a data structure for a parser
(defn- new-parser (defn- new-parser
"Creates a new parser data structure to pass around" "Creates a new parser data structure to pass around"
@ -98,9 +75,7 @@
(has-value? terminators ttype)) (has-value? terminators ttype))
# breakers are what terminate panics # breakers are what terminate panics
(def breaking [:break :newline :semicolon :comma :eof (def breaking [:break :newline :semicolon :comma :eof :then :else])
# :then :else :arrow
])
(defn- breaks? (defn- breaks?
"Returns true if the current token in the parser should break a panic" "Returns true if the current token in the parser should break a panic"
@ -114,12 +89,12 @@
[parser message] [parser message]
# (print "Panic in the parser: " message) # (print "Panic in the parser: " message)
(def origin (current parser)) (def origin (current parser))
(def skipped @[]) (advance parser)
(def skipped @[origin])
(while (not (breaks? parser)) (while (not (breaks? parser))
(array/push skipped (current parser)) (array/push skipped (current parser))
(advance parser)) (advance parser))
(array/push skipped (current parser)) (array/push skipped (current parser))
# (advance parser)
(def err {:type :error :data skipped :token origin :msg message}) (def err {:type :error :data skipped :token origin :msg message})
(update parser :errors array/push err) (update parser :errors array/push err)
(error err)) (error err))
@ -304,10 +279,8 @@
(def origin (current parser)) (def origin (current parser))
(advance parser) # consume the :lparen (advance parser) # consume the :lparen
(def ast @{:type :args :data @[] :token origin :partial false}) (def ast @{:type :args :data @[] :token origin :partial false})
(while (separates? parser) (advance parser)) # consume any separators
(while (not (check parser :rparen)) (while (not (check parser :rparen))
(accept-many parser :newline :comma)
(when (= :break ((current parser) :type))
(break (advance parser)))
(when (check parser :eof) (when (check parser :eof)
(def err {:type :error :token origin :msg "unclosed paren"}) (def err {:type :error :token origin :msg "unclosed paren"})
(array/push (parser :errors) err) (array/push (parser :errors) err)
@ -326,7 +299,8 @@
{:type :placeholder :token origin})) {:type :placeholder :token origin}))
(capture nonbinding parser))) (capture nonbinding parser)))
(array/push (ast :data) term) (array/push (ast :data) term)
(capture separators parser)) (try (separators parser)
([e] (array/push (ast :data) e))))
(advance parser) (advance parser)
ast) ast)
@ -359,26 +333,20 @@
{:type :synthetic :data [;terms] :token origin}) {:type :synthetic :data [;terms] :token origin})
# collections # collections
### XXX: the current panic/capture structure in this, script, etc. is blowing up when the LAST element (line, tuple member, etc.) has an error
# it does, however, work perfectly well when there isn't one
# there's something about advancing past the breaking token, or not
# aslo, I removed the captures here around nonbinding and separators, and we got into a loop with a panic
# oy
(defn- tup [parser] (defn- tup [parser]
(def origin (current parser)) (def origin (current parser))
(advance parser) # consume the :lparen (advance parser) # consume the :lparen
(def ast {:type :tuple :data @[] :token origin}) (def ast {:type :tuple :data @[] :token origin})
(while (separates? parser) (advance parser)) # consume any separators
(while (not (check parser :rparen)) (while (not (check parser :rparen))
(accept-many parser :newline :comma)
(when (= :break ((current parser) :type))
(break (advance parser)))
(when (check parser :eof) (when (check parser :eof)
(def err {:type :error :token origin :msg "unclosed paren"}) (def err {:type :error :token origin :msg "unclosed paren"})
(array/push (parser :errors) err) (array/push (parser :errors) err)
(error err)) (error err))
(def term (capture nonbinding parser)) (def term (capture nonbinding parser))
(array/push (ast :data) term) (array/push (ast :data) term)
(capture separators parser)) (try (separators parser)
([e] (array/push (ast :data) e))))
(advance parser) (advance parser)
ast) ast)
@ -386,10 +354,8 @@
(def origin (current parser)) (def origin (current parser))
(advance parser) (advance parser)
(def ast {:type :list :data @[] :token origin}) (def ast {:type :list :data @[] :token origin})
(while (separates? parser) (advance parser))
(while (not (check parser :rbracket)) (while (not (check parser :rbracket))
(accept-many parser :newline :comma)
(when (= :break ((current parser) :type))
(break (advance parser)))
(when (check parser :eof) (when (check parser :eof)
(def err {:type :error :token origin :msg "unclosed bracket"}) (def err {:type :error :token origin :msg "unclosed bracket"})
(array/push (parser :errors) err) (array/push (parser :errors) err)
@ -403,7 +369,8 @@
) )
(capture nonbinding parser))) (capture nonbinding parser)))
(array/push (ast :data) term) (array/push (ast :data) term)
(capture separators parser)) (try (separators parser)
([e] (array/push (ast :data) e))))
(advance parser) (advance parser)
ast) ast)
@ -411,10 +378,8 @@
(def origin (current parser)) (def origin (current parser))
(advance parser) (advance parser)
(def ast {:type :set :data @[] :token origin}) (def ast {:type :set :data @[] :token origin})
(while (separates? parser) (advance parser))
(while (not (check parser :rbrace)) (while (not (check parser :rbrace))
(accept-many parser :newline :comma)
(when (= :break ((current parser) :type))
(break (advance parser)))
(when (check parser :eof) (when (check parser :eof)
(def err {:type :error :token origin :msg "unclosed brace"}) (def err {:type :error :token origin :msg "unclosed brace"})
(array/push (parser :errors) err) (array/push (parser :errors) err)
@ -428,7 +393,8 @@
) )
(capture nonbinding parser))) (capture nonbinding parser)))
(array/push (ast :data) term) (array/push (ast :data) term)
(capture separators parser)) (try (separators parser)
([e] (array/push (ast :data) e))))
(advance parser) (advance parser)
ast) ast)
@ -436,10 +402,8 @@
(def origin (current parser)) (def origin (current parser))
(advance parser) (advance parser)
(def ast {:type :dict :data @[] :token origin}) (def ast {:type :dict :data @[] :token origin})
(while (separates? parser) (advance parser))
(while (not (check parser :rbrace)) (while (not (check parser :rbrace))
(accept-many parser :newline :comma)
(when (= :break ((current parser) :type))
(break (advance parser)))
(when (check parser :eof) (when (check parser :eof)
(def err {:type :error :token origin :msg "unclosed brace"}) (def err {:type :error :token origin :msg "unclosed brace"})
(array/push (parser :errors) err) (array/push (parser :errors) err)
@ -459,7 +423,7 @@
(try (panic parser (string "expected dict term, got " (type origin))) ([e] e)) (try (panic parser (string "expected dict term, got " (type origin))) ([e] e))
)) ))
(array/push (ast :data) term) (array/push (ast :data) term)
(capture separators parser)) (try (separators parser) ([e] (array/push (ast :data) e))))
(advance parser) (advance parser)
ast) ast)
@ -488,10 +452,8 @@
(def origin (current parser)) (def origin (current parser))
(advance parser) # consume the :lparen (advance parser) # consume the :lparen
(def ast {:type :tuple :data @[] :token origin}) (def ast {:type :tuple :data @[] :token origin})
(while (separates? parser) (advance parser)) # consume any separators
(while (not (check parser :rparen)) (while (not (check parser :rparen))
(accept-many parser :newline :comma)
(when (= :break ((current parser) :type))
(break (advance parser)))
(when (check parser :eof) (when (check parser :eof)
(def err {:type :error :token origin :msg "unclosed paren"}) (def err {:type :error :token origin :msg "unclosed paren"})
(array/push (parser :errors) err) (array/push (parser :errors) err)
@ -504,7 +466,8 @@
{:type :splat :data splatted :token origin}) {:type :splat :data splatted :token origin})
(capture pattern parser))) (capture pattern parser)))
(array/push (ast :data) term) (array/push (ast :data) term)
(capture separators parser)) (try (separators parser)
([e] (array/push (ast :data) e))))
(advance parser) (advance parser)
ast) ast)
@ -512,10 +475,8 @@
(def origin (current parser)) (def origin (current parser))
(advance parser) (advance parser)
(def ast {:type :list :data @[] :token origin}) (def ast {:type :list :data @[] :token origin})
(while (separates? parser) (advance parser))
(while (not (check parser :rbracket)) (while (not (check parser :rbracket))
(accept-many parser :newline :comma)
(when (= :break ((current parser) :type))
(break (advance parser)))
(when (check parser :eof) (when (check parser :eof)
(def err {:type :error :token origin :msg "unclosed bracket"}) (def err {:type :error :token origin :msg "unclosed bracket"})
(array/push (parser :errors) err) (array/push (parser :errors) err)
@ -528,7 +489,8 @@
{:type :splat :data splatted :token origin}) {:type :splat :data splatted :token origin})
(capture pattern parser))) (capture pattern parser)))
(array/push (ast :data) term) (array/push (ast :data) term)
(capture separators parser)) (try (separators parser)
([e] (array/push (ast :data) e))))
(advance parser) (advance parser)
ast) ast)
@ -536,10 +498,8 @@
(def origin (current parser)) (def origin (current parser))
(advance parser) (advance parser)
(def ast {:type :dict :data @[] :token origin}) (def ast {:type :dict :data @[] :token origin})
(while (separates? parser) (advance parser))
(while (not (check parser :rbrace)) (while (not (check parser :rbrace))
(accept-many parser :newline :comma)
(when (= :break ((current parser) :type))
(break (advance parser)))
(when (check parser :eof) (when (check parser :eof)
(def err {:type :error :token origin :msg "unclosed brace"}) (def err {:type :error :token origin :msg "unclosed brace"})
(array/push (parser :errors) err) (array/push (parser :errors) err)
@ -559,7 +519,7 @@
(try (panic parser (string "expected dict term, got " (type origin))) ([e] e)) (try (panic parser (string "expected dict term, got " (type origin))) ([e] e))
)) ))
(array/push (ast :data) term) (array/push (ast :data) term)
(capture separators parser)) (try (separators parser) ([e] (array/push (ast :data) e))))
(advance parser) (advance parser)
ast) ast)
@ -600,25 +560,22 @@
(defn- iff [parser] (defn- iff [parser]
(def ast {:type :if :data @[] :token (current parser)}) (def ast {:type :if :data @[] :token (current parser)})
(advance parser) #consume the if (advance parser) #consume the if
(array/push (ast :data) (simple parser)) (array/push (ast :data) (capture simple parser))
(accept-many parser :newline) (accept-many parser :newline)
(if-let [err (expect-ret parser :then)] (if-let [err (expect-ret parser :then)]
(array/push (ast :data) err) (array/push (ast :data) err)
(advance parser)) (advance parser))
(array/push (ast :data) (nonbinding parser)) (array/push (ast :data) (capture nonbinding parser))
(accept-many parser :newline) (accept-many parser :newline)
(if-let [err (expect-ret parser :else)] (if-let [err (expect-ret parser :else)]
(array/push (ast :data) err) (array/push (ast :data) err)
(advance parser)) (advance parser))
(array/push (ast :data) (nonbinding parser)) (array/push (ast :data) (capture nonbinding parser))
ast) ast)
(defn- literal-terminator? [token]
(def tok-type (token :type))
(or (= :newline tok-type) (= :semicolon tok-type)))
(defn- terminator [parser] (defn- terminator [parser]
(if-not (terminates? parser) (if-not (terminates? parser)
# this line panics, captures the panic, advances the parser, and re-throws the error; solves an off-by-one error
(panic parser "expected terminator")) (panic parser "expected terminator"))
(advance parser) (advance parser)
(while (terminates? parser) (advance parser))) (while (terminates? parser) (advance parser)))
@ -841,15 +798,13 @@
(defn- block [parser] (defn- block [parser]
(def origin (current parser)) (def origin (current parser))
(expect parser :lbrace) (advance parser) (expect parser :lbrace) (advance parser)
(accept-many parser ;terminators)
(def data @[]) (def data @[])
(while (not (check parser :rbrace)) (while (not (check parser :rbrace))
(accept-many parser :newline :semicolon)
(when (= :break ((current parser) :type))
(break (advance parser)))
(if (check parser :eof) (if (check parser :eof)
(error {:type :error :token origin :data data :msg "unclosed brace"})) (error {:type :error :token origin :data data :msg "unclosed brace"}))
(array/push data (capture expr parser)) (array/push data (capture expr parser))
(capture terminator parser)) (terminator parser))
(advance parser) (advance parser)
{:type :block :data data :token origin}) {:type :block :data data :token origin})
@ -871,16 +826,16 @@
(array/push data (capture simple parser))) (array/push data (capture simple parser)))
{:type :do :data data :token origin}) {:type :do :data data :token origin})
### boxs, pkgs, nses, etc. ### refs, pkgs, nses, etc.
(defn- box [parser] (defn- ref [parser]
(def origin (current parser)) (def origin (current parser))
(expect parser :box) (advance parser) (expect parser :ref) (advance parser)
(try (try
(do (do
(def name (-> parser word-only (get :data))) (def name (-> parser word-only (get :data)))
(expect parser :equals) (advance parser) (expect parser :equals) (advance parser)
(def value (nonbinding parser)) (def value (nonbinding parser))
{:type :box :data value :name name :token origin}) {:type :ref :data value :name name :token origin})
([err] err))) ([err] err)))
(defn- pkg-name [parser] (defn- pkg-name [parser]
@ -1011,7 +966,7 @@
### expressions ### expressions
# four levels of expression complexity: # four levels of expression complexity:
# simple (atoms, collections, synthetic expressions; no conditionals or binding or blocks) # simple (atoms, collections, synthetic expressions; no conditionals or binding or blocks)
# nonbinding (excludes let, box, named fn: what is allowed inside collections) # nonbinding (excludes let, ref, named fn: what is allowed inside collections)
# plain old exprs (anything but toplevel) # plain old exprs (anything but toplevel)
# toplevel (exprs + ns, pkg, test, import, use) # toplevel (exprs + ns, pkg, test, import, use)
@ -1099,7 +1054,7 @@
# binding forms # binding forms
:let (lett parser) :let (lett parser)
:fn (fnn parser) :fn (fnn parser)
:box (box parser) :ref (ref parser)
# nonbinding forms # nonbinding forms
:nil (nill parser) :nil (nill parser)
@ -1148,12 +1103,8 @@
(def origin (current parser)) (def origin (current parser))
(def lines @[]) (def lines @[])
(while (not (check parser :eof)) (while (not (check parser :eof))
# (print "starting script loop with " (pp-tok origin)) (accept-many parser :newline)
(accept-many parser :newline :semicolon) (array/push lines (capture toplevel parser))
(when (= :break ((current parser) :type))
(break (advance parser)))
(def term (capture toplevel parser))
(array/push lines term)
(capture terminator parser)) (capture terminator parser))
{:type :script :data lines :token origin}) {:type :script :data lines :token origin})
@ -1165,17 +1116,10 @@
# (do # (do
(comment (comment
(def source ` (def source `...
{
foo bar
quux frobulate
baz
12 23 42
}
`) `)
(def scanned (s/scan source)) (def scanned (s/scan source))
# (print "\n***NEW PARSE***\n") # (print "\n***NEW PARSE***\n")
(def parsed (parse scanned)) (def a-parser (new-parser scanned))
(pp (map (fn [err] (err :msg)) (parsed :errors))) (def parsed (splat a-parser))
(print (pp-ast (parsed :ast)))
) )

View File

@ -1,9 +1,8 @@
(def reserved-words (def reserved-words
"List of Ludus reserved words." "List of Ludus reserved words."
## see ludus-spec repo for more info ## see ludus-spec repo for more info
{ {"as" :as ## impl
"as" :as ## impl "box" :ref
"box" :box
"do" :do ## impl "do" :do ## impl
"else" :else ## impl "else" :else ## impl
"false" :false ## impl -> literal word "false" :false ## impl -> literal word
@ -17,15 +16,15 @@
"ns" :ns ## impl "ns" :ns ## impl
"panic!" :panic ## impl (should _not_ be a function) "panic!" :panic ## impl (should _not_ be a function)
"pkg" :pkg "pkg" :pkg
"recur" :recur ## impl "recur" :recur ## impl
"repeat" :repeat ## impl
"test" :test
"then" :then ## impl "then" :then ## impl
"true" :true ## impl -> literal word "true" :true ## impl -> literal word
"use" :use ## wip "use" :use ## wip
"with" :with ## impl
"when" :when ## impl, replaces cond "when" :when ## impl, replaces cond
"with" :with ## impl "repeat" :repeat ## syntax sugar over "loop": still unclear what this syntax could be
}) "test" :test
})
(def literal-words {"true" true (def literal-words {"true" true
"false" false "false" false
@ -155,7 +154,7 @@
:start (get scanner :start) :start (get scanner :start)
:source (get scanner :source) :source (get scanner :source)
:input (get scanner :input) :input (get scanner :input)
:msg msg}] :message msg}]
(-> scanner (-> scanner
(update :errors array/push token) (update :errors array/push token)
(update :tokens array/push token)))) (update :tokens array/push token))))
@ -195,15 +194,6 @@
:else (add-error scanner (string "Unexpected " curr " after number " num "."))))) :else (add-error scanner (string "Unexpected " curr " after number " num ".")))))
(recur scanner (buffer char) false)) (recur scanner (buffer char) false))
(def escape {
"\"" "\""
"n" "\n"
"{" "{"
"t" "\t"
"r" "\r"
"\\" "\\"
})
(defn- add-string (defn- add-string
[scanner] [scanner]
(defn recur [scanner buff interpolate?] (defn recur [scanner buff interpolate?]
@ -212,12 +202,14 @@
"{" (recur (advance scanner) (buffer/push buff char) true) "{" (recur (advance scanner) (buffer/push buff char) true)
# allow multiline strings # allow multiline strings
"\n" (recur (update (advance scanner) :line inc) (buffer/push buff char) interpolate?) "\n" (recur (update (advance scanner) :line inc) (buffer/push buff char) interpolate?)
"\"" (add-token (advance scanner) (if interpolate? :interpolated :string) (string buff)) "\"" (add-token (advance scanner) (if interpolate? :interpolated :string)(string buff))
"\\" (let [next (next-char scanner)] "\\" (let [next (next-char scanner)]
(recur (if (= next "{")
(advance (advance scanner)) (do
(buffer/push buff (get escape next next)) (buffer/push buff char)
interpolate?)) (buffer/push buff next)
(recur (advance (advance scanner)) buff interpolate?))
(recur (advance scanner) (buffer/push buff char) interpolate?)))
(if (at-end? scanner) (if (at-end? scanner)
(add-error scanner "Unterminated string.") (add-error scanner "Unterminated string.")
(recur (advance scanner) (buffer/push buff char) interpolate?))))) (recur (advance scanner) (buffer/push buff char) interpolate?)))))
@ -349,8 +341,3 @@
(recur (-> scanner (scan-token) (next-token))))) (recur (-> scanner (scan-token) (next-token)))))
(recur (new-scanner source input))) (recur (new-scanner source input)))
(comment
# (do
(def source "add 1 2 () four")
(scan source)
)

View File

@ -74,10 +74,6 @@ Deferred until a later iteration of Ludus:
(defn- block [validator] (defn- block [validator]
(def ast (validator :ast)) (def ast (validator :ast))
(def data (ast :data)) (def data (ast :data))
(when (= 0 (length data))
(array/push (validator :errors)
{:node ast :msg "blocks may not be empty"})
(break validator))
(def status (validator :status)) (def status (validator :status))
(set (status :toplevel) nil) (set (status :toplevel) nil)
(def tail? (status :tail)) (def tail? (status :tail))
@ -102,11 +98,6 @@ Deferred until a later iteration of Ludus:
(def node (get ctx name)) (def node (get ctx name))
(if node node (resolve-name (get ctx :^parent) name))) (if node node (resolve-name (get ctx :^parent) name)))
(defn- resolve-name-in-script [ctx name]
(when (ctx :^toplevel) (break nil))
(def node (ctx name))
(if node node (resolve-name-in-script (ctx :^parent) name)))
(defn- word [validator] (defn- word [validator]
(def ast (validator :ast)) (def ast (validator :ast))
(def name (ast :data)) (def name (ast :data))
@ -162,12 +153,10 @@ Deferred until a later iteration of Ludus:
(def ast (validator :ast)) (def ast (validator :ast))
(def name (ast :data)) (def name (ast :data))
(def ctx (validator :ctx)) (def ctx (validator :ctx))
### XXX TODO: this resolution should ONLY be for userspace, NOT prelude (when (has-key? ctx name)
(def resolved (resolve-name-in-script ctx name)) (def {:line line :input input} (get-in ctx [name :token]))
(when resolved
(def {:line line :input input} resolved)
(array/push (validator :errors) (array/push (validator :errors)
{:node ast :msg (string "name " name " is already bound on line " {:node ast :msg (string "name is already bound on line "
line " of " input)})) line " of " input)}))
(set (ctx name) ast) (set (ctx name) ast)
# (pp ctx) # (pp ctx)
@ -343,7 +332,7 @@ Deferred until a later iteration of Ludus:
(set (ast :arities) arities) (set (ast :arities) arities)
validator) validator)
(defn- box [validator] (defn- ref [validator]
(def ast (validator :ast)) (def ast (validator :ast))
(def ctx (validator :ctx)) (def ctx (validator :ctx))
(def expr (ast :data)) (def expr (ast :data))
@ -442,12 +431,12 @@ Deferred until a later iteration of Ludus:
(def rest-arities (keys (arities :rest))) (def rest-arities (keys (arities :rest)))
(when (empty? rest-arities) (when (empty? rest-arities)
(array/push (validator :errors) (array/push (validator :errors)
{:node ast :msg "wrong number of arguments"}) {:node ast :msg "mismatched arity"})
(break validator)) (break validator))
(def rest-min (min ;rest-arities)) (def rest-min (min ;rest-arities))
(when (< num-args rest-min) (when (< num-args rest-min)
(array/push (validator :errors) (array/push (validator :errors)
{:node ast :msg "wrong number of arguments"})) {:node ast :msg "mismatched arity"}))
validator) validator)
(defn- kw-root [validator] (defn- kw-root [validator]
@ -757,7 +746,7 @@ Deferred until a later iteration of Ludus:
:use (usee validator) :use (usee validator)
:loop (loopp validator) :loop (loopp validator)
:recur (recur validator) :recur (recur validator)
:box (box validator) :ref (ref validator)
(error (string "unknown node type " type))))) (error (string "unknown node type " type)))))
(set validate validate*) (set validate validate*)
@ -771,7 +760,6 @@ Deferred until a later iteration of Ludus:
(defn valid [ast &opt ctx] (defn valid [ast &opt ctx]
(default ctx @{}) (default ctx @{})
(set (ctx :^toplevel) true)
(def validator (new-validator ast)) (def validator (new-validator ast))
(def base-ctx @{:^parent ctx}) (def base-ctx @{:^parent ctx})
(set (validator :ctx) base-ctx) (set (validator :ctx) base-ctx)

View File

@ -1,81 +0,0 @@
# Turtle Graphics protocol
name: "turtle-graphics"
version: 0.1.0
### Description
Turtle graphics describe the movements and drawing behaviours of screen, robot, and print "turtles."
* `proto`: `["turtle-graphics", "{version number}"]`
* `data`: an array of arrays; each array represents a turtle command; the first element of a command array is the verb; any subsequent items are the arguments to the verbs.
* Valid arguments are numbers, strings, and booleans.
* Depending on what we end up doing, we may add arrays of these, representing tuples or lists, and/or objects with string keys whose text are well-formed keywords in Ludus. For now, however, arguments must be atomic values.
* E.g., `["forward", 100]`
* Each turtle has its own stream.
* At current, this protocol describes the behaviour of turtle-like objects, all of which "live" in the same "world"; there is not yet a provision for multiple canvases/worlds. That said, an additional field for "world" in at the top level may well be added in the future to allow for multiple worlds to unfold at the same time.
### Verbs and arguments
* `forward`, steps: number
- Moves the turtle forward by the number of steps/pixels.
* `back`, steps: number
- Moves the turtle backwards by the number of steps/pixels.
* `right`, turns: number
- Turns the turtle right by the number of turns. (1 turn = 360 degrees.)
* `left`, turns: number
- Turns the turtle to the left by the number of turns. (1 turn = 360 degrees.)
* `penup`, no arguments
- "Lifts" the turtle's pen, keeping it from drawing.
* `pendown`, no arguments
- "Lowers" the turtle's pen, starting it drawing a path.
* `pencolor`, red: number, green: number, blue: number, alpha: number, OR: color: string
- Sets the turtle's pen's color to the specified RGBA color.
* `penwidth`, width: number
- Sets the width of the turtle's pen, in pixels (or some other metric).
* `home`, no arguments
- Sends the turtle back to its starting point, with a heading of 0.
* `goto`, x: number, y: number
- Sends the turtle to the specified Cartesian coordinates, where the origin is the turtle's starting position.
* `setheading`, heading: number
- Sets the turtle's heading. 0 is the turtle's starting heading, with increasing numbers turning to the right.
* `show`, no arguments
- Shows the turtle.
* `hide`, no arguments
- Hides the turtle.
* `loadstate`, x: number, y: number, heading: number, pendown: boolean, width: number, color: string OR r: number, g: number, b: number, a: number
- Loads a turtle state.
* `clear`, no arguments
- Erases any paths drawn and sets the background color to the default.
* `background`, red: number, green: number, blue: number, alpha: number
- Sets the background color to the specified RGBA color, OR: color: string
These last two feel a little weird to me, since the background color is more the property of the **world** the turtle is in, not the turtle itself. Worlds with multiple turtles will be set up so that _any_ turtle will be able to change the background, and erase all paths.
That said, since we don't yet have a world abstraction/entity, then there's no other place to put them. This will likely be shifted around in later versions of the protocol.
### Other considerations
**Not all turtles will know how to do all these things.**
The idea is that this single abstraction will talk to all the turtle-like things we eventually use.
That means that some turtles won't be able to do all the things; that's fine!
They just won't do things they can't do; but warnings should go to `stderr`.
**Errors are not passed back to Ludus.**
These are fire-off commands.
Errors should be _reported_ to `stderr` or equivalent.
But Ludus sending things to its output streams should only cause Ludus panics when there's an issue in Ludus.
**Colors aren't always RGBA.**
For pen-and-paper turtles, we don't have RGBA colors.
Colors should also be specifiable with strings corresponding to CSS basic colors: black, silver, gray, white, maroon, red, purple, fuchsia, green, lime, olive, yellow, navy, blue, teal, and aqua.
**Turtles should communicate states.**
Ludus should have access to turtle states.
This is important for push/pop situations that we use for L-systems.
There are two ways to do this: Ludus does its own bookkeeping for turtle states, or it has a way to get the state from a turtle.
The latter has the value of being instantaneous, and gives us an _expected_ state of the turtle after the commands are all processed.
In particular, this will be necessary for the recursive L-systems that require pushing and popping turtle state.
The latter has the drawback of potentially allowing the turtle state and expected turtle state to fall out of synch.
The former has the value of always giving us the correct, actual state of the turtle.
It has the drawback of requiring such state reporting to be asynchronous, and perhaps wildly asynchronous, as things like moving robots and plotters will take quite some time to actually draw what Ludus tells it to.
(Being able to wait until `eq? (expected, actual)` to do anything else may well be extremely useful.)
That suggests, then, that both forms of turtle state are desirable and necessary.
Thus: turtles should communicate states (and thus there ought to be a protocol for communicating state back to Ludus) and Ludus should always do the bookkeeping of calculating the expected state.