12 ECMAScript 언어: Lexical Grammar

ECMAScript Script 또는 Module의 source text는 먼저 token, line terminator, comment 또는 white space인 input element의 sequence로 converted됩니다. source text는 left to right로 scanned되며, 가능한 가장 긴 code point sequence를 반복적으로 next input element로 취합니다.

lexical input element의 identification이 input element를 consuming하는 syntactic grammar context에 sensitive한 여러 situation이 있습니다. 이는 lexical grammar에 대해 multiple goal symbol을 require합니다. InputElementHashbangOrRegExp goal은 Script 또는 Module의 start에서 사용됩니다. InputElementRegExpOrTemplateTail goal은 RegularExpressionLiteral, TemplateMiddle 또는 TemplateTail이 permitted되는 syntactic grammar context에서 사용됩니다. InputElementRegExp goal symbolRegularExpressionLiteral은 permitted되지만 TemplateMiddleTemplateTail도 permitted되지 않는 모든 syntactic grammar context에서 사용됩니다. InputElementTemplateTail goal은 TemplateMiddle 또는 TemplateTail은 permitted되지만 RegularExpressionLiteral은 permitted되지 않는 모든 syntactic grammar context에서 사용됩니다. 그 밖의 모든 context에서는 InputElementDiv가 lexical goal symbol로 사용됩니다.

Note

multiple lexical goal의 사용은 automatic semicolon insertion에 영향을 줄 lexical ambiguity가 없음을 ensure합니다. 예를 들어 leading division 또는 division-assignment와 leading RegularExpressionLiteral이 둘 다 permitted되는 syntactic grammar context는 없습니다. 이는 semicolon insertion(12.10 참조)의 영향을 받지 않습니다; 다음과 같은 예에서:

a = b
/hi/g.exec(c).map(d);

LineTerminator 뒤의 first non-whitespace, non-comment code point가 U+002F (SOLIDUS)이고 syntactic context가 division 또는 division-assignment를 allow하면, LineTerminator에서 semicolon은 inserted되지 않습니다. 즉, 위 example은 다음과 같은 방식으로 interpreted됩니다:

a = b / hi / g.exec(c).map(d);

Syntax

InputElementDiv :: WhiteSpace LineTerminator Comment CommonToken DivPunctuator RightBracePunctuator InputElementRegExp :: WhiteSpace LineTerminator Comment CommonToken RightBracePunctuator RegularExpressionLiteral InputElementRegExpOrTemplateTail :: WhiteSpace LineTerminator Comment CommonToken RegularExpressionLiteral TemplateSubstitutionTail InputElementTemplateTail :: WhiteSpace LineTerminator Comment CommonToken DivPunctuator TemplateSubstitutionTail InputElementHashbangOrRegExp :: WhiteSpace LineTerminator Comment CommonToken HashbangComment RegularExpressionLiteral

12.1 Unicode Format-Control Characters

Unicode format-control character(즉, LEFT-TO-RIGHT MARK 또는 RIGHT-TO-LEFT MARK 같은 Unicode Character Database의 category “Cf” 안의 character)는 이를 위한 higher-level protocol(mark-up language 등)이 없을 때 text range의 formatting을 control하는 데 사용되는 control code입니다.

editing과 display를 facilitate하기 위해 source text 안에서 format-control character를 allow하는 것은 useful합니다. 모든 format control character는 comment 안에서, 그리고 string literal, template literal, regular expression literal 안에서 사용될 수 있습니다.

U+FEFF (ZERO WIDTH NO-BREAK SPACE)는 primarily text의 start에서 그것을 Unicode로 mark하고 text의 encoding과 byte order의 detection을 allow하는 데 사용되는 format-control character입니다. 이 purpose로 intended된 <ZWNBSP> character는 때때로 text의 start 뒤에도 나타날 수 있습니다. 예를 들어 file을 concatenating한 result로 그렇습니다. ECMAScript source text에서 <ZWNBSP> code point는 comment, string literal, template literal, regular expression literal 밖에서는 white space character(12.2 참조)로 treated됩니다.

12.2 White Space

White space code point는 source text readability를 improve하고 token(indivisible lexical unit)을 서로 separate하는 데 사용되지만, otherwise insignificant합니다. White space code point는 어떤 두 token 사이에도, input의 start 또는 end에도 occur할 수 있습니다. White space code point는 StringLiteral, RegularExpressionLiteral, Template 또는 TemplateSubstitutionTail 안에서도 occur할 수 있으며, 여기서는 literal value의 part를 forming하는 significant code point로 considered됩니다. 또한 Comment 안에서도 occur할 수 있지만, 그 밖의 어떤 kind의 token 안에는 appear할 수 없습니다.

ECMAScript white space code point는 Table 31에 listed되어 있습니다.

Table 31: White Space Code Points
Code Points Name Abbreviation
U+0009 CHARACTER TABULATION <TAB>
U+000B LINE TABULATION <VT>
U+000C FORM FEED (FF) <FF>
U+FEFF ZERO WIDTH NO-BREAK SPACE <ZWNBSP>
general category “Space_Separator” 안의 모든 code point <USP>
Note 1

U+0020 (SPACE) 및 U+00A0 (NO-BREAK SPACE) code point는 <USP>의 part입니다.

Note 2

Table 31에 listed된 code point 외에는, ECMAScript WhiteSpace는 Unicode “White_Space” property를 가지지만 general category “Space_Separator”(“Zs”)로 classified되지 않은 모든 code point를 intentionally excludes합니다.

Syntax

WhiteSpace :: <TAB> <VT> <FF> <ZWNBSP> <USP>

12.3 Line Terminators

