id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
21,600
mozilla/rhino
toolsrc/org/mozilla/javascript/tools/debugger/SwingGui.java
Menubar.addFile
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); }
java
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); }
[ "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...\"", ",", "'", "'", ")", ")", ";", "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", ")", "(", "'", "'", "+", "(", "count", "-", "4", ")", ")", "+", "\" \"", "+", "shortName", ",", "'", "'", "+", "(", "count", "-", "4", ")", ")", ")", ";", "if", "(", "hasMoreWin", ")", "{", "windowMenu", ".", "add", "(", "lastItem", ")", ";", "}", "}", "else", "{", "return", ";", "}", "item", ".", "setActionCommand", "(", "url", ")", ";", "item", ".", "addActionListener", "(", "this", ")", ";", "}" ]
Adds a file to the window menu.
[ "Adds", "a", "file", "to", "the", "window", "menu", "." ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/toolsrc/org/mozilla/javascript/tools/debugger/SwingGui.java#L3551-L3587
21,601
mozilla/rhino
toolsrc/org/mozilla/javascript/tools/debugger/SwingGui.java
Menubar.updateEnabled
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); } }
java
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); } }
[ "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.
[ "Updates", "the", "enabledness", "of", "menu", "items", "." ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/toolsrc/org/mozilla/javascript/tools/debugger/SwingGui.java#L3592-L3602
21,602
mozilla/rhino
toolsrc/org/mozilla/javascript/tools/debugger/SwingGui.java
RunProxy.run
@Override 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)); } }
java
@Override 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)); } }
[ "@", "Override", "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.
[ "Runs", "this", "Runnable", "." ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/toolsrc/org/mozilla/javascript/tools/debugger/SwingGui.java#L3670-L3711
21,603
mozilla/rhino
src/org/mozilla/javascript/NativeArray.java
NativeArray.toArrayIndex
private static long toArrayIndex(String id) { long index = toArrayIndex(ScriptRuntime.toNumber(id)); // Assume that ScriptRuntime.toString(index) is the same // as java.lang.Long.toString(index) for long if (Long.toString(index).equals(id)) { return index; } return -1; }
java
private static long toArrayIndex(String id) { long index = toArrayIndex(ScriptRuntime.toNumber(id)); // Assume that ScriptRuntime.toString(index) is the same // as java.lang.Long.toString(index) for long if (Long.toString(index).equals(id)) { return index; } return -1; }
[ "private", "static", "long", "toArrayIndex", "(", "String", "id", ")", "{", "long", "index", "=", "toArrayIndex", "(", "ScriptRuntime", ".", "toNumber", "(", "id", ")", ")", ";", "// Assume that ScriptRuntime.toString(index) is the same", "// as java.lang.Long.toString(index) for long", "if", "(", "Long", ".", "toString", "(", "index", ")", ".", "equals", "(", "id", ")", ")", "{", "return", "index", ";", "}", "return", "-", "1", ";", "}" ]
otherwise return -1L
[ "otherwise", "return", "-", "1L" ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeArray.java#L406-L415
21,604
mozilla/rhino
src/org/mozilla/javascript/NativeArray.java
NativeArray.jsConstructor
private static Object jsConstructor(Context cx, Scriptable scope, Object[] args) { if (args.length == 0) return new NativeArray(0); // Only use 1 arg as first element for version 1.2; for // any other version (including 1.3) follow ECMA and use it as // a length. 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); }
java
private static Object jsConstructor(Context cx, Scriptable scope, Object[] args) { if (args.length == 0) return new NativeArray(0); // Only use 1 arg as first element for version 1.2; for // any other version (including 1.3) follow ECMA and use it as // a length. 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); }
[ "private", "static", "Object", "jsConstructor", "(", "Context", "cx", ",", "Scriptable", "scope", ",", "Object", "[", "]", "args", ")", "{", "if", "(", "args", ".", "length", "==", "0", ")", "return", "new", "NativeArray", "(", "0", ")", ";", "// Only use 1 arg as first element for version 1.2; for", "// any other version (including 1.3) follow ECMA and use it as", "// a length.", "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
[ "See", "ECMA", "15", ".", "4", ".", "1", "2" ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeArray.java#L620-L642
21,605
mozilla/rhino
src/org/mozilla/javascript/NativeArray.java
NativeArray.getRawElem
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); }
java
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); }
[ "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
[ "same", "as", "getElem", "but", "without", "converting", "NOT_FOUND", "to", "undefined" ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeArray.java#L793-L798
21,606
mozilla/rhino
src/org/mozilla/javascript/NativeArray.java
NativeArray.js_join
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)); } // if no args, use "," as separator 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) { // str == null for undefined or null sb.append(str); } } return sb.toString(); }
java
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)); } // if no args, use "," as separator 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) { // str == null for undefined or null sb.append(str); } } return sb.toString(); }
[ "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", ")", ")", ";", "}", "// if no args, use \",\" as separator", "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", ")", "{", "// str == null for undefined or null", "sb", ".", "append", "(", "str", ")", ";", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
See ECMA 15.4.4.3
[ "See", "ECMA", "15", ".", "4", ".", "4", ".", "3" ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeArray.java#L931-L990
21,607
mozilla/rhino
src/org/mozilla/javascript/NativeArray.java
NativeArray.js_reverse
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; }
java
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; }
[ "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
[ "See", "ECMA", "15", ".", "4", ".", "4", ".", "4" ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeArray.java#L995-L1019
21,608
mozilla/rhino
src/org/mozilla/javascript/NativeArray.java
NativeArray.js_sort
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]; // Buffer for cmp arguments comparator = new ElementComparator( new Comparator<Object>() { @Override public int compare(final Object x, final Object y) { // This comparator is invoked only for non-undefined objects 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; // ??? double and 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)); } // copy the JS array into a working array, so it can be // sorted cheaply. final Object[] working = new Object[length]; for (int i = 0; i != length; ++i) { working[i] = getRawElem(thisObj, i); } Sorting.hybridSort(working, comparator); // copy the working array back into thisObj for (int i = 0; i < length; ++i) { setRawElem(cx, thisObj, i, working[i]); } return thisObj; }
java
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]; // Buffer for cmp arguments comparator = new ElementComparator( new Comparator<Object>() { @Override public int compare(final Object x, final Object y) { // This comparator is invoked only for non-undefined objects 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; // ??? double and 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)); } // copy the JS array into a working array, so it can be // sorted cheaply. final Object[] working = new Object[length]; for (int i = 0; i != length; ++i) { working[i] = getRawElem(thisObj, i); } Sorting.hybridSort(working, comparator); // copy the working array back into thisObj for (int i = 0; i < length; ++i) { setRawElem(cx, thisObj, i, working[i]); } return thisObj; }
[ "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", "]", ";", "// Buffer for cmp arguments", "comparator", "=", "new", "ElementComparator", "(", "new", "Comparator", "<", "Object", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "final", "Object", "x", ",", "final", "Object", "y", ")", "{", "// This comparator is invoked only for non-undefined objects", "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", ";", "// ??? double and 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", ")", ")", ";", "}", "// copy the JS array into a working array, so it can be", "// sorted cheaply.", "final", "Object", "[", "]", "working", "=", "new", "Object", "[", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "!=", "length", ";", "++", "i", ")", "{", "working", "[", "i", "]", "=", "getRawElem", "(", "thisObj", ",", "i", ")", ";", "}", "Sorting", ".", "hybridSort", "(", "working", ",", "comparator", ")", ";", "// copy the working array back into thisObj", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "++", "i", ")", "{", "setRawElem", "(", "cx", ",", "thisObj", ",", "i", ",", "working", "[", "i", "]", ")", ";", "}", "return", "thisObj", ";", "}" ]
See ECMA 15.4.4.5
[ "See", "ECMA", "15", ".", "4", ".", "4", ".", "5" ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeArray.java#L1024-L1076
21,609
mozilla/rhino
src/org/mozilla/javascript/NativeArray.java
NativeArray.reduceMethod
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); // hack to serve both reduce and reduceRight with the same loop 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) { // no initial value passed, use first element found as inital value value = elem; } else { Object[] innerArgs = { value, elem, index, o }; value = f.call(cx, parent, parent, innerArgs); } } if (value == Scriptable.NOT_FOUND) { // reproduce spidermonkey error message throw ScriptRuntime.typeError0("msg.empty.array.reduce"); } return value; }
java
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); // hack to serve both reduce and reduceRight with the same loop 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) { // no initial value passed, use first element found as inital value value = elem; } else { Object[] innerArgs = { value, elem, index, o }; value = f.call(cx, parent, parent, innerArgs); } } if (value == Scriptable.NOT_FOUND) { // reproduce spidermonkey error message throw ScriptRuntime.typeError0("msg.empty.array.reduce"); } return value; }
[ "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", ")", ";", "// hack to serve both reduce and reduceRight with the same loop", "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", ")", "{", "// no initial value passed, use first element found as inital value", "value", "=", "elem", ";", "}", "else", "{", "Object", "[", "]", "innerArgs", "=", "{", "value", ",", "elem", ",", "index", ",", "o", "}", ";", "value", "=", "f", ".", "call", "(", "cx", ",", "parent", ",", "parent", ",", "innerArgs", ")", ";", "}", "}", "if", "(", "value", "==", "Scriptable", ".", "NOT_FOUND", ")", "{", "// reproduce spidermonkey error message", "throw", "ScriptRuntime", ".", "typeError0", "(", "\"msg.empty.array.reduce\"", ")", ";", "}", "return", "value", ";", "}" ]
Implements the methods "reduce" and "reduceRight".
[ "Implements", "the", "methods", "reduce", "and", "reduceRight", "." ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeArray.java#L1745-L1779
21,610
mozilla/rhino
src/org/mozilla/javascript/NativeGlobal.java
NativeGlobal.js_parseInt
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); }
java
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); }
[ "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", ")", "==", "'", "'", ")", "{", "c", "=", "s", ".", "charAt", "(", "start", "+", "1", ")", ";", "if", "(", "c", "==", "'", "'", "||", "c", "==", "'", "'", ")", "start", "+=", "2", ";", "}", "if", "(", "radix", "==", "NO_RADIX", ")", "{", "radix", "=", "10", ";", "if", "(", "len", "-", "start", ">", "1", "&&", "s", ".", "charAt", "(", "start", ")", "==", "'", "'", ")", "{", "c", "=", "s", ".", "charAt", "(", "start", "+", "1", ")", ";", "if", "(", "c", "==", "'", "'", "||", "c", "==", "'", "'", ")", "{", "radix", "=", "16", ";", "start", "+=", "2", ";", "}", "else", "if", "(", "'", "'", "<=", "c", "&&", "c", "<=", "'", "'", ")", "{", "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.
[ "The", "global", "method", "parseInt", "as", "per", "ECMA", "-", "262", "15", ".", "1", ".", "2", ".", "2", "." ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeGlobal.java#L208-L256
21,611
mozilla/rhino
src/org/mozilla/javascript/NativeGlobal.java
NativeGlobal.js_parseFloat
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; // Scan forward to skip whitespace 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') { // check for "Infinity" 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; } // Find the end of the legal bit int decimal = -1; int exponent = -1; boolean exponentValid = false; for (; i < len; i++) { switch (s.charAt(i)) { case '.': if (decimal != -1) // Only allow a single decimal point. break; decimal = i; continue; case 'e': case 'E': if (exponent != -1) { break; } else if (i == len - 1) { break; } exponent = i; continue; case '+': case '-': // Only allow '+' or '-' after 'e' or 'E' 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; } }
java
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; // Scan forward to skip whitespace 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') { // check for "Infinity" 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; } // Find the end of the legal bit int decimal = -1; int exponent = -1; boolean exponentValid = false; for (; i < len; i++) { switch (s.charAt(i)) { case '.': if (decimal != -1) // Only allow a single decimal point. break; decimal = i; continue; case 'e': case 'E': if (exponent != -1) { break; } else if (i == len - 1) { break; } exponent = i; continue; case '+': case '-': // Only allow '+' or '-' after 'e' or 'E' 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; } }
[ "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", ";", "// Scan forward to skip whitespace", "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", "==", "'", "'", ")", "{", "// check for \"Infinity\"", "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", ";", "}", "// Find the end of the legal bit", "int", "decimal", "=", "-", "1", ";", "int", "exponent", "=", "-", "1", ";", "boolean", "exponentValid", "=", "false", ";", "for", "(", ";", "i", "<", "len", ";", "i", "++", ")", "{", "switch", "(", "s", ".", "charAt", "(", "i", ")", ")", "{", "case", "'", "'", ":", "if", "(", "decimal", "!=", "-", "1", ")", "// Only allow a single decimal point.", "break", ";", "decimal", "=", "i", ";", "continue", ";", "case", "'", "'", ":", "case", "'", "'", ":", "if", "(", "exponent", "!=", "-", "1", ")", "{", "break", ";", "}", "else", "if", "(", "i", "==", "len", "-", "1", ")", "{", "break", ";", "}", "exponent", "=", "i", ";", "continue", ";", "case", "'", "'", ":", "case", "'", "'", ":", "// Only allow '+' or '-' after 'e' or 'E'", "if", "(", "exponent", "!=", "i", "-", "1", ")", "{", "break", ";", "}", "else", "if", "(", "i", "==", "len", "-", "1", ")", "{", "--", "i", ";", "break", ";", "}", "continue", ";", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "case", "'", "'", ":", "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. @param args the arguments to parseFloat, ignoring args[>=1]
[ "The", "global", "method", "parseFloat", "as", "per", "ECMA", "-", "262", "15", ".", "1", ".", "2", ".", "3", "." ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeGlobal.java#L263-L362
21,612
mozilla/rhino
src/org/mozilla/javascript/NativeGlobal.java
NativeGlobal.js_escape
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) { // the 'mask' argument. Non-ECMA. 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; } // append hexadecimal form of c left-padded with 0 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(); }
java
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) { // the 'mask' argument. Non-ECMA. 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; } // append hexadecimal form of c left-padded with 0 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(); }
[ "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", ")", "{", "// the 'mask' argument. Non-ECMA.", "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", ">=", "'", "'", "&&", "c", "<=", "'", "'", ")", "||", "(", "c", ">=", "'", "'", "&&", "c", "<=", "'", "'", ")", "||", "(", "c", ">=", "'", "'", "&&", "c", "<=", "'", "'", ")", "||", "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", "(", "'", "'", ")", ";", "hexSize", "=", "4", ";", "}", "// append hexadecimal form of c left-padded with 0", "for", "(", "int", "shift", "=", "(", "hexSize", "-", "1", ")", "*", "4", ";", "shift", ">=", "0", ";", "shift", "-=", "4", ")", "{", "int", "digit", "=", "0xf", "&", "(", "c", ">>", "shift", ")", ";", "int", "hc", "=", "(", "digit", "<", "10", ")", "?", "'", "'", "+", "digit", ":", "'", "'", "-", "10", "+", "digit", ";", "sb", ".", "append", "(", "(", "char", ")", "hc", ")", ";", "}", "}", "}", "return", "(", "sb", "==", "null", ")", "?", "s", ":", "sb", ".", "toString", "(", ")", ";", "}" ]
The global method escape, as per ECMA-262 15.1.2.4. Includes code for the 'mask' argument supported by the C escape method, which used to be part of the browser imbedding. Blame for the strange constant names should be directed there.
[ "The", "global", "method", "escape", "as", "per", "ECMA", "-", "262", "15", ".", "1", ".", "2", ".", "4", "." ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeGlobal.java#L372-L433
21,613
mozilla/rhino
src/org/mozilla/javascript/NativeGlobal.java
NativeGlobal.js_unescape
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; }
java
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; }
[ "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", "]", "==", "'", "'", ")", "{", "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.
[ "The", "global", "unescape", "method", "as", "per", "ECMA", "-", "262", "15", ".", "1", ".", "2", ".", "5", "." ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/NativeGlobal.java#L439-L476
21,614
mozilla/rhino
src/org/mozilla/javascript/ast/TryStatement.java
TryStatement.addCatchClause
public void addCatchClause(CatchClause clause) { assertNotNull(clause); if (catchClauses == null) { catchClauses = new ArrayList<CatchClause>(); } catchClauses.add(clause); clause.setParent(this); }
java
public void addCatchClause(CatchClause clause) { assertNotNull(clause); if (catchClauses == null) { catchClauses = new ArrayList<CatchClause>(); } catchClauses.add(clause); clause.setParent(this); }
[ "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. @throws IllegalArgumentException} if {@code clause} is {@code null}
[ "Add", "a", "catch", "-", "clause", "to", "the", "end", "of", "the", "list", "and", "sets", "its", "parent", "to", "this", "node", "." ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/ast/TryStatement.java#L96-L103
21,615
mozilla/rhino
src/org/mozilla/javascript/ast/TryStatement.java
TryStatement.visit
@Override 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); } } }
java
@Override 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); } } }
[ "@", "Override", "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.
[ "Visits", "this", "node", "then", "the", "try", "-", "block", "then", "any", "catch", "clauses", "and", "then", "any", "finally", "block", "." ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/ast/TryStatement.java#L159-L170
21,616
mozilla/rhino
src/org/mozilla/javascript/ast/Name.java
Name.setIdentifier
public void setIdentifier(String identifier) { assertNotNull(identifier); this.identifier = identifier; setLength(identifier.length()); }
java
public void setIdentifier(String identifier) { assertNotNull(identifier); this.identifier = identifier; setLength(identifier.length()); }
[ "public", "void", "setIdentifier", "(", "String", "identifier", ")", "{", "assertNotNull", "(", "identifier", ")", ";", "this", ".", "identifier", "=", "identifier", ";", "setLength", "(", "identifier", ".", "length", "(", ")", ")", ";", "}" ]
Sets the node's identifier @throws IllegalArgumentException if identifier is null
[ "Sets", "the", "node", "s", "identifier" ]
fa8a86df11d37623f5faa8d445a5876612bc47b0
https://github.com/mozilla/rhino/blob/fa8a86df11d37623f5faa8d445a5876612bc47b0/src/org/mozilla/javascript/ast/Name.java#L68-L72
21,617
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/CompoundAssignment.java
CompoundAssignment.validateOperators
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; }
java
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; }
[ "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.
[ "Returns", "the", "provided", "set", "of", "operators", "if", "they", "are", "all", "compound", "-", "assignment", "operators", ".", "Otherwise", "throws", "an", "IllegalArgumentException", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/CompoundAssignment.java#L88-L95
21,618
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ThreadLocalUsage.java
ThreadLocalUsage.wellKnownTypeArgument
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; }
java
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; }
[ "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.
[ "Ignore", "some", "common", "ThreadLocal", "type", "arguments", "that", "are", "fine", "to", "have", "per", "-", "instance", "copies", "of", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/ThreadLocalUsage.java#L106-L126
21,619
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/TypeNameShadowing.java
TypeNameShadowing.findShadowedTypes
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(); }
java
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(); }
[ "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.
[ "Iterate", "through", "a", "list", "of", "type", "parameters", "looking", "for", "type", "names", "shadowed", "by", "any", "of", "them", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/TypeNameShadowing.java#L118-L171
21,620
google/error-prone
check_api/src/main/java/com/google/errorprone/util/Comments.java
Comments.getTextFromComment
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(); } }
java
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(); } }
[ "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. <p>This currently includes asterisks that start lines in the body of block comments. Do not rely on this behaviour. <p>TODO(andrewrice) Update this method to handle block comments properly if we find the need
[ "Extract", "the", "text", "body", "from", "a", "comment", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/Comments.java#L94-L103
21,621
google/error-prone
check_api/src/main/java/com/google/errorprone/util/Comments.java
Comments.computeEndPosition
@VisibleForTesting static Optional<Integer> computeEndPosition( Tree methodInvocationTree, CharSequence sourceCode, VisitorState state) { int invocationEnd = state.getEndPosition(methodInvocationTree); if (invocationEnd == -1) { return Optional.empty(); } // Finding a good end position is expensive so first check whether we have any comment at // the end of our line. If we don't then we can just use the end of the methodInvocationTree 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); }
java
@VisibleForTesting static Optional<Integer> computeEndPosition( Tree methodInvocationTree, CharSequence sourceCode, VisitorState state) { int invocationEnd = state.getEndPosition(methodInvocationTree); if (invocationEnd == -1) { return Optional.empty(); } // Finding a good end position is expensive so first check whether we have any comment at // the end of our line. If we don't then we can just use the end of the methodInvocationTree 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); }
[ "@", "VisibleForTesting", "static", "Optional", "<", "Integer", ">", "computeEndPosition", "(", "Tree", "methodInvocationTree", ",", "CharSequence", "sourceCode", ",", "VisitorState", "state", ")", "{", "int", "invocationEnd", "=", "state", ".", "getEndPosition", "(", "methodInvocationTree", ")", ";", "if", "(", "invocationEnd", "==", "-", "1", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "// Finding a good end position is expensive so first check whether we have any comment at", "// the end of our line. If we don't then we can just use the end of the methodInvocationTree", "int", "nextNewLine", "=", "CharMatcher", ".", "is", "(", "'", "'", ")", ".", "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. <p>For example: <pre> test(arg1, // comment1 arg2); // comment2 int i; </pre> In this case {@code comment2} lies beyond the end of the invocation tree. In order to get the comment we need the tokenizer to lex the token which follows the invocation ({@code int} in the example). <p>We over-approximate this end position by looking for the next node in the AST and using the end position of this node. <p>As a heuristic we first scan for any {@code /} characters on the same line as the end of the method invocation. If we don't find any then we use the end of the method invocation as the end position. @return the end position of the tree or Optional.empty if we are unable to calculate it
[ "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", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/Comments.java#L235-L260
21,622
google/error-prone
check_api/src/main/java/com/google/errorprone/util/Comments.java
Comments.after
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; }
java
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; }
[ "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 @param target is the element to search for @param iterable is the iterable to search @param defaultValue will be returned if there is no item following the searched for item @return the item following {@code target} or {@code defaultValue} if not found
[ "Find", "the", "element", "in", "the", "iterable", "following", "the", "target" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/Comments.java#L300-L313
21,623
google/error-prone
check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java
ErrorProneScanner.visitParameterizedType
@Override public Void visitParameterizedType(ParameterizedTypeTree tree, VisitorState visitorState) { VisitorState state = processMatchers( parameterizedTypeMatchers, tree, ParameterizedTypeTreeMatcher::matchParameterizedType, visitorState); return super.visitParameterizedType(tree, state); }
java
@Override public Void visitParameterizedType(ParameterizedTypeTree tree, VisitorState visitorState) { VisitorState state = processMatchers( parameterizedTypeMatchers, tree, ParameterizedTypeTreeMatcher::matchParameterizedType, visitorState); return super.visitParameterizedType(tree, state); }
[ "@", "Override", "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.
[ "generated", "by", "javac", "to", "implement", "autoboxing", ".", "We", "are", "only", "interested", "in", "source", "-", "level", "constructs", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java#L766-L775
21,624
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/LowInformationNameHeuristic.java
LowInformationNameHeuristic.isAcceptableChange
@Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { return changes.changedPairs().stream().allMatch(p -> findMatch(p.formal()) == null); }
java
@Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { return changes.changedPairs().stream().allMatch(p -> findMatch(p.formal()) == null); }
[ "@", "Override", "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.
[ "Return", "true", "if", "this", "parameter", "does", "not", "match", "any", "of", "the", "regular", "expressions", "in", "the", "list", "of", "overloaded", "words", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/LowInformationNameHeuristic.java#L51-L55
21,625
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/LowInformationNameHeuristic.java
LowInformationNameHeuristic.findMatch
protected String findMatch(Parameter parameter) { for (String regex : overloadedNamesRegexs) { if (parameter.name().matches(regex)) { return regex; } } return null; }
java
protected String findMatch(Parameter parameter) { for (String regex : overloadedNamesRegexs) { if (parameter.name().matches(regex)) { return regex; } } return null; }
[ "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.
[ "Return", "the", "first", "regular", "expression", "from", "the", "list", "of", "overloaded", "words", "which", "matches", "the", "parameter", "name", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/LowInformationNameHeuristic.java#L61-L68
21,626
google/error-prone
check_api/src/main/java/com/google/errorprone/names/NamingConventions.java
NamingConventions.splitToLowercaseTerms
public static ImmutableList<String> splitToLowercaseTerms(String identifierName) { if (ONLY_UNDERSCORES.matcher(identifierName).matches()) { // Degenerate case of names which contain only underscore return ImmutableList.of(identifierName); } return Arrays.stream(TERM_SPLITTER.split(identifierName)) .map(String::toLowerCase) .collect(toImmutableList()); }
java
public static ImmutableList<String> splitToLowercaseTerms(String identifierName) { if (ONLY_UNDERSCORES.matcher(identifierName).matches()) { // Degenerate case of names which contain only underscore return ImmutableList.of(identifierName); } return Arrays.stream(TERM_SPLITTER.split(identifierName)) .map(String::toLowerCase) .collect(toImmutableList()); }
[ "public", "static", "ImmutableList", "<", "String", ">", "splitToLowercaseTerms", "(", "String", "identifierName", ")", "{", "if", "(", "ONLY_UNDERSCORES", ".", "matcher", "(", "identifierName", ")", ".", "matches", "(", ")", ")", "{", "// Degenerate case of names which contain only underscore", "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. @param identifierName to split @return a list of the terms in the name, in order and converted to lowercase
[ "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", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/names/NamingConventions.java#L45-L53
21,627
google/error-prone
check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java
FindIdentifiers.findIdent
public static Symbol findIdent(String name, VisitorState state) { return findIdent(name, state, KindSelector.VAR); }
java
public static Symbol findIdent(String name, VisitorState state) { return findIdent(name, state, KindSelector.VAR); }
[ "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.
[ "Finds", "a", "variable", "declaration", "with", "the", "given", "name", "that", "is", "in", "scope", "at", "the", "current", "location", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java#L80-L82
21,628
google/error-prone
check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java
FindIdentifiers.findIdent
@Nullable 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); } }
java
@Nullable 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); } }
[ "@", "Nullable", "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.
[ "Finds", "a", "declaration", "with", "the", "given", "name", "and", "type", "that", "is", "in", "scope", "at", "the", "current", "location", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java#L85-L106
21,629
google/error-prone
check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java
FindIdentifiers.findReferencedIdentifiers
public static ImmutableSet<Symbol> findReferencedIdentifiers(Tree tree) { ImmutableSet.Builder<Symbol> builder = ImmutableSet.builder(); createFindIdentifiersScanner(builder, null).scan(tree, null); return builder.build(); }
java
public static ImmutableSet<Symbol> findReferencedIdentifiers(Tree tree) { ImmutableSet.Builder<Symbol> builder = ImmutableSet.builder(); createFindIdentifiersScanner(builder, null).scan(tree, null); return builder.build(); }
[ "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
[ "Find", "the", "set", "of", "all", "identifiers", "referenced", "within", "this", "Tree" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java#L272-L276
21,630
google/error-prone
check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java
FindIdentifiers.findAllFields
public static List<VarSymbol> findAllFields(Type classType, VisitorState state) { // TODO(andrewrice): Switch collector to ImmutableList.toImmutableList() when released 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)); }
java
public static List<VarSymbol> findAllFields(Type classType, VisitorState state) { // TODO(andrewrice): Switch collector to ImmutableList.toImmutableList() when released 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)); }
[ "public", "static", "List", "<", "VarSymbol", ">", "findAllFields", "(", "Type", "classType", ",", "VisitorState", "state", ")", "{", "// TODO(andrewrice): Switch collector to ImmutableList.toImmutableList() when released", "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
[ "Finds", "all", "the", "visible", "fields", "declared", "or", "inherited", "in", "the", "target", "class" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.java#L279-L298
21,631
google/error-prone
core/src/main/java/com/google/errorprone/refaster/ExpressionTemplate.java
ExpressionTemplate.match
@Override 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(); }
java
@Override 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(); }
[ "@", "Override", "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.
[ "Returns", "the", "matches", "of", "this", "template", "against", "the", "specified", "target", "AST", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/refaster/ExpressionTemplate.java#L124-L134
21,632
google/error-prone
core/src/main/java/com/google/errorprone/refaster/ExpressionTemplate.java
ExpressionTemplate.getPrecedence
private static int getPrecedence(JCTree leaf, Context context) { JCCompilationUnit comp = context.get(JCCompilationUnit.class); JCTree parent = TreeInfo.pathFor(leaf, comp).get(1); // In general, this should match the logic in com.sun.tools.javac.tree.Pretty. // // TODO(mdempsky): There are probably cases where we could omit parentheses // by tweaking the returned precedence, but they need careful review. // For example, consider a template to replace "add(a, b)" with "a + b", // which applied to "x + add(y, z)" would result in "x + (y + z)". // In most cases, we'd likely prefer "x + y + z" instead, but those aren't // always equivalent: "0L + (Integer.MIN_VALUE + Integer.MIN_VALUE)" yields // a different value than "0L + Integer.MIN_VALUE + Integer.MIN_VALUE" due // to integer promotion rules. if (parent instanceof JCConditional) { // This intentionally differs from Pretty, because Pretty appears buggy: // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html 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; } }
java
private static int getPrecedence(JCTree leaf, Context context) { JCCompilationUnit comp = context.get(JCCompilationUnit.class); JCTree parent = TreeInfo.pathFor(leaf, comp).get(1); // In general, this should match the logic in com.sun.tools.javac.tree.Pretty. // // TODO(mdempsky): There are probably cases where we could omit parentheses // by tweaking the returned precedence, but they need careful review. // For example, consider a template to replace "add(a, b)" with "a + b", // which applied to "x + add(y, z)" would result in "x + (y + z)". // In most cases, we'd likely prefer "x + y + z" instead, but those aren't // always equivalent: "0L + (Integer.MIN_VALUE + Integer.MIN_VALUE)" yields // a different value than "0L + Integer.MIN_VALUE + Integer.MIN_VALUE" due // to integer promotion rules. if (parent instanceof JCConditional) { // This intentionally differs from Pretty, because Pretty appears buggy: // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html 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; } }
[ "private", "static", "int", "getPrecedence", "(", "JCTree", "leaf", ",", "Context", "context", ")", "{", "JCCompilationUnit", "comp", "=", "context", ".", "get", "(", "JCCompilationUnit", ".", "class", ")", ";", "JCTree", "parent", "=", "TreeInfo", ".", "pathFor", "(", "leaf", ",", "comp", ")", ".", "get", "(", "1", ")", ";", "// In general, this should match the logic in com.sun.tools.javac.tree.Pretty.", "//", "// TODO(mdempsky): There are probably cases where we could omit parentheses", "// by tweaking the returned precedence, but they need careful review.", "// For example, consider a template to replace \"add(a, b)\" with \"a + b\",", "// which applied to \"x + add(y, z)\" would result in \"x + (y + z)\".", "// In most cases, we'd likely prefer \"x + y + z\" instead, but those aren't", "// always equivalent: \"0L + (Integer.MIN_VALUE + Integer.MIN_VALUE)\" yields", "// a different value than \"0L + Integer.MIN_VALUE + Integer.MIN_VALUE\" due", "// to integer promotion rules.", "if", "(", "parent", "instanceof", "JCConditional", ")", "{", "// This intentionally differs from Pretty, because Pretty appears buggy:", "// http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html", "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.
[ "Returns", "the", "precedence", "level", "appropriate", "for", "unambiguously", "printing", "leaf", "as", "a", "subexpression", "of", "its", "parent", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/refaster/ExpressionTemplate.java#L249-L295
21,633
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.getSymbol
@Nullable public static MethodSymbol getSymbol(NewClassTree tree) { Symbol sym = ((JCNewClass) tree).constructor; return sym instanceof MethodSymbol ? (MethodSymbol) sym : null; }
java
@Nullable public static MethodSymbol getSymbol(NewClassTree tree) { Symbol sym = ((JCNewClass) tree).constructor; return sym instanceof MethodSymbol ? (MethodSymbol) sym : null; }
[ "@", "Nullable", "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.
[ "Gets", "the", "method", "symbol", "for", "a", "new", "class", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L263-L267
21,634
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.getSymbol
@Nullable public static MethodSymbol getSymbol(MethodInvocationTree tree) { Symbol sym = ASTHelpers.getSymbol(tree.getMethodSelect()); if (!(sym instanceof MethodSymbol)) { // Defensive. Would only occur if there are errors in the AST. return null; } return (MethodSymbol) sym; }
java
@Nullable public static MethodSymbol getSymbol(MethodInvocationTree tree) { Symbol sym = ASTHelpers.getSymbol(tree.getMethodSelect()); if (!(sym instanceof MethodSymbol)) { // Defensive. Would only occur if there are errors in the AST. return null; } return (MethodSymbol) sym; }
[ "@", "Nullable", "public", "static", "MethodSymbol", "getSymbol", "(", "MethodInvocationTree", "tree", ")", "{", "Symbol", "sym", "=", "ASTHelpers", ".", "getSymbol", "(", "tree", ".", "getMethodSelect", "(", ")", ")", ";", "if", "(", "!", "(", "sym", "instanceof", "MethodSymbol", ")", ")", "{", "// Defensive. Would only occur if there are errors in the AST.", "return", "null", ";", "}", "return", "(", "MethodSymbol", ")", "sym", ";", "}" ]
Gets the symbol for a method invocation.
[ "Gets", "the", "symbol", "for", "a", "method", "invocation", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L275-L283
21,635
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.getSymbol
@Nullable public static MethodSymbol getSymbol(MemberReferenceTree tree) { Symbol sym = ((JCMemberReference) tree).sym; return sym instanceof MethodSymbol ? (MethodSymbol) sym : null; }
java
@Nullable public static MethodSymbol getSymbol(MemberReferenceTree tree) { Symbol sym = ((JCMemberReference) tree).sym; return sym instanceof MethodSymbol ? (MethodSymbol) sym : null; }
[ "@", "Nullable", "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.
[ "Gets", "the", "symbol", "for", "a", "member", "reference", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L286-L290
21,636
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.stripParentheses
public static Tree stripParentheses(Tree tree) { while (tree instanceof ParenthesizedTree) { tree = ((ParenthesizedTree) tree).getExpression(); } return tree; }
java
public static Tree stripParentheses(Tree tree) { while (tree instanceof ParenthesizedTree) { tree = ((ParenthesizedTree) tree).getExpression(); } return tree; }
[ "public", "static", "Tree", "stripParentheses", "(", "Tree", "tree", ")", "{", "while", "(", "tree", "instanceof", "ParenthesizedTree", ")", "{", "tree", "=", "(", "(", "ParenthesizedTree", ")", "tree", ")", ".", "getExpression", "(", ")", ";", "}", "return", "tree", ";", "}" ]
Removes any enclosing parentheses from the tree.
[ "Removes", "any", "enclosing", "parentheses", "from", "the", "tree", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L321-L326
21,637
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.stripParentheses
public static ExpressionTree stripParentheses(ExpressionTree tree) { while (tree instanceof ParenthesizedTree) { tree = ((ParenthesizedTree) tree).getExpression(); } return tree; }
java
public static ExpressionTree stripParentheses(ExpressionTree tree) { while (tree instanceof ParenthesizedTree) { tree = ((ParenthesizedTree) tree).getExpression(); } return tree; }
[ "public", "static", "ExpressionTree", "stripParentheses", "(", "ExpressionTree", "tree", ")", "{", "while", "(", "tree", "instanceof", "ParenthesizedTree", ")", "{", "tree", "=", "(", "(", "ParenthesizedTree", ")", "tree", ")", ".", "getExpression", "(", ")", ";", "}", "return", "tree", ";", "}" ]
Given an ExpressionTree, removes any enclosing parentheses.
[ "Given", "an", "ExpressionTree", "removes", "any", "enclosing", "parentheses", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L329-L334
21,638
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.findEnclosingNode
@Nullable public static <T> T findEnclosingNode(TreePath path, Class<T> klass) { path = findPathFromEnclosingNodeToTopLevel(path, klass); return (path == null) ? null : klass.cast(path.getLeaf()); }
java
@Nullable public static <T> T findEnclosingNode(TreePath path, Class<T> klass) { path = findPathFromEnclosingNodeToTopLevel(path, klass); return (path == null) ? null : klass.cast(path.getLeaf()); }
[ "@", "Nullable", "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.
[ "Given", "a", "TreePath", "walks", "up", "the", "tree", "until", "it", "finds", "a", "node", "of", "the", "given", "type", ".", "Returns", "null", "if", "no", "such", "node", "is", "found", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L353-L357
21,639
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.getReturnType
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"); }
java
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"); }
[ "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. <p>TODO(eaftan): Are there other places this could be used?
[ "Gives", "the", "return", "type", "of", "an", "ExpressionTree", "that", "represents", "a", "method", "select", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L409-L422
21,640
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.getReceiver
@Nullable 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())); } }
java
@Nullable 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())); } }
[ "@", "Nullable", "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. <p>Examples: <pre>{@code a.foo() ==> a a.b.foo() ==> a.b a.bar().foo() ==> a.bar() a.b.c ==> a.b a.b().c ==> a.b() this.foo() ==> this foo() ==> null TheClass.aStaticMethod() ==> TheClass aStaticMethod() ==> null aStaticallyImportedMethod() ==> null }</pre>
[ "Returns", "the", "receiver", "of", "an", "expression", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L490-L508
21,641
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.matchBinaryTree
@Nullable 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; }
java
@Nullable 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; }
[ "@", "Nullable", "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. @param tree a BinaryTree AST node @param matchers a list of matchers @param state the VisitorState @return a list of matched operands, or null if at least one did not match
[ "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", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L520-L533
21,642
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.findMethod
@Nullable public static MethodTree findMethod(MethodSymbol symbol, VisitorState state) { return JavacTrees.instance(state.context).getTree(symbol); }
java
@Nullable public static MethodTree findMethod(MethodSymbol symbol, VisitorState state) { return JavacTrees.instance(state.context).getTree(symbol); }
[ "@", "Nullable", "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.
[ "Returns", "the", "method", "tree", "that", "matches", "the", "given", "symbol", "within", "the", "compilation", "unit", "or", "null", "if", "none", "was", "found", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L539-L542
21,643
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.findClass
@Nullable public static ClassTree findClass(ClassSymbol symbol, VisitorState state) { return JavacTrees.instance(state.context).getTree(symbol); }
java
@Nullable public static ClassTree findClass(ClassSymbol symbol, VisitorState state) { return JavacTrees.instance(state.context).getTree(symbol); }
[ "@", "Nullable", "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.
[ "Returns", "the", "class", "tree", "that", "matches", "the", "given", "symbol", "within", "the", "compilation", "unit", "or", "null", "if", "none", "was", "found", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L548-L551
21,644
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.methodCanBeOverridden
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(); }
java
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(); }
[ "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. @return true if the method can be overridden.
[ "Determines", "whether", "a", "method", "can", "be", "overridden", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L631-L645
21,645
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.inSamePackage
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()); }
java
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()); }
[ "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.
[ "Return", "true", "if", "the", "given", "symbol", "is", "defined", "in", "the", "current", "package", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L889-L897
21,646
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.isVoidType
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); }
java
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); }
[ "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'.
[ "Return", "true", "if", "the", "given", "type", "is", "void", "or", "Void", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L938-L944
21,647
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.getModifiers
@Nullable 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; } }
java
@Nullable 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; } }
[ "@", "Nullable", "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.
[ "Returns", "the", "modifiers", "tree", "of", "the", "given", "class", "method", "or", "variable", "declaration", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L987-L998
21,648
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.getUpperBound
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(); } // concrete type, e.g. java.lang.String, or a case we haven't considered return type; }
java
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(); } // concrete type, e.g. java.lang.String, or a case we haven't considered return type; }
[ "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", "(", ")", ";", "}", "// concrete type, e.g. java.lang.String, or a case we haven't considered", "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.
[ "Returns", "the", "upper", "bound", "of", "a", "type", "if", "it", "has", "one", "or", "the", "type", "itself", "if", "not", ".", "Correctly", "handles", "wildcards", "and", "capture", "variables", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L1004-L1019
21,649
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.unaryNumericPromotion
@Nullable 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); } }
java
@Nullable 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); } }
[ "@", "Nullable", "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. <p><a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-5.html#jls-5.6.1">JLS §5.6.1</a>
[ "Implementation", "of", "unary", "numeric", "promotion", "rules", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L1248-L1264
21,650
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.binaryNumericPromotion
@Nullable 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; } }
java
@Nullable 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; } }
[ "@", "Nullable", "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. <p><a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-5.html#jls-5.6.2">JLS §5.6.2</a>
[ "Implementation", "of", "binary", "numeric", "promotion", "rules", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L1272-L1286
21,651
google/error-prone
check_api/src/main/java/com/google/errorprone/names/NeedlemanWunschEditDistance.java
NeedlemanWunschEditDistance.getWorstCaseEditDistance
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); // Compute maximum cost of changing one string into another. If the // lengths differ, you'll need maxLen - minLen insertions or deletions. int totChangeCost = scriptCost(openGapCost, continueGapCost, maxLen - minLen) + minLen * changeCost; // Another possibility is to just delete the entire source and insert the // target, and not do any changes. int blowAwayCost = scriptCost(openGapCost, continueGapCost, sourceLength) + scriptCost(openGapCost, continueGapCost, targetLength); return Math.min(totChangeCost, blowAwayCost); }
java
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); // Compute maximum cost of changing one string into another. If the // lengths differ, you'll need maxLen - minLen insertions or deletions. int totChangeCost = scriptCost(openGapCost, continueGapCost, maxLen - minLen) + minLen * changeCost; // Another possibility is to just delete the entire source and insert the // target, and not do any changes. int blowAwayCost = scriptCost(openGapCost, continueGapCost, sourceLength) + scriptCost(openGapCost, continueGapCost, targetLength); return Math.min(totChangeCost, blowAwayCost); }
[ "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", ")", ";", "// Compute maximum cost of changing one string into another. If the", "// lengths differ, you'll need maxLen - minLen insertions or deletions.", "int", "totChangeCost", "=", "scriptCost", "(", "openGapCost", ",", "continueGapCost", ",", "maxLen", "-", "minLen", ")", "+", "minLen", "*", "changeCost", ";", "// Another possibility is to just delete the entire source and insert the", "// target, and not do any changes.", "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
[ "Return", "the", "worst", "case", "edit", "distance", "between", "strings", "of", "this", "length" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/names/NeedlemanWunschEditDistance.java#L161-L179
21,652
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/LambdaFunctionalInterface.java
LambdaFunctionalInterface.matchMethod
@Override public Description matchMethod(MethodTree tree, VisitorState state) { MethodSymbol methodSym = ASTHelpers.getSymbol(tree); // precondition (1) 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()); // preconditions (2) and (3) 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()); }
java
@Override public Description matchMethod(MethodTree tree, VisitorState state) { MethodSymbol methodSym = ASTHelpers.getSymbol(tree); // precondition (1) 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()); // preconditions (2) and (3) 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()); }
[ "@", "Override", "public", "Description", "matchMethod", "(", "MethodTree", "tree", ",", "VisitorState", "state", ")", "{", "MethodSymbol", "methodSym", "=", "ASTHelpers", ".", "getSymbol", "(", "tree", ")", ";", "// precondition (1)", "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", "(", ")", ")", ";", "// preconditions (2) and (3)", "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. <pre>PreConditions: (1): The method declaration has to be private (to do a safe refactoring) (2): Its parameters have to meet the following conditions: 2.1 Contain type java.util.function.Function 2.2 At least one argument type of the Function must be subtype of Number (3): All its invocations in the top-level enclosing class have to meet the following conditions as well: 3.1: lambda argument of Kind.LAMBDA_EXPRESSION 3.2: same as 2.1 3.3: same as 2.2 </pre> <pre> Refactoring Changes for matched methods: (1) Add the imports (2) Change the method signature to use utility function instead of Function (3) Find and change the 'apply' calls to the corresponding applyAsT </pre>
[ "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", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/LambdaFunctionalInterface.java#L145-L185
21,653
google/error-prone
check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScannerTransformer.java
ErrorProneScannerTransformer.createVisitorState
private VisitorState createVisitorState(Context context, DescriptionListener listener) { ErrorProneOptions options = requireNonNull(context.get(ErrorProneOptions.class)); return VisitorState.createConfiguredForCompilation( context, listener, scanner().severityMap(), options); }
java
private VisitorState createVisitorState(Context context, DescriptionListener listener) { ErrorProneOptions options = requireNonNull(context.get(ErrorProneOptions.class)); return VisitorState.createConfiguredForCompilation( context, listener, scanner().severityMap(), options); }
[ "private", "VisitorState", "createVisitorState", "(", "Context", "context", ",", "DescriptionListener", "listener", ")", "{", "ErrorProneOptions", "options", "=", "requireNonNull", "(", "context", ".", "get", "(", "ErrorProneOptions", ".", "class", ")", ")", ";", "return", "VisitorState", ".", "createConfiguredForCompilation", "(", "context", ",", "listener", ",", "scanner", "(", ")", ".", "severityMap", "(", ")", ",", "options", ")", ";", "}" ]
Create a VisitorState object from a compilation unit.
[ "Create", "a", "VisitorState", "object", "from", "a", "compilation", "unit", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScannerTransformer.java#L52-L56
21,654
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/OrphanedFormatString.java
OrphanedFormatString.missingFormatArgs
private static boolean missingFormatArgs(String value) { try { Formatter.check(value); } catch (MissingFormatArgumentException e) { return true; } catch (Exception ignored) { // we don't care about other errors (it isn't supposed to be a format string) } return false; }
java
private static boolean missingFormatArgs(String value) { try { Formatter.check(value); } catch (MissingFormatArgumentException e) { return true; } catch (Exception ignored) { // we don't care about other errors (it isn't supposed to be a format string) } return false; }
[ "private", "static", "boolean", "missingFormatArgs", "(", "String", "value", ")", "{", "try", "{", "Formatter", ".", "check", "(", "value", ")", ";", "}", "catch", "(", "MissingFormatArgumentException", "e", ")", "{", "return", "true", ";", "}", "catch", "(", "Exception", "ignored", ")", "{", "// we don't care about other errors (it isn't supposed to be a format string)", "}", "return", "false", ";", "}" ]
Returns true for strings that contain format specifiers.
[ "Returns", "true", "for", "strings", "that", "contain", "format", "specifiers", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/OrphanedFormatString.java#L139-L148
21,655
google/error-prone
check_api/src/main/java/com/google/errorprone/JavacErrorDescriptionListener.java
JavacErrorDescriptionListener.shouldSkipImportTreeFix
private static boolean shouldSkipImportTreeFix(DiagnosticPosition position, Fix f) { if (position.getTree() != null && position.getTree().getKind() != Kind.IMPORT) { return false; } return !f.getImportsToAdd().isEmpty() || !f.getImportsToRemove().isEmpty(); }
java
private static boolean shouldSkipImportTreeFix(DiagnosticPosition position, Fix f) { if (position.getTree() != null && position.getTree().getKind() != Kind.IMPORT) { return false; } return !f.getImportsToAdd().isEmpty() || !f.getImportsToRemove().isEmpty(); }
[ "private", "static", "boolean", "shouldSkipImportTreeFix", "(", "DiagnosticPosition", "position", ",", "Fix", "f", ")", "{", "if", "(", "position", ".", "getTree", "(", ")", "!=", "null", "&&", "position", ".", "getTree", "(", ")", ".", "getKind", "(", ")", "!=", "Kind", ".", "IMPORT", ")", "{", "return", "false", ";", "}", "return", "!", "f", ".", "getImportsToAdd", "(", ")", ".", "isEmpty", "(", ")", "||", "!", "f", ".", "getImportsToRemove", "(", ")", ".", "isEmpty", "(", ")", ";", "}" ]
be fixed if they were specified via SuggestedFix.replace, for example.
[ "be", "fixed", "if", "they", "were", "specified", "via", "SuggestedFix", ".", "replace", "for", "example", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/JavacErrorDescriptionListener.java#L119-L125
21,656
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/android/MislabeledAndroidString.java
MislabeledAndroidString.matchMemberSelect
@Override public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) { Symbol symbol = ASTHelpers.getSymbol(tree); // Match symbol's owner to android.R.string separately because couldn't get fully qualified // "android.R.string.yes" out of symbol, just "yes" if (symbol == null || symbol.owner == null || symbol.getKind() != ElementKind.FIELD || !symbol.isStatic() || !R_STRING_CLASSNAME.contentEquals(symbol.owner.getQualifiedName())) { return Description.NO_MATCH; } String misleading = symbol.getSimpleName().toString(); String preferred = MISLEADING.get(misleading); if (preferred == null) { return Description.NO_MATCH; } return buildDescription(tree) .setMessage( String.format( "%s.%s is not \"%s\" but \"%s\"; prefer %s.%s for clarity", R_STRING_CLASSNAME, misleading, ASSUMED_MEANINGS.get(misleading), ASSUMED_MEANINGS.get(preferred), R_STRING_CLASSNAME, preferred)) // Keep the way tree refers to android.R.string as it is but replace the identifier .addFix( SuggestedFix.replace( tree, state.getSourceForNode(tree.getExpression()) + "." + preferred)) .build(); }
java
@Override public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) { Symbol symbol = ASTHelpers.getSymbol(tree); // Match symbol's owner to android.R.string separately because couldn't get fully qualified // "android.R.string.yes" out of symbol, just "yes" if (symbol == null || symbol.owner == null || symbol.getKind() != ElementKind.FIELD || !symbol.isStatic() || !R_STRING_CLASSNAME.contentEquals(symbol.owner.getQualifiedName())) { return Description.NO_MATCH; } String misleading = symbol.getSimpleName().toString(); String preferred = MISLEADING.get(misleading); if (preferred == null) { return Description.NO_MATCH; } return buildDescription(tree) .setMessage( String.format( "%s.%s is not \"%s\" but \"%s\"; prefer %s.%s for clarity", R_STRING_CLASSNAME, misleading, ASSUMED_MEANINGS.get(misleading), ASSUMED_MEANINGS.get(preferred), R_STRING_CLASSNAME, preferred)) // Keep the way tree refers to android.R.string as it is but replace the identifier .addFix( SuggestedFix.replace( tree, state.getSourceForNode(tree.getExpression()) + "." + preferred)) .build(); }
[ "@", "Override", "public", "Description", "matchMemberSelect", "(", "MemberSelectTree", "tree", ",", "VisitorState", "state", ")", "{", "Symbol", "symbol", "=", "ASTHelpers", ".", "getSymbol", "(", "tree", ")", ";", "// Match symbol's owner to android.R.string separately because couldn't get fully qualified", "// \"android.R.string.yes\" out of symbol, just \"yes\"", "if", "(", "symbol", "==", "null", "||", "symbol", ".", "owner", "==", "null", "||", "symbol", ".", "getKind", "(", ")", "!=", "ElementKind", ".", "FIELD", "||", "!", "symbol", ".", "isStatic", "(", ")", "||", "!", "R_STRING_CLASSNAME", ".", "contentEquals", "(", "symbol", ".", "owner", ".", "getQualifiedName", "(", ")", ")", ")", "{", "return", "Description", ".", "NO_MATCH", ";", "}", "String", "misleading", "=", "symbol", ".", "getSimpleName", "(", ")", ".", "toString", "(", ")", ";", "String", "preferred", "=", "MISLEADING", ".", "get", "(", "misleading", ")", ";", "if", "(", "preferred", "==", "null", ")", "{", "return", "Description", ".", "NO_MATCH", ";", "}", "return", "buildDescription", "(", "tree", ")", ".", "setMessage", "(", "String", ".", "format", "(", "\"%s.%s is not \\\"%s\\\" but \\\"%s\\\"; prefer %s.%s for clarity\"", ",", "R_STRING_CLASSNAME", ",", "misleading", ",", "ASSUMED_MEANINGS", ".", "get", "(", "misleading", ")", ",", "ASSUMED_MEANINGS", ".", "get", "(", "preferred", ")", ",", "R_STRING_CLASSNAME", ",", "preferred", ")", ")", "// Keep the way tree refers to android.R.string as it is but replace the identifier", ".", "addFix", "(", "SuggestedFix", ".", "replace", "(", "tree", ",", "state", ".", "getSourceForNode", "(", "tree", ".", "getExpression", "(", ")", ")", "+", "\".\"", "+", "preferred", ")", ")", ".", "build", "(", ")", ";", "}" ]
assumed and actual meaning
[ "assumed", "and", "actual", "meaning" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/android/MislabeledAndroidString.java#L65-L97
21,657
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java
ThreadSafety.isTypeParameterThreadSafe
private boolean isTypeParameterThreadSafe( TypeVariableSymbol symbol, Set<String> containerTypeParameters) { if (!recursiveThreadSafeTypeParameter.add(symbol)) { return true; } // TODO(b/77695285): Prevent type variables that are immutable because of an immutable upper // bound to be marked thread-safe via containerOf or typeParameterAnnotation. try { for (Type bound : symbol.getBounds()) { if (!isThreadSafeType(true, containerTypeParameters, bound).isPresent()) { // A type variable is thread-safe if any upper bound is thread-safe. return true; } } return hasThreadSafeTypeParameterAnnotation(symbol); } finally { recursiveThreadSafeTypeParameter.remove(symbol); } }
java
private boolean isTypeParameterThreadSafe( TypeVariableSymbol symbol, Set<String> containerTypeParameters) { if (!recursiveThreadSafeTypeParameter.add(symbol)) { return true; } // TODO(b/77695285): Prevent type variables that are immutable because of an immutable upper // bound to be marked thread-safe via containerOf or typeParameterAnnotation. try { for (Type bound : symbol.getBounds()) { if (!isThreadSafeType(true, containerTypeParameters, bound).isPresent()) { // A type variable is thread-safe if any upper bound is thread-safe. return true; } } return hasThreadSafeTypeParameterAnnotation(symbol); } finally { recursiveThreadSafeTypeParameter.remove(symbol); } }
[ "private", "boolean", "isTypeParameterThreadSafe", "(", "TypeVariableSymbol", "symbol", ",", "Set", "<", "String", ">", "containerTypeParameters", ")", "{", "if", "(", "!", "recursiveThreadSafeTypeParameter", ".", "add", "(", "symbol", ")", ")", "{", "return", "true", ";", "}", "// TODO(b/77695285): Prevent type variables that are immutable because of an immutable upper", "// bound to be marked thread-safe via containerOf or typeParameterAnnotation.", "try", "{", "for", "(", "Type", "bound", ":", "symbol", ".", "getBounds", "(", ")", ")", "{", "if", "(", "!", "isThreadSafeType", "(", "true", ",", "containerTypeParameters", ",", "bound", ")", ".", "isPresent", "(", ")", ")", "{", "// A type variable is thread-safe if any upper bound is thread-safe.", "return", "true", ";", "}", "}", "return", "hasThreadSafeTypeParameterAnnotation", "(", "symbol", ")", ";", "}", "finally", "{", "recursiveThreadSafeTypeParameter", ".", "remove", "(", "symbol", ")", ";", "}", "}" ]
Returns whether a type parameter is thread-safe. <p>This is true if either the type parameter's declaration is annotated with {@link #typeParameterAnnotation} (indicating it can only be instantiated with thread-safe types), or the type parameter has a thread-safe upper bound (sub-classes of thread-safe types are also thread-safe). <p>If a type has a recursive bound, we recursively assume that this type satisfies all thread-safety constraints. Recursion can only happen with type variables that have recursive type bounds. These type variables do not need to be called out in the "containerOf" attribute or annotated with {@link #typeParameterAnnotation}. <p>Recursion does not apply to other kinds of types because all declared types must be annotated thread-safe, which means that thread-safety checkers don't need to analyze all referenced types recursively.
[ "Returns", "whether", "a", "type", "parameter", "is", "thread", "-", "safe", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java#L627-L645
21,658
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java
ThreadSafety.mutableEnclosingInstance
public Type mutableEnclosingInstance(Optional<ClassTree> tree, ClassType type) { if (tree.isPresent() && !CanBeStaticAnalyzer.referencesOuter( tree.get(), ASTHelpers.getSymbol(tree.get()), state)) { return null; } Type enclosing = type.getEnclosingType(); while (!Type.noType.equals(enclosing)) { if (getMarkerOrAcceptedAnnotation(enclosing.tsym, state) == null && isThreadSafeType( /* allowContainerTypeParameters= */ false, /* containerTypeParameters= */ ImmutableSet.of(), enclosing) .isPresent()) { return enclosing; } enclosing = enclosing.getEnclosingType(); } return null; }
java
public Type mutableEnclosingInstance(Optional<ClassTree> tree, ClassType type) { if (tree.isPresent() && !CanBeStaticAnalyzer.referencesOuter( tree.get(), ASTHelpers.getSymbol(tree.get()), state)) { return null; } Type enclosing = type.getEnclosingType(); while (!Type.noType.equals(enclosing)) { if (getMarkerOrAcceptedAnnotation(enclosing.tsym, state) == null && isThreadSafeType( /* allowContainerTypeParameters= */ false, /* containerTypeParameters= */ ImmutableSet.of(), enclosing) .isPresent()) { return enclosing; } enclosing = enclosing.getEnclosingType(); } return null; }
[ "public", "Type", "mutableEnclosingInstance", "(", "Optional", "<", "ClassTree", ">", "tree", ",", "ClassType", "type", ")", "{", "if", "(", "tree", ".", "isPresent", "(", ")", "&&", "!", "CanBeStaticAnalyzer", ".", "referencesOuter", "(", "tree", ".", "get", "(", ")", ",", "ASTHelpers", ".", "getSymbol", "(", "tree", ".", "get", "(", ")", ")", ",", "state", ")", ")", "{", "return", "null", ";", "}", "Type", "enclosing", "=", "type", ".", "getEnclosingType", "(", ")", ";", "while", "(", "!", "Type", ".", "noType", ".", "equals", "(", "enclosing", ")", ")", "{", "if", "(", "getMarkerOrAcceptedAnnotation", "(", "enclosing", ".", "tsym", ",", "state", ")", "==", "null", "&&", "isThreadSafeType", "(", "/* allowContainerTypeParameters= */", "false", ",", "/* containerTypeParameters= */", "ImmutableSet", ".", "of", "(", ")", ",", "enclosing", ")", ".", "isPresent", "(", ")", ")", "{", "return", "enclosing", ";", "}", "enclosing", "=", "enclosing", ".", "getEnclosingType", "(", ")", ";", "}", "return", "null", ";", "}" ]
Returns an enclosing instance for the specified type if it is thread-safe.
[ "Returns", "an", "enclosing", "instance", "for", "the", "specified", "type", "if", "it", "is", "thread", "-", "safe", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java#L662-L681
21,659
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java
ThreadSafety.threadSafeTypeParametersInScope
public Set<String> threadSafeTypeParametersInScope(Symbol sym) { if (sym == null) { return ImmutableSet.of(); } ImmutableSet.Builder<String> result = ImmutableSet.builder(); OUTER: for (Symbol s = sym; s.owner != null; s = s.owner) { switch (s.getKind()) { case INSTANCE_INIT: continue; case PACKAGE: break OUTER; default: break; } AnnotationInfo annotation = getMarkerOrAcceptedAnnotation(s, state); if (annotation == null) { continue; } for (TypeVariableSymbol typaram : s.getTypeParameters()) { String name = typaram.getSimpleName().toString(); if (annotation.containerOf().contains(name)) { result.add(name); } } if (s.isStatic()) { break; } } return result.build(); }
java
public Set<String> threadSafeTypeParametersInScope(Symbol sym) { if (sym == null) { return ImmutableSet.of(); } ImmutableSet.Builder<String> result = ImmutableSet.builder(); OUTER: for (Symbol s = sym; s.owner != null; s = s.owner) { switch (s.getKind()) { case INSTANCE_INIT: continue; case PACKAGE: break OUTER; default: break; } AnnotationInfo annotation = getMarkerOrAcceptedAnnotation(s, state); if (annotation == null) { continue; } for (TypeVariableSymbol typaram : s.getTypeParameters()) { String name = typaram.getSimpleName().toString(); if (annotation.containerOf().contains(name)) { result.add(name); } } if (s.isStatic()) { break; } } return result.build(); }
[ "public", "Set", "<", "String", ">", "threadSafeTypeParametersInScope", "(", "Symbol", "sym", ")", "{", "if", "(", "sym", "==", "null", ")", "{", "return", "ImmutableSet", ".", "of", "(", ")", ";", "}", "ImmutableSet", ".", "Builder", "<", "String", ">", "result", "=", "ImmutableSet", ".", "builder", "(", ")", ";", "OUTER", ":", "for", "(", "Symbol", "s", "=", "sym", ";", "s", ".", "owner", "!=", "null", ";", "s", "=", "s", ".", "owner", ")", "{", "switch", "(", "s", ".", "getKind", "(", ")", ")", "{", "case", "INSTANCE_INIT", ":", "continue", ";", "case", "PACKAGE", ":", "break", "OUTER", ";", "default", ":", "break", ";", "}", "AnnotationInfo", "annotation", "=", "getMarkerOrAcceptedAnnotation", "(", "s", ",", "state", ")", ";", "if", "(", "annotation", "==", "null", ")", "{", "continue", ";", "}", "for", "(", "TypeVariableSymbol", "typaram", ":", "s", ".", "getTypeParameters", "(", ")", ")", "{", "String", "name", "=", "typaram", ".", "getSimpleName", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "annotation", ".", "containerOf", "(", ")", ".", "contains", "(", "name", ")", ")", "{", "result", ".", "add", "(", "name", ")", ";", "}", "}", "if", "(", "s", ".", "isStatic", "(", ")", ")", "{", "break", ";", "}", "}", "return", "result", ".", "build", "(", ")", ";", "}" ]
Gets the set of in-scope threadsafe type parameters from the containerOf specs on annotations. <p>Usually only the immediately enclosing declaration is searched, but it's possible to have cases like: <pre> {@literal @}MarkerAnnotation(containerOf="T") class C&lt;T&gt; { class Inner extends ThreadSafeCollection&lt;T&gt; {} } </pre>
[ "Gets", "the", "set", "of", "in", "-", "scope", "threadsafe", "type", "parameters", "from", "the", "containerOf", "specs", "on", "annotations", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java#L695-L725
21,660
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java
ThreadSafety.getInheritedAnnotation
public AnnotationInfo getInheritedAnnotation(Symbol sym, VisitorState state) { return getAnnotation(sym, markerAnnotations, state); }
java
public AnnotationInfo getInheritedAnnotation(Symbol sym, VisitorState state) { return getAnnotation(sym, markerAnnotations, state); }
[ "public", "AnnotationInfo", "getInheritedAnnotation", "(", "Symbol", "sym", ",", "VisitorState", "state", ")", "{", "return", "getAnnotation", "(", "sym", ",", "markerAnnotations", ",", "state", ")", ";", "}" ]
Gets the possibly inherited marker annotation on the given symbol, and reverse-propagates containerOf spec's from super-classes.
[ "Gets", "the", "possibly", "inherited", "marker", "annotation", "on", "the", "given", "symbol", "and", "reverse", "-", "propagates", "containerOf", "spec", "s", "from", "super", "-", "classes", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java#L796-L798
21,661
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java
ThreadSafety.checkInstantiation
public Violation checkInstantiation( Collection<TypeVariableSymbol> typeParameters, Collection<Type> typeArguments) { return Streams.zip( typeParameters.stream(), typeArguments.stream(), (sym, type) -> { if (!hasThreadSafeTypeParameterAnnotation(sym)) { return Violation.absent(); } Violation info = isThreadSafeType( /* allowContainerTypeParameters= */ true, /* containerTypeParameters= */ ImmutableSet.of(), type); if (!info.isPresent()) { return Violation.absent(); } return info.plus( String.format( "instantiation of '%s' is %s", sym, purpose.mutableOrNotThreadSafe())); }) .filter(Violation::isPresent) .findFirst() .orElse(Violation.absent()); }
java
public Violation checkInstantiation( Collection<TypeVariableSymbol> typeParameters, Collection<Type> typeArguments) { return Streams.zip( typeParameters.stream(), typeArguments.stream(), (sym, type) -> { if (!hasThreadSafeTypeParameterAnnotation(sym)) { return Violation.absent(); } Violation info = isThreadSafeType( /* allowContainerTypeParameters= */ true, /* containerTypeParameters= */ ImmutableSet.of(), type); if (!info.isPresent()) { return Violation.absent(); } return info.plus( String.format( "instantiation of '%s' is %s", sym, purpose.mutableOrNotThreadSafe())); }) .filter(Violation::isPresent) .findFirst() .orElse(Violation.absent()); }
[ "public", "Violation", "checkInstantiation", "(", "Collection", "<", "TypeVariableSymbol", ">", "typeParameters", ",", "Collection", "<", "Type", ">", "typeArguments", ")", "{", "return", "Streams", ".", "zip", "(", "typeParameters", ".", "stream", "(", ")", ",", "typeArguments", ".", "stream", "(", ")", ",", "(", "sym", ",", "type", ")", "->", "{", "if", "(", "!", "hasThreadSafeTypeParameterAnnotation", "(", "sym", ")", ")", "{", "return", "Violation", ".", "absent", "(", ")", ";", "}", "Violation", "info", "=", "isThreadSafeType", "(", "/* allowContainerTypeParameters= */", "true", ",", "/* containerTypeParameters= */", "ImmutableSet", ".", "of", "(", ")", ",", "type", ")", ";", "if", "(", "!", "info", ".", "isPresent", "(", ")", ")", "{", "return", "Violation", ".", "absent", "(", ")", ";", "}", "return", "info", ".", "plus", "(", "String", ".", "format", "(", "\"instantiation of '%s' is %s\"", ",", "sym", ",", "purpose", ".", "mutableOrNotThreadSafe", "(", ")", ")", ")", ";", "}", ")", ".", "filter", "(", "Violation", "::", "isPresent", ")", ".", "findFirst", "(", ")", ".", "orElse", "(", "Violation", ".", "absent", "(", ")", ")", ";", "}" ]
Checks that any thread-safe type parameters are instantiated with thread-safe types.
[ "Checks", "that", "any", "thread", "-", "safe", "type", "parameters", "are", "instantiated", "with", "thread", "-", "safe", "types", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java#L846-L870
21,662
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java
ThreadSafety.checkInvocation
public Violation checkInvocation(Type methodType, Symbol symbol) { if (methodType == null) { return Violation.absent(); } List<TypeVariableSymbol> typeParameters = symbol.getTypeParameters(); if (typeParameters.stream().noneMatch(this::hasThreadSafeTypeParameterAnnotation)) { // fast path return Violation.absent(); } ImmutableMap<TypeVariableSymbol, Type> instantiation = getInstantiation(state.getTypes(), methodType); // javac does not instantiate all types, so filter out ones that were not instantiated. Ideally // we wouldn't have to do this. typeParameters = typeParameters.stream().filter(instantiation::containsKey).collect(toImmutableList()); return checkInstantiation( typeParameters, typeParameters.stream().map(instantiation::get).collect(toImmutableList())); }
java
public Violation checkInvocation(Type methodType, Symbol symbol) { if (methodType == null) { return Violation.absent(); } List<TypeVariableSymbol> typeParameters = symbol.getTypeParameters(); if (typeParameters.stream().noneMatch(this::hasThreadSafeTypeParameterAnnotation)) { // fast path return Violation.absent(); } ImmutableMap<TypeVariableSymbol, Type> instantiation = getInstantiation(state.getTypes(), methodType); // javac does not instantiate all types, so filter out ones that were not instantiated. Ideally // we wouldn't have to do this. typeParameters = typeParameters.stream().filter(instantiation::containsKey).collect(toImmutableList()); return checkInstantiation( typeParameters, typeParameters.stream().map(instantiation::get).collect(toImmutableList())); }
[ "public", "Violation", "checkInvocation", "(", "Type", "methodType", ",", "Symbol", "symbol", ")", "{", "if", "(", "methodType", "==", "null", ")", "{", "return", "Violation", ".", "absent", "(", ")", ";", "}", "List", "<", "TypeVariableSymbol", ">", "typeParameters", "=", "symbol", ".", "getTypeParameters", "(", ")", ";", "if", "(", "typeParameters", ".", "stream", "(", ")", ".", "noneMatch", "(", "this", "::", "hasThreadSafeTypeParameterAnnotation", ")", ")", "{", "// fast path", "return", "Violation", ".", "absent", "(", ")", ";", "}", "ImmutableMap", "<", "TypeVariableSymbol", ",", "Type", ">", "instantiation", "=", "getInstantiation", "(", "state", ".", "getTypes", "(", ")", ",", "methodType", ")", ";", "// javac does not instantiate all types, so filter out ones that were not instantiated. Ideally", "// we wouldn't have to do this.", "typeParameters", "=", "typeParameters", ".", "stream", "(", ")", ".", "filter", "(", "instantiation", "::", "containsKey", ")", ".", "collect", "(", "toImmutableList", "(", ")", ")", ";", "return", "checkInstantiation", "(", "typeParameters", ",", "typeParameters", ".", "stream", "(", ")", ".", "map", "(", "instantiation", "::", "get", ")", ".", "collect", "(", "toImmutableList", "(", ")", ")", ")", ";", "}" ]
Checks the instantiation of any thread-safe type parameters in the current invocation.
[ "Checks", "the", "instantiation", "of", "any", "thread", "-", "safe", "type", "parameters", "in", "the", "current", "invocation", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafety.java#L873-L892
21,663
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/DoubleCheckedLocking.java
DoubleCheckedLocking.isImmutable
private static boolean isImmutable(Type type, VisitorState state) { switch (type.getKind()) { case BOOLEAN: case BYTE: case SHORT: case INT: case CHAR: case FLOAT: return true; case LONG: case DOUBLE: // double-width primitives aren't written atomically return true; default: break; } return IMMUTABLE_WHITELIST.contains( state.getTypes().erasure(type).tsym.getQualifiedName().toString()); }
java
private static boolean isImmutable(Type type, VisitorState state) { switch (type.getKind()) { case BOOLEAN: case BYTE: case SHORT: case INT: case CHAR: case FLOAT: return true; case LONG: case DOUBLE: // double-width primitives aren't written atomically return true; default: break; } return IMMUTABLE_WHITELIST.contains( state.getTypes().erasure(type).tsym.getQualifiedName().toString()); }
[ "private", "static", "boolean", "isImmutable", "(", "Type", "type", ",", "VisitorState", "state", ")", "{", "switch", "(", "type", ".", "getKind", "(", ")", ")", "{", "case", "BOOLEAN", ":", "case", "BYTE", ":", "case", "SHORT", ":", "case", "INT", ":", "case", "CHAR", ":", "case", "FLOAT", ":", "return", "true", ";", "case", "LONG", ":", "case", "DOUBLE", ":", "// double-width primitives aren't written atomically", "return", "true", ";", "default", ":", "break", ";", "}", "return", "IMMUTABLE_WHITELIST", ".", "contains", "(", "state", ".", "getTypes", "(", ")", ".", "erasure", "(", "type", ")", ".", "tsym", ".", "getQualifiedName", "(", ")", ".", "toString", "(", ")", ")", ";", "}" ]
Recognize a small set of known-immutable types that are safe for DCL even without a volatile field.
[ "Recognize", "a", "small", "set", "of", "known", "-", "immutable", "types", "that", "are", "safe", "for", "DCL", "even", "without", "a", "volatile", "field", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/DoubleCheckedLocking.java#L116-L134
21,664
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/DoubleCheckedLocking.java
DoubleCheckedLocking.handleLocal
private Description handleLocal(DCLInfo info, VisitorState state) { JCExpressionStatement expr = getChild(info.synchTree().getBlock(), JCExpressionStatement.class); if (expr == null) { return Description.NO_MATCH; } if (expr.getStartPosition() > ((JCTree) info.innerIf()).getStartPosition()) { return Description.NO_MATCH; } if (!(expr.getExpression() instanceof JCAssign)) { return Description.NO_MATCH; } JCAssign assign = (JCAssign) expr.getExpression(); if (!Objects.equals(ASTHelpers.getSymbol(assign.getVariable()), info.sym())) { return Description.NO_MATCH; } Symbol sym = ASTHelpers.getSymbol(assign.getExpression()); if (!(sym instanceof VarSymbol)) { return Description.NO_MATCH; } VarSymbol fvar = (VarSymbol) sym; if (fvar.getKind() != ElementKind.FIELD) { return Description.NO_MATCH; } return handleField(info.outerIf(), fvar, state); }
java
private Description handleLocal(DCLInfo info, VisitorState state) { JCExpressionStatement expr = getChild(info.synchTree().getBlock(), JCExpressionStatement.class); if (expr == null) { return Description.NO_MATCH; } if (expr.getStartPosition() > ((JCTree) info.innerIf()).getStartPosition()) { return Description.NO_MATCH; } if (!(expr.getExpression() instanceof JCAssign)) { return Description.NO_MATCH; } JCAssign assign = (JCAssign) expr.getExpression(); if (!Objects.equals(ASTHelpers.getSymbol(assign.getVariable()), info.sym())) { return Description.NO_MATCH; } Symbol sym = ASTHelpers.getSymbol(assign.getExpression()); if (!(sym instanceof VarSymbol)) { return Description.NO_MATCH; } VarSymbol fvar = (VarSymbol) sym; if (fvar.getKind() != ElementKind.FIELD) { return Description.NO_MATCH; } return handleField(info.outerIf(), fvar, state); }
[ "private", "Description", "handleLocal", "(", "DCLInfo", "info", ",", "VisitorState", "state", ")", "{", "JCExpressionStatement", "expr", "=", "getChild", "(", "info", ".", "synchTree", "(", ")", ".", "getBlock", "(", ")", ",", "JCExpressionStatement", ".", "class", ")", ";", "if", "(", "expr", "==", "null", ")", "{", "return", "Description", ".", "NO_MATCH", ";", "}", "if", "(", "expr", ".", "getStartPosition", "(", ")", ">", "(", "(", "JCTree", ")", "info", ".", "innerIf", "(", ")", ")", ".", "getStartPosition", "(", ")", ")", "{", "return", "Description", ".", "NO_MATCH", ";", "}", "if", "(", "!", "(", "expr", ".", "getExpression", "(", ")", "instanceof", "JCAssign", ")", ")", "{", "return", "Description", ".", "NO_MATCH", ";", "}", "JCAssign", "assign", "=", "(", "JCAssign", ")", "expr", ".", "getExpression", "(", ")", ";", "if", "(", "!", "Objects", ".", "equals", "(", "ASTHelpers", ".", "getSymbol", "(", "assign", ".", "getVariable", "(", ")", ")", ",", "info", ".", "sym", "(", ")", ")", ")", "{", "return", "Description", ".", "NO_MATCH", ";", "}", "Symbol", "sym", "=", "ASTHelpers", ".", "getSymbol", "(", "assign", ".", "getExpression", "(", ")", ")", ";", "if", "(", "!", "(", "sym", "instanceof", "VarSymbol", ")", ")", "{", "return", "Description", ".", "NO_MATCH", ";", "}", "VarSymbol", "fvar", "=", "(", "VarSymbol", ")", "sym", ";", "if", "(", "fvar", ".", "getKind", "(", ")", "!=", "ElementKind", ".", "FIELD", ")", "{", "return", "Description", ".", "NO_MATCH", ";", "}", "return", "handleField", "(", "info", ".", "outerIf", "(", ")", ",", "fvar", ",", "state", ")", ";", "}" ]
Report a diagnostic for an instance of DCL on a local variable. A match is only reported if a non-volatile field is written to the variable after acquiring the lock and before the second null-check on the local. <p>e.g. <pre>{@code if ($X == null) { synchronized (...) { $X = myNonVolatileField; if ($X == null) { ... } ... } } }</pre>
[ "Report", "a", "diagnostic", "for", "an", "instance", "of", "DCL", "on", "a", "local", "variable", ".", "A", "match", "is", "only", "reported", "if", "a", "non", "-", "volatile", "field", "is", "written", "to", "the", "variable", "after", "acquiring", "the", "lock", "and", "before", "the", "second", "null", "-", "check", "on", "the", "local", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/DoubleCheckedLocking.java#L155-L179
21,665
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/DoubleCheckedLocking.java
DoubleCheckedLocking.findFieldDeclaration
@Nullable private static JCTree findFieldDeclaration(TreePath path, VarSymbol var) { for (TreePath curr = path; curr != null; curr = curr.getParentPath()) { Tree leaf = curr.getLeaf(); if (!(leaf instanceof JCClassDecl)) { continue; } for (JCTree tree : ((JCClassDecl) leaf).getMembers()) { if (Objects.equals(var, ASTHelpers.getSymbol(tree))) { return tree; } } } return null; }
java
@Nullable private static JCTree findFieldDeclaration(TreePath path, VarSymbol var) { for (TreePath curr = path; curr != null; curr = curr.getParentPath()) { Tree leaf = curr.getLeaf(); if (!(leaf instanceof JCClassDecl)) { continue; } for (JCTree tree : ((JCClassDecl) leaf).getMembers()) { if (Objects.equals(var, ASTHelpers.getSymbol(tree))) { return tree; } } } return null; }
[ "@", "Nullable", "private", "static", "JCTree", "findFieldDeclaration", "(", "TreePath", "path", ",", "VarSymbol", "var", ")", "{", "for", "(", "TreePath", "curr", "=", "path", ";", "curr", "!=", "null", ";", "curr", "=", "curr", ".", "getParentPath", "(", ")", ")", "{", "Tree", "leaf", "=", "curr", ".", "getLeaf", "(", ")", ";", "if", "(", "!", "(", "leaf", "instanceof", "JCClassDecl", ")", ")", "{", "continue", ";", "}", "for", "(", "JCTree", "tree", ":", "(", "(", "JCClassDecl", ")", "leaf", ")", ".", "getMembers", "(", ")", ")", "{", "if", "(", "Objects", ".", "equals", "(", "var", ",", "ASTHelpers", ".", "getSymbol", "(", "tree", ")", ")", ")", "{", "return", "tree", ";", "}", "}", "}", "return", "null", ";", "}" ]
Performs a best-effort search for the AST node of a field declaration. <p>It will only find fields declared in a lexically enclosing scope of the current location. Since double-checked locking should always be used on a private field, this should be reasonably effective.
[ "Performs", "a", "best", "-", "effort", "search", "for", "the", "AST", "node", "of", "a", "field", "declaration", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/DoubleCheckedLocking.java#L309-L323
21,666
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/BadComparable.java
BadComparable.matches
private boolean matches(TypeCastTree tree, VisitorState state) { Type treeType = ASTHelpers.getType(tree.getType()); // If the cast isn't narrowing to an int then don't implicate it in the bug pattern. if (treeType.getTag() != TypeTag.INT) { return false; } // The expression should be a subtract but remove parentheses. ExpressionTree expression = ASTHelpers.stripParentheses(tree.getExpression()); if (expression.getKind() != Kind.MINUS) { return false; } // Ensure the expression type is wider and signed (ie a long) than the cast type ignoring // boxing. Type expressionType = getTypeOfSubtract((BinaryTree) expression, state); TypeTag expressionTypeTag = state.getTypes().unboxedTypeOrType(expressionType).getTag(); return (expressionTypeTag == TypeTag.LONG); }
java
private boolean matches(TypeCastTree tree, VisitorState state) { Type treeType = ASTHelpers.getType(tree.getType()); // If the cast isn't narrowing to an int then don't implicate it in the bug pattern. if (treeType.getTag() != TypeTag.INT) { return false; } // The expression should be a subtract but remove parentheses. ExpressionTree expression = ASTHelpers.stripParentheses(tree.getExpression()); if (expression.getKind() != Kind.MINUS) { return false; } // Ensure the expression type is wider and signed (ie a long) than the cast type ignoring // boxing. Type expressionType = getTypeOfSubtract((BinaryTree) expression, state); TypeTag expressionTypeTag = state.getTypes().unboxedTypeOrType(expressionType).getTag(); return (expressionTypeTag == TypeTag.LONG); }
[ "private", "boolean", "matches", "(", "TypeCastTree", "tree", ",", "VisitorState", "state", ")", "{", "Type", "treeType", "=", "ASTHelpers", ".", "getType", "(", "tree", ".", "getType", "(", ")", ")", ";", "// If the cast isn't narrowing to an int then don't implicate it in the bug pattern.", "if", "(", "treeType", ".", "getTag", "(", ")", "!=", "TypeTag", ".", "INT", ")", "{", "return", "false", ";", "}", "// The expression should be a subtract but remove parentheses.", "ExpressionTree", "expression", "=", "ASTHelpers", ".", "stripParentheses", "(", "tree", ".", "getExpression", "(", ")", ")", ";", "if", "(", "expression", ".", "getKind", "(", ")", "!=", "Kind", ".", "MINUS", ")", "{", "return", "false", ";", "}", "// Ensure the expression type is wider and signed (ie a long) than the cast type ignoring", "// boxing.", "Type", "expressionType", "=", "getTypeOfSubtract", "(", "(", "BinaryTree", ")", "expression", ",", "state", ")", ";", "TypeTag", "expressionTypeTag", "=", "state", ".", "getTypes", "(", ")", ".", "unboxedTypeOrType", "(", "expressionType", ")", ".", "getTag", "(", ")", ";", "return", "(", "expressionTypeTag", "==", "TypeTag", ".", "LONG", ")", ";", "}" ]
Matches if this is a narrowing integral cast between signed types where the expression is a subtract.
[ "Matches", "if", "this", "is", "a", "narrowing", "integral", "cast", "between", "signed", "types", "where", "the", "expression", "is", "a", "subtract", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/BadComparable.java#L96-L115
21,667
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/apidiff/ApiDiff.java
ApiDiff.isMemberUnsupported
boolean isMemberUnsupported(String className, ClassMemberKey memberKey) { return unsupportedMembersByClass().containsEntry(className, memberKey) || unsupportedMembersByClass() .containsEntry(className, ClassMemberKey.create(memberKey.identifier(), "")); }
java
boolean isMemberUnsupported(String className, ClassMemberKey memberKey) { return unsupportedMembersByClass().containsEntry(className, memberKey) || unsupportedMembersByClass() .containsEntry(className, ClassMemberKey.create(memberKey.identifier(), "")); }
[ "boolean", "isMemberUnsupported", "(", "String", "className", ",", "ClassMemberKey", "memberKey", ")", "{", "return", "unsupportedMembersByClass", "(", ")", ".", "containsEntry", "(", "className", ",", "memberKey", ")", "||", "unsupportedMembersByClass", "(", ")", ".", "containsEntry", "(", "className", ",", "ClassMemberKey", ".", "create", "(", "memberKey", ".", "identifier", "(", ")", ",", "\"\"", ")", ")", ";", "}" ]
Returns true if the member with the given declaring class is unsupported.
[ "Returns", "true", "if", "the", "member", "with", "the", "given", "declaring", "class", "is", "unsupported", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/apidiff/ApiDiff.java#L62-L66
21,668
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ReturnValueIgnored.java
ReturnValueIgnored.methodReturnsSameTypeAsReceiver
private static Matcher<ExpressionTree> methodReturnsSameTypeAsReceiver() { return new Matcher<ExpressionTree>() { @Override public boolean matches(ExpressionTree expressionTree, VisitorState state) { return isSameType( ASTHelpers.getReceiverType(expressionTree), ASTHelpers.getReturnType(expressionTree), state); } }; }
java
private static Matcher<ExpressionTree> methodReturnsSameTypeAsReceiver() { return new Matcher<ExpressionTree>() { @Override public boolean matches(ExpressionTree expressionTree, VisitorState state) { return isSameType( ASTHelpers.getReceiverType(expressionTree), ASTHelpers.getReturnType(expressionTree), state); } }; }
[ "private", "static", "Matcher", "<", "ExpressionTree", ">", "methodReturnsSameTypeAsReceiver", "(", ")", "{", "return", "new", "Matcher", "<", "ExpressionTree", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "ExpressionTree", "expressionTree", ",", "VisitorState", "state", ")", "{", "return", "isSameType", "(", "ASTHelpers", ".", "getReceiverType", "(", "expressionTree", ")", ",", "ASTHelpers", ".", "getReturnType", "(", "expressionTree", ")", ",", "state", ")", ";", "}", "}", ";", "}" ]
Matches method invocations that return the same type as the receiver object.
[ "Matches", "method", "invocations", "that", "return", "the", "same", "type", "as", "the", "receiver", "object", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/ReturnValueIgnored.java#L161-L171
21,669
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ReturnValueIgnored.java
ReturnValueIgnored.methodReceiverHasType
private static Matcher<ExpressionTree> methodReceiverHasType(final Set<String> typeSet) { return new Matcher<ExpressionTree>() { @Override public boolean matches(ExpressionTree expressionTree, VisitorState state) { Type receiverType = ASTHelpers.getReceiverType(expressionTree); return typeSet.contains(receiverType.toString()); } }; }
java
private static Matcher<ExpressionTree> methodReceiverHasType(final Set<String> typeSet) { return new Matcher<ExpressionTree>() { @Override public boolean matches(ExpressionTree expressionTree, VisitorState state) { Type receiverType = ASTHelpers.getReceiverType(expressionTree); return typeSet.contains(receiverType.toString()); } }; }
[ "private", "static", "Matcher", "<", "ExpressionTree", ">", "methodReceiverHasType", "(", "final", "Set", "<", "String", ">", "typeSet", ")", "{", "return", "new", "Matcher", "<", "ExpressionTree", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "ExpressionTree", "expressionTree", ",", "VisitorState", "state", ")", "{", "Type", "receiverType", "=", "ASTHelpers", ".", "getReceiverType", "(", "expressionTree", ")", ";", "return", "typeSet", ".", "contains", "(", "receiverType", ".", "toString", "(", ")", ")", ";", "}", "}", ";", "}" ]
Matches method calls whose receiver objects are of a type included in the set.
[ "Matches", "method", "calls", "whose", "receiver", "objects", "are", "of", "a", "type", "included", "in", "the", "set", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/ReturnValueIgnored.java#L174-L182
21,670
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/JdkObsolete.java
JdkObsolete.stringBufferFix
private static Optional<Fix> stringBufferFix(VisitorState state) { Tree tree = state.getPath().getLeaf(); // expect `new StringBuffer()` if (!(tree instanceof NewClassTree)) { return Optional.empty(); } // expect e.g. `StringBuffer sb = new StringBuffer();` NewClassTree newClassTree = (NewClassTree) tree; Tree parent = state.getPath().getParentPath().getLeaf(); if (!(parent instanceof VariableTree)) { return Optional.empty(); } VariableTree varTree = (VariableTree) parent; VarSymbol varSym = ASTHelpers.getSymbol(varTree); TreePath methodPath = findEnclosingMethod(state); if (methodPath == null) { return Optional.empty(); } // Expect all uses to be of the form `sb.<method>` (append, toString, etc.) // We don't want to refactor StringBuffers that escape the current method. // Use an array to get a boxed boolean that we can update in the anonymous class. boolean[] escape = {false}; new TreePathScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { if (varSym.equals(ASTHelpers.getSymbol(tree))) { Tree parent = getCurrentPath().getParentPath().getLeaf(); if (parent == varTree) { // the use of the variable in its declaration gets a pass return null; } // the LHS of a select (e.g. in `sb.append(...)`) does not escape if (!(parent instanceof MemberSelectTree) || ((MemberSelectTree) parent).getExpression() != tree) { escape[0] = true; } } return null; } }.scan(methodPath, null); if (escape[0]) { return Optional.empty(); } return Optional.of( SuggestedFix.builder() .replace(newClassTree.getIdentifier(), "StringBuilder") .replace(varTree.getType(), "StringBuilder") .build()); }
java
private static Optional<Fix> stringBufferFix(VisitorState state) { Tree tree = state.getPath().getLeaf(); // expect `new StringBuffer()` if (!(tree instanceof NewClassTree)) { return Optional.empty(); } // expect e.g. `StringBuffer sb = new StringBuffer();` NewClassTree newClassTree = (NewClassTree) tree; Tree parent = state.getPath().getParentPath().getLeaf(); if (!(parent instanceof VariableTree)) { return Optional.empty(); } VariableTree varTree = (VariableTree) parent; VarSymbol varSym = ASTHelpers.getSymbol(varTree); TreePath methodPath = findEnclosingMethod(state); if (methodPath == null) { return Optional.empty(); } // Expect all uses to be of the form `sb.<method>` (append, toString, etc.) // We don't want to refactor StringBuffers that escape the current method. // Use an array to get a boxed boolean that we can update in the anonymous class. boolean[] escape = {false}; new TreePathScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { if (varSym.equals(ASTHelpers.getSymbol(tree))) { Tree parent = getCurrentPath().getParentPath().getLeaf(); if (parent == varTree) { // the use of the variable in its declaration gets a pass return null; } // the LHS of a select (e.g. in `sb.append(...)`) does not escape if (!(parent instanceof MemberSelectTree) || ((MemberSelectTree) parent).getExpression() != tree) { escape[0] = true; } } return null; } }.scan(methodPath, null); if (escape[0]) { return Optional.empty(); } return Optional.of( SuggestedFix.builder() .replace(newClassTree.getIdentifier(), "StringBuilder") .replace(varTree.getType(), "StringBuilder") .build()); }
[ "private", "static", "Optional", "<", "Fix", ">", "stringBufferFix", "(", "VisitorState", "state", ")", "{", "Tree", "tree", "=", "state", ".", "getPath", "(", ")", ".", "getLeaf", "(", ")", ";", "// expect `new StringBuffer()`", "if", "(", "!", "(", "tree", "instanceof", "NewClassTree", ")", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "// expect e.g. `StringBuffer sb = new StringBuffer();`", "NewClassTree", "newClassTree", "=", "(", "NewClassTree", ")", "tree", ";", "Tree", "parent", "=", "state", ".", "getPath", "(", ")", ".", "getParentPath", "(", ")", ".", "getLeaf", "(", ")", ";", "if", "(", "!", "(", "parent", "instanceof", "VariableTree", ")", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "VariableTree", "varTree", "=", "(", "VariableTree", ")", "parent", ";", "VarSymbol", "varSym", "=", "ASTHelpers", ".", "getSymbol", "(", "varTree", ")", ";", "TreePath", "methodPath", "=", "findEnclosingMethod", "(", "state", ")", ";", "if", "(", "methodPath", "==", "null", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "// Expect all uses to be of the form `sb.<method>` (append, toString, etc.)", "// We don't want to refactor StringBuffers that escape the current method.", "// Use an array to get a boxed boolean that we can update in the anonymous class.", "boolean", "[", "]", "escape", "=", "{", "false", "}", ";", "new", "TreePathScanner", "<", "Void", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "visitIdentifier", "(", "IdentifierTree", "tree", ",", "Void", "unused", ")", "{", "if", "(", "varSym", ".", "equals", "(", "ASTHelpers", ".", "getSymbol", "(", "tree", ")", ")", ")", "{", "Tree", "parent", "=", "getCurrentPath", "(", ")", ".", "getParentPath", "(", ")", ".", "getLeaf", "(", ")", ";", "if", "(", "parent", "==", "varTree", ")", "{", "// the use of the variable in its declaration gets a pass", "return", "null", ";", "}", "// the LHS of a select (e.g. in `sb.append(...)`) does not escape", "if", "(", "!", "(", "parent", "instanceof", "MemberSelectTree", ")", "||", "(", "(", "MemberSelectTree", ")", "parent", ")", ".", "getExpression", "(", ")", "!=", "tree", ")", "{", "escape", "[", "0", "]", "=", "true", ";", "}", "}", "return", "null", ";", "}", "}", ".", "scan", "(", "methodPath", ",", "null", ")", ";", "if", "(", "escape", "[", "0", "]", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "return", "Optional", ".", "of", "(", "SuggestedFix", ".", "builder", "(", ")", ".", "replace", "(", "newClassTree", ".", "getIdentifier", "(", ")", ",", "\"StringBuilder\"", ")", ".", "replace", "(", "varTree", ".", "getType", "(", ")", ",", "\"StringBuilder\"", ")", ".", "build", "(", ")", ")", ";", "}" ]
current method.
[ "current", "method", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/JdkObsolete.java#L307-L355
21,671
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/JdkObsolete.java
JdkObsolete.mockingObsoleteMethod
private boolean mockingObsoleteMethod(MethodTree enclosingMethod, VisitorState state, Type type) { // mutable boolean to return result from visitor boolean[] found = {false}; enclosingMethod.accept( new TreeScanner<Void, Void>() { @Override public Void visitMethodInvocation(MethodInvocationTree node, Void unused) { if (found[0]) { return null; } if (MOCKITO_MATCHER.matches(node, state)) { Type stubber = ASTHelpers.getReturnType(node); if (!stubber.getTypeArguments().isEmpty() && ASTHelpers.isSameType( getOnlyElement(stubber.getTypeArguments()), type, state)) { found[0] = true; } } return super.visitMethodInvocation(node, null); } }, null); return found[0]; }
java
private boolean mockingObsoleteMethod(MethodTree enclosingMethod, VisitorState state, Type type) { // mutable boolean to return result from visitor boolean[] found = {false}; enclosingMethod.accept( new TreeScanner<Void, Void>() { @Override public Void visitMethodInvocation(MethodInvocationTree node, Void unused) { if (found[0]) { return null; } if (MOCKITO_MATCHER.matches(node, state)) { Type stubber = ASTHelpers.getReturnType(node); if (!stubber.getTypeArguments().isEmpty() && ASTHelpers.isSameType( getOnlyElement(stubber.getTypeArguments()), type, state)) { found[0] = true; } } return super.visitMethodInvocation(node, null); } }, null); return found[0]; }
[ "private", "boolean", "mockingObsoleteMethod", "(", "MethodTree", "enclosingMethod", ",", "VisitorState", "state", ",", "Type", "type", ")", "{", "// mutable boolean to return result from visitor", "boolean", "[", "]", "found", "=", "{", "false", "}", ";", "enclosingMethod", ".", "accept", "(", "new", "TreeScanner", "<", "Void", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "visitMethodInvocation", "(", "MethodInvocationTree", "node", ",", "Void", "unused", ")", "{", "if", "(", "found", "[", "0", "]", ")", "{", "return", "null", ";", "}", "if", "(", "MOCKITO_MATCHER", ".", "matches", "(", "node", ",", "state", ")", ")", "{", "Type", "stubber", "=", "ASTHelpers", ".", "getReturnType", "(", "node", ")", ";", "if", "(", "!", "stubber", ".", "getTypeArguments", "(", ")", ".", "isEmpty", "(", ")", "&&", "ASTHelpers", ".", "isSameType", "(", "getOnlyElement", "(", "stubber", ".", "getTypeArguments", "(", ")", ")", ",", "type", ",", "state", ")", ")", "{", "found", "[", "0", "]", "=", "true", ";", "}", "}", "return", "super", ".", "visitMethodInvocation", "(", "node", ",", "null", ")", ";", "}", "}", ",", "null", ")", ";", "return", "found", "[", "0", "]", ";", "}" ]
Allow mocking APIs that return obsolete types.
[ "Allow", "mocking", "APIs", "that", "return", "obsolete", "types", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/JdkObsolete.java#L390-L413
21,672
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/JdkObsolete.java
JdkObsolete.implementingObsoleteMethod
private static boolean implementingObsoleteMethod( MethodTree enclosingMethod, VisitorState state, Type type) { MethodSymbol method = ASTHelpers.getSymbol(enclosingMethod); if (method == null) { return false; } if (ASTHelpers.findSuperMethods(method, state.getTypes()).isEmpty()) { // not an override return false; } if (!ASTHelpers.isSameType(method.getReturnType(), type, state)) { return false; } return true; }
java
private static boolean implementingObsoleteMethod( MethodTree enclosingMethod, VisitorState state, Type type) { MethodSymbol method = ASTHelpers.getSymbol(enclosingMethod); if (method == null) { return false; } if (ASTHelpers.findSuperMethods(method, state.getTypes()).isEmpty()) { // not an override return false; } if (!ASTHelpers.isSameType(method.getReturnType(), type, state)) { return false; } return true; }
[ "private", "static", "boolean", "implementingObsoleteMethod", "(", "MethodTree", "enclosingMethod", ",", "VisitorState", "state", ",", "Type", "type", ")", "{", "MethodSymbol", "method", "=", "ASTHelpers", ".", "getSymbol", "(", "enclosingMethod", ")", ";", "if", "(", "method", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "ASTHelpers", ".", "findSuperMethods", "(", "method", ",", "state", ".", "getTypes", "(", ")", ")", ".", "isEmpty", "(", ")", ")", "{", "// not an override", "return", "false", ";", "}", "if", "(", "!", "ASTHelpers", ".", "isSameType", "(", "method", ".", "getReturnType", "(", ")", ",", "type", ",", "state", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Allow creating obsolete types when overriding a method with an obsolete return type.
[ "Allow", "creating", "obsolete", "types", "when", "overriding", "a", "method", "with", "an", "obsolete", "return", "type", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/JdkObsolete.java#L416-L430
21,673
google/error-prone
check_api/src/main/java/com/google/errorprone/scanner/Scanner.java
Scanner.isSuppressed
protected SuppressedState isSuppressed( Suppressible suppressible, ErrorProneOptions errorProneOptions) { boolean suppressedInGeneratedCode = errorProneOptions.disableWarningsInGeneratedCode() && severityMap().get(suppressible.canonicalName()) != SeverityLevel.ERROR; return currentSuppressions.suppressedState(suppressible, suppressedInGeneratedCode); }
java
protected SuppressedState isSuppressed( Suppressible suppressible, ErrorProneOptions errorProneOptions) { boolean suppressedInGeneratedCode = errorProneOptions.disableWarningsInGeneratedCode() && severityMap().get(suppressible.canonicalName()) != SeverityLevel.ERROR; return currentSuppressions.suppressedState(suppressible, suppressedInGeneratedCode); }
[ "protected", "SuppressedState", "isSuppressed", "(", "Suppressible", "suppressible", ",", "ErrorProneOptions", "errorProneOptions", ")", "{", "boolean", "suppressedInGeneratedCode", "=", "errorProneOptions", ".", "disableWarningsInGeneratedCode", "(", ")", "&&", "severityMap", "(", ")", ".", "get", "(", "suppressible", ".", "canonicalName", "(", ")", ")", "!=", "SeverityLevel", ".", "ERROR", ";", "return", "currentSuppressions", ".", "suppressedState", "(", "suppressible", ",", "suppressedInGeneratedCode", ")", ";", "}" ]
Returns if this checker should be suppressed on the current tree path. @param suppressible holds information about the suppressibility of a checker @param errorProneOptions Options object configuring whether or not to suppress non-errors in generated code.
[ "Returns", "if", "this", "checker", "should", "be", "suppressed", "on", "the", "current", "tree", "path", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/scanner/Scanner.java#L105-L113
21,674
google/error-prone
core/src/main/java/com/google/errorprone/refaster/URepeated.java
URepeated.getUnderlyingBinding
public JCExpression getUnderlyingBinding(Unifier unifier) { return (unifier == null) ? null : unifier.getBinding(new UFreeIdent.Key(identifier())); }
java
public JCExpression getUnderlyingBinding(Unifier unifier) { return (unifier == null) ? null : unifier.getBinding(new UFreeIdent.Key(identifier())); }
[ "public", "JCExpression", "getUnderlyingBinding", "(", "Unifier", "unifier", ")", "{", "return", "(", "unifier", "==", "null", ")", "?", "null", ":", "unifier", ".", "getBinding", "(", "new", "UFreeIdent", ".", "Key", "(", "identifier", "(", ")", ")", ")", ";", "}" ]
Gets the binding of the underlying identifier in the unifier.
[ "Gets", "the", "binding", "of", "the", "underlying", "identifier", "in", "the", "unifier", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/refaster/URepeated.java#L60-L62
21,675
google/error-prone
check_api/src/main/java/com/google/errorprone/ErrorProneVersion.java
ErrorProneVersion.loadVersionFromPom
public static Optional<String> loadVersionFromPom() { try (InputStream stream = ErrorProneVersion.class.getResourceAsStream(PROPERTIES_RESOURCE)) { if (stream == null) { return Optional.absent(); } Properties mavenProperties = new Properties(); mavenProperties.load(stream); return Optional.of(mavenProperties.getProperty("version")); } catch (IOException expected) { return Optional.absent(); } }
java
public static Optional<String> loadVersionFromPom() { try (InputStream stream = ErrorProneVersion.class.getResourceAsStream(PROPERTIES_RESOURCE)) { if (stream == null) { return Optional.absent(); } Properties mavenProperties = new Properties(); mavenProperties.load(stream); return Optional.of(mavenProperties.getProperty("version")); } catch (IOException expected) { return Optional.absent(); } }
[ "public", "static", "Optional", "<", "String", ">", "loadVersionFromPom", "(", ")", "{", "try", "(", "InputStream", "stream", "=", "ErrorProneVersion", ".", "class", ".", "getResourceAsStream", "(", "PROPERTIES_RESOURCE", ")", ")", "{", "if", "(", "stream", "==", "null", ")", "{", "return", "Optional", ".", "absent", "(", ")", ";", "}", "Properties", "mavenProperties", "=", "new", "Properties", "(", ")", ";", "mavenProperties", ".", "load", "(", "stream", ")", ";", "return", "Optional", ".", "of", "(", "mavenProperties", ".", "getProperty", "(", "\"version\"", ")", ")", ";", "}", "catch", "(", "IOException", "expected", ")", "{", "return", "Optional", ".", "absent", "(", ")", ";", "}", "}" ]
Loads the Error Prone version. <p>This depends on the Maven build, and will always return {@code Optional.absent()} with other build systems.
[ "Loads", "the", "Error", "Prone", "version", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/ErrorProneVersion.java#L36-L47
21,676
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/HeldLockAnalyzer.java
HeldLockAnalyzer.analyze
public static void analyze( VisitorState state, LockEventListener listener, Predicate<Tree> isSuppressed) { HeldLockSet locks = HeldLockSet.empty(); locks = handleMonitorGuards(state, locks); new LockScanner(state, listener, isSuppressed).scan(state.getPath(), locks); }
java
public static void analyze( VisitorState state, LockEventListener listener, Predicate<Tree> isSuppressed) { HeldLockSet locks = HeldLockSet.empty(); locks = handleMonitorGuards(state, locks); new LockScanner(state, listener, isSuppressed).scan(state.getPath(), locks); }
[ "public", "static", "void", "analyze", "(", "VisitorState", "state", ",", "LockEventListener", "listener", ",", "Predicate", "<", "Tree", ">", "isSuppressed", ")", "{", "HeldLockSet", "locks", "=", "HeldLockSet", ".", "empty", "(", ")", ";", "locks", "=", "handleMonitorGuards", "(", "state", ",", "locks", ")", ";", "new", "LockScanner", "(", "state", ",", "listener", ",", "isSuppressed", ")", ".", "scan", "(", "state", ".", "getPath", "(", ")", ",", "locks", ")", ";", "}" ]
Analyzes a method body, tracking the set of held locks and checking accesses to guarded members.
[ "Analyzes", "a", "method", "body", "tracking", "the", "set", "of", "held", "locks", "and", "checking", "accesses", "to", "guarded", "members", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/HeldLockAnalyzer.java#L83-L88
21,677
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdate.java
NonAtomicVolatileUpdate.expressionFromUnaryTree
private static Matcher<UnaryTree> expressionFromUnaryTree( final Matcher<ExpressionTree> exprMatcher) { return new Matcher<UnaryTree>() { @Override public boolean matches(UnaryTree tree, VisitorState state) { return exprMatcher.matches(tree.getExpression(), state); } }; }
java
private static Matcher<UnaryTree> expressionFromUnaryTree( final Matcher<ExpressionTree> exprMatcher) { return new Matcher<UnaryTree>() { @Override public boolean matches(UnaryTree tree, VisitorState state) { return exprMatcher.matches(tree.getExpression(), state); } }; }
[ "private", "static", "Matcher", "<", "UnaryTree", ">", "expressionFromUnaryTree", "(", "final", "Matcher", "<", "ExpressionTree", ">", "exprMatcher", ")", "{", "return", "new", "Matcher", "<", "UnaryTree", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "UnaryTree", "tree", ",", "VisitorState", "state", ")", "{", "return", "exprMatcher", ".", "matches", "(", "tree", ".", "getExpression", "(", ")", ",", "state", ")", ";", "}", "}", ";", "}" ]
Extracts the expression from a UnaryTree and applies a matcher to it.
[ "Extracts", "the", "expression", "from", "a", "UnaryTree", "and", "applies", "a", "matcher", "to", "it", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdate.java#L57-L65
21,678
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdate.java
NonAtomicVolatileUpdate.variableFromCompoundAssignmentTree
private static Matcher<CompoundAssignmentTree> variableFromCompoundAssignmentTree( final Matcher<ExpressionTree> exprMatcher) { return new Matcher<CompoundAssignmentTree>() { @Override public boolean matches(CompoundAssignmentTree tree, VisitorState state) { return exprMatcher.matches(tree.getVariable(), state); } }; }
java
private static Matcher<CompoundAssignmentTree> variableFromCompoundAssignmentTree( final Matcher<ExpressionTree> exprMatcher) { return new Matcher<CompoundAssignmentTree>() { @Override public boolean matches(CompoundAssignmentTree tree, VisitorState state) { return exprMatcher.matches(tree.getVariable(), state); } }; }
[ "private", "static", "Matcher", "<", "CompoundAssignmentTree", ">", "variableFromCompoundAssignmentTree", "(", "final", "Matcher", "<", "ExpressionTree", ">", "exprMatcher", ")", "{", "return", "new", "Matcher", "<", "CompoundAssignmentTree", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "CompoundAssignmentTree", "tree", ",", "VisitorState", "state", ")", "{", "return", "exprMatcher", ".", "matches", "(", "tree", ".", "getVariable", "(", ")", ",", "state", ")", ";", "}", "}", ";", "}" ]
Extracts the variable from a CompoundAssignmentTree and applies a matcher to it.
[ "Extracts", "the", "variable", "from", "a", "CompoundAssignmentTree", "and", "applies", "a", "matcher", "to", "it", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdate.java#L68-L76
21,679
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdate.java
NonAtomicVolatileUpdate.variableFromAssignmentTree
private static Matcher<AssignmentTree> variableFromAssignmentTree( final Matcher<ExpressionTree> exprMatcher) { return new Matcher<AssignmentTree>() { @Override public boolean matches(AssignmentTree tree, VisitorState state) { return exprMatcher.matches(tree.getVariable(), state); } }; }
java
private static Matcher<AssignmentTree> variableFromAssignmentTree( final Matcher<ExpressionTree> exprMatcher) { return new Matcher<AssignmentTree>() { @Override public boolean matches(AssignmentTree tree, VisitorState state) { return exprMatcher.matches(tree.getVariable(), state); } }; }
[ "private", "static", "Matcher", "<", "AssignmentTree", ">", "variableFromAssignmentTree", "(", "final", "Matcher", "<", "ExpressionTree", ">", "exprMatcher", ")", "{", "return", "new", "Matcher", "<", "AssignmentTree", ">", "(", ")", "{", "@", "Override", "public", "boolean", "matches", "(", "AssignmentTree", "tree", ",", "VisitorState", "state", ")", "{", "return", "exprMatcher", ".", "matches", "(", "tree", ".", "getVariable", "(", ")", ",", "state", ")", ";", "}", "}", ";", "}" ]
Extracts the variable from an AssignmentTree and applies a matcher to it.
[ "Extracts", "the", "variable", "from", "an", "AssignmentTree", "and", "applies", "a", "matcher", "to", "it", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdate.java#L79-L87
21,680
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdate.java
NonAtomicVolatileUpdate.assignmentIncrementDecrementMatcher
private static Matcher<AssignmentTree> assignmentIncrementDecrementMatcher( ExpressionTree variable) { return allOf( variableFromAssignmentTree(Matchers.<ExpressionTree>hasModifier(Modifier.VOLATILE)), not(inSynchronized()), assignment( Matchers.<ExpressionTree>anything(), toType( BinaryTree.class, Matchers.<BinaryTree>allOf( Matchers.<BinaryTree>anyOf(kindIs(Kind.PLUS), kindIs(Kind.MINUS)), binaryTree(sameVariable(variable), Matchers.<ExpressionTree>anything()))))); }
java
private static Matcher<AssignmentTree> assignmentIncrementDecrementMatcher( ExpressionTree variable) { return allOf( variableFromAssignmentTree(Matchers.<ExpressionTree>hasModifier(Modifier.VOLATILE)), not(inSynchronized()), assignment( Matchers.<ExpressionTree>anything(), toType( BinaryTree.class, Matchers.<BinaryTree>allOf( Matchers.<BinaryTree>anyOf(kindIs(Kind.PLUS), kindIs(Kind.MINUS)), binaryTree(sameVariable(variable), Matchers.<ExpressionTree>anything()))))); }
[ "private", "static", "Matcher", "<", "AssignmentTree", ">", "assignmentIncrementDecrementMatcher", "(", "ExpressionTree", "variable", ")", "{", "return", "allOf", "(", "variableFromAssignmentTree", "(", "Matchers", ".", "<", "ExpressionTree", ">", "hasModifier", "(", "Modifier", ".", "VOLATILE", ")", ")", ",", "not", "(", "inSynchronized", "(", ")", ")", ",", "assignment", "(", "Matchers", ".", "<", "ExpressionTree", ">", "anything", "(", ")", ",", "toType", "(", "BinaryTree", ".", "class", ",", "Matchers", ".", "<", "BinaryTree", ">", "allOf", "(", "Matchers", ".", "<", "BinaryTree", ">", "anyOf", "(", "kindIs", "(", "Kind", ".", "PLUS", ")", ",", "kindIs", "(", "Kind", ".", "MINUS", ")", ")", ",", "binaryTree", "(", "sameVariable", "(", "variable", ")", ",", "Matchers", ".", "<", "ExpressionTree", ">", "anything", "(", ")", ")", ")", ")", ")", ")", ";", "}" ]
Matches patterns like i = i + 1 and i = i - 1 in which i is volatile, and the pattern is not enclosed by a synchronized block.
[ "Matches", "patterns", "like", "i", "=", "i", "+", "1", "and", "i", "=", "i", "-", "1", "in", "which", "i", "is", "volatile", "and", "the", "pattern", "is", "not", "enclosed", "by", "a", "synchronized", "block", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/NonAtomicVolatileUpdate.java#L134-L146
21,681
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/CanBeStaticAnalyzer.java
CanBeStaticAnalyzer.referencesOuter
public static boolean referencesOuter(Tree tree, Symbol owner, VisitorState state) { CanBeStaticAnalyzer scanner = new CanBeStaticAnalyzer(owner, state); ((JCTree) tree).accept(scanner); return !scanner.canPossiblyBeStatic || !scanner.outerReferences.isEmpty(); }
java
public static boolean referencesOuter(Tree tree, Symbol owner, VisitorState state) { CanBeStaticAnalyzer scanner = new CanBeStaticAnalyzer(owner, state); ((JCTree) tree).accept(scanner); return !scanner.canPossiblyBeStatic || !scanner.outerReferences.isEmpty(); }
[ "public", "static", "boolean", "referencesOuter", "(", "Tree", "tree", ",", "Symbol", "owner", ",", "VisitorState", "state", ")", "{", "CanBeStaticAnalyzer", "scanner", "=", "new", "CanBeStaticAnalyzer", "(", "owner", ",", "state", ")", ";", "(", "(", "JCTree", ")", "tree", ")", ".", "accept", "(", "scanner", ")", ";", "return", "!", "scanner", ".", "canPossiblyBeStatic", "||", "!", "scanner", ".", "outerReferences", ".", "isEmpty", "(", ")", ";", "}" ]
Returns true if the tree references its enclosing class.
[ "Returns", "true", "if", "the", "tree", "references", "its", "enclosing", "class", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/CanBeStaticAnalyzer.java#L43-L47
21,682
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/CanBeStaticAnalyzer.java
CanBeStaticAnalyzer.memberOfEnclosing
private static boolean memberOfEnclosing(Symbol owner, VisitorState state, Symbol sym) { if (sym == null || !sym.hasOuterInstance()) { return false; } for (ClassSymbol encl = owner.owner.enclClass(); encl != null; encl = encl.owner != null ? encl.owner.enclClass() : null) { if (sym.isMemberOf(encl, state.getTypes())) { return true; } } return false; }
java
private static boolean memberOfEnclosing(Symbol owner, VisitorState state, Symbol sym) { if (sym == null || !sym.hasOuterInstance()) { return false; } for (ClassSymbol encl = owner.owner.enclClass(); encl != null; encl = encl.owner != null ? encl.owner.enclClass() : null) { if (sym.isMemberOf(encl, state.getTypes())) { return true; } } return false; }
[ "private", "static", "boolean", "memberOfEnclosing", "(", "Symbol", "owner", ",", "VisitorState", "state", ",", "Symbol", "sym", ")", "{", "if", "(", "sym", "==", "null", "||", "!", "sym", ".", "hasOuterInstance", "(", ")", ")", "{", "return", "false", ";", "}", "for", "(", "ClassSymbol", "encl", "=", "owner", ".", "owner", ".", "enclClass", "(", ")", ";", "encl", "!=", "null", ";", "encl", "=", "encl", ".", "owner", "!=", "null", "?", "encl", ".", "owner", ".", "enclClass", "(", ")", ":", "null", ")", "{", "if", "(", "sym", ".", "isMemberOf", "(", "encl", ",", "state", ".", "getTypes", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Is sym a non-static member of an enclosing class of currentClass?
[ "Is", "sym", "a", "non", "-", "static", "member", "of", "an", "enclosing", "class", "of", "currentClass?" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/CanBeStaticAnalyzer.java#L180-L192
21,683
google/error-prone
check_api/src/main/java/com/google/errorprone/names/TermEditDistance.java
TermEditDistance.computeCost
private static double computeCost( int[] assignments, double[][] costMatrix, double[] sourceTermDeletionCosts, double[] targetTermDeletionCosts) { // We need to sum the costs of each assigned pair, each unassigned source term, and each // unassigned target term. // Start with the total cost of _not_ using all the target terms, then when we use one we'll // remove it from this total. double totalCost = DoubleStream.of(targetTermDeletionCosts).sum(); for (int sourceTermIndex = 0; sourceTermIndex < assignments.length; sourceTermIndex++) { int targetTermIndex = assignments[sourceTermIndex]; if (targetTermIndex == -1) { // not using this source term totalCost += sourceTermDeletionCosts[sourceTermIndex]; } else { // add the cost of the assignments totalCost += costMatrix[sourceTermIndex][targetTermIndex]; // we are using this target term and so we should remove the cost of deleting it totalCost -= targetTermDeletionCosts[targetTermIndex]; } } return totalCost; }
java
private static double computeCost( int[] assignments, double[][] costMatrix, double[] sourceTermDeletionCosts, double[] targetTermDeletionCosts) { // We need to sum the costs of each assigned pair, each unassigned source term, and each // unassigned target term. // Start with the total cost of _not_ using all the target terms, then when we use one we'll // remove it from this total. double totalCost = DoubleStream.of(targetTermDeletionCosts).sum(); for (int sourceTermIndex = 0; sourceTermIndex < assignments.length; sourceTermIndex++) { int targetTermIndex = assignments[sourceTermIndex]; if (targetTermIndex == -1) { // not using this source term totalCost += sourceTermDeletionCosts[sourceTermIndex]; } else { // add the cost of the assignments totalCost += costMatrix[sourceTermIndex][targetTermIndex]; // we are using this target term and so we should remove the cost of deleting it totalCost -= targetTermDeletionCosts[targetTermIndex]; } } return totalCost; }
[ "private", "static", "double", "computeCost", "(", "int", "[", "]", "assignments", ",", "double", "[", "]", "[", "]", "costMatrix", ",", "double", "[", "]", "sourceTermDeletionCosts", ",", "double", "[", "]", "targetTermDeletionCosts", ")", "{", "// We need to sum the costs of each assigned pair, each unassigned source term, and each", "// unassigned target term.", "// Start with the total cost of _not_ using all the target terms, then when we use one we'll", "// remove it from this total.", "double", "totalCost", "=", "DoubleStream", ".", "of", "(", "targetTermDeletionCosts", ")", ".", "sum", "(", ")", ";", "for", "(", "int", "sourceTermIndex", "=", "0", ";", "sourceTermIndex", "<", "assignments", ".", "length", ";", "sourceTermIndex", "++", ")", "{", "int", "targetTermIndex", "=", "assignments", "[", "sourceTermIndex", "]", ";", "if", "(", "targetTermIndex", "==", "-", "1", ")", "{", "// not using this source term", "totalCost", "+=", "sourceTermDeletionCosts", "[", "sourceTermIndex", "]", ";", "}", "else", "{", "// add the cost of the assignments", "totalCost", "+=", "costMatrix", "[", "sourceTermIndex", "]", "[", "targetTermIndex", "]", ";", "// we are using this target term and so we should remove the cost of deleting it", "totalCost", "-=", "targetTermDeletionCosts", "[", "targetTermIndex", "]", ";", "}", "}", "return", "totalCost", ";", "}" ]
Compute the total cost of this assignment including the costs of unassigned source and target terms.
[ "Compute", "the", "total", "cost", "of", "this", "assignment", "including", "the", "costs", "of", "unassigned", "source", "and", "target", "terms", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/names/TermEditDistance.java#L102-L128
21,684
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/BigDecimalLiteralDouble.java
BigDecimalLiteralDouble.floatingPointArgument
private static boolean floatingPointArgument(ExpressionTree tree) { if (tree.getKind() == Kind.UNARY_PLUS || tree.getKind() == Kind.UNARY_MINUS) { tree = ((UnaryTree) tree).getExpression(); } return tree.getKind() == Kind.DOUBLE_LITERAL || tree.getKind() == Kind.FLOAT_LITERAL; }
java
private static boolean floatingPointArgument(ExpressionTree tree) { if (tree.getKind() == Kind.UNARY_PLUS || tree.getKind() == Kind.UNARY_MINUS) { tree = ((UnaryTree) tree).getExpression(); } return tree.getKind() == Kind.DOUBLE_LITERAL || tree.getKind() == Kind.FLOAT_LITERAL; }
[ "private", "static", "boolean", "floatingPointArgument", "(", "ExpressionTree", "tree", ")", "{", "if", "(", "tree", ".", "getKind", "(", ")", "==", "Kind", ".", "UNARY_PLUS", "||", "tree", ".", "getKind", "(", ")", "==", "Kind", ".", "UNARY_MINUS", ")", "{", "tree", "=", "(", "(", "UnaryTree", ")", "tree", ")", ".", "getExpression", "(", ")", ";", "}", "return", "tree", ".", "getKind", "(", ")", "==", "Kind", ".", "DOUBLE_LITERAL", "||", "tree", ".", "getKind", "(", ")", "==", "Kind", ".", "FLOAT_LITERAL", ";", "}" ]
accept multiple unary prefixes.
[ "accept", "multiple", "unary", "prefixes", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/BigDecimalLiteralDouble.java#L64-L69
21,685
google/error-prone
core/src/main/java/com/google/errorprone/refaster/PlaceholderUnificationVisitor.java
PlaceholderUnificationVisitor.chooseSubtrees
private static <T, R> Choice<State<R>> chooseSubtrees( State<?> state, Function<State<?>, Choice<? extends State<? extends T>>> choice1, Function<T, R> finalizer) { return choice1.apply(state).transform(s -> s.withResult(finalizer.apply(s.result()))); }
java
private static <T, R> Choice<State<R>> chooseSubtrees( State<?> state, Function<State<?>, Choice<? extends State<? extends T>>> choice1, Function<T, R> finalizer) { return choice1.apply(state).transform(s -> s.withResult(finalizer.apply(s.result()))); }
[ "private", "static", "<", "T", ",", "R", ">", "Choice", "<", "State", "<", "R", ">", ">", "chooseSubtrees", "(", "State", "<", "?", ">", "state", ",", "Function", "<", "State", "<", "?", ">", ",", "Choice", "<", "?", "extends", "State", "<", "?", "extends", "T", ">", ">", ">", "choice1", ",", "Function", "<", "T", ",", "R", ">", "finalizer", ")", "{", "return", "choice1", ".", "apply", "(", "state", ")", ".", "transform", "(", "s", "->", "s", ".", "withResult", "(", "finalizer", ".", "apply", "(", "s", ".", "result", "(", ")", ")", ")", ")", ";", "}" ]
This method, and its overloads, take <ol> <li>an initial state <li>functions that, given one state, return a branch choosing a subtree <li>a function that takes pieces of a tree type and recomposes them </ol>
[ "This", "method", "and", "its", "overloads", "take" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/refaster/PlaceholderUnificationVisitor.java#L311-L316
21,686
google/error-prone
check_api/src/main/java/com/google/errorprone/util/MoreAnnotations.java
MoreAnnotations.getValue
public static Optional<Attribute> getValue(Attribute.Compound attribute, String name) { return attribute.getElementValues().entrySet().stream() .filter(e -> e.getKey().getSimpleName().contentEquals(name)) .map(Map.Entry::getValue) .findFirst(); }
java
public static Optional<Attribute> getValue(Attribute.Compound attribute, String name) { return attribute.getElementValues().entrySet().stream() .filter(e -> e.getKey().getSimpleName().contentEquals(name)) .map(Map.Entry::getValue) .findFirst(); }
[ "public", "static", "Optional", "<", "Attribute", ">", "getValue", "(", "Attribute", ".", "Compound", "attribute", ",", "String", "name", ")", "{", "return", "attribute", ".", "getElementValues", "(", ")", ".", "entrySet", "(", ")", ".", "stream", "(", ")", ".", "filter", "(", "e", "->", "e", ".", "getKey", "(", ")", ".", "getSimpleName", "(", ")", ".", "contentEquals", "(", "name", ")", ")", ".", "map", "(", "Map", ".", "Entry", "::", "getValue", ")", ".", "findFirst", "(", ")", ";", "}" ]
Returns the value of the annotation element-value pair with the given name if it is not explicitly set.
[ "Returns", "the", "value", "of", "the", "annotation", "element", "-", "value", "pair", "with", "the", "given", "name", "if", "it", "is", "not", "explicitly", "set", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/MoreAnnotations.java#L109-L114
21,687
google/error-prone
check_api/src/main/java/com/google/errorprone/util/MoreAnnotations.java
MoreAnnotations.asIntegerValue
public static Optional<Integer> asIntegerValue(Attribute a) { class Visitor extends SimpleAnnotationValueVisitor8<Integer, Void> { @Override public Integer visitInt(int i, Void unused) { return i; } } return Optional.ofNullable(a.accept(new Visitor(), null)); }
java
public static Optional<Integer> asIntegerValue(Attribute a) { class Visitor extends SimpleAnnotationValueVisitor8<Integer, Void> { @Override public Integer visitInt(int i, Void unused) { return i; } } return Optional.ofNullable(a.accept(new Visitor(), null)); }
[ "public", "static", "Optional", "<", "Integer", ">", "asIntegerValue", "(", "Attribute", "a", ")", "{", "class", "Visitor", "extends", "SimpleAnnotationValueVisitor8", "<", "Integer", ",", "Void", ">", "{", "@", "Override", "public", "Integer", "visitInt", "(", "int", "i", ",", "Void", "unused", ")", "{", "return", "i", ";", "}", "}", "return", "Optional", ".", "ofNullable", "(", "a", ".", "accept", "(", "new", "Visitor", "(", ")", ",", "null", ")", ")", ";", "}" ]
Converts the given attribute to an integer value.
[ "Converts", "the", "given", "attribute", "to", "an", "integer", "value", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/MoreAnnotations.java#L117-L125
21,688
google/error-prone
check_api/src/main/java/com/google/errorprone/util/MoreAnnotations.java
MoreAnnotations.asStringValue
public static Optional<String> asStringValue(Attribute a) { class Visitor extends SimpleAnnotationValueVisitor8<String, Void> { @Override public String visitString(String s, Void unused) { return s; } } return Optional.ofNullable(a.accept(new Visitor(), null)); }
java
public static Optional<String> asStringValue(Attribute a) { class Visitor extends SimpleAnnotationValueVisitor8<String, Void> { @Override public String visitString(String s, Void unused) { return s; } } return Optional.ofNullable(a.accept(new Visitor(), null)); }
[ "public", "static", "Optional", "<", "String", ">", "asStringValue", "(", "Attribute", "a", ")", "{", "class", "Visitor", "extends", "SimpleAnnotationValueVisitor8", "<", "String", ",", "Void", ">", "{", "@", "Override", "public", "String", "visitString", "(", "String", "s", ",", "Void", "unused", ")", "{", "return", "s", ";", "}", "}", "return", "Optional", ".", "ofNullable", "(", "a", ".", "accept", "(", "new", "Visitor", "(", ")", ",", "null", ")", ")", ";", "}" ]
Converts the given attribute to an string value.
[ "Converts", "the", "given", "attribute", "to", "an", "string", "value", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/MoreAnnotations.java#L128-L136
21,689
google/error-prone
check_api/src/main/java/com/google/errorprone/util/MoreAnnotations.java
MoreAnnotations.asEnumValue
public static <T extends Enum<T>> Optional<T> asEnumValue(Class<T> clazz, Attribute a) { class Visitor extends SimpleAnnotationValueVisitor8<T, Void> { @Override public T visitEnumConstant(VariableElement c, Void unused) { return Enum.valueOf(clazz, c.getSimpleName().toString()); } } return Optional.ofNullable(a.accept(new Visitor(), null)); }
java
public static <T extends Enum<T>> Optional<T> asEnumValue(Class<T> clazz, Attribute a) { class Visitor extends SimpleAnnotationValueVisitor8<T, Void> { @Override public T visitEnumConstant(VariableElement c, Void unused) { return Enum.valueOf(clazz, c.getSimpleName().toString()); } } return Optional.ofNullable(a.accept(new Visitor(), null)); }
[ "public", "static", "<", "T", "extends", "Enum", "<", "T", ">", ">", "Optional", "<", "T", ">", "asEnumValue", "(", "Class", "<", "T", ">", "clazz", ",", "Attribute", "a", ")", "{", "class", "Visitor", "extends", "SimpleAnnotationValueVisitor8", "<", "T", ",", "Void", ">", "{", "@", "Override", "public", "T", "visitEnumConstant", "(", "VariableElement", "c", ",", "Void", "unused", ")", "{", "return", "Enum", ".", "valueOf", "(", "clazz", ",", "c", ".", "getSimpleName", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "}", "return", "Optional", ".", "ofNullable", "(", "a", ".", "accept", "(", "new", "Visitor", "(", ")", ",", "null", ")", ")", ";", "}" ]
Converts the given attribute to an enum value.
[ "Converts", "the", "given", "attribute", "to", "an", "enum", "value", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/MoreAnnotations.java#L139-L147
21,690
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/inject/InvalidTargetingOnScopingAnnotation.java
InvalidTargetingOnScopingAnnotation.replaceTargetAnnotation
private static Fix replaceTargetAnnotation( Target annotation, AnnotationTree targetAnnotationTree) { Set<ElementType> types = EnumSet.copyOf(REQUIRED_ELEMENT_TYPES); types.addAll(Arrays.asList(annotation.value())); return replaceTargetAnnotation(targetAnnotationTree, types); }
java
private static Fix replaceTargetAnnotation( Target annotation, AnnotationTree targetAnnotationTree) { Set<ElementType> types = EnumSet.copyOf(REQUIRED_ELEMENT_TYPES); types.addAll(Arrays.asList(annotation.value())); return replaceTargetAnnotation(targetAnnotationTree, types); }
[ "private", "static", "Fix", "replaceTargetAnnotation", "(", "Target", "annotation", ",", "AnnotationTree", "targetAnnotationTree", ")", "{", "Set", "<", "ElementType", ">", "types", "=", "EnumSet", ".", "copyOf", "(", "REQUIRED_ELEMENT_TYPES", ")", ";", "types", ".", "addAll", "(", "Arrays", ".", "asList", "(", "annotation", ".", "value", "(", ")", ")", ")", ";", "return", "replaceTargetAnnotation", "(", "targetAnnotationTree", ",", "types", ")", ";", "}" ]
Rewrite the annotation with static imports, adding TYPE and METHOD to the @Target annotation value (and reordering them to their declaration order in ElementType).
[ "Rewrite", "the", "annotation", "with", "static", "imports", "adding", "TYPE", "and", "METHOD", "to", "the" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/inject/InvalidTargetingOnScopingAnnotation.java#L98-L104
21,691
google/error-prone
check_api/src/main/java/com/google/errorprone/ErrorProneAnalyzer.java
ErrorProneAnalyzer.shouldExcludeSourceFile
private boolean shouldExcludeSourceFile(CompilationUnitTree tree) { Pattern excludedPattern = errorProneOptions.getExcludedPattern(); return excludedPattern != null && excludedPattern.matcher(ASTHelpers.getFileName(tree)).matches(); }
java
private boolean shouldExcludeSourceFile(CompilationUnitTree tree) { Pattern excludedPattern = errorProneOptions.getExcludedPattern(); return excludedPattern != null && excludedPattern.matcher(ASTHelpers.getFileName(tree)).matches(); }
[ "private", "boolean", "shouldExcludeSourceFile", "(", "CompilationUnitTree", "tree", ")", "{", "Pattern", "excludedPattern", "=", "errorProneOptions", ".", "getExcludedPattern", "(", ")", ";", "return", "excludedPattern", "!=", "null", "&&", "excludedPattern", ".", "matcher", "(", "ASTHelpers", ".", "getFileName", "(", "tree", ")", ")", ".", "matches", "(", ")", ";", "}" ]
Returns true if the given source file should be excluded from analysis.
[ "Returns", "true", "if", "the", "given", "source", "file", "should", "be", "excluded", "from", "analysis", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/ErrorProneAnalyzer.java#L177-L181
21,692
google/error-prone
check_api/src/main/java/com/google/errorprone/ErrorProneAnalyzer.java
ErrorProneAnalyzer.finishedCompilation
private boolean finishedCompilation(CompilationUnitTree tree) { OUTER: for (Tree decl : tree.getTypeDecls()) { switch (decl.getKind()) { case EMPTY_STATEMENT: // ignore ";" at the top level, which counts as an empty type decl continue OUTER; case IMPORT: // The spec disallows mixing imports and empty top-level declarations (";"), but // javac has a bug that causes it to accept empty declarations interspersed with imports: // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-August/006968.html // // Any import declarations after the first semi are incorrectly added to the list // of type declarations, so we have to skip over them here. continue OUTER; default: break; } if (!seen.contains(decl)) { return false; } } return true; }
java
private boolean finishedCompilation(CompilationUnitTree tree) { OUTER: for (Tree decl : tree.getTypeDecls()) { switch (decl.getKind()) { case EMPTY_STATEMENT: // ignore ";" at the top level, which counts as an empty type decl continue OUTER; case IMPORT: // The spec disallows mixing imports and empty top-level declarations (";"), but // javac has a bug that causes it to accept empty declarations interspersed with imports: // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-August/006968.html // // Any import declarations after the first semi are incorrectly added to the list // of type declarations, so we have to skip over them here. continue OUTER; default: break; } if (!seen.contains(decl)) { return false; } } return true; }
[ "private", "boolean", "finishedCompilation", "(", "CompilationUnitTree", "tree", ")", "{", "OUTER", ":", "for", "(", "Tree", "decl", ":", "tree", ".", "getTypeDecls", "(", ")", ")", "{", "switch", "(", "decl", ".", "getKind", "(", ")", ")", "{", "case", "EMPTY_STATEMENT", ":", "// ignore \";\" at the top level, which counts as an empty type decl", "continue", "OUTER", ";", "case", "IMPORT", ":", "// The spec disallows mixing imports and empty top-level declarations (\";\"), but", "// javac has a bug that causes it to accept empty declarations interspersed with imports:", "// http://mail.openjdk.java.net/pipermail/compiler-dev/2013-August/006968.html", "//", "// Any import declarations after the first semi are incorrectly added to the list", "// of type declarations, so we have to skip over them here.", "continue", "OUTER", ";", "default", ":", "break", ";", "}", "if", "(", "!", "seen", ".", "contains", "(", "decl", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns true if all declarations inside the given compilation unit have been visited.
[ "Returns", "true", "if", "all", "declarations", "inside", "the", "given", "compilation", "unit", "have", "been", "visited", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/ErrorProneAnalyzer.java#L184-L207
21,693
google/error-prone
core/src/main/java/com/google/errorprone/refaster/PlaceholderMethod.java
PlaceholderMethod.requiredParameters
Set<UVariableDecl> requiredParameters() { return Maps.filterValues( annotatedParameters(), (ImmutableClassToInstanceMap<Annotation> annotations) -> !annotations.containsKey(MayOptionallyUse.class)) .keySet(); }
java
Set<UVariableDecl> requiredParameters() { return Maps.filterValues( annotatedParameters(), (ImmutableClassToInstanceMap<Annotation> annotations) -> !annotations.containsKey(MayOptionallyUse.class)) .keySet(); }
[ "Set", "<", "UVariableDecl", ">", "requiredParameters", "(", ")", "{", "return", "Maps", ".", "filterValues", "(", "annotatedParameters", "(", ")", ",", "(", "ImmutableClassToInstanceMap", "<", "Annotation", ">", "annotations", ")", "->", "!", "annotations", ".", "containsKey", "(", "MayOptionallyUse", ".", "class", ")", ")", ".", "keySet", "(", ")", ";", "}" ]
Parameters which must be referenced in any tree matched to this placeholder.
[ "Parameters", "which", "must", "be", "referenced", "in", "any", "tree", "matched", "to", "this", "placeholder", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/refaster/PlaceholderMethod.java#L107-L113
21,694
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/JUnitMatchers.java
JUnitMatchers.hasJUnitAnnotation
public static boolean hasJUnitAnnotation(MethodTree tree, VisitorState state) { MethodSymbol methodSym = getSymbol(tree); if (methodSym == null) { return false; } if (hasJUnitAttr(methodSym)) { return true; } return findSuperMethods(methodSym, state.getTypes()).stream() .anyMatch(JUnitMatchers::hasJUnitAttr); }
java
public static boolean hasJUnitAnnotation(MethodTree tree, VisitorState state) { MethodSymbol methodSym = getSymbol(tree); if (methodSym == null) { return false; } if (hasJUnitAttr(methodSym)) { return true; } return findSuperMethods(methodSym, state.getTypes()).stream() .anyMatch(JUnitMatchers::hasJUnitAttr); }
[ "public", "static", "boolean", "hasJUnitAnnotation", "(", "MethodTree", "tree", ",", "VisitorState", "state", ")", "{", "MethodSymbol", "methodSym", "=", "getSymbol", "(", "tree", ")", ";", "if", "(", "methodSym", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "hasJUnitAttr", "(", "methodSym", ")", ")", "{", "return", "true", ";", "}", "return", "findSuperMethods", "(", "methodSym", ",", "state", ".", "getTypes", "(", ")", ")", ".", "stream", "(", ")", ".", "anyMatch", "(", "JUnitMatchers", "::", "hasJUnitAttr", ")", ";", "}" ]
Checks if a method, or any overridden method, is annotated with any annotation from the org.junit package.
[ "Checks", "if", "a", "method", "or", "any", "overridden", "method", "is", "annotated", "with", "any", "annotation", "from", "the", "org", ".", "junit", "package", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/JUnitMatchers.java#L81-L91
21,695
google/error-prone
check_api/src/main/java/com/google/errorprone/matchers/JUnitMatchers.java
JUnitMatchers.hasJUnitAttr
private static boolean hasJUnitAttr(MethodSymbol methodSym) { return methodSym.getRawAttributes().stream() .anyMatch(attr -> attr.type.tsym.getQualifiedName().toString().startsWith("org.junit.")); }
java
private static boolean hasJUnitAttr(MethodSymbol methodSym) { return methodSym.getRawAttributes().stream() .anyMatch(attr -> attr.type.tsym.getQualifiedName().toString().startsWith("org.junit.")); }
[ "private", "static", "boolean", "hasJUnitAttr", "(", "MethodSymbol", "methodSym", ")", "{", "return", "methodSym", ".", "getRawAttributes", "(", ")", ".", "stream", "(", ")", ".", "anyMatch", "(", "attr", "->", "attr", ".", "type", ".", "tsym", ".", "getQualifiedName", "(", ")", ".", "toString", "(", ")", ".", "startsWith", "(", "\"org.junit.\"", ")", ")", ";", "}" ]
Checks if a method symbol has any attribute from the org.junit package.
[ "Checks", "if", "a", "method", "symbol", "has", "any", "attribute", "from", "the", "org", ".", "junit", "package", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/matchers/JUnitMatchers.java#L94-L97
21,696
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedBySymbolResolver.java
GuardedBySymbolResolver.resolveType
private Symbol resolveType(String name, SearchSuperTypes searchSuperTypes) { Symbol type = null; if (searchSuperTypes == SearchSuperTypes.YES) { type = getSuperType(enclosingClass, name); } if (enclosingClass.getSimpleName().contentEquals(name)) { type = enclosingClass; } if (type == null) { type = getLexicallyEnclosing(enclosingClass, name); } if (type == null) { type = attribIdent(name); } checkGuardedBy( !(type instanceof Symbol.PackageSymbol), "All we could find for '%s' was a package symbol.", name); return type; }
java
private Symbol resolveType(String name, SearchSuperTypes searchSuperTypes) { Symbol type = null; if (searchSuperTypes == SearchSuperTypes.YES) { type = getSuperType(enclosingClass, name); } if (enclosingClass.getSimpleName().contentEquals(name)) { type = enclosingClass; } if (type == null) { type = getLexicallyEnclosing(enclosingClass, name); } if (type == null) { type = attribIdent(name); } checkGuardedBy( !(type instanceof Symbol.PackageSymbol), "All we could find for '%s' was a package symbol.", name); return type; }
[ "private", "Symbol", "resolveType", "(", "String", "name", ",", "SearchSuperTypes", "searchSuperTypes", ")", "{", "Symbol", "type", "=", "null", ";", "if", "(", "searchSuperTypes", "==", "SearchSuperTypes", ".", "YES", ")", "{", "type", "=", "getSuperType", "(", "enclosingClass", ",", "name", ")", ";", "}", "if", "(", "enclosingClass", ".", "getSimpleName", "(", ")", ".", "contentEquals", "(", "name", ")", ")", "{", "type", "=", "enclosingClass", ";", "}", "if", "(", "type", "==", "null", ")", "{", "type", "=", "getLexicallyEnclosing", "(", "enclosingClass", ",", "name", ")", ";", "}", "if", "(", "type", "==", "null", ")", "{", "type", "=", "attribIdent", "(", "name", ")", ";", "}", "checkGuardedBy", "(", "!", "(", "type", "instanceof", "Symbol", ".", "PackageSymbol", ")", ",", "\"All we could find for '%s' was a package symbol.\"", ",", "name", ")", ";", "return", "type", ";", "}" ]
Resolves a simple name as a type. Considers super classes, lexically enclosing classes, and then arbitrary types available in the current environment.
[ "Resolves", "a", "simple", "name", "as", "a", "type", ".", "Considers", "super", "classes", "lexically", "enclosing", "classes", "and", "then", "arbitrary", "types", "available", "in", "the", "current", "environment", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/GuardedBySymbolResolver.java#L197-L216
21,697
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/AssertEqualsArgumentOrderChecker.java
AssertEqualsArgumentOrderChecker.isEnumIdentifier
private static boolean isEnumIdentifier(Parameter parameter) { switch (parameter.kind()) { case IDENTIFIER: case MEMBER_SELECT: break; default: return false; } TypeSymbol typeSymbol = parameter.type().tsym; if (typeSymbol != null) { return typeSymbol.getKind() == ElementKind.ENUM; } return false; }
java
private static boolean isEnumIdentifier(Parameter parameter) { switch (parameter.kind()) { case IDENTIFIER: case MEMBER_SELECT: break; default: return false; } TypeSymbol typeSymbol = parameter.type().tsym; if (typeSymbol != null) { return typeSymbol.getKind() == ElementKind.ENUM; } return false; }
[ "private", "static", "boolean", "isEnumIdentifier", "(", "Parameter", "parameter", ")", "{", "switch", "(", "parameter", ".", "kind", "(", ")", ")", "{", "case", "IDENTIFIER", ":", "case", "MEMBER_SELECT", ":", "break", ";", "default", ":", "return", "false", ";", "}", "TypeSymbol", "typeSymbol", "=", "parameter", ".", "type", "(", ")", ".", "tsym", ";", "if", "(", "typeSymbol", "!=", "null", ")", "{", "return", "typeSymbol", ".", "getKind", "(", ")", "==", "ElementKind", ".", "ENUM", ";", "}", "return", "false", ";", "}" ]
Returns true if this parameter is an enum identifier
[ "Returns", "true", "if", "this", "parameter", "is", "an", "enum", "identifier" ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/argumentselectiondefects/AssertEqualsArgumentOrderChecker.java#L130-L143
21,698
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/AbstractMustBeClosedChecker.java
AbstractMustBeClosedChecker.enclosingMethod
@Nullable private static MethodTree enclosingMethod(VisitorState state) { for (Tree node : state.getPath().getParentPath()) { switch (node.getKind()) { case LAMBDA_EXPRESSION: case NEW_CLASS: return null; case METHOD: return (MethodTree) node; default: break; } } return null; }
java
@Nullable private static MethodTree enclosingMethod(VisitorState state) { for (Tree node : state.getPath().getParentPath()) { switch (node.getKind()) { case LAMBDA_EXPRESSION: case NEW_CLASS: return null; case METHOD: return (MethodTree) node; default: break; } } return null; }
[ "@", "Nullable", "private", "static", "MethodTree", "enclosingMethod", "(", "VisitorState", "state", ")", "{", "for", "(", "Tree", "node", ":", "state", ".", "getPath", "(", ")", ".", "getParentPath", "(", ")", ")", "{", "switch", "(", "node", ".", "getKind", "(", ")", ")", "{", "case", "LAMBDA_EXPRESSION", ":", "case", "NEW_CLASS", ":", "return", "null", ";", "case", "METHOD", ":", "return", "(", "MethodTree", ")", "node", ";", "default", ":", "break", ";", "}", "}", "return", "null", ";", "}" ]
Returns the enclosing method of the given visitor state. Returns null if the state is within a lambda expression or anonymous class.
[ "Returns", "the", "enclosing", "method", "of", "the", "given", "visitor", "state", ".", "Returns", "null", "if", "the", "state", "is", "within", "a", "lambda", "expression", "or", "anonymous", "class", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/AbstractMustBeClosedChecker.java#L162-L176
21,699
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/MissingCasesInEnumSwitch.java
MissingCasesInEnumSwitch.buildMessage
private String buildMessage(Set<String> unhandled) { StringBuilder message = new StringBuilder( "Non-exhaustive switch; either add a default or handle the remaining cases: "); int numberToShow = unhandled.size() > MAX_CASES_TO_PRINT ? 3 // if there are too many to print, only show three examples. : unhandled.size(); message.append(unhandled.stream().limit(numberToShow).collect(Collectors.joining(", "))); if (numberToShow < unhandled.size()) { message.append(String.format(", and %d others", unhandled.size() - numberToShow)); } return message.toString(); }
java
private String buildMessage(Set<String> unhandled) { StringBuilder message = new StringBuilder( "Non-exhaustive switch; either add a default or handle the remaining cases: "); int numberToShow = unhandled.size() > MAX_CASES_TO_PRINT ? 3 // if there are too many to print, only show three examples. : unhandled.size(); message.append(unhandled.stream().limit(numberToShow).collect(Collectors.joining(", "))); if (numberToShow < unhandled.size()) { message.append(String.format(", and %d others", unhandled.size() - numberToShow)); } return message.toString(); }
[ "private", "String", "buildMessage", "(", "Set", "<", "String", ">", "unhandled", ")", "{", "StringBuilder", "message", "=", "new", "StringBuilder", "(", "\"Non-exhaustive switch; either add a default or handle the remaining cases: \"", ")", ";", "int", "numberToShow", "=", "unhandled", ".", "size", "(", ")", ">", "MAX_CASES_TO_PRINT", "?", "3", "// if there are too many to print, only show three examples.", ":", "unhandled", ".", "size", "(", ")", ";", "message", ".", "append", "(", "unhandled", ".", "stream", "(", ")", ".", "limit", "(", "numberToShow", ")", ".", "collect", "(", "Collectors", ".", "joining", "(", "\", \"", ")", ")", ")", ";", "if", "(", "numberToShow", "<", "unhandled", ".", "size", "(", ")", ")", "{", "message", ".", "append", "(", "String", ".", "format", "(", "\", and %d others\"", ",", "unhandled", ".", "size", "(", ")", "-", "numberToShow", ")", ")", ";", "}", "return", "message", ".", "toString", "(", ")", ";", "}" ]
Build the diagnostic message. <p>Examples: <ul> <li>Non-exhaustive switch, expected cases for: FOO <li>Non-exhaustive switch, expected cases for: FOO, BAR, BAZ, and 42 others. </ul>
[ "Build", "the", "diagnostic", "message", "." ]
fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/MissingCasesInEnumSwitch.java#L79-L92