Skip to content

Write an extension in Rust

This guide builds an extension from an empty folder. The extension shows code in color. It uses the Rust library syntect for the work. Novis does not include a syntax highlighter, so an extension is the way to add one. At the end, a web page uses the extension to show Markdown with colored code blocks.

The extension has two classes:

  • Example\Highlight\Highlighter is written in Rust. It has two methods: tokens splits code into tokens, such as keywords and strings, and languages returns the languages it knows.
  • Example\Highlight\Code is written in Novis. It calls Highlighter and writes the tokens as HTML. It is packed into the same file as the Rust code.

Core\Markdown::toHtml converts Markdown to HTML. Its code parameter is a function that writes the HTML of each code block. The web page passes Code::toHtml there.

The finished project is in the Novis repository, in the folder website/guides/highlight-extension. The last section shows how to download it.

  • Novis. See Install.
  • Rust, installed with rustup.
  • The Rust target wasm32-wasip2. It compiles Rust to WebAssembly:
Terminal window
rustup target add wasm32-wasip2

nvs ext new writes a small extension that works. Start from it:

Terminal window
nvs ext new --lang rust highlight
cd highlight

The folder highlight now has these files:

File What it is
Cargo.toml The Rust package.
src/lib.rs The Rust code of the extension.
wit/greeting.wit The functions of the extension, written in WIT.
wit/deps/ What every extension can use. Do not change these files.
nvsx.toml The manifest: the class name and the Novis signature of each method.
tests/GreetingTest.nvs A Novis test for the extension.

The template is the class Example\Greeting with one method, hello. You can build and test it now to check that your tools work:

Terminal window
cargo build --release --target wasm32-wasip2
nvs ext build
nvs ext test

Then delete wit/greeting.wit, tests/GreetingTest.nvs and the file greeting.nvsx that nvs ext build wrote. The next steps add the files of the highlighter.

WIT is the language that WebAssembly components use to describe their functions. Novis reads it to know what the extension exports. Create wit/highlight.wit:

wit/highlight.wit
package example:highlight;
/// The functions a Novis program can call. Each one returns a `result`: the
/// value, or an `error` that the program gets as an exception.
interface api {
use nvs:ext/types@1.0.0.{error};
/// One piece of the code: its text, and what kind of text it is, such as
/// `keyword` or `comment`. The kind is empty for plain text.
record token {
text: string,
kind: string,
}
/// Splits `code` into tokens with the grammar of `language`. Returns
/// `none` when the extension has no grammar for `language`.
tokens: func(language: string, code: string) -> result<option<list<token>>, error>;
/// Returns the name of every language the extension has a grammar for.
languages: func() -> result<list<string>, error>;
}
/// What this project builds: the `nvs:ext` world, plus the functions above.
/// The files under `deps/` define that world. Do not change them.
world highlight {
include nvs:ext/extension@1.0.0;
export api;
}

A few things to know about this file:

  • A name in WIT uses dashes. A function to-html is to_html in Rust and toHtml in Novis.
  • Every function returns a result: the value, or an error. Novis throws an exception for an error. You can see which one in Errors.
  • The world at the end includes nvs:ext/extension. That is what every Novis extension can use.

Each WIT type has one Novis type:

WIT Novis
bool, s64, u64, f64 bool, int, uint, float
string string
borrow<bytes> as a parameter, bytes as a result bytes
list<T> array<T>
record an anonymous object, such as { text: string, kind: string }
option<T> ?T
enum an enum

A WIT bytes is a byte string that Novis keeps. The extension reads it with read(). It builds a result with append(). A WIT file that uses bytes needs the line use nvs:ext/types@1.0.0.{error, bytes};. A list<u8> for a Novis bytes does not load.

tokens returns option<list<token>>. In Novis, that is ?array<{ text: string, kind: string }>. The result is null when the extension has no grammar for the language.

Open Cargo.toml. Change the package name to highlight, and add syntect under [dependencies]:

