bern-macros 0.1.0

Procedural macros for Bern declarations
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
//! Project configuration for early checks.
//!
//! The build tool performs the authoritative checks; reading `Bern.toml`
//! here lets missing translations fail inside the editor with an exact
//! span, and gives the shell protocol's `Client` the module switches the
//! application composes. Files read are tracked with `include_bytes!` so
//! edits re-run macros.

use std::path::{Path, PathBuf};

#[derive(Clone, Debug)]
pub struct Languages {
    pub supported: Vec<String>,
    pub strict: bool,
    pub path: PathBuf,
}

/// The optional modules of an application, in the order of its
/// `[[modules]]`: what `app.modules.<id>` reads.
#[derive(Clone, Debug, Default)]
pub struct OptionalModules {
    pub ids: Vec<String>,
    /// Every module manifest read, to re-run the macro when one changes.
    pub manifests: Vec<PathBuf>,
}

/// Find `Bern.toml` in the crate directory or an ancestor.
fn nearest_manifest() -> Option<PathBuf> {
    let manifest = std::env::var("CARGO_MANIFEST_DIR").ok()?;
    let mut directory = Some(PathBuf::from(manifest));
    while let Some(current) = directory {
        let candidate = current.join("Bern.toml");
        if candidate.is_file() {
            return Some(candidate);
        }
        directory = current.parent().map(PathBuf::from);
    }
    None
}

fn read(path: &Path) -> Result<toml::Value, String> {
    let text = std::fs::read_to_string(path)
        .map_err(|error| format!("cannot read {}: {error}", path.display()))?;
    text.parse()
        .map_err(|error| format!("{} is not valid TOML: {error}", path.display()))
}

pub fn languages() -> Result<Option<Languages>, String> {
    match nearest_manifest() {
        Some(path) => parse(path).map(Some),
        None => Ok(None),
    }
}

fn parse(path: PathBuf) -> Result<Languages, String> {
    let value = read(&path)?;
    let languages = value
        .get("languages")
        .ok_or_else(|| format!("{} needs a [languages] table", path.display()))?;
    let supported: Vec<String> = languages
        .get("supported")
        .and_then(toml::Value::as_array)
        .ok_or_else(|| "[languages] needs `supported = [\"…\"]`".to_string())?
        .iter()
        .filter_map(|value| value.as_str().map(str::to_string))
        .collect();
    let strict = languages
        .get("strict")
        .and_then(toml::Value::as_bool)
        .unwrap_or(true);
    Ok(Languages {
        supported,
        strict,
        path,
    })
}

/// The enclosing application, including when expanding a crate inside a module.
fn application_manifest() -> Option<PathBuf> {
    let mut dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").ok()?);
    loop {
        let path = dir.join("Bern.toml");
        if path.is_file() && read(&path).ok().is_some_and(|v| v.get("app").is_some()) {
            return Some(path);
        }
        if !dir.pop() {
            return None;
        }
    }
}

fn excluded_for(path: &Path) -> Vec<String> {
    let root = std::env::var_os("BERN_BUILD_ROOT").map(PathBuf::from);
    if root.and_then(|p| p.canonicalize().ok()) != path.parent().and_then(|p| p.canonicalize().ok())
    {
        return Vec::new();
    }
    std::env::var("BERN_EXCLUDE_MODULES")
        .unwrap_or_default()
        .split(',')
        .filter(|id| !id.is_empty())
        .map(str::to_string)
        .collect()
}

pub fn build_modules() -> syn::Result<bern_syntax::build::Modules> {
    let Some(path) = application_manifest() else {
        return Ok(Default::default());
    };
    let result = (|| -> Result<_, String> {
        let app = read(&path)?;
        let excluded = excluded_for(&path);
        let modules = all_module_manifests(&path, &app)?
            .into_iter()
            .filter_map(|(_, module)| {
                let id = module.get("module")?.get("id")?.as_str()?.to_string();
                let enabled = !excluded.contains(&id);
                Some((id, enabled))
            })
            .collect();
        Ok(bern_syntax::build::Modules(modules))
    })();
    result.map_err(|e| syn::Error::new(proc_macro2::Span::call_site(), e))
}

