Compare commits
15
Commits
9f55bef238
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e500e9ec3 | ||
|
|
627baa8449 | ||
|
|
756d572d21 | ||
|
|
c7c7704b5d | ||
|
|
ed885b0f81 | ||
|
|
92e98bbdcb | ||
|
|
b363349dd2 | ||
|
|
4da9e9d781 | ||
|
|
b2e2db96db | ||
|
|
0e6ebd621f | ||
|
|
98e2380981 | ||
|
|
007634c980 | ||
|
|
facd320822 | ||
|
|
dd6a64539a | ||
|
|
83bf4b3bac |
No files matched your search
@@ -0,0 +1,8 @@
|
|||||||
|
10 REM Assign vars
|
||||||
|
20 LET a$="Hello"
|
||||||
|
30 LET b$="World"
|
||||||
|
40 LET c$=a$
|
||||||
|
50 REM Print values
|
||||||
|
60 PRINT a$
|
||||||
|
70 PRINT b$
|
||||||
|
80 PRINT c$
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
10 PRINT "Hello World"
|
||||||
|
20 LET apple=10
|
||||||
|
30 LET b$="Hello"
|
||||||
|
40 LET cat=apple
|
||||||
+267
-45
@@ -1,77 +1,299 @@
|
|||||||
use nom::{
|
use std::collections::HashMap;
|
||||||
branch::alt,
|
|
||||||
bytes::complete::{escaped_transform, tag, take_until},
|
use nom::{bytes::complete::tag, multi::separated_list0, IResult};
|
||||||
character::{
|
|
||||||
complete::{u32 as ccu32},
|
use crate::{
|
||||||
streaming::none_of,
|
commands::{Command, Primitive, PrintOutput},
|
||||||
},
|
node::Node,
|
||||||
combinator::{map, value},
|
parsers,
|
||||||
sequence::{delimited, terminated, tuple},
|
|
||||||
IResult,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub type Line = (u32, Command);
|
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||||
|
pub struct Program {
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
nodes: Node,
|
||||||
pub enum Command {
|
current: Node,
|
||||||
Print(String),
|
vars: HashMap<String, Primitive>,
|
||||||
None,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_string(i: &str) -> IResult<&str, String> {
|
impl Program {
|
||||||
// take_until("\"")(i)
|
pub fn new(node: Node) -> Self {
|
||||||
delimited(
|
Program {
|
||||||
tag("\""),
|
vars: HashMap::new(),
|
||||||
escaped_transform(
|
nodes: node.clone(),
|
||||||
none_of("\\\""),
|
current: node,
|
||||||
'\\',
|
}
|
||||||
alt((value("\\", tag("\\")), value("\"", tag("\"")))),
|
}
|
||||||
),
|
|
||||||
tag("\""),
|
pub fn jump_to_line(&mut self, line: usize) {
|
||||||
)(i)
|
if let Some(node) = self.nodes.find_line(line) {
|
||||||
|
self.current = node;
|
||||||
|
} else {
|
||||||
|
panic!("Cannot jump to line {}, it does not exist", line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn execute(&mut self) {
|
||||||
|
let mut iter = self.clone();
|
||||||
|
|
||||||
|
while let Some(node) = iter.next() {
|
||||||
|
if let Node::Link { item, next: _ } = node {
|
||||||
|
match item.1 {
|
||||||
|
Command::Print(PrintOutput::Value(line)) => println!("{}", line),
|
||||||
|
Command::Print(PrintOutput::Variable(variable)) => {
|
||||||
|
println!("{}", self.vars.get(&variable).unwrap())
|
||||||
|
}
|
||||||
|
Command::GoTo(line) => iter.jump_to_line(line),
|
||||||
|
Command::Var((id, Primitive::Assignment(variable))) => {
|
||||||
|
self.vars
|
||||||
|
.insert(id, self.vars.get(&variable).unwrap().clone());
|
||||||
|
}
|
||||||
|
Command::Var((id, var)) => {
|
||||||
|
self.vars.insert(id, var);
|
||||||
|
}
|
||||||
|
Command::Comment => (),
|
||||||
|
_ => panic!("Unrecognised command"),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_command(i: &str) -> IResult<&str, Command> {
|
impl From<&str> for Program {
|
||||||
let (i, (command, _)) = tuple((take_until(" "), tag(" ")))(i)?;
|
fn from(value: &str) -> Self {
|
||||||
|
let (_, program) = Self::read(value).unwrap();
|
||||||
let (i, cmd) = match command {
|
program
|
||||||
"PRINT" => map(read_string, Command::Print)(i)?,
|
}
|
||||||
_ => (i, Command::None),
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok((i, cmd))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parse_line(line: &str) -> IResult<&str, Line> {
|
impl Iterator for Program {
|
||||||
let (i, line_number) = terminated(ccu32, tag(" "))(line)?;
|
type Item = Node;
|
||||||
let (i, command) = parse_command(i)?;
|
|
||||||
Ok((i, (line_number, command)))
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
|
let curr = self.current.clone();
|
||||||
|
match &self.current {
|
||||||
|
Node::Link { item: _, next } => {
|
||||||
|
self.current = *next.clone();
|
||||||
|
Some(curr)
|
||||||
|
}
|
||||||
|
Node::None => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
use crate::basic::PrintOutput;
|
||||||
|
|
||||||
|
use super::{Command, Node, Primitive, Program};
|
||||||
|
|
||||||
|
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() {
|
||||||
let input = "10 PRINT \"Hello, world\"";
|
let input = "10 PRINT \"Hello, world\"";
|
||||||
let expected = (10, super::Command::Print(String::from("Hello, world")));
|
let expected = (
|
||||||
|
10,
|
||||||
|
Command::Print(PrintOutput::Value(String::from("Hello, world"))),
|
||||||
|
);
|
||||||
|
|
||||||
let (_, result) = super::parse_line(input).unwrap();
|
let (_, result) = parse_line(input).unwrap();
|
||||||
assert_eq!(expected, result);
|
assert_eq!(expected, result);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn it_reads_a_string() {
|
fn it_reads_a_string() {
|
||||||
let input = r#""Hello, \"World\"""#;
|
let input = r#""Hello, \"World\"""#;
|
||||||
let (_, output) = super::read_string(input).unwrap();
|
let (_, output) = read_string(input).unwrap();
|
||||||
assert_eq!(r#"Hello, "World""#, output);
|
assert_eq!(r#"Hello, "World""#, output);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn it_parses_a_print_command_with_escaped_quotes() {
|
fn it_parses_a_print_command_with_escaped_quotes() {
|
||||||
let input = r#"10 PRINT "Hello, \"world\"""#;
|
let input = r#"10 PRINT "Hello, \"world\"""#;
|
||||||
let expected = (10, super::Command::Print(String::from(r#"Hello, "world""#)));
|
let expected = (
|
||||||
|
10,
|
||||||
|
Command::Print(PrintOutput::Value(String::from(r#"Hello, "world""#))),
|
||||||
|
);
|
||||||
|
|
||||||
let (_, result) = super::parse_line(input).unwrap();
|
let (_, result) = parse_line(input).unwrap();
|
||||||
assert_eq!(expected, result);
|
assert_eq!(expected, result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_parses_a_goto_command() {
|
||||||
|
let input = "20 GO TO 10";
|
||||||
|
let expected = (20, Command::GoTo(10));
|
||||||
|
let (_, result) = parse_line(input).unwrap();
|
||||||
|
assert_eq!(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_can_create_a_linked_list_for_a_program() {
|
||||||
|
let mut node = Node::Link {
|
||||||
|
item: (
|
||||||
|
10,
|
||||||
|
Command::Print(PrintOutput::Value(String::from("Hello world"))),
|
||||||
|
),
|
||||||
|
next: Box::new(Node::None),
|
||||||
|
};
|
||||||
|
node.push((20, Command::GoTo(10)));
|
||||||
|
|
||||||
|
let expected = Node::Link {
|
||||||
|
item: (
|
||||||
|
10,
|
||||||
|
Command::Print(PrintOutput::Value(String::from("Hello world"))),
|
||||||
|
),
|
||||||
|
next: Box::new(Node::Link {
|
||||||
|
item: (20, Command::GoTo(10)),
|
||||||
|
next: Box::new(Node::None),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
assert_eq!(node, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_finds_a_node_by_line_number() {
|
||||||
|
let mut node = Node::Link {
|
||||||
|
item: (
|
||||||
|
10,
|
||||||
|
Command::Print(PrintOutput::Value(String::from("Hello world"))),
|
||||||
|
),
|
||||||
|
next: Box::new(Node::None),
|
||||||
|
};
|
||||||
|
node.push((
|
||||||
|
20,
|
||||||
|
Command::Print(PrintOutput::Value(String::from("I'm a second line"))),
|
||||||
|
));
|
||||||
|
node.push((
|
||||||
|
30,
|
||||||
|
Command::Print(PrintOutput::Value(String::from("Still printing..."))),
|
||||||
|
));
|
||||||
|
node.push((40, Command::GoTo(10)));
|
||||||
|
|
||||||
|
let expected: Option<Node> = Some(Node::Link {
|
||||||
|
item: (
|
||||||
|
30,
|
||||||
|
Command::Print(PrintOutput::Value(String::from("Still printing..."))),
|
||||||
|
),
|
||||||
|
next: Box::new(Node::Link {
|
||||||
|
item: (40, Command::GoTo(10)),
|
||||||
|
next: Box::new(Node::None),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
let result = node.find_line(30);
|
||||||
|
assert_eq!(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_reads_a_program() {
|
||||||
|
let lines = "10 PRINT \"Hello world\"\n20 GO TO 10";
|
||||||
|
let expected_node = Node::Link {
|
||||||
|
item: (
|
||||||
|
10,
|
||||||
|
Command::Print(PrintOutput::Value(String::from("Hello world"))),
|
||||||
|
),
|
||||||
|
next: Box::new(Node::Link {
|
||||||
|
item: (20, Command::GoTo(10)),
|
||||||
|
next: Box::new(Node::None),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
let expected = Program::new(expected_node);
|
||||||
|
let result = Program::from(lines);
|
||||||
|
assert_eq!(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_parses_an_integer() {
|
||||||
|
let line = "10 LET a=22";
|
||||||
|
let expected: Line = (10, Command::Var((String::from("a"), Primitive::Int(22))));
|
||||||
|
let (_, result) = parse_line(line).unwrap();
|
||||||
|
assert_eq!(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_parses_a_many_char_integer() {
|
||||||
|
let line = "10 LET apple=1";
|
||||||
|
let expected: Line = (10, Command::Var((String::from("apple"), Primitive::Int(1))));
|
||||||
|
let (_, result) = parse_line(line).unwrap();
|
||||||
|
assert_eq!(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_fails_if_integer_var_name_starts_with_number() {
|
||||||
|
let line = "10 LET 0apple=1";
|
||||||
|
let result = parse_line(line);
|
||||||
|
assert!(result.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_parses_a_string_variable() {
|
||||||
|
let line = r#"10 LET a$="Hello world""#;
|
||||||
|
let expected: Line = (
|
||||||
|
10,
|
||||||
|
Command::Var((
|
||||||
|
String::from("a$"),
|
||||||
|
Primitive::String(String::from("Hello world")),
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
let (_, result) = parse_line(line).unwrap();
|
||||||
|
assert_eq!(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_fails_a_string_var_with_a_multichar_name() {
|
||||||
|
let line = r#"10 LET asd$="Hello world""#;
|
||||||
|
let result = parse_line(line);
|
||||||
|
assert!(result.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_fails_a_string_var_with_a_numeric_name() {
|
||||||
|
let line = r#"10 LET 0$="Hello world""#;
|
||||||
|
let result = parse_line(line);
|
||||||
|
assert!(result.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_assigns_one_variable_to_another() {
|
||||||
|
let line = "10 LET a=b$";
|
||||||
|
let (_, result) = parse_line(line).unwrap();
|
||||||
|
let expected: Line = (
|
||||||
|
10,
|
||||||
|
Command::Var((String::from("a"), Primitive::Assignment(String::from("b$")))),
|
||||||
|
);
|
||||||
|
assert_eq!(result, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_parses_a_print_command_with_a_variable_name() {
|
||||||
|
let line = "10 PRINT a$";
|
||||||
|
let (_, result) = parse_line(line).unwrap();
|
||||||
|
let expected: Line = (
|
||||||
|
10,
|
||||||
|
Command::Print(PrintOutput::Variable(String::from("a$"))),
|
||||||
|
);
|
||||||
|
assert_eq!(result, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_parses_a_comment() {
|
||||||
|
let line = "10 REM This is an arbitrary comment";
|
||||||
|
let (_, result) = parse_line(line).unwrap();
|
||||||
|
let expected: Line = (10, Command::Comment);
|
||||||
|
assert_eq!(result, expected);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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),
|
||||||
|
}
|
||||||
+6
-11
@@ -1,17 +1,12 @@
|
|||||||
use std::fs;
|
use std::fs;
|
||||||
|
|
||||||
mod basic;
|
mod basic;
|
||||||
|
mod commands;
|
||||||
|
mod node;
|
||||||
|
mod parsers;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let file = fs::read_to_string("./inputs/hello_world.bas").unwrap();
|
let file = fs::read_to_string("./inputs/printing_program.bas").unwrap();
|
||||||
let lines = file.lines().next().unwrap();
|
let mut program = basic::Program::from(file.as_str());
|
||||||
let (_, (_, command)) = basic::parse_line(lines).unwrap();
|
program.execute();
|
||||||
match command {
|
|
||||||
basic::Command::Print(input) => {
|
|
||||||
println!("{}", input);
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
panic!("Command not recognised");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
+37
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
pub mod commands;
|
||||||
|
pub mod expressions;
|
||||||
|
pub mod generic;
|
||||||
|
pub mod variables;
|
||||||
@@ -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)))
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
use nom::{
|
||||||
|
branch::alt,
|
||||||
|
bytes::complete::{escaped_transform, tag, take_while},
|
||||||
|
character::complete::none_of,
|
||||||
|
combinator::value,
|
||||||
|
sequence::delimited,
|
||||||
|
IResult,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Take everything until it hits a newline, if it does
|
||||||
|
pub fn consume_line(i: &str) -> IResult<&str, &str> {
|
||||||
|
take_while(|c| c != '\n')(i)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_string(i: &str) -> IResult<&str, String> {
|
||||||
|
delimited(
|
||||||
|
tag("\""),
|
||||||
|
escaped_transform(
|
||||||
|
none_of("\\\""),
|
||||||
|
'\\',
|
||||||
|
alt((value("\\", tag("\\")), value("\"", tag("\"")))),
|
||||||
|
),
|
||||||
|
tag("\""),
|
||||||
|
)(i)
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
use nom::{
|
||||||
|
branch::alt,
|
||||||
|
bytes::complete::tag,
|
||||||
|
character::complete::{alphanumeric1, anychar, digit1, i64 as cci64},
|
||||||
|
combinator::{map, not, verify},
|
||||||
|
sequence::{preceded, terminated},
|
||||||
|
IResult,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::commands::Primitive;
|
||||||
|
|
||||||
|
use super::generic::{consume_line, read_string};
|
||||||
|
|
||||||
|
pub fn parse_int_variable_name(i: &str) -> IResult<&str, String> {
|
||||||
|
map(preceded(not(digit1), alphanumeric1), String::from)(i)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_int(i: &str) -> IResult<&str, (String, Primitive)> {
|
||||||
|
let (i, id) = parse_int_variable_name(i)?;
|
||||||
|
let (i, _) = tag("=")(i)?;
|
||||||
|
let (i, var) = map(cci64, Primitive::Int)(i)?;
|
||||||
|
|
||||||
|
Ok((i, (id, var)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_str_variable_name(i: &str) -> IResult<&str, String> {
|
||||||
|
let (i, id) = terminated(verify(anychar, |c| c.is_alphabetic()), tag("$"))(i)?;
|
||||||
|
let id = format!("{}$", id);
|
||||||
|
Ok((i, id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_str(i: &str) -> IResult<&str, (String, Primitive)> {
|
||||||
|
let (i, id) = parse_str_variable_name(i)?;
|
||||||
|
let (i, _) = tag("=")(i)?;
|
||||||
|
let (i, var) = map(read_string, Primitive::String)(i)?;
|
||||||
|
Ok((i, (id, var)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_assignment(i: &str) -> IResult<&str, (String, Primitive)> {
|
||||||
|
let (i, id) = alt((parse_str_variable_name, parse_int_variable_name))(i)?;
|
||||||
|
let (i, _) = tag("=")(i)?;
|
||||||
|
let (i, assigned_variable) = consume_line(i)?;
|
||||||
|
Ok((
|
||||||
|
i,
|
||||||
|
(id, Primitive::Assignment(assigned_variable.to_string())),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_var(i: &str) -> IResult<&str, (String, Primitive)> {
|
||||||
|
alt((parse_int, parse_str, parse_assignment))(i)
|
||||||
|
}
|
||||||
Reference in new issue
Block a user