wit-parser 0.247.0

Tooling for parsing `*.wit` files and working with their contents.
Documentation
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
#![no_std]

extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

use crate::abi::AbiVariant;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
#[cfg(feature = "std")]
use anyhow::Context;
use anyhow::{Result, bail};
use id_arena::{Arena, Id};
use semver::Version;

#[cfg(feature = "std")]
pub type IndexMap<K, V> = indexmap::IndexMap<K, V, std::hash::RandomState>;
#[cfg(feature = "std")]
pub type IndexSet<T> = indexmap::IndexSet<T, std::hash::RandomState>;
#[cfg(not(feature = "std"))]
pub type IndexMap<K, V> = indexmap::IndexMap<K, V, hashbrown::DefaultHashBuilder>;
#[cfg(not(feature = "std"))]
pub type IndexSet<T> = indexmap::IndexSet<T, hashbrown::DefaultHashBuilder>;

#[cfg(feature = "std")]
pub(crate) use std::collections::{HashMap, HashSet};

#[cfg(not(feature = "std"))]
pub(crate) use hashbrown::{HashMap, HashSet};

use alloc::borrow::Cow;
use core::fmt;
use core::hash::{Hash, Hasher};
#[cfg(feature = "std")]
use std::path::Path;

#[cfg(feature = "decoding")]
pub mod decoding;
#[cfg(feature = "decoding")]
mod metadata;
#[cfg(feature = "decoding")]
pub use metadata::PackageMetadata;

pub mod abi;
mod ast;
pub use ast::SourceMap;
pub use ast::error::*;
pub use ast::lex::Span;
pub use ast::{ParsedUsePath, parse_use_path};
mod sizealign;
pub use sizealign::*;
mod resolve;
pub use resolve::*;
mod live;
pub use live::{LiveTypes, TypeIdVisitor};

#[cfg(feature = "serde")]
use serde_derive::Serialize;
#[cfg(feature = "serde")]
mod serde_;
#[cfg(feature = "serde")]
use serde_::*;

/// Checks if the given string is a legal identifier in wit.
pub fn validate_id(s: &str) -> Result<()> {
    ast::validate_id(0, s)?;
    Ok(())
}

pub type WorldId = Id<World>;
pub type InterfaceId = Id<Interface>;
pub type TypeId = Id<TypeDef>;

/// Representation of a parsed WIT package which has not resolved external
/// dependencies yet.
///
/// This representation has performed internal resolution of the WIT package
/// itself, ensuring that all references internally are valid and the WIT was
/// syntactically valid and such.
///
/// The fields of this structure represent a flat list of arrays unioned from
/// all documents within the WIT package. This means, for example, that all
/// types from all documents are located in `self.types`. The fields of each
/// item can help splitting back out into packages/interfaces/etc as necessary.
///
/// Note that an `UnresolvedPackage` cannot be queried in general about
/// information such as size or alignment as that would require resolution of
/// foreign dependencies. Translations such as to-binary additionally are not
/// supported on an `UnresolvedPackage` due to the lack of knowledge about the
/// foreign types. This is intended to be an intermediate state which can be
/// inspected by embedders, if necessary, before quickly transforming to a
/// [`Resolve`] to fully work with a WIT package.
///
/// After an [`UnresolvedPackage`] is parsed it can be fully resolved with
/// [`Resolve::push`]. During this operation a dependency map is specified which
/// will connect the `foreign_deps` field of this structure to packages
/// previously inserted within the [`Resolve`]. Embedders are responsible for
/// performing this resolution themselves.
#[derive(Clone, PartialEq, Eq)]
pub struct UnresolvedPackage {
    /// The namespace, name, and version information for this package.
    pub name: PackageName,

    /// All worlds from all documents within this package.
    ///
    /// Each world lists the document that it is from.
    pub worlds: Arena<World>,

    /// All interfaces from all documents within this package.
    ///
    /// Each interface lists the document that it is from. Interfaces are listed
    /// in topological order as well so iteration through this arena will only
    /// reference prior elements already visited when working with recursive
    /// references.
    pub interfaces: Arena<Interface>,

    /// All types from all documents within this package.
    ///
    /// Each type lists the interface or world that defined it, or nothing if
    /// it's an anonymous type. Types are listed in this arena in topological
    /// order to ensure that iteration through this arena will only reference
    /// other types transitively that are already iterated over.
    pub types: Arena<TypeDef>,

    /// All foreign dependencies that this package depends on.
    ///
    /// These foreign dependencies must be resolved to convert this unresolved
    /// package into a `Resolve`. The map here is keyed by the name of the
    /// foreign package that this depends on, and the sub-map is keyed by an
    /// interface name followed by the identifier within `self.interfaces`. The
    /// fields of `self.interfaces` describes the required types that are from
    /// each foreign interface.
    pub foreign_deps: IndexMap<PackageName, IndexMap<String, (AstItem, Vec<Stability>)>>,

    /// Doc comments for this package.
    pub docs: Docs,

    #[cfg_attr(not(feature = "std"), allow(dead_code))]
    package_name_span: Span,
    unknown_type_spans: Vec<Span>,
    foreign_dep_spans: Vec<Span>,
    required_resource_types: Vec<(TypeId, Span)>,
}

