use std::any::Any;
use std::collections::{BTreeMap, BTreeSet};
use std::future::Future;
use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use crate::cli::{Command, UsageError};
use crate::contract::{Contract, ContractError, Location};
#[cfg(unix)]
use crate::server::Server;
use flow_abi::contract::{
self, Constructor, ContractModule, Declaration, Field, FlowDeclaration, Import, Item, Param,
Payload, TypeBody, TypeDeclaration, TypeRef, Visibility,
};
use flow_abi::wire::{Layout, Note, Notes, Parts, Shape, WireForm};
#[cfg(unix)]
use flow_abi::{TypeSpec, description};
#[cfg(unix)]
use flow_types::Placement;
use flow_types::{LibraryLayout, Segments, lowercase_name};
pub type CloseError = Box<dyn std::error::Error + Send + Sync>;
pub type StartError = Box<dyn std::error::Error + Send + Sync>;
#[cfg(unix)]
type CloseFuture = Pin<Box<dyn Future<Output = Result<(), CloseError>> + Send>>;
#[cfg(unix)]
type Close = Box<dyn FnOnce() -> CloseFuture + Send>;
static RESOURCE: Mutex<Option<Arc<dyn Any + Send + Sync>>> = Mutex::new(None);
pub struct Resource<T: Send + Sync + 'static> {
#[cfg(unix)]
value: Arc<T>,
#[cfg(unix)]
close: Box<dyn FnOnce(Arc<T>) -> CloseFuture + Send>,
#[cfg(not(unix))]
kept: std::marker::PhantomData<T>,
}
impl<T: Send + Sync + 'static> std::fmt::Debug for Resource<T> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("Resource")
.field("type", &std::any::type_name::<T>())
.finish_non_exhaustive()
}
}
impl<T: Send + Sync + 'static> Resource<T> {
pub fn new<F, Fut>(value: T, close: F) -> Self
where
F: FnOnce(Arc<T>) -> Fut + Send + 'static,
Fut: Future<Output = Result<(), CloseError>> + Send + 'static,
{
#[cfg(unix)]
{
Self {
value: Arc::new(value),
close: Box::new(move |value| Box::pin(close(value))),
}
}
#[cfg(not(unix))]
{
let _ = (value, close);
Self {
kept: std::marker::PhantomData,
}
}
}
pub fn sync<F>(value: T, close: F) -> Self
where
F: FnOnce(Arc<T>) -> Result<(), CloseError> + Send + 'static,
{
Self::new(value, move |value| std::future::ready(close(value)))
}
#[doc(hidden)]
pub fn into_lifespan(self) -> Lifespan {
#[cfg(unix)]
{
let value = Arc::clone(&self.value);
Lifespan {
value: self.value,
close: Box::new(move || (self.close)(value)),
}
}
#[cfg(not(unix))]
{
let _ = self;
Lifespan {}
}
}
}
pub struct Lifespan {
#[cfg(unix)]
value: Arc<dyn Any + Send + Sync>,
#[cfg(unix)]
close: Close,
}
impl std::fmt::Debug for Lifespan {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("Lifespan").finish_non_exhaustive()
}
}
pub type Start = fn() -> Result<Lifespan, StartError>;
impl crate::Context {
pub fn resource<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
RESOURCE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_ref()
.map(Arc::clone)?
.downcast::<T>()
.ok()
}
}
#[derive(Clone, Debug)]
pub struct Declared {
pub name: &'static str,
pub module: &'static str,
pub file: &'static str,
pub line: u32,
pub docs: &'static str,
pub declaration: Declaration<Owner>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Owner {
Rust(&'static str),
Std(&'static str),
}
#[derive(Default, Debug)]
pub struct Types {
definitions: BTreeMap<String, Declared>,
declaring: BTreeSet<String>,
parameters: Vec<Vec<String>>,
}
impl Types {
pub fn parameters(&mut self, names: &[&str]) {
self.parameters
.push(names.iter().map(|s| (*s).into()).collect());
}
pub fn end_parameters(&mut self) {
self.parameters.pop();
}
pub fn form(&mut self, form: WireForm) -> TypeRef<Owner> {
match form {
WireForm::Int => TypeRef::named("Int"),
WireForm::Decimal => TypeRef::named("Decimal"),
WireForm::Bool => TypeRef::named("Bool"),
WireForm::Text => TypeRef::named("Text"),
WireForm::Bytes => TypeRef::named("Bytes"),
WireForm::Unit => TypeRef::named("Unit"),
WireForm::Never => TypeRef::named("Never"),
WireForm::Duration => TypeRef::qualified(Owner::Std("duration"), "Duration"),
WireForm::Instant => TypeRef::qualified(Owner::Std("time"), "Instant"),
WireForm::RunId | WireForm::CallRef | WireForm::Number | WireForm::Rest => {
panic!("{form:?} is a message's form, which no Tool's type has")
}
WireForm::Option(item) => TypeRef::applied("Option", vec![self.form(item())]),
WireForm::List(item) => TypeRef::applied("List", vec![self.form(item())]),
WireForm::Set(item) => TypeRef::applied("Set", vec![self.form(item())]),
WireForm::Dict(key, value) => {
TypeRef::applied("Dict", vec![self.form(key()), self.form(value())])
}
WireForm::Tuple(parts) => TypeRef::Tuple(self.forms(parts)),
WireForm::Param(at) => TypeRef::named(
self.parameters
.last()
.and_then(|names| names.get(at))
.expect("generic parameter scope"),
),
WireForm::Declared(shape) => self.declared(shape(), &[]),
WireForm::Applied(shape, args) => self.declared(shape(), args),
WireForm::Std { module, name, args } => TypeRef::Named {
module: (!module.is_empty()).then_some(Owner::Std(module)),
name: name.to_owned(),
args: self.forms(args),
},
}
}
fn forms(&mut self, forms: &[fn() -> WireForm]) -> Vec<TypeRef<Owner>> {
forms.iter().map(|form| self.form(form())).collect()
}
fn declared(&mut self, shape: &'static Shape, args: &[fn() -> WireForm]) -> TypeRef<Owner> {
let notes = shape
.notes
.unwrap_or_else(|| panic!("{} has no notes: derive Flow for it", shape.name));
let key = format!(
"{}::{} at {}:{}",
notes.module, shape.name, notes.file, notes.line
);
if !self.definitions.contains_key(&key) && self.declaring.insert(key.clone()) {
self.parameters(shape.params);
let declaration = self.declaration(shape, notes);
self.end_parameters();
self.declaring.remove(&key);
self.definitions.insert(
key,
Declared {
name: shape.name,
module: notes.module,
file: notes.file,
line: notes.line,
docs: notes.docs,
declaration,
},
);
}
TypeRef::Named {
module: Some(Owner::Rust(notes.module)),
name: shape.name.to_owned(),
args: self.forms(args),
}
}
fn declaration(&mut self, shape: &Shape, notes: &Notes) -> Declaration<Owner> {
let note = |at: usize| ¬es.members[at];
let field = |types: &mut Types, note: &Note, name: &str, form: WireForm| Field {
docs: note.docs.to_owned(),
visibility: visibility(note),
name: name.to_owned(),
ty: types.form(form),
};
let body = match shape.layout {
Layout::Host => TypeBody::Host,
Layout::Newtype(base) => TypeBody::Newtype {
visibility: visibility(note(0)),
base: self.form(base),
},
Layout::Record(fields) => TypeBody::Record(
fields
.iter()
.enumerate()
.map(|(at, member)| field(self, note(at), member.name, member.form))
.collect(),
),
Layout::Enum(ctors) => TypeBody::Enum(
ctors
.iter()
.enumerate()
.map(|(at, ctor)| Constructor {
docs: note(at).docs.to_owned(),
name: ctor.name.to_owned(),
payload: match ctor.parts {
Parts::Empty => Payload::Empty,
Parts::Positional(forms) => Payload::Positional(
forms.iter().map(|form| self.form(*form)).collect(),
),
Parts::Named(fields) => Payload::Named(
fields
.iter()
.enumerate()
.map(|(index, member)| Field {
visibility: Visibility::Private,
..field(
self,
¬e(at).fields[index],
member.name,
member.form,
)
})
.collect(),
),
},
})
.collect(),
),
};
Declaration::Type(TypeDeclaration {
name: shape.name.to_owned(),
params: shape
.params
.iter()
.map(|param| (*param).to_owned())
.collect(),
body,
})
}
}
fn visibility(note: &Note) -> Visibility {
if note.public {
Visibility::Public
} else {
Visibility::Private
}
}
type Factory = fn() -> crate::server::Adapter;
#[derive(Clone, Debug, Default)]
struct Place {
module: String,
file: String,
line: u32,
}
#[derive(Clone, Copy, Debug)]
pub struct Origin {
pub module: &'static str,
pub file: &'static str,
pub line: u32,
}
#[derive(Debug)]
pub struct Function {
name: &'static str,
origin: Origin,
generic: Vec<String>,
docs: &'static str,
params: Vec<Param<Owner>>,
result: TypeRef<Owner>,
types: Types,
#[cfg(unix)]
factory: Factory,
place: Place,
}
impl Function {
pub(crate) fn with_generics(mut self, names: &[&str]) -> Self {
self.generic = names.iter().map(|name| (*name).into()).collect();
self
}
pub(crate) fn at(mut self, module: &str, file: &str, line: u32) -> Self {
self.place = Place {
module: module.into(),
file: file.into(),
line,
};
self
}
pub(crate) fn new(
name: &'static str,
origin: Origin,
docs: &'static str,
params: Vec<Param<Owner>>,
result: TypeRef<Owner>,
types: Types,
factory: Factory,
) -> Self {
#[cfg(not(unix))]
let _ = factory;
Self {
name,
origin,
generic: Vec::new(),
docs,
params,
result,
types,
#[cfg(unix)]
factory,
place: Place::default(),
}
}
}
impl Function {
#[cfg(unix)]
pub(crate) fn declare(
&self,
identity: description::Identity,
spec: TypeSpec,
) -> crate::server::Declaration {
crate::server::Declaration::new(identity, spec, (self.factory)())
}
}
struct Entry<'a> {
file: String,
line: u32,
name: &'a str,
docs: &'a str,
declaration: Declaration<Owner>,
}
fn library_module(crate_name: &str, module: &str) -> Option<String> {
let mut segments = module.split("::");
if segments.next() != Some(crate_name) {
return None;
}
Some(segments.collect::<Vec<_>>().join("/"))
}
fn library_file(root: Option<&Path>, file: &str) -> String {
let spelled = || file.replace('\\', "/");
let Some(root) = root.and_then(|root| std::fs::canonicalize(root).ok()) else {
return spelled();
};
let path = Path::new(file);
let candidates: Vec<PathBuf> = if path.is_absolute() {
vec![path.to_owned()]
} else {
root.ancestors()
.map(|directory| directory.join(path))
.collect()
};
for candidate in candidates {
if let Ok(found) = std::fs::canonicalize(candidate)
&& let Ok(relative) = found.strip_prefix(&root)
&& let Some(relative) = relative.to_str()
{
return relative.replace('\\', "/");
}
}
spelled()
}
fn check_module(module: &str, at: &Location) -> Result<Segments, ContractError> {
let not_a_path = |segment: &str| ContractError::NotAModulePath {
at: at.clone(),
module: module.to_owned(),
segment: segment.to_owned(),
};
let path: Segments = module.parse().map_err(|_| not_a_path(""))?;
if let Some(segment) = path.names().find(|segment| !lowercase_name(segment)) {
return Err(not_a_path(segment));
}
if LibraryLayout::spelled(&path).is_some() {
return Err(ContractError::Spelled {
at: at.clone(),
module: module.to_owned(),
});
}
Ok(path)
}
fn relative_import(from: &str, to: &str, root: &str) -> String {
let mut directory: Vec<&str> = if from.is_empty() {
Vec::new()
} else {
from.split('/').collect()
};
directory.pop();
if to.is_empty() {
return format!("{}{root}", "../".repeat(directory.len() + 1));
}
let target: Vec<&str> = to.split('/').collect();
let shared = directory
.iter()
.zip(&target[..target.len() - 1])
.take_while(|(left, right)| left == right)
.count();
let rest = target[shared..].join("/");
match directory.len() - shared {
0 => format!("./{rest}"),
ups => format!("{}{rest}", "../".repeat(ups)),
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Target {
Local(String),
Path {
root: PathBuf,
module: String,
},
Remote(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Dependency {
Path(PathBuf),
Git {
url: String,
tag: Option<String>,
},
Registry,
}
fn cargo_dependencies(
root: &Path,
read: &std::cell::RefCell<BTreeSet<PathBuf>>,
) -> BTreeMap<String, Dependency> {
let read = |path: &Path| {
read.borrow_mut().insert(path.to_owned());
std::fs::read_to_string(path)
.ok()?
.parse::<toml::Table>()
.ok()
};
let Some(manifest) = read(&root.join("Cargo.toml")) else {
return BTreeMap::new();
};
let workspace = root.ancestors().find_map(|directory| {
let table = read(&directory.join("Cargo.toml"))?;
let dependencies = table.get("workspace")?.get("dependencies");
let dependencies = dependencies.and_then(toml::Value::as_table).cloned();
Some((directory.to_owned(), dependencies.unwrap_or_default()))
});
let targets = manifest
.get("target")
.and_then(toml::Value::as_table)
.into_iter()
.flat_map(|targets| {
targets
.values()
.filter_map(|target| target.get("dependencies"))
});
let mut found = BTreeMap::new();
for table in manifest
.get("dependencies")
.into_iter()
.chain(targets)
.filter_map(toml::Value::as_table)
{
for (key, written) in table {
let inherited = written.get("workspace").and_then(toml::Value::as_bool) == Some(true);
let (spec, base) = match (&workspace, inherited) {
(_, false) => (written, root),
(Some((directory, dependencies)), true) => match dependencies.get(key) {
Some(spec) => (spec, directory.as_path()),
None => continue,
},
(None, true) => continue,
};
let text = |name: &str| {
written
.get(name)
.or_else(|| spec.get(name))
.and_then(toml::Value::as_str)
};
let package = text("package").unwrap_or(key);
let (name, dependency) = if let Some(path) = text("path") {
let at = base.join(path);
let at = std::fs::canonicalize(&at).unwrap_or(at);
let named = read(&at.join("Cargo.toml")).and_then(|manifest| {
let name = |table: &str| {
manifest
.get(table)?
.get("name")?
.as_str()
.map(str::to_owned)
};
name("lib").or_else(|| name("package"))
});
(
named.unwrap_or_else(|| package.to_owned()),
Dependency::Path(at),
)
} else if let Some(url) = text("git") {
let tag = text("tag").map(str::to_owned);
(
package.to_owned(),
Dependency::Git {
url: url.to_owned(),
tag,
},
)
} else {
(package.to_owned(), Dependency::Registry)
};
found.insert(name.replace('-', "_"), dependency);
}
}
found
}
fn flow_tag(tag: &str) -> bool {
tag.strip_prefix('v').is_some_and(|numbers| {
let parts: Vec<&str> = numbers.split('.').collect();
parts.len() <= 3
&& parts.iter().all(|part| {
!part.is_empty()
&& part.bytes().all(|byte| byte.is_ascii_digit())
&& (*part == "0" || !part.starts_with('0'))
})
})
}
fn remote_repository(url: &str, tag: &str) -> Option<String> {
let url = url.strip_prefix("git+").unwrap_or(url);
let location = match url.split_once("://") {
Some((_, location)) => location.to_owned(),
None if url.contains(':') => url.replacen(':', "/", 1),
None => return None,
};
let location = location.split(['#', '?']).next().unwrap_or_default();
let location = location
.rsplit_once('@')
.map_or(location, |(_, after)| after);
let (host, path) = location.split_once('/')?;
let host = host.split(':').next().unwrap_or(host);
let path = path.trim_matches('/');
let path = path.strip_suffix(".git").unwrap_or(path);
(!host.is_empty() && !path.is_empty()).then(|| format!("{host}/{path}@{tag}"))
}
fn repository_place(file: &str) -> Vec<String> {
let file = Path::new(file);
if !file.is_absolute() {
return Vec::new();
}
let Some(library) = file
.ancestors()
.skip(1)
.find(|directory| directory.join("flow.toml").is_file())
else {
return Vec::new();
};
library
.ancestors()
.find(|directory| directory.join(".git").exists() || directory.join(".cargo-ok").exists())
.and_then(|checkout| library.strip_prefix(checkout).ok())
.map(|inside| {
inside
.components()
.map(|part| part.as_os_str().to_string_lossy().into_owned())
.collect()
})
.unwrap_or_default()
}
fn foreign_target(
definition: &Declared,
at: &Location,
dependencies: &BTreeMap<String, Dependency>,
) -> Result<Target, ContractError> {
let (krate, inside) = definition
.module
.split_once("::")
.unwrap_or((definition.module, ""));
let module = inside
.split("::")
.filter(|segment| !segment.is_empty())
.collect::<Vec<_>>();
let unaddressed = |how: String| ContractError::UnaddressedType {
at: at.clone(),
name: definition.name.to_owned(),
dependency: krate.to_owned(),
how,
};
match dependencies.get(krate) {
None => Err(ContractError::ForeignType {
at: at.clone(),
name: definition.name.to_owned(),
module: definition.module.to_owned(),
}),
Some(Dependency::Path(root)) => Ok(Target::Path {
root: root.clone(),
module: module.join("/"),
}),
Some(Dependency::Registry) => Err(unaddressed(format!("the registry dependency {krate}"))),
Some(Dependency::Git { url, tag }) => {
let Some(tag) = tag.as_deref().filter(|tag| flow_tag(tag)) else {
return Err(unaddressed(format!(
"the git dependency {krate}, which names no tag such as v1.2"
)));
};
let repository = remote_repository(url, tag).ok_or_else(|| {
unaddressed(format!(
"the git dependency {krate}, whose URL {url} names no repository"
))
})?;
let mut path = vec![repository];
path.extend(repository_place(definition.file));
path.extend(module.into_iter().map(str::to_owned));
Ok(Target::Remote(path.join("/")))
}
}
}
fn relative_place(from: &Path, to: &Path) -> String {
let from: Vec<_> = from.components().collect();
let to: Vec<_> = to.components().collect();
let shared = from
.iter()
.zip(&to)
.take_while(|(left, right)| left == right)
.count();
std::iter::repeat_n("..".to_owned(), from.len() - shared)
.chain(
to[shared..]
.iter()
.map(|part| part.as_os_str().to_string_lossy().into_owned()),
)
.collect::<Vec<_>>()
.join("/")
}
pub fn extract(
crate_name: &str,
root: Option<&Path>,
functions: &[Function],
) -> Result<BTreeMap<Segments, ContractModule>, ContractError> {
extract_reading(crate_name, root, functions, &std::cell::RefCell::default())
}
fn extract_reading(
crate_name: &str,
root: Option<&Path>,
functions: &[Function],
read: &std::cell::RefCell<BTreeSet<PathBuf>>,
) -> Result<BTreeMap<Segments, ContractModule>, ContractError> {
let located = |file: &str, line: u32| match root {
Some(root) if Path::new(file).is_relative() => {
Location::new(root.join(file).display().to_string(), line)
}
_ => Location::new(file.to_owned(), line),
};
let mut grouped = tool_entries(functions, &located)?;
let mut declared: BTreeMap<&str, &Declared> = BTreeMap::new();
for (key, definition) in functions
.iter()
.flat_map(|function| &function.types.definitions)
{
declared.entry(key.as_str()).or_insert(definition);
}
let dependencies = root
.map(|root| cargo_dependencies(root, read))
.unwrap_or_default();
let mut modules: BTreeMap<&str, Target> = BTreeMap::new();
let mut names: BTreeMap<(String, &str), &str> = BTreeMap::new();
for (key, definition) in declared {
let file = library_file(root, definition.file);
let located = located(&file, definition.line);
let Some(module) = library_module(crate_name, definition.module) else {
modules.insert(
definition.module,
foreign_target(definition, &located, &dependencies)?,
);
continue;
};
let path = check_module(&module, &located)?;
if let Some(previous) = names.insert((module.clone(), definition.name), key) {
return Err(ContractError::SharedFlowName {
at: located,
name: definition.name.to_owned(),
first: previous.to_owned(),
second: key.to_owned(),
});
}
modules.insert(definition.module, Target::Local(module));
grouped.entry(path).or_default().push(Entry {
file,
line: definition.line,
name: definition.name,
docs: definition.docs,
declaration: definition.declaration.clone(),
});
}
let canonical = root.and_then(|root| std::fs::canonicalize(root).ok());
let root_name = canonical
.as_ref()
.and_then(|root| root.file_name()?.to_str().map(str::to_owned))
.unwrap_or_else(|| crate_name.to_owned());
let parent = canonical.as_deref().and_then(Path::parent);
let mut contracts = BTreeMap::new();
for (module, mut entries) in grouped {
entries.sort_by(|left, right| {
(&left.file, left.line, left.name).cmp(&(&right.file, right.line, right.name))
});
for std in entries.iter().flat_map(|entry| owners(&entry.declaration)) {
let Owner::Std(std) = std else { continue };
if let Some(entry) = entries.iter().find(|entry| entry.name == std) {
return Err(ContractError::StdImportCollision {
at: located(&entry.file, entry.line),
name: std.to_owned(),
});
}
}
let generated = contract_module(
crate_name,
&root_name,
parent,
module.as_str(),
&entries,
&modules,
);
contracts.insert(module, generated);
}
Ok(contracts)
}
fn tool_entries<'a>(
functions: &'a [Function],
located: &impl Fn(&str, u32) -> Location,
) -> Result<BTreeMap<Segments, Vec<Entry<'a>>>, ContractError> {
let mut grouped: BTreeMap<Segments, Vec<Entry<'a>>> = BTreeMap::new();
let mut tools = BTreeSet::new();
for function in functions {
let place = &function.place;
let located = located(&place.file, place.line);
let module = check_module(&place.module, &located)?;
if !tools.insert((place.module.as_str(), function.name)) {
return Err(ContractError::DuplicateTool {
at: located,
name: function.name.to_owned(),
});
}
grouped.entry(module).or_default().push(Entry {
file: place.file.clone(),
line: place.line,
name: function.name,
docs: function.docs,
declaration: Declaration::Flow(FlowDeclaration {
name: function.name.to_owned(),
generics: function.generic.clone(),
params: function.params.clone(),
result: function.result.clone(),
}),
});
}
Ok(grouped)
}
pub fn contract_of(root: &str, functions: Vec<Function>) -> Result<Contract, ContractError> {
let root = Path::new(root);
let mut crate_name: Option<&'static str> = None;
let mut placed = Vec::with_capacity(functions.len());
for function in functions {
let Origin { module, file, line } = function.origin;
let (owner, path) = module.split_once("::").unwrap_or((module, ""));
match crate_name {
Some(first) if first != owner => {
return Err(ContractError::SeveralCrates {
first: first.to_owned(),
second: owner.to_owned(),
});
}
_ => crate_name = Some(owner),
}
let path = path.split("::").collect::<Vec<_>>().join("/");
let file = library_file(Some(root), file);
placed.push(function.at(&path, &file, line));
}
let modules = extract(crate_name.unwrap_or_default(), Some(root), &placed)?
.into_iter()
.map(|(path, module)| (path, contract::print(&module)))
.collect();
Ok(Contract::new(root.to_owned(), modules))
}
fn foreign_import(
target: &Target,
module: &str,
parent: Option<&Path>,
) -> Option<(String, String, String)> {
let (path, natural, library) = match target {
Target::Local(_) => return None,
Target::Remote(path) => {
let (repository, inside) = path.split_once('@').unwrap_or((path, ""));
let library = repository.rsplit('/').next().unwrap_or(repository);
let natural = inside
.split_once('/')
.map_or(library, |(_, rest)| rest.rsplit('/').next().unwrap_or(rest));
(path.clone(), natural.to_owned(), library.to_owned())
}
Target::Path {
root,
module: place,
} => {
let library = root
.file_name()
.map_or_else(String::new, |name| name.to_string_lossy().into_owned());
let mut path = "../".repeat(module.split('/').count());
path.push_str(&parent.map_or_else(
|| root.to_string_lossy().into_owned(),
|parent| relative_place(parent, root),
));
let natural = if place.is_empty() {
library.clone()
} else {
path.push('/');
path.push_str(place);
place.rsplit('/').next().unwrap_or(place).to_owned()
};
(path, natural, library)
}
};
let fallback = if lowercase_name(&natural) {
format!("{library}_{natural}")
} else {
natural.clone()
};
Some((path, natural, fallback))
}
fn lower_name(text: &str) -> String {
let name: String = text
.to_lowercase()
.chars()
.map(|char| {
if char.is_ascii_lowercase() || char.is_ascii_digit() {
char
} else {
'_'
}
})
.collect();
if name.starts_with(|char: char| char.is_ascii_lowercase()) {
name
} else {
format!("library_{name}")
}
}
fn owners(declaration: &Declaration<Owner>) -> Vec<Owner> {
let mut found = Vec::new();
declaration.qualify(&mut |owner: &Owner| -> Option<()> {
found.push(*owner);
None
});
found
}
fn qualified(
owner: &Owner,
here: &Target,
modules: &BTreeMap<&str, Target>,
bindings: &BTreeMap<Target, String>,
) -> Option<String> {
match owner {
Owner::Std(std) => Some((*std).to_owned()),
Owner::Rust(rust) => modules
.get(rust)
.filter(|target| *target != here)
.and_then(|target| bindings.get(target))
.cloned(),
}
}
fn bind(
imports: &mut Vec<Import>,
taken: &mut BTreeSet<String>,
path: String,
natural: &str,
fallback: &str,
) -> String {
let binding = if lowercase_name(natural) && !taken.contains(natural) {
None
} else {
let base = lower_name(fallback);
let mut binding = base.clone();
let mut number = 2;
while !lowercase_name(&binding) || taken.contains(&binding) {
binding = format!("{base}_{number}");
number += 1;
}
Some(binding)
};
let bound = binding.clone().unwrap_or_else(|| natural.to_owned());
imports.push(Import { path, binding });
taken.insert(bound.clone());
bound
}
fn contract_module(
crate_name: &str,
root_name: &str,
parent: Option<&Path>,
module: &str,
entries: &[Entry<'_>],
modules: &BTreeMap<&str, Target>,
) -> ContractModule {
let mut origin = crate_name.to_owned();
for segment in module.split('/').filter(|segment| !segment.is_empty()) {
origin.push_str("::");
origin.push_str(segment);
}
let mut taken: BTreeSet<String> = entries.iter().map(|entry| entry.name.to_owned()).collect();
let owned: Vec<Owner> = entries
.iter()
.flat_map(|entry| owners(&entry.declaration))
.collect();
let mut imports = Vec::new();
let named_std: BTreeSet<&str> = owned
.iter()
.filter_map(|owner| match owner {
Owner::Std(std) => Some(*std),
Owner::Rust(_) => None,
})
.collect();
for std in &named_std {
imports.push(Import {
path: format!("std@v1/{std}"),
binding: None,
});
taken.insert((*std).to_owned());
}
let here = Target::Local(module.to_owned());
let referenced: BTreeSet<&Target> = owned
.iter()
.filter_map(|owner| match owner {
Owner::Rust(rust) => modules.get(rust),
Owner::Std(_) => None,
})
.filter(|target| **target != here)
.collect();
let mut bindings = BTreeMap::new();
for target in &referenced {
let Target::Local(target) = target else {
continue;
};
let target = target.as_str();
let natural = if target.is_empty() {
root_name
} else {
target.rsplit('/').next().unwrap_or(target)
};
let path = relative_import(module, target, root_name);
let fallback = if target.is_empty() {
crate_name.to_owned()
} else {
format!("{natural}_types")
};
let binding = bind(&mut imports, &mut taken, path, natural, &fallback);
bindings.insert(Target::Local(target.to_owned()), binding);
}
let mut others: Vec<_> = referenced
.iter()
.filter_map(|target| Some((foreign_import(target, module, parent)?, *target)))
.collect();
others.sort();
for ((path, natural, fallback), target) in others {
let binding = bind(&mut imports, &mut taken, path, &natural, &fallback);
bindings.insert(target.clone(), binding);
}
let mut qualify = |owner: &Owner| qualified(owner, &here, modules, &bindings);
let items = entries
.iter()
.map(|entry| Item {
docs: entry.docs.to_owned(),
origin: Some(contract::Origin {
path: entry.file.clone(),
item: entry.name.to_owned(),
}),
declaration: entry.declaration.qualify(&mut qualify),
})
.collect();
ContractModule {
generated_from: format!("rust module {origin}"),
imports,
items,
}
}
pub(crate) fn launcher_with_lifespan(
crate_name: &str,
functions: &[Function],
start: Option<Start>,
) -> Result<(), String> {
let arguments = std::env::args_os().skip(1).collect::<Vec<_>>();
match Command::parse(&arguments).map_err(|error| error.to_string())? {
Command::Extract {
library,
out,
depfile,
} => {
let read = std::cell::RefCell::default();
let contracts = extract_reading(crate_name, Some(&library), functions, &read)
.map_err(|error| error.to_string())?;
let contract = contract::Contract {
modules: contracts
.into_iter()
.map(|(path, module)| contract::Module {
path: path.names().map(str::to_owned).collect(),
module,
})
.collect(),
};
std::fs::write(&out, contract.bytes())
.map_err(|error| format!("{}: {error}", out.display()))?;
match depfile {
Some(depfile) => write_depfile(&depfile, read.into_inner()),
None => Ok(()),
}
}
Command::Serve { contract } => {
let contract = std::fs::read(&contract)
.map_err(|error| format!("{}: {error}", contract.display()))?;
serve(functions, &contract, start)
}
command @ (Command::Export { .. } | Command::New { .. }) => {
Err(UsageError::NotLauncher(command).to_string())
}
}
}
fn write_depfile(depfile: &Path, mut read: BTreeSet<PathBuf>) -> Result<(), String> {
let executable = std::env::current_exe()
.and_then(std::fs::canonicalize)
.map_err(|error| format!("the launcher's own path: {error}"))?;
read.insert(executable);
let mut lines = String::new();
for path in read {
let path =
std::path::absolute(&path).map_err(|error| format!("{}: {error}", path.display()))?;
match path.to_str() {
Some(line) if !line.contains('\n') => {
lines.push_str(line);
lines.push('\n');
}
_ => {
return Err(format!(
"{}: the path is not one line of UTF-8, which a depfile needs",
path.display()
));
}
}
}
std::fs::write(depfile, lines).map_err(|error| format!("{}: {error}", depfile.display()))
}
#[cfg(unix)]
fn module_of<'a>(file: &str, modules: &BTreeSet<&'a str>) -> Option<&'a str> {
let file = LibraryLayout::stem(file).unwrap_or(file);
let file = file.trim_start_matches("./");
modules
.iter()
.filter(|module| {
let Ok(path) = module.parse() else {
return false;
};
let contract = LibraryLayout::module_file(&path, Placement::Contract);
file == **module || file == contract.as_str() || file.ends_with(&format!("/{contract}"))
})
.max_by_key(|module| module.len())
.copied()
}
#[cfg(unix)]
pub(crate) fn serve(
functions: &[Function],
contract: &[u8],
start: Option<Start>,
) -> Result<(), String> {
let listing = flow_abi::read_listing(contract).map_err(|error| error.to_string())?;
let modules: BTreeSet<&str> = functions
.iter()
.map(|function| function.place.module.as_str())
.collect();
let mut declarations = Vec::new();
let mut served = BTreeSet::new();
for (identity, spec) in listing.into_iter().flat_map(|program| program.tools) {
let name = identity.name.as_str();
let candidates: Vec<&Function> = functions.iter().filter(|f| f.name == name).collect();
let function = match module_of(&identity.module, &modules) {
Some(module) => candidates
.iter()
.find(|function| function.place.module == module)
.copied(),
None if candidates.len() > 1 => {
return Err(format!(
"Tool {name} of {} names no module, and Rust functions of that name are in several",
identity.module
));
}
None => candidates.first().copied(),
}
.ok_or_else(|| format!("no Rust function implements {name}"))?;
if !served.insert((function.place.module.clone(), name.to_owned())) {
return Err(format!("ambiguous Tool {name} in contract"));
}
declarations.push(function.declare(identity, spec));
}
if served.is_empty() {
return Err("the contract file lists no Tool a Rust function implements".into());
}
run_protocol(&Server::new(declarations), start)
}
#[cfg(unix)]
fn run_protocol(server: &Server, start: Option<Start>) -> Result<(), String> {
use crate::server::{Sink, logging_to};
let protocol =
rustix::io::fcntl_dupfd_cloexec(std::io::stdout(), 3).map_err(|error| error.to_string())?;
rustix::stdio::dup2_stdout(std::io::stderr()).map_err(|error| error.to_string())?;
let sink = Sink::new(std::fs::File::from(protocol));
logging_to(&sink, || {
with_resource(start, || {
server
.run_process(std::io::stdin().lock(), &sink)
.map_err(|error| error.to_string())
})
})
}
#[cfg(not(unix))]
pub(crate) fn serve(
functions: &[Function],
contract: &[u8],
start: Option<Start>,
) -> Result<(), String> {
let _ = (functions, contract, start);
Err("Rust function-first protocol serving is currently supported only on Unix".into())
}
#[cfg(unix)]
fn chain(error: &(dyn std::error::Error + 'static)) -> String {
let mut written = error.to_string();
let mut cause = error.source();
while let Some(error) = cause {
written.push_str(": ");
written.push_str(&error.to_string());
cause = error.source();
}
written
}
#[cfg(unix)]
fn with_resource(
start: Option<Start>,
serve: impl FnOnce() -> Result<(), String>,
) -> Result<(), String> {
let lifespan = start
.map(|start| start())
.transpose()
.map_err(|error| format!("Rust resource initialization failed: {}", chain(&*error)))?;
if let Some(lifespan) = &lifespan {
let mut current = RESOURCE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if current.is_some() {
return Err("a Rust process resource is already initialized".into());
}
*current = Some(Arc::clone(&lifespan.value));
}
let result = serve();
if let Some(lifespan) = lifespan {
RESOURCE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
let closed = block_on((lifespan.close)())
.map_err(|error| format!("Rust resource cleanup failed: {}", chain(&*error)));
match (result, closed) {
(Err(run), Err(close)) => Err(format!("{run}; {close}")),
(Err(error), _) | (_, Err(error)) => Err(error),
_ => Ok(()),
}
} else {
result
}
}
pub fn block_on<F: Future>(future: F) -> F::Output {
static RUNTIME: std::sync::LazyLock<tokio::runtime::Runtime> = std::sync::LazyLock::new(|| {
#[cfg(not(target_family = "wasm"))]
let mut builder = tokio::runtime::Builder::new_multi_thread();
#[cfg(target_family = "wasm")]
let mut builder = tokio::runtime::Builder::new_current_thread();
builder.enable_all().build().expect("tool async runtime")
});
RUNTIME.block_on(future)
}
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
fn extract(
crate_name: &str,
root: Option<&Path>,
functions: &[Function],
) -> Result<BTreeMap<Segments, String>, ContractError> {
super::extract(crate_name, root, functions).map(|modules| {
modules
.into_iter()
.map(|(path, module)| (path, contract::print(&module)))
.collect()
})
}
#[test]
fn a_git_types_library_place_uses_the_nearest_library_and_the_checkout_root() {
let checkout = tempfile::TempDir::new().unwrap();
let root = checkout.path().canonicalize().unwrap();
let library = root.join("libraries/ledger");
std::fs::create_dir_all(library.join("src/models")).unwrap();
let file = library.join("src/models/types.rs");
std::fs::write(&file, "").unwrap();
let file = file.to_str().unwrap();
assert_eq!(
repository_place("src/models/types.rs"),
Vec::<String>::new()
);
assert_eq!(repository_place(file), Vec::<String>::new());
std::fs::write(library.join("flow.toml"), "[process]\ncommand = 'serve'\n").unwrap();
assert!(repository_place(file).is_empty(), "no checkout boundary");
for marker in [".git", ".cargo-ok"] {
std::fs::write(root.join(marker), "checkout marker").unwrap();
assert_eq!(repository_place(file), ["libraries", "ledger"], "{marker}");
std::fs::write(root.join("flow.toml"), "[process]\ncommand = 'outer'\n").unwrap();
assert_eq!(
repository_place(file),
["libraries", "ledger"],
"the nearest library wins"
);
std::fs::remove_file(library.join("flow.toml")).unwrap();
assert!(
repository_place(file).is_empty(),
"a library at the checkout root has no extra path"
);
std::fs::remove_file(root.join("flow.toml")).unwrap();
std::fs::remove_file(root.join(marker)).unwrap();
std::fs::write(library.join("flow.toml"), "[process]\ncommand = 'serve'\n").unwrap();
}
}
static STARTED: AtomicUsize = AtomicUsize::new(0);
static CLOSED: AtomicUsize = AtomicUsize::new(0);
#[expect(
clippy::unnecessary_wraps,
reason = "exercises the fallible lifespan factory signature"
)]
fn start_sync() -> Result<Lifespan, StartError> {
STARTED.fetch_add(1, Ordering::SeqCst);
Ok(Resource::sync(7_usize, |value| {
CLOSED.store(*value, Ordering::SeqCst);
Ok(())
})
.into_lifespan())
}
fn start_error() -> Result<Lifespan, StartError> {
Err("fixture init error".into())
}
#[expect(
clippy::unnecessary_wraps,
reason = "opening succeeds so the cleanup failure can be observed"
)]
fn close_error() -> Result<Lifespan, StartError> {
Ok(Resource::sync((), |_| Err("fixture close error".into())).into_lifespan())
}
#[test]
fn relative_imports_follow_module_paths_and_reach_the_root_from_its_parent() {
for (from, to, expected) in [
("", "models", "./models"),
("", "a/b", "./a/b"),
("a/b", "a/x", "./x"),
("a/b", "x", "../x"),
("a/c/d", "b/y", "../../b/y"),
("a/c/d", "a/c/e/f", "./e/f"),
("models", "", "../ledger"),
("a/b", "", "../../ledger"),
] {
assert_eq!(
relative_import(from, to, "ledger"),
expected,
"{from} -> {to}"
);
}
}
#[test]
fn a_contract_file_names_the_module_it_declares() {
let modules = BTreeSet::from(["", "session", "a/b"]);
for (file, expected) in [
("./ledger/contract/lib", Some("")),
("ledger/contract/lib.flow", Some("")),
("./ledger/contract/session", Some("session")),
("contract/a/b", Some("a/b")),
("session", Some("session")),
("./other/session", None),
("", Some("")),
("./ledger/contract/missing", None),
] {
assert_eq!(module_of(file, &modules), expected, "{file}");
}
assert_eq!(module_of("", &BTreeSet::from(["session"])), None);
}
#[test]
fn a_type_file_is_made_relative_to_the_library_root_however_cargo_spelled_it() {
let files = tempfile::TempDir::with_prefix("flow-library-file").unwrap();
let workspace = std::fs::canonicalize(files.path()).unwrap();
let root = workspace.join("libraries/ledger");
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("src/lib.rs"), "").unwrap();
let absolute = root.join("src/lib.rs");
assert_eq!(
library_file(Some(&root), absolute.to_str().unwrap()),
"src/lib.rs"
);
assert_eq!(library_file(Some(&root), "src/lib.rs"), "src/lib.rs");
assert_eq!(
library_file(Some(&root), "libraries/ledger/src/lib.rs"),
"src/lib.rs",
"a workspace member's file is spelled from the workspace root"
);
assert_eq!(
library_file(Some(&root), "elsewhere/x.rs"),
"elsewhere/x.rs"
);
assert_eq!(library_file(None, "src\\lib.rs"), "src/lib.rs");
}
fn rust(module: &'static str, name: &str) -> TypeRef<Owner> {
TypeRef::qualified(Owner::Rust(module), name)
}
#[test]
fn references_close_bare_in_their_module_and_through_an_import_elsewhere() {
let declaration = Declaration::Flow(FlowDeclaration {
name: "r".to_owned(),
generics: Vec::new(),
params: vec![Param {
name: "a".to_owned(),
ty: rust("ledger::models", "Refund"),
default: None,
}],
result: TypeRef::applied(
"List",
vec![TypeRef::Named {
module: Some(Owner::Rust("ledger")),
name: "Box".to_owned(),
args: vec![TypeRef::named("Int")],
}],
),
});
assert_eq!(
owners(&declaration),
[Owner::Rust("ledger::models"), Owner::Rust("ledger")]
);
let modules = BTreeMap::from([
("ledger::models", Target::Local("models".to_owned())),
("ledger", Target::Local(String::new())),
]);
let bindings = BTreeMap::from([
(Target::Local("models".to_owned()), "models".to_owned()),
(Target::Local(String::new()), "ledger".to_owned()),
]);
let written = |module: &str| {
let here = Target::Local(module.to_owned());
let item = Item {
docs: String::new(),
origin: None,
declaration: declaration
.qualify(&mut |owner| qualified(owner, &here, &modules, &bindings)),
};
contract::print_item(&item)
};
assert_eq!(
written(""),
"pub flow r(a: models.Refund) -> List<Box<Int>>\n"
);
assert_eq!(
written("models"),
"pub flow r(a: Refund) -> List<ledger.Box<Int>>\n"
);
}
fn found_in(name: &'static str, module: &'static str) -> Function {
let origin = Origin {
module,
file: "src/lib.rs",
line: 1,
};
Function::new(
name,
origin,
"",
Vec::new(),
TypeRef::named("Unit"),
Types::default(),
crate::test_contract::__flow_tool_exact().factory,
)
}
fn dependent_tree() -> tempfile::TempDir {
let files = tempfile::TempDir::with_prefix("flow-foreign-types").unwrap();
for (path, text) in [
(
"Cargo.toml",
"[workspace]\nmembers = [\"payments\"]\n[workspace.dependencies]\nledger = { git = \"https://github.com/acme/ledger.git\", tag = \"v1.2\" }\n",
),
(
"plans/Cargo.toml",
"[package]\nname = \"plans-core\"\nversion = \"0.0.0\"\n[lib]\nname = \"plans\"\n",
),
(
"Plans-Core/Cargo.toml",
"[package]\nname = \"plans-core\"\nversion = \"0.0.0\"\n",
),
(
"payments/Cargo.toml",
"[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",
),
] {
let path = files.path().join(path);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
files
}
fn reaching(
name: &'static str,
module: &str,
params: &[(&str, TypeRef<Owner>)],
result: TypeRef<Owner>,
declared: &[(&'static str, &'static str, &'static str)],
) -> Function {
let definitions = declared
.iter()
.map(|&(key, module, name)| {
let declared = Declared {
name,
module,
file: "src/lib.rs",
line: 1,
docs: "",
declaration: Declaration::Type(TypeDeclaration {
name: name.to_owned(),
params: Vec::new(),
body: TypeBody::Record(vec![Field {
docs: String::new(),
visibility: Visibility::Public,
name: "id".to_owned(),
ty: TypeRef::named("Int"),
}]),
}),
};
(key.to_owned(), declared)
})
.collect();
let types = Types {
definitions,
..Types::default()
};
let origin = Origin {
module: "payments",
file: "src/lib.rs",
line: 2,
};
let params = params
.iter()
.map(|(name, ty)| Param {
name: (*name).to_owned(),
ty: ty.clone(),
default: None,
})
.collect();
Function::new(name, origin, "", params, result, types, || {
unreachable!("extraction never serves")
})
.at(module, "src/lib.rs", 2)
}
#[test]
fn a_library_s_dependencies_are_read_from_its_cargo_toml_and_its_workspace_s() {
let files = dependent_tree();
let tree = std::fs::canonicalize(files.path()).unwrap();
let git = |url: &str, tag: Option<&str>| Dependency::Git {
url: url.to_owned(),
tag: tag.map(str::to_owned),
};
assert_eq!(
cargo_dependencies(&tree.join("payments"), &std::cell::RefCell::default()),
BTreeMap::from([
(
"ledger".to_owned(),
git("https://github.com/acme/ledger.git", Some("v1.2"))
),
("plans".to_owned(), Dependency::Path(tree.join("plans"))),
(
"plans_core".to_owned(),
Dependency::Path(tree.join("Plans-Core"))
),
("serde".to_owned(), Dependency::Registry),
(
"shared_models".to_owned(),
git("git@github.com:acme/shared", Some("v2"))
),
(
"unpinned".to_owned(),
git("https://github.com/acme/unpinned", None)
),
])
);
assert_eq!(
cargo_dependencies(&tree.join("missing"), &std::cell::RefCell::default()),
BTreeMap::new()
);
}
#[test]
fn a_package_at_its_workspace_s_root_inherits_from_its_own_manifest() {
let files = tempfile::TempDir::with_prefix("flow-workspace-root").unwrap();
let root = std::fs::canonicalize(files.path()).unwrap();
std::fs::create_dir_all(root.join("plans")).unwrap();
std::fs::write(
root.join("plans/Cargo.toml"),
"[package]\nname = \"plans\"\nversion = \"0.0.0\"\n",
)
.unwrap();
std::fs::write(
root.join("Cargo.toml"),
"[package]\nname = \"payments\"\nversion = \"0.0.0\"\n[workspace.dependencies]\nplans = { path = \"plans\" }\n[dependencies]\nplans.workspace = true\n",
)
.unwrap();
assert_eq!(
cargo_dependencies(&root, &std::cell::RefCell::default()),
BTreeMap::from([("plans".to_owned(), Dependency::Path(root.join("plans")))])
);
}
#[test]
fn an_import_name_is_made_a_flow_lowercase_name() {
for (text, expected) in [
("plans", "plans"),
("Plans-Core", "plans_core"),
("plans.v2", "plans_v2"),
("2plans", "library_2plans"),
("", "library_"),
] {
assert_eq!(lower_name(text), expected, "{text}");
}
}
#[test]
fn a_git_url_at_a_version_tag_is_a_remote_repository() {
for (url, expected) in [
(
"https://github.com/acme/plans",
Some("github.com/acme/plans@v1.2"),
),
(
"https://github.com/acme/plans.git/",
Some("github.com/acme/plans@v1.2"),
),
(
"ssh://git@github.com:22/acme/plans.git",
Some("github.com/acme/plans@v1.2"),
),
(
"git@github.com:acme/plans",
Some("github.com/acme/plans@v1.2"),
),
("plans", None),
] {
assert_eq!(remote_repository(url, "v1.2").as_deref(), expected, "{url}");
}
for (tag, flow) in [
("v1", true),
("v1.2.3", true),
("v0.10", true),
("1.2", false),
("v01", false),
("v1.2.3.4", false),
("v1-rc", false),
] {
assert_eq!(flow_tag(tag), flow, "{tag}");
}
}
#[test]
fn a_tool_name_collision_renames_a_local_module_with_suffix_as() {
let tool = reaching(
"models",
"",
&[("value", rust("payments::models", "Plan"))],
TypeRef::named("Int"),
&[("payments::models::Plan", "payments::models", "Plan")],
);
let contracts = extract("payments", None, &[tool]).unwrap();
assert!(contracts[""].contains("use \"./models\" as models_types\n"));
assert!(contracts[""].contains("pub flow models(value: models_types.Plan) -> Int\n"));
}
#[test]
fn a_type_of_another_crate_is_imported_from_its_library_and_never_declared() {
let files = dependent_tree();
let root = files.path().join("payments");
let charge = reaching(
"charge",
"",
&[
("plan", rust("plans::models", "Plan")),
("models", TypeRef::named("Int")),
],
rust("payments::models", "Plan"),
&[
("plans::models::Plan", "plans::models", "Plan"),
("payments::models::Plan", "payments::models", "Plan"),
],
);
let post = reaching(
"post",
"sub/refunds",
&[
("entry", rust("ledger", "Entry")),
("plan", rust("plans::models", "Plan")),
],
TypeRef::named("Int"),
&[
("ledger::Entry", "ledger", "Entry"),
("plans::models::Plan", "plans::models", "Plan"),
],
);
let contracts = extract("payments", Some(&root), &[charge, post]).unwrap();
assert_eq!(
contracts.keys().collect::<Vec<_>>(),
["", "models", "sub/refunds"]
);
assert_eq!(
contracts[""],
"// 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"
);
assert_eq!(
contracts["sub/refunds"],
"// 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"
);
assert_eq!(
contracts["models"],
"// 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"
);
let core = reaching(
"audit",
"",
&[("core", rust("plans_core", "Plan"))],
TypeRef::named("Int"),
&[("plans_core::Plan", "plans_core", "Plan")],
);
assert!(
extract("payments", Some(&root), &[core]).unwrap()[""]
.contains("use \"../Plans-Core\" as plans_core\n"),
);
let shared = reaching(
"share",
"",
&[("value", rust("shared_models::a", "Shared"))],
TypeRef::named("Int"),
&[("shared_models::a::Shared", "shared_models::a", "Shared")],
);
assert!(
extract("payments", Some(&root), &[shared]).unwrap()[""]
.contains("use \"github.com/acme/shared@v2/a\"\n"),
);
}
#[test]
fn a_type_of_a_crate_with_no_flow_address_is_refused() {
let files = dependent_tree();
let root = files.path().join("payments");
for (krate, module, key, how) in [
(
"serde",
"serde::x",
"serde::x::Value",
"the registry dependency serde",
),
(
"unpinned",
"unpinned::x",
"unpinned::x::Value",
"the git dependency unpinned, which names no tag such as v1.2",
),
] {
let refused = extract(
"payments",
Some(&root),
&[reaching(
"take",
"",
&[("value", rust(module, "Value"))],
TypeRef::named("Int"),
&[(key, module, "Value")],
)],
)
.unwrap_err();
assert_eq!(
refused.to_string(),
format!(
"{}: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",
root.join("src/lib.rs").display()
),
);
}
}
#[test]
fn a_git_dependency_with_a_tag_but_no_repository_address_cannot_supply_a_type() {
let files = dependent_tree();
let root = files.path().join("payments");
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();
let refused = extract(
"payments",
Some(&root),
&[reaching(
"take",
"",
&[("value", rust("ledger", "Entry"))],
TypeRef::named("Unit"),
&[("ledger::Entry", "ledger", "Entry")],
)],
)
.unwrap_err();
assert_eq!(
refused.to_string(),
format!(
"{}: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",
root.join("src/lib.rs").display()
)
);
}
#[test]
fn a_contract_places_each_tool_in_its_module_and_belongs_to_one_crate() {
let contract = contract_of(
env!("CARGO_MANIFEST_DIR"),
vec![
found_in("ping", "ledger"),
found_in("pong", "ledger::audit::log"),
],
)
.unwrap();
assert_eq!(
contract
.modules()
.keys()
.map(Segments::as_str)
.collect::<Vec<_>>(),
["", "audit/log"]
);
assert_eq!(
contract.module("audit/log"),
Some(
"// 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"
)
);
assert_eq!(
contract_of(
"",
vec![found_in("ping", "ledger"), found_in("pong", "journal::a")]
),
Err(ContractError::SeveralCrates {
first: "ledger".into(),
second: "journal".into(),
})
);
}
#[test]
fn a_rust_module_named_lib_is_refused_since_its_contract_file_is_the_roots() {
let refused = contract_of(
"",
vec![found_in("ping", "ledger"), found_in("pong", "ledger::lib")],
)
.unwrap_err();
assert!(
matches!(&refused, ContractError::Spelled { module, .. } if module == "lib"),
"{refused:?}"
);
assert!(
refused.to_string().contains("rename the Rust module"),
"{refused}"
);
}
#[test]
fn a_module_path_segment_is_a_flow_lowercase_name() {
let at = Location::new("src/x.rs".into(), 1);
assert!(check_module("a/b_2", &at).is_ok());
assert!(check_module("", &at).is_ok());
for (module, segment) in [
("Utils", "Utils"),
("a/flow", "flow"),
("a/2b", "2b"),
("a/use", "use"),
] {
assert_eq!(
check_module(module, &at),
Err(ContractError::NotAModulePath {
at: at.clone(),
module: module.into(),
segment: segment.into(),
}),
);
}
for module in ["lib", "contract", "contract/a"] {
let refused = check_module(module, &at).unwrap_err();
assert_eq!(
refused,
ContractError::Spelled {
at: at.clone(),
module: module.into(),
}
);
assert!(
refused.to_string().contains("contract/lib.flow"),
"{refused}"
);
}
assert!(check_module("a/lib", &at).is_ok());
assert!(check_module("lib/a", &at).is_ok());
assert_eq!(
library_module("ledger", "ledger::a::b").as_deref(),
Some("a/b")
);
assert_eq!(library_module("ledger", "ledger").as_deref(), Some(""));
assert_eq!(library_module("ledger", "other::a"), None);
}
#[test]
fn a_resource_cleanup_keeps_its_error_and_the_resource_shows_its_type() {
#[derive(Debug)]
struct Refused(std::io::Error);
impl std::fmt::Display for Refused {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("refused to close")
}
}
impl std::error::Error for Refused {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.0)
}
}
let resource = Resource::sync(3_u8, |_| {
Err(Refused(std::io::Error::other("still in use")).into())
});
assert_eq!(
format!("{resource:?}"),
"Resource { type: \"u8\", .. }",
"a resource shows the type it holds"
);
let lifespan = resource.into_lifespan();
assert_eq!(
format!("{lifespan:?}"),
"Lifespan { .. }",
"a lifespan hides its parts"
);
let error = block_on((lifespan.close)()).expect_err("the cleanup fails");
assert_eq!(
error.to_string(),
"refused to close",
"the author's error is kept"
);
assert_eq!(
error.source().map(ToString::to_string).as_deref(),
Some("still in use"),
"and so is its source"
);
}
#[test]
fn synchronous_resource_is_typed_shared_and_closed_even_when_serving_fails() {
let spec = crate::test_types::spec(
&crate::test_types::catalog(Vec::new()),
&[],
&[],
flow_types::Type::Unit,
);
let context = crate::Context::try_new(
"7f3a91c04be2d5e6f708192a3b4c5d6e/root#1"
.parse()
.expect("a call key"),
&spec,
None,
crate::Cancellation::default(),
)
.unwrap();
assert!(context.resource::<usize>().is_none());
let error = with_resource(Some(start_sync), || {
let first = context.resource::<usize>().unwrap();
let second = context.resource::<usize>().unwrap();
assert!(Arc::ptr_eq(&first, &second));
assert_eq!(*first, 7);
assert!(context.resource::<String>().is_none());
Err("fixture serve failed".into())
})
.unwrap_err();
assert_eq!(error, "fixture serve failed");
assert_eq!(STARTED.load(Ordering::SeqCst), 1);
assert_eq!(
CLOSED.load(Ordering::SeqCst),
7,
"the cleanup ran on the resource it opened"
);
assert!(context.resource::<usize>().is_none());
assert!(with_resource(None, || Ok(())).is_ok());
assert!(
with_resource(Some(start_error), || panic!(
"startup failure must not serve"
))
.unwrap_err()
.contains("initialization failed")
);
assert!(
with_resource(Some(close_error), || Ok(()))
.unwrap_err()
.contains("cleanup failed")
);
let error = with_resource(Some(close_error), || Err("serve failed".into())).unwrap_err();
assert!(error.contains("serve failed") && error.contains("cleanup failed"));
}
}