12 ECMAScript 言語: 字句文法 (ECMAScript Language: Lexical Grammar)

ECMAScript の Script または Module のソーステキストはまず入力要素(トークン、行終端子、コメント、または空白)から成る列へと変換される。ソーステキストは左から右へ走査され、可能な限り最長の符号位置列が次の入力要素として逐次選択される。

入力要素の識別がそれを消費する構文文法コンテキストに依存する状況がいくつか存在する。これは字句文法に複数の目標(goal)記号を必要とする。InputElementHashbangOrRegExp 目標は Script または Module の開始時に用いられる。InputElementRegExpOrTemplateTail 目標は RegularExpressionLiteral, TemplateMiddle, または TemplateTail が許可される構文文法コンテキストで用いられる。InputElementRegExp 目標記号は RegularExpressionLiteral が許可され、かつ TemplateMiddleTemplateTail が許可されないすべての構文文法コンテキストで用いられる。InputElementTemplateTail 目標は TemplateMiddle または TemplateTail が許可され、 RegularExpressionLiteral が許可されないすべての構文文法コンテキストで用いられる。その他すべてのコンテキストでは InputElementDiv が字句目標記号として用いられる。

Note

複数の字句目標を用いることで自動セミコロン挿入に影響する字句的曖昧さが存在しないことを保証する。例えば、先頭に除算または除算代入、かつ先頭に RegularExpressionLiteral の両方が許容される構文文法コンテキストは存在しない。これはセミコロン挿入(12.10 参照)によって影響を受けない。以下の例のように:

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

LineTerminator の後の最初の非空白・非コメント符号位置が U+002F (SOLIDUS) であり、構文コンテキストが除算または除算代入を許可する場合、LineTerminator の位置にセミコロンは挿入されない。すなわち上の例は次と同じように解釈される:

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 形式制御文字 (Unicode Format-Control Characters)

Unicode 形式制御文字(すなわち Unicode 文字データベースにおける “Cf” カテゴリ、例えば LEFT-TO-RIGHT MARK や RIGHT-TO-LEFT MARK)は、上位プロトコル(マークアップ言語など)が存在しない場合にテキスト範囲の整形を制御するために使用される制御コードである。

編集および表示を容易にするため、ソーステキスト内で形式制御文字を許可することは有用である。すべての形式制御文字はコメント内、ならびに文字列リテラル、テンプレートリテラル、正規表現リテラル内で使用できる。

U+FEFF (ZERO WIDTH NO-BREAK SPACE) は主としてテキストの冒頭で Unicode であることを示し、テキストのエンコーディングとバイト順を検出するために用いられる形式制御文字である。この目的で用いられる <ZWNBSP> 文字は、ファイル連結の結果などとしてテキスト開始後にも現れることがある。ECMAScript ソーステキストでは、コメント、文字列リテラル、テンプレートリテラル、正規表現リテラルの外側で <ZWNBSP> 符号位置は空白文字として扱われる(12.2 参照)。

12.2 空白 (White Space)

空白符号位置はソーステキストの可読性を高め、トークン(分割不可能な字句単位)を相互に分離するために使用されるが、それ以外の点では意味を持たない。空白符号位置は任意の 2 つのトークンの間および入力の開始・末尾に現れうる。空白符号位置は StringLiteral, RegularExpressionLiteral, Template, TemplateSubstitutionTail の内部に現れ、その場合リテラル値を構成する有意味な符号位置として扱われる。また Comment 内に現れうるが、他の種類のトークン内部には現れない。

ECMAScript の空白符号位置は Table 33 に列挙される。

Table 33: 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>
一般カテゴリ “Space_Separator” のいかなる符号位置 <USP>
Note 1

U+0020 (SPACE) と U+00A0 (NO-BREAK SPACE) は <USP> の一部である。

Note 2

Table 33 に列挙される符号位置を除き、ECMAScript WhiteSpace は Unicode “White_Space” プロパティを持つが一般カテゴリ “Space_Separator” (“Zs”) に分類されないすべての符号位置を意図的に除外する。

構文 (Syntax)

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

12.3 行終端子 (Line Terminators)

