XTemplateCompiler.html 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>The source code</title>
  6. <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
  7. <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
  8. <style type="text/css">
  9. .highlight { display: block; background-color: #ddd; }
  10. </style>
  11. <script type="text/javascript">
  12. function highlight() {
  13. document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
  14. }
  15. </script>
  16. </head>
  17. <body onload="prettyPrint(); highlight();">
  18. <pre class="prettyprint lang-js"><span id='Ext-XTemplateCompiler'>/**
  19. </span> * This class compiles the XTemplate syntax into a function object. The function is used
  20. * like so:
  21. *
  22. * function (out, values, parent, xindex, xcount) {
  23. * // out is the output array to store results
  24. * // values, parent, xindex and xcount have their historical meaning
  25. * }
  26. *
  27. * @markdown
  28. * @private
  29. */
  30. Ext.define('Ext.XTemplateCompiler', {
  31. extend: 'Ext.XTemplateParser',
  32. // Chrome really likes &quot;new Function&quot; to realize the code block (as in it is
  33. // 2x-3x faster to call it than using eval), but Firefox chokes on it badly.
  34. // IE and Opera are also fine with the &quot;new Function&quot; technique.
  35. useEval: Ext.isGecko,
  36. // See http://jsperf.com/nige-array-append for quickest way to append to an array of unknown length
  37. // (Due to arbitrary code execution inside a template, we cannot easily track the length in var)
  38. // On IE6 and 7 myArray[myArray.length]='foo' is better. On other browsers myArray.push('foo') is better.
  39. useIndex: Ext.isIE6 || Ext.isIE7,
  40. useFormat: true,
  41. propNameRe: /^[\w\d\$]*$/,
  42. compile: function (tpl) {
  43. var me = this,
  44. code = me.generate(tpl);
  45. // When using &quot;new Function&quot;, we have to pass our &quot;Ext&quot; variable to it in order to
  46. // support sandboxing. If we did not, the generated function would use the global
  47. // &quot;Ext&quot;, not the &quot;Ext&quot; from our sandbox (scope chain).
  48. //
  49. return me.useEval ? me.evalTpl(code) : (new Function('Ext', code))(Ext);
  50. },
  51. generate: function (tpl) {
  52. var me = this,
  53. // note: Ext here is properly sandboxed
  54. definitions = 'var fm=Ext.util.Format,ts=Object.prototype.toString;',
  55. code;
  56. // Track how many levels we use, so that we only &quot;var&quot; each level's variables once
  57. me.maxLevel = 0;
  58. me.body = [
  59. 'var c0=values, a0=' + me.createArrayTest(0) + ', p0=parent, n0=xcount, i0=xindex, v;\n'
  60. ];
  61. if (me.definitions) {
  62. if (typeof me.definitions === 'string') {
  63. me.definitions = [me.definitions, definitions ];
  64. } else {
  65. me.definitions.push(definitions);
  66. }
  67. } else {
  68. me.definitions = [ definitions ];
  69. }
  70. me.switches = [];
  71. me.parse(tpl);
  72. me.definitions.push(
  73. (me.useEval ? '$=' : 'return') + ' function (' + me.fnArgs + ') {',
  74. me.body.join(''),
  75. '}'
  76. );
  77. code = me.definitions.join('\n');
  78. // Free up the arrays.
  79. me.definitions.length = me.body.length = me.switches.length = 0;
  80. delete me.definitions;
  81. delete me.body;
  82. delete me.switches;
  83. return code;
  84. },
  85. //-----------------------------------
  86. // XTemplateParser callouts
  87. doText: function (text) {
  88. var me = this,
  89. out = me.body;
  90. text = text.replace(me.aposRe, &quot;\\'&quot;).replace(me.newLineRe, '\\n');
  91. if (me.useIndex) {
  92. out.push('out[out.length]=\'', text, '\'\n');
  93. } else {
  94. out.push('out.push(\'', text, '\')\n');
  95. }
  96. },
  97. doExpr: function (expr) {
  98. var out = this.body;
  99. out.push('if ((v=' + expr + ')!==undefined) out');
  100. // Coerce value to string using concatenation of an empty string literal.
  101. // See http://jsperf.com/tostringvscoercion/5
  102. if (this.useIndex) {
  103. out.push('[out.length]=v+\'\'\n');
  104. } else {
  105. out.push('.push(v+\'\')\n');
  106. }
  107. },
  108. doTag: function (tag) {
  109. this.doExpr(this.parseTag(tag));
  110. },
  111. doElse: function () {
  112. this.body.push('} else {\n');
  113. },
  114. doEval: function (text) {
  115. this.body.push(text, '\n');
  116. },
  117. doIf: function (action, actions) {
  118. var me = this;
  119. // If it's just a propName, use it directly in the if
  120. if (action === '.') {
  121. me.body.push('if (values) {\n');
  122. } else if (me.propNameRe.test(action)) {
  123. me.body.push('if (', me.parseTag(action), ') {\n');
  124. }
  125. // Otherwise, it must be an expression, and needs to be returned from an fn which uses with(values)
  126. else {
  127. me.body.push('if (', me.addFn(action), me.callFn, ') {\n');
  128. }
  129. if (actions.exec) {
  130. me.doExec(actions.exec);
  131. }
  132. },
  133. doElseIf: function (action, actions) {
  134. var me = this;
  135. // If it's just a propName, use it directly in the else if
  136. if (action === '.') {
  137. me.body.push('else if (values) {\n');
  138. } else if (me.propNameRe.test(action)) {
  139. me.body.push('} else if (', me.parseTag(action), ') {\n');
  140. }
  141. // Otherwise, it must be an expression, and needs to be returned from an fn which uses with(values)
  142. else {
  143. me.body.push('} else if (', me.addFn(action), me.callFn, ') {\n');
  144. }
  145. if (actions.exec) {
  146. me.doExec(actions.exec);
  147. }
  148. },
  149. doSwitch: function (action) {
  150. var me = this;
  151. // If it's just a propName, use it directly in the switch
  152. if (action === '.') {
  153. me.body.push('switch (values) {\n');
  154. } else if (me.propNameRe.test(action)) {
  155. me.body.push('switch (', me.parseTag(action), ') {\n');
  156. }
  157. // Otherwise, it must be an expression, and needs to be returned from an fn which uses with(values)
  158. else {
  159. me.body.push('switch (', me.addFn(action), me.callFn, ') {\n');
  160. }
  161. me.switches.push(0);
  162. },
  163. doCase: function (action) {
  164. var me = this,
  165. cases = Ext.isArray(action) ? action : [action],
  166. n = me.switches.length - 1,
  167. match, i;
  168. if (me.switches[n]) {
  169. me.body.push('break;\n');
  170. } else {
  171. me.switches[n]++;
  172. }
  173. for (i = 0, n = cases.length; i &lt; n; ++i) {
  174. match = me.intRe.exec(cases[i]);
  175. cases[i] = match ? match[1] : (&quot;'&quot; + cases[i].replace(me.aposRe,&quot;\\'&quot;) + &quot;'&quot;);
  176. }
  177. me.body.push('case ', cases.join(': case '), ':\n');
  178. },
  179. doDefault: function () {
  180. var me = this,
  181. n = me.switches.length - 1;
  182. if (me.switches[n]) {
  183. me.body.push('break;\n');
  184. } else {
  185. me.switches[n]++;
  186. }
  187. me.body.push('default:\n');
  188. },
  189. doEnd: function (type, actions) {
  190. var me = this,
  191. L = me.level-1;
  192. if (type == 'for') {
  193. /*
  194. To exit a for loop we must restore the outer loop's context. The code looks
  195. like this (which goes with that produced by doFor:
  196. for (...) { // the part generated by doFor
  197. ... // the body of the for loop
  198. // ... any tpl for exec statement goes here...
  199. }
  200. parent = p1;
  201. values = r2;
  202. xcount = n1;
  203. xindex = i1
  204. */
  205. if (actions.exec) {
  206. me.doExec(actions.exec);
  207. }
  208. me.body.push('}\n');
  209. me.body.push('parent=p',L,';values=r',L+1,';xcount=n',L,';xindex=i',L,'\n');
  210. } else if (type == 'if' || type == 'switch') {
  211. me.body.push('}\n');
  212. }
  213. },
  214. doFor: function (action, actions) {
  215. var me = this,
  216. s,
  217. L = me.level,
  218. up = L-1,
  219. pL = 'p' + L,
  220. parentAssignment;
  221. // If it's just a propName, use it directly in the switch
  222. if (action === '.') {
  223. s = 'values';
  224. } else if (me.propNameRe.test(action)) {
  225. s = me.parseTag(action);
  226. }
  227. // Otherwise, it must be an expression, and needs to be returned from an fn which uses with(values)
  228. else {
  229. s = me.addFn(action) + me.callFn;
  230. }
  231. /*
  232. We are trying to produce a block of code that looks like below. We use the nesting
  233. level to uniquely name the control variables.
  234. // Omit &quot;var &quot; if we have already been through level 2
  235. var i2 = 0,
  236. n2 = 0,
  237. c2 = values['propName'],
  238. // c2 is the context object for the for loop
  239. a2 = Array.isArray(c2);
  240. p2 = c1,
  241. // p2 is the parent context (of the outer for loop)
  242. r2 = values
  243. // r2 is the values object to
  244. // If iterating over the current data, the parent is always set to c2
  245. parent = c2;
  246. // If iterating over a property in an object, set the parent to the object
  247. parent = a1 ? c1[i1] : p2 // set parent
  248. if (c2) {
  249. if (a2) {
  250. n2 = c2.length;
  251. } else if (c2.isMixedCollection) {
  252. c2 = c2.items;
  253. n2 = c2.length;
  254. } else if (c2.isStore) {
  255. c2 = c2.data.items;
  256. n2 = c2.length;
  257. } else {
  258. c2 = [ c2 ];
  259. n2 = 1;
  260. }
  261. }
  262. // i2 is the loop index and n2 is the number (xcount) of this for loop
  263. for (xcount = n2; i2 &lt; n2; ++i2) {
  264. values = c2[i2] // adjust special vars to inner scope
  265. xindex = i2 + 1 // xindex is 1-based
  266. The body of the loop is whatever comes between the tpl and /tpl statements (which
  267. is handled by doEnd).
  268. */
  269. // Declare the vars for a particular level only if we have not already declared them.
  270. if (me.maxLevel &lt; L) {
  271. me.maxLevel = L;
  272. me.body.push('var ');
  273. }
  274. if (action == '.') {
  275. parentAssignment = 'c' + L;
  276. } else {
  277. parentAssignment = 'a' + up + '?c' + up + '[i' + up + ']:p' + L;
  278. }
  279. me.body.push('i',L,'=0,n', L, '=0,c',L,'=',s,',a',L,'=', me.createArrayTest(L), ',p',L,'=c',up,',r',L,'=values;\n',
  280. 'parent=',parentAssignment,'\n',
  281. 'if (c',L,'){if(a',L,'){n', L,'=c', L, '.length;}else if (c', L, '.isMixedCollection){c',L,'=c',L,'.items;n',L,'=c',L,'.length;}else if(c',L,'.isStore){c',L,'=c',L,'.data.items;n',L,'=c',L,'.length;}else{c',L,'=[c',L,'];n',L,'=1;}}\n',
  282. 'for (xcount=n',L,';i',L,'&lt;n'+L+';++i',L,'){\n',
  283. 'values=c',L,'[i',L,']');
  284. if (actions.propName) {
  285. me.body.push('.', actions.propName);
  286. }
  287. me.body.push('\n',
  288. 'xindex=i',L,'+1\n');
  289. },
  290. createArrayTest: ('isArray' in Array) ? function(L) {
  291. return 'Array.isArray(c' + L + ')';
  292. } : function(L) {
  293. return 'ts.call(c' + L + ')===&quot;[object Array]&quot;';
  294. },
  295. doExec: function (action, actions) {
  296. var me = this,
  297. name = 'f' + me.definitions.length;
  298. me.definitions.push('function ' + name + '(' + me.fnArgs + ') {',
  299. ' try { with(values) {',
  300. ' ' + action,
  301. ' }} catch(e) {',
  302. //&lt;debug&gt;
  303. 'Ext.log(&quot;XTemplate Error: &quot; + e.message);',
  304. //&lt;/debug&gt;
  305. '}',
  306. '}');
  307. me.body.push(name + me.callFn + '\n');
  308. },
  309. //-----------------------------------
  310. // Internal
  311. addFn: function (body) {
  312. var me = this,
  313. name = 'f' + me.definitions.length;
  314. if (body === '.') {
  315. me.definitions.push('function ' + name + '(' + me.fnArgs + ') {',
  316. ' return values',
  317. '}');
  318. } else if (body === '..') {
  319. me.definitions.push('function ' + name + '(' + me.fnArgs + ') {',
  320. ' return parent',
  321. '}');
  322. } else {
  323. me.definitions.push('function ' + name + '(' + me.fnArgs + ') {',
  324. ' try { with(values) {',
  325. ' return(' + body + ')',
  326. ' }} catch(e) {',
  327. //&lt;debug&gt;
  328. 'Ext.log(&quot;XTemplate Error: &quot; + e.message);',
  329. //&lt;/debug&gt;
  330. '}',
  331. '}');
  332. }
  333. return name;
  334. },
  335. parseTag: function (tag) {
  336. var me = this,
  337. m = me.tagRe.exec(tag),
  338. name = m[1],
  339. format = m[2],
  340. args = m[3],
  341. math = m[4],
  342. v;
  343. // name = &quot;.&quot; - Just use the values object.
  344. if (name == '.') {
  345. // filter to not include arrays/objects/nulls
  346. if (!me.validTypes) {
  347. me.definitions.push('var validTypes={string:1,number:1,boolean:1};');
  348. me.validTypes = true;
  349. }
  350. v = 'validTypes[typeof values] || ts.call(values) === &quot;[object Date]&quot; ? values : &quot;&quot;';
  351. }
  352. // name = &quot;#&quot; - Use the xindex
  353. else if (name == '#') {
  354. v = 'xindex';
  355. }
  356. else if (name.substr(0, 7) == &quot;parent.&quot;) {
  357. v = name;
  358. }
  359. // compound Javascript property name (e.g., &quot;foo.bar&quot;)
  360. else if (isNaN(name) &amp;&amp; name.indexOf('-') == -1 &amp;&amp; name.indexOf('.') != -1) {
  361. v = &quot;values.&quot; + name;
  362. }
  363. // number or a '-' in it or a single word (maybe a keyword): use array notation
  364. // (http://jsperf.com/string-property-access/4)
  365. else {
  366. v = &quot;values['&quot; + name + &quot;']&quot;;
  367. }
  368. if (math) {
  369. v = '(' + v + math + ')';
  370. }
  371. if (format &amp;&amp; me.useFormat) {
  372. args = args ? ',' + args : &quot;&quot;;
  373. if (format.substr(0, 5) != &quot;this.&quot;) {
  374. format = &quot;fm.&quot; + format + '(';
  375. } else {
  376. format += '(';
  377. }
  378. } else {
  379. return v;
  380. }
  381. return format + v + args + ')';
  382. },
  383. // @private
  384. evalTpl: function ($) {
  385. // We have to use eval to realize the code block and capture the inner func we also
  386. // don't want a deep scope chain. We only do this in Firefox and it is also unhappy
  387. // with eval containing a return statement, so instead we assign to &quot;$&quot; and return
  388. // that. Because we use &quot;eval&quot;, we are automatically sandboxed properly.
  389. eval($);
  390. return $;
  391. },
  392. newLineRe: /\r\n|\r|\n/g,
  393. aposRe: /[']/g,
  394. intRe: /^\s*(\d+)\s*$/,
  395. tagRe: /([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\/]\s?[\d\.\+\-\*\/\(\)]+)?/
  396. }, function () {
  397. var proto = this.prototype;
  398. proto.fnArgs = 'out,values,parent,xindex,xcount';
  399. proto.callFn = '.call(this,' + proto.fnArgs + ')';
  400. });
  401. </pre>
  402. </body>
  403. </html>