achitekfile 0.2.0

A tree-sitter backed semantic parser for the Achitekfile DSL
Documentation
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Domain model types for Achitekfile source.
//!
//! This module holds the Achitekfile representation that sits between the raw
//! Tree-sitter syntax tree and consumers.
//!
//! The parser layer answers "what syntax tree did Tree-sitter produce?" while
//! this layer should answer "what Achitekfile concepts were found in the
//! source?"
//!
//! There are two model families because Achitekfile consumers have different
//! tolerance for invalid source:
//!
//! - [`AchitekFile`] is the recovering model. It is designed for editor and
//!   diagnostic workflows where the source may be incomplete, malformed, or
//!   mid-edit. Fields that may be missing are represented with [`Option`], and
//!   recovered values can be wrapped in [`Spanned`] so tools can connect model
//!   values back to source ranges. Language servers, formatters, documentation
//!   generators, and rich CLI validation should generally start here.
//! - [`ValidAchitekFile`] is the strict model. It represents an Achitekfile
//!   after validation has proven that required structure exists and prompt data
//!   is complete enough to execute. Runtime consumers such as the Achitek CLI
//!   should reach for this model when scaffolding projects, evaluating
//!   dependencies, or applying prompt validation rules.
//!
//! The split keeps editor tooling useful while the user is still typing without
//! weakening the runtime contract. Invalid source can still produce a useful
//! [`AchitekFile`] plus diagnostics, while execution can require a
//! [`ValidAchitekFile`] and avoid repeatedly checking whether required values
//! are present.
//!
//! Keep Tree-sitter implementation details out of these types. Model values
//! should describe Achitek concepts such as blueprints, prompts, prompt types,
//! defaults, validation rules, and dependency expressions. When a value needs
//! to point back into source text, prefer crate-owned range types such as
//! [`TextRange`] instead of exposing Tree-sitter nodes directly.

use super::{
    TextRange,
    sort::{Graph, SortError, sort_graph},
};
use std::{collections::HashMap, vec};

/// A value paired with the source range that produced it.
///
/// Spans let editor-facing consumers connect recovered model values back to the
/// original source text without exposing Tree-sitter nodes.
///
/// # Examples
///
/// ```
/// let source = r#"
/// blueprint {
///   version = "1.0.0"
///   name = "web-app"
/// }
/// "#;
///
/// let analysis = achitekfile::analyze(source)?;
/// let version = analysis
///     .file()
///     .blueprint()
///     .version
///     .as_ref()
///     .map(|spanned| spanned.as_ref().as_str());
///
/// assert_eq!(version, Some("1.0.0"));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Spanned<T> {
    /// Recovered model value.
    pub value: T,
    /// Source range that produced the value.
    pub range: TextRange,
}

impl<T> AsRef<T> for Spanned<T> {
    fn as_ref(&self) -> &T {
        &self.value
    }
}

impl<T> AsMut<T> for Spanned<T> {
    fn as_mut(&mut self) -> &mut T {
        &mut self.value
    }
}

/// Recovering blueprint metadata.
///
/// The recovering model keeps fields optional because invalid source may omit
/// required blueprint attributes. A later validation step can turn this into a
/// [`ValidBlueprint`] once required fields are known to be present.
///
/// See [`AchitekFile`] for an example of reading recovered blueprint metadata.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Blueprint {
    /// Source range for the recovered `blueprint { ... }` block.
    ///
    /// This is `None` when no blueprint block was recovered. Diagnostics for
    /// missing blueprint attributes can use this range to point at the block
    /// that should contain the missing field.
    pub range: Option<TextRange>,
    /// Achitekfile format version declared by the blueprint.
    pub version: Option<Spanned<String>>,
    /// Blueprint name.
    pub name: Option<Spanned<String>>,
    /// Optional blueprint description.
    pub description: Option<Spanned<String>>,
    /// Optional blueprint author.
    pub author: Option<Spanned<String>>,
    /// Optional minimum Achitek version required by the blueprint.
    pub min_achitek_version: Option<Spanned<String>>,
}

/// Semantic representation of an Achitekfile.
///
/// # Examples
///
/// ```
/// let source = r#"
/// blueprint {
///   version = "1.0.0"
///   name = "web-app"
/// }
///
/// prompt "project_name" {
///   type = string
/// }
/// "#;
///
/// let analysis = achitekfile::analyze(source)?;
/// let file = analysis.file();
///
/// assert_eq!(file.blueprint().name.as_ref().map(|name| name.value.as_str()), Some("web-app"));
/// assert_eq!(file.prompts()[0].value.name, "project_name");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AchitekFile {
    blueprint: Blueprint,
    prompts: Vec<Spanned<Prompt>>,
}

