file/
main.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
//! This example shows how to use a file as input to a tokenizer, rather than a hardcoded string.
//!
//! This tokenizer simply captures as many standard identifiers as it can, and ignores everything else.

#![allow(dead_code)]

use std::{
    fs::File,
    io::{stdin, stdout, BufRead, BufReader, Write},
    path::Path,
};

use alkale::{token::Token, TokenizerContext};

struct Word(String);

pub fn main() {
    // Buffer for the input path
    let mut str_path = String::new();

    println!(
        "Current path: {:?}",
        std::env::current_dir().expect("No current dir exists.")
    );
    println!("Leave input blank to use default path.");
    print!("Input path to file: ");

    stdout().lock().flush().expect("Could not flush stdout.");

    // Read path input
    stdin()
        .lock()
        .read_line(&mut str_path)
        .expect("Could not read stdin.");

    let trimmed = str_path.trim();

    // Get path from string.
    let path = if trimmed.is_empty() {
        Path::new("./examples/file/file.txt")
    } else {
        Path::new(trimmed)
    };

    println!();
    println!("Path: {:?}", path);

    // Load file from path
    let file = File::open(path).expect("Could not open file.");

    // Get a buffered reader of the file.
    let mut reader = BufReader::new(file);

    // Create a context from the BufReader. The closure dictates
    // how we want to handle any read failures— in this case just panic.
    let mut context = TokenizerContext::new_file(&mut reader, |x| match x {
        Ok(char) => char,
        Err(_) => panic!("Unable to read file."),
    });

    // Tokenizer logic
    while context.has_next() {
        if let Some((ident, span)) = context.try_parse_standard_identifier() {
            context.push_token(Token::new(ident, span));
        } else {
            context.skip();
        }
    }

    // Print result
    println!();
    println!("{:#?}", context.result());
}