use of com.github.javaparser.ast.body.TypeDeclaration in project javaparser by javaparser.
the class CompilationUnitContext method fieldsExposedToChild.
@Override
public List<ResolvedFieldDeclaration> fieldsExposedToChild(Node child) {
List<ResolvedFieldDeclaration> res = new LinkedList<>();
// Consider the static imports for static fields
for (ImportDeclaration importDeclaration : wrappedNode.getImports()) {
if (importDeclaration.isStatic()) {
Name typeNameAsNode = importDeclaration.isAsterisk() ? importDeclaration.getName() : importDeclaration.getName().getQualifier().get();
String typeName = typeNameAsNode.asString();
ResolvedReferenceTypeDeclaration typeDeclaration = typeSolver.solveType(typeName);
res.addAll(typeDeclaration.getAllFields().stream().filter(f -> f.isStatic()).filter(f -> importDeclaration.isAsterisk() || importDeclaration.getName().getIdentifier().equals(f.getName())).collect(Collectors.toList()));
}
}
return res;
}
use of com.github.javaparser.ast.body.TypeDeclaration in project javaparser by javaparser.
the class JavaParserFacade method toMethodUsage.
protected MethodUsage toMethodUsage(MethodReferenceExpr methodReferenceExpr, List<ResolvedType> paramTypes) {
Expression scope = methodReferenceExpr.getScope();
ResolvedType typeOfScope = getType(methodReferenceExpr.getScope());
if (!typeOfScope.isReferenceType()) {
throw new UnsupportedOperationException(typeOfScope.getClass().getCanonicalName());
}
Optional<MethodUsage> result;
Set<MethodUsage> allMethods = typeOfScope.asReferenceType().getTypeDeclaration().orElseThrow(() -> new RuntimeException("TypeDeclaration unexpectedly empty.")).getAllMethods();
if (scope.isTypeExpr()) {
// static methods should match all params
List<MethodUsage> staticMethodUsages = allMethods.stream().filter(it -> it.getDeclaration().isStatic()).collect(Collectors.toList());
result = MethodResolutionLogic.findMostApplicableUsage(staticMethodUsages, methodReferenceExpr.getIdentifier(), paramTypes, typeSolver);
if (!paramTypes.isEmpty()) {
// instance methods are called on the first param and should match all other params
List<MethodUsage> instanceMethodUsages = allMethods.stream().filter(it -> !it.getDeclaration().isStatic()).collect(Collectors.toList());
List<ResolvedType> instanceMethodParamTypes = new ArrayList<>(paramTypes);
// remove the first one
instanceMethodParamTypes.remove(0);
Optional<MethodUsage> instanceResult = MethodResolutionLogic.findMostApplicableUsage(instanceMethodUsages, methodReferenceExpr.getIdentifier(), instanceMethodParamTypes, typeSolver);
if (result.isPresent() && instanceResult.isPresent()) {
throw new MethodAmbiguityException("Ambiguous method call: cannot find a most applicable method for " + methodReferenceExpr.getIdentifier());
}
if (instanceResult.isPresent()) {
result = instanceResult;
}
}
} else {
result = MethodResolutionLogic.findMostApplicableUsage(new ArrayList<>(allMethods), methodReferenceExpr.getIdentifier(), paramTypes, typeSolver);
if (result.isPresent() && result.get().getDeclaration().isStatic()) {
throw new RuntimeException("Invalid static method reference " + methodReferenceExpr.getIdentifier());
}
}
if (!result.isPresent()) {
throw new UnsupportedOperationException();
}
return result.get();
}
use of com.github.javaparser.ast.body.TypeDeclaration in project javaparser by javaparser.
the class JavaParserTypeDeclarationAdapter method solveMethod.
public SymbolReference<ResolvedMethodDeclaration> solveMethod(String name, List<ResolvedType> argumentsTypes, boolean staticOnly) {
// Begin by locating methods declared "here"
List<ResolvedMethodDeclaration> candidateMethods = typeDeclaration.getDeclaredMethods().stream().filter(m -> m.getName().equals(name)).filter(m -> !staticOnly || m.isStatic()).collect(Collectors.toList());
// Note that we only consider ancestors when we are not currently at java.lang.Object (avoiding infinite recursion).
if (!typeDeclaration.isJavaLangObject()) {
for (ResolvedReferenceType ancestor : typeDeclaration.getAncestors(true)) {
Optional<ResolvedReferenceTypeDeclaration> ancestorTypeDeclaration = ancestor.getTypeDeclaration();
// Avoid recursion on self
if (ancestor.getTypeDeclaration().isPresent() && typeDeclaration != ancestorTypeDeclaration.get()) {
// Consider methods declared on self
candidateMethods.addAll(ancestor.getAllMethodsVisibleToInheritors().stream().filter(m -> m.getName().equals(name)).collect(Collectors.toList()));
// consider methods from superclasses and only default methods from interfaces :
// not true, we should keep abstract as a valid candidate
// abstract are removed in MethodResolutionLogic.isApplicable is necessary
SymbolReference<ResolvedMethodDeclaration> res = MethodResolutionLogic.solveMethodInType(ancestorTypeDeclaration.get(), name, argumentsTypes, staticOnly);
if (res.isSolved()) {
candidateMethods.add(res.getCorrespondingDeclaration());
}
}
}
}
// Note that we want to avoid infinite recursion when a class is using its own method - see issue #75
if (candidateMethods.isEmpty()) {
SymbolReference<ResolvedMethodDeclaration> parentSolution = context.getParent().orElseThrow(() -> new RuntimeException("Parent context unexpectedly empty.")).solveMethod(name, argumentsTypes, staticOnly);
if (parentSolution.isSolved()) {
candidateMethods.add(parentSolution.getCorrespondingDeclaration());
}
}
// if is interface and candidate method list is empty, we should check the Object Methods
if (candidateMethods.isEmpty() && typeDeclaration.isInterface()) {
SymbolReference<ResolvedMethodDeclaration> res = MethodResolutionLogic.solveMethodInType(new ReflectionClassDeclaration(Object.class, typeSolver), name, argumentsTypes, false);
if (res.isSolved()) {
candidateMethods.add(res.getCorrespondingDeclaration());
}
}
return MethodResolutionLogic.findMostApplicable(candidateMethods, name, argumentsTypes, typeSolver);
}
use of com.github.javaparser.ast.body.TypeDeclaration in project structr by structr.
the class MethodVisitorAdapter method visit.
@Override
public void visit(final MethodCallExpr methodCall, final Object arg) {
final Map<String, Object> params = (HashMap) arg;
final String clsName = (String) params.get("clsName");
final JavaParserFacade facade = (JavaParserFacade) params.get("facade");
final App app = (App) params.get("app");
logger.info("###### " + clsName + ": " + methodCall.getName());
try {
// //// !!!!!!!!!!! Methoden-Aufruf kann in den meisten Fällen nicht aufgelöst werden!!
final SymbolReference<ResolvedMethodDeclaration> ref = facade.solve(methodCall);
if (ref.isSolved()) {
final String qualifiedSignature = ref.getCorrespondingDeclaration().getQualifiedSignature();
// final String scopeString = scope.toString();
final String parentNodeAsString = methodCall.getParentNode().toString();
// logger.info("Resolved to " + qualifiedSignature + ", scope: " + scopeString + ", parent node: " + parentNodeAsString);
logger.info("Resolved to " + qualifiedSignature + ", parent node: " + parentNodeAsString);
final String calledMethodQualifiedName = StringUtils.replacePattern(qualifiedSignature, "\\(.*\\)", "");
final String calledMethodQualifiedClassName = StringUtils.substringBeforeLast(calledMethodQualifiedName, ".");
final String calledMethodName = StringUtils.substringAfterLast(calledMethodQualifiedName, ".");
Method calledMethod = null;
final JavaClass calledMethodClass = (JavaClass) app.nodeQuery(JavaClass.class).and(JavaClass.name, calledMethodQualifiedClassName).getFirst();
if (calledMethodClass != null) {
logger.info("└ Found called class in graph: " + calledMethodClass.getName());
calledMethod = (Method) app.nodeQuery(Method.class).and(Method.name, calledMethodName).and(Method.classOrInterface, calledMethodClass).getFirst();
if (calledMethod != null) {
logger.info("└ Found called method in graph: " + calledMethod.getProperty(Method.declaration));
final Optional<MethodDeclaration> callingMethod = methodCall.getAncestorOfType(MethodDeclaration.class);
if (callingMethod.isPresent()) {
final String callingMethodDeclaration = callingMethod.get().getDeclarationAsString();
logger.info("└ Calling method: " + callingMethodDeclaration);
final String callingMethodName = callingMethod.get().getNameAsString();
final Optional<TypeDeclaration> typeDecl = callingMethod.get().getAncestorOfType(TypeDeclaration.class);
if (typeDecl.isPresent()) {
final String callingMethodClassName = typeDecl.get().getNameAsString();
// Find compilation unit
final Optional<CompilationUnit> localCU = typeDecl.get().getAncestorOfType(CompilationUnit.class);
if (localCU.isPresent()) {
// Does it have a package declaration?
final Optional<PackageDeclaration> packageDecl = localCU.get().getPackageDeclaration();
if (packageDecl.isPresent()) {
// Assemble qualified class name
final String packageName = packageDecl.get().getNameAsString();
final String fqcn = packageName + "." + callingMethodClassName;
// Find class in graph
final JavaClass callingClass = (JavaClass) app.nodeQuery(JavaClass.class).and(JavaClass.name, fqcn).getFirst();
if (callingClass != null) {
final Method method = (Method) app.nodeQuery(Method.class).and(Method.name, callingMethodName).and(Method.classOrInterface, callingClass).getFirst();
if (method != null) {
logger.info("Found calling method in graph: " + method.getName());
final List<Method> methodsCalled = Iterables.toList(method.getProperty(Method.methodsCalled));
methodsCalled.add(calledMethod);
method.setProperty(Method.methodsCalled, methodsCalled);
logger.info("Added " + calledMethod.getName() + " to list of methods called in " + method.getName());
}
}
}
}
}
}
}
}
}
} catch (final Throwable t) {
logger.info("Unable to resolve " + clsName, t);
}
}
use of com.github.javaparser.ast.body.TypeDeclaration in project Hidoc by yuzhengyang.
the class JavaDocCreateService method parseJavaDoc.
// @Transactional
// public ResponseData upload(String projectId, MultipartFile[] files) {
//
// // 参数判断检查
// if (!ListTool.ok(files)) return ResponseData.error("请选择文件");
//
// JavaDocProject javaDocProject = javaDocProjectMapper.selectById(projectId);
// if (javaDocProject == null) return ResponseData.error("JavaDoc项目不存在");
//
// SysUser curUser = CurrentUserManager.getUser();
//
// // 更新项目信息
// javaDocProject.setUpdateUserId(curUser.getId());
// javaDocProject.setUpdateTime(LocalDateTime.now());
// javaDocProject.setVersion(String.valueOf(System.currentTimeMillis()));
// List<JavaDocClass> javaDocClassList = new ArrayList<>();
// List<JavaDocMethod> javaDocMethodList = new ArrayList<>();
//
// // 准备数据开始分解存储
// for (MultipartFile file : files) {
// try {
// parseJavaDoc(cu, javaDocProject, javaDocClassList, javaDocMethodList);
// } catch (IOException ex) {
// }
// }
//
// // 最终汇总数据
// if (javaDocProject != null && javaDocClassList != null && javaDocMethodList != null) {
// javaDocProjectMapper.updateById(javaDocProject);
//
// if (ListTool.ok(javaDocClassList)) {
// for (JavaDocClass item : javaDocClassList) {
// javaDocClassMapper.insert(item);
// }
// }
//
// if (ListTool.ok(javaDocMethodList)) {
// for (JavaDocMethod item : javaDocMethodList) {
// javaDocMethodMapper.insert(item);
// }
// }
// return ResponseData.ok("JavaDoc创建完成");
// }
// return ResponseData.error("没有发现要创建的内容");
// }
private void parseJavaDoc(String filepath, JavaDocProject javaDocProject, List<JavaDocClass> javaDocClassList, List<JavaDocMethod> javaDocMethodList) throws FileNotFoundException {
SysUser curUser = CurrentUserManager.getUser();
List<String> oriDocTextList = TxtTool.readLine(filepath);
String oriDocText = String.join(StringConst.NEWLINE, oriDocTextList);
// parse() 参数可以是 String, File, InputStream等
CompilationUnit cu = StaticJavaParser.parse(new File(filepath));
List<TypeDeclaration> typeList = cu.findAll(TypeDeclaration.class);
// 遍历类信息
if (ListTool.ok(typeList)) {
for (TypeDeclaration typeItem : typeList) {
// 创建类信息
JavaDocClass javaDocClass = new JavaDocClass();
javaDocClass.setId(R.SnowFlake.nexts());
javaDocClass.setProjectId(javaDocProject.getId());
javaDocClass.setProjectName(javaDocProject.getName());
javaDocClass.setVersion(javaDocProject.getVersion());
javaDocClass.setCreateUserId(curUser.getId());
javaDocClass.setCreateTime(LocalDateTime.now());
javaDocClass.setName(typeItem.getNameAsString());
javaDocClass.setOriginalDocument(cu.toString());
javaDocClass.setIsStruct(false);
if (typeItem.hasParentNode() && typeItem.getParentNode().isPresent() && typeItem.getParentNode().get().findCompilationUnit().isPresent()) {
CompilationUnit parentNode = typeItem.getParentNode().get().findCompilationUnit().get();
// 填充包信息
if (parentNode.getPackageDeclaration().isPresent()) {
javaDocClass.setPackageInfo(parentNode.getPackageDeclaration().get().getNameAsString());
}
// 填充引用信息
if (ListTool.ok(parentNode.getImports())) {
List<Object> importsJson = new ArrayList<>(parentNode.getImports().size());
StringBuilder stringBuilder = new StringBuilder();
for (ImportDeclaration nodeItem : parentNode.getImports()) {
stringBuilder.append(nodeItem.getNameAsString());
stringBuilder.append(" ");
importsJson.add(nodeItem.getNameAsString());
}
javaDocClass.setImports(stringBuilder.toString());
javaDocClass.setImportsJson(new JSONArray(importsJson));
}
// 填充修饰词
if (ListTool.ok(typeItem.getModifiers())) {
StringBuilder stringBuilder = new StringBuilder();
for (Object modObject : typeItem.getModifiers()) {
if (modObject.getClass().equals(Modifier.class)) {
Modifier modItem = (Modifier) modObject;
stringBuilder.append(modItem.getKeyword().asString());
stringBuilder.append(" ");
}
}
javaDocClass.setQualifier(stringBuilder.toString());
}
// 填充注释内容
StringBuilder stringBuilder = new StringBuilder();
if (typeItem.getComment().isPresent()) {
String content = typeItem.getComment().get().getContent();
stringBuilder.append(content);
}
if (ListTool.ok(parentNode.getOrphanComments())) {
for (Comment commentItem : parentNode.getOrphanComments()) {
stringBuilder.append(commentItem.getContent());
stringBuilder.append(StringConst.NEWLINE);
}
}
if (stringBuilder.length() > 0) {
String[] commentArrays = parseComment(stringBuilder.toString());
javaDocClass.setCommentInfo(commentArrays[0]);
javaDocClass.setCommentScene(commentArrays[1]);
javaDocClass.setCommentLimit(commentArrays[2]);
javaDocClass.setCommentExample(commentArrays[3]);
javaDocClass.setCommentLog(commentArrays[4]);
javaDocClass.setCommentKeywords(commentArrays[5]);
javaDocClass.setCommentMenu(commentArrays[6]);
javaDocClass.setCommentLogJson(parseCommentLog(commentArrays[4]));
if (StringTool.ok(javaDocClass.getCommentScene()) || StringTool.ok(javaDocClass.getCommentLimit()) || StringTool.ok(javaDocClass.getCommentMenu()) || StringTool.ok(javaDocClass.getCommentKeywords())) {
javaDocClass.setIsStruct(true);
}
}
}
javaDocClassList.add(javaDocClass);
// 创建方法信息
if (ListTool.ok(typeItem.getChildNodes())) {
for (Node nodeItem : typeItem.getChildNodes()) {
if (nodeItem.getClass().equals(MethodDeclaration.class)) {
MethodDeclaration methodItem = (MethodDeclaration) nodeItem;
JavaDocMethod javaDocMethod = new JavaDocMethod();
javaDocMethod.setId(R.SnowFlake.nexts());
javaDocMethod.setClassId(javaDocClass.getId());
javaDocMethod.setClassName(javaDocClass.getName());
javaDocMethod.setProjectId(javaDocProject.getId());
javaDocMethod.setProjectName(javaDocProject.getName());
javaDocMethod.setVersion(javaDocProject.getVersion());
javaDocMethod.setCreateUserId(curUser.getId());
javaDocMethod.setCreateTime(LocalDateTime.now());
javaDocMethod.setName(methodItem.getNameAsString());
javaDocMethod.setSourceCode(methodItem.toString());
javaDocMethod.setIsStruct(false);
// 填充修饰词
if (ListTool.ok(methodItem.getModifiers())) {
StringBuilder stringBuilder = new StringBuilder();
for (Modifier modItem : methodItem.getModifiers()) {
stringBuilder.append(modItem.getKeyword().asString());
}
javaDocMethod.setQualifier(stringBuilder.toString());
}
// 填充传入参数
javaDocMethod.setReturnType(methodItem.getTypeAsString());
if (ListTool.ok(methodItem.getParameters())) {
StringBuilder stringBuilder = new StringBuilder();
JSONArray jsonArray = new JSONArray();
for (Parameter parameterItem : methodItem.getParameters()) {
stringBuilder.append(parameterItem.getTypeAsString());
stringBuilder.append(parameterItem.getNameAsString());
JSONObject jsonObject = new JSONObject();
jsonObject.put("type", parameterItem.getTypeAsString());
jsonObject.put("name", parameterItem.getNameAsString());
jsonArray.add(jsonObject);
}
javaDocMethod.setParams(stringBuilder.toString());
javaDocMethod.setParamsJson(jsonArray);
}
// 填充注释内容
if (methodItem.getComment().isPresent()) {
String content = methodItem.getComment().get().getContent();
String[] commentArrays = parseComment(content);
javaDocMethod.setCommentInfo(commentArrays[0]);
javaDocMethod.setCommentScene(commentArrays[1]);
javaDocMethod.setCommentLimit(commentArrays[2]);
javaDocMethod.setCommentExample(commentArrays[3]);
javaDocMethod.setCommentLog(commentArrays[4]);
javaDocMethod.setCommentKeywords(commentArrays[5] + " , " + javaDocClass.getCommentKeywords());
javaDocMethod.setCommentMenu(commentArrays[6]);
javaDocMethod.setCommentLogJson(parseCommentLog(commentArrays[4]));
if (StringTool.ok(javaDocMethod.getCommentScene()) || StringTool.ok(javaDocMethod.getCommentLimit()) || StringTool.ok(javaDocMethod.getCommentMenu()) || StringTool.ok(javaDocMethod.getCommentKeywords())) {
javaDocMethod.setIsStruct(true);
}
}
if (!javaDocClass.getIsStruct())
javaDocMethod.setIsStruct(false);
javaDocMethodList.add(javaDocMethod);
}
}
}
}
}
}
Aggregations