impl UnresolvedPackage {
    /// Adjusts all spans in this package by adding the given byte offset.
    ///
    /// This is used when merging source maps to update spans to point to the
    /// correct location in the combined source map.
    pub(crate) fn adjust_spans(&mut self, offset: u32) {
        // Adjust parallel vec spans
        self.package_name_span.adjust(offset);
        for span in &mut self.unknown_type_spans {
            span.adjust(offset);
        }
        for span in &mut self.foreign_dep_spans {
            span.adjust(offset);
        }
        for (_, span) in &mut self.required_resource_types {
            span.adjust(offset);
        }

        // Adjust spans on arena items
        for (_, world) in self.worlds.iter_mut() {
            world.adjust_spans(offset);
        }
        for (_, iface) in self.interfaces.iter_mut() {
            iface.adjust_spans(offset);
        }
        for (_, ty) in self.types.iter_mut() {
            ty.adjust_spans(offset);
        }
    }
}

/// Tracks a set of packages, all pulled from the same group of WIT source files.
#[derive(Clone, PartialEq, Eq)]
pub struct UnresolvedPackageGroup {
    /// The "main" package in this package group which was found at the root of
    /// the WIT files.
    ///
    /// Note that this is required to be present in all WIT files.
    pub main: UnresolvedPackage,

    /// Nested packages found while parsing `main`, if any.
    pub nested: Vec<UnresolvedPackage>,

    /// A set of processed source files from which these packages have been parsed.
    pub source_map: SourceMap,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum AstItem {
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
    Interface(InterfaceId),
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
    World(WorldId),
}

/// A structure used to keep track of the name of a package, containing optional
/// information such as a namespace and version information.
///
/// This is directly encoded as an "ID" in the binary component representation
/// with an interfaced tacked on as well.
#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(into = "String"))]
pub struct PackageName {
    /// A namespace such as `wasi` in `wasi:foo/bar`
    pub namespace: String,
    /// The kebab-name of this package, which is always specified.
    pub name: String,
    /// Optional major/minor version information.
    pub version: Option<Version>,
}

impl From<PackageName> for String {
    fn from(name: PackageName) -> String {
        name.to_string()
    }
}

impl PackageName {
    /// Returns the ID that this package name would assign the `interface` name
    /// specified.
    pub fn interface_id(&self, interface: &str) -> String {
        let mut s = String::new();
        s.push_str(&format!("{}:{}/{interface}", self.namespace, self.name));
        if let Some(version) = &self.version {
            s.push_str(&format!("@{version}"));
        }
        s
    }

    /// Determines the "semver compatible track" for the given version.
    ///
    /// This method implements the logic from the component model where semver
    /// versions can be compatible with one another. For example versions 1.2.0
    /// and 1.2.1 would be considered both compatible with one another because
    /// they're on the same semver compatible track.
    ///
    /// This predicate is used during
    /// [`Resolve::merge_world_imports_based_on_semver`] for example to
    /// determine whether two imports can be merged together. This is
    /// additionally used when creating components to match up imports in
    /// core wasm to imports in worlds.
    pub fn version_compat_track(version: &Version) -> Version {
        let mut version = version.clone();
        version.build = semver::BuildMetadata::EMPTY;
        if !version.pre.is_empty() {
            return version;
        }
        if version.major != 0 {
            version.minor = 0;
            version.patch = 0;
            return version;
        }
        if version.minor != 0 {
            version.patch = 0;
            return version;
        }
        version
    }

    /// Returns the string corresponding to
    /// [`PackageName::version_compat_track`]. This is done to match the
    /// component model's expected naming scheme of imports and exports.
    pub fn version_compat_track_string(version: &Version) -> String {
        let version = Self::version_compat_track(version);
        if !version.pre.is_empty() {
            return version.to_string();
        }
        if version.major != 0 {
            return format!("{}", version.major);
        }
        if version.minor != 0 {
            return format!("{}.{}", version.major, version.minor);
        }
        version.to_string()
    }
}

impl fmt::Display for PackageName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.namespace, self.name)?;
        if let Some(version) = &self.version {
            write!(f, "@{version}")?;
        }
        Ok(())
    }
}

#[derive(Debug)]
struct Error {
    span: Span,
    msg: String,
    highlighted: Option<String>,
}

impl Error {
    fn new(span: Span, msg: impl Into<String>) -> Error {
        Error {
            span,
            msg: msg.into(),
            highlighted: None,
        }
    }

    /// Highlights this error using the given source map, if the span is known.
    fn highlight(&mut self, source_map: &ast::SourceMap) {
        if self.highlighted.is_none() {
            self.highlighted = source_map.highlight_span(self.span, &self.msg);
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.highlighted.as_ref().unwrap_or(&self.msg).fmt(f)
    }
}

impl core::error::Error for Error {}

#[derive(Debug)]
struct PackageNotFoundError {
    span: Span,
    requested: PackageName,
    known: Vec<PackageName>,
    highlighted: Option<String>,
}

impl PackageNotFoundError {
    pub fn new(span: Span, requested: PackageName, known: Vec<PackageName>) -> Self {
        Self {
            span,
            requested,
            known,
            highlighted: None,
        }
    }

    /// Highlights this error using the given source map, if the span is known.
    fn highlight(&mut self, source_map: &ast::SourceMap) {
        if self.highlighted.is_none() {
            self.highlighted = source_map.highlight_span(self.span, &format!("{self}"));
        }
    }
}

impl fmt::Display for PackageNotFoundError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(highlighted) = &self.highlighted {
            return highlighted.fmt(f);
        }
        if self.known.is_empty() {
            write!(
                f,
                "package '{}' not found. no known packages.",
                self.requested
            )?;
        } else {
            write!(
                f,
                "package '{}' not found. known packages:\n",
                self.requested
            )?;
            for known in self.known.iter() {
                write!(f, "    {known}\n")?;
            }
        }
        Ok(())
    }
}

