001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 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.filters;
021
022import java.util.Objects;
023import java.util.regex.Pattern;
024
025import javax.annotation.Nullable;
026
027import com.puppycrawl.tools.checkstyle.api.AuditEvent;
028import com.puppycrawl.tools.checkstyle.api.Filter;
029
030/**
031 * This filter element is immutable and processes {@link AuditEvent}
032 * objects based on the criteria of file, check, module id, line, and
033 * column. It rejects an AuditEvent if the following match:
034 * <ul>
035 *   <li>the event's file name; and</li>
036 *   <li>the check name or the module identifier; and</li>
037 *   <li>(optionally) the event's line is in the filter's line CSV; and</li>
038 *   <li>(optionally) the check's columns is in the filter's column CSV.</li>
039 * </ul>
040 * If none of the criteria are configured, the element accepts all events.
041 *
042 */
043public class SuppressFilterElement implements Filter {
044
045    /** The regexp to match file names against. */
046    private final Pattern fileRegexp;
047
048    /** The regexp to match check names against. */
049    private final Pattern checkRegexp;
050
051    /** The regexp to match message names against. */
052    private final Pattern messageRegexp;
053
054    /** Module id filter. */
055    private final String moduleId;
056
057    /** Line number filter. */
058    private final CsvFilterElement lineFilter;
059
060    /** CSV for line number filter. */
061    private final String linesCsv;
062
063    /** Column number filter. */
064    private final CsvFilterElement columnFilter;
065
066    /** CSV for column number filter. */
067    private final String columnsCsv;
068
069    /**
070     * Creates a {@code SuppressFilterElement} instance.
071     *
072     * @param files regular expression for filtered file names
073     * @param checks regular expression for filtered check classes
074     * @param message regular expression for messages.
075     * @param moduleId the module id
076     * @param lines CSV for lines
077     * @param columns CSV for columns
078     */
079    public SuppressFilterElement(Pattern files, Pattern checks, Pattern message, String moduleId,
080            String lines, String columns) {
081        fileRegexp = files;
082        checkRegexp = checks;
083        messageRegexp = message;
084        this.moduleId = moduleId;
085        if (lines == null) {
086            linesCsv = null;
087            lineFilter = null;
088        }
089        else {
090            linesCsv = lines;
091            lineFilter = new CsvFilterElement(lines);
092        }
093        if (columns == null) {
094            columnsCsv = null;
095            columnFilter = null;
096        }
097        else {
098            columnsCsv = columns;
099            columnFilter = new CsvFilterElement(columns);
100        }
101    }
102
103    /**
104     * Constructs a {@code SuppressFilterElement} using regular expressions
105     * as {@code String}s. These are internally compiled into {@code Pattern}
106     * objects and passed to the main constructor.
107     *
108     * @param files   regular expression for names of filtered files.
109     * @param checks  regular expression for filtered check classes.
110     * @param message regular expression for messages.
111     * @param modId   the id
112     * @param lines   lines CSV values and ranges for line number filtering.
113     * @param columns columns CSV values and ranges for column number filtering.
114     */
115    public SuppressFilterElement(String files, String checks,
116                                 String message, String modId, String lines, String columns) {
117        this(toPattern(files), toPattern(checks), toPattern(message),
118                modId, lines, columns);
119    }
120
121    /**
122     * Converts a string into a compiled {@code Pattern}, or return {@code null}
123     * if input is {@code null}.
124     *
125     * @param regex the regular expression as a string, may be {@code null}.
126     * @return the compiled {@code Pattern}, or {@code null} if input is {@code null}.
127     */
128    private static Pattern toPattern(String regex) {
129        final Pattern result;
130        if (regex != null) {
131            result = Pattern.compile(regex);
132        }
133        else {
134            result = null;
135        }
136        return result;
137    }
138
139    @Override
140    public boolean accept(AuditEvent event) {
141        return isNotConfigured()
142                || !isFileNameAndModuleNameMatching(event)
143                || !isMessageNameMatching(event)
144                || !isLineAndColumnMatching(event);
145    }
146
147    /**
148     * Checks whether none of the suppression criteria have been configured. With every
149     * criterion unset, each individual matching check trivially reports a match, which would
150     * otherwise make {@link #accept(AuditEvent)} reject every event. An element with nothing
151     * to match against must instead accept all events.
152     *
153     * @return true if no suppression criteria are set
154     */
155    private boolean isNotConfigured() {
156        return fileRegexp == null && checkRegexp == null && messageRegexp == null
157                && moduleId == null && lineFilter == null && columnFilter == null;
158    }
159
160    /**
161     * Is matching by file name, module id, and Check name.
162     *
163     * @param event event
164     * @return true if it is matching
165     */
166    private boolean isFileNameAndModuleNameMatching(AuditEvent event) {
167        return event.getFileName() != null
168                && (fileRegexp == null || isFileMatch(event.getFileName()))
169                && event.getViolation() != null
170                && (moduleId == null || moduleId.equals(event.getModuleId()))
171                && (checkRegexp == null || checkRegexp.matcher(event.getSourceName()).find());
172    }
173
174    /**
175     * Checks if the given file name matches the file regexp.
176     * If there is no match and the OS uses backslashes (Windows),
177     * it converts backslashes to forward slashes and tries again.
178     *
179     * @param fileName the name of the file to check
180     * @return true if the file matches the regexp
181     */
182    private boolean isFileMatch(String fileName) {
183        return fileRegexp.matcher(fileName).find()
184                || matchAfterSlashNormalization(fileName);
185    }
186
187    /**
188     * Performance optimization: returns the file regex match against the
189     * backslash-normalized file name, but only when normalization changed the
190     * string. {@link String#replace(char, char)} returns the same instance when
191     * there is nothing to replace, so guarding against that case avoids running
192     * the same regex twice on identical input.
193     *
194     * @param fileName the original file name
195     * @return true if the normalized file name matches the file regex
196     */
197    private boolean matchAfterSlashNormalization(String fileName) {
198        final String slashesFileName = fileName.replace('\\', '/');
199        return !slashesFileName.equals(fileName)
200                && fileRegexp.matcher(slashesFileName).find();
201    }
202
203    /**
204     * Is matching by message.
205     *
206     * @param event event
207     * @return true if it is matching or not set.
208     */
209    private boolean isMessageNameMatching(AuditEvent event) {
210        return messageRegexp == null || messageRegexp.matcher(event.getMessage()).find();
211    }
212
213    /**
214     * Whether line and column match.
215     *
216     * @param event event to process.
217     * @return true if line and column are matching or not set.
218     */
219    private boolean isLineAndColumnMatching(AuditEvent event) {
220        return lineFilter == null && columnFilter == null
221                || lineFilter != null && lineFilter.accept(event.getLine())
222                || columnFilter != null && columnFilter.accept(event.getColumn());
223    }
224
225    @Override
226    public int hashCode() {
227        return Objects.hash(getPatternSafely(fileRegexp), getPatternSafely(checkRegexp),
228                getPatternSafely(messageRegexp), moduleId, linesCsv, columnsCsv);
229    }
230
231    @Override
232    public boolean equals(Object other) {
233        if (this == other) {
234            return true;
235        }
236        if (other == null || getClass() != other.getClass()) {
237            return false;
238        }
239        final SuppressFilterElement suppressElement = (SuppressFilterElement) other;
240        return Objects.equals(getPatternSafely(fileRegexp),
241                    getPatternSafely(suppressElement.fileRegexp))
242                && Objects.equals(getPatternSafely(checkRegexp),
243                    getPatternSafely(suppressElement.checkRegexp))
244                && Objects.equals(getPatternSafely(messageRegexp),
245                    getPatternSafely(suppressElement.messageRegexp))
246                && Objects.equals(moduleId, suppressElement.moduleId)
247                && Objects.equals(linesCsv, suppressElement.linesCsv)
248                && Objects.equals(columnsCsv, suppressElement.columnsCsv);
249    }
250
251    /**
252     * Util method to get pattern String value from Pattern object safely, return null if
253     * pattern object is null.
254     *
255     * @param pattern pattern object
256     * @return value of pattern or null
257     */
258    @Nullable
259    private static String getPatternSafely(Pattern pattern) {
260        String result = null;
261        if (pattern != null) {
262            result = pattern.pattern();
263        }
264        return result;
265    }
266
267}