001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools.template_engine;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import org.openstreetmap.josm.data.osm.search.SearchParseError;
007import org.openstreetmap.josm.tools.template_engine.Tokenizer.Token;
008import org.openstreetmap.josm.tools.template_engine.Tokenizer.TokenType;
009
010/**
011 * Exception thrown in case of an error during template parsing.
012 *
013 * Usually caused by invalid user input.
014 */
015public class ParseError extends Exception {
016
017    private final transient Token unexpectedToken;
018
019    /**
020     * Constructs a new {@code ParseError} for an unexpected token.
021     * @param unexpectedToken the unexpected token
022     */
023    public ParseError(Token unexpectedToken) {
024        super(tr("Unexpected token ({0}) on position {1}", unexpectedToken.getType(), unexpectedToken.getPosition()));
025        this.unexpectedToken = unexpectedToken;
026    }
027
028    /**
029     * Constructs a new {@code ParseError} for an unexpected token and an expected token.
030     * @param unexpectedToken the unexpected token
031     * @param expected the expected token
032     */
033    public ParseError(Token unexpectedToken, TokenType expected) {
034        super(tr("Unexpected token on position {0}. Expected {1}, found {2}",
035                unexpectedToken.getPosition(), expected, unexpectedToken.getType()));
036        this.unexpectedToken = unexpectedToken;
037    }
038
039    /**
040     * Constructs a new {@code ParseError} from a {@link SearchParseError}.
041     * @param position the position
042     * @param e the cause
043     */
044    public ParseError(int position, SearchParseError e) {
045        super(tr("Error while parsing search expression on position {0}", position), e);
046        unexpectedToken = null;
047    }
048
049    /**
050     * Constructs a new {@code ParseError} with a generic message.
051     * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
052     */
053    public ParseError(String message) {
054        super(message);
055        unexpectedToken = null;
056    }
057
058    /**
059     * Returns the unexpected token, if any.
060     * @return the unexpected token, or null
061     */
062    public Token getUnexpectedToken() {
063        return unexpectedToken;
064    }
065
066    /**
067     * Constructs a new {@code ParseError} for an unexpected character.
068     * @param expected the expected character
069     * @param found the found character
070     * @param position the position
071     * @return a new {@code ParseError}
072     */
073    public static ParseError unexpectedChar(char expected, char found, int position) {
074        return new ParseError(tr("Unexpected char on {0}. Expected {1} found {2}", position, expected, found));
075    }
076}