-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathcodeGenerator.py
2412 lines (2246 loc) · 130 KB
/
codeGenerator.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
# codeGenerator.py
import re
import copy
import datetime
import platform
import codeDogParser
import libraryMngr
import progSpec
import buildDog
from progSpec import cdlog, cdErr, logLvl, dePythonStr
from progSpec import structsNeedingModification
from pyparsing import ParseResults
from pprint import pprint
import pattern_GUI_Toolkit
import pattern_ManageCmdLine
import pattern_DispData
import pattern_GenSymbols
import pattern_MakeMenu
import pattern_MakeGUI
import pattern_RBMap
import pattern_MakeStyler
import pattern_WriteCallProxy
import stringStructs
import os
import errno
class CodeGenerator(object):
buildStr_libs = ''
funcDeclAcc = ''
funcDefnAcc = ''
classStore = []
tagStore = None
localVarsAllocated = [] # Format: [varName, typeSpec]
localArgsAllocated = [] # Format: [varName, typeSpec]
currentObjName = ''
inheritedEnums = {}
constFieldAccs = {}
modeStringsAcc = ''
nestedClasses = {}
isNestedClass = False
genericStructsGenerated = [ {}, [] ]
codeDogSpecificImpl = ["List", "Map", "MapNode","MapItr", "Multimap", ]
ForwardDeclsForGlobalFuncs = ''
listOfFuncsWithUnknownArgTypes = {}
def appendGlobalFuncAcc(self, decl, defn):
if decl!="":
self.funcDeclAcc+=decl+'; \t// Forward function declaration\n'
self.funcDefnAcc+=decl+defn
def bitsNeeded(self, n):
if n <= 1:
return 0
else:
return 1 + self.bitsNeeded((n + 1) // 2)
###### Routines to track types of identifiers and to look up type based on identifier.
def typeIsInteger(self, fType):
# NOTE: If you need this to work for wrapped types as well use the version in CodeGenerator.py
if fType == None: return False
if progSpec.typeIsNumRange(fType): return True
if not isinstance(fType, str):
fType= fType[0]
fType=progSpec.getUnwrappedClassFieldTypeKeyWord(self.classStore, fType)
if fType=="int" or fType=="BigInt" or fType=="uint" or fType=="uint64" or fType=="uint32"or fType=="int64" or fType=="int32" or fType=="FlexNum":
return True
return False
def typeIsRational(self, fType):
# NOTE: If you need this to work for wrapped types as well use the version in CodeGenerator.py
if fType == None: return False
#if progSpec.typeIsNumRange(fType): return True
if not isinstance(fType, str):
fType= fType[0]
fType=progSpec.getUnwrappedClassFieldTypeKeyWord(self.classStore, fType)
if fType=="double" or fType=="float" or fType=="BigFloat" or fType=="FlexNum" or fType=="BigFrac":
return True
return False
def CheckBuiltinItems(self, currentObjName, segSpec, genericArgs):
# Handle print, return, break, etc.
itemName=segSpec[0]
[code, retOwner, retType]=self.xlator.codeSpecialReference(segSpec, genericArgs)
if code == '': return None
if itemName=='self':
classDef = progSpec.findSpecOf(self.classStore[0], currentObjName, "struct")
if 'typeSpec' in classDef:
tSpecOut = progSpec.getTypeSpec(classDef)
tSpecOut['owner']='their' # TODO: write test case for containers
print("SHOULDNT MATCH:", tSpecOut['owner'],classDef['typeSpec']['owner'])
else: tSpecOut={'owner':'their', 'fieldType':retType, 'arraySpec':None, 'argList':None}
else: tSpecOut={'owner':retOwner, 'fieldType':retType, 'arraySpec':None, 'argList':None}
tSpecOut['codeConverter']=code
return [tSpecOut, 'BUILTIN']
def CheckFunctionsLocalVarArgList(self, itemName):
for item in reversed(self.localVarsAllocated):
if item[0]==itemName:
return [item[1], 'LOCAL']
for item in reversed(self.localArgsAllocated):
if item[0]==itemName:
return [item[1], 'FUNCARG']
return 0
def disassembleFieldID(self, fullFieldID):
openParenPos = fullFieldID.find("(")
if(openParenPos == -1): return(fullFieldID, None)
closeParenPos = fullFieldID.find(")")
classAndFuncName = fullFieldID[:openParenPos]
argListString = fullFieldID[openParenPos+1:closeParenPos]
argList = argListString.split(",")
return(classAndFuncName, argList)
def reassembleFieldID(self, classAndFuncName, argList):
fullFieldID = classAndFuncName
fullFieldID += "("
count = 0
for arg in argList:
if count > 0: fullFieldID += " ,"
fullFieldID += arg
count += 1
fullFieldID += ")"
return(fullFieldID)
def convertFieldIDType(self, fieldID, cvrtType):
[classAndFuncName, argList] = self.disassembleFieldID(fieldID)
if(argList != None):
newArgList= []
for arg in argList:
if(arg == 'uint64_t' or arg == 'uint64' or arg == 'uint32' or arg == 'double' or arg == 'uint' or arg == 'int64' or arg == 'mode' or arg == 'int' or arg == 'int64_t'):
newArgList.append('number_type')
else:
newArgList.append(arg)
fieldID = self.reassembleFieldID(classAndFuncName, newArgList)
return(fieldID)
def isArgNumeric(self, arg):
if arg=='numeric' or arg=='int' or arg=='int32' or arg=='int64' or arg=='uint' or arg=='uint32' or arg=='uint64' or arg=='BigInt':
return True
return False
def doFieldIDsMatch(self, foundFieldID, fullSearchFieldID):
if(foundFieldID!=fullSearchFieldID):
[foundClassAndFunc, foundArgs] = self.disassembleFieldID(foundFieldID)
[searchClassAndFunc, searchArgs] = self.disassembleFieldID(fullSearchFieldID)
if foundClassAndFunc != searchClassAndFunc:
return False
if foundArgs != searchArgs:
#print(" args don't match: "+ str(foundFieldID)+" != "+str(fullSearchFieldID))
if(len(foundArgs) != len(searchArgs)):
print(" # arg lists not same length: "+ foundFieldID+" != "+fullSearchFieldID)
return False
count = 0
while count < len(foundArgs):
foundArg=foundArgs[count]
searchArg=searchArgs[count]
if(foundArg != searchArg):
argsMatch = False
if(foundArg=='any'):argsMatch = True
elif(searchArg=='NULL'):argsMatch = True
elif(searchArg=='BigInt' and foundArg=='string')or(searchArg=='string' and foundArg=='BigInt'):argsMatch = True
elif self.isArgNumeric(searchArg) and self.isArgNumeric(foundArg):argsMatch = True
if not argsMatch:
print(" args don't match: "+ foundArg+" != "+searchArg)
return False
count += 1
return True
def CheckObjectVars(self, className, itemName, fieldIDArgList):
# also used to fetch codeConverter
# if returning wrong overloaded codeConverter check fieldIDArgList
searchFieldID = className+'::'+itemName
fullSearchFieldID = className+'::'+itemName+fieldIDArgList
#print("Searching",className,"for", itemName, fullSearchFieldID)
classDef = progSpec.findSpecOf(self.classStore[0], className, "struct")
if classDef==None:
message = "ERROR: definition not found for: "+ str(className) + " : " + str(itemName)
progSpec.setCurrentCheckObjectVars(message)
return 0
retVal=None
#if("libLevel" in classDef and classDef["libLevel"] == 2 and not 'implements' in classDef): if(classDef["libLevel"] == 2): cdErr(searchFieldID+ " is not defined in parent library of "+str(classDef["libName"]))
wrappedTypeSpec = progSpec.isWrappedType(self.classStore, className)
if(wrappedTypeSpec != None):
actualFieldType=progSpec.getFieldType(wrappedTypeSpec)
if not isinstance(actualFieldType, str):
retVal = self.CheckObjectVars(actualFieldType[0], itemName, "")
if retVal!=0:
wrappedOwner=progSpec.getOwner(wrappedTypeSpec)
retVal['typeSpec']['owner']=wrappedOwner
return retVal
else:
if 'fieldName' in wrappedTypeSpec and wrappedTypeSpec['fieldName']==itemName:
return wrappedTypeSpec
else:
message = "ERROR: MODEL def not found for: "+ str(className) + " : " + str(itemName)
progSpec.setCurrentCheckObjectVars(message)
return 0
callableStructFields=[]
progSpec.populateCallableStructFields(callableStructFields, self.classStore, className)
foundFieldID = 'None'
# TODO: Need to complete but fix, should search callableStructFields
# by inheritance hierarchy. Currently searches child class
# then all other fields returned. Should find hierarchy then
# search child, parent, grandparent etc.
# commit 2111d27664f99c2b4aad289586438efa1846e355 (HEAD -> master, origin/master, origin/HEAD, patternMakeGUI)
for field in callableStructFields:
fieldName=field['fieldName']
if fullSearchFieldID== field['fieldID']:
#print("fullSearchFieldID:",fullSearchFieldID)
return field
if fieldName==itemName and 'number_type' in field['fieldID']:
num_typeFieldID = self.convertFieldIDType(fullSearchFieldID, "number_type")
if(field['fieldID'] == num_typeFieldID):
return field
if fieldName==itemName:
foundFieldID = field
if foundFieldID != 'None':
#doIDsMatch = self.doFieldIDsMatch(foundFieldID['fieldID'], fullSearchFieldID)
#print ("Found", itemName)
return foundFieldID
### Check inherited enum values for a match after GLOBAL
if searchFieldID.startswith("GLOBAL::"):
searchFieldID = searchFieldID[8:]
for enumInheritedType, enumValues in self.inheritedEnums.items():
for value in enumValues:
if value == searchFieldID:
newField = {'typeSpec': {'owner': 'me', 'fieldType': enumInheritedType}, 'fieldName': itemName}
newField['fieldID'] = "{}::{}".format(enumInheritedType, searchFieldID)
newField['typeSpec']['isGlobalEnum'] = True
return newField
#print("WARNING: Could not find field", itemName ,"in", className, "or inherited enums")
return 0 # Field not found in model
def CheckClassStaticVars(self, className, itemName):
classDef = progSpec.findSpecOf(self.classStore[0], itemName, "struct")
if classDef==None:
return None
return [{'owner':'me', 'fieldType':[itemName], 'StaticMode':'yes'}, "CLASS:"+itemName]
StaticMemberVars={} # Used to find parent-class of const and enums
def staticVarNamePrefix(self, staticVarName, parentClass):
if staticVarName in self.StaticMemberVars:
crntBaseName = progSpec.baseStructName(self.currentObjName)
if parentClass!="": refedClass=parentClass
else: refedClass=progSpec.baseStructName(self.StaticMemberVars[staticVarName])
if refedClass=="GLOBAL": return ''
return(self.xlator.langVarNamePrefix(crntBaseName, refedClass))
return ''
def getFieldIDArgList(self, segSpec, genericArgs):
argList=None
fieldIDArgList = ""
argListStr = ""
if len(segSpec) > 1 and segSpec[1]=='(':
if(len(segSpec)==2):
argList=[]
else:
argList=segSpec[2]
if(argList):
count = 0
fieldIDArgList += '('
argListStr += '('
for arg in argList:
[S2, argTSpec]=self.codeExpr(arg[0], None, None, 'LVAL', genericArgs)
#print(argTSpec)
keyWord = progSpec.fieldTypeKeyword(argTSpec)
if keyWord == 'flag':keyWord ='bool'
if keyWord == None:keyWord ='NULL'
if(count >0 ):
fieldIDArgList += ','
argListStr += ', '
fieldIDArgList += keyWord
argListStr += S2
count += 1
fieldIDArgList += ')'
argListStr += ')'
return [argListStr, fieldIDArgList]
def fetchItemsTypeSpec(self, segSpec, genericArgs):
# also used to fetch codeConverter
# return format: [{typeSpec}, 'OBJVAR']. Substitute for wrapped types.
RefType=""
useClassTag=""
itemName=segSpec[0]
[argListStr, fieldIDArgList] = self.getFieldIDArgList(segSpec, genericArgs)
#print ("FETCHING TYPESPEC OF:", self.currentObjName+'::'+itemName+fieldIDArgList)
if self.currentObjName != "":
fieldID = self.currentObjName+'::'+itemName
tagToFind = "classOptions."+progSpec.flattenObjectName(fieldID)
classOptionsTag = progSpec.fetchTagValue([self.tagStore], tagToFind)
if classOptionsTag != None and "useClass" in classOptionsTag:
useClassTag = classOptionsTag["useClass"]
REF=self.CheckBuiltinItems(self.currentObjName, segSpec, genericArgs)
if (REF): # RefType="BUILTIN"
return REF
else:
REF=self.CheckFunctionsLocalVarArgList(itemName)
if (REF): # RefType="LOCAL" or "FUNCARG"
return REF
else:
REF=self.CheckObjectVars(self.currentObjName, itemName, fieldIDArgList)
if (REF):
if useClassTag != "":
fTypeKW = progSpec.fieldTypeKeyword(REF)
if progSpec.doesClassHaveProperty(self.classStore, fTypeKW, 'metaClass'):
REF['typeSpec']['fieldType'][0] = useClassTag
RefType="OBJVAR"
if(self.currentObjName=='GLOBAL'): RefType="GLOBAL"
if self.xlator.LanguageName=='Swift': #TODO Make this part of xlators
RefOwner = progSpec.getOwner(REF)
if RefOwner=='we': RefType = "STATIC:" + self.currentObjName + self.xlator.ObjConnector
else:
REF=self.CheckObjectVars("GLOBAL", itemName, fieldIDArgList)
if (REF):
RefType="GLOBAL"
else:
REF=self.CheckClassStaticVars(self.currentObjName, itemName)
if(REF):
return REF
elif(itemName in self.StaticMemberVars):
parentClassName = self.staticVarNamePrefix(itemName, '')
retTypeSpec = {'owner': 'me', 'fieldType': ['List', [{'tArgOwner': 'me', 'tArgType': 'string'}]], 'note':'not generated from parse', 'reqTagList': [{'tArgOwner': 'me', 'tArgType': 'string'}]}
if(parentClassName != ''):
return [retTypeSpec, "STATIC:"+parentClassName] # 'string' is probably not always correct.
else: return [retTypeSpec, "CONST"]
if itemName=='NULL': return [{'owner':'their', 'fieldType':"pointer", 'arraySpec':None}, "CONST"]
cdlog(logLvl(), "Variable {} could not be found.".format(itemName))
return [None, "LIB"] # TODO: Return correct type
return [REF['typeSpec'], RefType] # Example: [{typeSpec}, 'OBJVAR']
###### End of type tracking code
modeStateNames={}
def getModeStateNames(self):
return self.modeStateNames
def getInheritedEnums(self):
return self.inheritedEnums
typeDefMap={}
ObjectsFieldTypeMap={}
def registerType(self, objName, fieldName, typeOfField, typeDefTag):
ObjectsFieldTypeMap[objName+'::'+fieldName]={'rawType':typeOfField, 'typeDef':typeDefTag}
self.typeDefMap[typeOfField]=typeDefTag
def checkForReservedWord(self, identifier, currentObjName):
# TODO: other cases such as class names and enum values are not checked.
if identifier in ['auto', 'and', 'or', 'const', 'me', 'my', 'our', 'their', 'we', 'itr', 'while', 'withEach'
'do', 'else', 'flag', 'mode', 'for', 'if', 'model', 'struct', 'switch', 'typedef', 'void']:
if currentObjName!="": currentObjName = " in "+currentObjName
cdErr("Reserved word '"+identifier+"' cannot be used as an identifier"+ currentObjName)
if currentObjName!="":
if identifier in ['break', 'continue', 'return', 'false', 'NULL', 'true']:
cdErr("Reserved word '"+identifier+"' cannot be an identifier in "+ currentObjName)
#### GENERIC TYPE HANDLING #############################################
def getDataStructItrTSpec(self, datastructID):
fieldDefFind = self.CheckObjectVars(datastructID, "find", "")
if fieldDefFind==0: fieldDefFind = None
elif 'typeSpec' in fieldDefFind: fieldDefFind = fieldDefFind['typeSpec']
return fieldDefFind
def chooseStructImplementationToUse(self, tSpec,className,fieldName):
fType = progSpec.getFieldType(tSpec)
if not isinstance(fType, str) and len(fType) >1:
fTypeKW = progSpec.fieldTypeKeyword(tSpec)
classDef = progSpec.findSpecOf(self.classStore[0], fTypeKW, "struct")
ctnrCat = progSpec.getTagSpec(self.classStore, fTypeKW, 'implements')
if ('chosenType' in fType):
return(None, None, None, None)
implOptions = progSpec.getImplementationOptionsFor(fTypeKW)
if(implOptions == None):
if fTypeKW=="List" or fTypeKW=="Map" or fTypeKW=="Multimap" :
print("******WARNING: no implementation options found for container ", fTypeKW ,className,"::",fieldName)
# Check to confirm container type is in features needed
else:
reqTags = progSpec.getReqTags(fType)
hiScoreVal = -1
hiScoreName = None
for option in implOptions:
classDef = progSpec.findSpecOf(self.classStore[0], option, "struct")
if 'tags' in classDef and 'specs' in classDef['tags']:
optionTags = classDef['tags']
optionSpecs = optionTags['specs']
[implScore, errorMsg] = progSpec.scoreImplementation(optionSpecs, reqTags)
if 'native' in optionTags:
nativeTag = optionTags['native']
if nativeTag == "lang": implScore += 6
if nativeTag == "platform": implScore += 5
if(errorMsg != ""): cdErr(errorMsg)
if(implScore > hiScoreVal):
hiScoreVal = implScore
hiScoreName = classDef['name']
if hiScoreName != None:
implTArgs = progSpec.getTypeArgList(hiScoreName)
else: implTArgs = None
#print("IMPLEMENTS:", fTypeKW, '->', hiScoreName)
if hiScoreName!=None:progSpec.addDependencyToStruct(className,hiScoreName)
return(hiScoreName,fTypeKW,ctnrCat,implTArgs)
return(None, None, None, None)
def applyStructImplemetation(self, tSpec,className,fieldName):
self.checkForReservedWord(fieldName, className)
[structToImplement, cntrTypeKW, ctnrCat, implTArgs] = self.chooseStructImplementationToUse(tSpec,className,fieldName)
if(structToImplement != None):
tSpec['fieldType'][0] = structToImplement
if cntrTypeKW != None:tSpec['fromImplemented'] = cntrTypeKW
if ctnrCat != None:tSpec['containerCategory'] = ctnrCat
if implTArgs != None:tSpec['implTypeArgs'] = implTArgs
return tSpec
def copyFieldType(self, fType):
if isinstance(fType,str):retVal = copy.copy(fType)
else:
retVal=[]
for prop in fType:retVal.append(copy.copy(prop))
return retVal
def copyTypeSpec(self, tSpec):
retVal = {}
for prop in tSpec:
if prop=='fieldType': retVal[prop]=self.copyFieldType(tSpec[prop])
else: retVal[prop]=copy.copy(tSpec[prop])
return retVal
def copyField(self, field):
copyField = {}
for prop in field:
if prop=='typeSpec':
copyField[prop] = self.copyTypeSpec(field[prop])
else:
copyField[prop] = copy.copy(field[prop])
return copyField
def copyFields(self, fields):
retVal = []
for field in fields:
copyField = self.copyField(field)
retVal.append(copyField)
return retVal
def copyClassDef(self, classDef):
retVal = {}
for itm in classDef:
if itm == "fields":
retVal[itm] = self.copyFields(classDef[itm])
elif classDef[itm]==None:
retVal[itm] = None
else:
retVal[itm] = copy.copy(classDef[itm])
return retVal
def removeCodeDogImplTags(self, className, genericStructName, implTags):
if isinstance(implTags,str):
tagName = implTags
if tagName in self.codeDogSpecificImpl:
implTags = None
if implTags!=None:
implTags = self.xlator.getLangSpecificImplements(implTags)
if implTags=="": implTags = None
elif isinstance(implTags,list):
for implTag in implTags:
tagName = implTag
if tagName in self.codeDogSpecificImpl:
implTags.remove(tagName)
else:
tagName = self.xlator.getLangSpecificImplements(tagName)
if tagName=="":
implTags.remove(implTag)
if len(implTags)==0: implTags = None
return implTags
def generateGenericStructName(self, className, reqTagList, genericArgs):
classDef = progSpec.findSpecOf(self.classStore[0], className, "struct")
if classDef == None: classDef = progSpec.findSpecOf(self.classStore[0], className, "model")
if classDef == None: print("NO CLASS DEF FOR: ", className)
typeArgList = progSpec.getTypeArgList(className)
if typeArgList == None: return className
genericStructName = "__"+className
if genericArgs == None:
genericArgs = {}
count = 0
for reqTag in reqTagList:
genericType = progSpec.fieldTypeKeyword(reqTag)
unwrappedKW = progSpec.getUnwrappedClassFieldTypeKeyWord(self.classStore, genericType)
genericStructName += "_"+unwrappedKW
genericArgs[typeArgList[count]]=reqTag
count += 1
else:
for gArg in genericArgs:
genericType = progSpec.fieldTypeKeyword(genericArgs[gArg])
unwrappedKW = progSpec.getUnwrappedClassFieldTypeKeyWord(self.classStore, genericType)
genericStructName += "_"+unwrappedKW
if not genericStructName in self.genericStructsGenerated[1]:
self.genericStructsGenerated[1].append(genericStructName)
self.classStore[1].append(genericStructName)
genericClassDef = self.copyClassDef(classDef)
if 'vFields' in genericClassDef: genericClassDef['vFields'] = None
if 'implements' in genericClassDef:
implTags = self.removeCodeDogImplTags(className, genericStructName, genericClassDef['implements'])
genericClassDef['tags'].pop('implements')
if implTags!=None: genericClassDef['tags']['implements'] = implTags
if 'tags' in genericClassDef and 'implements' in genericClassDef['tags']:
implTags = self.removeCodeDogImplTags(className, genericStructName, genericClassDef['tags']['implements'])
genericClassDef['tags'].pop('implements')
if implTags!=None:
genericClassDef['tags']['implements'] = implTags
genericClassDef['name'] = genericStructName
genericClassDef['genericArgs'] = genericArgs
for field in genericClassDef["fields"]: # handle constructors and function return types
tSpec = progSpec.getTypeSpec(field)
if 'argList' in tSpec:
fieldName = field['fieldName']
fTypeKW = progSpec.fieldTypeKeyword(tSpec)
if tSpec['reqTagList']: tSpec['reqTagList'] = reqTagList
tSpec = self.getGenericFieldsTypeSpec(genericArgs, tSpec)
if not isinstance(tSpec['fieldType'], str) and len(tSpec['fieldType'])>1:
fTypeKW = self.generateGenericStructName(fTypeKW, reqTagList, genericArgs)
tSpec['fieldType'] = [fTypeKW]
if fTypeKW == "none": field['fieldName'] = genericStructName
self.genericStructsGenerated[0][genericStructName] = genericClassDef
self.classStore[0][genericStructName] = genericClassDef
previousObjName=self.currentObjName
self.setUpFlagAndModeFields(self.tagStore, [genericStructName])
self.currentObjName=previousObjName
return genericStructName
def copyGenericsToArgList(self, tSpec, genericArgs):
argListIn = progSpec.getArgList(tSpec)
argListOut = None
if argListIn and genericArgs:
argListOut = []
for arg in argListIn:
argTypeKW = progSpec.fieldTypeKeyword(arg)
if argTypeKW in genericArgs:
argOut = self.copyField(arg)
genericType = genericArgs[argTypeKW]
fTypeOut = progSpec.fieldTypeKeyword(genericType)
ownerOut = progSpec.getOwner(genericType)
tSpecOut = {'owner':ownerOut, 'fieldType':fTypeOut}
argOut['typeSpec'] = tSpecOut
argListOut.append(argOut)
return(argListOut)
def getGenericFieldsTypeSpec(self, genericArgs, tSpec):
if genericArgs == None: return tSpec
if genericArgs == {}: return tSpec
fTypeKW = progSpec.fieldTypeKeyword(tSpec)
if fTypeKW in genericArgs:
tSpec = self.copyTypeSpec(tSpec)
genericType = genericArgs[fTypeKW]
fTypeOut = progSpec.fieldTypeKeyword(genericType)
ownerIn = progSpec.getOwner(tSpec)
ownerOut = progSpec.getOwner(genericType)
if ownerIn=='itr': ownerOut = 'itr'
tSpec['fieldType'] = fTypeOut
tSpec['owner'] = ownerOut
tSpec['generic'] = fTypeKW
argListOut = self.copyGenericsToArgList(tSpec, genericArgs)
if argListOut and self.xlator.useNestedClasses:
tSpec = self.copyTypeSpec(tSpec)
tSpec['argList']=argListOut
return tSpec
def getGenericTypeSpec(self, genericArgs, tSpec):
fTypeKW = progSpec.fieldTypeKeyword(tSpec)
reqTagList = progSpec.getReqTagList(tSpec)
if reqTagList==None or progSpec.isWrappedType(self.classStore, fTypeKW) or progSpec.isAbstractStruct(self.classStore[0], fTypeKW):
tSpecOut = self.getGenericFieldsTypeSpec(genericArgs, tSpec)
elif self.xlator.renderGenerics=='True':
tSpecOut = self.copyTypeSpec(tSpec)
cvrtType = self.generateGenericStructName(fTypeKW, reqTagList, genericArgs)
tSpecOut['fieldType'] = [copy.copy(cvrtType)]
fromImpl = progSpec.getFromImpl(tSpecOut)
if fromImpl:
implTArgs = progSpec.getImplementationTypeArgs(tSpecOut)
if implTArgs: tSpecOut['implTypeArgs'] = implTArgs
tSpecOut['fromImplemented'] = fromImpl
else:
tArgList = progSpec.getTypeArgList(fTypeKW)
tSpecOut['fromImplemented'] = fTypeKW
tSpecOut['implTypeArgs'] = tArgList
ctnrCat = progSpec.getTagSpec(self.classStore, fTypeKW, 'implements')
if ctnrCat:
tSpecOut['containerCategory'] = ctnrCat
tSpecOut['generic'] = True
else: #renderGenerics=='False'
tSpecOut = self.getGenericFieldsTypeSpec(genericArgs, tSpec)
return tSpecOut
def getContainerValueOwnerAndType(self, tSpec):
fTypeKW = progSpec.fieldTypeKeyword(tSpec)
keyOwner = progSpec.getContainerFirstElementOwner(tSpec)
keyTypeKW = progSpec.getContainerFirstElementType(tSpec)
reqTagList = progSpec.getReqTagList(tSpec)
implTArgs = progSpec.getImplementationTypeArgs(tSpec)
fDefAt = self.CheckObjectVars(fTypeKW, "at", "")
if implTArgs and fDefAt:
atOwner = progSpec.getOwner(fDefAt)
atTypeKW = progSpec.fieldTypeKeyword(fDefAt)
if atTypeKW in implTArgs:
idxAt = implTArgs.index(atTypeKW)
valType = reqTagList[idxAt]
return[valType['tArgOwner'], valType['tArgType']]
else: return[atOwner, atTypeKW]
if reqTagList:
keyOwner = reqTagList[0]['tArgOwner']
keyTypeKW = reqTagList[0]['tArgType']
return[keyOwner, keyTypeKW]
########################################################################
def getUnwrappedIteratorTypeKW(self, owner, fTypeKW):
itrTypeKW = None
if owner=='itr' and not progSpec.isItrType(fTypeKW):
itrTypeKW = progSpec.convertItrType(self.classStore, owner, fTypeKW)
itrTypeKW = progSpec.getUnwrappedClassFieldTypeKeyWord(self.classStore, itrTypeKW)
return itrTypeKW
def getNestedOutter(self, innerKW):
outerKW = None
if innerKW in self.nestedClasses:
outerKW = self.nestedClasses[innerKW]
return outerKW
def convertType(self, tSpec, varMode, genericArgs):
# varMode is 'var' or 'arg' or 'alloc' or 'func' for function Header. Large items are passed as pointers
progSpec.isOldContainerTempFuncErr(tSpec, "convertType")
tSpec = self.getGenericFieldsTypeSpec(genericArgs, tSpec)
fTypeKW = progSpec.fieldTypeKeyword(tSpec)
ownerIn = progSpec.getOwner(tSpec)
ownerOut = self.xlator.getUnwrappedClassOwner(self.classStore, tSpec, fTypeKW, varMode, ownerIn)
unwrappedKW = progSpec.getUnwrappedClassFieldTypeKeyWord(self.classStore, fTypeKW)
reqTagList = progSpec.getReqTagList(tSpec)
itrTypeKW = self.getUnwrappedIteratorTypeKW(ownerOut, fTypeKW)
reqTagStr = self.xlator.getReqTagString(self.classStore, tSpec)
if self.xlator.renderGenerics=='True':
if reqTagList and not progSpec.isWrappedType(self.classStore, fTypeKW) and not progSpec.isAbstractStruct(self.classStore[0], fTypeKW):
if itrTypeKW: fTypeKW = itrTypeKW
unwrappedKW = self.generateGenericStructName(fTypeKW, reqTagList, genericArgs)
else: unwrappedKW += reqTagStr
else:
if self.xlator.useNestedClasses:
if fTypeKW in self.nestedClasses: # is a nested Class
if fTypeKW==self.currentObjName and self.isNestedClass:
unwrappedKW = unwrappedKW
elif self.currentObjName==self.getNestedOutter(fTypeKW):
itrTypeKW = unwrappedKW
unwrappedKW = self.currentObjName+reqTagStr
elif self.isNestedClass and self.getNestedOutter(fTypeKW)==self.getNestedOutter(self.currentObjName):
unwrappedKW = unwrappedKW
else:
unwrappedKW = unwrappedKW+reqTagStr
elif fTypeKW in self.nestedClasses.values(): # contains a nested class
if fTypeKW==self.currentObjName:
unwrappedKW = unwrappedKW
else:
unwrappedKW = unwrappedKW+reqTagStr
else: unwrappedKW += reqTagStr
else: unwrappedKW += reqTagStr
langType = self.xlator.adjustBaseTypes(unwrappedKW, progSpec.isNewContainerTempFunc(tSpec))
langType = self.xlator.applyIterator(langType, itrTypeKW, varMode)
langType = self.xlator.applyOwner(ownerOut, langType, varMode)
return langType
def codeAllocater(self, tSpec, paramList, genericArgs):
CPL = '()'
if paramList!=None:
if isinstance(paramList, str): CPL = '('+paramList+')'
elif len(paramList)>0:
fTypeKW = progSpec.fieldTypeKeyword(tSpec)
classDef = progSpec.findSpecOf(self.classStore[0], fTypeKW, "struct")
if genericArgs==None: genericArgs = progSpec.getGenericArgs(classDef)
modelParams = self.getCtorModelParams(fTypeKW)
if len(paramList)>len(modelParams): modelParams = []
[CPL, paramTypeList] = self.codeParameterList('Allocate', paramList, modelParams, genericArgs)
if self.xlator.useAllCtorArgs and len(paramList)<len(modelParams):
CPL2 = '('
count = 0
for modParam in modelParams:
modTypeKW = progSpec.fieldTypeKeyword(modParam)
if count>0: CPL2+=', '
if len(paramTypeList)>count:
paramTypeKW = progSpec.fieldTypeKeyword(paramTypeList[count])
if modTypeKW!=paramTypeKW and paramTypeKW!=None:
CPL2 = ''
break
[S2, argTSpec]=self.codeExpr(paramList[count][0], None, modParam, 'PARAM', genericArgs)
CPL2 += S2
else:
defaultVal = self.getFieldDefaultVal(modParam, genericArgs)
CPL2 += defaultVal
count += 1
if CPL2!="": CPL= CPL2+')'
CPL = self.xlator.codeSpecialParamList(tSpec, CPL)
S = self.xlator.codeXlatorAllocater(tSpec, genericArgs) + CPL
return S
def convertNameSeg(self, tSpec, name, connector, paramList, reqTagList, genericArgs):
newName = tSpec['codeConverter']
fTypeKW = progSpec.fieldTypeKeyword(tSpec)
if newName == "": cdErr("ERROR: empty codeConverter for: "+name)
if paramList != None:
count=1
for P in paramList:
oldTextTag='%'+str(count)
[S2, argTSpec]=self.codeExpr(P[0], None, None, 'RVAL', genericArgs)
if S2!='self':S2 += self.xlator.makePtrOpt(argTSpec)
if(isinstance(newName, str)):
newName=newName.replace(oldTextTag, S2)
else: cdErr("Unknown error in paramater list")
count+=1
paramList=None
if '%0.' in newName and connector==self.xlator.PtrConnector:
newName = newName.replace('%0.', '%0'+self.xlator.PtrConnector)
if "%T0Type" in newName:
if(reqTagList != None):
T0Type = progSpec.fieldTypeKeyword(reqTagList[0])
T0Type = progSpec.getUnwrappedClassFieldTypeKeyWord(self.classStore, T0Type)
T0Type = self.xlator.adjustBaseTypes(T0Type,True)
T0Owner = progSpec.getOwner(reqTagList[0])
T0Type = self.xlator.applyOwner(T0Owner, T0Type,'')
newName = newName.replace("%T0Type",T0Type)
else: cdErr("ERROR: looking for T0Type in codeConverter but reqTagList found in TypeSpec.")
if "%T1Type" in newName:
if(reqTagList != None):
T1Type = progSpec.fieldTypeKeyword(reqTagList[1])
T1Type = progSpec.getUnwrappedClassFieldTypeKeyWord(self.classStore, T1Type)
T1Type = self.xlator.adjustBaseTypes(T1Type,True)
T1Owner = progSpec.getOwner(reqTagList[1])
T1Type = self.xlator.applyOwner(T1Owner, T1Type,'')
newName = newName.replace("%T1Type",T1Type)
else: cdErr("ERROR: looking for T1Type in codeConverter but reqTagList found in TypeSpec.")
return [newName, paramList]
def codeComment(self, commentType, commentStr, indent):
if commentType=='/*^': return '\n'+ indent + '/* ' + commentStr+ '*/'
elif commentType=='//^': return indent + '// ' + commentStr
else: cdErr("unknown comment type: "+ commentType)
################################ C o d e E x p r e s s i o n s
def codeNameSeg(self, segSpec, tSpecIn, connector, LorR_Val, previousSegName, previousTypeSpec, returnType, LorRorP_Val, genericArgs):
# if tSpecIn has 'dummyType', this is a non-member (or self) and the first segment of the reference.
# return example: ['getData()', <typeSpec>, <alternate form>, 'OBJVAR']
S = ''
SRC = ''
namePrefix = '' # For static_Global vars
tSpecOut = {'owner':'', 'fieldType':'void'}
name = segSpec[0]
owner = progSpec.getOwner(tSpecIn)
fTypeKW = progSpec.fieldTypeKeyword(tSpecIn)
progSpec.isOldContainerTempFuncErr(tSpecIn, 'codeNameSeg1 '+self.currentObjName+' ' +str(name))
isCtnr = progSpec.isNewContainerTempFunc(tSpecIn)
if genericArgs==None and previousTypeSpec!=None: genericArgs = progSpec.getGenericArgsFromTypeSpec(previousTypeSpec)
if(name=='allocate'): cdErr("Deprecated use of allocate()")
paramList = None
if len(segSpec) > 1 and segSpec[1]=='(':
if(len(segSpec)==2): paramList=[]
else: paramList=segSpec[2]
if fTypeKW!=None and not isCtnr:
if fTypeKW=="string":
lenParams = 0
if paramList: lenParams = len(paramList)
[name, tmpTypeSpec] = self.xlator.recodeStringFunctions(name, tSpecOut, lenParams)
tSpecOut = copy.copy(tmpTypeSpec)
if isCtnr and name[0]=='[':
idxTSpec = self.xlator.getIdxType(tSpecIn)
[valOwner, valFType] = self.getContainerValueOwnerAndType(tSpecIn)
tSpecOut = {'owner':valOwner, 'fieldType': valFType}
[S2, idxTSpec] = self.codeExpr(name[1], None, None, LorRorP_Val, genericArgs)
S += self.xlator.codeArrayIndex(S2, tSpecIn, LorR_Val, previousSegName, idxTSpec)
return [S, tSpecOut, S2,'']
elif ('dummyType' in tSpecIn): # This is the first segment of a name
if name=="return":
SRC = "RETURN_TYPE"
tSpecOut['argList'] = [{'typeSpec':returnType}]
elif(name=='resetFlagsAndModes'):
tSpecOut={'owner':'me', 'fieldType': 'void', 'codeConverter':'flags=0'}
# TODO: if flags or modes have a non-zero default this should account for that.
else:
[tSpecOut, SRC]=self.fetchItemsTypeSpec(segSpec, genericArgs) # Possibly adds a codeConversion to tSpecOut
if tSpecOut: tSpecOut = self.getGenericTypeSpec(genericArgs, tSpecOut)
if not self.xlator.doesLangHaveGlobals:
if tSpecOut and 'isGlobalEnum' in tSpecOut and tSpecOut['isGlobalEnum']:namePrefix = progSpec.fieldTypeKeyword(tSpecOut)+ '.'
elif(SRC=="GLOBAL"): namePrefix = self.xlator.GlobalVarPrefix
elif name in self.modeStateNames and self.modeStateNames[name]=='modeStrings': namePrefix = self.xlator.GlobalVarPrefix+self.modeStateNames[name]+'.'
if(SRC[:6]=='STATIC'): namePrefix = SRC[7:];
else:
if(name=='resetFlagsAndModes'):
tSpecOut={'owner':'me', 'fieldType': 'void', 'codeConverter':'flags=0'}
# TODO: if flags or modes have a non-zero default this should account for that.
elif(name[0]=='[' and fTypeKW=='string'):
tSpecOut={'owner':'me', 'fieldType': 'char'}
[S2, idxTypeSpec] = self.codeExpr(name[1], None, None, 'RVAL', genericArgs)
S += self.xlator.codeArrayIndex(S2, 'string', LorR_Val, previousSegName, idxTypeSpec)
return [S, tSpecOut, S2, ''] # Here we return S2 for use in code forms other than [idx]. e.g. f(idx)
elif(name[0]=='[' and (fTypeKW=='uint' or fTypeKW=='int')):
cdErr("Error: integers can't be indexed: "+previousSegName+":"+name)
elif owner=="itr" and 'fromRep' in tSpecIn:
reqTagList = tSpecIn['reqTagList']
if name=="key":
keyOwner = progSpec.getOwner(reqTagList[0])
keyTypeKW = progSpec.fieldTypeKeyword(reqTagList[0])
tSpecOut={'owner':keyOwner, 'fieldType': keyTypeKW}
name = "first"
elif name=="val":
valOwner = progSpec.getOwner(reqTagList[1])
valTypeKW = progSpec.fieldTypeKeyword(reqTagList[1])
tSpecOut={'owner':valOwner, 'fieldType': valTypeKW}
name = "second"
else:
print("Warning! Iterator type not followed by 'key' or 'val' for variable: "+previousSegName+":"+name)
else:
if fTypeKW!="string":
itrTypeKW = progSpec.convertItrType(self.classStore, owner, fTypeKW)
if itrTypeKW!=None: fTypeKW = itrTypeKW
[argListStr, fieldIDArgList] = self.getFieldIDArgList(segSpec, genericArgs)
tSpecOut = self.CheckObjectVars(fTypeKW, name, fieldIDArgList)
if tSpecOut!=0:
tSpecOut = self.copyTypeSpec(self.getGenericTypeSpec(genericArgs, tSpecOut['typeSpec']))
if isCtnr:
segTypeKeyWord = progSpec.fieldTypeKeyword(tSpecOut)
segTypeOwner = progSpec.getOwner(tSpecOut)
[innerTypeOwner, innerTypeKeyWord] = progSpec.queryTagFunction(self.classStore, fTypeKW, "__getAt", segTypeKeyWord, tSpecIn)
if(innerTypeOwner and segTypeOwner != 'itr'):
tSpecOut['owner'] = innerTypeOwner
if(innerTypeKeyWord): tSpecOut['fieldType'][0] = innerTypeKeyWord
tSpecOut = self.copyTypeSpec(tSpecOut)
else: print("tSpecOut = 0 for: "+previousSegName+"."+name, " fTypeKW:",fTypeKW)
if tSpecOut and 'codeConverter' in tSpecOut and tSpecOut['codeConverter']!=None:
reqTagList = progSpec.getReqTagList(tSpecIn)
[convertedName, paramList]=self.convertNameSeg(tSpecOut, name, connector, paramList, reqTagList, genericArgs)
#print("codeConverter ",name,"->",convertedName, tSpecOut)
name = convertedName
callAsGlobal=name.find("%G")
if(callAsGlobal >= 0): namePrefix=''
S+=namePrefix+connector+name
# Add parameters if this is a function call
if(paramList != None):
modelParams = progSpec.getArgList(tSpecOut)
[CPL, paramTypeList] = self.codeParameterList(name, paramList, modelParams, genericArgs)
if self.xlator.renameInitFuncs and name=='init':
if not 'dummyType' in tSpecIn:
fTypeKW=progSpec.fieldTypeKeyword(tSpecIn)
else: fTypeKW=self.currentObjName
S=S.replace('init','__INIT_'+fTypeKW)
S+= CPL
if(tSpecOut==None): cdlog(logLvl(), "Type for {} was not found.".format(name))
return [S, tSpecOut, None, SRC]
def codeUnknownNameSeg(self, segSpec, genericArgs):
S=''
paramList=None
segName=segSpec[0]
segConnector = ''
if(len(segSpec)>1):
segConnector = self.xlator.NameSegFuncConnector
else:
segConnector = self.xlator.NameSegConnector
S += segConnector + segName
if len(segSpec) > 1 and segSpec[1]=='(':
if(len(segSpec)==2):
paramList=[]
else:
paramList=segSpec[2]
# Add parameters if this is a function call
if(paramList != None):
if(len(paramList)==0):
S+="()"
else:
[CPL, paramTypeList] = self.codeParameterList("", paramList, None, genericArgs)
S+= CPL
print("UNKNOWN NAME SEGMENT:", S)
return S;
#### codeItemRef ##################################################
def codeItemRef(self, name, LorR_Val, returnType, LorRorP_Val, genericArgs):
# Returns information related to a variable, function, etc.
previousSegName = ""
previousTypeSpec = None
S=''
segStr=''
if(LorR_Val=='RVAL'): canonicalName ='>'
else: canonicalName = '<'
segTSpec={'owner':'', 'dummyType':True}
connector=''
prevLen=len(S)
segIDX=0
AltFormat=None
AltIDXFormat=''
numNameSegs = len(name)
for segSpec in name:
LHSParentType='#'
owner=progSpec.getOwner(segTSpec)
segName=segSpec[0]
isLastSeg = numNameSegs == segIDX+1
if(segIDX>0):
# Detect connector to use '.' '->', '', (*...).
connector='.'
if(segTSpec): # This is where to detect type of vars not found to determine whether to use '.' or '->'
if 'StaticMode' in segTSpec and segTSpec['StaticMode']=='yes':
connector = self.xlator.ObjConnector
elif progSpec.wrappedTypeIsPointer(self.classStore, segTSpec, segName):
connector = self.xlator.PtrConnector
if previousSegName and previousSegName[-1] == ']' and connector=='!.':
connector = self.xlator.ObjConnector
AltFormat=None
if segTSpec!=None:
if segTSpec and 'fieldType' in segTSpec:
LHSParentType = progSpec.fieldTypeKeyword(segTSpec)
else: LHSParentType = progSpec.fieldTypeKeyword(self.currentObjName) # Landed here because this is the first segment
[segStr, segTSpec, AltIDXFormat, nameSource]=self.codeNameSeg(segSpec, segTSpec, connector, LorR_Val, previousSegName, previousTypeSpec, returnType, LorRorP_Val, genericArgs)
if nameSource!='': canonicalName+=nameSource
if AltIDXFormat!=None:
AltFormat=[S, previousTypeSpec, AltIDXFormat] # This is in case of an alternate index format such as Java's string.put(idx, val)
else:
segStr= self.codeUnknownNameSeg(segSpec, genericArgs)
prevLen=len(S)
if(isinstance(segTSpec, int)):
cdErr("Segment '{}' in the name '{}' is not recognized.".format(segSpec[0], dePythonStr(name)))
# Record canonical name for record keeping
if not isinstance(segName, str):
if segName[0]=='[': canonicalName+='[...]'
else: cdErr('Odd segment name:'+str(segName))
else: canonicalName+='.'+segName
# Should this be called as a global?
callAsGlobal=segStr.find("%G")
if(callAsGlobal >= 0):
S=''
prevLen=0
segStr=segStr.replace("%G", '')
segStr=segStr[len(connector):]
connector=''
# Handle case where LeftName is connected by '->' but the next segment is '[...]'. So we need '(*left)[...]'
if connector=='->' and segStr[0]=='[':
S='(*'+S+')'
connector=''
# Should this be called C style?
if(segStr.find("%0") >= 0):
# if connector=='->' and owner!='itr': S="*("+S+")"
S=segStr.replace("%0", S)
lenConnector = len(connector)
if S[:lenConnector]==connector: S=S[lenConnector:]
else: S+=segStr
# Language specific dereferencing of ->[...], etc.
S = self.xlator.LanguageSpecificDecorations(S, segTSpec, owner, LorRorP_Val)
previousSegName = segName
previousTypeSpec = segTSpec
segIDX+=1
# Handle cases where seg's type is flag or mode
if segTSpec and LorR_Val=='RVAL' and 'fieldType' in segTSpec:
fType=progSpec.fieldTypeKeyword(segTSpec)
if fType=='flag':
segName=segStr[len(connector):]
prefix = self.staticVarNamePrefix(segName, LHSParentType)
if self.xlator.hasMacros:
S='getFlagBit('+S[0:prevLen]+connector+'flags' + ', ' + prefix+segName+')'
else:
bitfieldMask=self.xlator.applyTypecast('uint64', prefix+segName)
flagReadCode = '('+S[0:prevLen] + connector + 'flags & ' + bitfieldMask+')'
S=self.xlator.applyTypecast('uint64', flagReadCode)
elif fType=='mode':
segName=segStr[len(connector):]
prefix = self.staticVarNamePrefix(segName+"Mask", LHSParentType)
if self.xlator.hasMacros:
S='getModeBits('+S[0:prevLen]+connector+'flags' + ', ' + prefix+segName+')'
else:
bitfieldMask =self.xlator.applyTypecast('uint64', prefix+segName+"Mask")
bitfieldOffset=self.xlator.applyTypecast('uint64', prefix+segName+"Offset")
S="((" + S[0:prevLen] + connector + "flags&"+bitfieldMask+")"+">>"+bitfieldOffset+')'
S=self.xlator.applyTypecast(self.xlator.modeIdxType, S)
return [S, segTSpec, LHSParentType, AltFormat]
def codeUserMesg(self, item):
# TODO: Make 'user messages'interpolate and adjust for locale.
S=''; fmtStr=''; argStr='';
pos=0
for m in re.finditer(r"%[ilscp]`.+?`", item):
fmtStr += item[pos:m.start()+2]
argStr += ', ' + item[m.start()+3:m.end()-1]