qleisli 0.2.2

Experimental quantum language with linear ownership, exact contracts and independent finite IR verification
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! Root-relative module discovery and import resolution for `.qli` sources.
//!
//! This phase checks paths, declarations, import visibility and cycles. It is
//! not a type checker: a resolved source name cannot bypass IR verification.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};

use super::ast::{self, FnKind, Span, UseDecl};
use super::diagnostic::{Diagnostic, SourceLocation, coordinates};
use super::lexer::keyword_kind;
use super::parser::parse_module;

mod source_file;

const BUNDLED_SOURCES: &[(&str, &str)] = &[
    (
        "arithmetic",
        include_str!("../../stdlib/src/arithmetic.qli"),
    ),
    ("basis", include_str!("../../stdlib/src/basis.qli")),
    ("routines", include_str!("../../stdlib/src/routines.qli")),
    (
        "transforms",
        include_str!("../../stdlib/src/transforms.qli"),
    ),
];

/// Byte policy before UTF-8 decoding or tokenization. The legacy adapter is
/// explicit; parser, evidence and lowering budgets are independent of this.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SourcePolicy {
    Legacy,
    Bounded {
        source_bytes: u64,
        project_bytes: u64,
    },
}

impl Default for SourcePolicy {
    fn default() -> Self {
        Self::Bounded {
            source_bytes: 1 << 20,
            project_bytes: 16 << 20,
        }
    }
}

struct SourceBudget {
    policy: SourcePolicy,
    used: u64,
}

impl SourceBudget {
    fn limit(path: &Path, message: impl Into<String>) -> LoadFailure {
        let mut failure = error(
            path,
            Span::default(),
            format!("{}: {}", path.display(), message.into()),
        );
        failure.code = "limit";
        failure
    }

    fn allowance(&self, path: &Path) -> Result<Option<u64>, LoadFailure> {
        match self.policy {
            SourcePolicy::Legacy => Ok(None),
            SourcePolicy::Bounded {
                source_bytes,
                project_bytes,
            } => {
                if source_bytes == 0 || project_bytes == 0 {
                    return Err(Self::limit(path, "source byte limits must be positive"));
                }
                let remaining = project_bytes
                    .checked_sub(self.used)
                    .ok_or_else(|| Self::limit(path, "aggregate source byte limit exceeded"))?;
                Ok(Some(source_bytes.min(remaining)))
            }
        }
    }

    fn charge(&mut self, path: &Path, bytes: u64) -> Result<(), LoadFailure> {
        if let SourcePolicy::Bounded {
            source_bytes,
            project_bytes,
        } = self.policy
        {
            self.allowance(path)?;
            if bytes > source_bytes {
                return Err(Self::limit(
                    path,
                    format!("source exceeds {source_bytes}-byte file limit"),
                ));
            }
            let total = self
                .used
                .checked_add(bytes)
                .ok_or_else(|| Self::limit(path, "source byte accounting overflow"))?;
            if total > project_bytes {
                return Err(Self::limit(
                    path,
                    format!("project exceeds {project_bytes}-byte aggregate limit"),
                ));
            }
            self.used = total;
        }
        Ok(())
    }

    fn read(&mut self, path: &Path) -> Result<String, LoadFailure> {
        let allowance = self.allowance(path)?;
        let file = source_file::open(path).map_err(|failure| io_error(path, failure))?;
        let mut bytes = Vec::new();
        match allowance {
            Some(limit) => {
                let sentinel = limit
                    .checked_add(1)
                    .ok_or_else(|| Self::limit(path, "source read limit overflow"))?;
                file.take(sentinel)
                    .read_to_end(&mut bytes)
                    .map_err(|failure| io_error(path, failure))?;
            }
            None => {
                let mut file = file;
                file.read_to_end(&mut bytes)
                    .map_err(|failure| io_error(path, failure))?;
            }
        }
        self.charge(path, bytes.len() as u64)?;
        String::from_utf8(bytes)
            .map_err(|_| error(path, Span::default(), "source file is not valid UTF-8"))
    }
}

