A stylesheet language written in TypeScript that compiles to CSS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

moss.ts 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #!/usr/bin/env node
  2. import * as minimist from 'minimist';
  3. import * as fs from 'fs';
  4. import * as path from 'path';
  5. import Compiler from './compiler';
  6. import { isError } from './error';
  7. import { EnvError } from './env';
  8. import Lexer, { LexerError } from './lexer';
  9. import Parser, { ParserError } from './parser';
  10. // import { inspect } from 'util';
  11. // const print = (obj: any) => {
  12. // console.log(inspect(obj, { depth: null }));
  13. // };
  14. const rawArgs = minimist(process.argv.slice(2));
  15. const args = {
  16. eval: rawArgs.e || rawArgs.eval,
  17. file: rawArgs.f || rawArgs.file,
  18. help: rawArgs.h || rawArgs.help,
  19. output: rawArgs.o || rawArgs.output,
  20. pretty: rawArgs.p || rawArgs.pretty,
  21. };
  22. const helpText = `Usage: moss [options]
  23. -e, --eval <source> Evaluate a string of source code
  24. -f, --file <path> Evaluate a file containing source code
  25. -h, --help Print this message
  26. -o, --output <path> Write output to a file
  27. -p, --pretty Pretty print the output`;
  28. const moss = (
  29. source: string,
  30. file?: string
  31. ): LexerError | ParserError | EnvError | string => {
  32. const lexer = new Lexer(source, file);
  33. const tokens = lexer.scan();
  34. if (tokens instanceof LexerError) {
  35. return tokens;
  36. } else {
  37. const parser = new Parser(tokens);
  38. const tree = parser.parse();
  39. if (tree instanceof ParserError) {
  40. return tree;
  41. } else {
  42. const compiler = new Compiler(tree, { prettyPrint: args.pretty });
  43. return compiler.compile();
  44. }
  45. }
  46. };
  47. const run = () => {
  48. if (args.help) {
  49. return helpText;
  50. } else if (args.file) {
  51. const filepath = path.join(process.cwd(), args.file);
  52. if (filepath !== null) {
  53. const source = fs.readFileSync(filepath, 'utf-8');
  54. return moss(source, args.file);
  55. }
  56. return '';
  57. } else if (args.eval) {
  58. return moss(args.eval);
  59. }
  60. return helpText;
  61. };
  62. const output = run();
  63. if (isError(output)) {
  64. const moduleAndLine = `${output.module ? output.module : '-e'}:${
  65. output.line
  66. }`;
  67. console.log(`Error ${moduleAndLine}
  68. ${output.message}`);
  69. } else {
  70. if (output.length) {
  71. if (args.output) {
  72. fs.writeFileSync(path.join(process.cwd(), args.output), output);
  73. } else {
  74. console.log(output);
  75. }
  76. }
  77. }