Java IRC bot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Lexer.java 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package com.dmdirc.addons.calc;
  6. import java.text.ParseException;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.List;
  10. import java.util.regex.Matcher;
  11. import java.util.regex.Pattern;
  12. /**
  13. *
  14. * @author chris
  15. */
  16. public class Lexer {
  17. final String input;
  18. public Lexer(String input) {
  19. this.input = input.replaceAll("\\s+", "");
  20. }
  21. public List<Token> tokenise() throws ParseException {
  22. final List<Token> res = new ArrayList<Token>();
  23. List<TokenType> possibles = Arrays.asList(TokenType.values());
  24. boolean cont = true;
  25. int i = 0;
  26. do {
  27. boolean found = false;
  28. for (TokenType type : possibles) {
  29. final int match = type.match(input, i);
  30. if (match > -1) {
  31. res.add(new Token(type, input.substring(i, match)));
  32. possibles = type.getFollowers();
  33. i = match;
  34. found = true;
  35. cont = type != TokenType.END;
  36. break;
  37. }
  38. }
  39. if (!found) {
  40. throw new ParseException("No legal token found at offset "
  41. + i + ". Expecting one of: "
  42. + Arrays.toString(possibles.toArray()), i);
  43. }
  44. } while (cont);
  45. return res;
  46. }
  47. }