aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java
blob: 6aa0ad823e24fe632ff88d17902c2cd016ddc932 (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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2017 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
////////////////////////////////////////////////////////////////////////////////

package com.puppycrawl.tools.checkstyle.api;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.puppycrawl.tools.checkstyle.grammars.CommentListener;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;

/**
 * Represents the contents of a file.
 *
 * @author Oliver Burn
 */
public final class FileContents implements CommentListener {
    /**
     * The pattern to match a single line comment containing only the comment
     * itself -- no code.
     */
    private static final String MATCH_SINGLELINE_COMMENT_PAT = "^\\s*//.*$";
    /** Compiled regexp to match a single-line comment line. */
    private static final Pattern MATCH_SINGLELINE_COMMENT = Pattern
            .compile(MATCH_SINGLELINE_COMMENT_PAT);

    /** The file name. */
    private final String fileName;

    /** The text. */
    private final FileText text;

    /** Map of the Javadoc comments indexed on the last line of the comment.
     * The hack is it assumes that there is only one Javadoc comment per line.
     */
    private final Map<Integer, TextBlock> javadocComments = new HashMap<>();
    /** Map of the C++ comments indexed on the first line of the comment. */
    private final Map<Integer, TextBlock> cppComments = new HashMap<>();

    /**
     * Map of the C comments indexed on the first line of the comment to a list
     * of comments on that line.
     */
    private final Map<Integer, List<TextBlock>> clangComments = new HashMap<>();

    /**
     * Creates a new {@code FileContents} instance.
     *
     * @param filename name of the file
     * @param lines the contents of the file
     * @deprecated Use {@link #FileContents(FileText)} instead
     *     in order to preserve the original line breaks where possible.
     */
    @Deprecated
    public FileContents(String filename, String... lines) {
        fileName = filename;
        text = new FileText(new File(filename), Arrays.asList(lines));
    }

    /**
     * Creates a new {@code FileContents} instance.
     *
     * @param text the contents of the file
     */
    public FileContents(FileText text) {
        fileName = text.getFile().toString();
        this.text = new FileText(text);
    }

    @Override
    public void reportSingleLineComment(String type, int startLineNo,
            int startColNo) {
        reportSingleLineComment(startLineNo, startColNo);
    }

    /**
     * Report the location of a single line comment.
     * @param startLineNo the starting line number
     * @param startColNo the starting column number
     **/
    public void reportSingleLineComment(int startLineNo, int startColNo) {
        final String line = line(startLineNo - 1);
        final String[] txt = {line.substring(startColNo)};
        final Comment comment = new Comment(txt, startColNo, startLineNo,
                line.length() - 1);
        cppComments.put(startLineNo, comment);
    }

    @Override
    public void reportBlockComment(String type, int startLineNo,
            int startColNo, int endLineNo, int endColNo) {
        reportBlockComment(startLineNo, startColNo, endLineNo, endColNo);
    }

    /**
     * Report the location of a block comment.
     * @param startLineNo the starting line number
     * @param startColNo the starting column number
     * @param endLineNo the ending line number
     * @param endColNo the ending column number
     **/
    private void reportBlockComment(int startLineNo, int startColNo,
            int endLineNo, int endColNo) {
        final String[] cComment = extractBlockComment(startLineNo, startColNo,
                endLineNo, endColNo);
        final Comment comment = new Comment(cComment, startColNo, endLineNo,
                endColNo);

        // save the comment
        if (clangComments.containsKey(startLineNo)) {
            final List<TextBlock> entries = clangComments.get(startLineNo);
            entries.add(comment);
        }
        else {
            final List<TextBlock> entries = new ArrayList<>();
            entries.add(comment);
            clangComments.put(startLineNo, entries);
        }

        // Remember if possible Javadoc comment
        final String firstLine = line(startLineNo - 1);
        if (firstLine.contains("/**") && !firstLine.contains("/**/")) {
            javadocComments.put(endLineNo - 1, comment);
        }
    }

    /**
     * Report the location of a C++ style comment.
     * @param startLineNo the starting line number
     * @param startColNo the starting column number
     * @deprecated Use {@link #reportSingleLineComment(int, int)} instead.
     **/
    @Deprecated
    public void reportCppComment(int startLineNo, int startColNo) {
        reportSingleLineComment(startLineNo, startColNo);
    }

    /**
     * Returns a map of all the C++ style comments. The key is a line number,
     * the value is the comment {@link TextBlock} at the line.
     * @return the Map of comments
     * @deprecated Use {@link #getSingleLineComments()} instead.
     */
    @Deprecated
    public Map<Integer, TextBlock> getCppComments() {
        return getSingleLineComments();
    }

    /**
     * Returns a map of all the single line comments. The key is a line number,
     * the value is the comment {@link TextBlock} at the line.
     * @return the Map of comments
     */
    public Map<Integer, TextBlock> getSingleLineComments() {
        return Collections.unmodifiableMap(cppComments);
    }

    /**
     * Report the location of a C-style comment.
     * @param startLineNo the starting line number
     * @param startColNo the starting column number
     * @param endLineNo the ending line number
     * @param endColNo the ending column number
     * @deprecated Use {@link #reportBlockComment(int, int, int, int)} instead.
     **/
    // -@cs[AbbreviationAsWordInName] Can't change yet since class is API.
    @Deprecated
    public void reportCComment(int startLineNo, int startColNo,
            int endLineNo, int endColNo) {
        reportBlockComment(startLineNo, startColNo, endLineNo, endColNo);
    }

    /**
     * Returns a map of all C style comments. The key is the line number, the
     * value is a {@link List} of C style comment {@link TextBlock}s
     * that start at that line.
     * @return the map of comments
     * @deprecated Use {@link #getBlockComments()} instead.
     */
    // -@cs[AbbreviationAsWordInName] Can't change yet since class is API.
    @Deprecated
    public Map<Integer, List<TextBlock>> getCComments() {
        return getBlockComments();
    }

    /**
     * Returns a map of all block comments. The key is the line number, the
     * value is a {@link List} of block comment {@link TextBlock}s
     * that start at that line.
     * @return the map of comments
     */
    public Map<Integer, List<TextBlock>> getBlockComments() {
        return Collections.unmodifiableMap(clangComments);
    }

    /**
     * Returns the specified block comment as a String array.
     * @param startLineNo the starting line number
     * @param startColNo the starting column number
     * @param endLineNo the ending line number
     * @param endColNo the ending column number
     * @return block comment as an array
     **/
    private String[] extractBlockComment(int startLineNo, int startColNo,
            int endLineNo, int endColNo) {
        final String[] returnValue;
        if (startLineNo == endLineNo) {
            returnValue = new String[1];
            returnValue[0] = line(startLineNo - 1).substring(startColNo,
                    endColNo + 1);
        }
        else {
            returnValue = new String[endLineNo - startLineNo + 1];
            returnValue[0] = line(startLineNo - 1).substring(startColNo);
            for (int i = startLineNo; i < endLineNo; i++) {
                returnValue[i - startLineNo + 1] = line(i);
            }
            returnValue[returnValue.length - 1] = line(endLineNo - 1).substring(0,
                    endColNo + 1);
        }
        return returnValue;
    }

    /**
     * Returns the Javadoc comment before the specified line.
     * A return value of {@code null} means there is no such comment.
     * @param lineNoBefore the line number to check before
     * @return the Javadoc comment, or {@code null} if none
     **/
    public TextBlock getJavadocBefore(int lineNoBefore) {
        // Lines start at 1 to the callers perspective, so need to take off 2
        int lineNo = lineNoBefore - 2;

        // skip blank lines
        while (lineNo > 0 && (lineIsBlank(lineNo) || lineIsComment(lineNo))) {
            lineNo--;
        }

        return javadocComments.get(lineNo);
    }

    /**
     * Get a single line.
     * For internal use only, as getText().get(lineNo) is just as
     * suitable for external use and avoids method duplication.
     * @param lineNo the number of the line to get
     * @return the corresponding line, without terminator
     * @throws IndexOutOfBoundsException if lineNo is invalid
     */
    private String line(int lineNo) {
        return text.get(lineNo);
    }

    /**
     * Get the full text of the file.
     * @return an object containing the full text of the file
     */
    public FileText getText() {
        return new FileText(text);
    }

    /**
     * Gets the lines in the file.
     * @return the lines in the file
     */
    public String[] getLines() {
        return text.toLinesArray();
    }

    /**
     * Get the line from text of the file.
     * @param index index of the line
     * @return line from text of the file
     */
    public String getLine(int index) {
        return text.get(index);
    }

    /**
     * Gets the name of the file.
     * @return the name of the file
     */
    public String getFileName() {
        return fileName;
    }

    /**
     * Checks if the specified line is blank.
     * @param lineNo the line number to check
     * @return if the specified line consists only of tabs and spaces.
     **/
    public boolean lineIsBlank(int lineNo) {
        return CommonUtils.isBlank(line(lineNo));
    }

    /**
     * Checks if the specified line is a single-line comment without code.
     * @param lineNo  the line number to check
     * @return if the specified line consists of only a single line comment
     *         without code.
     **/
    public boolean lineIsComment(int lineNo) {
        return MATCH_SINGLELINE_COMMENT.matcher(line(lineNo)).matches();
    }

    /**
     * Checks if the specified position intersects with a comment.
     * @param startLineNo the starting line number
     * @param startColNo the starting column number
     * @param endLineNo the ending line number
     * @param endColNo the ending column number
     * @return true if the positions intersects with a comment.
     **/
    public boolean hasIntersectionWithComment(int startLineNo,
            int startColNo, int endLineNo, int endColNo) {
        return hasIntersectionWithBlockComment(startLineNo, startColNo, endLineNo, endColNo)
                || hasIntersectionWithSingleLineComment(startLineNo, startColNo, endLineNo,
                        endColNo);
    }

    /**
     * Checks if the current file is a package-info.java file.
     * @return true if the package file.
     */
    public boolean inPackageInfo() {
        return fileName.endsWith("package-info.java");
    }

    /**
     * Checks if the specified position intersects with a block comment.
     * @param startLineNo the starting line number
     * @param startColNo the starting column number
     * @param endLineNo the ending line number
     * @param endColNo the ending column number
     * @return true if the positions intersects with a block comment.
     */
    private boolean hasIntersectionWithBlockComment(int startLineNo, int startColNo,
            int endLineNo, int endColNo) {
        boolean hasIntersection = false;
        // Check C comments (all comments should be checked)
        final Collection<List<TextBlock>> values = clangComments.values();
        for (final List<TextBlock> row : values) {
            for (final TextBlock comment : row) {
                if (comment.intersects(startLineNo, startColNo, endLineNo, endColNo)) {
                    hasIntersection = true;
                    break;
                }
            }
            if (hasIntersection) {
                break;
            }
        }
        return hasIntersection;
    }

    /**
     * Checks if the specified position intersects with a single line comment.
     * @param startLineNo the starting line number
     * @param startColNo the starting column number
     * @param endLineNo the ending line number
     * @param endColNo the ending column number
     * @return true if the positions intersects with a single line comment.
     */
    private boolean hasIntersectionWithSingleLineComment(int startLineNo, int startColNo,
            int endLineNo, int endColNo) {
        boolean hasIntersection = false;
        // Check CPP comments (line searching is possible)
        for (int lineNumber = startLineNo; lineNumber <= endLineNo;
             lineNumber++) {
            final TextBlock comment = cppComments.get(lineNumber);
            if (comment != null && comment.intersects(startLineNo, startColNo,
                    endLineNo, endColNo)) {
                hasIntersection = true;
                break;
            }
        }
        return hasIntersection;
    }
}