1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
//! A pure Rust dialogue system.
//!
//! Replique reads dialogues written in plain text, compiles them, and runs them
//! on a small virtual machine. It knows nothing about any engine: the VM hands
//! out events (*say this line*, *offer these choices*, *run this command*)
//! and waits for the caller to answer. [`bevy_replique`] is the Bevy plugin
//! built on top of this crate.
//!
//! [`bevy_replique`]: https://docs.rs/bevy_replique
//!
//! # The format
//!
//! ```text
//! := start
//! Alice: Hi! How are you?
//! -> Good, thanks!
//! Alice: Glad to hear it.
//! -> Not great.
//! Alice: Oh no, what happened?
//! => end
//! ---
//! ```
//!
//! | Syntax | Meaning |
//! | ------------------------------------ | ----------------------------------------------- |
//! | `:= name` | Start a node named `name` |
//! | `---` | End the current node |
//! | `Speaker: text` | A line of dialogue |
//! | `-> text` | A choice offered to the player |
//! | `>> command(arg1, arg2)` | A command to execute on the host |
//! | `=> name` | Jump to the node `name` |
//! | `[let $var = value]` | Set a variable |
//! | `[$var]` | Insert a value into the line |
//! | `[if cond]`, `[elif cond]`, `[else]` | Play a block only under a condition |
//! | `[while cond]` | Repeat a block, with `[break]` and `[continue]` |
//! | `#name`, `#name:value` | A tag on a line or on a choice |
//!
//! # Variables, conditions and loops
//!
//! Variables hold numbers, strings, booleans and dictionaries. Anything written
//! between `[` and `]` inside a line is evaluated and inserted where it stands:
//!
//! ```text
//! := shop
//! [let $gold = 12]
//! [let $player = {name: "Alice", hp: 7}]
//!
//! Merchant: Welcome [$player.name]! You have [$gold] coins.
//!
//! [if $gold >= 10]
//! Merchant: The lantern is yours.
//! [let $gold = $gold - 10]
//! [elif $gold > 0]
//! Merchant: Not quite enough, come back later.
//! [else]
//! Merchant: Come back when you can pay.
//!
//! [while $gold > 0]
//! [let $gold = $gold - 1]
//! >> ring_bell()
//!
//! Merchant: [$player.name], you are leaving with [$gold] coins.
//! ---
//! ```
//!
//! [`DialogueVm::vars`] reads back every variable a run has written.
//!
//! [`DialogueVm::vars`]: vm::DialogueVm::vars
//!
//! `has` tells whether a dictionary holds a key, whatever the value under it.
//! The key is a bare word, a string or a variable, and only the dictionary
//! itself is searched, not the ones nested in it:
//!
//! ```rust
//! use replique::RepliqueFile;
//! use replique::vm::{DialogueEvent, DialogueVm};
//!
//! let file = RepliqueFile::from_source(
//! r#":= start
//! [let $stats = {strength: 12}]
//! [if $stats has strength]
//! Alice: I can lift that.
//! [if not ($stats has magic)]
//! Alice: No spell from me, though.
//! ---
//! "#,
//! );
//! assert!(!file.has_errors());
//!
//! let mut vm = DialogueVm::default();
//! let DialogueEvent::Say { text, .. } = vm.start(file.dialogue.unwrap(), "start").unwrap()
//! else {
//! panic!("expected a line");
//! };
//! assert_eq!(text, "I can lift that.");
//! ```
//!
//! Asked of a string instead of a dictionary, `has` goes to the host: in
//! `[if Alice has Angry]`, [`RepliqueHost::has_feature`] says whether the
//! subject `Alice` has the feature `Angry`.
//!
//! [`RepliqueHost::has_feature`]: host::RepliqueHost::has_feature
//!
//! # Tags
//!
//! A tag is what a line says about itself rather than to the player: a mood,
//! a sound to play, an id. It is a word of its own, `#name` or `#name:value`,
//! written at the start or at the end of the text, and it reaches the caller
//! apart from that text:
//!
//! ```rust
//! use replique::RepliqueFile;
//! use replique::dialogue::Tag;
//! use replique::vm::{DialogueEvent, DialogueVm};
//!
//! let file = RepliqueFile::from_source(
//! ":= start\nAlice: #angry Give it back! #sound:alice_01\n---\n",
//! );
//!
//! let mut vm = DialogueVm::default();
//! let DialogueEvent::Say { text, tags, .. } =
//! vm.start(file.dialogue.unwrap(), "start").unwrap()
//! else {
//! panic!("expected a line");
//! };
//!
//! assert_eq!(text, "Give it back!");
//! assert_eq!(tags, [Tag::new("angry"), Tag::with_value("sound", "alice_01")]);
//! ```
//!
//! A `#` only opens a tag after a blank and before a letter, so `C#` and `#1`
//! are text, and `\#angry` writes the word with its `#`. A tag in the middle
//! of a line is not read: it stays in the text, with a warning.
//!
//! A choice takes tags the same way, `-> #hostile Attack #cost:3`, and each
//! [`Choice`] of a [`DialogueEvent::Choices`] carries its own.
//!
//! [`Choice`]: vm::Choice
//! [`DialogueEvent::Choices`]: vm::DialogueEvent::Choices
//!
//! # Schema
//!
//! With a [`RepliqueSchema`], the parsed dialogue can be validated against
//! speaker, tags, functions and commands.
//!
//! ```rust
//! use replique::parser::parse;
//! use replique::parser::validation::RepliqueSchema;
//!
//! let schema = RepliqueSchema::from_toml(
//! r#"
//! speakers = ["Robin", "Fanny"]
//!
//! [tags]
//! sad = { scope = ["Fanny"] }
//!
//! [commands]
//! change_mood = "2"
//! "#,
//! )
//! .unwrap();
//!
//! let mut parsed = parse(
//! ":= start\nFany: Hi!\nRobin: #sad Hello.\n>> change_mood(Fanny)\n---\n",
//! );
//! parsed.validate(&schema);
//!
//! let codes: Vec<_> = parsed.diagnostics.iter().map(|d| d.kind.code()).collect();
//! assert_eq!(codes, ["unknown-speaker", "tag-out-of-scope", "wrong-arity"]);
//! ```
//!
//! What a schema finds is a warning: the dialogue still compiles and runs.
//! Each section is optional and is not checked when empty. The [`builtins`]
//! are known to every schema. See [`parser::validation`] for the format of the file.
//!
//! [`RepliqueSchema`]: parser::validation::RepliqueSchema
//!
//! # Compiling
//!
//! [`RepliqueFile`] is the front door: it parses and compiles a source in one
//! step, and keeps the [`Diagnostics`] either way. A file with errors yields no
//! [`Dialogue`], so check [`RepliqueFile::has_errors`] before running anything.
//!
//! ```rust
//! use replique::RepliqueFile;
//! use replique::parser::diagnostic::Color;
//!
//! let file = RepliqueFile::from_source(":= start\nAlice: Hi!\n=> nope\n---\n");
//!
//! assert!(file.has_errors());
//! print!("{}", file.render_diagnostics(Color::Never));
//! ```
//!
//! [`Diagnostics`]: parser::diagnostic::Diagnostics
//! [`Dialogue`]: dialogue::Dialogue
//!
//! # Running
//!
//! [`DialogueVm`] is a coroutine: it walks the dialogue until it reaches
//! something only the caller can handle, then suspends and returns a
//! [`DialogueEvent`]. Answering it with [`DialogueVm::resume`] carries on.
//!
//! ```rust
//! use replique::RepliqueFile;
//! use replique::vm::{DialogueEvent, DialogueVm, ResumeEvent};
//!
//! let file = RepliqueFile::from_source(
//! ":= start\nAlice: Hi!\n-> Hello\n Alice: Hello!\n-> Bye\n Alice: Bye!\n---\n",
//! );
//! let dialogue = file.dialogue.unwrap();
//!
//! let mut vm = DialogueVm::default();
//! let mut event = vm.start(dialogue, "start").unwrap();
//!
//! loop {
//! event = match event {
//! DialogueEvent::Say { speaker, text, .. } => {
//! println!("{}: {}", speaker.unwrap_or_default(), text);
//! vm.resume(ResumeEvent::Advance).unwrap()
//! }
//! // A real game would show these and wait for the player.
//! DialogueEvent::Choices { .. } => vm.resume(ResumeEvent::Select(0)).unwrap(),
//! DialogueEvent::Finished => break,
//! _ => vm.resume(ResumeEvent::Advance).unwrap(),
//! };
//! }
//! ```
//!
//! A run never panics on a malformed dialogue: every way it can go wrong is a
//! [`VmError`], including the step limit that catches nodes jumping to each
//! other forever.
//!
//! [`DialogueVm`]: vm::DialogueVm
//! [`DialogueVm::resume`]: vm::DialogueVm::resume
//! [`DialogueEvent`]: vm::DialogueEvent
//! [`VmError`]: vm::VmError
//!
//! # Commands and functions
//!
//! A `>> command(...)` *does* something. It surfaces as
//! [`DialogueEvent::Command`], which suspends the VM like a line does, so an
//! animation or a sound can run to completion before the dialogue moves on.
//!
//! A `[function(...)]` *answers* something, and never suspends. The VM resolves
//! it through the [`RepliqueHost`] the caller passes to
//! [`DialogueVm::start_with`] and [`DialogueVm::resume_with`]. The same host
//! answers `has` when it is asked of a subject rather than of a dictionary:
//!
//! ```rust
//! use std::collections::HashMap;
//!
//! use replique::RepliqueFile;
//! use replique::dialogue::Value;
//! use replique::host::{HostError, RepliqueHost};
//! use replique::vm::{DialogueEvent, DialogueVm};
//!
//! struct Game {
//! gold: i64,
//! moods: HashMap<&'static str, &'static str>,
//! }
//!
//! impl RepliqueHost for Game {
//! fn call(&mut self, name: &str, _args: Vec<Value>) -> Result<Value, HostError> {
//! match name {
//! "gold" => Ok(Value::Int(self.gold)),
//! _ => Err(HostError::UnknownFunction(name.into())),
//! }
//! }
//!
//! fn has_feature(&mut self, subject: &str, name: &str) -> Result<bool, HostError> {
//! if !["Angry", "Happy"].contains(&name) {
//! return Err(HostError::UnknownFeature(name.into()));
//! }
//!
//! match self.moods.get(subject) {
//! Some(mood) => Ok(*mood == name),
//! None => Err(HostError::UnknownSubject(subject.into())),
//! }
//! }
//! }
//!
//! let file = RepliqueFile::from_source(
//! r#":= start
//! [if Alice has Angry]
//! Alice: Give me back my [gold()] coins!
//! [else]
//! Alice: You have [gold()] coins.
//! ---
//! "#,
//! );
//! let dialogue = file.dialogue.unwrap();
//!
//! let mut game = Game {
//! gold: 12,
//! moods: HashMap::from([("Alice", "Angry")]),
//! };
//! let mut vm = DialogueVm::default();
//!
//! let DialogueEvent::Say { text, .. } = vm.start_with(&mut game, dialogue, "start").unwrap()
//! else {
//! panic!("expected a line");
//! };
//! assert_eq!(text, "Give me back my 12 coins!");
//! ```
//!
//! The [`builtins`] are available to every dialogue, whatever the host.
//!
//! [`DialogueEvent::Command`]: vm::DialogueEvent::Command
//! [`RepliqueHost`]: host::RepliqueHost
//! [`DialogueVm::start_with`]: vm::DialogueVm::start_with
//! [`DialogueVm::resume_with`]: vm::DialogueVm::resume_with
//!
//! # Modules
//!
//! - [`parser`] turns a source into an AST and [`Diagnostics`].
//! - [`dialogue`] is the compiled form the VM walks, and its [`Value`] type.
//! - [`vm`] runs it.
//! - [`host`] is how a dialogue calls into the game.
//! - [`builtins`] are the functions every dialogue can call.
//!
//! [`Value`]: dialogue::Value
use ;
use crate::;