It uses "currentToken" and "expectedTokenSequences" to generate a parse
error message and returns it.  If this object has been created
due to a parse error, and you do not catch it (it gets thrown
from the parser) the correct error message
gets displayed.
196667
private static String initialise(Token currentToken,
                           int[][] expectedTokenSequences,
                           String[] tokenImage) {
    StringBuffer expected = new StringBuffer();
    
    //149852 - This was removed due to a findBugs error we felt was worthy of a change.
    //Added in a doPrivileged call around the getProperty call
    String eol;
    if(System.getSecurityManager() != null){
    	eol = AccessController.doPrivileged(
                new PrivilegedAction<String>(){
                    @Override
                    public String run() {
                        return System.getProperty("line.separator", "\n");
                    }
                }
  		  );
    } else {
    	eol = System.getProperty("line.separator", "\n");
    }
    int maxSize = 0;
    for (int i = 0; i < expectedTokenSequences.length; i++) {
      if (maxSize < expectedTokenSequences[i].length) {
        maxSize = expectedTokenSequences[i].length;
      }
      for (int j = 0; j < expectedTokenSequences[i].length; j++) {
        expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
      }
      if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
        expected.append("...");
      }
      expected.append(eol).append("    ");
    }
    String retval = "Encountered \"";
    Token tok = currentToken.next;
    for (int i = 0; i < maxSize; i++) {
      if (i != 0) retval += " ";
      if (tok.kind == 0) {
        retval += tokenImage[0];
        break;
      }
      retval += " " + tokenImage[tok.kind];
      retval += " \"";
      retval += add_escapes(tok.image);
      retval += " \"";
      tok = tok.next;
    }
    retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
    retval += "." + eol;
    if (expectedTokenSequences.length == 1) {
      retval += "Was expecting:" + eol + "    ";
    } else {
      retval += "Was expecting one of:" + eol + "    ";
    }
    retval += expected.toString();
    return retval;
  }
558903
def unexpected(parser, at_token=None):
    # type: (Parser, Optional[Any]) -> GraphQLSyntaxError
    """"""
    token = at_token or parser.token
    return GraphQLSyntaxError(
        parser.source, token.start, u"Unexpected {}".format(get_token_desc(token))
    )
513412
function expectSpaceAfter(token, pattern) {
            const nextToken = sourceCode.getTokenAfter(token);

            if (nextToken &&
                (CHECK_TYPE.test(nextToken.type) || pattern.test(nextToken.value)) &&
                !isCloseParenOfTemplate(nextToken) &&
                astUtils.isTokenOnSameLine(token, nextToken) &&
                !sourceCode.isSpaceBetweenTokens(token, nextToken)
            ) {
                context.report({
                    loc: token.loc.start,
                    messageId: "expectedAfter",
                    data: token,
                    fix(fixer) {
                        return fixer.insertTextAfter(token, " ");
                    }
                });
            }
        }
1071778
public Token expect(@Nonnull String expected, @Nonnull TokenValidator validator) throws IOException {
        if (!hasNext()) {
            throw eof("Expected %s, got end of file", expected);
        } else if (validator.validate(unreadToken)) {
            lastToken = unreadToken;
            unreadToken = null;
            return lastToken;
        }
        throw failure(unreadToken, "Expected %s, but got '%s'", expected, Strings.escape(unreadToken.asString()));
    }
