Skip to content

The Unified and Autonomous Development Platform

Add back various code mirror translated tokenizers in case we need them later.

robin shine23a6b01226fd
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/AbstractTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/AbstractTokenizer.java
new file mode 100644
index 0000000000..829b2735f3
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/AbstractTokenizer.java
@@ -0,0 +1,75 @@
+package com.pmease.commons.lang.tokenizers;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+import com.google.common.base.Splitter;
+import com.pmease.commons.util.StringUtils;
+
+public abstract class AbstractTokenizer<S> implements Tokenizer {
+
+ public List<TokenizedLine> tokenize(List<String> lines) {
+ List<TokenizedLine> tokenizedLines = new ArrayList<>();
+ S state = startState();
+ for (String line: lines) {
+ TokenizedLine tokenizedLine = new TokenizedLine();
+ if (line.length() == 0)
+ blankLine(state);
+ StringStream stream = new StringStream(line);
+ while (!stream.eol()) {
+ String style = token(stream, state);
+ tokenizedLine.getTokens().add(new Token(style, stream.current()));
+ stream.start(stream.pos());
+ }
+ tokenizedLines.add(tokenizedLine);
+ }
+ return tokenizedLines;
+ }
+
+ public List<TokenizedLine> tokenize(String text) {
+ return tokenize(Splitter.on("\n").splitToList(text));
+ }
+
+ protected abstract S startState();
+
+ protected abstract String token(StringStream stream, S state);
+
+ protected void blankLine(S state) {
+
+ }
+
+ protected int indentUnit() {
+ return 2;
+ }
+
+ protected boolean acceptExtensions(String fileName, String...exts) {
+ String thisExt = StringUtils.substringAfterLast(fileName, ".");
+ for (String ext: exts) {
+ if (ext.equalsIgnoreCase(thisExt))
+ return true;
+ }
+ return false;
+ }
+
+ protected boolean acceptPattern(String fileName, Pattern pattern) {
+ return pattern.matcher(fileName).matches();
+ }
+
+ protected static Set<String> wordsOf(String str) {
+ Set<String> words = new HashSet<>();
+ for (String word: Splitter.on(" ").omitEmptyStrings().trimResults().split(str))
+ words.add(word);
+ return words;
+ }
+
+ protected static Set<String> wordsOf(Set<String> words, String str) {
+ Set<String> newWords = new HashSet<>(words);
+ for (String word: Splitter.on(" ").omitEmptyStrings().trimResults().split(str))
+ newWords.add(word);
+ return newWords;
+ }
+
+}
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/DefaultTokenizers.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/DefaultTokenizers.java
new file mode 100644
index 0000000000..811fb7700d
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/DefaultTokenizers.java
@@ -0,0 +1,28 @@
+package com.pmease.commons.lang.tokenizers;
+
+import java.util.List;
+import java.util.Set;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+@Singleton
+public class DefaultTokenizers implements Tokenizers {
+
+ private final Set<Tokenizer> tokenizers;
+
+ @Inject
+ public DefaultTokenizers(Set<Tokenizer> tokenizers) {
+ this.tokenizers = tokenizers;
+ }
+
+ @Override
+ public List<TokenizedLine> tokenize(List<String> lines, String fileName) {
+ for (Tokenizer tokenizer: tokenizers) {
+ if (tokenizer.accept(fileName))
+ return tokenizer.tokenize(lines);
+ }
+ return null;
+ }
+
+}
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/StringStream.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/StringStream.java
new file mode 100644
index 0000000000..a96048793d
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/StringStream.java
@@ -0,0 +1,201 @@
+package com.pmease.commons.lang.tokenizers;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class StringStream {
+
+ private static final Pattern PATTERN_SPACE = Pattern.compile("[\\s\\u00a0]");
+
+ private int pos;
+
+ private int start;
+
+ private int lineStart;
+
+ private String string;
+
+ public StringStream(String string) {
+ this.string = string;
+ pos = start = lineStart = 0;
+ }
+
+ public int pos() {
+ return pos;
+ }
+
+ public void pos(int pos) {
+ this.pos = pos;
+ }
+
+ public int start() {
+ return start;
+ }
+
+ public void start(int start) {
+ this.start = start;
+ }
+
+ public int lineStart() {
+ return lineStart;
+ }
+
+ public void lineStart(int lineStart) {
+ this.lineStart = lineStart;
+ }
+
+ public String string() {
+ return string;
+ }
+
+ public void string(String string) {
+ this.string = string;
+ }
+
+ public boolean eol() {
+ return pos >= string.length();
+ }
+
+ public boolean sol() {
+ return pos == 0;
+ }
+
+ public String peek() {
+ if (pos<string.length())
+ return String.valueOf(string.charAt(pos));
+ else
+ return "";
+ }
+
+ public String next() {
+ if (pos < string.length())
+ return String.valueOf(string.charAt(pos++));
+ else
+ return "";
+ }
+
+ public String eat(String match) {
+ String ch = peek();
+ if (match.equals(ch)) {
+ ++pos;
+ return ch;
+ } else {
+ return "";
+ }
+ }
+
+ public String eat(Pattern pattern) {
+ String ch = peek();
+ if (pattern.matcher(ch).find()) {
+ ++pos;
+ return ch;
+ } else {
+ return "";
+ }
+ }
+
+ public boolean eatWhile(String match) {
+ int start = pos;
+ while (eat(match) != null);
+ return pos>start;
+ }
+
+ public boolean eatWhile(Pattern pattern) {
+ int start = pos;
+ while (eat(pattern).length() != 0);
+ return pos>start;
+ }
+
+ public boolean eatSpace() {
+ int start = pos;
+ String ch = peek();
+ while (PATTERN_SPACE.matcher(ch).find()) {
+ ++pos;
+ ch = peek();
+ }
+ return pos>start;
+ }
+
+ public void skipToEnd() {
+ pos = string.length();
+ }
+
+ public boolean skipTo(String ch) {
+ int found = string.indexOf(ch, pos);
+ if (found > -1) {
+ pos = found;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public void backUp(int n) {
+ pos -= n;
+ }
+
+ public int column() {
+ return start - lineStart;
+ }
+
+ public int indentation() {
+ return 0;
+ }
+
+ public boolean match(String match, boolean consume, boolean caseInsensitive) {
+ String casedMatch = caseInsensitive?match.toLowerCase():match;
+ String substr = string.substring(pos, match.length()+pos);
+ String casedSubstr = caseInsensitive?substr.toLowerCase():substr;
+ if (casedMatch.equals(casedSubstr)) {
+ if (consume)
+ pos += match.length();
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean match(String match) {
+ return match(match, true, false);
+ }
+
+ public List<String> match(Pattern pattern, boolean consume) {
+ Matcher matcher = pattern.matcher(string.substring(pos));
+ if (matcher.find()) {
+ if (matcher.start() > 0)
+ return new ArrayList<>();
+ if (consume)
+ pos += matcher.group().length();
+
+ List<String> matches = new ArrayList<>();
+ for (int i=0; i<=matcher.groupCount(); i++)
+ matches.add(matcher.group(i));
+ return matches;
+ } else {
+ return new ArrayList<>();
+ }
+ }
+
+ public List<String> match(Pattern pattern) {
+ return match(pattern, true);
+ }
+
+ public String current() {
+ return string.substring(start, pos);
+ }
+
+ public <T> Object hideFirstChars(int n, Callable<T> inner) {
+ lineStart += n;
+ try {
+ return inner.call();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ } finally {
+ lineStart -= n;
+ }
+ }
+
+}
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/Token.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/Token.java
new file mode 100644
index 0000000000..07ba141238
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/Token.java
@@ -0,0 +1,136 @@
+package com.pmease.commons.lang.tokenizers;
+
+import java.io.Serializable;
+
+import com.google.common.base.Objects;
+
+public class Token implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String style;
+
+ private final String text;
+
+ public Token(String style, String text) {
+ this.style = style;
+ this.text = text;
+ }
+
+ public String style() {
+ return style;
+ }
+
+ public String text() {
+ return text;
+ }
+
+ public boolean isComment() {
+ return style.contains("cm-comment");
+ }
+
+ public boolean isKeyword() {
+ return style.contains("cm-keyword");
+ }
+
+ public boolean isNumber() {
+ return style.contains("cm-number");
+ }
+
+ public boolean isIdentifier() {
+ return style.contains("cm-variable");
+ }
+
+ public boolean isString() {
+ return style.contains("cm-string");
+ }
+
+ public boolean isMeta() {
+ return style.contains("cm-meta");
+ }
+
+ public boolean isTag() {
+ return style.contains("cm-tag");
+ }
+
+ public boolean isBracket() {
+ return style.contains("cm-bracket");
+ }
+
+ public boolean isOperator() {
+ return style.contains("cm-operator");
+ }
+
+ public boolean isAtom() {
+ return style.contains("cm-atom");
+ }
+
+ public boolean isDef() {
+ return style.contains("cm-def");
+ }
+
+ public boolean isQualifier() {
+ return style.contains("cm-qualifier");
+ }
+
+ public boolean isAttribute() {
+ return style.contains("cm-attribute");
+ }
+
+ public boolean isProperty() {
+ return style.contains("cm-property");
+ }
+
+ public boolean isBuiltin() {
+ return style.contains("cm-builtin");
+ }
+
+ public boolean isLink() {
+ return style.contains("cm-link");
+ }
+
+ public boolean isError() {
+ return style.contains("cm-error");
+ }
+
+ public boolean isNotCommentOrString() {
+ return !isComment() && !isString();
+ }
+
+ public boolean isEof() {
+ return style.length() == 0 && text.length() == 0;
+ }
+
+ public boolean isEol() {
+ return style.length() == 0 && text.equals("\n");
+ }
+
+ public boolean isWhitespace() {
+ if (style.length() != 0)
+ return false;
+ for (char ch: text.toCharArray()) {
+ if (ch != ' ' && ch != '\n' && ch != '\r' && ch != '\t')
+ return false;
+ }
+ return true;
+ }
+
+ public boolean equals(Object other) {
+ if (!(other instanceof Token))
+ return false;
+ if (this == other)
+ return true;
+ Token otherToken = (Token) other;
+ return Objects.equal(style, otherToken.style) && Objects.equal(text, otherToken.text);
+ }
+
+ public int hashCode() {
+ return Objects.hashCode(style, text);
+ }
+
+ @Override
+ public String toString() {
+ return Objects.toStringHelper(Token.class).add("text", text).add("style", style).toString();
+ }
+
+}
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/TokenizedLine.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/TokenizedLine.java
new file mode 100644
index 0000000000..f93b3f2b3f
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/TokenizedLine.java
@@ -0,0 +1,72 @@
+package com.pmease.commons.lang.tokenizers;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.lang3.StringEscapeUtils;
+
+public class TokenizedLine implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private List<Token> tokens = new ArrayList<>();
+
+ public List<Token> getTokens() {
+ return tokens;
+ }
+
+ public void setTokens(List<Token> tokens) {
+ this.tokens = tokens;
+ }
+
+ public String toHtml(int tabSize) {
+ StringBuilder html = new StringBuilder();
+ int col = 0;
+ for (Token token: tokens) {
+ StringBuilder text = new StringBuilder();
+ for (int pos = 0; ;) {
+ int idx = token.text().indexOf('\t', pos);
+ if (idx == -1) {
+ text.append(token.text().substring(pos));
+ col += token.text().length() - pos;
+ break;
+ } else {
+ col += idx - pos;
+ text.append(token.text().substring(pos, idx));
+ int size = tabSize - col % tabSize;
+ col += size;
+ for (int i=0; i<size; ++i)
+ text.append(" ");
+ pos = idx + 1;
+ }
+ }
+
+ String escapedText = StringEscapeUtils.escapeHtml4(token.text());
+ if (token.style().length() != 0) {
+ html.append(String.format("<span class='%s'>%s</span>",
+ "cm-" + token.style().replaceAll(" +", " cm-"), escapedText));
+ } else {
+ html.append(escapedText);
+ }
+ }
+
+ return html.toString();
+ }
+
+ @Override
+ public String toString() {
+ return tokens.toString();
+ }
+
+ @Override
+ public int hashCode() {
+ return tokens.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return super.equals(obj);
+ }
+
+}
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/Tokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/Tokenizer.java
new file mode 100644
index 0000000000..a95cffa817
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/Tokenizer.java
@@ -0,0 +1,11 @@
+package com.pmease.commons.lang.tokenizers;
+
+import java.util.List;
+
+public interface Tokenizer {
+
+ List<TokenizedLine> tokenize(List<String> lines);
+
+ boolean accept(String fileName);
+
+}
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/Tokenizers.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/Tokenizers.java
new file mode 100644
index 0000000000..1aa5df119b
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/Tokenizers.java
@@ -0,0 +1,19 @@
+package com.pmease.commons.lang.tokenizers;
+
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+public interface Tokenizers {
+ /**
+ * Tokenize specified lines in language indicated by specified file name
+ *
+ * @param lines
+ * list of lines to be tokenized
+ * @param fileName
+ * this param indicates language of passed lines
+ * @return
+ * tokenized lines, or <tt>null</tt> if fileName does not indicate a supported language
+ */
+ @Nullable List<TokenizedLine> tokenize(List<String> lines, String fileName);
+}
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/CSharpTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/CSharpTokenizer.java
new file mode 100644
index 0000000000..6efcb44d73
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/CSharpTokenizer.java
@@ -0,0 +1,81 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.pmease.commons.lang.tokenizers.StringStream;
+
+public class CSharpTokenizer extends ClikeTokenizer {
+
+ private static Set<String> KEYWORDS = wordsOf("abstract as base break case catch checked class const continue"
+ + " default delegate do else enum event explicit extern finally fixed for"
+ + " foreach goto if implicit in interface internal is lock namespace new"
+ + " operator out override params private protected public readonly ref return sealed"
+ + " sizeof stackalloc static struct switch this throw try typeof unchecked"
+ + " unsafe using virtual void volatile while add alias ascending descending dynamic from get"
+ + " global group into join let orderby partial remove select set value var yield");
+
+ private static Set<String> BLOCK_KEYWORDS = wordsOf("catch class do else finally for foreach if struct switch try while");
+
+ private static Set<String> BUILT_IN = wordsOf("Boolean Byte Char DateTime DateTimeOffset Decimal Double"
+ + " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32"
+ + " UInt64 bool byte char decimal double short int long object"
+ + " sbyte float string ushort uint ulong");
+
+ private static Set<String> ATOMS = Sets.newHashSet("true", "false",
+ "null");
+
+ private static Map<String, Processor> HOOKS = Maps.newHashMap();
+
+ private static Pattern PATTERN = Pattern.compile("[\\w\\$_]");
+
+ static {
+ HOOKS.put("@", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ if (stream.eat("\"").length() != 0) {
+ state.tokenize = new TokenAtString();
+ return state.tokenize.process(stream, state);
+ }
+ stream.eatWhile(PATTERN);
+ return "meta";
+ }
+
+ });
+ }
+
+ @Override
+ protected Set<String> keywords() {
+ return KEYWORDS;
+ }
+
+ @Override
+ protected Set<String> blockKeywords() {
+ return BLOCK_KEYWORDS;
+ }
+
+ @Override
+ protected Set<String> atoms() {
+ return ATOMS;
+ }
+
+ @Override
+ protected Set<String> builtin() {
+ return BUILT_IN;
+ }
+
+ @Override
+ protected Map<String, Processor> hooks() {
+ return HOOKS;
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "cs");
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/CTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/CTokenizer.java
new file mode 100644
index 0000000000..c31995a977
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/CTokenizer.java
@@ -0,0 +1,47 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import java.util.Map;
+import java.util.Set;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+public class CTokenizer extends ClikeTokenizer {
+
+ private static Set<String> BLOCK_KEYWORDS = Sets.newHashSet("case",
+ "do", "else", "for", "if", "switch", "while", "struct");
+
+ private static Set<String> ATOMS = Sets.newHashSet("null");
+
+ private static Map<String, Processor> HOOKS = Maps.newHashMap();
+
+ static {
+ HOOKS.put("#", new CppHook());
+ }
+
+ @Override
+ protected Set<String> keywords() {
+ return C_KEYWORDS;
+ }
+
+ @Override
+ protected Set<String> blockKeywords() {
+ return BLOCK_KEYWORDS;
+ }
+
+ @Override
+ protected Set<String> atoms() {
+ return ATOMS;
+ }
+
+ @Override
+ protected Map<String, Processor> hooks() {
+ return HOOKS;
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "c", "h");
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/ClikeTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/ClikeTokenizer.java
new file mode 100644
index 0000000000..419e2fa755
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/ClikeTokenizer.java
@@ -0,0 +1,337 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+import com.google.common.collect.Sets;
+import com.pmease.commons.lang.tokenizers.AbstractTokenizer;
+import com.pmease.commons.lang.tokenizers.StringStream;
+
+public abstract class ClikeTokenizer extends
+ AbstractTokenizer<ClikeTokenizer.State> {
+
+ private static Pattern IS_OPERATOR_CHAR = Pattern
+ .compile("[+\\-*&%=<>!?|\\/]");
+
+ static Set<String> C_KEYWORDS = Sets.newHashSet("auto", "if",
+ "break", "int", "case", "long", "char", "register", "continue",
+ "return", "default", "short", "do", "sizeof", "double", "static",
+ "else", "struct", "entry", "switch", "extern", "typedef", "float",
+ "union", "for", "unsigned", "goto", "while", "enum", "void",
+ "const", "signed", "volatile");
+
+ static class State {
+ Processor tokenize;
+ Context context;
+ int indented;
+ boolean startOfLine;
+ String curPunc;
+ String cpp11RawStringDelim;
+
+ State(Processor tokenize, Context context, int indented,
+ boolean startOfLine) {
+ this.tokenize = tokenize;
+ this.context = context;
+ this.indented = indented;
+ this.startOfLine = startOfLine;
+ }
+ }
+
+ static class Context {
+ int indented;
+ int column;
+ String type;
+ Boolean align;
+ Context prev;
+
+ Context(int indented, int column, String type, Boolean align,
+ Context prev) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.align = align;
+ this.prev = prev;
+ }
+
+ }
+
+ private Context pushContext(State state, int col, String type) {
+ int indent = state.indented;
+ if (state.context != null && state.context.type.equals("statement"))
+ indent = state.context.indented;
+ return state.context = new Context(indent, col, type, null,
+ state.context);
+ }
+
+ private Context popContext(State state) {
+ String t = state.context.type;
+ if (t.equals(")") || t.equals("]") || t.equals("}"))
+ state.indented = state.context.indented;
+ return state.context = state.context.prev;
+ }
+
+ static interface Processor {
+ String process(StringStream stream, State state);
+ }
+
+ protected int statementIndentUnit() {
+ return indentUnit();
+ }
+
+ protected Set<String> keywords() {
+ return new HashSet<>();
+ }
+
+ protected Set<String> builtin() {
+ return new HashSet<>();
+ }
+
+ protected Set<String> blockKeywords() {
+ return new HashSet<>();
+ }
+
+ protected Set<String> atoms() {
+ return new HashSet<>();
+ }
+
+ protected Map<String, Processor> hooks() {
+ return new HashMap<>();
+ }
+
+ protected boolean multiLineStrings() {
+ return false;
+ }
+
+ protected boolean indentStatements() {
+ return true;
+ }
+
+ @Override
+ protected State startState() {
+ return new State(null,
+ new Context(-indentUnit(), 0, "top", false, null), 0, true);
+ }
+
+ @Override
+ protected String token(StringStream stream, State state) {
+ Context ctx = state.context;
+ if (stream.sol()) {
+ if (ctx.align == null)
+ ctx.align = false;
+ state.indented = stream.indentation();
+ state.startOfLine = true;
+ }
+ if (stream.eatSpace())
+ return "";
+
+ state.curPunc = "";
+
+ String style;
+ if (state.tokenize != null)
+ style = state.tokenize.process(stream, state);
+ else
+ style = tokenBase(stream, state);
+
+ if (style.equals("comment") || style.equals("meta"))
+ return style;
+
+ if (ctx.align == null)
+ ctx.align = true;
+
+ if ((state.curPunc.equals(";") || state.curPunc.equals(":") || state.curPunc
+ .equals(",")) && ctx.type.equals("statement"))
+ popContext(state);
+ else if (state.curPunc.equals("{"))
+ pushContext(state, stream.column(), "}");
+ else if (state.curPunc.equals("["))
+ pushContext(state, stream.column(), "]");
+ else if (state.curPunc.equals("("))
+ pushContext(state, stream.column(), ")");
+ else if (state.curPunc.equals("}")) {
+ while (ctx.type.equals("statement"))
+ ctx = popContext(state);
+ if (ctx.type.equals("}"))
+ ctx = popContext(state);
+ while (ctx.type.equals("statement"))
+ ctx = popContext(state);
+ } else if (state.curPunc.equals(ctx.type))
+ popContext(state);
+ else if (indentStatements()
+ && (((ctx.type.equals("}") || ctx.type.equals("top")) && !state.curPunc
+ .equals(';')) || (ctx.type.equals("statement") && state.curPunc
+ .equals("newstatement"))))
+ pushContext(state, stream.column(), "statement");
+ state.startOfLine = false;
+ return style;
+ }
+
+ private static Pattern TOKEN_BASE_PATTERN1 = Pattern
+ .compile("[\\[\\]{}\\(\\),;\\:\\.]");
+
+ private static Pattern TOKEN_BASE_PATTERN2 = Pattern.compile("\\d");
+
+ private static Pattern TOKEN_BASE_PATTERN3 = Pattern.compile("[\\w\\.]");
+
+ private static Pattern TOKEN_BASE_PATTERN4 = Pattern
+ .compile("[\\w\\$_\\xa1-\\uffff]");
+
+ private String tokenBase(StringStream stream, State state) {
+ String ch = stream.next();
+ if (hooks().get(ch) != null) {
+ String result = hooks().get(ch).process(stream, state);
+ if (result.length() != 0)
+ return result;
+ }
+
+ if (ch.equals("\"") || ch.equals(("'"))) {
+ state.tokenize = new TokenString(ch);
+ return state.tokenize.process(stream, state);
+ }
+ if (TOKEN_BASE_PATTERN1.matcher(ch).matches()) {
+ state.curPunc = ch;
+ return "";
+ }
+ if (TOKEN_BASE_PATTERN2.matcher(ch).matches()) {
+ stream.eatWhile(TOKEN_BASE_PATTERN3);
+ return "number";
+ }
+ if (ch.equals("/")) {
+ if (stream.eat("*").length() != 0) {
+ state.tokenize = new TokenComment();
+ return state.tokenize.process(stream, state);
+ }
+ if (stream.eat("/").length() != 0) {
+ stream.skipToEnd();
+ return "comment";
+ }
+ }
+ if (IS_OPERATOR_CHAR.matcher(ch).matches()) {
+ stream.eatWhile(IS_OPERATOR_CHAR);
+ return "operator";
+ }
+ stream.eatWhile(TOKEN_BASE_PATTERN4);
+ String cur = stream.current();
+ if (keywords().contains(cur)) {
+ if (blockKeywords().contains(cur))
+ state.curPunc = "newstatement";
+ return "keyword";
+ }
+ if (builtin().contains(cur)) {
+ if (blockKeywords().contains(cur))
+ state.curPunc = "newstatement";
+ return "builtin";
+ }
+ if (atoms().contains(cur))
+ return "atom";
+
+ return "variable";
+ }
+
+ class TokenComment implements Processor {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ boolean maybeEnd = false;
+ String ch;
+ while ((ch = stream.next()).length() != 0) {
+ if (ch.equals("/") && maybeEnd) {
+ state.tokenize = null;
+ break;
+ }
+ maybeEnd = (ch.equals("*"));
+ }
+ return "comment";
+ }
+
+ }
+
+ class TokenString implements Processor {
+
+ private String quote;
+
+ TokenString(String quote) {
+ this.quote = quote;
+ }
+
+ @Override
+ public String process(StringStream stream, State state) {
+ boolean escaped = false;
+ String next;
+ boolean end = false;
+ while ((next = stream.next()).length() != 0) {
+ if (next.equals(quote) && !escaped) {
+ end = true;
+ break;
+ }
+ escaped = !escaped && next.equals("\\");
+ }
+ if (end || !(escaped || multiLineStrings()))
+ state.tokenize = null;
+ return "string";
+ }
+
+ }
+
+ static class TokenRawString implements Processor {
+
+ private static Pattern PATTERN1 = Pattern.compile("[^\\w\\s]");
+
+ @Override
+ public String process(StringStream stream, State state) {
+ // Escape characters that have special regex meanings.
+ String delim = PATTERN1.matcher(state.cpp11RawStringDelim)
+ .replaceAll("\\\\$0");
+ if (!stream.match(Pattern.compile(".*?\\)" + delim + "\""))
+ .isEmpty())
+ state.tokenize = null;
+ else
+ stream.skipToEnd();
+ return "string";
+ }
+
+ }
+
+ static class TokenAtString implements Processor {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ String next;
+ while ((next = stream.next()).length() != 0) {
+ if (next.equals("\"") && stream.eat("\"").length() == 0) {
+ state.tokenize = null;
+ break;
+ }
+ }
+ return "string";
+ }
+
+ }
+
+ static class CppHook implements Processor {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ if (!state.startOfLine)
+ return "";
+ for (;;) {
+ if (stream.skipTo("\\")) {
+ stream.next();
+ if (stream.eol()) {
+ state.tokenize = new CppHook();
+ break;
+ }
+ } else {
+ stream.skipToEnd();
+ state.tokenize = null;
+ break;
+ }
+ }
+ return "meta";
+ }
+
+ }
+
+}
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/CppTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/CppTokenizer.java
new file mode 100644
index 0000000000..5b6d83ffc2
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/CppTokenizer.java
@@ -0,0 +1,109 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.pmease.commons.lang.tokenizers.StringStream;
+
+public class CppTokenizer extends ClikeTokenizer {
+
+ static class Cpp11StringHook implements Processor {
+
+ private static Pattern PATTERN1 = Pattern.compile("(R|u8R|uR|UR|LR)");
+
+ private static Pattern PATTERN2 = Pattern
+ .compile("\"([^\\s\\\\()]{0,16})\\(");
+
+ private static Pattern PATTERN3 = Pattern.compile("(u8|u|U|L)");
+
+ private static Pattern PATTERN4 = Pattern.compile("[\"']");
+
+ @Override
+ public String process(StringStream stream, State state) {
+ stream.backUp(1);
+ // Raw strings.
+ if (!stream.match(PATTERN1).isEmpty()) {
+ List<String> match = stream.match(PATTERN2);
+ if (match.isEmpty()) {
+ return "";
+ }
+ state.cpp11RawStringDelim = match.get(1);
+ state.tokenize = new TokenRawString();
+ return state.tokenize.process(stream, state);
+ }
+ // Unicode strings/chars.
+ if (!stream.match(PATTERN3).isEmpty()) {
+ if (!stream.match(PATTERN4, /* eat */false).isEmpty()) {
+ return "string";
+ }
+ return "";
+ }
+ // Ignore this hook.
+ stream.next();
+ return "";
+ }
+
+ }
+
+ private static Set<String> KEYWORDS = Sets.newHashSet("asm",
+ "dynamic_cast", "namespace", "reinterpret_cast", "try", "bool",
+ "explicit", "new", "static_cast", "typeid", "catch",
+ "operator", "template", "typename", "class", "friend",
+ "private", "this", "using", "const_cast", "inline", "public",
+ "throw", "virtual", "delete", "mutable", "protected",
+ "wchar_t", "alignas", "alignof", "constexpr", "decltype",
+ "nullptr", "noexcept", "thread_local", "final",
+ "static_assert", "override");
+
+ static {
+ KEYWORDS.addAll(C_KEYWORDS);
+ }
+
+ private static Set<String> BLOCK_KEYWORDS = Sets.newHashSet("catch",
+ "class", "do", "else", "finally", "for", "if", "struct",
+ "switch", "try", "while");
+
+ private static Set<String> ATOMS = Sets.newHashSet("true", "false",
+ "null");
+
+ private static Map<String, Processor> HOOKS = Maps.newHashMap();
+
+ static {
+ HOOKS.put("#", new CppHook());
+ HOOKS.put("u", new Cpp11StringHook());
+ HOOKS.put("U", new Cpp11StringHook());
+ HOOKS.put("L", new Cpp11StringHook());
+ HOOKS.put("R", new Cpp11StringHook());
+ }
+
+ @Override
+ protected Set<String> keywords() {
+ return KEYWORDS;
+ }
+
+ @Override
+ protected Set<String> blockKeywords() {
+ return BLOCK_KEYWORDS;
+ }
+
+ @Override
+ protected Set<String> atoms() {
+ return ATOMS;
+ }
+
+ @Override
+ protected Map<String, Processor> hooks() {
+ return HOOKS;
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "cpp", "c++", "cc", "cxx", "hpp",
+ "h++", "hh", "hxx");
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/JavaTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/JavaTokenizer.java
new file mode 100644
index 0000000000..ccfd26f6a0
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/JavaTokenizer.java
@@ -0,0 +1,71 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.pmease.commons.lang.tokenizers.StringStream;
+
+public class JavaTokenizer extends ClikeTokenizer {
+
+ private static Set<String> KEYWORDS = Sets.newHashSet("abstract",
+ "assert", "boolean", "break", "byte", "case", "catch", "char",
+ "class", "const", "continue", "default", "do", "double",
+ "else", "enum", "extends", "final", "finally", "float", "for",
+ "goto", "if", "implements", "import", "instanceof", "int",
+ "interface", "long", "native", "new", "package", "private",
+ "protected", "public", "return", "short", "static", "strictfp",
+ "super", "switch", "synchronized", "this", "throw", "throws",
+ "transient", "try", "void", "volatile", "while");
+
+ private static Set<String> BLOCK_KEYWORDS = Sets.newHashSet("catch",
+ "class", "do", "else", "finally", "for", "if", "switch", "try",
+ "while");
+
+ private static Set<String> ATOMS = Sets.newHashSet("true", "false",
+ "null");
+
+ private static Map<String, Processor> HOOKS = Maps.newHashMap();
+
+ private static Pattern PATTERN = Pattern.compile("[\\w\\$_]");
+
+ static {
+ HOOKS.put("@", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ stream.eatWhile(PATTERN);
+ return "meta";
+ }
+
+ });
+ }
+
+ @Override
+ protected Set<String> keywords() {
+ return KEYWORDS;
+ }
+
+ @Override
+ protected Set<String> blockKeywords() {
+ return BLOCK_KEYWORDS;
+ }
+
+ @Override
+ protected Set<String> atoms() {
+ return ATOMS;
+ }
+
+ @Override
+ protected Map<String, Processor> hooks() {
+ return HOOKS;
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "java");
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/ObjectiveCTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/ObjectiveCTokenizer.java
new file mode 100644
index 0000000000..a8a9d59c28
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/ObjectiveCTokenizer.java
@@ -0,0 +1,54 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+import com.google.common.collect.Maps;
+import com.pmease.commons.lang.tokenizers.StringStream;
+
+public class ObjectiveCTokenizer extends ClikeTokenizer {
+
+ private static Set<String> KEYWORDS = wordsOf(C_KEYWORDS, "inline restrict _Bool _Complex _Imaginery BOOL Class bycopy byref id IMP in " +
+ "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly");
+
+ private static Set<String> ATOMS = wordsOf("YES NO NULL NILL ON OFF");
+
+ private static Map<String, Processor> HOOKS = Maps.newHashMap();
+
+ private static Pattern PATTERN = Pattern.compile("[\\w\\$]");
+
+ static {
+ HOOKS.put("@", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ stream.eatWhile(PATTERN);
+ return "keyword";
+ }
+
+ });
+ HOOKS.put("#", new CppHook());
+ }
+
+ @Override
+ protected Set<String> keywords() {
+ return KEYWORDS;
+ }
+
+ @Override
+ protected Set<String> atoms() {
+ return ATOMS;
+ }
+
+ @Override
+ protected Map<String, Processor> hooks() {
+ return HOOKS;
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "m", "mm");
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/ScalaTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/ScalaTokenizer.java
new file mode 100644
index 0000000000..eeccd9a884
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/clike/ScalaTokenizer.java
@@ -0,0 +1,121 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.pmease.commons.lang.tokenizers.StringStream;
+
+public class ScalaTokenizer extends ClikeTokenizer {
+
+ private static Set<String> KEYWORDS = wordsOf(
+ /* scala */
+ "abstract case catch class def do else extends false final finally for forSome if "
+ + "implicit import lazy match new null object override package private protected return "
+ + "sealed super this throw trait try trye type val var while with yield _ : = => <- <: "
+ + "<% >: # @ "
+ +
+
+ /* package scala */
+ "assert assume require print println printf readLine readBoolean readByte readShort "
+ + "readChar readInt readLong readFloat readDouble "
+ +
+
+ "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either "
+ + "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable "
+ + "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering "
+ + "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder "
+ + "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: "
+ +
+
+ /* package java.lang */
+ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable "
+ + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process "
+ + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String "
+ + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void");
+
+ private static Set<String> BLOCK_KEYWORDS = wordsOf("catch class do else finally for forSome if match switch try while");
+
+ private static Set<String> ATOMS = Sets.newHashSet("true", "false", "null");
+
+ private static Map<String, Processor> HOOKS = Maps.newHashMap();
+
+ private static Pattern PATTERN = Pattern.compile("[\\w\\$_]");
+
+ static {
+ HOOKS.put("@", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ stream.eatWhile(PATTERN);
+ return "meta";
+ }
+
+ });
+ HOOKS.put("\"", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ if (!stream.match("\"\""))
+ return "";
+ state.tokenize = new TokenTripleString();
+ return state.tokenize.process(stream, state);
+ }
+
+ });
+ }
+
+ static class TokenTripleString implements Processor {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ boolean escaped = false;
+ while (!stream.eol()) {
+ if (!escaped && stream.match("\"\"\"")) {
+ state.tokenize = null;
+ break;
+ }
+ escaped = !stream.next().equals("\\") && !escaped;
+ }
+ return "string";
+ }
+ }
+
+ @Override
+ protected Set<String> keywords() {
+ return KEYWORDS;
+ }
+
+ @Override
+ protected Set<String> blockKeywords() {
+ return BLOCK_KEYWORDS;
+ }
+
+ @Override
+ protected Set<String> atoms() {
+ return ATOMS;
+ }
+
+ @Override
+ protected boolean indentStatements() {
+ return false;
+ }
+
+ @Override
+ protected Map<String, Processor> hooks() {
+ return HOOKS;
+ }
+
+ @Override
+ protected boolean multiLineStrings() {
+ return true;
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "scala");
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/AbstractCssTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/AbstractCssTokenizer.java
new file mode 100644
index 0000000000..746c804394
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/AbstractCssTokenizer.java
@@ -0,0 +1,770 @@
+package com.pmease.commons.lang.tokenizers.css;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+import com.google.common.collect.Sets;
+import com.pmease.commons.lang.tokenizers.AbstractTokenizer;
+import com.pmease.commons.lang.tokenizers.StringStream;
+import com.pmease.commons.util.StringUtils;
+
+public abstract class AbstractCssTokenizer extends AbstractTokenizer<AbstractCssTokenizer.State> {
+
+ private static Set<String> mediaTypes = Sets.newHashSet(
+ "all", "aural", "braille", "handheld", "print", "projection", "screen",
+ "tty", "tv", "embossed");
+
+ private static Set<String> mediaFeatures = Sets.newHashSet(
+ "width", "min-width", "max-width", "height", "min-height", "max-height",
+ "device-width", "min-device-width", "max-device-width", "device-height",
+ "min-device-height", "max-device-height", "aspect-ratio",
+ "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
+ "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
+ "max-color", "color-index", "min-color-index", "max-color-index",
+ "monochrome", "min-monochrome", "max-monochrome", "resolution",
+ "min-resolution", "max-resolution", "scan", "grid"
+ );
+
+ private static Set<String> propertyKeywords = Sets.newHashSet(
+ "align-content", "align-items", "align-self", "alignment-adjust",
+ "alignment-baseline", "anchor-point", "animation", "animation-delay",
+ "animation-direction", "animation-duration", "animation-fill-mode",
+ "animation-iteration-count", "animation-name", "animation-play-state",
+ "animation-timing-function", "appearance", "azimuth", "backface-visibility",
+ "background", "background-attachment", "background-clip", "background-color",
+ "background-image", "background-origin", "background-position",
+ "background-repeat", "background-size", "baseline-shift", "binding",
+ "bleed", "bookmark-label", "bookmark-level", "bookmark-state",
+ "bookmark-target", "border", "border-bottom", "border-bottom-color",
+ "border-bottom-left-radius", "border-bottom-right-radius",
+ "border-bottom-style", "border-bottom-width", "border-collapse",
+ "border-color", "border-image", "border-image-outset",
+ "border-image-repeat", "border-image-slice", "border-image-source",
+ "border-image-width", "border-left", "border-left-color",
+ "border-left-style", "border-left-width", "border-radius", "border-right",
+ "border-right-color", "border-right-style", "border-right-width",
+ "border-spacing", "border-style", "border-top", "border-top-color",
+ "border-top-left-radius", "border-top-right-radius", "border-top-style",
+ "border-top-width", "border-width", "bottom", "box-decoration-break",
+ "box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
+ "caption-side", "clear", "clip", "color", "color-profile", "column-count",
+ "column-fill", "column-gap", "column-rule", "column-rule-color",
+ "column-rule-style", "column-rule-width", "column-span", "column-width",
+ "columns", "content", "counter-increment", "counter-reset", "crop", "cue",
+ "cue-after", "cue-before", "cursor", "direction", "display",
+ "dominant-baseline", "drop-initial-after-adjust",
+ "drop-initial-after-align", "drop-initial-before-adjust",
+ "drop-initial-before-align", "drop-initial-size", "drop-initial-value",
+ "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
+ "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
+ "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings",
+ "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust",
+ "font-stretch", "font-style", "font-synthesis", "font-variant",
+ "font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
+ "font-variant-ligatures", "font-variant-numeric", "font-variant-position",
+ "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow",
+ "grid-auto-position", "grid-auto-rows", "grid-column", "grid-column-end",
+ "grid-column-start", "grid-row", "grid-row-end", "grid-row-start",
+ "grid-template", "grid-template-areas", "grid-template-columns",
+ "grid-template-rows", "hanging-punctuation", "height", "hyphens",
+ "icon", "image-orientation", "image-rendering", "image-resolution",
+ "inline-box-align", "justify-content", "left", "letter-spacing",
+ "line-break", "line-height", "line-stacking", "line-stacking-ruby",
+ "line-stacking-shift", "line-stacking-strategy", "list-style",
+ "list-style-image", "list-style-position", "list-style-type", "margin",
+ "margin-bottom", "margin-left", "margin-right", "margin-top",
+ "marker-offset", "marks", "marquee-direction", "marquee-loop",
+ "marquee-play-count", "marquee-speed", "marquee-style", "max-height",
+ "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index",
+ "nav-left", "nav-right", "nav-up", "object-fit", "object-position",
+ "opacity", "order", "orphans", "outline",
+ "outline-color", "outline-offset", "outline-style", "outline-width",
+ "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
+ "padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
+ "page", "page-break-after", "page-break-before", "page-break-inside",
+ "page-policy", "pause", "pause-after", "pause-before", "perspective",
+ "perspective-origin", "pitch", "pitch-range", "play-during", "position",
+ "presentation-level", "punctuation-trim", "quotes", "region-break-after",
+ "region-break-before", "region-break-inside", "region-fragment",
+ "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness",
+ "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang",
+ "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin",
+ "shape-outside", "size", "speak", "speak-as", "speak-header",
+ "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
+ "tab-size", "table-layout", "target", "target-name", "target-new",
+ "target-position", "text-align", "text-align-last", "text-decoration",
+ "text-decoration-color", "text-decoration-line", "text-decoration-skip",
+ "text-decoration-style", "text-emphasis", "text-emphasis-color",
+ "text-emphasis-position", "text-emphasis-style", "text-height",
+ "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
+ "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
+ "text-wrap", "top", "transform", "transform-origin", "transform-style",
+ "transition", "transition-delay", "transition-duration",
+ "transition-property", "transition-timing-function", "unicode-bidi",
+ "vertical-align", "visibility", "voice-balance", "voice-duration",
+ "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
+ "voice-volume", "volume", "white-space", "widows", "width", "word-break",
+ "word-spacing", "word-wrap", "z-index",
+ // SVG-specific
+ "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
+ "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
+ "color-interpolation", "color-interpolation-filters",
+ "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
+ "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
+ "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
+ "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
+ "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
+ "glyph-orientation-vertical", "text-anchor", "writing-mode"
+ );
+
+ private static Set<String> nonStandardPropertyKeywords = Sets.newHashSet(
+ "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
+ "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
+ "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside",
+ "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
+ "searchfield-results-decoration", "zoom"
+ );
+
+ private static Set<String> colorKeywords = Sets.newHashSet(
+ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
+ "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
+ "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
+ "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
+ "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
+ "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
+ "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
+ "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
+ "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
+ "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
+ "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
+ "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
+ "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
+ "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
+ "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
+ "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
+ "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
+ "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
+ "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
+ "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
+ "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
+ "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
+ "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
+ "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
+ "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
+ "whitesmoke", "yellow", "yellowgreen"
+ );
+
+ private static Set<String> valueKeywords = Sets.newHashSet(
+ "above", "absolute", "activeborder", "activecaption", "afar",
+ "after-white-space", "ahead", "alias", "all", "all-scroll", "alternate",
+ "always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
+ "arabic-indic", "armenian", "asterisks", "auto", "avoid", "avoid-column", "avoid-page",
+ "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary",
+ "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
+ "both", "bottom", "break", "break-all", "break-word", "button", "button-bevel",
+ "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian",
+ "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
+ "cell", "center", "checkbox", "circle", "cjk-earthly-branch",
+ "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
+ "col-resize", "collapse", "column", "compact", "condensed", "contain", "content",
+ "content-box", "context-menu", "continuous", "copy", "cover", "crop",
+ "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal",
+ "decimal-leading-zero", "default", "default-button", "destination-atop",
+ "destination-in", "destination-out", "destination-over", "devanagari",
+ "disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted",
+ "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
+ "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
+ "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
+ "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
+ "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
+ "ethiopic-halehame-gez", "ethiopic-halehame-om-et",
+ "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
+ "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et",
+ "ethiopic-halehame-tig", "ew-resize", "expanded", "extra-condensed",
+ "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "footnotes",
+ "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove",
+ "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew",
+ "help", "hidden", "hide", "higher", "highlight", "highlighttext",
+ "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore",
+ "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
+ "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
+ "inline-block", "inline-flex", "inline-table", "inset", "inside", "intrinsic", "invert",
+ "italic", "justify", "kannada", "katakana", "katakana-iroha", "keep-all", "khmer",
+ "landscape", "lao", "large", "larger", "left", "level", "lighter",
+ "line-through", "linear", "lines", "list-item", "listbox", "listitem",
+ "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
+ "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
+ "lower-roman", "lowercase", "ltr", "malayalam", "match",
+ "media-controls-background", "media-current-time-display",
+ "media-fullscreen-button", "media-mute-button", "media-play-button",
+ "media-return-to-realtime-button", "media-rewind-button",
+ "media-seek-back-button", "media-seek-forward-button", "media-slider",
+ "media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
+ "media-volume-slider-container", "media-volume-sliderthumb", "medium",
+ "menu", "menulist", "menulist-button", "menulist-text",
+ "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
+ "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize",
+ "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
+ "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
+ "ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote",
+ "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
+ "outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
+ "painted", "page", "paused", "persian", "plus-darker", "plus-lighter", "pointer",
+ "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button",
+ "radio", "read-only", "read-write", "read-write-plaintext-only", "rectangle", "region",
+ "relative", "repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba",
+ "ridge", "right", "round", "row-resize", "rtl", "run-in", "running",
+ "s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield",
+ "searchfield-cancel-button", "searchfield-decoration",
+ "searchfield-results-button", "searchfield-results-decoration",
+ "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
+ "single", "skip-white-space", "slide", "slider-horizontal",
+ "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
+ "small", "small-caps", "small-caption", "smaller", "solid", "somali",
+ "source-atop", "source-in", "source-out", "source-over", "space", "square",
+ "square-button", "start", "static", "status-bar", "stretch", "stroke",
+ "sub", "subpixel-antialiased", "super", "sw-resize", "table",
+ "table-caption", "table-cell", "table-column", "table-column-group",
+ "table-footer-group", "table-header-group", "table-row", "table-row-group",
+ "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
+ "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
+ "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
+ "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
+ "transparent", "ultra-condensed", "ultra-expanded", "underline", "up",
+ "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
+ "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
+ "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
+ "visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
+ "window", "windowframe", "windowtext", "x-large", "x-small", "xor",
+ "xx-large", "xx-small"
+ );
+
+ private static Set<String> fontProperties = Sets.newHashSet(
+ "font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
+ "font-stretch", "font-weight", "font-style"
+ );
+
+ static class State {
+ Processor tokenize;
+ StateTransition state;
+ Context context;
+ String override;
+ String type;
+
+ State(Processor tokenize, StateTransition state, Context context) {
+ this.tokenize = tokenize;
+ this.state = state;
+ this.context = context;
+ }
+ }
+
+ static class Context {
+ int indent;
+ StateTransition type;
+ Context prev;
+
+ Context(StateTransition type, int indent, Context prev) {
+ this.type = type;
+ this.indent = indent;
+ this.prev = prev;
+ }
+
+ }
+
+ private StateTransition pushContext(State state, StringStream stream, StateTransition type) {
+ state.context = new Context(type, stream.indentation() + indentUnit(), state.context);
+ return type;
+ }
+
+ private StateTransition popContext(State state) {
+ state.context = state.context.prev;
+ return state.context.type;
+ }
+
+ @Override
+ protected State startState() {
+ return new State(null, new StatesTop(), new Context(new StatesTop(), 0, null));
+ }
+
+ protected boolean allowNested() {
+ return false;
+ }
+
+ static interface StateTransition {
+ StateTransition transition(String type, StringStream stream, State state);
+ }
+
+ private static final Pattern STATES_TOP_PATTERN = Pattern.compile("^@(-(moz|ms|o|webkit)-)?keyframes$");
+
+ class StatesTop implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals("{")) {
+ return pushContext(state, stream, new StatesBlock());
+ } else if (type.equals("}") && state.context.prev != null) {
+ return popContext(state);
+ } else if (type.equals("@media")) {
+ return pushContext(state, stream, new StatesMedia());
+ } else if (type.equals("@font-face")) {
+ return new StatesFontFaceBefore();
+ } else if (STATES_TOP_PATTERN.matcher(type).find()) {
+ return new StatesKeyFrames();
+ } else if (type.length() != 0 && type.charAt(0) == '@') {
+ return pushContext(state, stream, new StatesAt());
+ } else if (type.equals("hash")) {
+ state.override = "builtin";
+ } else if (type.equals("word")) {
+ state.override = "tag";
+ } else if (type.equals("variable-definition")) {
+ return new StatesMaybeProp();
+ } else if (type.equals("interpolation")) {
+ return pushContext(state, stream, new StatesInterpolation());
+ } else if (type.equals(":")) {
+ return new StatesPseudo();
+ } else if (allowNested() && type.equals("(")) {
+ return pushContext(state, stream, new StatesParens());
+ }
+ return state.context.type;
+ }
+
+ }
+
+ private static Pattern STATES_BLOCK_PATTERN = Pattern.compile("^\\s*:(?:\\s|$)");
+
+ class StatesBlock implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals("word")) {
+ String word = stream.current().toLowerCase();
+ if (propertyKeywords.contains(word)) {
+ state.override = "property";
+ return new StatesMaybeProp();
+ } else if (nonStandardPropertyKeywords.contains(word)) {
+ state.override = "string-2";
+ return new StatesMaybeProp();
+ } else if (allowNested()) {
+ state.override = !stream.match(STATES_BLOCK_PATTERN, false).isEmpty()? "property" : "tag";
+ return new StatesBlock();
+ } else {
+ state.override += " error";
+ return new StatesMaybeProp();
+ }
+ } else if (type.equals("meta")) {
+ return new StatesBlock();
+ } else if (!allowNested() && (type.equals("hash") || type.equals("qualifier"))) {
+ state.override = "error";
+ return new StatesBlock();
+ } else {
+ return new StatesTop().transition(type, stream, state);
+ }
+ }
+
+ }
+
+ class StatesMaybeProp implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals(":"))
+ return pushContext(state, stream, new StatesProp());
+ return pass(type, stream, state);
+ }
+
+ }
+
+ private static Pattern STATES_PROP_PATTERN = Pattern.compile("^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$");
+
+ class StatesProp implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals(";"))
+ return popContext(state);
+ if (type.equals("{") && allowNested())
+ return pushContext(state, stream, new StatesPropBlock());
+ if (type.equals("}") || type.equals("{"))
+ return popAndPass(type, stream, state);
+ if (type.equals("("))
+ return pushContext(state, stream, new StatesParens());
+
+ if (type.equals("hash") && !STATES_PROP_PATTERN.matcher(stream.current()).find()) {
+ state.override += " error";
+ } else if (type.equals("word")) {
+ wordAsValue(stream, state);
+ } else if (type.equals("interpolation")) {
+ return pushContext(state, stream, new StatesInterpolation());
+ }
+ return new StatesProp();
+ }
+
+ }
+
+ class StatesPropBlock implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals("}"))
+ return popContext(state);
+ if (type.equals("word")) {
+ state.override = "property";
+ return new StatesMaybeProp();
+ }
+ return state.context.type;
+ }
+
+ }
+
+ class StatesParens implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals("{") || type.equals("}"))
+ return popAndPass(type, stream, state);
+ if (type.equals(")"))
+ return popContext(state);
+ if (type.equals("("))
+ return pushContext(state, stream, new StatesParens());
+ if (type.equals("word"))
+ wordAsValue(stream, state);
+ return new StatesParens();
+ }
+
+ }
+
+ class StatesPseudo implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals("word")) {
+ state.override = "variable-3";
+ return state.context.type;
+ }
+ return pass(type, stream, state);
+ }
+
+ }
+
+ class StatesMedia implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals("("))
+ return pushContext(state, stream, new StatesMediaParens());
+ if (type.equals("}"))
+ return popAndPass(type, stream, state);
+ if (type.equals("{")) {
+ StateTransition transition = popContext(state);
+ if (transition != null)
+ return pushContext(state, stream, allowNested()? new StatesBlock() : new StatesTop());
+ else
+ return null;
+ }
+
+ if (type.equals("word")) {
+ String word = stream.current().toLowerCase();
+ if (word.equals("only") || word.equals("not") || word.equals("and"))
+ state.override = "keyword";
+ else if (mediaTypes.contains(word))
+ state.override = "attribute";
+ else if (mediaFeatures.contains(word))
+ state.override = "property";
+ else
+ state.override = "error";
+ }
+ return state.context.type;
+ }
+
+ }
+
+ class StatesMediaParens implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals(")"))
+ return popContext(state);
+ if (type.equals("{") || type.equals("}"))
+ return popAndPass(type, stream, state, 2);
+ return new StatesMedia().transition(type, stream, state);
+ }
+
+ }
+
+ class StatesFontFaceBefore implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals("{"))
+ return pushContext(state, stream, new StatesFontFace());
+ return pass(type, stream, state);
+ }
+
+ }
+
+ class StatesFontFace implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals("}"))
+ return popContext(state);
+ if (type.equals("word")) {
+ if (!fontProperties.contains(stream.current().toLowerCase()))
+ state.override = "error";
+ else
+ state.override = "property";
+ return new StatesMaybeProp();
+ }
+ return new StatesFontFace();
+ }
+
+ }
+
+ class StatesKeyFrames implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals("word")) {
+ state.override = "variable";
+ return new StatesKeyFrames();
+ }
+ if (type.equals("{"))
+ return pushContext(state, stream, new StatesTop());
+ return pass(type, stream, state);
+ }
+
+ }
+
+ class StatesAt implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals(";"))
+ return popContext(state);
+ if (type.equals("{") || type.equals("}"))
+ return popAndPass(type, stream, state);
+ if (type.equals("word"))
+ state.override = "tag";
+ else if (type.equals("hash"))
+ state.override = "builtin";
+ return new StatesAt();
+ }
+
+ }
+
+ class StatesInterpolation implements StateTransition {
+
+ @Override
+ public StateTransition transition(String type, StringStream stream, State state) {
+ if (type.equals("}"))
+ return popContext(state);
+ if (type.equals("{") || type.equals(";"))
+ return popAndPass(type, stream, state);
+ if (!type.equals("variable"))
+ state.override = "error";
+ return new StatesInterpolation();
+ }
+
+ }
+
+ StateTransition pass(String type, StringStream stream, State state) {
+ return state.context.type.transition(type, stream, state);
+ }
+
+ StateTransition popAndPass(String type, StringStream stream, State state) {
+ return popAndPass(type, stream, state, 1);
+ }
+
+ StateTransition popAndPass(String type, StringStream stream, State state, int n) {
+ for (int i = n; i > 0; i--)
+ state.context = state.context.prev;
+ return pass(type, stream, state);
+ }
+
+ void wordAsValue(StringStream stream, State state) {
+ String word = stream.current().toLowerCase();
+ if (valueKeywords.contains(word))
+ state.override = "atom";
+ else if (colorKeywords.contains(word))
+ state.override = "keyword";
+ else
+ state.override = "variable";
+ }
+
+ static interface Processor {
+ String process(StringStream stream, State state);
+ }
+
+ @Override
+ protected String token(StringStream stream, State state) {
+ if (state.tokenize == null && stream.eatSpace())
+ return "";
+ String style;
+ if (state.tokenize != null)
+ style = state.tokenize.process(stream, state);
+ else
+ style = tokenBase(stream, state);
+
+ if (style.contains(" ")) {
+ state.type = StringUtils.substringAfter(style, " ");
+ style = StringUtils.substringBefore(style, " ");
+ }
+ state.override = style;
+ state.state = state.state.transition(state.type, stream, state);
+ return state.override;
+ }
+
+ String ret(String style, String tp, State state) {
+ state.type = tp;
+ return style;
+ }
+
+ private static Pattern TOKEN_BASE_PATTERN1 = Pattern.compile("[\\w\\\\\\-]");
+
+ private static Pattern TOKEN_BASE_PATTERN2 = Pattern.compile("^\\s*\\w*");
+
+ private static Pattern TOKEN_BASE_PATTERN3 = Pattern.compile("\\d");
+
+ private static Pattern TOKEN_BASE_PATTERN4 = Pattern.compile("[\\w.%]");
+
+ private static Pattern TOKEN_BASE_PATTERN5 = Pattern.compile("[\\d.]");
+
+ private static Pattern TOKEN_BASE_PATTERN6 = Pattern.compile("^\\w+-");
+
+ private static Pattern TOKEN_BASE_PATTERN7 = Pattern.compile("[,+>*\\/]");
+
+ private static Pattern TOKEN_BASE_PATTERN8 = Pattern.compile("^-?[_a-z][_a-z0-9-]*", Pattern.CASE_INSENSITIVE);
+
+ private static Pattern TOKEN_BASE_PATTERN9 = Pattern.compile("[:;{}\\[\\]\\(\\)]");
+
+ private static Pattern TOKEN_BASE_PATTERN10 = Pattern.compile("[\\w\\\\\\-]");
+
+ String tokenBase(StringStream stream, State state) {
+ String ch = stream.next();
+ if (tokenHooks().containsKey(ch)) {
+ String result = tokenHooks().get(ch).process(stream, state);
+ if (result.length() != 0)
+ return result;
+ }
+ if (ch.equals("@")) {
+ stream.eatWhile(TOKEN_BASE_PATTERN1);
+ return ret("def", stream.current(), state);
+ } else if (ch.equals("=") || (ch.equals("~") || ch.equals("|")) && stream.eat("=").length()!=0) {
+ return ret("", "compare", state);
+ } else if (ch.equals("\"") || ch.equals("'")) {
+ state.tokenize = new TokenString(ch);
+ return state.tokenize.process(stream, state);
+ } else if (ch.equals("#")) {
+ stream.eatWhile(TOKEN_BASE_PATTERN1);
+ return ret("atom", "hash", state);
+ } else if (ch.equals("!")) {
+ stream.match(TOKEN_BASE_PATTERN2);
+ return ret("keyword", "important", state);
+ } else if (TOKEN_BASE_PATTERN3.matcher(ch).find() || ch.equals(".") && stream.eat(TOKEN_BASE_PATTERN3).length()!=0) {
+ stream.eatWhile(TOKEN_BASE_PATTERN4);
+ return ret("number", "unit", state);
+ } else if (ch.equals("-")) {
+ if (TOKEN_BASE_PATTERN5.matcher(stream.peek()).find()) {
+ stream.eatWhile(TOKEN_BASE_PATTERN4);
+ return ret("number", "unit", state);
+ } else if (!stream.match(TOKEN_BASE_PATTERN6).isEmpty()) {
+ return ret("meta", "meta", state);
+ }
+ } else if (TOKEN_BASE_PATTERN7.matcher(ch).find()) {
+ return ret("", "select-op", state);
+ } else if (ch.equals(".") && !stream.match(TOKEN_BASE_PATTERN8).isEmpty()) {
+ return ret("qualifier", "qualifier", state);
+ } else if (TOKEN_BASE_PATTERN9.matcher(ch).find()) {
+ return ret("", ch, state);
+ } else if (ch.equals("u") && stream.match("rl(")) {
+ stream.backUp(1);
+ state.tokenize = new TokenParenthesized();
+ return ret("property", "word", state);
+ } else if (TOKEN_BASE_PATTERN10.matcher(ch).find()) {
+ stream.eatWhile(TOKEN_BASE_PATTERN10);
+ return ret("property", "word", state);
+ } else {
+ return ret("", "", state);
+ }
+ return "";
+ }
+
+ class TokenString implements Processor {
+
+ private final String quote;
+
+ public TokenString(String quote) {
+ this.quote = quote;
+ }
+
+ @Override
+ public String process(StringStream stream, State state) {
+ boolean escaped = false;
+ String ch;
+ while ((ch = stream.next()).length() != 0) {
+ if (ch.equals(quote) && !escaped) {
+ if (quote.equals(")"))
+ stream.backUp(1);
+ break;
+ }
+ escaped = !escaped && ch.equals("\\");
+ }
+ if (ch.equals(quote) || !escaped && !quote.equals(")"))
+ state.tokenize = null;
+ return ret("string", "string", state);
+ }
+
+ }
+
+ private static Pattern TOKEN_PARENTHESIZED_PATTERN = Pattern.compile("\\s*[\\\"\\')]");
+
+ class TokenParenthesized implements Processor {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ stream.next(); // Must be '('
+ if (stream.match(TOKEN_PARENTHESIZED_PATTERN, false).isEmpty())
+ state.tokenize = new TokenString(")");
+ else
+ state.tokenize = null;
+ return ret("", "(", state);
+ }
+
+ }
+
+ class TokenCComment implements Processor {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ boolean maybeEnd = false;
+ String ch;
+ while ((ch = stream.next()).length() != 0) {
+ if (maybeEnd && ch.equals("/")) {
+ state.tokenize = null;
+ break;
+ }
+ maybeEnd = (ch.equals("*"));
+ }
+ return "comment comment";
+ }
+
+ }
+
+ class TokenSGMLComment implements Processor {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ if (stream.skipTo("-->")) {
+ stream.match("-->");
+ state.tokenize = null;
+ } else {
+ stream.skipToEnd();
+ }
+ return "comment comment";
+ }
+
+ }
+
+ protected abstract Map<String, Processor> tokenHooks();
+}
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/CssTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/CssTokenizer.java
new file mode 100644
index 0000000000..03a5cf85bc
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/CssTokenizer.java
@@ -0,0 +1,47 @@
+package com.pmease.commons.lang.tokenizers.css;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.pmease.commons.lang.tokenizers.StringStream;
+
+public class CssTokenizer extends AbstractCssTokenizer {
+
+ private Map<String, Processor> TOKEN_HOOKS = new HashMap<>();
+
+ public CssTokenizer() {
+ TOKEN_HOOKS.put("<", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ if (!stream.match("!--"))
+ return "";
+ state.tokenize = new CssTokenizer.TokenSGMLComment();
+ return new TokenSGMLComment().process(stream, state);
+ }
+
+ });
+ TOKEN_HOOKS.put("/", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ if (stream.eat("*").length() == 0)
+ return "";
+ state.tokenize = new TokenCComment();
+ return state.tokenize.process(stream, state);
+ }
+
+ });
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "css");
+ }
+
+ @Override
+ protected Map<String, Processor> tokenHooks() {
+ return TOKEN_HOOKS;
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/LESSTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/LESSTokenizer.java
new file mode 100644
index 0000000000..be973e1d2b
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/LESSTokenizer.java
@@ -0,0 +1,74 @@
+package com.pmease.commons.lang.tokenizers.css;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import com.pmease.commons.lang.tokenizers.StringStream;
+
+public class LESSTokenizer extends AbstractCssTokenizer {
+
+ private Map<String, Processor> TOKEN_HOOKS = new HashMap<>();
+
+ private static Pattern PATTERN1 = Pattern.compile("^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\\b");
+
+ private static Pattern PATTERN2 = Pattern.compile("^[\\w\\\\\\-]");
+
+ private static Pattern PATTERN3 = Pattern.compile("^\\s*:");
+
+ public LESSTokenizer() {
+ TOKEN_HOOKS.put("/", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ if (stream.eat("/").length() != 0) {
+ stream.skipToEnd();
+ return "comment comment";
+ } else if (stream.eat("*").length() != 0) {
+ state.tokenize = new TokenCComment();
+ return state.tokenize.process(stream, state);
+ } else {
+ return "operator operator";
+ }
+ }
+
+ });
+ TOKEN_HOOKS.put("@", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ if (!stream.match(PATTERN1, false).isEmpty())
+ return "";
+ stream.eatWhile(PATTERN2);
+ if (!stream.match(PATTERN3, false).isEmpty())
+ return "variable-2 variable-definition";
+ return "variable-2 variable";
+ }
+
+ });
+ TOKEN_HOOKS.put("&", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ return "atom atom";
+ }
+
+ });
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "less");
+ }
+
+ @Override
+ protected boolean allowNested() {
+ return true;
+ }
+
+ @Override
+ protected Map<String, Processor> tokenHooks() {
+ return TOKEN_HOOKS;
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/SCSSTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/SCSSTokenizer.java
new file mode 100644
index 0000000000..a452e3fe0d
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/css/SCSSTokenizer.java
@@ -0,0 +1,84 @@
+package com.pmease.commons.lang.tokenizers.css;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import com.pmease.commons.lang.tokenizers.StringStream;
+
+public class SCSSTokenizer extends AbstractCssTokenizer {
+
+ private Map<String, Processor> TOKEN_HOOKS = new HashMap<>();
+
+ private static Pattern PATTERN1 = Pattern.compile("\\s*\\{");
+
+ private static Pattern PATTERN2 = Pattern.compile("^[\\w-]+");
+
+ private static Pattern PATTERN3 = Pattern.compile("^\\s*:");
+
+ public SCSSTokenizer() {
+ TOKEN_HOOKS.put("/", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ if (stream.eat("/").length() != 0) {
+ stream.skipToEnd();
+ return "comment comment";
+ } else if (stream.eat("*").length() != 0) {
+ state.tokenize = new TokenCComment();
+ return state.tokenize.process(stream, state);
+ } else {
+ return "operator operator";
+ }
+ }
+
+ });
+ TOKEN_HOOKS.put(":", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ if (!stream.match(PATTERN1).isEmpty())
+ return " {";
+ return "";
+ }
+
+ });
+ TOKEN_HOOKS.put("$", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ stream.match(PATTERN2);
+ if (!stream.match(PATTERN3, false).isEmpty())
+ return "variable-2 variable-definition";
+ return "variable-2 variable";
+ }
+
+ });
+ TOKEN_HOOKS.put("#", new Processor() {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ if (stream.eat("{").length() == 0)
+ return "";
+ return " interpolation";
+ }
+
+ });
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "scss");
+ }
+
+ @Override
+ protected boolean allowNested() {
+ return true;
+ }
+
+ @Override
+ protected Map<String, Processor> tokenHooks() {
+ return TOKEN_HOOKS;
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/AbstractJavaScriptTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/AbstractJavaScriptTokenizer.java
new file mode 100644
index 0000000000..d0ab30a851
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/AbstractJavaScriptTokenizer.java
@@ -0,0 +1,1285 @@
+package com.pmease.commons.lang.tokenizers.javascript;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.Stack;
+import java.util.regex.Pattern;
+
+import com.google.common.collect.Sets;
+import com.pmease.commons.lang.tokenizers.AbstractTokenizer;
+import com.pmease.commons.lang.tokenizers.StringStream;
+
+public abstract class AbstractJavaScriptTokenizer extends AbstractTokenizer<AbstractJavaScriptTokenizer.State> {
+
+ static class State {
+ String type = "";
+ String content;
+ Processor tokenize;
+ String lastType;
+ int fatArrowAt = -1;
+ Var localVars;
+ Var globalVars;
+ Context context;
+ Stack<Combinator> cc;
+ String style;
+ String marked;
+ JSLexical lexical;
+ int indented;
+ }
+
+ static class Keyword {
+ final String type, style;
+
+ Keyword(String type, String style) {
+ this.type = type;
+ this.style = style;
+ }
+ }
+
+ static interface Processor {
+ String process(StringStream stream, State state);
+ }
+
+ static Keyword kw(String type) {
+ return new Keyword(type, "keyword");
+ }
+
+ static Keyword A = kw("keyword a");
+ static Keyword B = kw("keyword b");
+ static Keyword C = kw("keyword c");
+ static Keyword operator = kw("operator");
+ static Keyword atom = new Keyword("atom", "atom");
+
+ final Map<String, Keyword> keywords = new HashMap<>();
+
+ final boolean isTS;
+
+ public AbstractJavaScriptTokenizer(boolean typescript) {
+ isTS = typescript;
+
+ keywords.put("if", kw("if"));
+ keywords.put("while", A);
+ keywords.put("with", A);
+ keywords.put("else", B);
+ keywords.put("do", B);
+ keywords.put("try", B);
+ keywords.put("finally", B);
+ keywords.put("return", C);
+ keywords.put("break", C);
+ keywords.put("continue", C);
+ keywords.put("new", C);
+ keywords.put("delete", C);
+ keywords.put("throw", C);
+ keywords.put("debugger", C);
+ keywords.put("var", kw("var"));
+ keywords.put("const", kw("var"));
+ keywords.put("let", kw("var"));
+ keywords.put("function", kw("function"));
+ keywords.put("catch", kw("catch"));
+ keywords.put("for", kw("for"));
+ keywords.put("switch", kw("switch"));
+ keywords.put("case", kw("case"));
+ keywords.put("default", kw("default"));
+ keywords.put("in", operator);
+ keywords.put("typeof", operator);
+ keywords.put("instanceof", operator);
+ keywords.put("true", atom);
+ keywords.put("false", atom);
+ keywords.put("null", atom);
+ keywords.put("undefined", atom);
+ keywords.put("NaN", atom);
+ keywords.put("Infinity", atom);
+ keywords.put("this", kw("this"));
+ keywords.put("module", kw("module"));
+ keywords.put("class", kw("class"));
+ keywords.put("super", kw("atom"));
+ keywords.put("yield", C);
+ keywords.put("export", kw("export"));
+ keywords.put("import", kw("import"));
+ keywords.put("extends", C);
+
+ if (isTS) {
+ Keyword type = new Keyword("variable", "variable-3");
+ keywords.put("interface", kw("interface"));
+ keywords.put("extends", kw("extends"));
+ keywords.put("constructor", kw("constructor"));
+ keywords.put("public", kw("public"));
+ keywords.put("private", kw("private"));
+ keywords.put("protected", kw("protected"));
+ keywords.put("static", kw("static"));
+ keywords.put("string", type);
+ keywords.put("number", type);
+ keywords.put("bool", type);
+ keywords.put("any", type);
+ }
+ }
+
+ static Pattern wordRE = Pattern.compile("[\\w$\\xa1-\\uffff]");
+
+ static Pattern isOperatorChar = Pattern.compile("[+\\-*&%=<>!?|~^]");
+
+ static Pattern isJsonldKeyword = Pattern.compile("^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)\"");
+
+ void readRegexp(StringStream stream) {
+ boolean escaped = false;
+ String next;
+ boolean inSet = false;
+ while ((next = stream.next()).length() != 0) {
+ if (!escaped) {
+ if (next.equals("/") && !inSet)
+ return;
+ if (next.equals("["))
+ inSet = true;
+ else if (inSet && next.equals("]"))
+ inSet = false;
+ }
+ escaped = !escaped && next.equals("\\");
+ }
+ }
+
+ String ret(String tp, String style, String cont, State state) {
+ state.type = tp; state.content = cont;
+ return style;
+ }
+
+ static Pattern TOKEN_BASE_PATTERN1 = Pattern.compile("^\\d+(?:[eE][+\\-]?\\d+)?");
+
+ static Pattern TOKEN_BASE_PATTERN2 = Pattern.compile("[\\[\\]{}\\(\\),;\\:\\.]");
+
+ static Pattern TOKEN_BASE_PATTERN3 = Pattern.compile("x", Pattern.CASE_INSENSITIVE);
+
+ static Pattern TOKEN_BASE_PATTERN4 = Pattern.compile("[\\da-f]", Pattern.CASE_INSENSITIVE);
+
+ static Pattern TOKEN_BASE_PATTERN5 = Pattern.compile("\\d");
+
+ static Pattern TOKEN_BASE_PATTERN6 = Pattern.compile("^\\d*(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?");
+
+ static Pattern TOKEN_BASE_PATTERN7 = Pattern.compile("^[\\[{}\\(,;:]$");
+
+ static Pattern TOKEN_BASE_PATTERN8 = Pattern.compile("[gimy]");
+
+ class TokenBase implements Processor {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ String ch = stream.next();
+ if (ch.equals("\"") || ch.equals("'")) {
+ state.tokenize = new TokenString(ch);
+ return state.tokenize.process(stream, state);
+ } else if (ch.equals(".") && !stream.match(TOKEN_BASE_PATTERN1).isEmpty()) {
+ return ret("number", "number", "", state);
+ } else if (ch.equals(".") && stream.match("..")) {
+ return ret("spread", "meta", "", state);
+ } else if (TOKEN_BASE_PATTERN2.matcher(ch).find()) {
+ return ret(ch, "", "", state);
+ } else if (ch.equals("=") && stream.eat(">").length() != 0) {
+ return ret("=>", "operator", "", state);
+ } else if (ch.equals("0") && stream.eat(TOKEN_BASE_PATTERN3).length() != 0) {
+ stream.eatWhile(TOKEN_BASE_PATTERN4);
+ return ret("number", "number", "", state);
+ } else if (TOKEN_BASE_PATTERN5.matcher(ch).find()) {
+ stream.match(TOKEN_BASE_PATTERN6);
+ return ret("number", "number", "", state);
+ } else if (ch.equals("/")) {
+ if (stream.eat("*").length() != 0) {
+ state.tokenize = new TokenComment();
+ return state.tokenize.process(stream, state);
+ } else if (stream.eat("/").length() != 0) {
+ stream.skipToEnd();
+ return ret("comment", "comment", "", state);
+ } else if (state.lastType.equals("operator") || state.lastType.equals("keyword c") ||
+ state.lastType.equals("sof") || TOKEN_BASE_PATTERN7.matcher(state.lastType).find()) {
+ readRegexp(stream);
+ stream.eatWhile(TOKEN_BASE_PATTERN8); // 'y' is "sticky" option in Mozilla
+ return ret("regexp", "string-2", "", state);
+ } else {
+ stream.eatWhile(isOperatorChar);
+ return ret("operator", "operator", stream.current(), state);
+ }
+ } else if (ch.equals("`")) {
+ state.tokenize = new TokenQuasi();
+ return state.tokenize.process(stream, state);
+ } else if (ch.equals("#")) {
+ stream.skipToEnd();
+ return ret("error", "error", "", state);
+ } else if (isOperatorChar.matcher(ch).find()) {
+ stream.eatWhile(isOperatorChar);
+ return ret("operator", "operator", stream.current(), state);
+ } else if (wordRE.matcher(ch).find()) {
+ stream.eatWhile(wordRE);
+ String word = stream.current();
+ Keyword known = keywords.get(word);
+ return (known!=null && !state.lastType.equals(".")) ? ret(known.type, known.style, word, state) :
+ ret("variable", "variable", word, state);
+ }
+ return "";
+ }
+
+ }
+
+ class TokenString implements Processor {
+ final String quote;
+
+ TokenString(String quote) {
+ this.quote = quote;
+ }
+
+ @Override
+ public String process(StringStream stream, State state) {
+ boolean escaped = false;
+ String next;
+ if (jsonldMode() && stream.peek().equals("@") && !stream.match(isJsonldKeyword).isEmpty()){
+ state.tokenize = new TokenBase();
+ return ret("jsonld-keyword", "meta", "", state);
+ }
+ while ((next = stream.next()).length() != 0) {
+ if (next.equals(quote) && !escaped)
+ break;
+ escaped = !escaped && next.equals("\\");
+ }
+ if (!escaped)
+ state.tokenize = new TokenBase();
+ return ret("string", "string", "", state);
+ }
+
+ }
+
+ class TokenComment implements Processor {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ boolean maybeEnd = false;
+ String ch;
+ while ((ch = stream.next()).length() != 0) {
+ if (ch.equals("/") && maybeEnd) {
+ state.tokenize = new TokenBase();
+ break;
+ }
+ maybeEnd = (ch.equals("*"));
+ }
+ return ret("comment", "comment", "", state);
+ }
+
+ }
+
+ class TokenQuasi implements Processor {
+
+ @Override
+ public String process(StringStream stream, State state) {
+ boolean escaped = false;
+ String next;
+ while ((next = stream.next()).length() != 0) {
+ if (!escaped && (next.equals("`") || next.equals("$") && stream.eat("{").length() != 0)) {
+ state.tokenize = new TokenBase();
+ break;
+ }
+ escaped = !escaped && next.equals("\\");
+ }
+ return ret("quasi", "string-2", stream.current(), state);
+ }
+
+ }
+
+ static String brackets = "([{}])";
+
+ static Pattern FIND_FAT_ARROW_PATTERN = Pattern.compile("[\"'\\/]");
+
+ void findFatArrow(StringStream stream, State state) {
+ if (state.fatArrowAt != -1)
+ state.fatArrowAt = -1;
+
+ int arrow = stream.string().indexOf("=>", stream.start());
+ if (arrow < 0)
+ return;
+
+ int depth = 0;
+ boolean sawSomething = false;
+ int pos;
+ for (pos = arrow - 1; pos >= 0; --pos) {
+ String ch = String.valueOf(stream.string().charAt(pos));
+ int bracket = brackets.indexOf(ch);
+ if (bracket >= 0 && bracket < 3) {
+ if (depth==0) {
+ ++pos; break;
+ }
+ if (--depth == 0)
+ break;
+ } else if (bracket >= 3 && bracket < 6) {
+ ++depth;
+ } else if (wordRE.matcher(ch).find()) {
+ sawSomething = true;
+ } else if (FIND_FAT_ARROW_PATTERN.matcher(ch).find()) {
+ return;
+ } else if (sawSomething && depth==0) {
+ ++pos;
+ break;
+ }
+ }
+ if (sawSomething && depth==0)
+ state.fatArrowAt = pos;
+ }
+
+ static Set<String> atomicTypes = Sets.newHashSet(
+ "atom", "number", "variable", "string", "regexp", "this", "jsonld-keyword");
+
+ class JSLexical {
+ int indented;
+ int column;
+ String type;
+ JSLexical prev;
+ String info;
+ Boolean align;
+ int pos;
+
+ JSLexical(int indented, int column, String type, Boolean align, JSLexical prev, String info) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.prev = prev;
+ this.info = info;
+ if (align != null)
+ this.align = align;
+ }
+ }
+
+ class Var {
+ String name;
+ Var next;
+
+ Var(String name, Var next) {
+ this.name = name;
+ this.next = next;
+ }
+ }
+
+ class Context {
+ Var vars;
+ Context prev;
+
+ Context(Var vars, Context prev) {
+ this.vars = vars;
+ this.prev = prev;
+ }
+ }
+
+ boolean inScope(State state, String varname) {
+ for (Var v = state.localVars; v != null; v = v.next)
+ if (v.name.equals(varname))
+ return true;
+ for (Context cx = state.context; cx != null; cx = cx.prev) {
+ for (Var v = cx.vars; v!=null; v = v.next)
+ if (v.name.equals(varname)) return true;
+ }
+ return false;
+ }
+
+ static abstract class Combinator {
+
+ abstract boolean combine(StringStream stream, State state, String type, String value);
+
+ boolean lex() {
+ return false;
+ }
+ }
+
+ class Expression extends Combinator {
+
+ @Override
+ public boolean combine(StringStream stream, State state, String type, String content) {
+ return expressionInner(stream, state, type, false);
+ }
+ }
+
+ class ExpressionNoComma extends Combinator {
+
+ @Override
+ public boolean combine(StringStream stream, State state, String type, String content) {
+ return expressionInner(stream, state, type, true);
+ }
+
+ }
+
+ boolean pass(State state, Combinator... combinators) {
+ for (int i = combinators.length - 1; i >= 0; i--)
+ state.cc.push(combinators[i]);
+ return false;
+ }
+
+ boolean cont(State state, Combinator... combinators) {
+ pass(state, combinators);
+ return true;
+ }
+
+ boolean inList(Var list, String varname) {
+ for (Var v = list; v!=null; v = v.next) {
+ if (v.name.equals(varname))
+ return true;
+ }
+ return false;
+ }
+
+ void register(State state, String varname) {
+ if (state.context != null) {
+ state.marked = "def";
+ if (inList(state.localVars, varname))
+ return;
+ state.localVars = new Var(varname, state.localVars);
+ } else {
+ if (inList(state.globalVars, varname))
+ return;
+ if (globalVars() != null)
+ state.globalVars = new Var(varname, state.globalVars);
+ }
+ }
+
+ final Var defaultVars = new Var("this", new Var("arguments", null));
+
+ class PushContext extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String value) {
+ state.context = new Context(state.localVars, state.context);
+ state.localVars = defaultVars;
+ return false;
+ }
+
+ }
+
+ class PopContext extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String value) {
+ state.localVars = state.context.vars;
+ state.context = state.context.prev;
+ return false;
+ }
+
+ }
+
+ class PushLex extends Combinator {
+
+ final String type;
+
+ final String info;
+
+ PushLex(String type, String info) {
+ this.type = type;
+ this.info = info;
+ }
+
+ @Override
+ boolean lex() {
+ return true;
+ }
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String content) {
+ int indent = state.indented;
+ if (state.lexical.type.equals("stat"))
+ indent = state.lexical.indented;
+ else for (JSLexical outer = state.lexical; outer!=null && outer.type.equals(")") && outer.align!=null&&outer.align; outer = outer.prev)
+ indent = outer.indented;
+ state.lexical = new JSLexical(indent, stream.column(), this.type, null, state.lexical, info);
+ return false;
+ }
+
+ }
+
+ class PopLex extends Combinator {
+
+ @Override
+ boolean lex() {
+ return true;
+ }
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String content) {
+ if (state.lexical.prev != null) {
+ if (state.lexical.type.equals(")"))
+ state.indented = state.lexical.indented;
+ state.lexical = state.lexical.prev;
+ }
+ return false;
+ }
+
+ }
+
+ class Expect extends Combinator {
+
+ final String wanted;
+
+ Expect(String wanted) {
+ this.wanted = wanted;
+ }
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String content) {
+ if (type.equals(wanted))
+ return cont(state);
+ else if (wanted.equals(";"))
+ return pass(state);
+ else
+ return cont(state, new Expect(wanted));
+ }
+
+ }
+
+ class Statement extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String value) {
+ if (type.equals("var"))
+ return cont(state, new PushLex("vardef", String.valueOf(value.length())), new Vardef(), new Expect(";"), new PopLex());
+ if (type.equals("keyword a"))
+ return cont(state, new PushLex("form", ""), new Expression(), new Statement(), new PopLex());
+ if (type.equals("keyword b"))
+ return cont(state, new PushLex("form", ""), new Statement(), new PopLex());
+ if (type.equals("{"))
+ return cont(state, new PushLex("}", ""), new Block(), new PopLex());
+ if (type.equals(";"))
+ return cont(state);
+ if (type.equals("if")) {
+ if (state.lexical.info.equals("else") && (state.cc.get(state.cc.size() - 1) instanceof PopLex))
+ state.cc.pop().combine(stream, state, "", "");
+ return cont(state, new PushLex("form", ""), new Expression(), new Statement(), new PopLex(), new Maybeelse());
+ }
+ if (type.equals("function"))
+ return cont(state, new Functiondef());
+ if (type.equals("for"))
+ return cont(state, new PushLex("form", ""), new Forspec(), new Statement(), new PopLex());
+ if (type.equals("variable"))
+ return cont(state, new PushLex("stat", ""), new Maybelabel());
+ if (type.equals("switch"))
+ return cont(state, new PushLex("form", ""), new Expression(), new PushLex("}", "switch"), new Expect("{"), new Block(), new PopLex(), new PopLex());
+ if (type.equals("case"))
+ return cont(state, new Expression(), new Expect(":"));
+ if (type.equals("default"))
+ return cont(state, new Expect(":"));
+ if (type.equals("catch"))
+ return cont(state, new PushLex("form", ""), new PushContext(), new Expect("("), new Funarg(), new Expect(")"), new Statement(), new PopLex(), new PopContext());
+ if (type.equals("module"))
+ return cont(state, new PushLex("form", ""), new PushContext(), new AfterModule(), new PopContext(), new PopLex());
+ if (type.equals("class"))
+ return cont(state, new PushLex("form", ""), new ClassName(), new PopLex());
+ if (type.equals("export"))
+ return cont(state, new PushLex("form", ""), new AfterExport(), new PopLex());
+ if (type.equals("import"))
+ return cont(state, new PushLex("form", ""), new AfterImport(), new PopLex());
+ return pass(state, new PushLex("stat", ""), new Expression(), new Expect(";"), new PopLex());
+ }
+
+ }
+
+ boolean expressionInner(StringStream stream, State state, String type, boolean noComma) {
+ if (state.fatArrowAt == stream.start()) {
+ Combinator body = noComma ? new ArrowBodyNoComma() : new ArrowBody();
+ if (type.equals("("))
+ return cont(state, new PushContext(), new PushLex(")", ""), new Commasep(new PatternCombinator(), ")"), new PopLex(), new Expect("=>"), body, new PopContext());
+ else if (type.equals("variable"))
+ return pass(state, new PushContext(), new PatternCombinator(), new Expect("=>"), body, new PopContext());
+ }
+
+ Combinator maybeop = noComma ? new MaybeoperatorNoComma() : new MaybeoperatorComma();
+ if (atomicTypes.contains(type))
+ return cont(state, maybeop);
+ if (type.equals("function"))
+ return cont(state, new Functiondef(), maybeop);
+ if (type.equals("keyword c"))
+ return cont(state, noComma ? new MaybeexpressionNoComma() : new Maybeexpression());
+ if (type.equals("("))
+ return cont(state, new PushLex(")", ""), new Maybeexpression(), new Comprehension(), new Expect(")"), new PopLex(), maybeop);
+ if (type.equals("operator") || type.equals("spread"))
+ return cont(state, noComma ? new ExpressionNoComma() : new Expression());
+ if (type.equals("["))
+ return cont(state, new PushLex("]", ""), new ArrayLiteral(), new PopLex(), maybeop);
+ if (type.equals("{"))
+ return contCommasep(state, new Objprop(), "}", "", maybeop);
+ if (type.equals("quasi")) {
+ return pass(state, new Quasi(), maybeop);
+ }
+ return cont(state);
+ }
+
+ String parseJS(State state, String style, String type, String content, StringStream stream) {
+ Stack<Combinator> cc = state.cc;
+ // Communicate our context to the combinators.
+ // (Less wasteful than consing up a hundred closures on every call.)
+ state.marked = ""; state.style = style;
+
+ if (state.lexical.align == null)
+ state.lexical.align = true;
+
+ while(true) {
+ Combinator combinator = !state.cc.isEmpty()? cc.pop() : jsonMode() ? new Expression() : new Statement();
+ if (combinator.combine(stream, state, type, content)) {
+ while(!state.cc.isEmpty() && state.cc.get(state.cc.size() - 1).lex())
+ cc.pop().combine(stream, state, "", "");
+ if (state.marked.length()!=0)
+ return state.marked;
+ if (type.equals("variable") && inScope(state, content))
+ return "variable-2";
+ return style;
+ }
+ }
+ }
+
+ static Pattern MAYBE_EXPRESSION_PATTERN = Pattern.compile("[;\\}\\)\\],]");
+
+ class Maybeexpression extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String value) {
+ if (MAYBE_EXPRESSION_PATTERN.matcher(type).find())
+ return pass(state);
+ return pass(state, new Expression());
+ }
+ }
+
+ class MaybeexpressionNoComma extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String value) {
+ if (MAYBE_EXPRESSION_PATTERN.matcher(type).find())
+ return pass(state);
+ return pass(state, new ExpressionNoComma());
+ }
+ }
+
+ class MaybeoperatorComma extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String value) {
+ if (type.equals(","))
+ return cont(state, new Expression());
+ return new MaybeoperatorNoComma(false).combine(stream, state, type, value);
+ }
+
+ }
+
+ static Pattern MAYBE_OPERATOR_NOCOMMA_PATTERN = Pattern.compile("\\+\\+|--");
+
+ class MaybeoperatorNoComma extends Combinator {
+
+ final boolean noComma;
+
+ MaybeoperatorNoComma() {
+ noComma = true;
+ }
+
+ MaybeoperatorNoComma(boolean noComma) {
+ this.noComma = noComma;
+ }
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String value) {
+ Combinator me = noComma == false ? new MaybeoperatorComma() : new MaybeoperatorNoComma();
+ Combinator expr = noComma == false ? new Expression() : new ExpressionNoComma();
+ if (type.equals("=>"))
+ return cont(state, new PushContext(), noComma ? new ArrowBodyNoComma() : new ArrowBody(), new PopContext());
+ if (type.equals("operator")) {
+ if (MAYBE_OPERATOR_NOCOMMA_PATTERN.matcher(value).find())
+ return cont(state, me);
+ if (value.equals("?"))
+ return cont(state, new Expression(), new Expect(":"), expr);
+ return cont(state, expr);
+ }
+ if (type.equals("quasi")) {return pass(state, new Quasi(), me); }
+ if (type.equals(";")) return false;
+ if (type.equals("(")) return contCommasep(state, new ExpressionNoComma(), ")", "call", me);
+ if (type.equals(".")) return cont(state, new Property(), me);
+ if (type.equals("[")) return cont(state, new PushLex("]", ""), new Maybeexpression(), new Expect("]"), new PopLex(), me);
+ return false;
+ }
+
+ }
+
+ class Quasi extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String value) {
+ if (!type.equals("quasi"))
+ return pass(state);
+ if (!value.substring(value.length() - 2).equals("${"))
+ return cont(state, new Quasi());
+ return cont(state, new Expression(), new ContinueQuasi());
+ }
+
+ }
+
+ class ContinueQuasi extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String value) {
+ if (type.equals("}")) {
+ state.marked = "string-2";
+ state.tokenize = new TokenQuasi();
+ return cont(state, new Quasi());
+ }
+ return false;
+ }
+
+ }
+
+ class ArrowBody extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type, String value) {
+ findFatArrow(stream, state);
+ return pass(state, type.equals("{") ? new Statement() : new Expression());
+ }
+
+ }
+
+ class ArrowBodyNoComma extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ findFatArrow(stream, state);
+ return pass(state, type.equals("{") ? new Statement(): new ExpressionNoComma());
+ }
+
+ }
+
+ class Maybelabel extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals(":"))
+ return cont(state, new PopLex(), new Statement());
+ return pass(state, new MaybeoperatorComma(), new Expect(";"), new PopLex());
+ }
+
+ }
+
+ class Property extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("variable")) {
+ state.marked = "property";
+ return cont(state);
+ }
+ return false;
+ }
+
+ }
+
+ class Objprop extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("variable") || state.style.equals("keyword")) {
+ state.marked = "property";
+ if (value.equals("get") || value.equals("set"))
+ return cont(state, new GetterSetter());
+ return cont(state, new Afterprop());
+ } else if (type.equals("number") || type.equals("string")) {
+ state.marked = jsonldMode() ? "property" : (state.style + " property");
+ return cont(state, new Afterprop());
+ } else if (type.equals("jsonld-keyword")) {
+ return cont(state, new Afterprop());
+ } else if (type.equals("[")) {
+ return cont(state, new Expression(), new Expect("]"), new Afterprop());
+ }
+ return false;
+ }
+
+ }
+
+ class GetterSetter extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (!type.equals("variable"))
+ return pass(state, new Afterprop());
+ state.marked = "property";
+ return cont(state, new Functiondef());
+ }
+
+ }
+
+ class Afterprop extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals(":"))
+ return cont(state, new ExpressionNoComma());
+ if (type.equals("("))
+ return pass(state, new Functiondef());
+ return false;
+ }
+
+ }
+
+ class Commasep extends Combinator {
+
+ final Combinator what;
+
+ final String end;
+
+ Commasep(Combinator what, String end) {
+ this.what = what;
+ this.end = end;
+ }
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals(end))
+ return cont(state);
+ return pass(state, what, new Combinator() {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals(",")) {
+ JSLexical lex = state.lexical;
+ if (lex.info.equals("call"))
+ lex.pos = lex.pos + 1;
+ return cont(state, what, this);
+ }
+ if (type.equals(end))
+ return cont(state);
+ return cont(state, new Expect(end));
+ }
+
+ });
+ }
+
+ }
+
+ boolean contCommasep(State state, Combinator what, String end, String info, Combinator...combinators) {
+ for (Combinator combinator: combinators)
+ state.cc.push(combinator);
+ return cont(state, new PushLex(end, info), new Commasep(what, end), new PopLex());
+ }
+
+ class Block extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("}"))
+ return cont(state);
+ return pass(state, new Statement(), new Block());
+ }
+
+ }
+
+ class Maybetype extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (isTS && type.equals(":"))
+ return cont(state, new Typedef());
+ return false;
+ }
+
+ }
+
+ class Typedef extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("variable")) {
+ state.marked = "variable-3";
+ return cont(state);
+ }
+ return false;
+ }
+
+ }
+
+ class Vardef extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ return pass(state, new PatternCombinator(), new Maybetype(), new MaybeAssign(), new VardefCont());
+ }
+
+ }
+
+ class PatternCombinator extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("variable")) {
+ register(state, value);
+ return cont(state);
+ }
+ if (type.equals("[")) return contCommasep(state, new PatternCombinator(), "]", "");
+ if (type.equals("{")) return contCommasep(state, new Proppattern(), "}", "");
+ return false;
+ }
+
+ }
+
+ static Pattern PROP_PATTERN_PATTERN = Pattern.compile("^\\s*:");
+
+ class Proppattern extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("variable") && stream.match(PROP_PATTERN_PATTERN, false).isEmpty()) {
+ register(state, value);
+ return cont(state, new MaybeAssign());
+ }
+ if (type.equals("variable")) state.marked = "property";
+ return cont(state, new Expect(":"), new PatternCombinator(), new MaybeAssign());
+ }
+
+ }
+
+ class MaybeAssign extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (value.equals("=")) return cont(state, new ExpressionNoComma());
+ return false;
+ }
+
+ }
+
+ class VardefCont extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals(",")) return cont(state, new Vardef());
+ return false;
+ }
+
+ }
+
+ class Maybeelse extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("keyword b") && value.equals("else"))
+ return cont(state, new PushLex("form", "else"), new Statement(), new PopLex());
+ return false;
+ }
+
+ }
+
+ class Forspec extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("("))
+ return cont(state, new PushLex(")", ""), new Forspec1(), new Expect(")"), new PopLex());
+ return false;
+ }
+
+ }
+
+ class Forspec1 extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("var"))
+ return cont(state, new Vardef(), new Expect(";"), new Forspec2());
+ if (type.equals(";"))
+ return cont(state, new Forspec2());
+ if (type.equals("variable"))
+ return cont(state, new Formaybeinof());
+ return pass(state, new Expression(), new Expect(";"), new Forspec2());
+ }
+
+ }
+
+ class Forspec2 extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals(";")) return cont(state, new Forspec3());
+ if (value.equals("in") || value.equals("of")) {
+ state.marked = "keyword";
+ return cont(state, new Expression());
+ }
+ return pass(state, new Expression(), new Expect(";"), new Forspec3());
+ }
+
+ }
+
+ class Forspec3 extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (!type.equals(")"))
+ cont(state, new Expression());
+ return false;
+ }
+
+ }
+
+ class Formaybeinof extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (value.equals("in") || value.equals("of")) {
+ state.marked = "keyword";
+ return cont(state, new Expression());
+ }
+ return cont(state, new MaybeoperatorComma(), new Forspec2());
+ }
+
+ }
+
+ class Functiondef extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (value.equals("*")) {
+ state.marked = "keyword";
+ return cont(state, new Functiondef());
+ }
+ if (type.equals("variable")) {
+ register(state, value);
+ return cont(state, new Functiondef());
+ }
+ if (type.equals("(")) return cont(state, new PushContext(), new PushLex(")", ""), new Commasep(new Funarg(), ")"), new PopLex(), new Statement(), new PopContext());
+ return false;
+ }
+
+ }
+
+ class Funarg extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("spread"))
+ return cont(state, new Funarg());
+ return pass(state, new PatternCombinator(), new Maybetype());
+ }
+
+ }
+
+ class ClassName extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("variable")) {
+ register(state, value);
+ return cont(state, new ClassNameAfter());
+ }
+ return false;
+ }
+
+ }
+
+ class ClassNameAfter extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (value.equals("extends"))
+ return cont(state, new Expression(), new ClassNameAfter());
+ if (type.equals("{"))
+ return cont(state, new PushLex("}", ""), new ClassBody(), new PopLex());
+ return false;
+ }
+
+ }
+
+ class ClassBody extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("variable") || state.style.equals("keyword")) {
+ state.marked = "property";
+ if (value.equals("get") || value.equals("set"))
+ return cont(state, new ClassGetterSetter(), new Functiondef(), new ClassBody());
+ return cont(state, new Functiondef(), new ClassBody());
+ }
+ if (value.equals("*")) {
+ state.marked = "keyword";
+ return cont(state, new ClassBody());
+ }
+ if (type.equals(";")) return cont(state, new ClassBody());
+ if (type.equals("}")) return cont(state);
+ return false;
+ }
+
+ }
+
+ class ClassGetterSetter extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (!type.equals("variable"))
+ return pass(state);
+ state.marked = "property";
+ return cont(state);
+ }
+
+ }
+
+ class AfterModule extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("string")) return cont(state, new Statement());
+ if (type.equals("variable")) { register(state, value); return cont(state, new MaybeFrom()); }
+ return false;
+ }
+
+ }
+
+ class AfterExport extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (value.equals("*")) {
+ state.marked = "keyword";
+ return cont(state, new MaybeFrom(), new Expect(";"));
+ }
+ if (value.equals("default")) {
+ state.marked = "keyword";
+ return cont(state, new Expression(), new Expect(";"));
+ }
+ return pass(state, new Statement());
+ }
+
+ }
+
+ class AfterImport extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("string")) return cont(state);
+ return pass(state, new ImportSpec(), new MaybeFrom());
+ }
+
+ }
+
+ class ImportSpec extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("{")) return contCommasep(state, new ImportSpec(), "}", "");
+ if (type.equals("variable")) register(state, value);
+ return cont(state);
+ }
+
+ }
+
+ class MaybeFrom extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (value.equals("from")) {
+ state.marked = "keyword";
+ return cont(state, new Expression());
+ }
+ return false;
+ }
+
+ }
+
+ class ArrayLiteral extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("]")) return cont(state);
+ return pass(state, new ExpressionNoComma(), new MaybeArrayComprehension());
+ }
+
+ }
+
+ class MaybeArrayComprehension extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("for")) return pass(state, new Comprehension(), new Expect("]"));
+ if (type.equals(",")) return cont(state, new Commasep(new MaybeexpressionNoComma(), "]"));
+ return pass(state, new Commasep(new ExpressionNoComma(), "]"));
+ }
+
+ }
+
+ class Comprehension extends Combinator {
+
+ @Override
+ boolean combine(StringStream stream, State state, String type,
+ String value) {
+ if (type.equals("for")) return cont(state, new Forspec(), new Comprehension());
+ if (type.equals("if")) return cont(state, new Expression(), new Comprehension());
+ return false;
+ }
+
+ }
+
+
+ @Override
+ protected State startState() {
+ State state = new State();
+ state.tokenize = new TokenBase();
+ state.lastType = "sof";
+ state.cc = new Stack<>();
+ state.lexical = new JSLexical(-indentUnit(), 0, "block", false, null, "");
+ state.indented = 0;
+ state.localVars = null;
+ state.context = null;
+ return state;
+ }
+
+ @Override
+ protected String token(StringStream stream, State state) {
+ if (stream.sol()) {
+ if (state.lexical.align == null)
+ state.lexical.align = false;
+ state.indented = stream.indentation();
+ findFatArrow(stream, state);
+ }
+ if (!(state.tokenize instanceof TokenComment) && stream.eatSpace()) return "";
+ String style = state.tokenize.process(stream, state);
+ if (state.type.equals("comment")) return style;
+ state.lastType = state.type.equals("operator") && (state.content.equals("++") || state.content.equals("--")) ? "incdec" : state.type;
+ return parseJS(state, style, state.type, state.content, stream);
+ }
+
+ protected abstract boolean jsonldMode();
+
+ protected abstract boolean json();
+
+ protected Var globalVars() {
+ return null;
+ }
+
+ protected boolean jsonMode() {
+ return jsonldMode() || json();
+ }
+
+}
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/JSONLDTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/JSONLDTokenizer.java
new file mode 100644
index 0000000000..3aa315c765
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/JSONLDTokenizer.java
@@ -0,0 +1,24 @@
+package com.pmease.commons.lang.tokenizers.javascript;
+
+public class JSONLDTokenizer extends AbstractJavaScriptTokenizer {
+
+ public JSONLDTokenizer() {
+ super(false);
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "jsonld");
+ }
+
+ @Override
+ protected boolean jsonldMode() {
+ return true;
+ }
+
+ @Override
+ protected boolean json() {
+ return false;
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/JSONTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/JSONTokenizer.java
new file mode 100644
index 0000000000..c4955b8e09
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/JSONTokenizer.java
@@ -0,0 +1,24 @@
+package com.pmease.commons.lang.tokenizers.javascript;
+
+public class JSONTokenizer extends AbstractJavaScriptTokenizer {
+
+ public JSONTokenizer() {
+ super(false);
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "json", "map");
+ }
+
+ @Override
+ protected boolean jsonldMode() {
+ return false;
+ }
+
+ @Override
+ protected boolean json() {
+ return true;
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/JavaScriptTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/JavaScriptTokenizer.java
new file mode 100644
index 0000000000..24064de063
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/JavaScriptTokenizer.java
@@ -0,0 +1,24 @@
+package com.pmease.commons.lang.tokenizers.javascript;
+
+public class JavaScriptTokenizer extends AbstractJavaScriptTokenizer {
+
+ public JavaScriptTokenizer() {
+ super(false);
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "js");
+ }
+
+ @Override
+ protected boolean jsonldMode() {
+ return false;
+ }
+
+ @Override
+ protected boolean json() {
+ return false;
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/TypeScriptTokenizer.java b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/TypeScriptTokenizer.java
new file mode 100644
index 0000000000..a8fb9f5059
--- /dev/null
+++ b/commons.lang/src/main/java/com/pmease/commons/lang/tokenizers/javascript/TypeScriptTokenizer.java
@@ -0,0 +1,25 @@
+package com.pmease.commons.lang.tokenizers.javascript;
+
+
+public class TypeScriptTokenizer extends AbstractJavaScriptTokenizer {
+
+ public TypeScriptTokenizer() {
+ super(true);
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return acceptExtensions(fileName, "ts");
+ }
+
+ @Override
+ protected boolean jsonldMode() {
+ return false;
+ }
+
+ @Override
+ protected boolean json() {
+ return false;
+ }
+
+}
\ No newline at end of file
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/AbstractTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/AbstractTokenizerTest.java
new file mode 100644
index 0000000000..8df6dd4645
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/AbstractTokenizerTest.java
@@ -0,0 +1,97 @@
+package com.pmease.commons.lang.tokenizers;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineManager;
+import javax.script.ScriptException;
+
+import org.apache.commons.lang3.StringUtils;
+import org.junit.Assert;
+
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Splitter;
+import com.google.common.io.Resources;
+
+public abstract class AbstractTokenizerTest {
+
+ protected void verify(Tokenizer tokenizer, String[] loadModes, String fileName) {
+ try {
+ byte[] bytes = Resources.toByteArray(Resources.getResource("META-INF/maven/org.webjars/codemirror/pom.properties"));
+ Properties cmProps = new Properties();
+ cmProps.load(new ByteArrayInputStream(bytes));
+ String cmResPrefix = "META-INF/resources/webjars/codemirror/" + cmProps.getProperty("version") + "/";
+
+ ScriptEngineManager factory = new ScriptEngineManager();
+ ScriptEngine engine = factory.getEngineByName("JavaScript");
+
+ Charset utf8 = Charset.forName("UTF-8");
+ String script = Resources.toString(Resources.getResource(cmResPrefix + "addon/runmode/runmode-standalone.js"), utf8);
+ script = StringUtils.replace(script, "window.CodeMirror", "CodeMirror");
+ engine.eval(script);
+
+ engine.eval(Resources.toString(Resources.getResource(cmResPrefix + "mode/meta.js"), utf8));
+
+ for (String mode: loadModes)
+ engine.eval(Resources.toString(Resources.getResource(cmResPrefix + "mode/" + mode), utf8));
+
+ String fileContent = Resources.toString(Resources.getResource(getClass(), fileName), utf8);
+ if (fileName.contains("/"))
+ fileName = StringUtils.substringAfterLast(fileName, "/");
+ if (fileName.endsWith(".txt"))
+ fileName = fileName.substring(0, fileName.length()-4);
+ engine.put("fileName", fileName);
+ engine.put("fileContent", fileContent);
+
+ Callback callback = new Callback();
+ engine.put("callback", callback);
+
+ engine.eval("var mime = CodeMirror.findModeByFileName(fileName).mime;"
+ + "CodeMirror.runMode(fileContent, mime, function(text, style) {callback.token(style, text);});");
+
+ List<String> lines = Splitter.on(new CharMatcher() {
+
+ @Override
+ public boolean matches(char c) {
+ return c == '\r' || c == '\n';
+ }
+
+ }).omitEmptyStrings().splitToList(fileContent);
+ Assert.assertEquals(callback.getTokenizedLines().toString(), tokenizer.tokenize(lines).toString());
+ } catch (IOException | ScriptException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static class Callback {
+
+ private List<TokenizedLine> tokenizedLines = new ArrayList<>();
+
+ private TokenizedLine currentLine = new TokenizedLine();
+
+ public void token(String style, String text) {
+ if (style == null || style.equals("null") || style.equals("undefined"))
+ style = "";
+ if (text.equals("\n")) {
+ if (!currentLine.getTokens().isEmpty()) {
+ tokenizedLines.add(currentLine);
+ currentLine = new TokenizedLine();
+ }
+ } else {
+ currentLine.getTokens().add(new Token(style, text));
+ }
+ }
+
+ public List<TokenizedLine> getTokenizedLines() {
+ List<TokenizedLine> copy = new ArrayList<>(tokenizedLines);
+ if (!currentLine.getTokens().isEmpty())
+ copy.add(currentLine);
+ return copy;
+ }
+ }
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/CSharpTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/CSharpTokenizerTest.java
new file mode 100644
index 0000000000..946af7bc1f
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/CSharpTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.clike.CSharpTokenizer;
+
+public class CSharpTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new CSharpTokenizer(), new String[]{"clike/clike.js"}, "test.cs");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/CTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/CTokenizerTest.java
new file mode 100644
index 0000000000..bcf683a1d9
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/CTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.clike.CTokenizer;
+
+public class CTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new CTokenizer(), new String[]{"clike/clike.js"}, "test.c");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/CppTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/CppTokenizerTest.java
new file mode 100644
index 0000000000..9dbb7713f3
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/CppTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.clike.CppTokenizer;
+
+public class CppTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new CppTokenizer(), new String[]{"clike/clike.js"}, "test.cpp");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/JavaTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/JavaTokenizerTest.java
new file mode 100644
index 0000000000..5ebe5c84b0
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/JavaTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.clike.JavaTokenizer;
+
+public class JavaTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new JavaTokenizer(), new String[]{"clike/clike.js"}, "test.java.txt");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/ObjectiveCTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/ObjectiveCTokenizerTest.java
new file mode 100644
index 0000000000..002242a989
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/ObjectiveCTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.clike.ObjectiveCTokenizer;
+
+public class ObjectiveCTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new ObjectiveCTokenizer(), new String[]{"clike/clike.js"}, "test.m");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/ScalaTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/ScalaTokenizerTest.java
new file mode 100644
index 0000000000..fa42ec2873
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/ScalaTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.clike;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.clike.ScalaTokenizer;
+
+public class ScalaTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new ScalaTokenizer(), new String[]{"clike/clike.js"}, "test.scala");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.c b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.c
new file mode 100644
index 0000000000..1bf09971d6
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.c
@@ -0,0 +1,65 @@
+/* C demo code */
+
+#include <zmq.h>
+#include <pthread.h>
+#include <semaphore.h>
+#include <time.h>
+#include <stdio.h>
+#include <fcntl.h>
+#include <malloc.h>
+
+typedef struct {
+ void* arg_socket;
+ zmq_msg_t* arg_msg;
+ char* arg_string;
+ unsigned long arg_len;
+ int arg_int, arg_command;
+
+ int signal_fd;
+ int pad;
+ void* context;
+ sem_t sem;
+} acl_zmq_context;
+
+#define p(X) (context->arg_##X)
+
+void* zmq_thread(void* context_pointer) {
+ acl_zmq_context* context = (acl_zmq_context*)context_pointer;
+ char ok = 'K', err = 'X';
+ int res;
+
+ while (1) {
+ while ((res = sem_wait(&context->sem)) == EINTR);
+ if (res) {write(context->signal_fd, &err, 1); goto cleanup;}
+ switch(p(command)) {
+ case 0: goto cleanup;
+ case 1: p(socket) = zmq_socket(context->context, p(int)); break;
+ case 2: p(int) = zmq_close(p(socket)); break;
+ case 3: p(int) = zmq_bind(p(socket), p(string)); break;
+ case 4: p(int) = zmq_connect(p(socket), p(string)); break;
+ case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &p(len)); break;
+ case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break;
+ case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break;
+ case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break;
+ case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break;
+ }
+ p(command) = errno;
+ write(context->signal_fd, &ok, 1);
+ }
+ cleanup:
+ close(context->signal_fd);
+ free(context_pointer);
+ return 0;
+}
+
+void* zmq_thread_init(void* zmq_context, int signal_fd) {
+ acl_zmq_context* context = malloc(sizeof(acl_zmq_context));
+ pthread_t thread;
+
+ context->context = zmq_context;
+ context->signal_fd = signal_fd;
+ sem_init(&context->sem, 1, 0);
+ pthread_create(&thread, 0, &zmq_thread, context);
+ pthread_detach(thread);
+ return context;
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.cpp b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.cpp
new file mode 100644
index 0000000000..3717c06433
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.cpp
@@ -0,0 +1,38 @@
+#include <iostream>
+#include "mystuff/util.h"
+
+namespace {
+enum Enum {
+ VAL1, VAL2, VAL3
+};
+
+char32_t unicode_string = U"\U0010FFFF";
+string raw_string = R"delim(anything
+you
+want)delim";
+
+int Helper(const MyType& param) {
+ return 0;
+}
+} // namespace
+
+class ForwardDec;
+
+template <class T, class V>
+class Class : public BaseClass {
+ const MyType<T, V> member_;
+
+ public:
+ const MyType<T, V>& Method() const {
+ return member_;
+ }
+
+ void Method2(MyType<T, V>* value);
+}
+
+template <class T, class V>
+void Class::Method2(MyType<T, V>* value) {
+ std::out << 1 >> method();
+ value->Method3(member_);
+ member_ = value;
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.cs b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.cs
new file mode 100644
index 0000000000..4cdb0a84e5
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.cs
@@ -0,0 +1,412 @@
+using System;
+using System.IO;
+using System.Text;
+
+namespace MongoDB.Bson
+{
+ /// <summary>
+ /// Reads binary streams containing BSON data and converts them to native types.
+ /// </summary>
+ public class BsonReader
+ {
+ private const int MaxCharBytesSize = 128;
+ private readonly IBsonObjectBuilder _builder;
+ private readonly BinaryReader _reader;
+ private readonly byte[] _seqRange1 = new byte[]{0, 127}; //Range of 1-byte sequence
+ private readonly byte[] _seqRange2 = new byte[]{194, 223}; //Range of 2-byte sequence
+ private readonly byte[] _seqRange3 = new byte[]{224, 239}; //Range of 3-byte sequence
+ private readonly byte[] _seqRange4 = new byte[]{240, 244}; //Range of 4-byte sequence
+ private readonly Stream _stream;
+ private readonly bool _readLocalTime;
+
+ private byte[] _byteBuffer;
+ private char[] _charBuffer;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BsonReader"/> class.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ /// <param name="settings">The settings.</param>
+ public BsonReader(Stream stream, BsonReaderSettings settings)
+ {
+ if(settings == null)
+ throw new ArgumentNullException("settings");
+
+ _builder = settings.Builder;
+ _readLocalTime = settings.ReadLocalTime;
+ Position = 0;
+ _stream = stream;
+ _reader = new BinaryReader(_stream);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BsonReader"/> class.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ /// <param name="builder">The builder.</param>
+ public BsonReader(Stream stream, IBsonObjectBuilder builder){
+ _builder = builder;
+ Position = 0;
+ _stream = stream;
+ _reader = new BinaryReader(_stream);
+ }
+
+ /// <summary>
+ /// Gets or sets the position.
+ /// </summary>
+ /// <value>The position.</value>
+ public int Position { get; private set; }
+
+ /// <summary>
+ /// Reads this instance.
+ /// </summary>
+ /// <returns></returns>
+ public Document Read(){
+ Position = 0;
+ var doc = (Document)ReadObject();
+ return doc;
+ }
+
+ /// <summary>
+ /// Reads the object.
+ /// </summary>
+ /// <returns></returns>
+ public object ReadObject(){
+ var instance = _builder.BeginObject();
+ ReadElements(instance);
+ return _builder.EndObject(instance);
+ }
+
+ /// <summary>
+ /// Reads the array.
+ /// </summary>
+ /// <returns></returns>
+ public object ReadArray(){
+ var instance = _builder.BeginArray();
+ ReadElements(instance);
+ return _builder.EndArray(instance);
+ }
+
+ /// <summary>
+ /// Reads the elements.
+ /// </summary>
+ /// <param name="instance">The instance.</param>
+ private void ReadElements(object instance){
+ var startPosition = Position;
+ var size = _reader.ReadInt32();
+ Position += 4;
+ while((Position - startPosition) + 1 < size)
+ ReadElement(instance);
+ Position++;
+ if(_reader.ReadByte() != 0)
+ throw new InvalidDataException("Document not null terminated");
+ if(size != Position - startPosition)
+ throw new InvalidDataException(string.Format("Should have read {0} bytes from stream but only read {1}",
+ size,
+ (Position - startPosition)));
+ }
+
+ /// <summary>
+ /// Reads the element.
+ /// </summary>
+ /// <param name="instance">The instance.</param>
+ private void ReadElement(object instance){
+ Position++;
+ var typeNumber = (sbyte)_reader.ReadByte();
+ var key = ReadString();
+ _builder.BeginProperty(instance, key);
+ var element = ReadElementType(typeNumber);
+ _builder.EndProperty(instance, key, element);
+ }
+
+ /// <summary>
+ /// Reads the type of the element.
+ /// </summary>
+ /// <param name="typeNumber">The type number.</param>
+ /// <returns></returns>
+ public Object ReadElementType(int typeNumber){
+ switch((BsonType)typeNumber){
+ case BsonType.Null:
+ case BsonType.Undefined:
+ return null;
+ case BsonType.MinKey:
+ return MongoMinKey.Value;
+ case BsonType.MaxKey:
+ return MongoMaxKey.Value;
+ case BsonType.Boolean:
+ Position++;
+ return _reader.ReadBoolean();
+ case BsonType.Integer:
+ Position += 4;
+ return _reader.ReadInt32();
+ case BsonType.Long:
+ Position += 8;
+ return _reader.ReadInt64();
+ case BsonType.Date:
+ return ReadDateTime();
+ case BsonType.Oid:
+ Position += 12;
+ return new Oid(_reader.ReadBytes(12));
+ case BsonType.Number:
+ Position += 8;
+ return _reader.ReadDouble();
+ case BsonType.String:
+ return ReadLengthString();
+ case BsonType.Symbol:
+ return new MongoSymbol(ReadLengthString());
+ case BsonType.Obj:
+ return ReadObject();
+ case BsonType.Array:
+ return ReadArray();
+ case BsonType.Regex:
+ return ReadRegex();
+ case BsonType.Code:
+ return ReadCode();
+ case BsonType.CodeWScope:
+ return ReadScope();
+ case BsonType.Binary:
+ return ReadBinary();
+ default:
+ throw new ArgumentOutOfRangeException(String.Format("Type Number: {0} not recognized", typeNumber));
+ }
+ }
+
+ /// <summary>
+ /// Reads the date time.
+ /// </summary>
+ /// <returns></returns>
+ private object ReadDateTime(){
+ Position += 8;
+ var milliseconds = _reader.ReadInt64();
+ var time = BsonInfo.Epoch.AddMilliseconds(milliseconds);
+ if(_readLocalTime)
+ time = time.ToLocalTime();
+ return time;
+ }
+
+ /// <summary>
+ /// Reads the string.
+ /// </summary>
+ /// <returns></returns>
+ public string ReadString(){
+ EnsureBuffers();
+
+ var builder = new StringBuilder();
+ var offset = 0;
+ do{
+ var count = offset;
+ byte readByte = 0;
+
+ while(count < MaxCharBytesSize && (readByte = _reader.ReadByte()) > 0)
+ _byteBuffer[count++] = readByte;
+
+ var byteCount = count - offset;
+ Position += byteCount;
+
+ if(count == 0)
+ break; //first byte read was the terminator.
+
+ var lastFullCharStop = GetLastFullCharStop(count - 1);
+
+ var charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
+ builder.Append(_charBuffer, 0, charCount);
+
+ if(lastFullCharStop < byteCount - 1){
+ offset = byteCount - lastFullCharStop - 1;
+ //Copy end bytes to begining
+ Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
+ }
+ else
+ offset = 0;
+
+ if(readByte == 0)
+ break;
+ }
+ while(true);
+ Position++;
+ return builder.ToString();
+ }
+
+ /// <summary>
+ /// Reads the length string.
+ /// </summary>
+ /// <returns></returns>
+ public string ReadLengthString(){
+ var length = _reader.ReadInt32();
+ var str = GetString(length - 1);
+ _reader.ReadByte();
+
+ Position += (4 + 1);
+ return str;
+ }
+
+ /// <summary>
+ /// Gets the string.
+ /// </summary>
+ /// <param name="length">The length.</param>
+ /// <returns></returns>
+ private string GetString(int length){
+ if(length == 0)
+ return string.Empty;
+
+ EnsureBuffers();
+
+ var builder = new StringBuilder(length);
+
+ var totalBytesRead = 0;
+ var offset = 0;
+ do{
+ var count = ((length - totalBytesRead) > MaxCharBytesSize - offset)
+ ? (MaxCharBytesSize - offset)
+ :
+ (length - totalBytesRead);
+
+ var byteCount = _reader.BaseStream.Read(_byteBuffer, offset, count);
+ totalBytesRead += byteCount;
+ byteCount += offset;
+
+ var lastFullCharStop = GetLastFullCharStop(byteCount - 1);
+
+ if(byteCount == 0)
+ throw new EndOfStreamException("Unable to read beyond the end of the stream.");
+
+ var charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
+ builder.Append(_charBuffer, 0, charCount);
+
+ if(lastFullCharStop < byteCount - 1){
+ offset = byteCount - lastFullCharStop - 1;
+ //Copy end bytes to begining
+ Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
+ }
+ else
+ offset = 0;
+ }
+ while(totalBytesRead < length);
+
+ Position += totalBytesRead;
+ return builder.ToString();
+ }
+
+ /// <summary>
+ /// Reads the scope.
+ /// </summary>
+ /// <returns></returns>
+ private object ReadScope(){
+ var startpos = Position;
+ var size = _reader.ReadInt32();
+ Position += 4;
+
+ var val = ReadLengthString();
+ var scope = (Document)ReadObject();
+ if(size != Position - startpos)
+ throw new InvalidDataException(string.Format("Should have read {0} bytes from stream but read {1} in CodeWScope",
+ size,
+ Position - startpos));
+
+ return new CodeWScope(val, scope);
+ }
+
+ /// <summary>
+ /// Reads the code.
+ /// </summary>
+ /// <returns></returns>
+ private object ReadCode(){
+ return new Code{Value = ReadLengthString()};
+ }
+
+ /// <summary>
+ /// Reads the regex.
+ /// </summary>
+ /// <returns></returns>
+ private object ReadRegex(){
+ return new MongoRegex{
+ Expression = ReadString(),
+ RawOptions = ReadString()
+ };
+ }
+
+ /// <summary>
+ /// Reads the binary.
+ /// </summary>
+ /// <returns></returns>
+ private object ReadBinary(){
+ var size = _reader.ReadInt32();
+ Position += 4;
+ var subtype = _reader.ReadByte();
+ Position ++;
+ if(subtype == (byte)BinarySubtype.General){
+ size = _reader.ReadInt32();
+ Position += 4;
+ }
+ var bytes = _reader.ReadBytes(size);
+ Position += size;
+
+ // From http://en.wikipedia.org/wiki/Universally_Unique_Identifier
+ // The most widespread use of this standard is in Microsoft's Globally Unique Identifiers (GUIDs).
+ if(subtype == 3 && 16 == size)
+ return new Guid(bytes);
+
+ return new Binary{
+ Bytes = bytes,
+ Subtype = (BinarySubtype)subtype
+ };
+ }
+
+ /// <summary>
+ /// Gets the last full char stop.
+ /// </summary>
+ /// <param name="start">The start.</param>
+ /// <returns></returns>
+ private int GetLastFullCharStop(int start){
+ var lookbackPos = start;
+ var bis = 0;
+
+ while(lookbackPos >= 0){
+ bis = BytesInSequence(_byteBuffer[lookbackPos]);
+ if(bis == 0){
+ lookbackPos--;
+ continue;
+ }
+
+ if(bis == 1)
+ break;
+
+ lookbackPos--;
+ break;
+ }
+
+ return bis == start - lookbackPos ? start : lookbackPos;
+ }
+
+ /// <summary>
+ /// Byteses the in sequence.
+ /// </summary>
+ /// <param name="b">The b.</param>
+ /// <returns></returns>
+ private int BytesInSequence(byte b){
+ if(b <= _seqRange1[1])
+ return 1;
+ if(b >= _seqRange2[0] && b <= _seqRange2[1])
+ return 2;
+ if(b >= _seqRange3[0] && b <= _seqRange3[1])
+ return 3;
+ if(b >= _seqRange4[0] && b <= _seqRange4[1])
+ return 4;
+ return 0;
+ }
+
+ /// <summary>
+ /// Ensures the buffers.
+ /// </summary>
+ private void EnsureBuffers(){
+ if(_byteBuffer == null)
+ _byteBuffer = new byte[MaxCharBytesSize];
+ if(_charBuffer != null)
+ return;
+
+ var charBufferSize = Encoding.UTF8.GetMaxCharCount(MaxCharBytesSize);
+
+ _charBuffer = new char[charBufferSize];
+ }
+ }
+}
\ No newline at end of file
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.java.txt b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.java.txt
new file mode 100644
index 0000000000..36bf050843
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.java.txt
@@ -0,0 +1,27 @@
+import com.demo.util.MyType;
+import com.demo.util.MyInterface;
+
+public enum Enum {
+ VAL1, VAL2, VAL3
+}
+
+public class Class<T, V> implements MyInterface {
+ public static final MyType<T, V> member;
+
+ private class InnerClass {
+ public int zero() {
+ return 0;
+ }
+ }
+
+ @Override
+ public MyType method() {
+ return member;
+ }
+
+ public void method2(MyType<T, V> value) {
+ method();
+ value.method3();
+ member = value;
+ }
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.m b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.m
new file mode 100644
index 0000000000..54f48c143f
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.m
@@ -0,0 +1,15 @@
+/*
+This is a longer comment
+That spans two lines
+*/
+
+#import <Test/Test.h>
+@implementation YourAppDelegate
+
+// This is a one-line comment
+
+- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
+ char myString[] = "This is a C character array";
+ int test = 5;
+ return YES;
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.scala b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.scala
new file mode 100644
index 0000000000..02938315d9
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/clike/test.scala
@@ -0,0 +1,726 @@
+
+ /* __ *\
+ ** ________ ___ / / ___ Scala API **
+ ** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL **
+ ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
+ ** /____/\___/_/ |_/____/_/ | | **
+ ** |/ **
+ \* */
+
+ package scala.collection
+
+ import generic._
+ import mutable.{ Builder, ListBuffer }
+ import annotation.{tailrec, migration, bridge}
+ import annotation.unchecked.{ uncheckedVariance => uV }
+ import parallel.ParIterable
+
+ /** A template trait for traversable collections of type `Traversable[A]`.
+ *
+ * $traversableInfo
+ * @define mutability
+ * @define traversableInfo
+ * This is a base trait of all kinds of $mutability Scala collections. It
+ * implements the behavior common to all collections, in terms of a method
+ * `foreach` with signature:
+ * {{{
+ * def foreach[U](f: Elem => U): Unit
+ * }}}
+ * Collection classes mixing in this trait provide a concrete
+ * `foreach` method which traverses all the
+ * elements contained in the collection, applying a given function to each.
+ * They also need to provide a method `newBuilder`
+ * which creates a builder for collections of the same kind.
+ *
+ * A traversable class might or might not have two properties: strictness
+ * and orderedness. Neither is represented as a type.
+ *
+ * The instances of a strict collection class have all their elements
+ * computed before they can be used as values. By contrast, instances of
+ * a non-strict collection class may defer computation of some of their
+ * elements until after the instance is available as a value.
+ * A typical example of a non-strict collection class is a
+ * <a href="../immutable/Stream.html" target="ContentFrame">
+ * `scala.collection.immutable.Stream`</a>.
+ * A more general class of examples are `TraversableViews`.
+ *
+ * If a collection is an instance of an ordered collection class, traversing
+ * its elements with `foreach` will always visit elements in the
+ * same order, even for different runs of the program. If the class is not
+ * ordered, `foreach` can visit elements in different orders for
+ * different runs (but it will keep the same order in the same run).'
+ *
+ * A typical example of a collection class which is not ordered is a
+ * `HashMap` of objects. The traversal order for hash maps will
+ * depend on the hash codes of its elements, and these hash codes might
+ * differ from one run to the next. By contrast, a `LinkedHashMap`
+ * is ordered because it's `foreach` method visits elements in the
+ * order they were inserted into the `HashMap`.
+ *
+ * @author Martin Odersky
+ * @version 2.8
+ * @since 2.8
+ * @tparam A the element type of the collection
+ * @tparam Repr the type of the actual collection containing the elements.
+ *
+ * @define Coll Traversable
+ * @define coll traversable collection
+ */
+ trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr]
+ with FilterMonadic[A, Repr]
+ with TraversableOnce[A]
+ with GenTraversableLike[A, Repr]
+ with Parallelizable[A, ParIterable[A]]
+ {
+ self =>
+
+ import Traversable.breaks._
+
+ /** The type implementing this traversable */
+ protected type Self = Repr
+
+ /** The collection of type $coll underlying this `TraversableLike` object.
+ * By default this is implemented as the `TraversableLike` object itself,
+ * but this can be overridden.
+ */
+ def repr: Repr = this.asInstanceOf[Repr]
+
+ /** The underlying collection seen as an instance of `$Coll`.
+ * By default this is implemented as the current collection object itself,
+ * but this can be overridden.
+ */
+ protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]]
+
+ /** A conversion from collections of type `Repr` to `$Coll` objects.
+ * By default this is implemented as just a cast, but this can be overridden.
+ */
+ protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]]
+
+ /** Creates a new builder for this collection type.
+ */
+ protected[this] def newBuilder: Builder[A, Repr]
+
+ protected[this] def parCombiner = ParIterable.newCombiner[A]
+
+ /** Applies a function `f` to all elements of this $coll.
+ *
+ * Note: this method underlies the implementation of most other bulk operations.
+ * It's important to implement this method in an efficient way.
+ *
+ *
+ * @param f the function that is applied for its side-effect to every element.
+ * The result of function `f` is discarded.
+ *
+ * @tparam U the type parameter describing the result of function `f`.
+ * This result will always be ignored. Typically `U` is `Unit`,
+ * but this is not necessary.
+ *
+ * @usecase def foreach(f: A => Unit): Unit
+ */
+ def foreach[U](f: A => U): Unit
+
+ /** Tests whether this $coll is empty.
+ *
+ * @return `true` if the $coll contain no elements, `false` otherwise.
+ */
+ def isEmpty: Boolean = {
+ var result = true
+ breakable {
+ for (x <- this) {
+ result = false
+ break
+ }
+ }
+ result
+ }
+
+ /** Tests whether this $coll is known to have a finite size.
+ * All strict collections are known to have finite size. For a non-strict collection
+ * such as `Stream`, the predicate returns `true` if all elements have been computed.
+ * It returns `false` if the stream is not yet evaluated to the end.
+ *
+ * Note: many collection methods will not work on collections of infinite sizes.
+ *
+ * @return `true` if this collection is known to have finite size, `false` otherwise.
+ */
+ def hasDefiniteSize = true
+
+ def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+ val b = bf(repr)
+ if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.seq.size)
+ b ++= thisCollection
+ b ++= that.seq
+ b.result
+ }
+
+ @bridge
+ def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
+ ++(that: GenTraversableOnce[B])(bf)
+
+ /** Concatenates this $coll with the elements of a traversable collection.
+ * It differs from ++ in that the right operand determines the type of the
+ * resulting collection rather than the left one.
+ *
+ * @param that the traversable to append.
+ * @tparam B the element type of the returned collection.
+ * @tparam That $thatinfo
+ * @param bf $bfinfo
+ * @return a new collection of type `That` which contains all elements
+ * of this $coll followed by all elements of `that`.
+ *
+ * @usecase def ++:[B](that: TraversableOnce[B]): $Coll[B]
+ *
+ * @return a new $coll which contains all elements of this $coll
+ * followed by all elements of `that`.
+ */
+ def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+ val b = bf(repr)
+ if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size)
+ b ++= that
+ b ++= thisCollection
+ b.result
+ }
+
+ /** This overload exists because: for the implementation of ++: we should reuse
+ * that of ++ because many collections override it with more efficient versions.
+ * Since TraversableOnce has no '++' method, we have to implement that directly,
+ * but Traversable and down can use the overload.
+ */
+ def ++:[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That =
+ (that ++ seq)(breakOut)
+
+ def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+ val b = bf(repr)
+ b.sizeHint(this)
+ for (x <- this) b += f(x)
+ b.result
+ }
+
+ def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+ val b = bf(repr)
+ for (x <- this) b ++= f(x).seq
+ b.result
+ }
+
+ /** Selects all elements of this $coll which satisfy a predicate.
+ *
+ * @param p the predicate used to test elements.
+ * @return a new $coll consisting of all elements of this $coll that satisfy the given
+ * predicate `p`. The order of the elements is preserved.
+ */
+ def filter(p: A => Boolean): Repr = {
+ val b = newBuilder
+ for (x <- this)
+ if (p(x)) b += x
+ b.result
+ }
+
+ /** Selects all elements of this $coll which do not satisfy a predicate.
+ *
+ * @param p the predicate used to test elements.
+ * @return a new $coll consisting of all elements of this $coll that do not satisfy the given
+ * predicate `p`. The order of the elements is preserved.
+ */
+ def filterNot(p: A => Boolean): Repr = filter(!p(_))
+
+ def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+ val b = bf(repr)
+ for (x <- this) if (pf.isDefinedAt(x)) b += pf(x)
+ b.result
+ }
+
+ /** Builds a new collection by applying an option-valued function to all
+ * elements of this $coll on which the function is defined.
+ *
+ * @param f the option-valued function which filters and maps the $coll.
+ * @tparam B the element type of the returned collection.
+ * @tparam That $thatinfo
+ * @param bf $bfinfo
+ * @return a new collection of type `That` resulting from applying the option-valued function
+ * `f` to each element and collecting all defined results.
+ * The order of the elements is preserved.
+ *
+ * @usecase def filterMap[B](f: A => Option[B]): $Coll[B]
+ *
+ * @param pf the partial function which filters and maps the $coll.
+ * @return a new $coll resulting from applying the given option-valued function
+ * `f` to each element and collecting all defined results.
+ * The order of the elements is preserved.
+ def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+ val b = bf(repr)
+ for (x <- this)
+ f(x) match {
+ case Some(y) => b += y
+ case _ =>
+ }
+ b.result
+ }
+ */
+
+ /** Partitions this $coll in two ${coll}s according to a predicate.
+ *
+ * @param p the predicate on which to partition.
+ * @return a pair of ${coll}s: the first $coll consists of all elements that
+ * satisfy the predicate `p` and the second $coll consists of all elements
+ * that don't. The relative order of the elements in the resulting ${coll}s
+ * is the same as in the original $coll.
+ */
+ def partition(p: A => Boolean): (Repr, Repr) = {
+ val l, r = newBuilder
+ for (x <- this) (if (p(x)) l else r) += x
+ (l.result, r.result)
+ }
+
+ def groupBy[K](f: A => K): immutable.Map[K, Repr] = {
+ val m = mutable.Map.empty[K, Builder[A, Repr]]
+ for (elem <- this) {
+ val key = f(elem)
+ val bldr = m.getOrElseUpdate(key, newBuilder)
+ bldr += elem
+ }
+ val b = immutable.Map.newBuilder[K, Repr]
+ for ((k, v) <- m)
+ b += ((k, v.result))
+
+ b.result
+ }
+
+ /** Tests whether a predicate holds for all elements of this $coll.
+ *
+ * $mayNotTerminateInf
+ *
+ * @param p the predicate used to test elements.
+ * @return `true` if the given predicate `p` holds for all elements
+ * of this $coll, otherwise `false`.
+ */
+ def forall(p: A => Boolean): Boolean = {
+ var result = true
+ breakable {
+ for (x <- this)
+ if (!p(x)) { result = false; break }
+ }
+ result
+ }
+
+ /** Tests whether a predicate holds for some of the elements of this $coll.
+ *
+ * $mayNotTerminateInf
+ *
+ * @param p the predicate used to test elements.
+ * @return `true` if the given predicate `p` holds for some of the
+ * elements of this $coll, otherwise `false`.
+ */
+ def exists(p: A => Boolean): Boolean = {
+ var result = false
+ breakable {
+ for (x <- this)
+ if (p(x)) { result = true; break }
+ }
+ result
+ }
+
+ /** Finds the first element of the $coll satisfying a predicate, if any.
+ *
+ * $mayNotTerminateInf
+ * $orderDependent
+ *
+ * @param p the predicate used to test elements.
+ * @return an option value containing the first element in the $coll
+ * that satisfies `p`, or `None` if none exists.
+ */
+ def find(p: A => Boolean): Option[A] = {
+ var result: Option[A] = None
+ breakable {
+ for (x <- this)
+ if (p(x)) { result = Some(x); break }
+ }
+ result
+ }
+
+ def scan[B >: A, That](z: B)(op: (B, B) => B)(implicit cbf: CanBuildFrom[Repr, B, That]): That = scanLeft(z)(op)
+
+ def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+ val b = bf(repr)
+ b.sizeHint(this, 1)
+ var acc = z
+ b += acc
+ for (x <- this) { acc = op(acc, x); b += acc }
+ b.result
+ }
+
+ @migration(2, 9,
+ "This scanRight definition has changed in 2.9.\n" +
+ "The previous behavior can be reproduced with scanRight.reverse."
+ )
+ def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+ var scanned = List(z)
+ var acc = z
+ for (x <- reversed) {
+ acc = op(x, acc)
+ scanned ::= acc
+ }
+ val b = bf(repr)
+ for (elem <- scanned) b += elem
+ b.result
+ }
+
+ /** Selects the first element of this $coll.
+ * $orderDependent
+ * @return the first element of this $coll.
+ * @throws `NoSuchElementException` if the $coll is empty.
+ */
+ def head: A = {
+ var result: () => A = () => throw new NoSuchElementException
+ breakable {
+ for (x <- this) {
+ result = () => x
+ break
+ }
+ }
+ result()
+ }
+
+ /** Optionally selects the first element.
+ * $orderDependent
+ * @return the first element of this $coll if it is nonempty, `None` if it is empty.
+ */
+ def headOption: Option[A] = if (isEmpty) None else Some(head)
+
+ /** Selects all elements except the first.
+ * $orderDependent
+ * @return a $coll consisting of all elements of this $coll
+ * except the first one.
+ * @throws `UnsupportedOperationException` if the $coll is empty.
+ */
+ override def tail: Repr = {
+ if (isEmpty) throw new UnsupportedOperationException("empty.tail")
+ drop(1)
+ }
+
+ /** Selects the last element.
+ * $orderDependent
+ * @return The last element of this $coll.
+ * @throws NoSuchElementException If the $coll is empty.
+ */
+ def last: A = {
+ var lst = head
+ for (x <- this)
+ lst = x
+ lst
+ }
+
+ /** Optionally selects the last element.
+ * $orderDependent
+ * @return the last element of this $coll$ if it is nonempty, `None` if it is empty.
+ */
+ def lastOption: Option[A] = if (isEmpty) None else Some(last)
+
+ /** Selects all elements except the last.
+ * $orderDependent
+ * @return a $coll consisting of all elements of this $coll
+ * except the last one.
+ * @throws `UnsupportedOperationException` if the $coll is empty.
+ */
+ def init: Repr = {
+ if (isEmpty) throw new UnsupportedOperationException("empty.init")
+ var lst = head
+ var follow = false
+ val b = newBuilder
+ b.sizeHint(this, -1)
+ for (x <- this.seq) {
+ if (follow) b += lst
+ else follow = true
+ lst = x
+ }
+ b.result
+ }
+
+ def take(n: Int): Repr = slice(0, n)
+
+ def drop(n: Int): Repr =
+ if (n <= 0) {
+ val b = newBuilder
+ b.sizeHint(this)
+ b ++= thisCollection result
+ }
+ else sliceWithKnownDelta(n, Int.MaxValue, -n)
+
+ def slice(from: Int, until: Int): Repr = sliceWithKnownBound(math.max(from, 0), until)
+
+ // Precondition: from >= 0, until > 0, builder already configured for building.
+ private[this] def sliceInternal(from: Int, until: Int, b: Builder[A, Repr]): Repr = {
+ var i = 0
+ breakable {
+ for (x <- this.seq) {
+ if (i >= from) b += x
+ i += 1
+ if (i >= until) break
+ }
+ }
+ b.result
+ }
+ // Precondition: from >= 0
+ private[scala] def sliceWithKnownDelta(from: Int, until: Int, delta: Int): Repr = {
+ val b = newBuilder
+ if (until <= from) b.result
+ else {
+ b.sizeHint(this, delta)
+ sliceInternal(from, until, b)
+ }
+ }
+ // Precondition: from >= 0
+ private[scala] def sliceWithKnownBound(from: Int, until: Int): Repr = {
+ val b = newBuilder
+ if (until <= from) b.result
+ else {
+ b.sizeHintBounded(until - from, this)
+ sliceInternal(from, until, b)
+ }
+ }
+
+ def takeWhile(p: A => Boolean): Repr = {
+ val b = newBuilder
+ breakable {
+ for (x <- this) {
+ if (!p(x)) break
+ b += x
+ }
+ }
+ b.result
+ }
+
+ def dropWhile(p: A => Boolean): Repr = {
+ val b = newBuilder
+ var go = false
+ for (x <- this) {
+ if (!p(x)) go = true
+ if (go) b += x
+ }
+ b.result
+ }
+
+ def span(p: A => Boolean): (Repr, Repr) = {
+ val l, r = newBuilder
+ var toLeft = true
+ for (x <- this) {
+ toLeft = toLeft && p(x)
+ (if (toLeft) l else r) += x
+ }
+ (l.result, r.result)
+ }
+
+ def splitAt(n: Int): (Repr, Repr) = {
+ val l, r = newBuilder
+ l.sizeHintBounded(n, this)
+ if (n >= 0) r.sizeHint(this, -n)
+ var i = 0
+ for (x <- this) {
+ (if (i < n) l else r) += x
+ i += 1
+ }
+ (l.result, r.result)
+ }
+
+ /** Iterates over the tails of this $coll. The first value will be this
+ * $coll and the final one will be an empty $coll, with the intervening
+ * values the results of successive applications of `tail`.
+ *
+ * @return an iterator over all the tails of this $coll
+ * @example `List(1,2,3).tails = Iterator(List(1,2,3), List(2,3), List(3), Nil)`
+ */
+ def tails: Iterator[Repr] = iterateUntilEmpty(_.tail)
+
+ /** Iterates over the inits of this $coll. The first value will be this
+ * $coll and the final one will be an empty $coll, with the intervening
+ * values the results of successive applications of `init`.
+ *
+ * @return an iterator over all the inits of this $coll
+ * @example `List(1,2,3).inits = Iterator(List(1,2,3), List(1,2), List(1), Nil)`
+ */
+ def inits: Iterator[Repr] = iterateUntilEmpty(_.init)
+
+ /** Copies elements of this $coll to an array.
+ * Fills the given array `xs` with at most `len` elements of
+ * this $coll, starting at position `start`.
+ * Copying will stop once either the end of the current $coll is reached,
+ * or the end of the array is reached, or `len` elements have been copied.
+ *
+ * $willNotTerminateInf
+ *
+ * @param xs the array to fill.
+ * @param start the starting index.
+ * @param len the maximal number of elements to copy.
+ * @tparam B the type of the elements of the array.
+ *
+ *
+ * @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit
+ */
+ def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
+ var i = start
+ val end = (start + len) min xs.length
+ breakable {
+ for (x <- this) {
+ if (i >= end) break
+ xs(i) = x
+ i += 1
+ }
+ }
+ }
+
+ def toTraversable: Traversable[A] = thisCollection
+ def toIterator: Iterator[A] = toStream.iterator
+ def toStream: Stream[A] = toBuffer.toStream
+
+ /** Converts this $coll to a string.
+ *
+ * @return a string representation of this collection. By default this
+ * string consists of the `stringPrefix` of this $coll,
+ * followed by all elements separated by commas and enclosed in parentheses.
+ */
+ override def toString = mkString(stringPrefix + "(", ", ", ")")
+
+ /** Defines the prefix of this object's `toString` representation.
+ *
+ * @return a string representation which starts the result of `toString`
+ * applied to this $coll. By default the string prefix is the
+ * simple name of the collection class $coll.
+ */
+ def stringPrefix : String = {
+ var string = repr.asInstanceOf[AnyRef].getClass.getName
+ val idx1 = string.lastIndexOf('.' : Int)
+ if (idx1 != -1) string = string.substring(idx1 + 1)
+ val idx2 = string.indexOf('$')
+ if (idx2 != -1) string = string.substring(0, idx2)
+ string
+ }
+
+ /** Creates a non-strict view of this $coll.
+ *
+ * @return a non-strict view of this $coll.
+ */
+ def view = new TraversableView[A, Repr] {
+ protected lazy val underlying = self.repr
+ override def foreach[U](f: A => U) = self foreach f
+ }
+
+ /** Creates a non-strict view of a slice of this $coll.
+ *
+ * Note: the difference between `view` and `slice` is that `view` produces
+ * a view of the current $coll, whereas `slice` produces a new $coll.
+ *
+ * Note: `view(from, to)` is equivalent to `view.slice(from, to)`
+ * $orderDependent
+ *
+ * @param from the index of the first element of the view
+ * @param until the index of the element following the view
+ * @return a non-strict view of a slice of this $coll, starting at index `from`
+ * and extending up to (but not including) index `until`.
+ */
+ def view(from: Int, until: Int): TraversableView[A, Repr] = view.slice(from, until)
+
+ /** Creates a non-strict filter of this $coll.
+ *
+ * Note: the difference between `c filter p` and `c withFilter p` is that
+ * the former creates a new collection, whereas the latter only
+ * restricts the domain of subsequent `map`, `flatMap`, `foreach`,
+ * and `withFilter` operations.
+ * $orderDependent
+ *
+ * @param p the predicate used to test elements.
+ * @return an object of class `WithFilter`, which supports
+ * `map`, `flatMap`, `foreach`, and `withFilter` operations.
+ * All these operations apply to those elements of this $coll which
+ * satisfy the predicate `p`.
+ */
+ def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p)
+
+ /** A class supporting filtered operations. Instances of this class are
+ * returned by method `withFilter`.
+ */
+ class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] {
+
+ /** Builds a new collection by applying a function to all elements of the
+ * outer $coll containing this `WithFilter` instance that satisfy predicate `p`.
+ *
+ * @param f the function to apply to each element.
+ * @tparam B the element type of the returned collection.
+ * @tparam That $thatinfo
+ * @param bf $bfinfo
+ * @return a new collection of type `That` resulting from applying
+ * the given function `f` to each element of the outer $coll
+ * that satisfies predicate `p` and collecting the results.
+ *
+ * @usecase def map[B](f: A => B): $Coll[B]
+ *
+ * @return a new $coll resulting from applying the given function
+ * `f` to each element of the outer $coll that satisfies
+ * predicate `p` and collecting the results.
+ */
+ def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+ val b = bf(repr)
+ for (x <- self)
+ if (p(x)) b += f(x)
+ b.result
+ }
+
+ /** Builds a new collection by applying a function to all elements of the
+ * outer $coll containing this `WithFilter` instance that satisfy
+ * predicate `p` and concatenating the results.
+ *
+ * @param f the function to apply to each element.
+ * @tparam B the element type of the returned collection.
+ * @tparam That $thatinfo
+ * @param bf $bfinfo
+ * @return a new collection of type `That` resulting from applying
+ * the given collection-valued function `f` to each element
+ * of the outer $coll that satisfies predicate `p` and
+ * concatenating the results.
+ *
+ * @usecase def flatMap[B](f: A => TraversableOnce[B]): $Coll[B]
+ *
+ * @return a new $coll resulting from applying the given collection-valued function
+ * `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.
+ */
+ def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+ val b = bf(repr)
+ for (x <- self)
+ if (p(x)) b ++= f(x).seq
+ b.result
+ }
+
+ /** Applies a function `f` to all elements of the outer $coll containing
+ * this `WithFilter` instance that satisfy predicate `p`.
+ *
+ * @param f the function that is applied for its side-effect to every element.
+ * The result of function `f` is discarded.
+ *
+ * @tparam U the type parameter describing the result of function `f`.
+ * This result will always be ignored. Typically `U` is `Unit`,
+ * but this is not necessary.
+ *
+ * @usecase def foreach(f: A => Unit): Unit
+ */
+ def foreach[U](f: A => U): Unit =
+ for (x <- self)
+ if (p(x)) f(x)
+
+ /** Further refines the filter for this $coll.
+ *
+ * @param q the predicate used to test elements.
+ * @return an object of class `WithFilter`, which supports
+ * `map`, `flatMap`, `foreach`, and `withFilter` operations.
+ * All these operations apply to those elements of this $coll which
+ * satisfy the predicate `q` in addition to the predicate `p`.
+ */
+ def withFilter(q: A => Boolean): WithFilter =
+ new WithFilter(x => p(x) && q(x))
+ }
+
+ // A helper for tails and inits.
+ private def iterateUntilEmpty(f: Traversable[A @uV] => Traversable[A @uV]): Iterator[Repr] = {
+ val it = Iterator.iterate(thisCollection)(f) takeWhile (x => !x.isEmpty)
+ it ++ Iterator(Nil) map (newBuilder ++= _ result)
+ }
+ }
+
+
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/CssTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/CssTokenizerTest.java
new file mode 100644
index 0000000000..fde88a06b9
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/CssTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.css;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.css.CssTokenizer;
+
+public class CssTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new CssTokenizer(), new String[]{"css/css.js"}, "test.css");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/LESSTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/LESSTokenizerTest.java
new file mode 100644
index 0000000000..befe57299f
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/LESSTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.css;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.css.LESSTokenizer;
+
+public class LESSTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new LESSTokenizer(), new String[]{"css/css.js"}, "test.less");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/SCSSTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/SCSSTokenizerTest.java
new file mode 100644
index 0000000000..d179427549
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/SCSSTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.css;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.css.SCSSTokenizer;
+
+public class SCSSTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new SCSSTokenizer(), new String[]{"css/css.js"}, "test.scss");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/test.css b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/test.css
new file mode 100644
index 0000000000..212f09cb56
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/test.css
@@ -0,0 +1,33 @@
+/* Some example CSS */
+
+@import url("something.css");
+
+body {
+ margin: 0;
+ padding: 3em 6em;
+ font-family: tahoma, arial, sans-serif;
+ color: #000;
+}
+
+#navigation a {
+ font-weight: bold;
+ text-decoration: none !important;
+}
+
+h1 {
+ font-size: 2.5em;
+}
+
+h2 {
+ font-size: 1.7em;
+}
+
+h1:before, h2:before {
+ content: "::";
+}
+
+code {
+ font-family: courier, monospace;
+ font-size: 80%;
+ color: #418A8A;
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/test.less b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/test.less
new file mode 100644
index 0000000000..3d8ba0401d
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/test.less
@@ -0,0 +1,112 @@
+@media screen and (device-aspect-ratio: 16/9) { … }
+@media screen and (device-aspect-ratio: 1280/720) { … }
+@media screen and (device-aspect-ratio: 2560/1440) { … }
+
+html:lang(fr-be)
+
+tr:nth-child(2n+1) /* represents every odd row of an HTML table */
+
+img:nth-of-type(2n+1) { float: right; }
+img:nth-of-type(2n) { float: left; }
+
+body > h2:not(:first-of-type):not(:last-of-type)
+
+html|*:not(:link):not(:visited)
+*|*:not(:hover)
+p::first-line { text-transform: uppercase }
+
+@namespace foo url(http://www.example.com);
+foo|h1 { color: blue } /* first rule */
+
+span[hello="Ocean"][goodbye="Land"]
+
+E[foo]{
+ padding:65px;
+}
+
+input[type="search"]::-webkit-search-decoration,
+input[type="search"]::-webkit-search-cancel-button {
+ -webkit-appearance: none; // Inner-padding issues in Chrome OSX, Safari 5
+}
+button::-moz-focus-inner,
+input::-moz-focus-inner { // Inner padding and border oddities in FF3/4
+ padding: 0;
+ border: 0;
+}
+.btn {
+ // reset here as of 2.0.3 due to Recess property order
+ border-color: #ccc;
+ border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);
+}
+fieldset span button, fieldset span input[type="file"] {
+ font-size:12px;
+ font-family:Arial, Helvetica, sans-serif;
+}
+
+.rounded-corners (@radius: 5px) {
+ border-radius: @radius;
+ -webkit-border-radius: @radius;
+ -moz-border-radius: @radius;
+}
+
+@import url("something.css");
+
+@light-blue: hsl(190, 50%, 65%);
+
+#menu {
+ position: absolute;
+ width: 100%;
+ z-index: 3;
+ clear: both;
+ display: block;
+ background-color: @blue;
+ height: 42px;
+ border-top: 2px solid lighten(@alpha-blue, 20%);
+ border-bottom: 2px solid darken(@alpha-blue, 25%);
+ .box-shadow(0, 1px, 8px, 0.6);
+ -moz-box-shadow: 0 0 0 #000; // Because firefox sucks.
+
+ &.docked {
+ background-color: hsla(210, 60%, 40%, 0.4);
+ }
+ &:hover {
+ background-color: @blue;
+ }
+
+ #dropdown {
+ margin: 0 0 0 117px;
+ padding: 0;
+ padding-top: 5px;
+ display: none;
+ width: 190px;
+ border-top: 2px solid @medium;
+ color: @highlight;
+ border: 2px solid darken(@medium, 25%);
+ border-left-color: darken(@medium, 15%);
+ border-right-color: darken(@medium, 15%);
+ border-top-width: 0;
+ background-color: darken(@medium, 10%);
+ ul {
+ padding: 0px;
+ }
+ li {
+ font-size: 14px;
+ display: block;
+ text-align: left;
+ padding: 0;
+ border: 0;
+ a {
+ display: block;
+ padding: 0px 15px;
+ text-decoration: none;
+ color: white;
+ &:hover {
+ background-color: darken(@medium, 15%);
+ text-decoration: none;
+ }
+ }
+ }
+ .border-radius(5px, bottom);
+ .box-shadow(0, 6px, 8px, 0.5);
+ }
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/test.scss b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/test.scss
new file mode 100644
index 0000000000..e6aa2a9e61
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/css/test.scss
@@ -0,0 +1,116 @@
+/* Some example SCSS */
+
+@import "compass/css3";
+$variable: #333;
+
+$blue: #3bbfce;
+$margin: 16px;
+
+.content-navigation {
+ #nested {
+ background-color: black;
+ }
+ border-color: $blue;
+ color:
+ darken($blue, 9%);
+}
+
+.border {
+ padding: $margin / 2;
+ margin: $margin / 2;
+ border-color: $blue;
+}
+
+@mixin table-base {
+ th {
+ text-align: center;
+ font-weight: bold;
+ }
+ td, th {padding: 2px}
+}
+
+table.hl {
+ margin: 2em 0;
+ td.ln {
+ text-align: right;
+ }
+}
+
+li {
+ font: {
+ family: serif;
+ weight: bold;
+ size: 1.2em;
+ }
+}
+
+@mixin left($dist) {
+ float: left;
+ margin-left: $dist;
+}
+
+#data {
+ @include left(10px);
+ @include table-base;
+}
+
+.source {
+ @include flow-into(target);
+ border: 10px solid green;
+ margin: 20px;
+ width: 200px; }
+
+.new-container {
+ @include flow-from(target);
+ border: 10px solid red;
+ margin: 20px;
+ width: 200px; }
+
+body {
+ margin: 0;
+ padding: 3em 6em;
+ font-family: tahoma, arial, sans-serif;
+ color: #000;
+}
+
+@mixin yellow() {
+ background: yellow;
+}
+
+.big {
+ font-size: 14px;
+}
+
+.nested {
+ @include border-radius(3px);
+ @extend .big;
+ p {
+ background: whitesmoke;
+ a {
+ color: red;
+ }
+ }
+}
+
+#navigation a {
+ font-weight: bold;
+ text-decoration: none !important;
+}
+
+h1 {
+ font-size: 2.5em;
+}
+
+h2 {
+ font-size: 1.7em;
+}
+
+h1:before, h2:before {
+ content: "::";
+}
+
+code {
+ font-family: courier, monospace;
+ font-size: 80%;
+ color: #418A8A;
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/JSONLDTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/JSONLDTokenizerTest.java
new file mode 100644
index 0000000000..36a0750791
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/JSONLDTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.javascript;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.javascript.JSONLDTokenizer;
+
+public class JSONLDTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new JSONLDTokenizer(), new String[]{"javascript/javascript.js"}, "test.jsonld");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/JSONTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/JSONTokenizerTest.java
new file mode 100644
index 0000000000..b31b2d27af
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/JSONTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.javascript;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.javascript.JSONTokenizer;
+
+public class JSONTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new JSONTokenizer(), new String[]{"javascript/javascript.js"}, "test.json");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/JavascriptTokenzierTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/JavascriptTokenzierTest.java
new file mode 100644
index 0000000000..92d02cb7a4
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/JavascriptTokenzierTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.javascript;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.javascript.JavaScriptTokenizer;
+
+public class JavascriptTokenzierTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new JavaScriptTokenizer(), new String[]{"javascript/javascript.js"}, "test.js");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/TypeScriptTokenizerTest.java b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/TypeScriptTokenizerTest.java
new file mode 100644
index 0000000000..6e7b3a57f1
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/TypeScriptTokenizerTest.java
@@ -0,0 +1,15 @@
+package com.pmease.commons.lang.tokenizers.javascript;
+
+import org.junit.Test;
+
+import com.pmease.commons.lang.tokenizers.AbstractTokenizerTest;
+import com.pmease.commons.lang.tokenizers.javascript.TypeScriptTokenizer;
+
+public class TypeScriptTokenizerTest extends AbstractTokenizerTest {
+
+ @Test
+ public void test() {
+ verify(new TypeScriptTokenizer(), new String[]{"javascript/javascript.js"}, "test.ts");
+ }
+
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.js b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.js
new file mode 100644
index 0000000000..91b0e89a06
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.js
@@ -0,0 +1,200 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+(function() {
+ var mode = CodeMirror.getMode({indentUnit: 2}, "javascript");
+ function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+ MT("locals",
+ "[keyword function] [variable foo]([def a], [def b]) { [keyword var] [def c] [operator =] [number 10]; [keyword return] [variable-2 a] [operator +] [variable-2 c] [operator +] [variable d]; }");
+
+ MT("comma-and-binop",
+ "[keyword function](){ [keyword var] [def x] [operator =] [number 1] [operator +] [number 2], [def y]; }");
+
+ MT("destructuring",
+ "([keyword function]([def a], [[[def b], [def c] ]]) {",
+ " [keyword let] {[def d], [property foo]: [def c][operator =][number 10], [def x]} [operator =] [variable foo]([variable-2 a]);",
+ " [[[variable-2 c], [variable y] ]] [operator =] [variable-2 c];",
+ "})();");
+
+ MT("class_body",
+ "[keyword class] [variable Foo] {",
+ " [property constructor]() {}",
+ " [property sayName]() {",
+ " [keyword return] [string-2 `foo${][variable foo][string-2 }oo`];",
+ " }",
+ "}");
+
+ MT("class",
+ "[keyword class] [variable Point] [keyword extends] [variable SuperThing] {",
+ " [property get] [property prop]() { [keyword return] [number 24]; }",
+ " [property constructor]([def x], [def y]) {",
+ " [keyword super]([string 'something']);",
+ " [keyword this].[property x] [operator =] [variable-2 x];",
+ " }",
+ "}");
+
+ MT("module",
+ "[keyword module] [string 'foo'] {",
+ " [keyword export] [keyword let] [def x] [operator =] [number 42];",
+ " [keyword export] [keyword *] [keyword from] [string 'somewhere'];",
+ "}");
+
+ MT("import",
+ "[keyword function] [variable foo]() {",
+ " [keyword import] [def $] [keyword from] [string 'jquery'];",
+ " [keyword module] [def crypto] [keyword from] [string 'crypto'];",
+ " [keyword import] { [def encrypt], [def decrypt] } [keyword from] [string 'crypto'];",
+ "}");
+
+ MT("const",
+ "[keyword function] [variable f]() {",
+ " [keyword const] [[ [def a], [def b] ]] [operator =] [[ [number 1], [number 2] ]];",
+ "}");
+
+ MT("for/of",
+ "[keyword for]([keyword let] [variable of] [keyword of] [variable something]) {}");
+
+ MT("generator",
+ "[keyword function*] [variable repeat]([def n]) {",
+ " [keyword for]([keyword var] [def i] [operator =] [number 0]; [variable-2 i] [operator <] [variable-2 n]; [operator ++][variable-2 i])",
+ " [keyword yield] [variable-2 i];",
+ "}");
+
+ MT("quotedStringAddition",
+ "[keyword let] [variable f] [operator =] [variable a] [operator +] [string 'fatarrow'] [operator +] [variable c];");
+
+ MT("quotedFatArrow",
+ "[keyword let] [variable f] [operator =] [variable a] [operator +] [string '=>'] [operator +] [variable c];");
+
+ MT("fatArrow",
+ "[variable array].[property filter]([def a] [operator =>] [variable-2 a] [operator +] [number 1]);",
+ "[variable a];", // No longer in scope
+ "[keyword let] [variable f] [operator =] ([[ [def a], [def b] ]], [def c]) [operator =>] [variable-2 a] [operator +] [variable-2 c];",
+ "[variable c];");
+
+ MT("spread",
+ "[keyword function] [variable f]([def a], [meta ...][def b]) {",
+ " [variable something]([variable-2 a], [meta ...][variable-2 b]);",
+ "}");
+
+ MT("comprehension",
+ "[keyword function] [variable f]() {",
+ " [[([variable x] [operator +] [number 1]) [keyword for] ([keyword var] [def x] [keyword in] [variable y]) [keyword if] [variable pred]([variable-2 x]) ]];",
+ " ([variable u] [keyword for] ([keyword var] [def u] [keyword of] [variable generateValues]()) [keyword if] ([variable-2 u].[property color] [operator ===] [string 'blue']));",
+ "}");
+
+ MT("quasi",
+ "[variable re][string-2 `fofdlakj${][variable x] [operator +] ([variable re][string-2 `foo`]) [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]");
+
+ MT("quasi_no_function",
+ "[variable x] [operator =] [string-2 `fofdlakj${][variable x] [operator +] [string-2 `foo`] [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]");
+
+ MT("indent_statement",
+ "[keyword var] [variable x] [operator =] [number 10]",
+ "[variable x] [operator +=] [variable y] [operator +]",
+ " [atom Infinity]",
+ "[keyword debugger];");
+
+ MT("indent_if",
+ "[keyword if] ([number 1])",
+ " [keyword break];",
+ "[keyword else] [keyword if] ([number 2])",
+ " [keyword continue];",
+ "[keyword else]",
+ " [number 10];",
+ "[keyword if] ([number 1]) {",
+ " [keyword break];",
+ "} [keyword else] [keyword if] ([number 2]) {",
+ " [keyword continue];",
+ "} [keyword else] {",
+ " [number 10];",
+ "}");
+
+ MT("indent_for",
+ "[keyword for] ([keyword var] [variable i] [operator =] [number 0];",
+ " [variable i] [operator <] [number 100];",
+ " [variable i][operator ++])",
+ " [variable doSomething]([variable i]);",
+ "[keyword debugger];");
+
+ MT("indent_c_style",
+ "[keyword function] [variable foo]()",
+ "{",
+ " [keyword debugger];",
+ "}");
+
+ MT("indent_else",
+ "[keyword for] (;;)",
+ " [keyword if] ([variable foo])",
+ " [keyword if] ([variable bar])",
+ " [number 1];",
+ " [keyword else]",
+ " [number 2];",
+ " [keyword else]",
+ " [number 3];");
+
+ MT("indent_funarg",
+ "[variable foo]([number 10000],",
+ " [keyword function]([def a]) {",
+ " [keyword debugger];",
+ "};");
+
+ MT("indent_below_if",
+ "[keyword for] (;;)",
+ " [keyword if] ([variable foo])",
+ " [number 1];",
+ "[number 2];");
+
+ MT("multilinestring",
+ "[keyword var] [variable x] [operator =] [string 'foo\\]",
+ "[string bar'];");
+
+ MT("scary_regexp",
+ "[string-2 /foo[[/]]bar/];");
+
+ MT("indent_strange_array",
+ "[keyword var] [variable x] [operator =] [[",
+ " [number 1],,",
+ " [number 2],",
+ "]];",
+ "[number 10];");
+
+ var jsonld_mode = CodeMirror.getMode(
+ {indentUnit: 2},
+ {name: "javascript", jsonld: true}
+ );
+ function LD(name) {
+ test.mode(name, jsonld_mode, Array.prototype.slice.call(arguments, 1));
+ }
+
+ LD("json_ld_keywords",
+ '{',
+ ' [meta "@context"]: {',
+ ' [meta "@base"]: [string "http://example.com"],',
+ ' [meta "@vocab"]: [string "http://xmlns.com/foaf/0.1/"],',
+ ' [property "likesFlavor"]: {',
+ ' [meta "@container"]: [meta "@list"]',
+ ' [meta "@reverse"]: [string "@beFavoriteOf"]',
+ ' },',
+ ' [property "nick"]: { [meta "@container"]: [meta "@set"] },',
+ ' [property "nick"]: { [meta "@container"]: [meta "@index"] }',
+ ' },',
+ ' [meta "@graph"]: [[ {',
+ ' [meta "@id"]: [string "http://dbpedia.org/resource/John_Lennon"],',
+ ' [property "name"]: [string "John Lennon"],',
+ ' [property "modified"]: {',
+ ' [meta "@value"]: [string "2010-05-29T14:17:39+02:00"],',
+ ' [meta "@type"]: [string "http://www.w3.org/2001/XMLSchema#dateTime"]',
+ ' }',
+ ' } ]]',
+ '}');
+
+ LD("json_ld_fake",
+ '{',
+ ' [property "@fake"]: [string "@fake"],',
+ ' [property "@contextual"]: [string "@identifier"],',
+ ' [property "[email protected]"]: [string "@graphical"],',
+ ' [property "@ID"]: [string "@@ID"]',
+ '}');
+})();
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.json b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.json
new file mode 100644
index 0000000000..b07325f5aa
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.json
@@ -0,0 +1,98 @@
+{
+ "100": {
+ "aliases": "",
+ "keywords": "hundred points symbol numbers perfect score 100 percent a plus perfect school quiz score test exam",
+ "shortname": ":100:",
+ "unicode": "1F4AF"
+ },
+ "1234": {
+ "aliases": "",
+ "keywords": "input symbol for numbers blue-square numbers",
+ "shortname": ":1234:",
+ "unicode": "1F522"
+ },
+ "8ball": {
+ "aliases": "",
+ "keywords": "billiards pool billiards eight ball pool pocket ball cue",
+ "shortname": ":8ball:",
+ "unicode": "1F3B1"
+ },
+ "a": {
+ "aliases": "",
+ "keywords": "negative squared latin capital letter a alphabet letter red-square",
+ "shortname": ":a:",
+ "unicode": "1F170"
+ },
+ "ab": {
+ "aliases": "",
+ "keywords": "negative squared ab alphabet red-square",
+ "shortname": ":ab:",
+ "unicode": "1F18E"
+ },
+ "abc": {
+ "aliases": "",
+ "keywords": "input symbol for latin letters alphabet blue-square",
+ "shortname": ":abc:",
+ "unicode": "1F524"
+ },
+ "abcd": {
+ "aliases": "",
+ "keywords": "input symbol for latin small letters alphabet blue-square",
+ "shortname": ":abcd:",
+ "unicode": "1F521"
+ },
+ "ac": {
+ "aliases": "",
+ "keywords": "ascension country nation",
+ "shortname": ":ac:",
+ "unicode": "1F1E6-1F1E8"
+ },
+ "accept": {
+ "aliases": "",
+ "keywords": "circled ideograph accept agree chinese good kanji ok yes",
+ "shortname": ":accept:",
+ "unicode": "1F251"
+ },
+ "ad": {
+ "aliases": "",
+ "keywords": "andorra country nation",
+ "shortname": ":ad:",
+ "unicode": "1F1E6-1F1E9"
+ },
+ "ae": {
+ "aliases": "",
+ "keywords": "the united arab emirates country nation",
+ "shortname": ":ae:",
+ "unicode": "1F1E6-1F1EA"
+ },
+ "aerial_tramway": {
+ "aliases": "",
+ "keywords": "aerial tramway transportation vehicle aerial tram tramway cable transport",
+ "shortname": ":aerial_tramway:",
+ "unicode": "1F6A1"
+ },
+ "af": {
+ "aliases": "",
+ "keywords": "afghanistan country nation afghanestan",
+ "shortname": ":af:",
+ "unicode": "1F1E6-1F1EB"
+ },
+ "ag": {
+ "aliases": "",
+ "keywords": "antigua and barbuda country nation",
+ "shortname": ":ag:",
+ "unicode": "1F1E6-1F1EC"
+ },
+ "ai": {
+ "aliases": "",
+ "keywords": "anguilla country nation",
+ "shortname": ":ai:",
+ "unicode": "1F1E6-1F1EE"
+ },
+ "airplane": {
+ "aliases": "",
+ "keywords": "airplane flight transportation vehicle airplane plane airport travel airlines fly jet jumbo boeing airbus",
+ "shortname": ":airplane:",
+ "unicode": "2708"
+ }
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.jsonld b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.jsonld
new file mode 100644
index 0000000000..a6fa380690
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.jsonld
@@ -0,0 +1,27 @@
+{
+ "@context": {
+ "name": "http://schema.org/name",
+ "description": "http://schema.org/description",
+ "image": {
+ "@id": "http://schema.org/image",
+ "@type": "@id"
+ },
+ "geo": "http://schema.org/geo",
+ "latitude": {
+ "@id": "http://schema.org/latitude",
+ "@type": "xsd:float"
+ },
+ "longitude": {
+ "@id": "http://schema.org/longitude",
+ "@type": "xsd:float"
+ },
+ "xsd": "http://www.w3.org/2001/XMLSchema#"
+ },
+ "name": "The Empire State Building",
+ "description": "The Empire State Building is a 102-story landmark in New York City.",
+ "image": "http://www.civil.usherbrooke.ca/cours/gci215a/empire-state-building.jpg",
+ "geo": {
+ "latitude": "40.75",
+ "longitude": "73.98"
+ }
+}
diff --git a/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.ts b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.ts
new file mode 100644
index 0000000000..558decd5d5
--- /dev/null
+++ b/commons.lang/src/test/java/com/pmease/commons/lang/tokenizers/javascript/test.ts
@@ -0,0 +1,20 @@
+class Greeter {
+ greeting: string;
+ constructor (message: string) {
+ this.greeting = message;
+ }
+ greet() {
+ return "Hello, " + this.greeting;
+ }
+}
+
+var greeter = new Greeter("world");
+
+var button = document.createElement('button')
+button.innerText = "Say Hello"
+button.onclick = function() {
+ alert(greeter.greet())
+}
+
+document.body.appendChild(button)
+