|
| 1 | +/* |
| 2 | + * Copyright 2013-2016 Sergey Ignatov, Alexander Zolotov, Florin Patan |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.goide.inspections; |
| 18 | + |
| 19 | +import com.goide.psi.*; |
| 20 | +import com.intellij.codeInspection.LocalInspectionToolSession; |
| 21 | +import com.intellij.codeInspection.ProblemsHolder; |
| 22 | +import com.intellij.psi.PsiElement; |
| 23 | +import com.intellij.util.ObjectUtils; |
| 24 | +import org.jetbrains.annotations.NotNull; |
| 25 | + |
| 26 | +public class GoAddressOfLoopVariableInspection extends GoInspectionBase { |
| 27 | + @NotNull |
| 28 | + @Override |
| 29 | + protected GoVisitor buildGoVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { |
| 30 | + return new GoVisitor() { |
| 31 | + @Override |
| 32 | + public void visitUnaryExpr(@NotNull GoUnaryExpr o) { |
| 33 | + if (o.getBitAnd() == null) { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + //TODO improve by supporting references to fields of struct variables |
| 38 | + GoReferenceExpression refExpr = ObjectUtils.tryCast(o.getExpression(), GoReferenceExpression.class); |
| 39 | + if (refExpr == null || refExpr.getQualifier() != null) { |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + GoVarDefinition varDefinition = ObjectUtils.tryCast(refExpr.getReference().resolve(), GoVarDefinition.class); |
| 44 | + PsiElement parent = varDefinition != null ? varDefinition.getParent() : null; |
| 45 | + if (!(parent instanceof GoRangeClause)) { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + holder.registerProblem(o, "Suspicious: obtaining address of a for loop variable"); |
| 50 | + } |
| 51 | + }; |
| 52 | + } |
| 53 | +} |
0 commit comments