summaryrefslogtreecommitdiff
path: root/src/mesa/es/main/apiutil.py
blob: 7fb1afc3a85e0ef4b39359f1bf6f56778f6fcc83 (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
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
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117

# apiutil.py
#
# This file defines a bunch of utility functions for OpenGL API code
# generation.

import sys, string, re


#======================================================================

def CopyrightC( ):
        print """/* Copyright (c) 2001, Stanford University
        All rights reserved.

        See the file LICENSE.txt for information on redistributing this software. */
        """

def CopyrightDef( ):
        print """; Copyright (c) 2001, Stanford University
        ; All rights reserved.
        ;
        ; See the file LICENSE.txt for information on redistributing this software.
        """


#======================================================================

class APIFunction:
        """Class to represent a GL API function (name, return type,
        parameters, etc)."""
        def __init__(self):
                self.name = ''
                self.returnType = ''
                self.category = ''
                self.categories = []
                self.offset = -1
                self.alias = ''
                self.vectoralias = ''
                self.convertalias = ''
                self.aliasprefix = ''
                self.params = []
                self.paramlist = []
                self.paramvec = []
                self.paramaction = []
                self.paramprop = []
                self.paramset = []
                self.props = []
                self.chromium = []

def FindParamIndex(params, paramName):
        """Given a function record, find the index of a named parameter"""
        for i in range (len(params)):
                if paramName == params[i][0]:
                        return i
        # If we get here, there was no such parameter
        return None

def SetTupleIndex(tuple, index, value):
        t = ()
        for i in range(len(tuple)):
                if i == index:
                        t += (value,)
                else:
                        t += (tuple[i],)
        return t

def VersionSpecificValues(category, values):
        selectedValues = []
        for value in values:
                # Version-specific values are prefixed with the version
                # number, e.g. GLES1.0:GL_TEXTURE_CUBE_MAP_OES
                splitValue = value.split(":")
                if len(splitValue) == 2:
                        if category != None and splitValue[0] != category:
                                # Don't want this one.
                                continue
                        else:
                                selectedValues.append(splitValue[1])
                else:
                        selectedValues.append(value)
        return selectedValues

def ProcessSpecFile(filename, userFunc, category = None):
        """Open the named API spec file and call userFunc(record, category) for each record
        processed."""
        specFile = open(filename, "r")
        if not specFile:
                print >>sys.stderr, "Error: couldn't open %s file!" % filename
                sys.exit()

        record = APIFunction()

        for line in specFile.readlines():

                # split line into tokens
                tokens = string.split(line)

                if len(tokens) > 0 and line[0] != '#':

                        if tokens[0] == 'name':
                                if record.name != '':
                                        # process the old function now
                                        userFunc(record, category)
                                        # reset the record
                                        record = APIFunction()

                                record.name = tokens[1]

                        elif tokens[0] == 'return':
                                record.returnType = string.join(tokens[1:], ' ')
                        
                        elif tokens[0] == 'param':
                                name = tokens[1]
                                type = string.join(tokens[2:], ' ')
                                vecSize = 0
                                record.params.append((name, type, vecSize, None, [], None))

                        elif tokens[0] == 'paramprop':
                                name = tokens[1]
                                str = tokens[2:]
                                enums = []
                                for i in range(len(str)):
                                        enums.append(str[i]) 
                                record.paramprop.append((name, enums))

                        elif tokens[0] == 'paramlist':
                                name = tokens[1]
                                str = tokens[2:]
                                list = []
                                for i in range(len(str)):
                                        list.append(str[i]) 
                                record.paramlist.append((name,list))

                        elif tokens[0] == 'paramvec':
                                name = tokens[1]
                                str = tokens[2:]
                                vec = []
                                for i in range(len(str)):
                                        vec.append(str[i]) 
                                record.paramvec.append((name,vec))

                        elif tokens[0] == 'paramset':
                                line = tokens[1:]
                                result = []
                                for i in range(len(line)):
                                        tset = line[i]
                                        if tset == '[':
                                                nlist = []
                                        elif tset == ']':
                                                result.append(nlist)
                                                nlist = []
                                        else:
                                                nlist.append(tset)
                                if result != []:
                                        record.paramset.append(result)

                        elif tokens[0] == 'paramaction':
                                name = tokens[1]
                                str = tokens[2:]
                                list = []
                                for i in range(len(str)):
                                        list.append(str[i]) 
                                record.paramaction.append((name,list))

                        elif tokens[0] == 'category':
                                record.category = tokens[1]
                                record.categories = tokens[1:]

                        elif tokens[0] == 'offset':
                                if tokens[1] == '?':
                                        record.offset = -2
                                else:
                                        record.offset = int(tokens[1])

                        elif tokens[0] == 'alias':
                                record.alias = tokens[1]

                        elif tokens[0] == 'vectoralias':
                                record.vectoralias = tokens[1]

                        elif tokens[0] == 'convertalias':
                                record.convertalias = tokens[1]

                        elif tokens[0] == 'aliasprefix':
                                record.aliasprefix = tokens[1]

                        elif tokens[0] == 'props':
                                record.props = tokens[1:]

                        elif tokens[0] == 'chromium':
                                record.chromium = tokens[1:]

                        elif tokens[0] == 'vector':
                                vecName = tokens[1]
                                vecSize = int(tokens[2])
                                index = FindParamIndex(record.params, vecName)
                                if index == None:
                                        print >>sys.stderr, "Can't find vector '%s' for function '%s'" % (vecName, record.name)
                                # Adjust just the vector size
                                record.params[index] = SetTupleIndex(record.params[index], 2, vecSize)

                        elif tokens[0] == 'dependentvector':
                                dependentVecName = tokens[1]
                                # the dependentVecSize may be an int
                                # expression
                                dependentVecSize = tokens[2]
                                controllingParam = tokens[3]
                                controllingParamIndex = FindParamIndex(record.params, controllingParam)
                                if controllingParamIndex == None:
                                        print >>sys.stderr, "Can't find controlling param '%s' for function '%s'" % (controllingParam, record.name)
                                controllingValues = tokens[4:]

                                # Remember that all of the controllingValues
                                # are valid values for the controllingParam.
                                # We may be duplicating controllingValues
                                # here (i.e. if we get them from different
                                # places); we'll sort them out later.
                                validValues = record.params[controllingParamIndex][4]
                                for value in VersionSpecificValues(category, controllingValues):
                                        validValues.append((value, dependentVecSize, dependentVecName, [], None, None))
                                # Don't need to reassign validValues back
                                # to the tuple - it's a shallow pointer,
                                # so the tuple is already modified.  
                                # (And attempting to do so would produce an
                                # error anyway.)

                        elif tokens[0] == "dependentnovalueconvert":
                                paramName = tokens[1]
                                controllingParamName = tokens[2]
                                controllingValues = tokens[3:]

                                controllingParamIndex = FindParamIndex(record.params, controllingParamName)
                                if controllingParamIndex == None:
                                        print >>sys.stderr, "Can't find controlling param '%s' for function '%s'" % (controllingParamName, record.name)

                                validValues = record.params[controllingParamIndex][4]
                                for value in VersionSpecificValues(category, controllingValues):
                                        validValues.append((value, None, None, [], None, "noconvert"))



                        elif tokens[0] == 'checkparam':
                                paramName = tokens[1]
                                values = tokens[2:]
                                paramIndex = FindParamIndex(record.params, paramName)
                                if paramIndex == None:
                                        print >>sys.stderr, "Can't find checked param '%s' for function '%s'" % (paramName, record.name)

                                errorCode = None

                                # We may be duplicating valid values here;
                                # just add all values to the existing
                                # record, and we'll prune out duplicates
                                # later
                                validValues = record.params[paramIndex][4]

                                # A /GL_* value represents an error, not
                                # a real value.  Look through the values
                                # and only append the non-error values.
                                for v in VersionSpecificValues(category, values):
                                        if v[0] == "/":
                                                errorCode = v[1:]
                                        else:
                                            validValues.append((v, None, None, [], errorCode, None))
                                # Don't need to reassign validValues back
                                # to the parameter tuple - it's a shallow pointer,
                                # so the tuple is already modified.  
                                # (And attempting to do so would produce an
                                # error anyway.)

                        elif tokens[0] == 'checkdependentparam':
                                paramName = tokens[1]
                                controllingValue = tokens[2]
                                dependentParamName = tokens[3]
                                validDependentValues = tokens[4:]
                                errorCode = None

                                # A /GL_* value represents an error, not
                                # a real value.  Look through the values
                                # and only append the non-error values.
                                validDependentValues = []
                                for v in tokens[4:]:
                                        if v[0] == "/":
                                                errorCode = v[1:]
                                        else:
                                            validDependentValues.append(v)

                                paramIndex = FindParamIndex(record.params, paramName)
                                if paramIndex == None:
                                        print >>sys.stderr, "Can't find dependent param '%s' for function '%s'" % (paramName, record.name)

                                validValues = record.params[paramIndex][4]
                                # We may be duplicating valid values here;
                                # we'll sort them out later.  Avoid
                                # adding a controlling value record
                                # at all if there are no values
                                # in the list of values (so that
                                # controlling values with only
                                # version-specific values listed
                                # end up as version-specific
                                # themselves).
                                versionSpecificValues = VersionSpecificValues(category, validDependentValues)
                                if versionSpecificValues != []:
                                        validValues.append((controllingValue, None, dependentParamName, versionSpecificValues, errorCode, None))
                                # Don't need to reassign validValues back
                                # to the tuple - it's a shallow pointer,
                                # so the tuple is already modified.  
                                # (And attempting to do so would produce an
                                # error anyway.)

                        elif tokens[0] == 'convertparams':
                                convertToType = tokens[1]
                                # Replace the conversion type in each named
                                # parameter
                                for paramName in tokens[2:]:
                                        paramIndex = FindParamIndex(record.params, paramName)
                                        if paramIndex == None:
                                            print >>sys.stderr, "Can't find converted param '%s' for function '%s'" % (paramName, record.name)
                                        # Tuples don't support item assignment,
                                        # so to replace scalar values in a
                                        # tuple, you have to reassign the
                                        # whole friggin' thing.
                                        record.params[paramIndex] = SetTupleIndex(record.params[paramIndex], 3, convertToType)

                        else:
                                print >>sys.stderr, 'Invalid token %s after function %s' % (tokens[0], record.name)
                        #endif
                #endif
        #endfor

        # Call the user function for the last record, if we still have one
        # lying around nearly finished
        if record.name != '':
                # process the function now
                userFunc(record, category)
        specFile.close()
#enddef


# Dictionary [name] of APIFunction:
__FunctionDict = {}

# Dictionary [name] of name
__VectorVersion = {}

# Reverse mapping of function name aliases
__ReverseAliases = {}

def CheckCategories(category, categories):
    for c in categories:
        if category == c.split(":")[0]:
            return 1

    return 0

def AddFunction(record, category):
        # If there is a category, we only want records from that category.
        # Note that a category may be in the form "GLES1.1:OES_extension_name",
        # which means that the function is supported as an extension in 
        # GLES1.1...
        if category and not CheckCategories(category, record.categories):
                return

        # Don't allow duplicates
        if __FunctionDict.has_key(record.name):
                print >>sys.stderr, "Duplicate record name '%s' ignored" % record.name
                return

        # Clean up a bit.  We collected valid values for parameters
        # on the fly; it's quite possible that there are duplicates.
        # If there are, collect them together.
        # 
        # We're also going to keep track of all the dependent values
        # that can show up for a parameter; the number of GLenum values
        # (identified with a prefixed "GL_") affects how parameter
        # value conversion happens, as GLenum values are not scaled
        # when converted to or from GLfixed values, the way integer
        # and floating point values are.
        paramValueConversion = {}

        for i in range(len(record.params)):
                foundValidValues = {}

                (name, type, maxVecSize, convertToType, validValues, valueConversion) = record.params[i]
                for (controllingValue, vecSize, dependentParamName, dependentValues, errorCode, valueConvert) in validValues:
                        # Keep track of the maximum vector size for the
                        # *dependent* parameter, not for the controlling
                        # parameter.  Note that the dependent parameter
                        # may be an expression - in this case, don't
                        # consider it.
                        if dependentParamName != None and vecSize != None and vecSize.isdigit():
                                dependentParamIndex = FindParamIndex(record.params, dependentParamName)
                                if dependentParamIndex == None:
                                        print >>sys.stderr, "Couldn't find dependent parameter '%s' of function '%s'" % (dependentParamName, record.name)
                                (dName, dType, dMaxVecSize, dConvert, dValid, dValueConversion) = record.params[dependentParamIndex]
                                if dMaxVecSize == None or int(vecSize) > dMaxVecSize:
                                        dMaxVecSize = int(vecSize)
                                        record.params[dependentParamIndex] = (dName, dType, dMaxVecSize, dConvert, dValid, dValueConversion)

                        # Make sure an entry for the controlling value
                        # exists in the foundValidValues dictionary
                        if controllingValue in foundValidValues:
                                # The value was already there.  Merge the
                                # two together, giving errors if needed.
                                (oldControllingValue, oldVecSize, oldDependentParamName, oldDependentValues, oldErrorCode, oldValueConvert) = foundValidValues[controllingValue]

                                # Make sure the vector sizes are compatible;
                                # either one should be None (and be 
                                # overridden by the other), or they should
                                # match exactly.  If one is not an
                                # integer (this can happen if the 
                                # dependent value is an integer expression,
                                # which occurs a couple of times), don't
                                # use it.
                                if oldVecSize == None:
                                        oldVecSize = vecSize
                                elif vecSize != None and vecSize != oldVecSize:
                                        print >>sys.stderr, "Found two different vector sizes (%s and %s) for the same controlling value '%s' of the same parameter '%s' of function '%s'" % (oldVecSize, vecSize, controllingValue, name, record.name)

                                # Same for the dependent parameter name.
                                if oldDependentParamName == None:
                                        oldDependentParamName = dependentParamName
                                elif dependentParamName != None and dependentParamName != oldDependentParamName:
                                        print >>sys.stderr, "Found two different dependent parameter names (%s and %s) for the same controlling value '%s' of the same parameter '%s' of function '%s'" % (oldDependentParamName, dependentParamName, controllingValue, name, record.name)

                                # And for the error code.
                                if oldErrorCode == None:
                                        oldErrorCode = errorCode
                                elif errorCode != None and errorCode != oldErrorCode:
                                        print >>sys.stderr, "Found two different error codes(%s and %s) for the same controlling value '%s' of the same parameter '%s' of function '%s'" % (oldErrorCode, errorCode, controllingValue, name, record.name)

                                # And for the value conversion flag
                                if oldValueConvert == None:
                                        oldValueConvert = valueConvert
                                elif valueConvert != None and valueConvert != oldValueConvert:
                                        print >>sys.stderr, "Found two different value conversions(%s and %s) for the same controlling value '%s' of the same parameter '%s' of function '%s'" % (oldValueConvert, valueConvert, controllingValue, name, record.name)

                                # Combine the dependentValues together
                                # directly, but uniquely
                                for value in dependentValues:
                                        if value not in oldDependentValues:
                                                oldDependentValues.append(value)

                                # Stick the combined value back into the
                                # dictionary.  We'll sort it back to the
                                # array later.
                                foundValidValues[oldControllingValue] = (oldControllingValue, oldVecSize, oldDependentParamName, oldDependentValues, oldErrorCode, oldValueConvert)
                        else: # new controlling value
                                # Just add it to the dictionary so we don't
                                # add the same value more than once.
                                foundValidValues[controllingValue] = (controllingValue, vecSize, dependentParamName, dependentValues, errorCode, valueConvert)
                        # endif a new controlling value

                # endfor all valid values for this parameter

                # Now the foundValidValues[] dictionary holds all the
                # pruned values (at most one for each valid value).
                # But the validValues[] array still holds the order,
                # which we want to maintain.  Go through the validValues
                # array just for the names of the controlling values; 
                # add any uncopied values to the prunedValidValues array.
                prunedValidValues = []

                for (controllingValue, vecSize, dependentParamName, dependentValues, errorCode, valueConvert) in validValues:
                        if controllingValue in foundValidValues:
                                prunedValidValues.append(foundValidValues[controllingValue])
                                # Delete it from the dictionary so it isn't
                                # copied again.
                                del foundValidValues[controllingValue]

                # Each parameter that is being converted may have a
                # subset of values that are GLenums and are never
                # converted.  In some cases, the parameter will 
                # be implicitly determined to be such, by examining
                # the listed possible values and determining for
                # any particular controlling value whether there are
                # any GLenum-valued allowed values.
                #
                # In other cases, the parameter will be explicitly
                # marked as such with the "dependentnovalueconvert" flag;
                # this is the way it has to be done with queries (which
                # cannot list a valid list of values to be passed,
                # because values are returned, not passed).
                #
                # For each value of controlling GLenum, we'll also
                # need to know whether its dependent values are
                # always converted (none of its values require
                # GLenums to be passed in dependent parameters),
                # never converted (all of its values require GLenums),
                # or sometimes converted.
                numNoConvertValues = 0
                allDependentParams = []
                for j in range(len(prunedValidValues)):
                        (controllingValue, vecSize, dependentParamName, dependentValues, errorCode, valueConvert) = prunedValidValues[j]
                        if dependentParamName != None and dependentParamName not in allDependentParams:
                                allDependentParams.append(dependentParamName)

                        # Check for an explicit noconvert marking...
                        if valueConvert == "noconvert":
                                numNoConvertValues += 1
                        else:
                                # Or check for an implicit one.
                                for value in dependentValues:
                                        if value[0:3] == "GL_":
                                                valueConvert = "noconvert"
                                                prunedValidValues[j] = (controllingValue, vecSize, dependentParamName, dependentValues, errorCode, valueConvert)
                                                numNoConvertValues += 1
                                                break

                # For each named dependent param, set the value conversion
                # flag based on whether all values, none, or some need
                # value conversion.  This value is set stepwise
                # for each parameter examined - 
                for dp in allDependentParams:
                        if numNoConvertValues == 0:
                                if not paramValueConversion.has_key(dp):
                                        paramValueConversion[dp] = "all"
                                elif paramValueConversion[dp] == "none":
                                        paramValueConversion[dp] = "some"
                        elif numNoConvertValues == len(prunedValidValues):
                                if not paramValueConversion.has_key(dp):
                                        paramValueConversion[dp] = "none"
                                elif paramValueConversion[dp] == "all":
                                        paramValueConversion[dp] = "some"
                        else:
                                paramValueConversion[dp] = "some"

                # Save away the record.  Save a placeholder in the
                # valueConversion field - we can't set that until we've
                # examined all the parameters.
                record.params[i] = (name, type, maxVecSize, convertToType, prunedValidValues, None)

        # endfor each param of the passed-in function record

        # One more pass: for each parameter, if it is a parameter that
        # needs conversion, save its value conversion type ("all", "none",
        # or "some").  We only have to worry about conditional value 
        # conversion for GLfixed parameters; in all other cases, we
        # either don't convert at all (for non-converting parameters) or
        # we convert everything.
        for i in range(len(record.params)):
                (name, type, maxVecSize, convertToType, validValues, valueConversion) = record.params[i]
                if convertToType == None:
                    valueConversion = None
                elif paramValueConversion.has_key(name):
                    valueConversion = paramValueConversion[name]
                else:
                    valueConversion = "all"

                record.params[i] = (name, type, maxVecSize, convertToType, validValues, valueConversion)
                                        
        # We're done cleaning up!
        # Add the function to the permanent record and we're done.
        __FunctionDict[record.name] = record


def GetFunctionDict(specFile = "", category = None):
        if not specFile:
                specFile = "../glapi_parser/APIspec.txt"
        if len(__FunctionDict) == 0:
                ProcessSpecFile(specFile, AddFunction, category)
                # Look for vector aliased functions
                for func in __FunctionDict.keys():
                        va = __FunctionDict[func].vectoralias
                        if va != '':
                                __VectorVersion[va] = func
                        #endif

                        # and look for regular aliases (for glloader)
                        a = __FunctionDict[func].alias
                        if a:
                                __ReverseAliases[a] = func
                        #endif
                #endfor
        #endif
        return __FunctionDict


def GetAllFunctions(specFile = "", category = None):
        """Return sorted list of all functions known to Chromium."""
        d = GetFunctionDict(specFile, category)
        funcs = []
        for func in d.keys():
                rec = d[func]
                if not "omit" in rec.chromium:
                        funcs.append(func)
        funcs.sort()
        return funcs
        

def GetDispatchedFunctions(specFile = "", category = None):
        """Return sorted list of all functions handled by SPU dispatch table."""
        d = GetFunctionDict(specFile, category)
        funcs = []
        for func in d.keys():
                rec = d[func]
                if (not "omit" in rec.chromium and
                        not "stub" in rec.chromium and
                        rec.alias == ''):
                        funcs.append(func)
        funcs.sort()
        return funcs

#======================================================================

def ReturnType(funcName):
        """Return the C return type of named function.
        Examples: "void" or "const GLubyte *". """
        d = GetFunctionDict()
        return d[funcName].returnType


def Parameters(funcName):
        """Return list of tuples (name, type, vecSize) of function parameters.
        Example: if funcName=="ClipPlane" return
        [ ("plane", "GLenum", 0), ("equation", "const GLdouble *", 4) ] """
        d = GetFunctionDict()
        return d[funcName].params

def ParamAction(funcName):
        """Return list of names of actions for testing.
        For PackerTest only."""
        d = GetFunctionDict()
        return d[funcName].paramaction

def ParamList(funcName):
        """Return list of tuples (name, list of values) of function parameters.
        For PackerTest only."""
        d = GetFunctionDict()
        return d[funcName].paramlist

def ParamVec(funcName):
        """Return list of tuples (name, vector of values) of function parameters.
        For PackerTest only."""
        d = GetFunctionDict()
        return d[funcName].paramvec

def ParamSet(funcName):
        """Return list of tuples (name, list of values) of function parameters.
        For PackerTest only."""
        d = GetFunctionDict()
        return d[funcName].paramset


def Properties(funcName):
        """Return list of properties of the named GL function."""
        d = GetFunctionDict()
        return d[funcName].props

def AllWithProperty(property):
        """Return list of functions that have the named property."""
        funcs = []
        for funcName in GetDispatchedFunctions():
                if property in Properties(funcName):
                        funcs.append(funcName)
        return funcs

def Category(funcName):
        """Return the primary category of the named GL function."""
        d = GetFunctionDict()
        return d[funcName].category

def Categories(funcName):
        """Return all the categories of the named GL function."""
        d = GetFunctionDict()
        return d[funcName].categories

def ChromiumProps(funcName):
        """Return list of Chromium-specific properties of the named GL function."""
        d = GetFunctionDict()
        return d[funcName].chromium

def ParamProps(funcName):
        """Return list of Parameter-specific properties of the named GL function."""
        d = GetFunctionDict()
        return d[funcName].paramprop

def Alias(funcName):
        """Return the function that the named function is an alias of.
        Ex: Alias('DrawArraysEXT') = 'DrawArrays'.
        """
        d = GetFunctionDict()
        return d[funcName].alias

def AliasPrefix(funcName):
        """Return the function that the named function is an alias of.
        Ex: Alias('DrawArraysEXT') = 'DrawArrays'.
        """
        d = GetFunctionDict()
        if d[funcName].aliasprefix == '':
            return "_mesa_"
        else:
            return d[funcName].aliasprefix

def ReverseAlias(funcName):
        """Like Alias(), but the inverse."""
        d = GetFunctionDict()
        if funcName in __ReverseAliases.keys():
                return __ReverseAliases[funcName]
        else:
                return ''

def NonVectorFunction(funcName):
        """Return the non-vector version of the given function, or ''.
        For example: NonVectorFunction("Color3fv") = "Color3f"."""
        d = GetFunctionDict()
        return d[funcName].vectoralias

def ConversionFunction(funcName):
        """Return a function that can be used to implement the
        given function, using different types.
        For example: ConvertedFunction("Color4x") = "Color4f"."""
        d = GetFunctionDict()
        return d[funcName].convertalias

def VectorFunction(funcName):
        """Return the vector version of the given non-vector-valued function,
        or ''.
        For example: VectorVersion("Color3f") = "Color3fv"."""
        d = GetFunctionDict()
        if funcName in __VectorVersion.keys():
                return __VectorVersion[funcName]
        else:
                return ''

def GetCategoryWrapper(func_name):
        """Return a C preprocessor token to test in order to wrap code.
        This handles extensions.
        Example: GetTestWrapper("glActiveTextureARB") = "CR_multitexture"
        Example: GetTestWrapper("glBegin") = ""
        """
        cat = Category(func_name)
        if (cat == "1.0" or
                cat == "1.1" or
                cat == "1.2" or
                cat == "Chromium" or
                cat == "GL_chromium"):
                return ''
        elif cat[0] =='1':
                # i.e. OpenGL 1.3 or 1.4 or 1.5
                return "OPENGL_VERSION_" + string.replace(cat, ".", "_")
        else:
                assert cat != ''
                return string.replace(cat, "GL_", "")


def CanCompile(funcName):
        """Return 1 if the function can be compiled into display lists, else 0."""
        props = Properties(funcName)
        if ("nolist" in props or
                "get" in props or
                "setclient" in props):
                return 0
        else:
                return 1

def HasChromiumProperty(funcName, propertyList):
        """Return 1 if the function or any alias has any property in the
        propertyList"""
        for funcAlias in [funcName, NonVectorFunction(funcName), VectorFunction(funcName)]:
                if funcAlias:
                        props = ChromiumProps(funcAlias)
                        for p in propertyList:
                                if p in props:
                                        return 1
        return 0

def CanPack(funcName):
        """Return 1 if the function can be packed, else 0."""
        return HasChromiumProperty(funcName, ['pack', 'extpack', 'expandpack'])

def HasPackOpcode(funcName):
        """Return 1 if the function has a true pack opcode"""
        return HasChromiumProperty(funcName, ['pack', 'extpack'])

def SetsState(funcName):
        """Return 1 if the function sets server-side state, else 0."""
        props = Properties(funcName)

        # Exceptions.  The first set of these functions *do* have 
        # server-side state-changing  effects, but will be missed 
        # by the general query, because they either render (e.g. 
        # Bitmap) or do not compile into display lists (e.g. all the others).
        # 
        # The second set do *not* have server-side state-changing
        # effects, despite the fact that they do not render
        # and can be compiled.  They are control functions
        # that are not trackable via state.
        if funcName in ['Bitmap', 'DeleteTextures', 'FeedbackBuffer', 
                'RenderMode', 'BindBufferARB', 'DeleteFencesNV']:
                return 1
        elif funcName in ['ExecuteProgramNV']:
                return 0

        # All compilable functions that do not render and that do
        # not set or use client-side state (e.g. DrawArrays, et al.), set
        # server-side state.
        if CanCompile(funcName) and "render" not in props and "useclient" not in props and "setclient" not in props:
                return 1

        # All others don't set server-side state.
        return 0

def SetsClientState(funcName):
        """Return 1 if the function sets client-side state, else 0."""
        props = Properties(funcName)
        if "setclient" in props:
                return 1
        return 0

def SetsTrackedState(funcName):
        """Return 1 if the function sets state that is tracked by
        the state tracker, else 0."""
        # These functions set state, but aren't tracked by the state
        # tracker for various reasons: 
        # - because the state tracker doesn't manage display lists
        #   (e.g. CallList and CallLists)
        # - because the client doesn't have information about what
        #   the server supports, so the function has to go to the
        #   server (e.g. CompressedTexImage calls)
        # - because they require a round-trip to the server (e.g.
        #   the CopyTexImage calls, SetFenceNV, TrackMatrixNV)
        if funcName in [
                'CopyTexImage1D', 'CopyTexImage2D',
                'CopyTexSubImage1D', 'CopyTexSubImage2D', 'CopyTexSubImage3D',
                'CallList', 'CallLists',
                'CompressedTexImage1DARB', 'CompressedTexSubImage1DARB',
                'CompressedTexImage2DARB', 'CompressedTexSubImage2DARB',
                'CompressedTexImage3DARB', 'CompressedTexSubImage3DARB',
                'SetFenceNV'
                ]:
                return 0

        # Anything else that affects client-side state is trackable.
        if SetsClientState(funcName):
                return 1

        # Anything else that doesn't set state at all is certainly
        # not trackable.
        if not SetsState(funcName):
                return 0

        # Per-vertex state isn't tracked the way other state is
        # tracked, so it is specifically excluded.
        if "pervertex" in Properties(funcName):
                return 0

        # Everything else is fine
        return 1

def UsesClientState(funcName):
        """Return 1 if the function uses client-side state, else 0."""
        props = Properties(funcName)
        if "pixelstore" in props or "useclient" in props:
                return 1
        return 0

def IsQuery(funcName):
        """Return 1 if the function returns information to the user, else 0."""
        props = Properties(funcName)
        if "get" in props:
                return 1
        return 0

def FuncGetsState(funcName):
        """Return 1 if the function gets GL state, else 0."""
        d = GetFunctionDict()
        props = Properties(funcName)
        if "get" in props:
                return 1
        else:
                return 0

def IsPointer(dataType):
        """Determine if the datatype is a pointer.  Return 1 or 0."""
        if string.find(dataType, "*") == -1:
                return 0
        else:
                return 1


def PointerType(pointerType):
        """Return the type of a pointer.
        Ex: PointerType('const GLubyte *') = 'GLubyte'
        """
        t = string.split(pointerType, ' ')
        if t[0] == "const":
                t[0] = t[1]
        return t[0]




def OpcodeName(funcName):
        """Return the C token for the opcode for the given function."""
        return "CR_" + string.upper(funcName) + "_OPCODE"


def ExtendedOpcodeName(funcName):
        """Return the C token for the extended opcode for the given function."""
        return "CR_" + string.upper(funcName) + "_EXTEND_OPCODE"




#======================================================================

def MakeCallString(params):
        """Given a list of (name, type, vectorSize) parameters, make a C-style
        formal parameter string.
        Ex return: 'index, x, y, z'.
        """
        result = ''
        i = 1
        n = len(params)
        for (name, type, vecSize, convertToType, validValues, valueConversion) in params:
                result += name
                if i < n:
                        result = result + ', '
                i += 1
        #endfor
        return result
#enddef


def MakeDeclarationString(params):
        """Given a list of (name, type, vectorSize) parameters, make a C-style
        parameter declaration string.
        Ex return: 'GLuint index, GLfloat x, GLfloat y, GLfloat z'.
        """
        n = len(params)
        if n == 0:
                return 'void'
        else:
                result = ''
                i = 1
                for (name, type, vecSize, convertToType, validValues, valueConversion) in params:
                        result = result + type + ' ' + name
                        if i < n:
                                result = result + ', '
                        i += 1
                #endfor
                return result
        #endif
#enddef


def MakePrototypeString(params):
        """Given a list of (name, type, vectorSize) parameters, make a C-style
        parameter prototype string (types only).
        Ex return: 'GLuint, GLfloat, GLfloat, GLfloat'.
        """
        n = len(params)
        if n == 0:
                return 'void'
        else:
                result = ''
                i = 1
                for (name, type, vecSize, convertToType, validValues, valueConversion) in params:
                        result = result + type
                        # see if we need a comma separator
                        if i < n:
                                result = result + ', '
                        i += 1
                #endfor
                return result
        #endif
#enddef


#======================================================================
        
__lengths = {
        'GLbyte': 1,
        'GLubyte': 1,
        'GLshort': 2,
        'GLushort': 2,
        'GLint': 4,
        'GLuint': 4,
        'GLfloat': 4,
        'GLclampf': 4,
        'GLdouble': 8,
        'GLclampd': 8,
        'GLenum': 4,
        'GLboolean': 1,
        'GLsizei': 4,
        'GLbitfield': 4,
        'void': 0,  # XXX why?
        'int': 4,
        'GLintptrARB': 4,   # XXX or 8 bytes?
        'GLsizeiptrARB': 4  # XXX or 8 bytes?
}

def sizeof(type):
        """Return size of C datatype, in bytes."""
        if not type in __lengths.keys():
                print >>sys.stderr, "%s not in lengths!" % type
        return __lengths[type]


#======================================================================
align_types = 1

def FixAlignment( pos, alignment ):
        # if we want double-alignment take word-alignment instead,
        # yes, this is super-lame, but we know what we are doing
        if alignment > 4:
                alignment = 4
        if align_types and alignment and ( pos % alignment ):
                pos += alignment - ( pos % alignment )
        return pos

def WordAlign( pos ):
        return FixAlignment( pos, 4 )

def PointerSize():
        return 8 # Leave room for a 64 bit pointer

def PacketLength( params ):
        len = 0
        for (name, type, vecSize, convertToType, validValues, valueConversion) in params:
                if IsPointer(type):
                        size = PointerSize()
                else:
                        assert string.find(type, "const") == -1
                        size = sizeof(type)
                len = FixAlignment( len, size ) + size
        len = WordAlign( len )
        return len

#======================================================================

__specials = {}

def LoadSpecials( filename ):
        table = {}
        try:
                f = open( filename, "r" )
        except:
                __specials[filename] = {}
                print >>sys.stderr, "%s not present" % filename
                return {}
        
        for line in f.readlines():
                line = string.strip(line)
                if line == "" or line[0] == '#':
                        continue
                table[line] = 1
        
        __specials[filename] = table
        return table


def FindSpecial( filename, glName ):
        table = {}
        try:
                table = __specials[filename]
        except KeyError:
                table = LoadSpecials( filename )
        
        try:
                if (table[glName] == 1):
                        return 1
                else:
                        return 0 #should never happen
        except KeyError:
                return 0


def AllSpecials( table_file ):
        table = {}
        filename = table_file + "_special"
        try:
                table = __specials[filename]
        except KeyError:
                table = LoadSpecials( filename )
        
        keys = table.keys()
        keys.sort()
        return keys


def AllSpecials( table_file ):
        filename = table_file + "_special"
        table = {}
        try:
                table = __specials[filename]
        except KeyError:
                table = LoadSpecials(filename)
        
        ret = table.keys()
        ret.sort()
        return ret
        

def NumSpecials( table_file ):
        filename = table_file + "_special"
        table = {}
        try:
                table = __specials[filename]
        except KeyError:
                table = LoadSpecials(filename)
        return len(table.keys())

def PrintRecord(record):
        argList = MakeDeclarationString(record.params)
        if record.category == "Chromium":
                prefix = "cr"
        else:
                prefix = "gl"
        print '%s %s%s(%s);' % (record.returnType, prefix, record.name, argList )
        if len(record.props) > 0:
                print '   /* %s */' % string.join(record.props, ' ')

#ProcessSpecFile("APIspec.txt", PrintRecord)