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
use nom::{
    bytes::complete::take_while1,
    IResult,
    sequence::delimited,
    character::complete::char,
};

pub(crate) mod token;
pub(crate) mod preamble;
pub(crate) mod comment;
pub(crate) mod function;
pub(crate) mod global;
pub(crate) mod ptx_file;
pub(crate) mod body;

#[derive(Debug, PartialEq)]
pub(crate) struct PtxFile<'a> {
    preamble: Preamble<'a>,
    body: Option<&'a str>,
}

#[derive(Debug, PartialEq)]
pub(crate) enum Comment<'a> {
    Line(&'a str),
    Block(&'a str),
}

#[derive(Debug, PartialEq)]
pub(crate) struct Preamble<'a> {
    version: preamble::Version<'a>,
    target: preamble::Target<'a>,
    address_size: preamble::AddressSize<'a>,
}

#[derive(Debug, PartialEq)]
pub(crate) struct Function<'a> {
    signature: function::FunctionSignature<'a>,
    body: Option<body::FunctionBody<'a>>,
}

#[derive(Debug, PartialEq)]
pub(crate) struct Global<'a> {
    raw_string: &'a str,
}

fn is_special(c: char) -> bool {
    ['.', '/', '(', ')', '[', ']', '{', '}', ',', ';', ':', '%']
    .contains(&c)
}

pub(crate) fn parse_name(input: &str) -> IResult<&str, &str> {
    take_while1(|c: char| !c.is_whitespace() && !is_special(c))
    (input)
}

pub(crate) fn parse_parenthesized_naive(input: &str) -> IResult<&str, &str> {
    delimited(
        char('('),
        take_while1(|c: char| c != ')'),
        char(')')
    )(input)
}

pub(crate) fn parse_braced_naive(input: &str) -> IResult<&str, &str> {
    delimited(
        char('{'),
        take_while1(|c: char| c != '}'),
        char('}')
    )(input)
}

pub(crate) fn parse_braced_balanced(input: &str) -> IResult<&str, &str> {
    let mut chars = input.chars().enumerate();
    let (mut depth, mut end) = match chars.next() {
        Some((_, '{')) => (1, None),
        _ => return Err(nom::Err::Error(
            nom::error::Error::new(input, nom::error::ErrorKind::Char)
        )),
    };

    for (i, c) in chars {
        match c {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    end = Some(i);
                    break;
                }
            },
            _ => (),
        }
    }
    if let Some(end) = end {
        Ok((&input[end+1..], &input[1..end]))
    } else {
        Err(nom::Err::Error(
            nom::error::Error::new(input, nom::error::ErrorKind::Eof)
        ))
    }
}

#[cfg(test)]
mod test_parse_parenthesized {
    
    use super::parse_parenthesized_naive;
    
    #[test]
    fn no_newline() {
        let input = "(hello)";
        let expected = Ok(("", "hello"));
        assert_eq!(parse_parenthesized_naive(input), expected)
    }

    #[test]
    fn newline() {
        let input = "(hello\n)";
        let expected = Ok(("", "hello\n"));
        assert_eq!(parse_parenthesized_naive(input), expected)
    }

    #[test]
    fn one_left_parenthesis() {
        let input = "(hello";
        assert!(
            parse_parenthesized_naive(input).is_err()
        )
    }

    #[test]
    fn two_left_one_right() {
        let input = "((hello)";
        assert_eq!(
            parse_parenthesized_naive(input),
            Ok(("", "(hello")),
        )
    }
}

#[cfg(test)]
mod test_parse_braced {
    
    use super::parse_braced_naive;
    
    #[test]
    fn no_newline() {
        let input = "{hello}";
        let expected = Ok(("", "hello"));
        assert_eq!(parse_braced_naive(input), expected)
    }

    #[test]
    fn newline() {
        let input = "{hello\n}";
        let expected = Ok(("", "hello\n"));
        assert_eq!(parse_braced_naive(input), expected)
    }

    #[test]
    fn one_left_brace() {
        let input = "{hello";
        assert!(
            parse_braced_naive(input).is_err()
        )
    }

    #[test]
    fn two_left_one_right() {
        let input = "{{hello}";
        assert_eq!(
            parse_braced_naive(input),
            Ok(("", "{hello")),
        )
    }

    #[test]
    fn mock_function_body() {
        let input = "{.reg .b32 %r<3>}";
        let expected = Ok(("", ".reg .b32 %r<3>"));
        assert_eq!(parse_braced_naive(input), expected)
    }
}

#[cfg(test)]
mod test_parse_braced_balanced {
    
    use super::parse_braced_balanced;
    
    #[test]
    fn one_pair() {
        let input = "{hello}";
        let expected = Ok(("", "hello"));
        assert_eq!(parse_braced_balanced(input), expected)
    }

    #[test]
    fn two_pairs() {
        let input = "{hello}{world}";
        let expected = Ok(("{world}", "hello"));
        assert_eq!(parse_braced_balanced(input), expected)
    }

    #[test]
    fn nested_pair() {
        let input = "{hello{world}}";
        let expected = Ok(("", "hello{world}"));
        assert_eq!(parse_braced_balanced(input), expected)
    }

    #[test]
    fn imbalanced() {
        let input = "{hello{world}";
        assert!(
            parse_braced_balanced(input).is_err()
        )
    }
}