001    /*
002     * Copyright 1999-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.io.*;
029    import java.util.Arrays;
030    import java.util.HashSet;
031    import java.util.Map;
032    import java.util.Set;
033    import javax.tools.DiagnosticListener;
034    import javax.tools.JavaFileObject;
035    
036    import com.sun.tools.javac.file.JavacFileManager;
037    import com.sun.tools.javac.tree.JCTree;
038    import com.sun.tools.javac.api.DiagnosticFormatter;
039    import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
040    import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType;
041    
042    /** A class for error logs. Reports errors and warnings, and
043     *  keeps track of error numbers and positions.
044     *
045     *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
046     *  you write code that depends on this, you do so at your own risk.
047     *  This code and its internal interfaces are subject to change or
048     *  deletion without notice.</b>
049     */
050    public class Log extends AbstractLog {
051        /** The context key for the log. */
052        public static final Context.Key<Log> logKey
053            = new Context.Key<Log>();
054    
055        /** The context key for the output PrintWriter. */
056        public static final Context.Key<PrintWriter> outKey =
057            new Context.Key<PrintWriter>();
058    
059        //@Deprecated
060        public final PrintWriter errWriter;
061    
062        //@Deprecated
063        public final PrintWriter warnWriter;
064    
065        //@Deprecated
066        public final PrintWriter noticeWriter;
067    
068        /** The maximum number of errors/warnings that are reported.
069         */
070        public final int MaxErrors;
071        public final int MaxWarnings;
072    
073        /** Switch: prompt user on each error.
074         */
075        public boolean promptOnError;
076    
077        /** Switch: emit warning messages.
078         */
079        public boolean emitWarnings;
080    
081        /** Print stack trace on errors?
082         */
083        public boolean dumpOnError;
084    
085        /** Print multiple errors for same source locations.
086         */
087        public boolean multipleErrors;
088    
089        /**
090         * Diagnostic listener, if provided through programmatic
091         * interface to javac (JSR 199).
092         */
093        protected DiagnosticListener<? super JavaFileObject> diagListener;
094    
095        /**
096         * Formatter for diagnostics
097         */
098        private DiagnosticFormatter<JCDiagnostic> diagFormatter;
099    
100        /**
101         * Keys for expected diagnostics
102         */
103        public Set<String> expectDiagKeys;
104    
105        /**
106         * JavacMessages object used for localization
107         */
108        private JavacMessages messages;
109    
110        /** Construct a log with given I/O redirections.
111         */
112        @Deprecated
113        protected Log(Context context, PrintWriter errWriter, PrintWriter warnWriter, PrintWriter noticeWriter) {
114            super(JCDiagnostic.Factory.instance(context));
115            context.put(logKey, this);
116            this.errWriter = errWriter;
117            this.warnWriter = warnWriter;
118            this.noticeWriter = noticeWriter;
119    
120            Options options = Options.instance(context);
121            this.dumpOnError = options.get("-doe") != null;
122            this.promptOnError = options.get("-prompt") != null;
123            this.emitWarnings = options.get("-Xlint:none") == null;
124            this.MaxErrors = getIntOption(options, "-Xmaxerrs", 100);
125            this.MaxWarnings = getIntOption(options, "-Xmaxwarns", 100);
126    
127            boolean rawDiagnostics = options.get("rawDiagnostics") != null;
128            messages = JavacMessages.instance(context);
129            this.diagFormatter = rawDiagnostics ? new RawDiagnosticFormatter(options) :
130                                                  new BasicDiagnosticFormatter(options, messages);
131            @SuppressWarnings("unchecked") // FIXME
132            DiagnosticListener<? super JavaFileObject> dl =
133                context.get(DiagnosticListener.class);
134            this.diagListener = dl;
135    
136            String ek = options.get("expectKeys");
137            if (ek != null)
138                expectDiagKeys = new HashSet<String>(Arrays.asList(ek.split(", *")));
139        }
140        // where
141            private int getIntOption(Options options, String optionName, int defaultValue) {
142                String s = options.get(optionName);
143                try {
144                    if (s != null) return Integer.parseInt(s);
145                } catch (NumberFormatException e) {
146                    // silently ignore ill-formed numbers
147                }
148                return defaultValue;
149            }
150    
151        /** The default writer for diagnostics
152         */
153        static final PrintWriter defaultWriter(Context context) {
154            PrintWriter result = context.get(outKey);
155            if (result == null)
156                context.put(outKey, result = new PrintWriter(System.err));
157            return result;
158        }
159    
160        /** Construct a log with default settings.
161         */
162        protected Log(Context context) {
163            this(context, defaultWriter(context));
164        }
165    
166        /** Construct a log with all output redirected.
167         */
168        protected Log(Context context, PrintWriter defaultWriter) {
169            this(context, defaultWriter, defaultWriter, defaultWriter);
170        }
171    
172        /** Get the Log instance for this context. */
173        public static Log instance(Context context) {
174            Log instance = context.get(logKey);
175            if (instance == null)
176                instance = new Log(context);
177            return instance;
178        }
179    
180        /** The number of errors encountered so far.
181         */
182        public int nerrors = 0;
183    
184        /** The number of warnings encountered so far.
185         */
186        public int nwarnings = 0;
187    
188        /** A set of all errors generated so far. This is used to avoid printing an
189         *  error message more than once. For each error, a pair consisting of the
190         *  source file name and source code position of the error is added to the set.
191         */
192        private Set<Pair<JavaFileObject, Integer>> recorded = new HashSet<Pair<JavaFileObject,Integer>>();
193    
194        public boolean hasDiagnosticListener() {
195            return diagListener != null;
196        }
197    
198        public void setEndPosTable(JavaFileObject name, Map<JCTree, Integer> table) {
199            name.getClass(); // null check
200            getSource(name).setEndPosTable(table);
201        }
202    
203        /** Return current sourcefile.
204         */
205        public JavaFileObject currentSourceFile() {
206            return source == null ? null : source.getFile();
207        }
208    
209        /** Flush the logs
210         */
211        public void flush() {
212            errWriter.flush();
213            warnWriter.flush();
214            noticeWriter.flush();
215        }
216    
217        /** Returns true if an error needs to be reported for a given
218         * source name and pos.
219         */
220        protected boolean shouldReport(JavaFileObject file, int pos) {
221            if (multipleErrors || file == null)
222                return true;
223    
224            Pair<JavaFileObject,Integer> coords = new Pair<JavaFileObject,Integer>(file, pos);
225            boolean shouldReport = !recorded.contains(coords);
226            if (shouldReport)
227                recorded.add(coords);
228            return shouldReport;
229        }
230    
231        /** Prompt user after an error.
232         */
233        public void prompt() {
234            if (promptOnError) {
235                System.err.println(getLocalizedString("resume.abort"));
236                char ch;
237                try {
238                    while (true) {
239                        switch (System.in.read()) {
240                        case 'a': case 'A':
241                            System.exit(-1);
242                            return;
243                        case 'r': case 'R':
244                            return;
245                        case 'x': case 'X':
246                            throw new AssertionError("user abort");
247                        default:
248                        }
249                    }
250                } catch (IOException e) {}
251            }
252        }
253    
254        /** Print the faulty source code line and point to the error.
255         *  @param pos   Buffer index of the error position, must be on current line
256         */
257        private void printErrLine(int pos, PrintWriter writer) {
258            String line = (source == null ? null : source.getLine(pos));
259            if (line == null)
260                return;
261            int col = source.getColumnNumber(pos, false);
262    
263            printLines(writer, line);
264            for (int i = 0; i < col - 1; i++) {
265                writer.print((line.charAt(i) == '\t') ? "\t" : " ");
266            }
267            writer.println("^");
268            writer.flush();
269        }
270    
271        /** Print the text of a message, translating newlines appropriately
272         *  for the platform.
273         */
274        public static void printLines(PrintWriter writer, String msg) {
275            int nl;
276            while ((nl = msg.indexOf('\n')) != -1) {
277                writer.println(msg.substring(0, nl));
278                msg = msg.substring(nl+1);
279            }
280            if (msg.length() != 0) writer.println(msg);
281        }
282    
283        protected void directError(String key, Object... args) {
284            printLines(errWriter, getLocalizedString(key, args));
285            errWriter.flush();
286        }
287    
288        /** Report a warning that cannot be suppressed.
289         *  @param pos    The source position at which to report the warning.
290         *  @param key    The key for the localized warning message.
291         *  @param args   Fields of the warning message.
292         */
293        public void strictWarning(DiagnosticPosition pos, String key, Object ... args) {
294            writeDiagnostic(diags.warning(source, pos, key, args));
295            nwarnings++;
296        }
297    
298        /**
299         * Common diagnostic handling.
300         * The diagnostic is counted, and depending on the options and how many diagnostics have been
301         * reported so far, the diagnostic may be handed off to writeDiagnostic.
302         */
303        public void report(JCDiagnostic diagnostic) {
304            if (expectDiagKeys != null)
305                expectDiagKeys.remove(diagnostic.getCode());
306    
307            switch (diagnostic.getType()) {
308            case FRAGMENT:
309                throw new IllegalArgumentException();
310    
311            case NOTE:
312                // Print out notes only when we are permitted to report warnings
313                // Notes are only generated at the end of a compilation, so should be small
314                // in number.
315                if (emitWarnings || diagnostic.isMandatory()) {
316                    writeDiagnostic(diagnostic);
317                }
318                break;
319    
320            case WARNING:
321                if (emitWarnings || diagnostic.isMandatory()) {
322                    if (nwarnings < MaxWarnings) {
323                        writeDiagnostic(diagnostic);
324                        nwarnings++;
325                    }
326                }
327                break;
328    
329            case ERROR:
330                if (nerrors < MaxErrors
331                    && shouldReport(diagnostic.getSource(), diagnostic.getIntPosition())) {
332                    writeDiagnostic(diagnostic);
333                    nerrors++;
334                }
335                break;
336            }
337        }
338    
339        /**
340         * Write out a diagnostic.
341         */
342        protected void writeDiagnostic(JCDiagnostic diag) {
343            if (diagListener != null) {
344                try {
345                    diagListener.report(diag);
346                    return;
347                }
348                catch (Throwable t) {
349                    throw new ClientCodeException(t);
350                }
351            }
352    
353            PrintWriter writer = getWriterForDiagnosticType(diag.getType());
354    
355            printLines(writer, diagFormatter.format(diag, messages.getCurrentLocale()));
356    
357            if (promptOnError) {
358                switch (diag.getType()) {
359                case ERROR:
360                case WARNING:
361                    prompt();
362                }
363            }
364    
365            if (dumpOnError)
366                new RuntimeException().printStackTrace(writer);
367    
368            writer.flush();
369        }
370    
371        @Deprecated
372        protected PrintWriter getWriterForDiagnosticType(DiagnosticType dt) {
373            switch (dt) {
374            case FRAGMENT:
375                throw new IllegalArgumentException();
376    
377            case NOTE:
378                return noticeWriter;
379    
380            case WARNING:
381                return warnWriter;
382    
383            case ERROR:
384                return errWriter;
385    
386            default:
387                throw new Error();
388            }
389        }
390    
391        /** Find a localized string in the resource bundle.
392         *  @param key    The key for the localized string.
393         *  @param args   Fields to substitute into the string.
394         */
395        public static String getLocalizedString(String key, Object ... args) {
396            return JavacMessages.getDefaultLocalizedString("compiler.misc." + key, args);
397        }
398    
399    /***************************************************************************
400     * raw error messages without internationalization; used for experimentation
401     * and quick prototyping
402     ***************************************************************************/
403    
404        /** print an error or warning message:
405         */
406        private void printRawError(int pos, String msg) {
407            if (source == null || pos == Position.NOPOS) {
408                printLines(errWriter, "error: " + msg);
409            } else {
410                int line = source.getLineNumber(pos);
411                JavaFileObject file = source.getFile();
412                if (file != null)
413                    printLines(errWriter,
414                               JavacFileManager.getJavacFileName(file) + ":" +
415                               line + ": " + msg);
416                printErrLine(pos, errWriter);
417            }
418            errWriter.flush();
419        }
420    
421        /** report an error:
422         */
423        public void rawError(int pos, String msg) {
424            if (nerrors < MaxErrors && shouldReport(currentSourceFile(), pos)) {
425                printRawError(pos, msg);
426                prompt();
427                nerrors++;
428            }
429            errWriter.flush();
430        }
431    
432        /** report a warning:
433         */
434        public void rawWarning(int pos, String msg) {
435            if (nwarnings < MaxWarnings && emitWarnings) {
436                printRawError(pos, "warning: " + msg);
437            }
438            prompt();
439            nwarnings++;
440            errWriter.flush();
441        }
442    
443        public static String format(String fmt, Object... args) {
444            return String.format((java.util.Locale)null, fmt, args);
445        }
446    
447    }