impl AchitekFile {
    /// Creates a recovering Achitekfile model from parsed parts.
    ///
    /// See [`AchitekFile`] for a parsing-oriented example.
    pub fn new(blueprint: Blueprint, prompts: Vec<Spanned<Prompt>>) -> Self {
        Self { blueprint, prompts }
    }
    /// Returns recovered blueprint metadata.
    ///
    /// See [`AchitekFile`] for a complete example.
    pub fn blueprint(&self) -> &Blueprint {
        &self.blueprint
    }
    /// Returns recovered prompts in source order.
    ///
    /// See [`AchitekFile`] for a complete example.
    pub fn prompts(&self) -> &[Spanned<Prompt>] {
        &self.prompts
    }
}

/// A parsed prompt declaration from an Achitekfile.
///
/// See [`AchitekFile`] for an example that reads recovered prompts.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Prompt {
    /// The prompt identifier from `prompt "..."`.
    pub name: String,
    /// The kind of input expected for this prompt.
    ///
    /// This is optional in the recovering model so diagnostics can report a
    /// missing `type` attribute without discarding the rest of the prompt.
    pub prompt_type: Option<PromptType>,
    /// Optional help text shown to a user alongside the prompt.
    pub help: Option<String>,
    /// The allowed choices for `select` and `multiselect` prompts.
    ///
    /// Non-choice prompt types may leave this empty.
    pub choices: Vec<Value>,
    /// Whether the prompt declared a `choices` attribute.
    ///
    /// This lets analysis distinguish an omitted `choices` attribute from an
    /// explicitly empty `choices = []` array.
    pub choices_declared: bool,
    /// The default answer for the prompt, if one was declared.
    pub default: Option<Value>,
    /// Whether the prompt requires an answer.
    ///
    /// `None` means the Achitekfile omitted the `required` attribute and the
    /// caller should apply its own default policy.
    pub required: Option<bool>,
    /// A dependency expression that controls whether this prompt should be
    /// asked.
    pub depends_on: Option<Dependency>,
    /// Validation rules declared in the nested `validate { ... }` block.
    pub validation: Validation,
}

/// The supported prompt input types.
///
/// See [`Prompt`] for the containing model type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PromptType {
    /// A single-line string answer.
    String,
    /// A multi-line string answer.
    Paragraph,
    /// A boolean answer.
    Bool,
    /// A single choice from the prompt's `choices`.
    Select,
    /// Zero or more choices from the prompt's `choices`.
    MultiSelect,
}

/// A literal or identifier value parsed from an Achitekfile.
///
/// See [`Prompt`] for an example of values attached to parsed prompts.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Value {
    /// A double-quoted string literal with supported escape sequences decoded.
    String(String),
    /// A `true` or `false` literal.
    Bool(bool),
    /// A non-negative integer literal.
    Integer(u64),
    /// An unquoted identifier.
    Identifier(String),
    /// An array of values.
    Array(Vec<Value>),
}

/// A dependency expression from a prompt's `depends_on` attribute.
///
/// Dependencies are both executable conditions and graph edges. For ordering,
/// every variant can reveal the prompt names it references:
///
/// - `database`
/// - `database != "none"`
/// - `features.contains("auth")`
/// - `all(database != "none", features.contains("auth"))`
///
/// See [`ValidAchitekFile::prompts_in`] for an example of using dependencies
/// to order prompts.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Dependency {
    /// A direct dependency on another prompt by name, such as `depends_on = database`.
    Reference(String),
    /// A comparison dependency, such as `database != "none"`.
    Comparison {
        /// The prompt name on the left-hand side of the comparison.
        left: String,
        /// The equality operator used by the comparison.
        operator: ComparisonOperator,
        /// The literal value on the right-hand side of the comparison.
        right: Value,
    },
    /// A `contains` dependency, such as `features.contains("auth")`.
    Contains {
        /// The prompt name whose answer is searched.
        receiver: String,
        /// The value expected to be contained in the receiver's answer.
        argument: Value,
    },
    /// A dependency that requires every nested dependency to be true.
    All(Vec<Dependency>),
    /// A dependency that requires at least one nested dependency to be true.
    Any(Vec<Dependency>),
}
impl Dependency {
    fn references(&self) -> Vec<&str> {
        let mut references = Vec::new();
        self.collect_references(&mut references);
        references
    }

