def Write_Extracter(classes, ToStructName, FromStructName, logLvl):
    global extracterFunctionAccumulator
    global alreadyWrittenFunctions
    nameForFunc = getFunctionName(FromStructName, ToStructName)
    cdlog(
        logLvl,
        "WRITING function {}() to extract struct {} from parse tree: stage 1..."
        .format(nameForFunc, ToStructName))
    if nameForFunc in alreadyWrittenFunctions: return
    alreadyWrittenFunctions[nameForFunc] = True
    S = ''
    ObjectDef = progSpec.findSpecOf(classes[0], FromStructName, 'string')
    fields = ObjectDef["fields"]
    configType = ObjectDef['configType']
    SeqOrAlt = ''
    if configType == 'SEQ': SeqOrAlt = 'parseSEQ'
    elif configType == 'ALT': SeqOrAlt = 'parseALT'
    cdlog(
        logLvl,
        "WRITING function {}() to extract struct {} from parse tree: stage 2..."
        .format(nameForFunc, ToStructName))
    if configType == 'SEQ':
        S += Write_structExtracter(classes, ToStructName, FromStructName,
                                   fields, nameForFunc, logLvl)
    elif configType == 'ALT':
        S += Write_ALT_Extracter(classes, ToStructName, fields, 'SRec', '',
                                 'tmpStr', '    ', -1, logLvl)

    seqExtracter = "\n    void: " + nameForFunc + "(our stateRec: SRec0, their " + ToStructName + ": memStruct, their EParser: EP) <- {\n" + S + "    }\n"
    extracterFunctionAccumulator += seqExtracter
 def processStruct(self, classes, className):
     global classesEncoded
     classesEncoded[className] = 1
     self.currentClassName = className
     modelRef = progSpec.findSpecOf(classes[0], className, 'model')
     self.resetVars(modelRef)
     self.currentModelSpec = modelRef
     if modelRef == None:
         cdErr('To write a processing function for class "' + className +
               '" a model is needed but is not found.')
     ### Write code for each field
     for field in modelRef['fields']:
         fldCat = progSpec.fieldsTypeCategory(field['typeSpec'])
         fieldName = field['fieldName']
         self.processField(fieldName, field, fldCat)
     self.addOrAmendClasses(classes, className, modelRef)
Beispiel #3
0
def getListWidgetMgrCode(classes, listManagerStructName, rowTypeName,
                         fieldName, classOptionsTags):
    # New listWidgetMgr code generator
    # Find the model
    rowWidgetName = rowTypeName + 'Widget'
    listWidgetStyle = progSpec.fetchTagValue([classOptionsTags],
                                             fieldName + '.style.widgetStyle')
    if listWidgetStyle == None: listWidgetStyle = 'simpleList'
    modelRef = progSpec.findSpecOf(classes[0], rowWidgetName, 'struct')
    if modelRef == None:
        print("modelRef: ", modelRef, rowTypeName)
        addNewStructToProcess(rowWidgetName, rowTypeName, 'struct',
                              'rowWidget')
    filename = './preDynamicTypes/' + listWidgetStyle + '.dog'
    classSpec = progSpec.stringFromFile(filename)
    classSpec = classSpec.replace('<ROW_TYPE>', rowTypeName)
    classSpec = classSpec.replace('<LIST_CLASS_NAME>', listManagerStructName)
    #print '==========================================================\n'+classSpec
    codeDogParser.AddToObjectFromText(classes[0], classes[1], classSpec,
                                      rowWidgetName)
