git.delta.rocks / jrsonnet / refs/commits / d78cbb7dd1e6

difftreelog

source

crates/jrsonnet-parser/src/expr.rs10.7 KiBsourcehistory
1use std::{2	fmt::{self, Debug, Display},3	ops::Deref,4	rc::Rc,5};67use jrsonnet_gcmodule::Trace;8use jrsonnet_interner::IStr;9#[cfg(feature = "serde")]10use serde::{Deserialize, Serialize};11#[cfg(feature = "structdump")]12use structdump::Codegen;1314use crate::source::Source;1516#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]17#[cfg_attr(feature = "structdump", derive(Codegen))]18#[derive(Debug, PartialEq, Trace)]19pub enum FieldName {20	/// {fixed: 2}21	Fixed(IStr),22	/// {["dyn"+"amic"]: 3}23	Dyn(LocExpr),24}2526#[cfg_attr(feature = "structdump", derive(Codegen))]27#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]28#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]29#[repr(u8)]30pub enum Visibility {31	/// :32	Normal,33	/// ::34	Hidden,35	/// :::36	Unhide,37}3839impl Visibility {40	pub fn is_visible(&self) -> bool {41		matches!(self, Self::Normal | Self::Unhide)42	}43}4445#[cfg_attr(feature = "structdump", derive(Codegen))]46#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]47#[derive(Clone, Debug, PartialEq, Trace)]48pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);4950#[cfg_attr(feature = "structdump", derive(Codegen))]51#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]52#[derive(Debug, PartialEq, Trace)]53pub struct FieldMember {54	pub name: FieldName,55	pub plus: bool,56	pub params: Option<ParamsDesc>,57	pub visibility: Visibility,58	pub value: LocExpr,59}6061#[cfg_attr(feature = "structdump", derive(Codegen))]62#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]63#[derive(Debug, PartialEq, Trace)]64pub enum Member {65	Field(FieldMember),66	BindStmt(BindSpec),67	AssertStmt(AssertStmt),68}6970#[cfg_attr(feature = "structdump", derive(Codegen))]71#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]72#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]73pub enum UnaryOpType {74	Plus,75	Minus,76	BitNot,77	Not,78}7980impl Display for UnaryOpType {81	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {82		use UnaryOpType::*;83		write!(84			f,85			"{}",86			match self {87				Plus => "+",88				Minus => "-",89				BitNot => "~",90				Not => "!",91			}92		)93	}94}9596#[cfg_attr(feature = "structdump", derive(Codegen))]97#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]98#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]99pub enum BinaryOpType {100	Mul,101	Div,102103	/// Implemented as intrinsic, put here for completeness104	Mod,105106	Add,107	Sub,108109	Lhs,110	Rhs,111112	Lt,113	Gt,114	Lte,115	Gte,116117	BitAnd,118	BitOr,119	BitXor,120121	Eq,122	Neq,123124	And,125	Or,126	#[cfg(feature = "exp-null-coaelse")]127	NullCoaelse,128129	// Equialent to std.objectHasEx(a, b, true)130	In,131}132133impl Display for BinaryOpType {134	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {135		use BinaryOpType::*;136		write!(137			f,138			"{}",139			match self {140				Mul => "*",141				Div => "/",142				Mod => "%",143				Add => "+",144				Sub => "-",145				Lhs => "<<",146				Rhs => ">>",147				Lt => "<",148				Gt => ">",149				Lte => "<=",150				Gte => ">=",151				BitAnd => "&",152				BitOr => "|",153				BitXor => "^",154				Eq => "==",155				Neq => "!=",156				And => "&&",157				Or => "||",158				In => "in",159				#[cfg(feature = "exp-null-coaelse")]160				NullCoaelse => "??",161			}162		)163	}164}165166/// name, default value167#[cfg_attr(feature = "structdump", derive(Codegen))]168#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]169#[derive(Debug, PartialEq, Trace)]170pub struct Param(pub Destruct, pub Option<LocExpr>);171172/// Defined function parameters173#[cfg_attr(feature = "structdump", derive(Codegen))]174#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]175#[derive(Debug, Clone, PartialEq, Trace)]176pub struct ParamsDesc(pub Rc<Vec<Param>>);177178impl Deref for ParamsDesc {179	type Target = Vec<Param>;180	fn deref(&self) -> &Self::Target {181		&self.0182	}183}184185#[cfg_attr(feature = "structdump", derive(Codegen))]186#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]187#[derive(Debug, PartialEq, Trace)]188pub struct ArgsDesc {189	pub unnamed: Vec<LocExpr>,190	pub named: Vec<(IStr, LocExpr)>,191}192impl ArgsDesc {193	pub fn new(unnamed: Vec<LocExpr>, named: Vec<(IStr, LocExpr)>) -> Self {194		Self { unnamed, named }195	}196}197198#[cfg_attr(feature = "structdump", derive(Codegen))]199#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]200#[derive(Debug, Clone, PartialEq, Eq, Trace)]201pub enum DestructRest {202	/// ...rest203	Keep(IStr),204	/// ...205	Drop,206}207208#[cfg_attr(feature = "structdump", derive(Codegen))]209#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]210#[derive(Debug, Clone, PartialEq, Trace)]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<LocExpr>)>,224		rest: Option<DestructRest>,225	},226}227impl Destruct {228	/// Name of destructure, used for function parameter names229	pub fn name(&self) -> Option<IStr> {230		match self {231			Self::Full(name) => Some(name.clone()),232			#[cfg(feature = "exp-destruct")]233			_ => None,234		}235	}236	pub fn capacity_hint(&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::capacity_hint).sum::<usize>()252					+ end.iter().map(Destruct::capacity_hint).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						// Field is destructured to default name262						None => out += 1,263					}264				}265				out + cap_rest(rest)266			}267		}268	}269}270271#[cfg_attr(feature = "structdump", derive(Codegen))]272#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]273#[derive(Debug, Clone, PartialEq, Trace)]274pub enum BindSpec {275	Field {276		into: Destruct,277		value: LocExpr,278	},279	Function {280		name: IStr,281		params: ParamsDesc,282		value: LocExpr,283	},284}285impl BindSpec {286	pub fn capacity_hint(&self) -> usize {287		match self {288			BindSpec::Field { into, .. } => into.capacity_hint(),289			BindSpec::Function { .. } => 1,290		}291	}292}293294#[cfg_attr(feature = "structdump", derive(Codegen))]295#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]296#[derive(Debug, PartialEq, Trace)]297pub struct IfSpecData(pub LocExpr);298299#[cfg_attr(feature = "structdump", derive(Codegen))]300#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]301#[derive(Debug, PartialEq, Trace)]302pub struct ForSpecData(pub Destruct, pub LocExpr);303304#[cfg_attr(feature = "structdump", derive(Codegen))]305#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]306#[derive(Debug, PartialEq, Trace)]307pub enum CompSpec {308	IfSpec(IfSpecData),309	ForSpec(ForSpecData),310}311312#[cfg_attr(feature = "structdump", derive(Codegen))]313#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]314#[derive(Debug, PartialEq, Trace)]315pub struct ObjComp {316	pub pre_locals: Vec<BindSpec>,317	pub field: FieldMember,318	pub post_locals: Vec<BindSpec>,319	pub compspecs: Vec<CompSpec>,320}321322#[cfg_attr(feature = "structdump", derive(Codegen))]323#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]324#[derive(Debug, PartialEq, Trace)]325pub enum ObjBody {326	MemberList(Vec<Member>),327	ObjComp(ObjComp),328}329330#[cfg_attr(feature = "structdump", derive(Codegen))]331#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]332#[derive(Debug, PartialEq, Eq, Clone, Copy, Trace)]333pub enum LiteralType {334	This,335	Super,336	Dollar,337	Null,338	True,339	False,340}341342#[cfg_attr(feature = "structdump", derive(Codegen))]343#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]344#[derive(Debug, PartialEq, Trace)]345pub struct SliceDesc {346	pub start: Option<LocExpr>,347	pub end: Option<LocExpr>,348	pub step: Option<LocExpr>,349}350351/// Syntax base352#[cfg_attr(feature = "structdump", derive(Codegen))]353#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]354#[derive(Debug, PartialEq, Trace)]355pub enum Expr {356	Literal(LiteralType),357358	/// String value: "hello"359	Str(IStr),360	/// Number: 1, 2.0, 2e+20361	Num(f64),362	/// Variable name: test363	Var(IStr),364365	/// Array of expressions: [1, 2, "Hello"]366	Arr(Vec<LocExpr>),367	/// Array comprehension:368	/// ```jsonnet369	///  ingredients: [370	///    { kind: kind, qty: 4 / 3 }371	///    for kind in [372	///      'Honey Syrup',373	///      'Lemon Juice',374	///      'Farmers Gin',375	///    ]376	///  ],377	/// ```378	ArrComp(LocExpr, Vec<CompSpec>),379380	/// Object: {a: 2}381	Obj(ObjBody),382	/// Object extension: var1 {b: 2}383	ObjExtend(LocExpr, ObjBody),384385	/// (obj)386	Parened(LocExpr),387388	/// -2389	UnaryOp(UnaryOpType, LocExpr),390	/// 2 - 2391	BinaryOp(LocExpr, BinaryOpType, LocExpr),392	/// assert 2 == 2 : "Math is broken"393	AssertExpr(AssertStmt, LocExpr),394	/// local a = 2; { b: a }395	LocalExpr(Vec<BindSpec>, LocExpr),396397	/// import "hello"398	Import(LocExpr),399	/// importStr "file.txt"400	ImportStr(LocExpr),401	/// importBin "file.txt"402	ImportBin(LocExpr),403	/// error "I'm broken"404	ErrorStmt(LocExpr),405	/// a(b, c)406	Apply(LocExpr, ArgsDesc, bool),407	/// a[b], a.b, a?.b408	Index {409		indexable: LocExpr,410		parts: Vec<IndexPart>,411	},412	/// function(x) x413	Function(ParamsDesc, LocExpr),414	/// if true == false then 1 else 2415	IfElse {416		cond: IfSpecData,417		cond_then: LocExpr,418		cond_else: Option<LocExpr>,419	},420	Slice(LocExpr, SliceDesc),421}422423#[cfg_attr(feature = "structdump", derive(Codegen))]424#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]425#[derive(Debug, PartialEq, Trace)]426pub struct IndexPart {427	pub value: LocExpr,428	#[cfg(feature = "exp-null-coaelse")]429	pub null_coaelse: bool,430}431432/// file, begin offset, end offset433#[cfg_attr(feature = "structdump", derive(Codegen))]434#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]435#[derive(Clone, PartialEq, Eq, Trace)]436#[trace(skip)]437#[repr(C)]438pub struct ExprLocation(pub Source, pub u32, pub u32);439impl ExprLocation {440	pub fn belongs_to(&self, other: &ExprLocation) -> bool {441		other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2442	}443}444445#[cfg(target_pointer_width = "64")]446static_assertions::assert_eq_size!(ExprLocation, [u8; 16]);447448impl Debug for ExprLocation {449	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {450		write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)451	}452}453454/// Holds AST expression and its location in source file455#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]456#[cfg_attr(feature = "structdump", derive(Codegen))]457#[derive(Clone, PartialEq, Trace)]458pub struct LocExpr(pub Rc<Expr>, pub ExprLocation);459460#[cfg(target_pointer_width = "64")]461static_assertions::assert_eq_size!(LocExpr, [u8; 24]);462463impl Debug for LocExpr {464	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {465		if f.alternate() {466			write!(f, "{:#?}", self.0)?;467		} else {468			write!(f, "{:?}", self.0)?;469		}470		write!(f, " from {:?}", self.1)?;471		Ok(())472	}473}