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

Name resolve field instantiations #654

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
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
Next Next commit
[wip] name_resolve: Add latent field instantation resolution
CohenArthur committed Mar 9, 2024
commit b5037430da601355b2aae4e1f87d2093b9b08725
32 changes: 30 additions & 2 deletions name_resolve/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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
@@ -342,7 +342,35 @@ 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()),
_ => unreachable!(),
};

map.insert(reqd, scope);

map
});

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

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(
@@ -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(
@@ -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,
@@ -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(),
)),
}
}
}
5 changes: 5 additions & 0 deletions name_resolve/src/scoper.rs
Original file line number Diff line number Diff line change
@@ -118,6 +118,7 @@ impl<'ast> Traversal<FlattenData<'ast>, ScoperError> for Scoper {
self.maybe_visit_child(fir, value)?;
self.maybe_visit_child(fir, ty)
}
// FIXME: Is it valid to put a union's variants in its scope?
Kind::RecordType { fields: subs, .. } | Kind::UnionType { variants: subs, .. } => {
let old = self.enter_scope(node.origin);

@@ -144,10 +145,14 @@ impl<'ast> Traversal<FlattenData<'ast>, ScoperError> for Scoper {
.iter()
.for_each(|generic| self.maybe_visit_child(fir, generic).unwrap());

let old = self.enter_scope(node.origin);

fields
.iter()
.for_each(|field| { self.maybe_visit_child(fir, field) }.unwrap());

self.enter_scope(old);

Ok(())
}
Kind::Call { to, generics, args } => {