diff --git a/cfgrammar/src/lib/header.rs b/cfgrammar/src/lib/header.rs index 5a8bea6b8..2b6e8f00d 100644 --- a/cfgrammar/src/lib/header.rs +++ b/cfgrammar/src/lib/header.rs @@ -1,12 +1,12 @@ use crate::{ - Location, Span, Spanned, - markmap::{Entry, MarkMap}, + Span, Spanned, yacc::{ YaccGrammarError, YaccGrammarErrorKind, YaccKind, YaccOriginalActionKind, parser::SpansKind, }, }; use regex::{Regex, RegexBuilder}; use std::{ + collections::hash_map::Entry, collections::{HashMap, HashSet}, error::Error, fmt, @@ -36,7 +36,7 @@ impl fmt::Display for HeaderError { impl From> for YaccGrammarError { fn from(e: HeaderError) -> YaccGrammarError { YaccGrammarError { - kind: YaccGrammarErrorKind::Header(e.kind, e.spanskind()), + kind: YaccGrammarErrorKind::Header(e.clone().kind, e.spanskind()), spans: e.locations, } } @@ -57,13 +57,7 @@ impl Spanned for HeaderError { #[doc(hidden)] pub struct HeaderValue(pub T, pub Value); -impl From> for HeaderValue { - fn from(hv: HeaderValue) -> HeaderValue { - HeaderValue(hv.0.into(), hv.1.into()) - } -} - -#[derive(Debug, Eq, PartialEq, Copy, Clone)] +#[derive(Debug, Eq, PartialEq, Clone)] #[non_exhaustive] #[doc(hidden)] pub enum HeaderErrorKind { @@ -71,9 +65,14 @@ pub enum HeaderErrorKind { IllegalName, ExpectedToken(char), UnexpectedToken(char, &'static str), + /// An entry occurs multiple times in the header having a span for each entry. + /// Requires two or more spans. DuplicateEntry, + /// Very similar to DuplicateEntry except that requires two spans. + /// When a value is specified in the builder and a header there is only one span. + ConflictingEntry(&'static str), InvalidEntry(&'static str), - ConversionError(&'static str, &'static str), + ConversionError(&'static str, String), } impl fmt::Display for HeaderErrorKind { @@ -87,6 +86,7 @@ impl fmt::Display for HeaderErrorKind { } HeaderErrorKind::InvalidEntry(s) => &format!("Invalid entry: '{}'", s), HeaderErrorKind::DuplicateEntry => "Duplicate Entry", + HeaderErrorKind::ConflictingEntry(s) => &format!("Conflicting Entry: '{}'", s), HeaderErrorKind::ConversionError(t, err_str) => { &format!("Converting header value to type '{}': {}", t, err_str) } @@ -127,21 +127,63 @@ pub enum Value { Namespaced(String, T), } -impl From> for Value { - fn from(it: Value) -> Value { - use Value as GV; - match it { - GV::String(v, span) => GV::String(v, Location::Span(span)), - GV::Num(v, span) => GV::Num(v, Location::Span(span)), - GV::Bool(v, span) => GV::Bool(v, Location::Span(span)), - GV::Array(mut v, span) => GV::Array( - v.drain(..).map(|val| val.into()).collect::>(), - Location::Span(span), - ), - GV::Namespaced(v, span) => GV::Namespaced(v, Location::Span(span)), +impl TryInto for &HeaderValue { + type Error = HeaderError; + fn try_into(self) -> Result { + macro_rules! fmt_err { + ($found:literal,$span:ident) => { + Err(HeaderError { + kind: HeaderErrorKind::ConversionError("bool", $found.to_string()), + locations: vec![$span], + }) + }; + } + match self.1 { + Value::Bool(flag, _) => Ok(flag), + Value::String(_, span) => fmt_err!("Found string", span), + Value::Num(_, span) => fmt_err!("Found numeric", span), + Value::Array(_, span) => fmt_err!("Found array", span), + Value::Namespaced(_, span) => fmt_err!("Found namespaced value", span), } } } +macro_rules! try_into_numeric { + ($typ:ty) => { + impl TryInto<$typ> for &HeaderValue { + type Error = HeaderError; + fn try_into(self) -> Result<$typ, Self::Error> { + macro_rules! fmt_err { + ($found:literal,$span:ident) => { + Err(HeaderError { + kind: HeaderErrorKind::ConversionError( + stringify!($typ), + $found.to_string(), + ), + locations: vec![$span], + }) + }; + } + match self.1 { + Value::Num(num, span) => <$typ>::try_from(num).map_err(|e| HeaderError { + kind: HeaderErrorKind::ConversionError(stringify!($typ), e.to_string()), + locations: vec![span], + }), + Value::Bool(_, span) => fmt_err!("Found bool", span), + Value::String(_, span) => fmt_err!("Found string", span), + + Value::Array(_, span) => fmt_err!("Found array", span), + Value::Namespaced(_, span) => fmt_err!("Found namespaced value", span), + } + } + } + }; +} + +try_into_numeric!(u64); +try_into_numeric!(usize); +try_into_numeric!(u32); +try_into_numeric!(u16); +try_into_numeric!(u8); impl HeaderError { /// Returns the [SpansKind] associated with this error. @@ -522,7 +564,7 @@ impl<'input> GrmtoolsSectionParser<'input> { /// A data structure representation of the %grmtools section. #[doc(hidden)] -pub type Header = MarkMap>; +pub type Header = HashMap>; impl TryFrom<&Value> for YaccKind { type Error = HeaderError; diff --git a/cfgrammar/src/lib/markmap.rs b/cfgrammar/src/lib/markmap.rs deleted file mode 100644 index 142887181..000000000 --- a/cfgrammar/src/lib/markmap.rs +++ /dev/null @@ -1,1038 +0,0 @@ -use std::borrow::Borrow; -use std::error::Error; -use std::fmt; - -/// MarkMap is a key value data structure that uses an API similar to that of -/// `std::collections::HashMap` and `std::collections::BTreeMap`. -/// -/// The current implementation is based on a sorted `Vec` is not optimized for -/// storing large number of items. -/// -/// On top of the familiar `std::collections` API it has a few additions: -/// -/// * Marking a key with a condition. -/// * Marking a key with a merge behavior. -/// * A merge operator. -/// -/// The current *conditions* are [`Used`](MarkMap::mark_used) and [`Required`](MarkMap::mark_required). -/// -/// The available merge behaviors are [`Theirs`](MergeBehavior::Theirs), [`Ours`](MergeBehavior::Ours), -/// and [`MutuallyExclusive`](MergeBehavior::MutuallyExclusive). -/// -/// Merge behaviors configure how the merge operator handles cases where both `MarkMaps` being merged -/// contain a particular key. -#[derive(Debug, PartialEq, Eq, Clone)] -#[doc(hidden)] -pub struct MarkMap { - default_merge_behavior: MergeBehavior, - contents: Vec<(K, u16, Option)>, -} - -/// Defines the merge behavior for a single key in the markmap. -#[repr(u8)] -#[derive(Clone, Copy, Eq, PartialEq, Debug)] -#[doc(hidden)] -pub enum MergeBehavior { - /// The value in `self` takes precedence. - Theirs = 1 << 0, - /// The value in `other` takes precedence. - Ours = 1 << 1, - /// It is an error if the key is present in both `MarkMaps`. - /// This is the default if no merge behavior is set. - MutuallyExclusive = 1 << 2, -} - -/// Conflicting values were present while merging, and the -/// merge behavior did not specify a means to resolve them. -#[derive(Debug)] -#[doc(hidden)] -pub enum MergeError { - // Contains the key which was present in both, and the value which was present in `Theirs`. - Exclusivity(K, V), -} - -impl Error for MergeError {} - -impl fmt::Display for MergeError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - Self::Exclusivity(k, _) => { - write!(f, "Merge behavior forbids overriding key: {:?}", k) - } - } - } -} - -/// A view into a single entry in a `MarkMap`, which may either be vacant or occupied. -#[doc(hidden)] -pub enum Entry<'a, K, V> { - Occupied(OccupiedEntry<'a, K, V>), - Vacant(VacantEntry<'a, K, V>), -} - -#[repr(u8)] -#[derive(Clone, Copy)] -#[doc(hidden)] -enum Mark { - // There are some other interesting marks that could be added based on row polymorphic records. - // Marks such as `Prohibited` could be used to prove disjointedness. - Used, - Required, - MergeBehavior(MergeBehavior), -} - -impl Mark { - fn repr(self) -> u16 { - match self { - Self::Used => 1 << 0, - Self::Required => 1 << 1, - Self::MergeBehavior(mb) => (1 << 2) | ((mb as u16) << 8), - } - } -} - -impl<'a, K: Ord + Clone, V> VacantEntry<'a, K, V> { - /// Inserts a value into a vacant entry. - /// Returns a mutable reference to value inserted. - pub fn insert(self, val: V) -> &'a mut V { - match self.pos { - Ok(pos) => { - self.map.contents[pos].2 = Some(val); - self.map.contents[pos].2.as_mut().unwrap() - } - Err(pos) => { - self.map.contents.insert(pos, (self.key, 0, Some(val))); - self.map.contents[pos].2.as_mut().unwrap() - } - } - } - - /// Inserts a value into a vacant entry. - /// Returns an occupied entry. - pub fn insert_entry(self, val: V) -> OccupiedEntry<'a, K, V> { - match self.pos { - Ok(pos) => { - self.map.contents[pos].2 = Some(val); - OccupiedEntry { pos, map: self.map } - } - Err(pos) => { - self.map.contents.insert(pos, (self.key, 0, Some(val))); - OccupiedEntry { pos, map: self.map } - } - } - } - - /// Marks the key associated with this entry as required. - pub fn mark_required(&mut self) { - match self.pos { - Ok(pos) => { - let repr = self.map.contents[pos].1; - self.map.contents[pos].1 = repr | Mark::Required.repr(); - } - Err(pos) => { - self.map - .contents - .insert(pos, (self.key.clone(), Mark::Required.repr(), None)); - self.pos = Ok(pos) - } - } - } - - /// Sets the merge behavior for the key associated with this entry. - pub fn set_merge_behavior(&mut self, mb: MergeBehavior) { - match self.pos { - Ok(pos) => { - let merge_reprs = Mark::MergeBehavior(MergeBehavior::MutuallyExclusive).repr() - | Mark::MergeBehavior(MergeBehavior::Ours).repr() - | Mark::MergeBehavior(MergeBehavior::Theirs).repr(); - let mut repr = self.map.contents[pos].1; - // Zap just the MergeBehavior bits. - repr ^= repr & merge_reprs; - repr |= Mark::MergeBehavior(mb).repr(); - self.map.contents[pos].1 = repr; - } - Err(pos) => { - self.map.contents.insert( - pos, - (self.key.clone(), Mark::MergeBehavior(mb).repr(), None), - ); - self.pos = Ok(pos) - } - } - } - - /// Returns the key associated with this entry. - pub fn key(&self) -> &K { - &self.key - } -} - -impl OccupiedEntry<'_, K, V> { - /// Returns the value associated with this entry. - pub fn get(&self) -> &V { - self.map.contents[self.pos].2.as_ref().unwrap() - } - - /// Sets the value of the entry, and returns the entry’s old value. - pub fn insert(self, val: V) -> V { - let v: Option = self.map.contents[self.pos].2.take(); - self.map.contents[self.pos].2 = Some(val); - v.unwrap() - } - - /// Gets the mark associated with the key of this entry. - pub fn get_mark(&self) -> u16 { - self.map.contents[self.pos].1 - } - - /// Marks the key associated with this entry as used. - pub fn mark_used(&mut self) { - let repr = self.map.contents[self.pos].1 | Mark::Used.repr(); - self.map.contents[self.pos].1 = repr; - } - - /// Returns whether the key associated with this entry is used. - pub fn is_used(&self) -> bool { - self.map.contents[self.pos].1 & Mark::Used.repr() != 0 - } - - /// Marks the key associated with this entry as required. - pub fn mark_required(&mut self) { - let repr = self.map.contents[self.pos].1 | Mark::Required.repr(); - self.map.contents[self.pos].1 = repr; - } - - /// Returns whether the key associated with this entry is required. - pub fn is_required(&self) -> bool { - self.map.contents[self.pos].1 & Mark::Required.repr() != 0 - } - - /// Sets the merge behavior for the key associated with this entry. - pub fn set_merge_behavior(&mut self, mb: MergeBehavior) { - let mut repr = self.map.contents[self.pos].1; - let merge_reprs = Mark::MergeBehavior(MergeBehavior::MutuallyExclusive).repr() - | Mark::MergeBehavior(MergeBehavior::Ours).repr() - | Mark::MergeBehavior(MergeBehavior::Theirs).repr(); - // Zap just the MergeBehavior bits. - repr ^= repr & merge_reprs; - repr |= Mark::MergeBehavior(mb).repr(); - self.map.contents[self.pos].1 = repr; - } -} - -/// A view into an occupied entry in a `MarkMap`. It is part of the `Entry` enum. -#[doc(hidden)] -pub struct OccupiedEntry<'a, K, V> { - pos: usize, - map: &'a mut MarkMap, -} - -/// A view into a vacant entry in a `MarkMap`. It is part of the `Entry` enum. -#[doc(hidden)] -pub struct VacantEntry<'a, K, V> { - // The values of the `pos` result imply: - // * When `Ok(pos)` the key was found at `pos`, and it's value was `None`. - // * When `Err(pos)` the key was not found at `pos`. - pos: Result, - key: K, - map: &'a mut MarkMap, -} - -impl MarkMap { - /// Returns a new `MarkMap`. - #[allow(clippy::new_without_default)] - pub fn new() -> Self { - MarkMap { - default_merge_behavior: MergeBehavior::MutuallyExclusive, - contents: vec![], - } - } - - /// Inserts a `key` `value` pair. - pub fn insert(&mut self, key: K, val: V) -> Option { - let pos = self.contents.binary_search_by(|(k, _, _)| k.cmp(&key)); - match pos { - Ok(pos) => { - let ret = self.contents[pos].2.take(); - self.contents[pos].2 = Some(val); - ret - } - Err(pos) => { - self.contents.insert(pos, (key, 0, Some(val))); - None - } - } - } - - /// Gets the raw mark value, for testing purposes. - #[cfg(test)] - pub(crate) fn get_mark(&mut self, key: &K) -> Option { - let pos = self.contents.binary_search_by(|(k, _, _)| k.cmp(key)); - match pos { - Ok(pos) => Some(self.contents[pos].1), - Err(_) => None, - } - } - - /// Marks `key` as used. - pub fn mark_used(&mut self, key: &K) { - let pos = self.contents.binary_search_by(|(k, _, _)| k.cmp(key)); - match pos { - Ok(pos) => { - let mut repr = self.contents[pos].1; - repr |= Mark::Used.repr(); - self.contents[pos].1 = repr; - } - Err(pos) => { - self.contents - .insert(pos, (key.to_owned(), Mark::Used.repr(), None)); - } - } - } - - /// Marks `key` as a required value. - pub fn mark_required(&mut self, key: &K) { - let pos = self.contents.binary_search_by(|(k, _, _)| k.cmp(key)); - match pos { - Ok(pos) => { - let mut repr = self.contents[pos].1; - repr |= Mark::Required.repr(); - self.contents[pos].1 = repr; - } - Err(pos) => { - self.contents - .insert(pos, (key.to_owned(), Mark::Required.repr(), None)); - } - } - } - - /// Returns whether `key` is required. - pub fn is_required(&self, key: &K) -> bool { - let pos = self.contents.binary_search_by(|(k, _, _)| k.cmp(key)); - match pos { - Ok(pos) => self.contents[pos].1 & Mark::Required.repr() != 0, - _ => false, - } - } - - pub fn set_default_merge_behavior(&mut self, mb: MergeBehavior) { - self.default_merge_behavior = mb; - } - - /// Sets the merge behavior for `key`. - pub fn set_merge_behavior(&mut self, key: &K, mb: MergeBehavior) { - let pos = self.contents.binary_search_by(|(k, _, _)| k.cmp(key)); - match pos { - Ok(pos) => { - let mut repr = self.contents[pos].1; - let merge_reprs = Mark::MergeBehavior(MergeBehavior::MutuallyExclusive).repr() - | Mark::MergeBehavior(MergeBehavior::Ours).repr() - | Mark::MergeBehavior(MergeBehavior::Theirs).repr(); - // Zap just the MergeBehavior bits. - repr ^= repr & merge_reprs; - repr |= Mark::MergeBehavior(mb).repr(); - self.contents[pos].1 = repr; - } - Err(pos) => { - self.contents - .insert(pos, (key.to_owned(), Mark::MergeBehavior(mb).repr(), None)); - } - } - } - - /// Returns a `Some(value)` associated with `key` if present otherwise `None`. - pub fn get(&self, key: &Q) -> Option<&V> - where - K: Borrow, - Q: Ord + ?Sized, - { - let pos = self.contents.binary_search_by(|(k, _, _)| { - let q: &Q = k.borrow(); - q.cmp(key) - }); - match pos { - Err(_) => None, - Ok(pos) => self.contents[pos].2.as_ref(), - } - } - - /// Returns true if the `MarkMap` contains `key` otherwise false. - pub fn contains_key(&self, key: &Q) -> bool - where - K: Borrow, - Q: Ord + ?Sized, - { - self.get(key).is_some() - } - - /// Removes `key` from the `MarkMap` and returns the previous value when present. - pub fn remove(&mut self, key: &K) -> Option { - let pos = self.contents.binary_search_by(|(k, _, _)| k.cmp(key)); - match pos { - Err(_) => None, - Ok(pos) => self.contents.remove(pos).2, - } - } - - /// Returns an `Entry` for `key`. - pub fn entry(&mut self, key: K) -> Entry<'_, K, V> { - let pos = self.contents.binary_search_by(|(k, _, _)| k.cmp(&key)); - match pos { - Err(pos) => Entry::Vacant(VacantEntry { - pos: Err(pos), - key, - map: self, - }), - Ok(pos) => { - if self.contents[pos].2.is_some() { - Entry::Occupied(OccupiedEntry { pos, map: self }) - } else { - Entry::Vacant(VacantEntry { - pos: Ok(pos), - key, - map: self, - }) - } - } - } - } - - /// Merges items from `other` into `self`, for each value it checks the `MergeBehavior` of self. - /// The `MergeBehavior` of other is not considered. - /// - /// * `MergeBehavior::Ours`: If a value is set in `other`, a value set in self takes precedence. - /// * `MergeBehavior::Theirs`: if a value in `other` `is_some()`, then it will overwrite values in self. - /// * `MergeBehavior::MutuallyExclusive` If a value is set in `other`, that value should be `None` in self. - /// * If `MergeBehavior` is unset, defaults to `MergeBehavior::MutuallyExclusive`. - /// - /// For the behavior of exclusive or mark the behavior as also `Mark::Required`, then after merge call `missing()` - /// to check all required values. - pub fn merge_from(&mut self, mut other: MarkMap) -> Result<(), MergeError>> - where - U: Into, - { - for (their_key, their_mark, their_val) in other.contents.drain(..) { - let pos = self.contents.binary_search_by(|x| x.0.cmp(&their_key)); - match pos { - Ok(pos) => { - let (_, my_mark, my_val) = &mut self.contents[pos]; - let theirs_mark = Mark::MergeBehavior(MergeBehavior::Theirs).repr(); - let ours_mark = Mark::MergeBehavior(MergeBehavior::Ours).repr(); - let exclusive_mark = - Mark::MergeBehavior(MergeBehavior::MutuallyExclusive).repr(); - // Their marks with their merge behavior stripped. - let mut just_their_marks = their_mark; - let merge_reprs = Mark::MergeBehavior(MergeBehavior::MutuallyExclusive).repr() - | Mark::MergeBehavior(MergeBehavior::Ours).repr() - | Mark::MergeBehavior(MergeBehavior::Theirs).repr(); - // Zap just the MergeBehavior bits. - just_their_marks ^= just_their_marks & merge_reprs; - let mut merge_behavior = (*my_mark & exclusive_mark) - | (*my_mark & ours_mark) - | (*my_mark & theirs_mark); - if merge_behavior == 0 { - merge_behavior = Mark::MergeBehavior(self.default_merge_behavior).repr(); - } - match their_val { - Some(their_val) if merge_behavior == exclusive_mark => { - if my_val.is_some() { - return Err(MergeError::Exclusivity( - their_key, - Box::new(their_val.into()), - )); - } else { - *my_mark |= just_their_marks; - *my_val = Some(their_val.into()); - } - } - - their_val if merge_behavior == theirs_mark => { - *my_mark |= just_their_marks; - *my_val = their_val.map(|u| u.into()); - } - - their_val if my_val.is_none() && merge_behavior == ours_mark => { - *my_mark |= just_their_marks; - *my_val = their_val.map(|u| u.into()); - } - _ => {} - } - } - Err(pos) => { - self.contents - .insert(pos, (their_key, their_mark, their_val.map(|u| u.into()))); - } - } - } - Ok(()) - } - - /// Returns whether `key` has been marked as used. - pub fn is_used(&self, key: &Q) -> bool - where - K: Borrow, - Q: Ord + ?Sized, - { - if let Ok(pos) = self.contents.binary_search_by(|x| { - let k: &Q = x.0.borrow(); - k.borrow().cmp(key) - }) { - self.contents[pos].1 & Mark::Used.repr() != 0 - } else { - false - } - } - - /// Returns a `Vec` containing all the keys that are not marked as used. - pub fn unused(&self) -> impl Iterator { - self.contents.iter().filter_map(|(k, mark, v)| { - let used_mark = Mark::Used.repr(); - if v.is_some() && mark & used_mark == 0 { - Some((k, v.as_ref().unwrap())) - } else { - None - } - }) - } - - /// Returns a `Vec` containing all the keys that are marked as required, - /// but have values that are not present in the `MarkMap`. - pub fn missing(&self) -> Vec<&K> { - let mut ret = Vec::new(); - for (k, mark, v) in &self.contents { - let required_mark = Mark::Required.repr(); - if v.is_none() && mark & required_mark != 0 { - ret.push(k) - } - } - ret - } - - /// Returns an `Iterator` over all the keys of the `MarkMap`. - pub fn keys(&self) -> Keys<'_, K, V> { - Keys { pos: 0, map: self } - } -} - -/// Iterator over the owned keys and values of a `MarkMap`. -#[doc(hidden)] -pub struct MarkMapIter { - map: MarkMap, -} - -#[doc(hidden)] -impl Iterator for MarkMapIter { - type Item = (K, V); - - fn next(&mut self) -> Option { - if !self.map.contents.is_empty() { - let (k, _, v) = self.map.contents.swap_remove(0); - v.map(|v| (k, v)) - } else { - None - } - } -} - -/// Iterator over references to keys and values of a `MarkMap`. -#[doc(hidden)] -pub struct MarkMapIterRef<'a, K, V> { - pos: usize, - map: &'a MarkMap, -} - -#[doc(hidden)] -impl<'a, K, V> Iterator for MarkMapIterRef<'a, K, V> { - type Item = (&'a K, &'a V); - - fn next(&mut self) -> Option { - loop { - if self.pos >= self.map.contents.len() { - return None; - } - let pos = self.pos; - self.pos += 1; - if self.map.contents[pos].2.is_some() { - return Some(( - &self.map.contents[pos].0, - self.map.contents[pos].2.as_ref().unwrap(), - )); - } - } - } -} - -#[doc(hidden)] -impl<'a, K, V> IntoIterator for &'a MarkMap { - type Item = (&'a K, &'a V); - type IntoIter = MarkMapIterRef<'a, K, V>; - fn into_iter(self) -> Self::IntoIter { - MarkMapIterRef { pos: 0, map: self } - } -} - -/// Iterator over references to keys and values of a `MarkMap`. -#[doc(hidden)] -pub struct Keys<'a, K, V> { - pos: usize, - map: &'a MarkMap, -} - -impl<'a, K, V> Iterator for Keys<'a, K, V> { - type Item = &'a K; - - fn next(&mut self) -> Option { - loop { - if self.pos >= self.map.contents.len() { - return None; - } - let pos = self.pos; - self.pos += 1; - if self.map.contents[pos].2.is_some() { - return Some(&self.map.contents[pos].0); - } - } - } -} - -#[cfg(test)] -mod test { - use super::*; - #[test] - fn test_insert_get_remove() { - let mut mm = MarkMap::new(); - mm.insert("a", "test"); - assert_eq!(mm.get(&"a"), Some(&"test")); - assert_eq!(mm.remove(&"a"), Some("test")); - assert_eq!(mm.get(&"a"), None); - } - - #[test] - fn test_entry_occupied() { - let mut mm = MarkMap::new(); - mm.insert("a", "test"); - assert!(!mm.is_required(&"a")); - assert!(!mm.is_used(&"a")); - let ent = mm.entry("a"); - match ent { - Entry::Occupied(mut o) => { - assert!(!o.is_required()); - assert!(!o.is_used()); - o.mark_used(); - assert!(o.is_used()); - assert!(!o.is_required()); - o.mark_required(); - assert!(o.is_required()); - assert!(o.is_used()); - } - Entry::Vacant(_) => { - panic!("Expected occupied entry"); - } - } - assert!(mm.is_required(&"a")); - assert!(mm.is_used(&"a")); - } - - #[test] - fn test_entry_vacant() { - let mut mm = MarkMap::new(); - mm.insert("a", "test"); - let ent = mm.entry("b"); - match ent { - Entry::Occupied(_) => { - panic!("Expected vacant entry"); - } - Entry::Vacant(v) => { - v.insert("test b"); - } - } - } - - #[test] - fn test_mark() { - let mut mm = MarkMap::new(); - assert!(mm.insert("a", "test").is_none()); - mm.mark_used(&"a"); - mm.set_merge_behavior(&"b", MergeBehavior::MutuallyExclusive); - assert_eq!(mm.get_mark(&"a"), Some(Mark::Used.repr())); - assert_eq!( - mm.get_mark(&"b"), - Some(Mark::MergeBehavior(MergeBehavior::MutuallyExclusive).repr()) - ); - assert_eq!(mm.get_mark(&"c"), None); - assert_eq!(mm.get(&"a"), Some(&"test")); - assert_eq!(mm.insert("a", "changed"), Some("test")); - assert_eq!(mm.get(&"b"), None); - assert_eq!(mm.insert("b", "added"), None); - assert_eq!( - mm.get_mark(&"b"), - Some(Mark::MergeBehavior(MergeBehavior::MutuallyExclusive).repr()) - ); - assert_eq!(mm.get(&"a"), Some(&"changed")); - assert_eq!(mm.get(&"c"), None); - } - - #[test] - fn test_mark_stable() { - let mut mm: MarkMap<&str, &str> = MarkMap::new(); - mm.mark_used(&"a"); - assert_eq!(mm.get_mark(&"a"), Some(Mark::Used.repr())); - mm.mark_required(&"a"); - assert_eq!( - mm.get_mark(&"a"), - Some(Mark::Used.repr() | Mark::Required.repr()) - ); - mm.set_merge_behavior(&"a", MergeBehavior::MutuallyExclusive); - assert_eq!( - mm.get_mark(&"a"), - Some( - Mark::Used.repr() - | Mark::Required.repr() - | Mark::MergeBehavior(MergeBehavior::MutuallyExclusive).repr() - ) - ); - mm.set_merge_behavior(&"a", MergeBehavior::Theirs); - assert_eq!( - mm.get_mark(&"a"), - Some( - Mark::Used.repr() - | Mark::Required.repr() - | Mark::MergeBehavior(MergeBehavior::Theirs).repr() - ) - ); - mm.set_merge_behavior(&"a", MergeBehavior::Ours); - assert_eq!( - mm.get_mark(&"a"), - Some( - Mark::Used.repr() - | Mark::Required.repr() - | Mark::MergeBehavior(MergeBehavior::Ours).repr() - ) - ); - } - - #[test] - fn test_unused() { - { - let mut mm = MarkMap::new(); - assert!(mm.insert("a", "test").is_none()); - mm.mark_used(&"a"); - assert_eq!(mm.get_mark(&"a"), Some(Mark::Used.repr())); - let empty: &[(&&str, &&str)] = &[]; - assert_eq!(mm.unused().collect::>(), empty); - } - - { - let mut mm = MarkMap::new(); - assert!(mm.insert("a", "test").is_none()); - mm.mark_used(&"a"); - assert!(mm.insert("b", "unused").is_none()); - assert_eq!(mm.get_mark(&"a"), Some(Mark::Used.repr())); - assert_eq!(mm.get_mark(&"b"), Some(0)); - assert_eq!( - mm.unused().collect::>(), - vec![(&"b", &"unused")] - ); - } - } - - #[test] - fn test_required() { - { - let mut mm = MarkMap::new(); - let empty: &[&String] = &[]; - mm.mark_required(&"a"); - assert!(mm.insert("a", "test").is_none()); - assert_eq!(mm.get_mark(&"a"), Some(Mark::Required.repr())); - assert_eq!(mm.missing().as_slice(), empty); - } - - { - let mut mm = MarkMap::new(); - mm.mark_required(&"a"); - mm.insert("for", "inference"); - assert_eq!(mm.get_mark(&"a"), Some(Mark::Required.repr())); - assert_eq!(mm.missing().as_slice(), &[&"a"]); - } - } - - #[test] - fn test_merge_empty() { - { - let mut ours: MarkMap<&str, &str> = MarkMap::new(); - let theirs: MarkMap<&str, &str> = MarkMap::new(); - assert!(ours.merge_from(theirs).is_ok()); - } - { - let mut ours: MarkMap<&str, &str> = MarkMap::new(); - let theirs: MarkMap<&str, &str> = MarkMap::new(); - ours.mark_required(&"a"); - assert!(ours.merge_from(theirs).is_ok()); - assert_eq!(ours.missing().as_slice(), &[&"a"]); - } - - { - let mut ours: MarkMap<&str, &str> = MarkMap::new(); - let theirs: MarkMap<&str, &str> = MarkMap::new(); - ours.mark_required(&"a"); - ours.set_merge_behavior(&"a", MergeBehavior::Ours); - assert!(ours.merge_from(theirs).is_ok()); - assert_eq!(ours.missing().as_slice(), &[&"a"]); - } - - { - let mut ours: MarkMap<&str, &str> = MarkMap::new(); - let theirs: MarkMap<&str, &str> = MarkMap::new(); - ours.mark_required(&"a"); - ours.set_merge_behavior(&"a", MergeBehavior::Theirs); - assert!(ours.merge_from(theirs).is_ok()); - assert_eq!(ours.missing().as_slice(), &[&"a"]); - } - } - - #[test] - fn test_merge_conflict() { - { - let mut ours = MarkMap::new(); - let mut theirs = MarkMap::new(); - ours.insert("a", "ours"); - ours.set_merge_behavior(&"a", MergeBehavior::MutuallyExclusive); - theirs.insert("a", "theirs"); - assert!(ours.merge_from(theirs).is_err()); - assert_eq!(ours.get(&"a"), Some(&"ours")); - } - { - // Default behavior should match `MutuallyExclusive` - let mut ours = MarkMap::new(); - let mut theirs = MarkMap::new(); - ours.insert("a", "ours"); - theirs.insert("a", "theirs"); - assert!(ours.merge_from(theirs).is_err()); - assert_eq!(ours.get(&"a"), Some(&"ours")); - } - } - - #[test] - fn test_merge_ours() { - { - let mut ours: MarkMap<&str, &str> = MarkMap::new(); - let mut theirs: MarkMap<&str, &str> = MarkMap::new(); - ours.insert("a", "ours"); - theirs.set_merge_behavior(&"a", MergeBehavior::MutuallyExclusive); - theirs.mark_required(&"b"); - assert!(ours.merge_from(theirs).is_ok()); - assert_eq!(ours.get(&"a"), Some(&"ours")); - assert!(ours.is_required(&"b")); - } - { - // Default behavior should match MutuallyExclusive - let mut ours: MarkMap<&str, &str> = MarkMap::new(); - let mut theirs: MarkMap<&str, &str> = MarkMap::new(); - theirs.mark_required(&"b"); - ours.insert("a", "ours"); - assert!(ours.merge_from(theirs).is_ok()); - assert_eq!(ours.get(&"a"), Some(&"ours")); - assert!(ours.is_required(&"b")); - } - - { - let mut ours: MarkMap<&str, &str> = MarkMap::new(); - let mut theirs: MarkMap<&str, &str> = MarkMap::new(); - theirs.mark_required(&"b"); - ours.insert("a", "ours"); - ours.set_merge_behavior(&"a", MergeBehavior::MutuallyExclusive); - assert!(ours.merge_from(theirs).is_ok()); - assert_eq!(ours.get(&"a"), Some(&"ours")); - assert!(ours.is_required(&"b")); - } - { - let mut ours = MarkMap::new(); - let mut theirs = MarkMap::new(); - theirs.mark_required(&"b"); - ours.insert("a", "ours"); - ours.set_merge_behavior(&"a", MergeBehavior::Ours); - - theirs.insert("a", "theirs"); - assert!(ours.merge_from(theirs).is_ok()); - assert_eq!(ours.get(&"a"), Some(&"ours")); - assert!(ours.is_required(&"b")); - } - } - - #[test] - fn test_merge_theirs() { - { - let mut ours: MarkMap<&str, &str> = MarkMap::new(); - let mut theirs: MarkMap<&str, &str> = MarkMap::new(); - theirs.mark_required(&"b"); - ours.set_merge_behavior(&"a", MergeBehavior::MutuallyExclusive); - theirs.insert("a", "theirs"); - assert!(ours.merge_from(theirs).is_ok()); - assert_eq!(ours.get(&"a"), Some(&"theirs")); - assert!(ours.is_required(&"b")); - } - - { - // Should match default behavior. - let mut ours: MarkMap<&str, &str> = MarkMap::new(); - let mut theirs: MarkMap<&str, &str> = MarkMap::new(); - theirs.mark_required(&"b"); - theirs.insert("a", "theirs"); - assert!(ours.merge_from(theirs).is_ok()); - assert_eq!(ours.get(&"a"), Some(&"theirs")); - assert!(ours.is_required(&"b")); - } - { - let mut ours = MarkMap::new(); - let mut theirs = MarkMap::new(); - theirs.mark_required(&"b"); - ours.insert("a", "ours"); - ours.set_merge_behavior(&"a", MergeBehavior::Theirs); - theirs.insert("a", "theirs"); - assert!(ours.merge_from(theirs).is_ok()); - assert_eq!(ours.get(&"a"), Some(&"theirs")); - assert!(ours.is_required(&"b")); - } - } - - #[test] - fn test_merge_both() { - { - let mut ours = MarkMap::new(); - let mut theirs = MarkMap::new(); - theirs.mark_required(&"b"); - ours.insert("a", "ours"); - ours.set_merge_behavior(&"a", MergeBehavior::MutuallyExclusive); - theirs.insert("b", "theirs"); - theirs.set_merge_behavior(&"b", MergeBehavior::MutuallyExclusive); - assert!(ours.merge_from(theirs).is_ok()); - assert_eq!(ours.get(&"a"), Some(&"ours")); - assert_eq!(ours.get(&"b"), Some(&"theirs")); - assert!(ours.is_required(&"b")); - } - } - - #[test] - fn test_vacant() { - let mut mm = MarkMap::new(); - let v = mm.entry("a"); - match v { - Entry::Occupied(_) => { - panic!("Expected vacant entry"); - } - Entry::Vacant(v) => { - let mut o = v.insert_entry("ours"); - o.mark_required(); - o.mark_used(); - assert_eq!(o.get(), &"ours"); - assert!(o.is_required()); - assert!(o.is_used()); - } - } - - assert_eq!(mm.get(&"a"), Some(&"ours")); - assert!(mm.is_required(&"a")); - assert!(mm.is_used(&"a")); - } - - #[test] - fn test_merge_many() { - let mut mm = MarkMap::new(); - mm.insert("a", ()); - mm.insert("b", ()); - - let mut mm2 = MarkMap::new(); - mm2.insert("x", ()); - mm2.insert("y", ()); - - mm.merge_from(mm2).unwrap(); - assert_eq!( - mm.keys().cloned().collect::>(), - vec!["a", "b", "x", "y"] - ); - } - - #[test] - fn test_default_merge_behavior() { - let mut mm = MarkMap::new(); - mm.set_default_merge_behavior(MergeBehavior::Ours); - mm.insert("a", "mm"); - mm.insert("b", "mm"); - mm.set_merge_behavior(&"b", MergeBehavior::Theirs); - - let mut mm2 = MarkMap::new(); - mm2.insert("x", "mm2"); - mm2.insert("b", "mm2"); - mm2.insert("a", "mm2"); - - mm.merge_from(mm2).unwrap(); - assert_eq!( - mm.into_iter().collect::>(), - vec![(&"a", &"mm"), (&"b", &"mm2"), (&"x", &"mm2")] - ); - } - - #[test] - fn test_vacant_entry_required() { - let mut mm = MarkMap::new(); - // To test the first case we want a marked key with no value associated to it. - mm.mark_used(&"a"); - let e = mm.entry("a"); - match e { - Entry::Occupied(_) => panic!("Expected unoccupied entry"), - Entry::Vacant(mut e) => { - e.mark_required(); - e.insert_entry("a"); - } - } - assert!(mm.is_required(&"a")); - assert!(mm.is_used(&"a")); - // For the second case we want an unmarked key with another key in it's binary search pos. - mm.insert("c", "c"); - let e = mm.entry("b"); - match e { - Entry::Occupied(_) => panic!("Expected unoccupied entry"), - Entry::Vacant(mut e) => { - e.mark_required(); - } - } - assert!(mm.is_required(&"b")); - assert!(!mm.is_required(&"c")); - } - - #[test] - fn test_vacant_entry_merge_behavior() { - let mut mm = MarkMap::new(); - // To test the first case we want a marked key with no value associated to it. - mm.mark_used(&"a"); - let mut mm2 = MarkMap::new(); - mm2.insert("a", "a2"); - mm2.insert("a", "c2"); - let e = mm.entry("a"); - match e { - Entry::Occupied(_) => panic!("Expected unoccupied entry"), - Entry::Vacant(mut e) => { - e.set_merge_behavior(MergeBehavior::Ours); - e.insert_entry("a1"); - } - } - assert_eq!( - mm.get_mark(&"a"), - Some(Mark::MergeBehavior(MergeBehavior::Ours).repr() | Mark::Used.repr()) - ); - // For the second case we want an unmarked key with another key in it's binary search pos. - mm.insert("c", "c"); - let e = mm.entry("b"); - match e { - Entry::Occupied(_) => panic!("Expected unoccupied entry"), - Entry::Vacant(mut e) => { - e.set_merge_behavior(MergeBehavior::Theirs); - } - } - assert_eq!( - mm.get_mark(&"b"), - Some(Mark::MergeBehavior(MergeBehavior::Theirs).repr()) - ); - assert_eq!(mm.get_mark(&"c"), Some(0)); - } -} diff --git a/cfgrammar/src/lib/mod.rs b/cfgrammar/src/lib/mod.rs index bb4d47144..f5bd84065 100644 --- a/cfgrammar/src/lib/mod.rs +++ b/cfgrammar/src/lib/mod.rs @@ -59,14 +59,12 @@ use wincode::{SchemaRead, SchemaWrite}; #[doc(hidden)] pub mod header; mod idxnewtype; -#[doc(hidden)] -pub mod markmap; pub mod newlinecache; pub mod span; pub mod yacc; pub use newlinecache::NewlineCache; -pub use span::{Location, Span, Spanned}; +pub use span::{Span, Spanned}; #[cfg(test)] pub mod test_utils; diff --git a/cfgrammar/src/lib/span.rs b/cfgrammar/src/lib/span.rs index 2c2d5366a..7b644d498 100644 --- a/cfgrammar/src/lib/span.rs +++ b/cfgrammar/src/lib/span.rs @@ -66,18 +66,3 @@ impl ToTokens for Span { tokens.append_all(quote! {::cfgrammar::Span::new(#start, #end)}); } } - -/// A possibly inexact location which could either be a `Span`, -/// a command-line option, or some other location described textually. -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum Location { - Span(Span), - CommandLine, - Other(String), -} - -impl From for Location { - fn from(span: Span) -> Location { - Location::Span(span) - } -} diff --git a/cfgrammar/src/lib/yacc/ast.rs b/cfgrammar/src/lib/yacc/ast.rs index 2689174f5..a54f5f816 100644 --- a/cfgrammar/src/lib/yacc/ast.rs +++ b/cfgrammar/src/lib/yacc/ast.rs @@ -126,22 +126,20 @@ impl ASTWithValidityInfo { /// Returns all the keys starting with `{prefix}.` for the `prefix` from the `%grmtools` section. pub fn iter_prefix_keys(&self, prefix: &str) -> impl Iterator { let prefix = format!("{prefix}."); - (&self.grmtools_section) - .into_iter() - .filter_map(move |(key, val)| { - let HeaderValue(span, _) = val; - if key.starts_with(&prefix) { - Some((key.as_str(), *span)) - } else { - None - } - }) + self.grmtools_section.iter().filter_map(move |(key, val)| { + let HeaderValue(span, _) = val; + if key.starts_with(&prefix) { + Some((key.as_str(), *span)) + } else { + None + } + }) } /// Returns all of the unique prefixes for all keys in the `%grmtools` section. pub fn iter_prefixes(&self) -> impl Iterator { let mut prefixes = HashSet::new(); - for (key, _) in &self.grmtools_section { + for key in self.grmtools_section.keys() { if let Some(prefix) = RE_CRATE_DOT.find(key) { prefixes.insert( prefix diff --git a/cfgrammar/src/lib/yacc/parser.rs b/cfgrammar/src/lib/yacc/parser.rs index 7af9885ba..6604a03ae 100644 --- a/cfgrammar/src/lib/yacc/parser.rs +++ b/cfgrammar/src/lib/yacc/parser.rs @@ -16,7 +16,7 @@ use wincode::{SchemaRead, SchemaWrite}; use crate::{ Span, Spanned, - header::{GrmtoolsSectionParser, Header, HeaderErrorKind, KEY_CRATE_MAP}, + header::{GrmtoolsSectionParser, Header, HeaderErrorKind}, }; pub type YaccGrammarResult = Result>; @@ -375,17 +375,7 @@ impl YaccParser<'_> { } pub(crate) fn build(self) -> (GrammarAST, Header) { - let mut header = self.header.expect("set by parse()"); - // At this point we still have mutable access to the header, so it is a convenient place - // to mark keys used. It would be less error prone if we did this at the point where keys - // are used. However at some points where we do lookups, there are shared references to the - // header making it difficult to get mutable access. - for (key_name, crate_name) in KEY_CRATE_MAP.iter() { - if ["cfgrammar", "lrpar"].contains(crate_name) { - header.mark_used(&format!("{crate_name}.{key_name}")); - } - } - (self.ast, header) + (self.ast, self.header.expect("set by parse()")) } fn parse_declarations( diff --git a/lrlex/src/lib/codegen.rs b/lrlex/src/lib/codegen.rs index 015296971..365e1417e 100644 --- a/lrlex/src/lib/codegen.rs +++ b/lrlex/src/lib/codegen.rs @@ -1,11 +1,13 @@ use cfgrammar::{ - Location, Span, - header::{GrmtoolsSectionParser, Header, HeaderError, HeaderValue}, - markmap::MergeError, + Span, + header::{GrmtoolsSectionParser, Header, HeaderError, HeaderErrorKind, HeaderValue}, }; use lrpar::LexerTypes; -use crate::{LRNonStreamingLexerDef, LexBuildError, LexFlags, LexerDef, LexerKind, Visibility}; +use crate::{ + DEFAULT_LEX_FLAGS, LRNonStreamingLexerDef, LexBuildError, LexFlags, LexerDef, LexerKind, + Visibility, +}; use proc_macro2::{Ident, TokenStream}; use quote::{ToTokens, TokenStreamExt, format_ident, quote}; use regex::Regex; @@ -23,27 +25,20 @@ static RE_TOKEN_ID: LazyLock = #[non_exhaustive] pub(crate) enum LexerSrcEnvError { - GrmtoolsSectionParseError(Vec>), - GrmtoolsSectionMergeError(MergeError>>), - GrmtoolsSectionLookupError(HeaderError), + GrmtoolsSectionError(Vec>), + GrmtoolsSectionLookupError(HeaderError), MissingModName, LexBuildErrors(Vec), } impl From>> for LexerSrcEnvError { fn from(it: Vec>) -> Self { - LexerSrcEnvError::GrmtoolsSectionParseError(it) - } -} - -impl From>>> for LexerSrcEnvError { - fn from(it: MergeError>>) -> Self { - LexerSrcEnvError::GrmtoolsSectionMergeError(it) + LexerSrcEnvError::GrmtoolsSectionError(it) } } -impl From> for LexerSrcEnvError { - fn from(it: HeaderError) -> Self { +impl From> for LexerSrcEnvError { + fn from(it: HeaderError) -> Self { LexerSrcEnvError::GrmtoolsSectionLookupError(it) } } @@ -51,12 +46,11 @@ impl From> for LexerSrcEnvError { impl fmt::Display for LexerSrcEnvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&match self { - Self::GrmtoolsSectionParseError(errs) => errs + Self::GrmtoolsSectionError(errs) => errs .iter() .map(|e| e.to_string()) .collect::>() .join("\n"), - Self::GrmtoolsSectionMergeError(e) => e.to_string(), Self::GrmtoolsSectionLookupError(e) => e.to_string(), Self::MissingModName => "Code generator requires a mod name".to_string(), Self::LexBuildErrors(_) => "Lex build error".to_string(), @@ -71,13 +65,13 @@ where { src: &'a str, fallback_modname: Option, - header: Header, phantom_storaget: PhantomData, } pub(crate) struct LexerBuildEnvArgs { mod_name: Option, lexerkind: Option, + lex_flags: LexFlags, visibility: Visibility, } @@ -86,6 +80,7 @@ impl LexerBuildEnvArgs { Self { mod_name: None, lexerkind: None, + lex_flags: DEFAULT_LEX_FLAGS, visibility: Visibility::Private, } } @@ -104,6 +99,11 @@ impl LexerBuildEnvArgs { self.visibility = visibility; self } + + pub(crate) fn lex_flags(mut self, lex_flags: LexFlags) -> Self { + self.lex_flags = lex_flags; + self + } } pub(crate) struct LexerBuildEnv @@ -113,7 +113,6 @@ where { mod_name: String, lexerkind: LexerKind, - header: Header, lex_flags: LexFlags, visibility: Visibility, lexerdef: LRNonStreamingLexerDef, @@ -133,11 +132,7 @@ where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, { - pub(crate) fn new_with_header( - src: &'a str, - path: Option<&Path>, - header: Header, - ) -> LexerSrcEnv<'a, LexerTypesT> { + pub(crate) fn new(src: &'a str, path: Option<&Path>) -> LexerSrcEnv<'a, LexerTypesT> { let fallback_modname = if let Some(lexerp) = path { // The user hasn't specified a module name, so we create one automatically: what we // do is strip off all the filename extensions (note that it's likely that inp ends @@ -158,16 +153,10 @@ where LexerSrcEnv { src, fallback_modname, - header, phantom_storaget: PhantomData, } } - fn merge_headers(&mut self) -> Result<(), LexerSrcEnvError> { - let (parsed_header, _) = self.parse_header()?; - Ok(self.header.merge_from(parsed_header)?) - } - /// Looks up the `mod_name` from the `args`, and defaults to /// the `{filename}_l` with any file extenstion stripped off. fn resolve_mod_name(&self, args: &LexerBuildEnvArgs) -> Result { @@ -185,29 +174,102 @@ where GrmtoolsSectionParser::new(self.src, false).parse() } + fn merge_lex_flags( + &self, + lex_flags: &mut LexFlags, + header: &Header, + ) -> Result<(), LexerSrcEnvError> { + macro_rules! cvt_bool { + ($key:literal,$field:ident,$errs:ident) => { + if let Some(header_value) = header.get($key) { + if lex_flags.$field.is_some() { + $errs.push(HeaderError { + kind: HeaderErrorKind::ConflictingEntry("Already specified by builder"), + locations: vec![header_value.0], + }); + } else { + match header_value.try_into() { + Ok(flag) => { + lex_flags.$field = Some(flag); + } + Err(e) => { + $errs.push(e); + } + } + } + } + }; + } + + macro_rules! cvt_num { + ($key:literal,$field:ident,$typ:ty,$errs:ident) => { + if let Some(header_value) = header.get($key) { + if lex_flags.$field.is_some() { + $errs.push(HeaderError { + kind: HeaderErrorKind::ConflictingEntry("Already specified by builder"), + locations: vec![header_value.0], + }); + } else { + let val: Result<$typ, HeaderError> = header_value.try_into(); + match val { + Ok(num) => { + lex_flags.$field = Some(num); + } + Err(e) => { + $errs.push(e); + } + } + } + } + }; + } + + let mut errs = Vec::new(); + cvt_bool!( + "lrlex.allow_wholeline_comments", + allow_wholeline_comments, + errs + ); + cvt_bool!("lrlex.posix_escapes", posix_escapes, errs); + cvt_bool!("regex.dot_matches_new_line", dot_matches_new_line, errs); + cvt_bool!("regex.multi_line", multi_line, errs); + cvt_bool!("regex.swap_greed", swap_greed, errs); + cvt_bool!("regex.ignore_whitespace", ignore_whitespace, errs); + cvt_bool!("regex.unicode", unicode, errs); + cvt_bool!("regex.case_insensitive", case_insensitive, errs); + cvt_num!("regex.size_limit", size_limit, usize, errs); + cvt_num!("regex.dfa_size_limit", dfa_size_limit, usize, errs); + cvt_num!("regex.nest_limit", nest_limit, u32, errs); + if errs.is_empty() { + Ok(()) + } else { + Err(LexerSrcEnvError::GrmtoolsSectionError(errs)) + } + } + pub(crate) fn build_env( - mut self, - args: LexerBuildEnvArgs, + self, + mut args: LexerBuildEnvArgs, ) -> Result, LexerSrcEnvError> where LexerTypesT: LexerTypes, usize: num_traits::AsPrimitive, LexerTypesT::StorageT: TryFrom, { - self.merge_headers()?; + let (header, _) = self.parse_header()?; + self.merge_lex_flags(&mut args.lex_flags, &header)?; let mod_name = self.resolve_mod_name(&args)?; - self.header.mark_used(&"lrlex.lexerkind".to_string()); let lexerkind = match args.lexerkind { Some(lexerkind) => lexerkind, None => { - if let Some(HeaderValue(_, lk_val)) = self.header.get("lrlex.lexerkind") { + if let Some(HeaderValue(_, lk_val)) = header.get("lrlex.lexerkind") { LexerKind::try_from(lk_val)? } else { LexerKind::LRNonStreamingLexer } } }; - let lex_flags = LexFlags::try_from(&mut self.header)?; + let lex_flags = args.lex_flags; let (lexerdef, lex_flags): (LRNonStreamingLexerDef, LexFlags) = match lexerkind { LexerKind::LRNonStreamingLexer => { @@ -223,7 +285,6 @@ where mod_name, lexerkind, visibility: args.visibility, - header: self.header, lex_flags, lexerdef, }) @@ -249,10 +310,6 @@ where &self.lexerkind } - pub(crate) fn header(&self) -> &Header { - &self.header - } - pub(crate) fn mod_name(&self) -> &String { &self.mod_name } diff --git a/lrlex/src/lib/ctbuilder.rs b/lrlex/src/lib/ctbuilder.rs index 7fab89341..2b22469f7 100644 --- a/lrlex/src/lib/ctbuilder.rs +++ b/lrlex/src/lib/ctbuilder.rs @@ -1,9 +1,8 @@ //! Build grammars at run-time. use cfgrammar::{ - header::{Header, HeaderError, HeaderErrorKind, HeaderValue, Value}, - markmap::MergeBehavior, - span::{Location, Span}, + header::{HeaderError, HeaderErrorKind, HeaderValue, Value}, + span::Span, }; use glob::glob; use lrpar::{ @@ -30,7 +29,7 @@ use std::{ use wincode::SchemaWrite; use crate::{ - DefaultLexerTypes, LRNonStreamingLexer, LexerDef, + DefaultLexerTypes, LRNonStreamingLexer, LexFlags, LexerDef, UNSPECIFIED_LEX_FLAGS, codegen::{LexerBuildEnvArgs, LexerSrcEnv, LexerSrcEnvError}, }; @@ -56,12 +55,18 @@ impl TryFrom<&Value> for LexerKind { Ok(LexerKind::LRNonStreamingLexer) } _ => Err(HeaderError { - kind: HeaderErrorKind::ConversionError("LexerKind", "Expected `LexerKind`"), + kind: HeaderErrorKind::ConversionError( + "LexerKind", + "Expected `LexerKind`".to_string(), + ), locations: vec![loc.clone()], }), }, val => Err(HeaderError { - kind: HeaderErrorKind::ConversionError("LexerKind", "Expected `LexerKind`"), + kind: HeaderErrorKind::ConversionError( + "LexerKind", + "Expected `LexerKind`".to_string(), + ), locations: vec![val.primary_location().clone()], }), } @@ -149,7 +154,7 @@ where allow_missing_tokens_in_parser: bool, warnings_are_errors: bool, show_warnings: bool, - header: Header, + lex_flags: LexFlags, #[cfg(test)] inspect_lexerkind_cb: Option Result<(), Box>>>, } @@ -201,8 +206,6 @@ where /// .build()?; /// ``` pub fn new_with_lexemet() -> Self { - let mut header = Header::new(); - header.set_default_merge_behavior(MergeBehavior::Ours); CTLexerBuilder { lrpar_config: None, lexer_path: None, @@ -216,7 +219,7 @@ where allow_missing_tokens_in_parser: false, warnings_are_errors: false, show_warnings: true, - header, + lex_flags: UNSPECIFIED_LEX_FLAGS, #[cfg(test)] inspect_lexerkind_cb: None, } @@ -402,37 +405,37 @@ where let args = LexerBuildEnvArgs::new() .mod_name(self.mod_name.map(|s| s.to_string())) .lexerkind(self.lexerkind) - .visibility(self.visibility); - let mut build_env = - LexerSrcEnv::::new_with_header(&lex_src, Some(lexerp), self.header) - .build_env(args) - .map_err(|e| match e { - LexerSrcEnvError::GrmtoolsSectionParseError(es) => { - let mut out = String::new(); - out.push_str(&format!( - "\n{ERROR}{}\n", - lex_diag.file_location_msg(" parsing the `%grmtools` section", None) - )); - for e in es { - out.push_str(&indent(" ", &lex_diag.format_error(e).to_string())); - out.push('\n'); - } - ErrorString(out) + .visibility(self.visibility) + .lex_flags(self.lex_flags); + let mut build_env = LexerSrcEnv::::new(&lex_src, Some(lexerp)) + .build_env(args) + .map_err(|e| match e { + LexerSrcEnvError::GrmtoolsSectionError(es) => { + let mut out = String::new(); + out.push_str(&format!( + "\n{ERROR}{}\n", + lex_diag.file_location_msg(" parsing the `%grmtools` section", None) + )); + for e in es { + out.push_str(&indent(" ", &lex_diag.format_error(e).to_string())); + out.push('\n'); } - LexerSrcEnvError::LexBuildErrors(errs) => { - let mut out = String::new(); - out.push_str(&format!( - "\n{ERROR}{}\n", - lex_diag.file_location_msg(" building the lexer", None) - )); - for e in errs { - out.push_str(&indent(" ", &lex_diag.format_error(e).to_string())); - out.push('\n'); - } - ErrorString(out) + ErrorString(out) + } + LexerSrcEnvError::LexBuildErrors(errs) => { + let mut out = String::new(); + out.push_str(&format!( + "\n{ERROR}{}\n", + lex_diag.file_location_msg(" building the lexer", None) + )); + for e in errs { + out.push_str(&indent(" ", &lex_diag.format_error(e).to_string())); + out.push('\n'); } - e => ErrorString(e.to_string()), - })?; + ErrorString(out) + } + e => ErrorString(e.to_string()), + })?; #[cfg(test)] if let Some(inspect_lexerkind_cb) = self.inspect_lexerkind_cb { @@ -519,17 +522,6 @@ where None }; - let unused_header_values = build_env - .header() - .unused() - .map(|(s, _)| s.to_string()) - .collect::>(); - if !unused_header_values.is_empty() { - return Err( - format!("Unused header values: {}", unused_header_values.join(", ")).into(), - ); - } - let code_gen = build_env .code_generator(self.rule_ids_map, env!("VERGEN_BUILD_TIMESTAMP")) .map_err(|e| match e {})?; @@ -788,14 +780,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn allow_wholeline_comments(mut self, flag: bool) -> Self { - let key = "lrlex.allow_wholeline_comments".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.allow_wholeline_comments = Some(flag); self } @@ -804,14 +789,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn dot_matches_new_line(mut self, flag: bool) -> Self { - let key = "regex.dot_matches_new_line".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.dot_matches_new_line = Some(flag); self } @@ -820,14 +798,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn multi_line(mut self, flag: bool) -> Self { - let key = "regex.multi_line".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.multi_line = Some(flag); self } @@ -836,14 +807,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn posix_escapes(mut self, flag: bool) -> Self { - let key = "lrlex.posix_escapes".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.posix_escapes = Some(flag); self } @@ -852,14 +816,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn octal(mut self, flag: bool) -> Self { - let key = "regex.octal".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.octal = Some(flag); self } @@ -868,14 +825,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn swap_greed(mut self, flag: bool) -> Self { - let key = "regex.swap_greed".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.swap_greed = Some(flag); self } @@ -884,14 +834,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn ignore_whitespace(mut self, flag: bool) -> Self { - let key = "regex.ignore_whitespace".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.ignore_whitespace = Some(flag); self } @@ -900,14 +843,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn unicode(mut self, flag: bool) -> Self { - let key = "regex.unicode".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.unicode = Some(flag); self } @@ -916,14 +852,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn case_insensitive(mut self, flag: bool) -> Self { - let key = "regex.case_insensitive".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Bool(flag, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.case_insensitive = Some(flag); self } @@ -932,14 +861,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn size_limit(mut self, sz: usize) -> Self { - let key = "regex.size_limit".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Num(sz as u64, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.size_limit = Some(sz); self } @@ -948,14 +870,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn dfa_size_limit(mut self, sz: usize) -> Self { - let key = "regex.dfa_size_limit".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Num(sz as u64, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.dfa_size_limit = Some(sz); self } @@ -964,14 +879,7 @@ where /// /// Setting this flag will override the same flag within a `%grmtools` section. pub fn nest_limit(mut self, lim: u32) -> Self { - let key = "regex.nest_limit".to_string(); - self.header.insert( - key, - HeaderValue( - Location::Other("CTLexerBuilder".to_string()), - Value::Num(lim as u64, Location::Other("CTLexerBuilder".to_string())), - ), - ); + self.lex_flags.nest_limit = Some(lim); self } diff --git a/lrlex/src/lib/lexer.rs b/lrlex/src/lib/lexer.rs index fa6dfb5fe..029cdeed3 100644 --- a/lrlex/src/lib/lexer.rs +++ b/lrlex/src/lib/lexer.rs @@ -10,7 +10,6 @@ use std::{ use cfgrammar::{ NewlineCache, Span, header::{GrmtoolsSectionParser, Header, HeaderError, HeaderErrorKind, HeaderValue, Value}, - span::Location, }; use num_traits::{AsPrimitive, PrimInt, Unsigned}; use regex::{Regex, RegexBuilder}; @@ -64,11 +63,13 @@ impl TryFrom<&mut Header> for LexFlags { } = &mut lex_flags; macro_rules! cvt_flag { ($prefix:ident, $it:ident) => { - header.mark_used(&stringify!($prefix.$it).to_string()); *$it = match header.get(stringify!($prefix.$it)) { Some(HeaderValue(_, Value::Bool(flag, _))) => Some(*flag), Some(HeaderValue(_, val)) => Err(HeaderError { - kind: HeaderErrorKind::ConversionError("LexFlags", "Expected boolean"), + kind: HeaderErrorKind::ConversionError( + "LexFlags", + "Expected boolean".to_string(), + ), locations: vec![val.primary_location().clone()], })?, None => None, @@ -86,11 +87,13 @@ impl TryFrom<&mut Header> for LexFlags { cvt_flag!(regex, unicode); macro_rules! cvt_num { ($prefix:ident, $it:ident, $num_ty: ty) => { - header.mark_used(&stringify!($prefix.$it).to_string()); *$it = match header.get(stringify!($prefix.$it)) { Some(HeaderValue(_, Value::Num(n, _))) => Some(*n as $num_ty), Some(HeaderValue(_, val)) => Err(HeaderError { - kind: HeaderErrorKind::ConversionError("LexFlags", "Expected numeric"), + kind: HeaderErrorKind::ConversionError( + "LexFlags", + "Expected numeric".to_string(), + ), locations: vec![val.primary_location().clone()], })?, None => None, @@ -104,67 +107,6 @@ impl TryFrom<&mut Header> for LexFlags { } } -impl From<&LexFlags> for Header { - fn from(flags: &LexFlags) -> Header { - let mut header = Header::new(); - let LexFlags { - dot_matches_new_line, - multi_line, - octal, - posix_escapes, - allow_wholeline_comments, - case_insensitive, - swap_greed, - ignore_whitespace, - unicode, - size_limit, - dfa_size_limit, - nest_limit, - } = flags; - macro_rules! cvt_flag { - ($it: ident) => { - $it.map(|x| { - header.insert( - stringify!($it).to_string(), - HeaderValue( - Location::Other("From<&LexFlags>".to_string()), - Value::Bool(x, Location::Other("From<&LexFlags>".to_string())), - ), - ) - }); - }; - } - cvt_flag!(dot_matches_new_line); - cvt_flag!(multi_line); - cvt_flag!(octal); - cvt_flag!(posix_escapes); - cvt_flag!(allow_wholeline_comments); - cvt_flag!(case_insensitive); - cvt_flag!(swap_greed); - cvt_flag!(ignore_whitespace); - cvt_flag!(unicode); - - macro_rules! cvt_num { - ($it: ident) => { - $it.map(|x| { - header.insert( - stringify!($it).to_string(), - HeaderValue( - Location::Other("From<&LexFlags>".to_string()), - Value::Num(x as u64, Location::Other("From<&LexFlags>".to_string())), - ), - ) - }); - }; - } - cvt_num!(size_limit); - cvt_num!(dfa_size_limit); - cvt_num!(nest_limit); - - header - } -} - /// LexFlags with flags set to default values. #[doc(hidden)] pub const DEFAULT_LEX_FLAGS: LexFlags = LexFlags { diff --git a/lrlex/src/lib/mod.rs b/lrlex/src/lib/mod.rs index 000d44259..6d806f79d 100644 --- a/lrlex/src/lib/mod.rs +++ b/lrlex/src/lib/mod.rs @@ -140,7 +140,7 @@ impl fmt::Display for LexBuildError { impl From> for LexBuildError { fn from(e: HeaderError) -> LexBuildError { LexBuildError { - kind: LexErrorKind::Header(e.kind, e.spanskind()), + kind: LexErrorKind::Header(e.clone().kind, e.spanskind()), spans: e.locations, } } diff --git a/lrlex/src/main.rs b/lrlex/src/main.rs index 0320ddae7..3eebbacec 100644 --- a/lrlex/src/main.rs +++ b/lrlex/src/main.rs @@ -95,7 +95,6 @@ fn main() -> Result<(), Box> { process::exit(1); } }; - header.mark_used(&"lrlex.lexerkind".to_string()); let lexerkind = if let Some(HeaderValue(_, lk_val)) = header.get("lrlex.lexerkind") { LexerKind::try_from(lk_val)? } else { @@ -122,18 +121,6 @@ fn main() -> Result<(), Box> { return Err(ErrorString("Unrecognized lexer kind".to_string()))?; } }; - { - let unused_header_values = header - .unused() - .map(|(s, _)| s.to_string()) - .collect::>(); - if !unused_header_values.is_empty() { - Err(ErrorString(format!( - "Unused header values: {}", - unused_header_values.join(", ") - )))? - } - } let input = &read_file(&matches.free[1]); for r in lexerdef.lexer(input).iter() { match r { diff --git a/lrpar/cttests/src/grmtools_section.test b/lrpar/cttests/src/grmtools_section.test index 69f3d0522..6ce8837ce 100644 --- a/lrpar/cttests/src/grmtools_section.test +++ b/lrpar/cttests/src/grmtools_section.test @@ -167,11 +167,11 @@ grammar: | KEY_CRATE_MAP, RE_CRATE_DOT, }, - markmap::Entry, }; use std::{ collections::HashMap, + collections::hash_map::Entry, sync::LazyLock }; diff --git a/lrpar/src/lib/parser.rs b/lrpar/src/lib/parser.rs index c8b987940..41f4e9515 100644 --- a/lrpar/src/lib/parser.rs +++ b/lrpar/src/lib/parser.rs @@ -649,7 +649,7 @@ impl TryFrom<&Value> for RecoveryKind { _ => Err(HeaderError { kind: HeaderErrorKind::ConversionError( "RecoveryKind", - "Cannot convert to RecoveryKind", + "Cannot convert to RecoveryKind".to_string(), ), locations: vec![*loc], }), @@ -657,7 +657,7 @@ impl TryFrom<&Value> for RecoveryKind { value => Err(HeaderError { kind: HeaderErrorKind::ConversionError( "RecoveryKind", - "Cannot convert to RecoveryKind", + "Cannot convert to RecoveryKind".to_string(), ), locations: vec![*value.primary_location()], }),