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

Execute record type instantiations #656

Draft
wants to merge 6 commits into
base: master
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 fir/src/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ impl<T: Debug> Fir<T> {
// FIXME: Check `to` as well
}
Kind::Assignment { to, from: _ } => {
check!(to => Kind::TypedValue { .. }, node);
check!(to => Kind::TypedValue { .. } | Kind::Binding { .. }, node);
// FIXME: Check `from` as well
}
Kind::Instantiation {
Expand Down
2 changes: 1 addition & 1 deletion fir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,9 @@ impl<T> Index<&OriginIdx> for Fir<T> {

#[derive(Debug, Clone)]
pub struct Node<T = ()> {
pub data: T,
pub origin: OriginIdx,
pub kind: Kind,
pub data: T,
}

/// An instance of [`Fir`] is similar to a graph, containing [`Node`]s and relationships binding them together.
Expand Down
7 changes: 6 additions & 1 deletion fire/src/instance.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

// FIXME: This is invalid
// what's a type? at runtime?
// just the hash of the type? -> that's good enough
Expand All @@ -23,7 +25,10 @@ pub enum Instance {
Bool(bool),
Char(char),
String(String),
Other {
/// A slow representation of a record type instance - useful for debugging
SlowRecord(HashMap<String, Instance>),
/// A speedy record type instance
Record {
ty: Type,
data: Vec<u8>,
},
Expand Down
65 changes: 59 additions & 6 deletions fire/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ impl Interpret for Fir<FlattenData<'_>> {
}

/// It's called [`GarbajKollector`] because this way you have "jk" in the middle of the word :)
#[derive(Debug)]
pub struct GarbaJKollector(HashMap<OriginIdx, Instance>);

// FIXME: Add documentation for all methods
Expand Down Expand Up @@ -323,6 +324,52 @@ impl<'ast, 'fir> Fire<'ast, 'fir> {
KeepGoing
}

#[must_use]
fn fire_instantiation(
&mut self,
node: &Node<FlattenData<'_>>,
to: &RefIdx,
_generics: &[RefIdx],
fields: &[RefIdx],
) -> ControlFlow<EarlyExit> {
let definition = self.access(to);
let fields_def = match &definition.kind {
Kind::RecordType { fields, .. } => fields,
_ => unreachable!(),
};

// FIXME: This is absolutely disgusting
let map = match fields_def.iter().zip(fields).try_fold(
HashMap::new(),
|mut field_map, (field_def, field)| {
let field_def = self
.access(field_def)
.data
.ast
.symbol()
.expect("interpreter error - field definition without a symbol");

match self.fire_node_ref(field) {
ControlFlow::Continue(_) => Ok(()),
ControlFlow::Break(early) => Err(early),
}?;

let value = self.gc.lookup(&field.expect_resolved()).cloned().unwrap();

field_map.insert(field_def.access().to_string(), value);

Ok::<HashMap<String, Instance>, EarlyExit>(field_map)
},
) {
Ok(map) => ControlFlow::Continue(map),
Err(early) => ControlFlow::Break(early),
}?;

self.gc.allocate(node.origin, Instance::SlowRecord(map));

KeepGoing
}

#[must_use]
fn fire_node(&mut self, node: &Node<FlattenData<'_>>) -> ControlFlow<EarlyExit> {
match &node.kind {
Expand All @@ -345,12 +392,18 @@ impl<'ast, 'fir> Fire<'ast, 'fir> {
// return_type,
// block,
// } => self.traverse_function( node, generics, args, return_type, block),
// Kind::Assignment { to, from } => self.traverse_assignment( node, to, from),
// Kind::Instantiation {
// to,
// generics,
// fields,
// } => self.traverse_instantiation( node, to, generics, fields),
// FIXME: Rework this - invalid
Kind::Assignment { from, .. } => {
self.fire_node_ref(from)?;
self.gc.transfer(from, node.origin);

KeepGoing
},
Kind::Instantiation {
to,
generics,
fields,
} => self.fire_instantiation(node, to, generics, fields),
// Kind::TypeOffset { instance, field } => {
// self.traverse_type_offset( node, instance, field)
// }
Expand Down
62 changes: 60 additions & 2 deletions name_resolve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ mod resolver;
mod scoper;

use declarator::Declarator;
use resolver::{ResolveKind, Resolver};
use resolver::{LatentResolver, ResolveKind, Resolver};
use scoper::Scoper;

/// Error reported when an item (variable, function, type) was already declared
Expand Down Expand Up @@ -343,7 +343,37 @@ impl<'enclosing> NameResolveCtx<'enclosing> {
&mut self,
fir: Fir<FlattenData<'ast>>,
) -> Result<Fir<FlattenData<'ast>>, Incomplete<FlattenData<'ast>, NameResolutionError>> {
Resolver(self).map(fir)
let mut resolver = Resolver {
ctx: self,
required_parents: Vec::new(),
};

let fir = resolver.map(fir)?;

let latent_map =
resolver
.required_parents
.into_iter()
.fold(HashMap::new(), |mut map, reqd| {
let required_node = &fir[&reqd];

let scope = match &required_node.kind {
Kind::Instantiation { to, .. } => Scope(to.expect_resolved()),
other => unreachable!(
"interpreter error - expected Instantiation, got {other:#?}"
),
};

map.insert(reqd, scope);

map
});

LatentResolver {
ctx: self,
latent_map,
}
.map(fir)
}
}

Expand Down Expand Up @@ -676,4 +706,32 @@ mod tests {

assert!(fir.is_err())
}

#[test]
fn field_instantiation_valid() {
let ast = ast! {
type Foo;

type Record(of: Foo);
where x = Record(of: Foo);
};

let fir = ast.flatten().name_resolve();

assert!(fir.is_ok());
}

#[test]
fn field_instantiation_invalid() {
let ast = ast! {
type Foo;

type Record(of: Foo);
where x = Record(not_of: Foo);
};

let fir = ast.flatten().name_resolve();

assert!(fir.is_err());
}
}
126 changes: 117 additions & 9 deletions name_resolve/src/resolver.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,50 @@
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::{
collections::HashMap,
fmt::{Display, Formatter, Result as FmtResult},
};

use fir::{Kind, Mapper, Node, OriginIdx, RefIdx};
use flatten::FlattenData;
use location::SpanTuple;
use symbol::Symbol;

use crate::{NameResolutionError, NameResolveCtx};
use crate::{NameResolutionError, NameResolveCtx, Scope};

#[derive(Clone, Copy)]
pub(crate) enum ResolveKind {
Call,
Type,
Var,
Binding,
}

impl Display for ResolveKind {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
ResolveKind::Call => write!(f, "call"),
ResolveKind::Type => write!(f, "type"),
ResolveKind::Var => write!(f, "binding"),
ResolveKind::Binding => write!(f, "binding"),
}
}
}

pub(crate) struct Resolver<'ctx, 'enclosing>(pub(crate) &'ctx mut NameResolveCtx<'enclosing>);
pub(crate) struct Resolver<'ctx, 'enclosing> {
pub(crate) ctx: &'ctx mut NameResolveCtx<'enclosing>,
/// The `required_parents` vector contains information about origins whose resolution is necessary
/// for the resolution of other nodes. For example, when resolving a type instantiation like
/// `Foo(bar: 15)`, we need to have `Foo` resolved to its definition in order to resolve `bar` to
/// that type's `.bar` field.
// FIXME: Rework this part of the doc
/// This vector is created as part of the first resolving pass - which
/// we can call early-resolving, or straightforward-resolving, and will be used by a secondary,
/// smaller resolving pass whose purpose is to map these undecidable usages to their definition.
pub(crate) required_parents: Vec<OriginIdx>,
}

/// Created thanks to [`Resolver`]
pub(crate) struct LatentResolver<'ctx, 'enclosing> {
pub(crate) ctx: &'ctx mut NameResolveCtx<'enclosing>,
pub(crate) latent_map: HashMap<OriginIdx, Scope>,
}

impl<'ctx, 'enclosing> Resolver<'ctx, 'enclosing> {
fn get_definition(
Expand All @@ -37,14 +57,14 @@ impl<'ctx, 'enclosing> Resolver<'ctx, 'enclosing> {
let symbol =
sym.expect("attempting to get definition for non existent symbol - interpreter bug");

let mappings = &self.0.mappings;
let mappings = &self.ctx.mappings;

let scope = self.0.enclosing_scope[node];
let scope = self.ctx.enclosing_scope[node];

let origin = match kind {
ResolveKind::Call => mappings.functions.lookup(symbol, scope),
ResolveKind::Type => mappings.types.lookup(symbol, scope),
ResolveKind::Var => mappings.bindings.lookup(symbol, scope),
ResolveKind::Binding => mappings.bindings.lookup(symbol, scope),
};

origin.map_or_else(
Expand Down Expand Up @@ -102,7 +122,7 @@ impl<'ast, 'ctx, 'enclosing> Mapper<FlattenData<'ast>, FlattenData<'ast>, NameRe
ty: RefIdx,
) -> Result<Node<FlattenData<'ast>>, NameResolutionError> {
let var_def = self.get_definition(
ResolveKind::Var,
ResolveKind::Binding,
data.ast.symbol(),
data.ast.location(),
origin,
Expand Down Expand Up @@ -173,4 +193,92 @@ impl<'ast, 'ctx, 'enclosing> Mapper<FlattenData<'ast>, FlattenData<'ast>, NameRe
})
}
}

fn map_assignment(
&mut self,
data: FlattenData<'ast>,
origin: OriginIdx,
to: RefIdx,
from: RefIdx,
) -> Result<Node<FlattenData<'ast>>, NameResolutionError> {
// we should probably do that ONLY if we can't resolve the binding?
// that's very spaghetti...

self.required_parents
.push(self.ctx.enclosing_scope[origin].0);

Ok(Node {
data,
origin,
kind: Kind::Assignment { to, from },
})
}

fn map_instantiation(
&mut self,
data: FlattenData<'ast>,
origin: OriginIdx,
_to: RefIdx,
generics: Vec<RefIdx>,
fields: Vec<RefIdx>,
) -> Result<Node<FlattenData<'ast>>, NameResolutionError> {
// FIXME: Can we have _to be resolved already?

let definition = self.get_definition(
ResolveKind::Type,
data.ast.symbol(),
data.ast.location(),
origin,
)?;

// do we have to go through all the fields here? should we instead have type fields count as declarations? e.g. encode them as <DefOriginIdx, Symbol>?

Ok(Node {
data,
origin,
kind: Kind::Instantiation {
to: RefIdx::Resolved(definition),
generics,
fields,
},
})
}
}

impl<'ast, 'ctx, 'enclosing> Mapper<FlattenData<'ast>, FlattenData<'ast>, NameResolutionError>
for LatentResolver<'ctx, 'enclosing>
{
// FIXME: Disgusting
fn map_assignment(
&mut self,
data: FlattenData<'ast>,
origin: OriginIdx,
_: RefIdx,
from: RefIdx,
) -> Result<Node<FlattenData<'ast>>, NameResolutionError> {
// FIXME: Do nothing if _to is resolved already

let instan = self.ctx.enclosing_scope[origin];
let scope = self.latent_map[&instan.0];

let bindings = self.ctx.mappings.bindings.scopes.get(&scope).unwrap();

let resolved = bindings.get(data.ast.symbol().expect("interpreter error"));

match resolved {
Some(field) => Ok(Node {
data,
origin,
kind: Kind::Assignment {
to: RefIdx::Resolved(*field),
from,
},
}),
None => Err(NameResolutionError::Unresolved(
ResolveKind::Binding,
data.ast.symbol().unwrap().clone(),
data.ast.location().clone(),
)),
}
}
}
Loading