    fn collect_references<'a>(&'a self, references: &mut Vec<&'a str>) {
        match self {
            Self::Reference(name) => references.push(name),
            Self::Comparison { left, .. } => references.push(left),
            Self::Contains { receiver, .. } => references.push(receiver),
            Self::All(dependencies) | Self::Any(dependencies) => {
                for dependency in dependencies {
                    dependency.collect_references(references);
                }
            }
        }
    }
}

/// Operators supported by comparison dependencies.
///
/// See [`Dependency`] for the comparison expression that uses this operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ComparisonOperator {
    /// Equality, written as `==`.
    Equal,
    /// Inequality, written as `!=`.
    NotEqual,
}

/// Validation rules for a prompt.
///
/// These fields correspond to attributes inside a `validate { ... }` block.
/// The parser records what the file declares; it does not currently enforce
/// whether a given rule is appropriate for the prompt type.
///
/// See [`Prompt`] and [`ValidPrompt`] for examples of prompts that carry
/// validation rules.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Validation {
    /// A regular expression that string-like answers must match.
    pub regex: Option<String>,
    /// The minimum accepted string length.
    pub min_length: Option<u64>,
    /// The maximum accepted string length.
    pub max_length: Option<u64>,
    /// The minimum number of selections for a multiselect prompt.
    pub min_selections: Option<u64>,
    /// The maximum number of selections for a multiselect prompt.
    pub max_selections: Option<u64>,
}

/// A valid semantic representation of an Achitekfile.
///
/// This type is intended for runtime consumers that need a file which has
/// already passed syntax and semantic validation. Unlike [`AchitekFile`], it
/// does not expose partial or optional structure for required concepts: a valid
/// file always has a blueprint and every prompt has a complete prompt type.
///
/// # Examples
///
/// ```
/// let source = r#"
/// blueprint {
///   version = "1.0.0"
///   name = "web-app"
/// }
///
/// prompt "database" {
///   type = select
///   choices = ["postgres", "sqlite"]
/// }
/// "#;
///
/// let file = achitekfile::analyze(source)?.into_valid().map_err(|diagnostics| {
///     let message = diagnostics
///         .into_iter()
///         .map(|diagnostic| diagnostic.message().to_owned())
///         .collect::<Vec<_>>()
///         .join(", ");
///     std::io::Error::new(std::io::ErrorKind::InvalidData, message)
/// })?;
///
/// assert_eq!(file.prompts()[0].prompt_type, achitekfile::model::PromptType::Select);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ValidAchitekFile {
    blueprint: ValidBlueprint,
    prompts: Vec<ValidPrompt>,
}

impl ValidAchitekFile {
    /// Creates a valid Achitekfile model from already validated parts.
    ///
    /// See [`ValidAchitekFile`] for a validation-oriented example.
    pub fn new(blueprint: ValidBlueprint, prompts: Vec<ValidPrompt>) -> Self {
        Self { blueprint, prompts }
    }

    /// Returns the validated blueprint metadata.
    ///
    /// See [`ValidAchitekFile`] for a complete example.
    pub fn blueprint(&self) -> &ValidBlueprint {
        &self.blueprint
    }

    /// Returns validated prompts in source order.
    ///
    /// See [`ValidAchitekFile`] for a complete example.
    pub fn prompts(&self) -> &[ValidPrompt] {
        &self.prompts
    }

