35c3956a72352f8d1a58f4b917a7f2bbde7cf386
[Packages/TYPO3.CMS.git] / typo3 / sysext / t3editor / jslib / stringstream.js
1 /* String streams are the things fed to parsers (which can feed them
2 * to a tokenizer if they want). They provide peek and next methods
3 * for looking at the current character (next 'consumes' this
4 * character, peek does not), and a get method for retrieving all the
5 * text that was consumed since the last time get was called.
6 */
7
8 // Make a stream out of a single string. Not used by the editor, but
9 // very useful for testing your parser.
10 function singleStringStream(string) {
11 var pos = 0, start = 0;
12
13 function peek() {
14 if (pos < string.length)
15 return string.charAt(pos);
16 else
17 return null;
18 }
19
20 function next() {
21 if (pos >= string.length)
22 throw StopIteration;
23 return string.charAt(pos++);
24 }
25
26 function get() {
27 var result = string.slice(start, pos);
28 start = pos;
29 return result;
30 }
31
32 return {peek: peek, next: next, get: get};
33 }
34
35 // Make a string stream out of an iterator that returns strings. This
36 // is applied to the result of traverseDOM (see codemirror.js), and
37 // the resulting stream is fed to the parser.
38 function multiStringStream(source){
39 source = iter(source);
40 var current = "", pos = 0;
41 var peeked = null, accum = "";
42 var result = {peek: peek, next: next, get: get};
43
44 function peek(){
45 if (!peeked)
46 peeked = nextOr(result, null);
47 return peeked;
48 }
49 function next(){
50 if (peeked){
51 var temp = peeked;
52 peeked = null;
53 return temp;
54 }
55 while (pos == current.length){
56 accum += current;
57 current = ""; // In case source.next() throws
58 pos = 0;
59 current = source.next();
60 }
61 return current.charAt(pos++);
62 }
63 function get(){
64 var temp = accum;
65 var realPos = peeked ? pos - 1 : pos;
66 accum = "";
67 if (realPos > 0){
68 temp += current.slice(0, realPos);
69 current = current.slice(realPos);
70 pos = peeked ? 1 : 0;
71 }
72 return temp;
73 }
74
75 return result;
76 }