cocoro 0.3.0

A more type-safe take on Rust stackless coroutines
Documentation
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
// A simple calculator example demonstrating lexer/parser composition with weave()
//
// This example shows how to compose coroutines using weave() for a complete
// parsing pipeline that handles tokenization and AST construction separately,
// with full error handling and information preservation.

use std::fmt;

use cocoro::Coro;
use cocoro::Return;
use cocoro::Suspend;
use cocoro::Yield;
use cocoro::weave;
use either::Either;

#[derive(Debug, Clone, PartialEq)]
enum Token {
    Number(i64),
    Plus,
    Minus,
    Star,
    Slash,
    LeftParen,
    RightParen,
    End,
}

#[derive(Debug, Clone, PartialEq)]
enum Expr {
    Number(i64),
    Binary {
        op: BinOp,
        left: Box<Expr>,
        right: Box<Expr>,
    },
}

#[derive(Debug, Clone, PartialEq)]
enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
}

#[derive(Debug, Clone, PartialEq)]
enum ParseError {
    UnexpectedToken(Token),
    UnexpectedEof,
    TrailingInput(Token),
    UnknownChar(char),
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::UnexpectedToken(token) => {
                write!(f, "Unexpected token: {token:?}")
            }
            ParseError::UnexpectedEof => write!(f, "Unexpected end of input"),
            ParseError::TrailingInput(token) => {
                write!(f, "Trailing input: {token:?}")
            }
            ParseError::UnknownChar(ch) => {
                write!(f, "Unknown character: '{ch}'")
            }
        }
    }
}

// Simple lexer that tokenizes character by character
struct Lexer<'a> {
    input: std::str::Chars<'a>,
    current: Option<char>,
}

impl<'a> Lexer<'a> {
    fn new(input: &'a str) -> Self {
        let mut chars = input.chars();
        let current = chars.next();
        Lexer {
            input: chars,
            current,
        }
    }

    fn advance(&mut self) {
        self.current = self.input.next();
    }

    fn skip_whitespace(&mut self) {
        while let Some(ch) = self.current {
            if ch.is_whitespace() {
                self.advance();
            } else {
                break;
            }
        }
    }

    fn read_number(&mut self) -> i64 {
        let mut num = 0;
        while let Some(ch) = self.current {
            if ch.is_ascii_digit() {
                num = num * 10 + (ch as i64 - '0' as i64);
                self.advance();
            } else {
                break;
            }
        }
        num
    }

    fn next_token(&mut self) -> Result<Token, ParseError> {
        self.skip_whitespace();

        match self.current {
            None => Ok(Token::End),
            Some('0'..='9') => Ok(Token::Number(self.read_number())),
            Some('+') => {
                self.advance();
                Ok(Token::Plus)
            }
            Some('-') => {
                self.advance();
                Ok(Token::Minus)
            }
            Some('*') => {
                self.advance();
                Ok(Token::Star)
            }
            Some('/') => {
                self.advance();
                Ok(Token::Slash)
            }
            Some('(') => {
                self.advance();
                Ok(Token::LeftParen)
            }
            Some(')') => {
                self.advance();
                Ok(Token::RightParen)
            }
            Some(ch) => Err(ParseError::UnknownChar(ch)),
        }
    }
}

impl Coro<(), Token, Result<(), ParseError>> for Lexer<'_> {
    type Next = Self;
    type Suspend = Suspend<Token, Result<(), ParseError>, Self>;

    fn resume(mut self, _: ()) -> Self::Suspend {
        match self.next_token() {
            Ok(Token::End) => Return(Ok(())),
            Ok(token) => Yield(token, self),
            Err(err) => Return(Err(err)),
        }
    }
}

enum Parser {
    WaitingForToken,
    Parsing(Vec<Token>), // Accumulate tokens until we can parse
}

impl Parser {
    fn new() -> Self {
        Self::WaitingForToken
    }

    fn try_parse(tokens: &[Token]) -> Result<Expr, ParseError> {
        if tokens.is_empty() {
            return Err(ParseError::UnexpectedEof);
        }

        let mut parser = ExprParser::new(tokens);
        parser.parse_expression()
    }
}

// Simple recursive descent parser with operator precedence
struct ExprParser<'a> {
    tokens: &'a [Token],
    pos: usize,
}

impl<'a> ExprParser<'a> {
    fn new(tokens: &'a [Token]) -> Self {
        Self { tokens, pos: 0 }
    }

    fn current(&self) -> Option<&Token> {
        self.tokens.get(self.pos)
    }

    fn advance(&mut self) -> Option<&Token> {
        if self.pos < self.tokens.len() {
            let token = &self.tokens[self.pos];
            self.pos += 1;
            Some(token)
        } else {
            None
        }
    }

    fn parse_expression(&mut self) -> Result<Expr, ParseError> {
        let expr = self.parse_addition()?;
        // Successfully parsed - return the expression
        Ok(expr)
    }

    // Addition and subtraction (lowest precedence)
    fn parse_addition(&mut self) -> Result<Expr, ParseError> {
        let mut left = self.parse_multiplication()?;

        while let Some(op) = self.current() {
            match op {
                Token::Plus | Token::Minus => {
                    let bin_op = match op {
                        Token::Plus => BinOp::Add,
                        Token::Minus => BinOp::Sub,
                        _ => unreachable!(),
                    };
                    self.advance();
                    let right = self.parse_multiplication()?;
                    left = Expr::Binary {
                        op: bin_op,
                        left: Box::new(left),
                        right: Box::new(right),
                    };
                }
                _ => break,
            }
        }

        Ok(left)
    }

