printobserver-types 0.4.2

Shared domain types for printobserver.
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
//! Reading a Rust source's declared surface, for the contract tests.
//!
//! The tests that hold a crate to the surface the contract states read the
//! declarations themselves rather than a table somebody maintains beside them,
//! because a surface is a property of a declaration rather than of a value. A
//! fixture trait or a fixture vocabulary is a source snippet read by this same
//! reader, so what refuses a fixture is what reads the committed crate.
//!
//! This one reader serves the type crate's own ownership tests and each port
//! crate's `surface` test, which include it by `#[path]` from here rather
//! than through a crate of its own. A port crate declares the type crate as
//! its only workspace dependency and a reader crate would be a second edge —
//! and what this reads is Rust source, a claim about no crate in particular,
//! so it belongs to none of them. `env!("CARGO_MANIFEST_DIR")` below resolves
//! in the including crate, and every crate of this workspace sits one
//! directory under `crates/`, so [`crate_dir`] answers the same path from any
//! of them.

use std::path::PathBuf;

use quote::ToTokens;

/// One field of a struct or of a variant's payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Field {
    /// The field's name, or its position for a tuple field.
    pub name: String,
    /// The field's type, with whitespace removed.
    pub ty: String,
}

/// One parameter of a method, excluding the receiver.
pub type Param = Field;

/// One method a trait declares.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Method {
    /// The method's name.
    pub name: String,
    /// The parameters, excluding the receiver.
    pub params: Vec<Param>,
    /// The return type, with whitespace removed.
    pub returns: String,
}

/// One variant an enum declares.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Variant {
    /// The variant's name.
    pub name: String,
    /// The variant's own declared fields.
    pub fields: Vec<Field>,
}

/// A type's whitespace-free spelling, which is what these tests compare.
fn spelling<T: ToTokens>(node: &T) -> String {
    node.to_token_stream().to_string().replace([' ', '\n'], "")
}

/// Parse one Rust source.
///
/// # Panics
///
/// Panics when the source does not parse, which is what a broken fixture is.
#[must_use]
pub fn parse(source: &str) -> syn::File {
    syn::parse_file(source).expect("the source parses as Rust")
}

/// The path of one crate of this workspace.
#[must_use]
pub fn crate_dir(crate_name: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("..")
        .join(crate_name)
}

/// One crate's `src/lib.rs`.
///
/// # Panics
///
/// Panics when the crate has no readable `src/lib.rs`.
#[must_use]
pub fn crate_source(crate_name: &str) -> String {
    let path = crate_dir(crate_name).join("src").join("lib.rs");
    std::fs::read_to_string(&path)
        .unwrap_or_else(|error| panic!("read {}: {error}", path.display()))
}

/// Every `.rs` source under one crate's `src`, parsed.
///
/// # Panics
///
/// Panics when a source cannot be read or does not parse.
#[must_use]
pub fn crate_sources(crate_name: &str) -> Vec<syn::File> {
    let dir = crate_dir(crate_name).join("src");
    let mut sources = Vec::new();
    let mut paths: Vec<PathBuf> = std::fs::read_dir(&dir)
        .unwrap_or_else(|error| panic!("read {}: {error}", dir.display()))
        .map(|entry| entry.expect("a readable directory entry").path())
        .filter(|path| path.extension().is_some_and(|extension| extension == "rs"))
        .collect();
    paths.sort();
    for path in paths {
        let text = std::fs::read_to_string(&path)
            .unwrap_or_else(|error| panic!("read {}: {error}", path.display()));
        sources.push(parse(&text));
    }
    sources
}

