001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2015 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.api;
021
022import java.io.File;
023import java.util.Arrays;
024import java.util.Collection;
025import java.util.List;
026import java.util.Map;
027import java.util.regex.Pattern;
028
029import com.google.common.collect.ImmutableMap;
030import com.google.common.collect.Lists;
031import com.google.common.collect.Maps;
032import com.puppycrawl.tools.checkstyle.grammars.CommentListener;
033
034/**
035 * Represents the contents of a file.
036 *
037 * @author Oliver Burn
038 */
039public final class FileContents implements CommentListener {
040    /**
041     * The pattern to match a single line comment containing only the comment
042     * itself -- no code.
043     */
044    private static final String MATCH_SINGLELINE_COMMENT_PAT = "^\\s*//.*$";
045    /** Compiled regexp to match a single-line comment line. */
046    private static final Pattern MATCH_SINGLELINE_COMMENT = Pattern
047            .compile(MATCH_SINGLELINE_COMMENT_PAT);
048
049    /** The file name. */
050    private final String fileName;
051
052    /** The text. */
053    private final FileText text;
054
055    /** Map of the Javadoc comments indexed on the last line of the comment.
056     * The hack is it assumes that there is only one Javadoc comment per line.
057     */
058    private final Map<Integer, TextBlock> javadocComments = Maps.newHashMap();
059    /** Map of the C++ comments indexed on the first line of the comment. */
060    private final Map<Integer, TextBlock> cppComments =
061        Maps.newHashMap();
062
063    /**
064     * Map of the C comments indexed on the first line of the comment to a list
065     * of comments on that line.
066     */
067    private final Map<Integer, List<TextBlock>> clangComments = Maps.newHashMap();
068
069    /**
070     * Creates a new {@code FileContents} instance.
071     *
072     * @param filename name of the file
073     * @param lines the contents of the file
074     * @deprecated Use {@link #FileContents(FileText)} instead
075     *     in order to preserve the original line breaks where possible.
076     */
077    @Deprecated
078    public FileContents(String filename, String... lines) {
079        fileName = filename;
080        text = FileText.fromLines(new File(filename), Arrays.asList(lines));
081    }
082
083    /**
084     * Creates a new {@code FileContents} instance.
085     *
086     * @param text the contents of the file
087     */
088    public FileContents(FileText text) {
089        fileName = text.getFile().toString();
090        this.text = new FileText(text);
091    }
092
093    @Override
094    public void reportSingleLineComment(String type, int startLineNo,
095            int startColNo) {
096        reportCppComment(startLineNo, startColNo);
097    }
098
099    @Override
100    public void reportBlockComment(String type, int startLineNo,
101            int startColNo, int endLineNo, int endColNo) {
102        reportCComment(startLineNo, startColNo, endLineNo, endColNo);
103    }
104
105    /**
106     * Report the location of a C++ style comment.
107     * @param startLineNo the starting line number
108     * @param startColNo the starting column number
109     **/
110    public void reportCppComment(int startLineNo, int startColNo) {
111        final String line = line(startLineNo - 1);
112        final String[] txt = {line.substring(startColNo)};
113        final Comment comment = new Comment(txt, startColNo, startLineNo,
114                line.length() - 1);
115        cppComments.put(startLineNo, comment);
116    }
117
118    /**
119     * Returns a map of all the C++ style comments. The key is a line number,
120     * the value is the comment {@link TextBlock} at the line.
121     * @return the Map of comments
122     */
123    public ImmutableMap<Integer, TextBlock> getCppComments() {
124        return ImmutableMap.copyOf(cppComments);
125    }
126
127    /**
128     * Report the location of a C-style comment.
129     * @param startLineNo the starting line number
130     * @param startColNo the starting column number
131     * @param endLineNo the ending line number
132     * @param endColNo the ending column number
133     **/
134    public void reportCComment(int startLineNo, int startColNo,
135            int endLineNo, int endColNo) {
136        final String[] cComment = extractCComment(startLineNo, startColNo,
137                endLineNo, endColNo);
138        final Comment comment = new Comment(cComment, startColNo, endLineNo,
139                endColNo);
140
141        // save the comment
142        if (clangComments.containsKey(startLineNo)) {
143            final List<TextBlock> entries = clangComments.get(startLineNo);
144            entries.add(comment);
145        }
146        else {
147            final List<TextBlock> entries = Lists.newArrayList();
148            entries.add(comment);
149            clangComments.put(startLineNo, entries);
150        }
151
152        // Remember if possible Javadoc comment
153        if (line(startLineNo - 1).indexOf("/**", startColNo) != -1) {
154            javadocComments.put(endLineNo - 1, comment);
155        }
156    }
157
158    /**
159     * Returns a map of all C style comments. The key is the line number, the
160     * value is a {@link List} of C style comment {@link TextBlock}s
161     * that start at that line.
162     * @return the map of comments
163     */
164    public ImmutableMap<Integer, List<TextBlock>> getCComments() {
165        return ImmutableMap.copyOf(clangComments);
166    }
167
168    /**
169     * Returns the specified C comment as a String array.
170     * @param startLineNo the starting line number
171     * @param startColNo the starting column number
172     * @param endLineNo the ending line number
173     * @param endColNo the ending column number
174     * @return C comment as a array
175     **/
176    private String[] extractCComment(int startLineNo, int startColNo,
177            int endLineNo, int endColNo) {
178        String[] retVal;
179        if (startLineNo == endLineNo) {
180            retVal = new String[1];
181            retVal[0] = line(startLineNo - 1).substring(startColNo,
182                    endColNo + 1);
183        }
184        else {
185            retVal = new String[endLineNo - startLineNo + 1];
186            retVal[0] = line(startLineNo - 1).substring(startColNo);
187            for (int i = startLineNo; i < endLineNo; i++) {
188                retVal[i - startLineNo + 1] = line(i);
189            }
190            retVal[retVal.length - 1] = line(endLineNo - 1).substring(0,
191                    endColNo + 1);
192        }
193        return retVal;
194    }
195
196    /**
197     * Returns the Javadoc comment before the specified line.
198     * A return value of {@code null} means there is no such comment.
199     * @param lineNoBefore the line number to check before
200     * @return the Javadoc comment, or {@code null} if none
201     **/
202    public TextBlock getJavadocBefore(int lineNoBefore) {
203        // Lines start at 1 to the callers perspective, so need to take off 2
204        int lineNo = lineNoBefore - 2;
205
206        // skip blank lines
207        while (lineNo > 0 && (lineIsBlank(lineNo) || lineIsComment(lineNo))) {
208            lineNo--;
209        }
210
211        return javadocComments.get(lineNo);
212    }
213
214    /**
215     * Get a single line.
216     * For internal use only, as getText().get(lineNo) is just as
217     * suitable for external use and avoids method duplication.
218     * @param lineNo the number of the line to get
219     * @return the corresponding line, without terminator
220     * @throws IndexOutOfBoundsException if lineNo is invalid
221     */
222    private String line(int lineNo) {
223        return text.get(lineNo);
224    }
225
226    /**
227     * Get the full text of the file.
228     * @return an object containing the full text of the file
229     */
230    public FileText getText() {
231        return new FileText(text);
232    }
233
234    /**
235     * Gets the lines in the file.
236     * @return the lines in the file
237     */
238    public String[] getLines() {
239        return text.toLinesArray();
240    }
241
242    /**
243     * Get the line from text of the file.
244     * @param index index of the line
245     * @return line from text of the file
246     */
247    public String getLine(int index) {
248        return text.get(index);
249    }
250
251    /**
252     * Gets the name of the file.
253     * @return the name of the file
254     */
255    public String getFileName() {
256        return fileName;
257    }
258
259    /**
260     * Getter.
261     * @return the name of the file
262     * @deprecated use {@link #getFileName} instead
263     */
264    @Deprecated
265    public String getFilename() {
266        return fileName;
267    }
268
269    /**
270     * Checks if the specified line is blank.
271     * @param lineNo the line number to check
272     * @return if the specified line consists only of tabs and spaces.
273     **/
274    public boolean lineIsBlank(int lineNo) {
275        // possible improvement: avoid garbage creation in trim()
276        return line(lineNo).trim().isEmpty();
277    }
278
279    /**
280     * Checks if the specified line is a single-line comment without code.
281     * @param lineNo  the line number to check
282     * @return if the specified line consists of only a single line comment
283     *         without code.
284     **/
285    public boolean lineIsComment(int lineNo) {
286        return MATCH_SINGLELINE_COMMENT.matcher(line(lineNo)).matches();
287    }
288
289    /**
290     * Checks if the specified position intersects with a comment.
291     * @param startLineNo the starting line number
292     * @param startColNo the starting column number
293     * @param endLineNo the ending line number
294     * @param endColNo the ending column number
295     * @return true if the positions intersects with a comment.
296     **/
297    public boolean hasIntersectionWithComment(int startLineNo,
298            int startColNo, int endLineNo, int endColNo) {
299        return hasIntersectionWithCComment(startLineNo, startColNo, endLineNo, endColNo)
300                || hasIntersectionWithCppComment(startLineNo, startColNo, endLineNo, endColNo);
301    }
302
303    /**
304     * Checks if the current file is a package-info.java file.
305     * @return true if the package file.
306     */
307    public boolean inPackageInfo() {
308        return fileName.endsWith("package-info.java");
309    }
310
311    /**
312     * Checks if the specified position intersects with a C comment.
313     * @param startLineNo the starting line number
314     * @param startColNo the starting column number
315     * @param endLineNo the ending line number
316     * @param endColNo the ending column number
317     * @return true if the positions intersects with a C comment.
318     */
319    private boolean hasIntersectionWithCComment(int startLineNo, int startColNo,
320            int endLineNo, int endColNo) {
321        // Check C comments (all comments should be checked)
322        final Collection<List<TextBlock>> values = clangComments.values();
323        for (final List<TextBlock> row : values) {
324            for (final TextBlock comment : row) {
325                if (comment.intersects(startLineNo, startColNo, endLineNo, endColNo)) {
326                    return true;
327                }
328            }
329        }
330        return false;
331    }
332
333    /**
334     * Checks if the specified position intersects with a CPP comment.
335     * @param startLineNo the starting line number
336     * @param startColNo the starting column number
337     * @param endLineNo the ending line number
338     * @param endColNo the ending column number
339     * @return true if the positions intersects with a CPP comment.
340     */
341    private boolean hasIntersectionWithCppComment(int startLineNo, int startColNo,
342            int endLineNo, int endColNo) {
343        // Check CPP comments (line searching is possible)
344        for (int lineNumber = startLineNo; lineNumber <= endLineNo;
345             lineNumber++) {
346            final TextBlock comment = cppComments.get(lineNumber);
347            if (comment != null && comment.intersects(startLineNo, startColNo,
348                    endLineNo, endColNo)) {
349                return true;
350            }
351        }
352        return false;
353    }
354}