001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2019 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;
021
022import java.io.File;
023import java.util.Arrays;
024import java.util.Collection;
025import java.util.HashMap;
026import java.util.HashSet;
027import java.util.Locale;
028import java.util.Map;
029import java.util.Set;
030import java.util.SortedSet;
031import java.util.TreeSet;
032
033import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
034import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
035import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
036import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
037import com.puppycrawl.tools.checkstyle.api.Configuration;
038import com.puppycrawl.tools.checkstyle.api.Context;
039import com.puppycrawl.tools.checkstyle.api.DetailAST;
040import com.puppycrawl.tools.checkstyle.api.ExternalResourceHolder;
041import com.puppycrawl.tools.checkstyle.api.FileContents;
042import com.puppycrawl.tools.checkstyle.api.FileText;
043import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
044import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
045
046/**
047 * Responsible for walking an abstract syntax tree and notifying interested
048 * checks at each each node.
049 *
050 */
051@FileStatefulCheck
052public final class TreeWalker extends AbstractFileSetCheck implements ExternalResourceHolder {
053
054    /** Maps from token name to ordinary checks. */
055    private final Map<String, Set<AbstractCheck>> tokenToOrdinaryChecks =
056        new HashMap<>();
057
058    /** Maps from token name to comment checks. */
059    private final Map<String, Set<AbstractCheck>> tokenToCommentChecks =
060            new HashMap<>();
061
062    /** Registered ordinary checks, that don't use comment nodes. */
063    private final Set<AbstractCheck> ordinaryChecks = new HashSet<>();
064
065    /** Registered comment checks. */
066    private final Set<AbstractCheck> commentChecks = new HashSet<>();
067
068    /** The ast filters. */
069    private final Set<TreeWalkerFilter> filters = new HashSet<>();
070
071    /** The sorted set of messages. */
072    private final SortedSet<LocalizedMessage> messages = new TreeSet<>();
073
074    /** Class loader to resolve classes with. **/
075    private ClassLoader classLoader;
076
077    /** Context of child components. */
078    private Context childContext;
079
080    /** A factory for creating submodules (i.e. the Checks) */
081    private ModuleFactory moduleFactory;
082
083    /**
084     * Creates a new {@code TreeWalker} instance.
085     */
086    public TreeWalker() {
087        setFileExtensions("java");
088    }
089
090    /**
091     * Sets classLoader to load class.
092     * @param classLoader class loader to resolve classes with.
093     */
094    public void setClassLoader(ClassLoader classLoader) {
095        this.classLoader = classLoader;
096    }
097
098    /**
099     * Sets the module factory for creating child modules (Checks).
100     * @param moduleFactory the factory
101     */
102    public void setModuleFactory(ModuleFactory moduleFactory) {
103        this.moduleFactory = moduleFactory;
104    }
105
106    @Override
107    public void finishLocalSetup() {
108        final DefaultContext checkContext = new DefaultContext();
109        checkContext.add("classLoader", classLoader);
110        checkContext.add("severity", getSeverity());
111        checkContext.add("tabWidth", String.valueOf(getTabWidth()));
112
113        childContext = checkContext;
114    }
115
116    /**
117     * {@inheritDoc} Creates child module.
118     * @noinspection ChainOfInstanceofChecks
119     */
120    @Override
121    public void setupChild(Configuration childConf)
122            throws CheckstyleException {
123        final String name = childConf.getName();
124        final Object module;
125
126        try {
127            module = moduleFactory.createModule(name);
128            if (module instanceof AutomaticBean) {
129                final AutomaticBean bean = (AutomaticBean) module;
130                bean.contextualize(childContext);
131                bean.configure(childConf);
132            }
133        }
134        catch (final CheckstyleException ex) {
135            throw new CheckstyleException("cannot initialize module " + name
136                    + " - " + ex.getMessage(), ex);
137        }
138        if (module instanceof AbstractCheck) {
139            final AbstractCheck check = (AbstractCheck) module;
140            check.init();
141            registerCheck(check);
142        }
143        else if (module instanceof TreeWalkerFilter) {
144            final TreeWalkerFilter filter = (TreeWalkerFilter) module;
145            filters.add(filter);
146        }
147        else {
148            throw new CheckstyleException(
149                "TreeWalker is not allowed as a parent of " + name
150                        + " Please review 'Parent Module' section for this Check in web"
151                        + " documentation if Check is standard.");
152        }
153    }
154
155    @Override
156    protected void processFiltered(File file, FileText fileText) throws CheckstyleException {
157        // check if already checked and passed the file
158        if (!ordinaryChecks.isEmpty() || !commentChecks.isEmpty()) {
159            final FileContents contents = getFileContents();
160            final DetailAST rootAST = JavaParser.parse(contents);
161            if (!ordinaryChecks.isEmpty()) {
162                walk(rootAST, contents, AstState.ORDINARY);
163            }
164            if (!commentChecks.isEmpty()) {
165                final DetailAST astWithComments = JavaParser.appendHiddenCommentNodes(rootAST);
166                walk(astWithComments, contents, AstState.WITH_COMMENTS);
167            }
168            if (filters.isEmpty()) {
169                addMessages(messages);
170            }
171            else {
172                final SortedSet<LocalizedMessage> filteredMessages =
173                    getFilteredMessages(file.getAbsolutePath(), contents, rootAST);
174                addMessages(filteredMessages);
175            }
176            messages.clear();
177        }
178    }
179
180    /**
181     * Returns filtered set of {@link LocalizedMessage}.
182     * @param fileName path to the file
183     * @param fileContents the contents of the file
184     * @param rootAST root AST element {@link DetailAST} of the file
185     * @return filtered set of messages
186     */
187    private SortedSet<LocalizedMessage> getFilteredMessages(
188            String fileName, FileContents fileContents, DetailAST rootAST) {
189        final SortedSet<LocalizedMessage> result = new TreeSet<>(messages);
190        for (LocalizedMessage element : messages) {
191            final TreeWalkerAuditEvent event =
192                    new TreeWalkerAuditEvent(fileContents, fileName, element, rootAST);
193            for (TreeWalkerFilter filter : filters) {
194                if (!filter.accept(event)) {
195                    result.remove(element);
196                    break;
197                }
198            }
199        }
200        return result;
201    }
202
203    /**
204     * Register a check for a given configuration.
205     * @param check the check to register
206     * @throws CheckstyleException if an error occurs
207     */
208    private void registerCheck(AbstractCheck check) throws CheckstyleException {
209        final int[] tokens;
210        final Set<String> checkTokens = check.getTokenNames();
211        if (checkTokens.isEmpty()) {
212            tokens = check.getDefaultTokens();
213        }
214        else {
215            tokens = check.getRequiredTokens();
216
217            //register configured tokens
218            final int[] acceptableTokens = check.getAcceptableTokens();
219            Arrays.sort(acceptableTokens);
220            for (String token : checkTokens) {
221                final int tokenId = TokenUtil.getTokenId(token);
222                if (Arrays.binarySearch(acceptableTokens, tokenId) >= 0) {
223                    registerCheck(token, check);
224                }
225                else {
226                    final String message = String.format(Locale.ROOT, "Token \"%s\" was "
227                            + "not found in Acceptable tokens list in check %s",
228                            token, check.getClass().getName());
229                    throw new CheckstyleException(message);
230                }
231            }
232        }
233        for (int element : tokens) {
234            registerCheck(element, check);
235        }
236        if (check.isCommentNodesRequired()) {
237            commentChecks.add(check);
238        }
239        else {
240            ordinaryChecks.add(check);
241        }
242    }
243
244    /**
245     * Register a check for a specified token id.
246     * @param tokenId the id of the token
247     * @param check the check to register
248     * @throws CheckstyleException if Check is misconfigured
249     */
250    private void registerCheck(int tokenId, AbstractCheck check) throws CheckstyleException {
251        registerCheck(TokenUtil.getTokenName(tokenId), check);
252    }
253
254    /**
255     * Register a check for a specified token name.
256     * @param token the name of the token
257     * @param check the check to register
258     * @throws CheckstyleException if Check is misconfigured
259     */
260    private void registerCheck(String token, AbstractCheck check) throws CheckstyleException {
261        if (check.isCommentNodesRequired()) {
262            tokenToCommentChecks.computeIfAbsent(token, empty -> new HashSet<>()).add(check);
263        }
264        else if (TokenUtil.isCommentType(token)) {
265            final String message = String.format(Locale.ROOT, "Check '%s' waits for comment type "
266                    + "token ('%s') and should override 'isCommentNodesRequired()' "
267                    + "method to return 'true'", check.getClass().getName(), token);
268            throw new CheckstyleException(message);
269        }
270        else {
271            tokenToOrdinaryChecks.computeIfAbsent(token, empty -> new HashSet<>()).add(check);
272        }
273    }
274
275    /**
276     * Initiates the walk of an AST.
277     * @param ast the root AST
278     * @param contents the contents of the file the AST was generated from.
279     * @param astState state of AST.
280     */
281    private void walk(DetailAST ast, FileContents contents,
282            AstState astState) {
283        notifyBegin(ast, contents, astState);
284        processIter(ast, astState);
285        notifyEnd(ast, astState);
286    }
287
288    /**
289     * Notify checks that we are about to begin walking a tree.
290     * @param rootAST the root of the tree.
291     * @param contents the contents of the file the AST was generated from.
292     * @param astState state of AST.
293     */
294    private void notifyBegin(DetailAST rootAST, FileContents contents,
295            AstState astState) {
296        final Set<AbstractCheck> checks;
297
298        if (astState == AstState.WITH_COMMENTS) {
299            checks = commentChecks;
300        }
301        else {
302            checks = ordinaryChecks;
303        }
304
305        for (AbstractCheck check : checks) {
306            check.setFileContents(contents);
307            check.clearMessages();
308            check.beginTree(rootAST);
309        }
310    }
311
312    /**
313     * Notify checks that we have finished walking a tree.
314     * @param rootAST the root of the tree.
315     * @param astState state of AST.
316     */
317    private void notifyEnd(DetailAST rootAST, AstState astState) {
318        final Set<AbstractCheck> checks;
319
320        if (astState == AstState.WITH_COMMENTS) {
321            checks = commentChecks;
322        }
323        else {
324            checks = ordinaryChecks;
325        }
326
327        for (AbstractCheck check : checks) {
328            check.finishTree(rootAST);
329            messages.addAll(check.getMessages());
330        }
331    }
332
333    /**
334     * Notify checks that visiting a node.
335     * @param ast the node to notify for.
336     * @param astState state of AST.
337     */
338    private void notifyVisit(DetailAST ast, AstState astState) {
339        final Collection<AbstractCheck> visitors = getListOfChecks(ast, astState);
340
341        if (visitors != null) {
342            for (AbstractCheck check : visitors) {
343                check.visitToken(ast);
344            }
345        }
346    }
347
348    /**
349     * Notify checks that leaving a node.
350     * @param ast
351     *        the node to notify for
352     * @param astState state of AST.
353     */
354    private void notifyLeave(DetailAST ast, AstState astState) {
355        final Collection<AbstractCheck> visitors = getListOfChecks(ast, astState);
356
357        if (visitors != null) {
358            for (AbstractCheck check : visitors) {
359                check.leaveToken(ast);
360            }
361        }
362    }
363
364    /**
365     * Method returns list of checks.
366     *
367     * @param ast
368     *            the node to notify for
369     * @param astState
370     *            state of AST.
371     * @return list of visitors
372     */
373    private Collection<AbstractCheck> getListOfChecks(DetailAST ast, AstState astState) {
374        final Collection<AbstractCheck> visitors;
375        final String tokenType = TokenUtil.getTokenName(ast.getType());
376
377        if (astState == AstState.WITH_COMMENTS) {
378            visitors = tokenToCommentChecks.get(tokenType);
379        }
380        else {
381            visitors = tokenToOrdinaryChecks.get(tokenType);
382        }
383        return visitors;
384    }
385
386    @Override
387    public void destroy() {
388        ordinaryChecks.forEach(AbstractCheck::destroy);
389        commentChecks.forEach(AbstractCheck::destroy);
390        super.destroy();
391    }
392
393    @Override
394    public Set<String> getExternalResourceLocations() {
395        final Set<String> ordinaryChecksResources =
396                getExternalResourceLocationsOfChecks(ordinaryChecks);
397        final Set<String> commentChecksResources =
398                getExternalResourceLocationsOfChecks(commentChecks);
399        final Set<String> filtersResources =
400                getExternalResourceLocationsOfFilters();
401        final int resultListSize = commentChecksResources.size()
402                + ordinaryChecksResources.size()
403                + filtersResources.size();
404        final Set<String> resourceLocations = new HashSet<>(resultListSize);
405        resourceLocations.addAll(ordinaryChecksResources);
406        resourceLocations.addAll(commentChecksResources);
407        resourceLocations.addAll(filtersResources);
408        return resourceLocations;
409    }
410
411    /**
412     * Returns a set of external configuration resource locations which are used by the filters set.
413     * @return a set of external configuration resource locations which are used by the filters set.
414     */
415    private Set<String> getExternalResourceLocationsOfFilters() {
416        final Set<String> externalConfigurationResources = new HashSet<>();
417        filters.stream().filter(filter -> filter instanceof ExternalResourceHolder)
418                .forEach(filter -> {
419                    final Set<String> checkExternalResources =
420                        ((ExternalResourceHolder) filter).getExternalResourceLocations();
421                    externalConfigurationResources.addAll(checkExternalResources);
422                });
423        return externalConfigurationResources;
424    }
425
426    /**
427     * Returns a set of external configuration resource locations which are used by the checks set.
428     * @param checks a set of checks.
429     * @return a set of external configuration resource locations which are used by the checks set.
430     */
431    private static Set<String> getExternalResourceLocationsOfChecks(Set<AbstractCheck> checks) {
432        final Set<String> externalConfigurationResources = new HashSet<>();
433        checks.stream().filter(check -> check instanceof ExternalResourceHolder).forEach(check -> {
434            final Set<String> checkExternalResources =
435                ((ExternalResourceHolder) check).getExternalResourceLocations();
436            externalConfigurationResources.addAll(checkExternalResources);
437        });
438        return externalConfigurationResources;
439    }
440
441    /**
442     * Processes a node calling interested checks at each node.
443     * Uses iterative algorithm.
444     * @param root the root of tree for process
445     * @param astState state of AST.
446     */
447    private void processIter(DetailAST root, AstState astState) {
448        DetailAST curNode = root;
449        while (curNode != null) {
450            notifyVisit(curNode, astState);
451            DetailAST toVisit = curNode.getFirstChild();
452            while (curNode != null && toVisit == null) {
453                notifyLeave(curNode, astState);
454                toVisit = curNode.getNextSibling();
455                curNode = curNode.getParent();
456            }
457            curNode = toVisit;
458        }
459    }
460
461    /**
462     * State of AST.
463     * Indicates whether tree contains certain nodes.
464     */
465    private enum AstState {
466
467        /**
468         * Ordinary tree.
469         */
470        ORDINARY,
471
472        /**
473         * AST contains comment nodes.
474         */
475        WITH_COMMENTS,
476
477    }
478
479}