2021-10-19 22:24:27 -07:00
|
|
|
#![allow(clippy::upper_case_acronyms)]
|
|
|
|
|
2021-11-14 04:25:24 -08:00
|
|
|
mod peg_parser;
|
2021-11-04 21:11:19 -07:00
|
|
|
mod test;
|
2019-06-16 14:59:11 -07:00
|
|
|
|
2021-11-14 03:18:05 -08:00
|
|
|
use std::fmt;
|
2018-06-04 19:25:40 -07:00
|
|
|
|
2021-11-14 04:35:04 -08:00
|
|
|
#[cfg(test)]
|
|
|
|
use crate::ast::{Block, Expression};
|
2021-11-14 03:55:35 -08:00
|
|
|
use crate::{
|
|
|
|
ast::{ASTItem, AST},
|
|
|
|
identifier::{Id, IdStore},
|
|
|
|
};
|
|
|
|
|
|
|
|
pub struct Parser {
|
|
|
|
id_store: IdStore<ASTItem>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Parser {
|
|
|
|
pub(crate) fn new() -> Self {
|
|
|
|
Self { id_store: IdStore::new() }
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn parse(&mut self, input: &str) -> Result<AST, ParseError> {
|
2021-11-14 04:35:04 -08:00
|
|
|
peg_parser::schala_parser::program(input, self).map_err(ParseError::from_peg)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
fn expression(&mut self, input: &str) -> Result<Expression, ParseError> {
|
|
|
|
peg_parser::schala_parser::expression(input, self).map_err(ParseError::from_peg)
|
|
|
|
}
|
2021-11-14 03:55:35 -08:00
|
|
|
|
2021-11-14 04:35:04 -08:00
|
|
|
#[cfg(test)]
|
|
|
|
fn block(&mut self, input: &str) -> Result<Block, ParseError> {
|
|
|
|
peg_parser::schala_parser::block(input, self).map_err(ParseError::from_peg)
|
2021-11-14 03:55:35 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
fn fresh(&mut self) -> Id<ASTItem> {
|
|
|
|
self.id_store.fresh()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-08 23:59:49 -07:00
|
|
|
/// Represents a parsing error
|
2018-07-11 02:32:29 -07:00
|
|
|
#[derive(Debug)]
|
2017-09-11 02:07:17 -07:00
|
|
|
pub struct ParseError {
|
2021-10-30 21:22:15 -07:00
|
|
|
pub msg: String,
|
2021-11-14 02:15:08 -08:00
|
|
|
pub location: Location,
|
2018-10-21 16:33:21 -07:00
|
|
|
}
|
|
|
|
|
2021-11-14 04:35:04 -08:00
|
|
|
impl ParseError {
|
|
|
|
fn from_peg(err: peg::error::ParseError<peg::str::LineCol>) -> Self {
|
|
|
|
let msg = err.to_string();
|
|
|
|
Self { msg, location: err.location.offset.into() }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-14 03:18:05 -08:00
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
|
|
|
pub struct Location {
|
|
|
|
pub(crate) offset: usize,
|
2017-09-11 02:07:17 -07:00
|
|
|
}
|
2017-09-09 00:31:15 -07:00
|
|
|
|
2021-11-14 03:18:05 -08:00
|
|
|
impl From<usize> for Location {
|
|
|
|
fn from(offset: usize) -> Self {
|
|
|
|
Self { offset }
|
2018-02-21 03:52:16 -08:00
|
|
|
}
|
2017-09-11 23:27:15 -07:00
|
|
|
}
|
|
|
|
|
2021-11-14 03:18:05 -08:00
|
|
|
impl fmt::Display for Location {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
write!(f, "{}", self.offset)
|
2018-02-21 03:52:16 -08:00
|
|
|
}
|
2018-01-08 05:57:36 -08:00
|
|
|
}
|