index.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. 'use strict';
  2. var doctypes = require('doctypes');
  3. var makeError = require('pug-error');
  4. var buildRuntime = require('pug-runtime/build');
  5. var runtime = require('pug-runtime');
  6. var compileAttrs = require('pug-attrs');
  7. var selfClosing = require('void-elements');
  8. var constantinople = require('constantinople');
  9. var stringify = require('js-stringify');
  10. var addWith = require('with');
  11. // This is used to prevent pretty printing inside certain tags
  12. var WHITE_SPACE_SENSITIVE_TAGS = {
  13. pre: true,
  14. textarea: true
  15. };
  16. var INTERNAL_VARIABLES = [
  17. 'pug',
  18. 'pug_mixins',
  19. 'pug_interp',
  20. 'pug_debug_filename',
  21. 'pug_debug_line',
  22. 'pug_debug_sources',
  23. 'pug_html'
  24. ];
  25. module.exports = generateCode;
  26. module.exports.CodeGenerator = Compiler;
  27. function generateCode(ast, options) {
  28. return (new Compiler(ast, options)).compile();
  29. }
  30. function isConstant(src) {
  31. return constantinople(src, {pug: runtime, 'pug_interp': undefined});
  32. }
  33. function toConstant(src) {
  34. return constantinople.toConstant(src, {pug: runtime, 'pug_interp': undefined});
  35. }
  36. /**
  37. * Initialize `Compiler` with the given `node`.
  38. *
  39. * @param {Node} node
  40. * @param {Object} options
  41. * @api public
  42. */
  43. function Compiler(node, options) {
  44. this.options = options = options || {};
  45. this.node = node;
  46. this.bufferedConcatenationCount = 0;
  47. this.hasCompiledDoctype = false;
  48. this.hasCompiledTag = false;
  49. this.pp = options.pretty || false;
  50. if (this.pp && typeof this.pp !== 'string') {
  51. this.pp = ' ';
  52. }
  53. this.debug = false !== options.compileDebug;
  54. this.indents = 0;
  55. this.parentIndents = 0;
  56. this.terse = false;
  57. this.mixins = {};
  58. this.dynamicMixins = false;
  59. this.eachCount = 0;
  60. if (options.doctype) this.setDoctype(options.doctype);
  61. this.runtimeFunctionsUsed = [];
  62. this.inlineRuntimeFunctions = options.inlineRuntimeFunctions || false;
  63. if (this.debug && this.inlineRuntimeFunctions) {
  64. this.runtimeFunctionsUsed.push('rethrow');
  65. }
  66. };
  67. /**
  68. * Compiler prototype.
  69. */
  70. Compiler.prototype = {
  71. runtime: function (name) {
  72. if (this.inlineRuntimeFunctions) {
  73. this.runtimeFunctionsUsed.push(name);
  74. return 'pug_' + name;
  75. } else {
  76. return 'pug.' + name;
  77. }
  78. },
  79. error: function (message, code, node) {
  80. var err = makeError(code, message, {
  81. line: node.line,
  82. column: node.column,
  83. filename: node.filename,
  84. });
  85. throw err;
  86. },
  87. /**
  88. * Compile parse tree to JavaScript.
  89. *
  90. * @api public
  91. */
  92. compile: function(){
  93. this.buf = [];
  94. if (this.pp) this.buf.push("var pug_indent = [];");
  95. this.lastBufferedIdx = -1;
  96. this.visit(this.node);
  97. if (!this.dynamicMixins) {
  98. // if there are no dynamic mixins we can remove any un-used mixins
  99. var mixinNames = Object.keys(this.mixins);
  100. for (var i = 0; i < mixinNames.length; i++) {
  101. var mixin = this.mixins[mixinNames[i]];
  102. if (!mixin.used) {
  103. for (var x = 0; x < mixin.instances.length; x++) {
  104. for (var y = mixin.instances[x].start; y < mixin.instances[x].end; y++) {
  105. this.buf[y] = '';
  106. }
  107. }
  108. }
  109. }
  110. }
  111. var js = this.buf.join('\n');
  112. var globals = this.options.globals ? this.options.globals.concat(INTERNAL_VARIABLES) : INTERNAL_VARIABLES;
  113. if (this.options.self) {
  114. js = 'var self = locals || {};' + js;
  115. } else {
  116. js = addWith('locals || {}', js, globals.concat(this.runtimeFunctionsUsed.map(function (name) { return 'pug_' + name; })));
  117. }
  118. if (this.debug) {
  119. if (this.options.includeSources) {
  120. js = 'var pug_debug_sources = ' + stringify(this.options.includeSources) + ';\n' + js;
  121. }
  122. js = 'var pug_debug_filename, pug_debug_line;' +
  123. 'try {' +
  124. js +
  125. '} catch (err) {' +
  126. (this.inlineRuntimeFunctions ? 'pug_rethrow' : 'pug.rethrow') +
  127. '(err, pug_debug_filename, pug_debug_line' +
  128. (
  129. this.options.includeSources
  130. ? ', pug_debug_sources[pug_debug_filename]'
  131. : ''
  132. ) +
  133. ');' +
  134. '}';
  135. }
  136. return buildRuntime(this.runtimeFunctionsUsed) + 'function ' + (this.options.templateName || 'template') + '(locals) {var pug_html = "", pug_mixins = {}, pug_interp;' + js + ';return pug_html;}';
  137. },
  138. /**
  139. * Sets the default doctype `name`. Sets terse mode to `true` when
  140. * html 5 is used, causing self-closing tags to end with ">" vs "/>",
  141. * and boolean attributes are not mirrored.
  142. *
  143. * @param {string} name
  144. * @api public
  145. */
  146. setDoctype: function(name){
  147. this.doctype = doctypes[name.toLowerCase()] || '<!DOCTYPE ' + name + '>';
  148. this.terse = this.doctype.toLowerCase() == '<!doctype html>';
  149. this.xml = 0 == this.doctype.indexOf('<?xml');
  150. },
  151. /**
  152. * Buffer the given `str` exactly as is or with interpolation
  153. *
  154. * @param {String} str
  155. * @param {Boolean} interpolate
  156. * @api public
  157. */
  158. buffer: function (str) {
  159. var self = this;
  160. str = stringify(str);
  161. str = str.substr(1, str.length - 2);
  162. if (this.lastBufferedIdx == this.buf.length && this.bufferedConcatenationCount < 100) {
  163. if (this.lastBufferedType === 'code') {
  164. this.lastBuffered += ' + "';
  165. this.bufferedConcatenationCount++;
  166. }
  167. this.lastBufferedType = 'text';
  168. this.lastBuffered += str;
  169. this.buf[this.lastBufferedIdx - 1] = 'pug_html = pug_html + ' + this.bufferStartChar + this.lastBuffered + '";';
  170. } else {
  171. this.bufferedConcatenationCount = 0;
  172. this.buf.push('pug_html = pug_html + "' + str + '";');
  173. this.lastBufferedType = 'text';
  174. this.bufferStartChar = '"';
  175. this.lastBuffered = str;
  176. this.lastBufferedIdx = this.buf.length;
  177. }
  178. },
  179. /**
  180. * Buffer the given `src` so it is evaluated at run time
  181. *
  182. * @param {String} src
  183. * @api public
  184. */
  185. bufferExpression: function (src) {
  186. if (isConstant(src)) {
  187. return this.buffer(toConstant(src) + '')
  188. }
  189. if (this.lastBufferedIdx == this.buf.length && this.bufferedConcatenationCount < 100) {
  190. this.bufferedConcatenationCount++;
  191. if (this.lastBufferedType === 'text') this.lastBuffered += '"';
  192. this.lastBufferedType = 'code';
  193. this.lastBuffered += ' + (' + src + ')';
  194. this.buf[this.lastBufferedIdx - 1] = 'pug_html = pug_html + (' + this.bufferStartChar + this.lastBuffered + ');';
  195. } else {
  196. this.bufferedConcatenationCount = 0;
  197. this.buf.push('pug_html = pug_html + (' + src + ');');
  198. this.lastBufferedType = 'code';
  199. this.bufferStartChar = '';
  200. this.lastBuffered = '(' + src + ')';
  201. this.lastBufferedIdx = this.buf.length;
  202. }
  203. },
  204. /**
  205. * Buffer an indent based on the current `indent`
  206. * property and an additional `offset`.
  207. *
  208. * @param {Number} offset
  209. * @param {Boolean} newline
  210. * @api public
  211. */
  212. prettyIndent: function(offset, newline){
  213. offset = offset || 0;
  214. newline = newline ? '\n' : '';
  215. this.buffer(newline + Array(this.indents + offset).join(this.pp));
  216. if (this.parentIndents)
  217. this.buf.push('pug_html = pug_html + pug_indent.join("");');
  218. },
  219. /**
  220. * Visit `node`.
  221. *
  222. * @param {Node} node
  223. * @api public
  224. */
  225. visit: function(node, parent){
  226. var debug = this.debug;
  227. if (!node) {
  228. var msg;
  229. if (parent) {
  230. msg = 'A child of ' + parent.type + ' (' + (parent.filename || 'Pug') + ':' + parent.line + ')';
  231. } else {
  232. msg = 'A top-level node';
  233. }
  234. msg += ' is ' + node + ', expected a Pug AST Node.';
  235. throw new TypeError(msg);
  236. }
  237. if (debug && node.debug !== false && node.type !== 'Block') {
  238. if (node.line) {
  239. var js = ';pug_debug_line = ' + node.line;
  240. if (node.filename) js += ';pug_debug_filename = ' + stringify(node.filename);
  241. this.buf.push(js + ';');
  242. }
  243. }
  244. if (!this['visit' + node.type]) {
  245. var msg;
  246. if (parent) {
  247. msg = 'A child of ' + parent.type
  248. } else {
  249. msg = 'A top-level node';
  250. }
  251. msg += ' (' + (node.filename || 'Pug') + ':' + node.line + ')'
  252. + ' is of type ' + node.type + ','
  253. + ' which is not supported by pug-code-gen.'
  254. switch (node.type) {
  255. case 'Filter':
  256. msg += ' Please use pug-filters to preprocess this AST.'
  257. break;
  258. case 'Extends':
  259. case 'Include':
  260. case 'NamedBlock':
  261. case 'FileReference': // unlikely but for the sake of completeness
  262. msg += ' Please use pug-linker to preprocess this AST.'
  263. break;
  264. }
  265. throw new TypeError(msg);
  266. }
  267. this.visitNode(node);
  268. },
  269. /**
  270. * Visit `node`.
  271. *
  272. * @param {Node} node
  273. * @api public
  274. */
  275. visitNode: function(node){
  276. return this['visit' + node.type](node);
  277. },
  278. /**
  279. * Visit case `node`.
  280. *
  281. * @param {Literal} node
  282. * @api public
  283. */
  284. visitCase: function(node){
  285. this.buf.push('switch (' + node.expr + '){');
  286. this.visit(node.block, node);
  287. this.buf.push('}');
  288. },
  289. /**
  290. * Visit when `node`.
  291. *
  292. * @param {Literal} node
  293. * @api public
  294. */
  295. visitWhen: function(node){
  296. if ('default' == node.expr) {
  297. this.buf.push('default:');
  298. } else {
  299. this.buf.push('case ' + node.expr + ':');
  300. }
  301. if (node.block) {
  302. this.visit(node.block, node);
  303. this.buf.push(' break;');
  304. }
  305. },
  306. /**
  307. * Visit literal `node`.
  308. *
  309. * @param {Literal} node
  310. * @api public
  311. */
  312. visitLiteral: function(node){
  313. this.buffer(node.str);
  314. },
  315. visitNamedBlock: function(block){
  316. return this.visitBlock(block);
  317. },
  318. /**
  319. * Visit all nodes in `block`.
  320. *
  321. * @param {Block} block
  322. * @api public
  323. */
  324. visitBlock: function(block){
  325. var escapePrettyMode = this.escapePrettyMode;
  326. var pp = this.pp;
  327. // Pretty print multi-line text
  328. if (pp && block.nodes.length > 1 && !escapePrettyMode &&
  329. block.nodes[0].type === 'Text' && block.nodes[1].type === 'Text' ) {
  330. this.prettyIndent(1, true);
  331. }
  332. for (var i = 0; i < block.nodes.length; ++i) {
  333. // Pretty print text
  334. if (pp && i > 0 && !escapePrettyMode &&
  335. block.nodes[i].type === 'Text' && block.nodes[i-1].type === 'Text' &&
  336. /\n$/.test(block.nodes[i - 1].val)) {
  337. this.prettyIndent(1, false);
  338. }
  339. this.visit(block.nodes[i], block);
  340. }
  341. },
  342. /**
  343. * Visit a mixin's `block` keyword.
  344. *
  345. * @param {MixinBlock} block
  346. * @api public
  347. */
  348. visitMixinBlock: function(block){
  349. if (this.pp) this.buf.push("pug_indent.push('" + Array(this.indents + 1).join(this.pp) + "');");
  350. this.buf.push('block && block();');
  351. if (this.pp) this.buf.push("pug_indent.pop();");
  352. },
  353. /**
  354. * Visit `doctype`. Sets terse mode to `true` when html 5
  355. * is used, causing self-closing tags to end with ">" vs "/>",
  356. * and boolean attributes are not mirrored.
  357. *
  358. * @param {Doctype} doctype
  359. * @api public
  360. */
  361. visitDoctype: function(doctype){
  362. if (doctype && (doctype.val || !this.doctype)) {
  363. this.setDoctype(doctype.val || 'html');
  364. }
  365. if (this.doctype) this.buffer(this.doctype);
  366. this.hasCompiledDoctype = true;
  367. },
  368. /**
  369. * Visit `mixin`, generating a function that
  370. * may be called within the template.
  371. *
  372. * @param {Mixin} mixin
  373. * @api public
  374. */
  375. visitMixin: function(mixin){
  376. var name = 'pug_mixins[';
  377. var args = mixin.args || '';
  378. var block = mixin.block;
  379. var attrs = mixin.attrs;
  380. var attrsBlocks = this.attributeBlocks(mixin.attributeBlocks);
  381. var pp = this.pp;
  382. var dynamic = mixin.name[0]==='#';
  383. var key = mixin.name;
  384. if (dynamic) this.dynamicMixins = true;
  385. name += (dynamic ? mixin.name.substr(2,mixin.name.length-3):'"'+mixin.name+'"')+']';
  386. this.mixins[key] = this.mixins[key] || {used: false, instances: []};
  387. if (mixin.call) {
  388. this.mixins[key].used = true;
  389. if (pp) this.buf.push("pug_indent.push('" + Array(this.indents + 1).join(pp) + "');")
  390. if (block || attrs.length || attrsBlocks.length) {
  391. this.buf.push(name + '.call({');
  392. if (block) {
  393. this.buf.push('block: function(){');
  394. // Render block with no indents, dynamically added when rendered
  395. this.parentIndents++;
  396. var _indents = this.indents;
  397. this.indents = 0;
  398. this.visit(mixin.block, mixin);
  399. this.indents = _indents;
  400. this.parentIndents--;
  401. if (attrs.length || attrsBlocks.length) {
  402. this.buf.push('},');
  403. } else {
  404. this.buf.push('}');
  405. }
  406. }
  407. if (attrsBlocks.length) {
  408. if (attrs.length) {
  409. var val = this.attrs(attrs);
  410. attrsBlocks.unshift(val);
  411. }
  412. if (attrsBlocks.length > 1) {
  413. this.buf.push('attributes: ' + this.runtime('merge') + '([' + attrsBlocks.join(',') + '])');
  414. } else {
  415. this.buf.push('attributes: ' + attrsBlocks[0]);
  416. }
  417. } else if (attrs.length) {
  418. var val = this.attrs(attrs);
  419. this.buf.push('attributes: ' + val);
  420. }
  421. if (args) {
  422. this.buf.push('}, ' + args + ');');
  423. } else {
  424. this.buf.push('});');
  425. }
  426. } else {
  427. this.buf.push(name + '(' + args + ');');
  428. }
  429. if (pp) this.buf.push("pug_indent.pop();")
  430. } else {
  431. var mixin_start = this.buf.length;
  432. args = args ? args.split(',') : [];
  433. var rest;
  434. if (args.length && /^\.\.\./.test(args[args.length - 1].trim())) {
  435. rest = args.pop().trim().replace(/^\.\.\./, '');
  436. }
  437. // we need use pug_interp here for v8: https://code.google.com/p/v8/issues/detail?id=4165
  438. // once fixed, use this: this.buf.push(name + ' = function(' + args.join(',') + '){');
  439. this.buf.push(name + ' = pug_interp = function(' + args.join(',') + '){');
  440. this.buf.push('var block = (this && this.block), attributes = (this && this.attributes) || {};');
  441. if (rest) {
  442. this.buf.push('var ' + rest + ' = [];');
  443. this.buf.push('for (pug_interp = ' + args.length + '; pug_interp < arguments.length; pug_interp++) {');
  444. this.buf.push(' ' + rest + '.push(arguments[pug_interp]);');
  445. this.buf.push('}');
  446. }
  447. this.parentIndents++;
  448. this.visit(block, mixin);
  449. this.parentIndents--;
  450. this.buf.push('};');
  451. var mixin_end = this.buf.length;
  452. this.mixins[key].instances.push({start: mixin_start, end: mixin_end});
  453. }
  454. },
  455. /**
  456. * Visit `tag` buffering tag markup, generating
  457. * attributes, visiting the `tag`'s code and block.
  458. *
  459. * @param {Tag} tag
  460. * @param {boolean} interpolated
  461. * @api public
  462. */
  463. visitTag: function(tag, interpolated){
  464. this.indents++;
  465. var name = tag.name
  466. , pp = this.pp
  467. , self = this;
  468. function bufferName() {
  469. if (interpolated) self.bufferExpression(tag.expr);
  470. else self.buffer(name);
  471. }
  472. if (WHITE_SPACE_SENSITIVE_TAGS[tag.name] === true) this.escapePrettyMode = true;
  473. if (!this.hasCompiledTag) {
  474. if (!this.hasCompiledDoctype && 'html' == name) {
  475. this.visitDoctype();
  476. }
  477. this.hasCompiledTag = true;
  478. }
  479. // pretty print
  480. if (pp && !tag.isInline)
  481. this.prettyIndent(0, true);
  482. if (tag.selfClosing || (!this.xml && selfClosing[tag.name])) {
  483. this.buffer('<');
  484. bufferName();
  485. this.visitAttributes(tag.attrs, this.attributeBlocks(tag.attributeBlocks));
  486. if (this.terse && !tag.selfClosing) {
  487. this.buffer('>');
  488. } else {
  489. this.buffer('/>');
  490. }
  491. // if it is non-empty throw an error
  492. if (tag.code ||
  493. tag.block &&
  494. !(tag.block.type === 'Block' && tag.block.nodes.length === 0) &&
  495. tag.block.nodes.some(function (tag) {
  496. return tag.type !== 'Text' || !/^\s*$/.test(tag.val)
  497. })) {
  498. this.error(name + ' is a self closing element: <'+name+'/> but contains nested content.', 'SELF_CLOSING_CONTENT', tag);
  499. }
  500. } else {
  501. // Optimize attributes buffering
  502. this.buffer('<');
  503. bufferName();
  504. this.visitAttributes(tag.attrs, this.attributeBlocks(tag.attributeBlocks));
  505. this.buffer('>');
  506. if (tag.code) this.visitCode(tag.code);
  507. this.visit(tag.block, tag);
  508. // pretty print
  509. if (pp && !tag.isInline && WHITE_SPACE_SENSITIVE_TAGS[tag.name] !== true && !tagCanInline(tag))
  510. this.prettyIndent(0, true);
  511. this.buffer('</');
  512. bufferName();
  513. this.buffer('>');
  514. }
  515. if (WHITE_SPACE_SENSITIVE_TAGS[tag.name] === true) this.escapePrettyMode = false;
  516. this.indents--;
  517. },
  518. /**
  519. * Visit InterpolatedTag.
  520. *
  521. * @param {InterpolatedTag} tag
  522. * @api public
  523. */
  524. visitInterpolatedTag: function(tag) {
  525. return this.visitTag(tag, true);
  526. },
  527. /**
  528. * Visit `text` node.
  529. *
  530. * @param {Text} text
  531. * @api public
  532. */
  533. visitText: function(text){
  534. this.buffer(text.val);
  535. },
  536. /**
  537. * Visit a `comment`, only buffering when the buffer flag is set.
  538. *
  539. * @param {Comment} comment
  540. * @api public
  541. */
  542. visitComment: function(comment){
  543. if (!comment.buffer) return;
  544. if (this.pp) this.prettyIndent(1, true);
  545. this.buffer('<!--' + comment.val + '-->');
  546. },
  547. /**
  548. * Visit a `YieldBlock`.
  549. *
  550. * This is necessary since we allow compiling a file with `yield`.
  551. *
  552. * @param {YieldBlock} block
  553. * @api public
  554. */
  555. visitYieldBlock: function(block) {},
  556. /**
  557. * Visit a `BlockComment`.
  558. *
  559. * @param {Comment} comment
  560. * @api public
  561. */
  562. visitBlockComment: function(comment){
  563. if (!comment.buffer) return;
  564. if (this.pp) this.prettyIndent(1, true);
  565. this.buffer('<!--' + (comment.val || ''));
  566. this.visit(comment.block, comment);
  567. if (this.pp) this.prettyIndent(1, true);
  568. this.buffer('-->');
  569. },
  570. /**
  571. * Visit `code`, respecting buffer / escape flags.
  572. * If the code is followed by a block, wrap it in
  573. * a self-calling function.
  574. *
  575. * @param {Code} code
  576. * @api public
  577. */
  578. visitCode: function(code){
  579. // Wrap code blocks with {}.
  580. // we only wrap unbuffered code blocks ATM
  581. // since they are usually flow control
  582. // Buffer code
  583. if (code.buffer) {
  584. var val = code.val.trim();
  585. val = 'null == (pug_interp = '+val+') ? "" : pug_interp';
  586. if (code.mustEscape !== false) val = this.runtime('escape') + '(' + val + ')';
  587. this.bufferExpression(val);
  588. } else {
  589. this.buf.push(code.val);
  590. }
  591. // Block support
  592. if (code.block) {
  593. if (!code.buffer) this.buf.push('{');
  594. this.visit(code.block, code);
  595. if (!code.buffer) this.buf.push('}');
  596. }
  597. },
  598. /**
  599. * Visit `Conditional`.
  600. *
  601. * @param {Conditional} cond
  602. * @api public
  603. */
  604. visitConditional: function(cond){
  605. var test = cond.test;
  606. this.buf.push('if (' + test + ') {');
  607. this.visit(cond.consequent, cond);
  608. this.buf.push('}')
  609. if (cond.alternate) {
  610. if (cond.alternate.type === 'Conditional') {
  611. this.buf.push('else')
  612. this.visitConditional(cond.alternate);
  613. } else {
  614. this.buf.push('else {');
  615. this.visit(cond.alternate, cond);
  616. this.buf.push('}');
  617. }
  618. }
  619. },
  620. /**
  621. * Visit `While`.
  622. *
  623. * @param {While} loop
  624. * @api public
  625. */
  626. visitWhile: function(loop){
  627. var test = loop.test;
  628. this.buf.push('while (' + test + ') {');
  629. this.visit(loop.block, loop);
  630. this.buf.push('}');
  631. },
  632. /**
  633. * Visit `each` block.
  634. *
  635. * @param {Each} each
  636. * @api public
  637. */
  638. visitEach: function(each){
  639. var indexVarName = each.key || 'pug_index' + this.eachCount;
  640. this.eachCount++;
  641. this.buf.push(''
  642. + '// iterate ' + each.obj + '\n'
  643. + ';(function(){\n'
  644. + ' var $$obj = ' + each.obj + ';\n'
  645. + ' if (\'number\' == typeof $$obj.length) {');
  646. if (each.alternate) {
  647. this.buf.push(' if ($$obj.length) {');
  648. }
  649. this.buf.push(''
  650. + ' for (var ' + indexVarName + ' = 0, $$l = $$obj.length; ' + indexVarName + ' < $$l; ' + indexVarName + '++) {\n'
  651. + ' var ' + each.val + ' = $$obj[' + indexVarName + '];');
  652. this.visit(each.block, each);
  653. this.buf.push(' }');
  654. if (each.alternate) {
  655. this.buf.push(' } else {');
  656. this.visit(each.alternate, each);
  657. this.buf.push(' }');
  658. }
  659. this.buf.push(''
  660. + ' } else {\n'
  661. + ' var $$l = 0;\n'
  662. + ' for (var ' + indexVarName + ' in $$obj) {\n'
  663. + ' $$l++;\n'
  664. + ' var ' + each.val + ' = $$obj[' + indexVarName + '];');
  665. this.visit(each.block, each);
  666. this.buf.push(' }');
  667. if (each.alternate) {
  668. this.buf.push(' if ($$l === 0) {');
  669. this.visit(each.alternate, each);
  670. this.buf.push(' }');
  671. }
  672. this.buf.push(' }\n}).call(this);\n');
  673. },
  674. /**
  675. * Visit `attrs`.
  676. *
  677. * @param {Array} attrs
  678. * @api public
  679. */
  680. visitAttributes: function(attrs, attributeBlocks){
  681. if (attributeBlocks.length) {
  682. if (attrs.length) {
  683. var val = this.attrs(attrs);
  684. attributeBlocks.unshift(val);
  685. }
  686. if (attributeBlocks.length > 1) {
  687. this.bufferExpression(this.runtime('attrs') + '(' + this.runtime('merge') + '([' + attributeBlocks.join(',') + ']), ' + stringify(this.terse) + ')');
  688. } else {
  689. this.bufferExpression(this.runtime('attrs') + '(' + attributeBlocks[0] + ', ' + stringify(this.terse) + ')');
  690. }
  691. } else if (attrs.length) {
  692. this.attrs(attrs, true);
  693. }
  694. },
  695. /**
  696. * Compile attributes.
  697. */
  698. attrs: function(attrs, buffer){
  699. var res = compileAttrs(attrs, {
  700. terse: this.terse,
  701. format: buffer ? 'html' : 'object',
  702. runtime: this.runtime.bind(this)
  703. });
  704. if (buffer) {
  705. this.bufferExpression(res);
  706. }
  707. return res;
  708. },
  709. /**
  710. * Compile attribute blocks.
  711. */
  712. attributeBlocks: function (attributeBlocks) {
  713. return attributeBlocks && attributeBlocks.slice().map(function(attrBlock){
  714. return attrBlock.val;
  715. });
  716. }
  717. };
  718. function tagCanInline(tag) {
  719. function isInline(node){
  720. // Recurse if the node is a block
  721. if (node.type === 'Block') return node.nodes.every(isInline);
  722. // When there is a YieldBlock here, it is an indication that the file is
  723. // expected to be included but is not. If this is the case, the block
  724. // must be empty.
  725. if (node.type === 'YieldBlock') return true;
  726. return (node.type === 'Text' && !/\n/.test(node.val)) || node.isInline;
  727. }
  728. return tag.block.nodes.every(isInline);
  729. }