Skip to main content

delvewright_dsl/
ids.rs

1//! Type-prefixed, kebab-case identifier newtypes (spec-0001 "IDs").
2//!
3//! IDs deserialize permissively from any JSON string so that *syntax* violations
4//! surface as validation diagnostics (`DW0110`) rather than opaque parse errors.
5//! Call [`is_valid_syntax`](AreaId::is_valid_syntax) during validation.
6
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9
10/// True if `s` is a single kebab-case token: `[a-z0-9]+(-[a-z0-9]+)*`.
11pub(crate) fn is_kebab(s: &str) -> bool {
12    !s.is_empty()
13        && s.split('-').all(|seg| {
14            !seg.is_empty()
15                && seg
16                    .bytes()
17                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
18        })
19}
20
21/// True if `s` is exactly `<prefix>/<kebab>`.
22pub(crate) fn is_prefixed(s: &str, prefix: &str) -> bool {
23    match s.strip_prefix(prefix).and_then(|r| r.strip_prefix('/')) {
24        Some(rest) => is_kebab(rest),
25        None => false,
26    }
27}
28
29macro_rules! prefixed_id {
30    ($(#[$m:meta])* $name:ident, $prefix:literal) => {
31        $(#[$m])*
32        #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema)]
33        #[serde(transparent)]
34        #[schemars(transparent)]
35        pub struct $name(pub String);
36
37        impl $name {
38            /// The required type prefix (`area`, `npc`, …).
39            pub const PREFIX: &'static str = $prefix;
40
41            /// Borrow the raw id string.
42            pub fn as_str(&self) -> &str {
43                &self.0
44            }
45
46            /// True if the id is well-formed: `<prefix>/<kebab>`.
47            pub fn is_valid_syntax(&self) -> bool {
48                is_prefixed(&self.0, Self::PREFIX)
49            }
50
51            /// The form THIS id has to take, for the diagnostic that rejected
52            /// one — `` `npc/<kebab>` ``, `` `dlg/<kebab>` ``, and so on.
53            ///
54            /// A refusal that says only "ids must be lowercase kebab-case with
55            /// their type prefix" and then lists three examples of other types
56            /// has told the author the general rule and withheld the one fact
57            /// they were missing: which prefix THIS field takes. The prefix is
58            /// a property of the id type, so the answer is derived from the
59            /// type at every site rather than hand-written per site — the
60            /// per-section refusals that already name their own prefix
61            /// (`wave/`, `trap/`, `loot/`, …) are that fact copied by hand,
62            /// which is exactly why the general path never had it.
63            pub fn syntax_form(&self) -> String {
64                format!("`{}/<kebab>`", Self::PREFIX)
65            }
66        }
67
68        impl std::fmt::Display for $name {
69            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70                f.write_str(&self.0)
71            }
72        }
73    };
74}
75
76prefixed_id!(
77    /// Area id: `area/<kebab>` (stage 1).
78    AreaId, "area");
79prefixed_id!(
80    /// NPC id: `npc/<kebab>` (stage 2).
81    NpcId, "npc");
82prefixed_id!(
83    /// Class id: `class/<kebab>` (stage 3).
84    ClassId, "class");
85prefixed_id!(
86    /// Quest id: `quest/<kebab>` (stages 4 & 5).
87    QuestId, "quest");
88prefixed_id!(
89    /// Prefab id: `prefab/<kebab>` (resolved against `prefabs/` at compile time).
90    PrefabId, "prefab");
91prefixed_id!(
92    /// Prefab-pool id: `pool/<kebab>` (jigsaw multi-piece assembly, stage 1;
93    /// resolved against `prefabs/` metadata at compile time).
94    PoolId, "pool");
95prefixed_id!(
96    /// Dialogue node id: `dlg/<kebab>` (stage-local to an NPC's dialogue graph).
97    DialogueId, "dlg");
98prefixed_id!(
99    /// Objective id: `obj/<kebab>` (stage-local to stage 5).
100    ObjectiveId, "obj");
101prefixed_id!(
102    /// Anchor id: `anchor/<kebab>` (resolved against prefab metadata).
103    AnchorId, "anchor");
104prefixed_id!(
105    /// Wave id: `wave/<kebab>` (stage-5 `waves` section, DSL v0.3).
106    WaveId, "wave");
107prefixed_id!(
108    /// Flag id: `flag/<kebab>` (declared by `set-flag` effects, read by
109    /// `requires_flags`, DSL v0.3). No separate declaration list — the set of
110    /// flags is exactly those produced by some `set-flag` effect.
111    FlagId, "flag");
112prefixed_id!(
113    /// Runtime-state id: `state/<kebab>` (stage-5 `state` section, DSL v0.10,
114    /// spec-0031). A named, scoped, integer-valued datum.
115    ///
116    /// Unlike [`FlagId`] this one **is** declared. A datum's scope (per-player or
117    /// party-wide) is a multiplayer semantic that no inference can supply, and a
118    /// counter — unlike a monotonic "this happened" flag — has an initial value
119    /// that only a declaration can state.
120    StateId, "state");
121prefixed_id!(
122    /// Environment-trigger id: `trigger/<kebab>` (stage-5 `triggers` section,
123    /// DSL v0.4). Unique within the stage-5 triggers namespace.
124    TriggerId, "trigger");
125prefixed_id!(
126    /// Scripted-actor id: `actor/<kebab>` (stage-5 `actors` section, DSL v0.6,
127    /// spec-0014). Unique within the stage-5 actors namespace; the puppet body
128    /// is tagged `dw_actor_<kebab>`.
129    ActorId, "actor");
130prefixed_id!(
131    /// Trap id: `trap/<kebab>` (stage-5 `traps` section, DSL v0.6, spec-0011).
132    /// Unique within the stage-5 traps namespace.
133    TrapId, "trap");
134prefixed_id!(
135    /// Timed-gate id: `timed-gate/<kebab>` (stage-5 `timed_gates` section,
136    /// spec-0016 §4). Unique within the stage-5 timed-gate namespace.
137    TimedGateId, "timed-gate");
138prefixed_id!(
139    /// Ambush id: `ambush/<kebab>` (stage-5 `ambushes` section, spec-0016 §3).
140    /// Unique within the stage-5 ambushes namespace; the derived environment
141    /// trigger is named `trigger/<kebab>` from the same local id.
142    AmbushId, "ambush");
143prefixed_id!(
144    /// Shortcut id: `shortcut/<kebab>` (stage-5 `shortcuts` section, spec-0016 §2).
145    /// Unique within the stage-5 shortcuts namespace.
146    ShortcutId, "shortcut");
147prefixed_id!(
148    /// Branch-point id: `branch-point/<kebab>` (stage-4 `branch_points`, DSL v0.8,
149    /// spec-0025). One declared fork in the story: the flags it forks on, the quest
150    /// it opens at, and the branches it offers.
151    BranchPointId, "branch-point");
152prefixed_id!(
153    /// Branch id: `branch/<kebab>` (stage-4 `branch_points[].branches`, DSL v0.8,
154    /// spec-0025). One alternative of a branch point. Unique campaign-wide, because
155    /// it names the emitted `validation/branch-chronicle-<kebab>.md`.
156    BranchId, "branch");
157prefixed_id!(
158    /// Ending id: `ending/<kebab>` (DSL v0.8, spec-0025). Declared on the
159    /// `campaign-complete` effect that ends the delve that way, and referenced by
160    /// the branch that runs to it. There is no separate declaration list — the set
161    /// of endings is exactly those named by some `campaign-complete`, the same rule
162    /// [`FlagId`] follows.
163    EndingId, "ending");
164prefixed_id!(
165    /// Loot-fill id: `loot/<kebab>` (stage-5 `loot` section, spec-0021). Unique
166    /// within the stage-5 loot namespace.
167    LootId, "loot");
168prefixed_id!(
169    /// Lethal-volume id: `lethal/<kebab>` (stage-5 `lethal_volumes` section, DSL
170    /// v0.10, spec-0031). Unique within the stage-5 lethal-volume namespace; it
171    /// names the volume's emitted tick function, its l10n key, and the volume a
172    /// completability finding blames.
173    LethalVolumeId, "lethal");
174prefixed_id!(
175    /// Shop id: `shop/<kebab>` (stage-5 `shops` section, DSL v0.10, spec-0032).
176    /// Unique within the stage-5 shop namespace; it names the shop's interaction
177    /// affordance, its dialog, its `/trigger` routing value and its l10n keys.
178    ShopId, "shop");
179prefixed_id!(
180    /// Recovery-stake id: `stake/<kebab>` (stage-5 `stakes` section, DSL v0.10,
181    /// spec-0032). Unique within the stage-5 stake namespace; it names the
182    /// per-player ledger objectives, the marker hardware's tag and the l10n key of
183    /// the line a collection says.
184    StakeId, "stake");
185prefixed_id!(
186    /// Edit-batch id: `batch/<kebab>` (stage-7 `world-edits` batches, DSL v0.6,
187    /// spec-0017). Unique within the edit script; also the batch's snapshot name
188    /// and its seed-stream label, so renaming a batch deliberately reseeds it.
189    EditBatchId, "batch");
190prefixed_id!(
191    /// Named edit region: `region/<kebab>` (stage-7 `select` verb, DSL v0.6,
192    /// spec-0017). Scoped to its batch; later edits in the batch refer back to it.
193    RegionId, "region");
194prefixed_id!(
195    /// Layout-graph node id: `node/<kebab>` (spec-0049 §3.1). A **place** — a
196    /// room, a courtyard, a stretch of shore, a cavern — named before any
197    /// coordinate exists. Unique within the layout graph.
198    NodeId, "node");
199prefixed_id!(
200    /// Layout-graph edge id: `edge/<kebab>` (spec-0049 §3.1). A connection
201    /// between two places, of a declared class. Unique within the layout graph.
202    EdgeId, "edge");
203prefixed_id!(
204    /// Geometry-brief fact id: `fact/<kebab>` (spec-0049 §4.2). A number with a
205    /// name, taken from the whole map's written brief. Unique within the brief;
206    /// a site plan's `identities[]` bind to these.
207    FactId, "fact");
208prefixed_id!(
209    /// Site-plan datum id: `datum/<kebab>` (spec-0049 §4.1). A named ground
210    /// plane a box's floor sits on. Unique within the site plan.
211    DatumId, "datum");
212prefixed_id!(
213    /// Site-plan volume id: `volume/<kebab>` (spec-0049 §4.1). A mass the WHOLE
214    /// owns — the mountain a cave system is inside, the ground under a village,
215    /// the sky a silhouette needs kept empty. Unique within the site plan.
216    VolumeId, "volume");
217prefixed_id!(
218    /// Site-plan view id: `view/<kebab>` (spec-0049 §4.1). A named exterior
219    /// vantage the walk judges the silhouette from. Unique within the site plan.
220    ViewId, "view");
221
222/// Campaign id: a bare kebab-case token (no type prefix).
223#[derive(
224    Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema,
225)]
226#[serde(transparent)]
227#[schemars(transparent)]
228pub struct CampaignId(pub String);
229
230impl CampaignId {
231    /// Borrow the raw id string.
232    pub fn as_str(&self) -> &str {
233        &self.0
234    }
235
236    /// True if the id is a bare kebab-case token.
237    pub fn is_valid_syntax(&self) -> bool {
238        is_kebab(&self.0)
239    }
240}
241
242impl std::fmt::Display for CampaignId {
243    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244        f.write_str(&self.0)
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    #[test]
253    fn kebab_rules() {
254        assert!(is_kebab("open-the-door"));
255        assert!(is_kebab("keep"));
256        assert!(is_kebab("area1"));
257        assert!(!is_kebab("Open"));
258        assert!(!is_kebab("open_the_door"));
259        assert!(!is_kebab("open--the"));
260        assert!(!is_kebab("-open"));
261        assert!(!is_kebab(""));
262    }
263
264    #[test]
265    fn prefixed_rules() {
266        assert!(AreaId("area/keep".into()).is_valid_syntax());
267        assert!(!AreaId("area/Keep".into()).is_valid_syntax());
268        assert!(!AreaId("keep".into()).is_valid_syntax());
269        assert!(!AreaId("npc/keeper".into()).is_valid_syntax());
270        assert!(NpcId("npc/keeper".into()).is_valid_syntax());
271    }
272}