Skip to main content

flow_toolkit/
function.rs

1//! Function-first Rust metadata and adapters. Functions remain ordinary Rust callables.
2use std::any::Any;
3use std::collections::{BTreeMap, BTreeSet};
4use std::future::Future;
5use std::path::{Path, PathBuf};
6#[cfg(unix)]
7use std::pin::Pin;
8use std::sync::{Arc, Mutex};
9
10use crate::cli::{Command, UsageError};
11use crate::contract::{Contract, ContractError, Location};
12#[cfg(unix)]
13use crate::server::Server;
14use flow_abi::contract::{
15    self, Constructor, ContractModule, Declaration, Field, FlowDeclaration, Import, Item, Param,
16    Payload, TypeBody, TypeDeclaration, TypeRef, Visibility,
17};
18use flow_abi::wire::{Layout, Note, Notes, Parts, Shape, WireForm};
19#[cfg(unix)]
20use flow_abi::{TypeSpec, description};
21#[cfg(unix)]
22use flow_types::Placement;
23use flow_types::{LibraryLayout, Segments, lowercase_name};
24
25/// Why a [`Resource`]'s cleanup failed: any error, kept with its `source()`
26/// chain. `?` converts an error type, a `String` or a `&str` into it.
27pub type CloseError = Box<dyn std::error::Error + Send + Sync>;
28
29/// Why a `#[lifespan]` function did not make its [`Resource`]: the error it
30/// returned, kept with its `source()` chain for the serving process to
31/// report as it stops.
32pub type StartError = Box<dyn std::error::Error + Send + Sync>;
33
34#[cfg(unix)]
35type CloseFuture = Pin<Box<dyn Future<Output = Result<(), CloseError>> + Send>>;
36#[cfg(unix)]
37type Close = Box<dyn FnOnce() -> CloseFuture + Send>;
38/// The process resource while serving. A panicked holder poisons nothing
39/// that matters: every lock only swaps or clones the one `Option<Arc<_>>`,
40/// so each recovers the guard with `PoisonError::into_inner`.
41static RESOURCE: Mutex<Option<Arc<dyn Any + Send + Sync>>> = Mutex::new(None);
42
43/// A process resource retained across calls and explicitly closed at normal shutdown.
44pub struct Resource<T: Send + Sync + 'static> {
45    #[cfg(unix)]
46    value: Arc<T>,
47    #[cfg(unix)]
48    close: Box<dyn FnOnce(Arc<T>) -> CloseFuture + Send>,
49    /// Where nothing is served, no resource is kept: only its type.
50    #[cfg(not(unix))]
51    kept: std::marker::PhantomData<T>,
52}
53impl<T: Send + Sync + 'static> std::fmt::Debug for Resource<T> {
54    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        formatter
56            .debug_struct("Resource")
57            .field("type", &std::any::type_name::<T>())
58            .finish_non_exhaustive()
59    }
60}
61impl<T: Send + Sync + 'static> Resource<T> {
62    /// Creates a resource with asynchronous cleanup, run after all calls finish.
63    pub fn new<F, Fut>(value: T, close: F) -> Self
64    where
65        F: FnOnce(Arc<T>) -> Fut + Send + 'static,
66        Fut: Future<Output = Result<(), CloseError>> + Send + 'static,
67    {
68        #[cfg(unix)]
69        {
70            Self {
71                value: Arc::new(value),
72                close: Box::new(move |value| Box::pin(close(value))),
73            }
74        }
75        #[cfg(not(unix))]
76        {
77            let _ = (value, close);
78            Self {
79                kept: std::marker::PhantomData,
80            }
81        }
82    }
83    /// Creates a resource with synchronous cleanup.
84    pub fn sync<F>(value: T, close: F) -> Self
85    where
86        F: FnOnce(Arc<T>) -> Result<(), CloseError> + Send + 'static,
87    {
88        Self::new(value, move |value| std::future::ready(close(value)))
89    }
90    /// Erases the concrete type for a generated lifespan factory.
91    #[doc(hidden)]
92    pub fn into_lifespan(self) -> Lifespan {
93        #[cfg(unix)]
94        {
95            let value = Arc::clone(&self.value);
96            Lifespan {
97                value: self.value,
98                close: Box::new(move || (self.close)(value)),
99            }
100        }
101        #[cfg(not(unix))]
102        {
103            let _ = self;
104            Lifespan {}
105        }
106    }
107}
108/// A generated lifespan factory's process resource and cleanup operation.
109pub struct Lifespan {
110    #[cfg(unix)]
111    value: Arc<dyn Any + Send + Sync>,
112    #[cfg(unix)]
113    close: Close,
114}
115impl std::fmt::Debug for Lifespan {
116    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        formatter.debug_struct("Lifespan").finish_non_exhaustive()
118    }
119}
120/// A generated resource initializer, invoked only while serving.
121pub type Start = fn() -> Result<Lifespan, StartError>;
122impl crate::Context {
123    /// Retrieves the initialized process resource by its actual Rust type.
124    pub fn resource<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
125        RESOURCE
126            .lock()
127            .unwrap_or_else(std::sync::PoisonError::into_inner)
128            .as_ref()
129            .map(Arc::clone)?
130            .downcast::<T>()
131            .ok()
132    }
133}
134
135/// One named type's declaration, as its derive writes it: where the Rust
136/// type is defined, its doc comment, and its declaration.
137#[derive(Clone, Debug)]
138pub struct Declared {
139    /// The Rust type's name, which is its Flow name.
140    pub name: &'static str,
141    /// The defining Rust module, as `module_path!()` gives it.
142    pub module: &'static str,
143    /// The defining file, as `file!()` gives it.
144    pub file: &'static str,
145    /// The line of the derive, which orders it among its module's declarations.
146    pub line: u32,
147    /// The doc comment's text, one line each.
148    pub docs: &'static str,
149    /// The declaration, whose types name the module that owns each.
150    pub declaration: Declaration<Owner>,
151}
152
153/// Which module declares a type a declaration names, until extraction knows
154/// which contract module the declaration is written in: a contract module
155/// names a type of its own bare, and another module's through that
156/// module's import.
157#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
158#[non_exhaustive]
159pub enum Owner {
160    /// The Rust module that defines it, as `module_path!()` spells it.
161    Rust(&'static str),
162    /// The std module that declares it. The contract imports that module,
163    /// and names the type through the import.
164    Std(&'static str),
165}
166
167/// Named declarations collected during metadata construction, by the Rust
168/// path of the type each declares and where it is defined, and the type
169/// each form names: built from a type's [`WireForm`] and the [`Shape`] and
170/// [`Notes`] of each declaration it reaches.
171#[derive(Default, Debug)]
172pub struct Types {
173    definitions: BTreeMap<String, Declared>,
174    /// The declarations being built, which a type that holds itself reaches
175    /// again.
176    declaring: BTreeSet<String>,
177    parameters: Vec<Vec<String>>,
178}
179impl Types {
180    /// Enters the symbolic type parameters of one declaration.
181    pub fn parameters(&mut self, names: &[&str]) {
182        self.parameters
183            .push(names.iter().map(|s| (*s).into()).collect());
184    }
185    /// Leaves a declaration's symbolic type parameters.
186    pub fn end_parameters(&mut self) {
187        self.parameters.pop();
188    }
189
190    /// The type of `form`, every declaration it reaches collected.
191    ///
192    /// # Panics
193    ///
194    /// On a form no Tool's type has, a message's own, and on a declared type
195    /// without the notes `#[derive(Flow)]` gives it.
196    pub fn form(&mut self, form: WireForm) -> TypeRef<Owner> {
197        match form {
198            WireForm::Int => TypeRef::named("Int"),
199            WireForm::Decimal => TypeRef::named("Decimal"),
200            WireForm::Bool => TypeRef::named("Bool"),
201            WireForm::Text => TypeRef::named("Text"),
202            WireForm::Bytes => TypeRef::named("Bytes"),
203            WireForm::Unit => TypeRef::named("Unit"),
204            WireForm::Never => TypeRef::named("Never"),
205            WireForm::Duration => TypeRef::qualified(Owner::Std("duration"), "Duration"),
206            WireForm::Instant => TypeRef::qualified(Owner::Std("time"), "Instant"),
207            WireForm::RunId | WireForm::CallRef | WireForm::Number | WireForm::Rest => {
208                panic!("{form:?} is a message's form, which no Tool's type has")
209            }
210            WireForm::Option(item) => TypeRef::applied("Option", vec![self.form(item())]),
211            WireForm::List(item) => TypeRef::applied("List", vec![self.form(item())]),
212            WireForm::Set(item) => TypeRef::applied("Set", vec![self.form(item())]),
213            WireForm::Dict(key, value) => {
214                TypeRef::applied("Dict", vec![self.form(key()), self.form(value())])
215            }
216            WireForm::Tuple(parts) => TypeRef::Tuple(self.forms(parts)),
217            WireForm::Param(at) => TypeRef::named(
218                self.parameters
219                    .last()
220                    .and_then(|names| names.get(at))
221                    .expect("generic parameter scope"),
222            ),
223            WireForm::Declared(shape) => self.declared(shape(), &[]),
224            WireForm::Applied(shape, args) => self.declared(shape(), args),
225            WireForm::Std { module, name, args } => TypeRef::Named {
226                module: (!module.is_empty()).then_some(Owner::Std(module)),
227                name: name.to_owned(),
228                args: self.forms(args),
229            },
230        }
231    }
232
233    /// The type of each of `forms`, in order.
234    fn forms(&mut self, forms: &[fn() -> WireForm]) -> Vec<TypeRef<Owner>> {
235        forms.iter().map(|form| self.form(form())).collect()
236    }
237
238    /// `shape`'s type applied to `args`, its declaration collected the first
239    /// time it is reached; a type that holds itself is reached again while
240    /// it is being declared.
241    fn declared(&mut self, shape: &'static Shape, args: &[fn() -> WireForm]) -> TypeRef<Owner> {
242        let notes = shape
243            .notes
244            .unwrap_or_else(|| panic!("{} has no notes: derive Flow for it", shape.name));
245        let key = format!(
246            "{}::{} at {}:{}",
247            notes.module, shape.name, notes.file, notes.line
248        );
249        if !self.definitions.contains_key(&key) && self.declaring.insert(key.clone()) {
250            self.parameters(shape.params);
251            let declaration = self.declaration(shape, notes);
252            self.end_parameters();
253            self.declaring.remove(&key);
254            self.definitions.insert(
255                key,
256                Declared {
257                    name: shape.name,
258                    module: notes.module,
259                    file: notes.file,
260                    line: notes.line,
261                    docs: notes.docs,
262                    declaration,
263                },
264            );
265        }
266        TypeRef::Named {
267            module: Some(Owner::Rust(notes.module)),
268            name: shape.name.to_owned(),
269            args: self.forms(args),
270        }
271    }
272
273    /// The declaration of `shape`, its members documented as `notes` says.
274    fn declaration(&mut self, shape: &Shape, notes: &Notes) -> Declaration<Owner> {
275        let note = |at: usize| &notes.members[at];
276        let field = |types: &mut Types, note: &Note, name: &str, form: WireForm| Field {
277            docs: note.docs.to_owned(),
278            visibility: visibility(note),
279            name: name.to_owned(),
280            ty: types.form(form),
281        };
282        let body = match shape.layout {
283            Layout::Host => TypeBody::Host,
284            Layout::Newtype(base) => TypeBody::Newtype {
285                visibility: visibility(note(0)),
286                base: self.form(base),
287            },
288            Layout::Record(fields) => TypeBody::Record(
289                fields
290                    .iter()
291                    .enumerate()
292                    .map(|(at, member)| field(self, note(at), member.name, member.form))
293                    .collect(),
294            ),
295            Layout::Enum(ctors) => TypeBody::Enum(
296                ctors
297                    .iter()
298                    .enumerate()
299                    .map(|(at, ctor)| Constructor {
300                        docs: note(at).docs.to_owned(),
301                        name: ctor.name.to_owned(),
302                        payload: match ctor.parts {
303                            Parts::Empty => Payload::Empty,
304                            Parts::Positional(forms) => Payload::Positional(
305                                forms.iter().map(|form| self.form(*form)).collect(),
306                            ),
307                            Parts::Named(fields) => Payload::Named(
308                                fields
309                                    .iter()
310                                    .enumerate()
311                                    .map(|(index, member)| Field {
312                                        visibility: Visibility::Private,
313                                        ..field(
314                                            self,
315                                            &note(at).fields[index],
316                                            member.name,
317                                            member.form,
318                                        )
319                                    })
320                                    .collect(),
321                            ),
322                        },
323                    })
324                    .collect(),
325            ),
326        };
327        Declaration::Type(TypeDeclaration {
328            name: shape.name.to_owned(),
329            params: shape
330                .params
331                .iter()
332                .map(|param| (*param).to_owned())
333                .collect(),
334            body,
335        })
336    }
337}
338
339/// A member's visibility, as its note says.
340fn visibility(note: &Note) -> Visibility {
341    if note.public {
342        Visibility::Public
343    } else {
344        Visibility::Private
345    }
346}
347
348type Factory = fn() -> crate::server::Adapter;
349
350/// Where a Tool's Rust function is: the library module whose contract
351/// declares it, its file relative to the library root, and the line that
352/// orders it among that module's declarations.
353#[derive(Clone, Debug, Default)]
354struct Place {
355    module: String,
356    file: String,
357    line: u32,
358}
359
360/// Where `#[tool]` found a Tool's Rust function: its module as
361/// `module_path!()` spells it, and its file and line as `file!()` and
362/// `line!()` do.
363#[derive(Clone, Copy, Debug)]
364pub struct Origin {
365    /// The defining Rust module.
366    pub module: &'static str,
367    /// The defining file.
368    pub file: &'static str,
369    /// The line of the `#[tool]` attribute.
370    pub line: u32,
371}
372
373/// Generated metadata plus an invocation factory; construction does not call the tool.
374#[derive(Debug)]
375pub struct Function {
376    name: &'static str,
377    origin: Origin,
378    generic: Vec<String>,
379    docs: &'static str,
380    params: Vec<Param<Owner>>,
381    result: TypeRef<Owner>,
382    types: Types,
383    #[cfg(unix)]
384    factory: Factory,
385    place: Place,
386}
387impl Function {
388    /// Adds the function-owned type parameter names generated by the attribute.
389    pub(crate) fn with_generics(mut self, names: &[&str]) -> Self {
390        self.generic = names.iter().map(|name| (*name).into()).collect();
391        self
392    }
393
394    /// Places the function in the library module `module`, defined in
395    /// `file` (relative to the library root) at `line`.
396    pub(crate) fn at(mut self, module: &str, file: &str, line: u32) -> Self {
397        self.place = Place {
398            module: module.into(),
399            file: file.into(),
400            line,
401        };
402        self
403    }
404
405    /// Builds metadata emitted by `#[tool]` through the generated adapter ABI.
406    pub(crate) fn new(
407        name: &'static str,
408        origin: Origin,
409        docs: &'static str,
410        params: Vec<Param<Owner>>,
411        result: TypeRef<Owner>,
412        types: Types,
413        factory: Factory,
414    ) -> Self {
415        #[cfg(not(unix))]
416        let _ = factory;
417        Self {
418            name,
419            origin,
420            generic: Vec::new(),
421            docs,
422            params,
423            result,
424            types,
425            #[cfg(unix)]
426            factory,
427            place: Place::default(),
428        }
429    }
430}
431
432impl Function {
433    /// The served declaration `identity` with the description `spec`,
434    /// whose values cross at the description's types.
435    #[cfg(unix)]
436    pub(crate) fn declare(
437        &self,
438        identity: description::Identity,
439        spec: TypeSpec,
440    ) -> crate::server::Declaration {
441        crate::server::Declaration::new(identity, spec, (self.factory)())
442    }
443}
444
445/// One declaration of a contract module, in the order its native source
446/// gives.
447struct Entry<'a> {
448    file: String,
449    line: u32,
450    name: &'a str,
451    docs: &'a str,
452    /// The declaration, whose types name the module that owns each.
453    declaration: Declaration<Owner>,
454}
455
456/// The library module of the Rust module `module` of the crate
457/// `crate_name`, or `None` when another crate defines it.
458fn library_module(crate_name: &str, module: &str) -> Option<String> {
459    let mut segments = module.split("::");
460    if segments.next() != Some(crate_name) {
461        return None;
462    }
463    Some(segments.collect::<Vec<_>>().join("/"))
464}
465
466/// The defining `file`, as `file!()` spelled it, relative to the library
467/// `root` with `/` separators. Cargo spells a path dependency's files
468/// absolutely, and a workspace member's relative to the workspace root, so a
469/// relative one is looked for from the root and each directory above it.
470fn library_file(root: Option<&Path>, file: &str) -> String {
471    let spelled = || file.replace('\\', "/");
472    let Some(root) = root.and_then(|root| std::fs::canonicalize(root).ok()) else {
473        return spelled();
474    };
475    let path = Path::new(file);
476    let candidates: Vec<PathBuf> = if path.is_absolute() {
477        vec![path.to_owned()]
478    } else {
479        root.ancestors()
480            .map(|directory| directory.join(path))
481            .collect()
482    };
483    for candidate in candidates {
484        if let Ok(found) = std::fs::canonicalize(candidate)
485            && let Ok(relative) = found.strip_prefix(&root)
486            && let Some(relative) = relative.to_str()
487        {
488            return relative.replace('\\', "/");
489        }
490    }
491    spelled()
492}
493
494/// The module path `module` spells, refusing one with a segment that is not
495/// a Flow lowercase name, and one that spells a library's layout
496/// (`modules.md`, *Libraries*).
497fn check_module(module: &str, at: &Location) -> Result<Segments, ContractError> {
498    let not_a_path = |segment: &str| ContractError::NotAModulePath {
499        at: at.clone(),
500        module: module.to_owned(),
501        segment: segment.to_owned(),
502    };
503    let path: Segments = module.parse().map_err(|_| not_a_path(""))?;
504    if let Some(segment) = path.names().find(|segment| !lowercase_name(segment)) {
505        return Err(not_a_path(segment));
506    }
507    if LibraryLayout::spelled(&path).is_some() {
508        return Err(ContractError::Spelled {
509            at: at.clone(),
510            module: module.to_owned(),
511        });
512    }
513    Ok(path)
514}
515
516/// The relative import that names the library module `to` from the contract
517/// module `from`, in module-path space: the root module sits at the top, and
518/// the root itself is reached from its parent directory as `root`.
519fn relative_import(from: &str, to: &str, root: &str) -> String {
520    let mut directory: Vec<&str> = if from.is_empty() {
521        Vec::new()
522    } else {
523        from.split('/').collect()
524    };
525    directory.pop();
526    if to.is_empty() {
527        return format!("{}{root}", "../".repeat(directory.len() + 1));
528    }
529    let target: Vec<&str> = to.split('/').collect();
530    let shared = directory
531        .iter()
532        .zip(&target[..target.len() - 1])
533        .take_while(|(left, right)| left == right)
534        .count();
535    let rest = target[shared..].join("/");
536    match directory.len() - shared {
537        0 => format!("./{rest}"),
538        ups => format!("{}{rest}", "../".repeat(ups)),
539    }
540}
541
542/// Where the types a Rust module defines are declared.
543#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
544enum Target {
545    /// In this library's contract module of that module path.
546    Local(String),
547    /// In the contract module `module` of the library at `root`, which
548    /// this library depends on by a path.
549    Path {
550        /// The library's root, canonical.
551        root: PathBuf,
552        /// The module path inside it.
553        module: String,
554    },
555    /// In the contract module at this remote path, of a library this one
556    /// depends on by a git URL at a tag.
557    Remote(String),
558}
559
560/// How a library's `Cargo.toml` depends on a crate.
561#[derive(Clone, Debug, PartialEq, Eq)]
562enum Dependency {
563    /// By a path, to this directory.
564    Path(PathBuf),
565    /// By a git URL, at a tag or not.
566    Git {
567        /// The repository URL.
568        url: String,
569        /// The tag it names, if any.
570        tag: Option<String>,
571    },
572    /// By a registry version.
573    Registry,
574}
575
576/// The crates the library at `root` depends on, by the crate name
577/// `module_path!()` spells, as its `Cargo.toml` says: its
578/// `[dependencies]` and each `[target.*.dependencies]`, a dependency
579/// inherited from the workspace read from the workspace's table. Each
580/// manifest it tries is added to `read`.
581fn cargo_dependencies(
582    root: &Path,
583    read: &std::cell::RefCell<BTreeSet<PathBuf>>,
584) -> BTreeMap<String, Dependency> {
585    let read = |path: &Path| {
586        read.borrow_mut().insert(path.to_owned());
587        std::fs::read_to_string(path)
588            .ok()?
589            .parse::<toml::Table>()
590            .ok()
591    };
592    let Some(manifest) = read(&root.join("Cargo.toml")) else {
593        return BTreeMap::new();
594    };
595    let workspace = root.ancestors().find_map(|directory| {
596        let table = read(&directory.join("Cargo.toml"))?;
597        let dependencies = table.get("workspace")?.get("dependencies");
598        let dependencies = dependencies.and_then(toml::Value::as_table).cloned();
599        Some((directory.to_owned(), dependencies.unwrap_or_default()))
600    });
601    let targets = manifest
602        .get("target")
603        .and_then(toml::Value::as_table)
604        .into_iter()
605        .flat_map(|targets| {
606            targets
607                .values()
608                .filter_map(|target| target.get("dependencies"))
609        });
610    let mut found = BTreeMap::new();
611    for table in manifest
612        .get("dependencies")
613        .into_iter()
614        .chain(targets)
615        .filter_map(toml::Value::as_table)
616    {
617        for (key, written) in table {
618            let inherited = written.get("workspace").and_then(toml::Value::as_bool) == Some(true);
619            let (spec, base) = match (&workspace, inherited) {
620                (_, false) => (written, root),
621                (Some((directory, dependencies)), true) => match dependencies.get(key) {
622                    Some(spec) => (spec, directory.as_path()),
623                    None => continue,
624                },
625                (None, true) => continue,
626            };
627            let text = |name: &str| {
628                written
629                    .get(name)
630                    .or_else(|| spec.get(name))
631                    .and_then(toml::Value::as_str)
632            };
633            let package = text("package").unwrap_or(key);
634            let (name, dependency) = if let Some(path) = text("path") {
635                let at = base.join(path);
636                let at = std::fs::canonicalize(&at).unwrap_or(at);
637                let named = read(&at.join("Cargo.toml")).and_then(|manifest| {
638                    let name = |table: &str| {
639                        manifest
640                            .get(table)?
641                            .get("name")?
642                            .as_str()
643                            .map(str::to_owned)
644                    };
645                    name("lib").or_else(|| name("package"))
646                });
647                (
648                    named.unwrap_or_else(|| package.to_owned()),
649                    Dependency::Path(at),
650                )
651            } else if let Some(url) = text("git") {
652                let tag = text("tag").map(str::to_owned);
653                (
654                    package.to_owned(),
655                    Dependency::Git {
656                        url: url.to_owned(),
657                        tag,
658                    },
659                )
660            } else {
661                (package.to_owned(), Dependency::Registry)
662            };
663            found.insert(name.replace('-', "_"), dependency);
664        }
665    }
666    found
667}
668
669/// Whether `tag` is a Flow version tag: `v1`, `v1.2` or `v1.2.3`.
670fn flow_tag(tag: &str) -> bool {
671    tag.strip_prefix('v').is_some_and(|numbers| {
672        let parts: Vec<&str> = numbers.split('.').collect();
673        parts.len() <= 3
674            && parts.iter().all(|part| {
675                !part.is_empty()
676                    && part.bytes().all(|byte| byte.is_ascii_digit())
677                    && (*part == "0" || !part.starts_with('0'))
678            })
679    })
680}
681
682/// The repository a git URL names, at `tag`, as a Flow remote path spells
683/// it: `https://github.com/acme/plans.git` at `v1.2` is
684/// `github.com/acme/plans@v1.2`, and so is `git@github.com:acme/plans`.
685fn remote_repository(url: &str, tag: &str) -> Option<String> {
686    let url = url.strip_prefix("git+").unwrap_or(url);
687    let location = match url.split_once("://") {
688        Some((_, location)) => location.to_owned(),
689        None if url.contains(':') => url.replacen(':', "/", 1),
690        None => return None,
691    };
692    let location = location.split(['#', '?']).next().unwrap_or_default();
693    let location = location
694        .rsplit_once('@')
695        .map_or(location, |(_, after)| after);
696    let (host, path) = location.split_once('/')?;
697    let host = host.split(':').next().unwrap_or(host);
698    let path = path.trim_matches('/');
699    let path = path.strip_suffix(".git").unwrap_or(path);
700    (!host.is_empty() && !path.is_empty()).then(|| format!("{host}/{path}@{tag}"))
701}
702
703/// Where a crate fetched from git keeps its library inside the repository:
704/// the directories from the checkout's top to the nearest one above the
705/// defining `file` that holds a `flow.toml`. Empty when `file` is not
706/// spelled absolutely or is in no checkout.
707fn repository_place(file: &str) -> Vec<String> {
708    let file = Path::new(file);
709    if !file.is_absolute() {
710        return Vec::new();
711    }
712    let Some(library) = file
713        .ancestors()
714        .skip(1)
715        .find(|directory| directory.join("flow.toml").is_file())
716    else {
717        return Vec::new();
718    };
719    library
720        .ancestors()
721        .find(|directory| directory.join(".git").exists() || directory.join(".cargo-ok").exists())
722        .and_then(|checkout| library.strip_prefix(checkout).ok())
723        .map(|inside| {
724            inside
725                .components()
726                .map(|part| part.as_os_str().to_string_lossy().into_owned())
727                .collect()
728        })
729        .unwrap_or_default()
730}
731
732/// Where the contract imports `definition`, a type of another crate, from:
733/// abi.md's *Imports, never copies*, read from how the library depends on
734/// that crate.
735fn foreign_target(
736    definition: &Declared,
737    at: &Location,
738    dependencies: &BTreeMap<String, Dependency>,
739) -> Result<Target, ContractError> {
740    let (krate, inside) = definition
741        .module
742        .split_once("::")
743        .unwrap_or((definition.module, ""));
744    let module = inside
745        .split("::")
746        .filter(|segment| !segment.is_empty())
747        .collect::<Vec<_>>();
748    let unaddressed = |how: String| ContractError::UnaddressedType {
749        at: at.clone(),
750        name: definition.name.to_owned(),
751        dependency: krate.to_owned(),
752        how,
753    };
754    match dependencies.get(krate) {
755        None => Err(ContractError::ForeignType {
756            at: at.clone(),
757            name: definition.name.to_owned(),
758            module: definition.module.to_owned(),
759        }),
760        Some(Dependency::Path(root)) => Ok(Target::Path {
761            root: root.clone(),
762            module: module.join("/"),
763        }),
764        Some(Dependency::Registry) => Err(unaddressed(format!("the registry dependency {krate}"))),
765        Some(Dependency::Git { url, tag }) => {
766            let Some(tag) = tag.as_deref().filter(|tag| flow_tag(tag)) else {
767                return Err(unaddressed(format!(
768                    "the git dependency {krate}, which names no tag such as v1.2"
769                )));
770            };
771            let repository = remote_repository(url, tag).ok_or_else(|| {
772                unaddressed(format!(
773                    "the git dependency {krate}, whose URL {url} names no repository"
774                ))
775            })?;
776            let mut path = vec![repository];
777            path.extend(repository_place(definition.file));
778            path.extend(module.into_iter().map(str::to_owned));
779            Ok(Target::Remote(path.join("/")))
780        }
781    }
782}
783
784/// The path from the directory `from` to `to`, both canonical, as `/`
785/// separated segments that climb with `..`.
786fn relative_place(from: &Path, to: &Path) -> String {
787    let from: Vec<_> = from.components().collect();
788    let to: Vec<_> = to.components().collect();
789    let shared = from
790        .iter()
791        .zip(&to)
792        .take_while(|(left, right)| left == right)
793        .count();
794    std::iter::repeat_n("..".to_owned(), from.len() - shared)
795        .chain(
796            to[shared..]
797                .iter()
798                .map(|part| part.as_os_str().to_string_lossy().into_owned()),
799        )
800        .collect::<Vec<_>>()
801        .join("/")
802}
803
804/// The contract modules of a crate's registered Rust functions: each
805/// library module that defines a Tool or a type a Tool reaches, mapped to
806/// its declarations.
807///
808/// `crate_name` is the crate's name as `module_path!()` spells it, and
809/// `root` the library root that a type's `file!()` is made relative to.
810///
811/// # Errors
812///
813/// Refuses two Tools of one name in one module, distinct Rust types that
814/// share a Flow name in one module, a type another crate defines, and a
815/// module path that is no Flow module path.
816pub fn extract(
817    crate_name: &str,
818    root: Option<&Path>,
819    functions: &[Function],
820) -> Result<BTreeMap<Segments, ContractModule>, ContractError> {
821    extract_reading(crate_name, root, functions, &std::cell::RefCell::default())
822}
823
824/// [`extract`], adding each file of the library it tries to `read`.
825fn extract_reading(
826    crate_name: &str,
827    root: Option<&Path>,
828    functions: &[Function],
829    read: &std::cell::RefCell<BTreeSet<PathBuf>>,
830) -> Result<BTreeMap<Segments, ContractModule>, ContractError> {
831    // A refusal names the file as a path the reader can open: under the
832    // root, when there is one.
833    let located = |file: &str, line: u32| match root {
834        Some(root) if Path::new(file).is_relative() => {
835            Location::new(root.join(file).display().to_string(), line)
836        }
837        _ => Location::new(file.to_owned(), line),
838    };
839    let mut grouped = tool_entries(functions, &located)?;
840    let mut declared: BTreeMap<&str, &Declared> = BTreeMap::new();
841    for (key, definition) in functions
842        .iter()
843        .flat_map(|function| &function.types.definitions)
844    {
845        declared.entry(key.as_str()).or_insert(definition);
846    }
847    let dependencies = root
848        .map(|root| cargo_dependencies(root, read))
849        .unwrap_or_default();
850    let mut modules: BTreeMap<&str, Target> = BTreeMap::new();
851    let mut names: BTreeMap<(String, &str), &str> = BTreeMap::new();
852    for (key, definition) in declared {
853        let file = library_file(root, definition.file);
854        let located = located(&file, definition.line);
855        let Some(module) = library_module(crate_name, definition.module) else {
856            modules.insert(
857                definition.module,
858                foreign_target(definition, &located, &dependencies)?,
859            );
860            continue;
861        };
862        let path = check_module(&module, &located)?;
863        if let Some(previous) = names.insert((module.clone(), definition.name), key) {
864            return Err(ContractError::SharedFlowName {
865                at: located,
866                name: definition.name.to_owned(),
867                first: previous.to_owned(),
868                second: key.to_owned(),
869            });
870        }
871        modules.insert(definition.module, Target::Local(module));
872        grouped.entry(path).or_default().push(Entry {
873            file,
874            line: definition.line,
875            name: definition.name,
876            docs: definition.docs,
877            declaration: definition.declaration.clone(),
878        });
879    }
880    let canonical = root.and_then(|root| std::fs::canonicalize(root).ok());
881    let root_name = canonical
882        .as_ref()
883        .and_then(|root| root.file_name()?.to_str().map(str::to_owned))
884        .unwrap_or_else(|| crate_name.to_owned());
885    let parent = canonical.as_deref().and_then(Path::parent);
886    let mut contracts = BTreeMap::new();
887    for (module, mut entries) in grouped {
888        entries.sort_by(|left, right| {
889            (&left.file, left.line, left.name).cmp(&(&right.file, right.line, right.name))
890        });
891        for std in entries.iter().flat_map(|entry| owners(&entry.declaration)) {
892            let Owner::Std(std) = std else { continue };
893            if let Some(entry) = entries.iter().find(|entry| entry.name == std) {
894                return Err(ContractError::StdImportCollision {
895                    at: located(&entry.file, entry.line),
896                    name: std.to_owned(),
897                });
898            }
899        }
900        let generated = contract_module(
901            crate_name,
902            &root_name,
903            parent,
904            module.as_str(),
905            &entries,
906            &modules,
907        );
908        contracts.insert(module, generated);
909    }
910    Ok(contracts)
911}
912
913/// Each library module's Tools, by module path, as declarations in no
914/// order yet.
915fn tool_entries<'a>(
916    functions: &'a [Function],
917    located: &impl Fn(&str, u32) -> Location,
918) -> Result<BTreeMap<Segments, Vec<Entry<'a>>>, ContractError> {
919    let mut grouped: BTreeMap<Segments, Vec<Entry<'a>>> = BTreeMap::new();
920    let mut tools = BTreeSet::new();
921    for function in functions {
922        let place = &function.place;
923        let located = located(&place.file, place.line);
924        let module = check_module(&place.module, &located)?;
925        if !tools.insert((place.module.as_str(), function.name)) {
926            return Err(ContractError::DuplicateTool {
927                at: located,
928                name: function.name.to_owned(),
929            });
930        }
931        grouped.entry(module).or_default().push(Entry {
932            file: place.file.clone(),
933            line: place.line,
934            name: function.name,
935            docs: function.docs,
936            declaration: Declaration::Flow(FlowDeclaration {
937                name: function.name.to_owned(),
938                generics: function.generic.clone(),
939                params: function.params.clone(),
940                result: function.result.clone(),
941            }),
942        });
943    }
944    Ok(grouped)
945}
946
947/// The contract of `functions`, each placed where `#[tool]` found it, in
948/// the library whose root is `root`: what [`contract!`](crate::contract)
949/// expands to.
950///
951/// # Errors
952///
953/// Refuses Tools of two crates, and what [`extract`] refuses.
954pub fn contract_of(root: &str, functions: Vec<Function>) -> Result<Contract, ContractError> {
955    let root = Path::new(root);
956    let mut crate_name: Option<&'static str> = None;
957    let mut placed = Vec::with_capacity(functions.len());
958    for function in functions {
959        let Origin { module, file, line } = function.origin;
960        let (owner, path) = module.split_once("::").unwrap_or((module, ""));
961        match crate_name {
962            Some(first) if first != owner => {
963                return Err(ContractError::SeveralCrates {
964                    first: first.to_owned(),
965                    second: owner.to_owned(),
966                });
967            }
968            _ => crate_name = Some(owner),
969        }
970        let path = path.split("::").collect::<Vec<_>>().join("/");
971        let file = library_file(Some(root), file);
972        placed.push(function.at(&path, &file, line));
973    }
974    let modules = extract(crate_name.unwrap_or_default(), Some(root), &placed)?
975        .into_iter()
976        .map(|(path, module)| (path, contract::print(&module)))
977        .collect();
978    Ok(Contract::new(root.to_owned(), modules))
979}
980
981/// The import of `target`, another library's module, from the contract
982/// module `module`: its path, its natural name, and the name it is given
983/// when that one is taken, the library's name joined to it, or the natural
984/// name itself when that is no Flow name. A library this
985/// one depends on by a path is reached from `parent`, the directory holding
986/// this library's root, as modules.md's *Versions and relative imports*
987/// reads a `../` that climbs above a library's root.
988fn foreign_import(
989    target: &Target,
990    module: &str,
991    parent: Option<&Path>,
992) -> Option<(String, String, String)> {
993    let (path, natural, library) = match target {
994        Target::Local(_) => return None,
995        Target::Remote(path) => {
996            let (repository, inside) = path.split_once('@').unwrap_or((path, ""));
997            let library = repository.rsplit('/').next().unwrap_or(repository);
998            let natural = inside
999                .split_once('/')
1000                .map_or(library, |(_, rest)| rest.rsplit('/').next().unwrap_or(rest));
1001            (path.clone(), natural.to_owned(), library.to_owned())
1002        }
1003        Target::Path {
1004            root,
1005            module: place,
1006        } => {
1007            let library = root
1008                .file_name()
1009                .map_or_else(String::new, |name| name.to_string_lossy().into_owned());
1010            let mut path = "../".repeat(module.split('/').count());
1011            path.push_str(&parent.map_or_else(
1012                || root.to_string_lossy().into_owned(),
1013                |parent| relative_place(parent, root),
1014            ));
1015            let natural = if place.is_empty() {
1016                library.clone()
1017            } else {
1018                path.push('/');
1019                path.push_str(place);
1020                place.rsplit('/').next().unwrap_or(place).to_owned()
1021            };
1022            (path, natural, library)
1023        }
1024    };
1025    let fallback = if lowercase_name(&natural) {
1026        format!("{library}_{natural}")
1027    } else {
1028        natural.clone()
1029    };
1030    Some((path, natural, fallback))
1031}
1032
1033/// `text` as a Flow lowercase name: lowercased, every character outside
1034/// `[a-z0-9_]` written `_`, and `library_` before one that does not
1035/// start with a letter.
1036fn lower_name(text: &str) -> String {
1037    let name: String = text
1038        .to_lowercase()
1039        .chars()
1040        .map(|char| {
1041            if char.is_ascii_lowercase() || char.is_ascii_digit() {
1042                char
1043            } else {
1044                '_'
1045            }
1046        })
1047        .collect();
1048    if name.starts_with(|char: char| char.is_ascii_lowercase()) {
1049        name
1050    } else {
1051        format!("library_{name}")
1052    }
1053}
1054
1055/// Every module that owns a type `declaration` names, once for each time
1056/// it names one.
1057fn owners(declaration: &Declaration<Owner>) -> Vec<Owner> {
1058    let mut found = Vec::new();
1059    declaration.qualify(&mut |owner: &Owner| -> Option<()> {
1060        found.push(*owner);
1061        None
1062    });
1063    found
1064}
1065
1066/// The import binding a contract module written for the target `here`
1067/// names a type of `owner` through, or `None` for a type of its own:
1068/// a std module's under its own name, and a Rust module's under the binding
1069/// of the module that declares its types.
1070fn qualified(
1071    owner: &Owner,
1072    here: &Target,
1073    modules: &BTreeMap<&str, Target>,
1074    bindings: &BTreeMap<Target, String>,
1075) -> Option<String> {
1076    match owner {
1077        Owner::Std(std) => Some((*std).to_owned()),
1078        Owner::Rust(rust) => modules
1079            .get(rust)
1080            .filter(|target| *target != here)
1081            .and_then(|target| bindings.get(target))
1082            .cloned(),
1083    }
1084}
1085
1086/// Imports `path` under `natural` when that is a Flow lowercase name no
1087/// other binding has taken, and otherwise under `fallback` made one, and
1088/// returns the name it is bound to.
1089fn bind(
1090    imports: &mut Vec<Import>,
1091    taken: &mut BTreeSet<String>,
1092    path: String,
1093    natural: &str,
1094    fallback: &str,
1095) -> String {
1096    let binding = if lowercase_name(natural) && !taken.contains(natural) {
1097        None
1098    } else {
1099        let base = lower_name(fallback);
1100        let mut binding = base.clone();
1101        let mut number = 2;
1102        while !lowercase_name(&binding) || taken.contains(&binding) {
1103            binding = format!("{base}_{number}");
1104            number += 1;
1105        }
1106        Some(binding)
1107    };
1108    let bound = binding.clone().unwrap_or_else(|| natural.to_owned());
1109    imports.push(Import { path, binding });
1110    taken.insert(bound.clone());
1111    bound
1112}
1113
1114/// The Flow source of the contract module `module`, holding `entries`.
1115/// `parent` is the directory holding the library's root, from which a
1116/// library this one depends on by a path is reached.
1117fn contract_module(
1118    crate_name: &str,
1119    root_name: &str,
1120    parent: Option<&Path>,
1121    module: &str,
1122    entries: &[Entry<'_>],
1123    modules: &BTreeMap<&str, Target>,
1124) -> ContractModule {
1125    let mut origin = crate_name.to_owned();
1126    for segment in module.split('/').filter(|segment| !segment.is_empty()) {
1127        origin.push_str("::");
1128        origin.push_str(segment);
1129    }
1130    // An import may bind no name a declaration binds, nor another import's;
1131    // a parameter or a field never collides with one (`modules.md`, *Name
1132    // collisions*).
1133    let mut taken: BTreeSet<String> = entries.iter().map(|entry| entry.name.to_owned()).collect();
1134    let owned: Vec<Owner> = entries
1135        .iter()
1136        .flat_map(|entry| owners(&entry.declaration))
1137        .collect();
1138    let mut imports = Vec::new();
1139    let named_std: BTreeSet<&str> = owned
1140        .iter()
1141        .filter_map(|owner| match owner {
1142            Owner::Std(std) => Some(*std),
1143            Owner::Rust(_) => None,
1144        })
1145        .collect();
1146    for std in &named_std {
1147        imports.push(Import {
1148            path: format!("std@v1/{std}"),
1149            binding: None,
1150        });
1151        taken.insert((*std).to_owned());
1152    }
1153    let here = Target::Local(module.to_owned());
1154    let referenced: BTreeSet<&Target> = owned
1155        .iter()
1156        .filter_map(|owner| match owner {
1157            Owner::Rust(rust) => modules.get(rust),
1158            Owner::Std(_) => None,
1159        })
1160        .filter(|target| **target != here)
1161        .collect();
1162    let mut bindings = BTreeMap::new();
1163    for target in &referenced {
1164        let Target::Local(target) = target else {
1165            continue;
1166        };
1167        let target = target.as_str();
1168        let natural = if target.is_empty() {
1169            root_name
1170        } else {
1171            target.rsplit('/').next().unwrap_or(target)
1172        };
1173        let path = relative_import(module, target, root_name);
1174        let fallback = if target.is_empty() {
1175            crate_name.to_owned()
1176        } else {
1177            format!("{natural}_types")
1178        };
1179        let binding = bind(&mut imports, &mut taken, path, natural, &fallback);
1180        bindings.insert(Target::Local(target.to_owned()), binding);
1181    }
1182    // Another library's module is imported under its natural name unless
1183    // that is taken, and then under the library's name joined to it.
1184    let mut others: Vec<_> = referenced
1185        .iter()
1186        .filter_map(|target| Some((foreign_import(target, module, parent)?, *target)))
1187        .collect();
1188    others.sort();
1189    for ((path, natural, fallback), target) in others {
1190        let binding = bind(&mut imports, &mut taken, path, &natural, &fallback);
1191        bindings.insert(target.clone(), binding);
1192    }
1193    let mut qualify = |owner: &Owner| qualified(owner, &here, modules, &bindings);
1194    let items = entries
1195        .iter()
1196        .map(|entry| Item {
1197            docs: entry.docs.to_owned(),
1198            origin: Some(contract::Origin {
1199                path: entry.file.clone(),
1200                item: entry.name.to_owned(),
1201            }),
1202            declaration: entry.declaration.qualify(&mut qualify),
1203        })
1204        .collect();
1205    ContractModule {
1206        generated_from: format!("rust module {origin}"),
1207        imports,
1208        items,
1209    }
1210}
1211
1212/// Runs a generated launcher for the crate `crate_name` with one optional
1213/// explicit resource initializer: the command its arguments give, of which
1214/// it runs `serve` and `extract` ([`crate::cli`]).
1215pub(crate) fn launcher_with_lifespan(
1216    crate_name: &str,
1217    functions: &[Function],
1218    start: Option<Start>,
1219) -> Result<(), String> {
1220    let arguments = std::env::args_os().skip(1).collect::<Vec<_>>();
1221    match Command::parse(&arguments).map_err(|error| error.to_string())? {
1222        Command::Extract {
1223            library,
1224            out,
1225            depfile,
1226        } => {
1227            let read = std::cell::RefCell::default();
1228            let contracts = extract_reading(crate_name, Some(&library), functions, &read)
1229                .map_err(|error| error.to_string())?;
1230            let contract = contract::Contract {
1231                modules: contracts
1232                    .into_iter()
1233                    .map(|(path, module)| contract::Module {
1234                        path: path.names().map(str::to_owned).collect(),
1235                        module,
1236                    })
1237                    .collect(),
1238            };
1239            std::fs::write(&out, contract.bytes())
1240                .map_err(|error| format!("{}: {error}", out.display()))?;
1241            match depfile {
1242                Some(depfile) => write_depfile(&depfile, read.into_inner()),
1243                None => Ok(()),
1244            }
1245        }
1246        Command::Serve { contract } => {
1247            let contract = std::fs::read(&contract)
1248                .map_err(|error| format!("{}: {error}", contract.display()))?;
1249            serve(functions, &contract, start)
1250        }
1251        command @ (Command::Export { .. } | Command::New { .. }) => {
1252            Err(UsageError::NotLauncher(command).to_string())
1253        }
1254    }
1255}
1256
1257/// Writes `depfile`: this launcher's own executable, whose code the
1258/// contract comes from, and each file of the library it tried to `read`,
1259/// one absolute path to a line (`abi.md`, *Extracting a contract*).
1260fn write_depfile(depfile: &Path, mut read: BTreeSet<PathBuf>) -> Result<(), String> {
1261    let executable = std::env::current_exe()
1262        .and_then(std::fs::canonicalize)
1263        .map_err(|error| format!("the launcher's own path: {error}"))?;
1264    read.insert(executable);
1265    let mut lines = String::new();
1266    for path in read {
1267        let path =
1268            std::path::absolute(&path).map_err(|error| format!("{}: {error}", path.display()))?;
1269        match path.to_str() {
1270            Some(line) if !line.contains('\n') => {
1271                lines.push_str(line);
1272                lines.push('\n');
1273            }
1274            _ => {
1275                return Err(format!(
1276                    "{}: the path is not one line of UTF-8, which a depfile needs",
1277                    path.display()
1278                ));
1279            }
1280        }
1281    }
1282    std::fs::write(depfile, lines).map_err(|error| format!("{}: {error}", depfile.display()))
1283}
1284
1285/// The library module whose contract module the identity `file` names, among
1286/// the `modules` that declare Tools: `<library>/contract/lib` is the root
1287/// module and `<library>/contract/P` the module `P`, and a file that spells
1288/// a module path itself names it. A module that is no path names no file.
1289#[cfg(unix)]
1290fn module_of<'a>(file: &str, modules: &BTreeSet<&'a str>) -> Option<&'a str> {
1291    let file = LibraryLayout::stem(file).unwrap_or(file);
1292    let file = file.trim_start_matches("./");
1293    modules
1294        .iter()
1295        .filter(|module| {
1296            let Ok(path) = module.parse() else {
1297                return false;
1298            };
1299            let contract = LibraryLayout::module_file(&path, Placement::Contract);
1300            file == **module || file == contract.as_str() || file.ends_with(&format!("/{contract}"))
1301        })
1302        .max_by_key(|module| module.len())
1303        .copied()
1304}
1305
1306/// Binds generated adapters to the Tools the \x60--contract\x60 file
1307/// \x60contract\x60 lists, in its order: the order \x60describe\x60 answers with,
1308/// and so the number a \x60call\x60 names its declaration by. Each Tool is
1309/// served by the function of its name in the module its identity names,
1310/// or, when that names no module that declares Tools, by the one function
1311/// of its name.
1312#[cfg(unix)]
1313pub(crate) fn serve(
1314    functions: &[Function],
1315    contract: &[u8],
1316    start: Option<Start>,
1317) -> Result<(), String> {
1318    let listing = flow_abi::read_listing(contract).map_err(|error| error.to_string())?;
1319    let modules: BTreeSet<&str> = functions
1320        .iter()
1321        .map(|function| function.place.module.as_str())
1322        .collect();
1323    let mut declarations = Vec::new();
1324    let mut served = BTreeSet::new();
1325    for (identity, spec) in listing.into_iter().flat_map(|program| program.tools) {
1326        let name = identity.name.as_str();
1327        let candidates: Vec<&Function> = functions.iter().filter(|f| f.name == name).collect();
1328        let function = match module_of(&identity.module, &modules) {
1329            Some(module) => candidates
1330                .iter()
1331                .find(|function| function.place.module == module)
1332                .copied(),
1333            None if candidates.len() > 1 => {
1334                return Err(format!(
1335                    "Tool {name} of {} names no module, and Rust functions of that name are in several",
1336                    identity.module
1337                ));
1338            }
1339            None => candidates.first().copied(),
1340        }
1341        .ok_or_else(|| format!("no Rust function implements {name}"))?;
1342        if !served.insert((function.place.module.clone(), name.to_owned())) {
1343            return Err(format!("ambiguous Tool {name} in contract"));
1344        }
1345        declarations.push(function.declare(identity, spec));
1346    }
1347    if served.is_empty() {
1348        return Err("the contract file lists no Tool a Rust function implements".into());
1349    }
1350    run_protocol(&Server::new(declarations), start)
1351}
1352#[cfg(unix)]
1353fn run_protocol(server: &Server, start: Option<Start>) -> Result<(), String> {
1354    use crate::server::{Sink, logging_to};
1355    // Keep the original protocol stream private before redirecting ordinary
1356    // Rust logging: a copy above the standard streams, close-on-exec from the
1357    // call that makes it, so no child this process starts inherits it.
1358    let protocol =
1359        rustix::io::fcntl_dupfd_cloexec(std::io::stdout(), 3).map_err(|error| error.to_string())?;
1360    rustix::stdio::dup2_stdout(std::io::stderr()).map_err(|error| error.to_string())?;
1361    let sink = Sink::new(std::fs::File::from(protocol));
1362    logging_to(&sink, || {
1363        with_resource(start, || {
1364            server
1365                .run_process(std::io::stdin().lock(), &sink)
1366                .map_err(|error| error.to_string())
1367        })
1368    })
1369}
1370
1371/// Refuses: the Tool process protocol is served only on Unix, where the
1372/// protocol's output can be kept from everything else the process writes.
1373#[cfg(not(unix))]
1374pub(crate) fn serve(
1375    functions: &[Function],
1376    contract: &[u8],
1377    start: Option<Start>,
1378) -> Result<(), String> {
1379    let _ = (functions, contract, start);
1380    Err("Rust function-first protocol serving is currently supported only on Unix".into())
1381}
1382/// `error` and every error in its `source()` chain, each after a colon.
1383#[cfg(unix)]
1384fn chain(error: &(dyn std::error::Error + 'static)) -> String {
1385    let mut written = error.to_string();
1386    let mut cause = error.source();
1387    while let Some(error) = cause {
1388        written.push_str(": ");
1389        written.push_str(&error.to_string());
1390        cause = error.source();
1391    }
1392    written
1393}
1394#[cfg(unix)]
1395fn with_resource(
1396    start: Option<Start>,
1397    serve: impl FnOnce() -> Result<(), String>,
1398) -> Result<(), String> {
1399    let lifespan = start
1400        .map(|start| start())
1401        .transpose()
1402        .map_err(|error| format!("Rust resource initialization failed: {}", chain(&*error)))?;
1403    if let Some(lifespan) = &lifespan {
1404        let mut current = RESOURCE
1405            .lock()
1406            .unwrap_or_else(std::sync::PoisonError::into_inner);
1407        if current.is_some() {
1408            return Err("a Rust process resource is already initialized".into());
1409        }
1410        *current = Some(Arc::clone(&lifespan.value));
1411    }
1412    let result = serve();
1413    if let Some(lifespan) = lifespan {
1414        RESOURCE
1415            .lock()
1416            .unwrap_or_else(std::sync::PoisonError::into_inner)
1417            .take();
1418        let closed = block_on((lifespan.close)())
1419            .map_err(|error| format!("Rust resource cleanup failed: {}", chain(&*error)));
1420        match (result, closed) {
1421            (Err(run), Err(close)) => Err(format!("{run}; {close}")),
1422            (Err(error), _) | (_, Err(error)) => Err(error),
1423            _ => Ok(()),
1424        }
1425    } else {
1426        result
1427    }
1428}
1429/// Drives an asynchronous tool with a Tokio runtime on its invocation thread:
1430/// a multi-threaded one where the target has threads, a current-thread one
1431/// on WebAssembly.
1432pub fn block_on<F: Future>(future: F) -> F::Output {
1433    static RUNTIME: std::sync::LazyLock<tokio::runtime::Runtime> = std::sync::LazyLock::new(|| {
1434        #[cfg(not(target_family = "wasm"))]
1435        let mut builder = tokio::runtime::Builder::new_multi_thread();
1436        #[cfg(target_family = "wasm")]
1437        let mut builder = tokio::runtime::Builder::new_current_thread();
1438        builder.enable_all().build().expect("tool async runtime")
1439    });
1440    RUNTIME.block_on(future)
1441}
1442
1443#[cfg(test)]
1444#[cfg_attr(coverage, coverage(off))]
1445mod tests {
1446    use super::*;
1447    use std::sync::atomic::{AtomicUsize, Ordering};
1448
1449    /// What [`super::extract`] gives, each module printed.
1450    fn extract(
1451        crate_name: &str,
1452        root: Option<&Path>,
1453        functions: &[Function],
1454    ) -> Result<BTreeMap<Segments, String>, ContractError> {
1455        super::extract(crate_name, root, functions).map(|modules| {
1456            modules
1457                .into_iter()
1458                .map(|(path, module)| (path, contract::print(&module)))
1459                .collect()
1460        })
1461    }
1462
1463    #[test]
1464    fn a_git_types_library_place_uses_the_nearest_library_and_the_checkout_root() {
1465        let checkout = tempfile::TempDir::new().unwrap();
1466        let root = checkout.path().canonicalize().unwrap();
1467        let library = root.join("libraries/ledger");
1468        std::fs::create_dir_all(library.join("src/models")).unwrap();
1469        let file = library.join("src/models/types.rs");
1470        std::fs::write(&file, "").unwrap();
1471        let file = file.to_str().unwrap();
1472        assert_eq!(
1473            repository_place("src/models/types.rs"),
1474            Vec::<String>::new()
1475        );
1476        assert_eq!(repository_place(file), Vec::<String>::new());
1477        std::fs::write(library.join("flow.toml"), "[process]\ncommand = 'serve'\n").unwrap();
1478        assert!(repository_place(file).is_empty(), "no checkout boundary");
1479        for marker in [".git", ".cargo-ok"] {
1480            std::fs::write(root.join(marker), "checkout marker").unwrap();
1481            assert_eq!(repository_place(file), ["libraries", "ledger"], "{marker}");
1482            std::fs::write(root.join("flow.toml"), "[process]\ncommand = 'outer'\n").unwrap();
1483            assert_eq!(
1484                repository_place(file),
1485                ["libraries", "ledger"],
1486                "the nearest library wins"
1487            );
1488            std::fs::remove_file(library.join("flow.toml")).unwrap();
1489            assert!(
1490                repository_place(file).is_empty(),
1491                "a library at the checkout root has no extra path"
1492            );
1493            std::fs::remove_file(root.join("flow.toml")).unwrap();
1494            std::fs::remove_file(root.join(marker)).unwrap();
1495            std::fs::write(library.join("flow.toml"), "[process]\ncommand = 'serve'\n").unwrap();
1496        }
1497    }
1498
1499    static STARTED: AtomicUsize = AtomicUsize::new(0);
1500    static CLOSED: AtomicUsize = AtomicUsize::new(0);
1501    #[expect(
1502        clippy::unnecessary_wraps,
1503        reason = "exercises the fallible lifespan factory signature"
1504    )]
1505    fn start_sync() -> Result<Lifespan, StartError> {
1506        STARTED.fetch_add(1, Ordering::SeqCst);
1507        Ok(Resource::sync(7_usize, |value| {
1508            // Records the resource the cleanup was handed.
1509            CLOSED.store(*value, Ordering::SeqCst);
1510            Ok(())
1511        })
1512        .into_lifespan())
1513    }
1514    fn start_error() -> Result<Lifespan, StartError> {
1515        Err("fixture init error".into())
1516    }
1517    #[expect(
1518        clippy::unnecessary_wraps,
1519        reason = "opening succeeds so the cleanup failure can be observed"
1520    )]
1521    fn close_error() -> Result<Lifespan, StartError> {
1522        Ok(Resource::sync((), |_| Err("fixture close error".into())).into_lifespan())
1523    }
1524    #[test]
1525    fn relative_imports_follow_module_paths_and_reach_the_root_from_its_parent() {
1526        for (from, to, expected) in [
1527            ("", "models", "./models"),
1528            ("", "a/b", "./a/b"),
1529            ("a/b", "a/x", "./x"),
1530            ("a/b", "x", "../x"),
1531            ("a/c/d", "b/y", "../../b/y"),
1532            ("a/c/d", "a/c/e/f", "./e/f"),
1533            ("models", "", "../ledger"),
1534            ("a/b", "", "../../ledger"),
1535        ] {
1536            assert_eq!(
1537                relative_import(from, to, "ledger"),
1538                expected,
1539                "{from} -> {to}"
1540            );
1541        }
1542    }
1543
1544    #[test]
1545    fn a_contract_file_names_the_module_it_declares() {
1546        let modules = BTreeSet::from(["", "session", "a/b"]);
1547        for (file, expected) in [
1548            ("./ledger/contract/lib", Some("")),
1549            ("ledger/contract/lib.flow", Some("")),
1550            ("./ledger/contract/session", Some("session")),
1551            ("contract/a/b", Some("a/b")),
1552            ("session", Some("session")),
1553            ("./other/session", None),
1554            ("", Some("")),
1555            ("./ledger/contract/missing", None),
1556        ] {
1557            assert_eq!(module_of(file, &modules), expected, "{file}");
1558        }
1559        assert_eq!(module_of("", &BTreeSet::from(["session"])), None);
1560    }
1561
1562    #[test]
1563    fn a_type_file_is_made_relative_to_the_library_root_however_cargo_spelled_it() {
1564        let files = tempfile::TempDir::with_prefix("flow-library-file").unwrap();
1565        let workspace = std::fs::canonicalize(files.path()).unwrap();
1566        let root = workspace.join("libraries/ledger");
1567        std::fs::create_dir_all(root.join("src")).unwrap();
1568        std::fs::write(root.join("src/lib.rs"), "").unwrap();
1569        let absolute = root.join("src/lib.rs");
1570        assert_eq!(
1571            library_file(Some(&root), absolute.to_str().unwrap()),
1572            "src/lib.rs"
1573        );
1574        assert_eq!(library_file(Some(&root), "src/lib.rs"), "src/lib.rs");
1575        assert_eq!(
1576            library_file(Some(&root), "libraries/ledger/src/lib.rs"),
1577            "src/lib.rs",
1578            "a workspace member's file is spelled from the workspace root"
1579        );
1580        assert_eq!(
1581            library_file(Some(&root), "elsewhere/x.rs"),
1582            "elsewhere/x.rs"
1583        );
1584        assert_eq!(library_file(None, "src\\lib.rs"), "src/lib.rs");
1585    }
1586
1587    /// The type `name` the Rust module `module` defines.
1588    fn rust(module: &'static str, name: &str) -> TypeRef<Owner> {
1589        TypeRef::qualified(Owner::Rust(module), name)
1590    }
1591
1592    #[test]
1593    fn references_close_bare_in_their_module_and_through_an_import_elsewhere() {
1594        let declaration = Declaration::Flow(FlowDeclaration {
1595            name: "r".to_owned(),
1596            generics: Vec::new(),
1597            params: vec![Param {
1598                name: "a".to_owned(),
1599                ty: rust("ledger::models", "Refund"),
1600                default: None,
1601            }],
1602            result: TypeRef::applied(
1603                "List",
1604                vec![TypeRef::Named {
1605                    module: Some(Owner::Rust("ledger")),
1606                    name: "Box".to_owned(),
1607                    args: vec![TypeRef::named("Int")],
1608                }],
1609            ),
1610        });
1611        assert_eq!(
1612            owners(&declaration),
1613            [Owner::Rust("ledger::models"), Owner::Rust("ledger")]
1614        );
1615        let modules = BTreeMap::from([
1616            ("ledger::models", Target::Local("models".to_owned())),
1617            ("ledger", Target::Local(String::new())),
1618        ]);
1619        let bindings = BTreeMap::from([
1620            (Target::Local("models".to_owned()), "models".to_owned()),
1621            (Target::Local(String::new()), "ledger".to_owned()),
1622        ]);
1623        let written = |module: &str| {
1624            let here = Target::Local(module.to_owned());
1625            let item = Item {
1626                docs: String::new(),
1627                origin: None,
1628                declaration: declaration
1629                    .qualify(&mut |owner| qualified(owner, &here, &modules, &bindings)),
1630            };
1631            contract::print_item(&item)
1632        };
1633        assert_eq!(
1634            written(""),
1635            "pub flow r(a: models.Refund) -> List<Box<Int>>\n"
1636        );
1637        assert_eq!(
1638            written("models"),
1639            "pub flow r(a: Refund) -> List<ledger.Box<Int>>\n"
1640        );
1641    }
1642
1643    /// A Tool named `name` that `#[tool]` found in the Rust module `module`.
1644    fn found_in(name: &'static str, module: &'static str) -> Function {
1645        let origin = Origin {
1646            module,
1647            file: "src/lib.rs",
1648            line: 1,
1649        };
1650        Function::new(
1651            name,
1652            origin,
1653            "",
1654            Vec::new(),
1655            TypeRef::named("Unit"),
1656            Types::default(),
1657            crate::test_contract::__flow_tool_exact().factory,
1658        )
1659    }
1660
1661    /// A tree holding `payments`, a member of the workspace at its top,
1662    /// beside `plans`, a crate whose library target is named `plans`.
1663    fn dependent_tree() -> tempfile::TempDir {
1664        let files = tempfile::TempDir::with_prefix("flow-foreign-types").unwrap();
1665        for (path, text) in [
1666            (
1667                "Cargo.toml",
1668                "[workspace]\nmembers = [\"payments\"]\n[workspace.dependencies]\nledger = { git = \"https://github.com/acme/ledger.git\", tag = \"v1.2\" }\n",
1669            ),
1670            (
1671                "plans/Cargo.toml",
1672                "[package]\nname = \"plans-core\"\nversion = \"0.0.0\"\n[lib]\nname = \"plans\"\n",
1673            ),
1674            (
1675                "Plans-Core/Cargo.toml",
1676                "[package]\nname = \"plans-core\"\nversion = \"0.0.0\"\n",
1677            ),
1678            (
1679                "payments/Cargo.toml",
1680                "[package]\nname = \"payments\"\nversion = \"0.0.0\"\n[dependencies]\nplans = { path = \"../plans\", package = \"plans-core\" }\ncore = { path = \"../Plans-Core\", package = \"plans-core\" }\nledger.workspace = true\nunpinned = { git = \"https://github.com/acme/unpinned\", branch = \"main\" }\nserde = \"1\"\n[target.'cfg(unix)'.dependencies]\nshared-models = { git = \"git@github.com:acme/shared\", tag = \"v2\" }\n",
1681            ),
1682        ] {
1683            let path = files.path().join(path);
1684            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1685            std::fs::write(path, text).unwrap();
1686        }
1687        files
1688    }
1689
1690    /// The Tool `name` of the library module `module` taking `params`,
1691    /// whose types define `declared`, each `(Rust module, name)`.
1692    fn reaching(
1693        name: &'static str,
1694        module: &str,
1695        params: &[(&str, TypeRef<Owner>)],
1696        result: TypeRef<Owner>,
1697        declared: &[(&'static str, &'static str, &'static str)],
1698    ) -> Function {
1699        let definitions = declared
1700            .iter()
1701            .map(|&(key, module, name)| {
1702                let declared = Declared {
1703                    name,
1704                    module,
1705                    file: "src/lib.rs",
1706                    line: 1,
1707                    docs: "",
1708                    declaration: Declaration::Type(TypeDeclaration {
1709                        name: name.to_owned(),
1710                        params: Vec::new(),
1711                        body: TypeBody::Record(vec![Field {
1712                            docs: String::new(),
1713                            visibility: Visibility::Public,
1714                            name: "id".to_owned(),
1715                            ty: TypeRef::named("Int"),
1716                        }]),
1717                    }),
1718                };
1719                (key.to_owned(), declared)
1720            })
1721            .collect();
1722        let types = Types {
1723            definitions,
1724            ..Types::default()
1725        };
1726        let origin = Origin {
1727            module: "payments",
1728            file: "src/lib.rs",
1729            line: 2,
1730        };
1731        let params = params
1732            .iter()
1733            .map(|(name, ty)| Param {
1734                name: (*name).to_owned(),
1735                ty: ty.clone(),
1736                default: None,
1737            })
1738            .collect();
1739        Function::new(name, origin, "", params, result, types, || {
1740            unreachable!("extraction never serves")
1741        })
1742        .at(module, "src/lib.rs", 2)
1743    }
1744
1745    #[test]
1746    fn a_library_s_dependencies_are_read_from_its_cargo_toml_and_its_workspace_s() {
1747        let files = dependent_tree();
1748        let tree = std::fs::canonicalize(files.path()).unwrap();
1749        let git = |url: &str, tag: Option<&str>| Dependency::Git {
1750            url: url.to_owned(),
1751            tag: tag.map(str::to_owned),
1752        };
1753        assert_eq!(
1754            cargo_dependencies(&tree.join("payments"), &std::cell::RefCell::default()),
1755            BTreeMap::from([
1756                (
1757                    "ledger".to_owned(),
1758                    git("https://github.com/acme/ledger.git", Some("v1.2"))
1759                ),
1760                ("plans".to_owned(), Dependency::Path(tree.join("plans"))),
1761                (
1762                    "plans_core".to_owned(),
1763                    Dependency::Path(tree.join("Plans-Core"))
1764                ),
1765                ("serde".to_owned(), Dependency::Registry),
1766                (
1767                    "shared_models".to_owned(),
1768                    git("git@github.com:acme/shared", Some("v2"))
1769                ),
1770                (
1771                    "unpinned".to_owned(),
1772                    git("https://github.com/acme/unpinned", None)
1773                ),
1774            ])
1775        );
1776        assert_eq!(
1777            cargo_dependencies(&tree.join("missing"), &std::cell::RefCell::default()),
1778            BTreeMap::new()
1779        );
1780    }
1781
1782    #[test]
1783    fn a_package_at_its_workspace_s_root_inherits_from_its_own_manifest() {
1784        let files = tempfile::TempDir::with_prefix("flow-workspace-root").unwrap();
1785        let root = std::fs::canonicalize(files.path()).unwrap();
1786        std::fs::create_dir_all(root.join("plans")).unwrap();
1787        std::fs::write(
1788            root.join("plans/Cargo.toml"),
1789            "[package]\nname = \"plans\"\nversion = \"0.0.0\"\n",
1790        )
1791        .unwrap();
1792        std::fs::write(
1793            root.join("Cargo.toml"),
1794            "[package]\nname = \"payments\"\nversion = \"0.0.0\"\n[workspace.dependencies]\nplans = { path = \"plans\" }\n[dependencies]\nplans.workspace = true\n",
1795        )
1796        .unwrap();
1797        assert_eq!(
1798            cargo_dependencies(&root, &std::cell::RefCell::default()),
1799            BTreeMap::from([("plans".to_owned(), Dependency::Path(root.join("plans")))])
1800        );
1801    }
1802
1803    #[test]
1804    fn an_import_name_is_made_a_flow_lowercase_name() {
1805        for (text, expected) in [
1806            ("plans", "plans"),
1807            ("Plans-Core", "plans_core"),
1808            ("plans.v2", "plans_v2"),
1809            ("2plans", "library_2plans"),
1810            ("", "library_"),
1811        ] {
1812            assert_eq!(lower_name(text), expected, "{text}");
1813        }
1814    }
1815
1816    #[test]
1817    fn a_git_url_at_a_version_tag_is_a_remote_repository() {
1818        for (url, expected) in [
1819            (
1820                "https://github.com/acme/plans",
1821                Some("github.com/acme/plans@v1.2"),
1822            ),
1823            (
1824                "https://github.com/acme/plans.git/",
1825                Some("github.com/acme/plans@v1.2"),
1826            ),
1827            (
1828                "ssh://git@github.com:22/acme/plans.git",
1829                Some("github.com/acme/plans@v1.2"),
1830            ),
1831            (
1832                "git@github.com:acme/plans",
1833                Some("github.com/acme/plans@v1.2"),
1834            ),
1835            ("plans", None),
1836        ] {
1837            assert_eq!(remote_repository(url, "v1.2").as_deref(), expected, "{url}");
1838        }
1839        for (tag, flow) in [
1840            ("v1", true),
1841            ("v1.2.3", true),
1842            ("v0.10", true),
1843            ("1.2", false),
1844            ("v01", false),
1845            ("v1.2.3.4", false),
1846            ("v1-rc", false),
1847        ] {
1848            assert_eq!(flow_tag(tag), flow, "{tag}");
1849        }
1850    }
1851
1852    #[test]
1853    fn a_tool_name_collision_renames_a_local_module_with_suffix_as() {
1854        let tool = reaching(
1855            "models",
1856            "",
1857            &[("value", rust("payments::models", "Plan"))],
1858            TypeRef::named("Int"),
1859            &[("payments::models::Plan", "payments::models", "Plan")],
1860        );
1861        let contracts = extract("payments", None, &[tool]).unwrap();
1862        assert!(contracts[""].contains("use \"./models\" as models_types\n"));
1863        assert!(contracts[""].contains("pub flow models(value: models_types.Plan) -> Int\n"));
1864    }
1865
1866    #[test]
1867    fn a_type_of_another_crate_is_imported_from_its_library_and_never_declared() {
1868        let files = dependent_tree();
1869        let root = files.path().join("payments");
1870        let charge = reaching(
1871            "charge",
1872            "",
1873            &[
1874                ("plan", rust("plans::models", "Plan")),
1875                ("models", TypeRef::named("Int")),
1876            ],
1877            rust("payments::models", "Plan"),
1878            &[
1879                ("plans::models::Plan", "plans::models", "Plan"),
1880                ("payments::models::Plan", "payments::models", "Plan"),
1881            ],
1882        );
1883        let post = reaching(
1884            "post",
1885            "sub/refunds",
1886            &[
1887                ("entry", rust("ledger", "Entry")),
1888                ("plan", rust("plans::models", "Plan")),
1889            ],
1890            TypeRef::named("Int"),
1891            &[
1892                ("ledger::Entry", "ledger", "Entry"),
1893                ("plans::models::Plan", "plans::models", "Plan"),
1894            ],
1895        );
1896        let contracts = extract("payments", Some(&root), &[charge, post]).unwrap();
1897        assert_eq!(
1898            contracts.keys().collect::<Vec<_>>(),
1899            ["", "models", "sub/refunds"]
1900        );
1901        assert_eq!(
1902            contracts[""],
1903            "// Generated by flow build from rust module payments. Do not edit.\nuse \"./models\"\nuse \"../plans/models\" as plans_models\n\n// from src/lib.rs: charge\npub flow charge(plan: plans_models.Plan, models: Int) -> models.Plan\n"
1904        );
1905        assert_eq!(
1906            contracts["sub/refunds"],
1907            "// Generated by flow build from rust module payments::sub::refunds. Do not edit.\nuse \"../../plans/models\"\nuse \"github.com/acme/ledger@v1.2\"\n\n// from src/lib.rs: post\npub flow post(entry: ledger.Entry, plan: models.Plan) -> Int\n"
1908        );
1909        assert_eq!(
1910            contracts["models"],
1911            "// Generated by flow build from rust module payments::models. Do not edit.\n\n// from src/lib.rs: Plan\npub type Plan {\n    pub id: Int,\n}\n"
1912        );
1913        let core = reaching(
1914            "audit",
1915            "",
1916            &[("core", rust("plans_core", "Plan"))],
1917            TypeRef::named("Int"),
1918            &[("plans_core::Plan", "plans_core", "Plan")],
1919        );
1920        assert!(
1921            extract("payments", Some(&root), &[core]).unwrap()[""]
1922                .contains("use \"../Plans-Core\" as plans_core\n"),
1923        );
1924        let shared = reaching(
1925            "share",
1926            "",
1927            &[("value", rust("shared_models::a", "Shared"))],
1928            TypeRef::named("Int"),
1929            &[("shared_models::a::Shared", "shared_models::a", "Shared")],
1930        );
1931        assert!(
1932            extract("payments", Some(&root), &[shared]).unwrap()[""]
1933                .contains("use \"github.com/acme/shared@v2/a\"\n"),
1934        );
1935    }
1936
1937    #[test]
1938    fn a_type_of_a_crate_with_no_flow_address_is_refused() {
1939        let files = dependent_tree();
1940        let root = files.path().join("payments");
1941        for (krate, module, key, how) in [
1942            (
1943                "serde",
1944                "serde::x",
1945                "serde::x::Value",
1946                "the registry dependency serde",
1947            ),
1948            (
1949                "unpinned",
1950                "unpinned::x",
1951                "unpinned::x::Value",
1952                "the git dependency unpinned, which names no tag such as v1.2",
1953            ),
1954        ] {
1955            let refused = extract(
1956                "payments",
1957                Some(&root),
1958                &[reaching(
1959                    "take",
1960                    "",
1961                    &[("value", rust(module, "Value"))],
1962                    TypeRef::named("Int"),
1963                    &[(key, module, "Value")],
1964                )],
1965            )
1966            .unwrap_err();
1967            assert_eq!(
1968                refused.to_string(),
1969                format!(
1970                    "{}:1:1: Value comes from {how}, so it has no Flow address and no contract can import it; depend on {krate} by a path in this repository or a git URL at a tag",
1971                    root.join("src/lib.rs").display()
1972                ),
1973            );
1974        }
1975    }
1976
1977    #[test]
1978    fn a_git_dependency_with_a_tag_but_no_repository_address_cannot_supply_a_type() {
1979        let files = dependent_tree();
1980        let root = files.path().join("payments");
1981        std::fs::write(root.join("Cargo.toml"), "[package]\nname = 'payments'\nversion = '0.0.0'\n[dependencies]\nledger = { git = 'not-a-repository', tag = 'v1.2' }\n").unwrap();
1982        let refused = extract(
1983            "payments",
1984            Some(&root),
1985            &[reaching(
1986                "take",
1987                "",
1988                &[("value", rust("ledger", "Entry"))],
1989                TypeRef::named("Unit"),
1990                &[("ledger::Entry", "ledger", "Entry")],
1991            )],
1992        )
1993        .unwrap_err();
1994        assert_eq!(
1995            refused.to_string(),
1996            format!(
1997                "{}:1:1: Entry comes from the git dependency ledger, whose URL not-a-repository names no repository, so it has no Flow address and no contract can import it; depend on ledger by a path in this repository or a git URL at a tag",
1998                root.join("src/lib.rs").display()
1999            )
2000        );
2001    }
2002
2003    #[test]
2004    fn a_contract_places_each_tool_in_its_module_and_belongs_to_one_crate() {
2005        let contract = contract_of(
2006            env!("CARGO_MANIFEST_DIR"),
2007            vec![
2008                found_in("ping", "ledger"),
2009                found_in("pong", "ledger::audit::log"),
2010            ],
2011        )
2012        .unwrap();
2013        assert_eq!(
2014            contract
2015                .modules()
2016                .keys()
2017                .map(Segments::as_str)
2018                .collect::<Vec<_>>(),
2019            ["", "audit/log"]
2020        );
2021        assert_eq!(
2022            contract.module("audit/log"),
2023            Some(
2024                "// Generated by flow build from rust module ledger::audit::log. Do not edit.\n\n// from src/lib.rs: pong\npub flow pong() -> Unit\n"
2025            )
2026        );
2027        assert_eq!(
2028            contract_of(
2029                "",
2030                vec![found_in("ping", "ledger"), found_in("pong", "journal::a")]
2031            ),
2032            Err(ContractError::SeveralCrates {
2033                first: "ledger".into(),
2034                second: "journal".into(),
2035            })
2036        );
2037    }
2038
2039    #[test]
2040    fn a_rust_module_named_lib_is_refused_since_its_contract_file_is_the_roots() {
2041        let refused = contract_of(
2042            "",
2043            vec![found_in("ping", "ledger"), found_in("pong", "ledger::lib")],
2044        )
2045        .unwrap_err();
2046        assert!(
2047            matches!(&refused, ContractError::Spelled { module, .. } if module == "lib"),
2048            "{refused:?}"
2049        );
2050        assert!(
2051            refused.to_string().contains("rename the Rust module"),
2052            "{refused}"
2053        );
2054    }
2055
2056    #[test]
2057    fn a_module_path_segment_is_a_flow_lowercase_name() {
2058        let at = Location::new("src/x.rs".into(), 1);
2059        assert!(check_module("a/b_2", &at).is_ok());
2060        assert!(check_module("", &at).is_ok());
2061        for (module, segment) in [
2062            ("Utils", "Utils"),
2063            ("a/flow", "flow"),
2064            ("a/2b", "2b"),
2065            ("a/use", "use"),
2066        ] {
2067            assert_eq!(
2068                check_module(module, &at),
2069                Err(ContractError::NotAModulePath {
2070                    at: at.clone(),
2071                    module: module.into(),
2072                    segment: segment.into(),
2073                }),
2074            );
2075        }
2076        for module in ["lib", "contract", "contract/a"] {
2077            let refused = check_module(module, &at).unwrap_err();
2078            assert_eq!(
2079                refused,
2080                ContractError::Spelled {
2081                    at: at.clone(),
2082                    module: module.into(),
2083                }
2084            );
2085            assert!(
2086                refused.to_string().contains("contract/lib.flow"),
2087                "{refused}"
2088            );
2089        }
2090        assert!(check_module("a/lib", &at).is_ok());
2091        assert!(check_module("lib/a", &at).is_ok());
2092        assert_eq!(
2093            library_module("ledger", "ledger::a::b").as_deref(),
2094            Some("a/b")
2095        );
2096        assert_eq!(library_module("ledger", "ledger").as_deref(), Some(""));
2097        assert_eq!(library_module("ledger", "other::a"), None);
2098    }
2099
2100    #[test]
2101    fn a_resource_cleanup_keeps_its_error_and_the_resource_shows_its_type() {
2102        #[derive(Debug)]
2103        struct Refused(std::io::Error);
2104        impl std::fmt::Display for Refused {
2105            fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2106                formatter.write_str("refused to close")
2107            }
2108        }
2109        impl std::error::Error for Refused {
2110            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2111                Some(&self.0)
2112            }
2113        }
2114        let resource = Resource::sync(3_u8, |_| {
2115            Err(Refused(std::io::Error::other("still in use")).into())
2116        });
2117        assert_eq!(
2118            format!("{resource:?}"),
2119            "Resource { type: \"u8\", .. }",
2120            "a resource shows the type it holds"
2121        );
2122        let lifespan = resource.into_lifespan();
2123        assert_eq!(
2124            format!("{lifespan:?}"),
2125            "Lifespan { .. }",
2126            "a lifespan hides its parts"
2127        );
2128        let error = block_on((lifespan.close)()).expect_err("the cleanup fails");
2129        assert_eq!(
2130            error.to_string(),
2131            "refused to close",
2132            "the author's error is kept"
2133        );
2134        assert_eq!(
2135            error.source().map(ToString::to_string).as_deref(),
2136            Some("still in use"),
2137            "and so is its source"
2138        );
2139    }
2140
2141    #[test]
2142    fn synchronous_resource_is_typed_shared_and_closed_even_when_serving_fails() {
2143        let spec = crate::test_types::spec(
2144            &crate::test_types::catalog(Vec::new()),
2145            &[],
2146            &[],
2147            flow_types::Type::Unit,
2148        );
2149        let context = crate::Context::try_new(
2150            "7f3a91c04be2d5e6f708192a3b4c5d6e/root#1"
2151                .parse()
2152                .expect("a call key"),
2153            &spec,
2154            None,
2155            crate::Cancellation::default(),
2156        )
2157        .unwrap();
2158        assert!(context.resource::<usize>().is_none());
2159        let error = with_resource(Some(start_sync), || {
2160            let first = context.resource::<usize>().unwrap();
2161            let second = context.resource::<usize>().unwrap();
2162            assert!(Arc::ptr_eq(&first, &second));
2163            assert_eq!(*first, 7);
2164            assert!(context.resource::<String>().is_none());
2165            Err("fixture serve failed".into())
2166        })
2167        .unwrap_err();
2168        assert_eq!(error, "fixture serve failed");
2169        assert_eq!(STARTED.load(Ordering::SeqCst), 1);
2170        assert_eq!(
2171            CLOSED.load(Ordering::SeqCst),
2172            7,
2173            "the cleanup ran on the resource it opened"
2174        );
2175        assert!(context.resource::<usize>().is_none());
2176        assert!(with_resource(None, || Ok(())).is_ok());
2177        assert!(
2178            with_resource(Some(start_error), || panic!(
2179                "startup failure must not serve"
2180            ))
2181            .unwrap_err()
2182            .contains("initialization failed")
2183        );
2184        assert!(
2185            with_resource(Some(close_error), || Ok(()))
2186                .unwrap_err()
2187                .contains("cleanup failed")
2188        );
2189        let error = with_resource(Some(close_error), || Err("serve failed".into())).unwrap_err();
2190        assert!(error.contains("serve failed") && error.contains("cleanup failed"));
2191    }
2192}