literal.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*!
  2. * Stylus - Literal
  3. * Copyright (c) Automattic <developer.wordpress.com>
  4. * MIT Licensed
  5. */
  6. /**
  7. * Module dependencies.
  8. */
  9. var Node = require('./node')
  10. , nodes = require('./');
  11. /**
  12. * Initialize a new `Literal` with the given `str`.
  13. *
  14. * @param {String} str
  15. * @api public
  16. */
  17. var Literal = module.exports = function Literal(str){
  18. Node.call(this);
  19. this.val = str;
  20. this.string = str;
  21. this.prefixed = false;
  22. };
  23. /**
  24. * Inherit from `Node.prototype`.
  25. */
  26. Literal.prototype.__proto__ = Node.prototype;
  27. /**
  28. * Return hash.
  29. *
  30. * @return {String}
  31. * @api public
  32. */
  33. Literal.prototype.__defineGetter__('hash', function(){
  34. return this.val;
  35. });
  36. /**
  37. * Return literal value.
  38. *
  39. * @return {String}
  40. * @api public
  41. */
  42. Literal.prototype.toString = function(){
  43. return this.val.toString();
  44. };
  45. /**
  46. * Coerce `other` to a literal.
  47. *
  48. * @param {Node} other
  49. * @return {String}
  50. * @api public
  51. */
  52. Literal.prototype.coerce = function(other){
  53. switch (other.nodeName) {
  54. case 'ident':
  55. case 'string':
  56. case 'literal':
  57. return new Literal(other.string);
  58. default:
  59. return Node.prototype.coerce.call(this, other);
  60. }
  61. };
  62. /**
  63. * Operate on `right` with the given `op`.
  64. *
  65. * @param {String} op
  66. * @param {Node} right
  67. * @return {Node}
  68. * @api public
  69. */
  70. Literal.prototype.operate = function(op, right){
  71. var val = right.first;
  72. switch (op) {
  73. case '+':
  74. return new nodes.Literal(this.string + this.coerce(val).string);
  75. default:
  76. return Node.prototype.operate.call(this, op, right);
  77. }
  78. };
  79. /**
  80. * Return a JSON representation of this node.
  81. *
  82. * @return {Object}
  83. * @api public
  84. */
  85. Literal.prototype.toJSON = function(){
  86. return {
  87. __type: 'Literal',
  88. val: this.val,
  89. string: this.string,
  90. prefixed: this.prefixed,
  91. lineno: this.lineno,
  92. column: this.column,
  93. filename: this.filename
  94. };
  95. };