/// Read a single documentation source with explicit byte limits. Unlike project
/// loading this does not include bundled modules, because none are loaded.
pub fn read_source_file(path: &Path, policy: SourcePolicy) -> Result<String, Diagnostic> {
    // The single-file command accepts ordinary parent aliases such as /tmp on
    // macOS. Resolve them before opening; never resolve the final source link.
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let resolved = fs::canonicalize(parent)
        .map_err(|failure| io_error(path, failure).into_diagnostic())?
        .join(path.file_name().ok_or_else(|| {
            error(path, Span::default(), "source path has no file name").into_diagnostic()
        })?);
    SourceBudget { policy, used: 0 }
        .read(&resolved)
        .map_err(LoadFailure::into_diagnostic)
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ModuleOrigin {
    Local,
    Bundled,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ImportOrigin {
    Local,
    Bundled,
    Sealed,
}

/// A name admitted to a module's top-level scope. `Sealed` is assigned only
/// by this resolver for known compiler primitives, never by a local `.qli`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolvedImport {
    pub module: String,
    pub name: String,
    pub kind: FnKind,
    pub origin: ImportOrigin,
    pub span: Span,
}

#[derive(Clone, Debug)]
pub struct SourceModule {
    pub name: String,
    pub path: PathBuf,
    pub source: String,
    pub ast: ast::Module,
    pub imports: BTreeMap<String, ResolvedImport>,
    pub origin: ModuleOrigin,
}

#[derive(Clone, Debug)]
pub struct Project {
    pub root: PathBuf,
    /// Local modules use root-relative names; bundled `std` source modules
    /// follow the same checks. Sealed quantum/observe primitives have no AST.
    pub modules: BTreeMap<String, SourceModule>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProjectError {
    pub path: PathBuf,
    /// Half-open UTF-8 byte range in `path`, or 0..0 for a path/I/O error.
    pub span: Span,
    pub message: String,
}

impl fmt::Display for ProjectError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}:{}..{}: {}",
            self.path.display(),
            self.span.start,
            self.span.end,
            self.message
        )
    }
}

impl std::error::Error for ProjectError {}

pub(crate) struct LoadFailure {
    pub error: ProjectError,
    pub coordinates: Option<(usize, usize)>,
    code: &'static str,
}

impl LoadFailure {
    pub(crate) fn into_diagnostic(self) -> Diagnostic {
        Diagnostic {
            code: self.code,
            message: self.error.message,
            primary: self.coordinates.map(|(line, column)| SourceLocation {
                path: self.error.path,
                span: self.error.span,
                line,
                column,
            }),
        }
    }
}

fn source_error(module: &SourceModule, span: Span, message: impl Into<String>) -> LoadFailure {
    located_error(&module.path, &module.source, span, "project", message)
}

fn located_error(
    path: &Path,
    source: &str,
    span: Span,
    code: &'static str,
    message: impl Into<String>,
) -> LoadFailure {
    let mut failure = error(path, span, message);
    let (line, column) = coordinates(source, span);
    failure.code = code;
    failure.coordinates = Some((line, column));
    failure
}

fn error(path: &Path, span: Span, message: impl Into<String>) -> LoadFailure {
    let message = message.into();
    LoadFailure {
        error: ProjectError {
            path: path.to_path_buf(),
            span,
            message,
        },
        coordinates: None,
        code: "project",
    }
}

fn io_error(path: &Path, failure: std::io::Error) -> LoadFailure {
    error(path, Span::default(), failure.to_string())
}

impl Project {
    /// Compatibility adapter retaining the pre-0.2 unbounded byte loader.
    pub fn load(root: &Path) -> Result<Self, ProjectError> {
        Self::load_detailed(root).map_err(|failure| failure.error)
    }

    pub(crate) fn load_detailed(root: &Path) -> Result<Self, LoadFailure> {
        Self::load_detailed_with_policy(root, SourcePolicy::Legacy)
    }

    pub fn load_with_policy(root: &Path, policy: SourcePolicy) -> Result<Self, Diagnostic> {
        Self::load_detailed_with_policy(root, policy).map_err(LoadFailure::into_diagnostic)
    }

    pub(crate) fn load_detailed_with_policy(
        root: &Path,
        policy: SourcePolicy,
    ) -> Result<Self, LoadFailure> {
        let mut budget = SourceBudget { policy, used: 0 };
        budget.allowance(root)?;
        let root = fs::canonicalize(root).map_err(|failure| io_error(root, failure))?;
        if !root.is_dir() {
            return Err(error(
                &root,
                Span::default(),
                "source root is not a directory",
            ));
        }
        let mut files = Vec::new();
        collect_qli_files(&root, &mut files)?;
        files.sort();

        let mut modules = BTreeMap::new();
        for path in files {
            let name = local_module_name(&root, &path)?;
            let source = budget.read(&path)?;
            let module = parse_source(name.clone(), path, ModuleOrigin::Local, source)?;
            if modules.insert(name.clone(), module).is_some() {
                return Err(error(
                    &root,
                    Span::default(),
                    format!("duplicate module `{name}`"),
                ));
            }
        }

        for &(name, source) in BUNDLED_SOURCES {
            let path = PathBuf::from(format!("<bundled>/std/{name}.qli"));
            budget.charge(&path, source.len() as u64)?;
            let ast = parse_module(source).map_err(|failure| {
                located_error(
                    &path,
                    source,
                    failure.span,
                    "parse",
                    format!("parse error: {}", failure.message),
                )
            })?;
            let module = SourceModule {
                name: format!("std::{name}"),
                path,
                source: source.to_owned(),
                ast,
                imports: BTreeMap::new(),
                origin: ModuleOrigin::Bundled,
            };
            check_declarations(&module)?;
            modules.insert(module.name.clone(), module);
        }

        let mut project = Self { root, modules };
        project.resolve_imports()?;
        project.reject_cycles()?;
        Ok(project)
    }

    pub fn module(&self, name: &str) -> Option<&SourceModule> {
        self.modules.get(name)
    }

    fn resolve_imports(&mut self) -> Result<(), LoadFailure> {
        // Resolve against immutable module declarations first, then publish the
        // completed scopes. Declaration order cannot change import meaning.
        let mut scopes = BTreeMap::new();
        for (module_name, module) in &self.modules {
            let mut used_names: BTreeSet<&str> = module
                .ast
                .decls
                .iter()
                .map(|decl| decl.name.text.as_str())
                .collect();
            let mut imports = BTreeMap::new();
            for use_decl in &module.ast.uses {
                let imported = self.resolve_one_import(module, use_decl)?;
                let local_name = imported.name.clone();
                if !used_names.insert(&use_decl.path.last().expect("parser requires name").text) {
                    return Err(source_error(
                        module,
                        use_decl.path.last().expect("parser requires name").span,
                        format!("name `{local_name}` collides with another declaration or import"),
                    ));
                }
                imports.insert(local_name, imported);
            }
            scopes.insert(module_name.clone(), imports);
        }
        for (module_name, imports) in scopes {
            self.modules
                .get_mut(&module_name)
                .expect("module exists")
                .imports = imports;
        }
        Ok(())
    }

    fn resolve_one_import(
        &self,
        caller: &SourceModule,
        use_decl: &UseDecl,
    ) -> Result<ResolvedImport, LoadFailure> {
        let segments = &use_decl.path;
        if segments.len() < 2 {
            return Err(source_error(
                caller,
                use_decl.span,
                "import needs a module and a name",
            ));
        }
        let name = &segments.last().expect("nonempty import path").text;
        let source_module = segments[..segments.len() - 1]
            .iter()
            .map(|segment| segment.text.as_str())
            .collect::<Vec<_>>()
            .join("::");

        if source_module == "std::quantum" || source_module == "std::observe" {
            if let Some(kind) = sealed_kind(&source_module, name) {
                return Ok(ResolvedImport {
                    module: source_module,
                    name: name.clone(),
                    kind,
                    origin: ImportOrigin::Sealed,
                    span: use_decl.span,
                });
            }
            return Err(source_error(
                caller,
                segments.last().expect("nonempty import path").span,
                format!("sealed module `{source_module}` has no public name `{name}`"),
            ));
        }
        let target = self.modules.get(&source_module).ok_or_else(|| {
            source_error(
                caller,
                use_decl.span,
                format!("missing module `{source_module}`"),
            )
        })?;
        let declaration = target
            .ast
            .decls
            .iter()
            .find(|declaration| declaration.name.text == *name)
            .ok_or_else(|| {
                source_error(
                    caller,
                    segments.last().expect("nonempty import path").span,
                    format!("module `{source_module}` has no name `{name}`"),
                )
            })?;
        if !declaration.public {
            return Err(source_error(
                caller,
                segments.last().expect("nonempty import path").span,
                format!("`{source_module}::{name}` is not public"),
            ));
        }
        Ok(ResolvedImport {
            module: source_module,
            name: name.clone(),
            kind: declaration.kind,
            origin: match target.origin {
                ModuleOrigin::Local => ImportOrigin::Local,
                ModuleOrigin::Bundled => ImportOrigin::Bundled,
            },
            span: use_decl.span,
        })
    }

