1.. 2 Copyright (c) 2021-2024 Huawei Device Co., Ltd. 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 http://www.apache.org/licenses/LICENSE-2.0 7 Unless required by applicable law or agreed to in writing, software 8 distributed under the License is distributed on an "AS IS" BASIS, 9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 See the License for the specific language governing permissions and 11 limitations under the License. 12 13.. _Expressions: 14 15Expressions 16########### 17 18.. meta: 19 frontend_status: Partly 20 21This chapter describes the meanings of expressions and the rules for the 22evaluation of expressions, except for the expressions related to coroutines 23(see :ref:`Create and Launch a Coroutine` for ``launch`` expressions, and 24:ref:`Awaiting a Coroutine` for ``await`` expressions) and expressions 25that are described as experimental (see :ref:`Lambda Expressions with Receiver`). 26 27.. index:: 28 evaluation 29 expression 30 coroutine 31 launch expression 32 await expression 33 34.. code-block:: abnf 35 36 expression: 37 primaryExpression 38 | castExpression 39 | instanceOfExpression 40 | typeOfExpression 41 | nullishCoalescingExpression 42 | spreadExpression 43 | unaryExpression 44 | binaryExpression 45 | assignmentExpression 46 | conditionalExpression 47 | stringInterpolation 48 | lambdaExpression 49 | lambdaExpressionWithReceiver 50 | dynamicImportExpression 51 | launchExpression 52 | awaitExpression 53 ; 54 primaryExpression: 55 literal 56 | namedReference 57 | arrayLiteral 58 | objectLiteral 59 | thisExpression 60 | parenthesizedExpression 61 | methodCallExpression 62 | fieldAccessExpression 63 | indexingExpression 64 | functionCallExpression 65 | newExpression 66 | ensureNotNullishExpression 67 ; 68 binaryExpression: 69 multiplicativeExpression 70 | additiveExpression 71 | shiftExpression 72 | relationalExpression 73 | equalityExpression 74 | bitwiseAndLogicalExpression 75 | conditionalAndExpression 76 | conditionalOrExpression 77 ; 78 79The grammar rules below introduce several productions to be used by other 80expression rules: 81 82.. code-block:: abnf 83 84 objectReference: 85 typeReference 86 | 'super' 87 | primaryExpression 88 ; 89 90There are three options the ``objectReference`` refers to: 91 92- A class that is to handle static members; 93- ``Super`` that is to access shadowed fields or constructors declared in the 94 superclass, or the overridden method version of the superclass; 95- *primaryExpression* that is to refer to an instance variable of a class, 96 interface, or function type after evaluation, unless the manner of the 97 evaluation is altered by the chaining operator '``?.``' (see 98 :ref:`Chaining Operator`). 99 100If the form of *primaryExpression* is *thisExpression*, then the pattern 101"``this?.``" is handled as a :index:`compile-time error`. 102 103If the form of *primaryExpression* is *super*, then the pattern "``super?.``" 104is handled as a :index:`compile-time error`. 105 106.. index:: 107 field 108 constructor 109 superclass 110 overriding 111 method 112 variable 113 expression 114 instance variable 115 class 116 interface 117 function type 118 evaluation 119 chaining operator 120 pattern 121 122.. code-block:: abnf 123 124 arguments: 125 '(' argumentSequence? ')' 126 ; 127 128 argumentSequence: 129 restArgument 130 | expression (',' expression)* (',' restArgument)? ','? 131 ; 132 133 restArgument: 134 '...'? expression 135 ; 136 137The *arguments* grammar rule refers to the list of arguments of a call. Only 138the last argument can have the form of a spread expression (see 139:ref:`Spread Expression`). 140 141 142.. index:: 143 argument 144 spread operator 145 spread expression 146 147| 148 149.. _Evaluation of Expressions: 150 151Evaluation of Expressions 152************************* 153 154.. meta: 155 frontend_status: Done 156 todo: needs more investigation, too much failing CTS tests (mostly tests are buggy) 157 158The result of a program expression *evaluation* denotes the following: 159 160- A variable (the term *variable* is used here in the general, non-terminological 161 sense to denote a modifiable lvalue in the left-hand side of an assignment); 162 or 163- A value (results found elsewhere). 164 165.. index:: 166 evaluation 167 expression 168 variable 169 lvalue 170 assignment 171 172A variable or a value are equally considered the *value of the expression* 173if such a value is required for further evaluation. 174 175The type of an expression is inferred at compile time (see 176:ref:`Contexts and Conversions`). 177 178Expressions can contain assignments, increment operators, decrement operators, 179method calls, and function calls. The evaluation of an expression can produce 180side effects as a result. 181 182*Constant expressions* (see :ref:`Constant Expressions`) are the expressions 183with values that can be determined at compile time. 184 185.. index:: 186 variable 187 value 188 evaluation 189 expression 190 type 191 assignment 192 increment operator 193 decrement operator 194 method call 195 function call 196 side effect 197 constant expression 198 compile time 199 200| 201 202.. _Normal and Abrupt Completion of Expression Evaluation: 203 204Normal and Abrupt Completion of Expression Evaluation 205===================================================== 206 207.. meta: 208 frontend_status: Done 209 210Every expression in a normal mode of evaluation requires certain computational 211steps. The normal modes of evaluation for each kind of expression are described 212in the following sections. 213 214An expression evaluation *completes normally* if all computational steps 215are performed without throwing an exception or error. 216 217On the contrary, an expression *completes abruptly* if the expression 218evaluation throws an exception or an error. 219 220The information about the causes of an abrupt completion can be available 221in the value attached to the exception or error object. 222 223.. index:: 224 normal completion 225 abrupt completion 226 evaluation 227 expression 228 error 229 exception 230 value 231 232Runtime errors can occur as a result of expression or operator evaluation as 233follows: 234 235- If an *array reference expression* has the value ``null``, then an *array 236 indexing expression* (see :ref:`Array Indexing Expression`) throws 237 ``NullPointerError``. 238- If the value of an array index expression is negative, or greater than, or 239 equal to the length of the array, then an *array indexing expression* (see 240 :ref:`Array Indexing Expression`) throws ``ArrayIndexOutOfBoundsError``. 241- If a cast cannot be performed at runtime, then a *cast expression* (see 242 :ref:`Cast Expressions`) throws ``ClassCastError``. 243- If the right-hand operand expression has the zero value, then integer 244 division (see :ref:`Division`), or integer remainder (see :ref:`Remainder`) 245 operators throw ``ArithmeticError``. 246- If the boxing conversion (see :ref:`Boxing Conversions`) occurs while 247 performing an assignment to an array element of a reference type, then a 248 method call expression (see :ref:`Method Call Expression`), or prefix/postfix 249 increment/decrement (see :ref:`Unary Expressions`) operators can throw 250 ``OutOfMemoryError``. 251- If the type of an array element is not compatible with the value that is 252 being assigned, then assignment to an array element of a reference type 253 throws ``ArrayStoreError``. 254 255.. index:: 256 predefined operator 257 runtime error 258 array reference expression 259 value 260 array access expression 261 error 262 array indexing expression 263 array 264 runtime 265 cast expression 266 integer division 267 integer remainder 268 operator 269 remainder operator 270 array element 271 reference type 272 array literal 273 method call expression 274 prefix 275 postfix 276 increment operator 277 decrement operator 278 array element type 279 cast 280 assignment 281 282Possible hard-to-predict and hard-to-handle linkage and virtual machine errors 283can cause errors in the course of an expression evaluation. 284 285An abrupt completion of a subexpression evaluation results in the following: 286 287- Immediate abrupt completion of the expression that contains such a 288 subexpression (if the evaluation of the entire expression requires 289 the evaluation of the contained subexpression); and 290- Cancellation of all subsequent steps of the normal mode of evaluation. 291 292The terms *complete normally* and *complete abruptly* can also denote 293normal and abrupt completion of the execution of statements (see 294:ref:`Normal and Abrupt Statement Execution`). A statement can complete 295abruptly for a variety of reasons in addition to an exception or an error 296being thrown. 297 298.. index:: 299 normal completion 300 abrupt completion 301 execution 302 statement 303 error 304 exception 305 virtual machine 306 expression 307 subexpression 308 evaluation 309 linkage 310 311| 312 313.. _Order of Expression Evaluation: 314 315Order of Expression Evaluation 316============================== 317 318.. meta: 319 frontend_status: Done 320 321The operands of an operator are evaluated from left to right in accordance with 322the following rules: 323 324- Any right-hand operand is evaluated only after the full evaluation of the 325 left-hand operand of a binary operator. 326 327 If using a compound-assignment operator (see :ref:`Simple Assignment Operator`), 328 the evaluation of the left-hand operand includes the following: 329 330 331 - Remembering the variable denoted by the left-hand operand; 332 - Fetching the value of that variable for the subsequent evaluation 333 of the right-hand operand; and 334 - Saving such value. 335 336 If the evaluation of the left-hand operand completes abruptly, then no 337 part of the right-hand operand is evaluated. 338 339- Any part of the operation can be executed only after the full evaluation 340 of every operand of an operator (except conditional operators '``&&``', 341 '``||``', and '``?:``'). 342 343 The execution of a binary operator that is an integer division '``/``' (see 344 :ref:`Division`), or integer remainder '``%``' (see :ref:`Remainder`) can 345 throw ``ArithmeticError`` only after the evaluations of both operands 346 complete normally. 347- The |LANG| programming language follows the order of evaluation as indicated 348 explicitly by parentheses, and implicitly by the precedence of operators. 349 This rule particularly applies for infinity and ``NaN`` values of floating-point 350 calculations. 351 |LANG| considers integer addition and multiplication as provably associative; 352 however, floating-point calculations must not be naively reordered because 353 they are unlikely to be computationally associative (even though they appear 354 to be mathematically associative). 355 356.. index:: 357 operand 358 order of evaluation 359 expression 360 operator 361 evaluation 362 binary operator 363 compound-assignment operator 364 simple assignment operator 365 variable 366 value 367 abrupt completion 368 operator 369 error 370 precedence 371 operator precedence 372 infinity 373 NaN value 374 floating-point calculation 375 integer addition 376 integer multiplication 377 integer division 378 associativity 379 parenthesis 380 381| 382 383.. _Operator Precedence: 384 385Operator Precedence 386=================== 387 388.. meta: 389 frontend_status: Done 390 391The table below summarizes all information on the precedence and 392associativity of operators. Each section on a particular operator 393also contains detailed information. 394 395.. index:: 396 precedence 397 operator precedence 398 operator 399 associativity 400 401+---------------------------------+--------------------------------------------+----------------+ 402| **Operator** | **Precedence** | **Assoc-ty** | 403+=================================+============================================+================+ 404| postfix increment and decrement | ``++`` ``--`` | left to right | 405+---------------------------------+--------------------------------------------+----------------+ 406| prefix increment and decrement, | ``++ -- + - ! ~ typeof`` | right to left | 407| | | | 408| unary, typeof | | | 409+---------------------------------+--------------------------------------------+----------------+ 410| multiplicative | ``* / %`` | left to right | 411+---------------------------------+--------------------------------------------+----------------+ 412| additive | ``+ -`` | left to right | 413+---------------------------------+--------------------------------------------+----------------+ 414| cast | ``as`` | left to right | 415+---------------------------------+--------------------------------------------+----------------+ 416| shift | ``<< >> >>>`` | left to right | 417+---------------------------------+--------------------------------------------+----------------+ 418| relational | ``< > <= >= instanceof`` | left to right | 419+---------------------------------+--------------------------------------------+----------------+ 420| equality | ``== !=`` | left to right | 421+---------------------------------+--------------------------------------------+----------------+ 422| bitwise AND | ``&`` | left to right | 423+---------------------------------+--------------------------------------------+----------------+ 424| bitwise exclusive OR | ``^`` | left to right | 425+---------------------------------+--------------------------------------------+----------------+ 426| bitwise inclusive OR | ``|`` | left to right | 427+---------------------------------+--------------------------------------------+----------------+ 428| logical AND | ``&&`` | left to right | 429+---------------------------------+--------------------------------------------+----------------+ 430| logical OR | ``||`` | left to right | 431+---------------------------------+--------------------------------------------+----------------+ 432| null-coalescing | ``??`` | left to right | 433+---------------------------------+--------------------------------------------+----------------+ 434| ternary | ``?:`` | right to left | 435+---------------------------------+--------------------------------------------+----------------+ 436| assignment | ``= += -= %= *= /= &= ^= |= <<= >>= >>>=`` | right to left | 437+---------------------------------+--------------------------------------------+----------------+ 438 439.. index:: 440 precedence 441 bitwise operator 442 null-coalescing operator 443 assignment 444 shift operator 445 cast operator 446 equality operator 447 postfix operator 448 increment operator 449 decrement operator 450 prefix operator 451 logical operator 452 relational operator 453 454| 455 456.. _Evaluation of Arguments: 457 458Evaluation of Arguments 459======================= 460 461.. meta: 462 frontend_status: Done 463 464An evaluation of arguments always progresses from left to right up to the first 465error, or through the end of the expression; i.e., any argument expression is 466evaluated after the evaluation of each argument expression to its left 467completes normally (including comma-separated argument expressions that appear 468within parentheses in method calls, constructor calls, class instance creation 469expressions, or function call expressions). 470 471If the left-hand argument expression completes abruptly, then no part of the 472right-hand argument expression is evaluated. 473 474.. index:: 475 evaluation 476 argument 477 error 478 expression 479 normal completion 480 comma-separated argument expression 481 method call 482 constructor call 483 class instance creation expression 484 instance 485 function call expression 486 abrupt completion 487 488| 489 490.. _Evaluation of Other Expressions: 491 492Evaluation of Other Expressions 493=============================== 494 495.. meta: 496 frontend_status: Done 497 498These general rules cannot cover the order of evaluation of certain expressions 499when they from time to time cause exceptional conditions. The order of 500evaluation of the following expressions requires specific explanation: 501 502- Class instance creation expressions (see :ref:`New Expressions`); 503- Array creation expressions (see :ref:`Array Creation Expressions`); 504- Indexing expressions (see :ref:`Indexing Expressions`); 505- Method call expressions (see :ref:`Method Call Expression`); 506- Assignments involving indexing (see :ref:`Assignment`); 507- Lambda expressions (see :ref:`Lambda Expressions`). 508 509.. index:: 510 evaluation 511 expression 512 method call expression 513 class instance creation expression 514 array creation expression 515 indexing expression 516 assignment 517 indexing 518 lambda 519 lambda expression 520 521| 522 523.. _Literal: 524 525Literal 526******* 527 528.. meta: 529 frontend_status: Done 530 531Literals (see :ref:`Literals`) denote fixed and unchanging value. The type of 532the literal (see :ref:`Literals`) is the type of the expression. 533 534.. index:: 535 literal 536 value 537 538| 539 540.. _Named Reference: 541 542Named Reference 543*************** 544 545.. meta: 546 frontend_status: Partly 547 548An expression can have the form of a *named reference* as described by the 549syntax rule as follows: 550 551.. code-block:: abnf 552 553 namedReference: 554 qualifiedName typeArguments? 555 ; 556 557A *qualifiedName* (see :ref:`Names`) is an expression that consists of 558dot-separated names. A *qualifiedName* that consists of a single identifier 559is called a *simple name*. 560 561A *simple name* refers to the following: 562 563- An entity declared in the current compilation unit; 564- A local variable or parameter of the surrounding function or method. 565 566A *qualifiedName* that is not a *simple name* refers to the following: 567 568- An entity imported from a compilation unit, or 569- A member of some class or interface. 570 571If *typeArguments* are provided, then *qualifiedName* is a valid instantiation 572of the generic method or function. Otherwise, a :index:`compile-time error` 573occurs. 574 575A :index:`compile-time error` occurs if: 576 577- The name referred by *qualifiedName* is undefined or inaccessible; or 578- Ambiguity occurs while resolving the name. 579 580The type of the *named reference* is the type of the expression. 581 582.. index:: 583 named reference 584 expression 585 simple name 586 qualified name 587 dot-separated name 588 imported variable 589 qualification 590 qualified name 591 compilation unit 592 package 593 field 594 class property 595 local variable 596 surrounding function 597 method parameter 598 method 599 instantiation 600 generic method 601 ambiguity 602 603.. code-block:: typescript 604 :linenos: 605 606 import * as compilationUnitName from "someFile" 607 608 class Type {} 609 610 function foo (parameter: Type) { 611 let local: Type = parameter /* 'parameter' here is the 612 expression in the form of simple name */ 613 local = new Type () /* 'local' here is the expression in the 614 form of simple name */ 615 local = compilationUnitName.someExportedVariable /* qualifiedName here 616 refers to a variable imported from a compilation unit */ 617 let func = foo /* foo is a simple name of the function declared in this 618 module */ 619 620 goo() // goo is a undefined name - compile-time error 621 let bar_ref = bar // bar is an ambiguous reference - compile-time error 622 } 623 624 function bar (p: string) {} 625 function bar (p: number) {} 626 627 function generic_function<T> () {} 628 let instantiation = generic_function<string> 629 630| 631 632.. _Array Literal: 633 634Array Literal 635************* 636 637.. meta: 638 frontend_status: Done 639 todo: let x : int = [1,2,3][1] - valid? 640 todo: let x = ([1,2,3][1]) - should be CTE, but it isn't 641 todo: implement it properly for invocation context to get type from the context, not from the first element 642 643An *array literal* is an expression that can be used to create an array, and 644to provide some initial values: 645 646.. code-block:: abnf 647 648 arrayLiteral: 649 '[' expressionSequence? ']' 650 ; 651 652 expressionSequence: 653 expression (',' expression)* ','? 654 ; 655 656An *array literal* is a comma-separated list of *initializer expressions* 657enclosed between '``[``' and '``]``'. A trailing comma after the last 658expression in an array literal is ignored: 659 660The type of the expression is the type of the *array literal*. 661 662.. index:: 663 array literal 664 expression 665 value 666 comma-separated list 667 initializer expression 668 trailing comma 669 670 671.. code-block:: typescript 672 :linenos: 673 674 let x = [1, 2, 3] // ok 675 let y = [1, 2, 3,] // ok, trailing comma is ignored 676 677The number of initializer expressions enclosed in braces of the array 678initializer determines the length of the array to be constructed. 679 680If sufficient space is allocated for a new array, then a one-dimensional 681array of the specified length is created. All elements of the array 682are initialized to the values specified by initializer expressions. 683 684.. index:: 685 initializer expression 686 array initializer 687 array 688 one-dimensional array 689 array element 690 initialization 691 initializer expression 692 value 693 694On the contrary, the evaluation of the array initializer completes abruptly if: 695 696- The space allocated for the new array is insufficient, and 697 ``OutOfMemoryError`` is thrown; or 698- Some initialization expression completes abruptly. 699 700.. index:: 701 evaluation 702 array initializer 703 abrupt completion 704 array 705 error 706 initialization expression 707 708Initializer expressions are executed from left to right. The *n*’th expression 709specifies the value of the *n-1*’th element of the array. 710 711Array literals can be nested (i.e., the initializer expression that specifies 712an array element can be an array literal if that element is of an array type). 713 714The type of an array literal is inferred by the following rules: 715 716.. index:: 717 initializer expression 718 execution 719 value 720 array element 721 array literal 722 array type 723 type inference 724 725- If a context is available, then the type is inferred from the context. If 726 successful, then the type of the array literal is the inferred type 727 ``T[]``, ``Array<T>``, or tuple. 728- Otherwise, the type is to be inferred from the types of its elements. 729 730More details of both cases are presented below. 731 732.. index:: 733 type inference 734 context 735 array literal 736 array element 737 738| 739 740.. _Array Type Inference from Context: 741 742Array Type Inference from Context 743================================= 744 745.. meta: 746 frontend_status: Done 747 748The type of an array literal can be inferred from the context, including 749explicit type annotation of a variable declaration, left-hand part type 750of an assignment, call parameter type, or type of a cast expression: 751 752.. index:: 753 type inference 754 context 755 array type 756 array literal 757 type 758 type annotation 759 variable declaration 760 assignment 761 call parameter type 762 cast expression 763 764.. code-block:: typescript 765 :linenos: 766 767 let a: number[] = [1, 2, 3] // ok, variable type is used 768 a = [4, 5] // ok, variable type is used 769 770 function min(x: number[]): number { 771 let m = x[0] 772 for (let v of x) 773 if (v < m) 774 m = v 775 return m 776 } 777 min([1., 3.14, 0.99]); // ok, parameter type is used 778 779 // ... 780 type Matrix = number[][] 781 let m: Matrix = [[1, 2], [3, 4], [5, 6]] 782 783All valid conversions are applied to the initializer expression, i.e., each 784initializer expression type must be compatible (see :ref:`Type Compatibility`) 785with the array element type. Otherwise, a :index:`compile-time error` occurs. 786 787.. index:: 788 conversion 789 initializer expression 790 compatible type 791 type compatibility 792 array element 793 type 794 compile-time error 795 796.. code-block:: typescript 797 :linenos: 798 799 let value: number = 2 800 let list: Object[] = [1, value, "hello", new Error()] // ok 801 802In the example above, the first literal and 'value' are implicitly boxed to 803``Number``, and the types of a string literal and the instance of type 804``Error`` are compatible (see :ref:`Type Compatibility`) with ``Object`` 805because the corresponding classes are inherited from Object. 806 807.. index:: 808 literal 809 boxing 810 string literal 811 instance 812 error 813 type compatibility 814 compatible type 815 inheritance 816 817If the type used in the context is a *tuple type* (see :ref:`Tuple Types`), 818and types of all literal expressions are compatible with tuple type elements 819at respective positions, then the type of the array literal is a tuple type. 820 821.. code-block:: typescript 822 :linenos: 823 824 let tuple: [number, string] = [1, "hello"] // ok 825 826 let incorrect: [number, string] = ["hello", 1] // compile-time error 827 828If the type used in the context is a *union type* (see :ref:`Union Types`), then 829it is necessary to try inferring the type of the array literal from its elements 830(see :ref:`Array Type Inference from Types of Elements`). If successful, then 831the type so inferred must be compatible with one of the types that form the 832union type. Otherwise, it is a :index:`compile-time error`: 833 834 835.. code-block:: typescript 836 :linenos: 837 838 839 let union_of_arrays: number[] | string[] = [1, 2] // OK, type of literal is number[] 840 let incorrect_union_of_arrays: number[] | string[] = [1, 2, "string"] 841 // compile-time error: number|string[] is not compatible with number[] | string[] 842 843.. index:: 844 tuple type 845 context 846 literal 847 expression 848 type 849 array literal 850 union type 851 inference 852 853| 854 855.. _Array Type Inference from Types of Elements: 856 857Array Type Inference from Types of Elements 858=========================================== 859 860.. meta: 861 frontend_status: Done 862 863If the type of an array literal ``[`` ``expr``:sub:`1`, ``...`` , ``expr``:sub:`N` ``]`` 864cannot be inferred from the context, then the following algorithm is to be 865used to infer it from the initialization expressions: 866 867.. #. If there is no expression (*N == 0*), then the type is ``Object[]``. 868 869#. If there is no expression (*N == 0*), then the type of the 870 array literal cannot be inferred, and a :index:`compile-time error` occurs. 871 872#. If the type of the expression cannot be determined, then the type of the 873 array literal cannot be inferred, and a :index:`compile-time error` occurs. 874 875#. If each initialization expression is of a numeric type, then the 876 type is ``number[]``. 877 878#. If all initialization expressions are of the same type ``T``, then the 879 type is ``T[]``. 880 881#. Otherwise, the type is constructed as the union type ``T``:sub:`1` ``| ... | 882 T``:sub:`N`, where ``T``:sub:`i` is the type of *expr*:sub:`i`. 883 Union type normalization (see :ref:`Union Types Normalization`) is applied 884 to this union type. 885 886.. index:: 887 type inference 888 array element 889 array literal 890 type 891 context 892 initialization expression 893 expression 894 compile-time error 895 numeric type 896 union type normalization 897 union type 898 899.. code-block:: typescript 900 :linenos: 901 902 let a = [] // type is Object[] 903 let b = ["a"] // type is string[] 904 let c = [1, 2, 3] // type is number[] 905 let d = ["a", 1, 3.14] // type is (string | number)[] 906 let e = [(): void => {}, new A()] // type is (() => void | A)[] 907 908| 909 910.. _Object Literal: 911 912Object Literal 913*************** 914 915.. meta: 916 frontend_status: Done 917 918An *object literal* is an expression that can be used to create a class 919instance, and to provide some initial values. In some cases it is more 920convenient to use an *object literal* in place of a class instance creation 921expression (see :ref:`New Expressions`): 922 923.. index:: 924 object literal 925 expression 926 instance 927 class instance 928 creation expression 929 930.. code-block:: abnf 931 932 objectLiteral: 933 '{' valueSequence? '}' 934 ; 935 936 valueSequence: 937 nameValue (',' nameValue)* ','? 938 ; 939 940 nameValue: 941 identifier ':' expression 942 ; 943 944An *object literal* is written as a comma-separated list of *name-value pairs* 945enclosed in curly braces '``{``' and '``}``'. A trailing comma after the last 946pair is ignored. Each *name-value pair* consists of an identifier and an 947expression: 948 949.. index:: 950 object literal 951 comma-separated list 952 name-value pair 953 curly brace 954 trailing comma 955 identifier 956 expression 957 958.. code-block:: typescript 959 :linenos: 960 961 class Person { 962 name: string = "" 963 age: number = 0 964 } 965 let b : Person = {name: "Bob", age: 25} 966 let a : Person = {name: "Alice", age: 18, } //ok, trailing comma is ignored 967 968The type of an object literal is always some class ``C`` that is inferred from 969the context. A type inferred from the context can be either a named class (see 970:ref:`Object Literal of Class Type`), or an anonymous class created for the 971inferred interface type (see :ref:`Object Literal of Interface Type`). 972 973A :index:`compile-time error` occurs if: 974 975- The type of an object literal cannot be inferred from the context; or 976- The inferred type is not a class or an interface type. 977 978The type of the expression is the type of the *object literal*. 979 980.. index:: 981 object literal 982 inference 983 named class 984 anonymous class 985 context 986 class type 987 anonymous class 988 interface type 989 compile-time error 990 inferred type 991 992.. code-block:: typescript 993 :linenos: 994 995 let p = {name: "Bob", age: 25} /* compile-time error, type is 996 not inferred */ 997 998| 999 1000.. _Object Literal of Class Type: 1001 1002Object Literal of Class Type 1003============================= 1004 1005.. meta: 1006 frontend_status: Done 1007 1008If the class type ``C`` is inferred from the context, then the type of object 1009literal is ``C``: 1010 1011.. index:: 1012 object literal 1013 class type 1014 inference 1015 context 1016 1017.. code-block:: typescript 1018 :linenos: 1019 1020 class Person { 1021 name: string = "" 1022 age: number = 0 1023 } 1024 function foo(p: Person) { /*some code*/ } 1025 // ... 1026 let p: Person = {name: "Bob", age: 25} /* ok, variable type is 1027 used */ 1028 foo({name: "Alice", age: 18}) // ok, parameter type is used 1029 1030 1031An identifier in each *name-value pair* must name a field of the class ``C``, 1032or a field of any superclass of class ``C``. 1033 1034A :index:`compile-time error` occurs if the identifier does not name an 1035*accessible member field* (see :ref:`Accessible`) in the type ``C``: 1036 1037.. index:: 1038 identifier 1039 name-value pair 1040 field 1041 superclass 1042 class 1043 compile-time error 1044 accessible member field 1045 scope 1046 1047.. code-block:: typescript 1048 :linenos: 1049 1050 class Friend { 1051 name: string = "" 1052 private nick: string = "" 1053 age: number = 0 1054 } 1055 // compile-time error, nick is private: 1056 let f: Friend = {name: "aa", age: 55, nick: "bb"} 1057 1058A :index:`compile-time error` occurs if the type of an expression in a 1059*name-value pair* is not compatible (see :ref:`Type Compatibility`) with the 1060field type: 1061 1062.. code-block:: typescript 1063 :linenos: 1064 1065 let f: Friend = {name: 123 /* compile-time error - type of right hand-side 1066 is not compatible to the type of the left hand-side */ 1067 1068If class ``C`` is to be used in an object literal, then it must have a 1069*parameterless* constructor (explicit or default) that is *accessible* 1070(see :ref:`Accessible`) in the class composite context. 1071 1072A :index:`compile-time error` occurs if: 1073 1074- ``C`` does not contain a parameterless constructor; or 1075- No constructor is accessible (see :ref:`Accessible`). 1076 1077These situations are presented in the examples below: 1078 1079.. index:: 1080 compile-time error 1081 expression 1082 type 1083 name-value pair 1084 compatibility 1085 field type 1086 accessibility 1087 constructor 1088 context 1089 parameterless constructor 1090 class composite context 1091 object literal 1092 access 1093 1094.. code-block:: typescript 1095 :linenos: 1096 1097 class C { 1098 constructor (x: number) {} 1099 } 1100 // ... 1101 let c: C = {} /* compile-time error - no parameterless 1102 constructor */ 1103 1104.. code-block:: typescript 1105 :linenos: 1106 1107 class C { 1108 private constructor () {} 1109 } 1110 // ... 1111 let c: C = {} /* compile-time error - constructor is not 1112 accessible */ 1113 1114| 1115 1116.. _Object Literal of Interface Type: 1117 1118Object Literal of Interface Type 1119================================ 1120 1121.. meta: 1122 frontend_status: Partly 1123 todo: implement generic types 1124 1125If the interface type ``I`` is inferred from the context, then the type of the 1126object literal is an anonymous class implicitly created for interface *I*: 1127 1128.. code-block:: typescript 1129 :linenos: 1130 1131 interface Person { 1132 name: string 1133 age: number 1134 } 1135 let b : Person = {name: "Bob", age: 25} 1136 1137In the example above, the type of *b* is an anonymous class that contains the 1138same fields as the interface *I*. 1139 1140The interface type ``I`` must contain fields only. A :index:`compile-time error` 1141occurs if the interface type ``I`` contains a method: 1142 1143.. index:: 1144 object literal 1145 interface type 1146 inference 1147 context 1148 anonymous class 1149 interface 1150 anonymous class 1151 field 1152 method 1153 compile-time error 1154 1155.. code-block:: typescript 1156 :linenos: 1157 1158 interface I { 1159 name: string 1160 foo() 1161 } 1162 let i : I = {name: "Bob"} // compile-time error, interface has methods 1163 1164| 1165 1166.. _Object Literal of Record Type: 1167 1168Object Literal of ``Record`` Type 1169================================= 1170 1171.. meta: 1172 frontend_status: Done 1173 1174Generic type ``Record<Key, Value>`` (see :ref:`Record Utility Type`) is used 1175to map the properties of a type (type ``Key``) to another type (type ``Value``). 1176A special form of an object literal is used to initialize the value of such 1177type: 1178 1179.. index:: 1180 object literal 1181 generic type 1182 record type 1183 type property 1184 type value 1185 type key 1186 initialization 1187 value 1188 1189.. code-block:: abnf 1190 1191 recordLiteral: 1192 '{' keyValueSequence? '}' 1193 ; 1194 1195 keyValueSequence: 1196 keyValue (',' keyValue)* ','? 1197 ; 1198 1199 keyValue: 1200 expression ':' expression 1201 ; 1202 1203The first expression in ``keyValue`` denotes a key, and must be of type ``Key``; 1204the second expression denotes a value, and must be of type ``Value``: 1205 1206.. index:: 1207 expression 1208 key 1209 value 1210 1211.. code-block:: typescript 1212 1213 let map: Record<string, number> = { 1214 "John": 25, 1215 "Mary": 21, 1216 } 1217 1218 console.log(map["John"]) // prints 25 1219 1220 1221.. code-block:: typescript 1222 1223 interface PersonInfo { 1224 age: number 1225 salary: number 1226 } 1227 let map: Record<string, PersonInfo> = { 1228 "John": { age: 25, salary: 10}, 1229 "Mary": { age: 21, salary: 20} 1230 } 1231 1232If a key is a union type consisting of literals, then all variants must be 1233listed in the object literal. Otherwise, a :index:`compile-time error` occurs: 1234 1235.. index:: 1236 key 1237 union type 1238 literal 1239 object literal 1240 compile-time error 1241 1242.. code-block:: typescript 1243 1244 let map: Record<"aa" | "bb", number> = { 1245 "aa": 1, 1246 } // compile-time error: "bb" key is missing 1247 1248| 1249 1250.. _Object Literal Evaluation: 1251 1252Object Literal Evaluation 1253========================= 1254 1255.. meta: 1256 frontend_status: Done 1257 1258The evaluation of an object literal of type ``C`` (where ``C`` is either 1259a named class type or an anonymous class type created for the interface) 1260is to be performed by the following steps: 1261 1262- A parameterless constructor is executed to produce an instance *x* of 1263 the class ``C``. The execution of the object literal completes abruptly 1264 if so does the execution of the constructor. 1265 1266- Name-value pairs of the object literal are then executed from left to 1267 right in the textual order they occur in the source code. The execution 1268 of a name-value pair includes the following: 1269 1270 - Evaluation of the expression; and 1271 - Assigning the value of the expression to the corresponding field 1272 of *x* as its initial value. This rule also applies to *readonly* fields. 1273 1274.. index:: 1275 object literal 1276 evaluation 1277 named class 1278 anonymous class 1279 interface 1280 parameterless constructor 1281 constructor 1282 instance 1283 execution 1284 abrupt completion 1285 name-value pair 1286 field 1287 value 1288 expression 1289 assignment 1290 literal type 1291 readonly field 1292 1293The execution of the object literal completes abruptly if so does 1294the execution of a name-value pair. 1295 1296The object literal completes normally with the value of the newly 1297initialized class instance if so do all name-value pairs. 1298 1299.. index:: 1300 execution 1301 object literal 1302 abrupt completion 1303 normal completion 1304 name-value pair 1305 evaluation 1306 initialization 1307 class instance 1308 1309| 1310 1311.. _spread Expression: 1312 1313Spread Expression 1314***************** 1315 1316.. meta: 1317 frontend_status: Done 1318 1319.. code-block:: abnf 1320 1321 spreadExpression: 1322 '...' expression 1323 ; 1324 1325A *spread expression* can be used only within the array literal (see 1326:ref:`Array Literal`) or argument passing. The *expression* must be of 1327array type (see :ref:`Array Types`) or tuple type (see :ref:`Tuple Types`). 1328Otherwise, a :index:`compile-time error` occurs. 1329 1330A *spread expression* for arrays or tuples can be evaluated as follows: 1331 1332- By the compiler at compile time if *expression* is constant (see 1333 :ref:`Constant Expressions`); 1334- At runtime otherwise. 1335 1336An array or tuple referred by the *expression* is broken by the evaluation into 1337a sequence of values. This sequence is used where a spread expression is used. 1338It can be an assignment, a call of a function, method, or constructor. 1339 1340The type of the *spread expression* is a sequence of types of these values. 1341 1342.. index:: 1343 spread expression 1344 array literal 1345 argument 1346 expression 1347 array type 1348 tuple type 1349 runtime 1350 compiler 1351 evaluation 1352 call 1353 function 1354 method 1355 constructor 1356 assignment 1357 1358.. code-block:: typescript 1359 :linenos: 1360 1361 let array1 = [1, 2, 3] 1362 let array2 = [4, 5] 1363 let array3 = [...array1, ...array2] // spread array1 and array2 elements 1364 // while building new array literal during compile-time 1365 console.log(array3) // prints [1, 2, 3, 4, 5] 1366 1367 foo (...array2) // spread array2 elements into arguments of the foo() call 1368 function foo (...array: number[]) { 1369 console.log (array) 1370 } 1371 1372 run_time_spread_application1 (array1, array2) // prints [1, 2, 3, 666, 4, 5] 1373 function run_time_spread_application1 (a1: number[], a2: number[]) { 1374 console.log ([...a1, 666, ...a2]) 1375 // array literal will be built at runtime 1376 } 1377 1378 let tuple1: [number, string, boolean] = [1, "2", true] 1379 let tuple2: [number, string] = [4, "5"] 1380 let tuple3: [number, string, boolean, number, string] = [...tuple1, ...tuple2] // spread tuple1 and tuple2 elements 1381 // while building new tuple object during compile-time 1382 console.log(tuple3) // prints [1, "2", true, 4, "5"] 1383 1384 bar (...tuple2) // spread tuple2 elements into arguments of the foo() call 1385 function bar (...tuple: [number, string]) { 1386 console.log (tuple) 1387 } 1388 1389 run_time_spread_application2 (tuple1, tuple2) // prints [1, "2", true, 666, 4, "5"] 1390 function run_time_spread_application2 (a1: [number, string, boolean], a2: [number, string]) { 1391 console.log ([...a1, 666, ...a2]) 1392 // such array literal will be built at runtime 1393 } 1394 1395 1396**Note**: If an array is spread while calling a function, then an appropriate 1397parameter must be of the spread array kind. If an array is spread into a 1398sequence of ordinary parameters, then a :index:`compile-time error` occurs: 1399 1400.. code-block:: typescript 1401 :linenos: 1402 1403 let an_array = [1, 2] 1404 bar (...an_array) // compile-time error 1405 function bar (n1: number, n2: number) { ... } 1406 1407**Note**: If a tuple is spread while calling a function, an appropriate 1408parameter must be of spread tuple kind. A :index:`compile-time error` occurs if 1409a tuple is spread into a sequence of ordinary parameters: 1410 1411.. code-block:: typescript 1412 :linenos: 1413 1414 let a_tuple: [number, string] = [1, "2"] 1415 bar (...a_tuple) // compile-time error 1416 function bar (n1: number, n2: string) { ... } 1417 1418.. index:: 1419 spread 1420 function call 1421 parameter 1422 tuple 1423 spread array 1424 array 1425 parameter 1426 1427| 1428 1429.. _Parenthesized Expression: 1430 1431Parenthesized Expression 1432************************ 1433 1434.. meta: 1435 frontend_status: Done 1436 1437.. code-block:: abnf 1438 1439 parenthesizedExpression: 1440 '(' expression ')' 1441 ; 1442 1443The type and the value of a parenthesized expression are the same as those of 1444the contained expression. 1445 1446.. index:: 1447 parenthesized expression 1448 type 1449 value 1450 contained expression 1451 1452| 1453 1454.. _this Expression: 1455 1456``this`` Expression 1457******************* 1458 1459.. meta: 1460 frontend_status: Done 1461 1462.. code-block:: abnf 1463 1464 thisExpression: 1465 'this' 1466 ; 1467 1468The keyword ``this`` can be used as an expression in the body of an instance 1469method of a class (see :ref:`Method Body`) or interface (see 1470:ref:`Default Interface Method Declarations`). The type of *this expression* 1471will be the appropriate class or interface type. 1472 1473It can be used in a lambda expression only if it is allowed in the 1474context the lambda expression appears in. 1475 1476The keyword ``this`` in a direct call expression *this(...)* can only 1477be used in the explicit constructor call statement. XXX 1478 1479Also the keyword ``this`` can be used in the body of the functiosn with 1480receiver (see :ref:`Functions with Receiver`). The type of *this expression* 1481will be the declared type of ``this`` parameter of the function. 1482 1483A :index:`compile-time error` occurs if the keyword ``this`` appears elsewhere. 1484 1485.. index:: 1486 compile-time error 1487 keyword this 1488 expression 1489 instance method 1490 method body 1491 class 1492 enum 1493 interface 1494 lambda expression 1495 direct call expression 1496 explicit constructor call statement 1497 constructor 1498 constructor call statement 1499 1500The keyword ``this`` used as a primary expression denotes a value that is a 1501reference to the following: 1502 1503- Object for which the instance method is called; or 1504- Object being constructed. 1505 1506 1507The value denoted by ``this`` in a lambda body and in the surrounding context 1508is the same. 1509 1510The class of the actual object referred to at runtime can be ``T`` if ``T`` 1511is a class type, or a class that is compatible (see :ref:`Type Compatibility`) 1512with ``T``. 1513 1514.. index:: 1515 keyword this 1516 primary expression 1517 value 1518 instance method 1519 instance method call 1520 object 1521 lambda body 1522 surrounding context 1523 compatibility 1524 class 1525 runtime 1526 class type 1527 class 1528 1529| 1530 1531.. _Field Access Expression: 1532 1533Field Access Expression 1534*********************** 1535 1536.. meta: 1537 frontend_status: Done 1538 1539A *field access expression* can access a field of an object that is referred to 1540by the object reference. The object reference can have different forms 1541described in detail in :ref:`Accessing Current Object Fields` and 1542:ref:`Accessing Superclass Fields`. 1543 1544 1545.. index:: 1546 field access expression 1547 access 1548 field 1549 superclass 1550 object reference 1551 1552.. code-block:: abnf 1553 1554 fieldAccessExpression: 1555 objectReference ('.' | '?.') identifier 1556 ; 1557 1558A *field access expression* that contains '``?.``' (see :ref:`Chaining Operator`) 1559is called *safe field access* because it handles nullish object references 1560safely. 1561 1562If object reference evaluation completes abruptly, then so does the entire 1563field access expression. 1564 1565An object reference used for Field Access must be a non-nullish reference 1566type ``T``. Otherwise, a :index:`compile-time error` occurs. 1567 1568Field access expression is valid if the identifier refers to an accessible 1569(see :ref:`Accessible`) member field in type ``T``. A :index:`compile-time error` 1570occurs otherwise. 1571 1572The type of the *field access expression* is the type of the member field. 1573 1574.. index:: 1575 access 1576 field 1577 field access expression 1578 safe field access 1579 nullish object reference 1580 abrupt completion 1581 non-nullish type 1582 reference type 1583 compile-time error 1584 member field 1585 identifier 1586 accessible member field 1587 1588| 1589 1590.. _Accessing Current Object Fields: 1591 1592Accessing Current Object Fields 1593=============================== 1594 1595.. meta: 1596 frontend_status: Done 1597 1598The result of the field access expression is computed at runtime as described 1599below. 1600 1601a. *Static* field access (*objectReference* is evaluated in the form *typeReference*) 1602 1603The evaluation of *typeReference* is performed. The result of the *field access 1604expression* of a static field in a class is as follows: 1605 1606- ``variable`` if the field is not ``readonly``. The resultant value can 1607 then be changed. 1608 1609- ``value`` if the field is ``readonly``, except where the *field access* 1610 occurs in a class initializer (see :ref:`Class Initializer`). 1611 1612 1613.. index:: 1614 access 1615 runtime 1616 field access expression 1617 object reference expression 1618 evaluation 1619 static field 1620 interface 1621 class variable 1622 type 1623 const field 1624 field 1625 field access 1626 variable 1627 readonly 1628 class 1629 static initializer 1630 class initializer 1631 variable initializer 1632 1633b. *Instance* field access (*objectReference* is evaluated in the form *primaryExpression*) 1634 1635The evaluation of *primaryExpression* is performed. The result of the *field 1636access expression* of an instance field in the class or interface is as follows: 1637 1638- ``variable`` if the field is not ``readonly``. Then the resultant value can 1639 be changed. 1640 1641- ``value`` if the field is ``readonly``, except where the *field access* 1642 occurs in a constructor (see :ref:`Constructor Declaration`). 1643 1644Only the *primaryExpression* type (not the class type of an actual object 1645referred at runtime) is used to determine the field to be accessed. 1646 1647.. index:: 1648 instance field access 1649 field access 1650 field access expression 1651 interface 1652 variable 1653 readonly 1654 object reference expression 1655 evaluation 1656 access 1657 runtime 1658 initializer 1659 instance initializer 1660 constructor 1661 field access 1662 reference type 1663 class type 1664 1665| 1666 1667.. _Accessing Superclass Fields: 1668 1669Accessing Superclass Fields 1670=========================== 1671 1672.. meta: 1673 frontend_status: Done 1674 1675The form ``super.identifier`` refers to the field named ``identifier`` of the 1676current object that is inherited by or declared in the superclass, and shadowed 1677by another field of the current object's class type. 1678 1679The forms that use the keyword ``super`` are valid only in: 1680 1681- Instance methods; 1682- Instance initializers; 1683- Constructors of a class; or 1684- Initializers of an instance variable of a class. 1685 1686A :index:`compile-time error` occurs if forms with the keyword ``super`` are found: 1687 1688- Elsewhere; 1689- In the declaration of class ``Object`` (since ``Object`` has no superclass). 1690 1691The field access expression *super.f* is handled in the same way as the 1692expression *this.f* in the body of class ``S``. Assuming that *super.f* 1693appears within class ``C``, *f* is accessible (see :ref:`Accessible`) in *S* from 1694class ``C`` while: 1695 1696- The direct superclass of ``C`` is class ``S``; 1697- The direct superclass of the class denoted by ``T`` is a class with ``S`` 1698 as its fully qualified name. 1699 1700A :index:`compile-time error` occurs otherwise (particularly if the current 1701class is not ``T``). 1702 1703.. index:: 1704 access 1705 superclass field 1706 class type 1707 identifier 1708 instance method 1709 instance initializer 1710 accessibility 1711 superclass 1712 constructor 1713 instance variable 1714 keyword super 1715 instance initializer 1716 initializer 1717 compile-time error 1718 Object 1719 field access expression 1720 direct superclass 1721 qualified name 1722 1723 1724| 1725 1726.. _Method Call Expression: 1727 1728Method Call Expression 1729********************** 1730 1731.. meta: 1732 frontend_status: Done 1733 1734A *method call expression* calls a static or instance method of a class or 1735an interface. 1736 1737.. index:: 1738 method call expression 1739 static method 1740 instance method 1741 class 1742 interface 1743 1744.. code-block:: abnf 1745 1746 methodCallExpression: 1747 objectReference ('.' | '?.') identifier typeArguments? arguments block? 1748 ; 1749 1750The syntax form that has a block associated with the method call is a special 1751form called *trailing lambda call* (see :ref:`Trailing Lambdas` for details. 1752 1753A method call with '``?.``' (see :ref:`Chaining Operator`) is called a 1754*safe method call* because it handles nullish values safely. 1755 1756Resolving a method at compile time is more complicated than resolving a field 1757because method overloading (see :ref:`Class Method Overloading`) can occur. 1758 1759There are several steps that determine and check the method to be called at 1760compile time (see :ref:`Step 1 Selection of Type to Use`, 1761:ref:`Step 2 Selection of Method`, and 1762:ref:`Step 3 Checking Method Modifiers`). 1763 1764.. index:: 1765 compile-time error 1766 trailing lambda call 1767 type argument 1768 method call 1769 chaining operator 1770 safe method call 1771 nullish value 1772 method resolution 1773 method modifier 1774 compile time 1775 field resolution 1776 method overloading 1777 semantic correctness check 1778 1779| 1780 1781.. _Step 1 Selection of Type to Use: 1782 1783Step 1: Selection of Type to Use 1784================================ 1785 1786.. meta: 1787 frontend_status: Done 1788 1789The *object reference* is used to determine the type in which to search the method. 1790Three forms of *object reference* are available: 1791 1792 1793.. table:: 1794 :widths: 40, 60 1795 1796 ============================== ================================================================= 1797 **Form of object reference** **Type to use** 1798 ============================== ================================================================= 1799 ``typeReference`` Type denoted by ``typeReference``. 1800 ``expression`` of type *T* ``T`` if ``T`` is a class, interface, or union; ``T``’s constraint (:ref:`Type Parameter Constraint`) if ``T`` is a type parameter. A :index:`compile-time error` occurs otherwise. 1801 ``super`` The superclass of the class that contains the method call. 1802 ============================== ================================================================= 1803 1804 1805.. index:: 1806 type 1807 object reference 1808 method identifier 1809 compile-time error 1810 expression 1811 identifier 1812 interface 1813 superclass 1814 class 1815 method call 1816 type parameter constraint 1817 1818| 1819 1820.. _Step 2 Selection of Method: 1821 1822Step 2: Selection of Method 1823=========================== 1824 1825.. meta: 1826 frontend_status: Done 1827 1828After the type to use is known, the method to call must be determined. As 1829|LANG| supports overloading, more than one method can be accessible 1830under the method name used in the call. 1831 1832All accessible methods are called *potentially applicable candidates*, and 1833:ref:`Overload Resolution` is used to select the method to call. If *overload 1834resolution* can definitely select a single method, then this method is called. 1835Otherwise, a :index:`compile-time error` occurs as more than one applicable 1836method is available (no method to call, or ambiguity). 1837 1838.. index:: 1839 overload resolution 1840 method call 1841 potentially applicable candidate 1842 accessible method 1843 access 1844 1845| 1846 1847.. _Step 3 Checking Method Modifiers: 1848 1849Step 3: Checking Method Modifiers 1850================================= 1851 1852.. meta: 1853 frontend_status: Done 1854 1855In this step, the single method to call is known, and the following set of 1856semantic checks must be performed: 1857 1858- If the method call has the form ``typeReference.identifier``, then 1859 ``typeReference`` refers to a class, and the method must be declared 1860 ``static``. Otherwise, a :index:`compile-time error` occurs. 1861 1862- If the method call has the form ``expression.identifier``, then the method 1863 must not be declared ``static``. Otherwise, a :index:`compile-time error` 1864 occurs. 1865 1866- If the method call has the form ``super.identifier``, then the method must 1867 not be declared ``abstract`` or ``static``. Otherwise, a 1868 :index:`compile-time error` occurs. 1869 1870.. index:: 1871 method call 1872 semantic check 1873 static method call 1874 abstract method call 1875 type argument 1876 1877 1878.. _Type of the method call expression: 1879 1880Type of the method call expression 1881================================== 1882 1883.. meta: 1884 frontend_status: None 1885 1886The type of the *method call expression* is defined below 1887- TBD 1888 1889 1890| 1891 1892.. _Function Call Expression: 1893 1894Function Call Expression 1895************************ 1896 1897.. meta: 1898 frontend_status: Done 1899 1900A *function call expression* is used to call a function (see 1901:ref:`Function Declarations`), a variable of a function type 1902(:ref:`Function Types`), or a lambda expression (see :ref:`Lambda Expressions`): 1903 1904.. code-block:: abnf 1905 1906 functionCallExpression: 1907 expression ('?.' | typeArguments)? arguments block? 1908 ; 1909 1910A special syntactic form that contains a block associated with the function 1911call is called *trailing lambda call* (see :ref:`Trailing Lambdas` for details). 1912 1913A :index:`compile-time error` occurs if: 1914 1915- The expression type is different than the function type; 1916- The expression type is nullish but without '``?.``' (see 1917 :ref:`Chaining Operator`). 1918 1919.. index:: 1920 function call expression 1921 function call 1922 function type 1923 trailing lambda call 1924 lambda expression 1925 compile-time error 1926 type argument 1927 expression type 1928 function type 1929 nullish type 1930 chaining operator 1931 1932If the operator '``?.``' (see :ref:`Chaining Operator`) is present, and the 1933*expression* evaluates to a nullish value, then: 1934 1935- *Arguments* are not evaluated; 1936- Call is not performed; and thus 1937- The result of *functionCallExpression* is not produced. 1938 1939The function call is *safe* because it handles nullish values properly. 1940 1941.. index:: 1942 chaining operator 1943 expression 1944 evaluation 1945 nullish value 1946 semantic correctness check 1947 undefined 1948 function call 1949 1950The following important situations depend on the form of expression in a call, 1951and require different semantic checks: 1952 1953- The form of expression in the call is *qualifiedName*, and *qualifiedName* 1954 refers to an accessible function (:ref:`Function Declarations`), or to a set 1955 of accessible overloaded functions. 1956 1957 In this case, all accessible functions are *potentially applicable candidates*, 1958 and :ref:`Overload Resolution` is used to select the function to call. 1959 If *overload resolution* can definitely select a single function, then this 1960 function is called. 1961 Otherwise (i.e., if there is no function to call, or if ambiguity is caused 1962 by more than one applicable functions available), a :index:`compile-time error` 1963 occurs. 1964 1965- All other forms of expression. 1966 1967 In this case, *overload resolution* is not required as the expression 1968 determines the entity to call unambiguously. See 1969 :ref:`Compatibility of Call Arguments` for the semantic checks to be performed. 1970 1971.. index:: 1972 overload resolution 1973 expression 1974 semantic check 1975 function call 1976 potentially applicable candidate 1977 accessibility 1978 qualified name 1979 function 1980 1981 1982The example below represents different forms of function calls: 1983 1984.. code-block:: typescript 1985 :linenos: 1986 1987 function foo() { console.log ("Function foo() is called") } 1988 foo() // function call uses function name to call it 1989 1990 call (foo) // top-level function passed 1991 call ((): void => { console.log ("Lambda is called") }) // lambda is passed 1992 call (A.method) // static method 1993 call ((new A).method) // instance method is passed 1994 1995 class A { 1996 static method() { console.log ("Static method() is called") } 1997 method() { console.log ("Instance method() is called") } 1998 } 1999 2000 function call (callee: () => void) { 2001 callee() // function call uses parameter name to call any functional object passed as an argument 2002 } 2003 2004 ((): void => { console.log ("Lambda is called") }) () // function call uses lambda expression to call it 2005 2006 2007The type of the *function call expression* is defined below 2008- TBD 2009 2010 2011| 2012 2013.. _Indexing Expressions: 2014 2015Indexing Expressions 2016******************** 2017 2018.. meta: 2019 frontend_status: Done 2020 2021Indexing expressions are used to access elements of arrays (see 2022:ref:`Array Types`) and ``Record`` instances (see :ref:`Record Utility Type`). 2023Indexing expressions can also be applied to instances of indexable types (see 2024:ref:`Indexable Types`): 2025 2026.. code-block:: abnf 2027 2028 indexingExpression: 2029 expression ('?.')? '[' expression ']' 2030 ; 2031 2032Any indexing expression has two subexpressions: 2033 2034- *Object reference expression* before the left bracket; and 2035- *Index expression* inside the brackets. 2036 2037.. index:: 2038 indexing expression 2039 indexable type 2040 access 2041 array element 2042 array type 2043 record instance 2044 record utility type 2045 subexpression 2046 object reference expression 2047 index expression 2048 2049If the operator '``?.``' (see :ref:`Chaining Operator`) is present in an 2050indexing expression, then: 2051 2052- If an object reference expression is not of a nullish type, then the 2053 chaining operator has no effect. 2054- Otherwise, object reference expression must be checked to nullish 2055 value. If the value is ``undefined`` or ``null``, 2056 then the evaluation of the entire surrounding *primary expression* stops. 2057 The result of the entire primary expression is then ``undefined``. 2058 2059If no '``?.``' is present in an indexing expression, then object reference 2060expression must be an array type or the ``Record`` type. Otherwise, a 2061:index:`compile-time error` occurs. 2062 2063.. index:: 2064 chaining operator 2065 indexing expression 2066 object reference expression 2067 expression 2068 primary expression 2069 array type 2070 nullish type 2071 record type 2072 compile-time error 2073 reference expression 2074 evaluation 2075 nullish value 2076 2077| 2078 2079.. _Array Indexing Expression: 2080 2081Array Indexing Expression 2082========================= 2083 2084.. meta: 2085 frontend_status: Partly 2086 todo: implement floating point index support - #14001 2087 2088For array indexing, the *index expression* must be of a numeric type. 2089 2090If *index expression* is of type ``number`` or other floating-point type, 2091and the fractional part differs from 0, then errors occur as follows: 2092 2093- A runtime error, if the situation is identified during program execution; 2094 and 2095- A :index:`compile-time error`, if the situation is detected during 2096 compilation. 2097 2098 2099A numeric types conversion (see :ref:`Primitive Types Conversions`) is 2100performed on *index expression* to ensure that the resultant type is ``int``. 2101Otherwise, a :index:`compile-time error` occurs. 2102 2103If the chaining operator '``?.``' (see :ref:`Chaining Operator`) is present, 2104and after its application the type of *object reference expression* is an array 2105type ``T[]``, then it makes a valid *array reference expression*, and the type 2106of the array indexing expression is ``T``. 2107 2108The result of an array indexing expression is a variable of type ``T`` (i.e., an 2109element of the array selected by the value of that *index expression*). 2110 2111It is essential that, if type ``T`` is a reference type, then the fields of 2112array elements can be modified by changing the resultant variable fields: 2113 2114.. index:: 2115 array indexing 2116 index expression 2117 numeric type 2118 array element 2119 floating-point type 2120 runtime error 2121 object reference expression 2122 chaining operator 2123 array type 2124 conversion 2125 predefined numeric type 2126 compile-time error 2127 variable field 2128 reference expression 2129 reference type 2130 array 2131 2132.. code-block:: typescript 2133 :linenos: 2134 2135 let names: string[] = ["Alice", "Bob", "Carol"] 2136 console.log(name[1]) // prints Bob 2137 string[1] = "Martin" 2138 console.log(name[1]) // prints Martin 2139 2140 class RefType { 2141 field: number = 666 2142 } 2143 const objects: RefType[] = [new RefType(), new RefType()] 2144 const object = objects [1] 2145 object.field = 777 // change the field in the array element 2146 console.log(objects[0].filed) // prints 666 2147 console.log(objects[1].filed) // prints 777 2148 2149 let an_array = [1, 2, 3] 2150 let element = an_array [3.5] // Compile-time error 2151 function foo (index: number) { 2152 let element = an_array [index] 2153 // Runtime-time error if index is not integer 2154 } 2155 2156An array indexing expression evaluated at runtime behaves as follows: 2157 2158- The object reference expression is evaluated first. 2159- If the evaluation completes abruptly, then so does the indexing 2160 expression, and the index expression is not evaluated. 2161- If the evaluation completes normally, then the index expression is evaluated. 2162 The resultant value of the object reference expression refers to an array. 2163- If the index expression value of an array is less than zero, greater than 2164 or equal to that array’s *length*, then the ``ArrayIndexOutOfBoundsError`` 2165 is thrown. 2166- Otherwise, the result of the array access is a type ``T`` variable within 2167 the array selected by the value of the index expression. 2168 2169.. code-block:: typescript 2170 :linenos: 2171 2172 function setElement(names: string[], i: number, name: string) { 2173 names[i] = name // run-time error, if 'i' is out of bounds 2174 } 2175 2176.. index:: 2177 array 2178 indexing expression 2179 index expression 2180 evaluation 2181 object reference expression 2182 abrupt completion 2183 normal completion 2184 reference expression 2185 error 2186 variable 2187 2188| 2189 2190.. _Record Indexing Expression: 2191 2192Record Indexing Expression 2193========================== 2194 2195.. meta: 2196 frontend_status: Done 2197 2198For a ``Record<Key, Value>`` indexing (see :ref:`Record Utility Type`), 2199the *index expression* must be of type ``Key``. 2200 2201The following two cases are to be considered separately: 2202 22031. Type ``Key`` is a union that contains literal types only; 22042. Other cases. 2205 2206**Case 1.** If type ``Key`` is a union that contains literal types only, then 2207the *index expression* can only be one of the literals listed in the type. 2208The result of an indexing expression is of type ``Value``. 2209 2210.. code-block-meta: 2211 2212 2213.. code-block:: typescript 2214 :linenos: 2215 2216 type Keys = 'key1' | 'key2' | 'key3' 2217 2218 let x: Record<Keys, number> = { 2219 'key1': 1, 2220 'key2': 2, 2221 'key3': 4, 2222 } 2223 let y = x['key2'] // y value is 2 2224 2225.. index:: 2226 index expression 2227 key 2228 union 2229 literal type 2230 literal 2231 value 2232 type 2233 2234A :index:`compile-time error` occurs if an index expression is not a valid 2235literal: 2236 2237.. code-block:: typescript 2238 :linenos: 2239 2240 console.log(x['key4']) // compile-time error 2241 x['another key'] = 5 // compile-time error 2242 2243For this type ``Key``, the compiler guarantees that an object of 2244``Record<Key, Value>`` contains values for all ``Key`` keys. 2245 2246**Case 2.** There is no restriction on an *index expression*. 2247The result of an indexing expression is of type ``Value | undefined``. 2248 2249.. code-block-meta: 2250 2251.. code-block:: typescript 2252 :linenos: 2253 2254 let x: Record<number, string> = { 2255 1: "hello", 2256 2: "buy", 2257 } 2258 2259 function foo(n: number): string | undefined { 2260 return x[n] 2261 } 2262 2263 function bar(n: number): string { 2264 let s = x[n] 2265 if (s == undefined) { return "no" } 2266 return s! 2267 } 2268 2269 foo(3) // prints "undefined" 2270 bar(3) // prints "no" 2271 2272 let y = x[3] 2273 2274.. index:: 2275 index expression 2276 literal 2277 key 2278 compiler 2279 value 2280 indexing expression 2281 2282In the code above, the type of *y* is ``string | undefined``, and the value of 2283*y* is ``undefined``. 2284 2285An indexing expression evaluated at runtime behaves as follows: 2286 2287- The object reference expression is evaluated first. 2288- If the evaluation completes abruptly, then so does the indexing 2289 expression, and the index expression is not evaluated. 2290- If the evaluation completes normally, then the index expression is 2291 evaluated. 2292 The resultant value of the object reference expression refers to a ``record`` 2293 instance. 2294- If the ``record`` instance contains a key defined by the index expression, 2295 then the result is the value mapped to the key. 2296- Otherwise, the result is the literal ``undefined``. 2297 2298.. index:: 2299 type 2300 value 2301 reference type 2302 key 2303 indexing expression 2304 index expression 2305 object reference expression 2306 abrupt completion 2307 normal completion 2308 literal 2309 record instance 2310 2311| 2312 2313.. _Chaining Operator: 2314 2315Chaining Operator 2316***************** 2317 2318.. meta: 2319 frontend_status: Done 2320 2321The *chaining operator* '``?.``' is used to effectively access values of 2322nullish types. It can be used in the following contexts: 2323 2324- :ref:`Field Access Expression`, 2325- :ref:`Method Call Expression`, 2326- :ref:`Function Call Expression`, 2327- :ref:`Indexing Expressions`. 2328 2329If the value of the expression to the left of '``?.``' is ``undefined`` or 2330``null``, then the evaluation of the entire surrounding *primary expression* 2331stops. The result of the entire primary expression is then ``undefined``. Thus 2332the type of the entire primary expression is the union ``undefined`` | 2333*the non-nullish type of the entire primary expression*. 2334 2335.. code-block-meta: 2336 2337.. code-block:: typescript 2338 :linenos: 2339 2340 class Person { 2341 name: string 2342 spouse?: Person = undefined 2343 constructor(name: string) { 2344 this.name = name 2345 } 2346 } 2347 2348 let bob = new Person("Bob") 2349 console.log(bob.spouse?.name) // prints "undefined" 2350 // the type of bob.spouse?.name is undefined|string 2351 2352 bob.spouse = new Person("Alice") 2353 console.log(bob.spouse?.name) // prints "Alice" 2354 // the type of bob.spouse?.name is undefined|string 2355 2356If an expression is not of a nullish type, then the chaining operator has 2357no effect. 2358 2359A :index:`compile-time error` occurs if a chaining operator is placed in the 2360context where a variable is expected, e.g., in the left-hand-side expression of 2361an assignment (see :ref:`Assignment`) or expression 2362(see :ref:`Postfix Increment`, :ref:`Postfix Decrement`, 2363:ref:`Prefix Increment` or :ref:`Prefix Decrement`). 2364 2365.. index:: 2366 expression 2367 evaluation 2368 nullish value 2369 nullish type 2370 function call 2371 method call 2372 primary expression 2373 evaluation 2374 chaining operator 2375 access 2376 value 2377 field access expression 2378 2379| 2380 2381.. _New Expressions: 2382 2383``New`` Expressions 2384******************* 2385 2386.. meta: 2387 frontend_status: Done 2388 2389The operation ``new`` instantiates an object of type ``class`` or ``array``: 2390 2391.. code-block:: abnf 2392 2393 newExpression: 2394 newClassInstance 2395 | newArrayInstance 2396 ; 2397 2398A *class instance creation expression* creates new object that is an instance 2399of the specified class described in full detail below. 2400 2401The creation of array instances is an experimental feature discussed in 2402:ref:`Array Creation Expressions`. 2403 2404.. index:: 2405 expression 2406 instantiation 2407 class instance creation expression 2408 class 2409 array 2410 object 2411 instance 2412 creation 2413 array instance 2414 array creation expression 2415 2416.. code-block:: abnf 2417 2418 newClassInstance: 2419 'new' typeArguments? typeReference arguments? 2420 ; 2421 2422A *class instance creation expression* specifies a class to be instantiated. 2423It optionally lists all actual arguments for the constructor. 2424 2425A *class instance creation expression* can throw an error or 2426an exception (see :ref:`Error Handling`, :ref:`Constructor Declaration`). 2427 2428 2429The execution of a class instance creation expression is performed as follows: 2430 2431- A new instance of the class is created; 2432- The constructor of the class is called to fully initialize the created 2433 instance. 2434 2435The validity of the constructor call is similar to the validity of the method 2436call as discussed in :ref:`Step 2 Selection of Method`, except the cases 2437discussed in the :ref:`Constructor Body` section. 2438 2439A :index:`compile-time error` occurs if ``typeReference`` is a type parameter. 2440 2441.. index:: 2442 class instance creation expression 2443 instantiation 2444 argument 2445 constructor 2446 instance creation expression 2447 instance 2448 error 2449 expression 2450 standalone expression 2451 assignment context 2452 call context 2453 class instance 2454 constructor 2455 method validity 2456 semantic correctness check 2457 type parameter 2458 2459| 2460 2461.. _Cast Expressions: 2462 2463``Cast`` Expressions 2464******************** 2465 2466.. meta: 2467 frontend_status: Done 2468 2469*Cast expressions* apply *cast operator* ``as`` to some *expression* by 2470issuing a value of the specified ``type``. 2471 2472.. code-block:: abnf 2473 2474 castExpression: 2475 expression 'as' type 2476 ; 2477 2478.. code-block:: typescript 2479 :linenos: 2480 2481 class X {} 2482 2483 let x1 : X = new X() 2484 let ob : Object = x1 as Object 2485 let x2 : X = ob as X 2486 2487The cast operator converts the value *V* of one type (as denoted by the 2488expression) at runtime to a value of another type. 2489 2490The cast expression introduces the target type for the casting context (see 2491:ref:`Casting Contexts and Conversions`). The target type can be either ``type`` 2492or ``typeReference``. 2493 2494.. index:: 2495 cast operator 2496 cast expression 2497 expression 2498 conversion 2499 value 2500 runtime 2501 casting context 2502 type 2503 2504A cast expression type is always the target type. 2505 2506The result of a cast expression is a value, not a variable (even if the operand 2507expression is a variable). 2508 2509The casting conversion (see :ref:`Casting Contexts and Conversions`) converts 2510the operand value at runtime to the target type specified by the cast operator 2511(if needed). 2512 2513A :index:`compile-time error` occurs if the casting conversion cannot convert 2514the compile-time type of the operand to the target type specified by the cast 2515operator. 2516 2517If the ``as`` cast cannot be performed during program execution, then 2518``ClassCastError`` is thrown. 2519 2520.. index:: 2521 cast expression 2522 target type 2523 value 2524 variable 2525 operand expression 2526 variable 2527 casting conversion 2528 operand value 2529 compile-time type 2530 cast operator 2531 execution 2532 error 2533 2534| 2535 2536.. _InstanceOf Expression: 2537 2538``InstanceOf`` Expression 2539************************* 2540 2541.. meta: 2542 frontend_status: Done 2543 2544.. code-block:: abnf 2545 2546 instanceOfExpression: 2547 expression 'instanceof' type 2548 ; 2549 2550Any ``instanceof`` expression is of type ``boolean``. 2551 2552The expression operand of the operator ``instanceof`` must be of a reference 2553type. Otherwise, a :index:`compile-time error` occurs. 2554 2555A :index:`compile-time error` occurs if ``type`` operand of the operator 2556``instanceof`` is one of the following: 2557 2558 - Type parameter (see :ref:`Type Parameters`), 2559 - Primitive type (see :ref:`Primitive Types`), 2560 - Union type that contains type parameter after normalization 2561 (see :ref:`Union Types Normalization`), 2562 - *Generic type* (see :ref:`Generics`)---this temporary limitation 2563 is expected to be removed in the future (see 2564 :ref:`Generic and function types peculiarities`). 2565 2566If the type of ``expression`` at compile time is compatible with ``type`` (see 2567:ref:`Type Compatibility`), then the result of the ``instanceof`` expression 2568is ``true``. 2569 2570Otherwise, an ``instanceof`` expression checks during program execution 2571whether the type of the value the ``expression`` successfully evaluates to is 2572compatible with ``type`` (see :ref:`Type Compatibility`). 2573If so, then the result of the ``instanceof`` expression is ``true``. 2574Otherwise, the result is ``false``. 2575 2576If the expression evaluation causes exception or error, then 2577execution control is transferred to a proper ``catch`` section or runtime 2578system, and the result of the ``instanceof`` expression cannot be determined. 2579 2580.. index:: 2581 instanceof expression 2582 expression 2583 operand 2584 reference type 2585 compatibility 2586 compile-time error 2587 execution 2588 evaluation 2589 compatible type 2590 catch section 2591 runtime 2592 control transfer 2593 execution control 2594 boolean type 2595 exception 2596 error 2597 primitive type 2598 generic type 2599 catch 2600 runtime 2601 2602| 2603 2604.. _TypeOf Expression: 2605 2606``TypeOf`` Expression 2607********************* 2608 2609.. meta: 2610 frontend_status: Done 2611 2612.. code-block:: abnf 2613 2614 typeOfExpression: 2615 'typeof' expression 2616 ; 2617 2618Any ``typeof`` expression is of type ``string``. Its evaluation starts with 2619``expression`` evaluation. If such evaluation causes exception or error, then 2620the result of the ``typeof`` expression cannot be determined in that case 2621otherwise the ``typeof`` expression value is defined like this 2622 2623- for the below types it is known at compile time: 2624 2625 2626.. index:: 2627 typeof expression 2628 string 2629 evaluation 2630 exception 2631 error 2632 compile time 2633 2634+---------------------------------+-------------------------+-----------------------------+ 2635| **Type of Expression** | **Resulting String** | **Code Example** | 2636+=================================+=========================+=============================+ 2637| ``number``/``Number`` | "number" | .. code-block:: typescript | 2638| | | | 2639| | | let n: number = ... | 2640| | | typeof n | 2641| | | let N: Number = ... | 2642| | | typeof N | 2643+---------------------------------+-------------------------+-----------------------------+ 2644| ``string``/``String`` | "string" | .. code-block:: typescript | 2645| | | | 2646| | | let s: string = ... | 2647| | | typeof s | 2648+---------------------------------+-------------------------+-----------------------------+ 2649| ``boolean``/``Boolean`` | "boolean" | .. code-block:: typescript | 2650| | | | 2651| | | let b: boolean = ... | 2652| | | typeof b | 2653| | | let B: Boolean = ... | 2654| | | typeof B | 2655+---------------------------------+-------------------------+-----------------------------+ 2656| ``bigint``/``BigInt`` | "bigint" | .. code-block:: typescript | 2657| | | | 2658| | | let b: bigint = ... | 2659| | | typeof b | 2660| | | let B: BigInt = ... | 2661| | | typeof B | 2662+---------------------------------+-------------------------+-----------------------------+ 2663| any class or interface | "object" | .. code-block:: typescript | 2664| | | | 2665| | | let a: Object = ... | 2666| | | typeof a | 2667+---------------------------------+-------------------------+-----------------------------+ 2668| any function type | "function" | .. code-block:: typescript | 2669| | | | 2670| | | let f: () => void = ... | 2671| | | typeof f | 2672+---------------------------------+-------------------------+-----------------------------+ 2673| ``undefined`` | "undefined" | .. code-block:: typescript | 2674| | | | 2675| | | typeof undefined | 2676+---------------------------------+-------------------------+-----------------------------+ 2677| ``null`` | "object" | .. code-block:: typescript | 2678| | | | 2679| | | typeof null | 2680+---------------------------------+-------------------------+-----------------------------+ 2681 2682(table cont'd) 2683 2684+---------------------------------+-------------------------+-----------------------------+ 2685| **Type of Expression** | **Resulting String** | **Code Example** | 2686+=================================+=========================+=============================+ 2687| ``T|null``, when ``T`` is a | "object" | .. code-block:: typescript | 2688| class (but not Object - | | | 2689| see next table), | | class C {} | 2690| interface or array | | let x: C | null = ... | 2691| | | typeof x | 2692+---------------------------------+-------------------------+-----------------------------+ 2693| ``enum`` | "number" or "string", | .. code-block:: typescript | 2694| | depending of constant | | 2695| | type | enum C {R, G, B} | 2696| | | let c: C = ... | 2697| | | typeof c | 2698+---------------------------------+-------------------------+-----------------------------+ 2699| All high-performance numeric | "number" | .. code-block:: typescript | 2700| value types and their boxed | | | 2701| versions: | | let x: byte = ... | 2702| ``byte``, ``short``, ``int``, | | typeof x | 2703| ``long``, ``float``, ``double``,| | ... | 2704| ``Byte``, ``Short``, ``Int``, | | | 2705| ``long``, ``Long``, ``Float``, | | | 2706| ``Double``, ``char``, ``Char`` | | | 2707+---------------------------------+-------------------------+-----------------------------+ 2708 2709- for all other types is evaluated during program execution: 2710 2711+------------------------+-----------------------------+ 2712| **Type of Expression** | **Code Example** | 2713+========================+=============================+ 2714| Object | .. code-block:: typescript | 2715| | | 2716| | function f(o: Object) { | 2717| | typeof o | 2718| | } | 2719+------------------------+-----------------------------+ 2720| union type | .. code-block:: typescript | 2721| | | 2722| | function f(p:A|B) { | 2723| | typeof p | 2724| | } | 2725+------------------------+-----------------------------+ 2726| type parameter | .. code-block:: typescript | 2727| | | 2728| | class A<T|null|undefined> {| 2729| | f: T | 2730| | m() { | 2731| | typeof this.f | 2732| | } | 2733| | constructor(p:T) { | 2734| | this.f = p | 2735| | } | 2736| | } | 2737+------------------------+-----------------------------+ 2738 2739| 2740 2741.. _Ensure-Not-Nullish Expressions: 2742 2743Ensure-Not-Nullish Expression 2744***************************** 2745 2746.. meta: 2747 frontend_status: Done 2748 2749.. code-block:: abnf 2750 2751 ensureNotNullishExpression: 2752 expression '!' 2753 ; 2754 2755An *ensure-not-nullish expression* is a postfix expression with the operator 2756'``!``'. An *ensure-not-nullish expression* in the expression *e!* checks 2757whether *e* of a nullish type (see :ref:`Nullish Types`) evaluates to a 2758nullish value. 2759 2760If the expression *e* is not of a nullish type, then the operator '``!``' 2761has no effect. 2762 2763If the result of the evaluation of *e* is not equal to ``null`` or ``undefined``, 2764then the result of *e!* is the outcome of the evaluation of *e*. 2765 2766If the result of the evaluation of *e* is equal to ``null`` or ``undefined``, 2767then ``NullPointerError`` is thrown. 2768 2769The type of *ensure-not-nullish* expression is the non-nullish variant of the 2770type of *e*. 2771 2772.. index:: 2773 ensure-not-nullish expression 2774 postfix expression 2775 prefix expression 2776 expression 2777 operator 2778 nullish type 2779 evaluation 2780 non-nullish variant 2781 nullish value 2782 null 2783 undefined 2784 error 2785 compile-time error 2786 undefined 2787 2788| 2789 2790.. _Nullish-Coalescing Expression: 2791 2792Nullish-Coalescing Expression 2793***************************** 2794 2795.. meta: 2796 frontend_status: Done 2797 2798.. code-block:: abnf 2799 2800 nullishCoalescingExpression: 2801 expression '??' expression 2802 ; 2803 2804A *nullish-coalescing expression* is a binary expression that uses the operator 2805'``??``', and checks whether the evaluation of the left-hand-side expression 2806equals the *nullish* value: 2807 2808- If so, then the right-hand-side expression evaluation is the result 2809 of a nullish-coalescing expression. 2810- If not so, then the left-hand-side expression evaluation result is 2811 the result of a nullish-coalescing expression, and the right-hand-side 2812 expression is not evaluated (the operator '``??``' is thus *lazy*). 2813 2814.. index:: 2815 nullish-coalescing expression 2816 binary expression 2817 operator 2818 evaluation 2819 expression 2820 nullish value 2821 lazy operator 2822 2823If the left-hand-side expression is not of a nullish type, then the type of 2824a nullish-coalescing expression is the type of this expression. Otherwise, 2825the type of a nullish-coalescing expression is a normalized *union type* 2826(see :ref:`Union Types`) formed from the following: 2827 2828- Non-nullish variant of the type of the left-hand-side expression; and 2829- Type of the right-hand-side expression. 2830 2831The semantics of a nullish-coalescing expression is represented in the 2832following example: 2833 2834.. code-block:: typescript 2835 :linenos: 2836 2837 let x = expression1 ?? expression2 2838 2839 let x$ = expression1 2840 if (x$ == null) {x = expression2} else x = x$! 2841 2842 // Type of x is NonNullishType(expression1)|Type(expression2) 2843 2844 2845A :index:`compile-time error` occurs if the nullish-coalescing operator is 2846mixed with conditional-and or conditional-or operators without parentheses. 2847 2848.. index:: 2849 compile-time error 2850 reference type 2851 nullish-coalescing expression 2852 non-nullish type 2853 expression 2854 nullish-coalescing operator 2855 conditional-and operator 2856 conditional-or operator 2857 union type 2858 2859| 2860 2861.. _Unary Expressions: 2862 2863Unary Expressions 2864***************** 2865 2866.. meta: 2867 frontend_status: Done 2868 2869.. code-block:: abnf 2870 2871 unaryExpression: 2872 expression '++' 2873 | expression '––' 2874 | '++' expression 2875 | '––' expression 2876 | '+' expression 2877 | '–' expression 2878 | '~' expression 2879 | '!' expression 2880 ; 2881 2882All expressions with unary operators (except postfix increment and postfix 2883decrement operators) group right-to-left for '``~+x``' to have the same meaning 2884as '``~(+x)``'. 2885 2886.. index:: 2887 unary expression 2888 expression 2889 unary operator 2890 postfix 2891 postfix 2892 increment operator 2893 decrement operator 2894 2895| 2896 2897.. _Postfix Increment: 2898 2899Postfix Increment 2900================= 2901 2902.. meta: 2903 frontend_status: Done 2904 2905A *postfix increment expression* is an expression followed by the increment 2906operator '``++``'. 2907 2908A :index:`compile-time error` occurs if the type of the variable resultant from 2909the *expression* is not convertible (see :ref:`Implicit Conversions`) to a 2910numeric type. 2911 2912The type of a postfix increment expression is the type of the variable. The 2913result of a postfix increment expression is a value, not a variable. 2914 2915If the evaluation of the operand expression completes normally at runtime, then: 2916 2917- The value *1* is added to the value of the variable by using necessary 2918 conversions (see :ref:`Primitive Types Conversions`); and 2919- The sum is stored back into the variable. 2920 2921.. index:: 2922 postfix expression 2923 increment expression 2924 increment operator 2925 expression 2926 conversion 2927 variable 2928 compile-time error 2929 convertible expression 2930 value 2931 operand 2932 normal completion 2933 runtime 2934 2935 2936Otherwise, the postfix increment expression completes abruptly, and no 2937incrementation occurs. 2938 2939The value of the postfix increment expression is the value of the variable 2940*before* the new value is stored. 2941 2942.. index:: 2943 variable 2944 conversion 2945 predefined numeric types conversion 2946 postfix expression 2947 increment expression 2948 abrupt completion 2949 expression 2950 variable 2951 postfix increment expression 2952 incrementation 2953 2954| 2955 2956.. _Postfix Decrement: 2957 2958Postfix Decrement 2959================= 2960 2961.. meta: 2962 frontend_status: Done 2963 todo: let a : Double = Double.Nan; a++; a--; ++a; --a; (assertion) 2964 2965A *postfix decrement expression* is an expression followed by the decrement 2966operator '``--``'. 2967 2968A :index:`compile-time error` occurs if the type of the variable resultant from 2969the *expression* is not convertible (see :ref:`Implicit Conversions`) to a 2970numeric type. 2971 2972The type of a postfix decrement expression is the type of the variable. The 2973result of a postfix decrement expression is a value, not a variable. 2974 2975If evaluation of the operand expression completes at runtime, then: 2976 2977.. index:: 2978 postfix expression 2979 decrement expression 2980 decrement operator 2981 postfix expression 2982 compile-time error 2983 variable 2984 expression 2985 conversion 2986 runtime 2987 operand 2988 completion 2989 evaluation 2990 2991- The value *1* is subtracted from the value of the variable by using 2992 necessary conversions (see :ref:`Primitive Types Conversions`); and 2993- The sum is stored back into the variable. 2994 2995Otherwise, the postfix decrement expression completes abruptly, and 2996no decrementation occurs. 2997 2998The value of the postfix decrement expression is the value of the variable 2999*before* the new value is stored. 3000 3001.. index:: 3002 subtraction 3003 value 3004 variable 3005 conversion 3006 abrupt completion 3007 predefined numeric types conversion 3008 abrupt completion 3009 decrementation 3010 postfix expression 3011 decrement expression 3012 postfix 3013 variable 3014 value 3015 3016| 3017 3018.. _Prefix Increment: 3019 3020Prefix Increment 3021================ 3022 3023.. meta: 3024 frontend_status: Done 3025 3026A *prefix increment expression* is an expression preceded by the operator 3027'``++``'. 3028 3029A :index:`compile-time error` occurs if the type of the variable resultant from 3030the *expression* is not convertible (see :ref:`Implicit Conversions`) to a 3031numeric type. 3032 3033The type of a prefix increment expression is the type of the variable. The 3034result of a prefix increment expression is a value, not a variable. 3035 3036If evaluation of the operand expression completes normally at runtime, then: 3037 3038.. index:: 3039 prefix operator 3040 increment operator 3041 prefix expression 3042 increment expression 3043 expression 3044 prefix expression 3045 evaluation 3046 variable 3047 runtime 3048 expression 3049 normal completion 3050 conversion 3051 3052- The value *1* is added to the value of the variable by using necessary 3053 conversions (see :ref:`Primitive Types Conversions`); and 3054- The sum is stored back into the variable. 3055 3056Otherwise, the prefix increment expression completes abruptly, and no 3057incrementation occurs. 3058 3059The value of the prefix increment expression is the value of the variable 3060*before* the new value is stored. 3061 3062.. index:: 3063 value 3064 variable 3065 conversion 3066 predefined type 3067 numeric type 3068 conversion 3069 numeric type 3070 abrupt completion 3071 prefix expression 3072 increment expression 3073 3074| 3075 3076.. _Prefix Decrement: 3077 3078Prefix Decrement 3079================ 3080 3081.. meta: 3082 frontend_status: Done 3083 3084A *prefix decrement expression* is an expression preceded by the operator 3085'``--``'. 3086 3087A :index:`compile-time error` occurs if the type of the variable resultant from 3088the *expression* is not convertible (see :ref:`Implicit Conversions`) to a 3089numeric type. 3090 3091The type of a prefix decrement expression is the type of the variable. The 3092result of a prefix decrement expression is a value, not a variable. 3093 3094.. index:: 3095 prefix operator 3096 decrement operator 3097 prefix expression 3098 decrement expression 3099 expression 3100 decrement operator 3101 operator 3102 variable 3103 expression 3104 value 3105 3106If evaluation of the operand expression completes normally at runtime, then: 3107 3108- The value *1* is subtracted from the value of the variable by using 3109 necessary conversions (see :ref:`Primitive Types Conversions`); and 3110- The sum is stored back into the variable. 3111 3112Otherwise, the prefix decrement expression completes abruptly, and no 3113decrementation occurs. The value of the prefix decrement expression remains 3114the value of the variable *before* a new value is stored. 3115 3116.. index:: 3117 evaluation 3118 runtime 3119 expression 3120 conversion 3121 operand 3122 normal completion 3123 predefined numeric types conversion 3124 numeric type 3125 decrement 3126 abrupt completion 3127 variable 3128 prefix expression 3129 decrement 3130 expression 3131 prefix decrement expression 3132 3133| 3134 3135.. _Unary Plus: 3136 3137Unary Plus 3138========== 3139 3140.. meta: 3141 frontend_status: Done 3142 3143A *unary plus expression* is an expression preceded by the operator '``+``'. 3144 3145The type of the operand *expression* with the unary operator '``+``' must 3146be convertible (see :ref:`Implicit Conversions`) to a numeric type. Otherwise, 3147a :index:`compile-time error` occurs. 3148 3149The numeric types conversion (see :ref:`Primitive Types Conversions`) is 3150performed on the operand to ensure that the resultant type is that of the 3151unary plus expression. The result of a unary plus expression is always a value, 3152not a variable (even if the result of the operand expression is a variable). 3153 3154.. index:: 3155 unary plus operator 3156 operand 3157 expression 3158 unary operator 3159 conversion 3160 numeric type 3161 compile-time error 3162 numeric types conversion 3163 predefined numeric types conversion 3164 unary plus expression 3165 expression 3166 operator 3167 value 3168 variable 3169 operand expression 3170 3171| 3172 3173.. _Unary Minus: 3174 3175Unary Minus 3176=========== 3177 3178.. meta: 3179 frontend_status: Done 3180 todo: let a : Double = Double.Nan; a = -a; (assertion) 3181 3182A *unary minus expression* is an expression preceded by the operator '``-``'. 3183 3184The type of the operand *expression* with the unary operator '``-``' must 3185be convertible (see :ref:`Implicit Conversions`) to a numeric type. Otherwise, 3186a :index:`compile-time error` occurs. 3187 3188The numeric types conversion (see :ref:`Primitive Types Conversions`) 3189is performed on the operand to ensure that the resultant type is that of the 3190unary minus expression. 3191The result of a unary minus expression is a value, not a variable (even if the 3192result of the operand expression is a variable). 3193 3194A unary numeric promotion performs the value set conversion (see 3195:ref:`Implicit Conversions`). 3196 3197The unary negation operation is always performed on, and its result is drawn 3198from the same value set as the promoted operand value. 3199 3200.. index:: 3201 unary minus operation 3202 operand 3203 unary operator 3204 conversion 3205 numeric type 3206 predefined numeric type 3207 numeric types conversion 3208 expression 3209 operand 3210 normal completion 3211 value 3212 variable 3213 conversion 3214 unary numeric promotion 3215 value set conversion 3216 unary negation operation 3217 promoted operand value 3218 3219Further value set conversions are then performed on that same result. 3220 3221The value of a unary minus expression at runtime is the arithmetic negation 3222of the promoted value of the operand. 3223 3224The negation of integer values is the same as subtraction from zero. The |LANG| 3225programming language uses two’s-complement representation for integers. The 3226range of two’s-complement value is not symmetric. The same maximum negative 3227number results from the negation of the maximum negative *int* or *long*. 3228In that case, an overflow occurs but throws no exception or error. 3229For any integer value *x*, *-x* is equal to *(~x)+1*. 3230 3231The negation of floating-point values is *not* the same as subtraction from 3232zero (if *x* is *+0.0*, then *0.0-x* is *+0.0*, however *-x* is *-0.0*). 3233 3234A unary minus merely inverts the sign of a floating-point number. Special 3235cases to consider are as follows: 3236 3237- The operand ``NaN`` results in ``NaN`` (``NaN`` has no sign). 3238- The operand infinity results in the infinity of the opposite sign. 3239- The operand zero results in zero of the opposite sign. 3240 3241.. index:: 3242 value set conversion 3243 conversion 3244 unary minus expression 3245 runtime 3246 negation 3247 promoted value 3248 operand 3249 operation 3250 integer 3251 value 3252 subtraction 3253 two’s-complement representation 3254 two’s-complement value 3255 overflow 3256 exception 3257 error 3258 floating-point value 3259 subtraction 3260 unary minus 3261 floating-point number 3262 infinity 3263 NaN 3264 3265| 3266 3267.. _Bitwise Complement: 3268 3269Bitwise Complement 3270================== 3271 3272.. meta: 3273 frontend_status: Done 3274 3275A *bitwise complement expression* is an expression preceded by the operator '``~``'. 3276 3277The type of the operand *expression* with the unary operator '``~``' must be 3278convertible (see :ref:`Implicit Conversions`) to a primitive integer type. 3279Otherwise, a :index:`compile-time error` occurs. 3280 3281The numeric types conversion (see :ref:`Primitive Types Conversions`) 3282is performed on the operand to ensure that the resultant type is that of the 3283unary bitwise complement expression. 3284 3285The result of a unary bitwise complement expression is a value, not a variable 3286(even if the result of the operand expression is a variable). 3287 3288The value of a unary bitwise complement expression at runtime is the bitwise 3289complement of the promoted value of the operand. In all cases, *~x* equals 3290*(-x)-1*. 3291 3292.. index:: 3293 bitwise complement expression 3294 numeric type 3295 operator 3296 complement operator 3297 expression 3298 operand 3299 unary operator 3300 conversion 3301 primitive type 3302 integer type 3303 unary bitwise complement expression 3304 variable 3305 runtime 3306 promoted value 3307 3308| 3309 3310.. _Logical Complement: 3311 3312Logical Complement 3313================== 3314 3315.. meta: 3316 frontend_status: Done 3317 3318A *logical complement expression* is an expression preceded by the operator 3319'``!``'. 3320 3321The type of the operand *expression* with the unary '``!``' operator must be 3322``boolean`` or ``Boolean``. Otherwise, a :index:`compile-time error` occurs. 3323See :ref:`Extended Conditional Expressions` for extended semantics. 3324 3325The unary logical complement expression’s type is ``boolean``. 3326 3327The unboxing conversion (see :ref:`Unboxing Conversions`) is 3328performed on the operand at runtime if needed. 3329 3330The value of a unary logical complement expression is ``true`` if the (possibly 3331converted) operand value is ``false``, and ``false`` if the operand value 3332(possibly converted) is ``true``. 3333 3334.. index:: 3335 logical complement operator 3336 expression 3337 operand 3338 operator 3339 unary operator 3340 boolean type 3341 Boolean type 3342 compile-time error 3343 unary logical complement expression 3344 unboxing conversion 3345 boxing conversion 3346 predefined numeric types conversion 3347 numeric type 3348 3349| 3350 3351.. _Multiplicative Expressions: 3352 3353Multiplicative Expressions 3354************************** 3355 3356.. meta: 3357 frontend_status: Done 3358 3359 3360Multiplicative expressions use *multiplicative operators* '``*``', '``/``', 3361and '``%``': 3362 3363.. code-block:: abnf 3364 3365 multiplicativeExpression: 3366 expression '*' expression 3367 | expression '/' expression 3368 | expression '%' expression 3369 ; 3370 3371The multiplicative operators group left-to-right. 3372 3373The type of each operand in a multiplicative operator must be convertible (see 3374:ref:`Contexts and Conversions`) to a numeric type. Otherwise, a 3375:index:`compile-time error` occurs. 3376 3377The numeric types conversion (see :ref:`Primitive Types Conversions`) 3378is performed on both operands to ensure that the resultant type is the type of 3379the multiplicative expression. 3380 3381The result of a unary bitwise complement expression is a value, not a 3382variable (even if the operand expression is a variable). 3383 3384.. index:: 3385 multiplicative expression 3386 conversion 3387 convertibility 3388 context 3389 conversion 3390 numeric type 3391 multiplicative operator 3392 multiplicative expression 3393 numeric type 3394 value 3395 unary bitwise complement expression 3396 operand expression 3397 variable 3398 predefined numeric types conversion 3399 multiplicative operator 3400 operand expression 3401 3402| 3403 3404.. _Multiplication: 3405 3406Multiplication 3407============== 3408 3409.. meta: 3410 frontend_status: Done 3411 todo: If either operand is NaN, the result should be NaN, but result is -NaN 3412 todo: Multiplication of an infinity by a zero should be NaN, but result is - NaN 3413 3414The binary operator '``*``' performs multiplication, and returns the product of 3415its operands. 3416 3417Multiplication is a commutative operation if operand expressions have no 3418side effects. 3419 3420Integer multiplication is associative when all operands are of the same type. 3421 3422Floating-point multiplication is not associative. 3423 3424If overflow occurs during integer multiplication, then: 3425 3426- The result is the low-order bits of the mathematical product as represented 3427 in some sufficiently large two’s-complement format. 3428- The sign of the result can be other than the sign of the mathematical 3429 product of the two operand values. 3430 3431 3432A floating-point multiplication result is determined in compliance with the 3433IEEE 754 arithmetic: 3434 3435.. index:: 3436 multiplication operator 3437 binary operator 3438 multiplication 3439 operand 3440 commutative operation 3441 expression 3442 side effect 3443 integer multiplication 3444 associativity 3445 two’s-complement format 3446 floating-type multiplication 3447 operand value 3448 IEEE 754 3449 3450- The result is ``NaN`` if: 3451 3452 - Either operand is ``NaN``; 3453 - Infinity is multiplied by zero. 3454 3455 3456- If the result is not ``NaN``, then the sign of the result is as follows: 3457 3458 - Positive, where both operands have the same sign; and 3459 - Negative, where the operands have different signs. 3460 3461 3462- If infinity is multiplied by a finite value, then the multiplication results 3463 in a signed infinity (the sign is determined by the rule above). 3464- If neither ``NaN`` nor infinity is involved, then the exact mathematical product 3465 is computed. 3466 3467 The product is rounded to the nearest value in the chosen value set by 3468 using the IEEE 754 *round-to-nearest* mode. The |LANG| programming 3469 language requires gradual underflow support as defined by IEEE 754 3470 (see :ref:`Floating-Point Types and Operations`). 3471 3472 If the magnitude of the product is too large to represent, then the 3473 operation overflows, and the result is an appropriately signed infinity. 3474 3475 3476The evaluation of a multiplication operator '``*``' never throws an error 3477despite possible overflow, underflow, or loss of information. 3478 3479.. index:: 3480 NaN 3481 infinity 3482 operand 3483 finite value 3484 multiplication 3485 signed infinity 3486 round-to-nearest 3487 rounding 3488 underflow 3489 floating-point type 3490 floating-point operation 3491 overflow 3492 evaluation 3493 multiplication operator 3494 error 3495 loss of information 3496 IEEE 754 3497 rounding 3498 3499| 3500 3501.. _Division: 3502 3503Division 3504======== 3505 3506.. meta: 3507 frontend_status: Done 3508 todo: If either operand is NaN, the result should be NaN, but result is -NaN 3509 todo: Division of infinity by infinity should be NaN, but result is - NaN 3510 todo: Division of a nonzero finite value by a zero results should be signed infinity, but "Floating point exception(core dumped)" occurs 3511 3512The binary operator '``/``' performs division and returns the quotient of its 3513left-hand and right-hand operands (``dividend`` and ``divisor`` respectively). 3514 3515Integer division rounds toward *0*, i.e., the quotient of integer operands 3516*n* and *d*, after a numeric types conversion on both (see 3517:ref:`Primitive Types Conversions` for details), is 3518an integer value *q* with the largest possible magnitude that 3519satisfies :math:`|d\cdot{}q|\leq{}|n|`. 3520 3521Note that *q* is: 3522 3523- Positive, where \|n| :math:`\geq{}` \|d|, and *n* and *d* have the same sign; 3524 but 3525- Negative, where \|n| :math:`\geq{}` \|d|, and *n* and *d* have opposite signs. 3526 3527 3528.. index:: 3529 division operator 3530 binary operator 3531 operand 3532 dividend 3533 divisor 3534 round-toward-zero 3535 integer division 3536 predefined numeric types conversion 3537 numeric type 3538 integer value 3539 3540Only a single special case does not comply with this rule: the integer overflow 3541occurs, and the result equals the dividend if the dividend is a negative 3542integer of the largest possible magnitude for its type, while the divisor 3543is *-1*. This case throws no exception or error despite the overflow. However, 3544if in an integer division the divisor value is *0*, then ``ArithmeticError`` is 3545thrown. 3546 3547A floating-point division result is determined in compliance with the IEEE 754 3548arithmetic: 3549 3550- The result is ``NaN`` if: 3551 3552 - Either operand is NaN; 3553 - Both operands are infinity; or 3554 - Both operands are zero. 3555 3556 3557.. index:: 3558 integer overflow 3559 dividend 3560 negative integer 3561 floating-point division 3562 divisor 3563 exception 3564 error 3565 overflow 3566 integer division 3567 floating-point division 3568 NaN 3569 infinity 3570 operand 3571 IEEE 754 3572 3573- If the result is not ``NaN``, then the sign of the result is: 3574 3575 - Positive, where both operands have the same sign; or 3576 - Negative, where the operands have different signs. 3577 3578 3579- Division produces a signed infinity (the sign is determined by 3580 the rule above) if: 3581 3582 - Infinity is divided by a finite value; and 3583 - A nonzero finite value is divided by zero. 3584 3585 3586- Division produces a signed zero (the sign is determined by the 3587 rule above) if: 3588 3589 - A finite value is divided by infinity; and 3590 - Zero is divided by any other finite value. 3591 3592.. index:: 3593 NaN 3594 operand 3595 division 3596 signed infinity 3597 finite value 3598 3599- If neither ``NaN`` nor infinity is involved, then the exact mathematical 3600 quotient is computed. 3601 3602 If the magnitude of the product is too large to represent, then the 3603 operation overflows, and the result is an appropriately signed infinity. 3604 3605 3606The quotient is rounded to the nearest value in the chosen value set by 3607using the IEEE 754 *round-to-nearest* mode. The |LANG| programming 3608language requires gradual underflow support as defined by IEEE 754 (see 3609:ref:`Floating-Point Types and Operations`). 3610 3611The evaluation of a floating-point division operator '``/``' never throws an 3612error despite possible overflow, underflow, division by zero, or loss of 3613information. 3614 3615.. index:: 3616 infinity 3617 NaN 3618 overflow 3619 floating-point division 3620 round-to-nearest 3621 rounding 3622 underflow 3623 floating-point types 3624 floating-point operation 3625 error 3626 exception 3627 loss of information 3628 division 3629 division operator 3630 IEEE 754 3631 3632| 3633 3634.. _Remainder: 3635 3636Remainder 3637========= 3638 3639.. meta: 3640 frontend_status: Done 3641 todo: If either operand is NaN, the result should be NaN, but result is -NaN 3642 todo: if the dividend is an infinity, or the divisor is a zero, or both, the result should be NaN, but this is -NaN 3643 3644The binary operator '``%``' yields the remainder of its operands (``dividend`` 3645as left-hand, and ``divisor`` as the right-hand operand) from an implied 3646division. 3647 3648The remainder operator in |LANG| accepts floating-point operands (unlike in 3649C and C++). 3650 3651The remainder operation on integer operands (for the numeric type conversion 3652on both see :ref:`Primitive Types Conversions`) produces a result 3653value, i.e., :math:`(a/b)*b+(a\%b)` equals *a*. 3654 3655 3656.. index:: 3657 remainder operator 3658 dividend 3659 divisor 3660 predefined numeric types conversion 3661 conversion 3662 floating-point operand 3663 remainder operation 3664 value 3665 integer operand 3666 implied division 3667 numeric types conversion 3668 numeric type 3669 conversion 3670 3671This equality holds even in the special case where the dividend is a negative 3672integer of the largest possible magnitude of its type, and the divisor is *-1* 3673(the remainder is then *0*). According to this rule, the result of the remainder 3674operation can only be: 3675 3676- Negative if the dividend is negative; or 3677- Positive if the dividend is positive. 3678 3679 3680The magnitude of the result is always less than that of the divisor. 3681 3682If the value of the divisor for an integer remainder operator is *0*, then 3683*ArithmeticError* is thrown. 3684 3685A floating-point remainder operation result as computed by the operator '``%``' 3686is different than that produced by the remainder operation defined by IEEE 754. 3687The IEEE 754 remainder operation computes the remainder from a rounding 3688division (not a truncating division), and its behavior is different from that 3689of the usual integer remainder operator. On the contrary, |LANG| presumes that 3690on floating-point operations the operator '``%``' behaves in the same manner as 3691the integer remainder operator (comparable to the C library function *fmod*). 3692The standard library (see :ref:`Standard Library`) routine ``Math.IEEEremainder`` 3693can compute the IEEE 754 remainder operation. 3694 3695.. index:: 3696 dividend 3697 equality 3698 magnitude 3699 negative integer 3700 divisor 3701 remainder operator 3702 remainder operation 3703 truncation 3704 integer remainder 3705 value 3706 floating-point remainder operation 3707 floating-point operation 3708 division 3709 truncating division 3710 rounding 3711 IEEE 754 3712 3713The result of a floating-point remainder operation is determined in compliance 3714with the IEEE 754 arithmetic: 3715 3716- The result is ``NaN`` if: 3717 3718 - Either operand is ``NaN``; 3719 - The dividend is infinity; 3720 - The divisor is zero; or 3721 - The dividend is infinity, and the divisor is zero. 3722 3723 3724- If the result is not ``NaN``, then the sign of the result is the same as the 3725 sign of the dividend. 3726- The result equals the dividend if: 3727 3728 - The dividend is finite, and the divisor is infinity; or 3729 - If the dividend is zero, and the divisor is finite. 3730 3731.. index:: 3732 floating-point remainder operation 3733 remainder operation 3734 NaN 3735 infinity 3736 divisor 3737 dividend 3738 IEEE 754 3739 3740- If infinity, zero, or ``NaN`` are not involved, then the floating-point remainder 3741 *r* from the division of the dividend *n* by the divisor *d* is determined 3742 by the mathematical relation :math:`r=n-(d\cdot{}q)`, where *q* is an 3743 integer that is only: 3744 3745 - Negative if :math:`n/d` is negative, or 3746 - Positive if :math:`n/d` is positive. 3747 3748 3749- The magnitude of *q* is the largest possible without exceeding the 3750 magnitude of the true mathematical quotient of *n* and *d*. 3751 3752 3753The evaluation of the floating-point remainder operator '``%``' never throws 3754an error, even if the right-hand operand is zero. Overflow, underflow, or 3755loss of precision cannot occur. 3756 3757.. index:: 3758 infinity 3759 NaN 3760 floating-point remainder 3761 remainder operator 3762 dividend 3763 loss of precision 3764 operand 3765 magnitude 3766 underflow 3767 error 3768 overflow 3769 loss of precision 3770 3771| 3772 3773.. _Additive Expressions: 3774 3775Additive Expressions 3776******************** 3777 3778.. meta: 3779 frontend_status: Done 3780 3781Additive expressions use *additive operators* '``+``' and '``-``': 3782 3783.. code-block:: abnf 3784 3785 additiveExpression: 3786 expression '+' expression 3787 | expression '-' expression 3788 ; 3789 3790The additive operators group left-to-right. 3791 3792If either operand of the operator is '``+``' of type ``string``, then the 3793operation is a string concatenation (see :ref:`String Concatenation`). In all 3794other cases, the type of each operand of the operator '``+``' must be 3795convertible (see :ref:`Primitive Types Conversions`) to a numeric type. 3796Otherwise, a :index:`compile-time error` occurs. 3797 3798The type of each operand of the binary operator '``-``' must be convertible 3799(see :ref:`Primitive Types Conversions`) to a numeric type in all cases. 3800Otherwise, a :index:`compile-time error` occurs. 3801 3802.. index:: 3803 additive expression 3804 additive operator 3805 operand 3806 string 3807 string concatenation 3808 operator 3809 conversion 3810 numeric type 3811 compile-time error 3812 binary operator 3813 3814| 3815 3816.. _String Concatenation: 3817 3818String Concatenation 3819==================== 3820 3821.. meta: 3822 frontend_status: Done 3823 3824If one operand of an expression is of type ``string``, then the string 3825conversion (see :ref:`String Operator Contexts`) is performed on the other 3826operand at runtime to produce a string. 3827 3828String concatenation produces a reference to a ``string`` object that is a 3829concatenation of two operand strings. The left-hand operand characters precede 3830the right-hand operand characters in a newly created string. 3831 3832If the expression is not a constant expression (see :ref:`Constant Expressions`), 3833then a new ``string`` object is created (see :ref:`New Expressions`). 3834 3835.. index:: 3836 string concatenation operator 3837 string 3838 operand 3839 string conversion 3840 operator context 3841 runtime 3842 operand string 3843 precedence 3844 expression 3845 constant expression 3846 object 3847 3848| 3849 3850.. _Additive Operators for Numeric Types: 3851 3852Additive Operators for Numeric Types 3853==================================== 3854 3855.. meta: 3856 frontend_status: Done 3857 todo: The sum of two infinities of opposite sign should be NaN, but it is -NaN 3858 3859The primitive types conversion (see :ref:`Primitive Types Conversions`) 3860performed on a pair of operands ensures that both operands are of a numeric 3861type. If the conversion fails, then a :index:`compile-time error` occurs. 3862 3863The binary operator '``+``' performs addition and produces the sum of such 3864operands. 3865 3866The binary operator '``-``' performs subtraction and produces the difference 3867of two numeric operands. 3868 3869The type of an additive expression performed on numeric operands is the 3870largest type (see :ref:`Numeric Types Hierarchy`) the operands of that 3871expression are converted to. 3872 3873If the promoted type is ``int`` or ``long``, then integer arithmetic is 3874performed. 3875If the promoted type is ``float`` or ``double``, then floating-point arithmetic 3876is performed. 3877 3878.. index:: 3879 additive operator 3880 primitive type 3881 conversion 3882 numeric type 3883 binary operator 3884 integer arithmetic 3885 integer 3886 type operand 3887 addition 3888 subtraction 3889 numeric operand 3890 predefined numeric types conversion 3891 floating-point arithmetic 3892 integer arithmetic 3893 promoted type 3894 expression 3895 additive expression 3896 3897If operand expressions have no side effects, then addition is a commutative 3898operation. 3899 3900If all operands are of the same type, then integer addition is associative. 3901 3902Floating-point addition is not associative. 3903 3904If overflow occurs on an integer addition, then: 3905 3906- The result is the low-order bits of the mathematical sum as represented in 3907 a sufficiently large two’s-complement format. 3908- The sign of the result is different than that of the mathematical sum of 3909 the operands’ values. 3910 3911 3912The result of a floating-point addition is determined in compliance with the 3913IEEE 754 arithmetic as follows: 3914 3915.. index:: 3916 operand expression 3917 expression 3918 side effect 3919 addition 3920 commutative operation 3921 operation 3922 two’s-complement format 3923 operand value 3924 overflow 3925 floating-point addition 3926 compliance 3927 associativity 3928 IEEE 754 3929 3930- The result is ``NaN`` if: 3931 3932 - Either operand is ``NaN``; or 3933 - The operands are two infinities of the opposite signs. 3934 3935 3936- The sum of two infinities of the same sign is the infinity of that sign. 3937- The sum of infinity and a finite value equals the infinite operand. 3938- The sum of two zeros of opposite sign is positive zero. 3939- The sum of two zeros of the same sign is zero of that sign. 3940- The sum of zero and a nonzero finite value is equal to the nonzero operand. 3941- The sum of two nonzero finite values of the same magnitude and opposite sign 3942 is positive zero. 3943- If infinity, zero, or ``NaN`` are not involved, and the operands have the 3944 same sign or different magnitudes, then the exact sum is computed 3945 mathematically. 3946 3947 3948If the magnitude of the sum is too large to represent, then the operation 3949overflows, and the result is an appropriately signed infinity. 3950 3951.. index:: 3952 NaN 3953 infinity 3954 signed infinity 3955 magnitude 3956 operand 3957 infinite operand 3958 infinite value 3959 nonzero operand 3960 finite value 3961 positive zero 3962 negative zero 3963 overflow 3964 operation overflow 3965 3966Otherwise, the sum is rounded to the nearest value within the chosen value set 3967by using the IEEE 754 *round-to-nearest* mode. The |LANG| programming language 3968requires gradual underflow support as defined by IEEE 754 (see 3969:ref:`Floating-Point Types and Operations`). 3970 3971When applied to two numeric type operands, the binary operator '``-``' performs 3972subtraction, and returns the difference of such operands (``minuend`` as 3973left-hand, and ``subtrahend`` as the right-hand operand). 3974 3975The result of *a-b* is always the same as that of *a+(-b)* in both integer and 3976floating-point subtraction. 3977 3978The subtraction from zero for integer values is the same as negation. However, 3979the subtraction from zero for floating-point operands and negation is *not* 3980the same (if *x* is *+0.0*, then *0.0-x* is *+0.0*; however *-x* is *-0.0*). 3981 3982The evaluation of a numeric additive operator never throws an error despite 3983possible overflow, underflow, or loss of information. 3984 3985.. index:: 3986 round-to-nearest mode 3987 rounding 3988 value set 3989 underflow 3990 floating-point type 3991 floating-point operation 3992 floating-point subtraction 3993 floating-point operand 3994 subtraction 3995 integer subtraction 3996 integer value 3997 loss of information 3998 numeric type operand 3999 binary operator 4000 subtraction 4001 negation 4002 overflow 4003 additive operator 4004 error 4005 IEEE 754 4006 4007| 4008 4009.. _Shift Expressions: 4010 4011Shift Expressions 4012***************** 4013 4014.. meta: 4015 frontend_status: Done 4016 todo: spec issue: uses 'L' postfix in example "(n >> s) + (2L << ~s)", we don't have it 4017 4018Shift expressions use *shift operators* '``<<``' (left shift), '``>>``' 4019(signed right shift), and '``>>>``' (unsigned right shift). The value to be 4020shifted is the left-hand operand in a shift operator, and the right-hand 4021operand specifies the shift distance: 4022 4023.. code-block:: abnf 4024 4025 shiftExpression: 4026 expression '<<' expression 4027 | expression '>>' expression 4028 | expression '>>>' expression 4029 ; 4030 4031The shift operators group left-to-right. 4032 4033Numeric types conversion (see :ref:`Primitive Types Conversions`) is performed 4034separately on each operand to ensure that both operands are of primitive 4035integer type. 4036 4037**Note**: If the initial type of one or both operands is ``double`` or 4038``float``, then such operand or operands are first truncated to the appropriate 4039integer type. If both operands are of type ``bigint``, then shift operator 4040is applied to bigint operands. 4041 4042A :index:`compile-time error` occurs if either operand in a shift operator 4043(after unary numeric promotion) is not a primitive ``integer`` or ``bigint`` 4044type. 4045 4046.. index:: 4047 shift 4048 shift expression 4049 left shift 4050 right shift 4051 shift distance 4052 shift operator 4053 signed right shift 4054 unsigned right shift 4055 operand 4056 shift distance 4057 numeric type 4058 predefined numeric types conversion 4059 numeric types conversion 4060 unary numeric promotion 4061 truncation 4062 truncated operand 4063 primitive type 4064 integer type 4065 bigint 4066 4067The shift expression type is the promoted type of the left-hand operand. 4068 4069If the left-hand operand is of the promoted type ``int``, then only five 4070lowest-order bits of the right-hand operand specify the shift distance 4071(as if using a bitwise logical AND operator '``&``' with the mask value *0x1f* 4072or *0b11111* on the right-hand operand). Thus, it is always within the 4073inclusive range of *0* through *31*. 4074 4075If the left-hand operand is of the promoted type ``long``, then only six 4076lowest-order bits of the right-hand operand specify the shift distance 4077(as if using a bitwise logical AND operator '``&``' with the mask value *0x3f* 4078or *0b111111* the right-hand operand). Thus, it is always within the inclusive 4079range of *0* through *63*. 4080 4081Shift operations are performed on the two’s-complement integer 4082representation of the value of the left-hand operand at runtime. 4083 4084The value of *n* ``<<`` *s* is *n* left-shifted by *s* bit positions. It is 4085equivalent to multiplication by two to the power *s* even in case of an 4086overflow. 4087 4088.. index:: 4089 shift expression 4090 promoted type 4091 operand 4092 shift distance 4093 bitwise logical AND operator 4094 mask value 4095 shift operation 4096 multiplication 4097 overflow 4098 two’s-complement integer representation 4099 left shift 4100 runtime 4101 4102The value of *n* ``>>`` *s* is *n* right-shifted by *s* bit positions with 4103sign-extension. The resultant value is :math:`floor(n / 2s)`. If *n* is 4104non-negative, then it is equivalent to truncating integer division (as computed 4105by the integer division operator by 2 to the power *s*). 4106 4107The value of *n* ``>>>`` *s* is *n* right-shifted by *s* bit positions with 4108zero-extension, where: 4109 4110- If *n* is positive, then the result is the same as that of *n* ``>>`` *s*. 4111- If *n* is negative, and the type of the left-hand operand is ``int``, then 4112 the result is equal to that of the expression (*n* ``>>`` *s*) ``+`` (*2* ``<<`` *s*). 4113- If *n* is negative, and the type of the left-hand operand is ``long``, then 4114 the result is equal to that of the expression (*n* ``>>`` *s*) ``+`` (*2L* ``<<`` *s*). 4115 4116.. index:: 4117 sign-extension 4118 right shift 4119 truncation 4120 truncating integer division 4121 integer division operator 4122 zero-extension 4123 operand 4124 expression 4125 4126| 4127 4128.. _Relational Expressions: 4129 4130Relational Expressions 4131********************** 4132 4133.. meta: 4134 frontend_status: Done 4135 todo: if either operand is NaN, then the result should be false, but Double.NaN < 2 is true, and assertion fail occurs with opt-level 2. (also fails with INF) 4136 todo: Double.POSITIVE_INFINITY > 1 should be true, but false (also fails with opt-level 2) 4137 4138Relational expressions use *relational operators* '``<``', '``>``', '``<=``', 4139and '``>=``'. 4140 4141.. code-block:: abnf 4142 4143 relationalExpression: 4144 expression '<' expression 4145 | expression '>' expression 4146 | expression '<=' expression 4147 | expression '>=' expression 4148 ; 4149 4150The relational operators group left-to-right. 4151 4152A relational expression is always of type ``boolean``. 4153 4154Two kinds of relational expressions are described below. The kind of a 4155relational expression depends on the types of operands. It is a 4156:index:`compile-time error` if at least one type of operands is different from 4157types described below. 4158 4159.. index:: 4160 numerical relational operator 4161 relational operator 4162 relational expression 4163 boolean type 4164 expression 4165 operand 4166 type 4167 4168| 4169 4170.. _Numerical Relational Operators: 4171 4172Numerical Relational Operators 4173============================== 4174 4175.. meta: 4176 frontend_status: Done 4177 4178The type of each operand in a numerical relational operator must be convertible 4179(see :ref:`Implicit Conversions`) to a numeric type. Otherwise, a 4180:index:`compile-time error` occurs. 4181 4182Numeric types conversions (see :ref:`Primitive Types Conversions`) are 4183performed on each operand as follows: 4184 4185- Signed integer comparison if the converted type of the operand is 4186 ``int`` or ``long``. 4187 4188- Floating-point comparison if the converted type of the operand is 4189 ``float`` or ``double``. 4190 4191.. index:: 4192 numerical relational operator 4193 operand 4194 conversion 4195 compile-time error 4196 numeric type 4197 numeric types conversion 4198 predefined numeric types conversion 4199 signed integer comparison 4200 floating-point comparison 4201 converted type 4202 4203The comparison of floating-point values drawn from any value set must be accurate. 4204 4205A floating-point comparison must be performed in accordance with the IEEE 754 4206standard specification as follows: 4207 4208- The result of a floating-point comparison is false if either operand is ``NaN``. 4209 4210- All values other than ``NaN`` must be ordered with the following: 4211 4212 - Negative infinity less than all finite values; and 4213 - Positive infinity greater than all finite values. 4214 4215- Positive zero equals negative zero. 4216 4217.. index:: 4218 floating-point value 4219 floating-point comparison 4220 comparison 4221 NaN 4222 finite value 4223 infinity 4224 negative infinity 4225 positive infinity 4226 positive zero 4227 negative zero 4228 IEEE 754 4229 4230Based on the above presumption, the following rules apply to integer operands, 4231or floating-point operands other than ``NaN``: 4232 4233- The value produced by the operator '``<``' is ``true`` if the value of the 4234 left-hand operand is less than that of the right-hand operand. Otherwise, 4235 the value is ``false``. 4236- The value produced by the operator '``<=``' is ``true`` if the value of the 4237 left-hand operand is less than or equal to that of the right-hand operand. 4238 Otherwise, the value is ``false``. 4239- The value produced by the operator '``>``' is ``true`` if the value of the 4240 left-hand operand is greater than that of the right-hand operand. Otherwise, 4241 the value is ``false``. 4242- The value produced by the operator '``>=``' is ``true`` if the value of the 4243 left-hand operand is greater than or equal to that of the right-hand operand. 4244 Otherwise, the value is ``false``. 4245 4246.. index:: 4247 integer operand 4248 floating-point operand 4249 NaN 4250 operator 4251 4252| 4253 4254.. _String Relational Operators: 4255 4256String Relational Operators 4257=========================== 4258 4259.. meta: 4260 frontend_status: Done 4261 4262Results of all string comparisons are defined as follows: 4263 4264- Operator '``<``' delivers ``true`` if the string value of the left-hand 4265 operand is lexicographically less than the string value of the right-hand 4266 operand, or ``false`` otherwise. 4267- Operator '``<=``' delivers ``true`` if the string value of the left-hand 4268 operand is lexicographically less than or equal to the string value of the 4269 right-hand operand, or ``false`` otherwise. 4270- Operator '``>``' delivers ``true`` if the string value of the left-hand 4271 operand is lexicographically greater than the string value of the right-hand 4272 operand, or ``false`` otherwise. 4273- Operator '``>=``' delivers ``true`` if the string value of the left-hand 4274 operand is lexicographically greater than or equal to the string value of 4275 the right-hand operand, or ``false`` otherwise. 4276 4277.. index:: 4278 operator 4279 string comparison 4280 string value 4281 4282| 4283 4284.. _Bigint Relational Operators: 4285 4286Bigint Relational Operators 4287=========================== 4288 4289.. meta: 4290 frontend_status: Done 4291 4292The type of each operand in a bigint relational operator must be ``bigint``. 4293Otherwise, a :index:`compile-time error` occurs. 4294 4295All bigint relational operators compare bigint values. 4296 4297.. index:: 4298 bigint comparison 4299 relational operator 4300 bigint 4301 operand 4302 4303| 4304 4305.. _Boolean Relational Operators: 4306 4307Boolean Relational Operators 4308============================ 4309 4310.. meta: 4311 frontend_status: Done 4312 4313Results of all boolean comparisons are defined as follows: 4314 4315- Operator '``<``' delivers ``true`` if the left-hand operand is ``false`` 4316 and the right-hand operand is true, or ``false`` otherwise. 4317- Operator '``<=``' delivers ``true`` if the left-hand operand is ``false`` 4318 and the right-hand operand is ``true`` or ``false``, or ``false`` otherwise. 4319- Operator '``>``' delivers ``true`` if the left-hand operand is ``true`` 4320 and the right-hand operand is ``false``, or ``false`` otherwise. 4321- Operator '``>=``' delivers ``true`` if the left-hand operand is ``true`` 4322 and the right-hand operand is ``false`` or ``true``, or ``false`` otherwise. 4323 4324.. index:: 4325 boolean operator 4326 relational operator 4327 boolean comparison 4328 4329| 4330 4331.. _Enumeration Relational Operators: 4332 4333Enumeration Relational Operators 4334================================ 4335 4336.. meta: 4337 frontend_status: Done 4338 4339If both operands are of the same Enumeration type (see :ref:`Enumerations`), 4340then :ref:`Numerical Relational Operators` or :ref:`String Relational Operators` 4341are used depending on the kind of enumeration constant value 4342( :ref:`Enumeration Integer Values` or :ref:`Enumeration String Values`). 4343 4344Otherwise, a :index:`compile-time error` occurs. 4345 4346.. index:: 4347 enumeration operator 4348 relational operator 4349 boolean comparison 4350 constant value 4351 4352| 4353 4354.. _Equality Expressions: 4355 4356Equality Expressions 4357******************** 4358 4359.. meta: 4360 frontend_status: Done 4361 4362Equality expressions use *equality operators* '``==``', '``===``', '``!=``', 4363and '``!==``': 4364 4365.. code-block:: abnf 4366 4367 equalityExpression: 4368 expression ('==' | '===' | '!=' | '!==') expression 4369 ; 4370 4371Any equality expression is of type ``boolean``. The result of operators '``==``' 4372and '``===``' is ``true`` if operands are *equal* (see below). Otherwise, the 4373result is ``false``. 4374 4375Equality operators group left-to-right. 4376Equality operators are commutative if operand expressions cause no side 4377effects. 4378 4379Equality operators are similar to relational operators, except for their 4380lower precedence (:math:`a < b==c < d` is ``true`` if both :math:`a < b` 4381and :math:`c < d` have the same ``truth`` value). 4382 4383.. index:: 4384 equality operator 4385 equality expression 4386 boolean type 4387 relational operator 4388 4389In all cases, ``a != b`` produces the same result as ``!(a == b)``, and 4390``a !== b`` produces the same result as ``!(a === b)``. 4391 4392The result of operators '``==``' and '``===``' is the same in all cases, 4393except when comparing the values ``null`` and ``undefined`` (see 4394:ref:`Reference Equality`). 4395 4396The variant of equality evaluation to be used depends on the types of the 4397operands used as follows: 4398 4399- *Value equality* is applied to entities of primitive types 4400 (see :ref:`Value Types`), their boxed versions (see :ref:`Boxed Types`), 4401 type ``string`` (see :ref:`Type string`), type ``bigint`` (see 4402 :ref:`BigInt Type`), and enumeration types (see :ref:`Enumerations`). 4403- *Reference Equality based on actual (dynamic) type* is applied to values of 4404 type ``Object`` (:ref:`Object Class Type`), values of union types 4405 (:ref:`Union Types`), and type parameters (:ref:`Type Parameters`). 4406- *Reference equality* is applied to entities of all other reference types 4407 (see :ref:`Reference Types`). 4408 4409.. index:: 4410 operator 4411 value 4412 value equality 4413 primitive type 4414 enumeration type 4415 bigint 4416 reference equality 4417 object 4418 type parameter 4419 4420Operators '``===``' and '``==``', or '``!==``' and '``!=``' are used for: 4421 4422- :ref:`Numerical Equality Operators` if operands are of numeric types, 4423 type ``char``, or the boxed version of numeric types; 4424 4425- :ref:`String Equality Operators` if both operands are of type ``string``; 4426 4427- :ref:`Bigint Equality Operators` if both operands are of type ``bigint``; 4428 4429- :ref:`Boolean Equality Operators` if both operands are of type ``boolean`` 4430 or ``Boolean``; 4431 4432- :ref:`Enumeration Equality Operators` if both operands are of enumeration type; 4433 4434- :ref:`Reference Equality based on actual type` if at least one operand is of 4435 ``Object`` type or union type, or is a type parameter; 4436 4437- :ref:`Reference Equality` if both operands are of compatible reference types, 4438 except types ``string``, ``bigint``, ``Object``, union types, and type 4439 parameters; 4440 4441- :ref:`Extended Equality with null or undefined` if one operand is ``null`` or 4442 ``undefined``. 4443 4444- Otherwise, a :index:`compile-time error` occurs. 4445 4446.. code-block:: typescript 4447 :linenos: 4448 4449 // Entities of value types are not comparable between each other 4450 5 == "5" // compile-time error 4451 5 == true // compile-time error 4452 "5" == true // compile-time error 4453 4454.. index:: 4455 compile-time error 4456 value equality 4457 comparison 4458 operand 4459 numeric type 4460 string 4461 equality operator 4462 boolean type 4463 type parameter 4464 object 4465 reference type 4466 4467| 4468 4469.. _Numerical Equality Operators: 4470 4471Numerical Equality Operators 4472============================ 4473 4474.. meta: 4475 frontend_status: Done 4476 4477The type of each operand in a numerical equality operator must be convertible 4478(see :ref:`Implicit Conversions`) to a numeric type. Otherwise, a 4479:index:`compile-time error` occurs. 4480 4481A widening conversion can occur (see :ref:`Widening Primitive Conversions`) 4482if type of one operand is smaller than type of the other operand (see 4483:ref:`Numeric Types Hierarchy`). 4484 4485If the converted type of the operands is ``int`` or ``long``, then an 4486integer equality test is performed. 4487 4488If the converted type is ``float`` or ``double``, then a floating-point 4489equality test is performed. 4490 4491The floating-point equality test must be performed in accordance with the 4492following IEEE 754 standard rules: 4493 4494.. index:: 4495 value equality operator 4496 numeric type 4497 numeric types conversion 4498 predefined numeric types conversion 4499 converted type 4500 floating-point equality test 4501 operand 4502 conversion 4503 integer equality test 4504 IEEE 754 4505 widening 4506 primitive conversion 4507 4508- The result of '``==``' or '``===``' is ``false`` but the result of '``!=``' 4509 is ``true`` if either operand is ``NaN``. 4510 4511 The test ``x != x`` or ``x !== x`` is ``true`` only if *x* is ``NaN``. 4512 4513- Positive zero equals negative zero. 4514 4515- Equality operators consider two distinct floating-point values unequal 4516 in any other situation. 4517 4518 For example, if one value represents positive infinity, and the other 4519 represents negative infinity, then each compares equal to itself and 4520 unequal to all other values. 4521 4522Based on the above presumptions, the following rules apply to integer operands 4523or floating-point operands other than ``NaN``: 4524 4525- If the value of the left-hand operand is equal to that of the right-hand 4526 operand, then the operator '``==``' or '``===``' produces the value 4527 ``true``. Otherwise, the result is ``false``. 4528 4529- If the value of the left-hand operand is not equal to that of the right-hand 4530 operand, then the operator '``!=``' or '``!==``' produces the value 4531 ``true``. Otherwise, the result is ``false``. 4532 4533The following example illustrates *numerical equality*: 4534 4535.. code-block:: typescript 4536 :linenos: 4537 4538 5 == 5 // true 4539 5 != 5 // false 4540 4541 5 === 5 // true 4542 4543 5 == new Number(5) // true 4544 5 === new Number(5) // true 4545 4546 new Number(5) == new Number(5) // true 4547 5 == 5.0 // true 4548 4549.. index:: 4550 NaN 4551 value equality 4552 floating-point value 4553 floating-point operand 4554 numerical equality 4555 positive infinity 4556 negative infinity 4557 positive zero 4558 negative zero 4559 4560| 4561 4562.. _String Equality Operators: 4563 4564String Equality Operators 4565========================= 4566 4567.. meta: 4568 frontend_status: Done 4569 4570The type of one operand must be of type ``string``, other operand must 4571be convertible (see :ref:`Implicit Conversions`) to ``string`` type. 4572 4573Two strings are equal if they represent the same sequence of characters: 4574 4575.. code-block:: typescript 4576 :linenos: 4577 4578 "abc" == "abc" // true 4579 "abc" === "ab" + "c" // true 4580 4581 function foo(s: string) { 4582 console.log(s == "hello") 4583 } 4584 foo("hello") // prints "true" 4585 4586.. index:: 4587 value equality 4588 string 4589 conversion 4590 4591| 4592 4593.. _Bigint Equality Operators: 4594 4595Bigint Equality Operators 4596========================== 4597 4598.. meta: 4599 frontend_status: Done 4600 4601*Boolean equality* is used for operands of types ``bigint`` or 4602``BigInt``. 4603 4604Two ``bigints`` are equal if they have the same value: 4605 4606.. code-block:: typescript 4607 :linenos: 4608 4609 let x = 2n 4610 x == 2n // true 4611 4612.. index:: 4613 value equality 4614 bigint 4615 equality operator 4616 boolean equality 4617 4618| 4619 4620.. _Boolean Equality Operators: 4621 4622Boolean Equality Operators 4623========================== 4624 4625.. meta: 4626 frontend_status: Done 4627 4628*Boolean equality* is used for operands of types ``boolean`` or 4629``Boolean``. 4630 4631If an operand is of type ``Boolean``, then the unboxing conversion must be 4632performed (see :ref:`Primitive Types Conversions`). 4633 4634If both operands (after the unboxing conversion is performed if required) are 4635either ``true`` or ``false``, then the result of ':math:`==`' or ':math:`===`' 4636is ``true``. Otherwise, the result is ``false``. 4637 4638If both operands are either ``true`` or ``false``, then the result of '``!=``' 4639or '``!==``' is ``false``. Otherwise, the result is ``true``. 4640 4641.. index:: 4642 value equality 4643 boolean type 4644 Boolean type 4645 boolean equality 4646 equality operator 4647 value equality operator 4648 operand 4649 unboxing conversion 4650 4651| 4652 4653.. _Enumeration Equality Operators: 4654 4655Enumeration Equality Operators 4656============================== 4657 4658.. meta: 4659 frontend_status: Done 4660 4661If both operands are of the same enumeration type (see :ref:`Enumerations`), 4662then :ref:`Numerical Equality Operators` or :ref:`String Equality Operators` 4663are used depending on the kind of enumeration constant value 4664(:ref:`Enumeration Integer Values` or :ref:`Enumeration String Values`). 4665 4666Otherwise, a :index:`compile-time error` occurs. 4667 4668.. index:: 4669 value equality 4670 enumeration type 4671 constant value 4672 4673| 4674 4675.. _Reference Equality Based on Actual Type: 4676 4677Reference Equality Based on Actual Type 4678======================================= 4679 4680.. meta: 4681 frontend_status: Done 4682 4683If an operand of an equality operator is of type ``Object``, or a union type, 4684or is a type parameter, then the operator is evaluated at runtime, and is based 4685on the actual type of this operand. If the other operand is of a type other 4686than that above, then the static type of this operand is used for evaluation. 4687 4688If actual types of objects are compatible, then the corresponding evaluation of 4689equality operator is used. Otherwise, the result of the operators '``==``' and 4690'``===``' is ``false``. 4691 4692.. index:: 4693 reference equality 4694 union type 4695 equality operator 4696 object 4697 type parameter 4698 evaluation 4699 operator 4700 4701| 4702 4703.. _Object Type Equality Operators: 4704 4705Object Type Equality Operators 4706------------------------------ 4707 4708.. meta: 4709 frontend_status: Done 4710 4711A value of type ``Object`` can be compared to a value of any reference type. 4712 4713The following example illustrates an equality with a value of type ``Object``: 4714 4715.. code-block:: typescript 4716 :linenos: 4717 4718 function equToString(a: Object, b: string): boolean { 4719 return a == b 4720 } 4721 4722 equToString("aa", "aa") // true, string equality 4723 equToString(1, "aa") // false, not compatible types 4724 4725 function equ(a: Object, b: Object): boolean { 4726 return a == b 4727 } 4728 4729 equ(1, 1) // true, numerical equality 4730 equ(1, 2) // false, numerical equality 4731 equ(1, new Number(1)) // true, numerical equality 4732 4733 equ("aa", "aa") // true, string equality 4734 equ(1, "aa") // false, not compatible types 4735 4736**Note**: The actual type of an ``Object`` value can be none of the following: 4737 4738- Union type, as only the current value of a union type variable can be assigned 4739 to an ``Object`` variable; 4740 4741- Type parameter, if it has no type constraint (see 4742 :ref:`Type Parameter Constraint`) as in the example below: 4743 4744.. code-block:: typescript 4745 :linenos: 4746 4747 function check(a: Object) {} 4748 4749 class G<A, B extends Number> { 4750 foo(x: A, y: B) { 4751 check(x) // compile-type error, A is not assignable to Object 4752 check(y) // ok, B is assignable to Object (as it is, at least, Number) 4753 } 4754 } 4755 4756.. index:: 4757 equality operator 4758 object 4759 reference type 4760 value 4761 union type 4762 assignment 4763 constraint 4764 type parameter 4765 4766| 4767 4768.. _Union Equality Operators: 4769 4770Union Equality Operators 4771------------------------ 4772 4773Where one operand is of type ``T``:sub:`1`, and the other operand is of type 4774``T``:sub:`2`, while ``T``:sub:`1`, ``T``:sub:`2`, or both are a union type, 4775then a :index:`compile-time error` occurs if ``T``:sub:`1` and ``T``:sub:`2` 4776have no overlap (i.e., if no value belongs to both ``T``:sub:`1` and 4777``T``:sub:`2`). 4778 4779**Note**: Any union type has an overlap with a value of type ``Object``. 4780 4781The following example illustrates an equality with values of two union types: 4782 4783.. code-block:: typescript 4784 :linenos: 4785 4786 function f1(x: number | string, y: boolean | null): boolean { 4787 return x == y // compile-time error, types have no overlap 4788 } 4789 4790 function f2(x: number | string, y: boolean | "abc"): boolean { 4791 return x == y // ok, types have overlap - value "abc" 4792 } 4793 4794If actual types of values are compatible, then the corresponding evaluation of 4795an equality operator is used. Otherwise, the result of the operators '``==``' 4796and '``===``' is ``false``: 4797 4798.. code-block:: typescript 4799 :linenos: 4800 4801 function equ(x: number | string, y: string): boolean { 4802 return x == y 4803 } 4804 4805 console.log(equ("aa", "aa")) // string equality: prints true 4806 console.log(equ("ab", "aa")) // string equality: prints false 4807 console.log(equ(1, "aa")) // different types: prints false 4808 4809.. index:: 4810 equality operator 4811 union 4812 operand 4813 union type 4814 overlap 4815 value 4816 object 4817 compatibility 4818 evaluation 4819 operator 4820 4821| 4822 4823.. _Type Parameter Equality Operators: 4824 4825Type Parameter Equality Operators 4826--------------------------------- 4827 4828.. meta: 4829 frontend_status: Done 4830 4831If one operand is a type parameter, then the other operand can be of any 4832reference type, including type parameter. 4833 4834If actual object types are compatible, then the corresponding evaluation of an 4835equality operator is used. Otherwise, the result of the operators '``==``' and 4836'``===``' is ``false``: 4837 4838.. code-block:: typescript 4839 :linenos: 4840 4841 function equ<A>(x: A, y: A): boolean { 4842 return x == y 4843 } 4844 4845 console.log(equ<string>("aa", "aa")) // string equality: prints true 4846 console.log(equ<number>(1, 2)) // numerical equality: prints false 4847 4848.. index:: 4849 equality operator 4850 type parameter 4851 operand 4852 reference type 4853 object 4854 compatibility 4855 evaluation 4856 4857| 4858 4859.. _Reference Equality: 4860 4861Reference Equality 4862================== 4863 4864.. meta: 4865 frontend_status: Partly 4866 todo: adapt latest specification changes 4867 4868Reference equality compares operands of two reference types except types 4869``string``, ``bigint``, ``Object``, union types, and type parameters. See 4870:ref:`Extended Equality with null or undefined` for extended semantics. 4871 4872A :index:`compile-time error` occurs if: 4873 4874- Any operand is not of a reference type; 4875 4876- There is no implicit conversion (see :ref:`Implicit Conversions`) that 4877 can convert the type of either operand to the type of the other. 4878 4879The result of '``==``' or '``===``' is ``true`` if both operand values: 4880 4881- Are ``null``; 4882- Are ``undefined``; or 4883- Refer to the same object, array, or function. 4884 4885In addition, the result of the '``==``' operator is ``true`` if one operand 4886value is ``null``, and the other operand value is ``undefined``. Otherwise, 4887the result is ``false``. This semantics is illustrated by the example below: 4888 4889.. index:: 4890 reference equality 4891 reference type 4892 operand 4893 entity 4894 bigint 4895 string 4896 object 4897 class 4898 function 4899 compile-time error 4900 reference type 4901 type parameter 4902 conversion 4903 operator 4904 operand value 4905 semantics 4906 4907.. code-block:: typescript 4908 :linenos: 4909 4910 class X {} 4911 new X() == new X() // false, two different object of class X 4912 new X() === new X() // false, the same 4913 let x1 = new X() 4914 let x2 = x1 4915 x1 == x2 // true, as x1 and x2 refer to the same object 4916 x1 === x2 // true, the same 4917 4918 new Number(5) === new Number(5) // true, value equality is used 4919 new Number(5) == new Number(6) // false, value equality is used 4920 4921 null == undefined // true 4922 null === undefined // false 4923 4924| 4925 4926.. _Extended Equality with null or undefined: 4927 4928Extended Equality with ``null`` or ``undefined`` 4929================================================ 4930 4931.. meta: 4932 frontend_status: None 4933 todo: adapt latest specification changes 4934 4935|LANG| provides extended semantics for equalities with ``null`` and ``undefined`` 4936to ensure better alignment with |TS|. 4937 4938Any entity can be compared to ``null`` by using the operators '``==``' and 4939'``===``'. This comparison can return ``true`` only for the entities of 4940*nullable* types if they actually have the ``null`` value during the program 4941execution. In all other cases the comparison to ``null`` returns ``false``. 4942 4943Operators '``!=``' and '``!==``' return ``true`` for any entity of 4944*non-nullable* types, and for *nullable* entities if they actually have no 4945``null`` value during program execution. 4946 4947These situations are to be known at compile time. 4948 4949Similarly, an equality comparison to ``undefined`` returns ``false`` if the 4950variable being compared is neither type ``undefined`` nor a union type with 4951``undefined`` as one of its types. 4952 4953The following comparisons evaluate to ``false`` at compile time: 4954 4955.. code-block-meta: 4956 4957 4958.. code-block:: typescript 4959 :linenos: 4960 4961 5 == null // false 4962 5 == undefined // false 4963 ((): void => {}) == null // false 4964 4965 class X {} 4966 new X() == null // false 4967 4968The following comparison is evaluated at runtime: 4969 4970.. code-block:: typescript 4971 :linenos: 4972 4973 function foo<T> (p1: string | null, p2: T) { 4974 console.log (p1 == undefined, p1 == null, p2 == undefined, p2 == null) 4975 } 4976 let nullable: string|null = "a string" 4977 let undefinedable: Object|undefined = undefined 4978 4979 foo (nullable, undefinedable) // Output: false false true true 4980 4981.. index:: 4982 semantics 4983 alignment 4984 equality 4985 comparison 4986 operator 4987 undefined 4988 null 4989 nullable type 4990 execution 4991 compilation 4992 compile time 4993 evaluation 4994 runtime 4995 4996| 4997 4998.. _Bitwise and Logical Expressions: 4999 5000Bitwise and Logical Expressions 5001******************************* 5002 5003.. meta: 5004 frontend_status: Done 5005 5006The *bitwise operators* and *logical operators* are as follows: 5007 5008- AND operator '``&``'; 5009- Exclusive OR operator '``^``'; and 5010- Inclusive OR operator '``|``'. 5011 5012 5013.. code-block:: abnf 5014 5015 bitwiseAndLogicalExpression: 5016 expression '&' expression 5017 | expression '^' expression 5018 | expression '|' expression 5019 ; 5020 5021These operators have different precedence. The operator '``&``' has the highest, 5022and '``|``' has the lowest precedence. 5023 5024The operators group left-to-right. Each operator is commutative, if the 5025operand expressions have no side effects, and associative. 5026 5027The bitwise and logical operators can compare two operands of a numeric 5028type, or two operands of the ``boolean`` type. Otherwise, a 5029:index:`compile-time error` occurs. 5030 5031.. index:: 5032 bitwise operator 5033 logical operator 5034 bitwise expression 5035 logical expression 5036 type boolean 5037 compile-time error 5038 operand expression 5039 precedence 5040 exclusive OR operator 5041 inclusive OR operator 5042 AND operator 5043 commutative operator 5044 side effect 5045 numeric type 5046 associativity 5047 operator 5048 boolean type 5049 5050 5051| 5052 5053.. _Integer Bitwise Operators: 5054 5055Integer Bitwise Operators 5056========================= 5057 5058.. meta: 5059 frontend_status: Done 5060 5061The numeric types conversion (see :ref:`Primitive Types Conversions`) 5062is performed first on the operands of an operator '``&``', '``^``', or '``|``' 5063if both operands are of a type convertible (see :ref:`Implicit Conversions`) 5064to a primitive integer type. 5065 5066**Note**: If the initial type of one or both operands is ``double`` or 5067``float``, then that operand or operands are truncated first to the appropriate 5068integer type. If both operands are of type ``bigint``, then no conversion is 5069required. 5070 5071A bitwise operator expression type is the converted type of its operands. 5072 5073The resultant value of '``&``' is the bitwise AND of the operand values. 5074 5075The resultant value of '``^``' is the bitwise exclusive OR of the operand values. 5076 5077The resultant value of '``|``' is the bitwise inclusive OR of the operand values. 5078 5079 5080.. index:: 5081 integer operator 5082 bitwise operator 5083 numeric types conversion 5084 numeric type 5085 conversion 5086 predefined numeric types conversion 5087 bitwise exclusive OR operand 5088 bitwise inclusive OR operand 5089 bitwise AND operand 5090 primitive type 5091 integer type 5092 conversion 5093 truncation 5094 5095| 5096 5097.. _Boolean Logical Operators: 5098 5099Boolean Logical Operators 5100========================= 5101 5102.. meta: 5103 frontend_status: Done 5104 5105The type of the bitwise operator expression is ``boolean`` if both operands of a 5106'``&``', '``^``', or '``|``' operator are of type ``boolean`` or ``Boolean``. 5107In any case, the unboxing conversion (see :ref:`Unboxing Conversions`) is 5108performed on the operands if required. 5109 5110If both operand values are ``true``, then the resultant value of '``&``' is 5111``true``. Otherwise, the result is ``false``. 5112 5113If the operand values are different, then the resultant value of ‘``^``’ is 5114``true``. Otherwise, the result is ``false``. 5115 5116If both operand values are ``false``, then the resultant value of ‘``|``’ is 5117``false``. Otherwise, the result is ``true``. 5118 5119.. index:: 5120 boolean operator 5121 Boolean operator 5122 logical operator 5123 bitwise operator expression 5124 unboxing conversion 5125 conversion 5126 predefined numeric types conversion 5127 numeric types conversion 5128 numeric type 5129 operand value 5130 5131| 5132 5133.. _Conditional-And Expression: 5134 5135Conditional-And Expression 5136************************** 5137 5138.. meta: 5139 frontend_status: Done 5140 5141The *conditional-and* operator '``&&``' is similar to '``&``' (see 5142:ref:`Bitwise and Logical Expressions`) but evaluates its right-hand 5143operand only if the left-hand operand’s value is ``true``. 5144 5145The computation results of '``&&``' and '``&``' on ``boolean`` operands are 5146the same, but the right-hand operand in '``&&``' cannot be evaluated. 5147 5148.. code-block:: abnf 5149 5150 conditionalAndExpression: 5151 expression '&&' expression 5152 ; 5153 5154The *conditional-and* operator groups left-to-right. 5155 5156The *conditional-and* operator is fully associative as regards both the result 5157value and side effects (i.e., the evaluations of the expressions *((a)* ``&&`` 5158*(b))* ``&&`` *(c)* and *(a)* ``&&`` *((b)* ``&&`` *(c))* produce the same 5159result, and the same side effects occur in the same order for any *a*, *b*, and 5160*c*). 5161 5162.. index:: 5163 conditional-and operator 5164 conditional-and expression 5165 bitwise expression 5166 logical expression 5167 boolean operand 5168 conditional evaluation 5169 evaluation 5170 expression 5171 5172A *conditional-and* expression is always of type ``boolean``. 5173 5174Each operand of the *conditional-and* operator must be of type ``boolean``, or 5175``Boolean``. Otherwise, a :index:`compile-time error` occurs. 5176See :ref:`Extended Conditional Expressions` for extended semantics, operands 5177and result type. 5178 5179The left-hand operand expression is first evaluated at runtime. If the result 5180is of type ``Boolean``, then the unboxing conversion (see 5181:ref:`Unboxing Conversions`) is performed as follows: 5182 5183- If the resultant value is ``false``, then the value of the *conditional-and* 5184 expression is ``false``; the evaluation of the right-hand operand expression 5185 is omitted. 5186 5187- If the value of the left-hand operand is ``true``, then the right-hand 5188 expression is evaluated. If the result of the evaluation is of type 5189 ``Boolean``, then the unboxing conversion (see :ref:`Unboxing Conversions`) 5190 is performed. The resultant value is the value of the *conditional-and* 5191 expression. 5192 5193.. index:: 5194 conditional-and expression 5195 conditional-and operator 5196 compile-time error 5197 boolean type 5198 Boolean type 5199 unboxing conversion 5200 predefined numeric types conversion 5201 numeric types conversion 5202 numeric type 5203 evaluation 5204 5205| 5206 5207.. _Conditional-Or Expression: 5208 5209Conditional-Or Expression 5210************************* 5211 5212.. meta: 5213 frontend_status: Done 5214 5215The *conditional-or* operator '``||``' is similar to '``|``' (see 5216:ref:`Integer Bitwise Operators`) but evaluates its right-hand operand 5217only if the value of its left-hand operand is ``false``. 5218 5219.. code-block:: abnf 5220 5221 conditionalOrExpression: 5222 expression '||' expression 5223 ; 5224 5225The *conditional-or* operator groups left-to-right. 5226 5227The *conditional-or* operator is fully associative as regards both the result 5228value and side effects (i.e., the evaluations of the expressions *((a)* ``||`` 5229*(b))* ``||`` *(c)* and *(a)* ``||`` *((b)* ``||`` *(c))* produce the same 5230result, and the same side effects occur in the same order for any *a*, *b*, 5231and *c*). 5232 5233A *conditional-or* expression is always of type ``boolean``. 5234 5235.. index:: 5236 conditional-or expression 5237 conditional-or operator 5238 integer bitwise expression 5239 associativity 5240 expression 5241 side effect 5242 evaluation 5243 boolean type 5244 5245Each operand of the *conditional-or* operator must be of type ``boolean`` or 5246``Boolean``. Otherwise, a :index:`compile-time error` occurs. 5247See :ref:`Extended Conditional Expressions` for extended semantics, operands 5248and result type. 5249 5250The left-hand operand expression is first evaluated at runtime. If the result 5251is of type ``Boolean``, then the *unboxing conversion ()* is performed as 5252follows: 5253 5254- If the resultant value is ``true``, then the value of the *conditional-or* 5255 expression is ``true``, and the evaluation of the right-hand operand 5256 expression is omitted. 5257 5258- If the resultant value is ``false``, then the right-hand expression is 5259 evaluated. If the result of the evaluation is of type ``Boolean``, then 5260 the *unboxing conversion* is performed (see 5261 :ref:`Unboxing Conversions`). The resultant value is the value of the 5262 *conditional-or* expression. 5263 5264The computation results of '``||``' and '``|``' on ``boolean`` operands are 5265the same, but the right-hand operand in '``||``' cannot be evaluated. 5266 5267.. index:: 5268 conditional-or expression 5269 conditional-or operator 5270 compile-time error 5271 runtime 5272 boolean type 5273 Boolean type 5274 unboxing conversion 5275 expression 5276 boolean operand 5277 predefined numeric types conversion 5278 numeric types conversion 5279 numeric type 5280 semantics 5281 conditional evaluation 5282 5283| 5284 5285.. _Assignment: 5286 5287Assignment 5288********** 5289 5290.. meta: 5291 frontend_status: Done 5292 5293All *assignment operators* group right-to-left (i.e., :math:`a=b=c` means 5294:math:`a=(b=c)`---and thus the value of *c* is assigned to *b*, and then 5295the value of *b* to *a*). 5296 5297.. code-block:: abnf 5298 5299 assignmentExpression: 5300 lhsExpression assignmentOperator rhsExpression 5301 ; 5302 5303 assignmentOperator 5304 : '=' 5305 | '+=' | '-=' | '*=' | '=' | '%=' 5306 | '<<=' | '>>=' | '>>>=' 5307 | '&=' | '|=' | '^=' 5308 ; 5309 5310 lhsExpression: 5311 expression 5312 ; 5313 5314 rhsExpression: 5315 expression 5316 ; 5317 5318The result of the first operand in an assignment operator (represented by 5319*lhsExpression*) must be one of the following: 5320 5321- Named variable, such as a local variable, or a field of the current 5322 object or class; 5323- Computed variable resultant from a field access (see 5324 :ref:`Field Access Expression`); or 5325- Array or record component access (see :ref:`Indexing Expressions`). 5326 5327.. index:: 5328 assignment 5329 assignment operator 5330 operand 5331 field 5332 variable 5333 local variable 5334 class 5335 object 5336 field access 5337 array 5338 field access expression 5339 indexing expression 5340 record component access 5341 5342A :index:`compile-time error` occurs if: 5343 5344- *lhsExpression* contains the chaining operator '``?.``' (see 5345 :ref:`Chaining Operator`); 5346- the result of *lhsExpression* is not a variable. 5347 5348 5349The type of the variable is the type of the assignment expression. 5350 5351The result of the assignment expression at runtime is not a variable itself 5352but the value of a variable after the assignment. 5353 5354.. index:: 5355 compile-time error 5356 chaining operator 5357 variable 5358 assignment 5359 assignment expression 5360 expression 5361 runtime 5362 5363| 5364 5365.. _Simple Assignment Operator: 5366 5367Simple Assignment Operator 5368========================== 5369 5370.. meta: 5371 frontend_status: Done 5372 5373A simple assignment expression has the form *E1 = E2*. 5374 5375A :index:`compile-time error` occurs if the type of the right-hand operand 5376(*rhsExpression*) is not compatible (see :ref:`Type Compatibility`) with 5377the type of the variable. Otherwise, the expression is evaluated at runtime in 5378one of the following ways: 5379 53801. If the left-hand operand *lhsExpression* is a field access expression 5381 *e.f* (see :ref:`Field Access Expression`), possibly enclosed in a 5382 pair of parentheses, then: 5383 5384 #. *lhsExpression* *e* is evaluated: if the evaluation of *e* 5385 completes abruptly, then so does the assignment expression. 5386 #. Right-hand operand *rhsExpression* is evaluated: if the evaluation 5387 completes abruptly, then so does the assignment expression. 5388 #. Value of the right-hand operand as computed above is assigned 5389 to the variable denoted by *e.f*. 5390 5391.. index:: 5392 simple assignment operator 5393 operator 5394 compile-time error 5395 compatible type 5396 compatibility 5397 access 5398 field access 5399 field access expression 5400 runtime 5401 abrupt completion 5402 evaluation 5403 assignment expression 5404 variable 5405 54062. If the left-hand operand is an array access expression (see 5407 :ref:`Array Indexing Expression`), possibly enclosed in a pair of 5408 parentheses, then: 5409 5410 #. Array reference subexpression of the left-hand operand is evaluated. 5411 If this evaluation completes abruptly, then so does the assignment 5412 expression. In that case, the right-hand operand and the index 5413 subexpression are not evaluated, and the assignment does not occur. 5414 #. If the evaluation completes normally, then the index subexpression of 5415 the left-hand operand is evaluated. If this evaluation completes 5416 abruptly, then so does the assignment expression. In that case, the 5417 right-hand operand is not evaluated, and the assignment does not occur. 5418 #. If the evaluation completes normally, then the right-hand operand is 5419 evaluated. If this evaluation completes abruptly, then so does the 5420 assignment expression, and the assignment does not occur. 5421 #. If the evaluation completes normally, but the value of the index 5422 subexpression is less than zero, or greater than, or equal to the 5423 *length* of the array, then ``ArrayIndexOutOfBoundsError`` is thrown, 5424 and the assignment does not occur. 5425 #. Otherwise, the value of the index subexpression is used to select an 5426 element of the array referred to by the value of the array reference 5427 subexpression. 5428 5429 5430 That element is a variable of type ``SC``. If ``TC`` is the type of the 5431 left-hand operand of the assignment operator determined at compile 5432 time, then there are two options: 5433 5434 - If ``TC`` is a primitive type, then ``SC`` can only be the same as ``TC``. 5435 5436 5437 The value of the right-hand operand is converted to the type of the 5438 selected array element. The value set conversion (see 5439 :ref:`Implicit Conversions`) is performed to convert it to the 5440 appropriate standard value set (not an extended-exponent value set). 5441 The result of the conversion is stored into the array element. 5442 - If ``TC`` is a reference type, then ``SC`` can be the same as ``TC`` or 5443 a type that extends or implements ``TC``. 5444 5445 If the |LANG| compiler cannot guarantee at compile time that the array 5446 element is exactly of type ``TC``, then a check must be performed 5447 at runtime to ensure that class ``RC``---i.e., the class of the 5448 object referred to by the value of the right-hand operand at 5449 runtime---is compatible with the actual type ``SC`` of the array element 5450 (see :ref:`Type Compatibility with Initializer`). 5451 5452 If class ``RC`` is not assignable to type ``SC``, then ``ArrayStoreError`` 5453 is thrown, and the assignment does not occur. 5454 5455 Otherwise, the reference value of the right-hand operand is stored in 5456 the selected array element. 5457 5458.. index:: 5459 array 5460 access expression 5461 indexing expression 5462 evaluation 5463 abrupt completion 5464 normal completion 5465 assignment 5466 assignment expression 5467 index subexpression 5468 reference subexpression 5469 variable 5470 assignment operator 5471 compile time 5472 primitive type 5473 operand 5474 conversion 5475 extended-exponent value set 5476 standard value set 5477 reference type 5478 class 5479 type compatibility 5480 compatible type 5481 array element 5482 error 5483 reference value 5484 54853. If the left-hand operand is a record access expression (see 5486 :ref:`Record Indexing Expression`), possibly enclosed in a pair of 5487 parentheses, then: 5488 5489 #. Object reference subexpression of the left-hand operand is evaluated. 5490 If this evaluation completes abruptly, then so does the assignment 5491 expression. 5492 In that case, the right-hand operand and the index subexpression are not 5493 evaluated, and the assignment does not occur. 5494 #. If the evaluation completes normally, the index subexpression of the 5495 left-hand operand is evaluated. If this evaluation completes abruptly, 5496 then so does the assignment expression. 5497 In that case, the right-hand operand is not evaluated, and the 5498 assignment does not occur. 5499 #. If the evaluation completes normally, the right-hand operand is evaluated. 5500 If this evaluation completes abruptly, then so does the assignment 5501 expression. 5502 In that case, the assignment does not occur. 5503 #. Otherwise, the value of the index subexpression is used as the ``key``. 5504 In that case, the right-hand operand is used as the ``value``, and the 5505 key-value pair is stored in the record instance. 5506 5507.. index:: 5508 operand 5509 record access expression 5510 access expression 5511 record indexing expression 5512 indexing expression 5513 object reference subexpression 5514 index subexpression 5515 assignment expression 5516 evaluation 5517 value 5518 key-value pair 5519 record instance 5520 normal completion 5521 abrupt completion 5522 key 5523 record instance 5524 5525If none of the above is true, then the following three steps are required: 5526 5527#. Left-hand operand is evaluated to produce a variable. If the 5528 evaluation completes abruptly, then so does the assignment expression. 5529 In that case, the right-hand operand is not evaluated, and the assignment 5530 does not occur. 5531 5532#. If the evaluation completes normally, then the right-hand operand is 5533 evaluated. If the evaluation completes abruptly, then so does the assignment 5534 expression. In that case, the assignment does not occur. 5535 5536#. If that evaluation completes normally, then the value of the right-hand 5537 operand is converted to the type of the left-hand variable. 5538 In that case, the result of the conversion is stored into the variable. 5539 A :index:`compile-time error` occurs if the type of the left-hand variable 5540 is one of the following: 5541 5542 - ``readonly`` array (see :ref:`Readonly Parameters`), while the 5543 converted type of the right-hand operand is a non-``readonly`` array; 5544 - ``readonly`` tuple (see :ref:`Readonly Parameters`), while the 5545 converted type of the right-hand operand is a non-``readonly`` tuple. 5546 5547.. index:: 5548 evaluation 5549 assignment expression 5550 assignment 5551 abrupt completion 5552 normal completion 5553 conversion 5554 variable 5555 expression 5556 readonly array 5557 readonly tuple 5558 converted type 5559 5560| 5561 5562.. _Compound Assignment Operators: 5563 5564Compound Assignment Operators 5565============================= 5566 5567.. meta: 5568 frontend_status: Done 5569 5570A compound assignment expression in the form *E1 op= E2* is equivalent to 5571*E1 = ((E1) op (E2)) as T*, where ``T`` is the type of *E1*, except that *E1* 5572is evaluated only once. This expression can be evaluated at runtime in one 5573of the following ways: 5574 55751. If the left-hand operand expression is not an indexing expression: 5576 5577 - The left-hand operand is evaluated to produce a variable. If the 5578 evaluation completes abruptly, then so does the assignment expression. 5579 In that case, the right-hand operand is not evaluated, and the 5580 assignment does not occur. 5581 5582 - If the evaluation completes normally, then the value of the left-hand 5583 operand is saved, and the right-hand operand is evaluated. If the 5584 evaluation completes abruptly, then so does the assignment expression. 5585 In that case, the assignment does not occur. 5586 5587 - If the evaluation completes normally, then the saved value of the 5588 left-hand variable, and the value of the right-hand operand are 5589 used to perform the binary operation as indicated by the compound 5590 assignment operator. If the operation completes abruptly, then so 5591 does the assignment expression. 5592 In that case, the assignment does not occur. 5593 5594 - If the evaluation completes normally, then the result of the binary 5595 operation converts to the type of the left-hand variable. 5596 The result of such conversion is stored into the variable. 5597 5598.. index:: 5599 compound assignment operator 5600 assignment operator 5601 evaluation 5602 expression 5603 runtime 5604 operand 5605 indexing expression 5606 variable 5607 assignment 5608 abrupt completion 5609 normal completion 5610 assignment expression 5611 binary operation 5612 conversion 5613 56142. If the left-hand operand expression is an array access expression (see 5615 :ref:`Array Indexing Expression`), then: 5616 5617 - Array reference subexpression of the left-hand operand is 5618 evaluated. If the evaluation completes abruptly, then so does 5619 the assignment expression. 5620 In that case, the right-hand operand and the index subexpression 5621 are not evaluated, and the assignment does not occur. 5622 5623 - If the evaluation completes normally, then the index subexpression 5624 of the left-hand operand is evaluated. If the evaluation completes 5625 abruptly, then so does the assignment expression. 5626 In that case, the right-hand operand is not evaluated, and the 5627 assignment does not occur. 5628 5629 - If the evaluation completes normally, the value of the array 5630 reference subexpression refers to an array, and the value of the 5631 index subexpression is less than zero, greater than, or equal to 5632 the *length* of the array, then ``ArrayIndexOutOfBoundsError`` is 5633 thrown. 5634 In that case, the assignment does not occur. 5635 5636 - If the evaluation completes normally, then the value of the index 5637 subexpression is used to select an array element referred to by 5638 the value of the array reference subexpression. The value of this 5639 element is saved, and then the right-hand operand is evaluated. 5640 If the evaluation completes abruptly, then so does the assignment 5641 expression. 5642 In that case, the assignment does not occur. 5643 5644 - If the evaluation completes normally, consideration must be given 5645 to the saved value of the array element selected in the previous 5646 step. While this element is a variable of type ``S``, and ``T`` is 5647 the type of the left-hand operand of the assignment operator 5648 determined at compile time: 5649 5650 - If ``T`` is a primitive type, then ``S`` is the same as ``T``. 5651 5652 The saved value of the array element, and the value of the right-hand 5653 operand are used to perform the binary operation of the compound 5654 assignment operator. 5655 5656 If this operation completes abruptly, then so does the assignment 5657 expression. 5658 In that case, the assignment does not occur. 5659 5660 If this evaluation completes normally, then the result of the binary 5661 operation converts to the type of the selected array element. 5662 The result of the conversion is stored into the array element. 5663 5664 - If ``T`` is a reference type, then it must be ``string``. 5665 5666 ``S`` must also be a ``string`` because the class ``string`` is the 5667 *final* class. The saved value of the array element, and the value of 5668 the right-hand operand are used to perform the binary operation (string 5669 concatenation) of the compound assignment operator '``+=``'. If 5670 this operation completes abruptly, then so does the assignment 5671 expression. 5672 In that case, the assignment does not occur. 5673 5674 - If the evaluation completes normally, then the ``string`` result of 5675 the binary operation is stored into the array element. 5676 5677.. index:: 5678 expression 5679 operand 5680 access expression 5681 array indexing expression 5682 indexing expression 5683 array reference subexpression 5684 reference subexpression 5685 evaluation 5686 abrupt completion 5687 normal completion 5688 index subexpression 5689 assignment expression 5690 array 5691 array length 5692 string 5693 primitive type 5694 reference subexpression 5695 error 5696 assignment 5697 index subexpression 5698 primitive type 5699 evaluation 5700 binary operation 5701 conversion 5702 array element 5703 57043. If the left-hand operand expression is a record access expression (see 5705 :ref:`Record Indexing Expression`): 5706 5707 - The object reference subexpression of the left-hand operand is 5708 evaluated. If this evaluation completes abruptly, then so does the 5709 assignment expression. 5710 In that case, the right-hand operand and the index subexpression are 5711 not evaluated, and the assignment does not occur. 5712 5713 - If this evaluation completes normally, then the index subexpression of 5714 the left-hand operand is evaluated. If the evaluation completes 5715 abruptly, then so does the assignment expression. 5716 In that case, the right-hand operand is not evaluated, and the 5717 assignment does not occur. 5718 5719 - If this evaluation completes normally, the value of the object 5720 reference subexpression and the value of index subexpression are saved, 5721 then the right-hand operand is evaluated. If the evaluation completes 5722 abruptly, then so does the assignment expression. 5723 In that case, the assignment does not occur. 5724 5725 - If this evaluation completes normally, the saved values of the 5726 object reference subexpression and index subexpression (as the *key*) 5727 are used to get the *value* that is mapped to the *key* (see 5728 :ref:`Record Indexing Expression`), then this *value* and the value 5729 of the right-hand operand are used to perform the binary operation as 5730 indicated by the compound assignment operator. If the operation 5731 completes abruptly, then so does the assignment expression. 5732 In that case, the assignment does not occur. 5733 5734 - If the evaluation completes normally, then the result of the binary 5735 operation is stored as the key-value pair in the record instance 5736 (as in :ref:`Simple Assignment Operator`). 5737 5738.. index:: 5739 record access expression 5740 operand expression 5741 record indexing expression 5742 object reference subexpression 5743 evaluation 5744 assignment expression 5745 abrupt completion 5746 normal completion 5747 assignment 5748 object reference subexpression 5749 reference subexpression 5750 index subexpression 5751 key 5752 key-value pair 5753 record indexing expression 5754 indexing expression 5755 record instance 5756 value 5757 compound assignment operator 5758 binary operation 5759 5760| 5761 5762.. _Conditional Expressions: 5763 5764Conditional Expressions 5765*********************** 5766 5767.. meta: 5768 frontend_status: Done 5769 todo: implement full LUB support (now only basic LUB implemented) 5770 5771The conditional expression '``? :``' uses the boolean value of the first 5772expression to decide which of the other two expressions to evaluate: 5773 5774.. code-block:: abnf 5775 5776 conditionalExpression: 5777 expression '?' expression ':' expression 5778 ; 5779 5780The conditional operator '``? :``' groups right-to-left (i.e., 5781:math:`a?b:c?d:e?f:g` and :math:`a?b:(c?d:(e?f:g))` have the same meaning). 5782 5783The conditional operator '``? :``' consists of three operand expressions 5784with the separators '``?``' between the first and the second, and 5785'``:``' between the second and the third expression. 5786 5787A :index:`compile-time error` occurs if the first expression is not of type 5788``boolean`` or ``Boolean``. 5789 5790.. index:: 5791 conditional expression 5792 boolean value 5793 expression 5794 conditional operator 5795 operand 5796 boolean type 5797 Boolean type 5798 5799Type of the conditional expression is determined as the union of types of the 5800second and the third expressions further normalized in accordance with the 5801process discussed in :ref:`Union Types Normalization`. If the second and the 5802third expressions are of the same type, then this is the type of the 5803conditional expression. 5804 5805The following steps are performed as the evaluation of a conditional expression 5806occurs at runtime: 5807 5808#. The operand expression of a conditional expression is evaluated first. 5809 The unboxing conversion (see :ref:`Unboxing Conversions`) is performed on 5810 the result if necessary. If the unboxing conversion fails, then so does the 5811 evaluation of the conditional expression. 5812 5813#. If the value of the first operand is ``true``, then the second operand 5814 expression is evaluated. Otherwise, the third operand expression is 5815 evaluated. The result of successful evaluation is the result of the 5816 conditional expression. 5817 5818The examples below represent different scenarios with standalone expressions: 5819 5820.. code-block:: typescript 5821 :linenos: 5822 5823 class A {} 5824 class B extends A {} 5825 5826 condition ? new A() : new B() // A | B => A 5827 5828 condition ? 5 : 6 // int 5829 5830 condition ? "5" : 6 // "5" | Int 5831 5832.. index:: 5833 conditional expression 5834 normalization 5835 union type 5836 evaluation 5837 operand expression 5838 unboxing conversion 5839 conversion 5840 standalone expression 5841 5842| 5843 5844.. _String Interpolation Expressions: 5845 5846String Interpolation Expressions 5847******************************** 5848 5849.. meta: 5850 frontend_status: Done 5851 5852A '*string interpolation expression*' is a multiline string literal (a string 5853literal delimited with backticks, see :ref:`Multiline String Literal` for 5854details) that contains at least one *embedded expression*: 5855 5856.. code-block:: abnf 5857 5858 stringInterpolation: 5859 '`' (BacktickCharacter | embeddedExpression)* '`' 5860 ; 5861 5862 embeddedExpression: 5863 '${' expression '}' 5864 ; 5865 5866An '*embedded expression*' is an expression specified inside curly braces 5867preceded by the *dollar sign* '``$``'. A string interpolation expression is of 5868type ``string`` (see :ref:`Type String`). 5869 5870When evaluating a *string interpolation expression*, the result of each 5871embedded expression substitutes that embedded expression. An embedded 5872expression must be of type ``string``. Otherwise, the implicit conversion 5873to ``string`` takes place in the same way as with the string concatenation 5874operator (see :ref:`String Concatenation`): 5875 5876.. index:: 5877 string interpolation expression 5878 multiline string 5879 string literal 5880 backtick 5881 curly brace 5882 concatenation 5883 embedded expression 5884 concatenation operator 5885 implicit conversion 5886 embedded expression 5887 5888.. code-block:: typescript 5889 :linenos: 5890 5891 let a = 2 5892 let b = 2 5893 console.log(`The result of ${a} * ${b} is ${a * b}`) 5894 // prints: The result of 2 * 2 is 4 5895 5896The string concatenation operator can be used to rewrite the above example 5897as follows: 5898 5899.. code-block:: typescript 5900 :linenos: 5901 5902 let a = 2 5903 let b = 2 5904 console.log("The result of " + a + " * " + b + " is " + a * b) 5905 5906An embedded expression can contain nested multiline strings. 5907 5908.. index:: 5909 string concatenation operator 5910 nested multiline string 5911 multiline string 5912 embedded expression 5913 5914| 5915 5916.. _Lambda Expressions: 5917 5918Lambda Expressions 5919****************** 5920 5921.. meta: 5922 frontend_status: Done 5923 5924*Lambda expression* fully defines an instance of a function type (see 5925:ref:`Function Types`) by providing optional ``async`` mark, type parameters 5926(see :ref:`Type Parameters`), mandatory lambda signature, and its body. The 5927definition of *lambda expression* is generally similar to that of a function 5928declaration (see :ref:`Function Declarations`), except that a lambda expression 5929has no function name specified, and can have types of parameters omitted: 5930 5931.. code-block:: abnf 5932 5933 lambdaExpression: 5934 ('async'|typeParameters)? lambdaSignature '=>' lambdaBody 5935 ; 5936 5937 lambdaBody: 5938 expression | block 5939 ; 5940 5941 lambdaSignature: 5942 lambdaParameters returnType? throwMark? 5943 ; 5944 5945 lambdaParameters: 5946 '(' lambdaParameterList? ')' 5947 | identifier 5948 ; 5949 5950 lambdaParameterList: 5951 lambdaParameter (',' lambdaParameter)* 5952 (',' lambdaOptionalParameters|lambdaRestParameter)? 5953 | lambdaRestParameter 5954 | optionalParameters 5955 ; 5956 5957 lambdaParameter: 5958 identifier (':' 'readonly'? type)? 5959 ; 5960 5961 lambdaRestParameter: 5962 '...' lambdaParameter 5963 ; 5964 5965 lambdaOptionalParameters: 5966 lambdaOptionalParameter (',' lambdaOptionalParameter) 5967 ; 5968 5969 lambdaOptionalParameter: 5970 identifier '?' (':' 'readonly'? type)? 5971 ; 5972 5973.. index:: 5974 lambda expression 5975 instance 5976 function type 5977 async mark 5978 type parameter 5979 lambda signature 5980 function declaration 5981 5982The examples of usage are presented below: 5983 5984.. code-block:: typescript 5985 :linenos: 5986 5987 (x: number): number => { return Math.sin(x) } // block as lambda body 5988 (x: number) => Math.sin(x) // expression as lambda body 5989 <T> (x: T, y: T) => { let local = x } // generic lambda 5990 e => e // shortest form of lambda 5991 p1, p2 => p1 + p2 5992 5993 function foo<T> (a: (p1: T, ...p2: T[]) => T) {} 5994 // All calls to foo pass valid lambda expressions in different forms 5995 foo (e => e) 5996 foo ((e1, e2) => e1) 5997 foo ((e1, e2: Object) => e1) 5998 foo ((e1: Object, e2) => e1) 5999 foo ((e1: Object, e2, e3) => e1) 6000 foo ((e1: Object, ...e2) => e1) 6001 6002 foo (<Object>(e1: Object, e2: Object) => e1) 6003 6004 function bar<T> (a: (...p: T[]) => T) {} 6005 // Type can be omitted for the rest parameter 6006 bar ((...e) => e) 6007 6008 6009 function goo<T> (a: (p?: T) => T) {} 6010 // Type can be omitted for the optional parameter 6011 goo ((e?) => e) 6012 6013 6014A *lambda expression* evaluation creates an instance of a function type (see 6015:ref:`Function Types`) as described in detail in 6016:ref:`Runtime Evaluation of Lambda Expressions`. 6017 6018.. index:: 6019 lambda expression 6020 function type 6021 instance 6022 6023| 6024 6025.. _Lambda Signature: 6026 6027Lambda Signature 6028================ 6029 6030.. meta: 6031 frontend_status: Done 6032 6033Similarly to function declarations (see :ref:`Function Declarations`), 6034*lambda signatures* are composed of formal parameters with optional types, 6035optional return types, and ``throw``/``rethrow`` marks as defined in a lambda 6036expression. 6037 6038See :ref:`Scopes` for the specification of the scope, and 6039:ref:`Shadowing by Parameter` for the shadowing details of formal parameter 6040declarations. 6041 6042A :index:`compile-time error` occurs if: 6043 6044- A lambda expression declares two formal parameters with the same name. 6045- A formal parameter contains no type provided, and the type cannot be derived 6046 by type inference. 6047 6048 6049See :ref:`Throwing Functions` for the details of ``throws``, and 6050:ref:`Rethrowing Functions` for the details of ``rethrows`` marks. 6051 6052 6053.. index:: 6054 lambda signature 6055 return type 6056 lambda expression 6057 function declaration 6058 scope 6059 shadow parameter 6060 shadowing 6061 parameter declaration 6062 compile-time error 6063 evaluation 6064 argument expression 6065 initialization 6066 variable 6067 execution 6068 lambda body 6069 throws mark 6070 rethrows mark 6071 throwing function 6072 rethrowing function 6073 6074| 6075 6076.. _Lambda Body: 6077 6078Lambda Body 6079=========== 6080 6081.. meta: 6082 frontend_status: Done 6083 6084*Lambda body* can be a single expression or a block (see :ref:`Block`). 6085Similarly to the body of a method or a function, a lambda body describes the 6086code to be executed when a lambda expression call occurs (see 6087:ref:`Function Call Expression`). 6088 6089The meanings of names, and of the keywords ``this`` and ``super`` (along with 6090the accessibility of the referred declarations) are the same as in the 6091surrounding context. However, lambda parameters introduce new names. 6092 6093If a *lambda body* is a single expression, then it is equivalent to the block 6094with one return statement that returns that single expression 6095*{ return singleExpression }*. 6096 6097If any local variable or formal parameter of the surrounding context is 6098used but not declared in a lambda body, then the local variable or formal 6099parameter is *captured* by the lambda. 6100 6101If an instance member of the surrounding type is used in the lambda body 6102defined in a method, then ``this`` is *captured* by the lambda. 6103 6104A :index:`compile-time error` occurs if a local variable is used in a lambda 6105body but is neither declared in nor assigned before it. 6106 6107.. index:: 6108 lambda body 6109 keyword this 6110 keyword super 6111 runtime 6112 evaluation 6113 lambda expression 6114 method body 6115 function body 6116 lambda call 6117 surrounding context 6118 name 6119 access 6120 accessibility 6121 referred declaration 6122 expression 6123 value-compatible block 6124 normal completion 6125 captured by lambda 6126 surrounding context 6127 local variable 6128 lambda body block 6129 instance member 6130 surrounding type 6131 return expression 6132 execution 6133 compile-time error 6134 assignment 6135 6136| 6137 6138.. _Lambda Expression Type: 6139 6140Lambda Expression Type 6141====================== 6142 6143.. meta: 6144 frontend_status: Done 6145 6146*Lambda expression type* is a function type (see :ref:`Function Types`) 6147that has the following: 6148 6149- Lambda parameters (if any) as parameters of the function type; and 6150 6151- Lambda return type as the return type of the function type. 6152 6153 6154**Note**: Lambda return type can be inferred from the *lambda body*. 6155 6156.. index:: 6157 lambda expression type 6158 function type 6159 lambda parameter 6160 lambda return type 6161 inference 6162 lambda body 6163 6164| 6165 6166.. _Runtime Evaluation of Lambda Expressions: 6167 6168Runtime Evaluation of Lambda Expressions 6169======================================== 6170 6171.. meta: 6172 frontend_status: Done 6173 6174The evaluation of a lambda expression itself never causes the execution of the 6175lambda body. If completing normally at runtime, the evaluation of a lambda 6176expression produces a reference to an allocated and initialized new instance 6177of a function type (see :ref:`Function Types`) that corresponds to the lambda 6178signature. In that case, it is similar to the evaluation of a class instance 6179creation expression (see :ref:`New Expressions`). 6180 6181If the available space is not sufficient for a new instance to be created, 6182then the evaluation of the lambda expression completes abruptly, and 6183``OutOfMemoryError`` is thrown. 6184 6185During a lambda expression evaluation, the captured values of the 6186lambda expression are saved to the internal state of the created instance. 6187 6188.. index:: 6189 runtime 6190 evaluation 6191 lambda expression 6192 execution 6193 normal completion 6194 instance creation expression 6195 initialization 6196 allocation 6197 instance 6198 class 6199 abrupt completion 6200 error 6201 captured value 6202 lambda internal state 6203 6204+-----------------------------------------------+--------------+ 6205| **Source Fragment** | **Output** | 6206+===============================================+==============+ 6207| .. code-block:: typescript || | 6208| :linenos: | | 6209| | | 6210| function foo() { | | 6211| let y: int = 1 | 2 | 6212| let x = () => { return y+1 } | | 6213| console.log(x()) | | 6214| } | | 6215+-----------------------------------------------+--------------+ 6216 6217The variable 'y' is *captured* by the lambda. 6218 6219The captured variable is not a copy of the original variable. If the 6220value of the variable captured by the lambda changes, then the original 6221variable is implied to change: 6222 6223.. index:: 6224 captured by lambda 6225 lambda 6226 variable 6227 captured variable 6228 original variable 6229 6230+-----------------------------------------------+--------------+ 6231| **Source Fragment** | **Output** | 6232+===============================================+==============+ 6233| .. code-block:: typescript || | 6234| :linenos: | | 6235| | | 6236| function foo() { | | 6237| let y: int = 1 | 1 | 6238| let x = () => { y++ } | | 6239| console.log(y) | 2 | 6240| x() | | 6241| console.log(y) | | 6242| } | | 6243+-----------------------------------------------+--------------+ 6244 6245In order to cause the lambdas behave as required, the language implementation 6246can act as follows: 6247 6248- Replace primitive type for the corresponding boxed type (x: int to x: Int) 6249 if the captured variable is of a primitive type; 6250 6251- Replace the captured variable’s type for a proxy class that contains an 6252 original reference (x: T for x: Proxy<T>; x.ref = original-ref) if that 6253 captured variable is of a non-primitive type. 6254 6255 6256If the captured variable is defined as ``const``, then neither boxing nor 6257proxying is required. 6258 6259If the captured formal parameter can be neither boxed nor proxied, then 6260the implementation can require the addition of a local variable as follows: 6261 6262.. index:: 6263 lambda 6264 implementation 6265 primitive type 6266 boxed type 6267 captured variable 6268 captured variable type 6269 non-primitive type 6270 boxing 6271 proxying 6272 local variable 6273 variable 6274 6275+-----------------------------------+-----------------------------------+ 6276| **Source Code** | **Pseudo Code** | 6277+===================================+===================================+ 6278| .. code-block:: typescript | .. code-block:: typescript | 6279| :linenos: | :linenos: | 6280| | | 6281| function foo(y: int) { | function foo(y: int) { | 6282| let x = () => { return y+1 } | let y$: Int = y | 6283| console.log(x()) | let x = () => { return y$+1 } | 6284| } | console.log(x()) | 6285| | } | 6286+-----------------------------------+-----------------------------------+ 6287 6288| 6289 6290.. _Dynamic Import Expression: 6291 6292Dynamic Import Expression 6293************************* 6294 6295.. meta: 6296 frontend_status: None 6297 6298*Dynamic import expression* allows loading a compilation unit asynchronously 6299and dynamically. 6300 6301.. code-block:: abnf 6302 6303 dynamicImportExpression: 6304 'import' '(' expression ')' 6305 ; 6306 6307The *expression* must be of type ``string`` that denotes the *path* to the 6308module to be loaded. The result of this expression is ``Promise<DynamicObject>`` 6309(see :ref:`Promise<T> Class` and :ref:`DynamicObject Type`). Methods of class 6310``Promise`` can be used to access the loaded module, or to handle an error 6311that can occur while attempting to load the module. 6312 6313.. index:: 6314 dynamic import expression 6315 compilation unit 6316 string 6317 expression 6318 path 6319 method 6320 class 6321 6322| 6323 6324.. _Constant Expressions: 6325 6326Constant Expressions 6327******************** 6328 6329.. meta: 6330 frontend_status: Done 6331 6332*Constant expressions* are expressions with values that can be evaluated at 6333compile time. 6334 6335.. code-block:: abnf 6336 6337 constantExpression: 6338 expression 6339 ; 6340 6341A *constant expression* is an expression of a predefined value type 6342(:ref:`Predefined Types`), 6343or of type ``string`` that completes normally while being composed only 6344of the following: 6345 6346- Literals of a primitive type, and literals of type ``string`` (see 6347 :ref:`Literals`); 6348 6349- Casts to primitive types, and casts to type ``string`` (see 6350 :ref:`Cast Expressions`); 6351 6352- Unary operators '``+``', '``-``', '``~``', and '``!``', but not '``++``' 6353 or '``--``' (see :ref:`Unary Plus`, :ref:`Unary Minus`, 6354 :ref:`Prefix Increment`, and :ref:`Prefix Decrement`); 6355 6356- Multiplicative operators '``*``', '``/``', and '``%``' (see 6357 :ref:`Multiplicative Expressions`); 6358 6359- Additive operators '``+``' and '``-``' (see :ref:`Additive Expressions`); 6360 6361- Shift operators '``<<``', '``>>``', and '``>>>``' (see :ref:`Shift Expressions`); 6362 6363- Relational operators '``<``', '``<=``', '``>``', and '``>=``' (see :ref:`Relational Expressions`); 6364 6365- Equality operators '``==``' and '``!=``' (see :ref:`Equality Expressions`); 6366 6367- Bitwise and logical operators '``&``', '``^``', and '``|``' (see :ref:`Bitwise and Logical Expressions`); 6368 6369- Conditional-and operator '``&&``' (see :ref:`Conditional-And Expression`), and 6370 conditional-or operator '``||``' (see :ref:`Conditional-Or Expression`); 6371 6372- Ternary conditional operator '``? :``' (see :ref:`Conditional Expressions`); 6373 6374- Parenthesized expressions (see :ref:`Parenthesized Expression`) that contain 6375 constant expressions; 6376 6377- Simple names or qualified names that refer to constant variables with 6378 compile-time expressions as initializers. 6379 6380.. index:: 6381 constant expression 6382 primitive type 6383 string 6384 normal completion 6385 literal 6386 cast expression 6387 unary operator 6388 increment operator 6389 decrement operator 6390 prefix 6391 multiplicative operator 6392 multiplicative expression 6393 shift operator 6394 relational operator 6395 equality operator 6396 bitwise operator 6397 logical operator 6398 ternary conditional operator 6399 conditional-and operator 6400 conditional-or operator 6401 parenthesized expression 6402 constant expression 6403 simple name 6404 constant variable 6405 qualified name 6406 initializer 6407 6408 6409 6410.. raw:: pdf 6411 6412 PageBreak 6413 6414