rustfmt fixes

This commit is contained in:
trimill 2024-11-04 13:31:53 -05:00
parent ba7db1e91b
commit 151c6abf45
12 changed files with 103 additions and 51 deletions

View file

@ -2,6 +2,7 @@ unstable_features = true
hard_tabs = true hard_tabs = true
tab_spaces = 4 tab_spaces = 4
max_width = 92
trailing_semicolon = false trailing_semicolon = false
trailing_comma = "Vertical" trailing_comma = "Vertical"

View file

@ -1,6 +1,8 @@
use clap::{ColorChoice, Parser}; use clap::{ColorChoice, Parser};
use std::{path::PathBuf, process::ExitCode, rc::Rc}; use std::{path::PathBuf, process::ExitCode, rc::Rc};
use talc_lang::{compiler::compile, parser, symbol::Symbol, value::function::disasm_recursive, Vm}; use talc_lang::{
compiler::compile, parser, symbol::Symbol, value::function::disasm_recursive, Vm,
};
mod helper; mod helper;
mod repl; mod repl;

View file

@ -110,12 +110,12 @@ pub enum Instruction {
LoadGlobal(Arg24), // load global by id LoadGlobal(Arg24), // load global by id
StoreGlobal(Arg24), // store global by id StoreGlobal(Arg24), // store global by id
CloseOver(Arg24), // load nth local and convert to cell, write back a copy CloseOver(Arg24), // load nth local and convert to cell, write back a copy
Closure(Arg24), // load constant function and fill state from stack Closure(Arg24), // load constant function and fill state from stack
LoadUpvalue(Arg24), // load LoadUpvalue(Arg24), // load
StoreUpvalue(Arg24), // store a cell from closure state to new local StoreUpvalue(Arg24), // store a cell from closure state to new local
ContinueUpvalue(Arg24), // ContinueUpvalue(Arg24), //
LoadClosedLocal(Arg24), // load through cell in nth local LoadClosedLocal(Arg24), // load through cell in nth local
StoreClosedLocal(Arg24), // store through cell in nth local StoreClosedLocal(Arg24), // store through cell in nth local
Const(Arg24), // push nth constant Const(Arg24), // push nth constant

View file

@ -7,8 +7,8 @@ use crate::{
use super::{ use super::{
ast::{BinaryOp, CatchBlock, Expr, ExprKind, LValue, UnaryOp}, ast::{BinaryOp, CatchBlock, Expr, ExprKind, LValue, UnaryOp},
parse_float, parse_int_literal, parse_str_escapes, Lexer, ParserError, Span, SpanParserError, parse_float, parse_int_literal, parse_str_escapes, Lexer, ParserError, Span,
Token, TokenKind, SpanParserError, Token, TokenKind,
}; };
use num_complex::Complex64; use num_complex::Complex64;
use ExprKind as E; use ExprKind as E;
@ -159,27 +159,24 @@ fn b<T>(t: T) -> Box<T> {
impl TokenKind { impl TokenKind {
fn expr_first(self) -> bool { fn expr_first(self) -> bool {
matches!(self, |T::Return| T::Var matches!(
| T::Global self,
| T::Fn | T::Not T::Return
| T::Backslash | T::Var | T::Global
| T::Colon | T::Fn | T::Not
| T::Minus | T::Backslash
| T::Identifier | T::Colon | T::Minus
| T::LParen | T::Identifier
| T::LBrack | T::LParen | T::LBrack
| T::LBrace | T::LBrace | T::Dollar
| T::Dollar | T::Do | T::If
| T::Do | T::If | T::While | T::For
| T::While | T::Try | T::Integer
| T::For | T::Try | T::Float | T::Imaginary
| T::Integer | T::String | T::Symbol
| T::Float | T::True | T::False
| T::Imaginary | T::Nil
| T::String )
| T::Symbol
| T::True | T::False
| T::Nil)
} }
} }
@ -371,7 +368,8 @@ impl<'s> Parser<'s> {
Ok(E::Literal(x.into()).span(tok.span)) Ok(E::Literal(x.into()).span(tok.span))
} }
T::Imaginary => { T::Imaginary => {
let x = parse_float(&tok.content[..tok.content.len() - 1]).span_err(tok.span)?; let x = parse_float(&tok.content[..tok.content.len() - 1])
.span_err(tok.span)?;
Ok(E::Literal(Complex64::new(0.0, x).into()).span(tok.span)) Ok(E::Literal(Complex64::new(0.0, x).into()).span(tok.span))
} }
T::String => { T::String => {
@ -388,7 +386,8 @@ impl<'s> Parser<'s> {
let s = match inner.chars().next() { let s = match inner.chars().next() {
Some('\'') => Symbol::get(&inner[1..inner.len() - 1]), Some('\'') => Symbol::get(&inner[1..inner.len() - 1]),
Some('\"') => Symbol::get( Some('\"') => Symbol::get(
&parse_str_escapes(&inner[1..inner.len() - 1]).span_err(tok.span)?, &parse_str_escapes(&inner[1..inner.len() - 1])
.span_err(tok.span)?,
), ),
_ => Symbol::get(inner), _ => Symbol::get(inner),
}; };

View file

@ -67,7 +67,10 @@ impl std::fmt::Debug for NativeFunc {
} }
} }
pub fn disasm_recursive(f: &Rc<Function>, w: &mut impl std::io::Write) -> std::io::Result<()> { pub fn disasm_recursive(
f: &Rc<Function>,
w: &mut impl std::io::Write,
) -> std::io::Result<()> {
writeln!(w, "{} ({})", Value::Function(f.clone()), f.attrs.arity)?; writeln!(w, "{} ({})", Value::Function(f.clone()), f.attrs.arity)?;
if !f.chunk.consts.is_empty() { if !f.chunk.consts.is_empty() {
writeln!(w, "constants")?; writeln!(w, "constants")?;

View file

@ -10,7 +10,9 @@ use crate::{
exception::{throw, Exception, Result}, exception::{throw, Exception, Result},
lstring::LStr, lstring::LStr,
parser::ast::{BinaryOp, UnaryOp}, parser::ast::{BinaryOp, UnaryOp},
symbol::{Symbol, SYM_CALL_STACK_OVERFLOW, SYM_INTERRUPTED, SYM_NAME_ERROR, SYM_TYPE_ERROR}, symbol::{
Symbol, SYM_CALL_STACK_OVERFLOW, SYM_INTERRUPTED, SYM_NAME_ERROR, SYM_TYPE_ERROR,
},
value::{ value::{
function::{FuncAttrs, Function, NativeFunc}, function::{FuncAttrs, Function, NativeFunc},
Value, Value,
@ -198,7 +200,9 @@ impl Vm {
while let Some(try_frame) = frame.try_frames.pop() { while let Some(try_frame) = frame.try_frames.pop() {
let table = &frame.func.chunk.try_tables[try_frame.idx]; let table = &frame.func.chunk.try_tables[try_frame.idx];
for catch in &table.catches { for catch in &table.catches {
if catch.types.is_none() || catch.types.as_ref().unwrap().contains(&exc.ty) { if catch.types.is_none()
|| catch.types.as_ref().unwrap().contains(&exc.ty)
{
frame.ip = catch.addr; frame.ip = catch.addr;
frame.locals.truncate(table.local_count); frame.locals.truncate(table.local_count);
self.stack.truncate(try_frame.stack_len); self.stack.truncate(try_frame.stack_len);
@ -241,7 +245,11 @@ impl Vm {
Ok(()) Ok(())
} }
fn run_instr(&mut self, frame: &mut CallFrame, instr: Instruction) -> Result<Option<Value>> { fn run_instr(
&mut self,
frame: &mut CallFrame,
instr: Instruction,
) -> Result<Option<Value>> {
use Instruction as I; use Instruction as I;
match instr { match instr {

View file

@ -149,7 +149,8 @@ fn insertion_by(vals: &mut [Value], by: &Value, vm: &mut Vm) -> Result<()> {
for i in 0..vals.len() { for i in 0..vals.len() {
let mut j = i; let mut j = i;
while j > 0 { while j > 0 {
let ord = call_comparison(vm, by.clone(), vals[j - 1].clone(), vals[j].clone())?; let ord =
call_comparison(vm, by.clone(), vals[j - 1].clone(), vals[j].clone())?;
if ord <= 0 { if ord <= 0 {
break break
} }

View file

@ -15,12 +15,18 @@ pub fn throw(_: &mut Vm, args: Vec<Value>) -> Result<Value> {
Value::Symbol(ty) => Exception::new(ty), Value::Symbol(ty) => Exception::new(ty),
Value::List(l) => match l.borrow().as_slice() { Value::List(l) => match l.borrow().as_slice() {
[Value::Symbol(ty)] | [Value::Symbol(ty), Value::Nil] => Exception::new(*ty), [Value::Symbol(ty)] | [Value::Symbol(ty), Value::Nil] => Exception::new(*ty),
[Value::Symbol(ty), Value::Nil, data] => Exception::new_with_data(*ty, data.clone()), [Value::Symbol(ty), Value::Nil, data] => {
[Value::Symbol(ty), Value::String(s)] => Exception::new_with_msg(*ty, s.clone()), Exception::new_with_data(*ty, data.clone())
}
[Value::Symbol(ty), Value::String(s)] => {
Exception::new_with_msg(*ty, s.clone())
}
[Value::Symbol(ty), Value::String(s), data] => { [Value::Symbol(ty), Value::String(s), data] => {
Exception::new_with_msg_data(*ty, s.clone(), data.clone()) Exception::new_with_msg_data(*ty, s.clone(), data.clone())
} }
[] | [_] | [_, _] | [_, _, _] => throw!(*SYM_TYPE_ERROR, "wrong argument for throw"), [] | [_] | [_, _] | [_, _, _] => {
throw!(*SYM_TYPE_ERROR, "wrong argument for throw")
}
[_, _, _, _, ..] => throw!( [_, _, _, _, ..] => throw!(
*SYM_VALUE_ERROR, *SYM_VALUE_ERROR,
"too many elements in list argument for throw" "too many elements in list argument for throw"

View file

@ -115,7 +115,9 @@ impl BufFile {
} }
} }
fn try_into_raw_fd(self) -> std::result::Result<RawFd, IntoInnerError<BufWriter<File>>> { fn try_into_raw_fd(
self,
) -> std::result::Result<RawFd, IntoInnerError<BufWriter<File>>> {
match self { match self {
BufFile::Buffered { r, w } => { BufFile::Buffered { r, w } => {
let _ = w.into_inner()?.into_raw_fd(); let _ = w.into_inner()?.into_raw_fd();

View file

@ -203,7 +203,11 @@ impl<'p> FmtParser<'p> {
} }
} }
fn get_arg<'a>(args: &'a [Value], n: Option<usize>, faidx: &mut usize) -> Result<&'a Value> { fn get_arg<'a>(
args: &'a [Value],
n: Option<usize>,
faidx: &mut usize,
) -> Result<&'a Value> {
let i = match n { let i = match n {
Some(n) => n, Some(n) => n,
None => { None => {
@ -255,7 +259,9 @@ fn format_float(
(None, FmtType::Repr) => write!(buf, "{:#}", Value::Float(f)), (None, FmtType::Repr) => write!(buf, "{:#}", Value::Float(f)),
(None, FmtType::Exp(true)) => write!(buf, "{:E}", f), (None, FmtType::Exp(true)) => write!(buf, "{:E}", f),
(None, FmtType::Exp(false)) => write!(buf, "{:e}", f), (None, FmtType::Exp(false)) => write!(buf, "{:e}", f),
(Some(p), FmtType::Str) | (Some(p), FmtType::Repr) => write!(buf, "{0:.1$}", f, p), (Some(p), FmtType::Str) | (Some(p), FmtType::Repr) => {
write!(buf, "{0:.1$}", f, p)
}
(Some(p), FmtType::Exp(true)) => write!(buf, "{0:.1$E}", f, p), (Some(p), FmtType::Exp(true)) => write!(buf, "{0:.1$E}", f, p),
(Some(p), FmtType::Exp(false)) => write!(buf, "{0:.1$e}", f, p), (Some(p), FmtType::Exp(false)) => write!(buf, "{0:.1$e}", f, p),
_ => throw!(*SYM_FORMAT_ERROR, "invalid format specifier for {ty_name}"), _ => throw!(*SYM_FORMAT_ERROR, "invalid format specifier for {ty_name}"),
@ -301,14 +307,24 @@ fn format_int(
res.map_err(|e| exception!(*SYM_FORMAT_ERROR, "{e}")) res.map_err(|e| exception!(*SYM_FORMAT_ERROR, "{e}"))
} }
fn format_ratio(n: Rational64, prec: Option<usize>, ty: FmtType, buf: &mut LString) -> Result<()> { fn format_ratio(
n: Rational64,
prec: Option<usize>,
ty: FmtType,
buf: &mut LString,
) -> Result<()> {
format_int(*n.numer(), prec, ty, buf, "ratio")?; format_int(*n.numer(), prec, ty, buf, "ratio")?;
buf.push_char('/'); buf.push_char('/');
format_int(*n.denom(), prec, ty, buf, "ratio")?; format_int(*n.denom(), prec, ty, buf, "ratio")?;
Ok(()) Ok(())
} }
fn format_value(v: &Value, prec: Option<usize>, ty: FmtType, buf: &mut LString) -> Result<()> { fn format_value(
v: &Value,
prec: Option<usize>,
ty: FmtType,
buf: &mut LString,
) -> Result<()> {
if prec.is_some() { if prec.is_some() {
throw!(*SYM_FORMAT_ERROR, "invalid format specifier for value") throw!(*SYM_FORMAT_ERROR, "invalid format specifier for value")
} }
@ -320,7 +336,12 @@ fn format_value(v: &Value, prec: Option<usize>, ty: FmtType, buf: &mut LString)
res.map_err(|e| exception!(*SYM_FORMAT_ERROR, "{e}")) res.map_err(|e| exception!(*SYM_FORMAT_ERROR, "{e}"))
} }
fn format_string(mut s: &LStr, prec: Option<usize>, ty: FmtType, buf: &mut LString) -> Result<()> { fn format_string(
mut s: &LStr,
prec: Option<usize>,
ty: FmtType,
buf: &mut LString,
) -> Result<()> {
if let Some(prec) = prec { if let Some(prec) = prec {
s = &s[..prec] s = &s[..prec]
} }
@ -341,7 +362,12 @@ fn pad_str(n: usize, c: char, buf: &mut LString) {
} }
} }
fn format_arg(args: &[Value], faidx: &mut usize, code: &LStr, res: &mut LString) -> Result<()> { fn format_arg(
args: &[Value],
faidx: &mut usize,
code: &LStr,
res: &mut LString,
) -> Result<()> {
if !code.is_utf8() { if !code.is_utf8() {
throw!( throw!(
*SYM_FORMAT_ERROR, *SYM_FORMAT_ERROR,

View file

@ -46,8 +46,12 @@ pub fn rand_in(vm: &mut Vm, args: Vec<Value>) -> Result<Value> {
throw!(*SYM_VALUE_ERROR, "rand_in: empty range") throw!(*SYM_VALUE_ERROR, "rand_in: empty range")
} }
match r.ty { match r.ty {
RangeType::Open => Ok(Value::Int(rand::thread_rng().gen_range(r.start..r.stop))), RangeType::Open => {
RangeType::Closed => Ok(Value::Int(rand::thread_rng().gen_range(r.start..=r.stop))), Ok(Value::Int(rand::thread_rng().gen_range(r.start..r.stop)))
}
RangeType::Closed => {
Ok(Value::Int(rand::thread_rng().gen_range(r.start..=r.stop)))
}
RangeType::Endless => throw!(*SYM_VALUE_ERROR, "rand_in: endless range"), RangeType::Endless => throw!(*SYM_VALUE_ERROR, "rand_in: endless range"),
} }
} }

View file

@ -323,8 +323,8 @@ pub fn compile(_: &mut Vm, args: Vec<Value>) -> Result<Value> {
"compile: argument must be valid unicode ({e})" "compile: argument must be valid unicode ({e})"
) )
})?; })?;
let ast = let ast = talc_lang::parser::parse(src)
talc_lang::parser::parse(src).map_err(|e| exception!(symbol!("parse_error"), "{e}"))?; .map_err(|e| exception!(symbol!("parse_error"), "{e}"))?;
let func = talc_lang::compiler::compile(&ast, None); let func = talc_lang::compiler::compile(&ast, None);
Ok(func.into()) Ok(func.into())
} }