testproperties.icl 15.7 KB
Newer Older
Camil Staps's avatar
Camil Staps committed
1
module testproperties
Camil Staps's avatar
Camil Staps committed
2 3 4

import _SystemArray
import StdBool
5
import StdEnum
Camil Staps's avatar
Camil Staps committed
6
import StdFile
Camil Staps's avatar
Camil Staps committed
7
from StdFunc import flip, o
8
import StdMisc
Camil Staps's avatar
Camil Staps committed
9 10 11 12
import StdOrdList
import StdString
import StdTuple

Camil Staps's avatar
Camil Staps committed
13 14
import Control.Applicative
from Control.Monad import class Monad(..), sequence, =<<, foldM
Camil Staps's avatar
Camil Staps committed
15 16 17 18 19 20 21 22 23 24 25 26
import Data.Error
from Data.Func import $, mapSt, on, `on`, seqSt
import Data.Functor
import Data.List
import Data.Maybe
import Data.Tuple
import System.CommandLine
import System.Directory
import System.Environment
import System.File
import System.FilePath
import System.Options
27
import System.OS
Camil Staps's avatar
Camil Staps committed
28 29
import System.Process
import Text
30
import Text.Language
Camil Staps's avatar
Camil Staps committed
31

32
import Clean.Doc
33 34
import Clean.Parse
import Clean.Parse.Comments
Camil Staps's avatar
Camil Staps committed
35
from Clean.Types import :: Type(Func,Type), :: TypeContext, :: TypeRestriction,
36
	:: TypeVar, :: TVAssignment, :: TypeContext(TypeContext),
Camil Staps's avatar
Camil Staps committed
37 38 39
	allVars
from Clean.Types.Util import instance toString Type, instance == Type,
	assign, assignAll
40 41 42

from syntax import
	:: Ident{id_name},
43 44 45
	:: Module{mod_defs,mod_ident}

import cocl_helper
Camil Staps's avatar
Camil Staps committed
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

:: Options =
	{ directory        :: !FilePath
	, modules          :: ![FilePath]
	, output_directory :: !FilePath
	, output_prefix    :: !String
	, includes         :: ![FilePath]
	, library_includes :: ![String]
	, clean_home       :: !FilePath
	, print_options    :: ![String]
	, test_options     :: ![String]
	, compile          :: !Bool
	, clm_args         :: ![String]
	, run              :: !Bool
	, verbosity        :: !Int
	, color            :: !Bool
	}

defaultOptions :: Options
defaultOptions =
	{ directory        = "."
	, modules          = []
	, output_directory = "."
	, output_prefix    = "_Tests"
	, includes         = []
	, library_includes = ["Gast","Platform"]
	, clean_home       = "/opt/clean"
	, print_options    = []
	, test_options     = []
	, compile          = False
76
	, clm_args         = ["-nt", "-nr"]
Camil Staps's avatar
Camil Staps committed
77 78 79 80 81 82 83 84 85 86 87 88
	, run              = False
	, verbosity        = SUCCESS
	, color            = True
	}

Start w
// Command line
# ([prog:args],w) = getCommandLine w
# (clean_home,w) = appFst (fromMaybe "") $ getEnvironmentVariable "CLEAN_HOME" w
# opts = parseOptions optionDescription args {defaultOptions & clean_home=clean_home}
| isError opts = exit (join "\n" $ fromError opts) {defaultOptions & color=False} w
# opts = fromOk opts
89 90 91
# opts = if (opts.run && isMember "OutputTestEvents" opts.print_options)
	{opts & verbosity=0, clm_args=["-ms":opts.clm_args]}
	opts
Camil Staps's avatar
Camil Staps committed
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
# (modules,w) = case opts.modules of
	[_:_] -> (Ok [opts.Options.directory </> replaceSubString "." {pathSeparator} mod +++ ".dcl" \\ mod <- opts.modules], w)
	[]    -> findModules opts.Options.directory w
