2019-08-14 07:25:45 -07:00
|
|
|
use std::rc::Rc;
|
|
|
|
|
2019-08-15 06:28:40 -07:00
|
|
|
use crate::tokenizing::TokenKind;
|
2019-08-14 07:25:45 -07:00
|
|
|
|
|
|
|
#[derive(Debug, PartialEq, Clone)]
|
|
|
|
pub struct PrefixOp {
|
2021-10-28 02:00:37 -07:00
|
|
|
sigil: Rc<String>,
|
2019-08-14 07:25:45 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
impl PrefixOp {
|
2021-10-28 02:00:37 -07:00
|
|
|
pub fn from_sigil(sigil: &str) -> PrefixOp {
|
|
|
|
PrefixOp { sigil: Rc::new(sigil.to_string()) }
|
|
|
|
}
|
2021-10-16 20:21:08 -07:00
|
|
|
|
2021-10-28 02:00:37 -07:00
|
|
|
pub fn sigil(&self) -> &str {
|
|
|
|
&self.sigil
|
|
|
|
}
|
2021-10-16 20:21:08 -07:00
|
|
|
|
2021-10-28 02:00:37 -07:00
|
|
|
pub fn is_prefix(op: &str) -> bool {
|
|
|
|
matches!(op, "+" | "-" | "!")
|
|
|
|
}
|
2019-08-14 07:25:45 -07:00
|
|
|
}
|
|
|
|
|
2019-08-15 06:28:40 -07:00
|
|
|
#[derive(Debug, PartialEq, Clone)]
|
|
|
|
pub struct BinOp {
|
2021-10-28 02:00:37 -07:00
|
|
|
sigil: Rc<String>,
|
2019-08-15 06:28:40 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
impl BinOp {
|
2021-10-28 02:00:37 -07:00
|
|
|
pub fn from_sigil(sigil: &str) -> BinOp {
|
|
|
|
BinOp { sigil: Rc::new(sigil.to_string()) }
|
|
|
|
}
|
2021-10-16 20:21:08 -07:00
|
|
|
|
2021-10-28 02:00:37 -07:00
|
|
|
pub fn sigil(&self) -> &str {
|
|
|
|
&self.sigil
|
|
|
|
}
|
2021-10-16 20:21:08 -07:00
|
|
|
|
2021-10-28 02:00:37 -07:00
|
|
|
pub fn from_sigil_token(tok: &TokenKind) -> Option<BinOp> {
|
|
|
|
let s = token_kind_to_sigil(tok)?;
|
|
|
|
Some(BinOp::from_sigil(s))
|
|
|
|
}
|
2019-08-15 06:28:40 -07:00
|
|
|
|
2021-10-28 02:00:37 -07:00
|
|
|
pub fn min_precedence() -> i32 {
|
|
|
|
i32::min_value()
|
|
|
|
}
|
|
|
|
pub fn get_precedence_from_token(op_tok: &TokenKind) -> Option<i32> {
|
|
|
|
let s = token_kind_to_sigil(op_tok)?;
|
|
|
|
Some(binop_precedences(s))
|
|
|
|
}
|
2019-08-15 06:28:40 -07:00
|
|
|
}
|
|
|
|
|
2021-10-28 02:00:37 -07:00
|
|
|
fn token_kind_to_sigil(tok: &TokenKind) -> Option<&str> {
|
|
|
|
use self::TokenKind::*;
|
|
|
|
Some(match tok {
|
|
|
|
Operator(op) => op.as_str(),
|
|
|
|
Period => ".",
|
|
|
|
Pipe => "|",
|
|
|
|
Slash => "/",
|
|
|
|
LAngleBracket => "<",
|
|
|
|
RAngleBracket => ">",
|
|
|
|
Equals => "=",
|
|
|
|
_ => return None,
|
|
|
|
})
|
2019-08-15 06:28:40 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
fn binop_precedences(s: &str) -> i32 {
|
2021-10-28 02:00:37 -07:00
|
|
|
let default = 10_000_000;
|
|
|
|
match s {
|
|
|
|
"+" => 10,
|
|
|
|
"-" => 10,
|
|
|
|
"*" => 20,
|
|
|
|
"/" => 20,
|
|
|
|
"%" => 20,
|
|
|
|
"++" => 30,
|
|
|
|
"^" => 30,
|
|
|
|
"&" => 20,
|
|
|
|
"|" => 20,
|
|
|
|
">" => 20,
|
|
|
|
">=" => 20,
|
|
|
|
"<" => 20,
|
|
|
|
"<=" => 20,
|
|
|
|
"==" => 40,
|
|
|
|
"<=>" => 30,
|
|
|
|
"=" => 5, // Assignment shoudl have highest precedence
|
|
|
|
_ => default,
|
|
|
|
}
|
2019-08-15 06:28:40 -07:00
|
|
|
}
|