UNPKG

2.5 kBJavaScriptView Raw
1
2/*!
3 * Stylus - Stack
4 * Copyright (c) Automattic <developer.wordpress.com>
5 * MIT Licensed
6 */
7
8/**
9 * Initialize a new `Stack`.
10 *
11 * @api private
12 */
13
14var Stack = module.exports = function Stack() {
15 Array.apply(this, arguments);
16};
17
18/**
19 * Inherit from `Array.prototype`.
20 */
21
22Stack.prototype.__proto__ = Array.prototype;
23
24/**
25 * Push the given `frame`.
26 *
27 * @param {Frame} frame
28 * @api public
29 */
30
31Stack.prototype.push = function(frame){
32 frame.stack = this;
33 frame.parent = this.currentFrame;
34 return [].push.apply(this, arguments);
35};
36
37/**
38 * Return the current stack `Frame`.
39 *
40 * @return {Frame}
41 * @api private
42 */
43
44Stack.prototype.__defineGetter__('currentFrame', function(){
45 return this[this.length - 1];
46});
47
48/**
49 * Lookup stack frame for the given `block`.
50 *
51 * @param {Block} block
52 * @return {Frame}
53 * @api private
54 */
55
56Stack.prototype.getBlockFrame = function(block){
57 for (var i = 0; i < this.length; ++i) {
58 if (block == this[i].block) {
59 return this[i];
60 }
61 }
62};
63
64/**
65 * Lookup the given local variable `name`, relative
66 * to the lexical scope of the current frame's `Block`.
67 *
68 * When the result of a lookup is an identifier
69 * a recursive lookup is performed, defaulting to
70 * returning the identifier itself.
71 *
72 * @param {String} name
73 * @return {Node}
74 * @api private
75 */
76
77Stack.prototype.lookup = function(name){
78 var block = this.currentFrame.block
79 , val
80 , ret;
81
82 do {
83 var frame = this.getBlockFrame(block);
84 if (frame && (val = frame.lookup(name))) {
85 return val;
86 }
87 } while (block = block.parent);
88};
89
90/**
91 * Custom inspect.
92 *
93 * @return {String}
94 * @api private
95 */
96
97Stack.prototype.inspect = function(){
98 return this.reverse().map(function(frame){
99 return frame.inspect();
100 }).join('\n');
101};
102
103/**
104 * Return stack string formatted as:
105 *
106 * at <context> (<filename>:<lineno>:<column>)
107 *
108 * @return {String}
109 * @api private
110 */
111
112Stack.prototype.toString = function(){
113 var block
114 , node
115 , buf = []
116 , location
117 , len = this.length;
118
119 while (len--) {
120 block = this[len].block;
121 if (node = block.node) {
122 location = '(' + node.filename + ':' + (node.lineno + 1) + ':' + node.column + ')';
123 switch (node.nodeName) {
124 case 'function':
125 buf.push(' at ' + node.name + '() ' + location);
126 break;
127 case 'group':
128 buf.push(' at "' + node.nodes[0].val + '" ' + location);
129 break;
130 }
131 }
132 }
133
134 return buf.join('\n');
135};