Initial commit
[yaffs-website] / node_modules / node-sass / src / libsass / src / ast.cpp
1 #include "sass.hpp"
2 #include "ast.hpp"
3 #include "context.hpp"
4 #include "node.hpp"
5 #include "eval.hpp"
6 #include "extend.hpp"
7 #include "emitter.hpp"
8 #include "color_maps.hpp"
9 #include "ast_fwd_decl.hpp"
10 #include <set>
11 #include <iomanip>
12 #include <iostream>
13 #include <algorithm>
14 #include <functional>
15 #include <cctype>
16 #include <locale>
17
18 namespace Sass {
19
20   static Null sass_null(ParserState("null"));
21
22   bool Supports_Operator::needs_parens(Supports_Condition_Obj cond) const {
23     if (Supports_Operator_Obj op = Cast<Supports_Operator>(cond)) {
24       return op->operand() != operand();
25     }
26     return Cast<Supports_Negation>(cond) != NULL;
27   }
28
29   bool Supports_Negation::needs_parens(Supports_Condition_Obj cond) const {
30     return Cast<Supports_Negation>(cond) ||
31            Cast<Supports_Operator>(cond);
32   }
33
34   void str_rtrim(std::string& str, const std::string& delimiters = " \f\n\r\t\v")
35   {
36     str.erase( str.find_last_not_of( delimiters ) + 1 );
37   }
38
39   void String_Constant::rtrim()
40   {
41     str_rtrim(value_);
42   }
43
44   void String_Schema::rtrim()
45   {
46     if (!empty()) {
47       if (String_Ptr str = Cast<String>(last())) str->rtrim();
48     }
49   }
50
51   void Argument::set_delayed(bool delayed)
52   {
53     if (value_) value_->set_delayed(delayed);
54     is_delayed(delayed);
55   }
56
57   void Arguments::set_delayed(bool delayed)
58   {
59     for (Argument_Obj arg : elements()) {
60       if (arg) arg->set_delayed(delayed);
61     }
62     is_delayed(delayed);
63   }
64
65
66   bool At_Root_Query::exclude(std::string str)
67   {
68     bool with = feature() && unquote(feature()->to_string()).compare("with") == 0;
69     List_Ptr l = static_cast<List_Ptr>(value().ptr());
70     std::string v;
71
72     if (with)
73     {
74       if (!l || l->length() == 0) return str.compare("rule") != 0;
75       for (size_t i = 0, L = l->length(); i < L; ++i)
76       {
77         v = unquote((*l)[i]->to_string());
78         if (v.compare("all") == 0 || v == str) return false;
79       }
80       return true;
81     }
82     else
83     {
84       if (!l || !l->length()) return str.compare("rule") == 0;
85       for (size_t i = 0, L = l->length(); i < L; ++i)
86       {
87         v = unquote((*l)[i]->to_string());
88         if (v.compare("all") == 0 || v == str) return true;
89       }
90       return false;
91     }
92   }
93
94   void AST_Node::update_pstate(const ParserState& pstate)
95   {
96     pstate_.offset += pstate - pstate_ + pstate.offset;
97   }
98
99   bool Simple_Selector::is_ns_eq(const Simple_Selector& r) const
100   {
101     // https://github.com/sass/sass/issues/2229
102     if ((has_ns_ == r.has_ns_) ||
103         (has_ns_ && ns_.empty()) ||
104         (r.has_ns_ && r.ns_.empty())
105     ) {
106       if (ns_.empty() && r.ns() == "*") return false;
107       else if (r.ns().empty() && ns() == "*") return false;
108       else return ns() == r.ns();
109     }
110     return false;
111   }
112
113   bool Compound_Selector::operator< (const Compound_Selector& rhs) const
114   {
115     size_t L = std::min(length(), rhs.length());
116     for (size_t i = 0; i < L; ++i)
117     {
118       Simple_Selector_Obj l = (*this)[i];
119       Simple_Selector_Obj r = rhs[i];
120       if (!l && !r) return false;
121       else if (!r) return false;
122       else if (!l) return true;
123       else if (*l != *r)
124       { return *l < *r; }
125     }
126     // just compare the length now
127     return length() < rhs.length();
128   }
129
130   bool Compound_Selector::has_parent_ref() const
131   {
132     for (Simple_Selector_Obj s : *this) {
133       if (s && s->has_parent_ref()) return true;
134     }
135     return false;
136   }
137
138   bool Compound_Selector::has_real_parent_ref() const
139   {
140     for (Simple_Selector_Obj s : *this) {
141       if (s && s->has_real_parent_ref()) return true;
142     }
143     return false;
144   }
145
146   bool Complex_Selector::has_parent_ref() const
147   {
148     return (head() && head()->has_parent_ref()) ||
149            (tail() && tail()->has_parent_ref());
150   }
151
152   bool Complex_Selector::has_real_parent_ref() const
153   {
154     return (head() && head()->has_real_parent_ref()) ||
155            (tail() && tail()->has_real_parent_ref());
156   }
157
158   bool Complex_Selector::operator< (const Complex_Selector& rhs) const
159   {
160     // const iterators for tails
161     Complex_Selector_Ptr_Const l = this;
162     Complex_Selector_Ptr_Const r = &rhs;
163     Compound_Selector_Ptr l_h = NULL;
164     Compound_Selector_Ptr r_h = NULL;
165     if (l) l_h = l->head();
166     if (r) r_h = r->head();
167     // process all tails
168     while (true)
169     {
170       #ifdef DEBUG
171       // skip empty ancestor first
172       if (l && l->is_empty_ancestor())
173       {
174         l_h = NULL;
175         l = l->tail();
176         if(l) l_h = l->head();
177         continue;
178       }
179       // skip empty ancestor first
180       if (r && r->is_empty_ancestor())
181       {
182         r_h = NULL;
183         r = r->tail();
184         if (r) r_h = r->head();
185         continue;
186       }
187       #endif
188       // check for valid selectors
189       if (!l) return !!r;
190       if (!r) return false;
191       // both are null
192       else if (!l_h && !r_h)
193       {
194         // check combinator after heads
195         if (l->combinator() != r->combinator())
196         { return l->combinator() < r->combinator(); }
197         // advance to next tails
198         l = l->tail();
199         r = r->tail();
200         // fetch the next headers
201         l_h = NULL; r_h = NULL;
202         if (l) l_h = l->head();
203         if (r) r_h = r->head();
204       }
205       // one side is null
206       else if (!r_h) return true;
207       else if (!l_h) return false;
208       // heads ok and equal
209       else if (*l_h == *r_h)
210       {
211         // check combinator after heads
212         if (l->combinator() != r->combinator())
213         { return l->combinator() < r->combinator(); }
214         // advance to next tails
215         l = l->tail();
216         r = r->tail();
217         // fetch the next headers
218         l_h = NULL; r_h = NULL;
219         if (l) l_h = l->head();
220         if (r) r_h = r->head();
221       }
222       // heads are not equal
223       else return *l_h < *r_h;
224     }
225     return true;
226   }
227
228   bool Complex_Selector::operator== (const Complex_Selector& rhs) const
229   {
230     // const iterators for tails
231     Complex_Selector_Ptr_Const l = this;
232     Complex_Selector_Ptr_Const r = &rhs;
233     Compound_Selector_Ptr l_h = NULL;
234     Compound_Selector_Ptr r_h = NULL;
235     if (l) l_h = l->head();
236     if (r) r_h = r->head();
237     // process all tails
238     while (true)
239     {
240       #ifdef DEBUG
241       // skip empty ancestor first
242       if (l && l->is_empty_ancestor())
243       {
244         l_h = NULL;
245         l = l->tail();
246         if (l) l_h = l->head();
247         continue;
248       }
249       // skip empty ancestor first
250       if (r && r->is_empty_ancestor())
251       {
252         r_h = NULL;
253         r = r->tail();
254         if (r) r_h = r->head();
255         continue;
256       }
257       #endif
258       // check the pointers
259       if (!r) return !l;
260       if (!l) return !r;
261       // both are null
262       if (!l_h && !r_h)
263       {
264         // check combinator after heads
265         if (l->combinator() != r->combinator())
266         { return l->combinator() < r->combinator(); }
267         // advance to next tails
268         l = l->tail();
269         r = r->tail();
270         // fetch the next heads
271         l_h = NULL; r_h = NULL;
272         if (l) l_h = l->head();
273         if (r) r_h = r->head();
274       }
275       // equals if other head is empty
276       else if ((!l_h && !r_h) ||
277                (!l_h && r_h->empty()) ||
278                (!r_h && l_h->empty()) ||
279                (*l_h == *r_h))
280       {
281         // check combinator after heads
282         if (l->combinator() != r->combinator())
283         { return l->combinator() == r->combinator(); }
284         // advance to next tails
285         l = l->tail();
286         r = r->tail();
287         // fetch the next heads
288         l_h = NULL; r_h = NULL;
289         if (l) l_h = l->head();
290         if (r) r_h = r->head();
291       }
292       // abort
293       else break;
294     }
295     // unreachable
296     return false;
297   }
298
299   Compound_Selector_Ptr Compound_Selector::unify_with(Compound_Selector_Ptr rhs, Context& ctx)
300   {
301     if (empty()) return rhs;
302     Compound_Selector_Obj unified = SASS_MEMORY_COPY(rhs);
303     for (size_t i = 0, L = length(); i < L; ++i)
304     {
305       if (unified.isNull()) break;
306       unified = at(i)->unify_with(unified, ctx);
307     }
308     return unified.detach();
309   }
310
311   bool Complex_Selector::operator== (const Selector& rhs) const
312   {
313     if (const Selector_List* sl = Cast<Selector_List>(&rhs)) return *this == *sl;
314     if (const Simple_Selector* sp = Cast<Simple_Selector>(&rhs)) return *this == *sp;
315     if (const Complex_Selector* cs = Cast<Complex_Selector>(&rhs)) return *this == *cs;
316     if (const Compound_Selector* ch = Cast<Compound_Selector>(&rhs)) return *this == *ch;
317     throw std::runtime_error("invalid selector base classes to compare");
318     return false;
319   }
320
321
322   bool Complex_Selector::operator< (const Selector& rhs) const
323   {
324     if (const Selector_List* sl = Cast<Selector_List>(&rhs)) return *this < *sl;
325     if (const Simple_Selector* sp = Cast<Simple_Selector>(&rhs)) return *this < *sp;
326     if (const Complex_Selector* cs = Cast<Complex_Selector>(&rhs)) return *this < *cs;
327     if (const Compound_Selector* ch = Cast<Compound_Selector>(&rhs)) return *this < *ch;
328     throw std::runtime_error("invalid selector base classes to compare");
329     return false;
330   }
331
332   bool Compound_Selector::operator== (const Selector& rhs) const
333   {
334     if (const Selector_List* sl = Cast<Selector_List>(&rhs)) return *this == *sl;
335     if (const Simple_Selector* sp = Cast<Simple_Selector>(&rhs)) return *this == *sp;
336     if (const Complex_Selector* cs = Cast<Complex_Selector>(&rhs)) return *this == *cs;
337     if (const Compound_Selector* ch = Cast<Compound_Selector>(&rhs)) return *this == *ch;
338     throw std::runtime_error("invalid selector base classes to compare");
339     return false;
340   }
341
342   bool Compound_Selector::operator< (const Selector& rhs) const
343   {
344     if (const Selector_List* sl = Cast<Selector_List>(&rhs)) return *this < *sl;
345     if (const Simple_Selector* sp = Cast<Simple_Selector>(&rhs)) return *this < *sp;
346     if (const Complex_Selector* cs = Cast<Complex_Selector>(&rhs)) return *this < *cs;
347     if (const Compound_Selector* ch = Cast<Compound_Selector>(&rhs)) return *this < *ch;
348     throw std::runtime_error("invalid selector base classes to compare");
349     return false;
350   }
351
352   bool Selector_Schema::operator== (const Selector& rhs) const
353   {
354     if (const Selector_List* sl = Cast<Selector_List>(&rhs)) return *this == *sl;
355     if (const Simple_Selector* sp = Cast<Simple_Selector>(&rhs)) return *this == *sp;
356     if (const Complex_Selector* cs = Cast<Complex_Selector>(&rhs)) return *this == *cs;
357     if (const Compound_Selector* ch = Cast<Compound_Selector>(&rhs)) return *this == *ch;
358     throw std::runtime_error("invalid selector base classes to compare");
359     return false;
360   }
361
362   bool Selector_Schema::operator< (const Selector& rhs) const
363   {
364     if (const Selector_List* sl = Cast<Selector_List>(&rhs)) return *this < *sl;
365     if (const Simple_Selector* sp = Cast<Simple_Selector>(&rhs)) return *this < *sp;
366     if (const Complex_Selector* cs = Cast<Complex_Selector>(&rhs)) return *this < *cs;
367     if (const Compound_Selector* ch = Cast<Compound_Selector>(&rhs)) return *this < *ch;
368     throw std::runtime_error("invalid selector base classes to compare");
369     return false;
370   }
371
372   bool Simple_Selector::operator== (const Selector& rhs) const
373   {
374     if (Simple_Selector_Ptr_Const sp = Cast<Simple_Selector>(&rhs)) return *this == *sp;
375     return false;
376   }
377
378   bool Simple_Selector::operator< (const Selector& rhs) const
379   {
380     if (Simple_Selector_Ptr_Const sp = Cast<Simple_Selector>(&rhs)) return *this < *sp;
381     return false;
382   }
383
384   bool Simple_Selector::operator== (const Simple_Selector& rhs) const
385   {
386     // solve the double dispatch problem by using RTTI information via dynamic cast
387     if (const Pseudo_Selector* lhs = Cast<Pseudo_Selector>(this)) {return *lhs == rhs; }
388     else if (const Wrapped_Selector* lhs = Cast<Wrapped_Selector>(this)) {return *lhs == rhs; }
389     else if (const Attribute_Selector* lhs = Cast<Attribute_Selector>(this)) {return *lhs == rhs; }
390     else if (name_ == rhs.name_)
391     { return is_ns_eq(rhs); }
392     else return false;
393   }
394
395   bool Simple_Selector::operator< (const Simple_Selector& rhs) const
396   {
397     // solve the double dispatch problem by using RTTI information via dynamic cast
398     if (const Pseudo_Selector* lhs = Cast<Pseudo_Selector>(this)) {return *lhs < rhs; }
399     else if (const Wrapped_Selector* lhs = Cast<Wrapped_Selector>(this)) {return *lhs < rhs; }
400     else if (const Attribute_Selector* lhs = Cast<Attribute_Selector>(this)) {return *lhs < rhs; }
401     if (is_ns_eq(rhs))
402     { return name_ < rhs.name_; }
403     return ns_ < rhs.ns_;
404   }
405
406   bool Selector_List::operator== (const Selector& rhs) const
407   {
408     // solve the double dispatch problem by using RTTI information via dynamic cast
409     if (Selector_List_Ptr_Const ls = Cast<Selector_List>(&rhs)) { return *this == *ls; }
410     else if (Complex_Selector_Ptr_Const ls = Cast<Complex_Selector>(&rhs)) { return *this == *ls; }
411     else if (Compound_Selector_Ptr_Const ls = Cast<Compound_Selector>(&rhs)) { return *this == *ls; }
412     // no compare method
413     return this == &rhs;
414   }
415
416   // Selector lists can be compared to comma lists
417   bool Selector_List::operator==(const Expression& rhs) const
418   {
419     // solve the double dispatch problem by using RTTI information via dynamic cast
420     if (List_Ptr_Const ls = Cast<List>(&rhs)) { return *this == *ls; }
421     if (Selector_Ptr_Const ls = Cast<Selector>(&rhs)) { return *this == *ls; }
422     // compare invalid (maybe we should error?)
423     return false;
424   }
425
426   bool Selector_List::operator== (const Selector_List& rhs) const
427   {
428     // for array access
429     size_t i = 0, n = 0;
430     size_t iL = length();
431     size_t nL = rhs.length();
432     // create temporary vectors and sort them
433     std::vector<Complex_Selector_Obj> l_lst = this->elements();
434     std::vector<Complex_Selector_Obj> r_lst = rhs.elements();
435     std::sort(l_lst.begin(), l_lst.end(), OrderNodes());
436     std::sort(r_lst.begin(), r_lst.end(), OrderNodes());
437     // process loop
438     while (true)
439     {
440       // first check for valid index
441       if (i == iL) return iL == nL;
442       else if (n == nL) return iL == nL;
443       // the access the vector items
444       Complex_Selector_Obj l = l_lst[i];
445       Complex_Selector_Obj r = r_lst[n];
446       // skip nulls
447       if (!l) ++i;
448       else if (!r) ++n;
449       // do the check
450       else if (*l != *r)
451       { return false; }
452       // advance
453       ++i; ++n;
454     }
455     // no mismatch
456     return true;
457   }
458
459   bool Selector_List::operator< (const Selector& rhs) const
460   {
461     if (Selector_List_Ptr_Const sp = Cast<Selector_List>(&rhs)) return *this < *sp;
462     return false;
463   }
464
465   bool Selector_List::operator< (const Selector_List& rhs) const
466   {
467     size_t l = rhs.length();
468     if (length() < l) l = length();
469     for (size_t i = 0; i < l; i ++) {
470       if (*at(i) < *rhs.at(i)) return true;
471     }
472     return false;
473   }
474
475   Compound_Selector_Ptr Simple_Selector::unify_with(Compound_Selector_Ptr rhs, Context& ctx)
476   {
477     for (size_t i = 0, L = rhs->length(); i < L; ++i)
478     { if (to_string(ctx.c_options) == rhs->at(i)->to_string(ctx.c_options)) return rhs; }
479
480     // check for pseudo elements because they are always last
481     size_t i, L;
482     bool found = false;
483     if (typeid(*this) == typeid(Pseudo_Selector) || typeid(*this) == typeid(Wrapped_Selector))
484     {
485       for (i = 0, L = rhs->length(); i < L; ++i)
486       {
487         if ((Cast<Pseudo_Selector>((*rhs)[i]) || Cast<Wrapped_Selector>((*rhs)[i])) && (*rhs)[L-1]->is_pseudo_element())
488         { found = true; break; }
489       }
490     }
491     else
492     {
493       for (i = 0, L = rhs->length(); i < L; ++i)
494       {
495         if (Cast<Pseudo_Selector>((*rhs)[i]) || Cast<Wrapped_Selector>((*rhs)[i]))
496         { found = true; break; }
497       }
498     }
499     if (!found)
500     {
501       rhs->append(this);
502       return rhs;
503     }
504     rhs->elements().insert(rhs->elements().begin() + i, this);
505     return rhs;
506   }
507
508   Simple_Selector_Ptr Element_Selector::unify_with(Simple_Selector_Ptr rhs, Context& ctx)
509   {
510     // check if ns can be extended
511     // true for no ns or universal
512     if (has_universal_ns())
513     {
514       // but dont extend with universal
515       // true for valid ns and universal
516       if (!rhs->is_universal_ns())
517       {
518         // overwrite the name if star is given as name
519         if (this->name() == "*") { this->name(rhs->name()); }
520         // now overwrite the namespace name and flag
521         this->ns(rhs->ns()); this->has_ns(rhs->has_ns());
522         // return copy
523         return this;
524       }
525     }
526     // namespace may changed, check the name now
527     // overwrite star (but not with another star)
528     if (name() == "*" && rhs->name() != "*")
529     {
530       // simply set the new name
531       this->name(rhs->name());
532       // return copy
533       return this;
534     }
535     // return original
536     return this;
537   }
538
539   Compound_Selector_Ptr Element_Selector::unify_with(Compound_Selector_Ptr rhs, Context& ctx)
540   {
541     // TODO: handle namespaces
542
543     // if the rhs is empty, just return a copy of this
544     if (rhs->length() == 0) {
545       rhs->append(this);
546       return rhs;
547     }
548
549     Simple_Selector_Ptr rhs_0 = rhs->at(0);
550     // otherwise, this is a tag name
551     if (name() == "*")
552     {
553       if (typeid(*rhs_0) == typeid(Element_Selector))
554       {
555         // if rhs is universal, just return this tagname + rhs's qualifiers
556         Element_Selector_Ptr ts = Cast<Element_Selector>(rhs_0);
557         rhs->at(0) = this->unify_with(ts, ctx);
558         return rhs;
559       }
560       else if (Cast<Class_Selector>(rhs_0) || Cast<Id_Selector>(rhs_0)) {
561         // qualifier is `.class`, so we can prefix with `ns|*.class`
562         if (has_ns() && !rhs_0->has_ns()) {
563           if (ns() != "*") rhs->elements().insert(rhs->begin(), this);
564         }
565         return rhs;
566       }
567
568
569       return rhs;
570     }
571
572     if (typeid(*rhs_0) == typeid(Element_Selector))
573     {
574       // if rhs is universal, just return this tagname + rhs's qualifiers
575       if (rhs_0->name() != "*" && rhs_0->ns() != "*" && rhs_0->name() != name()) return 0;
576       // otherwise create new compound and unify first simple selector
577       rhs->at(0) = this->unify_with(rhs_0, ctx);
578       return rhs;
579
580     }
581     // else it's a tag name and a bunch of qualifiers -- just append them
582     if (name() != "*") rhs->elements().insert(rhs->begin(), this);
583     return rhs;
584   }
585
586   Compound_Selector_Ptr Class_Selector::unify_with(Compound_Selector_Ptr rhs, Context& ctx)
587   {
588     rhs->has_line_break(has_line_break());
589     return Simple_Selector::unify_with(rhs, ctx);
590   }
591
592   Compound_Selector_Ptr Id_Selector::unify_with(Compound_Selector_Ptr rhs, Context& ctx)
593   {
594     for (size_t i = 0, L = rhs->length(); i < L; ++i)
595     {
596       if (Id_Selector_Ptr sel = Cast<Id_Selector>(rhs->at(i))) {
597         if (sel->name() != name()) return 0;
598       }
599     }
600     rhs->has_line_break(has_line_break());
601     return Simple_Selector::unify_with(rhs, ctx);
602   }
603
604   Compound_Selector_Ptr Pseudo_Selector::unify_with(Compound_Selector_Ptr rhs, Context& ctx)
605   {
606     if (is_pseudo_element())
607     {
608       for (size_t i = 0, L = rhs->length(); i < L; ++i)
609       {
610         if (Pseudo_Selector_Ptr sel = Cast<Pseudo_Selector>(rhs->at(i))) {
611           if (sel->is_pseudo_element() && sel->name() != name()) return 0;
612         }
613       }
614     }
615     return Simple_Selector::unify_with(rhs, ctx);
616   }
617
618   bool Attribute_Selector::operator< (const Attribute_Selector& rhs) const
619   {
620     if (is_ns_eq(rhs)) {
621       if (name() == rhs.name()) {
622         if (matcher() == rhs.matcher()) {
623           bool no_lhs_val = value().isNull();
624           bool no_rhs_val = rhs.value().isNull();
625           if (no_lhs_val && no_rhs_val) return false; // equal
626           else if (no_lhs_val) return true; // lhs is null
627           else if (no_rhs_val) return false; // rhs is null
628           return *value() < *rhs.value(); // both are given
629         } else { return matcher() < rhs.matcher(); }
630       } else { return name() < rhs.name(); }
631     } else { return ns() < rhs.ns(); }
632   }
633
634   bool Attribute_Selector::operator< (const Simple_Selector& rhs) const
635   {
636     if (Attribute_Selector_Ptr_Const w = Cast<Attribute_Selector>(&rhs))
637     {
638       return *this < *w;
639     }
640     if (is_ns_eq(rhs))
641     { return name() < rhs.name(); }
642     return ns() < rhs.ns();
643   }
644
645   bool Attribute_Selector::operator== (const Attribute_Selector& rhs) const
646   {
647     // get optional value state
648     bool no_lhs_val = value().isNull();
649     bool no_rhs_val = rhs.value().isNull();
650     // both are null, therefore equal
651     if (no_lhs_val && no_rhs_val) {
652       return (name() == rhs.name())
653         && (matcher() == rhs.matcher())
654         && (is_ns_eq(rhs));
655     }
656     // both are defined, evaluate
657     if (no_lhs_val == no_rhs_val) {
658       return (name() == rhs.name())
659         && (matcher() == rhs.matcher())
660         && (is_ns_eq(rhs))
661         && (*value() == *rhs.value());
662     }
663     // not equal
664     return false;
665
666   }
667
668   bool Attribute_Selector::operator== (const Simple_Selector& rhs) const
669   {
670     if (Attribute_Selector_Ptr_Const w = Cast<Attribute_Selector>(&rhs))
671     {
672       return *this == *w;
673     }
674     return is_ns_eq(rhs) &&
675            name() == rhs.name();
676   }
677
678   bool Pseudo_Selector::operator== (const Pseudo_Selector& rhs) const
679   {
680     if (is_ns_eq(rhs) && name() == rhs.name())
681     {
682       String_Obj lhs_ex = expression();
683       String_Obj rhs_ex = rhs.expression();
684       if (rhs_ex && lhs_ex) return *lhs_ex == *rhs_ex;
685       else return lhs_ex.ptr() == rhs_ex.ptr();
686     }
687     else return false;
688   }
689
690   bool Pseudo_Selector::operator== (const Simple_Selector& rhs) const
691   {
692     if (Pseudo_Selector_Ptr_Const w = Cast<Pseudo_Selector>(&rhs))
693     {
694       return *this == *w;
695     }
696     return is_ns_eq(rhs) &&
697            name() == rhs.name();
698   }
699
700   bool Pseudo_Selector::operator< (const Pseudo_Selector& rhs) const
701   {
702     if (is_ns_eq(rhs) && name() == rhs.name())
703     {
704       String_Obj lhs_ex = expression();
705       String_Obj rhs_ex = rhs.expression();
706       if (rhs_ex && lhs_ex) return *lhs_ex < *rhs_ex;
707       else return lhs_ex.ptr() < rhs_ex.ptr();
708     }
709     if (is_ns_eq(rhs))
710     { return name() < rhs.name(); }
711     return ns() < rhs.ns();
712   }
713
714   bool Pseudo_Selector::operator< (const Simple_Selector& rhs) const
715   {
716     if (Pseudo_Selector_Ptr_Const w = Cast<Pseudo_Selector>(&rhs))
717     {
718       return *this < *w;
719     }
720     if (is_ns_eq(rhs))
721     { return name() < rhs.name(); }
722     return ns() < rhs.ns();
723   }
724
725   bool Wrapped_Selector::operator== (const Wrapped_Selector& rhs) const
726   {
727     if (is_ns_eq(rhs) && name() == rhs.name())
728     { return *(selector()) == *(rhs.selector()); }
729     else return false;
730   }
731
732   bool Wrapped_Selector::operator== (const Simple_Selector& rhs) const
733   {
734     if (Wrapped_Selector_Ptr_Const w = Cast<Wrapped_Selector>(&rhs))
735     {
736       return *this == *w;
737     }
738     return is_ns_eq(rhs) &&
739            name() == rhs.name();
740   }
741
742   bool Wrapped_Selector::operator< (const Wrapped_Selector& rhs) const
743   {
744     if (is_ns_eq(rhs) && name() == rhs.name())
745     { return *(selector()) < *(rhs.selector()); }
746     if (is_ns_eq(rhs))
747     { return name() < rhs.name(); }
748     return ns() < rhs.ns();
749   }
750
751   bool Wrapped_Selector::operator< (const Simple_Selector& rhs) const
752   {
753     if (Wrapped_Selector_Ptr_Const w = Cast<Wrapped_Selector>(&rhs))
754     {
755       return *this < *w;
756     }
757     if (is_ns_eq(rhs))
758     { return name() < rhs.name(); }
759     return ns() < rhs.ns();
760   }
761
762   bool Wrapped_Selector::is_superselector_of(Wrapped_Selector_Obj sub)
763   {
764     if (this->name() != sub->name()) return false;
765     if (this->name() == ":current") return false;
766     if (Selector_List_Obj rhs_list = Cast<Selector_List>(sub->selector())) {
767       if (Selector_List_Obj lhs_list = Cast<Selector_List>(selector())) {
768         return lhs_list->is_superselector_of(rhs_list);
769       }
770     }
771     error("is_superselector expected a Selector_List", sub->pstate());
772     return false;
773   }
774
775   bool Compound_Selector::is_superselector_of(Selector_List_Obj rhs, std::string wrapped)
776   {
777     for (Complex_Selector_Obj item : rhs->elements()) {
778       if (is_superselector_of(item, wrapped)) return true;
779     }
780     return false;
781   }
782
783   bool Compound_Selector::is_superselector_of(Complex_Selector_Obj rhs, std::string wrapped)
784   {
785     if (rhs->head()) return is_superselector_of(rhs->head(), wrapped);
786     return false;
787   }
788
789   bool Compound_Selector::is_superselector_of(Compound_Selector_Obj rhs, std::string wrapping)
790   {
791     Compound_Selector_Ptr lhs = this;
792     Simple_Selector_Ptr lbase = lhs->base();
793     Simple_Selector_Ptr rbase = rhs->base();
794
795     // Check if pseudo-elements are the same between the selectors
796
797     std::set<std::string> lpsuedoset, rpsuedoset;
798     for (size_t i = 0, L = length(); i < L; ++i)
799     {
800       if ((*this)[i]->is_pseudo_element()) {
801         std::string pseudo((*this)[i]->to_string());
802         pseudo = pseudo.substr(pseudo.find_first_not_of(":")); // strip off colons to ensure :after matches ::after since ruby sass is forgiving
803         lpsuedoset.insert(pseudo);
804       }
805     }
806     for (size_t i = 0, L = rhs->length(); i < L; ++i)
807     {
808       if ((*rhs)[i]->is_pseudo_element()) {
809         std::string pseudo((*rhs)[i]->to_string());
810         pseudo = pseudo.substr(pseudo.find_first_not_of(":")); // strip off colons to ensure :after matches ::after since ruby sass is forgiving
811         rpsuedoset.insert(pseudo);
812       }
813     }
814     if (lpsuedoset != rpsuedoset) {
815       return false;
816     }
817
818     // would like to replace this without stringification
819     // https://github.com/sass/sass/issues/2229
820     // SimpleSelectorSet lset, rset;
821     std::set<std::string> lset, rset;
822
823     if (lbase && rbase)
824     {
825       if (lbase->to_string() == rbase->to_string()) {
826         for (size_t i = 1, L = length(); i < L; ++i)
827         { lset.insert((*this)[i]->to_string()); }
828         for (size_t i = 1, L = rhs->length(); i < L; ++i)
829         { rset.insert((*rhs)[i]->to_string()); }
830         return includes(rset.begin(), rset.end(), lset.begin(), lset.end());
831       }
832       return false;
833     }
834
835     for (size_t i = 0, iL = length(); i < iL; ++i)
836     {
837       Selector_Obj lhs = (*this)[i];
838       // very special case for wrapped matches selector
839       if (Wrapped_Selector_Obj wrapped = Cast<Wrapped_Selector>(lhs)) {
840         if (wrapped->name() == ":not") {
841           if (Selector_List_Obj not_list = Cast<Selector_List>(wrapped->selector())) {
842             if (not_list->is_superselector_of(rhs, wrapped->name())) return false;
843           } else {
844             throw std::runtime_error("wrapped not selector is not a list");
845           }
846         }
847         if (wrapped->name() == ":matches" || wrapped->name() == ":-moz-any") {
848           lhs = wrapped->selector();
849           if (Selector_List_Obj list = Cast<Selector_List>(wrapped->selector())) {
850             if (Compound_Selector_Obj comp = Cast<Compound_Selector>(rhs)) {
851               if (!wrapping.empty() && wrapping != wrapped->name()) return false;
852               if (wrapping.empty() || wrapping != wrapped->name()) {;
853                 if (list->is_superselector_of(comp, wrapped->name())) return true;
854               }
855             }
856           }
857         }
858         Simple_Selector_Ptr rhs_sel = NULL;
859         if (rhs->elements().size() > i) rhs_sel = (*rhs)[i];
860         if (Wrapped_Selector_Ptr wrapped_r = Cast<Wrapped_Selector>(rhs_sel)) {
861           if (wrapped->name() == wrapped_r->name()) {
862           if (wrapped->is_superselector_of(wrapped_r)) {
863              continue;
864              rset.insert(lhs->to_string());
865
866           }}
867         }
868       }
869       // match from here on as strings
870       lset.insert(lhs->to_string());
871     }
872
873     for (size_t n = 0, nL = rhs->length(); n < nL; ++n)
874     {
875       Selector_Obj r = (*rhs)[n];
876       if (Wrapped_Selector_Obj wrapped = Cast<Wrapped_Selector>(r)) {
877         if (wrapped->name() == ":not") {
878           if (Selector_List_Obj ls = Cast<Selector_List>(wrapped->selector())) {
879             ls->remove_parent_selectors();
880             if (is_superselector_of(ls, wrapped->name())) return false;
881           }
882         }
883         if (wrapped->name() == ":matches" || wrapped->name() == ":-moz-any") {
884           if (!wrapping.empty()) {
885             if (wrapping != wrapped->name()) return false;
886           }
887           if (Selector_List_Obj ls = Cast<Selector_List>(wrapped->selector())) {
888             ls->remove_parent_selectors();
889             return (is_superselector_of(ls, wrapped->name()));
890           }
891         }
892       }
893       rset.insert(r->to_string());
894     }
895
896     //for (auto l : lset) { cerr << "l: " << l << endl; }
897     //for (auto r : rset) { cerr << "r: " << r << endl; }
898
899     if (lset.empty()) return true;
900     // return true if rset contains all the elements of lset
901     return includes(rset.begin(), rset.end(), lset.begin(), lset.end());
902
903   }
904
905   // create complex selector (ancestor of) from compound selector
906   Complex_Selector_Obj Compound_Selector::to_complex()
907   {
908     // create an intermediate complex selector
909     return SASS_MEMORY_NEW(Complex_Selector,
910                            pstate(),
911                            Complex_Selector::ANCESTOR_OF,
912                            this,
913                            0);
914   }
915
916   Selector_List_Ptr Complex_Selector::unify_with(Complex_Selector_Ptr other, Context& ctx)
917   {
918
919     // get last tails (on the right side)
920     Complex_Selector_Obj l_last = this->last();
921     Complex_Selector_Obj r_last = other->last();
922
923     // check valid pointers (assertion)
924     SASS_ASSERT(l_last, "lhs is null");
925     SASS_ASSERT(r_last, "rhs is null");
926
927     // Not sure about this check, but closest way I could check
928     // was to see if this is a ruby 'SimpleSequence' equivalent.
929     // It seems to do the job correctly as some specs react to this
930     if (l_last->combinator() != Combinator::ANCESTOR_OF) return 0;
931     if (r_last->combinator() != Combinator::ANCESTOR_OF ) return 0;
932
933     // get the headers for the last tails
934     Compound_Selector_Obj l_last_head = l_last->head();
935     Compound_Selector_Obj r_last_head = r_last->head();
936
937     // check valid head pointers (assertion)
938     SASS_ASSERT(l_last_head, "lhs head is null");
939     SASS_ASSERT(r_last_head, "rhs head is null");
940
941     // get the unification of the last compound selectors
942     Compound_Selector_Obj unified = r_last_head->unify_with(l_last_head, ctx);
943
944     // abort if we could not unify heads
945     if (unified == 0) return 0;
946
947     // check for universal (star: `*`) selector
948     bool is_universal = l_last_head->is_universal() ||
949                         r_last_head->is_universal();
950
951     if (is_universal)
952     {
953       // move the head
954       l_last->head(0);
955       r_last->head(unified);
956     }
957
958     // create nodes from both selectors
959     Node lhsNode = complexSelectorToNode(this, ctx);
960     Node rhsNode = complexSelectorToNode(other, ctx);
961
962     // overwrite universal base
963     if (!is_universal)
964     {
965       // create some temporaries to convert to node
966       Complex_Selector_Obj fake = unified->to_complex();
967       Node unified_node = complexSelectorToNode(fake, ctx);
968       // add to permutate the list?
969       rhsNode.plus(unified_node);
970     }
971
972     // do some magic we inherit from node and extend
973     Node node = Extend::subweave(lhsNode, rhsNode, ctx);
974     Selector_List_Ptr result = SASS_MEMORY_NEW(Selector_List, pstate());
975     NodeDequePtr col = node.collection(); // move from collection to list
976     for (NodeDeque::iterator it = col->begin(), end = col->end(); it != end; it++)
977     { result->append(nodeToComplexSelector(Node::naiveTrim(*it, ctx), ctx)); }
978
979     // only return if list has some entries
980     return result->length() ? result : 0;
981
982   }
983
984   bool Compound_Selector::operator== (const Compound_Selector& rhs) const
985   {
986     // for array access
987     size_t i = 0, n = 0;
988     size_t iL = length();
989     size_t nL = rhs.length();
990     // create temporary vectors and sort them
991     std::vector<Simple_Selector_Obj> l_lst = this->elements();
992     std::vector<Simple_Selector_Obj> r_lst = rhs.elements();
993     std::sort(l_lst.begin(), l_lst.end(), OrderNodes());
994     std::sort(r_lst.begin(), r_lst.end(), OrderNodes());
995     // process loop
996     while (true)
997     {
998       // first check for valid index
999       if (i == iL) return iL == nL;
1000       else if (n == nL) return iL == nL;
1001       // the access the vector items
1002       Simple_Selector_Obj l = l_lst[i];
1003       Simple_Selector_Obj r = r_lst[n];
1004       // skip nulls
1005       if (!l) ++i;
1006       if (!r) ++n;
1007       // do the check now
1008       else if (*l != *r)
1009       { return false; }
1010       // advance now
1011       ++i; ++n;
1012     }
1013     // no mismatch
1014     return true;
1015   }
1016
1017   bool Complex_Selector::is_superselector_of(Compound_Selector_Obj rhs, std::string wrapping)
1018   {
1019     return last()->head() && last()->head()->is_superselector_of(rhs, wrapping);
1020   }
1021
1022   bool Complex_Selector::is_superselector_of(Complex_Selector_Obj rhs, std::string wrapping)
1023   {
1024     Complex_Selector_Ptr lhs = this;
1025     // check for selectors with leading or trailing combinators
1026     if (!lhs->head() || !rhs->head())
1027     { return false; }
1028     Complex_Selector_Obj l_innermost = lhs->innermost();
1029     if (l_innermost->combinator() != Complex_Selector::ANCESTOR_OF)
1030     { return false; }
1031     Complex_Selector_Obj r_innermost = rhs->innermost();
1032     if (r_innermost->combinator() != Complex_Selector::ANCESTOR_OF)
1033     { return false; }
1034     // more complex (i.e., longer) selectors are always more specific
1035     size_t l_len = lhs->length(), r_len = rhs->length();
1036     if (l_len > r_len)
1037     { return false; }
1038
1039     if (l_len == 1)
1040     { return lhs->head()->is_superselector_of(rhs->last()->head(), wrapping); }
1041
1042     // we have to look one tail deeper, since we cary the
1043     // combinator around for it (which is important here)
1044     if (rhs->tail() && lhs->tail() && combinator() != Complex_Selector::ANCESTOR_OF) {
1045       Complex_Selector_Obj lhs_tail = lhs->tail();
1046       Complex_Selector_Obj rhs_tail = rhs->tail();
1047       if (lhs_tail->combinator() != rhs_tail->combinator()) return false;
1048       if (lhs_tail->head() && !rhs_tail->head()) return false;
1049       if (!lhs_tail->head() && rhs_tail->head()) return false;
1050       if (lhs_tail->head() && rhs_tail->head()) {
1051         if (!lhs_tail->head()->is_superselector_of(rhs_tail->head())) return false;
1052       }
1053     }
1054
1055     bool found = false;
1056     Complex_Selector_Obj marker = rhs;
1057     for (size_t i = 0, L = rhs->length(); i < L; ++i) {
1058       if (i == L-1)
1059       { return false; }
1060       if (lhs->head() && marker->head() && lhs->head()->is_superselector_of(marker->head(), wrapping))
1061       { found = true; break; }
1062       marker = marker->tail();
1063     }
1064     if (!found)
1065     { return false; }
1066
1067     /*
1068       Hmm, I hope I have the logic right:
1069
1070       if lhs has a combinator:
1071         if !(marker has a combinator) return false
1072         if !(lhs.combinator == '~' ? marker.combinator != '>' : lhs.combinator == marker.combinator) return false
1073         return lhs.tail-without-innermost.is_superselector_of(marker.tail-without-innermost)
1074       else if marker has a combinator:
1075         if !(marker.combinator == ">") return false
1076         return lhs.tail.is_superselector_of(marker.tail)
1077       else
1078         return lhs.tail.is_superselector_of(marker.tail)
1079     */
1080     if (lhs->combinator() != Complex_Selector::ANCESTOR_OF)
1081     {
1082       if (marker->combinator() == Complex_Selector::ANCESTOR_OF)
1083       { return false; }
1084       if (!(lhs->combinator() == Complex_Selector::PRECEDES ? marker->combinator() != Complex_Selector::PARENT_OF : lhs->combinator() == marker->combinator()))
1085       { return false; }
1086       return lhs->tail()->is_superselector_of(marker->tail());
1087     }
1088     else if (marker->combinator() != Complex_Selector::ANCESTOR_OF)
1089     {
1090       if (marker->combinator() != Complex_Selector::PARENT_OF)
1091       { return false; }
1092       return lhs->tail()->is_superselector_of(marker->tail());
1093     }
1094     else
1095     {
1096       return lhs->tail()->is_superselector_of(marker->tail());
1097     }
1098     // catch-all
1099     return false;
1100   }
1101
1102   size_t Complex_Selector::length() const
1103   {
1104     // TODO: make this iterative
1105     if (!tail()) return 1;
1106     return 1 + tail()->length();
1107   }
1108
1109   // append another complex selector at the end
1110   // check if we need to append some headers
1111   // then we need to check for the combinator
1112   // only then we can safely set the new tail
1113   void Complex_Selector::append(Context& ctx, Complex_Selector_Obj ss)
1114   {
1115
1116     Complex_Selector_Obj t = ss->tail();
1117     Combinator c = ss->combinator();
1118     String_Obj r = ss->reference();
1119     Compound_Selector_Obj h = ss->head();
1120
1121     if (ss->has_line_feed()) has_line_feed(true);
1122     if (ss->has_line_break()) has_line_break(true);
1123
1124     // append old headers
1125     if (h && h->length()) {
1126       if (last()->combinator() != ANCESTOR_OF && c != ANCESTOR_OF) {
1127         error("Invalid parent selector", pstate_);
1128       } else if (last()->head_ && last()->head_->length()) {
1129         Compound_Selector_Obj rh = last()->head();
1130         size_t i = 0, L = h->length();
1131         if (Cast<Element_Selector>(h->first())) {
1132           if (Class_Selector_Ptr sq = Cast<Class_Selector>(rh->last())) {
1133             Class_Selector_Ptr sqs = SASS_MEMORY_COPY(sq);
1134             sqs->name(sqs->name() + (*h)[0]->name());
1135             sqs->pstate((*h)[0]->pstate());
1136             (*rh)[rh->length()-1] = sqs;
1137             rh->pstate(h->pstate());
1138             for (i = 1; i < L; ++i) rh->append((*h)[i]);
1139           } else if (Id_Selector_Ptr sq = Cast<Id_Selector>(rh->last())) {
1140             Id_Selector_Ptr sqs = SASS_MEMORY_COPY(sq);
1141             sqs->name(sqs->name() + (*h)[0]->name());
1142             sqs->pstate((*h)[0]->pstate());
1143             (*rh)[rh->length()-1] = sqs;
1144             rh->pstate(h->pstate());
1145             for (i = 1; i < L; ++i) rh->append((*h)[i]);
1146           } else if (Element_Selector_Ptr ts = Cast<Element_Selector>(rh->last())) {
1147             Element_Selector_Ptr tss = SASS_MEMORY_COPY(ts);
1148             tss->name(tss->name() + (*h)[0]->name());
1149             tss->pstate((*h)[0]->pstate());
1150             (*rh)[rh->length()-1] = tss;
1151             rh->pstate(h->pstate());
1152             for (i = 1; i < L; ++i) rh->append((*h)[i]);
1153           } else if (Placeholder_Selector_Ptr ps = Cast<Placeholder_Selector>(rh->last())) {
1154             Placeholder_Selector_Ptr pss = SASS_MEMORY_COPY(ps);
1155             pss->name(pss->name() + (*h)[0]->name());
1156             pss->pstate((*h)[0]->pstate());
1157             (*rh)[rh->length()-1] = pss;
1158             rh->pstate(h->pstate());
1159             for (i = 1; i < L; ++i) rh->append((*h)[i]);
1160           } else {
1161             last()->head_->concat(h);
1162           }
1163         } else {
1164           last()->head_->concat(h);
1165         }
1166       } else {
1167         last()->head_->concat(h);
1168       }
1169     } else {
1170       // std::cerr << "has no or empty head\n";
1171     }
1172
1173     if (last()) {
1174       if (last()->combinator() != ANCESTOR_OF && c != ANCESTOR_OF) {
1175         Complex_Selector_Ptr inter = SASS_MEMORY_NEW(Complex_Selector, pstate());
1176         inter->reference(r);
1177         inter->combinator(c);
1178         inter->tail(t);
1179         last()->tail(inter);
1180       } else {
1181         if (last()->combinator() == ANCESTOR_OF) {
1182           last()->combinator(c);
1183           last()->reference(r);
1184         }
1185         last()->tail(t);
1186       }
1187     }
1188
1189   }
1190
1191   Selector_List_Obj Selector_List::eval(Eval& eval)
1192   {
1193     Selector_List_Obj list = schema() ?
1194       eval(schema()) : eval(this);
1195     list->schema(schema());
1196     return list;
1197   }
1198
1199   Selector_List_Ptr Selector_List::resolve_parent_refs(Context& ctx, std::vector<Selector_List_Obj>& pstack, bool implicit_parent)
1200   {
1201     if (!this->has_parent_ref()) return this;
1202     Selector_List_Ptr ss = SASS_MEMORY_NEW(Selector_List, pstate());
1203     Selector_List_Ptr ps = pstack.back();
1204     for (size_t pi = 0, pL = ps->length(); pi < pL; ++pi) {
1205       for (size_t si = 0, sL = this->length(); si < sL; ++si) {
1206         Selector_List_Obj rv = at(si)->resolve_parent_refs(ctx, pstack, implicit_parent);
1207         ss->concat(rv);
1208       }
1209     }
1210     return ss;
1211   }
1212
1213   Selector_List_Ptr Complex_Selector::resolve_parent_refs(Context& ctx, std::vector<Selector_List_Obj>& pstack, bool implicit_parent)
1214   {
1215     Complex_Selector_Obj tail = this->tail();
1216     Compound_Selector_Obj head = this->head();
1217     Selector_List_Ptr parents = pstack.back();
1218
1219     if (!this->has_real_parent_ref() && !implicit_parent) {
1220       Selector_List_Ptr retval = SASS_MEMORY_NEW(Selector_List, pstate());
1221       retval->append(this);
1222       return retval;
1223     }
1224
1225     // first resolve_parent_refs the tail (which may return an expanded list)
1226     Selector_List_Obj tails = tail ? tail->resolve_parent_refs(ctx, pstack, implicit_parent) : 0;
1227
1228     if (head && head->length() > 0) {
1229
1230       Selector_List_Obj retval;
1231       // we have a parent selector in a simple compound list
1232       // mix parent complex selector into the compound list
1233       if (Cast<Parent_Selector>((*head)[0])) {
1234         retval = SASS_MEMORY_NEW(Selector_List, pstate());
1235
1236         // it turns out that real parent references reach
1237         // across @at-root rules, which comes unexpected
1238         if (parents == NULL && head->has_real_parent_ref()) {
1239           int i = pstack.size() - 1;
1240           while (!parents && i > -1) {
1241             parents = pstack.at(i--);
1242           }
1243         }
1244
1245         if (parents && parents->length()) {
1246           if (tails && tails->length() > 0) {
1247             for (size_t n = 0, nL = tails->length(); n < nL; ++n) {
1248               for (size_t i = 0, iL = parents->length(); i < iL; ++i) {
1249                 Complex_Selector_Obj t = (*tails)[n];
1250                 Complex_Selector_Obj parent = (*parents)[i];
1251                 Complex_Selector_Obj s = SASS_MEMORY_CLONE(parent);
1252                 Complex_Selector_Obj ss = SASS_MEMORY_CLONE(this);
1253                 ss->tail(t ? SASS_MEMORY_CLONE(t) : NULL);
1254                 Compound_Selector_Obj h = SASS_MEMORY_COPY(head_);
1255                 // remove parent selector from sequence
1256                 if (h->length()) {
1257                   h->erase(h->begin());
1258                   ss->head(h);
1259                 } else {
1260                   ss->head(NULL);
1261                 }
1262                 // adjust for parent selector (1 char)
1263                 if (h->length()) {
1264                   ParserState state(h->at(0)->pstate());
1265                   state.offset.column += 1;
1266                   state.column -= 1;
1267                   (*h)[0]->pstate(state);
1268                 }
1269                 // keep old parser state
1270                 s->pstate(pstate());
1271                 // append new tail
1272                 s->append(ctx, ss);
1273                 retval->append(s);
1274               }
1275             }
1276           }
1277           // have no tails but parents
1278           // loop above is inside out
1279           else {
1280             for (size_t i = 0, iL = parents->length(); i < iL; ++i) {
1281               Complex_Selector_Obj parent = (*parents)[i];
1282               Complex_Selector_Obj s = SASS_MEMORY_CLONE(parent);
1283               Complex_Selector_Obj ss = SASS_MEMORY_CLONE(this);
1284               // this is only if valid if the parent has no trailing op
1285               // otherwise we cannot append more simple selectors to head
1286               if (parent->last()->combinator() != ANCESTOR_OF) {
1287                 throw Exception::InvalidParent(parent, ss);
1288               }
1289               ss->tail(tail ? SASS_MEMORY_CLONE(tail) : NULL);
1290               Compound_Selector_Obj h = SASS_MEMORY_COPY(head_);
1291               // remove parent selector from sequence
1292               if (h->length()) {
1293                 h->erase(h->begin());
1294                 ss->head(h);
1295               } else {
1296                 ss->head(NULL);
1297               }
1298               // \/ IMO ruby sass bug \/
1299               ss->has_line_feed(false);
1300               // adjust for parent selector (1 char)
1301               if (h->length()) {
1302                 ParserState state(h->at(0)->pstate());
1303                 state.offset.column += 1;
1304                 state.column -= 1;
1305                 (*h)[0]->pstate(state);
1306               }
1307               // keep old parser state
1308               s->pstate(pstate());
1309               // append new tail
1310               s->append(ctx, ss);
1311               retval->append(s);
1312             }
1313           }
1314         }
1315         // have no parent but some tails
1316         else {
1317           if (tails && tails->length() > 0) {
1318             for (size_t n = 0, nL = tails->length(); n < nL; ++n) {
1319               Complex_Selector_Obj cpy = SASS_MEMORY_CLONE(this);
1320               cpy->tail(SASS_MEMORY_CLONE(tails->at(n)));
1321               cpy->head(SASS_MEMORY_NEW(Compound_Selector, head->pstate()));
1322               for (size_t i = 1, L = this->head()->length(); i < L; ++i)
1323                 cpy->head()->append((*this->head())[i]);
1324               if (!cpy->head()->length()) cpy->head(0);
1325               retval->append(cpy->skip_empty_reference());
1326             }
1327           }
1328           // have no parent nor tails
1329           else {
1330             Complex_Selector_Obj cpy = SASS_MEMORY_CLONE(this);
1331             cpy->head(SASS_MEMORY_NEW(Compound_Selector, head->pstate()));
1332             for (size_t i = 1, L = this->head()->length(); i < L; ++i)
1333               cpy->head()->append((*this->head())[i]);
1334             if (!cpy->head()->length()) cpy->head(0);
1335             retval->append(cpy->skip_empty_reference());
1336           }
1337         }
1338       }
1339       // no parent selector in head
1340       else {
1341         retval = this->tails(ctx, tails);
1342       }
1343
1344       for (Simple_Selector_Obj ss : head->elements()) {
1345         if (Wrapped_Selector_Ptr ws = Cast<Wrapped_Selector>(ss)) {
1346           if (Selector_List_Ptr sl = Cast<Selector_List>(ws->selector())) {
1347             if (parents) ws->selector(sl->resolve_parent_refs(ctx, pstack, implicit_parent));
1348           }
1349         }
1350       }
1351
1352       return retval.detach();
1353
1354     }
1355     // has no head
1356     else {
1357       return this->tails(ctx, tails);
1358     }
1359
1360     // unreachable
1361     return 0;
1362   }
1363
1364   Selector_List_Ptr Complex_Selector::tails(Context& ctx, Selector_List_Ptr tails)
1365   {
1366     Selector_List_Ptr rv = SASS_MEMORY_NEW(Selector_List, pstate_);
1367     if (tails && tails->length()) {
1368       for (size_t i = 0, iL = tails->length(); i < iL; ++i) {
1369         Complex_Selector_Obj pr = SASS_MEMORY_CLONE(this);
1370         pr->tail(tails->at(i));
1371         rv->append(pr);
1372       }
1373     }
1374     else {
1375       rv->append(this);
1376     }
1377     return rv;
1378   }
1379
1380   // return the last tail that is defined
1381   Complex_Selector_Obj Complex_Selector::first()
1382   {
1383     // declare variables used in loop
1384     Complex_Selector_Obj cur = this;
1385     Compound_Selector_Obj head;
1386     // processing loop
1387     while (cur)
1388     {
1389       // get the head
1390       head = cur->head_;
1391       // abort (and return) if it is not a parent selector
1392       if (!head || head->length() != 1 || !Cast<Parent_Selector>((*head)[0])) {
1393         break;
1394       }
1395       // advance to next
1396       cur = cur->tail_;
1397     }
1398     // result
1399     return cur;
1400   }
1401
1402   // return the last tail that is defined
1403   Complex_Selector_Obj Complex_Selector::last()
1404   {
1405     Complex_Selector_Ptr cur = this;
1406     Complex_Selector_Ptr nxt = cur;
1407     // loop until last
1408     while (nxt) {
1409       cur = nxt;
1410       nxt = cur->tail();
1411     }
1412     return cur;
1413   }
1414
1415   Complex_Selector::Combinator Complex_Selector::clear_innermost()
1416   {
1417     Combinator c;
1418     if (!tail() || tail()->tail() == 0)
1419     { c = combinator(); combinator(ANCESTOR_OF); tail(0); }
1420     else
1421     { c = tail()->clear_innermost(); }
1422     return c;
1423   }
1424
1425   void Complex_Selector::set_innermost(Complex_Selector_Obj val, Combinator c)
1426   {
1427     if (!tail())
1428     { tail(val); combinator(c); }
1429     else
1430     { tail()->set_innermost(val, c); }
1431   }
1432
1433   void Complex_Selector::cloneChildren()
1434   {
1435     if (head()) head(SASS_MEMORY_CLONE(head()));
1436     if (tail()) tail(SASS_MEMORY_CLONE(tail()));
1437   }
1438
1439   void Compound_Selector::cloneChildren()
1440   {
1441     for (size_t i = 0, l = length(); i < l; i++) {
1442       at(i) = SASS_MEMORY_CLONE(at(i));
1443     }
1444   }
1445
1446   void Selector_List::cloneChildren()
1447   {
1448     for (size_t i = 0, l = length(); i < l; i++) {
1449       at(i) = SASS_MEMORY_CLONE(at(i));
1450     }
1451   }
1452
1453   void Wrapped_Selector::cloneChildren()
1454   {
1455     selector(SASS_MEMORY_CLONE(selector()));
1456   }
1457
1458   // remove parent selector references
1459   // basically unwraps parsed selectors
1460   void Selector_List::remove_parent_selectors()
1461   {
1462     // Check every rhs selector against left hand list
1463     for(size_t i = 0, L = length(); i < L; ++i) {
1464       if (!(*this)[i]->head()) continue;
1465       if ((*this)[i]->head()->is_empty_reference()) {
1466         // simply move to the next tail if we have "no" combinator
1467         if ((*this)[i]->combinator() == Complex_Selector::ANCESTOR_OF) {
1468           if ((*this)[i]->tail()) {
1469             if ((*this)[i]->has_line_feed()) {
1470               (*this)[i]->tail()->has_line_feed(true);
1471             }
1472             (*this)[i] = (*this)[i]->tail();
1473           }
1474         }
1475         // otherwise remove the first item from head
1476         else {
1477           (*this)[i]->head()->erase((*this)[i]->head()->begin());
1478         }
1479       }
1480     }
1481   }
1482
1483   size_t Wrapped_Selector::hash()
1484   {
1485     if (hash_ == 0) {
1486       hash_combine(hash_, Simple_Selector::hash());
1487       if (selector_) hash_combine(hash_, selector_->hash());
1488     }
1489     return hash_;
1490   }
1491   bool Wrapped_Selector::has_parent_ref() const {
1492     // if (has_reference()) return true;
1493     if (!selector()) return false;
1494     return selector()->has_parent_ref();
1495   }
1496   bool Wrapped_Selector::has_real_parent_ref() const {
1497     // if (has_reference()) return true;
1498     if (!selector()) return false;
1499     return selector()->has_real_parent_ref();
1500   }
1501   unsigned long Wrapped_Selector::specificity() const
1502   {
1503     return selector_ ? selector_->specificity() : 0;
1504   }
1505
1506
1507   bool Selector_List::has_parent_ref() const
1508   {
1509     for (Complex_Selector_Obj s : elements()) {
1510       if (s && s->has_parent_ref()) return true;
1511     }
1512     return false;
1513   }
1514
1515   bool Selector_List::has_real_parent_ref() const
1516   {
1517     for (Complex_Selector_Obj s : elements()) {
1518       if (s && s->has_real_parent_ref()) return true;
1519     }
1520     return false;
1521   }
1522
1523   bool Selector_Schema::has_parent_ref() const
1524   {
1525     if (String_Schema_Obj schema = Cast<String_Schema>(contents())) {
1526       return schema->length() > 0 && Cast<Parent_Selector>(schema->at(0)) != NULL;
1527     }
1528     return false;
1529   }
1530
1531   bool Selector_Schema::has_real_parent_ref() const
1532   {
1533     if (String_Schema_Obj schema = Cast<String_Schema>(contents())) {
1534       Parent_Selector_Obj p = Cast<Parent_Selector>(schema->at(0));
1535       return schema->length() > 0 && p && p->is_real_parent_ref();
1536     }
1537     return false;
1538   }
1539
1540   void Selector_List::adjust_after_pushing(Complex_Selector_Obj c)
1541   {
1542     // if (c->has_reference())   has_reference(true);
1543   }
1544
1545   // it's a superselector if every selector of the right side
1546   // list is a superselector of the given left side selector
1547   bool Complex_Selector::is_superselector_of(Selector_List_Obj sub, std::string wrapping)
1548   {
1549     // Check every rhs selector against left hand list
1550     for(size_t i = 0, L = sub->length(); i < L; ++i) {
1551       if (!is_superselector_of((*sub)[i], wrapping)) return false;
1552     }
1553     return true;
1554   }
1555
1556   // it's a superselector if every selector of the right side
1557   // list is a superselector of the given left side selector
1558   bool Selector_List::is_superselector_of(Selector_List_Obj sub, std::string wrapping)
1559   {
1560     // Check every rhs selector against left hand list
1561     for(size_t i = 0, L = sub->length(); i < L; ++i) {
1562       if (!is_superselector_of((*sub)[i], wrapping)) return false;
1563     }
1564     return true;
1565   }
1566
1567   // it's a superselector if every selector on the right side
1568   // is a superselector of any one of the left side selectors
1569   bool Selector_List::is_superselector_of(Compound_Selector_Obj sub, std::string wrapping)
1570   {
1571     // Check every lhs selector against right hand
1572     for(size_t i = 0, L = length(); i < L; ++i) {
1573       if ((*this)[i]->is_superselector_of(sub, wrapping)) return true;
1574     }
1575     return false;
1576   }
1577
1578   // it's a superselector if every selector on the right side
1579   // is a superselector of any one of the left side selectors
1580   bool Selector_List::is_superselector_of(Complex_Selector_Obj sub, std::string wrapping)
1581   {
1582     // Check every lhs selector against right hand
1583     for(size_t i = 0, L = length(); i < L; ++i) {
1584       if ((*this)[i]->is_superselector_of(sub)) return true;
1585     }
1586     return false;
1587   }
1588
1589   Selector_List_Ptr Selector_List::unify_with(Selector_List_Ptr rhs, Context& ctx) {
1590     std::vector<Complex_Selector_Obj> unified_complex_selectors;
1591     // Unify all of children with RHS's children, storing the results in `unified_complex_selectors`
1592     for (size_t lhs_i = 0, lhs_L = length(); lhs_i < lhs_L; ++lhs_i) {
1593       Complex_Selector_Obj seq1 = (*this)[lhs_i];
1594       for(size_t rhs_i = 0, rhs_L = rhs->length(); rhs_i < rhs_L; ++rhs_i) {
1595         Complex_Selector_Ptr seq2 = rhs->at(rhs_i);
1596
1597         Selector_List_Obj result = seq1->unify_with(seq2, ctx);
1598         if( result ) {
1599           for(size_t i = 0, L = result->length(); i < L; ++i) {
1600             unified_complex_selectors.push_back( (*result)[i] );
1601           }
1602         }
1603       }
1604     }
1605
1606     // Creates the final Selector_List by combining all the complex selectors
1607     Selector_List_Ptr final_result = SASS_MEMORY_NEW(Selector_List, pstate());
1608     for (auto itr = unified_complex_selectors.begin(); itr != unified_complex_selectors.end(); ++itr) {
1609       final_result->append(*itr);
1610     }
1611     return final_result;
1612   }
1613
1614   void Selector_List::populate_extends(Selector_List_Obj extendee, Context& ctx, Subset_Map& extends)
1615   {
1616
1617     Selector_List_Ptr extender = this;
1618     for (auto complex_sel : extendee->elements()) {
1619       Complex_Selector_Obj c = complex_sel;
1620
1621
1622       // Ignore any parent selectors, until we find the first non Selectorerence head
1623       Compound_Selector_Obj compound_sel = c->head();
1624       Complex_Selector_Obj pIter = complex_sel;
1625       while (pIter) {
1626         Compound_Selector_Obj pHead = pIter->head();
1627         if (pHead && Cast<Parent_Selector>(pHead->elements()[0]) == NULL) {
1628           compound_sel = pHead;
1629           break;
1630         }
1631
1632         pIter = pIter->tail();
1633       }
1634
1635       if (!pIter->head() || pIter->tail()) {
1636         error("nested selectors may not be extended", c->pstate());
1637       }
1638
1639       compound_sel->is_optional(extendee->is_optional());
1640
1641       for (size_t i = 0, L = extender->length(); i < L; ++i) {
1642         extends.put(compound_sel, std::make_pair((*extender)[i], compound_sel));
1643       }
1644     }
1645   };
1646
1647   void Compound_Selector::append(Simple_Selector_Ptr element)
1648   {
1649     Vectorized<Simple_Selector_Obj>::append(element);
1650     pstate_.offset += element->pstate().offset;
1651   }
1652
1653   Compound_Selector_Ptr Compound_Selector::minus(Compound_Selector_Ptr rhs, Context& ctx)
1654   {
1655     Compound_Selector_Ptr result = SASS_MEMORY_NEW(Compound_Selector, pstate());
1656     // result->has_parent_reference(has_parent_reference());
1657
1658     // not very efficient because it needs to preserve order
1659     for (size_t i = 0, L = length(); i < L; ++i)
1660     {
1661       bool found = false;
1662       std::string thisSelector((*this)[i]->to_string(ctx.c_options));
1663       for (size_t j = 0, M = rhs->length(); j < M; ++j)
1664       {
1665         if (thisSelector == (*rhs)[j]->to_string(ctx.c_options))
1666         {
1667           found = true;
1668           break;
1669         }
1670       }
1671       if (!found) result->append((*this)[i]);
1672     }
1673
1674     return result;
1675   }
1676
1677   void Compound_Selector::mergeSources(ComplexSelectorSet& sources, Context& ctx)
1678   {
1679     for (ComplexSelectorSet::iterator iterator = sources.begin(), endIterator = sources.end(); iterator != endIterator; ++iterator) {
1680       this->sources_.insert(SASS_MEMORY_CLONE(*iterator));
1681     }
1682   }
1683
1684   Argument_Obj Arguments::get_rest_argument()
1685   {
1686     if (this->has_rest_argument()) {
1687       for (Argument_Obj arg : this->elements()) {
1688         if (arg->is_rest_argument()) {
1689           return arg;
1690         }
1691       }
1692     }
1693     return NULL;
1694   }
1695
1696   Argument_Obj Arguments::get_keyword_argument()
1697   {
1698     if (this->has_keyword_argument()) {
1699       for (Argument_Obj arg : this->elements()) {
1700         if (arg->is_keyword_argument()) {
1701           return arg;
1702         }
1703       }
1704     }
1705     return NULL;
1706   }
1707
1708   void Arguments::adjust_after_pushing(Argument_Obj a)
1709   {
1710     if (!a->name().empty()) {
1711       if (/* has_rest_argument_ || */ has_keyword_argument_) {
1712         error("named arguments must precede variable-length argument", a->pstate());
1713       }
1714       has_named_arguments_ = true;
1715     }
1716     else if (a->is_rest_argument()) {
1717       if (has_rest_argument_) {
1718         error("functions and mixins may only be called with one variable-length argument", a->pstate());
1719       }
1720       if (has_keyword_argument_) {
1721         error("only keyword arguments may follow variable arguments", a->pstate());
1722       }
1723       has_rest_argument_ = true;
1724     }
1725     else if (a->is_keyword_argument()) {
1726       if (has_keyword_argument_) {
1727         error("functions and mixins may only be called with one keyword argument", a->pstate());
1728       }
1729       has_keyword_argument_ = true;
1730     }
1731     else {
1732       if (has_rest_argument_) {
1733         error("ordinal arguments must precede variable-length arguments", a->pstate());
1734       }
1735       if (has_named_arguments_) {
1736         error("ordinal arguments must precede named arguments", a->pstate());
1737       }
1738     }
1739   }
1740
1741   bool Ruleset::is_invisible() const {
1742     if (Selector_List_Ptr sl = Cast<Selector_List>(selector())) {
1743       for (size_t i = 0, L = sl->length(); i < L; ++i)
1744         if (!(*sl)[i]->has_placeholder()) return false;
1745     }
1746     return true;
1747   }
1748
1749   bool Media_Block::is_invisible() const {
1750     for (size_t i = 0, L = block()->length(); i < L; ++i) {
1751       Statement_Obj stm = block()->at(i);
1752       if (!stm->is_invisible()) return false;
1753     }
1754     return true;
1755   }
1756
1757   Number::Number(ParserState pstate, double val, std::string u, bool zero)
1758   : Value(pstate),
1759     value_(val),
1760     zero_(zero),
1761     numerator_units_(std::vector<std::string>()),
1762     denominator_units_(std::vector<std::string>()),
1763     hash_(0)
1764   {
1765     size_t l = 0, r = 0;
1766     if (!u.empty()) {
1767       bool nominator = true;
1768       while (true) {
1769         r = u.find_first_of("*/", l);
1770         std::string unit(u.substr(l, r == std::string::npos ? r : r - l));
1771         if (!unit.empty()) {
1772           if (nominator) numerator_units_.push_back(unit);
1773           else denominator_units_.push_back(unit);
1774         }
1775         if (r == std::string::npos) break;
1776         // ToDo: should error for multiple slashes
1777         // if (!nominator && u[r] == '/') error(...)
1778         if (u[r] == '/')
1779           nominator = false;
1780         l = r + 1;
1781       }
1782     }
1783     concrete_type(NUMBER);
1784   }
1785
1786   std::string Number::unit() const
1787   {
1788     std::string u;
1789     for (size_t i = 0, S = numerator_units_.size(); i < S; ++i) {
1790       if (i) u += '*';
1791       u += numerator_units_[i];
1792     }
1793     if (!denominator_units_.empty()) u += '/';
1794     for (size_t i = 0, S = denominator_units_.size(); i < S; ++i) {
1795       if (i) u += '*';
1796       u += denominator_units_[i];
1797     }
1798     return u;
1799   }
1800
1801   bool Number::is_valid_css_unit() const
1802   {
1803     return numerator_units().size() <= 1 &&
1804            denominator_units().size() == 0;
1805   }
1806
1807   bool Number::is_unitless() const
1808   { return numerator_units_.empty() && denominator_units_.empty(); }
1809
1810   void Number::normalize(const std::string& prefered, bool strict)
1811   {
1812
1813     // first make sure same units cancel each other out
1814     // it seems that a map table will fit nicely to do this
1815     // we basically construct exponents for each unit
1816     // has the advantage that they will be pre-sorted
1817     std::map<std::string, int> exponents;
1818
1819     // initialize by summing up occurences in unit vectors
1820     for (size_t i = 0, S = numerator_units_.size(); i < S; ++i) ++ exponents[numerator_units_[i]];
1821     for (size_t i = 0, S = denominator_units_.size(); i < S; ++i) -- exponents[denominator_units_[i]];
1822
1823     // the final conversion factor
1824     double factor = 1;
1825
1826     // get the first entry of numerators
1827     // forward it when entry is converted
1828     std::vector<std::string>::iterator nom_it = numerator_units_.begin();
1829     std::vector<std::string>::iterator nom_end = numerator_units_.end();
1830     std::vector<std::string>::iterator denom_it = denominator_units_.begin();
1831     std::vector<std::string>::iterator denom_end = denominator_units_.end();
1832
1833     // main normalization loop
1834     // should be close to optimal
1835     while (denom_it != denom_end)
1836     {
1837       // get and increment afterwards
1838       const std::string denom = *(denom_it ++);
1839       // skip already canceled out unit
1840       if (exponents[denom] >= 0) continue;
1841       // skip all units we don't know how to convert
1842       if (string_to_unit(denom) == UNKNOWN) continue;
1843       // now search for nominator
1844       while (nom_it != nom_end)
1845       {
1846         // get and increment afterwards
1847         const std::string nom = *(nom_it ++);
1848         // skip already canceled out unit
1849         if (exponents[nom] <= 0) continue;
1850         // skip all units we don't know how to convert
1851         if (string_to_unit(nom) == UNKNOWN) continue;
1852         // we now have two convertable units
1853         // add factor for current conversion
1854         factor *= conversion_factor(nom, denom, strict);
1855         // update nominator/denominator exponent
1856         -- exponents[nom]; ++ exponents[denom];
1857         // inner loop done
1858         break;
1859       }
1860     }
1861
1862     // now we can build up the new unit arrays
1863     numerator_units_.clear();
1864     denominator_units_.clear();
1865
1866     // build them by iterating over the exponents
1867     for (auto exp : exponents)
1868     {
1869       // maybe there is more effecient way to push
1870       // the same item multiple times to a vector?
1871       for(size_t i = 0, S = abs(exp.second); i < S; ++i)
1872       {
1873         // opted to have these switches in the inner loop
1874         // makes it more readable and should not cost much
1875         if (!exp.first.empty()) {
1876           if (exp.second < 0) denominator_units_.push_back(exp.first);
1877           else if (exp.second > 0) numerator_units_.push_back(exp.first);
1878         }
1879       }
1880     }
1881
1882     // apply factor to value_
1883     // best precision this way
1884     value_ *= factor;
1885
1886     // maybe convert to other unit
1887     // easier implemented on its own
1888     try { convert(prefered, strict); }
1889     catch (incompatibleUnits& err)
1890     { error(err.what(), pstate()); }
1891     catch (...) { throw; }
1892
1893   }
1894
1895   // this does not cover all cases (multiple prefered units)
1896   double Number::convert_factor(const Number& n) const
1897   {
1898
1899     // first make sure same units cancel each other out
1900     // it seems that a map table will fit nicely to do this
1901     // we basically construct exponents for each unit class
1902     // std::map<std::string, int> exponents;
1903     // initialize by summing up occurences in unit vectors
1904     // for (size_t i = 0, S = numerator_units_.size(); i < S; ++i) ++ exponents[unit_to_class(numerator_units_[i])];
1905     // for (size_t i = 0, S = denominator_units_.size(); i < S; ++i) -- exponents[unit_to_class(denominator_units_[i])];
1906
1907     std::vector<std::string> l_miss_nums(0);
1908     std::vector<std::string> l_miss_dens(0);
1909     // create copy since we need these for state keeping
1910     std::vector<std::string> r_nums(n.numerator_units_);
1911     std::vector<std::string> r_dens(n.denominator_units_);
1912
1913     std::vector<std::string>::const_iterator l_num_it = numerator_units_.begin();
1914     std::vector<std::string>::const_iterator l_num_end = numerator_units_.end();
1915
1916     bool l_unitless = is_unitless();
1917     bool r_unitless = n.is_unitless();
1918
1919     // overall conversion
1920     double factor = 1;
1921
1922     // process all left numerators
1923     while (l_num_it != l_num_end)
1924     {
1925       // get and increment afterwards
1926       const std::string l_num = *(l_num_it ++);
1927
1928       std::vector<std::string>::iterator r_num_it = r_nums.begin();
1929       std::vector<std::string>::iterator r_num_end = r_nums.end();
1930
1931       bool found = false;
1932       // search for compatible numerator
1933       while (r_num_it != r_num_end)
1934       {
1935         // get and increment afterwards
1936         const std::string r_num = *(r_num_it);
1937         // get possible converstion factor for units
1938         double conversion = conversion_factor(l_num, r_num, false);
1939         // skip incompatible numerator
1940         if (conversion == 0) {
1941           ++ r_num_it;
1942           continue;
1943         }
1944         // apply to global factor
1945         factor *= conversion;
1946         // remove item from vector
1947         r_nums.erase(r_num_it);
1948         // found numerator
1949         found = true;
1950         break;
1951       }
1952       // maybe we did not find any
1953       // left numerator is leftover
1954       if (!found) l_miss_nums.push_back(l_num);
1955     }
1956
1957     std::vector<std::string>::const_iterator l_den_it = denominator_units_.begin();
1958     std::vector<std::string>::const_iterator l_den_end = denominator_units_.end();
1959
1960     // process all left denominators
1961     while (l_den_it != l_den_end)
1962     {
1963       // get and increment afterwards
1964       const std::string l_den = *(l_den_it ++);
1965
1966       std::vector<std::string>::iterator r_den_it = r_dens.begin();
1967       std::vector<std::string>::iterator r_den_end = r_dens.end();
1968
1969       bool found = false;
1970       // search for compatible denominator
1971       while (r_den_it != r_den_end)
1972       {
1973         // get and increment afterwards
1974         const std::string r_den = *(r_den_it);
1975         // get possible converstion factor for units
1976         double conversion = conversion_factor(l_den, r_den, false);
1977         // skip incompatible denominator
1978         if (conversion == 0) {
1979           ++ r_den_it;
1980           continue;
1981         }
1982         // apply to global factor
1983         factor *= conversion;
1984         // remove item from vector
1985         r_dens.erase(r_den_it);
1986         // found denominator
1987         found = true;
1988         break;
1989       }
1990       // maybe we did not find any
1991       // left denominator is leftover
1992       if (!found) l_miss_dens.push_back(l_den);
1993     }
1994
1995     // check left-overs (ToDo: might cancel out)
1996     if (l_miss_nums.size() > 0 && !r_unitless) {
1997       throw Exception::IncompatibleUnits(n, *this);
1998     }
1999     if (l_miss_dens.size() > 0 && !r_unitless) {
2000       throw Exception::IncompatibleUnits(n, *this);
2001     }
2002     if (r_nums.size() > 0 && !l_unitless) {
2003       throw Exception::IncompatibleUnits(n, *this);
2004     }
2005     if (r_dens.size() > 0 && !l_unitless) {
2006       throw Exception::IncompatibleUnits(n, *this);
2007     }
2008
2009     return factor;
2010   }
2011
2012   // this does not cover all cases (multiple prefered units)
2013   bool Number::convert(const std::string& prefered, bool strict)
2014   {
2015     // no conversion if unit is empty
2016     if (prefered.empty()) return true;
2017
2018     // first make sure same units cancel each other out
2019     // it seems that a map table will fit nicely to do this
2020     // we basically construct exponents for each unit
2021     // has the advantage that they will be pre-sorted
2022     std::map<std::string, int> exponents;
2023
2024     // initialize by summing up occurences in unit vectors
2025     for (size_t i = 0, S = numerator_units_.size(); i < S; ++i) ++ exponents[numerator_units_[i]];
2026     for (size_t i = 0, S = denominator_units_.size(); i < S; ++i) -- exponents[denominator_units_[i]];
2027
2028     // the final conversion factor
2029     double factor = 1;
2030
2031     std::vector<std::string>::iterator denom_it = denominator_units_.begin();
2032     std::vector<std::string>::iterator denom_end = denominator_units_.end();
2033
2034     // main normalization loop
2035     // should be close to optimal
2036     while (denom_it != denom_end)
2037     {
2038       // get and increment afterwards
2039       const std::string denom = *(denom_it ++);
2040       // check if conversion is needed
2041       if (denom == prefered) continue;
2042       // skip already canceled out unit
2043       if (exponents[denom] >= 0) continue;
2044       // skip all units we don't know how to convert
2045       if (string_to_unit(denom) == UNKNOWN) continue;
2046       // we now have two convertable units
2047       // add factor for current conversion
2048       factor *= conversion_factor(denom, prefered, strict);
2049       // update nominator/denominator exponent
2050       ++ exponents[denom]; -- exponents[prefered];
2051     }
2052
2053     std::vector<std::string>::iterator nom_it = numerator_units_.begin();
2054     std::vector<std::string>::iterator nom_end = numerator_units_.end();
2055
2056     // now search for nominator
2057     while (nom_it != nom_end)
2058     {
2059       // get and increment afterwards
2060       const std::string nom = *(nom_it ++);
2061       // check if conversion is needed
2062       if (nom == prefered) continue;
2063       // skip already canceled out unit
2064       if (exponents[nom] <= 0) continue;
2065       // skip all units we don't know how to convert
2066       if (string_to_unit(nom) == UNKNOWN) continue;
2067       // we now have two convertable units
2068       // add factor for current conversion
2069       factor *= conversion_factor(nom, prefered, strict);
2070       // update nominator/denominator exponent
2071       -- exponents[nom]; ++ exponents[prefered];
2072     }
2073
2074     // now we can build up the new unit arrays
2075     numerator_units_.clear();
2076     denominator_units_.clear();
2077
2078     // build them by iterating over the exponents
2079     for (auto exp : exponents)
2080     {
2081       // maybe there is more effecient way to push
2082       // the same item multiple times to a vector?
2083       for(size_t i = 0, S = abs(exp.second); i < S; ++i)
2084       {
2085         // opted to have these switches in the inner loop
2086         // makes it more readable and should not cost much
2087         if (!exp.first.empty()) {
2088           if (exp.second < 0) denominator_units_.push_back(exp.first);
2089           else if (exp.second > 0) numerator_units_.push_back(exp.first);
2090         }
2091       }
2092     }
2093
2094     // apply factor to value_
2095     // best precision this way
2096     value_ *= factor;
2097
2098     // success?
2099     return true;
2100
2101   }
2102
2103   // useful for making one number compatible with another
2104   std::string Number::find_convertible_unit() const
2105   {
2106     for (size_t i = 0, S = numerator_units_.size(); i < S; ++i) {
2107       std::string u(numerator_units_[i]);
2108       if (string_to_unit(u) != UNKNOWN) return u;
2109     }
2110     for (size_t i = 0, S = denominator_units_.size(); i < S; ++i) {
2111       std::string u(denominator_units_[i]);
2112       if (string_to_unit(u) != UNKNOWN) return u;
2113     }
2114     return std::string();
2115   }
2116
2117   bool Custom_Warning::operator== (const Expression& rhs) const
2118   {
2119     if (Custom_Warning_Ptr_Const r = Cast<Custom_Warning>(&rhs)) {
2120       return message() == r->message();
2121     }
2122     return false;
2123   }
2124
2125   bool Custom_Error::operator== (const Expression& rhs) const
2126   {
2127     if (Custom_Error_Ptr_Const r = Cast<Custom_Error>(&rhs)) {
2128       return message() == r->message();
2129     }
2130     return false;
2131   }
2132
2133   bool Number::operator== (const Expression& rhs) const
2134   {
2135     if (Number_Ptr_Const r = Cast<Number>(&rhs)) {
2136       size_t lhs_units = numerator_units_.size() + denominator_units_.size();
2137       size_t rhs_units = r->numerator_units_.size() + r->denominator_units_.size();
2138       // unitless and only having one unit seems equivalent (will change in future)
2139       if (!lhs_units || !rhs_units) {
2140         return std::fabs(value() - r->value()) < NUMBER_EPSILON;
2141       }
2142       return (numerator_units_ == r->numerator_units_) &&
2143              (denominator_units_ == r->denominator_units_) &&
2144              std::fabs(value() - r->value()) < NUMBER_EPSILON;
2145     }
2146     return false;
2147   }
2148
2149   bool Number::operator< (const Number& rhs) const
2150   {
2151     size_t lhs_units = numerator_units_.size() + denominator_units_.size();
2152     size_t rhs_units = rhs.numerator_units_.size() + rhs.denominator_units_.size();
2153     // unitless and only having one unit seems equivalent (will change in future)
2154     if (!lhs_units || !rhs_units) {
2155       return value() < rhs.value();
2156     }
2157
2158     Number tmp_r(&rhs); // copy
2159     tmp_r.normalize(find_convertible_unit());
2160     std::string l_unit(unit());
2161     std::string r_unit(tmp_r.unit());
2162     if (unit() != tmp_r.unit()) {
2163       error("cannot compare numbers with incompatible units", pstate());
2164     }
2165     return value() < tmp_r.value();
2166   }
2167
2168   bool String_Quoted::operator== (const Expression& rhs) const
2169   {
2170     if (String_Quoted_Ptr_Const qstr = Cast<String_Quoted>(&rhs)) {
2171       return (value() == qstr->value());
2172     } else if (String_Constant_Ptr_Const cstr = Cast<String_Constant>(&rhs)) {
2173       return (value() == cstr->value());
2174     }
2175     return false;
2176   }
2177
2178   bool String_Constant::is_invisible() const {
2179     return value_.empty() && quote_mark_ == 0;
2180   }
2181
2182   bool String_Constant::operator== (const Expression& rhs) const
2183   {
2184     if (String_Quoted_Ptr_Const qstr = Cast<String_Quoted>(&rhs)) {
2185       return (value() == qstr->value());
2186     } else if (String_Constant_Ptr_Const cstr = Cast<String_Constant>(&rhs)) {
2187       return (value() == cstr->value());
2188     }
2189     return false;
2190   }
2191
2192   bool String_Schema::is_left_interpolant(void) const
2193   {
2194     return length() && first()->is_left_interpolant();
2195   }
2196   bool String_Schema::is_right_interpolant(void) const
2197   {
2198     return length() && last()->is_right_interpolant();
2199   }
2200
2201   bool String_Schema::operator== (const Expression& rhs) const
2202   {
2203     if (String_Schema_Ptr_Const r = Cast<String_Schema>(&rhs)) {
2204       if (length() != r->length()) return false;
2205       for (size_t i = 0, L = length(); i < L; ++i) {
2206         Expression_Obj rv = (*r)[i];
2207         Expression_Obj lv = (*this)[i];
2208         if (!lv || !rv) return false;
2209         if (!(*lv == *rv)) return false;
2210       }
2211       return true;
2212     }
2213     return false;
2214   }
2215
2216   bool Boolean::operator== (const Expression& rhs) const
2217   {
2218     if (Boolean_Ptr_Const r = Cast<Boolean>(&rhs)) {
2219       return (value() == r->value());
2220     }
2221     return false;
2222   }
2223
2224   bool Color::operator== (const Expression& rhs) const
2225   {
2226     if (Color_Ptr_Const r = Cast<Color>(&rhs)) {
2227       return r_ == r->r() &&
2228              g_ == r->g() &&
2229              b_ == r->b() &&
2230              a_ == r->a();
2231     }
2232     return false;
2233   }
2234
2235   bool List::operator== (const Expression& rhs) const
2236   {
2237     if (List_Ptr_Const r = Cast<List>(&rhs)) {
2238       if (length() != r->length()) return false;
2239       if (separator() != r->separator()) return false;
2240       if (is_bracketed() != r->is_bracketed()) return false;
2241       for (size_t i = 0, L = length(); i < L; ++i) {
2242         Expression_Obj rv = r->at(i);
2243         Expression_Obj lv = this->at(i);
2244         if (!lv || !rv) return false;
2245         if (!(*lv == *rv)) return false;
2246       }
2247       return true;
2248     }
2249     return false;
2250   }
2251
2252   bool Map::operator== (const Expression& rhs) const
2253   {
2254     if (Map_Ptr_Const r = Cast<Map>(&rhs)) {
2255       if (length() != r->length()) return false;
2256       for (auto key : keys()) {
2257         Expression_Obj lv = at(key);
2258         Expression_Obj rv = r->at(key);
2259         if (!rv || !lv) return false;
2260         if (!(*lv == *rv)) return false;
2261       }
2262       return true;
2263     }
2264     return false;
2265   }
2266
2267   bool Null::operator== (const Expression& rhs) const
2268   {
2269     return rhs.concrete_type() == NULL_VAL;
2270   }
2271
2272   size_t List::size() const {
2273     if (!is_arglist_) return length();
2274     // arglist expects a list of arguments
2275     // so we need to break before keywords
2276     for (size_t i = 0, L = length(); i < L; ++i) {
2277       Expression_Obj obj = this->at(i);
2278       if (Argument_Ptr arg = Cast<Argument>(obj)) {
2279         if (!arg->name().empty()) return i;
2280       }
2281     }
2282     return length();
2283   }
2284
2285   Expression_Obj Hashed::at(Expression_Obj k) const
2286   {
2287     if (elements_.count(k))
2288     { return elements_.at(k); }
2289     else { return NULL; }
2290   }
2291
2292   bool Binary_Expression::is_left_interpolant(void) const
2293   {
2294     return is_interpolant() || (left() && left()->is_left_interpolant());
2295   }
2296   bool Binary_Expression::is_right_interpolant(void) const
2297   {
2298     return is_interpolant() || (right() && right()->is_right_interpolant());
2299   }
2300
2301   const std::string AST_Node::to_string(Sass_Inspect_Options opt) const
2302   {
2303     Sass_Output_Options out(opt);
2304     Emitter emitter(out);
2305     Inspect i(emitter);
2306     i.in_declaration = true;
2307     // ToDo: inspect should be const
2308     const_cast<AST_Node_Ptr>(this)->perform(&i);
2309     return i.get_buffer();
2310   }
2311
2312   const std::string AST_Node::to_string() const
2313   {
2314     return to_string({ NESTED, 5 });
2315   }
2316
2317   std::string String_Quoted::inspect() const
2318   {
2319     return quote(value_, '*');
2320   }
2321
2322   std::string String_Constant::inspect() const
2323   {
2324     return quote(value_, '*');
2325   }
2326
2327   //////////////////////////////////////////////////////////////////////////////////////////
2328   // Additional method on Lists to retrieve values directly or from an encompassed Argument.
2329   //////////////////////////////////////////////////////////////////////////////////////////
2330   Expression_Obj List::value_at_index(size_t i) {
2331     Expression_Obj obj = this->at(i);
2332     if (is_arglist_) {
2333       if (Argument_Ptr arg = Cast<Argument>(obj)) {
2334         return arg->value();
2335       } else {
2336         return obj;
2337       }
2338     } else {
2339       return obj;
2340     }
2341   }
2342
2343   //////////////////////////////////////////////////////////////////////////////////////////
2344   // Convert map to (key, value) list.
2345   //////////////////////////////////////////////////////////////////////////////////////////
2346   List_Obj Map::to_list(Context& ctx, ParserState& pstate) {
2347     List_Obj ret = SASS_MEMORY_NEW(List, pstate, length(), SASS_COMMA);
2348
2349     for (auto key : keys()) {
2350       List_Obj l = SASS_MEMORY_NEW(List, pstate, 2);
2351       l->append(key);
2352       l->append(at(key));
2353       ret->append(l);
2354     }
2355
2356     return ret;
2357   }
2358
2359   //////////////////////////////////////////////////////////////////////////////////////////
2360   // Copy implementations
2361   //////////////////////////////////////////////////////////////////////////////////////////
2362
2363   #ifdef DEBUG_SHARED_PTR
2364
2365   #define IMPLEMENT_AST_OPERATORS(klass) \
2366     klass##_Ptr klass::copy(std::string file, size_t line) const { \
2367       klass##_Ptr cpy = new klass(this); \
2368       cpy->trace(file, line); \
2369       return cpy; \
2370     } \
2371     klass##_Ptr klass::clone(std::string file, size_t line) const { \
2372       klass##_Ptr cpy = copy(file, line); \
2373       cpy->cloneChildren(); \
2374       return cpy; \
2375     } \
2376
2377   #else
2378
2379   #define IMPLEMENT_AST_OPERATORS(klass) \
2380     klass##_Ptr klass::copy() const { \
2381       return new klass(this); \
2382     } \
2383     klass##_Ptr klass::clone() const { \
2384       klass##_Ptr cpy = copy(); \
2385       cpy->cloneChildren(); \
2386       return cpy; \
2387     } \
2388
2389   #endif
2390
2391   IMPLEMENT_AST_OPERATORS(Supports_Operator);
2392   IMPLEMENT_AST_OPERATORS(Supports_Negation);
2393   IMPLEMENT_AST_OPERATORS(Compound_Selector);
2394   IMPLEMENT_AST_OPERATORS(Complex_Selector);
2395   IMPLEMENT_AST_OPERATORS(Element_Selector);
2396   IMPLEMENT_AST_OPERATORS(Class_Selector);
2397   IMPLEMENT_AST_OPERATORS(Id_Selector);
2398   IMPLEMENT_AST_OPERATORS(Pseudo_Selector);
2399   IMPLEMENT_AST_OPERATORS(Wrapped_Selector);
2400   IMPLEMENT_AST_OPERATORS(Selector_List);
2401   IMPLEMENT_AST_OPERATORS(Ruleset);
2402   IMPLEMENT_AST_OPERATORS(Media_Block);
2403   IMPLEMENT_AST_OPERATORS(Custom_Warning);
2404   IMPLEMENT_AST_OPERATORS(Custom_Error);
2405   IMPLEMENT_AST_OPERATORS(List);
2406   IMPLEMENT_AST_OPERATORS(Map);
2407   IMPLEMENT_AST_OPERATORS(Number);
2408   IMPLEMENT_AST_OPERATORS(Binary_Expression);
2409   IMPLEMENT_AST_OPERATORS(String_Schema);
2410   IMPLEMENT_AST_OPERATORS(String_Constant);
2411   IMPLEMENT_AST_OPERATORS(String_Quoted);
2412   IMPLEMENT_AST_OPERATORS(Boolean);
2413   IMPLEMENT_AST_OPERATORS(Color);
2414   IMPLEMENT_AST_OPERATORS(Null);
2415   IMPLEMENT_AST_OPERATORS(Parent_Selector);
2416   IMPLEMENT_AST_OPERATORS(Import);
2417   IMPLEMENT_AST_OPERATORS(Import_Stub);
2418   IMPLEMENT_AST_OPERATORS(Function_Call);
2419   IMPLEMENT_AST_OPERATORS(Directive);
2420   IMPLEMENT_AST_OPERATORS(At_Root_Block);
2421   IMPLEMENT_AST_OPERATORS(Supports_Block);
2422   IMPLEMENT_AST_OPERATORS(While);
2423   IMPLEMENT_AST_OPERATORS(Each);
2424   IMPLEMENT_AST_OPERATORS(For);
2425   IMPLEMENT_AST_OPERATORS(If);
2426   IMPLEMENT_AST_OPERATORS(Mixin_Call);
2427   IMPLEMENT_AST_OPERATORS(Extension);
2428   IMPLEMENT_AST_OPERATORS(Media_Query);
2429   IMPLEMENT_AST_OPERATORS(Media_Query_Expression);
2430   IMPLEMENT_AST_OPERATORS(Debug);
2431   IMPLEMENT_AST_OPERATORS(Error);
2432   IMPLEMENT_AST_OPERATORS(Warning);
2433   IMPLEMENT_AST_OPERATORS(Assignment);
2434   IMPLEMENT_AST_OPERATORS(Return);
2435   IMPLEMENT_AST_OPERATORS(At_Root_Query);
2436   IMPLEMENT_AST_OPERATORS(Variable);
2437   IMPLEMENT_AST_OPERATORS(Comment);
2438   IMPLEMENT_AST_OPERATORS(Attribute_Selector);
2439   IMPLEMENT_AST_OPERATORS(Supports_Interpolation);
2440   IMPLEMENT_AST_OPERATORS(Supports_Declaration);
2441   IMPLEMENT_AST_OPERATORS(Supports_Condition);
2442   IMPLEMENT_AST_OPERATORS(Parameters);
2443   IMPLEMENT_AST_OPERATORS(Parameter);
2444   IMPLEMENT_AST_OPERATORS(Arguments);
2445   IMPLEMENT_AST_OPERATORS(Argument);
2446   IMPLEMENT_AST_OPERATORS(Unary_Expression);
2447   IMPLEMENT_AST_OPERATORS(Function_Call_Schema);
2448   IMPLEMENT_AST_OPERATORS(Block);
2449   IMPLEMENT_AST_OPERATORS(Content);
2450   IMPLEMENT_AST_OPERATORS(Textual);
2451   IMPLEMENT_AST_OPERATORS(Trace);
2452   IMPLEMENT_AST_OPERATORS(Keyframe_Rule);
2453   IMPLEMENT_AST_OPERATORS(Bubble);
2454   IMPLEMENT_AST_OPERATORS(Selector_Schema);
2455   IMPLEMENT_AST_OPERATORS(Placeholder_Selector);
2456   IMPLEMENT_AST_OPERATORS(Definition);
2457   IMPLEMENT_AST_OPERATORS(Declaration);
2458
2459 }