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.ENUM_DEF) {
162            // perhaps it was inner class
163            int dotIdx = currentClassName.lastIndexOf('$');
164            if (dotIdx == -1) {
165                // perhaps just a class
166                dotIdx = currentClassName.lastIndexOf('.');
167            }
168            if (dotIdx == -1) {
169                // looks like a topmost class
170                currentClassName = "";
171            }
172            else {
173                currentClassName = currentClassName.substring(0, dotIdx);
174            }
175            typeParams.pop();
176        }
177        else if (ast.getType() == TokenTypes.METHOD_DEF) {
178            typeParams.pop();
179        }
180    }
181
182    /**
183     * Is exception is unchecked (subclass of {@code RuntimeException}
184     * or {@code Error}.
185     *
186     * @param exception {@code Class} of exception to check
187     * @return true  if exception is unchecked
188     *         false if exception is checked
189     */
190    protected static boolean isUnchecked(Class<?> exception) {
191        return isSubclass(exception, RuntimeException.class)
192            || isSubclass(exception, Error.class);
193    }
194
195    /**
196     * Checks if one class is subclass of another.
197     *
198     * @param child {@code Class} of class
199     *               which should be child
200     * @param parent {@code Class} of class
201     *                which should be parent
202     * @return true  if aChild is subclass of aParent
203     *         false otherwise
204     */
205    protected static boolean isSubclass(Class<?> child, Class<?> parent) {
206        return parent != null && child != null
207            && parent.isAssignableFrom(child);
208    }
209
210    /**
211     * @return {@code ClassResolver} for current tree.
212     */
213    private ClassResolver getClassResolver() {
214        if (classResolver == null) {
215            classResolver =
216                new ClassResolver(getClassLoader(),
217                                  packageFullIdent.getText(),
218                                  imports);
219        }
220        return classResolver;
221    }
222
223    /**
224     * Attempts to resolve the Class for a specified name.
225     * @param resolvableClassName name of the class to resolve
226     * @param className name of surrounding class.
227     * @return the resolved class or {@code null}
228     *          if unable to resolve the class.
229     */
230    // -@cs[ForbidWildcardAsReturnType] The class is deprecated and will be removed soon.
231    protected final Class<?> resolveClass(String resolvableClassName,
232            String className) {
233        try {
234            return getClassResolver().resolve(resolvableClassName, className);
235        }
236        catch (final ClassNotFoundException ignored) {
237            return null;
238        }
239    }
240
241    /**
242     * Tries to load class. Logs error if unable.
243     * @param ident name of class which we try to load.
244     * @param className name of surrounding class.
245     * @return {@code Class} for a ident.
246     */
247    // -@cs[ForbidWildcardAsReturnType] The class is deprecated and will be removed soon.
248    protected final Class<?> tryLoadClass(Token ident, String className) {
249        final Class<?> clazz = resolveClass(ident.getText(), className);
250        if (clazz == null) {
251            logLoadError(ident);
252        }
253        return clazz;
254    }
255
256    /**
257     * Common implementation for logLoadError() method.
258     * @param lineNo line number of the problem.
259     * @param columnNo column number of the problem.
260     * @param msgKey message key to use.
261     * @param values values to fill the message out.
262     */
263    protected final void logLoadErrorImpl(int lineNo, int columnNo,
264                                          String msgKey, Object... values) {
265        if (!logLoadErrors) {
266            final LocalizedMessage msg = new LocalizedMessage(lineNo,
267                                                    columnNo,
268                                                    getMessageBundle(),
269                                                    msgKey,
270                                                    values,
271                                                    getSeverityLevel(),
272                                                    getId(),
273                                                    getClass(),
274                                                    null);
275            throw new IllegalStateException(msg.getMessage());
276        }
277
278        if (!suppressLoadErrors) {
279            log(lineNo, columnNo, msgKey, values);
280        }
281    }
282
283    /**
284     * Collects the details of a package.
285     * @param ast node containing the package details
286     */
287    private void processPackage(DetailAST ast) {
288        final DetailAST nameAST = ast.getLastChild().getPreviousSibling();
289        packageFullIdent = FullIdent.createFullIdent(nameAST);
290    }
291
292    /**
293     * Collects the details of imports.
294     * @param ast node containing the import details
295     */
296    private void processImport(DetailAST ast) {
297        final FullIdent name = FullIdent.createFullIdentBelow(ast);
298        imports.add(name.getText());
299    }
300
301    /**
302     * Process type params (if any) for given class, enum or method.
303     * @param ast class, enum or method to process.
304     */
305    private void processTypeParams(DetailAST ast) {
306        final DetailAST params =
307            ast.findFirstToken(TokenTypes.TYPE_PARAMETERS);
308
309        final Map<String, AbstractClassInfo> paramsMap = new HashMap<>();
310        typeParams.push(paramsMap);
311
312        if (params != null) {
313            for (DetailAST child = params.getFirstChild();
314                 child != null;
315                 child = child.getNextSibling()) {
316                if (child.getType() == TokenTypes.TYPE_PARAMETER) {
317                    final String alias =
318                        child.findFirstToken(TokenTypes.IDENT).getText();
319                    final DetailAST bounds =
320                        child.findFirstToken(TokenTypes.TYPE_UPPER_BOUNDS);
321                    if (bounds != null) {
322                        final FullIdent name =
323                            FullIdent.createFullIdentBelow(bounds);
324                        final AbstractClassInfo classInfo =
325                            createClassInfo(new Token(name), currentClassName);
326                        paramsMap.put(alias, classInfo);
327                    }
328                }
329            }
330        }
331    }
332
333    /**
334     * Processes class definition.
335     * @param ast class definition to process.
336     */
337    private void processClass(DetailAST ast) {
338        final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT);
339        String innerClass = ident.getText();
340
341        if (!currentClassName.isEmpty()) {
342            innerClass = "$" + innerClass;
343        }
344        currentClassName += innerClass;
345        processTypeParams(ast);
346    }
347
348    /**
349     * Returns current class.
350     * @return name of current class.
351     */
352    protected final String getCurrentClassName() {
353        return currentClassName;
354    }
355
356    /**
357     * Creates class info for given name.
358     * @param name name of type.
359     * @param surroundingClass name of surrounding class.
360     * @return class info for given name.
361     */
362    protected final AbstractClassInfo createClassInfo(final Token name,
363                                              final String surroundingClass) {
364        final AbstractClassInfo classInfo = findClassAlias(name.getText());
365        if (classInfo != null) {
366            return new ClassAlias(name, classInfo);
367        }
368        return new RegularClass(name, surroundingClass, this);
369    }
370
371    /**
372     * Looking if a given name is alias.
373     * @param name given name
374     * @return ClassInfo for alias if it exists, null otherwise
375     */
376    protected final AbstractClassInfo findClassAlias(final String name) {
377        AbstractClassInfo classInfo = null;
378        final Iterator<Map<String, AbstractClassInfo>> iterator = typeParams.descendingIterator();
379        while (iterator.hasNext()) {
380            final Map<String, AbstractClassInfo> paramMap = iterator.next();
381            classInfo = paramMap.get(name);
382            if (classInfo != null) {
383                break;
384            }
385        }
386        return classInfo;
387    }
388
389    /**
390     * Contains class's {@code Token}.
391     */
392    protected abstract static class AbstractClassInfo {
393        /** {@code FullIdent} associated with this class. */
394        private final Token name;
395
396        /**
397         * Creates new instance of class information object.
398         * @param className token which represents class name.
399         */
400        protected AbstractClassInfo(final Token className) {
401            if (className == null) {
402                throw new IllegalArgumentException(
403                    "ClassInfo's name should be non-null");
404            }
405            name = className;
406        }
407
408        /**
409         * @return {@code Class} associated with an object.
410         */
411        // -@cs[ForbidWildcardAsReturnType] The class is deprecated and will be removed soon.
412        public abstract Class<?> getClazz();
413
414        /**
415         * Gets class name.
416         * @return class name
417         */
418        public final Token getName() {
419            return name;
420        }
421    }
422
423    /** Represents regular classes/enums. */
424    private static final class RegularClass extends AbstractClassInfo {
425        /** Name of surrounding class. */
426        private final String surroundingClass;
427        /** The check we use to resolve classes. */
428        private final AbstractTypeAwareCheck check;
429        /** Is class loadable. */
430        private boolean loadable = true;
431        /** {@code Class} object of this class if it's loadable. */
432        private Class<?> classObj;
433
434        /**
435         * Creates new instance of of class information object.
436         * @param name {@code FullIdent} associated with new object.
437         * @param surroundingClass name of current surrounding class.
438         * @param check the check we use to load class.
439         */
440        RegularClass(final Token name,
441                             final String surroundingClass,
442                             final AbstractTypeAwareCheck check) {
443            super(name);
444            this.surroundingClass = surroundingClass;
445            this.check = check;
446        }
447
448        @Override
449        public Class<?> getClazz() {
450            if (loadable && classObj == null) {
451                setClazz(check.tryLoadClass(getName(), surroundingClass));
452            }
453            return classObj;
454        }
455
456        /**
457         * Associates {@code Class} with an object.
458         * @param clazz {@code Class} to associate with.
459         */
460        private void setClazz(Class<?> clazz) {
461            classObj = clazz;
462            loadable = clazz != null;
463        }
464
465        @Override
466        public String toString() {
467            return "RegularClass[name=" + getName()
468                + ", in class=" + surroundingClass
469                + ", loadable=" + loadable
470                + ", class=" + classObj + "]";
471        }
472    }
473
474    /** Represents type param which is "alias" for real type. */
475    private static class ClassAlias extends AbstractClassInfo {
476        /** Class information associated with the alias. */
477        private final AbstractClassInfo classInfo;
478
479        /**
480         * Creates new instance of the class.
481         * @param name token which represents name of class alias.
482         * @param classInfo class information associated with the alias.
483         */
484        ClassAlias(final Token name, AbstractClassInfo classInfo) {
485            super(name);
486            this.classInfo = classInfo;
487        }
488
489        @Override
490        public final Class<?> getClazz() {
491            return classInfo.getClazz();
492        }
493
494        @Override
495        public String toString() {
496            return "ClassAlias[alias " + getName() + " for " + classInfo.getName() + "]";
497        }
498    }
499
500    /**
501     * Represents text element with location in the text.
502     */
503    protected static class Token {
504        /** Token's column number. */
505        private final int columnNo;
506        /** Token's line number. */
507        private final int lineNo;
508        /** Token's text. */
509        private final String text;
510
511        /**
512         * Creates token.
513         * @param text token's text
514         * @param lineNo token's line number
515         * @param columnNo token's column number
516         */
517        public Token(String text, int lineNo, int columnNo) {
518            this.text = text;
519            this.lineNo = lineNo;
520            this.columnNo = columnNo;
521        }
522
523        /**
524         * Converts FullIdent to Token.
525         * @param fullIdent full ident to convert.
526         */
527        public Token(FullIdent fullIdent) {
528            text = fullIdent.getText();
529            lineNo = fullIdent.getLineNo();
530            columnNo = fullIdent.getColumnNo();
531        }
532
533        /**
534         * Gets line number of the token.
535         * @return line number of the token
536         */
537        public int getLineNo() {
538            return lineNo;
539        }
540
541        /**
542         * Gets column number of the token.
543         * @return column number of the token
544         */
545        public int getColumnNo() {
546            return columnNo;
547        }
548
549        /**
550         * Gets text of the token.
551         * @return text of the token
552         */
553        public String getText() {
554            return text;
555        }
556
557        @Override
558        public String toString() {
559            return "Token[" + text + "(" + lineNo
560                + "x" + columnNo + ")]";
561        }
562    }
563}