white space code point와 마찬가지로, line terminator code point는 source text readability를 improve하고 token(indivisible lexical unit)을 서로 separate하는 데 사용됩니다. 그러나 white space code point와 달리, line terminator는 syntactic grammar의 behaviour에 어느 정도 influence를 가집니다. 일반적으로 line terminator는 어떤 두 token 사이에도 occur할 수 있지만, syntactic grammar에 의해 forbidden되는 몇몇 place가 있습니다. Line terminator는 automatic semicolon insertion(12.10) process에도 affect합니다. line terminator는 StringLiteral, Template 또는 TemplateSubstitutionTail을 제외한 어떤 token 안에도 occur할 수 없습니다. <LF> 및 <CR> line terminator는 LineContinuation의 part인 경우를 제외하고 StringLiteral token 안에 occur할 수 없습니다.

line terminator는 MultiLineComment 안에는 occur할 수 있지만 SingleLineComment 안에는 occur할 수 없습니다.

Line terminator는 regular expression 안의 \s class가 match하는 white space code point의 set에 included됩니다.

ECMAScript line terminator code point는 Table 32에 listed되어 있습니다.

Table 32: Line Terminator Code Points
Code Point Unicode Name Abbreviation
U+000A LINE FEED (LF) <LF>
U+000D CARRIAGE RETURN (CR) <CR>
U+2028 LINE SEPARATOR <LS>
U+2029 PARAGRAPH SEPARATOR <PS>

Table 32 안의 Unicode code point만 line terminator로 treated됩니다. 다른 new line 또는 line breaking Unicode code point는 line terminator로 treated되지 않지만, Table 31에 listed된 requirement를 meet하면 white space로 treated됩니다. sequence <CR><LF>는 commonly line terminator로 사용됩니다. 이는 line number를 reporting하기 위한 purpose에서는 single SourceCharacter로 considered되어야 합니다.

Syntax

LineTerminator :: <LF> <CR> <LS> <PS> LineTerminatorSequence :: <LF> <CR> [lookahead ≠ <LF>] <LS> <PS> <CR> <LF>

12.4 Comments

Comment는 single-line 또는 multi-line일 수 있습니다. Multi-line comment는 nest할 수 없습니다.

single-line comment는 LineTerminator code point를 제외한 어떤 Unicode code point든 contain할 수 있고, token은 항상 가능한 한 길다는 general rule 때문에, single-line comment는 항상 // marker부터 line의 end까지의 모든 code point로 구성됩니다. 그러나 line end의 LineTerminator는 single-line comment의 part로 considered되지 않습니다; 이는 lexical grammar에 의해 separately recognized되고 syntactic grammar를 위한 input element stream의 part가 됩니다. 이 point는 매우 important합니다. 왜냐하면 single-line comment의 presence 또는 absence가 automatic semicolon insertion process에 affect하지 않음을 imply하기 때문입니다(12.10 참조).

Comment는 white space처럼 behave하며 discarded됩니다. 단, MultiLineComment가 line terminator code point를 contain하면, syntactic grammar에 의한 parsing purpose에서 전체 comment가 LineTerminator로 considered됩니다.

Syntax

Comment :: MultiLineComment SingleLineComment MultiLineComment :: /* MultiLineCommentCharsopt */ MultiLineCommentChars :: MultiLineNotAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt PostAsteriskCommentChars :: MultiLineNotForwardSlashOrAsteriskChar MultiLineCommentCharsopt * PostAsteriskCommentCharsopt MultiLineNotAsteriskChar :: SourceCharacter but not * MultiLineNotForwardSlashOrAsteriskChar :: SourceCharacter but not one of / or * SingleLineComment :: // SingleLineCommentCharsopt SingleLineCommentChars :: SingleLineCommentChar SingleLineCommentCharsopt SingleLineCommentChar :: SourceCharacter but not LineTerminator

이 section의 여러 production은 section B.1.1에서 alternative definition이 given됩니다

12.5 Hashbang Comments

Hashbang Comment는 location-sensitive이며 다른 type의 comment처럼 syntactic grammar를 위한 input element stream에서 discarded됩니다.

Syntax

HashbangComment :: #! SingleLineCommentCharsopt

12.6 Tokens

Syntax

CommonToken :: IdentifierName PrivateIdentifier Punctuator NumericLiteral StringLiteral Template Note

DivPunctuator, RegularExpressionLiteral, RightBracePunctuator, TemplateSubstitutionTail production은 CommonToken production에 included되지 않은 additional token을 derive합니다.

12.7 Names and Keywords

IdentifierNameReservedWord는 Unicode Standard Annex #31, Identifier and Pattern Syntax에 given된 Default Identifier Syntax에 따라 interpreted되는 token이며, 약간의 modification이 있습니다. ReservedWordIdentifierName의 enumerated subset입니다. syntactic grammar는 IdentifierReservedWord가 아닌 IdentifierName으로 define합니다. Unicode identifier grammar는 Unicode Standard가 specified한 character property에 기반합니다. Unicode Standard의 latest version에서 specified된 category 안의 Unicode code point는 모든 conforming ECMAScript implementation에 의해 해당 category 안에 있는 것으로 treated되어야 합니다. ECMAScript implementation은 Unicode Standard의 later edition에 defined된 identifier code point를 recognize할 수 있습니다.

Note 1

이 standard는 specific code point addition을 specify합니다: U+0024 (DOLLAR SIGN) 및 U+005F (LOW LINE)는 IdentifierName 안의 어디에서나 permitted됩니다.

Syntax

PrivateIdentifier :: # IdentifierName IdentifierName :: IdentifierStart IdentifierName IdentifierPart IdentifierStart :: IdentifierStartChar \ UnicodeEscapeSequence IdentifierPart :: IdentifierPartChar \ UnicodeEscapeSequence IdentifierStartChar :: UnicodeIDStart $ _ IdentifierPartChar :: UnicodeIDContinue $ AsciiLetter :: one of a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z UnicodeIDStart :: any Unicode code point with the Unicode property “ID_Start” UnicodeIDContinue :: any Unicode code point with the Unicode property “ID_Continue”