    /// Returns validated prompts in the requested order.
    ///
    /// # Errors
    ///
    /// Returns [`SortError`] when dependency ordering is requested and
    /// the prompt dependency graph contains a cycle. Use
    /// [`SortError::cycles`] to inspect the cyclic regions.
    ///
    /// # Examples
    ///
    /// ```
    /// let source = r#"
    /// blueprint {
    ///   version = "1.0.0"
    ///   name = "web-app"
    /// }
    ///
    /// prompt "orm" {
    ///   type = select
    ///   choices = ["sqlx", "diesel"]
    ///   depends_on = database != "sqlite"
    /// }
    ///
    /// prompt "database" {
    ///   type = select
    ///   choices = ["postgres", "sqlite"]
    /// }
    /// "#;
    ///
    /// let file = achitekfile::analyze(source)?.into_valid().map_err(|diagnostics| {
    ///     let message = diagnostics
    ///         .into_iter()
    ///         .map(|diagnostic| diagnostic.message().to_owned())
    ///         .collect::<Vec<_>>()
    ///         .join(", ");
    ///     std::io::Error::new(std::io::ErrorKind::InvalidData, message)
    /// })?;
    /// let ordered_names = file
    ///     .prompts_in(achitekfile::model::PromptOrder::Dependency)?
    ///     .map(|prompt| prompt.name.as_str())
    ///     .collect::<Vec<_>>();
    ///
    /// assert_eq!(ordered_names, ["database", "orm"]);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn prompts_in(&self, order: PromptOrder) -> Result<PromptIter<'_>, SortError<String>> {
        match order {
            PromptOrder::Source => Ok(PromptIter::Source(self.prompts.iter())),
            PromptOrder::Dependency => self.prompts_in_dependency_order(),
        }
    }

    fn prompts_in_dependency_order(&self) -> Result<PromptIter<'_>, SortError<String>> {
        let prompt_names = self
            .prompts
            .iter()
            .map(|prompt| prompt.name.clone())
            .collect::<Vec<_>>();
        let edges = self
            .prompts
            .iter()
            .flat_map(|prompt| {
                prompt
                    .depends_on
                    .as_ref()
                    .into_iter()
                    .flat_map(|dependency| dependency.references())
                    .map(|reference| (reference.to_owned(), prompt.name.clone()))
            })
            .collect::<Vec<_>>();
        let graph = Graph {
            nodes: prompt_names,
            edges,
        };
        let sorted_names = sort_graph(&graph)?;
        let prompts_by_name = self
            .prompts
            .iter()
            .map(|prompt| (prompt.name.as_str(), prompt))
            .collect::<HashMap<_, _>>();
        let prompts = sorted_names
            .iter()
            .filter_map(|name| prompts_by_name.get(name.as_str()).copied())
            .collect::<Vec<_>>();

        Ok(PromptIter::Dependency(prompts.into_iter()))
    }
}

/// Ordering strategy for validated prompts.
///
/// See [`ValidAchitekFile::prompts_in`] for an example.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PromptOrder {
    /// Preserve the order prompts appeared in the source file.
    Source,
    /// Return dependency prompts before prompts that depend on them.
    Dependency,
}

/// Iterator over validated prompts.
///
/// See [`ValidAchitekFile::prompts_in`] for an example.
#[derive(Debug, Clone)]
pub enum PromptIter<'a> {
    /// Iterates over prompts in source order without allocating.
    Source(std::slice::Iter<'a, ValidPrompt>),
    /// Iterates over prompts in computed dependency order.
    Dependency(vec::IntoIter<&'a ValidPrompt>),
}

impl<'a> Iterator for PromptIter<'a> {
    type Item = &'a ValidPrompt;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Self::Source(prompts) => prompts.next(),
            Self::Dependency(prompts) => prompts.next(),
        }
    }
}

/// Validated blueprint metadata.
///
/// See [`ValidAchitekFile`] for an example that reads validated blueprint
/// metadata.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ValidBlueprint {
    /// Achitekfile format version declared by the blueprint.
    pub version: String,
    /// Blueprint name.
    pub name: String,
    /// Optional blueprint description.
    pub description: Option<String>,
    /// Optional blueprint author.
    pub author: Option<String>,
    /// Optional minimum Achitek version required by the blueprint.
    pub min_achitek_version: Option<String>,
}

/// A validated prompt declaration.
///
/// See [`ValidAchitekFile`] for an example that reads validated prompts.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ValidPrompt {
    /// The prompt identifier from `prompt "..."`.
    pub name: String,
    /// The kind of input expected for this prompt.
    pub prompt_type: PromptType,
    /// Optional help text shown to a user alongside the prompt.
    pub help: Option<String>,
    /// The allowed choices for `select` and `multiselect` prompts.
    pub choices: Vec<Value>,
    /// The default answer for the prompt, if one was declared.
    pub default: Option<Value>,
    /// Whether the prompt requires an answer.
    pub required: bool,
    /// A dependency expression that controls whether this prompt should be
    /// asked.
    pub depends_on: Option<Dependency>,
    /// Validation rules declared in the nested `validate { ... }` block.
    pub validation: Validation,
}