Cargo.toml
[package]
name = "highlight"
version = "0.1.0"
edition = "2024"
publish = false
# A `cdylib` builds one wasm file for `nvs ext build` to pack.
[lib]
crate-type = ["cdylib"]
[dependencies]
wit-bindgen = "0.63"
# The syntax highlighter. `default-syntaxes` contains the grammars of many
# languages. `regex-fancy` uses a regex library written in Rust, which builds
# for WebAssembly.
syntect = { version = "5.3", default-features = false, features = ["default-syntaxes", "regex-fancy"] }
[profile.release]
opt-level = "s"
lto = true
strip = true
# This table makes the project its own workspace. Without it, a project inside
# another Cargo workspace is built as part of that workspace.
[workspace]

syntect uses the grammars of the text editor Sublime Text, and it includes grammars for many languages. Its default regex library is written in C. The feature regex-fancy uses a regex library written in Rust, which builds for WebAssembly with no other tools.

crate-type = ["cdylib"] makes Cargo write one .wasm file. The [workspace] table at the end makes the project build alone, also inside another Cargo workspace.

Replace src/lib.rs:

src/lib.rs
// The code of the extension. Novis calls `tokens` as `Example\Highlight\Highlighter::tokens`
// and `languages` as `Example\Highlight\Highlighter::languages`.
// This macro reads the WIT files in `wit/` and writes the Rust types for them.
// `generate_all` also writes the types of the `nvs:ext` world and of WASI.
wit_bindgen::generate!({
path: "wit",
world: "highlight",
generate_all,
});
use std::sync::LazyLock;
use exports::example::highlight::api::{Error, Guest, Token};
use syntect::easy::ScopeRangeIterator;
use syntect::parsing::{ParseState, Scope, ScopeStack, SyntaxSet};
// The grammars of every language. They are loaded once, at the first call.
static SYNTAXES: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines);
// Each kind of token, and the scopes that give it. A grammar gives each piece of
// text a list of scopes, such as `keyword.control.rust`. The first scope in this
// list that starts a scope of the text gives its kind.
static KINDS: LazyLock<Vec<(Scope, &'static str)>> = LazyLock::new(|| {
[
("comment", "comment"),
("string", "string"),
("constant.numeric", "number"),
("constant", "constant"),
("keyword", "keyword"),
("storage", "keyword"),
("entity.name.function", "function"),
("support.function", "function"),
("entity.name", "type"),
("support.type", "type"),
("support.class", "type"),
("variable", "variable"),
]
.into_iter()
.map(|(scope, kind)| (Scope::new(scope).expect("a valid scope"), kind))
.collect()
});
struct Highlight;
impl Guest for Highlight {
// `tokens` splits the code into tokens. Two tokens of the same kind next to
// each other are joined, so the result is short.
fn tokens(language: String, code: String) -> Result<Option<Vec<Token>>, Error> {
let Some(syntax) = SYNTAXES.find_syntax_by_token(&language) else {
return Ok(None);
};
let mut state = ParseState::new(syntax);
let mut scopes = ScopeStack::new();
let mut tokens: Vec<Token> = Vec::new();
for line in code.split_inclusive('\n') {
let ops = state
.parse_line(line, &SYNTAXES)
.map_err(|e| Error::Runtime(e.to_string()))?;
for (range, op) in ScopeRangeIterator::new(&ops, line) {
scopes
.apply(op)
.map_err(|e| Error::Runtime(format!("{e:?}")))?;
if range.is_empty() {
continue;
}
let kind = kind_of(&scopes);
match tokens.last_mut() {
Some(last) if last.kind == kind => last.text.push_str(&line[range]),
_ => tokens.push(Token {
text: line[range].to_string(),
kind: kind.to_string(),
}),
}
}
}
Ok(Some(tokens))
}
// `languages` returns the names of the languages, such as `Rust` and `Python`.
fn languages() -> Result<Vec<String>, Error> {
Ok(SYNTAXES
.syntaxes()
.iter()
.filter(|syntax| !syntax.hidden)
.map(|syntax| syntax.name.clone())
.collect())
}
}
// The kind of the innermost scope that has one, or an empty kind.
fn kind_of(scopes: &ScopeStack) -> &'static str {
for scope in scopes.as_slice().iter().rev() {
if let Some((_, kind)) = KINDS.iter().find(|(prefix, _)| prefix.is_prefix_of(*scope)) {
return kind;
}
}
""
}
export!(Highlight);

