idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
31,700
private void generateResumeGenerator ( ClassFileWriter cfw ) { boolean hasGenerators = false ; for ( int i = 0 ; i < scriptOrFnNodes . length ; i ++ ) { if ( isGenerator ( scriptOrFnNodes [ i ] ) ) hasGenerators = true ; } if ( ! hasGenerators ) return ; cfw . startMethod ( "resumeGenerator" , "(Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "ILjava/lang/Object;" + "Ljava/lang/Object;)Ljava/lang/Object;" , ( short ) ( ACC_PUBLIC | ACC_FINAL ) ) ; cfw . addALoad ( 0 ) ; cfw . addALoad ( 1 ) ; cfw . addALoad ( 2 ) ; cfw . addALoad ( 4 ) ; cfw . addALoad ( 5 ) ; cfw . addILoad ( 3 ) ; cfw . addLoadThis ( ) ; cfw . add ( ByteCode . GETFIELD , cfw . getClassName ( ) , ID_FIELD_NAME , "I" ) ; int startSwitch = cfw . addTableSwitch ( 0 , scriptOrFnNodes . length - 1 ) ; cfw . markTableSwitchDefault ( startSwitch ) ; int endlabel = cfw . acquireLabel ( ) ; for ( int i = 0 ; i < scriptOrFnNodes . length ; i ++ ) { ScriptNode n = scriptOrFnNodes [ i ] ; cfw . markTableSwitchCase ( startSwitch , i , ( short ) 6 ) ; if ( isGenerator ( n ) ) { String type = "(" + mainClassSignature + "Lorg/mozilla/javascript/Context;" + "Lorg/mozilla/javascript/Scriptable;" + "Ljava/lang/Object;" + "Ljava/lang/Object;I)Ljava/lang/Object;" ; cfw . addInvoke ( ByteCode . INVOKESTATIC , mainClassName , getBodyMethodName ( n ) + "_gen" , type ) ; cfw . add ( ByteCode . ARETURN ) ; } else { cfw . add ( ByteCode . GOTO , endlabel ) ; } } cfw . markLabel ( endlabel ) ; pushUndefined ( cfw ) ; cfw . add ( ByteCode . ARETURN ) ; cfw . stopMethod ( ( short ) 6 ) ; }
appended by _gen .
31,701
String cleanName ( final ScriptNode n ) { String result = "" ; if ( n instanceof FunctionNode ) { Name name = ( ( FunctionNode ) n ) . getFunctionName ( ) ; if ( name == null ) { result = "anonymous" ; } else { result = name . getIdentifier ( ) ; } } else { result = "script" ; } return result ; }
Gets a Java - compatible informative name for the the ScriptOrFnNode
31,702
private void addLoadPropertyIds ( Object [ ] properties , int count ) { addNewObjectArray ( count ) ; for ( int i = 0 ; i != count ; ++ i ) { cfw . add ( ByteCode . DUP ) ; cfw . addPush ( i ) ; Object id = properties [ i ] ; if ( id instanceof String ) { cfw . addPush ( ( String ) id ) ; } else { cfw . addPush ( ( ( Integer ) id ) . intValue ( ) ) ; addScriptRuntimeInvoke ( "wrapInt" , "(I)Ljava/lang/Integer;" ) ; } cfw . add ( ByteCode . AASTORE ) ; } }
load array with property ids
31,703
private void addLoadPropertyValues ( Node node , Node child , int count ) { if ( isGenerator ) { for ( int i = 0 ; i != count ; ++ i ) { int childType = child . getType ( ) ; if ( childType == Token . GET || childType == Token . SET || childType == Token . METHOD ) { generateExpression ( child . getFirstChild ( ) , node ) ; } else { generateExpression ( child , node ) ; } child = child . getNext ( ) ; } addNewObjectArray ( count ) ; for ( int i = 0 ; i != count ; ++ i ) { cfw . add ( ByteCode . DUP_X1 ) ; cfw . add ( ByteCode . SWAP ) ; cfw . addPush ( count - i - 1 ) ; cfw . add ( ByteCode . SWAP ) ; cfw . add ( ByteCode . AASTORE ) ; } } else { addNewObjectArray ( count ) ; Node child2 = child ; for ( int i = 0 ; i != count ; ++ i ) { cfw . add ( ByteCode . DUP ) ; cfw . addPush ( i ) ; int childType = child2 . getType ( ) ; if ( childType == Token . GET || childType == Token . SET || childType == Token . METHOD ) { generateExpression ( child2 . getFirstChild ( ) , node ) ; } else { generateExpression ( child2 , node ) ; } cfw . add ( ByteCode . AASTORE ) ; child2 = child2 . getNext ( ) ; } } }
load array with property values
31,704
private void inlineFinally ( Node finallyTarget , int finallyStart , int finallyEnd ) { Node fBlock = getFinallyAtTarget ( finallyTarget ) ; fBlock . resetTargets ( ) ; Node child = fBlock . getFirstChild ( ) ; exceptionManager . markInlineFinallyStart ( fBlock , finallyStart ) ; while ( child != null ) { generateStatement ( child ) ; child = child . getNext ( ) ; } exceptionManager . markInlineFinallyEnd ( fBlock , finallyEnd ) ; }
Inline a FINALLY node into the method bytecode .
31,705
private Node getFinallyAtTarget ( Node node ) { if ( node == null ) { return null ; } if ( node . getType ( ) == Token . FINALLY ) { return node ; } if ( node . getType ( ) == Token . TARGET ) { Node fBlock = node . getNext ( ) ; if ( fBlock != null && fBlock . getType ( ) == Token . FINALLY ) { return fBlock ; } } throw Kit . codeBug ( "bad finally target" ) ; }
Get a FINALLY node at a point in the IR .
31,706
public static org . w3c . dom . Node toDomNode ( Object xmlObject ) { if ( xmlObject instanceof XML ) { return ( ( XML ) xmlObject ) . toDomNode ( ) ; } else { throw new IllegalArgumentException ( "xmlObject is not an XML object in JavaScript." ) ; } }
This experimental interface is undocumented .
31,707
public void visit ( NodeVisitor v ) { if ( v . visit ( this ) ) { expression . visit ( v ) ; statement . visit ( v ) ; } }
Visits this node then the with - object then the body statement .
31,708
public static Object write ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) { return doPrint ( args , funObj , false ) ; }
Print just as in print but without the trailing newline .
31,709
public static void quit ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) { Global global = getInstance ( funObj ) ; if ( global . quitAction != null ) { int exitCode = ( args . length == 0 ? 0 : ScriptRuntime . toInt32 ( args [ 0 ] ) ) ; global . quitAction . quit ( cx , exitCode ) ; } }
Call embedding - specific quit action passing its argument as int32 exit code .
31,710
public static Object spawn ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) { Scriptable scope = funObj . getParentScope ( ) ; Runner runner ; if ( args . length != 0 && args [ 0 ] instanceof Function ) { Object [ ] newArgs = null ; if ( args . length > 1 && args [ 1 ] instanceof Scriptable ) { newArgs = cx . getElements ( ( Scriptable ) args [ 1 ] ) ; } if ( newArgs == null ) { newArgs = ScriptRuntime . emptyArgs ; } runner = new Runner ( scope , ( Function ) args [ 0 ] , newArgs ) ; } else if ( args . length != 0 && args [ 0 ] instanceof Script ) { runner = new Runner ( scope , ( Script ) args [ 0 ] ) ; } else { throw reportRuntimeError ( "msg.spawn.args" ) ; } runner . factory = cx . getFactory ( ) ; Thread thread = new Thread ( runner ) ; thread . start ( ) ; return thread ; }
The spawn function runs a given function or script in a different thread .
31,711
public static void seal ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) { for ( int i = 0 ; i != args . length ; ++ i ) { Object arg = args [ i ] ; if ( ! ( arg instanceof ScriptableObject ) || arg == Undefined . instance ) { if ( ! ( arg instanceof Scriptable ) || arg == Undefined . instance ) { throw reportRuntimeError ( "msg.shell.seal.not.object" ) ; } else { throw reportRuntimeError ( "msg.shell.seal.not.scriptable" ) ; } } } for ( int i = 0 ; i != args . length ; ++ i ) { Object arg = args [ i ] ; ( ( ScriptableObject ) arg ) . sealObject ( ) ; } }
The seal function seals all supplied arguments .
31,712
public static Object toint32 ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) { Object arg = ( args . length != 0 ? args [ 0 ] : Undefined . instance ) ; if ( arg instanceof Integer ) return arg ; return ScriptRuntime . wrapInt ( ScriptRuntime . toInt32 ( arg ) ) ; }
Convert the argument to int32 number .
31,713
public String getJsDoc ( ) { Comment comment = getJsDocNode ( ) ; if ( comment != null ) { return comment . getValue ( ) ; } return null ; }
Gets the JsDoc comment string attached to this node .
31,714
public void addChildAfter ( Node newChild , Node node ) { if ( newChild . next != null ) throw new RuntimeException ( "newChild had siblings in addChildAfter" ) ; newChild . next = node . next ; node . next = newChild ; if ( last == node ) last = newChild ; }
Add child after node .
31,715
private int endCheckIf ( ) { Node th , el ; int rv = END_UNREACHED ; th = next ; el = ( ( Jump ) this ) . target ; rv = th . endCheck ( ) ; if ( el != null ) rv |= el . endCheck ( ) ; else rv |= END_DROPS_OFF ; return rv ; }
Returns in the then and else blocks must be consistent with each other . If there is no else block then the return statement can fall through .
31,716
private int endCheckLabel ( ) { int rv = END_UNREACHED ; rv = next . endCheck ( ) ; rv |= getIntProp ( CONTROL_BLOCK_PROP , END_UNREACHED ) ; return rv ; }
A labelled statement implies that there maybe a break to the label . The function processes the labelled statement and then checks the CONTROL_BLOCK_PROP property to see if there is ever a break to the particular label .
31,717
private int endCheckBreak ( ) { Node n = ( ( Jump ) this ) . getJumpStatement ( ) ; n . putIntProp ( CONTROL_BLOCK_PROP , END_DROPS_OFF ) ; return END_UNREACHED ; }
When a break is encountered annotate the statement being broken out of by setting its CONTROL_BLOCK_PROP property .
31,718
public void visit ( NodeVisitor v ) { if ( v . visit ( this ) && returnValue != null ) { returnValue . visit ( v ) ; } }
Visits this node then the return value if specified .
31,719
public void setBreakOnExceptions ( boolean value ) { dim . setBreakOnExceptions ( value ) ; debugGui . getMenubar ( ) . getBreakOnExceptions ( ) . setSelected ( value ) ; }
Sets whether execution should break when a script exception is thrown .
31,720
public void setBreakOnEnter ( boolean value ) { dim . setBreakOnEnter ( value ) ; debugGui . getMenubar ( ) . getBreakOnEnter ( ) . setSelected ( value ) ; }
Sets whether execution should break when a function is entered .
31,721
public void setBreakOnReturn ( boolean value ) { dim . setBreakOnReturn ( value ) ; debugGui . getMenubar ( ) . getBreakOnReturn ( ) . setSelected ( value ) ; }
Sets whether execution should break when a function is left .
31,722
public Object getObject ( int key ) { if ( key < 0 ) Kit . codeBug ( ) ; if ( values != null ) { int index = findIndex ( key ) ; if ( 0 <= index ) { return values [ index ] ; } } return null ; }
Get object value assigned with key .
31,723
public void put ( int key , Object value ) { if ( key < 0 ) Kit . codeBug ( ) ; int index = ensureIndex ( key , false ) ; if ( values == null ) { values = new Object [ 1 << power ] ; } values [ index ] = value ; }
Set object value of the key . If key does not exist also set its int value to 0 .
31,724
public void put ( int key , int value ) { if ( key < 0 ) Kit . codeBug ( ) ; int index = ensureIndex ( key , true ) ; if ( ivaluesShift == 0 ) { int N = 1 << power ; if ( keys . length != N * 2 ) { int [ ] tmp = new int [ N * 2 ] ; System . arraycopy ( keys , 0 , tmp , 0 , N ) ; keys = tmp ; } ivaluesShift = N ; } keys [ ivaluesShift + index ] = value ; }
Set int value of the key . If key does not exist also set its object value to null .
31,725
public int [ ] getKeys ( ) { int [ ] keys = this . keys ; int n = keyCount ; int [ ] result = new int [ n ] ; for ( int i = 0 ; n != 0 ; ++ i ) { int entry = keys [ i ] ; if ( entry != EMPTY && entry != DELETED ) { result [ -- n ] = entry ; } } return result ; }
Return array of present keys
31,726
public static NativeSymbol construct ( Context cx , Scriptable scope , Object [ ] args ) { cx . putThreadLocal ( CONSTRUCTOR_SLOT , Boolean . TRUE ) ; try { return ( NativeSymbol ) cx . newObject ( scope , CLASS_NAME , args ) ; } finally { cx . removeThreadLocal ( CONSTRUCTOR_SLOT ) ; } }
Use this when we need to create symbols internally because of the convoluted way we have to construct them .
31,727
public void put ( String name , Scriptable start , Object value ) { if ( ! isSymbol ( ) ) { super . put ( name , start , value ) ; } else if ( Context . getCurrentContext ( ) . isStrictMode ( ) ) { throw ScriptRuntime . typeError0 ( "msg.no.assign.symbol.strict" ) ; } }
Symbol objects have a special property that one cannot add properties .
31,728
public static int exec ( String origArgs [ ] ) { errorReporter = new ToolErrorReporter ( false , global . getErr ( ) ) ; shellContextFactory . setErrorReporter ( errorReporter ) ; String [ ] args = processOptions ( origArgs ) ; if ( exitCode > 0 ) { return exitCode ; } if ( processStdin ) { fileList . add ( null ) ; } if ( ! global . initialized ) { global . init ( shellContextFactory ) ; } IProxy iproxy = new IProxy ( IProxy . PROCESS_FILES ) ; iproxy . args = args ; shellContextFactory . call ( iproxy ) ; return exitCode ; }
Execute the given arguments but don t System . exit at the end .
31,729
public void setComments ( SortedSet < Comment > comments ) { if ( comments == null ) { this . comments = null ; } else { if ( this . comments != null ) this . comments . clear ( ) ; for ( Comment c : comments ) addComment ( c ) ; } }
Sets comment list and updates the parent of each entry to point to this node . Replaces any existing comments .
31,730
public void addComment ( Comment comment ) { assertNotNull ( comment ) ; if ( comments == null ) { comments = new TreeSet < Comment > ( new AstNode . PositionComparator ( ) ) ; } comments . add ( comment ) ; comment . setParent ( this ) ; }
Add a comment to the comment set .
31,731
public void checkParentLinks ( ) { this . visit ( new NodeVisitor ( ) { public boolean visit ( AstNode node ) { int type = node . getType ( ) ; if ( type == Token . SCRIPT ) return true ; if ( node . getParent ( ) == null ) throw new IllegalStateException ( "No parent for node: " + node + "\n" + node . toSource ( 0 ) ) ; return true ; } } ) ; }
Debugging function to check that the parser has set the parent link for every node in the tree .
31,732
public void setArguments ( List < AstNode > arguments ) { if ( arguments == null ) { this . arguments = null ; } else { if ( this . arguments != null ) this . arguments . clear ( ) ; for ( AstNode arg : arguments ) { addArgument ( arg ) ; } } }
Sets function argument list
31,733
public void addArgument ( AstNode arg ) { assertNotNull ( arg ) ; if ( arguments == null ) { arguments = new ArrayList < AstNode > ( ) ; } arguments . add ( arg ) ; arg . setParent ( this ) ; }
Adds an argument to the list and sets its parent to this node .
31,734
public void addRegExp ( RegExpLiteral re ) { if ( re == null ) codeBug ( ) ; if ( regexps == null ) regexps = new ArrayList < RegExpLiteral > ( ) ; regexps . add ( re ) ; re . putIntProp ( REGEXP_PROP , regexps . size ( ) - 1 ) ; }
Called by IRFactory to add a RegExp to the regexp table .
31,735
public void flattenSymbolTable ( boolean flattenAllTables ) { if ( ! flattenAllTables ) { List < Symbol > newSymbols = new ArrayList < Symbol > ( ) ; if ( this . symbolTable != null ) { for ( int i = 0 ; i < symbols . size ( ) ; i ++ ) { Symbol symbol = symbols . get ( i ) ; if ( symbol . getContainingTable ( ) == this ) { newSymbols . add ( symbol ) ; } } } symbols = newSymbols ; } variableNames = new String [ symbols . size ( ) ] ; isConsts = new boolean [ symbols . size ( ) ] ; for ( int i = 0 ; i < symbols . size ( ) ; i ++ ) { Symbol symbol = symbols . get ( i ) ; variableNames [ i ] = symbol . getName ( ) ; isConsts [ i ] = symbol . getDeclType ( ) == Token . CONST ; symbol . setIndex ( i ) ; } }
Assign every symbol a unique integer index . Generate arrays of variable names and constness that can be indexed by those indices .
31,736
public void setLabels ( List < Label > labels ) { assertNotNull ( labels ) ; if ( this . labels != null ) this . labels . clear ( ) ; for ( Label l : labels ) { addLabel ( l ) ; } }
Sets label list setting the parent of each label in the list . Replaces any existing labels .
31,737
public void addLabel ( Label label ) { assertNotNull ( label ) ; labels . add ( label ) ; label . setParent ( this ) ; }
Adds a label and sets its parent to this node .
31,738
public void visit ( NodeVisitor v ) { if ( v . visit ( this ) ) { for ( AstNode label : labels ) { label . visit ( v ) ; } statement . visit ( v ) ; } }
Visits this node then each label in the label - list and finally the statement .
31,739
public void setFragments ( List < XmlFragment > fragments ) { assertNotNull ( fragments ) ; this . fragments . clear ( ) ; for ( XmlFragment fragment : fragments ) addFragment ( fragment ) ; }
Sets fragment list removing any existing fragments first . Sets the parent pointer for each fragment in the list to this node .
31,740
public void addFragment ( XmlFragment fragment ) { assertNotNull ( fragment ) ; fragments . add ( fragment ) ; fragment . setParent ( this ) ; }
Adds a fragment to the fragment list . Sets its parent to this node .
31,741
public void visit ( NodeVisitor v ) { if ( v . visit ( this ) ) { for ( XmlFragment frag : fragments ) { frag . visit ( v ) ; } } }
Visits this node then visits each child fragment in lexical order .
31,742
public int getAbsolutePosition ( ) { int pos = position ; AstNode parent = this . parent ; while ( parent != null ) { pos += parent . getPosition ( ) ; parent = parent . getParent ( ) ; } return pos ; }
Returns the absolute document position of the node . Computes it by adding the node s relative position to the relative positions of all its parents .
31,743
public void setParent ( AstNode parent ) { if ( parent == this . parent ) { return ; } if ( this . parent != null ) { setRelative ( - this . parent . getAbsolutePosition ( ) ) ; } this . parent = parent ; if ( parent != null ) { setRelative ( parent . getAbsolutePosition ( ) ) ; } }
Sets the node parent . This method automatically adjusts the current node s start position to be relative to the new parent .
31,744
public void addChild ( AstNode kid ) { assertNotNull ( kid ) ; int end = kid . getPosition ( ) + kid . getLength ( ) ; setLength ( end - this . getPosition ( ) ) ; addChildToBack ( kid ) ; kid . setParent ( this ) ; }
Adds a child or function to the end of the block . Sets the parent of the child to this node and fixes up the start position of the child to be relative to this node . Sets the length of this node to include the new child .
31,745
public AstRoot getAstRoot ( ) { AstNode parent = this ; while ( parent != null && ! ( parent instanceof AstRoot ) ) { parent = parent . getParent ( ) ; } return ( AstRoot ) parent ; }
Returns the root of the tree containing this node .
31,746
public String shortName ( ) { String classname = getClass ( ) . getName ( ) ; int last = classname . lastIndexOf ( "." ) ; return classname . substring ( last + 1 ) ; }
Returns a short descriptive name for the node such as ArrayComprehension .
31,747
public static String operatorToString ( int op ) { String result = operatorNames . get ( op ) ; if ( result == null ) throw new IllegalArgumentException ( "Invalid operator: " + op ) ; return result ; }
Returns the string name for this operator .
31,748
public String debugPrint ( ) { DebugPrintVisitor dpv = new DebugPrintVisitor ( new StringBuilder ( 1000 ) ) ; visit ( dpv ) ; return dpv . toString ( ) ; }
Returns a debugging representation of the parse tree starting at this node .
31,749
public void setName ( String name ) { name = name == null ? null : name . trim ( ) ; if ( name == null || "" . equals ( name ) ) throw new IllegalArgumentException ( "invalid label name" ) ; this . name = name ; }
Sets the label text
31,750
public void visit ( NodeVisitor v ) { if ( v . visit ( this ) ) { target . visit ( v ) ; for ( AstNode arg : getArguments ( ) ) { arg . visit ( v ) ; } if ( initializer != null ) { initializer . visit ( v ) ; } } }
Visits this node the target and each argument . If there is a trailing initializer node visits that last .
31,751
public void setTargetImplements ( Class < ? > [ ] implementsClasses ) { targetImplements = implementsClasses == null ? null : ( Class [ ] ) implementsClasses . clone ( ) ; }
Set the interfaces that the generated target will implement .
31,752
public void setTarget ( AstNode target ) { if ( target == null ) throw new IllegalArgumentException ( "invalid target arg" ) ; this . target = target ; target . setParent ( this ) ; }
Sets the variable name or destructuring form and sets its parent to this node .
31,753
public void visit ( NodeVisitor v ) { if ( v . visit ( this ) ) { target . visit ( v ) ; if ( initializer != null ) { initializer . visit ( v ) ; } } }
Visits this node then the target expression then the initializer expression if present .
31,754
static Method [ ] getMethodList ( Class < ? > clazz ) { Method [ ] methods = null ; try { if ( ! sawSecurityException ) methods = clazz . getDeclaredMethods ( ) ; } catch ( SecurityException e ) { sawSecurityException = true ; } if ( methods == null ) { methods = clazz . getMethods ( ) ; } int count = 0 ; for ( int i = 0 ; i < methods . length ; i ++ ) { if ( sawSecurityException ? methods [ i ] . getDeclaringClass ( ) != clazz : ! Modifier . isPublic ( methods [ i ] . getModifiers ( ) ) ) { methods [ i ] = null ; } else { count ++ ; } } Method [ ] result = new Method [ count ] ; int j = 0 ; for ( int i = 0 ; i < methods . length ; i ++ ) { if ( methods [ i ] != null ) result [ j ++ ] = methods [ i ] ; } return result ; }
Returns all public methods declared by the specified class . This excludes inherited methods .
31,755
public void setRowHeight ( int rowHeight ) { super . setRowHeight ( rowHeight ) ; if ( tree != null && tree . getRowHeight ( ) != rowHeight ) { tree . setRowHeight ( getRowHeight ( ) ) ; } }
Overridden to pass the new rowHeight to the tree .
31,756
public static Object coerceType ( Class < ? > type , Object value ) { return coerceTypeImpl ( type , value ) ; }
Not intended for public use . Callers should use the public API Context . toType .
31,757
public void visit ( NodeVisitor v ) { if ( v . visit ( this ) ) { if ( namespace != null ) { namespace . visit ( v ) ; } indexExpr . visit ( v ) ; } }
Visits this node then the namespace if provided then the index expression .
31,758
public void visit ( NodeVisitor v ) { if ( v . visit ( this ) ) { target . visit ( v ) ; element . visit ( v ) ; } }
Visits this node the target and the index expression .
31,759
protected Class < ? > getCurrentScriptClass ( ) { Class < ? > [ ] context = getClassContext ( ) ; for ( Class < ? > c : context ) { if ( c != InterpretedFunction . class && NativeFunction . class . isAssignableFrom ( c ) || PolicySecurityController . SecureCaller . class . isAssignableFrom ( c ) ) { return c ; } } return null ; }
Get the class of the top - most stack element representing a script .
31,760
public void setElements ( List < AstNode > elements ) { if ( elements == null ) { this . elements = null ; } else { if ( this . elements != null ) this . elements . clear ( ) ; for ( AstNode e : elements ) addElement ( e ) ; } }
Sets the element list and sets each element s parent to this node .
31,761
private static Object matchOrReplace ( Context cx , Scriptable scope , Scriptable thisObj , Object [ ] args , RegExpImpl reImpl , GlobData data , NativeRegExp re ) { String str = data . str ; data . global = ( re . getFlags ( ) & NativeRegExp . JSREG_GLOB ) != 0 ; int [ ] indexp = { 0 } ; Object result = null ; if ( data . mode == RA_SEARCH ) { result = re . executeRegExp ( cx , scope , reImpl , str , indexp , NativeRegExp . TEST ) ; if ( result != null && result . equals ( Boolean . TRUE ) ) result = Integer . valueOf ( reImpl . leftContext . length ) ; else result = Integer . valueOf ( - 1 ) ; } else if ( data . global ) { re . lastIndex = 0d ; for ( int count = 0 ; indexp [ 0 ] <= str . length ( ) ; count ++ ) { result = re . executeRegExp ( cx , scope , reImpl , str , indexp , NativeRegExp . TEST ) ; if ( result == null || ! result . equals ( Boolean . TRUE ) ) break ; if ( data . mode == RA_MATCH ) { match_glob ( data , cx , scope , count , reImpl ) ; } else { if ( data . mode != RA_REPLACE ) Kit . codeBug ( ) ; SubString lastMatch = reImpl . lastMatch ; int leftIndex = data . leftIndex ; int leftlen = lastMatch . index - leftIndex ; data . leftIndex = lastMatch . index + lastMatch . length ; replace_glob ( data , cx , scope , reImpl , leftIndex , leftlen ) ; } if ( reImpl . lastMatch . length == 0 ) { if ( indexp [ 0 ] == str . length ( ) ) break ; indexp [ 0 ] ++ ; } } } else { result = re . executeRegExp ( cx , scope , reImpl , str , indexp , ( ( data . mode == RA_REPLACE ) ? NativeRegExp . TEST : NativeRegExp . MATCH ) ) ; } return result ; }
Analog of C match_or_replace .
31,762
private static void do_replace ( GlobData rdata , Context cx , RegExpImpl regExpImpl ) { StringBuilder charBuf = rdata . charBuf ; int cp = 0 ; String da = rdata . repstr ; int dp = rdata . dollar ; if ( dp != - 1 ) { int [ ] skip = new int [ 1 ] ; do { int len = dp - cp ; charBuf . append ( da . substring ( cp , dp ) ) ; cp = dp ; SubString sub = interpretDollar ( cx , regExpImpl , da , dp , skip ) ; if ( sub != null ) { len = sub . length ; if ( len > 0 ) { charBuf . append ( sub . str , sub . index , sub . index + len ) ; } cp += skip [ 0 ] ; dp += skip [ 0 ] ; } else { ++ dp ; } dp = da . indexOf ( '$' , dp ) ; } while ( dp >= 0 ) ; } int daL = da . length ( ) ; if ( daL > cp ) { charBuf . append ( da . substring ( cp , daL ) ) ; } }
Analog of do_replace in jsstr . c
31,763
static final String getPayloadAsType ( int typeInfo , ConstantPool pool ) { if ( getTag ( typeInfo ) == OBJECT_TAG ) { return ( String ) pool . getConstantData ( getPayload ( typeInfo ) ) ; } throw new IllegalArgumentException ( "expecting object type" ) ; }
Treat the result of getPayload as a constant pool index and fetch the corresponding String mapped to it .
31,764
static final int fromType ( String type , ConstantPool pool ) { if ( type . length ( ) == 1 ) { switch ( type . charAt ( 0 ) ) { case 'B' : case 'C' : case 'S' : case 'Z' : case 'I' : return INTEGER ; case 'D' : return DOUBLE ; case 'F' : return FLOAT ; case 'J' : return LONG ; default : throw new IllegalArgumentException ( "bad type" ) ; } } return TypeInfo . OBJECT ( type , pool ) ; }
Create type information from an internal type .
31,765
static int merge ( int current , int incoming , ConstantPool pool ) { int currentTag = getTag ( current ) ; int incomingTag = getTag ( incoming ) ; boolean currentIsObject = currentTag == TypeInfo . OBJECT_TAG ; boolean incomingIsObject = incomingTag == TypeInfo . OBJECT_TAG ; if ( current == incoming || ( currentIsObject && incoming == NULL ) ) { return current ; } else if ( currentTag == TypeInfo . TOP || incomingTag == TypeInfo . TOP ) { return TypeInfo . TOP ; } else if ( current == NULL && incomingIsObject ) { return incoming ; } else if ( currentIsObject && incomingIsObject ) { String currentName = getPayloadAsType ( current , pool ) ; String incomingName = getPayloadAsType ( incoming , pool ) ; String currentlyGeneratedName = ( String ) pool . getConstantData ( 2 ) ; String currentlyGeneratedSuperName = ( String ) pool . getConstantData ( 4 ) ; if ( currentName . equals ( currentlyGeneratedName ) ) { currentName = currentlyGeneratedSuperName ; } if ( incomingName . equals ( currentlyGeneratedName ) ) { incomingName = currentlyGeneratedSuperName ; } Class < ? > currentClass = getClassFromInternalName ( currentName ) ; Class < ? > incomingClass = getClassFromInternalName ( incomingName ) ; if ( currentClass . isAssignableFrom ( incomingClass ) ) { return current ; } else if ( incomingClass . isAssignableFrom ( currentClass ) ) { return incoming ; } else if ( incomingClass . isInterface ( ) || currentClass . isInterface ( ) ) { return OBJECT ( "java/lang/Object" , pool ) ; } else { Class < ? > commonClass = incomingClass . getSuperclass ( ) ; while ( commonClass != null ) { if ( commonClass . isAssignableFrom ( currentClass ) ) { String name = commonClass . getName ( ) ; name = ClassFileWriter . getSlashedForm ( name ) ; return OBJECT ( name , pool ) ; } commonClass = commonClass . getSuperclass ( ) ; } } } throw new IllegalArgumentException ( "bad merge attempt between " + toString ( current , pool ) + " and " + toString ( incoming , pool ) ) ; }
Merge two verification types .
31,766
private static Class < ? > getClassFromInternalName ( String internalName ) { try { return Class . forName ( internalName . replace ( '/' , '.' ) ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } }
Take an internal name and return a java . lang . Class instance that represents it .
31,767
public final void initSourceName ( String sourceName ) { if ( sourceName == null ) throw new IllegalArgumentException ( ) ; if ( this . sourceName != null ) throw new IllegalStateException ( ) ; this . sourceName = sourceName ; }
Initialize the uri of the script source containing the error .
31,768
public final void initLineNumber ( int lineNumber ) { if ( lineNumber <= 0 ) throw new IllegalArgumentException ( String . valueOf ( lineNumber ) ) ; if ( this . lineNumber > 0 ) throw new IllegalStateException ( ) ; this . lineNumber = lineNumber ; }
Initialize the line number of the script statement causing the error .
31,769
public final void initColumnNumber ( int columnNumber ) { if ( columnNumber <= 0 ) throw new IllegalArgumentException ( String . valueOf ( columnNumber ) ) ; if ( this . columnNumber > 0 ) throw new IllegalStateException ( ) ; this . columnNumber = columnNumber ; }
Initialize the column number of the script statement causing the error .
31,770
public final void initLineSource ( String lineSource ) { if ( lineSource == null ) throw new IllegalArgumentException ( ) ; if ( this . lineSource != null ) throw new IllegalStateException ( ) ; this . lineSource = lineSource ; }
Initialize the text of the source line containing the error .
31,771
public String getScriptStackTrace ( int limit , String functionName ) { ScriptStackElement [ ] stack = getScriptStack ( limit , functionName ) ; return formatStackTrace ( stack , details ( ) ) ; }
Get a string representing the script stack of this exception . If optimization is enabled this includes java stack elements whose source and method names suggest they have been generated by the Rhino script compiler . The optional limit parameter limits the number of stack frames returned . The functionName parameter will exclude any stack frames below the specified function on the stack .
31,772
public void addStatement ( AstNode statement ) { assertNotNull ( statement ) ; if ( statements == null ) { statements = new ArrayList < AstNode > ( ) ; } int end = statement . getPosition ( ) + statement . getLength ( ) ; this . setLength ( end - this . getPosition ( ) ) ; statements . add ( statement ) ; statement . setParent ( this ) ; }
Adds a statement to the end of the statement list . Sets the parent of the new statement to this node updates its start offset to be relative to this node and sets the length of this node to include the new child .
31,773
public void setXml ( String s ) { assertNotNull ( s ) ; xml = s ; setLength ( s . length ( ) ) ; }
Sets the string for this XML component . Sets the length of the component to the length of the passed string .
31,774
public NativeArrayBuffer slice ( double s , double e ) { int end = ScriptRuntime . toInt32 ( Math . max ( 0 , Math . min ( buffer . length , ( e < 0 ? buffer . length + e : e ) ) ) ) ; int start = ScriptRuntime . toInt32 ( Math . min ( end , Math . max ( 0 , ( s < 0 ? buffer . length + s : s ) ) ) ) ; int len = end - start ; NativeArrayBuffer newBuf = new NativeArrayBuffer ( len ) ; System . arraycopy ( buffer , start , newBuf . buffer , 0 , len ) ; return newBuf ; }
Return a new buffer that represents a slice of this buffer s content starting at position start and ending at position end . Both values will be clamped as per the JavaScript spec so that invalid values may be passed and will be adjusted up or down accordingly . This method will return a new buffer that contains a copy of the original buffer . Changes there will not affect the content of the buffer .
31,775
public Object execIdCall ( IdFunctionObject f , Context cx , Scriptable scope , Scriptable thisObj , Object [ ] args ) { if ( ! f . hasTag ( CLASS_NAME ) ) { return super . execIdCall ( f , cx , scope , thisObj , args ) ; } int id = f . methodId ( ) ; switch ( id ) { case ConstructorId_isView : return ( isArg ( args , 0 ) && ( args [ 0 ] instanceof NativeArrayBufferView ) ) ; case Id_constructor : double length = isArg ( args , 0 ) ? ScriptRuntime . toNumber ( args [ 0 ] ) : 0 ; return new NativeArrayBuffer ( length ) ; case Id_slice : NativeArrayBuffer self = realThis ( thisObj , f ) ; double start = isArg ( args , 0 ) ? ScriptRuntime . toNumber ( args [ 0 ] ) : 0 ; double end = isArg ( args , 1 ) ? ScriptRuntime . toNumber ( args [ 1 ] ) : self . buffer . length ; return self . slice ( start , end ) ; } throw new IllegalArgumentException ( String . valueOf ( id ) ) ; }
Function - calling dispatcher
31,776
public static double version ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) { double result = cx . getLanguageVersion ( ) ; if ( args . length > 0 ) { double d = Context . toNumber ( args [ 0 ] ) ; cx . setLanguageVersion ( ( int ) d ) ; } return result ; }
Get and set the language version .
31,777
private void putIntoActivation ( int index , Object value ) { String argName = activation . function . getParamOrVarName ( index ) ; activation . put ( argName , activation , value ) ; }
the following helper methods assume that 0 < index < args . length
31,778
public static Scriptable jsConstructor ( Context cx , Object [ ] args , Function ctorObj , boolean inNewExpr ) { File result = new File ( ) ; if ( args . length == 0 || args [ 0 ] == Context . getUndefinedValue ( ) ) { result . name = "" ; result . file = null ; } else { result . name = Context . toString ( args [ 0 ] ) ; result . file = new java . io . File ( result . name ) ; } return result ; }
The Java method defining the JavaScript File constructor .
31,779
public Object readLines ( ) throws IOException { List < String > list = new ArrayList < String > ( ) ; String s ; while ( ( s = readLine ( ) ) != null ) { list . add ( s ) ; } String [ ] lines = list . toArray ( new String [ list . size ( ) ] ) ; Scriptable scope = ScriptableObject . getTopLevelScope ( this ) ; Context cx = Context . getCurrentContext ( ) ; return cx . newObject ( scope , "Array" , lines ) ; }
Read the remaining lines in the file and return them in an array .
31,780
public static void write ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) throws IOException { write0 ( thisObj , args , false ) ; }
Write strings .
31,781
public static void writeLine ( Context cx , Scriptable thisObj , Object [ ] args , Function funObj ) throws IOException { write0 ( thisObj , args , true ) ; }
Write strings and a newline .
31,782
public void close ( ) throws IOException { if ( reader != null ) { reader . close ( ) ; reader = null ; } else if ( writer != null ) { writer . close ( ) ; writer = null ; } }
Close the file . It may be reopened .
31,783
@ JSFunction ( "getReader" ) public Object getJSReader ( ) { if ( reader == null ) return null ; Scriptable parent = ScriptableObject . getTopLevelScope ( this ) ; return Context . javaToJS ( reader , parent ) ; }
Get the Java reader .
31,784
public Object getWriter ( ) { if ( writer == null ) return null ; Scriptable parent = ScriptableObject . getTopLevelScope ( this ) ; return Context . javaToJS ( writer , parent ) ; }
Get the Java writer .
31,785
private LineNumberReader getReader ( ) throws FileNotFoundException { if ( writer != null ) { throw Context . reportRuntimeError ( "already writing file \"" + name + "\"" ) ; } if ( reader == null ) reader = new LineNumberReader ( file == null ? new InputStreamReader ( System . in ) : new FileReader ( file ) ) ; return reader ; }
Get the reader checking that we re not already writing this file .
31,786
private static void write0 ( Scriptable thisObj , Object [ ] args , boolean eol ) throws IOException { File thisFile = checkInstance ( thisObj ) ; if ( thisFile . reader != null ) { throw Context . reportRuntimeError ( "already writing file \"" + thisFile . name + "\"" ) ; } if ( thisFile . writer == null ) thisFile . writer = new BufferedWriter ( thisFile . file == null ? new OutputStreamWriter ( System . out ) : new FileWriter ( thisFile . file ) ) ; for ( int i = 0 ; i < args . length ; i ++ ) { String s = Context . toString ( args [ i ] ) ; thisFile . writer . write ( s , 0 , s . length ( ) ) ; } if ( eol ) thisFile . writer . newLine ( ) ; }
Perform the guts of write and writeLine .
31,787
private static File checkInstance ( Scriptable obj ) { if ( obj == null || ! ( obj instanceof File ) ) { throw Context . reportRuntimeError ( "called on incompatible object" ) ; } return ( File ) obj ; }
Perform the instanceof check and return the downcasted File object .
31,788
public void addOptionalExcludedName ( String name ) { Object obj = lookupQualifiedName ( scope , name ) ; if ( obj != null && obj != UniqueTag . NOT_FOUND ) { if ( ! ( obj instanceof Scriptable ) ) { throw new IllegalArgumentException ( "Object for excluded name " + name + " is not a Scriptable, it is " + obj . getClass ( ) . getName ( ) ) ; } table . put ( obj , name ) ; } }
Adds a qualified name to the list of object to be excluded from serialization . Names excluded from serialization are looked up in the new scope and replaced upon deserialization .
31,789
public void addExcludedName ( String name ) { Object obj = lookupQualifiedName ( scope , name ) ; if ( ! ( obj instanceof Scriptable ) ) { throw new IllegalArgumentException ( "Object for excluded name " + name + " not found." ) ; } table . put ( obj , name ) ; }
Adds a qualified name to the list of objects to be excluded from serialization . Names excluded from serialization are looked up in the new scope and replaced upon deserialization .
31,790
public void excludeStandardObjectNames ( ) { String [ ] names = { "Object" , "Object.prototype" , "Function" , "Function.prototype" , "String" , "String.prototype" , "Math" , "Array" , "Array.prototype" , "Error" , "Error.prototype" , "Number" , "Number.prototype" , "Date" , "Date.prototype" , "RegExp" , "RegExp.prototype" , "Script" , "Script.prototype" , "Continuation" , "Continuation.prototype" , } ; for ( int i = 0 ; i < names . length ; i ++ ) { addExcludedName ( names [ i ] ) ; } String [ ] optionalNames = { "XML" , "XML.prototype" , "XMLList" , "XMLList.prototype" , } ; for ( int i = 0 ; i < optionalNames . length ; i ++ ) { addOptionalExcludedName ( optionalNames [ i ] ) ; } }
Adds the names of the standard objects and their prototypes to the list of excluded names .
31,791
static void loadFromIterable ( Context cx , Scriptable scope , ScriptableObject map , Object arg1 ) { if ( ( arg1 == null ) || Undefined . instance . equals ( arg1 ) ) { return ; } final Object ito = ScriptRuntime . callIterator ( arg1 , cx , scope ) ; if ( Undefined . instance . equals ( ito ) ) { return ; } ScriptableObject dummy = ensureScriptableObject ( cx . newObject ( scope , map . getClassName ( ) ) ) ; final Callable set = ScriptRuntime . getPropFunctionAndThis ( dummy . getPrototype ( ) , "set" , cx , scope ) ; ScriptRuntime . lastStoredScriptable ( cx ) ; try ( IteratorLikeIterable it = new IteratorLikeIterable ( cx , scope , ito ) ) { for ( Object val : it ) { Scriptable sVal = ScriptableObject . ensureScriptable ( val ) ; if ( sVal instanceof Symbol ) { throw ScriptRuntime . typeError1 ( "msg.arg.not.object" , ScriptRuntime . typeof ( sVal ) ) ; } Object finalKey = sVal . get ( 0 , sVal ) ; if ( finalKey == NOT_FOUND ) { finalKey = Undefined . instance ; } Object finalVal = sVal . get ( 1 , sVal ) ; if ( finalVal == NOT_FOUND ) { finalVal = Undefined . instance ; } set . call ( cx , scope , map , new Object [ ] { finalKey , finalVal } ) ; } } }
If an iterable object was passed to the constructor there are many many things to do ... Make this static because NativeWeakMap has the exact same requirement .
31,792
private static double js_pow ( double x , double y ) { double result ; if ( y != y ) { result = y ; } else if ( y == 0 ) { result = 1.0 ; } else if ( x == 0 ) { if ( 1 / x > 0 ) { result = ( y > 0 ) ? 0 : Double . POSITIVE_INFINITY ; } else { long y_long = ( long ) y ; if ( y_long == y && ( y_long & 0x1 ) != 0 ) { result = ( y > 0 ) ? - 0.0 : Double . NEGATIVE_INFINITY ; } else { result = ( y > 0 ) ? 0.0 : Double . POSITIVE_INFINITY ; } } } else { result = Math . pow ( x , y ) ; if ( result != result ) { if ( y == Double . POSITIVE_INFINITY ) { if ( x < - 1.0 || 1.0 < x ) { result = Double . POSITIVE_INFINITY ; } else if ( - 1.0 < x && x < 1.0 ) { result = 0 ; } } else if ( y == Double . NEGATIVE_INFINITY ) { if ( x < - 1.0 || 1.0 < x ) { result = 0 ; } else if ( - 1.0 < x && x < 1.0 ) { result = Double . POSITIVE_INFINITY ; } } else if ( x == Double . POSITIVE_INFINITY ) { result = ( y > 0 ) ? Double . POSITIVE_INFINITY : 0.0 ; } else if ( x == Double . NEGATIVE_INFINITY ) { long y_long = ( long ) y ; if ( y_long == y && ( y_long & 0x1 ) != 0 ) { result = ( y > 0 ) ? Double . NEGATIVE_INFINITY : - 0.0 ; } else { result = ( y > 0 ) ? Double . POSITIVE_INFINITY : 0.0 ; } } } } return result ; }
See Ecma 15 . 8 . 2 . 13
31,793
private static int js_imul ( Object [ ] args ) { if ( args == null ) { return 0 ; } int x = ScriptRuntime . toInt32 ( args , 0 ) ; int y = ScriptRuntime . toInt32 ( args , 1 ) ; return x * y ; }
From EcmaScript 6 section 20 . 2 . 2 . 19
31,794
private static void badUsage ( String s ) { System . err . println ( ToolErrorReporter . getMessage ( "msg.jsc.bad.usage" , Main . class . getName ( ) , s ) ) ; }
Print a usage message .
31,795
public void processSource ( String [ ] filenames ) { for ( int i = 0 ; i != filenames . length ; ++ i ) { String filename = filenames [ i ] ; if ( ! filename . endsWith ( ".js" ) ) { addError ( "msg.extension.not.js" , filename ) ; return ; } File f = new File ( filename ) ; String source = readSource ( f ) ; if ( source == null ) return ; String mainClassName = targetName ; if ( mainClassName == null ) { String name = f . getName ( ) ; String nojs = name . substring ( 0 , name . length ( ) - 3 ) ; mainClassName = getClassName ( nojs ) ; } if ( targetPackage . length ( ) != 0 ) { mainClassName = targetPackage + "." + mainClassName ; } Object [ ] compiled = compiler . compileToClassFiles ( source , filename , 1 , mainClassName ) ; if ( compiled == null || compiled . length == 0 ) { return ; } File targetTopDir = null ; if ( destinationDir != null ) { targetTopDir = new File ( destinationDir ) ; } else { String parent = f . getParent ( ) ; if ( parent != null ) { targetTopDir = new File ( parent ) ; } } for ( int j = 0 ; j != compiled . length ; j += 2 ) { String className = ( String ) compiled [ j ] ; byte [ ] bytes = ( byte [ ] ) compiled [ j + 1 ] ; File outfile = getOutputFile ( targetTopDir , className ) ; try { FileOutputStream os = new FileOutputStream ( outfile ) ; try { os . write ( bytes ) ; } finally { os . close ( ) ; } } catch ( IOException ioe ) { addFormatedError ( ioe . toString ( ) ) ; } } } }
Compile JavaScript source .
31,796
String getClassName ( String name ) { char [ ] s = new char [ name . length ( ) + 1 ] ; char c ; int j = 0 ; if ( ! Character . isJavaIdentifierStart ( name . charAt ( 0 ) ) ) { s [ j ++ ] = '_' ; } for ( int i = 0 ; i < name . length ( ) ; i ++ , j ++ ) { c = name . charAt ( i ) ; if ( Character . isJavaIdentifierPart ( c ) ) { s [ j ] = c ; } else { s [ j ] = '_' ; } } return ( new String ( s ) ) . trim ( ) ; }
Verify that class file names are legal Java identifiers . Substitute illegal characters with underscores and prepend the name with an underscore if the file name does not begin with a JavaLetter .
31,797
public Object resumeGenerator ( Context cx , Scriptable scope , int operation , Object state , Object value ) { throw new EvaluatorException ( "resumeGenerator() not implemented" ) ; }
Resume execution of a suspended generator .
31,798
public void visit ( NodeVisitor v ) { if ( v . visit ( this ) ) { testExpression . visit ( v ) ; trueExpression . visit ( v ) ; falseExpression . visit ( v ) ; } }
Visits this node then the test - expression the true - expression and the false - expression .
31,799
public void addInterface ( String interfaceName ) { short interfaceIndex = itsConstantPool . addClass ( interfaceName ) ; itsInterfaces . add ( Short . valueOf ( interfaceIndex ) ) ; }
Add an interface implemented by this class .