-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcsspp.cpp
More file actions
672 lines (626 loc) · 21.5 KB
/
csspp.cpp
File metadata and controls
672 lines (626 loc) · 21.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
// Copyright (c) 2015-2025 Made to Order Software Corp. All Rights Reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
/** \file
* \brief Implementation of the CSS Preprocessor command line tool.
* \tableofcontents
*
* This tool can be used as a verification, compilation, and compression
* tool depending on your needs.
*
* The Snap! Websites environment uses the tool for verification when
* generating a layout. Later a Snap! Website plugin compresses the various
* files. That way the website system includes the original file and not
* just the minimized version.
*
* \section csspp-options Command Line Options
*
* The following are the options currently supported by csspp:
*
* \subsection arguments --args or -a -- specifying arguments
*
* The SCSS scripts expect some variables to be set. Some of these variables
* can be set on the command line with the --args option. The arguments are
* added to an array that can be accessed as the variable $_csspp_args.
*
* \code
* // command line
* csspp --args red -- my-file.scss
*
* // reference to the command line argument
* .flowers
* {
* border: 1px solid rgb(identifier($_csspp_args[1]));
* }
* \endcode
*
* \warning
* This example does not work yet because I did not yet implement the
* rgb() internal function to transform input in a COLOR token. However,
* I intend to work on the colors soonish and thus it could be fully
* functional by the time you read the example.
*
* At this time there is no other way to access command line arguments.
*
* There is no $_csspp_args[0] since arrays in SCSS start at 1. This
* also means you do not (yet) have access to the name of the program
* compiling the code.
*
* Multiple arguments can be specified one after another:
*
* \code
* csspp --args red green blue -- my-file.css
* \endcode
*
* \subsection debug --debug or -d -- show all messages, including @debug messages
*
* When specified, the error output is setup to output everything,
* including fatal errors, errors, warnings, informational messages,
* and debug messages.
*
* \subsection help --help or -h -- show the available command line options
*
* The --help command line option can be used to request that the csspp
* print out the complete list of supported command line options in
* stdout.
*
* The tool then quits immediately.
*
* \subsection include -I -- specify paths to include files
*
* Specify paths to user defined directories that include SCSS scripts
* one can include using the \@import command.
*
* By default the system looks for system defined scripts (i.e. the
* default validation, version, and other similar scripts) under
* the following directory:
*
* \code
* /usr/lib/csspp/scripts
* \endcode
*
* The system scripts (initialization, closure, version) appear under
* a sub-directory named "system".
*
* The validation scripts (field names, pseudo names, etc.) appear
* under a sub-directory named "validation".
*
* There are no specific rules for where include files will be found.
* The \@import can use a full path or a local path. When a local path
* is used, then all the specified -I paths are prepended until a
* file matches. The first match is used.
*
* You may specify any number of include paths one after another. You
* must specify -I only once:
*
* \code
* csspp ... -I my-scripts alfred-scripts extension-scripts ...
* \endcode
*
* \subsection no_logo --no-logo -- hide the "logo"
*
* This option prevents the "logo" comment from being added at the end
* of the output.
*
* \subsection output --output or -o -- specify the output
*
* This option may be used to specify a filename used to save the
* output of the compiler. By default the output is written to
* stdout.
*
* You may explicitly use '-' to write the output to stdout.
*
* \code
* csspp --output file.css my-script.scss
* \endcode
*
* \subsection precision --precision or -p -- specify the precision to use with decimal number
*
* The output is written as consice as possible. Only that can cause problems
* with decimal numbers getting written with less precision than you need.
*
* By default decimal numbers are written with 3 decimal numbers after the
* decimal point. You may use the --precision command line option to change
* that default to another value.
*
* \code
* csspp ... --precision 5 ...
* \endcode
*
* Note that numbers such as 3.5 are not written with ending zeroes (i.e.
* 3.50000) even if you increase precision.
*
* \warning
* The percent numbers, which are also decimal numbers, do not take this
* value in account. All percent numbers are always written with 2 decimal
* digits after the decimal point. We may change that behavior in the
* future if someone sees a need for it.
*
* \subsection quiet --quiet or -q -- make the output as quite as possible
*
* By default csspp prints out all messages except debug messages.
*
* This option also turns off informational and warning messages. So in
* effect all that's left are error and fatal error messages.
*
* Note that if you used the --Werror command line options, warning
* are transformed to errors and thus they get printed in your output
* anyway.
*
* \subsection style --style or -s -- define the output style
*
* By default the csspp compiler is expected to compress your CSS data
* as much as possible (i.e. it removes non-required spaces, delete empty
* rules, avoid new lines, etc.)
*
* The --style options let choose a different output style than the
* compressed style:
*
* \li --style compressed -- this is the default, it outputs files as
* compressed as possible
* \li --style tidy -- this option writes one rule per line, each rule is
* as compressed as possible
* \li --compact -- this option writes one declaration per line, making it
* a lot easier to edit if you were to do such a thing; this output is
* already quite gentle on humans and can easily be used for debug purposes
* \li expanded -- this option prints everything as neatly as possible
* for human consumption; the output uses many newlines and indentation
* for declarations
*
* The best to see how each style really looks like is for you to test
* with a large existing CSS file and check the output of csspp against
* that file.
*
* For example, you could use the \c expanded format before reading a
* file you found on a website as in:
*
* \code
* csspp --style expanded compressed.css
* \endcode
*
* \subsection version --version -- print out the version and exit
*
* This command line option prints out the version of the csspp compiler
* in stdout and then exits.
*
* \subsection warnings-to-errors --Werror -- transform warnings into errors
*
* The --Werror requests the compiler to generate errors whenever
* a warning message was to be printed. This also has the side effect
* of incrementing the error counter by one each time a warning is
* found. Note that as a result the warning counter will always
* remains zero nin this case.
*
* \note
* You may want to note that this option uses two dashes (--) to specify.
* With GNU C/C++, the command line accepts -Werror, with a single dash.
*
* \subsection command-line-filenames Input files
*
* Other parameters specified on the command line, or parameters defined
* after a "--", are taken as .scss filenames. The "--" is mandatory if
* you have a preceeding argument that accepts multiple values like the
* --args and -I options.
*
* \code
* // no need for "--" in this case:
* csspp -I scripts -p 2 my-script.scss
*
* // "--" required in this case:
* csspp -p 2 -I scripts -- my-script.scss
* \endcode
*/
// csspp
//
#include <csspp/assembler.h>
#include <csspp/compiler.h>
#include <csspp/exception.h>
#include <csspp/parser.h>
// advgetopt
//
#include <advgetopt/advgetopt.h>
#include <advgetopt/exception.h>
// boost
//
#include <boost/preprocessor/stringize.hpp>
// C++
//
#include <cstdlib>
#include <fstream>
#include <iostream>
// C
//
#include <unistd.h>
// last include
//
#include <snapdev/poison.h>
namespace
{
void free_char(char * ptr)
{
free(ptr);
}
// TODO: add support for configuration files & the variable
constexpr advgetopt::option g_options[] =
{
advgetopt::define_option(
advgetopt::Name("args")
, advgetopt::ShortName('a')
, advgetopt::Flags(advgetopt::command_flags<
advgetopt::GETOPT_FLAG_REQUIRED
, advgetopt::GETOPT_FLAG_MULTIPLE>())
, nullptr
, "define values in the $_csspp_args variable map"
, nullptr
),
advgetopt::define_option(
advgetopt::Name("debug")
, advgetopt::ShortName('d')
, advgetopt::Flags(advgetopt::standalone_command_flags<>())
, advgetopt::Help("show all messages, including @debug messages")
),
advgetopt::define_option(
advgetopt::Name("include")
, advgetopt::ShortName('I')
, advgetopt::Flags(advgetopt::command_flags<
advgetopt::GETOPT_FLAG_REQUIRED
, advgetopt::GETOPT_FLAG_MULTIPLE>())
, advgetopt::Help("specify one or more paths to various user defined CSS files; \"-\" to clear the list (i.e. \"-I -\")")
),
advgetopt::define_option(
advgetopt::Name("no-logo")
, advgetopt::ShortName('\0')
, advgetopt::Flags(advgetopt::standalone_command_flags<>())
, advgetopt::Help("prevent the \"logo\" from appearing in the output file")
),
advgetopt::define_option(
advgetopt::Name("empty-on-undefined-variable")
, advgetopt::ShortName('\0')
, advgetopt::Flags(advgetopt::standalone_command_flags<>())
, advgetopt::Help("if accessing an undefined variable, return an empty string, otherwise generate an error.")
),
advgetopt::define_option(
advgetopt::Name("output")
, advgetopt::ShortName('o')
, advgetopt::Flags(advgetopt::command_flags<
advgetopt::GETOPT_FLAG_REQUIRED>())
, advgetopt::Help("save the results in the specified file if specified; otherwise send output to stdout.")
),
advgetopt::define_option(
advgetopt::Name("precision")
, advgetopt::ShortName('p')
, advgetopt::Flags(advgetopt::command_flags<
advgetopt::GETOPT_FLAG_REQUIRED>())
, advgetopt::Help("define the number of digits to use after the decimal point, defaults to 3; note that for percent values, the precision is always 2.")
),
advgetopt::define_option(
advgetopt::Name("quiet")
, advgetopt::ShortName('q')
, advgetopt::Flags(advgetopt::standalone_command_flags<>())
, advgetopt::Help("suppress @info and @warning messages.")
),
advgetopt::define_option(
advgetopt::Name("style")
, advgetopt::ShortName('s')
, advgetopt::Flags(advgetopt::command_flags<
advgetopt::GETOPT_FLAG_REQUIRED>())
, advgetopt::Help("output style: compressed, tidy, compact, expanded.")
),
advgetopt::define_option(
advgetopt::Name("Werror")
, advgetopt::Flags(advgetopt::standalone_command_flags<>())
, advgetopt::Help("make warnings count as errors.")
),
advgetopt::define_option(
advgetopt::Name("--")
, advgetopt::Flags(advgetopt::command_flags<
advgetopt::GETOPT_FLAG_MULTIPLE
, advgetopt::GETOPT_FLAG_DEFAULT_OPTION
, advgetopt::GETOPT_FLAG_SHOW_USAGE_ON_ERROR>())
, advgetopt::Help("[file.css ...]; use stdin if no filename specified.")
),
advgetopt::end_options()
};
// TODO: once we have stdc++20, remove all defaults
#pragma GCC diagnostic ignored "-Wpedantic"
advgetopt::options_environment const g_options_environment =
{
.f_project_name = "csspp",
.f_group_name = nullptr,
.f_options = g_options,
.f_options_files_directory = nullptr,
.f_environment_variable_name = "CSSPPFLAGS",
.f_environment_variable_intro = nullptr,
.f_section_variables_name = nullptr,
.f_configuration_files = nullptr,
.f_configuration_filename = nullptr,
.f_configuration_directories = nullptr,
.f_environment_flags = advgetopt::GETOPT_ENVIRONMENT_FLAG_PROCESS_SYSTEM_PARAMETERS,
.f_help_header = "Usage: %p [-<opt>] [file.css ...] [-o out.css]\n"
"where -<opt> is one or more of:",
.f_help_footer = "%c",
.f_version = CSSPP_VERSION,
.f_license = "GNU GPL v2",
.f_copyright = "Copyright (c) 2015-"
BOOST_PP_STRINGIZE(UTC_BUILD_YEAR)
" by Made to Order Software Corporation -- All Rights Reserved",
//.f_build_date = UTC_BUILD_DATE,
//.f_build_time = UTC_BUILD_TIME
};
class pp
{
public:
pp(int argc, char * argv[]);
int compile();
private:
advgetopt::getopt f_opt;
int f_precision = 3;
};
pp::pp(int argc, char * argv[])
: f_opt(g_options_environment, argc, argv)
{
if(f_opt.is_defined("quiet"))
{
csspp::error::instance().set_hide_all(true);
}
if(f_opt.is_defined("debug"))
{
csspp::error::instance().set_show_debug(true);
}
if(f_opt.is_defined("Werror"))
{
csspp::error::instance().set_count_warnings_as_errors(true);
}
if(f_opt.is_defined("precision"))
{
f_precision = f_opt.get_long("precision");
}
}
int pp::compile()
{
csspp::lexer::pointer_t l;
csspp::position::pointer_t pos;
std::unique_ptr<std::stringstream> ss;
csspp::safe_precision_t safe_precision(f_precision);
if(f_opt.is_defined("--"))
{
// one or more filename specified
int const arg_count(f_opt.size("--"));
if(arg_count == 1
&& f_opt.get_string("--") == "-")
{
// user asked for stdin
pos.reset(new csspp::position("-"));
l.reset(new csspp::lexer(std::cin, *pos));
}
else
{
std::unique_ptr<char, void (*)(char *)> cwd(get_current_dir_name(), free_char);
ss.reset(new std::stringstream);
pos.reset(new csspp::position("csspp.css"));
for(int idx(0); idx < arg_count; ++idx)
{
// full paths so the -I have no effects on those files
std::string filename(f_opt.get_string("--", idx));
if(filename.empty())
{
csspp::error::instance() << *pos
<< "You cannot include a file with an empty name."
<< csspp::error_mode_t::ERROR_WARNING;
return 1;
}
if(filename == "-")
{
csspp::error::instance() << *pos
<< "You cannot currently mix files and stdin. You may use @import \"filename\"; in your stdin data though."
<< csspp::error_mode_t::ERROR_WARNING;
return 1;
}
if(filename[0] == '/')
{
// already absolute
*ss << "@import \"" << filename << "\";\n";
}
else
{
// make absolute so we do not need to have a "." path
*ss << "@import \"" << cwd.get() << "/" << filename << "\";\n";
}
}
l.reset(new csspp::lexer(*ss, *pos));
}
}
else
{
// default to stdin
pos.reset(new csspp::position("-"));
l.reset(new csspp::lexer(std::cin, *pos));
}
// run the lexer and parser
csspp::error_happened_t error_tracker;
csspp::parser p(l);
csspp::node::pointer_t root(p.stylesheet());
if(error_tracker.error_happened())
{
return 1;
}
csspp::node::pointer_t csspp_args(new csspp::node(csspp::node_type_t::LIST, root->get_position()));
csspp::node::pointer_t args_var(new csspp::node(csspp::node_type_t::VARIABLE, root->get_position()));
args_var->set_string("_csspp_args");
csspp::node::pointer_t wrapper(new csspp::node(csspp::node_type_t::LIST, root->get_position()));
csspp::node::pointer_t array(new csspp::node(csspp::node_type_t::ARRAY, root->get_position()));
wrapper->add_child(array);
csspp_args->add_child(args_var);
csspp_args->add_child(wrapper);
if(f_opt.is_defined("args"))
{
int const count(f_opt.size("args"));
for(int idx(0); idx < count; ++idx)
{
csspp::node::pointer_t arg(new csspp::node(csspp::node_type_t::STRING, root->get_position()));
arg->set_string(f_opt.get_string("args", idx));
array->add_child(arg);
}
}
root->set_variable("_csspp_args", csspp_args);
// run the compiler
csspp::compiler c;
c.set_root(root);
c.set_date_time_variables(time(nullptr));
// add paths to the compiler (i.e. for the user and system @imports)
if(f_opt.is_defined("include"))
{
std::size_t const count(f_opt.size("include"));
for(std::size_t idx(0); idx < count; ++idx)
{
std::string const path(f_opt.get_string("include", idx));
if(path == "-")
{
c.clear_paths();
}
else
{
c.add_path(path);
}
}
}
if(f_opt.is_defined("no-logo"))
{
c.set_no_logo();
}
if(f_opt.is_defined("empty-on-undefined-variable"))
{
c.set_empty_on_undefined_variable(true);
}
c.compile(false);
if(error_tracker.error_happened())
{
return 1;
}
csspp::output_mode_t output_mode(csspp::output_mode_t::COMPRESSED);
if(f_opt.is_defined("style"))
{
std::string const mode(f_opt.get_string("style"));
if(mode == "compressed")
{
output_mode = csspp::output_mode_t::COMPRESSED;
}
else if(mode == "tidy")
{
output_mode = csspp::output_mode_t::TIDY;
}
else if(mode == "compact")
{
output_mode = csspp::output_mode_t::COMPACT;
}
else if(mode == "expanded")
{
output_mode = csspp::output_mode_t::EXPANDED;
}
else
{
csspp::error::instance() << root->get_position()
<< "The output mode \""
<< mode
<< "\" is not supported. Try one of: compressed, tidy, compact, expanded instead."
<< csspp::error_mode_t::ERROR_WARNING;
return 1;
}
}
std::ostream * out(nullptr);
bool user_output(false);
std::string output_filename;
if(f_opt.is_defined("output"))
{
output_filename = f_opt.get_string("output");
user_output = output_filename != "-";
}
if(user_output)
{
out = new std::ofstream(output_filename);
}
else
{
out = &std::cout;
}
csspp::assembler a(*out);
a.output(c.get_root(), output_mode);
if(user_output)
{
delete out;
}
if(error_tracker.error_happened())
{
// this should be rare as the assembler generally does not generate
// errors (it may throw though.)
return 1;
}
return 0;
}
} // no name namespace
int main(int argc, char *argv[])
{
try
{
pp preprocessor(argc, argv);
return preprocessor.compile();
}
catch(advgetopt::getopt_exit const & except)
{
return except.code();
}
catch(csspp::csspp_exception_exit const & e)
{
// something went wrong in the library
return e.exit_code();
}
catch(csspp::csspp_exception_logic const & e)
{
std::cerr << "fatal error: a logic exception, which should NEVER occur, occurred: " << e.what() << std::endl;
exit(1);
}
catch(csspp::csspp_exception_overflow const & e)
{
std::cerr << "fatal error: an overflow exception occurred: " << e.what() << std::endl;
exit(1);
}
catch(csspp::csspp_exception_runtime const & e)
{
std::cerr << "fatal error: a runtime exception occurred: " << e.what() << std::endl;
exit(1);
}
catch(advgetopt::getopt_undefined const & e)
{
std::cerr << "fatal error: an undefined exception occurred because of your command line: " << e.what() << std::endl;
exit(1);
}
catch(advgetopt::getopt_invalid const & e)
{
std::cerr << "fatal error: there is an error on your command line, an exception occurred: " << e.what() << std::endl;
exit(1);
}
catch(advgetopt::getopt_invalid_default const & e)
{
std::cerr << "fatal error: there is an error on your command line, you used a parameter without a value and there is no default. The exception says: " << e.what() << std::endl;
exit(1);
}
}
// Local Variables:
// mode: cpp
// indent-tabs-mode: nil
// c-basic-offset: 4
// tab-width: 4
// End:
// vim: ts=4 sw=4 et