This commit is contained in:
2024-10-06 12:42:46 -04:00
parent 148ad00c83
commit e5aea8b24e
26 changed files with 1338 additions and 613 deletions
+106
View File
@@ -0,0 +1,106 @@
use std::fmt::{Debug, Write};
use super::token::{Keyword, Symbol, Token};
use crate::util::Padder;
use super::{Expr, ParserError, TokenCursor};
pub struct Body {
statements: Vec<Statement>,
}
pub enum Statement {
Let(String, Expr),
Return(Expr),
Expr(Expr),
}
impl Body {
pub fn parse(cursor: &mut TokenCursor) -> Result<Self, ParserError> {
let mut statements = Vec::new();
cursor.expect_sym(Symbol::OpenCurly)?;
loop {
let next = cursor.expect_peek()?;
if next.is_symbol(Symbol::CloseCurly) {
cursor.next();
return Ok(Self { statements });
}
statements.push(Statement::parse(cursor)?);
}
}
}
impl Statement {
pub fn parse(cursor: &mut TokenCursor) -> Result<Self, ParserError> {
let next = cursor.expect_peek()?;
Ok(match next.token {
Token::Keyword(Keyword::Let) => {
cursor.next();
let name = cursor.expect_ident()?;
cursor.expect_sym(Symbol::Equals)?;
let expr = Expr::parse(cursor)?;
cursor.expect_sym(Symbol::Semicolon)?;
Self::Let(name, expr)
}
Token::Keyword(Keyword::Return) => {
cursor.next();
let expr = Expr::parse(cursor)?;
cursor.expect_sym(Symbol::Semicolon)?;
Self::Return(expr)
}
_ => {
let expr = Expr::parse(cursor)?;
let next = cursor.expect_peek()?;
if next.is_symbol(Symbol::Semicolon) {
cursor.next();
Self::Expr(expr)
} else if next.is_symbol(Symbol::CloseCurly) {
Self::Return(expr)
} else {
return Err(ParserError::unexpected_token(next, "a ';' or '}'"));
}
}
})
}
}
impl Debug for Statement {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Statement::Let(n, e) => {
f.write_str("let ")?;
f.write_str(n)?;
f.write_str(" = ")?;
e.fmt(f)?;
f.write_char(';')?;
}
Statement::Return(e) => {
f.write_str("return ")?;
e.fmt(f)?;
f.write_char(';')?;
}
Statement::Expr(e) => {
e.fmt(f)?;
f.write_char(';')?;
}
}
Ok(())
}
}
impl Debug for Body {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.statements.first().is_some() {
f.write_str("{\n ")?;
let mut padder = Padder::new(f);
for s in &self.statements {
// they don't expose wrap_buf :grief:
padder.write_str(&format!("{s:?}\n"))?;
}
f.write_char('}')?;
} else {
f.write_str("{}")?;
}
Ok(())
}
}
+61
View File
@@ -0,0 +1,61 @@
use std::ops::{Deref, DerefMut};
use super::error::ParserError;
use super::token::{CharCursor, Keyword, Symbol, Token, TokenInstance};
pub struct TokenCursor<'a> {
cursor: CharCursor<'a>,
next: Option<TokenInstance>,
}
impl<'a> TokenCursor<'a> {
pub fn next(&mut self) -> Option<TokenInstance> {
std::mem::replace(&mut self.next, TokenInstance::parse(&mut self.cursor))
}
pub fn expect_next(&mut self) -> Result<TokenInstance, ParserError> {
self.next().ok_or(ParserError::unexpected_end())
}
pub fn expect_token(&mut self, t: Token) -> Result<(), ParserError> {
let next = self.expect_next()?;
if t == next.token {
Ok(())
} else {
Err(ParserError::unexpected_token(&next, &format!("{t:?}")))
}
}
pub fn expect_sym(&mut self, symbol: Symbol) -> Result<(), ParserError> {
self.expect_token(Token::Symbol(symbol))
}
pub fn expect_kw(&mut self, kw: Keyword) -> Result<(), ParserError> {
self.expect_token(Token::Keyword(kw))
}
pub fn peek(&self) -> Option<&TokenInstance> {
self.next.as_ref()
}
pub fn expect_peek(&mut self) -> Result<&TokenInstance, ParserError> {
self.peek().ok_or(ParserError::unexpected_end())
}
pub fn expect_ident(&mut self) -> Result<String, ParserError> {
let i = self.expect_next()?;
let Token::Ident(n) = &i.token else {
return Err(ParserError::unexpected_token(&i, "an identifier"));
};
Ok(n.to_string())
}
pub fn chars(&mut self) -> &mut CharCursor<'a> {
&mut self.cursor
}
}
impl<'a> From<&'a str> for TokenCursor<'a> {
fn from(string: &'a str) -> Self {
Self::from(CharCursor::from(string))
}
}
impl<'a> From<CharCursor<'a>> for TokenCursor<'a> {
fn from(mut cursor: CharCursor<'a>) -> Self {
let cur = TokenInstance::parse(&mut cursor);
Self { cursor, next: cur }
}
}
+50
View File
@@ -0,0 +1,50 @@
use super::{token::{FileRegion, TokenInstance}, FilePos};
#[derive(Debug)]
pub struct ParserError {
pub msg: String,
pub regions: Vec<FileRegion>,
}
impl ParserError {
pub fn from_instances(instances: &[&TokenInstance], msg: String) -> Self {
ParserError {
msg,
regions: instances.iter().map(|i| i.region).collect(),
}
}
pub fn from_msg(msg: String) -> Self {
Self {
msg,
regions: Vec::new(),
}
}
pub fn at(pos: FilePos, msg: String) -> Self {
Self {
msg,
regions: vec![FileRegion {
start: pos,
end: pos,
}],
}
}
pub fn unexpected_end() -> Self {
Self::from_msg("unexpected end of input".to_string())
}
pub fn unexpected_token(inst: &TokenInstance, expected: &str) -> Self {
let t = &inst.token;
ParserError::from_instances(
&[inst],
format!("Unexpected token {t:?}; expected {expected}"),
)
}
pub fn write_for(&self, writer: &mut impl std::io::Write, file: &str) -> std::io::Result<()> {
let after = if self.regions.is_empty() { "" } else { ":" };
writeln!(writer, "error: {}{}", self.msg, after)?;
for reg in &self.regions {
reg.write_for(writer, file)?;
}
Ok(())
}
}
+168
View File
@@ -0,0 +1,168 @@
use std::fmt::{Debug, Write};
use super::token::{Symbol, Token};
use super::{Body, Number, ParserError, TokenCursor, Val};
pub enum Expr {
Val(Val),
Ident(String),
BinaryOp(Operator, Box<Expr>, Box<Expr>),
Block(Body),
Call(Box<Expr>, Vec<Expr>),
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Operator {
Add,
Sub,
Mul,
Div,
LessThan,
GreaterThan,
Access,
}
impl Expr {
pub fn parse(cursor: &mut TokenCursor) -> Result<Self, ParserError> {
let Some(next) = cursor.peek() else {
return Ok(Expr::Val(Val::Unit));
};
let mut e1 = if next.is_symbol(Symbol::OpenParen) {
cursor.next();
let expr = Self::parse(cursor)?;
cursor.expect_sym(Symbol::CloseParen)?;
expr
} else if next.is_symbol(Symbol::OpenCurly) {
let expr = Body::parse(cursor)?;
Expr::Block(expr)
} else {
Self::parse_unit(cursor)?
};
let Some(mut next) = cursor.peek() else {
return Ok(e1);
};
while next.is_symbol(Symbol::OpenParen) {
cursor.next();
let inner = Self::parse(cursor)?;
cursor.expect_sym(Symbol::CloseParen)?;
e1 = Self::Call(Box::new(e1), vec![inner]);
let Some(next2) = cursor.peek() else {
return Ok(e1);
};
next = next2
}
Ok(if let Some(op) = Operator::from_token(&next.token) {
cursor.next();
let e2 = Self::parse(cursor)?;
if let Self::BinaryOp(op_next, e3, e4) = e2 {
if op.presedence() > op_next.presedence() {
Self::BinaryOp(op_next, Box::new(Self::BinaryOp(op, Box::new(e1), e3)), e4)
} else {
Self::BinaryOp(op, Box::new(e1), Box::new(Self::BinaryOp(op_next, e3, e4)))
}
} else {
Self::BinaryOp(op, Box::new(e1), Box::new(e2))
}
} else {
e1
})
}
fn parse_unit(cursor: &mut TokenCursor) -> Result<Self, ParserError> {
if let Some(val) = Val::parse(cursor)? {
return Ok(Self::Val(val));
}
let inst = cursor.expect_next()?;
match &inst.token {
Token::Ident(name) => Ok(Self::Ident(name.to_string())),
_ => Err(ParserError::unexpected_token(
&inst,
"an identifier or value",
)),
}
}
}
impl Operator {
pub fn presedence(&self) -> u32 {
match self {
Operator::LessThan => 0,
Operator::GreaterThan => 0,
Operator::Add => 1,
Operator::Sub => 2,
Operator::Mul => 3,
Operator::Div => 4,
Operator::Access => 5,
}
}
pub fn str(&self) -> &str {
match self {
Self::Add => "+",
Self::Sub => "-",
Self::Mul => "*",
Self::Div => "/",
Self::LessThan => "<",
Self::GreaterThan => ">",
Self::Access => ".",
}
}
pub fn from_token(token: &Token) -> Option<Self> {
let Token::Symbol(symbol) = token else {
return None;
};
Some(match symbol {
Symbol::OpenAngle => Operator::LessThan,
Symbol::CloseAngle => Operator::GreaterThan,
Symbol::Plus => Operator::Add,
Symbol::Minus => Operator::Sub,
Symbol::Asterisk => Operator::Mul,
Symbol::Slash => Operator::Div,
Symbol::Dot => Operator::Access,
_ => {
return None;
}
})
}
pub fn pad(&self) -> bool {
match self {
Operator::Add => true,
Operator::Sub => true,
Operator::Mul => true,
Operator::Div => true,
Operator::LessThan => true,
Operator::GreaterThan => true,
Operator::Access => false,
}
}
}
impl Debug for Expr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Expr::Val(c) => c.fmt(f)?,
Expr::Ident(n) => f.write_str(n)?,
Expr::Block(b) => b.fmt(f)?,
Expr::BinaryOp(op, e1, e2) => {
write!(f, "({:?}", *e1)?;
if op.pad() {
write!(f, " {} ", op.str())?;
} else {
write!(f, "{}", op.str())?;
}
write!(f, "{:?})", *e2)?;
}
Expr::Call(n, args) => {
n.fmt(f)?;
f.write_char('(')?;
if let Some(a) = args.first() {
a.fmt(f)?;
}
for arg in args.iter().skip(1) {
f.write_str(", ")?;
arg.fmt(f)?;
}
f.write_char(')')?;
}
}
Ok(())
}
}
+63
View File
@@ -0,0 +1,63 @@
use std::fmt::Debug;
mod body;
mod cursor;
mod error;
mod expr;
mod token;
mod val;
pub use body::*;
pub use cursor::*;
pub use error::*;
pub use expr::*;
pub use val::*;
use token::*;
#[derive(Debug)]
pub struct Module {
functions: Vec<Function>,
}
pub struct Function {
pub name: String,
pub body: Body,
}
impl Module {
pub fn parse(cursor: &mut TokenCursor) -> Result<Self, ParserError> {
let mut functions = Vec::new();
loop {
let Some(next) = cursor.peek() else {
return Ok(Self { functions });
};
if next.is_keyword(Keyword::Fn) {
functions.push(Function::parse(cursor)?);
} else {
return Err(ParserError::unexpected_token(next, "fn"));
}
}
}
}
impl Function {
pub fn parse(cursor: &mut TokenCursor) -> Result<Self, ParserError> {
cursor.expect_kw(Keyword::Fn)?;
let name = cursor.expect_ident()?;
cursor.expect_sym(Symbol::OpenParen)?;
cursor.expect_sym(Symbol::CloseParen)?;
let body = Body::parse(cursor)?;
Ok(Self { name, body })
}
}
impl Debug for Function {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("fn ")?;
f.write_str(&self.name)?;
f.write_str("() ")?;
self.body.fmt(f)?;
Ok(())
}
}
+79
View File
@@ -0,0 +1,79 @@
use std::{iter::Peekable, str::Chars};
use crate::v1::parser::ParserError;
use super::FilePos;
pub struct CharCursor<'a> {
chars: Peekable<Chars<'a>>,
pos: FilePos,
prev_pos: FilePos,
}
impl CharCursor<'_> {
pub fn next(&mut self) -> Option<char> {
let res = self.peek()?;
self.advance();
Some(res)
}
pub fn expect(&mut self, c: char) -> Result<(), ParserError> {
let next = self.expect_next()?;
if next == c {
Ok(())
} else {
Err(ParserError::at(
self.prev_pos,
format!("unexpected char '{next}'; expected '{c}'"),
))
}
}
pub fn skip_whitespace(&mut self) {
while self.peek().is_some_and(|c| c.is_whitespace()) {
self.advance();
}
}
pub fn peek(&mut self) -> Option<char> {
self.chars.peek().copied()
}
pub fn advance(&mut self) {
let Some(next) = self.chars.next() else {
return;
};
self.prev_pos = self.pos;
if next == '\n' {
self.pos.col = 0;
self.pos.line += 1;
} else {
self.pos.col += 1;
}
}
pub fn advance_if(&mut self, c: char) -> bool {
if let Some(c2) = self.peek() {
if c2 == c {
self.advance();
return true;
}
}
false
}
pub fn expect_next(&mut self) -> Result<char, ParserError> {
self.next()
.ok_or(ParserError::from_msg("Unexpected end of input".to_string()))
}
pub fn pos(&self) -> FilePos {
self.pos
}
pub fn prev_pos(&self) -> FilePos {
self.prev_pos
}
}
impl<'a> From<&'a str> for CharCursor<'a> {
fn from(value: &'a str) -> Self {
Self {
chars: value.chars().peekable(),
pos: FilePos::start(),
prev_pos: FilePos::start(),
}
}
}
+65
View File
@@ -0,0 +1,65 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FilePos {
pub line: usize,
pub col: usize,
}
#[derive(Debug, Clone, Copy)]
pub struct FileRegion {
pub start: FilePos,
pub end: FilePos,
}
impl FilePos {
pub fn start() -> Self {
Self { line: 0, col: 0 }
}
}
const BEFORE: usize = 1;
const AFTER: usize = 1;
impl FileRegion {
pub fn write_for(&self, writer: &mut impl std::io::Write, file: &str) -> std::io::Result<()> {
let start = self.start.line.saturating_sub(BEFORE);
let num_before = self.start.line - start;
let mut lines = file.lines().skip(start);
let width = format!("{}", self.end.line + AFTER).len();
let same_line = self.start.line == self.end.line;
for i in 0..num_before {
writeln!(writer, "{:>width$} | {}", start + i, lines.next().unwrap())?;
}
let line = lines.next().unwrap();
writeln!(writer, "{:>width$} | {}", self.start.line, line)?;
let len = if same_line {
self.end.col - self.start.col + 1
} else {
line.len() - self.start.col
};
writeln!(
writer,
"{} | {}",
" ".repeat(width),
" ".repeat(self.start.col) + &"^".repeat(len)
)?;
if !same_line {
for _ in 0..self.end.line - self.start.line - 1 {
lines.next();
}
let line = lines.next().unwrap();
writeln!(writer, "{:>width$} | {}", self.end.line, line)?;
writeln!(
writer,
"{} | {}",
" ".repeat(width),
"^".repeat(self.end.col + 1)
)?;
}
for i in 0..AFTER {
if let Some(next) = lines.next() {
writeln!(writer, "{:>width$} | {}", self.end.line + i + 1, next)?;
}
}
Ok(())
}
}
+27
View File
@@ -0,0 +1,27 @@
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Keyword {
Fn,
Let,
If,
Return,
}
impl Keyword {
pub fn from_string(str: &str) -> Option<Self> {
Some(match str {
"fn" => Self::Fn,
"let" => Self::Let,
"if" => Self::If,
"return" => Self::Return,
_ => return None,
})
}
pub const fn str(&self) -> &str {
match self {
Keyword::Fn => "fn",
Keyword::Let => "let",
Keyword::If => "if",
Keyword::Return => "return",
}
}
}
+83
View File
@@ -0,0 +1,83 @@
mod cursor;
mod file;
mod keyword;
mod symbol;
pub use cursor::*;
pub use file::*;
pub use keyword::*;
pub use symbol::*;
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Token {
Symbol(Symbol),
Ident(String),
Keyword(Keyword),
}
#[derive(Debug)]
pub struct TokenInstance {
pub token: Token,
pub region: FileRegion,
}
impl TokenInstance {
pub fn parse(cursor: &mut CharCursor) -> Option<TokenInstance> {
cursor.skip_whitespace();
cursor.peek()?;
let start = cursor.pos();
if let Some(s) = Symbol::parse(cursor) {
if s == Symbol::DoubleSlash {
while cursor.next() != Some('\n') {}
return Self::parse(cursor);
}
let end = cursor.prev_pos();
return Some(Self {
token: Token::Symbol(s),
region: FileRegion { start, end },
});
}
let mut word = String::new();
while let Some(c) = cursor.peek() {
if c.is_whitespace() || Symbol::from_char(c).is_some() {
break;
}
word.push(c);
cursor.advance();
}
let end = cursor.prev_pos();
let token = if let Some(keyword) = Keyword::from_string(&word) {
Token::Keyword(keyword)
} else {
Token::Ident(word)
};
Some(Self {
token,
region: FileRegion { start, end },
})
}
}
impl Token {
pub fn is_symbol(&self, symbol: Symbol) -> bool {
match self {
Token::Symbol(s) => *s == symbol,
_ => false,
}
}
pub fn is_keyword(&self, kw: Keyword) -> bool {
match self {
Token::Keyword(k) => *k == kw,
_ => false,
}
}
}
impl TokenInstance {
pub fn is_keyword(&self, kw: Keyword) -> bool {
self.token.is_keyword(kw)
}
pub fn is_symbol(&self, symbol: Symbol) -> bool {
self.token.is_symbol(symbol)
}
}
+123
View File
@@ -0,0 +1,123 @@
use std::fmt::Debug;
use super::CharCursor;
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum Symbol {
Semicolon,
Colon,
DoubleColon,
Equals,
DoubleEquals,
Arrow,
DoubleArrow,
Plus,
Minus,
Asterisk,
Slash,
DoubleSlash,
Dot,
OpenParen,
CloseParen,
OpenCurly,
CloseCurly,
OpenSquare,
CloseSquare,
OpenAngle,
CloseAngle,
SingleQuote,
DoubleQuote,
}
impl Symbol {
pub fn parse(cursor: &mut CharCursor) -> Option<Self> {
Self::from_char(cursor.peek()?).map(|mut s| {
cursor.advance();
s.finish(cursor);
s
})
}
pub fn from_char(c: char) -> Option<Self> {
Some(match c {
'(' => Self::OpenParen,
')' => Self::CloseParen,
'[' => Self::OpenSquare,
']' => Self::CloseSquare,
'{' => Self::OpenCurly,
'}' => Self::CloseCurly,
'<' => Self::OpenAngle,
'>' => Self::CloseAngle,
';' => Self::Semicolon,
':' => Self::Colon,
'+' => Self::Plus,
'-' => Self::Minus,
'*' => Self::Asterisk,
'/' => Self::Slash,
'=' => Self::Equals,
'.' => Self::Dot,
'\'' => Self::SingleQuote,
'"' => Self::DoubleQuote,
_ => return None,
})
}
pub fn finish(&mut self, cursor: &mut CharCursor) {
let Some(next) = cursor.peek() else {
return;
};
*self = match self {
Self::Colon => match next {
':' => Self::DoubleColon,
_ => return,
},
Self::Minus => match next {
'>' => Self::Arrow,
_ => return,
},
Self::Equals => match next {
'=' => Self::DoubleEquals,
'>' => Self::DoubleArrow,
_ => return,
}
Self::Slash => match next {
'/' => Self::DoubleSlash,
_ => return,
}
_ => return,
};
cursor.advance();
}
pub fn str(&self) -> &str {
match self {
Symbol::Semicolon => ";",
Symbol::Colon => ":",
Symbol::DoubleColon => "::",
Symbol::Equals => "=",
Symbol::DoubleEquals => "==",
Symbol::Arrow => "->",
Symbol::DoubleArrow => "=>",
Symbol::Plus => "+",
Symbol::Minus => "-",
Symbol::Asterisk => "*",
Symbol::Slash => "/",
Symbol::DoubleSlash => "//",
Symbol::Dot => ".",
Symbol::OpenParen => "(",
Symbol::CloseParen => ")",
Symbol::OpenCurly => "{",
Symbol::CloseCurly => "}",
Symbol::OpenSquare => "[",
Symbol::CloseSquare => "]",
Symbol::OpenAngle => "<",
Symbol::CloseAngle => ">",
Symbol::SingleQuote => "'",
Symbol::DoubleQuote => "\"",
}
}
}
impl Debug for Symbol {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "'{}'", self.str())
}
}
+110
View File
@@ -0,0 +1,110 @@
use super::{CharCursor, ParserError, Symbol, Token, TokenCursor};
use std::fmt::Debug;
#[derive(PartialEq, Eq)]
pub enum Val {
String(String),
Char(char),
Number(Number),
Unit,
}
#[derive(PartialEq, Eq)]
pub struct Number {
pub whole: String,
pub decimal: Option<String>,
pub ty: Option<String>,
}
impl Val {
pub fn parse(cursor: &mut TokenCursor) -> Result<Option<Self>, ParserError> {
let inst = cursor.expect_peek()?;
let mut res = match &inst.token {
Token::Symbol(Symbol::SingleQuote) => {
let chars = cursor.chars();
let c = chars.expect_next()?;
chars.expect('\'')?;
Self::Char(c)
}
Token::Symbol(Symbol::DoubleQuote) => Self::String(string_from(cursor.chars())?),
Token::Ident(text) => {
let first = text.chars().next().unwrap();
if first.is_ascii_digit() {
Self::Number(Number {
whole: text.to_string(),
decimal: None,
ty: None,
})
} else {
return Ok(None);
}
}
_ => return Ok(None),
};
cursor.next();
if let Some(next) = cursor.peek() {
if let Self::Number(num) = &mut res {
if let Token::Symbol(Symbol::Dot) = next.token {
let chars = cursor.chars();
if let Some(c) = chars.peek() {
if c.is_ascii_digit() {
cursor.next();
let decimal = cursor.expect_ident()?;
num.decimal = Some(decimal);
}
}
}
}
}
Ok(Some(res))
}
}
pub fn string_from(cursor: &mut CharCursor) -> Result<String, ParserError> {
let mut str = String::new();
loop {
let c = cursor.expect_next()?;
if c == '"' {
return Ok(str);
}
str.push(match c {
'\\' => {
let next = cursor.expect_next()?;
match next {
'"' => '"',
'\'' => '\'',
't' => '\t',
'n' => '\n',
'0' => '\0',
_ => {
todo!();
}
}
}
_ => c,
})
}
}
impl Debug for Val {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::String(str) => str.fmt(f),
Self::Char(c) => c.fmt(f),
Self::Number(n) => n.fmt(f),
Self::Unit => f.write_str("()"),
}
}
}
impl Debug for Number {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.whole)?;
if let Some(d) = &self.decimal {
write!(f, ".{}", d)?;
}
if let Some(ty) = &self.ty {
write!(f, "T{}", ty)?;
}
Ok(())
}
}