From 60099aed50b89daef29543c4700470e566c48798 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Tue, 11 Feb 2020 21:30:39 +0100 Subject: =?UTF-8?q?Parse=20tuples=20and=20objects=20=F0=9F=8D=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generalizes the parsing of tuples, objects and function arguments into generic comma-separated collections. --- src/syntax/expr.rs | 73 ++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 66 insertions(+), 7 deletions(-) (limited to 'src/syntax/expr.rs') diff --git a/src/syntax/expr.rs b/src/syntax/expr.rs index 2f2eb68e..b5bce2cd 100644 --- a/src/syntax/expr.rs +++ b/src/syntax/expr.rs @@ -1,6 +1,7 @@ //! Expressions in function headers. -use std::fmt::{self, Debug, Formatter}; +use std::fmt::{self, Write, Debug, Formatter}; +use std::iter::FromIterator; use crate::error::Errors; use crate::size::Size; @@ -90,7 +91,9 @@ impl Ident { impl Debug for Ident { fn fmt(&self, f: &mut Formatter) -> fmt::Result { - f.write_str(&self.0) + f.write_char('`')?; + f.write_str(&self.0)?; + f.write_char('`') } } @@ -143,15 +146,42 @@ impl Tuple { } }) } + + /// Iterate over the items of this tuple. + pub fn iter<'a>(&'a self) -> std::slice::Iter<'a, Spanned> { + self.items.iter() + } +} + +impl IntoIterator for Tuple { + type Item = Spanned; + type IntoIter = std::vec::IntoIter>; + + fn into_iter(self) -> Self::IntoIter { + self.items.into_iter() + } +} + +impl<'a> IntoIterator for &'a Tuple { + type Item = &'a Spanned; + type IntoIter = std::slice::Iter<'a, Spanned>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl FromIterator> for Tuple { + fn from_iter>>(iter: I) -> Self { + Tuple { items: iter.into_iter().collect() } + } } impl Debug for Tuple { fn fmt(&self, f: &mut Formatter) -> fmt::Result { - let mut tuple = f.debug_tuple(""); - for item in &self.items { - tuple.field(item); - } - tuple.finish() + f.debug_list() + .entries(&self.items) + .finish() } } @@ -276,6 +306,35 @@ impl Object { Err(err) => { errors.push(Spanned { v: err, span }); None } } } + + /// Iterate over the pairs of this object. + pub fn iter<'a>(&'a self) -> std::slice::Iter<'a, Pair> { + self.pairs.iter() + } +} + +impl IntoIterator for Object { + type Item = Pair; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.pairs.into_iter() + } +} + +impl<'a> IntoIterator for &'a Object { + type Item = &'a Pair; + type IntoIter = std::slice::Iter<'a, Pair>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl FromIterator for Object { + fn from_iter>(iter: I) -> Self { + Object { pairs: iter.into_iter().collect() } + } } impl Debug for Object { -- cgit v1.2.3