Beispiel #4
0
def codeListWidgetManagerClassOverride(classes, listManagerStructName, structTypeName):
    funcTextToUpdateViewWidget      = ''
    funcTextToUpdateEditWidget      = ''
    funcTextToUpdateCrntFromWidget  = ''
    funcTextToPushCrntToListView    = ''
    rowHeaderCode                   = ''
    rowViewCode                     = ''

    # Find the model
    modelRef = progSpec.findSpecOf(classes[0], structTypeName, 'model')
    currentModelSpec = modelRef
    if modelRef==None:
        cdErr('To build a list GUI for list of "'+structTypeName+'" a model is needed but is not found.')

    ### Write code for each field
    for field in modelRef['fields']:
        typeSpec        = field['typeSpec']
        fldCat          = progSpec.fieldsTypeCategory(typeSpec)
        fieldName       = field['fieldName']
        label           = deCamelCase(fieldName)
        CasedFieldName          = fieldName[0].upper() + fieldName[1:]
        widgetName         = CasedFieldName + 'Widget'

        if not progSpec.isAContainer(typeSpec):
            if(fldCat!='struct'):
                rowHeaderCode   += '        their GUI_Frame: '+fieldName + '_header <- makeLabelWidget("'+fieldName+'")\n'
                rowHeaderCode   += '        setLabelWidth('+fieldName+'_header, 15)\n'
                rowHeaderCode   += '        addToContainer(headerBox, '+fieldName+'_header)\n'

            if fldCat=='struct':
                funcTextToUpdateViewWidget     += ''
                funcTextToUpdateEditWidget     += '   /- updateWidgetFromVars()\n'
                funcTextToUpdateCrntFromWidget += '   /- updateVarsFromWidget()\n'
            elif fldCat=='enum' or fldCat=='mode':
                funcTextToUpdateViewWidget     += ''
                funcTextToUpdateEditWidget     += ''
                funcTextToUpdateCrntFromWidget += ''#  crntRecord.'+fieldName+' <- dialog.' + widgetName + '.getValue()\n'
            elif fldCat=='bool':
                funcTextToUpdateViewWidget     += ''
                funcTextToUpdateEditWidget     += ''
                funcTextToUpdateCrntFromWidget += '    crntRecord.'+fieldName+' <- dialog.' + widgetName + '.getValue()\n'
            elif fldCat=='string':
                funcTextToUpdateViewWidget     += ''
                funcTextToUpdateEditWidget     += '    dialog.' + widgetName + '.setValue('+structTypeName+'_ListData[N].'+fieldName+')\n'
                funcTextToUpdateCrntFromWidget += '    me string: '+widgetName+'Str <- string(dialog.' + widgetName + '.getValue())\n'
                funcTextToUpdateCrntFromWidget += '    crntRecord.'+fieldName+' <- '+widgetName+'Str\n'
                rowViewCode                    += '        their GUI_Frame: '+fieldName + '_value <- makeLabelWidget(crntRecord.'+fieldName+'.data())\n'
                rowViewCode                    += '        setLabelWidth('+fieldName+'_value, 15)\n'
                rowViewCode                    += '        addToContainer(rowBox, '+fieldName+'_value)\n'
                rowViewCode                    += '        showWidget('+fieldName+'_value)\n'
            elif fldCat=='int':
                funcTextToUpdateViewWidget     += ''
                funcTextToUpdateEditWidget     += '    dialog.' + widgetName + '.setValue('+structTypeName+'_ListData[N].'+fieldName+')\n'
                #funcTextToUpdateCrntFromWidget += '    me string: '+widgetName+'Str <- string(dialog.' + widgetName + '.getValue())\n'
                #funcTextToUpdateCrntFromWidget += '    crntRecord.'+fieldName+' <- dataStr\n'
                rowViewCode                    += '        their GUI_Frame: '+fieldName + '_value <- makeLabelWidget(toString(crntRecord.'+fieldName+').data())\n'
                rowViewCode                    += '        setLabelWidth('+fieldName+'_value, 15)\n'
                rowViewCode                    += '        addToContainer(rowBox, '+fieldName+'_value)\n'
                rowViewCode                    += '        showWidget('+fieldName+'_value)\n'
            else: print"pattern_MakeGUI.codeListWidgetManagerClassOverride fldCat not specified: ", fldCat;  exit(2)

