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
use anyhow::{anyhow, Context, Result};
use id_arena::{Arena, Id};
use indexmap::IndexMap;
use std::borrow::Cow;
use std::fmt;
use std::path::Path;
pub mod abi;
mod ast;
use ast::lex::Span;
pub use ast::SourceMap;
mod sizealign;
pub use sizealign::*;
mod resolve;
pub use resolve::{Package, PackageId, Remap, Resolve};
mod live;
pub use live::LiveTypes;
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>;
pub type DocumentId = Id<Document>;
#[derive(Clone)]
pub struct UnresolvedPackage {
pub name: String,
pub url: Option<String>,
pub worlds: Arena<World>,
pub interfaces: Arena<Interface>,
pub types: Arena<TypeDef>,
pub documents: Arena<Document>,
pub foreign_deps: IndexMap<String, IndexMap<String, DocumentId>>,
unknown_type_spans: Vec<Span>,
world_spans: Vec<(Vec<Span>, Vec<Span>)>,
document_spans: Vec<Span>,
interface_spans: Vec<Span>,
foreign_dep_spans: Vec<Span>,
source_map: SourceMap,
}
#[derive(Debug)]
struct Error {
span: Span,
msg: String,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.msg.fmt(f)
}
}
impl std::error::Error for Error {}
impl UnresolvedPackage {
pub fn parse(path: &Path, contents: &str) -> Result<Self> {
let mut map = SourceMap::default();
let name = path
.file_name()
.and_then(|s| s.to_str())
.ok_or_else(|| anyhow!("path doesn't end in a valid package name {path:?}"))?;
let name = match name.find('.') {
Some(i) => &name[..i],
None => name,
};
map.push(path, name, contents);
map.parse(name, None)
}
pub fn parse_path(path: &Path) -> Result<Self> {
if path.is_dir() {
UnresolvedPackage::parse_dir(path)
} else {
UnresolvedPackage::parse_file(path)
}
}
pub fn parse_file(path: &Path) -> Result<Self> {
let contents = std::fs::read_to_string(path)
.with_context(|| format!("failed to read file {path:?}"))?;
Self::parse(path, &contents)
}
pub fn parse_dir(path: &Path) -> Result<Self> {
let mut map = SourceMap::default();
let name = path
.file_name()
.and_then(|s| s.to_str())
.ok_or_else(|| anyhow!("path doesn't end in a valid package name {path:?}"))?;
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") && !filename.ends_with(".wit.md") {
continue;
}
map.push_file(&path)?;
}
map.parse(name, None)
}
pub fn source_files(&self) -> impl Iterator<Item = &Path> {
self.source_map.source_files()
}
}
#[derive(Debug, Clone)]
pub struct Document {
pub name: String,
pub interfaces: IndexMap<String, InterfaceId>,
pub worlds: IndexMap<String, WorldId>,
pub default_interface: Option<InterfaceId>,
pub default_world: Option<WorldId>,
pub package: Option<PackageId>,
}
#[derive(Debug, Clone)]
pub struct World {
pub name: String,
pub docs: Docs,
pub imports: IndexMap<String, WorldItem>,
pub exports: IndexMap<String, WorldItem>,
pub document: DocumentId,
}
#[derive(Debug, Clone)]
pub enum WorldItem {
Interface(InterfaceId),
Function(Function),
Type(TypeId),
}
#[derive(Debug, Clone)]
pub struct Interface {
pub name: Option<String>,
pub docs: Docs,
pub types: IndexMap<String, TypeId>,
pub functions: IndexMap<String, Function>,
pub document: DocumentId,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TypeDef {
pub docs: Docs,
pub kind: TypeDefKind,
pub name: Option<String>,
pub owner: TypeOwner,
}
#[derive(Debug, Clone, PartialEq)]
pub enum TypeDefKind {
Record(Record),
Flags(Flags),
Tuple(Tuple),
Variant(Variant),
Enum(Enum),
Option(Type),
Result(Result_),
Union(Union),
List(Type),
Future(Option<Type>),
Stream(Stream),
Type(Type),
Unknown,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum TypeOwner {
World(WorldId),
Interface(InterfaceId),
None,
}
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
pub enum Type {
Bool,
U8,
U16,
U32,
U64,
S8,
S16,
S32,
S64,
Float32,
Float64,
Char,
String,
Id(TypeId),
}
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum Int {
U8,
U16,
U32,
U64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Record {
pub fields: Vec<Field>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Field {
pub docs: Docs,
pub name: String,
pub ty: Type,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Flags {
pub flags: Vec<Flag>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Flag {
pub docs: Docs,
pub name: String,
}
#[derive(Debug)]
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)]
pub struct Tuple {
pub types: Vec<Type>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Variant {
pub cases: Vec<Case>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Case {
pub docs: Docs,
pub name: String,
pub ty: Option<Type>,
}
impl Variant {
pub fn tag(&self) -> Int {
match self.cases.len() {
n if n <= u8::max_value() as usize => Int::U8,
n if n <= u16::max_value() as usize => Int::U16,
n if n <= u32::max_value() as usize => Int::U32,
_ => panic!("too many cases to fit in a repr"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Enum {
pub cases: Vec<EnumCase>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EnumCase {
pub docs: Docs,
pub name: String,
}
impl Enum {
pub fn tag(&self) -> Int {
match self.cases.len() {
n if n <= u8::max_value() as usize => Int::U8,
n if n <= u16::max_value() as usize => Int::U16,
n if n <= u32::max_value() as usize => Int::U32,
_ => panic!("too many cases to fit in a repr"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Result_ {
pub ok: Option<Type>,
pub err: Option<Type>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Union {
pub cases: Vec<UnionCase>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct UnionCase {
pub docs: Docs,
pub ty: Type,
}
impl Union {
pub fn tag(&self) -> Int {
match self.cases.len() {
n if n <= u8::max_value() as usize => Int::U8,
n if n <= u16::max_value() as usize => Int::U16,
n if n <= u32::max_value() as usize => Int::U32,
_ => panic!("too many cases to fit in a repr"),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Stream {
pub element: Option<Type>,
pub end: Option<Type>,
}
#[derive(Clone, Default, Debug, PartialEq)]
pub struct Docs {
pub contents: Option<String>,
}
pub type Params = Vec<(String, Type)>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Results {
Named(Params),
Anon(Type),
}
pub enum ResultsTypeIter<'a> {
Named(std::slice::Iter<'a, (String, Type)>),
Anon(std::iter::Once<&'a Type>),
}
impl<'a> Iterator for ResultsTypeIter<'a> {
type Item = &'a Type;
fn next(&mut self) -> Option<&'a Type> {
match self {
ResultsTypeIter::Named(ps) => ps.next().map(|p| &p.1),
ResultsTypeIter::Anon(ty) => ty.next(),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self {
ResultsTypeIter::Named(ps) => ps.size_hint(),
ResultsTypeIter::Anon(ty) => ty.size_hint(),
}
}
}
impl<'a> ExactSizeIterator for ResultsTypeIter<'a> {}
impl Results {
pub fn empty() -> Results {
Results::Named(Vec::new())
}
pub fn len(&self) -> usize {
match self {
Results::Named(params) => params.len(),
Results::Anon(_) => 1,
}
}
pub fn throws<'a>(&self, resolve: &'a Resolve) -> Option<(Option<&'a Type>, Option<&'a Type>)> {
if self.len() != 1 {
return None;
}
match self.iter_types().next().unwrap() {
Type::Id(id) => match &resolve.types[*id].kind {
TypeDefKind::Result(r) => Some((r.ok.as_ref(), r.err.as_ref())),
_ => None,
},
_ => None,
}
}
pub fn iter_types(&self) -> ResultsTypeIter {
match self {
Results::Named(ps) => ResultsTypeIter::Named(ps.iter()),
Results::Anon(ty) => ResultsTypeIter::Anon(std::iter::once(ty)),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Function {
pub docs: Docs,
pub name: String,
pub kind: FunctionKind,
pub params: Params,
pub results: Results,
}
#[derive(Debug, Clone, PartialEq)]
pub enum FunctionKind {
Freestanding,
}
impl Function {
pub fn item_name(&self) -> &str {
match &self.kind {
FunctionKind::Freestanding => &self.name,
}
}
pub fn core_export_name<'a>(&'a self, interface: Option<&str>) -> Cow<'a, str> {
match interface {
Some(interface) => Cow::Owned(format!("{interface}#{}", self.name)),
None => Cow::Borrowed(&self.name),
}
}
}