Compare commits

..
5 Commits
Author SHA1 Message Date
Lewis Dale 5e500e9ec3 Start working on expressions 2023-01-27 13:51:41 +00:00
Lewis Dale 627baa8449 Move Node into module 2023-01-27 08:29:52 +00:00
Lewis Dale 756d572d21 Move commands into separate module 2023-01-27 08:27:44 +00:00
Lewis Dale c7c7704b5d Proper printing 2023-01-27 08:25:01 +00:00
Lewis Dale ed885b0f81 Move command parsers into parsers module 2023-01-21 08:40:11 +00:00
8 changed files with 271 additions and 124 deletions

No files matched your search

+26 -123
View File
@@ -1,72 +1,13 @@
use std::collections::HashMap; use std::collections::HashMap;
use nom::{ use nom::{bytes::complete::tag, multi::separated_list0, IResult};
branch::alt, bytes::complete::tag, character::complete::u64 as ccu64, combinator::map,
multi::separated_list0, sequence::terminated, IResult, use crate::{
commands::{Command, Primitive, PrintOutput},
node::Node,
parsers,
}; };
use crate::parsers::{generic, variables};
pub type Line = (usize, Command);
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Command {
Print(PrintOutput),
GoTo(usize),
Var((String, Primitive)),
Comment,
None,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Primitive {
Int(i64),
String(String),
Assignment(String),
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum PrintOutput {
Value(String),
Variable(String),
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Node {
None,
Link { item: Line, next: Box<Node> },
}
impl Node {
fn push(&mut self, val: Line) {
*self = match self {
Self::Link { item, next } => {
next.push(val);
Self::Link {
item: item.clone(),
next: next.clone(),
}
}
Self::None => Self::Link {
item: val,
next: Box::new(Self::None),
},
}
}
pub fn find_line(&self, line: usize) -> Option<Node> {
if let Self::Link { item, next } = self {
if item.0 == line {
Some(self.clone())
} else {
next.find_line(line)
}
} else {
None
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
pub struct Program { pub struct Program {
nodes: Node, nodes: Node,
@@ -99,7 +40,7 @@ impl Program {
match item.1 { match item.1 {
Command::Print(PrintOutput::Value(line)) => println!("{}", line), Command::Print(PrintOutput::Value(line)) => println!("{}", line),
Command::Print(PrintOutput::Variable(variable)) => { Command::Print(PrintOutput::Variable(variable)) => {
println!("{:?}", self.vars.get(&variable).unwrap()) println!("{}", self.vars.get(&variable).unwrap())
} }
Command::GoTo(line) => iter.jump_to_line(line), Command::GoTo(line) => iter.jump_to_line(line),
Command::Var((id, Primitive::Assignment(variable))) => { Command::Var((id, Primitive::Assignment(variable))) => {
@@ -115,11 +56,22 @@ impl Program {
}; };
} }
} }
fn read(i: &str) -> IResult<&str, Self> {
let (i, lines) = separated_list0(tag("\n"), parsers::commands::parse_line)(i)?;
let mut node = Node::None;
for line in lines.iter() {
node.push(line.clone());
}
Ok((i, Program::new(node)))
}
} }
impl From<&str> for Program { impl From<&str> for Program {
fn from(value: &str) -> Self { fn from(value: &str) -> Self {
let (_, program) = read_program(value).unwrap(); let (_, program) = Self::read(value).unwrap();
program program
} }
} }
@@ -139,65 +91,16 @@ impl Iterator for Program {
} }
} }
fn match_command(i: &str) -> IResult<&str, &str> {
alt((tag("PRINT"), tag("GO TO"), tag("LET"), tag("REM")))(i)
}
fn parse_print_command(i: &str) -> IResult<&str, PrintOutput> {
alt((
map(
alt((
variables::parse_str_variable_name,
variables::parse_int_variable_name,
)),
PrintOutput::Variable,
),
map(generic::read_string, PrintOutput::Value),
))(i)
}
fn parse_command(i: &str) -> IResult<&str, Command> {
let (i, command): (&str, &str) = match_command(i).unwrap_or((i, ""));
let (i, _) = tag(" ")(i)?;
let (i, cmd) = match command {
"PRINT" => map(parse_print_command, Command::Print)(i)?,
"GO TO" => map(ccu64, |line| Command::GoTo(line as usize))(i)?,
"LET" => map(variables::parse_var, Command::Var)(i)?,
"REM" => {
let (i, _) = generic::consume_line(i)?;
(i, Command::Comment)
}
_ => (i, Command::None),
};
Ok((i, cmd))
}
pub fn parse_line(line: &str) -> IResult<&str, Line> {
let (i, line_number) = map(terminated(ccu64, tag(" ")), |l| l as usize)(line)?;
let (i, command) = parse_command(i)?;
Ok((i, (line_number, command)))
}
pub fn read_program(i: &str) -> IResult<&str, Program> {
let (i, lines) = separated_list0(tag("\n"), parse_line)(i)?;
let mut node = Node::None;
for line in lines.iter() {
node.push(line.clone());
}
Ok((i, Program::new(node)))
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::basic::PrintOutput; use crate::basic::PrintOutput;
use super::{parse_line, read_program, Command, Line, Node, Primitive}; use super::{Command, Node, Primitive, Program};
use crate::parsers::generic::read_string; use crate::{
commands::Line,
parsers::{commands::parse_line, generic::read_string},
};
#[test] #[test]
fn it_parses_a_print_command() { fn it_parses_a_print_command() {
@@ -308,8 +211,8 @@ mod tests {
next: Box::new(Node::None), next: Box::new(Node::None),
}), }),
}; };
let expected = ("", super::Program::new(expected_node)); let expected = Program::new(expected_node);
let result = read_program(lines).unwrap(); let result = Program::from(lines);
assert_eq!(expected, result); assert_eq!(expected, result);
} }
+35
View File
@@ -0,0 +1,35 @@
use std::fmt::Display;
pub type Line = (usize, Command);
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Command {
Print(PrintOutput),
GoTo(usize),
Var((String, Primitive)),
Comment,
None,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Primitive {
Int(i64),
String(String),
Assignment(String),
}
impl Display for Primitive {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Primitive::Int(i) => write!(f, "{}", i),
Primitive::String(s) => write!(f, "{}", s),
Primitive::Assignment(a) => write!(f, "Assigment from {}", a),
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum PrintOutput {
Value(String),
Variable(String),
}
+2
View File
@@ -1,6 +1,8 @@
use std::fs; use std::fs;
mod basic; mod basic;
mod commands;
mod node;
mod parsers; mod parsers;
fn main() { fn main() {
+37
View File
@@ -0,0 +1,37 @@
use crate::commands::Line;
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Node {
None,
Link { item: Line, next: Box<Node> },
}
impl Node {
pub fn push(&mut self, val: Line) {
*self = match self {
Self::Link { item, next } => {
next.push(val);
Self::Link {
item: item.clone(),
next: next.clone(),
}
}
Self::None => Self::Link {
item: val,
next: Box::new(Self::None),
},
}
}
pub fn find_line(&self, line: usize) -> Option<Node> {
if let Self::Link { item, next } = self {
if item.0 == line {
Some(self.clone())
} else {
next.find_line(line)
}
} else {
None
}
}
}
+2
View File
@@ -1,2 +1,4 @@
pub mod commands;
pub mod expressions;
pub mod generic; pub mod generic;
pub mod variables; pub mod variables;
+49
View File
@@ -0,0 +1,49 @@
use nom::{
branch::alt, bytes::complete::tag, character::complete::u64 as ccu64, combinator::map,
sequence::terminated, IResult,
};
use crate::commands::{Command, Line, PrintOutput};
use super::{generic, variables};
pub fn match_command(i: &str) -> IResult<&str, &str> {
alt((tag("PRINT"), tag("GO TO"), tag("LET"), tag("REM")))(i)
}
pub fn parse_print_command(i: &str) -> IResult<&str, PrintOutput> {
alt((
map(
alt((
variables::parse_str_variable_name,
variables::parse_int_variable_name,
)),
PrintOutput::Variable,
),
map(generic::read_string, PrintOutput::Value),
))(i)
}
pub fn parse_command(i: &str) -> IResult<&str, Command> {
let (i, command): (&str, &str) = match_command(i).unwrap_or((i, ""));
let (i, _) = tag(" ")(i)?;
let (i, cmd) = match command {
"PRINT" => map(parse_print_command, Command::Print)(i)?,
"GO TO" => map(ccu64, |line| Command::GoTo(line as usize))(i)?,
"LET" => map(variables::parse_var, Command::Var)(i)?,
"REM" => {
let (i, _) = generic::consume_line(i)?;
(i, Command::Comment)
}
_ => (i, Command::None),
};
Ok((i, cmd))
}
pub fn parse_line(line: &str) -> IResult<&str, Line> {
let (i, line_number) = map(terminated(ccu64, tag(" ")), |l| l as usize)(line)?;
let (i, command) = parse_command(i)?;
Ok((i, (line_number, command)))
}
+119
View File
@@ -0,0 +1,119 @@
use nom::{
character::{complete::i64 as cci64, streaming::one_of},
combinator::{map, value},
sequence::tuple,
IResult, branch::alt, multi::many0,
};
use crate::commands::Primitive;
use super::variables::parse_int;
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Operator {
Add,
Subtract,
Divide,
Multiply,
}
impl From<char> for Operator {
fn from(value: char) -> Self {
match value {
'+' => Operator::Add,
'-' => Operator::Subtract,
'/' => Operator::Divide,
'*' => Operator::Multiply,
_ => panic!("Unrecognised character"),
}
}
}
pub type Expression = (ExpressionTarget, Operator, ExpressionTarget);
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ExpressionTarget {
Val(Primitive),
Expression(Box<Expression>),
}
impl From<i64> for ExpressionTarget {
fn from(value: i64) -> Self {
ExpressionTarget::Val(Primitive::Int(value))
}
}
impl From<Expression> for ExpressionTarget {
fn from(value: Expression) -> Self {
Self::Expression(Box::new(value))
}
}
fn parse_expression_target(i: &str) -> IResult<&str, ExpressionTarget> {
alt((
map(parse_expression, ExpressionTarget::from),
map(cci64, ExpressionTarget::from)
))(i)
}
pub fn parse_expression(i: &str) -> IResult<&str, Expression> {
tuple((map(cci64, ExpressionTarget::from),
map(one_of("*/+-"), Operator::from),
map(cci64, ExpressionTarget::from)))(i)
}
pub fn parse_full_expression(i: &str) -> IResult<&str, Expression> {
tuple((
parse_expression_target,
map(one_of("*/+-"), Operator::from),
parse_expression_target,
))(i)
}
#[cfg(test)]
mod tests {
use crate::commands::Primitive;
use super::{parse_full_expression, Expression, ExpressionTarget, Operator};
#[test]
fn it_parses_a_simple_expression() {
let input = "1+1";
let expected: Expression = (
ExpressionTarget::Val(Primitive::Int(1)),
Operator::Add,
ExpressionTarget::Val(Primitive::Int(1)),
);
let (_, result) = parse_full_expression(input).unwrap();
assert_eq!(expected, result);
}
#[test]
fn it_parses_a_subtraction_expression() {
let input = "1-1";
let expected: Expression = (
ExpressionTarget::Val(Primitive::Int(1)),
Operator::Subtract,
ExpressionTarget::Val(Primitive::Int(1)),
);
let (_, result) = parse_full_expression(input).unwrap();
assert_eq!(expected, result);
}
#[test]
fn it_parses_a_left_hand_subexpression() {
let input = "1+1+2";
let expected: Expression = (
ExpressionTarget::Expression(Box::new((
ExpressionTarget::Val(Primitive::Int(1)),
Operator::Add,
ExpressionTarget::Val(Primitive::Int(1))
))),
Operator::Add,
ExpressionTarget::Val(Primitive::Int(2))
);
let (_, result) = parse_full_expression(input).unwrap();
assert_eq!(expected, result);
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ use nom::{
IResult, IResult,
}; };
use crate::basic::Primitive; use crate::commands::Primitive;
use super::generic::{consume_line, read_string}; use super::generic::{consume_line, read_string};