###############
    CODE = 'struct '+listManagerStructName+''': inherits=ListWidgetManager{
    our <STRUCTNAME>: crntRecord
    our <STRUCTNAME>[our list]: <STRUCTNAME>_ListData
    me <STRUCTNAME>_Dialog_GUI: dialog
    their GUI_Frame:            listViewWidget
    their GUI_Frame[their list]:rows
    their GUI_Frame:            crntRow

    /- Override all these for each new list editing widget
    their GUI_Frame: makeListHeader() <- {
        their GUI_Frame: box <- makeFrameWidget()
        their GUI_Frame: headerRow <- makeRowWidget("")
        their GUI_Frame: headerBox <- makeXStackWidget("")
        <ROWHEADERCODE>
        addToContainer(headerRow, headerBox)
        addToContainer(box, headerRow)
        return(box)
    }

    their GUI_Frame: makeRowView(our <STRUCTNAME>: item) <- {
        crntRecord <- item
        their GUI_Frame: rowBox <- makeXStackWidget("")
        <ROWVIEWCODE>
        showWidget(rowBox)
        return(rowBox)
    }

    their listWidget: makeListViewWidget() <- {
        listViewWidget <- makeListWidget("")
        setListWidgetSelectionMode (listViewWidget, SINGLE)
        withEach item in <STRUCTNAME>_ListData {
            their GUI_Frame: row <- makeRowView(item)
            addToContainer(listViewWidget, row)
        }
        return(listViewWidget)
    }

    me int: pushCrntToList(me int: N) <- {
        <STRUCTNAME>_ListData.pushLast(crntRecord);
        me int: listLength <- getListLength()
        print("listLength: ", listLength)
        their GUI_Frame: row <- makeRowView(crntRecord)
        rows.pushLast(row)
        addToContainer(listViewWidget, row)
        return(listLength)
    }

    void: deleteNthRow(me int: N) <- {
        rows.deleteNth(N)
    }

    their GUI_Frame: getNthRow(me int: N) <-{
        crntRow <- rows[N]
    }

    me int: deleteNthItem(me int: N) <- {
        <STRUCTNAME>_ListData.deleteNth(N)
        me int: retVal <- getListLength()
        return(retVal)
    }

    void: updateViewableWidget() <- {<funcTextToUpdateViewWidget>}
    their GUI_item: makeEditableWidget() <- {return(dialog.make<STRUCTNAME>Widget(crntRecord))}
    void: updateEditableWidget(me int: N) <- {<funcTextToUpdateEditWidget>}
    void: updateCrntFromEdited(me int: N) <- {<funcTextToUpdateCrntFromWidget>}
    void: allocateNewCurrentItem() <- {Allocate(crntRecord)}
    void: copyCrntBackToList(me int: N) <- {<STRUCTNAME>_ListData[N] <- crntRecord}
    void: copyCrntBackToListView(me int: N) <- {
        print("copyCrntBackToListView ", N)
    }
    void: setCurrentItem(me int: idx) <- {crntRecord <- <STRUCTNAME>_ListData[idx]}
    void: setValue(our <STRUCTNAME>[our list]: ListData) <- {<STRUCTNAME>_ListData <- ListData}
    me int: getListLength() <- {return(<STRUCTNAME>_ListData.size())}

    their GUI_item: initWidget(our <STRUCTNAME>[our list]: Data) <- {
        <STRUCTNAME>_ListData <- Data
        Allocate(rows)
        return(ListEdBox.init_dialog(self))
    }
}
'''
    CODE = CODE.replace('<STRUCTNAME>', structTypeName)
    CODE = CODE.replace('<funcTextToUpdateViewWidget>', funcTextToUpdateViewWidget)
    CODE = CODE.replace('<funcTextToUpdateEditWidget>', funcTextToUpdateEditWidget)
    CODE = CODE.replace('<funcTextToUpdateCrntFromWidget>', funcTextToUpdateCrntFromWidget)
    CODE = CODE.replace('<funcTextToPushCrntToListView>', funcTextToPushCrntToListView)
    CODE = CODE.replace('<ROWHEADERCODE>', rowHeaderCode)
    CODE = CODE.replace('<ROWVIEWCODE>', rowViewCode)
    #print '==========================================================\n'+CODE
    codeDogParser.AddToObjectFromText(classes[0], classes[1], CODE, listManagerStructName)