/// Track both environment inputs in rustc's dep-info, including transitions
/// from a selected build back to an ordinary all-module Cargo build.
pub fn track_build() -> proc_macro2::TokenStream {
    let manifest: Vec<_> = application_manifest()
        .map(|p| p.display().to_string())
        .into_iter()
        .collect();
    quote::quote! {
        const _: Option<&str> = ::core::option_env!("BERN_BUILD_ROOT");
        const _: Option<&str> = ::core::option_env!("BERN_EXCLUDE_MODULES");
        #(const _: &[u8] = ::core::include_bytes!(#manifest);)*
    }
}

fn module_manifests(path: &Path, app: &toml::Value) -> Result<Vec<(PathBuf, toml::Value)>, String> {
    let excluded = excluded_for(path);
    Ok(all_module_manifests(path, app)?
        .into_iter()
        .filter(|(_, module)| {
            !module
                .get("module")
                .and_then(|m| m.get("id"))
                .and_then(toml::Value::as_str)
                .is_some_and(|id| excluded.iter().any(|e| e == id))
        })
        .collect())
}

/// The manifests of the modules of the application in `app`, read from
/// `path`, in the order of its `[[modules]]`.
fn all_module_manifests(
    path: &Path,
    app: &toml::Value,
) -> Result<Vec<(PathBuf, toml::Value)>, String> {
    let dir = path.parent().unwrap_or(Path::new("."));
    let entries = app.get("modules").and_then(toml::Value::as_array);
    entries
        .into_iter()
        .flatten()
        .filter_map(|entry| entry.get("path").and_then(toml::Value::as_str))
        .map(|module_dir| {
            let manifest = dir.join(module_dir).join("Bern.toml");
            read(&manifest).map(|module| (manifest, module))
        })
        .collect()
}

/// The value types the protocol of module `namespace` of the enclosing
/// application may use from the protocols of the modules it depends on,
/// as the build tool reads them, and every protocol source read. Empty for
/// a protocol that is not a module's.
pub fn imported_types(namespace: &str) -> Result<(bern_protocol::TypeTable, Vec<PathBuf>), String> {
    let Some(path) = application_manifest() else {
        return Ok(Default::default());
    };
    let app = read(&path)?;
    let modules = module_manifests(&path, &app)?;
    let selection = build_modules().map_err(|error| error.to_string())?;
    let mut files = Vec::new();
    let mut done = std::collections::BTreeMap::new();
    let imported = imports_of(namespace, &modules, &selection, &mut done, &mut files)?;
    Ok((imported, files))
}

fn depends_of(module: &toml::Value) -> Vec<String> {
    module
        .get("module")
        .and_then(|module| module.get("depends"))
        .and_then(toml::Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|id| id.as_str().map(str::to_string))
        .collect()
}

/// The types of the modules module `id` depends on, each lowered with the
/// types of those it depends on in turn.
fn imports_of(
    id: &str,
    modules: &[(PathBuf, toml::Value)],
    selection: &bern_syntax::build::Modules,
    done: &mut std::collections::BTreeMap<String, bern_protocol::TypeTable>,
    files: &mut Vec<PathBuf>,
) -> Result<bern_protocol::TypeTable, String> {
    let module_id = |module: &toml::Value| {
        module
            .get("module")
            .and_then(|module| module.get("id"))
            .and_then(toml::Value::as_str)
            .map(str::to_string)
    };
    let Some((_, module)) = modules
        .iter()
        .find(|(_, module)| module_id(module).as_deref() == Some(id))
    else {
        return Ok(Default::default());
    };
    let mut imported = bern_protocol::TypeTable::default();
    for dependency in depends_of(module) {
        if !done.contains_key(&dependency) {
            let types = protocol_types(&dependency, modules, selection, done, files)?;
            done.insert(dependency.clone(), types);
        }
        imported
            .merge(&done[&dependency])
            .map_err(|error| format!("modules `{id}` depends on: {}", error.message))?;
    }
    Ok(imported)
}