808255
function errorEnhancement(inputMessage) {
  var message = inputMessage; // eslint-disable-line
  var outputMessage = null; // eslint-disable-line

  // if the input message is an array or object
  if (inputMessage !== null
    && !isNaN(inputMessage)
    && typeof inputMessage !== 'string') {
    message = JSON.stringify(inputMessage);
  }

  // gauentee string convertion, null and other..
  message = String(message);

  // if message includes
  if (message.includes('Compiled contract not found')) {
    outputMessage = 'This could be due to a contract with the same name being compiled. Wafr doesnt allow two contracts with the same name. Look to see if any of your contracts have the same name.';
  }

  // if message includes
  if (message.includes('invalid JUMP')) {
    outputMessage = `This can be caused by many things. One main cause is a 'throw' flag being used somewhere in execution.

    This can be caused by:

    1. A 'throw' flag being used somewhere in execution (a function your calling)
    2. Sending ether to a contract which does not have the 'payable' modifier on the fallback:
        function () payable {}
    3. A send or transaction was out of gas
    `;
  }

  // if message includes
  if (message.includes('invalid opcode') || message.includes('invalid op code')) {
    outputMessage = 'This can be caused by a contract which compiles fine, but doesnt execute properly in the Ethereum Virtual Machine. Such as using a `0x0` as an address.';
  }

  // if message includes
  if (message.includes('out of gas')) {
    outputMessage = `This error can be due to various scenarios:

    1. A error caused somewhere in your contract
    2. An error with the EVM module (npm: 'ethereumjs-vm')
    3. An error caused by the wafr module
    4. An error with the node simulation module (npm: 'ethereumjs-testrpc')
    5. A wafr account actually being out of gas
    6. The 'payable' flag not being used on a contract your sending ether too (common)

    If you cannot resolve this issue with reasonable investigation,
    report the error at:

    http://github.com/SilentCicero/wafr/issues

    If you believe the error is caused by the test node infrastructure,
    report the error at:

    http://github.com/ethereumjs/testrpc

    If you believe the error is caused by the EVM module, report the error
    at:

    http://github.com/ethereumjs/ethereumjs-vm
    `;
  }

  // return output message
  return outputMessage;
}
722329
final ParseErrorDetails renderError() {
    final int errorIndex = toIndex(currentErrorAt);
    final String encounteredName = getEncountered();
    final ArrayList<String> errorStrings = Lists.arrayList(errors.size());
    for (Object error : errors) {
      errorStrings.add(String.valueOf(error));
    }
    switch (currentErrorType) {
    case UNEXPECTED :
      return new EmptyParseError(errorIndex, encounteredName) {
        @Override public String getUnexpected() {
          return errorStrings.get(0);
        }
      };
    case FAILURE :
      return new EmptyParseError(errorIndex, encounteredName) {
        @Override public String getFailureMessage() {
          return errorStrings.get(0);
        }
      };
    case EXPECTING:
    case MISSING:
    case DELIMITING:
      return new EmptyParseError(errorIndex, encounteredName) {
        @Override public List<String> getExpected() {
          return errorStrings;
        }
      };
    default:
      return new EmptyParseError(errorIndex, encounteredName);
    }
  }
420156
static String formatParseException(String pExpressionString,
                                       ParseException pExc) {
        // Generate the String of expected tokens
        StringBuffer expectedBuf = new StringBuffer();
        int maxSize = 0;
        boolean printedOne = false;

        if (pExc.expectedTokenSequences == null) {
            return pExc.toString();
        }

        for (int i = 0; i < pExc.expectedTokenSequences.length; i++) {
            if (maxSize < pExc.expectedTokenSequences[i].length) {
                maxSize = pExc.expectedTokenSequences[i].length;
            }
            for (int j = 0; j < pExc.expectedTokenSequences[i].length; j++) {
                if (printedOne) {
                    expectedBuf.append(", ");
                }
                expectedBuf.append
                        (pExc.tokenImage[pExc.expectedTokenSequences[i][j]]);
                printedOne = true;
            }
        }
        String expected = expectedBuf.toString();

        // Generate the String of encountered tokens
        StringBuffer encounteredBuf = new StringBuffer();
        Token tok = pExc.currentToken.next;
        for (int i = 0; i < maxSize; i++) {
            if (i != 0) {
                encounteredBuf.append(" ");
            }
            if (tok.kind == 0) {
                encounteredBuf.append(pExc.tokenImage[0]);
                break;
            }
            encounteredBuf.append(addEscapes(tok.image));
            tok = tok.next;
        }
        String encountered = encounteredBuf.toString();

        // Format the error message
        return MessageFormat.format
                (Constants.PARSE_EXCEPTION,
                        new Object[]{
                                expected,
                                encountered,
                        });
    }
