diff_man/
parser.rs

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
use {
    crate::diff::*,
    std::{path::PathBuf, str::FromStr},
};

pub struct Parser {}
#[derive(Debug)]
enum ParserState {
    Init,
    Command,
    Index,
    OriginPath,
    NewPath,
    Hunk,
    LineChange(Change),
}

#[derive(Debug)]
pub struct ParseError {
    kind: ParseErrorKind,
    reason: String,
    line: String,
}
#[derive(Debug)]
pub enum ParseErrorKind {
    InvalidLineStart,
    ExpectationFailed,
    InvalidLine,
}

impl Parser {
    fn parse_line_kind(state: &ParserState, line: &str) -> Line {
        match state {
            ParserState::Init => {
                if line.starts_with("diff") {
                    Line::Command
                } else {
                    Line::Unknown
                }
            }
            ParserState::Command => {
                if line.starts_with("index") {
                    Line::Index
                } else if line.starts_with(DIFF_SIGN_HEADER_ORIGIN) {
                    Line::OrignPath
                } else {
                    Line::Unknown
                }
            }
            ParserState::Index => {
                if line.starts_with(DIFF_SIGN_HEADER_ORIGIN) {
                    Line::OrignPath
                } else {
                    Line::Unknown
                }
            }
            ParserState::OriginPath => {
                if line.starts_with(DIFF_SIGN_HEADER_NEW) {
                    Line::NewPath
                } else {
                    Line::Unknown
                }
            }
            ParserState::NewPath => {
                if line.starts_with(DIFF_SIGN_HUNK) {
                    Line::Hunk
                } else {
                    Line::Unknown
                }
            }
            ParserState::Hunk => match line.split_at(1) {
                (DIFF_SIGN_LINE_ADDED, _) => Line::LineChange(Change::Added),
                (DIFF_SIGN_LINE_DEFAULT, _) => {
                    Line::LineChange(Change::Default)
                }
                (DIFF_SIGN_LINE_DELETED, _) => {
                    Line::LineChange(Change::Deleted)
                }
                _ => Line::Unknown,
            },
            ParserState::LineChange(_) => {
                if line.starts_with("diff") {
                    Line::Command
                } else if line.starts_with("index") {
                    Line::Index
                } else if line.starts_with(DIFF_SIGN_HEADER_ORIGIN) {
                    Line::OrignPath
                } else if line.starts_with(DIFF_SIGN_HUNK) {
                    Line::Hunk
                } else {
                    match line.split_at(1) {
                        (DIFF_SIGN_LINE_ADDED, _) => {
                            Line::LineChange(Change::Added)
                        }
                        (DIFF_SIGN_LINE_DEFAULT, _) => {
                            Line::LineChange(Change::Default)
                        }
                        (DIFF_SIGN_LINE_DELETED, _) => {
                            Line::LineChange(Change::Deleted)
                        }
                        _ => Line::Unknown,
                    }
                }
            }
        }
    }

