3 * Licensed under the MIT License
4 * Copyright (c) Marcel Greter
8 #define _CRT_SECURE_NO_WARNINGS
9 #define _CRT_NONSTDC_NO_DEPRECATE
23 // src comments: comments in sass syntax (staring with //)
24 // css comments: multiline comments in css syntax (starting with /*)
26 // KEEP_COMMENT: keep src comments in the resulting css code
27 // STRIP_COMMENT: strip out all comments (either src or css)
28 // CONVERT_COMMENT: convert all src comments to css comments
33 #include "sass2scss.h"
35 // add namespace for c++
39 // return the actual prettify value from options
40 #define PRETTIFY(converter) (converter.options - (converter.options & 248))
41 // query the options integer to check if the option is enables
42 #define KEEP_COMMENT(converter) ((converter.options & SASS2SCSS_KEEP_COMMENT) == SASS2SCSS_KEEP_COMMENT)
43 #define STRIP_COMMENT(converter) ((converter.options & SASS2SCSS_STRIP_COMMENT) == SASS2SCSS_STRIP_COMMENT)
44 #define CONVERT_COMMENT(converter) ((converter.options & SASS2SCSS_CONVERT_COMMENT) == SASS2SCSS_CONVERT_COMMENT)
46 // some makros to access the indentation stack
47 #define INDENT(converter) (converter.indents.top())
49 // some makros to query comment parser status
50 #define IS_PARSING(converter) (converter.comment == "")
51 #define IS_COMMENT(converter) (converter.comment != "")
52 #define IS_SRC_COMMENT(converter) (converter.comment == "//" && ! CONVERT_COMMENT(converter))
53 #define IS_CSS_COMMENT(converter) (converter.comment == "/*" || (converter.comment == "//" && CONVERT_COMMENT(converter)))
55 // pretty printer helper function
56 static std::string closer (const converter& converter)
58 return PRETTIFY(converter) == 0 ? " }" :
59 PRETTIFY(converter) <= 1 ? " }" :
60 "\n" + INDENT(converter) + "}";
63 // pretty printer helper function
64 static std::string opener (const converter& converter)
66 return PRETTIFY(converter) == 0 ? " { " :
67 PRETTIFY(converter) <= 2 ? " {" :
68 "\n" + INDENT(converter) + "{";
71 // check if the given string is a pseudo selector
72 // needed to differentiate from sass property syntax
73 static bool isPseudoSelector (std::string& sel)
76 size_t len = sel.length();
77 if (len < 1) return false;
78 size_t pos = sel.find_first_not_of("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1);
79 if (pos != std::string::npos) sel.erase(pos, std::string::npos);
80 size_t i = sel.length();
81 while (i -- > 0) { sel.at(i) = tolower(sel.at(i)); }
83 // CSS Level 1 - Recommendation
84 if (sel == ":link") return true;
85 if (sel == ":visited") return true;
86 if (sel == ":active") return true;
88 // CSS Level 2 (Revision 1) - Recommendation
89 if (sel == ":lang") return true;
90 if (sel == ":first-child") return true;
91 if (sel == ":hover") return true;
92 if (sel == ":focus") return true;
93 // disabled - also valid properties
94 // if (sel == ":left") return true;
95 // if (sel == ":right") return true;
96 if (sel == ":first") return true;
98 // Selectors Level 3 - Recommendation
99 if (sel == ":target") return true;
100 if (sel == ":root") return true;
101 if (sel == ":nth-child") return true;
102 if (sel == ":nth-last-of-child") return true;
103 if (sel == ":nth-of-type") return true;
104 if (sel == ":nth-last-of-type") return true;
105 if (sel == ":last-child") return true;
106 if (sel == ":first-of-type") return true;
107 if (sel == ":last-of-type") return true;
108 if (sel == ":only-child") return true;
109 if (sel == ":only-of-type") return true;
110 if (sel == ":empty") return true;
111 if (sel == ":not") return true;
113 // CSS Basic User Interface Module Level 3 - Working Draft
114 if (sel == ":default") return true;
115 if (sel == ":valid") return true;
116 if (sel == ":invalid") return true;
117 if (sel == ":in-range") return true;
118 if (sel == ":out-of-range") return true;
119 if (sel == ":required") return true;
120 if (sel == ":optional") return true;
121 if (sel == ":read-only") return true;
122 if (sel == ":read-write") return true;
123 if (sel == ":dir") return true;
124 if (sel == ":enabled") return true;
125 if (sel == ":disabled") return true;
126 if (sel == ":checked") return true;
127 if (sel == ":indeterminate") return true;
128 if (sel == ":nth-last-child") return true;
130 // Selectors Level 4 - Working Draft
131 if (sel == ":any-link") return true;
132 if (sel == ":local-link") return true;
133 if (sel == ":scope") return true;
134 if (sel == ":active-drop-target") return true;
135 if (sel == ":valid-drop-target") return true;
136 if (sel == ":invalid-drop-target") return true;
137 if (sel == ":current") return true;
138 if (sel == ":past") return true;
139 if (sel == ":future") return true;
140 if (sel == ":placeholder-shown") return true;
141 if (sel == ":user-error") return true;
142 if (sel == ":blank") return true;
143 if (sel == ":nth-match") return true;
144 if (sel == ":nth-last-match") return true;
145 if (sel == ":nth-column") return true;
146 if (sel == ":nth-last-column") return true;
147 if (sel == ":matches") return true;
149 // Fullscreen API - Living Standard
150 if (sel == ":fullscreen") return true;
152 // not a pseudo selector
157 // check if there is some char data
158 // will ignore everything in comments
159 static bool hasCharData (std::string& sass)
167 // try to find some meaningfull char
168 col_pos = sass.find_first_not_of(" \t\n\v\f\r", col_pos);
170 // there was no meaningfull char found
171 if (col_pos == std::string::npos) return false;
173 // found a multiline comment opener
174 if (sass.substr(col_pos, 2) == "/*")
176 // find the multiline comment closer
177 col_pos = sass.find("*/", col_pos);
178 // maybe we did not find the closer here
179 if (col_pos == std::string::npos) return false;
193 // find src comment opener
194 // correctly skips quoted strings
195 static size_t findCommentOpener (std::string& sass)
201 bool comment = false;
204 while (col_pos != std::string::npos)
207 // process all interesting chars
208 col_pos = sass.find_first_of("\"\'/\\*()", col_pos);
210 // assertion for valid result
211 if (col_pos != std::string::npos)
213 char character = sass.at(col_pos);
215 if (character == '(')
217 if (!quoted && !apoed) brackets ++;
219 else if (character == ')')
221 if (!quoted && !apoed) brackets --;
223 else if (character == '\"')
226 if (!apoed && !comment) quoted = !quoted;
228 else if (character == '\'')
231 if (!quoted && !comment) apoed = !apoed;
233 else if (col_pos > 0 && character == '/')
235 if (sass.at(col_pos - 1) == '*')
239 // next needs to be a slash too
240 else if (sass.at(col_pos - 1) == '/')
242 // only found if not in single or double quote, bracket or comment
243 if (!quoted && !apoed && !comment && brackets == 0) return col_pos - 1;
246 else if (character == '\\')
248 // skip next char if in quote
249 if (quoted || apoed) col_pos ++;
251 // this might be a comment opener
252 else if (col_pos > 0 && character == '*')
254 // opening a multiline comment
255 if (sass.at(col_pos - 1) == '/')
257 // we are now in a comment
258 if (!quoted && !apoed) comment = true;
273 // EO findCommentOpener
275 // remove multiline comments from sass string
276 // correctly skips quoted strings
277 static std::string removeMultilineComment (std::string &sass)
280 std::string clean = "";
283 size_t close_pos = 0;
286 bool comment = false;
288 // process sass til string end
289 while (col_pos != std::string::npos)
292 // process all interesting chars
293 col_pos = sass.find_first_of("\"\'/\\*", col_pos);
295 // assertion for valid result
296 if (col_pos != std::string::npos)
298 char character = sass.at(col_pos);
300 // found quoted string delimiter
301 if (character == '\"')
303 if (!apoed && !comment) quoted = !quoted;
305 else if (character == '\'')
307 if (!quoted && !comment) apoed = !apoed;
309 // found possible comment closer
310 else if (character == '/')
312 // look back to see if it is actually a closer
313 if (comment && col_pos > 0 && sass.at(col_pos - 1) == '*')
315 close_pos = col_pos + 1; comment = false;
318 else if (character == '\\')
321 if (quoted || apoed) col_pos ++;
323 // this might be a comment opener
324 else if (character == '*')
326 // look back to see if it is actually an opener
327 if (!quoted && !apoed && col_pos > 0 && sass.at(col_pos - 1) == '/')
329 comment = true; open_pos = col_pos - 1;
330 clean += sass.substr(close_pos, open_pos - close_pos);
342 // add final parts (add half open comment text)
343 if (comment) clean += sass.substr(open_pos);
344 else clean += sass.substr(close_pos);
350 // EO removeMultilineComment
352 // right trim a given string
353 std::string rtrim(const std::string &sass)
355 std::string trimmed = sass;
356 size_t pos_ws = trimmed.find_last_not_of(" \t\n\v\f\r");
357 if (pos_ws != std::string::npos)
358 { trimmed.erase(pos_ws + 1); }
359 else { trimmed.clear(); }
364 // flush whitespace and print additional text, but
365 // only print additional chars and buffer whitespace
366 std::string flush (std::string& sass, converter& converter)
370 std::string scss = "";
372 // print whitespace buffer
373 scss += PRETTIFY(converter) > 0 ?
374 converter.whitespace : "";
375 // reset whitespace buffer
376 converter.whitespace = "";
378 // remove possible newlines from string
379 size_t pos_right = sass.find_last_not_of("\n\r");
380 if (pos_right == std::string::npos) return scss;
382 // get the linefeeds from the string
383 std::string lfs = sass.substr(pos_right + 1);
384 sass = sass.substr(0, pos_right + 1);
386 // find some source comment opener
387 size_t comment_pos = findCommentOpener(sass);
388 // check if there was a source comment
389 if (comment_pos != std::string::npos)
391 // convert comment (but only outside other coments)
392 if (CONVERT_COMMENT(converter) && !IS_COMMENT(converter))
394 // convert to multiline comment
395 sass.at(comment_pos + 1) = '*';
396 // add comment node to the whitespace
402 // also include whitespace before the actual comment opener
403 size_t ws_pos = sass.find_last_not_of(SASS2SCSS_FIND_WHITESPACE, comment_pos - 1);
404 comment_pos = ws_pos == std::string::npos ? 0 : ws_pos + 1;
406 if (!STRIP_COMMENT(converter))
408 // add comment node to the whitespace
409 converter.whitespace += sass.substr(comment_pos);
413 // sass = removeMultilineComments(sass);
415 // update the actual sass code
416 sass = sass.substr(0, comment_pos);
419 // add newline as getline discharged it
420 converter.whitespace += lfs + "\n";
422 // maybe remove any leading whitespace
423 if (PRETTIFY(converter) == 0)
425 // remove leading whitespace and update string
426 size_t pos_left = sass.find_first_not_of(SASS2SCSS_FIND_WHITESPACE);
427 if (pos_left != std::string::npos) sass = sass.substr(pos_left);
439 // process a line of the sass text
440 std::string process (std::string& sass, converter& converter)
444 std::string scss = "";
446 // strip multi line comments
447 if (STRIP_COMMENT(converter))
449 sass = removeMultilineComment(sass);
455 // get postion of first meaningfull character in string
456 size_t pos_left = sass.find_first_not_of(SASS2SCSS_FIND_WHITESPACE);
458 // special case for final run
459 if (converter.end_of_file) pos_left = 0;
461 // maybe has only whitespace
462 if (pos_left == std::string::npos)
464 // just add complete whitespace
465 converter.whitespace += sass + "\n";
467 // have meaningfull first char
471 // extract and store indentation string
472 std::string indent = sass.substr(0, pos_left);
474 // check if current line starts a comment
475 std::string open = sass.substr(pos_left, 2);
477 // line has less or same indentation
478 // finalize previous open parser context
479 if (indent.length() <= INDENT(converter).length())
482 // close multilinie comment
483 if (IS_CSS_COMMENT(converter))
485 // check if comments will be stripped anyway
486 if (!STRIP_COMMENT(converter)) scss += " */";
488 // close src comment comment
489 else if (IS_SRC_COMMENT(converter))
491 // add a newline to avoid closer on same line
492 // this would put the bracket in the comment node
493 // no longer needed since we parse them correctly
494 // if (KEEP_COMMENT(converter)) scss += "\n";
496 // close css properties
497 else if (converter.property)
499 // add closer unless in concat mode
500 if (!converter.comma)
502 // if there was no colon we have a selector
503 // looks like there were no inner properties
504 if (converter.selector) scss += " {}";
505 // add final semicolon
506 else if (!converter.semicolon) scss += ";";
510 // reset comment state
511 converter.comment = "";
515 // make sure we close every "higher" block
516 while (indent.length() < INDENT(converter).length())
518 // pop stacked context
519 converter.indents.pop();
520 // print close bracket
521 if (IS_PARSING(converter))
522 { scss += closer(converter); }
523 else { scss += " */"; }
524 // reset comment state
525 converter.comment = "";
528 // reset converter state
529 converter.selector = false;
531 // looks like some undocumented behavior ...
532 // https://github.com/mgreter/sass2scss/issues/29
533 if (sass.substr(pos_left, 1) == "\\") {
534 converter.selector = true;
535 sass[pos_left] = ' ';
538 // check if we have sass property syntax
539 if (sass.substr(pos_left, 1) == ":" && sass.substr(pos_left, 2) != "::")
542 // default to a selector
543 // change back if property found
544 converter.selector = true;
545 // get postion of first whitespace char
546 size_t pos_wspace = sass.find_first_of(SASS2SCSS_FIND_WHITESPACE, pos_left);
547 // assertion check for valid result
548 if (pos_wspace != std::string::npos)
550 // get the possible pseudo selector
551 std::string pseudo = sass.substr(pos_left, pos_wspace - pos_left);
552 // get position of the first real property value char
553 // pseudo selectors get this far, but have no actual value
554 size_t pos_value = sass.find_first_not_of(SASS2SCSS_FIND_WHITESPACE, pos_wspace);
555 // assertion check for valid result
556 if (pos_value != std::string::npos)
558 // only process if not (fallowed by a semicolon or is a pseudo selector)
559 if (!(sass.at(pos_value) == ':' || isPseudoSelector(pseudo)))
561 // create new string by interchanging the colon sign for property and value
562 sass = indent + sass.substr(pos_left + 1, pos_wspace - pos_left - 1) + ":" + sass.substr(pos_wspace);
563 // try to find a colon in the current line, but only ...
564 size_t pos_colon = sass.find_first_not_of(":", pos_left);
565 // assertion for valid result
566 if (pos_colon != std::string::npos)
568 // ... after the first word (skip begining colons)
569 pos_colon = sass.find_first_of(":", pos_colon);
570 // it is a selector if there was no colon found
571 converter.selector = pos_colon == std::string::npos;
577 // check if we have a BEM property (one colon and no selector)
578 if (sass.substr(pos_left, 1) == ":" && converter.selector == true) {
579 size_t pos_wspace = sass.find_first_of(SASS2SCSS_FIND_WHITESPACE, pos_left);
580 sass = indent + sass.substr(pos_left + 1, pos_wspace) + ":";
585 // terminate some statements immediately
587 sass.substr(pos_left, 5) == "@warn" ||
588 sass.substr(pos_left, 6) == "@debug" ||
589 sass.substr(pos_left, 6) == "@error" ||
590 sass.substr(pos_left, 8) == "@charset" ||
591 sass.substr(pos_left, 10) == "@namespace"
592 ) { sass = indent + sass.substr(pos_left); }
593 // replace some specific sass shorthand directives (if not fallowed by a white space character)
594 else if (sass.substr(pos_left, 1) == "=")
595 { sass = indent + "@mixin " + sass.substr(pos_left + 1); }
596 else if (sass.substr(pos_left, 1) == "+")
598 // must be followed by a mixin call (no whitespace afterwards or at ending directly)
599 if (sass[pos_left+1] != 0 && sass[pos_left+1] != ' ' && sass[pos_left+1] != '\t') {
600 sass = indent + "@include " + sass.substr(pos_left + 1);
604 // add quotes for import if needed
605 else if (sass.substr(pos_left, 7) == "@import")
607 // get positions for the actual import url
608 size_t pos_import = sass.find_first_of(SASS2SCSS_FIND_WHITESPACE, pos_left + 7);
609 size_t pos_quote = sass.find_first_not_of(SASS2SCSS_FIND_WHITESPACE, pos_import);
610 // leave proper urls untouched
611 if (sass.substr(pos_quote, 4) != "url(")
613 // check if the url appears to be already quoted
614 if (sass.substr(pos_quote, 1) != "\"" && sass.substr(pos_quote, 1) != "\'")
616 // get position of the last char on the line
617 size_t pos_end = sass.find_last_not_of(SASS2SCSS_FIND_WHITESPACE);
618 // assertion check for valid result
619 if (pos_end != std::string::npos)
621 // add quotes around the full line after the import statement
622 sass = sass.substr(0, pos_quote) + "\"" + sass.substr(pos_quote, pos_end - pos_quote + 1) + "\"";
629 sass.substr(pos_left, 7) != "@return" &&
630 sass.substr(pos_left, 7) != "@extend" &&
631 sass.substr(pos_left, 8) != "@include" &&
632 sass.substr(pos_left, 8) != "@content"
635 // probably a selector anyway
636 converter.selector = true;
637 // try to find first colon in the current line
638 size_t pos_colon = sass.find_first_of(":", pos_left);
639 // assertion that we have a colon
640 if (pos_colon != std::string::npos)
642 // it is not a selector if we have a space after a colon
643 if (sass[pos_colon+1] == ' ') converter.selector = false;
644 if (sass[pos_colon+1] == ' ') converter.selector = false;
649 // current line has more indentation
650 if (indent.length() >= INDENT(converter).length())
652 // not in comment mode
653 if (IS_PARSING(converter))
655 // has meaningfull chars
656 if (hasCharData(sass))
658 // is probably a property
659 // also true for selectors
660 converter.property = true;
664 // current line has more indentation
665 if (indent.length() > INDENT(converter).length())
667 // not in comment mode
668 if (IS_PARSING(converter))
670 // had meaningfull chars
671 if (converter.property)
673 // print block opener
674 scss += opener(converter);
675 // push new stack context
676 converter.indents.push("");
677 // store block indentation
678 INDENT(converter) = indent;
681 // is and will be a src comment
682 else if (!IS_CSS_COMMENT(converter))
684 // scss does not allow multiline src comments
685 // therefore add forward slashes to all lines
686 sass.at(INDENT(converter).length()+0) = '/';
687 // there is an edge case here if indentation
688 // is minimal (will overwrite the fist char)
689 sass.at(INDENT(converter).length()+1) = '/';
690 // could code around that, but I dont' think
691 // this will ever be the cause for any trouble
695 // line is opening a new comment
696 if (open == "/*" || open == "//")
698 // reset the property state
699 converter.property = false;
700 // close previous comment
701 if (IS_CSS_COMMENT(converter) && open != "")
703 if (!STRIP_COMMENT(converter) && !CONVERT_COMMENT(converter)) scss += " */";
705 // force single line comments
706 // into a correct css comment
707 if (CONVERT_COMMENT(converter))
709 if (IS_PARSING(converter))
710 { sass.at(pos_left + 1) = '*'; }
713 converter.comment = open;
717 // flush data only under certain conditions
719 // strip css and src comments if option is set
720 (IS_COMMENT(converter) && STRIP_COMMENT(converter)) ||
721 // strip src comment even if strip option is not set
722 // but only if the keep src comment option is not set
723 (IS_SRC_COMMENT(converter) && ! KEEP_COMMENT(converter))
726 // flush data and buffer whitespace
727 scss += flush(sass, converter);
730 // get postion of last meaningfull char
731 size_t pos_right = sass.find_last_not_of(SASS2SCSS_FIND_WHITESPACE);
733 // check for invalid result
734 if (pos_right != std::string::npos)
737 // get the last meaningfull char
738 std::string close = sass.substr(pos_right, 1);
740 // check if next line should be concatenated (list mode)
741 converter.comma = IS_PARSING(converter) && close == ",";
742 converter.semicolon = IS_PARSING(converter) && close == ";";
744 // check if we have more than
745 // one meaningfull char
749 // get the last two chars from string
750 std::string close = sass.substr(pos_right - 1, 2);
751 // update parser status for expicitly closed comment
752 if (close == "*/") converter.comment = "";
757 // EO have meaningfull chars from end
760 // EO have meaningfull chars from start
768 // read line with either CR, LF or CR LF format
769 // http://stackoverflow.com/a/6089413/1550314
770 static std::istream& safeGetline(std::istream& is, std::string& t)
774 // The characters in the stream are read one-by-one using a std::streambuf.
775 // That is faster than reading them one-by-one using the std::istream.
776 // Code that uses streambuf this way must be guarded by a sentry object.
777 // The sentry object performs various tasks,
778 // such as thread synchronization and updating the stream state.
780 std::istream::sentry se(is, true);
781 std::streambuf* sb = is.rdbuf();
784 int c = sb->sbumpc();
789 if(sb->sgetc() == '\n')
793 // Also handle the case when the last line has no line ending
795 is.setstate(std::ios::eofbit);
803 // the main converter function for c++
804 char* sass2scss (const std::string& sass, const int options)
809 std::string scss = "";
810 std::stringstream stream(sass);
812 // create converter variable
814 // initialise all options
815 converter.comma = false;
816 converter.property = false;
817 converter.selector = false;
818 converter.semicolon = false;
819 converter.end_of_file = false;
820 converter.comment = "";
821 converter.whitespace = "";
822 converter.indents.push("");
823 converter.options = options;
825 // read line by line and process them
826 while(safeGetline(stream, line) && !stream.eof())
827 { scss += process(line, converter); }
829 // create mutable string
830 std::string closer = "";
831 // set the end of file flag
832 converter.end_of_file = true;
833 // process to close all open blocks
834 scss += process(closer, converter);
836 // allocate new memory on the heap
837 // caller has to free it after use
838 char * cstr = (char*) malloc (scss.length() + 1);
839 // create a copy of the string
840 strcpy (cstr, scss.c_str());
854 char* ADDCALL sass2scss (const char* sass, const int options)
856 return Sass::sass2scss(sass, options);
859 // Get compiled sass2scss version
860 const char* ADDCALL sass2scss_version(void) {
861 return SASS2SCSS_VERSION;