示例#1
0
def checkForTypeCastNeed(LHS_Type, RHS_Type, codeStr):
    LHS_KeyType = progSpec.fieldTypeKeyword(LHS_Type)
    RHS_KeyType = progSpec.fieldTypeKeyword(RHS_Type)
    if LHS_KeyType == 'bool' and progSpec.typeIsPointer(RHS_KeyType):
        return '(' + codeStr + ' != null)'
    if LHS_KeyType == 'bool' and RHS_KeyType == 'int':
        return '(' + codeStr + ' != 0)'
    return codeStr
示例#2
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)
示例#3
0
def buildListRowView(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
    global clearWidgetCode

    newWidgetFields = ''
    widgetInitFuncCode = ''
    widgetFromVarsCode = ''
    varsFromWidgetCode = ''
    clearWidgetCode = ''
    funcTextToUpdateViewWidget = ''
    funcTextToUpdateEditWidget = ''
    funcTextToUpdateCrntFromWidget = ''

    # Find the model
    modelRef = findModelRef(classes[0], className)
    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 + '_ROW_View'
            addNewStructToProcess(guiStructName, structTypeName, 'list',
                                  'Dialog')
        else:
            print("field::", fieldName, fldCat)
            if (fldCat != 'struct'):
                rowHeaderCode += '        their GUI_Label: ' + fieldName + '_header <- makeLabelWidget("' + fieldName + '")\n'
                rowHeaderCode += '        setLabelWidth(' + fieldName + '_header, 15)\n'
                rowHeaderCode += '        addToContainer(headerBox, ' + fieldName + '_header)\n'
            if fldCat == 'struct':
                funcTextToUpdateViewWidget += ''
            elif fldCat == 'enum' or fldCat == 'mode':
                funcTextToUpdateViewWidget += ''
                #funcTextToUpdateEditWidget     += ''
                funcTextToUpdateCrntFromWidget += ''  #  crntRecord.'+fieldName+' <- dialog.' + widgetName + '.getValue()\n'
            elif fldCat == 'bool':
                funcTextToUpdateViewWidget += ''
            elif fldCat == 'string':
                #funcTextToUpdateViewWidget     += ''
                #funcTextToUpdateEditWidget     += '    dialog.' + widgetName + '.setValue('+structTypeName+'_ListData[N].'+fieldName+')\n'
                #funcTextToUpdateCrntFromWidget += '    me string: '+widgetName+'Str <- dialog.' + widgetName + '.getValue()\n'
                #funcTextToUpdateCrntFromWidget += '    crntRecord.'+fieldName+' <- '+widgetName+'Str\n'
                rowViewCode += '        their GUI_Label: ' + fieldName + '_value <- makeLabelWidget2(Data.' + fieldName + ')\n'
                rowViewCode += '        setLabelWidth(' + fieldName + '_value, 15)\n'
                rowViewCode += '        addToContainer(box, ' + 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_Label: ' + fieldName + '_value <- makeLabelWidget2(toString(Data.' + fieldName + '))\n'
                rowViewCode += '        setLabelWidth(' + fieldName + '_value, 15)\n'
                rowViewCode += '        addToContainer(box, ' + fieldName + '_value)\n'
                rowViewCode += '        showWidget(' + fieldName + '_value)\n'
            else:
                print(
                    'pattern_MakeGUI.codeListWidgetManagerClassOverride fldCat not specified: ',
                    fldCat)
                exit(2)

    CODE = '''struct ''' + newStructName + '''{
    their GUI_Frame:            box
    their GUI_Frame: makeHeaderView() <- {
        their GUI_Frame: headerBox <- makeXStack("")
        ''' + rowHeaderCode + '''
        showWidget(headerBox)
        return(headerBox)
    }
    their GUI_Frame: initWidget(their ''' + className + ''': Data) <- {
        box <- makeXStack("")
        ''' + rowViewCode + '''
        showWidget(box)
        return(box)
    }
}
'''
    #print ('==========================================================\n'+CODE)
    codeDogParser.AddToObjectFromText(classes[0], classes[1], CODE,
                                      newStructName)
示例#4
0
def Write_fieldExtracter(classes, ToStructName, field, memObjFields,
                         VarTagBase, VarName, advancePtr, coFactualCode,
                         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']
        if progSpec.isNewContainerTempFunc(toTypeSpec):
            toFieldType = progSpec.getNewContainerFirstElementTypeTempFunc2(
                toTypeSpec)
            toFieldOwner = progSpec.getNewContainerFirstElementOwnerTempFunc(
                toTypeSpec)
        else:
            toFieldType = progSpec.getFieldType(toTypeSpec)
            toFieldOwner = progSpec.getContainerFirstElementOwner(toTypeSpec)

        if debugTmp:
            print('        toFieldType:', toFieldType)
    fTypeKW = progSpec.fieldTypeKeyword(fieldType)
    toFTypeKW = progSpec.fieldTypeKeyword(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)
    toIsBaseType = progSpec.isBaseType(toFieldType)
    ToIsEmbedded = (not toIsBaseType) and (toFieldType[0] == '['
                                           or toFieldType[0] == '{')
    [fromIsALT, fields] = progSpec.isAltStruct(classes, fieldType)
    fromIsOPT = False
    fromIsList = False
    toIsList = False
    optionalWhiteSpace = 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('        toIsBaseType:', toIsBaseType)
        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 + ', EP)\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, EP)\n'

    else:
        if not toIsBaseType:
            if debugTmp: print('        toFieldType:', toFieldType)
            if not ToIsEmbedded:
                objName = progSpec.fieldTypeKeyword(toFieldType)
                if progSpec.typeIsInteger(objName):
                    strFieldType = progSpec.fieldTypeKeyword(fieldType)
                    if (strFieldType == "HexNum"):
                        CODE_RVAL = 'makeHexInt(' + VarTag + '.child.next' + ', EP)'
                    elif (strFieldType == "BinNum"):
                        CODE_RVAL = 'makeBinInt(' + VarTag + '.child.next' + ', EP)'
                    else:
                        CODE_RVAL = 'makeStr(' + VarTag + '.child.next' + ', EP)'
                    toIsBaseType = True
                    # it is really a base type.
                elif (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.next' + ', EP)'
                    toIsBaseType = True
                    # it is really a base type.
                elif (objName == 'ws' or objName == 'wsc'):
                    CODE_RVAL = 'makeStr(' + VarTag + '.child.next' + ', EP)'
                    optionalWhiteSpace = True
                    toIsBaseType = True
                    # 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
                        finalCodeStr = (
                            indent + CodeLVAR_Alloc + '\n' + indent + '    ' +
                            getFunctionName(fTypeKW, memVersionName) +
                            '(getChildStateRec(' + VarTag + "<LVL_SUFFIX>" +
                            ', EP), memStruct, EP)\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
                        ) + '(getChildStateRec(' + VarTag + "<LVL_SUFFIX>" + ', EP), ' + CODE_LVAR_v2 + ', EP)\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'
        gatherFieldCode += '\n' + indent + 'while(' + childRecName + ' != NULL and getNextStateRec(' + childRecName + ', EP) !=NULL){\n'
        if fromIsALT:
            gatherFieldCode += Write_ALT_Extracter(classes, fTypeKW, fields,
                                                   childRecName, '', 'tmpVar',
                                                   indent + '    ', level)
            gatherFieldCode += '\n' + indent + CODE_LVAR + '.append(' + CODE_RVAL + ')'
        elif fromIsStruct and not toIsBaseType:
            gatherFieldCode += '\n' + indent + toFieldOwner + ' ' + progSpec.baseStructName(
                toFTypeKW) + ': tmpVar'
            if toFieldOwner != 'me':
                gatherFieldCode += '\n' + indent + 'Allocate(' + CODE_RVAL + ')'
            gatherFieldCode += '\n' + indent + CODE_LVAR + '.append(' + CODE_RVAL + ')'
            #print "##### FUNCT:", getFunctionName(fTypeKW, toFTypeKW)
            gatherFieldCode += '\n' + indent + getFunctionName(
                fTypeKW, toFTypeKW
            ) + '(getChildStateRec(' + childRecName + ', EP) , tmpVar, EP)\n'
            PP_FuncName = getPostParseFunctionName(classes, toFTypeKW)
            if PP_FuncName != None:
                gatherFieldCode += '\n' + indent + 'if(!' + CODE_RVAL + '.postParseProcessed){' + PP_FuncName + '_' + toFTypeKW + '(' + CODE_RVAL + ', SRec0)}'
        else:
            CODE_RVAL = CodeRValExpr(toFieldType, childRecName, ".next")
            gatherFieldCode += '\n' + indent + CODE_LVAR + '.append(' + CODE_RVAL + ')'

        gatherFieldCode += indent + '    ' + childRecName + ' <- getNextStateRec(' + childRecName + ', EP)\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' + ' == NULL or ' + 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, 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'
            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"
                fTypeKW = progSpec.fieldTypeKeyword(fieldType)
                assignerCode += Write_ALT_Extracter(classes, fTypeKW, 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'
            advance = False
            for innerField in field['innerDefs']:
                assignerCode += Write_fieldExtracter(classes, ToStructName,
                                                     innerField, memObjFields,
                                                     childRecNameBase, '',
                                                     advance, coFactualCode,
                                                     '    ', level, logLvl + 1)
                advance = True
        elif fromIsStruct and not toIsBaseType:
            assignerCode += finalCodeStr.replace("<LVL_SUFFIX>", levelSuffix)
            if debugTmp: print('        assignerCode:', assignerCode)
        elif optionalWhiteSpace:
            assignerCode += '\n' + indent + 'if(' + VarTag + '.child' + ' != NULL){' + CODE_LVAR + ' <- ' + CODE_RVAL + '}\n'
        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 += coFactualCode
    S += gatherFieldCode
    #print "ASSIGN_CODE", S
    #   if debugTmp: exit(2)
    return S
示例#5
0
def fetchOrWriteTerminalParseRule(modelName, field, logLvl):
    global nextParseNameID
    #print "FIELD_IN:", modelName, field
    fieldName = 'N/A'
    fieldValue = ''
    if 'value' in field: fieldValue = field['value']
    typeSpec = field['typeSpec']
    fieldType = progSpec.getFieldType(typeSpec)
    fieldOwner = typeSpec['owner']
    if 'fieldName' in field: fieldName = field['fieldName']
    cdlog(logLvl, "WRITING PARSE RULE for: {}.{}".format(modelName, fieldName))
    #print "WRITE PARSE RULE:", modelName, fieldName

    nameIn = None
    nameOut = None
    if fieldOwner == 'const':
        if fieldType == 'string':
            if fieldValue in definedRules: nameOut = definedRules[fieldValue]
            else: nameOut = appendRule(nameIn, "term", "parseSEQ", fieldValue)
        elif fieldType[0:4] == 'uint':
            nameOut = appendRule(nameIn, "term", "parseSEQ", fieldValue)
        elif fieldType[0:3] == 'int':
            nameOut = appendRule(nameIn, "term", "parseSEQ", fieldValue)
        elif fieldType[0:6] == 'double':
            nameOut = appendRule(nameIn, "term", "parseSEQ", fieldValue)
        elif fieldType[0:4] == 'char':
            nameOut = appendRule(nameIn, "term", "parseSEQ", fieldValue)
        elif fieldType[0:4] == 'bool':
            nameOut = appendRule(nameIn, "term", "parseSEQ", fieldValue)
        else:
            print("Unusable const type in fetchOrWriteTerminalParseRule():",
                  fieldType)
            exit(2)

    elif fieldOwner == 'me' or fieldOwner == 'their' or fieldOwner == 'our':
        if fieldType == 'string': nameOut = 'quotedStr'
        elif fieldType[0:4] == 'uint': nameOut = 'uintSeq'
        elif fieldType[0:3] == 'int': nameOut = 'intSeq'
        elif fieldType[0:6] == 'double': nameOut = 'RdxSeq'
        elif fieldType[0:4] == 'char':
            nameOut = appendRule(nameIn, "term", "parseSEQ", None)
        elif fieldType[0:4] == 'bool':
            nameOut = appendRule(nameIn, "term", "parseSEQ", None)
        elif progSpec.isStruct(fieldType):
            objName = progSpec.fieldTypeKeyword(fieldType)
            if (objName == 'ws' or objName == 'wsc' or objName == 'quotedStr'
                    or objName == 'quotedStr1' or objName == 'quotedStr2'
                    or objName == 'CID' or objName == 'UniID'
                    or objName == 'printables' or objName == 'toEOL'
                    or objName == 'alphaNumSeq'
                    or progSpec.typeIsInteger(objName)):
                nameOut = objName
            else:
                if objName == '[' or objName == '{':  # This is an ALT or SEQ sub structure
                    print(
                        "ERROR: These should be handled in writeNonTermParseRule().\n"
                    )
                    exit(1)
                else:
                    nameOut = objName + '_str'
        elif progSpec.isAlt(fieldType):
            pass
        elif progSpec.isCofactual(fieldType):
            pass
        else:
            print("Unusable type in fetchOrWriteTerminalParseRule():",
                  fieldType)
            exit(2)
    else:
        print(
            "Pointer types not yet handled in fetchOrWriteTerminalParseRule():",
            fieldType)
        exit(2)

    if progSpec.isAContainer(typeSpec):
        global rules
        containerTypeSpec = progSpec.getContainerSpec(typeSpec)
        idxType = ''
        if 'indexType' in containerTypeSpec:
            idxType = containerTypeSpec['indexType']
        if (isinstance(containerTypeSpec['datastructID'], str)):
            datastructID = containerTypeSpec['datastructID']
        else:  # it's a parseResult
            datastructID = containerTypeSpec['datastructID'][0]
        if idxType[0:4] == 'uint': pass
        if (datastructID == 'list'):
            nameOut = appendRule(nameOut + '_REP', "nonterm", "parseREP",
                                 [nameOut, 0, 0])
        elif datastructID == 'opt':
            nameOut = appendRule(nameOut + '_OPT', "nonterm", "parseREP",
                                 [nameOut, 0, 1])
            #print("NAMEOUT:", nameOut)
    field['parseRule'] = nameOut
    return nameOut