1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
use std::error::Error;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_false(b: &bool) -> bool {
  !(*b)
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Field {
  /// The name of the field.
  pub name: String,

  /// The type of the field.
  #[serde(rename = "type")]
  #[cfg_attr(feature = "parser", serde(deserialize_with = "crate::signatures::type_signature"))]
  #[cfg_attr(
    feature = "yaml",
    serde(serialize_with = "serde_yaml::with::singleton_map::serialize")
  )]
  pub ty: TypeSignature,

  /// Whether the field is required.
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub default: Option<serde_yaml::Value>,

  /// Whether the field is required.
  #[serde(default, skip_serializing_if = "is_false")]
  pub required: bool,

  /// The description of the field.
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub description: Option<String>,
}

impl Field {
  pub fn new(name: impl AsRef<str>, ty: TypeSignature) -> Self {
    Self {
      name: name.as_ref().to_owned(),
      description: None,
      default: None,
      required: false,
      ty,
    }
  }
}

impl std::fmt::Display for Field {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.write_str(&self.name);
    f.write_str(": ")?;
    self.ty.fmt(f)
  }
}

/// The signature of a Wick component, including its input and output types.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[must_use]
pub struct OperationSignature {
  /// The name of the component.
  #[serde(default)]
  pub name: String,
  /// The component's inputs.
  #[serde(default)]
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub inputs: Vec<Field>,
  /// The component's outputs.
  #[serde(default)]
  #[serde(skip_serializing_if = "Vec::is_empty")]
  pub outputs: Vec<Field>,
}

impl OperationSignature {
  /// Create a new [ComponentSignature] with the passed name.
  pub fn new<T: AsRef<str>>(name: T) -> Self {
    Self {
      name: name.as_ref().to_owned(),
      ..Default::default()
    }
  }

  /// Add an input port.
  pub fn add_input(mut self, name: impl AsRef<str>, ty: TypeSignature) -> Self {
    self.inputs.push(Field::new(name, ty));
    self
  }

  /// Add an input port.
  pub fn add_output(mut self, name: impl AsRef<str>, ty: TypeSignature) -> Self {
    self.outputs.push(Field::new(name, ty));
    self
  }
}

#[derive(Debug, Clone, Copy, PartialEq, serde_repr::Deserialize_repr, serde_repr::Serialize_repr)]
#[must_use]
#[repr(u32)]
/// The umbrella version of the component.
pub enum ComponentVersion {
  /// Version 0 Wick components.
  V0 = 0,
  /// Version 1 Wick components.
  V1 = 1,
}

impl Default for ComponentVersion {
  fn default() -> Self {
    Self::V1
  }
}

impl From<ComponentVersion> for u32 {
  fn from(v: ComponentVersion) -> Self {
    match v {
      ComponentVersion::V0 => 0,
      ComponentVersion::V1 => 1,
    }
  }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[must_use]
/// The Wick features this collection supports.
pub struct ComponentMetadata {
  /// Version of the component.
  #[serde(skip_serializing_if = "Option::is_none  ")]
  pub version: Option<String>,
}

impl ComponentMetadata {
  /// Quickly create a v0 feature set.
  pub fn v0() -> Self {
    Self { version: None }
  }
}

impl Default for ComponentMetadata {
  fn default() -> Self {
    Self::v0()
  }
}

/// Signature for Collections.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[must_use]
pub struct ComponentSignature {
  /// Name of the collection.
  pub name: Option<String>,

  /// The format of the component signature.
  pub format: ComponentVersion,

  /// Component implementation version.
  #[serde(default)]
  pub metadata: ComponentMetadata,

  /// A map of type signatures referenced elsewhere.
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub wellknown: Vec<WellKnownSchema>,

  /// A map of type signatures referenced elsewhere.
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub types: Vec<TypeDefinition>,

  /// A list of [OperationSignature]s in this component.
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub operations: Vec<OperationSignature>,
  /// The component's configuration for this implementation.

  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub config: Vec<TypeDefinition>,
}

impl ComponentSignature {
  /// Create a new [ComponentSignature] with the passed name.
  pub fn new<T: AsRef<str>>(name: T) -> Self {
    Self {
      name: Some(name.as_ref().to_owned()),
      ..Default::default()
    }
  }

  #[must_use]
  /// Get the [ComponentSignature] for the requested component.
  pub fn get_component(&self, field: &str) -> Option<&OperationSignature> {
    self.operations.iter().find(|op| op.name == field)
  }

  /// Add a [ComponentSignature] to the collection.
  pub fn add_component(mut self, signature: OperationSignature) -> Self {
    self.operations.push(signature);
    self
  }

  /// Set the version of the [ComponentSignature].
  pub fn version(mut self, version: impl AsRef<str>) -> Self {
    self.metadata.version = Some(version.as_ref().to_owned());
    self
  }

  /// Set the format of the [ComponentSignature].
  pub fn format(mut self, format: ComponentVersion) -> Self {
    self.format = format;
    self
  }

