1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
//! Abstract Syntax Tree representation of a cooklang recipe
//!
//! The [`Ast`] is generated by [`parser`](crate::parser) and then transformed
//! into a [`Recipe`](crate::model::Recipe) with an analysis pass, so this is
//! just a representation of the file and not a complete parsed recipe.
mod text;
use crate::{context::Recover, located::Located, quantity::Value, span::Span};
pub use text::{Text, TextFragment};
use bitflags::bitflags;
use serde::{Deserialize, Serialize};
/// Abstract syntax tree of a cooklang file
///
/// The AST is (mostly) borrowed from the input and offers location information of each
/// element back to the source file.
#[derive(Debug, Serialize, Clone)]
pub struct Ast<'a> {
pub lines: Vec<Line<'a>>,
}
/// Lines that form a recipe.
///
/// They may not be just 1 line in the file, as a single step can be parsed from
/// multiple lines when [`MULTILINE_STEPS`](crate::Extensions::MULTILINE_STEPS)
/// is enabled.
#[derive(Debug, Serialize, PartialEq, Clone)]
pub enum Line<'a> {
/// Metadata entry
Metadata { key: Text<'a>, value: Text<'a> },
/// Recipe step
Step {
/// Flag that indicates that this is a text step.
///
/// All `items` will be [Item::Text].
is_text: bool,
/// Items that compose the step.
///
/// This is in order, so to form the representation of the step just
/// iterate over the items and process them in that order.
items: Vec<Item<'a>>,
},
/// Section divider
///
/// In the ast, a section does not own steps, it just exists in between.
Section { name: Option<Text<'a>> },
}
/// An item of a [`Line::Step`].
#[derive(Debug, Serialize, PartialEq, Clone)]
pub enum Item<'a> {
/// Plain text
Text(Text<'a>),
/// A [`Component`]
Component(Box<Located<Component<'a>>>),
}
impl Item<'_> {
/// Returns the location of the item in the original input
pub fn span(&self) -> Span {
match self {
Item::Text(t) => t.span(),
Item::Component(c) => c.span(),
}
}
}
/// Step components
///
/// Components are the rich part of a step. These are the ingredients, cookware
/// and timers.
#[derive(Debug, Serialize, PartialEq, Clone)]
pub enum Component<'a> {
Ingredient(Ingredient<'a>),
Cookware(Cookware<'a>),
Timer(Timer<'a>),
}
/// Ingredient [`Component`]
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Ingredient<'a> {
/// Ingredient modifiers
///
/// If there are no modifiers, this will be [`Modifiers::empty`] and the
/// location of where the modifiers would be.
pub modifiers: Located<Modifiers>,
/// Data for [`Modifiers::REF_TO_STEP`] and [`Modifiers::REF_TO_SECTION`].
///
/// If any of those modifiers is present, this will be.
pub intermediate_data: Option<Located<IntermediateData>>,
pub name: Text<'a>,
pub alias: Option<Text<'a>>,
pub quantity: Option<Located<Quantity<'a>>>,
pub note: Option<Text<'a>>,
}
/// Cookware [`Component`]
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Cookware<'a> {
/// Cookware modifiers
///
/// If there are no modifiers, this will be [`Modifiers::empty`] and the
/// location of where the modifiers would be.
pub modifiers: Located<Modifiers>,
pub name: Text<'a>,
pub alias: Option<Text<'a>>,
/// This it's just a [`QuantityValue`], because cookware cannot not have
/// a unit.
pub quantity: Option<Located<QuantityValue>>,
pub note: Option<Text<'a>>,
}
/// Timer [`Component`]
///
/// At least one of the fields is guaranteed to be [`Some`].
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Timer<'a> {
pub name: Option<Text<'a>>,
/// If the [`TIMER_REQUIRES_TIME`](crate::Extensions::TIMER_REQUIRES_TIME)
/// extension is enabled, this is guaranteed to be [`Some`].
pub quantity: Option<Located<Quantity<'a>>>,
}
/// Quantity used in [components](Component)
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Quantity<'a> {
/// Value or values
pub value: QuantityValue,
/// Unit text
///
/// It's just the text, no checks
pub unit: Option<Text<'a>>,
}
/// Quantity value(s)
#[derive(Debug, Clone, PartialEq, Serialize)]
pub enum QuantityValue {
/// A single value
Single {
value: Located<Value>,
/// [`Some`] if the auto scale marker (`*`) is present
auto_scale: Option<Span>,
},
/// Many values
///
/// This is parsed from values separated by `|`. It is not compatible with
/// the auto scale marker (`*`).
Many(Vec<Located<Value>>),
}
impl QuantityValue {
/// Calculates the span of the value or values
pub fn span(&self) -> Span {
match self {
QuantityValue::Single { value, auto_scale } => {
let s = value.span();
if let Some(marker) = auto_scale {
assert_eq!(s.end(), marker.start());
Span::new(s.start(), marker.end())
} else {
s
}
}
QuantityValue::Many(v) => {
assert!(!v.is_empty(), "QuantityValue::Many with no values");
let start = v.first().unwrap().span().start();
let end = v.last().unwrap().span().end();
Span::new(start, end)
}
}
}
}
impl Recover for Text<'_> {
fn recover() -> Self {
Self::empty(0)
}
}
impl Recover for Quantity<'_> {
fn recover() -> Self {
Self {
value: Recover::recover(),
unit: Recover::recover(),
}
}
}
impl Recover for QuantityValue {
fn recover() -> Self {
Self::Single {
value: Recover::recover(),
auto_scale: None,
}
}
}
impl Recover for Value {
fn recover() -> Self {
Self::Number { value: 1.0 }
}
}
bitflags! {
/// Component modifiers
///
/// Sadly, for now this can represent invalid combinations of modifiers.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Modifiers: u16 {
/// refers to a recipe with the same name
const RECIPE = 1 << 0;
/// references another igr with the same name, if amount given will sum
const REF = 1 << 1;
/// not shown in the ingredient list, only inline
const HIDDEN = 1 << 2;
/// mark as optional
const OPT = 1 << 3;
/// forces to create a new ingredient
const NEW = 1 << 4;
}
}
impl Modifiers {
/// Returns true if the component should be diplayed in a list
pub fn should_be_listed(self) -> bool {
!self.intersects(Modifiers::HIDDEN | Modifiers::REF)
}
pub fn is_hidden(&self) -> bool {
self.contains(Modifiers::HIDDEN)
}
pub fn is_optional(&self) -> bool {
self.contains(Modifiers::OPT)
}
pub fn is_recipe(&self) -> bool {
self.contains(Modifiers::RECIPE)
}
pub fn is_reference(&self) -> bool {
self.contains(Modifiers::REF)
}
}
impl std::fmt::Display for Modifiers {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
/// Data for interemediate references
///
/// This is not checked, and may point to inexistent or future steps/sections
/// which is invalid.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateData {
/// The mode in which `val` works
pub ref_mode: IntermediateRefMode,
/// The target of the reference
pub target_kind: IntermediateTargetKind,
/// Value
///
/// This means:
///
/// | `ref_mode`/`target_kind` | [`Step`] | [`Section`] |
/// |:-------------------------|:-------------------------------------------------------|:-------------------------------|
/// | [`Index`] | Index in the vec of steps **of the current section** | Index into the vec of sections |
/// | [`Relative`] | Number of non text steps back | Number of sections back |
///
/// [`Step`]: IntermediateTargetKind::Step
/// [`Section`]: IntermediateTargetKind::Section
/// [`Index`]: IntermediateRefMode::Index
/// [`Relative`]: IntermediateRefMode::Relative
pub val: i16,
}
/// How to treat the value in [`IntermediateData`]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IntermediateRefMode {
/// Absoltute index
Index,
/// Relative backwards
///
/// When it is steps, is number of non text steps back.
Relative,
}
/// What the target of [`IntermediateData`] is
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum IntermediateTargetKind {
/// A step in the current section
Step,
/// A section of the recipe
Section,
}