diff --git a/bindings/rust/fig/tests/sibling_separators.rs b/bindings/rust/fig/tests/sibling_separators.rs new file mode 100644 index 00000000..6ac96e7c --- /dev/null +++ b/bindings/rust/fig/tests/sibling_separators.rs @@ -0,0 +1,252 @@ +//! An insert into a flow mapping that copies its neighbours +//! (`flow_kv_sep_from_siblings`) when a neighbour has nothing to copy. The +//! languages are a small CSS with nesting: a block's member is a declaration, +//! `name: value`, or a rule, a selector over a block of its own, which has no +//! separator after its selector and needs none after its `}`. `nest-sheet` +//! reads rules at its root, and `nest-decls` is a `style` attribute's list. + +use std::sync::OnceLock; + +use fig::language::{ + Comments, Description, Dialect, Language, LanguageError, NodeKind, NodeRow, NodeTable, + PrintOptions, Splice, Syntax, +}; +use fig::{Capabilities, Editor, Format, Segment, Span}; + +fn sp(start: usize, end: usize) -> Span { + Span { start, end } +} + +fn trim_end(b: &[u8], from: usize, mut to: usize) -> usize { + while to > from && b[to - 1].is_ascii_whitespace() { + to -= 1; + } + to +} + +/// The `}` closing the `{` at `open`. +fn close_of(b: &[u8], open: usize, to: usize) -> Result { + let mut depth = 0; + for (i, c) in b.iter().enumerate().take(to).skip(open) { + match c { + b'{' => depth += 1, + b'}' => { + depth -= 1; + if depth == 0 { + return Ok(i); + } + } + _ => {} + } + } + Err(LanguageError::at("expected `}`", open)) +} + +fn string(t: &mut NodeTable, src: &str, parent: u32, from: usize, to: usize) { + t.push(NodeRow::new(NodeKind::String, Some(parent), sp(from, to)).with_text(&src[from..to])); +} + +/// The members in `src[from..to]` as keyvalues under `parent`. What comes +/// before a `{` is a selector, a colon in it included, so `&:hover { b: c }` +/// is a rule; a member with no `{` before its `;` is a declaration. +fn members( + t: &mut NodeTable, + src: &str, + parent: u32, + from: usize, + to: usize, +) -> Result<(), LanguageError> { + let b = src.as_bytes(); + let mut i = from; + loop { + while i < to && (b[i].is_ascii_whitespace() || b[i] == b';') { + i += 1; + } + if i >= to { + return Ok(()); + } + let start = i; + while i < to && b[i] != b'{' && b[i] != b';' { + i += 1; + } + if i < to && b[i] == b'{' { + let close = close_of(b, i, to)?; + let kv = t.push(NodeRow::new( + NodeKind::KeyValue, + Some(parent), + sp(start, close + 1), + )); + string(t, src, kv, start, trim_end(b, start, i)); + let block = t.push(NodeRow::new(NodeKind::Mapping, Some(kv), sp(i, close + 1))); + members(t, src, block, i + 1, close)?; + i = close + 1; + continue; + } + let colon = src[start..i] + .find(':') + .map(|c| start + c) + .ok_or_else(|| LanguageError::at("expected `:`", start))?; + let mut value = colon + 1; + while value < i && b[value].is_ascii_whitespace() { + value += 1; + } + let value_end = trim_end(b, value, i); + if value_end == value { + return Err(LanguageError::at("expected a value", value)); + } + let kv = t.push(NodeRow::new( + NodeKind::KeyValue, + Some(parent), + sp(start, value_end), + )); + string(t, src, kv, start, trim_end(b, start, colon)); + string(t, src, kv, value, value_end); + } +} + +fn print_members(rows: &[NodeRow], parent: u32) -> String { + let text = |r: usize| rows[r].text.as_deref().unwrap_or(""); + let members: Vec = (0..rows.len()) + .filter(|&r| rows[r].parent == Some(parent) && rows[r].kind == NodeKind::KeyValue) + .map(|r| { + if rows[r + 2].kind == NodeKind::Mapping { + let block = print_members(rows, (r + 2) as u32); + format!("{} {{ {block} }}", text(r + 1)) + } else { + format!("{}: {}", text(r + 1), text(r + 2)) + } + }) + .collect(); + members.join("; ") +} + +struct Nested { + name: &'static str, + flow_root: bool, + samples: &'static [&'static str], +} + +impl Language for Nested { + fn describe(&self) -> Description { + let mut s = Syntax::default(); + s.comments = Comments::none(); + s.kv_sep = Some(": ".into()); + s.flow_kv_sep_from_siblings = true; + s.flow_entry_sep = ";".into(); + s.flow_map_pad = " ".into(); + s.flow_maps_only = true; + s.flow_root = self.flow_root; + let mut d = Description::new(self.name); + d.caps = Capabilities::new(true, true, true); + d.syntax = Some(s); + let mut dialect = Dialect::new(self.name); + dialect.splice = Splice::Raw; + dialect.empty_doc_seed = Some(String::new()); + d.dialects = vec![dialect]; + d.samples = self.samples.iter().map(|s| s.to_string()).collect(); + d + } + + fn parse(&self, _: &str, input: &[u8]) -> Result { + let src = std::str::from_utf8(input).map_err(|_| LanguageError::new("not UTF-8"))?; + let mut t = NodeTable::new(); + let root = t.push(NodeRow::new(NodeKind::Mapping, None, sp(0, src.len()))); + members(&mut t, src, root, 0, src.len())?; + Ok(t) + } + + fn print( + &self, + _: &str, + table: &NodeTable, + _: &PrintOptions, + ) -> Result, LanguageError> { + let rows = &table.rows; + if rows.len() == 1 && rows[0].kind != NodeKind::Mapping { + return Ok(rows[0].text.clone().unwrap_or_default().into_bytes()); + } + Ok(print_members(rows, 0).into_bytes()) + } +} + +fn formats() -> (Format, Format) { + static FORMATS: OnceLock<(Format, Format)> = OnceLock::new(); + *FORMATS.get_or_init(|| { + let sheet = fig::language::register(Nested { + name: "nest-sheet", + flow_root: false, + samples: &[".a { b: c; &:hover { d: e } }\n"], + }) + .expect("sheet registers")[0]; + let decls = fig::language::register(Nested { + name: "nest-decls", + flow_root: true, + samples: &["b: c; &:hover { d: e }"], + }) + .expect("decls registers")[0]; + (sheet, decls) + }) +} + +/// `src` with `x` set to `y` in the block of `.a`. +fn set_in_a(src: &str) -> String { + let (sheet, _) = formats(); + let mut e = Editor::open(src.as_bytes(), sheet).expect("opens"); + e.set_value(&[Segment::Key(".a"), Segment::Key("x")], "y") + .unwrap_or_else(|err| panic!("{src:?}: {err}")); + e.source().expect("source").to_owned() +} + +#[test] +fn a_block_opening_with_a_rule_takes_a_declaration_after_it() { + assert_eq!( + set_in_a(".a { &:hover { b: c } }"), + ".a { &:hover { b: c }; x: y }" + ); + assert_eq!(set_in_a(".a { &:hover{b:c} }"), ".a { &:hover{b:c}; x: y }"); + assert_eq!( + set_in_a(".a {\n &:hover { b: c }\n}\n"), + ".a {\n &:hover { b: c };\n x: y\n}\n" + ); + assert_eq!( + set_in_a(".a { &:hover { b: c } &:focus { d: e } }"), + ".a { &:hover { b: c } &:focus { d: e }; x: y }" + ); +} + +#[test] +fn a_rule_before_a_declaration_leaves_the_declaration_to_be_copied() { + // The gap after a rule holds no separator, so the joint is the default. + assert_eq!( + set_in_a(".a { &:hover { b: c } z: w }"), + ".a { &:hover { b: c } z: w; x: y }" + ); + // The declaration's own `:` is the spelling to copy, past the rule. + assert_eq!( + set_in_a(".a { &:hover { b: c } z:w }"), + ".a { &:hover { b: c } z:w; x:y }" + ); + // And so is the gap after it, the first that has a member with a + // separator of its own before it. + assert_eq!( + set_in_a(".a { &:hover { b: c } z: w;q: r }"), + ".a { &:hover { b: c } z: w;q: r;x: y }" + ); +} + +#[test] +fn a_block_opening_with_a_declaration_is_copied_as_it_was() { + assert_eq!( + set_in_a(".a { z: w; &:hover { b: c } }"), + ".a { z: w; &:hover { b: c }; x: y }" + ); + assert_eq!(set_in_a(".a { z:w;q:r }"), ".a { z:w;q:r;x:y }"); +} + +#[test] +fn a_declaration_list_opening_with_a_rule_takes_a_declaration_after_it() { + let (_, decls) = formats(); + let mut e = Editor::open(b"&:hover{b:c}", decls).expect("opens"); + e.set_value(&[Segment::Key("a")], "blue").expect("sets"); + assert_eq!(e.source().expect("source"), "&:hover{b:c}; a: blue"); +} diff --git a/docs/tasks/a-flow-insert-copies-a-separator-from-a-nested-rule.md b/docs/tasks/a-flow-insert-copies-a-separator-from-a-nested-rule.md index 77ee457d..5cefdc75 100644 --- a/docs/tasks/a-flow-insert-copies-a-separator-from-a-nested-rule.md +++ b/docs/tasks/a-flow-insert-copies-a-separator-from-a-nested-rule.md @@ -1,7 +1,7 @@ ```fig title = A flow insert copies a separator from a nested rule part_of = [Tasks](/docs/tasks/tasks.md) -status = open +status = done created = 2026-11-06 updated = 2026-11-06 description = With flow_kv_sep_from_siblings, an insert takes its key-value separator from the first member and its joint from the gap after it; a fig-css nested rule has neither, so a declaration added to a block that opens with one is refused as NotFound or UnsupportedOperation @@ -9,6 +9,23 @@ description = With flow_kv_sep_from_siblings, an insert takes its key-value sepa # A flow insert copies a separator from a nested rule +**Status.** Done, in `fix(editor): a flow insert copies only a separator a +member wrote`. The test of a usable sibling is whether the bytes between its key +and value hold anything but space, which was simpler than comparing them with +`kv_sep` and is right for figl's `:`-mode, whose `: ` is not its `kv_sep`. An +insert copies from the first member that passes, and takes the joint from the +gap after that member. With none to copy, it writes what an empty mapping would +for the separator and the default joint. figl requires `=` or `:` in a flow +object, so every member there passes and nothing changes; `edits.json` now holds +`{a={b=1}}`, `{a={b=1}, c=2}` and the JSON-embedded form to say so. +`bindings/rust/fig/tests/sibling_separators.rs` holds the rest, with a small +registered language. + +Run against fig-css at 601c5c2 through a `[patch.crates-io]`, each failing `set` +below returns `Ok`, and `with_declaration("&:hover{b:c}", "a", Some("blue"))` +returns `&:hover{b:c}; a: blue`, whose `declaration` for `a` is `blue`. What is +left is fig-css taking this at fig's next release. + **Where.** `rust/fig-core/src/editor/mod.rs`, `insert_flow_map_entry` and `flow_map_joint`, for a dialect that sets `flow_kv_sep_from_siblings`. diff --git a/languages/figl/tests/edits.json b/languages/figl/tests/edits.json index da3255e4..40164da7 100644 --- a/languages/figl/tests/edits.json +++ b/languages/figl/tests/edits.json @@ -351,6 +351,16 @@ { "op": "insertValue", "args": [["p"], "c", 3], "expect": { "ok": true, "source": "p = {a=1, b=2, c=3}\n" } } ] }, + { + "id": "insert key after a flow mapping's nested object copies the separators beside it", + "note": "The bytes before a nested object's `{` are a real separator here, as they are not before a CSS rule's block.", + "source": "p = {a={b=1}}\nq = {a={b=1}, c=2}\nr = {\"a\": {\"b\": 1}}\n", + "steps": [ + { "op": "insertValue", "args": [["p"], "x", 1], "expect": { "ok": true, "source": "p = {a={b=1} x=1}\nq = {a={b=1}, c=2}\nr = {\"a\": {\"b\": 1}}\n" } }, + { "op": "insertValue", "args": [["q"], "x", 1], "expect": { "ok": true, "source": "p = {a={b=1} x=1}\nq = {a={b=1}, c=2, x=1}\nr = {\"a\": {\"b\": 1}}\n" } }, + { "op": "insertValue", "args": [["r"], "\"x\"", 1], "expect": { "ok": true, "source": "p = {a={b=1} x=1}\nq = {a={b=1}, c=2, x=1}\nr = {\"a\": {\"b\": 1}, \"x\": 1}\n" } } + ] + }, { "id": "insert key into a multi-line compact flow mapping writes no comma", "source": "p = {\n a=1\n}\n", diff --git a/rust/fig-core/src/editor/mod.rs b/rust/fig-core/src/editor/mod.rs index 64be5b52..1f63632b 100644 --- a/rust/fig-core/src/editor/mod.rs +++ b/rust/fig-core/src/editor/mod.rs @@ -5358,16 +5358,23 @@ impl<'l> Editor<'l> { last_end = last_end.max(self.flow_entry_end(parsed, kv)?); each = parsed.ast.next(&kv); } - // The separator: `kv_sep`, or the bytes the first entry writes - // between its key and value for a format whose flow objects fix - // their own mode. See `Syntax.flow_kv_sep_from_siblings`. + // The separator: `kv_sep`, or the bytes the first entry that has any + // writes between its key and value for a format whose flow objects + // fix their own mode. See `Syntax.flow_kv_sep_from_siblings`. let sep: &[u8] = if syn.flow_kv_sep_from_siblings { - let first_id = node.kind.as_mapping().flatten().ok_or(err!(NotFound))?; - let first = first_written_leaf(parsed, parsed.ast.node(first_id)); - let kv = kv_of(&first); - let key_end = parsed.span(&parsed.ast.node(kv.key)).end; - let value_start = parsed.span(&parsed.ast.node(kv.value)).start; - &source[key_end..value_start] + let mut copied = None; + let mut each = parsed.ast.child(&node)?; + while let Some(member) = each { + copied = written_kv_sep(source, parsed, member); + if copied.is_some() { + break; + } + each = parsed.ast.next(&member); + } + match copied { + Some(sep) => sep, + None => self.new_flow_kv_sep()?, + } } else { self.kv_sep()? }; @@ -5406,19 +5413,26 @@ impl<'l> Editor<'l> { /// non-empty flow mapping `node` and a new one on its line, the new /// one's key and value parted by `kv`. A format that copies its flow /// separators (`Syntax.flow_kv_sep_from_siblings`) takes the bytes - /// between the first two members when they share a line and hold - /// nothing but spaces and at most one `flow_entry_sep`. Otherwise an - /// object whose entries are spelled with `flow_map_kv_sep` is joined by - /// `flow_map_entry_sep` (fig's `{a=1 b=2}`), and any other by + /// between the first member with a key-value separator of its own and + /// the member after it, when they share a line and hold nothing but + /// spaces and at most one `flow_entry_sep`. A member with no separator + /// is passed over, since what ends it says nothing of what ends the + /// others: a nested rule in CSS needs nothing after its `}`. Otherwise + /// an object whose entries are spelled with `flow_map_kv_sep` is joined + /// by `flow_map_entry_sep` (fig's `{a=1 b=2}`), and any other by /// `flow_entry_sep` and a space. fn flow_map_joint<'a>(&'a self, parsed: &Document, node: Node<'_>, kv: &[u8]) -> Result> { let source = &self.source[..]; let syn = self.syntax(); if syn.flow_kv_sep_from_siblings { - let first = present(parsed.ast.child(&node)?)?; - if let Some(second) = parsed.ast.next(&first) { - let from = parsed.span(&first_written_leaf(parsed, first)).end; - let to = flow_entry_start(parsed, second); + let mut member = present(parsed.ast.child(&node)?)?; + while let Some(next) = parsed.ast.next(&member) { + if written_kv_sep(source, parsed, member).is_none() { + member = next; + continue; + } + let from = parsed.span(&first_written_leaf(parsed, member)).end; + let to = flow_entry_start(parsed, next); if to > from { let gap = &source[from..to]; let joint = Joint::split(gap, false); @@ -5428,6 +5442,7 @@ impl<'l> Editor<'l> { return Ok(joint); } } + break; } } let ws: &[u8] = b" \t"; @@ -5440,6 +5455,14 @@ impl<'l> Editor<'l> { Ok(Joint { lead: b"", token: syn.flow_entry_sep, trail: b" ", declared: false }) } + /// The separator of a flow entry with no neighbour to copy. A format + /// that spells flow entries apart from block ones says how: + /// `Syntax.flow_map_kv_sep`. + fn new_flow_kv_sep(&self) -> Result<&'static [u8]> { + let kv = self.syntax().flow_map_kv_sep; + if kv.is_empty() { self.kv_sep() } else { Ok(kv) } + } + /// Insert the first entry into an EMPTY flow mapping (`{}` / ZON's /// `.{}`): a tight `{key: value}` splice, padded by `flow_map_pad`. fn insert_flow_entry(&mut self, parsed: &Document, node: Node<'_>, span: Span, key_text: &[u8], value_text: &[u8]) -> Result<()> { @@ -5451,10 +5474,7 @@ impl<'l> Editor<'l> { let pad: &[u8] = if open_root { b"" } else { syn.flow_map_pad }; out.extend_from_slice(pad); out.extend_from_slice(key_text); - // A format that spells flow entries apart from block ones says - // how: `Syntax.flow_map_kv_sep`. - let kv = syn.flow_map_kv_sep; - out.extend_from_slice(if !kv.is_empty() { kv } else { self.kv_sep()? }); + out.extend_from_slice(self.new_flow_kv_sep()?); out.extend_from_slice(value_text); out.extend_from_slice(pad); // Just after '{' (or ZON's '.{'); an open root has no opener, and @@ -5922,6 +5942,20 @@ fn flow_entry_start(parsed: &Document, kv: Node<'_>) -> usize { parsed.span(&kv).start } +/// The bytes the flow member `member` writes between its key and value, or +/// `None` where they hold nothing but space. A member like that has no +/// separator to copy: fig-css reads a rule nested in a block as a selector +/// over a mapping, so `&:hover { b: c }` has a space before its value and +/// `&:hover{b:c}` nothing, where a declaration beside it writes `: `. +fn written_kv_sep<'s>(source: &'s [u8], parsed: &Document, member: Node<'_>) -> Option<&'s [u8]> { + let leaf = first_written_leaf(parsed, member); + let kv = kv_of(&leaf); + let key_end = parsed.span(&parsed.ast.node(kv.key)).end; + let value_start = parsed.span(&parsed.ast.node(kv.value)).start; + let sep = &source[key_end..value_start]; + (!trim(sep, b" \t\r\n").is_empty()).then_some(sep) +} + /// The value of the entry `kv` when it is a table made by dotted keys, /// written by entries of its parent rather than by a value of its own: a /// section whose name is written on its parent's lines or in its braces diff --git a/rust/fig-kit/src/manifest.rs b/rust/fig-kit/src/manifest.rs index 60a03858..fcc8ab77 100644 --- a/rust/fig-kit/src/manifest.rs +++ b/rust/fig-kit/src/manifest.rs @@ -511,10 +511,12 @@ pub struct Syntax { /// FIRST entry uses — the bytes between that entry's key and value — /// rather than writing `kv_sep`. True for fig, whose flow objects are /// either `=`-mode or `:`-mode (JSON-embedded) and may not mix the two, - /// so the right separator is whichever the object already uses. An empty - /// flow mapping has no first entry and takes `flow_map_kv_sep`, or else - /// `kv_sep`. With it, an insert into a flow object whose first two - /// members share a line also copies the bytes between them. + /// so the right separator is whichever the object already uses. An entry + /// with only space there has no separator to copy and is passed over, as + /// a nested rule in a CSS block is. A flow mapping with no entry to copy, + /// an empty one among them, takes `flow_map_kv_sep`, or else `kv_sep`. + /// With it, an insert into a flow object also copies the bytes after the + /// first entry with a separator, when the next member shares its line. pub flow_kv_sep_from_siblings: bool, /// Bytes written inside the braces around a freshly created single