Beispiel #5
0
def BuildGuiForStruct(classes, className, dialogStyle, newStructName):
    # This makes 4 types of changes to the class:
    #   It adds a widget variable for items in model // newWidgetFields: '    their '+typeName+': '+widgetName
    #   It adds a set Widget from Vars function      // widgetFromVarsCode: Func UpdateWidgetFromVars()
    #   It adds a set Vars from Widget function      // varsFromWidgetCode: Func UpdateVarsFromWidget()
    #   It add an initialize Widgets function.       // widgetInitFuncCode: widgetName+' <- '+makeTypeNameCall+'\n    addToContainer(box, '+widgetName+')\n'

    # dialogStyles: 'Z_stack', 'X_stack', 'Y_stack', 'TabbedStack', 'FlowStack', 'WizardStack', 'Dialog', 'SectionedDialogStack', 'V_viewable'
    # also, handle non-modal dialogs

    global classesEncoded
    global currentClassName
    global currentModelSpec
    classesEncoded[className]=1
    currentClassName = className

    # reset the string vars that accumulate the code
    global newWidgetFields
    global widgetInitFuncCode
    global widgetFromVarsCode
    global varsFromWidgetCode

    newWidgetFields=''
    widgetInitFuncCode=''
    widgetFromVarsCode=''
    varsFromWidgetCode=''

    # Find the model
    modelRef         = progSpec.findSpecOf(classes[0], className, 'model')
    currentModelSpec = modelRef
    if modelRef==None: cdErr('To build a GUI for class "'+className+'" a model is needed but is not found.')
    #TODO: write func body for: widgetFromVarsCode(selected item & click edit) & varsFromWidgetCode(ckick OK from editMode)
    ### Write code for each field
    for field in modelRef['fields']:
        typeSpec     = field['typeSpec']
        fldCat       = progSpec.fieldsTypeCategory(typeSpec)
        fieldName    = field['fieldName']
        labelText    = deCamelCase(fieldName)
        if fieldName=='settings':
            # add settings
            continue

        structTypeName=''
        if fldCat=='struct': # Add a new class to be processed
            structTypeName =typeSpec['fieldType'][0]
            if (progSpec.doesClassDirectlyImlementThisField(classes, structTypeName, structTypeName+':managedWidget')
                    or structTypeName.endswith('Widget')):
                fldCat = 'widget'
            else:
                newGUIStyle    = 'Dialog'
                guiStructName  = structTypeName+'_'+newGUIStyle+'_GUI'
                addNewStructToProcess(guiStructName, structTypeName, 'struct', 'Dialog')

        if fldCat != 'widget' and progSpec.isAContainer(typeSpec):# Add a new list to be processed
            structTypeName = typeSpec['fieldType'][0]
            guiStructName  = structTypeName+'_LIST_View'
            addNewStructToProcess(guiStructName, structTypeName, 'list', 'Dialog')

        #TODO: make actions for each function
        if fldCat=='func':
            if fieldName[-4:]== '_btn':
                buttonLabel = deCamelCase(fieldName[:-4])
                # Add a button whose click calls this.
                print "ADDING BUTTON FOR:", fieldName
                getButtonHandlingCode(classes, buttonLabel, fieldName)

        else: # Here is the main case where code to edit this field is written
            getWidgetHandlingCode(classes, fldCat, fieldName, field, structTypeName, dialogStyle, '')

    # Parse everything
    initFuncName = 'make'+className[0].upper() + className[1:]+'Widget'
    if dialogStyle == 'Z_stack': containerWidget='makeStoryBoardWidget("makeStoryBoardWidget")'
    elif dialogStyle == 'TabbedStack': containerWidget='makeTabbedWidget("makeTabbedWidget")'
    else: containerWidget='makeFrameWidget()'


    CODE =  '''
struct <CLASSNAME> {}
struct <NEWSTRUCTNAME> {
    <NEWWIDGETFIELDS>
    our <CLASSNAME>: <CLASSNAME>_data
    their GUI_Frame: <INITFUNCNAME>(our <CLASSNAME>: Data) <- {
        <CLASSNAME>_data<-Data
        their GUI_Frame:box <- <CONTAINERWIDGET>
        <WIDGETINITFUNCCODE>
        return(box)
    }
    void: setValue(our <CLASSNAME>: var) <- {
        <WIDGETFROMVARSCODE>
    }
    void: getValue() <- {
        <VARSFROMWIDGETCODE>
    }
}\n'''  # TODO: add <VARSFROMWIDGETCODE>

    CODE = CODE.replace('<NEWSTRUCTNAME>', newStructName)
    CODE = CODE.replace('<NEWWIDGETFIELDS>', newWidgetFields)
    CODE = CODE.replace('<CLASSNAME>', className)
    CODE = CODE.replace('<WIDGETINITFUNCCODE>', widgetInitFuncCode)
    CODE = CODE.replace('<INITFUNCNAME>', initFuncName)
    CODE = CODE.replace('<WIDGETFROMVARSCODE>', widgetFromVarsCode)
    CODE = CODE.replace('<VARSFROMWIDGETCODE>', varsFromWidgetCode)
    CODE = CODE.replace('<CONTAINERWIDGET>', containerWidget)
    if newStructName == "EntryPad_Dialog_GUI":print '==========================================================\n'+CODE
    codeDogParser.AddToObjectFromText(classes[0], classes[1], CODE, newStructName)
