diff --git a/Cargo.lock b/Cargo.lock index d594fe0..1498c16 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,16 +23,6 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" -[[package]] -name = "cc" -version = "1.2.66" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996" -dependencies = [ - "find-msvc-tools", - "shlex", -] - [[package]] name = "cfg-if" version = "1.0.4" @@ -92,8 +82,6 @@ version = "0.1.3" dependencies = [ "decodal", "serde_json", - "tree-sitter", - "tree-sitter-decodal", "wasm-bindgen", ] @@ -121,12 +109,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "find-msvc-tools" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" - [[package]] name = "fluent-uri" version = "0.1.4" @@ -345,12 +327,6 @@ dependencies = [ "syn 3.0.3", ] -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - [[package]] name = "slab" version = "0.4.12" @@ -379,24 +355,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "tree-sitter" -version = "0.22.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df7cc499ceadd4dcdf7ec6d4cbc34ece92c3fa07821e287aedecd4416c516dca" -dependencies = [ - "cc", - "regex", -] - -[[package]] -name = "tree-sitter-decodal" -version = "0.1.0" -dependencies = [ - "cc", - "tree-sitter", -] - [[package]] name = "unicode-ident" version = "1.0.24" diff --git a/Cargo.toml b/Cargo.toml index c112d35..051d418 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,8 +7,8 @@ members = [ "crates/decodal-language-tools", "crates/decodal-language-service", "crates/decodal-lsp", - "editors/tree-sitter-decodal", ] +exclude = ["editors/tree-sitter-decodal"] resolver = "2" [workspace.package] diff --git a/RELEASING.md b/RELEASING.md index f29fcd0..9b7defb 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -5,22 +5,27 @@ Run all commands from the repository root. Publishing requires Cargo, npm, and J ## Versions - Rust crates: `0.1.3` -- `tree-sitter-decodal`: `0.1.0` - `decodal-wasm` npm/JSR package: `0.1.4` -- `decodal-codemirror`: unchanged at `0.1.5` +- `decodal-codemirror`: `0.1.6` ## Validate ```sh +cargo fmt --check cargo test --workspace +cargo test -p decodal --no-default-features cargo clippy --workspace --all-targets -- -D warnings cargo clippy -p decodal-wasm --target wasm32-unknown-unknown -- -D warnings -npm --prefix site/decodal-site run build:runtime +cargo clippy -p decodal-language-tools --target wasm32-unknown-unknown -- -D warnings +npm --prefix site/decodal-site run build:wasm +npm --prefix packages/decodal-codemirror test npm --prefix site/decodal-site test npm --prefix site/decodal-site run build deno check packages/decodal-wasm/mod.ts npm pack --dry-run ./packages/decodal-wasm deno publish --dry-run --config packages/decodal-wasm/jsr.json +npm pack --dry-run ./packages/decodal-codemirror +deno publish --dry-run --config packages/decodal-codemirror/jsr.json ``` ## Publish Rust crates @@ -31,7 +36,6 @@ Run the corresponding command with `--dry-run` immediately before each real publ ```sh cargo publish -p decodal-derive cargo publish -p decodal -cargo publish -p tree-sitter-decodal cargo publish -p decodal-language-service cargo publish -p decodal-language-tools cargo publish -p decodal-lsp @@ -41,12 +45,14 @@ cargo publish -p decodal-lsp ## Publish JavaScript packages -The runtime build regenerates and normalizes the committed npm/JSR package before publishing. +The WASM build regenerates and normalizes both committed npm/JSR packages before publishing. ```sh -npm --prefix site/decodal-site run build:runtime +npm --prefix site/decodal-site run build:wasm npm publish ./packages/decodal-wasm deno publish --config packages/decodal-wasm/jsr.json +npm publish ./packages/decodal-codemirror +deno publish --config packages/decodal-codemirror/jsr.json ``` After both registries accept the release, tag the release commit and update the deployed site. diff --git a/crates/decodal-core/src/ast.rs b/crates/decodal-core/src/ast.rs index 8551427..db5177d 100644 --- a/crates/decodal-core/src/ast.rs +++ b/crates/decodal-core/src/ast.rs @@ -70,6 +70,13 @@ pub enum Expr { params: Vec, body: ExprId, }, + /// An explicitly parenthesized expression. + /// + /// Keeping this node preserves the delimiters and their trivia for source + /// tools while evaluation remains equivalent to evaluating `expr`. + Parenthesized { + expr: ExprId, + }, Match { scrutinee: ExprId, arms: Vec, diff --git a/crates/decodal-core/src/eval.rs b/crates/decodal-core/src/eval.rs index ece0cc6..b8830ea 100644 --- a/crates/decodal-core/src/eval.rs +++ b/crates/decodal-core/src/eval.rs @@ -471,6 +471,13 @@ impl Engine { }, ))) } + Expr::Parenthesized { expr } => self.eval_expr( + ExprRef { + module: reference.module, + expr, + }, + env, + ), Expr::Match { scrutinee, arms } => { let value = self.eval_expr( ExprRef { @@ -827,6 +834,14 @@ impl Engine { ) -> Result { match self.expr(pattern).clone() { Expr::Wildcard => Ok(true), + Expr::Parenthesized { expr } => self.matches_pattern( + value, + ExprRef { + module: pattern.module, + expr, + }, + env, + ), Expr::ArrayConstraint { .. } | Expr::CompareConstraint { .. } | Expr::RegexConstraint(_) @@ -2043,6 +2058,13 @@ mod tests { assert_eq!(fields[4].value, Data::Int(-2)); } + #[test] + fn parenthesized_wildcard_remains_a_match_pattern() { + let data = eval_data("result = match 1 { (_): 2; };"); + let Data::Object(fields) = data else { panic!() }; + assert_eq!(fields[0].value, Data::Int(2)); + } + #[test] fn arithmetic_can_feed_constraints() { let data = eval_data("port = Int & > 4000 + 42 default 8080;"); diff --git a/crates/decodal-core/src/lexer.rs b/crates/decodal-core/src/lexer.rs index b020ad8..88d67ca 100644 --- a/crates/decodal-core/src/lexer.rs +++ b/crates/decodal-core/src/lexer.rs @@ -52,9 +52,25 @@ pub enum TokenKind { Gte, Lt, Lte, + /// A line comment, including its leading `#` and excluding its newline. + Comment, Eof, } +/// Tokenizes source while retaining comments and source spans for tooling. +/// +/// Whitespace remains available through the gaps between adjacent token spans, +/// making this a lossless syntax view when paired with the original source. +pub fn tokenize_source(source: &str) -> Result> { + tokenize_source_with_source_id(SourceId(0), source) +} + +/// Tokenizes source with a caller-provided source identifier while retaining +/// comments and source spans for tooling. +pub fn tokenize_source_with_source_id(source_id: SourceId, source: &str) -> Result> { + Lexer::with_source_id(source_id, source).tokenize_with_comments() +} + pub struct Lexer<'a> { source_id: SourceId, source: &'a str, @@ -78,10 +94,26 @@ impl<'a> Lexer<'a> { } pub fn tokenize(mut self) -> Result> { + self.tokenize_impl(false) + } + + fn tokenize_with_comments(mut self) -> Result> { + self.tokenize_impl(true) + } + + fn tokenize_impl(&mut self, include_comments: bool) -> Result> { let mut tokens = Vec::new(); let mut previous = None; loop { - let token = self.next_token(previous.as_ref())?; + self.skip_whitespace(); + if self.peek() == Some(b'#') { + let comment = self.lex_comment(); + if include_comments { + tokens.push(comment); + } + continue; + } + let token = self.next_non_ws_token(previous.as_ref())?; let is_eof = token.kind == TokenKind::Eof; if !is_eof { previous = Some(token.kind.clone()); @@ -93,11 +125,6 @@ impl<'a> Lexer<'a> { } } - fn next_token(&mut self, previous: Option<&TokenKind>) -> Result { - self.skip_ws_and_comments(); - self.next_non_ws_token(previous) - } - fn next_non_ws_token(&mut self, previous: Option<&TokenKind>) -> Result { let start = self.pos; let Some(ch) = self.peek() else { @@ -259,21 +286,23 @@ impl<'a> Lexer<'a> { }) } - fn skip_ws_and_comments(&mut self) { - loop { - while matches!(self.peek(), Some(b' ' | b'\t' | b'\r' | b'\n')) { - self.pos += 1; + fn skip_whitespace(&mut self) { + while matches!(self.peek(), Some(b' ' | b'\t' | b'\r' | b'\n')) { + self.pos += 1; + } + } + + fn lex_comment(&mut self) -> Token { + let start = self.pos; + while let Some(c) = self.peek() { + if c == b'\n' { + break; } - if self.peek() == Some(b'#') { - while let Some(c) = self.peek() { - self.pos += 1; - if c == b'\n' { - break; - } - } - continue; - } - break; + self.pos += 1; + } + Token { + kind: TokenKind::Comment, + span: self.span(start, self.pos), } } @@ -453,4 +482,30 @@ mod tests { assert!(matches!(tokens[2].kind, TokenKind::Ident(_))); assert_eq!(tokens[3].kind, TokenKind::RBracket); } + + #[test] + fn tooling_tokens_retain_comments_and_whitespace_gaps() { + let source = "value = 1; # trailing\n\n# leading\nnext = 2;"; + let tokens = tokenize_source(source).unwrap(); + let comments = tokens + .iter() + .filter(|token| token.kind == TokenKind::Comment) + .collect::>(); + assert_eq!(comments.len(), 2); + assert_eq!( + &source[comments[0].span.start as usize..comments[0].span.end as usize], + "# trailing" + ); + assert!( + source[comments[0].span.end as usize..comments[1].span.start as usize].contains("\n\n") + ); + + let source_id = SourceId(7); + let identified = tokenize_source_with_source_id(source_id, "# comment").unwrap(); + assert!( + identified + .iter() + .all(|token| token.span.source == source_id) + ); + } } diff --git a/crates/decodal-core/src/lib.rs b/crates/decodal-core/src/lib.rs index e0dec7a..0eb112a 100644 --- a/crates/decodal-core/src/lib.rs +++ b/crates/decodal-core/src/lib.rs @@ -23,6 +23,10 @@ pub use diagnostic::{Diagnostic, DiagnosticKind, Result}; pub use embedding::{HostField, HostValue}; pub use environment::HostEnvironment; pub use eval::{Engine, format_diagnostic_with}; +pub use lexer::{ + Token as SyntaxToken, TokenKind as SyntaxTokenKind, tokenize_source, + tokenize_source_with_source_id, +}; pub use module::{ EmptyLoader, ImportCandidate, ImportLoader, LoadedImport, LoadedSource, LoadedValue, Module, }; diff --git a/crates/decodal-core/src/parser.rs b/crates/decodal-core/src/parser.rs index 19a1efc..01b982e 100644 --- a/crates/decodal-core/src/parser.rs +++ b/crates/decodal-core/src/parser.rs @@ -38,7 +38,10 @@ pub struct Parser { impl Parser { pub fn new(tokens: Vec) -> Self { Self { - tokens, + tokens: tokens + .into_iter() + .filter(|token| token.kind != TokenKind::Comment) + .collect(), pos: 0, ast: Ast::new(), } @@ -380,8 +383,9 @@ impl Parser { } let expr = self.parse_expr(0)?; - self.expect_kind(&TokenKind::RParen, "expected ')' after expression")?; - Ok(expr) + let end_span = self.expect_kind(&TokenKind::RParen, "expected ')' after expression")?; + let span = start_span.join(end_span); + Ok(self.ast.push(Expr::Parenthesized { expr }, span)) } fn parse_params_after_lparen(&mut self) -> Result> { @@ -692,7 +696,24 @@ mod tests { let Expr::ArrayConstraint { item } = parsed.ast.get(parsed.root).expr else { panic!() }; - assert!(matches!(parsed.ast.get(item).expr, Expr::Binary { .. })); + let Expr::Parenthesized { expr } = parsed.ast.get(item).expr else { + panic!() + }; + assert!(matches!(parsed.ast.get(expr).expr, Expr::Binary { .. })); + assert_eq!(parsed.ast.span(item), Span::new(SourceId(0), 4, 22)); + } + + #[test] + fn parser_accepts_the_public_lossless_token_stream() { + let tokens = crate::tokenize_source("value = (# note\n 1);").unwrap(); + let parsed = Parser::new(tokens).parse().unwrap(); + let Expr::Object(fields) = &parsed.ast.get(parsed.root).expr else { + panic!() + }; + assert!(matches!( + parsed.ast.get(fields[0].value).expr, + Expr::Parenthesized { .. } + )); } #[test] diff --git a/crates/decodal-language-tools/Cargo.toml b/crates/decodal-language-tools/Cargo.toml index 53fe159..588deda 100644 --- a/crates/decodal-language-tools/Cargo.toml +++ b/crates/decodal-language-tools/Cargo.toml @@ -7,7 +7,7 @@ license.workspace = true repository.workspace = true readme.workspace = true description = "Source-level language tooling for Decodal." -keywords = ["decodal", "formatter", "lsp", "tree-sitter"] +keywords = ["decodal", "formatter", "lsp", "language-tools"] categories = ["development-tools", "text-processing"] [lib] @@ -16,8 +16,6 @@ crate-type = ["cdylib", "rlib"] [dependencies] decodal = { version = "0.1.3", path = "../decodal-core" } serde_json.workspace = true -tree-sitter = "0.22.6" -tree-sitter-decodal = { version = "0.1.0", path = "../../editors/tree-sitter-decodal" } wasm-bindgen.workspace = true [package.metadata.wasm-pack.profile.release] diff --git a/crates/decodal-language-tools/src/lib.rs b/crates/decodal-language-tools/src/lib.rs index 20bf1d1..0ac68e7 100644 --- a/crates/decodal-language-tools/src/lib.rs +++ b/crates/decodal-language-tools/src/lib.rs @@ -1,7 +1,11 @@ use std::{error::Error, fmt}; -#[cfg(not(target_arch = "wasm32"))] -use tree_sitter::{Node, Parser, TreeCursor}; +use decodal::{ + Ast, BinaryOp, CompareOp, Expr, ExprId, Field, Param, SourceForm, Span, SyntaxToken, + SyntaxTokenKind, + ast::{MatchArm, UnaryOp}, + parse_source, tokenize_source, +}; use wasm_bindgen::prelude::*; const INDENT: usize = 4; @@ -31,36 +35,17 @@ impl fmt::Display for FormatError { impl Error for FormatError {} +/// Formats a complete Decodal source with the canonical parser and syntax tokens. +/// +/// Native and WebAssembly callers execute this exact implementation. Comments +/// are recovered from the lossless token stream while expression structure and +/// precedence come from the same AST used by evaluation. pub fn format_source(source: &str) -> Result { - decodal::parse_source(source) + let parsed = parse_source(source) .map_err(|diagnostic| FormatError::new(format!("parse error: {}", diagnostic.message)))?; - format_source_impl(source) -} - -#[cfg(not(target_arch = "wasm32"))] -fn format_source_impl(source: &str) -> Result { - let mut parser = Parser::new(); - parser - .set_language(&tree_sitter_decodal::language()) - .map_err(|error| { - FormatError::new(format!("failed to load tree-sitter grammar: {error}")) - })?; - let tree = parser - .parse(source, None) - .ok_or_else(|| FormatError::new("tree-sitter failed to parse source"))?; - let root = tree.root_node(); - if root.has_error() { - return Err(FormatError::new( - "parse error: source contains tree-sitter errors", - )); - } - - let mut formatter = Formatter::new(source); - let mut out = formatter.format_source_file(root); - if !out.ends_with('\n') { - out.push('\n'); - } - Ok(out) + let tokens = tokenize_source(source) + .map_err(|diagnostic| FormatError::new(format!("lex error: {}", diagnostic.message)))?; + Ok(Formatter::new(source, &parsed.ast, tokens).format(parsed.root, parsed.source_form)) } #[wasm_bindgen(js_name = formatSource)] @@ -71,411 +56,174 @@ pub fn format_source_json(source: &str) -> String { } } -#[cfg(target_arch = "wasm32")] -fn format_source_impl(source: &str) -> Result { - Ok(LexicalFormatter::new(source).format()) -} - -#[cfg(target_arch = "wasm32")] -struct LexicalFormatter<'a> { - chars: core::iter::Peekable>, - out: String, - indent: usize, - line_start: bool, -} - -#[cfg(target_arch = "wasm32")] -impl<'a> LexicalFormatter<'a> { - fn new(source: &'a str) -> Self { - Self { - chars: source.chars().peekable(), - out: String::new(), - indent: 0, - line_start: true, - } - } - - fn format(mut self) -> String { - while let Some(ch) = self.chars.next() { - match ch { - ' ' | '\t' | '\r' | '\n' => self.consume_whitespace(ch), - '#' => self.write_comment(), - '"' => self.write_string(), - '{' => self.open_block('{'), - '[' => self.open_block('['), - '}' => self.close_block('}'), - ']' => self.close_block(']'), - ';' => self.end_statement(), - ',' => self.write_comma(), - '.' => self.write_compact('.'), - ':' => self.write_spaced_operator(":"), - '(' => self.write_compact('('), - ')' => self.write_compact(')'), - '+' | '-' | '*' | '/' | '=' | '!' | '&' | '|' | '>' | '<' => { - self.write_operator(ch) - } - _ => self.write_word(ch), - } - } - self.trim_trailing_spaces(); - if !self.out.ends_with('\n') { - self.out.push('\n'); - } - self.out - } - - fn consume_whitespace(&mut self, ch: char) { - if ch == '\n' && self.out.ends_with('\n') && !self.out.ends_with("\n\n") { - self.out.push('\n'); - self.line_start = true; - } - } - - fn write_comment(&mut self) { - if self.line_start { - self.write_indent(); - } else { - self.ensure_space(); - } - self.out.push('#'); - for ch in self.chars.by_ref() { - if ch == '\n' { - break; - } - self.out.push(ch); - } - self.trim_trailing_spaces(); - self.out.push('\n'); - self.line_start = true; - } - - fn write_string(&mut self) { - self.write_indent_if_needed(); - self.ensure_word_boundary(); - self.out.push('"'); - let mut escaped = false; - for ch in self.chars.by_ref() { - self.out.push(ch); - if escaped { - escaped = false; - } else if ch == '\\' { - escaped = true; - } else if ch == '"' { - break; - } - } - } - - fn open_block(&mut self, ch: char) { - self.trim_trailing_spaces(); - self.out.push(' '); - self.out.push(ch); - self.out.push('\n'); - self.indent += INDENT; - self.line_start = true; - } - - fn close_block(&mut self, ch: char) { - self.trim_trailing_spaces(); - if !self.out.ends_with('\n') { - self.out.push('\n'); - } - self.indent = self.indent.saturating_sub(INDENT); - self.write_indent(); - self.out.push(ch); - self.line_start = false; - } - - fn end_statement(&mut self) { - self.trim_trailing_spaces(); - self.out.push(';'); - self.out.push('\n'); - self.line_start = true; - } - - fn write_comma(&mut self) { - self.trim_trailing_spaces(); - self.out.push(','); - self.out.push(' '); - self.line_start = false; - } - - fn write_operator(&mut self, ch: char) { - let mut op = String::new(); - op.push(ch); - if let Some(next) = self.chars.peek().copied() { - let two_char = matches!( - (ch, next), - ('=', '=') - | ('!', '=') - | ('>', '=') - | ('<', '=') - | ('+', '+') - | ('/', '/') - | ('&', '&') - | ('|', '|') - | ('=', '>') - ); - if two_char { - op.push(next); - self.chars.next(); - } - } - self.write_spaced_operator(&op); - } - - fn write_spaced_operator(&mut self, op: &str) { - self.trim_trailing_spaces(); - self.ensure_space(); - self.out.push_str(op); - self.out.push(' '); - self.line_start = false; - } - - fn write_compact(&mut self, ch: char) { - self.trim_trailing_spaces(); - self.write_indent_if_needed(); - self.out.push(ch); - self.line_start = false; - } - - fn write_word(&mut self, first: char) { - self.write_indent_if_needed(); - self.ensure_word_boundary(); - self.out.push(first); - while let Some(next) = self.chars.peek().copied() { - if next.is_alphanumeric() || next == '_' { - self.out.push(next); - self.chars.next(); - } else { - break; - } - } - self.line_start = false; - } - - fn write_indent_if_needed(&mut self) { - if self.line_start { - self.write_indent(); - self.line_start = false; - } - } - - fn write_indent(&mut self) { - for _ in 0..self.indent { - self.out.push(' '); - } - } - - fn ensure_word_boundary(&mut self) { - let needs_space = self - .out - .chars() - .last() - .is_some_and(|ch| ch.is_alphanumeric() || matches!(ch, '_' | '"')); - if needs_space { - self.out.push(' '); - } - } - - fn ensure_space(&mut self) { - let needs_space = self - .out - .chars() - .last() - .is_some_and(|ch| !matches!(ch, ' ' | '\n' | '.' | '(' | '[')); - if needs_space { - self.out.push(' '); - } - } - - fn trim_trailing_spaces(&mut self) { - while self.out.ends_with(' ') || self.out.ends_with('\t') { - self.out.pop(); - } - } -} - -#[cfg(not(target_arch = "wasm32"))] struct Formatter<'a> { source: &'a str, + ast: &'a Ast, + tokens: Vec, + comments: Vec, } -#[cfg(not(target_arch = "wasm32"))] impl<'a> Formatter<'a> { - fn new(source: &'a str) -> Self { - Self { source } + fn new(source: &'a str, ast: &'a Ast, tokens: Vec) -> Self { + let comments = tokens + .iter() + .filter(|token| token.kind == SyntaxTokenKind::Comment) + .map(|token| token.span) + .collect(); + Self { + source, + ast, + tokens, + comments, + } } - fn format_source_file(&mut self, node: Node<'a>) -> String { + fn format(&self, root: ExprId, source_form: SourceForm) -> String { let mut out = String::new(); - let children = named_children(node); - self.write_statement_list(&mut out, &children, 0); + if source_form == SourceForm::Fields { + let Expr::Object(fields) = &self.ast.get(root).expr else { + unreachable!("field-form sources parse to an object") + }; + self.write_field_list(&mut out, fields, 0, self.source.len(), 0); + } else { + let span = self.ast.span(root); + self.write_between(&mut out, 0, span.start as usize, None, 0); + self.write_expr(&mut out, root, 0, 0); + self.write_between( + &mut out, + span.end as usize, + self.source.len(), + Some(span.end as usize), + 0, + ); + } + trim_trailing_whitespace(&mut out); + out.push('\n'); out } - fn write_statement_list(&mut self, out: &mut String, children: &[Node<'a>], indent: usize) { - let mut pending_comments = Vec::new(); - let mut pending_blank = false; - let mut previous_end = 0; - let mut previous_statement_end_row = None; - - for &child in children { - let is_trailing_comment = child.kind() == "comment" - && previous_statement_end_row == Some(child.start_position().row); - if previous_statement_end_row.is_some() && !is_trailing_comment { - if !out.ends_with('\n') { - out.push('\n'); - } - previous_statement_end_row = None; - } - - if previous_end > 0 && has_blank_line(self.slice(previous_end, child.start_byte())) { - pending_blank = true; - } - - if child.kind() == "comment" { - if is_trailing_comment { - if !out.ends_with(' ') { - out.push(' '); - } - out.push_str(self.raw_trimmed(child)); - out.push('\n'); - previous_statement_end_row = None; - } else { - pending_comments.push(child); - } - previous_end = child.end_byte(); - continue; - } - - if pending_blank && !out.is_empty() && !out.ends_with("\n\n") { - out.push('\n'); - } - pending_blank = false; - - for comment in pending_comments.drain(..) { - write_indent(out, indent); - out.push_str(self.raw_trimmed(comment)); - out.push('\n'); - } - + fn write_field_list( + &self, + out: &mut String, + fields: &[Field], + start: usize, + end: usize, + indent: usize, + ) { + let mut cursor = start; + let mut previous_end = None; + for field in fields { + let field_start = field.span.start as usize; + self.write_between(out, cursor, field_start, previous_end, indent); write_indent(out, indent); - self.write_statement(out, child, indent); - previous_statement_end_row = Some(child.end_position().row); - previous_end = child.end_byte(); - } - - if previous_statement_end_row.is_some() && !out.ends_with('\n') { - out.push('\n'); - } - - if pending_blank && !out.is_empty() && !out.ends_with("\n\n") { - out.push('\n'); - } - for comment in pending_comments { - write_indent(out, indent); - out.push_str(self.raw_trimmed(comment)); - out.push('\n'); + self.write_field(out, field, indent); + out.push(';'); + cursor = field.span.end as usize; + previous_end = Some(cursor); } + self.write_between(out, cursor, end, previous_end, indent); } - fn write_statement(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - match node.kind() { - "field_definition" => { - self.write_field_definition(out, node, indent); - out.push(';'); - } - _ => { - self.write_expr(out, node, indent, 0); - out.push(';'); - } - } - } - - fn write_field_definition(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - if let Some(path) = node.child_by_field_name("path") { - self.write_field_path(out, path); - } else { - out.push_str(self.raw_trimmed(node)); + fn write_field(&self, out: &mut String, field: &Field, indent: usize) { + let value_start = self.ast.span(field.value).start as usize; + if self.has_comment_between(field.span.start as usize, value_start) { + out.push_str(self.raw(field.span)); return; } - out.push_str(" = "); - if let Some(value) = node.child_by_field_name("value") { - self.write_expr(out, value, indent, 0); - } - } - - fn write_field_path(&mut self, out: &mut String, node: Node<'a>) { - let identifiers: Vec<_> = named_children(node) - .into_iter() - .filter(|child| child.kind() == "identifier") - .collect(); - if identifiers.is_empty() { - out.push_str(self.raw_trimmed(node)); - return; - } - for (index, identifier) in identifiers.into_iter().enumerate() { + for (index, part) in field.path.iter().enumerate() { if index > 0 { out.push('.'); } - out.push_str(self.raw_trimmed(identifier)); + out.push_str(part); } + out.push_str(" = "); + self.write_expr(out, field.value, indent, 0); } - fn write_expr(&mut self, out: &mut String, node: Node<'a>, indent: usize, parent_prec: u8) { - if expression_contains_comment(node) + fn write_expr(&self, out: &mut String, id: ExprId, indent: usize, parent_prec: u8) { + let node = self.ast.get(id); + if self.has_comment(node.span) && !matches!( - node.kind(), - "object" | "array" | "array_constraint" | "let_expression" | "match_expression" + node.expr, + Expr::Object(_) | Expr::Array(_) | Expr::Let { .. } | Expr::Match { .. } ) { - out.push_str(self.raw_trimmed(node)); + out.push_str(self.raw(node.span)); return; } - let prec = self.precedence(node); - let parenthesize = prec < parent_prec; + let precedence = self.precedence(id); + let parenthesize = precedence < parent_prec; if parenthesize { out.push('('); } - match node.kind() { - "literal" => { - if let Some(child) = named_children(node).first().copied() { - out.push_str(self.raw_trimmed(child)); - } else { - out.push_str(self.raw_trimmed(node)); - } + match &node.expr { + Expr::Literal(_) | Expr::Ident(_) | Expr::RegexConstraint(_) | Expr::Wildcard => { + out.push_str(self.raw(node.span)); } - "identifier" | "string" | "integer" | "float" | "boolean" | "regex_literal" => { - out.push_str(self.raw_trimmed(node)); + Expr::Object(fields) => self.write_object(out, node.span, fields, indent), + Expr::Array(items) => self.write_array(out, node.span, items, indent), + Expr::ArrayConstraint { item } => { + out.push_str("[..."); + self.write_expr(out, *item, indent, 0); + out.push(']'); } - "comparison_constraint" => self.write_comparison_constraint(out, node, indent), - "object" => self.write_object(out, node, indent), - "array" => self.write_array(out, node, indent), - "array_constraint" => self.write_array_constraint(out, node, indent), - "let_expression" => self.write_let(out, node, indent), - "function_expression" => self.write_function(out, node, indent), - "match_expression" => self.write_match(out, node, indent), - "import_expression" => self.write_import(out, node), - "parenthesized_expression" => { + Expr::Let { bindings, body } => self.write_let(out, node.span, bindings, *body, indent), + Expr::Import(_) => { + out.push_str("import "); + let raw = self.raw(node.span); + out.push_str(raw.strip_prefix("import").unwrap_or(raw).trim()); + } + Expr::Path { base, field } => { + self.write_expr(out, *base, indent, precedence); + out.push('.'); + out.push_str(field); + } + Expr::Call { callee, args } => { + self.write_expr(out, *callee, indent, precedence); out.push('('); - if let Some(expr) = named_children(node) - .into_iter() - .find(|child| child.kind() != "comment") - { - self.write_expr(out, expr, indent, 0); + for (index, argument) in args.iter().enumerate() { + if index > 0 { + out.push_str(", "); + } + self.write_expr(out, *argument, indent, 0); } out.push(')'); } - "call_expression" => self.write_call(out, node, indent), - "path_expression" => self.write_path(out, node, indent), - "unary_expression" => self.write_unary(out, node, indent), - "binary_expression" | "default_expression" => { - self.write_binary_like(out, node, indent, prec) + Expr::Function { params, body } => self.write_function(out, params, *body, indent), + Expr::Parenthesized { expr } => { + out.push('('); + self.write_expr(out, *expr, indent, 0); + out.push(')'); + } + Expr::Match { scrutinee, arms } => { + self.write_match(out, node.span, *scrutinee, arms, indent) + } + Expr::Unary { op, expr } => { + out.push_str(match op { + UnaryOp::Neg => "-", + UnaryOp::Not => "!", + }); + self.write_expr(out, *expr, indent, precedence); + } + Expr::Binary { op, lhs, rhs } => { + self.write_expr(out, *lhs, indent, precedence); + out.push(' '); + out.push_str(binary_operator(*op)); + out.push(' '); + self.write_expr(out, *rhs, indent, precedence + 1); + } + Expr::Default { base, fallback } => { + self.write_expr(out, *base, indent, precedence); + out.push_str(" default "); + self.write_expr(out, *fallback, indent, precedence + 1); + } + Expr::CompareConstraint { op, value } => { + out.push_str(compare_operator(*op)); + out.push(' '); + self.write_expr(out, *value, indent, precedence); } - _ => out.push_str(self.raw_trimmed(node)), } if parenthesize { @@ -483,346 +231,407 @@ impl<'a> Formatter<'a> { } } - fn write_object(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - let children = named_children(node); - if children.is_empty() { + fn write_object(&self, out: &mut String, span: Span, fields: &[Field], indent: usize) { + let (start, end) = + self.delimited_range(span, SyntaxTokenKind::LBrace, SyntaxTokenKind::RBrace); + if fields.is_empty() && !self.has_comment_between(start, end) { out.push_str("{}"); return; } - out.push('{'); - out.push('\n'); - self.write_statement_list(out, &children, indent + INDENT); + out.push_str("{\n"); + self.write_field_list(out, fields, start, end, indent + INDENT); write_indent(out, indent); out.push('}'); } - fn write_array(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - let children = named_children(node); - if children.is_empty() { + fn write_array(&self, out: &mut String, span: Span, items: &[ExprId], indent: usize) { + let (start, end) = + self.delimited_range(span, SyntaxTokenKind::LBracket, SyntaxTokenKind::RBracket); + if items.is_empty() && !self.has_comment_between(start, end) { out.push_str("[]"); return; } - let has_comment = children.iter().any(|child| child.kind() == "comment"); - let inline = !has_comment && children.iter().all(|child| is_inline_expr(*child)); + let inline = !self.has_comment_between(start, end) + && items.iter().all(|item| self.is_inline_expr(*item)); if inline { out.push('['); - for (index, child) in children.into_iter().enumerate() { + for (index, item) in items.iter().enumerate() { if index > 0 { out.push_str(", "); } - self.write_expr(out, child, indent, 0); + self.write_expr(out, *item, indent, 0); } out.push(']'); return; } - out.push('['); - out.push('\n'); - let mut pending_comments = Vec::new(); - for child in children { - if child.kind() == "comment" { - pending_comments.push(child); - continue; - } - for comment in pending_comments.drain(..) { - write_indent(out, indent + INDENT); - out.push_str(self.raw_trimmed(comment)); - out.push('\n'); - } + out.push_str("[\n"); + let mut cursor = start; + let mut previous_end = None; + for item in items { + let item_span = self.ast.span(*item); + self.write_between( + out, + cursor, + item_span.start as usize, + previous_end, + indent + INDENT, + ); write_indent(out, indent + INDENT); - self.write_expr(out, child, indent + INDENT, 0); - out.push_str(",\n"); - } - for comment in pending_comments { - write_indent(out, indent + INDENT); - out.push_str(self.raw_trimmed(comment)); - out.push('\n'); + self.write_expr(out, *item, indent + INDENT, 0); + out.push(','); + cursor = item_span.end as usize; + previous_end = Some(cursor); } + self.write_between(out, cursor, end, previous_end, indent + INDENT); write_indent(out, indent); out.push(']'); } - fn write_array_constraint(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - out.push_str("[..."); - if let Some(element) = node.child_by_field_name("element") { - self.write_expr(out, element, indent, 0); - } - out.push(']'); - } + fn write_let( + &self, + out: &mut String, + span: Span, + bindings: &[Field], + body: ExprId, + indent: usize, + ) { + let body_span = self.ast.span(body); + let in_token = self + .tokens_between(span.start as usize, body_span.start as usize) + .rev() + .find(|token| token.kind == SyntaxTokenKind::In) + .expect("parsed let expressions contain `in`"); + let let_token = self + .tokens_between(span.start as usize, span.end as usize) + .find(|token| token.kind == SyntaxTokenKind::Let) + .expect("parsed let expressions contain `let`"); - fn write_let(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - let body = node.child_by_field_name("body"); - out.push_str("let"); - out.push('\n'); - let children: Vec<_> = named_children(node) - .into_iter() - .filter(|child| Some(*child) != body) - .collect(); - self.write_statement_list(out, &children, indent + INDENT); + out.push_str("let\n"); + self.write_field_list( + out, + bindings, + let_token.span.end as usize, + in_token.span.start as usize, + indent + INDENT, + ); write_indent(out, indent); out.push_str("in"); - if let Some(body) = body { + self.write_between( + out, + in_token.span.end as usize, + body_span.start as usize, + Some(in_token.span.end as usize), + indent + INDENT, + ); + write_indent(out, indent + INDENT); + self.write_expr(out, body, indent + INDENT, 0); + } + + fn write_function(&self, out: &mut String, params: &[Param], body: ExprId, indent: usize) { + out.push('('); + for (index, parameter) in params.iter().enumerate() { + if index > 0 { + out.push_str(", "); + } + out.push_str(¶meter.name); + if let Some(constraint) = parameter.constraint { + out.push_str(": "); + self.write_expr(out, constraint, indent, 0); + } + } + out.push_str(") =>"); + if self.is_inline_expr(body) { + out.push(' '); + self.write_expr(out, body, indent, 0); + } else { out.push('\n'); write_indent(out, indent + INDENT); self.write_expr(out, body, indent + INDENT, 0); } } - fn write_function(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - let body = node.child_by_field_name("body"); - let params: Vec<_> = named_children(node) - .into_iter() - .filter(|child| child.kind() == "parameter") - .collect(); - out.push('('); - for (index, param) in params.into_iter().enumerate() { - if index > 0 { - out.push_str(", "); - } - self.write_parameter(out, param, indent); - } - out.push_str(") =>"); - if let Some(body) = body { - if is_inline_expr(body) { - out.push(' '); - self.write_expr(out, body, indent, 0); - } else { - out.push('\n'); - write_indent(out, indent + INDENT); - self.write_expr(out, body, indent + INDENT, 0); - } - } - } - - fn write_parameter(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - if let Some(name) = node.child_by_field_name("name") { - out.push_str(self.raw_trimmed(name)); - } - if let Some(constraint) = node.child_by_field_name("constraint") { - out.push_str(": "); - self.write_expr(out, constraint, indent, 0); - } - } - - fn write_match(&mut self, out: &mut String, node: Node<'a>, indent: usize) { + fn write_match( + &self, + out: &mut String, + span: Span, + scrutinee: ExprId, + arms: &[MatchArm], + indent: usize, + ) { out.push_str("match "); - if let Some(scrutinee) = node.child_by_field_name("scrutinee") { - self.write_expr(out, scrutinee, indent, 0); - } - out.push_str(" {"); - let children: Vec<_> = named_children(node) - .into_iter() - .filter(|child| child.kind() == "match_arm" || child.kind() == "comment") - .collect(); - if !children.is_empty() { - out.push('\n'); - self.write_match_arms(out, &children, indent + INDENT); + self.write_expr(out, scrutinee, indent, 0); + let scrutinee_end = self.ast.span(scrutinee).end as usize; + let open = self + .tokens_between(scrutinee_end, span.end as usize) + .find(|token| token.kind == SyntaxTokenKind::LBrace) + .expect("parsed match expressions contain `{`"); + let close = self + .tokens_between(open.span.end as usize, span.end as usize) + .rev() + .find(|token| token.kind == SyntaxTokenKind::RBrace) + .expect("parsed match expressions contain `}`"); + let start = open.span.end as usize; + let end = close.span.start as usize; + if self.has_comment_between(scrutinee_end, open.span.start as usize) { + self.write_between( + out, + scrutinee_end, + open.span.start as usize, + Some(scrutinee_end), + indent, + ); write_indent(out, indent); + out.push('{'); + } else { + out.push_str(" {"); } + if arms.is_empty() && !self.has_comment_between(start, end) { + out.push('}'); + return; + } + + out.push('\n'); + let mut cursor = start; + let mut previous_end = None; + for arm in arms { + self.write_between( + out, + cursor, + arm.span.start as usize, + previous_end, + indent + INDENT, + ); + write_indent(out, indent + INDENT); + if self.has_comment_between( + self.ast.span(arm.pattern).end as usize, + self.ast.span(arm.body).start as usize, + ) { + out.push_str(self.raw(arm.span)); + } else { + self.write_expr(out, arm.pattern, indent + INDENT, 0); + out.push_str(": "); + self.write_expr(out, arm.body, indent + INDENT, 0); + } + out.push(';'); + cursor = arm.span.end as usize; + previous_end = Some(cursor); + } + self.write_between(out, cursor, end, previous_end, indent + INDENT); + write_indent(out, indent); out.push('}'); } - fn write_match_arms(&mut self, out: &mut String, children: &[Node<'a>], indent: usize) { - let mut pending_comments = Vec::new(); - for &child in children { - if child.kind() == "comment" { - pending_comments.push(child); - continue; - } - for comment in pending_comments.drain(..) { + fn write_between( + &self, + out: &mut String, + start: usize, + end: usize, + previous_end: Option, + indent: usize, + ) { + let mut cursor = start.min(end); + for comment in self.comments_between(start, end) { + let comment_start = comment.start as usize; + let trailing = previous_end.is_some_and(|previous| { + !out.ends_with('\n') && self.same_line(previous, comment_start) + }); + if trailing { + out.push(' '); + out.push_str(self.raw(*comment)); + out.push('\n'); + } else { + ensure_line_break(out); + if self.has_blank_line(cursor, comment_start) { + ensure_blank_line(out); + } write_indent(out, indent); - out.push_str(self.raw_trimmed(comment)); + out.push_str(self.raw(*comment)); out.push('\n'); } - write_indent(out, indent); - if let Some(pattern) = child.child_by_field_name("pattern") { - self.write_expr(out, pattern, indent, 0); - } - out.push_str(": "); - if let Some(body) = child.child_by_field_name("body") { - self.write_expr(out, body, indent, 0); - } - out.push_str(";\n"); + cursor = comment.end as usize; } - for comment in pending_comments { - write_indent(out, indent); - out.push_str(self.raw_trimmed(comment)); - out.push('\n'); + if previous_end.is_some() { + ensure_line_break(out); + } + if self.has_blank_line(cursor, end) { + ensure_blank_line(out); } } - fn write_import(&mut self, out: &mut String, node: Node<'a>) { - out.push_str("import "); - if let Some(specifier) = node.child_by_field_name("specifier") { - out.push_str(self.raw_trimmed(specifier)); - } - } - - fn write_call(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - let callee = node.child_by_field_name("function"); - if let Some(callee) = callee { - self.write_expr(out, callee, indent, self.precedence(node)); - } - out.push('('); - let args: Vec<_> = named_children(node) - .into_iter() - .filter(|child| Some(*child) != callee && child.kind() != "comment") - .collect(); - for (index, arg) in args.into_iter().enumerate() { - if index > 0 { - out.push_str(", "); - } - self.write_expr(out, arg, indent, 0); - } - out.push(')'); - } - - fn write_path(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - if let Some(object) = node.child_by_field_name("object") { - self.write_expr(out, object, indent, self.precedence(node)); - } - out.push('.'); - if let Some(field) = node.child_by_field_name("field") { - out.push_str(self.raw_trimmed(field)); - } - } - - fn write_unary(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - if let Some(operand) = node.child_by_field_name("operand") { - let operator = self.slice(node.start_byte(), operand.start_byte()).trim(); - out.push_str(operator); - self.write_expr(out, operand, indent, self.precedence(node)); - } else { - out.push_str(self.raw_trimmed(node)); - } - } - - fn write_comparison_constraint(&mut self, out: &mut String, node: Node<'a>, indent: usize) { - if let Some(value) = node.child_by_field_name("value") { - let operator = self.slice(node.start_byte(), value.start_byte()).trim(); - out.push_str(operator); - out.push(' '); - self.write_expr(out, value, indent, self.precedence(node)); - } else { - out.push_str(self.raw_trimmed(node)); - } - } - - fn write_binary_like(&mut self, out: &mut String, node: Node<'a>, indent: usize, prec: u8) { - let left = node - .child_by_field_name("left") - .or_else(|| node.child_by_field_name("base")); - let right = node - .child_by_field_name("right") - .or_else(|| node.child_by_field_name("fallback")); - let (Some(left), Some(right)) = (left, right) else { - out.push_str(self.raw_trimmed(node)); - return; - }; - self.write_expr(out, left, indent, prec); - out.push(' '); - if node.kind() == "default_expression" { - out.push_str("default"); - } else { - out.push_str(self.slice(left.end_byte(), right.start_byte()).trim()); - } - out.push(' '); - self.write_expr(out, right, indent, prec + 1); - } - - fn precedence(&self, node: Node<'a>) -> u8 { - match node.kind() { - "default_expression" => 1, - "binary_expression" => self.binary_precedence(node), - "unary_expression" | "comparison_constraint" => 17, - "call_expression" | "path_expression" => 19, + fn precedence(&self, id: ExprId) -> u8 { + match &self.ast.get(id).expr { + Expr::Default { .. } => 1, + Expr::Binary { op, .. } => match op { + BinaryOp::Patch => 3, + BinaryOp::And => 5, + BinaryOp::LogicalOr => 7, + BinaryOp::LogicalAnd => 9, + BinaryOp::Equal + | BinaryOp::NotEqual + | BinaryOp::Greater + | BinaryOp::GreaterEqual + | BinaryOp::Less + | BinaryOp::LessEqual => 11, + BinaryOp::Concat => 12, + BinaryOp::Add | BinaryOp::Sub => 13, + BinaryOp::Mul | BinaryOp::Div => 15, + }, + Expr::Unary { .. } | Expr::CompareConstraint { .. } => 17, + Expr::Call { .. } | Expr::Path { .. } => 19, + Expr::Parenthesized { .. } => 20, _ => 20, } } - fn binary_precedence(&self, node: Node<'a>) -> u8 { - let Some(left) = node.child_by_field_name("left") else { - return 10; - }; - let Some(right) = node.child_by_field_name("right") else { - return 10; - }; - match self.slice(left.end_byte(), right.start_byte()).trim() { - "//" => 3, - "&" => 5, - "||" => 7, - "&&" => 9, - "==" | "!=" | ">" | ">=" | "<" | "<=" => 11, - "++" => 12, - "+" | "-" => 13, - "*" | "/" => 15, - _ => 10, + fn is_inline_expr(&self, id: ExprId) -> bool { + let node = self.ast.get(id); + if self.has_comment(node.span) { + return false; + } + match &node.expr { + Expr::Literal(_) + | Expr::Ident(_) + | Expr::RegexConstraint(_) + | Expr::Wildcard + | Expr::Import(_) + | Expr::CompareConstraint { .. } => true, + Expr::Path { base, .. } => self.is_inline_expr(*base), + Expr::Call { callee, args } => { + self.is_inline_expr(*callee) + && args.iter().all(|argument| self.is_inline_expr(*argument)) + } + Expr::Unary { expr, .. } => self.is_inline_expr(*expr), + Expr::Binary { lhs, rhs, .. } => self.is_inline_expr(*lhs) && self.is_inline_expr(*rhs), + Expr::Default { base, fallback } => { + self.is_inline_expr(*base) && self.is_inline_expr(*fallback) + } + Expr::Array(items) => items.iter().all(|item| self.is_inline_expr(*item)), + Expr::ArrayConstraint { item } => self.is_inline_expr(*item), + Expr::Parenthesized { expr } => self.is_inline_expr(*expr), + Expr::Object(_) | Expr::Let { .. } | Expr::Function { .. } | Expr::Match { .. } => { + false + } } } - fn raw_trimmed(&self, node: Node<'a>) -> &'a str { - self.slice(node.start_byte(), node.end_byte()).trim() + fn delimited_range( + &self, + span: Span, + open_kind: SyntaxTokenKind, + close_kind: SyntaxTokenKind, + ) -> (usize, usize) { + let open = self + .tokens_between(span.start as usize, span.end as usize) + .find(|token| same_kind(&token.kind, &open_kind)) + .expect("parsed delimited expressions contain an opening token"); + let close = self + .tokens_between(open.span.end as usize, span.end as usize) + .rev() + .find(|token| same_kind(&token.kind, &close_kind)) + .expect("parsed delimited expressions contain a closing token"); + (open.span.end as usize, close.span.start as usize) + } + + fn tokens_between( + &self, + start: usize, + end: usize, + ) -> impl DoubleEndedIterator { + self.tokens.iter().filter(move |token| { + token.span.start as usize >= start && token.span.end as usize <= end + }) + } + + fn comments_between(&self, start: usize, end: usize) -> impl Iterator { + self.comments + .iter() + .filter(move |comment| comment.start as usize >= start && comment.end as usize <= end) + } + + fn has_comment(&self, span: Span) -> bool { + self.has_comment_between(span.start as usize, span.end as usize) + } + + fn has_comment_between(&self, start: usize, end: usize) -> bool { + self.comments_between(start, end).next().is_some() + } + + fn same_line(&self, start: usize, end: usize) -> bool { + !self.slice(start, end).contains('\n') + } + + fn has_blank_line(&self, start: usize, end: usize) -> bool { + self.slice(start, end) + .bytes() + .filter(|byte| *byte == b'\n') + .count() + >= 2 + } + + fn raw(&self, span: Span) -> &'a str { + self.slice(span.start as usize, span.end as usize).trim() } fn slice(&self, start: usize, end: usize) -> &'a str { - &self.source[start..end] + &self.source[start.min(self.source.len())..end.min(self.source.len())] } } -#[cfg(not(target_arch = "wasm32"))] -fn named_children<'a>(node: Node<'a>) -> Vec> { - let mut cursor: TreeCursor<'a> = node.walk(); - node.named_children(&mut cursor).collect() -} - -#[cfg(not(target_arch = "wasm32"))] -fn expression_contains_comment(node: Node<'_>) -> bool { - if node.kind() == "comment" { - return true; - } - named_children(node) - .into_iter() - .any(expression_contains_comment) -} - -#[cfg(not(target_arch = "wasm32"))] -fn is_inline_expr(node: Node<'_>) -> bool { - match node.kind() { - "literal" - | "identifier" - | "string" - | "integer" - | "float" - | "boolean" - | "regex_literal" - | "comparison_constraint" - | "import_expression" => true, - "path_expression" - | "call_expression" - | "unary_expression" - | "binary_expression" - | "default_expression" - | "parenthesized_expression" => { - !expression_contains_comment(node) - && named_children(node).into_iter().all(is_inline_expr) - } - "array" | "array_constraint" => { - !expression_contains_comment(node) - && named_children(node).into_iter().all(is_inline_expr) - } - _ => false, +fn binary_operator(operator: BinaryOp) -> &'static str { + match operator { + BinaryOp::Add => "+", + BinaryOp::Sub => "-", + BinaryOp::Mul => "*", + BinaryOp::Div => "/", + BinaryOp::Concat => "++", + BinaryOp::Equal => "==", + BinaryOp::NotEqual => "!=", + BinaryOp::Greater => ">", + BinaryOp::GreaterEqual => ">=", + BinaryOp::Less => "<", + BinaryOp::LessEqual => "<=", + BinaryOp::LogicalAnd => "&&", + BinaryOp::LogicalOr => "||", + BinaryOp::And => "&", + BinaryOp::Patch => "//", } } -#[cfg(not(target_arch = "wasm32"))] -fn has_blank_line(text: &str) -> bool { - text.bytes().filter(|byte| *byte == b'\n').count() >= 2 +fn compare_operator(operator: CompareOp) -> &'static str { + match operator { + CompareOp::Gt => ">", + CompareOp::Gte => ">=", + CompareOp::Lt => "<", + CompareOp::Lte => "<=", + CompareOp::Eq => "==", + } +} + +fn same_kind(left: &SyntaxTokenKind, right: &SyntaxTokenKind) -> bool { + core::mem::discriminant(left) == core::mem::discriminant(right) } -#[cfg(not(target_arch = "wasm32"))] fn write_indent(out: &mut String, indent: usize) { - for _ in 0..indent { - out.push(' '); + out.extend(core::iter::repeat_n(' ', indent)); +} + +fn ensure_line_break(out: &mut String) { + if !out.is_empty() && !out.ends_with('\n') { + out.push('\n'); + } +} + +fn ensure_blank_line(out: &mut String) { + if !out.is_empty() && !out.ends_with("\n\n") { + ensure_line_break(out); + out.push('\n'); + } +} + +fn trim_trailing_whitespace(out: &mut String) { + while out.ends_with(char::is_whitespace) { + out.pop(); } } @@ -862,9 +671,89 @@ mod tests { } #[test] - fn wasm_export_returns_json() { - let output = format_source_json("value={a=1;};"); - assert!(output.contains("\"ok\":true")); - assert!(output.contains("value = {\\n a = 1;\\n};\\n")); + fn formats_let_functions_and_precedence_from_the_canonical_ast() { + let source = "value=let x=1+2*3;in(a:Int)=>{result=(x+a)*2;};"; + let formatted = format_source(source).unwrap(); + assert_eq!( + formatted, + "value = let\n x = 1 + 2 * 3;\nin\n (a: Int) =>\n {\n result = (x + a) * 2;\n };\n" + ); + } + + #[test] + fn preserves_regex_and_escaped_strings() { + let source = r#"value={pattern=/^api\/.+$/;text="a\n\"b";};"#; + let formatted = format_source(source).unwrap(); + assert!(formatted.contains(r#"pattern = /^api\/.+$/;"#)); + assert!(formatted.contains(r#"text = "a\n\"b";"#)); + } + + #[test] + fn preserves_comments_inside_grouping_and_between_structural_tokens() { + let source = "value = (# grouped\n 1 + 2); result = match x # before brace\n { _ # before body\n : value; };"; + let formatted = format_source(source).unwrap(); + assert!(formatted.contains("(# grouped\n 1 + 2)")); + assert!(formatted.contains("match x # before brace\n{")); + assert!(formatted.contains("_ # before body\n : value;")); + assert_eq!(format_source(&formatted).unwrap(), formatted); + } + + #[test] + fn wasm_export_returns_the_same_formatter_result() { + let source = "value={a=1;};"; + let expected = format_source(source).unwrap(); + let output: serde_json::Value = serde_json::from_str(&format_source_json(source)).unwrap(); + assert_eq!(output["source"], expected); + } + + #[test] + fn formats_all_repository_examples_idempotently() { + let examples = [ + ( + "advanced/main", + include_str!("../../../examples/advanced/main.dcdl"), + ), + ( + "advanced/profiles", + include_str!("../../../examples/advanced/profiles.dcdl"), + ), + ( + "advanced/schema", + include_str!("../../../examples/advanced/schema.dcdl"), + ), + ( + "arithmetic", + include_str!("../../../examples/arithmetic.dcdl"), + ), + ( + "array-concat", + include_str!("../../../examples/array-concat.dcdl"), + ), + ( + "array-constraint", + include_str!("../../../examples/array-constraint.dcdl"), + ), + ("basic", include_str!("../../../examples/basic.dcdl")), + ( + "import/main", + include_str!("../../../examples/import/main.dcdl"), + ), + ( + "import/schema", + include_str!("../../../examples/import/schema.dcdl"), + ), + ("logical", include_str!("../../../examples/logical.dcdl")), + ( + "regex/main", + include_str!("../../../examples/regex/main.dcdl"), + ), + ]; + for (name, source) in examples { + let once = format_source(source).unwrap_or_else(|error| panic!("{name}: {error}")); + let twice = format_source(&once).unwrap_or_else(|error| { + panic!("{name} reformatted to invalid source: {error}\n{once}") + }); + assert_eq!(once, twice, "{name}"); + } } } diff --git a/doc/manual/souce/components.md b/doc/manual/souce/components.md index 3265f5c..bf2faae 100644 --- a/doc/manual/souce/components.md +++ b/doc/manual/souce/components.md @@ -58,10 +58,11 @@ The default `decodal-lsp` binary reads Decodal imports from the filesystem. Embedded hosts can call its library entry point with a custom `LspEnvironment` to reuse structured imports and to make unsaved external documents, such as Markdown, visible to the loader. Source formatting lives in a separate Rust language tools crate. -Keeping it separate prevents host-specific semantic services from inheriting the formatter's Tree-sitter and WebAssembly dependencies. +It uses the canonical Decodal AST together with the runtime lexer's lossless syntax tokens, so native LSP and WebAssembly callers execute the same formatter implementation. This component is responsible for operations that must preserve source text details such as comments and whitespace. It is used by the CodeMirror package's bundled formatter WebAssembly and can also be used by an LSP adapter for formatting. +It does not depend on Tree-sitter or Lezer. Important paths: @@ -74,7 +75,7 @@ The current language tools crate exposes the formatter. ## Web editor components The Web playground editor uses CodeMirror 6 with a generated Lezer parser. -This is the source of syntax highlighting, folding, indentation, editor syntax tree behavior, and the browser formatter command in the browser UI. +Lezer provides syntax highlighting, folding, indentation, and editor syntax tree behavior. The browser formatter command calls the canonical Rust formatter compiled to WebAssembly. Important paths: @@ -120,18 +121,20 @@ doc/manual/souce/language/grammar.md This EBNF is the language-level reference. The Rust parser, Lezer grammar, and Tree-sitter grammar should be kept aligned with it, but each implementation may encode precedence and recovery behavior in the form required by its parser generator or runtime. -## What is not a public component +## Syntax token API -The Rust lexer is an implementation detail of the Rust parser. -Decodal does not expose a standalone public tokenizer API for editor tooling. -Consumers that need syntax information should use the component that matches their environment: +The `decodal` crate exposes `tokenize_source`, `tokenize_source_with_source_id`, `SyntaxToken`, and `SyntaxTokenKind` for source-preserving tooling. +Comments have explicit tokens, while whitespace is represented by gaps between token spans and can be recovered from the original source. +The evaluator parser and formatter therefore share one lexical definition without making Tree-sitter an upstream dependency. + +Consumers should otherwise use the component matching their environment: - Rust execution and embedding: `decodal` - Browser execution: `decodal-wasm` -- Web formatting and editor syntax: Lezer / CodeMirror +- Web formatting and editor syntax: canonical formatter / CodeMirror / Lezer - Semantic editor analysis: `decodal-language-service` - Language Server Protocol integration: `decodal-lsp` - Rust formatting: `decodal-language-tools` - General editor syntax: Tree-sitter -This avoids having a separate token stream API whose behavior would have to be kept compatible with both runtime parsing and editor grammars. +Tree-sitter and Lezer remain downstream editor grammars and are not dependencies of the runtime formatter. diff --git a/doc/manual/souce/development.md b/doc/manual/souce/development.md index c61dd26..5443375 100644 --- a/doc/manual/souce/development.md +++ b/doc/manual/souce/development.md @@ -34,33 +34,13 @@ cargo run -q -p decodal-cli --features regex -- examples/regex/main.dcdl ## crates.io release -The primary crates.io package is `decodal`, which contains the embeddable library. -`decodal-derive` provides optional derive macros for Rust struct integration and is published only when the derive crate changes. -Workspace support crates such as `decodal-cli`, the Rust source crate `decodal-wasm`, `decodal-language-tools`, and `decodal-lsp` are not published to crates.io. +The crates.io release contains `decodal`, `decodal-derive`, `decodal-language-service`, `decodal-language-tools`, and `decodal-lsp`. +`decodal-cli` and the Rust source crate `decodal-wasm` remain repository-only packages. The generated WebAssembly package under `packages/decodal-wasm/` is published to npm and JSR. The CodeMirror package bundles the generated formatter WebAssembly from `decodal-language-tools`. The project is dual licensed as `MIT OR Apache-2.0`. -```sh -cargo publish -p decodal -``` - -Publish `decodal-derive` first only when that crate has a new version: - -```sh -cargo publish -p decodal-derive -``` - -Before publishing, run: - -```sh -cargo fmt --check -cargo test -cargo check -p decodal --no-default-features -cargo publish -p decodal --dry-run -``` - -If `decodal-derive` changed, also run `cargo publish -p decodal-derive --dry-run`. +The authoritative validation commands, dependency order, and publish commands are maintained in `RELEASING.md` at the repository root. ## Web site and playground @@ -125,7 +105,6 @@ npx jsr publish --dry-run The npm package name is `decodal-wasm`. The JSR package name is `@hare/decodal-wasm`. -JSR currently expects a single SPDX license identifier in `jsr.json`; the WebAssembly package metadata uses `MIT` while the Rust workspace remains dual licensed as `MIT OR Apache-2.0`. The playground editor uses the `decodal-codemirror` package with the generated Lezer parser in `packages/decodal-codemirror/src/decodal-parser.js`. The canonical grammar is documented in `doc/manual/souce/language/grammar.md`; regenerate the Lezer parser when that grammar or `editors/lezer-decodal/decodal.grammar` changes. @@ -149,7 +128,6 @@ npx jsr publish --dry-run The npm package name is `decodal-codemirror`. The JSR package name is `@hare/decodal-codemirror`. -JSR currently expects a single SPDX license identifier in `jsr.json`; the CodeMirror package metadata uses `MIT` while the Rust workspace remains dual licensed as `MIT OR Apache-2.0`. The documentation build still uses the lightweight JavaScript fallback highlighter so Astro can render Markdown without initializing WASM at build time. diff --git a/editors/tree-sitter-decodal/Cargo.toml b/editors/tree-sitter-decodal/Cargo.toml index d975772..a8338f6 100644 --- a/editors/tree-sitter-decodal/Cargo.toml +++ b/editors/tree-sitter-decodal/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "tree-sitter-decodal" description = "Decodal grammar for tree-sitter" -version = "0.1.0" +version = "0.0.1" license = "MIT" readme = "README.md" keywords = ["incremental", "parsing", "tree-sitter", "decodal"] diff --git a/packages/decodal-codemirror/LICENSE-APACHE b/packages/decodal-codemirror/LICENSE-APACHE new file mode 100644 index 0000000..8ad3e6e --- /dev/null +++ b/packages/decodal-codemirror/LICENSE-APACHE @@ -0,0 +1,173 @@ + 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. + +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 diff --git a/packages/decodal-codemirror/LICENSE-MIT b/packages/decodal-codemirror/LICENSE-MIT new file mode 100644 index 0000000..dd4df64 --- /dev/null +++ b/packages/decodal-codemirror/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Decodal contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/decodal-codemirror/jsr.json b/packages/decodal-codemirror/jsr.json index b64e770..2c172dd 100644 --- a/packages/decodal-codemirror/jsr.json +++ b/packages/decodal-codemirror/jsr.json @@ -1,7 +1,7 @@ { "name": "@hare/decodal-codemirror", - "version": "0.1.5", - "license": "MIT", + "version": "0.1.6", + "license": "MIT OR Apache-2.0", "exports": { ".": "./src/mod.ts", "./format": "./src/format.ts" @@ -15,6 +15,8 @@ "publish": { "include": [ "README.md", + "LICENSE-MIT", + "LICENSE-APACHE", "src/mod.ts", "src/format.ts", "src/decodal.js", diff --git a/packages/decodal-codemirror/package-lock.json b/packages/decodal-codemirror/package-lock.json index aa73efa..d1b8950 100644 --- a/packages/decodal-codemirror/package-lock.json +++ b/packages/decodal-codemirror/package-lock.json @@ -1,12 +1,12 @@ { "name": "decodal-codemirror", - "version": "0.1.5", + "version": "0.1.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "decodal-codemirror", - "version": "0.1.5", + "version": "0.1.6", "license": "MIT OR Apache-2.0", "devDependencies": { "@codemirror/language": "^6.12.4", diff --git a/packages/decodal-codemirror/package.json b/packages/decodal-codemirror/package.json index 118da64..be2941d 100644 --- a/packages/decodal-codemirror/package.json +++ b/packages/decodal-codemirror/package.json @@ -1,6 +1,6 @@ { "name": "decodal-codemirror", - "version": "0.1.5", + "version": "0.1.6", "description": "CodeMirror 6 language support for Decodal.", "type": "module", "license": "MIT OR Apache-2.0", @@ -28,6 +28,8 @@ "types": "./src/decodal.d.ts", "files": [ "README.md", + "LICENSE-MIT", + "LICENSE-APACHE", "src/", "wasm/decodal_language_tools.js", "wasm/decodal_language_tools.d.ts", diff --git a/packages/decodal-codemirror/src/format.test.mjs b/packages/decodal-codemirror/src/format.test.mjs new file mode 100644 index 0000000..54ab3b5 --- /dev/null +++ b/packages/decodal-codemirror/src/format.test.mjs @@ -0,0 +1,16 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; + +import { formatDecodal, initDecodalFormatter } from './format.js'; + +const wasmPath = new URL('../wasm/decodal_language_tools_bg.wasm', import.meta.url); + +test('WASM uses the canonical formatter and is idempotent', async () => { + await initDecodalFormatter({ module_or_path: await readFile(wasmPath) }); + const source = 'Server={\n# host\nhost=String default "localhost"; # trailing\n\nport=Int&>0;\n};'; + const expected = 'Server = {\n # host\n host = String default "localhost"; # trailing\n\n port = Int & > 0;\n};\n'; + + assert.deepEqual(formatDecodal(source), { ok: true, source: expected }); + assert.deepEqual(formatDecodal(expected), { ok: true, source: expected }); +}); diff --git a/packages/decodal-codemirror/src/format.ts b/packages/decodal-codemirror/src/format.ts index 8ebe4fa..b1b4e03 100644 --- a/packages/decodal-codemirror/src/format.ts +++ b/packages/decodal-codemirror/src/format.ts @@ -1,8 +1,8 @@ /** * Decodal source formatting helpers for CodeMirror integrations. * - * The formatter is backed by WebAssembly generated from the internal Rust - * `decodal-language-tools` crate. Call {@link initDecodalFormatter} once before + * The formatter is backed by WebAssembly generated from the canonical Rust + * `decodal-language-tools` formatter. Call {@link initDecodalFormatter} once before * using {@link formatDecodal} or {@link formatDecodalCommand}. * * @module diff --git a/packages/decodal-codemirror/wasm/decodal_language_tools_bg.wasm b/packages/decodal-codemirror/wasm/decodal_language_tools_bg.wasm index 26fdfc2..01156bc 100644 Binary files a/packages/decodal-codemirror/wasm/decodal_language_tools_bg.wasm and b/packages/decodal-codemirror/wasm/decodal_language_tools_bg.wasm differ diff --git a/packages/decodal-wasm/decodal_wasm_bg.wasm b/packages/decodal-wasm/decodal_wasm_bg.wasm index 7147368..aa42a24 100644 Binary files a/packages/decodal-wasm/decodal_wasm_bg.wasm and b/packages/decodal-wasm/decodal_wasm_bg.wasm differ diff --git a/site/decodal-site/package-lock.json b/site/decodal-site/package-lock.json index 39d87f4..5149d19 100644 --- a/site/decodal-site/package-lock.json +++ b/site/decodal-site/package-lock.json @@ -25,7 +25,7 @@ } }, "../../packages/decodal-codemirror": { - "version": "0.1.5", + "version": "0.1.6", "license": "MIT OR Apache-2.0", "devDependencies": { "@codemirror/language": "^6.12.4", diff --git a/site/decodal-site/scripts/prepare-codemirror-wasm.mjs b/site/decodal-site/scripts/prepare-codemirror-wasm.mjs index df09ad0..0677463 100644 --- a/site/decodal-site/scripts/prepare-codemirror-wasm.mjs +++ b/site/decodal-site/scripts/prepare-codemirror-wasm.mjs @@ -1,7 +1,11 @@ -import { rmSync, writeFileSync } from 'node:fs'; +import { copyFileSync, rmSync, writeFileSync } from 'node:fs'; import { resolve } from 'node:path'; const wasmDir = resolve(import.meta.dirname, '../../../packages/decodal-codemirror/wasm'); +const packageDir = resolve(wasmDir, '..'); + +copyFileSync(resolve(packageDir, '../../LICENSE-MIT'), resolve(packageDir, 'LICENSE-MIT')); +copyFileSync(resolve(packageDir, '../../LICENSE-APACHE'), resolve(packageDir, 'LICENSE-APACHE')); rmSync(resolve(wasmDir, 'README.md'), { force: true }); rmSync(resolve(wasmDir, 'package.json'), { force: true }); diff --git a/site/decodal-site/src/pages/index.astro b/site/decodal-site/src/pages/index.astro index fed5a02..b71d36f 100644 --- a/site/decodal-site/src/pages/index.astro +++ b/site/decodal-site/src/pages/index.astro @@ -33,7 +33,7 @@ Production = Server & {
  • decodal-wasm on jsr / npm
  • -
  • decodal-codemirror on jsr / npm
  • +
  • decodal-codemirror on jsr / npm