/// The value types of module `id`'s protocol: its own and those it took.
fn protocol_types(
    id: &str,
    modules: &[(PathBuf, toml::Value)],
    selection: &bern_syntax::build::Modules,
    done: &mut std::collections::BTreeMap<String, bern_protocol::TypeTable>,
    files: &mut Vec<PathBuf>,
) -> Result<bern_protocol::TypeTable, String> {
    let imported = imports_of(id, modules, selection, done, files)?;
    let Some((manifest, module)) = modules.iter().find(|(_, module)| {
        module
            .get("module")
            .and_then(|m| m.get("id"))
            .and_then(toml::Value::as_str)
            == Some(id)
    }) else {
        return Ok(Default::default());
    };
    let Some(source) = module
        .get("module")
        .and_then(|module| module.get("protocol"))
        .and_then(|protocol| protocol.get("source"))
        .and_then(toml::Value::as_str)
    else {
        return Ok(Default::default());
    };
    let file = manifest.parent().unwrap_or(Path::new(".")).join(source);
    let text = std::fs::read_to_string(&file)
        .map_err(|error| format!("cannot read {}: {error}", file.display()))?;
    files.push(file.clone());
    let items = bern_syntax::items::parse_source_file_with_modules(&text, selection)
        .map_err(|error| format!("{}: {error}", file.display()))?;
    let Some((_, protocol)) = items.protocols.first() else {
        return Ok(Default::default());
    };
    let descriptor = bern_syntax::lower::protocol_descriptor_with(protocol, &imported)
        .map_err(|error| format!("{}: {error}", file.display()))?;
    Ok(descriptor.types)
}

/// The optional modules when this crate is the shell protocol of the
/// application in the nearest `Bern.toml` (its `[protocol] package`);
/// none for any other crate.
pub fn optional_modules() -> Result<OptionalModules, String> {
    match (nearest_manifest(), std::env::var("CARGO_PKG_NAME")) {
        (Some(path), Ok(package)) => optional_modules_of(&path, &package),
        _ => Ok(OptionalModules::default()),
    }
}

/// The optional modules of the application in `path` when `package` is
/// its shell protocol.
fn optional_modules_of(path: &Path, package: &str) -> Result<OptionalModules, String> {
    let app = read(path)?;
    let shell = app
        .get("protocol")
        .and_then(|protocol| protocol.get("package"))
        .and_then(toml::Value::as_str);
    if shell != Some(package) {
        return Ok(OptionalModules::default());
    }
    let mut modules = OptionalModules::default();
    for (manifest, module) in module_manifests(path, &app)? {
        modules.manifests.push(manifest);
        let module = module.get("module");
        let optional = module
            .and_then(|module| module.get("optional"))
            .and_then(toml::Value::as_bool)
            .unwrap_or(false);
        let id = module
            .and_then(|module| module.get("id"))
            .and_then(toml::Value::as_str);
        if let (true, Some(id)) = (optional, id) {
            modules.ids.push(id.to_string());
        }
    }
    Ok(modules)
}

/// A page a module adds to a page slot: its id and its label by language.
#[derive(Clone, Debug)]
pub struct ModulePage {
    pub id: String,
    pub label: Vec<(String, String)>,
    /// The page comes first in the enum, as the build tool puts it.
    pub start: bool,
}

/// The pages the modules of the application in the nearest `Bern.toml`
/// add to `slot`, in order, and every module manifest read.
pub fn module_pages(slot: &str) -> Result<(Vec<ModulePage>, Vec<PathBuf>), String> {
    match nearest_manifest() {
        Some(path) => module_pages_of(&path, slot),
        None => Ok(Default::default()),
    }
}

