You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

CppVisitor.java 14 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. MIT License
  3. Copyright (c) 2018-2019 Gang ZHANG
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. */
  20. package depends.extractor.cpp.cdt;
  21. import depends.entity.*;
  22. import depends.entity.repo.EntityRepo;
  23. import depends.entity.repo.IdGenerator;
  24. import depends.extractor.cpp.CppHandlerContext;
  25. import depends.importtypes.ExactMatchImport;
  26. import depends.importtypes.FileImport;
  27. import depends.importtypes.PackageWildCardImport;
  28. import depends.relations.IBindingResolver;
  29. import org.codehaus.plexus.util.StringUtils;
  30. import org.eclipse.cdt.core.dom.ast.*;
  31. import org.eclipse.cdt.core.dom.ast.IASTEnumerationSpecifier.IASTEnumerator;
  32. import org.eclipse.cdt.core.dom.ast.cpp.*;
  33. import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTCompositeTypeSpecifier.ICPPASTBaseSpecifier;
  34. import org.eclipse.cdt.internal.core.dom.parser.cpp.*;
  35. import org.slf4j.Logger;
  36. import org.slf4j.LoggerFactory;
  37. import java.util.ArrayList;
  38. import java.util.HashSet;
  39. import java.util.List;
  40. public class CppVisitor extends ASTVisitor {
  41. private static final Logger logger = LoggerFactory.getLogger(CppVisitor.class);
  42. private CppHandlerContext context;
  43. private IdGenerator idGenerator;
  44. private PreprocessorHandler preprocessorHandler;
  45. IBindingResolver bindingResolver;
  46. private ExpressionUsage expressionUsage;
  47. HashSet<String> file;
  48. public CppVisitor(String fileFullPath, EntityRepo entityRepo, PreprocessorHandler preprocessorHandler, IBindingResolver bindingResolver) {
  49. super(true);
  50. this.shouldVisitAmbiguousNodes = true;
  51. this.shouldVisitImplicitNames = true;
  52. this.includeInactiveNodes = true;
  53. this.context = new CppHandlerContext(entityRepo, bindingResolver);
  54. idGenerator = entityRepo;
  55. this.bindingResolver = bindingResolver;
  56. this.preprocessorHandler = preprocessorHandler;
  57. expressionUsage = new ExpressionUsage(context,entityRepo);
  58. file = new HashSet<>();
  59. context.startFile(fileFullPath);
  60. file.add(this.context.currentFile().getQualifiedName());
  61. }
  62. @Override
  63. public int visit(IASTTranslationUnit tu) {
  64. for (String incl:preprocessorHandler.getDirectIncludedFiles(tu.getAllPreprocessorStatements(),context.currentFile().getQualifiedName())) {
  65. context.foundNewImport(new FileImport(incl));
  66. }
  67. MacroExtractor macroExtractor = new MacroExtractor(tu.getAllPreprocessorStatements(),context.currentFile().getQualifiedName());
  68. macroExtractor.extract(context);
  69. for (IASTNode child:tu.getChildren()) {
  70. if (notLocalFile(child)) continue;
  71. child.accept(this);
  72. }
  73. return ASTVisitor.PROCESS_SKIP;
  74. }
  75. @Override
  76. public int visit(IASTProblem problem) {
  77. if (notLocalFile(problem)) return ASTVisitor.PROCESS_SKIP;
  78. System.out.println("warning: parse error " + problem.getOriginalNode().getRawSignature() + problem.getMessageWithLocation());
  79. return super.visit(problem);
  80. }
  81. private boolean notLocalFile(IASTNode node) {
  82. if (file.contains(node.getFileLocation().getFileName())) {
  83. return false;
  84. }
  85. return true;
  86. }
  87. // PACKAGES
  88. @Override
  89. public int visit(ICPPASTNamespaceDefinition namespaceDefinition) {
  90. if (notLocalFile(namespaceDefinition)) return ASTVisitor.PROCESS_SKIP;
  91. String ns = namespaceDefinition.getName().toString().replace("::", ".");
  92. logger.trace("enter ICPPASTNamespaceDefinition " + ns);
  93. Entity pkg = context.foundNamespace(ns,namespaceDefinition.getFileLocation().getStartingLineNumber());
  94. context.foundNewImport(new PackageWildCardImport(ns));
  95. return super.visit(namespaceDefinition);
  96. }
  97. @Override
  98. public int leave(ICPPASTNamespaceDefinition namespaceDefinition) {
  99. if (notLocalFile(namespaceDefinition)) return ASTVisitor.PROCESS_SKIP;
  100. context.exitLastedEntity();
  101. return super.leave(namespaceDefinition);
  102. }
  103. // Types
  104. @Override
  105. public int visit(IASTDeclSpecifier declSpec) {
  106. if (notLocalFile(declSpec)) return ASTVisitor.PROCESS_SKIP;
  107. logger.trace("enter IASTDeclSpecifier " + declSpec.getClass().getSimpleName());
  108. if (declSpec instanceof IASTCompositeTypeSpecifier) {
  109. IASTCompositeTypeSpecifier type = (IASTCompositeTypeSpecifier)declSpec;
  110. String name = ASTStringUtilExt.getName(type);
  111. List<GenericName> param = ASTStringUtilExt.getTemplateParameters(type);
  112. TypeEntity typeEntity = context.foundNewType(name, type.getFileLocation().getStartingLineNumber());
  113. if (declSpec instanceof ICPPASTCompositeTypeSpecifier) {
  114. ICPPASTBaseSpecifier[] baseSpecififers = ((ICPPASTCompositeTypeSpecifier)declSpec).getBaseSpecifiers();
  115. for (ICPPASTBaseSpecifier baseSpecififer:baseSpecififers) {
  116. String extendName = ASTStringUtilExt.getName(baseSpecififer.getNameSpecifier());
  117. context.foundExtends(extendName);
  118. }
  119. }
  120. }
  121. else if (declSpec instanceof IASTEnumerationSpecifier) {
  122. context.foundNewType(ASTStringUtilExt.getName(declSpec), declSpec.getFileLocation().getStartingLineNumber());
  123. }else {
  124. //we do not care other types
  125. }
  126. return super.visit(declSpec);
  127. }
  128. @Override
  129. public int leave(IASTDeclSpecifier declSpec) {
  130. if (notLocalFile(declSpec)) return ASTVisitor.PROCESS_SKIP;
  131. if (declSpec instanceof IASTCompositeTypeSpecifier) {
  132. context.exitLastedEntity();
  133. }
  134. else if (declSpec instanceof IASTEnumerationSpecifier) {
  135. context.exitLastedEntity();
  136. }else {
  137. //we do not care other types
  138. }
  139. return super.leave(declSpec);
  140. }
  141. //Function or Methods
  142. @Override
  143. public int visit(IASTDeclarator declarator) {
  144. if (notLocalFile(declarator)) return ASTVisitor.PROCESS_SKIP;
  145. logger.trace("enter IASTDeclarator " + declarator.getClass().getSimpleName());
  146. if (declarator instanceof IASTFunctionDeclarator){
  147. GenericName returnType = null;
  148. if ( declarator.getParent() instanceof IASTSimpleDeclaration) {
  149. IASTSimpleDeclaration decl = (IASTSimpleDeclaration)(declarator.getParent());
  150. returnType = buildGenericNameFromDeclSpecifier(decl.getDeclSpecifier());
  151. String rawName = ASTStringUtilExt.getName(declarator);
  152. List<Entity> namedEntity = context.currentFile().lookupFunctionInVisibleScope(GenericName.build(rawName));
  153. if (namedEntity!=null) {
  154. rawName = namedEntity.get(0).getQualifiedName();
  155. }
  156. returnType = reMapIfConstructDeconstruct(rawName,returnType);
  157. context.foundMethodDeclaratorProto(rawName, returnType,decl.getFileLocation().getStartingLineNumber());
  158. }
  159. else if ( declarator.getParent() instanceof IASTFunctionDefinition) {
  160. IASTFunctionDefinition decl = (IASTFunctionDefinition)declarator.getParent();
  161. returnType = buildGenericNameFromDeclSpecifier(decl.getDeclSpecifier());
  162. String rawName = ASTStringUtilExt.getName(declarator);
  163. List<Entity> namedEntity = context.currentFile().lookupFunctionInVisibleScope(GenericName.build(rawName));
  164. if (namedEntity!=null) {
  165. rawName = namedEntity.get(0).getQualifiedName();
  166. }
  167. returnType = reMapIfConstructDeconstruct(rawName,returnType);
  168. context.foundMethodDeclaratorImplementation(rawName, returnType,decl.getFileLocation().getStartingLineNumber());
  169. }
  170. }
  171. return super.visit(declarator);
  172. }
  173. private GenericName buildGenericNameFromDeclSpecifier(IASTDeclSpecifier decl) {
  174. String name = ASTStringUtilExt.getName(decl);
  175. List<GenericName> templateParams = ASTStringUtilExt.getTemplateParameters(decl);
  176. if (name==null)
  177. return null;
  178. return new GenericName(name,templateParams);
  179. }
  180. /**
  181. * In case of return type is empty, it maybe a construct/deconstruct function
  182. * @param functionname
  183. * @param returnType
  184. * @return
  185. */
  186. private GenericName reMapIfConstructDeconstruct(String functionname, GenericName returnType) {
  187. if (returnType!=null && returnType.uniqName().length()>0)
  188. return returnType;
  189. if (functionname.contains("::")) {
  190. return new GenericName(functionname.substring(0, functionname.indexOf("::")));
  191. }else {
  192. return new GenericName(functionname);
  193. }
  194. }
  195. @Override
  196. public int leave(IASTDeclarator declarator) {
  197. if (notLocalFile(declarator)) return ASTVisitor.PROCESS_SKIP;
  198. if (declarator instanceof IASTFunctionDeclarator){
  199. if ( declarator.getParent() instanceof IASTSimpleDeclaration) {
  200. String rawName = ASTStringUtilExt.getName(declarator);
  201. if (rawName.equals(context.lastContainer().getRawName().getName())) {
  202. context.exitLastedEntity();
  203. }else {
  204. System.err.println("unexpected symbol");
  205. }
  206. }
  207. }
  208. return super.leave(declarator);
  209. }
  210. @Override
  211. public int leave(IASTDeclaration declaration) {
  212. if (notLocalFile(declaration)) return ASTVisitor.PROCESS_SKIP;
  213. if ( declaration instanceof IASTFunctionDefinition) {
  214. context.exitLastedEntity();
  215. }
  216. return super.leave(declaration);
  217. }
  218. // Variables
  219. @Override
  220. public int visit(IASTDeclaration declaration) {
  221. if (notLocalFile(declaration)) return ASTVisitor.PROCESS_SKIP;
  222. logger.trace("enter IASTDeclaration " + declaration.getClass().getSimpleName());
  223. if (declaration instanceof ICPPASTUsingDeclaration) {
  224. String ns = ASTStringUtilExt.getName((ICPPASTUsingDeclaration)declaration);
  225. context.foundNewImport(new PackageWildCardImport(ns));
  226. }
  227. else if (declaration instanceof ICPPASTUsingDirective) {
  228. String ns = ((ICPPASTUsingDirective)declaration).getQualifiedName().toString().replace("::", ".");
  229. context.foundNewImport(new ExactMatchImport(ns));
  230. }
  231. else if (declaration instanceof IASTSimpleDeclaration ) {
  232. for (IASTDeclarator declarator:((IASTSimpleDeclaration) declaration).getDeclarators()) {
  233. IASTDeclSpecifier declSpecifier = ((IASTSimpleDeclaration) declaration).getDeclSpecifier();
  234. //Found new typedef definition
  235. if (declSpecifier.getStorageClass()==IASTDeclSpecifier.sc_typedef) {
  236. context.foundNewAlias(ASTStringUtilExt.getName(declarator),ASTStringUtilExt.getName(declSpecifier));
  237. }else if (!(declarator instanceof IASTFunctionDeclarator)) {
  238. String varType = ASTStringUtilExt.getName(declSpecifier);
  239. String varName = ASTStringUtilExt.getName(declarator);
  240. if (!StringUtils.isEmpty(varType)) {
  241. context.foundVarDefinition(varName, GenericName.build(varType), ASTStringUtilExt.getTemplateParameters(declSpecifier),declarator.getFileLocation().getStartingLineNumber());
  242. }else {
  243. expressionUsage.foundCallExpressionOfFunctionStyle(varName,declarator);
  244. }
  245. }
  246. }
  247. }else if (declaration instanceof IASTFunctionDefinition){
  248. //handled in declarator
  249. }else if (declaration instanceof CPPASTVisibilityLabel){
  250. //we ignore the visibility in dependency check
  251. }else if (declaration instanceof CPPASTLinkageSpecification){
  252. }else if (declaration instanceof CPPASTTemplateDeclaration){
  253. }else if (declaration instanceof CPPASTProblemDeclaration){
  254. System.err.println("parsing error \n" + declaration.getRawSignature());
  255. }else if (declaration instanceof ICPPASTAliasDeclaration){
  256. IASTName name = ((ICPPASTAliasDeclaration)declaration).getAlias();
  257. String alias = ASTStringUtilExt.getSimpleName(name).replace("::", ".");
  258. ICPPASTTypeId mapped = ((ICPPASTAliasDeclaration)declaration).getMappingTypeId();
  259. String originalName1 = ASTStringUtilExt.getTypeIdString(mapped);
  260. context.foundNewAlias(alias, originalName1);
  261. }else if (declaration instanceof CPPASTNamespaceAlias){
  262. IASTName name = ((CPPASTNamespaceAlias)declaration).getAlias();
  263. String alias = ASTStringUtilExt.getSimpleName(name).replace("::", ".");
  264. IASTName mapped = ((CPPASTNamespaceAlias)declaration).getMappingName();
  265. String originalName = ASTStringUtilExt.getName(mapped);
  266. context.foundNewAlias(alias, originalName);
  267. }
  268. else if(declaration instanceof CPPASTStaticAssertionDeclaration)
  269. {
  270. }else if (declaration instanceof CPPASTTemplateSpecialization) {
  271. }
  272. else{
  273. System.out.println("not handled type: " + declaration.getClass().getName());
  274. System.out.println(declaration.getRawSignature());
  275. }
  276. return super.visit(declaration);
  277. }
  278. @Override
  279. public int visit(IASTEnumerator enumerator) {
  280. if (notLocalFile(enumerator)) return ASTVisitor.PROCESS_SKIP;
  281. logger.trace("enter IASTEnumerator " + enumerator.getClass().getSimpleName());
  282. VarEntity var = context.foundVarDefinition(enumerator.getName().toString(), context.currentType().getRawName(), new ArrayList<>(),enumerator.getFileLocation().getStartingLineNumber());
  283. return super.visit(enumerator);
  284. }
  285. @Override
  286. public int visit(IASTExpression expression) {
  287. if (notLocalFile(expression)) return ASTVisitor.PROCESS_SKIP;
  288. Expression expr = expressionUsage.foundExpression(expression);
  289. expr.setLine(expression.getFileLocation().getStartingLineNumber());
  290. return super.visit(expression);
  291. }
  292. @Override
  293. public int visit(IASTParameterDeclaration parameterDeclaration) {
  294. if (notLocalFile(parameterDeclaration)) return ASTVisitor.PROCESS_SKIP;
  295. logger.trace("enter IASTParameterDeclaration " + parameterDeclaration.getClass().getSimpleName());
  296. String parameterName = ASTStringUtilExt.getName(parameterDeclaration.getDeclarator());
  297. String parameterType = ASTStringUtilExt.getName(parameterDeclaration.getDeclSpecifier());
  298. if (context.currentFunction()!=null) {
  299. VarEntity var = new VarEntity(GenericName.build(parameterName),GenericName.build(parameterType),context.currentFunction(),idGenerator.generateId());
  300. context.currentFunction().addParameter(var );
  301. }else {
  302. //System.out.println("** parameterDeclaration = " + parameter);
  303. }
  304. return super.visit(parameterDeclaration);
  305. }
  306. }