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