/// The pages the modules of the application in `path` add to `slot`.
fn module_pages_of(path: &Path, slot: &str) -> Result<(Vec<ModulePage>, Vec<PathBuf>), String> {
    let app = read(path)?;
    let mut pages = Vec::new();
    let mut manifests = Vec::new();
    for (manifest, module) in module_manifests(path, &app)? {
        manifests.push(manifest);
        let entries = module.get("pages").and_then(toml::Value::as_array);
        for page in entries.into_iter().flatten() {
            if page.get("slot").and_then(toml::Value::as_str) != Some(slot) {
                continue;
            }
            let Some(id) = page.get("id").and_then(toml::Value::as_str) else {
                continue;
            };
            let label = page
                .get("label")
                .and_then(toml::Value::as_table)
                .into_iter()
                .flatten()
                .filter_map(|(language, text)| Some((language.clone(), text.as_str()?.to_string())))
                .collect();
            pages.push(ModulePage {
                id: id.to_string(),
                label,
                start: page
                    .get("start")
                    .and_then(toml::Value::as_bool)
                    .unwrap_or(false),
            });
        }
    }
    Ok((pages, manifests))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// An application with a shell protocol `app-protocol`, an optional
    /// `notes` module adding a page to `main`, and a required `sync` module.
    fn application(name: &str) -> PathBuf {
        let root =
            std::env::temp_dir().join(format!("bern-macros-config-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        for module in ["notes", "sync"] {
            std::fs::create_dir_all(root.join("modules").join(module)).unwrap();
        }
        std::fs::write(
            root.join("Bern.toml"),
            "[protocol]\npackage = \"app-protocol\"\n\n\
             [[modules]]\npath = \"modules/notes\"\n\n\
             [[modules]]\npath = \"modules/sync\"\n",
        )
        .unwrap();
        std::fs::write(
            root.join("modules/notes/Bern.toml"),
            "[module]\nid = \"notes\"\noptional = true\n\n\
             [[pages]]\nslot = \"main\"\nid = \"recent_notes\"\n\
             label = { \"en\" = \"Recent notes\", \"ja\" = \"最近のメモ\" }\n\n\
             [[pages]]\nslot = \"settings\"\nid = \"notes\"\nlabel = { \"en\" = \"Notes\" }\n",
        )
        .unwrap();
        std::fs::write(
            root.join("modules/sync/Bern.toml"),
            "[module]\nid = \"sync\"\n",
        )
        .unwrap();
        root.join("Bern.toml")
    }

    #[test]
    fn the_shell_protocol_gets_the_optional_modules() {
        let manifest = application("optional");
        let modules = optional_modules_of(&manifest, "app-protocol").unwrap();
        assert_eq!(modules.ids, ["notes"]);
        assert_eq!(modules.manifests.len(), 2);
        // Any other crate of the application gets none.
        let other = optional_modules_of(&manifest, "app-ui").unwrap();
        assert!(other.ids.is_empty());
        let _ = std::fs::remove_dir_all(manifest.parent().unwrap());
    }

    #[test]
    fn a_page_enum_gets_the_pages_of_its_slot() {
        let manifest = application("pages");
        let (pages, manifests) = module_pages_of(&manifest, "main").unwrap();
        assert_eq!(manifests.len(), 2);
        assert_eq!(pages.len(), 1);
        assert_eq!(pages[0].id, "recent_notes");
        let mut label = pages[0].label.clone();
        label.sort();
        assert_eq!(
            label,
            [
                ("en".to_string(), "Recent notes".to_string()),
                ("ja".to_string(), "最近のメモ".to_string()),
            ]
        );
        let (none, _) = module_pages_of(&manifest, "sidebar").unwrap();
        assert!(none.is_empty());
        let _ = std::fs::remove_dir_all(manifest.parent().unwrap());
    }

    #[test]
    fn a_missing_module_manifest_is_named() {
        let manifest = application("missing");
        std::fs::remove_file(manifest.parent().unwrap().join("modules/sync/Bern.toml")).unwrap();
        let error = optional_modules_of(&manifest, "app-protocol").unwrap_err();
        assert!(error.contains("modules/sync/Bern.toml"), "{error}");
        let _ = std::fs::remove_dir_all(manifest.parent().unwrap());
    }
}