ulo 0.1.0-alpha.3

Fast and modular web framework for scalable applications
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
//! Step 3: the visibility tables and every injection point resolved against its module's table
//! (§8.2, §10.1 step 3).

use std::collections::{HashMap, HashSet};

use crate::binding::Recipe;
use crate::dependency::{Dependencies, ReadKind};
use crate::error::wiring::WiringError;
use crate::graph::wire::Declared;
use crate::graph::{
    BindingId, Edge, EdgeTarget, Graph, ModuleId, Visible, VisibilityTable, boundary_key, dependency_label, record_key,
};
use crate::key::{BindingKind, Key};
use crate::transport::controller::EnhancerDep;
use crate::type_name::short_type_name;

/// Fills `graph.visibility`: each module's own bindings, its direct imports' exports and the
/// globals' exports, a key with two sources recorded as `Visible::Ambiguous`. Execution inputs
/// are app-wide and in every table, below any binding under the same key.
///
/// Only the modules this wiring added get tables; a lazy load's base modules keep theirs, and
/// their resolved exports are read from `graph.exported`.
pub(crate) fn build_tables(graph: &mut Graph, declared: &Declared) {
    let count = graph.modules.len();
    graph.visibility.resize_with(count, VisibilityTable::default);
    graph.exported.resize_with(count, Vec::new);

    for (module, export) in declared.exports.iter().filter(|(_, export)| !export.reexport) {
        if let Some(id) = own_binding(graph, *module, export.key) {
            let key = boundary_key(graph.module(*module).keyed, export.key);
            graph.exported[module.0 as usize].push((key, id));
        }
    }

    // A re-export reads its module's view, which holds other modules' exports, re-exports
    // among them; each round resolves what the last round made visible. One that never resolves
    // is reported by step 1 as not visible or ambiguous.
    let mut pending: Vec<&(ModuleId, crate::module::def::ExportRecord)> =
        declared.exports.iter().filter(|(_, export)| export.reexport).collect();
    loop {
        let view: &Graph = graph;
        let mut resolved = Vec::new();
        pending.retain(|entry| {
            let (module, export) = &**entry;
            match sources(view, *module, export.key).as_slice() {
                [(_, id)] => {
                    resolved.push((*module, boundary_key(view.module(*module).keyed, export.key), *id));
                    false
                }
                _ => true,
            }
        });
        if resolved.is_empty() {
            break;
        }
        for (module, key, id) in resolved {
            graph.exported[module.0 as usize].push((key, id));
        }
    }

    for index in declared.first_module..count {
        let table = table_for(graph, ModuleId(index as u32));
        graph.visibility[index] = table;
    }
}

/// The first single binding of `module` itself answering to `key`. A second one is a duplicate
/// that step 2 reports.
pub(crate) fn own_binding(graph: &Graph, module: ModuleId, key: Key) -> Option<BindingId> {
    graph.module(module).bindings.iter().copied().find(|&id| {
        let record = &graph.binding(id).record;
        record.kind == BindingKind::Single && record.keys().any(|own| own == key)
    })
}

/// Every source `module` sees for `key`, one per binding: its own binding first, then its
/// imports' and the globals' exports. One binding reached through two routes is one source.
pub(crate) fn sources(graph: &Graph, module: ModuleId, key: Key) -> Vec<(ModuleId, BindingId)> {
    let mut found: Vec<(ModuleId, BindingId)> = own_binding(graph, module, key).map(|id| (module, id)).into_iter().collect();
    for exporter in exporters(graph, module) {
        for &(exported, id) in &graph.exported[exporter.0 as usize] {
            if exported == key && !found.iter().any(|&(_, seen)| seen == id) {
                found.push((exporter, id));
            }
        }
    }
    found
}

/// The modules whose exports `module` sees: its direct imports, then every global module.
fn exporters(graph: &Graph, module: ModuleId) -> impl Iterator<Item = ModuleId> + '_ {
    let imports = graph.module(module).imports.iter().copied();
    let globals = graph.modules.iter().filter(|m| m.global).map(|m| m.id);
    imports.chain(globals)
}

