19.2.1 eval (x )
This function is the%eval% intrinsic object.
It performs the following steps when called:
- Return ? PerformEval(x,false,false).
19.2.1.1 PerformEval (x,strictCaller,direct )
The abstract operation PerformEval takes argumentsx (anECMAScript language value),strictCaller (a Boolean), anddirect (a Boolean) and returns either anormal completion containing anECMAScript language value or athrow completion. It performs the following steps when called:
- Assert: Ifdirect isfalse, thenstrictCaller is alsofalse.
- Ifxis not a String, returnx.
- LetevalRealm bethe current Realm Record.
- NOTE: In the case of adirect eval,evalRealm is therealm of both the caller of
eval
and of theeval
function itself. - Perform ? HostEnsureCanCompileStrings(evalRealm, « »,x,direct).
- LetinFunction befalse.
- LetinMethod befalse.
- LetinDerivedConstructor befalse.
- LetinClassFieldInitializer befalse.
- Ifdirect istrue, then
- LetthisEnvRec beGetThisEnvironment().
- IfthisEnvRec is aFunction Environment Record, then
- LetF bethisEnvRec.[[FunctionObject]].
- SetinFunction totrue.
- SetinMethod tothisEnvRec.HasSuperBinding().
- IfF.[[ConstructorKind]] isderived, setinDerivedConstructor totrue.
- LetclassFieldInitializerName beF.[[ClassFieldInitializerName]].
- IfclassFieldInitializerName is notempty, setinClassFieldInitializer totrue.
- Perform the following substeps in animplementation-defined order, possibly interleaving parsing and error detection:
- Letscript beParseText(x,Script).
- Ifscript is aList of errors, throw aSyntaxError exception.
- IfscriptContainsScriptBody isfalse, returnundefined.
- Letbody be theScriptBody ofscript.
- IfinFunction isfalse andbodyContainsNewTarget, throw aSyntaxError exception.
- IfinMethod isfalse andbodyContainsSuperProperty, throw aSyntaxError exception.
- IfinDerivedConstructor isfalse andbodyContainsSuperCall, throw aSyntaxError exception.
- IfinClassFieldInitializer istrue andContainsArguments ofbody istrue, throw aSyntaxError exception.
- IfstrictCaller istrue, letstrictEval betrue.
- Else, letstrictEval beScriptIsStrict ofscript.
- LetrunningContext be therunning execution context.
- NOTE: Ifdirect istrue,runningContext will be theexecution context that performed thedirect eval. Ifdirect isfalse,runningContext will be theexecution context for the invocation of the
eval
function. - Ifdirect istrue, then
- LetlexEnv beNewDeclarativeEnvironment(runningContext's LexicalEnvironment).
- LetvarEnv berunningContext's VariableEnvironment.
- LetprivateEnv berunningContext's PrivateEnvironment.
- Else,
- LetlexEnv beNewDeclarativeEnvironment(evalRealm.[[GlobalEnv]]).
- LetvarEnv beevalRealm.[[GlobalEnv]].
- LetprivateEnv benull.
- IfstrictEval istrue, setvarEnv tolexEnv.
- IfrunningContext is not already suspended, suspendrunningContext.
- LetevalContext be a newECMAScript code execution context.
- SetevalContext's Function tonull.
- SetevalContext'sRealm toevalRealm.
- SetevalContext's ScriptOrModule torunningContext's ScriptOrModule.
- SetevalContext's VariableEnvironment tovarEnv.
- SetevalContext's LexicalEnvironment tolexEnv.
- SetevalContext's PrivateEnvironment toprivateEnv.
- PushevalContext onto theexecution context stack;evalContext is now therunning execution context.
- Letresult beCompletion(EvalDeclarationInstantiation(body,varEnv,lexEnv,privateEnv,strictEval)).
- Ifresult is anormal completion, then
- Setresult toCompletion(Evaluation ofbody).
- Ifresult is anormal completion andresult.[[Value]] isempty, then
- Setresult toNormalCompletion(undefined).
- SuspendevalContext and remove it from theexecution context stack.
- Resume the context that is now on the top of theexecution context stack as therunning execution context.
- Return ? result.
NoteThe eval code cannot instantiate variable or function bindings in the variable environment of the calling context that invoked the eval if either the code of the calling context or the eval code isstrict mode code. Instead such bindings are instantiated in a new VariableEnvironment that is only accessible to the eval code. Bindings introduced bylet
,const
, orclass
declarations are always instantiated in a new LexicalEnvironment.
19.2.1.2 HostEnsureCanCompileStrings (calleeRealm,parameterStrings,bodyString,direct )
Thehost-defined abstract operation HostEnsureCanCompileStrings takes argumentscalleeRealm (aRealm Record),parameterStrings (aList of Strings),bodyString (a String), anddirect (a Boolean) and returns either anormal completion containingunused or athrow completion. It allowshost environments to block certain ECMAScript functions which allow developers to interpret and evaluate strings as ECMAScript code.
parameterStrings represents the strings that, when using one of the functionconstructors, will be concatenated together to build the parameters list.bodyString represents the function body or the string passed to aneval
call.direct signifies whether the evaluation is adirect eval.
The default implementation of HostEnsureCanCompileStrings is to returnNormalCompletion(unused).
19.2.1.3 EvalDeclarationInstantiation (body,varEnv,lexEnv,privateEnv,strict )
The abstract operation EvalDeclarationInstantiation takes argumentsbody (aScriptBodyParse Node),varEnv (anEnvironment Record),lexEnv (aDeclarative Environment Record),privateEnv (aPrivateEnvironment Record ornull), andstrict (a Boolean) and returns either anormal completion containingunused or athrow completion. It performs the following steps when called:
- LetvarNames be theVarDeclaredNames ofbody.
- LetvarDeclarations be theVarScopedDeclarations ofbody.
- Ifstrict isfalse, then
- IfvarEnv is aGlobal Environment Record, then
- For each elementname ofvarNames, do
- IfHasLexicalDeclaration(varEnv,name) istrue, throw aSyntaxError exception.
- NOTE:
eval
will not create a global var declaration that would be shadowed by a global lexical declaration.
- LetthisEnv belexEnv.
- Assert: The following loop will terminate.
- Repeat, whilethisEnv andvarEnv are not the sameEnvironment Record,
- IfthisEnvis not an ObjectEnvironment Record, then
- NOTE: The environment of with statements cannot contain any lexical declaration so it doesn't need to be checked for var/let hoisting conflicts.
- For each elementname ofvarNames, do
- If ! thisEnv.HasBinding(name) istrue, then
- If thehost is a web browser or otherwise supportsVariableStatements in Catch Blocks, then
- IfthisEnv is not theEnvironment Record for aCatch clause, throw aSyntaxError exception.
- Else,
- Throw aSyntaxError exception.
- NOTE: Adirect eval will not hoist var declaration over a like-named lexical declaration.
- SetthisEnv tothisEnv.[[OuterEnv]].
- LetprivateIdentifiers be a new emptyList.
- Letpointer beprivateEnv.
- Repeat, whilepointer is notnull,
- For eachPrivate Namebinding ofpointer.[[Names]], do
- IfprivateIdentifiers does not containbinding.[[Description]], appendbinding.[[Description]] toprivateIdentifiers.
- Setpointer topointer.[[OuterPrivateEnvironment]].
- IfAllPrivateIdentifiersValid ofbody with argumentprivateIdentifiers isfalse, throw aSyntaxError exception.
- LetfunctionsToInitialize be a new emptyList.
- LetdeclaredFunctionNames be a new emptyList.
- For each elementd ofvarDeclarations, in reverseList order, do
- Ifd is not either aVariableDeclaration, aForBinding, or aBindingIdentifier, then
- Assert:d is either aFunctionDeclaration, aGeneratorDeclaration, anAsyncFunctionDeclaration, or anAsyncGeneratorDeclaration.
- NOTE: If there are multiple function declarations for the same name, the last declaration is used.
- Letfn be the sole element of theBoundNames ofd.
- IfdeclaredFunctionNames does not containfn, then
- IfvarEnv is aGlobal Environment Record, then
- LetfnDefinable be ? CanDeclareGlobalFunction(varEnv,fn).
- IffnDefinable isfalse, throw aTypeError exception.
- Appendfn todeclaredFunctionNames.
- Insertd as the first element offunctionsToInitialize.
- LetdeclaredVarNames be a new emptyList.
- For each elementd ofvarDeclarations, do
- Ifd is either aVariableDeclaration, aForBinding, or aBindingIdentifier, then
- For each Stringvn of theBoundNames ofd, do
- IfdeclaredFunctionNames does not containvn, then
- IfvarEnv is aGlobal Environment Record, then
- LetvnDefinable be ? CanDeclareGlobalVar(varEnv,vn).
- IfvnDefinable isfalse, throw aTypeError exception.
- IfdeclaredVarNames does not containvn, then
- Appendvn todeclaredVarNames.
- Ifstrict isfalse and thehost is a web browser or otherwise supportsBlock-Level Function Declarations Web Legacy Compatibility Semantics, then
- LetdeclaredFunctionOrVarNames be thelist-concatenation ofdeclaredFunctionNames anddeclaredVarNames.
- For eachFunctionDeclarationf that is directly contained in theStatementList of anyBlock,CaseClause, orDefaultClausex such thatbodyContainsx istrue, do
- LetF be theStringValue of theBindingIdentifier off.
- If replacing theFunctionDeclarationf with aVariableStatement that hasF as aBindingIdentifier would not produce any Early Errors forbody, then
- LetbindingExists befalse.
- SetthisEnv tolexEnv.
- Assert: The following loop will terminate.
- Repeat, whilethisEnv is notvarEnv,
- IfthisEnvis not an ObjectEnvironment Record, then
- If ! thisEnv.HasBinding(F) istrue, then
- If thehost is a web browser or otherwise supportsVariableStatements in Catch Blocks, then
- IfthisEnv is not theEnvironment Record for aCatch clause, setbindingExists totrue.
- Else,
- SetbindingExists totrue.
- SetthisEnv tothisEnv.[[OuterEnv]].
- IfbindingExists isfalse andvarEnv is aGlobal Environment Record, then
- IfHasLexicalDeclaration(varEnv,F) isfalse, then
- LetfnDefinable be ? CanDeclareGlobalVar(varEnv,F).
- Else,
- LetfnDefinable befalse.
- Else,
- LetfnDefinable betrue.
- IfbindingExists isfalse andfnDefinable istrue, then
- IfdeclaredFunctionOrVarNames does not containF, then
- IfvarEnv is aGlobal Environment Record, then
- Perform ? CreateGlobalVarBinding(varEnv,F,true).
- Else,
- SetbindingExists to ! varEnv.HasBinding(F).
- IfbindingExists isfalse, then
- Perform ! varEnv.CreateMutableBinding(F,true).
- Perform ! varEnv.InitializeBinding(F,undefined).
- AppendF todeclaredFunctionOrVarNames.
- When theFunctionDeclarationf is evaluated, perform the following steps in place of theFunctionDeclarationEvaluation algorithm provided in15.2.6:
- LetgEnv be therunning execution context's VariableEnvironment.
- LetbEnv be therunning execution context's LexicalEnvironment.
- LetfObj be ! bEnv.GetBindingValue(F,false).
- Perform ? gEnv.SetMutableBinding(F,fObj,false).
- Returnunused.
- NOTE: No abnormal terminations occur after this algorithm step unlessvarEnv is aGlobal Environment Record and theglobal object is aProxy exotic object.
- LetlexDeclarations be theLexicallyScopedDeclarations ofbody.
- For each elementd oflexDeclarations, do
- NOTE: Lexically declared names are only instantiated here but not initialized.
- For each elementdn of theBoundNames ofd, do
- IfIsConstantDeclaration ofd istrue, then
- Perform ? lexEnv.CreateImmutableBinding(dn,true).
- Else,
- Perform ? lexEnv.CreateMutableBinding(dn,false).
- For eachParse Nodef offunctionsToInitialize, do
- Letfn be the sole element of theBoundNames off.
- Letfo beInstantiateFunctionObject off with argumentslexEnv andprivateEnv.
- IfvarEnv is aGlobal Environment Record, then
- Perform ? CreateGlobalFunctionBinding(varEnv,fn,fo,true).
- Else,
- LetbindingExists be ! varEnv.HasBinding(fn).
- IfbindingExists isfalse, then
- NOTE: The following invocation cannot return anabrupt completion because of the validation preceding step14.
- Perform ! varEnv.CreateMutableBinding(fn,true).
- Perform ! varEnv.InitializeBinding(fn,fo).
- Else,
- Perform ! varEnv.SetMutableBinding(fn,fo,false).
- For each Stringvn ofdeclaredVarNames, do
- IfvarEnv is aGlobal Environment Record, then
- Perform ? CreateGlobalVarBinding(varEnv,vn,true).
- Else,
- LetbindingExists be ! varEnv.HasBinding(vn).
- IfbindingExists isfalse, then
- NOTE: The following invocation cannot return anabrupt completion because of the validation preceding step14.
- Perform ! varEnv.CreateMutableBinding(vn,true).
- Perform ! varEnv.InitializeBinding(vn,undefined).
- Returnunused.
19.2.5 parseInt (string,radix )
This function produces anintegral Number dictated by interpretation of the contents ofstring according to the specifiedradix. Leading white space instring is ignored. Ifradix coerces to 0 (such as when it isundefined), it is assumed to be 10 except when the number representation begins with"0x" or"0X", in which case it is assumed to be 16. Ifradix is 16, the number representation may optionally begin with"0x" or"0X".
It is the%parseInt% intrinsic object.
It performs the following steps when called:
- LetinputString be ? ToString(string).
- LetS be ! TrimString(inputString,start).
- Letsign be 1.
- IfS is not empty and the first code unit ofS is the code unit 0x002D (HYPHEN-MINUS), setsign to -1.
- IfS is not empty and the first code unit ofS is either the code unit 0x002B (PLUS SIGN) or the code unit 0x002D (HYPHEN-MINUS), setS to thesubstring ofS from index 1.
- LetR beℝ(?ToInt32(radix)).
- LetstripPrefix betrue.
- IfR ≠ 0, then
- IfR < 2 orR > 36, returnNaN.
- IfR ≠ 16, setstripPrefix tofalse.
- Else,
- SetR to 10.
- IfstripPrefix istrue, then
- If the length ofS ≥ 2 and the first two code units ofS are either"0x" or"0X", then
- SetS to thesubstring ofS from index 2.
- SetR to 16.
- IfS contains a code unit that is not a radix-R digit, letend be the index withinS of the first such code unit; otherwise letend be the length ofS.
- LetZ be thesubstring ofS from 0 toend.
- IfZ is empty, returnNaN.
- LetmathInt be theinteger value that is represented byZ in radix-R notation, using the lettersA throughZ anda throughz for digits with values 10 through 35. (However, ifR = 10 andZ contains more than 20 significant digits, every significant digit after the 20th may be replaced by a 0 digit, at the option of the implementation; and ifR is not one of 2, 4, 8, 10, 16, or 32, thenmathInt may be animplementation-approximatedinteger representing theinteger value denoted byZ in radix-R notation.)
- IfmathInt = 0, then
- Ifsign = -1, return-0𝔽.
- Return+0𝔽.
- Return𝔽(sign ×mathInt).
NoteThis function may interpret only a leading portion ofstring as aninteger value; it ignores any code units that cannot be interpreted as part of the notation of aninteger, and no indication is given that any such code units were ignored.
19.2.6 URI Handling Functions
Uniform Resource Identifiers, or URIs, are Strings that identify resources (e.g. web pages or files) and transport protocols by which to access them (e.g. HTTP or FTP) on the Internet. The ECMAScript language itself does not provide any support for using URIs except for functions that encode and decode URIs as described in this section.encodeURI
anddecodeURI
are intended to work with complete URIs; they assume that any reserved characters are intended to have special meaning (e.g., as delimiters) and so are not encoded.encodeURIComponent
anddecodeURIComponent
are intended to work with the individual components of a URI; they assume that any reserved characters represent text and must be encoded to avoid special meaning when the component is part of a complete URI.
Note 1The set of reserved characters is based upon RFC 2396 and does not reflect changes introduced by the more recent RFC 3986.
Note 2Many implementations of ECMAScript provide additional functions and methods that manipulate web pages; these functions are beyond the scope of this standard.
19.2.6.1 decodeURI (encodedURI )
This function computes a new version of a URI in which each escape sequence and UTF-8 encoding of the sort that might be introduced by theencodeURI
function is replaced with the UTF-16 encoding of the code point that it represents. Escape sequences that could not have been introduced byencodeURI
are not replaced.
It is the%decodeURI% intrinsic object.
It performs the following steps when called:
- LeturiString be ? ToString(encodedURI).
- LetpreserveEscapeSet be";/?:@&=+$,#".
- Return ? Decode(uriString,preserveEscapeSet).
19.2.6.2 decodeURIComponent (encodedURIComponent )
This function computes a new version of a URI in which each escape sequence and UTF-8 encoding of the sort that might be introduced by theencodeURIComponent
function is replaced with the UTF-16 encoding of the code point that it represents.
It is the%decodeURIComponent% intrinsic object.
It performs the following steps when called:
- LetcomponentString be ? ToString(encodedURIComponent).
- LetpreserveEscapeSet be the empty String.
- Return ? Decode(componentString,preserveEscapeSet).
19.2.6.3 encodeURI (uri )
This function computes a new version of a UTF-16 encoded (6.1.4) URI in which each instance of certain code points is replaced by one, two, three, or four escape sequences representing the UTF-8 encoding of the code point.
It is the%encodeURI% intrinsic object.
It performs the following steps when called:
- LeturiString be ? ToString(uri).
- LetextraUnescaped be";/?:@&=+$,#".
- Return ? Encode(uriString,extraUnescaped).
19.2.6.4 encodeURIComponent (uriComponent )
This function computes a new version of a UTF-16 encoded (6.1.4) URI in which each instance of certain code points is replaced by one, two, three, or four escape sequences representing the UTF-8 encoding of the code point.
It is the%encodeURIComponent% intrinsic object.
It performs the following steps when called:
- LetcomponentString be ? ToString(uriComponent).
- LetextraUnescaped be the empty String.
- Return ? Encode(componentString,extraUnescaped).
19.2.6.5 Encode (string,extraUnescaped )
The abstract operation Encode takes argumentsstring (a String) andextraUnescaped (a String) and returns either anormal completion containing a String or athrow completion. It performs URI encoding and escaping, interpretingstring as a sequence of UTF-16 encoded code points as described in6.1.4. If a character is identified as unreserved in RFC 2396 or appears inextraUnescaped, it is not escaped. It performs the following steps when called:
- Letlen be the length ofstring.
- LetR be the empty String.
- LetalwaysUnescaped be thestring-concatenation ofthe ASCII word characters and"-.!~*'()".
- LetunescapedSet be thestring-concatenation ofalwaysUnescaped andextraUnescaped.
- Letk be 0.
- Repeat, whilek <len,
- LetC be the code unit at indexk withinstring.
- IfunescapedSet containsC, then
- Setk tok + 1.
- SetR to thestring-concatenation ofR andC.
- Else,
- Letcp beCodePointAt(string,k).
- Ifcp.[[IsUnpairedSurrogate]] istrue, throw aURIError exception.
- Setk tok +cp.[[CodeUnitCount]].
- LetOctets be theList of octets resulting by applying the UTF-8 transformation tocp.[[CodePoint]].
- For each elementoctet ofOctets, do
- Lethex be the String representation ofoctet, formatted as an uppercase hexadecimal number.
- SetR to thestring-concatenation ofR,"%", andStringPad(hex, 2,"0",start).
- ReturnR.
NoteBecause percent-encoding is used to represent individual octets, a single code point may be expressed as multiple consecutive escape sequences (one for each of its 8-bit UTF-8 code units).
19.2.6.6 Decode (string,preserveEscapeSet )
The abstract operation Decode takes argumentsstring (a String) andpreserveEscapeSet (a String) and returns either anormal completion containing a String or athrow completion. It performs URI unescaping and decoding, preserving any escape sequences that correspond to Basic Latin characters inpreserveEscapeSet. It performs the following steps when called:
- Letlen be the length ofstring.
- LetR be the empty String.
- Letk be 0.
- Repeat, whilek <len,
- LetC be the code unit at indexk withinstring.
- LetS beC.
- IfC is the code unit 0x0025 (PERCENT SIGN), then
- Ifk + 3 >len, throw aURIError exception.
- Letescape be thesubstring ofstring fromk tok + 3.
- LetB beParseHexOctet(string,k + 1).
- IfB is not aninteger, throw aURIError exception.
- Setk tok + 2.
- Letn be the number of leading 1 bits inB.
- Ifn = 0, then
- LetasciiChar be the code unit whose numeric value isB.
- IfpreserveEscapeSet containsasciiChar, setS toescape; otherwise setS toasciiChar.
- Else,
- Ifn = 1 orn > 4, throw aURIError exception.
- LetOctets be «B ».
- Letj be 1.
- Repeat, whilej <n,
- Setk tok + 1.
- Ifk + 3 >len, throw aURIError exception.
- If the code unit at indexk withinstring is not the code unit 0x0025 (PERCENT SIGN), throw aURIError exception.
- LetcontinuationByte beParseHexOctet(string,k + 1).
- IfcontinuationByte is not aninteger, throw aURIError exception.
- AppendcontinuationByte toOctets.
- Setk tok + 2.
- Setj toj + 1.
- Assert: The length ofOctets isn.
- IfOctets does not contain a valid UTF-8 encoding of a Unicode code point, throw aURIError exception.
- LetV be the code point obtained by applying the UTF-8 transformation toOctets, that is, from aList of octets into a 21-bit value.
- SetS toUTF16EncodeCodePoint(V).
- SetR to thestring-concatenation ofR andS.
- Setk tok + 1.
- ReturnR.
NoteRFC 3629 prohibits the decoding of invalid UTF-8 octet sequences. For example, the invalid sequence 0xC0 0x80 must not decode into the code unit 0x0000. Implementations of the Decode algorithm are required to throw aURIError when encountering such invalid sequences.
19.2.6.7 ParseHexOctet (string,position )
The abstract operation ParseHexOctet takes argumentsstring (a String) andposition (a non-negativeinteger) and returns either a non-negativeinteger or a non-emptyList ofSyntaxError objects. It parses a sequence of two hexadecimal characters at the specifiedposition instring into an unsigned 8-bitinteger. It performs the following steps when called:
- Letlen be the length ofstring.
- Assert:position + 2 ≤len.
- LethexDigits be thesubstring ofstring fromposition toposition + 2.
- LetparseResult beParseText(hexDigits,HexDigits[~Sep]).
- IfparseResult is not aParse Node, returnparseResult.
- Letn be the MV ofparseResult.
- Assert:n is in theinclusive interval from 0 to 255.
- Returnn.