空白符号位置と同様に、行終端子符号位置はソーステキストの可読性を高め、トークンを相互に分離するために使用される。しかし空白符号位置と異なり、行終端子は構文文法の振る舞いに影響を及ぼす。一般に、行終端子は任意の 2 つのトークン間に現れうるが、構文文法により禁止される箇所がいくつか存在する。行終端子は自動セミコロン挿入(12.10)の過程にも影響する。行終端子は StringLiteral, Template, TemplateSubstitutionTail 以外のいかなるトークン内部にも現れない。<LF> および <CR> 行終端子は LineContinuation の一部である場合を除き StringLiteral トークン内部に現れない。

行終端子は MultiLineComment 内には現れることができるが、SingleLineComment 内には現れない。

行終端子は正規表現において \s クラスによりマッチされる空白符号位置集合に含まれる。

ECMAScript の行終端子符号位置は Table 34 に列挙される。

Table 34: 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 34 に示す Unicode 符号位置のみが行終端子として扱われる。その他の改行または行分割の Unicode 符号位置は行終端子とは扱われないが、Table 33 に記述された要件を満たす場合は空白として扱われる。シーケンス <CR><LF> は行終端子として一般的に使用される。行番号の報告目的においては一つの SourceCharacter と見なされるべきである。

構文 (Syntax)

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

12.4 コメント (Comments)

コメントは単一行または複数行のいずれかである。複数行コメントは入れ子にできない。

単一行コメントは LineTerminator 符号位置以外の任意の Unicode 符号位置を含むことができ、また一般規則としてトークンは常に可能な限り長くなるため、単一行コメントは // マーカーから行末までのすべての符号位置で構成される。ただし行末の LineTerminator は単一行コメントの一部とは見なされず、字句文法により別途認識され構文文法用の入力要素列の一部となる。これは重要な点であり、単一行コメントの有無が自動セミコロン挿入(12.10 参照)に影響しないことを意味する。

コメントは空白のように振る舞い破棄されるが、MultiLineComment に行終端子符号位置が含まれる場合、構文文法によるパース目的ではそのコメント全体が一つの 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

この節のいくつかの生成規則は B.1.1 節で代替定義が与えられる。

12.5 ハッシュバンコメント (Hashbang Comments)

ハッシュバンコメントは位置依存であり、他の種類のコメントと同様に構文文法への入力要素列からは破棄される。

構文 (Syntax)

HashbangComment :: #! SingleLineCommentCharsopt

12.6 トークン (Tokens)

構文 (Syntax)

CommonToken :: IdentifierName PrivateIdentifier Punctuator NumericLiteral StringLiteral Template Note

DivPunctuator, RegularExpressionLiteral, RightBracePunctuator, TemplateSubstitutionTail の生成規則は CommonToken 生成規則に含まれない追加トークンを導出する。

12.7 名前とキーワード (Names and Keywords)

IdentifierName および ReservedWord は Unicode Standard Annex #31「Identifier and Pattern Syntax」で与えられる既定の識別子構文(わずかな修正付き)に従って解釈されるトークンである。ReservedWordIdentifierName の列挙された部分集合である。構文文法は IdentifierReservedWord ではない IdentifierName として定義する。Unicode 識別子文法は Unicode Standard が定義する文字プロパティに基づく。Unicode 標準の最新バージョンで指定カテゴリに属する Unicode 符号位置は、すべての適合 ECMAScript 実装によりそのカテゴリとして扱われなければならない。実装は Unicode 標準の後続版で定義された識別子用符号位置を認識してもよい。

Note 1

この規格は追加の特定符号位置を許可する: 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”

非終端記号 UnicodeEscapeSequence の定義は 12.9.4 に示される。

Note 2

非終端記号 IdentifierPartUnicodeIDContinue を通じて _ を導出する。

Note 3

Unicode プロパティ “ID_Start” および “ID_Continue” の集合には、それぞれ “Other_ID_Start” および “Other_ID_Continue” プロパティを持つ符号位置が含まれる。

12.7.1 識別子名 (Identifier Names)

Unicode エスケープシーケンスは IdentifierName 内で許可され、その場合 UnicodeEscapeSequence の IdentifierCodePoint に等しい一つの Unicode 符号位置として寄与する。UnicodeEscapeSequence に先行する ` はいかなる符号位置も寄与しない。|UnicodeEscapeSequence| は、それが寄与する符号位置をエスケープ無しで書いた場合に無効となるような符号位置を |IdentifierName| に寄与するためには使用できない。言い換えると、 ` UnicodeEscapeSequence の並びをそれが寄与する SourceCharacter に置換した場合、結果は元の IdentifierName と同一の SourceCharacter 列を持つ有効な IdentifierName でなければならない。本仕様内の IdentifierName の解釈は、特定符号位置がエスケープシーケンスで与えられたかどうかに関わらず実際のコードポイントに基づく。

