// re2rust $INPUT -o $OUTPUT

use std::fs::File;
use std::io::{Read, Write};

const BUFSIZE: usize = 4096;
const NONE: usize = usize::MAX;

struct State {
    file: File,
    yyinput: [u8; BUFSIZE],
    yylimit: usize,
    yycursor: usize,
    yymarker: usize,
    token: usize,
    // Intermediate tag variables must be part of the lexer state passed to YYFILL.
    // They don't correspond to tags and should be autogenerated by re2c.
    /*!stags:re2c format = "@@: usize,\n"; */
    eof: bool,
}

#[derive(PartialEq)]
enum Fill { Ok, Eof, LongLexeme }

#[derive(Debug, PartialEq)]
struct SemVer(u32, u32, u32); // version: (major, minor, patch)

fn s2n(str: &[u8]) -> u32 { // convert a pre-parsed string to a number
    let mut n = 0;
    for i in str { n = n * 10 + *i as u32 - 48; }
    return n;
}

macro_rules! shift { // ignore overflow, marker and tags may not be set yet
    ($x:expr, $y:expr) => { $x = $x.overflowing_sub($y).0 }
}

fn fill(st: &mut State) -> Fill {
    if st.eof { return Fill::Eof; }

    // Error: lexeme too long. In real life could reallocate a larger buffer.
    if st.token < 1 { return Fill::LongLexeme; }

    // Shift buffer contents (discard everything up to the current token).
    st.yyinput.copy_within(st.token..st.yylimit, 0);
    st.yylimit -= st.token;
    st.yycursor -= st.token;
    shift!(st.yymarker, st.token);
    // Tag variables need to be shifted like other input positions. The check
    // for NONE is only needed if some tags are nested inside of alternative or
    // repetition, so that they can have NONE value.
    /*!stags:re2c format = "if st.@@ != NONE { shift!(st.@@, st.token); }\n"; */
    st.token = 0;

    // Fill free space at the end of buffer with new data from file.
    match st.file.read(&mut st.yyinput[st.yylimit..BUFSIZE - 1]) {
        Ok(n) => {
            st.yylimit += n;
            st.eof = n == 0;
            st.yyinput[st.yylimit] = 0;
        }
        Err(why) => panic!("cannot read from file: {}", why)
    }

    return Fill::Ok;
}

fn parse(st: &mut State) -> Option<Vec::<SemVer>> {
    let mut vers = Vec::new();

    // Final tag variables available in semantic action.
    /*!svars:re2c format = 'let mut @@;\n'; */

    'parse: loop {
        st.token = st.yycursor;
    /*!re2c
        re2c:api = record;
        re2c:eof = 0;
        re2c:tags = 1;
        re2c:yyrecord = st;
        re2c:YYCTYPE = u8;
        re2c:YYFILL = "fill(st) == Fill::Ok";

        num = [0-9]+;

        num @t1 "." @t2 num @t3 ("." @t4 num)? [\n] {
            let major = s2n(&st.yyinput[st.token..t1]);
            let minor = s2n(&st.yyinput[t2..t3]);
            let patch = if t4 != NONE {s2n(&st.yyinput[t4..st.yycursor - 1])} else {0};
            vers.push(SemVer(major, minor, patch));
            continue 'parse;
        }
        $ { return Some(vers); }
        * { return None; }
    */
    }
}

fn main() {
    let fname = "input";
    let verstr = b"1.22.333\n";
    let expect = (0..BUFSIZE).map(|_| SemVer(1, 22, 333)).collect();

    // Prepare input file (make sure it exceeds buffer size).
    match File::create(fname) {
        Err(why) => panic!("cannot open {}: {}", fname, why),
        Ok(mut file) => match file.write_all(&verstr.repeat(BUFSIZE)) {
            Err(why) => panic!("cannot write to {}: {}", fname, why),
            Ok(_) => {}
        }
    };

    // Reopen input file for reading.
    let file = match File::open(fname) {
        Err(why) => panic!("cannot read file {}: {}", fname, why),
        Ok(file) => file,
    };

    // Initialize lexer state.
    let yylimit = BUFSIZE - 1;
    let mut st = State {
        file: file,
        yyinput: [0; BUFSIZE], // sentinel is set to zero, which triggers YYFILL
        yylimit: yylimit,
        yycursor: yylimit,
        yymarker: yylimit,
        token: yylimit,
        /*!stags:re2c format = "@@: NONE,\n"; */
        eof: false,
    };

    // Run the lexer and check results.
    assert_eq!(parse(&mut st), Some(expect));

    // Cleanup: remove input file.
    match std::fs::remove_file(fname) {
        Err(why) => panic!("cannot remove {}: {}", fname, why),
        Ok(_) => {}
    }
}
