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
#[derive(Debug)]
pub enum Error {
UnexpectedToken {
expected: String,
actual: String,
start: usize,
end: usize,
},
UnexpectedEof {
expected: String,
start: usize,
},
Invalid {
message: String,
start: usize,
end: usize,
},
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::UnexpectedToken {
actual, expected, ..
} => writeln!(f, "Expected {}, found {}", expected, actual),
Error::UnexpectedEof { expected, .. } => {
writeln!(f, "Expected {}, found Eof", expected)
}
Error::Invalid { message, .. } => writeln!(f, "{}", message),
}
}
}
pub struct Parser<'a> {
source: &'a str,
boundary_length: usize,
pos: usize,
}
impl<'a> Parser<'a> {
pub fn new(source: &'a str) -> Self {
Self {
source,
boundary_length: 0,
pos: 0,
}
}
pub fn cur_byte(&self) -> Option<u8> {
self.source.as_bytes().get(self.pos).map(|item| *item)
}
pub fn eof(&self) -> bool {
self.pos == self.source.len()
}
pub fn is_line_feed(&self) -> bool {
self.cur_byte() == Some(b'\n')
}
pub fn pos(&self) -> usize {
self.pos
}
pub fn scan_boundary(&mut self) -> Result<(usize, usize), Error> {
let start = self.pos;
let mut eq_len = 1;
self.expect_byte(b'<')?;
self.expect_byte(b'=')?;
while self.cur_byte() == Some(b'=') {
eq_len += 1;
self.pos += 1;
}
self.expect_byte(b'>')?;
let end = self.pos;
if self.boundary_length == 0 {
self.boundary_length = eq_len;
} else if self.boundary_length != eq_len {
return Err(Error::Invalid {
message: "Un matched boundary length".to_string(),
start,
end,
});
}
Ok((start, end))
}
pub fn scan_contents(&mut self) -> Result<(usize, usize), Error> {
let start = self.pos;
if self.cur_byte() == Some(b'<') {
match self.scan_boundary() {
Ok(_) => {
self.pos = start;
return Ok((start, start));
}
Err(_) => {}
}
}
loop {
if self.eof() {
break;
}
if self.cur_byte() == Some(b'\n') {
self.pos += 1;
if self.cur_byte() == Some(b'<') {
let checkpoint = self.pos;
match self.scan_boundary() {
Ok(_) => {
self.pos = checkpoint;
break;
}
Err(_) => {}
}
}
} else {
self.pos += 1;
}
}
let end = self.pos;
Ok((start, end))
}
pub fn expect_byte(&mut self, byte: u8) -> Result<(), Error> {
if self.cur_byte() != Some(byte) {
if self.eof() {
return Err(Error::UnexpectedEof {
expected: (byte as char).to_string(),
start: self.pos,
});
}
return Err(Error::UnexpectedToken {
expected: (byte as char).to_string(),
actual: (self.cur_byte().unwrap() as char).to_string(),
start: self.pos,
end: self.pos + 1,
});
}
self.pos += 1;
Ok(())
}
pub fn scan_path_component(&mut self) -> Result<(usize, usize, &'a str), Error> {
let start = self.pos;
while !self.eof() && self.is_path_component(self.cur_byte().unwrap()) {
self.pos += 1;
}
let end = self.pos;
let source = &self.source[start..end];
if source.len() == 0 || source == "." || source == ".." {
if self.eof() {
return Err(Error::UnexpectedEof {
expected: "path".to_string(),
start: self.pos,
});
} else {
return Err(Error::UnexpectedToken {
expected: "path".to_string(),
actual: source.to_string(),
start,
end,
});
}
}
Ok((start, end, source))
}
#[inline]
fn is_path_component(&self, byte: u8) -> bool {
!matches!(byte, 0..=0x1f | 0x7f | 0x2f | 0x3a | 0x5c)
}
}
#[derive(Debug)]
pub enum FileOrDirectory<'a> {
File(File<'a>),
Directory(Directory<'a>),
}
#[derive(Debug)]
pub struct File<'a> {
pub start: usize,
pub end: usize,
pub body: Option<Body<'a>>,
pub path: Path<'a>,
}
#[derive(Debug)]
pub struct Path<'a> {
pub start: usize,
pub end: usize,
pub source: &'a str,
}
#[derive(Debug)]
pub struct Directory<'a> {
pub start: usize,
pub end: usize,
pub path: Path<'a>,
}
#[derive(Debug)]
pub struct Archive<'a> {
pub start: usize,
pub end: usize,
pub entries: Vec<Entry<'a>>,
pub comment: Option<Comment<'a>>,
}
#[derive(Debug)]
pub struct Entry<'a> {
pub start: usize,
pub end: usize,
pub comment: Option<Comment<'a>>,
pub body: FileOrDirectory<'a>,
}
#[derive(Debug)]
pub struct Comment<'a> {
pub start: usize,
pub end: usize,
pub source: &'a str,
pub boundary: Boundary,
pub body: Body<'a>,
}
#[derive(Debug)]
pub struct Body<'a> {
pub start: usize,
pub end: usize,
pub source: &'a str,
}
#[derive(Debug)]
pub struct Boundary {
pub start: usize,
pub end: usize,
}
pub fn parse_archive<'a>(p: &mut Parser<'a>) -> Result<Archive<'a>, Error> {
let start = p.pos;
let mut entries = vec![];
loop {
let checkpoint = p.pos;
match parse_entry(p) {
Ok(entry) => {
entries.push(entry);
}
Err(err) => {
p.pos = checkpoint;
match err {
Error::UnexpectedToken { .. } => {}
Error::UnexpectedEof { .. } => {},
Error::Invalid { .. } => {
return Err(err);
}
}
break;
}
}
}
dbg!(&p.source[p.pos..]);
let comment = parse_comment(p).ok();
dbg!(&comment);
if !p.eof() {
return Err(Error::UnexpectedToken {
expected: "Eof eof".to_string(),
actual: p.cur_byte().unwrap().to_string(),
start: p.pos,
end: p.pos + 1,
});
}
Ok(Archive {
start,
end: p.pos,
entries,
comment,
})
}
pub fn parse_entry<'a>(p: &mut Parser<'a>) -> Result<Entry<'a>, Error> {
let start = p.pos;
let comment = parse_comment(p).ok();
if comment.is_none() {
p.pos = start;
}
parse_boundary(p)?;
p.expect_byte(b' ')?;
let path = parse_path(p)?;
match p.cur_byte() {
Some(b'/') => {
p.expect_byte(b'/')?;
while !p.eof() && p.is_line_feed() {
p.pos += 1;
}
let end = p.pos;
if !p.eof() && p.cur_byte() != Some(b'<') {
return Err(Error::Invalid {
message: "A directory can't have text contents.".to_string(),
start: p.pos,
end: p.pos + 1,
});
}
return Ok(Entry {
start,
end,
comment,
body: FileOrDirectory::Directory(Directory { start, end, path }),
});
}
Some(b'\n') => {
p.expect_byte(b'\n')?;
let checkpoint = p.pos;
let body = parse_body(p).ok();
if body.is_none() {
p.pos = checkpoint;
}
let end = p.pos;
return Ok(Entry {
start,
end,
comment,
body: FileOrDirectory::File(File {
start,
end,
body,
path,
}),
});
}
_ if p.eof() => {
return Err(Error::UnexpectedEof {
expected: "`/` or `\n`".to_string(),
start: p.pos,
})
}
_ => {
return Err(Error::UnexpectedToken {
expected: "`/` or `\n`".to_string(),
actual: p.cur_byte().unwrap().to_string(),
start,
end: p.pos,
});
}
}
}
pub fn parse_comment<'a>(p: &mut Parser<'a>) -> Result<Comment<'a>, Error> {
let start = p.pos();
let boundary = parse_boundary(p)?;
p.expect_byte(b'\n')?;
let body = parse_body(p)?;
let end = p.pos;
Ok(Comment {
start,
end,
source: &p.source[start..end],
boundary,
body,
})
}
fn parse_path<'a>(p: &mut Parser<'a>) -> Result<Path<'a>, Error> {
let (start, mut end, _) = p.scan_path_component()?;
while !p.eof() && p.cur_byte() == Some(b'/') {
let checkpoint = p.pos;
p.expect_byte(b'/')?;
match p.scan_path_component() {
Ok((_, e, ..)) => {
end = e;
}
Err(_) => {
p.pos = checkpoint;
break;
}
}
}
Ok(Path {
start,
end,
source: &p.source[start..end],
})
}
fn parse_body<'a>(p: &mut Parser<'a>) -> Result<Body<'a>, Error> {
let (start, end) = p.scan_contents()?;
Ok(Body {
start,
end,
source: &p.source[start..end],
})
}
pub fn parse_boundary<'a>(p: &mut Parser<'a>) -> Result<Boundary, Error> {
let (start, end) = p.scan_boundary()?;
Ok(Boundary { start, end })
}
pub fn parse(source: &str) -> Result<Archive, Error> {
let mut parser = Parser::new(source);
parse_archive(&mut parser)
}