    fn parse_line_content<'line>(
        line: &'line str,
        kind: &Line,
    ) -> Result<&'line str, ParseError> {
        let content = match kind {
            Line::Command => line,
            Line::Index => {
                line.strip_prefix("index ").ok_or_else(|| ParseError {
                    kind: ParseErrorKind::ExpectationFailed,
                    reason: "expect line start with `index `".to_string(),
                    line: line.to_string(),
                })?
            }
            Line::OrignPath => {
                line.strip_prefix("--- ").ok_or_else(|| ParseError {
                    kind: ParseErrorKind::ExpectationFailed,
                    reason: "expect line start with `--- `".to_string(),
                    line: line.to_string(),
                })?
            }
            Line::NewPath => {
                line.strip_prefix("+++ ").ok_or_else(|| ParseError {
                    kind: ParseErrorKind::ExpectationFailed,
                    reason: "expect line start with `+++ `".to_string(),
                    line: line.to_string(),
                })?
            }
            Line::Hunk => {
                let end_offset =
                    line.find(" @@").ok_or_else(|| ParseError {
                        kind: ParseErrorKind::ExpectationFailed,
                        reason: "cannot find hunk end with ` @@`".to_string(),
                        line: line.to_string(),
                    })?;
                line.split_at(end_offset).0.strip_prefix("@@ ").ok_or_else(
                    || ParseError {
                        kind: ParseErrorKind::ExpectationFailed,
                        reason: "expect line start with `@@ `".to_string(),
                        line: line.to_string(),
                    },
                )?
            }
            Line::LineChange(_) => line.split_at(1).1,
            // this should be unreachable
            Line::Unknown => panic!("unknown line start"),
        };

        Ok(content)
    }

    pub fn parse_git_udiff(src: &str) -> Result<DiffComposition, ParseError> {
        let mut state = ParserState::Init;
        // State
        //  command     diff --git a/tests/vm.rs b/tests/vm.rs
        //  index       index 90d5af1..30044cb 100644
        //  old_path    --- a/tests/vm.rs
        //  new_path    +++ b/tests/vm.rs
        //  hunk        @@ -16,7 +16,9 @@ scope..
        //      linechange... |+|
        //      linechange... |-|
        //      linechange... | |
        //      *hunk        @@ ...
        let mut diffcom = DiffComposition {
            format: DiffFormat::GitUdiff,
            diff: Vec::new(),
        };

        let mut diff_cur: Option<Diff> = None;
        let mut hunk_cur: Option<DiffHunk> = None;

        for line in src.lines() {
            let tag = Self::parse_line_kind(&state, line);
            state = match &tag {
                Line::Command => ParserState::Command,
                Line::Index => ParserState::Index,
                Line::OrignPath => ParserState::OriginPath,
                Line::NewPath => ParserState::NewPath,
                Line::Hunk => ParserState::Hunk,
                Line::LineChange(change_kind) => {
                    ParserState::LineChange(*change_kind)
                }
                Line::Unknown => Err(ParseError {
                    kind: ParseErrorKind::InvalidLineStart,
                    reason: "line starting with invalid token".to_string(),
                    line: line.to_string(),
                })?,
            };
            let content = Self::parse_line_content(line, &tag)?;
            match state {
                ParserState::Init => unreachable!(),
                ParserState::Command => {
                    if diff_cur.is_some() {
                        let mut diff_before = diff_cur.take().unwrap();

                        if hunk_cur.is_some() {
                            let hunk_before = hunk_cur.take().unwrap();
                            diff_before.hunk.push(hunk_before);
                        }
                        diffcom.diff.push(diff_before);
                    }
                    let (file_path_a, file_path_b) = content
                        .strip_prefix("diff --git ")
                        .and_then(|s|s.split_once(' '))
                        .ok_or_else(||{
                            ParseError{
                                kind:ParseErrorKind::ExpectationFailed,
                                reason:"lines not starting with `diff --git ` or cannot split command's arguments".to_string(
                                ),
                                line:line.to_string(),
                            }
                        })?;
                    let file_path_a = file_path_a
                        .strip_prefix("a/")
                        .ok_or_else(|| ParseError {
                            kind: ParseErrorKind::ExpectationFailed,
                            reason: "expect to path_a start with `a/`"
                                .to_string(),
                            line: line.to_string(),
                        })?;

                    let file_path_b = file_path_b
                        .strip_prefix("b/")
                        .ok_or_else(|| ParseError {
                            kind: ParseErrorKind::ExpectationFailed,
                            reason: "expect to path_a start with `b/`"
                                .to_string(),
                            line: line.to_string(),
                        })?;
                    if file_path_a != file_path_b {
                        Err(ParseError {
                            kind: ParseErrorKind::ExpectationFailed,
                            reason: "file path a and b are different"
                                .to_string(),
                            line: line.to_string(),
                        })?;
                    }
                    let path = PathBuf::from_str(file_path_a).map_err(|e| {
                        ParseError {
                            kind: ParseErrorKind::ExpectationFailed,
                            reason: format!("cannot parse file_path, {:?}", e),
                            line: line.to_string(),
                        }
                    })?;

                    diff_cur = Some(Diff {
                        path,
                        hunk: Vec::new(),
                        command: Some(content.to_string()),
                        index: None,
                    });
                }
                ParserState::Index => match &mut diff_cur {
                    Some(cur) => {
                        if cur.index.is_some() {
                            Err(ParseError {
                                kind: ParseErrorKind::InvalidLine,
                                reason: format!(
                                    "there is index in current diff {:?}",
                                    &diff_cur
                                ),
                                line: line.to_string(),
                            })?;
                        } else {
                            cur.index = Some(content.to_string())
                        }
                    }
                    None => {
                        Err(ParseError {
                            kind: ParseErrorKind::ExpectationFailed,
                            reason: format!(
                                "there is no current diff {:?}",
                                &diff_cur
                            ),
                            line: line.to_string(),
                        })?;
                    }
                },
                ParserState::OriginPath => match &diff_cur {
                    Some(d) => {
                        let diff_path =
                            d.path.to_str().ok_or_else(|| ParseError {
                                kind: ParseErrorKind::ExpectationFailed,
                                reason: "cannot convert diff path to str"
                                    .to_string(),
                                line: line.to_string(),
                            })?;

                        let origin_path = content
                            .strip_prefix("a/")
                            .ok_or_else(|| ParseError {
                                kind: ParseErrorKind::ExpectationFailed,
                                reason: "old file path not start with `a/`"
                                    .to_string(),
                                line: line.to_string(),
                            })?;
                        if diff_path != origin_path {
                            Err(ParseError {
                                kind: ParseErrorKind::ExpectationFailed,
                                reason: format!(
                                    "diff path and origin path is different, [diff: {}] [origin: {}]",
                                    diff_path, origin_path
                                ),
                                line: line.to_string(),
                            })?;
                        }
                    }
                    None => {
                        Err(ParseError {
                            kind: ParseErrorKind::ExpectationFailed,
                            reason: format!(
                                "there is no current diff {:?}",
                                &diff_cur
                            ),
                            line: line.to_string(),
                        })?;
                    }
                },
                ParserState::NewPath => match &diff_cur {
                    Some(d) => {
                        let diff_path =
                            d.path.to_str().ok_or_else(|| ParseError {
                                kind: ParseErrorKind::ExpectationFailed,
                                reason: "cannot convert diff path to str"
                                    .to_string(),
                                line: line.to_string(),
                            })?;

                        let new_path =
                            content.strip_prefix("b/").ok_or_else(|| {
                                ParseError {
                                    kind: ParseErrorKind::ExpectationFailed,
                                    reason: "old file path not start with `b/`"
                                        .to_string(),
                                    line: line.to_string(),
                                }
                            })?;
                        if diff_path != new_path {
                            Err(ParseError {
                                kind: ParseErrorKind::ExpectationFailed,
                                reason: format!(
                                    "diff path and new path is different, [diff: {}] [new: {}]",
                                    diff_path, new_path
                                ),
                                line: line.to_string(),
                            })?;
                        }
                    }
                    None => {
                        Err(ParseError {
                            kind: ParseErrorKind::ExpectationFailed,
                            reason: format!(
                                "there is no current diff {:?}",
                                &diff_cur
                            ),
                            line: line.to_string(),
                        })?;
                    }
                },
                ParserState::Hunk => match &mut diff_cur {
                    Some(dc) => {
                        if let Some(hunk_before) = hunk_cur.take() {
                            dc.hunk.push(hunk_before)
                        }
                        let (old, new) =
                            content.split_once(' ').ok_or_else(|| {
                                ParseError {
                                    kind: ParseErrorKind::ExpectationFailed,
                                    reason: "there is no space in hunk line"
                                        .to_string(),
                                    line: line.to_string(),
                                }
                            })?;
                        let (old_line, old_len) =
                            old.split_once(',').ok_or_else(|| ParseError {
                                kind: ParseErrorKind::ExpectationFailed,
                                reason: "cannot split hunk old range with `,`"
                                    .to_string(),
                                line: line.to_string(),
                            })?;
                        let (new_line, new_len) =
                            new.split_once(',').ok_or_else(|| ParseError {
                                kind: ParseErrorKind::ExpectationFailed,
                                reason: "cannot split hunk new range with `,`"
                                    .to_string(),
                                line: line.to_string(),
                            })?;

                        let old_line = old_line
                            .strip_prefix('-')
                            .ok_or_else(|| ParseError {
                                kind: ParseErrorKind::ExpectationFailed,
                                reason: "cannot strip `-` of old_line"
                                    .to_string(),
                                line: line.to_string(),
                            })?
                            .parse::<usize>()
                            .map_err(|e| ParseError {
                                kind: ParseErrorKind::ExpectationFailed,
                                reason: format!(
                                    "cannot parse old_line to usize, {:?}",
                                    e
                                ),
                                line: line.to_string(),
                            })?;
                        let old_len =
                            old_len.parse::<usize>().map_err(|e| {
                                ParseError {
                                    kind: ParseErrorKind::ExpectationFailed,
                                    reason: format!(
                                        "cannot parse old_len to usize, {:?}",
                                        e
                                    ),
                                    line: line.to_string(),
                                }
                            })?;
                        let new_line = new_line
                            .strip_prefix('+')
                            .ok_or_else(|| ParseError {
                                kind: ParseErrorKind::ExpectationFailed,
                                reason: "cannot strip `+` of new_line"
                                    .to_string(),
                                line: line.to_string(),
                            })?
                            .parse::<usize>()
                            .map_err(|e| ParseError {
                                kind: ParseErrorKind::ExpectationFailed,
                                reason: format!(
                                    "cannot parse new_line to usize, {:?}",
                                    e
                                ),
                                line: line.to_string(),
                            })?;
                        let new_len =
                            new_len.parse::<usize>().map_err(|e| {
                                ParseError {
                                    kind: ParseErrorKind::ExpectationFailed,
                                    reason: format!(
                                        "cannot parse new_len to usize, {:?}",
                                        e
                                    ),
                                    line: line.to_string(),
                                }
                            })?;

                        hunk_cur = Some(DiffHunk {
                            old_line,
                            old_len,
                            new_line,
                            new_len,
                            change: Vec::new(),
                        });
                    }
                    None => {
                        panic!("there is no current diff {:?}", &diff_cur)
                    }
                },
                ParserState::LineChange(kind) => match &mut hunk_cur {
                    Some(h) => {
                        let change = LineChange {
                            kind,
                            content: content.to_string(),
                        };
                        h.change.push(change)
                    }
                    None => {
                        Err(ParseError {
                            kind: ParseErrorKind::ExpectationFailed,
                            reason: format!(
                                "there is no current hunk. current diff {:?}",
                                &diff_cur
                            ),
                            line: line.to_string(),
                        })?;
                    }
                },
            }
        }

        if let Some(hunk) = hunk_cur {
            match &mut diff_cur {
                Some(c) => c.hunk.push(hunk),
                None => {
                    Err(ParseError {
                        kind: ParseErrorKind::ExpectationFailed,
                        reason: "there is no diff_cur to add hunk".to_string(),
                        line: "".to_string(),
                    })?;
                }
            }
        }
        if let Some(diff) = diff_cur {
            diffcom.diff.push(diff);
        } else {
            Err(ParseError {
                kind: ParseErrorKind::ExpectationFailed,
                reason: "there is no diff_cur at end".to_string(),
                line: "".to_string(),
            })?;
        }

        Ok(diffcom)
    }
}

