pklr 5.2.0

Pure Rust pkl configuration language parser and evaluator
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
566
567
568
569
570
571
572
573
574
575
576
577
578
//! Static checks pkl performs while building a module: modifier
//! applicability, duplicate member definitions and a few member rules.
//! They run while parsing, so the errors point at the offending member.

use std::collections::HashSet;

use super::Parser;
use super::ast::{Annotation, Entry, Expr, Import, Modifier, Property};
use crate::error::Result;
use crate::lexer::TokenKind;

/// The kind of body whose members are being parsed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum BodyKind {
    /// A module that does not amend another module. Its members are class
    /// members.
    Module,
    /// A module that amends another module. Its members are object members.
    AmendingModule,
    Class,
    Object,
    /// The body of a `when` generator.
    When,
    /// The body of a `for` generator, or of a `when` generator nested in one.
    For,
}

/// A constant object entry key, as far as duplicate detection is concerned.
#[derive(Debug, PartialEq, Eq, Hash)]
enum ConstKey {
    String(String),
    Int(i64),
    Bool(bool),
}

/// Members defined so far in one body.
pub(super) struct BodyScope {
    pub(super) kind: BodyKind,
    /// Offset of the innermost enclosing `for` keyword, if the body is
    /// (nested in) a for-generator body.
    for_offset: Option<usize>,
    /// Names of properties, classes, type aliases and imports. In modules
    /// and classes, local and non-local members share one namespace.
    properties: HashSet<String>,
    /// Local property names (object bodies keep them apart from non-local
    /// ones).
    local_properties: HashSet<String>,
    methods: HashSet<String>,
    entries: HashSet<ConstKey>,
    /// Whether the body has a generator or spread member. pkl merges the
    /// members of such a body at runtime, so a duplicate in it is not a
    /// static error.
    has_generator: bool,
    /// The first duplicate found in an object body, reported once the body
    /// is known to have no generator.
    duplicate: Option<(usize, String)>,
    /// Type aliases defined in the body: offset, name and the names their
    /// type refers to.
    type_aliases: Vec<(usize, String, Vec<String>)>,
}

impl BodyScope {
    pub(super) fn new(kind: BodyKind, for_offset: Option<usize>) -> Self {
        Self {
            kind,
            for_offset,
            properties: HashSet::new(),
            local_properties: HashSet::new(),
            methods: HashSet::new(),
            entries: HashSet::new(),
            has_generator: false,
            duplicate: None,
            type_aliases: Vec::new(),
        }
    }

    /// Record a type alias and the type names its type uses, for the cycle
    /// check. Its own type parameters shadow other types inside it.
    pub(super) fn record_type_alias(
        &mut self,
        offset: usize,
        name: &str,
        mut refs: Vec<String>,
        params: &[String],
    ) {
        refs.retain(|r| !params.contains(r));
        self.type_aliases.push((offset, name.to_string(), refs));
    }

    /// The offset of a type alias that refers back to itself, directly or
    /// through other aliases of the body.
    fn cyclic_type_alias(&self) -> Option<usize> {
        if self.type_aliases.is_empty() {
            return None;
        }
        let index_of: std::collections::HashMap<&str, usize> = self
            .type_aliases
            .iter()
            .enumerate()
            .map(|(i, (_, name, _))| (name.as_str(), i))
            .collect();
        // 0 = unvisited, 1 = on the current path, 2 = done
        let mut state = vec![0u8; self.type_aliases.len()];
        for root in 0..self.type_aliases.len() {
            if state[root] != 0 {
                continue;
            }
            // Depth-first with an explicit stack of (alias, next ref).
            let mut stack = vec![(root, 0usize)];
            state[root] = 1;
            while let Some((alias, next)) = stack.last_mut() {
                let refs = &self.type_aliases[*alias].2;
                if *next == refs.len() {
                    state[*alias] = 2;
                    stack.pop();
                    continue;
                }
                let r = &refs[*next];
                *next += 1;
                let Some(&target) = index_of.get(r.as_str()) else {
                    continue;
                };
                match state[target] {
                    1 => return Some(self.type_aliases[target].0),
                    0 => {
                        state[target] = 1;
                        stack.push((target, 0));
                    }
                    _ => {}
                }
            }
        }
        None
    }

