001    /*
002     * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
003     * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004     *
005     * This code is free software; you can redistribute it and/or modify it
006     * under the terms of the GNU General Public License version 2 only, as
007     * published by the Free Software Foundation.  Sun designates this
008     * particular file as subject to the "Classpath" exception as provided
009     * by Sun in the LICENSE file that accompanied this code.
010     *
011     * This code is distributed in the hope that it will be useful, but WITHOUT
012     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013     * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
014     * version 2 for more details (a copy is included in the LICENSE file that
015     * accompanied this code).
016     *
017     * You should have received a copy of the GNU General Public License version
018     * 2 along with this work; if not, write to the Free Software Foundation,
019     * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020     *
021     * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022     * CA 95054 USA or visit www.sun.com if you need additional information or
023     * have any questions.
024     */
025    
026    package com.sun.tools.javac.util;
027    
028    import java.util.HashMap;
029    import java.util.Locale;
030    import java.util.Map;
031    import javax.tools.JavaFileObject;
032    
033    import static com.sun.tools.javac.util.BasicDiagnosticFormatter.BasicFormatKind.*;
034    import static com.sun.tools.javac.api.DiagnosticFormatter.PositionKind.*;
035    
036    /**
037     * A basic formatter for diagnostic messages.
038     * The basic formatter will format a diagnostic according to one of three format patterns, depending on whether
039     * or not the source name and position are set. The formatter supports a printf-like string for patterns
040     * with the following special characters:
041     * <ul>
042     * <li>%b: the base of the source name
043     * <li>%f: the source name (full absolute path)
044     * <li>%l: the line number of the diagnostic, derived from the character offset
045     * <li>%c: the column number of the diagnostic, derived from the character offset
046     * <li>%o: the character offset of the diagnostic if set
047     * <li>%p: the prefix for the diagnostic, derived from the diagnostic type
048     * <li>%t: the prefix as it normally appears in standard diagnostics. In this case, no prefix is
049     *        shown if the type is ERROR and if a source name is set
050     * <li>%m: the text or the diagnostic, including any appropriate arguments
051     * <li>%_: space delimiter, useful for formatting purposes
052     * </ul>
053     */
054    public class BasicDiagnosticFormatter extends AbstractDiagnosticFormatter {
055    
056        protected Map<BasicFormatKind, String> availableFormats;
057    
058        /**
059         * Create a basic formatter based on the supplied options.
060         *
061         * @param opts list of command-line options
062         * @param msgs JavacMessages object used for i18n
063         */
064        @SuppressWarnings("fallthrough")
065        BasicDiagnosticFormatter(Options opts, JavacMessages msgs) {
066            super(msgs, opts, true);
067            initAvailableFormats();
068            String fmt = opts.get("diags");
069            if (fmt != null) {
070                String[] formats = fmt.split("\\|");
071                switch (formats.length) {
072                    case 3:
073                        availableFormats.put(DEFAULT_CLASS_FORMAT, formats[2]);
074                    case 2:
075                        availableFormats.put(DEFAULT_NO_POS_FORMAT, formats[1]);
076                    default:
077                        availableFormats.put(DEFAULT_POS_FORMAT, formats[0]);
078                }
079            }
080        }
081    
082        /**
083         * Create a standard basic formatter
084         *
085         * @param msgs JavacMessages object used for i18n
086         */
087        public BasicDiagnosticFormatter(JavacMessages msgs) {
088            super(msgs, true);
089            initAvailableFormats();
090        }
091    
092        public void initAvailableFormats() {
093            availableFormats = new HashMap<BasicFormatKind, String>();
094            availableFormats.put(DEFAULT_POS_FORMAT, "%f:%l:%_%t%m");
095            availableFormats.put(DEFAULT_NO_POS_FORMAT, "%p%m");
096            availableFormats.put(DEFAULT_CLASS_FORMAT, "%f:%_%t%m");
097        }
098    
099        public String format(JCDiagnostic d, Locale l) {
100            if (l == null)
101                l = messages.getCurrentLocale();
102            String format = selectFormat(d);
103            StringBuilder buf = new StringBuilder();
104            for (int i = 0; i < format.length(); i++) {
105                char c = format.charAt(i);
106                boolean meta = false;
107                if (c == '%' && i < format.length() - 1) {
108                    meta = true;
109                    c = format.charAt(++i);
110                }
111                buf.append(meta ? formatMeta(c, d, l) : String.valueOf(c));
112            }
113            if (displaySource(d)) {
114                buf.append("\n" + formatSourceLine(d));
115            }
116            return buf.toString();
117        }
118    
119        protected String formatMeta(char c, JCDiagnostic d, Locale l) {
120            switch (c) {
121                case 'b':
122                    return formatSource(d, false, l);
123                case 'e':
124                    return formatPosition(d, END, l);
125                case 'f':
126                    return formatSource(d, true, l);
127                case 'l':
128                    return formatPosition(d, LINE, l);
129                case 'c':
130                    return formatPosition(d, COLUMN, l);
131                case 'o':
132                    return formatPosition(d, OFFSET, l);
133                case 'p':
134                    return formatKind(d, l);
135                case 's':
136                    return formatPosition(d, START, l);
137                case 't': {
138                    boolean usePrefix;
139                    switch (d.getType()) {
140                    case FRAGMENT:
141                        usePrefix = false;
142                        break;
143                    case ERROR:
144                        usePrefix = (d.getIntPosition() == Position.NOPOS);
145                        break;
146                    default:
147                        usePrefix = true;
148                    }
149                    if (usePrefix)
150                        return formatKind(d, l);
151                    else
152                        return "";
153                }
154                case 'm':
155                    return formatMessage(d, l);
156                case '_':
157                    return " ";
158                case '%':
159                    return "%";
160                default:
161                    return String.valueOf(c);
162            }
163        }
164    
165        private String selectFormat(JCDiagnostic d) {
166            DiagnosticSource source = d.getDiagnosticSource();
167            String format = availableFormats.get(DEFAULT_NO_POS_FORMAT);
168            if (source != null) {
169                if (d.getIntPosition() != Position.NOPOS) {
170                    format = availableFormats.get(DEFAULT_POS_FORMAT);
171                } else if (source.getFile() != null &&
172                           source.getFile().getKind() == JavaFileObject.Kind.CLASS) {
173                    format = availableFormats.get(DEFAULT_CLASS_FORMAT);
174                }
175            }
176            return format;
177        }
178    
179        /**
180         * This enum contains all the kinds of formatting patterns supported
181         * by a basic diagnostic formatter.
182         */
183        public enum BasicFormatKind {
184            /**
185            * A format string to be used for diagnostics with a given position.
186            */
187            DEFAULT_POS_FORMAT,
188            /**
189            * A format string to be used for diagnostics without a given position.
190            */
191            DEFAULT_NO_POS_FORMAT,
192            /**
193            * A format string to be used for diagnostics regarding classfiles
194            */
195            DEFAULT_CLASS_FORMAT;
196        }
197    }