|
16 | 16 | import cpp
|
17 | 17 | import codingstandards.cpp.autosar
|
18 | 18 |
|
19 |
| -from CStyleCast c |
| 19 | +/** |
| 20 | + * Gets the macro (if any) that generated the given `CStyleCast`. |
| 21 | + * |
| 22 | + * If there are nested macro invocations, we identify the most specific macro that generated the |
| 23 | + * cast. |
| 24 | + */ |
| 25 | +Macro getGeneratedFrom(CStyleCast c) { |
| 26 | + exists(MacroInvocation mi | |
| 27 | + mi = result.getAnInvocation() and |
| 28 | + mi.getAGeneratedElement() = c and |
| 29 | + mi.getLocation().getStartColumn() = c.getLocation().getStartColumn() and |
| 30 | + not exists(MacroInvocation child | |
| 31 | + child.getParentInvocation() = mi and |
| 32 | + child.getAGeneratedElement() = c |
| 33 | + ) |
| 34 | + ) |
| 35 | +} |
| 36 | + |
| 37 | +/** A macro within the source location of this project. */ |
| 38 | +class UserProvidedMacro extends Macro { |
| 39 | + UserProvidedMacro() { exists(this.getFile().getRelativePath()) } |
| 40 | +} |
| 41 | + |
| 42 | +/** A macro defined within a library used by this project. */ |
| 43 | +class LibraryMacro extends Macro { |
| 44 | + LibraryMacro() { not this instanceof UserProvidedMacro } |
| 45 | +} |
| 46 | + |
| 47 | +from CStyleCast c, string extraMessage, Locatable l, string supplementary |
20 | 48 | where
|
21 | 49 | not isExcluded(c, BannedSyntaxPackage::traditionalCStyleCastsUsedQuery()) and
|
22 | 50 | not c.isImplicit() and
|
23 |
| - not c.getType() instanceof UnknownType |
24 |
| -select c, "Use of explicit C-style Cast" |
| 51 | + not c.getType() instanceof UnknownType and |
| 52 | + // Exclude casts created from macro invocations of macros defined by third parties |
| 53 | + not getGeneratedFrom(c) instanceof LibraryMacro and |
| 54 | + // If the cast was generated from a user-provided macro, then report the macro that generated the |
| 55 | + // cast, as the macro itself may have generated the cast |
| 56 | + if getGeneratedFrom(c) instanceof UserProvidedMacro |
| 57 | + then |
| 58 | + extraMessage = " generated from macro $@" and |
| 59 | + // Add macro as explanatory link |
| 60 | + l = getGeneratedFrom(c) and |
| 61 | + supplementary = getGeneratedFrom(c).getName() |
| 62 | + else ( |
| 63 | + // No extra message required |
| 64 | + extraMessage = "" and |
| 65 | + // No explanatory link required, but we still need to set these to valid values |
| 66 | + l = c and |
| 67 | + supplementary = "" |
| 68 | + ) |
| 69 | +select c, "Use of explicit c-style cast to " + c.getType().getName() + extraMessage + ".", l, |
| 70 | + supplementary |
0 commit comments