Fix warnings, refactor code

This commit is contained in:
Andreas Longva 2021-04-11 17:29:33 +02:00
parent ab95cf7020
commit ed833506a9
2 changed files with 30 additions and 20 deletions

View File

@ -34,33 +34,41 @@ impl Matrix {
} }
type MatrixRowSyntax = Punctuated<Expr, Token![,]>; type MatrixRowSyntax = Punctuated<Expr, Token![,]>;
type MatrixSyntax = Punctuated<MatrixRowSyntax, Token![;]>;
impl Parse for Matrix { impl Parse for Matrix {
fn parse(input: ParseStream) -> Result<Self> { fn parse(input: ParseStream) -> Result<Self> {
let span = input.span();
// TODO: Handle empty matrix case
let ast = MatrixSyntax::parse_separated_nonempty_with(input,
|input| MatrixRowSyntax::parse_separated_nonempty(input))?;
let ncols = ast.first().map(|row| row.len())
.unwrap_or(0);
let mut rows = Vec::new(); let mut rows = Vec::new();
let mut ncols = None;
for row in ast { while !input.is_empty() {
let row_span = input.span();
let row = MatrixRowSyntax::parse_separated_nonempty(input)?;
if let Some(ncols) = ncols {
if row.len() != ncols { if row.len() != ncols {
// TODO: Is this the correct span? let row_idx = rows.len();
// Currently it returns the span corresponding to the first element in the macro let error_msg = format!(
// invocation, but it would be nice if it returned the span of the first element "Unexpected number of entries in row {}. Expected {}, found {} entries.",
// in the first row that has an unexpected number of columns row_idx,
return Err(Error::new(span, "Unexpected number of columns. TODO")) ncols,
row.len());
return Err(Error::new(row_span, error_msg));
}
} else {
ncols = Some(row.len());
} }
rows.push(row.into_iter().collect()); rows.push(row.into_iter().collect());
// We've just read a row, so if there are more tokens, there must be a semi-colon,
// otherwise the input is malformed
if !input.is_empty() {
input.parse::<Token![;]>()?;
}
} }
Ok(Self { Ok(Self {
rows, rows,
ncols ncols: ncols.unwrap_or(0)
}) })
} }
} }

View File

@ -1,8 +1,10 @@
use nalgebra_macros::matrix; use nalgebra_macros::matrix;
use nalgebra::Matrix3x2;
#[test] #[test]
fn basic_usage() { fn matrix_basic_construction() {
matrix![ 1, 3; let matrix: Matrix3x2<_> = matrix![ 1, 2;
4, 5*3; 3, 4;
3, 3]; 5, 6 ];
assert_eq!(matrix, Matrix3x2::new(1, 2, 3, 4, 5, 6));
} }