nonterminal UnicodeEscapeSequence의 definition은 12.9.4에 given됩니다.

Note 2

nonterminal IdentifierPartUnicodeIDContinue를 통해 _를 derive합니다.

Note 3

Unicode property “ID_Start” 및 “ID_Continue”를 가진 code point의 set은 각각 Unicode property “Other_ID_Start” 및 “Other_ID_Continue”를 가진 code point를 포함합니다.

12.7.1 Identifier Names

Unicode escape sequence는 IdentifierName 안에서 permitted되며, 여기서 UnicodeEscapeSequenceIdentifierCodePoint와 equal한 single Unicode code point를 contribute합니다. UnicodeEscapeSequence 앞의 \는 어떤 code point도 contribute하지 않습니다. UnicodeEscapeSequence는 otherwise invalid일 code point를 IdentifierName에 contribute하는 데 사용할 수 없습니다. 다시 말해, \ UnicodeEscapeSequence sequence가 그것이 contribute하는 SourceCharacter로 replaced되면, result는 original IdentifierName과 exact same sequence의 SourceCharacter element를 가지는 valid IdentifierName이어야 합니다. 이 명세 안의 IdentifierName에 대한 모든 interpretation은 특정 code point를 contribute하기 위해 escape sequence가 사용되었는지 여부와 관계없이 actual code point에 based합니다.

Unicode Standard에 따라 canonically equivalent한 두 IdentifierName은, 각 UnicodeEscapeSequence의 replacement 후 exact same sequence의 code point로 represented되지 않는 한 not equal입니다.

12.7.1.1 Static Semantics: Early Errors

IdentifierStart :: \ UnicodeEscapeSequence IdentifierPart :: \ UnicodeEscapeSequence

12.7.1.2 Static Semantics: IdentifierCodePoints

The syntax-directed operation IdentifierCodePoints takes no arguments and returns a List of code points. It is defined piecewise over the following productions:

IdentifierName :: IdentifierStart
  1. codePointIdentifierStartIdentifierCodePoint로 둔다.
  2. « codePoint »를 반환한다.
IdentifierName :: IdentifierName IdentifierPart
  1. codePoints 를 derived IdentifierNameIdentifierCodePoints로 둔다.
  2. codePointIdentifierPartIdentifierCodePoint로 둔다.
  3. codePoints 와 « codePoint »의 list-concatenation을 반환한다.

12.7.1.3 Static Semantics: IdentifierCodePoint

The syntax-directed operation IdentifierCodePoint takes no arguments and returns a code point. It is defined piecewise over the following productions:

IdentifierStart :: IdentifierStartChar
  1. IdentifierStartChar에 matched된 code point를 반환한다.
IdentifierPart :: IdentifierPartChar
  1. IdentifierPartChar에 matched된 code point를 반환한다.
UnicodeEscapeSequence :: u Hex4Digits
  1. numeric value가 Hex4Digits의 MV인 code point를 반환한다.
UnicodeEscapeSequence :: u{ CodePoint }
  1. numeric value가 CodePoint의 MV인 code point를 반환한다.

12.7.2 Keywords and Reserved Words

keywordIdentifierName과 match되지만 syntactic use도 가지는 token입니다; 즉, 어떤 syntactic production 안에서 fixed width font로 literally appear합니다. ECMAScript의 keyword에는 if, while, async, await 및 many others가 포함됩니다.

reserved word는 identifier로 사용할 수 없는 IdentifierName입니다. 많은 keyword는 reserved word이지만, 일부는 그렇지 않으며, 일부는 certain context에서만 reserved됩니다. ifwhile은 reserved word입니다. await는 async function과 module 안에서만 reserved됩니다. async는 reserved되지 않습니다; variable name 또는 statement label로 restriction 없이 사용할 수 있습니다.

이 명세는 어떤 name이 valid identifier이고 어떤 것이 reserved word인지 specify하기 위해 grammatical production과 early error rule의 combination을 사용합니다. 아래 ReservedWord list 안의 모든 token은 awaityield를 제외하고 unconditionally reserved됩니다. awaityield에 대한 exception은 parameterized syntactic production을 사용하여 13.1에 specified되어 있습니다. Lastly, several early error rule이 valid identifier의 set을 restrict합니다. 13.1.1, 14.3.1.1, 14.7.5.1, 15.7.1를 참조하십시오. 요약하면, identifier name에는 다섯 category가 있습니다:

  • Math, window, toString, _처럼 always identifier로 allowed되고 keyword가 아닌 것;

  • identifier로 never allowed되지 않는 것, 즉 awaityield를 제외하고 아래 listed된 ReservedWord;

  • contextually identifier로 allowed되는 것, 즉 awaityield;

  • strict mode code에서 contextually identifier로 disallowed되는 것: let, static, implements, interface, package, private, protected, public;

  • always identifier로 allowed되지만 Identifier가 allowed되지 않는 place에서 certain syntactic production 안의 keyword로도 appear하는 것: as, async, from, get, meta, of, set, target.

conditional keyword 또는 contextual keyword라는 term은 때때로 last three category에 속해 일부 context에서는 identifier로, 다른 context에서는 keyword로 사용될 수 있는 keyword를 refer하는 데 사용됩니다.

Syntax

ReservedWord :: one of await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield Note 1

5.1.5에 따르면, grammar 안의 keyword는 specific SourceCharacter element의 literal sequence와 match합니다. keyword 안의 code point는 \ UnicodeEscapeSequence로 expressed될 수 없습니다.

IdentifierName\ UnicodeEscapeSequence를 contain할 수 있지만, els\u{65}라고 spelling하여 “else”라는 variable을 declare하는 것은 possible하지 않습니다. 13.1.1early error rule은 reserved word와 같은 StringValue를 가진 identifier를 rule out합니다.

Note 2

enum은 이 명세에서 현재 keyword로 사용되지 않습니다. 이는 future language extension에서 keyword로 use하기 위해 set aside된 future reserved word입니다.

마찬가지로, implements, interface, package, private, protected, publicstrict mode code에서 future reserved word입니다.

Note 3

name argumentseval은 keyword가 아니지만, strict mode code에서 일부 restriction의 subject입니다. 13.1.1, 8.6.4, 15.2.1, 15.5.1, 15.6.1, 15.8.1를 참조하십시오.

12.8 Punctuators

Syntax

Punctuator :: OptionalChainingPunctuator OtherPunctuator OptionalChainingPunctuator :: ?. [lookahead ∉ DecimalDigit] OtherPunctuator :: one of { ( ) [ ] . ... ; , < > <= >= == != === !== + - * % ** ++ -- << >> >>> & | ^ ! ~ && || ?? ? : = += -= *= %= **= <<= >>= >>>= &= |= ^= &&= ||= ??= => DivPunctuator :: / /= RightBracePunctuator :: }

12.9 Literals

12.9.1 Null Literals

Syntax

NullLiteral :: null

12.9.2 Boolean Literals

Syntax

BooleanLiteral :: true false

12.9.3 Numeric Literals

Syntax

NumericLiteralSeparator :: _ NumericLiteral :: DecimalLiteral DecimalBigIntegerLiteral NonDecimalIntegerLiteral[+Sep] NonDecimalIntegerLiteral[+Sep] BigIntLiteralSuffix LegacyOctalIntegerLiteral DecimalBigIntegerLiteral :: 0 BigIntLiteralSuffix NonZeroDigit DecimalDigits[+Sep]opt BigIntLiteralSuffix NonZeroDigit NumericLiteralSeparator DecimalDigits[+Sep] BigIntLiteralSuffix NonDecimalIntegerLiteral[Sep] :: BinaryIntegerLiteral[?Sep] OctalIntegerLiteral[?Sep] HexIntegerLiteral[?Sep] BigIntLiteralSuffix :: n DecimalLiteral :: DecimalIntegerLiteral . DecimalDigits[+Sep]opt ExponentPart[+Sep]opt . DecimalDigits[+Sep] ExponentPart[+Sep]opt DecimalIntegerLiteral ExponentPart[+Sep]opt DecimalIntegerLiteral :: 0 NonZeroDigit NonZeroDigit NumericLiteralSeparatoropt DecimalDigits[+Sep] NonOctalDecimalIntegerLiteral DecimalDigits[Sep] :: DecimalDigit DecimalDigits[?Sep] DecimalDigit [+Sep] DecimalDigits[+Sep] NumericLiteralSeparator DecimalDigit DecimalDigit :: one of 0 1 2 3 4 5 6 7 8 9 NonZeroDigit :: one of 1 2 3 4 5 6 7 8 9 ExponentPart[Sep] :: ExponentIndicator SignedInteger[?Sep] ExponentIndicator :: one of e E SignedInteger[Sep] :: DecimalDigits[?Sep] + DecimalDigits[?Sep] - DecimalDigits[?Sep] BinaryIntegerLiteral[Sep] :: 0b BinaryDigits[?Sep] 0B BinaryDigits[?Sep] BinaryDigits[Sep] :: BinaryDigit BinaryDigits[?Sep] BinaryDigit [+Sep] BinaryDigits[+Sep] NumericLiteralSeparator BinaryDigit BinaryDigit :: one of 0 1 OctalIntegerLiteral[Sep] :: 0o OctalDigits[?Sep] 0O OctalDigits[?Sep] OctalDigits[Sep] :: OctalDigit OctalDigits[?Sep] OctalDigit [+Sep] OctalDigits[+Sep] NumericLiteralSeparator OctalDigit LegacyOctalIntegerLiteral :: 0 OctalDigit LegacyOctalIntegerLiteral OctalDigit NonOctalDecimalIntegerLiteral :: 0 NonOctalDigit LegacyOctalLikeDecimalIntegerLiteral NonOctalDigit NonOctalDecimalIntegerLiteral DecimalDigit LegacyOctalLikeDecimalIntegerLiteral :: 0 OctalDigit LegacyOctalLikeDecimalIntegerLiteral OctalDigit OctalDigit :: one of 0 1 2 3 4 5 6 7 NonOctalDigit :: one of 8 9 HexIntegerLiteral[Sep] :: 0x HexDigits[?Sep] 0X HexDigits[?Sep] HexDigits[Sep] :: HexDigit HexDigits[?Sep] HexDigit [+Sep] HexDigits[+Sep] NumericLiteralSeparator HexDigit HexDigit :: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

NumericLiteral 바로 뒤의 SourceCharacterIdentifierStart 또는 DecimalDigit이어서는 안 됩니다.

Note

예: 3in은 error이며 두 input element 3in이 아닙니다.

12.9.3.1 Static Semantics: Early Errors

NumericLiteral :: LegacyOctalIntegerLiteral DecimalIntegerLiteral :: NonOctalDecimalIntegerLiteral
  • IsStrict(this production)이 true이면 Syntax Error입니다.
Note
non-strict code에서 이 syntax는 Legacy입니다.

12.9.3.2 Static Semantics: MV

numeric literal은 Number type 또는 BigInt type의 value를 나타냅니다.

12.9.3.3 Static Semantics: NumericValue

The syntax-directed operation NumericValue takes no arguments and returns a Number or a BigInt. It is defined piecewise over the following productions:

NumericLiteral :: DecimalLiteral
  1. RoundMVResult(DecimalLiteral의 MV)를 반환한다.
NumericLiteral :: NonDecimalIntegerLiteral
  1. 𝔽(NonDecimalIntegerLiteral의 MV)를 반환한다.
NumericLiteral :: LegacyOctalIntegerLiteral
  1. 𝔽(LegacyOctalIntegerLiteral의 MV)를 반환한다.
NumericLiteral :: NonDecimalIntegerLiteral BigIntLiteralSuffix
  1. NonDecimalIntegerLiteral의 MV에 대한 BigInt value를 반환한다.
DecimalBigIntegerLiteral :: 0 BigIntLiteralSuffix
  1. 0를 반환한다.
DecimalBigIntegerLiteral :: NonZeroDigit BigIntLiteralSuffix
  1. NonZeroDigit의 MV에 대한 BigInt value를 반환한다.
DecimalBigIntegerLiteral :: NonZeroDigit DecimalDigits BigIntLiteralSuffix NonZeroDigit NumericLiteralSeparator DecimalDigits BigIntLiteralSuffix
  1. nNumericLiteralSeparator의 모든 occurrence를 제외한 DecimalDigits 안의 code point 수로 둔다.
  2. mv를 (NonZeroDigit의 MV × 10n) plus DecimalDigits의 MV로 둔다.
  3. (mv)를 반환한다.

12.9.4 String Literals

Note 1

string literal은 single 또는 double quote로 enclosed된 0개 이상의 Unicode code point입니다. Unicode code point는 escape sequence로 represented될 수도 있습니다. closing quote code point, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), U+000A (LINE FEED)를 제외한 모든 code point는 string literal에 literally appear할 수 있습니다. 어떤 code point든 escape sequence의 form으로 appear할 수 있습니다. String literal은 ECMAScript String value로 evaluate됩니다. 이러한 String value를 generating할 때 Unicode code point는 11.1.1에 defined된 대로 UTF-16 encoded됩니다. Basic Multilingual Plane에 속하는 code point는 string의 single code unit element로 encoded됩니다. 그 밖의 모든 code point는 string의 two code unit element로 encoded됩니다.

Syntax

StringLiteral :: " DoubleStringCharactersopt " ' SingleStringCharactersopt ' DoubleStringCharacters :: DoubleStringCharacter DoubleStringCharactersopt SingleStringCharacters :: SingleStringCharacter SingleStringCharactersopt DoubleStringCharacter :: SourceCharacter but not one of " or \ or LineTerminator <LS> <PS> \ EscapeSequence LineContinuation SingleStringCharacter :: SourceCharacter but not one of ' or \ or LineTerminator <LS> <PS> \ EscapeSequence LineContinuation LineContinuation :: \ LineTerminatorSequence EscapeSequence :: CharacterEscapeSequence 0 [lookahead ∉ DecimalDigit] LegacyOctalEscapeSequence NonOctalDecimalEscapeSequence HexEscapeSequence UnicodeEscapeSequence CharacterEscapeSequence :: SingleEscapeCharacter NonEscapeCharacter SingleEscapeCharacter :: one of ' " \ b f n r t v NonEscapeCharacter :: SourceCharacter but not one of EscapeCharacter or LineTerminator EscapeCharacter :: SingleEscapeCharacter DecimalDigit x u LegacyOctalEscapeSequence :: 0 [lookahead ∈ { 8, 9 }] NonZeroOctalDigit [lookahead ∉ OctalDigit] ZeroToThree OctalDigit [lookahead ∉ OctalDigit] FourToSeven OctalDigit ZeroToThree OctalDigit OctalDigit NonZeroOctalDigit :: OctalDigit but not 0 ZeroToThree :: one of 0 1 2 3 FourToSeven :: one of 4 5 6 7 NonOctalDecimalEscapeSequence :: one of 8 9 HexEscapeSequence :: x HexDigit HexDigit UnicodeEscapeSequence :: u Hex4Digits u{ CodePoint } Hex4Digits :: HexDigit HexDigit HexDigit HexDigit

nonterminal HexDigit의 definition은 12.9.3에 given되어 있습니다. SourceCharacter11.1에 defined되어 있습니다.

Note 2

<LF> 및 <CR>은 empty code point sequence를 produce하는 LineContinuation의 part인 경우를 제외하고 string literal 안에 appear할 수 없습니다. string literal의 String value 안에 둘 중 하나를 include하는 proper way는 \n 또는 \u000A 같은 escape sequence를 사용하는 것입니다.

12.9.4.1 Static Semantics: Early Errors

EscapeSequence :: LegacyOctalEscapeSequence NonOctalDecimalEscapeSequence
  • IsStrict(this production)이 true이면 Syntax Error입니다.
Note 1
non-strict code에서 이 syntax는 Legacy입니다.
Note 2

string literal이 enclosing code를 strict mode로 place하는 Use Strict Directive보다 preceding할 수 있으며, implementation은 그러한 literal에 대해 위 rule을 enforce하도록 care해야 합니다. 예를 들어 다음 source text는 Syntax Error를 contain합니다:

function invalid() { "\7"; "use strict"; }

12.9.4.2 Static Semantics: SV

The syntax-directed operation SV takes no arguments and returns a String.

string literal은 String type의 value를 나타냅니다. SV는 string literal의 various part에 대한 recursive application을 통해 string literal에 대한 String value를 produce합니다. 이 process의 part로, string literal 안의 일부 Unicode code point는 아래 또는 12.9.3에 described된 대로 mathematical value를 가지는 것으로 interpreted됩니다.

Table 33: String Single Character Escape Sequences
Escape Sequence Code Unit Value Unicode Character Name Symbol
\b 0x0008 BACKSPACE <BS>
\t 0x0009 CHARACTER TABULATION <HT>
\n 0x000A LINE FEED (LF) <LF>
\v 0x000B LINE TABULATION <VT>
\f 0x000C FORM FEED (FF) <FF>
\r 0x000D CARRIAGE RETURN (CR) <CR>
\" 0x0022 QUOTATION MARK "
\' 0x0027 APOSTROPHE '
\\ 0x005C REVERSE SOLIDUS \

12.9.4.3 Static Semantics: MV

12.9.5 Regular Expression Literals

Note 1

regular expression literal은 literal이 evaluated될 때마다 RegExp object(22.2 참조)로 converted되는 input element입니다. program 안의 두 regular expression literal은 두 literal의 content가 identical하더라도 서로 ===로 compare되는 regular expression object로 evaluate되지 않습니다. RegExp object는 runtime에 new RegExp에 의해 또는 RegExp constructor를 function으로 calling하여 created될 수도 있습니다(22.2.4 참조).

아래 production은 regular expression literal의 syntax를 describe하며 input element scanner가 regular expression literal의 end를 find하는 데 사용됩니다. RegularExpressionBodyRegularExpressionFlags를 comprising하는 source text는 subsequently 더 stringent한 ECMAScript Regular Expression grammar(22.2.1)를 사용하여 다시 parsed됩니다.

implementation은 22.2.1에 defined된 ECMAScript Regular Expression grammar를 extend할 수 있지만, 아래 defined된 RegularExpressionBodyRegularExpressionFlags production이나 이러한 production이 사용하는 production을 extend해서는 안 됩니다.

Syntax

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags RegularExpressionBody :: RegularExpressionFirstChar RegularExpressionChars RegularExpressionChars :: [empty] RegularExpressionChars RegularExpressionChar RegularExpressionFirstChar :: RegularExpressionNonTerminator but not one of * or \ or / or [ RegularExpressionBackslashSequence RegularExpressionClass RegularExpressionChar :: RegularExpressionNonTerminator but not one of \ or / or [ RegularExpressionBackslashSequence RegularExpressionClass RegularExpressionBackslashSequence :: \ RegularExpressionNonTerminator RegularExpressionNonTerminator :: SourceCharacter but not LineTerminator RegularExpressionClass :: [ RegularExpressionClassChars ] RegularExpressionClassChars :: [empty] RegularExpressionClassChars RegularExpressionClassChar RegularExpressionClassChar :: RegularExpressionNonTerminator but not one of ] or \ RegularExpressionBackslashSequence RegularExpressionFlags :: [empty] RegularExpressionFlags IdentifierPartChar Note 2

Regular expression literal은 empty일 수 없습니다; empty regular expression literal을 represent하는 대신 code unit sequence //는 single-line comment를 start합니다. empty regular expression을 specify하려면 /(?:)/를 사용하십시오.

12.9.5.1 Static Semantics: BodyText

The syntax-directed operation BodyText takes no arguments and returns source text. It is defined piecewise over the following productions:

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionBody로 recognized된 source text를 반환한다.

12.9.5.2 Static Semantics: FlagText

The syntax-directed operation FlagText takes no arguments and returns source text. It is defined piecewise over the following productions:

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionFlags로 recognized된 source text를 반환한다.

12.9.6 Template Literal Lexical Components

Syntax

Template :: NoSubstitutionTemplate TemplateHead NoSubstitutionTemplate :: ` TemplateCharactersopt ` TemplateHead :: ` TemplateCharactersopt ${ TemplateSubstitutionTail :: TemplateMiddle TemplateTail TemplateMiddle :: } TemplateCharactersopt ${ TemplateTail :: } TemplateCharactersopt ` TemplateCharacters :: TemplateCharacter TemplateCharactersopt TemplateCharacter :: $ [lookahead ≠ {] \ TemplateEscapeSequence \ NotEscapeSequence LineContinuation LineTerminatorSequence SourceCharacter but not one of ` or \ or $ or LineTerminator TemplateEscapeSequence :: CharacterEscapeSequence 0 [lookahead ∉ DecimalDigit] HexEscapeSequence UnicodeEscapeSequence NotEscapeSequence :: 0 DecimalDigit DecimalDigit but not 0 x [lookahead ∉ HexDigit] x HexDigit [lookahead ∉ HexDigit] u [lookahead ∉ HexDigit] [lookahead ≠ {] u HexDigit [lookahead ∉ HexDigit] u HexDigit HexDigit [lookahead ∉ HexDigit] u HexDigit HexDigit HexDigit [lookahead ∉ HexDigit] u { [lookahead ∉ HexDigit] u { NotCodePoint [lookahead ∉ HexDigit] u { CodePoint [lookahead ∉ HexDigit] [lookahead ≠ }] NotCodePoint :: HexDigits[~Sep] but only if the MV of HexDigits > 0x10FFFF CodePoint :: HexDigits[~Sep] but only if the MV of HexDigits ≤ 0x10FFFF Note

TemplateSubstitutionTailInputElementTemplateTail alternative lexical goal에 의해 사용됩니다.

12.9.6.1 Static Semantics: TV

The syntax-directed operation TV takes no arguments and returns a String or undefined. template literal component는 TV에 의해 String type의 value로 interpreted됩니다. TV는 template object의 indexed component(colloquially, template values)를 construct하는 데 사용됩니다. TV에서 escape sequence는 escape sequence가 represented하는 Unicode code point의 UTF-16 code unit으로 replaced됩니다.

12.9.6.2 Static Semantics: TRV

The syntax-directed operation TRV takes no arguments and returns a String. template literal component는 TRV에 의해 String type의 value로 interpreted됩니다. TRV는 template object의 raw component(colloquially, template raw values)를 construct하는 데 사용됩니다. TRV는 TV와 similar하지만 차이점은 TRV에서 escape sequence가 literal에 appear하는 그대로 interpreted된다는 것입니다.

Note

TVLineContinuation의 code unit을 excludes하지만 TRV는 them을 includes합니다. <CR><LF> 및 <CR> LineTerminatorSequenceTV와 TRV 모두에서 <LF>로 normalized됩니다. <CR> 또는 <CR><LF> sequence를 include하려면 explicit TemplateEscapeSequence가 필요합니다.

12.10 Automatic Semicolon Insertion

대부분의 ECMAScript statement와 declaration은 semicolon으로 terminated되어야 합니다. 그러한 semicolon은 source text에 항상 explicitly appear할 수 있습니다. 그러나 convenience를 위해, certain situation에서는 그러한 semicolon을 source text에서 omitted할 수 있습니다. 이러한 situation은 semicolon이 그 situation에서 source code token stream에 automatically inserted된다고 말함으로써 described됩니다.

12.10.1 Rules of Automatic Semicolon Insertion

다음 rule에서 “token”은 clause 12에 described된 대로 current lexical goal symbol을 사용하여 determined된 actual recognized lexical token을 의미합니다.

semicolon insertion에는 세 가지 basic rule이 있습니다:

  1. source text가 left to right로 parsed될 때, grammar의 어떤 production에도 allowed되지 않는 token(offending token이라고 함)이 encountered되면, 다음 condition 중 하나 이상이 true인 경우 semicolon이 offending token 앞에 automatically inserted됩니다:

    • offending token이 previous token과 적어도 하나의 LineTerminator에 의해 separated되어 있습니다.
    • offending token이 }입니다.
    • previous token이 )이고 inserted semicolon이 do-while statement(14.7.2)의 terminating semicolon으로 parsed될 것입니다.
  2. source text가 left to right로 parsed될 때, token의 input stream의 end가 encountered되고 parser가 input token stream을 goal nonterminal의 single instance로 parse할 수 없으면, semicolon이 input stream의 end에 automatically inserted됩니다.
  3. source text가 left to right로 parsed될 때, grammar의 어떤 production에서는 allowed되지만 그 production이 restricted production이고, 그 token이 restricted production 안에서 annotation “[no LineTerminator here]” 바로 뒤의 terminal 또는 nonterminal을 위한 first token이 될 수 있는 token(restricted token이라고 함)이며, restricted token이 previous token과 적어도 하나의 LineTerminator에 의해 separated되어 있으면, semicolon이 restricted token 앞에 automatically inserted됩니다.

그러나 preceding rule에는 additional overriding condition이 있습니다: semicolon이 empty statement로 parsed될 경우 또는 그 semicolon이 for statement(14.7.4 참조)의 header 안의 두 semicolon 중 하나가 될 경우, semicolon은 never automatically inserted되지 않습니다.

Note

다음은 grammar 안의 only restricted production입니다:

UpdateExpression[Yield, Await] : LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] ++ LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] -- UsingDeclaration[In, Yield, Await] : using [no LineTerminator here] BindingList[?In, ?Yield, ?Await, ~Pattern] ; ContinueStatement[Yield, Await] : continue ; continue [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ; BreakStatement[Yield, Await] : break ; break [no LineTerminator here] LabelIdentifier[?Yield, ?Await] ; ReturnStatement[Yield, Await] : return ; return [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; ThrowStatement[Yield, Await] : throw [no LineTerminator here] Expression[+In, ?Yield, ?Await] ; YieldExpression[In, Await] : yield yield [no LineTerminator here] AssignmentExpression[?In, +Yield, ?Await] yield [no LineTerminator here] * AssignmentExpression[?In, +Yield, ?Await] ArrowFunction[In, Yield, Await] : ArrowParameters[?Yield, ?Await] [no LineTerminator here] => ConciseBody[?In] AsyncFunctionDeclaration[Yield, Await, Default] : async [no LineTerminator here] function BindingIdentifier[?Yield, ?Await] ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } [+Default] async [no LineTerminator here] function ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncFunctionExpression : async [no LineTerminator here] function BindingIdentifier[~Yield, +Await]opt ( FormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncMethod[Yield, Await] : async [no LineTerminator here] ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[~Yield, +Await] ) { AsyncFunctionBody } AsyncGeneratorDeclaration[Yield, Await, Default] : async [no LineTerminator here] function * BindingIdentifier[?Yield, ?Await] ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } [+Default] async [no LineTerminator here] function * ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorExpression : async [no LineTerminator here] function * BindingIdentifier[+Yield, +Await]opt ( FormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncGeneratorMethod[Yield, Await] : async [no LineTerminator here] * ClassElementName[?Yield, ?Await] ( UniqueFormalParameters[+Yield, +Await] ) { AsyncGeneratorBody } AsyncArrowFunction[In, Yield, Await] : async [no LineTerminator here] AsyncArrowBindingIdentifier[?Yield] [no LineTerminator here] => AsyncConciseBody[?In] CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await] [no LineTerminator here] => AsyncConciseBody[?In] AsyncArrowHead : async [no LineTerminator here] ArrowFormalParameters[~Yield, +Await]

이러한 restricted production의 practical effect는 다음과 같습니다:

  • 파서가 후위 연산자로 처리할 위치에서 ++ 또는 -- 토큰을 만났고, 앞선 토큰과 ++ 또는 -- 토큰 사이에 하나 이상의 LineTerminator가 발생한 경우, ++ 또는 -- 토큰 앞에 세미콜론이 자동으로 삽입된다.
  • using 토큰을 만났고 IdentifierName 토큰 앞에서 LineTerminator를 만난 경우, using 토큰 뒤에 세미콜론이 자동으로 삽입된다.
  • continue, break, return, throw 또는 yield 토큰을 만났고 다음 토큰 앞에서 LineTerminator를 만난 경우, continue, break, return, throw 또는 yield 토큰 뒤에 세미콜론이 자동으로 삽입된다.
  • 화살표 함수 매개변수 뒤에 => 토큰 앞의 LineTerminator가 오는 경우, 세미콜론이 자동으로 삽입되고 해당 punctuator가 구문 오류를 일으킨다.
  • async 토큰 뒤에 function, IdentifierName 또는 ( 토큰 앞의 LineTerminator가 오는 경우, 세미콜론이 자동으로 삽입되고 async 토큰은 뒤따르는 토큰들과 같은 표현식 또는 클래스 요소의 일부로 처리되지 않는다.
  • async 토큰 뒤에 * 토큰 앞의 LineTerminator가 오는 경우, 세미콜론이 자동으로 삽입되고 해당 punctuator가 구문 오류를 일으킨다.

그 결과 ECMAScript 프로그래머에게 주어지는 실질적인 조언은 다음과 같다:

  • 후위 ++ 또는 -- 연산자는 그 피연산자와 같은 줄에 있어야 한다.
  • using 선언의 BindingListusing 토큰과 같은 줄에서 시작해야 한다.
  • return 또는 throw 문에서의 Expression, 또는 yield 표현식에서의 AssignmentExpressionreturn, throw 또는 yield 토큰과 같은 줄에서 시작해야 한다.
  • break 또는 continue 문에서의 LabelIdentifierbreak 또는 continue 토큰과 같은 줄에 있어야 한다.
  • 화살표 함수의 매개변수 끝과 그 =>는 같은 줄에 있어야 한다.
  • 비동기 함수 또는 메서드 앞의 async 토큰은 바로 뒤따르는 토큰과 같은 줄에 있어야 한다.

12.10.2 Examples of Automatic Semicolon Insertion

This section is non-normative.

source

{ 1 2 } 3

는 automatic semicolon insertion rule이 있어도 ECMAScript grammar에서 valid sentence가 아닙니다. 반대로, source

{ 1
2 } 3

역시 valid ECMAScript sentence는 아니지만, automatic semicolon insertion에 의해 다음으로 transformed됩니다:

{ 1
;2 ;} 3;

이는 valid ECMAScript sentence입니다.

source

for (a; b
)

는 valid ECMAScript sentence가 아니며, semicolon이 for statement의 header에 needed되기 때문에 automatic semicolon insertion에 의해 altered되지 않습니다. Automatic semicolon insertion은 for statement의 header 안의 두 semicolon 중 하나를 never inserts하지 않습니다.

source

return
a + b

는 automatic semicolon insertion에 의해 다음으로 transformed됩니다:

return;
a + b;
Note 1

LineTerminator가 token return과 expression a + b를 separate하기 때문에, expression a + breturn statement에 의해 returned될 value로 treated되지 않습니다.

source

a = b
++c

는 automatic semicolon insertion에 의해 다음으로 transformed됩니다:

a = b;
++c;
Note 2

LineTerminatorb++ 사이에 occur하기 때문에, token ++는 variable b에 applying되는 postfix operator로 treated되지 않습니다.

source

if (a > b)
else c = d

는 valid ECMAScript sentence가 아니며, grammar의 어떤 production도 그 point에 apply되지 않더라도, automatically inserted된 semicolon이 empty statement로 parsed될 것이기 때문에 else token 앞에서 automatic semicolon insertion에 의해 altered되지 않습니다.

source

a = b + c
(d + e).print()

not automatic semicolon insertion에 의해 transformed되지 않습니다. second line을 begin하는 parenthesized expression이 function call의 argument list로 interpreted될 수 있기 때문입니다:

a = b + c(d + e).print()

assignment statement가 left parenthesis로 begin해야 하는 circumstance에서는, programmer가 automatic semicolon insertion에 rely하기보다는 preceding statement의 end에 explicit semicolon을 provide하는 것이 good idea입니다.

12.10.3 Interesting Cases of Automatic Semicolon Insertion

This section is non-normative.

ECMAScript program은 automatic semicolon insertion에 relying함으로써 very few semicolon을 가진 style로 written될 수 있습니다. 위에 described된 것처럼, semicolon은 every newline에 inserted되지 않으며, automatic semicolon insertion은 line terminator를 across하는 multiple token에 depend할 수 있습니다.

새 syntactic feature가 ECMAScript에 added됨에 따라, automatic semicolon insertion에 preceding하여 relying하는 line이 parsed될 때 grammar production을 change하게 하는 additional grammar production이 added될 수 있습니다.

이 section의 purpose상, automatic semicolon insertion의 case는 preceding source text에 따라 semicolon이 inserted될 수도 있고 inserted되지 않을 수도 있는 place이면 interesting하다고 considered됩니다. 이 section의 rest는 이 version의 ECMAScript에서 automatic semicolon insertion의 여러 interesting case를 describe합니다.

12.10.3.1 Statement List 안의 Automatic Semicolon Insertion의 Interesting Cases

StatementList에서 많은 StatementListItem은 semicolon으로 end하며, 이는 automatic semicolon insertion을 사용하여 omitted될 수 있습니다. 위 rule의 consequence로, expression을 ending하는 line의 end에서는 following line이 다음 중 하나로 begin하면 semicolon이 required됩니다:

  • opening parenthesis((). semicolon이 없으면 두 line은 together CallExpression으로 treated됩니다.
  • opening square bracket([). semicolon이 없으면 두 line은 ArrayLiteral 또는 ArrayAssignmentPattern이 아니라 property access로 treated됩니다.
  • template literal(`). semicolon이 없으면 두 line은 previous expression을 MemberExpression으로 하는 tagged Template(13.3.11)으로 interpreted됩니다.
  • Unary + 또는 -. semicolon이 없으면 두 line은 corresponding binary operator의 usage로 interpreted됩니다.
  • RegExp literal. semicolon이 없으면 두 line은 instead / MultiplicativeOperator로 parsed될 수 있습니다. 예를 들어 RegExp에 flag가 있는 경우입니다.

12.10.3.2 Automatic Semicolon Insertion 및 “[no LineTerminator here]”의 Cases

This section is non-normative.

ECMAScript는 “[no LineTerminator here]”를 include하는 grammar production을 contain합니다. 이러한 production은 때때로 grammar 안에서 optional operand를 가지기 위한 means입니다. 이러한 location에 LineTerminator를 introducing하면 optional operand가 없는 grammar production을 사용하여 source text의 grammar production을 change하게 됩니다.

이 section의 rest는 이 version의 ECMAScript에서 “[no LineTerminator here]”를 사용하는 여러 production을 describe합니다.

12.10.3.2.1 Optional Operand와 “[no LineTerminator here]”를 가진 Grammar Production의 List