  /// Set the features of the [ComponentSignature].
  pub fn metadata(mut self, features: ComponentMetadata) -> Self {
    self.metadata = features;
    self
  }
}

/// An entry from a well-known schema
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct WellKnownSchema {
  /// The capability the schema provides.
  pub capabilities: Vec<String>,
  /// The location where you can find and validate the schema.
  pub url: String,
  /// The schema itself.
  pub schema: ComponentSignature,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[must_use]
/// A valid type definition.
#[serde(tag = "type")]
pub enum TypeDefinition {
  /// A struct definition.
  #[serde(rename = "struct")]
  Struct(StructSignature),
  /// An enum definition.
  #[serde(rename = "enum")]
  Enum(EnumSignature),
}

/// Signatures of enum type definitions.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[must_use]
pub struct EnumSignature {
  /// The name of the enum.
  pub name: String,
  /// The variants in the enum.
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub variants: Vec<EnumVariant>,
}

impl EnumSignature {
  /// Constructor for [EnumSignature]
  pub fn new<T: AsRef<str>>(name: T, variants: Vec<EnumVariant>) -> Self {
    Self {
      name: name.as_ref().to_owned(),
      variants,
    }
  }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[must_use]
/// An enum variant definition
pub struct EnumVariant {
  /// The name of the variant.
  pub name: String,
  /// The index of the variant.
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub index: Option<u32>,
  /// The optional value of the variant.
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub value: Option<String>,
}

impl EnumVariant {
  /// Constructor for [EnumVariant]
  pub fn new<T: AsRef<str>>(name: T, index: Option<u32>, value: Option<String>) -> Self {
    Self {
      name: name.as_ref().to_owned(),
      index,
      value,
    }
  }
}

/// Signatures of struct-like type definitions.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[must_use]
pub struct StructSignature {
  /// The name of the struct.
  pub name: String,
  /// The fields in this struct.
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub fields: Vec<Field>,
}

impl StructSignature {
  /// Constructor for [StructSignature]
  pub fn new<T: AsRef<str>>(name: T, fields: Vec<Field>) -> Self {
    Self {
      name: name.as_ref().to_owned(),
      fields,
    }
  }
}

/// An enum representing the types of components that can be hosted.
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[must_use]
pub enum HostedType {
  /// A collection.
  Collection(ComponentSignature),
}

impl HostedType {
  /// Get the name of the [HostedType] regardless of kind.
  #[must_use]
  pub fn get_name(&self) -> &Option<String> {
    match self {
      HostedType::Collection(s) => &s.name,
    }
  }
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
#[must_use]
/// Enum of valid types.
pub enum TypeSignature {
  /// I8 type.
  I8,
  /// I16 type.
  I16,
  /// I32 type.
  I32,
  /// I64 type.
  I64,
  /// u8 type.
  U8,
  /// u16 type.
  U16,
  /// u32 type.
  U32,
  /// u64 type.
  U64,
  /// f32 type.
  F32,
  /// f64 type.
  F64,
  /// Boolean type.
  Bool,
  /// String type.
  String,
  /// Date type.
  Datetime,
  /// Raw bytes.
  Bytes,
  /// Any valid value.
  Value,
  /// A custom type name.
  Custom(String),
  /// An internal type.
  Internal(InternalType),
  /// A reference to another type.
  Ref {
    #[serde(rename = "ref")]
    /// The reference string
    reference: String,
  },
  /// A stream type
  Stream {
    /// The inner type
    #[serde(rename = "type")]
    #[cfg_attr(
      feature = "parser",
      serde(deserialize_with = "crate::signatures::box_type_signature")
    )]
    #[cfg_attr(
      feature = "yaml",
      serde(serialize_with = "serde_yaml::with::singleton_map::serialize")
    )]
    ty: Box<TypeSignature>,
  },
  /// A list type
  List {
    /// The type of the list's elements
    #[serde(rename = "type")]
    #[cfg_attr(
      feature = "parser",
      serde(deserialize_with = "crate::signatures::box_type_signature")
    )]
    #[cfg_attr(
      feature = "yaml",
      serde(serialize_with = "serde_yaml::with::singleton_map::serialize")
    )]
    ty: Box<TypeSignature>,
  },
  /// A type representing an optional value.
  Optional {
    /// The actual type that is optional.
    #[serde(rename = "type")]
    #[cfg_attr(
      feature = "parser",
      serde(deserialize_with = "crate::signatures::box_type_signature")
    )]
    #[cfg_attr(
      feature = "yaml",
      serde(serialize_with = "serde_yaml::with::singleton_map::serialize")
    )]
    ty: Box<TypeSignature>,
  },
  /// A HashMap-like type.
  Map {
    /// The type of the map's keys.
    #[cfg_attr(
      feature = "parser",
      serde(deserialize_with = "crate::signatures::box_type_signature")
    )]
    #[cfg_attr(
      feature = "yaml",
      serde(serialize_with = "serde_yaml::with::singleton_map::serialize")
    )]
    key: Box<TypeSignature>,
    /// The type of the map's values.
    #[cfg_attr(
      feature = "parser",
      serde(deserialize_with = "crate::signatures::box_type_signature")
    )]
    #[cfg_attr(
      feature = "yaml",
      serde(serialize_with = "serde_yaml::with::singleton_map::serialize")
    )]
    value: Box<TypeSignature>,
  },
  /// A type representing a link to another collection.
  Link {
    /// The schemas that must be provided with the linked collection.
    #[serde(default)]
    schemas: Vec<String>,
  },
  /// A JSON-like key/value map.
  Struct,
  /// An inline, anonymous struct interface.
  AnonymousStruct(
    /// A list of fields in the struct.
    Vec<Field>,
  ),
}

