Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ Each command's arguments, flags and examples are in `htl <cmd> --help` (and
| `htl cache` | report what the `.htl/cache` store holds, or empty it (`status`, `clear`; see Caching) |
| `htl dts` | write the `.d.tl` files this project declares from Rust (`#[host_module]`, `#[derive(TealRecord)]`), Teal (`---@contract`) and crate dependencies ([`htl::dep_dts`](https://docs.rs/htl/latest/htl/dep_dts/index.html)) |
| `htl shapes` | write an `lshape` run-time schema and typed `Schema<T>` `.d.tl` for each record and enum the project declares ([`htl::shapes`](https://docs.rs/htl/latest/htl/shapes/index.html)) |
| `htl rs` | write one Rust file deriving `TealRecord` for each record and enum the modules in `[rust] modules` declare ([`htl::rsgen`](https://docs.rs/htl/latest/htl/rsgen/index.html)) |
| `htl rs` | write one Rust file: a `TealRecord` type for each record and enum of the modules in `[rust] modules`, a client for each module in `[rust] exports` ([`htl::rsgen`](https://docs.rs/htl/latest/htl/rsgen/index.html)) |
| `htl lsp` | run the language server on stdio, whose diagnostics are `htl check`'s (see Editors) |

Exit code 1 is a verdict (an error in a file, a finding at `deny`, a failing test, a name
Expand Down Expand Up @@ -221,6 +221,51 @@ and the pages behind it are
nothing is embedded and `require` goes through mlua-pkg at run time. Its README says what
each one prints and which line of the output is the point.

### Calling Teal from async Rust (`htl::run`, `[rust] exports`)

A host whose logic is in Teal starts one runner and calls the functions of a module on it.
With `htl = { features = ["async"] }`, `[rust] exports = ["app"]` in `htl.toml`, and
`htl::teal_types!();` at the crate root (or `htl rs`, which writes the same code to a file),
the record a module returns becomes a typed client; an argument or a result that disagrees
with the Teal declaration fails `cargo build`:

```teal
local record app
add: function(a: integer, b: integer): integer -- a function the body declares is a method
end

function app.add(a: integer, b: integer): integer
return a + b
end

return app
```

```rust
htl::teal_types!(); // at the crate root: reads `[rust]` of htl.toml

async fn run() -> anyhow::Result<()> {
let (runner, driver) = htl::run::start(htl::run::RunnerConfig {
search_paths: vec!["src".into()],
deadline: std::time::Duration::from_secs(5),
queue: 64,
})
.await?;
let app = app::App::load(&runner, &[]).await?; // `require("app")`, in a state of its own
let n: i64 = app.add(2, 3).await?; // Result<i64, htl::run::CallError>
driver.shutdown().await?;
Ok(())
}
```

Every call runs under the runner's `deadline` and is cut off past it. Each `load` is an
instance with its own program state, so two instances of one module share nothing of the
module's own. A client is named for the record its module returns, so the clients of
`local record M` modules are all `M`, told apart by their module path (`shop::app::M`).
What a runner promises is [`htl::run`](https://docs.rs/htl/latest/htl/run/index.html);
which functions get a method, how each type is written, and what is refused is the
Exports section of [`htl::rsgen`](https://docs.rs/htl/latest/htl/rsgen/index.html).

## Lints (`htl check`, `include_tl!`)

Every rule has a level — `allow`, `warn` or `deny` — and a project sets it by name:
Expand Down
24 changes: 12 additions & 12 deletions crates/htl-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ Examples:
dir: Option<PathBuf>,
},
/// Write a Rust struct for each record and a Rust enum for each enum that the modules
/// listed in `[rust] modules` declare
/// listed in `[rust] modules` declare, and a client for each module in `[rust] exports`
///
/// Reads the project's own `.tl` files, as `htl shapes` does, and writes one file,
/// `<source>/teal_types.rs` unless `[rust] out` says otherwise: one `pub mod` per module
Expand All @@ -432,7 +432,9 @@ Examples:
/// back. The record is the source: nothing generated is to be edited. A field is
/// `Option<T>` unless its record is marked `---@struct` and the field is neither
/// `---@optional` nor `T | nil`; `[rust.types] "ev.Event.at" = "u32"` gives one field
/// the Rust type written there. What is lowered, the mapping, and every case that is
/// the Rust type written there. A module listed in `[rust] exports` gets a client for
/// its functions, called on an `htl::run` instance (the host builds `htl` with its
/// `async` feature). What is lowered, the mapping, and every case that is
/// refused (a function field, a generic, a union, a tuple, `---@extensible`, a type of
/// a module that is not listed, a name Rust cannot have, ...) is the module doc of
/// `htl::rsgen`; a run with any such problem names each at `file:line:col` and writes
Expand All @@ -441,13 +443,14 @@ Examples:
/// Reports `htl rs: wrote <path>` or `htl rs: <path> is current` on stderr; a file
/// whose text would not change is not touched. A target that exists and does not begin
/// with the line `htl rs` writes is not one of its own and is never overwritten or
/// removed: it exits non-zero, saying so. With `[rust] modules` empty (the default) it
/// writes nothing, and removes a file an earlier run wrote. A type error in any own
/// removed: it exits non-zero, saying so. With `[rust] modules` and `exports` empty (the
/// default) it writes nothing, and removes a file an earlier run wrote. A type error in any own
/// file, listed or not, is reported and nothing is written.
///
/// `--check` writes nothing: it compares what would be written with the file, and
/// exits non-zero with `htl rs: <path> is stale; run htl rs` when they differ, the file
/// is missing, or `[rust] modules` is empty and a file `htl rs` wrote is still there.
/// is missing, or `[rust] modules` and `exports` are empty and a file `htl rs` wrote is
/// still there.
/// The file is committed, and this is how CI says it has fallen behind the Teal.
Rs {
/// Project root or any path inside it (default: current directory)
Expand Down Expand Up @@ -1623,15 +1626,12 @@ fn cmd_rs(dir: Option<&Path>, check: bool) -> Result<ExitCode> {
None => source.join("teal_types.rs"),
};
let shown = out.strip_prefix(&root).unwrap_or(&out).to_path_buf();
let spec = htl::rsgen::Spec {
modules: cfg.rust.modules.clone(),
types: cfg.rust.types.clone(),
};
let spec = htl::rsgen::Spec::from(&cfg.rust);

// Nothing is asked for: nothing is checked, and a file an earlier run wrote is no longer
// wanted. One that is somebody's is none of this command's business.
if spec.modules.is_empty() {
eprintln!("htl rs: nothing to write ([rust] modules is empty)");
if spec.is_empty() {
eprintln!("htl rs: nothing to write ([rust] modules and exports are empty)");
if !written_by(&out, Writer::Rs)? {
return Ok(ExitCode::SUCCESS);
}
Expand Down Expand Up @@ -1683,7 +1683,7 @@ fn cmd_rs(dir: Option<&Path>, check: bool) -> Result<ExitCode> {
eprintln!("htl rs: {} not written", shown.display());
return Ok(ExitCode::FAILURE);
}
// `modules` was not empty above.
// `modules` and `exports` were not both empty above.
htl::rsgen::Rendered::Nothing => return Ok(ExitCode::SUCCESS),
};

Expand Down
52 changes: 51 additions & 1 deletion crates/htl-cli/tests/rs_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,56 @@ fn a_record_and_an_enum_are_written_as_a_struct_and_an_enum() {
);
}

/// The project of `htl-core/tests/fixtures/client`: `[rust] exports` next to `modules`, and
/// the file `htl rs` writes for it, which `teal_types!()` expands to as well (the test of
/// `htl-macros`) and which the `htl` crate compiles against `htl::run`.
#[test]
fn an_exported_module_is_written_as_the_client_the_macro_expands_to() {
let root = common::tempdir("htl-cli-rs", "client");
write(
&root.join("htl.toml"),
include_str!("../../htl-core/tests/fixtures/client/htl.toml"),
);
write(
&root.join("src/shop/types.tl"),
include_str!("../../htl-core/tests/fixtures/client/src/shop/types.tl"),
);
write(
&root.join("src/shop/app.tl"),
include_str!("../../htl-core/tests/fixtures/client/src/shop/app.tl"),
);
let out = htl(&root, &["rs"]);
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(stderr(&out), "htl rs: wrote src/teal_types.rs\n");
assert_eq!(
read(&root.join("src/teal_types.rs")),
include_str!("../../htl-core/tests/fixtures/client/teal_types.rs")
);
}

/// `exports` without `modules` is something to write, and a note about a function the
/// client does not have is said without failing the run.
#[test]
fn exports_alone_are_written_and_a_function_outside_the_body_is_a_note() {
let app = "local record app\n add: function(integer, integer): integer\nend\n\
function app.add(a: integer, b: integer): integer\n return a + b\nend\n\
function app.helper()\nend\nreturn app\n";
let root = project_with("exports-alone", "[rust]\nexports = [\"app\"]\n", EV);
write(&root.join("src/app.tl"), app);
let out = htl(&root, &["rs"]);
assert!(out.status.success(), "{}", stderr(&out));
assert!(
stderr(&out).contains(
"src/app.tl:7:1: `app.helper` is defined outside the body of the record, so it is not in the client; declare `helper: function(..)` in the body to add it"
),
"{}",
stderr(&out)
);
let file = read(&root.join("src/teal_types.rs"));
assert!(file.contains("pub struct App {"), "{file}");
assert!(!file.contains("helper"), "{file}");
}

/// Acceptance 2: `---@struct` makes a field required unless it is `---@optional`.
#[test]
fn a_struct_record_requires_the_fields_that_are_not_optional() {
Expand Down Expand Up @@ -204,7 +254,7 @@ fn an_empty_modules_removes_the_file_it_wrote() {
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(
stderr(&out),
"htl rs: nothing to write ([rust] modules is empty)\n\
"htl rs: nothing to write ([rust] modules and exports are empty)\n\
htl rs: removed src/teal_types.rs\n"
);
assert!(!root.join("src/teal_types.rs").exists());
Expand Down
30 changes: 21 additions & 9 deletions crates/htl-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,10 @@
//! async = true # async / await are keywords (local async function f, async local
//! # x = e, await x, await f()); off, they are ordinary names
//!
//! [rust] # htl rs: Rust types written from Teal records and enums
//! modules = ["ev"] # the modules written; absent or empty, htl rs writes nothing
//! [rust] # htl rs: Rust types from Teal records and enums, clients of modules
//! modules = ["ev"] # the modules whose types are written
//! # exports = ["app"] # the modules whose functions get a client (needs htl's `async`);
//! # no module and no export: htl rs writes nothing
//! # out = "src/teal_types.rs" # where; default "<source>/teal_types.rs"
//!
//! [rust.types]
Expand Down Expand Up @@ -119,8 +121,8 @@ pub struct HtlConfig {
/// `await`, off unless the project says so.
#[serde(default)]
pub lang: LangConfig,
/// `[rust]` — which modules `htl rs` writes Rust types for, where, and how a field's
/// Rust type is overridden.
/// `[rust]` — which modules `htl rs` writes Rust types and clients for, where, and how
/// a field's Rust type is overridden.
#[serde(default)]
pub rust: RustConfig,
/// Static counterpart of `TealResolver::expect_type` / `require_fields`: files
Expand Down Expand Up @@ -547,11 +549,13 @@ impl LangConfig {
}
}

/// `[rust]`: the Rust types `htl rs` writes from this project's Teal records and enums.
/// `[rust]`: the Rust types and clients `htl rs` writes from this project's Teal records,
/// enums and module functions.
///
/// ```toml
/// [rust]
/// modules = ["ev", "geom.types"] # the modules whose records and enums are written
/// exports = ["app"] # the modules whose functions get a client
/// out = "src/teal_types.rs" # where; default "<source>/teal_types.rs"
///
/// [rust.types]
Expand All @@ -564,12 +568,20 @@ impl LangConfig {
#[serde(deny_unknown_fields)]
pub struct RustConfig {
/// The modules (`ev`, `geom.types`: the names `require` takes) whose records and enums
/// `htl rs` writes. Absent or empty: `htl rs` writes nothing, and removes the file an
/// earlier run wrote. The opt-in is per module, because a module of shared types is the
/// unit a Rust host imports. A name that is no module of the project's own sources is a
/// problem, not a no-op.
/// `htl rs` writes. Absent or empty, and `exports` too: `htl rs` writes nothing, and
/// removes the file an earlier run wrote. The opt-in is per module, because a module of
/// shared types is the unit a Rust host imports. A name that is no module of the
/// project's own sources is a problem, not a no-op.
#[serde(default)]
pub modules: Vec<String>,
/// The modules (`app`: the name `require` takes) whose returned record `htl rs` writes
/// as a client: a struct with one async method per function the record's body declares,
/// each a call on an `htl::run::Instance`. What a client is made of, and what refuses
/// one, is the Exports section of the module doc of [`crate::rsgen`]. The generated
/// code names `htl::run`, so the host builds `htl` with its `async` feature. A name that
/// is no module of the project's own sources is a problem, as in `modules`.
#[serde(default)]
pub exports: Vec<String>,
/// The file `htl rs` writes, relative to `htl.toml`. Absent: `teal_types.rs` in the
/// source directory (`[layout] source`). A file there that `htl rs` did not write is
/// never overwritten. Only the command reads this; the lowering does not.
Expand Down
Loading
Loading