The macro wit_bindgen::generate! reads the WIT files and writes the Rust types for them. The trait Guest has one method for each function in the WIT file. Token is the WIT record as a Rust struct.

A grammar gives each piece of code a list of scopes, such as keyword.control.rust. kind_of turns those scopes into one short kind, such as keyword. The list of kinds is fixed, so the Novis class knows every kind it can get.

SYNTAXES loads the grammars at the first call. Later calls in the same request use them again.

This extension uses only strings. A function with a bytes parameter or result uses two helpers. They are in the template’s src/lib.rs from Step 1.

read_all reads a bytes parameter into a Vec<u8>. bytes_from returns a Vec<u8> as a new Bytes. In Rust, Bytes is nvs::ext::types::Bytes. The template’s reverse uses both:

fn reverse(data: &Bytes) -> Result<Bytes, Error> {
let mut bytes = read_all(data);
bytes.reverse();
Ok(bytes_from(&bytes))
}

If the Rust code panics, the program gets an ExtensionError. The request goes on. The next call to the extension gets a new copy of it.

Replace nvsx.toml:

nvsx.toml
# The manifest of this extension. `nvs ext build` reads it.
class = "Example\\Highlight\\Highlighter"
interface = "example:highlight/api"
# The wasm file that `cargo build --release --target wasm32-wasip2` writes.
module = "target/wasm32-wasip2/release/highlight.wasm"
# The folder of the Novis classes that are packed with the extension.
source = "nvs"
# One `[[methods]]` table for each function in the `api` interface.
# The signature is written in Novis.
[[methods]]
signature = "tokens(string $language, string $code): ?array<{text: string, kind: string}>"
help = "Splits `code` into tokens with the grammar of `language`. Returns `null` when there is no grammar for `language`."
[[methods]]
signature = "languages(): array<string>"
help = "Returns the name of every language the extension has a grammar for."
Key What it is
class The Novis name of the class.
interface The WIT interface the class calls: the package, then the interface name.
module The .wasm file that Cargo writes.
source A folder of Novis files to pack with the extension. Step 6 adds one.
[[methods]] One table for each function. signature is written in Novis. help is a short description.

The Novis signature and the WIT function must match. If they do not match, nvs ext build stops with an error that names the method.

An extension can contain Novis classes beside its Rust code. They must be in the namespace of the manifest’s class, here Example\Highlight. A program can use them with no autoload line. Create nvs/Code.nvs:

nvs/Code.nvs
<?nvs
namespace Example\Highlight;
use Core\Html;
use Core\Html\Markup;
/// Writes code as HTML with colors.
final class Code
{
/// `Code::toHtml` returns `code` as a `<pre>` block, with a class on each token.
/// The result is `null` when there is no grammar for `language`.
public static function toHtml(tainted string $language, tainted string $code): ?Markup
{
var $tokens = Highlighter::tokens($language, $code);
if ($tokens == null) {
return null;
}
array<Markup> $parts = [];
foreach ($tokens as var $token) {
if ($token->kind == '') {
$parts[] = html`{$token->text}`;
} else {
$parts[] = html`<span class="hl-{$token->kind}">{$token->text}</span>`;
}
}
return html`<pre class="hl"><code>` + Html::join($parts, html``) + html`</code></pre>`;
}
/// `Code::styles` returns a `<style>` element with a color for each kind of token.
public static function styles(): Markup
{
return html`<style>
.hl { background: #f6f8fa; padding: 1em; }
.hl-comment { color: #6a737d; }
.hl-string { color: #032f62; }
.hl-number, .hl-constant { color: #005cc5; }
.hl-keyword { color: #d73a49; }
.hl-function { color: #6f42c1; }
.hl-type { color: #22863a; }
.hl-variable { color: #e36209; }
</style>`;
}
}

