Skip to content
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

Add a Context and use it for interning strings and Rules. #4

Merged
merged 7 commits into from
May 20, 2019
Merged
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 Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ readme = "README.md"
description = "Grammar framework."

[dependencies]
ordermap = "0.3.0"
indexmap = "1"
85 changes: 85 additions & 0 deletions src/context.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use indexmap::IndexSet;
use std::convert::TryInto;
use std::hash::Hash;

/// Context object with global resources for working with grammar,
/// such as interners.
pub struct Context<Pat> {
interners: Interners<Pat>,
}

/// Dispatch helper, to allow implementing interning logic on
/// the type passed to `cx.intern(...)`.
pub trait InternInCx<Pat> {
type Interned;

fn intern_in_cx(self, cx: &mut Context<Pat>) -> Self::Interned;
}

impl<Pat> Context<Pat> {
pub fn new() -> Self {
Context {
interners: Interners::default(),
}
}

pub fn intern<T: InternInCx<Pat>>(&mut self, x: T) -> T::Interned {
x.intern_in_cx(self)
}
}

macro_rules! interners {
($($name:ident => $ty:ty),* $(,)?) => {
#[allow(non_snake_case)]
struct Interners<Pat> {
$($name: IndexSet<$ty>),*
}

impl<Pat> Default for Interners<Pat> {
fn default() -> Self {
Interners {
$($name: IndexSet::new()),*
}
}
}

$(
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct $name(u32);

impl<Pat: Eq + Hash> InternInCx<Pat> for $ty {
type Interned = $name;

fn intern_in_cx(self, cx: &mut Context<Pat>) -> Self::Interned {
$name(cx.interners.$name.insert_full(self).0.try_into().unwrap())
}
}

impl<Pat> std::ops::Index<$name> for Context<Pat> {
type Output = $ty;

fn index(&self, interned: $name) -> &Self::Output {
self.interners.$name.get_index(interned.0 as usize).unwrap()
}
}
)*
};
}

interners! {
IStr => String,
CAD97 marked this conversation as resolved.
Show resolved Hide resolved
IRule => crate::rule::Rule<Pat>,
}

impl<Pat: Eq + Hash> InternInCx<Pat> for &'_ str {
CAD97 marked this conversation as resolved.
Show resolved Hide resolved
type Interned = IStr;

fn intern_in_cx(self, cx: &mut Context<Pat>) -> IStr {
// Avoid allocating if this string is already in the interner.
if let Some((i, _)) = cx.interners.IStr.get_full(self) {
return IStr(i.try_into().unwrap());
}

cx.intern(self.to_string())
}
}
Loading