#[cfg(test)]
mod test {
    use core::panic;

    use crate::{
        diff::*,
        parser::{Parser, ParserState},
    };

    const short_test_data: &str = r#"diff --git a/tests/vm.rs b/tests/vm.rs
index 90d5af1..30044cb 100644
--- a/tests/vm.rs
+++ b/tests/vm.rs
@@ -16,7 +16,9 @@ fn run_vm_test(tests: Tests<Option<Object>>) {
         let program = Parser::new(lexer).parse().unwrap();
 
         let mut comp = Compiler::create().unwrap();
-        comp.compile(program);
+        if let Err(e) = comp.compile(program) {
+            panic!("Compile error {:?}", e);
+        }
         let bytecode = comp.bytecode().unwrap();
 
         println!("Bytecode\n{}", bytecode.to_string());
@@ -25,7 +27,7 @@ fn run_vm_test(tests: Tests<Option<Object>>) {
 
         while vm.is_runable() {
             if let Err(err) = vm.run_single() {
-                eprintln!("Error {:?}", err);
+                panic!("VmError {:?}", err)
             }
         }
         println!("VM STACK:\n {}", vm.stack_to_string());
@@ -262,8 +264,7 @@ let no_return = fn() { };no_return() no_return() no_return() no_return()
 
     tests.add((
         "
-let fun = fn() { 10 + 20 };
-fun()
+let fun = fn() { 10 + 20 }; fun()
 ",
         Some(Object::Int(Int { value: 30 })),
     ));
"#;
    #[test]
    fn test_parse_linestart() {
        let mut state = ParserState::Init;
        for line in short_test_data.lines() {
            let tag = Parser::parse_line_kind(&state, line);
            state = match &tag {
                Line::Command => ParserState::Command,
                Line::Index => ParserState::Index,
                Line::OrignPath => ParserState::OriginPath,
                Line::NewPath => ParserState::NewPath,
                Line::Hunk => ParserState::Hunk,
                Line::LineChange(change_kind) => {
                    ParserState::LineChange(*change_kind)
                }
                Line::Unknown => panic!("Unknown line start"),
            };

            println!("[S:{:?}] [T:{:?}] -- L>{}", &state, &tag, &line);
        }
    }

    #[test]
    fn test_parse_udiff() {
        let com = Parser::parse_git_udiff(short_test_data).unwrap();
        println!("{:#?}", com);
    }
}