#!/usr/bin/env python

import os
import sys
import fnmatch
from subprocess import *
from difflib import *

#
# PARAMETERS
#

ROOT = "test"
PATTERN = "*.ml"

SYNTAX = True # Test syntax examples
TYPING = True # Test typing examples
EXEC = True   # Exec examples
AUTO_VERIFY = True # Make a diff between ocaml results and spim results

APP_PARTIELLE = False # Accepte l'application partielle des foncteurs

FAST = False   # Do not accept files in slow list (!!)

slow = ["test/exec2/recT.ml","test/exec/mandelbrot.ml"]

#
# Program
#

if FAST==False :
	slow = []

filepaths = []
for dirpath, dirnames, filenames in os.walk (ROOT):
	filepaths.extend (
		os.path.join (dirpath, f) for f in fnmatch.filter (filenames, PATTERN)
	)

if SYNTAX :
	print("")
	print("##### Syntax #####")
	print("")

	for f in filepaths :
		if f[5:11]=="syntax" :
			print("----- %s -----" % f)
			os.system("./mimo -parse-only %s" % f)
			print(" ")


if TYPING :
	print("")
	print("##### Typing #####")
	print("")

	for f in filepaths :
		if f[5:11]=="typing" :
			print("----- %s -----" % f)
			if APP_PARTIELLE :
				os.system("./mimo -app-partielle -type-only %s" % f)
			else :
				os.system("./mimo -type-only %s" % f)
			print(" ")

if EXEC :
	print("")
	print("##### Simulation #####")
	print("")

	if AUTO_VERIFY :
		for f in filepaths :
			if f[5:9]=="exec" and f!="test/exec2/read_int.ml" and f not in slow :
				print("----- %s -----" % f)
				arg=[]
				if APP_PARTIELLE :
					arg = ["-app-partielle"]
				p = Popen(["./mimo"]+arg+[f], stdout=PIPE,stderr=PIPE)
				output = p.communicate()[1]
				if p.returncode!=0 :
					print("*** ERREUR MIMO !!!")
					print(output)
					continue
				p = Popen(["spim","-file","%s.s" % f[:-3]], stdout=PIPE)
				output1 = p.communicate()[0]
				p = Popen(["ocaml","%s.ml" % f[:-3]], stdout=PIPE)
				output2 = p.communicate()[0]
				output1 = output1.split("\n",5)[-1]
				d = unified_diff(output1.splitlines(1), output2.splitlines(2))
				if ''.join(d)=='' :
					print("*** OK !")
				else :
					print("*** ERREUR !!!")
					print("--- Spim result")
					print(output1)
					print("--- Diff")
					print(''.join(d))
	else :
		for f in filepaths :
			if f[5:9]=="exec" and f not in slow :
				print("----- %s -----" % f)
				if APP_PARTIELLE :
					os.system("./mimo -app-partielle %s" %f)
				else :
					os.system("./mimo %s" %f)
				os.system("spim -file %s.s" % f[:-3])
				print(" ")


