説明なし

expressions.js 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. var EscapeStore = require('./escape-store');
  2. module.exports = function Expressions() {
  3. var expressions = new EscapeStore('EXPRESSION');
  4. var findEnd = function(data, start) {
  5. var end = start + 'expression'.length;
  6. var level = 0;
  7. var quoted = false;
  8. while (true) {
  9. var next = data[end++];
  10. if (quoted) {
  11. quoted = next != '\'' && next != '"';
  12. } else {
  13. quoted = next == '\'' || next == '"';
  14. if (next == '(')
  15. level++;
  16. if (next == ')')
  17. level--;
  18. if (next == '}' && level == 1) {
  19. end--;
  20. level--;
  21. }
  22. }
  23. if (level === 0 && next == ')')
  24. break;
  25. if (!next) {
  26. end = data.substring(0, end).lastIndexOf('}');
  27. break;
  28. }
  29. }
  30. return end;
  31. };
  32. return {
  33. // Escapes expressions by replacing them by a special
  34. // marker for further restoring. It's done via string scanning
  35. // instead of regexps to speed up the process.
  36. escape: function(data) {
  37. var nextStart = 0;
  38. var nextEnd = 0;
  39. var cursor = 0;
  40. var tempData = [];
  41. for (; nextEnd < data.length;) {
  42. nextStart = data.indexOf('expression(', nextEnd);
  43. if (nextStart == -1)
  44. break;
  45. nextEnd = findEnd(data, nextStart);
  46. var expression = data.substring(nextStart, nextEnd);
  47. var placeholder = expressions.store(expression);
  48. tempData.push(data.substring(cursor, nextStart));
  49. tempData.push(placeholder);
  50. cursor = nextEnd;
  51. }
  52. return tempData.length > 0 ?
  53. tempData.join('') + data.substring(cursor, data.length) :
  54. data;
  55. },
  56. restore: function(data) {
  57. return data.replace(expressions.placeholderRegExp, expressions.restore);
  58. }
  59. };
  60. };