    /// Record the names a module's imports bind, which share the namespace
    /// of its properties. Returns a name bound twice.
    pub(super) fn declare_imports(&mut self, imports: &[Import]) -> Option<String> {
        for import in imports {
            let name = match &import.alias {
                Some(alias) => alias.as_str(),
                None if import.is_glob => continue,
                None => inferred_import_name(&import.uri),
            };
            if !self.properties.insert(name.to_string()) {
                return Some(name.to_string());
            }
        }
        None
    }

    pub(super) fn set_has_generator(&mut self) {
        self.has_generator = true;
    }
}

fn modifier_keyword(modifier: &Modifier) -> &'static str {
    match modifier {
        Modifier::Local => "local",
        Modifier::Const => "const",
        Modifier::Fixed => "fixed",
        Modifier::Hidden => "hidden",
        Modifier::Abstract => "abstract",
        Modifier::Open => "open",
        Modifier::External => "external",
    }
}

const MODULE_MODIFIERS: &[Modifier] = &[Modifier::Abstract, Modifier::Open];
const CLASS_MODIFIERS: &[Modifier] = &[
    Modifier::Abstract,
    Modifier::Open,
    Modifier::Local,
    Modifier::External,
];
const TYPE_ALIAS_MODIFIERS: &[Modifier] = &[Modifier::Local, Modifier::External];
const METHOD_MODIFIERS: &[Modifier] = &[
    Modifier::Abstract,
    Modifier::Local,
    Modifier::External,
    Modifier::Const,
];
const PROPERTY_MODIFIERS: &[Modifier] = &[
    Modifier::Abstract,
    Modifier::Local,
    Modifier::Hidden,
    Modifier::External,
    Modifier::Fixed,
    Modifier::Const,
];
const OBJECT_MEMBER_MODIFIERS: &[Modifier] = &[Modifier::Local, Modifier::Const];

/// The Pkl release whose language pklr implements, checked against a
/// module's `@ModuleInfo { minPklVersion = "..." }`.
pub(crate) const PKL_VERSION: &str = "0.32.1";

/// `major.minor.patch` of a version string, ignoring any pre-release or
/// build suffix.
fn version_triple(version: &str) -> Option<(u64, u64, u64)> {
    let core = version.split(['-', '+']).next()?;
    let mut parts = core.split('.').map(|part| part.parse::<u64>().ok());
    Some((parts.next()??, parts.next()??, parts.next()??))
}

/// The value of a string expression made only of literals
/// (`"0.2" + "7.0"`), as pkl folds them.
fn constant_string(expr: &Expr) -> Option<String> {
    match expr {
        Expr::String(s) => Some(s.to_string()),
        Expr::Binop(super::ast::BinOp::Add, left, right) => {
            Some(constant_string(left)? + &constant_string(right)?)
        }
        Expr::StringInterpolation(parts) => parts
            .iter()
            .map(|part| match part {
                super::ast::StringInterpPart::Literal(s) => Some(s.to_string()),
                super::ast::StringInterpPart::Expr(expr) => constant_string(expr),
            })
            .collect(),
        _ => None,
    }
}

/// The name a module import is bound to when it has no `as` alias: the last
/// path segment of the URI without its extension.
fn inferred_import_name(uri: &str) -> &str {
    let last = uri.rsplit(['/', ':', '#']).next().unwrap_or(uri);
    match last.rfind('.') {
        Some(dot) if dot > 0 => &last[..dot],
        _ => last,
    }
}

