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

difftreelog

source

crates/jrsonnet-parser/src/expr.rs8.1 KiBsourcehistory
1use gcmodule::Trace;2use jrsonnet_interner::IStr;3#[cfg(feature = "deserialize")]4use serde::Deserialize;5#[cfg(feature = "serialize")]6use serde::Serialize;7use std::{8	fmt::{Debug, Display},9	ops::Deref,10	path::{Path, PathBuf},11	rc::Rc,12};1314#[cfg_attr(feature = "serialize", derive(Serialize))]15#[cfg_attr(feature = "deserialize", derive(Deserialize))]16#[derive(Debug, PartialEq, Trace)]17pub enum FieldName {18	/// {fixed: 2}19	Fixed(IStr),20	/// {["dyn"+"amic"]: 3}21	Dyn(LocExpr),22}2324#[cfg_attr(feature = "serialize", derive(Serialize))]25#[cfg_attr(feature = "deserialize", derive(Deserialize))]26#[derive(Debug, Clone, Copy, PartialEq, Trace)]27pub enum Visibility {28	/// :29	Normal,30	/// ::31	Hidden,32	/// :::33	Unhide,34}3536impl Visibility {37	pub fn is_visible(&self) -> bool {38		matches!(self, Self::Normal | Self::Unhide)39	}40}4142#[cfg_attr(feature = "serialize", derive(Serialize))]43#[cfg_attr(feature = "deserialize", derive(Deserialize))]44#[derive(Clone, Debug, PartialEq, Trace)]45pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);4647#[cfg_attr(feature = "serialize", derive(Serialize))]48#[cfg_attr(feature = "deserialize", derive(Deserialize))]49#[derive(Debug, PartialEq, Trace)]50pub struct FieldMember {51	pub name: FieldName,52	pub plus: bool,53	pub params: Option<ParamsDesc>,54	pub visibility: Visibility,55	pub value: LocExpr,56}5758#[cfg_attr(feature = "serialize", derive(Serialize))]59#[cfg_attr(feature = "deserialize", derive(Deserialize))]60#[derive(Debug, PartialEq, Trace)]61pub enum Member {62	Field(FieldMember),63	BindStmt(BindSpec),64	AssertStmt(AssertStmt),65}6667#[cfg_attr(feature = "serialize", derive(Serialize))]68#[cfg_attr(feature = "deserialize", derive(Deserialize))]69#[derive(Debug, Clone, Copy, PartialEq, Trace)]70pub enum UnaryOpType {71	Plus,72	Minus,73	BitNot,74	Not,75}7677impl Display for UnaryOpType {78	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {79		use UnaryOpType::*;80		write!(81			f,82			"{}",83			match self {84				Plus => "+",85				Minus => "-",86				BitNot => "~",87				Not => "!",88			}89		)90	}91}9293#[cfg_attr(feature = "serialize", derive(Serialize))]94#[cfg_attr(feature = "deserialize", derive(Deserialize))]95#[derive(Debug, Clone, Copy, PartialEq, Trace)]96pub enum BinaryOpType {97	Mul,98	Div,99100	/// Implemented as intrinsic, put here for completeness101	Mod,102103	Add,104	Sub,105106	Lhs,107	Rhs,108109	Lt,110	Gt,111	Lte,112	Gte,113114	BitAnd,115	BitOr,116	BitXor,117118	Eq,119	Neq,120121	And,122	Or,123124	// Equialent to std.objectHasEx(a, b, true)125	In,126}127128impl Display for BinaryOpType {129	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {130		use BinaryOpType::*;131		write!(132			f,133			"{}",134			match self {135				Mul => "*",136				Div => "/",137				Mod => "%",138				Add => "+",139				Sub => "-",140				Lhs => "<<",141				Rhs => ">>",142				Lt => "<",143				Gt => ">",144				Lte => "<=",145				Gte => ">=",146				BitAnd => "&",147				BitOr => "|",148				BitXor => "^",149				Eq => "==",150				Neq => "!=",151				And => "&&",152				Or => "||",153				In => "in",154			}155		)156	}157}158159/// name, default value160#[cfg_attr(feature = "serialize", derive(Serialize))]161#[cfg_attr(feature = "deserialize", derive(Deserialize))]162#[derive(Debug, PartialEq, Trace)]163pub struct Param(pub IStr, pub Option<LocExpr>);164165/// Defined function parameters166#[cfg_attr(feature = "serialize", derive(Serialize))]167#[cfg_attr(feature = "deserialize", derive(Deserialize))]168#[derive(Debug, Clone, PartialEq, Trace)]169pub struct ParamsDesc(pub Rc<Vec<Param>>);170171impl Deref for ParamsDesc {172	type Target = Vec<Param>;173	fn deref(&self) -> &Self::Target {174		&self.0175	}176}177178#[cfg_attr(feature = "serialize", derive(Serialize))]179#[cfg_attr(feature = "deserialize", derive(Deserialize))]180#[derive(Debug, PartialEq, Trace)]181pub struct ArgsDesc {182	pub unnamed: Vec<LocExpr>,183	pub named: Vec<(IStr, LocExpr)>,184}185impl ArgsDesc {186	pub fn new(unnamed: Vec<LocExpr>, named: Vec<(IStr, LocExpr)>) -> Self {187		Self { unnamed, named }188	}189}190191#[cfg_attr(feature = "serialize", derive(Serialize))]192#[cfg_attr(feature = "deserialize", derive(Deserialize))]193#[derive(Debug, Clone, PartialEq, Trace)]194pub struct BindSpec {195	pub name: IStr,196	pub params: Option<ParamsDesc>,197	pub value: LocExpr,198}199200#[cfg_attr(feature = "serialize", derive(Serialize))]201#[cfg_attr(feature = "deserialize", derive(Deserialize))]202#[derive(Debug, PartialEq, Trace)]203pub struct IfSpecData(pub LocExpr);204205#[cfg_attr(feature = "serialize", derive(Serialize))]206#[cfg_attr(feature = "deserialize", derive(Deserialize))]207#[derive(Debug, PartialEq, Trace)]208pub struct ForSpecData(pub IStr, pub LocExpr);209210#[cfg_attr(feature = "serialize", derive(Serialize))]211#[cfg_attr(feature = "deserialize", derive(Deserialize))]212#[derive(Debug, PartialEq, Trace)]213pub enum CompSpec {214	IfSpec(IfSpecData),215	ForSpec(ForSpecData),216}217218#[cfg_attr(feature = "serialize", derive(Serialize))]219#[cfg_attr(feature = "deserialize", derive(Deserialize))]220#[derive(Debug, PartialEq, Trace)]221pub struct ObjComp {222	pub pre_locals: Vec<BindSpec>,223	pub key: LocExpr,224	pub plus: bool,225	pub value: LocExpr,226	pub post_locals: Vec<BindSpec>,227	pub compspecs: Vec<CompSpec>,228}229230#[cfg_attr(feature = "serialize", derive(Serialize))]231#[cfg_attr(feature = "deserialize", derive(Deserialize))]232#[derive(Debug, PartialEq, Trace)]233pub enum ObjBody {234	MemberList(Vec<Member>),235	ObjComp(ObjComp),236}237238#[cfg_attr(feature = "serialize", derive(Serialize))]239#[cfg_attr(feature = "deserialize", derive(Deserialize))]240#[derive(Debug, PartialEq, Clone, Copy, Trace)]241pub enum LiteralType {242	This,243	Super,244	Dollar,245	Null,246	True,247	False,248}249250#[cfg_attr(feature = "serialize", derive(Serialize))]251#[cfg_attr(feature = "deserialize", derive(Deserialize))]252#[derive(Debug, PartialEq, Trace)]253pub struct SliceDesc {254	pub start: Option<LocExpr>,255	pub end: Option<LocExpr>,256	pub step: Option<LocExpr>,257}258259/// Syntax base260#[cfg_attr(feature = "serialize", derive(Serialize))]261#[cfg_attr(feature = "deserialize", derive(Deserialize))]262#[derive(Debug, PartialEq, Trace)]263pub enum Expr {264	Literal(LiteralType),265266	/// String value: "hello"267	Str(IStr),268	/// Number: 1, 2.0, 2e+20269	Num(f64),270	/// Variable name: test271	Var(IStr),272273	/// Array of expressions: [1, 2, "Hello"]274	Arr(Vec<LocExpr>),275	/// Array comprehension:276	/// ```jsonnet277	///  ingredients: [278	///    { kind: kind, qty: 4 / 3 }279	///    for kind in [280	///      'Honey Syrup',281	///      'Lemon Juice',282	///      'Farmers Gin',283	///    ]284	///  ],285	/// ```286	ArrComp(LocExpr, Vec<CompSpec>),287288	/// Object: {a: 2}289	Obj(ObjBody),290	/// Object extension: var1 {b: 2}291	ObjExtend(LocExpr, ObjBody),292293	/// (obj)294	Parened(LocExpr),295296	/// -2297	UnaryOp(UnaryOpType, LocExpr),298	/// 2 - 2299	BinaryOp(LocExpr, BinaryOpType, LocExpr),300	/// assert 2 == 2 : "Math is broken"301	AssertExpr(AssertStmt, LocExpr),302	/// local a = 2; { b: a }303	LocalExpr(Vec<BindSpec>, LocExpr),304305	/// import "hello"306	Import(PathBuf),307	/// importStr "file.txt"308	ImportStr(PathBuf),309	/// error "I'm broken"310	ErrorStmt(LocExpr),311	/// a(b, c)312	Apply(LocExpr, ArgsDesc, bool),313	/// a[b]314	Index(LocExpr, LocExpr),315	/// function(x) x316	Function(ParamsDesc, LocExpr),317	/// std.primitiveEquals318	Intrinsic(IStr),319	/// if true == false then 1 else 2320	IfElse {321		cond: IfSpecData,322		cond_then: LocExpr,323		cond_else: Option<LocExpr>,324	},325	Slice(LocExpr, SliceDesc),326}327328/// file, begin offset, end offset329#[cfg_attr(feature = "serialize", derive(Serialize))]330#[cfg_attr(feature = "deserialize", derive(Deserialize))]331#[derive(Clone, PartialEq, Trace)]332#[skip_trace]333pub struct ExprLocation(pub Rc<Path>, pub usize, pub usize);334impl ExprLocation {335	pub fn belongs_to(&self, other: &ExprLocation) -> bool {336		other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2337	}338}339340impl Debug for ExprLocation {341	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {342		write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)343	}344}345346/// Holds AST expression and its location in source file347#[cfg_attr(feature = "serialize", derive(Serialize))]348#[cfg_attr(feature = "deserialize", derive(Deserialize))]349#[derive(Clone, PartialEq, Trace)]350pub struct LocExpr(pub Rc<Expr>, pub ExprLocation);351352impl Debug for LocExpr {353	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {354		if f.alternate() {355			write!(f, "{:#?}", self.0)?;356		} else {357			write!(f, "{:?}", self.0)?;358		}359		write!(f, " from {:?}", self.1)?;360		Ok(())361	}362}