-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathprogSpec.py
1372 lines (1197 loc) · 51.2 KB
/
progSpec.py
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
# ProgSpec manipulation routines
import sys
import re
import copy
from timeit import default_timer as timer
from pyparsing import ParseResults
MaxLogLevelToShow = 1
storeOfBaseTypesUsed={} # Registry of all types used
startTime = timer()
#########################
# Variables to store what Classes and fields were added after a marked point (When MarkItems=True).
# So that they can be "rolled back" later. (For rolling back libaries, etc.)
MarkItems=False
MarkedObjects={}
MarkedFields=[]
ModifierCommands=[]
funcsCalled={}
structsNeedingModification={}
DependanciesUnmarked={}
DependanciesMarked={}
classHeirarchyInfo = {}
currentCheckObjectVars = ""
templatesDefined={}
classImplementationOptions = {}
libLevels = {}
def setLibLevels(childLibList):
global libLevels
libLevels = childLibList
def getLibLevel(libName):
global libLevels
for lib in range(0,len(libLevels)):
if (libLevels[lib] == libName):
return 2
return 1
def rollBack(classes, tags):
global MarkedObjects
global MarkedFields
global ModifierCommands
global structsNeedingModification
global DependanciesMarked
global funcsCalled
if 'initCode' in tags and tags['initCode']:
del tags['initCode']
for ObjToDel in list(MarkedObjects.keys()):
del classes[0][ObjToDel]
classes[1].remove(ObjToDel)
for fieldToDel in MarkedFields:
removeFieldFromObject(classes, fieldToDel[0], fieldToDel[1])
# Delete platform-specific ModifierCommands
idx=0
while(idx<len(ModifierCommands)):
if ModifierCommands[idx][3]==True:
del ModifierCommands[idx]
else: idx+=1
# Delete platform-specific functions called in two stages
# First, delete calls of keys marked for deletion
for FC_ListKey in funcsCalled:
idx=0
FC_List=funcsCalled[FC_ListKey]
while(idx<len(FC_List)):
if FC_List[idx][1]==True:
del FC_List[idx]
else: idx+=1
# Second, remove empty keys entirely.
## This doesn't appear to be necessary
'''deleteFunc = [key for key in funcsCalled if len(funcsCalled[key]) == 0]
for key in deleteFunc:
#print("DELETING KEY: ", key, " WITH CONTENTS: ", funcsCalled[key])
del funcsCalled[key]'''
# Delete platform-specific items in codeGenerator.structsNeedingModification {}
itemsToDelete=[]
for itm in structsNeedingModification:
if structsNeedingModification[itm][3] == True:
itemsToDelete.append(itm)
for itm in itemsToDelete: del(structsNeedingModification[itm])
# Clear other variables
MarkedObjects={}
MarkedFields=[]
DependanciesMarked={}
# featuresHandled is cleared in libraryMngr.py
#########################
def getTypesBase(tSpec):
if isinstance(tSpec, str):
return tSpec
else: return getTypesBase(tSpec[1])
def registerBaseType(usedType, className):
baseType=getTypesBase(usedType)
if not (baseType in storeOfBaseTypesUsed):
storeOfBaseTypesUsed[baseType]={}
if not (className in storeOfBaseTypesUsed[baseType]):
storeOfBaseTypesUsed[baseType][className]=0
else: storeOfBaseTypesUsed[baseType][className] += 1
patternNonce = 0
def addPattern(objSpecs, objectNameList, name, patternList):
global patternNonce
patternName='!'+name+'.'+str(patternNonce)
objectNameList.append(patternName)
objSpecs[patternName[1:]]={'name':name, 'parameters':patternList}
patternNonce += 1
def processParentClass(name, parentClass):
global classHeirarchyInfo
if not parentClass in classHeirarchyInfo: classHeirarchyInfo[parentClass]={'parentClass': None, 'childClasses': set([name])}
else: classHeirarchyInfo[parentClass]['childClasses'].add(name)
if not name in classHeirarchyInfo: classHeirarchyInfo[name]={'parentClass': parentClass, 'childClasses': set([])}
else:
prevParentClassName = classHeirarchyInfo[name]['parentClass']
if prevParentClassName == None:
classHeirarchyInfo[name]['parentClass'] = parentClass
elif parentClass != prevParentClassName:
cdErr("The class "+name+" cannot descend from both "+parentClass+" and "+prevParentClassName)
# returns an identifier for functions that accounts for class and argument types
def fieldIdentifierString(className, packedField):
fieldName = packedField['fieldName']
if fieldName == None: fieldName =""
fieldID=className+'::'+fieldName
if 'typeSpec' in packedField: tSpec = getTypeSpec(packedField)
if 'argList' in tSpec and tSpec['argList'] :
argList = tSpec['argList']
fieldID+='('
count=0
for arg in argList:
if count>0: fieldID+=','
fieldID += fieldTypeKeyword(arg)
count+=1
fieldID+=')'
return fieldID
def addClass(objSpecs, objectNameList, name, stateType, configType, libName = None, comments = None):
global MarkItems
global MarkedObjects
global libLevels
# Config type is [unknown | SEQ | ALT]
if libName != None:
level = getLibLevel(libName)
else: level = 0
if stateType=='model': name='%'+name
elif stateType=='string': name='$'+name
if(name in objSpecs):
cdlog(4, "Note: The struct '{}' is being added but already exists.".format(name))
return None
objSpecs[name]={'name':name, "attrList":[], "attr":{}, "fields":[], "vFields":None, 'stateType':stateType, 'configType':configType,'libLevel':level, 'libName':libName, 'comments':comments}
objectNameList.append(name)
if MarkItems: MarkedObjects[name]=1
return name
def filterClassesToList(parentClassList):
'''Takes string, list or ParseResults and returns it as a list
This is used in a specific situation where different parse branches
cause types to vary between string, list and ParseResults.
'''
if isinstance(parentClassList, list):
return parentClassList
elif isinstance(parentClassList, str):
parentClassList = parentClassList.replace(" ", "")
tmpList = parentClassList.split(",")
elif isinstance(parentClassList, ParseResults):
if parentClassList.get('fieldType', 0) and parentClassList['fieldType'].get('altModeList', 0):
tmpList = parentClassList['fieldType']['altModeList'].asList()
print("tmpList: ", tmpList)
else:
cdErr("Expected a ParseResults to be for the case where a mode is inherited")
else:
cdErr("Trying to convert unexpected type to list")
return tmpList
def filterClassesToString(classes):
'''Takes string, list or ParseResults and returns it as a string
This is used in a specific situation where different parse branches
cause types to vary between string, list and ParseResults.
See specificity of filterClassesToList
'''
if isinstance(classes, ParseResults):
classes = filterClassesToList(classes)
if isinstance(classes, list):
classes = str(classes)
elif isinstance(classes, str):
pass
else:
cdErr("Trying to convert unexpected type to string")
return classes
def appendToAncestorList(objRef, className, subClassMode, parentClassList):
global classImplementationOptions
#subClassMode ="inherits" or "implements"
#objRef = objSpecs[className]
tmpList = []
if not subClassMode in objRef:
objRef[subClassMode] = []
if isinstance(parentClassList,str):
parentClassList = parentClassList.replace(" ", "")
tmpList = parentClassList.split(",")
elif isinstance(parentClassList,list):
for itm in parentClassList:
itm = itm.replace(" ", "")
tmpList.append(itm)
for parentClass in tmpList:
if subClassMode=='inherits': processParentClass(className, parentClass)
if (not parentClass in objRef[subClassMode]):
objRef[subClassMode].append(parentClass)
if subClassMode=='implements':
if not (parentClass in classImplementationOptions):
classImplementationOptions[parentClass] = [className]
else: classImplementationOptions[parentClass].append(className)
def addObjTags(objSpecs, className, stateType, objTags):
startTags = {}
if stateType=='model': className='%'+className
elif stateType=='string': className='$'+className
objRef = objSpecs[className]
if ('tags' in objRef):
objRef['tags'].update(objTags)
else:
objRef['tags']=objTags
if ('inherits' in objRef['tags']):
parentClassList = objRef['tags']['inherits']
inheritsMode = False
try:
if parentClassList['fieldType']['altModeIndicator']:
inheritsMode = True
except (KeyError, TypeError) as e:
cdlog(6, "{}\n failed dict lookup in codeFlagAndModeFields".format(e))
if not inheritsMode:
appendToAncestorList(objRef, className, 'inherits', parentClassList)
addDependencyToStruct(className, parentClassList)
if ('implements' in objRef['tags']):
appendToAncestorList(objRef, className, 'implements', objRef['tags']['implements'])
for tag in objRef['tags']:
if tag[:7]=='COMMAND':
newCommand = objRef['tags'][tag]
commandArg = tag[8:]
addModifierCommand(objSpecs, className, commandArg, commandArg, newCommand)
def addTypeArgList(className, typeArgList):
templatesDefined[className]=typeArgList
def addModifierCommand(objSpecs, objName, funcName, commandArg, commandStr):
global MarkItems
global ModifierCommands
ModifierCommands.append([objName, funcName, commandStr, commandArg, MarkItems])
def appendToFuncsCalled(funcName,funcParams):
global MarkItems
global funcsCalled
if not(funcName in funcsCalled):
funcsCalled[funcName]= []
funcsCalled[funcName].append([funcParams, MarkItems])
def packField(className, thisIsNext, thisOwner, thisType, thisArraySpec, thisReqTagList, thisName, thisArgList, paramList, thisValue, isAllocated, hasFuncBody):
codeConverter=None
packedField = {'isNext': thisIsNext, 'typeSpec':{'owner':thisOwner, 'fieldType':thisType, 'arraySpec':thisArraySpec, 'reqTagList':thisReqTagList, 'argList':thisArgList}, 'fieldName':thisName, 'paramList':paramList, 'value':thisValue, 'isAllocated':isAllocated}
if(thisValue!=None and (not isinstance(thisValue, str)) and len(thisValue)>1 and thisValue[1]!=''):
if thisValue[1][0]=='!':
# This is where the definitions of code conversions are loaded. E.g., 'setRGBA' might get 'setColor(new Color(%1, %2, %3, %4))'
codeConverter = thisValue[1][1:]
packedField['typeSpec']['codeConverter']=codeConverter
elif thisValue[1]!='':
verbatimText=thisValue[1][1:]
#packedField['typeSpec']['verbatimText']=verbatimText
if hasFuncBody:
packedField['hasFuncBody']=True
else:
packedField['hasFuncBody']=False
fieldID = fieldIdentifierString(className, packedField)
packedField['fieldID']=fieldID
return packedField
def addDependencyToStruct(className, dependency):
#print("############ addDependencyToStruct:", className, " --> ", dependency)
global DependanciesMarked
global DependanciesUnmarked
fTypeKW = fieldTypeKeyword(dependency)
reqTagList = getReqTagList(dependency)
if reqTagList:
owner = getOwner(dependency)
addDependencyToStruct(className, fTypeKW)
for reqTag in reqTagList:
argTypeKW = reqTag['tArgType']
argOwner = reqTag['tArgOwner']
if argOwner=='me' and not isBaseType(argTypeKW):
addDependencyToStruct(className, argTypeKW)
else:
dependency = fieldTypeKeyword(dependency)
if className == dependency: return
if MarkItems: listToUpdate = DependanciesMarked
else: listToUpdate = DependanciesUnmarked
if dependency in listToUpdate and className in listToUpdate[dependency]:
cdlog(1, " NOTE: Possible circular dependency between "+className+" and "+dependency)
if not(className in listToUpdate): listToUpdate[className]=[dependency]
else:
if not (dependency in listToUpdate[className]):
listToUpdate[className].append(dependency)
def getClassesDependancies(className):
global DependanciesMarked
global DependanciesUnmarked
retList=[]
if className in DependanciesUnmarked: retList.extend(DependanciesUnmarked[className])
if className in DependanciesMarked: retList.extend(DependanciesMarked[className])
return retList
def appendActionList(fields, fieldID, newActions):
for field in fields:
if 'fieldID' in field and fieldOnlyID(field['fieldID']) == fieldOnlyID(fieldID):
if 'typeSpec' in field and field['typeSpec']!=None: tSpec=field['typeSpec']
else: tSpec=None
fieldIsAFunction = fieldIsFunction(tSpec)
if fieldIsAFunction and 'value' in field and field['value']!=None:
for action in newActions:
field['value'][0].append(copy.copy(action))
return
def appendExtractedStruct(objSpecs, className, newActions):
fields = objSpecs[className]['fields']
for action in newActions:
fields.append(copy.copy(action['fieldDef']))
def addField(objSpecs, className, stateType, packedField):
global MarkItems
global MarkedObjects
global MarkedFields
global ModifierCommands
fieldID = packedField['fieldID']
tSpec = getTypeSpec(packedField)
fTypeKW = fieldTypeKeyword(tSpec)
owner = getOwner(tSpec)
if stateType=='model': taggedClassName='%'+className
elif stateType=='string': taggedClassName='$'+className
else: taggedClassName = className
if stateType!='string':
fieldIfExists = doesClassDirectlyImlementThisField(objSpecs, className, fieldID)
field=fieldIfExists
if fieldIfExists:
cdlog(2, "Note: The field '" + fieldID + "' already exists. Not re-adding")
if not isinstance(fieldIfExists, dict): return
if not ('value' in field) or field['value']==None: return
if not ('value' in packedField) or packedField['value'] ==None: return
if field['value']==packedField['value']: return
if owner=='const' and fTypeKW=='struct': # append inner struct & extracted struct
appendActionList(objSpecs[taggedClassName]["fields"], fieldID, packedField['value'][0])
appendExtractedStruct(objSpecs, fieldID.split('::')[1].split('(')[0], packedField['value'][0])
return
cdErr(fieldID+" is being contradictorily redefined.")
# Don't override flags and modes in derived Classes
if fTypeKW=='flag' or fTypeKW=='mode':
if fieldIDAlreadyDeclaredInStruct(objSpecs, className, fieldID):
cdlog(2, "Note: The field '" + fieldID + "' already exists. Not overriding")
return
objSpecs[taggedClassName]["fields"].append(packedField)
objSpecs[taggedClassName]["vFields"]=None
# if me or we and type is struct add unique dependency
fieldOwner = getOwner(tSpec)
if (fieldOwner=='me' or fieldOwner=='we' or fieldOwner=='const') and fieldsTypeCategory(tSpec)=='struct':
addDependencyToStruct(className, tSpec)
if 'typeSpec' in packedField and 'argList' in packedField['typeSpec']:
argList = packedField['typeSpec']['argList']
if argList:
for arg in argList:
argOwner = getOwner(arg)
if (argOwner=='me' or argOwner=='we' or argOwner=='const') and fieldsTypeCategory(arg)=='struct':
addDependencyToStruct(className, arg)
if MarkItems:
if not (taggedClassName in MarkedObjects):
MarkedFields.append([taggedClassName, fieldID])
if 'optionalTags' in packedField:
for tag in packedField['optionalTags']:
if tag[:7]=='COMMAND':
newCommand = packedField['optionalTags'][tag]
commandArg = tag[8:]
addModifierCommand(objSpecs, taggedClassName, fieldID, commandArg, newCommand)
def markStructAuto(objSpecs, className):
objSpecs[className]["autoGen"]='yes'
###############
def getTagSpec(classStore, className, tagName):
if className in classStore[1]:
objRef = classStore[0][className]
if 'tags' in objRef and tagName in objRef['tags']:
return objRef['tags'][tagName]
return None
def extractMapFromTagMap(tagmap):
tagRetMap={}
#tagmap = tagmap.asList()
if ((not isinstance(tagmap, str)) and len(tagmap)>=2):
tagmap = tagmap[1]
for each in tagmap:
#print("EACH:", each)
tagRetMap[each[0]] = each[1][0]
return tagRetMap
def extractListFromTagList(tagVal):
tagValues=[]
if ((not isinstance(tagVal, str)) and len(tagVal)>=2):
if(tagVal[0]=='['):
for each in tagVal.tagListContents:
tagValues.append(each.tagValue[0])
return tagValues
def searchATagStore(tagStore, tagToFind):
#print("SEARCHING for tag", tagToFind, " in tagStore: ", tagStore)
if tagStore == None: return None
tagSegs=tagToFind.split(r'.')
crntStore=tagStore
item=''
for seg in tagSegs:
#print("seg: ", seg, " crntStore: ", crntStore)
if seg in crntStore:
item=crntStore[seg]
crntStore=item
else: return None
return [item]
def doesClassHaveProperty(classes, fType, propToFind):
if isinstance(fType, str) or fType == None: return False
className=fType[0]
modelSpec = findSpecOf(classes[0], className, 'struct')
if modelSpec == None: return False
classProperties=searchATagStore(modelSpec["tags"], 'properties')
if classProperties != None and classProperties[0] != None :
if propToFind in classProperties[0]:
return True
return False
def fetchTagValue(tagStoreArray, tagToFind):
"""Searches tagStoreArray, a list of dictionaries, for tagToFind
Pass in a list of tag stores to search, sorted with the lower priority lists first.
For example, if you want to search for the tag "platform", first in the buildSpecs tags
and if not found there, in the main tag store, call it like this:
fetchTagValue([mainTags, buildSpecTags], "platform")
If "platform" is defined in the buildSpecTags, that value will override any value for "platform" in the mainTags.
The return value will be of the type and value of the given tag or None if there was no such tag.
Because a tag's value can be a string, number, dict or list, the return value can be any of these.
To search a specific tag store (instead of a prioritized list) use searchAtTagStore().
"""
for tagStore in reversed(tagStoreArray):
tagRet=searchATagStore(tagStore, tagToFind)
if tagRet:
#print("tagRet[0]. type: {} value: {}".format(type(tagRet[0]), tagRet[0]))
return tagRet[0]
return None
def setTagValue(tagStore, tagToSet, tagValue):
tagRet=searchATagStore(tagStore, tagToSet)
tagRet[0]=tagValue
def appendToStringTagValue(tagStore, tagToSet, toAppend):
tagRet=searchATagStore(tagStore, tagToSet)
if(tagRet==None):
tagStore[tagToSet]=toAppend
else:
tagRet[0]+= "\n" +toAppend
tagStore[tagToSet]=tagRet[0]
def wrapFieldListInObjectDef(objName, fieldDefStr):
retStr='struct '+objName +' {\n' + fieldDefStr + '\n}\n'
return retStr
def setFeatureNeeded(tags, featureID):
tags['featuresNeeded'].append(featureID)
def setFeaturesNeeded(tags, featureIDs):
for feature in featureIDs:
setFeatureNeeded(tags, feature)
dataStructureRequirements = []
def addDataStructureRequirements(requirementSpec):
global dataStructureRequirements
dataStructureRequirements.append(requirementSpec)
def addCodeToInit(tagStore, newInitCode):
appendToStringTagValue(tagStore, "initCode", newInitCode);
def removeFieldFromObject (classes, className, fieldtoRemove):
if not className in classes[0]:
return
fieldList=classes[0][className]['fields']
idx=0
for field in fieldList:
if field["fieldID"] == fieldtoRemove:
#print("Removed: ", field["fieldID"])
del fieldList[idx]
idx+=1
############## Field manupulation regarding inheritance
def insertOrReplaceField(fieldListToUpdate, field):
idx=0
for F in fieldListToUpdate:
if field['fieldID']==F['fieldID']:
fieldListToUpdate[idx]=field
return
idx+=1
fieldListToUpdate.append(field)
def updateCvt(classes, fieldListToUpdate, fieldsToConvert):
for F in fieldsToConvert:
tSpec = getTypeSpec(F)
baseType = TypeSpecsMinimumBaseType(classes, tSpec)
G = F.copy()
if baseType!=None:
G['typeSpec']=tSpec
G['typeSpec']['fieldType'] = baseType
insertOrReplaceField(fieldListToUpdate, G)
def updateCpy(fieldListToUpdate, fieldsToCopy):
for field in fieldsToCopy:
insertOrReplaceField(fieldListToUpdate, field)
def populateCallableStructFields(fieldList, classes, className): # e.g. 'type::subType::subType2'
#print("POPULATING-STRUCT:", className)
# TODO: fix sometimes will populateCallableStructFields with sibling class fields
structSpec=findSpecOf(classes[0], className, 'struct')
if structSpec==None: return
if structSpec['vFields']!=None:
fieldList.extend(structSpec['vFields'])
return
classInherits = searchATagStore(structSpec['tags'], 'inherits')
if classInherits!=None:
for classParent in classInherits:
populateCallableStructFields(fieldList, classes, classParent)
classInherits = searchATagStore(structSpec['tags'], 'implements')
if classInherits!=None:
for classParent in classInherits:
if isinstance(classParent, list): classParent = classParent[0]
populateCallableStructFields(fieldList, classes, classParent)
modelSpec=findSpecOf(classes[0], className, 'model')
if(modelSpec!=None): updateCvt(classes, fieldList, modelSpec["fields"])
modelSpec=findSpecOf(classes[0], className, 'struct')
updateCpy(fieldList, modelSpec["fields"])
fieldListOut = copy.copy(fieldList)
structSpec['vFields'] = fieldListOut
def generateListOfFieldsToImplement(classes, className):
fieldList=[]
modelSpec=findSpecOf(classes[0], className, 'model')
if(modelSpec!=None):
updateCvt(classes, fieldList, modelSpec["fields"])
modelSpec=findSpecOf(classes[0], className, 'struct')
if(modelSpec!=None):
updateCpy(fieldList, modelSpec["fields"])
return fieldList
def fieldOnlyID(fieldID):
breakPos = fieldID.find('::')
if breakPos<0: return fieldID
return fieldID[breakPos+2:]
def fieldNameID(fieldID):
colonIndex = fieldID.find('::')
fieldID = fieldID[colonIndex+2:]
parenIndex=fieldID.find('(')
return fieldID[0:parenIndex]
def fieldDefIsInList(fieldList, fieldID):
for field in fieldList:
if 'fieldID' in field and fieldOnlyID(field['fieldID']) == fieldOnlyID(fieldID):
if 'typeSpec' in field and field['typeSpec']!=None: tSpec=field['typeSpec']
else: tSpec=None
fieldIsAFunction = fieldIsFunction(tSpec)
if not fieldIsAFunction: return True
if fieldIsAFunction and 'value' in field and field['value']!=None: # AND, the function is defined
return field
return False
def fieldIDAlreadyDeclaredInStruct(classes, className, fieldID):
structSpec=findSpecOf(classes, className, 'struct')
if structSpec==None:
return False;
if structSpec['vFields']!=None:
for field in structSpec['vFields']:
if fieldID == field['fieldID']:
return True
classInherits = searchATagStore(structSpec['tags'], 'inherits')
if classInherits!=None:
for classParent in classInherits:
if fieldIDAlreadyDeclaredInStruct(classes, classParent, fieldID):
return True
classImplements = searchATagStore(structSpec['tags'], 'implements')
if classImplements!=None:
for classParent in classImplements:
if fieldIDAlreadyDeclaredInStruct(classes, classParent, fieldID):
return True
modelSpec=findSpecOf(classes, className, 'model')
if(modelSpec!=None):
if fieldDefIsInList(modelSpec["fields"], fieldID):
return True
if(structSpec!=None):
if fieldDefIsInList(structSpec["fields"], fieldID):
return True
return False
def fieldNameInStructHierachy(classes, className, fName):
#print('Searching for ', fName, ' in', className)
structSpec=findSpecOf(classes, className, 'struct')
if structSpec==None:
return False;
if structSpec['vFields']!=None:
for field in structSpec['vFields']:
if 'fieldID' in field:
fieldID = field['fieldID']
if fName in field['fieldID']:
return True
classInherits = searchATagStore(structSpec['tags'], 'inherits')
if classInherits!=None:
for classParent in classInherits:
if fieldNameInStructHierachy(classes, classParent, fName):
return True
classImplements = searchATagStore(structSpec['tags'], 'implements')
if classImplements!=None:
for classParent in classImplements:
if fieldNameInStructHierachy(classes, classParent, fName):
return True
modelSpec=findSpecOf(classes, className, 'model')
if(modelSpec!=None):
if fieldDefIsInList(modelSpec["fields"], fName):
return True
if(structSpec!=None):
if fieldDefIsInList(structSpec["fields"], fName):
return True
return False
#### These functions help evaluate parent-class / child-class relations
def doesChildImplementParentClass(classes, parentClassName, childClassName):
parentClassDef = findSpecOf(classes, parentClassName, 'model')
if(parentClassDef == None):parentClassDef = findSpecOf(classes, parentClassName, 'struct')
if(parentClassDef == None):cdErr("Struct to implement not found:"+parentClassName)
for field in parentClassDef['fields']:
argList = getArgList(field)
if(argList != None): # ArgList exists so this is a FUNCTION
parentFieldID = field['fieldID']
childFieldID = parentFieldID.replace(parentClassName+"::", childClassName+"::")
fieldExists = doesClassDirectlyImlementThisField(classes, childClassName, childFieldID)
if not fieldExists:
return [False, parentFieldID]
return [True, ""]
def doesClassDirectlyImlementThisField(objSpecs, className, fieldID):
#print ' ['+className+']: ', fieldID
modelSpec=findSpecOf(objSpecs, className, 'model')
if(modelSpec!=None):
fieldExists = fieldDefIsInList(modelSpec["fields"], fieldID)
if fieldExists:
return fieldExists
structSpec=findSpecOf(objSpecs, className, 'struct')
if(structSpec!=None):
fieldExists = fieldDefIsInList(structSpec["fields"], fieldID)
if fieldExists:
return fieldExists
return False
def doesClassFromListDirectlyImplementThisField(classes, structNameList, fieldID):
if structNameList==None or len(structNameList)==0: return False
for className in structNameList:
if doesClassDirectlyImlementThisField(classes[0], className, fieldID):
return True
return False
def getParentClassList(classes, thisStructName): # Checks 'inherits' but does not check 'implements'
structSpec=findSpecOf(classes[0], thisStructName, 'struct')
classInherits = searchATagStore(structSpec['tags'], 'inherits')
if classInherits==None: classInherits=[]
#print(thisStructName+':', classInherits)
return classInherits
def getChildClassList(classes, thisStructName): # Checks 'inherits' but does not check 'implements'
global classHeirarchyInfo
if thisStructName in classHeirarchyInfo:
classRelationData = classHeirarchyInfo[thisStructName]
if 'childClasses' in classRelationData and len(classRelationData['childClasses'])>0:
listOfChildClasses = classRelationData['childClasses']
grandChildren = set([])
for className in listOfChildClasses:
GchildList = getChildClassList(classes, className)
grandChildren.update(GchildList)
listOfChildClasses |= grandChildren
return listOfChildClasses
return []
def doesParentClassImplementFunc(classes, className, fieldID):
#print ' Parents:\n',
parentClasses=getParentClassList(classes, className)
result = doesClassFromListDirectlyImplementThisField(classes, parentClasses, fieldID)
#if len(parentClasses)>0: print ' P-Results:', result
return result
def doesChildClassImplementFunc(classes, className, fieldID):
childClasses=getChildClassList(classes, className)
result = doesClassFromListDirectlyImplementThisField(classes, childClasses, fieldID)
#if len(childClasses)>0: print ' Childs Result:', result
return result
def doesClassContainFunc(classes, className, funcName):
#TODO: make this take field ID instead of funcName
callableStructFields=[]
populateCallableStructFields(callableStructFields, classes, className)
for field in callableStructFields:
fieldName=field['fieldName']
if fieldName == funcName: return field
return False
templateSpecKeyWords = {'verySlow':0, 'slow':10, 'normal':20, 'fast':30, 'veryFast':40, 'polynomial':0, 'exponential':0, 'nLog_n':10, 'linear':20, 'logarithmic':30, 'constant':40, 'dontUse':0}
def scoreImplementation(optionSpecs, reqTags):
returnScore = 0
errorStr = ""
if(reqTags != None):
for reqTag in reqTags:
reqID = reqTag[0]
reqVal = templateSpecKeyWords[reqTag[1][0]]
if(reqID in optionSpecs):
specVal = templateSpecKeyWords[optionSpecs[reqID]]
if(specVal < reqVal):return([-1, errorStr])
if(specVal > reqVal):returnScore = specVal - reqVal
else:
errorStr = "Requirement '"+reqID+"' not found in Spec:"+str(optionSpecs)
return([-1, errorStr])
return [returnScore, errorStr]
else:
for specKey,specValue in optionSpecs.items():
specScore = templateSpecKeyWords[specValue]
returnScore += specScore
return([returnScore, errorStr])
def getImplementationOptionsFor(fType):
global classImplementationOptions
if fType in classImplementationOptions:
return classImplementationOptions[fType]
return None
############### Various Dynamic Type-handling functions
def isItrType(fTypeKW):
fTypeKW = fieldTypeKeyword(fTypeKW)
if fTypeKW[:8]=='iterator': return True
return False
def convertItrType(classStore, owner, fTypeKW):
# TODO: have this look for iterator sub class
if owner=='itr':
classDef = findSpecOf(classStore[0], fTypeKW, "struct")
for field in classDef['fields']:
KW = fieldTypeKeyword(field)
if KW=='struct' or KW=='model':
fieldName = field['fieldName']
if isItrType(fieldName):
return fieldName
return None
def getGenericArgs(ObjectDef):
if('genericArgs' in ObjectDef): return(ObjectDef['genericArgs'])
else: return(None)
def getGenericArgsFromTypeSpec(tSpec):
genericArgs = {}
reqTagList = getReqTagList(tSpec)
if reqTagList:
implTArgs = getImplementationTypeArgs(tSpec)
if implTArgs:
count = 0
for reqTag in reqTagList:
genericArgs[implTArgs[count]]=reqTag
count += 1
return genericArgs
return None
def getTypeArgList(className):
if not isinstance(className, str): print("ERROR: in progSpec.getTypeArgList(): expected a string not: "+ str(className))
if(className in templatesDefined): return(templatesDefined[className])
else: return(None)
def getReqTagList(tSpec):
if('fieldType' in tSpec and 'reqTagList' in tSpec['fieldType']):
tSpec = tSpec['fieldType']
if('reqTagList' in tSpec):
return(tSpec['reqTagList'])
return(None)
def getReqTags(fType):
if('optionalTag' in fType[1]): return(fType[1][3])
else: return None
def isOldContainerTempFuncErr(tSpec, msg):
if'arraySpec' in tSpec and tSpec['arraySpec']!=None:
cdErr("Deprecated container type in " + msg)
def isNewContainerTempFunc(tSpec):
# use only while transitioning to dynamic lists<> then delete
# TODO: delete this function when dynamic types working
if not 'fieldType' in tSpec: return(False)
fType = tSpec['fieldType']
if isinstance(fType, str): return(False)
fieldTypeKW = fType[0]
if fieldTypeKW=='PovList': return(True)
reqTagList = getReqTagList(tSpec)
if reqTagList: return(True)
elif reqTagList == None: return(False)
return(False)
def isAContainer(tSpec):
if tSpec==None:return(False)
if isNewContainerTempFunc(tSpec): return True # TODO: Remove this after Dynamix Types work.
# TODO: remove check for Old Container
# needed for stringStructs
return('arraySpec' in tSpec and tSpec['arraySpec']!=None)
def getContainerSpec(tSpec):
if isNewContainerTempFunc(tSpec):
if 'fieldType' in tSpec: fType = tSpec['fieldType']
else: fType = None
containerType=fType[0]
return {'owner': tSpec['owner'], 'datastructID':containerType}
# TODO: remove check for Old Container. Needed for stringStructs
return(tSpec['arraySpec'])
def getDatastructID(tSpec):
if isNewContainerTempFunc(tSpec):
# if fType is parseResult w/ fType whose value is 'PovList'
return 'list'
# TODO: remove check for Old Container. Needed for stringStructs
if(isinstance(tSpec['arraySpec']['datastructID'], str)):
return(tSpec['arraySpec']['datastructID'])
else: #is a parseResult
return(tSpec['arraySpec']['datastructID'][0])
def getContaineCategory(classStore, ctnrTSpec):
if 'containerCategory' in ctnrTSpec: return ctnrTSpec['containerCategory']
fTypeKW = fieldTypeKeyword(ctnrTSpec)
if fTypeKW=='string': return 'string'
structSpec = findSpecOf(classStore[0], fTypeKW, 'struct')
if structSpec:
classImplements = searchATagStore(structSpec['tags'], 'implements')
return classImplements[0]
cdErr("Unknown type in progSpec.getContaineCategory() "+fTypeKW)
def getContainerType_Owner(tSpec):
isOldContainerTempFuncErr(tSpec,"progSpec.getContainerType_Owner()")
owner = getOwner(tSpec)
if isNewContainerTempFunc(tSpec): datastructID = fieldTypeKeyword(tSpec)
else: datastructID = 'None'
return [datastructID, owner]
def isContainerTemplateTempFunc(tSpec):
fTypeKW = fieldTypeKeyword(tSpec)
if fTypeKW=='CPP_Deque' or fTypeKW=='Java_ArrayList' or fTypeKW=='Swift_Array':
return True
if fTypeKW=='CPP_Map' or fTypeKW=='Java_Map' or fTypeKW=='Swift_Map':
return True
if fTypeKW=='Java_MultiMap':
return True
if not "RBNode" in fTypeKW and not "RBTree" in fTypeKW and not "List" in fTypeKW and fTypeKW!="Map" and not "Multimap" in fTypeKW:
print("Template class '"+fTypeKW+"' not found")
return False
def getNewContainerFirstElementTypeTempFunc2(tSpec):
# use only while transitioning to dynamic lists<> then delete
# TODO: delete this function when dynamic types working
if tSpec == None: return(None)
if not 'fieldType' in tSpec: return(None)
fType = tSpec['fieldType']
if isinstance(fType, str): return(None)
fTypeKW = fType[0]
if fTypeKW=='PovList': return(['infon'])
reqTagList = getReqTagList(tSpec)
if reqTagList:
if isContainerTemplateTempFunc(tSpec) or fTypeKW=='List': return(reqTagList[0]['tArgType'])
elif reqTagList == None: return(None)
return(None)
def getNewContainerFirstElementTypeTempFunc(tSpec):
# use only while transitioning to dynamic lists<> then delete
# TODO: delete this function when dynamic types working
if tSpec == None: return(None)
if not 'fieldType' in tSpec: return(None)
fType = tSpec['fieldType']
if isinstance(fType, str): return(None)
fTypeKW = fType[0]
if fTypeKW=='PovList': return(['infon'])
reqTagList = getReqTagList(tSpec)
if reqTagList:
if isContainerTemplateTempFunc(tSpec): return(reqTagList[0]['tArgType'])
elif reqTagList == None: return(None)
return(None)
def getNewContainerFirstElementOwnerTempFunc(tSpec):
# TODO: delete this function when dynamic types working. Needed for stringStructs
if tSpec == None: return(None)
if not 'fieldType' in tSpec: return(None)
fType = tSpec['fieldType']
if isinstance(fType, str): return(None)
fTypeKW = fType[0]
if fTypeKW=='PovList': return('our')
reqTagList = getReqTagList(tSpec)
if reqTagList:
if isContainerTemplateTempFunc(tSpec) or fTypeKW=='List': return(reqTagList[0]['tArgOwner'])
elif reqTagList == None: return(None)
return(None)
def getFromImpl(tSpec):
if 'fromImplemented' in tSpec: return tSpec['fromImplemented']
return None
def getImplementationTypeArgs(tSpec):
if 'implTypeArgs' in tSpec: return tSpec['implTypeArgs']
return None
def fieldTypeKeyword(fType):
# fType can be fType or typeSpec
if fType==None: return None
if 'dummyType' in fType: return None
if 'tArgType' in fType: return fType['tArgType']
if 'typeSpec' in fType: fType = fType['typeSpec'] # if var fType is fieldDef
if 'fieldType' in fType: fType = fType['fieldType'] # if var fType is typeSpec
if 'owner' in fType and fType['owner']=='PTR': return None
if isinstance(fType, str): return fType
if len(fType)>1 and fType[1]=='..': return 'int'
if('varType' in fType[0]): fType = fType[0]['varType']
if isinstance(fType[0], str): return fType[0]
if isinstance(fType[0][0], str): return fType[0][0]
cdErr("?Invalid fieldTypeKeyword?")
def getFieldType(tSpec):
retVal = getNewContainerFirstElementTypeTempFunc(tSpec)
if retVal != None: return retVal
if 'fieldType' in tSpec: return(tSpec['fieldType'])
return None
def getContainerFirstElementType(tSpec):
reqTagList=getReqTagList(tSpec)
if reqTagList:
return(reqTagList[0]['tArgType'])
return None
def getContainerFirstElementOwner(tSpec):
global currentCheckObjectVars
if (tSpec == 0):
cdErr(currentCheckObjectVars)
if isAContainer(tSpec):
if isNewContainerTempFunc(tSpec):
if(tSpec['fieldType'][0] == 'PovList'): return('our')
else: return (getOwner(tSpec['reqTagList'][0]))
else: return(getOwner(tSpec))
else:
# TODO: This should throw error, no lists should reach this point.
return(getOwner(tSpec))
def getOwner(tSpec):