Source

GL Profile Suite / tests / codegen.lua

Full commit
   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
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  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
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 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
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019

local gen = require("generate")

local codegen = {}
codegen._suites = {}

local function assert_suite(operation)
	assert(codegen._curr, "Attempt to " .. operation .. " when a suite is not current");
	assert(codegen._curr._type == "suite", "Attempt to " .. operation .. " when a test is current");
end

local function assert_test(operation)
	assert(codegen._curr, "Attempt to " .. operation .. " when a test is not current");
	assert(codegen._curr._type == "test", "Attempt to " .. operation .. " when a suite is current");
end

local function get_suite_or_assert(operation)
	assert(codegen._curr, "Attempt to " .. operation .. " when a suite is not current");
	if(codegen._curr._type == "test") then
		return codegen._curr._suite
	else
		return codegen._curr
	end
end

local function assert_enum(enumValues, testValue, operation)
	assert(enumValues[testValue], testValue .. " is not a legal " .. operation .. " value")
end

--Used for setting enumerated flags into a list of flags.
local function set_flags(flagDataList, flagEnum, newFlags, operation)
	if(type(newFlags) == "string") then
		print(newFlags)
		assert_enum(flagEnum, newFlags, operation)
		flagDataList[newFlags] = true
	elseif(type(newFlags) == "table") then
		for _,flag in ipairs(newFlags) do
			assert_enum(flagEnum, flag, operation)
			flagDataList[flag] = true
		end
	else
		assert(nil, "You must provide a string or a list of fields when trying to set the " .. operation .. " flags")
	end
end

--Use the current directory as the base directory for all file operations.
--Suites must have a `_type` field equal to "suite".
local function create_new_suite(name)
	local suite = {}
	suite._type = "suite"
	suite._base_dir = os.getcwd()
	suite._tests = {}
	
	suite.name = name
	suite.desc = "No Description"
	suite.params = {}
	suite.timings = {}
	suite.includes = {}
	suite.variables = {}
	suite.initialize = {}
	return suite
end

--Use the current directory as the base directory for all file operations.
--Tests must have a `_type` field equal to "test".
--Test has its current suite as the `_suite` field.
local function create_new_test(name)
	local test = {}
	test._type = "test"
	test._suite = codegen._curr
	test._base_dir = os.getcwd()
	
	test.name = name
	test.desc = "No Description"
	test.flags = {}
	test.render_flags = {}
	test.includes = {}
	test.variables = {}
	test.initialize = {}
	test.execinit = {}
	test.exec = {}
	test.execfinal = {}
	return test
end

-------------------------------
-- Suite interface functions.

--Interface functions for doing codegen work.
function codegen.suite(name)
	name = tostring(name)
	assert(name, "Name of a suite must be a string")
	
	if(not codegen._suites[name]) then
		codegen._suites[name] = create_new_suite(name)
	end
	
	codegen._curr = codegen._suites[name]
	return codegen._curr
end

--Sets the discription for a suite or test.
function codegen.description(desc)
	assert(codegen._curr, "Attempt to set a description for a suite/test that doesn't exist.")
	
	codegen._curr.desc = tostring(desc)
end

codegen.desc = codegen.description

function codegen.range(first, count)
	assert(count > 0, "Ranges must have a size > 0.")
	local rng = {}
	rng.first = tonumber(first)
	rng.count = tonumber(count)
	rng._rng = "range"
	return rng
end

function codegen.half_open_range(first, last)
	assert(last > first, "Half-open ranges must have last be larger than first")
	return codegen.range(first, last - first)
end

function codegen.closed_range(first, last)
	assert(last >= first, "Closed ranges must have last be larger than first")
	return codegen.range(first, last - first + 1)
end

function codegen.params(paramList)
	assert_suite("set parameters")
	assert(type(paramList) == "table", "Parameters are a table of named values")
	
	for k,v in pairs(paramList) do
		assert(type(k) == "string", "Parameter names must be strings.")
		assert(k:match("^[%a%_][%w%_]*$"), "Parameter names must be valid Lua and C++ identifiers.")
		--TODO: verify that v is a valid number range or series of numbers.
		codegen._curr.params[k] = v;
	end
end

local legalTimings = {cpu_time = true, gpu_time = true, gpu_latency = true}

function codegen.timings(timings)
	assert_suite("set timings")
	
	set_flags(codegen._curr.timings, legalTimings, timings, "timings")