impl core::error::Error for PackageNotFoundError {}

impl UnresolvedPackageGroup {
    /// Parses the given string as a wit document.
    ///
    /// The `path` argument is used for error reporting. The `contents` provided
    /// are considered to be the contents of `path`. This function does not read
    /// the filesystem.
    #[cfg(feature = "std")]
    pub fn parse(path: impl AsRef<Path>, contents: &str) -> Result<UnresolvedPackageGroup> {
        let path = path
            .as_ref()
            .to_str()
            .ok_or_else(|| anyhow::anyhow!("path is not valid utf-8: {:?}", path.as_ref()))?;
        let mut map = SourceMap::default();
        map.push_str(path, contents);
        map.parse()
            .map_err(|(map, e)| anyhow::anyhow!("{}", e.highlight(&map)))
    }

    /// Parses a WIT package from the directory provided.
    ///
    /// This method will look at all files under the `path` specified. All
    /// `*.wit` files are parsed and assumed to be part of the same package
    /// grouping. This is useful when a WIT package is split across multiple
    /// files.
    #[cfg(feature = "std")]
    pub fn parse_dir(path: impl AsRef<Path>) -> Result<UnresolvedPackageGroup> {
        let path = path.as_ref();
        let mut map = SourceMap::default();
        let cx = || format!("failed to read directory {path:?}");
        for entry in path.read_dir().with_context(&cx)? {
            let entry = entry.with_context(&cx)?;
            let path = entry.path();
            let ty = entry.file_type().with_context(&cx)?;
            if ty.is_dir() {
                continue;
            }
            if ty.is_symlink() {
                if path.is_dir() {
                    continue;
                }
            }
            let filename = match path.file_name().and_then(|s| s.to_str()) {
                Some(name) => name,
                None => continue,
            };
            if !filename.ends_with(".wit") {
                continue;
            }
            map.push_file(&path)?;
        }
        map.parse()
            .map_err(|(map, e)| anyhow::anyhow!("{}", e.highlight(&map)))
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct World {
    /// The WIT identifier name of this world.
    pub name: String,

    /// All imported items into this interface, both worlds and functions.
    pub imports: IndexMap<WorldKey, WorldItem>,

    /// All exported items from this interface, both worlds and functions.
    pub exports: IndexMap<WorldKey, WorldItem>,

    /// The package that owns this world.
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_optional_id"))]
    pub package: Option<PackageId>,

    /// Documentation associated with this world declaration.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Docs::is_empty"))]
    pub docs: Docs,

    /// Stability annotation for this world itself.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Stability::is_unknown")
    )]
    pub stability: Stability,

    /// All the included worlds from this world. Empty if this is fully resolved.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub includes: Vec<WorldInclude>,

    /// Source span for this world.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub span: Span,
}

