firmware_tools/logic_memory_mapper/gen_elhal.py

453 lines
21 KiB
Python

# -----------------------------------------------------------------------------
# Title : EL C++ HAL class generator
# Project : Generic FW tools
# -----------------------------------------------------------------------------
# File : gen_elhal.py
# Author : Simon Southwell
# Company : Global Inkjet Systems
# Created : 2018-03-15
# Created : 2018-03-15
# Last update: 2018-03-15
# Platform :
# Standard : Python 3.x
# -----------------------------------------------------------------------------
# Description:
# Definition of class to read JSON register definitions and generate a set
# of C++ access class declarations. Inherits MemMapperBase for methods to
# read JSON files and produce a model.
# -----------------------------------------------------------------------------
# Copyright (c) 2017 Global Inkjet Systems
# -----------------------------------------------------------------------------
import os
import sys
import argparse
# Import base class to locate and read JSON files, and present a model
# to derived child class.
import memMapperBase
from memMapperBase import MemMapperBase, attr, regtype
from gen_cpp import MemMapperCpp
# ---------------------------------------------------------
# ---------------------------------------------------------
class MemMapperElHal(MemMapperBase):
def __init__(self):
print('MemMapperElHal')
self.__useByteAddrs = False
self.__enableTag = ''
self.__classSuffix = 'Auto'
MemMapperBase.__init__(self)
# ---------------------------------------------------------
# ---------------------------------------------------------
def setDerivedClassOn(self):
self.__classSuffix = ''
# ---------------------------------------------------------
# Configure the byte address output mode
# ---------------------------------------------------------
def setByteAddrMode(self, mode):
self.__useByteAddrs = mode
def setEnableTag(self, enableTag):
self.__enableTag = enableTag
# ---------------------------------------------------------
# Genereate a field name string from data
# ---------------------------------------------------------
@staticmethod
def __genFieldNameStr(bus, ip, regName, fieldName) :
regNameNoSpaces = regName.replace(' ', '')
if regName == fieldName :
field = 'value'
else :
field = fieldName
fieldNameStr = bus.upper() + '_' + ip.upper() + '_' + regNameNoSpaces.upper() + '_' + field.upper()
return fieldNameStr
# ---------------------------------------------------------
# Overload virtual function with specific output generation,
# and generate a C/C++ header file with some useful
# constants in it.
# ---------------------------------------------------------
def genOutput(self, ip, opDir='', opSuffix=''):
# colWidth = 60
ipCC = self._underScore2CamelCase(ip)
# ipLCC = self._underScore2LowCamelCase(ip)
# ipCAP = ip.capitalize()
# Fetch the JSON path and the dictionary with the parsed data
jsonPath, jsonDict = self._getModel(ip)
# What's the path separator? Usually '\\' for windows, else '/'
sep = os.sep
# Generate specific output. Assumes src/ exists (or will be created) in level above JSON file location.
if opDir == '':
srcDir = sep.join(jsonPath.split(sep)[:-2]) + sep + 'src'
else:
srcDir = opDir
# Check destination directory exists, and create it if not
if not os.path.exists(srcDir) :
os.makedirs(srcDir)
# Open the main class definition output file
writeFileName = srcDir + sep + 'C' + ipCC + 'Auto' + opSuffix + '.h'
wfp = open(writeFileName, 'w')
# Open template file for reading
templateFname = os.path.dirname(sys.argv[0]) + sep + 'templates' + sep + 'template_elhal.h'
tfp = open(templateFname, 'r')
classNameList = []
# Read in each line of the template, looking for tags
for line in tfp:
# If the line has no tags, send straight to output, unmodified
if '%%' not in line:
wfp.write(line)
# When a tag present...
else:
# Split the line around the tag
tagLineSplit = line.split('%%')
# The tag is the second entry of the split list
tagStr = tagLineSplit[1]
# Decode the tag, and generate the appropriate output accordingly
if tagStr == 'HEADER':
stemStr = ipCC + 'Auto' + opSuffix + '.h\n *\n * >>> AUTO-GENERATED. DO NOT EDIT. <<<\n *\n */\n'
wfp.write('/*\n * C' + stemStr)
if tagStr == 'INCLUDEDEFS':
stemStr = ip.upper() + '_AUTO_H_\n'
wfp.write('#ifndef C' + stemStr)
wfp.write('#define C' + stemStr)
if tagStr == 'INCLUDES':
wfp.write('#include "' + ip + '.h"\n')
sbList = []
for jsonBusDict in jsonDict :
if attr.SUB_BLOCKS in jsonBusDict:
subBlocks = jsonBusDict[attr.SUB_BLOCKS]
for sb in subBlocks :
processStr = subBlocks[sb][attr.PROCESS]
if processStr == 'enabled' or self.__enableTag in processStr:
if sb.split(':')[0] not in sbList and sb != 'local' :
wfp.write('#include "C' + self._underScore2CamelCase(sb.split(':')[0]) + self.__classSuffix + '.h"\n')
sbList.append(sb.split(':')[0])
if tagStr == 'CLASS':
wfp.write('class C' + ipCC + 'Auto\n')
firstBus = True
if tagStr == 'REGCLASSDEFS':
for jsonBusDict in jsonDict:
# Get the bus name from the dictionary
bus = jsonBusDict[attr.BUS]
busBaseName = 'm_pv' + bus.capitalize() + 'BaseAddr'
# Detect if a process_regs attribute present, and flag if not to process
processRegs = True
if attr.PROCESS_REGS in jsonBusDict :
if jsonBusDict[attr.PROCESS_REGS] != 'enabled' :
processRegs = False
# If there are no registers, loop to the next bus
if attr.REGISTERS not in jsonBusDict:
continue
# Extract register data
regDict = jsonBusDict[attr.REGISTERS]
regKeys = regDict.keys()
classStr = 'C' + ipCC + 'Auto'
# Process the register
for regName in regKeys:
# Added as the FPM has register names with spaces
regNameNoSpaces = regName.replace(' ', '')
regCC = self._underScore2CamelCase(regNameNoSpaces)
#regLCC = self._underScore2LowCamelCase(regNameNoSpaces)
# Process registers, even if present, only if enabled
if processRegs:
classNameList.append(('C' + regCC, regCC))
# Output class name
wfp.write(' class C' + regCC + '\n {\n public:\n')
# Output constructor
wfp.write(' C' + regCC + '(uint32_t* blkBaseAddr) {' + busBaseName + ' = blkBaseAddr;};\n')
# Output extractor for whole reg
regFuncStr = ' inline uint32_t Get' + regCC + '()'
opStr = regFuncStr + '{return ' + classStr + '::readReg(' + busBaseName + ' + CSR_' + ip.upper() + '_' + regNameNoSpaces.upper() + '/4);}\n'
wfp.write(opStr)
# If no sub fields, and a write register, output injector method for whole reg
if attr.FIELDS not in regDict[regName]:
# Output a 'Set' function if the register (with no fields) is a write type
if regDict[regName][attr.TYPE] in MemMapperElHal.writeTypes:
regFuncStr = ' inline void Set' + regCC + '(uint32_t val)'
opStr = regFuncStr + '{' + classStr + '::writeReg(' + busBaseName + ' + CSR_' + ip.upper() + '_' + regNameNoSpaces.upper() + '/4, val);}\n'
wfp.write(opStr)
# When bit fields present, process them here
else:
# Extract the fields section from the model
fields = regDict[regName][attr.FIELDS]
hasWriteFields = False
# Loop through each field entry
for fieldName in fields:
# Added as the FPM will reuse the register name as a field name, which causes definition clashes
if fieldName == regName :
fieldNoClash = 'value'
else :
fieldNoClash = fieldName
# Ignoring reserved fields...
if fields[fieldName][attr.TYPE] != regtype.RESERVED:
# ----------------------------------
# Generate the extraction functions
fieldCC = self._underScore2CamelCase(fieldNoClash)
regCC = self._underScore2CamelCase(regNameNoSpaces)
# Construct the macro names (from the partner auto-generated header file)
macroStem = 'CSR_' + ip.upper() + '_' + regNameNoSpaces.upper() + '_' + fieldNoClash.upper()
maskName = macroStem + '_MASK'
# Always generate a Get function for the field
opStr = ' inline uint32_t Get' + fieldCC + '()' + '{return (Get' + regCC + '() & ' + maskName + ') >> ' + macroStem + ';}\n'
wfp.write(opStr)
# If a write type, generate an injection function
if fields[fieldName][attr.TYPE] in MemMapperElHal.writeTypes:
hasWriteFields = True
fieldFuncStr = ' inline void Set' + fieldCC + '(uint32_t val)'
opStr = fieldFuncStr + '{' + classStr + '::writeReg(' + busBaseName + ' + CSR_' + \
ip.upper() + '_' \
+ regNameNoSpaces.upper() \
+ '/4, ((Get' \
+ regCC + '() & ~' + \
maskName + \
') | ((val << ' + \
macroStem + ') & ' + \
maskName + ')));}\n'
wfp.write(opStr)
if hasWriteFields :
regFuncStr = ' inline void Set' + regCC + '(uint32_t val)'
opStr = regFuncStr + '{' + classStr + '::writeReg(' + busBaseName + ' + CSR_' + ip.upper() + '_' + regNameNoSpaces.upper() + '/4, val);}\n'
wfp.write(opStr)
# end
wfp.write(' private:\n volatile uint32_t* ' + busBaseName + ';\n')
wfp.write(' };\n\n')
# Note that this relies on the above tag being run first. DON'T CHANGE THE TEMPLATE ORDER
if tagStr == 'CONSTRUCTORS':
# Start constructing a constrcutor for the class
stemStr = 'C' + ipCC + 'Auto('
opStr = ''
# Loop through the busses and add base address arguments for each relevant one.
for jsonBusDict in jsonDict:
bus = jsonBusDict[attr.BUS]
if not firstBus :
stemStr += ', '
stemStr += 'uint32_t* ' + bus + 'BaseAddr = 0'
firstBus = False
stemStr += ')'
# Add the definition of the constructor
opStr += ' ' + stemStr + '\n {'
# Initialise a dictionary we'll use to kee sub-block information in
sbDict = {}
# Loop through the busses...
for jsonBusDict in jsonDict:
regsAreLocal = False
# Pull out bus information
bus = jsonBusDict[attr.BUS]
busBaseName = '\n m_pv' + bus.capitalize() + 'BaseAddr'
# If there are sub-block present...
if attr.SUB_BLOCKS in jsonBusDict :
subBlocks = jsonBusDict[attr.SUB_BLOCKS]
# Detect whether there is a local sub-block, and this the registers defined will be for this.
if 'local' in subBlocks:
regsAreLocal = True
# Loop through the sub-blocks adding to the sbDict dictionary the blocks and the busses
# that they are defined on. Ignore local.
for sb in subBlocks :
if sb != 'local' :
if sb not in sbDict :
sbDict[sb] = [bus]
else :
if bus not in sbDict[sb] :
sbDict[sb].append(bus)
# Add the setting of the local base address member variable for this bus
opStr += busBaseName + ' = ' + bus + 'BaseAddr;\n\n'
# For the CSR bus, add creation of register objects, assigning to the local pointers.
# CSR is the only bus processed as it will have all the blocks, but don't want duplicates
# ff defined on other busses.
if bus == 'csr' :
for className, objName in classNameList:
opStr += ' p' + objName + ' = new ' + className + '(' + bus + 'BaseAddr'
if regsAreLocal :
opStr += ' + CSR_' + ip.upper() + '_LOCAL/4'
opStr += ');\n'
# Output sub-block declarations
for jsonBusDict in jsonDict:
if attr.SUB_BLOCKS in jsonBusDict:
subBlocks = jsonBusDict[attr.SUB_BLOCKS]
bus = jsonBusDict[attr.BUS]
# Loop through the sub-blocks...
for sb in subBlocks :
processStr = subBlocks[sb][attr.PROCESS]
# Only process if no a local sub-block, is on CSR bus and enabled to process
if sb != 'local' and bus == 'csr' and (processStr == 'enabled' or self.__enableTag in processStr) :
sbRoot = sb.split(':')[0]
instance = subBlocks[sb][attr.INSTANCE]
opStr += ' p' + self._underScore2CamelCase(sbRoot) + self._underScore2CamelCase(instance) + ' = new C' + self._underScore2CamelCase(sbRoot) + self.__classSuffix + '('
firstLoop = False
for busName in sbDict[sb] :
if firstLoop :
opStr += ', '
opStr += busName + 'BaseAddr' + ' + ' + busName.upper() + '_' + ip.upper() + '_' + sb.split(':')[0].upper()
if instance != '' :
opStr += '_' + instance.upper()
opStr += '/4'
firstLoop = True
opStr += ');\n'
opStr += ' };\n'
wfp.write(opStr)
if tagStr == 'REGOBJPOINTERS':
for className, objName in classNameList:
wfp.write(' ' + className + '* p' + objName + ';\n')
if tagStr == 'SBOBJPOINTERS':
sbList = []
for jsonBusDict in jsonDict :
if attr.SUB_BLOCKS in jsonBusDict:
subBlocks = jsonBusDict[attr.SUB_BLOCKS]
for sb in subBlocks :
if sb != 'local' and sb not in sbList:
instance = subBlocks[sb][attr.INSTANCE]
processStr = subBlocks[sb][attr.PROCESS]
if processStr == 'enabled' or self.__enableTag in processStr:
opStr = ' C' + self._underScore2CamelCase(sb.split(':')[0]) + self.__classSuffix + '* p' + \
self._underScore2CamelCase(sb.split(':')[0]) + \
self._underScore2CamelCase(instance) + ';\n'
wfp.write(opStr)
sbList.append(sb)
if tagStr == 'BASEADDREXTRACTION' :
for jsonBusDict in jsonDict:
# Get the bus name from the dictionary
bus = jsonBusDict[attr.BUS]
busBaseName = 'm_pv' + bus.capitalize() + 'BaseAddr'
wfp.write(' inline volatile uint32_t* Get' + bus.capitalize() + 'BaseAddr() {return ' + busBaseName + ';}\n')
if tagStr == 'BASEADDRMEMBER' :
for jsonBusDict in jsonDict:
# Get the bus name from the dictionary
bus = jsonBusDict[attr.BUS]
busBaseName = 'm_pv' + bus.capitalize() + 'BaseAddr'
wfp.write(' volatile uint32_t* ' + busBaseName + ';\n')
if tagStr == 'ENDIF':
wfp.write('#endif /* C' + ip.upper() + '_AUTO_H_ */\n')
wfp.close()
# --------------------------------------------------------------
# Parse the command line arguments
#
def processCmdLine():
# Create a parser object
parser = argparse.ArgumentParser(description='Process command line options.')
# Process common command line options with inherited static base class method
MemMapperElHal.processCmdLine(parser)
# Specific command line options added here
parser.add_argument('-D', '--derived_classes', dest='devClasses', default=False, action='store_true', help='Use derived classes as class types of child objects (default false)')
return parser.parse_args()
# ###############################################################
# Only run if not imported (to test)
#
if __name__ == '__main__':
enTag = 'cpp'
memMap = MemMapperElHal()
memMapHdrs = MemMapperCpp()
# Process the command line options
cmdArgs = processCmdLine()
# Do initialisation for text object specific configurations
memMap.setByteAddrMode(True)
memMap.setEnableTag(enTag)
if cmdArgs.devClasses:
memMap.setDerivedClassOn()
memMapHdrs.setByteAddrMode(True)
memMapHdrs.setHeadersMode(True)
# Run the program for C++ definitions generation
memMapHdrs.run(cmdArgs.topBlock, cmdArgs.busList, cmdArgs.repoDir, cmdArgs.opDir, '', enTag,
cmdArgs.jsonFile, cmdArgs.buildDir)
# Run the program for C++ class generation
memMap.run(cmdArgs.topBlock, cmdArgs.busList, cmdArgs.repoDir, cmdArgs.opDir, cmdArgs.opFileSuffix, enTag, cmdArgs.jsonFile, cmdArgs.buildDir, cmdArgs.qsysSuffix)
del memMap