Rename the language from Dino to Rex
Files use .rex, the command is rex, and the crate, runtime prefixes, docs, editor files and examples all use the new name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2f44f09b6a
commit
7cf9727bcd
94 files changed
+858
-858
No files matched your search
Generated
+1
-1
@@ -3,5 +3,5 @@
|
|||||||
version = 4
|
version = 4
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "dino"
|
name = "rex"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "dino"
|
name = "rex"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
description = "The Dino programming language compiler"
|
description = "The Rex programming language compiler"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="dino-logo.svg" alt="Dino, the mascot" width="420">
|
<img src="rex-logo.svg" alt="Rex, the mascot" width="420">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<h1 align="center">Dino</h1>
|
<h1 align="center">Rex</h1>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
A small, fast language. It looks like Go, runs like C, and you never write anything low-level.
|
A small, fast language. It looks like Go, runs like C, and you never write anything low-level.
|
||||||
@@ -10,10 +10,10 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
Dino compiles to C and then to a native program. There is no garbage collector, no pointers
|
Rex compiles to C and then to a native program. There is no garbage collector, no pointers
|
||||||
and no manual memory: you write plain code and the compiler works out the rest.
|
and no manual memory: you write plain code and the compiler works out the rest.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
enum Shape {
|
enum Shape {
|
||||||
Circle(r: float)
|
Circle(r: float)
|
||||||
Rect(w, h: float)
|
Rect(w, h: float)
|
||||||
@@ -52,7 +52,7 @@ func main() {
|
|||||||
error: age cannot be negative
|
error: age cannot be negative
|
||||||
```
|
```
|
||||||
|
|
||||||
## Why Dino
|
## Why Rex
|
||||||
|
|
||||||
- **Simple syntax.** `var`, `func`, `for`, `match`. One loop keyword, no semicolons, no
|
- **Simple syntax.** `var`, `func`, `for`, `match`. One loop keyword, no semicolons, no
|
||||||
parentheses around conditions. Types are inferred.
|
parentheses around conditions. Types are inferred.
|
||||||
@@ -63,42 +63,42 @@ error: age cannot be negative
|
|||||||
missing is `T?`. Both must be handled.
|
missing is `T?`. Both must be handled.
|
||||||
- **Modern basics.** Enums that carry data, exhaustive `match`, generics, interfaces,
|
- **Modern basics.** Enums that carry data, exhaustive `match`, generics, interfaces,
|
||||||
closures, maps, characters, modules.
|
closures, maps, characters, modules.
|
||||||
- **C and C++ libraries.** `import "raylib.h"` and call it: Dino reads the header itself,
|
- **C and C++ libraries.** `import "raylib.h"` and call it: Rex reads the header itself,
|
||||||
links the library, and builds your own `.c`/`.cpp` files next to the program.
|
links the library, and builds your own `.c`/`.cpp` files next to the program.
|
||||||
- **Tooling included.** A formatter, a language server, and editor files, all in the one `dino`
|
- **Tooling included.** A formatter, a language server, and editor files, all in the one `rex`
|
||||||
program.
|
program.
|
||||||
|
|
||||||
## Get started
|
## Get started
|
||||||
|
|
||||||
You need a [Rust toolchain](https://rustup.rs) to build the compiler and a C compiler
|
You need a [Rust toolchain](https://rustup.rs) to build the compiler and a C compiler
|
||||||
(`gcc` or `clang`, available as `cc`) to build your programs. Dino itself has no dependencies.
|
(`gcc` or `clang`, available as `cc`) to build your programs. Rex itself has no dependencies.
|
||||||
|
|
||||||
```text
|
```text
|
||||||
cargo build --release
|
cargo build --release
|
||||||
cp target/release/dino ~/.local/bin/ # or anywhere on your PATH
|
cp target/release/rex ~/.local/bin/ # or anywhere on your PATH
|
||||||
```
|
```
|
||||||
|
|
||||||
Save this as `hello.dino`:
|
Save this as `hello.rex`:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
print("Hello, Dino!")
|
print("Hello, Rex!")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```text
|
```text
|
||||||
dino run hello.dino
|
rex run hello.rex
|
||||||
```
|
```
|
||||||
|
|
||||||
| Command | What it does |
|
| Command | What it does |
|
||||||
|---------|--------------|
|
|---------|--------------|
|
||||||
| `dino run file.dino [args...]` | Compile and run. Extra words reach the program as `os.args`. |
|
| `rex run file.rex [args...]` | Compile and run. Extra words reach the program as `os.args`. |
|
||||||
| `dino build file.dino -o out` | Make an executable you can keep. |
|
| `rex build file.rex -o out` | Make an executable you can keep. |
|
||||||
| `dino check file.dino` | Look for errors without building. |
|
| `rex check file.rex` | Look for errors without building. |
|
||||||
| `dino emit-c file.dino` | Print the generated C. |
|
| `rex emit-c file.rex` | Print the generated C. |
|
||||||
| `dino fmt [--check] path...` | Format code (`--check` only reports). |
|
| `rex fmt [--check] path...` | Format code (`--check` only reports). |
|
||||||
| `dino lsp` | Start the language server (editors run this for you). |
|
| `rex lsp` | Start the language server (editors run this for you). |
|
||||||
| `dino header file.h [word]` | Show what Dino can use from a C header. |
|
| `rex header file.h [word]` | Show what Rex can use from a C header. |
|
||||||
|
|
||||||
## Learn the language
|
## Learn the language
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Dino language spec (draft)
|
# Rex language spec (draft)
|
||||||
|
|
||||||
Goal: Go-like simplicity, C++/Rust speed, no GC, no low-level syntax.
|
Goal: Go-like simplicity, C++/Rust speed, no GC, no low-level syntax.
|
||||||
Targets: game dev, CLI tools, desktop apps.
|
Targets: game dev, CLI tools, desktop apps.
|
||||||
@@ -160,8 +160,8 @@ Targets: game dev, CLI tools, desktop apps.
|
|||||||
passing lists around costs nothing. Every test program runs under the address
|
passing lists around costs nothing. Every test program runs under the address
|
||||||
sanitizer, so a leak, double free or use after free fails the test.
|
sanitizer, so a leak, double free or use after free fails the test.
|
||||||
|
|
||||||
- **Imports**: `import os` (built-in) or `import utils` (the file `utils.dino` next to the
|
- **Imports**: `import os` (built-in) or `import utils` (the file `utils.rex` next to the
|
||||||
main file; `import tools.fs` is `tools/fs.dino`, used as `fs.name`). Use things as
|
main file; `import tools.fs` is `tools/fs.rex`, used as `fs.name`). Use things as
|
||||||
`utils.double(2)`, `utils.Vec2{1.0, 2.0}`, `utils.Shape.Circle(1.0)`, `utils.SCALE`,
|
`utils.double(2)`, `utils.Vec2{1.0, 2.0}`, `utils.Shape.Circle(1.0)`, `utils.SCALE`,
|
||||||
and `utils.Vec2` in types. Only `pub` functions, consts, types, methods and fields can be used
|
and `utils.Vec2` in types. Only `pub` functions, consts, types, methods and fields can be used
|
||||||
from another file (fields are private too unless written `pub x: int`). Each file has its own imports and its
|
from another file (fields are private too unless written `pub x: int`). Each file has its own imports and its
|
||||||
@@ -185,12 +185,12 @@ Targets: game dev, CLI tools, desktop apps.
|
|||||||
invalid UTF-8 comes out as U+FFFD). `s[i]` is the character starting at byte `i` (panics out of range or
|
invalid UTF-8 comes out as U+FFFD). `s[i]` is the character starting at byte `i` (panics out of range or
|
||||||
in the middle of a character); strings can't be assigned to. Methods `is_digit is_letter is_alnum is_space
|
in the middle of a character); strings can't be assigned to. Methods `is_digit is_letter is_alnum is_space
|
||||||
is_upper is_lower upper lower` (ASCII plus Latin-1 letters). `s.chars()` gives a `[]char`. Not yet: `[]char`→string.
|
is_upper is_lower upper lower` (ASCII plus Latin-1 letters). `s.chars()` gives a `[]char`. Not yet: `[]char`→string.
|
||||||
- **Formatter** `dino fmt [--check] <file|folder>..` (`src/fmt.rs`): text based, so comments and blank lines survive.
|
- **Formatter** `rex fmt [--check] <file|folder>..` (`src/fmt.rs`): text based, so comments and blank lines survive.
|
||||||
4-space indent, spaces around binary operators and after `,` `:`, tight `Point{...}` / map literals and `[]T`,
|
4-space indent, spaces around binary operators and after `,` `:`, tight `Point{...}` / map literals and `[]T`,
|
||||||
at most one blank line, trailing `//` comments of neighbouring lines aligned. It never moves line breaks (a one-line
|
at most one blank line, trailing `//` comments of neighbouring lines aligned. It never moves line breaks (a one-line
|
||||||
block stays one line), indents continuation lines (after an operator, or inside open brackets) one level, and
|
block stays one line), indents continuation lines (after an operator, or inside open brackets) one level, and
|
||||||
verifies that the token stream is unchanged before writing. `examples/` must stay formatted (a test checks).
|
verifies that the token stream is unchanged before writing. `examples/` must stay formatted (a test checks).
|
||||||
- **Editor support** (`editors/`): `dino lsp` is a language server (`src/lsp.rs`, own JSON in `src/json.rs`, no
|
- **Editor support** (`editors/`): `rex lsp` is a language server (`src/lsp.rs`, own JSON in `src/json.rs`, no
|
||||||
dependencies): full-text sync, error diagnostics from the real checker (imports read from disk or from open
|
dependencies): full-text sync, error diagnostics from the real checker (imports read from disk or from open
|
||||||
buffers; errors in other files shown at the top of the importing file; UTF-16 columns), whole-file formatting.
|
buffers; errors in other files shown at the top of the importing file; UTF-16 columns), whole-file formatting.
|
||||||
`editors/vscode` (extension + TextMate grammar), `editors/vim` (syntax), `editors/README.md` (Neovim, Helix, others).
|
`editors/vscode` (extension + TextMate grammar), `editors/vim` (syntax), `editors/README.md` (Neovim, Helix, others).
|
||||||
@@ -204,16 +204,16 @@ Targets: game dev, CLI tools, desktop apps.
|
|||||||
guessed from the header path, else `import "x.h" link "x"` (`-lx`). A header next to the program adds `-I` and
|
guessed from the header path, else `import "x.h" link "x"` (`-lx`). A header next to the program adds `-I` and
|
||||||
builds the `.c`/`.cpp`/`.cc` file with the same name into the program (C++ with `c++`, linked with `-lstdc++`).
|
builds the `.c`/`.cpp`/`.cc` file with the same name into the program (C++ with `c++`, linked with `-lstdc++`).
|
||||||
Types: C ints -> sized numbers (`int` i32, `long` int, `size_t` u64), `double` float, `char` i8 (takes `'a'`),
|
Types: C ints -> sized numbers (`int` i32, `long` int, `size_t` u64), `double` float, `char` i8 (takes `'a'`),
|
||||||
`char *` -> string (copied both ways, NULL -> ""), enums -> `i32` constants, plain structs -> Dino structs with the
|
`char *` -> string (copied both ways, NULL -> ""), enums -> `i32` constants, plain structs -> Rex structs with the
|
||||||
C field names (`raylib.Color`; converted field by field at calls), other pointers -> pointer types
|
C field names (`raylib.Color`; converted field by field at calls), other pointers -> pointer types
|
||||||
(`Ty::CPtr`, `stdio.FILE`, `nil` = NULL, `==` compares); `void *` (`pointer`) mixes with every pointer type.
|
(`Ty::CPtr`, `stdio.FILE`, `nil` = NULL, `==` compares); `void *` (`pointer`) mixes with every pointer type.
|
||||||
`T *` parameters take a variable (the address is passed; counts as a change for inferred mutation) or a list
|
`T *` parameters take a variable (the address is passed; counts as a change for inferred mutation) or a list
|
||||||
(its items); `const T *` also takes any value. Constants: numbers, strings, and struct literals like
|
(its items); `const T *` also takes any value. Constants: numbers, strings, and struct literals like
|
||||||
`CLITERAL(Color){...}` (emitted as the macro). Programs that import headers are built with `-std=gnu11`.
|
`CLITERAL(Color){...}` (emitted as the macro). Programs that import headers are built with `-std=gnu11`.
|
||||||
Not supported (a clear error when called): variadic functions, callbacks, unions/arrays by value, lists of
|
Not supported (a clear error when called): variadic functions, callbacks, unions/arrays by value, lists of
|
||||||
structs, `long double`, function-like macros. Dino never frees C memory. `dino header x.h [word]` lists what Dino sees.
|
structs, `long double`, function-like macros. Rex never frees C memory. `rex header x.h [word]` lists what Rex sees.
|
||||||
- **String slicing**: `s[a..b]`, `s[a..]`, `s[..b]` (byte positions, bounds checked; panics with "the length is N").
|
- **String slicing**: `s[a..b]`, `s[a..]`, `s[..b]` (byte positions, bounds checked; panics with "the length is N").
|
||||||
- **Running**: `dino run file.dino a b c` passes `a b c` to the program (`os.args`).
|
- **Running**: `rex run file.rex a b c` passes `a b c` to the program (`os.args`).
|
||||||
- **Example**: `examples/calc/` is a multi-file calculator (tokenizer, parser, evaluator, shared scope); `session.txt` / `session.out` are checked by a test.
|
- **Example**: `examples/calc/` is a multi-file calculator (tokenizer, parser, evaluator, shared scope); `session.txt` / `session.out` are checked by a test.
|
||||||
|
|
||||||
## Open questions
|
## Open questions
|
||||||
@@ -225,6 +225,6 @@ Working: functions, int/float/bool/string, var/const, if/else, for (infinite,
|
|||||||
while, range with step, over lists), break/continue, string interpolation, print,
|
while, range with step, over lists), break/continue, string interpolation, print,
|
||||||
structs with methods (value semantics, inferred mutation), lists (value
|
structs with methods (value semantics, inferred mutation), lists (value
|
||||||
semantics, bounds checked), enums with data + exhaustive match, errors (`error`,
|
semantics, bounds checked), enums with data + exhaustive match, errors (`error`,
|
||||||
multi-value returns, `?`), optionals (`T?`, `nil`, narrowing), `dino run`.
|
multi-value returns, `?`), optionals (`T?`, `nil`, narrowing), `rex run`.
|
||||||
Not yet: nested match patterns, `==` on lists/structs, top-level const lists. These give a clear "not supported yet" error.
|
Not yet: nested match patterns, `==` on lists/structs, top-level const lists. These give a clear "not supported yet" error.
|
||||||
Known gaps: memory is only freed on normal exits (a panic just ends the program).
|
Known gaps: memory is only freed on normal exits (a panic just ends the program).
|
||||||
+20
-20
@@ -2,40 +2,40 @@
|
|||||||
|
|
||||||
## Running a program
|
## Running a program
|
||||||
|
|
||||||
Save this as `hello.dino`:
|
Save this as `hello.rex`:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
print("Hello, Dino!")
|
print("Hello, Rex!")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
```text
|
```text
|
||||||
Hello, Dino!
|
Hello, Rex!
|
||||||
```
|
```
|
||||||
|
|
||||||
Every program starts at `func main()`. Run it from the project folder:
|
Every program starts at `func main()`. Run it from the project folder:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
cargo run -q -- run hello.dino
|
cargo run -q -- run hello.rex
|
||||||
```
|
```
|
||||||
|
|
||||||
The compiler turns your Dino code into C and builds it with your C compiler (`cc`, so you
|
The compiler turns your Rex code into C and builds it with your C compiler (`cc`, so you
|
||||||
need gcc or clang installed). If you build the `dino` binary once, the commands are:
|
need gcc or clang installed). If you build the `rex` binary once, the commands are:
|
||||||
|
|
||||||
| Command | What it does |
|
| Command | What it does |
|
||||||
|---------|--------------|
|
|---------|--------------|
|
||||||
| `dino run file.dino [args...]` | Compile and run. Extra words are given to the program (`os.args`). |
|
| `rex run file.rex [args...]` | Compile and run. Extra words are given to the program (`os.args`). |
|
||||||
| `dino build file.dino -o out` | Make an executable you can keep. |
|
| `rex build file.rex -o out` | Make an executable you can keep. |
|
||||||
| `dino check file.dino` | Look for errors without building. |
|
| `rex check file.rex` | Look for errors without building. |
|
||||||
| `dino emit-c file.dino` | Print the generated C. |
|
| `rex emit-c file.rex` | Print the generated C. |
|
||||||
| `dino fmt file-or-folder...` | Tidy the code in place (`--check` only reports). |
|
| `rex fmt file-or-folder...` | Tidy the code in place (`--check` only reports). |
|
||||||
|
|
||||||
## print
|
## print
|
||||||
|
|
||||||
`print` takes any number of values, separates them with spaces, and ends the line.
|
`print` takes any number of values, separates them with spaces, and ends the line.
|
||||||
It can print numbers, strings, lists, maps, structs, enums and more.
|
It can print numbers, strings, lists, maps, structs, enums and more.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
print("score:", 42, true)
|
print("score:", 42, true)
|
||||||
print([1, 2, 3])
|
print([1, 2, 3])
|
||||||
@@ -52,7 +52,7 @@ Notice that a float always shows a `.0` so you can tell `3.0` from `3`.
|
|||||||
|
|
||||||
## Comments
|
## Comments
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
// a comment runs to the end of the line
|
// a comment runs to the end of the line
|
||||||
func main() {
|
func main() {
|
||||||
print("hi") // so does this
|
print("hi") // so does this
|
||||||
@@ -64,7 +64,7 @@ hi
|
|||||||
|
|
||||||
## Reading the error messages
|
## Reading the error messages
|
||||||
|
|
||||||
Dino tries hard to explain mistakes. For example, forgetting that `int` and `float`
|
Rex tries hard to explain mistakes. For example, forgetting that `int` and `float`
|
||||||
don't mix:
|
don't mix:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@@ -79,16 +79,16 @@ message and worth fixing.
|
|||||||
`editors/` has colours, live error underlines and format-on-save for VS Code, Neovim, Vim and
|
`editors/` has colours, live error underlines and format-on-save for VS Code, Neovim, Vim and
|
||||||
Helix (any editor that can run a language server works). See `editors/README.md`. It is the
|
Helix (any editor that can run a language server works). See `editors/README.md`. It is the
|
||||||
compiler itself doing the checking, so you see the same messages as in the terminal. The
|
compiler itself doing the checking, so you see the same messages as in the terminal. The
|
||||||
server is started with `dino lsp`.
|
server is started with `rex lsp`.
|
||||||
|
|
||||||
## Formatting your code
|
## Formatting your code
|
||||||
|
|
||||||
`dino fmt` rewrites your files in one standard style, so you never argue about spaces:
|
`rex fmt` rewrites your files in one standard style, so you never argue about spaces:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
dino fmt hello.dino # one file
|
rex fmt hello.rex # one file
|
||||||
dino fmt src/ # every .dino file in a folder
|
rex fmt src/ # every .rex file in a folder
|
||||||
dino fmt --check src/ # change nothing; exit code 1 if something is untidy
|
rex fmt --check src/ # change nothing; exit code 1 if something is untidy
|
||||||
```
|
```
|
||||||
|
|
||||||
It uses 4-space indents, one space around operators, `a: int` colons, `Point{x: 1}` literals,
|
It uses 4-space indents, one space around operators, `a: int` colons, `Point{x: 1}` literals,
|
||||||
|
|||||||
+11
-11
@@ -4,27 +4,27 @@
|
|||||||
|
|
||||||
`var` makes a variable you can change. The type is worked out from the value.
|
`var` makes a variable you can change. The type is worked out from the value.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var score = 10
|
var score = 10
|
||||||
score = score + 5
|
score = score + 5
|
||||||
score += 1
|
score += 1
|
||||||
print(score)
|
print(score)
|
||||||
|
|
||||||
var name: string = "Dino" // you may write the type after a colon
|
var name: string = "Rex" // you may write the type after a colon
|
||||||
var ratio: float = 1 // a whole-number literal fits a float
|
var ratio: float = 1 // a whole-number literal fits a float
|
||||||
print(name, ratio)
|
print(name, ratio)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
```text
|
```text
|
||||||
16
|
16
|
||||||
Dino 1.0
|
Rex 1.0
|
||||||
```
|
```
|
||||||
|
|
||||||
`const` is a value that never changes. It must be known when the program is compiled
|
`const` is a value that never changes. It must be known when the program is compiled
|
||||||
(you can't call functions in it).
|
(you can't call functions in it).
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
const MAX = 100
|
const MAX = 100
|
||||||
const GREETING = "hi"
|
const GREETING = "hi"
|
||||||
|
|
||||||
@@ -53,7 +53,7 @@ func main() {
|
|||||||
Sized numbers exist for when you need exact control: `i8 i16 i32 u8 u16 u32 u64 f32`
|
Sized numbers exist for when you need exact control: `i8 i16 i32 u8 u16 u32 u64 f32`
|
||||||
(`i64` is the same as `int`, `f64` the same as `float`).
|
(`i64` is the same as `int`, `f64` the same as `float`).
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var small: u8 = 200
|
var small: u8 = 200
|
||||||
var wrapped = small + 100 // whole numbers wrap around: 300 - 256
|
var wrapped = small + 100 // whole numbers wrap around: 300 - 256
|
||||||
@@ -82,7 +82,7 @@ Rules worth remembering:
|
|||||||
|
|
||||||
Put values inside text with `{ }`. Write a literal brace as `\{`.
|
Put values inside text with `{ }`. Write a literal brace as `\{`.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var name = "Ada"
|
var name = "Ada"
|
||||||
var age = 36
|
var age = 36
|
||||||
@@ -106,7 +106,7 @@ starts_with ends_with index_of to_int to_float`. See the [cheatsheet](11-cheatsh
|
|||||||
|
|
||||||
`s[a..b]` is the part from byte `a` up to (not including) `b`. Leave a side out to go to the edge.
|
`s[a..b]` is the part from byte `a` up to (not including) `b`. Leave a side out to go to the edge.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var s = "hello world"
|
var s = "hello world"
|
||||||
print(s[0..5])
|
print(s[0..5])
|
||||||
@@ -127,7 +127,7 @@ A slice outside the string stops the program with a message that shows the lengt
|
|||||||
|
|
||||||
A `char` is **one character**, written with single quotes. Double quotes are for text.
|
A `char` is **one character**, written with single quotes. Double quotes are for text.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var c = 'a'
|
var c = 'a'
|
||||||
print(c, c == 'a', c < 'b')
|
print(c, c == 'a', c < 'b')
|
||||||
@@ -145,7 +145,7 @@ a!
|
|||||||
|
|
||||||
Going through a string gives characters:
|
Going through a string gives characters:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var s = "héllo 42"
|
var s = "héllo 42"
|
||||||
var letters = 0
|
var letters = 0
|
||||||
@@ -181,7 +181,7 @@ h é l
|
|||||||
- `char` can be compared (`== != < > <= >=`), matched with `match`, and used as a map key.
|
- `char` can be compared (`== != < > <= >=`), matched with `match`, and used as a map key.
|
||||||
It does no arithmetic: use `int(c)` and `char(n)` if you need that.
|
It does no arithmetic: use `int(c)` and `char(n)` if you need that.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func kind(c: char): string {
|
func kind(c: char): string {
|
||||||
return match c {
|
return match c {
|
||||||
'+' => "plus"
|
'+' => "plus"
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
No parentheses around the condition. The braces are required. The condition must be a `bool`.
|
No parentheses around the condition. The braces are required. The condition must be a `bool`.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var temp = 21
|
var temp = 21
|
||||||
if temp > 30 {
|
if temp > 30 {
|
||||||
@@ -26,7 +26,7 @@ Combine conditions with `&&`, `||` and `!`. The right side only runs when needed
|
|||||||
|
|
||||||
There is one keyword for every kind of loop.
|
There is one keyword for every kind of loop.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
for i in 0..3 { // 0, 1, 2: the end is not included
|
for i in 0..3 { // 0, 1, 2: the end is not included
|
||||||
print("i =", i)
|
print("i =", i)
|
||||||
@@ -83,7 +83,7 @@ the loop is safe.
|
|||||||
`match` picks a branch by shape. It must cover every possibility, otherwise the compiler
|
`match` picks a branch by shape. It must cover every possibility, otherwise the compiler
|
||||||
lists what is missing. `_` means "anything else".
|
lists what is missing. `_` means "anything else".
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
enum Shape {
|
enum Shape {
|
||||||
Circle(r: float)
|
Circle(r: float)
|
||||||
Rect(w, h: float)
|
Rect(w, h: float)
|
||||||
@@ -119,7 +119,7 @@ zero one many
|
|||||||
`match` works on enums, ints, bools and strings. Used as a **value** (like above) each arm
|
`match` works on enums, ints, bools and strings. Used as a **value** (like above) each arm
|
||||||
is one expression. Used as a **statement** an arm can be a block:
|
is one expression. Used as a **statement** an arm can be a block:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var cmd = "stop"
|
var cmd = "stop"
|
||||||
match cmd {
|
match cmd {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# 4. Functions
|
# 4. Functions
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func add(a: int, b: int): int {
|
func add(a: int, b: int): int {
|
||||||
return a + b
|
return a + b
|
||||||
}
|
}
|
||||||
@@ -25,7 +25,7 @@ Names in a row can share a type: `func area(w, h: float): float`.
|
|||||||
|
|
||||||
A function can return more than one value. The most common use is a value and an `error`.
|
A function can return more than one value. The most common use is a value and an `error`.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func divide(a, b: int): (int, error) {
|
func divide(a, b: int): (int, error) {
|
||||||
if b == 0 {
|
if b == 0 {
|
||||||
return 0, error("cannot divide by zero")
|
return 0, error("cannot divide by zero")
|
||||||
@@ -53,7 +53,7 @@ A parameter is a copy as far as you can tell: changing it inside never changes t
|
|||||||
variable. (When a function only *reads* a parameter, the compiler passes it without copying,
|
variable. (When a function only *reads* a parameter, the compiler passes it without copying,
|
||||||
so big lists are free to pass around.)
|
so big lists are free to pass around.)
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func grow(xs: []int): []int {
|
func grow(xs: []int): []int {
|
||||||
xs.push(99)
|
xs.push(99)
|
||||||
return xs
|
return xs
|
||||||
@@ -73,7 +73,7 @@ func main() {
|
|||||||
|
|
||||||
A function has a type like `func(int): int`. You can store it, pass it and return it.
|
A function has a type like `func(int): int`. You can store it, pass it and return it.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func double(x: int): int { return x * 2 }
|
func double(x: int): int { return x * 2 }
|
||||||
|
|
||||||
func apply(f: func(int): int, x: int): int {
|
func apply(f: func(int): int, x: int): int {
|
||||||
@@ -96,7 +96,7 @@ func main() {
|
|||||||
### Short lambdas
|
### Short lambdas
|
||||||
|
|
||||||
`x => x * 2` and `(a, b) => a + b` are shorthand for a one-expression function. The types
|
`x => x * 2` and `(a, b) => a + b` are shorthand for a one-expression function. The types
|
||||||
come from where it is used, so it works where Dino already knows what function is expected
|
come from where it is used, so it works where Rex already knows what function is expected
|
||||||
(a parameter, a typed variable, a struct field, or another argument of a generic function).
|
(a parameter, a typed variable, a struct field, or another argument of a generic function).
|
||||||
The short form is one expression; for several statements use the long `func(x: int): int { }`.
|
The short form is one expression; for several statements use the long `func(x: int): int { }`.
|
||||||
|
|
||||||
@@ -105,7 +105,7 @@ The short form is one expression; for several statements use the long `func(x: i
|
|||||||
A function written inside another can use the variables around it. It **copies** them when
|
A function written inside another can use the variables around it. It **copies** them when
|
||||||
it is created and keeps its own copy from then on.
|
it is created and keeps its own copy from then on.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func make_counter(): func(): int {
|
func make_counter(): func(): int {
|
||||||
var n = 0
|
var n = 0
|
||||||
return func(): int {
|
return func(): int {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
An ordered, growable sequence.
|
An ordered, growable sequence.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var nums = [10, 20, 30]
|
var nums = [10, 20, 30]
|
||||||
nums.push(40)
|
nums.push(40)
|
||||||
@@ -35,7 +35,7 @@ Facts:
|
|||||||
- Going outside the list (`nums[9]`) or popping an empty list stops the program with a message.
|
- Going outside the list (`nums[9]`) or popping an empty list stops the program with a message.
|
||||||
- **Lists are values.** `var b = a` copies the list. Changing `b` leaves `a` alone.
|
- **Lists are values.** `var b = a` copies the list. Changing `b` leaves `a` alone.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var a = [1, 2, 3]
|
var a = [1, 2, 3]
|
||||||
var b = a
|
var b = a
|
||||||
@@ -51,7 +51,7 @@ func main() {
|
|||||||
|
|
||||||
A map finds a value by a **key** instead of a position, like a phone book.
|
A map finds a value by a **key** instead of a position, like a phone book.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var ages = {"alice": 30, "bob": 25}
|
var ages = {"alice": 30, "bob": 25}
|
||||||
ages["carol"] = 41 // add a new entry
|
ages["carol"] = 41 // add a new entry
|
||||||
@@ -67,7 +67,7 @@ func main() {
|
|||||||
|
|
||||||
### Making a map
|
### Making a map
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var a = {"x": 1, "y": 2} // types are guessed from the entries
|
var a = {"x": 1, "y": 2} // types are guessed from the entries
|
||||||
var b: map[string, int] = {} // empty: the type comes from the variable
|
var b: map[string, int] = {} // empty: the type comes from the variable
|
||||||
@@ -100,7 +100,7 @@ The value can be anything: numbers, strings, lists, structs, even other maps.
|
|||||||
| `m.keys()` | a list of the keys |
|
| `m.keys()` | a list of the keys |
|
||||||
| `m.values()` | a list of the values |
|
| `m.values()` | a list of the values |
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var stock = {"apple": 3, "pear": 0}
|
var stock = {"apple": 3, "pear": 0}
|
||||||
print(stock.has("apple"), stock.has("fig"))
|
print(stock.has("apple"), stock.has("fig"))
|
||||||
@@ -120,7 +120,7 @@ true false
|
|||||||
|
|
||||||
`m[k] = v` adds or replaces. `m.remove(k)` deletes (and does nothing if the key is missing).
|
`m[k] = v` adds or replaces. `m.remove(k)` deletes (and does nothing if the key is missing).
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var m = {"a": 1, "b": 2}
|
var m = {"a": 1, "b": 2}
|
||||||
m["c"] = 3
|
m["c"] = 3
|
||||||
@@ -137,7 +137,7 @@ func main() {
|
|||||||
The most common map job is counting. `m[k] += 1` on a key that isn't there yet starts from
|
The most common map job is counting. `m[k] += 1` on a key that isn't there yet starts from
|
||||||
zero, so you don't have to check first.
|
zero, so you don't have to check first.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var counts: map[string, int] = {}
|
var counts: map[string, int] = {}
|
||||||
for w in "a b a c b a".split(" ") {
|
for w in "a b a c b a".split(" ") {
|
||||||
@@ -156,7 +156,7 @@ func main() {
|
|||||||
|
|
||||||
Entries come out **in the order they were added**, so output is always predictable.
|
Entries come out **in the order they were added**, so output is always predictable.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var prices = {"tea": 2.5, "cake": 4.0}
|
var prices = {"tea": 2.5, "cake": 4.0}
|
||||||
for name, price in prices {
|
for name, price in prices {
|
||||||
@@ -178,7 +178,7 @@ cake
|
|||||||
|
|
||||||
`var b = a` copies the whole map. A map inside a struct is copied with the struct.
|
`var b = a` copies the whole map. A map inside a struct is copied with the struct.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var a = {"x": 1}
|
var a = {"x": 1}
|
||||||
var b = a
|
var b = a
|
||||||
|
|||||||
@@ -4,13 +4,13 @@
|
|||||||
|
|
||||||
A struct groups related values. **Methods go inside the struct** and see the fields directly.
|
A struct groups related values. **Methods go inside the struct** and see the fields directly.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
struct Player {
|
struct Player {
|
||||||
name: string
|
name: string
|
||||||
hp: int
|
hp: int
|
||||||
x, y: float // names in a row share a type
|
x, y: float // names in a row share a type
|
||||||
|
|
||||||
func hurt(amount: int) { // changes hp, so Dino knows it modifies the player
|
func hurt(amount: int) { // changes hp, so Rex knows it modifies the player
|
||||||
hp -= amount
|
hp -= amount
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,7 +45,7 @@ method of the same struct (`hurt(2)`), then a global function.
|
|||||||
|
|
||||||
### Structs are values
|
### Structs are values
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
struct Point { x, y: int }
|
struct Point { x, y: int }
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -64,7 +64,7 @@ Point{x: 1, y: 2} Point{x: 99, y: 2}
|
|||||||
|
|
||||||
### Methods that return values, and nested data
|
### Methods that return values, and nested data
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
struct Vec2 {
|
struct Vec2 {
|
||||||
x, y: float
|
x, y: float
|
||||||
|
|
||||||
@@ -98,7 +98,7 @@ Vec2{x: 3.0, y: 1.0} [Vec2{x: 1.0, y: 1.0}] 10.0
|
|||||||
|
|
||||||
An enum is "one of these cases", and each case can carry data.
|
An enum is "one of these cases", and each case can carry data.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
enum Event {
|
enum Event {
|
||||||
Quit
|
Quit
|
||||||
Key(code: int)
|
Key(code: int)
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
# 7. Errors and nil
|
# 7. Errors and nil
|
||||||
|
|
||||||
Dino has no exceptions. A function that can fail says so in its result, and you handle it.
|
Rex has no exceptions. A function that can fail says so in its result, and you handle it.
|
||||||
|
|
||||||
## error
|
## error
|
||||||
|
|
||||||
`error` is a type that is either `nil` (all fine) or holds a message.
|
`error` is a type that is either `nil` (all fine) or holds a message.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func parse_age(s: string): (int, error) {
|
func parse_age(s: string): (int, error) {
|
||||||
var n, err = s.to_int()
|
var n, err = s.to_int()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -40,7 +40,7 @@ func main() {
|
|||||||
Writing `?` after a call means "if this failed, return the error from *my* function too".
|
Writing `?` after a call means "if this failed, return the error from *my* function too".
|
||||||
Otherwise you get the value.
|
Otherwise you get the value.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func half(n: int): (int, error) {
|
func half(n: int): (int, error) {
|
||||||
if n % 2 != 0 { return 0, error("{n} is odd") }
|
if n % 2 != 0 { return 0, error("{n} is odd") }
|
||||||
return n / 2, nil
|
return n / 2, nil
|
||||||
@@ -69,9 +69,9 @@ if it returns an error, the program prints `error: message` and exits with code
|
|||||||
|
|
||||||
## Optional values: `T?`
|
## Optional values: `T?`
|
||||||
|
|
||||||
A `T?` is either a `T` or `nil`. It is how Dino says "this might be missing".
|
A `T?` is either a `T` or `nil`. It is how Rex says "this might be missing".
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func find(names: []string, wanted: string): int? {
|
func find(names: []string, wanted: string): int? {
|
||||||
for i, n in names {
|
for i, n in names {
|
||||||
if n == wanted { return i }
|
if n == wanted { return i }
|
||||||
@@ -105,7 +105,7 @@ program with a message instead of misbehaving.)
|
|||||||
|
|
||||||
Maps give you optionals too:
|
Maps give you optionals too:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var ports = {"http": 80}
|
var ports = {"http": 80}
|
||||||
var p = ports.get("https")
|
var p = ports.get("https")
|
||||||
|
|||||||
+4
-4
@@ -10,7 +10,7 @@ and it also happens on an early `return`, `break`, `continue` or `?`.
|
|||||||
|
|
||||||
Giving a value a new owner **copies** it:
|
Giving a value a new owner **copies** it:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var a = [1, 2, 3]
|
var a = [1, 2, 3]
|
||||||
var b = a // b is a real copy
|
var b = a // b is a real copy
|
||||||
@@ -36,7 +36,7 @@ All tests of the compiler run under a memory checker, so leaks and double frees
|
|||||||
Sometimes you really do want several owners of **one** value (a texture used by many
|
Sometimes you really do want several owners of **one** value (a texture used by many
|
||||||
sprites, a window and its buttons). Write `shared`:
|
sprites, a window and its buttons). Write `shared`:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
struct Texture {
|
struct Texture {
|
||||||
name: string
|
name: string
|
||||||
uses: int
|
uses: int
|
||||||
@@ -75,7 +75,7 @@ func main() {
|
|||||||
If a window owns its buttons and each button owns its window, neither would ever be freed.
|
If a window owns its buttons and each button owns its window, neither would ever be freed.
|
||||||
Make one side `weak`: it points at the value without keeping it alive.
|
Make one side `weak`: it points at the value without keeping it alive.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
struct Window {
|
struct Window {
|
||||||
title: string
|
title: string
|
||||||
buttons: []shared Button
|
buttons: []shared Button
|
||||||
@@ -118,7 +118,7 @@ OK clicked, window is gone
|
|||||||
- To use the value as an owner, call `w.upgrade()`. It gives a `shared T?`: the value
|
- To use the value as an owner, call `w.upgrade()`. It gives a `shared T?`: the value
|
||||||
(now with one more owner, so it can't vanish while you hold it) or `nil`.
|
(now with one more owner, so it can't vanish while you hold it) or `nil`.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
struct Node { name: string }
|
struct Node { name: string }
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
Put the type names in `[ ]` after the function name. The compiler works the real types out
|
Put the type names in `[ ]` after the function name. The compiler works the real types out
|
||||||
from the arguments.
|
from the arguments.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func first[T](xs: []T): T {
|
func first[T](xs: []T): T {
|
||||||
return xs[0]
|
return xs[0]
|
||||||
}
|
}
|
||||||
@@ -38,7 +38,7 @@ Generics cost nothing at run time: every set of types gets its own compiled copy
|
|||||||
|
|
||||||
A generic function can take functions too, which makes `map` and `filter` easy to write:
|
A generic function can take functions too, which makes `map` and `filter` easy to write:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func map[T, U](xs: []T, f: func(T): U): []U {
|
func map[T, U](xs: []T, f: func(T): U): []U {
|
||||||
var out: []U
|
var out: []U
|
||||||
for x in xs { out.push(f(x)) }
|
for x in xs { out.push(f(x)) }
|
||||||
@@ -59,7 +59,7 @@ func main() {
|
|||||||
|
|
||||||
Structs and enums can take types too. When you **use** one, write the types out.
|
Structs and enums can take types too. When you **use** one, write the types out.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
struct Stack[T] {
|
struct Stack[T] {
|
||||||
items: []T
|
items: []T
|
||||||
|
|
||||||
@@ -93,7 +93,7 @@ Maybe[string].Some(hi)
|
|||||||
An interface lists methods. A type follows it just by having those methods, with no
|
An interface lists methods. A type follows it just by having those methods, with no
|
||||||
`implements` keyword.
|
`implements` keyword.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
interface Shape {
|
interface Shape {
|
||||||
area(): float
|
area(): float
|
||||||
name(): string
|
name(): string
|
||||||
@@ -114,7 +114,7 @@ struct Circle {
|
|||||||
|
|
||||||
### As a rule for generics
|
### As a rule for generics
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
interface Shape {
|
interface Shape {
|
||||||
area(): float
|
area(): float
|
||||||
}
|
}
|
||||||
@@ -141,7 +141,7 @@ area is 9.0
|
|||||||
An interface is also a type of its own. A variable of that type can hold any value that has
|
An interface is also a type of its own. A variable of that type can hold any value that has
|
||||||
the methods, and the right method runs at run time. This is how you build a mixed list.
|
the methods, and the right method runs at run time. This is how you build a mixed list.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
interface Shape {
|
interface Shape {
|
||||||
area(): float
|
area(): float
|
||||||
name(): string
|
name(): string
|
||||||
|
|||||||
@@ -2,12 +2,12 @@
|
|||||||
|
|
||||||
## Splitting a program into files
|
## Splitting a program into files
|
||||||
|
|
||||||
`import utils` brings in the file `utils.dino` that sits next to your main file. Use its
|
`import utils` brings in the file `utils.rex` that sits next to your main file. Use its
|
||||||
contents with the module name in front. Only things marked `pub` can be used from outside.
|
contents with the module name in front. Only things marked `pub` can be used from outside.
|
||||||
|
|
||||||
`utils.dino`:
|
`utils.rex`:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
pub const SCALE = 10
|
pub const SCALE = 10
|
||||||
|
|
||||||
pub struct Vec2 {
|
pub struct Vec2 {
|
||||||
@@ -20,9 +20,9 @@ pub func double(n: int): int { return n * 2 }
|
|||||||
func secret() {} // private: only this file can call it
|
func secret() {} // private: only this file can call it
|
||||||
```
|
```
|
||||||
|
|
||||||
`main.dino`:
|
`main.rex`:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
import utils
|
import utils
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -32,7 +32,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- Folders work too: `import tools.fs` is the file `tools/fs.dino`, used as `fs.name`.
|
- Folders work too: `import tools.fs` is the file `tools/fs.rex`, used as `fs.name`.
|
||||||
- Fields are private as well unless written `pub x: int`.
|
- Fields are private as well unless written `pub x: int`.
|
||||||
- Every file has its own names, so two files can both define `helper`.
|
- Every file has its own names, so two files can both define `helper`.
|
||||||
- Import loops and missing files are errors. An error message names the file it is in.
|
- Import loops and missing files are errors. An error message names the file it is in.
|
||||||
@@ -59,7 +59,7 @@ Import them like your own files: `import os`.
|
|||||||
`sqrt pow floor ceil round trunc sin cos tan asin acos atan atan2 exp log log10 hypot
|
`sqrt pow floor ceil round trunc sin cos tan asin acos atan atan2 exp log log10 hypot
|
||||||
min max abs`, and the values `PI` and `E`.
|
min max abs`, and the values `PI` and `E`.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
import math
|
import math
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -79,7 +79,7 @@ func main() {
|
|||||||
`upper lower trim split lines fields replace repeat contains starts_with ends_with
|
`upper lower trim split lines fields replace repeat contains starts_with ends_with
|
||||||
index_of to_int to_float`, plus `len()` and slicing.
|
index_of to_int to_float`, plus `len()` and slicing.
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
var csv = " a, b ,c "
|
var csv = " a, b ,c "
|
||||||
for part in csv.split(",") {
|
for part in csv.split(",") {
|
||||||
@@ -101,7 +101,7 @@ A list of strings can be joined: `["a", "b"].join("-")`.
|
|||||||
|
|
||||||
## A program that reads input
|
## A program that reads input
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
import os
|
import os
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|||||||
+16
-16
@@ -1,7 +1,7 @@
|
|||||||
# 11. Cheatsheet
|
# 11. Cheatsheet
|
||||||
|
|
||||||
## Basics
|
## Basics
|
||||||
```dino
|
```rex
|
||||||
var x = 1 // changeable; type inferred
|
var x = 1 // changeable; type inferred
|
||||||
var y: float = 2 // with a type
|
var y: float = 2 // with a type
|
||||||
const MAX = 100 // fixed
|
const MAX = 100 // fixed
|
||||||
@@ -15,7 +15,7 @@ print("x is {x}", y) // interpolation with { }
|
|||||||
Convert numbers with `float(x)`, `int(x)`, `u8(x)`.
|
Convert numbers with `float(x)`, `int(x)`, `u8(x)`.
|
||||||
|
|
||||||
## Control flow
|
## Control flow
|
||||||
```dino
|
```rex
|
||||||
if a > b { } else if a == b { } else { }
|
if a > b { } else if a == b { } else { }
|
||||||
for i in 0..10 { } // 0..9
|
for i in 0..10 { } // 0..9
|
||||||
for i in 0..10 step 2 { }
|
for i in 0..10 step 2 { }
|
||||||
@@ -28,7 +28,7 @@ match v { 1 => a, _ => b }
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Functions
|
## Functions
|
||||||
```dino
|
```rex
|
||||||
func add(a, b: int): int { return a + b }
|
func add(a, b: int): int { return a + b }
|
||||||
func f(): (int, error) { return 1, nil }
|
func f(): (int, error) { return 1, nil }
|
||||||
var n, err = f()
|
var n, err = f()
|
||||||
@@ -38,14 +38,14 @@ var h = x => x * 2 // where the type is known
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Lists
|
## Lists
|
||||||
```dino
|
```rex
|
||||||
var xs = [1, 2, 3] var e: []int
|
var xs = [1, 2, 3] var e: []int
|
||||||
xs.push(4) xs.pop() xs.len()
|
xs.push(4) xs.pop() xs.len()
|
||||||
xs[0] xs[0] = 9 xs[1..3]
|
xs[0] xs[0] = 9 xs[1..3]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Maps
|
## Maps
|
||||||
```dino
|
```rex
|
||||||
var m = {"a": 1} var e: map[string, int] = {}
|
var m = {"a": 1} var e: map[string, int] = {}
|
||||||
var e2 = map[string, int]{}
|
var e2 = map[string, int]{}
|
||||||
m["b"] = 2 // add or replace
|
m["b"] = 2 // add or replace
|
||||||
@@ -56,7 +56,7 @@ m.get_or("z", 0) m.len() m.keys() m.values() m.remove("a")
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Strings
|
## Strings
|
||||||
```dino
|
```rex
|
||||||
s.len() s.upper() s.lower() s.trim() s.split(",") s.lines() s.fields()
|
s.len() s.upper() s.lower() s.trim() s.split(",") s.lines() s.fields()
|
||||||
s.replace(a, b) s.repeat(n) s.contains(x) s.starts_with(x) s.ends_with(x)
|
s.replace(a, b) s.repeat(n) s.contains(x) s.starts_with(x) s.ends_with(x)
|
||||||
s.index_of(x) s.to_int() s.to_float() s[1..4] s[2..] s[..3]
|
s.index_of(x) s.to_int() s.to_float() s[1..4] s[2..] s[..3]
|
||||||
@@ -64,7 +64,7 @@ s.index_of(x) s.to_int() s.to_float() s[1..4] s[2..] s[..3]
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Characters
|
## Characters
|
||||||
```dino
|
```rex
|
||||||
var c = 'a' '\n' 'é' // one character, single quotes
|
var c = 'a' '\n' 'é' // one character, single quotes
|
||||||
c == 'a' c < 'z' // compare
|
c == 'a' c < 'z' // compare
|
||||||
c.is_digit() c.is_letter() c.is_alnum() c.is_space() c.is_upper() c.is_lower()
|
c.is_digit() c.is_letter() c.is_alnum() c.is_space() c.is_upper() c.is_lower()
|
||||||
@@ -75,7 +75,7 @@ s[i] // the char starting at byte i
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Structs and enums
|
## Structs and enums
|
||||||
```dino
|
```rex
|
||||||
struct P {
|
struct P {
|
||||||
name: string
|
name: string
|
||||||
x, y: float
|
x, y: float
|
||||||
@@ -91,19 +91,19 @@ E.B(3) match e { A => 1, B(n) => n }
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Errors and nil
|
## Errors and nil
|
||||||
```dino
|
```rex
|
||||||
error("message {x}") err != nil return 0, nil
|
error("message {x}") err != nil return 0, nil
|
||||||
var v: int? = nil if v != nil { v } if v == nil { return }
|
var v: int? = nil if v != nil { v } if v == nil { return }
|
||||||
```
|
```
|
||||||
|
|
||||||
## Sharing
|
## Sharing
|
||||||
```dino
|
```rex
|
||||||
var a = shared T{...} var b = a // same value, two owners
|
var a = shared T{...} var b = a // same value, two owners
|
||||||
var w = weak a w.upgrade() // shared T? (nil if gone)
|
var w = weak a w.upgrade() // shared T? (nil if gone)
|
||||||
```
|
```
|
||||||
|
|
||||||
## Generics and interfaces
|
## Generics and interfaces
|
||||||
```dino
|
```rex
|
||||||
func first[T](xs: []T): T { return xs[0] }
|
func first[T](xs: []T): T { return xs[0] }
|
||||||
func big[T: Ordered](a, b: T): T { ... } // Ordered, Number, or an interface
|
func big[T: Ordered](a, b: T): T { ... } // Ordered, Number, or an interface
|
||||||
struct Stack[T] { items: []T } Stack[int]{}
|
struct Stack[T] { items: []T } Stack[int]{}
|
||||||
@@ -112,15 +112,15 @@ var s: Shape = Circle{1.0}
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Files
|
## Files
|
||||||
```dino
|
```rex
|
||||||
import utils // utils.dino next to this file
|
import utils // utils.rex next to this file
|
||||||
import tools.fs // tools/fs.dino, used as fs.name
|
import tools.fs // tools/fs.rex, used as fs.name
|
||||||
import os // built-in: os math time
|
import os // built-in: os math time
|
||||||
pub func f() {} // visible to other files
|
pub func f() {} // visible to other files
|
||||||
```
|
```
|
||||||
|
|
||||||
## C libraries
|
## C libraries
|
||||||
```dino
|
```rex
|
||||||
import "zlib.h" // zlib.crc32(...), zlib.Z_OK, types like zlib.gzFile
|
import "zlib.h" // zlib.crc32(...), zlib.Z_OK, types like zlib.gzFile
|
||||||
import "raylib.h" { InitWindow } // only these names, used bare
|
import "raylib.h" { InitWindow } // only these names, used bare
|
||||||
import "foo.h" link "foo" // when pkg-config doesn't know it (libfoo.so)
|
import "foo.h" link "foo" // when pkg-config doesn't know it (libfoo.so)
|
||||||
@@ -129,7 +129,7 @@ lib.fill(buf, n) // T* parameters take a variable or a list
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
`dino run f.dino args…` · `dino build f.dino -o out` · `dino check f.dino` · `dino emit-c f.dino` · `dino fmt path` (`--check` to only report) · `dino lsp` (editor server) · `dino header x.h [word]` (what a C header offers)
|
`rex run f.rex args…` · `rex build f.rex -o out` · `rex check f.rex` · `rex emit-c f.rex` · `rex fmt path` (`--check` to only report) · `rex lsp` (editor server) · `rex header x.h [word]` (what a C header offers)
|
||||||
|
|
||||||
## Things that stop the program (exit code 2)
|
## Things that stop the program (exit code 2)
|
||||||
Divide by zero · list index/slice out of range · `pop` on an empty list · reading a missing
|
Divide by zero · list index/slice out of range · `pop` on an empty list · reading a missing
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ The folder `examples/calc/` holds a calculator split over five files. It uses al
|
|||||||
everything from these notes. Run it:
|
everything from these notes. Run it:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
cargo run -q -- run examples/calc/main.dino examples/calc/session.txt
|
cargo run -q -- run examples/calc/main.rex examples/calc/session.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
or type calculations interactively by leaving off the file name.
|
or type calculations interactively by leaving off the file name.
|
||||||
@@ -21,11 +21,11 @@ sqrt(16) + max(1, 5)
|
|||||||
|
|
||||||
| File | Job | Features it shows |
|
| File | Job | Features it shows |
|
||||||
|------|-----|-------------------|
|
|------|-----|-------------------|
|
||||||
| `token.dino` | Turns text into tokens | enums, structs, `char`, string slicing, errors |
|
| `token.rex` | Turns text into tokens | enums, structs, `char`, string slicing, errors |
|
||||||
| `ast.dino` | The shape of a calculation | an enum that holds other nodes |
|
| `ast.rex` | The shape of a calculation | an enum that holds other nodes |
|
||||||
| `parser.dino` | Builds the tree | a struct with methods, `?`, recursion |
|
| `parser.rex` | Builds the tree | a struct with methods, `?`, recursion |
|
||||||
| `eval.dino` | Computes the answer | `match`, maps, function values, closures |
|
| `eval.rex` | Computes the answer | `match`, maps, function values, closures |
|
||||||
| `main.dino` | Reads lines and prints | `import`, `os`, `shared` |
|
| `main.rex` | Reads lines and prints | `import`, `os`, `shared` |
|
||||||
|
|
||||||
## 1. Tokens
|
## 1. Tokens
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ kind of token starts there: `c.is_digit()` starts a number, `c.is_letter()` a na
|
|||||||
|
|
||||||
## 2. The tree
|
## 2. The tree
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
pub enum Node {
|
pub enum Node {
|
||||||
Num(value: float)
|
Num(value: float)
|
||||||
Var(name: string)
|
Var(name: string)
|
||||||
@@ -63,7 +63,7 @@ with `?`.
|
|||||||
|
|
||||||
The scope that remembers variables and functions is two maps:
|
The scope that remembers variables and functions is two maps:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
pub struct Scope {
|
pub struct Scope {
|
||||||
variables: map[string, float]
|
variables: map[string, float]
|
||||||
builtins: map[string, Builtin]
|
builtins: map[string, Builtin]
|
||||||
@@ -74,7 +74,7 @@ pub struct Scope {
|
|||||||
A built-in function is a struct holding its name, how many arguments it takes, and a
|
A built-in function is a struct holding its name, how many arguments it takes, and a
|
||||||
function value:
|
function value:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
s.builtins["sqrt"] = Builtin{"sqrt", 1, a => math.sqrt(a[0])}
|
s.builtins["sqrt"] = Builtin{"sqrt", 1, a => math.sqrt(a[0])}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -86,7 +86,7 @@ which gives `nil` when it isn't there, turned into a friendly error.
|
|||||||
The scope is created once as `shared`, so every line sees the variables set by the
|
The scope is created once as `shared`, so every line sees the variables set by the
|
||||||
lines before it, with no need to pass the scope back and forth:
|
lines before it, with no need to pass the scope back and forth:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
var scope = shared eval.new_scope()
|
var scope = shared eval.new_scope()
|
||||||
...
|
...
|
||||||
run_line(scope, line)
|
run_line(scope, line)
|
||||||
|
|||||||
+33
-33
@@ -1,8 +1,8 @@
|
|||||||
# 13. C and C++ libraries
|
# 13. C and C++ libraries
|
||||||
|
|
||||||
A huge amount of useful code is written in C: graphics (raylib, SDL), compression (zlib),
|
A huge amount of useful code is written in C: graphics (raylib, SDL), compression (zlib),
|
||||||
databases (SQLite), and the C library that comes with every system. Dino can use it
|
databases (SQLite), and the C library that comes with every system. Rex can use it
|
||||||
directly. You don't write any declarations: Dino reads the library's **header file** (the
|
directly. You don't write any declarations: Rex reads the library's **header file** (the
|
||||||
`.h` file that lists what the library has) and works out the rest.
|
`.h` file that lists what the library has) and works out the rest.
|
||||||
|
|
||||||
## Importing a header
|
## Importing a header
|
||||||
@@ -10,7 +10,7 @@ directly. You don't write any declarations: Dino reads the library's **header fi
|
|||||||
Put the header's name in quotes. Its functions, types and constants are then used with the
|
Put the header's name in quotes. Its functions, types and constants are then used with the
|
||||||
header's name in front, the same way as your own files (`import utils` gives `utils.name`).
|
header's name in front, the same way as your own files (`import utils` gives `utils.name`).
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
import "string.h"
|
import "string.h"
|
||||||
import "stdlib.h"
|
import "stdlib.h"
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ gives `SDL`, `"my-lib.h"` gives `my_lib`. To choose another one, write it before
|
|||||||
When you only want some things from a header, list them in braces. Those names are then
|
When you only want some things from a header, list them in braces. Those names are then
|
||||||
used **without** a prefix, and nothing else from the header is visible:
|
used **without** a prefix, and nothing else from the header is visible:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
import "math.h" { cbrt, hypot }
|
import "math.h" { cbrt, hypot }
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -44,12 +44,12 @@ func main() {
|
|||||||
3.0 5.0
|
3.0 5.0
|
||||||
```
|
```
|
||||||
|
|
||||||
(`math.h` is the C math library. Dino's own `import math` is usually nicer; this is just a
|
(`math.h` is the C math library. Rex's own `import math` is usually nicer; this is just a
|
||||||
small example.)
|
small example.)
|
||||||
|
|
||||||
## How C types look in Dino
|
## How C types look in Rex
|
||||||
|
|
||||||
| In C | In Dino |
|
| In C | In Rex |
|
||||||
|------|---------|
|
|------|---------|
|
||||||
| `int`, `unsigned int`, `short`, ... | `i32`, `u32`, `i16`, ... |
|
| `int`, `unsigned int`, `short`, ... | `i32`, `u32`, `i16`, ... |
|
||||||
| `long`, `long long`, `int64_t` | `int` |
|
| `long`, `long long`, `int64_t` | `int` |
|
||||||
@@ -59,28 +59,28 @@ small example.)
|
|||||||
| `bool` | `bool` |
|
| `bool` | `bool` |
|
||||||
| `const char *` and `char *` | `string` |
|
| `const char *` and `char *` | `string` |
|
||||||
| an `enum` | its values are constants (`i32`) |
|
| an `enum` | its values are constants (`i32`) |
|
||||||
| a `struct` with plain fields | a Dino struct: `raylib.Color{255, 0, 0, 255}` |
|
| a `struct` with plain fields | a Rex struct: `raylib.Color{255, 0, 0, 255}` |
|
||||||
| any other pointer (`FILE *`, `SDL_Window *`) | a pointer type: `stdio.FILE`, `SDL.SDL_Window` |
|
| any other pointer (`FILE *`, `SDL_Window *`) | a pointer type: `stdio.FILE`, `SDL.SDL_Window` |
|
||||||
| `NULL` | `nil` |
|
| `NULL` | `nil` |
|
||||||
|
|
||||||
Numbers follow the usual Dino rule: a number written in the code fits any number type, but
|
Numbers follow the usual Rex rule: a number written in the code fits any number type, but
|
||||||
a variable has to be converted, for example `i32(n)` when the C function takes an `int`.
|
a variable has to be converted, for example `i32(n)` when the C function takes an `int`.
|
||||||
|
|
||||||
Text works both ways: a Dino string is handed to C as a C string, and a C string that comes
|
Text works both ways: a Rex string is handed to C as a C string, and a C string that comes
|
||||||
back becomes a Dino string (a copy, so it stays valid).
|
back becomes a Rex string (a copy, so it stays valid).
|
||||||
|
|
||||||
## Pointers: things you only pass around
|
## Pointers: things you only pass around
|
||||||
|
|
||||||
Many C libraries give you a pointer to something they manage, like an open file or a
|
Many C libraries give you a pointer to something they manage, like an open file or a
|
||||||
window. In Dino you keep it in a variable, hand it back to the library, and compare it with
|
window. In Rex you keep it in a variable, hand it back to the library, and compare it with
|
||||||
`nil` to see if it is missing:
|
`nil` to see if it is missing:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
import "stdio.h"
|
import "stdio.h"
|
||||||
import os
|
import os
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var f = stdio.fopen("/tmp/dino-hello.txt", "w")
|
var f = stdio.fopen("/tmp/rex-hello.txt", "w")
|
||||||
if f == nil {
|
if f == nil {
|
||||||
print("can't open the file")
|
print("can't open the file")
|
||||||
return
|
return
|
||||||
@@ -88,7 +88,7 @@ func main() {
|
|||||||
stdio.fputs("hello from C\n", f)
|
stdio.fputs("hello from C\n", f)
|
||||||
stdio.fclose(f)
|
stdio.fclose(f)
|
||||||
|
|
||||||
var text, err = os.read_file("/tmp/dino-hello.txt")
|
var text, err = os.read_file("/tmp/rex-hello.txt")
|
||||||
print(text.trim(), err)
|
print(text.trim(), err)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -98,16 +98,16 @@ hello from C nil
|
|||||||
|
|
||||||
The type can be written like any other: `var f: stdio.FILE` starts out as `nil`.
|
The type can be written like any other: `var f: stdio.FILE` starts out as `nil`.
|
||||||
|
|
||||||
**Dino does not free C things for you.** Whatever the library opens or creates, close or
|
**Rex does not free C things for you.** Whatever the library opens or creates, close or
|
||||||
free it with the library's own function (`fclose`, `sqlite3_close`, `UnloadTexture`, ...).
|
free it with the library's own function (`fclose`, `sqlite3_close`, `UnloadTexture`, ...).
|
||||||
|
|
||||||
## Functions that write into your variables
|
## Functions that write into your variables
|
||||||
|
|
||||||
Some C functions give back extra results by writing into a variable you pass them (in C:
|
Some C functions give back extra results by writing into a variable you pass them (in C:
|
||||||
a pointer parameter like `double *out`). Pass a Dino **variable**, and the function changes
|
a pointer parameter like `double *out`). Pass a Rex **variable**, and the function changes
|
||||||
it. Pass a **list** where the C function wants room for several values (a buffer):
|
it. Pass a **list** where the C function wants room for several values (a buffer):
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
import "math.h" { modf }
|
import "math.h" { modf }
|
||||||
import "string.h" { memset }
|
import "string.h" { memset }
|
||||||
|
|
||||||
@@ -139,14 +139,14 @@ sqlite3.sqlite3_open("notes.db", db) // db is now open (or still nil if it fai
|
|||||||
|
|
||||||
## Constants
|
## Constants
|
||||||
|
|
||||||
Values from `#define` and `enum` work like Dino constants: `stdio.EOF`, `zlib.Z_OK`,
|
Values from `#define` and `enum` work like Rex constants: `stdio.EOF`, `zlib.Z_OK`,
|
||||||
`raylib.KEY_SPACE`. raylib's colours (`raylib.RED`, `raylib.RAYWHITE`) are struct constants
|
`raylib.KEY_SPACE`. raylib's colours (`raylib.RED`, `raylib.RAYWHITE`) are struct constants
|
||||||
of type `raylib.Color`.
|
of type `raylib.Color`.
|
||||||
|
|
||||||
## Linking: where the library's code is
|
## Linking: where the library's code is
|
||||||
|
|
||||||
The header only describes a library; its code is in a library file that has to be linked
|
The header only describes a library; its code is in a library file that has to be linked
|
||||||
in. Dino asks the system (`pkg-config`) for that, so for most installed libraries
|
in. Rex asks the system (`pkg-config`) for that, so for most installed libraries
|
||||||
`import "raylib.h"` or `import "zlib.h"` is all you need. If a library isn't known to
|
`import "raylib.h"` or `import "zlib.h"` is all you need. If a library isn't known to
|
||||||
`pkg-config`, name it yourself: for the file `libfoo.so`, write
|
`pkg-config`, name it yourself: for the file `libfoo.so`, write
|
||||||
|
|
||||||
@@ -161,11 +161,11 @@ If it is missing, building stops with a message that says so.
|
|||||||
[raylib](https://www.raylib.com) is a simple library for games and graphics. With it
|
[raylib](https://www.raylib.com) is a simple library for games and graphics. With it
|
||||||
installed, this opens a window and draws a circle:
|
installed, this opens a window and draws a circle:
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
import "raylib.h"
|
import "raylib.h"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
raylib.InitWindow(800, 450, "Hello from Dino")
|
raylib.InitWindow(800, 450, "Hello from Rex")
|
||||||
raylib.SetTargetFPS(60)
|
raylib.SetTargetFPS(60)
|
||||||
var x: f32 = 400.0
|
var x: f32 = 400.0
|
||||||
for !raylib.WindowShouldClose() {
|
for !raylib.WindowShouldClose() {
|
||||||
@@ -182,12 +182,12 @@ func main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
A bigger example with bouncing balls is in
|
A bigger example with bouncing balls is in
|
||||||
[`examples/c/bounce.dino`](../examples/c/bounce.dino).
|
[`examples/c/bounce.rex`](../examples/c/bounce.rex).
|
||||||
|
|
||||||
## Your own C code
|
## Your own C code
|
||||||
|
|
||||||
Put a header and its `.c` file next to your program. `import "shapes.h"` reads the header,
|
Put a header and its `.c` file next to your program. `import "shapes.h"` reads the header,
|
||||||
and Dino compiles `shapes.c` and builds it into your program.
|
and Rex compiles `shapes.c` and builds it into your program.
|
||||||
|
|
||||||
```c
|
```c
|
||||||
// shapes.h
|
// shapes.h
|
||||||
@@ -203,7 +203,7 @@ double area(Size s) { return s.w * s.h; }
|
|||||||
void grow(Size *s, double by) { s->w *= by; s->h *= by; }
|
void grow(Size *s, double by) { s->w *= by; s->h *= by; }
|
||||||
```
|
```
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
import "shapes.h"
|
import "shapes.h"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -218,10 +218,10 @@ func main() {
|
|||||||
|
|
||||||
## C++
|
## C++
|
||||||
|
|
||||||
C++ code can't be called from C or Dino directly: C++ functions get scrambled ("mangled")
|
C++ code can't be called from C or Rex directly: C++ functions get scrambled ("mangled")
|
||||||
names when compiled, and classes and templates don't exist in C. The usual fix is a small
|
names when compiled, and classes and templates don't exist in C. The usual fix is a small
|
||||||
set of plain functions marked `extern "C"`. Write them in a `.cpp` file next to the header,
|
set of plain functions marked `extern "C"`. Write them in a `.cpp` file next to the header,
|
||||||
and Dino compiles it with your C++ compiler (`c++`) and links in the C++ library:
|
and Rex compiles it with your C++ compiler (`c++`) and links in the C++ library:
|
||||||
|
|
||||||
```c
|
```c
|
||||||
// counter.h: plain C, also readable by C++
|
// counter.h: plain C, also readable by C++
|
||||||
@@ -252,7 +252,7 @@ void counter_free(Counter *c) { delete c; }
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```dino
|
```rex
|
||||||
import "counter.h"
|
import "counter.h"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -271,11 +271,11 @@ functions.
|
|||||||
|
|
||||||
## Seeing what a header has
|
## Seeing what a header has
|
||||||
|
|
||||||
`dino header` lists everything Dino can use from a header, written as Dino. Add a word to
|
`rex header` lists everything Rex can use from a header, written as Rex. Add a word to
|
||||||
only see names that contain it:
|
only see names that contain it:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
dino header zlib.h compress
|
rex header zlib.h compress
|
||||||
```
|
```
|
||||||
```text
|
```text
|
||||||
import "zlib.h" // use the names below as zlib.name
|
import "zlib.h" // use the names below as zlib.name
|
||||||
@@ -286,11 +286,11 @@ func compress(dest: []u8 or u8 variable, destLen: []u64 or u64 variable, source:
|
|||||||
...
|
...
|
||||||
```
|
```
|
||||||
|
|
||||||
In an editor with Dino support, completion after `zlib.` and hovering a name show the same.
|
In an editor with Rex support, completion after `zlib.` and hovering a name show the same.
|
||||||
|
|
||||||
## What doesn't work yet
|
## What doesn't work yet
|
||||||
|
|
||||||
Dino tells you when you call one of these, and why:
|
Rex tells you when you call one of these, and why:
|
||||||
|
|
||||||
- functions with a variable number of arguments, like `printf`
|
- functions with a variable number of arguments, like `printf`
|
||||||
- functions that take a callback (a function pointer)
|
- functions that take a callback (a function pointer)
|
||||||
@@ -299,6 +299,6 @@ Dino tells you when you call one of these, and why:
|
|||||||
- C macros that take arguments (`#define MAX(a, b) ...`)
|
- C macros that take arguments (`#define MAX(a, b) ...`)
|
||||||
|
|
||||||
When you need one of these, write a small function in your own `.c` file that does the C
|
When you need one of these, write a small function in your own `.c` file that does the C
|
||||||
part, and call that from Dino.
|
part, and call that from Rex.
|
||||||
|
|
||||||
Next: back to the [overview](README.md)
|
Next: back to the [overview](README.md)
|
||||||
+5
-5
@@ -1,6 +1,6 @@
|
|||||||
# Dino: learn the language
|
# Rex: learn the language
|
||||||
|
|
||||||
Dino is a small, fast, modern language. It looks like Go, runs like C, and has no
|
Rex is a small, fast, modern language. It looks like Go, runs like C, and has no
|
||||||
garbage collector, no pointers, and nothing low-level to write. You write plain code;
|
garbage collector, no pointers, and nothing low-level to write. You write plain code;
|
||||||
the compiler works out the memory.
|
the compiler works out the memory.
|
||||||
|
|
||||||
@@ -25,11 +25,11 @@ These notes teach it from zero. Read them in order, or jump to the
|
|||||||
|
|
||||||
## How to read the examples
|
## How to read the examples
|
||||||
|
|
||||||
Every `dino` block that has a `func main` is a complete program you can save and run.
|
Every `rex` block that has a `func main` is a complete program you can save and run.
|
||||||
The block right after it (marked `text`) shows what it prints.
|
The block right after it (marked `text`) shows what it prints.
|
||||||
|
|
||||||
````
|
````
|
||||||
```dino
|
```rex
|
||||||
func main() {
|
func main() {
|
||||||
print("hello")
|
print("hello")
|
||||||
}
|
}
|
||||||
@@ -39,7 +39,7 @@ hello
|
|||||||
```
|
```
|
||||||
````
|
````
|
||||||
|
|
||||||
## The four ideas behind Dino
|
## The four ideas behind Rex
|
||||||
|
|
||||||
1. **Values.** `var b = a` makes a real copy. Change `b` and `a` stays the same.
|
1. **Values.** `var b = a` makes a real copy. Change `b` and `a` stays the same.
|
||||||
There are no hidden aliases, which makes programs easy to reason about.
|
There are no hidden aliases, which makes programs easy to reason about.
|
||||||
|
|||||||
+29
-29
@@ -1,20 +1,20 @@
|
|||||||
# Editor support for Dino
|
# Editor support for Rex
|
||||||
|
|
||||||
Everything here talks to the compiler itself, so what you see in the editor is exactly what
|
Everything here talks to the compiler itself, so what you see in the editor is exactly what
|
||||||
`dino run` would tell you.
|
`rex run` would tell you.
|
||||||
|
|
||||||
| You get | How |
|
| You get | How |
|
||||||
|---------|-----|
|
|---------|-----|
|
||||||
| Syntax colours | a grammar file (VS Code, Neovim, Vim) |
|
| Syntax colours | a grammar file (VS Code, Neovim, Vim) |
|
||||||
| Errors underlined as you type | the language server, `dino lsp` |
|
| Errors underlined as you type | the language server, `rex lsp` |
|
||||||
| Format the file (and on save) | the same server, using `dino fmt` |
|
| Format the file (and on save) | the same server, using `rex fmt` |
|
||||||
| Outline, go to definition, hover, completion, parameter hints | the same server (reads the file's names; no type checking) |
|
| Outline, go to definition, hover, completion, parameter hints | the same server (reads the file's names; no type checking) |
|
||||||
|
|
||||||
First put the `dino` program on your `PATH`:
|
First put the `rex` program on your `PATH`:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
cargo build --release
|
cargo build --release
|
||||||
cp target/release/dino ~/.local/bin/ # or anywhere on your PATH
|
cp target/release/rex ~/.local/bin/ # or anywhere on your PATH
|
||||||
```
|
```
|
||||||
|
|
||||||
## VS Code
|
## VS Code
|
||||||
@@ -24,14 +24,14 @@ The extension is in `editors/vscode/`.
|
|||||||
```text
|
```text
|
||||||
cd editors/vscode
|
cd editors/vscode
|
||||||
npm install # downloads the small language-client library
|
npm install # downloads the small language-client library
|
||||||
npx @vscode/vsce package # makes dino-0.1.0.vsix
|
npx @vscode/vsce package # makes rex-0.1.0.vsix
|
||||||
code --install-extension dino-0.1.0.vsix
|
code --install-extension rex-0.1.0.vsix
|
||||||
```
|
```
|
||||||
|
|
||||||
To try it without installing, open the `editors/vscode` folder in VS Code and press **F5**.
|
To try it without installing, open the `editors/vscode` folder in VS Code and press **F5**.
|
||||||
|
|
||||||
If `dino` is not on your `PATH`, set **Dino: Server Path** in the settings to the full path.
|
If `rex` is not on your `PATH`, set **Rex: Server Path** in the settings to the full path.
|
||||||
Format-on-save and 4-space indents are switched on for `.dino` files by default.
|
Format-on-save and 4-space indents are switched on for `.rex` files by default.
|
||||||
|
|
||||||
## Neovim
|
## Neovim
|
||||||
|
|
||||||
@@ -40,19 +40,19 @@ Put the `vim/` folder on your runtime path to get file detection and colours, fo
|
|||||||
|
|
||||||
```text
|
```text
|
||||||
mkdir -p ~/.config/nvim/syntax ~/.config/nvim/ftdetect
|
mkdir -p ~/.config/nvim/syntax ~/.config/nvim/ftdetect
|
||||||
cp vim/syntax/dino.vim ~/.config/nvim/syntax/
|
cp vim/syntax/rex.vim ~/.config/nvim/syntax/
|
||||||
cp vim/ftdetect/dino.vim ~/.config/nvim/ftdetect/
|
cp vim/ftdetect/rex.vim ~/.config/nvim/ftdetect/
|
||||||
```
|
```
|
||||||
|
|
||||||
Then in `init.lua` (Neovim 0.8 or newer):
|
Then in `init.lua` (Neovim 0.8 or newer):
|
||||||
|
|
||||||
```lua
|
```lua
|
||||||
vim.api.nvim_create_autocmd("FileType", {
|
vim.api.nvim_create_autocmd("FileType", {
|
||||||
pattern = "dino",
|
pattern = "rex",
|
||||||
callback = function(args)
|
callback = function(args)
|
||||||
vim.lsp.start({
|
vim.lsp.start({
|
||||||
name = "dino",
|
name = "rex",
|
||||||
cmd = { "dino", "lsp" },
|
cmd = { "rex", "lsp" },
|
||||||
root_dir = vim.fs.dirname(args.file),
|
root_dir = vim.fs.dirname(args.file),
|
||||||
})
|
})
|
||||||
vim.bo.shiftwidth = 4
|
vim.bo.shiftwidth = 4
|
||||||
@@ -61,7 +61,7 @@ vim.api.nvim_create_autocmd("FileType", {
|
|||||||
})
|
})
|
||||||
-- format when saving
|
-- format when saving
|
||||||
vim.api.nvim_create_autocmd("BufWritePre", {
|
vim.api.nvim_create_autocmd("BufWritePre", {
|
||||||
pattern = "*.dino",
|
pattern = "*.rex",
|
||||||
callback = function() vim.lsp.buf.format({ async = false }) end,
|
callback = function() vim.lsp.buf.format({ async = false }) end,
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
@@ -73,26 +73,26 @@ Plain Vim gets the colours from the same two files (no language server).
|
|||||||
Add this to `~/.config/helix/languages.toml`:
|
Add this to `~/.config/helix/languages.toml`:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[language-server.dino]
|
[language-server.rex]
|
||||||
command = "dino"
|
command = "rex"
|
||||||
args = ["lsp"]
|
args = ["lsp"]
|
||||||
|
|
||||||
[[language]]
|
[[language]]
|
||||||
name = "dino"
|
name = "rex"
|
||||||
scope = "source.dino"
|
scope = "source.rex"
|
||||||
file-types = ["dino"]
|
file-types = ["rex"]
|
||||||
comment-token = "//"
|
comment-token = "//"
|
||||||
indent = { tab-width = 4, unit = " " }
|
indent = { tab-width = 4, unit = " " }
|
||||||
language-servers = ["dino"]
|
language-servers = ["rex"]
|
||||||
auto-format = true
|
auto-format = true
|
||||||
```
|
```
|
||||||
|
|
||||||
## Any other editor
|
## Any other editor
|
||||||
|
|
||||||
Anything that can run a language server works: start `dino lsp` (it speaks the standard
|
Anything that can run a language server works: start `rex lsp` (it speaks the standard
|
||||||
protocol over stdin/stdout) for files ending in `.dino`. It supports diagnostics and
|
protocol over stdin/stdout) for files ending in `.rex`. It supports diagnostics and
|
||||||
whole-file formatting. The grammar for colours is the TextMate file
|
whole-file formatting. The grammar for colours is the TextMate file
|
||||||
`vscode/syntaxes/dino.tmLanguage.json`, which Sublime Text, Zed and many others can read.
|
`vscode/syntaxes/rex.tmLanguage.json`, which Sublime Text, Zed and many others can read.
|
||||||
|
|
||||||
## What the server does (and doesn't) do yet
|
## What the server does (and doesn't) do yet
|
||||||
|
|
||||||
@@ -105,7 +105,7 @@ whole-file formatting. The grammar for colours is the TextMate file
|
|||||||
|
|
||||||
## Opcode
|
## Opcode
|
||||||
|
|
||||||
Opcode (the C++ editor in `~/Desktop/Porn/Linux/Clean/opcode`) knows Dino out of the box: colours,
|
Opcode (the C++ editor in `~/Desktop/Porn/Linux/Clean/opcode`) knows Rex out of the box: colours,
|
||||||
`//` comments, snippets, the outline, format with `dino fmt -`, and the language server
|
`//` comments, snippets, the outline, format with `rex fmt -`, and the language server
|
||||||
(`dino lsp`) for errors, go to definition, hover, completion and parameter hints. It only needs
|
(`rex lsp`) for errors, go to definition, hover, completion and parameter hints. It only needs
|
||||||
`dino` on your `PATH` (see the top of this page).
|
`rex` on your `PATH` (see the top of this page).
|
||||||
@@ -1 +0,0 @@
|
|||||||
autocmd BufRead,BufNewFile *.dino setfiletype dino
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
autocmd BufRead,BufNewFile *.rex setfiletype rex
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
" Vim / Neovim syntax highlighting for Dino
|
|
||||||
if exists("b:current_syntax")
|
|
||||||
finish
|
|
||||||
endif
|
|
||||||
|
|
||||||
syn keyword dinoControl if else for in step match return break continue
|
|
||||||
syn keyword dinoDeclare func var const import struct enum interface pub
|
|
||||||
syn keyword dinoModifier shared weak
|
|
||||||
syn keyword dinoConstant true false nil
|
|
||||||
syn keyword dinoType int float bool char string error map i8 i16 i32 i64 u8 u16 u32 u64 f32 f64
|
|
||||||
syn match dinoTypeName "\<[A-Z][A-Za-z0-9_]*\>"
|
|
||||||
syn match dinoNumber "\<[0-9][0-9_]*\(\.[0-9][0-9_]*\)\?\>"
|
|
||||||
syn match dinoCall "\<[a-z_][A-Za-z0-9_]*\ze\s*("
|
|
||||||
syn match dinoOperator "=>\|\.\.\|==\|!=\|<=\|>=\|&&\|||\|[-+*/%]=\?\|[<>!?=]"
|
|
||||||
syn match dinoEscape "\\." contained
|
|
||||||
syn region dinoInterp matchgroup=dinoInterpEdge start="{" end="}" contained contains=TOP
|
|
||||||
syn region dinoString start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=dinoEscape,dinoInterp
|
|
||||||
syn match dinoChar "'\(\\.\|[^'\\]\)'"
|
|
||||||
syn region dinoComment start="/\*" end="\*/"
|
|
||||||
syn match dinoComment "//.*$"
|
|
||||||
|
|
||||||
hi def link dinoControl Conditional
|
|
||||||
hi def link dinoDeclare Keyword
|
|
||||||
hi def link dinoModifier StorageClass
|
|
||||||
hi def link dinoConstant Constant
|
|
||||||
hi def link dinoType Type
|
|
||||||
hi def link dinoTypeName Type
|
|
||||||
hi def link dinoNumber Number
|
|
||||||
hi def link dinoCall Function
|
|
||||||
hi def link dinoOperator Operator
|
|
||||||
hi def link dinoEscape SpecialChar
|
|
||||||
hi def link dinoInterpEdge Delimiter
|
|
||||||
hi def link dinoString String
|
|
||||||
hi def link dinoChar Character
|
|
||||||
hi def link dinoComment Comment
|
|
||||||
|
|
||||||
let b:current_syntax = "dino"
|
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
" Vim / Neovim syntax highlighting for Rex
|
||||||
|
if exists("b:current_syntax")
|
||||||
|
finish
|
||||||
|
endif
|
||||||
|
|
||||||
|
syn keyword rexControl if else for in step match return break continue
|
||||||
|
syn keyword rexDeclare func var const import struct enum interface pub
|
||||||
|
syn keyword rexModifier shared weak
|
||||||
|
syn keyword rexConstant true false nil
|
||||||
|
syn keyword rexType int float bool char string error map i8 i16 i32 i64 u8 u16 u32 u64 f32 f64
|
||||||
|
syn match rexTypeName "\<[A-Z][A-Za-z0-9_]*\>"
|
||||||
|
syn match rexNumber "\<[0-9][0-9_]*\(\.[0-9][0-9_]*\)\?\>"
|
||||||
|
syn match rexCall "\<[a-z_][A-Za-z0-9_]*\ze\s*("
|
||||||
|
syn match rexOperator "=>\|\.\.\|==\|!=\|<=\|>=\|&&\|||\|[-+*/%]=\?\|[<>!?=]"
|
||||||
|
syn match rexEscape "\\." contained
|
||||||
|
syn region rexInterp matchgroup=rexInterpEdge start="{" end="}" contained contains=TOP
|
||||||
|
syn region rexString start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=rexEscape,rexInterp
|
||||||
|
syn match rexChar "'\(\\.\|[^'\\]\)'"
|
||||||
|
syn region rexComment start="/\*" end="\*/"
|
||||||
|
syn match rexComment "//.*$"
|
||||||
|
|
||||||
|
hi def link rexControl Conditional
|
||||||
|
hi def link rexDeclare Keyword
|
||||||
|
hi def link rexModifier StorageClass
|
||||||
|
hi def link rexConstant Constant
|
||||||
|
hi def link rexType Type
|
||||||
|
hi def link rexTypeName Type
|
||||||
|
hi def link rexNumber Number
|
||||||
|
hi def link rexCall Function
|
||||||
|
hi def link rexOperator Operator
|
||||||
|
hi def link rexEscape SpecialChar
|
||||||
|
hi def link rexInterpEdge Delimiter
|
||||||
|
hi def link rexString String
|
||||||
|
hi def link rexChar Character
|
||||||
|
hi def link rexComment Comment
|
||||||
|
|
||||||
|
let b:current_syntax = "rex"
|
||||||
@@ -1,20 +1,20 @@
|
|||||||
// Starts `dino lsp` and connects the editor to it. All the work is done by the compiler.
|
// Starts `rex lsp` and connects the editor to it. All the work is done by the compiler.
|
||||||
const vscode = require('vscode');
|
const vscode = require('vscode');
|
||||||
const { LanguageClient } = require('vscode-languageclient/node');
|
const { LanguageClient } = require('vscode-languageclient/node');
|
||||||
|
|
||||||
let client;
|
let client;
|
||||||
|
|
||||||
function activate() {
|
function activate() {
|
||||||
const command = vscode.workspace.getConfiguration('dino').get('serverPath') || 'dino';
|
const command = vscode.workspace.getConfiguration('rex').get('serverPath') || 'rex';
|
||||||
client = new LanguageClient(
|
client = new LanguageClient(
|
||||||
'dino',
|
'rex',
|
||||||
'Dino Language Server',
|
'Rex Language Server',
|
||||||
{ command, args: ['lsp'] },
|
{ command, args: ['lsp'] },
|
||||||
{ documentSelector: [{ scheme: 'file', language: 'dino' }] }
|
{ documentSelector: [{ scheme: 'file', language: 'rex' }] }
|
||||||
);
|
);
|
||||||
client.start().catch((err) => {
|
client.start().catch((err) => {
|
||||||
vscode.window.showErrorMessage(
|
vscode.window.showErrorMessage(
|
||||||
`Could not start "${command} lsp": ${err.message}. Put the dino program on your PATH or set "dino.serverPath".`
|
`Could not start "${command} lsp": ${err.message}. Put the rex program on your PATH or set "rex.serverPath".`
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-16
@@ -1,43 +1,43 @@
|
|||||||
{
|
{
|
||||||
"name": "dino",
|
"name": "rex",
|
||||||
"displayName": "Dino",
|
"displayName": "Rex",
|
||||||
"description": "Syntax highlighting, error checking and formatting for the Dino language",
|
"description": "Syntax highlighting, error checking and formatting for the Rex language",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"publisher": "dino-lang",
|
"publisher": "rex-lang",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": { "vscode": "^1.75.0" },
|
"engines": { "vscode": "^1.75.0" },
|
||||||
"categories": ["Programming Languages", "Formatters"],
|
"categories": ["Programming Languages", "Formatters"],
|
||||||
"activationEvents": ["onLanguage:dino"],
|
"activationEvents": ["onLanguage:rex"],
|
||||||
"main": "./extension.js",
|
"main": "./extension.js",
|
||||||
"dependencies": { "vscode-languageclient": "^9.0.1" },
|
"dependencies": { "vscode-languageclient": "^9.0.1" },
|
||||||
"contributes": {
|
"contributes": {
|
||||||
"languages": [
|
"languages": [
|
||||||
{
|
{
|
||||||
"id": "dino",
|
"id": "rex",
|
||||||
"aliases": ["Dino", "dino"],
|
"aliases": ["Rex", "rex"],
|
||||||
"extensions": [".dino"],
|
"extensions": [".rex"],
|
||||||
"configuration": "./language-configuration.json"
|
"configuration": "./language-configuration.json"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"grammars": [
|
"grammars": [
|
||||||
{
|
{
|
||||||
"language": "dino",
|
"language": "rex",
|
||||||
"scopeName": "source.dino",
|
"scopeName": "source.rex",
|
||||||
"path": "./syntaxes/dino.tmLanguage.json"
|
"path": "./syntaxes/rex.tmLanguage.json"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"configuration": {
|
"configuration": {
|
||||||
"title": "Dino",
|
"title": "Rex",
|
||||||
"properties": {
|
"properties": {
|
||||||
"dino.serverPath": {
|
"rex.serverPath": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"default": "dino",
|
"default": "rex",
|
||||||
"description": "The `dino` program that provides the language server (it is started as `dino lsp`)."
|
"description": "The `rex` program that provides the language server (it is started as `rex lsp`)."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"configurationDefaults": {
|
"configurationDefaults": {
|
||||||
"[dino]": {
|
"[rex]": {
|
||||||
"editor.insertSpaces": true,
|
"editor.insertSpaces": true,
|
||||||
"editor.tabSize": 4,
|
"editor.tabSize": 4,
|
||||||
"editor.formatOnSave": true
|
"editor.formatOnSave": true
|
||||||
|
|||||||
@@ -1,103 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
|
|
||||||
"name": "Dino",
|
|
||||||
"scopeName": "source.dino",
|
|
||||||
"patterns": [
|
|
||||||
{ "include": "#comments" },
|
|
||||||
{ "include": "#strings" },
|
|
||||||
{ "include": "#chars" },
|
|
||||||
{ "include": "#declarations" },
|
|
||||||
{ "include": "#keywords" },
|
|
||||||
{ "include": "#constants" },
|
|
||||||
{ "include": "#numbers" },
|
|
||||||
{ "include": "#types" },
|
|
||||||
{ "include": "#calls" },
|
|
||||||
{ "include": "#operators" }
|
|
||||||
],
|
|
||||||
"repository": {
|
|
||||||
"comments": {
|
|
||||||
"patterns": [
|
|
||||||
{ "name": "comment.line.double-slash.dino", "match": "//.*$" },
|
|
||||||
{ "name": "comment.block.dino", "begin": "/\\*", "end": "\\*/" }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"strings": {
|
|
||||||
"name": "string.quoted.double.dino",
|
|
||||||
"begin": "\"",
|
|
||||||
"end": "\"",
|
|
||||||
"patterns": [
|
|
||||||
{ "name": "constant.character.escape.dino", "match": "\\\\." },
|
|
||||||
{
|
|
||||||
"name": "meta.interpolation.dino",
|
|
||||||
"begin": "\\{",
|
|
||||||
"end": "\\}",
|
|
||||||
"beginCaptures": { "0": { "name": "punctuation.section.interpolation.begin.dino" } },
|
|
||||||
"endCaptures": { "0": { "name": "punctuation.section.interpolation.end.dino" } },
|
|
||||||
"patterns": [{ "include": "$self" }]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"chars": {
|
|
||||||
"name": "string.quoted.single.dino",
|
|
||||||
"match": "'(?:\\\\.|[^'\\\\])'",
|
|
||||||
"captures": {}
|
|
||||||
},
|
|
||||||
"declarations": {
|
|
||||||
"patterns": [
|
|
||||||
{
|
|
||||||
"match": "\\b(func)\\s+([A-Za-z_][A-Za-z0-9_]*)",
|
|
||||||
"captures": {
|
|
||||||
"1": { "name": "keyword.declaration.function.dino" },
|
|
||||||
"2": { "name": "entity.name.function.dino" }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"match": "\\b(struct|enum|interface)\\s+([A-Za-z_][A-Za-z0-9_]*)",
|
|
||||||
"captures": {
|
|
||||||
"1": { "name": "keyword.declaration.type.dino" },
|
|
||||||
"2": { "name": "entity.name.type.dino" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"keywords": {
|
|
||||||
"patterns": [
|
|
||||||
{ "name": "keyword.control.dino", "match": "\\b(if|else|for|in|step|match|return|break|continue)\\b" },
|
|
||||||
{ "name": "keyword.declaration.dino", "match": "\\b(func|var|const|import|struct|enum|interface|pub)\\b" },
|
|
||||||
{ "name": "storage.modifier.dino", "match": "\\b(shared|weak)\\b" }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"constants": {
|
|
||||||
"name": "constant.language.dino",
|
|
||||||
"match": "\\b(true|false|nil)\\b"
|
|
||||||
},
|
|
||||||
"numbers": {
|
|
||||||
"name": "constant.numeric.dino",
|
|
||||||
"match": "\\b[0-9][0-9_]*(?:\\.[0-9][0-9_]*)?\\b"
|
|
||||||
},
|
|
||||||
"types": {
|
|
||||||
"patterns": [
|
|
||||||
{
|
|
||||||
"name": "support.type.builtin.dino",
|
|
||||||
"match": "\\b(int|float|bool|char|string|error|map|i8|i16|i32|i64|u8|u16|u32|u64|f32|f64)\\b"
|
|
||||||
},
|
|
||||||
{ "name": "entity.name.type.dino", "match": "\\b[A-Z][A-Za-z0-9_]*\\b" }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"calls": {
|
|
||||||
"name": "entity.name.function.call.dino",
|
|
||||||
"match": "\\b[a-z_][A-Za-z0-9_]*(?=\\s*\\()"
|
|
||||||
},
|
|
||||||
"operators": {
|
|
||||||
"patterns": [
|
|
||||||
{ "name": "keyword.operator.arrow.dino", "match": "=>" },
|
|
||||||
{ "name": "keyword.operator.range.dino", "match": "\\.\\." },
|
|
||||||
{ "name": "keyword.operator.comparison.dino", "match": "==|!=|<=|>=|<|>" },
|
|
||||||
{ "name": "keyword.operator.logical.dino", "match": "&&|\\|\\||!" },
|
|
||||||
{ "name": "keyword.operator.assignment.dino", "match": "[-+*/%]?=" },
|
|
||||||
{ "name": "keyword.operator.arithmetic.dino", "match": "[-+*/%]" },
|
|
||||||
{ "name": "keyword.operator.optional.dino", "match": "\\?" }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
|
||||||
|
"name": "Rex",
|
||||||
|
"scopeName": "source.rex",
|
||||||
|
"patterns": [
|
||||||
|
{ "include": "#comments" },
|
||||||
|
{ "include": "#strings" },
|
||||||
|
{ "include": "#chars" },
|
||||||
|
{ "include": "#declarations" },
|
||||||
|
{ "include": "#keywords" },
|
||||||
|
{ "include": "#constants" },
|
||||||
|
{ "include": "#numbers" },
|
||||||
|
{ "include": "#types" },
|
||||||
|
{ "include": "#calls" },
|
||||||
|
{ "include": "#operators" }
|
||||||
|
],
|
||||||
|
"repository": {
|
||||||
|
"comments": {
|
||||||
|
"patterns": [
|
||||||
|
{ "name": "comment.line.double-slash.rex", "match": "//.*$" },
|
||||||
|
{ "name": "comment.block.rex", "begin": "/\\*", "end": "\\*/" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"strings": {
|
||||||
|
"name": "string.quoted.double.rex",
|
||||||
|
"begin": "\"",
|
||||||
|
"end": "\"",
|
||||||
|
"patterns": [
|
||||||
|
{ "name": "constant.character.escape.rex", "match": "\\\\." },
|
||||||
|
{
|
||||||
|
"name": "meta.interpolation.rex",
|
||||||
|
"begin": "\\{",
|
||||||
|
"end": "\\}",
|
||||||
|
"beginCaptures": { "0": { "name": "punctuation.section.interpolation.begin.rex" } },
|
||||||
|
"endCaptures": { "0": { "name": "punctuation.section.interpolation.end.rex" } },
|
||||||
|
"patterns": [{ "include": "$self" }]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"chars": {
|
||||||
|
"name": "string.quoted.single.rex",
|
||||||
|
"match": "'(?:\\\\.|[^'\\\\])'",
|
||||||
|
"captures": {}
|
||||||
|
},
|
||||||
|
"declarations": {
|
||||||
|
"patterns": [
|
||||||
|
{
|
||||||
|
"match": "\\b(func)\\s+([A-Za-z_][A-Za-z0-9_]*)",
|
||||||
|
"captures": {
|
||||||
|
"1": { "name": "keyword.declaration.function.rex" },
|
||||||
|
"2": { "name": "entity.name.function.rex" }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "\\b(struct|enum|interface)\\s+([A-Za-z_][A-Za-z0-9_]*)",
|
||||||
|
"captures": {
|
||||||
|
"1": { "name": "keyword.declaration.type.rex" },
|
||||||
|
"2": { "name": "entity.name.type.rex" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"keywords": {
|
||||||
|
"patterns": [
|
||||||
|
{ "name": "keyword.control.rex", "match": "\\b(if|else|for|in|step|match|return|break|continue)\\b" },
|
||||||
|
{ "name": "keyword.declaration.rex", "match": "\\b(func|var|const|import|struct|enum|interface|pub)\\b" },
|
||||||
|
{ "name": "storage.modifier.rex", "match": "\\b(shared|weak)\\b" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"constants": {
|
||||||
|
"name": "constant.language.rex",
|
||||||
|
"match": "\\b(true|false|nil)\\b"
|
||||||
|
},
|
||||||
|
"numbers": {
|
||||||
|
"name": "constant.numeric.rex",
|
||||||
|
"match": "\\b[0-9][0-9_]*(?:\\.[0-9][0-9_]*)?\\b"
|
||||||
|
},
|
||||||
|
"types": {
|
||||||
|
"patterns": [
|
||||||
|
{
|
||||||
|
"name": "support.type.builtin.rex",
|
||||||
|
"match": "\\b(int|float|bool|char|string|error|map|i8|i16|i32|i64|u8|u16|u32|u64|f32|f64)\\b"
|
||||||
|
},
|
||||||
|
{ "name": "entity.name.type.rex", "match": "\\b[A-Z][A-Za-z0-9_]*\\b" }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"calls": {
|
||||||
|
"name": "entity.name.function.call.rex",
|
||||||
|
"match": "\\b[a-z_][A-Za-z0-9_]*(?=\\s*\\()"
|
||||||
|
},
|
||||||
|
"operators": {
|
||||||
|
"patterns": [
|
||||||
|
{ "name": "keyword.operator.arrow.rex", "match": "=>" },
|
||||||
|
{ "name": "keyword.operator.range.rex", "match": "\\.\\." },
|
||||||
|
{ "name": "keyword.operator.comparison.rex", "match": "==|!=|<=|>=|<|>" },
|
||||||
|
{ "name": "keyword.operator.logical.rex", "match": "&&|\\|\\||!" },
|
||||||
|
{ "name": "keyword.operator.assignment.rex", "match": "[-+*/%]?=" },
|
||||||
|
{ "name": "keyword.operator.arithmetic.rex", "match": "[-+*/%]" },
|
||||||
|
{ "name": "keyword.operator.optional.rex", "match": "\\?" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File renamed without changes.
@@ -21,7 +21,7 @@ struct Player {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var win = gfx.open("Dino", 800, 600)
|
var win = gfx.open("Rex", 800, 600)
|
||||||
var player = Player{pos: Vec2{100, 100}, vel: Vec2{200, 150}, size: 32}
|
var player = Player{pos: Vec2{100, 100}, vel: Vec2{200, 150}, size: 32}
|
||||||
|
|
||||||
for win.is_open() {
|
for win.is_open() {
|
||||||
@@ -15,7 +15,7 @@ struct Editor {
|
|||||||
func main() {
|
func main() {
|
||||||
var doc = shared Document{title: "Notes", text: ""}
|
var doc = shared Document{title: "Notes", text: ""}
|
||||||
|
|
||||||
var win = ui.window("Dino Notes", 640, 480)
|
var win = ui.window("Rex Notes", 640, 480)
|
||||||
var editor = Editor{doc: doc}
|
var editor = Editor{doc: doc}
|
||||||
|
|
||||||
win.on_key(func(k: ui.Key) {
|
win.on_key(func(k: ui.Key) {
|
||||||
File renamed without changes.
@@ -4,6 +4,6 @@ a true true 97 B a!
|
|||||||
1 é
|
1 é
|
||||||
3 😀
|
3 😀
|
||||||
h é l 2
|
h é l 2
|
||||||
DINO q plus newline other
|
REX q plus newline other
|
||||||
{b: 1, a: 3, n: 2}
|
{b: 1, a: 3, n: 2}
|
||||||
abc true true true
|
abc true true true
|
||||||
@@ -23,7 +23,7 @@ func main() {
|
|||||||
for i, ch in "aé😀" { print(i, ch) }
|
for i, ch in "aé😀" { print(i, ch) }
|
||||||
print(s[0], s[1], s[3], s[s.len() - 1])
|
print(s[0], s[1], s[3], s[s.len() - 1])
|
||||||
var up = ""
|
var up = ""
|
||||||
for ch in "dino" { up += string(ch.upper()) }
|
for ch in "rex" { up += string(ch.upper()) }
|
||||||
print(up, 'Q'.lower(), kind('+'), kind('\n'), kind('z'))
|
print(up, 'Q'.lower(), kind('+'), kind('\n'), kind('z'))
|
||||||
var counts: map[char, int] = {}
|
var counts: map[char, int] = {}
|
||||||
for ch in "banana" { counts[ch] += 1 }
|
for ch in "banana" { counts[ch] += 1 }
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,3 +0,0 @@
|
|||||||
func main() {
|
|
||||||
print("Hello, Dino!")
|
|
||||||
}
|
|
||||||
@@ -1 +1 @@
|
|||||||
Hello, Dino!
|
Hello, Rex!
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
func main() {
|
||||||
|
print("Hello, Rex!")
|
||||||
|
}
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -10,4 +10,4 @@ sq[4] = 16
|
|||||||
[] 0
|
[] 0
|
||||||
[a, b] 2 items
|
[a, b] 2 items
|
||||||
[1.0, 2.5, 3.0]
|
[1.0, 2.5, 3.0]
|
||||||
dino-lang 4
|
rex-lang 3
|
||||||
@@ -55,6 +55,6 @@ func main() {
|
|||||||
var floats: []float = [1, 2.5, 3]
|
var floats: []float = [1, 2.5, 3]
|
||||||
print(floats)
|
print(floats)
|
||||||
|
|
||||||
var words = ["dino", "lang"]
|
var words = ["rex", "lang"]
|
||||||
print(words[0] + "-" + words[1], words[0].len())
|
print(words[0] + "-" + words[1], words[0].len())
|
||||||
}
|
}
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -36,13 +36,13 @@ func main() {
|
|||||||
time.sleep(0.01)
|
time.sleep(0.01)
|
||||||
print(time.now() - t0 >= 0.01)
|
print(time.now() - t0 >= 0.01)
|
||||||
|
|
||||||
var err4 = os.write_file("/tmp/dino_std_test.txt", "one two\nthree\n\nfour five six\n")
|
var err4 = os.write_file("/tmp/rex_std_test.txt", "one two\nthree\n\nfour five six\n")
|
||||||
print(err4)
|
print(err4)
|
||||||
var lines, words, e5 = count("/tmp/dino_std_test.txt")
|
var lines, words, e5 = count("/tmp/rex_std_test.txt")
|
||||||
print(lines, words, e5)
|
print(lines, words, e5)
|
||||||
var l2, w2, e6 = count("/tmp/definitely/not/here.txt")
|
var l2, w2, e6 = count("/tmp/definitely/not/here.txt")
|
||||||
print(l2, w2, e6)
|
print(l2, w2, e6)
|
||||||
print(os.exists("/tmp/dino_std_test.txt"), os.exists("/nope"))
|
print(os.exists("/tmp/rex_std_test.txt"), os.exists("/nope"))
|
||||||
print(os.args.len(), os.env("HOME_NOPE_X") == nil)
|
print(os.args.len(), os.env("HOME_NOPE_X") == nil)
|
||||||
var home = os.env("PATH")
|
var home = os.env("PATH")
|
||||||
if home != nil { print(home.len() > 0) }
|
if home != nil { print(home.len() > 0) }
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
Hello, Dino!
|
Hello, Rex!
|
||||||
n is 3, doubled 6, big? true
|
n is 3, doubled 6, big? true
|
||||||
pi is about 3.75
|
pi is about 3.75
|
||||||
true true false
|
true true false
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ func greet(name: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
var name = "Dino"
|
var name = "Rex"
|
||||||
print(greet(name))
|
print(greet(name))
|
||||||
var n = 3
|
var n = 3
|
||||||
print("n is {n}, doubled {n * 2}, big? {n > 2}")
|
print("n is {n}, doubled {n * 2}, big? {n > 2}")
|
||||||
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,5 @@
|
|||||||
// A ball bouncing around a window, drawn with raylib (https://www.raylib.com).
|
// A ball bouncing around a window, drawn with raylib (https://www.raylib.com).
|
||||||
// Needs raylib installed: `dino run bounce.dino`. Space adds a ball, Escape quits.
|
// Needs raylib installed: `rex run bounce.rex`. Space adds a ball, Escape quits.
|
||||||
|
|
||||||
import "raylib.h"
|
import "raylib.h"
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ func new_ball(n: int): Ball {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
raylib.InitWindow(WIDTH, HEIGHT, "Dino + raylib")
|
raylib.InitWindow(WIDTH, HEIGHT, "Rex + raylib")
|
||||||
raylib.SetTargetFPS(60)
|
raylib.SetTargetFPS(60)
|
||||||
var balls = [new_ball(0)]
|
var balls = [new_ball(0)]
|
||||||
for !raylib.WindowShouldClose() {
|
for !raylib.WindowShouldClose() {
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -29,7 +29,7 @@
|
|||||||
<path d="M788.0799999999999 649.88Q806.96 649.88 821.2 657.56Q835.4399999999999 665.24 843.12 677.72V652.44H897.8399999999999V831.0H843.12V805.72Q835.12 818.2 820.88 825.88Q806.64 833.56 787.76 833.56Q766.0 833.56 748.0799999999999 822.2Q730.16 810.84 719.76 789.88Q709.36 768.92 709.36 741.4Q709.36 713.88 719.76 693.0799999999999Q730.16 672.28 748.0799999999999 661.0799999999999Q766.0 649.88 788.0799999999999 649.88ZM804.0799999999999 697.56Q787.76 697.56 776.4 709.24Q765.04 720.92 765.04 741.4Q765.04 761.88 776.4 773.88Q787.76 785.88 804.0799999999999 785.88Q820.4 785.88 831.76 774.04Q843.12 762.2 843.12 741.72Q843.12 721.24 831.76 709.4Q820.4 697.56 804.0799999999999 697.56Z" fill="#000" transform="rotate(2 809.0 719.0)" stroke="#000" stroke-linejoin="round" stroke-width="22"/>
|
<path d="M788.0799999999999 649.88Q806.96 649.88 821.2 657.56Q835.4399999999999 665.24 843.12 677.72V652.44H897.8399999999999V831.0H843.12V805.72Q835.12 818.2 820.88 825.88Q806.64 833.56 787.76 833.56Q766.0 833.56 748.0799999999999 822.2Q730.16 810.84 719.76 789.88Q709.36 768.92 709.36 741.4Q709.36 713.88 719.76 693.0799999999999Q730.16 672.28 748.0799999999999 661.0799999999999Q766.0 649.88 788.0799999999999 649.88ZM804.0799999999999 697.56Q787.76 697.56 776.4 709.24Q765.04 720.92 765.04 741.4Q765.04 761.88 776.4 773.88Q787.76 785.88 804.0799999999999 785.88Q820.4 785.88 831.76 774.04Q843.12 762.2 843.12 741.72Q843.12 721.24 831.76 709.4Q820.4 697.56 804.0799999999999 697.56Z" fill="#000" transform="rotate(2 809.0 719.0)" stroke="#000" stroke-linejoin="round" stroke-width="22"/>
|
||||||
<path d="M1111.12 732.68V837.0H1056.72V740.04Q1056.72 722.12 1047.44 712.2Q1038.1599999999999 702.28 1022.4799999999999 702.28Q1006.8 702.28 997.52 712.2Q988.24 722.12 988.24 740.04V837.0H933.52V658.44H988.24V682.12Q996.56 670.28 1010.64 663.4Q1024.72 656.52 1042.32 656.52Q1073.6799999999998 656.52 1092.3999999999999 676.8399999999999Q1111.12 697.16 1111.12 732.68Z" fill="#000" transform="rotate(-4 1021.5 725.0)" stroke="#000" stroke-linejoin="round" stroke-width="22"/>
|
<path d="M1111.12 732.68V837.0H1056.72V740.04Q1056.72 722.12 1047.44 712.2Q1038.1599999999999 702.28 1022.4799999999999 702.28Q1006.8 702.28 997.52 712.2Q988.24 722.12 988.24 740.04V837.0H933.52V658.44H988.24V682.12Q996.56 670.28 1010.64 663.4Q1024.72 656.52 1042.32 656.52Q1073.6799999999998 656.52 1092.3999999999999 676.8399999999999Q1111.12 697.16 1111.12 732.68Z" fill="#000" transform="rotate(-4 1021.5 725.0)" stroke="#000" stroke-linejoin="round" stroke-width="22"/>
|
||||||
<path d="M1268.08 675.72V650.44H1322.8V828.68Q1322.8 853.32 1313.04 873.32Q1303.28 893.32 1283.28 905.1600000000001Q1263.28 917.0 1233.52 917.0Q1193.84 917.0 1169.1999999999998 898.28Q1144.56 879.56 1141.04 847.56H1195.12Q1197.6799999999998 857.8 1207.2799999999997 863.72Q1216.8799999999999 869.64 1230.9599999999998 869.64Q1247.9199999999998 869.64 1258.0 859.88Q1268.08 850.12 1268.08 828.68V803.4Q1260.08 815.88 1246.0 823.72Q1231.9199999999998 831.56 1213.04 831.56Q1190.9599999999998 831.56 1173.04 820.2Q1155.12 808.84 1144.7199999999998 787.88Q1134.32 766.92 1134.32 739.4Q1134.32 711.88 1144.7199999999998 691.0799999999999Q1155.12 670.28 1173.04 659.0799999999999Q1190.9599999999998 647.88 1213.04 647.88Q1231.9199999999998 647.88 1246.1599999999999 655.56Q1260.3999999999999 663.24 1268.08 675.72ZM1229.04 695.56Q1212.7199999999998 695.56 1201.36 707.24Q1190.0 718.92 1190.0 739.4Q1190.0 759.88 1201.36 771.88Q1212.7199999999998 783.88 1229.04 783.88Q1245.36 783.88 1256.7199999999998 772.04Q1268.08 760.2 1268.08 739.72Q1268.08 719.24 1256.7199999999998 707.4Q1245.36 695.56 1229.04 695.56Z" fill="#000" transform="rotate(3 1234.0 717.0)" stroke="#000" stroke-linejoin="round" stroke-width="22"/></clipPath>
|
<path d="M1268.08 675.72V650.44H1322.8V828.68Q1322.8 853.32 1313.04 873.32Q1303.28 893.32 1283.28 905.1600000000001Q1263.28 917.0 1233.52 917.0Q1193.84 917.0 1169.1999999999998 898.28Q1144.56 879.56 1141.04 847.56H1195.12Q1197.6799999999998 857.8 1207.2799999999997 863.72Q1216.8799999999999 869.64 1230.9599999999998 869.64Q1247.9199999999998 869.64 1258.0 859.88Q1268.08 850.12 1268.08 828.68V803.4Q1260.08 815.88 1246.0 823.72Q1231.9199999999998 831.56 1213.04 831.56Q1190.9599999999998 831.56 1173.04 820.2Q1155.12 808.84 1144.7199999999998 787.88Q1134.32 766.92 1134.32 739.4Q1134.32 711.88 1144.7199999999998 691.0799999999999Q1155.12 670.28 1173.04 659.0799999999999Q1190.9599999999998 647.88 1213.04 647.88Q1231.9199999999998 647.88 1246.1599999999999 655.56Q1260.3999999999999 663.24 1268.08 675.72ZM1229.04 695.56Q1212.7199999999998 695.56 1201.36 707.24Q1190.0 718.92 1190.0 739.4Q1190.0 759.88 1201.36 771.88Q1212.7199999999998 783.88 1229.04 783.88Q1245.36 783.88 1256.7199999999998 772.04Q1268.08 760.2 1268.08 739.72Q1268.08 719.24 1256.7199999999998 707.4Q1245.36 695.56 1229.04 695.56Z" fill="#000" transform="rotate(3 1234.0 717.0)" stroke="#000" stroke-linejoin="round" stroke-width="22"/></clipPath>
|
||||||
<symbol id="ldino" viewBox="0 0 400 420">
|
<symbol id="lrex" viewBox="0 0 400 420">
|
||||||
<g stroke="#8FD293" stroke-width="12" stroke-linejoin="round" stroke-linecap="round">
|
<g stroke="#8FD293" stroke-width="12" stroke-linejoin="round" stroke-linecap="round">
|
||||||
|
|
||||||
<path d="M300,300 C345,300 372,282 384,248 C390,270 378,318 330,345 C318,352 304,352 296,348 Z" fill="#5DB862"/>
|
<path d="M300,300 C345,300 372,282 384,248 C390,270 378,318 330,345 C318,352 304,352 296,348 Z" fill="#5DB862"/>
|
||||||
@@ -136,6 +136,6 @@
|
|||||||
<g clip-path="url(#clipBot)"><rect x="560" y="540" width="800" height="400" fill="url(#spikes)"/></g>
|
<g clip-path="url(#clipBot)"><rect x="560" y="540" width="800" height="400" fill="url(#spikes)"/></g>
|
||||||
|
|
||||||
<!-- mascot -->
|
<!-- mascot -->
|
||||||
<use href="#ldino" x="205" y="505" width="400" height="420"/>
|
<use href="#lrex" x="205" y="505" width="400" height="420"/>
|
||||||
</g>
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 35 KiB |
File renamed without changes.
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 3.2 KiB |
+33
-33
@@ -1,5 +1,5 @@
|
|||||||
//! Reads a C header for `import "zlib.h"`: runs the C preprocessor on it, then picks out the
|
//! Reads a C header for `import "zlib.h"`: runs the C preprocessor on it, then picks out the
|
||||||
//! functions, structs, constants and pointer types that Dino code can use.
|
//! functions, structs, constants and pointer types that Rex code can use.
|
||||||
//!
|
//!
|
||||||
//! The generated C program includes the header itself, so nothing here has to be exact about
|
//! The generated C program includes the header itself, so nothing here has to be exact about
|
||||||
//! how C declares things: it only has to know enough to check calls and convert values.
|
//! how C declares things: it only has to know enough to check calls and convert values.
|
||||||
@@ -11,21 +11,21 @@ use std::sync::{Mutex, OnceLock};
|
|||||||
|
|
||||||
use crate::types::{Num, Ty};
|
use crate::types::{Num, Ty};
|
||||||
|
|
||||||
/// A C type as Dino sees it.
|
/// A C type as Rex sees it.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub enum CTy {
|
pub enum CTy {
|
||||||
Void,
|
Void,
|
||||||
/// A number or `bool` (never `Str`).
|
/// A number or `bool` (never `Str`).
|
||||||
Num(Ty),
|
Num(Ty),
|
||||||
/// `char *` / `const char *`: Dino strings.
|
/// `char *` / `const char *`: Rex strings.
|
||||||
Str,
|
Str,
|
||||||
/// A pointer Dino can only pass around: `SDL_Window *`, `gzFile`, `void *` (`"pointer"`).
|
/// A pointer Rex can only pass around: `SDL_Window *`, `gzFile`, `void *` (`"pointer"`).
|
||||||
Handle(String),
|
Handle(String),
|
||||||
/// A struct passed by value, by its Dino name.
|
/// A struct passed by value, by its Rex name.
|
||||||
Struct(String),
|
Struct(String),
|
||||||
/// A pointer to a number or struct: filled in by the function (or only read, if `konst`).
|
/// A pointer to a number or struct: filled in by the function (or only read, if `konst`).
|
||||||
Ptr { to: Box<CTy>, konst: bool },
|
Ptr { to: Box<CTy>, konst: bool },
|
||||||
/// Something Dino can't pass; the text says what.
|
/// Something Rex can't pass; the text says what.
|
||||||
Unsupported(String),
|
Unsupported(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,13 +34,13 @@ pub struct Func {
|
|||||||
pub name: String,
|
pub name: String,
|
||||||
pub params: Vec<(String, CTy)>,
|
pub params: Vec<(String, CTy)>,
|
||||||
pub ret: CTy,
|
pub ret: CTy,
|
||||||
/// Why the function can't be called from Dino, if it can't.
|
/// Why the function can't be called from Rex, if it can't.
|
||||||
pub problem: Option<String>,
|
pub problem: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Struct {
|
pub struct Struct {
|
||||||
/// The Dino name (the typedef name if there is one, else the struct tag).
|
/// The Rex name (the typedef name if there is one, else the struct tag).
|
||||||
pub name: String,
|
pub name: String,
|
||||||
/// How C spells the type: `Color` or `struct timeval`.
|
/// How C spells the type: `Color` or `struct timeval`.
|
||||||
pub c: String,
|
pub c: String,
|
||||||
@@ -52,7 +52,7 @@ pub enum Value {
|
|||||||
Int(i64),
|
Int(i64),
|
||||||
Float(f64),
|
Float(f64),
|
||||||
Str(String),
|
Str(String),
|
||||||
/// A macro that stands for a struct value, like raylib's `RED`: the struct's Dino name.
|
/// A macro that stands for a struct value, like raylib's `RED`: the struct's Rex name.
|
||||||
Struct(String),
|
Struct(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,12 +62,12 @@ pub struct Const {
|
|||||||
pub value: Value,
|
pub value: Value,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Everything Dino knows about one header.
|
/// Everything Rex knows about one header.
|
||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
pub struct Lib {
|
pub struct Lib {
|
||||||
/// As written in the import: `zlib.h`, `SDL2/SDL.h`.
|
/// As written in the import: `zlib.h`, `SDL2/SDL.h`.
|
||||||
pub header: String,
|
pub header: String,
|
||||||
/// The default name in Dino code: `zlib`, `SDL`.
|
/// The default name in Rex code: `zlib`, `SDL`.
|
||||||
pub prefix: String,
|
pub prefix: String,
|
||||||
/// Flags for compiling (`-I...`, `-D...`) and for linking (`-l...`).
|
/// Flags for compiling (`-I...`, `-D...`) and for linking (`-l...`).
|
||||||
pub cflags: Vec<String>,
|
pub cflags: Vec<String>,
|
||||||
@@ -77,7 +77,7 @@ pub struct Lib {
|
|||||||
pub funcs: Vec<Func>,
|
pub funcs: Vec<Func>,
|
||||||
pub structs: Vec<Struct>,
|
pub structs: Vec<Struct>,
|
||||||
pub consts: Vec<Const>,
|
pub consts: Vec<Const>,
|
||||||
/// Pointer types that can be written as Dino types: `gzFile`, `SDL_Window`.
|
/// Pointer types that can be written as Rex types: `gzFile`, `SDL_Window`.
|
||||||
pub handles: Vec<String>,
|
pub handles: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,7 +94,7 @@ impl Lib {
|
|||||||
pub fn has_handle(&self, name: &str) -> bool {
|
pub fn has_handle(&self, name: &str) -> bool {
|
||||||
self.handles.iter().any(|h| h == name)
|
self.handles.iter().any(|h| h == name)
|
||||||
}
|
}
|
||||||
/// How a C type reads in Dino.
|
/// How a C type reads in Rex.
|
||||||
pub fn type_text(&self, t: &CTy) -> String {
|
pub fn type_text(&self, t: &CTy) -> String {
|
||||||
match t {
|
match t {
|
||||||
CTy::Void => "nothing".into(),
|
CTy::Void => "nothing".into(),
|
||||||
@@ -122,12 +122,12 @@ impl Lib {
|
|||||||
format!("{}({}){ret}", f.name, params.join(", "))
|
format!("{}({}){ret}", f.name, params.join(", "))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One line about a name of the header, for hover and `dino header`.
|
/// One line about a name of the header, for hover and `rex header`.
|
||||||
pub fn describe(&self, name: &str) -> Option<String> {
|
pub fn describe(&self, name: &str) -> Option<String> {
|
||||||
if let Some(f) = self.func(name) {
|
if let Some(f) = self.func(name) {
|
||||||
let mut s = format!("func {}", self.signature(f));
|
let mut s = format!("func {}", self.signature(f));
|
||||||
if let Some(p) = &f.problem {
|
if let Some(p) = &f.problem {
|
||||||
s.push_str(&format!("\n(can't be called from Dino: it {p})"));
|
s.push_str(&format!("\n(can't be called from Rex: it {p})"));
|
||||||
}
|
}
|
||||||
return Some(s);
|
return Some(s);
|
||||||
}
|
}
|
||||||
@@ -150,7 +150,7 @@ impl Lib {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Every name the header gives Dino, for messages and completion.
|
/// Every name the header gives Rex, for messages and completion.
|
||||||
pub fn names(&self) -> Vec<&str> {
|
pub fn names(&self) -> Vec<&str> {
|
||||||
let mut v: Vec<&str> = self.funcs.iter().filter(|f| f.problem.is_none()).map(|f| f.name.as_str()).collect();
|
let mut v: Vec<&str> = self.funcs.iter().filter(|f| f.problem.is_none()).map(|f| f.name.as_str()).collect();
|
||||||
v.extend(self.structs.iter().map(|s| s.name.as_str()));
|
v.extend(self.structs.iter().map(|s| s.name.as_str()));
|
||||||
@@ -160,7 +160,7 @@ impl Lib {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The name a header gets in Dino code: `SDL2/SDL.h` -> `SDL`, `my-lib.h` -> `my_lib`.
|
/// The name a header gets in Rex code: `SDL2/SDL.h` -> `SDL`, `my-lib.h` -> `my_lib`.
|
||||||
pub fn prefix_of(header: &str) -> String {
|
pub fn prefix_of(header: &str) -> String {
|
||||||
let file = header.rsplit('/').next().unwrap_or(header);
|
let file = header.rsplit('/').next().unwrap_or(header);
|
||||||
let stem = file.split('.').next().unwrap_or(file);
|
let stem = file.split('.').next().unwrap_or(file);
|
||||||
@@ -171,7 +171,7 @@ pub fn prefix_of(header: &str) -> String {
|
|||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read a header. `dir` is the folder of the Dino file that imports it (local headers and their
|
/// Read a header. `dir` is the folder of the Rex file that imports it (local headers and their
|
||||||
/// `.c`/`.cpp` files are found there); `link` is the library named with `link "..."`.
|
/// `.c`/`.cpp` files are found there); `link` is the library named with `link "..."`.
|
||||||
pub fn load(header: &str, dir: &Path, link: Option<&str>) -> Result<Lib, String> {
|
pub fn load(header: &str, dir: &Path, link: Option<&str>) -> Result<Lib, String> {
|
||||||
type Key = (String, PathBuf, Option<String>, Option<std::time::SystemTime>);
|
type Key = (String, PathBuf, Option<String>, Option<std::time::SystemTime>);
|
||||||
@@ -360,7 +360,7 @@ fn lex(text: &str) -> Lexed {
|
|||||||
let def = def.trim_start();
|
let def = def.trim_start();
|
||||||
let name_end = def.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(def.len());
|
let name_end = def.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(def.len());
|
||||||
let name = def[..name_end].to_string();
|
let name = def[..name_end].to_string();
|
||||||
// function-like macros can't be used from Dino
|
// function-like macros can't be used from Rex
|
||||||
if !def[name_end..].starts_with('(') && !name.is_empty() {
|
if !def[name_end..].starts_with('(') && !name.is_empty() {
|
||||||
let body = lex_line(&def[name_end..], cur);
|
let body = lex_line(&def[name_end..], cur);
|
||||||
defines.retain(|d| d.0 != name);
|
defines.retain(|d| d.0 != name);
|
||||||
@@ -399,7 +399,7 @@ fn lex_line(line: &str, file: u32) -> Vec<Tok> {
|
|||||||
i += 1;
|
i += 1;
|
||||||
}
|
}
|
||||||
let word = &line[s..i];
|
let word = &line[s..i];
|
||||||
// `L"..."`, `u8"..."`: wide strings are not for Dino; keep the prefix as a name
|
// `L"..."`, `u8"..."`: wide strings are not for Rex; keep the prefix as a name
|
||||||
out.push(Tok { t: T::Id(word.to_string()), file });
|
out.push(Tok { t: T::Id(word.to_string()), file });
|
||||||
} else if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).map_or(false, |d| d.is_ascii_digit())) {
|
} else if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).map_or(false, |d| d.is_ascii_digit())) {
|
||||||
let s = i;
|
let s = i;
|
||||||
@@ -475,7 +475,7 @@ fn lex_line(line: &str, file: u32) -> Vec<Tok> {
|
|||||||
|
|
||||||
// ---------- C declarations ----------
|
// ---------- C declarations ----------
|
||||||
|
|
||||||
/// A C type as written, before Dino decides what it can do with it.
|
/// A C type as written, before Rex decides what it can do with it.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
enum Raw {
|
enum Raw {
|
||||||
Void,
|
Void,
|
||||||
@@ -496,7 +496,7 @@ enum Raw {
|
|||||||
|
|
||||||
struct RawStruct {
|
struct RawStruct {
|
||||||
fields: Option<Vec<(String, Raw)>>,
|
fields: Option<Vec<(String, Raw)>>,
|
||||||
/// Something in the body Dino can't copy field by field (an array, an unnamed member).
|
/// Something in the body Rex can't copy field by field (an array, an unnamed member).
|
||||||
problem: Option<String>,
|
problem: Option<String>,
|
||||||
union: bool,
|
union: bool,
|
||||||
}
|
}
|
||||||
@@ -858,7 +858,7 @@ impl Parser {
|
|||||||
let Some((base, konst)) = self.specifiers() else {
|
let Some((base, konst)) = self.specifiers() else {
|
||||||
self.pos = start;
|
self.pos = start;
|
||||||
self.recover();
|
self.recover();
|
||||||
problem.get_or_insert("has a field Dino can't read".into());
|
problem.get_or_insert("has a field Rex can't read".into());
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if self.eat(";") {
|
if self.eat(";") {
|
||||||
@@ -1086,7 +1086,7 @@ impl Parser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- from C declarations to what Dino can use ----------
|
// ---------- from C declarations to what Rex can use ----------
|
||||||
|
|
||||||
fn wanted(&self, file: u32) -> bool {
|
fn wanted(&self, file: u32) -> bool {
|
||||||
let Some(main) = self.main else { return true };
|
let Some(main) = self.main else { return true };
|
||||||
@@ -1145,7 +1145,7 @@ impl Parser {
|
|||||||
(t, last)
|
(t, last)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The Dino name of a struct tag: a typedef naming exactly that struct, else the tag.
|
/// The Rex name of a struct tag: a typedef naming exactly that struct, else the tag.
|
||||||
fn struct_name(&self, tag: &str, names: &HashMap<String, String>) -> String {
|
fn struct_name(&self, tag: &str, names: &HashMap<String, String>) -> String {
|
||||||
names.get(tag).cloned().unwrap_or_else(|| tag.to_string())
|
names.get(tag).cloned().unwrap_or_else(|| tag.to_string())
|
||||||
}
|
}
|
||||||
@@ -1174,7 +1174,7 @@ impl Parser {
|
|||||||
if !union && mapped.contains(tag) {
|
if !union && mapped.contains(tag) {
|
||||||
CTy::Struct(name)
|
CTy::Struct(name)
|
||||||
} else {
|
} else {
|
||||||
CTy::Unsupported(format!("passes a `{name}` by value, and Dino can't build that type"))
|
CTy::Unsupported(format!("passes a `{name}` by value, and Rex can't build that type"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Raw::Ptr(inner, konst) => {
|
Raw::Ptr(inner, konst) => {
|
||||||
@@ -1195,7 +1195,7 @@ impl Parser {
|
|||||||
CTy::Handle(name)
|
CTy::Handle(name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Raw::Func { .. } => CTy::Unsupported("takes a callback function, which Dino can't pass yet".into()),
|
Raw::Func { .. } => CTy::Unsupported("takes a callback function, which Rex can't pass yet".into()),
|
||||||
// `sqlite3 **db`: the function hands back a pointer through it
|
// `sqlite3 **db`: the function hands back a pointer through it
|
||||||
Raw::Ptr(..) if typedef.is_none() => match self.convert(inner, mapped, names) {
|
Raw::Ptr(..) if typedef.is_none() => match self.convert(inner, mapped, names) {
|
||||||
h @ CTy::Handle(_) => CTy::Ptr { to: Box::new(h), konst: *konst },
|
h @ CTy::Handle(_) => CTy::Ptr { to: Box::new(h), konst: *konst },
|
||||||
@@ -1206,12 +1206,12 @@ impl Parser {
|
|||||||
}
|
}
|
||||||
Raw::Array(_) => CTy::Unsupported("uses a C array type".into()),
|
Raw::Array(_) => CTy::Unsupported("uses a C array type".into()),
|
||||||
Raw::Func { .. } => CTy::Unsupported("uses a function type".into()),
|
Raw::Func { .. } => CTy::Unsupported("uses a function type".into()),
|
||||||
Raw::Named(n) | Raw::Unknown(n) => CTy::Unsupported(format!("uses the C type `{n}`, which Dino doesn't know")),
|
Raw::Named(n) | Raw::Unknown(n) => CTy::Unsupported(format!("uses the C type `{n}`, which Rex doesn't know")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn finish(mut self, lib: &mut Lib) {
|
fn finish(mut self, lib: &mut Lib) {
|
||||||
// struct tag -> Dino name: `typedef struct Color {...} Color;` and `typedef struct {...} Color;`
|
// struct tag -> Rex name: `typedef struct Color {...} Color;` and `typedef struct {...} Color;`
|
||||||
let mut names: HashMap<String, String> = HashMap::new();
|
let mut names: HashMap<String, String> = HashMap::new();
|
||||||
for (n, _) in &self.typedef_order {
|
for (n, _) in &self.typedef_order {
|
||||||
if let Some(Raw::Struct { tag, .. }) = self.typedefs.get(n) {
|
if let Some(Raw::Struct { tag, .. }) = self.typedefs.get(n) {
|
||||||
@@ -1222,7 +1222,7 @@ impl Parser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// which structs Dino can copy field by field (all fields numbers, pointers or such structs)
|
// which structs Rex can copy field by field (all fields numbers, pointers or such structs)
|
||||||
let mut mapped: HashSet<String> = HashSet::new();
|
let mut mapped: HashSet<String> = HashSet::new();
|
||||||
loop {
|
loop {
|
||||||
let mut changed = false;
|
let mut changed = false;
|
||||||
@@ -1302,7 +1302,7 @@ impl Parser {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let CTy::Ptr { .. } = ret {
|
if let CTy::Ptr { .. } = ret {
|
||||||
// a returned pointer to numbers: Dino can only hold on to it
|
// a returned pointer to numbers: Rex can only hold on to it
|
||||||
}
|
}
|
||||||
let ret = match ret {
|
let ret = match ret {
|
||||||
CTy::Ptr { .. } => CTy::Handle("pointer".into()),
|
CTy::Ptr { .. } => CTy::Handle("pointer".into()),
|
||||||
@@ -1625,7 +1625,7 @@ mod tests {
|
|||||||
typedef struct Window Window;\n\
|
typedef struct Window Window;\n\
|
||||||
typedef struct gz_s *gzFile;\n\
|
typedef struct gz_s *gzFile;\n\
|
||||||
enum { A = 1, B, C = A << 4 };\n\
|
enum { A = 1, B, C = A << 4 };\n\
|
||||||
#define NAME \"dino\"\n\
|
#define NAME \"rex\"\n\
|
||||||
#define RED (Color){ 255, 0, 0, 255 }\n\
|
#define RED (Color){ 255, 0, 0, 255 }\n\
|
||||||
#define FLAG (0x10u | 2)\n\
|
#define FLAG (0x10u | 2)\n\
|
||||||
#define PI 3.5\n\
|
#define PI 3.5\n\
|
||||||
@@ -1655,7 +1655,7 @@ mod tests {
|
|||||||
let c = |n: &str| lib.konst(n).map(|c| c.value.clone());
|
let c = |n: &str| lib.konst(n).map(|c| c.value.clone());
|
||||||
assert_eq!(c("B"), Some(Value::Int(2)));
|
assert_eq!(c("B"), Some(Value::Int(2)));
|
||||||
assert_eq!(c("C"), Some(Value::Int(16)));
|
assert_eq!(c("C"), Some(Value::Int(16)));
|
||||||
assert_eq!(c("NAME"), Some(Value::Str("dino".into())));
|
assert_eq!(c("NAME"), Some(Value::Str("rex".into())));
|
||||||
assert_eq!(c("RED"), Some(Value::Struct("Color".into())));
|
assert_eq!(c("RED"), Some(Value::Struct("Color".into())));
|
||||||
assert_eq!(c("FLAG"), Some(Value::Int(0x12)));
|
assert_eq!(c("FLAG"), Some(Value::Int(0x12)));
|
||||||
assert_eq!(c("PI"), Some(Value::Float(3.5)));
|
assert_eq!(c("PI"), Some(Value::Float(3.5)));
|
||||||
|
|||||||
+10
-10
@@ -659,7 +659,7 @@ impl Checker {
|
|||||||
if module != self.cur_mod && self.private.contains(key) {
|
if module != self.cur_mod && self.private.contains(key) {
|
||||||
let short = key.rsplit('.').next().unwrap();
|
let short = key.rsplit('.').next().unwrap();
|
||||||
return Err(Diag::new(
|
return Err(Diag::new(
|
||||||
format!("`{short}` is private to `{module}`; write `pub` in front of it in {module}.dino to share it"),
|
format!("`{short}` is private to `{module}`; write `pub` in front of it in {module}.rex to share it"),
|
||||||
span,
|
span,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -1165,7 +1165,7 @@ impl Checker {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The Dino type for a C type, if it has one.
|
/// The Rex type for a C type, if it has one.
|
||||||
fn c_type(&self, lib: usize, t: &CTy) -> Option<Ty> {
|
fn c_type(&self, lib: usize, t: &CTy) -> Option<Ty> {
|
||||||
Some(match t {
|
Some(match t {
|
||||||
CTy::Void => Ty::Unit,
|
CTy::Void => Ty::Unit,
|
||||||
@@ -1178,7 +1178,7 @@ impl Checker {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Structs from C headers become Dino structs (`raylib.Color`), converted at calls.
|
/// Structs from C headers become Rex structs (`raylib.Color`), converted at calls.
|
||||||
fn register_c_structs(&mut self) {
|
fn register_c_structs(&mut self) {
|
||||||
for li in 0..self.clibs.len() {
|
for li in 0..self.clibs.len() {
|
||||||
let prefix = self.clibs[li].prefix.clone();
|
let prefix = self.clibs[li].prefix.clone();
|
||||||
@@ -1248,7 +1248,7 @@ impl Checker {
|
|||||||
return Err(Diag::new(format!("`{}` has no function `{name}`{hint}", l.header), name_span));
|
return Err(Diag::new(format!("`{}` has no function `{name}`{hint}", l.header), name_span));
|
||||||
};
|
};
|
||||||
if let Some(why) = &f.problem {
|
if let Some(why) = &f.problem {
|
||||||
return Err(Diag::new(format!("`{name}` can't be called from Dino: it {why}"), name_span));
|
return Err(Diag::new(format!("`{name}` can't be called from Rex: it {why}"), name_span));
|
||||||
}
|
}
|
||||||
if args.len() != f.params.len() {
|
if args.len() != f.params.len() {
|
||||||
let names: Vec<String> = f
|
let names: Vec<String> = f
|
||||||
@@ -1325,7 +1325,7 @@ impl Checker {
|
|||||||
}
|
}
|
||||||
CTy::Ptr { to, konst } => {
|
CTy::Ptr { to, konst } => {
|
||||||
let Some(inner) = self.c_type(lib, to) else {
|
let Some(inner) = self.c_type(lib, to) else {
|
||||||
return Err(Diag::new(format!("{what} has a type Dino can't pass"), a.span));
|
return Err(Diag::new(format!("{what} has a type Rex can't pass"), a.span));
|
||||||
};
|
};
|
||||||
if is_nil {
|
if is_nil {
|
||||||
return null();
|
return null();
|
||||||
@@ -1349,7 +1349,7 @@ impl Checker {
|
|||||||
let h = self.expr(a, Some(inner))?;
|
let h = self.expr(a, Some(inner))?;
|
||||||
if h.ty == Ty::list(inner) {
|
if h.ty == Ty::list(inner) {
|
||||||
if matches!(inner, Ty::Struct(_)) {
|
if matches!(inner, Ty::Struct(_)) {
|
||||||
return Err(Diag::new(format!("{what} wants C structs in a row; a Dino list of structs can't be passed"), a.span));
|
return Err(Diag::new(format!("{what} wants C structs in a row; a Rex list of structs can't be passed"), a.span));
|
||||||
}
|
}
|
||||||
return Ok((h, CArg::Buffer));
|
return Ok((h, CArg::Buffer));
|
||||||
}
|
}
|
||||||
@@ -1376,7 +1376,7 @@ impl Checker {
|
|||||||
}
|
}
|
||||||
CTy::Num(_) | CTy::Struct(_) => {
|
CTy::Num(_) | CTy::Struct(_) => {
|
||||||
let want = self.c_type(lib, pt).unwrap();
|
let want = self.c_type(lib, pt).unwrap();
|
||||||
// a C `char` takes a Dino character: `'a'`
|
// a C `char` takes a Rex character: `'a'`
|
||||||
if matches!(want, Ty::Num(Num::I8 | Num::U8)) {
|
if matches!(want, Ty::Num(Num::I8 | Num::U8)) {
|
||||||
let h = self.expr(a, Some(want))?;
|
let h = self.expr(a, Some(want))?;
|
||||||
if h.ty == Ty::Char {
|
if h.ty == Ty::Char {
|
||||||
@@ -1386,7 +1386,7 @@ impl Checker {
|
|||||||
}
|
}
|
||||||
Ok((self.expr_as(a, want)?, CArg::Value))
|
Ok((self.expr_as(a, want)?, CArg::Value))
|
||||||
}
|
}
|
||||||
CTy::Void | CTy::Unsupported(_) => Err(Diag::new(format!("{what} has a type Dino can't pass"), a.span)),
|
CTy::Void | CTy::Unsupported(_) => Err(Diag::new(format!("{what} has a type Rex can't pass"), a.span)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2462,7 +2462,7 @@ impl Checker {
|
|||||||
let owner_mod = module_of(owner);
|
let owner_mod = module_of(owner);
|
||||||
if owner_mod != self.cur_mod && self.private.contains(&format!("{owner}.{field}")) {
|
if owner_mod != self.cur_mod && self.private.contains(&format!("{owner}.{field}")) {
|
||||||
return Err(Diag::new(
|
return Err(Diag::new(
|
||||||
format!("field `{field}` is private to `{owner_mod}`; write `pub` in front of it in {owner_mod}.dino to share it"),
|
format!("field `{field}` is private to `{owner_mod}`; write `pub` in front of it in {owner_mod}.rex to share it"),
|
||||||
span,
|
span,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@@ -3409,7 +3409,7 @@ impl Checker {
|
|||||||
&& self.ifaces.values().any(|i| i.methods.iter().any(|(n, _, _)| n == name));
|
&& self.ifaces.values().any(|i| i.methods.iter().any(|(n, _, _)| n == name));
|
||||||
if owner_mod != self.cur_mod && !via_rule && self.private.contains(&format!("{owner}.{name}")) {
|
if owner_mod != self.cur_mod && !via_rule && self.private.contains(&format!("{owner}.{name}")) {
|
||||||
return Err(Diag::new(
|
return Err(Diag::new(
|
||||||
format!("method `{name}` is private to `{owner_mod}`; write `pub` in front of it in {owner_mod}.dino to share it"),
|
format!("method `{name}` is private to `{owner_mod}`; write `pub` in front of it in {owner_mod}.rex to share it"),
|
||||||
name_span,
|
name_span,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|||||||
+100
-100
@@ -1,7 +1,7 @@
|
|||||||
//! Emits C from the typed tree.
|
//! Emits C from the typed tree.
|
||||||
//!
|
//!
|
||||||
//! Evaluation order: every call (and every operation that can panic) is stored
|
//! Evaluation order: every call (and every operation that can panic) is stored
|
||||||
//! in a temporary in its own statement, so Dino's left-to-right order holds even
|
//! in a temporary in its own statement, so Rex's left-to-right order holds even
|
||||||
//! though C leaves argument order unspecified. An operand read before a later
|
//! though C leaves argument order unspecified. An operand read before a later
|
||||||
//! operand that changes things (or may panic) is copied to a temporary first.
|
//! operand that changes things (or may panic) is copied to a temporary first.
|
||||||
//!
|
//!
|
||||||
@@ -127,13 +127,13 @@ pub fn generate(p: &HProgram) -> String {
|
|||||||
}
|
}
|
||||||
// what building needs, for the driver (one item per line, so paths may contain spaces)
|
// what building needs, for the driver (one item per line, so paths may contain spaces)
|
||||||
for f in &p.c.cflags {
|
for f in &p.c.cflags {
|
||||||
g.out.push_str(&format!("// dino-cflag: {f}\n"));
|
g.out.push_str(&format!("// rex-cflag: {f}\n"));
|
||||||
}
|
}
|
||||||
for f in &p.c.libs {
|
for f in &p.c.libs {
|
||||||
g.out.push_str(&format!("// dino-lib: {f}\n"));
|
g.out.push_str(&format!("// rex-lib: {f}\n"));
|
||||||
}
|
}
|
||||||
for f in &p.c.sources {
|
for f in &p.c.sources {
|
||||||
g.out.push_str(&format!("// dino-source: {f}\n"));
|
g.out.push_str(&format!("// rex-source: {f}\n"));
|
||||||
}
|
}
|
||||||
if p.c.headers.is_empty() {
|
if p.c.headers.is_empty() {
|
||||||
g.out.push_str(RUNTIME);
|
g.out.push_str(RUNTIME);
|
||||||
@@ -336,10 +336,10 @@ pub fn generate(p: &HProgram) -> String {
|
|||||||
g.out.push_str(&defs);
|
g.out.push_str(&defs);
|
||||||
if main_fails {
|
if main_fails {
|
||||||
g.out.push_str(
|
g.out.push_str(
|
||||||
"int main(int argc, char **argv) {\n dino_set_args(argc, argv);\n dino_err e = d_main();\n if (e.set) {\n fflush(stdout);\n fprintf(stderr, \"error: %.*s\\n\", (int)e.msg.n, e.msg.p);\n dino_err_release(e);\n return 1;\n }\n return 0;\n}\n",
|
"int main(int argc, char **argv) {\n rex_set_args(argc, argv);\n rex_err e = d_main();\n if (e.set) {\n fflush(stdout);\n fprintf(stderr, \"error: %.*s\\n\", (int)e.msg.n, e.msg.p);\n rex_err_release(e);\n return 1;\n }\n return 0;\n}\n",
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
g.out.push_str("int main(int argc, char **argv) {\n dino_set_args(argc, argv);\n d_main();\n return 0;\n}\n");
|
g.out.push_str("int main(int argc, char **argv) {\n rex_set_args(argc, argv);\n d_main();\n return 0;\n}\n");
|
||||||
}
|
}
|
||||||
g.out
|
g.out
|
||||||
}
|
}
|
||||||
@@ -523,7 +523,7 @@ fn c_ty(t: Ty) -> String {
|
|||||||
Ty::Struct(name) | Ty::Enum(name) => c_struct(name),
|
Ty::Struct(name) | Ty::Enum(name) => c_struct(name),
|
||||||
Ty::List(_) | Ty::Map(..) | Ty::Opt(_) | Ty::Tuple(_) | Ty::Shared(_) | Ty::Weak(_) | Ty::Func(_) | Ty::Iface(_) => tag(t),
|
Ty::List(_) | Ty::Map(..) | Ty::Opt(_) | Ty::Tuple(_) | Ty::Shared(_) | Ty::Weak(_) | Ty::Func(_) | Ty::Iface(_) => tag(t),
|
||||||
Ty::Num(n) => num_c(n).into(),
|
Ty::Num(n) => num_c(n).into(),
|
||||||
Ty::Error => "dino_err".into(),
|
Ty::Error => "rex_err".into(),
|
||||||
Ty::CPtr(_) => "void *".into(),
|
Ty::CPtr(_) => "void *".into(),
|
||||||
Ty::Unit => "void".into(),
|
Ty::Unit => "void".into(),
|
||||||
}
|
}
|
||||||
@@ -542,7 +542,7 @@ fn num_c(n: Num) -> &'static str {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Make a Dino name safe to use as part of a C identifier.
|
/// Make a Rex name safe to use as part of a C identifier.
|
||||||
fn mangle(name: &str) -> String {
|
fn mangle(name: &str) -> String {
|
||||||
name.chars()
|
name.chars()
|
||||||
.map(|c| if c.is_ascii_alphanumeric() || c == '_' { c.to_string() } else { format!("u{:x}_", c as u32) })
|
.map(|c| if c.is_ascii_alphanumeric() || c == '_' { c.to_string() } else { format!("u{:x}_", c as u32) })
|
||||||
@@ -570,9 +570,9 @@ fn func_cname(owner: Option<&str>, name: &str) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A C string literal for `dstr`, as `dino_lit("...", len)`.
|
/// A C string literal for `dstr`, as `rex_lit("...", len)`.
|
||||||
fn str_lit(s: &str) -> String {
|
fn str_lit(s: &str) -> String {
|
||||||
let mut out = String::from("dino_lit(\"");
|
let mut out = String::from("rex_lit(\"");
|
||||||
for b in s.bytes() {
|
for b in s.bytes() {
|
||||||
match b {
|
match b {
|
||||||
b'"' => out.push_str("\\\""),
|
b'"' => out.push_str("\\\""),
|
||||||
@@ -618,17 +618,17 @@ fn is_place(e: &HExpr) -> bool {
|
|||||||
/// A C expression turning a value of type `ty` (given as C code) into a `dstr`.
|
/// A C expression turning a value of type `ty` (given as C code) into a `dstr`.
|
||||||
fn to_str(ty: Ty, c: &str) -> String {
|
fn to_str(ty: Ty, c: &str) -> String {
|
||||||
match ty {
|
match ty {
|
||||||
Ty::Int => format!("dino_i64_str({c})"),
|
Ty::Int => format!("rex_i64_str({c})"),
|
||||||
Ty::Float => format!("dino_f64_str({c})"),
|
Ty::Float => format!("rex_f64_str({c})"),
|
||||||
Ty::Bool => format!("dino_bool_str({c})"),
|
Ty::Bool => format!("rex_bool_str({c})"),
|
||||||
Ty::Char => format!("dino_char_str({c})"),
|
Ty::Char => format!("rex_char_str({c})"),
|
||||||
Ty::Str => format!("dino_str_retain({c})"),
|
Ty::Str => format!("rex_str_retain({c})"),
|
||||||
Ty::Struct(_) | Ty::Enum(_) | Ty::List(_) | Ty::Map(..) | Ty::Opt(_) | Ty::Shared(_) | Ty::Weak(_) | Ty::Func(_) | Ty::Iface(_) => format!("{}_str({c})", c_ty(ty)),
|
Ty::Struct(_) | Ty::Enum(_) | Ty::List(_) | Ty::Map(..) | Ty::Opt(_) | Ty::Shared(_) | Ty::Weak(_) | Ty::Func(_) | Ty::Iface(_) => format!("{}_str({c})", c_ty(ty)),
|
||||||
Ty::Num(Num::U64) => format!("dino_u64_str({c})"),
|
Ty::Num(Num::U64) => format!("rex_u64_str({c})"),
|
||||||
Ty::Num(Num::F32) => format!("dino_f32_str({c})"),
|
Ty::Num(Num::F32) => format!("rex_f32_str({c})"),
|
||||||
Ty::Num(_) => format!("dino_i64_str((int64_t)({c}))"),
|
Ty::Num(_) => format!("rex_i64_str((int64_t)({c}))"),
|
||||||
Ty::Error => format!("dino_err_str({c})"),
|
Ty::Error => format!("rex_err_str({c})"),
|
||||||
Ty::CPtr(_) => format!("dino_ptr_str({c})"),
|
Ty::CPtr(_) => format!("rex_ptr_str({c})"),
|
||||||
Ty::Tuple(_) => unreachable!("several values can't be turned into text"),
|
Ty::Tuple(_) => unreachable!("several values can't be turned into text"),
|
||||||
Ty::Unit => unreachable!("nothing can't be turned into text"),
|
Ty::Unit => unreachable!("nothing can't be turned into text"),
|
||||||
}
|
}
|
||||||
@@ -728,8 +728,8 @@ impl Gen {
|
|||||||
/// The C statement that frees the value in the lvalue `lv`.
|
/// The C statement that frees the value in the lvalue `lv`.
|
||||||
fn drop_line(&self, ty: Ty, lv: &str) -> String {
|
fn drop_line(&self, ty: Ty, lv: &str) -> String {
|
||||||
match ty {
|
match ty {
|
||||||
Ty::Str => format!("dino_str_release({lv});"),
|
Ty::Str => format!("rex_str_release({lv});"),
|
||||||
Ty::Error => format!("dino_err_release({lv});"),
|
Ty::Error => format!("rex_err_release({lv});"),
|
||||||
_ => format!("{}_drop(&({lv}));", c_ty(ty)),
|
_ => format!("{}_drop(&({lv}));", c_ty(ty)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -780,9 +780,9 @@ impl Gen {
|
|||||||
if !self.info.needs_copy(ty) {
|
if !self.info.needs_copy(ty) {
|
||||||
e.to_string()
|
e.to_string()
|
||||||
} else if ty == Ty::Str {
|
} else if ty == Ty::Str {
|
||||||
format!("dino_str_retain({e})")
|
format!("rex_str_retain({e})")
|
||||||
} else if ty == Ty::Error {
|
} else if ty == Ty::Error {
|
||||||
format!("dino_err_retain({e})")
|
format!("rex_err_retain({e})")
|
||||||
} else {
|
} else {
|
||||||
format!("{}_copy({e})", c_ty(ty))
|
format!("{}_copy({e})", c_ty(ty))
|
||||||
}
|
}
|
||||||
@@ -802,7 +802,7 @@ impl Gen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// For a struct from a C header: `S_raylib_Color_to_c` and `S_raylib_Color_from_c`, which copy
|
/// For a struct from a C header: `S_raylib_Color_to_c` and `S_raylib_Color_from_c`, which copy
|
||||||
/// the fields between Dino's struct and the C one.
|
/// the fields between Rex's struct and the C one.
|
||||||
fn c_struct_conversions(&mut self, s: &HStruct) {
|
fn c_struct_conversions(&mut self, s: &HStruct) {
|
||||||
let Some(cname) = &s.c else { return };
|
let Some(cname) = &s.c else { return };
|
||||||
let c = c_struct(&s.name);
|
let c = c_struct(&s.name);
|
||||||
@@ -827,7 +827,7 @@ impl Gen {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A Dino value as the C function wants it.
|
/// A Rex value as the C function wants it.
|
||||||
fn to_c_value(&self, ty: Ty, v: &str) -> String {
|
fn to_c_value(&self, ty: Ty, v: &str) -> String {
|
||||||
match ty {
|
match ty {
|
||||||
Ty::Struct(n) if self.c_structs.contains_key(n) => format!("{}_to_c({v})", c_struct(n)),
|
Ty::Struct(n) if self.c_structs.contains_key(n) => format!("{}_to_c({v})", c_struct(n)),
|
||||||
@@ -859,7 +859,7 @@ impl Gen {
|
|||||||
CArg::Str => {
|
CArg::Str => {
|
||||||
let v = vs.next().unwrap();
|
let v = vs.next().unwrap();
|
||||||
let t = self.fresh();
|
let t = self.fresh();
|
||||||
self.line(&format!("char *{t} = dino_cstr({v});"));
|
self.line(&format!("char *{t} = rex_cstr({v});"));
|
||||||
after.push(format!("free({t});"));
|
after.push(format!("free({t});"));
|
||||||
parts.push(t);
|
parts.push(t);
|
||||||
}
|
}
|
||||||
@@ -895,7 +895,7 @@ impl Gen {
|
|||||||
String::new()
|
String::new()
|
||||||
} else {
|
} else {
|
||||||
let conv = match ty {
|
let conv = match ty {
|
||||||
Ty::Str => format!("dino_from_cstr({call})"),
|
Ty::Str => format!("rex_from_cstr({call})"),
|
||||||
Ty::Struct(n) if self.c_structs.contains_key(n) => format!("{}_from_c({call})", c_struct(n)),
|
Ty::Struct(n) if self.c_structs.contains_key(n) => format!("{}_from_c({call})", c_struct(n)),
|
||||||
Ty::CPtr(_) => format!("(void *)({call})"),
|
Ty::CPtr(_) => format!("(void *)({call})"),
|
||||||
t => format!("({})({call})", c_ty(t)),
|
t => format!("({})({call})", c_ty(t)),
|
||||||
@@ -924,7 +924,7 @@ impl Gen {
|
|||||||
self.out.push_str(&format!("static dstr {c}_str({c} v) {{\n"));
|
self.out.push_str(&format!("static dstr {c}_str({c} v) {{\n"));
|
||||||
self.out.push_str(&format!(" dstr parts[] = {{{}}};\n", parts.join(", ")));
|
self.out.push_str(&format!(" dstr parts[] = {{{}}};\n", parts.join(", ")));
|
||||||
self.out.push_str(&format!(
|
self.out.push_str(&format!(
|
||||||
" dstr r = dino_cat_n({0}, parts);\n for (int i = 0; i < {0}; i++) dino_str_release(parts[i]);\n return r;\n}}\n\n",
|
" dstr r = rex_cat_n({0}, parts);\n for (int i = 0; i < {0}; i++) rex_str_release(parts[i]);\n return r;\n}}\n\n",
|
||||||
parts.len()
|
parts.len()
|
||||||
));
|
));
|
||||||
|
|
||||||
@@ -984,13 +984,13 @@ impl Gen {
|
|||||||
}
|
}
|
||||||
parts.push(str_lit(")"));
|
parts.push(str_lit(")"));
|
||||||
self.out.push_str(&format!(
|
self.out.push_str(&format!(
|
||||||
" case {i}: {{ dstr parts[] = {{{}}}; dstr r = dino_cat_n({n}, parts); for (int k = 0; k < {n}; k++) dino_str_release(parts[k]); return r; }}\n",
|
" case {i}: {{ dstr parts[] = {{{}}}; dstr r = rex_cat_n({n}, parts); for (int k = 0; k < {n}; k++) rex_str_release(parts[k]); return r; }}\n",
|
||||||
parts.join(", "),
|
parts.join(", "),
|
||||||
n = parts.len()
|
n = parts.len()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.out.push_str(" }\n return dino_lit(\"?\", 1);\n}\n\n");
|
self.out.push_str(" }\n return rex_lit(\"?\", 1);\n}\n\n");
|
||||||
|
|
||||||
if self.info.needs_copy_named(&e.name) {
|
if self.info.needs_copy_named(&e.name) {
|
||||||
self.out.push_str(&format!("static {c} {c}_copy({c} v) {{\n {c} r = v;\n switch (v.tag) {{\n"));
|
self.out.push_str(&format!("static {c} {c}_copy({c} v) {{\n {c} r = v;\n switch (v.tag) {{\n"));
|
||||||
@@ -1063,7 +1063,7 @@ impl Gen {
|
|||||||
match w {
|
match w {
|
||||||
Ty::Opt(inner) => {
|
Ty::Opt(inner) => {
|
||||||
out.push_str(&format!(
|
out.push_str(&format!(
|
||||||
"static dstr {c}_str({c} v) {{\n if (!v.has) return dino_lit(\"nil\", 3);\n return {};\n}}\n\n",
|
"static dstr {c}_str({c} v) {{\n if (!v.has) return rex_lit(\"nil\", 3);\n return {};\n}}\n\n",
|
||||||
to_str(*inner, "v.v")
|
to_str(*inner, "v.v")
|
||||||
));
|
));
|
||||||
if self.info.needs_copy(*inner) {
|
if self.info.needs_copy(*inner) {
|
||||||
@@ -1099,7 +1099,7 @@ impl Gen {
|
|||||||
let methods = &ifaces.iter().find(|(n, _)| n == iname).unwrap().1;
|
let methods = &ifaces.iter().find(|(n, _)| n == iname).unwrap().1;
|
||||||
let drop_t = if self.info.needs_copy(t) { format!(" {}\n", self.drop_line(t, &format!("*({tc} *)p"))) } else { String::new() };
|
let drop_t = if self.info.needs_copy(t) { format!(" {}\n", self.drop_line(t, &format!("*({tc} *)p"))) } else { String::new() };
|
||||||
let mut out = format!(
|
let mut out = format!(
|
||||||
"static void *{base}_copy(void *p) {{\n {tc} *d = ({tc} *)malloc(sizeof({tc}));\n if (!d) dino_panic(\"out of memory\");\n *d = {};\n return d;\n}}\n\
|
"static void *{base}_copy(void *p) {{\n {tc} *d = ({tc} *)malloc(sizeof({tc}));\n if (!d) rex_panic(\"out of memory\");\n *d = {};\n return d;\n}}\n\
|
||||||
static void {base}_drop(void *p) {{\n{drop_t} free(p);\n}}\n\
|
static void {base}_drop(void *p) {{\n{drop_t} free(p);\n}}\n\
|
||||||
static dstr {base}_str(void *p) {{\n return {tc}_str(*({tc} *)p);\n}}\n",
|
static dstr {base}_str(void *p) {{\n return {tc}_str(*({tc} *)p);\n}}\n",
|
||||||
self.copy_of(t, &format!("*({tc} *)p"))
|
self.copy_of(t, &format!("*({tc} *)p"))
|
||||||
@@ -1141,7 +1141,7 @@ impl Gen {
|
|||||||
.collect();
|
.collect();
|
||||||
out.push_str(&format!(
|
out.push_str(&format!(
|
||||||
"static const struct VT_{ic} {base}_vt = {{ {} }};\n\
|
"static const struct VT_{ic} {base}_vt = {{ {} }};\n\
|
||||||
static {ic} {ic}_from_{tc}({tc} v) {{\n {tc} *b = ({tc} *)malloc(sizeof({tc}));\n if (!b) dino_panic(\"out of memory\");\n *b = v;\n return ({ic}){{ b, &{base}_vt }};\n}}\n\n",
|
static {ic} {ic}_from_{tc}({tc} v) {{\n {tc} *b = ({tc} *)malloc(sizeof({tc}));\n if (!b) rex_panic(\"out of memory\");\n *b = v;\n return ({ic}){{ b, &{base}_vt }};\n}}\n\n",
|
||||||
entries.join(", ")
|
entries.join(", ")
|
||||||
));
|
));
|
||||||
out
|
out
|
||||||
@@ -1179,7 +1179,7 @@ impl Gen {
|
|||||||
.collect();
|
.collect();
|
||||||
self.closure_protos.push_str(&format!(
|
self.closure_protos.push_str(&format!(
|
||||||
"typedef struct {env} {{ {} }} {env};\n\
|
"typedef struct {env} {{ {} }} {env};\n\
|
||||||
static void *{env}_copy(void *p) {{\n {env} *s = ({env} *)p;\n {env} *d = ({env} *)malloc(sizeof({env}));\n if (!d) dino_panic(\"out of memory\");\n{}\n return d;\n}}\n\
|
static void *{env}_copy(void *p) {{\n {env} *s = ({env} *)p;\n {env} *d = ({env} *)malloc(sizeof({env}));\n if (!d) rex_panic(\"out of memory\");\n{}\n return d;\n}}\n\
|
||||||
static void {env}_drop(void *p) {{\n {env} *s = ({env} *)p;\n{}\n free(s);\n}}\n",
|
static void {env}_drop(void *p) {{\n {env} *s = ({env} *)p;\n{}\n free(s);\n}}\n",
|
||||||
fields.join(" "),
|
fields.join(" "),
|
||||||
copies.join("\n"),
|
copies.join("\n"),
|
||||||
@@ -1216,7 +1216,7 @@ impl Gen {
|
|||||||
self.stmts(body);
|
self.stmts(body);
|
||||||
self.end_scope();
|
self.end_scope();
|
||||||
if ret != Ty::Unit {
|
if ret != Ty::Unit {
|
||||||
self.line("dino_panic(\"reached the end of a function without returning\");");
|
self.line("rex_panic(\"reached the end of a function without returning\");");
|
||||||
}
|
}
|
||||||
self.out.push_str("}\n\n");
|
self.out.push_str("}\n\n");
|
||||||
let text = std::mem::replace(&mut self.out, saved_out);
|
let text = std::mem::replace(&mut self.out, saved_out);
|
||||||
@@ -1234,7 +1234,7 @@ impl Gen {
|
|||||||
} else {
|
} else {
|
||||||
let t = self.fresh();
|
let t = self.fresh();
|
||||||
self.line(&format!("{env} *{t} = ({env} *)malloc(sizeof({env}));"));
|
self.line(&format!("{env} *{t} = ({env} *)malloc(sizeof({env}));"));
|
||||||
self.line(&format!("if (!{t}) dino_panic(\"out of memory\");"));
|
self.line(&format!("if (!{t}) rex_panic(\"out of memory\");"));
|
||||||
for (i, v) in vs.iter().enumerate() {
|
for (i, v) in vs.iter().enumerate() {
|
||||||
self.line(&format!("{t}->f{i} = {v};"));
|
self.line(&format!("{t}->f{i} = {v};"));
|
||||||
}
|
}
|
||||||
@@ -1272,7 +1272,7 @@ impl Gen {
|
|||||||
format!(
|
format!(
|
||||||
r#"static {c} {c}_new({t} v) {{
|
r#"static {c} {c}_new({t} v) {{
|
||||||
{bx} *b = ({bx} *)malloc(sizeof({bx}));
|
{bx} *b = ({bx} *)malloc(sizeof({bx}));
|
||||||
if (!b) dino_panic("out of memory");
|
if (!b) rex_panic("out of memory");
|
||||||
b->rc = 1;
|
b->rc = 1;
|
||||||
b->wk = 0;
|
b->wk = 0;
|
||||||
b->v = v;
|
b->v = v;
|
||||||
@@ -1296,7 +1296,7 @@ static void {c}_drop({c} *h) {{
|
|||||||
}}
|
}}
|
||||||
|
|
||||||
static {t} *{c}_ref({c} h) {{
|
static {t} *{c}_ref({c} h) {{
|
||||||
if (!h.p) dino_panic("this `shared` value is empty");
|
if (!h.p) rex_panic("this `shared` value is empty");
|
||||||
return &h.p->v;
|
return &h.p->v;
|
||||||
}}
|
}}
|
||||||
|
|
||||||
@@ -1342,7 +1342,7 @@ static bool {c}_alive({c} w) {{
|
|||||||
}}
|
}}
|
||||||
|
|
||||||
static {t} *{c}_ref({c} w) {{
|
static {t} *{c}_ref({c} w) {{
|
||||||
if (!{c}_alive(w)) dino_panic("this `weak` value is gone (or was never set)");
|
if (!{c}_alive(w)) rex_panic("this `weak` value is gone (or was never set)");
|
||||||
return &w.p->v;
|
return &w.p->v;
|
||||||
}}
|
}}
|
||||||
|
|
||||||
@@ -1379,9 +1379,9 @@ static dstr {c}_str({c} w) {{
|
|||||||
let Ty::Map(k, v) = m else { unreachable!() };
|
let Ty::Map(k, v) = m else { unreachable!() };
|
||||||
let (c, kt, vt) = (c_ty(m), c_ty(*k), c_ty(*v));
|
let (c, kt, vt) = (c_ty(m), c_ty(*k), c_ty(*v));
|
||||||
let (hash, eq) = if *k == Ty::Str {
|
let (hash, eq) = if *k == Ty::Str {
|
||||||
("dino_hash_str(key)".to_string(), "dino_streq(a, b)".to_string())
|
("rex_hash_str(key)".to_string(), "rex_streq(a, b)".to_string())
|
||||||
} else {
|
} else {
|
||||||
("dino_hash_i64((int64_t)key)".to_string(), "a == b".to_string())
|
("rex_hash_i64((int64_t)key)".to_string(), "a == b".to_string())
|
||||||
};
|
};
|
||||||
let copy_k = self.copy_of(*k, "m.k[i]");
|
let copy_k = self.copy_of(*k, "m.k[i]");
|
||||||
let copy_v = self.copy_of(*v, "m.v[i]");
|
let copy_v = self.copy_of(*v, "m.v[i]");
|
||||||
@@ -1410,7 +1410,7 @@ static void {c}_reindex({c} *m) {{
|
|||||||
while (cap < m->len * 2 + 2) cap *= 2;
|
while (cap < m->len * 2 + 2) cap *= 2;
|
||||||
free(m->idx);
|
free(m->idx);
|
||||||
m->idx = (int64_t *)calloc((size_t)cap, sizeof(int64_t));
|
m->idx = (int64_t *)calloc((size_t)cap, sizeof(int64_t));
|
||||||
if (!m->idx) dino_panic("out of memory");
|
if (!m->idx) rex_panic("out of memory");
|
||||||
m->icap = cap;
|
m->icap = cap;
|
||||||
for (int64_t i = 0; i < m->len; i++) {{
|
for (int64_t i = 0; i < m->len; i++) {{
|
||||||
uint64_t h = {c}_hash(m->k[i]) & (uint64_t)(cap - 1);
|
uint64_t h = {c}_hash(m->k[i]) & (uint64_t)(cap - 1);
|
||||||
@@ -1437,7 +1437,7 @@ static {vt} *{c}_ptr(const {c} *m, {kt} key) {{
|
|||||||
|
|
||||||
static {vt} *{c}_at(const {c} *m, {kt} key) {{
|
static {vt} *{c}_at(const {c} *m, {kt} key) {{
|
||||||
{vt} *p = {c}_ptr(m, key);
|
{vt} *p = {c}_ptr(m, key);
|
||||||
if (!p) dino_panic("that key is not in the map (check with `has` or use `get`)");
|
if (!p) rex_panic("that key is not in the map (check with `has` or use `get`)");
|
||||||
return p;
|
return p;
|
||||||
}}
|
}}
|
||||||
|
|
||||||
@@ -1459,10 +1459,10 @@ static void {c}_set({c} *m, {kt} key, {vt} val) {{
|
|||||||
if (m->len == m->cap) {{
|
if (m->len == m->cap) {{
|
||||||
int64_t cap = m->cap ? m->cap * 2 : 4;
|
int64_t cap = m->cap ? m->cap * 2 : 4;
|
||||||
{kt} *nk = ({kt} *)realloc(m->k, (size_t)cap * sizeof({kt}));
|
{kt} *nk = ({kt} *)realloc(m->k, (size_t)cap * sizeof({kt}));
|
||||||
if (!nk) dino_panic("out of memory");
|
if (!nk) rex_panic("out of memory");
|
||||||
m->k = nk;
|
m->k = nk;
|
||||||
{vt} *nv = ({vt} *)realloc(m->v, (size_t)cap * sizeof({vt}));
|
{vt} *nv = ({vt} *)realloc(m->v, (size_t)cap * sizeof({vt}));
|
||||||
if (!nv) dino_panic("out of memory");
|
if (!nv) rex_panic("out of memory");
|
||||||
m->v = nv;
|
m->v = nv;
|
||||||
m->cap = cap;
|
m->cap = cap;
|
||||||
}}
|
}}
|
||||||
@@ -1489,7 +1489,7 @@ static {c} {c}_copy({c} m) {{
|
|||||||
if (m.len > 0) {{
|
if (m.len > 0) {{
|
||||||
r.k = ({kt} *)malloc((size_t)m.len * sizeof({kt}));
|
r.k = ({kt} *)malloc((size_t)m.len * sizeof({kt}));
|
||||||
r.v = ({vt} *)malloc((size_t)m.len * sizeof({vt}));
|
r.v = ({vt} *)malloc((size_t)m.len * sizeof({vt}));
|
||||||
if (!r.k || !r.v) dino_panic("out of memory");
|
if (!r.k || !r.v) rex_panic("out of memory");
|
||||||
r.len = r.cap = m.len;
|
r.len = r.cap = m.len;
|
||||||
for (int64_t i = 0; i < m.len; i++) {{
|
for (int64_t i = 0; i < m.len; i++) {{
|
||||||
r.k[i] = {copy_k};
|
r.k[i] = {copy_k};
|
||||||
@@ -1513,18 +1513,18 @@ static void {c}_drop({c} *m) {{
|
|||||||
|
|
||||||
static dstr {c}_str({c} m) {{
|
static dstr {c}_str({c} m) {{
|
||||||
dstr *parts = (dstr *)malloc(sizeof(dstr) * (size_t)(m.len * 4 + 2));
|
dstr *parts = (dstr *)malloc(sizeof(dstr) * (size_t)(m.len * 4 + 2));
|
||||||
if (!parts) dino_panic("out of memory");
|
if (!parts) rex_panic("out of memory");
|
||||||
int k = 0;
|
int k = 0;
|
||||||
parts[k++] = dino_lit("{{", 1);
|
parts[k++] = rex_lit("{{", 1);
|
||||||
for (int64_t i = 0; i < m.len; i++) {{
|
for (int64_t i = 0; i < m.len; i++) {{
|
||||||
if (i > 0) parts[k++] = dino_lit(", ", 2);
|
if (i > 0) parts[k++] = rex_lit(", ", 2);
|
||||||
parts[k++] = {key_str};
|
parts[k++] = {key_str};
|
||||||
parts[k++] = dino_lit(": ", 2);
|
parts[k++] = rex_lit(": ", 2);
|
||||||
parts[k++] = {val_str};
|
parts[k++] = {val_str};
|
||||||
}}
|
}}
|
||||||
parts[k++] = dino_lit("}}", 1);
|
parts[k++] = rex_lit("}}", 1);
|
||||||
dstr r = dino_cat_n(k, parts);
|
dstr r = rex_cat_n(k, parts);
|
||||||
for (int i = 0; i < k; i++) dino_str_release(parts[i]);
|
for (int i = 0; i < k; i++) rex_str_release(parts[i]);
|
||||||
free(parts);
|
free(parts);
|
||||||
return r;
|
return r;
|
||||||
}}
|
}}
|
||||||
@@ -1561,7 +1561,7 @@ static dstr {c}_str({c} m) {{
|
|||||||
};
|
};
|
||||||
format!(
|
format!(
|
||||||
r#"static inline {t} *{c}_at(const {c} *l, int64_t i) {{
|
r#"static inline {t} *{c}_at(const {c} *l, int64_t i) {{
|
||||||
if (i < 0 || i >= l->len) dino_index_panic(i, l->len);
|
if (i < 0 || i >= l->len) rex_index_panic(i, l->len);
|
||||||
return &l->p[i];
|
return &l->p[i];
|
||||||
}}
|
}}
|
||||||
|
|
||||||
@@ -1569,7 +1569,7 @@ static void {c}_push({c} *l, {t} v) {{
|
|||||||
if (l->len == l->cap) {{
|
if (l->len == l->cap) {{
|
||||||
int64_t cap = l->cap ? l->cap * 2 : 4;
|
int64_t cap = l->cap ? l->cap * 2 : 4;
|
||||||
{t} *p = ({t} *)realloc(l->p, (size_t)cap * sizeof({t}));
|
{t} *p = ({t} *)realloc(l->p, (size_t)cap * sizeof({t}));
|
||||||
if (!p) dino_panic("out of memory");
|
if (!p) rex_panic("out of memory");
|
||||||
l->p = p;
|
l->p = p;
|
||||||
l->cap = cap;
|
l->cap = cap;
|
||||||
}}
|
}}
|
||||||
@@ -1577,7 +1577,7 @@ static void {c}_push({c} *l, {t} v) {{
|
|||||||
}}
|
}}
|
||||||
|
|
||||||
static {t} {c}_pop({c} *l) {{
|
static {t} {c}_pop({c} *l) {{
|
||||||
if (l->len == 0) dino_panic("pop from an empty list");
|
if (l->len == 0) rex_panic("pop from an empty list");
|
||||||
return l->p[--l->len];
|
return l->p[--l->len];
|
||||||
}}
|
}}
|
||||||
|
|
||||||
@@ -1585,7 +1585,7 @@ static {c} {c}_copy({c} l) {{
|
|||||||
{c} r = {{0}};
|
{c} r = {{0}};
|
||||||
if (l.len > 0) {{
|
if (l.len > 0) {{
|
||||||
r.p = ({t} *)malloc((size_t)l.len * sizeof({t}));
|
r.p = ({t} *)malloc((size_t)l.len * sizeof({t}));
|
||||||
if (!r.p) dino_panic("out of memory");
|
if (!r.p) rex_panic("out of memory");
|
||||||
r.len = r.cap = l.len;
|
r.len = r.cap = l.len;
|
||||||
for (int64_t i = 0; i < l.len; i++) r.p[i] = {copy_i};
|
for (int64_t i = 0; i < l.len; i++) r.p[i] = {copy_i};
|
||||||
}}
|
}}
|
||||||
@@ -1599,12 +1599,12 @@ static void {c}_drop({c} *l) {{
|
|||||||
}}
|
}}
|
||||||
|
|
||||||
static {c} {c}_slice({c} l, int64_t lo, int64_t hi) {{
|
static {c} {c}_slice({c} l, int64_t lo, int64_t hi) {{
|
||||||
if (lo < 0 || hi > l.len || lo > hi) dino_slice_panic(lo, hi, l.len);
|
if (lo < 0 || hi > l.len || lo > hi) rex_slice_panic(lo, hi, l.len);
|
||||||
{c} r = {{0}};
|
{c} r = {{0}};
|
||||||
if (hi > lo) {{
|
if (hi > lo) {{
|
||||||
int64_t n = hi - lo;
|
int64_t n = hi - lo;
|
||||||
r.p = ({t} *)malloc((size_t)n * sizeof({t}));
|
r.p = ({t} *)malloc((size_t)n * sizeof({t}));
|
||||||
if (!r.p) dino_panic("out of memory");
|
if (!r.p) rex_panic("out of memory");
|
||||||
r.len = r.cap = n;
|
r.len = r.cap = n;
|
||||||
for (int64_t i = 0; i < n; i++) r.p[i] = {copy_lo};
|
for (int64_t i = 0; i < n; i++) r.p[i] = {copy_lo};
|
||||||
}}
|
}}
|
||||||
@@ -1613,16 +1613,16 @@ static {c} {c}_slice({c} l, int64_t lo, int64_t hi) {{
|
|||||||
|
|
||||||
static dstr {c}_str({c} l) {{
|
static dstr {c}_str({c} l) {{
|
||||||
dstr *parts = (dstr *)malloc(sizeof(dstr) * (size_t)(l.len * 2 + 2));
|
dstr *parts = (dstr *)malloc(sizeof(dstr) * (size_t)(l.len * 2 + 2));
|
||||||
if (!parts) dino_panic("out of memory");
|
if (!parts) rex_panic("out of memory");
|
||||||
int k = 0;
|
int k = 0;
|
||||||
parts[k++] = dino_lit("[", 1);
|
parts[k++] = rex_lit("[", 1);
|
||||||
for (int64_t i = 0; i < l.len; i++) {{
|
for (int64_t i = 0; i < l.len; i++) {{
|
||||||
if (i > 0) parts[k++] = dino_lit(", ", 2);
|
if (i > 0) parts[k++] = rex_lit(", ", 2);
|
||||||
parts[k++] = {elem_str};
|
parts[k++] = {elem_str};
|
||||||
}}
|
}}
|
||||||
parts[k++] = dino_lit("]", 1);
|
parts[k++] = rex_lit("]", 1);
|
||||||
dstr r = dino_cat_n(k, parts);
|
dstr r = rex_cat_n(k, parts);
|
||||||
for (int i = 0; i < k; i++) dino_str_release(parts[i]);
|
for (int i = 0; i < k; i++) rex_str_release(parts[i]);
|
||||||
free(parts);
|
free(parts);
|
||||||
return r;
|
return r;
|
||||||
}}
|
}}
|
||||||
@@ -1676,7 +1676,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
self.stmts(&f.body);
|
self.stmts(&f.body);
|
||||||
self.end_scope();
|
self.end_scope();
|
||||||
if f.ret != Ty::Unit {
|
if f.ret != Ty::Unit {
|
||||||
self.line("dino_panic(\"reached the end of a function without returning\");");
|
self.line("rex_panic(\"reached the end of a function without returning\");");
|
||||||
}
|
}
|
||||||
self.indent = 0;
|
self.indent = 0;
|
||||||
self.out.push_str("}\n\n");
|
self.out.push_str("}\n\n");
|
||||||
@@ -1833,7 +1833,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
match &step_v {
|
match &step_v {
|
||||||
None => self.line(&format!("for (int64_t {cc} = {cs}; {cc} < {ce}; {cc}++) {{")),
|
None => self.line(&format!("for (int64_t {cc} = {cs}; {cc} < {ce}; {cc}++) {{")),
|
||||||
Some(step_v) => {
|
Some(step_v) => {
|
||||||
self.line(&format!("if ({step_v} == 0) dino_panic(\"the step of a range can't be 0\");"));
|
self.line(&format!("if ({step_v} == 0) rex_panic(\"the step of a range can't be 0\");"));
|
||||||
self.line(&format!(
|
self.line(&format!(
|
||||||
"for (int64_t {cc} = {cs}; {step_v} > 0 ? {cc} < {ce} : {cc} > {ce}; {cc} += {step_v}) {{"
|
"for (int64_t {cc} = {cs}; {step_v} > 0 ? {cc} < {ce} : {cc} > {ce}; {cc} += {step_v}) {{"
|
||||||
));
|
));
|
||||||
@@ -1956,7 +1956,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
} else if iter.ty == Ty::Str {
|
} else if iter.ty == Ty::Str {
|
||||||
let name = local_name(var.id, &var.name);
|
let name = local_name(var.id, &var.name);
|
||||||
self.line(&format!("uint32_t {name} = 0;"));
|
self.line(&format!("uint32_t {name} = 0;"));
|
||||||
self.line(&format!("{w} = dino_utf8_decode({it}.p + {k}, {it}.n - {k}, &{name});"));
|
self.line(&format!("{w} = rex_utf8_decode({it}.p + {k}, {it}.n - {k}, &{name});"));
|
||||||
} else {
|
} else {
|
||||||
let elem = format!("{it}.p[{k}]");
|
let elem = format!("{it}.p[{k}]");
|
||||||
// a list or struct element is copied only if the body changes the loop variable
|
// a list or struct element is copied only if the body changes the loop variable
|
||||||
@@ -2050,7 +2050,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
let idx = self.expr(index);
|
let idx = self.expr(index);
|
||||||
if base.ty == Ty::Str {
|
if base.ty == Ty::Str {
|
||||||
// a character of a string is a value, not a place
|
// a character of a string is a value, not a place
|
||||||
return format!("dino_str_char_at({b}, {idx})");
|
return format!("rex_str_char_at({b}, {idx})");
|
||||||
}
|
}
|
||||||
format!("(*{}_at(&{b}, {idx}))", c_ty(base.ty))
|
format!("(*{}_at(&{b}, {idx}))", c_ty(base.ty))
|
||||||
}
|
}
|
||||||
@@ -2063,7 +2063,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
self.line(&format!("{} {t} = {v};", c_ty(inner.ty)));
|
self.line(&format!("{} {t} = {v};", c_ty(inner.ty)));
|
||||||
t
|
t
|
||||||
};
|
};
|
||||||
self.line(&format!("if (!{b}.has) dino_panic(\"used a nil value\");"));
|
self.line(&format!("if (!{b}.has) rex_panic(\"used a nil value\");"));
|
||||||
format!("{b}.v")
|
format!("{b}.v")
|
||||||
}
|
}
|
||||||
_ => self.expr(e),
|
_ => self.expr(e),
|
||||||
@@ -2135,7 +2135,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
HExprKind::MakeError(msg) => {
|
HExprKind::MakeError(msg) => {
|
||||||
let v = self.expr(msg);
|
let v = self.expr(msg);
|
||||||
self.take(&v);
|
self.take(&v);
|
||||||
format!("((dino_err){{ .set = true, .msg = {v} }})")
|
format!("((rex_err){{ .set = true, .msg = {v} }})")
|
||||||
}
|
}
|
||||||
HExprKind::ToIface(inner) => {
|
HExprKind::ToIface(inner) => {
|
||||||
let v = self.expr(inner);
|
let v = self.expr(inner);
|
||||||
@@ -2158,7 +2158,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
Some(t) => t,
|
Some(t) => t,
|
||||||
None => self.place_str(recv),
|
None => self.place_str(recv),
|
||||||
};
|
};
|
||||||
self.line(&format!("if (!{cs}.data) dino_panic(\"called a method on an empty interface value\");"));
|
self.line(&format!("if (!{cs}.data) rex_panic(\"called a method on an empty interface value\");"));
|
||||||
let mut all = vec![format!("{cs}.data")];
|
let mut all = vec![format!("{cs}.data")];
|
||||||
all.extend(vs);
|
all.extend(vs);
|
||||||
self.materialize(e.ty, format!("{cs}.vt->m_{}({})", mangle(method), all.join(", ")))
|
self.materialize(e.ty, format!("{cs}.vt->m_{}({})", mangle(method), all.join(", ")))
|
||||||
@@ -2179,7 +2179,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
Some(t) => t,
|
Some(t) => t,
|
||||||
None => self.place_str(callee),
|
None => self.place_str(callee),
|
||||||
};
|
};
|
||||||
self.line(&format!("if (!{cs}.fn) dino_panic(\"called an empty function value\");"));
|
self.line(&format!("if (!{cs}.fn) rex_panic(\"called an empty function value\");"));
|
||||||
let mut all = vec![format!("{cs}.env")];
|
let mut all = vec![format!("{cs}.env")];
|
||||||
all.extend(vs);
|
all.extend(vs);
|
||||||
self.materialize(e.ty, format!("{cs}.fn({})", all.join(", ")))
|
self.materialize(e.ty, format!("{cs}.fn({})", all.join(", ")))
|
||||||
@@ -2330,28 +2330,28 @@ static dstr {c}_str({c} l) {{
|
|||||||
let vs = self.seq(&refs);
|
let vs = self.seq(&refs);
|
||||||
for (i, (a, v)) in args.iter().zip(&vs).enumerate() {
|
for (i, (a, v)) in args.iter().zip(&vs).enumerate() {
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
self.line("dino_print_sp();");
|
self.line("rex_print_sp();");
|
||||||
}
|
}
|
||||||
let stmt = match a.ty {
|
let stmt = match a.ty {
|
||||||
Ty::Int => format!("dino_print_i64({v});"),
|
Ty::Int => format!("rex_print_i64({v});"),
|
||||||
Ty::Float => format!("dino_print_f64({v});"),
|
Ty::Float => format!("rex_print_f64({v});"),
|
||||||
Ty::Bool => format!("dino_print_bool({v});"),
|
Ty::Bool => format!("rex_print_bool({v});"),
|
||||||
Ty::Char => format!("dino_print_char({v});"),
|
Ty::Char => format!("rex_print_char({v});"),
|
||||||
Ty::Str => format!("dino_print_str({v});"),
|
Ty::Str => format!("rex_print_str({v});"),
|
||||||
Ty::Num(Num::U64) => format!("dino_print_u64({v});"),
|
Ty::Num(Num::U64) => format!("rex_print_u64({v});"),
|
||||||
Ty::Num(Num::F32) => format!("dino_print_f32({v});"),
|
Ty::Num(Num::F32) => format!("rex_print_f32({v});"),
|
||||||
Ty::Num(_) => format!("dino_print_i64((int64_t)({v}));"),
|
Ty::Num(_) => format!("rex_print_i64((int64_t)({v}));"),
|
||||||
Ty::Struct(_) | Ty::Enum(_) | Ty::List(_) | Ty::Map(..) | Ty::Opt(_) | Ty::Error | Ty::Shared(_) | Ty::Weak(_) | Ty::Func(_) | Ty::Iface(_) | Ty::CPtr(_) => {
|
Ty::Struct(_) | Ty::Enum(_) | Ty::List(_) | Ty::Map(..) | Ty::Opt(_) | Ty::Error | Ty::Shared(_) | Ty::Weak(_) | Ty::Func(_) | Ty::Iface(_) | Ty::CPtr(_) => {
|
||||||
let t = self.fresh();
|
let t = self.fresh();
|
||||||
self.line(&format!("dstr {t} = {};", to_str(a.ty, v)));
|
self.line(&format!("dstr {t} = {};", to_str(a.ty, v)));
|
||||||
self.register_temp(&t, Ty::Str);
|
self.register_temp(&t, Ty::Str);
|
||||||
format!("dino_print_str({t});")
|
format!("rex_print_str({t});")
|
||||||
}
|
}
|
||||||
Ty::Tuple(_) | Ty::Unit => unreachable!(),
|
Ty::Tuple(_) | Ty::Unit => unreachable!(),
|
||||||
};
|
};
|
||||||
self.line(&stmt);
|
self.line(&stmt);
|
||||||
}
|
}
|
||||||
self.line("dino_print_nl();");
|
self.line("rex_print_nl();");
|
||||||
String::new()
|
String::new()
|
||||||
}
|
}
|
||||||
HExprKind::Convert(inner) => {
|
HExprKind::Convert(inner) => {
|
||||||
@@ -2359,11 +2359,11 @@ static dstr {c}_str({c} l) {{
|
|||||||
let to = c_ty(e.ty);
|
let to = c_ty(e.ty);
|
||||||
match (inner.ty.is_float(), e.ty) {
|
match (inner.ty.is_float(), e.ty) {
|
||||||
// float to integer: out-of-range values stop at the nearest end, NaN is 0
|
// float to integer: out-of-range values stop at the nearest end, NaN is 0
|
||||||
(true, Ty::Int) => format!("dino_f2i((double){v})"),
|
(true, Ty::Int) => format!("rex_f2i((double){v})"),
|
||||||
(true, Ty::Num(Num::U64)) => format!("dino_f2u64((double){v})"),
|
(true, Ty::Num(Num::U64)) => format!("rex_f2u64((double){v})"),
|
||||||
(true, Ty::Num(k)) if !k.is_float() => {
|
(true, Ty::Num(k)) if !k.is_float() => {
|
||||||
let (lo, hi) = k.range();
|
let (lo, hi) = k.range();
|
||||||
format!("(({to})dino_f2i_clamp((double){v}, INT64_C({lo}), INT64_C({hi})))")
|
format!("(({to})rex_f2i_clamp((double){v}, INT64_C({lo}), INT64_C({hi})))")
|
||||||
}
|
}
|
||||||
// everything else is a plain C conversion (integers wrap)
|
// everything else is a plain C conversion (integers wrap)
|
||||||
_ => format!("(({to}){v})"),
|
_ => format!("(({to}){v})"),
|
||||||
@@ -2398,7 +2398,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
let t = self.fresh();
|
let t = self.fresh();
|
||||||
self.line(&format!("dstr {t} = dino_cat_n({}, (dstr[]){{{}}});", cs.len(), cs.join(", ")));
|
self.line(&format!("dstr {t} = rex_cat_n({}, (dstr[]){{{}}});", cs.len(), cs.join(", ")));
|
||||||
self.register_temp(&t, Ty::Str);
|
self.register_temp(&t, Ty::Str);
|
||||||
t
|
t
|
||||||
}
|
}
|
||||||
@@ -2441,7 +2441,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
let (t, n, ct) = (self.fresh(), elems.len(), c_ty(*elem));
|
let (t, n, ct) = (self.fresh(), elems.len(), c_ty(*elem));
|
||||||
self.line(&format!("{c} {t} = {{0}};"));
|
self.line(&format!("{c} {t} = {{0}};"));
|
||||||
self.line(&format!("{t}.p = ({ct} *)malloc({n} * sizeof({ct}));"));
|
self.line(&format!("{t}.p = ({ct} *)malloc({n} * sizeof({ct}));"));
|
||||||
self.line(&format!("if (!{t}.p) dino_panic(\"out of memory\");"));
|
self.line(&format!("if (!{t}.p) rex_panic(\"out of memory\");"));
|
||||||
self.line(&format!("{t}.len = {t}.cap = {n};"));
|
self.line(&format!("{t}.len = {t}.cap = {n};"));
|
||||||
for (i, v) in vs.iter().enumerate() {
|
for (i, v) in vs.iter().enumerate() {
|
||||||
self.line(&format!("{t}.p[{i}] = {v};"));
|
self.line(&format!("{t}.p[{i}] = {v};"));
|
||||||
@@ -2513,7 +2513,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
let copy = self.copy_of(et, &format!("{m}.{src}[i]"));
|
let copy = self.copy_of(et, &format!("{m}.{src}[i]"));
|
||||||
self.line(&format!("{lc} {t} = {{0}};"));
|
self.line(&format!("{lc} {t} = {{0}};"));
|
||||||
self.line(&format!(
|
self.line(&format!(
|
||||||
"if ({m}.len > 0) {{ {t}.p = ({ect} *)malloc((size_t){m}.len * sizeof({ect})); if (!{t}.p) dino_panic(\"out of memory\"); {t}.len = {t}.cap = {m}.len; for (int64_t i = 0; i < {m}.len; i++) {t}.p[i] = {copy}; }}"
|
"if ({m}.len > 0) {{ {t}.p = ({ect} *)malloc((size_t){m}.len * sizeof({ect})); if (!{t}.p) rex_panic(\"out of memory\"); {t}.len = {t}.cap = {m}.len; for (int64_t i = 0; i < {m}.len; i++) {t}.p[i] = {copy}; }}"
|
||||||
));
|
));
|
||||||
self.register_temp(&t, e.ty);
|
self.register_temp(&t, e.ty);
|
||||||
t
|
t
|
||||||
@@ -2642,7 +2642,7 @@ static dstr {c}_str({c} l) {{
|
|||||||
HPat::Variant { index, .. } => Some(format!("{s}.tag == {index}")),
|
HPat::Variant { index, .. } => Some(format!("{s}.tag == {index}")),
|
||||||
HPat::Int(k) => Some(format!("{s} == INT64_C({k})")),
|
HPat::Int(k) => Some(format!("{s} == INT64_C({k})")),
|
||||||
HPat::Bool(b) => Some(format!("{s} == {b}")),
|
HPat::Bool(b) => Some(format!("{s} == {b}")),
|
||||||
HPat::Str(t) => Some(format!("dino_streq({s}, {})", str_lit(t))),
|
HPat::Str(t) => Some(format!("rex_streq({s}, {})", str_lit(t))),
|
||||||
HPat::CatchAll(_) => None,
|
HPat::CatchAll(_) => None,
|
||||||
};
|
};
|
||||||
// the last arm needs no test: the checker made sure the arms cover everything
|
// the last arm needs no test: the checker made sure the arms cover everything
|
||||||
@@ -2766,9 +2766,9 @@ static dstr {c}_str({c} l) {{
|
|||||||
(BinOp::Div | BinOp::Rem, Ty::Num(k)) if !k.is_float() => {
|
(BinOp::Div | BinOp::Rem, Ty::Num(k)) if !k.is_float() => {
|
||||||
let name = if op == BinOp::Div { "div" } else { "rem" };
|
let name = if op == BinOp::Div { "div" } else { "rem" };
|
||||||
let call = if k == Num::U64 {
|
let call = if k == Num::U64 {
|
||||||
format!("dino_u{name}({l}, {r})")
|
format!("rex_u{name}({l}, {r})")
|
||||||
} else {
|
} else {
|
||||||
format!("(({})dino_{name}((int64_t){l}, (int64_t){r}))", num_c(k))
|
format!("(({})rex_{name}((int64_t){l}, (int64_t){r}))", num_c(k))
|
||||||
};
|
};
|
||||||
self.materialize(lhs.ty, call)
|
self.materialize(lhs.ty, call)
|
||||||
}
|
}
|
||||||
@@ -2776,14 +2776,14 @@ static dstr {c}_str({c} l) {{
|
|||||||
(BinOp::Add | BinOp::Sub | BinOp::Mul, Ty::Num(k)) if !k.is_float() => {
|
(BinOp::Add | BinOp::Sub | BinOp::Mul, Ty::Num(k)) if !k.is_float() => {
|
||||||
format!("(({})({l} {} {r}))", num_c(k), sym(op))
|
format!("(({})({l} {} {r}))", num_c(k), sym(op))
|
||||||
}
|
}
|
||||||
(BinOp::Div, Ty::Int) => self.materialize(Ty::Int, format!("dino_div({l}, {r})")),
|
(BinOp::Div, Ty::Int) => self.materialize(Ty::Int, format!("rex_div({l}, {r})")),
|
||||||
(BinOp::Rem, Ty::Int) => self.materialize(Ty::Int, format!("dino_rem({l}, {r})")),
|
(BinOp::Rem, Ty::Int) => self.materialize(Ty::Int, format!("rex_rem({l}, {r})")),
|
||||||
(BinOp::Eq | BinOp::Ne, Ty::Enum(_)) => format!("({l}.tag {} {r}.tag)", sym(op)),
|
(BinOp::Eq | BinOp::Ne, Ty::Enum(_)) => format!("({l}.tag {} {r}.tag)", sym(op)),
|
||||||
(BinOp::Add, Ty::Str) => self.materialize(Ty::Str, format!("dino_cat({l}, {r})")),
|
(BinOp::Add, Ty::Str) => self.materialize(Ty::Str, format!("rex_cat({l}, {r})")),
|
||||||
(BinOp::Eq, Ty::Str) => format!("dino_streq({l}, {r})"),
|
(BinOp::Eq, Ty::Str) => format!("rex_streq({l}, {r})"),
|
||||||
(BinOp::Ne, Ty::Str) => format!("(!dino_streq({l}, {r}))"),
|
(BinOp::Ne, Ty::Str) => format!("(!rex_streq({l}, {r}))"),
|
||||||
(BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge, Ty::Str) => {
|
(BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge, Ty::Str) => {
|
||||||
format!("(dino_strcmp({l}, {r}) {} 0)", sym(op))
|
format!("(rex_strcmp({l}, {r}) {} 0)", sym(op))
|
||||||
}
|
}
|
||||||
_ => format!("({l} {} {r})", sym(op)),
|
_ => format!("({l} {} {r})", sym(op)),
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-8
@@ -14,7 +14,7 @@ pub fn load_c_headers(main: &Program, modules: &[(String, Program)], dir: &Path)
|
|||||||
let mut libs: Vec<cheader::Lib> = Vec::new();
|
let mut libs: Vec<cheader::Lib> = Vec::new();
|
||||||
let all = std::iter::once(("", main)).chain(modules.iter().map(|(k, p)| (k.as_str(), p)));
|
let all = std::iter::once(("", main)).chain(modules.iter().map(|(k, p)| (k.as_str(), p)));
|
||||||
for (key, p) in all {
|
for (key, p) in all {
|
||||||
// `import a.b` lives in a/b.dino: its headers are found next to it
|
// `import a.b` lives in a/b.rex: its headers are found next to it
|
||||||
let mut here = dir.to_path_buf();
|
let mut here = dir.to_path_buf();
|
||||||
let parts: Vec<&str> = key.split('.').collect();
|
let parts: Vec<&str> = key.split('.').collect();
|
||||||
for part in &parts[..parts.len().saturating_sub(1)] {
|
for part in &parts[..parts.len().saturating_sub(1)] {
|
||||||
@@ -33,7 +33,7 @@ pub fn load_c_headers(main: &Program, modules: &[(String, Program)], dir: &Path)
|
|||||||
Ok(libs)
|
Ok(libs)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Dino source -> C source, for a program in a single file. C headers it imports are looked
|
/// Rex source -> C source, for a program in a single file. C headers it imports are looked
|
||||||
/// for in the current folder and the system's.
|
/// for in the current folder and the system's.
|
||||||
pub fn compile_to_c(src: &str) -> PResult<String> {
|
pub fn compile_to_c(src: &str) -> PResult<String> {
|
||||||
let ast = parser::parse(src)?;
|
let ast = parser::parse(src)?;
|
||||||
@@ -78,7 +78,7 @@ pub fn compile_file(path: &str) -> Result<String, String> {
|
|||||||
let src = std::fs::read_to_string(path).map_err(|e| format!("error: cannot read {path}: {e}"))?;
|
let src = std::fs::read_to_string(path).map_err(|e| format!("error: cannot read {path}: {e}"))?;
|
||||||
let dir = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default();
|
let dir = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default();
|
||||||
compile_project(path, &src, |key| {
|
compile_project(path, &src, |key| {
|
||||||
let file = dir.join(format!("{}.dino", key.replace('.', "/")));
|
let file = dir.join(format!("{}.rex", key.replace('.', "/")));
|
||||||
std::fs::read_to_string(&file).ok().map(|s| (file.display().to_string(), s))
|
std::fs::read_to_string(&file).ok().map(|s| (file.display().to_string(), s))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -88,7 +88,7 @@ fn unique_name(tag: &str, ext: &str) -> PathBuf {
|
|||||||
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||||
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
|
let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
|
||||||
std::env::temp_dir().join(format!("dino-{}-{}-{}-{}{}", std::process::id(), nanos, n, tag, ext))
|
std::env::temp_dir().join(format!("rex-{}-{}-{}-{}{}", std::process::id(), nanos, n, tag, ext))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A path for a throw-away executable.
|
/// A path for a throw-away executable.
|
||||||
@@ -102,11 +102,11 @@ pub fn build_exe(c_code: &str, out: &Path) -> Result<(), String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Like `build_exe`, with explicit compiler flags (used by tests to turn on strict warnings).
|
/// Like `build_exe`, with explicit compiler flags (used by tests to turn on strict warnings).
|
||||||
/// The generated code says which C libraries it needs in `// dino-...:` lines at the top.
|
/// The generated code says which C libraries it needs in `// rex-...:` lines at the top.
|
||||||
pub fn build_exe_with(c_code: &str, out: &Path, flags: &[&str]) -> Result<(), String> {
|
pub fn build_exe_with(c_code: &str, out: &Path, flags: &[&str]) -> Result<(), String> {
|
||||||
let (mut cflags, mut libs, mut sources) = (Vec::new(), Vec::new(), Vec::new());
|
let (mut cflags, mut libs, mut sources) = (Vec::new(), Vec::new(), Vec::new());
|
||||||
for line in c_code.lines().take_while(|l| l.starts_with("// dino-")) {
|
for line in c_code.lines().take_while(|l| l.starts_with("// rex-")) {
|
||||||
let (kind, value) = line["// dino-".len()..].split_once(": ").unwrap_or(("", ""));
|
let (kind, value) = line["// rex-".len()..].split_once(": ").unwrap_or(("", ""));
|
||||||
match kind {
|
match kind {
|
||||||
"cflag" => cflags.push(value.to_string()),
|
"cflag" => cflags.push(value.to_string()),
|
||||||
"lib" => libs.push(value.to_string()),
|
"lib" => libs.push(value.to_string()),
|
||||||
@@ -173,7 +173,7 @@ pub fn build_exe_with(c_code: &str, out: &Path, flags: &[&str]) -> Result<(), St
|
|||||||
} else if uses_c {
|
} else if uses_c {
|
||||||
Err(format!("the C compiler rejected the program:\n{err}"))
|
Err(format!("the C compiler rejected the program:\n{err}"))
|
||||||
} else {
|
} else {
|
||||||
Err(format!("the C compiler rejected the generated code (this is a bug in Dino):\n{err}"))
|
Err(format!("the C compiler rejected the generated code (this is a bug in Rex):\n{err}"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(_) => Ok(()),
|
Ok(_) => Ok(()),
|
||||||
|
|||||||
+1
-1
@@ -25,7 +25,7 @@ impl Diag {
|
|||||||
/// Render like:
|
/// Render like:
|
||||||
/// ```text
|
/// ```text
|
||||||
/// error: expected `}`, found end of file
|
/// error: expected `}`, found end of file
|
||||||
/// --> hello.dino:3:10
|
/// --> hello.rex:3:10
|
||||||
/// |
|
/// |
|
||||||
/// 3 | func main() {
|
/// 3 | func main() {
|
||||||
/// | ^
|
/// | ^
|
||||||
|
|||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
//! The code formatter behind `dino fmt`.
|
//! The code formatter behind `rex fmt`.
|
||||||
//!
|
//!
|
||||||
//! It works on the text, not on the syntax tree, so comments and blank lines survive. It
|
//! It works on the text, not on the syntax tree, so comments and blank lines survive. It
|
||||||
//! never moves a line break: it fixes the indentation, the spaces between tokens and runs of
|
//! never moves a line break: it fixes the indentation, the spaces between tokens and runs of
|
||||||
@@ -49,11 +49,11 @@ pub fn format(src: &str) -> Result<String, Diag> {
|
|||||||
// the safety net: the same tokens in, the same tokens out
|
// the safety net: the same tokens in, the same tokens out
|
||||||
let before = fingerprint(src)?;
|
let before = fingerprint(src)?;
|
||||||
let after = fingerprint(&out).map_err(|d| {
|
let after = fingerprint(&out).map_err(|d| {
|
||||||
Diag::new(format!("the formatter produced code that doesn't lex ({}); this is a bug in `dino fmt`", d.msg), d.span)
|
Diag::new(format!("the formatter produced code that doesn't lex ({}); this is a bug in `rex fmt`", d.msg), d.span)
|
||||||
})?;
|
})?;
|
||||||
if before != after {
|
if before != after {
|
||||||
return Err(Diag::new(
|
return Err(Diag::new(
|
||||||
"the formatter would change the meaning of this file; this is a bug in `dino fmt`, nothing was written",
|
"the formatter would change the meaning of this file; this is a bug in `rex fmt`, nothing was written",
|
||||||
crate::ast::Span::default(),
|
crate::ast::Span::default(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -87,7 +87,7 @@ pub enum HArmBody {
|
|||||||
pub struct HStruct {
|
pub struct HStruct {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub fields: Vec<(String, Ty)>,
|
pub fields: Vec<(String, Ty)>,
|
||||||
/// For a struct from a C header: how C spells it (`Color`, `struct timeval`). Dino keeps its
|
/// For a struct from a C header: how C spells it (`Color`, `struct timeval`). Rex keeps its
|
||||||
/// own copy of the fields and converts at calls.
|
/// own copy of the fields and converts at calls.
|
||||||
pub c: Option<String>,
|
pub c: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -106,7 +106,7 @@ pub struct CInfo {
|
|||||||
pub enum CArg {
|
pub enum CArg {
|
||||||
/// As it is (numbers, pointers) or converted (structs).
|
/// As it is (numbers, pointers) or converted (structs).
|
||||||
Value,
|
Value,
|
||||||
/// A Dino string as a C string (`const char *`), copied for the call.
|
/// A Rex string as a C string (`const char *`), copied for the call.
|
||||||
Str,
|
Str,
|
||||||
/// `nil`: a NULL pointer.
|
/// `nil`: a NULL pointer.
|
||||||
Null,
|
Null,
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
//! A quick map of a Dino file for editors: what it declares, what it imports, and which names
|
//! A quick map of a Rex file for editors: what it declares, what it imports, and which names
|
||||||
//! are visible at a point. It reads the token stream only (not the syntax tree), so it keeps
|
//! are visible at a point. It reads the token stream only (not the syntax tree), so it keeps
|
||||||
//! working while the code is half typed and has errors in it.
|
//! working while the code is half typed and has errors in it.
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -573,14 +573,14 @@ impl Lexer {
|
|||||||
if self.eat('&') {
|
if self.eat('&') {
|
||||||
Tok::AndAnd
|
Tok::AndAnd
|
||||||
} else {
|
} else {
|
||||||
return Err(Diag::new("a single `&` is not part of Dino; use `&&` for \"and\"", span));
|
return Err(Diag::new("a single `&` is not part of Rex; use `&&` for \"and\"", span));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
'|' => {
|
'|' => {
|
||||||
if self.eat('|') {
|
if self.eat('|') {
|
||||||
Tok::OrOr
|
Tok::OrOr
|
||||||
} else {
|
} else {
|
||||||
return Err(Diag::new("a single `|` is not part of Dino; use `||` for \"or\"", span));
|
return Err(Diag::new("a single `|` is not part of Rex; use `||` for \"or\"", span));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
other => return Err(Diag::new(format!("unexpected character `{other}`"), span)),
|
other => return Err(Diag::new(format!("unexpected character `{other}`"), span)),
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
//! The Dino compiler.
|
//! The Rex compiler.
|
||||||
|
|
||||||
pub mod ast;
|
pub mod ast;
|
||||||
pub mod check;
|
pub mod check;
|
||||||
|
|||||||
+3
-3
@@ -1,5 +1,5 @@
|
|||||||
//! Finds the files a program imports. `import utils` loads `utils.dino` from the
|
//! Finds the files a program imports. `import utils` loads `utils.rex` from the
|
||||||
//! folder of the main file; `import a.b` loads `a/b.dino`.
|
//! folder of the main file; `import a.b` loads `a/b.rex`.
|
||||||
|
|
||||||
use crate::ast::{Item, Program};
|
use crate::ast::{Item, Program};
|
||||||
use crate::error::{Diag, PResult};
|
use crate::error::{Diag, PResult};
|
||||||
@@ -48,7 +48,7 @@ fn load_imports(
|
|||||||
return Err(Diag::new(format!("circular import: {}", cycle.join(" -> ")), i.span).in_module(from));
|
return Err(Diag::new(format!("circular import: {}", cycle.join(" -> ")), i.span).in_module(from));
|
||||||
}
|
}
|
||||||
let Some((_, src)) = read(&key) else {
|
let Some((_, src)) = read(&key) else {
|
||||||
let file = format!("{}.dino", key.replace('.', "/"));
|
let file = format!("{}.rex", key.replace('.', "/"));
|
||||||
return Err(Diag::new(
|
return Err(Diag::new(
|
||||||
format!(
|
format!(
|
||||||
"cannot find module `{key}` (looked for {file} next to your program; built-in modules: {})",
|
"cannot find module `{key}` (looked for {file} next to your program; built-in modules: {})",
|
||||||
|
|||||||
+7
-7
@@ -1,4 +1,4 @@
|
|||||||
//! The language server (`dino lsp`): talks to an editor over stdin/stdout and shows the
|
//! The language server (`rex lsp`): talks to an editor over stdin/stdout and shows the
|
||||||
//! compiler's errors while you type, and formats the file on request.
|
//! compiler's errors while you type, and formats the file on request.
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -81,7 +81,7 @@ impl Server {
|
|||||||
("signatureHelpProvider", Json::obj(vec![("triggerCharacters", Json::Arr(vec![Json::str("("), Json::str(",")]))])),
|
("signatureHelpProvider", Json::obj(vec![("triggerCharacters", Json::Arr(vec![Json::str("("), Json::str(",")]))])),
|
||||||
]),
|
]),
|
||||||
),
|
),
|
||||||
("serverInfo", Json::obj(vec![("name", Json::str("dino"))])),
|
("serverInfo", Json::obj(vec![("name", Json::str("rex"))])),
|
||||||
])),
|
])),
|
||||||
"shutdown" => {
|
"shutdown" => {
|
||||||
self.shutdown = true;
|
self.shutdown = true;
|
||||||
@@ -171,7 +171,7 @@ impl Server {
|
|||||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||||
let here = dir.clone().unwrap_or_default();
|
let here = dir.clone().unwrap_or_default();
|
||||||
driver::diagnose(text, &here, |key| {
|
driver::diagnose(text, &here, |key| {
|
||||||
let file = dir.as_ref()?.join(format!("{}.dino", key.replace('.', "/")));
|
let file = dir.as_ref()?.join(format!("{}.rex", key.replace('.', "/")));
|
||||||
// an import that is open in the editor counts with its unsaved changes
|
// an import that is open in the editor counts with its unsaved changes
|
||||||
for (u, t) in docs {
|
for (u, t) in docs {
|
||||||
if uri_to_path(u).as_deref() == Some(file.as_path()) {
|
if uri_to_path(u).as_deref() == Some(file.as_path()) {
|
||||||
@@ -226,12 +226,12 @@ fn diagnostic(d: &Diag, text: &str) -> Json {
|
|||||||
Json::obj(vec![
|
Json::obj(vec![
|
||||||
("range", range(start, end)),
|
("range", range(start, end)),
|
||||||
("severity", Json::Num(1.0)),
|
("severity", Json::Num(1.0)),
|
||||||
("source", Json::str("dino")),
|
("source", Json::str("rex")),
|
||||||
("message", Json::str(message)),
|
("message", Json::str(message)),
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `file:///home/me/a%20b.dino` -> `/home/me/a b.dino`
|
/// `file:///home/me/a%20b.rex` -> `/home/me/a b.rex`
|
||||||
fn uri_to_path(uri: &str) -> Option<PathBuf> {
|
fn uri_to_path(uri: &str) -> Option<PathBuf> {
|
||||||
let rest = uri.strip_prefix("file://")?;
|
let rest = uri.strip_prefix("file://")?;
|
||||||
let bytes = rest.as_bytes();
|
let bytes = rest.as_bytes();
|
||||||
@@ -399,7 +399,7 @@ impl Server {
|
|||||||
/// The source of the module `key` as seen from the file `uri`: open in the editor, or on disk.
|
/// The source of the module `key` as seen from the file `uri`: open in the editor, or on disk.
|
||||||
fn module_source(&self, uri: &str, key: &str) -> Option<(String, String)> {
|
fn module_source(&self, uri: &str, key: &str) -> Option<(String, String)> {
|
||||||
let dir = uri_to_path(uri)?.parent()?.to_path_buf();
|
let dir = uri_to_path(uri)?.parent()?.to_path_buf();
|
||||||
let file = dir.join(format!("{}.dino", key.replace('.', "/")));
|
let file = dir.join(format!("{}.rex", key.replace('.', "/")));
|
||||||
let target = path_to_uri(&file);
|
let target = path_to_uri(&file);
|
||||||
for (u, t) in &self.docs {
|
for (u, t) in &self.docs {
|
||||||
if uri_to_path(u).as_deref() == Some(file.as_path()) {
|
if uri_to_path(u).as_deref() == Some(file.as_path()) {
|
||||||
@@ -629,7 +629,7 @@ impl Server {
|
|||||||
};
|
};
|
||||||
if a > 0 && chars[a - 1] == '.' {
|
if a > 0 && chars[a - 1] == '.' {
|
||||||
let left = word_before(line_text, a - 1);
|
let left = word_before(line_text, a - 1);
|
||||||
// a C header: everything Dino can use from it
|
// a C header: everything Rex can use from it
|
||||||
if let Some(imp) = left.as_deref().and_then(|q| ix.imports.iter().find(|i| i.name == q && i.header.is_some())) {
|
if let Some(imp) = left.as_deref().and_then(|q| ix.imports.iter().find(|i| i.name == q && i.header.is_some())) {
|
||||||
if let Some(lib) = self.c_lib(uri, imp) {
|
if let Some(lib) = self.c_lib(uri, imp) {
|
||||||
for n in lib.names() {
|
for n in lib.names() {
|
||||||
|
|||||||
+24
-24
@@ -1,20 +1,20 @@
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::{env, fs, process};
|
use std::{env, fs, process};
|
||||||
|
|
||||||
use dino::{driver, fmt, lexer, lsp, parser};
|
use rex::{driver, fmt, lexer, lsp, parser};
|
||||||
|
|
||||||
fn usage() -> ! {
|
fn usage() -> ! {
|
||||||
eprintln!("Dino compiler (work in progress)\n");
|
eprintln!("Rex compiler (work in progress)\n");
|
||||||
eprintln!("usage:");
|
eprintln!("usage:");
|
||||||
eprintln!(" dino run <file.dino> [args...] compile and run (args go to the program)");
|
eprintln!(" rex run <file.rex> [args...] compile and run (args go to the program)");
|
||||||
eprintln!(" dino build <file.dino> [-o out] compile to an executable");
|
eprintln!(" rex build <file.rex> [-o out] compile to an executable");
|
||||||
eprintln!(" dino emit-c <file.dino> print the generated C code");
|
eprintln!(" rex emit-c <file.rex> print the generated C code");
|
||||||
eprintln!(" dino check <file.dino> check for errors without building");
|
eprintln!(" rex check <file.rex> check for errors without building");
|
||||||
eprintln!(" dino fmt [--check] <file|dir>.. format code in place (--check only reports; `-` = stdin to stdout)");
|
eprintln!(" rex fmt [--check] <file|dir>.. format code in place (--check only reports; `-` = stdin to stdout)");
|
||||||
eprintln!(" dino lsp run the language server (for editors)");
|
eprintln!(" rex lsp run the language server (for editors)");
|
||||||
eprintln!(" dino header <file.h> [name] show what Dino can use from a C header");
|
eprintln!(" rex header <file.h> [name] show what Rex can use from a C header");
|
||||||
eprintln!(" dino parse <file.dino> print the syntax tree");
|
eprintln!(" rex parse <file.rex> print the syntax tree");
|
||||||
eprintln!(" dino tokens <file.dino> print the tokens");
|
eprintln!(" rex tokens <file.rex> print the tokens");
|
||||||
process::exit(2);
|
process::exit(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,20 +23,20 @@ fn die(msg: &str) -> ! {
|
|||||||
process::exit(1);
|
process::exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// All `.dino` files at `path` (a file, or a folder searched recursively).
|
/// All `.rex` files at `path` (a file, or a folder searched recursively).
|
||||||
fn dino_files(path: &std::path::Path, out: &mut Vec<PathBuf>) {
|
fn rex_files(path: &std::path::Path, out: &mut Vec<PathBuf>) {
|
||||||
if path.is_dir() {
|
if path.is_dir() {
|
||||||
let mut entries: Vec<PathBuf> = fs::read_dir(path).map(|r| r.filter_map(|e| e.ok().map(|e| e.path())).collect()).unwrap_or_default();
|
let mut entries: Vec<PathBuf> = fs::read_dir(path).map(|r| r.filter_map(|e| e.ok().map(|e| e.path())).collect()).unwrap_or_default();
|
||||||
entries.sort();
|
entries.sort();
|
||||||
for e in entries {
|
for e in entries {
|
||||||
dino_files(&e, out);
|
rex_files(&e, out);
|
||||||
}
|
}
|
||||||
} else if path.extension().map_or(false, |e| e == "dino") || path.is_file() && out.is_empty() && path.extension().is_none() {
|
} else if path.extension().map_or(false, |e| e == "rex") || path.is_file() && out.is_empty() && path.extension().is_none() {
|
||||||
out.push(path.to_path_buf());
|
out.push(path.to_path_buf());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `dino header zlib.h [name] [--link z]`: what Dino code can use from a C header.
|
/// `rex header zlib.h [name] [--link z]`: what Rex code can use from a C header.
|
||||||
fn run_header(args: &[String]) -> ! {
|
fn run_header(args: &[String]) -> ! {
|
||||||
let mut header: Option<&str> = None;
|
let mut header: Option<&str> = None;
|
||||||
let mut filter: Option<&str> = None;
|
let mut filter: Option<&str> = None;
|
||||||
@@ -51,7 +51,7 @@ fn run_header(args: &[String]) -> ! {
|
|||||||
}
|
}
|
||||||
let Some(header) = header else { usage() };
|
let Some(header) = header else { usage() };
|
||||||
let dir = env::current_dir().unwrap_or_default();
|
let dir = env::current_dir().unwrap_or_default();
|
||||||
let lib = dino::cheader::load(header, &dir, link).unwrap_or_else(|e| die(&format!("error: {e}")));
|
let lib = rex::cheader::load(header, &dir, link).unwrap_or_else(|e| die(&format!("error: {e}")));
|
||||||
let shown = |n: &str| filter.map_or(true, |f| n.to_lowercase().contains(&f.to_lowercase()));
|
let shown = |n: &str| filter.map_or(true, |f| n.to_lowercase().contains(&f.to_lowercase()));
|
||||||
let mut text = format!("import \"{header}\" // use the names below as {}.name\n", lib.prefix);
|
let mut text = format!("import \"{header}\" // use the names below as {}.name\n", lib.prefix);
|
||||||
if !lib.libs.is_empty() || !lib.cflags.is_empty() {
|
if !lib.libs.is_empty() || !lib.cflags.is_empty() {
|
||||||
@@ -77,7 +77,7 @@ fn run_header(args: &[String]) -> ! {
|
|||||||
);
|
);
|
||||||
section("constants", lib.consts.iter().filter(|c| shown(&c.name)).map(|c| lib.describe(&c.name).unwrap()).collect());
|
section("constants", lib.consts.iter().filter(|c| shown(&c.name)).map(|c| lib.describe(&c.name).unwrap()).collect());
|
||||||
section(
|
section(
|
||||||
"functions Dino can't call yet",
|
"functions Rex can't call yet",
|
||||||
lib.funcs
|
lib.funcs
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|f| shown(&f.name))
|
.filter(|f| shown(&f.name))
|
||||||
@@ -89,9 +89,9 @@ fn run_header(args: &[String]) -> ! {
|
|||||||
process::exit(0);
|
process::exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `dino fmt [--check] files-or-folders...`
|
/// `rex fmt [--check] files-or-folders...`
|
||||||
fn run_fmt(args: &[String]) -> ! {
|
fn run_fmt(args: &[String]) -> ! {
|
||||||
// `dino fmt -`: text in on stdin, tidy text out on stdout (for editors)
|
// `rex fmt -`: text in on stdin, tidy text out on stdout (for editors)
|
||||||
if args.len() == 1 && args[0] == "-" {
|
if args.len() == 1 && args[0] == "-" {
|
||||||
let mut src = String::new();
|
let mut src = String::new();
|
||||||
if std::io::Read::read_to_string(&mut std::io::stdin(), &mut src).is_err() {
|
if std::io::Read::read_to_string(&mut std::io::stdin(), &mut src).is_err() {
|
||||||
@@ -117,9 +117,9 @@ fn run_fmt(args: &[String]) -> ! {
|
|||||||
if path.is_file() {
|
if path.is_file() {
|
||||||
files.push(path);
|
files.push(path);
|
||||||
} else {
|
} else {
|
||||||
dino_files(&path, &mut files);
|
rex_files(&path, &mut files);
|
||||||
if files.len() == before {
|
if files.len() == before {
|
||||||
die(&format!("error: no .dino files found at {p}"));
|
die(&format!("error: no .rex files found at {p}"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -170,7 +170,7 @@ fn main() {
|
|||||||
let cmd = args[0].as_str();
|
let cmd = args[0].as_str();
|
||||||
let path = &args[1];
|
let path = &args[1];
|
||||||
let mut out: Option<PathBuf> = None;
|
let mut out: Option<PathBuf> = None;
|
||||||
// `dino run file.dino a b c` hands `a b c` to the program; `build` takes `-o`
|
// `rex run file.rex a b c` hands `a b c` to the program; `build` takes `-o`
|
||||||
let mut program_args: Vec<String> = Vec::new();
|
let mut program_args: Vec<String> = Vec::new();
|
||||||
let mut rest = args[2..].iter();
|
let mut rest = args[2..].iter();
|
||||||
while let Some(a) = rest.next() {
|
while let Some(a) = rest.next() {
|
||||||
@@ -182,7 +182,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let src = fs::read_to_string(path).unwrap_or_else(|e| die(&format!("error: cannot read {path}: {e}")));
|
let src = fs::read_to_string(path).unwrap_or_else(|e| die(&format!("error: cannot read {path}: {e}")));
|
||||||
let fail = |d: dino::error::Diag| -> ! { die(&d.render(path, &src)) };
|
let fail = |d: rex::error::Diag| -> ! { die(&d.render(path, &src)) };
|
||||||
|
|
||||||
match cmd {
|
match cmd {
|
||||||
"tokens" => match lexer::lex(&src) {
|
"tokens" => match lexer::lex(&src) {
|
||||||
|
|||||||
+167
-167
@@ -1,4 +1,4 @@
|
|||||||
/* Dino runtime (generated programs include this verbatim). */
|
/* Rex runtime (generated programs include this verbatim). */
|
||||||
#define _POSIX_C_SOURCE 200809L
|
#define _POSIX_C_SOURCE 200809L
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
@@ -14,62 +14,62 @@
|
|||||||
(NULL for literals, which live forever). */
|
(NULL for literals, which live forever). */
|
||||||
typedef struct { const char *p; int64_t n; int64_t *rc; } dstr;
|
typedef struct { const char *p; int64_t n; int64_t *rc; } dstr;
|
||||||
|
|
||||||
static void dino_panic(const char *msg) {
|
static void rex_panic(const char *msg) {
|
||||||
fflush(stdout);
|
fflush(stdout);
|
||||||
fprintf(stderr, "panic: %s\n", msg);
|
fprintf(stderr, "panic: %s\n", msg);
|
||||||
exit(2);
|
exit(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void dino_index_panic(int64_t i, int64_t n) {
|
static void rex_index_panic(int64_t i, int64_t n) {
|
||||||
fflush(stdout);
|
fflush(stdout);
|
||||||
fprintf(stderr, "panic: index %lld is out of range (the length is %lld)\n", (long long)i, (long long)n);
|
fprintf(stderr, "panic: index %lld is out of range (the length is %lld)\n", (long long)i, (long long)n);
|
||||||
exit(2);
|
exit(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void dino_slice_panic(int64_t lo, int64_t hi, int64_t n) {
|
static void rex_slice_panic(int64_t lo, int64_t hi, int64_t n) {
|
||||||
fflush(stdout);
|
fflush(stdout);
|
||||||
fprintf(stderr, "panic: slice %lld..%lld is out of range (the length is %lld)\n", (long long)lo, (long long)hi, (long long)n);
|
fprintf(stderr, "panic: slice %lld..%lld is out of range (the length is %lld)\n", (long long)lo, (long long)hi, (long long)n);
|
||||||
exit(2);
|
exit(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline dstr dino_lit(const char *p, int64_t n) { dstr s = {p, n, NULL}; return s; }
|
static inline dstr rex_lit(const char *p, int64_t n) { dstr s = {p, n, NULL}; return s; }
|
||||||
|
|
||||||
/* A new heap string of n bytes (plus a trailing 0), counted once. */
|
/* A new heap string of n bytes (plus a trailing 0), counted once. */
|
||||||
static char *dino_str_alloc(int64_t n, int64_t **rc) {
|
static char *rex_str_alloc(int64_t n, int64_t **rc) {
|
||||||
int64_t *blk = (int64_t *)malloc(sizeof(int64_t) + (size_t)n + 1);
|
int64_t *blk = (int64_t *)malloc(sizeof(int64_t) + (size_t)n + 1);
|
||||||
if (!blk) dino_panic("out of memory");
|
if (!blk) rex_panic("out of memory");
|
||||||
*blk = 1;
|
*blk = 1;
|
||||||
*rc = blk;
|
*rc = blk;
|
||||||
return (char *)(blk + 1);
|
return (char *)(blk + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline dstr dino_str_retain(dstr s) { if (s.rc) ++*s.rc; return s; }
|
static inline dstr rex_str_retain(dstr s) { if (s.rc) ++*s.rc; return s; }
|
||||||
static inline void dino_str_release(dstr s) { if (s.rc && --*s.rc == 0) free(s.rc); }
|
static inline void rex_str_release(dstr s) { if (s.rc && --*s.rc == 0) free(s.rc); }
|
||||||
|
|
||||||
static inline int64_t dino_div(int64_t a, int64_t b) {
|
static inline int64_t rex_div(int64_t a, int64_t b) {
|
||||||
if (b == 0) dino_panic("integer division by zero");
|
if (b == 0) rex_panic("integer division by zero");
|
||||||
if (b == -1) return (int64_t)(0 - (uint64_t)a);
|
if (b == -1) return (int64_t)(0 - (uint64_t)a);
|
||||||
return a / b;
|
return a / b;
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline int64_t dino_rem(int64_t a, int64_t b) {
|
static inline int64_t rex_rem(int64_t a, int64_t b) {
|
||||||
if (b == 0) dino_panic("integer remainder by zero");
|
if (b == 0) rex_panic("integer remainder by zero");
|
||||||
if (b == -1) return 0;
|
if (b == -1) return 0;
|
||||||
return a % b;
|
return a % b;
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline int64_t dino_f2i(double x) {
|
static inline int64_t rex_f2i(double x) {
|
||||||
if (x != x) return 0;
|
if (x != x) return 0;
|
||||||
if (x >= 9223372036854775807.0) return INT64_MAX;
|
if (x >= 9223372036854775807.0) return INT64_MAX;
|
||||||
if (x <= -9223372036854775808.0) return INT64_MIN;
|
if (x <= -9223372036854775808.0) return INT64_MIN;
|
||||||
return (int64_t)x;
|
return (int64_t)x;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_cat_n(int n, const dstr *parts) {
|
static dstr rex_cat_n(int n, const dstr *parts) {
|
||||||
int64_t total = 0;
|
int64_t total = 0;
|
||||||
for (int i = 0; i < n; i++) total += parts[i].n;
|
for (int i = 0; i < n; i++) total += parts[i].n;
|
||||||
int64_t *rc;
|
int64_t *rc;
|
||||||
char *buf = dino_str_alloc(total, &rc);
|
char *buf = rex_str_alloc(total, &rc);
|
||||||
int64_t at = 0;
|
int64_t at = 0;
|
||||||
for (int i = 0; i < n; i++) {
|
for (int i = 0; i < n; i++) {
|
||||||
if (parts[i].n) memcpy(buf + at, parts[i].p, (size_t)parts[i].n);
|
if (parts[i].n) memcpy(buf + at, parts[i].p, (size_t)parts[i].n);
|
||||||
@@ -80,18 +80,18 @@ static dstr dino_cat_n(int n, const dstr *parts) {
|
|||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline dstr dino_cat(dstr a, dstr b) {
|
static inline dstr rex_cat(dstr a, dstr b) {
|
||||||
dstr parts[2] = {a, b};
|
dstr parts[2] = {a, b};
|
||||||
return dino_cat_n(2, parts);
|
return rex_cat_n(2, parts);
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline bool dino_streq(dstr a, dstr b) {
|
static inline bool rex_streq(dstr a, dstr b) {
|
||||||
return a.n == b.n && (a.n == 0 || memcmp(a.p, b.p, (size_t)a.n) == 0);
|
return a.n == b.n && (a.n == 0 || memcmp(a.p, b.p, (size_t)a.n) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decode the UTF-8 character at `p` (at most `n` bytes left); stores it in `*out` and returns its width in bytes.
|
/// Decode the UTF-8 character at `p` (at most `n` bytes left); stores it in `*out` and returns its width in bytes.
|
||||||
/// Bytes that aren't valid UTF-8 come out one at a time as U+FFFD.
|
/// Bytes that aren't valid UTF-8 come out one at a time as U+FFFD.
|
||||||
static int64_t dino_utf8_decode(const char *p, int64_t n, uint32_t *out) {
|
static int64_t rex_utf8_decode(const char *p, int64_t n, uint32_t *out) {
|
||||||
const unsigned char *s = (const unsigned char *)p;
|
const unsigned char *s = (const unsigned char *)p;
|
||||||
if (s[0] < 0x80) { *out = s[0]; return 1; }
|
if (s[0] < 0x80) { *out = s[0]; return 1; }
|
||||||
int64_t w = s[0] >= 0xF0 ? 4 : s[0] >= 0xE0 ? 3 : s[0] >= 0xC0 ? 2 : 0;
|
int64_t w = s[0] >= 0xF0 ? 4 : s[0] >= 0xE0 ? 3 : s[0] >= 0xC0 ? 2 : 0;
|
||||||
@@ -106,61 +106,61 @@ static int64_t dino_utf8_decode(const char *p, int64_t n, uint32_t *out) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `s[i]`: the character that starts at byte `i`.
|
/// `s[i]`: the character that starts at byte `i`.
|
||||||
static uint32_t dino_str_char_at(dstr s, int64_t i) {
|
static uint32_t rex_str_char_at(dstr s, int64_t i) {
|
||||||
if (i < 0 || i >= s.n) dino_index_panic(i, s.n);
|
if (i < 0 || i >= s.n) rex_index_panic(i, s.n);
|
||||||
if (((unsigned char)s.p[i] & 0xC0) == 0x80) dino_panic("that position is in the middle of a character");
|
if (((unsigned char)s.p[i] & 0xC0) == 0x80) rex_panic("that position is in the middle of a character");
|
||||||
uint32_t c;
|
uint32_t c;
|
||||||
dino_utf8_decode(s.p + i, s.n - i, &c);
|
rex_utf8_decode(s.p + i, s.n - i, &c);
|
||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_new_str(const char *src, int64_t n);
|
static dstr rex_new_str(const char *src, int64_t n);
|
||||||
|
|
||||||
static dstr dino_char_str(uint32_t c) {
|
static dstr rex_char_str(uint32_t c) {
|
||||||
char b[4];
|
char b[4];
|
||||||
int n;
|
int n;
|
||||||
if (c < 0x80) { b[0] = (char)c; n = 1; }
|
if (c < 0x80) { b[0] = (char)c; n = 1; }
|
||||||
else if (c < 0x800) { b[0] = (char)(0xC0 | (c >> 6)); b[1] = (char)(0x80 | (c & 0x3F)); n = 2; }
|
else if (c < 0x800) { b[0] = (char)(0xC0 | (c >> 6)); b[1] = (char)(0x80 | (c & 0x3F)); n = 2; }
|
||||||
else if (c < 0x10000) { b[0] = (char)(0xE0 | (c >> 12)); b[1] = (char)(0x80 | ((c >> 6) & 0x3F)); b[2] = (char)(0x80 | (c & 0x3F)); n = 3; }
|
else if (c < 0x10000) { b[0] = (char)(0xE0 | (c >> 12)); b[1] = (char)(0x80 | ((c >> 6) & 0x3F)); b[2] = (char)(0x80 | (c & 0x3F)); n = 3; }
|
||||||
else { b[0] = (char)(0xF0 | (c >> 18)); b[1] = (char)(0x80 | ((c >> 12) & 0x3F)); b[2] = (char)(0x80 | ((c >> 6) & 0x3F)); b[3] = (char)(0x80 | (c & 0x3F)); n = 4; }
|
else { b[0] = (char)(0xF0 | (c >> 18)); b[1] = (char)(0x80 | ((c >> 12) & 0x3F)); b[2] = (char)(0x80 | ((c >> 6) & 0x3F)); b[3] = (char)(0x80 | (c & 0x3F)); n = 4; }
|
||||||
return dino_new_str(b, n);
|
return rex_new_str(b, n);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void dino_print_char(uint32_t c) {
|
static void rex_print_char(uint32_t c) {
|
||||||
dstr s = dino_char_str(c);
|
dstr s = rex_char_str(c);
|
||||||
fwrite(s.p, 1, (size_t)s.n, stdout);
|
fwrite(s.p, 1, (size_t)s.n, stdout);
|
||||||
if (s.rc && --*s.rc == 0) free(s.rc);
|
if (s.rc && --*s.rc == 0) free(s.rc);
|
||||||
}
|
}
|
||||||
|
|
||||||
static bool dino_char_is_digit(uint32_t c) { return c >= '0' && c <= '9'; }
|
static bool rex_char_is_digit(uint32_t c) { return c >= '0' && c <= '9'; }
|
||||||
static bool dino_char_is_upper(uint32_t c) { return (c >= 'A' && c <= 'Z') || (c >= 0xC0 && c <= 0xDE && c != 0xD7); }
|
static bool rex_char_is_upper(uint32_t c) { return (c >= 'A' && c <= 'Z') || (c >= 0xC0 && c <= 0xDE && c != 0xD7); }
|
||||||
static bool dino_char_is_lower(uint32_t c) { return (c >= 'a' && c <= 'z') || (c >= 0xDF && c <= 0xFF && c != 0xF7); }
|
static bool rex_char_is_lower(uint32_t c) { return (c >= 'a' && c <= 'z') || (c >= 0xDF && c <= 0xFF && c != 0xF7); }
|
||||||
static bool dino_char_is_letter(uint32_t c) { return dino_char_is_upper(c) || dino_char_is_lower(c) || c > 0xFF; }
|
static bool rex_char_is_letter(uint32_t c) { return rex_char_is_upper(c) || rex_char_is_lower(c) || c > 0xFF; }
|
||||||
static bool dino_char_is_alnum(uint32_t c) { return dino_char_is_digit(c) || dino_char_is_letter(c); }
|
static bool rex_char_is_alnum(uint32_t c) { return rex_char_is_digit(c) || rex_char_is_letter(c); }
|
||||||
static bool dino_char_is_space(uint32_t c) { return c == ' ' || (c >= '\t' && c <= '\r'); }
|
static bool rex_char_is_space(uint32_t c) { return c == ' ' || (c >= '\t' && c <= '\r'); }
|
||||||
static uint32_t dino_char_upper(uint32_t c) { return (c >= 'a' && c <= 'z') ? c - 32 : c; }
|
static uint32_t rex_char_upper(uint32_t c) { return (c >= 'a' && c <= 'z') ? c - 32 : c; }
|
||||||
static uint32_t dino_char_lower(uint32_t c) { return (c >= 'A' && c <= 'Z') ? c + 32 : c; }
|
static uint32_t rex_char_lower(uint32_t c) { return (c >= 'A' && c <= 'Z') ? c + 32 : c; }
|
||||||
|
|
||||||
static inline uint64_t dino_hash_i64(int64_t v) {
|
static inline uint64_t rex_hash_i64(int64_t v) {
|
||||||
uint64_t x = (uint64_t)v;
|
uint64_t x = (uint64_t)v;
|
||||||
x ^= x >> 33; x *= 0xff51afd7ed558ccdULL; x ^= x >> 33; x *= 0xc4ceb9fe1a85ec53ULL; x ^= x >> 33;
|
x ^= x >> 33; x *= 0xff51afd7ed558ccdULL; x ^= x >> 33; x *= 0xc4ceb9fe1a85ec53ULL; x ^= x >> 33;
|
||||||
return x;
|
return x;
|
||||||
}
|
}
|
||||||
|
|
||||||
static uint64_t dino_hash_str(dstr s) {
|
static uint64_t rex_hash_str(dstr s) {
|
||||||
uint64_t h = 1469598103934665603ULL;
|
uint64_t h = 1469598103934665603ULL;
|
||||||
for (int64_t i = 0; i < s.n; i++) { h ^= (unsigned char)s.p[i]; h *= 1099511628211ULL; }
|
for (int64_t i = 0; i < s.n; i++) { h ^= (unsigned char)s.p[i]; h *= 1099511628211ULL; }
|
||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
|
|
||||||
static int dino_strcmp(dstr a, dstr b) {
|
static int rex_strcmp(dstr a, dstr b) {
|
||||||
int64_t m = a.n < b.n ? a.n : b.n;
|
int64_t m = a.n < b.n ? a.n : b.n;
|
||||||
int c = m ? memcmp(a.p, b.p, (size_t)m) : 0;
|
int c = m ? memcmp(a.p, b.p, (size_t)m) : 0;
|
||||||
if (c) return c;
|
if (c) return c;
|
||||||
return a.n < b.n ? -1 : (a.n > b.n ? 1 : 0);
|
return a.n < b.n ? -1 : (a.n > b.n ? 1 : 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
static int dino_fmt_f64(char *buf, size_t cap, double v) {
|
static int rex_fmt_f64(char *buf, size_t cap, double v) {
|
||||||
int n = snprintf(buf, cap, "%.15g", v);
|
int n = snprintf(buf, cap, "%.15g", v);
|
||||||
if (!strpbrk(buf, ".eEn")) { /* looks like an integer: show it as a float */
|
if (!strpbrk(buf, ".eEn")) { /* looks like an integer: show it as a float */
|
||||||
buf[n++] = '.';
|
buf[n++] = '.';
|
||||||
@@ -170,61 +170,61 @@ static int dino_fmt_f64(char *buf, size_t cap, double v) {
|
|||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_heap_str(const char *tmp, int n) {
|
static dstr rex_heap_str(const char *tmp, int n) {
|
||||||
int64_t *rc;
|
int64_t *rc;
|
||||||
char *buf = dino_str_alloc(n, &rc);
|
char *buf = rex_str_alloc(n, &rc);
|
||||||
memcpy(buf, tmp, (size_t)n + 1);
|
memcpy(buf, tmp, (size_t)n + 1);
|
||||||
dstr r = {buf, n, rc};
|
dstr r = {buf, n, rc};
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_i64_str(int64_t v) {
|
static dstr rex_i64_str(int64_t v) {
|
||||||
char tmp[32];
|
char tmp[32];
|
||||||
int n = snprintf(tmp, sizeof tmp, "%lld", (long long)v);
|
int n = snprintf(tmp, sizeof tmp, "%lld", (long long)v);
|
||||||
return dino_heap_str(tmp, n);
|
return rex_heap_str(tmp, n);
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_f64_str(double v) {
|
static dstr rex_f64_str(double v) {
|
||||||
char tmp[64];
|
char tmp[64];
|
||||||
int n = dino_fmt_f64(tmp, sizeof tmp, v);
|
int n = rex_fmt_f64(tmp, sizeof tmp, v);
|
||||||
return dino_heap_str(tmp, n);
|
return rex_heap_str(tmp, n);
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline dstr dino_bool_str(bool v) { return v ? dino_lit("true", 4) : dino_lit("false", 5); }
|
static inline dstr rex_bool_str(bool v) { return v ? rex_lit("true", 4) : rex_lit("false", 5); }
|
||||||
|
|
||||||
static inline void dino_print_str(dstr s) { if (s.n) fwrite(s.p, 1, (size_t)s.n, stdout); }
|
static inline void rex_print_str(dstr s) { if (s.n) fwrite(s.p, 1, (size_t)s.n, stdout); }
|
||||||
static inline void dino_print_i64(int64_t v) { printf("%lld", (long long)v); }
|
static inline void rex_print_i64(int64_t v) { printf("%lld", (long long)v); }
|
||||||
static inline void dino_print_f64(double v) { char tmp[64]; dino_fmt_f64(tmp, sizeof tmp, v); fputs(tmp, stdout); }
|
static inline void rex_print_f64(double v) { char tmp[64]; rex_fmt_f64(tmp, sizeof tmp, v); fputs(tmp, stdout); }
|
||||||
static inline void dino_print_bool(bool v) { fputs(v ? "true" : "false", stdout); }
|
static inline void rex_print_bool(bool v) { fputs(v ? "true" : "false", stdout); }
|
||||||
static inline void dino_print_sp(void) { putchar(' '); }
|
static inline void rex_print_sp(void) { putchar(' '); }
|
||||||
static inline void dino_print_nl(void) { putchar('\n'); }
|
static inline void rex_print_nl(void) { putchar('\n'); }
|
||||||
|
|
||||||
/* ---- sized numbers ---- */
|
/* ---- sized numbers ---- */
|
||||||
static inline int64_t dino_f2i_clamp(double x, int64_t lo, int64_t hi) {
|
static inline int64_t rex_f2i_clamp(double x, int64_t lo, int64_t hi) {
|
||||||
if (x != x) return 0;
|
if (x != x) return 0;
|
||||||
if (x <= (double)lo) return lo;
|
if (x <= (double)lo) return lo;
|
||||||
if (x >= (double)hi) return hi;
|
if (x >= (double)hi) return hi;
|
||||||
return (int64_t)x;
|
return (int64_t)x;
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline uint64_t dino_f2u64(double x) {
|
static inline uint64_t rex_f2u64(double x) {
|
||||||
if (x != x || x <= 0) return 0;
|
if (x != x || x <= 0) return 0;
|
||||||
if (x >= 18446744073709551615.0) return UINT64_MAX;
|
if (x >= 18446744073709551615.0) return UINT64_MAX;
|
||||||
return (uint64_t)x;
|
return (uint64_t)x;
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline uint64_t dino_udiv(uint64_t a, uint64_t b) {
|
static inline uint64_t rex_udiv(uint64_t a, uint64_t b) {
|
||||||
if (b == 0) dino_panic("integer division by zero");
|
if (b == 0) rex_panic("integer division by zero");
|
||||||
return a / b;
|
return a / b;
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline uint64_t dino_urem(uint64_t a, uint64_t b) {
|
static inline uint64_t rex_urem(uint64_t a, uint64_t b) {
|
||||||
if (b == 0) dino_panic("integer remainder by zero");
|
if (b == 0) rex_panic("integer remainder by zero");
|
||||||
return a % b;
|
return a % b;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* the shortest text that reads back as the same f32 */
|
/* the shortest text that reads back as the same f32 */
|
||||||
static int dino_fmt_f32(char *buf, size_t cap, float v) {
|
static int rex_fmt_f32(char *buf, size_t cap, float v) {
|
||||||
int n = 0;
|
int n = 0;
|
||||||
for (int p = 1; p <= 9; p++) {
|
for (int p = 1; p <= 9; p++) {
|
||||||
n = snprintf(buf, cap, "%.*g", p, (double)v);
|
n = snprintf(buf, cap, "%.*g", p, (double)v);
|
||||||
@@ -238,28 +238,28 @@ static int dino_fmt_f32(char *buf, size_t cap, float v) {
|
|||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_f32_str(float v) {
|
static dstr rex_f32_str(float v) {
|
||||||
char tmp[64];
|
char tmp[64];
|
||||||
int n = dino_fmt_f32(tmp, sizeof tmp, v);
|
int n = rex_fmt_f32(tmp, sizeof tmp, v);
|
||||||
return dino_heap_str(tmp, n);
|
return rex_heap_str(tmp, n);
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_u64_str(uint64_t v) {
|
static dstr rex_u64_str(uint64_t v) {
|
||||||
char tmp[32];
|
char tmp[32];
|
||||||
int n = snprintf(tmp, sizeof tmp, "%llu", (unsigned long long)v);
|
int n = snprintf(tmp, sizeof tmp, "%llu", (unsigned long long)v);
|
||||||
return dino_heap_str(tmp, n);
|
return rex_heap_str(tmp, n);
|
||||||
}
|
}
|
||||||
|
|
||||||
static inline void dino_print_u64(uint64_t v) { printf("%llu", (unsigned long long)v); }
|
static inline void rex_print_u64(uint64_t v) { printf("%llu", (unsigned long long)v); }
|
||||||
static inline void dino_print_f32(float v) { char tmp[64]; dino_fmt_f32(tmp, sizeof tmp, v); fputs(tmp, stdout); }
|
static inline void rex_print_f32(float v) { char tmp[64]; rex_fmt_f32(tmp, sizeof tmp, v); fputs(tmp, stdout); }
|
||||||
|
|
||||||
/* ---- end of runtime ---- */
|
/* ---- end of runtime ---- */
|
||||||
|
|
||||||
/* error: nil (set == false) or a message */
|
/* error: nil (set == false) or a message */
|
||||||
typedef struct { bool set; dstr msg; } dino_err;
|
typedef struct { bool set; dstr msg; } rex_err;
|
||||||
static dstr dino_err_str(dino_err e) { return e.set ? dino_str_retain(e.msg) : dino_lit("nil", 3); }
|
static dstr rex_err_str(rex_err e) { return e.set ? rex_str_retain(e.msg) : rex_lit("nil", 3); }
|
||||||
static inline dino_err dino_err_retain(dino_err e) { dino_str_retain(e.msg); return e; }
|
static inline rex_err rex_err_retain(rex_err e) { rex_str_retain(e.msg); return e; }
|
||||||
static inline void dino_err_release(dino_err e) { dino_str_release(e.msg); }
|
static inline void rex_err_release(rex_err e) { rex_str_release(e.msg); }
|
||||||
|
|
||||||
/* ---- standard library ---- */
|
/* ---- standard library ---- */
|
||||||
|
|
||||||
@@ -267,9 +267,9 @@ static inline void dino_err_release(dino_err e) { dino_str_release(e.msg); }
|
|||||||
the generated code uses this same type for `[]string`. */
|
the generated code uses this same type for `[]string`. */
|
||||||
typedef struct L_str { dstr *p; int64_t len; int64_t cap; } L_str;
|
typedef struct L_str { dstr *p; int64_t len; int64_t cap; } L_str;
|
||||||
|
|
||||||
static dstr dino_new_str(const char *src, int64_t n) {
|
static dstr rex_new_str(const char *src, int64_t n) {
|
||||||
int64_t *rc;
|
int64_t *rc;
|
||||||
char *buf = dino_str_alloc(n, &rc);
|
char *buf = rex_str_alloc(n, &rc);
|
||||||
if (n) memcpy(buf, src, (size_t)n);
|
if (n) memcpy(buf, src, (size_t)n);
|
||||||
buf[n] = 0;
|
buf[n] = 0;
|
||||||
dstr r = {buf, n, rc};
|
dstr r = {buf, n, rc};
|
||||||
@@ -278,83 +278,83 @@ static dstr dino_new_str(const char *src, int64_t n) {
|
|||||||
|
|
||||||
/* `s[lo..hi]`: a copy of those bytes; out of range panics */
|
/* `s[lo..hi]`: a copy of those bytes; out of range panics */
|
||||||
static dstr dstr_slice(dstr s, int64_t lo, int64_t hi) {
|
static dstr dstr_slice(dstr s, int64_t lo, int64_t hi) {
|
||||||
if (lo < 0 || hi < lo || hi > s.n) dino_slice_panic(lo, hi, s.n);
|
if (lo < 0 || hi < lo || hi > s.n) rex_slice_panic(lo, hi, s.n);
|
||||||
return dino_new_str(s.p + lo, hi - lo);
|
return rex_new_str(s.p + lo, hi - lo);
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_fmt_msg(const char *fmt, dstr a, const char *extra) {
|
static dstr rex_fmt_msg(const char *fmt, dstr a, const char *extra) {
|
||||||
int n = snprintf(NULL, 0, fmt, (int)a.n, a.p, extra);
|
int n = snprintf(NULL, 0, fmt, (int)a.n, a.p, extra);
|
||||||
char *tmp = (char *)malloc((size_t)n + 1);
|
char *tmp = (char *)malloc((size_t)n + 1);
|
||||||
if (!tmp) dino_panic("out of memory");
|
if (!tmp) rex_panic("out of memory");
|
||||||
snprintf(tmp, (size_t)n + 1, fmt, (int)a.n, a.p, extra);
|
snprintf(tmp, (size_t)n + 1, fmt, (int)a.n, a.p, extra);
|
||||||
dstr r = dino_new_str(tmp, n);
|
dstr r = rex_new_str(tmp, n);
|
||||||
free(tmp);
|
free(tmp);
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dino_err dino_make_err(dstr msg) { dino_err e = {true, msg}; return e; }
|
static rex_err rex_make_err(dstr msg) { rex_err e = {true, msg}; return e; }
|
||||||
|
|
||||||
/* a NUL-terminated copy of a string (for file names and the C library) */
|
/* a NUL-terminated copy of a string (for file names and the C library) */
|
||||||
static char *dino_cstr(dstr s) {
|
static char *rex_cstr(dstr s) {
|
||||||
char *c = (char *)malloc((size_t)s.n + 1);
|
char *c = (char *)malloc((size_t)s.n + 1);
|
||||||
if (!c) dino_panic("out of memory");
|
if (!c) rex_panic("out of memory");
|
||||||
if (s.n) memcpy(c, s.p, (size_t)s.n);
|
if (s.n) memcpy(c, s.p, (size_t)s.n);
|
||||||
c[s.n] = 0;
|
c[s.n] = 0;
|
||||||
return c;
|
return c;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void dino_strs_push(L_str *l, dstr s) {
|
static void rex_strs_push(L_str *l, dstr s) {
|
||||||
if (l->len == l->cap) {
|
if (l->len == l->cap) {
|
||||||
int64_t cap = l->cap ? l->cap * 2 : 4;
|
int64_t cap = l->cap ? l->cap * 2 : 4;
|
||||||
dstr *p = (dstr *)realloc(l->p, (size_t)cap * sizeof(dstr));
|
dstr *p = (dstr *)realloc(l->p, (size_t)cap * sizeof(dstr));
|
||||||
if (!p) dino_panic("out of memory");
|
if (!p) rex_panic("out of memory");
|
||||||
l->p = p;
|
l->p = p;
|
||||||
l->cap = cap;
|
l->cap = cap;
|
||||||
}
|
}
|
||||||
l->p[l->len++] = s;
|
l->p[l->len++] = s;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_str_upper(dstr s) {
|
static dstr rex_str_upper(dstr s) {
|
||||||
dstr r = dino_new_str(s.p, s.n);
|
dstr r = rex_new_str(s.p, s.n);
|
||||||
for (int64_t i = 0; i < r.n; i++) if (r.p[i] >= 'a' && r.p[i] <= 'z') ((char *)r.p)[i] -= 32;
|
for (int64_t i = 0; i < r.n; i++) if (r.p[i] >= 'a' && r.p[i] <= 'z') ((char *)r.p)[i] -= 32;
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_str_lower(dstr s) {
|
static dstr rex_str_lower(dstr s) {
|
||||||
dstr r = dino_new_str(s.p, s.n);
|
dstr r = rex_new_str(s.p, s.n);
|
||||||
for (int64_t i = 0; i < r.n; i++) if (r.p[i] >= 'A' && r.p[i] <= 'Z') ((char *)r.p)[i] += 32;
|
for (int64_t i = 0; i < r.n; i++) if (r.p[i] >= 'A' && r.p[i] <= 'Z') ((char *)r.p)[i] += 32;
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
static bool dino_is_space(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f'; }
|
static bool rex_is_space(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f'; }
|
||||||
|
|
||||||
static dstr dino_str_trim(dstr s) {
|
static dstr rex_str_trim(dstr s) {
|
||||||
int64_t a = 0, b = s.n;
|
int64_t a = 0, b = s.n;
|
||||||
while (a < b && dino_is_space(s.p[a])) a++;
|
while (a < b && rex_is_space(s.p[a])) a++;
|
||||||
while (b > a && dino_is_space(s.p[b - 1])) b--;
|
while (b > a && rex_is_space(s.p[b - 1])) b--;
|
||||||
return dino_new_str(s.p + a, b - a);
|
return rex_new_str(s.p + a, b - a);
|
||||||
}
|
}
|
||||||
|
|
||||||
static int64_t dino_str_index_of(dstr s, dstr sub) {
|
static int64_t rex_str_index_of(dstr s, dstr sub) {
|
||||||
if (sub.n == 0) return 0;
|
if (sub.n == 0) return 0;
|
||||||
for (int64_t i = 0; i + sub.n <= s.n; i++)
|
for (int64_t i = 0; i + sub.n <= s.n; i++)
|
||||||
if (memcmp(s.p + i, sub.p, (size_t)sub.n) == 0) return i;
|
if (memcmp(s.p + i, sub.p, (size_t)sub.n) == 0) return i;
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
static bool dino_str_contains(dstr s, dstr sub) { return dino_str_index_of(s, sub) >= 0; }
|
static bool rex_str_contains(dstr s, dstr sub) { return rex_str_index_of(s, sub) >= 0; }
|
||||||
static bool dino_str_starts_with(dstr s, dstr p) { return p.n <= s.n && (p.n == 0 || memcmp(s.p, p.p, (size_t)p.n) == 0); }
|
static bool rex_str_starts_with(dstr s, dstr p) { return p.n <= s.n && (p.n == 0 || memcmp(s.p, p.p, (size_t)p.n) == 0); }
|
||||||
static bool dino_str_ends_with(dstr s, dstr p) { return p.n <= s.n && (p.n == 0 || memcmp(s.p + s.n - p.n, p.p, (size_t)p.n) == 0); }
|
static bool rex_str_ends_with(dstr s, dstr p) { return p.n <= s.n && (p.n == 0 || memcmp(s.p + s.n - p.n, p.p, (size_t)p.n) == 0); }
|
||||||
|
|
||||||
static dstr dino_str_replace(dstr s, dstr from, dstr to) {
|
static dstr rex_str_replace(dstr s, dstr from, dstr to) {
|
||||||
if (from.n == 0) return dino_new_str(s.p, s.n);
|
if (from.n == 0) return rex_new_str(s.p, s.n);
|
||||||
int64_t count = 0;
|
int64_t count = 0;
|
||||||
for (int64_t i = 0; i + from.n <= s.n;) {
|
for (int64_t i = 0; i + from.n <= s.n;) {
|
||||||
if (memcmp(s.p + i, from.p, (size_t)from.n) == 0) { count++; i += from.n; } else i++;
|
if (memcmp(s.p + i, from.p, (size_t)from.n) == 0) { count++; i += from.n; } else i++;
|
||||||
}
|
}
|
||||||
int64_t total = s.n + count * (to.n - from.n);
|
int64_t total = s.n + count * (to.n - from.n);
|
||||||
int64_t *rc;
|
int64_t *rc;
|
||||||
char *buf = dino_str_alloc(total, &rc);
|
char *buf = rex_str_alloc(total, &rc);
|
||||||
int64_t at = 0;
|
int64_t at = 0;
|
||||||
for (int64_t i = 0; i < s.n;) {
|
for (int64_t i = 0; i < s.n;) {
|
||||||
if (i + from.n <= s.n && memcmp(s.p + i, from.p, (size_t)from.n) == 0) {
|
if (i + from.n <= s.n && memcmp(s.p + i, from.p, (size_t)from.n) == 0) {
|
||||||
@@ -370,24 +370,24 @@ static dstr dino_str_replace(dstr s, dstr from, dstr to) {
|
|||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_str_repeat(dstr s, int64_t n) {
|
static dstr rex_str_repeat(dstr s, int64_t n) {
|
||||||
if (n < 0) n = 0;
|
if (n < 0) n = 0;
|
||||||
int64_t total = s.n * n;
|
int64_t total = s.n * n;
|
||||||
int64_t *rc;
|
int64_t *rc;
|
||||||
char *buf = dino_str_alloc(total, &rc);
|
char *buf = rex_str_alloc(total, &rc);
|
||||||
for (int64_t i = 0; i < n; i++) if (s.n) memcpy(buf + i * s.n, s.p, (size_t)s.n);
|
for (int64_t i = 0; i < n; i++) if (s.n) memcpy(buf + i * s.n, s.p, (size_t)s.n);
|
||||||
buf[total] = 0;
|
buf[total] = 0;
|
||||||
dstr r = {buf, total, rc};
|
dstr r = {buf, total, rc};
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
static L_str dino_str_split(dstr s, dstr sep) {
|
static L_str rex_str_split(dstr s, dstr sep) {
|
||||||
L_str out = {0};
|
L_str out = {0};
|
||||||
if (sep.n == 0) { /* one piece per character */
|
if (sep.n == 0) { /* one piece per character */
|
||||||
for (int64_t i = 0; i < s.n;) {
|
for (int64_t i = 0; i < s.n;) {
|
||||||
int64_t j = i + 1;
|
int64_t j = i + 1;
|
||||||
while (j < s.n && (s.p[j] & 0xC0) == 0x80) j++;
|
while (j < s.n && (s.p[j] & 0xC0) == 0x80) j++;
|
||||||
dino_strs_push(&out, dino_new_str(s.p + i, j - i));
|
rex_strs_push(&out, rex_new_str(s.p + i, j - i));
|
||||||
i = j;
|
i = j;
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
@@ -395,41 +395,41 @@ static L_str dino_str_split(dstr s, dstr sep) {
|
|||||||
int64_t start = 0;
|
int64_t start = 0;
|
||||||
for (int64_t i = 0; i + sep.n <= s.n;) {
|
for (int64_t i = 0; i + sep.n <= s.n;) {
|
||||||
if (memcmp(s.p + i, sep.p, (size_t)sep.n) == 0) {
|
if (memcmp(s.p + i, sep.p, (size_t)sep.n) == 0) {
|
||||||
dino_strs_push(&out, dino_new_str(s.p + start, i - start));
|
rex_strs_push(&out, rex_new_str(s.p + start, i - start));
|
||||||
i += sep.n;
|
i += sep.n;
|
||||||
start = i;
|
start = i;
|
||||||
} else i++;
|
} else i++;
|
||||||
}
|
}
|
||||||
dino_strs_push(&out, dino_new_str(s.p + start, s.n - start));
|
rex_strs_push(&out, rex_new_str(s.p + start, s.n - start));
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
static L_str dino_str_lines(dstr s) {
|
static L_str rex_str_lines(dstr s) {
|
||||||
L_str out = {0};
|
L_str out = {0};
|
||||||
int64_t start = 0;
|
int64_t start = 0;
|
||||||
for (int64_t i = 0; i < s.n; i++) {
|
for (int64_t i = 0; i < s.n; i++) {
|
||||||
if (s.p[i] == '\n') {
|
if (s.p[i] == '\n') {
|
||||||
int64_t end = i;
|
int64_t end = i;
|
||||||
if (end > start && s.p[end - 1] == '\r') end--;
|
if (end > start && s.p[end - 1] == '\r') end--;
|
||||||
dino_strs_push(&out, dino_new_str(s.p + start, end - start));
|
rex_strs_push(&out, rex_new_str(s.p + start, end - start));
|
||||||
start = i + 1;
|
start = i + 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (start < s.n) {
|
if (start < s.n) {
|
||||||
int64_t end = s.n;
|
int64_t end = s.n;
|
||||||
if (end > start && s.p[end - 1] == '\r') end--;
|
if (end > start && s.p[end - 1] == '\r') end--;
|
||||||
dino_strs_push(&out, dino_new_str(s.p + start, end - start));
|
rex_strs_push(&out, rex_new_str(s.p + start, end - start));
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void dino_str_chars(dstr s, void **p, int64_t *len, int64_t *cap) {
|
static void rex_str_chars(dstr s, void **p, int64_t *len, int64_t *cap) {
|
||||||
uint32_t *out = (uint32_t *)malloc((size_t)(s.n ? s.n : 1) * sizeof(uint32_t));
|
uint32_t *out = (uint32_t *)malloc((size_t)(s.n ? s.n : 1) * sizeof(uint32_t));
|
||||||
if (!out) dino_panic("out of memory");
|
if (!out) rex_panic("out of memory");
|
||||||
int64_t n = 0;
|
int64_t n = 0;
|
||||||
for (int64_t i = 0; i < s.n;) {
|
for (int64_t i = 0; i < s.n;) {
|
||||||
uint32_t c;
|
uint32_t c;
|
||||||
i += dino_utf8_decode(s.p + i, s.n - i, &c);
|
i += rex_utf8_decode(s.p + i, s.n - i, &c);
|
||||||
out[n++] = c;
|
out[n++] = c;
|
||||||
}
|
}
|
||||||
*p = out;
|
*p = out;
|
||||||
@@ -437,23 +437,23 @@ static void dino_str_chars(dstr s, void **p, int64_t *len, int64_t *cap) {
|
|||||||
*cap = s.n ? s.n : 1;
|
*cap = s.n ? s.n : 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
static L_str dino_str_fields(dstr s) {
|
static L_str rex_str_fields(dstr s) {
|
||||||
L_str out = {0};
|
L_str out = {0};
|
||||||
int64_t i = 0;
|
int64_t i = 0;
|
||||||
while (i < s.n) {
|
while (i < s.n) {
|
||||||
while (i < s.n && dino_is_space(s.p[i])) i++;
|
while (i < s.n && rex_is_space(s.p[i])) i++;
|
||||||
int64_t start = i;
|
int64_t start = i;
|
||||||
while (i < s.n && !dino_is_space(s.p[i])) i++;
|
while (i < s.n && !rex_is_space(s.p[i])) i++;
|
||||||
if (i > start) dino_strs_push(&out, dino_new_str(s.p + start, i - start));
|
if (i > start) rex_strs_push(&out, rex_new_str(s.p + start, i - start));
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_strs_join(L_str l, dstr sep) {
|
static dstr rex_strs_join(L_str l, dstr sep) {
|
||||||
int64_t total = 0;
|
int64_t total = 0;
|
||||||
for (int64_t i = 0; i < l.len; i++) total += l.p[i].n + (i ? sep.n : 0);
|
for (int64_t i = 0; i < l.len; i++) total += l.p[i].n + (i ? sep.n : 0);
|
||||||
int64_t *rc;
|
int64_t *rc;
|
||||||
char *buf = dino_str_alloc(total, &rc);
|
char *buf = rex_str_alloc(total, &rc);
|
||||||
int64_t at = 0;
|
int64_t at = 0;
|
||||||
for (int64_t i = 0; i < l.len; i++) {
|
for (int64_t i = 0; i < l.len; i++) {
|
||||||
if (i && sep.n) { memcpy(buf + at, sep.p, (size_t)sep.n); at += sep.n; }
|
if (i && sep.n) { memcpy(buf + at, sep.p, (size_t)sep.n); at += sep.n; }
|
||||||
@@ -464,118 +464,118 @@ static dstr dino_strs_join(L_str l, dstr sep) {
|
|||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dino_err dino_str_to_int(dstr s, int64_t *out) {
|
static rex_err rex_str_to_int(dstr s, int64_t *out) {
|
||||||
*out = 0;
|
*out = 0;
|
||||||
char *c = dino_cstr(s);
|
char *c = rex_cstr(s);
|
||||||
char *end = NULL;
|
char *end = NULL;
|
||||||
errno = 0;
|
errno = 0;
|
||||||
long long v = strtoll(c, &end, 10);
|
long long v = strtoll(c, &end, 10);
|
||||||
bool ok = s.n > 0 && *end == 0 && !dino_is_space(c[0]);
|
bool ok = s.n > 0 && *end == 0 && !rex_is_space(c[0]);
|
||||||
int e = errno;
|
int e = errno;
|
||||||
free(c);
|
free(c);
|
||||||
if (!ok) return dino_make_err(dino_fmt_msg("\"%.*s\" is not a whole number%s", s, ""));
|
if (!ok) return rex_make_err(rex_fmt_msg("\"%.*s\" is not a whole number%s", s, ""));
|
||||||
if (e == ERANGE) return dino_make_err(dino_fmt_msg("\"%.*s\" is too big for an int%s", s, ""));
|
if (e == ERANGE) return rex_make_err(rex_fmt_msg("\"%.*s\" is too big for an int%s", s, ""));
|
||||||
*out = (int64_t)v;
|
*out = (int64_t)v;
|
||||||
dino_err none = {0};
|
rex_err none = {0};
|
||||||
return none;
|
return none;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dino_err dino_str_to_float(dstr s, double *out) {
|
static rex_err rex_str_to_float(dstr s, double *out) {
|
||||||
*out = 0;
|
*out = 0;
|
||||||
char *c = dino_cstr(s);
|
char *c = rex_cstr(s);
|
||||||
char *end = NULL;
|
char *end = NULL;
|
||||||
double v = strtod(c, &end);
|
double v = strtod(c, &end);
|
||||||
bool ok = s.n > 0 && *end == 0 && !dino_is_space(c[0]);
|
bool ok = s.n > 0 && *end == 0 && !rex_is_space(c[0]);
|
||||||
free(c);
|
free(c);
|
||||||
if (!ok) return dino_make_err(dino_fmt_msg("\"%.*s\" is not a number%s", s, ""));
|
if (!ok) return rex_make_err(rex_fmt_msg("\"%.*s\" is not a number%s", s, ""));
|
||||||
*out = v;
|
*out = v;
|
||||||
dino_err none = {0};
|
rex_err none = {0};
|
||||||
return none;
|
return none;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dino_err dino_os_read_file(dstr path, dstr *out) {
|
static rex_err rex_os_read_file(dstr path, dstr *out) {
|
||||||
dstr empty = {0};
|
dstr empty = {0};
|
||||||
*out = empty;
|
*out = empty;
|
||||||
char *c = dino_cstr(path);
|
char *c = rex_cstr(path);
|
||||||
FILE *f = fopen(c, "rb");
|
FILE *f = fopen(c, "rb");
|
||||||
free(c);
|
free(c);
|
||||||
if (!f) return dino_make_err(dino_fmt_msg("cannot read \"%.*s\": %s", path, strerror(errno)));
|
if (!f) return rex_make_err(rex_fmt_msg("cannot read \"%.*s\": %s", path, strerror(errno)));
|
||||||
size_t cap = 4096, len = 0;
|
size_t cap = 4096, len = 0;
|
||||||
char *buf = (char *)malloc(cap);
|
char *buf = (char *)malloc(cap);
|
||||||
if (!buf) dino_panic("out of memory");
|
if (!buf) rex_panic("out of memory");
|
||||||
for (;;) {
|
for (;;) {
|
||||||
size_t got = fread(buf + len, 1, cap - len, f);
|
size_t got = fread(buf + len, 1, cap - len, f);
|
||||||
len += got;
|
len += got;
|
||||||
if (len < cap) break;
|
if (len < cap) break;
|
||||||
cap *= 2;
|
cap *= 2;
|
||||||
buf = (char *)realloc(buf, cap);
|
buf = (char *)realloc(buf, cap);
|
||||||
if (!buf) dino_panic("out of memory");
|
if (!buf) rex_panic("out of memory");
|
||||||
}
|
}
|
||||||
bool bad = ferror(f);
|
bool bad = ferror(f);
|
||||||
fclose(f);
|
fclose(f);
|
||||||
if (bad) {
|
if (bad) {
|
||||||
free(buf);
|
free(buf);
|
||||||
return dino_make_err(dino_fmt_msg("cannot read \"%.*s\": %s", path, "read error"));
|
return rex_make_err(rex_fmt_msg("cannot read \"%.*s\": %s", path, "read error"));
|
||||||
}
|
}
|
||||||
*out = dino_new_str(buf, (int64_t)len);
|
*out = rex_new_str(buf, (int64_t)len);
|
||||||
free(buf);
|
free(buf);
|
||||||
dino_err none = {0};
|
rex_err none = {0};
|
||||||
return none;
|
return none;
|
||||||
}
|
}
|
||||||
|
|
||||||
static dino_err dino_os_write(dstr path, dstr text, const char *mode) {
|
static rex_err rex_os_write(dstr path, dstr text, const char *mode) {
|
||||||
char *c = dino_cstr(path);
|
char *c = rex_cstr(path);
|
||||||
FILE *f = fopen(c, mode);
|
FILE *f = fopen(c, mode);
|
||||||
free(c);
|
free(c);
|
||||||
if (!f) return dino_make_err(dino_fmt_msg("cannot write \"%.*s\": %s", path, strerror(errno)));
|
if (!f) return rex_make_err(rex_fmt_msg("cannot write \"%.*s\": %s", path, strerror(errno)));
|
||||||
size_t put = text.n ? fwrite(text.p, 1, (size_t)text.n, f) : 0;
|
size_t put = text.n ? fwrite(text.p, 1, (size_t)text.n, f) : 0;
|
||||||
int closed = fclose(f);
|
int closed = fclose(f);
|
||||||
dino_err none = {0};
|
rex_err none = {0};
|
||||||
if (put != (size_t)text.n || closed != 0) return dino_make_err(dino_fmt_msg("cannot write \"%.*s\": %s", path, "write error"));
|
if (put != (size_t)text.n || closed != 0) return rex_make_err(rex_fmt_msg("cannot write \"%.*s\": %s", path, "write error"));
|
||||||
return none;
|
return none;
|
||||||
}
|
}
|
||||||
static dino_err dino_os_write_file(dstr path, dstr text) { return dino_os_write(path, text, "wb"); }
|
static rex_err rex_os_write_file(dstr path, dstr text) { return rex_os_write(path, text, "wb"); }
|
||||||
static dino_err dino_os_append_file(dstr path, dstr text) { return dino_os_write(path, text, "ab"); }
|
static rex_err rex_os_append_file(dstr path, dstr text) { return rex_os_write(path, text, "ab"); }
|
||||||
|
|
||||||
static bool dino_os_exists(dstr path) {
|
static bool rex_os_exists(dstr path) {
|
||||||
char *c = dino_cstr(path);
|
char *c = rex_cstr(path);
|
||||||
bool r = access(c, F_OK) == 0;
|
bool r = access(c, F_OK) == 0;
|
||||||
free(c);
|
free(c);
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
static int dino_argc;
|
static int rex_argc;
|
||||||
static char **dino_argv;
|
static char **rex_argv;
|
||||||
static void dino_set_args(int argc, char **argv) { dino_argc = argc; dino_argv = argv; }
|
static void rex_set_args(int argc, char **argv) { rex_argc = argc; rex_argv = argv; }
|
||||||
|
|
||||||
static L_str dino_os_args(void) {
|
static L_str rex_os_args(void) {
|
||||||
L_str out = {0};
|
L_str out = {0};
|
||||||
for (int i = 0; i < dino_argc; i++) dino_strs_push(&out, dino_new_str(dino_argv[i], (int64_t)strlen(dino_argv[i])));
|
for (int i = 0; i < rex_argc; i++) rex_strs_push(&out, rex_new_str(rex_argv[i], (int64_t)strlen(rex_argv[i])));
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void dino_os_exit(int64_t code) {
|
static void rex_os_exit(int64_t code) {
|
||||||
fflush(stdout);
|
fflush(stdout);
|
||||||
exit((int)code);
|
exit((int)code);
|
||||||
}
|
}
|
||||||
|
|
||||||
static bool dino_os_env(dstr name, dstr *out) {
|
static bool rex_os_env(dstr name, dstr *out) {
|
||||||
dstr empty = {0};
|
dstr empty = {0};
|
||||||
*out = empty;
|
*out = empty;
|
||||||
char *c = dino_cstr(name);
|
char *c = rex_cstr(name);
|
||||||
const char *v = getenv(c);
|
const char *v = getenv(c);
|
||||||
free(c);
|
free(c);
|
||||||
if (!v) return false;
|
if (!v) return false;
|
||||||
*out = dino_new_str(v, (int64_t)strlen(v));
|
*out = rex_new_str(v, (int64_t)strlen(v));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
static bool dino_os_read_line(dstr *out) {
|
static bool rex_os_read_line(dstr *out) {
|
||||||
dstr empty = {0};
|
dstr empty = {0};
|
||||||
*out = empty;
|
*out = empty;
|
||||||
size_t cap = 128, len = 0;
|
size_t cap = 128, len = 0;
|
||||||
char *buf = (char *)malloc(cap);
|
char *buf = (char *)malloc(cap);
|
||||||
if (!buf) dino_panic("out of memory");
|
if (!buf) rex_panic("out of memory");
|
||||||
int ch;
|
int ch;
|
||||||
bool any = false;
|
bool any = false;
|
||||||
while ((ch = getchar()) != EOF) {
|
while ((ch = getchar()) != EOF) {
|
||||||
@@ -584,23 +584,23 @@ static bool dino_os_read_line(dstr *out) {
|
|||||||
if (len + 1 >= cap) {
|
if (len + 1 >= cap) {
|
||||||
cap *= 2;
|
cap *= 2;
|
||||||
buf = (char *)realloc(buf, cap);
|
buf = (char *)realloc(buf, cap);
|
||||||
if (!buf) dino_panic("out of memory");
|
if (!buf) rex_panic("out of memory");
|
||||||
}
|
}
|
||||||
buf[len++] = (char)ch;
|
buf[len++] = (char)ch;
|
||||||
}
|
}
|
||||||
if (len > 0 && buf[len - 1] == '\r') len--;
|
if (len > 0 && buf[len - 1] == '\r') len--;
|
||||||
if (any) *out = dino_new_str(buf, (int64_t)len);
|
if (any) *out = rex_new_str(buf, (int64_t)len);
|
||||||
free(buf);
|
free(buf);
|
||||||
return any;
|
return any;
|
||||||
}
|
}
|
||||||
|
|
||||||
static double dino_time_now(void) {
|
static double rex_time_now(void) {
|
||||||
struct timespec ts;
|
struct timespec ts;
|
||||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||||
return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
|
return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void dino_time_sleep(double secs) {
|
static void rex_time_sleep(double secs) {
|
||||||
if (secs <= 0) return;
|
if (secs <= 0) return;
|
||||||
fflush(stdout);
|
fflush(stdout);
|
||||||
struct timespec ts;
|
struct timespec ts;
|
||||||
@@ -611,13 +611,13 @@ static void dino_time_sleep(double secs) {
|
|||||||
|
|
||||||
/* ---- C libraries ---- */
|
/* ---- C libraries ---- */
|
||||||
|
|
||||||
static dstr dino_from_cstr(const char *p) {
|
static dstr rex_from_cstr(const char *p) {
|
||||||
return p ? dino_new_str(p, (int64_t)strlen(p)) : dino_lit("", 0);
|
return p ? rex_new_str(p, (int64_t)strlen(p)) : rex_lit("", 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
static dstr dino_ptr_str(const void *p) {
|
static dstr rex_ptr_str(const void *p) {
|
||||||
if (!p) return dino_lit("nil", 3);
|
if (!p) return rex_lit("nil", 3);
|
||||||
char b[32];
|
char b[32];
|
||||||
int n = snprintf(b, sizeof b, "%p", p);
|
int n = snprintf(b, sizeof b, "%p", p);
|
||||||
return dino_new_str(b, n);
|
return rex_new_str(b, n);
|
||||||
}
|
}
|
||||||
+34
-34
@@ -36,13 +36,13 @@ fn with_err(t: Ty) -> Ty {
|
|||||||
pub fn module_fn(module: &str, name: &str) -> Option<BuiltinFn> {
|
pub fn module_fn(module: &str, name: &str) -> Option<BuiltinFn> {
|
||||||
use Ty::*;
|
use Ty::*;
|
||||||
match (module, name) {
|
match (module, name) {
|
||||||
("os", "read_file") => f("dino_os_read_file", vec![Str], with_err(Str), BuiltinShape::ErrOut),
|
("os", "read_file") => f("rex_os_read_file", vec![Str], with_err(Str), BuiltinShape::ErrOut),
|
||||||
("os", "write_file") => plain("dino_os_write_file", vec![Str, Str], Error),
|
("os", "write_file") => plain("rex_os_write_file", vec![Str, Str], Error),
|
||||||
("os", "append_file") => plain("dino_os_append_file", vec![Str, Str], Error),
|
("os", "append_file") => plain("rex_os_append_file", vec![Str, Str], Error),
|
||||||
("os", "exists") => plain("dino_os_exists", vec![Str], Bool),
|
("os", "exists") => plain("rex_os_exists", vec![Str], Bool),
|
||||||
("os", "exit") => plain("dino_os_exit", vec![Int], Unit),
|
("os", "exit") => plain("rex_os_exit", vec![Int], Unit),
|
||||||
("os", "env") => f("dino_os_env", vec![Str], Ty::opt(Str), BuiltinShape::OptOut),
|
("os", "env") => f("rex_os_env", vec![Str], Ty::opt(Str), BuiltinShape::OptOut),
|
||||||
("os", "read_line") => f("dino_os_read_line", vec![], Ty::opt(Str), BuiltinShape::OptOut),
|
("os", "read_line") => f("rex_os_read_line", vec![], Ty::opt(Str), BuiltinShape::OptOut),
|
||||||
|
|
||||||
("math", "sqrt") => plain("sqrt", vec![Float], Float),
|
("math", "sqrt") => plain("sqrt", vec![Float], Float),
|
||||||
("math", "sin") => plain("sin", vec![Float], Float),
|
("math", "sin") => plain("sin", vec![Float], Float),
|
||||||
@@ -66,8 +66,8 @@ pub fn module_fn(module: &str, name: &str) -> Option<BuiltinFn> {
|
|||||||
("math", "max") => f("", vec![], Unit, BuiltinShape::Max),
|
("math", "max") => f("", vec![], Unit, BuiltinShape::Max),
|
||||||
("math", "abs") => f("", vec![], Unit, BuiltinShape::Abs),
|
("math", "abs") => f("", vec![], Unit, BuiltinShape::Abs),
|
||||||
|
|
||||||
("time", "now") => plain("dino_time_now", vec![], Float),
|
("time", "now") => plain("rex_time_now", vec![], Float),
|
||||||
("time", "sleep") => plain("dino_time_sleep", vec![Float], Unit),
|
("time", "sleep") => plain("rex_time_sleep", vec![Float], Unit),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,7 +82,7 @@ pub fn module_value(module: &str, name: &str) -> Option<ModuleValue> {
|
|||||||
match (module, name) {
|
match (module, name) {
|
||||||
("math", "PI") => Some(ModuleValue::Float(std::f64::consts::PI)),
|
("math", "PI") => Some(ModuleValue::Float(std::f64::consts::PI)),
|
||||||
("math", "E") => Some(ModuleValue::Float(std::f64::consts::E)),
|
("math", "E") => Some(ModuleValue::Float(std::f64::consts::E)),
|
||||||
("os", "args") => plain("dino_os_args", vec![], strings()).map(ModuleValue::Call),
|
("os", "args") => plain("rex_os_args", vec![], strings()).map(ModuleValue::Call),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -104,21 +104,21 @@ pub fn module_names(module: &str) -> Vec<&'static str> {
|
|||||||
pub fn str_method(name: &str) -> Option<BuiltinFn> {
|
pub fn str_method(name: &str) -> Option<BuiltinFn> {
|
||||||
use Ty::*;
|
use Ty::*;
|
||||||
match name {
|
match name {
|
||||||
"upper" => plain("dino_str_upper", vec![Str], Str),
|
"upper" => plain("rex_str_upper", vec![Str], Str),
|
||||||
"lower" => plain("dino_str_lower", vec![Str], Str),
|
"lower" => plain("rex_str_lower", vec![Str], Str),
|
||||||
"trim" => plain("dino_str_trim", vec![Str], Str),
|
"trim" => plain("rex_str_trim", vec![Str], Str),
|
||||||
"contains" => plain("dino_str_contains", vec![Str, Str], Bool),
|
"contains" => plain("rex_str_contains", vec![Str, Str], Bool),
|
||||||
"starts_with" => plain("dino_str_starts_with", vec![Str, Str], Bool),
|
"starts_with" => plain("rex_str_starts_with", vec![Str, Str], Bool),
|
||||||
"ends_with" => plain("dino_str_ends_with", vec![Str, Str], Bool),
|
"ends_with" => plain("rex_str_ends_with", vec![Str, Str], Bool),
|
||||||
"index_of" => plain("dino_str_index_of", vec![Str, Str], Int),
|
"index_of" => plain("rex_str_index_of", vec![Str, Str], Int),
|
||||||
"replace" => plain("dino_str_replace", vec![Str, Str, Str], Str),
|
"replace" => plain("rex_str_replace", vec![Str, Str, Str], Str),
|
||||||
"repeat" => plain("dino_str_repeat", vec![Str, Int], Str),
|
"repeat" => plain("rex_str_repeat", vec![Str, Int], Str),
|
||||||
"split" => plain("dino_str_split", vec![Str, Str], strings()),
|
"split" => plain("rex_str_split", vec![Str, Str], strings()),
|
||||||
"lines" => plain("dino_str_lines", vec![Str], strings()),
|
"lines" => plain("rex_str_lines", vec![Str], strings()),
|
||||||
"fields" => plain("dino_str_fields", vec![Str], strings()),
|
"fields" => plain("rex_str_fields", vec![Str], strings()),
|
||||||
"chars" => f("dino_str_chars", vec![Str], Ty::list(Ty::Char), BuiltinShape::ListOut),
|
"chars" => f("rex_str_chars", vec![Str], Ty::list(Ty::Char), BuiltinShape::ListOut),
|
||||||
"to_int" => f("dino_str_to_int", vec![Str], with_err(Int), BuiltinShape::ErrOut),
|
"to_int" => f("rex_str_to_int", vec![Str], with_err(Int), BuiltinShape::ErrOut),
|
||||||
"to_float" => f("dino_str_to_float", vec![Str], with_err(Float), BuiltinShape::ErrOut),
|
"to_float" => f("rex_str_to_float", vec![Str], with_err(Float), BuiltinShape::ErrOut),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -130,14 +130,14 @@ pub const STR_METHODS: &str =
|
|||||||
pub fn char_method(name: &str) -> Option<BuiltinFn> {
|
pub fn char_method(name: &str) -> Option<BuiltinFn> {
|
||||||
use Ty::*;
|
use Ty::*;
|
||||||
match name {
|
match name {
|
||||||
"is_digit" => plain("dino_char_is_digit", vec![Char], Bool),
|
"is_digit" => plain("rex_char_is_digit", vec![Char], Bool),
|
||||||
"is_letter" => plain("dino_char_is_letter", vec![Char], Bool),
|
"is_letter" => plain("rex_char_is_letter", vec![Char], Bool),
|
||||||
"is_alnum" => plain("dino_char_is_alnum", vec![Char], Bool),
|
"is_alnum" => plain("rex_char_is_alnum", vec![Char], Bool),
|
||||||
"is_space" => plain("dino_char_is_space", vec![Char], Bool),
|
"is_space" => plain("rex_char_is_space", vec![Char], Bool),
|
||||||
"is_upper" => plain("dino_char_is_upper", vec![Char], Bool),
|
"is_upper" => plain("rex_char_is_upper", vec![Char], Bool),
|
||||||
"is_lower" => plain("dino_char_is_lower", vec![Char], Bool),
|
"is_lower" => plain("rex_char_is_lower", vec![Char], Bool),
|
||||||
"upper" => plain("dino_char_upper", vec![Char], Char),
|
"upper" => plain("rex_char_upper", vec![Char], Char),
|
||||||
"lower" => plain("dino_char_lower", vec![Char], Char),
|
"lower" => plain("rex_char_lower", vec![Char], Char),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -147,7 +147,7 @@ pub const CHAR_METHODS: &str = "is_digit, is_letter, is_alnum, is_space, is_uppe
|
|||||||
/// Methods of `[]string`, besides `len`, `push` and `pop`.
|
/// Methods of `[]string`, besides `len`, `push` and `pop`.
|
||||||
pub fn str_list_method(name: &str) -> Option<BuiltinFn> {
|
pub fn str_list_method(name: &str) -> Option<BuiltinFn> {
|
||||||
match name {
|
match name {
|
||||||
"join" => plain("dino_strs_join", vec![strings(), Ty::Str], Ty::Str),
|
"join" => plain("rex_strs_join", vec![strings(), Ty::Str], Ty::Str),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -85,7 +85,7 @@ pub enum Ty {
|
|||||||
Iface(&'static str),
|
Iface(&'static str),
|
||||||
/// A function value: `func(int, string): bool`.
|
/// A function value: `func(int, string): bool`.
|
||||||
Func(&'static FuncTy),
|
Func(&'static FuncTy),
|
||||||
/// A pointer from a C library that Dino only passes around: `SDL.SDL_Window`, `zlib.gzFile`.
|
/// A pointer from a C library that Rex only passes around: `SDL.SDL_Window`, `zlib.gzFile`.
|
||||||
/// `"pointer"` (C's `void *`) goes with every other pointer type.
|
/// `"pointer"` (C's `void *`) goes with every other pointer type.
|
||||||
CPtr(&'static str),
|
CPtr(&'static str),
|
||||||
/// The "type" of a call that returns nothing.
|
/// The "type" of a call that returns nothing.
|
||||||
|
|||||||
+22
-22
@@ -4,13 +4,13 @@
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
use dino::driver;
|
use rex::driver;
|
||||||
|
|
||||||
/// A fresh folder with the given files in it.
|
/// A fresh folder with the given files in it.
|
||||||
fn folder(files: &[(&str, &str)]) -> PathBuf {
|
fn folder(files: &[(&str, &str)]) -> PathBuf {
|
||||||
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||||
let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
let dir = std::env::temp_dir().join(format!("dino-clib-{}-{n}", std::process::id()));
|
let dir = std::env::temp_dir().join(format!("rex-clib-{}-{n}", std::process::id()));
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
for (name, text) in files {
|
for (name, text) in files {
|
||||||
@@ -19,10 +19,10 @@ fn folder(files: &[(&str, &str)]) -> PathBuf {
|
|||||||
dir
|
dir
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Compile `main.dino` in a folder with these files and run it; returns what it printed.
|
/// Compile `main.rex` in a folder with these files and run it; returns what it printed.
|
||||||
fn run(files: &[(&str, &str)]) -> String {
|
fn run(files: &[(&str, &str)]) -> String {
|
||||||
let dir = folder(files);
|
let dir = folder(files);
|
||||||
let c = driver::compile_file(dir.join("main.dino").to_str().unwrap()).unwrap_or_else(|e| panic!("{e}"));
|
let c = driver::compile_file(dir.join("main.rex").to_str().unwrap()).unwrap_or_else(|e| panic!("{e}"));
|
||||||
let exe = dir.join("prog");
|
let exe = dir.join("prog");
|
||||||
let sanitized = driver::build_exe_with(&c, &exe, &["-std=c11", "-fwrapv", "-w", "-fsanitize=address", "-g"]);
|
let sanitized = driver::build_exe_with(&c, &exe, &["-std=c11", "-fwrapv", "-w", "-fsanitize=address", "-g"]);
|
||||||
if let Err(e) = sanitized {
|
if let Err(e) = sanitized {
|
||||||
@@ -40,7 +40,7 @@ fn run(files: &[(&str, &str)]) -> String {
|
|||||||
/// The error message for a program that should not compile.
|
/// The error message for a program that should not compile.
|
||||||
fn error(files: &[(&str, &str)]) -> String {
|
fn error(files: &[(&str, &str)]) -> String {
|
||||||
let dir = folder(files);
|
let dir = folder(files);
|
||||||
let r = driver::compile_file(dir.join("main.dino").to_str().unwrap());
|
let r = driver::compile_file(dir.join("main.rex").to_str().unwrap());
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
match r {
|
match r {
|
||||||
Ok(_) => panic!("expected an error"),
|
Ok(_) => panic!("expected an error"),
|
||||||
@@ -55,7 +55,7 @@ fn have_pkg(name: &str) -> bool {
|
|||||||
#[test]
|
#[test]
|
||||||
fn the_c_library() {
|
fn the_c_library() {
|
||||||
let out = run(&[(
|
let out = run(&[(
|
||||||
"main.dino",
|
"main.rex",
|
||||||
"import \"math.h\" { cbrt, hypot }\nimport \"string.h\"\nimport \"stdlib.h\"\n\n\
|
"import \"math.h\" { cbrt, hypot }\nimport \"string.h\"\nimport \"stdlib.h\"\n\n\
|
||||||
func main() {\n print(cbrt(27.0), hypot(3.0, 4.0))\n print(string.strlen(\"héllo\"), stdlib.abs(-4))\n print(stdlib.atoi(\"42abc\") + 1)\n}\n",
|
func main() {\n print(cbrt(27.0), hypot(3.0, 4.0))\n print(string.strlen(\"héllo\"), stdlib.abs(-4))\n print(stdlib.atoi(\"42abc\") + 1)\n}\n",
|
||||||
)]);
|
)]);
|
||||||
@@ -149,7 +149,7 @@ shapes.Box{size: shapes.Size{w: 2.0, h: 3.0}, id: 5} 7\n0 10 11\n10\n[97, 98, 99
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn your_own_c_file() {
|
fn your_own_c_file() {
|
||||||
let out = run(&[("shapes.h", SHAPES_H), ("shapes.c", SHAPES_C), ("main.dino", SHAPES_MAIN)]);
|
let out = run(&[("shapes.h", SHAPES_H), ("shapes.c", SHAPES_C), ("main.rex", SHAPES_MAIN)]);
|
||||||
assert_eq!(out, SHAPES_OUT);
|
assert_eq!(out, SHAPES_OUT);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,7 +178,7 @@ const char *counter_name(const Counter *c) { return c->name.c_str(); }
|
|||||||
void counter_free(Counter *c) { delete c; }
|
void counter_free(Counter *c) { delete c; }
|
||||||
}
|
}
|
||||||
"#;
|
"#;
|
||||||
let out = run(&[("shapes.h", SHAPES_H), ("shapes.cpp", cpp), ("main.dino", SHAPES_MAIN)]);
|
let out = run(&[("shapes.h", SHAPES_H), ("shapes.cpp", cpp), ("main.rex", SHAPES_MAIN)]);
|
||||||
assert_eq!(out, SHAPES_OUT);
|
assert_eq!(out, SHAPES_OUT);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -188,7 +188,7 @@ fn picked_names_are_used_bare() {
|
|||||||
("shapes.h", SHAPES_H),
|
("shapes.h", SHAPES_H),
|
||||||
("shapes.c", SHAPES_C),
|
("shapes.c", SHAPES_C),
|
||||||
(
|
(
|
||||||
"main.dino",
|
"main.rex",
|
||||||
"import \"shapes.h\" { Size, area, MAX_SIDES }\n\nfunc main() {\n var s: Size = Size{1.5, 2.0}\n print(area(s), MAX_SIDES)\n}\n",
|
"import \"shapes.h\" { Size, area, MAX_SIDES }\n\nfunc main() {\n var s: Size = Size{1.5, 2.0}\n print(area(s), MAX_SIDES)\n}\n",
|
||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
@@ -201,7 +201,7 @@ fn zlib_through_pkg_config() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let out = run(&[(
|
let out = run(&[(
|
||||||
"main.dino",
|
"main.rex",
|
||||||
r#"import "zlib.h"
|
r#"import "zlib.h"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -235,7 +235,7 @@ fn sqlite_fills_in_pointer_variables() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let out = run(&[(
|
let out = run(&[(
|
||||||
"main.dino",
|
"main.rex",
|
||||||
r#"import "sqlite3.h"
|
r#"import "sqlite3.h"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -260,7 +260,7 @@ fn raylib_structs_without_a_window() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let out = run(&[(
|
let out = run(&[(
|
||||||
"main.dino",
|
"main.rex",
|
||||||
"import \"raylib.h\"\n\nfunc main() {\n var c = raylib.Fade(raylib.RED, 0.5)\n print(c, raylib.ColorToInt(raylib.Color{0, 0, 0, 255}))\n var p = raylib.Vector2{1.0, 1.0}\n print(raylib.CheckCollisionPointRec(p, raylib.Rectangle{0.0, 0.0, 2.0, 2.0}))\n}\n",
|
"import \"raylib.h\"\n\nfunc main() {\n var c = raylib.Fade(raylib.RED, 0.5)\n print(c, raylib.ColorToInt(raylib.Color{0, 0, 0, 255}))\n var p = raylib.Vector2{1.0, 1.0}\n print(raylib.CheckCollisionPointRec(p, raylib.Rectangle{0.0, 0.0, 2.0, 2.0}))\n}\n",
|
||||||
)]);
|
)]);
|
||||||
assert_eq!(out, "raylib.Color{r: 230, g: 41, b: 55, a: 127} 255\ntrue\n");
|
assert_eq!(out, "raylib.Color{r: 230, g: 41, b: 55, a: 127} 255\ntrue\n");
|
||||||
@@ -268,32 +268,32 @@ fn raylib_structs_without_a_window() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn errors_name_the_problem() {
|
fn errors_name_the_problem() {
|
||||||
let e = error(&[("main.dino", "import \"no_such_header.h\"\n\nfunc main() {}\n")]);
|
let e = error(&[("main.rex", "import \"no_such_header.h\"\n\nfunc main() {}\n")]);
|
||||||
assert!(e.contains("cannot find the C header `no_such_header.h`"), "{e}");
|
assert!(e.contains("cannot find the C header `no_such_header.h`"), "{e}");
|
||||||
|
|
||||||
let e = error(&[("shapes.h", SHAPES_H), ("main.dino", "import \"shapes.h\" { aera }\n\nfunc main() {}\n")]);
|
let e = error(&[("shapes.h", SHAPES_H), ("main.rex", "import \"shapes.h\" { aera }\n\nfunc main() {}\n")]);
|
||||||
assert!(e.contains("`shapes.h` has no `aera` (did you mean `area`?)"), "{e}");
|
assert!(e.contains("`shapes.h` has no `aera` (did you mean `area`?)"), "{e}");
|
||||||
|
|
||||||
let e = error(&[("main.dino", "import \"stdio.h\"\n\nfunc main() {\n stdio.printf(\"hi\")\n}\n")]);
|
let e = error(&[("main.rex", "import \"stdio.h\"\n\nfunc main() {\n stdio.printf(\"hi\")\n}\n")]);
|
||||||
assert!(e.contains("`printf` can't be called from Dino: it takes a variable number of arguments"), "{e}");
|
assert!(e.contains("`printf` can't be called from Rex: it takes a variable number of arguments"), "{e}");
|
||||||
|
|
||||||
let e = error(&[("shapes.h", SHAPES_H), ("main.dino", "import \"shapes.h\"\n\nfunc main() {\n shapes.grow(shapes.Size{1.0, 1.0}, 2.0)\n}\n")]);
|
let e = error(&[("shapes.h", SHAPES_H), ("main.rex", "import \"shapes.h\"\n\nfunc main() {\n shapes.grow(shapes.Size{1.0, 1.0}, 2.0)\n}\n")]);
|
||||||
assert!(e.contains("`grow` writes into `s`, so it must be a variable"), "{e}");
|
assert!(e.contains("`grow` writes into `s`, so it must be a variable"), "{e}");
|
||||||
|
|
||||||
let e = error(&[("shapes.h", SHAPES_H), ("main.dino", "import \"shapes.h\"\n\nfunc main() {\n var n = 3\n print(shapes.make_box(n))\n}\n")]);
|
let e = error(&[("shapes.h", SHAPES_H), ("main.rex", "import \"shapes.h\"\n\nfunc main() {\n var n = 3\n print(shapes.make_box(n))\n}\n")]);
|
||||||
assert!(e.contains("expected `i32`, found `int` (convert it with `i32(...)`)"), "{e}");
|
assert!(e.contains("expected `i32`, found `int` (convert it with `i32(...)`)"), "{e}");
|
||||||
|
|
||||||
let e = error(&[("shapes.h", SHAPES_H), ("main.dino", "import \"shapes.h\"\n\nfunc main() {\n print(shapes.area())\n}\n")]);
|
let e = error(&[("shapes.h", SHAPES_H), ("main.rex", "import \"shapes.h\"\n\nfunc main() {\n print(shapes.area())\n}\n")]);
|
||||||
assert!(e.contains("`area` takes 1 argument (s: shapes.Size), but 0 were given"), "{e}");
|
assert!(e.contains("`area` takes 1 argument (s: shapes.Size), but 0 were given"), "{e}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_missing_library_says_how_to_link() {
|
fn a_missing_library_says_how_to_link() {
|
||||||
let dir = folder(&[(
|
let dir = folder(&[(
|
||||||
"main.dino",
|
"main.rex",
|
||||||
"import \"math.h\" link \"dino_no_such_lib\"\n\nfunc main() {\n print(math.sqrt(4.0))\n}\n",
|
"import \"math.h\" link \"rex_no_such_lib\"\n\nfunc main() {\n print(math.sqrt(4.0))\n}\n",
|
||||||
)]);
|
)]);
|
||||||
let c = driver::compile_file(dir.join("main.dino").to_str().unwrap()).unwrap();
|
let c = driver::compile_file(dir.join("main.rex").to_str().unwrap()).unwrap();
|
||||||
let e = driver::build_exe(&c, &dir.join("prog")).unwrap_err();
|
let e = driver::build_exe(&c, &dir.join("prog")).unwrap_err();
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
assert!(e.contains("linking with the C library failed") && e.contains("link \"name\""), "{e}");
|
assert!(e.contains("linking with the C library failed") && e.contains("link \"name\""), "{e}");
|
||||||
|
|||||||
+10
-10
@@ -1,9 +1,9 @@
|
|||||||
//! Tests of `dino fmt`.
|
//! Tests of `rex fmt`.
|
||||||
|
|
||||||
use dino::fmt::format;
|
use rex::fmt::format;
|
||||||
|
|
||||||
fn fmt(src: &str) -> String {
|
fn fmt(src: &str) -> String {
|
||||||
format(src).unwrap_or_else(|d| panic!("{}", d.render("test.dino", src)))
|
format(src).unwrap_or_else(|d| panic!("{}", d.render("test.rex", src)))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -59,12 +59,12 @@ fn broken_code_is_refused() {
|
|||||||
assert!(format("func main( {").is_err());
|
assert!(format("func main( {").is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dino_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
|
fn rex_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
|
||||||
for e in std::fs::read_dir(dir).unwrap() {
|
for e in std::fs::read_dir(dir).unwrap() {
|
||||||
let p = e.unwrap().path();
|
let p = e.unwrap().path();
|
||||||
if p.is_dir() {
|
if p.is_dir() {
|
||||||
dino_files(&p, out);
|
rex_files(&p, out);
|
||||||
} else if p.extension().map_or(false, |x| x == "dino") {
|
} else if p.extension().map_or(false, |x| x == "rex") {
|
||||||
out.push(p);
|
out.push(p);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,12 +73,12 @@ fn dino_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
|
|||||||
#[test]
|
#[test]
|
||||||
fn examples_are_formatted_and_formatting_is_stable() {
|
fn examples_are_formatted_and_formatting_is_stable() {
|
||||||
let mut files = Vec::new();
|
let mut files = Vec::new();
|
||||||
dino_files(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("examples"), &mut files);
|
rex_files(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("examples"), &mut files);
|
||||||
assert!(files.len() > 30);
|
assert!(files.len() > 30);
|
||||||
for f in files {
|
for f in files {
|
||||||
let src = std::fs::read_to_string(&f).unwrap();
|
let src = std::fs::read_to_string(&f).unwrap();
|
||||||
let once = fmt(&src);
|
let once = fmt(&src);
|
||||||
assert_eq!(once, src, "{} is not formatted (run `dino fmt examples`)", f.display());
|
assert_eq!(once, src, "{} is not formatted (run `rex fmt examples`)", f.display());
|
||||||
assert_eq!(fmt(&once), once, "formatting {} twice differs", f.display());
|
assert_eq!(fmt(&once), once, "formatting {} twice differs", f.display());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -91,8 +91,8 @@ fn doc_examples_are_stable() {
|
|||||||
let p = e.unwrap().path();
|
let p = e.unwrap().path();
|
||||||
let text = std::fs::read_to_string(&p).unwrap();
|
let text = std::fs::read_to_string(&p).unwrap();
|
||||||
let mut rest = text.as_str();
|
let mut rest = text.as_str();
|
||||||
while let Some(start) = rest.find("```dino\n") {
|
while let Some(start) = rest.find("```rex\n") {
|
||||||
let after = &rest[start + 8..];
|
let after = &rest[start + "```rex\n".len()..];
|
||||||
let end = after.find("```").unwrap();
|
let end = after.find("```").unwrap();
|
||||||
let code = &after[..end];
|
let code = &after[..end];
|
||||||
rest = &after[end + 3..];
|
rest = &after[end + 3..];
|
||||||
|
|||||||
+19
-19
@@ -1,7 +1,7 @@
|
|||||||
//! Tests of the language server: feed it editor messages, read what it answers.
|
//! Tests of the language server: feed it editor messages, read what it answers.
|
||||||
|
|
||||||
use dino::json::{self, Json};
|
use rex::json::{self, Json};
|
||||||
use dino::lsp;
|
use rex::lsp;
|
||||||
|
|
||||||
fn frame(v: &Json) -> Vec<u8> {
|
fn frame(v: &Json) -> Vec<u8> {
|
||||||
let body = v.to_string();
|
let body = v.to_string();
|
||||||
@@ -68,7 +68,7 @@ fn initialize_announces_features() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn errors_show_up_as_diagnostics() {
|
fn errors_show_up_as_diagnostics() {
|
||||||
let src = "func main() {\n var x: int = \"no\"\n}\n";
|
let src = "func main() {\n var x: int = \"no\"\n}\n";
|
||||||
let mut msgs = vec![open("file:///tmp/dino-lsp-test/a.dino", src)];
|
let mut msgs = vec![open("file:///tmp/rex-lsp-test/a.rex", src)];
|
||||||
msgs.extend(exit_messages());
|
msgs.extend(exit_messages());
|
||||||
let (out, _) = talk(msgs);
|
let (out, _) = talk(msgs);
|
||||||
let d = match out[0].path(&["params", "diagnostics"]) {
|
let d = match out[0].path(&["params", "diagnostics"]) {
|
||||||
@@ -83,7 +83,7 @@ fn errors_show_up_as_diagnostics() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn fixing_the_code_clears_the_diagnostics() {
|
fn fixing_the_code_clears_the_diagnostics() {
|
||||||
let uri = "file:///tmp/dino-lsp-test/b.dino";
|
let uri = "file:///tmp/rex-lsp-test/b.rex";
|
||||||
let change = notify(
|
let change = notify(
|
||||||
"textDocument/didChange",
|
"textDocument/didChange",
|
||||||
Json::obj(vec![
|
Json::obj(vec![
|
||||||
@@ -102,7 +102,7 @@ fn fixing_the_code_clears_the_diagnostics() {
|
|||||||
fn error_columns_count_utf16_units() {
|
fn error_columns_count_utf16_units() {
|
||||||
// the emoji takes two units in the editor's counting
|
// the emoji takes two units in the editor's counting
|
||||||
let src = "func main() {\n print(\"😀\", nope)\n}\n";
|
let src = "func main() {\n print(\"😀\", nope)\n}\n";
|
||||||
let mut msgs = vec![open("file:///tmp/dino-lsp-test/c.dino", src)];
|
let mut msgs = vec![open("file:///tmp/rex-lsp-test/c.rex", src)];
|
||||||
msgs.extend(exit_messages());
|
msgs.extend(exit_messages());
|
||||||
let (out, _) = talk(msgs);
|
let (out, _) = talk(msgs);
|
||||||
let d = match out[0].path(&["params", "diagnostics"]) {
|
let d = match out[0].path(&["params", "diagnostics"]) {
|
||||||
@@ -117,7 +117,7 @@ fn error_columns_count_utf16_units() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn formatting_returns_the_tidy_text() {
|
fn formatting_returns_the_tidy_text() {
|
||||||
let uri = "file:///tmp/dino-lsp-test/d.dino";
|
let uri = "file:///tmp/rex-lsp-test/d.rex";
|
||||||
let fmt_req = request(
|
let fmt_req = request(
|
||||||
2,
|
2,
|
||||||
"textDocument/formatting",
|
"textDocument/formatting",
|
||||||
@@ -136,10 +136,10 @@ fn formatting_returns_the_tidy_text() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn imports_are_read_next_to_the_file() {
|
fn imports_are_read_next_to_the_file() {
|
||||||
let dir = std::env::temp_dir().join(format!("dino-lsp-{}", std::process::id()));
|
let dir = std::env::temp_dir().join(format!("rex-lsp-{}", std::process::id()));
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
std::fs::write(dir.join("util.dino"), "pub func twice(x: int): int { return x * 2 }\n").unwrap();
|
std::fs::write(dir.join("util.rex"), "pub func twice(x: int): int { return x * 2 }\n").unwrap();
|
||||||
let uri = format!("file://{}/main.dino", dir.display());
|
let uri = format!("file://{}/main.rex", dir.display());
|
||||||
let src = "import util\nfunc main() {\n print(util.twice(2))\n}\n";
|
let src = "import util\nfunc main() {\n print(util.twice(2))\n}\n";
|
||||||
let mut msgs = vec![open(&uri, src)];
|
let mut msgs = vec![open(&uri, src)];
|
||||||
msgs.extend(exit_messages());
|
msgs.extend(exit_messages());
|
||||||
@@ -159,7 +159,7 @@ fn unknown_requests_get_an_error() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn editor_files_are_valid_json() {
|
fn editor_files_are_valid_json() {
|
||||||
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("editors/vscode");
|
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("editors/vscode");
|
||||||
for f in ["package.json", "language-configuration.json", "syntaxes/dino.tmLanguage.json"] {
|
for f in ["package.json", "language-configuration.json", "syntaxes/rex.tmLanguage.json"] {
|
||||||
let text = std::fs::read_to_string(dir.join(f)).unwrap();
|
let text = std::fs::read_to_string(dir.join(f)).unwrap();
|
||||||
json::parse(&text).unwrap_or_else(|e| panic!("{f}: {e}"));
|
json::parse(&text).unwrap_or_else(|e| panic!("{f}: {e}"));
|
||||||
}
|
}
|
||||||
@@ -177,7 +177,7 @@ fn at(uri: &str, line: i64, ch: i64) -> Json {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn ask(method: &str, params: Json) -> Json {
|
fn ask(method: &str, params: Json) -> Json {
|
||||||
let mut msgs = vec![request(1, "initialize", Json::obj(vec![])), open("file:///x/a.dino", SRC), request(2, method, params)];
|
let mut msgs = vec![request(1, "initialize", Json::obj(vec![])), open("file:///x/a.rex", SRC), request(2, method, params)];
|
||||||
msgs.extend(exit_messages());
|
msgs.extend(exit_messages());
|
||||||
let (out, _) = talk(msgs);
|
let (out, _) = talk(msgs);
|
||||||
out.into_iter().find(|m| m.get("id") == Some(&Json::Num(2.0))).unwrap().get("result").cloned().unwrap_or(Json::Null)
|
out.into_iter().find(|m| m.get("id") == Some(&Json::Num(2.0))).unwrap().get("result").cloned().unwrap_or(Json::Null)
|
||||||
@@ -185,40 +185,40 @@ fn ask(method: &str, params: Json) -> Json {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn outline_lists_top_level_names() {
|
fn outline_lists_top_level_names() {
|
||||||
let r = ask("textDocument/documentSymbol", Json::obj(vec![("textDocument", Json::obj(vec![("uri", Json::str("file:///x/a.dino"))]))]));
|
let r = ask("textDocument/documentSymbol", Json::obj(vec![("textDocument", Json::obj(vec![("uri", Json::str("file:///x/a.rex"))]))]));
|
||||||
let text = r.to_string();
|
let text = r.to_string();
|
||||||
assert!(text.contains("\"add\"") && text.contains("\"P\"") && text.contains("\"main\"") && text.contains("\"x\""), "{text}");
|
assert!(text.contains("\"add\"") && text.contains("\"P\"") && text.contains("\"main\"") && text.contains("\"x\""), "{text}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn definition_jumps_to_the_function() {
|
fn definition_jumps_to_the_function() {
|
||||||
let r = ask("textDocument/definition", at("file:///x/a.dino", 11, 14));
|
let r = ask("textDocument/definition", at("file:///x/a.rex", 11, 14));
|
||||||
assert_eq!(r.path(&["range", "start", "line"]).and_then(Json::as_i64), Some(1), "{r:?}");
|
assert_eq!(r.path(&["range", "start", "line"]).and_then(Json::as_i64), Some(1), "{r:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn definition_finds_a_local() {
|
fn definition_finds_a_local() {
|
||||||
let r = ask("textDocument/definition", at("file:///x/a.dino", 3, 12));
|
let r = ask("textDocument/definition", at("file:///x/a.rex", 3, 12));
|
||||||
assert_eq!(r.path(&["range", "start", "line"]).and_then(Json::as_i64), Some(2), "{r:?}");
|
assert_eq!(r.path(&["range", "start", "line"]).and_then(Json::as_i64), Some(2), "{r:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hover_shows_the_signature_and_comment() {
|
fn hover_shows_the_signature_and_comment() {
|
||||||
let r = ask("textDocument/hover", at("file:///x/a.dino", 11, 14));
|
let r = ask("textDocument/hover", at("file:///x/a.rex", 11, 14));
|
||||||
let v = r.path(&["contents", "value"]).and_then(Json::as_str).unwrap_or("").to_string();
|
let v = r.path(&["contents", "value"]).and_then(Json::as_str).unwrap_or("").to_string();
|
||||||
assert!(v.contains("func add(a: int, b: int): int") && v.contains("Adds two numbers."), "{v}");
|
assert!(v.contains("func add(a: int, b: int): int") && v.contains("Adds two numbers."), "{v}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn completion_offers_names_and_keywords() {
|
fn completion_offers_names_and_keywords() {
|
||||||
let r = ask("textDocument/completion", at("file:///x/a.dino", 12, 4)).to_string();
|
let r = ask("textDocument/completion", at("file:///x/a.rex", 12, 4)).to_string();
|
||||||
assert!(r.contains("\"add\"") && r.contains("\"t\"") && r.contains("\"func\"") && r.contains("\"string\""), "{r:?}");
|
assert!(r.contains("\"add\"") && r.contains("\"t\"") && r.contains("\"func\"") && r.contains("\"string\""), "{r:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn signature_help_marks_the_parameter() {
|
fn signature_help_marks_the_parameter() {
|
||||||
let src = "func add(a: int, b: int): int {\n return a + b\n}\nfunc main() {\n add(1, \n}\n";
|
let src = "func add(a: int, b: int): int {\n return a + b\n}\nfunc main() {\n add(1, \n}\n";
|
||||||
let mut msgs = vec![request(1, "initialize", Json::obj(vec![])), open("file:///x/b.dino", src), request(2, "textDocument/signatureHelp", at("file:///x/b.dino", 4, 11))];
|
let mut msgs = vec![request(1, "initialize", Json::obj(vec![])), open("file:///x/b.rex", src), request(2, "textDocument/signatureHelp", at("file:///x/b.rex", 4, 11))];
|
||||||
msgs.extend(exit_messages());
|
msgs.extend(exit_messages());
|
||||||
let (out, _) = talk(msgs);
|
let (out, _) = talk(msgs);
|
||||||
let r = out.into_iter().find(|m| m.get("id") == Some(&Json::Num(2.0))).unwrap().get("result").cloned().unwrap();
|
let r = out.into_iter().find(|m| m.get("id") == Some(&Json::Num(2.0))).unwrap().get("result").cloned().unwrap();
|
||||||
@@ -229,10 +229,10 @@ fn signature_help_marks_the_parameter() {
|
|||||||
// ---------- C headers ----------
|
// ---------- C headers ----------
|
||||||
|
|
||||||
fn with_header(src: &str, method: &str, line: i64, ch: i64) -> Json {
|
fn with_header(src: &str, method: &str, line: i64, ch: i64) -> Json {
|
||||||
let dir = std::env::temp_dir().join(format!("dino-lsp-c-{}-{}", std::process::id(), method.replace('/', "_")));
|
let dir = std::env::temp_dir().join(format!("rex-lsp-c-{}-{}", std::process::id(), method.replace('/', "_")));
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
std::fs::write(dir.join("geo.h"), "typedef struct { double x, y; } Point;\n#define ORIGIN_NAME \"origin\"\n/* distance */\ndouble dist(Point a, Point b);\nint clamp(int v, int lo, int hi);\n").unwrap();
|
std::fs::write(dir.join("geo.h"), "typedef struct { double x, y; } Point;\n#define ORIGIN_NAME \"origin\"\n/* distance */\ndouble dist(Point a, Point b);\nint clamp(int v, int lo, int hi);\n").unwrap();
|
||||||
let uri = format!("file://{}/main.dino", dir.display());
|
let uri = format!("file://{}/main.rex", dir.display());
|
||||||
let mut msgs = vec![request(1, "initialize", Json::obj(vec![])), open(&uri, src), request(2, method, at(&uri, line, ch))];
|
let mut msgs = vec![request(1, "initialize", Json::obj(vec![])), open(&uri, src), request(2, method, at(&uri, line, ch))];
|
||||||
msgs.extend(exit_messages());
|
msgs.extend(exit_messages());
|
||||||
let (out, _) = talk(msgs);
|
let (out, _) = talk(msgs);
|
||||||
|
|||||||
+6
-6
@@ -1,5 +1,5 @@
|
|||||||
use dino::ast::*;
|
use rex::ast::*;
|
||||||
use dino::parser::parse;
|
use rex::parser::parse;
|
||||||
|
|
||||||
fn body_of(src: &str) -> Vec<Stmt> {
|
fn body_of(src: &str) -> Vec<Stmt> {
|
||||||
let p = parse(src).unwrap_or_else(|d| panic!("{}", d.render("test", src)));
|
let p = parse(src).unwrap_or_else(|d| panic!("{}", d.render("test", src)));
|
||||||
@@ -23,7 +23,7 @@ fn all_examples_parse() {
|
|||||||
let mut n = 0;
|
let mut n = 0;
|
||||||
for entry in std::fs::read_dir(dir).unwrap() {
|
for entry in std::fs::read_dir(dir).unwrap() {
|
||||||
let path = entry.unwrap().path();
|
let path = entry.unwrap().path();
|
||||||
if path.extension().map_or(false, |e| e == "dino") {
|
if path.extension().map_or(false, |e| e == "rex") {
|
||||||
let src = std::fs::read_to_string(&path).unwrap();
|
let src = std::fs::read_to_string(&path).unwrap();
|
||||||
parse(&src).unwrap_or_else(|d| panic!("{}", d.render(path.to_str().unwrap(), &src)));
|
parse(&src).unwrap_or_else(|d| panic!("{}", d.render(path.to_str().unwrap(), &src)));
|
||||||
n += 1;
|
n += 1;
|
||||||
@@ -190,7 +190,7 @@ fn semicolons_work() {
|
|||||||
|
|
||||||
// ---------- error messages ----------
|
// ---------- error messages ----------
|
||||||
|
|
||||||
fn err(src: &str) -> dino::error::Diag {
|
fn err(src: &str) -> rex::error::Diag {
|
||||||
parse(src).unwrap_err()
|
parse(src).unwrap_err()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -239,8 +239,8 @@ fn error_two_statements_on_one_line() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn render_shows_caret() {
|
fn render_shows_caret() {
|
||||||
let src = "func main() {\n var x = \n}";
|
let src = "func main() {\n var x = \n}";
|
||||||
let out = err(src).render("t.dino", src);
|
let out = err(src).render("t.rex", src);
|
||||||
assert!(out.contains("t.dino:3:1"), "{out}");
|
assert!(out.contains("t.rex:3:1"), "{out}");
|
||||||
assert!(out.contains("^"), "{out}");
|
assert!(out.contains("^"), "{out}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+17
-17
@@ -1,9 +1,9 @@
|
|||||||
//! End-to-end tests: compile Dino programs to C, build them with the system C
|
//! End-to-end tests: compile Rex programs to C, build them with the system C
|
||||||
//! compiler, run them, and compare the output.
|
//! compiler, run them, and compare the output.
|
||||||
|
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
|
|
||||||
use dino::driver;
|
use rex::driver;
|
||||||
|
|
||||||
struct Output {
|
struct Output {
|
||||||
stdout: String,
|
stdout: String,
|
||||||
@@ -12,7 +12,7 @@ struct Output {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn run_source(src: &str) -> Output {
|
fn run_source(src: &str) -> Output {
|
||||||
let c = driver::compile_to_c(src).unwrap_or_else(|d| panic!("{}", d.render("test.dino", src)));
|
let c = driver::compile_to_c(src).unwrap_or_else(|d| panic!("{}", d.render("test.rex", src)));
|
||||||
run_c(&c, src)
|
run_c(&c, src)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ fn golden_examples() {
|
|||||||
let mut n = 0;
|
let mut n = 0;
|
||||||
for entry in std::fs::read_dir(dir).unwrap() {
|
for entry in std::fs::read_dir(dir).unwrap() {
|
||||||
let path = entry.unwrap().path();
|
let path = entry.unwrap().path();
|
||||||
if path.extension().map_or(false, |e| e == "dino") {
|
if path.extension().map_or(false, |e| e == "rex") {
|
||||||
let src = std::fs::read_to_string(&path).unwrap();
|
let src = std::fs::read_to_string(&path).unwrap();
|
||||||
let want = std::fs::read_to_string(path.with_extension("out"))
|
let want = std::fs::read_to_string(path.with_extension("out"))
|
||||||
.unwrap_or_else(|_| panic!("missing .out file for {}", path.display()));
|
.unwrap_or_else(|_| panic!("missing .out file for {}", path.display()));
|
||||||
@@ -285,7 +285,7 @@ fn generated_c_is_const_correct() {
|
|||||||
// wrong, the C compiler would complain about discarding `const`.
|
// wrong, the C compiler would complain about discarding `const`.
|
||||||
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/basics");
|
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/basics");
|
||||||
for name in ["structs", "value_semantics", "lists", "list_values", "sieve", "enums", "enum_data", "errors", "optionals", "sized", "own_strings", "own_structs", "own_flows"] {
|
for name in ["structs", "value_semantics", "lists", "list_values", "sieve", "enums", "enum_data", "errors", "optionals", "sized", "own_strings", "own_structs", "own_flows"] {
|
||||||
let src = std::fs::read_to_string(format!("{dir}/{name}.dino")).unwrap();
|
let src = std::fs::read_to_string(format!("{dir}/{name}.rex")).unwrap();
|
||||||
let c = driver::compile_to_c(&src).unwrap();
|
let c = driver::compile_to_c(&src).unwrap();
|
||||||
let exe = driver::temp_exe();
|
let exe = driver::temp_exe();
|
||||||
driver::build_exe_with(
|
driver::build_exe_with(
|
||||||
@@ -1125,7 +1125,7 @@ fn optional_as_struct_return_through_match() {
|
|||||||
fn generated_c_for_errors_is_clean() {
|
fn generated_c_for_errors_is_clean() {
|
||||||
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/basics");
|
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/basics");
|
||||||
for name in ["errors", "optionals", "sized", "own_strings", "own_structs", "own_flows"] {
|
for name in ["errors", "optionals", "sized", "own_strings", "own_structs", "own_flows"] {
|
||||||
let src = std::fs::read_to_string(format!("{dir}/{name}.dino")).unwrap();
|
let src = std::fs::read_to_string(format!("{dir}/{name}.rex")).unwrap();
|
||||||
let c = driver::compile_to_c(&src).unwrap();
|
let c = driver::compile_to_c(&src).unwrap();
|
||||||
let exe = driver::temp_exe();
|
let exe = driver::temp_exe();
|
||||||
driver::build_exe_with(&c, &exe, &["-std=c11", "-Wall", "-Werror=incompatible-pointer-types"])
|
driver::build_exe_with(&c, &exe, &["-std=c11", "-Wall", "-Werror=incompatible-pointer-types"])
|
||||||
@@ -1314,8 +1314,8 @@ fn error_float_literal_for_integer_type() {
|
|||||||
// ---------- modules: `import utils` ----------
|
// ---------- modules: `import utils` ----------
|
||||||
|
|
||||||
fn project_c(main: &str, modules: &[(&str, &str)]) -> Result<String, String> {
|
fn project_c(main: &str, modules: &[(&str, &str)]) -> Result<String, String> {
|
||||||
driver::compile_project("main.dino", main, |key| {
|
driver::compile_project("main.rex", main, |key| {
|
||||||
modules.iter().find(|(k, _)| *k == key).map(|(k, src)| (format!("{k}.dino"), src.to_string()))
|
modules.iter().find(|(k, _)| *k == key).map(|(k, src)| (format!("{k}.rex"), src.to_string()))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1398,7 +1398,7 @@ fn project_err(main: &str, modules: &[(&str, &str)]) -> String {
|
|||||||
fn error_private_function() {
|
fn error_private_function() {
|
||||||
let e = project_err("import utils\nfunc main() { print(utils.helper()) }", &[("utils", UTILS)]);
|
let e = project_err("import utils\nfunc main() { print(utils.helper()) }", &[("utils", UTILS)]);
|
||||||
assert!(e.contains("`helper` is private to `utils`"), "{e}");
|
assert!(e.contains("`helper` is private to `utils`"), "{e}");
|
||||||
assert!(e.contains("main.dino:2"), "{e}");
|
assert!(e.contains("main.rex:2"), "{e}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -1420,20 +1420,20 @@ fn error_private_type() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn error_in_module_names_that_file() {
|
fn error_in_module_names_that_file() {
|
||||||
let e = project_err("import bad\nfunc main() { print(bad.f()) }", &[("bad", "pub func f(): int { return \"x\" }")]);
|
let e = project_err("import bad\nfunc main() { print(bad.f()) }", &[("bad", "pub func f(): int { return \"x\" }")]);
|
||||||
assert!(e.contains("bad.dino:1"), "{e}");
|
assert!(e.contains("bad.rex:1"), "{e}");
|
||||||
assert!(e.contains("expected `int`"), "{e}");
|
assert!(e.contains("expected `int`"), "{e}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn error_syntax_error_in_module() {
|
fn error_syntax_error_in_module() {
|
||||||
let e = project_err("import bad\nfunc main() {}", &[("bad", "func f( {")]);
|
let e = project_err("import bad\nfunc main() {}", &[("bad", "func f( {")]);
|
||||||
assert!(e.contains("bad.dino"), "{e}");
|
assert!(e.contains("bad.rex"), "{e}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn error_missing_module() {
|
fn error_missing_module() {
|
||||||
let e = project_err("import nope\nfunc main() {}", &[]);
|
let e = project_err("import nope\nfunc main() {}", &[]);
|
||||||
assert!(e.contains("cannot find module `nope`") && e.contains("nope.dino"), "{e}");
|
assert!(e.contains("cannot find module `nope`") && e.contains("nope.rex"), "{e}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -1452,7 +1452,7 @@ fn error_unknown_name_in_module() {
|
|||||||
fn error_module_does_not_see_main_or_other_imports() {
|
fn error_module_does_not_see_main_or_other_imports() {
|
||||||
// `b` imports nothing, so it can't use `os`
|
// `b` imports nothing, so it can't use `os`
|
||||||
let e = project_err("import b\nfunc main() { print(b.f()) }", &[("b", "pub func f(): int { return os.exists(\"x\") }")]);
|
let e = project_err("import b\nfunc main() { print(b.f()) }", &[("b", "pub func f(): int { return os.exists(\"x\") }")]);
|
||||||
assert!(e.contains("b.dino"), "{e}");
|
assert!(e.contains("b.rex"), "{e}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -1468,7 +1468,7 @@ fn error_private_field() {
|
|||||||
// ---------- move on last use ----------
|
// ---------- move on last use ----------
|
||||||
|
|
||||||
fn c_of(src: &str) -> String {
|
fn c_of(src: &str) -> String {
|
||||||
driver::compile_to_c(src).unwrap_or_else(|d| panic!("{}", d.render("test.dino", src)))
|
driver::compile_to_c(src).unwrap_or_else(|d| panic!("{}", d.render("test.rex", src)))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -2154,7 +2154,7 @@ fn string_slice_out_of_range_panics() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn calc_example_session() {
|
fn calc_example_session() {
|
||||||
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/calc");
|
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/calc");
|
||||||
let main = format!("{dir}/main.dino");
|
let main = format!("{dir}/main.rex");
|
||||||
let c = driver::compile_file(&main).unwrap_or_else(|e| panic!("{e}"));
|
let c = driver::compile_file(&main).unwrap_or_else(|e| panic!("{e}"));
|
||||||
let exe = driver::temp_exe();
|
let exe = driver::temp_exe();
|
||||||
driver::build_exe_with(&c, &exe, &["-std=c11", "-fwrapv", "-w", "-fsanitize=address", "-g"]).unwrap();
|
driver::build_exe_with(&c, &exe, &["-std=c11", "-fwrapv", "-w", "-fsanitize=address", "-g"]).unwrap();
|
||||||
@@ -2203,8 +2203,8 @@ fn docs_examples_run() {
|
|||||||
}
|
}
|
||||||
let text = std::fs::read_to_string(&path).unwrap();
|
let text = std::fs::read_to_string(&path).unwrap();
|
||||||
let mut rest = text.as_str();
|
let mut rest = text.as_str();
|
||||||
while let Some(start) = rest.find("```dino\n") {
|
while let Some(start) = rest.find("```rex\n") {
|
||||||
let after = &rest[start + 8..];
|
let after = &rest[start + "```rex\n".len()..];
|
||||||
let end = after.find("```").unwrap();
|
let end = after.find("```").unwrap();
|
||||||
let code = &after[..end];
|
let code = &after[..end];
|
||||||
rest = &after[end + 3..];
|
rest = &after[end + 3..];
|
||||||
|
|||||||
Reference in new issue
Block a user