001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2016 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.Iterator;
025import java.util.Map;
026import java.util.Set;
027
028import com.google.common.collect.Maps;
029import com.google.common.collect.Sets;
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 = Sets.newHashSet();
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    protected final Class<?> resolveClass(String resolvableClassName,
231            String className) {
232        try {
233            return getClassResolver().resolve(resolvableClassName, className);
234        }
235        catch (final ClassNotFoundException ignored) {
236            return null;
237        }
238    }
239
240    /**
241     * Tries to load class. Logs error if unable.
242     * @param ident name of class which we try to load.
243     * @param className name of surrounding class.
244     * @return {@code Class} for a ident.
245     */
246    protected final Class<?> tryLoadClass(Token ident, String className) {
247        final Class<?> clazz = resolveClass(ident.getText(), className);
248        if (clazz == null) {
249            logLoadError(ident);
250        }
251        return clazz;
252    }
253
254    /**
255     * Common implementation for logLoadError() method.
256     * @param lineNo line number of the problem.
257     * @param columnNo column number of the problem.
258     * @param msgKey message key to use.
259     * @param values values to fill the message out.
260     */
261    protected final void logLoadErrorImpl(int lineNo, int columnNo,
262                                          String msgKey, Object... values) {
263        if (!logLoadErrors) {
264            final LocalizedMessage msg = new LocalizedMessage(lineNo,
265                                                    columnNo,
266                                                    getMessageBundle(),
267                                                    msgKey,
268                                                    values,
269                                                    getSeverityLevel(),
270                                                    getId(),
271                                                    getClass(),
272                                                    null);
273            throw new IllegalStateException(msg.getMessage());
274        }
275
276        if (!suppressLoadErrors) {
277            log(lineNo, columnNo, msgKey, values);
278        }
279    }
280
281    /**
282     * Collects the details of a package.
283     * @param ast node containing the package details
284     */
285    private void processPackage(DetailAST ast) {
286        final DetailAST nameAST = ast.getLastChild().getPreviousSibling();
287        packageFullIdent = FullIdent.createFullIdent(nameAST);
288    }
289
290    /**
291     * Collects the details of imports.
292     * @param ast node containing the import details
293     */
294    private void processImport(DetailAST ast) {
295        final FullIdent name = FullIdent.createFullIdentBelow(ast);
296        imports.add(name.getText());
297    }
298
299    /**
300     * Process type params (if any) for given class, enum or method.
301     * @param ast class, enum or method to process.
302     */
303    private void processTypeParams(DetailAST ast) {
304        final DetailAST params =
305            ast.findFirstToken(TokenTypes.TYPE_PARAMETERS);
306
307        final Map<String, AbstractClassInfo> paramsMap = Maps.newHashMap();
308        typeParams.push(paramsMap);
309
310        if (params != null) {
311            for (DetailAST child = params.getFirstChild();
312                 child != null;
313                 child = child.getNextSibling()) {
314                if (child.getType() == TokenTypes.TYPE_PARAMETER) {
315                    final String alias =
316                        child.findFirstToken(TokenTypes.IDENT).getText();
317                    final DetailAST bounds =
318                        child.findFirstToken(TokenTypes.TYPE_UPPER_BOUNDS);
319                    if (bounds != null) {
320                        final FullIdent name =
321                            FullIdent.createFullIdentBelow(bounds);
322                        final AbstractClassInfo classInfo =
323                            createClassInfo(new Token(name), currentClassName);
324                        paramsMap.put(alias, classInfo);
325                    }
326                }
327            }
328        }
329    }
330
331    /**
332     * Processes class definition.
333     * @param ast class definition to process.
334     */
335    private void processClass(DetailAST ast) {
336        final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT);
337        String innerClass = ident.getText();
338
339        if (!currentClassName.isEmpty()) {
340            innerClass = "$" + innerClass;
341        }
342        currentClassName += innerClass;
343        processTypeParams(ast);
344    }
345
346    /**
347     * Returns current class.
348     * @return name of current class.
349     */
350    protected final String getCurrentClassName() {
351        return currentClassName;
352    }
353
354    /**
355     * Creates class info for given name.
356     * @param name name of type.
357     * @param surroundingClass name of surrounding class.
358     * @return class info for given name.
359     */
360    protected final AbstractClassInfo createClassInfo(final Token name,
361                                              final String surroundingClass) {
362        final AbstractClassInfo classInfo = findClassAlias(name.getText());
363        if (classInfo != null) {
364            return new ClassAlias(name, classInfo);
365        }
366        return new RegularClass(name, surroundingClass, this);
367    }
368
369    /**
370     * Looking if a given name is alias.
371     * @param name given name
372     * @return ClassInfo for alias if it exists, null otherwise
373     */
374    protected final AbstractClassInfo findClassAlias(final String name) {
375        AbstractClassInfo classInfo = null;
376        final Iterator<Map<String, AbstractClassInfo>> iterator = typeParams.descendingIterator();
377        while (iterator.hasNext()) {
378            final Map<String, AbstractClassInfo> paramMap = iterator.next();
379            classInfo = paramMap.get(name);
380            if (classInfo != null) {
381                break;
382            }
383        }
384        return classInfo;
385    }
386
387    /**
388     * Contains class's {@code Token}.
389     */
390    protected abstract static class AbstractClassInfo {
391        /** {@code FullIdent} associated with this class. */
392        private final Token name;
393
394        /**
395         * Creates new instance of class information object.
396         * @param className token which represents class name.
397         */
398        protected AbstractClassInfo(final Token className) {
399            if (className == null) {
400                throw new IllegalArgumentException(
401                    "ClassInfo's name should be non-null");
402            }
403            name = className;
404        }
405
406        /**
407         * @return {@code Class} associated with an object.
408         */
409        public abstract Class<?> getClazz();
410
411        /**
412         * Gets class name.
413         * @return class name
414         */
415        public final Token getName() {
416            return name;
417        }
418    }
419
420    /** Represents regular classes/enums. */
421    private static final class RegularClass extends AbstractClassInfo {
422        /** Name of surrounding class. */
423        private final String surroundingClass;
424        /** The check we use to resolve classes. */
425        private final AbstractTypeAwareCheck check;
426        /** Is class loadable. */
427        private boolean loadable = true;
428        /** {@code Class} object of this class if it's loadable. */
429        private Class<?> classObj;
430
431        /**
432         * Creates new instance of of class information object.
433         * @param name {@code FullIdent} associated with new object.
434         * @param surroundingClass name of current surrounding class.
435         * @param check the check we use to load class.
436         */
437        RegularClass(final Token name,
438                             final String surroundingClass,
439                             final AbstractTypeAwareCheck check) {
440            super(name);
441            this.surroundingClass = surroundingClass;
442            this.check = check;
443        }
444
445        @Override
446        public Class<?> getClazz() {
447            if (loadable && classObj == null) {
448                setClazz(check.tryLoadClass(getName(), surroundingClass));
449            }
450            return classObj;
451        }
452
453        /**
454         * Associates {@code Class} with an object.
455         * @param clazz {@code Class} to associate with.
456         */
457        private void setClazz(Class<?> clazz) {
458            classObj = clazz;
459            loadable = clazz != null;
460        }
461
462        @Override
463        public String toString() {
464            return "RegularClass[name=" + getName()
465                + ", in class=" + surroundingClass
466                + ", loadable=" + loadable
467                + ", class=" + classObj + "]";
468        }
469    }
470
471    /** Represents type param which is "alias" for real type. */
472    private static class ClassAlias extends AbstractClassInfo {
473        /** Class information associated with the alias. */
474        private final AbstractClassInfo classInfo;
475
476        /**
477         * Creates new instance of the class.
478         * @param name token which represents name of class alias.
479         * @param classInfo class information associated with the alias.
480         */
481        ClassAlias(final Token name, AbstractClassInfo classInfo) {
482            super(name);
483            this.classInfo = classInfo;
484        }
485
486        @Override
487        public final Class<?> getClazz() {
488            return classInfo.getClazz();
489        }
490
491        @Override
492        public String toString() {
493            return "ClassAlias[alias " + getName() + " for " + classInfo.getName() + "]";
494        }
495    }
496
497    /**
498     * Represents text element with location in the text.
499     */
500    protected static class Token {
501        /** Token's column number. */
502        private final int columnNo;
503        /** Token's line number. */
504        private final int lineNo;
505        /** Token's text. */
506        private final String text;
507
508        /**
509         * Creates token.
510         * @param text token's text
511         * @param lineNo token's line number
512         * @param columnNo token's column number
513         */
514        public Token(String text, int lineNo, int columnNo) {
515            this.text = text;
516            this.lineNo = lineNo;
517            this.columnNo = columnNo;
518        }
519
520        /**
521         * Converts FullIdent to Token.
522         * @param fullIdent full ident to convert.
523         */
524        public Token(FullIdent fullIdent) {
525            text = fullIdent.getText();
526            lineNo = fullIdent.getLineNo();
527            columnNo = fullIdent.getColumnNo();
528        }
529
530        /**
531         * Gets line number of the token.
532         * @return line number of the token
533         */
534        public int getLineNo() {
535            return lineNo;
536        }
537
538        /**
539         * Gets column number of the token.
540         * @return column number of the token
541         */
542        public int getColumnNo() {
543            return columnNo;
544        }
545
546        /**
547         * Gets text of the token.
548         * @return text of the token
549         */
550        public String getText() {
551            return text;
552        }
553
554        @Override
555        public String toString() {
556            return "Token[" + text + "(" + lineNo
557                + "x" + columnNo + ")]";
558        }
559    }
560}