Unicode 標準に従い正規等価な 2 つの IdentifierName は、各 UnicodeEscapeSequence を置換した後に完全に同じコードポイント列で表されない限り等しくない

12.7.1.1 静的セマンティクス: 早期エラー (Early Errors)

IdentifierStart :: \ UnicodeEscapeSequence IdentifierPart :: \ UnicodeEscapeSequence

12.7.1.2 静的セマンティクス: IdentifierCodePoints : 符号位置の List

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

IdentifierName :: IdentifierStart
  1. cpIdentifierStart の IdentifierCodePoint とする。
  2. « cp » を返す。
IdentifierName :: IdentifierName IdentifierPart
  1. cps を導出された IdentifierName の IdentifierCodePoints とする。
  2. cpIdentifierPart の IdentifierCodePoint とする。
  3. cps と « cp » のリスト結合を返す。

12.7.1.3 静的セマンティクス: IdentifierCodePoint : 符号位置

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

IdentifierStart :: IdentifierStartChar
  1. IdentifierStartChar によりマッチされた符号位置を返す。
IdentifierPart :: IdentifierPartChar
  1. IdentifierPartChar によりマッチされた符号位置を返す。
UnicodeEscapeSequence :: u Hex4Digits
  1. Hex4Digits の MV の数値値を持つ符号位置を返す。
UnicodeEscapeSequence :: u{ CodePoint }
  1. CodePoint の MV の数値値を持つ符号位置を返す。

12.7.2 キーワードと予約語 (Keywords and Reserved Words)

キーワード (keyword) とは IdentifierName にマッチしかつ構文上の用途(生成規則中に等幅フォントで文字通り出現する)を持つトークンである。ECMAScript のキーワードには if, while, async, await など多数が含まれる。

予約語 (reserved word) とは識別子として使用できない IdentifierName である。多くのキーワードは予約語であるが、そうでないものもあり、また特定の文脈でのみ予約されるものもある。ifwhile は予約語である。await は async 関数およびモジュール内でのみ予約される。async は予約されていないため、変数名やラベルとして制限なく使用できる。

この仕様は文法生成規則および早期エラールールの組み合わせを用いて、どの名前が有効な識別子でどれが予約語かを指定する。下記 ReservedWord 一覧内の awaityield を除くすべてのトークンは無条件に予約される。awaityield の例外は 13.1 でパラメータ化された構文生成規則を用いて指定される。最後に、いくつかの早期エラールールが有効な識別子集合を制限する。13.1.1, 14.3.1.1, 14.7.5.1, 15.7.1 を参照。まとめると識別子名には 5 つの分類がある:

  • 常に識別子として許可されキーワードではないもの(Math, window, toString, _ など);

  • 決して識別子として許可されないもの(awaityield を除く ReservedWord);

  • 文脈的に識別子として許可されるもの(awaityield);

  • strict mode code で文脈的に識別子として不許可となるもの: let, static, implements, interface, package, private, protected, public;

  • 常に識別子として許可されるが、特定の構文生成規則中で Identifier が許可されない位置にキーワードとして現れるもの: as, async, from, get, meta, of, set, target

条件付きキーワード (conditional keyword) または 文脈的キーワード (contextual keyword) という語がしばしば最後の 3 つのカテゴリに属するキーワードを指し、これらは文脈によって識別子またはキーワードとして使用できる。

