file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
AddThrowsAction.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/quickfix/AddThrowsAction.java | package com.tyron.completion.java.action.quickfix;
import static com.tyron.completion.java.util.DiagnosticUtil.findMethod;
import androidx.annotation.NonNull;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.util.TreePath;
import com.tyron.actions.AnActionEvent;
import com.tyron.actions.CommonDataKeys;
import com.tyron.actions.Presentation;
import com.tyron.common.util.ThreadUtil;
import com.tyron.completion.java.R;
import com.tyron.completion.java.action.CommonJavaContextKeys;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.CompilerContainer;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.rewrite.AddException;
import com.tyron.completion.java.rewrite.JavaRewrite;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.java.util.DiagnosticUtil;
import com.tyron.completion.java.util.ElementUtil;
import com.tyron.completion.util.RewriteUtil;
import com.tyron.editor.Editor;
import java.io.File;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicReference;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
public class AddThrowsAction extends ExceptionsQuickFix {
public static final String ID = "javaAddThrowsQuickFix";
@Override
public void update(@NonNull AnActionEvent event) {
super.update(event);
Presentation presentation = event.getPresentation();
if (!presentation.isVisible()) {
return;
}
presentation.setVisible(false);
Diagnostic<?> diagnostic = event.getData(CommonDataKeys.DIAGNOSTIC);
if (diagnostic == null) {
return;
}
TreePath surroundingPath =
ActionUtil.findSurroundingPath(event.getData(CommonJavaContextKeys.CURRENT_PATH));
if (surroundingPath == null) {
return;
}
if (surroundingPath.getLeaf() instanceof LambdaExpressionTree) {
return;
}
Editor editor = event.getData(CommonDataKeys.EDITOR);
if (editor == null) {
return;
}
presentation.setEnabled(true);
presentation.setVisible(true);
presentation.setText(event.getDataContext().getString(R.string.menu_quickfix_add_throws_title));
}
@Override
public void actionPerformed(@NonNull AnActionEvent e) {
Editor editor = e.getData(CommonDataKeys.EDITOR);
File file = e.getData(CommonDataKeys.FILE);
JavaCompilerService compiler = e.getData(CommonJavaContextKeys.COMPILER);
Diagnostic<?> diagnostic = e.getData(CommonDataKeys.DIAGNOSTIC);
TreePath currentPath = e.getData(CommonJavaContextKeys.CURRENT_PATH);
String exceptionName =
DiagnosticUtil.extractExceptionName(diagnostic.getMessage(Locale.ENGLISH));
ThreadUtil.runOnBackgroundThread(
() -> {
CompilerContainer container = compiler.getCachedContainer();
AtomicReference<JavaRewrite> rewrite = new AtomicReference<>();
container.run(task -> rewrite.set(performInternal(task, exceptionName, diagnostic)));
JavaRewrite r = rewrite.get();
if (r != null) {
RewriteUtil.performRewrite(editor, file, compiler, r);
}
});
}
private JavaRewrite performInternal(
CompileTask task, String exceptionName, Diagnostic<?> diagnostic) {
if (task == null) {
return null;
}
DiagnosticUtil.MethodPtr needsThrow = findMethod(task, diagnostic.getPosition());
Element classElement = needsThrow.method.getEnclosingElement();
TypeElement classTypeElement = (TypeElement) classElement;
TypeMirror superclass = classTypeElement.getSuperclass();
TypeElement superClassElement = (TypeElement) task.task.getTypes().asElement(superclass);
if (!ElementUtil.isMemberOf(task, needsThrow.method, superClassElement)) {
return new AddException(
needsThrow.className,
needsThrow.methodName,
needsThrow.erasedParameterTypes,
exceptionName);
}
return null;
}
}
| 4,091 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ImportClassAction.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/quickfix/ImportClassAction.java | package com.tyron.completion.java.action.quickfix;
import android.app.AlertDialog;
import androidx.annotation.NonNull;
import com.sun.tools.javac.api.ClientCodeWrapper;
import com.sun.tools.javac.util.JCDiagnostic;
import com.tyron.actions.ActionPlaces;
import com.tyron.actions.AnAction;
import com.tyron.actions.AnActionEvent;
import com.tyron.actions.CommonDataKeys;
import com.tyron.actions.Presentation;
import com.tyron.completion.java.R;
import com.tyron.completion.java.action.CommonJavaContextKeys;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.rewrite.AddImport;
import com.tyron.completion.java.rewrite.JavaRewrite;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.java.util.DiagnosticUtil;
import com.tyron.completion.util.RewriteUtil;
import com.tyron.editor.Editor;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.tools.Diagnostic;
public class ImportClassAction extends AnAction {
public static final String ID = "javaImportClassFix";
public static final String ERROR_CODE = "compiler.err.cant.resolve.location";
public static final String ERROR_CODE_RETURN_TYPE = "compiler.err.cant.resolve";
@Override
public void update(@NonNull AnActionEvent event) {
Presentation presentation = event.getPresentation();
presentation.setVisible(false);
if (!ActionPlaces.EDITOR.equals(event.getPlace())) {
return;
}
Diagnostic<?> diagnostic = event.getData(CommonDataKeys.DIAGNOSTIC);
if (diagnostic == null) {
return;
}
ClientCodeWrapper.DiagnosticSourceUnwrapper diagnosticSourceUnwrapper =
DiagnosticUtil.getDiagnosticSourceUnwrapper(diagnostic);
if (diagnosticSourceUnwrapper == null) {
return;
}
if (!ERROR_CODE.equals(diagnostic.getCode())
&& !ERROR_CODE_RETURN_TYPE.equals(diagnostic.getCode())) {
return;
}
JavaCompilerService compiler = event.getData(CommonJavaContextKeys.COMPILER);
if (compiler == null) {
return;
}
String simpleName = String.valueOf(diagnosticSourceUnwrapper.d.getArgs()[1]);
List<String> classNames = new ArrayList<>();
for (String qualifiedName : compiler.publicTopLevelTypes()) {
if (qualifiedName.endsWith("." + simpleName)) {
classNames.add(qualifiedName);
}
}
if (classNames.isEmpty()) {
return;
}
if (classNames.size() > 1) {
presentation.setText(event.getDataContext().getString(R.string.import_class_title));
} else {
String format =
event
.getDataContext()
.getString(
R.string.import_class_name,
ActionUtil.getSimpleName(classNames.iterator().next()));
presentation.setText(format);
}
presentation.setEnabled(true);
presentation.setVisible(true);
}
@Override
public void actionPerformed(@NonNull AnActionEvent e) {
Diagnostic<?> diagnostic = e.getData(CommonDataKeys.DIAGNOSTIC);
diagnostic = DiagnosticUtil.getDiagnosticSourceUnwrapper(diagnostic);
if (diagnostic == null) {
return;
}
Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
JCDiagnostic d = ((ClientCodeWrapper.DiagnosticSourceUnwrapper) diagnostic).d;
String simpleName = String.valueOf(d.getArgs()[1]);
JavaCompilerService compiler = e.getRequiredData(CommonJavaContextKeys.COMPILER);
Path file = e.getRequiredData(CommonDataKeys.FILE).toPath();
Map<String, JavaRewrite> map = new TreeMap<>();
for (String qualifiedName : compiler.publicTopLevelTypes()) {
if (qualifiedName.endsWith("." + simpleName)) {
String title = e.getDataContext().getString(R.string.import_class_name, qualifiedName);
JavaRewrite addImport = new AddImport(file.toFile(), qualifiedName);
map.put(title, addImport);
}
}
if (map.size() == 1) {
RewriteUtil.performRewrite(editor, file.toFile(), compiler, map.values().iterator().next());
} else {
String[] titles = map.keySet().toArray(new String[0]);
new AlertDialog.Builder(e.getDataContext())
.setTitle(R.string.import_class_title)
.setItems(
titles,
(di, w) -> {
JavaRewrite rewrite = map.get(titles[w]);
RewriteUtil.performRewrite(editor, file.toFile(), compiler, rewrite);
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
}
}
| 4,589 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ImplementAbstractMethodsFix.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/quickfix/ImplementAbstractMethodsFix.java | package com.tyron.completion.java.action.quickfix;
import androidx.annotation.NonNull;
import com.sun.tools.javac.api.ClientCodeWrapper;
import com.sun.tools.javac.util.JCDiagnostic;
import com.tyron.actions.ActionPlaces;
import com.tyron.actions.AnAction;
import com.tyron.actions.AnActionEvent;
import com.tyron.actions.CommonDataKeys;
import com.tyron.actions.Presentation;
import com.tyron.completion.java.R;
import com.tyron.completion.java.action.CommonJavaContextKeys;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.rewrite.ImplementAbstractMethods;
import com.tyron.completion.java.rewrite.JavaRewrite;
import com.tyron.completion.java.util.DiagnosticUtil;
import com.tyron.completion.util.RewriteUtil;
import com.tyron.editor.Editor;
import java.io.File;
import javax.tools.Diagnostic;
public class ImplementAbstractMethodsFix extends AnAction {
public static final String ID = "javaImplementAbstractMethodsFix";
public static final String ERROR_CODE = "compiler.err.does.not.override.abstract";
@Override
public void update(@NonNull AnActionEvent event) {
Presentation presentation = event.getPresentation();
presentation.setVisible(false);
Diagnostic<?> diagnostic = event.getData(CommonDataKeys.DIAGNOSTIC);
if (diagnostic == null) {
return;
}
if (!ActionPlaces.EDITOR.equals(event.getPlace())) {
return;
}
ClientCodeWrapper.DiagnosticSourceUnwrapper diagnosticSourceUnwrapper =
DiagnosticUtil.getDiagnosticSourceUnwrapper(diagnostic);
if (diagnosticSourceUnwrapper == null) {
return;
}
if (!ERROR_CODE.equals(diagnostic.getCode())) {
return;
}
JavaCompilerService compiler = event.getData(CommonJavaContextKeys.COMPILER);
if (compiler == null) {
return;
}
presentation.setVisible(true);
presentation.setText(
event.getDataContext().getString(R.string.menu_quickfix_implement_abstract_methods_title));
}
@Override
public void actionPerformed(@NonNull AnActionEvent e) {
Editor editor = e.getData(CommonDataKeys.EDITOR);
File file = e.getData(CommonDataKeys.FILE);
JavaCompilerService compiler = e.getData(CommonJavaContextKeys.COMPILER);
Diagnostic<?> diagnostic = e.getData(CommonDataKeys.DIAGNOSTIC);
ClientCodeWrapper.DiagnosticSourceUnwrapper diagnosticSourceUnwrapper =
DiagnosticUtil.getDiagnosticSourceUnwrapper(diagnostic);
if (diagnosticSourceUnwrapper == null) {
return;
}
JCDiagnostic jcDiagnostic = diagnosticSourceUnwrapper.d;
JavaRewrite rewrite = new ImplementAbstractMethods(jcDiagnostic);
RewriteUtil.performRewrite(editor, file, compiler, rewrite);
}
}
| 2,728 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
SurroundWithTryCatchAction.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/quickfix/SurroundWithTryCatchAction.java | package com.tyron.completion.java.action.quickfix;
import androidx.annotation.NonNull;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TryTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.tree.EndPosTable;
import com.sun.tools.javac.tree.JCTree;
import com.tyron.actions.AnActionEvent;
import com.tyron.actions.CommonDataKeys;
import com.tyron.actions.Presentation;
import com.tyron.common.util.ThreadUtil;
import com.tyron.completion.java.R;
import com.tyron.completion.java.action.CommonJavaContextKeys;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.rewrite.AddTryCatch;
import com.tyron.completion.java.rewrite.JavaRewrite;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.java.util.DiagnosticUtil;
import com.tyron.completion.util.RewriteUtil;
import com.tyron.editor.Editor;
import java.io.File;
import java.util.Locale;
import javax.tools.Diagnostic;
public class SurroundWithTryCatchAction extends ExceptionsQuickFix {
public static final String ID = "javaSurroundWithTryCatchQuickFix";
@Override
public void update(@NonNull AnActionEvent event) {
super.update(event);
Presentation presentation = event.getPresentation();
if (!presentation.isVisible()) {
return;
}
presentation.setVisible(false);
Diagnostic<?> diagnostic = event.getData(CommonDataKeys.DIAGNOSTIC);
if (diagnostic == null) {
return;
}
TreePath surroundingPath =
ActionUtil.findSurroundingPath(event.getData(CommonJavaContextKeys.CURRENT_PATH));
if (surroundingPath == null) {
return;
}
if (surroundingPath.getLeaf() instanceof LambdaExpressionTree) {
return;
}
if (surroundingPath.getLeaf() instanceof TryTree) {
return;
}
presentation.setEnabled(true);
presentation.setVisible(true);
presentation.setText(
event.getDataContext().getString(R.string.menu_quickfix_surround_try_catch_title));
}
@Override
public void actionPerformed(@NonNull AnActionEvent e) {
Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
File file = e.getRequiredData(CommonDataKeys.FILE);
JavaCompilerService compiler = e.getRequiredData(CommonJavaContextKeys.COMPILER);
Diagnostic<?> diagnostic = e.getRequiredData(CommonDataKeys.DIAGNOSTIC);
TreePath currentPath = e.getRequiredData(CommonJavaContextKeys.CURRENT_PATH);
TreePath surroundingPath = ActionUtil.findSurroundingPath(currentPath);
String exceptionName =
DiagnosticUtil.extractExceptionName(diagnostic.getMessage(Locale.ENGLISH));
if (surroundingPath == null) {
return;
}
ThreadUtil.runOnBackgroundThread(
() -> {
JavaRewrite r = performInternal(file, exceptionName, surroundingPath);
RewriteUtil.performRewrite(editor, file, compiler, r);
});
}
private JavaRewrite performInternal(File file, String exceptionName, TreePath surroundingPath) {
Tree leaf = surroundingPath.getLeaf();
JCTree tree = (JCTree) leaf;
CompilationUnitTree root = surroundingPath.getCompilationUnit();
JCTree.JCCompilationUnit compilationUnit = (JCTree.JCCompilationUnit) root;
EndPosTable endPositions = compilationUnit.endPositions;
int start = tree.getStartPosition();
int end = tree.getEndPosition(endPositions);
String contents = leaf.toString();
return new AddTryCatch(file.toPath(), contents, start, end, exceptionName);
}
}
| 3,607 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ImportClassFieldFix.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/action/quickfix/ImportClassFieldFix.java | package com.tyron.completion.java.action.quickfix;
import android.app.AlertDialog;
import androidx.annotation.NonNull;
import com.sun.tools.javac.api.ClientCodeWrapper;
import com.sun.tools.javac.util.JCDiagnostic;
import com.tyron.actions.ActionPlaces;
import com.tyron.actions.AnAction;
import com.tyron.actions.AnActionEvent;
import com.tyron.actions.CommonDataKeys;
import com.tyron.actions.Presentation;
import com.tyron.completion.java.R;
import com.tyron.completion.java.action.CommonJavaContextKeys;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.rewrite.AddImport;
import com.tyron.completion.java.rewrite.JavaRewrite;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.java.util.DiagnosticUtil;
import com.tyron.completion.util.RewriteUtil;
import com.tyron.editor.Editor;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.tools.Diagnostic;
public class ImportClassFieldFix extends AnAction {
public static final String ID = "javaImportClassFieldFix";
public static final String ERROR_CODE = "compiler.err.doesnt.exist";
@Override
public void update(@NonNull AnActionEvent event) {
Presentation presentation = event.getPresentation();
presentation.setVisible(false);
if (!ActionPlaces.EDITOR.equals(event.getPlace())) {
return;
}
Diagnostic<?> diagnostic = event.getData(CommonDataKeys.DIAGNOSTIC);
if (diagnostic == null) {
return;
}
ClientCodeWrapper.DiagnosticSourceUnwrapper diagnosticSourceUnwrapper =
DiagnosticUtil.getDiagnosticSourceUnwrapper(diagnostic);
if (diagnosticSourceUnwrapper == null) {
return;
}
if (!ERROR_CODE.equals(diagnostic.getCode())) {
return;
}
JavaCompilerService compiler = event.getData(CommonJavaContextKeys.COMPILER);
if (compiler == null) {
return;
}
String simpleName = String.valueOf(diagnosticSourceUnwrapper.d.getArgs()[0]);
List<String> classNames = new ArrayList<>();
for (String qualifiedName : compiler.publicTopLevelTypes()) {
if (qualifiedName.endsWith("." + simpleName)) {
classNames.add(qualifiedName);
}
}
if (classNames.isEmpty()) {
return;
}
if (classNames.size() > 1) {
presentation.setText(event.getDataContext().getString(R.string.import_class_title));
} else {
String format =
event
.getDataContext()
.getString(
R.string.import_class_name,
ActionUtil.getSimpleName(classNames.iterator().next()));
presentation.setText(format);
}
presentation.setEnabled(true);
presentation.setVisible(true);
}
@Override
public void actionPerformed(@NonNull AnActionEvent e) {
Diagnostic<?> diagnostic = e.getRequiredData(CommonDataKeys.DIAGNOSTIC);
diagnostic = DiagnosticUtil.getDiagnosticSourceUnwrapper(diagnostic);
if (diagnostic == null) {
return;
}
Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
JCDiagnostic d = ((ClientCodeWrapper.DiagnosticSourceUnwrapper) diagnostic).d;
String simpleName = String.valueOf(d.getArgs()[0]);
JavaCompilerService compiler = e.getRequiredData(CommonJavaContextKeys.COMPILER);
Path file = e.getRequiredData(CommonDataKeys.FILE).toPath();
boolean isField = simpleName.contains(".");
String searchName = simpleName;
if (isField) {
searchName = searchName.substring(0, searchName.indexOf('.'));
}
Map<String, JavaRewrite> map = new TreeMap<>();
for (String qualifiedName : compiler.publicTopLevelTypes()) {
if (qualifiedName.endsWith("." + simpleName)) {
if (qualifiedName.endsWith("." + searchName)) {
if (isField) {
qualifiedName = qualifiedName.substring(0, qualifiedName.lastIndexOf('.'));
qualifiedName += simpleName;
}
String name = e.getDataContext().getString(R.string.import_class_name, qualifiedName);
JavaRewrite addImport = new AddImport(file.toFile(), qualifiedName);
map.put(name, addImport);
}
}
}
if (map.size() == 1) {
RewriteUtil.performRewrite(editor, file.toFile(), compiler, map.values().iterator().next());
} else {
String[] titles = map.keySet().toArray(new String[0]);
new AlertDialog.Builder(e.getDataContext())
.setTitle(R.string.import_class_title)
.setItems(
titles,
(di, w) -> {
JavaRewrite rewrite = map.get(titles[w]);
RewriteUtil.performRewrite(editor, file.toFile(), compiler, rewrite);
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
}
}
| 4,863 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ExpressionTreePattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/ExpressionTreePattern.java | package com.tyron.completion.java.patterns;
import androidx.annotation.NonNull;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.InitialPatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
import org.jetbrains.kotlin.com.intellij.util.containers.ContainerUtil;
public class ExpressionTreePattern<
T extends ExpressionTree, Self extends ExpressionTreePattern<T, Self>>
extends JavacTreePattern<T, Self> {
protected ExpressionTreePattern(@NonNull InitialPatternCondition<T> condition) {
super(condition);
}
protected ExpressionTreePattern(Class<T> aClass) {
super(aClass);
}
public MethodInvocationTreePattern methodCall(
final ElementPattern<? extends MethodInvocationTree> method) {
final JavacTreeNamePatternCondition nameCondition =
ContainerUtil.findInstance(
method.getCondition().getConditions(), JavacTreeNamePatternCondition.class);
return new MethodInvocationTreePattern()
.and(this)
.with(
new PatternCondition<MethodInvocationTree>("methodCall") {
@Override
public boolean accepts(
@NotNull MethodInvocationTree t, ProcessingContext processingContext) {
return false;
}
});
}
public static class Capture<T extends ExpressionTree>
extends ExpressionTreePattern<T, Capture<T>> {
protected Capture(@NonNull InitialPatternCondition<T> condition) {
super(condition);
}
protected Capture(Class<T> aClass) {
super(aClass);
}
}
}
| 1,858 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavacFieldPattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/JavacFieldPattern.java | package com.tyron.completion.java.patterns;
import androidx.annotation.NonNull;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.completion.java.patterns.elements.JavacElementPatternCondition;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.VariableElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.InitialPatternCondition;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public class JavacFieldPattern<T extends Tree>
extends JavacTreeMemberPattern<T, JavacFieldPattern<T>> {
protected JavacFieldPattern(@NonNull InitialPatternCondition<T> condition) {
super(condition);
}
protected JavacFieldPattern(Class<T> aClass) {
super(aClass);
}
public JavacFieldPattern<T> withType(@NonNull String fqn) {
return withType(JavacTreePatterns.classTree().withQualifiedName(fqn));
}
public JavacFieldPattern<T> withType(@NonNull ElementPattern<? extends ClassTree> pattern) {
return with(
new JavacElementPatternCondition<T>("withType") {
@Override
public boolean accepts(@NonNull Element element, ProcessingContext context) {
if (element.getKind() == ElementKind.FIELD) {
VariableElement variableElement = (VariableElement) element;
}
return pattern.accepts(element, context);
}
@Override
public boolean accepts(@NotNull T t, ProcessingContext context) {
if (t instanceof VariableTree) {
Tree type = ((VariableTree) t).getType();
if (type == null) {
return false;
}
Trees trees = (Trees) context.get("trees");
CompilationUnitTree root = (CompilationUnitTree) context.get("root");
TreePath path = trees.getPath(root, type);
if (path == null) {
return false;
}
Element element = trees.getElement(path);
return pattern.accepts(element, context);
}
return false;
}
});
}
}
| 2,438 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
PsiElementPatterns.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/PsiElementPatterns.java | package com.tyron.completion.java.patterns;
import static org.jetbrains.kotlin.com.intellij.patterns.PsiJavaPatterns.psiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.openapi.util.TextRange;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.psi.PsiElement;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public class PsiElementPatterns {
public static @NotNull org.jetbrains.kotlin.com.intellij.patterns.PsiJavaElementPattern.Capture<
PsiElement>
insideStarting(final ElementPattern<? extends PsiElement> ancestor) {
return psiElement()
.with(
new PatternCondition<PsiElement>("insideStarting") {
@Override
public boolean accepts(@NotNull PsiElement start, ProcessingContext context) {
PsiElement element = start.getParent();
TextRange range = start.getTextRange();
if (range == null) return false;
int startOffset = range.getStartOffset();
while (element != null
&& element.getTextRange() != null
&& element.getTextRange().getStartOffset() == startOffset) {
if (ancestor.accepts(element, context)) {
return true;
}
element = element.getParent();
}
return false;
}
});
}
public static @NotNull org.jetbrains.kotlin.com.intellij.patterns.PsiJavaElementPattern.Capture<
PsiElement>
withParents(Class<? extends PsiElement>... types) {
return psiElement()
.with(
new PatternCondition<PsiElement>("withParents") {
@Override
public boolean accepts(
@NotNull PsiElement psiElement, ProcessingContext processingContext) {
PsiElement parent = psiElement.getContext();
for (Class<? extends PsiElement> type : types) {
if (parent == null || !type.isInstance(parent)) {
return false;
}
parent = parent.getContext();
}
return true;
}
});
}
}
| 2,401 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
PsiNameValuePairPattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/PsiNameValuePairPattern.java | package com.tyron.completion.java.patterns;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.PsiElementPattern;
import org.jetbrains.kotlin.com.intellij.psi.PsiNameValuePair;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
/**
* @author peter
*/
public final class PsiNameValuePairPattern
extends PsiElementPattern<PsiNameValuePair, PsiNameValuePairPattern> {
static final PsiNameValuePairPattern NAME_VALUE_PAIR_PATTERN = new PsiNameValuePairPattern();
private PsiNameValuePairPattern() {
super(PsiNameValuePair.class);
}
@NotNull
public PsiNameValuePairPattern withName(@NotNull @NonNls final String requiredName) {
return with(
new PatternCondition<PsiNameValuePair>("withName") {
@Override
public boolean accepts(
@NotNull final PsiNameValuePair psiNameValuePair, final ProcessingContext context) {
String actualName = psiNameValuePair.getName();
return requiredName.equals(actualName)
|| actualName == null && "value".equals(requiredName);
}
});
}
}
| 1,254 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ModifierTreePattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/ModifierTreePattern.java | package com.tyron.completion.java.patterns;
import androidx.annotation.NonNull;
import com.sun.source.tree.ModifiersTree;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.patterns.InitialPatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
import org.jetbrains.kotlin.com.intellij.util.containers.ContainerUtil;
public class ModifierTreePattern extends JavacTreePattern<ModifiersTree, ModifierTreePattern> {
protected ModifierTreePattern(@NonNull InitialPatternCondition<ModifiersTree> condition) {
super(condition);
}
protected ModifierTreePattern(Class<ModifiersTree> aClass) {
super(aClass);
}
public ModifierTreePattern withModifiers(final String... modifiers) {
return with(
new PatternCondition<ModifiersTree>("withModifiers") {
@Override
public boolean accepts(@NotNull ModifiersTree tree, ProcessingContext processingContext) {
return ContainerUtil.and(
modifiers, t -> tree.getFlags().stream().anyMatch(it -> it.toString().equals(t)));
}
});
}
public static class Capture extends ModifierTreePattern {
protected Capture(@NonNull InitialPatternCondition<ModifiersTree> condition) {
super(condition);
}
}
}
| 1,369 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ClassTreePattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/ClassTreePattern.java | package com.tyron.completion.java.patterns;
import static com.tyron.completion.java.util.TreeUtil.*;
import static org.jetbrains.kotlin.com.intellij.patterns.StandardPatterns.string;
import androidx.annotation.NonNull;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.completion.java.patterns.elements.JavacElementPatternCondition;
import javax.lang.model.element.Element;
import javax.lang.model.util.Elements;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.InitialPatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public class ClassTreePattern extends JavacTreeMemberPattern<ClassTree, ClassTreePattern> {
protected ClassTreePattern(@NonNull InitialPatternCondition<ClassTree> condition) {
super(condition);
}
protected ClassTreePattern(Class<ClassTree> aClass) {
super(aClass);
}
public ClassTreePattern inheritorOf(boolean strict, final ClassTreePattern pattern) {
return with(
new PatternCondition<ClassTree>("inheritorOf") {
@Override
public boolean accepts(@NotNull ClassTree t, ProcessingContext context) {
return false;
}
});
}
private static boolean isInheritor(
ClassTree classTree,
ElementPattern pattern,
final ProcessingContext matchingContext,
boolean checkThisClass) {
if (classTree == null) return false;
if (checkThisClass && pattern.accepts(classTree, matchingContext)) return true;
return false;
}
public ClassTreePattern isInterface() {
return with(
new PatternCondition<ClassTree>("isInterface") {
@Override
public boolean accepts(
@NotNull ClassTree classTree, ProcessingContext processingContext) {
return classTree.getKind() == Tree.Kind.INTERFACE;
}
});
}
public ClassTreePattern withField(final boolean checkDeep, final ElementPattern memberPattern) {
return with(
new JavacElementPatternCondition<ClassTree>("withField") {
@Override
public boolean accepts(@NotNull ClassTree classTree, ProcessingContext context) {
for (Tree member : classTree.getMembers()) {
if (member.getKind() != Tree.Kind.VARIABLE) {
continue;
}
if (memberPattern.accepts(member, context)) {
return true;
}
}
return false;
}
@Override
public boolean accepts(@NonNull Element element, ProcessingContext processingContext) {
return false;
}
});
}
public ClassTreePattern withMethod(
final boolean checkDeep, final ElementPattern<? extends Tree> memberPattern) {
return with(
new PatternCondition<ClassTree>("withMethod") {
@Override
public boolean accepts(@NotNull ClassTree classTree, ProcessingContext context) {
if (checkDeep) {
Trees trees = (Trees) context.get("trees");
if (trees == null) {
return false;
}
Elements elements = (Elements) context.get("elements");
if (elements == null) {
return false;
}
CompilationUnitTree root = (CompilationUnitTree) context.get("root");
if (root == null) {
return false;
}
TreePath path = trees.getPath(root, classTree);
for (MethodTree methodTree : getAllMethods(trees, elements, path)) {
if (memberPattern.accepts(methodTree, context)) {
return true;
}
}
} else {
for (MethodTree method : getMethods(classTree)) {
if (memberPattern.accepts(method, context)) {
return true;
}
}
}
return false;
}
});
}
public ClassTreePattern withQualifiedName(@NonNull final String qname) {
return with(new ClassTreeNamePatternCondition(string().equalTo(qname)));
}
}
| 4,500 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
PsiAnnotationPattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/PsiAnnotationPattern.java | package com.tyron.completion.java.patterns;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.PsiElementPattern;
import org.jetbrains.kotlin.com.intellij.psi.PsiAnnotation;
import org.jetbrains.kotlin.com.intellij.psi.PsiArrayInitializerMemberValue;
import org.jetbrains.kotlin.com.intellij.psi.PsiElement;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public final class PsiAnnotationPattern
extends PsiElementPattern<PsiAnnotation, PsiAnnotationPattern> {
public static final PsiAnnotationPattern PSI_ANNOTATION_PATTERN = new PsiAnnotationPattern();
private PsiAnnotationPattern() {
super(PsiAnnotation.class);
}
public PsiAnnotationPattern qName(final ElementPattern<String> pattern) {
return with(
new PatternCondition<PsiAnnotation>("qName") {
@Override
public boolean accepts(
@NotNull final PsiAnnotation psiAnnotation, final ProcessingContext context) {
return pattern.accepts(psiAnnotation.getQualifiedName(), context);
}
});
}
public PsiAnnotationPattern qName(@NonNls final String qname) {
return with(
new PatternCondition<PsiAnnotation>("qName") {
@Override
public boolean accepts(
@NotNull final PsiAnnotation psiAnnotation, final ProcessingContext context) {
return psiAnnotation.hasQualifiedName(qname);
}
});
}
public PsiAnnotationPattern insideAnnotationAttribute(
@NotNull final String attributeName,
@NotNull final ElementPattern<? extends PsiAnnotation> parentAnnoPattern) {
return with(
new PatternCondition<PsiAnnotation>("insideAnnotationAttribute") {
final PsiNameValuePairPattern attrPattern =
PsiNameValuePairPattern.NAME_VALUE_PAIR_PATTERN
.withName(attributeName)
.withSuperParent(2, parentAnnoPattern);
@Override
public boolean accepts(@NotNull PsiAnnotation annotation, ProcessingContext context) {
PsiElement attr = getParentElement(annotation);
if (attr instanceof PsiArrayInitializerMemberValue) attr = getParentElement(attr);
return attrPattern.accepts(attr);
}
});
}
private PsiElement getParentElement(@NotNull PsiElement element) {
return getParent(element);
}
}
| 2,589 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
MethodTreePattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/MethodTreePattern.java | package com.tyron.completion.java.patterns;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.completion.java.patterns.elements.JavacElementPattern;
import com.tyron.completion.java.patterns.elements.JavacElementPatternConditionPlus;
import java.util.List;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.InitialPatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.util.PairProcessor;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public class MethodTreePattern<T extends Tree, Self extends MethodTreePattern<T, Self>>
extends JavacTreeMemberPattern<T, Self> implements JavacElementPattern {
protected MethodTreePattern(@NonNull InitialPatternCondition<T> condition) {
super(condition);
}
protected MethodTreePattern(Class<T> aClass) {
super(aClass);
}
public Self definedInClass(String fqn) {
return definedInClass(JavacTreePatterns.classTree().withQualifiedName(fqn));
}
public Self definedInClass(ElementPattern<? extends ClassTree> pattern) {
return with(
new JavacElementPatternConditionPlus<Tree, Tree>("definedInClass", pattern) {
@Override
public boolean processValues(
Element target,
ProcessingContext context,
PairProcessor<Element, ProcessingContext> processor) {
if (!processor.process(target.getEnclosingElement(), context)) {
return false;
}
for (Element enclosedElement : target.getEnclosedElements()) {
System.out.println(enclosedElement);
}
return true;
}
@Override
public boolean processValues(
Tree t, ProcessingContext context, PairProcessor<Tree, ProcessingContext> processor) {
Trees trees = (Trees) context.get("trees");
CompilationUnitTree root = (CompilationUnitTree) context.get("root");
Elements elements = (Elements) context.get("elements");
if (t instanceof MethodInvocationTree) {
MethodInvocationTree invocationTree = (MethodInvocationTree) t;
ExpressionTree methodSelect = invocationTree.getMethodSelect();
TreePath path = trees.getPath(root, methodSelect);
if (!processor.process(path.getLeaf(), context)) {
return false;
}
ExecutableElement element = (ExecutableElement) trees.getElement(path);
Element enclosingElement = element.getEnclosingElement();
List<? extends Element> allMembers =
elements.getAllMembers((TypeElement) enclosingElement);
for (Element allMember : allMembers) {
if (allMember.getKind() != ElementKind.METHOD) {
continue;
}
if (!getValuePattern().accepts(allMember.getEnclosingElement(), context)) {
return false;
}
}
return true;
}
return true;
}
});
}
@Override
public @NotNull Self with(@NotNull PatternCondition<? super T> pattern) {
return super.with(pattern);
}
@Override
public boolean accepts(@Nullable Object o, ProcessingContext context) {
if (o instanceof MethodTree) {
return super.accepts(o, context);
}
if (o instanceof Tree) {
T invocation = (T) o;
for (PatternCondition<? super T> condition : getCondition().getConditions()) {
if (!condition.accepts(invocation, context)) {
return false;
}
}
return true;
}
return false;
}
@Override
public boolean accepts(Element element, ProcessingContext context) {
return accepts((Object) element, context);
}
public static class Capture<T extends Tree> extends MethodTreePattern<T, Capture<T>> {
protected Capture(@NonNull InitialPatternCondition<T> condition) {
super(condition);
}
protected Capture(Class<T> aClass) {
super(aClass);
}
}
}
| 4,802 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavacTreePatterns.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/JavacTreePatterns.java | package com.tyron.completion.java.patterns;
import androidx.annotation.Nullable;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.InitialPatternConditionPlus;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public class JavacTreePatterns {
public static JavacTreePattern.Capture<Tree> tree() {
return new JavacTreePattern.Capture<>(Tree.class);
}
public static <T extends Tree> JavacTreePattern.Capture<T> tree(Class<T> clazz) {
return new JavacTreePattern.Capture<>(clazz);
}
public static ClassTreePattern classTree() {
return new ClassTreePattern(ClassTree.class);
}
public static ModifierTreePattern modifiers() {
return new ModifierTreePattern(ModifiersTree.class);
}
public static ExpressionTreePattern.Capture<ExpressionTree> expression() {
return new ExpressionTreePattern.Capture<>(ExpressionTree.class);
}
public static JavacFieldPattern<VariableTree> variable() {
return new JavacFieldPattern<>(VariableTree.class);
}
public static JavacTreePattern.Capture<LiteralTree> literal() {
return literal(null);
}
public static JavacTreePattern.Capture<LiteralTree> literal(
@Nullable final ElementPattern<?> value) {
return new JavacTreePattern.Capture<>(
new InitialPatternConditionPlus<LiteralTree>(LiteralTree.class) {
@Override
public boolean accepts(@Nullable Object o, ProcessingContext context) {
return o instanceof LiteralTree
&& (value == null || value.accepts(((LiteralTree) o).getValue(), context));
}
});
}
public static JavacTreeElementPattern.Capture<LiteralTree> literalExpression(
@Nullable final ElementPattern<?> value) {
return new JavacTreeElementPattern.Capture<>(
new InitialPatternConditionPlus<LiteralTree>(LiteralTree.class) {
@Override
public boolean accepts(@Nullable Object o, ProcessingContext context) {
return o instanceof LiteralTree
&& (value == null || value.accepts(((LiteralTree) o).getValue(), context));
}
});
}
public static MethodTreePattern.Capture<Tree> method() {
return new MethodTreePattern.Capture<>(Tree.class);
}
public static MethodInvocationTreePattern methodInvocation() {
return new MethodInvocationTreePattern();
}
}
| 2,657 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavacTreeElementPattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/JavacTreeElementPattern.java | package com.tyron.completion.java.patterns;
import java.util.Arrays;
import java.util.Collection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.InitialPatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.ObjectPattern;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.PatternConditionPlus;
import org.jetbrains.kotlin.com.intellij.patterns.PsiElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.StandardPatterns;
import org.jetbrains.kotlin.com.intellij.util.PairProcessor;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
/**
* Provides patterns for tree-like objects.
*
* <p>Please see the <a
* href="https://plugins.jetbrains.com/docs/intellij/element-patterns.html">IntelliJ Platform
* Docs</a> for a high-level overview.
*
* @see PsiElementPattern
*/
public abstract class JavacTreeElementPattern<
ParentType, T extends ParentType, Self extends JavacTreeElementPattern<ParentType, T, Self>>
extends ObjectPattern<T, Self> {
protected JavacTreeElementPattern(@NotNull final InitialPatternCondition<T> condition) {
super(condition);
}
protected JavacTreeElementPattern(final Class<T> aClass) {
super(aClass);
}
@Nullable
protected abstract ParentType getParent(
ProcessingContext context, @NotNull ParentType parentType);
protected abstract ParentType[] getChildren(@NotNull final ParentType parentType);
@SafeVarargs
public final Self withParents(final Class<? extends ParentType>... types) {
return with(
new PatternCondition<T>("withParents") {
@Override
public boolean accepts(@NotNull T t, ProcessingContext context) {
ParentType current = getParent(context, t);
for (Class<? extends ParentType> type : types) {
if (current == null || !type.isInstance(current)) {
return false;
}
current = getParent(context, current);
}
return true;
}
});
}
public Self withParent(@NotNull final Class<? extends ParentType> type) {
return withParent(StandardPatterns.instanceOf(type));
}
@NotNull
public Self withParent(@NotNull final ElementPattern<? extends ParentType> pattern) {
return withSuperParent(1, pattern);
}
// public Self withChild(@NotNull final ElementPattern<? extends ParentType> pattern) {
// return withChildren(StandardPatterns.<ParentType>collection().atLeastOne(pattern));
// }
//
// public Self withFirstChild(@NotNull final ElementPattern<? extends ParentType> pattern) {
// return withChildren(StandardPatterns.<ParentType>collection().first(pattern));
// }
//
// public Self withLastChild(@NotNull final ElementPattern<? extends ParentType> pattern) {
// return withChildren(StandardPatterns.<ParentType>collection().last(pattern));
// }
public Self withChildren(@NotNull final ElementPattern<Collection<ParentType>> pattern) {
return with(
new PatternConditionPlus<T, Collection<ParentType>>("withChildren", pattern) {
@Override
public boolean processValues(
T t,
ProcessingContext context,
PairProcessor<Collection<ParentType>, ProcessingContext> processor) {
return processor.process(Arrays.asList(getChildren(t)), context);
}
});
}
public Self isFirstAcceptedChild(@NotNull final ElementPattern<? super ParentType> pattern) {
return with(
new PatternCondition<T>("isFirstAcceptedChild") {
@Override
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
final ParentType parent = getParent(context, t);
if (parent != null) {
final ParentType[] children = getChildren(parent);
for (ParentType child : children) {
if (pattern.accepts(child, context)) {
return child == t;
}
}
}
return false;
}
});
}
public Self withSuperParent(final int level, @NotNull final Class<? extends ParentType> aClass) {
return withSuperParent(level, StandardPatterns.instanceOf(aClass));
}
public Self withSuperParent(
final int level, @NotNull final ElementPattern<? extends ParentType> pattern) {
return with(
new PatternConditionPlus<T, ParentType>(
level == 1 ? "withParent" : "withSuperParent", pattern) {
@Override
public boolean processValues(
T t,
ProcessingContext context,
PairProcessor<ParentType, ProcessingContext> processor) {
ParentType parent = t;
for (int i = 0; i < level; i++) {
if (parent == null) return true;
parent = getParent(context, parent);
}
return processor.process(parent, context);
}
});
}
public Self inside(@NotNull final Class<? extends ParentType> pattern) {
return inside(StandardPatterns.instanceOf(pattern));
}
public Self inside(@NotNull final ElementPattern<? extends ParentType> pattern) {
return inside(false, pattern);
}
public Self inside(
final boolean strict, @NotNull final ElementPattern<? extends ParentType> pattern) {
return with(
new PatternConditionPlus<T, ParentType>("inside", pattern) {
@Override
public boolean processValues(
T t,
ProcessingContext context,
PairProcessor<ParentType, ProcessingContext> processor) {
ParentType element = strict ? getParent(context, t) : t;
while (element != null) {
if (!processor.process(element, context)) return false;
element = getParent(context, element);
}
return true;
}
});
}
public Self withAncestor(
final int levelsUp, @NotNull final ElementPattern<? extends ParentType> pattern) {
return with(
new PatternCondition<T>("withAncestor") {
@Override
public boolean accepts(@NotNull T t, ProcessingContext context) {
ParentType element = t;
for (int i = 0; i < levelsUp + 1; i++) {
if (pattern.accepts(element, context)) return true;
element = getParent(context, element);
if (element == null) break;
}
return false;
}
});
}
public Self inside(
final boolean strict,
@NotNull final ElementPattern<? extends ParentType> pattern,
@NotNull final ElementPattern<? extends ParentType> stopAt) {
return with(
new PatternCondition<T>("inside") {
@Override
public boolean accepts(@NotNull T t, ProcessingContext context) {
ParentType element = strict ? getParent(context, t) : t;
while (element != null) {
if (stopAt.accepts(element, context)) return false;
if (pattern.accepts(element, context)) return true;
element = getParent(context, element);
}
return false;
}
});
}
/**
* @return Ensures that first elements in hierarchy accepted by patterns appear in specified order
*/
@SafeVarargs
public final Self insideSequence(
final boolean strict, final ElementPattern<? extends ParentType>... patterns) {
return with(
new PatternCondition<T>("insideSequence") {
@Override
public boolean accepts(@NotNull final T t, final ProcessingContext context) {
int i = 0;
ParentType element = strict ? getParent(context, t) : t;
while (element != null && i < patterns.length) {
for (int j = i; j < patterns.length; j++) {
if (patterns[j].accepts(element, context)) {
if (i != j) return false;
i++;
break;
}
}
element = getParent(context, element);
}
return true;
}
});
}
public Self afterSibling(final ElementPattern<? extends ParentType> pattern) {
return with(
new PatternCondition<T>("afterSibling") {
@Override
public boolean accepts(@NotNull T t, ProcessingContext context) {
final ParentType parent = getParent(context, t);
if (parent == null) return false;
final ParentType[] children = getChildren(parent);
final int i = Arrays.asList(children).indexOf(t);
if (i <= 0) return false;
return pattern.accepts(children[i - 1], context);
}
});
}
public Self afterSiblingSkipping(
@NotNull final ElementPattern skip, final ElementPattern<? extends ParentType> pattern) {
return with(
new PatternCondition<T>("afterSiblingSkipping") {
@Override
public boolean accepts(@NotNull T t, ProcessingContext context) {
final ParentType parent = getParent(context, t);
if (parent == null) return false;
final ParentType[] children = getChildren(parent);
int i = Arrays.asList(children).indexOf(t);
while (--i >= 0) {
if (!skip.accepts(children[i], context)) {
return pattern.accepts(children[i], context);
}
}
return false;
}
});
}
}
| 9,787 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavacTreePattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/JavacTreePattern.java | package com.tyron.completion.java.patterns;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.lang.model.element.ExecutableElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.InitialPatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.StandardPatterns;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
import org.jetbrains.kotlin.com.intellij.util.containers.ContainerUtil;
public class JavacTreePattern<T extends Tree, Self extends JavacTreePattern<T, Self>>
extends JavacTreeElementPattern<Tree, T, Self> {
protected JavacTreePattern(@NonNull InitialPatternCondition<T> condition) {
super(condition);
}
protected JavacTreePattern(Class<T> aClass) {
super(aClass);
}
protected TreePath getPath(ProcessingContext context, Tree tree) {
Trees trees = (Trees) context.get("trees");
if (trees == null) {
return null;
}
CompilationUnitTree root = (CompilationUnitTree) context.get("root");
if (root == null) {
return null;
}
return trees.getPath(root, tree);
}
@Nullable
@Override
protected Tree getParent(ProcessingContext context, @NonNull Tree tree) {
TreePath path = getPath(context, tree);
if (path == null) {
return null;
}
TreePath parent = path.getParentPath();
if (parent == null) {
return null;
}
return parent.getLeaf();
}
@Override
protected Tree[] getChildren(@NonNull Tree tree) {
if (tree instanceof ExpressionStatementTree) {
return new Tree[] {((ExpressionStatementTree) tree).getExpression()};
}
if (tree instanceof MethodInvocationTree) {
List<Tree> children = new ArrayList<>();
ExpressionTree methodSelect = ((MethodInvocationTree) tree).getMethodSelect();
while (methodSelect != null) {
children.add(methodSelect);
if (methodSelect instanceof MemberSelectTree) {
methodSelect = ((MemberSelectTree) methodSelect).getExpression();
} else {
methodSelect = null;
}
}
Collections.reverse(children);
return children.toArray(new Tree[0]);
}
return new Tree[0];
}
public Self methodCallParameter(final int index, final ElementPattern<?> methodPattern) {
final JavacTreeNamePatternCondition nameCondition =
ContainerUtil.findInstance(
methodPattern.getCondition().getConditions(), JavacTreeNamePatternCondition.class);
return with(
new PatternCondition<T>("methodCallParameter") {
@Override
public boolean accepts(@NotNull T t, ProcessingContext context) {
Tree parent = getParent(context, t);
if (parent instanceof MethodInvocationTree) {
MethodInvocationTree method = (MethodInvocationTree) parent;
List<? extends ExpressionTree> arguments = method.getArguments();
if (index >= arguments.size()) {
return false;
}
return checkCall(context, method, methodPattern, nameCondition);
}
return false;
}
});
}
private static boolean checkCall(
ProcessingContext context,
MethodInvocationTree tree,
ElementPattern<?> methodPattern,
JavacTreeNamePatternCondition nameCondition) {
Trees trees = (Trees) context.get("trees");
CompilationUnitTree root = (CompilationUnitTree) context.get("root");
TreePath path = trees.getPath(root, tree);
ExecutableElement element = (ExecutableElement) trees.getElement(path);
if (nameCondition != null
&& !nameCondition.getNamePattern().accepts(element.getSimpleName().toString())) {
return false;
}
return methodPattern.accepts(tree, context);
}
@NonNull
public Self withName(@NonNull String name) {
return withName(StandardPatterns.string().equalTo(name));
}
@NonNull
public Self withName(@NonNull final String... names) {
return withName(StandardPatterns.string().oneOf(names));
}
@NonNull
public Self withName(@NonNull ElementPattern<String> name) {
return with(new JavacTreeNamePatternCondition("withName", name));
}
public static class Capture<T extends Tree> extends JavacTreePattern<T, Capture<T>> {
protected Capture(@NonNull InitialPatternCondition<T> condition) {
super(condition);
}
protected Capture(Class<T> aClass) {
super(aClass);
}
}
}
| 5,051 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavacTreeMemberPattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/JavacTreeMemberPattern.java | package com.tyron.completion.java.patterns;
import androidx.annotation.NonNull;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.Tree;
import com.tyron.completion.java.patterns.elements.JavacElementPattern;
import com.tyron.completion.java.patterns.elements.JavacElementPatternConditionPlus;
import javax.lang.model.element.Element;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.InitialPatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.util.PairProcessor;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public class JavacTreeMemberPattern<T extends Tree, Self extends JavacTreeMemberPattern<T, Self>>
extends JavacTreePattern<T, Self> implements JavacElementPattern {
protected JavacTreeMemberPattern(@NonNull InitialPatternCondition<T> condition) {
super(condition);
}
protected JavacTreeMemberPattern(Class<T> aClass) {
super(aClass);
}
public Self inClass(@NonNull String fqn) {
return inClass(JavacTreePatterns.classTree().withQualifiedName(fqn));
}
public Self inClass(final ElementPattern elementPattern) {
return with(
new JavacElementPatternConditionPlus<T, ClassTree>("inClass", elementPattern) {
@Override
public boolean processValues(
T t,
ProcessingContext processingContext,
PairProcessor<ClassTree, ProcessingContext> pairProcessor) {
return elementPattern.accepts(t, processingContext);
}
@Override
public boolean processValues(
Element target,
ProcessingContext context,
PairProcessor<Element, ProcessingContext> processor) {
return false;
}
});
}
@Override
public boolean accepts(@Nullable Object o, ProcessingContext context) {
if (o instanceof Tree) {
return super.accepts(o, context);
}
if (o instanceof Element) {
Element element = (Element) o;
for (PatternCondition<? super T> condition : getCondition().getConditions()) {
if (condition instanceof JavacElementPattern) {
if (!((JavacElementPattern) condition).accepts(element, context)) {
return false;
}
}
}
return true;
}
return false;
}
@Override
public boolean accepts(Element element, ProcessingContext context) {
return accepts((Object) element, context);
}
}
| 2,606 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavacTreeNamePatternCondition.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/JavacTreeNamePatternCondition.java | package com.tyron.completion.java.patterns;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.tyron.completion.java.patterns.elements.JavacElementPattern;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.lang.model.element.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.PatternConditionPlus;
import org.jetbrains.kotlin.com.intellij.util.PairProcessor;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public class JavacTreeNamePatternCondition extends PatternConditionPlus<Tree, String>
implements JavacElementPattern {
public JavacTreeNamePatternCondition(@NonNls String methodName, ElementPattern valuePattern) {
super(methodName, valuePattern);
}
public @Nullable String getPropertyValue(@NotNull Object o) {
if (o instanceof MethodInvocationTree) {
MethodInvocationTree invocationTree = (MethodInvocationTree) o;
ExpressionTree methodSelect = invocationTree.getMethodSelect();
if (methodSelect.getKind() == Tree.Kind.IDENTIFIER) {
return methodSelect.toString();
} else {
MemberSelectTree memberSelectTree = (MemberSelectTree) methodSelect;
return memberSelectTree.getIdentifier().toString();
}
}
if (o instanceof Tree) {
try {
Method method = o.getClass().getMethod("getName");
Object invoke = method.invoke(o);
if (invoke != null) {
return invoke.toString();
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
}
try {
Method method = o.getClass().getMethod("getSimpleName");
Object invoke = method.invoke(o);
if (invoke != null) {
return invoke.toString();
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
return null;
}
}
return null;
}
@Override
public boolean processValues(
Tree tree, ProcessingContext context, PairProcessor<String, ProcessingContext> processor) {
return processor.process(getPropertyValue(tree), context);
}
@Override
public boolean accepts(Element element, ProcessingContext context) {
return getNamePattern().accepts(element.getSimpleName().toString(), context);
}
public ElementPattern<Tree> getNamePattern() {
return getValuePattern();
}
}
| 2,717 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ClassTreeNamePatternCondition.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/ClassTreeNamePatternCondition.java | package com.tyron.completion.java.patterns;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.Trees;
import com.sun.tools.javac.code.Symbol;
import com.tyron.completion.java.patterns.elements.JavacElementPattern;
import com.tyron.completion.java.util.FindQualifiedName;
import javax.lang.model.element.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public class ClassTreeNamePatternCondition extends PatternCondition<ClassTree>
implements JavacElementPattern {
private final ElementPattern<String> namePattern;
public ClassTreeNamePatternCondition(ElementPattern<String> pattern) {
this("withQualifiedName", pattern);
}
public ClassTreeNamePatternCondition(
@Nullable @NonNls String debugMethodName, ElementPattern<String> pattern) {
super(debugMethodName);
namePattern = pattern;
}
@Override
public boolean accepts(@NotNull ClassTree t, ProcessingContext context) {
Trees trees = (Trees) context.get("trees");
if (trees == null) {
return false;
}
CompilationUnitTree root = (CompilationUnitTree) context.get("root");
if (root == null) {
return false;
}
String name = new FindQualifiedName().scan(root, t);
return namePattern.accepts(name, context);
}
public ElementPattern<String> getNamePattern() {
return namePattern;
}
@Override
public boolean accepts(Element element, ProcessingContext context) {
if (element instanceof Symbol.ClassSymbol) {
String name = ((Symbol.ClassSymbol) element).fullname.toString();
return namePattern.accepts(name, context);
} else if (element instanceof Symbol.MethodSymbol) {
String s = ((Symbol.MethodSymbol) element).name.toString();
return namePattern.accepts(s, context);
}
return false;
}
}
| 2,123 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
MethodInvocationTreePattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/MethodInvocationTreePattern.java | package com.tyron.completion.java.patterns;
import androidx.annotation.NonNull;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import javax.lang.model.element.ExecutableElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.InitialPatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public class MethodInvocationTreePattern
extends ExpressionTreePattern<MethodInvocationTree, MethodInvocationTreePattern> {
public MethodInvocationTreePattern() {
this(MethodInvocationTree.class);
}
protected MethodInvocationTreePattern(
@NonNull InitialPatternCondition<MethodInvocationTree> condition) {
super(condition);
}
protected MethodInvocationTreePattern(Class<MethodInvocationTree> aClass) {
super(aClass);
}
@NonNull
public MethodInvocationTreePattern withName(@NonNull final String name) {
return with(
new PatternCondition<MethodInvocationTree>("withName") {
@Override
public boolean accepts(@NotNull MethodInvocationTree t, ProcessingContext context) {
Trees trees = (Trees) context.get("trees");
CompilationUnitTree root = (CompilationUnitTree) context.get("root");
TreePath path = trees.getPath(root, t);
ExecutableElement element = (ExecutableElement) trees.getElement(path);
return element.getSimpleName().contentEquals(name);
}
});
}
public MethodInvocationTreePattern withQualifier(
final ElementPattern<? extends ExpressionTree> pattern) {
return with(
new PatternCondition<MethodInvocationTree>("withQualifier") {
@Override
public boolean accepts(
@NotNull MethodInvocationTree methodInvocationTree,
ProcessingContext processingContext) {
ExpressionTree methodSelect = methodInvocationTree.getMethodSelect();
if (methodSelect instanceof IdentifierTree) {
return false;
} else {
MemberSelectTree memberSelectTree = (MemberSelectTree) methodSelect;
return pattern.accepts(memberSelectTree.getExpression(), processingContext);
}
}
});
}
private String getMethodName(MethodInvocationTree tree) {
ExpressionTree methodSelect = tree.getMethodSelect();
while (methodSelect != null) {
if (methodSelect instanceof IdentifierTree) {
return ((IdentifierTree) methodSelect).getName().toString();
}
if (methodSelect instanceof MemberSelectTree) {
methodSelect = ((MemberSelectTree) methodSelect).getExpression();
} else {
methodSelect = null;
}
}
return null;
}
}
| 3,130 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavacElementPatternCondition.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/elements/JavacElementPatternCondition.java | package com.tyron.completion.java.patterns.elements;
import javax.lang.model.element.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public abstract class JavacElementPatternCondition<T> extends PatternCondition<T>
implements JavacElementPattern {
public JavacElementPatternCondition(@Nullable @NonNls String debugMethodName) {
super(debugMethodName);
}
@Override
public abstract boolean accepts(@NotNull Element element, ProcessingContext processingContext);
}
| 701 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavacElementPattern.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/elements/JavacElementPattern.java | package com.tyron.completion.java.patterns.elements;
import javax.lang.model.element.Element;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public interface JavacElementPattern {
boolean accepts(Element element, ProcessingContext context);
}
| 265 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavacElementPatternConditionPlus.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/patterns/elements/JavacElementPatternConditionPlus.java | package com.tyron.completion.java.patterns.elements;
import javax.lang.model.element.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.PatternConditionPlus;
import org.jetbrains.kotlin.com.intellij.util.PairProcessor;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
public abstract class JavacElementPatternConditionPlus<Target, Value>
extends PatternConditionPlus<Target, Value> implements JavacElementPattern {
public JavacElementPatternConditionPlus(@NonNls String methodName, ElementPattern valuePattern) {
super(methodName, valuePattern);
}
@Override
public boolean accepts(Element element, ProcessingContext context) {
return processValues(
element, context, (value, context1) -> getValuePattern().accepts(value, context1));
}
public abstract boolean processValues(
Element target,
ProcessingContext context,
PairProcessor<Element, ProcessingContext> processor);
}
| 1,059 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
HoverProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/hover/HoverProvider.java | package com.tyron.completion.java.hover;
import com.sun.source.doctree.DocCommentTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.DocTrees;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.CompilerContainer;
import com.tyron.completion.java.compiler.ParseTask;
import com.tyron.completion.java.provider.FindHelper;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.tools.JavaFileObject;
public class HoverProvider {
final CompilerProvider compiler;
public static final List<String> NOT_SUPPORTED = Collections.emptyList();
public HoverProvider(CompilerProvider provider) {
compiler = provider;
}
public List<String> hover(Path file, int offset) {
CompilerContainer container = compiler.compile(file);
return container.get(
task -> {
Element element = new FindHoverElement(task.task).scan(task.root(), (long) offset);
if (element == null) {
return NOT_SUPPORTED;
}
List<String> list = new ArrayList<>();
String code = printType(element);
list.add(code);
String docs = docs(task, element);
if (!docs.isEmpty()) {
list.add(docs);
}
return list;
});
}
public String docs(CompileTask task, Element element) {
if (element instanceof TypeElement) {
TypeElement type = (TypeElement) element;
String className = type.getQualifiedName().toString();
Optional<JavaFileObject> file = compiler.findAnywhere(className);
if (!file.isPresent()) return "";
ParseTask parse = compiler.parse(file.get());
Tree tree = FindHelper.findType(parse, className);
return docs(parse, tree);
} else if (element.getKind() == ElementKind.FIELD) {
VariableElement field = (VariableElement) element;
TypeElement type = (TypeElement) field.getEnclosingElement();
String className = type.getQualifiedName().toString();
Optional<JavaFileObject> file = compiler.findAnywhere(className);
if (!file.isPresent()) return "";
ParseTask parse = compiler.parse(file.get());
Tree tree = FindHelper.findType(parse, className);
return docs(parse, tree);
} else if (element instanceof ExecutableElement) {
ExecutableElement method = (ExecutableElement) element;
TypeElement type = (TypeElement) method.getEnclosingElement();
String className = type.getQualifiedName().toString();
String methodName = method.getSimpleName().toString();
String[] erasedParameterTypes = FindHelper.erasedParameterTypes(task, method);
Optional<JavaFileObject> file = compiler.findAnywhere(className);
if (!file.isPresent()) return "";
ParseTask parse = compiler.parse(file.get());
Tree tree = FindHelper.findMethod(parse, className, methodName, erasedParameterTypes);
return docs(parse, tree);
} else {
return "";
}
}
private String docs(ParseTask task, Tree tree) {
TreePath path = Trees.instance(task.task).getPath(task.root, tree);
DocCommentTree docTree = DocTrees.instance(task.task).getDocCommentTree(path);
if (docTree == null) return "";
// TODO: format this
return docTree.toString();
}
private String printType(Element e) {
if (e instanceof ExecutableElement) {
ExecutableElement m = (ExecutableElement) e;
return ShortTypePrinter.DEFAULT.printMethod(m);
} else if (e instanceof VariableElement) {
VariableElement v = (VariableElement) e;
return ShortTypePrinter.DEFAULT.print(v.asType()) + " " + v;
} else if (e instanceof TypeElement) {
TypeElement t = (TypeElement) e;
StringJoiner lines = new StringJoiner("\n");
lines.add(hoverTypeDeclaration(t) + " {");
for (Element member : t.getEnclosedElements()) {
// TODO check accessibility
if (member instanceof ExecutableElement || member instanceof VariableElement) {
lines.add(" " + printType(member) + ";");
} else if (member instanceof TypeElement) {
lines.add(" " + hoverTypeDeclaration((TypeElement) member) + " { /* removed " + "*/ }");
}
}
lines.add("}");
return lines.toString();
} else {
return e.toString();
}
}
private String hoverTypeDeclaration(TypeElement t) {
StringBuilder result = new StringBuilder();
switch (t.getKind()) {
case ANNOTATION_TYPE:
result.append("@interface");
break;
case INTERFACE:
result.append("interface");
break;
case CLASS:
result.append("class");
break;
case ENUM:
result.append("enum");
break;
default:
result.append("_");
}
result.append(" ").append(ShortTypePrinter.DEFAULT.print(t.asType()));
String superType = ShortTypePrinter.DEFAULT.print(t.getSuperclass());
switch (superType) {
case "Object":
case "none":
break;
default:
result.append(" extends ").append(superType);
}
return result.toString();
}
}
| 5,586 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ShortTypePrinter.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/hover/ShortTypePrinter.java | package com.tyron.completion.java.hover;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.*;
import javax.lang.model.util.AbstractTypeVisitor8;
public class ShortTypePrinter extends AbstractTypeVisitor8<String, Void> {
public static final ShortTypePrinter DEFAULT = new ShortTypePrinter("");
public static final ShortTypePrinter NO_PACKAGE = new ShortTypePrinter("*");
private final String packageContext;
private ShortTypePrinter(String packageContext) {
this.packageContext = packageContext;
}
public String print(TypeMirror type) {
return type.accept(new ShortTypePrinter(packageContext), null);
}
@Override
public String visitIntersection(IntersectionType t, Void aVoid) {
return t.getBounds().stream().map(this::print).collect(Collectors.joining(" & "));
}
@Override
public String visitUnion(UnionType t, Void aVoid) {
return t.getAlternatives().stream().map(this::print).collect(Collectors.joining(" | "));
}
@Override
public String visitPrimitive(PrimitiveType t, Void aVoid) {
return t.toString();
}
@Override
public String visitNull(NullType t, Void aVoid) {
return t.toString();
}
@Override
public String visitArray(ArrayType t, Void aVoid) {
return print(t.getComponentType()) + "[]";
}
@Override
public String visitDeclared(DeclaredType t, Void aVoid) {
String result = t.asElement().toString();
if (!t.getTypeArguments().isEmpty()) {
String params =
t.getTypeArguments().stream().map(this::print).collect(Collectors.joining(", "));
result += "<" + params + ">";
}
if (packageContext.equals("*")) return result.substring(result.lastIndexOf('.') + 1);
else if (result.startsWith("java.lang")) return result.substring("java.lang.".length());
else if (result.startsWith("java.util")) return result.substring("java.util.".length());
else if (result.startsWith(packageContext)) return result.substring(packageContext.length());
else return result;
}
@Override
public String visitError(ErrorType t, Void aVoid) {
return "_";
}
@Override
public String visitTypeVariable(TypeVariable t, Void aVoid) {
String result = t.asElement().toString();
// TypeMirror upper = t.getUpperBound();
// NOTE this can create infinite recursion
// if (!upper.toString().equals("java.lang.Object"))
// result += " extends " + print(upper);
return result;
}
@Override
public String visitWildcard(WildcardType t, Void aVoid) {
String result = "?";
if (t.getSuperBound() != null) result += " super " + print(t.getSuperBound());
if (t.getExtendsBound() != null) result += " extends " + print(t.getExtendsBound());
return result;
}
@Override
public String visitExecutable(ExecutableType t, Void aVoid) {
return t.toString();
}
@Override
public String visitNoType(NoType t, Void aVoid) {
return t.toString();
}
public static boolean missingParamNames(ExecutableElement e) {
return e.getParameters().stream()
.allMatch(p -> p.getSimpleName().toString().matches("arg\\d+"));
}
private String printArguments(ExecutableElement e) {
StringJoiner result = new StringJoiner(", ");
boolean missingParamNames = missingParamNames(e);
for (VariableElement p : e.getParameters()) {
StringBuilder s = new StringBuilder();
s.append(print(p.asType()));
if (!missingParamNames) {
s.append(" ").append(p.getSimpleName());
}
result.add(s);
}
return result.toString();
}
String printMethod(ExecutableElement m) {
if (m.getSimpleName().contentEquals("<init>")) {
return m.getEnclosingElement().getSimpleName() + "(" + printArguments(m) + ")";
} else {
StringBuilder result = new StringBuilder();
// static void foo
if (m.getModifiers().contains(Modifier.STATIC)) result.append("static ");
result.append(print(m.getReturnType())).append(" ");
result.append(m.getSimpleName());
// (int arg, String other)
result.append("(").append(printArguments(m)).append(")");
// throws Foo, Bar
if (!m.getThrownTypes().isEmpty()) {
result.append(" throws ");
StringJoiner types = new StringJoiner(", ");
for (TypeMirror t : m.getThrownTypes()) {
types.add(print(t));
}
result.append(types);
}
return result.toString();
}
}
}
| 4,619 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FindHoverElement.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/hover/FindHoverElement.java | package com.tyron.completion.java.hover;
import com.sun.source.tree.*;
import com.sun.source.util.*;
import javax.lang.model.element.Element;
/** Class that searches where the current cursor is and returns the element corresponding to it */
public class FindHoverElement extends TreePathScanner<Element, Long> {
private final JavacTask task;
private CompilationUnitTree root;
public FindHoverElement(JavacTask task) {
this.task = task;
}
@Override
public Element visitCompilationUnit(CompilationUnitTree t, Long find) {
root = t;
return super.visitCompilationUnit(t, find);
}
@Override
public Element visitIdentifier(IdentifierTree t, Long find) {
SourcePositions pos = Trees.instance(task).getSourcePositions();
long start = pos.getStartPosition(root, t);
long end = pos.getEndPosition(root, t);
if (start <= find && find < end) {
return Trees.instance(task).getElement(getCurrentPath());
}
return super.visitIdentifier(t, find);
}
@Override
public Element visitMemberSelect(MemberSelectTree t, Long find) {
SourcePositions pos = Trees.instance(task).getSourcePositions();
long start = pos.getEndPosition(root, t.getExpression()) + 1;
long end = pos.getEndPosition(root, t);
if (start <= find && find < end) {
return Trees.instance(task).getElement(getCurrentPath());
}
return super.visitMemberSelect(t, find);
}
@Override
public Element visitMemberReference(MemberReferenceTree t, Long find) {
SourcePositions pos = Trees.instance(task).getSourcePositions();
long start = pos.getStartPosition(root, t.getQualifierExpression()) + 2;
long end = pos.getEndPosition(root, t);
if (start <= find && find < end) {
return Trees.instance(task).getElement(getCurrentPath());
}
return super.visitMemberReference(t, find);
}
@Override
public Element reduce(Element a, Element b) {
if (a != null) return a;
else return b;
}
}
| 1,972 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CompileTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/compiler/CompileTask.java | package com.tyron.completion.java.compiler;
import android.annotation.SuppressLint;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.Trees;
import java.io.File;
import java.net.URI;
import java.nio.file.Path;
import java.util.List;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
public class CompileTask implements AutoCloseable {
private final CompileBatch mCompileBatch;
public final JavacTask task;
public final List<CompilationUnitTree> roots;
public final List<Diagnostic<? extends JavaFileObject>> diagnostics;
private final Trees trees;
public CompileTask(CompileBatch batch) {
mCompileBatch = batch;
this.task = batch.task;
this.trees = Trees.instance(task);
this.roots = batch.roots;
this.diagnostics = batch.parent.getDiagnostics();
}
public Trees getTrees() {
return trees;
}
public CompilationUnitTree root() {
if (roots.size() != 1) {
throw new RuntimeException(Integer.toString(roots.size()));
}
return roots.get(0);
}
@SuppressLint("NewApi")
public CompilationUnitTree root(Path file) {
return root(file.toUri());
}
public CompilationUnitTree root(File file) {
return root(file.toURI());
}
public CompilationUnitTree root(JavaFileObject file) {
return root(file.toUri());
}
public CompilationUnitTree root(URI uri) {
for (CompilationUnitTree root : roots) {
if (root.getSourceFile().toUri().equals(uri)) {
return root;
}
}
return null;
}
@Override
public void close() {
mCompileBatch.close();
}
}
| 1,644 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CompileBatch.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/compiler/CompileBatch.java | package com.tyron.completion.java.compiler;
import android.util.Log;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.Trees;
import com.sun.tools.javac.api.ClientCodeWrapper;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.util.JCDiagnostic;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.common.util.StringSearch;
import com.tyron.completion.java.CompletionModule;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import org.apache.commons.io.FileUtils;
@SuppressWarnings("NewApi")
public class CompileBatch implements AutoCloseable {
static final int MAX_COMPLETION_ITEMS = 50;
public final JavaCompilerService parent;
public final ReusableCompiler.Borrow borrow;
/** Indicates the task that requested the compilation is finished with it. */
public boolean closed;
public final JavacTask task;
public final Trees trees;
public final Elements elements;
public final Types types;
public final List<CompilationUnitTree> roots;
public CompileBatch(JavaCompilerService parent, Collection<? extends JavaFileObject> files) {
this.parent = parent;
this.borrow = batchTask(parent, files);
this.task = borrow.task;
this.trees = Trees.instance(borrow.task);
this.elements = borrow.task.getElements();
this.types = borrow.task.getTypes();
this.roots = new ArrayList<>();
// Compile all roots
try {
for (CompilationUnitTree t : borrow.task.parse()) {
roots.add(t);
}
// The results of borrow.task.analyze() are unreliable when errors are present
// You can get at `Element` values using `Trees`
task.analyze();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* If the compilation failed because javac didn't find some package-private files in source files
* with different names, list those source files.
*/
public Set<Path> needsAdditionalSources() {
if (parent.getCurrentModule() == null) {
return Collections.emptySet();
}
JavaModule module = parent.getCurrentModule();
// Check for "class not found errors" that refer to package private classes
Set<Path> addFiles = new HashSet<>();
for (Diagnostic<? extends JavaFileObject> err : parent.getDiagnostics()) {
if (!err.getCode().equals("compiler.err.cant.resolve.location")) {
continue;
}
if (!isValidFileRange(err)) {
continue;
}
String className;
try {
className = errorText(err);
} catch (IOException e) {
continue;
}
if (className == null) {
continue;
}
String packageName = packageName(err);
File javaFile = module.getJavaFile(packageName);
if (javaFile != null) {
addFiles.add(javaFile.toPath());
}
}
return addFiles;
}
private String errorText(Diagnostic<? extends JavaFileObject> err) throws IOException {
if (err instanceof ClientCodeWrapper.DiagnosticSourceUnwrapper) {
JCDiagnostic diagnostic = ((ClientCodeWrapper.DiagnosticSourceUnwrapper) err).d;
String className = String.valueOf(diagnostic.getArgs()[1]);
if (!className.equals("null")) {
return className;
}
}
// fallback to parsing the file
Path file = Paths.get(err.getSource().toUri());
String contents = FileUtils.readFileToString(file.toFile(), Charset.defaultCharset());
int begin = (int) err.getStartPosition();
int end = (int) err.getEndPosition();
if (begin < 0 || end > contents.length()) {
Log.w("CompileBatch", "Diagnostic position does not match with the contents");
return null;
}
return contents.substring(begin, end);
}
private String packageName(Diagnostic<? extends JavaFileObject> err) {
if (err instanceof ClientCodeWrapper.DiagnosticSourceUnwrapper) {
JCDiagnostic diagnostic = ((ClientCodeWrapper.DiagnosticSourceUnwrapper) err).d;
JCDiagnostic.DiagnosticPosition pos = diagnostic.getDiagnosticPosition();
Object[] args = diagnostic.getArgs();
Kinds.KindName kind = (Kinds.KindName) args[0];
if (kind == Kinds.KindName.CLASS) {
if (pos.toString().contains(".")) {
return pos.toString().substring(0, pos.toString().lastIndexOf('.'));
}
}
}
Path file = Paths.get(err.getSource().toUri());
return StringSearch.packageName(file.toFile());
}
private static final Path FILE_NOT_FOUND = Paths.get("");
@Override
public void close() {
closed = true;
}
private static ReusableCompiler.Borrow batchTask(
JavaCompilerService parent, Collection<? extends JavaFileObject> sources) {
parent.clearDiagnostics();
List<String> options = options(parent, parent.classPath, parent.addExports);
return parent.compiler.getTask(
parent.mSourceFileManager,
parent::addDiagnostic,
options,
Collections.emptyList(),
sources);
}
/**
* Combine source path or class path entries using the system separator, for example ':' in unix
*/
private static String joinPath(Collection<File> classOrSourcePath) {
return classOrSourcePath.stream()
.map(File::getAbsolutePath)
.collect(Collectors.joining(File.pathSeparator));
}
private static List<String> options(
JavaCompilerService parent, Set<File> classPath, Set<String> addExports) {
List<String> list = new ArrayList<>();
JavaModule module = parent.getCurrentModule();
List<File> bootClassPathEntries = new ArrayList<>(classPath);
bootClassPathEntries.add(CompletionModule.getAndroidJar());
bootClassPathEntries.add(CompletionModule.getLambdaStubs());
bootClassPathEntries.add(
new File(
module.getRootFile(),
"build/libraries/kotlin_runtime/" + module.getRootFile().getName() + ".jar"));
list.add("-bootclasspath");
list.add(joinPath(bootClassPathEntries));
Collections.addAll(list, "-cp", joinPath(bootClassPathEntries));
Collections.addAll(list, "-target", "1.8", "-source", "1.8");
// Collections.addAll(list, "--add-modules", "ALL-MODULE-PATH");
Collections.addAll(list, "-proc:none");
// You would think we could do -Xlint:all,
// but some lints trigger fatal errors in the presence of parse errors
Collections.addAll(
list,
"-Xlint:cast",
"-Xlint:deprecation",
"-Xlint:empty",
"-Xlint" + ":fallthrough",
"-Xlint:finally",
"-Xlint:path",
"-Xlint:unchecked",
"-Xlint" + ":varargs",
"-Xlint:static");
for (String export : addExports) {
list.add("--add-exports");
list.add(export + "=ALL-UNNAMED");
}
return list;
}
private boolean isValidFileRange(Diagnostic<? extends JavaFileObject> d) {
return d.getSource().toUri().getScheme().equals("file")
&& d.getStartPosition() >= 0
&& d.getEndPosition() >= 0;
}
}
| 7,434 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ReusableCompiler.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/compiler/ReusableCompiler.java | package com.tyron.completion.java.compiler;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TaskEvent;
import com.sun.source.util.TaskListener;
import com.sun.tools.javac.api.JavacTaskImpl;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.api.MultiTaskListener;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.comp.Annotate;
import com.sun.tools.javac.comp.Check;
import com.sun.tools.javac.comp.CompileStates;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Modules;
import com.sun.tools.javac.main.Arguments;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.model.JavacElements;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.DefinedBy;
import com.sun.tools.javac.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
/**
* A pool of reusable JavacTasks. When a task is no valid anymore, it is returned to the pool, and
* its Context may be reused for future processing in some cases. The reuse is achieved by replacing
* some components (most notably JavaCompiler and Log) with reusable counterparts, and by cleaning
* up leftovers from previous compilation.
*
* <p>For each combination of options, a separate task/context is created and kept, as most option
* values are cached inside components themselves.
*
* <p>When the compilation redefines sensitive classes (e.g. classes in the the java.* packages),
* the task/context is not reused.
*
* <p>When the task is reused, then packages that were already listed won't be listed again.
*
* <p>Care must be taken to only return tasks that won't be used by the original caller.
*
* <p>Care must also be taken when custom components are installed, as those are not cleaned when
* the task/context is reused, and subsequent getTask may return a task based on a context with
* these custom components.
*
* <p><b>This is NOT part of any supported API. If you write code that depends on this, you do so at
* your own risk. This code and its internal interfaces are subject to change or deletion without
* notice.</b>
*/
public class ReusableCompiler {
private static final Logger LOG = Logger.getLogger("main");
private static final JavacTool systemProvider = JavacTool.create();
private final List<String> currentOptions = new ArrayList<>();
private ReusableContext currentContext;
private volatile boolean checkedOut;
/**
* Creates a new task as if by JavaCompiler and runs the provided worker with it. The task is only
* valid while the worker is running. The internal structures may be reused from some previous
* compilation.
*
* @param fileManager a file manager; if {@code null} use the compiler's standard filemanager
* @param diagnosticListener a diagnostic listener; if {@code null} use the compiler's default
* method for reporting diagnostics
* @param options compiler options, {@code null} means no options
* @param classes names of classes to be processed by annotation processing, {@code null} means no
* class names
* @param compilationUnits the compilation units to compile, {@code null} means no compilation
* units
* @return an object representing the compilation
* @throws RuntimeException if an unrecoverable error occurred in a user supplied component. The
* {@linkplain Throwable#getCause() cause} will be the error in user code.
* @throws IllegalArgumentException if any of the options are invalid, or if any of the given
* compilation units are of other kind than {@linkplain JavaFileObject.Kind#SOURCE source}
*/
public Borrow getTask(
JavaFileManager fileManager,
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Iterable<String> options,
Iterable<String> classes,
Iterable<? extends JavaFileObject> compilationUnits) {
if (checkedOut) {
throw new RuntimeException("Compiler is already in-use!");
}
checkedOut = true;
List<String> opts =
StreamSupport.stream(options.spliterator(), false).collect(Collectors.toList());
if (!opts.equals(currentOptions)) {
List<String> difference = new ArrayList<>(currentOptions);
difference.removeAll(opts);
LOG.warning("Options changed, creating new compiler \n difference: " + difference);
currentOptions.clear();
currentOptions.addAll(opts);
currentContext = new ReusableContext(new ArrayList<>(opts));
}
JavacTaskImpl task =
(JavacTaskImpl)
systemProvider.getTask(
null,
fileManager,
diagnosticListener,
opts,
classes,
compilationUnits,
currentContext);
task.addTaskListener(currentContext);
return new Borrow(task, currentContext);
}
public ReusableContext getCurrentContext() {
return currentContext;
}
public class Borrow implements AutoCloseable {
final JavacTask task;
boolean closed;
Borrow(JavacTask task, ReusableContext ctx) {
this.task = task;
}
@Override
public void close() {
if (closed) return;
// not returning the context to the pool if task crashes with an exception
// the task/context may be in a broken state
currentContext.clear();
try {
Method method = JavacTaskImpl.class.getDeclaredMethod("cleanup");
method.setAccessible(true);
method.invoke(task);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
} finally {
checkedOut = false;
closed = true;
}
}
}
static class ReusableContext extends Context implements TaskListener {
List<String> arguments;
ReusableContext(List<String> arguments) {
super();
this.arguments = arguments;
put(Log.logKey, ReusableLog.factory);
put(JavaCompiler.compilerKey, ReusableJavaCompiler.factory);
}
public void clear() {
drop(Arguments.argsKey);
drop(DiagnosticListener.class);
drop(Log.outKey);
drop(Log.errKey);
drop(JavaFileManager.class);
drop(JavacTask.class);
drop(JavacTrees.class);
drop(JavacElements.class);
if (ht.get(Log.logKey) instanceof ReusableLog) {
// log already inited - not first round
((ReusableLog) Log.instance(this)).clear();
Enter.instance(this).newRound();
((ReusableJavaCompiler) ReusableJavaCompiler.instance(this)).clear();
Types.instance(this).newRound();
Check.instance(this).newRound();
Modules.instance(this).newRound();
Annotate.instance(this).newRound();
CompileStates.instance(this).clear();
MultiTaskListener.instance(this).clear();
}
}
@Override
@DefinedBy(DefinedBy.Api.COMPILER_TREE)
public void finished(TaskEvent e) {
// do nothing
}
@Override
@DefinedBy(DefinedBy.Api.COMPILER_TREE)
public void started(TaskEvent e) {
// do nothing
}
<T> void drop(Key<T> k) {
ht.remove(k);
}
<T> void drop(Class<T> c) {
ht.remove(key(c));
}
/**
* Reusable JavaCompiler; exposes a method to clean up the component from leftovers associated
* with previous compilations.
*/
static class ReusableJavaCompiler extends JavaCompiler {
static final Factory<JavaCompiler> factory = ReusableJavaCompiler::new;
ReusableJavaCompiler(Context context) {
super(context);
}
@Override
public void close() {
// do nothing
}
void clear() {
newRound();
}
@Override
protected void checkReusable() {
// do nothing - it's ok to reuse the compiler
}
}
/**
* Reusable Log; exposes a method to clean up the component from leftovers associated with
* previous compilations.
*/
static class ReusableLog extends Log {
static final Factory<Log> factory = ReusableLog::new;
Context context;
ReusableLog(Context context) {
super(context);
this.context = context;
}
void clear() {
recorded.clear();
sourceMap.clear();
nerrors = 0;
nwarnings = 0;
// Set a fake listener that will lazily lookup the context for the 'real' listener. Since
// this field is never updated when a new task is created, we cannot simply reset the field
// or keep old value. This is a hack to workaround the limitations in the current
// infrastructure.
diagListener =
new DiagnosticListener<JavaFileObject>() {
DiagnosticListener<JavaFileObject> cachedListener;
@Override
@DefinedBy(DefinedBy.Api.COMPILER)
@SuppressWarnings("unchecked")
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
if (cachedListener == null) {
cachedListener = context.get(DiagnosticListener.class);
}
cachedListener.report(diagnostic);
}
};
}
}
}
}
| 9,618 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ParseTask.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/compiler/ParseTask.java | package com.tyron.completion.java.compiler;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.JavacTask;
public class ParseTask {
public final JavacTask task;
public final CompilationUnitTree root;
public ParseTask(JavacTask task, CompilationUnitTree root) {
this.task = task;
this.root = root;
}
}
| 343 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
Parser.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/compiler/Parser.java | package com.tyron.completion.java.compiler;
import android.annotation.SuppressLint;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ErroneousTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.SwitchTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreeScanner;
import com.sun.source.util.Trees;
import com.sun.tools.javac.api.JavacTool;
import com.tyron.builder.model.SourceFileObject;
import com.tyron.builder.project.Project;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.tools.Diagnostic;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
public class Parser {
private static final JavaCompiler COMPILER = JavacTool.create();
private static SourceFileManager FILE_MANAGER;
/** Create a task that compiles a single file */
@SuppressLint("NewApi")
private static JavacTask singleFileTask(Project project, JavaFileObject file) {
return (JavacTask)
COMPILER.getTask(
null,
getFileManager(project),
Parser::ignoreError,
Collections.emptyList(),
Collections.emptyList(),
Collections.singletonList(file));
}
private static SourceFileManager getFileManager(Project project) {
return new SourceFileManager(project);
}
public final JavaFileObject file;
public final String contents;
public final JavacTask task;
public final CompilationUnitTree root;
public final Trees trees;
private Parser(Project project, JavaFileObject file) {
this.file = file;
try {
this.contents = file.getCharContent(false).toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
this.task = singleFileTask(project, file);
try {
this.root = task.parse().iterator().next();
} catch (IOException e) {
throw new RuntimeException(e);
}
this.trees = Trees.instance(task);
}
public static Parser parseFile(Project project, Path file) {
return parseJavaFileObject(project, new SourceFileObject(file));
}
private static Parser cachedParse;
private static long cachedModified = -1;
private static boolean needsParse(JavaFileObject file) {
if (cachedParse == null) return true;
if (!cachedParse.file.equals(file)) return true;
if (file.getLastModified() > cachedModified) return true;
return false;
}
private static void loadParse(Project project, JavaFileObject file) {
cachedParse = new Parser(project, file);
cachedModified = file.getLastModified();
}
public static Parser parseJavaFileObject(Project project, JavaFileObject file) {
if (needsParse(file)) {
loadParse(project, file);
}
return cachedParse;
}
public Set<Name> packagePrivateClasses() {
Set<Name> result = new HashSet<>();
for (Tree t : root.getTypeDecls()) {
if (t instanceof ClassTree) {
ClassTree c = (ClassTree) t;
boolean isPublic = c.getModifiers().getFlags().contains(Modifier.PUBLIC);
if (isPublic) {
result.add(c.getSimpleName());
}
}
}
return result;
}
private static String prune(
final CompilationUnitTree root,
final SourcePositions pos,
final StringBuilder buffer,
final long[] offsets,
final boolean eraseAfterCursor) {
class Scan extends TreeScanner<Void, Void> {
boolean erasedAfterCursor = !eraseAfterCursor;
boolean containsCursor(Tree node) {
long start = pos.getStartPosition(root, node);
long end = pos.getEndPosition(root, node);
for (long cursor : offsets) {
if (start <= cursor && cursor <= end) {
return true;
}
}
return false;
}
boolean anyContainsCursor(Collection<? extends Tree> nodes) {
for (Tree n : nodes) {
if (containsCursor(n)) return true;
}
return false;
}
long lastCursorIn(Tree node) {
long start = pos.getStartPosition(root, node);
long end = pos.getEndPosition(root, node);
long last = -1;
for (long cursor : offsets) {
if (start <= cursor && cursor <= end) {
last = cursor;
}
}
if (last == -1) {
throw new RuntimeException(
String.format("No cursor in %s is between %d and %d", offsets, start, end));
}
return last;
}
@Override
public Void visitImport(ImportTree node, Void __) {
// Erase 'static' keyword so autocomplete works better
if (containsCursor(node) && node.isStatic()) {
int start = (int) pos.getStartPosition(root, node);
start = buffer.indexOf("static", start);
int end = start + "static".length();
erase(buffer, start, end);
}
return super.visitImport(node, null);
}
@Override
public Void visitSwitch(SwitchTree node, Void __) {
if (containsCursor(node)) {
// Prevent the enclosing block from erasing the closing } of the switch
erasedAfterCursor = true;
}
return super.visitSwitch(node, null);
}
@Override
public Void visitBlock(BlockTree node, Void __) {
if (containsCursor(node)) {
super.visitBlock(node, null);
// When we find the deepest block that includes the cursor
if (!erasedAfterCursor) {
long cursor = lastCursorIn(node);
long start = cursor;
long end = pos.getEndPosition(root, node);
if (end >= buffer.length()) end = buffer.length() - 1;
// Find the next line
while (start < end && buffer.charAt((int) start) != '\n') start++;
// Find the end of the block
while (end > start && buffer.charAt((int) end) != '}') end--;
// Erase from next line to end of block
erase(buffer, start, end - 1);
erasedAfterCursor = true;
}
} else if (!node.getStatements().isEmpty()) {
StatementTree first = node.getStatements().get(0);
StatementTree last = node.getStatements().get(node.getStatements().size() - 1);
long start = pos.getStartPosition(root, first);
long end = pos.getEndPosition(root, last);
if (end >= buffer.length()) end = buffer.length() - 1;
erase(buffer, start, end);
}
return null;
}
@Override
public Void visitErroneous(ErroneousTree node, Void nothing) {
return super.scan(node.getErrorTrees(), nothing);
}
}
new Scan().scan(root, null);
String pruned = buffer.toString();
// For debugging:
if (false) {
Path file = Paths.get(root.getSourceFile().toUri());
Path out = file.resolveSibling(file.getFileName() + ".pruned");
/*try {
// Files.writeString(out, pruned);
} catch (IOException e) {
throw new RuntimeException(e);
}*/
}
return pruned;
}
private static void erase(StringBuilder buffer, long start, long end) {
for (int i = (int) start; i < end; i++) {
switch (buffer.charAt(i)) {
case '\r':
case '\n':
break;
default:
buffer.setCharAt(i, ' ');
}
}
}
public String prune(long cursor) {
SourcePositions pos = Trees.instance(task).getSourcePositions();
StringBuilder buffer = new StringBuilder(contents);
long[] cursors = {cursor};
return prune(root, pos, buffer, cursors, true);
}
private static void ignoreError(Diagnostic<? extends JavaFileObject> __) {
// Too noisy, this only comes up in parse tasks which tend to be less important
// LOG.warning(err.getMessage(Locale.getDefault()));
}
}
| 8,216 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CompilerContainer.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/compiler/CompilerContainer.java | package com.tyron.completion.java.compiler;
import java.util.concurrent.Semaphore;
import java.util.function.Consumer;
import kotlin.jvm.functions.Function1;
/**
* A container class for compiled information, used for thread safety
*
* <p>A read is when the {@link CompileTask} is being accessed to get information about the parse
* tree. A write is when the {@link CompileTask} is being changed from a compile call
*
* <p>Any threads are allowed to read only if there is no thread that is currently writing. If there
* is a thread that is currently writing, all other threads that attempts to read will be blocked
* until the write thread has finished.
*
* <p>Only one thread is allowed to write at a time, during a write operation all threads that
* attempts to read will be blocked until the thread writing has finished.
*/
public class CompilerContainer {
private static final String TAG = CompilerContainer.class.getSimpleName();
private volatile boolean mIsWriting;
private final Semaphore semaphore = new Semaphore(1);
private CompileTask mCompileTask;
public CompilerContainer() {}
/**
* This is for codes that will use the compile information, it ensures that all other threads
* accessing the compile information are synchronized
*/
public void run(Consumer<CompileTask> consumer) {
semaphore.acquireUninterruptibly();
try {
consumer.accept(mCompileTask);
} finally {
semaphore.release();
}
}
public <T> T get(Function1<CompileTask, T> fun) {
semaphore.acquireUninterruptibly();
try {
return fun.invoke(mCompileTask);
} finally {
semaphore.release();
}
}
public <T> T getWithLock(Function1<CompileTask, T> fun) {
semaphore.acquireUninterruptibly();
try {
return fun.invoke(mCompileTask);
} finally {
semaphore.release();
}
}
public synchronized boolean isWriting() {
return mIsWriting || semaphore.hasQueuedThreads();
}
void initialize(Runnable runnable) {
semaphore.acquireUninterruptibly();
mIsWriting = true;
try {
// ensure that compile task is closed
if (mCompileTask != null) {
mCompileTask.close();
}
runnable.run();
} finally {
mIsWriting = false;
semaphore.release();
}
}
void setCompileTask(CompileTask task) {
mCompileTask = task;
}
}
| 2,381 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
SourceFileManager.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/compiler/SourceFileManager.java | package com.tyron.completion.java.compiler;
import android.text.TextUtils;
import com.sun.tools.javac.api.JavacTool;
import com.tyron.builder.model.SourceFileObject;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.builder.project.api.Module;
import com.tyron.common.util.StringSearch;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
public class SourceFileManager extends ForwardingJavaFileManager<StandardJavaFileManager> {
private final Project mProject;
private Module mCurrentModule;
public SourceFileManager(Project project) {
super(createDelegateFileManager());
mProject = project;
}
private static StandardJavaFileManager createDelegateFileManager() {
JavacTool compiler = JavacTool.create();
return compiler.getStandardFileManager(
SourceFileManager::logError, Locale.getDefault(), Charset.defaultCharset());
}
private static void logError(Diagnostic<?> error) {}
public void setCurrentModule(Module module) {
mCurrentModule = module;
}
@Override
public Iterable<JavaFileObject> list(
JavaFileManager.Location location,
String packageName,
Set<JavaFileObject.Kind> kinds,
boolean recurse)
throws IOException {
if (location == StandardLocation.SOURCE_PATH) {
List<File> found = new ArrayList<>();
for (Module module : mProject.getModules()) {
found.addAll(list(module, packageName));
}
Stream<JavaFileObject> stream = found.stream().map(this::asJavaFileObject);
return stream.collect(Collectors.toList());
}
return super.list(location, packageName, kinds, recurse);
}
private JavaFileObject asJavaFileObject(File file) {
return new SourceFileObject(file.toPath(), (JavaModule) mProject.getModule(file));
}
@Override
public String inferBinaryName(Location location, JavaFileObject file) {
if (location == StandardLocation.SOURCE_PATH) {
SourceFileObject source = (SourceFileObject) file;
String packageName = StringSearch.packageName(source.mFile.toFile());
String className = removeExtension(source.mFile.getFileName().toString());
if (!packageName.isEmpty()) className = packageName + "." + className;
return className;
} else {
return super.inferBinaryName(location, file);
}
}
private String removeExtension(String fileName) {
int lastDot = fileName.lastIndexOf(".");
return (lastDot == -1 ? fileName : fileName.substring(0, lastDot));
}
@Override
public boolean hasLocation(Location location) {
return location == StandardLocation.SOURCE_PATH || super.hasLocation(location);
}
@Override
public JavaFileObject getJavaFileForInput(
Location location, String className, JavaFileObject.Kind kind) throws IOException {
if (TextUtils.isEmpty(className)) {
return null;
}
// FileStore shadows disk
if (location == StandardLocation.SOURCE_PATH) {
String packageName = StringSearch.mostName(className);
String simpleClassName = StringSearch.lastName(className);
for (File f : list(mCurrentModule, packageName)) {
if (f.getName().equals(simpleClassName + kind.extension)) {
return new SourceFileObject(f.toPath(), (JavaModule) mCurrentModule);
}
}
// Fall through to disk in case we have .jar or .zip files on the source path
}
return super.getJavaFileForInput(location, className, kind);
}
@Override
public FileObject getFileForInput(Location location, String packageName, String relativeName)
throws IOException {
if (location == StandardLocation.SOURCE_PATH) {
return null;
}
return super.getFileForInput(location, packageName, relativeName);
}
@Override
public boolean contains(Location location, FileObject fileObject) throws IOException {
System.out.println(
"Contains called at location " + location + " " + "\n" + "file object: " + fileObject);
return super.contains(location, fileObject);
}
public void setLocation(Location location, Iterable<? extends File> path) throws IOException {
fileManager.setLocation(location, path);
}
public static List<File> list(Module module, String packageName) {
if (!(module instanceof JavaModule)) {
return Collections.emptyList();
}
JavaModule javaModule = (JavaModule) module;
List<File> list = new ArrayList<>();
Map<String, File> toSearch = new HashMap<>(javaModule.getJavaFiles());
toSearch.putAll(javaModule.getInjectedClasses());
for (String file : toSearch.keySet()) {
String name = file;
if (file.endsWith(".")) {
name = file.substring(0, file.length() - 1);
}
if (!name.startsWith(packageName)) {
continue;
}
if (name.substring(0, name.lastIndexOf(".")).equals(packageName)
|| name.equals(packageName)) {
list.add(toSearch.get(file));
}
}
return list;
}
}
| 5,524 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaCompilerService.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/compiler/JavaCompilerService.java | package com.tyron.completion.java.compiler;
import android.annotation.SuppressLint;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.tools.javac.file.PathFileObject;
import com.tyron.builder.model.SourceFileObject;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.builder.project.api.Module;
import com.tyron.builder.project.util.PackageTrie;
import com.tyron.common.util.Cache;
import com.tyron.common.util.StringSearch;
import com.tyron.completion.java.CompilerProvider;
import com.tyron.completion.java.Docs;
import com.tyron.completion.java.FindTypeDeclarations;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
public class JavaCompilerService implements CompilerProvider {
private DiagnosticListener<? super JavaFileObject> mDiagnosticListener;
public final SourceFileManager mSourceFileManager;
private final List<Diagnostic<? extends JavaFileObject>> diagnostics = new ArrayList<>();
private final Project mProject;
private JavaModule mCurrentModule;
public final Set<File> classPath, docPath;
public final Set<String> addExports;
public ReusableCompiler compiler = new ReusableCompiler();
private final Docs docs;
private final CompilerContainer mContainer = new CompilerContainer();
private CompileBatch cachedCompile;
private final Map<JavaFileObject, Long> cachedModified = new HashMap<>();
public final ReentrantLock mLock = new ReentrantLock();
public JavaCompilerService(
Project project, Set<File> classPath, Set<File> docPath, Set<String> addExports) {
mProject = project;
this.classPath = Collections.unmodifiableSet(classPath);
this.docPath = Collections.unmodifiableSet(docPath);
this.addExports = Collections.unmodifiableSet(addExports);
this.mSourceFileManager = new SourceFileManager(project);
this.docs = new Docs(project, docPath);
}
public Project getProject() {
return mProject;
}
public void setCurrentModule(@NonNull JavaModule module) {
mSourceFileManager.setCurrentModule(module);
mCurrentModule = module;
}
/**
* Checks whether this list has been compiled before
*
* @param sources list of java files to compile
* @return true if there's a valid cache for it, false otherwise
*/
private boolean needsCompile(Collection<? extends JavaFileObject> sources) {
if (cachedModified.size() != sources.size()) {
return true;
}
for (JavaFileObject f : sources) {
if (!cachedModified.containsKey(f)) {
return true;
}
Long cached = cachedModified.get(f);
if (cached == null) {
return true;
}
if (f.getLastModified() != cached) {
return true;
}
}
return false;
}
private synchronized void loadCompile(Collection<? extends JavaFileObject> sources) {
if (cachedCompile != null) {
if (!cachedCompile.closed) {
throw new RuntimeException("Compiler is still in-use!");
}
cachedCompile.borrow.close();
}
cachedCompile = doCompile(sources);
cachedModified.clear();
for (JavaFileObject f : sources) {
cachedModified.put(f, f.getLastModified());
}
}
private CompileBatch doCompile(Collection<? extends JavaFileObject> sources) {
if (sources.isEmpty()) throw new RuntimeException("empty sources");
CompileBatch firstAttempt = new CompileBatch(this, sources);
Set<Path> addFiles = firstAttempt.needsAdditionalSources();
if (addFiles.isEmpty()) return firstAttempt;
// If the compiler needs additional source files that contain package-private files
// LOG.info("...need to recompile with " + addFiles);
Log.d("JavaCompilerService", "Need to recompile with " + addFiles);
firstAttempt.close();
firstAttempt.borrow.close();
List<JavaFileObject> moreSources = new ArrayList<>(sources);
for (Path add : addFiles) {
moreSources.add(new SourceFileObject(add, mCurrentModule));
}
return new CompileBatch(this, moreSources);
}
/**
* Creates a compile batch only if it has not been compiled before
*
* @param sources Files to compile
* @return CompileBatch for this compilation
*/
private CompilerContainer compileBatch(Collection<? extends JavaFileObject> sources) {
mContainer.initialize(
() -> {
if (needsCompile(sources)) {
loadCompile(sources);
}
CompileTask task = new CompileTask(cachedCompile);
mContainer.setCompileTask(task);
});
return mContainer;
}
public void clearDiagnostics() {
diagnostics.clear();
if (mDiagnosticListener != null) {
mDiagnosticListener.report(null);
}
}
public void addDiagnostic(Diagnostic<? extends JavaFileObject> diagnostic) {
diagnostics.add(diagnostic);
if (mDiagnosticListener != null) {
mDiagnosticListener.report(diagnostic);
}
}
public void setDiagnosticListener(DiagnosticListener<? super JavaFileObject> listener) {
mDiagnosticListener = listener;
}
public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() {
return ImmutableList.copyOf(diagnostics);
}
@Override
public Set<String> imports() {
return null;
}
// TODO: This doesn't list all the public types
@Override
public Set<String> publicTopLevelTypes() {
Set<String> classes = new HashSet<>();
for (Module module : mProject.getDependencies(mCurrentModule)) {
if (module instanceof JavaModule) {
classes.addAll(((JavaModule) module).getAllClasses());
}
}
return classes;
}
public Set<String> findClasses(String packageName) {
Set<String> classes = new HashSet<>();
for (Module module : mProject.getDependencies(mCurrentModule)) {
if (module instanceof JavaModule) {
PackageTrie classIndex = ((JavaModule) module).getClassIndex();
classes.addAll(classIndex.getMatchingPackages(packageName));
}
}
return classes;
}
/** For suggesting the first import typed where the package names are not yet correct */
public Set<String> getTopLevelNonLeafPackages(Predicate<String> filter) {
Set<String> packages = new HashSet<>();
for (Module module : mProject.getDependencies(mCurrentModule)) {
if (module instanceof JavaModule) {
PackageTrie classIndex = ((JavaModule) module).getClassIndex();
for (String node : classIndex.getTopLevelNonLeafNodes()) {
if (filter.test(node)) {
packages.add(node);
}
}
}
}
return packages;
}
@Override
public List<String> packagePrivateTopLevelTypes(String packageName) {
return Collections.emptyList();
}
@Override
public Iterable<Path> search(String query) {
return null;
}
/**
* Finds all the occurrences of a class in javadocs, and source files
*
* @param className fully qualified name of the class
* @return Optional of type JavaFileObject that may be empty if the file is not found
*/
@SuppressLint("NewApi")
@Override
public Optional<JavaFileObject> findAnywhere(String className) {
Optional<JavaFileObject> fromDocs = findPublicTypeDeclarationInDocPath(className);
if (fromDocs.isPresent()) {
return fromDocs;
}
Path fromSource = findTypeDeclaration(className);
if (fromSource != NOT_FOUND) {
return Optional.of(new SourceFileObject(fromSource, mCurrentModule));
}
return Optional.empty();
}
/**
* Searches the javadoc file manager if it contains the classes with javadoc
*
* @param className the fully qualified name of the class
* @return optional of type JavaFileObject, may be empty if it doesn't exist
*/
private Optional<JavaFileObject> findPublicTypeDeclarationInDocPath(String className) {
try {
JavaFileObject found =
docs.fileManager.getJavaFileForInput(
StandardLocation.SOURCE_PATH, className, JavaFileObject.Kind.SOURCE);
return Optional.ofNullable(found);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static final Pattern PACKAGE_EXTRACTOR =
Pattern.compile("^([a-z][_a-zA-Z0-9]*\\.)*[a-z][_a-zA-Z0-9]*");
private String packageName(String className) {
Matcher m = PACKAGE_EXTRACTOR.matcher(className);
if (m.find()) {
return m.group();
}
return "";
}
private static final Pattern SIMPLE_EXTRACTOR = Pattern.compile("[A-Z][_a-zA-Z0-9]*$");
private String simpleName(String className) {
Matcher m = SIMPLE_EXTRACTOR.matcher(className);
if (m.find()) {
return m.group();
}
return "";
}
private static final Cache<String, Boolean> cacheContainsWord = new Cache<>();
private boolean containsWord(Path file, String word) {
if (cacheContainsWord.needs(file, word)) {
cacheContainsWord.load(file, word, StringSearch.containsWord(file, word));
}
return cacheContainsWord.get(file, word);
}
private static final Cache<Void, List<String>> cacheContainsType = new Cache<>();
private boolean containsType(Path file, String className) {
if (cacheContainsType.needs(file, null)) {
CompilationUnitTree root = parse(file).root;
List<String> types = new ArrayList<>();
new FindTypeDeclarations().scan(root, types);
cacheContainsType.load(file, null, types);
}
return cacheContainsType.get(file, null).contains(className);
}
@Override
public Path findTypeDeclaration(String className) {
Path fastFind = findPublicTypeDeclaration(className);
if (fastFind != NOT_FOUND) {
return fastFind;
}
List<Module> dependencies = mProject.getDependencies(mCurrentModule);
String packageName = packageName(className);
String simpleName = simpleName(className);
for (Module dependency : dependencies) {
Path path = findPublicTypeDeclarationInModule(dependency, packageName, simpleName, className);
if (path != NOT_FOUND) {
return path;
}
}
return NOT_FOUND;
}
private Path findPublicTypeDeclarationInModule(
Module module, String packageName, String simpleName, String className) {
for (File file : SourceFileManager.list(module, packageName)) {
if (containsWord(file.toPath(), simpleName) && containsType(file.toPath(), className)) {
if (file.getName().endsWith(".java")) {
return file.toPath();
}
}
}
return NOT_FOUND;
}
private Path findPublicTypeDeclaration(String className) {
JavaFileObject source;
try {
source =
mSourceFileManager.getJavaFileForInput(
StandardLocation.SOURCE_PATH, className, JavaFileObject.Kind.SOURCE);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (source == null) return NOT_FOUND;
if (!source.toUri().getScheme().equals("file")) return NOT_FOUND;
Path file = Paths.get(source.toUri());
if (!containsType(file, className)) return NOT_FOUND;
return file;
}
public Optional<JavaFileObject> findPublicTypeDeclarationInJdk(String className) {
JavaFileObject source;
try {
source =
mSourceFileManager.getJavaFileForInput(
StandardLocation.PLATFORM_CLASS_PATH, className, JavaFileObject.Kind.CLASS);
} catch (IOException e) {
throw new RuntimeException(e);
}
return Optional.ofNullable(source);
}
@Override
public Path[] findTypeReferences(String className) {
return null;
}
@Override
public Path[] findMemberReferences(String className, String memberName) {
return null;
}
private final Cache<String, ParseTask> parseCache = new Cache<>();
private ParseTask cachedParse(Path file) {
if (parseCache.needs(file, file.toFile().getName())) {
Parser parser = Parser.parseFile(mProject, file);
parseCache.load(file, file.toFile().getName(), new ParseTask(parser.task, parser.root));
}
return parseCache.get(file, file.toFile().getName());
}
private ParseTask cachedParse(JavaFileObject file) {
if (file instanceof PathFileObject) {
// workaround to get the file uri of a JarFileObject
String path = file.toUri().toString().substring(4, file.toUri().toString().lastIndexOf("!"));
Path parsedPath = new File(URI.create(path)).toPath();
if (parseCache.needs(parsedPath, file.getName())) {
Parser parser = Parser.parseJavaFileObject(mProject, file);
parseCache.load(parsedPath, file.getName(), new ParseTask(parser.task, parser.root));
} else {
Log.d("JavaCompilerService", "Using cached parse for " + file.getName());
}
return parseCache.get(parsedPath, file.getName());
} else if (file instanceof SourceFileObject) {
return cachedParse(((SourceFileObject) file).mFile);
}
Parser parser = Parser.parseJavaFileObject(mProject, file);
return new ParseTask(parser.task, parser.root);
}
/**
* Convenience method for parsing a path
*
* @param file Path of java file to compile
* @return ParseTask for this compilation
*/
@Override
public ParseTask parse(Path file) {
return cachedParse(file);
}
/**
* Parses a single java file without analysing and parsing other files
*
* @param file Java file to parse
* @return ParseTask for this compilation
*/
@Override
public ParseTask parse(JavaFileObject file) {
Parser parser = Parser.parseJavaFileObject(mProject, file);
return new ParseTask(parser.task, parser.root);
}
public ParseTask parse(Path file, String contents) {
SourceFileObject object = new SourceFileObject(file, contents, Instant.now());
Parser parser = Parser.parseJavaFileObject(mProject, object);
return new ParseTask(parser.task, parser.root);
}
/**
* Convenience method to compile a list of paths, this just wraps them in a SourceFileObject and
* calls {@link JavaCompilerService#compile(Collection)}
*
* @param files list of java paths to compile
* @return a CompileTask for this compilation
*/
@Override
public CompilerContainer compile(Path... files) {
List<JavaFileObject> sources = new ArrayList<>();
for (Path f : files) {
sources.add(new SourceFileObject(f, mCurrentModule));
}
return compile(sources);
}
/**
* Compiles a list of {@link JavaFileObject} not all of them needs no be compiled if they have
* been compiled before
*
* @param sources list of java sources
* @return a CompileTask for this compilation
*/
@Override
public CompilerContainer compile(Collection<? extends JavaFileObject> sources) {
return compileBatch(sources);
}
public synchronized void close() {
if (cachedCompile != null && !cachedCompile.closed) {
cachedCompile.close();
}
if (mLock.isHeldByCurrentThread() && mLock.isLocked()) {
mLock.unlock();
}
}
public JavaModule getCurrentModule() {
return mCurrentModule;
}
public void destroy() {
mContainer.initialize(
() -> {
close();
if (cachedCompile != null) {
final ReusableCompiler.Borrow borrow = cachedCompile.borrow;
if (borrow != null) {
borrow.close();
}
}
cachedCompile = null;
cachedModified.clear();
compiler = new ReusableCompiler();
});
}
@NonNull
public CompilerContainer getCachedContainer() {
return mContainer;
}
}
| 16,217 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ClassImportInsertHandler.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/insert/ClassImportInsertHandler.java | package com.tyron.completion.java.insert;
import com.tyron.builder.model.SourceFileObject;
import com.tyron.completion.DefaultInsertHandler;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.compiler.ParseTask;
import com.tyron.completion.java.compiler.Parser;
import com.tyron.completion.java.rewrite.AddImport;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.model.TextEdit;
import com.tyron.completion.util.RewriteUtil;
import com.tyron.editor.Editor;
import java.io.File;
import java.time.Instant;
import java.util.Map;
public class ClassImportInsertHandler extends DefaultInsertHandler {
protected final File file;
private final JavaCompilerService service;
public ClassImportInsertHandler(JavaCompilerService provider, File file, CompletionItem item) {
super(item);
this.file = file;
this.service = provider;
}
@Override
public void handleInsert(Editor editor) {
super.handleInsert(editor);
AddImport addImport = new AddImport(file, item.data);
Parser parse =
Parser.parseJavaFileObject(
service.getProject(),
new SourceFileObject(file.toPath(), editor.getContent().toString(), Instant.now()));
Map<File, TextEdit> imports = addImport.getText(new ParseTask(parse.task, parse.root));
for (Map.Entry<File, TextEdit> entry : imports.entrySet()) {
RewriteUtil.applyTextEdit(editor, entry.getValue());
}
}
}
| 1,479 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
KeywordInsertHandler.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/insert/KeywordInsertHandler.java | package com.tyron.completion.java.insert;
import com.sun.source.tree.MethodTree;
import com.sun.source.util.TreePath;
import com.tyron.completion.DefaultInsertHandler;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.util.TreeUtil;
import com.tyron.completion.model.CompletionItem;
import com.tyron.editor.Caret;
import com.tyron.editor.Editor;
public class KeywordInsertHandler extends DefaultInsertHandler {
private final CompileTask task;
private final TreePath currentPath;
public KeywordInsertHandler(CompileTask task, TreePath currentPath, CompletionItem item) {
super(item);
this.task = task;
this.currentPath = currentPath;
}
@Override
protected void insert(String string, Editor editor, boolean calcSpace) {
Caret caret = editor.getCaret();
int line = caret.getStartLine();
int column = caret.getStartColumn();
if ("return".equals(string)) {
TreePath method = TreeUtil.findParentOfType(currentPath, MethodTree.class);
if (method != null) {
MethodTree methodTree = (MethodTree) method.getLeaf();
String textToInsert = "return";
if (TreeUtil.isVoid(methodTree)) {
textToInsert = "return;";
} else if (isEndOfLine(line, column, editor)) {
textToInsert = "return ";
}
super.insert(textToInsert, editor, false);
return;
}
}
deletePrefix(editor);
super.insert(string, editor, true);
}
}
| 1,484 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
MethodInsertHandler.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/insert/MethodInsertHandler.java | package com.tyron.completion.java.insert;
import com.tyron.common.util.StringSearch;
import com.tyron.completion.DefaultInsertHandler;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.util.CompletionUtils;
import com.tyron.editor.Caret;
import com.tyron.editor.Editor;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.TypeKind;
public class MethodInsertHandler extends DefaultInsertHandler {
private boolean includeParen;
private final ExecutableElement method;
public MethodInsertHandler(ExecutableElement method, boolean includeParen, CompletionItem item) {
super(CompletionUtils.JAVA_PREDICATE, item);
this.method = method;
this.includeParen = includeParen;
}
public MethodInsertHandler(ExecutableElement method, CompletionItem item) {
this(method, false, item);
}
public MethodInsertHandler(ExecutableElement method, CompletionItem item, boolean includeParen) {
this(method, includeParen, item);
}
@Override
public void handleInsert(Editor editor) {
deletePrefix(editor);
String commitText = item.commitText;
Caret caret = editor.getCaret();
boolean isEndOfLine = isEndOfLine(caret.getStartLine(), caret.getStartColumn(), editor);
boolean endsWithParen =
StringSearch.endsWithParen(editor.getContent(), editor.getCaret().getStart());
if (endsWithParen) {
if (commitText.endsWith("()")) {
commitText = commitText.substring(0, commitText.length() - 2);
} else if (commitText.endsWith("();")) {
commitText = commitText.substring(0, commitText.length() - 3);
}
} else if (includeParen) {
commitText += "()";
}
boolean insertSemi = shouldInsertSemiColon() && isEndOfLine;
if (insertSemi) {
commitText = commitText + ";";
}
insert(commitText, editor, false);
String lineString = editor.getContent().getLineString(caret.getStartLine());
int startIndex = caret.getStartColumn() - commitText.length();
int offset = 0;
if (hasParameters()) {
offset = lineString.indexOf('(', startIndex);
} else {
offset = lineString.indexOf(')', startIndex);
int semicolon = lineString.indexOf(';', startIndex);
// if the text contains semicolon and the semicolon is right next to the ')' character
if (semicolon == offset + 1) {
offset = semicolon;
}
}
if (offset != -1) {
editor.setSelection(caret.getStartLine(), offset + 1);
}
}
private boolean hasParameters() {
return !method.getParameters().isEmpty();
}
private boolean shouldInsertSemiColon() {
if (method.getReturnType().getKind() == TypeKind.VOID) {
return true;
}
return method.getReturnType().getKind().isPrimitive();
}
}
| 2,791 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaPrettyPrinterVisitor.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/JavaPrettyPrinterVisitor.java | package com.tyron.completion.java.util;
import static com.github.javaparser.utils.PositionUtils.sortByBeginPosition;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.comments.Comment;
import com.github.javaparser.ast.expr.Name;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.printer.DefaultPrettyPrinterVisitor;
import com.github.javaparser.printer.SourcePrinter;
import com.github.javaparser.printer.configuration.ConfigurationOption;
import com.github.javaparser.printer.configuration.DefaultConfigurationOption;
import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration;
import com.github.javaparser.printer.configuration.PrinterConfiguration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class JavaPrettyPrinterVisitor extends DefaultPrettyPrinterVisitor {
public JavaPrettyPrinterVisitor(PrinterConfiguration configuration) {
super(configuration);
}
public JavaPrettyPrinterVisitor(PrinterConfiguration configuration, SourcePrinter printer) {
super(configuration, printer);
}
@Override
public void visit(Name n, Void arg) {
printOrphanCommentsBeforeThisChildNode(n);
printComment(n.getComment(), arg);
if (false) {
if (n.getQualifier().isPresent()) {
n.getQualifier().get().accept(this, arg);
printer.print(".");
}
}
printer.print(n.getIdentifier());
printOrphanCommentsEnding(n);
}
@Override
public void visit(ClassOrInterfaceType n, Void arg) {
printOrphanCommentsBeforeThisChildNode(n);
printComment(n.getComment(), arg);
if (false) {
if (n.getScope().isPresent()) {
n.getScope().get().accept(this, arg);
printer.print(".");
}
}
printAnnotations(n.getAnnotations(), false, arg);
n.getName().accept(this, arg);
if (n.isUsingDiamondOperator()) {
printer.print("<>");
} else {
printTypeArgs(n, arg);
}
}
@Override
public void visit(SimpleName n, Void arg) {
printOrphanCommentsBeforeThisChildNode(n);
printComment(n.getComment(), arg);
String identifier = n.getIdentifier();
printer.print(ActionUtil.getSimpleName(identifier));
}
protected void printOrphanCommentsBeforeThisChildNode(final Node node) {
if (!getOption(DefaultPrinterConfiguration.ConfigOption.PRINT_COMMENTS).isPresent()) return;
if (node instanceof Comment) return;
Node parent = node.getParentNode().orElse(null);
if (parent == null) return;
List<Node> everything = new ArrayList<>(parent.getChildNodes());
sortByBeginPosition(everything);
int positionOfTheChild = -1;
for (int i = 0; i < everything.size(); ++i) { // indexOf is by equality, so this
// is used to index by identity
if (everything.get(i) == node) {
positionOfTheChild = i;
break;
}
}
if (positionOfTheChild == -1) {
throw new AssertionError("I am not a child of my parent.");
}
int positionOfPreviousChild = -1;
for (int i = positionOfTheChild - 1; i >= 0 && positionOfPreviousChild == -1; i--) {
if (!(everything.get(i) instanceof Comment)) positionOfPreviousChild = i;
}
for (int i = positionOfPreviousChild + 1; i < positionOfTheChild; i++) {
Node nodeToPrint = everything.get(i);
if (!(nodeToPrint instanceof Comment))
throw new RuntimeException(
"Expected comment, instead "
+ nodeToPrint.getClass()
+ ". Position of previous child: "
+ positionOfPreviousChild
+ ", position of child "
+ positionOfTheChild);
nodeToPrint.accept(this, null);
}
}
protected void printOrphanCommentsEnding(final Node node) {
if (!getOption(DefaultPrinterConfiguration.ConfigOption.PRINT_COMMENTS).isPresent()) return;
List<Node> everything = new ArrayList<>(node.getChildNodes());
sortByBeginPosition(everything);
if (everything.isEmpty()) {
return;
}
int commentsAtEnd = 0;
boolean findingComments = true;
while (findingComments && commentsAtEnd < everything.size()) {
Node last = everything.get(everything.size() - 1 - commentsAtEnd);
findingComments = (last instanceof Comment);
if (findingComments) {
commentsAtEnd++;
}
}
for (int i = 0; i < commentsAtEnd; i++) {
everything.get(everything.size() - commentsAtEnd + i).accept(this, null);
}
}
private Optional<ConfigurationOption> getOption(
DefaultPrinterConfiguration.ConfigOption cOption) {
return configuration.get(new DefaultConfigurationOption(cOption));
}
}
| 4,752 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FileContentFixer.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/FileContentFixer.java | package com.tyron.completion.java.util;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Ordering;
import com.sun.source.tree.LineMap;
import com.sun.tools.javac.parser.Scanner;
import com.sun.tools.javac.parser.ScannerFactory;
import com.sun.tools.javac.parser.Tokens.Token;
import com.sun.tools.javac.parser.Tokens.TokenKind;
import com.sun.tools.javac.util.Context;
import com.tyron.completion.progress.ProgressManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class FileContentFixer {
/**
* The injected identifier before completion, this is done so it so there will always be a text at
* the current position of the caret.
*/
public static final String INJECTED_IDENT = "CodeAssistRulezzzz";
private static final Set<TokenKind> VALID_MEMBER_SELECTION_TOKENS =
ImmutableSet.of(
TokenKind.IDENTIFIER,
TokenKind.LT,
TokenKind.NEW,
TokenKind.THIS,
TokenKind.SUPER,
TokenKind.CLASS,
TokenKind.STAR);
/** Token kinds that can not be right after a memeber selection. */
private static final Set<TokenKind> INVALID_MEMBER_SELECTION_SUFFIXES =
ImmutableSet.of(TokenKind.RBRACE);
private final Context context;
public FileContentFixer(Context context) {
this.context = context;
}
public CharSequence fixFileContent(CharSequence content) {
Scanner scanner = ScannerFactory.instance(context).newScanner(content, true);
List<Insertion> insertions = new ArrayList<>();
for (; ; scanner.nextToken()) {
ProgressManager.checkCanceled();
Token token = scanner.token();
if (token.kind == TokenKind.EOF) {
break;
} else if (token.kind == TokenKind.DOT || token.kind == TokenKind.COLCOL) {
fixMemberSelection(scanner, insertions);
} else if (token.kind == TokenKind.ERROR) {
int errPos = scanner.errPos();
if (errPos >= 0 && errPos < content.length()) {
fixError(scanner, content, insertions);
}
}
}
return Insertion.applyInsertions(content, insertions);
}
private void fixMemberSelection(Scanner scanner, List<Insertion> insertions) {
Token token = scanner.token();
Token nextToken = scanner.token(1);
LineMap lineMap = scanner.getLineMap();
int tokenLine = (int) lineMap.getLineNumber(token.pos);
int nextLine = (int) lineMap.getLineNumber(nextToken.pos);
if (nextLine > tokenLine) {
// The line ends with a dot. It's likely the user is entering a dot and waiting for member
// completion. The current line is incomplete and contextually invalid.
insertions.add(Insertion.create(token.endPos, INJECTED_IDENT + ";"));
} else if (!VALID_MEMBER_SELECTION_TOKENS.contains(nextToken.kind)) {
String toInsert = INJECTED_IDENT;
if (INVALID_MEMBER_SELECTION_SUFFIXES.contains(nextToken.kind)) {
toInsert = INJECTED_IDENT + ";";
}
// The member selection is contextually invalid. Fix it.
insertions.add(Insertion.create(token.endPos, toInsert));
}
}
private void fixError(Scanner scanner, CharSequence content, List<Insertion> insertions) {
int errPos = scanner.errPos();
if (content.charAt(errPos) == '.' && errPos > 0 && content.charAt(errPos) == '.') {
// The scanner fails at two dots because it expects three dots for
// ellipse. The errPos is at the second dot.
//
// If the second dot is followed by an identifier character, it's likely
// the user is trying to complete between the two dots. Otherwise, the
// user is likely in the process of typing the third dot.
if (errPos < content.length() - 1
&& Character.isJavaIdentifierStart(content.charAt(errPos + 1))) {
// Insert a dumbIdent between two dots so the Javac parser can parse it.
insertions.add(Insertion.create(errPos, INJECTED_IDENT));
}
}
}
public static class Insertion {
private static final Ordering<Insertion> REVERSE_INSERTION =
Ordering.natural().onResultOf(Insertion::getPos).reverse();
private final int pos;
private final String text;
public Insertion(int pos, String text) {
this.pos = pos;
this.text = text;
}
public int getPos() {
return pos;
}
public String getText() {
return text;
}
public static Insertion create(int pos, String text) {
return new Insertion(pos, text);
}
public static CharSequence applyInsertions(CharSequence content, List<Insertion> insertions) {
List<Insertion> reverseInsertions = REVERSE_INSERTION.immutableSortedCopy(insertions);
StringBuilder sb = new StringBuilder(content);
for (Insertion insertion : reverseInsertions) {
sb.insert(insertion.getPos(), insertion.getText());
}
return sb;
}
}
}
| 4,910 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ElementUtil.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/ElementUtil.java | package com.tyron.completion.java.util;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import com.sun.source.tree.Scope;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.provider.ScopeHelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
public class ElementUtil {
/**
* Gets all the fully qualified name of classes that can be found on this type
*
* @param typeMirror The type to search
* @return list of fully qualified class names
*/
public static List<String> getAllClasses(TypeMirror typeMirror) {
TypeKind kind = typeMirror.getKind();
if (kind == TypeKind.DECLARED) {
List<String> classes = new ArrayList<>();
DeclaredType declaredType = (DeclaredType) typeMirror;
TypeElement element = (TypeElement) declaredType.asElement();
if (isAnonymous(declaredType)) {
// the type of an anonymous class
classes.add(element.getSuperclass().toString());
} else {
classes.add(element.toString());
}
for (TypeMirror argument : declaredType.getTypeArguments()) {
classes.addAll(getAllClasses(argument));
}
return classes;
}
return Collections.emptyList();
}
private static boolean isAnonymous(TypeMirror typeMirror) {
return typeMirror.toString().startsWith("<anonymous");
}
public static String simpleType(TypeMirror mirror) {
return simpleClassName(mirror.toString());
}
public static String simpleClassName(String name) {
return name.replaceAll("[a-zA-Z\\.0-9_\\$]+\\.", "");
}
public static boolean isEnclosingClass(DeclaredType type, Scope start) {
checkCanceled();
for (Scope s : ScopeHelper.fastScopes(start)) {
// If we reach a static method, stop looking
ExecutableElement method = s.getEnclosingMethod();
if (method != null && method.getModifiers().contains(Modifier.STATIC)) {
return false;
}
// If we find the enclosing class
TypeElement thisElement = s.getEnclosingClass();
if (thisElement != null && thisElement.asType().equals(type)) {
return true;
}
// If the enclosing class is static, stop looking
if (thisElement != null && thisElement.getModifiers().contains(Modifier.STATIC)) {
return false;
}
}
return false;
}
public static boolean isFinal(ExecutableElement element) {
Set<Modifier> modifiers = element.getModifiers();
if (modifiers == null) {
return false;
}
return modifiers.contains(Modifier.FINAL);
}
/**
* Search all the super class of the provided TypeElement to see if the given method is overriding
* a method from them
*
* <p>This is a hack, since ExecutableElement does not override equals and hashCode, i manually
* checked the necessary information to determine on whether the two methods are equal.
*/
public static boolean isMemberOf(CompileTask task, ExecutableElement method, TypeElement aClass) {
if (aClass == null) {
return false;
}
outer:
for (Element member : task.task.getElements().getAllMembers(aClass)) {
if (member.getKind() != ElementKind.METHOD) {
continue;
}
ExecutableElement execMember = (ExecutableElement) member;
if (ElementUtil.isFinal(execMember)) {
// cannot override final methods
continue;
}
// check the name of methods
if (!method.getSimpleName().contentEquals(execMember.getSimpleName())) {
continue;
}
// return type does not matter when checking if two methods are equal
List<? extends VariableElement> parameters = method.getParameters();
List<? extends VariableElement> execParameters = execMember.getParameters();
if (parameters.size() != execParameters.size()) {
continue;
}
// check for the parameter types, only checking their class names
for (VariableElement parameter : parameters) {
for (VariableElement execParameter : execParameters) {
if (parameter != null && execParameter != null) {
if (!parameter.asType().toString().equals(execParameter.asType().toString())) {
continue outer;
}
}
}
}
return true;
}
return false;
}
}
| 4,784 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CompilationUnitConverter.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/CompilationUnitConverter.java | package com.tyron.completion.java.util;
import com.github.javaparser.Position;
import com.github.javaparser.Range;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
import com.github.javaparser.ast.nodeTypes.NodeWithModifiers;
import com.github.javaparser.ast.nodeTypes.NodeWithRange;
import com.github.javaparser.ast.nodeTypes.NodeWithTypeParameters;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.PrimitiveType;
import com.github.javaparser.ast.type.ReferenceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.type.UnknownType;
import com.github.javaparser.ast.type.VoidType;
import com.github.javaparser.ast.type.WildcardType;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.LineMap;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.PrimitiveTypeTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.WildcardTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.tree.DocCommentTable;
import com.sun.tools.javac.tree.EndPosTable;
import com.sun.tools.javac.tree.JCTree;
import com.tyron.completion.java.compiler.ParseTask;
import java.util.List;
/** Converts the CompilationUnitTree generated by javac into {@link CompilationUnit}. */
public class CompilationUnitConverter extends TreeScanner<Void, Node> {
/**
* Delegate for converting an index based position into line and column based position.
*
* <p>This is needed because javac treats tabs as 8 spaces and it causes inconsistencies with
* editors that treats tabs as 4 spaces
*/
public interface LineColumnCallback {
int getLine(int pos);
int getColumn(int pos);
}
private CompilationUnit mCompilationUnit = null;
private LineMap mLineMap;
private EndPosTable mEndPosTable = null;
private DocCommentTable mDocComments = null;
private final ParseTask mParseTask;
private final String mContents;
private final LineColumnCallback mCallback;
public CompilationUnitConverter(ParseTask task, String contents, LineColumnCallback callback) {
mParseTask = task;
mContents = contents;
mCallback = callback;
}
public CompilationUnit startScan() {
scan(mParseTask.root, null);
return mCompilationUnit;
}
@Override
public Void visitCompilationUnit(CompilationUnitTree node, Node current) {
JCTree.JCCompilationUnit unit = (JCTree.JCCompilationUnit) node;
mLineMap = unit.getLineMap();
mEndPosTable = unit.endPositions;
mDocComments = unit.docComments;
mCompilationUnit = new CompilationUnit();
addNodeRange(unit, mCompilationUnit);
if (unit.getPackageName() != null) {
PackageDeclaration packageDeclaration = new PackageDeclaration();
packageDeclaration.setName(unit.getPackageName().toString());
addNodeRange(node.getPackage(), packageDeclaration);
mCompilationUnit.setPackageDeclaration(packageDeclaration);
}
for (ImportTree importTree : unit.getImports()) {
String name = importTree.getQualifiedIdentifier().toString();
if (name.isEmpty()) {
continue;
}
boolean isAsterisk = name.endsWith("*");
boolean isStatic = importTree.isStatic();
ImportDeclaration importDeclaration = new ImportDeclaration(name, isStatic, isAsterisk);
mCompilationUnit.addImport(importDeclaration);
addNodeRange(importTree, importDeclaration);
}
for (Tree decl : node.getTypeDecls()) {
this.scan(decl, mCompilationUnit);
}
mEndPosTable = null;
return null;
}
@Override
public Void visitClass(ClassTree classTree, Node current) {
ClassOrInterfaceDeclaration declaration = new ClassOrInterfaceDeclaration();
addNodeRange(classTree, declaration);
if (classTree.getModifiers() != null) {
scan(classTree.getModifiers(), declaration);
}
Tree extendsClause = classTree.getExtendsClause();
if (extendsClause != null) {
ClassOrInterfaceType extended = JavaParserTypesUtil.toClassOrInterfaceType(extendsClause);
addNodeRange(extendsClause, extended);
declaration.setExtendedTypes(NodeList.nodeList(extended));
}
List<? extends Tree> implementsClause = classTree.getImplementsClause();
for (Tree tree : implementsClause) {
ClassOrInterfaceType implemented = JavaParserTypesUtil.toClassOrInterfaceType(tree);
addNodeRange(tree, implemented);
declaration.addImplementedType(implemented);
}
int classStart = ((JCTree.JCClassDecl) classTree).getStartPosition();
int classEnd = mEndPosTable.getEndPos((JCTree) classTree);
String contents = mContents.substring(classStart, classEnd);
String name = classTree.getSimpleName().toString();
declaration.setName(name);
declaration.getName().setRange(getRangeForName(contents, name, classStart));
if (classTree.getTypeParameters() != null) {
scan(classTree.getTypeParameters(), declaration);
}
for (Tree member : classTree.getMembers()) {
scan(member, declaration);
}
((CompilationUnit) current).addType(declaration);
return null;
}
@Override
public Void visitMethod(MethodTree methodTree, Node node) {
int methodStart = ((JCTree.JCMethodDecl) methodTree).getStartPosition();
int methodEnd = ((JCTree.JCMethodDecl) methodTree).getEndPosition(mEndPosTable);
String contents = mContents.substring(methodStart, methodEnd);
MethodDeclaration methodDeclaration = new MethodDeclaration();
if (methodTree.getModifiers() != null) {
scan(methodTree.getModifiers(), methodDeclaration);
}
if (methodTree.getTypeParameters() != null) {
scan(methodTree.getTypeParameters(), methodDeclaration);
}
Type type = getType(methodTree.getReturnType());
methodDeclaration.setType(type);
String name = methodTree.getName().toString();
methodDeclaration.setName(name);
methodDeclaration.getName().setRange(getRangeForName(contents, name, methodStart));
addNodeRange(methodTree, methodDeclaration);
if (node instanceof ClassOrInterfaceDeclaration) {
((ClassOrInterfaceDeclaration) node).addMember(methodDeclaration);
}
return null;
}
@Override
public Void visitTypeParameter(TypeParameterTree typeParameterTree, Node node) {
if (node instanceof NodeWithTypeParameters) {
TypeParameter typeParameter = new TypeParameter();
int typeStart = ((JCTree.JCTypeParameter) typeParameterTree).getStartPosition();
int typeEnd = ((JCTree.JCTypeParameter) typeParameterTree).getEndPosition(mEndPosTable);
String contents = mContents.substring(typeStart, typeEnd);
String name = typeParameterTree.getName().toString();
typeParameter.setName(name);
if (typeParameterTree.getBounds() != null) {
NodeList<ClassOrInterfaceType> typeParameters = new NodeList<>();
for (Tree bound : typeParameterTree.getBounds()) {
ClassOrInterfaceType type = getClassOrInterfaceType(bound);
typeParameters.add(type);
}
typeParameter.setTypeBound(typeParameters);
}
typeParameter.getName().setRange(getRangeForName(contents, name, typeStart));
((NodeWithTypeParameters<?>) node).addTypeParameter(typeParameter);
}
return null;
}
private ClassOrInterfaceType getClassOrInterfaceType(Tree tree) {
ClassOrInterfaceType type = new ClassOrInterfaceType();
if (tree instanceof IdentifierTree) {
type.setName(((IdentifierTree) tree).getName().toString());
type.getName().setRange(getTreeRange(tree));
addNodeRange(tree, type);
}
if (tree instanceof ParameterizedTypeTree) {
ParameterizedTypeTree parameterizedTypeTree = (ParameterizedTypeTree) tree;
Type t = getType(parameterizedTypeTree.getType());
NodeList<Type> typeArguments = new NodeList<>();
for (Tree typeArgument : parameterizedTypeTree.getTypeArguments()) {
Type typ = getType(typeArgument);
typeArguments.add(typ);
}
if (t.isClassOrInterfaceType()) {
type.setName(t.asClassOrInterfaceType().getName());
}
type.setTypeArguments(typeArguments);
}
return type;
}
private Type getType(Tree tree) {
Type type;
if (tree instanceof PrimitiveTypeTree) {
type = getPrimitiveType((PrimitiveTypeTree) tree);
} else if (tree instanceof IdentifierTree) {
type = getClassOrInterfaceType(tree);
} else if (tree instanceof WildcardTree) {
JCTree.JCWildcard wildcardTree = (JCTree.JCWildcard) tree;
WildcardType wildcardType = new WildcardType();
Tree bound = wildcardTree.getBound();
Type boundType = getType(bound);
if (wildcardTree.kind.kind == BoundKind.EXTENDS) {
wildcardType.setExtendedType((ReferenceType) boundType);
} else {
wildcardType.setSuperType((ReferenceType) boundType);
}
type = wildcardType;
} else if (tree instanceof ParameterizedTypeTree) {
type = getClassOrInterfaceType(tree);
} else {
type = new UnknownType();
}
type.setRange(getTreeRange(tree));
return type;
}
private Type getPrimitiveType(PrimitiveTypeTree tree) {
Type type;
switch (tree.getPrimitiveTypeKind()) {
case INT:
type = PrimitiveType.intType();
break;
case BOOLEAN:
type = PrimitiveType.booleanType();
break;
case LONG:
type = PrimitiveType.longType();
break;
case SHORT:
type = PrimitiveType.shortType();
break;
case CHAR:
type = PrimitiveType.charType();
break;
case FLOAT:
type = PrimitiveType.floatType();
break;
case VOID:
type = new VoidType();
break;
default:
type = new UnknownType();
}
type.setRange(getTreeRange(tree));
return type;
}
@Override
public Void visitModifiers(ModifiersTree modifiersTree, Node node) {
// ModifiersTree also contains annotations, add them here
if (node instanceof NodeWithModifiers) {
NodeList<Modifier> modifiers = new NodeList<>();
for (javax.lang.model.element.Modifier flag : modifiersTree.getFlags()) {
Modifier modifier = JavaParserUtil.toModifier(flag);
addNodeRange(modifiersTree, modifier);
modifiers.add(modifier);
}
((NodeWithModifiers<?>) node).setModifiers(modifiers);
}
if (node instanceof NodeWithAnnotations) {
for (AnnotationTree annotation : modifiersTree.getAnnotations()) {
AnnotationExpr expr = JavaParserUtil.toAnnotation(annotation);
addNodeRange(annotation, expr);
((NodeWithAnnotations<?>) node).addAnnotation(expr);
}
}
return null;
}
private Position getPosition(int start) {
int line = mCallback.getLine(start);
int column = mCallback.getColumn(start);
return new Position(line, column);
}
/**
* Creates a range object based on the position of the tree
*
* @param tree Javac Tree
* @return Range representing the position of the tree
*/
private Range getTreeRange(Tree tree) {
JCTree jcTree = ((JCTree) tree);
int start = jcTree.getStartPosition();
int end = jcTree.getEndPosition(mEndPosTable);
if (end < 0) {
end = start + 1;
}
return Range.range(getPosition(start), getPosition(end));
}
/**
* Convenience method for getting the range of a name identifier
*
* @param contents The contents of the tree where the name can be found
* @param name Name to get the range for
* @param startPos The start index of the tree from the main CompilationUnit
* @return the range of the position of the name
*/
private Range getRangeForName(String contents, String name, int startPos) {
int startName = contents.indexOf(name);
int endName = startName + name.length();
int start = startPos + startName;
int end = startPos + endName;
return Range.range(getPosition(start), getPosition(end));
}
/**
* Convenience method to add a range of the tree into its node
*
* @param tree javac generated tree
* @param node node on where to add the range
*/
private void addNodeRange(Tree tree, NodeWithRange<?> node) {
node.setRange(getTreeRange(tree));
}
}
| 13,161 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
PrintHelper.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/PrintHelper.java | package com.tyron.completion.java.util;
import static com.tyron.completion.java.rewrite.EditHelper.printBody;
import static com.tyron.completion.java.rewrite.EditHelper.printParameters;
import static com.tyron.completion.java.rewrite.EditHelper.printThrows;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Type;
import com.tyron.completion.java.rewrite.EditHelper;
import java.util.List;
import java.util.StringJoiner;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeMirror;
/**
* Converts the given Element directly into String without converting first through {@link
* com.github.javaparser.JavaParser}
*/
public class PrintHelper {
/**
* Prints a given method into a String, adds {@code throws UnsupportedOperationException} to the
* method body if the source is null, it will get the parameter names from the class file which
* will be {@code arg1, arg2, arg3}
*
* <p>Not to be confused with {@link EditHelper#printMethod(ExecutableElement, ExecutableType,
* MethodTree)} This does not convert the method into a {@link
* com.github.javaparser.ast.body.MethodDeclaration}
*
* @param method method to print
* @param parameterizedType type parameters of this method
* @param source the source method, in which the parameter names are fetched
* @return a string that represents the method
*/
public static String printMethod(
ExecutableElement method, ExecutableType parameterizedType, MethodTree source) {
StringBuilder buf = new StringBuilder();
buf.append("@Override\n");
if (method.getModifiers().contains(Modifier.PUBLIC)) {
buf.append("public ");
}
if (method.getModifiers().contains(Modifier.PROTECTED)) {
buf.append("protected ");
}
buf.append(PrintHelper.printType(parameterizedType.getReturnType())).append(" ");
buf.append(method.getSimpleName()).append("(");
if (source == null) {
buf.append(printParameters(parameterizedType, method));
} else {
buf.append(printParameters(parameterizedType, source));
}
buf.append(") {\n\t");
buf.append(printBody(method, source));
buf.append("\n}");
return buf.toString();
}
public static String printMethod(
ExecutableElement method, ExecutableType parameterizedType, ExecutableElement source) {
StringBuilder buf = new StringBuilder();
buf.append("@Override\n");
if (method.getModifiers().contains(Modifier.PUBLIC)) {
buf.append("public ");
}
if (method.getModifiers().contains(Modifier.PROTECTED)) {
buf.append("protected ");
}
buf.append(PrintHelper.printType(parameterizedType.getReturnType())).append(" ");
buf.append(method.getSimpleName()).append("(");
if (source == null) {
buf.append(printParameters(parameterizedType, method));
} else {
buf.append(printParameters(parameterizedType, source));
}
buf.append(") ");
if (method.getThrownTypes() != null && !method.getThrownTypes().isEmpty()) {
buf.append(printThrows(method.getThrownTypes()));
buf.append(" ");
}
buf.append("{\n\t");
buf.append(printBody(method, source));
buf.append("\n}");
return buf.toString();
}
/**
* Prints parameters given the source method that contains parameter names
*
* @param method element from the .class file
* @param source element from the .java file
* @return Formatted string that represents the methods parameters with proper names
*/
public static String printParameters(ExecutableType method, MethodTree source) {
StringJoiner join = new StringJoiner(", ");
for (int i = 0; i < method.getParameterTypes().size(); i++) {
String type = printType(method.getParameterTypes().get(i));
Name name = source.getParameters().get(i).getName();
join.add(type + " " + name);
}
return join.toString();
}
public static String printParameters(ExecutableType method, ExecutableElement source) {
StringJoiner join = new StringJoiner(", ");
for (int i = 0; i < method.getParameterTypes().size(); i++) {
String type = printType(method.getParameterTypes().get(i));
Name name = source.getParameters().get(i).getSimpleName();
join.add(type + " " + name);
}
return join.toString();
}
public static String printType(TypeMirror type) {
return printType(type, false);
}
public static String printType(TypeMirror type, boolean fqn) {
if (type instanceof DeclaredType) {
DeclaredType declared = (DeclaredType) type;
if (declared instanceof Type.ClassType) {
Type.ClassType classType = (Type.ClassType) declared;
if (classType.all_interfaces_field != null && !classType.all_interfaces_field.isEmpty()) {
Type next = classType.all_interfaces_field.get(0);
declared = (DeclaredType) next;
}
}
String string = EditHelper.printTypeName((TypeElement) declared.asElement(), fqn);
if (!declared.getTypeArguments().isEmpty()) {
string = string + "<" + printTypeParameters(declared.getTypeArguments()) + ">";
}
return string;
} else if (type instanceof ArrayType) {
ArrayType arrayType = (ArrayType) type;
if (!fqn) {
return printType(arrayType.getComponentType()) + "[]";
} else {
return arrayType.toString();
}
} else if (type instanceof Type.TypeVar) {
Type.TypeVar typeVar = ((Type.TypeVar) type);
if (typeVar.isCaptured()) {
return "? extends " + printType(typeVar.getUpperBound(), fqn);
}
return typeVar.toString();
} else {
if (fqn) {
return type.toString();
} else {
return ActionUtil.getSimpleName(type.toString());
}
}
}
public static String printTypeParameters(List<? extends TypeMirror> arguments) {
StringJoiner join = new StringJoiner(", ");
for (TypeMirror a : arguments) {
join.add(printType(a));
}
return join.toString();
}
}
| 6,284 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaDataContextUtil.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/JavaDataContextUtil.java | package com.tyron.completion.java.util;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.TreePath;
import com.tyron.actions.DataContext;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.builder.project.api.Module;
import com.tyron.common.SharedPreferenceKeys;
import com.tyron.completion.index.CompilerService;
import com.tyron.completion.java.JavaCompilerProvider;
import com.tyron.completion.java.action.CommonJavaContextKeys;
import com.tyron.completion.java.action.FindCurrentPath;
import com.tyron.completion.java.compiler.CompilerContainer;
import com.tyron.completion.java.compiler.JavaCompilerService;
import java.io.File;
public class JavaDataContextUtil {
public static void addEditorKeys(DataContext context, Project project, File file, int cursor) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (project != null
&& preferences.getBoolean(SharedPreferenceKeys.JAVA_ERROR_HIGHLIGHTING, true)) {
Module currentModule = project.getModule(file);
if (currentModule instanceof JavaModule) {
JavaCompilerProvider service =
CompilerService.getInstance().getIndex(JavaCompilerProvider.KEY);
JavaCompilerService compiler = service.getCompiler(project, (JavaModule) currentModule);
CompilerContainer cachedContainer = compiler.getCachedContainer();
// don't block the ui thread
if (!cachedContainer.isWriting()) {
cachedContainer.run(
task -> {
if (task != null) {
CompilationUnitTree root = task.root(file);
if (root != null) {
FindCurrentPath findCurrentPath = new FindCurrentPath(task.task);
TreePath currentPath = findCurrentPath.scan(root, cursor);
context.putData(CommonJavaContextKeys.CURRENT_PATH, currentPath);
}
}
});
}
context.putData(CommonJavaContextKeys.COMPILER, compiler);
}
}
}
}
| 2,213 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
DiagnosticUtil.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/DiagnosticUtil.java | package com.tyron.completion.java.util;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.sun.source.tree.Tree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.sun.tools.javac.api.ClientCodeWrapper;
import com.tyron.builder.model.DiagnosticWrapper;
import com.tyron.completion.java.action.FindMethodDeclarationAt;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.editor.CharPosition;
import com.tyron.editor.Editor;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
public class DiagnosticUtil {
private static final Pattern UNREPORTED_EXCEPTION =
Pattern.compile("unreported exception (" + "(\\w+\\.)*\\w+)");
public static void setLineAndColumn(DiagnosticWrapper diagnostic, Editor editor) {
try {
if (diagnostic.getStartLine() <= -1 && diagnostic.getStartPosition() > 0) {
CharPosition start = editor.getCharPosition(((int) diagnostic.getStartPosition()));
diagnostic.setStartLine(start.getLine() + 1);
diagnostic.setStartColumn(start.getColumn());
diagnostic.setLineNumber(start.getLine() + 1);
diagnostic.setColumnNumber(start.getColumn());
}
if (diagnostic.getEndLine() <= -1 && diagnostic.getEndPosition() > 0) {
CharPosition end = editor.getCharPosition(((int) diagnostic.getEndPosition()));
diagnostic.setEndLine(end.getLine() + 1);
diagnostic.setEndColumn(end.getColumn());
}
} catch (IndexOutOfBoundsException ignored) {
// unknown index, dont display line number
}
}
public static class MethodPtr {
public String className, methodName;
public String[] erasedParameterTypes;
public ExecutableElement method;
public MethodPtr(JavacTask task, ExecutableElement method) {
this.method = method;
Types types = task.getTypes();
TypeElement parent = (TypeElement) method.getEnclosingElement();
className = parent.getQualifiedName().toString();
methodName = method.getSimpleName().toString();
erasedParameterTypes = new String[method.getParameters().size()];
for (int i = 0; i < erasedParameterTypes.length; i++) {
VariableElement param = method.getParameters().get(i);
TypeMirror type = param.asType();
TypeMirror erased = types.erasure(type);
erasedParameterTypes[i] = erased.toString();
}
}
@NonNull
@Override
public String toString() {
return "MethodPtr{"
+ "className='"
+ className
+ '\''
+ ", methodName='"
+ methodName
+ '\''
+ ", erasedParameterTypes="
+ Arrays.toString(erasedParameterTypes)
+ ", method="
+ method
+ '}';
}
}
/**
* Gets the diagnostics of the current compile task
*
* @param task the current compile task where the diagnostic is retrieved
* @param cursor the current cursor position
* @return null if no diagnostic is found
*/
@Nullable
public static Diagnostic<? extends JavaFileObject> getDiagnostic(CompileTask task, long cursor) {
return getDiagnostic(task.diagnostics, cursor);
}
public static Diagnostic<? extends JavaFileObject> getDiagnostic(
List<Diagnostic<? extends JavaFileObject>> diagnostics, long cursor) {
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
if (diagnostic.getStartPosition() <= cursor && cursor < diagnostic.getEndPosition()) {
return diagnostic;
}
}
return null;
}
public static DiagnosticWrapper getDiagnosticWrapper(
List<DiagnosticWrapper> diagnostics, long start, long end) {
if (diagnostics == null) {
return null;
}
DiagnosticWrapper current = null;
for (DiagnosticWrapper diagnostic : diagnostics) {
if (diagnostic.getStartPosition() <= start && end <= diagnostic.getEndPosition()) {
if (current == null
|| diagnostic.getStartPosition() < current.getStartPosition()
&& diagnostic.getEndPosition() > current.getEndPosition()) {
current = diagnostic;
}
}
}
if (current != null) {
return current;
}
// fallback to start and end separately
current = getDiagnosticWrapper(diagnostics, start);
if (current != null) {
return current;
}
return getDiagnosticWrapper(diagnostics, end);
}
@Nullable
public static DiagnosticWrapper getDiagnosticWrapper(
List<DiagnosticWrapper> diagnostics, long cursor) {
if (diagnostics == null) {
return null;
}
for (DiagnosticWrapper diagnostic : diagnostics) {
if (diagnostic.getStartPosition() <= cursor && cursor <= diagnostic.getEndPosition()) {
return diagnostic;
}
}
return null;
}
@Nullable
public static DiagnosticWrapper getXmlDiagnosticWrapper(
List<DiagnosticWrapper> diagnostics, int line) {
if (diagnostics == null) {
return null;
}
for (DiagnosticWrapper diagnostic : diagnostics) {
if (diagnostic.getLineNumber() - 1 == line) {
return diagnostic;
}
}
return null;
}
@Nullable
public static ClientCodeWrapper.DiagnosticSourceUnwrapper getDiagnosticSourceUnwrapper(
Diagnostic<?> diagnostic) {
if (diagnostic instanceof DiagnosticWrapper) {
if (((DiagnosticWrapper) diagnostic).getExtra()
instanceof ClientCodeWrapper.DiagnosticSourceUnwrapper) {
return (ClientCodeWrapper.DiagnosticSourceUnwrapper)
((DiagnosticWrapper) diagnostic).getExtra();
}
}
if (diagnostic instanceof ClientCodeWrapper.DiagnosticSourceUnwrapper) {
return (ClientCodeWrapper.DiagnosticSourceUnwrapper) diagnostic;
}
return null;
}
@NonNull
public static MethodPtr findMethod(CompileTask task, long position) {
Trees trees = Trees.instance(task.task);
Tree tree = new FindMethodDeclarationAt(task.task).scan(task.root(), position);
TreePath path = trees.getPath(task.root(), tree);
ExecutableElement method = (ExecutableElement) trees.getElement(path);
return new MethodPtr(task.task, method);
}
@NonNull
public static String extractExceptionName(String message) {
Matcher matcher = UNREPORTED_EXCEPTION.matcher(message);
if (!matcher.find()) {
return "";
}
String group = matcher.group(1);
if (group == null) {
return "";
}
return group;
}
}
| 6,877 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaCompletionUtil.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/JavaCompletionUtil.java | package com.tyron.completion.java.util;
import androidx.annotation.NonNull;
import org.jetbrains.kotlin.com.intellij.psi.JavaPsiFacade;
import org.jetbrains.kotlin.com.intellij.psi.PsiElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiReferenceExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiType;
import org.jetbrains.kotlin.com.intellij.psi.ResolveState;
import org.jetbrains.kotlin.com.intellij.psi.impl.FakePsiElement;
import org.jetbrains.kotlin.com.intellij.psi.impl.light.LightVariableBuilder;
import org.jetbrains.kotlin.com.intellij.psi.scope.PsiScopeProcessor;
public class JavaCompletionUtil {
@NonNull
public static PsiReferenceExpression createReference(
@NonNull String text, @NonNull PsiElement context) {
return (PsiReferenceExpression)
JavaPsiFacade.getElementFactory(context.getProject())
.createExpressionFromText(text, context);
}
public static FakePsiElement createContextWithXxxVariable(
@NonNull PsiElement place, @NonNull PsiType varType) {
return new FakePsiElement() {
@Override
public boolean processDeclarations(
@NonNull PsiScopeProcessor processor,
@NonNull ResolveState state,
PsiElement lastParent,
@NonNull PsiElement place) {
return processor.execute(
new LightVariableBuilder<>("xxx", varType, place), ResolveState.initial());
}
@Override
public PsiElement getParent() {
return place;
}
};
}
}
| 1,509 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaParserUtil.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/JavaParserUtil.java | package com.tyron.completion.java.util;
import static com.tyron.completion.java.util.JavaParserTypesUtil.toType;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.ReceiverParameter;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.AssignExpr;
import com.github.javaparser.ast.expr.BooleanLiteralExpr;
import com.github.javaparser.ast.expr.CharLiteralExpr;
import com.github.javaparser.ast.expr.DoubleLiteralExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.FieldAccessExpr;
import com.github.javaparser.ast.expr.IntegerLiteralExpr;
import com.github.javaparser.ast.expr.LiteralExpr;
import com.github.javaparser.ast.expr.LongLiteralExpr;
import com.github.javaparser.ast.expr.MarkerAnnotationExpr;
import com.github.javaparser.ast.expr.MemberValuePair;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.Name;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.NormalAnnotationExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;
import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.stmt.ExpressionStmt;
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.type.ArrayType;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.type.WildcardType;
import com.github.javaparser.printer.DefaultPrettyPrinter;
import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration;
import com.github.javaparser.printer.configuration.PrinterConfiguration;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ErroneousTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.PackageTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.VariableTree;
import com.tyron.completion.java.rewrite.EditHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.IntStream;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
public class JavaParserUtil {
public static CompilationUnit toCompilationUnit(CompilationUnitTree tree) {
CompilationUnit compilationUnit = new CompilationUnit();
compilationUnit.setPackageDeclaration(toPackageDeclaration(tree.getPackage()));
tree.getImports()
.forEach(importTree -> compilationUnit.addImport(toImportDeclaration(importTree)));
compilationUnit.setTypes(
tree.getTypeDecls().stream()
.map(JavaParserUtil::toClassOrInterfaceDeclaration)
.collect(NodeList.toNodeList()));
return compilationUnit;
}
public static PackageDeclaration toPackageDeclaration(PackageTree tree) {
PackageDeclaration declaration = new PackageDeclaration();
declaration.setName(tree.getPackageName().toString());
return declaration;
}
public static ImportDeclaration toImportDeclaration(ImportTree tree) {
String name = tree.getQualifiedIdentifier().toString();
boolean isAsterisk = name.endsWith("*");
return new ImportDeclaration(name, tree.isStatic(), isAsterisk);
}
public static ClassOrInterfaceDeclaration toClassOrInterfaceDeclaration(Tree tree) {
if (tree instanceof ClassTree) {
return toClassOrInterfaceDeclaration((ClassTree) tree);
}
return null;
}
public static BlockStmt toBlockStatement(BlockTree tree) {
BlockStmt blockStmt = new BlockStmt();
blockStmt.setStatements(
tree.getStatements().stream()
.map(JavaParserUtil::toStatement)
.collect(NodeList.toNodeList()));
return blockStmt;
}
public static Statement toStatement(StatementTree tree) {
if (tree instanceof ExpressionStatementTree) {
return toExpressionStatement((ExpressionStatementTree) tree);
}
if (tree instanceof VariableTree) {
return toVariableDeclarationExpression(((VariableTree) tree));
}
return StaticJavaParser.parseStatement(tree.toString());
}
public static ExpressionStmt toExpressionStatement(ExpressionStatementTree tree) {
ExpressionStmt expressionStmt = new ExpressionStmt();
expressionStmt.setExpression(toExpression(tree.getExpression()));
return expressionStmt;
}
public static Expression toExpression(ExpressionTree tree) {
if (tree instanceof MethodInvocationTree) {
return toMethodCallExpression((MethodInvocationTree) tree);
}
if (tree instanceof MemberSelectTree) {
return toFieldAccessExpression((MemberSelectTree) tree);
}
if (tree instanceof IdentifierTree) {
return toNameExpr(((IdentifierTree) tree));
}
if (tree instanceof LiteralTree) {
return toLiteralExpression(((LiteralTree) tree));
}
if (tree instanceof AssignmentTree) {
return toAssignExpression(((AssignmentTree) tree));
}
if (tree instanceof ErroneousTree) {
ErroneousTree erroneousTree = (ErroneousTree) tree;
if (!erroneousTree.getErrorTrees().isEmpty()) {
Tree errorTree = erroneousTree.getErrorTrees().get(0);
return toExpression((ExpressionTree) errorTree);
}
}
return null;
}
private static AssignExpr toAssignExpression(AssignmentTree tree) {
AssignExpr assignExpr = new AssignExpr();
assignExpr.setTarget(toExpression(tree.getVariable()));
assignExpr.setValue(toExpression(tree.getExpression()));
return assignExpr;
}
public static ExpressionStmt toVariableDeclarationExpression(VariableTree tree) {
VariableDeclarationExpr expr = new VariableDeclarationExpr();
expr.setModifiers(
tree.getModifiers().getFlags().stream()
.map(JavaParserUtil::toModifier)
.collect(NodeList.toNodeList()));
VariableDeclarator declarator = new VariableDeclarator();
declarator.setName(tree.getName().toString());
declarator.setInitializer(toExpression(tree.getInitializer()));
declarator.setType(toType(tree.getType()));
expr.addVariable(declarator);
ExpressionStmt stmt = new ExpressionStmt();
stmt.setExpression(expr);
return stmt;
}
public static NameExpr toNameExpr(IdentifierTree tree) {
NameExpr nameExpr = new NameExpr();
nameExpr.setName(tree.getName().toString());
return nameExpr;
}
public static LiteralExpr toLiteralExpression(LiteralTree tree) {
Object value = tree.getValue();
if (value instanceof String) {
return new StringLiteralExpr((String) value);
}
if (value instanceof Boolean) {
return new BooleanLiteralExpr((Boolean) value);
}
if (value instanceof Integer) {
return new IntegerLiteralExpr(String.valueOf(value));
}
if (value instanceof Character) {
return new CharLiteralExpr((Character) value);
}
if (value instanceof Long) {
return new LongLiteralExpr((Long) value);
}
if (value instanceof Double) {
return new DoubleLiteralExpr((Double) value);
}
return null;
}
public static MethodCallExpr toMethodCallExpression(MethodInvocationTree tree) {
MethodCallExpr expr = new MethodCallExpr();
if (tree.getMethodSelect() instanceof MemberSelectTree) {
MemberSelectTree methodSelect = (MemberSelectTree) tree.getMethodSelect();
expr.setScope(toExpression(methodSelect.getExpression()));
expr.setName(methodSelect.getIdentifier().toString());
}
expr.setArguments(
tree.getArguments().stream()
.map(JavaParserUtil::toExpression)
.collect(NodeList.toNodeList()));
expr.setTypeArguments(
tree.getTypeArguments().stream()
.map(JavaParserTypesUtil::toType)
.collect(NodeList.toNodeList()));
if (tree.getMethodSelect() instanceof IdentifierTree) {
expr.setName(toNameExpr((IdentifierTree) tree.getMethodSelect()).getName());
}
return expr;
}
public static FieldAccessExpr toFieldAccessExpression(MemberSelectTree tree) {
FieldAccessExpr fieldAccessExpr = new FieldAccessExpr();
fieldAccessExpr.setName(tree.getIdentifier().toString());
fieldAccessExpr.setScope(toExpression(tree.getExpression()));
return fieldAccessExpr;
}
public static ClassOrInterfaceDeclaration toClassOrInterfaceDeclaration(ClassTree tree) {
ClassOrInterfaceDeclaration declaration = new ClassOrInterfaceDeclaration();
declaration.setName(tree.getSimpleName().toString());
declaration.setExtendedTypes(
NodeList.nodeList(JavaParserTypesUtil.toClassOrInterfaceType(tree.getExtendsClause())));
declaration.setTypeParameters(
tree.getTypeParameters().stream()
.map(JavaParserUtil::toTypeParameter)
.collect(NodeList.toNodeList()));
declaration.setTypeParameters(
tree.getTypeParameters().stream()
.map(JavaParserUtil::toTypeParameter)
.collect(NodeList.toNodeList()));
declaration.setImplementedTypes(
tree.getImplementsClause().stream()
.map(JavaParserTypesUtil::toClassOrInterfaceType)
.collect(NodeList.toNodeList()));
declaration.setModifiers(
tree.getModifiers().getFlags().stream()
.map(JavaParserUtil::toModifier)
.collect(NodeList.toNodeList()));
declaration.setMembers(
tree.getMembers().stream()
.map(JavaParserUtil::toBodyDeclaration)
.collect(NodeList.toNodeList()));
return declaration;
}
public static BodyDeclaration<?> toBodyDeclaration(Tree tree) {
if (tree instanceof MethodTree) {
return toMethodDeclaration(((MethodTree) tree), null);
}
if (tree instanceof VariableTree) {
return toFieldDeclaration((VariableTree) tree);
}
return null;
}
public static FieldDeclaration toFieldDeclaration(VariableTree tree) {
FieldDeclaration declaration = new FieldDeclaration();
declaration.setModifiers(
tree.getModifiers().getFlags().stream()
.map(JavaParserUtil::toModifier)
.collect(NodeList.toNodeList()));
VariableDeclarator declarator = new VariableDeclarator();
declarator.setName(tree.getName().toString());
Expression initializer = toExpression(tree.getInitializer());
if (initializer != null) {
declarator.setInitializer(initializer);
}
Type type = toType(tree.getType());
if (type != null) {
declarator.setType(type);
}
declaration.addVariable(declarator);
return declaration;
}
public static MethodDeclaration toMethodDeclaration(MethodTree method, ExecutableType type) {
MethodDeclaration methodDeclaration = new MethodDeclaration();
methodDeclaration.setAnnotations(
method.getModifiers().getAnnotations().stream()
.map(JavaParserUtil::toAnnotation)
.collect(NodeList.toNodeList()));
methodDeclaration.setName(method.getName().toString());
Type returnType;
if (type != null) {
returnType = toType(type.getReturnType());
} else {
returnType = toType(method.getReturnType());
}
if (returnType != null) {
methodDeclaration.setType(getTypeWithoutBounds(returnType));
}
methodDeclaration.setModifiers(
method.getModifiers().getFlags().stream()
.map(JavaParserUtil::toModifier)
.collect(NodeList.toNodeList()));
methodDeclaration.setParameters(
method.getParameters().stream()
.map(JavaParserUtil::toParameter)
.peek(
parameter -> {
Type firstType = getTypeWithoutBounds(parameter.getType());
parameter.setType(firstType);
})
.collect(NodeList.toNodeList()));
methodDeclaration.setTypeParameters(
method.getTypeParameters().stream()
.map(it -> toType(((Tree) it)))
.filter(Objects::nonNull)
.map(type1 -> type1 != null ? type1.toTypeParameter() : Optional.<TypeParameter>empty())
.filter(Optional::isPresent)
.map(Optional::get)
.collect(NodeList.toNodeList()));
if (method.getBody() != null) {
methodDeclaration.setBody(toBlockStatement(method.getBody()));
}
if (method.getReceiverParameter() != null) {
methodDeclaration.setReceiverParameter(toReceiverParameter(method.getReceiverParameter()));
}
return methodDeclaration;
}
public static AnnotationExpr toAnnotation(AnnotationTree tree) {
if (tree.getArguments().isEmpty()) {
MarkerAnnotationExpr expr = new MarkerAnnotationExpr();
expr.setName(toType(tree.getAnnotationType()).toString());
return expr;
}
if (tree.getArguments().size() == 1) {
SingleMemberAnnotationExpr expr = new SingleMemberAnnotationExpr();
expr.setName(toType(tree.getAnnotationType()).toString());
expr.setMemberValue(toExpression(tree.getArguments().get(0)));
return expr;
}
NormalAnnotationExpr expr = new NormalAnnotationExpr();
expr.setName(toType(tree.getAnnotationType()).toString());
expr.setPairs(
tree.getArguments().stream()
.map(
arg -> {
if (arg instanceof AssignmentTree) {
AssignExpr assignExpr = toAssignExpression((AssignmentTree) arg);
MemberValuePair pair = new MemberValuePair();
pair.setName(assignExpr.getTarget().toString());
pair.setValue(assignExpr.getValue());
return pair;
}
// TODO: Handle erroneous trees
return null;
})
.collect(NodeList.toNodeList()));
return expr;
}
public static Parameter toParameter(VariableTree tree) {
Parameter parameter = new Parameter();
parameter.setType(toType(tree.getType()));
parameter.setModifiers(
tree.getModifiers().getFlags().stream()
.map(JavaParserUtil::toModifier)
.collect(NodeList.toNodeList()));
parameter.setName(tree.getName().toString());
return parameter;
}
/**
* Convert a parameter into {@link Parameter} object. This method is called from source files,
* giving their accurate names.
*/
public static Parameter toParameter(TypeMirror type, VariableTree name) {
Parameter parameter = new Parameter();
parameter.setType(EditHelper.printType(type));
parameter.setName(name.getName().toString());
parameter.setModifiers(
name.getModifiers().getFlags().stream()
.map(JavaParserUtil::toModifier)
.collect(NodeList.toNodeList()));
parameter.setName(name.getName().toString());
return parameter;
}
public static TypeParameter toTypeParameter(TypeParameterTree type) {
return StaticJavaParser.parseTypeParameter(type.toString());
}
public static ReceiverParameter toReceiverParameter(VariableTree parameter) {
ReceiverParameter receiverParameter = new ReceiverParameter();
receiverParameter.setName(parameter.getName().toString());
receiverParameter.setType(toType(parameter.getType()));
return receiverParameter;
}
public static MethodDeclaration toMethodDeclaration(
ExecutableElement method, ExecutableType type) {
MethodDeclaration methodDeclaration = new MethodDeclaration();
Type returnType;
if (type != null) {
returnType = toType(type.getReturnType());
} else {
returnType = toType(method.getReturnType());
}
if (returnType != null) {
methodDeclaration.setType(getTypeWithoutBounds(returnType));
}
methodDeclaration.setDefault(method.isDefault());
methodDeclaration.setName(method.getSimpleName().toString());
methodDeclaration.setModifiers(
method.getModifiers().stream()
.map(modifier -> Modifier.Keyword.valueOf(modifier.name()))
.toArray(Modifier.Keyword[]::new));
methodDeclaration.setParameters(
IntStream.range(0, method.getParameters().size())
.mapToObj(
i -> toParameter(type.getParameterTypes().get(i), method.getParameters().get(i)))
.peek(
parameter -> {
Type firstType = getTypeWithoutBounds(parameter.getType());
parameter.setType(firstType);
})
.collect(NodeList.toNodeList()));
methodDeclaration.setTypeParameters(
type.getTypeVariables().stream()
.map(it -> toType(((TypeMirror) it)))
.filter(Objects::nonNull)
.map(type1 -> type1 != null ? type1.toTypeParameter() : Optional.<TypeParameter>empty())
.filter(Optional::isPresent)
.map(Optional::get)
.collect(NodeList.toNodeList()));
return methodDeclaration;
}
public static Type getFirstArrayType(Type type) {
if (type.isTypeParameter()) {
TypeParameter typeParameter = type.asTypeParameter();
if (typeParameter.getTypeBound().isNonEmpty()) {
Optional<ClassOrInterfaceType> first = typeParameter.getTypeBound().getFirst();
if (first.isPresent()) {
return new ArrayType(first.get());
}
}
}
return type;
}
public static Type getFirstType(Type type) {
if (type.isTypeParameter()) {
TypeParameter typeParameter = type.asTypeParameter();
if (typeParameter.getTypeBound().isNonEmpty()) {
Optional<ClassOrInterfaceType> first = typeParameter.getTypeBound().getFirst();
if (first.isPresent()) {
return first.get();
}
}
}
if (type.isClassOrInterfaceType()) {
Optional<NodeList<Type>> typeArguments = type.asClassOrInterfaceType().getTypeArguments();
if (typeArguments.isPresent()) {
if (typeArguments.get().isNonEmpty()) {
Optional<Type> first = typeArguments.get().getFirst();
if (first.isPresent()) {
if (first.get().isTypeParameter()) {
NodeList<ClassOrInterfaceType> typeBound =
first.get().asTypeParameter().getTypeBound();
if (typeBound.isNonEmpty()) {
Optional<ClassOrInterfaceType> first1 = typeBound.getFirst();
if (first1.isPresent()) {
type.asClassOrInterfaceType().setTypeArguments(first1.get());
return type;
}
}
}
}
}
}
}
return type;
}
public static Type getTypeWithoutBounds(Type type) {
if (type.isArrayType() && !type.asArrayType().getComponentType().isTypeParameter()) {
return type;
}
if (!type.isArrayType() && !type.isTypeParameter()) {
return type;
}
if (type instanceof NodeWithSimpleName) {
return new ClassOrInterfaceType(((NodeWithSimpleName<?>) type).getNameAsString());
}
if (type.isArrayType()) {
return new ArrayType(getTypeWithoutBounds(type.asArrayType().getComponentType()));
}
return type;
}
public static Modifier toModifier(javax.lang.model.element.Modifier modifier) {
return new Modifier(Modifier.Keyword.valueOf(modifier.name()));
}
/**
* Convert a parameter into {@link Parameter} object. This method is called from compiled class
* files, giving inaccurate parameter names
*/
public static Parameter toParameter(TypeMirror type, VariableElement name) {
Parameter parameter = new Parameter();
parameter.setType(EditHelper.printType(type));
if (parameter.getType().isArrayType()) {
if (((com.sun.tools.javac.code.Type.ArrayType) type).isVarargs()) {
parameter.setType(parameter.getType().asArrayType().getComponentType());
parameter.setVarArgs(true);
}
}
parameter.setName(name.getSimpleName().toString());
parameter.setModifiers(
name.getModifiers().stream()
.map(JavaParserUtil::toModifier)
.collect(NodeList.toNodeList()));
parameter.setName(name.getSimpleName().toString());
return parameter;
}
public static TypeParameter toTypeParameter(TypeParameterElement type) {
return StaticJavaParser.parseTypeParameter(type.toString());
}
public static TypeParameter toTypeParameter(TypeVariable typeVariable) {
return StaticJavaParser.parseTypeParameter(typeVariable.toString());
}
public static List<String> getClassNames(Type type) {
List<String> classNames = new ArrayList<>();
if (type.isClassOrInterfaceType()) {
classNames.add(type.asClassOrInterfaceType().getName().asString());
}
if (type.isWildcardType()) {
WildcardType wildcardType = type.asWildcardType();
wildcardType.getExtendedType().ifPresent(t -> classNames.addAll(getClassNames(t)));
wildcardType.getSuperType().ifPresent(t -> classNames.addAll(getClassNames(t)));
}
if (type.isArrayType()) {
classNames.addAll(getClassNames(type.asArrayType().getComponentType()));
}
if (type.isIntersectionType()) {
type.asIntersectionType().getElements().stream()
.map(JavaParserUtil::getClassNames)
.forEach(classNames::addAll);
}
return classNames;
}
/**
* Print a node declaration into its string representation
*
* @param node node to print
* @param delegate callback to whether a class name should be printed as fully qualified names
* @return String representation of the method declaration properly formatted
*/
public static String prettyPrint(Node node, JavaParserTypesUtil.NeedFqnDelegate delegate) {
PrinterConfiguration configuration = new DefaultPrinterConfiguration();
JavaPrettyPrinterVisitor visitor =
new JavaPrettyPrinterVisitor(configuration) {
@Override
public void visit(SimpleName n, Void arg) {
printOrphanCommentsBeforeThisChildNode(n);
printComment(n.getComment(), arg);
String identifier = n.getIdentifier();
if (delegate.needsFqn(identifier)) {
printer.print(identifier);
} else {
printer.print(ActionUtil.getSimpleName(identifier));
}
}
@Override
public void visit(Name n, Void arg) {
super.visit(n, arg);
}
};
DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter(t -> visitor, configuration);
return prettyPrinter.print(node);
}
}
| 24,189 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CompletionItemFactory.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/CompletionItemFactory.java | package com.tyron.completion.java.util;
import static com.tyron.completion.java.util.ElementUtil.simpleClassName;
import static com.tyron.completion.java.util.ElementUtil.simpleType;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import androidx.annotation.NonNull;
import com.sun.source.tree.MethodTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.completion.DefaultInsertHandler;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.insert.MethodInsertHandler;
import com.tyron.completion.java.provider.JavaSortCategory;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.model.DrawableKind;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Types;
import org.jetbrains.kotlin.com.intellij.psi.PsiMethod;
import org.jetbrains.kotlin.com.intellij.psi.PsiNamedElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiParameter;
import org.jetbrains.kotlin.com.intellij.psi.PsiParameterList;
import org.jetbrains.kotlin.com.intellij.psi.PsiType;
public class CompletionItemFactory {
/**
* Creates a completion item from a java psi element
*
* @param element The psi element
* @return the completion item instance
*/
public static CompletionItem forPsiElement(PsiNamedElement element) {
if (element instanceof PsiMethod) {
return forPsiMethod(((PsiMethod) element));
}
return item(element.getName());
}
public static CompletionItem forPsiMethod(PsiMethod psiMethod) {
CompletionItem item = new CompletionItem();
item.label = getMethodLabel(psiMethod);
item.detail = psiMethod.getReturnType().getPresentableText();
item.commitText = psiMethod.getName();
item.cursorOffset = item.commitText.length();
item.iconKind = DrawableKind.Method;
return item;
}
public static CompletionItem packageSnippet(Path file) {
String name = "com.tyron.test";
return snippetItem("package " + name, "package " + name + ";\n\n");
}
public static CompletionItem classSnippet(Path file) {
String name = file.getFileName().toString();
name = name.substring(0, name.length() - ".java".length());
return snippetItem("class " + name, "class " + name + " {\n $0\n}");
}
public static CompletionItem keyword(String keyword) {
CompletionItem completionItem =
CompletionItem.create(keyword, keyword, keyword, DrawableKind.Keyword);
completionItem.setSortText(JavaSortCategory.KEYWORD.toString());
return completionItem;
}
public static CompletionItem packageItem(String name) {
return CompletionItem.create(name, "", name, DrawableKind.Package);
}
public static CompletionItem classItem(String className) {
CompletionItem item =
CompletionItem.create(
simpleClassName(className), className, simpleClassName(className), DrawableKind.Class);
item.data = className;
item.action = CompletionItem.Kind.IMPORT;
item.setSortText(JavaSortCategory.TO_IMPORT.toString());
return item;
}
public static CompletionItem importClassItem(String className) {
CompletionItem item = classItem(className);
item.action = CompletionItem.Kind.NORMAL;
;
return item;
}
public static CompletionItem snippetItem(String label, String snippet) {
CompletionItem item = new CompletionItem();
item.label = label;
item.commitText = snippet;
item.cursorOffset = item.commitText.length();
item.detail = "Snippet";
item.iconKind = DrawableKind.Snippet;
return item;
}
public static CompletionItem item(Element element) {
CompletionItem item = new CompletionItem();
item.label = element.getSimpleName().toString();
item.detail = simpleType(element.asType());
item.commitText = element.getSimpleName().toString();
item.cursorOffset = item.commitText.length();
item.iconKind = getKind(element);
item.setInsertHandler(new DefaultInsertHandler(item));
return item;
}
public static CompletionItem item(String element) {
CompletionItem item = new CompletionItem();
item.label = element;
item.detail = "";
item.commitText = element;
item.cursorOffset = item.commitText.length();
item.iconKind = DrawableKind.Snippet;
item.setInsertHandler(new DefaultInsertHandler(item));
return item;
}
private String getThrowsType(ExecutableElement e) {
if (e.getThrownTypes() == null) {
return "";
}
if (e.getThrownTypes().isEmpty()) {
return "";
}
StringBuilder types = new StringBuilder();
for (TypeMirror m : e.getThrownTypes()) {
types.append((types.length() == 0) ? "" : ", ").append(simpleType(m));
}
return " throws " + types;
}
public static String getMethodLabel(@NonNull PsiMethod psiMethod) {
String name = psiMethod.getName();
String parameters = "";
if (psiMethod.hasParameters()) {
PsiParameterList parameterList = psiMethod.getParameterList();
parameters =
Arrays.stream(parameterList.getParameters())
.map(PsiParameter::getType)
.map(PsiType::getPresentableText)
.collect(Collectors.joining(", "));
}
return name + "(" + parameters + ")";
}
public static String getMethodLabel(ExecutableElement element, ExecutableType type) {
String name = element.getSimpleName().toString();
String params = PrintHelper.printParameters(type, element);
return name + "(" + params + ")";
}
public static String getMethodLabel(MethodTree element, ExecutableType type) {
String name = element.getName().toString();
String params = PrintHelper.printParameters(type, element);
return name + "(" + params + ")";
}
public static List<CompletionItem> method(
CompileTask task,
List<ExecutableElement> overloads,
boolean endsWithParen,
boolean methodRef,
DeclaredType type) {
checkCanceled();
List<CompletionItem> items = new ArrayList<>();
Types types = task.task.getTypes();
for (ExecutableElement overload : overloads) {
ExecutableType executableType = (ExecutableType) types.asMemberOf(type, overload);
items.add(method(overload, endsWithParen, methodRef, executableType));
}
return items;
}
public static CompletionItem method(
MethodTree first, boolean endsWithParen, boolean methodRef, ExecutableType type) {
CompletionItem item = new CompletionItem();
item.label = getMethodLabel(first, type);
item.commitText = first.getName() + ((methodRef || endsWithParen) ? "" : "()");
item.detail =
type != null
? PrintHelper.printType(type.getReturnType())
: ActionUtil.getSimpleName(first.getReturnType().toString());
item.iconKind = DrawableKind.Method;
item.cursorOffset = item.commitText.length();
if (first.getParameters() != null && !first.getParameters().isEmpty()) {
item.cursorOffset = item.commitText.length() - ((methodRef || endsWithParen) ? 0 : 1);
}
item.setInsertHandler(new DefaultInsertHandler(item));
return item;
}
public static CompletionItem method(
ExecutableElement first, boolean endsWithParen, boolean methodRef, ExecutableType type) {
CompletionItem item = new CompletionItem();
item.label = getMethodLabel(first, type);
item.commitText = first.getSimpleName().toString();
item.detail =
type != null
? PrintHelper.printType(type.getReturnType())
: PrintHelper.printType(first.getReturnType());
item.iconKind = DrawableKind.Method;
item.cursorOffset = item.commitText.length();
if (first.getParameters() != null && !first.getParameters().isEmpty()) {
item.cursorOffset = item.commitText.length() - ((methodRef || endsWithParen) ? 0 : 1);
}
item.setInsertHandler(new MethodInsertHandler(first, item, !methodRef));
item.addFilterText(first.getSimpleName().toString());
return item;
}
public static List<CompletionItem> method(
CompileTask task,
List<ExecutableElement> overloads,
boolean endsWithParen,
boolean methodRef,
ExecutableType type) {
checkCanceled();
List<CompletionItem> items = new ArrayList<>();
for (ExecutableElement first : overloads) {
checkCanceled();
items.add(method(first, endsWithParen, methodRef, type));
}
return items;
}
public static List<CompletionItem> overridableMethod(
CompileTask task,
TreePath parentPath,
List<ExecutableElement> overloads,
boolean endsWithParen) {
checkCanceled();
List<CompletionItem> items = new ArrayList<>(overloads.size());
Types types = task.task.getTypes();
Element parentElement = Trees.instance(task.task).getElement(parentPath);
DeclaredType type = (DeclaredType) parentElement.asType();
for (ExecutableElement element : overloads) {
checkCanceled();
Element enclosingElement = element.getEnclosingElement();
if (!types.isAssignable(type, enclosingElement.asType())) {
items.addAll(method(task, Collections.singletonList(element), endsWithParen, false, type));
continue;
}
ExecutableType executableType = (ExecutableType) types.asMemberOf(type, element);
String text = PrintHelper.printMethod(element, executableType, element);
CompletionItem item = new CompletionItem();
item.label = getMethodLabel(element, executableType);
item.detail = PrintHelper.printType(element.getReturnType());
item.commitText = text;
item.cursorOffset = item.commitText.length();
item.iconKind = DrawableKind.Method;
item.setInsertHandler(new DefaultInsertHandler(item));
items.add(item);
}
return items;
}
private static DrawableKind getKind(Element element) {
switch (element.getKind()) {
case METHOD:
return DrawableKind.Method;
case CLASS:
return DrawableKind.Class;
case INTERFACE:
return DrawableKind.Interface;
case FIELD:
return DrawableKind.Field;
default:
return DrawableKind.LocalVariable;
}
}
}
| 10,536 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ErrorCodes.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/ErrorCodes.java | package com.tyron.completion.java.util;
public class ErrorCodes {
public static final String MISSING_RETURN_STATEMENT = "compiler.err.missing.ret.stmt";
public static final String DOES_NOT_OVERRIDE_ABSTRACT = "compiler.err.does.not.override.abstract";
public static final String DEPRECATED = "compiler.warn.has.been.deprecated";
}
| 340 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ActionUtil.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/ActionUtil.java | package com.tyron.completion.java.util;
import static com.sun.source.tree.Tree.Kind.ANNOTATION;
import static com.sun.source.tree.Tree.Kind.ARRAY_TYPE;
import static com.sun.source.tree.Tree.Kind.ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.BLOCK;
import static com.sun.source.tree.Tree.Kind.BOOLEAN_LITERAL;
import static com.sun.source.tree.Tree.Kind.CATCH;
import static com.sun.source.tree.Tree.Kind.DO_WHILE_LOOP;
import static com.sun.source.tree.Tree.Kind.EXPRESSION_STATEMENT;
import static com.sun.source.tree.Tree.Kind.FOR_LOOP;
import static com.sun.source.tree.Tree.Kind.IDENTIFIER;
import static com.sun.source.tree.Tree.Kind.IF;
import static com.sun.source.tree.Tree.Kind.IMPORT;
import static com.sun.source.tree.Tree.Kind.INTERFACE;
import static com.sun.source.tree.Tree.Kind.INT_LITERAL;
import static com.sun.source.tree.Tree.Kind.LAMBDA_EXPRESSION;
import static com.sun.source.tree.Tree.Kind.LONG_LITERAL;
import static com.sun.source.tree.Tree.Kind.MEMBER_SELECT;
import static com.sun.source.tree.Tree.Kind.METHOD;
import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION;
import static com.sun.source.tree.Tree.Kind.NEW_CLASS;
import static com.sun.source.tree.Tree.Kind.PACKAGE;
import static com.sun.source.tree.Tree.Kind.PARAMETERIZED_TYPE;
import static com.sun.source.tree.Tree.Kind.PARENTHESIZED;
import static com.sun.source.tree.Tree.Kind.PRIMITIVE_TYPE;
import static com.sun.source.tree.Tree.Kind.RETURN;
import static com.sun.source.tree.Tree.Kind.STRING_LITERAL;
import static com.sun.source.tree.Tree.Kind.THROW;
import static com.sun.source.tree.Tree.Kind.TRY;
import static com.sun.source.tree.Tree.Kind.TYPE_CAST;
import static com.sun.source.tree.Tree.Kind.UNARY_MINUS;
import static com.sun.source.tree.Tree.Kind.UNARY_PLUS;
import static com.sun.source.tree.Tree.Kind.VARIABLE;
import static com.sun.source.tree.Tree.Kind.WHILE_LOOP;
import androidx.annotation.Nullable;
import com.google.common.collect.ImmutableSet;
import com.sun.source.doctree.ThrowsTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.Scope;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TryTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.sun.tools.javac.tree.JCTree;
import com.tyron.completion.java.action.FindCurrentPath;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.rewrite.EditHelper;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
public class ActionUtil {
private static final Pattern DIGITS_PATTERN = Pattern.compile("^(.+?)(\\d+)$");
private static final Pattern CAMEL_CASE_PATTERN =
Pattern.compile("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])");
private static final Set<Tree.Kind> DISALLOWED_KINDS_INTRODUCE_LOCAL_VARIABLE =
ImmutableSet.of(
IMPORT,
PACKAGE,
INTERFACE,
METHOD,
ANNOTATION,
THROW,
WHILE_LOOP,
DO_WHILE_LOOP,
FOR_LOOP,
IF,
TRY,
CATCH,
UNARY_PLUS,
UNARY_MINUS,
RETURN,
LAMBDA_EXPRESSION,
ASSIGNMENT);
private static final Set<Tree.Kind> CHECK_PARENT_KINDS_INTRODUCE_LOCAL_VARIABLE =
ImmutableSet.of(
STRING_LITERAL,
ARRAY_TYPE,
PARENTHESIZED,
MEMBER_SELECT,
PRIMITIVE_TYPE,
IDENTIFIER,
BLOCK,
TYPE_CAST,
PARAMETERIZED_TYPE,
INT_LITERAL,
LONG_LITERAL,
BOOLEAN_LITERAL);
public static TreePath canIntroduceLocalVariable(TreePath path) {
if (path == null) {
return null;
}
Tree.Kind kind = path.getLeaf().getKind();
TreePath parent = path.getParentPath();
// = new ..
if (kind == NEW_CLASS && parent.getLeaf().getKind() == VARIABLE) {
return null;
}
if (DISALLOWED_KINDS_INTRODUCE_LOCAL_VARIABLE.contains(kind)) {
return null;
}
if (path.getLeaf() instanceof JCTree.JCVariableDecl) {
return null;
}
if (CHECK_PARENT_KINDS_INTRODUCE_LOCAL_VARIABLE.contains(kind)) {
return canIntroduceLocalVariable(parent);
}
if (path.getLeaf() instanceof ClassTree && parent.getLeaf() instanceof NewClassTree) {
return null;
}
if (path.getLeaf() instanceof ClassTree) {
return null;
}
if (kind == METHOD_INVOCATION) {
JCTree.JCMethodInvocation methodInvocation = (JCTree.JCMethodInvocation) path.getLeaf();
// void return type
if (isVoid(methodInvocation)) {
return null;
}
if (parent.getLeaf().getKind() == EXPRESSION_STATEMENT) {
return path;
}
return canIntroduceLocalVariable(parent);
}
if (parent == null) {
return null;
}
TreePath grandParent = parent.getParentPath();
if (parent.getLeaf() instanceof ParenthesizedTree) {
if (grandParent.getLeaf() instanceof IfTree) {
return null;
}
if (grandParent.getLeaf() instanceof WhileLoopTree) {
return null;
}
if (grandParent.getLeaf() instanceof ForLoopTree) {
return null;
}
}
// can't introduce a local variable on a lambda expression
// eg. run(() -> something());
if (parent.getLeaf() instanceof JCTree.JCLambda) {
return null;
}
if (path.getLeaf() instanceof NewClassTree) {
// run(new Runnable() { });
if (parent.getLeaf() instanceof MethodInvocationTree) {
return null;
}
}
return path;
}
private static boolean isVoid(JCTree.JCMethodInvocation methodInvocation) {
if (methodInvocation.type == null) {
// FIXME: get the type from elements using the tree
return false;
}
if (!methodInvocation.type.isPrimitive()) {
return methodInvocation.type.isPrimitiveOrVoid();
}
return false;
}
public static TreePath findSurroundingPath(TreePath path) {
TreePath parent = path.getParentPath();
TreePath grandParent = parent.getParentPath();
if (path.getLeaf() instanceof ExpressionStatementTree) {
return path;
}
if (path.getLeaf() instanceof MethodInvocationTree) {
return findSurroundingPath(parent);
}
if (path.getLeaf() instanceof MemberSelectTree) {
return findSurroundingPath(parent);
}
if (path.getLeaf() instanceof IdentifierTree) {
return findSurroundingPath(parent);
}
if (parent.getLeaf() instanceof JCTree.JCVariableDecl) {
return parent;
}
// inside if parenthesis
if (parent.getLeaf() instanceof ParenthesizedTree) {
if (grandParent.getLeaf() instanceof IfTree) {
return grandParent;
}
if (grandParent.getLeaf() instanceof WhileLoopTree) {
return grandParent;
}
if (grandParent.getLeaf() instanceof ForLoopTree) {
return grandParent;
}
if (grandParent.getLeaf() instanceof EnhancedForLoopTree) {
return grandParent;
}
}
if (grandParent.getLeaf() instanceof BlockTree) {
// try catch statement
if (grandParent.getParentPath().getLeaf() instanceof TryTree) {
return grandParent.getParentPath();
}
if (grandParent.getParentPath().getLeaf() instanceof JCTree.JCLambda) {
return parent;
}
}
if (parent.getLeaf() instanceof ExpressionStatementTree) {
if (grandParent.getLeaf() instanceof ThrowsTree) {
return null;
}
return parent;
}
return null;
}
public static TypeMirror getReturnType(JavacTask task, TreePath path, ExecutableElement element) {
if (path.getLeaf() instanceof JCTree.JCNewClass) {
JCTree.JCNewClass newClass = (JCTree.JCNewClass) path.getLeaf();
return newClass.type;
}
return element.getReturnType();
}
/** Used to check whether we need to add fully qualified names instead of importing it */
public static boolean needsFqn(CompilationUnitTree root, String className) {
return needsFqn(
root.getImports().stream()
.map(ImportTree::getQualifiedIdentifier)
.map(Tree::toString)
.collect(Collectors.toSet()),
className);
}
public static boolean needsFqn(Set<String> imports, String className) {
String name = getSimpleName(className);
for (String fqn : imports) {
if (fqn.equals(className)) {
return false;
}
String simpleName = getSimpleName(fqn);
if (simpleName.equals(name)) {
return true;
}
}
return false;
}
public static boolean hasImport(CompilationUnitTree root, String className) {
if (className.endsWith("[]")) {
className = className.substring(0, className.length() - 2);
}
if (className.contains("<")) {
className = className.substring(0, className.indexOf('<'));
}
return hasImport(
root.getImports().stream()
.map(ImportTree::getQualifiedIdentifier)
.map(Tree::toString)
.collect(Collectors.toSet()),
className);
}
public static boolean hasImport(Set<String> importDeclarations, String className) {
String packageName = "";
if (className.contains(".")) {
packageName = className.substring(0, className.lastIndexOf("."));
}
if (packageName.equals("java.lang")) {
return true;
}
if (needsFqn(importDeclarations, className)) {
return true;
}
for (String name : importDeclarations) {
if (name.equals(className)) {
return true;
}
if (name.endsWith("*")) {
String first = name.substring(0, name.lastIndexOf("."));
String end = className.substring(0, className.lastIndexOf("."));
if (first.equals(end)) {
return true;
}
}
}
return false;
}
public static String getSimpleName(TypeMirror typeMirror) {
return EditHelper.printType(typeMirror, false).toString();
}
public static String getSimpleName(String className) {
className = removeDiamond(className);
int dot = className.lastIndexOf('.');
if (dot == -1) {
return className;
}
if (className.startsWith("? extends")) {
return "? extends " + className.substring(dot + 1);
}
return className.substring(dot + 1);
}
public static String removeDiamond(String className) {
if (className.contains("<")) {
className = className.substring(0, className.indexOf('<'));
}
return className;
}
public static String removeArray(String className) {
if (className.contains("[")) {
className = className.substring(0, className.indexOf('['));
}
return className;
}
public static boolean containsVariableAtScope(String name, long position, CompileTask parse) {
TreePath scan = new FindCurrentPath(parse.task).scan(parse.root(), position + 1);
if (scan == null) {
return false;
}
Scope scope = Trees.instance(parse.task).getScope(scan);
Iterable<? extends Element> localElements = scope.getLocalElements();
for (Element element : localElements) {
if (name.contentEquals(element.getSimpleName())) {
return true;
}
}
return false;
}
public static boolean containsVariableAtScope(String name, CompileTask parse, TreePath path) {
Scope scope = Trees.instance(parse.task).getScope(path);
Iterable<? extends Element> localElements = scope.getLocalElements();
for (Element element : localElements) {
if (element.getKind() != ElementKind.LOCAL_VARIABLE && !element.getKind().isField()) {
continue;
}
if (name.contentEquals(element.getSimpleName())) {
return true;
}
}
return false;
}
public static String getVariableName(String name) {
Matcher matcher = DIGITS_PATTERN.matcher(name);
if (matcher.matches()) {
String variableName = matcher.group(1);
String stringNumber = matcher.group(2);
if (stringNumber == null) {
stringNumber = "0";
}
int number = Integer.parseInt(stringNumber) + 1;
return variableName + number;
}
return name + "1";
}
public static List<String> guessNamesFromType(TypeMirror typeMirror) {
List<String> list = new ArrayList<>();
if (typeMirror.getKind() == TypeKind.DECLARED) {
DeclaredType type = (DeclaredType) typeMirror;
String typeName = guessNameFromTypeName(getSimpleName(type.toString()));
String[] types = getSimpleName(type.toString()).split(CAMEL_CASE_PATTERN.pattern());
if (types.length != 0) {
for (int i = 0; i < types.length; i++) {
StringBuilder sb = new StringBuilder();
sb.append(guessNameFromTypeName(types[i]));
if (i + 1 < types.length) {
for (int j = i + 1; j < types.length; j++) {
sb.append(Character.toUpperCase(types[j].charAt(0))).append(types[j].substring(1));
}
}
list.add(sb.toString());
}
} else {
list.add(typeName);
}
List<String> typeNames = new ArrayList<>();
for (TypeMirror typeArgument : type.getTypeArguments()) {
String s = guessNameFromTypeName(getSimpleName(typeArgument.toString()));
if (!s.isEmpty()) {
typeNames.add(s);
}
}
if (!typeNames.isEmpty()) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < typeNames.size(); i++) {
String name = typeNames.get(i);
if (i == 0) {
name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
} else {
name = Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
stringBuilder.append(name);
}
stringBuilder
.append(Character.toUpperCase(typeName.charAt(0)))
.append(typeName.substring(1));
list.add(stringBuilder.toString());
}
}
return list;
}
/**
* @return null if type is an anonymous class
*/
@Nullable
public static String guessNameFromType(TypeMirror type) {
if (type instanceof DeclaredType) {
DeclaredType declared = (DeclaredType) type;
Element element = declared.asElement();
String name = element.getSimpleName().toString();
// anonymous class, guess from class name
if (name.length() == 0) {
name = declared.toString();
name = name.substring("<anonymous ".length(), name.length() - 1);
}
name = ActionUtil.getSimpleName(name);
return guessNameFromTypeName(name);
}
return null;
}
public static String guessNameFromTypeName(String name) {
String lowercase = "" + Character.toLowerCase(name.charAt(0)) + name.substring(1);
if (!SourceVersion.isName(lowercase)) {
String uppercase = Character.toUpperCase(name.charAt(0)) + name.substring(1);
char c = lowercase.charAt(0);
if ("aeiouAEIOU".indexOf(c) != -1) {
return "an" + uppercase;
} else {
return "a" + uppercase;
}
}
return lowercase;
}
public static String guessNameFromMethodName(String methodName) {
if (methodName == null) {
return null;
}
if (methodName.startsWith("get")) {
methodName = methodName.substring("get".length());
}
if (methodName.isEmpty()) {
return null;
}
if ("<init>".equals(methodName)) {
return null;
}
if ("<clinit>".equals(methodName)) {
return null;
}
return guessNameFromTypeName(methodName);
}
/**
* Get all the possible fully qualified names that may be imported
*
* @param type method to scan
* @return Set of fully qualified names not including the diamond operator
*/
public static Set<String> getTypesToImport(ExecutableType type) {
Set<String> types = new HashSet<>();
TypeMirror returnType = type.getReturnType();
if (returnType != null) {
if (returnType.getKind() != TypeKind.VOID
&& returnType.getKind() != TypeKind.TYPEVAR
&& !returnType.getKind().isPrimitive()) {
String fqn = getTypeToImport(returnType);
if (fqn != null) {
types.add(fqn);
}
}
}
if (type.getThrownTypes() != null) {
for (TypeMirror thrown : type.getThrownTypes()) {
String fqn = getTypeToImport(thrown);
if (fqn != null) {
types.add(fqn);
}
}
}
for (TypeMirror t : type.getParameterTypes()) {
if (t.getKind().isPrimitive()) {
continue;
}
String fqn = getTypeToImport(t);
if (fqn != null) {
types.add(fqn);
}
}
return types;
}
@Nullable
private static String getTypeToImport(TypeMirror type) {
if (type.getKind().isPrimitive()) {
return null;
}
if (type.getKind() == TypeKind.TYPEVAR) {
return null;
}
String fqn = EditHelper.printType(type, true).toString();
if (type.getKind() == TypeKind.ARRAY) {
fqn = removeArray(fqn);
}
return removeDiamond(fqn);
}
public static List<? extends TypeParameterElement> getTypeParameters(
JavacTask task, TreePath path, ExecutableElement element) {
if (path.getLeaf() instanceof JCTree.JCNewClass) {
JCTree.JCNewClass newClass = (JCTree.JCNewClass) path.getLeaf();
// return newClass.getTypeArguments();
}
return element.getTypeParameters();
}
}
| 18,585 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FindQualifiedName.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/FindQualifiedName.java | package com.tyron.completion.java.util;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.TreePathScanner;
/**
* Visits the {@link CompilationUnitTree} and builds up the fully qualified name of the given class
* tree.
*/
public class FindQualifiedName extends TreePathScanner<String, ClassTree> {
private final StringBuilder mBuilder = new StringBuilder();
@Override
public String visitCompilationUnit(CompilationUnitTree t, ClassTree classTree) {
mBuilder.append(t.getPackageName().toString());
return super.visitCompilationUnit(t, classTree);
}
@Override
public String visitClass(ClassTree classTree, ClassTree unused) {
if (!mBuilder.toString().isEmpty()) {
mBuilder.append('.');
}
mBuilder.append(classTree.getSimpleName().toString());
if (!unused.equals(classTree)) {
return super.visitClass(classTree, unused);
}
return mBuilder.toString();
}
}
| 981 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaParserTypesUtil.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/JavaParserTypesUtil.java | package com.tyron.completion.java.util;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.type.ArrayType;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.IntersectionType;
import com.github.javaparser.ast.type.PrimitiveType;
import com.github.javaparser.ast.type.ReferenceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.type.UnknownType;
import com.github.javaparser.ast.type.VoidType;
import com.github.javaparser.ast.type.WildcardType;
import com.github.javaparser.printer.DefaultPrettyPrinter;
import com.github.javaparser.printer.configuration.DefaultPrinterConfiguration;
import com.github.javaparser.printer.configuration.PrinterConfiguration;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.PrimitiveTypeTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.WildcardTree;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.tree.JCTree;
import java.util.Objects;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.NoType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
public class JavaParserTypesUtil {
public interface NeedFqnDelegate {
boolean needsFqn(String name);
}
// trees
public static ClassOrInterfaceType toClassOrInterfaceType(Tree tree) {
ClassOrInterfaceType type = new ClassOrInterfaceType();
if (tree instanceof IdentifierTree) {
type.setName(((IdentifierTree) tree).getName().toString());
}
if (tree instanceof ParameterizedTypeTree) {
ParameterizedTypeTree parameterizedTypeTree = (ParameterizedTypeTree) tree;
Type t = toType(parameterizedTypeTree.getType());
NodeList<Type> typeArguments = new NodeList<>();
for (Tree typeArgument : parameterizedTypeTree.getTypeArguments()) {
Type typ = toType(typeArgument);
typeArguments.add(typ);
}
if (t.isClassOrInterfaceType()) {
type.setName(t.asClassOrInterfaceType().getName());
}
type.setTypeArguments(typeArguments);
}
return type;
}
public static Type toType(Tree tree) {
Type type;
if (tree instanceof PrimitiveTypeTree) {
type = getPrimitiveType((PrimitiveTypeTree) tree);
} else if (tree instanceof IdentifierTree) {
type = toClassOrInterfaceType(tree);
} else if (tree instanceof WildcardTree) {
JCTree.JCWildcard wildcardTree = (JCTree.JCWildcard) tree;
WildcardType wildcardType = new WildcardType();
Tree bound = wildcardTree.getBound();
Type boundType = toType(bound);
if (wildcardTree.kind.kind == BoundKind.EXTENDS) {
wildcardType.setExtendedType((ReferenceType) boundType);
} else {
wildcardType.setSuperType((ReferenceType) boundType);
}
type = wildcardType;
} else if (tree instanceof ParameterizedTypeTree) {
type = toClassOrInterfaceType(tree);
} else if (tree instanceof TypeParameterTree) {
TypeParameter typeParameter = new TypeParameter();
typeParameter.setName(((TypeParameterTree) tree).getName().toString());
typeParameter.setTypeBound(
((TypeParameterTree) tree)
.getBounds().stream()
.map(JavaParserTypesUtil::toClassOrInterfaceType)
.collect(NodeList.toNodeList()));
type = typeParameter;
} else {
if (tree != null) {
type = StaticJavaParser.parseType(tree.toString());
} else {
type = null;
}
}
return type;
}
public static Type getPrimitiveType(PrimitiveTypeTree tree) {
Type type;
switch (tree.getPrimitiveTypeKind()) {
case INT:
type = PrimitiveType.intType();
break;
case BOOLEAN:
type = PrimitiveType.booleanType();
break;
case LONG:
type = PrimitiveType.longType();
break;
case SHORT:
type = PrimitiveType.shortType();
break;
case CHAR:
type = PrimitiveType.charType();
break;
case FLOAT:
type = PrimitiveType.floatType();
break;
case VOID:
type = new VoidType();
break;
default:
type = new UnknownType();
}
return type;
}
// type mirrors
public static Type toType(TypeMirror typeMirror) {
if (typeMirror.getKind() == TypeKind.ARRAY) {
return toArrayType((javax.lang.model.type.ArrayType) typeMirror);
}
if (typeMirror.getKind().isPrimitive()) {
return toPrimitiveType((javax.lang.model.type.PrimitiveType) typeMirror);
}
if (typeMirror instanceof javax.lang.model.type.IntersectionType) {
return toIntersectionType((javax.lang.model.type.IntersectionType) typeMirror);
}
if (typeMirror instanceof javax.lang.model.type.WildcardType) {
return toWildcardType((javax.lang.model.type.WildcardType) typeMirror);
}
if (typeMirror instanceof javax.lang.model.type.DeclaredType) {
return toClassOrInterfaceType((DeclaredType) typeMirror);
}
if (typeMirror instanceof javax.lang.model.type.TypeVariable) {
return toType(((TypeVariable) typeMirror));
}
if (typeMirror instanceof NoType) {
return new VoidType();
}
return null;
}
public static IntersectionType toIntersectionType(javax.lang.model.type.IntersectionType type) {
NodeList<ReferenceType> collect =
type.getBounds().stream()
.map(JavaParserTypesUtil::toType)
.map(it -> ((ReferenceType) it))
.collect(NodeList.toNodeList());
return new IntersectionType(collect);
}
public static Type toType(TypeVariable typeVariable) {
TypeParameter typeParameter = new TypeParameter();
TypeMirror upperBound = typeVariable.getUpperBound();
if (!typeVariable.equals(upperBound)) {
Type type = toType(upperBound);
if (type != null) {
if (type.isIntersectionType()) {
typeParameter.setTypeBound(
type.asIntersectionType().getElements().stream()
.filter(Type::isClassOrInterfaceType)
.map(Type::asClassOrInterfaceType)
.collect(NodeList.toNodeList()));
} else if (type.isClassOrInterfaceType()) {
typeParameter.setTypeBound(NodeList.nodeList(type.asClassOrInterfaceType()));
}
}
}
typeParameter.setName(typeVariable.toString());
return typeParameter;
}
public static WildcardType toWildcardType(javax.lang.model.type.WildcardType type) {
WildcardType wildcardType = new WildcardType();
if (type.getSuperBound() != null) {
Type result = toType(type.getSuperBound());
if (result instanceof ReferenceType) {
wildcardType.setSuperType((ReferenceType) result);
} else if (result instanceof WildcardType) {
wildcardType = result.asWildcardType();
}
}
if (type.getExtendsBound() != null) {
wildcardType.setExtendedType((ReferenceType) toType(type.getExtendsBound()));
}
return wildcardType;
}
public static PrimitiveType toPrimitiveType(javax.lang.model.type.PrimitiveType type) {
PrimitiveType.Primitive primitive = PrimitiveType.Primitive.valueOf(type.getKind().name());
return new PrimitiveType(primitive);
}
public static ArrayType toArrayType(javax.lang.model.type.ArrayType type) {
Type componentType = toType(type.getComponentType());
return new ArrayType(componentType);
}
public static ClassOrInterfaceType toClassOrInterfaceType(DeclaredType type) {
ClassOrInterfaceType classOrInterfaceType = new ClassOrInterfaceType();
if (!type.getTypeArguments().isEmpty()) {
classOrInterfaceType.setTypeArguments(
type.getTypeArguments().stream()
.map(JavaParserTypesUtil::toType)
.filter(Objects::nonNull)
.collect(NodeList.toNodeList()));
}
if (!type.asElement().toString().isEmpty()) {
classOrInterfaceType.setName(type.asElement().toString());
}
return classOrInterfaceType;
}
public static String getName(Type type, NeedFqnDelegate needFqnDelegate) {
PrinterConfiguration configuration = new DefaultPrinterConfiguration();
JavaPrettyPrinterVisitor visitor =
new JavaPrettyPrinterVisitor(configuration) {
@Override
public void visit(SimpleName n, Void arg) {
printOrphanCommentsBeforeThisChildNode(n);
printComment(n.getComment(), arg);
String identifier = n.getIdentifier();
if (needFqnDelegate.needsFqn(identifier)) {
printer.print(identifier);
} else {
printer.print(ActionUtil.getSimpleName(identifier));
}
}
};
DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter(t -> visitor, configuration);
return prettyPrinter.print(type);
}
public static String getSimpleName(Type type) {
PrinterConfiguration configuration = new DefaultPrinterConfiguration();
JavaPrettyPrinterVisitor visitor = new JavaPrettyPrinterVisitor(configuration);
DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter(t -> visitor, configuration);
return prettyPrinter.print(type);
}
}
| 9,576 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
TreeUtil.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/util/TreeUtil.java | package com.tyron.completion.java.util;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LineMap;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.PrimitiveTypeTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.completion.java.action.FindCurrentPath;
import com.tyron.completion.java.compiler.CompileTask;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.util.Elements;
public class TreeUtil {
/** From a chained method calls, find the first method call and return its path */
public static Tree findCallerPath(TreePath invocation) {
if (invocation.getLeaf() instanceof MethodInvocationTree) {
return findCallerPath((MethodInvocationTree) invocation.getLeaf());
}
return null;
}
public static boolean isVoid(MethodTree tree) {
Tree returnType = tree.getReturnType();
if (returnType.getKind() == Tree.Kind.PRIMITIVE_TYPE) {
return ((PrimitiveTypeTree) returnType).getPrimitiveTypeKind() == TypeKind.VOID;
}
return false;
}
private static Tree findCallerPath(MethodInvocationTree invocation) {
ExpressionTree methodSelect = invocation.getMethodSelect();
if (methodSelect == null) {
return invocation;
}
if (methodSelect instanceof MemberSelectTree) {
return findCallerPath((MemberSelectTree) methodSelect);
}
if (methodSelect instanceof IdentifierTree) {
return invocation;
}
return null;
}
private static Tree findCallerPath(MemberSelectTree methodSelect) {
ExpressionTree expressionTree = methodSelect.getExpression();
if (expressionTree == null) {
return methodSelect;
}
if (expressionTree instanceof MemberSelectTree) {
return findCallerPath((MemberSelectTree) expressionTree);
}
if (expressionTree instanceof MethodInvocationTree) {
return findCallerPath((MethodInvocationTree) expressionTree);
}
return null;
}
public static TreePath findCurrentPath(CompileTask task, long position) {
return new FindCurrentPath(task.task).scan(task.root(), position);
}
public static boolean isBlankLine(CompilationUnitTree root, long cursor) {
LineMap lines = root.getLineMap();
long line = lines.getLineNumber(cursor);
long start = lines.getStartPosition(line);
CharSequence contents;
try {
contents = root.getSourceFile().getCharContent(true);
} catch (IOException e) {
throw new RuntimeException(e);
}
for (long i = start; i < cursor; i++) {
if (!Character.isWhitespace(contents.charAt((int) i))) {
return false;
}
}
return true;
}
public static TreePath findParentOfType(TreePath tree, Class<? extends Tree> type) {
TreePath current = tree;
while (current != null) {
Tree leaf = current.getLeaf();
if (type.isAssignableFrom(leaf.getClass())) {
return current;
}
current = current.getParentPath();
}
return null;
}
public static List<MethodTree> getAllMethods(Trees trees, Elements elements, TreePath treePath) {
Element element = trees.getElement(treePath);
if (element == null) {
return Collections.emptyList();
}
if (!(element instanceof TypeElement)) {
return Collections.emptyList();
}
TypeElement typeElement = (TypeElement) element;
List<MethodTree> methodTrees = new ArrayList<>();
List<? extends Element> allMembers = elements.getAllMembers(typeElement);
for (Element member : allMembers) {
if (member.getKind() != ElementKind.METHOD) {
continue;
}
Tree tree = trees.getTree(member);
if (tree != null) {
methodTrees.add((MethodTree) tree);
}
}
return methodTrees;
}
public static List<MethodTree> getMethods(ClassTree t) {
List<MethodTree> methods = new ArrayList<>();
List<? extends Tree> members = t.getMembers();
for (Tree member : members) {
if (member.getKind() != Tree.Kind.METHOD) {
continue;
}
methods.add((MethodTree) member);
}
return methods;
}
}
| 4,615 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaKotlincCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/JavaKotlincCompletionProvider.java | package com.tyron.completion.java.provider;
import androidx.annotation.NonNull;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.completion.java.util.CompletionItemFactory;
import com.tyron.completion.java.util.JavaCompletionUtil;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.model.CompletionList;
import com.tyron.completion.psi.completion.JavaKeywordCompletion;
import com.tyron.completion.psi.scope.CompletionElement;
import com.tyron.completion.psi.scope.JavaCompletionProcessor;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.com.intellij.openapi.util.Condition;
import org.jetbrains.kotlin.com.intellij.psi.LambdaUtil;
import org.jetbrains.kotlin.com.intellij.psi.PsiElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiIdentifier;
import org.jetbrains.kotlin.com.intellij.psi.PsiJavaCodeReferenceElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiLambdaExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiLambdaParameterType;
import org.jetbrains.kotlin.com.intellij.psi.PsiNamedElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiParameter;
import org.jetbrains.kotlin.com.intellij.psi.PsiReferenceExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiType;
import org.jetbrains.kotlin.com.intellij.psi.PsiWildcardType;
import org.jetbrains.kotlin.com.intellij.psi.filters.ElementFilter;
import org.jetbrains.kotlin.com.intellij.psi.util.PsiTypesUtil;
/** Computes completion candidates using PSI from the kotlin compiler. */
public class JavaKotlincCompletionProvider {
private final JavaModule mJavaModule;
public JavaKotlincCompletionProvider(JavaModule module) {
mJavaModule = module;
}
public void fillCompletionVariants(
@NonNull PsiElement elementAt, @NonNull CompletionList.Builder builder) {
PsiElement parent = elementAt.getParent();
if (elementAt instanceof PsiIdentifier) {
new JavaKeywordCompletion(elementAt, builder);
addIdentifierVariants(elementAt, builder);
addClassNames(elementAt, builder);
if (parent instanceof PsiJavaCodeReferenceElement) {
PsiJavaCodeReferenceElement parentRef = (PsiJavaCodeReferenceElement) parent;
completeReference(elementAt, parentRef, builder);
}
}
}
private void addClassNames(PsiElement elementAt, CompletionList.Builder builder) {}
private void completeReference(
PsiElement position, PsiJavaCodeReferenceElement parentRef, CompletionList.Builder builder) {
PsiElement elementParent = position.getContext();
if (elementParent instanceof PsiReferenceExpression) {
final PsiExpression qualifierExpression =
((PsiReferenceExpression) elementParent).getQualifierExpression();
if (qualifierExpression instanceof PsiReferenceExpression) {
final PsiElement resolve = ((PsiReferenceExpression) qualifierExpression).resolve();
if (resolve instanceof PsiParameter) {
final PsiElement declarationScope = ((PsiParameter) resolve).getDeclarationScope();
if (((PsiParameter) resolve).getType() instanceof PsiLambdaParameterType) {
final PsiLambdaExpression lambdaExpression = (PsiLambdaExpression) declarationScope;
if (PsiTypesUtil.getExpectedTypeByParent(lambdaExpression) == null) {
final int parameterIndex =
lambdaExpression.getParameterList().getParameterIndex((PsiParameter) resolve);
final boolean overloadsFound =
LambdaUtil.processParentOverloads(
lambdaExpression,
functionalInterfaceType -> {
PsiType qualifierType =
LambdaUtil.getLambdaParameterFromType(
functionalInterfaceType, parameterIndex);
if (qualifierType instanceof PsiWildcardType) {
qualifierType = ((PsiWildcardType) qualifierType).getBound();
}
if (qualifierType == null) return;
PsiReferenceExpression fakeRef =
JavaCompletionUtil.createReference(
"xxx.xxx",
JavaCompletionUtil.createContextWithXxxVariable(
position, qualifierType));
System.out.println(fakeRef);
});
if (overloadsFound) {
// TODO: 3/11/2022
}
}
}
}
}
}
JavaCompletionProcessor.Options options = JavaCompletionProcessor.Options.DEFAULT_OPTIONS;
JavaCompletionProcessor processor =
new JavaCompletionProcessor(
position,
new ElementFilter() {
@Override
public boolean isAcceptable(Object o, @Nullable PsiElement psiElement) {
return true;
}
@Override
public boolean isClassAcceptable(Class aClass) {
return true;
}
},
options,
Condition.TRUE);
parentRef.processVariants(processor);
Iterable<CompletionElement> results = processor.getResults();
results.forEach(
result -> {
CompletionItem item =
CompletionItemFactory.forPsiElement((PsiNamedElement) result.getElement());
builder.addItem(item);
});
}
private void addIdentifierVariants(PsiElement elementAt, CompletionList.Builder builder) {}
}
| 5,669 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
PruneMethodBodies.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/PruneMethodBodies.java | package com.tyron.completion.java.provider;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreeScanner;
import com.sun.source.util.Trees;
import java.io.IOException;
public class PruneMethodBodies extends TreeScanner<StringBuilder, Long> {
private final JavacTask task;
private final StringBuilder buf = new StringBuilder();
private CompilationUnitTree root;
public PruneMethodBodies(JavacTask task) {
this.task = task;
}
@Override
public StringBuilder visitCompilationUnit(CompilationUnitTree t, Long find) {
root = t;
try {
CharSequence contents = t.getSourceFile().getCharContent(true);
buf.setLength(0);
buf.append(contents);
} catch (IOException e) {
throw new RuntimeException(e);
}
super.visitCompilationUnit(t, find);
return buf;
}
@Override
public StringBuilder visitBlock(BlockTree blockTree, Long find) {
SourcePositions pos = Trees.instance(task).getSourcePositions();
long start = pos.getStartPosition(root, blockTree);
long end = pos.getEndPosition(root, blockTree);
if (!(start <= find && find < end)) {
for (int i = (int) start + 1; i < end - 1; i++) {
if (!Character.isWhitespace(buf.charAt(i))) {
buf.setCharAt(i, ' ');
}
}
return buf;
}
super.visitBlock(blockTree, find);
return buf;
}
@Override
public StringBuilder reduce(StringBuilder a, StringBuilder b) {
return buf;
}
}
| 1,605 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CompletionEngine.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/CompletionEngine.java | package com.tyron.completion.java.provider;
import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import com.tyron.builder.log.ILogger;
import com.tyron.builder.project.Project;
import com.tyron.builder.project.api.JavaModule;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.model.CachedCompletion;
import com.tyron.completion.model.CompletionList;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
public class CompletionEngine {
private static final String TAG = CompletionEngine.class.getSimpleName();
private final List<DiagnosticListener<? super JavaFileObject>> mDiagnosticListeners;
private final DiagnosticListener<? super JavaFileObject> mInternalListener;
private final HashSet<Object> mCachedPaths;
private CachedCompletion cachedCompletion;
public static volatile CompletionEngine Instance = null;
public static synchronized CompletionEngine getInstance() {
if (Instance == null) {
Instance = new CompletionEngine();
}
return Instance;
}
private JavaCompilerService mProvider;
private static boolean mIndexing;
private CompletionEngine() {
mDiagnosticListeners = new ArrayList<>();
mCachedPaths = new HashSet<>();
mInternalListener =
d -> {
for (DiagnosticListener<? super JavaFileObject> listener : mDiagnosticListeners) {
listener.report(d);
}
};
}
public void addDiagnosticListener(DiagnosticListener<? super JavaFileObject> listener) {
mDiagnosticListeners.add(listener);
}
public void removeDiagnosticListener(DiagnosticListener<? super JavaFileObject> listener) {
mDiagnosticListeners.remove(listener);
}
@NonNull
/** Disable subsequent completions */
public static void setIndexing(boolean val) {
mIndexing = val;
}
public static boolean isIndexing() {
return mIndexing;
}
private final Handler handler = new Handler(Looper.getMainLooper());
@SuppressLint("NewApi")
public void index(Project project, JavaModule module, ILogger logger, Runnable callback) {
// if (module instanceof AndroidModule) {
// IncrementalAapt2Task task = new IncrementalAapt2Task((AndroidModule) module,
// ILogger.EMPTY, false);
// try {
// task.prepare(BuildType.DEBUG);
// task.generateResourceClasses();
// } catch (IOException | CompilationFailedException e) {
// Log.e(TAG, "Failed to index with aapt2", e);
// }
// }
// Set<File> newSet = new HashSet<>(module.getJavaFiles().values());
//
// for (File library : module.getLibraries()) {
// try {
// JarFile jarFile = new JarFile(library);
// newSet.add(library);
// } catch (IOException e) {
// FileUtils.deleteQuietly(library);
// logger.warning("Library is corrupt, deleting jar file! " + library);
// }
// }
//
// if (!changed(mCachedPaths, newSet)) {
// setIndexing(false);
// handler.post(callback);
// return;
// }
//
// setIndexing(true);
//
// JavaCompilerService compiler = getCompiler(project, module);
//
// List<File> filesToIndex = new ArrayList<>(module.getJavaFiles().values());
//
// if (!filesToIndex.isEmpty()) {
// try (CompileTask task = compiler.compile(filesToIndex.stream()
// .map(File::toPath)
// .toArray(Path[]::new))) {
// Log.d(TAG, "Index success.");
// }
// }
//
// setIndexing(false);
// if (callback != null) {
// handler.post(callback);
// }
}
public synchronized CompletionList complete(
Project project,
JavaModule module,
File file,
String contents,
String prefix,
int line,
int column,
long index)
throws InterruptedException {
// if (mIndexing) {
// return CompletionList.EMPTY;
// }
//
return CompletionList.EMPTY;
}
@NonNull
public synchronized CompletionList complete(
Project project, JavaModule module, File file, String contents, long cursor)
throws InterruptedException {
// Do not request for completion if we're indexing
// if (mIndexing) {
// return CompletionList.EMPTY;
// }
//
// try {
// JavaCompilerService compiler = getCompiler(project, module);
// return new CompletionProvider(compiler)
// .complete(file, contents, cursor);
// } catch (Throwable e) {
// if (e instanceof InterruptedException) {
// throw e;
// }
//
// Log.d(TAG, "Completion failed: " + Log.getStackTraceString(e) + " Clearing
// cache.");
// mProvider = null;
// }
return CompletionList.EMPTY;
}
}
| 5,431 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ClassNameCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/ClassNameCompletionProvider.java | package com.tyron.completion.java.provider;
import static com.tyron.completion.java.util.CompletionItemFactory.classItem;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.TreePath;
import com.tyron.common.ApplicationProvider;
import com.tyron.common.SharedPreferenceKeys;
import com.tyron.common.util.StringSearch;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.insert.ClassImportInsertHandler;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.model.CompletionList;
import java.io.File;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
public class ClassNameCompletionProvider extends BaseCompletionProvider {
public ClassNameCompletionProvider(JavaCompilerService service) {
super(service);
}
@Override
public void complete(
CompletionList.Builder builder,
CompileTask task,
TreePath path,
String partial,
boolean endsWithParen) {
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext());
boolean caseSensitiveMatch =
!preferences.getBoolean(SharedPreferenceKeys.JAVA_CASE_INSENSITIVE_MATCH, false);
addClassNames(task.root(), partial, builder, getCompiler(), caseSensitiveMatch);
}
public static void addClassNames(
CompilationUnitTree root,
String partial,
CompletionList.Builder list,
JavaCompilerService compiler,
boolean caseSensitive) {
checkCanceled();
Predicate<String> predicate;
if (caseSensitive) {
predicate = string -> StringSearch.matchesPartialName(string, partial);
} else {
predicate = string -> StringSearch.matchesPartialNameLowercase(string, partial);
}
String packageName = Objects.toString(root.getPackageName(), "");
Set<String> uniques = new HashSet<>();
for (String className : compiler.packagePrivateTopLevelTypes(packageName)) {
if (!predicate.test(className)) {
continue;
}
list.addItem(classItem(className));
uniques.add(className);
}
for (String className : compiler.publicTopLevelTypes()) {
// more strict on matching class names
String simpleName = ActionUtil.getSimpleName(className);
if (!predicate.test(simpleName)) {
continue;
}
if (uniques.contains(className)) {
continue;
}
if (list.getItemCount() >= Completions.MAX_COMPLETION_ITEMS) {
list.incomplete();
break;
}
CompletionItem item = classItem(className);
item.data = className;
item.setInsertHandler(
new ClassImportInsertHandler(compiler, new File(root.getSourceFile().toUri()), item));
item.setSortText(JavaSortCategory.TO_IMPORT.toString());
list.addItem(item);
uniques.add(className);
}
}
}
| 3,216 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
SwitchConstantCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/SwitchConstantCompletionProvider.java | package com.tyron.completion.java.provider;
import static com.tyron.completion.java.util.CompletionItemFactory.item;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import com.sun.source.tree.SwitchTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.common.util.StringSearch;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.util.TreeUtil;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.model.CompletionList;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
public class SwitchConstantCompletionProvider extends BaseCompletionProvider {
public SwitchConstantCompletionProvider(JavaCompilerService service) {
super(service);
}
@Override
public void complete(
CompletionList.Builder builder,
CompileTask task,
TreePath path,
String partial,
boolean endsWithParen) {
completeSwitchConstant(builder, task, path, partial);
}
public static void completeSwitchConstant(
CompletionList.Builder builder, CompileTask task, TreePath path, String partial) {
checkCanceled();
if (path.getLeaf() instanceof SwitchTree) {
SwitchTree switchTree = (SwitchTree) path.getLeaf();
path = new TreePath(path, switchTree.getExpression());
} else {
TreePath parent = TreeUtil.findParentOfType(path, SwitchTree.class);
if (parent == null) {
return;
}
if (parent.getLeaf() instanceof SwitchTree) {
path = new TreePath(parent, ((SwitchTree) parent.getLeaf()).getExpression());
}
}
TypeMirror type = Trees.instance(task.task).getTypeMirror(path);
if (!(type instanceof DeclaredType)) {
return;
}
DeclaredType declared = (DeclaredType) type;
TypeElement element = (TypeElement) declared.asElement();
for (Element member : task.task.getElements().getAllMembers(element)) {
if (member.getKind() != ElementKind.ENUM_CONSTANT) {
continue;
}
if (!StringSearch.matchesPartialName(member.getSimpleName(), partial)) {
continue;
}
CompletionItem item = item(member);
item.setSortText(JavaSortCategory.UNKNOWN.toString());
builder.addItem(item);
}
}
}
| 2,515 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
MemberSelectCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/MemberSelectCompletionProvider.java | package com.tyron.completion.java.provider;
import static com.tyron.completion.java.util.CompletionItemFactory.item;
import static com.tyron.completion.java.util.CompletionItemFactory.keyword;
import static com.tyron.completion.java.util.CompletionItemFactory.method;
import static com.tyron.completion.java.util.ElementUtil.isEnclosingClass;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.Scope;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.common.util.StringSearch;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.model.CompletionList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import me.xdrop.fuzzywuzzy.FuzzySearch;
public class MemberSelectCompletionProvider extends BaseCompletionProvider {
public MemberSelectCompletionProvider(JavaCompilerService service) {
super(service);
}
@Override
public void complete(
CompletionList.Builder builder,
CompileTask task,
TreePath path,
String partial,
boolean endsWithParen) {
checkCanceled();
MemberSelectTree select = (MemberSelectTree) path.getLeaf();
path = new TreePath(path, select.getExpression());
Trees trees = task.getTrees();
Element element;
try {
element = trees.getElement(path);
} catch (Throwable t) {
element = null;
}
boolean isStatic = element instanceof TypeElement;
Scope scope = trees.getScope(path);
TypeMirror type = trees.getTypeMirror(path);
if (type instanceof ArrayType) {
completeArrayMemberSelect(builder, isStatic);
} else if (type instanceof TypeVariable) {
completeTypeVariableMemberSelect(
builder, task, scope, (TypeVariable) type, isStatic, partial, endsWithParen);
} else if (type instanceof DeclaredType) {
completeDeclaredTypeMemberSelect(
builder, task, scope, (DeclaredType) type, isStatic, partial, endsWithParen);
} else if (type instanceof PrimitiveType) {
if (path.getLeaf().getKind() != Tree.Kind.METHOD_INVOCATION) {
completePrimitiveMemberSelect(
builder, task, scope, (PrimitiveType) type, isStatic, partial, endsWithParen);
}
}
}
private void completePrimitiveMemberSelect(
CompletionList.Builder builder,
CompileTask task,
Scope scope,
PrimitiveType type,
boolean isStatic,
String partial,
boolean endsWithParen) {
checkCanceled();
builder.addItem(keyword("class"));
}
private void completeArrayMemberSelect(CompletionList.Builder builder, boolean isStatic) {
checkCanceled();
if (!isStatic) {
builder.addItem(keyword("length"));
}
}
private void completeTypeVariableMemberSelect(
CompletionList.Builder builder,
CompileTask task,
Scope scope,
TypeVariable type,
boolean isStatic,
String partial,
boolean endsWithParen) {
checkCanceled();
if (type.getUpperBound() instanceof DeclaredType) {
completeDeclaredTypeMemberSelect(
builder,
task,
scope,
(DeclaredType) type.getUpperBound(),
isStatic,
partial,
endsWithParen);
} else if (type.getUpperBound() instanceof TypeVariable) {
completeTypeVariableMemberSelect(
builder,
task,
scope,
(TypeVariable) type.getUpperBound(),
isStatic,
partial,
endsWithParen);
}
}
private void completeDeclaredTypeMemberSelect(
CompletionList.Builder builder,
CompileTask task,
Scope scope,
DeclaredType type,
boolean isStatic,
String partial,
boolean endsWithParen) {
checkCanceled();
Trees trees = Trees.instance(task.task);
TypeElement typeElement = (TypeElement) type.asElement();
HashMap<String, List<ExecutableElement>> methods = new HashMap<>();
for (Element member : task.task.getElements().getAllMembers(typeElement)) {
checkCanceled();
if (builder.getItemCount() >= Completions.MAX_COMPLETION_ITEMS) {
builder.incomplete();
break;
}
if (member.getKind() == ElementKind.CONSTRUCTOR) {
continue;
}
if (FuzzySearch.tokenSetPartialRatio(String.valueOf(member.getSimpleName()), partial) < 70
&& !partial.endsWith(".")
&& !partial.isEmpty()) {
continue;
}
if (!trees.isAccessible(scope, member, type)) {
continue;
}
if (isStatic != member.getModifiers().contains(Modifier.STATIC)) {
continue;
}
if (member.getKind() == ElementKind.METHOD) {
putMethod((ExecutableElement) member, methods);
} else {
builder.addItem(item(member));
}
}
for (List<ExecutableElement> overloads : methods.values()) {
builder.addItems(
method(task, overloads, endsWithParen, false, type),
JavaSortCategory.ACCESSIBLE_SYMBOL.toString());
}
if (isStatic) {
if (StringSearch.matchesPartialName("class", partial)) {
builder.addItem(keyword("class"));
}
}
if (isStatic && isEnclosingClass(type, scope)) {
if (StringSearch.matchesPartialName("this", partial)) {
builder.addItem(keyword("this"));
}
if (StringSearch.matchesPartialName("super", partial)) {
builder.addItem(keyword("super"));
}
}
}
public static void putMethod(
ExecutableElement method, Map<String, List<ExecutableElement>> methods) {
String name = method.getSimpleName().toString();
if (!methods.containsKey(name)) {
methods.put(name, new ArrayList<>());
}
List<ExecutableElement> elements = methods.get(name);
if (elements != null) {
elements.add(method);
}
}
}
| 6,487 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ScopeHelper.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/ScopeHelper.java | package com.tyron.completion.java.provider;
import com.sun.source.tree.Scope;
import com.sun.source.util.Trees;
import com.tyron.completion.java.compiler.CompileTask;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.util.Elements;
public class ScopeHelper {
// TODO is this still necessary? Test speed. We could get rid of the extra static-imports step.
public static List<Scope> fastScopes(Scope start) {
List<Scope> scopes = new ArrayList<>();
for (Scope s = start; s != null; s = s.getEnclosingScope()) {
scopes.add(s);
}
// Scopes may be contained in an enclosing scope.
// The outermost scope contains those elements available via "star import" declarations;
// the scope within that contains the top level elements of the compilation unit, including any
// named
// imports.
// https://parent.docs.oracle.com/en/java/javase/11/docs/api/jdk.compiler/com.sun.source/tree/Scope.html
// CodeAssist changed: allow top level scopes, but not imports they are handled in
// ImportCompletionProvider
return scopes.subList(0, scopes.size() - 2);
}
public static List<Element> scopeMembers(
CompileTask task, Scope inner, Predicate<CharSequence> filter) {
Trees trees = Trees.instance(task.task);
Elements elements = task.task.getElements();
boolean isStatic = false;
List<Element> list = new ArrayList<>();
for (Scope scope : fastScopes(inner)) {
if (scope.getEnclosingMethod() != null) {
isStatic = isStatic || scope.getEnclosingMethod().getModifiers().contains(Modifier.STATIC);
}
for (Element member : scope.getLocalElements()) {
if (!filter.test(member.getSimpleName())) continue;
if (isStatic && member.getSimpleName().contentEquals("this")) continue;
if (isStatic && member.getSimpleName().contentEquals("super")) continue;
list.add(member);
}
if (scope.getEnclosingClass() != null) {
TypeElement typeElement = scope.getEnclosingClass();
DeclaredType typeType = (DeclaredType) typeElement.asType();
for (Element member : elements.getAllMembers(typeElement)) {
if (!filter.test(member.getSimpleName())) continue;
if (!trees.isAccessible(scope, member, typeType)) continue;
if (isStatic && !member.getModifiers().contains(Modifier.STATIC)) continue;
list.add(member);
}
isStatic = isStatic || typeElement.getModifiers().contains(Modifier.STATIC);
}
}
return list;
}
}
| 2,760 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
IdentifierCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/IdentifierCompletionProvider.java | package com.tyron.completion.java.provider;
import static com.tyron.completion.java.provider.ClassNameCompletionProvider.addClassNames;
import static com.tyron.completion.java.provider.ImportCompletionProvider.addStaticImports;
import static com.tyron.completion.java.provider.SwitchConstantCompletionProvider.completeSwitchConstant;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.sun.source.tree.CaseTree;
import com.sun.source.util.TreePath;
import com.tyron.common.ApplicationProvider;
import com.tyron.common.SharedPreferenceKeys;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.model.CompletionList;
public class IdentifierCompletionProvider extends BaseCompletionProvider {
public IdentifierCompletionProvider(JavaCompilerService service) {
super(service);
}
@Override
public void complete(
CompletionList.Builder builder,
CompileTask task,
TreePath path,
String partial,
boolean endsWithParen) {
checkCanceled();
if (path.getParentPath().getLeaf() instanceof CaseTree) {
completeSwitchConstant(builder, task, path.getParentPath(), partial);
return;
}
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext());
boolean caseSensitiveMatch =
!preferences.getBoolean(SharedPreferenceKeys.JAVA_CASE_INSENSITIVE_MATCH, false);
ScopeCompletionProvider.addCompletionItems(task, path, partial, endsWithParen, builder);
addStaticImports(task, path.getCompilationUnit(), partial, endsWithParen, builder);
if (!builder.isIncomplete()) {
if (!caseSensitiveMatch || partial.length() > 0 && Character.isUpperCase(partial.charAt(0))) {
addClassNames(
path.getCompilationUnit(), partial, builder, getCompiler(), caseSensitiveMatch);
}
}
KeywordCompletionProvider.addKeywords(task, path, partial, builder);
}
}
| 2,142 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
MemberReferenceCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/MemberReferenceCompletionProvider.java | package com.tyron.completion.java.provider;
import static com.tyron.completion.java.provider.Completions.MAX_COMPLETION_ITEMS;
import static com.tyron.completion.java.provider.MemberSelectCompletionProvider.putMethod;
import static com.tyron.completion.java.util.CompletionItemFactory.item;
import static com.tyron.completion.java.util.CompletionItemFactory.keyword;
import static com.tyron.completion.java.util.CompletionItemFactory.method;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.Scope;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.model.CompletionList;
import java.util.HashMap;
import java.util.List;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.ArrayType;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.type.TypeVariable;
import me.xdrop.fuzzywuzzy.FuzzySearch;
public class MemberReferenceCompletionProvider extends BaseCompletionProvider {
public MemberReferenceCompletionProvider(JavaCompilerService service) {
super(service);
}
@Override
public void complete(
CompletionList.Builder builder,
CompileTask task,
TreePath path,
String partial,
boolean endsWithParen) {
checkCanceled();
Trees trees = Trees.instance(task.task);
MemberReferenceTree select = (MemberReferenceTree) path.getLeaf();
path = new TreePath(path, select.getQualifierExpression());
Element element = trees.getElement(path);
boolean isStatic = element instanceof TypeElement;
Scope scope = trees.getScope(path);
TypeMirror type = trees.getTypeMirror(path);
if (type instanceof ArrayType) {
completeArrayMemberReference(builder, isStatic);
} else if (type instanceof TypeVariable) {
completeTypeVariableMemberReference(
builder, task, scope, (TypeVariable) type, isStatic, partial);
} else if (type instanceof DeclaredType) {
completeDeclaredTypeMemberReference(
builder, task, scope, (DeclaredType) type, isStatic, partial);
}
}
private void completeArrayMemberReference(CompletionList.Builder builder, boolean isStatic) {
if (isStatic) {
builder.addItem(keyword("new"));
}
}
private void completeTypeVariableMemberReference(
CompletionList.Builder builder,
CompileTask task,
Scope scope,
TypeVariable type,
boolean isStatic,
String partial) {
if (type.getUpperBound() instanceof DeclaredType) {
completeDeclaredTypeMemberReference(
builder, task, scope, (DeclaredType) type.getUpperBound(), isStatic, partial);
} else if (type.getUpperBound() instanceof TypeVariable) {
completeTypeVariableMemberReference(
builder, task, scope, (TypeVariable) type.getUpperBound(), isStatic, partial);
}
}
private void completeDeclaredTypeMemberReference(
CompletionList.Builder builder,
CompileTask task,
Scope scope,
DeclaredType type,
boolean isStatic,
String partial) {
checkCanceled();
Trees trees = Trees.instance(task.task);
TypeElement typeElement = (TypeElement) type.asElement();
for (Element member : task.task.getElements().getAllMembers(typeElement)) {
if (FuzzySearch.partialRatio(String.valueOf(member.getSimpleName()), partial) < 70) {
continue;
}
if (member.getKind() != ElementKind.METHOD) {
continue;
}
if (!trees.isAccessible(scope, member, type)) {
continue;
}
if (!isStatic && member.getModifiers().contains(Modifier.STATIC)) {
continue;
}
if (member.getKind() == ElementKind.METHOD) {
HashMap<String, List<ExecutableElement>> methods = new HashMap<>();
putMethod((ExecutableElement) member, methods);
for (List<ExecutableElement> overloads : methods.values()) {
builder.addItems(
method(task, overloads, false, true, type),
JavaSortCategory.ACCESSIBLE_SYMBOL.toString());
}
} else {
builder.addItem(item(member));
}
}
if (isStatic) {
builder.addItem(keyword("new"));
}
if (builder.getItemCount() > MAX_COMPLETION_ITEMS) {
builder.incomplete();
}
}
}
| 4,694 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
BaseCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/BaseCompletionProvider.java | package com.tyron.completion.java.provider;
import com.sun.source.util.TreePath;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.model.CompletionList;
public abstract class BaseCompletionProvider {
private final JavaCompilerService mCompiler;
public BaseCompletionProvider(JavaCompilerService service) {
mCompiler = service;
}
protected JavaCompilerService getCompiler() {
return mCompiler;
}
public abstract void complete(
CompletionList.Builder builder,
CompileTask task,
TreePath path,
String partial,
boolean endsWithParen);
}
| 685 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FindCompletionsAt.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/FindCompletionsAt.java | package com.tyron.completion.java.provider;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ErroneousTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.SwitchTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.Trees;
public class FindCompletionsAt extends TreePathScanner<TreePath, Long> {
private static final String TAG = FindCompletionsAt.class.getSimpleName();
private CompilationUnitTree root;
private final SourcePositions pos;
public FindCompletionsAt(JavacTask task) {
pos = Trees.instance(task).getSourcePositions();
}
@Override
public TreePath visitLiteral(LiteralTree t, Long find) {
if (isInside(t, find)) {
return getCurrentPath();
}
return super.visitLiteral(t, find);
}
@Override
public TreePath visitCompilationUnit(CompilationUnitTree node, Long p) {
root = node;
return reduce(super.visitCompilationUnit(node, p), getCurrentPath());
}
@Override
public TreePath visitIdentifier(IdentifierTree t, Long find) {
if (isInside(t, find)) {
return getCurrentPath();
}
return super.visitIdentifier(t, find);
}
@Override
public TreePath visitImport(ImportTree t, Long find) {
if (isInside(t, find)) {
return getCurrentPath();
}
return super.visitImport(t, find);
}
@Override
public TreePath visitMemberSelect(MemberSelectTree t, Long find) {
if (isInside(t, find)) {
return getCurrentPath();
}
return super.visitMemberSelect(t, find);
}
@Override
public TreePath visitMemberReference(MemberReferenceTree t, Long find) {
if (isInside(t, find)) {
return getCurrentPath();
}
return super.visitMemberReference(t, find);
}
@Override
public TreePath visitCase(CaseTree t, Long find) {
TreePath smaller = super.visitCase(t, find);
if (smaller != null) {
return smaller;
}
if (isInside(t, find)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitSwitch(SwitchTree t, Long find) {
TreePath smaller = super.visitSwitch(t, find);
if (smaller != null) {
return smaller;
}
if (isInside(t, find)) {
return getCurrentPath();
}
return null;
}
@Override
public TreePath visitErroneous(ErroneousTree node, Long find) {
if (node.getErrorTrees() == null) {
return null;
}
for (Tree tree : node.getErrorTrees()) {
TreePath found = scan(tree, find);
if (found != null) {
return found;
}
}
return null;
}
private boolean isInside(Tree t, long find) {
long start = pos.getStartPosition(root, t);
long end = pos.getEndPosition(root, t);
if (start <= find && find <= end) {
return true;
}
return false;
}
@Override
public TreePath reduce(TreePath r1, TreePath r2) {
if (r1 == null) {
return r2;
}
return r1;
}
long start, end;
public String test() {
return "Identifier: " + start + ", " + end;
}
}
| 3,416 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaSortCategory.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/JavaSortCategory.java | package com.tyron.completion.java.provider;
import androidx.annotation.NonNull;
public enum JavaSortCategory {
/** A symbol within the local scope, e.g inside a method */
LOCAL_VARIABLE,
/** A symbol directly defined in this class, e.g a field or a method from the class */
DIRECT_MEMBER,
/**
* A symbol accessible from the current scope but is not a direct member, e.g a field or method
* from a super class
*/
ACCESSIBLE_SYMBOL,
/** Any other symbols that are not categorized above */
UNKNOWN,
/** Java keywords */
KEYWORD,
/** Symbols that are not yet accessible but will be accessible once imported */
TO_IMPORT;
@NonNull
@Override
public String toString() {
return String.valueOf(ordinal());
}
}
| 755 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ScopeCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/ScopeCompletionProvider.java | package com.tyron.completion.java.provider;
import static com.tyron.completion.java.util.CompletionItemFactory.classItem;
import static com.tyron.completion.java.util.CompletionItemFactory.item;
import static com.tyron.completion.java.util.CompletionItemFactory.method;
import static com.tyron.completion.java.util.CompletionItemFactory.overridableMethod;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.Scope;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.util.ElementUtil;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.model.CompletionList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.type.ExecutableType;
import me.xdrop.fuzzywuzzy.FuzzySearch;
public class ScopeCompletionProvider extends BaseCompletionProvider {
public ScopeCompletionProvider(JavaCompilerService service) {
super(service);
}
@Override
public void complete(
CompletionList.Builder builder,
CompileTask task,
TreePath path,
String partial,
boolean endsWithParen) {
checkCanceled();
addCompletionItems(task, path, partial, endsWithParen, builder);
}
public static void addCompletionItems(
CompileTask task,
TreePath path,
String partial,
boolean endsWithParen,
CompletionList.Builder builder) {
Trees trees = task.getTrees();
Scope scope = trees.getScope(path);
Predicate<CharSequence> filter =
p1 -> {
String label = p1.toString();
if (label.contains("(")) {
label = label.substring(0, label.indexOf('('));
}
return FuzzySearch.tokenSetPartialRatio(label, partial) >= 70;
};
TreePath parentPath = path.getParentPath().getParentPath();
Tree parentLeaf = parentPath.getLeaf();
for (Element element : ScopeHelper.scopeMembers(task, scope, filter)) {
checkCanceled();
if (element.getKind() == ElementKind.METHOD) {
ExecutableElement executableElement = (ExecutableElement) element;
String sortText = "";
if (Objects.equals(scope.getEnclosingClass(), element.getEnclosingElement())) {
sortText = JavaSortCategory.DIRECT_MEMBER.toString();
} else {
sortText = JavaSortCategory.ACCESSIBLE_SYMBOL.toString();
}
if (parentLeaf.getKind() == Tree.Kind.CLASS && !ElementUtil.isFinal(executableElement)) {
builder.addItems(
overridableMethod(
task, parentPath, Collections.singletonList(executableElement), endsWithParen),
sortText);
} else {
builder.addItems(
method(
task,
Collections.singletonList(executableElement),
endsWithParen,
false,
(ExecutableType) executableElement.asType()),
sortText);
}
} else {
CompletionItem item = item(element);
if (Objects.equals(scope.getEnclosingClass(), element.getEnclosingElement())) {
item.setSortText(JavaSortCategory.DIRECT_MEMBER.toString());
} else if (Objects.nonNull(scope.getEnclosingMethod())
&& Objects.equals(scope.getEnclosingMethod(), element.getEnclosingElement())) {
item.setSortText(JavaSortCategory.LOCAL_VARIABLE.toString());
} else {
item.setSortText(JavaSortCategory.ACCESSIBLE_SYMBOL.toString());
}
builder.addItem(item);
}
}
CompilationUnitTree root = task.root();
if (root != null) {
List<? extends Tree> typeDecls = root.getTypeDecls();
List<ClassTree> classTrees =
typeDecls.stream()
.filter(it -> it instanceof ClassTree)
.map(it -> (ClassTree) it)
.collect(Collectors.toList());
for (ClassTree classTree : classTrees) {
CompletionItem item = classItem(classTree.getSimpleName().toString());
item.setSortText(JavaSortCategory.ACCESSIBLE_SYMBOL.toString());
builder.addItem(item);
}
}
}
}
| 4,651 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
Completions.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/Completions.java | package com.tyron.completion.java.provider;
import static com.tyron.common.util.StringSearch.endsWithParen;
import static com.tyron.common.util.StringSearch.partialIdentifier;
import static com.tyron.completion.java.patterns.JavacTreePatterns.tree;
import static com.tyron.completion.java.util.CompletionItemFactory.classSnippet;
import static com.tyron.completion.java.util.CompletionItemFactory.packageSnippet;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import android.util.Log;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.sun.tools.javac.tree.JCTree;
import com.tyron.builder.model.SourceFileObject;
import com.tyron.common.util.StringSearch;
import com.tyron.completion.java.action.FindCurrentPath;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.CompilerContainer;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.compiler.ParseTask;
import com.tyron.completion.java.patterns.JavacTreePattern;
import com.tyron.completion.java.util.FileContentFixer;
import com.tyron.completion.model.CompletionList;
import com.tyron.completion.progress.ProcessCanceledException;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.util.Collections;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
/** Main entry point for getting completions */
public class Completions {
public static final int MAX_COMPLETION_ITEMS = 70;
private static final String TAG = Completions.class.getSimpleName();
// patterns
private static final JavacTreePattern.Capture<IdentifierTree> INSIDE_PARAMETERIZED =
tree(IdentifierTree.class).withParent(ParameterizedTypeTree.class);
private static final JavacTreePattern.Capture<IdentifierTree> INSIDE_RETURN =
tree(IdentifierTree.class).withParent(ReturnTree.class);
private static final JavacTreePattern.Capture<IdentifierTree> VARIABLE_NAME =
tree(IdentifierTree.class).withParent(JCTree.JCVariableDecl.class);
private static final JavacTreePattern.Capture<IdentifierTree> SWITCH_CONSTANT =
tree(IdentifierTree.class).withParent(CaseTree.class);
private final JavaCompilerService compiler;
public Completions(JavaCompilerService compiler) {
this.compiler = compiler;
}
public CompletionList.Builder complete(File file, String fileContents, long index) {
checkCanceled();
ParseTask task = compiler.parse(file.toPath(), fileContents);
CharSequence contents;
try {
StringBuilder pruned = new PruneMethodBodies(task.task).scan(task.root, index);
int end = StringSearch.endOfLine(pruned, (int) index);
pruned.insert(end, ';');
if (compiler.compiler.getCurrentContext() != null) {
contents =
new FileContentFixer(compiler.compiler.getCurrentContext()).fixFileContent(pruned);
} else {
contents = pruned.toString();
}
} catch (IndexOutOfBoundsException e) {
Log.w(TAG, "Unable to fix file content", e);
return null;
}
String partial = partialIdentifier(contents.toString(), (int) index);
return compileAndComplete(file, contents.toString(), partial, index);
}
private CompletionList.Builder compileAndComplete(
File file, String contents, final String partial, long cursor) {
SourceFileObject source = new SourceFileObject(file.toPath(), contents, Instant.now());
boolean endsWithParen = endsWithParen(contents, (int) cursor);
checkCanceled();
if (compiler.getCachedContainer().isWriting()) {
return null;
}
CompilerContainer container = compiler.compile(Collections.singletonList(source));
try {
return container.get(
task -> {
TreePath path = new FindCurrentPath(task.task).scan(task.root(), cursor);
String modifiedPartial = partial;
if (path.getLeaf().getKind() == Tree.Kind.IMPORT) {
modifiedPartial = StringSearch.qualifiedPartialIdentifier(contents, (int) cursor);
if (modifiedPartial.endsWith(FileContentFixer.INJECTED_IDENT)) {
modifiedPartial =
modifiedPartial.substring(
0, modifiedPartial.length() - FileContentFixer.INJECTED_IDENT.length());
}
}
return getCompletionList(task, path, modifiedPartial, endsWithParen);
});
} catch (Throwable e) {
if (e instanceof ProcessCanceledException) {
throw e;
}
compiler.destroy();
throw e;
}
}
private CompletionList.Builder getCompletionList(
CompileTask task, TreePath path, String partial, boolean endsWithParen) {
ProcessingContext context = createProcessingContext(task.task, task.root());
CompletionList.Builder builder = CompletionList.builder(partial);
switch (path.getLeaf().getKind()) {
case IDENTIFIER:
// suggest only classes on a parameterized tree
if (INSIDE_PARAMETERIZED.accepts(path.getLeaf(), context)) {
new ClassNameCompletionProvider(compiler)
.complete(builder, task, path, partial, endsWithParen);
break;
} else if (SWITCH_CONSTANT.accepts(path.getLeaf(), context)) {
new SwitchConstantCompletionProvider(compiler)
.complete(builder, task, path, partial, endsWithParen);
}
new IdentifierCompletionProvider(compiler)
.complete(builder, task, path, partial, endsWithParen);
break;
case MEMBER_SELECT:
new MemberSelectCompletionProvider(compiler)
.complete(builder, task, path, partial, endsWithParen);
break;
case MEMBER_REFERENCE:
new MemberReferenceCompletionProvider(compiler)
.complete(builder, task, path, partial, endsWithParen);
break;
case IMPORT:
new ImportCompletionProvider(compiler)
.complete(builder, task, path, partial, endsWithParen);
break;
case STRING_LITERAL:
break;
case VARIABLE:
new VariableNameCompletionProvider(compiler)
.complete(builder, task, path, partial, endsWithParen);
break;
default:
new KeywordCompletionProvider(compiler)
.complete(builder, task, path, partial, endsWithParen);
break;
}
return builder;
}
private void addTopLevelSnippets(ParseTask task, CompletionList list) {
Path file = Paths.get(task.root.getSourceFile().toUri());
if (!hasTypeDeclaration(task.root)) {
list.items.add(classSnippet(file));
if (task.root.getPackageName() == null) {
list.items.add(packageSnippet(file));
}
}
}
private boolean hasTypeDeclaration(CompilationUnitTree root) {
for (Tree tree : root.getTypeDecls()) {
if (tree.getKind() != Tree.Kind.ERRONEOUS) {
return true;
}
}
return false;
}
private ProcessingContext createProcessingContext(JavacTask task, CompilationUnitTree root) {
ProcessingContext context = new ProcessingContext();
context.put("trees", Trees.instance(task));
context.put("root", root);
return context;
}
}
| 7,550 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ImportCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/ImportCompletionProvider.java | package com.tyron.completion.java.provider;
import static com.tyron.completion.java.provider.MemberSelectCompletionProvider.putMethod;
import static com.tyron.completion.java.util.CompletionItemFactory.importClassItem;
import static com.tyron.completion.java.util.CompletionItemFactory.item;
import static com.tyron.completion.java.util.CompletionItemFactory.method;
import static com.tyron.completion.java.util.CompletionItemFactory.packageItem;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.common.util.StringSearch;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.model.CompletionList;
import com.tyron.completion.model.DrawableKind;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import me.xdrop.fuzzywuzzy.FuzzySearch;
public class ImportCompletionProvider extends BaseCompletionProvider {
public ImportCompletionProvider(JavaCompilerService service) {
super(service);
}
@Override
public void complete(
CompletionList.Builder builder,
CompileTask task,
TreePath treePath,
String path,
boolean endsWithParen) {
checkCanceled();
Set<String> names = new HashSet<>();
for (String className : getCompiler().publicTopLevelTypes()) {
if (className.startsWith(path)) {
int start = path.lastIndexOf('.');
int end = className.indexOf('.', path.length());
if (end == -1) end = className.length();
String segment = className.substring(start + 1, end);
if (names.contains(segment)) continue;
names.add(segment);
boolean isClass = className.endsWith(segment);
CompletionItem item;
if (isClass) {
item = importClassItem(className);
} else {
item = packageItem(segment);
}
item.addFilterText(segment);
if (path.contains(".")) {
item.addFilterText(path.substring(0, path.lastIndexOf('.')) + "." + segment);
}
builder.addItem(item);
}
}
}
public List<CompletionItem> addAnonymous(CompileTask task, TreePath path, String partial) {
checkCanceled();
List<CompletionItem> items = new ArrayList<>();
if (!(path.getLeaf() instanceof NewClassTree)) {
return items;
}
if (path.getParentPath().getParentPath().getLeaf().getKind() == Tree.Kind.METHOD_INVOCATION) {
Trees trees = Trees.instance(task.task);
MethodInvocationTree method =
(MethodInvocationTree) path.getParentPath().getParentPath().getLeaf();
Element element = trees.getElement(path.getParentPath().getParentPath());
if (element instanceof ExecutableElement) {
ExecutableElement executable = (ExecutableElement) element;
int argumentToComplete = 0;
for (int i = 0; i < method.getArguments().size(); i++) {
ExpressionTree exp = method.getArguments().get(i);
if (exp.toString().equals(partial) || exp.toString().equals("new " + partial)) {
argumentToComplete = i;
}
}
VariableElement var = executable.getParameters().get(argumentToComplete);
if (var.asType() instanceof DeclaredType) {
DeclaredType type = (DeclaredType) var.asType();
Element classElement = type.asElement();
if (StringSearch.matchesPartialName(classElement.getSimpleName().toString(), partial)) {
CompletionItem item = new CompletionItem();
StringBuilder sb = new StringBuilder();
if (classElement instanceof TypeElement) {
TypeElement typeElement = (TypeElement) classElement;
// import the class
item.action = CompletionItem.Kind.IMPORT;
item.data = typeElement.getQualifiedName().toString();
item.iconKind = DrawableKind.Interface;
item.label = classElement.getSimpleName().toString() + " {...}";
item.commitText =
"" + classElement.getSimpleName() + "() {\n" + "\t" + "// TODO\n" + "}";
item.cursorOffset = item.commitText.length();
item.detail = "";
}
items.add(item);
}
}
}
}
return items;
}
public static void addStaticImports(
CompileTask task,
CompilationUnitTree root,
String partial,
boolean endsWithParen,
CompletionList.Builder list) {
checkCanceled();
Trees trees = Trees.instance(task.task);
HashMap<String, List<ExecutableElement>> methods = new HashMap<>();
for (ImportTree i : root.getImports()) {
if (!i.isStatic()) continue;
MemberSelectTree id = (MemberSelectTree) i.getQualifiedIdentifier();
if (!importMatchesPartial(id.getIdentifier(), partial)) continue;
TreePath path = trees.getPath(root, id.getExpression());
TypeElement type = (TypeElement) trees.getElement(path);
for (Element member : type.getEnclosedElements()) {
if (!member.getModifiers().contains(Modifier.STATIC)) continue;
if (!memberMatchesImport(id.getIdentifier(), member)) continue;
if (FuzzySearch.partialRatio(String.valueOf(member.getSimpleName()), partial) < 70)
continue;
if (member.getKind() == ElementKind.METHOD) {
methods.clear();
putMethod((ExecutableElement) member, methods);
for (List<ExecutableElement> overloads : methods.values()) {
for (CompletionItem item :
method(task, overloads, endsWithParen, false, (DeclaredType) type.asType())) {
item.setSortText(JavaSortCategory.ACCESSIBLE_SYMBOL.toString());
list.addItem(item);
}
}
} else {
CompletionItem item = item(member);
item.setSortText(JavaSortCategory.ACCESSIBLE_SYMBOL.toString());
list.addItem(item);
}
}
}
}
private static boolean importMatchesPartial(Name staticImport, String partial) {
return staticImport.contentEquals("*")
|| StringSearch.matchesPartialName(staticImport, partial);
}
private static boolean memberMatchesImport(Name staticImport, Element member) {
return staticImport.contentEquals("*") || staticImport.contentEquals(member.getSimpleName());
}
}
| 7,214 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
KeywordCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/KeywordCompletionProvider.java | package com.tyron.completion.java.provider;
import static com.tyron.completion.java.util.CompletionItemFactory.keyword;
import static com.tyron.completion.progress.ProgressManager.checkCanceled;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import com.tyron.common.util.StringSearch;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.insert.KeywordInsertHandler;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.model.CompletionList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class KeywordCompletionProvider extends BaseCompletionProvider {
private static final String[] TOP_LEVEL_KEYWORDS = {
"package",
"import",
"public",
"private",
"protected",
"abstract",
"class",
"interface",
"@interface",
"extends",
"implements",
};
private static final String[] CLASS_BODY_KEYWORDS = {
"public",
"private",
"protected",
"static",
"final",
"native",
"synchronized",
"abstract",
"default",
"class",
"interface",
"void",
"boolean",
"int",
"long",
"float",
"double",
"implements",
"extends"
};
private static final String[] METHOD_BODY_KEYWORDS = {
"new",
"assert",
"try",
"catch",
"finally",
"throw",
"return",
"break",
"case",
"continue",
"default",
"do",
"while",
"for",
"switch",
"if",
"else",
"instanceof",
"final",
"class",
"void",
"boolean",
"int",
"long",
"float",
"double"
};
private static final String[] CLASS_LEVEL_KEYWORDS = {
"public",
"private",
"protected",
"abstract",
"class",
"interface",
"@interface",
"extends",
"implements"
};
public KeywordCompletionProvider(JavaCompilerService service) {
super(service);
}
public static void addKeywords(
CompileTask task, TreePath path, String partial, CompletionList.Builder list) {
checkCanceled();
if (!partial.isEmpty() && Character.isUpperCase(partial.charAt(0))) {
// keywords are only lowercase
return;
}
TreePath keywordPath = findKeywordLevel(path);
Tree level = keywordPath.getLeaf();
Set<String> keywords = new HashSet<>();
if (level instanceof CompilationUnitTree) {
keywords.addAll(Arrays.asList(TOP_LEVEL_KEYWORDS));
} else if (level instanceof ClassTree) {
keywords.addAll(Arrays.asList(CLASS_BODY_KEYWORDS));
} else if (level instanceof MethodTree) {
keywords.addAll(Arrays.asList(METHOD_BODY_KEYWORDS));
}
for (String k : keywords) {
if (StringSearch.matchesPartialName(k, partial)) {
CompletionItem keyword = keyword(k);
keyword.setInsertHandler(new KeywordInsertHandler(task, path, keyword));
keyword.setSortText(JavaSortCategory.KEYWORD.toString());
list.addItem(keyword);
}
}
}
@Override
public void complete(
CompletionList.Builder builder,
CompileTask task,
TreePath path,
String partial,
boolean endsWithParen) {
addKeywords(task, path, partial, builder);
}
public static TreePath findKeywordLevel(TreePath path) {
while (path != null) {
checkCanceled();
if (path.getLeaf() instanceof CompilationUnitTree
|| path.getLeaf() instanceof ClassTree
|| path.getLeaf() instanceof MethodTree) {
return path;
}
path = path.getParentPath();
}
throw new RuntimeException("empty path");
}
}
| 3,807 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FindTypeDeclarationNamed.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/FindTypeDeclarationNamed.java | package com.tyron.completion.java.provider;
import com.sun.source.tree.*;
import com.sun.source.util.TreeScanner;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/** TreeScanner that looks for occurrences of qualified names */
public class FindTypeDeclarationNamed extends TreeScanner<ClassTree, String> {
private final List<CharSequence> qualifiedName = new ArrayList<>();
@Override
public ClassTree visitCompilationUnit(CompilationUnitTree t, String find) {
String name = Objects.toString(t.getPackageName(), "");
qualifiedName.add(name);
return super.visitCompilationUnit(t, find);
}
@Override
public ClassTree visitClass(ClassTree t, String find) {
qualifiedName.add(t.getSimpleName());
if (String.join(".", qualifiedName).equals(find)) {
return t;
}
ClassTree recurse = super.visitClass(t, find);
qualifiedName.remove(qualifiedName.size() - 1);
return recurse;
}
@Override
public ClassTree reduce(ClassTree a, ClassTree b) {
if (a != null) return a;
return b;
}
}
| 1,073 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
VariableNameCompletionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/VariableNameCompletionProvider.java | package com.tyron.completion.java.provider;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.JavaCompilerService;
import com.tyron.completion.java.util.ActionUtil;
import com.tyron.completion.java.util.CompletionItemFactory;
import com.tyron.completion.model.CompletionItem;
import com.tyron.completion.model.CompletionList;
import java.util.List;
import javax.lang.model.element.Element;
import javax.lang.model.type.TypeMirror;
/**
* Responsive for suggesting unique variable names. If a variable already exists, it is appended
* with a number. If the existing variable ends with a number one is added to it.
*/
public class VariableNameCompletionProvider extends BaseCompletionProvider {
public VariableNameCompletionProvider(JavaCompilerService service) {
super(service);
}
@Override
public void complete(
CompletionList.Builder builder,
CompileTask task,
TreePath path,
String partial,
boolean endsWithParen) {
Element element = Trees.instance(task.task).getElement(path);
if (element == null) {
return;
}
TypeMirror type = element.asType();
if (type == null) {
return;
}
List<String> names = ActionUtil.guessNamesFromType(type);
if (names.isEmpty()) {
return;
}
for (String name : names) {
while (ActionUtil.containsVariableAtScope(name, task, path)) {
name = ActionUtil.getVariableName(name);
}
CompletionItem item = CompletionItemFactory.item(name);
item.setSortText(JavaSortCategory.UNKNOWN.toString());
builder.addItem(item);
}
}
}
| 1,714 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
FindHelper.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/provider/FindHelper.java | package com.tyron.completion.java.provider;
import com.sun.source.tree.ArrayTypeTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.PrimitiveTypeTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.tyron.completion.java.compiler.CompileTask;
import com.tyron.completion.java.compiler.ParseTask;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Types;
/** Convenience class for common tasks with completions */
public class FindHelper {
public static String[] erasedParameterTypes(CompileTask task, ExecutableElement method) {
Types types = task.task.getTypes();
String[] erasedParameterTypes = new String[method.getParameters().size()];
for (int i = 0; i < erasedParameterTypes.length; i++) {
TypeMirror p = method.getParameters().get(i).asType();
erasedParameterTypes[i] = types.erasure(p).toString();
}
return erasedParameterTypes;
}
public static String[] erasedParameterTypes(ParseTask task, ExecutableElement method) {
Types types = task.task.getTypes();
String[] erasedParameterTypes = new String[method.getParameters().size()];
for (int i = 0; i < erasedParameterTypes.length; i++) {
TypeMirror p = method.getParameters().get(i).asType();
erasedParameterTypes[i] = types.erasure(p).toString();
}
return erasedParameterTypes;
}
public static MethodTree findMethod(
ParseTask task, String className, String methodName, String[] erasedParameterTypes) {
ClassTree classTree = findType(task, className);
for (Tree member : classTree.getMembers()) {
if (member.getKind() != Tree.Kind.METHOD) continue;
MethodTree method = (MethodTree) member;
if (!method.getName().contentEquals(methodName)) continue;
if (!isSameMethodType(method, erasedParameterTypes)) continue;
return method;
}
return null;
}
public static VariableTree findField(ParseTask task, String className, String memberName) {
ClassTree classTree = findType(task, className);
for (Tree member : classTree.getMembers()) {
if (member.getKind() != Tree.Kind.VARIABLE) continue;
VariableTree variable = (VariableTree) member;
if (!variable.getName().contentEquals(memberName)) continue;
return variable;
}
throw new RuntimeException("no variable");
}
public static ClassTree findType(ParseTask task, String className) {
return new FindTypeDeclarationNamed().scan(task.root, className);
}
public static ExecutableElement findMethod(
CompileTask task, String className, String methodName, String[] erasedParameterTypes) {
TypeElement type = task.task.getElements().getTypeElement(className);
for (Element member : type.getEnclosedElements()) {
if (member.getKind() != ElementKind.METHOD) continue;
ExecutableElement method = (ExecutableElement) member;
if (isSameMethod(task, method, className, methodName, erasedParameterTypes)) {
return method;
}
}
return null;
}
private static boolean isSameMethod(
CompileTask task,
ExecutableElement method,
String className,
String methodName,
String[] erasedParameterTypes) {
Types types = task.task.getTypes();
TypeElement parent = (TypeElement) method.getEnclosingElement();
if (!parent.getQualifiedName().contentEquals(className)) return false;
if (!method.getSimpleName().contentEquals(methodName)) return false;
if (method.getParameters().size() != erasedParameterTypes.length) return false;
for (int i = 0; i < erasedParameterTypes.length; i++) {
TypeMirror erasure = types.erasure(method.getParameters().get(i).asType());
boolean same = erasure.toString().equals(erasedParameterTypes[i]);
if (!same) return false;
}
return true;
}
private static boolean isSameMethodType(MethodTree candidate, String[] erasedParameterTypes) {
if (candidate.getParameters().size() != erasedParameterTypes.length) {
return false;
}
for (int i = 0; i < candidate.getParameters().size(); i++) {
if (!typeMatches(candidate.getParameters().get(i).getType(), erasedParameterTypes[i])) {
return false;
}
}
return true;
}
private static boolean typeMatches(Tree candidate, String erasedType) {
if (candidate instanceof ParameterizedTypeTree) {
ParameterizedTypeTree parameterized = (ParameterizedTypeTree) candidate;
return typeMatches(parameterized.getType(), erasedType);
}
if (candidate instanceof PrimitiveTypeTree) {
return candidate.toString().equals(erasedType);
}
if (candidate instanceof IdentifierTree) {
String simpleName = candidate.toString();
return erasedType.endsWith(simpleName);
}
if (candidate instanceof MemberSelectTree) {
return candidate.toString().equals(erasedType);
}
if (candidate instanceof ArrayTypeTree) {
ArrayTypeTree array = (ArrayTypeTree) candidate;
if (!erasedType.endsWith("[]")) return false;
String erasedElement = erasedType.substring(0, erasedType.length() - "[]".length());
return typeMatches(array.getType(), erasedElement);
}
return true;
}
// public static Location location(CompileTask task, TreePath path) {
// return location(task, path, "");
// }
//
// public static Location location(CompileTask task, TreePath path, CharSequence name) {
// var lines = path.getCompilationUnit().getLineMap();
// var pos = Trees.instance(task.task).getSourcePositions();
// var start = (int) pos.getStartPosition(path.getCompilationUnit(), path.getLeaf());
// var end = (int) pos.getEndPosition(path.getCompilationUnit(), path.getLeaf());
// if (name.length() > 0) {
// start = FindHelper.findNameIn(path.getCompilationUnit(), name, start, end);
// end = start + name.length();
// }
// var startLine = (int) lines.getLineNumber(start);
// var startColumn = (int) lines.getColumnNumber(start);
// var startPos = new Position(startLine - 1, startColumn - 1);
// var endLine = (int) lines.getLineNumber(end);
// var endColumn = (int) lines.getColumnNumber(end);
// var endPos = new Position(endLine - 1, endColumn - 1);
// var range = new Range(startPos, endPos);
// URI uri = path.getCompilationUnit().getSourceFile().toUri();
// return new Location(uri, range);
// }
public static int findNameIn(CompilationUnitTree root, CharSequence name, int start, int end) {
CharSequence contents;
try {
contents = root.getSourceFile().getCharContent(true);
} catch (IOException e) {
throw new RuntimeException(e);
}
Matcher matcher = Pattern.compile("\\b" + name + "\\b").matcher(contents);
matcher.region(start, end);
if (matcher.find()) {
return matcher.start();
}
return -1;
}
}
| 7,502 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CodeAction.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/model/CodeAction.java | package com.tyron.completion.java.model;
import androidx.annotation.NonNull;
import com.tyron.completion.model.TextEdit;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
public class CodeAction {
private String title;
private Map<Path, List<TextEdit>> edits;
public static CodeAction NONE = new CodeAction();
public Map<Path, List<TextEdit>> getEdits() {
return edits;
}
public void setEdits(Map<Path, List<TextEdit>> edits) {
this.edits = edits;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@NonNull
@Override
public String toString() {
return title + " : " + edits.values();
}
}
| 722 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CodeActionList.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/java/model/CodeActionList.java | package com.tyron.completion.java.model;
import java.util.List;
/**
* CLass that holds a list of {@link CodeAction} useful when passing CodeActions with different
* categories
*
* <p>eg. Quick fixes - CodeAction - CodeActon Suggestions - CodeAction - CodeAction
*/
public class CodeActionList {
private String title;
private List<CodeAction> actions;
public List<CodeAction> getActions() {
return actions;
}
public void setActions(List<CodeAction> actions) {
this.actions = actions;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
| 638 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaCompletionProcessor.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/psi/scope/JavaCompletionProcessor.java | package com.tyron.completion.psi.scope;
import androidx.annotation.Nullable;
import com.tyron.common.logging.IdeLog;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.codeInsight.completion.scope.JavaCompletionHints;
import org.jetbrains.kotlin.com.intellij.openapi.util.Condition;
import org.jetbrains.kotlin.com.intellij.openapi.util.Key;
import org.jetbrains.kotlin.com.intellij.openapi.util.NotNullLazyValue;
import org.jetbrains.kotlin.com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.kotlin.com.intellij.psi.JavaPsiFacade;
import org.jetbrains.kotlin.com.intellij.psi.JavaResolveResult;
import org.jetbrains.kotlin.com.intellij.psi.LambdaUtil;
import org.jetbrains.kotlin.com.intellij.psi.PsiClass;
import org.jetbrains.kotlin.com.intellij.psi.PsiCompiledElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiElementFactory;
import org.jetbrains.kotlin.com.intellij.psi.PsiEnumConstant;
import org.jetbrains.kotlin.com.intellij.psi.PsiExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiField;
import org.jetbrains.kotlin.com.intellij.psi.PsiFile;
import org.jetbrains.kotlin.com.intellij.psi.PsiImportStatementBase;
import org.jetbrains.kotlin.com.intellij.psi.PsiIntersectionType;
import org.jetbrains.kotlin.com.intellij.psi.PsiJavaCodeReferenceElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiKeyword;
import org.jetbrains.kotlin.com.intellij.psi.PsiMember;
import org.jetbrains.kotlin.com.intellij.psi.PsiMethod;
import org.jetbrains.kotlin.com.intellij.psi.PsiMethodReferenceExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiMethodReferenceType;
import org.jetbrains.kotlin.com.intellij.psi.PsiMethodReferenceUtil;
import org.jetbrains.kotlin.com.intellij.psi.PsiModifier;
import org.jetbrains.kotlin.com.intellij.psi.PsiModifierList;
import org.jetbrains.kotlin.com.intellij.psi.PsiModifierListOwner;
import org.jetbrains.kotlin.com.intellij.psi.PsiPackage;
import org.jetbrains.kotlin.com.intellij.psi.PsiQualifiedReference;
import org.jetbrains.kotlin.com.intellij.psi.PsiReferenceExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiResolveHelper;
import org.jetbrains.kotlin.com.intellij.psi.PsiSubstitutor;
import org.jetbrains.kotlin.com.intellij.psi.PsiSuperExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiType;
import org.jetbrains.kotlin.com.intellij.psi.PsiVariable;
import org.jetbrains.kotlin.com.intellij.psi.ResolveState;
import org.jetbrains.kotlin.com.intellij.psi.filters.ElementFilter;
import org.jetbrains.kotlin.com.intellij.psi.impl.PsiNameHelperImpl;
import org.jetbrains.kotlin.com.intellij.psi.impl.light.LightMethodBuilder;
import org.jetbrains.kotlin.com.intellij.psi.impl.source.resolve.JavaResolveUtil;
import org.jetbrains.kotlin.com.intellij.psi.infos.CandidateInfo;
import org.jetbrains.kotlin.com.intellij.psi.scope.ElementClassHint;
import org.jetbrains.kotlin.com.intellij.psi.scope.JavaScopeProcessorEvent;
import org.jetbrains.kotlin.com.intellij.psi.scope.PsiScopeProcessor;
import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.kotlin.com.intellij.psi.util.PsiTypesUtil;
import org.jetbrains.kotlin.com.intellij.psi.util.PsiUtil;
import org.jetbrains.kotlin.com.intellij.psi.util.PsiUtilCore;
import org.jetbrains.kotlin.com.intellij.util.containers.ContainerUtil;
import org.jetbrains.kotlin.it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet;
public class JavaCompletionProcessor implements PsiScopeProcessor, ElementClassHint {
private static final Logger LOG = IdeLog.getCurrentLogger(JavaCompletionProcessor.class);
private final boolean myInJavaDoc;
private boolean myStatic;
private PsiElement myDeclarationHolder;
private final Map<CompletionElement, CompletionElement> myResults = new LinkedHashMap<>();
private final Set<CompletionElement> mySecondRateResults = new ReferenceOpenHashSet<>();
private final Set<String> myShadowedNames = new HashSet<>();
private final Set<String> myCurrentScopeMethodNames = new HashSet<>();
private final Set<String> myFinishedScopesMethodNames = new HashSet<>();
private final PsiElement myElement;
private final PsiElement myScope;
private final ElementFilter myFilter;
private boolean myMembersFlag;
private final boolean myQualified;
private PsiType myQualifierType;
private final Condition<? super String> myMatcher;
private final Options myOptions;
private final boolean myAllowStaticWithInstanceQualifier;
private final NotNullLazyValue<Collection<PsiType>> myExpectedGroundTypes;
public JavaCompletionProcessor(
@NotNull PsiElement element,
ElementFilter filter,
Options options,
@NotNull Condition<? super String> nameCondition) {
myOptions = options;
myElement = element;
myMatcher = nameCondition;
myFilter = filter;
PsiElement scope = element;
myInJavaDoc = JavaResolveUtil.isInJavaDoc(myElement);
if (myInJavaDoc) myMembersFlag = true;
while (scope != null && !(scope instanceof PsiFile) && !(scope instanceof PsiClass)) {
scope = scope.getContext();
}
myScope = scope;
PsiClass qualifierClass = null;
PsiElement elementParent = element.getContext();
myQualified =
elementParent instanceof PsiReferenceExpression
&& ((PsiReferenceExpression) elementParent).isQualified();
if (elementParent instanceof PsiReferenceExpression) {
PsiExpression qualifier = ((PsiReferenceExpression) elementParent).getQualifierExpression();
if (qualifier instanceof PsiSuperExpression) {
final PsiJavaCodeReferenceElement qSuper = ((PsiSuperExpression) qualifier).getQualifier();
if (qSuper == null) {
qualifierClass = JavaResolveUtil.getContextClass(myElement);
} else {
final PsiElement target = qSuper.resolve();
qualifierClass = target instanceof PsiClass ? (PsiClass) target : null;
}
} else if (qualifier != null) {
myQualifierType = qualifier.getType();
if (myQualifierType == null && qualifier instanceof PsiJavaCodeReferenceElement) {
final PsiElement target = ((PsiJavaCodeReferenceElement) qualifier).resolve();
if (target instanceof PsiClass) {
qualifierClass = (PsiClass) target;
}
}
} else {
qualifierClass = JavaResolveUtil.getContextClass(myElement);
}
}
if (qualifierClass != null) {
myQualifierType =
JavaPsiFacade.getElementFactory(element.getProject()).createType(qualifierClass);
}
myAllowStaticWithInstanceQualifier =
!options.filterStaticAfterInstance || allowStaticAfterInstanceQualifier(element);
// myExpectedGroundTypes = NotNullLazyValue.createValue(
// () -> ContainerUtil.map(ExpectedTypesGetter.getExpectedTypes(element, false),
//
// FunctionalInterfaceParameterizationUtil::getGroundTargetType));
myExpectedGroundTypes = NotNullLazyValue.createValue(Collections::emptyList);
}
private static boolean allowStaticAfterInstanceQualifier(@NotNull PsiElement position) {
// return SuppressManager.getInstance().isSuppressedFor(position,
// AccessStaticViaInstanceBase.ACCESS_STATIC_VIA_INSTANCE) ||
// Registry.is("ide.java.completion.suggest.static.after.instance");
return false;
}
public static boolean seemsInternal(PsiClass clazz) {
String name = clazz.getName();
return name != null && name.startsWith("$");
}
@Override
public void handleEvent(@NotNull Event event, Object associated) {
if (JavaScopeProcessorEvent.isEnteringStaticScope(event, associated)) {
myStatic = true;
}
if (event == JavaScopeProcessorEvent.CHANGE_LEVEL) {
myMembersFlag = true;
myFinishedScopesMethodNames.addAll(myCurrentScopeMethodNames);
myCurrentScopeMethodNames.clear();
}
if (event == JavaScopeProcessorEvent.SET_CURRENT_FILE_CONTEXT) {
myDeclarationHolder = (PsiElement) associated;
}
}
@Override
public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) {
if (element instanceof PsiPackage && !isQualifiedContext()) {
if (myScope instanceof PsiClass) {
return true;
}
if (((PsiPackage) element).getQualifiedName().contains(".")
&& PsiTreeUtil.getParentOfType(myElement, PsiImportStatementBase.class) != null) {
return true;
}
}
if (element instanceof PsiClass && seemsInternal((PsiClass) element)) {
return true;
}
if (element instanceof PsiMember
&& !PsiNameHelperImpl.getInstance().isIdentifier(((PsiMember) element).getName())) {
// The member could be defined in another JVM language where its name is not a legal name in
// Java.
// In this case, just skip such the member. We cannot legally reference it from Java source.
return true;
}
if (element instanceof PsiMethod) {
PsiMethod method = (PsiMethod) element;
if (PsiTypesUtil.isGetClass(method) && PsiUtil.isLanguageLevel5OrHigher(myElement)) {
PsiType patchedType =
PsiTypesUtil.createJavaLangClassType(myElement, myQualifierType, false);
if (patchedType != null) {
element =
new LightMethodBuilder(element.getManager(), method.getName())
.addModifier(PsiModifier.PUBLIC)
.setMethodReturnType(patchedType)
.setContainingClass(method.getContainingClass());
}
}
}
if (element instanceof PsiVariable) {
String name = ((PsiVariable) element).getName();
if (myShadowedNames.contains(name)) return true;
if (myQualified || PsiUtil.isJvmLocalVariable(element)) {
myShadowedNames.add(name);
}
}
if (element instanceof PsiMethod) {
myCurrentScopeMethodNames.add(((PsiMethod) element).getName());
}
if (!satisfies(element, state) || !isAccessible(element)) return true;
StaticProblem sp =
myElement.getParent() instanceof PsiMethodReferenceExpression
? StaticProblem.none
: getStaticProblem(element);
if (sp == StaticProblem.instanceAfterStatic) return true;
CompletionElement completion =
new CompletionElement(
element,
state.get(PsiSubstitutor.KEY),
getCallQualifierText(element),
getMethodReferenceType(element));
CompletionElement prev = myResults.get(completion);
if (prev == null || completion.isMoreSpecificThan(prev)) {
myResults.put(completion, completion);
if (sp == StaticProblem.staticAfterInstance) {
mySecondRateResults.add(completion);
}
}
// || !PATTERNS_IN_SWITCH.isAvailable(myElement)
if (!(element instanceof PsiClass)) return true;
final PsiClass psiClass = (PsiClass) element;
if (psiClass.hasModifierProperty(PsiModifier.SEALED)) {
// addSealedHierarchy(state, psiClass);
}
return true;
}
public Iterable<CompletionElement> getResults() {
if (mySecondRateResults.size() == myResults.size()) {
return mySecondRateResults;
}
return ContainerUtil.filter(
myResults.values(), element -> !mySecondRateResults.contains(element));
}
public void clear() {
myResults.clear();
mySecondRateResults.clear();
}
@Override
public boolean shouldProcess(@NotNull ElementClassHint.DeclarationKind kind) {
switch (kind) {
case CLASS:
return myFilter.isClassAcceptable(PsiClass.class);
case FIELD:
return myFilter.isClassAcceptable(PsiField.class);
case METHOD:
return myFilter.isClassAcceptable(PsiMethod.class);
case PACKAGE:
return myFilter.isClassAcceptable(PsiPackage.class);
case VARIABLE:
return myFilter.isClassAcceptable(PsiVariable.class);
case ENUM_CONST:
return myFilter.isClassAcceptable(PsiEnumConstant.class);
}
return false;
}
@Override
public <T> T getHint(@NotNull Key<T> hintKey) {
if (hintKey == ElementClassHint.KEY) {
//noinspection unchecked
return (T) this;
}
if (hintKey == JavaCompletionHints.NAME_FILTER) {
//noinspection unchecked
return (T) myMatcher;
}
return null;
}
@Nullable
private PsiType getMethodReferenceType(PsiElement completion) {
PsiElement parent = myElement.getParent();
if (completion instanceof PsiMethod && parent instanceof PsiMethodReferenceExpression) {
PsiType matchingType =
ContainerUtil.find(
myExpectedGroundTypes.getValue(),
candidate ->
candidate != null
&& hasSuitableType(
(PsiMethodReferenceExpression) parent,
(PsiMethod) completion,
candidate));
return matchingType != null
? matchingType
: new PsiMethodReferenceType((PsiMethodReferenceExpression) parent);
}
return null;
}
private static boolean hasSuitableType(
PsiMethodReferenceExpression refPlace, PsiMethod method, @NotNull PsiType expectedType) {
PsiMethodReferenceExpression referenceExpression =
createMethodReferenceExpression(method, refPlace);
return LambdaUtil.performWithTargetType(
referenceExpression,
expectedType,
() -> {
JavaResolveResult result = referenceExpression.advancedResolve(false);
return method.getManager().areElementsEquivalent(method, result.getElement())
&& PsiMethodReferenceUtil.isReturnTypeCompatible(
referenceExpression, result, expectedType); // &&
//
// PsiMethodReferenceHighlightingUtil.checkMethodReferenceContext(referenceExpression,
// method, expectedType) == null;
});
}
private static PsiMethodReferenceExpression createMethodReferenceExpression(
PsiMethod method, PsiMethodReferenceExpression place) {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(method.getProject());
PsiMethodReferenceExpression copy = (PsiMethodReferenceExpression) place.copy();
PsiElement referenceNameElement = copy.getReferenceNameElement();
assert (referenceNameElement != null) : copy;
referenceNameElement.replace(
method.isConstructor()
? factory.createKeyword("new")
: factory.createIdentifier(method.getName()));
return copy;
}
private boolean isQualifiedContext() {
final PsiElement elementParent = myElement.getParent();
return elementParent instanceof PsiQualifiedReference
&& ((PsiQualifiedReference) elementParent).getQualifier() != null;
}
@NotNull
private String getCallQualifierText(@NotNull PsiElement element) {
if (element instanceof PsiMethod) {
PsiMethod method = (PsiMethod) element;
if (myFinishedScopesMethodNames.contains(method.getName())) {
String className =
myDeclarationHolder instanceof PsiClass
? ((PsiClass) myDeclarationHolder).getName()
: null;
if (className != null) {
return className + (method.hasModifierProperty(PsiModifier.STATIC) ? "." : ".this.");
}
}
}
return "";
}
private StaticProblem getStaticProblem(PsiElement element) {
if (myOptions.showInstanceInStaticContext && !isQualifiedContext()) {
return StaticProblem.none;
}
if (element instanceof PsiModifierListOwner) {
PsiModifierListOwner modifierListOwner = (PsiModifierListOwner) element;
if (myStatic) {
if (!(element instanceof PsiClass)
&& !modifierListOwner.hasModifierProperty(PsiModifier.STATIC)) {
// we don't need non-static method in static context.
return StaticProblem.instanceAfterStatic;
}
} else {
if (!myAllowStaticWithInstanceQualifier
&& modifierListOwner.hasModifierProperty(PsiModifier.STATIC)
&& !myMembersFlag) {
// according settings we don't need to process such fields/methods
return StaticProblem.staticAfterInstance;
}
}
}
return StaticProblem.none;
}
public boolean satisfies(@NotNull PsiElement element, @NotNull ResolveState state) {
String name = PsiUtilCore.getName(element);
if (element instanceof PsiMethod
&& ((PsiMethod) element).isConstructor()
&& myElement.getParent() instanceof PsiMethodReferenceExpression) {
name = PsiKeyword.NEW;
}
if (name != null && StringUtil.isNotEmpty(name) && myMatcher.value(name)) {
if (myFilter.isClassAcceptable(element.getClass())
&& myFilter.isAcceptable(
new CandidateInfo(element, state.get(PsiSubstitutor.KEY)), myElement)) {
return true;
}
}
return false;
}
public boolean isAccessible(@Nullable final PsiElement element) {
// if checkAccess is false, we only show inaccessible source elements because their access
// modifiers can be changed later by the user.
// compiled element can't be changed, so we don't pollute the completion with them. In Javadoc,
// everything is allowed.
if (!myOptions.checkAccess && myInJavaDoc) return true;
if (isAccessibleForResolve(element)) {
return true;
}
return !myOptions.checkAccess && !(element instanceof PsiCompiledElement);
}
private boolean isAccessibleForResolve(@Nullable PsiElement element) {
if (element instanceof PsiMember) {
Set<PsiClass> accessObjectClasses =
!myQualified
? Collections.singleton(null)
: myQualifierType instanceof PsiIntersectionType
? ContainerUtil.map2Set(
Arrays.asList(((PsiIntersectionType) myQualifierType).getConjuncts()),
PsiUtil::resolveClassInClassTypeOnly)
: Collections.singleton(PsiUtil.resolveClassInClassTypeOnly(myQualifierType));
PsiMember member = (PsiMember) element;
PsiResolveHelper helper = getResolveHelper();
PsiModifierList modifierList = member.getModifierList();
return ContainerUtil.exists(
accessObjectClasses,
aoc -> helper.isAccessible(member, modifierList, myElement, aoc, myDeclarationHolder));
}
if (element instanceof PsiPackage) {
return getResolveHelper().isAccessible((PsiPackage) element, myElement);
}
return true;
}
@NotNull
private PsiResolveHelper getResolveHelper() {
return JavaPsiFacade.getInstance(myElement.getProject()).getResolveHelper();
}
public static final class Options {
public static final Options DEFAULT_OPTIONS = new Options(true, true, false);
public static final Options CHECK_NOTHING = new Options(false, false, false);
final boolean checkAccess;
final boolean filterStaticAfterInstance;
final boolean showInstanceInStaticContext;
private Options(
boolean checkAccess,
boolean filterStaticAfterInstance,
boolean showInstanceInStaticContext) {
this.checkAccess = checkAccess;
this.filterStaticAfterInstance = filterStaticAfterInstance;
this.showInstanceInStaticContext = showInstanceInStaticContext;
}
public Options withCheckAccess(boolean checkAccess) {
return new Options(checkAccess, filterStaticAfterInstance, showInstanceInStaticContext);
}
public Options withFilterStaticAfterInstance(boolean filterStaticAfterInstance) {
return new Options(checkAccess, filterStaticAfterInstance, showInstanceInStaticContext);
}
public Options withShowInstanceInStaticContext(boolean showInstanceInStaticContext) {
return new Options(checkAccess, filterStaticAfterInstance, showInstanceInStaticContext);
}
}
private enum StaticProblem {
none,
staticAfterInstance,
instanceAfterStatic
}
}
| 20,256 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CompletionElement.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/psi/scope/CompletionElement.java | package com.tyron.completion.psi.scope;
import com.tyron.completion.psi.util.CompletionUtilCoreImpl;
import java.util.Arrays;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.com.intellij.openapi.util.Comparing;
import org.jetbrains.kotlin.com.intellij.openapi.util.Trinity;
import org.jetbrains.kotlin.com.intellij.psi.PsiClass;
import org.jetbrains.kotlin.com.intellij.psi.PsiClassType;
import org.jetbrains.kotlin.com.intellij.psi.PsiElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiKeyword;
import org.jetbrains.kotlin.com.intellij.psi.PsiMethod;
import org.jetbrains.kotlin.com.intellij.psi.PsiMethodReferenceType;
import org.jetbrains.kotlin.com.intellij.psi.PsiModifier;
import org.jetbrains.kotlin.com.intellij.psi.PsiPackage;
import org.jetbrains.kotlin.com.intellij.psi.PsiSubstitutor;
import org.jetbrains.kotlin.com.intellij.psi.PsiType;
import org.jetbrains.kotlin.com.intellij.psi.PsiVariable;
import org.jetbrains.kotlin.com.intellij.psi.util.MethodSignature;
import org.jetbrains.kotlin.com.intellij.psi.util.MethodSignatureUtil;
import org.jetbrains.kotlin.com.intellij.psi.util.TypeConversionUtil;
public final class CompletionElement {
private final Object myElement;
private final PsiSubstitutor mySubstitutor;
private final Object myEqualityObject;
private final String myQualifierText;
private final @Nullable PsiType myMethodRefType;
public CompletionElement(Object element, PsiSubstitutor substitutor) {
this(element, substitutor, "", null);
}
CompletionElement(
Object element,
PsiSubstitutor substitutor,
@NotNull String qualifierText,
@Nullable PsiType methodRefType) {
myElement = element;
mySubstitutor = substitutor;
myQualifierText = qualifierText;
myMethodRefType = methodRefType;
myEqualityObject = getUniqueId();
}
@NotNull
public String getQualifierText() {
return myQualifierText;
}
public PsiSubstitutor getSubstitutor() {
return mySubstitutor;
}
public Object getElement() {
return myElement;
}
@Nullable
private Object getUniqueId() {
if (myElement instanceof PsiClass) {
String qName = ((PsiClass) myElement).getQualifiedName();
return qName == null ? ((PsiClass) myElement).getName() : qName;
}
if (myElement instanceof PsiPackage) {
return ((PsiPackage) myElement).getQualifiedName();
}
if (myElement instanceof PsiMethod) {
if (myMethodRefType != null) {
return ((PsiMethod) myElement).isConstructor()
? PsiKeyword.NEW
: ((PsiMethod) myElement).getName();
}
return Trinity.create(
((PsiMethod) myElement).getName(),
Arrays.asList(
MethodSignatureUtil.calcErasedParameterTypes(
((PsiMethod) myElement).getSignature(mySubstitutor))),
myQualifierText);
}
if (myElement instanceof PsiVariable) {
return CompletionUtilCoreImpl.getOriginalOrSelf((PsiElement) myElement);
}
return null;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof CompletionElement)) return false;
Object thatObj = ((CompletionElement) obj).myEqualityObject;
if (myEqualityObject instanceof MethodSignature) {
return thatObj instanceof MethodSignature
&& MethodSignatureUtil.areSignaturesErasureEqual(
(MethodSignature) myEqualityObject, (MethodSignature) thatObj);
}
return Comparing.equal(myEqualityObject, thatObj);
}
@Override
public int hashCode() {
if (myEqualityObject instanceof MethodSignature) {
return myEqualityObject.hashCode();
}
return myEqualityObject != null ? myEqualityObject.hashCode() : 0;
}
@Nullable
public PsiType getMethodRefType() {
return myMethodRefType;
}
public boolean isMoreSpecificThan(@NotNull CompletionElement another) {
Object anotherElement = another.getElement();
if (!(anotherElement instanceof PsiMethod && myElement instanceof PsiMethod)) return false;
if (another.myMethodRefType instanceof PsiMethodReferenceType
&& myMethodRefType instanceof PsiClassType) {
return true;
}
if (anotherElement != myElement
&& ((PsiMethod) myElement).hasModifierProperty(PsiModifier.ABSTRACT)
&& !((PsiMethod) anotherElement).hasModifierProperty(PsiModifier.ABSTRACT)) {
return false;
}
PsiType prevType =
TypeConversionUtil.erasure(
another.getSubstitutor().substitute(((PsiMethod) anotherElement).getReturnType()));
PsiType candidateType = mySubstitutor.substitute(((PsiMethod) myElement).getReturnType());
return prevType != null
&& candidateType != null
&& !prevType.equals(candidateType)
&& prevType.isAssignableFrom(candidateType);
}
@Override
public String toString() {
return "CompletionElement{"
+ "myElement="
+ myElement
+ ", mySubstitutor="
+ mySubstitutor
+ ", myEqualityObject="
+ myEqualityObject
+ ", myQualifierText='"
+ myQualifierText
+ '\''
+ ", myMethodRefType="
+ myMethodRefType
+ '}';
}
}
| 5,278 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaKeywordCompletion.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/psi/completion/JavaKeywordCompletion.java | package com.tyron.completion.psi.completion;
import static com.tyron.completion.java.patterns.PsiElementPatterns.insideStarting;
import static org.jetbrains.kotlin.com.intellij.patterns.PsiJavaPatterns.psiElement;
import static org.jetbrains.kotlin.com.intellij.patterns.PsiJavaPatterns.string;
import static org.jetbrains.kotlin.com.intellij.patterns.StandardPatterns.or;
import com.tyron.completion.java.patterns.PsiAnnotationPattern;
import com.tyron.completion.java.patterns.PsiElementPatterns;
import com.tyron.completion.java.util.CompletionItemFactory;
import com.tyron.completion.model.CompletionList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.patterns.ElementPattern;
import org.jetbrains.kotlin.com.intellij.patterns.PatternCondition;
import org.jetbrains.kotlin.com.intellij.patterns.PsiJavaPatterns;
import org.jetbrains.kotlin.com.intellij.patterns.StandardPatterns;
import org.jetbrains.kotlin.com.intellij.psi.JavaCodeFragment;
import org.jetbrains.kotlin.com.intellij.psi.PsiAnnotation;
import org.jetbrains.kotlin.com.intellij.psi.PsiAnnotationParameterList;
import org.jetbrains.kotlin.com.intellij.psi.PsiClass;
import org.jetbrains.kotlin.com.intellij.psi.PsiClassObjectAccessExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiClassType;
import org.jetbrains.kotlin.com.intellij.psi.PsiCodeBlock;
import org.jetbrains.kotlin.com.intellij.psi.PsiCodeFragment;
import org.jetbrains.kotlin.com.intellij.psi.PsiComment;
import org.jetbrains.kotlin.com.intellij.psi.PsiConditionalExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiDeclarationStatement;
import org.jetbrains.kotlin.com.intellij.psi.PsiElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiErrorElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiExpressionCodeFragment;
import org.jetbrains.kotlin.com.intellij.psi.PsiExpressionList;
import org.jetbrains.kotlin.com.intellij.psi.PsiExpressionStatement;
import org.jetbrains.kotlin.com.intellij.psi.PsiFile;
import org.jetbrains.kotlin.com.intellij.psi.PsiForStatement;
import org.jetbrains.kotlin.com.intellij.psi.PsiIdentifier;
import org.jetbrains.kotlin.com.intellij.psi.PsiIfStatement;
import org.jetbrains.kotlin.com.intellij.psi.PsiJavaCodeReferenceCodeFragment;
import org.jetbrains.kotlin.com.intellij.psi.PsiJavaModule;
import org.jetbrains.kotlin.com.intellij.psi.PsiKeyword;
import org.jetbrains.kotlin.com.intellij.psi.PsiLiteralExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiLocalVariable;
import org.jetbrains.kotlin.com.intellij.psi.PsiMember;
import org.jetbrains.kotlin.com.intellij.psi.PsiMethod;
import org.jetbrains.kotlin.com.intellij.psi.PsiModifier;
import org.jetbrains.kotlin.com.intellij.psi.PsiModifierList;
import org.jetbrains.kotlin.com.intellij.psi.PsiParameter;
import org.jetbrains.kotlin.com.intellij.psi.PsiParameterList;
import org.jetbrains.kotlin.com.intellij.psi.PsiRecordHeader;
import org.jetbrains.kotlin.com.intellij.psi.PsiReferenceExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiStatement;
import org.jetbrains.kotlin.com.intellij.psi.PsiType;
import org.jetbrains.kotlin.com.intellij.psi.PsiTypeCastExpression;
import org.jetbrains.kotlin.com.intellij.psi.PsiTypeCodeFragment;
import org.jetbrains.kotlin.com.intellij.psi.PsiUnaryExpression;
import org.jetbrains.kotlin.com.intellij.psi.javadoc.PsiDocComment;
import org.jetbrains.kotlin.com.intellij.psi.templateLanguages.OuterLanguageElement;
import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.kotlin.com.intellij.psi.util.PsiUtil;
import org.jetbrains.kotlin.com.intellij.util.ProcessingContext;
import org.jetbrains.kotlin.com.intellij.util.containers.ContainerUtil;
public class JavaKeywordCompletion {
public static final ElementPattern<PsiElement> AFTER_DOT =
psiElement().afterLeaf(psiElement().withText(StandardPatterns.string().oneOf(".")));
static final ElementPattern<PsiElement> VARIABLE_AFTER_FINAL =
psiElement()
.afterLeaf(psiElement().withText(StandardPatterns.string().oneOf(PsiKeyword.FINAL)))
.inside(psiElement(PsiDeclarationStatement.class));
private static boolean isStatementCodeFragment(PsiFile file) {
return file instanceof JavaCodeFragment
&& !(file instanceof PsiExpressionCodeFragment
|| file instanceof PsiJavaCodeReferenceCodeFragment
|| file instanceof PsiTypeCodeFragment);
}
static boolean isEndOfBlock(@NotNull PsiElement element) {
PsiElement prev = prevSignificantLeaf(element);
if (prev == null) {
PsiFile file = element.getContainingFile();
return !(file instanceof PsiCodeFragment) || isStatementCodeFragment(file);
}
if (psiElement().inside(PsiAnnotationPattern.PSI_ANNOTATION_PATTERN).accepts(prev)) {
return false;
}
if (prev instanceof OuterLanguageElement) {
return true;
}
if (psiElement().withText(string().oneOf("{", "}", ";", ":", "else")).accepts(prev)) {
return true;
}
if (prev.textMatches(")")) {
PsiElement parent = prev.getParent();
if (parent instanceof PsiParameterList) {
return PsiTreeUtil.getParentOfType(
PsiTreeUtil.prevVisibleLeaf(element), PsiDocComment.class)
!= null;
}
return !(parent instanceof PsiExpressionList
|| parent instanceof PsiTypeCastExpression
|| parent instanceof PsiRecordHeader);
}
return false;
}
static final Set<String> PRIMITIVE_TYPES =
ContainerUtil.newLinkedHashSet(
Arrays.asList(
PsiKeyword.SHORT,
PsiKeyword.BOOLEAN,
PsiKeyword.DOUBLE,
PsiKeyword.LONG,
PsiKeyword.INT,
PsiKeyword.FLOAT,
PsiKeyword.CHAR,
PsiKeyword.BYTE));
private final PsiElement myPosition;
private final CompletionList.Builder myBuilder;
public JavaKeywordCompletion(PsiElement position, CompletionList.Builder builder) {
myPosition = position;
myBuilder = builder;
addKeywords();
}
private static PsiElement prevSignificantLeaf(PsiElement position) {
return position;
}
public void addKeywords() {
if (PsiTreeUtil.getNonStrictParentOfType(
myPosition, PsiLiteralExpression.class, PsiComment.class)
!= null) {
return;
}
if (psiElement()
.afterLeaf(psiElement().withText(StandardPatterns.string().oneOf("::")))
.accepts(myPosition)) {
return;
}
PsiFile file = myPosition.getContainingFile();
if (PsiJavaModule.MODULE_INFO_FILE.equals(file.getName())
&& PsiUtil.isLanguageLevel9OrHigher(file)) {
// addModuleKeywords();
return;
}
myBuilder.addItem(CompletionItemFactory.keyword(PsiKeyword.FINAL));
boolean statementPosition = isStatementPosition(myPosition);
if (statementPosition) {}
addExpressionKeywords(statementPosition);
// addThisSuper();
addInstanceOf();
addClassKeywords();
}
private void addClassKeywords() {
if (isSuitableForClass(myPosition)) {
for (String modifier : PsiModifier.MODIFIERS) {
myBuilder.addItem(CompletionItemFactory.keyword(modifier));
}
if (insideStarting(or(psiElement(PsiLocalVariable.class), psiElement(PsiExpression.class)))
.accepts(myPosition)) {
myBuilder.addItem(CompletionItemFactory.keyword(PsiKeyword.CLASS));
myBuilder.addItem(CompletionItemFactory.item("abstract class"));
}
if (PsiTreeUtil.getParentOfType(myPosition, PsiExpression.class, true, PsiMember.class)
== null
&& PsiTreeUtil.getParentOfType(myPosition, PsiCodeBlock.class, true, PsiMember.class)
== null) {
List<String> keywords = new ArrayList<>();
keywords.add(PsiKeyword.CLASS);
keywords.add(PsiKeyword.INTERFACE);
if (PsiUtil.isLanguageLevel5OrHigher(myPosition)) {
keywords.add(PsiKeyword.ENUM);
}
// TODO: recommend class declaration
for (String keyword : keywords) {
myBuilder.addItem(CompletionItemFactory.keyword(keyword));
}
}
}
}
private void addPrimitiveTypes() {}
private void addExpressionKeywords(boolean statementPosition) {
if (isExpressionPosition(myPosition)) {
PsiElement parent = myPosition.getParent();
PsiElement grandParent = parent == null ? null : parent.getParent();
boolean allowExprKeywords =
!(grandParent instanceof PsiExpressionStatement)
&& !(grandParent instanceof PsiUnaryExpression);
if (PsiTreeUtil.getParentOfType(myPosition, PsiAnnotation.class) == null) {
if (!statementPosition) {
myBuilder.addItem(CompletionItemFactory.keyword(PsiKeyword.NEW));
}
if (allowExprKeywords) {
myBuilder.addItem(CompletionItemFactory.keyword(PsiKeyword.NULL));
}
}
if (allowExprKeywords && mayExpectBoolean()) {
myBuilder.addItem(CompletionItemFactory.keyword(PsiKeyword.TRUE));
myBuilder.addItem(CompletionItemFactory.keyword(PsiKeyword.FALSE));
}
}
if (isQualifiedNewContext()) {
myBuilder.addItem(CompletionItemFactory.keyword(PsiKeyword.NEW));
}
}
private boolean isQualifiedNewContext() {
if (myPosition.getParent() instanceof PsiReferenceExpression) {
PsiExpression qualifier =
((PsiReferenceExpression) myPosition.getParent()).getQualifierExpression();
PsiClass qualifierClass =
PsiUtil.resolveClassInClassTypeOnly(qualifier == null ? null : qualifier.getType());
return qualifierClass != null
&& ContainerUtil.exists(
qualifierClass.getAllInnerClasses(),
inner -> canBeCreatedInQualifiedNew(qualifierClass, inner));
}
return false;
}
private boolean canBeCreatedInQualifiedNew(PsiClass outer, PsiClass inner) {
PsiMethod[] constructors = inner.getConstructors();
return !inner.hasModifierProperty(PsiModifier.STATIC)
&& PsiUtil.isAccessible(inner, myPosition, outer)
&& (constructors.length == 0
|| ContainerUtil.exists(constructors, c -> PsiUtil.isAccessible(c, myPosition, outer)));
}
private static boolean mayExpectBoolean() {
return false;
}
private static boolean isExpressionPosition(PsiElement position) {
if (insideStarting(psiElement(PsiClassObjectAccessExpression.class)).accepts(position))
return true;
PsiElement parent = position.getParent();
if (!(parent instanceof PsiReferenceExpression)
|| ((PsiReferenceExpression) parent).isQualified()
// JavaCompletionContributor.IN_SWITCH_LABEL.accepts(position)) {
) {
return false;
}
if (parent.getParent() instanceof PsiExpressionStatement) {
PsiElement previous = PsiTreeUtil.skipWhitespacesBackward(parent.getParent());
return previous == null || !(previous.getLastChild() instanceof PsiErrorElement);
}
return true;
}
public static boolean isInstanceofPlace(PsiElement position) {
PsiElement prev = PsiTreeUtil.prevVisibleLeaf(position);
if (prev == null) return false;
PsiElement expr = PsiTreeUtil.getParentOfType(prev, PsiExpression.class);
if (expr != null
&& expr.getTextRange().getEndOffset() == prev.getTextRange().getEndOffset()
&& PsiTreeUtil.getParentOfType(expr, PsiAnnotation.class) == null) {
return true;
}
if (position instanceof PsiIdentifier && position.getParent() instanceof PsiLocalVariable) {
PsiType type = ((PsiLocalVariable) position.getParent()).getType();
if (type instanceof PsiClassType && ((PsiClassType) type).resolve() == null) {
PsiElement grandParent = position.getParent().getParent();
return !(grandParent instanceof PsiDeclarationStatement)
|| !(grandParent.getParent() instanceof PsiForStatement)
|| ((PsiForStatement) grandParent.getParent()).getInitialization() != grandParent;
}
}
return false;
}
private void addInstanceOf() {
if (isInstanceofPlace(myPosition)) {
myBuilder.addItem(CompletionItemFactory.keyword(PsiKeyword.INSTANCEOF));
}
}
public static boolean isSuitableForClass(PsiElement position) {
if (psiElement().afterLeaf(psiElement().withText("@")).accepts(position)
|| PsiTreeUtil.getNonStrictParentOfType(
position,
PsiLiteralExpression.class,
PsiComment.class,
PsiExpressionCodeFragment.class)
!= null) {
return false;
}
PsiElement prev = prevSignificantLeaf(position);
if (prev == null) {
return true;
}
if (psiElement()
.without(
new PatternCondition<PsiElement>("withoutText") {
@Override
public boolean accepts(
@NotNull PsiElement psiElement, ProcessingContext processingContext) {
return psiElement.getText().equals(".");
}
})
.inside(
psiElement(PsiModifierList.class)
.withParent(
PsiJavaPatterns.not(psiElement(PsiParameter.class))
.andNot(psiElement(PsiParameterList.class))))
.accepts(prev)
&& (!psiElement().inside(psiElement(PsiAnnotationParameterList.class)).accepts(prev)
|| prev.textMatches(")"))) {
return true;
}
if (PsiElementPatterns.withParents(PsiErrorElement.class, PsiFile.class).accepts(position)) {
return true;
}
return isEndOfBlock(position);
}
private static boolean isForLoopMachinery(PsiElement position) {
PsiStatement statement = PsiTreeUtil.getParentOfType(position, PsiStatement.class);
if (statement == null) return false;
return statement instanceof PsiForStatement
|| statement.getParent() instanceof PsiForStatement
&& statement != ((PsiForStatement) statement.getParent()).getBody();
}
private static boolean isStatementPosition(PsiElement position) {
if (psiElement()
.withSuperParent(2, psiElement(PsiConditionalExpression.class))
.andNot(insideStarting(psiElement(PsiConditionalExpression.class)))
.accepts(position)) {
return false;
}
if (isEndOfBlock(position)
&& PsiTreeUtil.getParentOfType(position, PsiCodeBlock.class, true, PsiMember.class)
!= null) {
return !isForLoopMachinery(position);
}
if (PsiElementPatterns.withParents(
PsiReferenceExpression.class, PsiExpressionStatement.class, PsiIfStatement.class)
.andNot(psiElement().afterLeaf(psiElement().withText(".")))
.accepts(position)) {
PsiElement stmt = position.getParent().getParent();
PsiIfStatement ifStatement = (PsiIfStatement) stmt.getParent();
return ifStatement.getElseBranch() == stmt || ifStatement.getThenBranch() == stmt;
}
return false;
}
}
| 15,295 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
CompletionUtilCoreImpl.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/psi/util/CompletionUtilCoreImpl.java | package com.tyron.completion.psi.util;
import androidx.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.com.intellij.injected.editor.DocumentWindow;
import org.jetbrains.kotlin.com.intellij.openapi.editor.Document;
import org.jetbrains.kotlin.com.intellij.openapi.util.TextRange;
import org.jetbrains.kotlin.com.intellij.psi.PsiCompiledFile;
import org.jetbrains.kotlin.com.intellij.psi.PsiElement;
import org.jetbrains.kotlin.com.intellij.psi.PsiFile;
import org.jetbrains.kotlin.com.intellij.psi.impl.light.LightElement;
import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil;
public final class CompletionUtilCoreImpl {
@Nullable
public static <T extends PsiElement> T getOriginalElement(@NotNull T psi) {
return getOriginalElement(psi, psi.getContainingFile());
}
@Nullable
public static <T extends PsiElement> T getOriginalElement(
@NotNull T psi, PsiFile containingFile) {
if (containingFile == null || psi instanceof LightElement) return psi;
PsiFile originalFile = containingFile.getOriginalFile();
if (psi == containingFile && psi.getClass().isInstance(originalFile)) {
//noinspection unchecked
return (T) originalFile;
}
TextRange range;
if (originalFile != containingFile
&& !(originalFile instanceof PsiCompiledFile)
&& (range = psi.getTextRange()) != null) {
Integer start = range.getStartOffset();
Integer end = range.getEndOffset();
Document document = containingFile.getViewProvider().getDocument();
if (document != null) {
Document hostDocument =
document instanceof DocumentWindow
? ((DocumentWindow) document).getDelegate()
: document;
OffsetTranslator translator = hostDocument.getUserData(OffsetTranslator.RANGE_TRANSLATION);
if (translator != null) {
if (document instanceof DocumentWindow) {
TextRange translated =
((DocumentWindow) document).injectedToHost(new TextRange(start, end));
start = translated.getStartOffset();
end = translated.getEndOffset();
}
start = translator.translateOffset(start);
end = translator.translateOffset(end);
if (start == null || end == null) {
return null;
}
if (document instanceof DocumentWindow) {
start = ((DocumentWindow) document).hostToInjected(start);
end = ((DocumentWindow) document).hostToInjected(end);
}
}
}
//noinspection unchecked
return (T) PsiTreeUtil.findElementOfClassAtRange(originalFile, start, end, psi.getClass());
}
return psi;
}
@NotNull
public static <T extends PsiElement> T getOriginalOrSelf(@NotNull T psi) {
final T element = getOriginalElement(psi);
return element == null ? psi : element;
}
}
| 2,921 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
OffsetTranslator.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/completion/psi/util/OffsetTranslator.java | package com.tyron.completion.psi.util;
import java.util.ArrayList;
import java.util.List;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.com.intellij.openapi.Disposable;
import org.jetbrains.kotlin.com.intellij.openapi.editor.Document;
import org.jetbrains.kotlin.com.intellij.openapi.editor.event.DocumentEvent;
import org.jetbrains.kotlin.com.intellij.openapi.editor.event.DocumentListener;
import org.jetbrains.kotlin.com.intellij.openapi.editor.impl.event.DocumentEventImpl;
import org.jetbrains.kotlin.com.intellij.openapi.util.Disposer;
import org.jetbrains.kotlin.com.intellij.openapi.util.Key;
import org.jetbrains.kotlin.com.intellij.psi.PsiFile;
import org.jetbrains.kotlin.com.intellij.psi.util.PsiModificationTracker;
/**
* @author peter
*/
public class OffsetTranslator implements Disposable {
static final Key<OffsetTranslator> RANGE_TRANSLATION = Key.create("completion.rangeTranslation");
private final PsiFile myOriginalFile;
private final Document myCopyDocument;
private final List<DocumentEvent> myTranslation = new ArrayList<>();
public OffsetTranslator(
Document originalDocument,
PsiFile originalFile,
Document copyDocument,
int start,
int end,
String replacement) {
myOriginalFile = originalFile;
myCopyDocument = copyDocument;
myCopyDocument.putUserData(RANGE_TRANSLATION, this);
myTranslation.add(
new DocumentEventImpl(
copyDocument,
start,
originalDocument.getImmutableCharSequence().subSequence(start, end),
replacement,
0,
false,
start,
end - start,
start));
Disposer.register(originalFile.getProject(), this);
List<DocumentEvent> sinceCommit = new ArrayList<>();
originalDocument.addDocumentListener(
new DocumentListener() {
@Override
public void documentChanged(@NotNull DocumentEvent e) {
if (isUpToDate()) {
DocumentEventImpl inverse =
new DocumentEventImpl(
originalDocument,
e.getOffset(),
e.getNewFragment(),
e.getOldFragment(),
0,
false,
e.getOffset(),
e.getNewFragment().length(),
e.getOffset());
sinceCommit.add(inverse);
}
}
});
originalFile
.getProject()
.getMessageBus()
.connect(this)
.subscribe(
PsiModificationTracker.TOPIC,
new PsiModificationTracker.Listener() {
final long lastModCount = originalFile.getViewProvider().getModificationStamp();
@Override
public void modificationCountChanged() {
if (isUpToDate()
&& lastModCount != originalFile.getViewProvider().getModificationStamp()) {
myTranslation.addAll(sinceCommit);
sinceCommit.clear();
}
}
});
}
private boolean isUpToDate() {
return this == myCopyDocument.getUserData(RANGE_TRANSLATION) && myOriginalFile.isValid();
}
@Override
public void dispose() {
if (isUpToDate()) {
myCopyDocument.putUserData(RANGE_TRANSLATION, null);
}
}
@Nullable
Integer translateOffset(Integer offset) {
for (DocumentEvent event : myTranslation) {
offset = translateOffset(offset, event);
if (offset == null) {
return null;
}
}
return offset;
}
@Nullable
private static Integer translateOffset(int offset, DocumentEvent event) {
if (event.getOffset() < offset && offset < event.getOffset() + event.getNewLength()) {
if (event.getOldLength() == 0) {
return event.getOffset();
}
return null;
}
return offset <= event.getOffset()
? offset
: offset - event.getNewLength() + event.getOldLength();
}
}
| 4,116 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaExpandSelectionProvider.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/selection/java/JavaExpandSelectionProvider.java | package com.tyron.selection.java;
import com.google.common.collect.Range;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import com.sun.source.util.Trees;
import com.tyron.builder.model.SourceFileObject;
import com.tyron.builder.project.Project;
import com.tyron.completion.java.action.FindCurrentPath;
import com.tyron.completion.java.compiler.Parser;
import com.tyron.editor.Editor;
import com.tyron.editor.selection.ExpandSelectionProvider;
import java.io.File;
import java.time.Instant;
import org.jetbrains.annotations.Nullable;
public class JavaExpandSelectionProvider extends ExpandSelectionProvider {
@Override
public @Nullable Range<Integer> expandSelection(Editor editor) {
Project project = editor.getProject();
if (project == null) {
return null;
}
File file = editor.getCurrentFile();
SourceFileObject fileObject =
new SourceFileObject(file.toPath(), editor.getContent().toString(), Instant.now());
Parser parser = Parser.parseJavaFileObject(project, fileObject);
FindCurrentPath findCurrentPath = new FindCurrentPath(parser.task);
int cursorStart = editor.getCaret().getStart();
int cursorEnd = editor.getCaret().getEnd();
SourcePositions positions = Trees.instance(parser.task).getSourcePositions();
TreePath path = findCurrentPath.scan(parser.root, cursorStart, cursorEnd);
if (path == null) {
return null;
}
long afterStart;
long afterEnd;
long currentStart = positions.getStartPosition(parser.root, path.getLeaf());
long currentEnd = positions.getEndPosition(parser.root, path.getLeaf());
if (currentStart == cursorStart && currentEnd == cursorEnd) {
TreePath parentPath = path.getParentPath();
afterStart = positions.getStartPosition(parser.root, parentPath.getLeaf());
afterEnd = positions.getEndPosition(parser.root, parentPath.getLeaf());
} else {
afterStart = currentStart;
afterEnd = currentEnd;
}
return Range.closed((int) afterStart, (int) afterEnd);
}
}
| 2,063 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaLanguage.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/language/java/JavaLanguage.java | package com.tyron.language.java;
import com.tyron.language.api.Language;
import org.jetbrains.annotations.NotNull;
public class JavaLanguage extends Language {
public static final JavaLanguage INSTANCE = new JavaLanguage("JAVA");
protected JavaLanguage(@NotNull String id) {
super(id);
}
}
| 304 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
JavaFileType.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/com/tyron/language/java/JavaFileType.java | package com.tyron.language.java;
import android.graphics.drawable.Drawable;
import com.tyron.language.api.Language;
import com.tyron.language.fileTypes.LanguageFileType;
import org.jetbrains.annotations.NotNull;
public class JavaFileType extends LanguageFileType {
public static final JavaFileType INSTANCE = new JavaFileType(JavaLanguage.INSTANCE);
protected JavaFileType(@NotNull Language instance) {
super(instance);
}
@Override
public @NotNull String getName() {
return "Java";
}
@Override
public @NotNull String getDescription() {
return "Java programming language file";
}
@Override
public @NotNull String getDefaultExtension() {
return "java";
}
@Override
public @NotNull Drawable getIcon() {
return null;
}
}
| 775 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
SwingUtilities.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/java-completion/src/main/java/javax/swing/SwingUtilities.java | package javax.swing;
import android.os.Looper;
public class SwingUtilities {
public static boolean isEventDispatchThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
}
| 192 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AppCompatModule.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/AppCompatModule.java | package com.tyron.layout.appcompat;
import com.flipkart.android.proteus.ProteusBuilder;
import com.tyron.layout.appcompat.widget.AppBarLayoutParser;
import com.tyron.layout.appcompat.widget.AppCompatButtonParser;
import com.tyron.layout.appcompat.widget.AppCompatEditTextParser;
import com.tyron.layout.appcompat.widget.AppCompatToolbarParser;
import com.tyron.layout.appcompat.widget.CollapsingToolbarLayoutParser;
import com.tyron.layout.appcompat.widget.CoordinatorLayoutParser;
import com.tyron.layout.appcompat.widget.FloatingActionButtonParser;
import com.tyron.layout.appcompat.widget.MaterialButtonParser;
import com.tyron.layout.appcompat.widget.MaterialCardViewParser;
import com.tyron.layout.appcompat.widget.RecyclerViewParser;
import com.tyron.layout.appcompat.widget.TextInputEditTextParser;
import com.tyron.layout.appcompat.widget.TextInputLayoutParser;
import com.tyron.layout.appcompat.widget.VisibilityAwareImageButtonParser;
public class AppCompatModule implements ProteusBuilder.Module {
private AppCompatModule() {}
public static AppCompatModule create() {
return new AppCompatModule();
}
@Override
public void registerWith(ProteusBuilder builder) {
builder.register(new AppBarLayoutParser<>());
builder.register(new CollapsingToolbarLayoutParser<>());
builder.register(new CoordinatorLayoutParser<>());
builder.register(new MaterialCardViewParser<>());
builder.register(new VisibilityAwareImageButtonParser<>());
builder.register(new FloatingActionButtonParser<>());
builder.register(new RecyclerViewParser<>());
builder.register(new AppCompatButtonParser<>());
builder.register(new MaterialButtonParser<>());
builder.register(new AppCompatToolbarParser<>());
builder.register(new TextInputLayoutParser());
builder.register(new AppCompatEditTextParser());
builder.register(new TextInputEditTextParser());
AppCompatModuleAttributeHelper.register(builder);
}
}
| 1,959 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AppCompatModuleAttributeHelper.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/AppCompatModuleAttributeHelper.java | package com.tyron.layout.appcompat;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.flipkart.android.proteus.ProteusBuilder;
import com.flipkart.android.proteus.ProteusConstants;
import com.flipkart.android.proteus.parser.ParseHelper;
import com.flipkart.android.proteus.processor.AttributeProcessor;
import com.flipkart.android.proteus.processor.GravityAttributeProcessor;
import com.flipkart.android.proteus.toolbox.Attributes;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class AppCompatModuleAttributeHelper {
public static <V extends View> void register(ProteusBuilder builder) {
Map<String, AttributeProcessor> processors = new LinkedHashMap<>(4);
processors.put(
Attributes.View.LayoutGravity,
new GravityAttributeProcessor<V>() {
@Override
public void setGravity(V view, @Gravity int gravity) {
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
if (layoutParams instanceof LinearLayout.LayoutParams) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) layoutParams;
params.gravity = gravity;
view.setLayoutParams(layoutParams);
} else if (layoutParams instanceof FrameLayout.LayoutParams) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) layoutParams;
params.gravity = gravity;
view.setLayoutParams(layoutParams);
} else if (layoutParams instanceof CoordinatorLayout.LayoutParams) {
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) layoutParams;
params.gravity = gravity;
view.setLayoutParams(layoutParams);
}
}
});
builder.register("View", processors);
}
public static class AppBarLayoutParamsHelper {
private static final String SCROLL_FLAG_SCROLL = "scroll";
private static final String SCROLL_FLAG_EXIT_UNTIL_COLLAPSED = "exitUntilCollapsed";
private static final String SCROLL_FLAG_ENTER_ALWAYS = "enterAlways";
private static final String SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED = "enterAlwaysCollapsed";
private static final String SCROLL_FLAG_SNAP = "snap";
private static final HashMap<String, Integer> sScrollFlagMap = new HashMap<>();
private static boolean sInitialized = false;
private static void initialize() {
if (!sInitialized) {
sInitialized = true;
sScrollFlagMap.put(SCROLL_FLAG_SCROLL, AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL);
sScrollFlagMap.put(
SCROLL_FLAG_EXIT_UNTIL_COLLAPSED,
AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED);
sScrollFlagMap.put(
SCROLL_FLAG_ENTER_ALWAYS, AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
sScrollFlagMap.put(
SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED,
AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED);
sScrollFlagMap.put(SCROLL_FLAG_SNAP, AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP);
}
}
private static AppBarLayout.LayoutParams getLayoutParams(View v) {
initialize();
AppBarLayout.LayoutParams result = null;
ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
if (layoutParams instanceof AppBarLayout.LayoutParams) {
result = (AppBarLayout.LayoutParams) layoutParams;
}
return result;
}
public static void setLayoutScrollFlags(View v, String scrollFlags) {
AppBarLayout.LayoutParams layoutParams = getLayoutParams(v);
if (null != layoutParams && !TextUtils.isEmpty(scrollFlags)) {
String[] listFlags = scrollFlags.split("\\|");
int scrollFlag = 0;
for (String flag : listFlags) {
Integer flags = sScrollFlagMap.get(flag.trim());
if (null != flags) {
scrollFlag |= flags;
}
}
if (scrollFlag != 0) {
layoutParams.setScrollFlags(scrollFlag);
}
}
}
}
public static class CollapsingToolbarLayoutParamsHelper {
private static final String COLLAPSE_MODE_OFF = "off";
private static final String COLLAPSE_MODE_PARALLAX = "parallax";
private static final String COLLAPSE_MODE_PIN = "pin";
private static final HashMap<String, Integer> sCollapseModeMap = new HashMap<>();
private static boolean sInitialized = false;
private static void initialize() {
if (!sInitialized) {
sInitialized = true;
sCollapseModeMap.put(
COLLAPSE_MODE_OFF, CollapsingToolbarLayout.LayoutParams.COLLAPSE_MODE_OFF);
sCollapseModeMap.put(
COLLAPSE_MODE_PARALLAX, CollapsingToolbarLayout.LayoutParams.COLLAPSE_MODE_PARALLAX);
sCollapseModeMap.put(
COLLAPSE_MODE_PIN, CollapsingToolbarLayout.LayoutParams.COLLAPSE_MODE_PIN);
}
}
private static CollapsingToolbarLayout.LayoutParams getLayoutParams(View v) {
initialize();
CollapsingToolbarLayout.LayoutParams result = null;
ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
if (layoutParams instanceof CollapsingToolbarLayout.LayoutParams) {
result = (CollapsingToolbarLayout.LayoutParams) layoutParams;
}
return result;
}
public static void setCollapseMode(View v, String mode) {
CollapsingToolbarLayout.LayoutParams layoutParams = getLayoutParams(v);
if (null != layoutParams) {
Integer collapseMode = sCollapseModeMap.get(mode);
if (null != collapseMode) {
layoutParams.setCollapseMode(collapseMode);
}
}
}
public static void setParallaxMultiplier(View v, String multiplier) {
CollapsingToolbarLayout.LayoutParams layoutParams = getLayoutParams(v);
if (null != layoutParams && !TextUtils.isEmpty(multiplier)) {
layoutParams.setParallaxMultiplier(ParseHelper.parseFloat(multiplier));
}
}
}
public static class CoordinatorLayoutParamsHelper {
private static final HashMap<String, Class<?>> sBehaviorMap = new HashMap<>();
private static CoordinatorLayout.LayoutParams getLayoutParams(View v) {
CoordinatorLayout.LayoutParams result = null;
ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
if (layoutParams instanceof CoordinatorLayout.LayoutParams) {
result = (CoordinatorLayout.LayoutParams) layoutParams;
}
return result;
}
public static void setLayoutBehavior(View v, String behavior) {
CoordinatorLayout.LayoutParams layoutParams = getLayoutParams(v);
if (null != layoutParams && !TextUtils.isEmpty(behavior)) {
//noinspection TryWithIdenticalCatches since there are min API requirements
try {
Class<?> clazz = sBehaviorMap.get(behavior);
if (null == clazz) {
clazz = Class.forName(behavior);
sBehaviorMap.put(behavior, clazz);
}
Object behaviorObj = clazz.newInstance();
if (behaviorObj instanceof CoordinatorLayout.Behavior) {
layoutParams.setBehavior((CoordinatorLayout.Behavior<?>) behaviorObj);
}
} catch (ClassNotFoundException e) {
if (ProteusConstants.isLoggingEnabled()) {
e.printStackTrace();
}
} catch (InstantiationException e) {
if (ProteusConstants.isLoggingEnabled()) {
e.printStackTrace();
}
} catch (IllegalAccessException e) {
if (ProteusConstants.isLoggingEnabled()) {
e.printStackTrace();
}
}
}
}
}
}
| 7,963 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusMaterialCardView.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusMaterialCardView.java | package com.tyron.layout.appcompat.view;
import android.content.Context;
import android.view.View;
import androidx.annotation.NonNull;
import com.flipkart.android.proteus.ProteusView;
import com.google.android.material.card.MaterialCardView;
public class ProteusMaterialCardView extends MaterialCardView implements ProteusView {
private Manager manager;
public ProteusMaterialCardView(Context context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 686 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusAppCompatToolbar.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusAppCompatToolbar.java | package com.tyron.layout.appcompat.view;
import android.content.Context;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import com.flipkart.android.proteus.ProteusView;
public class ProteusAppCompatToolbar extends Toolbar implements ProteusView {
private Manager manager;
public ProteusAppCompatToolbar(@NonNull Context context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 670 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusAppCompatEditText.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusAppCompatEditText.java | package com.tyron.layout.appcompat.view;
import android.content.Context;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatEditText;
import com.flipkart.android.proteus.ProteusView;
public class ProteusAppCompatEditText extends AppCompatEditText implements ProteusView {
private Manager manager;
public ProteusAppCompatEditText(@NonNull Context context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 692 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProetusVisibilityAwareImageButton.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProetusVisibilityAwareImageButton.java | package com.tyron.layout.appcompat.view;
import android.content.Context;
import android.view.View;
import androidx.annotation.NonNull;
import com.flipkart.android.proteus.ProteusView;
import com.google.android.material.internal.VisibilityAwareImageButton;
public class ProetusVisibilityAwareImageButton extends VisibilityAwareImageButton
implements ProteusView {
public ProetusVisibilityAwareImageButton(Context context) {
super(context);
}
private Manager manager;
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 734 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusAppCompatButton.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusAppCompatButton.java | package com.tyron.layout.appcompat.view;
import android.content.Context;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import com.flipkart.android.proteus.ProteusView;
public class ProteusAppCompatButton extends AppCompatButton implements ProteusView {
private Manager manager;
public ProteusAppCompatButton(@NonNull Context context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 684 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusRecyclerView.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusRecyclerView.java | package com.tyron.layout.appcompat.view;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.flipkart.android.proteus.ProteusContext;
import com.flipkart.android.proteus.ProteusView;
import com.flipkart.android.proteus.value.Layout;
import com.flipkart.android.proteus.value.ObjectValue;
import com.flipkart.android.proteus.view.UnknownView;
public class ProteusRecyclerView extends RecyclerView implements ProteusView {
private String mLayoutPreviewName;
private Manager manager;
private int itemCount = 10;
public ProteusRecyclerView(@NonNull Context context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
public void setListItem(String layoutName) {
mLayoutPreviewName = layoutName;
setLayoutManager(new LinearLayoutManager(getContext()));
setAdapter(new PreviewAdapter());
}
public class PreviewAdapter extends Adapter<PreviewAdapter.ViewHolder> {
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
FrameLayout frameLayout = new FrameLayout(parent.getContext());
return new ViewHolder(frameLayout);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {}
@Override
public int getItemCount() {
return itemCount;
}
private View getView(ProteusContext context) {
if (mLayoutPreviewName.equals(
manager.getDataContext().getData().getAsString("layout_name"))) {
return new UnknownView(context, "Unable to find layout: " + mLayoutPreviewName);
}
Layout layout = context.getLayout(mLayoutPreviewName);
if (layout == null) {
return new UnknownView(context, "Unable to find layout: " + mLayoutPreviewName);
}
return context.getInflater().inflate(layout, new ObjectValue()).getAsView();
}
private class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(@NonNull FrameLayout itemView) {
super(itemView);
ProteusContext context = manager.getContext();
itemView.addView(getView(context));
}
}
}
}
| 2,543 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusTextInputEditText.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusTextInputEditText.java | package com.tyron.layout.appcompat.view;
import android.content.Context;
import android.view.View;
import androidx.annotation.NonNull;
import com.flipkart.android.proteus.ProteusView;
import com.google.android.material.textfield.TextInputEditText;
public class ProteusTextInputEditText extends TextInputEditText implements ProteusView {
private Manager manager;
public ProteusTextInputEditText(@NonNull Context context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 704 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusNestedScrollView.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusNestedScrollView.java | package com.tyron.layout.appcompat.view;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import com.flipkart.android.proteus.ProteusView;
public class ProteusNestedScrollView extends NestedScrollView implements ProteusView {
private Manager manager;
public ProteusNestedScrollView(@NonNull Context context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
@Override
public void addView(View child, int width, int height) {
if (getChildCount() > 1) {
return;
}
super.addView(child, width, height);
}
@Override
public void addView(View child) {
if (getChildCount() > 1) {
return;
}
super.addView(child);
}
@Override
public void addView(View child, int index) {
if (getChildCount() > 1) {
return;
}
super.addView(child, index);
}
@Override
public void addView(View child, ViewGroup.LayoutParams params) {
if (getChildCount() > 1) {
return;
}
super.addView(child, params);
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if (getChildCount() > 1) {
return;
}
super.addView(child, index, params);
}
@Override
protected boolean addViewInLayout(View child, int index, ViewGroup.LayoutParams params) {
if (getChildCount() > 1) {
return false;
}
return super.addViewInLayout(child, index, params);
}
@Override
protected boolean addViewInLayout(
View child, int index, ViewGroup.LayoutParams params, boolean preventRequestLayout) {
if (getChildCount() > 1) {
return false;
}
return super.addViewInLayout(child, index, params, preventRequestLayout);
}
}
| 2,019 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusAppBarLayout.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusAppBarLayout.java | package com.tyron.layout.appcompat.view;
import android.view.View;
import androidx.annotation.NonNull;
import com.flipkart.android.proteus.ProteusContext;
import com.flipkart.android.proteus.ProteusView;
import com.google.android.material.appbar.AppBarLayout;
/**
* ProteusAppBarLayout
*
* @author adityasharat
*/
public class ProteusAppBarLayout extends AppBarLayout implements ProteusView {
private Manager manager;
public ProteusAppBarLayout(ProteusContext context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 757 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusCoordinatorLayout.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusCoordinatorLayout.java | package com.tyron.layout.appcompat.view;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.flipkart.android.proteus.ProteusContext;
import com.flipkart.android.proteus.ProteusView;
/**
* ProteusCoordinatorLayout
*
* @author adityasharat
*/
public class ProteusCoordinatorLayout extends CoordinatorLayout implements ProteusView {
private Manager manager;
public ProteusCoordinatorLayout(ProteusContext context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 781 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusCollapsingToolbarLayout.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusCollapsingToolbarLayout.java | package com.tyron.layout.appcompat.view;
import android.view.View;
import androidx.annotation.NonNull;
import com.flipkart.android.proteus.ProteusContext;
import com.flipkart.android.proteus.ProteusView;
import com.google.android.material.appbar.CollapsingToolbarLayout;
/**
* ProteusCollapsingToolbarLayout
*
* @author adityasharat
*/
public class ProteusCollapsingToolbarLayout extends CollapsingToolbarLayout implements ProteusView {
private Manager manager;
public ProteusCollapsingToolbarLayout(ProteusContext context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 812 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusFloatingActionButton.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusFloatingActionButton.java | package com.tyron.layout.appcompat.view;
import android.content.Context;
import android.view.View;
import androidx.annotation.NonNull;
import com.flipkart.android.proteus.ProteusView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class ProteusFloatingActionButton extends FloatingActionButton implements ProteusView {
private Manager manager;
public ProteusFloatingActionButton(@NonNull Context context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 727 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusMaterialButton.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusMaterialButton.java | package com.tyron.layout.appcompat.view;
import android.content.Context;
import android.view.View;
import androidx.annotation.NonNull;
import com.flipkart.android.proteus.ProteusView;
import com.google.android.material.button.MaterialButton;
public class ProteusMaterialButton extends MaterialButton implements ProteusView {
private Manager manager;
public ProteusMaterialButton(@NonNull Context context) {
super(context);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 689 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
ProteusTextInputLayout.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/view/ProteusTextInputLayout.java | package com.tyron.layout.appcompat.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.flipkart.android.proteus.ProteusView;
import com.google.android.material.textfield.TextInputLayout;
public class ProteusTextInputLayout extends TextInputLayout implements ProteusView {
private Manager manager;
public ProteusTextInputLayout(@NonNull Context context) {
super(context);
}
public ProteusTextInputLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ProteusTextInputLayout(
@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public Manager getViewManager() {
return manager;
}
@Override
public void setViewManager(@NonNull Manager manager) {
this.manager = manager;
}
@NonNull
@Override
public View getAsView() {
return this;
}
}
| 1,050 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
VisibilityAwareImageButtonParser.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/widget/VisibilityAwareImageButtonParser.java | package com.tyron.layout.appcompat.widget;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.flipkart.android.proteus.ProteusContext;
import com.flipkart.android.proteus.ProteusView;
import com.flipkart.android.proteus.ViewTypeParser;
import com.flipkart.android.proteus.value.Layout;
import com.flipkart.android.proteus.value.ObjectValue;
import com.google.android.material.internal.VisibilityAwareImageButton;
import com.tyron.layout.appcompat.view.ProetusVisibilityAwareImageButton;
public class VisibilityAwareImageButtonParser<V extends View> extends ViewTypeParser<V> {
@NonNull
@Override
public String getType() {
return VisibilityAwareImageButton.class.getName();
}
@Nullable
@Override
public String getParentType() {
return ImageButton.class.getName();
}
@NonNull
@Override
public ProteusView createView(
@NonNull ProteusContext context,
@NonNull Layout layout,
@NonNull ObjectValue data,
@Nullable ViewGroup parent,
int dataIndex) {
return new ProetusVisibilityAwareImageButton(context);
}
@Override
protected void addAttributeProcessors() {}
}
| 1,257 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
AppCompatToolbarParser.java | /FileExtraction/Java_unseen/Deenu488_CodeAssist-Unofficial/appcompat-widgets/src/main/java/com/tyron/layout/appcompat/widget/AppCompatToolbarParser.java | package com.tyron.layout.appcompat.widget;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import com.flipkart.android.proteus.ProteusContext;
import com.flipkart.android.proteus.ProteusView;
import com.flipkart.android.proteus.ViewTypeParser;
import com.flipkart.android.proteus.value.Layout;
import com.flipkart.android.proteus.value.ObjectValue;
import com.tyron.layout.appcompat.view.ProteusAppCompatToolbar;
public class AppCompatToolbarParser<V extends View> extends ViewTypeParser<V> {
@NonNull
@Override
public String getType() {
return Toolbar.class.getName();
}
@Nullable
@Override
public String getParentType() {
return ViewGroup.class.getName();
}
@NonNull
@Override
public ProteusView createView(
@NonNull ProteusContext context,
@NonNull Layout layout,
@NonNull ObjectValue data,
@Nullable ViewGroup parent,
int dataIndex) {
return new ProteusAppCompatToolbar(context);
}
@Override
protected void addAttributeProcessors() {
// TODO: add processors
}
}
| 1,171 | Java | .java | Deenu488/CodeAssist-Unofficial | 122 | 27 | 2 | 2022-12-13T08:34:02Z | 2024-05-08T01:27:41Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.