impl World {
    /// Adjusts all spans in this world by adding the given byte offset.
    pub(crate) fn adjust_spans(&mut self, offset: u32) {
        self.span.adjust(offset);
        for item in self.imports.values_mut().chain(self.exports.values_mut()) {
            item.adjust_spans(offset);
        }
        for include in &mut self.includes {
            include.span.adjust(offset);
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludeName {
    /// The name of the item
    pub name: String,

    /// The name to be replaced with
    pub as_: String,
}

/// An entry in the `includes` list of a world, representing an `include`
/// statement in WIT.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorldInclude {
    /// The stability annotation on this include.
    pub stability: Stability,

    /// The world being included.
    pub id: WorldId,

    /// Names being renamed as part of this include.
    pub names: Vec<IncludeName>,

    /// Source span for this include statement.
    pub span: Span,
}

/// The key to the import/export maps of a world. Either a kebab-name or a
/// unique interface.
#[derive(Debug, Clone, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(into = "String"))]
pub enum WorldKey {
    /// A kebab-name.
    Name(String),
    /// An interface which is assigned no kebab-name.
    Interface(InterfaceId),
}

impl Hash for WorldKey {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        match self {
            WorldKey::Name(s) => {
                0u8.hash(hasher);
                s.as_str().hash(hasher);
            }
            WorldKey::Interface(i) => {
                1u8.hash(hasher);
                i.hash(hasher);
            }
        }
    }
}

impl PartialEq for WorldKey {
    fn eq(&self, other: &WorldKey) -> bool {
        match (self, other) {
            (WorldKey::Name(a), WorldKey::Name(b)) => a.as_str() == b.as_str(),
            (WorldKey::Name(_), _) => false,
            (WorldKey::Interface(a), WorldKey::Interface(b)) => a == b,
            (WorldKey::Interface(_), _) => false,
        }
    }
}

impl From<WorldKey> for String {
    fn from(key: WorldKey) -> String {
        match key {
            WorldKey::Name(name) => name,
            WorldKey::Interface(id) => format!("interface-{}", id.index()),
        }
    }
}

impl WorldKey {
    /// Asserts that this is `WorldKey::Name` and returns the name.
    #[track_caller]
    pub fn unwrap_name(self) -> String {
        match self {
            WorldKey::Name(name) => name,
            WorldKey::Interface(_) => panic!("expected a name, found interface"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum WorldItem {
    /// An interface is being imported or exported from a world, indicating that
    /// it's a namespace of functions.
    Interface {
        #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
        id: InterfaceId,
        #[cfg_attr(
            feature = "serde",
            serde(skip_serializing_if = "Stability::is_unknown")
        )]
        stability: Stability,
        #[cfg_attr(feature = "serde", serde(skip))]
        span: Span,
    },

    /// A function is being directly imported or exported from this world.
    Function(Function),

    /// A type is being exported from this world.
    ///
    /// Note that types are never imported into worlds at this time.
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id_ignore_span"))]
    Type { id: TypeId, span: Span },
}

impl WorldItem {
    pub fn stability<'a>(&'a self, resolve: &'a Resolve) -> &'a Stability {
        match self {
            WorldItem::Interface { stability, .. } => stability,
            WorldItem::Function(f) => &f.stability,
            WorldItem::Type { id, .. } => &resolve.types[*id].stability,
        }
    }

    pub fn span(&self) -> Span {
        match self {
            WorldItem::Interface { span, .. } => *span,
            WorldItem::Function(f) => f.span,
            WorldItem::Type { span, .. } => *span,
        }
    }

    pub(crate) fn adjust_spans(&mut self, offset: u32) {
        match self {
            WorldItem::Function(f) => f.adjust_spans(offset),
            WorldItem::Interface { span, .. } => span.adjust(offset),
            WorldItem::Type { span, .. } => span.adjust(offset),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Interface {
    /// Optionally listed name of this interface.
    ///
    /// This is `None` for inline interfaces in worlds.
    pub name: Option<String>,

    /// Exported types from this interface.
    ///
    /// Export names are listed within the types themselves. Note that the
    /// export name here matches the name listed in the `TypeDef`.
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id_map"))]
    pub types: IndexMap<String, TypeId>,

    /// Exported functions from this interface.
    pub functions: IndexMap<String, Function>,

    /// Documentation associated with this interface.
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Docs::is_empty"))]
    pub docs: Docs,

    /// Stability attribute for this interface.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Stability::is_unknown")
    )]
    pub stability: Stability,

    /// The package that owns this interface.
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_optional_id"))]
    pub package: Option<PackageId>,

    /// Source span for this interface.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub span: Span,

    /// The interface that this one was cloned from, if any.
    ///
    /// Applicable for [`Resolve::generate_nominal_type_ids`].
    #[cfg_attr(
        feature = "serde",
        serde(
            skip_serializing_if = "Option::is_none",
            serialize_with = "serialize_optional_id",
        )
    )]
    pub clone_of: Option<InterfaceId>,
}

impl Interface {
    /// Adjusts all spans in this interface by adding the given byte offset.
    pub(crate) fn adjust_spans(&mut self, offset: u32) {
        self.span.adjust(offset);
        for func in self.functions.values_mut() {
            func.adjust_spans(offset);
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct TypeDef {
    pub name: Option<String>,
    pub kind: TypeDefKind,
    pub owner: TypeOwner,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Docs::is_empty"))]
    pub docs: Docs,
    /// Stability attribute for this type.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Stability::is_unknown")
    )]
    pub stability: Stability,
    /// Source span for this type.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub span: Span,
}

impl TypeDef {
    /// Adjusts all spans in this type definition by adding the given byte offset.
    ///
    /// This is used when merging source maps to update spans to point to the
    /// correct location in the combined source map.
    pub(crate) fn adjust_spans(&mut self, offset: u32) {
        self.span.adjust(offset);
        match &mut self.kind {
            TypeDefKind::Record(r) => {
                for field in &mut r.fields {
                    field.span.adjust(offset);
                }
            }
            TypeDefKind::Variant(v) => {
                for case in &mut v.cases {
                    case.span.adjust(offset);
                }
            }
            TypeDefKind::Enum(e) => {
                for case in &mut e.cases {
                    case.span.adjust(offset);
                }
            }
            TypeDefKind::Flags(f) => {
                for flag in &mut f.flags {
                    flag.span.adjust(offset);
                }
            }
            _ => {}
        }
    }
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum TypeDefKind {
    Record(Record),
    Resource,
    Handle(Handle),
    Flags(Flags),
    Tuple(Tuple),
    Variant(Variant),
    Enum(Enum),
    Option(Type),
    Result(Result_),
    List(Type),
    Map(Type, Type),
    FixedLengthList(Type, u32),
    Future(Option<Type>),
    Stream(Option<Type>),
    Type(Type),

    /// This represents a type of unknown structure imported from a foreign
    /// interface.
    ///
    /// This variant is only used during the creation of `UnresolvedPackage` but
    /// by the time a `Resolve` is created then this will not exist.
    Unknown,
}

impl TypeDefKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            TypeDefKind::Record(_) => "record",
            TypeDefKind::Resource => "resource",
            TypeDefKind::Handle(handle) => match handle {
                Handle::Own(_) => "own",
                Handle::Borrow(_) => "borrow",
            },
            TypeDefKind::Flags(_) => "flags",
            TypeDefKind::Tuple(_) => "tuple",
            TypeDefKind::Variant(_) => "variant",
            TypeDefKind::Enum(_) => "enum",
            TypeDefKind::Option(_) => "option",
            TypeDefKind::Result(_) => "result",
            TypeDefKind::List(_) => "list",
            TypeDefKind::Map(_, _) => "map",
            TypeDefKind::FixedLengthList(..) => "fixed-length list",
            TypeDefKind::Future(_) => "future",
            TypeDefKind::Stream(_) => "stream",
            TypeDefKind::Type(_) => "type",
            TypeDefKind::Unknown => "unknown",
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum TypeOwner {
    /// This type was defined within a `world` block.
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
    World(WorldId),
    /// This type was defined within an `interface` block.
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
    Interface(InterfaceId),
    /// This type wasn't inherently defined anywhere, such as a `list<T>`, which
    /// doesn't need an owner.
    #[cfg_attr(feature = "serde", serde(untagged, serialize_with = "serialize_none"))]
    None,
}

#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum Handle {
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
    Own(TypeId),
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
    Borrow(TypeId),
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
pub enum Type {
    Bool,
    U8,
    U16,
    U32,
    U64,
    S8,
    S16,
    S32,
    S64,
    F32,
    F64,
    Char,
    String,
    ErrorContext,
    Id(TypeId),
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Int {
    U8,
    U16,
    U32,
    U64,
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Record {
    pub fields: Vec<Field>,
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Field {
    pub name: String,
    #[cfg_attr(feature = "serde", serde(rename = "type"))]
    pub ty: Type,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Docs::is_empty"))]
    pub docs: Docs,
    /// Source span for this field.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Flags {
    pub flags: Vec<Flag>,
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Flag {
    pub name: String,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Docs::is_empty"))]
    pub docs: Docs,
    /// Source span for this flag.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq)]
pub enum FlagsRepr {
    U8,
    U16,
    U32(usize),
}

impl Flags {
    pub fn repr(&self) -> FlagsRepr {
        match self.flags.len() {
            0 => FlagsRepr::U32(0),
            n if n <= 8 => FlagsRepr::U8,
            n if n <= 16 => FlagsRepr::U16,
            n => FlagsRepr::U32(sizealign::align_to(n, 32) / 32),
        }
    }
}

impl FlagsRepr {
    pub fn count(&self) -> usize {
        match self {
            FlagsRepr::U8 => 1,
            FlagsRepr::U16 => 1,
            FlagsRepr::U32(n) => *n,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Tuple {
    pub types: Vec<Type>,
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Variant {
    pub cases: Vec<Case>,
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Case {
    pub name: String,
    #[cfg_attr(feature = "serde", serde(rename = "type"))]
    pub ty: Option<Type>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Docs::is_empty"))]
    pub docs: Docs,
    /// Source span for this variant case.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub span: Span,
}

impl Variant {
    pub fn tag(&self) -> Int {
        discriminant_type(self.cases.len())
    }
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Enum {
    pub cases: Vec<EnumCase>,
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct EnumCase {
    pub name: String,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Docs::is_empty"))]
    pub docs: Docs,
    /// Source span for this enum case.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub span: Span,
}

impl Enum {
    pub fn tag(&self) -> Int {
        discriminant_type(self.cases.len())
    }
}

/// This corresponds to the `discriminant_type` function in the Canonical ABI.
fn discriminant_type(num_cases: usize) -> Int {
    match num_cases.checked_sub(1) {
        None => Int::U8,
        Some(n) if n <= u8::max_value() as usize => Int::U8,
        Some(n) if n <= u16::max_value() as usize => Int::U16,
        Some(n) if n <= u32::max_value() as usize => Int::U32,
        _ => panic!("too many cases to fit in a repr"),
    }
}

#[derive(Debug, Clone, PartialEq, Hash, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Result_ {
    pub ok: Option<Type>,
    pub err: Option<Type>,
}

#[derive(Clone, Default, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Docs {
    pub contents: Option<String>,
}

impl Docs {
    pub fn is_empty(&self) -> bool {
        self.contents.is_none()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Param {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "String::is_empty"))]
    pub name: String,
    #[cfg_attr(feature = "serde", serde(rename = "type"))]
    pub ty: Type,
    #[cfg_attr(feature = "serde", serde(skip))]
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Function {
    pub name: String,
    pub kind: FunctionKind,
    pub params: Vec<Param>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub result: Option<Type>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Docs::is_empty"))]
    pub docs: Docs,
    /// Stability attribute for this function.
    #[cfg_attr(
        feature = "serde",
        serde(skip_serializing_if = "Stability::is_unknown")
    )]
    pub stability: Stability,

    /// Source span for this function.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum FunctionKind {
    /// A freestanding function.
    ///
    /// ```wit
    /// interface foo {
    ///     the-func: func();
    /// }
    /// ```
    Freestanding,

    /// An async freestanding function.
    ///
    /// ```wit
    /// interface foo {
    ///     the-func: async func();
    /// }
    /// ```
    AsyncFreestanding,

    /// A resource method where the first parameter is implicitly
    /// `borrow<T>`.
    ///
    /// ```wit
    /// interface foo {
    ///     resource r {
    ///         the-func: func();
    ///     }
    /// }
    /// ```
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
    Method(TypeId),

    /// An async resource method where the first parameter is implicitly
    /// `borrow<T>`.
    ///
    /// ```wit
    /// interface foo {
    ///     resource r {
    ///         the-func: async func();
    ///     }
    /// }
    /// ```
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
    AsyncMethod(TypeId),

    /// A static resource method.
    ///
    /// ```wit
    /// interface foo {
    ///     resource r {
    ///         the-func: static func();
    ///     }
    /// }
    /// ```
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
    Static(TypeId),

    /// An async static resource method.
    ///
    /// ```wit
    /// interface foo {
    ///     resource r {
    ///         the-func: static async func();
    ///     }
    /// }
    /// ```
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
    AsyncStatic(TypeId),

    /// A resource constructor where the return value is implicitly `own<T>`.
    ///
    /// ```wit
    /// interface foo {
    ///     resource r {
    ///         constructor();
    ///     }
    /// }
    /// ```
    #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_id"))]
    Constructor(TypeId),
}

impl FunctionKind {
    /// Returns whether this is an async function or not.
    pub fn is_async(&self) -> bool {
        match self {
            FunctionKind::Freestanding
            | FunctionKind::Method(_)
            | FunctionKind::Static(_)
            | FunctionKind::Constructor(_) => false,
            FunctionKind::AsyncFreestanding
            | FunctionKind::AsyncMethod(_)
            | FunctionKind::AsyncStatic(_) => true,
        }
    }

    /// Returns the resource, if present, that this function kind refers to.
    pub fn resource(&self) -> Option<TypeId> {
        match self {
            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => None,
            FunctionKind::Method(id)
            | FunctionKind::Static(id)
            | FunctionKind::Constructor(id)
            | FunctionKind::AsyncMethod(id)
            | FunctionKind::AsyncStatic(id) => Some(*id),
        }
    }

    /// Returns the resource, if present, that this function kind refers to.
    pub fn resource_mut(&mut self) -> Option<&mut TypeId> {
        match self {
            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => None,
            FunctionKind::Method(id)
            | FunctionKind::Static(id)
            | FunctionKind::Constructor(id)
            | FunctionKind::AsyncMethod(id)
            | FunctionKind::AsyncStatic(id) => Some(id),
        }
    }
}

/// Possible forms of name mangling that are supported by this crate.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Mangling {
    /// The "standard" component model mangling format for 32-bit linear
    /// memories. This is specified in WebAssembly/component-model#378
    Standard32,

    /// The "legacy" name mangling supported in versions 218-and-prior for this
    /// crate. This is the original support for how components were created from
    /// core wasm modules and this does not correspond to any standard. This is
    /// preserved for now while tools transition to the new scheme.
    Legacy,
}

impl core::str::FromStr for Mangling {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Mangling> {
        match s {
            "legacy" => Ok(Mangling::Legacy),
            "standard32" => Ok(Mangling::Standard32),
            _ => {
                bail!(
                    "unknown name mangling `{s}`, \
                     supported values are `legacy` or `standard32`"
                )
            }
        }
    }
}

/// Possible lift/lower ABI choices supported when mangling names.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LiftLowerAbi {
    /// Both imports and exports will use the synchronous ABI.
    Sync,

    /// Both imports and exports will use the async ABI (with a callback for
    /// each export).
    AsyncCallback,

    /// Both imports and exports will use the async ABI (with no callbacks for
    /// exports).
    AsyncStackful,
}

impl LiftLowerAbi {
    fn import_prefix(self) -> &'static str {
        match self {
            Self::Sync => "",
            Self::AsyncCallback | Self::AsyncStackful => "[async-lower]",
        }
    }

    /// Get the import [`AbiVariant`] corresponding to this [`LiftLowerAbi`]
    pub fn import_variant(self) -> AbiVariant {
        match self {
            Self::Sync => AbiVariant::GuestImport,
            Self::AsyncCallback | Self::AsyncStackful => AbiVariant::GuestImportAsync,
        }
    }

    fn export_prefix(self) -> &'static str {
        match self {
            Self::Sync => "",
            Self::AsyncCallback => "[async-lift]",
            Self::AsyncStackful => "[async-lift-stackful]",
        }
    }

    /// Get the export [`AbiVariant`] corresponding to this [`LiftLowerAbi`]
    pub fn export_variant(self) -> AbiVariant {
        match self {
            Self::Sync => AbiVariant::GuestExport,
            Self::AsyncCallback => AbiVariant::GuestExportAsync,
            Self::AsyncStackful => AbiVariant::GuestExportAsyncStackful,
        }
    }
}

/// Combination of [`Mangling`] and [`LiftLowerAbi`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ManglingAndAbi {
    /// See [`Mangling::Standard32`].
    ///
    /// As of this writing, the standard name mangling only supports the
    /// synchronous ABI.
    Standard32,

    /// See [`Mangling::Legacy`] and [`LiftLowerAbi`].
    Legacy(LiftLowerAbi),
}

impl ManglingAndAbi {
    /// Get the import [`AbiVariant`] corresponding to this [`ManglingAndAbi`]
    pub fn import_variant(self) -> AbiVariant {
        match self {
            Self::Standard32 => AbiVariant::GuestImport,
            Self::Legacy(abi) => abi.import_variant(),
        }
    }

    /// Get the export [`AbiVariant`] corresponding to this [`ManglingAndAbi`]
    pub fn export_variant(self) -> AbiVariant {
        match self {
            Self::Standard32 => AbiVariant::GuestExport,
            Self::Legacy(abi) => abi.export_variant(),
        }
    }

    /// Switch the ABI to be sync if it's async.
    pub fn sync(self) -> Self {
        match self {
            Self::Standard32 | Self::Legacy(LiftLowerAbi::Sync) => self,
            Self::Legacy(LiftLowerAbi::AsyncCallback)
            | Self::Legacy(LiftLowerAbi::AsyncStackful) => Self::Legacy(LiftLowerAbi::Sync),
        }
    }

    /// Returns whether this is an async ABI
    pub fn is_async(&self) -> bool {
        match self {
            Self::Standard32 | Self::Legacy(LiftLowerAbi::Sync) => false,
            Self::Legacy(LiftLowerAbi::AsyncCallback)
            | Self::Legacy(LiftLowerAbi::AsyncStackful) => true,
        }
    }

    pub fn mangling(&self) -> Mangling {
        match self {
            Self::Standard32 => Mangling::Standard32,
            Self::Legacy(_) => Mangling::Legacy,
        }
    }
}

impl Function {
    /// Adjusts all spans in this function by adding the given byte offset.
    pub(crate) fn adjust_spans(&mut self, offset: u32) {
        self.span.adjust(offset);
        for param in &mut self.params {
            param.span.adjust(offset);
        }
    }

    pub fn item_name(&self) -> &str {
        match &self.kind {
            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => &self.name,
            FunctionKind::Method(_)
            | FunctionKind::Static(_)
            | FunctionKind::AsyncMethod(_)
            | FunctionKind::AsyncStatic(_) => &self.name[self.name.find('.').unwrap() + 1..],
            FunctionKind::Constructor(_) => "constructor",
        }
    }

    /// Returns an iterator over the types used in parameters and results.
    ///
    /// Note that this iterator is not transitive, it only iterates over the
    /// direct references to types that this function has.
    pub fn parameter_and_result_types(&self) -> impl Iterator<Item = Type> + '_ {
        self.params.iter().map(|p| p.ty).chain(self.result)
    }

    /// Gets the core export name for this function.
    pub fn standard32_core_export_name<'a>(&'a self, interface: Option<&str>) -> Cow<'a, str> {
        self.core_export_name(interface, Mangling::Standard32)
    }