Code::toHtml builds the HTML with html templates. A template escapes each value in it, so the code is shown as text. <script> in the code is shown as the text <script>. The result is a Core\Html\Markup value, so a page writes it as HTML.

Each token gets a class, such as hl-keyword, and Code::styles gives each class a color. A template escapes a value in an attribute for HTML, but not for CSS. So the colors are in the style sheet, and the tokens have only class names.

The parameters are tainted string, so a method accepts text from a form. When an argument to an extension is tainted, every string in the result is tainted too. The template escapes them.

Terminal window
cargo build --release --target wasm32-wasip2
nvs ext build

cargo build writes target/wasm32-wasip2/release/highlight.wasm. nvs ext build packs it with the manifest and the Novis files into one file, highlighter.nvsx. It names the file after the last part of the class name. Then it loads the file and checks it, and prints the path and the sha256 of the file.

Run both commands again after each change to the Rust code, the manifest or the Novis files.

Create tests/HighlightTest.nvs:

tests/HighlightTest.nvs
<?nvs
// Tests for the extension. `nvs ext test` runs them with the built `.nvsx` loaded.
use Core\Html;
use Core\Html\Markup;
use Core\Markdown;
use Core\Test;
use Example\Highlight\Code;
use Example\Highlight\Highlighter;
class HighlightTest
{
#[Test]
public function tokensSplitsCodeByKind(): void
{
array<{ text: string, kind: string }> $tokens = Highlighter::tokens('rust', 'let x = 1;') ?? [];
Test::assertSame($tokens[0]->text, 'let');
Test::assertSame($tokens[0]->kind, 'keyword');
}
#[Test]
public function anUnknownLanguageReturnsNull(): void
{
Test::assertNull(Highlighter::tokens('no-such-language', 'x'));
}
#[Test]
public function languagesListsRust(): void
{
Test::assertContains(Highlighter::languages(), 'Rust');
}
#[Test]
public function toHtmlEscapesTheCode(): void
{
Test::assertSame(Html::toSource(Code::toHtml('txt', '<b>') ?? html``, 'comparing the HTML'), '<pre class="hl"><code>&lt;b&gt;</code></pre>');
}
#[Test]
public function markdownUsesItForACodeBlock(): void
{
Markup $html = Markdown::toHtml("```rust\nlet x = 1;\n```", code: fn(string $language, string $code): ?Markup => Code::toHtml($language, $code));
string $want = '<pre class="hl"><code><span class="hl-keyword">let</span> x <span class="hl-keyword">=</span> <span class="hl-number">1</span>;'
. "\n</code></pre>\n";
Test::assertSame(Html::toSource($html, 'comparing the HTML'), $want);
}
}

nvs ext test runs every #[Test] method in the folder tests, with highlighter.nvsx loaded:

Terminal window
nvs ext test
HighlightTest
✓ tokensSplitsCodeByKind 35.4 ms
✓ anUnknownLanguageReturnsNull 2.0 ms
✓ languagesListsRust 2.1 ms
✓ toHtmlEscapesTheCode 2.3 ms
✓ markdownUsesItForACodeBlock 34.7 ms
0 failed, 5 passed, 0 skipped, 0 flaky in 79 ms

The first test that highlights code takes longer, because it loads the grammars.

The tests need no nvs.toml. If highlighter.nvsx is older than a file it is built from, nvs ext test stops and tells you to build it again.

Create demo/index.nvs. It is a page with a form. You write Markdown in the box, and the page shows it as HTML. Each code block that names a language is shown in color:

