TokenList.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package de.jplag;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. /**
  5. * List of tokens. Allows random access to individual tokens. Contains a hash map for token hashes.
  6. */
  7. public class TokenList implements TokenConstants {
  8. private final List<Token> tokens;
  9. TokenHashMap tokenHashes = null;
  10. int hash_length = -1;
  11. public TokenList() {
  12. tokens = new ArrayList<>();
  13. }
  14. public final int size() {
  15. return tokens.size();
  16. }
  17. public final void addToken(Token token) {
  18. if (tokens.size() > 0) {
  19. Token lastToken = tokens.get(tokens.size() - 1);
  20. if (lastToken.file.equals(token.file)) {
  21. token.file = lastToken.file; // To save memory ...
  22. }
  23. if (token.getLine() < lastToken.getLine() && (token.file.equals(lastToken.file))) {
  24. token.setLine(lastToken.getLine()); // just to make sure
  25. }
  26. }
  27. tokens.add(token);
  28. }
  29. /**
  30. * Returns a view on all tokens.
  31. * @return all tokens.
  32. */
  33. public Iterable<Token> allTokens() {
  34. return new ArrayList<>(tokens);
  35. }
  36. /**
  37. * Grants access to a specific token.
  38. * @param index is the token index.
  39. * @return the desired token.
  40. * @throws IllegalArgumentException if the index is out of bounds.
  41. */
  42. public Token getToken(int index) {
  43. if (index < 0 || index >= tokens.size()) {
  44. throw new IllegalArgumentException("Cannot access token with index " + index + ", there are only " + tokens.size() + " tokens!");
  45. }
  46. return tokens.get(index);
  47. }
  48. @Override
  49. public final String toString() {
  50. StringBuilder buffer = new StringBuilder();
  51. try {
  52. for (int i = 0; i < tokens.size(); i++) {
  53. buffer.append(i);
  54. buffer.append("\t");
  55. buffer.append(tokens.get(i).toString());
  56. if (i < tokens.size() - 1) {
  57. buffer.append("\n");
  58. }
  59. }
  60. } catch (OutOfMemoryError e) {
  61. return "Tokenlist to large for output: " + tokens.size() + " Tokens";
  62. }
  63. return buffer.toString();
  64. }
  65. }