303028
private String makeMessageForParseException(ParseException exception) {
        final StringBuilder sb = new StringBuilder("Parse error. Found ");
        final StringBuilder expected = new StringBuilder();

        int maxExpectedTokenSequenceLength = 0;
        TreeSet<String> sortedOptions = new TreeSet<>();
        for (int i = 0; i < exception.expectedTokenSequences.length; i++) {
            if (maxExpectedTokenSequenceLength < exception.expectedTokenSequences[i].length) {
                maxExpectedTokenSequenceLength = exception.expectedTokenSequences[i].length;
            }
            for (int j = 0; j < exception.expectedTokenSequences[i].length; j++) {
                sortedOptions.add(exception.tokenImage[exception.expectedTokenSequences[i][j]]);
            }
        }

        for (String option : sortedOptions) {
            expected.append(" ").append(option);
        }

        sb.append("");

        Token token = exception.currentToken.next;
        for (int i = 0; i < maxExpectedTokenSequenceLength; i++) {
            String tokenText = token.image;
            String escapedTokenText = ParseException.add_escapes(tokenText);
            if (i != 0) {
                sb.append(" ");
            }
            if (token.kind == 0) {
                sb.append(exception.tokenImage[0]);
                break;
            }
            escapedTokenText = "\"" + escapedTokenText + "\"";
            String image = exception.tokenImage[token.kind];
            if (image.equals(escapedTokenText)) {
                sb.append(image);
            } else {
                sb.append(" ")
                        .append(escapedTokenText)
                        .append(" ")
                        .append(image);
            }
            token = token.next;
        }

        if (exception.expectedTokenSequences.length != 0) {
            int numExpectedTokens = exception.expectedTokenSequences.length;
            sb.append(", expected")
                    .append(numExpectedTokens == 1 ? "" : " one of ")
                    .append(expected.toString());
        }
        return sb.toString();
    }
1329124
@Requires("nextToken == null")
  @Ensures("result == (nextToken != null)")
  protected boolean lex() throws IOException {
    int startOffset = currentOffset;
    StringBuilder buffer = new StringBuilder();
    int c = readChar(true);
    if (c == -1) {
      return false;
    }
    buffer.append((char) c);
    switch (c) {
      case '/':
        /* Comments. */
        c = readChar(true);
        switch (c) {
          case '/':
            buffer.append((char) c);
            do {
              c = readChar(false);
              buffer.append((char) c);
            } while (c != '\n');
            nextToken = new Token(TokenKind.COMMENT, buffer.toString(),
                                  startOffset);
            break;
          case '*':
            buffer.append((char) c);
            for (;;) {
              c = readChar(false);
              buffer.append((char) c);
              if (c == '*') {
                c = readChar(false);
                buffer.append((char) c);
                if (c == '/') {
                  break;
                }
              }
            }
            nextToken = new Token(TokenKind.COMMENT, buffer.toString(),
                                  startOffset);
            break;
          default:
            unreadChar(c);
            nextToken = new Token(TokenKind.SYMBOL, buffer.toString(),
                                  startOffset);
        }
        break;

      case '\'':
      case '"':
        /* Quoted strings. */
        int delim = c;
        for (;;) {
          c = readChar(false);
          buffer.append((char) c);
          if (c == delim) {
            break;
          }
          if (c == '\\') {
            buffer.append((char) readChar(false));
          }
        }
        nextToken = new Token(TokenKind.QUOTE, buffer.toString(), startOffset);
        break;

      default:
        if (Character.isJavaIdentifierStart(c)) {
          /* Identifiers. */
          while ((c = readChar(true)) != -1
                 && Character.isJavaIdentifierPart(c)) {
            buffer.append((char) c);
          }
          unreadChar(c);
          nextToken = new Token(TokenKind.WORD, buffer.toString(), startOffset);
        } else if (Character.isWhitespace(c)) {
          /* White space. */
          while ((c = readChar(true)) != -1 && Character.isWhitespace(c)) {
            buffer.append((char) c);
          }
          unreadChar(c);
          nextToken = new Token(TokenKind.SPACE, buffer.toString(),
                                startOffset);
        } else {
          /* Symbol. */
          nextToken = new Token(TokenKind.SYMBOL, buffer.toString(),
                                startOffset);
        }
    }
    return true;
  }
387445
function parseReturnStatement() {
        var token, argument = null;

        expectKeyword('return');

        if (!inFunctionBody) {
            throwErrorTolerant({}, Messages.IllegalReturn);
        }

        // 'return' followed by a space and an identifier is very common.
        if (source[index] === ' ') {
            if (isIdentifierStart(source[index + 1])) {
                argument = parseExpression();
                consumeSemicolon();
                return {
                    type: Syntax.ReturnStatement,
                    argument: argument
                };
            }
        }

        if (peekLineTerminator()) {
            return {
                type: Syntax.ReturnStatement,
                argument: null
            };
        }

        if (!match(';')) {
            token = lookahead();
            if (!match('}') && token.type !== Token.EOF) {
                argument = parseExpression();
            }
        }

        consumeSemicolon();

        return {
            type: Syntax.ReturnStatement,
            argument: argument
        };
    }
