1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.puppycrawl.tools.checkstyle.checks.whitespace;
21
22 import java.util.Locale;
23
24 import com.puppycrawl.tools.checkstyle.StatelessCheck;
25 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
26 import com.puppycrawl.tools.checkstyle.api.DetailAST;
27 import com.puppycrawl.tools.checkstyle.utils.CodePointUtil;
28 import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
29
30
31
32
33
34
35
36 @StatelessCheck
37 public abstract class AbstractParenPadCheck
38 extends AbstractCheck {
39
40
41
42
43
44 public static final String MSG_WS_FOLLOWED = "ws.followed";
45
46
47
48
49
50 public static final String MSG_WS_NOT_FOLLOWED = "ws.notFollowed";
51
52
53
54
55
56 public static final String MSG_WS_PRECEDED = "ws.preceded";
57
58
59
60
61
62 public static final String MSG_WS_NOT_PRECEDED = "ws.notPreceded";
63
64
65 private static final char OPEN_PARENTHESIS = '(';
66
67
68 private static final char CLOSE_PARENTHESIS = ')';
69
70
71 private PadOption option = PadOption.NOSPACE;
72
73
74
75
76
77
78
79 public void setOption(String optionStr) {
80 option = PadOption.valueOf(optionStr.trim().toUpperCase(Locale.ENGLISH));
81 }
82
83
84
85
86
87
88 protected void processLeft(DetailAST ast) {
89 final int[] line = getLineCodePoints(ast.getLineNo() - 1);
90 final int after = ast.getColumnNo() + 1;
91
92 if (after < line.length) {
93 final boolean hasWhitespaceAfter =
94 CommonUtil.isCodePointWhitespace(line, after);
95 if (option == PadOption.NOSPACE && hasWhitespaceAfter) {
96 log(ast, MSG_WS_FOLLOWED, OPEN_PARENTHESIS);
97 }
98 else if (option == PadOption.SPACE && !hasWhitespaceAfter
99 && line[after] != CLOSE_PARENTHESIS) {
100 log(ast, MSG_WS_NOT_FOLLOWED, OPEN_PARENTHESIS);
101 }
102 }
103 }
104
105
106
107
108
109
110 protected void processRight(DetailAST ast) {
111 final int before = ast.getColumnNo() - 1;
112 if (before >= 0) {
113 final int[] line = getLineCodePoints(ast.getLineNo() - 1);
114 final boolean hasPrecedingWhitespace =
115 CommonUtil.isCodePointWhitespace(line, before);
116
117 if (option == PadOption.NOSPACE && hasPrecedingWhitespace
118 && !CodePointUtil.hasWhitespaceBefore(before, line)) {
119 log(ast, MSG_WS_PRECEDED, CLOSE_PARENTHESIS);
120 }
121 else if (option == PadOption.SPACE && !hasPrecedingWhitespace
122 && line[before] != OPEN_PARENTHESIS) {
123 log(ast, MSG_WS_NOT_PRECEDED, CLOSE_PARENTHESIS);
124 }
125 }
126 }
127
128 }