feat: calc

This commit is contained in:
Artemy 2022-08-03 16:28:00 +03:00
parent e9c84d1066
commit 757d668f46
3 changed files with 284 additions and 122 deletions

7
LICENSE Normal file
View file

@ -0,0 +1,7 @@
Copyright © 2022 Artemy Egorov
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,6 +1,6 @@
use colored::*; use colored::*;
use json5; use json5;
use serde_json::Value; use serde_json::{json, Value};
use std::collections::HashMap; use std::collections::HashMap;
pub struct Interpreter { pub struct Interpreter {
input: String, input: String,
@ -22,11 +22,19 @@ impl Interpreter {
let arr = obj.as_array_mut().unwrap(); let arr = obj.as_array_mut().unwrap();
for command in arr { for command in arr {
self.eval_node(command);
}
self.pos += 1;
}
fn eval_node(&self, command: &mut Value) -> Value {
match command { match command {
Value::Object(command) => { Value::Object(command) => {
for (name, value) in command { for (name, value) in command {
match name.as_str() { match name.as_str() {
"print" => match value { "print" => {
match value {
Value::Array(value) => { Value::Array(value) => {
self.print(value, false); self.print(value, false);
} }
@ -36,8 +44,11 @@ impl Interpreter {
_ => { _ => {
self.error("Unsupported data type for the print argument"); self.error("Unsupported data type for the print argument");
} }
}, }
"println" => match value { return Value::Null;
}
"println" => {
match value {
Value::Array(value) => { Value::Array(value) => {
self.print(value, true); self.print(value, true);
} }
@ -47,14 +58,34 @@ impl Interpreter {
_ => { _ => {
self.error("Unsupported data type for the println argument"); self.error("Unsupported data type for the println argument");
} }
}, }
return Value::Null;
}
"calc" => {
match value {
Value::Array(value) => {
if value.len() == 3 {
return self.calc(value);
} else {
return Value::Null;
}
}
_ => {
self.error("Unsupported data type for the println argument");
}
}
return Value::Null;
}
name => { name => {
self.unk_token(&name); self.unk_token(&name);
return Value::Null;
} }
} }
} }
Value::Null
} }
Value::String(name) => match name.as_str() { Value::String(name) => {
match name.as_str() {
"Exit" => { "Exit" => {
self.exit(); self.exit();
} }
@ -64,20 +95,104 @@ impl Interpreter {
value => { value => {
self.print(&mut vec![Value::String(value.to_string())], false); self.print(&mut vec![Value::String(value.to_string())], false);
} }
}, }
Value::Null
}
Value::Array(command) => { Value::Array(command) => {
self.print(command, false); self.print(command, false);
Value::Null
} }
_ => { _ => {
self.error("Unsupported data type for the command"); self.error("Unsupported data type for the command");
Value::Null
}
} }
} }
self.pos += 1; fn calc(&self, value: &mut Vec<Value>) -> Value {
let op1 = &value[0];
let operation = &value[1];
let op2 = &value[2];
match op1 {
Value::Number(op1) => match op2 {
Value::Number(op2) => {
let op1 = op1.as_f64().unwrap();
let op2 = op2.as_f64().unwrap();
match operation {
Value::String(operation) => match operation.as_str() {
"+" => json!(op1 + op2),
"-" => json!(op1 - op2),
"/" => json!(op1 / op2),
"*" => json!(op1 * op2),
"%" => json!(op1 % op2),
"&" => json!(op1 as i64 & op2 as i64),
"|" => json!(op1 as i64 | op2 as i64),
"^" => json!(op1 as i64 ^ op2 as i64),
"<<" => json!((op1 as i64) << (op2 as i64)),
">>" => json!((op1 as i64) >> (op2 as i64)),
name => {
self.error(&format!(
"Unsupported operation type for calculation: {}",
name
));
panic!();
}
},
name => {
self.error(&format!(
"Unsupported operation type for calculation: {}",
name
));
panic!();
} }
} }
}
Value::Object(_) => self.calc(&mut vec![
serde_json::Value::Number(op1.clone()),
operation.clone(),
self.eval_node(&mut op2.clone()),
]),
_ => {
self.error("Unsupported operand type for calculation");
panic!();
}
},
Value::Object(_) => match op2 {
Value::Number(_) => self.calc(&mut vec![
self.eval_node(&mut op1.clone()),
operation.clone(),
op2.clone(),
]),
Value::Object(_) => self.calc(&mut vec![
self.eval_node(&mut op1.clone()),
Value::String(operation.to_string()),
self.eval_node(&mut op2.clone()),
]),
_ => {
self.error("Unsupported operand type for calculation");
panic!();
}
},
_ => {
self.error("Unsupported operand type for calculation");
panic!();
}
}
}
fn print(&self, args: &mut Vec<Value>, ln: bool) { fn print(&self, args: &mut Vec<Value>, ln: bool) {
for arg in args { for arg in args {
self.print_one(arg);
if ln == true {
println!();
}
}
if ln == false {
println!();
}
}
fn print_one(&self, arg: &Value) {
match arg { match arg {
Value::Array(args) => { Value::Array(args) => {
print!("{}", serde_json::to_string_pretty(args).unwrap()); print!("{}", serde_json::to_string_pretty(args).unwrap());
@ -92,19 +207,12 @@ impl Interpreter {
print!("{}", arg.to_string().truecolor(180, 208, 143)); print!("{}", arg.to_string().truecolor(180, 208, 143));
} }
Value::Object(arg) => { Value::Object(arg) => {
print!("{}", serde_json::to_string_pretty(arg).unwrap()); self.print_one(&self.eval_node(&mut Value::Object(arg.clone())));
} }
Value::Null => { Value::Null => {
print!("{}", "null".blue()); print!("{}", "null".blue());
} }
} }
if ln == true {
println!();
}
}
if ln == false {
println!();
}
} }
fn exit(&self) { fn exit(&self) {
println!("{}", "Programm finished with exit code: 0".green()); println!("{}", "Programm finished with exit code: 0".green());
@ -116,7 +224,7 @@ impl Interpreter {
} }
fn unk_token(&self, name: &str) { fn unk_token(&self, name: &str) {
println!( println!(
"{} {} | {} {}", "\n{} {} | {} {}",
"Unexpected token name:".red(), "Unexpected token name:".red(),
name.bold().black(), name.bold().black(),
"pos:".green(), "pos:".green(),
@ -127,7 +235,7 @@ impl Interpreter {
fn error(&self, name: &str) { fn error(&self, name: &str) {
println!( println!(
"{} {} | {} {}", "\n{} {} | {} {}",
"Error:".red(), "Error:".red(),
name.bold().black(), name.bold().black(),
"pos:".green(), "pos:".green(),

View file

@ -1,91 +1,138 @@
// Now the file with the extension .json5, but then it will be .onla // Now the file with the extension .json5, but then it will be .onla
[ [
//print functions
{ {
print: ["Hello world", "! ", 1, "\n", ["wow"]], print: [
}, "Test calc and recursion\n",
"(2+2*4) + 2 = ",
{ {
println: ["Hello", "world", "!"], calc: [{ calc: [2, "+", { calc: [2, "*", 4] }] }, "+", 2],
}, },
{ "\n",
print: "Fool",
},
"Really?",
[2, "Yes \n", true],
true, //throw error
//Exit functions
"Exit",
"ErrExit",
//TODO CONCEPTS ---------------------
//variables------------
//defining variables
{
let: {
var: "value",
anotherVar: true,
},
},
//print variables
{ print: "@var" },
["This is ", "@var"],
//assign variables
{
assign: { var: "newvalue" },
},
//-------------------
//math--------------
{
calc: ["@var", "+", 1],
},
//or
{
calc: ["@var", "+", { calc: [1, "*", 2] }],
},
//------------------
//comparison--------
{
comp: [1, ">=", "@var"],
},
//or
{
comp: [
{ comp: [{ calc: [1, "+", 1] }, ">", 1] },
"&&",
{ comp: ["@var", ">=", 2] },
],
},
//------------------
//cycles
{
loop: [
{
let: {
var: "val",
},
},
"@var",
], ],
}, },
{ {
while: { print: [
cond: { comp: [1, ">=", "@var"] }, "-----All operators-----\n\n\tNORMAL",
body: [ "\n\t2 * 3 = ",
//commands { calc: [2, "*", 3] },
"\n\t6 / 2 = ",
{ calc: [6, "/", 2.5] },
"\n\t2 + 3 = ",
{ calc: [2, "+", 3] },
"\n\t2 - 3 = ",
{ calc: [2, "-", 3] },
"\n\t2 % 2 = ",
{ calc: [2, "%", 2] },
"\n\t3 % 2 = ",
{ calc: [3, "%", 2] },
"\n\n\tBit operators",
"\n\t4 & 4 = ",
{ calc: [4, "&", 4] },
"\n\t4 & 3 = ",
{ calc: [4, "&", 3] },
"\n\t4 | 4 = ",
{ calc: [4, "|", 4] },
"\n\t4 | 3 = ",
{ calc: [4, "|", 3] },
"\n\t-8 >> 3 = ",
{ calc: [-8, ">>", 3] },
"\n\t5 << 3 = ",
{ calc: [5, "<<", 3] },
"\n\n--End of All operators--",
], ],
}, },
}, // //print functions
// {
// print: ["Hello world", "! ", 1, "\n", ["wow"], "\n", { calc: [1, "+", 2] }],
// },
// {
// println: ["Hello", "world", "!"],
// },
// {
// print: "Fool",
// },
// "Really?",
// [2, "Yes \n", true],
// true, //throw error
// //Exit functions
// "Exit",
// "ErrExit",
// //TODO CONCEPTS ##########################################################################################################################################################################################################################
// //variables------------
// //defining variables
// {
// let: {
// var: "value",
// anotherVar: true,
// },
// },
// //print variables
// { print: "@var" },
// ["This is ", "@var"],
// //assign variables
// {
// assign: { var: "newvalue" },
// },
// //-------------------
// //math--------------
// {
// calc: ["@var", "+", 1],
// },
// //or
// {
// calc: ["@var", "+", { calc: [1, "*", 2] }],
// },
// //------------------
// //comparison--------
// {
// comp: [1, ">=", "@var"],
// },
// //or
// {
// comp: [
// { comp: [{ calc: [1, "+", 1] }, ">", 1] },
// "&&",
// { comp: ["@var", ">=", 2] },
// ],
// },
// //------------------
// //cycles
// {
// loop: [
// {
// let: {
// var: "val",
// },
// },
// "@var",
// ],
// },
// {
// while: {
// cond: { comp: [1, ">=", "@var"] },
// body: [
// //commands
// ],
// },
// },
] ]