    pub fn legacy_core_export_name<'a>(&'a self, interface: Option<&str>) -> Cow<'a, str> {
        self.core_export_name(interface, Mangling::Legacy)
    }
    /// Gets the core export name for this function.
    pub fn core_export_name<'a>(
        &'a self,
        interface: Option<&str>,
        mangling: Mangling,
    ) -> Cow<'a, str> {
        match interface {
            Some(interface) => match mangling {
                Mangling::Standard32 => Cow::Owned(format!("cm32p2|{interface}|{}", self.name)),
                Mangling::Legacy => Cow::Owned(format!("{interface}#{}", self.name)),
            },
            None => match mangling {
                Mangling::Standard32 => Cow::Owned(format!("cm32p2||{}", self.name)),
                Mangling::Legacy => Cow::Borrowed(&self.name),
            },
        }
    }
    /// Collect any future and stream types appearing in the signature of this
    /// function by doing a depth-first search over the parameter types and then
    /// the result types.
    ///
    /// For example, given the WIT function `foo: func(x: future<future<u32>>,
    /// y: u32) -> stream<u8>`, we would return `[future<u32>,
    /// future<future<u32>>, stream<u8>]`.
    ///
    /// This may be used by binding generators to refer to specific `future` and
    /// `stream` types when importing canonical built-ins such as `stream.new`,
    /// `future.read`, etc.  Using the example above, the import
    /// `[future-new-0]foo` would indicate a call to `future.new` for the type
    /// `future<u32>`.  Likewise, `[future-new-1]foo` would indicate a call to
    /// `future.new` for `future<future<u32>>`, and `[stream-new-2]foo` would
    /// indicate a call to `stream.new` for `stream<u8>`.
    pub fn find_futures_and_streams(&self, resolve: &Resolve) -> Vec<TypeId> {
        let mut results = Vec::new();
        for param in self.params.iter() {
            find_futures_and_streams(resolve, param.ty, &mut results);
        }
        if let Some(ty) = self.result {
            find_futures_and_streams(resolve, ty, &mut results);
        }
        results
    }