| isError modules = exit (snd (fromError modules) +++ " while finding modules") opts w
# w = seqSt (handleModule opts) (fromOk modules) w
= w
where
	optionDescription :: Option Options
	optionDescription = WithHelp True $ Options
		[ Shorthand "-d" "--directory" $ Option
			"--directory"
			(\dir opts -> Ok {Options | opts & directory=dir})
			"DIR"
			"The directory to test modules from (default: .)"
		, Shorthand "-m" "--module" $ Option
			"--module"
			(\mod opts -> Ok {opts & modules=opts.modules ++ [mod]})
			"MOD"
			"Add MOD to the to-test modules -- when no modules are given, all modules from --directory are used"
		, Shorthand "-D" "--output-directory" $ Option
			"--output-directory"
			(\dir opts -> Ok {opts & output_directory=dir})
			"DIR"
			"Use DIR as directory for test modules (default: .)"
		, Shorthand "-p" "--prefix" $ Option
			"--prefix"
			(\p opts -> Ok {opts & output_prefix=p})
			"PREFIX"
			"The prefix for test module names (default: _Tests, i.e., Data.Set goes to _Tests.Data.Set)"
		, Shorthand "-I" "--include" $ Option
			"--include"
			(\dir opts -> Ok {opts & includes=opts.includes ++ [dir]})
			"DIR"
			"Add DIR to the include path"
		, Shorthand "-IL" "--include-library" $ Option
			"--include-library"
			(\lib opts -> Ok {opts & library_includes=opts.library_includes ++ [lib]})
			"LIB"
			"Add CLEAN_HOME/lib/LIB to the include path"
		, Shorthand "-H" "--clean-home" $ Option
			"--clean-home"
			(\h opts -> Ok {opts & clean_home=h})
			"PATH"
			"Set CLEAN_HOME to PATH (used to find libraries)"
		, Shorthand "-P" "--print-option" $ Option
			"--print-option"
			(\po opts -> Ok {opts & print_options=opts.print_options ++ [po]})
			"OPT"
			"Add OPT to the print options (see Gast's PrintOption type)"
		, Shorthand "-T" "--test-option" $ Option
			"--test-option"
			(\po opts -> Ok {opts & test_options=opts.test_options ++ [po]})
			"OPT"
			"Add OPT to the test options (see Gast's Testoption type)"
		, Shorthand "-c" "--compile" $ Flag
			"--compile"
			(\opts -> Ok {opts & compile=True})
			"Compile the tests after generation"
		, Shorthand "-C" "--clm-arg" $ Option
			"--clm-arg"
			(\arg opts -> Ok {opts & clm_args=opts.clm_args ++ [arg]})
			"ARG"
			"Add ARG to the command line arguments for clm"
		, Shorthand "-r" "--run" $ Flag
			"--run"
			(\opts -> Ok {opts & compile=True, run=True})
			"Run the tests after generation (implies --compile)"
		, Shorthand "-v" "--verbose" $ Flag
			"--verbose"
			(\opts -> Ok {opts & verbosity=inc opts.verbosity})
			"Increase verbosity (can be given multiple times)"
		, Shorthand "-q" "--quiet" $ Flag
			"--quiet"
			(\opts -> Ok {opts & verbosity=dec opts.verbosity})
			"Decrease verbosity (can be given multiple times)"
		, Flag "--no-color"
			(\opts -> Ok {opts & color=False})
			"Turn off color in output"
		]

exit :: !String !Options !*World -> *World
exit error opts w = setReturnCode 1 $ output ERROR error opts w

DEBUG   :== 5
SUCCESS :== 4
INFO    :== 3
WARNING :== 2
ERROR   :== 1

output :: !Int !String !Options !*World -> *World
output level s opts w
| level > opts.verbosity = w
# (io,w) = stdio w
= snd $ fclose (io <<< color <<< s <<< newline) w
where
	color
	| opts.color = case level of
		DEBUG   -> "\033[0;36m"
		INFO    -> "\033[0;34m"
		SUCCESS -> "\033[0;32m"
		WARNING -> "\033[0;33m"
		ERROR   -> "\033[0;31m"
	| otherwise = ""

	newline = if opts.color "\033[0m\n" "\n"

findModules :: !FilePath !*World -> *(!MaybeOSError [FilePath], !*World)
findModules dir w
# (files,w) = readDirectory dir w
| isError files = (Error (fromError files), w)
= appFst (fmap flatten o sequence) $ mapSt recurse [fp \\ fp <- fromOk files | not $ isMember fp [".",".."]] w
where
	recurse :: !FilePath !*World -> *(!MaybeOSError [FilePath], !*World)
	recurse fp w
	# fp = dir </> fp
	# (info,w) = getFileInfo fp w
	| isError info = (Error (fromError info), w)
	| (fromOk info).FileInfo.directory = findModules fp w
	| otherwise = (Ok (if (endsWith ".dcl" fp) [fp] []), w)

handleModule :: !Options !FilePath !*World -> *World
handleModule opts fp w
# w = output DEBUG ("Checking " +++ fp +++ "...") opts w
// Find properties
216 217
#! (comments,w) = scanComments fp w
#! (dcl,w) = readModule fp w
218
#! (mod,dcldefs,documentation) = case dcl of
219
	Error _ -> (abort "failed to parse module\n", [], emptyCollectedComments)