fn table_for(graph: &Graph, module: ModuleId) -> VisibilityTable {
    let mut sources: HashMap<Key, Vec<(ModuleId, BindingId)>> = HashMap::new();
    for &id in &graph.module(module).bindings {
        let record = &graph.binding(id).record;
        if record.kind != BindingKind::Single {
            continue;
        }
        for key in record.keys() {
            sources.entry(key).or_insert_with(|| vec![(module, id)]);
        }
    }
    for exporter in exporters(graph, module) {
        for &(key, id) in &graph.exported[exporter.0 as usize] {
            let list = sources.entry(key).or_default();
            if !list.iter().any(|&(_, seen)| seen == id) {
                list.push((exporter, id));
            }
        }
    }

    let mut entries: HashMap<Key, Visible> = sources
        .into_iter()
        .map(|(key, list)| {
            let visible = if list.len() == 1 { Visible::Binding(list[0].1) } else { Visible::Ambiguous(list) };
            (key, visible)
        })
        .collect();
    for &key in graph.inputs.keys() {
        entries.entry(key).or_insert(Visible::Input(key));
    }
    VisibilityTable { entries }
}

/// Resolves every injection point of every binding, hook closure, readiness check, handler
/// parameter, enhancer declaration and metadata value into `Edge`s, and reports missing keys
/// (with the injection point, the key and the module) and ambiguous keys (naming every source
/// module). A missing key whose name equals a bound key's name up to a trailing
/// `+ core::marker::Send + core::marker::Sync` names both spellings.
///
/// Only a binding's own dependencies become edges. Readiness checks, hooks, handler parameters,
/// enhancer closures and metadata are checked for missing and ambiguous keys alone; the passes
/// that need what they read resolve it again from the tables. A handler's parameters resolve
/// against its controller's module, where the pipeline reads them.
///
/// The root's table is then swept: an ambiguous key there is reported even when nothing reads
/// it, because a lookup naming no module uses the root's visibility and has no variant for an
/// ambiguity (§8.2).
pub(crate) fn resolve_dependencies(graph: &mut Graph, declared: &Declared, errors: &mut Vec<WiringError>) {
    let mut reported: HashSet<(ModuleId, Key)> = HashSet::new();

    for index in declared.first_binding..graph.bindings.len() {
        let edges = binding_edges(graph, BindingId(index as u32), errors, &mut reported);
        graph.bindings[index].edges = edges;
    }

    let graph = &*graph;
    for binding in graph.bindings.iter().skip(declared.first_binding) {
        if let Some(ready) = &binding.record.ready {
            let owner = format!("readiness check of {}", graph.label(binding.id));
            check_dependencies(graph, binding.origin, &ready.dependencies, &owner, errors, &mut reported);
        }
        for hook in &binding.record.hooks {
            let owner = format!("{} hook of {}", hook.kind, graph.label(binding.id));
            check_dependencies(graph, binding.origin, &hook.dependencies, &owner, errors, &mut reported);
        }
    }
    for module in graph.modules.iter().skip(declared.first_module) {
        for hook in &module.hooks {
            let owner = format!("{} hook of {}", hook.kind, module.name);
            check_dependencies(graph, module.id, &hook.dependencies, &owner, errors, &mut reported);
        }
    }
    for (module, name, dependencies) in &declared.meta {
        let owner = format!("metadata `{}` of {}", short_type_name(*name), graph.module_name(*module));
        check_dependencies(graph, *module, dependencies, &owner, errors, &mut reported);
    }
    for handler in graph.handlers.iter().skip(declared.first_handler) {
        let name = graph.handler_name(handler);
        // The pipeline finds the controller by its key in its own module, which an import
        // exporting the same type would make ambiguous; nothing else reads that key.
        let controller = record_key(&graph.binding(handler.controller).record);
        if let Some(Visible::Ambiguous(list)) = graph.lookup(handler.module, controller) {
            if reported.insert((handler.module, controller)) {
                errors.push(WiringError::Ambiguous {
                    key: controller.name(BindingKind::Single),
                    consumer: format!("{name} (its controller)"),
                    module: graph.module_name(handler.module),
                    sources: ambiguous_sources(graph, list),
                });
            }
        }
        check_dependencies(graph, handler.module, &handler.decl.dependencies, &name, errors, &mut reported);
        for dep in &handler.decl.enhancer_deps {
            match dep {
                EnhancerDep::Type(key) => {
                    let consumer = || format!("{name} (enhancer `{}`)", key.type_name());
                    check_key(graph, handler.module, *key, false, consumer, errors, &mut reported);
                }
                EnhancerDep::Closure(closure) => {
                    let owner = format!("{name} (enhancer closure)");
                    check_dependencies(graph, handler.module, &closure.dependencies, &owner, errors, &mut reported);
                }
            }
        }
    }

    if declared.first_module == 0 {
        let root = graph.root;
        let mut unread: Vec<(&Key, &Vec<(ModuleId, BindingId)>)> = graph.visibility[root.0 as usize]
            .entries
            .iter()
            .filter_map(|(key, visible)| match visible {
                Visible::Ambiguous(list) if !reported.contains(&(root, *key)) => Some((key, list)),
                _ => None,
            })
            .collect();
        unread.sort_by_key(|(key, _)| (key.type_name().full(), key.qualifier_name()));
        for (key, list) in unread {
            errors.push(WiringError::Ambiguous {
                key: key.name(BindingKind::Single),
                consumer: "a lookup that names no module".to_owned(),
                module: graph.module_name(root),
                sources: ambiguous_sources(graph, list),
            });
        }
    }
}