構文 (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 に従い、文法内のキーワードは特定の SourceCharacter 列をリテラルにマッチする。キーワード中の符号位置は `` |UnicodeEscapeSequence| で表現できない。

IdentifierName` |UnicodeEscapeSequence| を含み得るが、els\u{65}` のように書いて “else” という名前の変数を宣言することはできない。13.1.1 にある早期エラールールが、予約語と同じ StringValue を持つ識別子を除外する。

Note 2

enum は現時点で本仕様においてキーワードとして使用されていない。これは将来の言語拡張でキーワードとして使用するために予約された future reserved word である。

同様に、implements, interface, package, private, protected, publicstrict mode code における future reserved words である。

Note 3

arguments および eval はキーワードではないが strict mode code でいくつかの制限を受ける。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 リテラル (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 はエラーであり、3in の 2 つの入力要素ではない。

12.9.3.1 静的セマンティクス: 早期エラー (Early Errors)

NumericLiteral :: LegacyOctalIntegerLiteral DecimalIntegerLiteral :: NonOctalDecimalIntegerLiteral
  • IsStrict(this production) が true なら構文エラー。
Note
非 strict コードではこの構文は Legacy である。

12.9.3.2 静的セマンティクス: MV

数値リテラルは Number 型または BigInt 型の値を表す。

12.9.3.3 静的セマンティクス: NumericValue : Number または BigInt

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. 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. nNumericLiteralSeparator の出現を除いた DecimalDigits の符号位置数とする。
  2. mv を (NonZeroDigit の MV × 10n) + DecimalDigits の MV とする。
  3. (mv) を返す。

12.9.4 文字列リテラル (String Literals)

Note 1

文字列リテラルは単一または二重引用符で囲まれた 0 個以上の Unicode 符号位置である。Unicode 符号位置はエスケープシーケンスで表すこともできる。閉じ引用符、U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), U+000A (LINE FEED) 以外のすべての符号位置は文字列リテラル内にリテラルに記述可能である。任意の符号位置はエスケープシーケンスの形で出現可能である。文字列リテラルは ECMAScript String 値へと評価される。これらの String 値を生成する際、Unicode 符号位置は 11.1.1 で定義されるように UTF-16 エンコードされる。基本多言語面に属するコードポイントは文字列の 1 つのコードユニット要素としてエンコードされ、それ以外は 2 つのコードユニット要素としてエンコードされる。

構文 (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

非終端 HexDigit の定義は 12.9.3 に、SourceCharacter11.1 にある。

Note 2

<LF> と <CR> は LineContinuation の一部として空の符号位置列を生成する場合を除き文字列リテラル内に現れない。文字列リテラルの String 値にこれらを含める正しい方法は \n\u000A などのエスケープシーケンスを用いることである。

12.9.4.1 静的セマンティクス: 早期エラー (Early Errors)

EscapeSequence :: LegacyOctalEscapeSequence NonOctalDecimalEscapeSequence
  • IsStrict(this production) が true なら構文エラー。
Note 1
非 strict コードではこの構文は Legacy。
Note 2

文字列リテラルは囲むコードを strict mode にする Use Strict ディレクティブより前に現れる可能性があるため、実装はそのようなリテラルに対して上記規則を適用する際注意しなければならない。例えば次のソーステキストは構文エラーを含む:

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

12.9.4.2 静的セマンティクス: SV : String

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS.

文字列リテラルは String 型の値を表す。SV は文字列リテラルの各部分に再帰的に適用され String 値を生成する。この過程で、文字列リテラル内の一部の Unicode 符号位置は下記または 12.9.3 に述べるように数学的値を持つものとして解釈される。

Table 35: 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 静的セマンティクス: MV

12.9.5 正規表現リテラル (Regular Expression Literals)

Note 1

正規表現リテラルは評価のたびに RegExp オブジェクト(22.2 参照)へ変換される入力要素である。プログラム中の 2 つの正規表現リテラルは内容が同一でも === で等しくならない。RegExp オブジェクトは new RegExp またはコンストラクタ呼び出し(22.2.4)で実行時に生成することもできる。

以下の生成規則は正規表現リテラルの構文を記述し、入力要素スキャナが正規表現リテラルの終端を見つけるために用いられる。RegularExpressionBodyRegularExpressionFlags を成すソーステキストは、その後より厳密な ECMAScript 正規表現文法(22.2.1)を用いて再度パースされる。

実装は 22.2.1 で定義される ECMAScript 正規表現文法を拡張してもよいが、下に定義される RegularExpressionBody および RegularExpressionFlags 生成規則、またそれらが使用する生成規則を拡張してはならない。

構文 (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

正規表現リテラルは空にできない。空の正規表現リテラルを表す代わりに // は単一行コメントを開始する。空の正規表現を指定するには /(?:)/ を用いる。

12.9.5.1 静的セマンティクス: BodyText : ソーステキスト

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionBody として認識されたソーステキストを返す。

12.9.5.2 静的セマンティクス: FlagText : ソーステキスト

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. It is defined piecewise over the following productions:

RegularExpressionLiteral :: / RegularExpressionBody / RegularExpressionFlags
  1. RegularExpressionFlags として認識されたソーステキストを返す。

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 の代替字句目標で用いられる。

12.9.6.1 静的セマンティクス: TV : String または undefined

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. テンプレートリテラル構成要素は TV により String 型の値として解釈される。TV はテンプレートオブジェクトのインデックス付き構成要素(テンプレート値)を構成する。TV ではエスケープシーケンスはその Unicode 符号位置を UTF-16 のコードユニットに置換される。

12.9.6.2 静的セマンティクス: TRV : String

The syntax-directed operation UNKNOWN takes UNPARSEABLE ARGUMENTS. テンプレートリテラル構成要素は TRV により String 型の値として解釈される。TRV はテンプレートオブジェクトの raw 構成要素(テンプレート raw 値)を構築する。TRV は TV と似ているが、TRV ではエスケープシーケンスは字面通りのコード単位として扱われる点が異なる。

Note

TV は LineContinuation のコードユニットを除外するが TRV は含む。<CR><LF> と <CR> の LineTerminatorSequence は TV と TRV の両方で <LF> に正規化される。<CR> または <CR><LF> を含めるには明示的な TemplateEscapeSequence が必要。

12.10 自動セミコロン挿入 (Automatic Semicolon Insertion)

ほとんどの ECMAScript 文および宣言はセミコロンで終端されなければならない。これらのセミコロンは常に明示的に記述できる。利便性のため、特定の状況ではそれらを省略できる。これらの状況ではソースコードトークン列へ自動的にセミコロンが挿入されると記述される。

12.10.1 自動セミコロン挿入の規則 (Rules of Automatic Semicolon Insertion)

以下の規則において “token” は 12 に述べる現在の字句目標記号を用いて決定される実際に認識された字句トークンを意味する。

セミコロン挿入には 3 つの基本規則がある:

  1. ソーステキストを左から右へパースする際、いかなる文法生成規則でも許可されないトークン(違反トークン)に遭遇したとき、以下のいずれかが真ならその違反トークンの前にセミコロンが自動挿入される:

    • 違反トークンが直前のトークンと 1 つ以上の LineTerminator で分離されている。
    • 違反トークンが } である。
    • 直前のトークンが ) であり、挿入されたセミコロンが do-while 文 (14.7.2) の終端セミコロンとしてパースされる。
  2. ソーステキストを左から右へパースする際、トークン入力列の終端に到達し、構文解析器が入力トークン列を目標非終端の単一インスタンスとしてパースできないなら、入力列末尾にセミコロンが自動挿入される。
  3. ソーステキストを左から右へパースする際、文法生成規則により許可されるトークンだがその生成規則が制限付き生成規則であり、トークンが制限付き生成規則内の “[no LineTerminator here]” 注釈直後に位置する終端または非終端の先頭トークン(= 制限トークン)であり、その制限トークンが直前トークンと 1 つ以上の LineTerminator で分離されているなら、制限トークンの前にセミコロンが自動挿入される。

ただし上記規則には更に支配的な条件がある: セミコロンが自動挿入された結果それが空文としてパースされる場合、またはそのセミコロンが for 文ヘッダ内の 2 つのセミコロンの一つになる場合(14.7.4 参照)、セミコロンは決して自動挿入されない。

Note

以下は文法中の唯一の制限付き生成規則である:

UpdateExpression[Yield, Await] : LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] ++ LeftHandSideExpression[?Yield, ?Await] [no LineTerminator here] -- 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]

