aboutsummaryrefslogtreecommitdiff
path: root/src/core/lombok/javac/handlers/HandleUtilityClass.java
blob: a4f8cb45213e05eb6b0f0a1654c0db088cb74190 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/*
 * Copyright (C) 2015 The Project Lombok Authors.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package lombok.javac.handlers;

import static lombok.core.handlers.HandlerUtil.*;
import static lombok.javac.handlers.JavacHandlerUtil.*;
import lombok.ConfigurationKeys;
import lombok.core.AST.Kind;
import lombok.core.AnnotationValues;
import lombok.experimental.UtilityClass;
import lombok.javac.JavacAnnotationHandler;
import lombok.javac.JavacNode;
import lombok.javac.JavacTreeMaker;

import org.mangosdk.spi.ProviderFor;

import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;

/**
 * Handles the {@code @UtilityClass} annotation for javac.
 */
@ProviderFor(JavacAnnotationHandler.class)
public class HandleUtilityClass extends JavacAnnotationHandler<UtilityClass> {
	@Override public void handle(AnnotationValues<UtilityClass> annotation, JCAnnotation ast, JavacNode annotationNode) {
		handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.UTLITY_CLASS_FLAG_USAGE, "@UtilityClass");
		
		deleteAnnotationIfNeccessary(annotationNode, UtilityClass.class);
		
		JavacNode typeNode = annotationNode.up();
		if (!checkLegality(typeNode, annotationNode)) return;
		changeModifiersAndGenerateConstructor(annotationNode.up(), annotationNode);
	}
	
	private static boolean checkLegality(JavacNode typeNode, JavacNode errorNode) {
		JCClassDecl typeDecl = null;
		if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get();
		long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags;
		boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION | Flags.ENUM)) != 0;
		
		if (typeDecl == null || notAClass) {
			errorNode.addError("@UtilityClass is only supported on a class (can't be an interface, enum, or annotation).");
			return false;
		}
		
		// It might be an inner class. This is okay, but only if it is / can be a static inner class. Thus, all of its parents have to be static inner classes until the top-level.
		JavacNode typeWalk = typeNode;
		while (true) {
			typeWalk = typeWalk.up();
			switch (typeWalk.getKind()) {
			case TYPE:
				JCClassDecl typeDef = (JCClassDecl) typeWalk.get();
				if ((typeDef.mods.flags & (Flags.STATIC | Flags.ANNOTATION | Flags.ENUM | Flags.INTERFACE)) != 0) continue;
				if (typeWalk.up().getKind() == Kind.COMPILATION_UNIT) return true;
				errorNode.addError("@UtilityClass automatically makes the class static, however, this class cannot be made static.");
				return false;
			case COMPILATION_UNIT:
				return true;
			default:
				errorNode.addError("@UtilityClass cannot be placed on a method local or anonymous inner class, or any class nested in such a class.");
				return false;
			}
		}
	}
	
	private void changeModifiersAndGenerateConstructor(JavacNode typeNode, JavacNode errorNode) {
		JCClassDecl classDecl = (JCClassDecl) typeNode.get();
		
		boolean makeConstructor = true;
		
		classDecl.mods.flags |= Flags.FINAL;
		
		boolean markStatic = true;
		
		if (typeNode.up().getKind() == Kind.COMPILATION_UNIT) markStatic = false;
		if (markStatic && typeNode.up().getKind() == Kind.TYPE) {
			JCClassDecl typeDecl = (JCClassDecl) typeNode.up().get();
			if ((typeDecl.mods.flags & Flags.INTERFACE) != 0) markStatic = false;
		}
		
		if (markStatic) classDecl.mods.flags |= Flags.STATIC;
		
		for (JavacNode element : typeNode.down()) {
			if (element.getKind() == Kind.FIELD) {
				JCVariableDecl fieldDecl = (JCVariableDecl) element.get();
				fieldDecl.mods.flags |= Flags.STATIC;
			} else if (element.getKind() == Kind.METHOD) {
				JCMethodDecl methodDecl = (JCMethodDecl) element.get();
				if (methodDecl.name.contentEquals("<init>")) {
					if (getGeneratedBy(methodDecl) == null && (methodDecl.mods.flags & Flags.GENERATEDCONSTR) == 0) {
						element.addError("@UtilityClasses cannot have declared constructors.");
						makeConstructor = false;
						continue;
					}
				}
				
				methodDecl.mods.flags |= Flags.STATIC;
			} else if (element.getKind() == Kind.TYPE) {
				JCClassDecl innerClassDecl = (JCClassDecl) element.get();
				innerClassDecl.mods.flags |= Flags.STATIC;
			}
		}
		
		if (makeConstructor) createPrivateDefaultConstructor(typeNode);
	}
	
	private void createPrivateDefaultConstructor(JavacNode typeNode) {
		JavacTreeMaker maker = typeNode.getTreeMaker();
		JCModifiers mods = maker.Modifiers(Flags.PRIVATE, List.<JCAnnotation>nil());
		
		Name name = typeNode.toName("<init>");
		JCBlock block = maker.Block(0L, createThrowStatement(typeNode, maker));
		JCMethodDecl methodDef = maker.MethodDef(mods, name, null, List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), block, null);
		JCMethodDecl constructor = recursiveSetGeneratedBy(methodDef, typeNode.get(), typeNode.getContext());
		JavacHandlerUtil.injectMethod(typeNode, constructor);
	}
	
	private List<JCStatement> createThrowStatement(JavacNode typeNode, JavacTreeMaker maker) {
		JCExpression exceptionType = genJavaLangTypeRef(typeNode, "UnsupportedOperationException");
		List<JCExpression> jceBlank = List.nil();
		JCExpression message = maker.Literal("This is a utility class and cannot be instantiated");
		JCExpression exceptionInstance = maker.NewClass(null, jceBlank, exceptionType, List.of(message), null);
		JCStatement throwStatement = maker.Throw(exceptionInstance);
		return List.of(throwStatement);
	}
}