    /// Check if this function is a resource constructor in shorthand form.
    /// I.e. without an explicit return type annotation.
    pub fn is_constructor_shorthand(&self, resolve: &Resolve) -> bool {
        let FunctionKind::Constructor(containing_resource_id) = self.kind else {
            return false;
        };

        let Some(Type::Id(id)) = &self.result else {
            return false;
        };

        let TypeDefKind::Handle(Handle::Own(returned_resource_id)) = resolve.types[*id].kind else {
            return false;
        };

        return containing_resource_id == returned_resource_id;
    }

    /// Returns the `module`, `name`, and signature to use when importing this
    /// function's `task.return` intrinsic using the `mangling` specified.
    pub fn task_return_import(
        &self,
        resolve: &Resolve,
        interface: Option<&WorldKey>,
        mangling: Mangling,
    ) -> (String, String, abi::WasmSignature) {
        match mangling {
            Mangling::Standard32 => todo!(),
            Mangling::Legacy => {}
        }
        // For exported async functions, generate a `task.return` intrinsic.
        let module = match interface {
            Some(key) => format!("[export]{}", resolve.name_world_key(key)),
            None => "[export]$root".to_string(),
        };
        let name = format!("[task-return]{}", self.name);

        let mut func_tmp = self.clone();
        func_tmp.params = Vec::new();
        func_tmp.result = None;
        if let Some(ty) = self.result {
            func_tmp.params.push(Param {
                name: "x".to_string(),
                ty,
                span: Default::default(),
            });
        }
        let sig = resolve.wasm_signature(AbiVariant::GuestImport, &func_tmp);
        (module, name, sig)
    }

    // push_imported_future_and_stream_intrinsics(wat, resolve, "[export]", interface, func);
}

fn find_futures_and_streams(resolve: &Resolve, ty: Type, results: &mut Vec<TypeId>) {
    let Type::Id(id) = ty else {
        return;
    };

    match &resolve.types[id].kind {
        TypeDefKind::Resource
        | TypeDefKind::Handle(_)
        | TypeDefKind::Flags(_)
        | TypeDefKind::Enum(_) => {}
        TypeDefKind::Record(r) => {
            for Field { ty, .. } in &r.fields {
                find_futures_and_streams(resolve, *ty, results);
            }
        }
        TypeDefKind::Tuple(t) => {
            for ty in &t.types {
                find_futures_and_streams(resolve, *ty, results);
            }
        }
        TypeDefKind::Variant(v) => {
            for Case { ty, .. } in &v.cases {
                if let Some(ty) = ty {
                    find_futures_and_streams(resolve, *ty, results);
                }
            }
        }
        TypeDefKind::Option(ty)
        | TypeDefKind::List(ty)
        | TypeDefKind::FixedLengthList(ty, ..)
        | TypeDefKind::Type(ty) => {
            find_futures_and_streams(resolve, *ty, results);
        }
        TypeDefKind::Map(k, v) => {
            find_futures_and_streams(resolve, *k, results);
            find_futures_and_streams(resolve, *v, results);
        }
        TypeDefKind::Result(r) => {
            if let Some(ty) = r.ok {
                find_futures_and_streams(resolve, ty, results);
            }
            if let Some(ty) = r.err {
                find_futures_and_streams(resolve, ty, results);
            }
        }
        TypeDefKind::Future(ty) => {
            if let Some(ty) = ty {
                find_futures_and_streams(resolve, *ty, results);
            }
            results.push(id);
        }
        TypeDefKind::Stream(ty) => {
            if let Some(ty) = ty {
                find_futures_and_streams(resolve, *ty, results);
            }
            results.push(id);
        }
        TypeDefKind::Unknown => unreachable!(),
    }
}

