Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions ffi/fixtures/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2634,6 +2634,12 @@ pub fn parse_cert(text: &str) -> Result<u32, tls::held::Malformed<'_>> {
}
}

/// `parse_cert` as a future: its error borrows `text`, which the future owns, so the glue
/// makes it its message before the future ends.
pub async fn parse_later(text: &str) -> Result<u32, tls::held::Malformed<'_>> {
parse_cert(text)
}

/// Another crate's error taken back by value, which no export returns: left out.
pub fn blame(err: tls::held::Invalid) -> String {
err.to_string()
Expand Down
273 changes: 136 additions & 137 deletions ffi/fixtures/reject/expected.txt

Large diffs are not rendered by default.

9 changes: 0 additions & 9 deletions ffi/fixtures/reject/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,15 +117,6 @@ pub struct Size {
pub bytes: u64,
}

/// Another crate's error borrowing `text`, the output of a future: the glue awaits the
/// future past the call that owns `text`, so the error's borrow would outlive it.
pub async fn parse_later(text: &str) -> Result<u32, tls::held::Malformed<'_>> {
match text.is_empty() {
true => Err(tls::held::Malformed(text)),
false => Ok(text.len() as u32),
}
}

/// A waiter of another crate, which a handle holds by value.
pub fn waiter() -> tls::held::Waiter {
tls::held::Waiter::new(std::task::Waker::noop().clone())
Expand Down
29 changes: 27 additions & 2 deletions ffi/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4407,8 +4407,10 @@ impl<'tcx> Collector<'tcx> {
}
}
// A returned object's lifetimes are `'static` too, which no lent borrow may be; not a
// `Result`'s error of another crate, which crosses as its message.
let output = match sig.output().kind() {
// `Result`'s error of another crate, which crosses as its message, even a future's,
// which the glue makes its message inside the future, while what it borrows lives.
let output = self.awaited(sig.output()).unwrap_or(sig.output());
let output = match output.kind() {
ty::Adt(adt, args)
if tcx.is_diagnostic_item(sym::Result, adt.did())
&& self.opaque_value(args.type_at(1)).is_some()
Expand Down Expand Up @@ -4436,6 +4438,29 @@ impl<'tcx> Collector<'tcx> {
(statics, errs, interned)
}

/// What an `impl Future` resolves to, its lifetimes kept as the signature binds them.
fn awaited(&self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
let tcx = self.tcx;
let ty::Alias(
_,
ty::AliasTy {
kind: ty::AliasTyKind::Opaque { def_id },
args,
..
},
) = ty.kind()
else {
return None;
};
let output = tcx.lang_items().future_output()?;
let bounds = tcx.item_bounds(*def_id).skip_binder();
let term = bounds.iter().find_map(|clause| {
let p = clause.as_projection_clause()?.skip_binder();
(p.projection_term.expect_projection_def_id() == output).then_some(p.term.as_type()?)
})?;
Some(ty::EarlyBinder::bind(tcx, term).instantiate(tcx, args).skip_norm_wip())
}

/// Where a named lifetime of `def_id`'s signature is declared.
fn region_span(&self, def_id: DefId, region: ty::Region<'tcx>) -> Option<Span> {
let tcx = self.tcx;
Expand Down
22 changes: 14 additions & 8 deletions ffi/src/glue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1727,11 +1727,7 @@ impl Gen<'_> {
Some(err) => format!(
"match result {{\n\t\tOk(v) => {{\n\t\t\tlet _ = &v;\n\t\t\t{write_ok}\n\t\t\t{ready}\n\t\t}}\n\t\tErr(e) => {{\n\t\t\tunsafe {{ rt::write::<{}>(err.cast(), || {}) }};\n\t\t\t{error}\n\t\t}}\n\t}}",
rs(&self.abi.ty(err)),
match err {
// A `String` error may stand for another crate's, as its message.
Type::String => self.lower(err, "::std::string::ToString::to_string(&e)"),
err => self.lower(err, "e"),
}
self.lower(err, "e")
),
}
}
Expand Down Expand Up @@ -1972,6 +1968,12 @@ impl Gen<'_> {
(Some(own), Some(_)) => format!("{later}.await.map(|v| {own})"),
(Some(own), None) => format!("{{ let v = {later}.await; {own} }}"),
};
// A `String` error may stand for another crate's, which may borrow what the
// future owns, so it becomes its message before the future ends.
let later = match &function.err {
Some(Type::String) => format!("{later}.map_err(|e| ::std::string::ToString::to_string(&e))"),
_ => later,
};
let bind: String = Self::outs(function)
.iter()
.enumerate()
Expand Down Expand Up @@ -2035,10 +2037,14 @@ impl Gen<'_> {
self.export(format!(
"#[unsafe(no_mangle)]\npub unsafe extern \"C\" fn {name}({}) -> {ret} {{\n\tlet w = \"{name}\";\n\tlet _ = w;\n\t{body}\n\tlet result = {};{writes}\n\t{finish}\n}}\n",
params.join(", "),
match function.collect {
match (function.collect, &function.err, &function.access) {
// An iterator's items, all taken now.
true => format!("::std::iter::Iterator::collect::<::std::vec::Vec<_>>({call})"),
false => call,
(true, ..) => format!("::std::iter::Iterator::collect::<::std::vec::Vec<_>>({call})"),
// A parse's error is its message already.
(_, _, Access::Parse) => call,
// A `String` error may stand for another crate's, as its message.
(_, Some(Type::String), _) => format!("({call}).map_err(|e| ::std::string::ToString::to_string(&e))"),
_ => call,
},
));
}
Expand Down
8 changes: 8 additions & 0 deletions ffi/tests/api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -913,6 +913,14 @@ Future<void> futures() async {
check(await api.halved(3) == null, 'a future ready with None returns null');
check(await api.halved(4) == 2, 'a future ready with Some returns its value');
check(await api.cornerLater() == (1, 1), "a future's borrowed tuple returns whole");
// A future's error borrowing its argument crosses as its message, as `parseCert`'s does.
check(await api.parseLater('cert') == 4, 'a future with a borrowing error returns Ok');
try {
await api.parseLater('');
check(false, "a future's borrowing error throws");
} on api.StringException catch (e) {
check(e.error == 'malformed: ', "a future's borrowing error is its message");
}
channel.send(Uint8List(0));
try {
await channel.recvNonempty();
Expand Down
7 changes: 7 additions & 0 deletions ffi/tests/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,13 @@ async def recv():
# future polls again rather than waiting for a wake that already happened.
check(loop.run_until_complete(asyncio.wait_for(api.yielded(7), 5)) == 7, "a wake during the poll polls again")
check(loop.run_until_complete(api.corner_later()) == (1, 1), "a future's borrowed tuple returns whole")
# A future's error borrowing its argument crosses as its message, as `parse_cert`'s does.
check(loop.run_until_complete(api.parse_later("cert")) == 4, "a future with a borrowing error returns Ok")
try:
loop.run_until_complete(api.parse_later(""))
check(False, "a future's borrowing error raises")
except api.StringException as e:
check(e.error == "malformed: ", "a future's borrowing error is its message")

# Cancelled between its wake and its poll, a receive loses nothing: the payload stays
# for the next.
Expand Down
22 changes: 0 additions & 22 deletions quest/m1/ffi-export/future-error-borrow.md

This file was deleted.