Skip to content

Implement optional modifiers #105

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ fn tokenize(line: &str) -> StrResult<Line> {
Line::ModuleEnd
} else if let Some(rest) = head.strip_prefix('.') {
for part in rest.split('.') {
validate_ident(part)?;
validate_ident(part.strip_suffix('?').unwrap_or(part))?;
}
let value = decode_value(tail.ok_or("missing char")?)?;
Line::Variant(ModifierSet::from_raw_dotted(rest), value)
Expand Down
107 changes: 102 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ impl Symbol {
match self {
Self::Single(c) => modifs.is_empty().then_some((*c, None)),
Self::Multi(list) => {
modifs.best_match_in(list.iter().copied().map(|(m, c, d)| (m, (c, d))))
modifs.best_match_in(list.iter().copied().map(|(ms, c, d)| (ms, (c, d))))
}
}
}
Expand Down Expand Up @@ -107,7 +107,7 @@ impl Symbol {
/// Possible modifiers for this symbol.
pub fn modifiers(&self) -> impl Iterator<Item = &str> + '_ {
self.variants()
.flat_map(|(m, _, _)| m.into_iter())
.flat_map(|(ms, _, _)| ms.into_iter().map(|m| m.name()))
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
}
Expand Down Expand Up @@ -170,14 +170,17 @@ mod test {
};
let variants = s
.variants()
.map(|(m, v, _)| (m.into_iter().collect::<BTreeSet<_>>(), v))
.map(|(ms, v, _)| {
(ms.into_iter().map(|m| m.as_str()).collect::<BTreeSet<_>>(), v)
})
.collect::<BTreeSet<_>>();
let control = control
.iter()
.map(|&(m, v)| {
.map(|&(ms, v)| {
(
ModifierSet::from_raw_dotted(m)
ModifierSet::from_raw_dotted(ms)
.into_iter()
.map(|m| m.as_str())
.collect::<BTreeSet<_>>(),
v,
)
Expand All @@ -187,4 +190,98 @@ mod test {
assert_eq!(variants, control);
}
}

#[test]
fn no_overlap() {
recur("", ROOT);

/// Iterate over all symbols in a module, recursing into submodules.
fn recur(prefix: &str, m: Module) {
for (name, b) in m.iter() {
match b.def {
Def::Module(m) => {
let new_prefix = if prefix.is_empty() {
name.to_string()
} else {
prefix.to_string() + "." + name
};
recur(&new_prefix, m);
}
Def::Symbol(s) => check_symbol(prefix, name, s),
}
}
}

/// Check the no overlap rule for a single symbol
fn check_symbol(prefix: &str, name: &str, sym: Symbol) {
// maximum number of modifiers per variant (we don't need to check more than this).
let max_modifs =
sym.variants().map(|(ms, ..)| ms.iter().count()).max().unwrap();
let modifs = sym.modifiers().collect::<Vec<_>>();
let max_index = modifs.len().saturating_sub(1);

for k in 0..=max_modifs {
let mut indices = (0..k).collect::<Vec<_>>();
loop {
let mset = indices.iter().map(|i| modifs[*i]).fold(
ModifierSet::<String>::default(),
|mut res, m| {
res.insert_raw(m);
res
},
);
Comment on lines +226 to +232
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should have an impl<S: Deref<Target = str>> FromIterator<S> for ModifierSet<String> instead.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really don't like that, see #46 (comment).
Maybe we could have an inherent method from_iter_raw that documents all of those requirements (S::default() must be empty, each item must be a single modifier). To use that like collect, we'd also need an iterator extension trait, which seems overkill, but maybe calling it directly on an iterator is already ergonomic enough?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh indeed you are right! I had forgotten I already suggested a similar thing before.

I think having from_iter_raw could be useful.


if sym.variants().filter(|(ms, ..)| mset.is_candidate(*ms)).count()
> 1
{
panic!(
"Overlap in symbol {prefix}.{name} for modifiers {}",
mset.as_str()
);
}

if next_subseq(&mut indices, max_index).is_none() {
break;
}
}
}
}

/// Produces the (lexicographically) next strictly increasing array of numbers
/// less than or equal to `max_index`.
///
/// Example:
/// ```text
/// [0,1,2], [0,1,3], [0,1,4], [0,2,3], [0,2,4], [0,3,4], [1,2,3], [1,2,4], [1,3,4], [2,3,4]
/// ```
///
/// Invariants:
/// - `indices` is strictly increasing
/// - All elements of `indices` are `<= max_index`
/// - `indices.len() <= max_index + 1` (this is already implied by the previous two)
fn next_subseq(indices: &mut [usize], max_index: usize) -> Option<()> {
match indices {
[] => None,
[single] => {
if *single < max_index {
*single += 1;
Some(())
} else {
None
}
}
[left @ .., last] => {
assert_ne!(max_index, 0);
assert_ne!(left.len(), 0);
if *last < max_index {
*last += 1;
} else {
next_subseq(left, max_index - 1)?;
*last = left.last().unwrap() + 1;
}
Some(())
}
}
}
}
}
Loading