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