Beispiel #6
0
def BuildGuiForList(classes, className, dialogStyle, newStructName):
    # This makes 4 types of changes to the class:
    #   It adds a widget variable for items in model // newWidgetFields: '    their '+typeName+': '+widgetName
    #   It adds a set Widget from Vars function      // widgetFromVarsCode: Func UpdateWidgetFromVars()
    #   It adds a set Vars from Widget function      // varsFromWidgetCode: Func UpdateVarsFromWidget()
    #   It add an initialize Widgets function.       // widgetInitFuncCode: widgetName+' <- '+makeTypeNameCall+'\n    addToContainer(box, '+widgetName+')\n'

    # dialogStyles: 'Z_stack', 'X_stack', 'Y_stack', 'TabbedStack', 'FlowStack', 'WizardStack', 'Dialog', 'SectionedDialogStack'
    # also, handle non-modal dialogs

    global classesEncoded
    global currentClassName
    global currentModelSpec
    classesEncoded[className]=1
    currentClassName = className

    # reset the string vars that accumulate the code
    global newWidgetFields
    global widgetInitFuncCode
    global widgetFromVarsCode
    global varsFromWidgetCode

    newWidgetFields=''
    widgetInitFuncCode=''
    widgetFromVarsCode=''
    varsFromWidgetCode=''

    # Find the model
    modelRef            = progSpec.findSpecOf(classes[0], className, 'model')
    if modelRef==None: cdErr('To build a GUI for a list of "'+className+'" a model is needed but is not found.')
    currentModelSpec    = modelRef
    rowHeaderCode       = ''
    rowViewCode         = ''
    for field in modelRef['fields']:
        fieldName       = field['fieldName']
        typeSpec        = field['typeSpec']
        fldCat          = progSpec.fieldsTypeCategory(typeSpec)
        fieldType       = progSpec.fieldTypeKeyword(field['typeSpec']['fieldType'])
        [fieldSpec, params] = getFieldSpec(fldCat, field)
        structTypeName  =''
        if fldCat=='struct': # Add a new class to be processed
            structTypeName =typeSpec['fieldType'][0]
            newGUIStyle    = 'Dialog'
            guiStructName  = structTypeName+'_'+newGUIStyle+'_GUI'
            addNewStructToProcess(guiStructName, structTypeName, 'struct', 'Dialog')

        if progSpec.isAContainer(typeSpec):# Add a new list to be processed
            structTypeName = typeSpec['fieldType'][0]
            guiStructName  = structTypeName+'_LIST_View'
            addNewStructToProcess(guiStructName, structTypeName, 'list', 'Dialog')


    CODE =  '''struct <NEWSTRUCTNAME>{
    our <CLASSNAME>[our list]: <CLASSNAME>_ListData
    our <CLASSNAME>:   crntRecord
}
'''

    CODE = CODE.replace('<NEWSTRUCTNAME>', newStructName)
    CODE = CODE.replace('<CLASSNAME>', className)
    CODE = CODE.replace('<NEWWIDGETFIELDS>', newWidgetFields)
    CODE = CODE.replace('<WIDGETFROMVARSCODE>', widgetFromVarsCode)
    CODE = CODE.replace('<VARSFROMWIDGETCODE>', varsFromWidgetCode)
    #print '==========================================================\n'+CODE
    codeDogParser.AddToObjectFromText(classes[0], classes[1], CODE, newStructName)
Beispiel #7
0
def findModelRef(classes, structTypeName):
    modelRef = progSpec.findSpecOf(classes, structTypeName, 'model')
    if modelRef == None:
        cdErr('To build a list GUI for list of "' + structTypeName +
              '" a model is needed but is not found.')
    return modelRef
