use std::fmt;
use std::rc::Rc;
use rhue_common::Span;
pub type NameId = u32;
#[derive(Clone, Debug, PartialEq)]
pub struct Name {
pub text: Rc<str>,
pub id: NameId,
pub span: Span,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Chunk {
pub body: Block,
pub span: Span,
pub name_count: u32,
pub mode: Option<(TypeMode, Span)>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TypeMode {
NoCheck,
NonStrict,
Strict,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Block {
pub stmts: Vec<Stmt>,
pub ret: Option<Return>,
pub span: Span,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Return {
pub values: Vec<Expr>,
pub span: Span,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Stmt {
pub kind: StmtKind,
pub span: Span,
}
#[derive(Clone, Debug, PartialEq)]
pub enum StmtKind {
Local {
names: Vec<Name>,
types: Vec<Option<TypeExpr>>,
values: Vec<Expr>,
},
Assign {
targets: Vec<Expr>,
values: Vec<Expr>,
},
CompoundAssign {
op: BinOp,
op_span: Span,
target: Expr,
value: Expr,
},
Do(Block),
While {
cond: Expr,
body: Block,
},
Repeat {
body: Block,
cond: Expr,
},
If {
branches: Vec<(Expr, Block)>,
else_block: Option<Block>,
},
NumericFor {
var: Name,
var_type: Option<Box<TypeExpr>>,
start: Expr,
limit: Expr,
step: Option<Expr>,
body: Block,
},
Break,
Continue,
Call(Expr),
Function {
target: Expr,
func: Rc<FunctionBody>,
},
LocalFunction {
name: Name,
func: Rc<FunctionBody>,
},
GenericFor {
names: Vec<Name>,
types: Vec<Option<TypeExpr>>,
exprs: Vec<Expr>,
body: Block,
},
TypeAlias(Rc<TypeAlias>),
}
#[derive(Clone, Debug, PartialEq)]
pub struct TypeAlias {
pub name: Rc<str>,
pub name_span: Span,
pub generics: Vec<GenericParam>,
pub ty: TypeExpr,
pub exported: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub struct FunctionBody {
pub generics: Vec<GenericParam>,
pub params: Vec<Name>,
pub param_types: Vec<Option<TypeExpr>>,
pub is_vararg: bool,
pub vararg_type: Option<TypeExpr>,
pub return_type: Option<TypePack>,
pub is_method: bool,
pub body: Block,
pub name: Option<Rc<str>>,
pub span: Span,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Expr {
pub kind: ExprKind,
pub span: Span,
}
#[derive(Clone, Debug, PartialEq)]
pub enum ExprKind {
Nil,
Bool(bool),
Number(f64),
String(Rc<str>),
Interp(Vec<InterpPart>),
Name(Name),
Group(Box<Expr>),
Unary {
op: UnOp,
op_span: Span,
operand: Box<Expr>,
},
Binary {
op: BinOp,
op_span: Span,
lhs: Box<Expr>,
rhs: Box<Expr>,
},
IfElse {
branches: Vec<(Expr, Expr)>,
else_expr: Box<Expr>,
},
Call {
callee: Box<Expr>,
args: Vec<Expr>,
},
Vararg,
Function(Rc<FunctionBody>),
Index {
object: Box<Expr>,
key: Box<Expr>,
},
MethodCall {
object: Box<Expr>,
method: Rc<str>,
method_span: Span,
args: Vec<Expr>,
},
Table(Vec<TableItem>),
Cast {
expr: Box<Expr>,
ty: Box<TypeExpr>,
},
}
#[derive(Clone, Debug, PartialEq)]
pub struct TypeExpr {
pub kind: TypeKind,
pub span: Span,
}
#[derive(Clone, Debug, PartialEq)]
pub enum TypeKind {
Name {
name: Rc<str>,
args: Vec<TypeExpr>,
},
Singleton(Singleton),
Typeof(Box<Expr>),
Optional(Box<TypeExpr>),
Union(Vec<TypeExpr>),
Intersection(Vec<TypeExpr>),
Table {
props: Vec<TableProp>,
indexer: Option<Box<(TypeExpr, TypeExpr)>>,
},
GenericPack(Rc<str>),
Pack(TypePack),
Function {
generics: Vec<GenericParam>,
params: Vec<FnParam>,
variadic: Option<Box<TypeExpr>>,
returns: TypePack,
},
}
#[derive(Clone, Debug, PartialEq)]
pub enum Singleton {
Bool(bool),
String(Rc<str>),
}
#[derive(Clone, Debug, PartialEq)]
pub struct TableProp {
pub name: Rc<str>,
pub ty: TypeExpr,
pub span: Span,
pub access: Access,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Access {
#[default]
ReadWrite,
Read,
Write,
}
impl Access {
pub fn can_read(self) -> bool {
self != Access::Write
}
pub fn can_write(self) -> bool {
self != Access::Read
}
pub fn prefix(self) -> &'static str {
match self {
Access::ReadWrite => "",
Access::Read => "read ",
Access::Write => "write ",
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct FnParam {
pub name: Option<Rc<str>>,
pub ty: TypeExpr,
}
#[derive(Clone, Debug, PartialEq)]
pub struct GenericParam {
pub name: Rc<str>,
pub span: Span,
pub pack: bool,
pub default: Option<TypeExpr>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TypePack {
pub types: Vec<TypeExpr>,
pub variadic: Option<Box<TypeExpr>>,
pub span: Span,
}
impl fmt::Display for TypeExpr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.kind {
TypeKind::Name { name, args } => {
f.write_str(name)?;
if !args.is_empty() {
let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
write!(f, "<{}>", args.join(", "))?;
}
Ok(())
}
TypeKind::Singleton(Singleton::Bool(b)) => write!(f, "{b}"),
TypeKind::Singleton(Singleton::String(s)) => write!(f, "{s:?}"),
TypeKind::Typeof(e) => write!(f, "typeof({e})"),
TypeKind::Optional(t) => write!(f, "{t}?"),
TypeKind::GenericPack(name) => write!(f, "{name}..."),
TypeKind::Pack(p) => write!(f, "{p}"),
TypeKind::Union(ts) | TypeKind::Intersection(ts) => {
let sep = if matches!(self.kind, TypeKind::Union(_)) {
" | "
} else {
" & "
};
let parts: Vec<String> = ts.iter().map(|t| t.to_string()).collect();
write!(f, "({})", parts.join(sep))
}
TypeKind::Table { props, indexer } => {
let mut parts: Vec<String> = props
.iter()
.map(|p| format!("{}{}: {}", p.access.prefix(), p.name, p.ty))
.collect();
if let Some(ix) = indexer {
parts.push(format!("[{}]: {}", ix.0, ix.1));
}
write!(f, "{{{}}}", parts.join(", "))
}
TypeKind::Function {
generics,
params,
variadic,
returns,
} => {
if !generics.is_empty() {
let g: Vec<String> = generics
.iter()
.map(|g| format!("{}{}", g.name, if g.pack { "..." } else { "" }))
.collect();
write!(f, "<{}>", g.join(", "))?;
}
let mut ps: Vec<String> = params.iter().map(|p| p.ty.to_string()).collect();
if let Some(v) = variadic {
ps.push(variadic_text(v));
}
write!(f, "({}) -> {returns}", ps.join(", "))
}
}
}
}
impl fmt::Display for TypePack {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut parts: Vec<String> = self.types.iter().map(|t| t.to_string()).collect();
if let Some(v) = &self.variadic {
parts.push(variadic_text(v));
}
write!(f, "({})", parts.join(", "))
}
}
fn variadic_text(v: &TypeExpr) -> String {
match &v.kind {
TypeKind::GenericPack(_) => v.to_string(),
_ => format!("...{v}"),
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum TableItem {
Positional(Expr),
Keyed { key: Expr, value: Expr },
}
impl ExprKind {
pub fn is_multi(&self) -> bool {
matches!(
self,
ExprKind::Call { .. } | ExprKind::MethodCall { .. } | ExprKind::Vararg
)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum InterpPart {
Text(Rc<str>),
Expr(Expr),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnOp {
Neg,
Not,
Len,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
IDiv,
Mod,
Pow,
Concat,
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
And,
Or,
}
pub const UNARY_BP: u8 = 30;
impl BinOp {
pub fn binding_power(self) -> (u8, u8) {
use BinOp::*;
match self {
Or => (1, 2),
And => (3, 4),
Eq | Ne | Lt | Le | Gt | Ge => (5, 6),
Concat => (9, 8),
Add | Sub => (10, 11),
Mul | Div | IDiv | Mod => (20, 21),
Pow => (41, 40),
}
}
pub fn symbol(self) -> &'static str {
use BinOp::*;
match self {
Add => "+",
Sub => "-",
Mul => "*",
Div => "/",
IDiv => "//",
Mod => "%",
Pow => "^",
Concat => "..",
Eq => "==",
Ne => "~=",
Lt => "<",
Le => "<=",
Gt => ">",
Ge => ">=",
And => "and",
Or => "or",
}
}
}
impl UnOp {
pub fn symbol(self) -> &'static str {
match self {
UnOp::Neg => "-",
UnOp::Not => "not",
UnOp::Len => "#",
}
}
}
impl fmt::Display for Expr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.kind {
ExprKind::Nil => f.write_str("nil"),
ExprKind::Bool(b) => write!(f, "{b}"),
ExprKind::Number(n) => write!(f, "{n}"),
ExprKind::String(s) => write!(f, "{s:?}"),
ExprKind::Name(n) => f.write_str(&n.text),
ExprKind::Group(e) => write!(f, "(group {e})"),
ExprKind::Unary { op, operand, .. } => write!(f, "({} {operand})", op.symbol()),
ExprKind::Binary { op, lhs, rhs, .. } => write!(f, "({} {lhs} {rhs})", op.symbol()),
ExprKind::IfElse {
branches,
else_expr,
} => {
f.write_str("(if")?;
for (c, v) in branches {
write!(f, " {c} {v}")?;
}
write!(f, " {else_expr})")
}
ExprKind::Call { callee, args } => {
write!(f, "(call {callee}")?;
for a in args {
write!(f, " {a}")?;
}
f.write_str(")")
}
ExprKind::Vararg => f.write_str("..."),
ExprKind::Interp(parts) => {
f.write_str("(interp")?;
for part in parts {
match part {
InterpPart::Text(t) => write!(f, " {t:?}")?,
InterpPart::Expr(e) => write!(f, " {e}")?,
}
}
f.write_str(")")
}
ExprKind::Function(func) => {
let mut params: Vec<&str> = func.params.iter().map(|p| &*p.text).collect();
if func.is_vararg {
params.push("...");
}
write!(f, "(function ({}))", params.join(" "))
}
ExprKind::Index { object, key } => write!(f, "(index {object} {key})"),
ExprKind::Cast { expr, ty } => write!(f, "(:: {expr} {ty})"),
ExprKind::MethodCall {
object,
method,
args,
..
} => {
write!(f, "(method {object} {method}")?;
for a in args {
write!(f, " {a}")?;
}
f.write_str(")")
}
ExprKind::Table(items) => {
f.write_str("(table")?;
for item in items {
match item {
TableItem::Positional(e) => write!(f, " {e}")?,
TableItem::Keyed { key, value } => write!(f, " [{key}]={value}")?,
}
}
f.write_str(")")
}
}
}
}