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

Implement type inference for rest attributes #68

Merged
merged 5 commits into from
Mar 8, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
14 changes: 10 additions & 4 deletions crates/ide/src/ty/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,16 @@ impl fmt::Display for TyDisplay<'_> {
let value = Self { ty, config };
write!(f, " {name}: {value}")?;
}
if set.len() > config.max_attrset_fields {
", … }".fmt(f)
} else {
" }".fmt(f)
match (config.max_attrset_fields.checked_sub(set.len()), &*set.rest) {
figsoda marked this conversation as resolved.
Show resolved Hide resolved
(Some(1..), Some((ty, _))) => {
if !set.is_empty() {
",".fmt(f)?;
}
let value = Self { ty, config };
write!(f, " _: {value} }}")
}
(Some(_), _) => " }".fmt(f),
(None, _) => ", … }".fmt(f),
}
}
}
Expand Down
9 changes: 6 additions & 3 deletions crates/ide/src/ty/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,13 +532,16 @@ impl<'a> Collector<'a> {
let b = self.collect(b);
super::Ty::Lambda(a.into(), b.into())
}
Ty::Attrset(set) => {
let set = set
Ty::Attrset(named) => {
let named = named
.0
.into_iter()
.map(|(name, (ty, src))| (name, self.collect(ty), src))
.collect();
super::Ty::Attrset(super::Attrset(set))
super::Ty::Attrset(super::Attrset {
named,
rest: Arc::new(None),
})
}
Ty::External(ty) => ty,
}
Expand Down
11 changes: 8 additions & 3 deletions crates/ide/src/ty/known.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,18 @@ fn merge_attrset(lhs: &Ty, rhs: &Ty) -> Ty {
let rhs = rhs.as_attrset().unwrap();
// Put the RHS on the front and ...
let mut xs = rhs
.0
.named
.iter()
.chain(lhs.0.iter())
.chain(lhs.named.iter())
.map(|(name, ty, src)| (name.clone(), ty.clone(), *src))
.collect::<Vec<_>>();
// ... run stable sort to prefer RHS when duplicated.
xs.sort_by(|(lhs, ..), (rhs, ..)| lhs.cmp(rhs));
xs.dedup_by(|(lhs, ..), (rhs, ..)| lhs == rhs);
Ty::Attrset(Attrset(xs.into()))
Ty::Attrset(Attrset {
named: xs.into(),
rest: rhs.rest.clone(),
})
}

/// https://nixos.wiki/wiki/Flakes
Expand All @@ -87,6 +90,7 @@ pub fn flake(inputs: &[&str]) -> Ty {
.iter()
.copied()
.map(|name| (name, input_ty.clone(), AttrSource::Unknown)),
None,
));

