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
use crate::common::*;

#[derive(Debug)]
pub struct CheckNext<M> {
    pattern: M,
}
impl<M> CheckNext<M>
where
    M: MatcherMut,
{
    pub fn new(pattern: M) -> Self {
        Self { pattern }
    }
}
impl<M> Spanned for CheckNext<M>
where
    M: MatcherMut,
{
    fn span(&self) -> SourceSpan {
        self.pattern.span()
    }
}
impl<M> Rule for CheckNext<M>
where
    M: MatcherMut,
{
    fn kind(&self) -> Check {
        Check::Next
    }

    fn apply<'input, 'context, C>(&self, context: &mut C) -> DiagResult<Matches<'input>>
    where
        C: Context<'input, 'context> + ?Sized,
    {
        let cursor = context.cursor();
        let start = cursor.start_of_next_line();
        let block_end = cursor.end();
        let next_eol = cursor.next_newline_from(start).unwrap_or(block_end);
        if start >= block_end {
            // Cannot match, since the search range would
            // overflow the current block.
            return Ok(Matches::from(MatchResult {
                ty: MatchType::Failed(CheckFailedError::MatchNoneButExpected {
                    span: self.pattern.span(),
                    match_file: context.match_file(),
                    note: if cursor.end_of_file() == block_end {
                        None
                    } else {
                        Some(
                            "search was stopped at end of the preceding CHECK-LABEL scope"
                                .to_string(),
                        )
                    },
                }),
                info: None,
            }));
        }
        let input = context.search_range(start..next_eol);
        let result = self.pattern.try_match_mut(input, context)?;
        match &result {
            MatchResult {
                ty,
                info: Some(ref info),
            } if ty.is_ok() => {
                context.cursor_mut().set_start(info.span.end());
            }
            _ => (),
        }
        Ok(result.into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pattern::matcher::*;
    use crate::rules::CheckPlain;

    #[test]
    fn check_next_test() -> DiagResult<()> {
        let mut context = TestContext::new();
        context
            .with_checks(
                "
CHECK: @inc4
CHECK-NEXT: entry:
",
            )
            .with_input(
                "
define void @inc4(i64* %p) {
entry:
        %0 = tail call i64 @llvm.atomic.load.add.i64.p0i64(i64* %p, i64 1)
        ret void
}
",
            );
        let mut mctx = context.match_context();
        let pattern = SubstringMatcher::new(
            Span::new(SourceSpan::from(8..12), Cow::Borrowed("@inc4")),
            &mctx.config,
        )
        .expect("expected pattern to be valid");
        let rule = CheckPlain::new(pattern);
        let matches = rule
            .apply(&mut mctx)
            .expect("expected non-fatal application of rule");
        TestResult::from_matches(matches, &mctx).into_result()?;

        let pattern = SubstringMatcher::new(
            Span::new(SourceSpan::from(22..30), Cow::Borrowed("entry:")),
            &mctx.config,
        )
        .expect("expected pattern to be valid");
        let rule = CheckNext::new(pattern);
        let matches = rule
            .apply(&mut mctx)
            .expect("expected non-fatal application of rule");
        let matched = TestResult::from_matches(matches, &mctx).into_result()?;
        assert_eq!(matched.len(), 1);
        assert_eq!(matched[0].span.offset(), 30);
        assert_eq!(matched[0].span.len(), 6);
        let input = mctx.search();
        assert_eq!(input.as_str(matched[0].matched_range()), "entry:");
        assert_eq!(input.buffer()[mctx.cursor().start()], b'\n');

        Ok(())
    }

    #[test]
    fn check_next_multiple_times_test() -> DiagResult<()> {
        let mut context = TestContext::new();
        context
            .with_checks(
                "
CHECK: @inc4
CHECK-NEXT: entry:
CHECK-NEXT:         %0 = tail call
CHECK-NEXT:         ret void
CHECK-NEXT: }
",
            )
            .with_input(
                "
define void @inc4(i64* %p) {
entry:
        %0 = tail call i64 @llvm.atomic.load.add.i64.p0i64(i64* %p, i64 1)
        ret void
}
",
            );

        context.check()?;

        Ok(())
    }

    #[test]
    fn check_next_real() -> DiagResult<()> {
        let mut context = TestContext::new();
        context
            .with_checks(
                "
;; RUN: midenc compile --stdout --emit=hir $s | filecheck %s
(module
    (func $main (local i32)
        i32.const 1
        local.set 0
        local.get 0
        drop
    )
)

;; CHECK: (module #locals
;; CHECK-NEXT:     ;; Functions
;; CHECK-NEXT:     (func (export #main)
;; CHECK-NEXT:         (block 0
;; CHECK-NEXT:             (let (v0 i32) (const.i32 0))
;; CHECK-NEXT:             (let (v1 i32) (const.i32 1))
;; CHECK-NEXT:             (br (block 1)))
;; CHECK-EMPTY:
;; CHECK-NEXT:         (block 1
;; CHECK-NEXT:             (ret))
;; CHECK-NEXT:     )
;; CHECK-NEXT: )
",
            )
            .with_input(
                "
(module #locals
    ;; Functions
    (func (export #main)
        (block 0
            (let (v0 i32) (const.i32 0))
            (let (v1 i32) (const.i32 1))
            (br (block 1)))

        (block 1
            (ret))
    )
)
",
            );

        context.check()?;

        Ok(())
    }
}