Beispiel #8
0
def Write_fieldExtracter(classes, ToStructName, field, memObjFields, VarTagBase, VarName, advancePtr, indent, level, logLvl):
    debugTmp=False # Erase this line
    VarTag=VarTagBase+str(level)
    ###################   G a t h e r   N e e d e d   I n f o r m a t i o n
    global  globalFieldCount
    global  globalTempVarIdx
    S=''
    fieldName  = field['fieldName']
    fieldIsNext= field['isNext']
    fieldValue = field['value']
    typeSpec   = field['typeSpec']
    fieldType  = progSpec.getFieldType(typeSpec)
    fieldOwner =typeSpec['owner']
    fromIsEmbeddedAlt = (not isinstance(fieldType, str) and fieldType[0]=='[')
    fromIsEmbeddedSeq = (not isinstance(fieldType, str) and fieldType[0]=='{')
    fromIsEmbedded    = fromIsEmbeddedAlt or fromIsEmbeddedSeq

    if(fieldIsNext!=True): return '' # This field isn't in the parse stream.

    [memObj, memVersionName]=fetchMemVersion(classes, ToStructName)

    toField = progSpec.fetchFieldByName(memObjFields, fieldName)
    if(toField==None):
        #print "   TOFIELD == None", fieldName
        # Even tho there is no LVAL, we need to move the cursor. Also, there could be a co-factual.
        toFieldType = progSpec.TypeSpecsMinimumBaseType(classes, typeSpec)
        toTypeSpec=typeSpec
        toFieldOwner="me"
    else:
        toTypeSpec   = toField['typeSpec']
        toFieldType  = progSpec.getFieldType(toTypeSpec)
        toFieldOwner = progSpec.getInnerContainerOwner(toTypeSpec)

        if debugTmp:
            print('        toFieldType:', toFieldType)

    LHS_IsPointer=progSpec.typeIsPointer(toTypeSpec)

   # print "        CONVERTING:", fieldName, str(toFieldType)[:100]+'... ', str(typeSpec)[:100]+'... '
   # print "            TOFieldTYPE1:", str(toField)[:100]
   # print "            TOFieldTYPE :", toFieldOwner, toFieldType
   # print "       fieldValue:",ToStructName, fieldType, fieldValue
    cdlog(logLvl, "FIELD {}: '{}'".format(fieldName, str(fieldValue)))

    fields=[]
    fromIsStruct=progSpec.isStruct(fieldType)
    toIsStruct=progSpec.isStruct(toFieldType)
    ToIsEmbedded = toIsStruct and (toFieldType[0]=='[' or toFieldType[0]=='{')
    [fromIsALT, fields] = progSpec.isAltStruct(classes, fieldType)
    fromIsOPT =False
    fromIsList=False
    toIsList  =False
    if progSpec.isAContainer(typeSpec):
        datastructID = progSpec.getDatastructID(typeSpec)
        if datastructID=='opt': fromIsOPT=True;
        else: fromIsList=True

    if progSpec.isAContainer(toTypeSpec):
        if datastructID != 'opt': toIsList=True

    if debugTmp:
        print('        fromIsOPT:', fromIsOPT)
        print('        fromIsList:', fromIsList)
        print('        toIsList:', toIsList)
        print('        fromIsStruct:', fromIsStruct)
        print('        toIsStruct:', toIsStruct)
        print('        fieldType:', fieldType)
        print('        ToIsEmbedded:', ToIsEmbedded)
        print('        ToStructName:', ToStructName)
        print('        memVersionName:', memVersionName, "\n")
    ###################   W r i t e   L V A L   R e f e r e n c e
    finalCodeStr=''
    CodeLVAR_Alloc=''
    CODE_LVAR_v2=''
    if VarName=='' or VarName=='memStruct':  # Default to the target argument name
        #if VarName=='': print "        VARNAME was ''; FIELDNAME:", fieldName
        VarName='memStruct'
        if(fieldName==None): # Field hasn't a name so in memory it's a cofactual or this is a parser marker.
            globalFieldCount+=1
            # We need two versions in case this is set in a function instead of assignment
            CODE_LVAR_v2 = 'S'+str(globalFieldCount)
            CodeLVAR_Alloc='    me string: '+CODE_LVAR_v2
            CODE_LVAR = CodeLVAR_Alloc
            if debugTmp: print('        CODE_LVARS:', CODE_LVAR)
        else:
            CODE_LVAR = VarName+'.'+fieldName
            if fieldName=='inf': CODE_LVAR = VarName
            CODE_LVAR_v2 = CODE_LVAR
    else:
        CODE_LVAR = VarName
        CODE_LVAR_v2 = CODE_LVAR

    ###################   W r i t e   R V A L   C o d e
    CODE_RVAL=''
    objName=''
    humanIDType= VarTag+' ('+str(fieldName)+' / '+str(fieldValue) + ' / '+str(fieldType)[:40] +')'
    humanIDType=humanIDType.replace('"', "'")
    #print humanIDType

    if advancePtr:
        S+=indent+VarTag+' <- getNextStateRec('+VarTag+')\n'
        # UNCOMMENT FOR DEGUG: S+='    docPos('+str(level)+', '+VarTag+', "Get Next in SEQ for: '+humanIDType+'")\n'


    if fieldOwner=='const'and (toField == None):
        #print'CONSTFIELDVALUE("'+fieldValue+'")\n'
        finalCodeStr += indent + 'tmpStr'+' <- makeStr('+VarTag+"<LVL_SUFFIX>"+'.child)\n'

    else:
        if toIsStruct:
            if debugTmp: print('        toFieldType:', toFieldType)
            if not ToIsEmbedded:
                objName=toFieldType[0]
                if  progSpec.typeIsInteger(objName):
                    strFieldType = fieldType[0]
                    if(strFieldType == "BigInt"):
                        CODE_RVAL='makeStr('+VarTag+'.child'+')'
                    elif(strFieldType == "HexNum"):
                        CODE_RVAL='makeHexInt('+VarTag+'.child'+')'
                    elif(strFieldType == "BinNum"):
                        CODE_RVAL='makeBinInt('+VarTag+'.child'+')'
                    else:
                        CODE_RVAL='makeStr('+VarTag+'.child'+')'
                    toIsStruct=False; # false because it is really a base type.
                elif (objName=='ws' or objName=='wsc' or objName=='quotedStr1' or objName=='quotedStr2' or objName=='CID' or objName=='UniID'
                      or objName=='printables' or objName=='toEOL' or objName=='alphaNumSeq'):
                    CODE_RVAL='makeStr('+VarTag+'.child'+')'
                    toIsStruct=False; # false because it is really a base type.
                else:
                    #print "toObjName:", objName, memVersionName, fieldName
                    [toMemObj, toMemVersionName]=fetchMemVersion(classes, objName)
                    if toMemVersionName==None:
                        # make alternate finalCodeStr. Also, write the extractor that extracts toStruct fields to memVersion of this
                        childStr = ".child"
                        if fromIsOPT:
                            childStr += ".next"
                        finalCodeStr=(indent + CodeLVAR_Alloc + '\n' +indent+'    '+getFunctionName(fieldType[0], memVersionName)+'('+VarTag+"<LVL_SUFFIX>"+childStr+', memStruct)\n')
                        objSpec = progSpec.findSpecOf(classes[0], objName, 'string')
                        ToFields=objSpec['fields']
                        FromStructName=objName
                        Write_Extracter(classes, ToStructName, FromStructName, logLvl+1)
                    else:
                        fromFieldTypeCID = fieldType[0].replace('::', '_')
                        toFieldTypeCID = toMemVersionName.replace('::', '_')
                        #print "FUNC:", getFunctionName(fromFieldTypeCID, toFieldTypeCID)
                        if fromFieldTypeCID != toFieldTypeCID:
                            Write_Extracter(classes, toFieldTypeCID, fromFieldTypeCID, logLvl+1)
                        finalCodeStr=indent + CodeLVAR_Alloc + '\n' +indent+'    '+getFunctionName(fromFieldTypeCID, toFieldTypeCID)+'('+VarTag+"<LVL_SUFFIX>"+'.child, '+CODE_LVAR_v2+')\n'
            else: pass

        else:
            CODE_RVAL = CodeRValExpr(toFieldType, VarTag, "")


    #print "CODE_RVAL:", CODE_RVAL

    ###################   H a n d l e   o p t i o n a l   a n d   r e p e t i t i o n   a n d   a s s i g n m e n t   c a s e s
    gatherFieldCode=''
    if fromIsList and toIsList:
        CODE_RVAL='tmpVar'
        globalFieldCount +=1
        childRecName='SRec' + str(globalFieldCount)
        gatherFieldCode+='\n'+indent+'\nour stateRec: '+childRecName+' <- '+VarTag+'.child.next'
        gatherFieldCode+='\n'+indent+'while('+childRecName+'){\n'
        if fromIsALT:
          #  print "ALT-#1"
            gatherFieldCode+=Write_ALT_Extracter(classes, fieldType[0], fields, childRecName, '', 'tmpVar', indent+'    ', level)

        elif fromIsStruct and toIsStruct:
            gatherFieldCode+='\n'+indent+toFieldOwner+' '+progSpec.baseStructName(toFieldType[0])+': tmpVar'
            if toFieldOwner!='me':
                gatherFieldCode+='\n'+indent+'Allocate('+CODE_RVAL+')'
            #print "##### FUNCT:", getFunctionName(fieldType[0], fieldType[0])
            gatherFieldCode+='\n'+indent+getFunctionName(fieldType[0], toFieldType[0])+'('+childRecName+'.child, tmpVar)\n'

        else:
            CODE_RVAL = CodeRValExpr(toFieldType, childRecName, ".next")

        # Now code to push the chosen alternative into the data field# This is a LIST, not an OPT:
        gatherFieldCode+='\n'+indent+CODE_LVAR+'.pushLast('+CODE_RVAL+')'

        gatherFieldCode+=indent+'    '+childRecName+' <- getNextStateRec('+childRecName+')\n'
        # UNCOMMENT FOR DEGUG: S+= '    docPos('+str(level)+', '+VarTag+', "Get Next in LIST for: '+humanIDType+'")\n'


        gatherFieldCode+='\n'+indent+'}\n'
        if(fromIsOPT):
            print("Handle when the optional item is a list.");
            exit(2)
    else:
        if toIsList: print("Error: parsing a non-list to a list is not supported.\n"); exit(1);
        levelSuffix=''
        assignerCode=''
        oldIndent=indent
        if (fromIsOPT):
            setTrueCode=''
            assignerCode+='\n'+indent+'if('+VarTag+'.child.next' +' == NULL){'
            if toFieldOwner=='me':
                if debugTmp: print('        toFieldOwner:', toFieldOwner)
                ## if fieldName==None and a model of fromFieldType has no cooresponding model But we are in EXTRACT_ mode:
                        ## Make a special form of Extract_fromFieldType_to_ToFieldType()
                        ## Call that function instead of the one in Code_LVAR
                # First, create a new flag field
                if fieldName==None:
                    fieldName="TEMP"+str(globalTempVarIdx)
                    globalTempVarIdx += globalTempVarIdx
                newFieldsName=fieldName   #'has_'+fieldName
                fieldDef=progSpec.packField(ToStructName, False, 'me', 'flag', None, None, newFieldsName, None, None, None, False)
                progSpec.addField(classes[0], memVersionName, 'struct', fieldDef)

                # Second, generate the code to set the flag
                assignerCode+='\n'+indent+'    '+VarName+'.'+newFieldsName+' <- false'
                setTrueCode += VarName+'.'+newFieldsName+' <- true'
            elif LHS_IsPointer: # If owner is my, our or their
                assignerCode+='\n'+indent+'    '+CODE_LVAR+' <- NULL'
            else:
                print("ERROR: OPTional fields must not be '"+toFieldOwner+"'.\n")
                exit(1)
            assignerCode+='\n'+indent+'} else {\n'
            levelSuffix='.child.next'
            indent+='    '
            assignerCode+=indent+setTrueCode+'\n'


        if fromIsALT or fromIsEmbeddedAlt:
            if(fromIsEmbeddedAlt):
               # print "ALT-#2"
                assignerCode+=Write_ALT_Extracter(classes, ToStructName, field['innerDefs'], VarTagBase, levelSuffix, VarName, indent+'    ', level+1, logLvl+1)
            else:
              #  print "ALT-#3"
                assignerCode+=Write_ALT_Extracter(classes, fieldType[0], fields, VarTagBase, levelSuffix, VarName+'X', indent+'    ', level, logLvl+1)
                assignerCode+=indent+CODE_LVAR+' <- '+(VarName+'X')+"\n"
        elif fromIsEmbeddedSeq:
            globalFieldCount +=1
            childRecNameBase='childSRec' + str(globalFieldCount)
            childRecName=childRecNameBase+str(level)
            assignerCode+='\n'+indent+'our stateRec: '+childRecName+' <- '+VarTag+levelSuffix+'.child\n'
            for innerField in field['innerDefs']:
                assignerCode+=Write_fieldExtracter(classes, ToStructName, innerField, memObjFields, childRecNameBase, '', True, '    ', level, logLvl+1)
        elif fromIsStruct and toIsStruct:
            assignerCode+=finalCodeStr.replace("<LVL_SUFFIX>", levelSuffix);
            if debugTmp: print('        assignerCode:', assignerCode)
        else:
           # if toFieldOwner == 'const': print "Error: Attempt to extract a parse to const field.\n"; exit(1);
            if CODE_RVAL!="":
                if LHS_IsPointer:
                    assignerCode+='        '+CODE_LVAR+' <deep- '+CODE_RVAL+"\n"
                else: assignerCode+='        '+CODE_LVAR+' <- '+CODE_RVAL+"\n"
            elif finalCodeStr!="": assignerCode+=finalCodeStr.replace("<LVL_SUFFIX>", levelSuffix);

        if (fromIsOPT):
            indent=oldIndent
            assignerCode += indent+'}\n'
            #print '######################\n'+assignerCode, memVersionName, '\n'
           # exit(2)
        gatherFieldCode = assignerCode
    #print ("##########################\n",S,"\n#####################################\n")
    if LHS_IsPointer: # LVAL is a pointer and should be allocated or cleared.
        S+= indent + 'AllocateOrClear(' +CODE_LVAR +')\n'

    S+=gatherFieldCode
    #print "ASSIGN_CODE", S
 #   if debugTmp: exit(2)
    return S
Beispiel #9
0
def fetchMemVersion(classes, objName):
    if objName=='[' or objName=='{': return [None, None]
    memObj = progSpec.findSpecOf(classes[0], objName, 'struct')
    if memObj==None: return [None, None]
    return [memObj, objName]
def findStructRef(classes, structTypeName):
    structRef = progSpec.findSpecOf(classes, structTypeName, 'struct')
    if structRef==None:
        cdErr('To build a list GUI for list of "'+structTypeName+'" a struct is needed but is not found.')
    return structRef