/// Every read of a controller's key by a binding that is not a controller: its construction's
/// edges, its hooks and readiness check, and an alias naming the controller; and by a module's own
/// hook or a handler's enhancer closure. Each injection point is one entry. A controller reading
/// another controller is not refused, since both sit at the edge; a handler parameter is not
/// checked either.
pub(crate) fn check_controller_reads(graph: &Graph, declared: &Declared, errors: &mut Vec<WiringError>) {
    let controller_of = |module: ModuleId, key: Key| match graph.lookup(module, key) {
        Some(Visible::Binding(id)) if graph.binding(*id).record.controller => Some(*id),
        _ => None,
    };
    let report = |reader_module: ModuleId, controller: BindingId, consumer: String, errors: &mut Vec<WiringError>| {
        errors.push(WiringError::ControllerRead {
            controller: graph.key_name(controller),
            consumer,
            module: graph.module_name(reader_module),
            controller_module: graph.module_name(graph.binding(controller).origin),
        });
    };
    for reader in graph.bindings.iter().skip(declared.first_binding).filter(|binding| !binding.record.controller) {
        for edge in &reader.edges {
            if let EdgeTarget::Binding(id) = edge.target
                && graph.binding(id).record.controller
            {
                report(reader.origin, id, graph.consumer(reader.id, edge.dependency), errors);
            }
        }
        if let Recipe::Alias { target } = &reader.record.recipe
            && let Some(id) = controller_of(reader.origin, *target)
        {
            report(reader.origin, id, format!("the alias `{}`", graph.key_name(reader.id)), errors);
        }
        let ready = reader.record.ready.iter().map(|ready| (format!("readiness check of {}", graph.label(reader.id)), &ready.dependencies));
        let hooks =
            reader.record.hooks.iter().map(|hook| (format!("{} hook of {}", hook.kind, graph.label(reader.id)), &hook.dependencies));
        for (owner, dependencies) in ready.chain(hooks) {
            for dependency in &dependencies.list {
                for read in &dependency.requirement.reads {
                    if let ReadKind::Single(key) = &read.kind
                        && let Some(id) = controller_of(reader.origin, *key)
                    {
                        report(reader.origin, id, format!("{owner} ({})", dependency_label(dependency.label)), errors);
                    }
                }
            }
        }
    }
    let closure_reads = |module: ModuleId, owner: &str, dependencies: &Dependencies, errors: &mut Vec<WiringError>| {
        for dependency in &dependencies.list {
            for read in &dependency.requirement.reads {
                if let ReadKind::Single(key) = &read.kind
                    && let Some(id) = controller_of(module, *key)
                {
                    report(module, id, format!("{owner} ({})", dependency_label(dependency.label)), errors);
                }
            }
        }
    };
    for module in graph.modules.iter().skip(declared.first_module) {
        for hook in &module.hooks {
            closure_reads(module.id, &format!("{} hook of {}", hook.kind, module.name), &hook.dependencies, errors);
        }
    }
    for handler in graph.handlers.iter().skip(declared.first_handler) {
        for dep in &handler.decl.enhancer_deps {
            if let EnhancerDep::Closure(closure) = dep {
                let owner = format!("{} (enhancer closure)", graph.handler_name(handler));
                closure_reads(handler.module, &owner, &closure.dependencies, errors);
            }
        }
    }
}