これら制限付き生成規則の実際的効果は次の通り:

  • 後置 ++ または -- が出現し、直前トークンとの間に 1 つ以上の LineTerminator がある場合、その前にセミコロンが自動挿入される。
  • continue, break, return, throw, yield トークンに続いて LineTerminator が現れた場合、それらトークンの直後にセミコロンが自動挿入される。
  • アロー関数パラメータの終わりと => の間に LineTerminator がある場合、セミコロンが挿入され => は構文エラーとなる。
  • async の後に LineTerminator があり、その後に functionIdentifierName( が続く前に改行がある場合、セミコロンが挿入され async は後続と同じ式/クラス要素と扱われない。
  • async の後に LineTerminator があり、その後に * が来る場合、セミコロンが挿入され * は構文エラーとなる。

実務上の指針:

  • 後置 ++ / -- はオペランドと同じ行に置く。
  • return / throw / yield の後に続く式は同じ行で開始する。
  • break / continueLabelIdentifier は同じ行に置く。
  • アロー関数のパラメータ終端と => は同じ行に置く。
  • 非同期関数やメソッドの直前の async は直後のトークンと同じ行に置く。

12.10.2 自動セミコロン挿入の例 (Examples of Automatic Semicolon Insertion)

この節は規範的でない (non-normative)。

次のソース

{ 1 2 } 3

は自動セミコロン挿入規則を考慮しても ECMAScript 文法の妥当な文ではない。対照的に次のソース

{ 1
2 } 3

も妥当ではないが、自動セミコロン挿入により以下に変換される:

{ 1
;2 ;} 3;

これは妥当な ECMAScript 文である。

次のソース

for (a; b
)

は妥当ではなく、自動セミコロン挿入で変更されない。これは for 文ヘッダのセミコロンが必要であり、自動挿入は for ヘッダ内 2 つのセミコロンのいずれも挿入しないためである。

次のソース

return
a + b

は次に変換される:

return;
a + b;
Note 1

a + breturn 文で返される値として扱われない。LineTerminatorreturn トークンとそれに続く式を分離するためである。

次のソース

a = b
++c

は以下に変換される:

a = b;
++c;
Note 2

++ トークンは変数 b への後置演算子として扱われない。b++ の間に LineTerminator があるため。

次のソース

if (a > b)
else c = d

は妥当ではなく、else トークンの前には自動セミコロン挿入による変化は起こらない。文法生成規則が適用できない地点ではあるが、挿入された場合空文になるため。

次のソース

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

は自動セミコロン挿入で変換されない。2 行目冒頭の括弧付き式は関数呼び出しの引数リストと解釈できるためである:

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

代入文が左括弧で始まらなければならない状況では、自動セミコロン挿入に頼らず前の文末に明示的なセミコロンを置くべきである。

12.10.3 自動セミコロン挿入の興味深いケース (Interesting Cases of Automatic Semicolon Insertion)

この節は規範的でない。

ECMAScript プログラムは自動セミコロン挿入に依存することで非常に少ないセミコロンで書くことができる。上述のようにセミコロンはすべての改行で挿入されるわけではなく、挿入は複数トークンにまたがる。

ECMAScript に新しい構文機能が追加されると、追加の構文生成規則が導入され、自動セミコロン挿入に依存する行がパース時に使用する生成規則を変化させる可能性がある。

本節では、前に現れるソーステキストによってセミコロンが挿入されるか否かが変わりうる箇所を興味深いケースとみなす。本バージョンでの自動セミコロン挿入のいくつかの興味深いケースを以下で説明する。

12.10.3.1 文リストにおける自動セミコロン挿入の興味深いケース

StatementList では多くの StatementListItem がセミコロンで終わり、自動セミコロン挿入により省略できる。上記規則の結果、式で終わる行の末尾で、次の行が以下のいずれかで始まる場合セミコロンが必要になる:

  • 開き丸括弧 (()。セミコロンがなければ 2 行は CallExpression とみなされる。
  • 開き角括弧 ([)。セミコロンがなければ 2 行は ArrayLiteral / ArrayAssignmentPattern ではなくプロパティアクセスと解釈される。
  • テンプレートリテラル (`)。セミコロンがなければ 2 行は前の式を MemberExpression とするタグ付きテンプレート (13.3.11) と解釈される。
  • 単項 + または -。セミコロンがなければ 2 行は対応する二項演算子の使用と解釈され得る。
  • RegExp リテラル。セミコロンがなければ 2 行は / MultiplicativeOperator として(正規表現にフラグがある場合など)パースされ得る。

12.10.3.2 “[no LineTerminator here]” を伴う自動セミコロン挿入のケース

この節は規範的でない。

ECMAScript には “[no LineTerminator here]” を含む生成規則があり、これらはしばしば文法における省略可能オペランドを実現する手段である。これら位置に LineTerminator を導入すると省略可能オペランドを持たない別生成規則の使用へ切り替わる。

以下では本バージョンの “[no LineTerminator here]” を使用するいくつかの生成規則を列挙する。

12.10.3.2.1 省略可能オペランドと “[no LineTerminator here]” を持つ生成規則一覧