001 /* 002 * Sonar, open source software quality management tool. 003 * Copyright (C) 2009 SonarSource SA 004 * mailto:contact AT sonarsource DOT com 005 * 006 * Sonar is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 3 of the License, or (at your option) any later version. 010 * 011 * Sonar is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014 * Lesser General Public License for more details. 015 * 016 * You should have received a copy of the GNU Lesser General Public 017 * License along with Sonar; if not, write to the Free Software 018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 019 */ 020 package org.sonar.colorizer; 021 022 public class StringTokenizer extends Tokenizer { 023 024 public StringTokenizer(String tagBefore, String tagAfter) { 025 super(tagBefore, tagAfter); 026 } 027 028 public StringTokenizer() { 029 super("", ""); 030 } 031 032 @Override 033 public boolean hasNextToken(CodeReader code) { 034 return code.peek() == '\'' || code.peek() == '\"'; 035 } 036 037 @Override 038 public String nextToken(CodeReader code) { 039 int firstChar = code.peek(); 040 return code.popTo(new EndCommentMatcher(firstChar, code)); 041 } 042 043 private static class EndCommentMatcher implements EndTokenMatcher { 044 private final int firstChar; 045 private final CodeReader code; 046 private StringBuilder literalValue; 047 048 public EndCommentMatcher(int firstChar, CodeReader code) { 049 this.firstChar = firstChar; 050 this.code = code; 051 literalValue = new StringBuilder(); 052 } 053 054 public boolean match(int endFlag) { 055 literalValue.append((char)endFlag); 056 return (code.lastChar() == firstChar && evenNumberOfBackSlashBeforeDelimiter() && literalValue.length() > 1); 057 } 058 059 private boolean evenNumberOfBackSlashBeforeDelimiter() { 060 int numberOfBackSlashChar = 0; 061 for (int index = literalValue.length() - 3; index >= 0; index--) { 062 if (literalValue.charAt(index) == '\\') { 063 numberOfBackSlashChar++; 064 } else { 065 break; 066 } 067 } 068 return numberOfBackSlashChar % 2 == 0; 069 } 070 } 071 }