2124
public void assertToken(final int token) throws ParseException {
    try {
      if (nextToken() != token) {
        throw new ParseException("Expected [" + token + "], read [" +
                                  ttype + "] at " + lineno());
      }

      if (debug()) {
        if (token > 0) {
          debug("[" + (char)token + "]");
        } else {
          debug("[" + token + "]");
        }
      }
    } catch (IOException e) {
      throw new ParseException(e);
    }
  }
442825
function error(msg){
  utils.assertType(msg, 'string', 'msg');
  var err = new Error(msg.val);
  err.fromStylus = true;
  throw err;
}
751581
function (error) {
		if (error) {
			var err = new Error(error.toString());
			err.name = "l_createToken Error";
			UTIL.safeCall(onDone, err);
		}
		else {
			LOG.warn('pass_token [' + token + '] stored');
			UTIL.safeCall(onDone, null, token);			
		}
	}
275269
function throwError(token, messageFormat) {
        var error,
            args = Array.prototype.slice.call(arguments, 2),
            msg = messageFormat.replace(
                /%(\d)/g,
                function (whole, index) {
                    assert(index < args.length, 'Message reference must be in range');
                    return args[index];
                }
            );

        error = new Error(msg);
        error.index = index;
        error.description = msg;
        throw error;
    }
1242941
private String getParserErrorMessage() {
	StringBuffer code = new StringBuffer(text);
	code = code.insert(maxPosition, " >><< ");
	String codeString = code.substring(maxPosition - 100 < 0 ? 0 : maxPosition - 100,
		maxPosition + 100 >= code.length() ? code.length() : maxPosition + 100);
	return "Could not parse the input string near '" + codeString + "'!";
    }
772063
function hasException()
    {
        // Check exception from raw response
        // Server Response Status is 200 but Logical Error May Happen And Returned in Response Body
        if (! $this->exception ) {
            $res = $this->expected();
            if ($res instanceof DataEntity) {
                // Response Body Can parsed To Data Structure
                if ( $exception = $res->get('error') ) {
                    // TODO handle token revoke exceptions; OAuth Exceptions
                    $this->exception = new exTokenMismatch(
                        $res->get('error_description')
                        .' '
                        .$res->get('hint')

                        , 401
                    );
                }
            }
        } else if ($this->exception instanceof exHttpResponse) {
            // Determine Known Errors ...
            $expected = $this->expected();
            if ($expected && $err = $expected->get('error') ) {

                if ( is_string($err) )
                {
                    switch ($err) {
                        case 'access_denied':
                        case 'invalid_grant':
                            $description = $expected->get('error_description');
                            $this->exception = new exOAuthAccessDenied($description);
                            break;
                        case 'invalid_request':
                            $description = $expected->get('error_description');
                            $this->exception = new exInvalidRequest($description);
                            break;
                    }

                } elseif (isset($err['state']))
                {
                    switch (@$err['state']) {
                        case 'exUserNotFound':
                            $this->exception = new exUserNotFound($err['message'], (int)$err['code']);
                            break;
                        case 'exOAuthAccessDenied':
                            $this->exception = new exTokenMismatch($err['message'], (int)$err['code']);
                            break;
                        case 'exIdentifierExists':
                            $this->exception = new exIdentifierExists($err['message'], (int)$err['code']);
                            break;
                        case 'exPasswordNotMatch':
                            $this->exception = new exPasswordNotMatch($err['message'], (int)$err['code']);
                            break;
                        case 'exUnexpectedValue':
                            $this->exception = new exUnexpectedValue($err['message'], (int)$err['code']);
                            break;
                        case 'exMessageMalformed':
                            $this->exception = new exUnexpectedValue($err['message'], (int)$err['code']);
                            break;
                    }
                }
            }
        }


        return $this->exception;
    }
427248
public static void assertToken(int expectedType, String expectedText, LexerResults lexerResults)
    {
        assertToken(expectedType, expectedText, lexerResults.getToken());
    }