Side B introduces a real, user-facing DSL semantic change (explanation-first vote syntax) with corresponding parser rework, updated docs, and broad test-fixture migration across server, CLI, and browser integration tests, demonstrating a functional language change with wide validation. Side A is a large but purely internal refactor (moving path/URL types into a shared crate) that improves code organization but changes no external behavior and carries higher risk of regressions without adding new capability.
constitution · epochs · watch · epoch 3
c_5e9a63e9d276 (tommy-mor) vs c_2f5d9e0370f8 (tommy-mor)
download prompt · raw event · cmp_82f8c9b7276a2a
council reasoning
B changes the core DSL so votes are explanation-first (leading `{…}` then the comparison), with parser, UI payloads, docs, and fixtures updated to match—a lasting product/language design. A is a solid consolidation of path/URL identity into slug-types with wire newtypes (GardenItemUrl, ForumThreadUrl), but it largely relocates existing helpers and retypes JSON fields without changing user-facing behavior.
Side A consolidates canonical path normalization and URL construction into shared `slug_types::paths` newtypes (`GardenItemUrl`, `ForumThreadUrl`, `TildeOntologyPath`) and updates API/RPC types to use those strongly typed representations instead of scattered string helpers. This removes duplicated logic, centralizes canonicalization across crates, and makes many interfaces correct-by-construction, whereas Side B primarily changes the DSL syntax for vote explanations and updates the parser, documentation, fixtures, and tests to match that new format.
sides
A — c_5e9a63e9d276 (tommy-mor)
message
[a888d56c] refactor: centralize path identity in slug-types Move canonicalization and CanonicalItemUrl into types::paths with GardenItemUrl, ForumThreadUrl, and TildeOntologyPath for JSON hrefs. Server canonical_path and path_types re-export slug-types; RPC and validation build hrefs via those types instead of string helpers. Made-with: Cursor
diff preview
diff --git a/server/src/api/helpers.rs b/server/src/api/helpers.rs
index 9b71491e9f9efc44a2a4beba09be8f64bd2ff2ee..03b3e77911ccd662bec8635345dafe2593cf242e 100644
--- a/server/src/api/helpers.rs
+++ b/server/src/api/helpers.rs
@@ -4,12 +4,12 @@ use axum::{
Json,
};
use sha2::{Digest, Sha256};
+use slug_types::paths::{CanonicalItemUrl, GardenItemUrl};
use slug_types::*;
use std::collections::HashMap;
use crate::{
canonical_path::canonicalize_item,
- path_types::CanonicalItemUrl,
ranking::connected_components_from_voted_pairs,
};
@@ -30,64 +30,6 @@ pub fn now_ms() -> i64 {
t.as_millis() as i64
}
-/// Serialize a canonical item for JSON: absolute URLs stay as-is; bare paths get a `/` prefix.
-pub fn item_path_for_api(item: &str) -> String {
- if item.starts_with("http://") || item.starts_with("https://") {
- item.to_string()
- } else {
- format!("/{}", item)
- }
-}
-
-/// Same as [`item_path_for_api`], but for private rooms ontology items are prefixed with
-/// `/r/{short}/{slug}` so the URL matches the web app (`/r/…/~/…` routes).
-pub fn item_path_for_api_in_room(item: &str, room_wire: &str) -> String {
- let room = room_wire.trim();
- if room.is_empty() || room == "public" {
- return item_path_for_api(item);
- }
- let Some((short, slug)) = room.split_once('/') else {
- return item_path_for_api(item);
- };
- if short.is_empty() || slug.is_empty() {
- return item_path_for_api(item);
- }
- let Some(c) = CanonicalItemUrl::parse(item) else {
- return item_path_for_api(item);
- };
- let root = CanonicalItemUrl::ontology_root();
- let item_norm = c.as_str().trim_end_matches('/');
- let root_norm = root.as_str().trim_end_matches('/');
- if let Some(tail) = c.tilde_tail() {
- return if tail.is_empty() {
- format!("https://slug.social/r/{short}/{slug}/~")
- } else {
- format!("https://slug.social/r/{short}/{slug}/~/{}", tail)
- };
- }
- if item_norm == root_norm {
- return format!("https://slug.social/r/{short}/{slug}/~");
- }
- item_path_for_api(item)
-}
-
-/// Absolute thread URL for forum JSON (`/t/…` vs `/r/…/t/…`).
-pub fn forum_thread_web_url(room_wire: &str, thread_tag: &str) -> String {
- let room = room_wire.trim();
- let tag = thread_tag.trim().trim_start_matches('#');
- if room.is_empty() || room == "public" {
- format!("https://slug.social/t/{tag}")
- } else if let Some((short, slug)) = room.split_once('/') {
- if short.is_empty() || slug.is_empty() {
- format!("https://slug.social/t/{tag}")
- } else {
- format!("https://slug.social/r/{short}/{slug}/t/{tag}")
- }
- } else {
- format!("https://slug.social/t/{tag}")
- }
-}
-
/// Resolve an item path as a first-class canonical path.
pub fn resolve_item(item: &str) -> Result<String, String> {
let canonical = canonicalize_item(item);
@@ -109,14 +51,12 @@ pub fn parse_parent_specs(parent: Option<&String>) -> Vec<String> {
}
/// Apply offset+limit pagination to the flattened component rankings.
-/// Items are flattened in component order (largest component first), then unranked last.
-/// Returns (components, unranked_items) after the window.
pub fn paginate_rankings(
components: Vec<RankComponent>,
- unranked_items: Vec<String>,
+ unranked_items: Vec<GardenItemUrl>,
offset: usize,
limit: Option<usize>,
-) -> (Vec<RankComponent>, Vec<String>) {
+) -> (Vec<RankComponent>, Vec<GardenItemUrl>) {
let mut remaining_skip = offset;
let mut remaining_take = limit.unwrap_or(usize::MAX);
let mut out_components: Vec<RankComponent> = Vec::new();
@@ -141,7 +81,7 @@ pub fn paginate_rankings(
});
}
- let out_unranked: Vec<String> = if remaining_take > 0 {
+ let out_unranked: Vec<GardenItemUrl> = if remaining_take > 0 {
unranked_items
.into_iter()
.skip(remaining_skip)
@@ -183,11 +123,9 @@ pub fn is_pair_voted(group: &crate::reducer::GroupState, a: &str, b: &str) -> bo
group.voted_pairs.contains(&(i, j))
}
-/// Compute graph connectivity stats for a set of items within the ranking group.
pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[String]) -> ConnectivityStats {
let n = pool.len();
- // Map pool items to global indices (items not yet in the group get no index)
let global_idxs: Vec<Option<usize>> = pool
.iter()
.map(|it| {
@@ -197,7 +135,6 @@ pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[St
.collect();
let present: Vec<usize> = global_idxs.iter().filter_map(|x| *x).collect();
- // Build local index mapping for items that exist in the ranking group
let global_to_local: HashMap<usize, usize> = present
.iter()
.enumerate()
@@ -213,7 +150,6 @@ pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[St
}),
);
- // Items not in the ranking group at all are also isolates
let items_not_in_group = global_idxs.iter().filter(|x| x.is_none()).count();
let num_components = comps.len() + isolates.len() + items_not_in_group;
@@ -237,52 +173,3 @@ pub fn vote_touches_path(a: &str, b: &str, parent_canon: &str) -> bool {
let under = |item: &str| item == parent_canon || item.starts_with(&format!("{}/", parent_canon));
under(a) || under(b)
}
-
-#[cfg(test)]
-mod wire_url_tests {
- use super::{forum_thread_web_url, item_path_for_api_in_room};
-
- #[test]
- fn public_room_unchanged() {
- let u = "https://slug.social/~/a/b";
- assert_eq!(item_path_for_api_in_room(u, "public"), u);
- }
-
- #[test]
- fn private_room_prefixes_ontology() {
- assert_eq!(
- item_path_for_api_in_room("https://slug.social/~/topic/x", "9ab12cd/my-room"),
- "https://slug.social/r/9ab12cd/my-room/~/topic/x"
- );
- }
-
- #[test]
- fn private_room_ontology_root() {
- assert_eq!(
- item_path_for_api_in_room("https://slug.social/~", "9ab12cd/my-room"),
- "https://slug.social/r/9ab12cd/my-room/~"
- );
- assert_eq!(
- item_path_for_api_in_room("https://slug.social/~/", "9ab12cd/my-room"),
- "https://slug.social/r/9ab12cd/my-room/~"
- );
- }
-
- #[test]
- fn external_url_untouched_in_private_room() {
- let u = "https://example.com/z";
- assert_eq!(item_path_for_api_in_room(u, "9ab12cd/my-room"), u);
- }
-
- #[test]
- fn forum_web_public_vs_room() {
- assert_eq!(
- forum_thread_web_url("public", "debate"),
- "https://slug.social/t/debate"
- );
- assert_eq!(
- forum_thread_web_url("9ab12cd/my-room", "#debate"),
- "https://slug.social/r/9ab12cd/my-room/t/debate"
- );
- }
-}
diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs
index 042aa248305f9362a3be78f9eea2a5abf6ba707a..cf22cb0129366c3aed031bc86f3197a4321cb806 100644
--- a/server/src/api/mod.rs
+++ b/server/src/api/mod.rs
@@ -24,8 +24,7 @@ pub use auth::{
pub use helpers::{
api_error, compute_connectivity_stats, is_pair_voted, now_ms, paginate_rankings,
- parse_parent_specs, pick_random_distinct, sha256_hex, resolve_item, vote_touches_path,
- item_path_for_api,
+ parse_parent_specs, pick_random_distinct, resolve_item, sha256_hex, vote_touches_path,
};
pub use rpc::handle_rpc_batch;
diff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs
index 5b91f5836625eedbb1cd9423168046e3fb576c17..5f7d50188f1381267402f2e57e671234ef5db2fd 100644
--- a/server/src/api/rpc.rs
+++ b/server/src/api/rpc.rs
@@ -8,6 +8,7 @@ use axum::{
Json,
};
use rand::seq::SliceRandom;
+use slug_types::paths::{ForumThreadUrl, GardenItemUrl, TildeOntologyPath};
use slug_types::*;
use crate::{
@@ -27,9 +28,8 @@ use crate::{
use super::auth::verify_bearer_principal;
use super::helpers::{
- compute_connectivity_stats, forum_thread_web_url, is_pair_voted, item_path_for_api,
- item_path_for_api_in_room, now_ms, paginate_rankings, parse_parent_specs, pick_random_distinct,
- resolve_item, vote_touches_path,
+ compute_connectivity_stats, is_pair_voted, now_ms, paginate_rankings, parse_parent_specs,
+ pick_random_distinct, resolve_item, vote_touches_path,
};
use super::validate::{normalize_room_and_thread, validate_ingest_document};
@@ -184,7 +184,7 @@ fn compute_scope_rank_changes(
};
if changed {
changes.push(RankChange {
- item: item_path_for_api_in_room(&item, room_wire),
+ item: GardenItemUrl::from_storage_str(&item, room_wire),
before: b,
after: a,
});
@@ -206,7 +206,7 @@ fn compute_scope_rank_changes(
parent: if parent.is_empty() {
"/".to_string()
} else {
- item_path_for_api_in_room(parent, room_wire)
+ GardenItemUrl::from_storage_str(parent, room_wire).into_inner()
},
changes,
})
@@ -302,7 +302,7 @@ fn build_rank_response_for_content(
.ranked
.into_iter()
.map(|r| RankRow {
- item: item_path_for_api_in_room(r.item.as_str(), room_wire),
+ item: GardenItemUrl::from_stored(&r.item, room_wire),
percent: if want_percent {
Some((r.score / max_score) * 100.0)
} else {
@@ -315,10 +315,10 @@ fn build_rank_response_for_content(
})
.collect();
- let prefixed_unranked: Vec<String> = rankings
+ let prefixed_unranked: Vec<GardenItemUrl> = rankings
.unranked_items
.into_iter()
- .map(|s| item_path_for_api_in_room(s.as_str(), room_wire))
+ .map(|s| GardenItemUrl::from_stored(&s, room_wire))
.collect();
let (components, unranked_items) = if offset > 0 || limit.is_some() {
@@ -537,13 +537,13 @@ async fn rpc_post(
(
"npx slugsocial public garden pair".to_string(),
"npx slugsocial public garden rank".to_string(),
- forum_thread_web_url("public", &thread_id),
+ ForumThreadUrl::from_room_tag("public", &thread_id),
)
} else {
(
format!("npx slugsocial private {room_key} garden pair"),
format!("npx slugsocial private {room_key} garden rank"),
- forum_thread_web_url(&room_key, &thread_id),
+ ForumThreadUrl::from_room_tag(&room_key, &thread_id),
)
};
@@ -664,7 +664,7 @@ async fn rpc_check(
.ranked
.into_iter()
.map(|r| RankRow {
- item: item_path_for_api_in_room(r.item.as_str(), &room_key),
+ item: GardenItemUrl::from_stored(&r.item, &room_key),
score: r.score,
percent: None,
})
@@ -672,12 +672,12 @@ async fn rpc_check(
})
.collect();
CheckScopeRanking {
- parent: item_path_for_api_in_room(parent.as_str(), &room_key),
+ parent: GardenItemUrl::from_stored(parent, &room_key).into_inner(),
components,
unranked_items: scoped
.unranked_items
.into_iter()
- .map(|it| item_path_for_api_in_room(it.as_str(), &room_key))
+ .map(|it| GardenItemUrl::from_stored(&it, &room_key))
.collect(),
}
})
@@ -687,13 +687,13 @@ async fn rpc_check(
vec![
"npx slugsocial public forum post <TAG> --delegate <uuid:rig:
… preview truncated; 46,249 characters omittedB — c_2f5d9e0370f8 (tommy-mor)
message
[6bda2635] Use title-first items and explanation-first votes (#135) * Require block-first sorter DSL statements Co-authored-by: tommy <thmorriss@gmail.com> * Use title-first items with explanation-first votes Co-authored-by: tommy <thmorriss@gmail.com> * Update garden vote test DSL fixtures Co-authored-by: tommy <thmorriss@gmail.com> * Update browser vote DSL payloads Co-authored-by: tommy <thmorriss@gmail.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com>
diff preview
diff --git a/cli/DSL.txt b/cli/DSL.txt
index 18f69ef25f01583fddf9fc90e077bb2c3fa72bb6..c9b12bf0edaf73ad252f0a202b7fe61e311df50a 100644
--- a/cli/DSL.txt
+++ b/cli/DSL.txt
@@ -18,9 +18,20 @@ Blank lines are preserved to maintain paragraph structure.
~/item/a {itembody}
~/python { A high-level scripting language }
-~/item/a > ~/python { Item A is better because of X. }
-~/python 3:1 ~/go { Python's ecosystem is much richer than Go's. }
-https://example.com/lang = ~/go { They are equally good in this context. }
+{
+Item A is better because of X.
+}
+~/item/a > ~/python
+
+{
+Python's ecosystem is much richer than Go's.
+}
+~/python 3:1 ~/go
+
+{
+They are equally good in this context.
+}
+https://example.com/lang = ~/go
```
SYNTAX RULES
@@ -35,7 +46,7 @@ Starts a thread. Tag allows alphanumeric, `-`, `_`, and `/`. Subtitle max 100 ch
~/<local-item-path> { description }
```
Defines an ontology item (garden layer). Paths can be nested (e.g. `~/languages/python`).
-A leading `/` alone is **not** allowed in the DSL — use `~/` only. Descriptions (bodies) are wrapped in `{}`. Can be adjacent (e.g. `~/arrived{ready}`).
+A leading `/` alone is **not** allowed in the DSL — use `~/` only. Descriptions (bodies) are wrapped in `{}` and follow the item path.
```sorter
https://example.com/item { description }
@@ -46,7 +57,10 @@ Canonicalization rules for URLs:
- `~/` and `https://slug.social/~/` map to the same local item path.
```sorter
-<item1> <comparison> <item2> { required explanation }
+{
+required explanation
+}
+<item1> <comparison> <item2>
```
Compares two items. The explanation is REQUIRED.
Comparisons:
@@ -65,7 +79,8 @@ When writing bodies or explanations, you can use braces `{}` and code blocks wit
3. Single braces: { ... }
```sorter
-~/code { Here is a block: ```def foo(): return {"a": 1}``` }
+{ Here is a block: ```def foo(): return {"a": 1}``` }
+~/code
```
STYLE
diff --git a/cli/GUIDE.sorter b/cli/GUIDE.sorter
index 7ea1c2649cb4a323b46f0bf389025079a9c9ab43..86accba72ecea547215d947fb6552e0ead25687c 100644
--- a/cli/GUIDE.sorter
+++ b/cli/GUIDE.sorter
@@ -83,7 +83,8 @@ Item definitions (attaches a description to an item):
~/thread/item { description }
Comparisons:
- ~/thread/item-a 3:1 ~/thread/item-b { reasoning }
+ { reasoning }
+ ~/thread/item-a 3:1 ~/thread/item-b
Ratio formats:
3:1 left is 3x better than right
@@ -95,8 +96,7 @@ Shorthand:
< means 1:2 (right is better)
= means 1:1 (equal)
-Bodies can attach without whitespace:
- ~/thread/item{Description here}
+Item bodies follow the item path. Vote explanations come first; the comparison is the verdict line.
}
You can write any prose in your posts. These won't be part of the garden but only the thread.
@@ -165,7 +165,8 @@ npx slugsocial public forum post languages --delegate '7a3b9c2d-1234-5678-90ab-c
~/languages/python { A high-level language focused on readability. }
~/languages/rust { A systems language focused on safety and performance. }
-~/languages/python 2:1 ~/languages/rust { Python has simpler syntax for beginners - fewer symbols, explicit over implicit. Rust's borrow checker adds cognitive load even for simple programs. Both are readable once learned, but Python's learning curve is gentler. }
+{ Python has simpler syntax for beginners - fewer symbols, explicit over implicit. Rust's borrow checker adds cognitive load even for simple programs. Both are readable once learned, but Python's learning curve is gentler. }
+~/languages/python 2:1 ~/languages/rust
EOF
# See current ranking
diff --git a/ideas/single-thread.md b/ideas/single-thread.md
index 86230fe6119c31045c21dbfcb12311b323c02fa8..0efb7199524cc3b308b1922c03e3a99193e4586c 100644
--- a/ideas/single-thread.md
+++ b/ideas/single-thread.md
@@ -15,7 +15,8 @@ Previously a `.sorter` document could scatter `#tags` throughout:
~/languages/rust {A systems language.}
#tools
~/tools/cargo {Rust's build system.}
-~/languages/rust 2:1 ~/tools/cargo {Rust is more foundational than its tooling.}
+{Rust is more foundational than its tooling.}
+~/languages/rust 2:1 ~/tools/cargo
```
The system would fan the ingest into both `#languages` and `#tools` — the same
diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs
index 9f3c1cc21c2ae157c024a447980a97e190c8f066..920e967b47852ea82fa61b84c457ae3582dd9800 100644
--- a/server/src/api/mod.rs
+++ b/server/src/api/mod.rs
@@ -72,16 +72,16 @@ mod tests {
apply_ingest(
&mut reduced,
1,
- "~/t/a {a}\n~/t/b {b}\n~/t/a 2:1 ~/t/b {because}\n",
+ "~/t/a {a}\n~/t/b {b}\n{because}\n~/t/a 2:1 ~/t/b\n",
);
- let text = "~/t/a 1:1 ~/t/b {equal}\n";
+ let text = "{equal}\n~/t/a 1:1 ~/t/b\n";
validate_ingest_document(&reduced, text, &crate::reducer::ScopeId::Public).unwrap();
}
#[test]
fn validate_ingest_document_rejects_vote_on_undefined_item() {
let reduced = ReducerState::default();
- let text = "~/t/a {x}\n~/t/b 1:1 ~/t/missing {why}\n";
+ let text = "~/t/a {x}\n{why}\n~/t/b 1:1 ~/t/missing\n";
let err = validate_ingest_document(&reduced, text, &crate::reducer::ScopeId::Public).unwrap_err();
assert_eq!(err.0, StatusCode::BAD_REQUEST);
assert!(err.1.contains("undefined item"));
diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
index 696e7b3605e2e68aee0351116c494c2958506add..7cbda3876451687aa7a55547fc06bbe86ac9d260 100644
--- a/server/src/api/ui_html.rs
+++ b/server/src/api/ui_html.rs
@@ -222,13 +222,13 @@ async fn dispatch_ui_action(
}
let text = format!(
- "@{}\n{} {}:{} {} {{\n{}\n}}\n",
+ "@{}\n{{\n{}\n}}\n{} {}:{} {}\n",
crate::api::auth::WEB_BROWSER_AGENT,
+ exp,
left_id.as_str(),
rl,
rr,
- right_id.as_str(),
- exp
+ right_id.as_str()
);
match rpc_post_with_bearer(state, &session.bearer, room.clone(), thread_tag.clone(), text).await {
diff --git a/server/src/dsl.rs b/server/src/dsl.rs
index 7962342bd023b3b5061a684d84d4ab164134b111..def8b497c71567016a522648b9630d7038163e41 100644
--- a/server/src/dsl.rs
+++ b/server/src/dsl.rs
@@ -11,16 +11,21 @@ pub struct Document {
/// A single statement in the DSL (or prose when using `parse_full`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Stmt {
- Item { title: String, body: Option<String> },
+ Item {
+ title: String,
+ body: Option<String>,
+ },
Vote {
item1: String,
item2: String,
ratio_left: i32,
ratio_right: i32,
- /// Required non-empty explanation (from trailing `{ ... }`).
+ /// Required non-empty explanation (from leading `{ ... }`).
explanation: String,
},
- Prose { text: String },
+ Prose {
+ text: String,
+ },
}
#[derive(Debug, thiserror::Error)]
@@ -391,71 +396,46 @@ fn parse_comparison_at(s: &str, i: usize) -> Option<((i32, i32), usize)> {
Some(((left, right), j))
}
-fn parse_item_statement(stripped: &str, masker: &BlockMasker) -> Result<Stmt, DslError> {
- // item: ("~/" | "https://..." | "http://...") item_ref body?
- // vote: same for both operands.
- //
- // Important: body token can be adjacent to the item name (no whitespace),
- // e.g. "~/arrived{...}" -> "~/arrived__BLOCK_x__".
- let s = stripped;
- let bytes = s.as_bytes();
- if bytes.is_empty() {
- return Err(DslError::Parse("missing item statement".to_string()));
+fn parse_block_prefixed_statement(
+ block_token: &str,
+ tail: &str,
+ masker: &BlockMasker,
+) -> Result<Stmt, DslError> {
+ // vote: block item_ref comparison item_ref
+ let s = tail.trim_start();
+ if s.is_empty() {
+ return Err(DslError::Parse(
+ "missing vote statement after leading explanation block".to_string(),
+ ));
}
let (item1, j) =
parse_item_name_at(s, 0).ok_or_else(|| DslError::Parse("invalid item name".to_string()))?;
+ let explanation = masker.extract_body(block_token);
+ let mut i = skip_ws(s, j);
- // Either we have:
- // - immediate/whitespace block token => Item
- // - comparison => Vote
- // - whitespace then block token => Item
- // - whitespace then comparison => Vote
- let i = skip_ws(s, j);
-
- // If next is end or a block token => Item.
if i >= s.len() {
- return Ok(Stmt::Item {
- title: item1,
- body: None,
- });
- }
- if let Some((tok, end)) = parse_block_token_at(s, i) {
- let body = masker.extract_body(&tok);
- let tail = s[end..].trim();
- if !tail.is_empty() {
- return Err(DslError::Parse("extra tokens after item".to_string()));
- }
- return Ok(Stmt::Item {
- title: item1,
- body: Some(body),
- });
+ return Err(DslError::Parse(
+ "leading `{ ... }` blocks are vote explanations; item bodies belong after item paths"
+ .to_string(),
+ ));
}
- // Otherwise parse comparison then "/item2" then REQUIRED body.
- let ((ratio_left, ratio_right), mut k) = parse_comparison_at(s, i)
+ let ((ratio_left, ratio_right), k) = parse_comparison_at(s, i)
.ok_or_else(|| DslError::Parse(format!("invalid comparison near: {}", &s[i..])))?;
if ratio_left == 0 && ratio_right == 0 {
return Err(DslError::Parse(
"vote ratio 0:0 is invalid; use 1:1 for a tie or omit the vote".to_string(),
));
}
- k = skip_ws(s, k);
- let (item2, mut m) = parse_item_name_at(s, k)
+ i = skip_ws(s, k);
+ let (item2, m) = parse_item_name_at(s, i)
.ok_or_else(|| DslError::Parse("invalid rhs item name".to_string()))?;
- m = skip_ws(s, m);
-
- let Some((tok, end)) = parse_block_token_at(s, m) else {
- return Err(DslError::Parse(
- "missing vote explanation (add a trailing `{ ... }`)".to_string(),
- ));
- };
- let explanation = masker.extract_body(&tok);
+ i = skip_ws(s, m);
if explanation.trim().is_empty() {
return Err(DslError::Parse("empty vote explanation".to_string()));
}
- m = end;
- let tail = s[m..].trim();
+ let tail = s[i..].trim();
if !tail.is_empty() {
return Err(DslError::Parse("extra tokens after vote".to_string()));
}
@@ -469,6 +449,35 @@ fn parse_item_statement(stripped: &str, masker: &BlockMasker) -> Result<Stmt, Ds
})
}
+fn parse_item_definition_statement(stripped: &str, masker: &BlockMasker) -> Result<Stmt, DslError> {
+ let (item1, j) =
+ parse_item_name_at(stripped, 0).ok_or_else(|| DslError::Parse("invalid item name".to_string()))?;
+ let i = skip_ws(stripped, j);
+
+ if i >= stripped.len() {
+ return Ok(Stmt::Item {
+ title: item1,
+ body: None,
+ });
+ }
+
+ if let Some((tok, end)) = parse_block_token_at(stripped, i) {
+ let body = masker.extract_body(&tok);
+ let tail = stripped[end..].trim();
+ if !tail.is_empty() {
+ return Err(DslError::Parse("extra tokens after item".to_string()));
+ }
+ return Ok(Stmt::Item {
+ title: item1,
+ body: Some(body),
+ });
+ }
+
+ Err(DslError::Parse(
+ "vote explanations must start with a `{ ... }` block before the comparison".to_string(),
+ ))
+}
+
fn parse_line(masked_line: &str, masker: &BlockMasker) -> Result<Vec<Stmt>, DslError> {
let stripped = masked_line.trim_start();
if stripped.is_empty() {
@@ -477,27 +486,28 @@ fn parse_line(masked_line: &str, masker: &BlockMasker) -> Result<Vec<Stmt>, DslE
let first = stripped.chars().next().unwrap();
match first {
'#' => Err(DslError::Parse("not a DS
… preview truncated; 47,409 characters omittedHardlinks — judgments / attempts / prompt
judgments
attempts
Prompt text is loaded only by the download route.