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
//! This module implements the `Node` structure, which composes the AST. pub mod array; pub mod block; pub mod break_node; pub mod conditional; pub mod declaration; pub mod expression; pub mod field; pub mod identifier; pub mod iteration; pub mod object; pub mod operator; pub mod return_smt; pub mod spread; pub mod statement_list; pub mod switch; pub mod throw; pub mod try_node; pub use self::{ array::ArrayDecl, block::Block, break_node::Break, conditional::{ConditionalOp, If}, declaration::{ ArrowFunctionDecl, ConstDecl, ConstDeclList, FunctionDecl, FunctionExpr, LetDecl, LetDeclList, VarDecl, VarDeclList, }, expression::{Call, New}, field::{GetConstField, GetField}, identifier::Identifier, iteration::{Continue, DoWhileLoop, ForLoop, WhileLoop}, object::Object, operator::{Assign, BinOp, UnaryOp}, return_smt::Return, spread::Spread, statement_list::{RcStatementList, StatementList}, switch::{Case, Switch}, throw::Throw, try_node::{Catch, Finally, Try}, }; use super::Const; use gc::{unsafe_empty_trace, Finalize, Trace}; use std::{ cmp::Ordering, fmt::{self, Display}, }; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug, Trace, Finalize, PartialEq)] pub enum Node { /// Array declaration node. [More information](./array/struct.ArrayDecl.html). ArrayDecl(ArrayDecl), /// An arrow function expression node. [More information](./arrow_function/struct.ArrowFunctionDecl.html). ArrowFunctionDecl(ArrowFunctionDecl), /// An assignment operator node. [More information](./operator/struct.Assign.html). Assign(Assign), /// A binary operator node. [More information](./operator/struct.BinOp.html). BinOp(BinOp), /// A Block node. [More information](./block/struct.Block.html). Block(Block), /// A break node. [More information](./break/struct.Break.html). Break(Break), /// A function call. [More information](./expression/struct.Call.html). Call(Call), /// A javascript conditional operand ( x ? y : z ). [More information](./conditional/struct.ConditionalOp.html). ConditionalOp(ConditionalOp), /// Literals represent values in JavaScript. /// /// These are fixed values not variables that you literally provide in your script. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-primary-expression-literals /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Literals Const(Const), /// A constant declaration list. [More information](./declaration/struct.ConstDeclList.html). ConstDeclList(ConstDeclList), /// A continue statement. [More information](./iteration/struct.Continue.html). Continue(Continue), /// A do ... while statement. [More information](./iteration/struct.DoWhileLoop.html). DoWhileLoop(DoWhileLoop), /// A function declaration node. [More information](./declaration/struct.FunctionDecl.html). FunctionDecl(FunctionDecl), /// A function expressino node. [More information](./declaration/struct.FunctionExpr.html). FunctionExpr(FunctionExpr), /// Provides access to an object types' constant properties. [More information](./declaration/struct.GetConstField.html). GetConstField(GetConstField), /// Provides access to object fields. [More information](./declaration/struct.GetField.html). GetField(GetField), /// A `for` statement. [More information](./iteration/struct.ForLoop.html). ForLoop(ForLoop), /// An 'if' statement. [More information](./conditional/struct.If.html). If(If), /// A `let` declaration list. [More information](./declaration/struct.LetDeclList.html). LetDeclList(LetDeclList), /// A local identifier node. [More information](./identifier/struct.Identifier.html). Identifier(Identifier), /// A `new` expression. [More information](./expression/struct.New.html). New(New), /// An object. [More information](./object/struct.Object.html). Object(Object), /// A return statement. [More information](./object/struct.Return.html). Return(Return), /// A switch {case} statement. [More information](./switch/struct.Switch.html). Switch(Switch), /// A spread (...x) statement. [More information](./spread/struct.Spread.html). Spread(Spread), /// A throw statement. [More information](./throw/struct.Throw.html). Throw(Throw), /// A `try...catch` node. [More information](./try_node/struct.Try.htl). Try(Try), /// The JavaScript `this` keyword refers to the object it belongs to. /// /// A property of an execution context (global, function or eval) that, /// in non–strict mode, is always a reference to an object and in strict /// mode can be any value. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#sec-this-keyword /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this This, /// Unary operation node. [More information](./operator/struct.UnaryOp.html) UnaryOp(UnaryOp), /// Array declaration node. [More information](./declaration/struct.VarDeclList.html). VarDeclList(VarDeclList), /// A 'while {...}' node. [More information](./iteration/struct.WhileLoop.html). WhileLoop(WhileLoop), } impl Display for Node { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.display(f, 0) } } impl From<Const> for Node { fn from(c: Const) -> Self { Self::Const(c) } } impl Node { /// Returns a node ordering based on the hoistability of each node. pub(crate) fn hoistable_order(a: &Node, b: &Node) -> Ordering { match (a, b) { (Node::FunctionDecl(_), Node::FunctionDecl(_)) => Ordering::Equal, (_, Node::FunctionDecl(_)) => Ordering::Greater, (Node::FunctionDecl(_), _) => Ordering::Less, (_, _) => Ordering::Equal, } } /// Creates a `This` AST node. pub fn this() -> Self { Self::This } /// Implements the display formatting with indentation. fn display(&self, f: &mut fmt::Formatter<'_>, indentation: usize) -> fmt::Result { let indent = " ".repeat(indentation); match *self { Self::Block(_) => {} _ => write!(f, "{}", indent)?, } match *self { Self::Const(ref c) => write!(f, "{}", c), Self::ConditionalOp(ref cond_op) => Display::fmt(cond_op, f), Self::ForLoop(ref for_loop) => for_loop.display(f, indentation), Self::This => write!(f, "this"), Self::Try(ref try_catch) => try_catch.display(f, indentation), Self::Break(ref break_smt) => Display::fmt(break_smt, f), Self::Continue(ref cont) => Display::fmt(cont, f), Self::Spread(ref spread) => Display::fmt(spread, f), Self::Block(ref block) => block.display(f, indentation), Self::Identifier(ref s) => Display::fmt(s, f), Self::GetConstField(ref get_const_field) => Display::fmt(get_const_field, f), Self::GetField(ref get_field) => Display::fmt(get_field, f), Self::Call(ref expr) => Display::fmt(expr, f), Self::New(ref expr) => Display::fmt(expr, f), Self::WhileLoop(ref while_loop) => while_loop.display(f, indentation), Self::DoWhileLoop(ref do_while) => do_while.display(f, indentation), Self::If(ref if_smt) => if_smt.display(f, indentation), Self::Switch(ref switch) => switch.display(f, indentation), Self::Object(ref obj) => obj.display(f, indentation), Self::ArrayDecl(ref arr) => Display::fmt(arr, f), Self::VarDeclList(ref list) => Display::fmt(list, f), Self::FunctionDecl(ref decl) => decl.display(f, indentation), Self::FunctionExpr(ref expr) => expr.display(f, indentation), Self::ArrowFunctionDecl(ref decl) => decl.display(f, indentation), Self::BinOp(ref op) => Display::fmt(op, f), Self::UnaryOp(ref op) => Display::fmt(op, f), Self::Return(ref ret) => Display::fmt(ret, f), Self::Throw(ref throw) => Display::fmt(throw, f), Self::Assign(ref op) => Display::fmt(op, f), Self::LetDeclList(ref decl) => Display::fmt(decl, f), Self::ConstDeclList(ref decl) => Display::fmt(decl, f), } } } /// Utility to join multiple Nodes into a single string. fn join_nodes<N>(f: &mut fmt::Formatter<'_>, nodes: &[N]) -> fmt::Result where N: Display, { let mut first = true; for e in nodes { if !first { f.write_str(", ")?; } first = false; Display::fmt(e, f)?; } Ok(()) } /// "Formal parameter" is a fancy way of saying "function parameter". /// /// In the declaration of a function, the parameters must be identifiers, /// not any value like numbers, strings, or objects. ///```text ///function foo(formalParameter1, formalParameter2) { ///} ///``` /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#prod-FormalParameter /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Missing_formal_parameter #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug, PartialEq, Trace, Finalize)] pub struct FormalParameter { name: Box<str>, init: Option<Node>, is_rest_param: bool, } impl FormalParameter { /// Creates a new formal parameter. pub(in crate::syntax) fn new<N>(name: N, init: Option<Node>, is_rest_param: bool) -> Self where N: Into<Box<str>>, { Self { name: name.into(), init, is_rest_param, } } /// Gets the name of the formal parameter. pub fn name(&self) -> &str { &self.name } /// Gets the initialization node of the formal parameter, if any. pub fn init(&self) -> Option<&Node> { self.init.as_ref() } /// Gets wether the parameter is a rest parameter. pub fn is_rest_param(&self) -> bool { self.is_rest_param } } impl Display for FormalParameter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.is_rest_param { write!(f, "...")?; } write!(f, "{}", self.name)?; if let Some(n) = self.init.as_ref() { write!(f, " = {}", n)?; } Ok(()) } } /// A JavaScript property is a characteristic of an object, often describing attributes associated with a data structure. /// /// A property has a name (a string) and a value (primitive, method, or object reference). /// Note that when we say that "a property holds an object", that is shorthand for "a property holds an object reference". /// This distinction matters because the original referenced object remains unchanged when you change the property's value. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#prod-PropertyDefinition /// [mdn]: https://developer.mozilla.org/en-US/docs/Glossary/property/JavaScript // TODO: Support all features: https://tc39.es/ecma262/#prod-PropertyDefinition #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug, PartialEq, Trace, Finalize)] pub enum PropertyDefinition { /// Puts a variable into an object. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#prod-IdentifierReference /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions IdentifierReference(Box<str>), /// Binds a property name to a JavaScript value. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#prod-PropertyDefinition /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions Property(Box<str>, Node), /// A property of an object can also refer to a function or a getter or setter method. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#prod-MethodDefinition /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Method_definitions MethodDefinition(MethodDefinitionKind, Box<str>, FunctionExpr), /// The Rest/Spread Properties for ECMAScript proposal (stage 4) adds spread properties to object literals. /// It copies own enumerable properties from a provided object onto a new object. /// /// Shallow-cloning (excluding `prototype`) or merging objects is now possible using a shorter syntax than `Object.assign()`. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#prod-PropertyDefinition /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Spread_properties SpreadObject(Node), } impl PropertyDefinition { /// Creates an `IdentifierReference` property definition. pub fn identifier_reference<I>(ident: I) -> Self where I: Into<Box<str>>, { Self::IdentifierReference(ident.into()) } /// Creates a `Property` definition. pub fn property<N, V>(name: N, value: V) -> Self where N: Into<Box<str>>, V: Into<Node>, { Self::Property(name.into(), value.into()) } /// Creates a `MethodDefinition`. pub fn method_definition<N>(kind: MethodDefinitionKind, name: N, body: FunctionExpr) -> Self where N: Into<Box<str>>, { Self::MethodDefinition(kind, name.into(), body) } /// Creates a `SpreadObject`. pub fn spread_object<O>(obj: O) -> Self where O: Into<Node>, { Self::SpreadObject(obj.into()) } } /// Method definition kinds. /// /// Starting with ECMAScript 2015, a shorter syntax for method definitions on objects initializers is introduced. /// It is a shorthand for a function assigned to the method's name. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#prod-MethodDefinition /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug, PartialEq, Copy, Finalize)] pub enum MethodDefinitionKind { /// The `get` syntax binds an object property to a function that will be called when that property is looked up. /// /// Sometimes it is desirable to allow access to a property that returns a dynamically computed value, /// or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. /// In JavaScript, this can be accomplished with the use of a getter. /// /// It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, /// although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#prod-MethodDefinition /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get Get, /// The `set` syntax binds an object property to a function to be called when there is an attempt to set that property. /// /// In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. /// Setters are most often used in conjunction with getters to create a type of pseudo-property. /// It is not possible to simultaneously have a setter on a property that holds an actual value. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#prod-MethodDefinition /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set Set, /// Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. /// /// More information: /// - [ECMAScript reference][spec] /// - [MDN documentation][mdn] /// /// [spec]: https://tc39.es/ecma262/#prod-MethodDefinition /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#Method_definition_syntax Ordinary, // TODO: support other method definition kinds, like `Generator`. } unsafe impl Trace for MethodDefinitionKind { unsafe_empty_trace!(); }