1use std::{2 fmt::{self, Debug, Display},3 ops::Deref,4 rc::Rc,5};67use jrsonnet_gcmodule::Acyclic;8use jrsonnet_interner::IStr;910use crate::{11 function::{FunctionSignature, ParamDefault, ParamName, ParamParse},12 source::Source,13};1415#[derive(Debug, PartialEq, Acyclic)]16pub enum FieldName {17 18 Fixed(IStr),19 20 Dyn(Spanned<Expr>),21}2223#[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]24#[repr(u8)]25pub enum Visibility {26 27 Normal,28 29 Hidden,30 31 Unhide,32}3334impl Visibility {35 pub fn is_visible(&self) -> bool {36 matches!(self, Self::Normal | Self::Unhide)37 }38}3940#[derive(Debug, PartialEq, Acyclic)]41pub struct AssertStmt(pub Spanned<Expr>, pub Option<Spanned<Expr>>);4243#[derive(Debug, PartialEq, Acyclic)]44pub struct FieldMember {45 pub name: FieldName,46 pub plus: bool,47 pub params: Option<ExprParams>,48 pub visibility: Visibility,49 pub value: Rc<Spanned<Expr>>,50}5152#[derive(Debug, PartialEq, Acyclic)]53pub(crate) enum Member {54 Field(FieldMember),55 BindStmt(BindSpec),56 AssertStmt(AssertStmt),57}5859#[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]60pub enum UnaryOpType {61 Plus,62 Minus,63 BitNot,64 Not,65}6667impl Display for UnaryOpType {68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {69 use UnaryOpType::*;70 write!(71 f,72 "{}",73 match self {74 Plus => "+",75 Minus => "-",76 BitNot => "~",77 Not => "!",78 }79 )80 }81}8283#[derive(Debug, Clone, Copy, PartialEq, Eq, Acyclic)]84pub enum BinaryOpType {85 Mul,86 Div,8788 89 Mod,9091 Add,92 Sub,9394 Lhs,95 Rhs,9697 Lt,98 Gt,99 Lte,100 Gte,101102 BitAnd,103 BitOr,104 BitXor,105106 Eq,107 Neq,108109 And,110 Or,111 #[cfg(feature = "exp-null-coaelse")]112 NullCoaelse,113114 115 In,116}117118impl Display for BinaryOpType {119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {120 use BinaryOpType::*;121 write!(122 f,123 "{}",124 match self {125 Mul => "*",126 Div => "/",127 Mod => "%",128 Add => "+",129 Sub => "-",130 Lhs => "<<",131 Rhs => ">>",132 Lt => "<",133 Gt => ">",134 Lte => "<=",135 Gte => ">=",136 BitAnd => "&",137 BitOr => "|",138 BitXor => "^",139 Eq => "==",140 Neq => "!=",141 And => "&&",142 Or => "||",143 In => "in",144 #[cfg(feature = "exp-null-coaelse")]145 NullCoaelse => "??",146 }147 )148 }149}150151152#[derive(Debug, PartialEq, Acyclic)]153pub struct ExprParam {154 pub destruct: Destruct,155 pub default: Option<Rc<Spanned<Expr>>>,156}157158159#[derive(Debug, Clone, PartialEq, Acyclic)]160pub struct ExprParams {161 pub exprs: Rc<Vec<ExprParam>>,162 pub signature: FunctionSignature,163 binds_len: usize,164}165impl ExprParams {166 pub fn len(&self) -> usize {167 self.exprs.len()168 }169 pub fn binds_len(&self) -> usize {170 self.binds_len171 }172 pub fn new(exprs: Vec<ExprParam>) -> Self {173 Self {174 signature: FunctionSignature::new(175 exprs176 .iter()177 .map(|p| {178 ParamParse::new(179 p.destruct.name(),180 ParamDefault::exists(p.default.is_some()),181 )182 })183 .collect(),184 ),185 binds_len: exprs.iter().map(|v| v.destruct.binds_len()).sum(),186 exprs: Rc::new(exprs),187 }188 }189}190191#[derive(Debug, PartialEq, Acyclic)]192pub struct ArgsDesc {193 pub unnamed: Vec<Rc<Spanned<Expr>>>,194 pub named: Vec<(IStr, Rc<Spanned<Expr>>)>,195}196impl ArgsDesc {197 pub fn new(unnamed: Vec<Rc<Spanned<Expr>>>, named: Vec<(IStr, Rc<Spanned<Expr>>)>) -> Self {198 Self { unnamed, named }199 }200}201202#[derive(Debug, Clone, PartialEq, Eq, Acyclic)]203pub enum DestructRest {204 205 Keep(IStr),206 207 Drop,208}209210#[derive(Debug, Clone, PartialEq, Acyclic)]211pub enum Destruct {212 Full(IStr),213 #[cfg(feature = "exp-destruct")]214 Skip,215 #[cfg(feature = "exp-destruct")]216 Array {217 start: Vec<Destruct>,218 rest: Option<DestructRest>,219 end: Vec<Destruct>,220 },221 #[cfg(feature = "exp-destruct")]222 Object {223 fields: Vec<(IStr, Option<Destruct>, Option<Spanned<Expr>>)>,224 rest: Option<DestructRest>,225 },226}227impl Destruct {228 229 pub fn name(&self) -> ParamName {230 ParamName(match self {231 Self::Full(name) => Some(name.clone()),232 #[cfg(feature = "exp-destruct")]233 _ => None,234 })235 }236 pub fn binds_len(&self) -> usize {237 #[cfg(feature = "exp-destruct")]238 fn cap_rest(rest: &Option<DestructRest>) -> usize {239 match rest {240 Some(DestructRest::Keep(_)) => 1,241 Some(DestructRest::Drop) => 0,242 None => 0,243 }244 }245 match self {246 Self::Full(_) => 1,247 #[cfg(feature = "exp-destruct")]248 Self::Skip => 0,249 #[cfg(feature = "exp-destruct")]250 Self::Array { start, rest, end } => {251 start.iter().map(Destruct::binds_len).sum::<usize>()252 + end.iter().map(Destruct::binds_len).sum::<usize>()253 + cap_rest(rest)254 }255 #[cfg(feature = "exp-destruct")]256 Self::Object { fields, rest } => {257 let mut out = 0;258 for (_, into, _) in fields {259 match into {260 Some(v) => out += v.capacity_hint(),261 262 None => out += 1,263 }264 }265 out + cap_rest(rest)266 }267 }268 }269}270271#[derive(Debug, PartialEq, Acyclic)]272pub enum BindSpec {273 Field {274 into: Destruct,275 value: Rc<Spanned<Expr>>,276 },277 Function {278 name: IStr,279 params: ExprParams,280 value: Rc<Spanned<Expr>>,281 },282}283impl BindSpec {284 pub fn binds_len(&self) -> usize {285 match self {286 BindSpec::Field { into, .. } => into.binds_len(),287 BindSpec::Function { .. } => 1,288 }289 }290}291292#[derive(Debug, PartialEq, Acyclic)]293pub struct IfSpecData(pub Spanned<Expr>);294295#[derive(Debug, PartialEq, Acyclic)]296pub struct ForSpecData(pub Destruct, pub Spanned<Expr>);297298#[derive(Debug, PartialEq, Acyclic)]299pub enum CompSpec {300 IfSpec(IfSpecData),301 ForSpec(ForSpecData),302}303304#[derive(Debug, PartialEq, Acyclic)]305pub struct ObjComp {306 pub locals: Rc<Vec<BindSpec>>,307 pub field: Rc<FieldMember>,308 pub compspecs: Vec<CompSpec>,309}310311#[derive(Debug, PartialEq, Acyclic)]312pub struct ObjMembers {313 pub locals: Rc<Vec<BindSpec>>,314 pub asserts: Rc<Vec<AssertStmt>>,315 pub fields: Vec<FieldMember>,316}317318#[derive(Debug, PartialEq, Acyclic)]319pub enum ObjBody {320 MemberList(ObjMembers),321 ObjComp(ObjComp),322}323324#[derive(Debug, PartialEq, Eq, Clone, Copy, Acyclic)]325pub enum LiteralType {326 This,327 Super,328 Dollar,329 Null,330 True,331 False,332}333334#[derive(Debug, PartialEq, Acyclic)]335pub struct SliceDesc {336 pub start: Option<Spanned<Expr>>,337 pub end: Option<Spanned<Expr>>,338 pub step: Option<Spanned<Expr>>,339}340341#[derive(Debug, PartialEq, Acyclic)]342pub struct AssertExpr {343 pub assert: AssertStmt,344 pub rest: Spanned<Expr>,345}346347#[derive(Debug, PartialEq, Acyclic)]348pub struct BinaryOp {349 pub lhs: Spanned<Expr>,350 pub op: BinaryOpType,351 pub rhs: Spanned<Expr>,352}353354#[derive(Debug, PartialEq, Acyclic)]355pub enum ImportKind {356 Normal,357 Str,358 Bin,359}360361#[derive(Debug, PartialEq, Acyclic)]362pub struct IfElse {363 pub cond: IfSpecData,364 pub cond_then: Spanned<Expr>,365 pub cond_else: Option<Spanned<Expr>>,366}367368#[derive(Debug, PartialEq, Acyclic)]369pub struct Slice {370 pub value: Spanned<Expr>,371 pub slice: SliceDesc,372}373374375#[derive(Debug, PartialEq, Acyclic)]376pub enum Expr {377 Literal(LiteralType),378379 380 Str(IStr),381 382 Num(f64),383 384 Var(IStr),385386 387 Arr(Rc<Vec<Spanned<Expr>>>),388 389 390 391 392 393 394 395 396 397 398 399 ArrComp(Rc<Spanned<Expr>>, Vec<CompSpec>),400401 402 Obj(ObjBody),403 404 ObjExtend(Rc<Spanned<Expr>>, ObjBody),405406 407 UnaryOp(UnaryOpType, Box<Spanned<Expr>>),408 409 BinaryOp(Box<BinaryOp>),410 411 AssertExpr(Rc<AssertExpr>),412 413 LocalExpr(Vec<BindSpec>, Box<Spanned<Expr>>),414415 416 Import(ImportKind, Box<Spanned<Expr>>),417 418 ErrorStmt(Box<Spanned<Expr>>),419 420 Apply(Box<Spanned<Expr>>, ArgsDesc, bool),421 422 Index {423 indexable: Box<Spanned<Expr>>,424 parts: Vec<IndexPart>,425 },426 427 Function(ExprParams, Rc<Spanned<Expr>>),428 429 IfElse(Box<IfElse>),430 Slice(Box<Slice>),431}432433#[derive(Debug, PartialEq, Acyclic)]434pub struct IndexPart {435 pub value: Spanned<Expr>,436 #[cfg(feature = "exp-null-coaelse")]437 pub null_coaelse: bool,438}439440441#[derive(Clone, PartialEq, Eq, Acyclic)]442#[repr(C)]443pub struct Span(pub Source, pub u32, pub u32);444impl Span {445 pub fn belongs_to(&self, other: &Span) -> bool {446 other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2447 }448}449450static_assertions::assert_eq_size!(Span, (usize, usize));451452impl Debug for Span {453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {454 write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)455 }456}457458#[derive(Clone, PartialEq, Acyclic)]459pub struct Spanned<T: Acyclic>(T, Span);460impl<T: Acyclic> Deref for Spanned<T> {461 type Target = T;462 fn deref(&self) -> &Self::Target {463 &self.0464 }465}466impl<T: Acyclic> Spanned<T> {467 #[inline]468 pub fn new(v: T, s: Span) -> Self {469 Self(v, s)470 }471 #[inline]472 pub fn span(&self) -> Span {473 self.1.clone()474 }475}476477impl<T: Debug + Acyclic> Debug for Spanned<T> {478 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {479 let expr = &**self;480 if f.alternate() {481 write!(f, "{:#?}", expr)?;482 } else {483 write!(f, "{:?}", expr)?;484 }485 write!(f, " from {:?}", self.span())?;486 Ok(())487 }488}