switch everything to locate spans

main
notafile 2022-01-04 20:05:10 +01:00
parent 0699278eab
commit 401e7a3dba
3 changed files with 60 additions and 65 deletions

View File

@ -8,20 +8,9 @@ use nom::{
AsChar, FindToken, InputIter, InputLength, Offset, Slice AsChar, FindToken, InputIter, InputLength, Offset, Slice
}; };
use crate::parser::IResult; use crate::parser::{IResult, Span};
pub fn hexadecimal<'a, I>(input: I) -> IResult<I, u64> pub fn hexadecimal(input: Span) -> IResult<Span, u64>
where
// TODO: ask if there is any way to avoid this hellish constraint
I: InputIter
+ nom::Slice<RangeFrom<usize>>
+ InputLength
+ Clone
+ Offset
+ Into<&'a str>
+ Slice<RangeTo<usize>>,
<I as InputIter>::Item: AsChar + Copy,
&'a str: FindToken<<I as InputIter>::Item>
{ {
map_res( map_res(
preceded( preceded(
@ -31,7 +20,7 @@ where
many0(char('_')), many0(char('_')),
))), ))),
), ),
|out: I| u64::from_str_radix(&str::replace(&out.into(), "_", ""), 16), |out: Span| u64::from_str_radix(&str::replace(&out.fragment(), "_", ""), 16),
)(input) )(input)
} }
@ -41,7 +30,7 @@ mod test {
#[test] #[test]
fn test_hex() { fn test_hex() {
assert_eq!(hexadecimal("hfF").unwrap().1, 0xff); assert_eq!(hexadecimal("hfF".into()).unwrap().1, 0xff);
assert_eq!(hexadecimal("hF").unwrap().1, 0xf); assert_eq!(hexadecimal("hF".into()).unwrap().1, 0xf);
} }
} }

View File

