001/*
002 * Units of Measurement Reference Implementation
003 * Copyright (c) 2005-2024, Jean-Marie Dautelle, Werner Keil, Otavio Santana.
004 *
005 * All rights reserved.
006 *
007 * Redistribution and use in source and binary forms, with or without modification,
008 * are permitted provided that the following conditions are met:
009 *
010 * 1. Redistributions of source code must retain the above copyright notice,
011 *    this list of conditions and the following disclaimer.
012 *
013 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
014 *    and the following disclaimer in the documentation and/or other materials provided with the distribution.
015 *
016 * 3. Neither the name of JSR-385, Indriya nor the names of their contributors may be used to endorse or promote products
017 *    derived from this software without specific prior written permission.
018 *
019 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
020 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
021 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
022 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
023 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
024 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
025 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
026 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
027 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
028 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
029 */
030/* JavaCCOptions:KEEP_LINE_COL=null */
031package tech.units.indriya.format;
032
033import javax.measure.format.MeasurementParseException;
034
035/**
036 * This exception is thrown when token errors are encountered. You can explicitly create objects of this exception type by calling the method
037 * raiseTokenException in the generated parser.
038 *
039 * You can modify this class to customize your error reporting mechanisms so long as you retain the public fields.
040 * 
041 * @author <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a>
042 * @author <a href="mailto:werner@units.tech">Werner Keil</a>
043 * @version 1.1, Sep 29, 2020
044 */
045public class TokenException extends MeasurementParseException {
046  /**
047   * The Serialization identifier for this class. Increment only if the <i>serialized</i> form of the class changes.
048   */
049  private static final long serialVersionUID = 2932151235799168061L;
050
051  /**
052   * This is the last token that has been consumed successfully. If this object has been created due to a parse error, the token following this token
053   * will (therefore) be the first error token.
054   */
055  public Token currentToken;
056
057  /**
058   * Each entry in this array is an array of integers. Each array of integers represents a sequence of tokens (by their ordinal values) that is
059   * expected at this point of the parse.
060   */
061  @SuppressWarnings("unused")
062  private int[][] expectedTokenSequences;
063
064  /**
065   * This is a reference to the "tokenImage" array of the generated parser within which the parse error occurred. This array is defined in the
066   * generated ...Constants interface.
067   */
068  @SuppressWarnings("unused")
069  private String[] tokenImage;
070  
071  /**
072   * This constructor is used by the method "raiseTokenException" in the generated parser. Calling this constructor generates a new object of this
073   * type with the fields "currentToken", "expectedTokenSequences", and "tokenImage" set.
074   */
075  public TokenException(Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal) {
076    super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal));
077    currentToken = currentTokenVal;
078    expectedTokenSequences = expectedTokenSequencesVal;
079    tokenImage = tokenImageVal;
080  }
081
082  /**
083   * The following constructors are for use by you for whatever purpose you can think of. Constructing the exception in this manner makes the
084   * exception behave in the normal way - i.e., as documented in the class "Throwable". The fields "errorToken", "expectedTokenSequences", and
085   * "tokenImage" do not contain relevant information. The JavaCC generated code does not use these constructors.
086   */
087
088  public TokenException() {
089    super("");
090  }
091
092  /** Constructor with message. */
093  public TokenException(String message) {
094    super(message);
095  }
096
097  public Token getToken() {
098        return currentToken;
099  }
100  
101  /**
102   * It uses "currentToken" and "expectedTokenSequences" to generate a parse error message and returns it. If this object has been created due to a
103   * parse error, and you do not catch it (it gets thrown from the parser) the correct error message gets displayed.
104   */
105  private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) {
106    String eol = System.getProperty("line.separator", "\n");
107    StringBuilder expected = new StringBuilder();
108    int maxSize = 0;
109    for (int[] expectedTokenSequence : expectedTokenSequences) {
110      if (maxSize < expectedTokenSequence.length) {
111        maxSize = expectedTokenSequence.length;
112      }
113      for (int anExpectedTokenSequence : expectedTokenSequence) {
114        expected.append(tokenImage[anExpectedTokenSequence]).append(' ');
115      }
116      if (expectedTokenSequence[expectedTokenSequence.length - 1] != 0) {
117        expected.append("...");
118      }
119      expected.append(eol).append("    ");
120    }
121    String retval = "Encountered \"";
122    Token tok = currentToken.next;
123    for (int i = 0; i < maxSize; i++) {
124      if (i != 0)
125        retval += " ";
126      if (tok.kind == 0) {
127        retval += tokenImage[0];
128        break;
129      }
130      retval += " " + tokenImage[tok.kind];
131      retval += " \"";
132      retval += add_escapes(tok.image);
133      retval += " \"";
134      tok = tok.next;
135    }
136    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
137    retval += "." + eol;
138    if (expectedTokenSequences.length == 1) {
139      retval += "Was expecting:" + eol + "    ";
140    } else {
141      retval += "Was expecting one of:" + eol + "    ";
142    }
143    retval += expected.toString();
144    return retval;
145  }
146
147  /**
148   * The end of line string for this machine.
149   */
150  protected String eol = System.getProperty("line.separator", "\n");
151
152  /**
153   * Used to convert raw characters to their escaped version when these raw version cannot be used as part of an ASCII string literal.
154   */
155  private static String add_escapes(String str) {
156    StringBuilder retval = new StringBuilder();
157    char ch;
158    for (int i = 0; i < str.length(); i++) {
159      switch (str.charAt(i)) {
160        case 0:
161          continue;
162        case '\b':
163          retval.append("\\b");
164          continue;
165        case '\t':
166          retval.append("\\t");
167          continue;
168        case '\n':
169          retval.append("\\n");
170          continue;
171        case '\f':
172          retval.append("\\f");
173          continue;
174        case '\r':
175          retval.append("\\r");
176          continue;
177        case '\"':
178          retval.append("\\\"");
179          continue;
180        case '\'':
181          retval.append("\\\'");
182          continue;
183        case '\\':
184          retval.append("\\\\");
185          continue;
186        default:
187          if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
188            String s = "0000" + Integer.toString(ch, 16);
189            retval.append("\\u").append(s.substring(s.length() - 4, s.length()));
190          } else {
191            retval.append(ch);
192          }
193      }
194    }
195    return retval.toString();
196  }
197
198}
199/*
200 * JavaCC - OriginalChecksum=c67b0f8ee6c642900399352b33f90efd (do not edit this
201 * line)
202 */