tokenizer.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /* ***** BEGIN LICENSE BLOCK *****
  2. * Distributed under the BSD license:
  3. *
  4. * Copyright (c) 2010, Ajax.org B.V.
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * * Neither the name of Ajax.org B.V. nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * ***** END LICENSE BLOCK ***** */
  30. define(function(require, exports, module) {
  31. "use strict";
  32. // tokenizing lines longer than this makes editor very slow
  33. var MAX_TOKEN_COUNT = 1000;
  34. /**
  35. * This class takes a set of highlighting rules, and creates a tokenizer out of them. For more information, see [the wiki on extending highlighters](https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode#wiki-extendingTheHighlighter).
  36. * @class Tokenizer
  37. **/
  38. /**
  39. * Constructs a new tokenizer based on the given rules and flags.
  40. * @param {Object} rules The highlighting rules
  41. *
  42. * @constructor
  43. **/
  44. var Tokenizer = function(rules) {
  45. this.states = rules;
  46. this.regExps = {};
  47. this.matchMappings = {};
  48. for (var key in this.states) {
  49. var state = this.states[key];
  50. var ruleRegExps = [];
  51. var matchTotal = 0;
  52. var mapping = this.matchMappings[key] = {defaultToken: "text"};
  53. var flag = "g";
  54. var splitterRurles = [];
  55. for (var i = 0; i < state.length; i++) {
  56. var rule = state[i];
  57. if (rule.defaultToken)
  58. mapping.defaultToken = rule.defaultToken;
  59. if (rule.caseInsensitive)
  60. flag = "gi";
  61. if (rule.regex == null)
  62. continue;
  63. if (rule.regex instanceof RegExp)
  64. rule.regex = rule.regex.toString().slice(1, -1);
  65. // Count number of matching groups. 2 extra groups from the full match
  66. // And the catch-all on the end (used to force a match);
  67. var adjustedregex = rule.regex;
  68. var matchcount = new RegExp("(?:(" + adjustedregex + ")|(.))").exec("a").length - 2;
  69. if (Array.isArray(rule.token)) {
  70. if (rule.token.length == 1 || matchcount == 1) {
  71. rule.token = rule.token[0];
  72. } else if (matchcount - 1 != rule.token.length) {
  73. throw new Error("number of classes and regexp groups in '" +
  74. rule.token + "'\n'" + rule.regex + "' doesn't match\n"
  75. + (matchcount - 1) + "!=" + rule.token.length);
  76. } else {
  77. rule.tokenArray = rule.token;
  78. rule.token = null;
  79. rule.onMatch = this.$arrayTokens;
  80. }
  81. } else if (typeof rule.token == "function" && !rule.onMatch) {
  82. if (matchcount > 1)
  83. rule.onMatch = this.$applyToken;
  84. else
  85. rule.onMatch = rule.token;
  86. }
  87. if (matchcount > 1) {
  88. if (/\\\d/.test(rule.regex)) {
  89. // Replace any backreferences and offset appropriately.
  90. adjustedregex = rule.regex.replace(/\\([0-9]+)/g, function(match, digit) {
  91. return "\\" + (parseInt(digit, 10) + matchTotal + 1);
  92. });
  93. } else {
  94. matchcount = 1;
  95. adjustedregex = this.removeCapturingGroups(rule.regex);
  96. }
  97. if (!rule.splitRegex && typeof rule.token != "string")
  98. splitterRurles.push(rule); // flag will be known only at the very end
  99. }
  100. mapping[matchTotal] = i;
  101. matchTotal += matchcount;
  102. ruleRegExps.push(adjustedregex);
  103. // makes property access faster
  104. if (!rule.onMatch)
  105. rule.onMatch = null;
  106. rule.__proto__ = null;
  107. }
  108. splitterRurles.forEach(function(rule) {
  109. rule.splitRegex = this.createSplitterRegexp(rule.regex, flag);
  110. }, this);
  111. this.regExps[key] = new RegExp("(" + ruleRegExps.join(")|(") + ")|($)", flag);
  112. }
  113. };
  114. (function() {
  115. this.$setMaxTokenCount = function(m) {
  116. MAX_TOKEN_COUNT = m | 0;
  117. };
  118. this.$applyToken = function(str) {
  119. var values = this.splitRegex.exec(str).slice(1);
  120. var types = this.token.apply(this, values);
  121. // required for compatibility with old modes
  122. if (typeof types === "string")
  123. return [{type: types, value: str}];
  124. var tokens = [];
  125. for (var i = 0, l = types.length; i < l; i++) {
  126. if (values[i])
  127. tokens[tokens.length] = {
  128. type: types[i],
  129. value: values[i]
  130. };
  131. }
  132. return tokens;
  133. },
  134. this.$arrayTokens = function(str) {
  135. if (!str)
  136. return [];
  137. var values = this.splitRegex.exec(str);
  138. if (!values)
  139. return "text";
  140. var tokens = [];
  141. var types = this.tokenArray;
  142. for (var i = 0, l = types.length; i < l; i++) {
  143. if (values[i + 1])
  144. tokens[tokens.length] = {
  145. type: types[i],
  146. value: values[i + 1]
  147. };
  148. }
  149. return tokens;
  150. };
  151. this.removeCapturingGroups = function(src) {
  152. var r = src.replace(
  153. /\[(?:\\.|[^\]])*?\]|\\.|\(\?[:=!]|(\()/g,
  154. function(x, y) {return y ? "(?:" : x;}
  155. );
  156. return r;
  157. };
  158. this.createSplitterRegexp = function(src, flag) {
  159. if (src.indexOf("(?=") != -1) {
  160. var stack = 0;
  161. var inChClass = false;
  162. var lastCapture = {};
  163. src.replace(/(\\.)|(\((?:\?[=!])?)|(\))|([\[\]])/g, function(
  164. m, esc, parenOpen, parenClose, square, index
  165. ) {
  166. if (inChClass) {
  167. inChClass = square != "]";
  168. } else if (square) {
  169. inChClass = true;
  170. } else if (parenClose) {
  171. if (stack == lastCapture.stack) {
  172. lastCapture.end = index+1;
  173. lastCapture.stack = -1;
  174. }
  175. stack--;
  176. } else if (parenOpen) {
  177. stack++;
  178. if (parenOpen.length != 1) {
  179. lastCapture.stack = stack
  180. lastCapture.start = index;
  181. }
  182. }
  183. return m;
  184. });
  185. if (lastCapture.end != null && /^\)*$/.test(src.substr(lastCapture.end)))
  186. src = src.substring(0, lastCapture.start) + src.substr(lastCapture.end);
  187. }
  188. return new RegExp(src, (flag||"").replace("g", ""));
  189. };
  190. /**
  191. * Returns an object containing two properties: `tokens`, which contains all the tokens; and `state`, the current state.
  192. * @returns {Object}
  193. **/
  194. this.getLineTokens = function(line, startState) {
  195. if (startState && typeof startState != "string") {
  196. var stack = startState.slice(0);
  197. startState = stack[0];
  198. } else
  199. var stack = [];
  200. var currentState = startState || "start";
  201. var state = this.states[currentState];
  202. if (!state) {
  203. currentState = "start";
  204. state = this.states[currentState];
  205. }
  206. var mapping = this.matchMappings[currentState];
  207. var re = this.regExps[currentState];
  208. re.lastIndex = 0;
  209. var match, tokens = [];
  210. var lastIndex = 0;
  211. var token = {type: null, value: ""};
  212. while (match = re.exec(line)) {
  213. var type = mapping.defaultToken;
  214. var rule = null;
  215. var value = match[0];
  216. var index = re.lastIndex;
  217. if (index - value.length > lastIndex) {
  218. var skipped = line.substring(lastIndex, index - value.length);
  219. if (token.type == type) {
  220. token.value += skipped;
  221. } else {
  222. if (token.type)
  223. tokens.push(token);
  224. token = {type: type, value: skipped};
  225. }
  226. }
  227. for (var i = 0; i < match.length-2; i++) {
  228. if (match[i + 1] === undefined)
  229. continue;
  230. rule = state[mapping[i]];
  231. if (rule.onMatch)
  232. type = rule.onMatch(value, currentState, stack);
  233. else
  234. type = rule.token;
  235. if (rule.next) {
  236. if (typeof rule.next == "string")
  237. currentState = rule.next;
  238. else
  239. currentState = rule.next(currentState, stack);
  240. state = this.states[currentState];
  241. if (!state) {
  242. window.console && console.error && console.error(currentState, "doesn't exist");
  243. currentState = "start";
  244. state = this.states[currentState];
  245. }
  246. mapping = this.matchMappings[currentState];
  247. lastIndex = index;
  248. re = this.regExps[currentState];
  249. re.lastIndex = index;
  250. }
  251. break;
  252. }
  253. if (value) {
  254. if (typeof type == "string") {
  255. if ((!rule || rule.merge !== false) && token.type === type) {
  256. token.value += value;
  257. } else {
  258. if (token.type)
  259. tokens.push(token);
  260. token = {type: type, value: value};
  261. }
  262. } else if (type) {
  263. if (token.type)
  264. tokens.push(token);
  265. token = {type: null, value: ""};
  266. for (var i = 0; i < type.length; i++)
  267. tokens.push(type[i]);
  268. }
  269. }
  270. if (lastIndex == line.length)
  271. break;
  272. lastIndex = index;
  273. if (tokens.length > MAX_TOKEN_COUNT) {
  274. // chrome doens't show contents of text nodes with very long text
  275. while (lastIndex < line.length) {
  276. if (token.type)
  277. tokens.push(token);
  278. token = {
  279. value: line.substring(lastIndex, lastIndex += 2000),
  280. type: "overflow"
  281. };
  282. }
  283. currentState = "start";
  284. stack = [];
  285. break;
  286. }
  287. }
  288. if (token.type)
  289. tokens.push(token);
  290. return {
  291. tokens : tokens,
  292. state : stack.length ? stack : currentState
  293. };
  294. };
  295. }).call(Tokenizer.prototype);
  296. exports.Tokenizer = Tokenizer;
  297. });