Compare commits
9 Commits
Author | SHA1 | Date | |
---|---|---|---|
e3d94d8949 | |||
7a8da33de9 | |||
697d139cfd | |||
5d2c714bc1 | |||
b115fea71b | |||
eebabf02fb | |||
088cd4d1e4 | |||
0fd9c002fc | |||
772286eefa |
@ -146,14 +146,14 @@ pub struct Function {
|
|||||||
pub name: Sym,
|
pub name: Sym,
|
||||||
pub sign: TyFn,
|
pub sign: TyFn,
|
||||||
pub bind: Vec<Param>,
|
pub bind: Vec<Param>,
|
||||||
pub body: Option<Block>,
|
pub body: Option<Expr>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A single parameter for a [Function]
|
/// A single parameter for a [Function]
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
pub struct Param {
|
pub struct Param {
|
||||||
pub mutability: Mutability,
|
pub mutability: Mutability,
|
||||||
pub name: Sym,
|
pub bind: Pattern,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A user-defined product type
|
/// A user-defined product type
|
||||||
@ -418,12 +418,13 @@ pub struct Let {
|
|||||||
/// A [Pattern] meta-expression (any [`ExprKind`] that fits pattern rules)
|
/// A [Pattern] meta-expression (any [`ExprKind`] that fits pattern rules)
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
pub enum Pattern {
|
pub enum Pattern {
|
||||||
Path(Path),
|
Name(Sym),
|
||||||
Literal(Literal),
|
Literal(Literal),
|
||||||
Ref(Mutability, Box<Pattern>),
|
Ref(Mutability, Box<Pattern>),
|
||||||
Tuple(Vec<Pattern>),
|
Tuple(Vec<Pattern>),
|
||||||
Array(Vec<Pattern>),
|
Array(Vec<Pattern>),
|
||||||
Struct(Path, Vec<(Path, Option<Pattern>)>),
|
Struct(Path, Vec<(Sym, Option<Pattern>)>),
|
||||||
|
TupleStruct(Path, Vec<Pattern>),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A `match` expression: `match` `{` ([MatchArm] `,`)* [MatchArm]? `}`
|
/// A `match` expression: `match` `{` ([MatchArm] `,`)* [MatchArm]? `}`
|
||||||
@ -620,7 +621,7 @@ pub struct If {
|
|||||||
/// A [For] expression: `for` Pattern `in` [`Expr`] [`Block`] [`Else`]?
|
/// A [For] expression: `for` Pattern `in` [`Expr`] [`Block`] [`Else`]?
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
pub struct For {
|
pub struct For {
|
||||||
pub bind: Sym, // TODO: Patterns?
|
pub bind: Pattern,
|
||||||
pub cond: Box<Expr>,
|
pub cond: Box<Expr>,
|
||||||
pub pass: Box<Block>,
|
pub pass: Box<Block>,
|
||||||
pub fail: Else,
|
pub fail: Else,
|
||||||
|
@ -194,8 +194,8 @@ mod display {
|
|||||||
|
|
||||||
impl Display for Param {
|
impl Display for Param {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
let Self { mutability, name } = self;
|
let Self { mutability, bind } = self;
|
||||||
write!(f, "{mutability}{name}")
|
write!(f, "{mutability}{bind}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -468,17 +468,17 @@ mod display {
|
|||||||
impl Display for Pattern {
|
impl Display for Pattern {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
Pattern::Path(path) => path.fmt(f),
|
Pattern::Name(sym) => sym.fmt(f),
|
||||||
Pattern::Literal(literal) => literal.fmt(f),
|
Pattern::Literal(literal) => literal.fmt(f),
|
||||||
Pattern::Ref(mutability, pattern) => write!(f, "&{mutability}{pattern}"),
|
Pattern::Ref(mutability, pattern) => write!(f, "&{mutability}{pattern}"),
|
||||||
Pattern::Tuple(patterns) => separate(patterns, ", ")(f.delimit(INLINE_PARENS)),
|
Pattern::Tuple(patterns) => separate(patterns, ", ")(f.delimit(INLINE_PARENS)),
|
||||||
Pattern::Array(patterns) => separate(patterns, ", ")(f.delimit(INLINE_SQUARE)),
|
Pattern::Array(patterns) => separate(patterns, ", ")(f.delimit(INLINE_SQUARE)),
|
||||||
Pattern::Struct(path, items) => {
|
Pattern::Struct(path, items) => {
|
||||||
write!(f, "{path}: ")?;
|
write!(f, "{path} ")?;
|
||||||
let f = &mut f.delimit(BRACES);
|
let f = &mut f.delimit(INLINE_BRACES);
|
||||||
for (idx, (name, item)) in items.iter().enumerate() {
|
for (idx, (name, item)) in items.iter().enumerate() {
|
||||||
if idx != 0 {
|
if idx != 0 {
|
||||||
f.write_str(",\n")?;
|
f.write_str(", ")?;
|
||||||
}
|
}
|
||||||
write!(f, "{name}")?;
|
write!(f, "{name}")?;
|
||||||
if let Some(pattern) = item {
|
if let Some(pattern) = item {
|
||||||
@ -487,6 +487,10 @@ mod display {
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
Pattern::TupleStruct(path, items) => {
|
||||||
|
write!(f, "{path}")?;
|
||||||
|
separate(items, ", ")(f.delimit(INLINE_PARENS))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -635,7 +639,7 @@ mod display {
|
|||||||
impl Display for Structor {
|
impl Display for Structor {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
let Self { to, init } = self;
|
let Self { to, init } = self;
|
||||||
write!(f, "{to}: ")?;
|
write!(f, "{to} ")?;
|
||||||
separate(init, ", ")(f.delimit(INLINE_BRACES))
|
separate(init, ", ")(f.delimit(INLINE_BRACES))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -863,7 +867,10 @@ mod convert {
|
|||||||
fn try_from(value: ExprKind) -> Result<Self, Self::Error> {
|
fn try_from(value: ExprKind) -> Result<Self, Self::Error> {
|
||||||
Ok(match value {
|
Ok(match value {
|
||||||
ExprKind::Literal(literal) => Pattern::Literal(literal),
|
ExprKind::Literal(literal) => Pattern::Literal(literal),
|
||||||
ExprKind::Path(path) => Pattern::Path(path),
|
ExprKind::Path(Path { absolute: false, ref parts }) => match parts.as_slice() {
|
||||||
|
[PathPart::Ident(name)] => Pattern::Name(*name),
|
||||||
|
_ => Err(value)?,
|
||||||
|
},
|
||||||
ExprKind::Empty => Pattern::Tuple(vec![]),
|
ExprKind::Empty => Pattern::Tuple(vec![]),
|
||||||
ExprKind::Group(Group { expr }) => Pattern::Tuple(vec![Pattern::try_from(*expr)?]),
|
ExprKind::Group(Group { expr }) => Pattern::Tuple(vec![Pattern::try_from(*expr)?]),
|
||||||
ExprKind::Tuple(Tuple { exprs }) => Pattern::Tuple(
|
ExprKind::Tuple(Tuple { exprs }) => Pattern::Tuple(
|
||||||
@ -881,16 +888,24 @@ mod convert {
|
|||||||
.map(|e| Pattern::try_from(e.kind))
|
.map(|e| Pattern::try_from(e.kind))
|
||||||
.collect::<Result<_, _>>()?,
|
.collect::<Result<_, _>>()?,
|
||||||
),
|
),
|
||||||
// ExprKind::Index(index) => todo!(),
|
ExprKind::Binary(Binary { kind: BinaryKind::Call, parts }) => {
|
||||||
// ExprKind::Member(member) => todo!(),
|
let (ExprKind::Path(path), args) = *parts else {
|
||||||
|
return Err(parts.0);
|
||||||
|
};
|
||||||
|
match args {
|
||||||
|
ExprKind::Empty | ExprKind::Tuple(_) => {}
|
||||||
|
_ => return Err(args),
|
||||||
|
}
|
||||||
|
let Pattern::Tuple(args) = Pattern::try_from(args)? else {
|
||||||
|
unreachable!("Arguments should be convertible to pattern!")
|
||||||
|
};
|
||||||
|
Pattern::TupleStruct(path, args)
|
||||||
|
}
|
||||||
ExprKind::Structor(Structor { to, init }) => {
|
ExprKind::Structor(Structor { to, init }) => {
|
||||||
let fields = init
|
let fields = init
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|Fielder { name, init }| {
|
.map(|Fielder { name, init }| {
|
||||||
Ok((
|
Ok((name, init.map(|i| Pattern::try_from(i.kind)).transpose()?))
|
||||||
name.into(),
|
|
||||||
init.map(|i| Pattern::try_from(i.kind)).transpose()?,
|
|
||||||
))
|
|
||||||
})
|
})
|
||||||
.collect::<Result<_, Self::Error>>()?;
|
.collect::<Result<_, Self::Error>>()?;
|
||||||
Pattern::Struct(to, fields)
|
Pattern::Struct(to, fields)
|
||||||
@ -925,6 +940,14 @@ mod path {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Checks whether this path ends in the given [Sym]
|
||||||
|
pub fn ends_with(&self, name: &Sym) -> bool {
|
||||||
|
match self.parts.as_slice() {
|
||||||
|
[.., PathPart::Ident(last)] => name == last,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Checks whether this path refers to the sinkhole identifier, `_`
|
/// Checks whether this path refers to the sinkhole identifier, `_`
|
||||||
pub fn is_sinkhole(&self) -> bool {
|
pub fn is_sinkhole(&self) -> bool {
|
||||||
if let [PathPart::Ident(id)] = self.parts.as_slice() {
|
if let [PathPart::Ident(id)] = self.parts.as_slice() {
|
||||||
|
@ -107,12 +107,12 @@ pub trait Fold {
|
|||||||
name: self.fold_sym(name),
|
name: self.fold_sym(name),
|
||||||
sign: self.fold_ty_fn(sign),
|
sign: self.fold_ty_fn(sign),
|
||||||
bind: bind.into_iter().map(|p| self.fold_param(p)).collect(),
|
bind: bind.into_iter().map(|p| self.fold_param(p)).collect(),
|
||||||
body: body.map(|b| self.fold_block(b)),
|
body: body.map(|b| self.fold_expr(b)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn fold_param(&mut self, p: Param) -> Param {
|
fn fold_param(&mut self, p: Param) -> Param {
|
||||||
let Param { mutability, name } = p;
|
let Param { mutability, bind } = p;
|
||||||
Param { mutability: self.fold_mutability(mutability), name: self.fold_sym(name) }
|
Param { mutability: self.fold_mutability(mutability), bind: self.fold_pattern(bind) }
|
||||||
}
|
}
|
||||||
fn fold_struct(&mut self, s: Struct) -> Struct {
|
fn fold_struct(&mut self, s: Struct) -> Struct {
|
||||||
let Struct { name, kind } = s;
|
let Struct { name, kind } = s;
|
||||||
@ -248,7 +248,7 @@ pub trait Fold {
|
|||||||
|
|
||||||
fn fold_pattern(&mut self, p: Pattern) -> Pattern {
|
fn fold_pattern(&mut self, p: Pattern) -> Pattern {
|
||||||
match p {
|
match p {
|
||||||
Pattern::Path(path) => Pattern::Path(self.fold_path(path)),
|
Pattern::Name(sym) => Pattern::Name(self.fold_sym(sym)),
|
||||||
Pattern::Literal(literal) => Pattern::Literal(self.fold_literal(literal)),
|
Pattern::Literal(literal) => Pattern::Literal(self.fold_literal(literal)),
|
||||||
Pattern::Ref(mutability, pattern) => Pattern::Ref(
|
Pattern::Ref(mutability, pattern) => Pattern::Ref(
|
||||||
self.fold_mutability(mutability),
|
self.fold_mutability(mutability),
|
||||||
@ -267,6 +267,13 @@ pub trait Fold {
|
|||||||
.map(|(name, bind)| (name, bind.map(|p| self.fold_pattern(p))))
|
.map(|(name, bind)| (name, bind.map(|p| self.fold_pattern(p))))
|
||||||
.collect(),
|
.collect(),
|
||||||
),
|
),
|
||||||
|
Pattern::TupleStruct(path, items) => Pattern::TupleStruct(
|
||||||
|
self.fold_path(path),
|
||||||
|
items
|
||||||
|
.into_iter()
|
||||||
|
.map(|bind| self.fold_pattern(bind))
|
||||||
|
.collect(),
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -400,7 +407,7 @@ pub trait Fold {
|
|||||||
fn fold_for(&mut self, f: For) -> For {
|
fn fold_for(&mut self, f: For) -> For {
|
||||||
let For { bind, cond, pass, fail } = f;
|
let For { bind, cond, pass, fail } = f;
|
||||||
For {
|
For {
|
||||||
bind: self.fold_sym(bind),
|
bind: self.fold_pattern(bind),
|
||||||
cond: Box::new(self.fold_expr(*cond)),
|
cond: Box::new(self.fold_expr(*cond)),
|
||||||
pass: Box::new(self.fold_block(*pass)),
|
pass: Box::new(self.fold_block(*pass)),
|
||||||
fail: self.fold_else(fail),
|
fail: self.fold_else(fail),
|
||||||
|
@ -85,13 +85,13 @@ pub trait Visit<'a>: Sized {
|
|||||||
self.visit_ty_fn(sign);
|
self.visit_ty_fn(sign);
|
||||||
bind.iter().for_each(|p| self.visit_param(p));
|
bind.iter().for_each(|p| self.visit_param(p));
|
||||||
if let Some(b) = body {
|
if let Some(b) = body {
|
||||||
self.visit_block(b)
|
self.visit_expr(b)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn visit_param(&mut self, p: &'a Param) {
|
fn visit_param(&mut self, p: &'a Param) {
|
||||||
let Param { mutability, name } = p;
|
let Param { mutability, bind } = p;
|
||||||
self.visit_mutability(mutability);
|
self.visit_mutability(mutability);
|
||||||
self.visit_sym(name);
|
self.visit_pattern(bind);
|
||||||
}
|
}
|
||||||
fn visit_struct(&mut self, s: &'a Struct) {
|
fn visit_struct(&mut self, s: &'a Struct) {
|
||||||
let Struct { name, kind } = s;
|
let Struct { name, kind } = s;
|
||||||
@ -214,7 +214,7 @@ pub trait Visit<'a>: Sized {
|
|||||||
|
|
||||||
fn visit_pattern(&mut self, p: &'a Pattern) {
|
fn visit_pattern(&mut self, p: &'a Pattern) {
|
||||||
match p {
|
match p {
|
||||||
Pattern::Path(path) => self.visit_path(path),
|
Pattern::Name(name) => self.visit_sym(name),
|
||||||
Pattern::Literal(literal) => self.visit_literal(literal),
|
Pattern::Literal(literal) => self.visit_literal(literal),
|
||||||
Pattern::Ref(mutability, pattern) => {
|
Pattern::Ref(mutability, pattern) => {
|
||||||
self.visit_mutability(mutability);
|
self.visit_mutability(mutability);
|
||||||
@ -234,6 +234,10 @@ pub trait Visit<'a>: Sized {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
Pattern::TupleStruct(path, items) => {
|
||||||
|
self.visit_path(path);
|
||||||
|
items.iter().for_each(|bind| self.visit_pattern(bind));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -347,7 +351,7 @@ pub trait Visit<'a>: Sized {
|
|||||||
}
|
}
|
||||||
fn visit_for(&mut self, f: &'a For) {
|
fn visit_for(&mut self, f: &'a For) {
|
||||||
let For { bind, cond, pass, fail } = f;
|
let For { bind, cond, pass, fail } = f;
|
||||||
self.visit_sym(bind);
|
self.visit_pattern(bind);
|
||||||
self.visit_expr(cond);
|
self.visit_expr(cond);
|
||||||
self.visit_block(pass);
|
self.visit_block(pass);
|
||||||
self.visit_else(fail);
|
self.visit_else(fail);
|
||||||
|
@ -57,7 +57,7 @@ impl super::Callable for Builtin {
|
|||||||
/// Turns a function definition into a [Builtin].
|
/// Turns a function definition into a [Builtin].
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// # use cl_interpret::{builtin2::builtin, convalue::ConValue};
|
/// # use cl_interpret::{builtin::builtin, convalue::ConValue};
|
||||||
/// let my_builtin = builtin! {
|
/// let my_builtin = builtin! {
|
||||||
/// /// Use the `@env` suffix to bind the environment!
|
/// /// Use the `@env` suffix to bind the environment!
|
||||||
/// /// (needed for recursive calls)
|
/// /// (needed for recursive calls)
|
||||||
|
@ -6,7 +6,8 @@ use cl_ast::{format::FmtAdapter, ExprKind, Sym};
|
|||||||
use super::{
|
use super::{
|
||||||
builtin::Builtin,
|
builtin::Builtin,
|
||||||
error::{Error, IResult},
|
error::{Error, IResult},
|
||||||
function::Function, Callable, Environment,
|
function::Function,
|
||||||
|
Callable, Environment,
|
||||||
};
|
};
|
||||||
use std::{collections::HashMap, ops::*, rc::Rc};
|
use std::{collections::HashMap, ops::*, rc::Rc};
|
||||||
|
|
||||||
@ -40,6 +41,8 @@ pub enum ConValue {
|
|||||||
RangeInc(Integer, Integer),
|
RangeInc(Integer, Integer),
|
||||||
/// A value of a product type
|
/// A value of a product type
|
||||||
Struct(Box<(Sym, HashMap<Sym, ConValue>)>),
|
Struct(Box<(Sym, HashMap<Sym, ConValue>)>),
|
||||||
|
/// A value of a product type with anonymous members
|
||||||
|
TupleStruct(Box<(Sym, Box<[ConValue]>)>),
|
||||||
/// An entire namespace
|
/// An entire namespace
|
||||||
Module(Box<HashMap<Sym, Option<ConValue>>>),
|
Module(Box<HashMap<Sym, Option<ConValue>>>),
|
||||||
/// A quoted expression
|
/// A quoted expression
|
||||||
@ -298,11 +301,25 @@ impl std::fmt::Display for ConValue {
|
|||||||
}
|
}
|
||||||
')'.fmt(f)
|
')'.fmt(f)
|
||||||
}
|
}
|
||||||
|
ConValue::TupleStruct(parts) => {
|
||||||
|
let (name, tuple) = parts.as_ref();
|
||||||
|
if !name.is_empty() {
|
||||||
|
write!(f, "{name}")?;
|
||||||
|
}
|
||||||
|
'('.fmt(f)?;
|
||||||
|
for (idx, element) in tuple.iter().enumerate() {
|
||||||
|
if idx > 0 {
|
||||||
|
", ".fmt(f)?
|
||||||
|
}
|
||||||
|
element.fmt(f)?
|
||||||
|
}
|
||||||
|
')'.fmt(f)
|
||||||
|
}
|
||||||
ConValue::Struct(parts) => {
|
ConValue::Struct(parts) => {
|
||||||
let (name, map) = parts.as_ref();
|
let (name, map) = parts.as_ref();
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
if !name.is_empty() {
|
if !name.is_empty() {
|
||||||
write!(f, "{name}: ")?;
|
write!(f, "{name} ")?;
|
||||||
}
|
}
|
||||||
let mut f = f.delimit_with("{", "\n}");
|
let mut f = f.delimit_with("{", "\n}");
|
||||||
for (k, v) in map.iter() {
|
for (k, v) in map.iter() {
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
use collect_upvars::collect_upvars;
|
use collect_upvars::collect_upvars;
|
||||||
|
|
||||||
use super::{Callable, ConValue, Environment, Error, IResult, Interpret};
|
use super::{pattern, Callable, ConValue, Environment, Error, IResult, Interpret};
|
||||||
use cl_ast::{Function as FnDecl, Param, Sym};
|
use cl_ast::{Function as FnDecl, Param, Sym};
|
||||||
use std::{
|
use std::{
|
||||||
cell::{Ref, RefCell},
|
cell::{Ref, RefCell},
|
||||||
@ -21,12 +21,16 @@ pub struct Function {
|
|||||||
decl: Rc<FnDecl>,
|
decl: Rc<FnDecl>,
|
||||||
/// Stores data from the enclosing scopes
|
/// Stores data from the enclosing scopes
|
||||||
upvars: RefCell<Upvars>,
|
upvars: RefCell<Upvars>,
|
||||||
|
is_constructor: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Function {
|
impl Function {
|
||||||
pub fn new(decl: &FnDecl) -> Self {
|
pub fn new(decl: &FnDecl) -> Self {
|
||||||
// let upvars = collect_upvars(decl, env);
|
// let upvars = collect_upvars(decl, env);
|
||||||
Self { decl: decl.clone().into(), upvars: Default::default() }
|
Self { decl: decl.clone().into(), upvars: Default::default(), is_constructor: false }
|
||||||
|
}
|
||||||
|
pub fn new_constructor(decl: FnDecl) -> Self {
|
||||||
|
Self { decl: decl.into(), upvars: Default::default(), is_constructor: true }
|
||||||
}
|
}
|
||||||
pub fn decl(&self) -> &FnDecl {
|
pub fn decl(&self) -> &FnDecl {
|
||||||
&self.decl
|
&self.decl
|
||||||
@ -54,6 +58,9 @@ impl Callable for Function {
|
|||||||
if args.len() != bind.len() {
|
if args.len() != bind.len() {
|
||||||
return Err(Error::ArgNumber { want: bind.len(), got: args.len() });
|
return Err(Error::ArgNumber { want: bind.len(), got: args.len() });
|
||||||
}
|
}
|
||||||
|
if self.is_constructor {
|
||||||
|
return Ok(ConValue::TupleStruct(Box::new((*name, args.into()))));
|
||||||
|
}
|
||||||
let Some(body) = body else {
|
let Some(body) = body else {
|
||||||
return Err(Error::NotDefined(*name));
|
return Err(Error::NotDefined(*name));
|
||||||
};
|
};
|
||||||
@ -63,8 +70,10 @@ impl Callable for Function {
|
|||||||
|
|
||||||
// TODO: completely refactor data storage
|
// TODO: completely refactor data storage
|
||||||
let mut frame = env.frame("fn args");
|
let mut frame = env.frame("fn args");
|
||||||
for (Param { mutability: _, name }, value) in bind.iter().zip(args) {
|
for (Param { mutability: _, bind }, value) in bind.iter().zip(args) {
|
||||||
frame.insert(*name, Some(value.clone()));
|
for (name, value) in pattern::substitution(bind, value.clone())? {
|
||||||
|
frame.insert(*name, Some(value));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let res = body.interpret(&mut frame);
|
let res = body.interpret(&mut frame);
|
||||||
drop(frame);
|
drop(frame);
|
||||||
|
@ -67,11 +67,11 @@ impl<'a> Visit<'a> for CollectUpvars<'_> {
|
|||||||
fn visit_function(&mut self, f: &'a cl_ast::Function) {
|
fn visit_function(&mut self, f: &'a cl_ast::Function) {
|
||||||
let Function { name: _, sign: _, bind, body } = f;
|
let Function { name: _, sign: _, bind, body } = f;
|
||||||
// parameters can never be upvars
|
// parameters can never be upvars
|
||||||
for Param { mutability: _, name } in bind {
|
for Param { mutability: _, bind } in bind {
|
||||||
self.bind_name(name);
|
self.visit_pattern(bind);
|
||||||
}
|
}
|
||||||
if let Some(body) = body {
|
if let Some(body) = body {
|
||||||
self.visit_block(body);
|
self.visit_expr(body);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -79,7 +79,7 @@ impl<'a> Visit<'a> for CollectUpvars<'_> {
|
|||||||
let cl_ast::For { bind, cond, pass, fail } = f;
|
let cl_ast::For { bind, cond, pass, fail } = f;
|
||||||
self.visit_expr(cond);
|
self.visit_expr(cond);
|
||||||
self.visit_else(fail);
|
self.visit_else(fail);
|
||||||
self.bind_name(bind); // TODO: is bind only bound in the pass block?
|
self.visit_pattern(bind);
|
||||||
self.visit_block(pass);
|
self.visit_block(pass);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -105,10 +105,8 @@ impl<'a> Visit<'a> for CollectUpvars<'_> {
|
|||||||
|
|
||||||
fn visit_pattern(&mut self, p: &'a cl_ast::Pattern) {
|
fn visit_pattern(&mut self, p: &'a cl_ast::Pattern) {
|
||||||
match p {
|
match p {
|
||||||
Pattern::Path(path) => {
|
Pattern::Name(name) => {
|
||||||
if let [PathPart::Ident(name)] = path.parts.as_slice() {
|
self.bind_name(name);
|
||||||
self.bind_name(name)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Pattern::Literal(literal) => self.visit_literal(literal),
|
Pattern::Literal(literal) => self.visit_literal(literal),
|
||||||
Pattern::Ref(mutability, pattern) => {
|
Pattern::Ref(mutability, pattern) => {
|
||||||
@ -129,6 +127,10 @@ impl<'a> Visit<'a> for CollectUpvars<'_> {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
Pattern::TupleStruct(path, items) => {
|
||||||
|
self.visit_path(path);
|
||||||
|
items.iter().for_each(|bind| self.visit_pattern(bind));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,7 +8,7 @@
|
|||||||
use std::{borrow::Borrow, rc::Rc};
|
use std::{borrow::Borrow, rc::Rc};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use cl_ast::*;
|
use cl_ast::{ast_visitor::Visit, *};
|
||||||
use cl_structures::intern::interned::Interned;
|
use cl_structures::intern::interned::Interned;
|
||||||
/// A work-in-progress tree walk interpreter for Conlang
|
/// A work-in-progress tree walk interpreter for Conlang
|
||||||
pub trait Interpret {
|
pub trait Interpret {
|
||||||
@ -20,9 +20,29 @@ pub trait Interpret {
|
|||||||
|
|
||||||
impl Interpret for File {
|
impl Interpret for File {
|
||||||
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
|
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
|
||||||
for item in &self.items {
|
/// Sorts items
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct ItemSorter<'ast>(pub [Vec<&'ast Item>; 6]);
|
||||||
|
impl<'ast> Visit<'ast> for ItemSorter<'ast> {
|
||||||
|
fn visit_item(&mut self, i: &'ast Item) {
|
||||||
|
self.0[match &i.kind {
|
||||||
|
ItemKind::Module(_) => 0,
|
||||||
|
ItemKind::Use(_) => 1,
|
||||||
|
ItemKind::Enum(_) | ItemKind::Struct(_) | ItemKind::Alias(_) => 2,
|
||||||
|
ItemKind::Function(_) => 3,
|
||||||
|
ItemKind::Impl(_) => 4,
|
||||||
|
ItemKind::Const(_) | ItemKind::Static(_) => 5,
|
||||||
|
}]
|
||||||
|
.push(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut items = ItemSorter::default();
|
||||||
|
items.visit_file(self);
|
||||||
|
for item in items.0.into_iter().flatten() {
|
||||||
item.interpret(env)?;
|
item.interpret(env)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(ConValue::Empty)
|
Ok(ConValue::Empty)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -93,8 +113,42 @@ impl Interpret for Function {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Interpret for Struct {
|
impl Interpret for Struct {
|
||||||
fn interpret(&self, _env: &mut Environment) -> IResult<ConValue> {
|
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
|
||||||
println!("TODO: {self}");
|
let Self { name, kind } = self;
|
||||||
|
match kind {
|
||||||
|
StructKind::Empty => {}
|
||||||
|
StructKind::Tuple(args) => {
|
||||||
|
// Constructs the AST from scratch. TODO: This, better.
|
||||||
|
let constructor = Function {
|
||||||
|
name: *name,
|
||||||
|
sign: TyFn {
|
||||||
|
args: TyKind::Tuple(TyTuple {
|
||||||
|
types: args.iter().map(|ty| ty.kind.clone()).collect(),
|
||||||
|
})
|
||||||
|
.into(),
|
||||||
|
rety: Some(
|
||||||
|
Ty {
|
||||||
|
extents: cl_structures::span::Span::dummy(),
|
||||||
|
kind: TyKind::Path(Path::from(*name)),
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
bind: args
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(idx, _)| Param {
|
||||||
|
mutability: Mutability::Not,
|
||||||
|
bind: Pattern::Name(idx.to_string().into()),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
body: None,
|
||||||
|
};
|
||||||
|
let constructor = crate::function::Function::new_constructor(constructor);
|
||||||
|
env.insert(*name, Some(constructor.into()));
|
||||||
|
}
|
||||||
|
StructKind::Struct(_) => eprintln!("TODO: {self}"),
|
||||||
|
}
|
||||||
Ok(ConValue::Empty)
|
Ok(ConValue::Empty)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -106,7 +160,7 @@ impl Interpret for Enum {
|
|||||||
}
|
}
|
||||||
impl Interpret for Impl {
|
impl Interpret for Impl {
|
||||||
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
|
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
|
||||||
println!("TODO: {self}");
|
println!("TODO: impl {}", self.target);
|
||||||
let Self { target: _, body } = self;
|
let Self { target: _, body } = self;
|
||||||
body.interpret(env)
|
body.interpret(env)
|
||||||
}
|
}
|
||||||
@ -246,19 +300,13 @@ impl Interpret for Let {
|
|||||||
let Let { mutable: _, name, ty: _, init } = self;
|
let Let { mutable: _, name, ty: _, init } = self;
|
||||||
match init.as_ref().map(|i| i.interpret(env)).transpose()? {
|
match init.as_ref().map(|i| i.interpret(env)).transpose()? {
|
||||||
Some(value) => {
|
Some(value) => {
|
||||||
for (path, value) in assignment::pattern_substitution(name, value)? {
|
for (name, value) in pattern::substitution(name, value)? {
|
||||||
match path.parts.as_slice() {
|
env.insert(*name, Some(value));
|
||||||
[PathPart::Ident(name)] => env.insert(*name, Some(value)),
|
|
||||||
_ => eprintln!("Bad assignment: {path} = {value}"),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
for path in assignment::pattern_variables(name) {
|
for name in pattern::variables(name) {
|
||||||
match path.parts.as_slice() {
|
env.insert(*name, None);
|
||||||
[PathPart::Ident(name)] => env.insert(*name, None),
|
|
||||||
_ => eprintln!("Bad assignment: {path}"),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -270,13 +318,10 @@ impl Interpret for Match {
|
|||||||
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
|
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
|
||||||
let Self { scrutinee, arms } = self;
|
let Self { scrutinee, arms } = self;
|
||||||
let scrutinee = scrutinee.interpret(env)?;
|
let scrutinee = scrutinee.interpret(env)?;
|
||||||
'arm: for MatchArm(pat, expr) in arms {
|
for MatchArm(pat, expr) in arms {
|
||||||
if let Ok(substitution) = assignment::pattern_substitution(pat, scrutinee.clone()) {
|
if let Ok(substitution) = pattern::substitution(pat, scrutinee.clone()) {
|
||||||
let mut env = env.frame("match");
|
let mut env = env.frame("match");
|
||||||
for (path, value) in substitution {
|
for (name, value) in substitution {
|
||||||
let [PathPart::Ident(name)] = path.parts.as_slice() else {
|
|
||||||
continue 'arm;
|
|
||||||
};
|
|
||||||
env.insert(*name, Some(value));
|
env.insert(*name, Some(value));
|
||||||
}
|
}
|
||||||
return expr.interpret(&mut env);
|
return expr.interpret(&mut env);
|
||||||
@ -292,127 +337,11 @@ mod assignment {
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
type Namespace = HashMap<Sym, Option<ConValue>>;
|
type Namespace = HashMap<Sym, Option<ConValue>>;
|
||||||
|
|
||||||
/// Gets the path variables in the given Pattern
|
|
||||||
pub fn pattern_variables(pat: &Pattern) -> Vec<&Path> {
|
|
||||||
fn patvars<'p>(set: &mut Vec<&'p Path>, pat: &'p Pattern) {
|
|
||||||
match pat {
|
|
||||||
Pattern::Path(path) if path.is_sinkhole() => {}
|
|
||||||
Pattern::Path(path) => set.push(path),
|
|
||||||
Pattern::Literal(_) => {}
|
|
||||||
Pattern::Ref(_, pattern) => patvars(set, pattern),
|
|
||||||
Pattern::Tuple(patterns) | Pattern::Array(patterns) => {
|
|
||||||
patterns.iter().for_each(|pat| patvars(set, pat))
|
|
||||||
}
|
|
||||||
Pattern::Struct(_path, items) => {
|
|
||||||
items.iter().for_each(|(name, pat)| match pat {
|
|
||||||
Some(pat) => patvars(set, pat),
|
|
||||||
None => set.push(name),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut set = Vec::new();
|
|
||||||
patvars(&mut set, pat);
|
|
||||||
set
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Appends a substitution to the provided table
|
|
||||||
pub fn append_sub<'pat>(
|
|
||||||
env: &mut HashMap<&'pat Path, ConValue>,
|
|
||||||
pat: &'pat Pattern,
|
|
||||||
value: ConValue,
|
|
||||||
) -> IResult<()> {
|
|
||||||
match pat {
|
|
||||||
Pattern::Path(path) if path.is_sinkhole() => Ok(()),
|
|
||||||
Pattern::Path(path) => {
|
|
||||||
env.insert(path, value);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
Pattern::Literal(literal) => match (literal, value) {
|
|
||||||
(Literal::Bool(a), ConValue::Bool(b)) => *a == b,
|
|
||||||
(Literal::Char(a), ConValue::Char(b)) => *a == b,
|
|
||||||
(Literal::Int(a), ConValue::Int(b)) => *a as isize == b,
|
|
||||||
(Literal::Float(a), ConValue::Float(b)) => f64::from_bits(*a) == b,
|
|
||||||
(Literal::String(a), ConValue::String(b)) => *a == *b,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
.then_some(())
|
|
||||||
.ok_or(Error::NotAssignable),
|
|
||||||
|
|
||||||
Pattern::Ref(_, pattern) => match value {
|
|
||||||
ConValue::Ref(value) => append_sub(env, pattern, Rc::unwrap_or_clone(value)),
|
|
||||||
_ => Err(Error::NotAssignable),
|
|
||||||
},
|
|
||||||
|
|
||||||
Pattern::Tuple(patterns) => match value {
|
|
||||||
ConValue::Tuple(values) => {
|
|
||||||
if patterns.len() != values.len() {
|
|
||||||
return Err(Error::OobIndex(patterns.len(), values.len()));
|
|
||||||
};
|
|
||||||
for (pat, value) in patterns.iter().zip(Vec::from(values).into_iter()) {
|
|
||||||
append_sub(env, pat, value)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
_ => Err(Error::NotAssignable),
|
|
||||||
},
|
|
||||||
|
|
||||||
Pattern::Array(patterns) => match value {
|
|
||||||
ConValue::Array(values) => {
|
|
||||||
if patterns.len() != values.len() {
|
|
||||||
return Err(Error::OobIndex(patterns.len(), values.len()));
|
|
||||||
};
|
|
||||||
for (pat, value) in patterns.iter().zip(Vec::from(values).into_iter()) {
|
|
||||||
append_sub(env, pat, value)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
_ => Err(Error::NotAssignable),
|
|
||||||
},
|
|
||||||
|
|
||||||
Pattern::Struct(_path, patterns) => {
|
|
||||||
let ConValue::Struct(parts) = value else {
|
|
||||||
return Err(Error::TypeError);
|
|
||||||
};
|
|
||||||
let (_, mut values) = *parts;
|
|
||||||
if values.len() != patterns.len() {
|
|
||||||
return Err(Error::TypeError);
|
|
||||||
}
|
|
||||||
for (name, pat) in patterns {
|
|
||||||
let [.., PathPart::Ident(index)] = name.parts.as_slice() else {
|
|
||||||
Err(Error::TypeError)?
|
|
||||||
};
|
|
||||||
let value = values.remove(index).ok_or(Error::TypeError)?;
|
|
||||||
match pat {
|
|
||||||
Some(pat) => append_sub(env, pat, value)?,
|
|
||||||
None => {
|
|
||||||
env.insert(name, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Constructs a substitution from a pattern and a value
|
|
||||||
pub fn pattern_substitution(
|
|
||||||
pat: &Pattern,
|
|
||||||
value: ConValue,
|
|
||||||
) -> IResult<HashMap<&Path, ConValue>> {
|
|
||||||
let mut substitution = HashMap::new();
|
|
||||||
append_sub(&mut substitution, pat, value)?;
|
|
||||||
Ok(substitution)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn pat_assign(env: &mut Environment, pat: &Pattern, value: ConValue) -> IResult<()> {
|
pub(super) fn pat_assign(env: &mut Environment, pat: &Pattern, value: ConValue) -> IResult<()> {
|
||||||
let mut substitution = HashMap::new();
|
for (name, value) in
|
||||||
append_sub(&mut substitution, pat, value)
|
pattern::substitution(pat, value).map_err(|_| Error::PatFailed(pat.clone().into()))?
|
||||||
.map_err(|_| Error::PatFailed(pat.clone().into()))?;
|
{
|
||||||
for (path, value) in substitution {
|
*env.get_mut(*name)? = Some(value);
|
||||||
assign_path(env, path, value)?;
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@ -424,20 +353,12 @@ mod assignment {
|
|||||||
match pat {
|
match pat {
|
||||||
ExprKind::Member(member) => *addrof_member(env, member)? = value,
|
ExprKind::Member(member) => *addrof_member(env, member)? = value,
|
||||||
ExprKind::Index(index) => *addrof_index(env, index)? = value,
|
ExprKind::Index(index) => *addrof_index(env, index)? = value,
|
||||||
|
ExprKind::Path(path) => *addrof_path(env, &path.parts)? = Some(value),
|
||||||
_ => Err(Error::NotAssignable)?,
|
_ => Err(Error::NotAssignable)?,
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn assign_path(env: &mut Environment, path: &Path, value: ConValue) -> IResult<()> {
|
|
||||||
let Ok(addr) = addrof_path(env, &path.parts) else {
|
|
||||||
eprintln!("Cannot assign {value} to path {path}");
|
|
||||||
return Err(Error::NotAssignable);
|
|
||||||
};
|
|
||||||
*addr = Some(value);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn addrof<'e>(
|
pub(super) fn addrof<'e>(
|
||||||
env: &'e mut Environment,
|
env: &'e mut Environment,
|
||||||
pat: &ExprKind,
|
pat: &ExprKind,
|
||||||
@ -461,14 +382,17 @@ mod assignment {
|
|||||||
match path {
|
match path {
|
||||||
[PathPart::Ident(name)] => env.get_mut(*name),
|
[PathPart::Ident(name)] => env.get_mut(*name),
|
||||||
[PathPart::Ident(name), rest @ ..] => match env.get_mut(*name)? {
|
[PathPart::Ident(name), rest @ ..] => match env.get_mut(*name)? {
|
||||||
Some(ConValue::Module(env)) => addrof_path_within_namespace(env, rest),
|
Some(ConValue::Module(env)) => project_path_in_namespace(env, rest),
|
||||||
_ => Err(Error::NotIndexable),
|
_ => Err(Error::NotIndexable),
|
||||||
},
|
},
|
||||||
_ => Err(Error::NotAssignable),
|
_ => Err(Error::NotAssignable),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn addrof_member<'e>(env: &'e mut Environment, member: &Member) -> IResult<&'e mut ConValue> {
|
pub fn addrof_member<'e>(
|
||||||
|
env: &'e mut Environment,
|
||||||
|
member: &Member,
|
||||||
|
) -> IResult<&'e mut ConValue> {
|
||||||
let Member { head, kind } = member;
|
let Member { head, kind } = member;
|
||||||
let ExprKind::Path(path) = head.as_ref() else {
|
let ExprKind::Path(path) = head.as_ref() else {
|
||||||
return Err(Error::TypeError);
|
return Err(Error::TypeError);
|
||||||
@ -476,15 +400,7 @@ mod assignment {
|
|||||||
let slot = addrof_path(env, &path.parts)?
|
let slot = addrof_path(env, &path.parts)?
|
||||||
.as_mut()
|
.as_mut()
|
||||||
.ok_or(Error::NotAssignable)?;
|
.ok_or(Error::NotAssignable)?;
|
||||||
Ok(match (slot, kind) {
|
project_memberkind(slot, kind)
|
||||||
(ConValue::Struct(s), MemberKind::Struct(id)) => {
|
|
||||||
s.1.get_mut(id).ok_or(Error::NotDefined(*id))?
|
|
||||||
}
|
|
||||||
(ConValue::Tuple(t), MemberKind::Tuple(Literal::Int(id))) => t
|
|
||||||
.get_mut(*id as usize)
|
|
||||||
.ok_or_else(|| Error::NotDefined(id.to_string().into()))?,
|
|
||||||
_ => Err(Error::TypeError)?,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn addrof_index<'e>(env: &'e mut Environment, index: &Index) -> IResult<&'e mut ConValue> {
|
fn addrof_index<'e>(env: &'e mut Environment, index: &Index) -> IResult<&'e mut ConValue> {
|
||||||
@ -495,19 +411,50 @@ mod assignment {
|
|||||||
.collect::<IResult<Vec<_>>>()?;
|
.collect::<IResult<Vec<_>>>()?;
|
||||||
let mut head = addrof(env, head)?;
|
let mut head = addrof(env, head)?;
|
||||||
for index in indices {
|
for index in indices {
|
||||||
head = match (head, index) {
|
head = project_index(head, &index)?;
|
||||||
(ConValue::Array(a), ConValue::Int(i)) => {
|
|
||||||
let a_len = a.len();
|
|
||||||
a.get_mut(i as usize)
|
|
||||||
.ok_or(Error::OobIndex(i as usize, a_len))?
|
|
||||||
}
|
|
||||||
_ => Err(Error::NotIndexable)?,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Ok(head)
|
Ok(head)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn addrof_path_within_namespace<'e>(
|
/// Performs member-access "projection" from a ConValue to a particular element
|
||||||
|
pub fn project_memberkind<'v>(
|
||||||
|
value: &'v mut ConValue,
|
||||||
|
kind: &MemberKind,
|
||||||
|
) -> IResult<&'v mut ConValue> {
|
||||||
|
match (value, kind) {
|
||||||
|
(ConValue::Struct(s), MemberKind::Struct(id)) => {
|
||||||
|
s.1.get_mut(id).ok_or(Error::NotDefined(*id))
|
||||||
|
}
|
||||||
|
(ConValue::TupleStruct(s), MemberKind::Tuple(Literal::Int(id))) => {
|
||||||
|
let len = s.1.len();
|
||||||
|
s.1.get_mut(*id as usize)
|
||||||
|
.ok_or(Error::OobIndex(*id as _, len))
|
||||||
|
}
|
||||||
|
(ConValue::Tuple(t), MemberKind::Tuple(Literal::Int(id))) => {
|
||||||
|
let len = t.len();
|
||||||
|
t.get_mut(*id as usize)
|
||||||
|
.ok_or(Error::OobIndex(*id as _, len))
|
||||||
|
}
|
||||||
|
_ => Err(Error::TypeError),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Performs index "projection" from a ConValue to a particular element
|
||||||
|
pub fn project_index<'v>(
|
||||||
|
value: &'v mut ConValue,
|
||||||
|
index: &ConValue,
|
||||||
|
) -> IResult<&'v mut ConValue> {
|
||||||
|
match (value, index) {
|
||||||
|
(ConValue::Array(a), ConValue::Int(i)) => {
|
||||||
|
let a_len = a.len();
|
||||||
|
a.get_mut(*i as usize)
|
||||||
|
.ok_or(Error::OobIndex(*i as usize, a_len))
|
||||||
|
}
|
||||||
|
_ => Err(Error::NotIndexable),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn project_path_in_namespace<'e>(
|
||||||
env: &'e mut Namespace,
|
env: &'e mut Namespace,
|
||||||
path: &[PathPart],
|
path: &[PathPart],
|
||||||
) -> IResult<&'e mut Option<ConValue>> {
|
) -> IResult<&'e mut Option<ConValue>> {
|
||||||
@ -516,11 +463,11 @@ mod assignment {
|
|||||||
[PathPart::Ident(name)] => env.get_mut(name).ok_or(Error::NotDefined(*name)),
|
[PathPart::Ident(name)] => env.get_mut(name).ok_or(Error::NotDefined(*name)),
|
||||||
[PathPart::Ident(name), rest @ ..] => {
|
[PathPart::Ident(name), rest @ ..] => {
|
||||||
match env.get_mut(name).ok_or(Error::NotDefined(*name))? {
|
match env.get_mut(name).ok_or(Error::NotDefined(*name))? {
|
||||||
Some(ConValue::Module(env)) => addrof_path_within_namespace(env, rest),
|
Some(ConValue::Module(env)) => project_path_in_namespace(env, rest),
|
||||||
_ => Err(Error::NotIndexable),
|
_ => Err(Error::NotIndexable),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
[PathPart::SelfKw, rest @ ..] => addrof_path_within_namespace(env, rest),
|
[PathPart::SelfKw, rest @ ..] => project_path_in_namespace(env, rest),
|
||||||
[PathPart::SelfTy, ..] => todo!("calc_address for `Self`"),
|
[PathPart::SelfTy, ..] => todo!("calc_address for `Self`"),
|
||||||
[PathPart::SuperKw, ..] => todo!("calc_address for `super`"),
|
[PathPart::SuperKw, ..] => todo!("calc_address for `super`"),
|
||||||
}
|
}
|
||||||
@ -732,16 +679,14 @@ impl Interpret for Cast {
|
|||||||
impl Interpret for Member {
|
impl Interpret for Member {
|
||||||
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
|
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
|
||||||
let Member { head, kind } = self;
|
let Member { head, kind } = self;
|
||||||
|
if let ExprKind::Path(_) = head.as_ref() {
|
||||||
|
return assignment::addrof_member(env, self).cloned();
|
||||||
|
}
|
||||||
let head = head.interpret(env)?;
|
let head = head.interpret(env)?;
|
||||||
match (head, kind) {
|
match (head, kind) {
|
||||||
(ConValue::Tuple(v), MemberKind::Tuple(Literal::Int(id))) => v
|
(ConValue::Struct(parts), MemberKind::Call(name, args))
|
||||||
.get(*id as usize)
|
if parts.1.contains_key(name) =>
|
||||||
.cloned()
|
{
|
||||||
.ok_or(Error::OobIndex(*id as usize, v.len())),
|
|
||||||
(ConValue::Struct(parts), MemberKind::Struct(name)) => {
|
|
||||||
parts.1.get(name).cloned().ok_or(Error::NotDefined(*name))
|
|
||||||
}
|
|
||||||
(ConValue::Struct(parts), MemberKind::Call(name, args)) => {
|
|
||||||
let mut values = vec![];
|
let mut values = vec![];
|
||||||
for arg in &args.exprs {
|
for arg in &args.exprs {
|
||||||
values.push(arg.interpret(env)?);
|
values.push(arg.interpret(env)?);
|
||||||
@ -759,7 +704,7 @@ impl Interpret for Member {
|
|||||||
}
|
}
|
||||||
env.call(*name, &values)
|
env.call(*name, &values)
|
||||||
}
|
}
|
||||||
_ => Err(Error::TypeError)?,
|
(mut head, kind) => assignment::project_memberkind(&mut head, kind).cloned(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -909,7 +854,7 @@ impl Interpret for If {
|
|||||||
}
|
}
|
||||||
impl Interpret for For {
|
impl Interpret for For {
|
||||||
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
|
fn interpret(&self, env: &mut Environment) -> IResult<ConValue> {
|
||||||
let Self { bind: name, cond, pass, fail } = self;
|
let Self { bind, cond, pass, fail } = self;
|
||||||
let cond = cond.interpret(env)?;
|
let cond = cond.interpret(env)?;
|
||||||
// TODO: A better iterator model
|
// TODO: A better iterator model
|
||||||
let mut bounds: Box<dyn Iterator<Item = ConValue>> = match &cond {
|
let mut bounds: Box<dyn Iterator<Item = ConValue>> = match &cond {
|
||||||
@ -921,8 +866,10 @@ impl Interpret for For {
|
|||||||
};
|
};
|
||||||
loop {
|
loop {
|
||||||
let mut env = env.frame("loop variable");
|
let mut env = env.frame("loop variable");
|
||||||
if let Some(loop_var) = bounds.next() {
|
if let Some(value) = bounds.next() {
|
||||||
env.insert(*name, Some(loop_var));
|
for (name, value) in pattern::substitution(bind, value)? {
|
||||||
|
env.insert(*name, Some(value));
|
||||||
|
}
|
||||||
match pass.interpret(&mut env) {
|
match pass.interpret(&mut env) {
|
||||||
Err(Error::Break(value)) => return Ok(value),
|
Err(Error::Break(value)) => return Ok(value),
|
||||||
Err(Error::Continue) => continue,
|
Err(Error::Continue) => continue,
|
||||||
|
@ -25,6 +25,8 @@ pub mod function;
|
|||||||
|
|
||||||
pub mod builtin;
|
pub mod builtin;
|
||||||
|
|
||||||
|
pub mod pattern;
|
||||||
|
|
||||||
pub mod env;
|
pub mod env;
|
||||||
|
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
130
compiler/cl-interpret/src/pattern.rs
Normal file
130
compiler/cl-interpret/src/pattern.rs
Normal file
@ -0,0 +1,130 @@
|
|||||||
|
//! Unification algorithm for cl-ast patterns and ConValues
|
||||||
|
//!
|
||||||
|
//! [`variables()`] returns a flat list of symbols that are bound by a given pattern
|
||||||
|
//! [`substitution()`] unifies a ConValue with a pattern, and produces a list of bound names
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
convalue::ConValue,
|
||||||
|
error::{Error, IResult},
|
||||||
|
};
|
||||||
|
use cl_ast::{Literal, Pattern, Sym};
|
||||||
|
use std::{collections::HashMap, rc::Rc};
|
||||||
|
|
||||||
|
/// Gets the path variables in the given Pattern
|
||||||
|
pub fn variables(pat: &Pattern) -> Vec<&Sym> {
|
||||||
|
fn patvars<'p>(set: &mut Vec<&'p Sym>, pat: &'p Pattern) {
|
||||||
|
match pat {
|
||||||
|
Pattern::Name(name) if &**name == "_" => {}
|
||||||
|
Pattern::Name(name) => set.push(name),
|
||||||
|
Pattern::Literal(_) => {}
|
||||||
|
Pattern::Ref(_, pattern) => patvars(set, pattern),
|
||||||
|
Pattern::Tuple(patterns) | Pattern::Array(patterns) => {
|
||||||
|
patterns.iter().for_each(|pat| patvars(set, pat))
|
||||||
|
}
|
||||||
|
Pattern::Struct(_path, items) => {
|
||||||
|
items.iter().for_each(|(name, pat)| match pat {
|
||||||
|
Some(pat) => patvars(set, pat),
|
||||||
|
None => set.push(name),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Pattern::TupleStruct(_path, items) => {
|
||||||
|
items.iter().for_each(|pat| patvars(set, pat));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut set = Vec::new();
|
||||||
|
patvars(&mut set, pat);
|
||||||
|
set
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends a substitution to the provided table
|
||||||
|
pub fn append_sub<'pat>(
|
||||||
|
sub: &mut HashMap<&'pat Sym, ConValue>,
|
||||||
|
pat: &'pat Pattern,
|
||||||
|
value: ConValue,
|
||||||
|
) -> IResult<()> {
|
||||||
|
match (pat, value) {
|
||||||
|
(Pattern::Array(patterns), ConValue::Array(values))
|
||||||
|
| (Pattern::Tuple(patterns), ConValue::Tuple(values)) => {
|
||||||
|
if patterns.len() != values.len() {
|
||||||
|
Err(Error::ArgNumber { want: patterns.len(), got: values.len() })?
|
||||||
|
}
|
||||||
|
for (pat, value) in patterns.iter().zip(Vec::from(values).into_iter()) {
|
||||||
|
append_sub(sub, pat, value)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
(Pattern::Tuple(patterns), ConValue::Empty) if patterns.is_empty() => Ok(()),
|
||||||
|
|
||||||
|
(Pattern::Literal(Literal::Bool(a)), ConValue::Bool(b)) => {
|
||||||
|
(*a == b).then_some(()).ok_or(Error::NotAssignable)
|
||||||
|
}
|
||||||
|
(Pattern::Literal(Literal::Char(a)), ConValue::Char(b)) => {
|
||||||
|
(*a == b).then_some(()).ok_or(Error::NotAssignable)
|
||||||
|
}
|
||||||
|
(Pattern::Literal(Literal::Float(a)), ConValue::Float(b)) => (f64::from_bits(*a) == b)
|
||||||
|
.then_some(())
|
||||||
|
.ok_or(Error::NotAssignable),
|
||||||
|
(Pattern::Literal(Literal::Int(a)), ConValue::Int(b)) => {
|
||||||
|
(b == *a as _).then_some(()).ok_or(Error::NotAssignable)
|
||||||
|
}
|
||||||
|
(Pattern::Literal(Literal::String(a)), ConValue::String(b)) => {
|
||||||
|
(*a == *b).then_some(()).ok_or(Error::NotAssignable)
|
||||||
|
}
|
||||||
|
(Pattern::Literal(_), _) => Err(Error::NotAssignable),
|
||||||
|
|
||||||
|
(Pattern::Name(name), _) if "_".eq(&**name) => Ok(()),
|
||||||
|
(Pattern::Name(name), value) => {
|
||||||
|
sub.insert(name, value);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
(Pattern::Ref(_, pat), ConValue::Ref(r)) => append_sub(sub, pat, Rc::unwrap_or_clone(r)),
|
||||||
|
|
||||||
|
(Pattern::Struct(path, patterns), ConValue::Struct(parts)) => {
|
||||||
|
let (name, mut values) = *parts;
|
||||||
|
if !path.ends_with(&name) {
|
||||||
|
Err(Error::TypeError)?
|
||||||
|
}
|
||||||
|
if patterns.len() != values.len() {
|
||||||
|
return Err(Error::ArgNumber { want: patterns.len(), got: values.len() });
|
||||||
|
}
|
||||||
|
for (name, pat) in patterns {
|
||||||
|
let value = values.remove(name).ok_or(Error::TypeError)?;
|
||||||
|
match pat {
|
||||||
|
Some(pat) => append_sub(sub, pat, value)?,
|
||||||
|
None => {
|
||||||
|
sub.insert(name, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
(Pattern::TupleStruct(path, patterns), ConValue::TupleStruct(parts)) => {
|
||||||
|
let (name, values) = *parts;
|
||||||
|
if !path.ends_with(&name) {
|
||||||
|
Err(Error::TypeError)?
|
||||||
|
}
|
||||||
|
if patterns.len() != values.len() {
|
||||||
|
Err(Error::ArgNumber { want: patterns.len(), got: values.len() })?
|
||||||
|
}
|
||||||
|
for (pat, value) in patterns.iter().zip(Vec::from(values).into_iter()) {
|
||||||
|
append_sub(sub, pat, value)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
(pat, value) => {
|
||||||
|
eprintln!("Could not match pattern `{pat}` with value `{value}`!");
|
||||||
|
Err(Error::NotAssignable)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Constructs a substitution from a pattern and a value
|
||||||
|
pub fn substitution(pat: &Pattern, value: ConValue) -> IResult<HashMap<&Sym, ConValue>> {
|
||||||
|
let mut sub = HashMap::new();
|
||||||
|
append_sub(&mut sub, pat, value)?;
|
||||||
|
Ok(sub)
|
||||||
|
}
|
@ -1,5 +1,6 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
use cl_ast::ExprKind;
|
||||||
use cl_lexer::error::{Error as LexError, Reason};
|
use cl_lexer::error::{Error as LexError, Reason};
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
pub type PResult<T> = Result<T, Error>;
|
pub type PResult<T> = Result<T, Error>;
|
||||||
@ -29,6 +30,7 @@ pub enum ErrorKind {
|
|||||||
ExpectedParsing {
|
ExpectedParsing {
|
||||||
want: Parsing,
|
want: Parsing,
|
||||||
},
|
},
|
||||||
|
InvalidPattern(Box<ExprKind>),
|
||||||
/// Indicates unfinished code
|
/// Indicates unfinished code
|
||||||
Todo(&'static str),
|
Todo(&'static str),
|
||||||
}
|
}
|
||||||
@ -148,6 +150,7 @@ impl Display for ErrorKind {
|
|||||||
ErrorKind::Unexpected(t) => write!(f, "Encountered unexpected token `{t}`"),
|
ErrorKind::Unexpected(t) => write!(f, "Encountered unexpected token `{t}`"),
|
||||||
ErrorKind::ExpectedToken { want: e, got: g } => write!(f, "Expected `{e}`, got `{g}`"),
|
ErrorKind::ExpectedToken { want: e, got: g } => write!(f, "Expected `{e}`, got `{g}`"),
|
||||||
ErrorKind::ExpectedParsing { want } => write!(f, "Expected {want}"),
|
ErrorKind::ExpectedParsing { want } => write!(f, "Expected {want}"),
|
||||||
|
ErrorKind::InvalidPattern(got) => write!(f, "Got invalid `{got}`"),
|
||||||
ErrorKind::Todo(unfinished) => write!(f, "TODO: {unfinished}"),
|
ErrorKind::Todo(unfinished) => write!(f, "TODO: {unfinished}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -459,12 +459,11 @@ impl Parse<'_> for Function {
|
|||||||
sign,
|
sign,
|
||||||
bind,
|
bind,
|
||||||
body: match p.peek_kind(P)? {
|
body: match p.peek_kind(P)? {
|
||||||
TokenKind::LCurly => Some(Block::parse(p)?),
|
|
||||||
TokenKind::Semi => {
|
TokenKind::Semi => {
|
||||||
p.consume_peeked();
|
p.consume_peeked();
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
t => Err(p.error(Unexpected(t), P))?,
|
_ => Some(Expr::parse(p)?),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -495,7 +494,7 @@ impl Parse<'_> for TypedParam {
|
|||||||
/// Parses a single function [parameter](Param)
|
/// Parses a single function [parameter](Param)
|
||||||
fn parse(p: &mut Parser) -> PResult<(Param, TyKind)> {
|
fn parse(p: &mut Parser) -> PResult<(Param, TyKind)> {
|
||||||
Ok((
|
Ok((
|
||||||
Param { mutability: Mutability::parse(p)?, name: Sym::parse(p)? },
|
Param { mutability: Mutability::parse(p)?, bind: Pattern::parse(p)? },
|
||||||
{
|
{
|
||||||
p.match_type(TokenKind::Colon, Parsing::Param)?;
|
p.match_type(TokenKind::Colon, Parsing::Param)?;
|
||||||
TyKind::parse(p)?
|
TyKind::parse(p)?
|
||||||
@ -1007,13 +1006,20 @@ impl Parse<'_> for Block {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Conditions (which precede curly-braced blocks) get special treatment
|
||||||
|
fn condition(p: &mut Parser) -> PResult<Expr> {
|
||||||
|
let start = p.loc();
|
||||||
|
let kind = prec::exprkind(p, prec::Precedence::Condition.level())?;
|
||||||
|
Ok(Expr { kind, extents: Span(start, p.loc()) })
|
||||||
|
}
|
||||||
|
|
||||||
impl Parse<'_> for While {
|
impl Parse<'_> for While {
|
||||||
/// [While] = `while` [Expr] [Block] [Else]?
|
/// [While] = `while` [Expr] [Block] [Else]?
|
||||||
#[rustfmt::skip]
|
#[rustfmt::skip]
|
||||||
fn parse(p: &mut Parser) -> PResult<While> {
|
fn parse(p: &mut Parser) -> PResult<While> {
|
||||||
p.match_type(TokenKind::While, Parsing::While)?;
|
p.match_type(TokenKind::While, Parsing::While)?;
|
||||||
Ok(While {
|
Ok(While {
|
||||||
cond: Expr::parse(p)?.into(),
|
cond: condition(p)?.into(),
|
||||||
pass: Block::parse(p)?.into(),
|
pass: Block::parse(p)?.into(),
|
||||||
fail: Else::parse(p)?
|
fail: Else::parse(p)?
|
||||||
})
|
})
|
||||||
@ -1026,7 +1032,7 @@ impl Parse<'_> for If {
|
|||||||
fn parse(p: &mut Parser) -> PResult<If> {
|
fn parse(p: &mut Parser) -> PResult<If> {
|
||||||
p.match_type(TokenKind::If, Parsing::If)?;
|
p.match_type(TokenKind::If, Parsing::If)?;
|
||||||
Ok(If {
|
Ok(If {
|
||||||
cond: Expr::parse(p)?.into(),
|
cond: condition(p)?.into(),
|
||||||
pass: Block::parse(p)?.into(),
|
pass: Block::parse(p)?.into(),
|
||||||
fail: Else::parse(p)?,
|
fail: Else::parse(p)?,
|
||||||
})
|
})
|
||||||
@ -1034,15 +1040,15 @@ impl Parse<'_> for If {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Parse<'_> for For {
|
impl Parse<'_> for For {
|
||||||
/// [For]: `for` Pattern (TODO) `in` [Expr] [Block] [Else]?
|
/// [For]: `for` [Pattern] `in` [Expr] [Block] [Else]?
|
||||||
#[rustfmt::skip]
|
#[rustfmt::skip]
|
||||||
fn parse(p: &mut Parser) -> PResult<For> {
|
fn parse(p: &mut Parser) -> PResult<For> {
|
||||||
p.match_type(TokenKind::For, Parsing::For)?;
|
p.match_type(TokenKind::For, Parsing::For)?;
|
||||||
let bind = Sym::parse(p)?;
|
let bind = Pattern::parse(p)?;
|
||||||
p.match_type(TokenKind::In, Parsing::For)?;
|
p.match_type(TokenKind::In, Parsing::For)?;
|
||||||
Ok(For {
|
Ok(For {
|
||||||
bind,
|
bind,
|
||||||
cond: Expr::parse(p)?.into(),
|
cond: condition(p)?.into(),
|
||||||
pass: Block::parse(p)?.into(),
|
pass: Block::parse(p)?.into(),
|
||||||
fail: Else::parse(p)?,
|
fail: Else::parse(p)?,
|
||||||
})
|
})
|
||||||
@ -1081,9 +1087,8 @@ impl Parse<'_> for Return {
|
|||||||
|
|
||||||
impl Parse<'_> for Pattern {
|
impl Parse<'_> for Pattern {
|
||||||
fn parse(p: &mut Parser<'_>) -> PResult<Self> {
|
fn parse(p: &mut Parser<'_>) -> PResult<Self> {
|
||||||
let value = prec::exprkind(p, prec::Precedence::Highest.level())?;
|
let value = prec::exprkind(p, prec::Precedence::Pattern.level())?;
|
||||||
Pattern::try_from(value)
|
Pattern::try_from(value).map_err(|e| p.error(InvalidPattern(e.into()), Parsing::Pattern))
|
||||||
.map_err(|_| p.error(ExpectedParsing { want: Parsing::Pattern }, Parsing::Pattern))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -44,7 +44,9 @@ pub fn exprkind(p: &mut Parser, power: u8) -> PResult<ExprKind> {
|
|||||||
Some(match op {
|
Some(match op {
|
||||||
TokenKind::LBrack => Precedence::Index,
|
TokenKind::LBrack => Precedence::Index,
|
||||||
TokenKind::LParen => Precedence::Call,
|
TokenKind::LParen => Precedence::Call,
|
||||||
|
TokenKind::LCurly => Precedence::Structor,
|
||||||
TokenKind::Dot => Precedence::Member,
|
TokenKind::Dot => Precedence::Member,
|
||||||
|
TokenKind::As => Precedence::Cast,
|
||||||
_ => None?,
|
_ => None?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -55,25 +57,36 @@ pub fn exprkind(p: &mut Parser, power: u8) -> PResult<ExprKind> {
|
|||||||
if before < power {
|
if before < power {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
p.consume_peeked();
|
|
||||||
|
|
||||||
head = match op {
|
head = match op {
|
||||||
TokenKind::LBrack => {
|
TokenKind::LBrack => {
|
||||||
|
p.consume_peeked();
|
||||||
let indices =
|
let indices =
|
||||||
sep(Expr::parse, TokenKind::Comma, TokenKind::RBrack, parsing)(p)?;
|
sep(Expr::parse, TokenKind::Comma, TokenKind::RBrack, parsing)(p)?;
|
||||||
p.match_type(TokenKind::RBrack, parsing)?;
|
p.match_type(TokenKind::RBrack, parsing)?;
|
||||||
ExprKind::Index(Index { head: head.into(), indices })
|
ExprKind::Index(Index { head: head.into(), indices })
|
||||||
}
|
}
|
||||||
TokenKind::LParen => {
|
TokenKind::LParen => {
|
||||||
|
p.consume_peeked();
|
||||||
let exprs = sep(Expr::parse, TokenKind::Comma, TokenKind::RParen, parsing)(p)?;
|
let exprs = sep(Expr::parse, TokenKind::Comma, TokenKind::RParen, parsing)(p)?;
|
||||||
p.match_type(TokenKind::RParen, parsing)?;
|
p.match_type(TokenKind::RParen, parsing)?;
|
||||||
Binary { kind: BinaryKind::Call, parts: (head, Tuple { exprs }.into()).into() }
|
Binary { kind: BinaryKind::Call, parts: (head, Tuple { exprs }.into()).into() }
|
||||||
.into()
|
.into()
|
||||||
}
|
}
|
||||||
|
TokenKind::LCurly => match head {
|
||||||
|
ExprKind::Path(path) => ExprKind::Structor(structor_body(p, path)?),
|
||||||
|
_ => break,
|
||||||
|
},
|
||||||
TokenKind::Dot => {
|
TokenKind::Dot => {
|
||||||
|
p.consume_peeked();
|
||||||
let kind = MemberKind::parse(p)?;
|
let kind = MemberKind::parse(p)?;
|
||||||
Member { head: Box::new(head), kind }.into()
|
Member { head: Box::new(head), kind }.into()
|
||||||
}
|
}
|
||||||
|
TokenKind::As => {
|
||||||
|
p.consume_peeked();
|
||||||
|
let ty = Ty::parse(p)?;
|
||||||
|
Cast { head: head.into(), ty }.into()
|
||||||
|
}
|
||||||
_ => Err(p.error(Unexpected(op), parsing))?,
|
_ => Err(p.error(Unexpected(op), parsing))?,
|
||||||
};
|
};
|
||||||
continue;
|
continue;
|
||||||
@ -217,11 +230,7 @@ fn exprkind_group(p: &mut Parser) -> PResult<ExprKind> {
|
|||||||
|
|
||||||
/// Parses an expression beginning with a [Path] (i.e. [Path] or [Structor])
|
/// Parses an expression beginning with a [Path] (i.e. [Path] or [Structor])
|
||||||
fn exprkind_pathlike(p: &mut Parser) -> PResult<ExprKind> {
|
fn exprkind_pathlike(p: &mut Parser) -> PResult<ExprKind> {
|
||||||
let head = Path::parse(p)?;
|
Path::parse(p).map(Into::into)
|
||||||
Ok(match p.match_type(TokenKind::Colon, Parsing::Path) {
|
|
||||||
Ok(_) => ExprKind::Structor(structor_body(p, head)?),
|
|
||||||
Err(_) => ExprKind::Path(head),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [Structor]Body = `{` ([Fielder] `,`)* [Fielder]? `}`
|
/// [Structor]Body = `{` ([Fielder] `,`)* [Fielder]? `}`
|
||||||
@ -244,6 +253,9 @@ fn structor_body(p: &mut Parser, to: Path) -> PResult<Structor> {
|
|||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
pub enum Precedence {
|
pub enum Precedence {
|
||||||
Assign,
|
Assign,
|
||||||
|
Pattern, // A pattern can contain a structor
|
||||||
|
Structor, // A structor is never a valid conditional
|
||||||
|
Condition, // Anything that syntactically needs a block following it
|
||||||
Logic,
|
Logic,
|
||||||
Compare,
|
Compare,
|
||||||
Range,
|
Range,
|
||||||
@ -256,7 +268,6 @@ pub enum Precedence {
|
|||||||
Cast,
|
Cast,
|
||||||
Member, // left-associative
|
Member, // left-associative
|
||||||
Call,
|
Call,
|
||||||
Highest,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Precedence {
|
impl Precedence {
|
||||||
@ -284,7 +295,9 @@ impl Precedence {
|
|||||||
|
|
||||||
pub fn postfix(self) -> Option<(u8, ())> {
|
pub fn postfix(self) -> Option<(u8, ())> {
|
||||||
match self {
|
match self {
|
||||||
Self::Index | Self::Call | Self::Member => Some((self.level(), ())),
|
Self::Structor | Self::Index | Self::Call | Self::Member | Self::Cast => {
|
||||||
|
Some((self.level(), ()))
|
||||||
|
}
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -428,7 +428,7 @@ pub mod yamlify {
|
|||||||
impl Yamlify for Pattern {
|
impl Yamlify for Pattern {
|
||||||
fn yaml(&self, y: &mut Yamler) {
|
fn yaml(&self, y: &mut Yamler) {
|
||||||
match self {
|
match self {
|
||||||
Pattern::Path(path) => y.value(path),
|
Pattern::Name(name) => y.value(name),
|
||||||
Pattern::Literal(literal) => y.value(literal),
|
Pattern::Literal(literal) => y.value(literal),
|
||||||
Pattern::Ref(mutability, pattern) => {
|
Pattern::Ref(mutability, pattern) => {
|
||||||
y.pair("mutability", mutability).pair("subpattern", pattern)
|
y.pair("mutability", mutability).pair("subpattern", pattern)
|
||||||
@ -438,13 +438,20 @@ pub mod yamlify {
|
|||||||
Pattern::Struct(path, items) => {
|
Pattern::Struct(path, items) => {
|
||||||
{
|
{
|
||||||
let mut y = y.key("Struct");
|
let mut y = y.key("Struct");
|
||||||
y.pair("name", path);
|
y.yaml(path);
|
||||||
for (name, item) in items {
|
for (name, item) in items {
|
||||||
y.pair(name, item);
|
y.pair(name, item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
y
|
y
|
||||||
}
|
}
|
||||||
|
Pattern::TupleStruct(path, items) => {
|
||||||
|
{
|
||||||
|
let mut y = y.key("TupleStruct");
|
||||||
|
y.yaml(path).list(items);
|
||||||
|
}
|
||||||
|
y
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -636,8 +643,8 @@ pub mod yamlify {
|
|||||||
}
|
}
|
||||||
impl Yamlify for Param {
|
impl Yamlify for Param {
|
||||||
fn yaml(&self, y: &mut Yamler) {
|
fn yaml(&self, y: &mut Yamler) {
|
||||||
let Self { mutability, name } = self;
|
let Self { mutability, bind } = self;
|
||||||
y.key("Param").yaml(mutability).pair("name", name);
|
y.key("Param").yaml(mutability).pair("pat", bind);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Yamlify for Ty {
|
impl Yamlify for Ty {
|
||||||
|
@ -108,7 +108,7 @@ impl<'a> Visit<'a> for Populator<'_, 'a> {
|
|||||||
self.visit_ty_fn(sign);
|
self.visit_ty_fn(sign);
|
||||||
bind.iter().for_each(|p| self.visit_param(p));
|
bind.iter().for_each(|p| self.visit_param(p));
|
||||||
if let Some(b) = body {
|
if let Some(b) = body {
|
||||||
self.visit_block(b)
|
self.visit_expr(b)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
13
grammar.ebnf
13
grammar.ebnf
@ -26,7 +26,7 @@ Static = "static" Mutability Identifier ':' Ty '=' Expr ';' ;
|
|||||||
Module = "mod" Identifier ModuleKind ;
|
Module = "mod" Identifier ModuleKind ;
|
||||||
ModuleKind = '{' Item* '}' | ';' ;
|
ModuleKind = '{' Item* '}' | ';' ;
|
||||||
|
|
||||||
Function = "fn" Identifier '(' (Param ',')* Param? ')' ('->' Ty)? Block? ;
|
Function = "fn" Identifier '(' (Param ',')* Param? ')' ('->' Ty)? (Expr | ';') ;
|
||||||
Param = Mutability Identifier ':' Ty ;
|
Param = Mutability Identifier ':' Ty ;
|
||||||
|
|
||||||
Struct = "struct" Identifier (StructTuple | StructBody)?;
|
Struct = "struct" Identifier (StructTuple | StructBody)?;
|
||||||
@ -127,6 +127,17 @@ Block = '{' Stmt* '}';
|
|||||||
Group = Empty | '(' (Expr | Tuple) ')' ;
|
Group = Empty | '(' (Expr | Tuple) ')' ;
|
||||||
Tuple = (Expr ',')* Expr? ;
|
Tuple = (Expr ',')* Expr? ;
|
||||||
|
|
||||||
|
|
||||||
|
Match = "match" { (MatchArm ',')* MatchArm? } ;
|
||||||
|
MatchArm = Pattern '=>' Expr ;
|
||||||
|
Pattern = Path
|
||||||
|
| Literal
|
||||||
|
| '&' "mut"? Pattern
|
||||||
|
| '(' (Pattern ',')* (Pattern | '..' )? ')'
|
||||||
|
| '[' (Pattern ',')* (Pattern | '..' Identifier?)? ']'
|
||||||
|
| StructPattern
|
||||||
|
;
|
||||||
|
|
||||||
Loop = "loop" Block ;
|
Loop = "loop" Block ;
|
||||||
While = "while" Expr Block Else ;
|
While = "while" Expr Block Else ;
|
||||||
If = "if" Expr Block Else ;
|
If = "if" Expr Block Else ;
|
||||||
|
@ -112,6 +112,17 @@ impl<'a> Editor<'a> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn print_err<W: Write>(&self, w: &mut W, err: impl Display) -> ReplResult<()> {
|
||||||
|
queue!(
|
||||||
|
w,
|
||||||
|
SavePosition,
|
||||||
|
Clear(ClearType::UntilNewLine),
|
||||||
|
Print(err),
|
||||||
|
RestorePosition
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Prints the characters after the cursor on the current line.
|
/// Prints the characters after the cursor on the current line.
|
||||||
pub fn print_tail<W: Write>(&self, w: &mut W) -> ReplResult<()> {
|
pub fn print_tail<W: Write>(&self, w: &mut W) -> ReplResult<()> {
|
||||||
let Self { tail, .. } = self;
|
let Self { tail, .. } = self;
|
||||||
|
@ -49,7 +49,7 @@ where F: FnMut(&str) -> Result<Response, Box<dyn Error>> {
|
|||||||
Ok(Response::Deny) => rl.deny(),
|
Ok(Response::Deny) => rl.deny(),
|
||||||
Ok(Response::Break) => break,
|
Ok(Response::Break) => break,
|
||||||
Ok(Response::Continue) => continue,
|
Ok(Response::Continue) => continue,
|
||||||
Err(e) => print!("\x1b[40G\x1b[A\x1bJ\x1b[91m{e}\x1b[0m\x1b[B"),
|
Err(e) => rl.print_inline(format_args!("\x1b[40G\x1b[91m{e}\x1b[0m"))?,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
@ -111,6 +111,15 @@ impl<'a, R: Read> Repline<'a, R> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/// Prints a message without moving the cursor
|
||||||
|
pub fn print_inline(&mut self, value: impl std::fmt::Display) -> ReplResult<()> {
|
||||||
|
let mut stdout = stdout().lock();
|
||||||
|
self.print_err(&mut stdout, value)
|
||||||
|
}
|
||||||
|
/// Prints a message (ideally an error) without moving the cursor
|
||||||
|
fn print_err<W: Write>(&mut self, w: &mut W, value: impl std::fmt::Display) -> ReplResult<()> {
|
||||||
|
self.ed.print_err(w, value)
|
||||||
|
}
|
||||||
/// Handle ANSI Escape
|
/// Handle ANSI Escape
|
||||||
fn escape<W: Write>(&mut self, w: &mut W) -> ReplResult<()> {
|
fn escape<W: Write>(&mut self, w: &mut W) -> ReplResult<()> {
|
||||||
match self.input.next().ok_or(Error::EndOfInput)?? {
|
match self.input.next().ok_or(Error::EndOfInput)?? {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user