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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
//! The AST (abstract syntax tree) represents the template syntax in a structured format. //! It mainly consists of an enum [SyntaxNode] which has different variants for each syntax. use std::fmt::{Display, Formatter}; /// The base enum for each syntax element in a document. /// Each variant represents some sort of structured representation of the document syntax. /// This is the foundation for the AST (abstract syntax tree) that is produced by the parser. #[derive(Debug, Eq, PartialEq, Clone)] pub enum SyntaxNode { /// The root of the AST which contains other [SyntaxNode] values. Root(Vec<SyntaxNode>), /// Plain old Html tag that can have any value as a name (even vue components for example). /// It may also have attributes. /// It can also have children which are only a list of [SyntaxNode] instances. /// For example `<h2 class="bold">...</h2>` Tag(Tag), /// Basically only plain text but does only represent text without line break characters or indentation. Plain(Plain), /// Some sort of whitespace (can be anything from spaces to tabs to line breaks). /// Multiple sequential forms of whitespace will always result in only one instance of this. Whitespace, /// Comments in Html that look like `<!-- some comment -->` HtmlComment(HtmlComment), /// Some expression to output something like /// twig: `{{ my_counter|e }}` (can be php) /// vue: `{{ myCounter.count }}` (can be javascript) OutputExpression(OutputExpression), /// Comment in twig syntax: `{# some comment #}` TwigComment(TwigComment), /// Some execute statement that has no children / has no closing syntax. /// /// # Examples /// `{% set foo = 'foo' %}` /// /// or `{% parent %}` /// /// or ... TwigStatement(TwigStatement), /// Some hierarchical twig syntax. /// /// # Examples /// `{% block my_block_name %}...{% endblock %}` /// /// # Notes /// This is preferred over [TwigStatement] by the parser if it sees special keywords like `block` right after the `{% `. /// TwigStructure(TwigStructure<SyntaxNode>), } #[derive(Debug, Eq, PartialEq, Clone)] pub enum TwigStatement { /// For a first implementation there is no difference between all the possibilities of twig execute statements. /// This may change in the future with a more advanced parser. /// /// # Examples /// `{% set foo = 'foo' %}` -> `Raw("set foo = 'foo'")` /// /// `{% parent %}` -> `Raw("parent")` /// /// `{% include 'header.html' %}` -> `Raw("include 'header.html'")` /// /// ... Raw(String), } #[derive(Debug, Eq, PartialEq, Clone)] pub enum TwigStructure<C> { /// Twig block structure which has a name and contains other [SyntaxNode] values as children. /// For example `{% block my_block_name %}...{% endblock %}` TwigBlock(TwigBlock<C>), /// Twig for block. /// /// # Example /// ```twig /// {% for user in users %} /// <li>{{ user.username|e }}</li> /// {% endfor %} /// ``` TwigFor(TwigFor<C>), /// Twig if block. /// /// # Example /// ```twig /// {% if product.stock > 10 %} /// Available /// {% elseif product.stock > 0 %} /// Only {{ product.stock }} left! /// {% else %} /// Sold-out! /// {% endif %} /// ``` TwigIf(TwigIf<C>), /// Twig apply block. /// /// # Example /// ```twig /// {% apply upper %} /// This text becomes uppercase /// {% endapply %} /// ``` TwigApply(TwigApply<C>), /// Twig set block with no '='. captures the children. /// /// # Example /// ```twig /// {% set foo %} /// <div> /// hello world /// </div> /// {% endset %} /// ``` TwigSetCapture(TwigSetCapture<C>), } /// implement the display trait for TwigStructure<TagAttribute> to easily display the user /// tag attributes as context, so they can find the tag that is causing parsing issues. impl Display for TwigStructure<TagAttribute> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { TwigStructure::TwigBlock(t) => { write!(f, "{{% block {} %}}", t.name)?; for child in &t.children { write!(f, " {}", child)?; } write!(f, "{{% endblock %}}") } TwigStructure::TwigFor(t) => { write!(f, "{{% for {} %}}", t.expression)?; for child in &t.children { write!(f, " {}", child)?; } write!(f, "{{% endfor %}}") } TwigStructure::TwigIf(t) => { for (i, arm) in t.if_arms.iter().enumerate() { match (i, &arm.expression) { (0, Some(expr)) => write!(f, "{{% if {} %}}", expr), (_, Some(expr)) => write!(f, "{{% elseif {} %}}", expr), (_, None) => write!(f, "{{% else %}}"), }?; for child in &arm.children { write!(f, " {}", child)?; } write!(f, " ")?; } write!(f, "{{% endif %}}") } TwigStructure::TwigApply(t) => { write!(f, "{{% apply {} %}}", t.expression)?; for child in &t.children { write!(f, " {}", child)?; } write!(f, "{{% endapply %}}") } TwigStructure::TwigSetCapture(t) => { write!(f, "{{% set {} %}}", t.name)?; for child in &t.children { write!(f, " {}", child)?; } write!(f, "{{% endset %}}") } } } } /// Every AST data structure that implements this trait has a list of children (of type [SyntaxNode]). pub trait HasChildren<C> { /// Get the children of this AST node. fn get_children(&self) -> &[C]; } /* impl HasChildren for TwigStructure { fn get_children(&self) -> &[SyntaxNode] { match self { TwigStructure::TwigBlock(p) => p.get_children(), TwigStructure::TwigFor(p) => p.get_children(), TwigStructure::TwigIf(p) => p.get_children(), // how to handle this? is it really needed? TwigStructure::TwigApply(p) => p.get_children(), TwigStructure::TwigSetCapture(p) => p.get_children(), } } } */ #[derive(Debug, Eq, PartialEq, Clone)] pub enum TagAttribute { HtmlAttribute(HtmlAttribute), TwigComment(TwigComment), TwigStructure(TwigStructure<TagAttribute>), } impl Display for TagAttribute { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { TagAttribute::HtmlAttribute(a) => { write!(f, "{}", a) } TagAttribute::TwigComment(c) => { write!(f, "{}", c) } TagAttribute::TwigStructure(s) => { write!(f, "{}", s) } } } } /// Represents any html tag attribute like `class="hello"`. /// /// ## It could also contain output expressions like /// ...="{{ ... }}" /// {{ ... }}="..." /// {{ ... }}="{{ ... }}" /// {{ ... }} #[derive(Debug, Eq, PartialEq, Clone, Default)] pub struct HtmlAttribute { pub name: String, pub value: Option<String>, } impl HtmlAttribute { pub fn new(name: String, value: Option<String>) -> Self { Self { name, value } } } impl Display for HtmlAttribute { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { if let Some(v) = &self.value { write!(f, r#"{}="{}""#, self.name, v) } else { write!(f, "{}", self.name) } } } #[derive(Debug, Eq, PartialEq, Clone, Default)] pub struct Tag { pub name: String, pub self_closed: bool, pub attributes: Vec<TagAttribute>, pub children: Vec<SyntaxNode>, } impl Tag { pub fn new( name: String, self_closed: bool, attributes: Vec<TagAttribute>, children: Vec<SyntaxNode>, ) -> Self { Self { name, self_closed, attributes, children, } } } impl HasChildren<SyntaxNode> for Tag { fn get_children(&self) -> &[SyntaxNode] { self.children.as_ref() } } /// Represents one line of plain text in the html document without line break characters or indentation. #[derive(Debug, Eq, PartialEq, Clone, Default)] pub struct Plain { pub plain: String, } impl Plain { pub fn new(plain: String) -> Self { Self { plain } } } #[derive(Debug, Eq, PartialEq, Clone, Default)] pub struct HtmlComment { pub content: String, } impl HtmlComment { pub fn new(content: String) -> Self { Self { content } } } #[derive(Debug, Eq, PartialEq, Clone, Default)] pub struct OutputExpression { pub content: String, } impl OutputExpression { pub fn new(content: String) -> Self { Self { content } } } #[derive(Debug, Eq, PartialEq, Clone, Default)] pub struct TwigComment { pub content: String, } impl TwigComment { pub fn new(content: String) -> Self { Self { content } } } impl Display for TwigComment { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{{# {} #}}", self.content) } } #[derive(Debug, Eq, PartialEq, Clone)] pub struct TwigBlock<C> { pub name: String, pub children: Vec<C>, } impl<C> Default for TwigBlock<C> { fn default() -> Self { Self { name: "".to_string(), children: vec![], } } } impl<C> TwigBlock<C> { pub fn new(name: String, children: Vec<C>) -> Self { Self { name, children } } } impl<C> HasChildren<C> for TwigBlock<C> { fn get_children(&self) -> &[C] { self.children.as_ref() } } #[derive(Debug, Eq, PartialEq, Clone)] pub struct TwigFor<C> { pub expression: String, pub children: Vec<C>, } impl<C> Default for TwigFor<C> { fn default() -> Self { Self { expression: "".to_string(), children: vec![], } } } impl<C> TwigFor<C> { pub fn new(expression: String, children: Vec<C>) -> Self { Self { expression, children, } } } impl<C> HasChildren<C> for TwigFor<C> { fn get_children(&self) -> &[C] { self.children.as_ref() } } /// Represents a full set of if / elseif / else expressions. /// /// # Example /// ```twig /// {% if product.stock > 10 %} /// Available /// {% elseif product.stock > 0 %} /// Only {{ product.stock }} left! /// {% else %} /// Sold-out! /// {% endif %} /// ``` #[derive(Debug, Eq, PartialEq, Clone)] pub struct TwigIf<C> { pub if_arms: Vec<TwigIfArm<C>>, } /// Represents one Arm of a possible multi arm if /// /// # Example /// ```twig /// {% if product.stock > 10 %} /// Available /// ... /// ``` #[derive(Debug, Eq, PartialEq, Clone)] pub struct TwigIfArm<C> { /// 'if' and 'elseif' arms have an expression, /// otherwise it is an 'else' arm. pub expression: Option<String>, pub children: Vec<C>, } impl<C> Default for TwigIfArm<C> { fn default() -> Self { Self { expression: None, children: vec![], } } } impl<C> HasChildren<C> for TwigIfArm<C> { fn get_children(&self) -> &[C] { self.children.as_ref() } } #[derive(Debug, Eq, PartialEq, Clone)] pub struct TwigApply<C> { pub expression: String, pub children: Vec<C>, } impl<C> Default for TwigApply<C> { fn default() -> Self { Self { expression: "".to_string(), children: vec![], } } } impl<C> TwigApply<C> { pub fn new(expression: String, children: Vec<C>) -> Self { Self { expression, children, } } } impl<C> HasChildren<C> for TwigApply<C> { fn get_children(&self) -> &[C] { self.children.as_ref() } } #[derive(Debug, Eq, PartialEq, Clone)] pub struct TwigSetCapture<C> { pub name: String, pub children: Vec<C>, } impl<C> Default for TwigSetCapture<C> { fn default() -> Self { Self { name: "".to_string(), children: vec![], } } } impl<C> TwigSetCapture<C> { pub fn new(name: String, children: Vec<C>) -> Self { Self { name, children } } } impl<C> HasChildren<C> for TwigSetCapture<C> { fn get_children(&self) -> &[C] { self.children.as_ref() } }