app: cherry-pick rune's pause and sound fixes onto the checkout
Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch ported, carrying the four commits of upstream issues 1320 (a pause while a clip is layered holds the layer's picture and time) and 1325 (a video's sound is read ahead of the clock and leads it). Both were written against eb9f1104 and ported across the refactors since. The faults are the first two and the third in docs/rune-upstream.md; the app's workarounds in review.rs stay until the fixes arrive upstream.
This commit is contained in:
1 parent
80fef698ce
commit
5bf262b82b
3795 files changed
+663463
-28
No files matched your search
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "rune-highlights"
|
||||
version = "0.0.1"
|
||||
edition.workspace = true
|
||||
# Crate code is MIT; vendored highlights.wasm (@pierre/highlights) is Apache-2.0.
|
||||
license = "MIT AND Apache-2.0"
|
||||
description = "Pierre's Highlights (the code highlighter OpenCode's desktop app draws with), translated from its WebAssembly to Rust at build time: 80 languages, the same tokens, no runtime."
|
||||
|
||||
[dependencies]
|
||||
# Identifier characters for the lexers' `is_id_start` and `is_id_continue` imports.
|
||||
unicode-ident = "1"
|
||||
|
||||
[build-dependencies]
|
||||
wasmparser = { version = "0.245", default-features = false, features = ["std", "simd"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
//! Translates `vendor/highlights.wasm` to Rust (`$OUT_DIR/highlights.rs`), which `src/lib.rs`
|
||||
//! includes. See `codegen/translate.rs`.
|
||||
|
||||
#[path = "codegen/translate.rs"]
|
||||
mod translate;
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-changed=vendor/highlights.wasm");
|
||||
println!("cargo:rerun-if-changed=codegen/translate.rs");
|
||||
let wasm = std::fs::read("vendor/highlights.wasm").unwrap_or_else(|e| panic!("vendor/highlights.wasm: {e}"));
|
||||
let rust = translate::translate(&wasm).unwrap_or_else(|e| panic!("vendor/highlights.wasm: {e}"));
|
||||
let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_else(|| panic!("OUT_DIR is unset")));
|
||||
std::fs::write(out.join("highlights.rs"), rust).unwrap_or_else(|e| panic!("highlights.rs: {e}"));
|
||||
}
|
||||
@@ -0,0 +1,663 @@
|
||||
//! A WebAssembly module as Rust source, for `build.rs`.
|
||||
//!
|
||||
//! Each wasm function becomes a Rust function over the module's state (`Wasm`: linear memory and
|
||||
//! globals). The operand stack is resolved here: the value at stack depth `d` of type `t` lives
|
||||
//! in a local `s{d}{t}`, so every instruction is one assignment. Structured control flow maps
|
||||
//! onto labelled blocks: `block` is `'l: { }`, `loop` is `'l: loop { }` (falling off its end
|
||||
//! breaks out), `if` is `'l: { if c != 0 { } else { } }`; a branch first moves the values its
|
||||
//! target keeps into that target's slots. Code after an unconditional branch is skipped up to
|
||||
//! its block's end, as it can never run. Calls stay calls; `call_indirect` dispatches through a
|
||||
//! `match` per signature over the module's one table. Imports become calls to
|
||||
//! `env::<name>(&mut mem, ..)`.
|
||||
//!
|
||||
//! Only what Highlights uses is supported: `i32`, `i64` and `v128` values, one memory, one
|
||||
//! table, active data and element segments, single-result functions and blocks, and the
|
||||
//! integer, memory and `i8x16` instructions below. Anything else fails the build, so a new
|
||||
//! Highlights that needs more says so.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt::Write;
|
||||
|
||||
use wasmparser::{BlockType, DataKind, ElementItems, ElementKind, ExternalKind, FunctionBody, Operator, Parser, Payload, TypeRef, ValType};
|
||||
|
||||
/// The Rust source for `wasm`: `mod generated` with `Wasm` (`Wasm::new()` and one method per
|
||||
/// exported function, in snake case).
|
||||
pub fn translate(wasm: &[u8]) -> Result<String, String> {
|
||||
let m = Module::read(wasm)?;
|
||||
let mut out = String::new();
|
||||
out.push_str("// Generated by build.rs from vendor/highlights.wasm.\n");
|
||||
out.push_str("#[allow(warnings, clippy::all, clippy::pedantic, clippy::nursery, clippy::restriction)]\nmod generated {\nuse super::env;\nuse super::rt::*;\n\n");
|
||||
writeln!(out, "const PAGES: usize = {};\n", m.pages).ok();
|
||||
out.push_str("static DATA: &[(usize, &[u8])] = &[\n");
|
||||
for (at, bytes) in &m.data {
|
||||
writeln!(out, " ({at}, b\"{}\"),", escape(bytes)).ok();
|
||||
}
|
||||
out.push_str("];\n\n#[derive(Clone)]\npub struct Wasm {\n pub mem: Vec<u8>,\n");
|
||||
for (i, (t, _)) in m.globals.iter().enumerate() {
|
||||
writeln!(out, " g{i}: {},", t.rust()).ok();
|
||||
}
|
||||
out.push_str("}\n\nimpl Wasm {\n pub fn new() -> Wasm {\n let mut mem = vec![0u8; PAGES * PAGE];\n for (at, bytes) in DATA {\n mem[*at..*at + bytes.len()].copy_from_slice(bytes);\n }\n Wasm {\n mem,\n");
|
||||
for (i, (_, init)) in m.globals.iter().enumerate() {
|
||||
writeln!(out, " g{i}: {init},").ok();
|
||||
}
|
||||
out.push_str(" }\n }\n");
|
||||
for (name, f) in &m.exports {
|
||||
let sig = m.sig_of(*f);
|
||||
writeln!(out, "\n pub fn {}(&mut self{}){} {{\n f{f}(self{})\n }}", snake(name), params(&sig.params, ""), ret(&sig.results)?, args(sig.params.len())).ok();
|
||||
}
|
||||
out.push_str("}\n\n");
|
||||
let mut indirect = BTreeSet::new();
|
||||
for (k, body) in m.bodies.iter().enumerate() {
|
||||
let index = m.imports.len() as u32 + k as u32;
|
||||
Func::emit(&mut out, &m, index, body, &mut indirect).map_err(|e| format!("function {index}: {e}"))?;
|
||||
}
|
||||
for t in indirect {
|
||||
let sig = &m.types[t as usize];
|
||||
writeln!(out, "fn call_indirect_{t}(m: &mut Wasm, at: i32{}){} {{\n match at {{", params(&sig.params, ""), ret(&sig.results)?).ok();
|
||||
for (i, f) in m.table.iter().enumerate() {
|
||||
if let Some(f) = f
|
||||
&& m.sig_of(*f) == sig
|
||||
{
|
||||
writeln!(out, " {i} => f{f}(m{}),", args(sig.params.len())).ok();
|
||||
}
|
||||
}
|
||||
out.push_str(" _ => trap(),\n }\n}\n\n");
|
||||
}
|
||||
out.push_str("}\n\npub use generated::Wasm;\n");
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum Ty {
|
||||
I32,
|
||||
I64,
|
||||
V128,
|
||||
}
|
||||
|
||||
impl Ty {
|
||||
fn of(v: ValType) -> Result<Ty, String> {
|
||||
match v {
|
||||
ValType::I32 => Ok(Ty::I32),
|
||||
ValType::I64 => Ok(Ty::I64),
|
||||
ValType::V128 => Ok(Ty::V128),
|
||||
other => Err(format!("unsupported value type {other:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn rust(self) -> &'static str {
|
||||
match self {
|
||||
Ty::I32 => "i32",
|
||||
Ty::I64 => "i64",
|
||||
Ty::V128 => "V128",
|
||||
}
|
||||
}
|
||||
|
||||
fn zero(self) -> &'static str {
|
||||
match self {
|
||||
Ty::I32 => "0i32",
|
||||
Ty::I64 => "0i64",
|
||||
Ty::V128 => "[0u8; 16]",
|
||||
}
|
||||
}
|
||||
|
||||
fn suffix(self) -> char {
|
||||
match self {
|
||||
Ty::I32 => 'i',
|
||||
Ty::I64 => 'l',
|
||||
Ty::V128 => 'v',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
struct Sig {
|
||||
params: Vec<Ty>,
|
||||
results: Vec<Ty>,
|
||||
}
|
||||
|
||||
/// What `translate` needs of the module, read in one pass.
|
||||
struct Module<'a> {
|
||||
types: Vec<Sig>,
|
||||
imports: Vec<(String, u32)>,
|
||||
funcs: Vec<u32>,
|
||||
globals: Vec<(Ty, String)>,
|
||||
exports: Vec<(String, u32)>,
|
||||
table: Vec<Option<u32>>,
|
||||
pages: u64,
|
||||
data: Vec<(u32, &'a [u8])>,
|
||||
bodies: Vec<FunctionBody<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> Module<'a> {
|
||||
fn read(wasm: &'a [u8]) -> Result<Module<'a>, String> {
|
||||
let mut m = Module { types: vec![], imports: vec![], funcs: vec![], globals: vec![], exports: vec![], table: vec![], pages: 0, data: vec![], bodies: vec![] };
|
||||
for payload in Parser::new(0).parse_all(wasm) {
|
||||
match payload.map_err(|e| e.to_string())? {
|
||||
Payload::TypeSection(r) => {
|
||||
for t in r.into_iter_err_on_gc_types() {
|
||||
let t = t.map_err(|e| e.to_string())?;
|
||||
let params = t.params().iter().map(|&v| Ty::of(v)).collect::<Result<_, _>>()?;
|
||||
let results = t.results().iter().map(|&v| Ty::of(v)).collect::<Result<_, _>>()?;
|
||||
m.types.push(Sig { params, results });
|
||||
}
|
||||
}
|
||||
Payload::ImportSection(r) => {
|
||||
for i in r.into_imports() {
|
||||
let i = i.map_err(|e| e.to_string())?;
|
||||
let TypeRef::Func(t) = i.ty else { return Err(format!("unsupported import {}", i.name)) };
|
||||
m.imports.push((i.name.to_string(), t));
|
||||
}
|
||||
}
|
||||
Payload::FunctionSection(r) => {
|
||||
for f in r {
|
||||
m.funcs.push(f.map_err(|e| e.to_string())?);
|
||||
}
|
||||
}
|
||||
Payload::MemorySection(r) => {
|
||||
for mem in r {
|
||||
m.pages = mem.map_err(|e| e.to_string())?.initial;
|
||||
}
|
||||
}
|
||||
Payload::GlobalSection(r) => {
|
||||
for g in r {
|
||||
let g = g.map_err(|e| e.to_string())?;
|
||||
let init = match g.init_expr.get_operators_reader().read().map_err(|e| e.to_string())? {
|
||||
Operator::I32Const { value } => format!("{value}i32"),
|
||||
Operator::I64Const { value } => format!("{value}i64"),
|
||||
other => return Err(format!("unsupported global initializer {other:?}")),
|
||||
};
|
||||
m.globals.push((Ty::of(g.ty.content_type)?, init));
|
||||
}
|
||||
}
|
||||
Payload::ExportSection(r) => {
|
||||
for e in r {
|
||||
let e = e.map_err(|e| e.to_string())?;
|
||||
if e.kind == ExternalKind::Func {
|
||||
m.exports.push((e.name.to_string(), e.index));
|
||||
}
|
||||
}
|
||||
}
|
||||
Payload::ElementSection(r) => {
|
||||
for e in r {
|
||||
let e = e.map_err(|e| e.to_string())?;
|
||||
let ElementKind::Active { offset_expr, .. } = e.kind else { return Err("passive element segment".into()) };
|
||||
let Ok(Operator::I32Const { value }) = offset_expr.get_operators_reader().read() else { return Err("element offset".into()) };
|
||||
let ElementItems::Functions(items) = e.items else { return Err("element expressions".into()) };
|
||||
for (k, f) in items.into_iter().enumerate() {
|
||||
let at = value as usize + k;
|
||||
if m.table.len() <= at {
|
||||
m.table.resize(at + 1, None);
|
||||
}
|
||||
m.table[at] = Some(f.map_err(|e| e.to_string())?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Payload::DataSection(r) => {
|
||||
for d in r {
|
||||
let d = d.map_err(|e| e.to_string())?;
|
||||
let DataKind::Active { offset_expr, .. } = d.kind else { return Err("passive data segment".into()) };
|
||||
let Ok(Operator::I32Const { value }) = offset_expr.get_operators_reader().read() else { return Err("data offset".into()) };
|
||||
m.data.push((value as u32, d.data));
|
||||
}
|
||||
}
|
||||
Payload::CodeSectionEntry(body) => m.bodies.push(body),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
fn sig_of(&self, f: u32) -> &Sig {
|
||||
let n = self.imports.len() as u32;
|
||||
let t = if f < n { self.imports[f as usize].1 } else { self.funcs[(f - n) as usize] };
|
||||
&self.types[t as usize]
|
||||
}
|
||||
}
|
||||
|
||||
fn escape(bytes: &[u8]) -> String {
|
||||
let mut s = String::with_capacity(bytes.len());
|
||||
for &b in bytes {
|
||||
match b {
|
||||
b'"' => s.push_str("\\\""),
|
||||
b'\\' => s.push_str("\\\\"),
|
||||
0x20..=0x7e => s.push(b as char),
|
||||
_ => {
|
||||
write!(s, "\\x{b:02x}").ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn params(tys: &[Ty], prefix: &str) -> String {
|
||||
tys.iter().enumerate().map(|(i, t)| format!(", {prefix}a{i}: {}", t.rust())).collect()
|
||||
}
|
||||
|
||||
fn args(n: usize) -> String {
|
||||
(0..n).map(|i| format!(", a{i}")).collect()
|
||||
}
|
||||
|
||||
fn ret(results: &[Ty]) -> Result<String, String> {
|
||||
match results {
|
||||
[] => Ok(String::new()),
|
||||
[t] => Ok(format!(" -> {}", t.rust())),
|
||||
_ => Err("multi-value results".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn snake(name: &str) -> String {
|
||||
name.chars().flat_map(|c| if c.is_ascii_uppercase() { vec!['_', c.to_ascii_lowercase()] } else { vec![c] }).collect()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Kind {
|
||||
Func,
|
||||
Block,
|
||||
Loop,
|
||||
If,
|
||||
}
|
||||
|
||||
/// An open block: where its label's values go and how it is reached.
|
||||
struct Label {
|
||||
kind: Kind,
|
||||
id: usize,
|
||||
/// Stack depth below the block's parameters.
|
||||
height: usize,
|
||||
params: Vec<Ty>,
|
||||
results: Vec<Ty>,
|
||||
}
|
||||
|
||||
/// One function being translated.
|
||||
struct Func<'m> {
|
||||
m: &'m Module<'m>,
|
||||
locals: Vec<Ty>,
|
||||
body: String,
|
||||
stack: Vec<Ty>,
|
||||
labels: Vec<Label>,
|
||||
slots: BTreeSet<(usize, Ty)>,
|
||||
next_label: usize,
|
||||
indent: usize,
|
||||
}
|
||||
|
||||
impl<'m> Func<'m> {
|
||||
fn emit(out: &mut String, m: &'m Module<'m>, index: u32, body: &FunctionBody, indirect: &mut BTreeSet<u32>) -> Result<(), String> {
|
||||
let sig = m.sig_of(index);
|
||||
let mut locals = sig.params.clone();
|
||||
let mut lr = body.get_locals_reader().map_err(|e| e.to_string())?;
|
||||
for _ in 0..lr.get_count() {
|
||||
let (n, t) = lr.read().map_err(|e| e.to_string())?;
|
||||
locals.extend(std::iter::repeat_n(Ty::of(t)?, n as usize));
|
||||
}
|
||||
let mut f = Func { m, locals, body: String::new(), stack: vec![], labels: vec![], slots: BTreeSet::new(), next_label: 1, indent: 1 };
|
||||
f.labels.push(Label { kind: Kind::Func, id: 0, height: 0, params: vec![], results: sig.results.clone() });
|
||||
f.line("'l0: {".into());
|
||||
f.indent += 1;
|
||||
let mut ops = body.get_operators_reader().map_err(|e| e.to_string())?;
|
||||
// After an unconditional branch: how many blocks deep the skipped code is.
|
||||
let mut dead: Option<usize> = None;
|
||||
while !ops.eof() {
|
||||
let op = ops.read().map_err(|e| e.to_string())?;
|
||||
if let Some(depth) = dead.as_mut() {
|
||||
match op {
|
||||
Operator::Block { .. } | Operator::Loop { .. } | Operator::If { .. } => *depth += 1,
|
||||
Operator::End | Operator::Else if *depth > 0 => {
|
||||
if matches!(op, Operator::End) {
|
||||
*depth -= 1;
|
||||
}
|
||||
}
|
||||
Operator::End | Operator::Else => dead = None,
|
||||
_ => {}
|
||||
}
|
||||
if dead.is_some() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if f.op(op, indirect)? {
|
||||
dead = Some(0);
|
||||
}
|
||||
}
|
||||
writeln!(out, "fn f{index}(m: &mut Wasm{}){} {{", params(&sig.params, "mut "), ret(&sig.results)?).ok();
|
||||
for (i, t) in f.locals.iter().enumerate() {
|
||||
if i < sig.params.len() {
|
||||
writeln!(out, " let mut l{i} = a{i};").ok();
|
||||
} else {
|
||||
writeln!(out, " let mut l{i}: {} = {};", t.rust(), t.zero()).ok();
|
||||
}
|
||||
}
|
||||
for (d, t) in &f.slots {
|
||||
writeln!(out, " let mut s{d}{}: {} = {};", t.suffix(), t.rust(), t.zero()).ok();
|
||||
}
|
||||
out.push_str(&f.body);
|
||||
out.push_str("}\n\n");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn line(&mut self, s: String) {
|
||||
for _ in 0..self.indent {
|
||||
self.body.push_str(" ");
|
||||
}
|
||||
self.body.push_str(&s);
|
||||
self.body.push('\n');
|
||||
}
|
||||
|
||||
fn slot(&mut self, depth: usize, t: Ty) -> String {
|
||||
self.slots.insert((depth, t));
|
||||
format!("s{depth}{}", t.suffix())
|
||||
}
|
||||
|
||||
fn pop(&mut self) -> Result<String, String> {
|
||||
let t = self.stack.pop().ok_or("stack underflow")?;
|
||||
Ok(self.slot(self.stack.len(), t))
|
||||
}
|
||||
|
||||
fn push(&mut self, t: Ty) -> String {
|
||||
self.stack.push(t);
|
||||
self.slot(self.stack.len() - 1, t)
|
||||
}
|
||||
|
||||
fn top(&self, n: usize) -> Result<Ty, String> {
|
||||
self.stack.len().checked_sub(n + 1).map(|i| self.stack[i]).ok_or_else(|| "stack underflow".into())
|
||||
}
|
||||
|
||||
/// `r = f(a)`: pops one value, pushes a `t`.
|
||||
fn unop(&mut self, t: Ty, f: impl FnOnce(&str) -> String) -> Result<(), String> {
|
||||
let a = self.pop()?;
|
||||
let r = self.push(t);
|
||||
self.line(format!("{r} = {};", f(&a)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `r = f(a, b)`: pops two values, pushes a `t`.
|
||||
fn binop(&mut self, t: Ty, f: impl FnOnce(&str, &str) -> String) -> Result<(), String> {
|
||||
let b = self.pop()?;
|
||||
let a = self.pop()?;
|
||||
let r = self.push(t);
|
||||
self.line(format!("{r} = {};", f(&a, &b)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn call(&mut self, call: &str, sig: &Sig) -> Result<(), String> {
|
||||
match sig.results.as_slice() {
|
||||
[] => self.line(format!("{call};")),
|
||||
[t] => {
|
||||
let r = self.push(*t);
|
||||
self.line(format!("{r} = {call};"));
|
||||
}
|
||||
_ => return Err("multi-value call".into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pop_args(&mut self, n: usize) -> Result<String, String> {
|
||||
let mut v = (0..n).map(|_| self.pop()).collect::<Result<Vec<_>, _>>()?;
|
||||
v.reverse();
|
||||
Ok(v.iter().map(|a| format!(", {a}")).collect())
|
||||
}
|
||||
|
||||
/// A jump to the label `depth` blocks out: the values it keeps moved into its slots, then
|
||||
/// `break`, `continue` or `return`.
|
||||
fn branch(&mut self, depth: u32) -> Result<String, String> {
|
||||
let l = self.labels.len().checked_sub(depth as usize + 1).map(|i| &self.labels[i]).ok_or("branch depth")?;
|
||||
let (kind, id, height) = (l.kind, l.id, l.height);
|
||||
let keep = if kind == Kind::Loop { l.params.clone() } else { l.results.clone() };
|
||||
let from = self.stack.len().checked_sub(keep.len()).ok_or("stack underflow")?;
|
||||
let mut s = String::new();
|
||||
for (i, &t) in keep.iter().enumerate() {
|
||||
if from + i != height + i {
|
||||
let (a, b) = (self.slot(from + i, t), self.slot(height + i, t));
|
||||
write!(s, "{b} = {a}; ").ok();
|
||||
}
|
||||
}
|
||||
match (kind, keep.as_slice()) {
|
||||
(Kind::Func, []) => s.push_str("return;"),
|
||||
(Kind::Func, [t]) => {
|
||||
let r = self.slot(height, *t);
|
||||
write!(s, "return {r};").ok();
|
||||
}
|
||||
(Kind::Func, _) => return Err("multi-value return".into()),
|
||||
(Kind::Loop, _) => {
|
||||
write!(s, "continue 'l{id};").ok();
|
||||
}
|
||||
_ => {
|
||||
write!(s, "break 'l{id};").ok();
|
||||
}
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn open(&mut self, kind: Kind, bt: BlockType) -> Result<usize, String> {
|
||||
let (params, results) = match bt {
|
||||
BlockType::Empty => (vec![], vec![]),
|
||||
BlockType::Type(v) => (vec![], vec![Ty::of(v)?]),
|
||||
BlockType::FuncType(t) => {
|
||||
let s = &self.m.types[t as usize];
|
||||
(s.params.clone(), s.results.clone())
|
||||
}
|
||||
};
|
||||
let id = self.next_label;
|
||||
self.next_label += 1;
|
||||
let height = self.stack.len().checked_sub(params.len()).ok_or("stack underflow")?;
|
||||
self.labels.push(Label { kind, id, height, params, results });
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Emits `op`. True when it always jumps, so what follows in its block never runs.
|
||||
fn op(&mut self, op: Operator, indirect: &mut BTreeSet<u32>) -> Result<bool, String> {
|
||||
use Operator as O;
|
||||
match op {
|
||||
O::Nop => {}
|
||||
O::Unreachable => {
|
||||
self.line("trap();".into());
|
||||
return Ok(true);
|
||||
}
|
||||
O::Block { blockty } => {
|
||||
let id = self.open(Kind::Block, blockty)?;
|
||||
self.line(format!("'l{id}: {{"));
|
||||
self.indent += 1;
|
||||
}
|
||||
O::Loop { blockty } => {
|
||||
let id = self.open(Kind::Loop, blockty)?;
|
||||
self.line(format!("'l{id}: loop {{"));
|
||||
self.indent += 1;
|
||||
}
|
||||
O::If { blockty } => {
|
||||
let c = self.pop()?;
|
||||
let id = self.open(Kind::If, blockty)?;
|
||||
self.line(format!("'l{id}: {{ if {c} != 0 {{"));
|
||||
self.indent += 1;
|
||||
}
|
||||
O::Else => {
|
||||
let l = self.labels.last().ok_or("else outside a block")?;
|
||||
let (height, params) = (l.height, l.params.clone());
|
||||
self.stack.truncate(height);
|
||||
self.stack.extend(params);
|
||||
self.indent -= 1;
|
||||
self.line("} else {".into());
|
||||
self.indent += 1;
|
||||
}
|
||||
O::End => {
|
||||
let l = self.labels.pop().ok_or("end outside a block")?;
|
||||
self.indent -= 1;
|
||||
match l.kind {
|
||||
Kind::Loop => {
|
||||
self.indent += 1;
|
||||
self.line(format!("break 'l{};", l.id));
|
||||
self.indent -= 1;
|
||||
self.line("}".into());
|
||||
}
|
||||
Kind::If => self.line("} }".into()),
|
||||
Kind::Block | Kind::Func => self.line("}".into()),
|
||||
}
|
||||
self.stack.truncate(l.height);
|
||||
self.stack.extend(l.results.iter().copied());
|
||||
if l.kind == Kind::Func {
|
||||
match l.results.as_slice() {
|
||||
[] => {}
|
||||
[t] => {
|
||||
let r = self.slot(0, *t);
|
||||
self.line(r);
|
||||
}
|
||||
_ => return Err("multi-value results".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
O::Br { relative_depth } => {
|
||||
let s = self.branch(relative_depth)?;
|
||||
self.line(s);
|
||||
return Ok(true);
|
||||
}
|
||||
O::BrIf { relative_depth } => {
|
||||
let c = self.pop()?;
|
||||
let s = self.branch(relative_depth)?;
|
||||
self.line(format!("if {c} != 0 {{ {s} }}"));
|
||||
}
|
||||
O::BrTable { targets } => {
|
||||
let c = self.pop()?;
|
||||
self.line(format!("match {c} as u32 {{"));
|
||||
for (i, t) in targets.targets().enumerate() {
|
||||
let s = self.branch(t.map_err(|e| e.to_string())?)?;
|
||||
self.line(format!(" {i} => {{ {s} }}"));
|
||||
}
|
||||
let s = self.branch(targets.default())?;
|
||||
self.line(format!(" _ => {{ {s} }}"));
|
||||
self.line("}".into());
|
||||
return Ok(true);
|
||||
}
|
||||
O::Return => {
|
||||
let s = self.branch(self.labels.len() as u32 - 1)?;
|
||||
self.line(s);
|
||||
return Ok(true);
|
||||
}
|
||||
O::Call { function_index } => {
|
||||
let sig = self.m.sig_of(function_index);
|
||||
let a = self.pop_args(sig.params.len())?;
|
||||
let call = match self.m.imports.get(function_index as usize) {
|
||||
Some((name, _)) => format!("env::{name}(&mut m.mem{a})"),
|
||||
None => format!("f{function_index}(m{a})"),
|
||||
};
|
||||
self.call(&call, sig)?;
|
||||
}
|
||||
O::CallIndirect { type_index, .. } => {
|
||||
indirect.insert(type_index);
|
||||
let sig = &self.m.types[type_index as usize];
|
||||
let at = self.pop()?;
|
||||
let a = self.pop_args(sig.params.len())?;
|
||||
self.call(&format!("call_indirect_{type_index}(m, {at}{a})"), sig)?;
|
||||
}
|
||||
O::Drop => {
|
||||
self.pop()?;
|
||||
}
|
||||
O::Select | O::TypedSelect { .. } => {
|
||||
let t = self.top(1)?;
|
||||
let c = self.pop()?;
|
||||
let b = self.pop()?;
|
||||
let a = self.pop()?;
|
||||
let r = self.push(t);
|
||||
self.line(format!("{r} = if {c} != 0 {{ {a} }} else {{ {b} }};"));
|
||||
}
|
||||
O::LocalGet { local_index } => {
|
||||
let t = *self.locals.get(local_index as usize).ok_or("local index")?;
|
||||
let r = self.push(t);
|
||||
self.line(format!("{r} = l{local_index};"));
|
||||
}
|
||||
O::LocalSet { local_index } => {
|
||||
let a = self.pop()?;
|
||||
self.line(format!("l{local_index} = {a};"));
|
||||
}
|
||||
O::LocalTee { local_index } => {
|
||||
let t = self.top(0)?;
|
||||
let a = self.slot(self.stack.len() - 1, t);
|
||||
self.line(format!("l{local_index} = {a};"));
|
||||
}
|
||||
O::GlobalGet { global_index } => {
|
||||
let t = self.m.globals.get(global_index as usize).ok_or("global index")?.0;
|
||||
let r = self.push(t);
|
||||
self.line(format!("{r} = m.g{global_index};"));
|
||||
}
|
||||
O::GlobalSet { global_index } => {
|
||||
let a = self.pop()?;
|
||||
self.line(format!("m.g{global_index} = {a};"));
|
||||
}
|
||||
O::I32Load { memarg } => self.unop(Ty::I32, |a| format!("m.ld32({a}, {})", memarg.offset))?,
|
||||
O::I64Load { memarg } => self.unop(Ty::I64, |a| format!("m.ld64({a}, {})", memarg.offset))?,
|
||||
O::V128Load { memarg } => self.unop(Ty::V128, |a| format!("m.ld128({a}, {})", memarg.offset))?,
|
||||
O::I32Load8U { memarg } => self.unop(Ty::I32, |a| format!("m.ld8u({a}, {})", memarg.offset))?,
|
||||
O::I32Load16U { memarg } => self.unop(Ty::I32, |a| format!("m.ld16u({a}, {})", memarg.offset))?,
|
||||
O::I32Load16S { memarg } => self.unop(Ty::I32, |a| format!("m.ld16s({a}, {})", memarg.offset))?,
|
||||
O::I32Store { memarg } | O::I64Store { memarg } | O::V128Store { memarg } | O::I32Store8 { memarg } | O::I32Store16 { memarg } => {
|
||||
let name = match op {
|
||||
O::I32Store { .. } => "st32",
|
||||
O::I64Store { .. } => "st64",
|
||||
O::V128Store { .. } => "st128",
|
||||
O::I32Store8 { .. } => "st8",
|
||||
_ => "st16",
|
||||
};
|
||||
let v = self.pop()?;
|
||||
let a = self.pop()?;
|
||||
self.line(format!("m.{name}({a}, {}, {v});", memarg.offset));
|
||||
}
|
||||
O::MemorySize { .. } => {
|
||||
let r = self.push(Ty::I32);
|
||||
self.line(format!("{r} = (m.mem.len() / PAGE) as i32;"));
|
||||
}
|
||||
O::MemoryGrow { .. } => self.unop(Ty::I32, |a| format!("m.grow({a})"))?,
|
||||
O::MemoryCopy { .. } | O::MemoryFill { .. } => {
|
||||
let n = self.pop()?;
|
||||
let b = self.pop()?;
|
||||
let a = self.pop()?;
|
||||
let name = if matches!(op, O::MemoryCopy { .. }) { "copy" } else { "fill" };
|
||||
self.line(format!("m.{name}({a}, {b}, {n});"));
|
||||
}
|
||||
O::I32Const { value } => {
|
||||
let r = self.push(Ty::I32);
|
||||
self.line(format!("{r} = {value}i32;"));
|
||||
}
|
||||
O::I64Const { value } => {
|
||||
let r = self.push(Ty::I64);
|
||||
self.line(format!("{r} = {value}i64;"));
|
||||
}
|
||||
O::I32Eqz | O::I64Eqz => self.unop(Ty::I32, |a| format!("({a} == 0) as i32"))?,
|
||||
O::I32Clz => self.unop(Ty::I32, |a| format!("{a}.leading_zeros() as i32"))?,
|
||||
O::I32Ctz => self.unop(Ty::I32, |a| format!("{a}.trailing_zeros() as i32"))?,
|
||||
O::I32Popcnt => self.unop(Ty::I32, |a| format!("{a}.count_ones() as i32"))?,
|
||||
O::I32WrapI64 => self.unop(Ty::I32, |a| format!("{a} as i32"))?,
|
||||
O::I64ExtendI32U => self.unop(Ty::I64, |a| format!("{a} as u32 as i64"))?,
|
||||
O::I32Eq | O::I64Eq => self.binop(Ty::I32, |a, b| format!("({a} == {b}) as i32"))?,
|
||||
O::I32Ne | O::I64Ne => self.binop(Ty::I32, |a, b| format!("({a} != {b}) as i32"))?,
|
||||
O::I32LtS => self.binop(Ty::I32, |a, b| format!("({a} < {b}) as i32"))?,
|
||||
O::I32LtU => self.binop(Ty::I32, |a, b| format!("(({a} as u32) < ({b} as u32)) as i32"))?,
|
||||
O::I32GtS => self.binop(Ty::I32, |a, b| format!("({a} > {b}) as i32"))?,
|
||||
O::I32GtU => self.binop(Ty::I32, |a, b| format!("(({a} as u32) > ({b} as u32)) as i32"))?,
|
||||
O::I32LeS => self.binop(Ty::I32, |a, b| format!("({a} <= {b}) as i32"))?,
|
||||
O::I32LeU => self.binop(Ty::I32, |a, b| format!("(({a} as u32) <= ({b} as u32)) as i32"))?,
|
||||
O::I32GeS => self.binop(Ty::I32, |a, b| format!("({a} >= {b}) as i32"))?,
|
||||
O::I32GeU => self.binop(Ty::I32, |a, b| format!("(({a} as u32) >= ({b} as u32)) as i32"))?,
|
||||
O::I32Add | O::I64Add => self.binop(self.top(0)?, |a, b| format!("{a}.wrapping_add({b})"))?,
|
||||
O::I32Sub | O::I64Sub => self.binop(self.top(0)?, |a, b| format!("{a}.wrapping_sub({b})"))?,
|
||||
O::I32Mul | O::I64Mul => self.binop(self.top(0)?, |a, b| format!("{a}.wrapping_mul({b})"))?,
|
||||
O::I32And | O::I64And => self.binop(self.top(0)?, |a, b| format!("{a} & {b}"))?,
|
||||
O::I32Or | O::I64Or => self.binop(self.top(0)?, |a, b| format!("{a} | {b}"))?,
|
||||
O::I32Xor | O::I64Xor => self.binop(self.top(0)?, |a, b| format!("{a} ^ {b}"))?,
|
||||
O::I32Shl | O::I64Shl => self.binop(self.top(0)?, |a, b| format!("{a}.wrapping_shl({b} as u32)"))?,
|
||||
O::I32ShrS => self.binop(Ty::I32, |a, b| format!("{a}.wrapping_shr({b} as u32)"))?,
|
||||
O::I32ShrU => self.binop(Ty::I32, |a, b| format!("({a} as u32).wrapping_shr({b} as u32) as i32"))?,
|
||||
O::I64ShrU => self.binop(Ty::I64, |a, b| format!("({a} as u64).wrapping_shr({b} as u32) as i64"))?,
|
||||
O::I32Rotl => self.binop(Ty::I32, |a, b| format!("({a} as u32).rotate_left({b} as u32) as i32"))?,
|
||||
O::I64Rotl => self.binop(Ty::I64, |a, b| format!("({a} as u64).rotate_left({b} as u32) as i64"))?,
|
||||
O::I8x16Splat => self.unop(Ty::V128, |a| format!("[{a} as u8; 16]"))?,
|
||||
O::I8x16Bitmask => self.unop(Ty::I32, |a| format!("bitmask({a})"))?,
|
||||
O::V128AnyTrue => self.unop(Ty::I32, |a| format!("({a} != [0u8; 16]) as i32"))?,
|
||||
O::I8x16Eq => self.binop(Ty::V128, |a, b| format!("lanes({a}, {b}, |x, y| x == y)"))?,
|
||||
O::I8x16Ne => self.binop(Ty::V128, |a, b| format!("lanes({a}, {b}, |x, y| x != y)"))?,
|
||||
O::I8x16LeU => self.binop(Ty::V128, |a, b| format!("lanes({a}, {b}, |x, y| x <= y)"))?,
|
||||
O::I8x16GeU => self.binop(Ty::V128, |a, b| format!("lanes({a}, {b}, |x, y| x >= y)"))?,
|
||||
O::I8x16GtS => self.binop(Ty::V128, |a, b| format!("lanes({a}, {b}, |x, y| x as i8 > y as i8)"))?,
|
||||
O::I8x16Sub => self.binop(Ty::V128, |a, b| format!("map2({a}, {b}, u8::wrapping_sub)"))?,
|
||||
O::V128And => self.binop(Ty::V128, |a, b| format!("map2({a}, {b}, |x, y| x & y)"))?,
|
||||
O::V128Or => self.binop(Ty::V128, |a, b| format!("map2({a}, {b}, |x, y| x | y)"))?,
|
||||
O::V128Xor => self.binop(Ty::V128, |a, b| format!("map2({a}, {b}, |x, y| x ^ y)"))?,
|
||||
other => return Err(format!("unsupported instruction {other:?}")),
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! The module's imports: whether the UTF-8 character at `ptr` (`len` bytes) may start or
|
||||
//! continue an identifier, as JavaScript's `\p{ID_Start}` and `[\u200C\u200D\p{ID_Continue}]`
|
||||
//! answer in Highlights' own host.
|
||||
|
||||
/// `ID_Start` characters that `XID_Start` (what `unicode-ident` knows) leaves out.
|
||||
const ID_START_ONLY: &[u32] = &[
|
||||
0x037a, 0x0e33, 0x0eb3, 0x309b, 0x309c, 0xfc5e, 0xfc5f, 0xfc60, 0xfc61, 0xfc62, 0xfc63, 0xfdfa, 0xfdfb, 0xfe70,
|
||||
0xfe72, 0xfe74, 0xfe76, 0xfe78, 0xfe7a, 0xfe7c, 0xfe7e, 0xff9e, 0xff9f,
|
||||
];
|
||||
|
||||
/// `ID_Continue` characters that `XID_Continue` leaves out.
|
||||
const ID_CONTINUE_ONLY: &[u32] = &[
|
||||
0x037a, 0x309b, 0x309c, 0xfc5e, 0xfc5f, 0xfc60, 0xfc61, 0xfc62, 0xfc63, 0xfdfa, 0xfdfb, 0xfe70, 0xfe72, 0xfe74,
|
||||
0xfe76, 0xfe78, 0xfe7a, 0xfe7c, 0xfe7e,
|
||||
];
|
||||
|
||||
pub fn is_id_start(mem: &mut [u8], ptr: i32, len: i32) -> i32 {
|
||||
char_at(mem, ptr, len).is_some_and(|c| unicode_ident::is_xid_start(c) || ID_START_ONLY.contains(&(c as u32))) as i32
|
||||
}
|
||||
|
||||
pub fn is_id_continue(mem: &mut [u8], ptr: i32, len: i32) -> i32 {
|
||||
char_at(mem, ptr, len)
|
||||
.is_some_and(|c| matches!(c, '\u{200c}' | '\u{200d}') || unicode_ident::is_xid_continue(c) || ID_CONTINUE_ONLY.contains(&(c as u32)))
|
||||
as i32
|
||||
}
|
||||
|
||||
fn char_at(mem: &[u8], ptr: i32, len: i32) -> Option<char> {
|
||||
let at = ptr as u32 as usize;
|
||||
std::str::from_utf8(mem.get(at..at + len as u32 as usize)?).ok()?.chars().next()
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Highlights' language names and token types, from `languages.js` and `token-types.js` in
|
||||
//! `@pierre/highlights` 0.2.0.
|
||||
|
||||
/// Every name and alias Highlights accepts (lowercase), sorted, with its lexer's id.
|
||||
pub(crate) const ALIASES: [(&str, u8); 211] = [
|
||||
("angular-html", 1), ("angular-ts", 72), ("asm", 2), ("assembly", 2), ("astro", 3), ("bash", 4),
|
||||
("bat", 5), ("batch", 5), ("batchfile", 5), ("c", 6), ("c#", 11), ("c++", 10),
|
||||
("c3", 7), ("cc", 10), ("cjs", 35), ("cl", 44), ("clj", 8), ("cljc", 8),
|
||||
("cljs", 8), ("clojure", 8), ("cmake", 9), ("cmd", 5), ("comp", 27), ("containerfile", 16),
|
||||
("cpp", 10), ("cs", 11), ("csharp", 11), ("css", 12), ("cts", 72), ("cu", 13),
|
||||
("cuda", 13), ("cuh", 13), ("cxx", 10), ("dart", 14), ("delphi", 54), ("diff", 15),
|
||||
("docker", 16), ("dockerfile", 16), ("dos", 5), ("dpk", 54), ("dpr", 54), ("edn", 8),
|
||||
("el", 44), ("elisp", 44), ("elixir", 17), ("elm", 18), ("emacs-lisp", 44), ("erl", 19),
|
||||
("erlang", 19), ("ex", 17), ("exs", 17), ("f", 21), ("f#", 22), ("f03", 20),
|
||||
("f08", 20), ("f77", 21), ("f90", 20), ("f95", 20), ("for", 21), ("fortran", 20),
|
||||
("fortran-fixed-form", 21), ("fortran-free-form", 20), ("frag", 27), ("fs", 22), ("fsharp", 22), ("fsi", 22),
|
||||
("fsx", 22), ("gd", 24), ("gdresource", 23), ("gdscript", 24), ("gdshader", 25), ("gdshaderinc", 25),
|
||||
("geom", 27), ("git-commit", 15), ("git-rebase", 15), ("gleam", 26), ("glsl", 27), ("go", 28),
|
||||
("godot-resource", 23), ("godot-shader", 25), ("golang", 28), ("gql", 29), ("gradle", 30), ("graphql", 29),
|
||||
("groovy", 30), ("gsh", 30), ("gvy", 30), ("gy", 30), ("h", 6), ("haskell", 31),
|
||||
("hcl", 70), ("hh", 10), ("hlsl", 32), ("hpp", 10), ("hrl", 19), ("hs", 31),
|
||||
("htm", 33), ("html", 33), ("hxx", 10), ("java", 34), ("javascript", 35), ("jl", 40),
|
||||
("js", 35), ("json", 36), ("json5", 37), ("jsonc", 36), ("jsonl", 38), ("jsx", 39),
|
||||
("julia", 40), ("kotlin", 41), ("kt", 41), ("kts", 41), ("latex", 42), ("less", 43),
|
||||
("lisp", 44), ("lpr", 54), ("lsp", 44), ("lua", 45), ("m", 52), ("make", 46),
|
||||
("makefile", 46), ("markdown", 47), ("matlab", 48), ("md", 47), ("mdx", 49), ("mjs", 35),
|
||||
("mk", 46), ("ml", 53), ("mli", 53), ("mm", 52), ("mts", 72), ("nim", 50),
|
||||
("nix", 51), ("objc", 52), ("objcpp", 52), ("object-pascal", 54), ("objective-c", 52), ("objective-cpp", 52),
|
||||
("objectivec", 52), ("objectpascal", 54), ("ocaml", 53), ("octave", 48), ("pas", 54), ("pascal", 54),
|
||||
("patch", 15), ("perl", 55), ("php", 56), ("pl", 55), ("plain", 0), ("plaintext", 0),
|
||||
("pm", 55), ("powershell", 57), ("pp", 54), ("proto", 58), ("protobuf", 58), ("ps", 57),
|
||||
("ps1", 57), ("psd1", 57), ("psm1", 57), ("pwsh", 57), ("py", 59), ("python", 59),
|
||||
("r", 60), ("rb", 61), ("rs", 62), ("rscript", 60), ("ruby", 61), ("rust", 62),
|
||||
("s", 2), ("sass", 63), ("sbt", 64), ("sc", 64), ("scala", 64), ("scheme", 44),
|
||||
("scm", 44), ("scss", 65), ("sh", 4), ("shell", 4), ("shellscript", 4), ("shellsession", 4),
|
||||
("sol", 66), ("solidity", 66), ("sql", 67), ("svelte", 68), ("svg", 78), ("swift", 69),
|
||||
("terraform", 70), ("tex", 42), ("text", 0), ("tf", 70), ("tfvars", 70), ("toml", 71),
|
||||
("tres", 23), ("ts", 72), ("tscn", 23), ("tsrx", 73), ("tsx", 74), ("txt", 0),
|
||||
("typescript", 72), ("vert", 27), ("vue", 75), ("wasm", 76), ("wat", 76), ("wgsl", 77),
|
||||
("xml", 78), ("xsd", 78), ("yaml", 79), ("yml", 79), ("zig", 80), ("zon", 80),
|
||||
("zsh", 4),
|
||||
];
|
||||
|
||||
/// Each lexer's name, by id.
|
||||
pub(crate) const NAMES: [&str; 81] = [
|
||||
"plain", "angular-html", "asm", "astro", "bash", "bat", "c", "c3",
|
||||
"clojure", "cmake", "cpp", "csharp", "css", "cuda", "dart", "diff",
|
||||
"dockerfile", "elixir", "elm", "erlang", "fortran", "fortran-fixed-form", "fsharp", "gdresource",
|
||||
"gdscript", "gdshader", "gleam", "glsl", "go", "graphql", "groovy", "haskell",
|
||||
"hlsl", "html", "java", "javascript", "json", "json5", "jsonl", "jsx",
|
||||
"julia", "kotlin", "latex", "less", "lisp", "lua", "makefile", "markdown",
|
||||
"matlab", "mdx", "nim", "nix", "objective-c", "ocaml", "pascal", "perl",
|
||||
"php", "powershell", "proto", "python", "r", "ruby", "rust", "sass",
|
||||
"scala", "scss", "solidity", "sql", "svelte", "swift", "terraform", "toml",
|
||||
"typescript", "tsrx", "tsx", "vue", "wasm", "wgsl", "xml", "yaml",
|
||||
"zig",
|
||||
];
|
||||
|
||||
/// Each token type's Zed capture name, by id.
|
||||
pub(crate) const TOKENS: [&str; 73] = [
|
||||
"none", "attribute", "attribute.jsx", "boolean", "comment", "comment.doc",
|
||||
"constant", "constant.builtin", "constructor", "diff.minus", "diff.plus", "embedded",
|
||||
"emphasis", "emphasis.strong", "function", "function.definition", "function.method", "keyword",
|
||||
"keyword.control", "keyword.declaration", "keyword.import", "keyword.operator", "label", "namespace",
|
||||
"number", "operator", "predictive", "preproc", "primary", "property",
|
||||
"property.json_key", "punctuation", "punctuation.bracket", "punctuation.bracket.html", "punctuation.bracket.jsx", "punctuation.delimiter",
|
||||
"punctuation.delimiter.html", "punctuation.delimiter.jsx", "punctuation.list_marker", "punctuation.markup", "punctuation.special", "selector",
|
||||
"selector.class", "selector.id", "string", "string.escape", "string.regex", "string.special",
|
||||
"string.special.symbol", "tag", "tag.doctype", "tag.jsx", "text.jsx", "text.literal",
|
||||
"title", "type", "type.builtin", "type.class", "variable", "variable.parameter",
|
||||
"variable.special", "enum", "hint", "keyword.jsdoc", "link_text", "link_uri",
|
||||
"selector.pseudo", "tag.component.jsx", "type.jsdoc", "variable.jsdoc", "variant", "background",
|
||||
"foreground",
|
||||
];
|
||||
+286
@@ -0,0 +1,286 @@
|
||||
//! Pierre's Highlights, the code highlighter OpenCode's desktop app colours diffs, files and
|
||||
//! Markdown with (`@pierre/highlights`, Apache-2.0), as Rust.
|
||||
//!
|
||||
//! Highlights is a set of hand-written lexers, one per language (80 of them), shipped as one
|
||||
//! WebAssembly module. `build.rs` translates that module, `vendor/highlights.wasm`, to Rust at
|
||||
//! build time: the same lexers run natively, with no WebAssembly runtime, on every target Rune
|
||||
//! builds for (web included), and give the very tokens the desktop app draws.
|
||||
//!
|
||||
//! ```
|
||||
//! use rune_highlights::{Highlighter, Lang};
|
||||
//! let mut h = Highlighter::new();
|
||||
//! let lang = Lang::from_name("kotlin").unwrap();
|
||||
//! for (range, token) in h.highlight(lang, "val x = 1") {
|
||||
//! println!("{range:?} {}", token.name()); // 0..4 keyword, ...
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! Token types are Zed's capture names (`keyword.control`, `string.escape`); a theme colours a
|
||||
//! name or, failing that, its parent (`keyword`).
|
||||
//!
|
||||
//! **Cost.** About 0.1 to 0.6 ms per thousand lines in an optimised build, linear in the
|
||||
//! source, and the module's memory (three 64 KiB pages, plus room for the source and its
|
||||
//! tokens) per [`Highlighter`].
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod env;
|
||||
mod langs;
|
||||
mod rt;
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/highlights.rs"));
|
||||
|
||||
use std::ops::Range;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
|
||||
use rt::PAGE;
|
||||
|
||||
/// A language Highlights lexes, or [`Lang::PLAIN`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Lang(u8);
|
||||
|
||||
impl Lang {
|
||||
/// Text without a lexer: no tokens.
|
||||
pub const PLAIN: Lang = Lang(0);
|
||||
|
||||
/// The language `name` names, ignoring ASCII case: Highlights' names and aliases (`ts`,
|
||||
/// `typescript`, `c++`, `dockerfile`, `text`), as its `isSupportedLanguage` accepts them.
|
||||
pub fn from_name(name: &str) -> Option<Lang> {
|
||||
let name = name.to_ascii_lowercase();
|
||||
langs::ALIASES.binary_search_by(|(k, _)| (*k).cmp(name.as_str())).ok().map(|i| Lang(langs::ALIASES[i].1))
|
||||
}
|
||||
|
||||
/// The language's main name (`typescript`, `cpp`, `plain`).
|
||||
pub fn name(self) -> &'static str {
|
||||
langs::NAMES[self.0 as usize]
|
||||
}
|
||||
|
||||
/// Every language with a lexer, in Highlights' order.
|
||||
pub fn all() -> impl Iterator<Item = Lang> {
|
||||
(1..langs::NAMES.len() as u8).map(Lang)
|
||||
}
|
||||
|
||||
/// Every name and alias of a language with a lexer, with its language.
|
||||
pub fn aliases() -> impl Iterator<Item = (&'static str, Lang)> {
|
||||
langs::ALIASES.iter().filter(|(_, l)| *l != 0).map(|&(k, l)| (k, Lang(l)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A token type: one of Highlights' Zed capture names.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct Token(u8);
|
||||
|
||||
impl Token {
|
||||
/// Text no lexer rule matched; [`Highlighter::highlight`] leaves it out.
|
||||
pub const NONE: Token = Token(0);
|
||||
/// How many token types there are, [`Token::NONE`] included.
|
||||
pub const COUNT: usize = langs::TOKENS.len();
|
||||
|
||||
/// Zed's capture name (`keyword.control`, `punctuation.bracket`).
|
||||
pub fn name(self) -> &'static str {
|
||||
langs::TOKENS[self.0 as usize]
|
||||
}
|
||||
|
||||
/// Its index in [`Token::all`], below [`Token::COUNT`].
|
||||
pub fn index(self) -> usize {
|
||||
self.0 as usize
|
||||
}
|
||||
|
||||
pub fn from_name(name: &str) -> Option<Token> {
|
||||
langs::TOKENS.iter().position(|t| *t == name).map(|i| Token(i as u8))
|
||||
}
|
||||
|
||||
pub fn all() -> impl Iterator<Item = Token> {
|
||||
(0..Self::COUNT as u8).map(Token)
|
||||
}
|
||||
}
|
||||
|
||||
/// One instance of the lexers: their memory, reused from call to call. Not shared between
|
||||
/// threads; make one per thread.
|
||||
pub struct Highlighter {
|
||||
wasm: Wasm,
|
||||
}
|
||||
|
||||
/// Memory a highlighter keeps after a large source; past this it starts over, as Highlights'
|
||||
/// own host does.
|
||||
const KEEP_PAGES: usize = 128;
|
||||
|
||||
/// Where the source starts in the module's memory, and the room it needs after its end.
|
||||
const INPUT: usize = PAGE;
|
||||
const SLACK: usize = 96;
|
||||
|
||||
/// Output mode 3: (UTF-16 end, token type) records per run, `u32::MAX` types marking where
|
||||
/// each next line starts.
|
||||
const RECORDS: u8 = 3;
|
||||
|
||||
impl Highlighter {
|
||||
pub fn new() -> Highlighter {
|
||||
Highlighter { wasm: Wasm::new() }
|
||||
}
|
||||
|
||||
/// `src`'s tokens as `lang` lexes them: byte ranges in order, not overlapping, without the
|
||||
/// runs no rule matched ([`Token::NONE`]) and without line ends. Empty for
|
||||
/// [`Lang::PLAIN`].
|
||||
pub fn highlight(&mut self, lang: Lang, src: &str) -> Vec<(Range<usize>, Token)> {
|
||||
if lang == Lang::PLAIN || src.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let records = catch_unwind(AssertUnwindSafe(|| self.records(lang, src)));
|
||||
if self.wasm.mem.len() > KEEP_PAGES * PAGE {
|
||||
self.wasm = Wasm::new();
|
||||
}
|
||||
match records {
|
||||
Ok(r) => runs(src, &r),
|
||||
// A trap is a bug in the lexers; the code draws plain rather than taking the app down.
|
||||
Err(_) => {
|
||||
self.wasm = Wasm::new();
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn records(&mut self, lang: Lang, src: &str) -> Vec<u32> {
|
||||
records(&mut self.wasm, lang, src, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Highlighter {
|
||||
fn default() -> Highlighter {
|
||||
Highlighter::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Lexes a source that grows at its end, such as a code block streaming in: each call lexes
|
||||
/// only the lines after those an earlier call lexed, carrying the lexer's state over, as
|
||||
/// Highlights' own `StreamTokenizer` does. The tokens are the same as [`Highlighter::highlight`]
|
||||
/// gives for the whole source.
|
||||
pub struct Stream {
|
||||
lang: Lang,
|
||||
/// The lexers' state after `text`.
|
||||
wasm: Wasm,
|
||||
/// The lines lexed so far, each with its line end.
|
||||
text: String,
|
||||
runs: Vec<(Range<usize>, Token)>,
|
||||
/// Where the last line, still without its line end, is lexed from a copy of `wasm`.
|
||||
tail: Option<Box<Wasm>>,
|
||||
}
|
||||
|
||||
impl Stream {
|
||||
pub fn new(lang: Lang) -> Stream {
|
||||
Stream { lang, wasm: Wasm::new(), text: String::new(), runs: Vec::new(), tail: None }
|
||||
}
|
||||
|
||||
pub fn lang(&self) -> Lang {
|
||||
self.lang
|
||||
}
|
||||
|
||||
/// Whether `src` extends what this stream has lexed, so [`highlight`](Self::highlight)
|
||||
/// lexes only what it adds.
|
||||
pub fn continues(&self, src: &str) -> bool {
|
||||
!self.text.is_empty() && src.starts_with(&self.text)
|
||||
}
|
||||
|
||||
/// `src`'s tokens, as [`Highlighter::highlight`] gives them. When `src` doesn't extend the
|
||||
/// source of earlier calls, the stream starts over.
|
||||
pub fn highlight(&mut self, src: &str) -> Vec<(Range<usize>, Token)> {
|
||||
if self.lang == Lang::PLAIN {
|
||||
return Vec::new();
|
||||
}
|
||||
match catch_unwind(AssertUnwindSafe(|| self.lex(src))) {
|
||||
Ok(runs) => runs,
|
||||
Err(_) => {
|
||||
*self = Stream::new(self.lang);
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lex(&mut self, src: &str) -> Vec<(Range<usize>, Token)> {
|
||||
if !self.continues(src) {
|
||||
self.wasm = Wasm::new();
|
||||
self.text.clear();
|
||||
self.runs.clear();
|
||||
}
|
||||
let lines = src.rfind('\n').map_or(0, |i| i + 1);
|
||||
if lines > self.text.len() {
|
||||
let (at, chunk) = (self.text.len(), &src[self.text.len()..lines]);
|
||||
let r = records(&mut self.wasm, self.lang, chunk, Some(at == 0));
|
||||
self.runs.extend(runs(chunk, &r).into_iter().map(|(range, t)| (range.start + at..range.end + at, t)));
|
||||
self.text.push_str(chunk);
|
||||
}
|
||||
let mut out = self.runs.clone();
|
||||
if lines < src.len() {
|
||||
let tail = self.tail.get_or_insert_with(|| Box::new(self.wasm.clone()));
|
||||
(**tail).clone_from(&self.wasm);
|
||||
let chunk = &src[lines..];
|
||||
let r = records(tail, self.lang, chunk, Some(lines == 0));
|
||||
out.extend(runs(chunk, &r).into_iter().map(|(range, t)| (range.start + lines..range.end + lines, t)));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `src` through the module in output mode [`RECORDS`]: whole (`stream: None`), or as the
|
||||
/// next chunk of a stream (`Some(true)` for its first), and returns the records.
|
||||
fn records(w: &mut Wasm, lang: Lang, src: &str, stream: Option<bool>) -> Vec<u32> {
|
||||
let len = src.len();
|
||||
let need = (1 + (len + SLACK).div_ceil(PAGE)) * PAGE;
|
||||
if w.mem.len() < need {
|
||||
w.mem.resize(need, 0);
|
||||
}
|
||||
w.mem[INPUT..INPUT + len].copy_from_slice(src.as_bytes());
|
||||
w.mem[INPUT + len] = 0;
|
||||
w.mem[0] = lang.0;
|
||||
w.mem[1] = RECORDS;
|
||||
w.mem[2..6].copy_from_slice(&(len as u32).to_le_bytes());
|
||||
match stream {
|
||||
None => w.highlight(),
|
||||
Some(first) => w.highlight_stream(first as i32),
|
||||
}
|
||||
let word = |at: usize| u32::from_le_bytes([w.mem[at], w.mem[at + 1], w.mem[at + 2], w.mem[at + 3]]) as usize;
|
||||
let (at, n) = (word(6), word(10));
|
||||
w.mem[at..at + n].chunks_exact(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect()
|
||||
}
|
||||
|
||||
/// The records' runs as byte ranges of `src`, typed runs only.
|
||||
fn runs(src: &str, records: &[u32]) -> Vec<(Range<usize>, Token)> {
|
||||
let mut out = Vec::with_capacity(records.len() / 2);
|
||||
let mut cursor = Utf16Cursor { src, byte: 0, unit: 0 };
|
||||
let mut start = 0usize;
|
||||
for pair in records.chunks_exact(2) {
|
||||
let (end, ty) = (pair[0] as usize, pair[1]);
|
||||
if ty == u32::MAX {
|
||||
start = cursor.byte_at(end);
|
||||
continue;
|
||||
}
|
||||
let end = cursor.byte_at(end);
|
||||
if ty != 0 && end > start && (ty as usize) < Token::COUNT {
|
||||
out.push((start..end, Token(ty as u8)));
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Walks `src` forward, turning UTF-16 offsets into byte offsets.
|
||||
struct Utf16Cursor<'a> {
|
||||
src: &'a str,
|
||||
byte: usize,
|
||||
unit: usize,
|
||||
}
|
||||
|
||||
impl Utf16Cursor<'_> {
|
||||
fn byte_at(&mut self, unit: usize) -> usize {
|
||||
if unit < self.unit {
|
||||
*self = Utf16Cursor { src: self.src, byte: 0, unit: 0 };
|
||||
}
|
||||
for c in self.src[self.byte..].chars() {
|
||||
if self.unit >= unit {
|
||||
break;
|
||||
}
|
||||
self.unit += c.len_utf16();
|
||||
self.byte += c.len_utf8();
|
||||
}
|
||||
self.byte
|
||||
}
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
//! What the translated module calls: little-endian memory access, `memory.grow`, `memory.copy`
|
||||
//! and `memory.fill`, and the `i8x16` lanes. A trap (an access out of bounds, an
|
||||
//! `unreachable`) panics, which [`Highlighter`](crate::Highlighter) turns into no highlights.
|
||||
|
||||
pub type V128 = [u8; 16];
|
||||
|
||||
/// WebAssembly's page size.
|
||||
pub const PAGE: usize = 65536;
|
||||
|
||||
/// Pages a module may grow to (wasm32's 4 GiB).
|
||||
const MAX_PAGES: usize = 65536;
|
||||
|
||||
#[cold]
|
||||
#[inline(never)]
|
||||
pub fn trap() -> ! {
|
||||
panic!("highlights: wasm trap")
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn bitmask(v: V128) -> i32 {
|
||||
v.iter().enumerate().fold(0, |r, (i, b)| r | (((b >> 7) as i32) << i))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn lanes(a: V128, b: V128, f: impl Fn(u8, u8) -> bool) -> V128 {
|
||||
std::array::from_fn(|i| if f(a[i], b[i]) { 0xff } else { 0 })
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn map2(a: V128, b: V128, f: impl Fn(u8, u8) -> u8) -> V128 {
|
||||
std::array::from_fn(|i| f(a[i], b[i]))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn at(addr: i32, offset: u64) -> usize {
|
||||
addr as u32 as usize + offset as usize
|
||||
}
|
||||
|
||||
/// `N` bytes of memory at `at`. Out of bounds traps: one cold call per access rather than an
|
||||
/// inlined panic with its own location, which would double the code's size.
|
||||
#[inline(always)]
|
||||
fn read<const N: usize>(mem: &[u8], at: usize) -> [u8; N] {
|
||||
let mut b = [0u8; N];
|
||||
b.copy_from_slice(mem.get(at..at + N).unwrap_or_else(|| trap()));
|
||||
b
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn write<const N: usize>(mem: &mut [u8], at: usize, v: [u8; N]) {
|
||||
mem.get_mut(at..at + N).unwrap_or_else(|| trap()).copy_from_slice(&v);
|
||||
}
|
||||
|
||||
impl super::Wasm {
|
||||
#[inline(always)]
|
||||
pub fn ld8u(&self, a: i32, off: u64) -> i32 {
|
||||
read::<1>(&self.mem, at(a, off))[0] as i32
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn ld16u(&self, a: i32, off: u64) -> i32 {
|
||||
u16::from_le_bytes(read(&self.mem, at(a, off))) as i32
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn ld16s(&self, a: i32, off: u64) -> i32 {
|
||||
i16::from_le_bytes(read(&self.mem, at(a, off))) as i32
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn ld32(&self, a: i32, off: u64) -> i32 {
|
||||
i32::from_le_bytes(read(&self.mem, at(a, off)))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn ld64(&self, a: i32, off: u64) -> i64 {
|
||||
i64::from_le_bytes(read(&self.mem, at(a, off)))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn ld128(&self, a: i32, off: u64) -> V128 {
|
||||
read(&self.mem, at(a, off))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn st8(&mut self, a: i32, off: u64, v: i32) {
|
||||
write(&mut self.mem, at(a, off), [v as u8]);
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn st16(&mut self, a: i32, off: u64, v: i32) {
|
||||
write(&mut self.mem, at(a, off), (v as u16).to_le_bytes());
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn st32(&mut self, a: i32, off: u64, v: i32) {
|
||||
write(&mut self.mem, at(a, off), v.to_le_bytes());
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn st64(&mut self, a: i32, off: u64, v: i64) {
|
||||
write(&mut self.mem, at(a, off), v.to_le_bytes());
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn st128(&mut self, a: i32, off: u64, v: V128) {
|
||||
write(&mut self.mem, at(a, off), v);
|
||||
}
|
||||
|
||||
/// `memory.grow`: the old size in pages, or -1.
|
||||
pub fn grow(&mut self, pages: i32) -> i32 {
|
||||
let old = self.mem.len() / PAGE;
|
||||
let new = old + pages as u32 as usize;
|
||||
if new > MAX_PAGES {
|
||||
return -1;
|
||||
}
|
||||
self.mem.resize(new * PAGE, 0);
|
||||
old as i32
|
||||
}
|
||||
|
||||
pub fn copy(&mut self, dst: i32, src: i32, n: i32) {
|
||||
let (d, s, n) = (dst as u32 as usize, src as u32 as usize, n as u32 as usize);
|
||||
if d.max(s) + n > self.mem.len() {
|
||||
trap();
|
||||
}
|
||||
self.mem.copy_within(s..s + n, d);
|
||||
}
|
||||
|
||||
pub fn fill(&mut self, dst: i32, v: i32, n: i32) {
|
||||
let (d, n) = (dst as u32 as usize, n as u32 as usize);
|
||||
self.mem.get_mut(d..d + n).unwrap_or_else(|| trap()).fill(v as u8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and
|
||||
distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the
|
||||
copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other
|
||||
entities that control, are controlled by, or are under common control with
|
||||
that entity. For the purposes of this definition, "control" means (i) the
|
||||
power, direct or indirect, to cause the direction or management of such
|
||||
entity, whether by contract or otherwise, or (ii) ownership of fifty percent
|
||||
(50%) or more of the outstanding shares, or (iii) beneficial ownership of
|
||||
such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
||||
permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation source, and
|
||||
configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation
|
||||
or translation of a Source form, including but not limited to compiled
|
||||
object code, generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form,
|
||||
made available under the License, as indicated by a copyright notice that is
|
||||
included in or attached to the work (an example is provided in the Appendix
|
||||
below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form,
|
||||
that is based on (or derived from) the Work and for which the editorial
|
||||
revisions, annotations, elaborations, or other modifications represent, as a
|
||||
whole, an original work of authorship. For the purposes of this License,
|
||||
Derivative Works shall not include works that remain separable from, or
|
||||
merely link (or bind by name) to the interfaces of, the Work and Derivative
|
||||
Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original
|
||||
version of the Work and any modifications or additions to that Work or
|
||||
Derivative Works thereof, that is intentionally submitted to Licensor for
|
||||
inclusion in the Work by the copyright owner or by an individual or Legal
|
||||
Entity authorized to submit on behalf of the copyright owner. For the
|
||||
purposes of this definition, "submitted" means any form of electronic,
|
||||
verbal, or written communication sent to the Licensor or its
|
||||
representatives, including but not limited to communication on electronic
|
||||
mailing lists, source code control systems, and issue tracking systems that
|
||||
are managed by, or on behalf of, the Licensor for the purpose of discussing
|
||||
and improving the Work, but excluding communication that is conspicuously
|
||||
marked or otherwise designated in writing by the copyright owner as "Not a
|
||||
Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on
|
||||
behalf of whom a Contribution has been received by Licensor and subsequently
|
||||
incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of this
|
||||
License, each Contributor hereby grants to You a perpetual, worldwide,
|
||||
non-exclusive, no-charge, royalty-free, irrevocable copyright license to
|
||||
reproduce, prepare Derivative Works of, publicly display, publicly perform,
|
||||
sublicense, and distribute the Work and such Derivative Works in Source or
|
||||
Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of this
|
||||
License, each Contributor hereby grants to You a perpetual, worldwide,
|
||||
non-exclusive, no-charge, royalty-free, irrevocable (except as stated in
|
||||
this section) patent license to make, have made, use, offer to sell, sell,
|
||||
import, and otherwise transfer the Work, where such license applies only to
|
||||
those patent claims licensable by such Contributor that are necessarily
|
||||
infringed by their Contribution(s) alone or by combination of their
|
||||
Contribution(s) with the Work to which such Contribution(s) was submitted.
|
||||
If You institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
||||
Contribution incorporated within the Work constitutes direct or contributory
|
||||
patent infringement, then any patent licenses granted to You under this
|
||||
License for that Work shall terminate as of the date such litigation is
|
||||
filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the Work or
|
||||
Derivative Works thereof in any medium, with or without modifications, and
|
||||
in Source or Object form, provided that You meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative Works a
|
||||
copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices stating
|
||||
that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works that You
|
||||
distribute, all copyright, patent, trademark, and attribution notices from
|
||||
the Source form of the Work, excluding those notices that do not pertain to
|
||||
any part of the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its distribution,
|
||||
then any Derivative Works that You distribute must include a readable copy
|
||||
of the attribution notices contained within such NOTICE file, excluding
|
||||
those notices that do not pertain to any part of the Derivative Works, in at
|
||||
least one of the following places: within a NOTICE text file distributed as
|
||||
part of the Derivative Works; within the Source form or documentation, if
|
||||
provided along with the Derivative Works; or, within a display generated by
|
||||
the Derivative Works, if and wherever such third-party notices normally
|
||||
appear. The contents of the NOTICE file are for informational purposes only
|
||||
and do not modify the License. You may add Your own attribution notices
|
||||
within Derivative Works that You distribute, alongside or as an addendum to
|
||||
the NOTICE text from the Work, provided that such additional attribution
|
||||
notices cannot be construed as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and may
|
||||
provide additional or different license terms and conditions for use,
|
||||
reproduction, or distribution of Your modifications, or for any such
|
||||
Derivative Works as a whole, provided Your use, reproduction, and
|
||||
distribution of the Work otherwise complies with the conditions stated in
|
||||
this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise, any
|
||||
Contribution intentionally submitted for inclusion in the Work by You to the
|
||||
Licensor shall be under the terms and conditions of this License, without
|
||||
any additional terms or conditions. Notwithstanding the above, nothing
|
||||
herein shall supersede or modify the terms of any separate license agreement
|
||||
you may have executed with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade names,
|
||||
trademarks, service marks, or product names of the Licensor, except as
|
||||
required for reasonable and customary use in describing the origin of the
|
||||
Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
|
||||
writing, Licensor provides the Work (and each Contributor provides its
|
||||
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied, including, without limitation, any
|
||||
warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or
|
||||
FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining
|
||||
the appropriateness of using or redistributing the Work and assume any risks
|
||||
associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory, whether in
|
||||
tort (including negligence), contract, or otherwise, unless required by
|
||||
applicable law (such as deliberate and grossly negligent acts) or agreed to
|
||||
in writing, shall any Contributor be liable to You for damages, including
|
||||
any direct, indirect, special, incidental, or consequential damages of any
|
||||
character arising as a result of this License or out of the use or inability
|
||||
to use the Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all other
|
||||
commercial damages or losses), even if such Contributor has been advised of
|
||||
the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or
|
||||
Derivative Works thereof, You may choose to offer, and charge a fee for,
|
||||
acceptance of support, warranty, indemnity, or other liability obligations
|
||||
and/or rights consistent with this License. However, in accepting such
|
||||
obligations, You may act only on Your own behalf and on Your sole
|
||||
responsibility, not on behalf of any other Contributor, and only if You
|
||||
agree to indemnify, defend, and hold each Contributor harmless for any
|
||||
liability incurred by, or claims asserted against, such Contributor by
|
||||
reason of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2025 Pierre Computer Company
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
||||
this file except in compliance with the License. You may obtain a copy of the
|
||||
License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software distributed
|
||||
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations under the License.
|
||||
@@ -0,0 +1,6 @@
|
||||
# Vendored Highlights
|
||||
|
||||
- `highlights.wasm`: `dist/highlights.wasm` from the npm package `@pierre/highlights` 0.2.0, unchanged. SHA-256 `cf5fc4d83e7c1ddab19d163de096f787f87efe61504909aa469434f61ef51e2e`.
|
||||
- `LICENSE.md`: that package's license, Apache-2.0.
|
||||
|
||||
`build.rs` translates the module to Rust; `src/langs.rs` copies the package's `languages.js` (names and aliases) and `token-types.js` (Zed capture names). To update, replace both with a new release's, check `Lang` and `Token` against the new lists, and build: an instruction the translator doesn't know fails the build and names it.
|
||||
Binary file not shown.
Reference in new issue
Block a user