Compare commits

...

6 Commits

2 changed files with 67 additions and 17 deletions

View File

@ -21,9 +21,18 @@ opcodeArguments
The currently available opcodes are as follows:
- `p` - print out the arguments: `pHello pWorld!` prints "Hello World!"
- `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 `pv` prints out 9.
- `l` - declare a variable: `lv9` declares variable `v` with value `9`; doing `p$v` prints out 9.
- `#` - comment: the interpreter will skip this line.
Here's an example "Hello world" program:
```
lhHello
lwWorld!
p$h $w
```
## Contributing
@ -46,6 +55,13 @@ You can do two things to submit code:
You can send a patch to `karx@tilde.team`.
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)
- [ ] Unit testing and CI/CD
## License
This is free and unencumbered software released into the public domain.

View File

@ -9,16 +9,15 @@ mod eval;
struct Program {
data: Vec<String>,
pc: usize,
vars: HashMap<char, char>
vars: HashMap<char, String>
}
impl Program {
fn from_string(program: String) -> Program {
let mut op_list: Vec<String> = Vec::new();
for opcode in program.split(" ").collect::<Vec<&str>>() {
let mut new_op = opcode.to_owned();
new_op = new_op.replace("\n", "");
for opcode in program.split("\n").collect::<Vec<&str>>() {
let new_op = opcode.to_owned();
if new_op.len() != 0 {
op_list.push(new_op.to_owned());
@ -28,28 +27,57 @@ impl Program {
return Program{ data: op_list, pc: 0, vars: HashMap::new() };
}
fn args_or_vars<'a>(&self, arguments: &'a str) -> String {
let mut deconstructed: Vec<char> = arguments.chars().collect();
// Reads the arguments passed to an opcode, and inserts variables where necessary
fn args_or_vars(&self, arguments: &str) -> String {
let mut builder = String::from(""); // Empty string that will be rebuilt based on the loop
let argument_vec: Vec<char> = arguments.chars().collect(); // Deconstructed arguments
for (index, char) in arguments.chars().enumerate() {
let value = self.vars.get(&char);
// Iterate through each char
for index in 0..argument_vec.len() {
let current_char = argument_vec[index];
let str_to_push: String;
match value {
Some(content) => deconstructed[index] = *content,
None => {}
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 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 key = self.vars.get(&variable);
match key {
Some(value) => str_to_push = value.to_string(),
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);
}
deconstructed.into_iter().collect()
builder
}
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();
self.vars.insert(argument_vec[0], argument_vec[1]);
self.vars.insert(name, value);
}
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..];
@ -60,18 +88,20 @@ impl Program {
'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),
_ => panic!("SyntaxError at opcode {}!", self.pc)
'#' => {}, // Do nothing for comments
_ => panic!("SyntaxError: No such opcode: {}", self.pc)
}
}
fn run(&mut self) {
println!("{}", self);
while self.pc < self.data.len() {
// Grab instruction from op list and parse the instruction
let instruction = self.data[self.pc].to_owned();
self.parse(&instruction);
self.pc = self.pc + 1;
self.pc += 1;
}
}
}
@ -83,13 +113,17 @@ impl fmt::Display for Program {
}
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.
// That's why we're checking index 1, not index 0.
panic!("You must provide a filename!");
}
let filename = &args[1];
// Read contents of the provided file and construct a symbolic Program from it
let contents = fs::read_to_string(filename).expect("Something went wrong reading the file");
let mut prog = Program::from_string(contents);
prog.run();