    fn reject_cycles(&self) -> Result<(), LoadFailure> {
        let mut marks = BTreeMap::<&str, u8>::new();
        // Each frame records the next import to visit. Keep the active path on
        // the heap so a long acyclic module chain cannot exhaust the Rust stack.
        let mut stack = Vec::<(&str, usize)>::new();
        for name in self.modules.keys() {
            if marks.get(name.as_str()).copied() == Some(2) {
                continue;
            }
            marks.insert(name, 1);
            stack.push((name, 0));
            while let Some((name, next_import)) = stack.last_mut() {
                let module = self.modules.get(*name).expect("known module");
                let Some(use_decl) = module.ast.uses.get(*next_import) else {
                    marks.insert(*name, 2);
                    stack.pop();
                    continue;
                };
                *next_import += 1;
                let local_name = &use_decl.path.last().expect("parser requires name").text;
                let imported = module.imports.get(local_name).expect("imports resolved");
                if imported.origin == ImportOrigin::Sealed {
                    continue;
                }
                let dependency = imported.module.as_str();
                match marks.get(dependency).copied() {
                    Some(1) => {
                        let start = stack
                            .iter()
                            .position(|(name, _)| *name == dependency)
                            .expect("active module is on the DFS path");
                        let mut cycle: Vec<_> =
                            stack[start..].iter().map(|(name, _)| *name).collect();
                        cycle.push(dependency);
                        return Err(source_error(
                            module,
                            use_decl.span,
                            format!("cyclic import: {}", cycle.join(" -> ")),
                        ));
                    }
                    Some(2) => continue,
                    _ => {}
                }
                marks.insert(dependency, 1);
                stack.push((dependency, 0));
            }
        }
        Ok(())
    }
}

fn collect_qli_files(directory: &Path, files: &mut Vec<PathBuf>) -> Result<(), LoadFailure> {
    let mut entries = fs::read_dir(directory)
        .map_err(|failure| io_error(directory, failure))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|failure| io_error(directory, failure))?;
    entries.sort_by_key(|entry| entry.file_name());
    for entry in entries {
        let path = entry.path();
        let kind = entry
            .file_type()
            .map_err(|failure| io_error(&path, failure))?;
        if kind.is_symlink() {
            return Err(error(
                &path,
                Span::default(),
                "symlinks are not allowed in a source root",
            ));
        }
        if kind.is_dir() {
            collect_qli_files(&path, files)?;
        } else if kind.is_file() && path.extension().is_some_and(|extension| extension == "qli") {
            files.push(path);
        }
    }
    Ok(())
}

fn local_module_name(root: &Path, path: &Path) -> Result<String, LoadFailure> {
    let relative = path.strip_prefix(root).expect("collected beneath root");
    let mut parts = Vec::new();
    let file = relative.file_name().expect("collected file has a name");
    for component in relative.parent().into_iter().flat_map(Path::components) {
        let text = component
            .as_os_str()
            .to_str()
            .ok_or_else(|| error(path, Span::default(), "module path is not valid UTF-8"))?;
        if !valid_ident(text) {
            return Err(error(
                path,
                Span::default(),
                format!("invalid module path component `{text}`"),
            ));
        }
        parts.push(text.to_owned());
    }
    let file = file
        .to_str()
        .ok_or_else(|| error(path, Span::default(), "module path is not valid UTF-8"))?;
    let stem = file.strip_suffix(".qli").expect("collected .qli file");
    if !valid_ident(stem) {
        return Err(error(
            path,
            Span::default(),
            format!("invalid module path component `{stem}`"),
        ));
    }
    parts.push(stem.to_owned());
    if parts.first().is_some_and(|part| part == "std") {
        return Err(error(
            path,
            Span::default(),
            "`std::` is reserved for bundled modules",
        ));
    }
    Ok(parts.join("::"))
}

fn valid_ident(name: &str) -> bool {
    let mut bytes = name.bytes();
    let Some(first) = bytes.next() else {
        return false;
    };
    (first.is_ascii_alphabetic() || first == b'_' && name.len() > 1)
        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
        && keyword_kind(name).is_none()
}

fn parse_source(
    name: String,
    path: PathBuf,
    origin: ModuleOrigin,
    source: String,
) -> Result<SourceModule, LoadFailure> {
    let ast = parse_module(&source).map_err(|failure| {
        located_error(
            &path,
            &source,
            failure.span,
            "parse",
            format!("parse error: {}", failure.message),
        )
    })?;
    let module = SourceModule {
        name,
        path,
        source,
        ast,
        imports: BTreeMap::new(),
        origin,
    };
    check_declarations(&module)?;
    Ok(module)
}

fn check_declarations(module: &SourceModule) -> Result<(), LoadFailure> {
    let mut seen = BTreeSet::new();
    for declaration in &module.ast.decls {
        if !seen.insert(declaration.name.text.as_str()) {
            return Err(source_error(
                module,
                declaration.name.span,
                format!("duplicate declaration `{}`", declaration.name.text),
            ));
        }
    }
    Ok(())
}

fn sealed_kind(module: &str, name: &str) -> Option<FnKind> {
    super::core::primitive(module, name).map(|item| item.kind)
}