summaryrefslogtreecommitdiff
path: root/src/index.ts
blob: d162465edd27fdafea316e716f55455ba117e8a4 (plain)
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
import { args, type Args } from '@/args';
import { join } from 'path';
import { watch } from 'fs/promises';
import { generateParser, GRAMMAR_FILE, GENERATED_PARSER } from '@/parser';
import {
  ConsoleTracingLogger,
  type LogLevel,
  type TracingLogger,
} from '@/utils';
import { doRepl } from './repl';

const LOG_LEVELS: LogLevel[] = ['info', 'warn', 'error'];

const devMode = async (logger: TracingLogger) => {
  logger.info('Watching for changes in parser...');

  const watcher = watch(import.meta.dir, { recursive: true });
  for await (const event of watcher) {
    if (event.filename?.endsWith(GRAMMAR_FILE)) {
      const grammarFile = join(import.meta.dir, event.filename);
      const outputFile = join(
        import.meta.dir,
        event.filename.replace(GRAMMAR_FILE, GENERATED_PARSER),
      );
      logger.info(
        `Generating parser at Location=(${grammarFile}) to Source=(${outputFile})...`,
      );
      generateParser(grammarFile, outputFile);
    }
  }
};

export const main = async (args: Args) => {
  if (args.devMode) {
    LOG_LEVELS.push('debug');
  }

  const logger = new ConsoleTracingLogger('main', LOG_LEVELS);

  if (args.devMode) {
    logger.info('Starting in dev mode...');
    await devMode(logger);
  }

  if (args.repl) {
    await doRepl(logger);
  }
  return 0;
};

main(args).then(code => process.exit(code));