idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
31,900 | public void addElement ( ObjectProperty element ) { assertNotNull ( element ) ; if ( elements == null ) { elements = new ArrayList < ObjectProperty > ( ) ; } elements . add ( element ) ; element . setParent ( this ) ; } | Adds an element to the list and sets its parent to this node . |
31,901 | public static Object getStopIterationObject ( Scriptable scope ) { Scriptable top = ScriptableObject . getTopLevelScope ( scope ) ; return ScriptableObject . getTopScopeValue ( top , ITERATOR_TAG ) ; } | Get the value of the StopIteration object . Note that this value is stored in the top - level scope using associateValue so the value can still be found even if a script overwrites or deletes the global StopIteration property . |
31,902 | public void visit ( NodeVisitor v ) { if ( v . visit ( this ) ) { if ( namespace != null ) { namespace . visit ( v ) ; } propName . visit ( v ) ; } } | Visits this node then the namespace if present then the property name . |
31,903 | protected void checkMapSize ( ) { if ( ( map instanceof EmbeddedSlotMap ) && map . size ( ) >= LARGE_HASH_SIZE ) { SlotMap newMap = new HashSlotMap ( ) ; for ( Slot s : map ) { newMap . addSlot ( s ) ; } map = newMap ; } } | Before inserting a new item in the map check and see if we need to expand from the embedded map to a HashMap that is more robust against large numbers of hash collisions . |
31,904 | public boolean containsKey ( Object key ) { if ( key instanceof String ) { return has ( ( String ) key , this ) ; } else if ( key instanceof Number ) { return has ( ( ( Number ) key ) . intValue ( ) , this ) ; } return false ; } | methods implementing java . util . Map |
31,905 | public void setVisible ( boolean b ) { super . setVisible ( b ) ; if ( b ) { console . consoleTextArea . requestFocus ( ) ; context . split . setDividerLocation ( 0.5 ) ; try { console . setMaximum ( true ) ; console . setSelected ( true ) ; console . show ( ) ; console . consoleTextArea . requestFocus ( ) ; } catch ( Exception exc ) { } } } | Sets the visibility of the debugger GUI . |
31,906 | void addTopLevel ( String key , JFrame frame ) { if ( frame != this ) { toplevels . put ( key , frame ) ; } } | Records a new internal frame . |
31,907 | static String getShortName ( String url ) { int lastSlash = url . lastIndexOf ( '/' ) ; if ( lastSlash < 0 ) { lastSlash = url . lastIndexOf ( '\\' ) ; } String shortName = url ; if ( lastSlash >= 0 && lastSlash + 1 < url . length ( ) ) { shortName = url . substring ( lastSlash + 1 ) ; } return shortName ; } | Returns a short version of the given URL . |
31,908 | void showStopLine ( Dim . StackFrame frame ) { String sourceName = frame . getUrl ( ) ; if ( sourceName == null || sourceName . equals ( "<stdin>" ) ) { if ( console . isVisible ( ) ) { console . show ( ) ; } } else { showFileWindow ( sourceName , - 1 ) ; int lineNumber = frame . getLineNumber ( ) ; FileWindow w = getFileWindow ( sourceName ) ; if ( w != null ) { setFilePosition ( w , lineNumber ) ; } } } | Shows the line at which execution in the given stack frame just stopped . |
31,909 | void enterInterruptImpl ( Dim . StackFrame lastFrame , String threadTitle , String alertMessage ) { statusBar . setText ( "Thread: " + threadTitle ) ; showStopLine ( lastFrame ) ; if ( alertMessage != null ) { MessageDialogWrapper . showMessageDialog ( this , alertMessage , "Exception in Script" , JOptionPane . ERROR_MESSAGE ) ; } updateEnabled ( true ) ; Dim . ContextData contextData = lastFrame . contextData ( ) ; JComboBox < String > ctx = context . context ; List < String > toolTips = context . toolTips ; context . disableUpdate ( ) ; int frameCount = contextData . frameCount ( ) ; ctx . removeAllItems ( ) ; ctx . setSelectedItem ( null ) ; toolTips . clear ( ) ; for ( int i = 0 ; i < frameCount ; i ++ ) { Dim . StackFrame frame = contextData . getFrame ( i ) ; String url = frame . getUrl ( ) ; int lineNumber = frame . getLineNumber ( ) ; String shortName = url ; if ( url . length ( ) > 20 ) { shortName = "..." + url . substring ( url . length ( ) - 17 ) ; } String location = "\"" + shortName + "\", line " + lineNumber ; ctx . insertItemAt ( location , i ) ; location = "\"" + url + "\", line " + lineNumber ; toolTips . add ( location ) ; } context . enableUpdate ( ) ; ctx . setSelectedIndex ( 0 ) ; ctx . setMinimumSize ( new Dimension ( 50 , ctx . getMinimumSize ( ) . height ) ) ; } | Handles script interruption . |
31,910 | private JInternalFrame getSelectedFrame ( ) { JInternalFrame [ ] frames = desk . getAllFrames ( ) ; for ( int i = 0 ; i < frames . length ; i ++ ) { if ( frames [ i ] . isShowing ( ) ) { return frames [ i ] ; } } return frames [ frames . length - 1 ] ; } | Returns the current selected internal frame . |
31,911 | private void updateEnabled ( boolean interrupted ) { ( ( Menubar ) getJMenuBar ( ) ) . updateEnabled ( interrupted ) ; for ( int ci = 0 , cc = toolBar . getComponentCount ( ) ; ci < cc ; ci ++ ) { boolean enableButton ; if ( ci == 0 ) { enableButton = ! interrupted ; } else { enableButton = interrupted ; } toolBar . getComponent ( ci ) . setEnabled ( enableButton ) ; } if ( interrupted ) { toolBar . setEnabled ( true ) ; int state = getExtendedState ( ) ; if ( state == Frame . ICONIFIED ) { setExtendedState ( Frame . NORMAL ) ; } toFront ( ) ; context . setEnabled ( true ) ; } else { if ( currentWindow != null ) currentWindow . setPosition ( - 1 ) ; context . setEnabled ( false ) ; } } | Enables or disables the menu and tool bars with respect to the state of script execution . |
31,912 | private String readFile ( String fileName ) { String text ; try { try ( Reader r = new FileReader ( fileName ) ) { text = Kit . readReader ( r ) ; } } catch ( IOException ex ) { MessageDialogWrapper . showMessageDialog ( this , ex . getMessage ( ) , "Error reading " + fileName , JOptionPane . ERROR_MESSAGE ) ; text = null ; } return text ; } | Reads the file with the given name and returns its contents as a String . |
31,913 | public void updateSourceText ( Dim . SourceInfo sourceInfo ) { RunProxy proxy = new RunProxy ( this , RunProxy . UPDATE_SOURCE_TEXT ) ; proxy . sourceInfo = sourceInfo ; SwingUtilities . invokeLater ( proxy ) ; } | Called when the source text for a script has been updated . |
31,914 | public void enterInterrupt ( Dim . StackFrame lastFrame , String threadTitle , String alertMessage ) { if ( SwingUtilities . isEventDispatchThread ( ) ) { enterInterruptImpl ( lastFrame , threadTitle , alertMessage ) ; } else { RunProxy proxy = new RunProxy ( this , RunProxy . ENTER_INTERRUPT ) ; proxy . lastFrame = lastFrame ; proxy . threadTitle = threadTitle ; proxy . alertMessage = alertMessage ; SwingUtilities . invokeLater ( proxy ) ; } } | Called when the interrupt loop has been entered . |
31,915 | public void dispatchNextGuiEvent ( ) throws InterruptedException { EventQueue queue = awtEventQueue ; if ( queue == null ) { queue = Toolkit . getDefaultToolkit ( ) . getSystemEventQueue ( ) ; awtEventQueue = queue ; } AWTEvent event = queue . getNextEvent ( ) ; if ( event instanceof ActiveEvent ) { ( ( ActiveEvent ) event ) . dispatch ( ) ; } else { Object source = event . getSource ( ) ; if ( source instanceof Component ) { Component comp = ( Component ) source ; comp . dispatchEvent ( event ) ; } else if ( source instanceof MenuComponent ) { ( ( MenuComponent ) source ) . dispatchEvent ( event ) ; } } } | Processes the next GUI event . |
31,916 | private synchronized void returnPressed ( ) { Document doc = getDocument ( ) ; int len = doc . getLength ( ) ; Segment segment = new Segment ( ) ; try { doc . getText ( outputMark , len - outputMark , segment ) ; } catch ( javax . swing . text . BadLocationException ignored ) { ignored . printStackTrace ( ) ; } String text = segment . toString ( ) ; if ( debugGui . dim . stringIsCompilableUnit ( text ) ) { if ( text . trim ( ) . length ( ) > 0 ) { history . add ( text ) ; historyIndex = history . size ( ) ; } append ( "\n" ) ; String result = debugGui . dim . eval ( text ) ; if ( result . length ( ) > 0 ) { append ( result ) ; append ( "\n" ) ; } append ( "% " ) ; outputMark = doc . getLength ( ) ; } else { append ( "\n" ) ; } } | Called when Enter is pressed . |
31,917 | public synchronized void insertUpdate ( DocumentEvent e ) { int len = e . getLength ( ) ; int off = e . getOffset ( ) ; if ( outputMark > off ) { outputMark += len ; } } | Called when text was inserted into the text area . |
31,918 | public synchronized void removeUpdate ( DocumentEvent e ) { int len = e . getLength ( ) ; int off = e . getOffset ( ) ; if ( outputMark > off ) { if ( outputMark >= off + len ) { outputMark -= len ; } else { outputMark = off ; } } } | Called when text was removed from the text area . |
31,919 | public void actionPerformed ( ActionEvent e ) { String cmd = e . getActionCommand ( ) ; if ( cmd . equals ( "Cut" ) ) { consoleTextArea . cut ( ) ; } else if ( cmd . equals ( "Copy" ) ) { consoleTextArea . copy ( ) ; } else if ( cmd . equals ( "Paste" ) ) { consoleTextArea . paste ( ) ; } } | Performs an action on the text area . |
31,920 | public void show ( JComponent comp , int x , int y ) { this . x = x ; this . y = y ; super . show ( comp , x , y ) ; } | Displays the menu at the given coordinates . |
31,921 | public void select ( int pos ) { if ( pos >= 0 ) { try { int line = getLineOfOffset ( pos ) ; Rectangle rect = modelToView ( pos ) ; if ( rect == null ) { select ( pos , pos ) ; } else { try { Rectangle nrect = modelToView ( getLineStartOffset ( line + 1 ) ) ; if ( nrect != null ) { rect = nrect ; } } catch ( Exception exc ) { } JViewport vp = ( JViewport ) getParent ( ) ; Rectangle viewRect = vp . getViewRect ( ) ; if ( viewRect . y + viewRect . height > rect . y ) { select ( pos , pos ) ; } else { rect . y += ( viewRect . height - rect . height ) / 2 ; scrollRectToVisible ( rect ) ; select ( pos , pos ) ; } } } catch ( BadLocationException exc ) { select ( pos , pos ) ; } } } | Moves the selection to the given offset . |
31,922 | private void checkPopup ( MouseEvent e ) { if ( e . isPopupTrigger ( ) ) { popup . show ( this , e . getX ( ) , e . getY ( ) ) ; } } | Checks if the popup menu should be shown . |
31,923 | public void mouseClicked ( MouseEvent e ) { checkPopup ( e ) ; requestFocus ( ) ; getCaret ( ) . setVisible ( true ) ; } | Called when the mouse is clicked . |
31,924 | public void keyPressed ( KeyEvent e ) { switch ( e . getKeyCode ( ) ) { case KeyEvent . VK_BACK_SPACE : case KeyEvent . VK_ENTER : case KeyEvent . VK_DELETE : case KeyEvent . VK_TAB : e . consume ( ) ; break ; } } | Called when a key is pressed . |
31,925 | public String showDialog ( Component comp ) { value = null ; setLocationRelativeTo ( comp ) ; setVisible ( true ) ; return value ; } | Shows the dialog . |
31,926 | public void update ( ) { FileTextArea textArea = fileWindow . textArea ; Font font = textArea . getFont ( ) ; setFont ( font ) ; FontMetrics metrics = getFontMetrics ( font ) ; int h = metrics . getHeight ( ) ; int lineCount = textArea . getLineCount ( ) + 1 ; String dummy = Integer . toString ( lineCount ) ; if ( dummy . length ( ) < 2 ) { dummy = "99" ; } Dimension d = new Dimension ( ) ; d . width = metrics . stringWidth ( dummy ) + 16 ; d . height = lineCount * h + 100 ; setPreferredSize ( d ) ; setSize ( d ) ; } | Updates the gutter . |
31,927 | public void mousePressed ( MouseEvent e ) { Font font = fileWindow . textArea . getFont ( ) ; FontMetrics metrics = getFontMetrics ( font ) ; int h = metrics . getHeight ( ) ; pressLine = e . getY ( ) / h ; } | Called when a mouse button is pressed . |
31,928 | void load ( ) { String url = getUrl ( ) ; if ( url != null ) { RunProxy proxy = new RunProxy ( debugGui , RunProxy . LOAD_FILE ) ; proxy . fileName = url ; proxy . text = sourceInfo . source ( ) ; new Thread ( proxy ) . start ( ) ; } } | Loads the file . |
31,929 | public int getPosition ( int line ) { int result = - 1 ; try { result = textArea . getLineStartOffset ( line ) ; } catch ( javax . swing . text . BadLocationException exc ) { } return result ; } | Returns the offset position for the given line . |
31,930 | public void setBreakPoint ( int line ) { if ( sourceInfo . breakableLine ( line ) ) { boolean changed = sourceInfo . breakpoint ( line , true ) ; if ( changed ) { fileHeader . repaint ( ) ; } } } | Sets a breakpoint on the given line . |
31,931 | public void clearBreakPoint ( int line ) { if ( sourceInfo . breakableLine ( line ) ) { boolean changed = sourceInfo . breakpoint ( line , false ) ; if ( changed ) { fileHeader . repaint ( ) ; } } } | Clears a breakpoint from the given line . |
31,932 | private void updateToolTip ( ) { int n = getComponentCount ( ) - 1 ; if ( n > 1 ) { n = 1 ; } else if ( n < 0 ) { return ; } Component c = getComponent ( n ) ; if ( c != null && c instanceof JComponent ) { ( ( JComponent ) c ) . setToolTipText ( getUrl ( ) ) ; } } | Updates the tool tip contents . |
31,933 | public void updateText ( Dim . SourceInfo sourceInfo ) { this . sourceInfo = sourceInfo ; String newText = sourceInfo . source ( ) ; if ( ! textArea . getText ( ) . equals ( newText ) ) { textArea . setText ( newText ) ; int pos = 0 ; if ( currentPos != - 1 ) { pos = currentPos ; } textArea . select ( pos ) ; } fileHeader . update ( ) ; fileHeader . repaint ( ) ; } | Called when the text of the script has changed . |
31,934 | public void select ( int start , int end ) { int docEnd = textArea . getDocument ( ) . getLength ( ) ; textArea . select ( docEnd , docEnd ) ; textArea . select ( start , end ) ; } | Selects a range of characters . |
31,935 | public Object getValueAt ( int row , int column ) { switch ( column ) { case 0 : return expressions . get ( row ) ; case 1 : return values . get ( row ) ; } return "" ; } | Returns the value in the given cell . |
31,936 | public void setValueAt ( Object value , int row , int column ) { switch ( column ) { case 0 : String expr = value . toString ( ) ; expressions . set ( row , expr ) ; String result = "" ; if ( expr . length ( ) > 0 ) { result = debugGui . dim . eval ( expr ) ; if ( result == null ) result = "" ; } values . set ( row , result ) ; updateModel ( ) ; if ( row + 1 == expressions . size ( ) ) { expressions . add ( "" ) ; values . add ( "" ) ; fireTableRowsInserted ( row + 1 , row + 1 ) ; } break ; case 1 : fireTableDataChanged ( ) ; } } | Sets the value in the given cell . |
31,937 | void updateModel ( ) { for ( int i = 0 ; i < expressions . size ( ) ; ++ i ) { String expr = expressions . get ( i ) ; String result = "" ; if ( expr . length ( ) > 0 ) { result = debugGui . dim . eval ( expr ) ; if ( result == null ) result = "" ; } else { result = "" ; } result = result . replace ( '\n' , ' ' ) ; values . set ( i , result ) ; } fireTableDataChanged ( ) ; } | Re - evaluates the expressions in the table . |
31,938 | public int getChildCount ( Object nodeObj ) { if ( debugger == null ) { return 0 ; } VariableNode node = ( VariableNode ) nodeObj ; return children ( node ) . length ; } | Returns the number of children of the given node . |
31,939 | public Object getChild ( Object nodeObj , int i ) { if ( debugger == null ) { return null ; } VariableNode node = ( VariableNode ) nodeObj ; return children ( node ) [ i ] ; } | Returns a child of the given node . |
31,940 | public boolean isLeaf ( Object nodeObj ) { if ( debugger == null ) { return true ; } VariableNode node = ( VariableNode ) nodeObj ; return children ( node ) . length == 0 ; } | Returns whether the given node is a leaf node . |
31,941 | public int getIndexOfChild ( Object parentObj , Object childObj ) { if ( debugger == null ) { return - 1 ; } VariableNode parent = ( VariableNode ) parentObj ; VariableNode child = ( VariableNode ) childObj ; VariableNode [ ] children = children ( parent ) ; for ( int i = 0 ; i != children . length ; i ++ ) { if ( children [ i ] == child ) { return i ; } } return - 1 ; } | Returns the index of a node under its parent . |
31,942 | public Object getValueAt ( Object nodeObj , int column ) { if ( debugger == null ) { return null ; } VariableNode node = ( VariableNode ) nodeObj ; switch ( column ) { case 0 : return node . toString ( ) ; case 1 : String result ; try { result = debugger . objectToString ( getValue ( node ) ) ; } catch ( RuntimeException exc ) { result = exc . getMessage ( ) ; } StringBuilder buf = new StringBuilder ( ) ; int len = result . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char ch = result . charAt ( i ) ; if ( Character . isISOControl ( ch ) ) { ch = ' ' ; } buf . append ( ch ) ; } return buf . toString ( ) ; } return null ; } | Returns the value at the given cell . |
31,943 | private VariableNode [ ] children ( VariableNode node ) { if ( node . children != null ) { return node . children ; } VariableNode [ ] children ; Object value = getValue ( node ) ; Object [ ] ids = debugger . getObjectIds ( value ) ; if ( ids == null || ids . length == 0 ) { children = CHILDLESS ; } else { Arrays . sort ( ids , new Comparator < Object > ( ) { public int compare ( Object l , Object r ) { if ( l instanceof String ) { if ( r instanceof Integer ) { return - 1 ; } return ( ( String ) l ) . compareToIgnoreCase ( ( String ) r ) ; } if ( r instanceof String ) { return 1 ; } int lint = ( ( Integer ) l ) . intValue ( ) ; int rint = ( ( Integer ) r ) . intValue ( ) ; return lint - rint ; } } ) ; children = new VariableNode [ ids . length ] ; for ( int i = 0 ; i != ids . length ; ++ i ) { children [ i ] = new VariableNode ( value , ids [ i ] ) ; } } node . children = children ; return children ; } | Returns an array of the children of the given node . |
31,944 | public Object getValue ( VariableNode node ) { try { return debugger . getObjectProperty ( node . object , node . id ) ; } catch ( Exception exc ) { return "undefined" ; } } | Returns the value of the given node . |
31,945 | public JTree resetTree ( TreeTableModel treeTableModel ) { tree = new TreeTableCellRenderer ( treeTableModel ) ; super . setModel ( new TreeTableModelAdapter ( treeTableModel , tree ) ) ; ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper ( ) ; tree . setSelectionModel ( selectionWrapper ) ; setSelectionModel ( selectionWrapper . getListSelectionModel ( ) ) ; if ( tree . getRowHeight ( ) < 1 ) { setRowHeight ( 18 ) ; } setDefaultRenderer ( TreeTableModel . class , tree ) ; setDefaultEditor ( TreeTableModel . class , new TreeTableCellEditor ( ) ) ; setShowGrid ( true ) ; setIntercellSpacing ( new Dimension ( 1 , 1 ) ) ; tree . setRootVisible ( false ) ; tree . setShowsRootHandles ( true ) ; DefaultTreeCellRenderer r = ( DefaultTreeCellRenderer ) tree . getCellRenderer ( ) ; r . setOpenIcon ( null ) ; r . setClosedIcon ( null ) ; r . setLeafIcon ( null ) ; return tree ; } | Initializes a tree for this tree table . |
31,946 | public void setEnabled ( boolean enabled ) { context . setEnabled ( enabled ) ; thisTable . setEnabled ( enabled ) ; localsTable . setEnabled ( enabled ) ; evaluator . setEnabled ( enabled ) ; cmdLine . setEnabled ( enabled ) ; } | Enables or disables the component . |
31,947 | public void addFile ( String url ) { int count = windowMenu . getItemCount ( ) ; JMenuItem item ; if ( count == 4 ) { windowMenu . addSeparator ( ) ; count ++ ; } JMenuItem lastItem = windowMenu . getItem ( count - 1 ) ; boolean hasMoreWin = false ; int maxWin = 5 ; if ( lastItem != null && lastItem . getText ( ) . equals ( "More Windows..." ) ) { hasMoreWin = true ; maxWin ++ ; } if ( ! hasMoreWin && count - 4 == 5 ) { windowMenu . add ( item = new JMenuItem ( "More Windows..." , 'M' ) ) ; item . setActionCommand ( "More Windows..." ) ; item . addActionListener ( this ) ; return ; } else if ( count - 4 <= maxWin ) { if ( hasMoreWin ) { count -- ; windowMenu . remove ( lastItem ) ; } String shortName = SwingGui . getShortName ( url ) ; windowMenu . add ( item = new JMenuItem ( ( char ) ( '0' + ( count - 4 ) ) + " " + shortName , '0' + ( count - 4 ) ) ) ; if ( hasMoreWin ) { windowMenu . add ( lastItem ) ; } } else { return ; } item . setActionCommand ( url ) ; item . addActionListener ( this ) ; } | Adds a file to the window menu . |
31,948 | public void updateEnabled ( boolean interrupted ) { for ( int i = 0 ; i != interruptOnlyItems . size ( ) ; ++ i ) { JMenuItem item = interruptOnlyItems . get ( i ) ; item . setEnabled ( interrupted ) ; } for ( int i = 0 ; i != runOnlyItems . size ( ) ; ++ i ) { JMenuItem item = runOnlyItems . get ( i ) ; item . setEnabled ( ! interrupted ) ; } } | Updates the enabledness of menu items . |
31,949 | public void run ( ) { switch ( type ) { case OPEN_FILE : try { debugGui . dim . compileScript ( fileName , text ) ; } catch ( RuntimeException ex ) { MessageDialogWrapper . showMessageDialog ( debugGui , ex . getMessage ( ) , "Error Compiling " + fileName , JOptionPane . ERROR_MESSAGE ) ; } break ; case LOAD_FILE : try { debugGui . dim . evalScript ( fileName , text ) ; } catch ( RuntimeException ex ) { MessageDialogWrapper . showMessageDialog ( debugGui , ex . getMessage ( ) , "Run error for " + fileName , JOptionPane . ERROR_MESSAGE ) ; } break ; case UPDATE_SOURCE_TEXT : { String fileName = sourceInfo . url ( ) ; if ( ! debugGui . updateFileWindow ( sourceInfo ) && ! fileName . equals ( "<stdin>" ) ) { debugGui . createFileWindow ( sourceInfo , - 1 ) ; } } break ; case ENTER_INTERRUPT : debugGui . enterInterruptImpl ( lastFrame , threadTitle , alertMessage ) ; break ; default : throw new IllegalArgumentException ( String . valueOf ( type ) ) ; } } | Runs this Runnable . |
31,950 | private static long toArrayIndex ( String id ) { long index = toArrayIndex ( ScriptRuntime . toNumber ( id ) ) ; if ( Long . toString ( index ) . equals ( id ) ) { return index ; } return - 1 ; } | otherwise return - 1L |
31,951 | private static Object jsConstructor ( Context cx , Scriptable scope , Object [ ] args ) { if ( args . length == 0 ) return new NativeArray ( 0 ) ; if ( cx . getLanguageVersion ( ) == Context . VERSION_1_2 ) { return new NativeArray ( args ) ; } Object arg0 = args [ 0 ] ; if ( args . length > 1 || ! ( arg0 instanceof Number ) ) { return new NativeArray ( args ) ; } long len = ScriptRuntime . toUint32 ( arg0 ) ; if ( len != ( ( Number ) arg0 ) . doubleValue ( ) ) { String msg = ScriptRuntime . getMessage0 ( "msg.arraylength.bad" ) ; throw ScriptRuntime . constructError ( "RangeError" , msg ) ; } return new NativeArray ( len ) ; } | See ECMA 15 . 4 . 1 2 |
31,952 | private static Object getRawElem ( Scriptable target , long index ) { if ( index > Integer . MAX_VALUE ) { return ScriptableObject . getProperty ( target , Long . toString ( index ) ) ; } return ScriptableObject . getProperty ( target , ( int ) index ) ; } | same as getElem but without converting NOT_FOUND to undefined |
31,953 | private static String js_join ( Context cx , Scriptable thisObj , Object [ ] args ) { long llength = getLengthProperty ( cx , thisObj , false ) ; int length = ( int ) llength ; if ( llength != length ) { throw Context . reportRuntimeError1 ( "msg.arraylength.too.big" , String . valueOf ( llength ) ) ; } String separator = ( args . length < 1 || args [ 0 ] == Undefined . instance ) ? "," : ScriptRuntime . toString ( args [ 0 ] ) ; if ( thisObj instanceof NativeArray ) { NativeArray na = ( NativeArray ) thisObj ; if ( na . denseOnly ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; i ++ ) { if ( i != 0 ) { sb . append ( separator ) ; } if ( i < na . dense . length ) { Object temp = na . dense [ i ] ; if ( temp != null && temp != Undefined . instance && temp != Scriptable . NOT_FOUND ) { sb . append ( ScriptRuntime . toString ( temp ) ) ; } } } return sb . toString ( ) ; } } if ( length == 0 ) { return "" ; } String [ ] buf = new String [ length ] ; int total_size = 0 ; for ( int i = 0 ; i != length ; i ++ ) { Object temp = getElem ( cx , thisObj , i ) ; if ( temp != null && temp != Undefined . instance ) { String str = ScriptRuntime . toString ( temp ) ; total_size += str . length ( ) ; buf [ i ] = str ; } } total_size += ( length - 1 ) * separator . length ( ) ; StringBuilder sb = new StringBuilder ( total_size ) ; for ( int i = 0 ; i != length ; i ++ ) { if ( i != 0 ) { sb . append ( separator ) ; } String str = buf [ i ] ; if ( str != null ) { sb . append ( str ) ; } } return sb . toString ( ) ; } | See ECMA 15 . 4 . 4 . 3 |
31,954 | private static Scriptable js_reverse ( Context cx , Scriptable thisObj , Object [ ] args ) { if ( thisObj instanceof NativeArray ) { NativeArray na = ( NativeArray ) thisObj ; if ( na . denseOnly ) { for ( int i = 0 , j = ( ( int ) na . length ) - 1 ; i < j ; i ++ , j -- ) { Object temp = na . dense [ i ] ; na . dense [ i ] = na . dense [ j ] ; na . dense [ j ] = temp ; } return thisObj ; } } long len = getLengthProperty ( cx , thisObj , false ) ; long half = len / 2 ; for ( long i = 0 ; i < half ; i ++ ) { long j = len - i - 1 ; Object temp1 = getRawElem ( thisObj , i ) ; Object temp2 = getRawElem ( thisObj , j ) ; setRawElem ( cx , thisObj , i , temp2 ) ; setRawElem ( cx , thisObj , j , temp1 ) ; } return thisObj ; } | See ECMA 15 . 4 . 4 . 4 |
31,955 | private static Scriptable js_sort ( final Context cx , final Scriptable scope , final Scriptable thisObj , final Object [ ] args ) { final Comparator < Object > comparator ; if ( args . length > 0 && Undefined . instance != args [ 0 ] ) { final Callable jsCompareFunction = ScriptRuntime . getValueFunctionAndThis ( args [ 0 ] , cx ) ; final Scriptable funThis = ScriptRuntime . lastStoredScriptable ( cx ) ; final Object [ ] cmpBuf = new Object [ 2 ] ; comparator = new ElementComparator ( new Comparator < Object > ( ) { public int compare ( final Object x , final Object y ) { cmpBuf [ 0 ] = x ; cmpBuf [ 1 ] = y ; Object ret = jsCompareFunction . call ( cx , scope , funThis , cmpBuf ) ; final double d = ScriptRuntime . toNumber ( ret ) ; if ( d < 0 ) { return - 1 ; } else if ( d > 0 ) { return + 1 ; } return 0 ; } } ) ; } else { comparator = DEFAULT_COMPARATOR ; } long llength = getLengthProperty ( cx , thisObj , false ) ; final int length = ( int ) llength ; if ( llength != length ) { throw Context . reportRuntimeError1 ( "msg.arraylength.too.big" , String . valueOf ( llength ) ) ; } final Object [ ] working = new Object [ length ] ; for ( int i = 0 ; i != length ; ++ i ) { working [ i ] = getRawElem ( thisObj , i ) ; } Sorting . hybridSort ( working , comparator ) ; for ( int i = 0 ; i < length ; ++ i ) { setRawElem ( cx , thisObj , i , working [ i ] ) ; } return thisObj ; } | See ECMA 15 . 4 . 4 . 5 |
31,956 | private static Object reduceMethod ( Context cx , int id , Scriptable scope , Scriptable thisObj , Object [ ] args ) { Scriptable o = ScriptRuntime . toObject ( cx , scope , thisObj ) ; long length = getLengthProperty ( cx , o , false ) ; Object callbackArg = args . length > 0 ? args [ 0 ] : Undefined . instance ; if ( callbackArg == null || ! ( callbackArg instanceof Function ) ) { throw ScriptRuntime . notFunctionError ( callbackArg ) ; } Function f = ( Function ) callbackArg ; Scriptable parent = ScriptableObject . getTopLevelScope ( f ) ; boolean movingLeft = id == Id_reduce ; Object value = args . length > 1 ? args [ 1 ] : Scriptable . NOT_FOUND ; for ( long i = 0 ; i < length ; i ++ ) { long index = movingLeft ? i : ( length - 1 - i ) ; Object elem = getRawElem ( o , index ) ; if ( elem == Scriptable . NOT_FOUND ) { continue ; } if ( value == Scriptable . NOT_FOUND ) { value = elem ; } else { Object [ ] innerArgs = { value , elem , index , o } ; value = f . call ( cx , parent , parent , innerArgs ) ; } } if ( value == Scriptable . NOT_FOUND ) { throw ScriptRuntime . typeError0 ( "msg.empty.array.reduce" ) ; } return value ; } | Implements the methods reduce and reduceRight . |
31,957 | static Object js_parseInt ( Object [ ] args ) { String s = ScriptRuntime . toString ( args , 0 ) ; int radix = ScriptRuntime . toInt32 ( args , 1 ) ; int len = s . length ( ) ; if ( len == 0 ) return ScriptRuntime . NaNobj ; boolean negative = false ; int start = 0 ; char c ; do { c = s . charAt ( start ) ; if ( ! ScriptRuntime . isStrWhiteSpaceChar ( c ) ) break ; start ++ ; } while ( start < len ) ; if ( c == '+' || ( negative = ( c == '-' ) ) ) start ++ ; final int NO_RADIX = - 1 ; if ( radix == 0 ) { radix = NO_RADIX ; } else if ( radix < 2 || radix > 36 ) { return ScriptRuntime . NaNobj ; } else if ( radix == 16 && len - start > 1 && s . charAt ( start ) == '0' ) { c = s . charAt ( start + 1 ) ; if ( c == 'x' || c == 'X' ) start += 2 ; } if ( radix == NO_RADIX ) { radix = 10 ; if ( len - start > 1 && s . charAt ( start ) == '0' ) { c = s . charAt ( start + 1 ) ; if ( c == 'x' || c == 'X' ) { radix = 16 ; start += 2 ; } else if ( '0' <= c && c <= '9' ) { radix = 8 ; start ++ ; } } } double d = ScriptRuntime . stringPrefixToNumber ( s , start , radix ) ; return ScriptRuntime . wrapNumber ( negative ? - d : d ) ; } | The global method parseInt as per ECMA - 262 15 . 1 . 2 . 2 . |
31,958 | static Object js_parseFloat ( Object [ ] args ) { if ( args . length < 1 ) return ScriptRuntime . NaNobj ; String s = ScriptRuntime . toString ( args [ 0 ] ) ; int len = s . length ( ) ; int start = 0 ; char c ; for ( ; ; ) { if ( start == len ) { return ScriptRuntime . NaNobj ; } c = s . charAt ( start ) ; if ( ! ScriptRuntime . isStrWhiteSpaceChar ( c ) ) { break ; } ++ start ; } int i = start ; if ( c == '+' || c == '-' ) { ++ i ; if ( i == len ) { return ScriptRuntime . NaNobj ; } c = s . charAt ( i ) ; } if ( c == 'I' ) { if ( i + 8 <= len && s . regionMatches ( i , "Infinity" , 0 , 8 ) ) { double d ; if ( s . charAt ( start ) == '-' ) { d = Double . NEGATIVE_INFINITY ; } else { d = Double . POSITIVE_INFINITY ; } return ScriptRuntime . wrapNumber ( d ) ; } return ScriptRuntime . NaNobj ; } int decimal = - 1 ; int exponent = - 1 ; boolean exponentValid = false ; for ( ; i < len ; i ++ ) { switch ( s . charAt ( i ) ) { case '.' : if ( decimal != - 1 ) break ; decimal = i ; continue ; case 'e' : case 'E' : if ( exponent != - 1 ) { break ; } else if ( i == len - 1 ) { break ; } exponent = i ; continue ; case '+' : case '-' : if ( exponent != i - 1 ) { break ; } else if ( i == len - 1 ) { -- i ; break ; } continue ; case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : if ( exponent != - 1 ) { exponentValid = true ; } continue ; default : break ; } break ; } if ( exponent != - 1 && ! exponentValid ) { i = exponent ; } s = s . substring ( start , i ) ; try { return Double . valueOf ( s ) ; } catch ( NumberFormatException ex ) { return ScriptRuntime . NaNobj ; } } | The global method parseFloat as per ECMA - 262 15 . 1 . 2 . 3 . |
31,959 | private Object js_escape ( Object [ ] args ) { final int URL_XALPHAS = 1 , URL_XPALPHAS = 2 , URL_PATH = 4 ; String s = ScriptRuntime . toString ( args , 0 ) ; int mask = URL_XALPHAS | URL_XPALPHAS | URL_PATH ; if ( args . length > 1 ) { double d = ScriptRuntime . toNumber ( args [ 1 ] ) ; if ( d != d || ( ( mask = ( int ) d ) != d ) || 0 != ( mask & ~ ( URL_XALPHAS | URL_XPALPHAS | URL_PATH ) ) ) { throw Context . reportRuntimeError0 ( "msg.bad.esc.mask" ) ; } } StringBuilder sb = null ; for ( int k = 0 , L = s . length ( ) ; k != L ; ++ k ) { int c = s . charAt ( k ) ; if ( mask != 0 && ( ( c >= '0' && c <= '9' ) || ( c >= 'A' && c <= 'Z' ) || ( c >= 'a' && c <= 'z' ) || c == '@' || c == '*' || c == '_' || c == '-' || c == '.' || ( 0 != ( mask & URL_PATH ) && ( c == '/' || c == '+' ) ) ) ) { if ( sb != null ) { sb . append ( ( char ) c ) ; } } else { if ( sb == null ) { sb = new StringBuilder ( L + 3 ) ; sb . append ( s ) ; sb . setLength ( k ) ; } int hexSize ; if ( c < 256 ) { if ( c == ' ' && mask == URL_XPALPHAS ) { sb . append ( '+' ) ; continue ; } sb . append ( '%' ) ; hexSize = 2 ; } else { sb . append ( '%' ) ; sb . append ( 'u' ) ; hexSize = 4 ; } for ( int shift = ( hexSize - 1 ) * 4 ; shift >= 0 ; shift -= 4 ) { int digit = 0xf & ( c >> shift ) ; int hc = ( digit < 10 ) ? '0' + digit : 'A' - 10 + digit ; sb . append ( ( char ) hc ) ; } } } return ( sb == null ) ? s : sb . toString ( ) ; } | The global method escape as per ECMA - 262 15 . 1 . 2 . 4 . |
31,960 | private Object js_unescape ( Object [ ] args ) { String s = ScriptRuntime . toString ( args , 0 ) ; int firstEscapePos = s . indexOf ( '%' ) ; if ( firstEscapePos >= 0 ) { int L = s . length ( ) ; char [ ] buf = s . toCharArray ( ) ; int destination = firstEscapePos ; for ( int k = firstEscapePos ; k != L ; ) { char c = buf [ k ] ; ++ k ; if ( c == '%' && k != L ) { int end , start ; if ( buf [ k ] == 'u' ) { start = k + 1 ; end = k + 5 ; } else { start = k ; end = k + 2 ; } if ( end <= L ) { int x = 0 ; for ( int i = start ; i != end ; ++ i ) { x = Kit . xDigitToInt ( buf [ i ] , x ) ; } if ( x >= 0 ) { c = ( char ) x ; k = end ; } } } buf [ destination ] = c ; ++ destination ; } s = new String ( buf , 0 , destination ) ; } return s ; } | The global unescape method as per ECMA - 262 15 . 1 . 2 . 5 . |
31,961 | public void addCatchClause ( CatchClause clause ) { assertNotNull ( clause ) ; if ( catchClauses == null ) { catchClauses = new ArrayList < CatchClause > ( ) ; } catchClauses . add ( clause ) ; clause . setParent ( this ) ; } | Add a catch - clause to the end of the list and sets its parent to this node . |
31,962 | public void visit ( NodeVisitor v ) { if ( v . visit ( this ) ) { tryBlock . visit ( v ) ; for ( CatchClause cc : getCatchClauses ( ) ) { cc . visit ( v ) ; } if ( finallyBlock != null ) { finallyBlock . visit ( v ) ; } } } | Visits this node then the try - block then any catch clauses and then any finally block . |
31,963 | public void setIdentifier ( String identifier ) { assertNotNull ( identifier ) ; this . identifier = identifier ; setLength ( identifier . length ( ) ) ; } | Sets the node s identifier |
31,964 | private static Set < Kind > validateOperators ( Set < Kind > kinds ) { for ( Kind kind : kinds ) { if ( ! COMPOUND_ASSIGNMENT_OPERATORS . contains ( kind ) ) { throw new IllegalArgumentException ( kind . name ( ) + " is not a compound-assignment operator." ) ; } } return kinds ; } | Returns the provided set of operators if they are all compound - assignment operators . Otherwise throws an IllegalArgumentException . |
31,965 | private boolean wellKnownTypeArgument ( NewClassTree tree , VisitorState state ) { Type type = getType ( tree ) ; if ( type == null ) { return false ; } type = state . getTypes ( ) . asSuper ( type , state . getSymbolFromString ( "java.lang.ThreadLocal" ) ) ; if ( type == null ) { return false ; } if ( type . getTypeArguments ( ) . isEmpty ( ) ) { return false ; } Type argType = getOnlyElement ( type . getTypeArguments ( ) ) ; if ( WELL_KNOWN_TYPES . contains ( argType . asElement ( ) . getQualifiedName ( ) . toString ( ) ) ) { return true ; } if ( isSubtype ( argType , state . getTypeFromString ( "java.text.DateFormat" ) , state ) ) { return true ; } return false ; } | Ignore some common ThreadLocal type arguments that are fine to have per - instance copies of . |
31,966 | private Description findShadowedTypes ( Tree tree , List < ? extends TypeParameterTree > typeParameters , VisitorState state ) { Env < AttrContext > env = Enter . instance ( state . context ) . getEnv ( ASTHelpers . getSymbol ( state . findEnclosing ( ClassTree . class ) ) ) ; Symtab symtab = state . getSymtab ( ) ; PackageSymbol javaLang = symtab . enterPackage ( symtab . java_base , Names . instance ( state . context ) . java_lang ) ; Iterable < Symbol > enclosingTypes = typesInEnclosingScope ( env , javaLang ) ; List < Symbol > shadowedTypes = typeParameters . stream ( ) . map ( param -> Iterables . tryFind ( enclosingTypes , sym -> sym . getSimpleName ( ) . equals ( ASTHelpers . getType ( param ) . tsym . getSimpleName ( ) ) ) . orNull ( ) ) . filter ( Objects :: nonNull ) . collect ( ImmutableList . toImmutableList ( ) ) ; if ( shadowedTypes . isEmpty ( ) ) { return Description . NO_MATCH ; } Description . Builder descBuilder = buildDescription ( tree ) ; descBuilder . setMessage ( buildMessage ( shadowedTypes ) ) ; Set < String > visibleNames = Streams . stream ( Iterables . concat ( env . info . getLocalElements ( ) , enclosingTypes ) ) . map ( sym -> sym . getSimpleName ( ) . toString ( ) ) . collect ( ImmutableSet . toImmutableSet ( ) ) ; SuggestedFix . Builder fixBuilder = SuggestedFix . builder ( ) ; shadowedTypes . stream ( ) . filter ( tv -> TypeParameterNamingClassification . classify ( tv . name . toString ( ) ) . isValidName ( ) ) . map ( tv -> TypeParameterShadowing . renameTypeVariable ( TypeParameterShadowing . typeParameterInList ( typeParameters , tv ) , tree , TypeParameterShadowing . replacementTypeVarName ( tv . name , visibleNames ) , state ) ) . forEach ( fixBuilder :: merge ) ; descBuilder . addFix ( fixBuilder . build ( ) ) ; return descBuilder . build ( ) ; } | Iterate through a list of type parameters looking for type names shadowed by any of them . |
31,967 | public static String getTextFromComment ( Comment comment ) { switch ( comment . getStyle ( ) ) { case BLOCK : return comment . getText ( ) . replaceAll ( "^\\s*/\\*\\s*(.*?)\\s*\\*/\\s*" , "$1" ) ; case LINE : return comment . getText ( ) . replaceAll ( "^\\s*//\\s*" , "" ) ; default : return comment . getText ( ) ; } } | Extract the text body from a comment . |
31,968 | static Optional < Integer > computeEndPosition ( Tree methodInvocationTree , CharSequence sourceCode , VisitorState state ) { int invocationEnd = state . getEndPosition ( methodInvocationTree ) ; if ( invocationEnd == - 1 ) { return Optional . empty ( ) ; } int nextNewLine = CharMatcher . is ( '\n' ) . indexIn ( sourceCode , invocationEnd ) ; if ( nextNewLine == - 1 ) { return Optional . of ( invocationEnd ) ; } if ( CharMatcher . is ( '/' ) . matchesNoneOf ( sourceCode . subSequence ( invocationEnd , nextNewLine ) ) ) { return Optional . of ( invocationEnd ) ; } int nextNodeEnd = state . getEndPosition ( getNextNodeOrParent ( methodInvocationTree , state ) ) ; if ( nextNodeEnd == - 1 ) { return Optional . of ( invocationEnd ) ; } return Optional . of ( nextNodeEnd ) ; } | Finds the end position of this MethodInvocationTree . This is complicated by the fact that sometimes a comment will fall outside of the bounds of the tree . |
31,969 | private static < T > T after ( T target , Iterable < ? extends T > iterable , T defaultValue ) { Iterator < ? extends T > iterator = iterable . iterator ( ) ; while ( iterator . hasNext ( ) ) { if ( iterator . next ( ) . equals ( target ) ) { break ; } } if ( iterator . hasNext ( ) ) { return iterator . next ( ) ; } return defaultValue ; } | Find the element in the iterable following the target |
31,970 | public Void visitParameterizedType ( ParameterizedTypeTree tree , VisitorState visitorState ) { VisitorState state = processMatchers ( parameterizedTypeMatchers , tree , ParameterizedTypeTreeMatcher :: matchParameterizedType , visitorState ) ; return super . visitParameterizedType ( tree , state ) ; } | generated by javac to implement autoboxing . We are only interested in source - level constructs . |
31,971 | public boolean isAcceptableChange ( Changes changes , Tree node , MethodSymbol symbol , VisitorState state ) { return changes . changedPairs ( ) . stream ( ) . allMatch ( p -> findMatch ( p . formal ( ) ) == null ) ; } | Return true if this parameter does not match any of the regular expressions in the list of overloaded words . |
31,972 | protected String findMatch ( Parameter parameter ) { for ( String regex : overloadedNamesRegexs ) { if ( parameter . name ( ) . matches ( regex ) ) { return regex ; } } return null ; } | Return the first regular expression from the list of overloaded words which matches the parameter name . |
31,973 | public static ImmutableList < String > splitToLowercaseTerms ( String identifierName ) { if ( ONLY_UNDERSCORES . matcher ( identifierName ) . matches ( ) ) { return ImmutableList . of ( identifierName ) ; } return Arrays . stream ( TERM_SPLITTER . split ( identifierName ) ) . map ( String :: toLowerCase ) . collect ( toImmutableList ( ) ) ; } | Split a Java name into terms based on either Camel Case or Underscores . We also split digits at the end of the name into a separate term so as to treat PERSON1 and PERSON_1 as the same thing . |
31,974 | public static Symbol findIdent ( String name , VisitorState state ) { return findIdent ( name , state , KindSelector . VAR ) ; } | Finds a variable declaration with the given name that is in scope at the current location . |
31,975 | public static Symbol findIdent ( String name , VisitorState state , KindSelector kind ) { ClassType enclosingClass = ASTHelpers . getType ( state . findEnclosing ( ClassTree . class ) ) ; if ( enclosingClass == null || enclosingClass . tsym == null ) { return null ; } Env < AttrContext > env = Enter . instance ( state . context ) . getClassEnv ( enclosingClass . tsym ) ; MethodTree enclosingMethod = state . findEnclosing ( MethodTree . class ) ; if ( enclosingMethod != null ) { env = MemberEnter . instance ( state . context ) . getMethodEnv ( ( JCMethodDecl ) enclosingMethod , env ) ; } try { Method method = Resolve . class . getDeclaredMethod ( "findIdent" , Env . class , Name . class , KindSelector . class ) ; method . setAccessible ( true ) ; Symbol result = ( Symbol ) method . invoke ( Resolve . instance ( state . context ) , env , state . getName ( name ) , kind ) ; return result . exists ( ) ? result : null ; } catch ( ReflectiveOperationException e ) { throw new LinkageError ( e . getMessage ( ) , e ) ; } } | Finds a declaration with the given name and type that is in scope at the current location . |
31,976 | public static ImmutableSet < Symbol > findReferencedIdentifiers ( Tree tree ) { ImmutableSet . Builder < Symbol > builder = ImmutableSet . builder ( ) ; createFindIdentifiersScanner ( builder , null ) . scan ( tree , null ) ; return builder . build ( ) ; } | Find the set of all identifiers referenced within this Tree |
31,977 | public static List < VarSymbol > findAllFields ( Type classType , VisitorState state ) { return state . getTypes ( ) . closure ( classType ) . stream ( ) . flatMap ( type -> { TypeSymbol tsym = type . tsym ; if ( tsym == null ) { return ImmutableList . < VarSymbol > of ( ) . stream ( ) ; } WriteableScope scope = tsym . members ( ) ; if ( scope == null ) { return ImmutableList . < VarSymbol > of ( ) . stream ( ) ; } return ImmutableList . copyOf ( scope . getSymbols ( VarSymbol . class :: isInstance ) ) . reverse ( ) . stream ( ) . map ( v -> ( VarSymbol ) v ) . filter ( v -> isVisible ( v , state . getPath ( ) ) ) ; } ) . collect ( Collectors . toCollection ( ArrayList :: new ) ) ; } | Finds all the visible fields declared or inherited in the target class |
31,978 | public Iterable < ExpressionTemplateMatch > match ( JCTree target , Context context ) { if ( target instanceof JCExpression ) { JCExpression targetExpr = ( JCExpression ) target ; Optional < Unifier > unifier = unify ( targetExpr , new Unifier ( context ) ) . first ( ) ; if ( unifier . isPresent ( ) ) { return ImmutableList . of ( new ExpressionTemplateMatch ( targetExpr , unifier . get ( ) ) ) ; } } return ImmutableList . of ( ) ; } | Returns the matches of this template against the specified target AST . |
31,979 | private static int getPrecedence ( JCTree leaf , Context context ) { JCCompilationUnit comp = context . get ( JCCompilationUnit . class ) ; JCTree parent = TreeInfo . pathFor ( leaf , comp ) . get ( 1 ) ; if ( parent instanceof JCConditional ) { JCConditional conditional = ( JCConditional ) parent ; return TreeInfo . condPrec + ( ( conditional . cond == leaf ) ? 1 : 0 ) ; } else if ( parent instanceof JCAssign ) { JCAssign assign = ( JCAssign ) parent ; return TreeInfo . assignPrec + ( ( assign . lhs == leaf ) ? 1 : 0 ) ; } else if ( parent instanceof JCAssignOp ) { JCAssignOp assignOp = ( JCAssignOp ) parent ; return TreeInfo . assignopPrec + ( ( assignOp . lhs == leaf ) ? 1 : 0 ) ; } else if ( parent instanceof JCUnary ) { return TreeInfo . opPrec ( parent . getTag ( ) ) ; } else if ( parent instanceof JCBinary ) { JCBinary binary = ( JCBinary ) parent ; return TreeInfo . opPrec ( parent . getTag ( ) ) + ( ( binary . rhs == leaf ) ? 1 : 0 ) ; } else if ( parent instanceof JCTypeCast ) { JCTypeCast typeCast = ( JCTypeCast ) parent ; return ( typeCast . expr == leaf ) ? TreeInfo . prefixPrec : TreeInfo . noPrec ; } else if ( parent instanceof JCInstanceOf ) { JCInstanceOf instanceOf = ( JCInstanceOf ) parent ; return TreeInfo . ordPrec + ( ( instanceOf . clazz == leaf ) ? 1 : 0 ) ; } else if ( parent instanceof JCArrayAccess ) { JCArrayAccess arrayAccess = ( JCArrayAccess ) parent ; return ( arrayAccess . indexed == leaf ) ? TreeInfo . postfixPrec : TreeInfo . noPrec ; } else if ( parent instanceof JCFieldAccess ) { JCFieldAccess fieldAccess = ( JCFieldAccess ) parent ; return ( fieldAccess . selected == leaf ) ? TreeInfo . postfixPrec : TreeInfo . noPrec ; } else { return TreeInfo . noPrec ; } } | Returns the precedence level appropriate for unambiguously printing leaf as a subexpression of its parent . |
31,980 | public static MethodSymbol getSymbol ( NewClassTree tree ) { Symbol sym = ( ( JCNewClass ) tree ) . constructor ; return sym instanceof MethodSymbol ? ( MethodSymbol ) sym : null ; } | Gets the method symbol for a new class . |
31,981 | public static MethodSymbol getSymbol ( MethodInvocationTree tree ) { Symbol sym = ASTHelpers . getSymbol ( tree . getMethodSelect ( ) ) ; if ( ! ( sym instanceof MethodSymbol ) ) { return null ; } return ( MethodSymbol ) sym ; } | Gets the symbol for a method invocation . |
31,982 | public static MethodSymbol getSymbol ( MemberReferenceTree tree ) { Symbol sym = ( ( JCMemberReference ) tree ) . sym ; return sym instanceof MethodSymbol ? ( MethodSymbol ) sym : null ; } | Gets the symbol for a member reference . |
31,983 | public static Tree stripParentheses ( Tree tree ) { while ( tree instanceof ParenthesizedTree ) { tree = ( ( ParenthesizedTree ) tree ) . getExpression ( ) ; } return tree ; } | Removes any enclosing parentheses from the tree . |
31,984 | public static ExpressionTree stripParentheses ( ExpressionTree tree ) { while ( tree instanceof ParenthesizedTree ) { tree = ( ( ParenthesizedTree ) tree ) . getExpression ( ) ; } return tree ; } | Given an ExpressionTree removes any enclosing parentheses . |
31,985 | public static < T > T findEnclosingNode ( TreePath path , Class < T > klass ) { path = findPathFromEnclosingNodeToTopLevel ( path , klass ) ; return ( path == null ) ? null : klass . cast ( path . getLeaf ( ) ) ; } | Given a TreePath walks up the tree until it finds a node of the given type . Returns null if no such node is found . |
31,986 | public static Type getReturnType ( ExpressionTree expressionTree ) { if ( expressionTree instanceof JCFieldAccess ) { JCFieldAccess methodCall = ( JCFieldAccess ) expressionTree ; return methodCall . type . getReturnType ( ) ; } else if ( expressionTree instanceof JCIdent ) { JCIdent methodCall = ( JCIdent ) expressionTree ; return methodCall . type . getReturnType ( ) ; } else if ( expressionTree instanceof JCMethodInvocation ) { return getReturnType ( ( ( JCMethodInvocation ) expressionTree ) . getMethodSelect ( ) ) ; } else if ( expressionTree instanceof JCMemberReference ) { return ( ( JCMemberReference ) expressionTree ) . sym . type . getReturnType ( ) ; } throw new IllegalArgumentException ( "Expected a JCFieldAccess or JCIdent" ) ; } | Gives the return type of an ExpressionTree that represents a method select . |
31,987 | public static ExpressionTree getReceiver ( ExpressionTree expressionTree ) { if ( expressionTree instanceof MethodInvocationTree ) { ExpressionTree methodSelect = ( ( MethodInvocationTree ) expressionTree ) . getMethodSelect ( ) ; if ( methodSelect instanceof IdentifierTree ) { return null ; } return getReceiver ( methodSelect ) ; } else if ( expressionTree instanceof MemberSelectTree ) { return ( ( MemberSelectTree ) expressionTree ) . getExpression ( ) ; } else if ( expressionTree instanceof MemberReferenceTree ) { return ( ( MemberReferenceTree ) expressionTree ) . getQualifierExpression ( ) ; } else { throw new IllegalStateException ( String . format ( "Expected expression '%s' to be a method invocation or field access, but was %s" , expressionTree , expressionTree . getKind ( ) ) ) ; } } | Returns the receiver of an expression . |
31,988 | public static List < ExpressionTree > matchBinaryTree ( BinaryTree tree , List < Matcher < ExpressionTree > > matchers , VisitorState state ) { ExpressionTree leftOperand = tree . getLeftOperand ( ) ; ExpressionTree rightOperand = tree . getRightOperand ( ) ; if ( matchers . get ( 0 ) . matches ( leftOperand , state ) && matchers . get ( 1 ) . matches ( rightOperand , state ) ) { return Arrays . asList ( leftOperand , rightOperand ) ; } else if ( matchers . get ( 0 ) . matches ( rightOperand , state ) && matchers . get ( 1 ) . matches ( leftOperand , state ) ) { return Arrays . asList ( rightOperand , leftOperand ) ; } return null ; } | Given a BinaryTree to match against and a list of two matchers applies the matchers to the operands in both orders . If both matchers match returns a list with the operand that matched each matcher in the corresponding position . |
31,989 | public static MethodTree findMethod ( MethodSymbol symbol , VisitorState state ) { return JavacTrees . instance ( state . context ) . getTree ( symbol ) ; } | Returns the method tree that matches the given symbol within the compilation unit or null if none was found . |
31,990 | public static ClassTree findClass ( ClassSymbol symbol , VisitorState state ) { return JavacTrees . instance ( state . context ) . getTree ( symbol ) ; } | Returns the class tree that matches the given symbol within the compilation unit or null if none was found . |
31,991 | public static boolean methodCanBeOverridden ( MethodSymbol methodSymbol ) { if ( methodSymbol . getModifiers ( ) . contains ( Modifier . ABSTRACT ) ) { return true ; } if ( methodSymbol . isStatic ( ) || methodSymbol . isPrivate ( ) || isFinal ( methodSymbol ) || methodSymbol . isConstructor ( ) ) { return false ; } ClassSymbol classSymbol = ( ClassSymbol ) methodSymbol . owner ; return ! isFinal ( classSymbol ) && ! classSymbol . isAnonymous ( ) ; } | Determines whether a method can be overridden . |
31,992 | public static boolean inSamePackage ( Symbol targetSymbol , VisitorState state ) { JCCompilationUnit compilationUnit = ( JCCompilationUnit ) state . getPath ( ) . getCompilationUnit ( ) ; PackageSymbol usePackage = compilationUnit . packge ; PackageSymbol targetPackage = targetSymbol . packge ( ) ; return targetPackage != null && usePackage != null && targetPackage . getQualifiedName ( ) . equals ( usePackage . getQualifiedName ( ) ) ; } | Return true if the given symbol is defined in the current package . |
31,993 | public static boolean isVoidType ( Type type , VisitorState state ) { if ( type == null ) { return false ; } return type . getKind ( ) == TypeKind . VOID || state . getTypes ( ) . isSameType ( Suppliers . JAVA_LANG_VOID_TYPE . get ( state ) , type ) ; } | Return true if the given type is void or Void . |
31,994 | public static ModifiersTree getModifiers ( Tree tree ) { if ( tree instanceof ClassTree ) { return ( ( ClassTree ) tree ) . getModifiers ( ) ; } else if ( tree instanceof MethodTree ) { return ( ( MethodTree ) tree ) . getModifiers ( ) ; } else if ( tree instanceof VariableTree ) { return ( ( VariableTree ) tree ) . getModifiers ( ) ; } else { return null ; } } | Returns the modifiers tree of the given class method or variable declaration . |
31,995 | public static Type getUpperBound ( Type type , Types types ) { if ( type . hasTag ( TypeTag . WILDCARD ) ) { return types . wildUpperBound ( type ) ; } if ( type . hasTag ( TypeTag . TYPEVAR ) && ( ( TypeVar ) type ) . isCaptured ( ) ) { return types . cvarUpperBound ( type ) ; } if ( type . getUpperBound ( ) != null ) { return type . getUpperBound ( ) ; } return type ; } | Returns the upper bound of a type if it has one or the type itself if not . Correctly handles wildcards and capture variables . |
31,996 | private static Type unaryNumericPromotion ( Type type , VisitorState state ) { Type unboxed = unboxAndEnsureNumeric ( type , state ) ; switch ( unboxed . getTag ( ) ) { case BYTE : case SHORT : case CHAR : return state . getSymtab ( ) . intType ; case INT : case LONG : case FLOAT : case DOUBLE : return unboxed ; default : throw new AssertionError ( "Should not reach here: " + type ) ; } } | Implementation of unary numeric promotion rules . |
31,997 | private static Type binaryNumericPromotion ( Type leftType , Type rightType , VisitorState state ) { Type unboxedLeft = unboxAndEnsureNumeric ( leftType , state ) ; Type unboxedRight = unboxAndEnsureNumeric ( rightType , state ) ; Set < TypeTag > tags = EnumSet . of ( unboxedLeft . getTag ( ) , unboxedRight . getTag ( ) ) ; if ( tags . contains ( TypeTag . DOUBLE ) ) { return state . getSymtab ( ) . doubleType ; } else if ( tags . contains ( TypeTag . FLOAT ) ) { return state . getSymtab ( ) . floatType ; } else if ( tags . contains ( TypeTag . LONG ) ) { return state . getSymtab ( ) . longType ; } else { return state . getSymtab ( ) . intType ; } } | Implementation of binary numeric promotion rules . |
31,998 | public static int getWorstCaseEditDistance ( int sourceLength , int targetLength , int changeCost , int openGapCost , int continueGapCost ) { int maxLen = Math . max ( sourceLength , targetLength ) ; int minLen = Math . min ( sourceLength , targetLength ) ; int totChangeCost = scriptCost ( openGapCost , continueGapCost , maxLen - minLen ) + minLen * changeCost ; int blowAwayCost = scriptCost ( openGapCost , continueGapCost , sourceLength ) + scriptCost ( openGapCost , continueGapCost , targetLength ) ; return Math . min ( totChangeCost , blowAwayCost ) ; } | Return the worst case edit distance between strings of this length |
31,999 | public Description matchMethod ( MethodTree tree , VisitorState state ) { MethodSymbol methodSym = ASTHelpers . getSymbol ( tree ) ; if ( ! methodSym . getModifiers ( ) . contains ( Modifier . PRIVATE ) ) { return Description . NO_MATCH ; } ImmutableList < Tree > params = tree . getParameters ( ) . stream ( ) . filter ( param -> hasFunctionAsArg ( param , state ) ) . filter ( param -> isFunctionArgSubtypeOf ( param , 0 , state . getTypeFromString ( JAVA_LANG_NUMBER ) , state ) || isFunctionArgSubtypeOf ( param , 1 , state . getTypeFromString ( JAVA_LANG_NUMBER ) , state ) ) . collect ( toImmutableList ( ) ) ; if ( params . isEmpty ( ) || ! methodCallsMeetConditions ( methodSym , state ) ) { return Description . NO_MATCH ; } SuggestedFix . Builder fixBuilder = SuggestedFix . builder ( ) ; for ( Tree param : params ) { getMappingForFunctionFromTree ( param ) . ifPresent ( mappedFunction -> { fixBuilder . addImport ( getImportName ( mappedFunction ) ) ; fixBuilder . replace ( param , getFunctionName ( mappedFunction ) + " " + ASTHelpers . getSymbol ( param ) . name ) ; refactorInternalApplyMethods ( tree , fixBuilder , param , mappedFunction ) ; } ) ; } return describeMatch ( tree , fixBuilder . build ( ) ) ; } | Identifies methods with parameters that have a generic argument with Int Long or Double . If pre - conditions are met it refactors them to the primitive specializations . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.