diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index c33bed439..bb4557746 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -5110,3 +5110,150 @@ impl Key { ) } } + +/// A type named as Kotlin's and Dart's deprecation annotation, which the bindings' own +/// annotations must not resolve to. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Deprecated { + pub on: bool, + /// Named as the Swift record's own conversion, which its stored field must not be. + #[deprecated] + pub lower: u32, + /// Named as Dart's annotation, which its sibling's must not resolve to. + pub deprecated: bool, +} + +/// A function named as Dart's deprecation annotation, which the deprecated items after it +/// must not resolve to. +pub fn deprecated(note: u8) -> u8 { + note +} + +/// A dial, whose docs carry each rustdoc form a binding renders as its own: links to a +/// method [`Self::turn`], a field [`Dial::level`], a variant [`Error::Overflow`], a +/// function [`advance`], a constant [`LIMIT`], an object [`Counter`], a callback's method +/// [`Log::log`], [`Spawned`], which the web lacks, a method [`clash::Span::width`] and the +/// [field](field@clash::Span::width) of its name, [`Vec`], which no binding has, and +/// [a link with its own text](Self::turn). +/// +/// # Examples +/// +/// ``` +/// let dial = api::Dial::default(); +/// assert_eq!(dial.level, 0); +/// ``` +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Dial { + /// How far it is turned, below [`LIMIT`]. + pub level: u64, + /// What [`Self::level`] was before the last turn. + #[deprecated(note = "keep the [`Dial`] from before the turn")] + pub before: u64, +} + +impl Dial { + /// The dial turned `by` more. + /// + /// # Errors + /// + /// [`Error::Overflow`] past [`LIMIT`]. + /// + /// # Panics + /// + /// When `by` is zero. + #[allow(deprecated, reason = "it keeps the field it deprecates")] + pub fn turn(self, by: u64) -> Result { + assert!(by != 0, "a turn by nothing"); + match self.level.checked_add(by) { + Some(level) if level <= LIMIT => Ok(Dial { + level, + before: self.level, + }), + _ => Err(Error::Overflow), + } + } + + /// The dial turned all the way: use [`Self::turn`]. + #[deprecated(since = "0.2.0", note = "turn it by [`LIMIT`] with [`Dial::turn`]")] + pub fn max(self) -> Dial { + #[allow(deprecated, reason = "it keeps the field it deprecates")] + Dial { + level: LIMIT, + before: self.level, + } + } +} + +/// A knob, deprecated as a whole: [`Dial`] replaces it. +#[deprecated(note = "use [`Dial`], whose 'level' is \"the same\" at $0\nand past it")] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Knob { + pub level: u64, +} + +#[allow(deprecated, reason = "it is the type it deprecates")] +impl Knob { + /// Its level, twice. + pub fn doubled(&self) -> u64 { + self.level * 2 + } +} + +/// A knob behind a handle, which reaches its deprecated type's methods, deprecated too. +#[allow(deprecated, reason = "it holds the type it deprecates")] +pub struct Holder { + knob: Knob, +} + +#[allow(deprecated, reason = "it holds the type it deprecates")] +impl Holder { + /// A knob at `level`. + pub fn new(level: u64) -> Self { + Self { knob: Knob { level } } + } +} + +#[allow(deprecated, reason = "it holds the type it deprecates")] +impl std::ops::Deref for Holder { + type Target = Knob; + + fn deref(&self) -> &Knob { + &self.knob + } +} + +/// The knob of `dial`. +#[deprecated] +#[allow(deprecated, reason = "it returns the type it deprecates")] +pub fn knob(dial: Dial) -> Knob { + Knob { level: dial.level } +} + +/// The level of `dial`, from a future. +#[deprecated(note = "read its `level`")] +pub async fn level_later(dial: Dial) -> u64 { + dial.level +} + +/// What turns a [`Dial`], implemented in each binding. +pub trait Turner { + /// How far to turn. + fn by(&self) -> u64; + + /// How far to turn once. + #[deprecated(note = "turn [`Turner::by`] instead")] + fn once(&self) -> u64; +} + +/// `dial` turned as `turner` says, and once more. +#[allow(deprecated, reason = "it calls the method it deprecates")] +pub fn turned(dial: Dial, turner: impl Turner) -> Result { + dial.turn(turner.by())?.turn(turner.once()) +} + +/// The most a [`Dial`] turns, a name the web's globals take too: [`URL`] links its own. +pub const URL: u64 = LIMIT; + +/// The step a [`Dial`] turned by before [`Dial::turn`] took any, at most [`URL`]. +#[deprecated(note = "pass a step to [`Dial::turn`], whose `}` or `{` alone stays in the note")] +pub const STEP: u64 = 1; diff --git a/ffi/runtime/python.rs b/ffi/runtime/python.rs index 6142d5c02..3ee2199ab 100644 --- a/ffi/runtime/python.rs +++ b/ffi/runtime/python.rs @@ -101,6 +101,16 @@ pub fn raise(exc: *mut PyObject, msg: &str) -> R { Err(Raised) } +/// Warn of a call of a deprecated item, as `msg` says: a `DeprecationWarning` at the caller +/// `level` frames up, which raises where warnings are errors. +pub fn deprecated(msg: &CStr, level: isize) -> R<()> { + // SAFETY: the GIL is held, and the category is a static warning type. + match unsafe { PyErr_WarnEx(PyExc_DeprecationWarning, msg.as_ptr(), level) } { + 0 => Ok(()), + _ => Err(Raised), + } +} + /// Raise for a call of `what`, or a value of it crossing in, which the library's target /// lacks: the binding serves other targets, which have it. pub fn missing(what: &str) -> R { diff --git a/ffi/src/c.rs b/ffi/src/c.rs index fb612bfef..7d5ac6064 100644 --- a/ffi/src/c.rs +++ b/ffi/src/c.rs @@ -19,6 +19,10 @@ pub(crate) fn header(abi: &Abi<'_>, packages: &str) -> (String, u64, BTreeMap None, + None => Some(link(abi, l.target)), + }); // Platform independent, so a header names the same contract wherever it is generated. let mut hasher = StableHasher::new(); hasher.write(h.out.as_bytes()); @@ -184,7 +188,7 @@ impl Header<'_> { .collect(); self.line(format!( "{}typedef enum {name} {{\n{}\n}} {name};\n", - comment(&e.docs, ""), + comment(&deprecation(&e.docs, e.deprecated.as_deref()), ""), variants.join("\n") )); } @@ -241,7 +245,7 @@ impl Header<'_> { let docs = format!( "{}: implemented in C. Rust calls free once it drops the implementation, and\nmay call the others from any thread.\n\n{}", callback.path.join("::"), - callback.docs + deprecation(&callback.docs, callback.deprecated.as_deref()) ); self.line(format!( "{}typedef struct {name}_vtable {{\n{}\n}} {name}_vtable;\n\ntypedef struct {name} {{\n\tconst {name}_vtable *vtable;\n\tvoid *data;\n}} {name};\n", @@ -257,7 +261,7 @@ impl Header<'_> { }; self.line(format!( "{}#define {} {value}", - comment(&constant.docs, ""), + comment(&deprecation(&constant.docs, constant.deprecated.as_deref()), ""), abi.constant(&constant.path) )); } @@ -302,7 +306,11 @@ impl Header<'_> { } for (i, object) in api.objects.iter().enumerate() { let name = abi.object(i); - let docs = format!("{}\n\n{}", abi.api.rust(&object.path, &object.args), object.docs); + let docs = format!( + "{}\n\n{}", + abi.api.rust(&object.path, &object.args), + deprecation(&object.docs, object.deprecated.as_deref()) + ); self.line(comment(docs.trim(), "").trim_end()); self.line(format!("void {name}_free({name} *self);")); if abi.checked[i] { @@ -421,7 +429,7 @@ impl Header<'_> { if let Some(opaque) = &record.opaque { self.line(format!( "{}typedef struct {name} {{\n\t/* Its bytes, which only Rust reads: copy it, but never make or change one. */\n\t{} opaque[{}];\n}} {name};\n", - comment(&record.docs, ""), + comment(&deprecation(&record.docs, record.deprecated.as_deref()), ""), c_unit(opaque.unit()), opaque.units() )); @@ -435,11 +443,17 @@ impl Header<'_> { .fields .iter() .zip(&fields) - .map(|(f, ty)| format!("{}\t{};", comment(&f.docs, "\t"), self.decl(ty, &abi::escape(&f.name)))) + .map(|(f, ty)| { + format!( + "{}\t{};", + comment(&deprecation(&f.docs, f.deprecated.as_deref()), "\t"), + self.decl(ty, &abi::escape(&f.name)) + ) + }) .collect(); self.line(format!( "{}typedef struct {name} {{\n{}\n}} {name};\n", - comment(&record.docs, ""), + comment(&deprecation(&record.docs, record.deprecated.as_deref()), ""), decls.join("\n") )); return; @@ -517,7 +531,8 @@ impl Header<'_> { fn function(&mut self, function: &Function, owner: Option<&Ty>) { let export = self.abi.export(function, owner); crate::lock::function(&mut self.names, function, &export.call.name); - let mut docs = function.docs.clone(); + let sections = crate::doc::sections(&function.docs); + let mut docs = sections.body; // What the call moves out of the caller's handles, which are then only freed. // A handle taken by value: one taken `&mut` is not `const` either, but stays. let receiver = function.receiver.map(|r| r == Receiver::Owned); @@ -592,6 +607,13 @@ impl Header<'_> { api.named(function.on).join(", ") )); } + if let Some(errors) = §ions.errors { + docs.push_str(&format!("\n\n# Errors\n\n{errors}")); + } + if let Some(panics) = §ions.panics { + docs.push_str(&format!("\n\n# Aborts\n\n{panics}")); + } + let docs = deprecation(&docs, function.deprecated.as_deref()); self.out.push_str(&comment(docs.trim(), "")); if let Some(future) = &export.future { let handle = &future.handle; @@ -660,6 +682,49 @@ pub(crate) fn decl(abi: &Abi<'_>, ty: &Ty, name: &str) -> String { } } +/// `docs`, then the note of `deprecated`, where it has one: C's compilers would warn of the +/// C++ header's own calls, so the header only says so. +fn deprecation(docs: &str, deprecated: Option<&str>) -> String { + match deprecated { + Some("") => format!("{docs}\n\nDeprecated."), + Some(note) => format!("{docs}\n\nDeprecated: {note}"), + None => docs.to_string(), + } + .trim() + .to_string() +} + +/// The C name a link in the header's comments names for `target`. +fn link(abi: &Abi<'_>, target: crate::doc::Target<'_>) -> String { + use crate::doc::{Owner, Target}; + let api = abi.api; + let owner = |owner: Owner| match owner { + Owner::Record(i) => Ty::Struct(abi.record(i)), + Owner::Enum(i) => abi.ty(&Type::Enum(i)), + Owner::Object(i) => Ty::Handle { + name: abi.object(i), + constant: false, + }, + Owner::Callback(i) => Ty::Struct(abi.callback(i)), + }; + match target { + Target::Record(i) => abi.record(i), + Target::Enum(i) => abi.enumeration(i), + Target::Object(i) => abi.object(i), + Target::Callback(i) => abi.callback(i), + Target::Variant(i, v) => format!( + "{}_{}", + abi.enumeration(i).to_uppercase(), + abi::snake(&api.enums[i].variants[v].name).to_uppercase() + ), + Target::Field(i, n) => format!("{}.{}", abi.record(i), abi::escape(&api.records[i].fields[n].name)), + Target::Constant(c) => abi.constant(&c.path), + // A callback's method is its table's member. + Target::Function(Some(Owner::Callback(i)), f) => format!("{}_vtable.{}", abi.callback(i), f.name()), + Target::Function(of, f) => format!("{}()", abi.export(f, of.map(owner).as_ref()).call.name), + } +} + /// A C comment holding `docs`, each line indented by `indent`, or nothing for none. fn comment(docs: &str, indent: &str) -> String { if docs.is_empty() { diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index a6c54b2ee..bc232f35b 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -1598,6 +1598,119 @@ impl<'tcx> Collector<'tcx> { None } + /// `def_id`'s doc comment, in [`crate::doc`]'s canonical form. + fn docs(&self, def_id: DefId) -> String { + let tcx = self.tcx; + let module = doc_module(tcx, def_id); + // Looked up only once a link is found: rustc keeps a module's resolutions only where + // one of its items' docs links. + let mut resolutions = None; + crate::doc::canonical(&raw_docs(tcx, def_id), |path, ns| { + let map = *resolutions.get_or_insert_with(|| match module.as_local() { + Some(local) => tcx + .resolutions(()) + .doc_link_resolutions + .get(&rustc_hir::def_id::LocalModId::new_unchecked(local)), + None => Some(tcx.doc_link_resolutions(rustc_hir::def_id::ModId::new_unchecked(module))), + }); + self.link(def_id, map?, path, ns) + }) + } + + /// The path in the IR of what a link of `def_id`'s doc comment names, by its path as + /// rustc's resolver caches it, in `map`, the resolutions of its module: an item, or a + /// member of a type, as `Self::abort` or `Error::Timeout` names one. + fn link( + &self, + def_id: DefId, + map: &rustc_middle::middle::resolve::DocLinkResMap, + path: &str, + ns: Option, + ) -> Option { + use rustc_hir::def::Namespace; + let tcx = self.tcx; + let namespaces: Vec = match ns { + Some(crate::doc::Ns::Type) => vec![Namespace::TypeNS], + Some(crate::doc::Ns::Value | crate::doc::Ns::Field) => vec![Namespace::ValueNS, Namespace::TypeNS], + Some(crate::doc::Ns::Macro) => return None, + None => vec![Namespace::TypeNS, Namespace::ValueNS], + }; + let resolved = |path: &str, ns: Namespace| match map.get(&(rustc_span::Symbol::intern(path), ns)) { + Some(Some(Res::Def(_, did))) => Some(*did), + _ => None, + }; + let (base, rest) = match path.split_once("::") { + _ if path == "Self" => (doc_self(tcx, def_id)?, ""), + Some(("Self", rest)) => (doc_self(tcx, def_id)?, rest), + _ => match namespaces.iter().find_map(|&ns| resolved(path, ns)) { + Some(did) => (did, ""), + // A member of a type, which rustc resolves the type of alone. + None => { + let (ty, member) = path.rsplit_once("::")?; + (resolved(ty, Namespace::TypeNS)?, member) + } + }, + }; + let mut out = self.item_path(base)?; + // A member is a field where `field@` says so, or where the type has no associated + // item of its name, which rustdoc looks for first. + let field = |member: &str| { + let adt = matches!(tcx.def_kind(base), DefKind::Struct | DefKind::Union); + let has = |name: &str| adt && tcx.adt_def(base).all_fields().any(|f| f.name.as_str() == name); + let associated = (tcx.inherent_impls(base).iter()).any(|&i| { + tcx.associated_item_def_ids(i) + .iter() + .any(|&a| tcx.item_name(a).as_str() == member) + }); + has(member) && (ns == Some(crate::doc::Ns::Field) || !associated) + }; + match rest { + "" => {} + member if !member.contains("::") && field(member) => out.push(format!("field@{member}")), + rest => out.extend(rest.split("::").map(String::from)), + } + Some(out.join("::")) + } + + /// The path in the IR of `def_id`, an item the walk met or a member of one. + fn item_path(&self, def_id: DefId) -> Option> { + let tcx = self.tcx; + if let Some((_, path)) = self.items.iter().find(|(item, _)| *item == def_id) { + return Some(path.clone()); + } + let owner = match tcx.def_kind(def_id) { + DefKind::Ctor(..) => return self.item_path(tcx.parent(def_id)), + DefKind::Variant | DefKind::Field | DefKind::AssocFn | DefKind::AssocConst => doc_self(tcx, def_id)?, + _ => return None, + }; + let mut path = self.item_path(owner)?; + let name = tcx.item_name(def_id); + // A field apart from a method of its name, as `doc::field` keys it. + path.push(match tcx.def_kind(def_id) { + DefKind::Field => format!("field@{name}"), + _ => name.to_string(), + }); + Some(path) + } + + /// `def_id`'s `#[deprecated]` note, if it is deprecated: its own, or an enclosing + /// module's, but not its type's, whose own deprecation covers its members. + fn deprecated(&self, def_id: DefId) -> Option { + let tcx = self.tcx; + let deprecation = tcx.lookup_deprecation(def_id).filter(|d| d.is_in_effect())?; + let owner = doc_self(tcx, def_id).filter(|&owner| owner != def_id); + if owner.and_then(|owner| tcx.lookup_deprecation(owner)).is_some_and(|of| { + format!("{:?}", (of.since, of.note)) == format!("{:?}", (deprecation.since, deprecation.note)) + }) { + return None; + } + Some( + deprecation + .note + .map_or_else(String::new, |note| crate::doc::plain(note.as_str())), + ) + } + /// Decide how each type and trait is exported, before any signature names one. fn declare(&mut self) { let tcx = self.tcx; @@ -1644,7 +1757,8 @@ impl<'tcx> Collector<'tcx> { // Number each kind in item order, with placeholders filled in by `define`. for (def_id, path) in self.items.clone() { let span = tcx.def_span(def_id); - let docs = docs(tcx, def_id); + let docs = self.docs(def_id); + let deprecated = self.deprecated(def_id); let home = self.home(def_id); for site in self.sites(def_id, &path) { let Some(decl) = self.decls.get_mut(&site.key) else { @@ -1663,6 +1777,7 @@ impl<'tcx> Collector<'tcx> { span, on: On::ALL, docs, + deprecated: deprecated.clone(), fields: Vec::new(), tuple: false, methods: Vec::new(), @@ -1681,6 +1796,7 @@ impl<'tcx> Collector<'tcx> { span, on: On::ALL, docs, + deprecated: deprecated.clone(), variants: Vec::new(), exhaustive: true, methods: Vec::new(), @@ -1701,6 +1817,7 @@ impl<'tcx> Collector<'tcx> { span, on: On::ALL, docs, + deprecated: deprecated.clone(), fields: Vec::new(), tuple: false, methods: Vec::new(), @@ -1725,6 +1842,7 @@ impl<'tcx> Collector<'tcx> { span, on: On::ALL, docs, + deprecated: deprecated.clone(), sync, send, copy, @@ -1745,6 +1863,7 @@ impl<'tcx> Collector<'tcx> { span, on: On::ALL, docs, + deprecated: deprecated.clone(), methods: Vec::new(), }); } @@ -1771,6 +1890,7 @@ impl<'tcx> Collector<'tcx> { span: object.span, on: object.on, docs: object.docs, + deprecated: object.deprecated, fields: Vec::new(), tuple: false, methods: object.methods, @@ -1801,6 +1921,7 @@ impl<'tcx> Collector<'tcx> { span: tcx.def_span(def_id), on: On::ALL, docs: "`tracing::Level`: how verbose a span or event is, from the most to the least.".to_string(), + deprecated: None, variants: (variants.iter().zip(0..)) .map(|(name, discriminant)| Variant { name: name.to_string(), @@ -1870,6 +1991,7 @@ impl<'tcx> Collector<'tcx> { span, on: On::ALL, docs, + deprecated: self.deprecated(def_id), sync: true, send: true, copy: false, @@ -1911,6 +2033,7 @@ impl<'tcx> Collector<'tcx> { span, on: On::ALL, docs: docs.to_string(), + deprecated: None, receiver: None, params: vec![Param { name: "input".to_string(), @@ -1971,6 +2094,7 @@ impl<'tcx> Collector<'tcx> { span, on: On::ALL, docs: "The document as JSON text.".to_string(), + deprecated: None, receiver: Some(Receiver::Ref), params: Vec::new(), units: Vec::new(), @@ -2011,6 +2135,7 @@ impl<'tcx> Collector<'tcx> { span, on: On::ALL, docs: docs.to_string(), + deprecated: None, sync: true, send: true, copy: implements(tcx, self_ty, def_id, sym::Copy), @@ -2297,7 +2422,8 @@ impl<'tcx> Collector<'tcx> { match self.ty(ty, Pos::Field) { Ok(ty) => fields.push(Field { name: field.name.to_string(), - docs: docs(tcx, field.did), + docs: self.docs(field.did), + deprecated: self.deprecated(field.did), ty, }), Err(why) => errs.push(why), @@ -2568,7 +2694,16 @@ impl<'tcx> Collector<'tcx> { }; let mut all = Vec::new(); for (key, ty, derefs, mutable) in chain { - let members = match key.and_then(|key| self.decls.get(&key).cloned()) { + let decl = key.and_then(|key| self.decls.get(&key).cloned()); + // A member of a deprecated type leaves its type's deprecation to the type, which + // the object reaching it does not carry: the member takes it on. + let inherited = match decl { + Some(Decl::Object(u)) => self.api.objects[u].deprecated.clone(), + Some(Decl::Value(u) | Decl::Record(u)) => self.api.records[u].deprecated.clone(), + Some(Decl::Enum(u)) => self.api.enums[u].deprecated.clone(), + _ => None, + }; + let members = match decl { Some(Decl::Object(u)) => self.api.objects[u].methods.clone(), Some(Decl::Value(u)) => self.api.records[u].methods.clone(), // A record's fields cross with it, so reaching them through the object takes @@ -2602,6 +2737,7 @@ impl<'tcx> Collector<'tcx> { m.path = [&path[..], &[name(&m.path)]].concat(); m.shown = [&shown[..], &[name(&m.shown)]].concat(); m.derefs = derefs; + m.deprecated = m.deprecated.or_else(|| inherited.clone()); m }) .collect(); @@ -2843,7 +2979,8 @@ impl<'tcx> Collector<'tcx> { shown: shown.clone(), span, on: On::ALL, - docs: docs(tcx, field.did), + docs: self.docs(field.did), + deprecated: self.deprecated(field.did), receiver: Some(receiver), params, units: Vec::new(), @@ -3859,15 +3996,15 @@ impl<'tcx> Collector<'tcx> { None => None, }; // What interning costs, which the caller cannot see from the parameter's type. - let mut docs = docs(tcx, def_id); + let mut docs = self.docs(def_id); for param in params.iter().filter(|p| p.interned) { - if !docs.is_empty() { - docs.push_str("\n\n"); - } - docs.push_str(&format!( - "`{}` must live as long as the program, so each distinct value passed is copied once and never freed: memory grows with each distinct value.", - param.name - )); + docs = crate::doc::note( + &docs, + &format!( + "`{}` must live as long as the program, so each distinct value passed is copied once and never freed: memory grows with each distinct value.", + param.name + ), + ); } match (errs.is_empty(), ok) { (true, Some(ok)) => Ok(Function { @@ -3876,6 +4013,7 @@ impl<'tcx> Collector<'tcx> { span: tcx.def_span(def_id), on: On::ALL, docs, + deprecated: self.deprecated(def_id), receiver, params, units, @@ -5729,7 +5867,8 @@ impl<'tcx> Collector<'tcx> { home, span, on: On::ALL, - docs: docs(tcx, def_id), + docs: self.docs(def_id), + deprecated: self.deprecated(def_id), value, }); return None; @@ -5749,7 +5888,8 @@ impl<'tcx> Collector<'tcx> { shown: path, span, on: On::ALL, - docs: docs(tcx, def_id), + docs: self.docs(def_id), + deprecated: self.deprecated(def_id), receiver: None, params: Vec::new(), units: Vec::new(), @@ -6571,7 +6711,7 @@ fn signed<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, bits: u128) -> i128 { } /// An item's doc comment, each line as written after `///`. -fn docs(tcx: TyCtxt<'_>, def_id: DefId) -> String { +fn raw_docs(tcx: TyCtxt<'_>, def_id: DefId) -> String { #[expect(deprecated, reason = "doc comments are no parsed attribute to find")] let attrs = tcx.get_all_attrs(def_id); let lines: Vec = attrs @@ -6587,6 +6727,32 @@ fn docs(tcx: TyCtxt<'_>, def_id: DefId) -> String { lines.join("\n").trim().to_string() } +/// The module whose scope an item's doc comment resolves its links in. +fn doc_module(tcx: TyCtxt<'_>, mut def_id: DefId) -> DefId { + while tcx.def_kind(def_id) != DefKind::Mod { + def_id = tcx.parent(def_id); + } + def_id +} + +/// What `Self` names in an item's doc comment: the type it is or belongs to. +fn doc_self(tcx: TyCtxt<'_>, def_id: DefId) -> Option { + match tcx.def_kind(def_id) { + DefKind::Struct | DefKind::Enum | DefKind::Union | DefKind::Trait | DefKind::TyAlias => Some(def_id), + DefKind::Field | DefKind::Variant | DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy => { + let parent = tcx.parent(def_id); + match tcx.def_kind(parent) { + DefKind::Impl { .. } => match tcx.type_of(parent).instantiate_identity().skip_norm_wip().kind() { + ty::Adt(adt, _) => Some(adt.did()), + _ => None, + }, + _ => doc_self(tcx, parent), + } + } + _ => None, + } +} + /// Whether `tr` is `Send`, `Sync`, or `Sized`, which a foreign implementation or a lent /// closure meets. /// Whether `implied`, bounds with each they imply, makes `param` outlive the call, so it diff --git a/ffi/src/cpp.rs b/ffi/src/cpp.rs index ec18dd1e1..083357587 100644 --- a/ffi/src/cpp.rs +++ b/ffi/src/cpp.rs @@ -25,6 +25,7 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::abi::{self, Abi, Ty}; use crate::c::decl; +use crate::doc; use crate::ir::{Closure, Family, Function, Int, Literal, Receiver, Traits, Type}; const RUNTIME: &str = include_str!("../runtime/rt.hpp"); @@ -78,6 +79,22 @@ pub(crate) fn headers(abi: &Abi<'_>, packages: &str) -> Result { } umbrella.push_str(&format!("\n#endif // {guard}\n")); headers.insert(0, (format!("{p}.hpp"), umbrella)); + // Each link once every name is final, and the headers' own uses of what they deprecate + // kept from warning, which a consumer's still do. + let deprecates = headers.iter().any(|(_, text)| text.contains("[[deprecated")); + for (_, text) in &mut headers { + let render = |link: &doc::Link<'_>| { + let target = h.link(link.target)?; + Some(match link.text { + Some(text) => format!("@ref {} \"{text}\"", target.trim_end_matches("()")), + None => target, + }) + }; + *text = doc::links(text, api, render); + if deprecates { + *text = quiet(text); + } + } match h.errors.is_empty() { true => Ok(Output { files: headers, @@ -630,8 +647,9 @@ impl<'a> Header<'a> { } let alias = self.global(&self.name(&name)); self.line(format!( - "{}using {alias} = ::std::variant<{}>;", + "{}using {alias}{} = ::std::variant<{}>;", docs(&e.docs, ""), + suffixed(e.deprecated.as_deref()), payloads.join(", ") )); } @@ -692,8 +710,9 @@ impl<'a> Header<'a> { .map(|v| format!("\t{} = {},", escape(&abi::snake(&v.name)), v.discriminant)) .collect(); self.line(format!( - "{}enum class {name} {{\n{}\n}};\n", + "{}enum class{} {name} {{\n{}\n}};\n", docs(&e.docs, ""), + suffixed(e.deprecated.as_deref()), variants.join("\n") )); } @@ -708,8 +727,9 @@ impl<'a> Header<'a> { self.locked .insert(format!("const {}", constant.path.join("::")), name.clone()); self.line(format!( - "{}inline constexpr {ty} {name} = {};", + "{}{}inline constexpr {ty} {name} = {};", docs(&constant.docs, ""), + prefixed(constant.deprecated.as_deref()), abi.constant(&constant.path) )); } @@ -997,8 +1017,9 @@ impl<'a> Header<'a> { } self.distinct(&name, &abi.api.rust(&object.path, &object.args), &members); self.line(format!( - "{}class RUST2_FFI_CONSUMABLE {name} {{\n{}\n}};\n", + "{}class{} RUST2_FFI_CONSUMABLE {name} {{\n{}\n}};\n", docs(text.trim(), ""), + suffixed(object.deprecated.as_deref()), body.join("\n") )); } @@ -1097,8 +1118,9 @@ impl<'a> Header<'a> { .map(|p| declare(&self.lent(&p.ty), &escape(&p.name))) .collect(); body.push(format!( - "{}\tvirtual {} {member}({}){constant} = 0;", - docs(&method.docs, "\t"), + "{}\t{}virtual {} {member}({}){constant} = 0;", + docs(&self.function_docs(method, doc::sections(&method.docs).body), "\t"), + prefixed(method.deprecated.as_deref()), self.owned(&method.ok), params.join(", ") )); @@ -1135,8 +1157,9 @@ impl<'a> Header<'a> { } self.distinct(&name, &callback.path.join("::"), &members); self.line(format!( - "{}class {name} {{\n{}\n}};\n", + "{}class{} {name} {{\n{}\n}};\n", docs(text.trim(), ""), + suffixed(callback.deprecated.as_deref()), body.join("\n") )); self.def(format!( @@ -1185,7 +1208,15 @@ impl<'a> Header<'a> { .fields .iter() .zip(&fields) - .map(|(f, field)| format!("{}\t{} {field}{};", docs(&f.docs, "\t"), self.owned(&f.ty), init(&f.ty))) + .map(|(f, field)| { + format!( + "{}\t{}{} {field}{};", + docs(&f.docs, "\t"), + prefixed(f.deprecated.as_deref()), + self.owned(&f.ty), + init(&f.ty) + ) + }) .collect(); body.push(String::new()); let mut members = fields.clone(); @@ -1232,15 +1263,17 @@ impl<'a> Header<'a> { record.docs ); self.line(format!( - "{}class {name} {{\npublic:\n{}\n\nprivate:\n\tfriend struct {d}::access;\n\n\texplicit {name}(const ::{c} &c) noexcept : c_(c) {{}}\n\n\t::{c} c_;\n}};\n", + "{}class{} {name} {{\npublic:\n{}\n\nprivate:\n\tfriend struct {d}::access;\n\n\texplicit {name}(const ::{c} &c) noexcept : c_(c) {{}}\n\n\t::{c} c_;\n}};\n", docs(text.trim(), ""), + suffixed(record.deprecated.as_deref()), body.join("\n"), d = self.d() )); } None => self.line(format!( - "{}struct {name} {{\n{}\n}};\n", + "{}struct{} {name} {{\n{}\n}};\n", docs(&record.docs, ""), + suffixed(record.deprecated.as_deref()), body.join("\n") )), } @@ -1478,6 +1511,64 @@ impl<'a> Header<'a> { (declared, ok, err) } + /// `text`, a function's docs without its sections, then its `# Errors`, naming the + /// error its `result` holds, and its `# Panics` as when it aborts. + fn function_docs(&mut self, function: &Function, text: String) -> String { + let sections = doc::sections(&function.docs); + let mut text = text.trim().to_string(); + if let Some(errors) = §ions.errors { + let what = match &function.err { + Some(err) => format!("Its `result` holds a `{}` error: ", self.owned(err)), + None => String::new(), + }; + text.push_str(&format!("\n\n# Errors\n\n{what}{errors}")); + } + if let Some(panics) = §ions.panics { + text.push_str(&format!("\n\n# Aborts\n\n{panics}")); + } + text.trim().to_string() + } + + /// What Doxygen links for `target`, if C++ has it. + fn link(&self, target: doc::Target<'_>) -> Option { + let abi = self.abi; + let ns = &self.ns; + let owner = |owner: doc::Owner| match owner { + doc::Owner::Record(i) => self.name(&abi.record(i)), + doc::Owner::Enum(i) => self.name(&abi.enumeration(i)), + doc::Owner::Object(i) => self.name(&abi.object(i)), + doc::Owner::Callback(i) => self.name(&abi.callback(i)), + }; + Some(match target { + doc::Target::Record(i) => format!("{ns}::{}", owner(doc::Owner::Record(i))), + doc::Target::Enum(i) => format!("{ns}::{}", owner(doc::Owner::Enum(i))), + doc::Target::Object(i) => format!("{ns}::{}", owner(doc::Owner::Object(i))), + doc::Target::Callback(i) => format!("{ns}::{}", owner(doc::Owner::Callback(i))), + doc::Target::Variant(i, v) => { + let e = &abi.api.enums[i]; + let variant = &e.variants[v].name; + match e.plain() { + true => format!("{ns}::{}::{}", owner(doc::Owner::Enum(i)), escape(&abi::snake(variant))), + false => format!("{ns}::{}", self.name(&abi::payload(&abi.enumeration(i), variant))), + } + } + doc::Target::Field(i, n) => format!( + "{ns}::{}::{}", + owner(doc::Owner::Record(i)), + escape(&abi.api.records[i].fields[n].name) + ), + doc::Target::Constant(c) => format!("{ns}::{}", self.locked.get(&format!("const {}", c.path.join("::")))?), + doc::Target::Function(of, f) => { + let member = self.locked.get(&crate::lock::function_key(f))?; + match of { + // An enum's methods are free functions. + Some(doc::Owner::Enum(_)) | None => format!("{ns}::{member}()"), + Some(of) => format!("{ns}::{}::{member}()", owner(of)), + } + } + }) + } + /// `function`'s declaration in its class, and its member name, with its definition /// among the definitions; or as a free function if it has no class. fn function( @@ -1714,15 +1805,7 @@ impl<'a> Header<'a> { true => String::new(), false => format!("template <{}>\n", templates.join(", ")), }; - // Defined in the header of the crate it belongs to, which may follow its class's. - if function.home.krate == self.krate { - self.def(format!( - "{template}inline {ret} {scope}{member}({}){qualifier} {{\n\t{}\n}}\n", - params.join(", "), - body.join("\n\t") - )); - } - let mut text = function.docs.clone(); + let mut text = doc::sections(&function.docs).body; for (param, name) in function.params.iter().zip(&names) { if let Type::Future = param.ty { text.push_str(&format!( @@ -1756,6 +1839,24 @@ impl<'a> Header<'a> { } } } + let text = self.function_docs(function, text); + // Defined in the header of the crate it belongs to, which may follow its class's; + // a free function's definition is its declaration, which carries its docs. + if function.home.krate == self.krate { + let docs = match scope.is_empty() { + true => format!( + "{}{template}{}", + docs(&text, ""), + prefixed(function.deprecated.as_deref()) + ), + false => template.clone(), + }; + self.def(format!( + "{docs}inline {ret} {scope}{member}({}){qualifier} {{\n\t{}\n}}\n", + params.join(", "), + body.join("\n\t") + )); + } // An object's method is callable only before a move empties it, and one taking // `self` empties it. let prefix = match (is_static, free, owner) { @@ -1765,9 +1866,10 @@ impl<'a> Header<'a> { _ => "", }; let declaration = format!( - "{}\t{}{prefix}{ret} {member}({}){qualifier};", - docs(text.trim(), "\t"), + "{}\t{}{}{prefix}{ret} {member}({}){qualifier};", + docs(&text, "\t"), template.replace('\n', "\n\t"), + prefixed(function.deprecated.as_deref()), params.join(", ") ); (declaration, member) @@ -2035,6 +2137,68 @@ fn init(ty: &Type) -> &'static str { } } +/// `header` with no warning of a use of a deprecated item between its include guard's +/// lines: the generated code's own uses, which a consumer's are not. +fn quiet(header: &str) -> String { + const PUSH: &str = "#if defined(__GNUC__) || defined(__clang__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#elif defined(_MSC_VER)\n#pragma warning(push)\n#pragma warning(disable : 4996)\n#endif\n"; + const POP: &str = "#if defined(__GNUC__) || defined(__clang__)\n#pragma GCC diagnostic pop\n#elif defined(_MSC_VER)\n#pragma warning(pop)\n#endif\n"; + let (Some(start), Some(end)) = (header.find("\n#define "), header.rfind("\n#endif")) else { + return header.to_string(); + }; + let start = start + header[start + 1..].find('\n').map_or(0, |n| n + 1) + 1; + format!( + "{}{PUSH}{}{POP}{}", + &header[..start], + &header[start..end + 1], + &header[end + 1..] + ) +} + +/// `[[deprecated]]` with `deprecated`'s note, where it has one. +fn attribute(deprecated: Option<&str>) -> String { + match deprecated { + Some("") => "[[deprecated]]".to_string(), + Some(note) => format!("[[deprecated({})]]", cpp_string(note)), + None => String::new(), + } +} + +/// A C++ string literal of `text`, its control characters in octal, which ends after +/// three digits where a hex escape would take the next character as its own. +fn cpp_string(text: &str) -> String { + let mut out = String::from("\""); + for c in text.chars() { + match c { + '"' | '\\' => { + out.push('\\'); + out.push(c); + } + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + c if c.is_ascii_control() => out.push_str(&format!("\\{:03o}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +/// [`attribute`] before a declaration, which a space then follows. +fn prefixed(deprecated: Option<&str>) -> String { + match deprecated { + Some(_) => format!("{} ", attribute(deprecated)), + None => String::new(), + } +} + +/// [`attribute`] after a class's or alias's key word or name, which a space then precedes. +fn suffixed(deprecated: Option<&str>) -> String { + match deprecated { + Some(_) => format!(" {}", attribute(deprecated)), + None => String::new(), + } +} + /// C++ comments holding `docs`, each line indented by `indent`, or nothing for none. A line /// ending in a backslash, as a string continued in clap's examples does, would continue a /// `///` comment onto the next line, so such docs are a block comment instead. diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 2b2f992a8..81674956e 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -26,6 +26,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fmt::Write; use crate::abi::{self, Abi, Sig, Ty, pascal}; +use crate::doc; use crate::glue::rs; use crate::ir::{Access, Closure, Family, Function, Int, Literal, On, Type}; use crate::kotlin::strip_refs; @@ -114,7 +115,7 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result, packages: &str, contract: u64) -> Result| match link.text { + Some(_) => None, + None => g.link(link.target).map(|target| format!("[{target}]")), + }; + dart.push_str(&doc::links(&g.types, abi.api, render)); + dart.push_str(&doc::links(&g.top, abi.api, render)); for code in g.helpers.values() { dart.push_str(code); } @@ -343,6 +349,7 @@ const TAKEN: &[&str] = &[ "Cancelable", "Cancelled", "Comparable", + "Deprecated", "Duration", "Exception", "Expando", @@ -1430,7 +1437,11 @@ impl<'a> Gen<'a> { Literal::Int(Int::U64 | Int::Usize, v) => format!("U64.fromBits({})", int_literal(v)), Literal::Int(_, v) => int_literal(v), }; - let _ = write!(self.top, "{}const {name} = {value};\n\n", docs(&constant.docs, "")); + let _ = write!( + self.top, + "{}const {name} = {value};\n\n", + docs(&constant.docs, constant.deprecated.as_deref(), "") + ); } for i in 0..api.records.len() { self.record(i); @@ -1751,7 +1762,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}final class {name} {{\n{}}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), record.deprecated.as_deref(), ""), body.join("\n") ); return; @@ -1761,7 +1772,7 @@ impl<'a> Gen<'a> { .collect(); let mut members: Vec = fields.iter().map(|(f, _)| f.clone()).collect(); let mut body: Vec = (record.fields.iter().zip(&fields)) - .map(|(f, (name, dt))| format!("{}\tfinal {dt} {name};\n", docs(&f.docs, "\t"))) + .map(|(f, (name, dt))| format!("{}\tfinal {dt} {name};\n", docs(&f.docs, f.deprecated.as_deref(), "\t"))) .collect(); let params: Vec = match record.tuple { true => fields.iter().map(|(f, _)| format!("this.{f}")).collect(), @@ -1780,7 +1791,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}final class {name} {{\n{}}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), record.deprecated.as_deref(), ""), body.join("\n") ); } @@ -1838,7 +1849,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}enum {name} {{\n{}}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), e.deprecated.as_deref(), ""), body.join("\n") ); return; @@ -1851,7 +1862,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}sealed class {name} {{\n{}}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), e.deprecated.as_deref(), ""), body.join("\n") ); for (k, variant) in e.variants.iter().enumerate() { @@ -1923,7 +1934,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}final class {name} extends _Object {{\n{}}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), object.deprecated.as_deref(), ""), body.join("\n") ); } @@ -1950,7 +1961,11 @@ impl<'a> Gen<'a> { .collect(); body.push(format!( "{}\t{} {member}({});", - docs(&method.docs, "\t"), + docs( + &self.function_docs(method, doc::sections(&method.docs).body), + method.deprecated.as_deref(), + "\t" + ), self.dt(&method.ok), params.join(", ") )); @@ -2013,7 +2028,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}abstract class {name} {{\n{}\n}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), callback.deprecated.as_deref(), ""), body.join("\n\n") ); } @@ -2560,7 +2575,7 @@ impl<'a> Gen<'a> { } } - let mut text = function.docs.clone(); + let mut text = doc::sections(&function.docs).body; if handed.is_some() { text.push_str( "\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes.", @@ -2649,7 +2664,11 @@ impl<'a> Gen<'a> { }; crate::lock::function(&mut self.locked, function, &member); - let code = format!("{}{head} {{\n{code_body}\n}}\n", docs(text.trim(), "")); + let text = self.function_docs(function, text); + let code = format!( + "{}{head} {{\n{code_body}\n}}\n", + docs(&text, function.deprecated.as_deref(), "") + ); Some((code, member)) } @@ -2703,6 +2722,77 @@ impl<'a> Gen<'a> { } } + /// `text`, a function's docs without its sections, then its `# Errors` as what it + /// throws, and its `# Panics` as when it aborts. + fn function_docs(&mut self, function: &Function, text: String) -> String { + let sections = doc::sections(&function.docs); + let mut text = text.trim().to_string(); + match (§ions.errors, &function.err) { + (Some(errors), Some(err)) => { + let thrown = match self.thrown(err) { + Thrown::Itself => self.dt(err), + Thrown::Wrapped(name) => name, + }; + let _ = write!(text, "\n\nThrows [{thrown}]: {errors}"); + } + (Some(errors), None) => { + let _ = write!(text, "\n\n# Errors\n\n{errors}"); + } + (None, _) => {} + } + if let Some(panics) = §ions.panics { + let _ = write!(text, "\n\n# Aborts\n\n{panics}"); + } + text.trim().to_string() + } + + /// What a dartdoc link names for `target`, if Dart has it. + fn link(&self, target: doc::Target<'_>) -> Option { + let abi = self.abi; + let owner = |owner: doc::Owner| match owner { + doc::Owner::Record(i) => self.class(&abi.record(i)), + doc::Owner::Enum(i) => self.class(&abi.enumeration(i)), + doc::Owner::Object(i) => self.class(&abi.object(i)), + doc::Owner::Callback(i) => self.class(&abi.callback(i)), + }; + Some(match target { + doc::Target::Record(i) => owner(doc::Owner::Record(i)), + doc::Target::Enum(i) => owner(doc::Owner::Enum(i)), + doc::Target::Object(i) => owner(doc::Owner::Object(i)), + doc::Target::Callback(i) => owner(doc::Owner::Callback(i)), + doc::Target::Variant(i, v) => { + let e = &abi.api.enums[i]; + let name = owner(doc::Owner::Enum(i)); + match e.plain() { + true => format!("{name}.{}", enum_value(&e.variants[v].name)), + false => self.variant_class(&name, &e.variants[v].name), + } + } + doc::Target::Field(i, n) => format!( + "{}.{}", + owner(doc::Owner::Record(i)), + field_name(&abi.api.records[i].fields[n].name) + ), + doc::Target::Constant(c) => self.locked.get(&format!("const {}", c.path.join("::")))?.clone(), + doc::Target::Function(of, f) => { + // The lock holds a member as its type declares it: `static `, or `new + // ` for a constructor, unnamed where the name is empty, which dartdoc + // links as `new`. + let member = self.locked.get(&crate::lock::function_key(f))?; + let member = member.strip_prefix("static ").unwrap_or(member); + let member = match member.strip_prefix("new ") { + Some("") => "new", + Some(named) => named, + None => member, + }; + match of { + Some(of) => format!("{}.{member}", owner(of)), + None => member.to_string(), + } + } + }) + } + /// How an error of type `err` is thrown: as itself if an exported type, which then /// implements `Exception`, or else in an exception of its own. fn thrown(&mut self, err: &Type) -> Thrown { @@ -2888,14 +2978,41 @@ fn collides(a: &str, b: &str) -> bool { a == b && a_spaces.iter().any(|space| b_spaces.contains(space)) } -/// Dart doc comments holding `docs`, each line indented by `indent`, or nothing for none. -fn docs(docs: &str, indent: &str) -> String { - docs.lines() +/// Dart doc comments holding `docs`, each line indented by `indent`, or nothing for none, +/// and `@Deprecated` with its note where `deprecated` has one. +fn docs(docs: &str, deprecated: Option<&str>, indent: &str) -> String { + let mut out: String = docs + .lines() .map(|line| match line.is_empty() { true => format!("{indent}///\n"), false => format!("{indent}/// {line}\n"), }) - .collect() + .collect(); + // Never `@deprecated`, which says "next release" and a member named `deprecated` hides. + if let Some(note) = deprecated { + let _ = writeln!(out, "{indent}@Deprecated({})", dart_string(note)); + } + out +} + +/// A Dart string literal of `text`. +fn dart_string(text: &str) -> String { + let mut out = String::from("'"); + for c in text.chars() { + match c { + '\'' | '\\' | '$' => { + out.push('\\'); + out.push(c); + } + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if c.is_control() => out.push_str(&format!("\\u{{{:x}}}", c as u32)), + c => out.push(c), + } + } + out.push('\''); + out } /// Code indented by one tab more, but for blank lines. diff --git a/ffi/src/doc.rs b/ffi/src/doc.rs new file mode 100644 index 000000000..c6283aea2 --- /dev/null +++ b/ffi/src/doc.rs @@ -0,0 +1,634 @@ +//! Rustdoc carried into every binding. +//! +//! Collection writes each doc comment in a canonical Markdown form, with no Rust code +//! example, since no binding runs one, and each intra-doc link rustc resolved to an item +//! the export may hold written `[label](rust2:)`, by the item's path in the IR: the +//! language links its own name for it, or keeps `label` where it has none. A link written +//! with text of its own, such as `[the abort](Self::abort)`, is `rust2-text:` instead, and +//! keeps that text. A link rustc could not resolve, or that names no item, keeps its label. +//! +//! Each generator writes the Markdown into its comments as they are, then renders every +//! link once its names are final, with [`links`]. + +use std::collections::HashMap; +use std::ops::Range; + +use rustc_resolve::rustdoc::pulldown_cmark::{ + BrokenLink, CodeBlockKind, CowStr, Event, HeadingLevel, LinkType, Options, Parser, Tag, TagEnd, +}; + +use crate::ir::{Api, Constant, Function}; + +/// A resolved link's scheme, which shows the binding's name for the item. +const AUTO: &str = "rust2:"; +/// A resolved link's scheme, which keeps its own text. +const TEXT: &str = "rust2-text:"; +/// What opens a resolved link's destination, of either scheme. +pub(crate) const LINK: &str = "](rust2"; + +/// The options rustdoc parses a doc comment with. +fn options() -> Options { + rustc_resolve::rustdoc::main_body_opts() +} + +/// What a doc comment links to, by the namespace its disambiguator or suffix names. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Ns { + Type, + Value, + /// A value that `field@` says is a field, not a method of its name. + Field, + Macro, +} + +/// A link's path as rustc's resolver caches it, and the namespace it names, if any: rustc's +/// `preprocess_link`, which must agree with it, since its resolutions are looked up by it. +pub(crate) fn preprocess(dest: &str) -> (String, Option) { + let link = dest.replace('`', ""); + let link = link.split('#').next().unwrap_or("").trim(); + let (ns, link) = match link.split_once('@') { + Some((kind, rest)) => (disambiguator(kind), rest), + None => (None, link), + }; + let suffixed = |suffix: &str| link.ends_with(suffix); + let ns = ns.or(match () { + _ if suffixed("()") => Some(Ns::Value), + _ if suffixed("!") || suffixed("!{}") || suffixed("![]") || suffixed("!()") => Some(Ns::Macro), + _ => None, + }); + let link = link.strip_suffix("()").unwrap_or(link); + let link = link.strip_suffix("{}").unwrap_or(link); + let link = link.strip_suffix("[]").unwrap_or(link); + let link = match link { + "!" => link, + _ => link.strip_suffix('!').unwrap_or(link), + }; + let link = link.trim(); + let path = rustc_resolve::rustdoc::strip_generics_from_path(link).map_or_else(|_| link.to_string(), String::from); + (path, ns) +} + +/// The namespace a rustdoc disambiguator such as `struct` or `fn` names. +fn disambiguator(kind: &str) -> Option { + match kind { + "struct" | "enum" | "trait" | "union" | "mod" | "module" | "type" | "tyalias" | "typealias" | "prim" + | "primitive" => Some(Ns::Type), + "fn" | "function" | "method" | "tymethod" | "const" | "constant" | "static" | "value" | "variant" => { + Some(Ns::Value) + } + "field" => Some(Ns::Field), + "macro" | "derive" | "attr" => Some(Ns::Macro), + _ => None, + } +} + +/// Whether a fenced code block of `info` is Rust, as rustdoc reads its tags: with none, +/// with `rust`, or with only tags rustdoc gives a Rust example, such as `no_run`. +fn rust(info: &str) -> bool { + let mut other = false; + for tag in info + .split(|c: char| c == ',' || c.is_whitespace()) + .filter(|t| !t.is_empty()) + { + match tag { + "rust" => return true, + "should_panic" | "no_run" | "ignore" | "test_harness" | "compile_fail" | "standalone_crate" => {} + _ if tag.starts_with("ignore-") || tag.starts_with("edition") || tag.starts_with('{') => {} + _ if tag.len() == 5 && tag.starts_with('E') && tag[1..].bytes().all(|b| b.is_ascii_digit()) => {} + _ => other = true, + } + } + !other +} + +/// Whether a link's destination is a URL rather than a Rust path: an absolute URL keeps its +/// link, and any other, such as rustdoc's own `struct.Foo.html`, only its label. +fn url(dest: &str) -> Option { + if dest.contains("://") || dest.starts_with("mailto:") { + return Some(true); + } + (dest.starts_with('#') || dest.contains('/') || dest.ends_with(".html") || dest.contains(".html#")).then_some(false) +} + +/// `docs` in the canonical form, each intra-doc link's preprocessed path and namespace +/// resolved by `resolve` to the path of the item it names, if any. +pub(crate) fn canonical(docs: &str, mut resolve: impl FnMut(&str, Option) -> Option) -> String { + rewrite(docs, |link| { + let (path, ns) = preprocess(link.dest); + let path = resolve(&path, ns)?; + Some(format!( + "[{}]({}{path})", + link.label, + if link.auto { AUTO } else { TEXT } + )) + }) +} + +/// `note`, a deprecation's, as plain Markdown: each link only its label, as a language's +/// deprecation message links nothing. +pub(crate) fn plain(note: &str) -> String { + rewrite(note, |_| None) +} + +/// A link collection meets. +struct Found<'a> { + /// Its label as written, on one line. + label: String, + /// Its destination: a reference's, for one written by reference. + dest: &'a str, + /// Whether its label only spells its destination, as `` [`Foo`] `` does, so a binding + /// shows its own name for it. + auto: bool, +} + +/// `docs` without Rust examples or reference definitions, each intra-doc link `link` +/// renders, or its label where it renders none, and then without each heading left empty. +fn rewrite(docs: &str, mut link: impl FnMut(&Found<'_>) -> Option) -> String { + // As rustc's resolver does: an undefined reference is a link to its own text. + let mut broken = |broken: BrokenLink<'_>| Some((CowStr::from(broken.reference.to_string()), CowStr::from(""))); + let mut events = Parser::new_with_broken_link_callback(docs, options(), Some(&mut broken)).into_offset_iter(); + let mut edits: Vec<(Range, String)> = Vec::new(); + while let Some((event, range)) = events.next() { + match event { + Event::Start(Tag::CodeBlock(kind)) => { + let example = match &kind { + CodeBlockKind::Indented => true, + CodeBlockKind::Fenced(info) => rust(info), + }; + if example { + edits.push((range, String::new())); + } + } + // A reference image is written inline, as the definitions it names go. + Event::Start(Tag::Image { + link_type, + dest_url, + title, + .. + }) if !matches!(link_type, LinkType::Inline) => { + let alt = inner(&mut events, TagEnd::Image).map_or("", |r| &docs[r]); + // Escaped again, as the parser read them unescaped. + let title = match title.is_empty() { + true => String::new(), + false => format!(" \"{}\"", title.replace('\\', "\\\\").replace('"', "\\\"")), + }; + let dest = dest_url.replace('\\', "\\\\").replace('<', "\\<").replace('>', "\\>"); + edits.push((range, format!("![{alt}](<{dest}>{title})"))); + } + Event::Start(Tag::Link { + link_type, dest_url, .. + }) if rustc_resolve::rustdoc::may_be_doc_link(link_type) => { + let label: String = inner(&mut events, TagEnd::Link) + .map(|r| docs[r].replace(['\n', '\r'], " ").replace(['[', ']'], "")) + .unwrap_or_default(); + let dest = dest_url.to_string(); + let replacement = match url(&dest) { + Some(true) => format!("[{label}]({dest})"), + Some(false) => label.clone(), + None => { + let auto = !matches!( + link_type, + LinkType::Inline | LinkType::Reference | LinkType::ReferenceUnknown + ) || label.replace('`', "").trim() == dest.replace('`', "").trim(); + link(&Found { + label: label.clone(), + dest: &dest, + auto, + }) + .unwrap_or(label) + } + }; + edits.push((range, replacement)); + } + _ => {} + } + } + for (_, def) in events.reference_definitions().iter() { + edits.push((def.span.clone(), String::new())); + } + let text = drop_empty(&apply(docs, edits)); + tidy(&text) +} + +/// The extent of what `events` hold before the `end` of the tag they are inside, which +/// they are then past. +fn inner<'a>(events: &mut impl Iterator, Range)>, end: TagEnd) -> Option> { + let mut inner: Option> = None; + let mut depth = 0; + for (event, at) in events.by_ref() { + match event { + Event::End(e) if depth == 0 && e == end => break, + Event::Start(_) => depth += 1, + Event::End(_) => depth -= 1, + _ => {} + } + inner = Some(match inner { + Some(r) => r.start.min(at.start)..r.end.max(at.end), + None => at, + }); + } + inner +} + +/// `text` with each of `edits`' ranges replaced, ignoring one inside an earlier one. +fn apply(text: &str, mut edits: Vec<(Range, String)>) -> String { + edits.sort_by_key(|(range, _)| range.start); + let mut out = String::with_capacity(text.len()); + let mut at = 0; + for (range, replacement) in edits { + if range.start < at { + continue; + } + out.push_str(&text[at..range.start]); + out.push_str(&replacement); + at = range.end; + } + out.push_str(&text[at..]); + out +} + +/// Each top-level block of `text`: its range, and its heading level if it is a heading. +fn blocks(text: &str) -> Vec<(Range, Option)> { + let mut blocks = Vec::new(); + let mut depth = 0usize; + for (event, range) in Parser::new_ext(text, options()).into_offset_iter() { + match event { + Event::Start(tag) => { + if depth == 0 { + let level = match tag { + Tag::Heading { level, .. } => Some(level), + _ => None, + }; + blocks.push((range, level)); + } + depth += 1; + } + Event::End(_) => depth -= 1, + _ if depth == 0 => blocks.push((range, None)), + _ => {} + } + } + blocks +} + +/// `text` without each heading whose section is empty, such as an `# Examples` that held +/// only Rust examples. +fn drop_empty(text: &str) -> String { + let mut text = text.to_string(); + loop { + let blocks = blocks(&text); + let empty: Vec<(Range, String)> = (blocks.iter().enumerate()) + .filter_map(|(i, (range, level))| { + let level = (*level)?; + let next = blocks.get(i + 1).map(|(_, next)| *next); + match next { + None => Some((range.clone(), String::new())), + Some(Some(next)) if next <= level => Some((range.clone(), String::new())), + _ => None, + } + }) + .collect(); + if empty.is_empty() { + return text; + } + text = apply(&text, empty); + } +} + +/// `text` trimmed, with no line's trailing space and at most one blank line in a row. +fn tidy(text: &str) -> String { + let mut out = String::new(); + let mut blank = 0; + for line in text.trim().lines() { + let line = line.trim_end(); + match line.is_empty() { + true => blank += 1, + false => { + if blank > 0 && !out.is_empty() { + out.push('\n'); + } + blank = 0; + out.push_str(line); + out.push('\n'); + } + } + } + out.trim_end().to_string() +} + +/// `docs` with `note`, a paragraph, after its text and before its first heading. +pub(crate) fn note(docs: &str, note: &str) -> String { + let at = (blocks(docs).into_iter()) + .find(|(_, level)| level.is_some()) + .map_or(docs.len(), |(range, _)| range.start); + tidy(&format!("{}\n\n{note}\n\n{}", &docs[..at], &docs[at..])) +} + +/// A function's docs, apart from its `# Errors` and `# Panics` sections, which a language +/// writes in its own form. +#[derive(Default, Debug, PartialEq)] +pub(crate) struct Sections { + /// The rest, in order. + pub(crate) body: String, + /// When it fails: its `# Errors` section. + pub(crate) errors: Option, + /// When it panics, which aborts the process: its `# Panics` section. + pub(crate) panics: Option, +} + +/// `docs` in its sections. +pub(crate) fn sections(docs: &str) -> Sections { + let blocks = blocks(docs); + let mut out = Sections::default(); + let mut edits = Vec::new(); + for (i, (range, level)) in blocks.iter().enumerate() { + let Some(level) = level else { + continue; + }; + let title = docs[range.clone()].trim_start_matches('#').trim(); + let slot = match title { + "Errors" => &mut out.errors, + "Panics" => &mut out.panics, + _ => continue, + }; + let end = (blocks[i + 1..].iter()) + .find(|(_, next)| next.is_some_and(|next| next <= *level)) + .map_or(docs.len(), |(next, _)| next.start); + *slot = Some(tidy(&docs[range.end..end])); + edits.push((range.start..end, String::new())); + } + out.body = tidy(&apply(docs, edits)); + out +} + +/// What a resolved link names. +#[derive(Clone, Copy)] +pub(crate) enum Target<'a> { + Record(usize), + Enum(usize), + /// An enum's variant, by its index. + Variant(usize, usize), + Object(usize), + Callback(usize), + Constant(&'a Constant), + /// A function, or a method of its owner. + Function(Option, &'a Function), + /// A record's field, by its index. + Field(usize, usize), +} + +/// The type a method belongs to. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Owner { + Record(usize), + Enum(usize), + Object(usize), + Callback(usize), +} + +/// The path a link names a field by, apart from a method of its name, as rustdoc's +/// `field@` keeps it: `::field@`. +pub(crate) fn field(owner: &[String], name: &str) -> String { + format!("{}::field@{name}", owner.join("::")) +} + +/// Each item a link may name, by its path: an instance of a generic type, or a function of +/// one, by its first. +fn index<'a>(api: &'a Api) -> HashMap> { + let mut index = HashMap::new(); + let mut add = |path: String, target: Target<'a>| { + index.entry(path).or_insert(target); + }; + for (i, r) in api.records.iter().enumerate() { + add(r.path.join("::"), Target::Record(i)); + for (n, f) in r.fields.iter().enumerate() { + add(field(&r.path, &f.name), Target::Field(i, n)); + } + } + for (i, e) in api.enums.iter().enumerate() { + add(e.path.join("::"), Target::Enum(i)); + for (n, v) in e.variants.iter().enumerate() { + add(format!("{}::{}", e.path.join("::"), v.name), Target::Variant(i, n)); + } + } + for (i, o) in api.objects.iter().enumerate() { + add(o.path.join("::"), Target::Object(i)); + } + for (i, c) in api.callbacks.iter().enumerate() { + add(c.path.join("::"), Target::Callback(i)); + } + for c in &api.constants { + add(c.path.join("::"), Target::Constant(c)); + } + let owned = (api + .records + .iter() + .enumerate() + .map(|(i, r)| (Owner::Record(i), &r.methods))) + .chain(api.enums.iter().enumerate().map(|(i, e)| (Owner::Enum(i), &e.methods))) + .chain( + api.objects + .iter() + .enumerate() + .map(|(i, o)| (Owner::Object(i), &o.methods)), + ) + .chain( + api.callbacks + .iter() + .enumerate() + .map(|(i, c)| (Owner::Callback(i), &c.methods)), + ) + .flat_map(|(owner, methods)| methods.iter().map(move |f| (Some(owner), f))); + for (owner, f) in owned.chain(api.functions.iter().map(|f| (None, f))) { + // A field's getter is the field, before its setter, which shares its path. + match f.access { + crate::ir::Access::Field { set: true, .. } => {} + crate::ir::Access::Field { set: false, .. } => { + if let Some((name, path)) = f.path.split_last() { + add(field(path, name), Target::Function(owner, f)); + } + } + _ => add(f.path.join("::"), Target::Function(owner, f)), + } + } + index +} + +/// A resolved link a generator renders. +pub(crate) struct Link<'a> { + pub(crate) target: Target<'a>, + /// Its own text, for a link written with one, else none: the binding's name shows. + pub(crate) text: Option<&'a str>, +} + +/// `out`, generated code, with each resolved link in its docs as `render` writes it, or +/// its label where `render` writes none, as for an item the binding lacks. +pub(crate) fn links(out: &str, api: &Api, mut render: impl FnMut(&Link<'_>) -> Option) -> String { + let index = index(api); + let mut result = String::with_capacity(out.len()); + let mut rest = out; + while let Some(at) = rest.find(LINK) { + let (before, after) = rest.split_at(at); + let scheme = match () { + _ if after[2..].starts_with(AUTO) => AUTO, + _ if after[2..].starts_with(TEXT) => TEXT, + _ => { + result.push_str(&rest[..at + 1]); + rest = &rest[at + 1..]; + continue; + } + }; + let (Some(open), Some(close)) = (before.rfind('['), after.find(')')) else { + result.push_str(&rest[..at + 1]); + rest = &rest[at + 1..]; + continue; + }; + let label = &before[open + 1..]; + let path = &after[2 + scheme.len()..close]; + result.push_str(&before[..open]); + let rendered = index.get(path).and_then(|&target| { + render(&Link { + target, + text: (scheme == TEXT).then_some(label), + }) + }); + result.push_str(rendered.as_deref().unwrap_or(label)); + rest = &after[close + 1..]; + } + result.push_str(rest); + result +} + +/// The docs of one item on two targets as one, keeping each link either resolved: they +/// differ only where a link one target resolved is only its label on the other, as for an +/// item the other lacks. None where they differ otherwise. +pub(crate) fn merge(ours: &str, theirs: &str) -> Option { + let (mut a, mut b) = (ours, theirs); + let mut out = String::with_capacity(ours.len().max(theirs.len())); + while !a.is_empty() || !b.is_empty() { + match (resolved(a), resolved(b)) { + (Some((link, _)), Some((other, _))) if link == other => {} + (Some((link, label)), _) if b.starts_with(label) => { + out.push_str(link); + a = &a[link.len()..]; + b = &b[label.len()..]; + continue; + } + (_, Some((link, label))) if a.starts_with(label) => { + out.push_str(link); + a = &a[label.len()..]; + b = &b[link.len()..]; + continue; + } + _ => {} + } + let c = a.chars().next()?; + if !b.starts_with(c) { + return None; + } + out.push(c); + a = &a[c.len_utf8()..]; + b = &b[c.len_utf8()..]; + } + Some(out) +} + +/// The resolved link `text` opens with, and its label. +fn resolved(text: &str) -> Option<(&str, &str)> { + let rest = text.strip_prefix('[')?; + let close = rest.find(']')?; + let label = &rest[..close]; + let dest = &rest[close..]; + if !dest.starts_with(LINK) || label.contains('[') { + return None; + } + let end = 1 + close + dest.find(')')? + 1; + Some((&text[..end], label)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Resolves `Self::*` and `Error::*` under `moq::Track`, and nothing else. + fn resolve(path: &str, _: Option) -> Option { + match path.split_once("::") { + Some(("Self", rest)) => Some(format!("moq::Track::{rest}")), + Some(("Error", rest)) => Some(format!("moq::Error::{rest}")), + _ if path == "Track" => Some("moq::Track".to_string()), + _ => None, + } + } + + /// Each target's docs resolve the link to the item only it has, and their merge both. + #[test] + fn merge_keeps_each_link() { + let unix = "Use [`Fd`](rust2:a::Fd) or `Handle`, [the docs](rust2-text:a::Fd)."; + let windows = "Use `Fd` or [`Handle`](rust2:a::Handle), the docs."; + let both = "Use [`Fd`](rust2:a::Fd) or [`Handle`](rust2:a::Handle), [the docs](rust2-text:a::Fd)."; + assert_eq!(merge(unix, windows).as_deref(), Some(both)); + assert_eq!(merge(windows, unix).as_deref(), Some(both)); + assert_eq!(merge(both, both).as_deref(), Some(both)); + assert_eq!(merge("[a] b", "[a] b").as_deref(), Some("[a] b")); + assert_eq!(merge(unix, "Other docs."), None); + } + + #[test] + fn links_resolve() { + let docs = "Call [`Self::abort`] or [the close](Self::close()) on [`Track`], else [`Vec`].\n\n\ + See [its docs](https://example.com) and [`Error::Timeout`][timeout], not [rustdoc](struct.Track.html).\n\n\ + [timeout]: Error::Timeout"; + assert_eq!( + canonical(docs, resolve), + "Call [`Self::abort`](rust2:moq::Track::abort) or [the close](rust2-text:moq::Track::close) on [`Track`](rust2:moq::Track), else `Vec`.\n\n\ + See [its docs](https://example.com) and [`Error::Timeout`](rust2:moq::Error::Timeout), not rustdoc." + ); + } + + /// A reference image keeps its target, written inline, as its definition goes. + #[test] + fn images_kept() { + let docs = "See ![the flow][flow] and ![`Track`](rust2-not-a-link.png).\n\n[flow]: https://example.com/flow.png \"Flow\""; + assert_eq!( + canonical(docs, resolve), + "See ![the flow]( \"Flow\") and ![`Track`](rust2-not-a-link.png)." + ); + assert_eq!( + canonical("![x][x]\n\n[x]: b.png> \"a \\\"quote\\\" and a \\\\\"", resolve), + "![x](b.png> \"a \\\"quote\\\" and a \\\\\")" + ); + } + + #[test] + fn examples_dropped() { + let docs = "Starts.\n\n# Examples\n\n```\nlet x = 1;\n```\n\n## Output\n\n```text\nok\n```\n\n# Panics\n\n indented();\n\nWhen empty."; + assert_eq!( + canonical(docs, resolve), + "Starts.\n\n# Examples\n\n## Output\n\n```text\nok\n```\n\n# Panics\n\nWhen empty." + ); + assert_eq!(canonical("Hi.\n\n# Examples\n\n```no_run\nx();\n```", resolve), "Hi."); + assert!(!rust("text") && !rust("sh,no_run") && rust("") && rust("ignore,edition2021") && rust("rust,text")); + } + + #[test] + fn split() { + let docs = "Opens it.\n\n# Errors\n\nWhen [`Error::Timeout`](rust2:x).\n\n## Detail\n\nMore.\n\n# Panics\n\nIf zero.\n\n# Notes\n\nKept."; + assert_eq!( + sections(docs), + Sections { + body: "Opens it.\n\n# Notes\n\nKept.".to_string(), + errors: Some("When [`Error::Timeout`](rust2:x).\n\n## Detail\n\nMore.".to_string()), + panics: Some("If zero.".to_string()), + } + ); + assert_eq!(note("A.\n\n# Errors\n\nB.", "N."), "A.\n\nN.\n\n# Errors\n\nB."); + } + + #[test] + fn plain_note() { + assert_eq!( + plain("use [`Self::poll_next`] instead"), + "use `Self::poll_next` instead" + ); + } +} diff --git a/ffi/src/go.rs b/ffi/src/go.rs index 46bff3d93..5d6faee53 100644 --- a/ffi/src/go.rs +++ b/ffi/src/go.rs @@ -42,6 +42,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fmt::Write; use crate::abi::{self, Abi, Ty, pascal}; +use crate::doc; use crate::ir::{Access, Closure, Collection, Function, Home, Int, Literal, On, Param, Receiver, Type}; const RUNTIME: &str = include_str!("../runtime/rt.go"); @@ -176,6 +177,7 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64, module: &st let mut files = Vec::new(); let mut errors = Vec::new(); let mut tuples = BTreeSet::new(); + let mut api_files = Vec::new(); let mut rt = Gen::new(abi, &set, Packages::RT, &shared); rt.write_rt(); for krate in &abi.api.crates { @@ -191,6 +193,7 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64, module: &st // through cgo, whose runtime links the static library rt/lib{p}__.a.\n", p = abi.prefix ); + api_files.push((files.len(), krate)); files.push((format!("{name}/{name}.go"), g.file(&doc))); // No package name holds a `_` but at its end, so the helpers never take the API's file. files.push((format!("{name}/ffi_cgo.go"), g.conversions())); @@ -199,6 +202,13 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64, module: &st if !errors.is_empty() { return Err(errors.join("\n")); } + // Each link once every name is final; Go's show only the item's own name. + for (at, krate) in api_files { + files[at].1 = doc::links(&files[at].1, api, |link| match link.text { + Some(_) => None, + None => doc_link(abi, &set, &shared, &locked, krate, link.target), + }); + } for n in tuples { let params: Vec = (0..n).map(|k| format!("T{k}")).collect(); let fields: String = (0..n).map(|k| format!("\tV{k} T{k}\n")).collect(); @@ -497,7 +507,7 @@ impl Method { }; format!( "{}func {receiver}{} {{\n{}\n}}\n\n", - docs(self.docs.trim(), ""), + docs(self.docs.trim(), None, ""), self.signature(), indent(&self.body) ) @@ -1428,7 +1438,11 @@ impl<'a> Gen<'a> { Literal::Bool(b) => ("bool", b.to_string()), Literal::Int(int, v) => (go_int(int), v.to_string()), }; - let _ = write!(self.top, "{}const {name} {ty} = {value}\n\n", docs(&constant.docs, "")); + let _ = write!( + self.top, + "{}const {name} {ty} = {value}\n\n", + docs(&constant.docs, constant.deprecated.as_deref(), "") + ); } for i in (0..api.records.len()).filter(|&i| mine(&api.records[i].home)) { self.record(i); @@ -1908,7 +1922,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}type {name} struct {{\n\t_ [0]func()\n\t// Bytes_ is its bytes, for the generated packages: use none of it.\n\tBytes_ [{}]uint{}\n\t// Made_ is whether Rust made it, rather than it being Go's zero value.\n\tMade_ bool\n}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), record.deprecated.as_deref(), ""), opaque.units(), opaque.unit() * 8 ); @@ -1931,13 +1945,13 @@ impl<'a> Gen<'a> { .collect(); let mut members: Vec = fields.iter().map(|(f, _)| f.clone()).collect(); let body: String = (record.fields.iter().zip(&fields)) - .map(|(f, (name, go))| format!("{}\t{name} {go}\n", docs(&f.docs, "\t"))) + .map(|(f, (name, go))| format!("{}\t{name} {go}\n", docs(&f.docs, f.deprecated.as_deref(), "\t"))) .collect(); let text = format!("{name} is `{rust}`.\n\n{}", record.docs); let _ = write!( self.types, "{}type {name} struct {{\n{body}}}\n\n", - docs(text.trim(), "") + docs(text.trim(), record.deprecated.as_deref(), "") ); let fields: Vec = members.clone(); members.extend(self.methods_of( @@ -2144,7 +2158,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}type {name} int32\n\nconst (\n{consts})\n\n", - docs(text.trim(), "") + docs(text.trim(), e.deprecated.as_deref(), "") ); let members = self.methods_of(&ty, &c, &rust, e.traits, &e.methods, &Ty::Enum(c.clone()), &[]); self.distinct(&rust, &members); @@ -2157,7 +2171,12 @@ impl<'a> Gen<'a> { let mut interface = format!("\t{seal}()\n"); let mut shared = String::new(); for method in &methods { - let _ = writeln!(interface, "{}\t{}", docs(method.docs.trim(), "\t"), method.signature()); + let _ = writeln!( + interface, + "{}\t{}", + docs(method.docs.trim(), None, "\t"), + method.signature() + ); let mut function = Method { key: None, docs: String::new(), @@ -2173,7 +2192,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}type {name} interface {{\n{interface}}}\n\n{shared}", - docs(text.trim(), "") + docs(text.trim(), e.deprecated.as_deref(), "") ); for variant in &e.variants { let vname = self.variants[&(c.clone(), variant.name.clone())].clone(); @@ -2305,7 +2324,7 @@ impl<'a> Gen<'a> { self.types, "{}type {name} struct {{\n\t// Handle_ is the handle it owns, for the generated packages: use none of it.\n\tHandle_ *{handle}\n}}\n\n\ {close}func (self *{name}) Close() error {{\n\treturn self.Handle_.Close()\n}}\n\n", - docs(text.trim(), "") + docs(text.trim(), object.deprecated.as_deref(), "") ); let mut members = vec!["Close".to_string(), "Handle_".to_string()]; let owner = Ty::Handle { @@ -2376,7 +2395,11 @@ impl<'a> Gen<'a> { }; body.push(format!( "{}\t{member}({}){ret}", - docs(&method.docs, "\t"), + docs( + &self.function_docs(method, doc::sections(&method.docs).body), + method.deprecated.as_deref(), + "\t" + ), params.join(", ") )); let export = format!("{p}Go_{}_{}", self.bare(&c), method.name()); @@ -2407,7 +2430,7 @@ impl<'a> Gen<'a> { var vtable_{c} = func() *C.{c}_vtable {{\n\tv := (*C.{c}_vtable)(C.malloc(C.size_t(unsafe.Sizeof(C.{c}_vtable{{}}))))\n{}\treturn v\n}}()\n\n\ // {vtable} is the table of {name}'s methods Rust calls, for the generated packages.\n\ func {vtable}() unsafe.Pointer {{\n\treturn unsafe.Pointer(vtable_{c})\n}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), callback.deprecated.as_deref(), ""), body.join("\n"), table.join("") ); @@ -3149,7 +3172,7 @@ impl<'a> Gen<'a> { } } - let mut text = function.docs.clone(); + let mut text = doc::sections(&function.docs).body; for (param, name) in function.params.iter().zip(&names) { if let Type::Closure(closure) = ¶m.ty { text.push_str(&match closure.kept { @@ -3185,9 +3208,10 @@ impl<'a> Gen<'a> { let error = format!("{supported}({}, \"{c_name}\")", function.on.0 & abi.api.all().0); body.insert(0, format!("if err_ := {error}; err_ != nil {{\n\t{}\n}}", fail("err_"))); } + let text = self.function_docs(function, text); Method { key: Some(crate::lock::function_key(function)), - docs: text, + docs: deprecation(&text, function.deprecated.as_deref()), receiver: go_receiver, name: member, params, @@ -3196,6 +3220,42 @@ impl<'a> Gen<'a> { } } + /// `text`, a function's docs without its sections, then its `# Errors`, naming its + /// error's type, and its `# Panics` as when it aborts. + fn function_docs(&mut self, function: &Function, text: String) -> String { + let sections = doc::sections(&function.docs); + let mut text = text.trim().to_string(); + if let Some(errors) = §ions.errors { + let what = match &function.err { + Some(err) => format!("Its error type is {}.\n\n", self.error_link(err)), + None => String::new(), + }; + let _ = write!(text, "\n\n# Errors\n\n{what}{errors}"); + } + if let Some(panics) = §ions.panics { + let _ = write!(text, "\n\n# Aborts\n\n{panics}"); + } + text.trim().to_string() + } + + /// A doc link to the Go type of an error of type `err`. + fn error_link(&self, err: &Type) -> String { + let api = self.abi.api; + let (krate, name) = match err.base() { + Type::Record(i) => (&api.records[*i].home.krate, &self.type_names[&self.abi.record(*i)]), + Type::Enum(i) => (&api.enums[*i].home.krate, &self.type_names[&self.abi.enumeration(*i)]), + Type::Object(i) => (&api.objects[*i].home.krate, &self.type_names[&self.abi.object(*i)]), + _ => { + let key = self.abi.key(err); + let (name, (home, _)) = (self.thrown.iter()) + .find(|(_, (_, thrown))| self.abi.key(thrown) == key) + .expect("each error is thrown"); + (home, name) + } + }; + format!("[{}]", in_package(self.set, self.pkg, krate, name)) + } + /// The Go error of the C error `e` of type `err`: itself if an exported type, which then /// implements `error`, or else in a struct of its own. fn lift_err(&mut self, err: &Type, e: &str) -> String { @@ -3214,6 +3274,68 @@ impl<'a> Gen<'a> { } } +/// `name`, of `krate`'s package, as a doc link names it from `here`'s: by its import path +/// from another package's. +fn in_package(set: &Packages, here: &str, krate: &str, name: &str) -> String { + match krate == here { + true => name.to_string(), + false => format!("{}.{name}", set.by_crate[krate].1), + } +} + +/// The Go doc link for `target`, from `here`'s package, if Go has it. +fn doc_link( + abi: &Abi<'_>, + set: &Packages, + shared: &Shared, + locked: &BTreeMap, + here: &str, + target: doc::Target<'_>, +) -> Option { + let api = abi.api; + let owner = |owner: doc::Owner| match owner { + doc::Owner::Record(i) => (&api.records[i].home.krate, &shared.type_names[&abi.record(i)]), + doc::Owner::Enum(i) => (&api.enums[i].home.krate, &shared.type_names[&abi.enumeration(i)]), + doc::Owner::Object(i) => (&api.objects[i].home.krate, &shared.type_names[&abi.object(i)]), + doc::Owner::Callback(i) => (&api.callbacks[i].home.krate, &shared.type_names[&abi.callback(i)]), + }; + let (krate, name) = match target { + doc::Target::Record(i) => owner(doc::Owner::Record(i)), + doc::Target::Enum(i) => owner(doc::Owner::Enum(i)), + doc::Target::Object(i) => owner(doc::Owner::Object(i)), + doc::Target::Callback(i) => owner(doc::Owner::Callback(i)), + doc::Target::Variant(i, v) => ( + &api.enums[i].home.krate, + &shared.variants[&(abi.enumeration(i), api.enums[i].variants[v].name.clone())], + ), + doc::Target::Field(i, n) => { + let (krate, name) = owner(doc::Owner::Record(i)); + let record = &api.records[i]; + let key = format!( + "{} / field {}", + crate::lock::type_key(&record.shown), + record.fields[n].name + ); + let field = locked.get(&key)?; + return Some(format!("[{}.{field}]", in_package(set, here, krate, name))); + } + doc::Target::Constant(c) => (&c.home.krate, locked.get(&format!("const {}", c.path.join("::")))?), + doc::Target::Function(of, f) => { + let member = locked.get(&crate::lock::function_key(f))?; + // A method with a receiver in its type's package is the type's; any other is a + // function of its own package, named for the type already. + let (krate, name) = match of.map(owner) { + Some((krate, name)) if f.receiver.is_some() && *krate == f.home.krate => { + (krate, format!("{name}.{member}")) + } + _ => (&f.home.krate, member.clone()), + }; + return Some(format!("[{}]", in_package(set, here, krate, &name))); + } + }; + Some(format!("[{}]", in_package(set, here, krate, name))) +} + /// The Go statements `first`, if any, then `rest`. fn then(first: &str, rest: &str) -> String { match first.is_empty() { @@ -3443,14 +3565,34 @@ fn cgo_field(name: &str) -> String { } } -/// Go doc comments holding `docs`, each line indented by `indent`, or nothing for none. -fn docs(docs: &str, indent: &str) -> String { - docs.lines() - .map(|line| match line.is_empty() { - true => format!("{indent}//\n"), - false => format!("{indent}// {line}\n"), - }) - .collect() +/// `docs`, then a `Deprecated:` paragraph of `deprecated`'s note where it has one. +fn deprecation(docs: &str, deprecated: Option<&str>) -> String { + match deprecated { + Some("") => format!("{docs}\n\nDeprecated: Rust deprecates it."), + Some(note) => format!("{docs}\n\nDeprecated: {note}"), + None => docs.to_string(), + } +} + +/// Go doc comments holding `docs`, then a `Deprecated:` paragraph of `deprecated`'s note +/// where it has one, as Go's tools read it, each line indented by `indent`, or nothing for +/// none. A fenced block is indented instead, as Go's doc comments set code. +fn docs(docs: &str, deprecated: Option<&str>, indent: &str) -> String { + let docs = deprecation(docs, deprecated); + let mut fenced = false; + let mut out = String::new(); + for line in docs.trim().lines() { + if line.trim_start().starts_with("```") { + fenced = !fenced; + continue; + } + let _ = match (line.is_empty(), fenced) { + (true, _) => writeln!(out, "{indent}//"), + (false, true) => writeln!(out, "{indent}//\t{line}"), + (false, false) => writeln!(out, "{indent}// {line}"), + }; + } + out } /// Code indented by one tab more, but for blank lines. diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 2376d9516..e2661a101 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -210,6 +210,10 @@ pub(crate) struct Record { /// The targets it compiles on. pub(crate) on: On, pub(crate) docs: String, + /// Its `#[deprecated]` note, if it is deprecated: empty for none. A baseline written + /// before it has none. + #[serde(default)] + pub(crate) deprecated: Option, pub(crate) fields: Vec, /// Whether its fields are positional, named `0`, `1`, ... pub(crate) tuple: bool, @@ -277,6 +281,10 @@ pub(crate) struct Field { /// Its Rust name: a number for a positional field. pub(crate) name: String, pub(crate) docs: String, + /// Its `#[deprecated]` note, if it is deprecated: empty for none. A baseline written + /// before it has none. + #[serde(default)] + pub(crate) deprecated: Option, pub(crate) ty: Type, } @@ -293,6 +301,10 @@ pub(crate) struct Enum { /// The targets it compiles on. pub(crate) on: On, pub(crate) docs: String, + /// Its `#[deprecated]` note, if it is deprecated: empty for none. A baseline written + /// before it has none. + #[serde(default)] + pub(crate) deprecated: Option, pub(crate) variants: Vec, /// Whether another crate can match it without a wildcard arm. pub(crate) exhaustive: bool, @@ -335,6 +347,10 @@ pub(crate) struct Object { /// The targets it compiles on. pub(crate) on: On, pub(crate) docs: String, + /// Its `#[deprecated]` note, if it is deprecated: empty for none. A baseline written + /// before it has none. + #[serde(default)] + pub(crate) deprecated: Option, /// Whether it is `Sync`: if not, `&self` borrows it on one thread at a time. One that is /// not `Send` is not, as only its thread borrows it. pub(crate) sync: bool, @@ -404,6 +420,10 @@ pub(crate) struct Callback { /// The targets it compiles on. pub(crate) on: On, pub(crate) docs: String, + /// Its `#[deprecated]` note, if it is deprecated: empty for none. A baseline written + /// before it has none. + #[serde(default)] + pub(crate) deprecated: Option, /// Its required methods, each taking `&self` or `&mut self`. pub(crate) methods: Vec, } @@ -447,6 +467,10 @@ pub(crate) struct Function { pub(crate) on: On, /// Its doc comment, as Markdown. pub(crate) docs: String, + /// Its `#[deprecated]` note, if it is deprecated: empty for none. A baseline written + /// before it has none. + #[serde(default)] + pub(crate) deprecated: Option, pub(crate) receiver: Option, pub(crate) params: Vec, /// Where among Rust's parameters each `()` one sits, which C does not pass. @@ -594,6 +618,10 @@ pub(crate) struct Constant { /// The targets it compiles on. pub(crate) on: On, pub(crate) docs: String, + /// Its `#[deprecated]` note, if it is deprecated: empty for none. A baseline written + /// before it has none. + #[serde(default)] + pub(crate) deprecated: Option, pub(crate) value: Literal, } diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index edbedfd49..166cd0511 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -29,6 +29,7 @@ use std::hash::Hasher; use rustc_data_structures::stable_hash::StableHasher; use crate::abi::{self, Abi, Ty, pascal}; +use crate::doc; use crate::ir::{Access, Family, Function, Int, Jni, Literal, Mutability, On, Opaque, Param, Receiver, Type}; const RUNTIME: &str = include_str!("../runtime/rt.kt"); @@ -81,6 +82,19 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result| { + let target = g.link(link.target)?; + Some(match link.text { + Some(text) => format!("[{text}][{target}]"), + None => format!("[{target}]"), + }) + }; + let (types, top) = ( + doc::links(&g.types, abi.api, render), + doc::links(&g.top, abi.api, render), + ); + (g.types, g.top) = (types, top); let p = &abi.prefix; let mut hasher = StableHasher::new(); hasher.write_u64(contract); @@ -99,7 +113,7 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result Gen<'a> { let _ = write!( self.top, "{}const val {name}: {ty} = {value}\n\n", - docs(&constant.docs, "") + docs(&constant.docs, constant.deprecated.as_deref(), "") ); } for i in 0..api.records.len() { @@ -1716,20 +1730,20 @@ impl<'a> Gen<'a> { if !statics.is_empty() { body.push(format!("\tcompanion object {{\n{}\t}}\n", statics.join("\n"))); } - let docs = docs(&record.docs, ""); + let comment = docs(&record.docs, record.deprecated.as_deref(), ""); let body = match body.is_empty() { true => String::new(), false => format!(" {{\n{}}}", body.join("\n")), }; if let Some(opaque) = record.opaque { - self.opaque(&c, &name, &opaque, &docs, &body); + self.opaque(&c, &name, &opaque, &comment, &body); return; } match fields.is_empty() { true => { let _ = write!( self.types, - "{docs}class {name} {}\n\n", + "{comment}class {name} {}\n\n", match body.is_empty() { true => format!( "{{\n\toverride fun equals(other: kotlin.Any?): kotlin.Boolean = other is {name}\n\n\toverride fun hashCode(): kotlin.Int = 0\n}}" @@ -1748,11 +1762,16 @@ impl<'a> Gen<'a> { let params: Vec = fields .iter() .zip(&record.fields) - .map(|((f, kt), field)| format!("{}\tval {f}: {kt},", docs_inline(&field.docs, "\t"))) + .map(|((f, kt), field)| { + format!( + "{}\tval {f}: {kt},", + docs(&field.docs, field.deprecated.as_deref(), "\t") + ) + }) .collect(); let _ = write!( self.types, - "{docs}data class {name}(\n{}\n){body}\n\n", + "{comment}data class {name}(\n{}\n){body}\n\n", params.join("\n") ); } @@ -1927,7 +1946,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}enum class {name}(internal {open}val value: Int) {{\n{entries};\n\n{}\tcompanion object {{\n{}\t}}\n}}\n\n", - docs(&e.docs, ""), + docs(&e.docs, e.deprecated.as_deref(), ""), body.iter().map(|b| format!("{b}\n")).collect::(), statics.join("\n") ); @@ -2011,7 +2030,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}sealed class {name} {{\n{}}}\n\n", - docs(&e.docs, ""), + docs(&e.docs, e.deprecated.as_deref(), ""), all.join("\n") ); let _ = write!( @@ -2095,7 +2114,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}class {name} internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable {{\n{}}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), object.deprecated.as_deref(), ""), body.join("\n") ); } @@ -2121,7 +2140,11 @@ impl<'a> Gen<'a> { let ret = self.kt(&method.ok); body.push(format!( "{}\tfun {member}({}){}", - docs(&method.docs, "\t"), + docs( + &self.function_docs(method, doc::sections(&method.docs).body), + method.deprecated.as_deref(), + "\t" + ), params.join(", "), match method.ok { Type::Unit => String::new(), @@ -2151,7 +2174,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}interface {name} {{\n{}\n}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), callback.deprecated.as_deref(), ""), body.join("\n\n") ); let _ = write!( @@ -2382,6 +2405,65 @@ impl<'a> Gen<'a> { ); } + /// `text`, a function's docs without its sections, then its `# Errors` as `@throws` of + /// its exception, and its `# Panics` as when it aborts. + fn function_docs(&mut self, function: &Function, text: String) -> String { + let sections = doc::sections(&function.docs); + let mut text = text.trim().to_string(); + if let Some(panics) = §ions.panics { + let _ = write!(text, "\n\n# Aborts\n\n{panics}"); + } + match (§ions.errors, &function.err) { + (Some(errors), Some(err)) => { + let thrown = self.exception(err); + let _ = write!(text, "\n\n@throws {thrown} {errors}"); + } + (Some(errors), None) => { + let _ = write!(text, "\n\n# Errors\n\n{errors}"); + } + (None, _) => {} + } + text.trim().to_string() + } + + /// What a link in KDoc names for `target`, if Kotlin has it. + fn link(&self, target: doc::Target<'_>) -> Option { + let abi = self.abi; + let owner = |owner: doc::Owner| match owner { + doc::Owner::Record(i) => self.class(&abi.record(i)), + doc::Owner::Enum(i) => self.class(&abi.enumeration(i)), + doc::Owner::Object(i) => self.class(&abi.object(i)), + doc::Owner::Callback(i) => self.class(&abi.callback(i)), + }; + Some(match target { + doc::Target::Record(i) => owner(doc::Owner::Record(i)), + doc::Target::Enum(i) => owner(doc::Owner::Enum(i)), + doc::Target::Object(i) => owner(doc::Owner::Object(i)), + doc::Target::Callback(i) => owner(doc::Owner::Callback(i)), + doc::Target::Variant(i, v) => { + let e = &abi.api.enums[i]; + let name = &e.variants[v].name; + match e.plain() { + true => format!("{}.{}", owner(doc::Owner::Enum(i)), abi::snake(name).to_uppercase()), + false => format!("{}.{}", owner(doc::Owner::Enum(i)), pascal(name)), + } + } + doc::Target::Field(i, n) => format!( + "{}.{}", + owner(doc::Owner::Record(i)), + field_name(&abi.api.records[i].fields[n].name) + ), + doc::Target::Constant(c) => self.locked.get(&format!("const {}", c.path.join("::")))?.clone(), + doc::Target::Function(of, f) => { + let member = self.locked.get(&crate::lock::function_key(f))?; + match of { + Some(of) => format!("{}.{member}", owner(of)), + None => member.clone(), + } + } + }) + } + /// The exception Kotlin throws for an error of type `e`, declared once. fn exception(&mut self, e: &Type) -> String { let kt = self.kt(e); @@ -3115,7 +3197,7 @@ impl<'a> Gen<'a> { }; } - let mut text = function.docs.clone(); + let mut text = doc::sections(&function.docs).body; if handed.is_some() { text.push_str( "\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes.", @@ -3219,7 +3301,11 @@ impl<'a> Gen<'a> { if let Some(exception) = &exception { let _ = writeln!(annotations, "@{target}kotlin.jvm.Throws({exception}::class)"); } - let code = format!("{}{annotations}{code}\n", docs(text.trim(), "")); + let text = self.function_docs(function, text); + let code = format!( + "{}{annotations}{code}\n", + docs(&text, function.deprecated.as_deref(), "") + ); Some(indent_by(&code, indent_level)) } @@ -4106,11 +4192,17 @@ fn member_name(code: &str) -> Option { Some(format!("{kind} {name}")) } -/// Kotlin's KDoc holding `docs`, each line indented by `indent`, or nothing for none. +/// Kotlin's KDoc holding `docs`, each line indented by `indent`, or nothing for none, and +/// `@kotlin.Deprecated` with its note where `deprecated` has one, qualified since an +/// exported `Deprecated` would shadow it. /// A Kotlin block comment nests, so a `/*` or `*/` in the docs is escaped. -fn docs(docs: &str, indent: &str) -> String { +fn docs(docs: &str, deprecated: Option<&str>, indent: &str) -> String { + let deprecated = match deprecated { + Some(note) => format!("{indent}@kotlin.Deprecated({})\n", kt_string(note)), + None => String::new(), + }; if docs.trim().is_empty() { - return String::new(); + return deprecated; } let escaped = docs.replace("/*", "/*").replace("*/", "*/"); let mut out = format!("{indent}/**\n"); @@ -4125,12 +4217,26 @@ fn docs(docs: &str, indent: &str) -> String { } } let _ = writeln!(out, "{indent} */"); - out + out + &deprecated } -/// A field's docs, before it in a constructor's parameters. -fn docs_inline(text: &str, indent: &str) -> String { - docs(text, indent) +/// A Kotlin string literal of `text`, which no template reads. +fn kt_string(text: &str) -> String { + let mut out = String::from("\""); + for c in text.chars() { + match c { + '"' | '\\' | '$' => { + out.push('\\'); + out.push(c); + } + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c => out.push(c), + } + } + out.push('"'); + out } /// Code indented by one tab more. diff --git a/ffi/src/lock.rs b/ffi/src/lock.rs index 79abc195b..f3823c624 100644 --- a/ffi/src/lock.rs +++ b/ffi/src/lock.rs @@ -884,6 +884,7 @@ mod tests { span: DUMMY_SP, on: On::ALL, docs: String::new(), + deprecated: None, receiver: None, params: vec![], units: vec![], @@ -926,6 +927,7 @@ mod tests { span: DUMMY_SP, on: On::ALL, docs: String::new(), + deprecated: None, fields: vec![], tuple: false, methods: vec![], @@ -1011,6 +1013,7 @@ mod tests { span: DUMMY_SP, on: On::ALL, docs: String::new(), + deprecated: None, sync: true, send: true, copy: false, diff --git a/ffi/src/main.rs b/ffi/src/main.rs index eb4b1c054..19f390c1a 100644 --- a/ffi/src/main.rs +++ b/ffi/src/main.rs @@ -22,6 +22,7 @@ extern crate rustc_lexer; extern crate rustc_metadata; extern crate rustc_middle; extern crate rustc_parse; +extern crate rustc_resolve; extern crate rustc_session; extern crate rustc_span; extern crate rustc_structures; @@ -36,6 +37,7 @@ mod collect; mod config; mod cpp; mod dart; +mod doc; mod driver; mod glue; mod go; diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index d64254157..6fb94f73c 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -182,7 +182,21 @@ impl Maps { } } -/// `item` with what may differ between targets alike cleared: its span, docs, targets, +/// `ours` with each link `theirs` resolves too: a link to an item one target lacks resolves +/// only where it has it, and each binding drops the links it cannot follow. Docs that +/// differ in more than links, as `cfg_attr` can make them, keep the side that resolves more. +fn linked(ours: &mut String, theirs: String) { + if let Some(merged) = crate::doc::merge(ours, &theirs) { + *ours = merged; + return; + } + let links = |docs: &str| docs.matches(crate::doc::LINK).count(); + if links(&theirs) > links(ours) { + *ours = theirs; + } +} + +/// `item` with what may differ between targets alike cleared: its span, docs, deprecation, targets, /// and `clear`'s, which clears its members, compared on their own. fn bare(item: &T, clear: impl Fn(&mut T)) -> T { let mut item = item.clone(); @@ -194,6 +208,7 @@ pub(crate) fn bare_function(f: &Function) -> Function { bare(f, |f| { f.span = DUMMY_SP; f.docs.clear(); + f.deprecated = None; f.on = On::ALL; }) } @@ -202,9 +217,13 @@ pub(crate) fn bare_record(r: &Record) -> Record { bare(r, |r| { r.span = DUMMY_SP; r.docs.clear(); + r.deprecated = None; r.on = On::ALL; r.methods.clear(); - r.fields.iter_mut().for_each(|f| f.docs.clear()); + r.fields.iter_mut().for_each(|f| { + f.docs.clear(); + f.deprecated = None; + }); // Merged apart: one binding holds the largest, and each target asserts its own size. if let Some(opaque) = &mut r.opaque { opaque.size = 0; @@ -220,6 +239,7 @@ pub(crate) fn bare_enum(e: &Enum) -> Enum { bare(e, |e| { e.span = DUMMY_SP; e.docs.clear(); + e.deprecated = None; e.on = On::ALL; e.methods.clear(); e.variants.clear(); @@ -232,7 +252,10 @@ pub(crate) fn bare_variant(v: &Variant) -> Variant { v.on = On::ALL; // Compared apart, as only a plain enum's matter. v.discriminant = 0; - v.fields.iter_mut().for_each(|f| f.docs.clear()); + v.fields.iter_mut().for_each(|f| { + f.docs.clear(); + f.deprecated = None; + }); }) } @@ -240,6 +263,7 @@ pub(crate) fn bare_object(o: &Object) -> Object { bare(o, |o| { o.span = DUMMY_SP; o.docs.clear(); + o.deprecated = None; o.on = On::ALL; o.methods.clear(); o.variants.clear(); @@ -266,6 +290,7 @@ pub(crate) fn bare_callback(c: &Callback) -> Callback { bare(c, |c| { c.span = DUMMY_SP; c.docs.clear(); + c.deprecated = None; c.on = On::ALL; c.methods = c.methods.iter().map(bare_function).collect(); }) @@ -275,6 +300,7 @@ pub(crate) fn bare_constant(c: &Constant) -> Constant { bare(c, |c| { c.span = DUMMY_SP; c.docs.clear(); + c.deprecated = None; c.on = On::ALL; }) } @@ -445,6 +471,11 @@ impl Merged { let what = format!("struct `{}`", record.shown.join("::")); self.differ(what, (ours.on, ours.span), (record.on, record.span)); } + let ours = &mut self.api.records[at]; + linked(&mut ours.docs, record.docs); + for (field, theirs) in ours.fields.iter_mut().zip(record.fields) { + linked(&mut field.docs, theirs.docs); + } self.api.records[at].on.0 |= record.on.0; leaves(&mut self.api.records[at].traits, record.traits); if let (Some(ours), Some(theirs)) = (&mut self.api.records[at].opaque, record.opaque) { @@ -466,6 +497,7 @@ impl Merged { self.differ(what.clone(), (ours.on, ours.span), (e.on, e.span)); } self.variants(at, &e, what); + linked(&mut self.api.enums[at].docs, e.docs); self.api.enums[at].on.0 |= e.on.0; leaves(&mut self.api.enums[at].traits, e.traits); let methods = std::mem::take(&mut self.api.enums[at].methods); @@ -480,6 +512,7 @@ impl Merged { let what = format!("type `{}`", object.shown.join("::")); self.differ(what, (ours.on, ours.span), (object.on, object.span)); } + linked(&mut self.api.objects[at].docs, object.docs); self.api.objects[at].on.0 |= object.on.0; // Each variant is on the targets it is, after the one it follows in theirs. let mut after = 0; @@ -510,6 +543,10 @@ impl Merged { self.differ(what, (ours.on, ours.span), (callback.on, callback.span)); } let ours = &mut self.api.callbacks[at]; + linked(&mut ours.docs, callback.docs); + for (method, theirs) in ours.methods.iter_mut().zip(callback.methods) { + linked(&mut method.docs, theirs.docs); + } ours.on.0 |= callback.on.0; ours.methods.iter_mut().for_each(|m| m.on.0 |= callback.on.0); } @@ -525,6 +562,7 @@ impl Merged { let what = format!("const `{}`", constant.path.join("::")); self.differ(what, (ours.on, ours.span), (constant.on, constant.span)); } + linked(&mut self.api.constants[at].docs, constant.docs); self.api.constants[at].on.0 |= constant.on.0; } } @@ -546,6 +584,7 @@ impl Merged { self.differ(what, (ours[at].on, ours[at].span), (function.on, function.span)); } ours[at].on.0 |= function.on.0; + linked(&mut ours[at].docs, function.docs); } ours } @@ -803,9 +842,19 @@ mod tests { use rustc_span::DUMMY_SP; - use super::{On, cycle, order_crates}; + use super::{On, cycle, linked, order_crates}; use crate::ir::{Api, Enum, Field, Home, Traits, Type, Variant}; + /// Docs keep the target's whose links resolve more, as one lacking an item does not. + #[test] + fn docs_keep_the_most_links() { + let mut docs = "Joins a `Spawned`.".to_string(); + linked(&mut docs, "Joins a [`Spawned`](rust2:api::Spawned).".to_string()); + assert_eq!(docs, "Joins a [`Spawned`](rust2:api::Spawned)."); + linked(&mut docs, "Joins a `Spawned`.".to_string()); + assert_eq!(docs, "Joins a [`Spawned`](rust2:api::Spawned)."); + } + #[test] fn names_a_cycle_across_targets() { // `a` names `c`'s types on the first target and `c` names `a`'s on the second, while @@ -836,12 +885,14 @@ mod tests { span: DUMMY_SP, on: On(on), docs: String::new(), + deprecated: None, variants: vec![Variant { name: "V".into(), discriminant: 0, fields: vec![Field { name: "0".into(), docs: String::new(), + deprecated: None, ty: Type::Enum(ty), }], tuple: true, @@ -885,6 +936,7 @@ mod tests { span: DUMMY_SP, on: On::ALL, docs: String::new(), + deprecated: None, value: crate::ir::Literal::Bool(true), }], crates: vec!["f".into()], diff --git a/ffi/src/python.rs b/ffi/src/python.rs index ccab638ff..a8e78dc0b 100644 --- a/ffi/src/python.rs +++ b/ffi/src/python.rs @@ -27,6 +27,7 @@ use std::hash::Hasher; use rustc_data_structures::stable_hash::StableHasher; use crate::abi::{self, Abi, Ty, pascal}; +use crate::doc; use crate::ir::{Access, Family, Function, Int, Literal, On, Param, Receiver, Traits, Type}; use crate::kotlin::{indent_by, rust_c, strip_refs}; @@ -104,10 +105,15 @@ const TAKEN: &[&str] = &[ "_bytearray", "_object", "_range", + "_deprecated", + "_T", "ForeignReader", "Duration", ]; +/// The module's `@_deprecated`, which `TAKEN` keeps an export from shadowing. +const DEPRECATOR: &str = "_T = _typing.TypeVar(\"_T\")\n\nif _typing.TYPE_CHECKING:\n\tfrom typing_extensions import deprecated as _deprecated\nelse:\n\n\tdef _deprecated(message: _str, /) -> _typing.Callable[[_T], _T]:\n\t\t\"\"\"Marks a deprecated item for type checkers.\"\"\"\n\t\treturn lambda item: item\n"; + /// Any buffer, as Python before 3.12's `collections.abc.Buffer` spells it. const BUFFER: &str = "_bytes | _bytearray | _memoryview"; @@ -300,6 +306,27 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result| { + let (role, target) = g.link(link.target)?; + Some(match link.text { + Some(text) => format!(":{role}:`{} <{target}>`", text.replace('`', "")), + None => format!(":{role}:`{target}`"), + }) + }; + let body = doc::links(&body, abi.api, render); let glue = format!( "//! Generated by rust2-ffi: the CPython extension `python/{p}.py` loads, over the C ABI of {packages}.\n\n\ #![allow(non_snake_case, non_upper_case_globals, unused_mut, unused_unsafe, unused_parens, unused_variables, clippy::all)]\n\n\ @@ -349,6 +376,7 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result(), ); + let glue = doc::links(&glue, abi.api, render); Ok(Output { names: g.locked, python: body, @@ -811,7 +839,11 @@ impl<'a> Gen<'a> { Literal::Bool(false) => "False".to_string(), Literal::Int(_, v) => v.to_string(), }; - let _ = write!(self.top, "{name} = {value}\n{}\n", docstring(&constant.docs, "")); + let _ = write!( + self.top, + "{name} = {value}\n{}\n", + docstring(&deprecation(&constant.docs, constant.deprecated.as_deref()), "") + ); } for i in 0..api.records.len() { self.record(i); @@ -1294,8 +1326,9 @@ impl<'a> Gen<'a> { ); let _ = write!( self.py, - "class {name}(_n.Value):\n{}{}\n\n", - docstring(text.trim(), "\t"), + "{}class {name}(_n.Value):\n{}{}\n\n", + deprecator(record.deprecated.as_deref()), + docstring(&deprecation(text.trim(), record.deprecated.as_deref()), "\t"), body.members().join("\n") ); let _ = write!( @@ -1308,14 +1341,15 @@ impl<'a> Gen<'a> { .map(|f| Slot { name: field_name(&f.name), ty: self.py_field(&f.ty), - docs: f.docs.clone(), + docs: deprecation(&f.docs, f.deprecated.as_deref()), same: own_eq(abi, &f.ty), }) .collect(); - let docs = format!("{rust}\n\n{}", record.docs); + let docs = deprecation(&format!("{rust}\n\n{}", record.docs), record.deprecated.as_deref()); let _ = write!( self.py, - "{}\n\n", + "{}{}\n\n", + deprecator(record.deprecated.as_deref()), record_class(&name, "_Record", &docs, &fields, &body.members()) ); // The glue. @@ -1383,8 +1417,12 @@ impl<'a> Gen<'a> { .collect(); let _ = write!( self.py, - "class {name}(_enum.Enum):\n{}{entries}{}\n\n", - docstring(&format!("{rust}\n\n{}", e.docs), "\t"), + "{}class {name}(_enum.Enum):\n{}{entries}{}\n\n", + deprecator(e.deprecated.as_deref()), + docstring( + &deprecation(&format!("{rust}\n\n{}", e.docs), e.deprecated.as_deref()), + "\t" + ), body.members().iter().map(|m| format!("\n{m}")).collect::() ); return; @@ -1411,8 +1449,12 @@ impl<'a> Gen<'a> { } let _ = write!( self.py, - "class {name}:\n{}\t__slots__ = ()\n{}\n\n", - docstring(&format!("{rust}\n\n{}", e.docs), "\t"), + "{}class {name}:\n{}\t__slots__ = ()\n{}\n\n", + deprecator(e.deprecated.as_deref()), + docstring( + &deprecation(&format!("{rust}\n\n{}", e.docs), e.deprecated.as_deref()), + "\t" + ), body.members().iter().map(|m| format!("\n{m}")).collect::() ); let mut reads = Vec::new(); @@ -1505,8 +1547,9 @@ impl<'a> Gen<'a> { ); let _ = write!( self.py, - "class {name}(_n.Object):\n{}{}\n\n", - docstring(text.trim(), "\t"), + "{}class {name}(_n.Object):\n{}{}\n\n", + deprecator(object.deprecated.as_deref()), + docstring(&deprecation(text.trim(), object.deprecated.as_deref()), "\t"), body.members().join("\n") ); } @@ -1536,11 +1579,22 @@ impl<'a> Gen<'a> { .map(|(name, p)| format!("{name}: {}", self.py_lent(&p.ty))), ) .collect(); + // Type checkers flag a call of a deprecated method of an implementation too. + let deprecated = match deprecator(method.deprecated.as_deref()) { + d if d.is_empty() => d, + d => format!("\t{d}"), + }; body.push(format!( - "\t@_abc.abstractmethod\n\tdef {member}({}) -> {}:\n{}\t\t...\n", + "{deprecated}\t@_abc.abstractmethod\n\tdef {member}({}) -> {}:\n{}\t\t...\n", params.join(", "), self.py_param(&method.ok), - docstring(&method.docs, "\t\t") + docstring( + &deprecation( + &self.function_docs(method, doc::sections(&method.docs).body), + method.deprecated.as_deref(), + ), + "\t\t" + ) )); let c_params: Vec = method.params.iter().map(|p| abi.ty(&p.ty)).collect(); let c_ret = abi.ty(&method.ok); @@ -1564,8 +1618,9 @@ impl<'a> Gen<'a> { ); let _ = write!( self.py, - "class {name}(_abc.ABC):\n{}\t__slots__ = ()\n\n{}\n\n", - docstring(text.trim(), "\t"), + "{}class {name}(_abc.ABC):\n{}\t__slots__ = ()\n\n{}\n\n", + deprecator(callback.deprecated.as_deref()), + docstring(&deprecation(text.trim(), callback.deprecated.as_deref()), "\t"), body.join("\n") ); let _ = write!( @@ -1660,6 +1715,91 @@ impl<'a> Gen<'a> { } } + /// `text`, a function's docs without its sections, then its `# Errors` as what it + /// raises, and its `# Panics` as when it aborts. + fn function_docs(&mut self, function: &Function, text: String) -> String { + let sections = doc::sections(&function.docs); + let mut text = text.trim().to_string(); + let section = |title: &str, body: &str| { + let body: String = body + .lines() + .map(|l| format!("\n {l}").trim_end().to_string()) + .collect(); + format!("\n\n{title}:{body}") + }; + match (§ions.errors, &function.err) { + (Some(errors), Some(err)) => { + let thrown = self.thrown(err); + text.push_str(§ion("Raises", &format!("{thrown}: {errors}"))); + } + (Some(errors), None) => text.push_str(§ion("Errors", errors)), + (None, _) => {} + } + if let Some(panics) = §ions.panics { + text.push_str(§ion("Aborts", panics)); + } + text.trim().to_string() + } + + /// The Sphinx role and target a link names for `target`, if Python has it. + fn link(&self, target: doc::Target<'_>) -> Option<(&'static str, String)> { + let abi = self.abi; + let owner = |owner: doc::Owner| match owner { + doc::Owner::Record(i) => self.class(&abi.record(i)), + doc::Owner::Enum(i) => self.class(&abi.enumeration(i)), + doc::Owner::Object(i) => self.class(&abi.object(i)), + doc::Owner::Callback(i) => self.class(&abi.callback(i)), + }; + Some(match target { + doc::Target::Record(i) => ("class", owner(doc::Owner::Record(i))), + doc::Target::Enum(i) => ("class", owner(doc::Owner::Enum(i))), + doc::Target::Object(i) => ("class", owner(doc::Owner::Object(i))), + doc::Target::Callback(i) => ("class", owner(doc::Owner::Callback(i))), + doc::Target::Variant(i, v) => { + let e = &abi.api.enums[i]; + let name = &e.variants[v].name; + match e.plain() { + true => ( + "attr", + format!("{}.{}", owner(doc::Owner::Enum(i)), abi::snake(name).to_uppercase()), + ), + // As its class is named, apart from its siblings'. + false => ( + "class", + format!( + "{}.{}", + owner(doc::Owner::Enum(i)), + variant_classes(e.variants.iter().map(|v| v.name.as_str())).swap_remove(v) + ), + ), + } + } + doc::Target::Field(i, n) => ( + "attr", + format!( + "{}.{}", + owner(doc::Owner::Record(i)), + field_name(&abi.api.records[i].fields[n].name) + ), + ), + doc::Target::Constant(c) => ( + "data", + self.locked.get(&format!("const {}", c.path.join("::")))?.clone(), + ), + doc::Target::Function(of, f) => { + let member = self.locked.get(&crate::lock::function_key(f))?; + let role = match f.access { + Access::Field { .. } | Access::Const => "attr", + _ => "meth", + }; + match of { + Some(of) => (role, format!("{}.{member}", owner(of))), + None => ("func", member.clone()), + } + } + }) + } + /// The registry's index of the exception class an error of type `e` raises. fn exception(&mut self, e: &Type) -> String { let name = self.thrown(e); @@ -1997,7 +2137,7 @@ impl<'a> Gen<'a> { )); } // The Python. - let mut text = function.docs.clone(); + let mut text = doc::sections(&function.docs).body; if handed.is_some() { text.push_str( "\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes.", @@ -2032,9 +2172,28 @@ impl<'a> Gen<'a> { )); } } - let body = stmts.join("\n\t\t"); + let text = deprecation(&self.function_docs(function, text), function.deprecated.as_deref()); // An `async def` stays Python's, as callers may need a coroutine. let direct = !constant && (export.future.is_none() || function.eager); + // A call of a deprecated function warns, as Python's own deprecations do. + if let Some(note) = &function.deprecated { + let what = match &owner_c { + Some(c) => format!("{}.{member}() is deprecated", self.class(c)), + None => format!("{member}() is deprecated"), + }; + let warning = match note.is_empty() { + true => what, + false => format!("{what}: {note}"), + }; + // The caller's frame is the first, or the second past the Python that calls the + // glue: an `async def`'s, or a constant's getter. + let level = match direct { + true => 1, + false => 2, + }; + stmts.insert(0, format!("rt::deprecated({}, {level})?;", c_str(&warning))); + } + let body = stmts.join("\n\t\t"); let property = matches!(function.access, Access::Field { set: false, .. }) && place == Place::Member; match direct { true => { @@ -2072,6 +2231,7 @@ impl<'a> Gen<'a> { (true, true) => format!("def {member}({params}) -> _typing.Awaitable[{ret}]:\n{docs}\t..."), (false, _) => format!("def {member}({params}) -> {ret}:\n{docs}\t..."), }; + let code = format!("{}{code}", deprecator(function.deprecated.as_deref())); let code = match (function.access, place) { (Access::Const, Place::Top) if constant => { let name = member.clone(); @@ -2304,6 +2464,42 @@ fn c_str(text: &str) -> String { format!("c{text:?}") } +/// `@_deprecated` with `deprecated`'s note, which type checkers read, where it has one. +fn deprecator(deprecated: Option<&str>) -> String { + match deprecated { + Some(note) => format!("@_deprecated({})\n", py_str(note)), + None => String::new(), + } +} + +/// `docs`, then the note of `deprecated`, where it has one. +fn deprecation(docs: &str, deprecated: Option<&str>) -> String { + match deprecated { + Some("") => format!("{docs}\n\nDeprecated."), + Some(note) => format!("{docs}\n\nDeprecated: {note}"), + None => docs.to_string(), + } + .trim() + .to_string() +} + +/// A Python string literal of `text`. +fn py_str(text: &str) -> String { + let mut out = String::from("\""); + for c in text.chars() { + match c { + '"' | '\\' => { + out.push('\\'); + out.push(c); + } + c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + /// A docstring holding `docs`, each line indented by `indent`, or nothing for none. fn docstring(docs: &str, indent: &str) -> String { let docs = docs.trim(); @@ -2423,9 +2619,23 @@ fn record_class(name: &str, bases: &str, docs: &str, fields: &[Slot], members: & #[cfg(test)] mod tests { - use super::{member, param_name, param_names, variant_classes}; + use super::{DEPRECATOR, TAKEN, member, param_name, param_names, variant_classes}; use crate::ir::{Param, Type}; + /// Every name the deprecation helper binds is taken, so no export shadows it. + #[test] + fn deprecator_names_taken() { + for line in DEPRECATOR.lines() { + let line = line.trim_start(); + let name = (line.strip_prefix("def ").map(|rest| rest.split('(').next().unwrap())) + .or_else(|| line.split_once(" as ").map(|(_, name)| name)) + .or_else(|| line.split_once(" = ").map(|(name, _)| name)); + if let Some(name) = name { + assert!(TAKEN.contains(&name), "the helper's `{name}` is not in TAKEN"); + } + } + } + #[test] fn params_keep_apart() { let params = |names: &[&str]| { diff --git a/ffi/src/swift.rs b/ffi/src/swift.rs index 952f7a2fb..95ad38117 100644 --- a/ffi/src/swift.rs +++ b/ffi/src/swift.rs @@ -26,6 +26,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fmt::Write; use crate::abi::{self, Abi, Ty, pascal}; +use crate::doc; use crate::ir::{Access, Closure, Family, Function, Int, Literal, Mutability, On, Param, Receiver, Type}; const RUNTIME: &str = include_str!("../runtime/rt.swift"); @@ -62,6 +63,7 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result, packages: &str, contract: u64) -> Result| match link.text { + Some(_) => None, + None => g.link(link.target), + }; + let (types, top) = ( + doc::links(&g.types, abi.api, render), + doc::links(&g.top, abi.api, render), + ); + (g.types, g.top) = (types, top); let p = &abi.prefix; let upper = p.to_uppercase(); let module = module(p); @@ -242,6 +254,8 @@ struct Arg { struct Gen<'a> { locked: BTreeMap, + /// Each function's name as DocC links it, by its [`crate::lock::function_key`]. + docc: HashMap, abi: &'a Abi<'a>, /// Each exported type's name, by its C name. classes: HashMap, @@ -756,7 +770,7 @@ impl<'a> Gen<'a> { let _ = write!( self.top, "{}public let {name}: {ty} = {value}\n\n", - docs(&constant.docs, "") + docs(&constant.docs, constant.deprecated.as_deref(), "") ); } for i in 0..api.records.len() { @@ -1066,8 +1080,33 @@ impl<'a> Gen<'a> { .map(|f| (field_name(&f.name), self.sw(&f.ty))) .collect(); let mut members: Vec = fields.iter().map(|(f, _)| unquote(f)).collect(); - let mut body: Vec = (record.fields.iter().zip(&fields)) - .map(|(f, (name, sw))| format!("{}\tpublic var {name}: {sw}\n", docs(&f.docs, "\t"))) + // A deprecated field is stored apart, under `_` and its name, so its own code's uses + // do not warn as a caller's do: Swift has no way to silence one. + // Apart from the fields and the record's own `_lift` and `_lower` too. + let mut stored: Vec = Vec::new(); + for (f, (name, _)) in record.fields.iter().zip(&fields) { + let mut name = match f.deprecated { + Some(_) => format!("_{}", unquote(name)), + None => name.clone(), + }; + while f.deprecated.is_some() + && (["_lift", "_lower"].contains(&name.as_str()) || members.contains(&name) || stored.contains(&name)) + { + name.push('_'); + } + stored.push(name); + } + members.extend(stored.iter().filter(|s| !fields.iter().any(|(f, _)| f == *s)).cloned()); + let mut body: Vec = (record.fields.iter().zip(&fields).zip(&stored)) + .map(|((f, (name, sw)), stored)| { + let docs = docs(&f.docs, f.deprecated.as_deref(), "\t"); + match f.deprecated { + Some(_) => format!( + "\tvar {stored}: {sw}\n\n{docs}\tpublic var {name}: {sw} {{\n\t\tget {{ {stored} }}\n\t\tset {{ {stored} = newValue }}\n\t}}\n" + ), + None => format!("{docs}\tpublic var {name}: {sw}\n"), + } + }) .collect(); let params: Vec = fields .iter() @@ -1076,7 +1115,9 @@ impl<'a> Gen<'a> { false => format!("{f}: {sw}"), }) .collect(); - let assigns: String = fields.iter().map(|(f, _)| format!("\t\tself.{f} = {f}\n")).collect(); + let assigns: String = (fields.iter().zip(&stored)) + .map(|((f, _), stored)| format!("\t\tself.{stored} = {f}\n")) + .collect(); body.push(format!("\tpublic init({}) {{\n{assigns}\t}}\n", params.join(", "))); let mut protocols = self.sendable(&ty); self.traits(&ty, &c, record.traits, &mut body, &mut members, &mut protocols); @@ -1093,9 +1134,9 @@ impl<'a> Gen<'a> { } }) .collect(); - let lowered: Vec = (record.fields.iter().zip(&fields)) - .map(|(f, (name, _))| { - let value = self.lower(&f.ty, &format!("self.{name}")); + let lowered: Vec = (record.fields.iter().zip(&stored)) + .map(|(f, stored)| { + let value = self.lower(&f.ty, &format!("self.{stored}")); format!("{}: {value}", abi::escape(&f.name)) }) .collect(); @@ -1119,7 +1160,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}public struct {name}{} {{\n{}}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), record.deprecated.as_deref(), ""), conform(&protocols), body.join("\n") ); @@ -1150,7 +1191,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}public struct {name}{} {{\n{}}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), record.deprecated.as_deref(), ""), conform(&protocols), body.join("\n") ); @@ -1261,7 +1302,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}public enum {name}{} {{\n{}}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), e.deprecated.as_deref(), ""), conform(&protocols), body.join("\n") ); @@ -1320,7 +1361,7 @@ impl<'a> Gen<'a> { self.methods(&object.methods, &owner, &ty, &mut body, &mut members); self.distinct(&rust, &members); let text = format!("{rust}\n\n{}", object.docs); - let docs = docs(text.trim(), ""); + let docs = docs(text.trim(), object.deprecated.as_deref(), ""); let body = body.join("\n"); if !unique { let _ = write!( @@ -1361,6 +1402,10 @@ impl<'a> Gen<'a> { for method in &callback.methods { let member = member(&abi::snake(method.name()), &[]); crate::lock::function(&mut self.locked, method, &member); + self.docc.insert( + crate::lock::function_key(method), + docc_call(&member, method.params.iter().map(|_| "_")), + ); members.push(full(false, &member, method.params.iter().map(|_| "_".to_string()))); let params: Vec = (method.params.iter().zip(locals(&method.params))) .map(|(p, name)| format!("_ {name}: {}", self.sw(&p.ty))) @@ -1369,9 +1414,18 @@ impl<'a> Gen<'a> { Type::Unit => String::new(), _ => format!(" -> {}", self.sw(&method.ok)), }; + // The trampoline calls the requirement, which an `@available` deprecation would warn + // of, and Swift has no way to silence one: its docs say it instead, to the + // implementation Rust calls. + let mut text = self.function_docs(method, doc::sections(&method.docs).body); + match method.deprecated.as_deref() { + Some("") => text.push_str("\n\nDeprecated."), + Some(note) => text.push_str(&format!("\n\nDeprecated: {note}")), + None => {} + } body.push(format!( "{}\tfunc {member}({}){ret}", - docs(&method.docs, "\t"), + docs(text.trim(), None, "\t"), params.join(", ") )); let ps: Vec = (0..method.params.len()).map(|k| format!("p{k}_")).collect(); @@ -1399,7 +1453,7 @@ impl<'a> Gen<'a> { let _ = write!( self.types, "{}public protocol {name}: Sendable {{\n{}\n}}\n\n", - docs(text.trim(), ""), + docs(text.trim(), callback.deprecated.as_deref(), ""), body.join("\n\n") ); let _ = write!( @@ -2084,7 +2138,7 @@ impl<'a> Gen<'a> { None => body.push(code), } - let mut text = function.docs.clone(); + let mut text = doc::sections(&function.docs).body; for k in left { text.push_str(&format!("\n\nWithout `{}`, as Rust's `None`.", unquote(&names[*k]))); } @@ -2181,7 +2235,19 @@ impl<'a> Gen<'a> { true => format!("get throws {{\n{}\n}}", indent(&body)), false => body, }; - let code = format!("{}{head} {{\n{}\n}}\n", docs(text.trim(), ""), indent(&body)); + self.docc.insert( + crate::lock::function_key(function), + match var { + true => unquote(&member), + false => docc_call(&member, labels.iter().map(String::as_str)), + }, + ); + let text = self.function_docs(function, text); + let code = format!( + "{}{head} {{\n{}\n}}\n", + docs(&text, function.deprecated.as_deref(), ""), + indent(&body) + ); (code, full(is_static, &member, labels)) } @@ -2210,6 +2276,66 @@ impl<'a> Gen<'a> { } } + /// `text`, a function's docs without its sections, then its `# Errors` as what it throws, + /// and its `# Panics` as when it aborts. + fn function_docs(&mut self, function: &Function, text: String) -> String { + let sections = doc::sections(&function.docs); + let mut text = text.trim().to_string(); + if let Some(panics) = §ions.panics { + let _ = write!(text, "\n\n# Aborts\n\n{panics}"); + } + match (§ions.errors, &function.err) { + (Some(errors), Some(err)) => { + let thrown = match self.thrown(err) { + Thrown::Itself => self.sw(err), + Thrown::Wrapped(name) => name, + }; + let _ = write!(text, "\n\n- Throws: ``{thrown}``: {errors}"); + } + (Some(errors), None) => { + let _ = write!(text, "\n\n# Errors\n\n{errors}"); + } + (None, _) => {} + } + text.trim().to_string() + } + + /// The DocC symbol link for `target`, if Swift has it. + fn link(&self, target: doc::Target<'_>) -> Option { + let abi = self.abi; + let owner = |owner: doc::Owner| match owner { + doc::Owner::Record(i) => self.class(&abi.record(i)), + doc::Owner::Enum(i) => self.class(&abi.enumeration(i)), + doc::Owner::Object(i) => self.class(&abi.object(i)), + doc::Owner::Callback(i) => self.class(&abi.callback(i)), + }; + let path = match target { + doc::Target::Record(i) => owner(doc::Owner::Record(i)), + doc::Target::Enum(i) => owner(doc::Owner::Enum(i)), + doc::Target::Object(i) => owner(doc::Owner::Object(i)), + doc::Target::Callback(i) => owner(doc::Owner::Callback(i)), + doc::Target::Variant(i, v) => format!( + "{}/{}", + owner(doc::Owner::Enum(i)), + unquote(&member(&abi::snake(&abi.api.enums[i].variants[v].name), &["init"])) + ), + doc::Target::Field(i, n) => format!( + "{}/{}", + owner(doc::Owner::Record(i)), + unquote(&field_name(&abi.api.records[i].fields[n].name)) + ), + doc::Target::Constant(c) => self.locked.get(&format!("const {}", c.path.join("::")))?.clone(), + doc::Target::Function(of, f) => { + let member = self.docc.get(&crate::lock::function_key(f))?; + match of { + Some(of) => format!("{}/{member}", owner(of)), + None => member.clone(), + } + } + }; + Some(format!("``{path}``")) + } + /// How an error of type `err` is thrown: as itself if an exported type, which then /// conforms to `Swift.Error`, or else in a struct of its own. fn thrown(&mut self, err: &Type) -> Thrown { @@ -2442,6 +2568,12 @@ fn full(is_static: bool, name: &str, labels: impl IntoIterator) - } } +/// A function's name as DocC links it: with its argument labels. +fn docc_call<'l>(name: &str, labels: impl IntoIterator) -> String { + let labels: String = labels.into_iter().map(|l| format!("{l}:")).collect(); + format!("{}({labels})", unquote(name)) +} + /// A name without the backticks quoting a keyword. fn unquote(name: &str) -> String { name.trim_matches('`').to_string() @@ -2599,8 +2731,7 @@ fn inlinable(swift: &str) -> String { written = Some(format!("{tabs}{attributes}{attribute}{modifiers}{rest}")); } } - let opens = line.matches('{').count(); - let closes = line.matches('}').count(); + let (opens, closes) = braces(line); if !code.starts_with("//") { match opens.cmp(&closes) { std::cmp::Ordering::Greater => { @@ -2622,14 +2753,42 @@ fn inlinable(swift: &str) -> String { out } -/// Swift doc comments holding `docs`, each line indented by `indent`, or nothing for none. -fn docs(docs: &str, indent: &str) -> String { - docs.lines() +/// The braces `line` opens and closes outside its string literals, such as a deprecation's +/// message, whose escapes, `\u{301}` among them, stay inside the literal. +fn braces(line: &str) -> (usize, usize) { + let (mut opens, mut closes) = (0, 0); + let mut chars = line.chars(); + let mut quoted = false; + while let Some(c) = chars.next() { + match (quoted, c) { + (true, '\\') => { + chars.next(); + } + (_, '"') => quoted = !quoted, + (false, '{') => opens += 1, + (false, '}') => closes += 1, + _ => {} + } + } + (opens, closes) +} + +/// Swift doc comments holding `docs`, each line indented by `indent`, or nothing for none, +/// and `@available(*, deprecated)` with its note where `deprecated` has one. +fn docs(docs: &str, deprecated: Option<&str>, indent: &str) -> String { + let mut out: String = docs + .lines() .map(|line| match line.is_empty() { true => format!("{indent}///\n"), false => format!("{indent}/// {line}\n"), }) - .collect() + .collect(); + match deprecated { + Some("") => out.push_str(&format!("{indent}@available(*, deprecated)\n")), + Some(note) => out.push_str(&format!("{indent}@available(*, deprecated, message: {note:?})\n")), + None => {} + } + out } /// Code indented by one tab more, but for blank lines. diff --git a/ffi/src/web.rs b/ffi/src/web.rs index b4e70a535..e47a503b5 100644 --- a/ffi/src/web.rs +++ b/ffi/src/web.rs @@ -32,6 +32,7 @@ use std::fmt::Write; use crate::abi::{self, Abi, Ty, pascal}; use crate::config::Package; +use crate::doc; use crate::glue::rs; use crate::ir::{Access, Closure, Family, Function, Int, Literal, Type}; use crate::kotlin::strip_refs; @@ -246,6 +247,13 @@ pub(crate) fn generate(abi: &Abi<'_>, facade: &Package, contract: u64) -> Result type_imports(&refs, "glue") ); files.push(("glue.ts".to_string(), glue)); + // Each module's local name of each export it renames, which its own links name. + let locals: HashMap> = (g.modules.iter()) + .map(|(name, module)| { + let locals = (module.renames.iter()).map(|(local, export)| (export.clone(), local.clone())); + (name.clone(), locals.collect()) + }) + .collect(); let mut index = g.modules.remove("index").unwrap_or_default(); let mut out = format!( "// Generated by rust2-ffi: TypeScript over the C ABI of the pub API of {packages}, for the web. Do not edit.\n\n\ @@ -281,9 +289,57 @@ pub(crate) fn generate(abi: &Abi<'_>, facade: &Package, contract: u64) -> Result } files.push((format!("{name}.ts"), trim(out))); } + // Each link once every name is final. + let mut namespaces = HashMap::new(); + for (name, ts) in &mut files { + let module = name.strip_suffix(".ts").unwrap_or(name); + // A link names its own module's item as the module does, and another module's + // through a type-only import of that module as a namespace, `$`, which reaches + // every export whether or not the module's code names it; either shows the name a + // caller writes. + let mut spaces = BTreeSet::new(); + let linked = doc::links(ts, abi.api, |link| { + let (home, local, shown) = g.link(link.target)?; + let target = match home == module { + // A renamed export is its local name in its own module, where the export binds + // no name: `URL$`, not the global `URL`. + true => { + let (head, rest) = local.split_once('.').map_or((&local[..], ""), |(h, r)| (h, r)); + match locals.get(module).and_then(|l| l.get(head)) { + Some(own) if rest.is_empty() => own.clone(), + Some(own) => format!("{own}.{rest}"), + None => local, + } + } + false => { + let target = format!("{home}$.{local}"); + spaces.insert(home); + target + } + }; + Some(match link.text.unwrap_or(&shown) { + text if text == target => format!("{{@link {target}}}"), + text => format!("{{@link {target} | {text}}}"), + }) + }); + let imports: String = (spaces.iter()) + .map(|space| format!("import type * as {space}$ from \"./{space}.ts\";\n")) + .collect(); + // After the header's line. + let at = linked.find('\n').map_or(0, |at| at + 1); + *ts = format!("{}{imports}{}", &linked[..at], &linked[at..]); + if !imports.is_empty() { + namespaces.insert(name.clone(), imports.replace(".ts\";", ".js\";")); + } + } let mut emitted = Vec::new(); for (name, ts) in &files { - let (js, dts) = crate::js::emit(name, ts)?; + let (js, mut dts) = crate::js::emit(name, ts)?; + // Declarations keep no import only a doc names, which the links need. + if let Some(imports) = namespaces.get(name) { + let at = dts.find('\n').map_or(0, |at| at + 1); + dts.insert_str(at, imports); + } let stem = name.strip_suffix(".ts").expect("each module is a .ts file"); emitted.push((format!("{stem}.js"), js)); emitted.push((format!("{stem}.d.ts"), dts)); @@ -424,6 +480,97 @@ impl<'a> Gen<'a> { &c[self.abi.prefix.len() + 1..] } + /// `text`, a function's docs without its sections, then its `# Errors`, naming the + /// error its `Err` holds, and its `# Panics` as when it aborts. + fn function_docs(&mut self, function: &Function, text: String) -> String { + let sections = doc::sections(&function.docs); + let mut text = text.trim().to_string(); + if let Some(errors) = §ions.errors { + let what = match &function.err { + Some(err) => format!("Its `Err` holds a `{}`: ", self.tt(err)), + None => String::new(), + }; + let _ = write!(text, "\n\n# Errors\n\n{what}{errors}"); + } + if let Some(panics) = §ions.panics { + let _ = write!(text, "\n\n# Aborts\n\n{panics}"); + } + text.trim().to_string() + } + + /// Where `target` is, if TypeScript has it: its module, the module's name for it, and + /// the name a caller writes, who imports a type's module as the type's name. A variant is + /// a tag of its union, which no declaration names. + /// None where the binding lacks it, as for an item off the web's target. + fn link(&self, target: doc::Target<'_>) -> Option<(String, String, String)> { + let abi = self.abi; + let api = abi.api; + let on = |owner: doc::Owner| match owner { + doc::Owner::Record(i) => api.records[i].on, + doc::Owner::Enum(i) => api.enums[i].on, + doc::Owner::Object(i) => api.objects[i].on, + doc::Owner::Callback(i) => api.callbacks[i].on, + }; + let here = match target { + doc::Target::Record(i) | doc::Target::Field(i, _) => self.here(on(doc::Owner::Record(i))), + doc::Target::Enum(i) => self.here(on(doc::Owner::Enum(i))), + doc::Target::Variant(i, v) => self.here(on(doc::Owner::Enum(i))) && self.here(api.enums[i].variants[v].on), + doc::Target::Object(i) => self.here(on(doc::Owner::Object(i))), + doc::Target::Callback(i) => self.here(on(doc::Owner::Callback(i))), + doc::Target::Constant(c) => self.here(c.on), + doc::Target::Function(of, f) => self.here(f.on) && of.is_none_or(|of| self.here(on(of))), + }; + if !here { + return None; + } + let owner = |owner: doc::Owner| match owner { + doc::Owner::Record(i) => self.class(&abi.record(i)), + doc::Owner::Enum(i) => self.class(&abi.enumeration(i)), + doc::Owner::Object(i) => self.class(&abi.object(i)), + doc::Owner::Callback(i) => self.class(&abi.callback(i)), + }; + let ty = |of: doc::Owner| { + let class = owner(of); + (class.clone(), class.clone(), class) + }; + Some(match target { + doc::Target::Record(i) => ty(doc::Owner::Record(i)), + doc::Target::Enum(i) => ty(doc::Owner::Enum(i)), + doc::Target::Object(i) => ty(doc::Owner::Object(i)), + doc::Target::Callback(i) => ty(doc::Owner::Callback(i)), + doc::Target::Variant(i, v) => { + let class = owner(doc::Owner::Enum(i)); + let tag = &abi.api.enums[i].variants[v].name; + (class.clone(), class.clone(), format!("{class} \"{tag}\"")) + } + doc::Target::Field(i, n) => { + let class = owner(doc::Owner::Record(i)); + let field = format!("{class}.{}", field_names(&abi.api.records[i].fields)[n]); + (class, field.clone(), field) + } + doc::Target::Constant(c) => { + let name = self.locked.get(&format!("const {}", c.path.join("::")))?; + ("index".to_string(), name.clone(), name.clone()) + } + doc::Target::Function(of, f) => { + let member = self.locked.get(&crate::lock::function_key(f))?; + match of { + // A callback's method is its interface's member, not an export. + Some(of @ doc::Owner::Callback(_)) => { + let class = owner(of); + let member = format!("{class}.{member}"); + (class, member.clone(), member) + } + Some(of) => { + let class = owner(of); + (class.clone(), member.clone(), format!("{class}.{member}")) + } + None => ("index".to_string(), member.clone(), member.clone()), + } + } + }) + } + /// The TypeScript name of the C type `c`. fn class(&self, c: &str) -> String { self.classes.get(c).cloned().unwrap_or_else(|| pascal(self.bare(c))) @@ -1461,8 +1608,13 @@ fn param_name(name: &str) -> String { } } -/// JSDoc holding `docs`, each line indented by `indent`, or nothing for none. -fn docs(docs: &str, indent: &str) -> String { +/// JSDoc holding `docs`, each line indented by `indent`, or nothing for none, then +/// `@deprecated` with its note where `deprecated` has one. +fn docs(docs: &str, deprecated: Option<&str>, indent: &str) -> String { + let docs = match deprecated { + Some(note) => format!("{docs}\n\n@deprecated {note}"), + None => docs.to_string(), + }; let docs = docs.trim(); if docs.is_empty() { return String::new(); @@ -1975,7 +2127,10 @@ impl Gen<'_> { if local != name { self.out().renames.insert(local.clone(), name.clone()); } - let code = format!("{}export const {local}: {ty} = {value};\n\n", docs(&constant.docs, "")); + let code = format!( + "{}export const {local}: {ty} = {value};\n\n", + docs(&constant.docs, constant.deprecated.as_deref(), "") + ); self.out().body.push_str(&code); } for i in 0..api.records.len() { @@ -2039,14 +2194,27 @@ impl Gen<'_> { "{rust}\n\nIts bytes, which only Rust makes or reads: copy it, but never make one.\n\n{}", record.docs ); - format!("{}export type {name} = rt.Opaque<\"{name}\">;\n\n", docs(&text, "")) + format!( + "{}export type {name} = rt.Opaque<\"{name}\">;\n\n", + docs(&text, record.deprecated.as_deref(), "") + ) } None => { let fields: Vec = (record.fields.iter().zip(field_names(&record.fields))) - .map(|(f, name)| format!("{}\t{name}: {};\n", docs(&f.docs, "\t"), self.tt(&f.ty))) + .map(|(f, name)| { + format!( + "{}\t{name}: {};\n", + docs(&f.docs, f.deprecated.as_deref(), "\t"), + self.tt(&f.ty) + ) + }) .collect(); let text = format!("{rust}\n\n{}", record.docs); - format!("{}export type {name} = {{\n{}}};\n\n", docs(&text, ""), fields.concat()) + format!( + "{}export type {name} = {{\n{}}};\n\n", + docs(&text, record.deprecated.as_deref(), ""), + fields.concat() + ) } }; self.start(&name, declaration); @@ -2089,7 +2257,13 @@ impl Gen<'_> { false => format!("\n\t| {}", variants.join("\n\t| ")), }; let text = format!("{rust}\n\n{}", e.docs); - self.start(&name, format!("{}export type {name} = {union};\n\n", docs(&text, ""))); + self.start( + &name, + format!( + "{}export type {name} = {union};\n\n", + docs(&text, e.deprecated.as_deref(), "") + ), + ); let mut taken = BTreeSet::new(); self.traits(&ty, &c, e.traits, &mut taken); self.methods(&e.methods, &abi.ty(&ty), &ty, &mut taken); @@ -2112,7 +2286,10 @@ impl Gen<'_> { ); self.start( &name, - format!("{}export type {name} = rt.Handle<\"{name}\">;\n\n", docs(&text, "")), + format!( + "{}export type {name} = rt.Handle<\"{name}\">;\n\n", + docs(&text, object.deprecated.as_deref(), "") + ), ); let owner = Ty::Handle { name: c.clone(), @@ -2176,7 +2353,11 @@ impl Gen<'_> { let ok = self.tt(&method.ok); members.push(format!( "{}\t{member}({}): {ok};\n", - docs(&method.docs, "\t"), + docs( + &self.function_docs(method, doc::sections(&method.docs).body), + method.deprecated.as_deref(), + "\t" + ), params.join(", ") )); } @@ -2189,7 +2370,7 @@ impl Gen<'_> { &name, format!( "{}export interface {name} {{\n{}}}\n\n", - docs(&text, ""), + docs(&text, callback.deprecated.as_deref(), ""), members.join("\n") ), ); @@ -2651,7 +2832,7 @@ impl Gen<'_> { } self.module = module; - let mut text = function.docs.clone(); + let mut text = doc::sections(&function.docs).body; if handed.is_some() { text.push_str( "\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes.", @@ -2684,9 +2865,10 @@ impl Gen<'_> { if local != member { self.out().renames.insert(local.clone(), member.clone()); } + let text = self.function_docs(function, text); Some(format!( "{}export function {local}({}): {ret_t} {{\n{}\n}}\n", - docs(&text, ""), + docs(&text, function.deprecated.as_deref(), ""), params.join(", "), indent(&wrap(&lines)) )) @@ -2738,6 +2920,7 @@ mod tests { .map(|name| crate::ir::Field { name: name.to_string(), docs: String::new(), + deprecated: None, ty: Type::Unit, }) .collect() diff --git a/ffi/surface/api/c.h b/ffi/surface/api/c.h index 08d047e2a..34019f678 100644 --- a/ffi/surface/api/c.h +++ b/ffi/surface/api/c.h @@ -7,7 +7,7 @@ #ifdef __cplusplus extern "C" { #endif -#define API_CONTRACT ((uint64_t)0xe8ef8b7c46c50cebULL) +#define API_CONTRACT ((uint64_t)0x975c247cc8b7a808ULL) uint64_t api_contract(void); uint32_t api_target(void); typedef int32_t api_status; @@ -118,6 +118,7 @@ typedef struct api_Site api_Site; typedef struct api_Trail api_Trail; typedef struct api_Worker api_Worker; typedef struct api_Handle api_Handle; +typedef struct api_Holder api_Holder; typedef struct api_Area api_Area; typedef struct api_Counter api_Counter; typedef struct api_Meter api_Meter; @@ -813,6 +814,18 @@ typedef struct api_Qualifiers { double api; double kotlin; } api_Qualifiers; +typedef struct api_Deprecated { + bool on; + uint32_t lower; + bool deprecated; +} api_Deprecated; +typedef struct api_Dial { + uint64_t level; + uint64_t before; +} api_Dial; +typedef struct api_Knob { + uint64_t level; +} api_Knob; typedef struct api_polar_Turn { uint8_t part; } api_polar_Turn; @@ -1079,8 +1092,19 @@ typedef struct api_Beat { const api_Beat_vtable *vtable; void *data; } api_Beat; +typedef struct api_Turner_vtable { + void (*free)(void *data); + uint64_t (*by)(void *data); + uint64_t (*once)(void *data); +} api_Turner_vtable; +typedef struct api_Turner { + const api_Turner_vtable *vtable; + void *data; +} api_Turner; #define API_LIMIT ((uint64_t)1000ULL) #define API_FAR ((int64_t)9223372036854775807LL) +#define API_URL ((uint64_t)1000ULL) +#define API_STEP ((uint64_t)1ULL) void api_Parcel_free(api_Parcel *self); void api_Weighted_free(api_Weighted *self); uint64_t api_Weighted_total(const api_Weighted *self); @@ -1291,6 +1315,21 @@ bool api_a_eq(const api_a *a, const api_a *b); api_buf api_a_debug(const api_a *self); void api_Qualifiers_free(api_Qualifiers *self); bool api_Qualifiers_eq(const api_Qualifiers *a, const api_Qualifiers *b); +void api_Deprecated_free(api_Deprecated *self); +bool api_Deprecated_eq(const api_Deprecated *a, const api_Deprecated *b); +api_buf api_Deprecated_debug(const api_Deprecated *self); +api_Deprecated api_Deprecated_default(void); +void api_Dial_free(api_Dial *self); +bool api_Dial_eq(const api_Dial *a, const api_Dial *b); +api_buf api_Dial_debug(const api_Dial *self); +api_Dial api_Dial_default(void); +bool api_Dial_turn(const api_Dial *self, uint64_t by, api_Dial *out, api_Error *err); +api_Dial api_Dial_max(const api_Dial *self); +void api_Knob_free(api_Knob *self); +bool api_Knob_eq(const api_Knob *a, const api_Knob *b); +api_buf api_Knob_debug(const api_Knob *self); +api_Knob api_Knob_default(void); +uint64_t api_Knob_doubled(const api_Knob *self); void api_polar_Point_free(api_polar_Point *self); bool api_polar_Point_eq(const api_polar_Point *a, const api_polar_Point *b); api_buf api_polar_Point_debug(const api_polar_Point *self); @@ -1565,6 +1604,10 @@ api_Handle_later_future *api_Handle_later(uint32_t count); api_poll api_Handle_later_start(uint32_t count, api_Handle **out, api_Handle_later_future **future); api_poll api_Handle_later_poll(api_Handle_later_future *future, api_waker waker, api_Handle **out); void api_Handle_later_future_free(api_Handle_later_future *future); +void api_Holder_free(api_Holder *self); +api_Holder *api_Holder_new(uint64_t level); +uint64_t api_Holder_level_get(const api_Holder *self); +uint64_t api_Holder_doubled(const api_Holder *self); void api_Area_free(api_Area *self); bool api_Area_borrowed(const api_Area *self); api_Area *api_Area_clone(const api_Area *self); @@ -2271,6 +2314,14 @@ api_socket_addr api_same_socket_addr(api_socket_addr v); api_socket_addr_v4 api_same_socket_addr_v4(api_socket_addr_v4 v); api_socket_addr_v6 api_same_socket_addr_v6(api_socket_addr_v6 v); api_ip_addr api_same_ip_addr(api_ip_addr v); +uint8_t api_deprecated(uint8_t note); +api_Knob api_knob(api_Dial dial); +typedef struct api_level_later_future api_level_later_future; +api_level_later_future *api_level_later(api_Dial dial); +api_poll api_level_later_start(api_Dial dial, uint64_t *out, api_level_later_future **future); +api_poll api_level_later_poll(api_level_later_future *future, api_waker waker, uint64_t *out); +void api_level_later_future_free(api_level_later_future *future); +bool api_turned(api_Dial dial, api_Turner turner, api_Dial *out, api_Error *err); uint64_t api_crowded(api_Reading reading, api_Stamp a, api_Stamp b, uint64_t n0, uint64_t n1, uint64_t n2, uint64_t n3, uint64_t n4, uint64_t n5, uint64_t n6, uint64_t n7, uint64_t n8, uint64_t n9, uint64_t n10, uint64_t n11, uint64_t n12, uint64_t n13, uint64_t n14, uint64_t n15, uint64_t n16, uint64_t n17, uint64_t n18, uint64_t n19, uint64_t n20, uint64_t n21, uint64_t n22, uint64_t n23, uint64_t n24, uint64_t n25, uint64_t n26, uint64_t n27, uint64_t n28, uint64_t n29, uint64_t n30, uint64_t n31, uint64_t n32, uint64_t n33, uint64_t n34, uint64_t n35, uint64_t n36, uint64_t n37, uint64_t n38, uint64_t n39, uint64_t n40, uint64_t n41, uint64_t n42, uint64_t n43, uint64_t n44, uint64_t n45, uint64_t n46, uint64_t n47, uint64_t n48, uint64_t n49, uint64_t n50, uint64_t n51, uint64_t n52, uint64_t n53, uint64_t n54, uint64_t n55, uint64_t n56, uint64_t n57, uint64_t n58, uint64_t n59, uint64_t n60, uint64_t n61, uint64_t n62, uint64_t n63, uint64_t n64, uint64_t n65, uint64_t n66, uint64_t n67, uint64_t n68, uint64_t n69, uint64_t n70, uint64_t n71, uint64_t n72, uint64_t n73, uint64_t n74, uint64_t n75, uint64_t n76, uint64_t n77, uint64_t n78, uint64_t n79, uint64_t n80, uint64_t n81, uint64_t n82, uint64_t n83, uint64_t n84, uint64_t n85, uint64_t n86, uint64_t n87, uint64_t n88, uint64_t n89, uint64_t n90, uint64_t n91, uint64_t n92, uint64_t n93, uint64_t n94, uint64_t n95, uint64_t n96, uint64_t n97, uint64_t n98, uint64_t n99, uint64_t n100, uint64_t n101, uint64_t n102, uint64_t n103, uint64_t n104, uint64_t n105, uint64_t n106, uint64_t n107, uint64_t n108, uint64_t n109, uint64_t n110, uint64_t n111, uint64_t n112, uint64_t n113, uint64_t n114, uint64_t n115, uint64_t n116, uint64_t n117, uint64_t n118); uint64_t api_crammed(api_Moment a, api_Moment b, uint64_t n0, uint64_t n1, uint64_t n2, uint64_t n3, uint64_t n4, uint64_t n5, uint64_t n6, uint64_t n7, uint64_t n8, uint64_t n9, uint64_t n10, uint64_t n11, uint64_t n12, uint64_t n13, uint64_t n14, uint64_t n15, uint64_t n16, uint64_t n17, uint64_t n18, uint64_t n19, uint64_t n20, uint64_t n21, uint64_t n22, uint64_t n23, uint64_t n24, uint64_t n25, uint64_t n26, uint64_t n27, uint64_t n28, uint64_t n29, uint64_t n30, uint64_t n31, uint64_t n32, uint64_t n33, uint64_t n34, uint64_t n35, uint64_t n36, uint64_t n37, uint64_t n38, uint64_t n39, uint64_t n40, uint64_t n41, uint64_t n42, uint64_t n43, uint64_t n44, uint64_t n45, uint64_t n46, uint64_t n47, uint64_t n48, uint64_t n49, uint64_t n50, uint64_t n51, uint64_t n52, uint64_t n53, uint64_t n54, uint64_t n55, uint64_t n56, uint64_t n57, uint64_t n58, uint64_t n59, uint64_t n60, uint64_t n61, uint64_t n62, uint64_t n63, uint64_t n64, uint64_t n65, uint64_t n66, uint64_t n67, uint64_t n68, uint64_t n69, uint64_t n70, uint64_t n71, uint64_t n72, uint64_t n73, uint64_t n74, uint64_t n75, uint64_t n76, uint64_t n77, uint64_t n78, uint64_t n79, uint64_t n80, uint64_t n81, uint64_t n82, uint64_t n83, uint64_t n84, uint64_t n85, uint64_t n86, uint64_t n87, uint64_t n88, uint64_t n89, uint64_t n90, uint64_t n91, uint64_t n92, uint64_t n93, uint64_t n94, uint64_t n95, uint64_t n96, uint64_t n97, uint64_t n98, uint64_t n99, uint64_t n100, uint64_t n101, uint64_t n102, uint64_t n103, uint64_t n104, uint64_t n105, uint64_t n106, uint64_t n107, uint64_t n108, uint64_t n109, uint64_t n110, uint64_t n111, uint64_t n112, uint64_t n113, uint64_t n114, uint64_t n115, uint64_t n116, uint64_t n117, uint64_t n118, uint64_t n119, uint64_t n120, uint64_t n121, uint64_t n122, uint64_t n123); uint32_t api_jni_one(void); diff --git a/ffi/surface/api/cpp.hpp b/ffi/surface/api/cpp.hpp index b848cf7df..b4c68c509 100644 --- a/ffi/surface/api/cpp.hpp +++ b/ffi/surface/api/cpp.hpp @@ -1,6 +1,13 @@ // api.hpp #ifndef API_HPP_CRATE7 #define API_HPP_CRATE7 +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif #include "rt.hpp" #include "core.hpp" #include "dep.hpp" @@ -27,6 +34,8 @@ namespace api { }; inline constexpr ::std::uint64_t LIMIT = API_LIMIT; inline constexpr ::std::int64_t FAR = API_FAR; + inline constexpr ::std::uint64_t URL = API_URL; + [[deprecated("pass a step to `Dial::turn`, whose `}` or `{` alone stays in the note")]] inline constexpr ::std::uint64_t STEP = API_STEP; class RUST2_FFI_CONSUMABLE Board { RUST2_FFI_UNCONSUMED Board(Board &&other RUST2_FFI_MOVED_FROM) noexcept = default; Board &operator=(Board &&other) noexcept = default; @@ -252,6 +261,13 @@ namespace api { RUST2_FFI_CALLABLE ::std::uint32_t count() const; static ::api::Handle_later_future later(::std::uint32_t count); }; + class RUST2_FFI_CONSUMABLE Holder { + RUST2_FFI_UNCONSUMED Holder(Holder &&other RUST2_FFI_MOVED_FROM) noexcept = default; + Holder &operator=(Holder &&other) noexcept = default; + static ::api::Holder new_(::std::uint64_t level); + [[deprecated("use `Dial`, whose 'level' is \"the same\" at $0\nand past it")]] RUST2_FFI_CALLABLE ::std::uint64_t level_get() const; + [[deprecated("use `Dial`, whose 'level' is \"the same\" at $0\nand past it")]] RUST2_FFI_CALLABLE ::std::uint64_t doubled() const; + }; class RUST2_FFI_CONSUMABLE Counter { RUST2_FFI_UNCONSUMED Counter(Counter &&other RUST2_FFI_MOVED_FROM) noexcept = default; Counter &operator=(Counter &&other) noexcept = default; @@ -628,6 +644,11 @@ namespace api { virtual ~Beat() = default; virtual ::std::uint32_t beat() const = 0; }; + class Turner { + virtual ~Turner() = default; + virtual ::std::uint64_t by() const = 0; + [[deprecated("turn `Turner::by` instead")]] virtual ::std::uint64_t once() const = 0; + }; struct Parcel { ::api::Mark mark; ::api::buf payload; @@ -1046,6 +1067,33 @@ namespace api { friend bool operator==(const Qualifiers &a__, const Qualifiers &b_); friend bool operator!=(const Qualifiers &a__, const Qualifiers &b_); }; + struct Deprecated { + bool on; + [[deprecated]] ::std::uint32_t lower; + bool deprecated; + friend bool operator==(const Deprecated &a__, const Deprecated &b_); + friend bool operator!=(const Deprecated &a__, const Deprecated &b_); + ::api::buf debug() const; + static Deprecated default_(); + }; + struct Dial { + ::std::uint64_t level; + [[deprecated("keep the `Dial` from before the turn")]] ::std::uint64_t before; + friend bool operator==(const Dial &a__, const Dial &b_); + friend bool operator!=(const Dial &a__, const Dial &b_); + ::api::buf debug() const; + static Dial default_(); + ::api::result<::api::Dial, ::api::Error> turn(::std::uint64_t by) const; + [[deprecated("turn it by `LIMIT` with `Dial::turn`")]] ::api::Dial max() const; + }; + struct [[deprecated("use `Dial`, whose 'level' is \"the same\" at $0\nand past it")]] Knob { + ::std::uint64_t level; + friend bool operator==(const Knob &a__, const Knob &b_); + friend bool operator!=(const Knob &a__, const Knob &b_); + ::api::buf debug() const; + static Knob default_(); + ::std::uint64_t doubled() const; + }; struct polar_Point { ::std::uint8_t turns; ::std::uint32_t distance; @@ -1257,6 +1305,9 @@ namespace api { inline bool operator==(const DoubleArray &a__, const DoubleArray &b_); inline bool operator==(const a &a__, const a &b_); inline bool operator==(const Qualifiers &a__, const Qualifiers &b_); + inline bool operator==(const Deprecated &a__, const Deprecated &b_); + inline bool operator==(const Dial &a__, const Dial &b_); + inline bool operator==(const Knob &a__, const Knob &b_); inline bool operator==(const polar_Point &a__, const polar_Point &b_); inline bool operator==(const polar_Turn &a__, const polar_Turn &b_); inline bool operator==(const clash_Tone &a__, const clash_Tone &b_); @@ -1570,6 +1621,10 @@ namespace api { inline ::api::socket_addr_v4 same_socket_addr_v4(::api::socket_addr_v4 v); inline ::api::socket_addr_v6 same_socket_addr_v6(::api::socket_addr_v6 v); inline ::api::ip_addr same_ip_addr(::api::ip_addr v); + inline ::std::uint8_t deprecated(::std::uint8_t note); + [[deprecated]] inline ::api::Knob knob(const ::api::Dial &dial); + [[deprecated("read its `level`")]] inline ::api::level_later_future level_later(const ::api::Dial &dial); + inline ::api::result<::api::Dial, ::api::Error> turned(const ::api::Dial &dial, ::std::unique_ptr<::api::Turner> turner); inline ::std::uint64_t crowded(const ::api::Reading &reading, const ::api::Stamp &a__, const ::api::Stamp &b_, ::std::uint64_t n0, ::std::uint64_t n1, ::std::uint64_t n2, ::std::uint64_t n3, ::std::uint64_t n4, ::std::uint64_t n5, ::std::uint64_t n6, ::std::uint64_t n7, ::std::uint64_t n8, ::std::uint64_t n9, ::std::uint64_t n10, ::std::uint64_t n11, ::std::uint64_t n12, ::std::uint64_t n13, ::std::uint64_t n14, ::std::uint64_t n15, ::std::uint64_t n16, ::std::uint64_t n17, ::std::uint64_t n18, ::std::uint64_t n19, ::std::uint64_t n20, ::std::uint64_t n21, ::std::uint64_t n22, ::std::uint64_t n23, ::std::uint64_t n24, ::std::uint64_t n25, ::std::uint64_t n26, ::std::uint64_t n27, ::std::uint64_t n28, ::std::uint64_t n29, ::std::uint64_t n30, ::std::uint64_t n31, ::std::uint64_t n32, ::std::uint64_t n33, ::std::uint64_t n34, ::std::uint64_t n35, ::std::uint64_t n36, ::std::uint64_t n37, ::std::uint64_t n38, ::std::uint64_t n39, ::std::uint64_t n40, ::std::uint64_t n41, ::std::uint64_t n42, ::std::uint64_t n43, ::std::uint64_t n44, ::std::uint64_t n45, ::std::uint64_t n46, ::std::uint64_t n47, ::std::uint64_t n48, ::std::uint64_t n49, ::std::uint64_t n50, ::std::uint64_t n51, ::std::uint64_t n52, ::std::uint64_t n53, ::std::uint64_t n54, ::std::uint64_t n55, ::std::uint64_t n56, ::std::uint64_t n57, ::std::uint64_t n58, ::std::uint64_t n59, ::std::uint64_t n60, ::std::uint64_t n61, ::std::uint64_t n62, ::std::uint64_t n63, ::std::uint64_t n64, ::std::uint64_t n65, ::std::uint64_t n66, ::std::uint64_t n67, ::std::uint64_t n68, ::std::uint64_t n69, ::std::uint64_t n70, ::std::uint64_t n71, ::std::uint64_t n72, ::std::uint64_t n73, ::std::uint64_t n74, ::std::uint64_t n75, ::std::uint64_t n76, ::std::uint64_t n77, ::std::uint64_t n78, ::std::uint64_t n79, ::std::uint64_t n80, ::std::uint64_t n81, ::std::uint64_t n82, ::std::uint64_t n83, ::std::uint64_t n84, ::std::uint64_t n85, ::std::uint64_t n86, ::std::uint64_t n87, ::std::uint64_t n88, ::std::uint64_t n89, ::std::uint64_t n90, ::std::uint64_t n91, ::std::uint64_t n92, ::std::uint64_t n93, ::std::uint64_t n94, ::std::uint64_t n95, ::std::uint64_t n96, ::std::uint64_t n97, ::std::uint64_t n98, ::std::uint64_t n99, ::std::uint64_t n100, ::std::uint64_t n101, ::std::uint64_t n102, ::std::uint64_t n103, ::std::uint64_t n104, ::std::uint64_t n105, ::std::uint64_t n106, ::std::uint64_t n107, ::std::uint64_t n108, ::std::uint64_t n109, ::std::uint64_t n110, ::std::uint64_t n111, ::std::uint64_t n112, ::std::uint64_t n113, ::std::uint64_t n114, ::std::uint64_t n115, ::std::uint64_t n116, ::std::uint64_t n117, ::std::uint64_t n118); inline ::std::uint64_t crammed(const ::api::Moment &a__, const ::api::Moment &b_, ::std::uint64_t n0, ::std::uint64_t n1, ::std::uint64_t n2, ::std::uint64_t n3, ::std::uint64_t n4, ::std::uint64_t n5, ::std::uint64_t n6, ::std::uint64_t n7, ::std::uint64_t n8, ::std::uint64_t n9, ::std::uint64_t n10, ::std::uint64_t n11, ::std::uint64_t n12, ::std::uint64_t n13, ::std::uint64_t n14, ::std::uint64_t n15, ::std::uint64_t n16, ::std::uint64_t n17, ::std::uint64_t n18, ::std::uint64_t n19, ::std::uint64_t n20, ::std::uint64_t n21, ::std::uint64_t n22, ::std::uint64_t n23, ::std::uint64_t n24, ::std::uint64_t n25, ::std::uint64_t n26, ::std::uint64_t n27, ::std::uint64_t n28, ::std::uint64_t n29, ::std::uint64_t n30, ::std::uint64_t n31, ::std::uint64_t n32, ::std::uint64_t n33, ::std::uint64_t n34, ::std::uint64_t n35, ::std::uint64_t n36, ::std::uint64_t n37, ::std::uint64_t n38, ::std::uint64_t n39, ::std::uint64_t n40, ::std::uint64_t n41, ::std::uint64_t n42, ::std::uint64_t n43, ::std::uint64_t n44, ::std::uint64_t n45, ::std::uint64_t n46, ::std::uint64_t n47, ::std::uint64_t n48, ::std::uint64_t n49, ::std::uint64_t n50, ::std::uint64_t n51, ::std::uint64_t n52, ::std::uint64_t n53, ::std::uint64_t n54, ::std::uint64_t n55, ::std::uint64_t n56, ::std::uint64_t n57, ::std::uint64_t n58, ::std::uint64_t n59, ::std::uint64_t n60, ::std::uint64_t n61, ::std::uint64_t n62, ::std::uint64_t n63, ::std::uint64_t n64, ::std::uint64_t n65, ::std::uint64_t n66, ::std::uint64_t n67, ::std::uint64_t n68, ::std::uint64_t n69, ::std::uint64_t n70, ::std::uint64_t n71, ::std::uint64_t n72, ::std::uint64_t n73, ::std::uint64_t n74, ::std::uint64_t n75, ::std::uint64_t n76, ::std::uint64_t n77, ::std::uint64_t n78, ::std::uint64_t n79, ::std::uint64_t n80, ::std::uint64_t n81, ::std::uint64_t n82, ::std::uint64_t n83, ::std::uint64_t n84, ::std::uint64_t n85, ::std::uint64_t n86, ::std::uint64_t n87, ::std::uint64_t n88, ::std::uint64_t n89, ::std::uint64_t n90, ::std::uint64_t n91, ::std::uint64_t n92, ::std::uint64_t n93, ::std::uint64_t n94, ::std::uint64_t n95, ::std::uint64_t n96, ::std::uint64_t n97, ::std::uint64_t n98, ::std::uint64_t n99, ::std::uint64_t n100, ::std::uint64_t n101, ::std::uint64_t n102, ::std::uint64_t n103, ::std::uint64_t n104, ::std::uint64_t n105, ::std::uint64_t n106, ::std::uint64_t n107, ::std::uint64_t n108, ::std::uint64_t n109, ::std::uint64_t n110, ::std::uint64_t n111, ::std::uint64_t n112, ::std::uint64_t n113, ::std::uint64_t n114, ::std::uint64_t n115, ::std::uint64_t n116, ::std::uint64_t n117, ::std::uint64_t n118, ::std::uint64_t n119, ::std::uint64_t n120, ::std::uint64_t n121, ::std::uint64_t n122, ::std::uint64_t n123); inline ::std::uint32_t jni_one(); @@ -1614,11 +1669,23 @@ namespace std { size_t operator()(const ::api::Part &value) const noexcept; }; } +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif #endif // core.hpp #ifndef API_HPP_CRATE0 #define API_HPP_CRATE0 +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif #include "rt.hpp" namespace api { class RUST2_FFI_CONSUMABLE std_io_Error { @@ -1626,11 +1693,23 @@ namespace api { std_io_Error &operator=(std_io_Error &&other) noexcept = default; }; } +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif #endif // dep.hpp #ifndef API_HPP_CRATE2 #define API_HPP_CRATE2 +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif #include "rt.hpp" namespace api { class RUST2_FFI_CONSUMABLE Area { @@ -1653,11 +1732,23 @@ namespace api { }; inline bool operator==(const Size &a__, const Size &b_); } +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif #endif // rt.hpp #ifndef API_HPP_RT #define API_HPP_RT +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif #include "../api.h" #include #include @@ -1892,6 +1983,9 @@ namespace api { struct NonZeros; struct a; struct Qualifiers; + struct Deprecated; + struct Dial; + struct Knob; struct polar_Point; struct polar_Turn; struct clash_Tone; @@ -1930,6 +2024,7 @@ namespace api { class Trail; class Worker; class Handle; + class Holder; class Area; class Counter; class Meter; @@ -1977,6 +2072,7 @@ namespace api { class Part; class Log; class Beat; + class Turner; struct Choice_Empty; struct Choice_Picked; using Choice = ::std::variant; @@ -2066,14 +2162,27 @@ namespace api { using byte_len_future = ::api::future; using parse_later_future = ::api::future; using either_later_future = ::api::future; + using level_later_future = ::api::future; using emit_later_future = ::api::future; using log_on_drop_future = ::api::future; } +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif #endif // serdejson.hpp #ifndef API_HPP_CRATE4 #define API_HPP_CRATE4 +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif #include "rt.hpp" namespace api { class RUST2_FFI_CONSUMABLE Json { @@ -2083,11 +2192,23 @@ namespace api { RUST2_FFI_CALLABLE ::api::buf to_text() const; }; } +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif #endif // std.hpp #ifndef API_HPP_CRATE1 #define API_HPP_CRATE1 +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif #include "rt.hpp" namespace api { class RUST2_FFI_CONSUMABLE Instant { @@ -2106,11 +2227,23 @@ namespace std { size_t operator()(const ::api::Instant &value) const noexcept; }; } +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif #endif // tls.hpp #ifndef API_HPP_CRATE6 #define API_HPP_CRATE6 +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif #include "rt.hpp" namespace api { class RUST2_FFI_CONSUMABLE tls_Session { @@ -2147,11 +2280,23 @@ namespace api { }; inline bool operator==(const tls_policy_Lifetime &a__, const tls_policy_Lifetime &b_); } +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif #endif // tracingcore.hpp #ifndef API_HPP_CRATE3 #define API_HPP_CRATE3 +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif #include "rt.hpp" namespace api { enum class Level { @@ -2165,11 +2310,23 @@ namespace api { inline bool operator!=(::api::Level a__, ::api::Level b_); inline ::api::buf Level_to_string(::api::Level self); } +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif #endif // url.hpp #ifndef API_HPP_CRATE5 #define API_HPP_CRATE5 +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif #include "rt.hpp" namespace api { class RUST2_FFI_CONSUMABLE Url { @@ -2190,4 +2347,9 @@ namespace std { size_t operator()(const ::api::Url &value) const noexcept; }; } +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif #endif diff --git a/ffi/surface/api/dart.dart b/ffi/surface/api/dart.dart index 47e53734a..3661a7e02 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -614,6 +614,36 @@ final class Qualifiers { @override bool operator ==(Object other); @override int get hashCode; } +final class Deprecated_ { + final bool on; + @Deprecated('') final int lower; + final bool deprecated; + const Deprecated_({required this.on, required this.lower, required this.deprecated}); + String debug(); + @override bool operator ==(Object other); + @override int get hashCode; + factory Deprecated_.default_(); +} +final class Dial { + final U64 level; + @Deprecated('keep the `Dial` from before the turn') final U64 before; + const Dial({required this.level, required this.before}); + String debug(); + @override bool operator ==(Object other); + @override int get hashCode; + factory Dial.default_(); + Dial turn(U64 by); + @Deprecated('turn it by `LIMIT` with `Dial::turn`') Dial max(); +} +@Deprecated('use `Dial`, whose \'level\' is "the same" at \$0\nand past it') final class Knob { + final U64 level; + const Knob({required this.level}); + String debug(); + @override bool operator ==(Object other); + @override int get hashCode; + factory Knob.default_(); + U64 doubled(); +} final class PolarPoint { final int turns; final int distance; @@ -1110,6 +1140,11 @@ final class Handle extends _Object { int count(); static Cancelable later(int count); } +final class Holder extends _Object { + factory Holder(U64 level); + @Deprecated('use `Dial`, whose \'level\' is "the same" at \$0\nand past it') U64 get levelGet; + @Deprecated('use `Dial`, whose \'level\' is "the same" at \$0\nand past it') U64 doubled(); +} final class Area extends _Object { String debug(); Area clone(); @@ -1450,6 +1485,11 @@ abstract class Beat { int beat(); void close(); } +abstract class Turner { + U64 by(); + @Deprecated('turn `Turner::by` instead') U64 once(); + void close(); +} final class BoundsU64Exception implements Exception { final BoundsU64 error; const BoundsU64Exception(this.error); @@ -1467,6 +1507,8 @@ final class VecClashToneException implements Exception { } const LIMIT = U64.fromBits(1000); const FAR = 9223372036854775807; +const URL = U64.fromBits(1000); +@Deprecated('pass a step to `Dial::turn`, whose `}` or `{` alone stays in the note') const STEP = U64.fromBits(1); bool hasText(Note note); U64 marked(Mark apiMarked); Reading? reading(int n); @@ -1722,6 +1764,10 @@ SocketAddr sameSocketAddr(SocketAddr v); SocketAddrV4 sameSocketAddrV4(SocketAddrV4 v); SocketAddrV6 sameSocketAddrV6(SocketAddrV6 v); IpAddr sameIpAddr(IpAddr v); +int deprecated(int note); +@Deprecated('') Knob knob(Dial dial); +@Deprecated('read its `level`') Cancelable levelLater(Dial dial); +Dial turned(Dial dial, Turner turner); U64 crowded(Reading reading, Stamp a, Stamp b, U64 n0, U64 n1, U64 n2, U64 n3, U64 n4, U64 n5, U64 n6, U64 n7, U64 n8, U64 n9, U64 n10, U64 n11, U64 n12, U64 n13, U64 n14, U64 n15, U64 n16, U64 n17, U64 n18, U64 n19, U64 n20, U64 n21, U64 n22, U64 n23, U64 n24, U64 n25, U64 n26, U64 n27, U64 n28, U64 n29, U64 n30, U64 n31, U64 n32, U64 n33, U64 n34, U64 n35, U64 n36, U64 n37, U64 n38, U64 n39, U64 n40, U64 n41, U64 n42, U64 n43, U64 n44, U64 n45, U64 n46, U64 n47, U64 n48, U64 n49, U64 n50, U64 n51, U64 n52, U64 n53, U64 n54, U64 n55, U64 n56, U64 n57, U64 n58, U64 n59, U64 n60, U64 n61, U64 n62, U64 n63, U64 n64, U64 n65, U64 n66, U64 n67, U64 n68, U64 n69, U64 n70, U64 n71, U64 n72, U64 n73, U64 n74, U64 n75, U64 n76, U64 n77, U64 n78, U64 n79, U64 n80, U64 n81, U64 n82, U64 n83, U64 n84, U64 n85, U64 n86, U64 n87, U64 n88, U64 n89, U64 n90, U64 n91, U64 n92, U64 n93, U64 n94, U64 n95, U64 n96, U64 n97, U64 n98, U64 n99, U64 n100, U64 n101, U64 n102, U64 n103, U64 n104, U64 n105, U64 n106, U64 n107, U64 n108, U64 n109, U64 n110, U64 n111, U64 n112, U64 n113, U64 n114, U64 n115, U64 n116, U64 n117, U64 n118); U64 crammed(Moment a, Moment b, U64 n0, U64 n1, U64 n2, U64 n3, U64 n4, U64 n5, U64 n6, U64 n7, U64 n8, U64 n9, U64 n10, U64 n11, U64 n12, U64 n13, U64 n14, U64 n15, U64 n16, U64 n17, U64 n18, U64 n19, U64 n20, U64 n21, U64 n22, U64 n23, U64 n24, U64 n25, U64 n26, U64 n27, U64 n28, U64 n29, U64 n30, U64 n31, U64 n32, U64 n33, U64 n34, U64 n35, U64 n36, U64 n37, U64 n38, U64 n39, U64 n40, U64 n41, U64 n42, U64 n43, U64 n44, U64 n45, U64 n46, U64 n47, U64 n48, U64 n49, U64 n50, U64 n51, U64 n52, U64 n53, U64 n54, U64 n55, U64 n56, U64 n57, U64 n58, U64 n59, U64 n60, U64 n61, U64 n62, U64 n63, U64 n64, U64 n65, U64 n66, U64 n67, U64 n68, U64 n69, U64 n70, U64 n71, U64 n72, U64 n73, U64 n74, U64 n75, U64 n76, U64 n77, U64 n78, U64 n79, U64 n80, U64 n81, U64 n82, U64 n83, U64 n84, U64 n85, U64 n86, U64 n87, U64 n88, U64 n89, U64 n90, U64 n91, U64 n92, U64 n93, U64 n94, U64 n95, U64 n96, U64 n97, U64 n98, U64 n99, U64 n100, U64 n101, U64 n102, U64 n103, U64 n104, U64 n105, U64 n106, U64 n107, U64 n108, U64 n109, U64 n110, U64 n111, U64 n112, U64 n113, U64 n114, U64 n115, U64 n116, U64 n117, U64 n118, U64 n119, U64 n120, U64 n121, U64 n122, U64 n123); int jniOne(); diff --git a/ffi/surface/api/go.txt b/ffi/surface/api/go.txt index e5e1f9844..82481abc0 100644 --- a/ffi/surface/api/go.txt +++ b/ffi/surface/api/go.txt @@ -3,6 +3,8 @@ package api // import "api/api" CONSTANTS const FAR int64 = 9223372036854775807 const LIMIT uint64 = 1000 +const STEP uint64 = 1 +const URL uint64 = 1000 FUNCTIONS func Admit(entry p_rt.Tuple4[*Counter, *Mark, Seat, Choice]) (uint64, error) @@ -48,6 +50,7 @@ func Counted(ctx context.Context, n uint32, count func(uint32)) (uint32, error) func Crammed(a Moment, b Moment, n0 uint64, n1 uint64, n2 uint64, n3 uint64, n4 uint64, n5 uint64, n6 uint64, n7 uint64, n8 uint64, n9 uint64, n10 uint64, n11 uint64, n12 uint64, n13 uint64, n14 uint64, n15 uint64, n16 uint64, n17 uint64, n18 uint64, n19 uint64, n20 uint64, n21 uint64, n22 uint64, n23 uint64, n24 uint64, n25 uint64, n26 uint64, n27 uint64, n28 uint64, n29 uint64, n30 uint64, n31 uint64, n32 uint64, n33 uint64, n34 uint64, n35 uint64, n36 uint64, n37 uint64, n38 uint64, n39 uint64, n40 uint64, n41 uint64, n42 uint64, n43 uint64, n44 uint64, n45 uint64, n46 uint64, n47 uint64, n48 uint64, n49 uint64, n50 uint64, n51 uint64, n52 uint64, n53 uint64, n54 uint64, n55 uint64, n56 uint64, n57 uint64, n58 uint64, n59 uint64, n60 uint64, n61 uint64, n62 uint64, n63 uint64, n64 uint64, n65 uint64, n66 uint64, n67 uint64, n68 uint64, n69 uint64, n70 uint64, n71 uint64, n72 uint64, n73 uint64, n74 uint64, n75 uint64, n76 uint64, n77 uint64, n78 uint64, n79 uint64, n80 uint64, n81 uint64, n82 uint64, n83 uint64, n84 uint64, n85 uint64, n86 uint64, n87 uint64, n88 uint64, n89 uint64, n90 uint64, n91 uint64, n92 uint64, n93 uint64, n94 uint64, n95 uint64, n96 uint64, n97 uint64, n98 uint64, n99 uint64, n100 uint64, n101 uint64, n102 uint64, n103 uint64, n104 uint64, n105 uint64, n106 uint64, n107 uint64, n108 uint64, n109 uint64, n110 uint64, n111 uint64, n112 uint64, n113 uint64, n114 uint64, n115 uint64, n116 uint64, n117 uint64, n118 uint64, n119 uint64, n120 uint64, n121 uint64, n122 uint64, n123 uint64) uint64 func Cross(left LeftRightU8, right RightLeftU8) uint8 func Crowded(reading Reading, a Stamp, b Stamp, n0 uint64, n1 uint64, n2 uint64, n3 uint64, n4 uint64, n5 uint64, n6 uint64, n7 uint64, n8 uint64, n9 uint64, n10 uint64, n11 uint64, n12 uint64, n13 uint64, n14 uint64, n15 uint64, n16 uint64, n17 uint64, n18 uint64, n19 uint64, n20 uint64, n21 uint64, n22 uint64, n23 uint64, n24 uint64, n25 uint64, n26 uint64, n27 uint64, n28 uint64, n29 uint64, n30 uint64, n31 uint64, n32 uint64, n33 uint64, n34 uint64, n35 uint64, n36 uint64, n37 uint64, n38 uint64, n39 uint64, n40 uint64, n41 uint64, n42 uint64, n43 uint64, n44 uint64, n45 uint64, n46 uint64, n47 uint64, n48 uint64, n49 uint64, n50 uint64, n51 uint64, n52 uint64, n53 uint64, n54 uint64, n55 uint64, n56 uint64, n57 uint64, n58 uint64, n59 uint64, n60 uint64, n61 uint64, n62 uint64, n63 uint64, n64 uint64, n65 uint64, n66 uint64, n67 uint64, n68 uint64, n69 uint64, n70 uint64, n71 uint64, n72 uint64, n73 uint64, n74 uint64, n75 uint64, n76 uint64, n77 uint64, n78 uint64, n79 uint64, n80 uint64, n81 uint64, n82 uint64, n83 uint64, n84 uint64, n85 uint64, n86 uint64, n87 uint64, n88 uint64, n89 uint64, n90 uint64, n91 uint64, n92 uint64, n93 uint64, n94 uint64, n95 uint64, n96 uint64, n97 uint64, n98 uint64, n99 uint64, n100 uint64, n101 uint64, n102 uint64, n103 uint64, n104 uint64, n105 uint64, n106 uint64, n107 uint64, n108 uint64, n109 uint64, n110 uint64, n111 uint64, n112 uint64, n113 uint64, n114 uint64, n115 uint64, n116 uint64, n117 uint64, n118 uint64) (uint64, error) +func Deprecated_(note uint8) uint8 func Describe(event Event) (string, error) func DescribeNonZeros(nonZeros NonZeros) (string, error) func Digit(r *p_rt.Bytes) (uint8, error) @@ -118,6 +121,7 @@ func Least(sets [][]uint32) [][]uint32 func Len(payload p_rt.Bytes) uint func LentBack(value p_rt.Bytes) p_rt.Bytes func Less(value uint32, value2 uint32) uint32 +func LevelLater(ctx context.Context, dial Dial) (uint64, error) func LocalLater(ctx context.Context, n uint32) (uint32, error) func LocalWaiterPollReady(ctx context.Context, n uint32) (uint32, error) func LocalsDropped() uint32 @@ -230,6 +234,7 @@ func Title(formal bool) *string func TokenBytes(id uint32, len_ uint32) p_rt.Bytes func TokenSlice(id uint32, len_ uint32, of uint32) p_rt.Bytes func Total(range_ p_rt.RangeU64) uint64 +func TurnerVtable_() unsafe.Pointer func Unhook() error func Verify(cert *p_tls.Cert) (uint32, error) func VisitStray(visit func(string)) @@ -749,12 +754,30 @@ type Cursor struct { } func (self *Cursor) At() (uint64, error) func (self *Cursor) Close() error +type Deprecated struct { + On bool + Lower uint32 + Deprecated bool +} +func DeprecatedDefault() Deprecated +func (self Deprecated) Equal(other Deprecated) bool +func (self Deprecated) GoString() string type Der struct { Handle_ *p_rt.Handle_ } func DerFromSlice(bytes p_rt.Bytes) *Der func (self *Der) Bytes() (p_rt.Bytes, error) func (self *Der) Close() error +type Dial struct { + Level uint64 + Before uint64 +} +func DialDefault() Dial +func Turned(dial Dial, turner Turner) (Dial, error) +func (self Dial) Equal(other Dial) bool +func (self Dial) GoString() string +func (self Dial) Max() Dial +func (self Dial) Turn(by uint64) (Dial, error) type Digest struct { Handle_ *p_rt.Handle_ } @@ -900,6 +923,13 @@ func (self Hits) HitsGet() uint64 func (self *Hits) HitsSet(value uint64) func (self Hits) MissesGet() uint64 func (self *Hits) MissesSet(value uint64) +type Holder struct { + Handle_ *p_rt.Handle_ +} +func NewHolder(level uint64) *Holder +func (self *Holder) Close() error +func (self *Holder) Doubled() (uint64, error) +func (self *Holder) LevelGet() (uint64, error) type Hooked struct { Handle_ *p_rt.Handle_ } @@ -940,6 +970,14 @@ func (self *Key) Close() error func (self *Key) Equal(other *Key) (bool, error) func (self *Key) GoString() string func (self *Key) HashOf() (uint64, error) +type Knob struct { + Level uint64 +} +func KnobDefault() Knob +func NewKnob(dial Dial) Knob +func (self Knob) Doubled() uint64 +func (self Knob) Equal(other Knob) bool +func (self Knob) GoString() string type Label struct { Name string At *Point @@ -1642,6 +1680,10 @@ func (self *Trail) Iter() ([]Point, error) func (self *Trail) Labels() ([]Label, error) func (self *Trail) Names() ([]string, error) func (self *Trail) Points() ([]Point, error) +type Turner interface { + By() uint64 + Once() uint64 +} type VecClashTone int32 const ( VecClashToneError_ VecClashTone = 0 diff --git a/ffi/surface/api/kotlin.kt b/ffi/surface/api/kotlin.kt index d709f8c38..83e670fc9 100644 --- a/ffi/surface/api/kotlin.kt +++ b/ffi/surface/api/kotlin.kt @@ -368,6 +368,27 @@ data class Qualifiers(val api: kotlin.Double, val kotlin: kotlin.Double) { override fun equals(other: kotlin.Any?): kotlin.Boolean override fun hashCode(): kotlin.Int } +data class Deprecated(val on: kotlin.Boolean, @kotlin.Deprecated("") val lower: kotlin.UInt, val deprecated: kotlin.Boolean) { + fun debug(): kotlin.String + companion object { + @kotlin.jvm.JvmStatic fun default(): api.Deprecated + } +} +data class Dial(val level: kotlin.ULong, @kotlin.Deprecated("keep the `Dial` from before the turn") val before: kotlin.ULong) { + fun debug(): kotlin.String + @kotlin.jvm.Throws(ErrorException::class) fun turn(by: kotlin.ULong): api.Dial + @kotlin.Deprecated("turn it by `LIMIT` with `Dial::turn`") fun max(): api.Dial + companion object { + @kotlin.jvm.JvmStatic fun default(): api.Dial + } +} +@kotlin.Deprecated("use `Dial`, whose 'level' is \"the same\" at \$0\nand past it") data class Knob(val level: kotlin.ULong) { + fun debug(): kotlin.String + fun doubled(): kotlin.ULong + companion object { + @kotlin.jvm.JvmStatic fun default(): api.Knob + } +} data class PolarPoint(val turns: kotlin.UByte, val distance: kotlin.UInt) { fun debug(): kotlin.String } @@ -786,6 +807,14 @@ class Handle internal constructor(raw: Long, lent: Boolean = false) : AutoClosea @kotlin.jvm.JvmStatic suspend fun later(count: kotlin.UInt): api.Handle } } +class Holder internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { + override fun close() + @kotlin.Deprecated("use `Dial`, whose 'level' is \"the same\" at \$0\nand past it") val levelGet: kotlin.ULong + @kotlin.Deprecated("use `Dial`, whose 'level' is \"the same\" at \$0\nand past it") fun doubled(): kotlin.ULong + companion object { + @kotlin.jvm.JvmStatic fun new(level: kotlin.ULong): api.Holder + } +} class Area internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { override fun close() fun debug(): kotlin.String @@ -1236,6 +1265,10 @@ interface Log { interface Beat { fun beat(): kotlin.UInt } +interface Turner { + fun by(): kotlin.ULong + @kotlin.Deprecated("turn `Turner::by` instead") fun once(): kotlin.ULong +} data class Tuple1(val first: T1) { override fun equals(other: kotlin.Any?): kotlin.Boolean override fun hashCode(): kotlin.Int @@ -1268,6 +1301,8 @@ class kotlincollectionsListClashToneException(val error: kotlin.collections.List } const val LIMIT: ULong const val FAR: Long +const val URL: ULong +@kotlin.Deprecated("pass a step to `Dial::turn`, whose `}` or `{` alone stays in the note") const val STEP: ULong fun hasText(note: api.Note): kotlin.Boolean fun marked(apiMarked: api.Mark): kotlin.ULong fun reading(n: kotlin.UInt): api.Reading? @@ -1526,6 +1561,10 @@ fun sameSocketAddr(v: api.SocketAddr): api.SocketAddr fun sameSocketAddrV4(v: api.SocketAddrV4): api.SocketAddrV4 fun sameSocketAddrV6(v: api.SocketAddrV6): api.SocketAddrV6 fun sameIpAddr(v: api.IpAddr): api.IpAddr +fun deprecated(note: kotlin.UByte): kotlin.UByte +@kotlin.Deprecated("") fun knob(dial: api.Dial): api.Knob +@kotlin.Deprecated("read its `level`") suspend fun levelLater(dial: api.Dial): kotlin.ULong +@kotlin.jvm.Throws(ErrorException::class) fun turned(dial: api.Dial, turner: api.Turner): api.Dial fun crowded(reading: api.Reading, a: api.Stamp, b: api.Stamp, n0: kotlin.ULong, n1: kotlin.ULong, n2: kotlin.ULong, n3: kotlin.ULong, n4: kotlin.ULong, n5: kotlin.ULong, n6: kotlin.ULong, n7: kotlin.ULong, n8: kotlin.ULong, n9: kotlin.ULong, n10: kotlin.ULong, n11: kotlin.ULong, n12: kotlin.ULong, n13: kotlin.ULong, n14: kotlin.ULong, n15: kotlin.ULong, n16: kotlin.ULong, n17: kotlin.ULong, n18: kotlin.ULong, n19: kotlin.ULong, n20: kotlin.ULong, n21: kotlin.ULong, n22: kotlin.ULong, n23: kotlin.ULong, n24: kotlin.ULong, n25: kotlin.ULong, n26: kotlin.ULong, n27: kotlin.ULong, n28: kotlin.ULong, n29: kotlin.ULong, n30: kotlin.ULong, n31: kotlin.ULong, n32: kotlin.ULong, n33: kotlin.ULong, n34: kotlin.ULong, n35: kotlin.ULong, n36: kotlin.ULong, n37: kotlin.ULong, n38: kotlin.ULong, n39: kotlin.ULong, n40: kotlin.ULong, n41: kotlin.ULong, n42: kotlin.ULong, n43: kotlin.ULong, n44: kotlin.ULong, n45: kotlin.ULong, n46: kotlin.ULong, n47: kotlin.ULong, n48: kotlin.ULong, n49: kotlin.ULong, n50: kotlin.ULong, n51: kotlin.ULong, n52: kotlin.ULong, n53: kotlin.ULong, n54: kotlin.ULong, n55: kotlin.ULong, n56: kotlin.ULong, n57: kotlin.ULong, n58: kotlin.ULong, n59: kotlin.ULong, n60: kotlin.ULong, n61: kotlin.ULong, n62: kotlin.ULong, n63: kotlin.ULong, n64: kotlin.ULong, n65: kotlin.ULong, n66: kotlin.ULong, n67: kotlin.ULong, n68: kotlin.ULong, n69: kotlin.ULong, n70: kotlin.ULong, n71: kotlin.ULong, n72: kotlin.ULong, n73: kotlin.ULong, n74: kotlin.ULong, n75: kotlin.ULong, n76: kotlin.ULong, n77: kotlin.ULong, n78: kotlin.ULong, n79: kotlin.ULong, n80: kotlin.ULong, n81: kotlin.ULong, n82: kotlin.ULong, n83: kotlin.ULong, n84: kotlin.ULong, n85: kotlin.ULong, n86: kotlin.ULong, n87: kotlin.ULong, n88: kotlin.ULong, n89: kotlin.ULong, n90: kotlin.ULong, n91: kotlin.ULong, n92: kotlin.ULong, n93: kotlin.ULong, n94: kotlin.ULong, n95: kotlin.ULong, n96: kotlin.ULong, n97: kotlin.ULong, n98: kotlin.ULong, n99: kotlin.ULong, n100: kotlin.ULong, n101: kotlin.ULong, n102: kotlin.ULong, n103: kotlin.ULong, n104: kotlin.ULong, n105: kotlin.ULong, n106: kotlin.ULong, n107: kotlin.ULong, n108: kotlin.ULong, n109: kotlin.ULong, n110: kotlin.ULong, n111: kotlin.ULong, n112: kotlin.ULong, n113: kotlin.ULong, n114: kotlin.ULong, n115: kotlin.ULong, n116: kotlin.ULong, n117: kotlin.ULong, n118: kotlin.ULong): kotlin.ULong fun crammed(a: api.Moment, b: api.Moment, n0: kotlin.ULong, n1: kotlin.ULong, n2: kotlin.ULong, n3: kotlin.ULong, n4: kotlin.ULong, n5: kotlin.ULong, n6: kotlin.ULong, n7: kotlin.ULong, n8: kotlin.ULong, n9: kotlin.ULong, n10: kotlin.ULong, n11: kotlin.ULong, n12: kotlin.ULong, n13: kotlin.ULong, n14: kotlin.ULong, n15: kotlin.ULong, n16: kotlin.ULong, n17: kotlin.ULong, n18: kotlin.ULong, n19: kotlin.ULong, n20: kotlin.ULong, n21: kotlin.ULong, n22: kotlin.ULong, n23: kotlin.ULong, n24: kotlin.ULong, n25: kotlin.ULong, n26: kotlin.ULong, n27: kotlin.ULong, n28: kotlin.ULong, n29: kotlin.ULong, n30: kotlin.ULong, n31: kotlin.ULong, n32: kotlin.ULong, n33: kotlin.ULong, n34: kotlin.ULong, n35: kotlin.ULong, n36: kotlin.ULong, n37: kotlin.ULong, n38: kotlin.ULong, n39: kotlin.ULong, n40: kotlin.ULong, n41: kotlin.ULong, n42: kotlin.ULong, n43: kotlin.ULong, n44: kotlin.ULong, n45: kotlin.ULong, n46: kotlin.ULong, n47: kotlin.ULong, n48: kotlin.ULong, n49: kotlin.ULong, n50: kotlin.ULong, n51: kotlin.ULong, n52: kotlin.ULong, n53: kotlin.ULong, n54: kotlin.ULong, n55: kotlin.ULong, n56: kotlin.ULong, n57: kotlin.ULong, n58: kotlin.ULong, n59: kotlin.ULong, n60: kotlin.ULong, n61: kotlin.ULong, n62: kotlin.ULong, n63: kotlin.ULong, n64: kotlin.ULong, n65: kotlin.ULong, n66: kotlin.ULong, n67: kotlin.ULong, n68: kotlin.ULong, n69: kotlin.ULong, n70: kotlin.ULong, n71: kotlin.ULong, n72: kotlin.ULong, n73: kotlin.ULong, n74: kotlin.ULong, n75: kotlin.ULong, n76: kotlin.ULong, n77: kotlin.ULong, n78: kotlin.ULong, n79: kotlin.ULong, n80: kotlin.ULong, n81: kotlin.ULong, n82: kotlin.ULong, n83: kotlin.ULong, n84: kotlin.ULong, n85: kotlin.ULong, n86: kotlin.ULong, n87: kotlin.ULong, n88: kotlin.ULong, n89: kotlin.ULong, n90: kotlin.ULong, n91: kotlin.ULong, n92: kotlin.ULong, n93: kotlin.ULong, n94: kotlin.ULong, n95: kotlin.ULong, n96: kotlin.ULong, n97: kotlin.ULong, n98: kotlin.ULong, n99: kotlin.ULong, n100: kotlin.ULong, n101: kotlin.ULong, n102: kotlin.ULong, n103: kotlin.ULong, n104: kotlin.ULong, n105: kotlin.ULong, n106: kotlin.ULong, n107: kotlin.ULong, n108: kotlin.ULong, n109: kotlin.ULong, n110: kotlin.ULong, n111: kotlin.ULong, n112: kotlin.ULong, n113: kotlin.ULong, n114: kotlin.ULong, n115: kotlin.ULong, n116: kotlin.ULong, n117: kotlin.ULong, n118: kotlin.ULong, n119: kotlin.ULong, n120: kotlin.ULong, n121: kotlin.ULong, n122: kotlin.ULong, n123: kotlin.ULong): kotlin.ULong fun jniOne(): kotlin.UInt diff --git a/ffi/surface/api/python.pyi b/ffi/surface/api/python.pyi index 47eff22ae..0e73a9780 100644 --- a/ffi/surface/api/python.pyi +++ b/ffi/surface/api/python.pyi @@ -424,6 +424,35 @@ class Qualifiers(_Record): kotlin: _float def __init__(self, api: _float, kotlin: _float) -> None: ... def __eq__(self, other: _object) -> _bool: ... +class Deprecated(_Record): + on: _bool + lower: _int + deprecated: _bool + def __init__(self, on: _bool, lower: _int, deprecated: _bool) -> None: ... + def __eq__(self, other: _object) -> _bool: ... + def __repr__(self) -> _str: ... + @_staticmethod + def default() -> Deprecated: ... +class Dial(_Record): + level: _int + before: _int + def __init__(self, level: _int, before: _int) -> None: ... + def __eq__(self, other: _object) -> _bool: ... + def __repr__(self) -> _str: ... + @_staticmethod + def default() -> Dial: ... + def turn(self, by: _int) -> Dial: ... + @_deprecated('turn it by `LIMIT` with `Dial::turn`') + def max(self) -> Dial: ... +@_deprecated('use `Dial`, whose \'level\' is "the same" at $0\nand past it') +class Knob(_Record): + level: _int + def __init__(self, level: _int) -> None: ... + def __eq__(self, other: _object) -> _bool: ... + def __repr__(self) -> _str: ... + @_staticmethod + def default() -> Knob: ... + def doubled(self) -> _int: ... class PolarPoint(_Record): turns: _int distance: _int @@ -897,6 +926,14 @@ class Handle(_n.Object): @_staticmethod def new(count: _int) -> Handle: ... def count(self) -> _int: ... +class Holder(_n.Object): + @_staticmethod + def new(level: _int) -> Holder: ... + @_property + @_deprecated('use `Dial`, whose \'level\' is "the same" at $0\nand past it') + def level_get(self) -> _int: ... + @_deprecated('use `Dial`, whose \'level\' is "the same" at $0\nand past it') + def doubled(self) -> _int: ... class Area(_n.Object): def __repr__(self) -> _str: ... def clone(self) -> Area: ... @@ -1251,6 +1288,12 @@ class Log(_abc.ABC): class Beat(_abc.ABC): @_abc.abstractmethod def beat(self) -> _int: ... +class Turner(_abc.ABC): + @_abc.abstractmethod + def by(self) -> _int: ... + @_deprecated('turn `Turner::by` instead') + @_abc.abstractmethod + def once(self) -> _int: ... class BoundsU64Exception(_Exception): def __init__(self, error: BoundsU64) -> None: ... def __str__(self) -> _str: ... @@ -1288,6 +1331,8 @@ class StringException(_Exception): def __str__(self) -> _str: ... LIMIT = 1000 FAR = 9223372036854775807 +URL = 1000 +STEP = 1 async def corner_later() -> _tuple[_int, _int]: ... async def fill_4(batch: Batch, v: _int) -> _array.array[_int]: ... async def fill_2(batch: Batch2, v: _int) -> _array.array[_int]: ... @@ -1301,6 +1346,8 @@ async def local_later(n: _int) -> _int: ... async def poll_tripled(n: _int) -> _int: ... async def parse_later(text: _str) -> _int: ... async def either_later(text: _str | None) -> _int: ... +@_deprecated('read its `level`') +async def level_later(dial: Dial) -> _int: ... def has_text(note: Note) -> _bool: ... def marked(api_marked: Mark) -> _int: ... def reading(n: _int) -> Reading | None: ... @@ -1540,6 +1587,10 @@ def same_socket_addr(v: _tuple[_str, _int] | _tuple[_str, _int, _int, _int]) -> def same_socket_addr_v4(v: _tuple[_str, _int]) -> _tuple[_str, _int]: ... def same_socket_addr_v6(v: _tuple[_str, _int] | _tuple[_str, _int, _int, _int]) -> _tuple[_str, _int, _int, _int]: ... def same_ip_addr(v: _ipaddress.IPv4Address | _ipaddress.IPv6Address) -> _ipaddress.IPv4Address | _ipaddress.IPv6Address: ... +def deprecated(note: _int) -> _int: ... +@_deprecated('') +def knob(dial: Dial) -> Knob: ... +def turned(dial: Dial, turner: Turner) -> Dial: ... def crowded(reading: Reading, a: Stamp, b: Stamp, n0: _int, n1: _int, n2: _int, n3: _int, n4: _int, n5: _int, n6: _int, n7: _int, n8: _int, n9: _int, n10: _int, n11: _int, n12: _int, n13: _int, n14: _int, n15: _int, n16: _int, n17: _int, n18: _int, n19: _int, n20: _int, n21: _int, n22: _int, n23: _int, n24: _int, n25: _int, n26: _int, n27: _int, n28: _int, n29: _int, n30: _int, n31: _int, n32: _int, n33: _int, n34: _int, n35: _int, n36: _int, n37: _int, n38: _int, n39: _int, n40: _int, n41: _int, n42: _int, n43: _int, n44: _int, n45: _int, n46: _int, n47: _int, n48: _int, n49: _int, n50: _int, n51: _int, n52: _int, n53: _int, n54: _int, n55: _int, n56: _int, n57: _int, n58: _int, n59: _int, n60: _int, n61: _int, n62: _int, n63: _int, n64: _int, n65: _int, n66: _int, n67: _int, n68: _int, n69: _int, n70: _int, n71: _int, n72: _int, n73: _int, n74: _int, n75: _int, n76: _int, n77: _int, n78: _int, n79: _int, n80: _int, n81: _int, n82: _int, n83: _int, n84: _int, n85: _int, n86: _int, n87: _int, n88: _int, n89: _int, n90: _int, n91: _int, n92: _int, n93: _int, n94: _int, n95: _int, n96: _int, n97: _int, n98: _int, n99: _int, n100: _int, n101: _int, n102: _int, n103: _int, n104: _int, n105: _int, n106: _int, n107: _int, n108: _int, n109: _int, n110: _int, n111: _int, n112: _int, n113: _int, n114: _int, n115: _int, n116: _int, n117: _int, n118: _int) -> _int: ... def crammed(a: Moment, b: Moment, n0: _int, n1: _int, n2: _int, n3: _int, n4: _int, n5: _int, n6: _int, n7: _int, n8: _int, n9: _int, n10: _int, n11: _int, n12: _int, n13: _int, n14: _int, n15: _int, n16: _int, n17: _int, n18: _int, n19: _int, n20: _int, n21: _int, n22: _int, n23: _int, n24: _int, n25: _int, n26: _int, n27: _int, n28: _int, n29: _int, n30: _int, n31: _int, n32: _int, n33: _int, n34: _int, n35: _int, n36: _int, n37: _int, n38: _int, n39: _int, n40: _int, n41: _int, n42: _int, n43: _int, n44: _int, n45: _int, n46: _int, n47: _int, n48: _int, n49: _int, n50: _int, n51: _int, n52: _int, n53: _int, n54: _int, n55: _int, n56: _int, n57: _int, n58: _int, n59: _int, n60: _int, n61: _int, n62: _int, n63: _int, n64: _int, n65: _int, n66: _int, n67: _int, n68: _int, n69: _int, n70: _int, n71: _int, n72: _int, n73: _int, n74: _int, n75: _int, n76: _int, n77: _int, n78: _int, n79: _int, n80: _int, n81: _int, n82: _int, n83: _int, n84: _int, n85: _int, n86: _int, n87: _int, n88: _int, n89: _int, n90: _int, n91: _int, n92: _int, n93: _int, n94: _int, n95: _int, n96: _int, n97: _int, n98: _int, n99: _int, n100: _int, n101: _int, n102: _int, n103: _int, n104: _int, n105: _int, n106: _int, n107: _int, n108: _int, n109: _int, n110: _int, n111: _int, n112: _int, n113: _int, n114: _int, n115: _int, n116: _int, n117: _int, n118: _int, n119: _int, n120: _int, n121: _int, n122: _int, n123: _int) -> _int: ... def jni_one() -> _int: ... @@ -1797,6 +1848,9 @@ same_socket_addr = _n.same_socket_addr same_socket_addr_v4 = _n.same_socket_addr_v4 same_socket_addr_v6 = _n.same_socket_addr_v6 same_ip_addr = _n.same_ip_addr +deprecated = _n.deprecated +knob = _n.knob +turned = _n.turned crowded = _n.crowded crammed = _n.crammed jni_one = _n.jni_one diff --git a/ffi/surface/api/swift.swift b/ffi/surface/api/swift.swift index 40eda7932..c3e8f71fc 100644 --- a/ffi/surface/api/swift.swift +++ b/ffi/surface/api/swift.swift @@ -578,6 +578,33 @@ public struct Qualifiers: Sendable, Equatable { @inlinable public init(api: Swift.Double, kotlin: Swift.Double) @inlinable public static func == (a: Qualifiers, b: Qualifiers) -> Swift.Bool } +public struct Deprecated: Sendable, CustomDebugStringConvertible, Equatable { + public var on: Swift.Bool + @available(*, deprecated) @inlinable public var lower: Swift.UInt32 { get set } + public var deprecated: Swift.Bool + @inlinable public init(on: Swift.Bool, lower: Swift.UInt32, deprecated: Swift.Bool) + @inlinable public var debugDescription: Swift.String { get } + @inlinable public static func == (a: Deprecated, b: Deprecated) -> Swift.Bool + @inlinable public static func `default`() -> Deprecated +} +public struct Dial: Sendable, CustomDebugStringConvertible, Equatable { + public var level: Swift.UInt64 + @available(*, deprecated, message: "keep the `Dial` from before the turn") @inlinable public var before: Swift.UInt64 { get set } + @inlinable public init(level: Swift.UInt64, before: Swift.UInt64) + @inlinable public var debugDescription: Swift.String { get } + @inlinable public static func == (a: Dial, b: Dial) -> Swift.Bool + @inlinable public static func `default`() -> Dial + @inlinable public func turn(_ by: Swift.UInt64) throws -> Dial + @available(*, deprecated, message: "turn it by `LIMIT` with `Dial::turn`") @inlinable public func max() -> Dial +} +@available(*, deprecated, message: "use `Dial`, whose 'level' is \"the same\" at $0\nand past it") public struct Knob: Sendable, CustomDebugStringConvertible, Equatable { + public var level: Swift.UInt64 + @inlinable public init(level: Swift.UInt64) + @inlinable public var debugDescription: Swift.String { get } + @inlinable public static func == (a: Knob, b: Knob) -> Swift.Bool + @inlinable public static func `default`() -> Knob + @inlinable public func doubled() -> Swift.UInt64 +} public struct PolarPoint: Sendable, CustomDebugStringConvertible, Equatable { public var turns: Swift.UInt8 public var distance: Swift.UInt32 @@ -932,6 +959,11 @@ public struct Handle: ~Copyable, @unchecked Sendable { @inlinable public func count() -> Swift.UInt32 @inlinable nonisolated(nonsending) public static func later(_ count: Swift.UInt32) async throws -> Handle } +public struct Holder: ~Copyable, @unchecked Sendable { + @inlinable public static func new(_ level: Swift.UInt64) -> Holder + @available(*, deprecated, message: "use `Dial`, whose 'level' is \"the same\" at $0\nand past it") @inlinable public var levelGet: Swift.UInt64 { get } + @available(*, deprecated, message: "use `Dial`, whose 'level' is \"the same\" at $0\nand past it") @inlinable public func doubled() -> Swift.UInt64 +} public struct Area: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } @inlinable public func clone() -> Area @@ -1274,6 +1306,10 @@ public protocol Log: Sendable { public protocol Beat: Sendable { func beat() -> Swift.UInt32 } +public protocol Turner: Sendable { + func by() -> Swift.UInt64 + func once() -> Swift.UInt64 +} public struct BoundsU64Error: Swift.Error, CustomStringConvertible { public let error: BoundsU64 @inlinable public init(error: BoundsU64) @@ -1294,6 +1330,8 @@ extension Fault: Swift.Error {} extension Refusal: Swift.Error {} public let LIMIT: Swift.UInt64 public let FAR: Swift.Int64 +public let URL: Swift.UInt64 +@available(*, deprecated, message: "pass a step to `Dial::turn`, whose `}` or `{` alone stays in the note") public let STEP: Swift.UInt64 @inlinable public func hasText(_ note: Note) -> Swift.Bool @inlinable public func marked(_ apiMarked: Mark) throws -> Swift.UInt64 @inlinable public func reading(_ n: Swift.UInt32) -> Reading? @@ -1552,6 +1590,10 @@ public let FAR: Swift.Int64 @inlinable public func sameSocketAddrV4(_ v: SocketAddrV4) -> SocketAddrV4 @inlinable public func sameSocketAddrV6(_ v: SocketAddrV6) -> SocketAddrV6 @inlinable public func sameIpAddr(_ v: IpAddr) -> IpAddr +@inlinable public func deprecated(_ note: Swift.UInt8) -> Swift.UInt8 +@available(*, deprecated) @inlinable public func knob(_ dial: Dial) -> Knob +@available(*, deprecated, message: "read its `level`") @inlinable nonisolated(nonsending) public func levelLater(_ dial: Dial) async throws -> Swift.UInt64 +@inlinable public func turned(_ dial: Dial, _ turner: any Turner) throws -> Dial @inlinable public func crowded(_ reading: Reading, _ a: Stamp, _ b: Stamp, _ n0: Swift.UInt64, _ n1: Swift.UInt64, _ n2: Swift.UInt64, _ n3: Swift.UInt64, _ n4: Swift.UInt64, _ n5: Swift.UInt64, _ n6: Swift.UInt64, _ n7: Swift.UInt64, _ n8: Swift.UInt64, _ n9: Swift.UInt64, _ n10: Swift.UInt64, _ n11: Swift.UInt64, _ n12: Swift.UInt64, _ n13: Swift.UInt64, _ n14: Swift.UInt64, _ n15: Swift.UInt64, _ n16: Swift.UInt64, _ n17: Swift.UInt64, _ n18: Swift.UInt64, _ n19: Swift.UInt64, _ n20: Swift.UInt64, _ n21: Swift.UInt64, _ n22: Swift.UInt64, _ n23: Swift.UInt64, _ n24: Swift.UInt64, _ n25: Swift.UInt64, _ n26: Swift.UInt64, _ n27: Swift.UInt64, _ n28: Swift.UInt64, _ n29: Swift.UInt64, _ n30: Swift.UInt64, _ n31: Swift.UInt64, _ n32: Swift.UInt64, _ n33: Swift.UInt64, _ n34: Swift.UInt64, _ n35: Swift.UInt64, _ n36: Swift.UInt64, _ n37: Swift.UInt64, _ n38: Swift.UInt64, _ n39: Swift.UInt64, _ n40: Swift.UInt64, _ n41: Swift.UInt64, _ n42: Swift.UInt64, _ n43: Swift.UInt64, _ n44: Swift.UInt64, _ n45: Swift.UInt64, _ n46: Swift.UInt64, _ n47: Swift.UInt64, _ n48: Swift.UInt64, _ n49: Swift.UInt64, _ n50: Swift.UInt64, _ n51: Swift.UInt64, _ n52: Swift.UInt64, _ n53: Swift.UInt64, _ n54: Swift.UInt64, _ n55: Swift.UInt64, _ n56: Swift.UInt64, _ n57: Swift.UInt64, _ n58: Swift.UInt64, _ n59: Swift.UInt64, _ n60: Swift.UInt64, _ n61: Swift.UInt64, _ n62: Swift.UInt64, _ n63: Swift.UInt64, _ n64: Swift.UInt64, _ n65: Swift.UInt64, _ n66: Swift.UInt64, _ n67: Swift.UInt64, _ n68: Swift.UInt64, _ n69: Swift.UInt64, _ n70: Swift.UInt64, _ n71: Swift.UInt64, _ n72: Swift.UInt64, _ n73: Swift.UInt64, _ n74: Swift.UInt64, _ n75: Swift.UInt64, _ n76: Swift.UInt64, _ n77: Swift.UInt64, _ n78: Swift.UInt64, _ n79: Swift.UInt64, _ n80: Swift.UInt64, _ n81: Swift.UInt64, _ n82: Swift.UInt64, _ n83: Swift.UInt64, _ n84: Swift.UInt64, _ n85: Swift.UInt64, _ n86: Swift.UInt64, _ n87: Swift.UInt64, _ n88: Swift.UInt64, _ n89: Swift.UInt64, _ n90: Swift.UInt64, _ n91: Swift.UInt64, _ n92: Swift.UInt64, _ n93: Swift.UInt64, _ n94: Swift.UInt64, _ n95: Swift.UInt64, _ n96: Swift.UInt64, _ n97: Swift.UInt64, _ n98: Swift.UInt64, _ n99: Swift.UInt64, _ n100: Swift.UInt64, _ n101: Swift.UInt64, _ n102: Swift.UInt64, _ n103: Swift.UInt64, _ n104: Swift.UInt64, _ n105: Swift.UInt64, _ n106: Swift.UInt64, _ n107: Swift.UInt64, _ n108: Swift.UInt64, _ n109: Swift.UInt64, _ n110: Swift.UInt64, _ n111: Swift.UInt64, _ n112: Swift.UInt64, _ n113: Swift.UInt64, _ n114: Swift.UInt64, _ n115: Swift.UInt64, _ n116: Swift.UInt64, _ n117: Swift.UInt64, _ n118: Swift.UInt64) -> Swift.UInt64 @inlinable public func crammed(_ a: Moment, _ b: Moment, _ n0: Swift.UInt64, _ n1: Swift.UInt64, _ n2: Swift.UInt64, _ n3: Swift.UInt64, _ n4: Swift.UInt64, _ n5: Swift.UInt64, _ n6: Swift.UInt64, _ n7: Swift.UInt64, _ n8: Swift.UInt64, _ n9: Swift.UInt64, _ n10: Swift.UInt64, _ n11: Swift.UInt64, _ n12: Swift.UInt64, _ n13: Swift.UInt64, _ n14: Swift.UInt64, _ n15: Swift.UInt64, _ n16: Swift.UInt64, _ n17: Swift.UInt64, _ n18: Swift.UInt64, _ n19: Swift.UInt64, _ n20: Swift.UInt64, _ n21: Swift.UInt64, _ n22: Swift.UInt64, _ n23: Swift.UInt64, _ n24: Swift.UInt64, _ n25: Swift.UInt64, _ n26: Swift.UInt64, _ n27: Swift.UInt64, _ n28: Swift.UInt64, _ n29: Swift.UInt64, _ n30: Swift.UInt64, _ n31: Swift.UInt64, _ n32: Swift.UInt64, _ n33: Swift.UInt64, _ n34: Swift.UInt64, _ n35: Swift.UInt64, _ n36: Swift.UInt64, _ n37: Swift.UInt64, _ n38: Swift.UInt64, _ n39: Swift.UInt64, _ n40: Swift.UInt64, _ n41: Swift.UInt64, _ n42: Swift.UInt64, _ n43: Swift.UInt64, _ n44: Swift.UInt64, _ n45: Swift.UInt64, _ n46: Swift.UInt64, _ n47: Swift.UInt64, _ n48: Swift.UInt64, _ n49: Swift.UInt64, _ n50: Swift.UInt64, _ n51: Swift.UInt64, _ n52: Swift.UInt64, _ n53: Swift.UInt64, _ n54: Swift.UInt64, _ n55: Swift.UInt64, _ n56: Swift.UInt64, _ n57: Swift.UInt64, _ n58: Swift.UInt64, _ n59: Swift.UInt64, _ n60: Swift.UInt64, _ n61: Swift.UInt64, _ n62: Swift.UInt64, _ n63: Swift.UInt64, _ n64: Swift.UInt64, _ n65: Swift.UInt64, _ n66: Swift.UInt64, _ n67: Swift.UInt64, _ n68: Swift.UInt64, _ n69: Swift.UInt64, _ n70: Swift.UInt64, _ n71: Swift.UInt64, _ n72: Swift.UInt64, _ n73: Swift.UInt64, _ n74: Swift.UInt64, _ n75: Swift.UInt64, _ n76: Swift.UInt64, _ n77: Swift.UInt64, _ n78: Swift.UInt64, _ n79: Swift.UInt64, _ n80: Swift.UInt64, _ n81: Swift.UInt64, _ n82: Swift.UInt64, _ n83: Swift.UInt64, _ n84: Swift.UInt64, _ n85: Swift.UInt64, _ n86: Swift.UInt64, _ n87: Swift.UInt64, _ n88: Swift.UInt64, _ n89: Swift.UInt64, _ n90: Swift.UInt64, _ n91: Swift.UInt64, _ n92: Swift.UInt64, _ n93: Swift.UInt64, _ n94: Swift.UInt64, _ n95: Swift.UInt64, _ n96: Swift.UInt64, _ n97: Swift.UInt64, _ n98: Swift.UInt64, _ n99: Swift.UInt64, _ n100: Swift.UInt64, _ n101: Swift.UInt64, _ n102: Swift.UInt64, _ n103: Swift.UInt64, _ n104: Swift.UInt64, _ n105: Swift.UInt64, _ n106: Swift.UInt64, _ n107: Swift.UInt64, _ n108: Swift.UInt64, _ n109: Swift.UInt64, _ n110: Swift.UInt64, _ n111: Swift.UInt64, _ n112: Swift.UInt64, _ n113: Swift.UInt64, _ n114: Swift.UInt64, _ n115: Swift.UInt64, _ n116: Swift.UInt64, _ n117: Swift.UInt64, _ n118: Swift.UInt64, _ n119: Swift.UInt64, _ n120: Swift.UInt64, _ n121: Swift.UInt64, _ n122: Swift.UInt64, _ n123: Swift.UInt64) -> Swift.UInt64 @inlinable public func jniOne() -> Swift.UInt32 diff --git a/ffi/surface/api/web.d.ts b/ffi/surface/api/web.d.ts index 1db810bc7..369e2854f 100644 --- a/ffi/surface/api/web.d.ts +++ b/ffi/surface/api/web.d.ts @@ -380,12 +380,37 @@ import * as rt from "./rt.ts"; export type Cursor = rt.Handle<"Cursor">; export declare function at(self: Cursor): rt.u64; +// Deprecated.ts +export type Deprecated = { + on: boolean; + lower: number; + deprecated: boolean; +}; +export declare function debug(self: Deprecated): string; +export declare function eq(a: Deprecated, b: Deprecated): boolean; +export declare function default$(): Deprecated; +export { default$ as default }; + // Der.ts import * as rt from "./rt.ts"; export type Der = rt.Handle<"Der">; export declare function fromSlice(bytes: Uint8Array | rt.Bytes): Der; export declare function bytes(self: Der): rt.Bytes; +// Dial.ts +import * as rt from "./rt.ts"; +import type { Error_ } from "./Error_.ts"; +export type Dial = { + level: rt.u64; + before: rt.u64; +}; +export declare function debug(self: Dial): string; +export declare function eq(a: Dial, b: Dial): boolean; +export declare function default$(): Dial; +export declare function turn(self: Dial, by: rt.u64): rt.Result; +export declare function max(self: Dial): Dial; +export { default$ as default }; + // Digest.ts import * as rt from "./rt.ts"; export type Digest = rt.Handle<"Digest">; @@ -517,6 +542,14 @@ export declare function add(self: Hits, other: Hits): Hits; export declare function eq_(self: Hits, other: Hits): [Hits, boolean]; export { default$ as default }; +// Holder.ts +import * as rt from "./rt.ts"; +export type Holder = rt.Handle<"Holder">; +export declare function new$(level: rt.u64): Holder; +export declare function levelGet(self: Holder): rt.u64; +export declare function doubled(self: Holder): rt.u64; +export { new$ as new }; + // InnerU8.ts export type InnerU8 = { value: number; @@ -572,6 +605,17 @@ export declare function new$(name: string): Key; export declare function hashOf(self: Key): rt.u64; export { new$ as new }; +// Knob.ts +import * as rt from "./rt.ts"; +export type Knob = { + level: rt.u64; +}; +export declare function debug(self: Knob): string; +export declare function eq(a: Knob, b: Knob): boolean; +export declare function default$(): Knob; +export declare function doubled(self: Knob): rt.u64; +export { default$ as default }; + // Label.ts import * as rt from "./rt.ts"; import type { Point } from "./Point.ts"; @@ -1409,6 +1453,14 @@ export declare function bytes(self: Trail): rt.Bytes; export declare function drain(self: Trail): Label[]; export { new$ as new }; +// Turner.ts +import * as rt from "./rt.ts"; +export interface Turner { + by(): rt.u64; + once(): rt.u64; + close?(): void; +} + // Url.ts import * as rt from "./rt.ts"; export type Url = rt.Handle<"Url">; @@ -1516,6 +1568,8 @@ import type { ClashTone_ } from "./ClashTone_.ts"; import type { Clocked } from "./Clocked.ts"; import type { Counter } from "./Counter.ts"; import type { Cursor } from "./Cursor.ts"; +import type { Deprecated } from "./Deprecated.ts"; +import type { Dial } from "./Dial.ts"; import type { DoubleArray } from "./DoubleArray.ts"; import type { Error_ } from "./Error_.ts"; import type { Event } from "./Event.ts"; @@ -1528,6 +1582,7 @@ import type { InnerU8 } from "./InnerU8.ts"; import type { Json } from "./Json.ts"; import type { JvmField } from "./JvmField.ts"; import type { JvmStatic } from "./JvmStatic.ts"; +import type { Knob } from "./Knob.ts"; import type { Label } from "./Label.ts"; import type { Labelled } from "./Labelled.ts"; import type { LeftRightU8 } from "./LeftRightU8.ts"; @@ -1629,6 +1684,7 @@ export declare const k_Filed_Receipt: rt.Kind; export declare const k_Gap: rt.Kind; export declare const k_Gauge: rt.Kind; export declare const k_Handle: rt.Kind; +export declare const k_Holder: rt.Kind; export declare const k_Instant: rt.Kind; export declare const k_Journal: rt.Kind; export declare const k_Json: rt.Kind; @@ -1708,6 +1764,7 @@ export declare function p_either_later(f: number, w$: number): [boolean, number] export declare function p_fill_2(f: number, w$: number): [boolean, Uint32Array]; export declare function p_fill_4(f: number, w$: number): [boolean, Uint32Array]; export declare function p_halved(f: number, w$: number): [boolean, number | undefined]; +export declare function p_level_later(f: number, w$: number): [boolean, rt.u64]; export declare function p_local_after(f: number, w$: number): [boolean, Local]; export declare function p_local_later(f: number, w$: number): [boolean, number]; export declare function p_local_or_new_later(f: number, w$: number): [boolean, Local]; @@ -1721,10 +1778,13 @@ export declare function r_Boxed_u16(p: number, o: boolean): BoxedU16; export declare function r_Boxed_u8(p: number, o: boolean): BoxedU8; export declare function r_Clash(p: number, o: boolean): Clash; export declare function r_Clocked(p: number, o: boolean): Clocked; +export declare function r_Deprecated(p: number, o: boolean): Deprecated; +export declare function r_Dial(p: number, o: boolean): Dial; export declare function r_Error(p: number, o: boolean): Error_; export declare function r_Event(p: number, o: boolean): Event; export declare function r_Extent(p: number, o: boolean): Extent; export declare function r_Hits(p: number, o: boolean): Hits; +export declare function r_Knob(p: number, o: boolean): Knob; export declare function r_Label(p: number, o: boolean): Label; export declare function r_Labelled(p: number, o: boolean): Labelled; export declare function r_Limits_bytes(p: number, o: boolean): LimitsBytes; @@ -1884,6 +1944,7 @@ export declare function t_Ticket(p: number, v: Ticket): void; export declare function t_option_Moment(p: number, v: Moment | undefined): void; export declare function vt_Beat(): number; export declare function vt_Log(): number; +export declare function vt_Turner(): number; export declare function w_Atlas(p: number, v: Atlas): void; export declare function w_Booth(p: number, v: Booth): void; export declare function w_Boxed_u16(p: number, v: BoxedU16): void; @@ -1893,6 +1954,8 @@ export declare function w_Cancelled(p: number, v: Cancelled): void; export declare function w_Choice(p: number, v: Choice): void; export declare function w_Clash(p: number, v: Clash): void; export declare function w_Clocked(p: number, v: Clocked): void; +export declare function w_Deprecated(p: number, v: Deprecated): void; +export declare function w_Dial(p: number, v: Dial): void; export declare function w_DoubleArray(p: number, v: DoubleArray): void; export declare function w_Error(p: number, v: Error_): void; export declare function w_Event(p: number, v: Event): void; @@ -1901,6 +1964,7 @@ export declare function w_Hits(p: number, v: Hits): void; export declare function w_Inner_u8(p: number, v: InnerU8): void; export declare function w_JvmField(p: number, v: JvmField): void; export declare function w_JvmStatic(p: number, v: JvmStatic): void; +export declare function w_Knob(p: number, v: Knob): void; export declare function w_Label(p: number, v: Label): void; export declare function w_Labelled(p: number, v: Labelled): void; export declare function w_Left_Right_u8(p: number, v: LeftRightU8): void; @@ -2063,6 +2127,8 @@ export declare function w_vec_vec_u32_2(p: number, v: number[][] | undefined): v export declare const imports: { api_web_cb_Beat_beat: (data: number) => number; api_web_cb_Log_log: (data: number, p0: number, p1: number) => number; + api_web_cb_Turner_by: (data: number) => bigint; + api_web_cb_Turner_once: (data: number) => bigint; api_web_i_fn_0: (data: number, p0: bigint) => void; api_web_i_fn_1: (data: number) => number; api_web_i_fn_10: (data: number, p0: number) => bigint; @@ -2098,6 +2164,7 @@ import type { ClashTone } from "./ClashTone.ts"; import type { Clocked } from "./Clocked.ts"; import type { Counter } from "./Counter.ts"; import type { Cursor } from "./Cursor.ts"; +import type { Dial } from "./Dial.ts"; import type { Draft } from "./Draft.ts"; import type { Error_ } from "./Error_.ts"; import type { Event } from "./Event.ts"; @@ -2108,6 +2175,7 @@ import type { Instant } from "./Instant.ts"; import type { Json } from "./Json.ts"; import type { JvmField } from "./JvmField.ts"; import type { JvmStatic } from "./JvmStatic.ts"; +import type { Knob } from "./Knob.ts"; import type { Label } from "./Label.ts"; import type { Labelled } from "./Labelled.ts"; import type { LeftRightU8 } from "./LeftRightU8.ts"; @@ -2153,12 +2221,15 @@ import type { TlsCert } from "./TlsCert.ts"; import type { TlsConfig } from "./TlsConfig.ts"; import type { TlsResolver } from "./TlsResolver.ts"; import type { TlsSession } from "./TlsSession.ts"; +import type { Turner } from "./Turner.ts"; import type { Url } from "./Url.ts"; import type { Waiter } from "./Waiter.ts"; import type { WrapU32 } from "./WrapU32.ts"; export declare function load(source?: rt.Source): Promise; export declare const LIMIT: rt.u64; export declare const FAR: rt.i64; +export declare const URL$: rt.u64; +export declare const STEP: rt.u64; export declare function hasText(note: Note): boolean; export declare function marked(apiMarked: Mark): rt.u64; export declare function reading(n: number): Reading | undefined; @@ -2485,6 +2556,10 @@ export declare function sameSocketAddr(v: rt.SocketAddr): rt.SocketAddr; export declare function sameSocketAddrV4(v: rt.SocketAddrV4): rt.SocketAddrV4; export declare function sameSocketAddrV6(v: rt.SocketAddrV6): rt.SocketAddrV6; export declare function sameIpAddr(v: rt.IpAddr): rt.IpAddr; +export declare function deprecated(note: number): number; +export declare function knob(dial: Dial): Knob; +export declare function levelLater(dial: Dial): rt.Call; +export declare function turned(dial: Dial, turner: Turner): rt.Result; export declare function crowded(reading: Reading, a: Stamp, b: Stamp, n0: rt.u64, n1: rt.u64, n2: rt.u64, n3: rt.u64, n4: rt.u64, n5: rt.u64, n6: rt.u64, n7: rt.u64, n8: rt.u64, n9: rt.u64, n10: rt.u64, n11: rt.u64, n12: rt.u64, n13: rt.u64, n14: rt.u64, n15: rt.u64, n16: rt.u64, n17: rt.u64, n18: rt.u64, n19: rt.u64, n20: rt.u64, n21: rt.u64, n22: rt.u64, n23: rt.u64, n24: rt.u64, n25: rt.u64, n26: rt.u64, n27: rt.u64, n28: rt.u64, n29: rt.u64, n30: rt.u64, n31: rt.u64, n32: rt.u64, n33: rt.u64, n34: rt.u64, n35: rt.u64, n36: rt.u64, n37: rt.u64, n38: rt.u64, n39: rt.u64, n40: rt.u64, n41: rt.u64, n42: rt.u64, n43: rt.u64, n44: rt.u64, n45: rt.u64, n46: rt.u64, n47: rt.u64, n48: rt.u64, n49: rt.u64, n50: rt.u64, n51: rt.u64, n52: rt.u64, n53: rt.u64, n54: rt.u64, n55: rt.u64, n56: rt.u64, n57: rt.u64, n58: rt.u64, n59: rt.u64, n60: rt.u64, n61: rt.u64, n62: rt.u64, n63: rt.u64, n64: rt.u64, n65: rt.u64, n66: rt.u64, n67: rt.u64, n68: rt.u64, n69: rt.u64, n70: rt.u64, n71: rt.u64, n72: rt.u64, n73: rt.u64, n74: rt.u64, n75: rt.u64, n76: rt.u64, n77: rt.u64, n78: rt.u64, n79: rt.u64, n80: rt.u64, n81: rt.u64, n82: rt.u64, n83: rt.u64, n84: rt.u64, n85: rt.u64, n86: rt.u64, n87: rt.u64, n88: rt.u64, n89: rt.u64, n90: rt.u64, n91: rt.u64, n92: rt.u64, n93: rt.u64, n94: rt.u64, n95: rt.u64, n96: rt.u64, n97: rt.u64, n98: rt.u64, n99: rt.u64, n100: rt.u64, n101: rt.u64, n102: rt.u64, n103: rt.u64, n104: rt.u64, n105: rt.u64, n106: rt.u64, n107: rt.u64, n108: rt.u64, n109: rt.u64, n110: rt.u64, n111: rt.u64, n112: rt.u64, n113: rt.u64, n114: rt.u64, n115: rt.u64, n116: rt.u64, n117: rt.u64, n118: rt.u64): rt.u64; export declare function crammed(a: Moment, b: Moment, n0: rt.u64, n1: rt.u64, n2: rt.u64, n3: rt.u64, n4: rt.u64, n5: rt.u64, n6: rt.u64, n7: rt.u64, n8: rt.u64, n9: rt.u64, n10: rt.u64, n11: rt.u64, n12: rt.u64, n13: rt.u64, n14: rt.u64, n15: rt.u64, n16: rt.u64, n17: rt.u64, n18: rt.u64, n19: rt.u64, n20: rt.u64, n21: rt.u64, n22: rt.u64, n23: rt.u64, n24: rt.u64, n25: rt.u64, n26: rt.u64, n27: rt.u64, n28: rt.u64, n29: rt.u64, n30: rt.u64, n31: rt.u64, n32: rt.u64, n33: rt.u64, n34: rt.u64, n35: rt.u64, n36: rt.u64, n37: rt.u64, n38: rt.u64, n39: rt.u64, n40: rt.u64, n41: rt.u64, n42: rt.u64, n43: rt.u64, n44: rt.u64, n45: rt.u64, n46: rt.u64, n47: rt.u64, n48: rt.u64, n49: rt.u64, n50: rt.u64, n51: rt.u64, n52: rt.u64, n53: rt.u64, n54: rt.u64, n55: rt.u64, n56: rt.u64, n57: rt.u64, n58: rt.u64, n59: rt.u64, n60: rt.u64, n61: rt.u64, n62: rt.u64, n63: rt.u64, n64: rt.u64, n65: rt.u64, n66: rt.u64, n67: rt.u64, n68: rt.u64, n69: rt.u64, n70: rt.u64, n71: rt.u64, n72: rt.u64, n73: rt.u64, n74: rt.u64, n75: rt.u64, n76: rt.u64, n77: rt.u64, n78: rt.u64, n79: rt.u64, n80: rt.u64, n81: rt.u64, n82: rt.u64, n83: rt.u64, n84: rt.u64, n85: rt.u64, n86: rt.u64, n87: rt.u64, n88: rt.u64, n89: rt.u64, n90: rt.u64, n91: rt.u64, n92: rt.u64, n93: rt.u64, n94: rt.u64, n95: rt.u64, n96: rt.u64, n97: rt.u64, n98: rt.u64, n99: rt.u64, n100: rt.u64, n101: rt.u64, n102: rt.u64, n103: rt.u64, n104: rt.u64, n105: rt.u64, n106: rt.u64, n107: rt.u64, n108: rt.u64, n109: rt.u64, n110: rt.u64, n111: rt.u64, n112: rt.u64, n113: rt.u64, n114: rt.u64, n115: rt.u64, n116: rt.u64, n117: rt.u64, n118: rt.u64, n119: rt.u64, n120: rt.u64, n121: rt.u64, n122: rt.u64, n123: rt.u64): rt.u64; export declare function jniOne(): number; @@ -2497,6 +2572,7 @@ export declare function clashAudible(tone: ClashTone): rt.Result