/// The fields of one struct or variant declaration.
fn fields_of(fields: &syn::Fields) -> Vec<Field> {
    match fields {
        syn::Fields::Named(named) => named
            .named
            .iter()
            .map(|field| Field {
                name: field
                    .ident
                    .as_ref()
                    .expect("a named field has a name")
                    .to_string(),
                ty: spelling(&field.ty),
            })
            .collect(),
        syn::Fields::Unnamed(unnamed) => unnamed
            .unnamed
            .iter()
            .enumerate()
            .map(|(index, field)| Field {
                name: index.to_string(),
                ty: spelling(&field.ty),
            })
            .collect(),
        syn::Fields::Unit => Vec::new(),
    }
}

/// The methods one trait declares, in declaration order.
#[must_use]
pub fn trait_methods(file: &syn::File, trait_name: &str) -> Vec<Method> {
    let mut methods = Vec::new();
    for item in &file.items {
        let syn::Item::Trait(declaration) = item else {
            continue;
        };
        if declaration.ident != trait_name {
            continue;
        }
        for entry in &declaration.items {
            let syn::TraitItem::Fn(function) = entry else {
                continue;
            };
            let params = function
                .sig
                .inputs
                .iter()
                .filter_map(|input| match input {
                    syn::FnArg::Receiver(_) => None,
                    syn::FnArg::Typed(typed) => Some(Param {
                        name: spelling(&typed.pat),
                        ty: spelling(&typed.ty),
                    }),
                })
                .collect();
            let returns = match &function.sig.output {
                syn::ReturnType::Default => "()".to_owned(),
                syn::ReturnType::Type(_, ty) => spelling(ty),
            };
            methods.push(Method {
                name: function.sig.ident.to_string(),
                params,
                returns,
            });
        }
    }
    methods
}

/// The variants one enum declares, in declaration order.
#[must_use]
pub fn enum_variants(file: &syn::File, enum_name: &str) -> Vec<Variant> {
    let mut variants = Vec::new();
    for item in &file.items {
        let syn::Item::Enum(declaration) = item else {
            continue;
        };
        if declaration.ident != enum_name {
            continue;
        }
        for variant in &declaration.variants {
            variants.push(Variant {
                name: variant.ident.to_string(),
                fields: fields_of(&variant.fields),
            });
        }
    }
    variants
}

/// The fields one struct declares.
#[must_use]
pub fn struct_fields(file: &syn::File, struct_name: &str) -> Vec<Field> {
    for item in &file.items {
        let syn::Item::Struct(declaration) = item else {
            continue;
        };
        if declaration.ident == struct_name {
            return fields_of(&declaration.fields);
        }
    }
    Vec::new()
}

/// Whether an item is publicly visible.
fn is_public(visibility: &syn::Visibility) -> bool {
    matches!(visibility, syn::Visibility::Public(_))
}

/// Every public struct and enum one source declares, by name.
#[must_use]
pub fn declared_type_names(file: &syn::File) -> Vec<String> {
    let mut names = Vec::new();
    for item in &file.items {
        match item {
            syn::Item::Struct(declaration) if is_public(&declaration.vis) => {
                names.push(declaration.ident.to_string());
            }
            syn::Item::Enum(declaration) if is_public(&declaration.vis) => {
                names.push(declaration.ident.to_string());
            }
            _ => {}
        }
    }
    names
}

/// Every public constant one source exports: its name and its type.
#[must_use]
pub fn public_constants(file: &syn::File) -> Vec<Field> {
    file.items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Const(declaration) if is_public(&declaration.vis) => Some(Field {
                name: declaration.ident.to_string(),
                ty: spelling(&declaration.ty),
            }),
            _ => None,
        })
        .collect()
}

/// Every public free function one source exports.
#[must_use]
pub fn public_functions(file: &syn::File) -> Vec<Method> {
    file.items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Fn(declaration) if is_public(&declaration.vis) => {
                let params = declaration
                    .sig
                    .inputs
                    .iter()
                    .filter_map(|input| match input {
                        syn::FnArg::Receiver(_) => None,
                        syn::FnArg::Typed(typed) => Some(Param {
                            name: spelling(&typed.pat),
                            ty: spelling(&typed.ty),
                        }),
                    })
                    .collect();
                let returns = match &declaration.sig.output {
                    syn::ReturnType::Default => "()".to_owned(),
                    syn::ReturnType::Type(_, ty) => spelling(ty),
                };
                Some(Method {
                    name: declaration.sig.ident.to_string(),
                    params,
                    returns,
                })
            }
            _ => None,
        })
        .collect()
}