/// Representation of the stability attributes associated with a world,
/// interface, function, or type.
///
/// This is added for WebAssembly/component-model#332 where @since and @unstable
/// annotations were added to WIT.
///
/// The order of the of enum values is significant since it is used with Ord and PartialOrd
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde_derive::Deserialize, Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
pub enum Stability {
    /// This item does not have either `@since` or `@unstable`.
    Unknown,

    /// `@unstable(feature = foo)`
    ///
    /// This item is explicitly tagged `@unstable`. A feature name is listed and
    /// this item is excluded by default in `Resolve` unless explicitly enabled.
    Unstable {
        feature: String,
        #[cfg_attr(
            feature = "serde",
            serde(
                skip_serializing_if = "Option::is_none",
                default,
                serialize_with = "serialize_optional_version",
                deserialize_with = "deserialize_optional_version"
            )
        )]
        deprecated: Option<Version>,
    },

    /// `@since(version = 1.2.3)`
    ///
    /// This item is explicitly tagged with `@since` as stable since the
    /// specified version.  This may optionally have a feature listed as well.
    Stable {
        #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_version"))]
        #[cfg_attr(feature = "serde", serde(deserialize_with = "deserialize_version"))]
        since: Version,
        #[cfg_attr(
            feature = "serde",
            serde(
                skip_serializing_if = "Option::is_none",
                default,
                serialize_with = "serialize_optional_version",
                deserialize_with = "deserialize_optional_version"
            )
        )]
        deprecated: Option<Version>,
    },
}

impl Stability {
    /// Returns whether this is `Stability::Unknown`.
    pub fn is_unknown(&self) -> bool {
        matches!(self, Stability::Unknown)
    }

    pub fn is_stable(&self) -> bool {
        matches!(self, Stability::Stable { .. })
    }
}

impl Default for Stability {
    fn default() -> Stability {
        Stability::Unknown
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use alloc::vec;

    #[test]
    fn test_discriminant_type() {
        assert_eq!(discriminant_type(1), Int::U8);
        assert_eq!(discriminant_type(0x100), Int::U8);
        assert_eq!(discriminant_type(0x101), Int::U16);
        assert_eq!(discriminant_type(0x10000), Int::U16);
        assert_eq!(discriminant_type(0x10001), Int::U32);
        if let Ok(num_cases) = usize::try_from(0x100000000_u64) {
            assert_eq!(discriminant_type(num_cases), Int::U32);
        }
    }

    #[test]
    fn test_find_futures_and_streams() {
        let mut resolve = Resolve::default();
        let t0 = resolve.types.alloc(TypeDef {
            name: None,
            kind: TypeDefKind::Future(Some(Type::U32)),
            owner: TypeOwner::None,
            docs: Docs::default(),
            stability: Stability::Unknown,
            span: Default::default(),
        });
        let t1 = resolve.types.alloc(TypeDef {
            name: None,
            kind: TypeDefKind::Future(Some(Type::Id(t0))),
            owner: TypeOwner::None,
            docs: Docs::default(),
            stability: Stability::Unknown,
            span: Default::default(),
        });
        let t2 = resolve.types.alloc(TypeDef {
            name: None,
            kind: TypeDefKind::Stream(Some(Type::U32)),
            owner: TypeOwner::None,
            docs: Docs::default(),
            stability: Stability::Unknown,
            span: Default::default(),
        });
        let found = Function {
            name: "foo".into(),
            kind: FunctionKind::Freestanding,
            params: vec![
                Param {
                    name: "p1".into(),
                    ty: Type::Id(t1),
                    span: Default::default(),
                },
                Param {
                    name: "p2".into(),
                    ty: Type::U32,
                    span: Default::default(),
                },
            ],
            result: Some(Type::Id(t2)),
            docs: Docs::default(),
            stability: Stability::Unknown,
            span: Default::default(),
        }
        .find_futures_and_streams(&resolve);
        assert_eq!(3, found.len());
        assert_eq!(t0, found[0]);
        assert_eq!(t1, found[1]);
        assert_eq!(t2, found[2]);
    }
}