Skip to content

Commit

Permalink
Fix var bind (#449)
Browse files Browse the repository at this point in the history
* Replace VarBind with Enum

* Add wildcard variant

* Fix bug

* Reenable check

* Implement hover correctly

* Small fix
  • Loading branch information
BinderDavid authored Jan 16, 2025
1 parent dbc8b9e commit 2e37373
Show file tree
Hide file tree
Showing 13 changed files with 141 additions and 81 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 8 additions & 8 deletions lang/ast/src/decls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -893,8 +893,8 @@ impl Print for SelfParam {
cfg.print_function_sugar = false;

match name {
Some(name) => alloc
.text(&name.id)
Some(name) => name
.print(&cfg, alloc)
.append(COLON)
.append(alloc.space())
.append(typ.print(&cfg, alloc))
Expand Down Expand Up @@ -987,7 +987,7 @@ impl Print for Telescope {
if shift_and_clone(rtype, (0, 1)) == **typ && rimplicit == *implicit =>
{
// We are adding another parameter of the same type.
output = output.append(alloc.space()).append(alloc.text(&name.id));
output = output.append(alloc.space()).append(name.print(cfg, alloc));
}
Some((rtype, _)) => {
// We are adding another parameter with a different type,
Expand All @@ -1002,9 +1002,9 @@ impl Print for Telescope {
output = output
.append(IMPLICIT)
.append(alloc.space())
.append(alloc.text(&name.id));
.append(name.print(cfg, alloc));
} else {
output = output.append(alloc.text(&name.id));
output = output.append(name.print(cfg, alloc));
}
}
None => {
Expand All @@ -1015,7 +1015,7 @@ impl Print for Telescope {
output = output.append(IMPLICIT).append(alloc.space())
}

output = output.append(alloc.text(&name.id));
output = output.append(name.print(cfg, alloc));
}
}
running = Some((typ, *implicit));
Expand Down Expand Up @@ -1196,12 +1196,12 @@ impl Print for Param {
alloc
.text(IMPLICIT)
.append(alloc.space())
.append(&name.id)
.append(name.print(cfg, alloc))
.append(COLON)
.append(alloc.space())
.append(typ.print(cfg, alloc))
} else {
alloc.text(&name.id).append(COLON).append(alloc.space()).append(typ.print(cfg, alloc))
name.print(cfg, alloc).append(COLON).append(alloc.space()).append(typ.print(cfg, alloc))
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion lang/ast/src/exp/local_comatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ fn print_lambda_sugar<'a>(cases: &'a [Case], cfg: &PrintCfg, alloc: &'a Alloc<'a
.name;
alloc
.backslash_anno(cfg)
.append(&var_name.id)
.append(var_name.print(cfg, alloc))
.append(DOT)
.append(alloc.space())
.append(body.print(cfg, alloc))
Expand Down
4 changes: 2 additions & 2 deletions lang/ast/src/exp/telescope_inst.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,9 @@ pub struct ParamInst {
}

impl Print for ParamInst {
fn print<'a>(&'a self, _cfg: &PrintCfg, alloc: &'a Alloc<'a>) -> Builder<'a> {
fn print<'a>(&'a self, cfg: &PrintCfg, alloc: &'a Alloc<'a>) -> Builder<'a> {
let ParamInst { span: _, info: _, name, typ: _, erased: _ } = self;
alloc.text(&name.id)
name.print(cfg, alloc)
}
}

Expand Down
51 changes: 41 additions & 10 deletions lang/ast/src/ident.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,27 +20,58 @@ use crate::HasSpan;
/// E.g. on the left-hand side of a pattern or in a parameter list
#[derive(Debug, Clone, Derivative)]
#[derivative(Eq, PartialEq, Hash)]
pub struct VarBind {
#[derivative(PartialEq = "ignore", Hash = "ignore")]
pub span: Option<Span>,
pub id: String,
pub enum VarBind {
Var {
#[derivative(PartialEq = "ignore", Hash = "ignore")]
span: Option<Span>,
id: String,
},
Wildcard {
#[derivative(PartialEq = "ignore", Hash = "ignore")]
span: Option<Span>,
},
}

impl VarBind {
pub fn from_string(id: &str) -> Self {
VarBind { span: None, id: id.to_owned() }
VarBind::Var { span: None, id: id.to_owned() }
}
}

impl fmt::Display for VarBind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.id)
match self {
VarBind::Var { id, .. } => write!(f, "{}", id),
VarBind::Wildcard { .. } => write!(f, "_"),
}
}
}