let outputs_param_ty = Ty::Attrset(Attrset::from_internal(
Expand All @@ -95,6 +99,7 @@ pub fn flake(inputs: &[&str]) -> Ty {
.copied()
.chain(Some("self"))
.map(|name| (name, FLAKE.clone(), AttrSource::Unknown)),
None,
));

ty!({
Expand Down
82 changes: 59 additions & 23 deletions crates/ide/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,37 @@ macro_rules! ty {

(($($inner:tt)*)) => { ty!($($inner)*) };
([$($inner:tt)*]) => { $crate::ty::Ty::List(::std::sync::Arc::new(ty!($($inner)*)))};
({ $($key:literal : $ty:tt),* $(,)? $(_ : $rest_ty:tt)? }) => {{
// TODO: Rest type.
$(let _ = ty!($rest_ty);)?
$crate::ty::Ty::Attrset($crate::ty::Attrset::from_internal([
$(($key, ty!($ty), $crate::ty::AttrSource::Unknown),)*
]))
({ $($key:literal : $ty:tt),* $(,)? }) => {{
$crate::ty::Ty::Attrset($crate::ty::Attrset::from_internal(
[
$(($key, ty!($ty), $crate::ty::AttrSource::Unknown),)*
],
None,
))
}};
({($src:expr) $($key:literal : $ty:tt),* $(,)? $(_ : $rest_ty:tt)? }) => {{
$(let _ = ty!($rest_ty);)?
$crate::ty::Ty::Attrset($crate::ty::Attrset::from_internal([
$(($key, ty!($ty), $src),)*
]))
({ $($key:literal : $ty:tt),* $(,)? _ : $rest_ty:tt }) => {{
$crate::ty::Ty::Attrset($crate::ty::Attrset::from_internal(
[
$(($key, ty!($ty), $crate::ty::AttrSource::Unknown),)*
],
Some((ty!($rest_ty), $crate::ty::AttrSource::Unknown)),
))
}};
({($src:expr) $($key:literal : $ty:tt),* $(,)? }) => {{
$crate::ty::Ty::Attrset($crate::ty::Attrset::from_internal(
[
$(($key, ty!($ty), $src),)*
],
None
))
}};
({($src:expr) $($key:literal : $ty:tt),* $(,)? _ : $rest_ty:tt }) => {{
$crate::ty::Ty::Attrset($crate::ty::Attrset::from_internal(
[
$(($key, ty!($ty), $src),)*
],
Some((ty!($rest_ty), $src))
))
}};
($arg:tt -> $($ret:tt)*) => {
$crate::ty::Ty::Lambda(
Expand Down Expand Up @@ -122,11 +141,17 @@ impl fmt::Debug for Ty {

// Invariant: sorted by names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attrset(Arc<[(SmolStr, Ty, AttrSource)]>);
pub struct Attrset {
named: Arc<[(SmolStr, Ty, AttrSource)]>,
figsoda marked this conversation as resolved.
Show resolved Hide resolved
rest: Arc<Option<(Ty, AttrSource)>>,
figsoda marked this conversation as resolved.
Show resolved Hide resolved
}

impl Default for Attrset {
fn default() -> Self {
Self(Arc::new([]))
Self {
named: Arc::new([]),
rest: Arc::new(None),
}
}
}

Expand All @@ -136,32 +161,43 @@ impl Attrset {
/// # Panics
/// The given iterator must have no duplicated fields, or it'll panic.
#[track_caller]
pub fn from_internal<'a>(iter: impl IntoIterator<Item = (&'a str, Ty, AttrSource)>) -> Self {
let mut set = iter
pub fn from_internal<'a>(
iter: impl IntoIterator<Item = (&'a str, Ty, AttrSource)>,
rest: Option<(Ty, AttrSource)>,
) -> Self {
let mut named = iter
.into_iter()
.map(|(name, ty, src)| (SmolStr::from(name), ty, src))
.collect::<Arc<[_]>>();
Arc::get_mut(&mut set)
Arc::get_mut(&mut named)
.unwrap()
.sort_by(|(lhs, ..), (rhs, ..)| lhs.cmp(rhs));
assert!(
set.windows(2).all(|w| w[0].0 != w[1].0),
named.windows(2).all(|w| w[0].0 != w[1].0),
"Duplicated fields",
);
Self(set)
Self {
named,
rest: Arc::new(rest),
}
}

pub fn is_empty(&self) -> bool {
self.0.is_empty()
self.named.is_empty()
}

pub fn len(&self) -> usize {
self.0.len()
self.named.len()
}

fn get_all(&self, field: &str) -> Option<(&Ty, AttrSource)> {
let i = self.0.binary_search_by(|p| (*p.0).cmp(field)).ok()?;
Some((&self.0[i].1, self.0[i].2))
if let Ok(i) = self.named.binary_search_by(|p| (*p.0).cmp(field)) {
Some((&self.named[i].1, self.named[i].2))
} else if let Some((ty, src)) = &*self.rest {
Some((ty, *src))
} else {
None
}
}

pub fn get(&self, field: &str) -> Option<&Ty> {
Expand All @@ -173,7 +209,7 @@ impl Attrset {
}

pub fn iter(&self) -> impl Iterator<Item = (&SmolStr, &Ty, AttrSource)> + '_ {
self.0.iter().map(|(k, ty, src)| (k, ty, *src))
self.named.iter().map(|(k, ty, src)| (k, ty, *src))
}
}

Expand Down
18 changes: 18 additions & 0 deletions crates/ide/src/ty/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,10 +226,28 @@ fn flake_file() {
",
expect!["{ inputs: { }, lastModified: int, lastModifiedDate: string, narHash: string, outPath: string, outputs: { }, rev: string, revCount: int, shortRev: string, sourceInfo: { dir: string, id: string, narHash: string, owner: string, ref: string, repo: string, rev: string, submodules: bool, type: string, url: string }, submodules: bool }"],
);

// Placeholders
check_name(
figsoda marked this conversation as resolved.
Show resolved Hide resolved
"bar",
r"
#- /flake.nix
{
outputs = { self }: {
apps.x86_64-linux = {
foo = let bar = bar; in bar;
};
};
}
",
expect!["{ program: string, type: string }"],
);
}

#[test]
fn builtins() {
check("true", expect!["bool"]);
check("builtins.length [ ]", expect!["int"]);
check("builtins.readDir ./.", expect!["{ _: string }"]);
check("(builtins.readDir ./.).foo", expect!["string"]);
}