fn binding_edges(
    graph: &Graph,
    id: BindingId,
    errors: &mut Vec<WiringError>,
    reported: &mut HashSet<(ModuleId, Key)>,
) -> Vec<Edge> {
    let binding = graph.binding(id);
    let mut edges = Vec::new();
    for (index, dependency) in binding.record.dependencies.list.iter().enumerate() {
        for read in &dependency.requirement.reads {
            let target = match &read.kind {
                ReadKind::Single(key) => {
                    let consumer = || graph.consumer(id, index);
                    check_key(graph, binding.origin, *key, read.optional, consumer, errors, reported)
                }
                ReadKind::Collection(key) => Some(EdgeTarget::Collection(*key)),
                ReadKind::Extension(_) | ReadKind::Execution => Some(EdgeTarget::Execution),
                ReadKind::Module => Some(EdgeTarget::Module),
            };
            if let Some(target) = target {
                edges.push(Edge { target, dependency: index, optional: read.optional });
            }
        }
    }
    edges
}

/// Every single-key read of `dependencies` checked against `module`'s table, each named
/// ``{owner} (param #1)``.
fn check_dependencies(
    graph: &Graph,
    module: ModuleId,
    dependencies: &Dependencies,
    owner: &str,
    errors: &mut Vec<WiringError>,
    reported: &mut HashSet<(ModuleId, Key)>,
) {
    for dependency in &dependencies.list {
        for read in &dependency.requirement.reads {
            if let ReadKind::Single(key) = &read.kind {
                let consumer = || format!("{owner} ({})", dependency_label(dependency.label));
                check_key(graph, module, *key, read.optional, consumer, errors, reported);
            }
        }
    }
}

/// What `key` resolves to in `module`, or the error a read of it is reported with. A
/// missing optional read is no error and no edge.
fn check_key(
    graph: &Graph,
    module: ModuleId,
    key: Key,
    optional: bool,
    consumer: impl FnOnce() -> String,
    errors: &mut Vec<WiringError>,
    reported: &mut HashSet<(ModuleId, Key)>,
) -> Option<EdgeTarget> {
    match graph.lookup(module, key) {
        Some(Visible::Binding(id)) => Some(EdgeTarget::Binding(*id)),
        Some(Visible::Input(input)) => Some(EdgeTarget::Input(*input)),
        Some(Visible::Ambiguous(list)) => {
            reported.insert((module, key));
            errors.push(WiringError::Ambiguous {
                key: key.name(BindingKind::Single),
                consumer: consumer(),
                module: graph.module_name(module),
                sources: ambiguous_sources(graph, list),
            });
            None
        }
        None => {
            if !optional {
                errors.push(WiringError::Missing {
                    key: key.name(BindingKind::Single),
                    consumer: consumer(),
                    module: graph.module_name(module),
                    near: near_spelling(graph, module, key)
                        .map(|(near, exporter)| (near.name(BindingKind::Single), graph.module_name(exporter))),
                });
            }
            None
        }
    }
}

