Compare commits
7 Commits
5272744330
...
761600a759
Author | SHA1 | Date |
---|---|---|
~karx | 761600a759 | |
~karx | 6788ddbbb6 | |
~karx | 618a47422e | |
~karx | 630e38cfda | |
~karx | 0355142103 | |
~karx | 1a811c650f | |
~karx | 520c7f9262 |
33
README.md
33
README.md
|
@ -30,6 +30,7 @@ The currently available opcodes are as follows:
|
|||
- `p` - print out the arguments: `pHello World!` prints "Hello World!"
|
||||
- `a`, `s`, `m`, `d` - add, subtract, multiply, and divide, respectively: `a2-2` adds 2 + 2.
|
||||
- `l` - declare a variable: `lv9` declares variable `v` with value `9`; doing `p$v` prints out 9.
|
||||
- `f` - declare a function: see [Functions](#make-a-pull-request) for more info
|
||||
- `#` - comment: the interpreter will skip this line.
|
||||
|
||||
Here's an example "Hello world" program:
|
||||
|
@ -40,6 +41,31 @@ lwWorld!
|
|||
p$h $w
|
||||
```
|
||||
|
||||
### Functions
|
||||
|
||||
*functions* are ways to "pipe" math output to another operation. For example, you could assign the output to a variable, like below:
|
||||
|
||||
```
|
||||
#Declare a function
|
||||
fxa3-3
|
||||
#Call the function and assign it to variable
|
||||
lv*x
|
||||
#will print out 6
|
||||
p$v
|
||||
```
|
||||
|
||||
Or you could print it out directly:
|
||||
|
||||
```
|
||||
#Declare a function
|
||||
fxs30-3
|
||||
#Call it and print it out
|
||||
#Will print out 27
|
||||
p*x
|
||||
```
|
||||
|
||||
Read [the devlog entry for more](https:/tilde.team/~karx/blog/sandwich-devlog-3-function-junction.html) info.
|
||||
|
||||
## Contributing
|
||||
|
||||
|
||||
|
@ -63,10 +89,11 @@ Read [this guide](https://git-send-email.io) for more information.
|
|||
|
||||
## TODO
|
||||
|
||||
- [x] Better documentation
|
||||
|
||||
- [ ] Ability to explicitly print math output and assign math output to variables
|
||||
- [x] Add support for comments (should be pretty easy)
|
||||
- [x] Unit testing and CI/CD
|
||||
- [ ] Better function parsing (multi-instruction functions?)
|
||||
- [ ] Importing/Running other files
|
||||
- [ ] "Verbose" or "Debug" mode (environment variable or flag?)
|
||||
|
||||
## License
|
||||
|
||||
|
|
10
src/eval.rs
10
src/eval.rs
|
@ -3,19 +3,19 @@ pub fn do_math(arguments: String, operator: char) -> u32 {
|
|||
|
||||
let num1: u32 = match split_args[0].parse() {
|
||||
Ok(num) => num,
|
||||
Err(_e) => panic!("ArgumentError: Not a number: {}", split_args[0])
|
||||
Err(_e) => panic!("ArgumentError: Not a number: {}", split_args[0]),
|
||||
};
|
||||
|
||||
let num2: u32 = match split_args[1].parse() {
|
||||
Ok(num) => num,
|
||||
Err(_e) => panic!("ArgumentError: Not a number: {}", split_args[1])
|
||||
Err(_e) => panic!("ArgumentError: Not a number: {}", split_args[1]),
|
||||
};
|
||||
|
||||
|
||||
match operator {
|
||||
'+' => num1 + num2,
|
||||
'-' => num1 - num2,
|
||||
'*' => num1 * num2,
|
||||
'/' => num1 / num2,
|
||||
_ => panic!("SyntaxError: Unknown operator {}", operator)
|
||||
_ => panic!("SyntaxError: Unknown operator {}", operator),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
132
src/main.rs
132
src/main.rs
|
@ -1,21 +1,22 @@
|
|||
use std::fs;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::fmt;
|
||||
use std::fs;
|
||||
use std::usize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
mod eval;
|
||||
|
||||
struct Program {
|
||||
data: Vec<String>,
|
||||
pc: usize,
|
||||
vars: HashMap<char, String>
|
||||
vars: HashMap<char, String>,
|
||||
funcs: HashMap<char, String>
|
||||
}
|
||||
|
||||
impl Program {
|
||||
fn from_string(program: String) -> Program {
|
||||
let mut op_list: Vec<String> = Vec::new();
|
||||
|
||||
|
||||
for opcode in program.split("\n").collect::<Vec<&str>>() {
|
||||
let new_op = opcode.to_owned();
|
||||
|
||||
|
@ -24,7 +25,12 @@ impl Program {
|
|||
}
|
||||
}
|
||||
|
||||
return Program{ data: op_list, pc: 0, vars: HashMap::new() };
|
||||
return Program {
|
||||
data: op_list,
|
||||
pc: 0,
|
||||
vars: HashMap::new(),
|
||||
funcs: HashMap::new()
|
||||
};
|
||||
}
|
||||
|
||||
// Reads the arguments passed to an opcode, and inserts variables where necessary
|
||||
|
@ -40,28 +46,26 @@ impl Program {
|
|||
if index > 0 {
|
||||
// Only test for the dollar sign if it's not the first character
|
||||
// This is because there can't be anything before the first character, otherwise it's not the first
|
||||
if argument_vec[index-1] == '$' {
|
||||
if argument_vec[index - 1] == '$' {
|
||||
// If the previous character is a dollar sign, we can skip this iteration because we know the variable has already been handled
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if current_char == '$' {
|
||||
// If the current char is a $, we know that the next char should be a variable
|
||||
let variable = argument_vec[index+1];
|
||||
let variable = argument_vec[index + 1];
|
||||
|
||||
let key = self.vars.get(&variable);
|
||||
match key {
|
||||
Some(value) => str_to_push = value.to_string(),
|
||||
None => panic!("NotFoundError: Variable {} has not been defined", variable)
|
||||
None => panic!("NotFoundError: Variable {} has not been defined", variable),
|
||||
}
|
||||
|
||||
} else {
|
||||
// If there's no variable, then just push the char that was already there
|
||||
str_to_push = current_char.to_string();
|
||||
}
|
||||
|
||||
|
||||
builder.push_str(&str_to_push);
|
||||
}
|
||||
|
||||
|
@ -71,25 +75,86 @@ impl Program {
|
|||
fn add_var(&mut self, arguments: &str) {
|
||||
let argument_vec: Vec<char> = arguments.chars().collect();
|
||||
let name = argument_vec[0];
|
||||
let value: String = argument_vec[1..].into_iter().collect();
|
||||
let mut value: String = argument_vec[1..].into_iter().collect();
|
||||
value = self.args_or_funcs(&value);
|
||||
|
||||
self.vars.insert(name, value);
|
||||
}
|
||||
|
||||
fn add_func(&mut self, arguments: &str) {
|
||||
let argument_vec: Vec<char> = arguments.chars().collect();
|
||||
let name = argument_vec[0];
|
||||
let body: String = argument_vec[1..].into_iter().collect();
|
||||
|
||||
self.funcs.insert(name, body);
|
||||
}
|
||||
|
||||
fn parse_funcs(&mut self, instruction: &String) -> u32 {
|
||||
// Opcode is the first character, arguments are everything after the first char
|
||||
let opcode = instruction.chars().collect::<Vec<char>>()[0];
|
||||
let arguments = &instruction[1..];
|
||||
|
||||
// Only a subset of opcodes, because the others don't make sense in a function
|
||||
match opcode {
|
||||
'a' => eval::do_math(self.args_or_funcs(&self.args_or_vars(arguments)), '+'),
|
||||
's' => eval::do_math(self.args_or_funcs(&self.args_or_vars(arguments)), '-'),
|
||||
'm' => eval::do_math(self.args_or_funcs(&self.args_or_vars(arguments)), '*'),
|
||||
'd' => eval::do_math(self.args_or_funcs(&self.args_or_vars(arguments)), '/'),
|
||||
'l' => {self.add_var(arguments);0}
|
||||
_ => panic!("SyntaxError: No such opcode: {}", self.pc),
|
||||
}
|
||||
}
|
||||
|
||||
fn args_or_funcs(&mut self, arguments: &str) -> String {
|
||||
let mut builder = String::from("");
|
||||
let argument_vec: Vec<char> = arguments.chars().collect();
|
||||
|
||||
for index in 0..argument_vec.len() {
|
||||
let current_char = argument_vec[index];
|
||||
let str_to_push: String;
|
||||
|
||||
if index > 0 {
|
||||
if argument_vec[index-1] == '*' {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if current_char == '*' {
|
||||
let func_name = argument_vec[index+1];
|
||||
let body: String;
|
||||
|
||||
let key = (self).funcs.get(&func_name);
|
||||
match key {
|
||||
Some(content) => body = content.to_owned(),
|
||||
None => panic!("ValueError: function {} has not been defined yet!", func_name)
|
||||
}
|
||||
|
||||
str_to_push = self.parse_funcs(&body).to_string();
|
||||
} else {
|
||||
str_to_push = current_char.to_string();
|
||||
}
|
||||
|
||||
builder.push_str(&str_to_push);
|
||||
}
|
||||
|
||||
builder
|
||||
}
|
||||
|
||||
fn parse(&mut self, instruction: &String) {
|
||||
// Opcode is the first character, arguments are everything after the first char
|
||||
let opcode = instruction.chars().collect::<Vec<char>>()[0];
|
||||
let arguments = &instruction[1..];
|
||||
|
||||
match opcode {
|
||||
'p' => println!("{}", self.args_or_vars(arguments)),
|
||||
'p' => println!("{}", self.args_or_funcs(&self.args_or_vars(arguments))),
|
||||
'a' => println!("{}", eval::do_math(self.args_or_vars(arguments), '+')),
|
||||
's' => println!("{}", eval::do_math(self.args_or_vars(arguments), '-')),
|
||||
'm' => println!("{}", eval::do_math(self.args_or_vars(arguments), '*')),
|
||||
'd' => println!("{}", eval::do_math(self.args_or_vars(arguments), '/')),
|
||||
'l' => self.add_var(arguments),
|
||||
'#' => {}, // Do nothing for comments
|
||||
_ => panic!("SyntaxError: No such opcode: {}", self.pc)
|
||||
'f' => self.add_func(arguments),
|
||||
'#' => {} // Do nothing for comments
|
||||
_ => panic!("SyntaxError at opcode {}: Unknown opcode {}", self.pc, opcode),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -116,7 +181,7 @@ fn main() {
|
|||
// Grab args and a filename
|
||||
let args: Vec<String> = env::args().collect();
|
||||
if args.len() == 1 {
|
||||
// Args will always have at least 1 argument, which is the name of the executable.
|
||||
// Args will always have at least 1 argument, which is the name of the executable.
|
||||
// That's why we're checking index 1, not index 0.
|
||||
panic!("You must provide a filename!");
|
||||
}
|
||||
|
@ -154,4 +219,37 @@ mod tests {
|
|||
make_program("p$v").run();
|
||||
}
|
||||
|
||||
}
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_undefined_function() {
|
||||
make_program("p*x").run();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_factory() {
|
||||
let prog = make_program("lhHello\nlwWorld\np$h $w");
|
||||
let vec_to_check: Vec<String> = vec!["lhHello", "lwWorld", "p$h $w"].into_iter().map(|s| s.to_string()).collect();
|
||||
|
||||
assert_eq!(prog.data, vec_to_check);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_args() {
|
||||
let mut prog = make_program("lhHello\nlwWorld\np$h $w");
|
||||
prog.run();
|
||||
|
||||
let args_to_check: HashMap<char, String> = [('h', String::from("Hello")), ('w', String::from("World"))].iter().cloned().collect();
|
||||
|
||||
assert_eq!(prog.vars, args_to_check);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_funcs() {
|
||||
let mut prog = make_program("fxa10-10\nfys10-5\np*x *y");
|
||||
prog.run();
|
||||
|
||||
let funcs_to_check: HashMap<char, String> = [('x', String::from("a10-10")), ('y', String::from("s10-5"))].iter().cloned().collect();
|
||||
|
||||
assert_eq!(prog.funcs, funcs_to_check);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue