12 ECMAScript Language: Lexical Grammar

ECMAScript ScriptまたはModuleのsource textは、まずinput elementsのsequenceへ変換されます。input elementsはtokens、line terminators、comments、またはwhite spaceです。source textは左から右へscanされ、次のinput elementとして可能な最長のcode pointsのsequenceを繰り返し取得します。

lexical input elementsの識別が、そのinput elementsを消費しているsyntactic grammar contextに依存する状況がいくつかあります。このため、lexical grammarには複数のgoal symbolsが必要です。InputElementHashbangOrRegExp goalは、ScriptまたはModuleの開始時に使用されます。InputElementRegExpOrTemplateTail goalは、RegularExpressionLiteralTemplateMiddle、またはTemplateTailが許可されるsyntactic grammar contextsで使用されます。InputElementRegExp goal symbolは、RegularExpressionLiteralが許可されるが、TemplateMiddleTemplateTailも許可されないすべてのsyntactic grammar contextsで使用されます。InputElementTemplateTail goalは、TemplateMiddleまたはTemplateTailが許可されるが、RegularExpressionLiteralが許可されないすべてのsyntactic grammar contextsで使用されます。その他すべてのcontextsでは、InputElementDivがlexical goal symbolとして使用されます。

Note

複数のlexical goalsの使用により、automatic semicolon insertionに影響するlexical ambiguitiesが存在しないことが保証されます。例えば、leading divisionまたはdivision-assignmentと、leading RegularExpressionLiteralの両方が許可されるsyntactic grammar contextsは存在しません。これはsemicolon insertion(12.10を参照)の影響を受けません;次のような例では:

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

LineTerminatorの後の最初のnon-whitespace、non-comment code pointがU+002F (SOLIDUS)であり、syntactic contextがdivisionまたはdivision-assignmentを許可している場合、LineTerminatorでsemicolonは挿入されません。つまり、上の例は次と同じ方法で解釈されます:

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 characters(すなわち、LEFT-TO-RIGHT MARKやRIGHT-TO-LEFT MARKなど、Unicode Character Databaseのcategory “Cf”にあるcharacters)は、これに対するより高レベルのprotocols(mark-up languagesなど)が存在しない場合に、textの範囲のformattingを制御するために使用されるcontrol codesです。

source text内でformat-control charactersを許可することは、editingおよびdisplayを容易にするために有用です。すべてのformat control charactersは、comments内、およびstring literals、template literals、regular expression literals内で使用できます。

U+FEFF (ZERO WIDTH NO-BREAK SPACE)は、主にtextの開始時に、それがUnicodeであることをmarkし、textのencodingおよびbyte orderの検出を可能にするために使用されるformat-control characterです。この目的のために意図された<ZWNBSP> charactersは、例えばfilesを連結した結果として、textの開始後に現れることもあります。ECMAScript source textでは、<ZWNBSP> code pointsは、comments、string literals、template literals、regular expression literalsの外側ではwhite space characters(12.2を参照)として扱われます。

12.2 White Space

White space code pointsは、source textのreadabilityを向上させ、tokens(分割できないlexical units)を互いに分離するために使用されますが、それ以外では重要ではありません。White space code pointsは任意の2つのtokensの間、およびinputの開始または終了に出現できます。White space code pointsは、StringLiteralRegularExpressionLiteralTemplate、またはTemplateSubstitutionTail内に出現する場合があり、その場合literal valueの一部を形成するsignificant code pointsとみなされます。Comment内にも出現できますが、他の種類のtoken内に現れることはできません。

ECMAScript white space code pointsはTable 31に列挙されています。

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 pointsは<USP>の一部です。

Note 2

Table 31に列挙されたcode pointsを除き、ECMAScript WhiteSpaceは、Unicode “White_Space” propertyを持つがgeneral category “Space_Separator”(“Zs”)に分類されないすべてのcode pointsを意図的に除外します。

Syntax

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

12.3 Line Terminators

white space code pointsと同様に、line terminator code pointsはsource textのreadabilityを向上させ、tokens(分割できないlexical units)を互いに分離するために使用されます。しかし、white space code pointsとは異なり、line terminatorsはsyntactic grammarの振る舞いにある程度影響します。一般に、line terminatorsは任意の2つのtokensの間に出現できますが、syntactic grammarによって禁止される場所がいくつかあります。Line terminatorsはautomatic semicolon insertion(12.10)のprocessにも影響します。line terminatorは、StringLiteralTemplate、またはTemplateSubstitutionTailを除くどのtoken内にも出現できません。<LF>および<CR> line terminatorsは、LineContinuationの一部としてでなければ、StringLiteral token内に出現できません。

line terminatorはMultiLineComment内に出現できますが、SingleLineComment内には出現できません。

Line terminatorsは、regular expressions内の\s classによってmatchされるwhite space code pointsのsetに含まれます。

ECMAScript line terminator code pointsはTable 32に列挙されています。

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 pointsだけがline terminatorsとして扱われます。他のnew lineまたはline breaking Unicode code pointsはline terminatorsとして扱われませんが、Table 31に列挙された要件を満たす場合はwhite spaceとして扱われます。sequence <CR><LF>は一般にline terminatorとして使用されます。line numbersを報告する目的では、これは単一のSourceCharacterとみなされるべきです。

Syntax

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

12.4 Comments

Commentsはsingle-lineまたはmulti-lineのいずれかです。Multi-line commentsはnestできません。

single-line commentはLineTerminator code pointを除く任意のUnicode code pointを含むことができ、またtokenは常に可能な限り長くなるという一般規則があるため、single-line commentは常に// markerから行末までのすべてのcode pointsで構成されます。ただし、行末のLineTerminatorはsingle-line commentの一部とはみなされません;これはlexical grammarによって別個に認識され、syntactic grammarのためのinput elementsのstreamの一部になります。この点は非常に重要です。なぜなら、single-line commentsの有無がautomatic semicolon insertionのprocessに影響しないことを意味するからです(12.10を参照)。

Commentsはwhite spaceのように振る舞い破棄されますが、MultiLineCommentがline terminator code pointを含む場合、そのcomment全体はsyntactic grammarによるparsingの目的でLineTerminatorとみなされます。

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のいくつかのproductionsには、section B.1.1でalternative definitionsが与えられています

12.5 Hashbang Comments

Hashbang Commentsはlocation-sensitiveであり、他のtypes of commentsと同様に、syntactic grammarのinput elementsのstreamから破棄されます。

Syntax

HashbangComment :: #! SingleLineCommentCharsopt

12.6 Tokens

Syntax

CommonToken :: IdentifierName PrivateIdentifier Punctuator NumericLiteral StringLiteral Template Note

DivPunctuatorRegularExpressionLiteralRightBracePunctuator、およびTemplateSubstitutionTail productionsは、CommonToken productionに含まれない追加tokensをderiveします。

12.7 Names and Keywords

IdentifierNameおよびReservedWordは、Unicode Standard Annex #31, Identifier and Pattern Syntaxに示されるDefault Identifier Syntaxに従って解釈されるtokensですが、いくつかの小さな変更があります。ReservedWordIdentifierNameのenumerated subsetです。syntactic grammarは、IdentifierReservedWordでないIdentifierNameとして定義します。Unicode identifier grammarは、Unicode Standardによって指定されるcharacter propertiesに基づいています。Unicode Standardのlatest versionにおける指定categories内のUnicode code pointsは、すべてのconforming ECMAScript implementationsによってそれらのcategoriesにあるものとして扱われなければなりません。ECMAScript implementationsは、Unicode Standardの後続editionで定義されたidentifier code pointsを認識してよいです。

Note 1

この標準は特定のcode point additionsを指定します:U+0024 (DOLLAR SIGN)およびU+005F (LOW LINE)はIdentifierName内の任意の場所で許可されます。

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の定義は12.9.4に与えられています。

Note 2

nonterminal IdentifierPartUnicodeIDContinueを介して_をderiveします。

Note 3

Unicode properties “ID_Start”および“ID_Continue”を持つcode pointsのsetsは、それぞれUnicode properties “Other_ID_Start”および“Other_ID_Continue”を持つcode pointsを含みます。

12.7.1 Identifier Names

Unicode escape sequencesはIdentifierName内で許可され、そこでUnicodeEscapeSequenceIdentifierCodePointと等しい単一のUnicode code pointに寄与します。UnicodeEscapeSequenceの前にある\はどのcode pointsにも寄与しません。UnicodeEscapeSequenceは、そうでなければinvalidとなるcode pointをIdentifierNameに寄与するために使用することはできません。言い換えれば、\ UnicodeEscapeSequence sequenceが、それが寄与するSourceCharacterで置き換えられた場合、その結果はなおvalidなIdentifierNameであり、元のIdentifierNameとまったく同じSourceCharacter elementsのsequenceを持たなければなりません。この仕様内のIdentifierNameのすべての解釈は、特定のcode pointに寄与するためにescape sequenceが使用されたかどうかにかかわらず、実際のcode pointsに基づきます。

Unicode Standardに従ってcanonically equivalentである2つのIdentifierNamesは、各UnicodeEscapeSequenceの置換後に、完全に同じcode pointsのsequenceで表されない限り、等しくありません

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によってmatchされたcode pointを返す。
IdentifierPart :: IdentifierPartChar
  1. IdentifierPartCharによってmatchされたcode pointを返す。
UnicodeEscapeSequence :: u Hex4Digits
  1. 数値がHex4DigitsのMVであるcode pointを返す。
UnicodeEscapeSequence :: u{ CodePoint }
  1. 数値がCodePointのMVであるcode pointを返す。

12.7.2 Keywords and Reserved Words

keywordIdentifierNameにmatchするtokenですが、syntactic useも持ちます;つまり、何らかのsyntactic production内に、fixed width fontでliteralに現れます。ECMAScriptのkeywordsには、ifwhileasyncawait、その他多数が含まれます。

reserved wordはidentifierとして使用できないIdentifierNameです。多くのkeywordsはreserved wordsですが、そうでないものもあり、また特定のcontextsでのみreservedであるものもあります。ifおよびwhileはreserved wordsです。awaitはasync functionsおよびmodulesの内部でのみreservedです。asyncはreservedではありません;制限なくvariable nameまたはstatement labelとして使用できます。

この仕様は、grammatical productionsとearly error rulesの組み合わせを使用して、どのnamesがvalid identifiersであり、どれがreserved wordsであるかを指定します。下のReservedWord list内のすべてのtokensは、awaitおよびyieldを除き、無条件にreservedです。awaitおよびyieldに対する例外は、parameterized syntactic productionsを使用して13.1で指定されます。最後に、いくつかのearly error rulesがvalid identifiersのsetを制限します。13.1.114.3.1.114.7.5.1、および15.7.1を参照してください。まとめると、identifier namesには5つのcategoriesがあります:

  • MathwindowtoString、および_など、常にidentifiersとして許可され、keywordsではないもの;

  • 下に列挙されるReservedWordsのうち、awaitおよびyieldを除いた、identifiersとして決して許可されないもの;

  • awaitおよびyieldという、contextuallyにidentifiersとして許可されるもの;

  • strict mode codeにおいて、contextuallyにidentifiersとして許可されないもの:letstaticimplementsinterfacepackageprivateprotected、およびpublic

  • 常にidentifiersとして許可されるが、特定のsyntactic productions内で、Identifierが許可されない場所にkeywordsとしても現れるもの:asasyncfromgetmetaofset、およびtarget

用語conditional keyword、またはcontextual keywordは、最後の3つのcategoriesに属し、したがってあるcontextsではidentifiersとして、別のcontextsではkeywordsとして使用できるkeywordsを指すために使われることがあります。

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内のkeywordsは特定のSourceCharacter elementsのliteral sequencesにmatchします。keyword内のcode pointを\ UnicodeEscapeSequenceによって表すことはできません。

IdentifierName\ UnicodeEscapeSequencesを含むことができますが、els\u{65}と綴ることによって“else”という名前のvariableを宣言することはできません。13.1.1内のearly error rulesは、reserved wordと同じStringValueを持つidentifiersを除外します。

Note 2

enumは現在、この仕様内でkeywordとして使用されていません。これは、将来のlanguage extensionsでkeywordとして使用するために取っておかれたfuture reserved wordです。

同様に、implementsinterfacepackageprivateprotected、およびpublicstrict mode codeにおけるfuture reserved wordsです。

Note 3

names argumentsおよびevalはkeywordsではありませんが、strict mode codeではいくつかの制限を受けます。13.1.18.6.415.2.115.5.115.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の直後に続くSourceCharacterは、IdentifierStartまたはDecimalDigitであってはなりません。

Note

例えば:3inはerrorであり、2つのinput elements 3およびinではありません。

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の値を表します。

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値を返す。
DecimalBigIntegerLiteral :: 0 BigIntLiteralSuffix
  1. 0を返す。
DecimalBigIntegerLiteral :: NonZeroDigit BigIntLiteralSuffix
  1. NonZeroDigitのMVに対するBigInt値を返す。
DecimalBigIntegerLiteral :: NonZeroDigit DecimalDigits BigIntLiteralSuffix NonZeroDigit NumericLiteralSeparator DecimalDigits BigIntLiteralSuffix
  1. nを、NumericLiteralSeparatorのすべての出現を除いたDecimalDigits内のcode pointsの数とする。
  2. mvを(NonZeroDigitのMV × 10n)にDecimalDigitsのMVを加えたものとする。
  3. (mv)を返す。

12.9.4 String Literals

Note 1

string literalは、single quotesまたはdouble quotesで囲まれた0個以上のUnicode code pointsです。Unicode code pointsはescape sequenceによって表すこともできます。closing quote code points、U+005C (REVERSE SOLIDUS)、U+000D (CARRIAGE RETURN)、およびU+000A (LINE FEED)を除き、すべてのcode pointsはstring literal内にliteralに現れてよいです。任意のcode pointsはescape sequenceの形式で現れてよいです。String literalsはECMAScript String valuesにevaluateされます。これらのString valuesを生成するとき、Unicode code pointsは11.1.1で定義されるようにUTF-16 encodedされます。Basic Multilingual Planeに属するcode pointsは、stringの単一のcode unit elementとしてencodedされます。それ以外のすべてのcode pointsは、stringの2つのcode unit elementsとして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の定義は12.9.3に与えられています。SourceCharacter11.1で定義されます。

Note 2

<LF>および<CR>は、空のcode points sequenceを生成するためのLineContinuationの一部としてでない限り、string literal内に現れることはできません。string literalのString値にこれらのいずれかを含める適切な方法は、\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 literalsが、それを囲むcodeをstrict modeに置くUse Strict Directiveより前に出現することは可能であり、implementationsはそのようなliteralsについて上記rulesを強制するよう注意しなければなりません。例えば、次のsource textはSyntax Errorを含みます:

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の値を表します。SVは、string literalのさまざまなpartsへのrecursive applicationを通じて、string literalsに対するString valuesを生成します。このprocessの一部として、string literal内の一部のUnicode code pointsは、以下または12.9.3で説明されるように、mathematical valueを持つものとして解釈されます。

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がevaluateされるたびにRegExp object(22.2を参照)へ変換されるinput elementです。program内の2つのregular expression literalsは、2つのliteralsのcontentsが同一であっても、互いに===としてcompareされることのないregular expression objectsへevaluateされます。RegExp objectは、runtimeにnew RegExpによって、またはRegExp constructorをfunctionとして呼び出すことによっても作成できます(22.2.4を参照)。

以下のproductionsはregular expression literalのsyntaxを記述し、input element scannerがregular expression literalの終端を見つけるために使用されます。RegularExpressionBodyおよびRegularExpressionFlagsを構成するsource textは、その後、より厳密なECMAScript Regular Expression grammar(22.2.1)を使用して再びparseされます。

実装は22.2.1で定義されるECMAScript Regular Expression grammarを拡張してよいですが、以下で定義されるRegularExpressionBodyおよびRegularExpressionFlags productions、またはこれらのproductionsによって使用されるproductionsを拡張してはなりません。

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 literalsは空であってはなりません;空のregular expression literalを表す代わりに、code unit sequence //はsingle-line commentを開始します。空のregular expressionを指定するには、/(?:)/を使用してください。

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として認識された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として認識された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の値として解釈されます。TVはtemplate objectのindexed components(口語的にはtemplate values)を構築するために使用されます。TVでは、escape sequencesは、escape sequenceによって表されるUnicode code pointのUTF-16 code unit(s)に置き換えられます。

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の値として解釈されます。TRVはtemplate objectのraw components(口語的にはtemplate raw values)を構築するために使用されます。TRVはTVと似ていますが、TRVではescape sequencesがliteral内に現れたままに解釈される点が異なります。

Note

TVLineContinuationのcode unitsを除外する一方、TRVはそれらを含みます。<CR><LF>および<CR> LineTerminatorSequencesは、TVとTRVの両方について<LF>にnormalizedされます。<CR>または<CR><LF> sequenceを含めるには、明示的なTemplateEscapeSequenceが必要です。

12.10 Automatic Semicolon Insertion

ほとんどのECMAScript statementsおよびdeclarationsはsemicolonで終了しなければなりません。そのようなsemicolonsはsource text内に常に明示的に現れてよいです。しかし便宜上、そのようなsemicolonsは特定の状況ではsource textから省略されてもよいです。これらの状況は、そのような状況でsemicolonsがsource code token streamに自動的に挿入される、と述べることで説明されます。

12.10.1 Rules of Automatic Semicolon Insertion

次のrulesでは、“token”とは、clause 12で説明されるように、現在のlexical goal symbolを使用して決定される、実際に認識されたlexical tokenを意味します。

semicolon insertionには3つの基本rulesがあります:

  1. source textが左から右へparseされるとき、grammarのどのproductionによっても許可されないtoken(offending tokenと呼ばれる)に遭遇した場合、次の条件の1つ以上がtrueであれば、そのoffending tokenの前にsemicolonが自動的に挿入されます:

    • offending tokenがprevious tokenから少なくとも1つのLineTerminatorによって分離されている。
    • offending tokenが}である。
    • previous tokenが)であり、挿入されたsemicolonがdo-while statement(14.7.2)のterminating semicolonとしてparseされる。
  2. source textが左から右へparseされるとき、tokensのinput streamの終端に遭遇し、parserがinput token streamをgoal nonterminalの単一のinstanceとしてparseできない場合、input streamの終端にsemicolonが自動的に挿入されます。
  3. source textが左から右へparseされるとき、grammarのあるproductionによって許可されるtokenに遭遇したが、そのproductionがrestricted productionであり、そのtokenがrestricted production内の注釈“[no LineTerminator here]”の直後にあるterminalまたはnonterminalの最初のtokenとなる場合(したがって、そのようなtokenはrestricted tokenと呼ばれる)、かつrestricted tokenがprevious tokenから少なくとも1つのLineTerminatorによって分離されている場合、そのrestricted tokenの前にsemicolonが自動的に挿入されます。

ただし、上記rulesには追加のoverriding conditionがあります:semicolonがempty statementとしてparseされることになる場合、またはそのsemicolonがfor statement(14.7.4を参照)のheader内の2つのsemicolonsの1つになる場合、semicolonは自動的には決して挿入されません。

Note

grammar内のrestricted productionsは次のものだけです:

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 productionsの実際上の効果は次のとおりです:

  • パーサが後置演算子として扱う位置で ++ または -- トークンに遭遇し、直前のトークンと ++ または -- トークンの間に少なくとも1つの LineTerminator が出現していた場合、セミコロンは ++ または -- トークンの前に自動的に挿入される。
  • using トークンに遭遇し、IdentifierName トークンの前に LineTerminator が遭遇された場合、セミコロンは using トークンの後に自動的に挿入される。
  • continuebreakreturnthrow、または yield トークンに遭遇し、次のトークンの前に LineTerminator が遭遇された場合、セミコロンは continuebreakreturnthrow、または yield トークンの後に自動的に挿入される。
  • アロー関数のパラメータが => トークンの前の LineTerminator に続く場合、セミコロンが自動的に挿入され、その区切り子は構文エラーを引き起こす。
  • async トークンの後に、functionIdentifierName、または ( トークンの前の LineTerminator が続く場合、セミコロンが自動的に挿入され、async トークンは後続のトークンと同じ式またはクラス要素の一部として扱われない。
  • async トークンの後に、* トークンの前の LineTerminator が続く場合、セミコロンが自動的に挿入され、その区切り子は構文エラーを引き起こす。

結果として、ECMAScript プログラマに対する実践的な助言は次のとおりである:

  • 後置 ++ または -- 演算子は、そのオペランドと同じ行に置かれるべきである。
  • using 宣言内の BindingList は、using トークンと同じ行で開始するべきである。
  • return または throw 文内の Expression、または yield 式内の AssignmentExpression は、returnthrow、または yield トークンと同じ行で開始するべきである。
  • break または continue 文内の LabelIdentifier は、break または continue トークンと同じ行に置かれるべきである。
  • アロー関数のパラメータの終端とその => は、同じ行に置かれるべきである。
  • 非同期関数またはメソッドの前にある async トークンは、直後に続くトークンと同じ行に置かれるべきである。

12.10.2 Examples of Automatic Semicolon Insertion

This section is non-normative.

source

{ 1 2 } 3

は、automatic semicolon insertion rulesを用いても、ECMAScript grammarにおけるvalid sentenceではありません。対照的に、source

{ 1
2 } 3

もvalidなECMAScript sentenceではありませんが、automatic semicolon insertionによって次のように変換されます:

{ 1
;2 ;} 3;

これはvalidなECMAScript sentenceです。

source

for (a; b
)

はvalidなECMAScript sentenceではなく、automatic semicolon insertionによって変更されません。なぜなら、semicolonはfor statementのheaderに必要だからです。Automatic semicolon insertionは、for statementのheader内の2つのsemicolonsの1つを決して挿入しません。

source

return
a + b

はautomatic semicolon insertionによって次のように変換されます:

return;
a + b;
Note 1

LineTerminatorがexpression a + bをtoken returnから分離しているため、expression a + breturn statementによって返される値として扱われません。

source

a = b
++c

はautomatic semicolon insertionによって次のように変換されます:

a = b;
++c;
Note 2

++ tokenは、variable bに適用されるpostfix operatorとして扱われません。なぜなら、b++の間にLineTerminatorが出現するからです。

source

if (a > b)
else c = d

はvalidなECMAScript sentenceではなく、その時点でgrammarのどのproductionも適用されないにもかかわらず、else tokenの前にautomatic semicolon insertionによって変更されません。なぜなら、自動的に挿入されたsemicolonはempty statementとしてparseされることになるからです。

source

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

はautomatic semicolon insertionによって変換されません。なぜなら、2行目を開始するparenthesized expressionはfunction callのargument listとして解釈できるからです:

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

assignment statementがleft parenthesisで開始しなければならない状況では、programmerはautomatic semicolon insertionに頼るのではなく、preceding statementの終端に明示的なsemicolonを提供することがよい考えです。

12.10.3 Interesting Cases of Automatic Semicolon Insertion

This section is non-normative.

ECMAScript programsは、automatic semicolon insertionに頼ることで、非常に少ないsemicolonsのstyleで書くことができます。上で説明したように、semicolonsはすべてのnewlineで挿入されるわけではなく、automatic semicolon insertionはline terminatorsをまたいだ複数のtokensに依存する場合があります。

新しいsyntactic featuresがECMAScriptに追加されるにつれて、その前でautomatic semicolon insertionに頼っている行がparseされるときにgrammar productionsを変更させる追加grammar productionsが追加される可能性があります。

このsectionの目的では、automatic semicolon insertionのcaseは、その前にあるsource textに応じてsemicolonが挿入される場合もされない場合もある場所であるなら、interestingとみなされます。このsectionの残りでは、このversion of ECMAScriptにおけるautomatic semicolon insertionのいくつかのinteresting casesを説明します。

12.10.3.1 Interesting Cases of Automatic Semicolon Insertion in Statement Lists

StatementListでは、多くのStatementListItemsはsemicolonsで終わり、automatic semicolon insertionを使用して省略される場合があります。上記rulesの帰結として、expressionで終わる行の終端では、次の行が以下のいずれかで始まる場合、semicolonが必要です:

  • opening parenthesis((。semicolonがない場合、2つの行は一緒にCallExpressionとして扱われます。
  • opening square bracket([。semicolonがない場合、2つの行はArrayLiteralまたはArrayAssignmentPatternではなくproperty accessとして扱われます。
  • template literal(`。semicolonがない場合、2つの行は、previous expressionをMemberExpressionとするtagged Template(13.3.11)として解釈されます。
  • Unary +または-。semicolonがない場合、2つの行は対応するbinary operatorの使用として解釈されます。
  • RegExp literal。semicolonがない場合、2つの行は、例えばRegExpにflagsがある場合、代わりに/ MultiplicativeOperatorとしてparseされる可能性があります。

12.10.3.2 Cases of Automatic Semicolon Insertion and “[no LineTerminator here]”

This section is non-normative.

ECMAScriptには、“[no LineTerminator here]”を含むgrammar productionsがあります。これらのproductionsは、grammar内にoptional operandsを持つための手段である場合があります。これらの場所にLineTerminatorを導入すると、optional operandを持たないgrammar productionを使用することにより、source textのgrammar productionが変更されます。

このsectionの残りでは、このversion of ECMAScriptで“[no LineTerminator here]”を使用するいくつかのproductionsを説明します。

12.10.3.2.1 List of Grammar Productions with Optional Operands and “[no LineTerminator here]”