2 * Copyright 2000-2009 JetBrains s.r.o.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 package com
.intellij
.codeInsight
.template
.macro
;
22 import com
.intellij
.codeInsight
.CodeInsightBundle
;
23 import com
.intellij
.codeInsight
.lookup
.LookupElement
;
24 import com
.intellij
.codeInsight
.template
.*;
25 import com
.intellij
.openapi
.project
.Project
;
26 import com
.intellij
.psi
.*;
27 import com
.intellij
.psi
.util
.PsiTreeUtil
;
28 import org
.jetbrains
.annotations
.NotNull
;
30 public class CastToLeftSideTypeMacro
implements Macro
{
31 public String
getName() {
32 return "castToLeftSideType";
35 public String
getDescription() {
36 return CodeInsightBundle
.message("macro.cast.to.left.side.type");
39 public String
getDefaultValue() {
43 public Result
calculateResult(@NotNull Expression
[] params
, ExpressionContext context
) {
44 int offset
= context
.getStartOffset();
45 Project project
= context
.getProject();
46 PsiDocumentManager
.getInstance(project
).commitAllDocuments();
47 PsiFile file
= PsiDocumentManager
.getInstance(project
).getPsiFile(context
.getEditor().getDocument());
48 PsiElement element
= file
.findElementAt(offset
);
49 element
= PsiTreeUtil
.getParentOfType(element
, PsiAssignmentExpression
.class, PsiVariable
.class);
50 PsiType leftType
= null;
51 PsiExpression rightSide
= null;
52 if (element
instanceof PsiAssignmentExpression
) {
53 PsiAssignmentExpression assignment
= (PsiAssignmentExpression
) element
;
54 leftType
= assignment
.getLExpression().getType();
55 rightSide
= assignment
.getRExpression();
56 } else if (element
instanceof PsiVariable
) {
57 PsiVariable var
= (PsiVariable
) element
;
58 leftType
= var
.getType();
59 rightSide
= var
.getInitializer();
62 while (rightSide
instanceof PsiTypeCastExpression
) rightSide
= ((PsiTypeCastExpression
) rightSide
).getOperand();
64 if (leftType
!= null && rightSide
!= null && rightSide
.getType() != null && !leftType
.isAssignableFrom(rightSide
.getType())) {
65 return new TextResult("("+ leftType
.getCanonicalText() + ")");
68 return new TextResult("");
71 public Result
calculateQuickResult(@NotNull Expression
[] params
, ExpressionContext context
) {
75 public LookupElement
[] calculateLookupItems(@NotNull Expression
[] params
, ExpressionContext context
) {
76 return LookupElement
.EMPTY_ARRAY
;