demo/index.nvs
<?nvs
// A page with a form. You write Markdown in the box, and the page shows it as HTML.
// Each code block that names a language gets colors.
// Start it with `nvs serve index.nvs` in this folder, after you build the extension.
use Core\Html\Markup;
use Core\Markdown;
use Example\Highlight\Code;
// The text that the form sent. The first time, there is no form, so the page uses an example.
tainted string $text = Core\Request::formField('text') ?? "# Rust\n\n```rust\n// Add two numbers.\nfn add(a: i64, b: i64) -> i64 {\n a + b\n}\n```";
// `Markdown::toHtml` calls `Code::toHtml` for each code block that names a language.
// If `Code::toHtml` returns `null`, the block is written as plain text.
Markup $preview = Markdown::toHtml($text, code: fn(string $language, string $code): ?Markup => Code::toHtml($language, $code));
// The colors of each kind of token.
Markup $styles = Code::styles();
echo html`<!doctype html>
<title>Markdown preview</title>
{$styles}
<form method="post">
<textarea name="text" rows="10" cols="60">{$text}</textarea>
<button>Show</button>
</form>
<h2>Preview</h2>
{$preview}
`;

Core\Markdown::toHtml calls the code function for each code block that names a language after its opening backticks. If the function returns null, the block is written as plain text. Code::toHtml returns null for a language it has no grammar for.

A program can use an extension only when the configuration file nvs.toml lists it. nvs ext pin prints the entry for a file:

Terminal window
cd demo
nvs ext pin ../highlighter.nvsx
[[extension]]
path = "/home/you/highlight/highlighter.nvsx"
sha256 = "a09d75a3a0dbc8e46980ebc716f5955705e0ed92c18249cbba4fe070c5b0cf81"

Save the entry as demo/nvs.toml. Your path and your sha256 are different. Then start the server:

Terminal window
nvs serve index.nvs

Open http://127.0.0.1:8000/ and click Show. Try some code that looks like HTML, too:

```html
<script>alert(1)</script>
```

The page shows the <script> tag in color, as text. It does not run.

Each build writes a new highlighter.nvsx with a new sha256. A file whose sha256 is not the one in nvs.toml does not load. So after each build, run nvs ext pin again and replace the entry.

The Rust code can fail in three ways. Each one gives the program something different:

What happens in Rust What the program gets
A function returns Err(Error::Invalid(message)) a LogicError with the message
A function returns Err(Error::Parse(message)) a ParseError with the message
A function returns Err(Error::Runtime(message)) a RuntimeError with the message
The code panics an ExtensionError
The code uses more time or memory than the request may use the request stops, as for any limit

tokens returns Error::Runtime if a grammar cannot read a line. The template’s hello from step 1 shows another error: an empty name returns Error::Invalid.

This extension needs no files and no network. An extension that needs them asks in its manifest, with a [requests] table. The person who runs the server then allows them in the [[extension]] entry. The extension gets only what both allow. See the [[extension]] entry.

Pass a large file on disk to the extension as a path. Do not pass its content as bytes. The extension asks for its folder with read in the [requests] table. The [[extension]] entry allows that folder with grants = { read = [...] }. Then the extension reads the file itself.

wit/highlight.wit
package example:highlight;
/// The functions a Novis program can call. Each one returns a `result`: the
/// value, or an `error` that the program gets as an exception.
interface api {
use nvs:ext/types@1.0.0.{error};
/// One piece of the code: its text, and what kind of text it is, such as
/// `keyword` or `comment`. The kind is empty for plain text.
record token {
text: string,
kind: string,
}
/// Splits `code` into tokens with the grammar of `language`. Returns
/// `none` when the extension has no grammar for `language`.
tokens: func(language: string, code: string) -> result<option<list<token>>, error>;
/// Returns the name of every language the extension has a grammar for.
languages: func() -> result<list<string>, error>;
}
/// What this project builds: the `nvs:ext` world, plus the functions above.
/// The files under `deps/` define that world. Do not change them.
world highlight {
include nvs:ext/extension@1.0.0;
export api;
}

Download only the folder website/guides/highlight-extension of the Novis repository. A sparse clone (a clone that checks out only the folders you name) does this:

Terminal window
git clone --depth 1 --filter=blob:none --sparse https://github.com/novis-lang/novis.git
cd novis
git sparse-checkout set website/guides/highlight-extension
cd website/guides/highlight-extension

Then build and test it, as in steps 7 and 8.