impl Print for VarBind {
fn print<'a>(&'a self, _cfg: &PrintCfg, alloc: &'a Alloc<'a>) -> Builder<'a> {
match self {
VarBind::Var { id, .. } => alloc.text(id),
VarBind::Wildcard { .. } => alloc.text(UNDERSCORE),
}
}
}

/// TODO: Remove this instance!
impl From<VarBind> for VarBound {
fn from(var: VarBind) -> Self {
match var {
VarBind::Var { span, id } => VarBound { span, id },
VarBind::Wildcard { span } => VarBound { span, id: "_".to_string() },
}
}
}

impl HasSpan for VarBind {
fn span(&self) -> Option<Span> {
self.span
match self {
VarBind::Var { span, .. } => *span,
VarBind::Wildcard { span } => *span,
}
}
}

Expand Down Expand Up @@ -75,9 +106,9 @@ impl HasSpan for VarBound {
}
}

impl From<VarBind> for VarBound {
fn from(var: VarBind) -> Self {
VarBound { span: var.span, id: var.id }
impl Print for VarBound {
fn print<'a>(&'a self, _cfg: &PrintCfg, alloc: &'a Alloc<'a>) -> Builder<'a> {
alloc.text(self.id.clone())
}
}

Expand Down
15 changes: 11 additions & 4 deletions lang/driver/src/info/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,9 @@ pub struct Ctx {
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binder {
pub name: String,
pub typ: String,
pub enum Binder {
Var { name: String, typ: String },
Wildcard { typ: String },
}

impl From<TypeCtx> for Ctx {
Expand All @@ -334,6 +334,13 @@ impl From<TypeCtx> for Ctx {

impl From<TypeCtxBinder> for Binder {
fn from(binder: TypeCtxBinder) -> Self {
Binder { name: binder.name.id, typ: binder.typ.print_to_string(None) }
match binder.name {
ast::VarBind::Var { id, .. } => {
Binder::Var { name: id, typ: binder.typ.print_to_string(None) }
}
ast::VarBind::Wildcard { .. } => {
Binder::Wildcard { typ: binder.typ.print_to_string(None) }
}
}
}
}
1 change: 1 addition & 0 deletions lang/lowering/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ log = { workspace = true }
url = { workspace = true }

# workspace members
printer = { path = "../printer" }
parser = { path = "../parser" }
ast = { path = "../ast" }
miette_util = { path = "../miette_util" }
7 changes: 2 additions & 5 deletions lang/lowering/src/lower/decls/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use ast::VarBind;
use exp::bs_to_name;
use miette_util::ToMiette;
use parser::cst::{self};

Expand Down Expand Up @@ -98,7 +96,7 @@ fn lower_self_param<T, F: FnOnce(&mut Ctx, ast::SelfParam) -> Result<T, Lowering
ctx,
ast::SelfParam {
info: Some(*span),
name: name.clone().map(|name| ast::VarBind { span: None, id: name.id }),
name: name.clone().map(|name| ast::VarBind::Var { span: None, id: name.id }),
typ: typ_ctor,
},
)
Expand Down Expand Up @@ -154,8 +152,7 @@ where
let mut params_out = params_out?;
let cst::decls::Param { implicit, name, names: _, typ } = param; // The `names` field has been removed by `desugar_telescope`.
let typ_out = typ.lower(ctx)?;
let name = bs_to_name(name)?;
let name = VarBind { span: Some(name.span), id: name.id.clone() };
let name = name.lower(ctx)?;
let param_out = ast::Param { implicit: *implicit, name, typ: typ_out, erased: false };
params_out.push(param_out);
Ok(params_out)
Expand Down
46 changes: 24 additions & 22 deletions lang/lowering/src/lower/exp/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use ast::IdBound;
use ast::MetaVarKind;
use ast::VarBind;
use ast::VarBound;
use codespan::Span;
use num_bigint::BigUint;
Expand All @@ -13,6 +12,7 @@ use parser::cst;
use parser::cst::decls::Telescope;
use parser::cst::exp::BindingSite;
use parser::cst::ident::Ident;
use printer::Print;

use crate::ctx::*;
use crate::result::*;
Expand Down Expand Up @@ -46,14 +46,13 @@ fn lower_telescope_inst<T, F: FnOnce(&mut Ctx, ast::TelescopeInst) -> Result<T,
ctx.bind_fold(
tel_inst.iter(),
Ok(vec![]),
|_ctx, params_out, param| {
|ctx, params_out, param| {
let mut params_out = params_out?;
let span = bs_to_span(param);
let name = bs_to_name(param)?;
let param_out = ast::ParamInst {
span: Some(span),
info: None,
name: VarBind { span: Some(span), id: name.id.clone() },
name: param.lower(ctx)?,
typ: None,
erased: false,
};
Expand Down Expand Up @@ -153,10 +152,9 @@ fn lower_args(
ctx: &mut Ctx,
) -> Result<(), LoweringError> {
let Some(arg) = given.next() else {
return Err(LoweringError::MissingArgForParam {
expected: bs_to_name(expected_bs)?.to_owned(),
span: span.to_miette(),
});
let expected = expected_bs.lower(ctx)?;
let expected = expected.print_to_string(None);
return Err(LoweringError::MissingArgForParam { expected, span: span.to_miette() });
};
match arg {
cst::exp::Arg::UnnamedArg(exp) => {
Expand Down Expand Up @@ -572,26 +570,30 @@ impl Lower for cst::exp::Lam {
}
}

pub fn bs_to_name(bs: &cst::exp::BindingSite) -> Result<Ident, LoweringError> {
match bs {
BindingSite::Var { name, span } => {
if name.id == "Type" {
Err(LoweringError::TypeUnivIdentifier { span: span.to_miette() })
} else {
Ok(name.clone())
}
}
BindingSite::Wildcard { span } => Ok(Ident { span: *span, id: "_".to_owned() }),
}
}

fn bs_to_span(bs: &cst::exp::BindingSite) -> Span {
match bs {
BindingSite::Var { span, .. } => *span,
BindingSite::Wildcard { span } => *span,
}
}

impl Lower for cst::exp::BindingSite {
type Target = ast::VarBind;

fn lower(&self, _ctx: &mut Ctx) -> Result<Self::Target, LoweringError> {
match self {
BindingSite::Var { span, name } => {
if name.id == "Type" {
Err(LoweringError::TypeUnivIdentifier { span: span.to_miette() })
} else {
Ok(ast::VarBind::Var { span: Some(*span), id: name.id.clone() })
}
}
BindingSite::Wildcard { span } => Ok(ast::VarBind::Wildcard { span: Some(*span) }),
}
}
}

impl Lower for cst::exp::Motive {
type Target = ast::Motive;

Expand All @@ -603,7 +605,7 @@ impl Lower for cst::exp::Motive {
param: ast::ParamInst {
span: Some(bs_to_span(param)),
info: None,
name: ast::VarBind { span: Some(bs_to_span(param)), id: bs_to_name(param)?.id },
name: param.lower(ctx)?,
typ: None,
erased: false,
},
Expand Down
4 changes: 2 additions & 2 deletions lang/lowering/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,10 @@ pub enum LoweringError {
#[label]
span: SourceSpan,
},
#[error("Missing argument for parameter {}", expected.id)]
#[error("Missing argument for parameter {}", expected)]
#[diagnostic(code("L-013"))]
MissingArgForParam {
expected: Ident,
expected: String,
#[label]
span: SourceSpan,
},
Expand Down
18 changes: 10 additions & 8 deletions lang/lsp/src/hover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,17 @@ fn ctx_to_markdown(ctx: &Ctx, value: &mut String) {
value.push_str("**Context**\n\n");
value.push_str("| | |\n");
value.push_str("|-|-|\n");
for Binder { name, typ } in ctx.bound.iter().rev().flatten() {
if name == "_" {
continue;
for binder in ctx.bound.iter().rev().flatten() {
match binder {
Binder::Var { name, typ } => {
value.push_str("| ");
value.push_str(name);
value.push_str(" | `");
value.push_str(typ);
value.push_str("` |\n");
}
Binder::Wildcard { .. } => continue,
}
value.push_str("| ");
value.push_str(name);
value.push_str(" | `");
value.push_str(typ);
value.push_str("` |\n");
}
}

Expand Down
Loading

0 comments on commit 2e37373

Please sign in to comment.