220
	Ok (dcl,_) -> (dcl, dcl.mod_defs, case comments of
221 222
		Error _ -> emptyCollectedComments
		Ok comments -> collectComments comments dcl)
223
# (fundefs,instancedefs,typedefs) = get_checkable_definitions documentation dcldefs
224
# moddoc = case parseDoc <$> getComment mod documentation of
225 226
	Just (Right (doc,_)) -> Just doc
	_                    -> Nothing
227
# modname = mod.mod_ident.id_name
Camil Staps's avatar
Camil Staps committed
228 229
# output_modname = opts.output_prefix +++ "." +++ modname
# output_filename = opts.output_directory </> replaceSubString "." {pathSeparator} output_modname +++ ".icl"
Camil Staps's avatar
Camil Staps committed
230
# (nprops,coverage,props) = generatePropertyModule
231
	output_modname modname
Camil Staps's avatar
Camil Staps committed
232 233
	opts.print_options
	opts.test_options
234
	moddoc
235
	fundefs instancedefs typedefs
Camil Staps's avatar
Camil Staps committed
236 237
// Write properties
| nprops == 0 = w
Camil Staps's avatar
Camil Staps committed
238 239 240 241
# w = output INFO
	("Found " +++ pluralisen English nprops "test case" +++
		" in module " +++ modname +++
		"; " <+ entier (coverage * 100.0) <+ "% coverage") opts w
Camil Staps's avatar
Camil Staps committed
242 243 244 245 246 247 248 249 250
# (dir,_) = splitFileName output_filename
# (ok,w) = assertDirectory dir w
| isError ok = exit (snd (fromError ok) <+ " " +++ output_filename) opts w
# (ok,w) = writeFile output_filename props w
| isError ok = exit (fromError ok <+ " " +++ output_filename) opts w
// Compile tests
| not opts.compile = w
# w = output INFO ("Compiling " +++ output_modname +++ "...") opts w
# output_exename = opts.output_directory </> output_modname
251
# (ok,w) = callProcess (IF_WINDOWS "clm.exe" "clm")
Camil Staps's avatar
Camil Staps committed
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
	(opts.clm_args ++
		interleave "-I" [opts.Options.directory:opts.includes] ++
		interleave "-IL" opts.library_includes ++
		["-nr", output_modname, "-o", output_exename]) Nothing w
| isError ok = exit (snd (fromError ok) <+ " during compilation") opts w
| fromOk ok <> 0 = exit "Compilation finished with non-zero exit code" opts w
// Run tests
| not opts.run = w
# w = output INFO ("Running " +++ output_modname +++ "...") opts w
# (ok,w) = callProcess output_exename [] Nothing w
| isError ok = exit (snd (fromError ok) <+ " while running the tests") opts w
| fromOk ok <> 0 = exit "Test finished with non-zero exit code" opts w
= output SUCCESS (output_modname +++ " passed") opts w
where
	assertDirectory :: !FilePath !*World -> *(!MaybeOSError (), !*World)
	assertDirectory "" w = (Ok (), w)
	assertDirectory fp w
	# (ex,w) = fileExists fp w
	| ex = (Ok (), w)
	# (base,_) = splitFileName fp
	# (err,w) = assertDirectory base w
	| isError err = (err, w)
	= createDirectory fp w

	interleave :: a [a] -> [a]
	interleave _ []     = []
	interleave g [x:xs] = [g,x:interleave g xs]

280
generatePropertyModule :: !String !String ![String] ![String] !(Maybe ModuleDoc)
281 282 283
	![(String, FunctionDoc)]
	![(String, InstanceDoc)]
	![(String, TypeDoc)]
284
	-> (!Int, !Real, !String)
285
generatePropertyModule testmodname modname print_options test_options mod_doc fes ies tes
286
	= (n_props, coverage, tests)
Camil Staps's avatar
Camil Staps committed
287
where
Camil Staps's avatar
Camil Staps committed
288
	n_props = length props
289
	coverage = toReal (length (filter (not o isEmpty) propsets)) / toReal (length fes + length ies)
Camil Staps's avatar
Camil Staps committed
290
	tests = join "\n\n"