impl Parser<'_> {
    fn semantic_error(&self, offset: usize, message: impl Into<String>) -> crate::error::Error {
        crate::error::Error::parse(self.name, self.source, offset, message.into())
    }

    /// Check `modifiers` against the set valid for a kind of member, then
    /// reject the combinations pkl never allows.
    fn check_modifiers(
        &self,
        offset: usize,
        modifiers: &[Modifier],
        valid: &[Modifier],
        what: &str,
    ) -> Result<()> {
        if let Some(invalid) = modifiers.iter().find(|m| !valid.contains(m)) {
            return Err(self.semantic_error(
                offset,
                format!(
                    "Modifier `{}` is not applicable to {what}.",
                    modifier_keyword(invalid)
                ),
            ));
        }
        let has = |m: Modifier| modifiers.contains(&m);
        let message = if has(Modifier::External) {
            "External members can only be defined by standard library modules."
        } else if has(Modifier::Local) && has(Modifier::Hidden) {
            "Modifier `hidden` is redundant here; just use `local`."
        } else if has(Modifier::Local) && has(Modifier::Fixed) {
            "Modifier `fixed` is redundant here; just use `local`."
        } else if has(Modifier::Abstract) && has(Modifier::Open) {
            "Modifier `open` is redundant here; just use `abstract`."
        } else {
            return Ok(());
        };
        Err(self.semantic_error(offset, message))
    }

    fn check_object_member_modifiers(&self, offset: usize, modifiers: &[Modifier]) -> Result<()> {
        self.check_modifiers(offset, modifiers, OBJECT_MEMBER_MODIFIERS, "object members")?;
        if modifiers.contains(&Modifier::Const) && !modifiers.contains(&Modifier::Local) {
            return Err(self.semantic_error(
                offset,
                "Modifier `const` can only be applied to object members that are also `local`.",
            ));
        }
        Ok(())
    }

    /// Reject a module whose `@ModuleInfo` requires a newer Pkl than
    /// [`PKL_VERSION`].
    pub(super) fn check_min_pkl_version(
        &self,
        annotations: &[Annotation],
        module_name: Option<&str>,
    ) -> Result<()> {
        let Some(required) = annotations
            .iter()
            .filter(|annotation| annotation.name == "ModuleInfo")
            .flat_map(|annotation| &annotation.body)
            .find_map(|entry| match entry {
                Entry::Property(prop) if prop.name == "minPklVersion" => {
                    prop.value.as_ref().and_then(constant_string)
                }
                _ => None,
            })
        else {
            return Ok(());
        };
        let (Some(required_triple), Some(current)) =
            (version_triple(&required), version_triple(PKL_VERSION))
        else {
            return Ok(());
        };
        if required_triple <= current {
            return Ok(());
        }
        let name = module_name.map(str::to_string).unwrap_or_else(|| {
            std::path::Path::new(self.name)
                .file_stem()
                .map(|stem| stem.to_string_lossy().into_owned())
                .unwrap_or_else(|| self.name.to_string())
        });
        Err(self.semantic_error(
            0,
            format!(
                "Module `{name}` requires Pkl version {required} or higher, but your Pkl version is {PKL_VERSION}."
            ),
        ))
    }

    /// Check the modifiers of the module declaration (`open module foo`).
    pub(super) fn check_module_modifiers(
        &self,
        offset: usize,
        modifiers: &[Modifier],
        amends: bool,
    ) -> Result<()> {
        self.check_modifiers(offset, modifiers, MODULE_MODIFIERS, "modules")?;
        if amends {
            self.check_modifiers(offset, modifiers, &[], "modules that amend another module")?;
        }
        Ok(())
    }

    pub(super) fn duplicate_error(&self, offset: usize, name: &str) -> crate::error::Error {
        self.semantic_error(offset, format!("Duplicate definition of member `{name}`."))
    }

    /// Record a member name, reporting a duplicate right away in modules and
    /// classes, and once the body is complete in object bodies.
    fn declare(&mut self, offset: usize, name: &str, method: bool, local: bool) -> Result<()> {
        let in_object = matches!(
            self.body.kind,
            BodyKind::Object | BodyKind::When | BodyKind::For
        );
        let set = if method {
            &mut self.body.methods
        } else if in_object && local {
            &mut self.body.local_properties
        } else {
            &mut self.body.properties
        };
        if set.insert(name.to_string()) {
            return Ok(());
        }
        if !in_object {
            return Err(self.duplicate_error(offset, name));
        }
        if self.body.duplicate.is_none() {
            self.body.duplicate = Some((offset, name.to_string()));
        }
        Ok(())
    }

    /// Report a duplicate member of a finished body, unless pkl only finds it
    /// at runtime.
    pub(super) fn finish_body(&self, scope: &BodyScope) -> Result<()> {
        if let Some(offset) = scope.cyclic_type_alias() {
            return Err(self.semantic_error(offset, "Type alias definitions must not be cyclic."));
        }
        if scope.has_generator || matches!(scope.kind, BodyKind::When | BodyKind::For) {
            return Ok(());
        }
        match &scope.duplicate {
            Some((offset, name)) => Err(self.duplicate_error(*offset, name)),
            None => Ok(()),
        }
    }

    pub(super) fn check_class(
        &mut self,
        offset: usize,
        modifiers: &[Modifier],
        name: &str,
    ) -> Result<()> {
        self.check_modifiers(offset, modifiers, CLASS_MODIFIERS, "classes")?;
        if self.body.kind == BodyKind::AmendingModule && !modifiers.contains(&Modifier::Local) {
            return Err(self.semantic_error(offset, "Class needs a `local` modifier."));
        }
        self.declare(offset, name, false, modifiers.contains(&Modifier::Local))
    }

    pub(super) fn check_type_alias(
        &mut self,
        offset: usize,
        modifiers: &[Modifier],
        name: &str,
    ) -> Result<()> {
        self.check_modifiers(offset, modifiers, TYPE_ALIAS_MODIFIERS, "type aliases")?;
        if self.body.kind == BodyKind::AmendingModule && !modifiers.contains(&Modifier::Local) {
            return Err(self.semantic_error(offset, "Type alias needs a `local` modifier."));
        }
        self.declare(offset, name, false, modifiers.contains(&Modifier::Local))
    }

    /// A `*` default marker is only valid on one member of a union type.
    pub(super) fn check_union_defaults(
        &self,
        offset: usize,
        variants: &[(super::TypeExpr, bool)],
    ) -> Result<()> {
        let defaults = variants
            .iter()
            .filter(|(_, is_default)| *is_default)
            .count();
        if defaults == 0 {
            Ok(())
        } else if variants.len() == 1 {
            Err(self.semantic_error(offset, "Only type unions can have a default marker (*)."))
        } else if defaults > 1 {
            Err(self.semantic_error(
                offset,
                "A type union cannot have more than one default type.",
            ))
        } else {
            Ok(())
        }
    }

    /// The names and offsets of the type parameters in the `<...>` list
    /// starting at token `start`, without the `out` variance markers.
    pub(super) fn type_parameter_names(&self, start: usize) -> Vec<(String, usize)> {
        let mut names = Vec::new();
        let mut depth = 0;
        for (i, tok) in self.tokens.iter().enumerate().skip(start) {
            match &tok.kind {
                TokenKind::Lt => depth += 1,
                TokenKind::Gt if depth > 0 => {
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                }
                TokenKind::Ident(name) if depth == 1 => {
                    let is_variance = name == "out"
                        && matches!(
                            self.tokens.get(i + 1).map(|t| &t.kind),
                            Some(TokenKind::Ident(_))
                        );
                    if !is_variance {
                        names.push((name.clone(), tok.offset));
                    }
                }
                TokenKind::Eof => break,
                _ => {}
            }
        }
        names
    }

    /// Reject a duplicate type parameter in the `<...>` list starting at
    /// token `start`.
    pub(super) fn check_type_parameters(&self, start: usize) -> Result<()> {
        let names = self.type_parameter_names(start);
        for (i, (name, offset)) in names.iter().enumerate() {
            if names[..i].iter().any(|(other, _)| other == name) {
                return Err(
                    self.semantic_error(*offset, format!("Duplicate type parameter `{name}`."))
                );
            }
        }
        Ok(())
    }

    pub(super) fn type_parameters_error(&self) -> crate::error::Error {
        self.semantic_error(
            self.peek_tok().offset,
            "Only standard library members can have type parameters.",
        )
    }

    pub(super) fn check_method(
        &mut self,
        offset: usize,
        modifiers: &[Modifier],
        name: &str,
    ) -> Result<()> {
        let local = modifiers.contains(&Modifier::Local);
        match self.body.kind {
            BodyKind::Module | BodyKind::Class => {
                self.check_modifiers(offset, modifiers, METHOD_MODIFIERS, "methods")?;
            }
            BodyKind::For => {
                return Err(self.semantic_error(
                    self.body.for_offset.unwrap_or(offset),
                    "A for-generator cannot generate object methods (only entries and elements).",
                ));
            }
            kind => {
                self.check_modifiers(offset, modifiers, OBJECT_MEMBER_MODIFIERS, "object members")?;
                if !local {
                    let message = if kind == BodyKind::AmendingModule {
                        "Method needs a `local` modifier."
                    } else {
                        "Method needs a `local` modifier because it is defined in an object, not a class."
                    };
                    return Err(self.semantic_error(offset, message));
                }
            }
        }
        self.declare(offset, name, true, local)
    }

    pub(super) fn check_property(&mut self, offset: usize, prop: &Property) -> Result<()> {
        let local = prop.modifiers.contains(&Modifier::Local);
        match self.body.kind {
            BodyKind::Module | BodyKind::Class => {
                self.check_modifiers(offset, &prop.modifiers, PROPERTY_MODIFIERS, "properties")?;
            }
            BodyKind::For => {
                return Err(self.semantic_error(
                    self.body.for_offset.unwrap_or(offset),
                    "A for-generator cannot generate object properties (only entries and elements).",
                ));
            }
            _ => {
                self.check_object_member_modifiers(offset, &prop.modifiers)?;
                if !local && prop.type_ann.is_some() {
                    return Err(self.semantic_error(
                        offset,
                        "A non-local object property cannot have a type annotation.",
                    ));
                }
                if local && prop.body.is_some() {
                    return Err(self
                        .semantic_error(offset, "A local property definition cannot be amended."));
                }
            }
        }
        if local && prop.value.is_none() && prop.body.is_none() {
            return Err(self.semantic_error(offset, "Missing property value."));
        }
        self.declare(offset, &prop.name, false, local)
    }

    /// Record an object entry whose key is a constant.
    pub(super) fn check_entry_key(&mut self, offset: usize, key: &Expr) {
        let key = match key {
            Expr::String(s) => ConstKey::String(s.to_string()),
            Expr::Int(i) => ConstKey::Int(*i),
            Expr::Bool(b) => ConstKey::Bool(*b),
            _ => return,
        };
        let shown = match &key {
            ConstKey::String(s) => format!("\"{s}\""),
            ConstKey::Int(i) => i.to_string(),
            ConstKey::Bool(b) => b.to_string(),
        };
        if !self.body.entries.insert(key) && self.body.duplicate.is_none() {
            self.body.duplicate = Some((offset, shown));
        }
    }

    pub(super) fn for_scope(&self, for_offset: usize) -> BodyScope {
        BodyScope::new(BodyKind::For, Some(for_offset))
    }

    pub(super) fn when_scope(&self) -> BodyScope {
        match self.body.for_offset {
            Some(offset) => BodyScope::new(BodyKind::For, Some(offset)),
            None => BodyScope::new(BodyKind::When, None),
        }
    }
}