fn ambiguous_sources(
    graph: &Graph,
    list: &[(ModuleId, BindingId)],
) -> Vec<(crate::module::ModuleName, &'static std::panic::Location<'static>)> {
    list.iter().map(|&(module, id)| (graph.module_name(module), graph.binding(id).record.location)).collect()
}

/// The bound key spelled like `missing`, for the hint on a missing dependency, with the module
/// providing it: one `module` sees first, then any binding in the graph. See `spelled_alike`.
pub(crate) fn near_spelling(graph: &Graph, module: ModuleId, missing: Key) -> Option<(Key, ModuleId)> {
    let near = |key: &Key| spelled_alike(*key, missing);

    let mut visible: Vec<(Key, ModuleId)> = graph.visibility[module.0 as usize]
        .entries
        .iter()
        .filter(|(key, _)| near(*key))
        .filter_map(|(key, visible)| match visible {
            Visible::Binding(id) => Some((*key, graph.binding(*id).origin)),
            Visible::Ambiguous(list) => list.first().map(|&(source, _)| (*key, source)),
            Visible::Input(_) => None,
        })
        .collect();
    // A key of the same full name, one type from two versions of its crate, is the likelier
    // cause, so it is named before one spelled alike by its last segment.
    visible.sort_by_key(|(key, _)| (!two_versions(*key, missing), key.type_name().full()));
    if let Some(found) = visible.into_iter().next() {
        return Some(found);
    }
    let anywhere = || graph.bindings.iter().flat_map(|binding| binding.record.keys().map(move |key| (key, binding.origin)));
    anywhere()
        .find(|(key, _)| near(key) && two_versions(*key, missing))
        .or_else(|| anywhere().find(|(key, _)| near(key)))
}

/// A key `module` binds itself spelled like `exported`, for the hint on an export of a key the
/// module does not bind.
pub(crate) fn own_near_spelling(graph: &Graph, module: ModuleId, exported: Key) -> Option<Key> {
    graph.module(module).bindings.iter().find_map(|&id| {
        let record = &graph.binding(id).record;
        if record.kind != BindingKind::Single {
            return None;
        }
        record.keys().find(|key| spelled_alike(*key, exported))
    })
}

/// Two different keys under one qualifier that a report cannot tell apart at a glance: equal up
/// to trailing `Send` and `Sync` bounds, which are distinct `TypeId`s, equal in their last path
/// segments, `a::Config` beside `b::Config`, or equal in their full names with distinct `TypeId`s,
/// which is one type from two versions of its crate (I12).
fn spelled_alike(key: Key, other: Key) -> bool {
    key.qualifier_id() == other.qualifier_id()
        && (two_versions(key, other)
            || (key.type_name().full() != other.type_name().full()
                && short_type_name(strip_auto_traits(key.type_name().full()))
                    == short_type_name(strip_auto_traits(other.type_name().full()))))
}

/// The same full type name on two `TypeId`s: `type_name` writes a crate's name without its
/// version, so two versions of one crate in the build give two types under one path.
pub(crate) fn two_versions(key: Key, other: Key) -> bool {
    key.type_id() != other.type_id() && key.type_name().full() == other.type_name().full()
}

/// `name` without trailing auto-trait bounds, in either order and either spelling.
fn strip_auto_traits(name: &str) -> &str {
    const SUFFIXES: [&str; 4] = [" + core::marker::Send", " + core::marker::Sync", " + Send", " + Sync"];
    let mut name = name;
    while let Some(rest) = SUFFIXES.iter().find_map(|suffix| name.strip_suffix(*suffix)) {
        name = rest;
    }
    name
}