Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
389 changes: 190 additions & 199 deletions interpreter/src/ir.rs

Large diffs are not rendered by default.

409 changes: 233 additions & 176 deletions interpreter/src/ir/lower.rs

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion interpreter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
//
// For the full copyright and license information, please view the LICENSE
// files that was distributed with this source code.

#![allow(dead_code)]

pub(crate) mod ir;
Expand Down
168 changes: 91 additions & 77 deletions interpreter/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use parser::{Command, Identifier, Redirection};

use crate::{
ir::{
Instruction, Label, MaybeImm, NonLocal, Reg,
Instruction, Label, NonLocal, Reg,
lower::{Bytecode, Code},
},
types::Value,
Expand All @@ -32,7 +32,6 @@ pub enum ExecMode {
Posix,
}

#[derive(Debug)]
pub struct Interpreter<'a> {
arena: &'a Bump,
bc: Bytecode<'a>,
Expand Down Expand Up @@ -121,20 +120,25 @@ impl<'a> Consts<'a> {
impl Interpreter<'_> {
pub fn run(&mut self) {
macro_rules! rx {
($self:expr, $dest:expr, $src:ident, $e:expr) => {{
rx!($self, $src);
($self:expr, $dest:expr, $src:ident: $ty:ident, $e:expr) => {{
rx!($self, $src: $ty);
$self.registers.write($dest, $e);
}};
($self:expr, $dest:expr, $lhs:ident: $tyl:ident, $rhs:ident: $tyr:ident, $e:expr) => {{
rx!($self, $lhs: $tyl, $rhs: $tyr);
$self.registers.write($dest, $e);
}};
($self:expr, $($src:ident),+) => {
$(let $src = match $src {
MaybeImm::Reg(src) => $self.registers.get(src),
MaybeImm::Rec(_) => todo!(),
MaybeImm::Imm(src) => &Value::Int(src.into()),
MaybeImm::ImmCnt(src) => &$self.consts.0.get_index(src as _).unwrap().clone(),
MaybeImm::ImmUserVar(src) => {
&$self.symbols.lookup_user_scalar(NonLocal(src.into())).clone()
($self:expr, $($src:ident: $ty:ident),+) => {
use $crate::ir::ArgTy;
$(let $src = match $ty {
ArgTy::Reg => $self.registers.get(unsafe { $src.reg }),
ArgTy::Rec => todo!(),
ArgTy::Imm => &Value::Int(unsafe { $src.imm } as _),
ArgTy::Cnt => &$self.consts.0.get_index(unsafe { $src.sym.0 } as _).unwrap().clone(),
ArgTy::UsVal => {
&$self.symbols.lookup_user_scalar(unsafe { $src.sym }).clone()
}
MaybeImm::ImmBuiltinVar(_) => todo!(),
_ => todo!()
};)+
};
($self:expr, $dest:expr, $lhs:ident, $rhs:ident, $e:expr) => {{
Expand All @@ -144,92 +148,102 @@ impl Interpreter<'_> {
}
while let Some(&instr) = self.bc.code.get(self.program_counter) {
match instr {
Instruction::Record(_) => todo!(),
Instruction::Negation((dest, src)) => {
rx!(self, dest, src, Value::b2f(!src.to_bool()));
Instruction::Record { dest: _, arg: _, ty: _ } => todo!(),
Instruction::Negation { dest, arg, ty } => {
rx!(self, dest, arg: ty, Value::b2f(!arg.to_bool()));
}
Instruction::ToInt { dest, arg, ty } => {
rx!(self, dest, arg: ty, Value::Float(arg.to_num().trunc()));
}
Instruction::Negative { dest, arg, ty } => {
rx!(self, dest, arg: ty, Value::Float(-arg.to_num()));
}
Instruction::Copy { dest, arg, ty } => rx!(self, dest, arg: ty, arg.clone()),
Instruction::Eq { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, Value::b2f(lhs == rhs));
}
Instruction::ToInt((dest, src)) => {
rx!(self, dest, src, Value::Float(src.to_num().trunc()));
Instruction::NEq { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, Value::b2f(lhs != rhs));
}
Instruction::Negative((dest, src)) => {
rx!(self, dest, src, Value::Float(-src.to_num()));
Instruction::Gt { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, Value::b2f(lhs > rhs));
}
Instruction::Copy((dest, src)) => rx!(self, dest, src, src.clone()),
Instruction::Eq((dest, lhs, rhs)) => {
rx!(self, dest, lhs, rhs, Value::b2f(lhs == rhs));
Instruction::Lt { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, Value::b2f(lhs < rhs));
}
Instruction::NEq((dest, lhs, rhs)) => {
rx!(self, dest, lhs, rhs, Value::b2f(lhs != rhs));
Instruction::LtE { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, Value::b2f(lhs <= rhs));
}
Instruction::Gt((dest, lhs, rhs)) => {
rx!(self, dest, lhs, rhs, Value::b2f(lhs > rhs));
Instruction::GtE { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, Value::b2f(lhs >= rhs));
}
Instruction::Lt((dest, lhs, rhs)) => {
rx!(self, dest, lhs, rhs, Value::b2f(lhs < rhs));
Instruction::And { dest: _, lhs: _, rhs: _, tyr: _, tyl: _ } => todo!(),
Instruction::Or { dest: _, lhs: _, rhs: _, tyr: _, tyl: _ } => todo!(),
Instruction::Matches { dest: _, lhs: _, rhs: _, tyr: _, tyl: _ } => todo!(),
Instruction::MatchesNot { dest: _, lhs: _, rhs: _, tyr: _, tyl: _ } => todo!(),
Instruction::Add { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, lhs + rhs);
}
Instruction::LtE((dest, lhs, rhs)) => {
rx!(self, dest, lhs, rhs, Value::b2f(lhs <= rhs));
Instruction::Subtract { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, lhs - rhs);
}
Instruction::GtE((dest, lhs, rhs)) => {
rx!(self, dest, lhs, rhs, Value::b2f(lhs >= rhs));
Instruction::Multiply { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, lhs * rhs);
}
Instruction::And((_dest, _lhs, _rhs)) => todo!(),
Instruction::Or((_dest, _lhs, _rhs)) => todo!(),
Instruction::Matches((_dest, _lhs, _rhs)) => todo!(),
Instruction::MatchesNot((_dest, _lhs, _rhs)) => todo!(),
Instruction::Add((dest, lhs, rhs)) => rx!(self, dest, lhs, rhs, lhs + rhs),
Instruction::Subtract((dest, lhs, rhs)) => rx!(self, dest, lhs, rhs, lhs - rhs),
Instruction::Multiply((dest, lhs, rhs)) => rx!(self, dest, lhs, rhs, lhs * rhs),
Instruction::Divide((dest, lhs, rhs)) => rx!(self, dest, lhs, rhs, lhs / rhs),
Instruction::Raise((dest, lhs, rhs)) => rx!(self, dest, lhs, rhs, lhs ^ rhs),
Instruction::Modulo((dest, lhs, rhs)) => rx!(self, dest, lhs, rhs, lhs % rhs),
Instruction::Concat((dest, lhs, rhs)) => {
rx!(self, lhs, rhs);
Instruction::Divide { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, lhs / rhs);
}
Instruction::Raise { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, lhs ^ rhs);
}
Instruction::Modulo { dest, lhs, rhs, tyl, tyr } => {
rx!(self, dest, lhs: tyl, rhs: tyr, lhs % rhs);
}
Instruction::Concat { dest, lhs, rhs, tyl, tyr } => {
rx!(self, lhs: tyl, rhs: tyr);
let mut buf =
StdVec::with_capacity(lhs.string_size_hint() + rhs.string_size_hint());
lhs.write_string(&mut buf);
rhs.write_string(&mut buf);
self.registers.write(dest, Value::String(buf.into()));
}
Instruction::LoadUserScalar((dest, src)) => {
let val = self.symbols.lookup_user_scalar(src);
self.registers.write(dest, val.clone());
}
Instruction::LoadUserArray((_dest, _start, _end, _src)) => todo!(),
Instruction::LoadUserMDimArray((_dest, _start, _end, _place)) => todo!(),
Instruction::LoadBuiltinScalar((_dest, _src)) => todo!(),
Instruction::LoadBuiltinArray((_dest, _src, _start, _end)) => todo!(),
Instruction::LoadConst((dest, src)) => {
let val = self.consts.0.get_index(src.0 as _).unwrap().clone();
self.registers.write(dest, val);
Instruction::LoadA { dest: _, ty_place: _, start: _, end: _, var: _ } => todo!(),
Instruction::StoreS { dest, ty_place, var, arg, ty } => {
rx!(self, arg: ty);
match ty_place {
ArgTy::UsVal => self.symbols.write_user_val(var, arg.clone()),
ArgTy::IsVal => todo!(),
_ => unreachable!(),
}
self.registers.write(dest, arg.clone());
}
Instruction::StoreUserScalar((dest, imm, src)) => {
rx!(self, imm);
self.symbols.write_user_val(src, imm.clone());
self.registers.write(dest, imm.clone());
Instruction::StoreR { dest: _, src: _, arg: _, ty: _, tys: _ } => {
todo!()
}
Instruction::StoreUserArray((_dest, _src, _start, _end)) => todo!(),
Instruction::StoreUserMDimArray((_dest, _start, _end, _place)) => todo!(),
Instruction::StoreRecord(_) => todo!(),
Instruction::StoreBuiltinScalar((_dest, _imm, _src)) => todo!(),
Instruction::StoreBuiltinArray((_dest, _src, _start, _end)) => todo!(),
Instruction::IntrinsicCall((_dest, _start, _end, _fun)) => todo!(),
Instruction::OutputCall((start, end, fun, redir)) => {
self.intrinsic_print(start, end, fun, redir);
Instruction::StoreA {
dest: _,
ty_place: _,
start: _,
end: _,
var: _,
arg: _,
} => todo!(),
Instruction::IntrinsicCall { dest: _, start: _, end: _, name: _ } => todo!(),
Instruction::OutputCall { start, end, cmd, redir } => {
self.intrinsic_print(start, end, cmd, redir);
}
Instruction::UserCall((_dest, _start, _end, _fun)) => todo!(),
Instruction::IndirectCall((_dest, _start, _end, _fun)) => todo!(),
Instruction::Jump(Label(label)) => {
Instruction::UserCall { dest: _, start: _, end: _, name: _ } => todo!(),
Instruction::IndirectCall { dest: _, start: _, end: _, name: _, ty: _ } => todo!(),
Instruction::Jump { to: Label(label) } => {
self.program_counter = label as _;
continue;
}
Instruction::Return(_src) => todo!(),
Instruction::Branch((src, Label(true_to), Label(false_to))) => {
rx!(self, src);
if src.to_bool() {
self.program_counter = true_to as _;
Instruction::Return { arg: _, ty: _ } => todo!(),
Instruction::Branch { then_label, else_label, condition } => {
if self.registers.get(condition).to_bool() {
self.program_counter = then_label.0 as _;
} else {
self.program_counter = false_to as _;
self.program_counter = else_label.0 as _;
}
continue;
}
Expand Down
92 changes: 86 additions & 6 deletions lexer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ use thiserror::Error;
pub type Lexer<'a> = logos::Lexer<'a, Token<'a>>;
pub type Result<T, E = LexingError> = std::result::Result<T, E>;

// TODO: check wnat GNU does about potentially reserved `@ident`; add error branch if so.
#[derive(Logos, Debug, PartialEq)]
#[logos(utf8 = false)]
#[logos(skip(r"(?&ignore)"))]
Expand All @@ -34,8 +33,10 @@ pub type Result<T, E = LexingError> = std::result::Result<T, E>;
#[logos(subpattern ignore_with_nl = r"(?:(?&ignore)|\n)*")]
#[logos(error(LexingError, callback = |lex| LexingError::unexpected(lex)))]
pub enum Token<'a> {
#[regex("(-128|(-)?(12[0-7]|1[01][0-9]|[1-9]?[0-9]))", parse_i8, priority = 9)]
SmallInt(i8),
#[regex(r"(-)?\d+", parse_num, priority = 9)]
Numeric,
// Not emitted by Logos directly.
Integer(i32),
#[regex(r"(-)?[0-9]+(\.[0-9]*)?([eE][+-]?[0-9]+)?", parse_float, priority = 8)]
#[regex(r"\.[0-9]+([eE][+-]?[0-9]+)?", parse_float)]
Number(f64),
Expand Down Expand Up @@ -100,6 +101,82 @@ pub enum Token<'a> {
#[token("function", accept_expression)]
#[token("func", |lex| parse_non_posix_keyword(lex, Token::Function))]
Function,
#[token("length", accept_expression)]
Length,
#[token("substr", accept_expression)]
Substr,
#[token("split", accept_expression)]
Split,
#[token("sub", accept_expression)]
Sub,
#[token("gsub", accept_expression)]
Gsub,
#[token("match", accept_expression)]
MatchFn,
#[token("index", accept_expression)]
Index,
#[token("sprintf", accept_expression)]
Sprintf,
#[token("toupper", accept_expression)]
Toupper,
#[token("tolower", accept_expression)]
Tolower,
#[token("gensub", |lex| parse_non_posix_keyword(lex, Token::Gensub))]
Gensub,
#[token("patsplit", |lex| parse_non_posix_keyword(lex, Token::Patsplit))]
Patsplit,
#[token("strtonum", |lex| parse_non_posix_keyword(lex, Token::Strtonum))]
Strtonum,
#[token("close", accept_expression)]
Close,
#[token("fflush", accept_expression)]
Fflush,
#[token("system", accept_expression)]
System,
#[token("int", accept_expression)]
Int,
#[token("sqrt", accept_expression)]
Sqrt,
#[token("exp", accept_expression)]
Exp,
#[token("log", accept_expression)]
Log,
#[token("sin", accept_expression)]
Sin,
#[token("cos", accept_expression)]
Cos,
#[token("atan2", accept_expression)]
Atan2,
#[token("rand", accept_expression)]
Rand,
#[token("srand", accept_expression)]
Srand,
#[token("systime", |lex| parse_non_posix_keyword(lex, Token::Systime))]
Systime,
#[token("mktime", |lex| parse_non_posix_keyword(lex, Token::Mktime))]
Mktime,
#[token("strftime", |lex| parse_non_posix_keyword(lex, Token::Strftime))]
Strftime,
#[token("typeof", |lex| parse_non_posix_keyword(lex, Token::Typeof))]
Typeof,
#[token("isarray", |lex| parse_non_posix_keyword(lex, Token::Isarray))]
Isarray,
#[token("asort", |lex| parse_non_posix_keyword(lex, Token::Asort))]
Asort,
#[token("asorti", |lex| parse_non_posix_keyword(lex, Token::Asorti))]
Asorti,
#[token("and", |lex| parse_non_posix_keyword(lex, Token::And))]
And,
#[token("or", |lex| parse_non_posix_keyword(lex, Token::Or))]
Or,
#[token("xor", |lex| parse_non_posix_keyword(lex, Token::Xor))]
Xor,
#[token("compl", |lex| parse_non_posix_keyword(lex, Token::Compl))]
Compl,
#[token("lshift", |lex| parse_non_posix_keyword(lex, Token::Lshift))]
Lshift,
#[token("rshift", |lex| parse_non_posix_keyword(lex, Token::Rshift))]
Rshift,
#[token("NR", accept_expression)]
NrVariable,
#[token("NF", accept_expression)]
Expand Down Expand Up @@ -484,9 +561,12 @@ fn parse_float(lex: &mut Lexer<'_>) -> f64 {
parse_ident(lex, ..).parse().unwrap_or(0.)
}

fn parse_i8(lex: &mut Lexer<'_>) -> i8 {
// SAFETY: The regex matchin ensures it is well-formed and in [-128, 127].
unsafe { parse_ident(lex, ..).parse().unwrap_unchecked() }
fn parse_num<'a>(lex: &mut Lexer<'a>) -> Token<'a> {
if let Ok(num) = parse_ident(lex, ..).parse() {
Token::Integer(num)
} else {
Token::Number(parse_float(lex))
}
}

fn parse_non_posix_keyword<'a>(lex: &mut Lexer<'a>, other: Token<'a>) -> Token<'a> {
Expand Down
Loading
Loading