end

function codegen.executions(numExecutions)
	assert_suite("set default execution count")
	numExecutions = tonumber(numExecutions)
	assert(type(numExecutions) == "number")
	
	codegen._curr.executions = math.floor(numExecutions)
end

local function InsertTableOfStrings(output, input, funcName)
	if(type(input) == "string") then
		output[#output + 1] = input
	elseif(type(input) == "table") then
		for _,v in ipairs(input) do
			output[#output + 1] = v
		end
	else
		assert(nil, funcName .. " takes a string or a table of strings.");
	end

end

function codegen.includes(includes)
	assert(codegen._curr, "Attempt to set includes for a suite/test that doesn't exist.")
	
	InsertTableOfStrings(codegen._curr.includes, includes, "includes")
end

function codegen.variables(vars)
	assert(codegen._curr, "Attempt to set variables for a suite/test that doesn't exist.")

	for varname, vartype in pairs(vars) do
		codegen._curr.variables[varname] = vartype
	end
end

codegen.vars = codegen.variables

local function AddCodeStmts(dst, cmds, cmd_name)
	if(type(cmds) == "string") then
		dst[#dst + 1] = cmds
	elseif(type(cmds) == "function") then
		dst[#dst + 1] = cmds
	elseif(type(input) == "table") then
		for _,v in ipairs(input) do
			AddCodeStmts(dst, v, cmd_name)
		end
	else
		assert(nil, cmd_name .. " takes a string, function, or a table of such values.");
	end
end

function codegen.initialize(init_cmds)
	assert(codegen._curr, "Attempt to set initialization data for a suite/test that doesn't exist.")
	
	AddCodeStmts(codegen._curr.initialize, init_cmds, "initialize")
end

codegen.init = codegen.initialize

-----------------------------------------
-- Miscellaneous functions
function codegen.stmtfile(filename)
	assert(codegen._curr, "Must have a current suite/test to call stmtfile.")
	
	local base_dir = codegen._curr._base_dir
	return function(...)
		local oldcwd = os.getcwd()
		os.chdir(base_dir)
		local hFile = io.open(path.getabsolute(filename), "r")
		local str = hFile:read("*a");
		hFile:close()
		os.chdir(oldcwd)
		return str
	end
end

function codegen.stmtlua(filename)
	assert(codegen._curr, "Must have a current suite/test to call stmtlua.")

	local base_dir = codegen._curr._base_dir
	return function(...)
		local oldcwd = os.getcwd()
		os.chdir(base_dir)
		local func = loadfile(path.getabsolute(filename),
			path.getname(filename))
		local temp = func(...)
		os.chdir(oldcwd)
		return temp
	end
end


--------------------------------
-- Test specific functions.

function codegen.test(name)
	assert_suite("create a test")
	
	name = tostring(name)
	assert(name, "Name of a test must be a string")
	
	if(not codegen._curr._tests[name]) then
		codegen._curr._tests[name] = create_new_test(name)
	end
	
	codegen._curr = codegen._curr._tests[name]
	return codegen._curr
end

local legalFlags = {cache_flush = true, finish = true, swap = true}

function codegen.flags(flags)
	assert_test("set flags")
	set_flags(codegen._curr.flags, legalFlags, flags, "flags")
end

local legalRenderFlags = {discard = true}

function codegen.render_flags(render_flags)
	assert_test("set render flags")
	set_flags(codegen._curr.render_flags, legalRenderFlags, render_flags, "render_flags")
end

function codegen.execinit(cmds)
	assert_test("set initial execution code")
	AddCodeStmts(codegen._curr.execinit, cmds, "execinit")
end

function codegen.exec(cmds)
	assert_test("set execution code")
	AddCodeStmts(codegen._curr.exec, cmds, "exec")
end

function codegen.execfinal(cmds)
	assert_test("set execution finalization code")
	AddCodeStmts(codegen._curr.execfinal, cmds, "execfinal")
end

--Build the environment that the codegen-loaded scripts execute within.
local copyFromGlobal =
{
	--Take these packages.
	"debug",
	"io",
	"os",
	"package",
	"string",
	"table",
	"coroutine",
	
	--Functions
	"assert",
	"collectgarbage",
	"dofile",
	"error",
	"getfenv",
	"getmetatable",
	"ipairs",
	"load",
	"loadstring",
	"loadfile",
	"module",
	"next",
	"pairs",
	"pcall",
	"print",
	"rawequal",
	"rawget",
	"rawset",
	"require",
	"select",
	"setfenv",
	"setmetatable",
	"tonumber",
	"tostring",
	"type",
	"unpack",
	"xpcall",
}

--Copy functions/modules from the Lua envrionment.
codegen._env = {}
for _, copy in ipairs(copyFromGlobal) do
	codegen._env[copy] = _G[copy]
end

--Add our functions from the codegen space to the environment.
for name, copy in pairs(codegen) do
	if(not name:match("^%_")) then
		codegen._env[name] = copy
	end
end

--Emulate lua dofile, but change the current directory.
--Also, change the environment, so they can't see Premake4 (outside of Premake's
--additions to global tables).
function codegen.dofile(filename)
	local oldcwd = os.getcwd()
	local fullPathname = path.getabsolute(filename)
	
	local hFile = io.open(fullPathname, "rt")
	local fileString = hFile:read("*a")
	hFile:close()
	
	os.chdir(path.getdirectory(fullPathname))
	local chunk = assert(loadstring(fileString, path.getname(filename)))
	setfenv(chunk, codegen._env)
	chunk()
	os.chdir(oldcwd)
end


-------------------------------------------------------
-- Code generation functions

---------------------------
--Preprocessing steps
local function minmax(tbl)
	local min, max
	for _,val in ipairs(tbl) do
		if(not min or min > val) then
			min = val
		end
		
		if(not max or max < val) then
			max = val
		end
	end
	return min, max
end

local function MakeParamIface(suite)
	local param_iface = {}
	suite._param_iface = param_iface
	
	for name, range in pairs(suite.params) do
		if(range._rng == "range") then
			local iface = {}
			param_iface[name] = iface;
			
			local endval = range.first + range.count - 1
			iface.min = range.first
			iface.max = endval
			iface.count = range.count
			iface.iter = function(self)
				local state = {}
				local function iterfunc(state, index)
					if(not index) then
						return 1, range.first
					else
						if(index >= range.count) then
							return nil
						else
							return index + 1, range.first + index
						end
					end
				end
				return iterfunc, state
			end
		else
			local iface = {}
			param_iface[name] = iface;

			local min, max = minmax(range)
			iface.min = min
			iface.max = max
			iface.count = #range
			iface.iter = function()
				return ipairs(range)
			end
		end
	end
end

local function MakeParamIndexMap(suite)
	local param_map = {}
	local param_array = {}

	suite._param_map = param_map
	suite._param_array = param_array

	local currIx = 0
	for name, range in pairs(suite.params) do
		suite._param_map[name] = currIx
		param_array[#param_array+1] = name
		currIx = currIx + 1
	end
end

local function PreprocessSuite(suite)
	MakeParamIface(suite)
	MakeParamIndexMap(suite)
end

---------------------------------------
--Headers and includes.
local function WriteInclude(hFile, hdrsWritten, include)
	if(type(include) == "table") then
		for _,file in ipairs(include) do
			WriteInclude(hFile, hdrsWritten, file)
		end
	else
		if(not hdrsWritten[include]) then
			hFile:write("#include ", include, "\n")
			hdrsWritten[include] = true
		end
	end
end

local function WriteIncludes(hFile, suite)
	local hdrsWritten = {}
	
	--Write the standard headers.
	WriteInclude(hFile, hdrsWritten, gen.GetStandardIncludes())
	--TODO: Use OpenGL version/profile that was asked for.
	WriteInclude(hFile, hdrsWritten, gen.GetOpenGLIncludes(3, 3))
	--TODO: Use FreeGLUT only if asked.
	WriteInclude(hFile, hdrsWritten, gen.GetFreeglutIncludes())

	--Now include what the user wanted.
	WriteInclude(hFile, hdrsWritten, suite.includes)
	
	for testname, test in pairs(suite._tests) do
		WriteInclude(hFile, hdrsWritten, test.includes)
	end
end

-------------------------------------
-- Parameter definitions.
local function WriteParamStructs(hFile, suite)
	hFile:write(gen.GetParamDefStructDefinition())
	hFile:write("\n\n");
	
	for name, iface in pairs(suite._param_iface) do
		hFile:write("const int ", gen.GetParamArrayVarname(name), "[] = {")
		local temp = {}
		for _, val in iface:iter() do
			temp[#temp + 1] = val
		end
		hFile:write(table.concat(temp, ", "))
		hFile:write("};\n")

		hFile:write("const ParamDefinition ", gen.GetParamDefVarname(name), " = {")
		hFile:write(iface.min, ", ", iface.max, ", ", iface.count, ", ")
		hFile:write(gen.GetParamArrayVarname(name), "};\n\n")
	end
	
	hFile:write(gen.GetCmdOptionDef(), "\n\n");

end

--------------------------------------
-- Statements
local function GetStmtString(suite, stmt)
	if(type(stmt) == "string") then return stmt end
	if(type(stmt) == "function") then
		return stmt(suite._param_iface)
	end

	--TODO: Stmt can be a file. Load it.
end

-- Initialization statements
local function WriteAndFormatInitStmts(hFile, suite, stmt)
	local currStmt = GetStmtString(suite, stmt)
	
	for name, range in pairs(suite.params) do
		currStmt = currStmt:gsub("%$" .. name, gen.GetParamDefVarname(name))
	end
	
	hFile:write("\t\t", currStmt:gsub("%\n", "\n\t\t"), "\n")
end

-- Execution statements
local function WriteAndFormatExecStmts(hFile, suite, stmt)
	local currStmt = GetStmtString(suite, stmt)
	
	for name, range in pairs(suite.params) do
		currStmt = currStmt:gsub("%$" .. name,
			gen.GetParamValueVarname(suite._param_map[name]))
	end
	
	hFile:write("\t\t", currStmt:gsub("%\n", "\n\t\t"), "\n")
end

local function WriteAndFormatExecStmtsList(hFile, suite, stmtList)
	for _, stmt in ipairs(stmtList) do
		WriteAndFormatExecStmts(hFile, suite, stmt)
	end
end

-- Suite and test classes.
local specialVarTypes =
{
	["gl buffer object"] =
		{type = "GLuint", destroy = "glDeleteBuffers(1, &%s);"},
	["gl vao"] =
		{type = "GLuint", destroy = "glDeleteVertexArrays(1, &%s);"},
	["gl program"] =
		{type = "GLuint", destroy = "glDeleteProgram(%s);"},
	["gl list buffer object"] = 
		{type = "std::vector<GLuint>", destroy = "util::DestroyBufferObjects(%s);"},
	["gl list vao"] =
		{type = "std::vector<GLuint>", destroy = "util::DestroyVertexArrays(%s);"},
	["gl list program"] =
		{type = "std::vector<GLuint>", destroy = "util::DestroyPrograms(%s);"},
}

local function WriteVariableList(hFile, class)
	local bFound = false
	for varname, vartype in pairs(class.variables) do
		hFile:write("\t")
		if(specialVarTypes[vartype]) then
			hFile:write(specialVarTypes[vartype].type)
		else
			hFile:write(vartype)
		end
		
		hFile:write(" ", varname, ";\n")
		bFound = true
	end
	
	hFile:write(iif(bFound, "\n", ""))
end

local function WriteSuiteClass(hFile, suite)
	hFile:write("struct ", gen.GetSuiteClassname(suite.name), "\n{\n")
	
	WriteVariableList(hFile, suite)
	
	--Write the constructor.
	hFile:write("\t", gen.GetSuiteClassname(suite.name), "()\n\t{\n")
	for _, stmt in ipairs(suite.initialize) do
		WriteAndFormatInitStmts(hFile, suite, stmt)
	end
	hFile:write("\t}\n\n")
	
	--Write the destructor.
	hFile:write("\t~", gen.GetSuiteClassname(suite.name), "()\n\t{\n")
	for varname, vartype in pairs(suite.variables) do
		if(specialVarTypes[vartype]) then
			hFile:write("\t\t")
			hFile:write(string.format(specialVarTypes[vartype].destroy, varname))
			hFile:write("\n")
		end
	end
	hFile:write("\t}\n")

	hFile:write("};\n");
end

local function WriteGenerator(hFile, gens, genmode)
	for _,generator in ipairs(gens) do
		if(generator[genmode]) then
			hFile:write(generator[genmode]());
		end
	end
end

local function GetTestTimingGenerators(test)
	--From least-important to most important.
	local order = {"gpu_latency", "gpu_time", "cpu_time"}

	local gens = {}
	for _, timing in ipairs(order) do
		if(test._suite.timings[timing]) then
			gens[#gens + 1] = gen[timing]
		end
	end
	
	local revgens = {}
	for i = #gens, 1, -1 do
		revgens[#revgens + 1] = gens[i]
	end
	
	return gens, revgens;
end

local function WriteTestClass(hFile, test)
	hFile:write("struct ", gen.GetTestClassname(test.name), "\n{\n")
	
	--Write variables first.
	WriteVariableList(hFile, test)
	
	--Write the constructor.
	hFile:write("\t", gen.GetTestClassname(test.name), "(", gen.GetSuiteFuncParam(test._suite), ")\n\t{\n")
	for _, stmt in ipairs(test.initialize) do
		WriteAndFormatInitStmts(hFile, test._suite, stmt)
	end
	hFile:write("\t}\n\n")
	
	--Write the destructor.
	hFile:write("\t~", gen.GetTestClassname(test.name), "()\n\t{\n")
	for varname, vartype in pairs(test.variables) do
		if(specialVarTypes[vartype]) then
			hFile:write("\t\t")
			hFile:write(string.format(specialVarTypes[vartype].destroy, varname))
			hFile:write("\n")
		end
	end
	hFile:write("\t}\n\n")
	
	--Write execution function.
	hFile:write("\tvoid ", gen.GetExecuteFuncName(), "(")
	hFile:write("util::TestDatum &datum")
	hFile:write(", ", gen.GetSuiteFuncParam(test._suite))
	hFile:write(", ", gen.GetParamArgDef())
	hFile:write(")\n\t{\n")
	
	local gens, revgens = GetTestTimingGenerators(test)
	
	--User initialization first.
	WriteAndFormatExecStmtsList(hFile, test._suite, test.execinit)

	--Initialize timings.
	WriteGenerator(hFile, gens, "init");
	hFile:write("\n");
	
	WriteGenerator(hFile, gens, "start");
	hFile:write("\t\t//Time this code.\n");
	WriteAndFormatExecStmtsList(hFile, test._suite, test.exec)
	WriteGenerator(hFile, revgens, "stop"); --Stop the timings in reverse order
	hFile:write("\n");
	
	if(test.flags["swap"]) then
		--TODO: Do different swap when not GLUT.
		hFile:write("\t\tglutSwapBuffers();\n")
	end
	if(test.flags["finish"]) then
		hFile:write("\t\tglFinish();\n");
	end
	
	WriteGenerator(hFile, gens, "record");
	hFile:write("\n");

	WriteGenerator(hFile, gens, "final");
	WriteAndFormatExecStmtsList(hFile, test._suite, test.execfinal)


	hFile:write("\t}\n")

	hFile:write("};\n");
end

------------------------------------------
-- Actual testing function
local function GetLongStringForC(longStr)
	return "\"" .. longStr .. "\""
end


local function WriteTestFunction(hFile, suite)
	hFile:write("void ", gen.GetTestingFuncName(), "()\n{\n")
	hFile:write("\ttry\n") --TODO: Don't do this if not FreeGLUT.
	hFile:write("\t{\n")
	
	--Write the suite/test class instances
	hFile:write("\t\t", gen.GetSuiteClassname(suite.name), " suite;\n")
	for testname, test in pairs(suite._tests) do
		hFile:write("\t\t", gen.GetTestClassname(testname), " ", testname,
			"(suite);\n")
	end
	hFile:write("\n")
	
	--Write parameter declarations.
	hFile:write("\t\tutil::ParamDecl params[] = {")
	for i, paramname in ipairs(suite._param_array) do
		hFile:write("{\"", paramname, "\"}")
		if(i ~= #suite._param_array) then
			hFile:write(", ")
		end
	end
	hFile:write("};\n")
	hFile:write("\t\tstd::vector<util::ParamDecl> paramDecl(boost::begin(params), boost::end(params));\n")
	hFile:write("\n")

	--Write test declarations.
	hFile:write("\t\tutil::TestDesc testArray[] = {\n")
	for testname, test in pairs(suite._tests) do
		hFile:write("\t\t\t{\"", testname, "\", ",
			GetLongStringForC(test.desc), "},\n")
	end
	hFile:write("\t\t};\n")
	hFile:write("\t\tstd::vector<util::TestDesc> tests(boost::begin(testArray), boost::end(testArray));\n")
	hFile:write("\n")

	--Build up the list of instances.
	hFile:write("\t\tstd::vector<int> instValues;\n")
	for i, paramname in ipairs(suite._param_array) do
		local varName = "param" .. i;
		hFile:write(string.rep("\t", i + 1),
			"BOOST_FOREACH(int ", varName, ", ",
			gen.GetParamDefVarname(paramname), ".range())\n")
		hFile:write(string.rep("\t", i + 1), "{\n")
	end
	
	for i, paramname in ipairs(suite._param_array) do
		local varName = "param" .. i;
		hFile:write(string.rep("\t", #suite._param_array + 2),
			string.format("instValues.push_back(%s)", varName), ";\n")
	end

	for i, paramname in ipairs(suite._param_array) do
		hFile:write(string.rep("\t", #suite._param_array - i + 2), "}\n")
	end
	hFile:write("\n")
	
	--TODO: Get the number of executions from the command line.
	hFile:write("\t\tutil::Report report(g_test_options.numExecutions.get(), instValues, paramDecl, tests);\n")
	hFile:write("\n")

	--Perform the timings.
	--TODO: Cull tests that require specialized features that aren't available.
	hFile:write([[
		int instIx = 0;
		boost::container::vector<ParamValue> paramValues;
]])

	hFile:write(string.format("\t\tparamValues.reserve(%i);\n", #suite._param_array))

	--For each test, loop over each parameter.
	for testname, test in pairs(suite._tests) do
		for i, paramname in ipairs(suite._param_array) do
			local varName = "paramIx" .. i;
			local tabs = string.rep("\t", i + 1)
			hFile:write(tabs,
				"BOOST_FOREACH(int ", varName, ", boost::irange(0, ",
				gen.GetParamDefVarname(paramname), ".count))\n")
			hFile:write(tabs, "{\n")
			hFile:write(tabs, "\t",
				string.format("paramValues.emplace_back(%s, %s);\n",
					gen.GetParamDefVarname(paramname), varName))
		end
		
		local tabs = string.rep("\t", #suite._param_array + 2)
		hFile:write(tabs, [[
BOOST_FOREACH(int execCounter, boost::irange(0, g_test_options.numExecutions.get()))
]])
		hFile:write(tabs, "{\n")
		if(test.render_flags["discard"]) then
			hFile:write(tabs, "\tglEnable(GL_RASTERIZER_DISCARD);\n");
		end
		hFile:write(tabs, "\t",
			string.format([[util::TestDatum datum(report, "%s", instIx, execCounter);]],
				testname), "\n")
		hFile:write(tabs, "\t",
			string.format([[%s.%s(datum, suite, &paramValues[0]);]],
				testname, gen.GetExecuteFuncName()), "\n")

		if(test.render_flags["discard"]) then
			hFile:write(tabs, "\tglDisable(GL_RASTERIZER_DISCARD);\n");
		end
		hFile:write(tabs, "}\n")
		hFile:write(tabs, "++instIx;\n")

		for i, paramname in ipairs(suite._param_array) do
			local tabs = string.rep("\t", #suite._param_array - i + 2)
			hFile:write(tabs, "\tparamValues.pop_back();\n")
			hFile:write(tabs, "}\n")
		end
	end
	hFile:write("\n")
	
	--Deliver the report
	hFile:write [[
		const char *version_string_gl = reinterpret_cast<const char*>(glGetString(GL_VERSION));
		const char *vendor_string_gl = reinterpret_cast<const char*>(glGetString(GL_VENDOR));
		const char *renderer_string_gl = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
]]
	
	hFile:write(string.format([[
		if(g_test_options.outputFilename)
		{
			std::ofstream filestream(g_test_options.outputFilename.get().c_str(), std::ios::binary);
			report.WriteToLua(filestream, "%s", %s,
				version_string_gl, vendor_string_gl, renderer_string_gl);
		}
		else
		{
			report.WriteToLua(std::cout, "%s", %s,
				version_string_gl, vendor_string_gl, renderer_string_gl);
		}
]],
		suite.name, GetLongStringForC(suite.desc),
		suite.name, GetLongStringForC(suite.desc)))
	
	hFile:write("\t}\n");
	--TODO: Don't do this if not FreeGLUT
	hFile:write([[
	catch(...)
	{
		glutLeaveMainLoop();
		throw;
	}
]])

	--TODO: Don't do this if not FreeGLUT
	hFile:write([[	glutLeaveMainLoop();
]])
	
	
	hFile:write("}\n");	
end


------------------------------------------
-- Main startup
local function WriteMainGlut(hFile, suite)
	hFile:write("\tglutInit(&argc, argv);\n")

	hFile:write "\n"
	
	--TODO: allow suite to determine resolution.
	hFile:write[[
	int width = 640;
	int height = 480;
]]

	hFile:write "\n"
	
	--TODO: allow suite to determine these parameters
	hFile:write [[
	unsigned int displayMode = GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH | GLUT_STENCIL;
]]
	
	hFile:write "\n"
	
	--TODO: Determine version and core profile from the suite.
	hFile:write [[
	glutInitDisplayMode(displayMode);
	glutInitContextVersion (3, 3);
	glutInitContextProfile(GLUT_CORE_PROFILE);
]]

	hFile:write "\n"

	hFile:write [[
	glutInitWindowSize (width, height); 
	glutInitWindowPosition (300, 200);
	int window = glutCreateWindow(argv[0]);

	glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);

	glload::LoadFunctions();
]]

	hFile:write "\n"
	
	hFile:write(string.format("\tglutDisplayFunc(%s);\n", gen.GetTestingFuncName()))
	
	hFile:write "\n"
	
	hFile:write [[
	glutMainLoop();

	return 0;
]]
end

local function WriteMainFunction(hFile, suite)
	hFile:write [[
int main(int argc, char** argv)
{
	g_test_options = util::GetCmdOptions(argc, argv);
]]

	hFile:write [[
	if(!g_test_options.numExecutions)
]]

	if(suite.executions) then
		--Has default, so use it.
		hFile:write("\t\tg_test_options.numExecutions = ",
			suite.executions, ";\n")
	else
		--No default, so error.
		hFile:write("\t{\n\t\t std::cout << \"You MUST specify the -exec parameter for this test suite.\" << std::endl;\n\t\t return 1;\n\t}\n")
	end
	
	hFile:write "\n"


	--TODO: alternate main form for GLFW.
	WriteMainGlut(hFile, suite)
	hFile:write("}\n")
end


------------------------------------------
-- Primary codegeneration function
function codegen.gencode()
	for name, suite in pairs(codegen._suites) do
		PreprocessSuite(suite)
	
		local mainFilename = suite._base_dir .. "/" .. gen.GetMainFilename(name)

		local hFile = io.open(mainFilename, "w+")
		gen.WritePreamble(hFile, name)
		
		WriteIncludes(hFile, suite)
		hFile:write("\n\n")
		
		WriteParamStructs(hFile, suite)
		hFile:write(gen.GetParamValueStructDefinition(), "\n\n")
		
		WriteSuiteClass(hFile, suite)
		hFile:write("\n\n")
		
		for testname, test in pairs(suite._tests) do	
			WriteTestClass(hFile, test)
			hFile:write("\n")
		end
		
		hFile:write("\n")

		--Write testing function
		WriteTestFunction(hFile, suite)
		
		hFile:write("\n")

		--Write main function
		WriteMainFunction(hFile, suite)
		
		
		hFile:close()
	end
end


------------------------------------------
-- Premake4 project/solution generation

function codegen.genproj()
	local cwd = os.getcwd()
	for name, suite in pairs(codegen._suites) do
		os.chdir(suite._base_dir)

		project(name)
			kind "ConsoleApp"
			language "c++"
			
			files {"../util/*.h", "../util/*.cpp"}
			files {"*_codegen.cpp"}
--			files {"manual/*.h", "manual/*.cpp"}

			includedirs "../../boost_1_51_0"
				
			--Must be after including framwork... because GCC is stupid.
			UseLibs("glload", "glutil", "glm", "freeglut")
			
			configuration "Debug"
				defines {"DEBUG", "_DEBUG"}
				flags "Symbols"
				targetname("manualD")

			configuration "Release"
				defines {"RELEASE", "NDEBUG"};
				flags {"OptimizeSpeed", "NoFramePointer", "ExtraWarnings", "NoEditAndContinue"};
				targetname("manual")

			configuration {"windows"}
				links {"glu32", "opengl32", "gdi32", "winmm", "user32"}

			configuration "linux"
				links {"GL", "GLU"}
	end
	os.chdir(cwd)
end

return codegen