1use 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#[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#[derive(Debug, Clone, serde::Serialize)]
76pub struct WcModel {
77 pub unit: String,
78 pub service: String,
79 pub kind: WcBoundaryKind,
80 pub range: Range,
84 #[serde(rename = "handlerLine")]
85 pub handler_line: usize,
86 pub envelope: WcEnvelope,
87 pub contract: Option<WcContractForm>,
89 pub types: Vec<WcType>,
90 pub instantiations: Vec<WcInst>,
91 pub recursive: Vec<String>,
92 pub responses: Vec<WcHttpResponse>,
94 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 pub payload: Option<WcRef>,
154 pub body: Option<WcResponseBody>,
157}
158
159#[derive(Debug, Clone, serde::Serialize)]
161#[serde(tag = "kind")]
162pub enum WcResponseBody {
163 Value {
165 #[serde(rename = "ref")]
166 ty: WcRef,
167 },
168 Message,
170 Redirect { header: &'static str },
172 Raw,
174 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 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 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 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 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
323fn 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
373fn 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
495fn 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 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
551fn 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
677pub 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 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}