291
		[ "module " +++ testmodname
292 293 294 295 296 297 298 299 300
		, join "\n" $
			if default_imports
				[ "import Gast, Gast.CommandLine"
				, "from Testing.TestEvents import :: TestLocation{..}"
				, "from StdString import instance toString {#Char}"
				, "import Control.GenBimap"
				, "import " +++ modname
				]
				[]
Camil Staps's avatar
Camil Staps committed
301 302
		, bootstrap
		, generators_string
303
		, invariants
Camil Staps's avatar
Camil Staps committed
304 305 306 307
		, start
		: [gp.gp_implementation \\ gp <- props]
		]

308 309 310 311 312
	propsets = handle fes ++ handle ies
	where
		handle :: ([(String,doc)] -> [[GeneratedProperty]]) | docPreconditions, docProperties, docPropertyTestWith doc
		handle = map (uncurry $ generateProperties modname pvis generators)
		pvis = fromMaybe [] $ docPropertyTestWith <$> mod_doc
Camil Staps's avatar
Camil Staps committed
313
	props = flatten propsets
Camil Staps's avatar
Camil Staps committed
314

315 316 317 318 319 320 321
	(bootstrap,default_imports) = case docPropertyBootstrap =<< mod_doc of
		Nothing ->
			("",True)
		Just bs=:{bootstrap_content=MultiLine content} ->
			( content
			, not bs.bootstrap_without_default_imports
			)
322

323 324 325 326
	invariants = join "\n\n" $ concatMap (\(_,td) -> map invariant td.TypeDoc.invariants) tes
	where
		invariant :: Property -> String
		invariant (ForAll name args impl) =
327
			name +++ " :: " <+ Func (map noContext argtypes) (Type "Property" []) (TypeContext (concatMap context argtypes)) <+ "\n" +++
328 329 330 331 332
			name +++ concat [" " +++ a \\ (a,_) <- args] +++ " =\n\t" +++
			replaceSubString "\n" "\n\t" impl
		where
			noContext (Func [] t _) = t
			noContext t = t
333
			context (Func [] _ (TypeContext c)) = c
334 335 336 337
			context _ = []

			argtypes = map snd args

338
	generators = [("gast_generator_" <+ i,ptg) \\ i <- [0..] & ptg <- fromMaybe [] (docPropertyTestGenerators <$> mod_doc)]
339 340 341
	generators_string = join "\n\n" $ map makeGenerator $ generators
	where
		makeGenerator :: NamedTestGenerator -> String
342 343 344 345 346 347 348
		makeGenerator (name, ptg) = case ptg of
			PTG_Function t imp -> mkgen name t (imp % (3, size imp-1))
			PTG_List t imp     -> mkgen name (Type "_List" [t]) (" = " +++ imp)

		mkgen name type imp = join "\n"
			[ name +++ " :: " <+ type
			, name +++ imp
349
			]
Camil Staps's avatar
Camil Staps committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363

	start = join "\n\t"
		[ "Start w = exposeProperties"
		, "[" +++ join "," print_options +++ "]"
		, "[" +++ join "," test_options +++ "]"
		, "[ EP " +++ join "\n\t, EP " [gp.gp_name \\ gp <- props]
		, "] w"
		]

:: GeneratedProperty =
	{ gp_name           :: !String
	, gp_implementation :: !String
	}

364 365 366
:: NamedTestGenerator :== (String, PropertyTestGenerator)

:: GeneratedArgument =
367 368 369 370
	{ ga_arg   :: !String // the name of the argument as stated
	, ga_names :: ![String] // generated argument names
	, ga_expr  :: !String // expression (for PTG_Function)
	, ga_ptg   :: !Maybe NamedTestGenerator // the generator used
371
	}
372

373 374
generateProperties :: !String ![PropertyVarInstantiation] ![NamedTestGenerator] !String
	!doc -> [GeneratedProperty] | docPreconditions, docProperties, docPropertyTestWith doc
375
generateProperties modname pvis generators fname doc =
376 377
	[gen i fname (docPreconditions doc) p config
		\\ p <- docProperties doc
378
		, config <- configurationsForProperty p (pvis ++ docPropertyTestWith doc)
Camil Staps's avatar
Camil Staps committed
379 380
		& i <- [1..]]
where
381 382 383 384 385 386 387 388 389 390
	configurationsForProperty :: !Property ![PropertyVarInstantiation] -> [[(String,Type)]]
	configurationsForProperty (ForAll _ ts _) pvis =
		case [vi \\ PropertyVarInstantiation vi=:(v,_) <- pvis | isMember v allvs] of
			[]  -> [[]]
			vis -> configurations $ groupInstantiations vis
	where
		allvs = concatMap (allVars o snd) ts

		groupInstantiations :: [(String,Type)] -> [[(String,Type)]]
		groupInstantiations pvis = groupBy ((==) `on` fst) $ sortBy ((<) `on` fst) pvis
