TokenStream.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import { adoptBuffer } from './adopt-buffer.js';
  2. import { cmpStr } from './utils.js';
  3. import tokenNames from './names.js';
  4. import {
  5. WhiteSpace,
  6. Comment,
  7. Delim,
  8. EOF,
  9. Function as FunctionToken,
  10. LeftParenthesis,
  11. RightParenthesis,
  12. LeftSquareBracket,
  13. RightSquareBracket,
  14. LeftCurlyBracket,
  15. RightCurlyBracket
  16. } from './types.js';
  17. const OFFSET_MASK = 0x00FFFFFF;
  18. const TYPE_SHIFT = 24;
  19. const BLOCK_OPEN_TOKEN = 1;
  20. const BLOCK_CLOSE_TOKEN = 2;
  21. const balancePair = new Uint8Array(32); // 32b of memory ought to be enough for anyone (any number of tokens)
  22. balancePair[FunctionToken] = RightParenthesis;
  23. balancePair[LeftParenthesis] = RightParenthesis;
  24. balancePair[LeftSquareBracket] = RightSquareBracket;
  25. balancePair[LeftCurlyBracket] = RightCurlyBracket;
  26. const blockTokens = new Uint8Array(32);
  27. blockTokens[FunctionToken] = BLOCK_OPEN_TOKEN;
  28. blockTokens[LeftParenthesis] = BLOCK_OPEN_TOKEN;
  29. blockTokens[LeftSquareBracket] = BLOCK_OPEN_TOKEN;
  30. blockTokens[LeftCurlyBracket] = BLOCK_OPEN_TOKEN;
  31. blockTokens[RightParenthesis] = BLOCK_CLOSE_TOKEN;
  32. blockTokens[RightSquareBracket] = BLOCK_CLOSE_TOKEN;
  33. blockTokens[RightCurlyBracket] = BLOCK_CLOSE_TOKEN;
  34. function boundIndex(index, min, max) {
  35. return index < min ? min : index > max ? max : index;
  36. }
  37. export class TokenStream {
  38. constructor(source, tokenize) {
  39. this.setSource(source, tokenize);
  40. }
  41. reset() {
  42. this.eof = false;
  43. this.tokenIndex = -1;
  44. this.tokenType = 0;
  45. this.tokenStart = this.firstCharOffset;
  46. this.tokenEnd = this.firstCharOffset;
  47. }
  48. setSource(source = '', tokenize = () => {}) {
  49. source = String(source || '');
  50. const sourceLength = source.length;
  51. const offsetAndType = adoptBuffer(this.offsetAndType, source.length + 1); // +1 because of eof-token
  52. const balance = adoptBuffer(this.balance, source.length + 1);
  53. let tokenCount = 0;
  54. let firstCharOffset = -1;
  55. let balanceCloseType = 0;
  56. let balanceStart = source.length;
  57. // capture buffers
  58. this.offsetAndType = null;
  59. this.balance = null;
  60. balance.fill(0);
  61. tokenize(source, (type, start, end) => {
  62. const index = tokenCount++;
  63. // type & offset
  64. offsetAndType[index] = (type << TYPE_SHIFT) | end;
  65. if (firstCharOffset === -1) {
  66. firstCharOffset = start;
  67. }
  68. // balance
  69. balance[index] = balanceStart;
  70. if (type === balanceCloseType) {
  71. const prevBalanceStart = balance[balanceStart];
  72. // set reference to balance end for a block opener
  73. balance[balanceStart] = index;
  74. // pop state
  75. balanceStart = prevBalanceStart;
  76. balanceCloseType = balancePair[offsetAndType[prevBalanceStart] >> TYPE_SHIFT];
  77. } else if (this.isBlockOpenerTokenType(type)) { // check for FunctionToken, <(-token>, <[-token> and <{-token>
  78. // push state
  79. balanceStart = index;
  80. balanceCloseType = balancePair[type];
  81. }
  82. });
  83. // finalize buffers
  84. offsetAndType[tokenCount] = (EOF << TYPE_SHIFT) | sourceLength; // <EOF-token>
  85. balance[tokenCount] = tokenCount; // prevents false positive balance match with any token
  86. // reverse references from balance start to end
  87. // tokens
  88. // token: a ( [ b c ] d e ) {
  89. // index: 0 1 2 3 4 5 6 7 8 9
  90. // before
  91. // balance: 0 8 5 2 2 2 1 1 1 0
  92. // - > > < < < < < < -
  93. // after
  94. // balance: 9 8 5 5 5 2 8 8 1 9
  95. // > > > > > < > > < >
  96. for (let i = 0; i < tokenCount; i++) {
  97. const balanceStart = balance[i];
  98. if (balanceStart <= i) {
  99. const balanceEnd = balance[balanceStart];
  100. if (balanceEnd !== i) {
  101. balance[i] = balanceEnd;
  102. }
  103. } else if (balanceStart > tokenCount) {
  104. balance[i] = tokenCount;
  105. }
  106. }
  107. // balance[0] = tokenCount;
  108. this.source = source;
  109. this.firstCharOffset = firstCharOffset === -1 ? 0 : firstCharOffset;
  110. this.tokenCount = tokenCount;
  111. this.offsetAndType = offsetAndType;
  112. this.balance = balance;
  113. this.reset();
  114. this.next();
  115. }
  116. lookupType(offset) {
  117. offset += this.tokenIndex;
  118. if (offset < this.tokenCount) {
  119. return this.offsetAndType[offset] >> TYPE_SHIFT;
  120. }
  121. return EOF;
  122. }
  123. lookupTypeNonSC(idx) {
  124. for (let offset = this.tokenIndex; offset < this.tokenCount; offset++) {
  125. const tokenType = this.offsetAndType[offset] >> TYPE_SHIFT;
  126. if (tokenType !== WhiteSpace && tokenType !== Comment) {
  127. if (idx-- === 0) {
  128. return tokenType;
  129. }
  130. }
  131. }
  132. return EOF;
  133. }
  134. lookupOffset(offset) {
  135. offset += this.tokenIndex;
  136. if (offset < this.tokenCount) {
  137. return this.offsetAndType[offset - 1] & OFFSET_MASK;
  138. }
  139. return this.source.length;
  140. }
  141. lookupOffsetNonSC(idx) {
  142. for (let offset = this.tokenIndex; offset < this.tokenCount; offset++) {
  143. const tokenType = this.offsetAndType[offset] >> TYPE_SHIFT;
  144. if (tokenType !== WhiteSpace && tokenType !== Comment) {
  145. if (idx-- === 0) {
  146. return offset - this.tokenIndex;
  147. }
  148. }
  149. }
  150. return EOF;
  151. }
  152. lookupValue(offset, referenceStr) {
  153. offset += this.tokenIndex;
  154. if (offset < this.tokenCount) {
  155. return cmpStr(
  156. this.source,
  157. this.offsetAndType[offset - 1] & OFFSET_MASK,
  158. this.offsetAndType[offset] & OFFSET_MASK,
  159. referenceStr
  160. );
  161. }
  162. return false;
  163. }
  164. getTokenStart(tokenIndex) {
  165. if (tokenIndex === this.tokenIndex) {
  166. return this.tokenStart;
  167. }
  168. if (tokenIndex > 0) {
  169. return tokenIndex < this.tokenCount
  170. ? this.offsetAndType[tokenIndex - 1] & OFFSET_MASK
  171. : this.offsetAndType[this.tokenCount] & OFFSET_MASK;
  172. }
  173. return this.firstCharOffset;
  174. }
  175. getTokenEnd(tokenIndex) {
  176. if (tokenIndex === this.tokenIndex) {
  177. return this.tokenEnd;
  178. }
  179. return this.offsetAndType[boundIndex(tokenIndex, 0, this.tokenCount)] & OFFSET_MASK;
  180. }
  181. getTokenType(tokenIndex) {
  182. if (tokenIndex === this.tokenIndex) {
  183. return this.tokenType;
  184. }
  185. return this.offsetAndType[boundIndex(tokenIndex, 0, this.tokenCount)] >> TYPE_SHIFT;
  186. }
  187. substrToCursor(start) {
  188. return this.source.substring(start, this.tokenStart);
  189. }
  190. isBlockOpenerTokenType(tokenType) {
  191. return blockTokens[tokenType] === BLOCK_OPEN_TOKEN;
  192. }
  193. isBlockCloserTokenType(tokenType) {
  194. return blockTokens[tokenType] === BLOCK_CLOSE_TOKEN;
  195. }
  196. getBlockTokenPairIndex(tokenIndex) {
  197. const type = this.getTokenType(tokenIndex);
  198. if (blockTokens[type] === 1) {
  199. // block open token
  200. const pairIndex = this.balance[tokenIndex];
  201. const closeType = this.getTokenType(pairIndex);
  202. return balancePair[type] === closeType ? pairIndex : -1;
  203. } else if (blockTokens[type] === 2) {
  204. // block close token
  205. const pairIndex = this.balance[tokenIndex];
  206. const openType = this.getTokenType(pairIndex);
  207. return balancePair[openType] === type ? pairIndex : -1;
  208. }
  209. return -1;
  210. }
  211. isBalanceEdge(tokenIndex) {
  212. return this.balance[this.tokenIndex] < tokenIndex;
  213. }
  214. isDelim(code, offset) {
  215. if (offset) {
  216. return (
  217. this.lookupType(offset) === Delim &&
  218. this.source.charCodeAt(this.lookupOffset(offset)) === code
  219. );
  220. }
  221. return (
  222. this.tokenType === Delim &&
  223. this.source.charCodeAt(this.tokenStart) === code
  224. );
  225. }
  226. skip(tokenCount) {
  227. let next = this.tokenIndex + tokenCount;
  228. if (next < this.tokenCount) {
  229. this.tokenIndex = next;
  230. this.tokenStart = this.offsetAndType[next - 1] & OFFSET_MASK;
  231. next = this.offsetAndType[next];
  232. this.tokenType = next >> TYPE_SHIFT;
  233. this.tokenEnd = next & OFFSET_MASK;
  234. } else {
  235. this.tokenIndex = this.tokenCount;
  236. this.next();
  237. }
  238. }
  239. next() {
  240. let next = this.tokenIndex + 1;
  241. if (next < this.tokenCount) {
  242. this.tokenIndex = next;
  243. this.tokenStart = this.tokenEnd;
  244. next = this.offsetAndType[next];
  245. this.tokenType = next >> TYPE_SHIFT;
  246. this.tokenEnd = next & OFFSET_MASK;
  247. } else {
  248. this.eof = true;
  249. this.tokenIndex = this.tokenCount;
  250. this.tokenType = EOF;
  251. this.tokenStart = this.tokenEnd = this.source.length;
  252. }
  253. }
  254. skipSC() {
  255. while (this.tokenType === WhiteSpace || this.tokenType === Comment) {
  256. this.next();
  257. }
  258. }
  259. skipUntilBalanced(startToken, stopConsume) {
  260. let cursor = startToken;
  261. let balanceEnd = 0;
  262. let offset = 0;
  263. loop:
  264. for (; cursor < this.tokenCount; cursor++) {
  265. balanceEnd = this.balance[cursor];
  266. // stop scanning on balance edge that points to offset before start token
  267. if (balanceEnd < startToken) {
  268. break loop;
  269. }
  270. offset = cursor > 0 ? this.offsetAndType[cursor - 1] & OFFSET_MASK : this.firstCharOffset;
  271. // check stop condition
  272. switch (stopConsume(this.source.charCodeAt(offset))) {
  273. case 1: // just stop
  274. break loop;
  275. case 2: // stop & included
  276. cursor++;
  277. break loop;
  278. default:
  279. // fast forward to the end of balanced block for an open block tokens
  280. if (this.isBlockOpenerTokenType(this.offsetAndType[cursor] >> TYPE_SHIFT)) {
  281. cursor = balanceEnd;
  282. }
  283. }
  284. }
  285. this.skip(cursor - this.tokenIndex);
  286. }
  287. forEachToken(fn) {
  288. for (let i = 0, offset = this.firstCharOffset; i < this.tokenCount; i++) {
  289. const start = offset;
  290. const item = this.offsetAndType[i];
  291. const end = item & OFFSET_MASK;
  292. const type = item >> TYPE_SHIFT;
  293. offset = end;
  294. fn(type, start, end, i);
  295. }
  296. }
  297. dump() {
  298. const tokens = new Array(this.tokenCount);
  299. this.forEachToken((type, start, end, index) => {
  300. tokens[index] = {
  301. idx: index,
  302. type: tokenNames[type],
  303. chunk: this.source.substring(start, end),
  304. balance: this.balance[index]
  305. };
  306. });
  307. return tokens;
  308. }
  309. };