@ -24,10 +24,12 @@ fn main() {
.read_to_string(&mut input) .read_to_string(&mut input)
.expect("error reading file"); .expect("error reading file");
let input: &str = input.as_str(); let input: &str = input.as_str();
let parsed = parser::parse(&input); let input = parser::Span::new(input);
let parsed = parser::parse(input);
match parsed { match parsed {
Err(nom::Err::Error(err) | nom::Err::Failure(err)) => { Err(nom::Err::Error(err) | nom::Err::Failure(err)) => {
print!("{}", convert_error(input, err)) // TODO: get this working again
// print!("{}", convert_error(input, err))
} }
Err(_) => (), Err(_) => (),
Ok(res) => { Ok(res) => {

View File

@ -2,7 +2,7 @@ use nom::{
branch::alt, branch::alt,
bytes::complete::tag, bytes::complete::tag,
character::complete::{alpha1, alphanumeric1, char, multispace0, multispace1, u64 as decimal}, character::complete::{alpha1, alphanumeric1, char, multispace0, multispace1, u64 as decimal},
combinator::{map, opt, recognize}, combinator::{map, opt, recognize, consumed},
error::{context, ParseError, VerboseError}, error::{context, ParseError, VerboseError},
multi::{many0, many1, separated_list0}, multi::{many0, many1, separated_list0},
sequence::{delimited, pair, preceded, separated_pair, terminated, tuple}, sequence::{delimited, pair, preceded, separated_pair, terminated, tuple},
@ -11,33 +11,34 @@ use nom::{
use nom_locate::{position, LocatedSpan}; use nom_locate::{position, LocatedSpan};
// custom span type for nom_locate // custom span type for nom_locate
type Span<'a> = LocatedSpan<&'a str>; pub type Span<'a> = LocatedSpan<&'a str>;
// custom IResult type for VerboseError // custom IResult type for VerboseError
pub type IResult<I, O, E = VerboseError<I>> = nom::IResult<I, O, E>; pub type IResult<I, O, E = VerboseError<I>> = nom::IResult<I, O, E>;
use crate::literals::hexadecimal; use crate::literals::hexadecimal;
fn ws0<'a, F: 'a, O, E: ParseError<&'a str>>( fn ws0<'a, F: 'a, O, E: ParseError<Span<'a>>>(
inner: F, inner: F,
) -> impl FnMut(&'a str) -> IResult<&'a str, O, E> ) -> impl FnMut(Span<'a>) -> IResult<Span<'a>, O, E>
where where
F: FnMut(&'a str) -> IResult<&'a str, O, E>, F: FnMut(Span<'a>) -> IResult<Span<'a>, O, E>,
{ {
delimited(multispace0, inner, multispace0) delimited(multispace0, inner, multispace0)
} }
fn identifier(input: &str) -> IResult<&str, &str> {
fn identifier(input: Span) -> IResult<Span, Span> {
recognize(pair( recognize(pair(
alt((alpha1, tag("_"))), alt((alpha1, tag("_"))),
many0(alt((alphanumeric1, tag("_")))), many0(alt((alphanumeric1, tag("_")))),
))(input) ))(input)
} }
fn widthspec(input: &str) -> IResult<&str, u64> { fn widthspec(input: Span) -> IResult<Span, u64> {
delimited(char('['), ws0(decimal), char(']'))(input) delimited(char('['), ws0(decimal), char(']'))(input)
} }
fn intliteral(input: &str) -> IResult<&str, (u64, u64)> { fn intliteral(input: Span) -> IResult<Span, (u64, u64)> {
tuple((terminated(decimal, char('\'')), alt((decimal, hexadecimal))))(input) tuple((terminated(decimal, char('\'')), alt((decimal, hexadecimal))))(input)
} }
@ -55,15 +56,16 @@ pub enum PortDirection {
} }
#[derive(Debug)] #[derive(Debug)]
pub struct PortDecl { pub struct PortDecl<'a> {
pub pos: Span<'a>,
pub direction: PortDirection, pub direction: PortDirection,
pub net: NetDecl, pub net: NetDecl,
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Module { pub struct Module<'a> {
pub name: String, pub name: String,
pub ports: Vec<PortDecl>, pub ports: Vec<PortDecl<'a>>,
pub statements: Vec<Statement>, pub statements: Vec<Statement>,
} }
@ -97,7 +99,7 @@ pub enum Expression {
Operation(Box<Operation>), Operation(Box<Operation>),
} }
fn declaration(i: &str) -> IResult<&str, NetDecl> { fn declaration(i: Span) -> IResult<Span, NetDecl> {
map( map(
tuple(( tuple((
ws0(alt((tag("reg"), tag("wire")))), ws0(alt((tag("reg"), tag("wire")))),
@ -106,45 +108,47 @@ fn declaration(i: &str) -> IResult<&str, NetDecl> {
opt(preceded(ws0(char('=')), intliteral)), opt(preceded(ws0(char('=')), intliteral)),
)), )),
|(_, width, ident, value)| NetDecl { |(_, width, ident, value)| NetDecl {
name: ident.into(), name: (*ident.fragment()).into(),
width, width,
value, value,
}, },
)(i) )(i)
} }
fn port_decl(i: &str) -> IResult<&str, PortDecl> { fn port_decl(i: Span) -> IResult<Span, PortDecl> {
map( map(
tuple(( consumed(
alt(( tuple((
map(tag("input"), |_| PortDirection::Input), alt((
map(tag("output"), |_| PortDirection::Output), map(tag("input"), |_| PortDirection::Input),
)), map(tag("output"), |_| PortDirection::Output),
declaration, )),
)), declaration,
|(direction, net)| PortDecl { direction, net }, ))
),
|(pos, (direction, net))| PortDecl { pos, direction, net },
)(i) )(i)
} }
fn ports_list(input: &str) -> IResult<&str, Vec<PortDecl>> { fn ports_list(input: Span) -> IResult<Span, Vec<PortDecl>> {
separated_list0(ws0(char(',')), ws0(port_decl))(input) separated_list0(ws0(char(',')), ws0(port_decl))(input)
} }
fn operation(input: &str) -> IResult<&str, Operation> { fn operation(input: Span) -> IResult<Span, Operation> {
// temporarily given up on before I learn the shunting yard algorithm // temporarily given up on before I learn the shunting yard algorithm
alt(( alt((
map( map(
separated_pair(ws0(identifier), char('&'), ws0(expression)), separated_pair(ws0(identifier), char('&'), ws0(expression)),
|(a, b)| Operation::And { a: a.into(), b }, |(a, b)| Operation::And { a: (*a.fragment()).into(), b },
), ),
map( map(
separated_pair(ws0(identifier), char('|'), ws0(expression)), separated_pair(ws0(identifier), char('|'), ws0(expression)),
|(a, b)| Operation::Or { a: a.into(), b }, |(a, b)| Operation::Or { a: (*a.fragment()).into(), b },
), ),
))(input) ))(input)
} }
fn call_item(input: &str) -> IResult<&str, Call> { fn call_item(input: Span) -> IResult<Span, Call> {
map( map(
tuple(( tuple((
ws0(identifier), ws0(identifier),
@ -155,21 +159,21 @@ fn call_item(input: &str) -> IResult<&str, Call> {
), ),
)), )),
|(name, args)| Call { |(name, args)| Call {
name: name.into(), name: (*name.fragment()).into(),
args, args,
}, },
)(input) )(input)
} }
fn expression(input: &str) -> IResult<&str, Expression> { fn expression(input: Span) -> IResult<Span, Expression> {
alt(( alt((
map(ws0(operation), |op| Expression::Operation(Box::new(op))), map(ws0(operation), |op| Expression::Operation(Box::new(op))),
map(ws0(call_item), |call| Expression::Call(Box::new(call))), map(ws0(call_item), |call| Expression::Call(Box::new(call))),
map(ws0(identifier), |ident| Expression::Ident(ident.into())), map(ws0(identifier), |ident| Expression::Ident((*ident.fragment()).into())),
))(input) ))(input)
} }
fn assign_statement(input: &str) -> IResult<&str, Statement> { fn assign_statement(input: Span) -> IResult<Span, Statement> {
context( context(
"assignment", "assignment",
delimited( delimited(
@ -178,8 +182,8 @@ fn assign_statement(input: &str) -> IResult<&str, Statement> {
separated_pair(ws0(identifier), char('='), ws0(expression)), separated_pair(ws0(identifier), char('='), ws0(expression)),
|(lhs, expr)| { |(lhs, expr)| {
Statement::Assign(Assign { Statement::Assign(Assign {
lhs: lhs.into(), lhs: (*lhs.fragment()).into(),
expr: expr.into(), expr,
}) })
}, },
), ),
@ -188,7 +192,7 @@ fn assign_statement(input: &str) -> IResult<&str, Statement> {
)(input) )(input)
} }
pub fn module(input: &str) -> IResult<&str, Module> { pub fn module(input: Span) -> IResult<Span, Module> {
context( context(
"module", "module",
map( map(
@ -203,7 +207,7 @@ pub fn module(input: &str) -> IResult<&str, Module> {
)), )),
)), )),
|(_, name, ports, statements)| Module { |(_, name, ports, statements)| Module {
name: name.into(), name: (*name.fragment()).into(),
ports, ports,
statements, statements,
}, },
@ -211,7 +215,7 @@ pub fn module(input: &str) -> IResult<&str, Module> {
)(input) )(input)
} }
pub fn parse(input: &str) -> IResult<&str, Module> { pub fn parse(input: Span) -> IResult<Span, Module> {
module(input) module(input)
} }
@ -221,32 +225,32 @@ mod test {
#[test] #[test]
fn test_decl() { fn test_decl() {
declaration("reg abcd").unwrap(); declaration("reg abcd".into()).unwrap();
} }
#[test] #[test]
fn test_operation() { fn test_operation() {
operation(" a | b ").unwrap(); operation(" a | b ".into()).unwrap();
operation(" a & b ").unwrap(); operation(" a & b ".into()).unwrap();
} }
#[test] #[test]
fn test_expression() { fn test_expression() {
expression(" a ").unwrap(); expression(" a ".into()).unwrap();
expression(" a | b ").unwrap(); expression(" a | b ".into()).unwrap();
expression(" a | b | c ").unwrap(); expression(" a | b | c ".into()).unwrap();
} }
#[test] #[test]
fn test_assignment() { fn test_assignment() {
assign_statement(" assign a = b ; ").unwrap(); assign_statement(" assign a = b ; ".into()).unwrap();
assign_statement(" assign a = b | c ; ").unwrap(); assign_statement(" assign a = b | c ; ".into()).unwrap();
} }
#[test] #[test]
fn test_call() { fn test_call() {
call_item("thing ( )").unwrap(); call_item("thing ( )".into()).unwrap();
call_item("thing ( a , b , c )").unwrap(); call_item("thing ( a , b , c )".into()).unwrap();
call_item("thing(a,b,c)").unwrap(); call_item("thing(a,b,c)".into()).unwrap();
} }
} }