/// The documentation attached to one method of one trait.
#[must_use]
pub fn trait_method_docs(file: &syn::File, trait_name: &str, method_name: &str) -> String {
    let mut lines = Vec::new();
    for item in &file.items {
        let syn::Item::Trait(declaration) = item else {
            continue;
        };
        if declaration.ident != trait_name {
            continue;
        }
        for entry in &declaration.items {
            let syn::TraitItem::Fn(function) = entry else {
                continue;
            };
            if function.sig.ident != method_name {
                continue;
            }
            for attribute in &function.attrs {
                let syn::Meta::NameValue(pair) = &attribute.meta else {
                    continue;
                };
                if !pair.path.is_ident("doc") {
                    continue;
                }
                let syn::Expr::Lit(literal) = &pair.value else {
                    continue;
                };
                let syn::Lit::Str(text) = &literal.lit else {
                    continue;
                };
                lines.push(text.value());
            }
        }
    }
    lines.join("\n")
}

/// Whether a declaration derives one named trait.
fn derives(attrs: &[syn::Attribute], wanted: &str) -> bool {
    attrs.iter().any(|attribute| {
        attribute.path().is_ident("derive")
            && attribute.to_token_stream().to_string().contains(wanted)
    })
}

/// Every type one source declares that can emit a JSON Schema.
///
/// Three shapes reach that: a declaration deriving `JsonSchema`, one carrying a
/// hand-written `impl JsonSchema`, and an identifier newtype the `identifier!`
/// macro declares, whose expansion no source-level reader can see.
#[must_use]
pub fn schema_emitting_types(file: &syn::File) -> Vec<String> {
    let mut names = Vec::new();
    for item in &file.items {
        match item {
            syn::Item::Struct(declaration)
                if is_public(&declaration.vis) && derives(&declaration.attrs, "JsonSchema") =>
            {
                names.push(declaration.ident.to_string());
            }
            syn::Item::Enum(declaration)
                if is_public(&declaration.vis) && derives(&declaration.attrs, "JsonSchema") =>
            {
                names.push(declaration.ident.to_string());
            }
            syn::Item::Impl(block) => {
                let Some((path, _)) = &block.trait_ else {
                    continue;
                };
                if path
                    .segments
                    .last()
                    .is_some_and(|segment| segment.ident == "JsonSchema")
                {
                    names.push(spelling(&block.self_ty).replace("<f64>", ""));
                }
            }
            syn::Item::Macro(invocation) if invocation.mac.path.is_ident("identifier") => {
                let tokens = invocation.mac.tokens.to_string();
                if let Some((name, _)) = tokens.split_once(',') {
                    names.push(name.trim().to_owned());
                }
            }
            _ => {}
        }
    }
    names.sort();
    names.dedup();
    names
}

/// The crates of this workspace one manifest names, across every dependency
/// table.
///
/// A dependency of this workspace is one whose name carries the workspace's
/// prefix; a reader of Rust sources such as `syn` is not one, so a port crate's
/// test-only readers do not count against the one edge it may have.
#[must_use]
pub fn workspace_dependency_names(manifest: &str) -> Vec<String> {
    let mut names = Vec::new();
    let mut inside = false;
    for line in manifest.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('[') {
            inside = trimmed.contains("dependencies]");
            continue;
        }
        if inside
            && !trimmed.is_empty()
            && !trimmed.starts_with('#')
            && let Some((name, _)) = trimmed.split_once('=')
            && name.trim().starts_with("printobserver-")
        {
            names.push(name.trim().to_owned());
        }
    }
    names.sort();
    names.dedup();
    names
}