Skip to main content

bynk_lsp/
wire_contract_request.rs

1//! #855: `bynk/wireContract` — the wire-contract-peek custom LSP request.
2//!
3//! File-scoped + position, like #846's `bynk/sequenceModel` (the panel is
4//! per-handler, not project-wide like #851's `bynk/architectureModel`): the
5//! params carry a `textDocument` + `position` and the result is one
6//! handler's wire contract, or `null` when nothing resolves. Same on-demand
7//! posture as every custom request in this server — no `workspace/*/refresh`
8//! nudge exists for one and none is needed (see `sequence_request`'s module
9//! doc for why).
10//!
11//! Two responsibilities live here: [`WcModel`] and its hand-mirrored `Wc*`
12//! siblings — a plain serde shape for [`bynk_ide::wire_contract::WireContractModel`]
13//! and everything it contains ([`bynk_check::wire::WireModel`] included) —
14//! and [`to_wire`], which lowers one to the other, `Span` → `{uri, range}`
15//! the same way `architecture_request.rs` does (this module reuses its
16//! `WireLoc` under the `WcLoc` alias rather than redeclaring an identical
17//! struct).
18//!
19//! **Cross-file type locations.** A boundary type may be declared in a
20//! *different* file than the handler being hovered — the whole reason
21//! `ContextBoundaryInfo::types` (Phase 3) is a *combined* table (own
22//! declarations plus every `uses` target's). `WireContractModel::type_sites`
23//! (`bynk-ide/src/wire_contract.rs`) carries only a bare `Span` per type
24//! name, with no file — a single project-relative path cannot be assumed
25//! (that path is the *handler's* file, not necessarily the type's). This
26//! module resolves each boundary type's own file the same way every other
27//! cross-file lookup in this server does: through the already-assembled
28//! [`bynk_check::index::ProjectIndex`], searching the candidate units in
29//! `doc_scope`'s order (itself first, then `uses` targets, then `consumes`
30//! targets — #848's existing search order, reused rather than re-derived).
31//! A type whose def cannot be resolved this way renders with `loc: null`
32//! rather than a guessed location — the same "never send a bogus location"
33//! rule `architecture_request.rs`'s `wire_loc` follows.
34
35use std::collections::HashMap;
36use std::path::{Path, PathBuf};
37use std::sync::Arc;
38
39use bynk_check::index::{ProjectIndex, SymbolKey, SymbolKind};
40use bynk_check::wire::{
41    self, BaseGuard, Expected, JsonKind, Provenance, Revalidation, UncheckedReason, WireBody,
42    WireField, WireInst, WireModel, WireRef, WireScalar, WireSum, WireType,
43};
44use bynk_ide::wire_contract::{
45    BoundaryKind, Envelope, HttpResponse, NoCrossContextReason, REDIRECT_HEADER, ResponseBody,
46    ResponseOrigin, WireContractModel, response_body,
47};
48use bynk_syntax::ast::{PredKind, TypeDecl};
49use tower_lsp::lsp_types::Range;
50
51pub use crate::architecture_request::WireLoc as WcLoc;
52
53/// The `bynk/wireContract` request payload — a text-document position, the
54/// same two-field shape `SequenceModelParams`/every cursor-anchored request
55/// in this server uses.
56///
57/// `rename_all = "camelCase"` is load-bearing: the client sends the LSP wire
58/// names `textDocument`/`position`, and #846 already shipped once as a
59/// missing-field bug from omitting this (see `sequence_request`'s and
60/// `architecture_request`'s own params docs).
61#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
62#[serde(rename_all = "camelCase")]
63pub struct WireContractParams {
64    pub text_document: tower_lsp::lsp_types::TextDocumentIdentifier,
65    pub position: tower_lsp::lsp_types::Position,
66}
67
68// ---------------------------------------------------------------------
69// Wire shape: a plain serde mirror of `bynk_ide::wire_contract::WireContractModel`
70// (and, transitively, `bynk_check::wire::WireModel`) — `Wc`-prefixed to
71// avoid the `WireWireContractModel`-style stutter a bare `Wire*` prefix
72// would produce given this module already imports the real `Wire*` types.
73// ---------------------------------------------------------------------
74
75#[derive(Debug, Clone, serde::Serialize)]
76pub struct WcModel {
77    pub unit: String,
78    pub service: String,
79    pub kind: WcBoundaryKind,
80    /// The handler's own header/signature span, against the request
81    /// document (the handler's own file — never cross-file, unlike a
82    /// boundary type's `loc`).
83    pub range: Range,
84    #[serde(rename = "handlerLine")]
85    pub handler_line: usize,
86    pub envelope: WcEnvelope,
87    /// `on call` only; `null` whenever `noCrossContext` is set.
88    pub contract: Option<WcContractForm>,
89    pub types: Vec<WcType>,
90    pub instantiations: Vec<WcInst>,
91    pub recursive: Vec<String>,
92    /// Empty for a non-HTTP handler.
93    pub responses: Vec<WcHttpResponse>,
94    /// #3609: the `T` of the handler's `HttpResult[T]`, resolved against
95    /// `types`/`instantiations`. `null` for a non-HTTP handler and for a raw or
96    /// unit-payload return.
97    pub success: Option<WcRef>,
98    #[serde(rename = "noCrossContext")]
99    pub no_cross_context: Option<&'static str>,
100}
101
102#[derive(Debug, Clone, serde::Serialize)]
103#[serde(tag = "kind")]
104pub enum WcBoundaryKind {
105    Http { method: &'static str, path: String },
106    Call,
107    Cron { expr: String },
108    Message,
109    Open,
110    Close,
111    Event,
112    Rejected,
113}
114
115#[derive(Debug, Clone, serde::Serialize)]
116#[serde(tag = "kind")]
117pub enum WcEnvelope {
118    Empty,
119    Bare {
120        param: String,
121        shape: WcRef,
122    },
123    Keyed {
124        params: Vec<WcParam>,
125    },
126    Raw {
127        param: String,
128        #[serde(rename = "contentType")]
129        content_type: String,
130    },
131}
132
133#[derive(Debug, Clone, serde::Serialize)]
134pub struct WcParam {
135    pub name: String,
136    pub shape: WcRef,
137}
138
139#[derive(Debug, Clone, serde::Serialize)]
140pub struct WcContractForm {
141    #[serde(rename = "normalForm")]
142    pub normal_form: String,
143    pub hash: String,
144}
145
146#[derive(Debug, Clone, serde::Serialize)]
147pub struct WcHttpResponse {
148    pub status: u16,
149    pub variant: String,
150    pub origin: WcResponseOrigin,
151    /// #3609: `T` for a value variant, `null` otherwise. The value-only ref;
152    /// [`Self::body`] describes every other kind of body.
153    pub payload: Option<WcRef>,
154    /// #3632: what the response body is. `null` when there is none to describe
155    /// (a no-payload variant, a `()` value, a boundary-implicit response).
156    pub body: Option<WcResponseBody>,
157}
158
159/// #3632: a response body, the same classification `bynk openapi` makes.
160#[derive(Debug, Clone, serde::Serialize)]
161#[serde(tag = "kind")]
162pub enum WcResponseBody {
163    /// `T`, JSON-encoded; `ref` is the same ref as `payload`.
164    Value {
165        #[serde(rename = "ref")]
166        ty: WcRef,
167    },
168    /// `{ "error": String }`.
169    Message,
170    /// No body; the target is in `header`.
171    Redirect { header: &'static str },
172    /// Author-owned bytes, no codec.
173    Raw,
174    /// `text/event-stream`.
175    Stream,
176}
177
178#[derive(Debug, Clone, serde::Serialize)]
179#[serde(tag = "kind")]
180pub enum WcResponseOrigin {
181    DeclaredSuccess,
182    Constructed { range: Range },
183    BoundaryImplicit { why: &'static str },
184}
185
186#[derive(Debug, Clone, serde::Serialize)]
187pub struct WcType {
188    pub name: String,
189    #[serde(rename = "codecSuffix")]
190    pub codec_suffix: String,
191    pub provenance: WcProvenance,
192    pub body: WcBody,
193    /// `null` when the declaring file could not be resolved through the
194    /// index (defensive only — see the module doc).
195    pub loc: Option<WcLoc>,
196}
197
198#[derive(Debug, Clone, serde::Serialize)]
199#[serde(tag = "kind")]
200pub enum WcProvenance {
201    Owned,
202    Consumed {
203        #[serde(rename = "ownerUnit")]
204        owner_unit: String,
205    },
206}
207
208#[derive(Debug, Clone, serde::Serialize)]
209#[serde(tag = "kind")]
210pub enum WcBody {
211    Scalar {
212        base: &'static str,
213        json: &'static str,
214        opaque: bool,
215        /// Declaration order — see `bynk_check::wire`'s module doc on why
216        /// this must never be sorted.
217        predicates: Vec<String>,
218        #[serde(rename = "baseGuards")]
219        base_guards: Vec<&'static str>,
220        revalidation: &'static str,
221    },
222    Record {
223        fields: Vec<WcField>,
224    },
225    Sum {
226        #[serde(rename = "wireDiscriminant")]
227        wire_discriminant: &'static str,
228        #[serde(rename = "memoryDiscriminant")]
229        memory_discriminant: &'static str,
230        variants: Vec<WcVariant>,
231    },
232}
233
234#[derive(Debug, Clone, serde::Serialize)]
235pub struct WcField {
236    pub name: String,
237    pub shape: WcRef,
238    #[serde(rename = "pathSegment")]
239    pub path_segment: String,
240    /// The default initialiser's source rendering (`bynk_fmt::expr_to_string`),
241    /// `null` when the field has none.
242    pub default: Option<String>,
243}
244
245#[derive(Debug, Clone, serde::Serialize)]
246pub struct WcVariant {
247    pub name: String,
248    pub payload: Vec<WcField>,
249}
250
251#[derive(Debug, Clone, serde::Serialize)]
252#[serde(tag = "kind")]
253pub enum WcRef {
254    Base {
255        base: &'static str,
256        json: &'static str,
257        guards: Vec<&'static str>,
258        expected: WcExpected,
259    },
260    Bytes,
261    Decimal,
262    Named {
263        name: String,
264    },
265    Inst {
266        key: String,
267    },
268    Unit,
269    Unchecked {
270        reason: &'static str,
271    },
272}
273
274#[derive(Debug, Clone, serde::Serialize)]
275#[serde(tag = "kind")]
276pub enum WcExpected {
277    Json { json: &'static str },
278    Integer,
279    FiniteNumber,
280    Base64String,
281    SumVariantKind,
282}
283
284#[derive(Debug, Clone, serde::Serialize)]
285#[serde(tag = "kind")]
286pub enum WcInst {
287    ResultInst {
288        key: String,
289        ok: WcRef,
290        err: WcRef,
291    },
292    OptionInst {
293        key: String,
294        inner: WcRef,
295    },
296    ListInst {
297        key: String,
298        elem: WcRef,
299    },
300    /// K6a (#2596): a `Set[T]` instantiation.
301    SetInst {
302        key: String,
303        elem: WcRef,
304    },
305    MapInst {
306        key: String,
307        #[serde(rename = "mapKey")]
308        map_key: WcRef,
309        val: WcRef,
310    },
311    RecordInst {
312        key: String,
313        name: String,
314        args: Vec<WcRef>,
315    },
316    SumInst {
317        key: String,
318        name: String,
319        args: Vec<WcRef>,
320    },
321}
322
323// -- scalar enum -> wire-string helpers (matches this codebase's convention
324// -- of `&'static str` fields over deriving `Serialize` on the upstream
325// -- enums directly — see `sequence_request.rs`'s `participant_kind_str` etc).
326
327fn json_kind_str(j: JsonKind) -> &'static str {
328    match j {
329        JsonKind::Number => "Number",
330        JsonKind::String => "String",
331        JsonKind::Boolean => "Boolean",
332        JsonKind::Object => "Object",
333        JsonKind::Array => "Array",
334        JsonKind::Null => "Null",
335    }
336}
337
338fn base_guard_str(g: BaseGuard) -> &'static str {
339    match g {
340        BaseGuard::Integral => "Integral",
341        BaseGuard::Finite => "Finite",
342    }
343}
344
345fn unchecked_reason_str(r: UncheckedReason) -> &'static str {
346    match r {
347        UncheckedReason::Effect => "Effect",
348        UncheckedReason::ValidationError => "ValidationError",
349        UncheckedReason::DecodeError => "DecodeError",
350        UncheckedReason::HttpResult => "HttpResult",
351        UncheckedReason::QueueResult => "QueueResult",
352        UncheckedReason::Asset => "Asset",
353    }
354}
355
356fn revalidation_str(r: Revalidation) -> &'static str {
357    match r {
358        Revalidation::ViaConstructor => "ViaConstructor",
359        Revalidation::Inline => "Inline",
360        Revalidation::StructuralOnly => "StructuralOnly",
361        Revalidation::Base64Decode => "Base64Decode",
362        Revalidation::DecimalParse => "DecimalParse",
363    }
364}
365
366fn no_cross_context_str(r: NoCrossContextReason) -> &'static str {
367    match r {
368        NoCrossContextReason::NotACallHandler => "NotACallHandler",
369        NoCrossContextReason::SingleContext => "SingleContext",
370    }
371}
372
373/// A `PredKind`'s source-like rendering, predicate args included
374/// (`MaxLength(20)`, not just `"MaxLength"`) — `PredKind::name()`
375/// (`bynk-syntax/src/ast.rs`) drops the payload, which the peek's whole
376/// point is to show. Mirrors `bynk_fmt::fmt`'s private `pred_to_string`
377/// (that one renders a `RefinementPred`, the AST wrapper; `WireScalar::
378/// predicates` is bare `Vec<PredKind>`, `bynk-check/src/wire.rs`'s own
379/// extraction), reusing its public `escape_string` rather than
380/// re-implementing string escaping.
381fn pred_kind_str(p: &PredKind) -> String {
382    match p {
383        PredKind::Matches(re) => format!("Matches(\"{}\")", bynk_fmt::escape_string(re)),
384        PredKind::InRange(a, b) => format!("InRange({}, {})", a.value, b.value),
385        PredKind::InRangeF(a, b) => format!("InRange({}, {})", a.lexeme, b.lexeme),
386        PredKind::InRangeD(a, b) => format!("InRange({}, {})", a.lexeme, b.lexeme),
387        PredKind::MinLength(n) => format!("MinLength({n})"),
388        PredKind::MaxLength(n) => format!("MaxLength({n})"),
389        PredKind::Length(n) => format!("Length({n})"),
390        PredKind::NonNegative => "NonNegative".to_string(),
391        PredKind::Positive => "Positive".to_string(),
392        PredKind::NonEmpty => "NonEmpty".to_string(),
393        PredKind::IsoDate => "IsoDate".to_string(),
394        PredKind::Cron => "Cron".to_string(),
395    }
396}
397
398fn provenance_wire(p: &Provenance) -> WcProvenance {
399    match p {
400        Provenance::Owned => WcProvenance::Owned,
401        Provenance::Consumed { owner_unit } => WcProvenance::Consumed {
402            owner_unit: owner_unit.clone(),
403        },
404    }
405}
406
407fn expected_wire(e: &Expected) -> WcExpected {
408    match e {
409        Expected::Json(j) => WcExpected::Json {
410            json: json_kind_str(*j),
411        },
412        Expected::Integer => WcExpected::Integer,
413        Expected::FiniteNumber => WcExpected::FiniteNumber,
414        Expected::Base64String => WcExpected::Base64String,
415        Expected::SumVariantKind => WcExpected::SumVariantKind,
416    }
417}
418
419fn wc_ref(r: &WireRef) -> WcRef {
420    match r {
421        WireRef::Base {
422            base,
423            json,
424            guards,
425            expected,
426        } => WcRef::Base {
427            base: base.name(),
428            json: json_kind_str(*json),
429            guards: guards.iter().map(|g| base_guard_str(*g)).collect(),
430            expected: expected_wire(expected),
431        },
432        WireRef::Bytes => WcRef::Bytes,
433        WireRef::Decimal => WcRef::Decimal,
434        WireRef::Named { name } => WcRef::Named {
435            name: bynk_check::symbols::display_type_name(name).to_string(),
436        },
437        WireRef::Inst { key } => WcRef::Inst { key: key.clone() },
438        WireRef::Unit => WcRef::Unit,
439        WireRef::Unchecked { reason } => WcRef::Unchecked {
440            reason: unchecked_reason_str(*reason),
441        },
442    }
443}
444
445fn wc_field(f: &WireField) -> WcField {
446    WcField {
447        name: f.name.clone(),
448        shape: wc_ref(&f.shape),
449        path_segment: f.path_segment.clone(),
450        default: f
451            .default
452            .as_ref()
453            .map(|(e, _ty)| bynk_fmt::expr_to_string(e)),
454    }
455}
456
457fn wc_body(b: &WireBody) -> WcBody {
458    match b {
459        WireBody::Scalar(WireScalar {
460            base,
461            json,
462            opaque,
463            predicates,
464            base_guards,
465            revalidation,
466        }) => WcBody::Scalar {
467            base: base.name(),
468            json: json_kind_str(*json),
469            opaque: *opaque,
470            predicates: predicates.iter().map(pred_kind_str).collect(),
471            base_guards: base_guards.iter().map(|g| base_guard_str(*g)).collect(),
472            revalidation: revalidation_str(*revalidation),
473        },
474        WireBody::Record { fields } => WcBody::Record {
475            fields: fields.iter().map(wc_field).collect(),
476        },
477        WireBody::Sum(WireSum {
478            wire_discriminant,
479            memory_discriminant,
480            variants,
481        }) => WcBody::Sum {
482            wire_discriminant,
483            memory_discriminant,
484            variants: variants
485                .iter()
486                .map(|v| WcVariant {
487                    name: v.name.clone(),
488                    payload: v.payload.iter().map(wc_field).collect(),
489                })
490                .collect(),
491        },
492    }
493}
494
495/// Resolve `name`'s own declaration site through the project index,
496/// searching `search_order` (self-first — #848's `doc_scope` order) so a
497/// type declared in a different file of the same unit, or in a `uses`
498/// target, resolves to *its* file rather than the handler's. `None` when no
499/// candidate unit's index entry resolves — the type renders with `loc:
500/// null` rather than a guessed location.
501fn resolve_type_loc(
502    project_root: &Path,
503    index: &ProjectIndex,
504    snapshots: &HashMap<PathBuf, String>,
505    search_order: &[String],
506    name: &str,
507) -> Option<WcLoc> {
508    for unit in search_order {
509        let key = SymbolKey {
510            unit: unit.clone(),
511            kind: SymbolKind::Type,
512            name: name.to_string(),
513        };
514        let Some(entry) = index.symbols.get(&key) else {
515            continue;
516        };
517        let Some(def) = &entry.def else { continue };
518        let Some(text) = snapshots.get(&def.path) else {
519            continue;
520        };
521        let Ok(uri) = tower_lsp::lsp_types::Url::from_file_path(project_root.join(&def.path))
522        else {
523            continue;
524        };
525        return Some(WcLoc {
526            uri,
527            range: crate::position::span_to_range(text, def.span),
528        });
529    }
530    None
531}
532
533fn wc_type(
534    t: &WireType,
535    project_root: &Path,
536    index: &ProjectIndex,
537    snapshots: &HashMap<PathBuf, String>,
538    search_order: &[String],
539) -> WcType {
540    // #2087: a qualified key reads, and resolves, as its declaration's name.
541    let name = bynk_check::symbols::display_type_name(&t.name);
542    WcType {
543        name: name.to_string(),
544        codec_suffix: t.codec_suffix.clone(),
545        provenance: provenance_wire(&t.provenance),
546        body: wc_body(&t.body),
547        loc: resolve_type_loc(project_root, index, snapshots, search_order, name),
548    }
549}
550
551/// Lower one boundary occurrence of a generic instantiation. `WireInst`
552/// (`bynk-check/src/wire.rs`) carries raw `TypeRef`s for its type
553/// arguments — the same "shape, not TS" IR the emitter's codec generation
554/// renders — so each argument is resolved through
555/// [`bynk_check::wire::wire_ref`] (the same single-level resolver
556/// `wire_contract_for_service` uses for envelope params) before lowering,
557/// which is why `types` (the owning unit's combined type table) threads
558/// through here.
559fn wc_inst(inst: &WireInst, types: &HashMap<String, Arc<TypeDecl>>) -> WcInst {
560    let key = inst.ts_name();
561    match inst {
562        WireInst::ResultInst { ok, err } => WcInst::ResultInst {
563            key,
564            ok: wc_ref(&wire::wire_ref(ok, types)),
565            err: wc_ref(&wire::wire_ref(err, types)),
566        },
567        WireInst::OptionInst { inner } => WcInst::OptionInst {
568            key,
569            inner: wc_ref(&wire::wire_ref(inner, types)),
570        },
571        WireInst::ListInst { elem } => WcInst::ListInst {
572            key,
573            elem: wc_ref(&wire::wire_ref(elem, types)),
574        },
575        WireInst::SetInst { elem } => WcInst::SetInst {
576            key,
577            elem: wc_ref(&wire::wire_ref(elem, types)),
578        },
579        WireInst::MapInst { key: k, val } => WcInst::MapInst {
580            key,
581            map_key: wc_ref(&wire::wire_ref(k, types)),
582            val: wc_ref(&wire::wire_ref(val, types)),
583        },
584        WireInst::RecordInst { name, args } => WcInst::RecordInst {
585            key,
586            name: name.clone(),
587            args: args
588                .iter()
589                .map(|a| wc_ref(&wire::wire_ref(a, types)))
590                .collect(),
591        },
592        WireInst::SumInst { name, args } => WcInst::SumInst {
593            key,
594            name: name.clone(),
595            args: args
596                .iter()
597                .map(|a| wc_ref(&wire::wire_ref(a, types)))
598                .collect(),
599        },
600    }
601}
602
603fn boundary_kind_wire(k: &BoundaryKind) -> WcBoundaryKind {
604    match k {
605        BoundaryKind::Http { method, path } => WcBoundaryKind::Http {
606            method: method.as_str(),
607            path: path.clone(),
608        },
609        BoundaryKind::Call => WcBoundaryKind::Call,
610        BoundaryKind::Cron { expr } => WcBoundaryKind::Cron { expr: expr.clone() },
611        BoundaryKind::Message => WcBoundaryKind::Message,
612        BoundaryKind::Open => WcBoundaryKind::Open,
613        BoundaryKind::Close => WcBoundaryKind::Close,
614        BoundaryKind::Event => WcBoundaryKind::Event,
615        BoundaryKind::Rejected => WcBoundaryKind::Rejected,
616    }
617}
618
619fn envelope_wire(e: &Envelope) -> WcEnvelope {
620    match e {
621        Envelope::Empty => WcEnvelope::Empty,
622        Envelope::Bare { param, shape } => WcEnvelope::Bare {
623            param: param.clone(),
624            shape: wc_ref(shape),
625        },
626        Envelope::Raw {
627            param,
628            content_type,
629        } => WcEnvelope::Raw {
630            param: param.clone(),
631            content_type: content_type.clone(),
632        },
633        Envelope::Keyed { params } => WcEnvelope::Keyed {
634            params: params
635                .iter()
636                .map(|(n, s)| WcParam {
637                    name: n.clone(),
638                    shape: wc_ref(s),
639                })
640                .collect(),
641        },
642    }
643}
644
645fn wc_response_body(b: &ResponseBody) -> WcResponseBody {
646    match b {
647        ResponseBody::Value(v) => WcResponseBody::Value { ty: wc_ref(v) },
648        ResponseBody::Message => WcResponseBody::Message,
649        ResponseBody::Redirect => WcResponseBody::Redirect {
650            header: REDIRECT_HEADER,
651        },
652        ResponseBody::Raw => WcResponseBody::Raw,
653        ResponseBody::Stream => WcResponseBody::Stream,
654    }
655}
656
657fn wc_response(r: &HttpResponse, success: Option<&WireRef>, text: &str) -> WcHttpResponse {
658    let body = response_body(r, success);
659    WcHttpResponse {
660        status: r.status,
661        variant: r.variant.clone(),
662        payload: match &body {
663            Some(ResponseBody::Value(v)) => Some(wc_ref(v)),
664            _ => None,
665        },
666        body: body.as_ref().map(wc_response_body),
667        origin: match &r.origin {
668            ResponseOrigin::DeclaredSuccess => WcResponseOrigin::DeclaredSuccess,
669            ResponseOrigin::Constructed { span } => WcResponseOrigin::Constructed {
670                range: crate::position::span_to_range(text, *span),
671            },
672            ResponseOrigin::BoundaryImplicit { why } => WcResponseOrigin::BoundaryImplicit { why },
673        },
674    }
675}
676
677/// Lower a [`WireContractModel`] to its wire shape.
678///
679/// `text` is the handler's **own** file's committed snapshot (the request
680/// document) — `model.handler_span` and each HTTP response's `Constructed`
681/// span both index into it. `types` is the owning unit's combined type
682/// table (`ContextBoundaryInfo::types`), needed to resolve each generic
683/// instantiation's type-argument shapes (see `wc_inst`). `index` +
684/// `snapshots` + `search_order` resolve each boundary type's own declaring
685/// file (see the module doc's "Cross-file type locations" section) — a
686/// deliberate widening of the plan's sketched `to_wire(model, project_root,
687/// snapshots)` signature, which had no way to know *which* file a `uses`-
688/// imported boundary type's span belongs to.
689pub fn to_wire(
690    model: &WireContractModel,
691    project_root: &Path,
692    text: &str,
693    types: &HashMap<String, Arc<TypeDecl>>,
694    index: &ProjectIndex,
695    snapshots: &HashMap<PathBuf, String>,
696    search_order: &[String],
697) -> WcModel {
698    let WireModel {
699        types: wtypes,
700        instantiations,
701        recursive,
702    } = &model.boundary;
703    WcModel {
704        unit: model.unit.clone(),
705        service: model.service.clone(),
706        kind: boundary_kind_wire(&model.kind),
707        range: crate::position::span_to_range(text, model.handler_span),
708        handler_line: model.handler_line,
709        envelope: envelope_wire(&model.envelope),
710        contract: model.contract.as_ref().map(|c| WcContractForm {
711            // #2087: shown with each qualified key as its declaration's name;
712            // `hash` is still over the canonical form.
713            normal_form: bynk_check::symbols::display_type_names_in(&c.normal_form),
714            hash: c.hash.clone(),
715        }),
716        types: wtypes
717            .iter()
718            .map(|t| wc_type(t, project_root, index, snapshots, search_order))
719            .collect(),
720        instantiations: instantiations.iter().map(|i| wc_inst(i, types)).collect(),
721        recursive: recursive.iter().cloned().collect(),
722        responses: model
723            .responses
724            .iter()
725            .map(|r| wc_response(r, model.success.as_ref(), text))
726            .collect(),
727        success: model.success.as_ref().map(wc_ref),
728        no_cross_context: model.no_cross_context.map(no_cross_context_str),
729    }
730}
731
732#[cfg(test)]
733mod tests {
734    use super::*;
735
736    #[test]
737    fn params_deserialize_from_camel_case_wire_json() {
738        let json = serde_json::json!({
739            "textDocument": { "uri": "file:///a/b.bynk" },
740            "position": { "line": 3, "character": 7 },
741        });
742        let params: WireContractParams =
743            serde_json::from_value(json).expect("camelCase textDocument/position must deserialize");
744        assert_eq!(params.text_document.uri.as_str(), "file:///a/b.bynk");
745        assert_eq!(params.position.line, 3);
746        assert_eq!(params.position.character, 7);
747    }
748
749    #[test]
750    fn pred_kind_str_renders_predicate_arguments_not_just_the_bare_name() {
751        assert_eq!(pred_kind_str(&PredKind::NonEmpty), "NonEmpty");
752        assert_eq!(pred_kind_str(&PredKind::MaxLength(20)), "MaxLength(20)");
753    }
754}