Camil Staps's avatar
Camil Staps committed
391

392 393 394
		configurations :: [[(String,Type)]] -> [[(String,Type)]]
		configurations [vis:viss] = [[vi`:vis`] \\ vi` <- vis, vis` <- configurations viss]
		configurations [] = [[]]
Camil Staps's avatar
Camil Staps committed
395

Camil Staps's avatar
Camil Staps committed
396 397
	gen :: !Int !String ![String] !Property ![(String,Type)] -> GeneratedProperty
	gen i fname preconditions (ForAll name ts imp) vis =
398
		{ gp_name = tname
Camil Staps's avatar
Camil Staps committed
399
		, gp_implementation = join "\n"
400
			[ tname +++ " :: Property"
401
			, tname +++ " = location_and_name {moduleName=Just \"" +++ modname +++ "\"} \"" +++ fname +++ ": " +++ name` +++ "\""
402
			, "\t(" +++ join " " lambdas +++ join " " [name`` +++ "`":[ga.ga_expr \\ ga <- gas]] +++ {')' \\ _ <- lambdas} +++ ")"
403
			, "where"
404
			, "\t" +++ name`` +++ "` :: " +++ toString type`
405
			, "\t" +++ join " " [name`` +++ "`":[ga.ga_arg \\ ga <- gas]] +++ " = (True" +++ concat [" /\\ precondition_" <+ i <+ "_" \\ i <- [1..] & pre <- preconditions] +++ ") ==> actual_property_"
Camil Staps's avatar
Camil Staps committed
406
			, "\twhere"
407 408
			, "\t\tactual_property_ = " +++ replaceSubString "\n" "\n\t\t\t" imp
			: ["\t\tprecondition_" <+ i <+ "_ = " +++ s \\ s <- preconditions & i <- [1..]]
Camil Staps's avatar
Camil Staps committed
409 410 411
			]
		}
	where
412 413
		tname = concat ["p",fixname fname,"_",fixname name,"_",toString i]
		name`` = "p" +++ fixname name`
Camil Staps's avatar
Camil Staps committed
414
		name` = if (i == 1) name (name +++ "_" +++ toString i)
415
		type` = fromJust $ assignAll vis $ Func (map snd ts) (Type "Property" []) (TypeContext [])
416

417 418 419 420
		gas = map resolveGenerators ts
		where
			resolveGenerators :: (String,Type) -> GeneratedArgument
			resolveGenerators (arg,t) =
421 422 423 424 425 426
				case [(n,is,ntg) \\ ntg=:(n,PTG_Function (Func is r _) _) <- generators | r == t] of
					[(n,is,ntg):_] ->
						{ ga_arg   = arg
						, ga_names = args
						, ga_expr  = "(" +++ join " " [n:args] +++ ")"
						, ga_ptg   = Just ntg
427
						}
428
						with args = [arg +++ "`" +++ toString i \\ _ <- is & i <- [0..]]
429 430
					[] -> case [(n,ntg) \\ ntg=:(n,PTG_List r _) <- generators | r == t] of
						[(n,ntg):_] ->
431 432 433 434
							{ ga_arg   = arg
							, ga_names = [arg]
							, ga_expr  = arg
							, ga_ptg   = Just ntg
435 436
							}
						[] ->
437 438 439 440
							{ ga_arg   = arg
							, ga_names = [arg]
							, ga_expr  = arg
							, ga_ptg   = Nothing
441
							}
442

443 444 445 446 447
		lambdas = map makeLambda gas
		where
			makeLambda :: GeneratedArgument -> String
			makeLambda ga = case ga.ga_ptg of
				Just (gen,PTG_List _ _)
448 449
					-> "ForEach " +++ gen +++ " (\\" +++ ga.ga_arg +++ "->"
					-> "\\" +++ join " " ga.ga_names +++ "->("
450 451

		fixname :: String -> String
452 453 454 455 456 457 458 459 460 461 462 463
		fixname s = fix (size s-1) (createArray (size s*2) '\0')
		where
			fix :: !Int !*String -> .String
			fix i arr
				| i<0
					= arr
					# ci = toInt s.[i]
					# arr = {arr & [i*2]=hex (ci >> 4), [i*2+1]=hex (ci bitand 0xf)}
					= fix (i-1) arr

			hex :: !Int -> Char
			hex i = "0123456789abcdef".[i]