Skip to content

Commit

Permalink
Move io to main
Browse files Browse the repository at this point in the history
  • Loading branch information
froth committed Jan 24, 2024
1 parent bb52ac8 commit 0085fb4
Show file tree
Hide file tree
Showing 6 changed files with 380 additions and 375 deletions.
32 changes: 4 additions & 28 deletions src/lox.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use std::{
fs,
io::{self, Write},
};
use std::sync::Arc;

use miette::IntoDiagnostic;
use miette::NamedSource;

use crate::{parser::Parser, scanner::Scanner};

Expand All @@ -14,33 +11,12 @@ impl Lox {
Self {}
}

fn run(&mut self, source: String, filename: String) -> miette::Result<()> {
let mut scanner = Scanner::new(source, filename);
pub fn run(&self, source: String, named_source: Arc<NamedSource>) -> miette::Result<()> {
let mut scanner = Scanner::new(source, named_source);
let tokens = scanner.scan_tokens()?;
// tokens.iter().for_each(|x| println!("{:?}", x));
let mut parser = Parser::new(tokens);
println!("{}", parser.parse());
Ok(())
}
pub fn run_file(&mut self, file: String) -> miette::Result<()> {
let contents = fs::read_to_string(file.clone()).into_diagnostic()?;
self.run(contents, file)?;
Ok(())
}

pub fn run_prompt(&mut self) -> miette::Result<()> {
let std = io::stdin();
loop {
print!("> ");
io::stdout().flush().into_diagnostic()?;
let mut buf = String::new();
match std.read_line(&mut buf).into_diagnostic()? {
0 => return Ok(()),
_ => match self.run(buf.trim_end().to_string(), "stdin".to_string()) {
Ok(_) => (),
Err(err) => println!("{:?}", err),
},
}
}
}
}
43 changes: 40 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
use std::{
fs,
io::{self, Write},
sync::Arc,
};

use clap::Parser;
use lox::Lox;

use args::Args;
use miette::{IntoDiagnostic, NamedSource};

mod args;
mod expr;
Expand All @@ -12,10 +19,9 @@ mod token;

fn main() {
let args = Args::parse();
let mut lox = Lox::new();
let result = match args.file {
Some(file) => lox.run_file(file),
None => lox.run_prompt(),
Some(file) => run_file(file),
None => run_prompt(),
};
match result {
Ok(_) => (),
Expand All @@ -26,6 +32,37 @@ fn main() {
};
}

fn run_file(file: String) -> miette::Result<()> {
let contents = fs::read_to_string(file.clone()).into_diagnostic()?;

let named_source: Arc<NamedSource> = NamedSource::new(file, contents.to_string()).into();
let lox = Lox::new();
lox.run(contents, named_source)?;
Ok(())
}

fn run_prompt() -> miette::Result<()> {
let std = io::stdin();
let lox = Lox::new();
loop {
print!("> ");
io::stdout().flush().into_diagnostic()?;
let mut buf = String::new();
match std.read_line(&mut buf).into_diagnostic()? {
0 => return Ok(()),
_ => {
let source = buf.trim_end().to_string();
let named_source: Arc<NamedSource> =
NamedSource::new("stdin", source.to_string()).into();
match lox.run(source.to_string(), named_source) {
Ok(_) => (),
Err(err) => println!("{:?}", err),
}
}
}
}
}

#[cfg(test)]
#[macro_use]
extern crate assert_matches;
10 changes: 5 additions & 5 deletions src/scanner/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::num::ParseFloatError;
use std::{num::ParseFloatError, rc::Rc, sync::Arc};

use miette::{Diagnostic, NamedSource, SourceSpan};

Expand All @@ -8,7 +8,7 @@ pub enum ScannerError {
UnexpectedCharacter {
char: char,
#[source_code]
src: NamedSource,
src: Arc<NamedSource>,
#[label("here")]
location: SourceSpan,
},
Expand All @@ -17,15 +17,15 @@ pub enum ScannerError {
UnexpectedCharacters {
chars: String,
#[source_code]
src: NamedSource,
src: Arc<NamedSource>,
#[label("here")]
location: SourceSpan,
},

#[error("Non terminated String")]
NonTerminatedString {
#[source_code]
src: NamedSource,
src: Arc<NamedSource>,
#[label("here")]
location: SourceSpan,
},
Expand All @@ -39,4 +39,4 @@ pub enum ScannerError {
pub struct AccumulatedScannerErrors {
#[related]
pub scanner_errors: Vec<ScannerError>,
}
}
24 changes: 10 additions & 14 deletions src/scanner/error_combiner.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
use std::sync::Arc;

use miette::{NamedSource, SourceSpan};

use super::error::ScannerError::{self, UnexpectedCharacter, UnexpectedCharacters};

pub struct ErrorCombiner {
source: String,
filename: String,
named_source: Arc<NamedSource>,
}

impl ErrorCombiner {
pub fn new(source: String, filename: String) -> Self { Self { source, filename } }
pub fn new(named_source: Arc<NamedSource>) -> Self {
Self { named_source }
}

fn handle_accumulated(
&self,
Expand All @@ -21,12 +24,12 @@ impl ErrorCombiner {
[] => (),
[char] => result.push(UnexpectedCharacter {
char: *char,
src: self.named_source(),
src: self.named_source.clone(),
location: *last_offset,
}),
_ => result.push(UnexpectedCharacters {
chars: accumulated.iter().collect(),
src: self.named_source(),
src: self.named_source.clone(),
location: *last_offset,
}),
};
Expand All @@ -35,10 +38,7 @@ impl ErrorCombiner {
*last_offset = None;
}

pub fn combine(
&self,
scanner_errors: Vec<ScannerError>,
) -> Vec<ScannerError> {
pub fn combine(&self, scanner_errors: Vec<ScannerError>) -> Vec<ScannerError> {
let mut result = vec![];
let mut accumulated = vec![];
let mut last_offset: Option<SourceSpan> = None;
Expand Down Expand Up @@ -71,8 +71,4 @@ impl ErrorCombiner {
self.handle_accumulated(&mut accumulated, &mut last_offset, &mut result);
result
}

fn named_source(&self) -> NamedSource {
NamedSource::new(self.filename.clone(), self.source.to_string())
}
}
}
Loading

0 comments on commit 0085fb4

Please sign in to comment.