1use std::fmt;
2use std::rc::Rc;
3
4use rhue_common::Span;
5
6pub type NameId = u32;
10
11#[derive(Clone, Debug, PartialEq)]
12pub struct Name {
13 pub text: Rc<str>,
14 pub id: NameId,
15 pub span: Span,
16}
17
18#[derive(Clone, Debug, PartialEq)]
19pub struct Chunk {
20 pub body: Block,
21 pub span: Span,
22 pub name_count: u32,
24 pub mode: Option<(TypeMode, Span)>,
26}
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
31pub enum TypeMode {
32 NoCheck,
34 NonStrict,
37 Strict,
39}
40
41#[derive(Clone, Debug, PartialEq)]
42pub struct Block {
43 pub stmts: Vec<Stmt>,
44 pub ret: Option<Return>,
45 pub span: Span,
46}
47
48#[derive(Clone, Debug, PartialEq)]
49pub struct Return {
50 pub values: Vec<Expr>,
51 pub span: Span,
52}
53
54#[derive(Clone, Debug, PartialEq)]
55pub struct Stmt {
56 pub kind: StmtKind,
57 pub span: Span,
58}
59
60#[derive(Clone, Debug, PartialEq)]
61pub enum StmtKind {
62 Local {
64 names: Vec<Name>,
65 types: Vec<Option<TypeExpr>>,
67 values: Vec<Expr>,
68 },
69 Assign {
71 targets: Vec<Expr>,
72 values: Vec<Expr>,
73 },
74 CompoundAssign {
76 op: BinOp,
77 op_span: Span,
78 target: Expr,
79 value: Expr,
80 },
81 Do(Block),
82 While {
83 cond: Expr,
84 body: Block,
85 },
86 Repeat {
88 body: Block,
89 cond: Expr,
90 },
91 If {
92 branches: Vec<(Expr, Block)>,
93 else_block: Option<Block>,
94 },
95 NumericFor {
96 var: Name,
97 var_type: Option<Box<TypeExpr>>,
98 start: Expr,
99 limit: Expr,
100 step: Option<Expr>,
101 body: Block,
102 },
103 Break,
104 Continue,
105 Call(Expr),
107 Function {
109 target: Expr,
110 func: Rc<FunctionBody>,
111 },
112 LocalFunction {
115 name: Name,
116 func: Rc<FunctionBody>,
117 },
118 GenericFor {
122 names: Vec<Name>,
123 types: Vec<Option<TypeExpr>>,
124 exprs: Vec<Expr>,
125 body: Block,
126 },
127 TypeAlias(Rc<TypeAlias>),
129}
130
131#[derive(Clone, Debug, PartialEq)]
132pub struct TypeAlias {
133 pub name: Rc<str>,
134 pub name_span: Span,
135 pub generics: Vec<GenericParam>,
136 pub ty: TypeExpr,
137 pub exported: bool,
138}
139
140#[derive(Clone, Debug, PartialEq)]
142pub struct FunctionBody {
143 pub generics: Vec<GenericParam>,
145 pub params: Vec<Name>,
146 pub param_types: Vec<Option<TypeExpr>>,
149 pub is_vararg: bool,
150 pub vararg_type: Option<TypeExpr>,
152 pub return_type: Option<TypePack>,
154 pub is_method: bool,
156 pub body: Block,
157 pub name: Option<Rc<str>>,
159 pub span: Span,
160}
161
162#[derive(Clone, Debug, PartialEq)]
163pub struct Expr {
164 pub kind: ExprKind,
165 pub span: Span,
166}
167
168#[derive(Clone, Debug, PartialEq)]
169pub enum ExprKind {
170 Nil,
171 Bool(bool),
172 Number(f64),
173 String(Rc<str>),
174 Interp(Vec<InterpPart>),
177 Name(Name),
178 Group(Box<Expr>),
181 Unary {
182 op: UnOp,
183 op_span: Span,
184 operand: Box<Expr>,
185 },
186 Binary {
187 op: BinOp,
188 op_span: Span,
189 lhs: Box<Expr>,
190 rhs: Box<Expr>,
191 },
192 IfElse {
194 branches: Vec<(Expr, Expr)>,
195 else_expr: Box<Expr>,
196 },
197 Call {
199 callee: Box<Expr>,
200 args: Vec<Expr>,
201 },
202 Vararg,
204 Function(Rc<FunctionBody>),
206 Index {
208 object: Box<Expr>,
209 key: Box<Expr>,
210 },
211 MethodCall {
213 object: Box<Expr>,
214 method: Rc<str>,
215 method_span: Span,
216 args: Vec<Expr>,
217 },
218 Table(Vec<TableItem>),
220 Cast {
222 expr: Box<Expr>,
223 ty: Box<TypeExpr>,
224 },
225}
226
227#[derive(Clone, Debug, PartialEq)]
231pub struct TypeExpr {
232 pub kind: TypeKind,
233 pub span: Span,
234}
235
236#[derive(Clone, Debug, PartialEq)]
237pub enum TypeKind {
238 Name {
240 name: Rc<str>,
241 args: Vec<TypeExpr>,
242 },
243 Singleton(Singleton),
245 Typeof(Box<Expr>),
247 Optional(Box<TypeExpr>),
249 Union(Vec<TypeExpr>),
250 Intersection(Vec<TypeExpr>),
251 Table {
253 props: Vec<TableProp>,
254 indexer: Option<Box<(TypeExpr, TypeExpr)>>,
255 },
256 GenericPack(Rc<str>),
259 Pack(TypePack),
261 Function {
263 generics: Vec<GenericParam>,
264 params: Vec<FnParam>,
265 variadic: Option<Box<TypeExpr>>,
266 returns: TypePack,
267 },
268}
269
270#[derive(Clone, Debug, PartialEq)]
271pub enum Singleton {
272 Bool(bool),
273 String(Rc<str>),
274}
275
276#[derive(Clone, Debug, PartialEq)]
277pub struct TableProp {
278 pub name: Rc<str>,
279 pub ty: TypeExpr,
280 pub span: Span,
281 pub access: Access,
283}
284
285#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
287pub enum Access {
288 #[default]
289 ReadWrite,
290 Read,
292 Write,
294}
295
296impl Access {
297 pub fn can_read(self) -> bool {
298 self != Access::Write
299 }
300
301 pub fn can_write(self) -> bool {
302 self != Access::Read
303 }
304
305 pub fn prefix(self) -> &'static str {
307 match self {
308 Access::ReadWrite => "",
309 Access::Read => "read ",
310 Access::Write => "write ",
311 }
312 }
313}
314
315#[derive(Clone, Debug, PartialEq)]
316pub struct FnParam {
317 pub name: Option<Rc<str>>,
319 pub ty: TypeExpr,
320}
321
322#[derive(Clone, Debug, PartialEq)]
323pub struct GenericParam {
324 pub name: Rc<str>,
325 pub span: Span,
326 pub pack: bool,
328 pub default: Option<TypeExpr>,
331}
332
333#[derive(Clone, Debug, PartialEq)]
335pub struct TypePack {
336 pub types: Vec<TypeExpr>,
337 pub variadic: Option<Box<TypeExpr>>,
338 pub span: Span,
339}
340
341impl fmt::Display for TypeExpr {
342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343 match &self.kind {
344 TypeKind::Name { name, args } => {
345 f.write_str(name)?;
346 if !args.is_empty() {
347 let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
348 write!(f, "<{}>", args.join(", "))?;
349 }
350 Ok(())
351 }
352 TypeKind::Singleton(Singleton::Bool(b)) => write!(f, "{b}"),
353 TypeKind::Singleton(Singleton::String(s)) => write!(f, "{s:?}"),
354 TypeKind::Typeof(e) => write!(f, "typeof({e})"),
355 TypeKind::Optional(t) => write!(f, "{t}?"),
356 TypeKind::GenericPack(name) => write!(f, "{name}..."),
357 TypeKind::Pack(p) => write!(f, "{p}"),
358 TypeKind::Union(ts) | TypeKind::Intersection(ts) => {
359 let sep = if matches!(self.kind, TypeKind::Union(_)) {
360 " | "
361 } else {
362 " & "
363 };
364 let parts: Vec<String> = ts.iter().map(|t| t.to_string()).collect();
365 write!(f, "({})", parts.join(sep))
366 }
367 TypeKind::Table { props, indexer } => {
368 let mut parts: Vec<String> = props
369 .iter()
370 .map(|p| format!("{}{}: {}", p.access.prefix(), p.name, p.ty))
371 .collect();
372 if let Some(ix) = indexer {
373 parts.push(format!("[{}]: {}", ix.0, ix.1));
374 }
375 write!(f, "{{{}}}", parts.join(", "))
376 }
377 TypeKind::Function {
378 generics,
379 params,
380 variadic,
381 returns,
382 } => {
383 if !generics.is_empty() {
384 let g: Vec<String> = generics
385 .iter()
386 .map(|g| format!("{}{}", g.name, if g.pack { "..." } else { "" }))
387 .collect();
388 write!(f, "<{}>", g.join(", "))?;
389 }
390 let mut ps: Vec<String> = params.iter().map(|p| p.ty.to_string()).collect();
391 if let Some(v) = variadic {
392 ps.push(variadic_text(v));
393 }
394 write!(f, "({}) -> {returns}", ps.join(", "))
395 }
396 }
397 }
398}
399
400impl fmt::Display for TypePack {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 let mut parts: Vec<String> = self.types.iter().map(|t| t.to_string()).collect();
403 if let Some(v) = &self.variadic {
404 parts.push(variadic_text(v));
405 }
406 write!(f, "({})", parts.join(", "))
407 }
408}
409
410fn variadic_text(v: &TypeExpr) -> String {
412 match &v.kind {
413 TypeKind::GenericPack(_) => v.to_string(),
414 _ => format!("...{v}"),
415 }
416}
417
418#[derive(Clone, Debug, PartialEq)]
420pub enum TableItem {
421 Positional(Expr),
424 Keyed { key: Expr, value: Expr },
426}
427
428impl ExprKind {
429 pub fn is_multi(&self) -> bool {
432 matches!(
433 self,
434 ExprKind::Call { .. } | ExprKind::MethodCall { .. } | ExprKind::Vararg
435 )
436 }
437}
438
439#[derive(Clone, Debug, PartialEq)]
441pub enum InterpPart {
442 Text(Rc<str>),
443 Expr(Expr),
445}
446
447#[derive(Clone, Copy, Debug, PartialEq, Eq)]
448pub enum UnOp {
449 Neg,
450 Not,
451 Len,
452}
453
454#[derive(Clone, Copy, Debug, PartialEq, Eq)]
455pub enum BinOp {
456 Add,
457 Sub,
458 Mul,
459 Div,
460 IDiv,
461 Mod,
462 Pow,
463 Concat,
464 Eq,
465 Ne,
466 Lt,
467 Le,
468 Gt,
469 Ge,
470 And,
471 Or,
472}
473
474pub const UNARY_BP: u8 = 30;
477
478impl BinOp {
479 pub fn binding_power(self) -> (u8, u8) {
486 use BinOp::*;
487 match self {
488 Or => (1, 2),
489 And => (3, 4),
490 Eq | Ne | Lt | Le | Gt | Ge => (5, 6),
491 Concat => (9, 8),
492 Add | Sub => (10, 11),
493 Mul | Div | IDiv | Mod => (20, 21),
494 Pow => (41, 40),
495 }
496 }
497
498 pub fn symbol(self) -> &'static str {
499 use BinOp::*;
500 match self {
501 Add => "+",
502 Sub => "-",
503 Mul => "*",
504 Div => "/",
505 IDiv => "//",
506 Mod => "%",
507 Pow => "^",
508 Concat => "..",
509 Eq => "==",
510 Ne => "~=",
511 Lt => "<",
512 Le => "<=",
513 Gt => ">",
514 Ge => ">=",
515 And => "and",
516 Or => "or",
517 }
518 }
519}
520
521impl UnOp {
522 pub fn symbol(self) -> &'static str {
523 match self {
524 UnOp::Neg => "-",
525 UnOp::Not => "not",
526 UnOp::Len => "#",
527 }
528 }
529}
530
531impl fmt::Display for Expr {
534 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
535 match &self.kind {
536 ExprKind::Nil => f.write_str("nil"),
537 ExprKind::Bool(b) => write!(f, "{b}"),
538 ExprKind::Number(n) => write!(f, "{n}"),
539 ExprKind::String(s) => write!(f, "{s:?}"),
540 ExprKind::Name(n) => f.write_str(&n.text),
541 ExprKind::Group(e) => write!(f, "(group {e})"),
542 ExprKind::Unary { op, operand, .. } => write!(f, "({} {operand})", op.symbol()),
543 ExprKind::Binary { op, lhs, rhs, .. } => write!(f, "({} {lhs} {rhs})", op.symbol()),
544 ExprKind::IfElse {
545 branches,
546 else_expr,
547 } => {
548 f.write_str("(if")?;
549 for (c, v) in branches {
550 write!(f, " {c} {v}")?;
551 }
552 write!(f, " {else_expr})")
553 }
554 ExprKind::Call { callee, args } => {
555 write!(f, "(call {callee}")?;
556 for a in args {
557 write!(f, " {a}")?;
558 }
559 f.write_str(")")
560 }
561 ExprKind::Vararg => f.write_str("..."),
562 ExprKind::Interp(parts) => {
563 f.write_str("(interp")?;
564 for part in parts {
565 match part {
566 InterpPart::Text(t) => write!(f, " {t:?}")?,
567 InterpPart::Expr(e) => write!(f, " {e}")?,
568 }
569 }
570 f.write_str(")")
571 }
572 ExprKind::Function(func) => {
573 let mut params: Vec<&str> = func.params.iter().map(|p| &*p.text).collect();
574 if func.is_vararg {
575 params.push("...");
576 }
577 write!(f, "(function ({}))", params.join(" "))
578 }
579 ExprKind::Index { object, key } => write!(f, "(index {object} {key})"),
580 ExprKind::Cast { expr, ty } => write!(f, "(:: {expr} {ty})"),
581 ExprKind::MethodCall {
582 object,
583 method,
584 args,
585 ..
586 } => {
587 write!(f, "(method {object} {method}")?;
588 for a in args {
589 write!(f, " {a}")?;
590 }
591 f.write_str(")")
592 }
593 ExprKind::Table(items) => {
594 f.write_str("(table")?;
595 for item in items {
596 match item {
597 TableItem::Positional(e) => write!(f, " {e}")?,
598 TableItem::Keyed { key, value } => write!(f, " [{key}]={value}")?,
599 }
600 }
601 f.write_str(")")
602 }
603 }
604 }
605}