001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 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.checks;
021
022import java.util.ArrayDeque;
023import java.util.Deque;
024import java.util.HashMap;
025import java.util.HashSet;
026import java.util.Iterator;
027import java.util.Map;
028import java.util.Set;
029
030import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
031import com.puppycrawl.tools.checkstyle.api.DetailAST;
032import com.puppycrawl.tools.checkstyle.api.FullIdent;
033import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
034import com.puppycrawl.tools.checkstyle.api.TokenTypes;
035
036/**
037 * Abstract class that endeavours to maintain type information for the Java
038 * file being checked. It provides helper methods for performing type
039 * information functions.
040 *
041 * @author Oliver Burn
042 * @deprecated Checkstyle is not type aware tool and all Checks derived from this
043 *     class are potentially unstable.
044 */
045@Deprecated
046public abstract class AbstractTypeAwareCheck extends AbstractCheck {
047    /** Stack of maps for type params. */
048    private final Deque<Map<String, AbstractClassInfo>> typeParams = new ArrayDeque<>();
049
050    /** Imports details. **/
051    private final Set<String> imports = new HashSet<>();
052
053    /** Full identifier for package of the method. **/
054    private FullIdent packageFullIdent;
055
056    /** Name of current class. */
057    private String currentClassName;
058
059    /** {@code ClassResolver} instance for current tree. */
060    private ClassResolver classResolver;
061
062    /**
063     * Whether to log class loading errors to the checkstyle report
064     * instead of throwing a RTE.
065     *
066     * <p>Logging errors will avoid stopping checkstyle completely
067     * because of a typo in javadoc. However, with modern IDEs that
068     * support automated refactoring and generate javadoc this will
069     * occur rarely, so by default we assume a configuration problem
070     * in the checkstyle classpath and throw an exception.
071     *
072     * <p>This configuration option was triggered by bug 1422462.
073     */
074    private boolean logLoadErrors = true;
075
076    /**
077     * Whether to show class loading errors in the checkstyle report.
078     * Request ID 1491630
079     */
080    private boolean suppressLoadErrors;
081
082    /**
083     * Called to process an AST when visiting it.
084     * @param ast the AST to process. Guaranteed to not be PACKAGE_DEF or
085     *             IMPORT tokens.
086     */
087    protected abstract void processAST(DetailAST ast);
088
089    /**
090     * Logs error if unable to load class information.
091     * Abstract, should be overridden in subclasses.
092     * @param ident class name for which we can no load class.
093     */
094    protected abstract void logLoadError(Token ident);
095
096    /**
097     * Controls whether to log class loading errors to the checkstyle report
098     * instead of throwing a RTE.
099     *
100     * @param logLoadErrors true if errors should be logged
101     */
102    public final void setLogLoadErrors(boolean logLoadErrors) {
103        this.logLoadErrors = logLoadErrors;
104    }
105
106    /**
107     * Controls whether to show class loading errors in the checkstyle report.
108     *
109     * @param suppressLoadErrors true if errors shouldn't be shown
110     */
111    public final void setSuppressLoadErrors(boolean suppressLoadErrors) {
112        this.suppressLoadErrors = suppressLoadErrors;
113    }
114
115    @Override
116    public final int[] getRequiredTokens() {
117        return new int[] {
118            TokenTypes.PACKAGE_DEF,
119            TokenTypes.IMPORT,
120            TokenTypes.CLASS_DEF,
121            TokenTypes.INTERFACE_DEF,
122            TokenTypes.ENUM_DEF,
123        };
124    }
125
126    @Override
127    public void beginTree(DetailAST rootAST) {
128        packageFullIdent = FullIdent.createFullIdent(null);
129        imports.clear();
130        // add java.lang.* since it's always imported
131        imports.add("java.lang.*");
132        classResolver = null;
133        currentClassName = "";
134        typeParams.clear();
135    }
136
137    @Override
138    public final void visitToken(DetailAST ast) {
139        if (ast.getType() == TokenTypes.PACKAGE_DEF) {
140            processPackage(ast);
141        }
142        else if (ast.getType() == TokenTypes.IMPORT) {
143            processImport(ast);
144        }
145        else if (ast.getType() == TokenTypes.CLASS_DEF
146                 || ast.getType() == TokenTypes.INTERFACE_DEF
147                 || ast.getType() == TokenTypes.ENUM_DEF) {
148            processClass(ast);
149        }
150        else {
151            if (ast.getType() == TokenTypes.METHOD_DEF) {
152                processTypeParams(ast);
153            }
154            processAST(ast);
155        }
156    }
157
158    @Override
159    public final void leaveToken(DetailAST ast) {
160        if (ast.getType() == TokenTypes.CLASS_DEF
161            || ast.getType() == TokenTypes.INTERFACE_DEF
162            || ast.getType() == TokenTypes.ENUM_DEF) {
163            // perhaps it was inner class
164            int dotIdx = currentClassName.lastIndexOf('$');
165            if (dotIdx == -1) {
166                // perhaps just a class
167                dotIdx = currentClassName.lastIndexOf('.');
168            }
169            if (dotIdx == -1) {
170                // looks like a topmost class
171                currentClassName = "";
172            }
173            else {
174                currentClassName = currentClassName.substring(0, dotIdx);
175            }
176            typeParams.pop();
177        }
178        else if (ast.getType() == TokenTypes.METHOD_DEF) {
179            typeParams.pop();
180        }
181    }
182
183    /**
184     * Is exception is unchecked (subclass of {@code RuntimeException}
185     * or {@code Error}.
186     *
187     * @param exception {@code Class} of exception to check
188     * @return true  if exception is unchecked
189     *         false if exception is checked
190     */
191    protected static boolean isUnchecked(Class<?> exception) {
192        return isSubclass(exception, RuntimeException.class)
193            || isSubclass(exception, Error.class);
194    }
195
196    /**
197     * Checks if one class is subclass of another.
198     *
199     * @param child {@code Class} of class
200     *               which should be child
201     * @param parent {@code Class} of class
202     *                which should be parent
203     * @return true  if aChild is subclass of aParent
204     *         false otherwise
205     */
206    protected static boolean isSubclass(Class<?> child, Class<?> parent) {
207        return parent != null && child != null
208            && parent.isAssignableFrom(child);
209    }
210
211    /**
212     * @return {@code ClassResolver} for current tree.
213     */
214    private ClassResolver getClassResolver() {
215        if (classResolver == null) {
216            classResolver =
217                new ClassResolver(getClassLoader(),
218                                  packageFullIdent.getText(),
219                                  imports);
220        }
221        return classResolver;
222    }
223
224    /**
225     * Attempts to resolve the Class for a specified name.
226     * @param resolvableClassName name of the class to resolve
227     * @param className name of surrounding class.
228     * @return the resolved class or {@code null}
229     *          if unable to resolve the class.
230     */
231    // -@cs[ForbidWildcardAsReturnType] The class is deprecated and will be removed soon.
232    protected final Class<?> resolveClass(String resolvableClassName,
233            String className) {
234        Class<?> clazz;
235        try {
236            clazz = getClassResolver().resolve(resolvableClassName, className);
237        }
238        catch (final ClassNotFoundException ignored) {
239            clazz = null;
240        }
241        return clazz;
242    }
243
244    /**
245     * Tries to load class. Logs error if unable.
246     * @param ident name of class which we try to load.
247     * @param className name of surrounding class.
248     * @return {@code Class} for a ident.
249     */
250    // -@cs[ForbidWildcardAsReturnType] The class is deprecated and will be removed soon.
251    protected final Class<?> tryLoadClass(Token ident, String className) {
252        final Class<?> clazz = resolveClass(ident.getText(), className);
253        if (clazz == null) {
254            logLoadError(ident);
255        }
256        return clazz;
257    }
258
259    /**
260     * Common implementation for logLoadError() method.
261     * @param lineNo line number of the problem.
262     * @param columnNo column number of the problem.
263     * @param msgKey message key to use.
264     * @param values values to fill the message out.
265     */
266    protected final void logLoadErrorImpl(int lineNo, int columnNo,
267                                          String msgKey, Object... values) {
268        if (!logLoadErrors) {
269            final LocalizedMessage msg = new LocalizedMessage(lineNo,
270                                                    columnNo,
271                                                    getMessageBundle(),
272                                                    msgKey,
273                                                    values,
274                                                    getSeverityLevel(),
275                                                    getId(),
276                                                    getClass(),
277                                                    null);
278            throw new IllegalStateException(msg.getMessage());
279        }
280
281        if (!suppressLoadErrors) {
282            log(lineNo, columnNo, msgKey, values);
283        }
284    }
285
286    /**
287     * Collects the details of a package.
288     * @param ast node containing the package details
289     */
290    private void processPackage(DetailAST ast) {
291        final DetailAST nameAST = ast.getLastChild().getPreviousSibling();
292        packageFullIdent = FullIdent.createFullIdent(nameAST);
293    }
294
295    /**
296     * Collects the details of imports.
297     * @param ast node containing the import details
298     */
299    private void processImport(DetailAST ast) {
300        final FullIdent name = FullIdent.createFullIdentBelow(ast);
301        imports.add(name.getText());
302    }
303
304    /**
305     * Process type params (if any) for given class, enum or method.
306     * @param ast class, enum or method to process.
307     */
308    private void processTypeParams(DetailAST ast) {
309        final DetailAST params =
310            ast.findFirstToken(TokenTypes.TYPE_PARAMETERS);
311
312        final Map<String, AbstractClassInfo> paramsMap = new HashMap<>();
313        typeParams.push(paramsMap);
314
315        if (params != null) {
316            for (DetailAST child = params.getFirstChild();
317                 child != null;
318                 child = child.getNextSibling()) {
319                if (child.getType() == TokenTypes.TYPE_PARAMETER) {
320                    final String alias =
321                        child.findFirstToken(TokenTypes.IDENT).getText();
322                    final DetailAST bounds =
323                        child.findFirstToken(TokenTypes.TYPE_UPPER_BOUNDS);
324                    if (bounds != null) {
325                        final FullIdent name =
326                            FullIdent.createFullIdentBelow(bounds);
327                        final AbstractClassInfo classInfo =
328                            createClassInfo(new Token(name), currentClassName);
329                        paramsMap.put(alias, classInfo);
330                    }
331                }
332            }
333        }
334    }
335
336    /**
337     * Processes class definition.
338     * @param ast class definition to process.
339     */
340    private void processClass(DetailAST ast) {
341        final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT);
342        String innerClass = ident.getText();
343
344        if (!currentClassName.isEmpty()) {
345            innerClass = "$" + innerClass;
346        }
347        currentClassName += innerClass;
348        processTypeParams(ast);
349    }
350
351    /**
352     * Returns current class.
353     * @return name of current class.
354     */
355    protected final String getCurrentClassName() {
356        return currentClassName;
357    }
358
359    /**
360     * Creates class info for given name.
361     * @param name name of type.
362     * @param surroundingClass name of surrounding class.
363     * @return class info for given name.
364     */
365    protected final AbstractClassInfo createClassInfo(final Token name,
366                                              final String surroundingClass) {
367        final AbstractClassInfo result;
368        final AbstractClassInfo classInfo = findClassAlias(name.getText());
369        if (classInfo == null) {
370            result = new RegularClass(name, surroundingClass, this);
371        }
372        else {
373            result = new ClassAlias(name, classInfo);
374        }
375        return result;
376    }
377
378    /**
379     * Looking if a given name is alias.
380     * @param name given name
381     * @return ClassInfo for alias if it exists, null otherwise
382     */
383    protected final AbstractClassInfo findClassAlias(final String name) {
384        AbstractClassInfo classInfo = null;
385        final Iterator<Map<String, AbstractClassInfo>> iterator = typeParams.descendingIterator();
386        while (iterator.hasNext()) {
387            final Map<String, AbstractClassInfo> paramMap = iterator.next();
388            classInfo = paramMap.get(name);
389            if (classInfo != null) {
390                break;
391            }
392        }
393        return classInfo;
394    }
395
396    /**
397     * Contains class's {@code Token}.
398     */
399    protected abstract static class AbstractClassInfo {
400        /** {@code FullIdent} associated with this class. */
401        private final Token name;
402
403        /**
404         * Creates new instance of class information object.
405         * @param className token which represents class name.
406         */
407        protected AbstractClassInfo(final Token className) {
408            if (className == null) {
409                throw new IllegalArgumentException(
410                    "ClassInfo's name should be non-null");
411            }
412            name = className;
413        }
414
415        /**
416         * @return {@code Class} associated with an object.
417         */
418        // -@cs[ForbidWildcardAsReturnType] The class is deprecated and will be removed soon.
419        public abstract Class<?> getClazz();
420
421        /**
422         * Gets class name.
423         * @return class name
424         */
425        public final Token getName() {
426            return name;
427        }
428    }
429
430    /** Represents regular classes/enums. */
431    private static final class RegularClass extends AbstractClassInfo {
432        /** Name of surrounding class. */
433        private final String surroundingClass;
434        /** The check we use to resolve classes. */
435        private final AbstractTypeAwareCheck check;
436        /** Is class loadable. */
437        private boolean loadable = true;
438        /** {@code Class} object of this class if it's loadable. */
439        private Class<?> classObj;
440
441        /**
442         * Creates new instance of of class information object.
443         * @param name {@code FullIdent} associated with new object.
444         * @param surroundingClass name of current surrounding class.
445         * @param check the check we use to load class.
446         */
447        RegularClass(final Token name,
448                             final String surroundingClass,
449                             final AbstractTypeAwareCheck check) {
450            super(name);
451            this.surroundingClass = surroundingClass;
452            this.check = check;
453        }
454
455        @Override
456        public Class<?> getClazz() {
457            if (loadable && classObj == null) {
458                setClazz(check.tryLoadClass(getName(), surroundingClass));
459            }
460            return classObj;
461        }
462
463        /**
464         * Associates {@code Class} with an object.
465         * @param clazz {@code Class} to associate with.
466         */
467        private void setClazz(Class<?> clazz) {
468            classObj = clazz;
469            loadable = clazz != null;
470        }
471
472        @Override
473        public String toString() {
474            return "RegularClass[name=" + getName()
475                + ", in class=" + surroundingClass
476                + ", loadable=" + loadable
477                + ", class=" + classObj + "]";
478        }
479    }
480
481    /** Represents type param which is "alias" for real type. */
482    private static class ClassAlias extends AbstractClassInfo {
483        /** Class information associated with the alias. */
484        private final AbstractClassInfo classInfo;
485
486        /**
487         * Creates new instance of the class.
488         * @param name token which represents name of class alias.
489         * @param classInfo class information associated with the alias.
490         */
491        ClassAlias(final Token name, AbstractClassInfo classInfo) {
492            super(name);
493            this.classInfo = classInfo;
494        }
495
496        @Override
497        public final Class<?> getClazz() {
498            return classInfo.getClazz();
499        }
500
501        @Override
502        public String toString() {
503            return "ClassAlias[alias " + getName() + " for " + classInfo.getName() + "]";
504        }
505    }
506
507    /**
508     * Represents text element with location in the text.
509     */
510    protected static class Token {
511        /** Token's column number. */
512        private final int columnNo;
513        /** Token's line number. */
514        private final int lineNo;
515        /** Token's text. */
516        private final String text;
517
518        /**
519         * Creates token.
520         * @param text token's text
521         * @param lineNo token's line number
522         * @param columnNo token's column number
523         */
524        public Token(String text, int lineNo, int columnNo) {
525            this.text = text;
526            this.lineNo = lineNo;
527            this.columnNo = columnNo;
528        }
529
530        /**
531         * Converts FullIdent to Token.
532         * @param fullIdent full ident to convert.
533         */
534        public Token(FullIdent fullIdent) {
535            text = fullIdent.getText();
536            lineNo = fullIdent.getLineNo();
537            columnNo = fullIdent.getColumnNo();
538        }
539
540        /**
541         * Gets line number of the token.
542         * @return line number of the token
543         */
544        public int getLineNo() {
545            return lineNo;
546        }
547
548        /**
549         * Gets column number of the token.
550         * @return column number of the token
551         */
552        public int getColumnNo() {
553            return columnNo;
554        }
555
556        /**
557         * Gets text of the token.
558         * @return text of the token
559         */
560        public String getText() {
561            return text;
562        }
563
564        @Override
565        public String toString() {
566            return "Token[" + text + "(" + lineNo
567                + "x" + columnNo + ")]";
568        }
569    }
570}