fn stringify<S>(x: &str, s: S) -> Result<S::Ok, S::Error>
where
  S: serde::Serializer,
{
  println!("{:?}", x);
  s.serialize_str(x)
}

impl std::fmt::Display for TypeSignature {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      TypeSignature::I8 => f.write_str("i8"),
      TypeSignature::I16 => f.write_str("i16"),
      TypeSignature::I32 => f.write_str("i32"),
      TypeSignature::I64 => f.write_str("i64"),
      TypeSignature::U8 => f.write_str("u8"),
      TypeSignature::U16 => f.write_str("u16"),
      TypeSignature::U32 => f.write_str("u32"),
      TypeSignature::U64 => f.write_str("u64"),
      TypeSignature::F32 => f.write_str("f32"),
      TypeSignature::F64 => f.write_str("f64"),
      TypeSignature::Bool => f.write_str("bool"),
      TypeSignature::String => f.write_str("string"),
      TypeSignature::Datetime => f.write_str("datetime"),
      TypeSignature::Bytes => f.write_str("bytes"),
      TypeSignature::Value => f.write_str("value"),
      TypeSignature::Custom(_) => todo!(),
      TypeSignature::Internal(_) => todo!(),
      TypeSignature::Ref { reference } => todo!(),
      TypeSignature::Stream { ty } => todo!(),
      TypeSignature::List { ty } => todo!(),
      TypeSignature::Optional { ty } => todo!(),
      TypeSignature::Map { key, value } => todo!(),
      TypeSignature::Link { schemas } => todo!(),
      TypeSignature::Struct => todo!(),
      TypeSignature::AnonymousStruct(_) => todo!(),
    }
  }
}

#[derive(Debug)]
/// Error returned when attempting to convert an invalid source into a Wick type.
pub struct ParseError(String);
impl Error for ParseError {}
impl std::fmt::Display for ParseError {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "Could not parse {} into a TypeSignature.", self.0)
  }
}

#[cfg(feature = "parser")]
impl FromStr for TypeSignature {
  type Err = ParseError;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    crate::parser::parse(s).map_err(|e| ParseError(s.to_owned()))
  }
}

fn is_valid_typeid(name: &str) -> bool {
  name.chars().all(|c| c.is_alphanumeric() || c == '_')
}

/// Internal types for use within the Wick runtime
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Copy)]
#[serde(tag = "id")]
pub enum InternalType {
  /// Represents a complete set of component inputs
  #[serde(rename = "__input__")]
  OperationInput,
}

impl FromStr for InternalType {
  type Err = ParseError;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    let t = match s {
      "component_input" => Self::OperationInput,
      _ => return Err(ParseError(s.to_owned())),
    };
    Ok(t)
  }
}

#[cfg(feature = "parser")]
pub(crate) fn type_signature<'de, D>(deserializer: D) -> Result<TypeSignature, D::Error>
where
  D: serde::Deserializer<'de>,
{
  struct TypeSignatureVisitor;

  impl<'de> serde::de::Visitor<'de> for TypeSignatureVisitor {
    type Value = TypeSignature;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
      formatter.write_str("a TypeSignature definition")
    }

    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
    where
      E: serde::de::Error,
    {
      TypeSignature::from_str(s).map_err(|e| serde::de::Error::custom(e.to_string()))
    }

    fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
    where
      A: serde::de::MapAccess<'de>,
    {
      TypeSignature::deserialize(serde::de::value::MapAccessDeserializer::new(map))
    }
  }

  deserializer.deserialize_any(TypeSignatureVisitor)
}

#[cfg(feature = "parser")]
pub(crate) fn box_type_signature<'de, D>(deserializer: D) -> Result<Box<TypeSignature>, D::Error>
where
  D: serde::Deserializer<'de>,
{
  struct TypeSignatureVisitor;

  impl<'de> serde::de::Visitor<'de> for TypeSignatureVisitor {
    type Value = Box<TypeSignature>;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
      formatter.write_str("a TypeSignature definition")
    }

    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
    where
      E: serde::de::Error,
    {
      TypeSignature::from_str(s)
        .map(Box::new)
        .map_err(|e| serde::de::Error::custom(e.to_string()))
    }

    fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
    where
      A: serde::de::MapAccess<'de>,
    {
      TypeSignature::deserialize(serde::de::value::MapAccessDeserializer::new(map)).map(Box::new)
    }
  }

  deserializer.deserialize_any(TypeSignatureVisitor)
}