#!/usr/bin/env python3
"""Check both cores using the built-in Yosys reader, or optionally Slang."""
import argparse
import os
from pathlib import Path
import subprocess


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--frontend', choices=['verilog', 'slang'], default='verilog')
    args = parser.parse_args()
    exercise = Path(__file__).resolve().parents[1]
    build = exercise / 'build/synthesis'
    build.mkdir(parents=True, exist_ok=True)
    sources = sorted((exercise / 'rtl').glob('*.sv'))
    sources += sorted((exercise / 'models').glob('*.sv'))
    # Fixed relative source names also work when the exercise directory has spaces.
    filenames = ' '.join(p.relative_to(exercise).as_posix() for p in sources)
    yosys = os.environ.get('YOSYS', 'yosys')

    for top in ['basic_display', 'basic_display_chips']:
        read = (f'read_slang --top {top}' if args.frontend == 'slang'
                else 'read_verilog -sv')
        commands = (f'{read} {filenames}; '
                    f'synth -top {top} -flatten; check -assert; stat')
        log = build / f'{top}.log'
        with log.open('w') as output:
            plugin = ['-m', 'slang'] if args.frontend == 'slang' else []
            result = subprocess.run([yosys, '-Q'] + plugin + ['-p', commands],
                                    cwd=exercise, stdout=output, stderr=subprocess.STDOUT)
        if result.returncode:
            print(log.read_text())
            raise SystemExit(result.returncode)
        print(f'PASS synthesis: {top} (Yosys, {args.frontend} frontend); {log}')


if __name__ == '__main__':
    main()