    // Multiplication and division (higher precedence)
    fn parse_multiplication(&mut self) -> Result<Expr, ParseError> {
        let mut left = self.parse_primary()?;

        while let Some(op) = self.current() {
            match op {
                Token::Star | Token::Slash => {
                    let bin_op = match op {
                        Token::Star => BinOp::Mul,
                        Token::Slash => BinOp::Div,
                        _ => unreachable!(),
                    };
                    self.advance();
                    let right = self.parse_primary()?;
                    left = Expr::Binary {
                        op: bin_op,
                        left: Box::new(left),
                        right: Box::new(right),
                    };
                }
                _ => break,
            }
        }

        Ok(left)
    }

    // Primary expressions (numbers and parentheses)
    fn parse_primary(&mut self) -> Result<Expr, ParseError> {
        match self.advance() {
            Some(Token::Number(n)) => Ok(Expr::Number(*n)),
            Some(Token::LeftParen) => {
                let expr = self.parse_expression()?;
                match self.advance() {
                    Some(Token::RightParen) => Ok(expr),
                    Some(token) => {
                        Err(ParseError::UnexpectedToken(token.clone()))
                    }
                    None => Err(ParseError::UnexpectedEof),
                }
            }
            Some(token) => Err(ParseError::UnexpectedToken(token.clone())),
            None => Err(ParseError::UnexpectedEof),
        }
    }
}

impl Coro<Token, (), Result<Expr, ParseError>> for Parser {
    type Next = Self;
    type Suspend = Suspend<(), Result<Expr, ParseError>, Self>;

    fn resume(mut self, token: Token) -> Self::Suspend {
        match self {
            Parser::WaitingForToken => {
                // Start accumulating tokens
                self = Parser::Parsing(vec![token]);
                Suspend::Yield((), self)
            }
            Parser::Parsing(mut tokens) => {
                tokens.push(token);

                // Check if we can parse a complete expression
                let mut parser = ExprParser::new(&tokens);
                match parser.parse_expression() {
                    Ok(expr) => {
                        // Debug: print parsing info
                        if tokens.len() > 3 {
                            eprintln!(
                                "Parsed {:?} from tokens {:?}, consumed {}/{}",
                                expr,
                                tokens,
                                parser.pos,
                                tokens.len()
                            );
                        }

                        // Check if we consumed all tokens
                        if parser.pos == tokens.len() {
                            Suspend::Return(Ok(expr))
                        } else {
                            // Continue accumulating - we might have more to parse
                            self = Parser::Parsing(tokens);
                            Suspend::Yield((), self)
                        }
                    }
                    Err(_) => {
                        // Can't parse yet, continue accumulating
                        self = Parser::Parsing(tokens);
                        Suspend::Yield((), self)
                    }
                }
            }
        }
    }
}

impl Parser {
    // Handle end of input by trying to parse what we have
    fn try_complete(&self) -> Result<Expr, ParseError> {
        match &self {
            Parser::WaitingForToken => Err(ParseError::UnexpectedEof),
            Parser::Parsing(tokens) => Self::try_parse(tokens),
        }
    }
}

// Coroutine that expects no more input
struct ExpectEnd;

impl Coro<Token, (), ParseError> for ExpectEnd {
    type Next = Self;
    type Suspend = Suspend<(), ParseError, Self>;

    fn resume(self, token: Token) -> Self::Suspend {
        Return(ParseError::TrailingInput(token))
    }
}

fn parse_expression(input: &str) -> Result<Expr, ParseError> {
    use Either::Left;
    use Either::Right;
    let lexer = Lexer::new(input);
    let parser = Parser::new();

    match weave(lexer, parser, ()) {
        // Lexer finished, try to complete parsing with what we have
        Left((lexer_result, remaining_parser)) => match lexer_result {
            Ok(()) => remaining_parser.try_complete(),
            Err(lex_error) => Err(lex_error),
        },
        Right((result, remaining_lexer)) => match result {
            // Successful parse, check for trailing input
            Ok(expr) => match weave(remaining_lexer, ExpectEnd, ()) {
                Left((lexer_result, _)) => match lexer_result {
                    Ok(()) => Ok(expr), // No trailing input
                    Err(lex_error) => Err(lex_error),
                },
                Right((trailing_error, _)) => Err(trailing_error),
            },
            Err(parse_error) => Err(parse_error),
        },
    }
}

fn main() {
    let test_cases = [
        "42",
        "1 + 2",
        "3 * 4 + 5",
        "1 + 2 * 3",
        "(1 + 2) * 3",
        "1 + ",    // Error: incomplete
        "1 + 2 3", // Error: trailing input
        "",        // Error: empty
        "1 + @",   // Error: unknown character
    ];

    for input in &test_cases {
        print!("Input: {:10} -> ", format!("\"{}\"", input));
        match parse_expression(input) {
            Ok(expr) => println!("Success: {expr:?}"),
            Err(err) => println!("Error: {err}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_number() {
        assert_eq!(parse_expression("42"), Ok(Expr::Number(42)));
    }

    #[test]
    fn test_addition() {
        assert_eq!(
            parse_expression("1 + 2"),
            Ok(Expr::Binary {
                op: BinOp::Add,
                left: Box::new(Expr::Number(1)),
                right: Box::new(Expr::Number(2)),
            })
        );
    }

    #[test]
    fn test_trailing_input() {
        assert!(matches!(
            parse_expression("1 + 2 3"),
            Err(ParseError::TrailingInput(Token::Number(3)))
        ));
    }

    #[test]
    fn test_incomplete_expression() {
        assert!(matches!(
            parse_expression("1 +"),
            Err(ParseError::UnexpectedEof)
        ));
    }
}