MetaFileParser.py revision 4fd606d1f5abe38e1f42c38de1d2e895166bd0f4
## @file
# This file is used to parse meta files
#
# Copyright (c) 2008 - 2010, Intel Corporation. All rights reserved.<BR>
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
##
# Import Modules
#
import os
import re
import time
import copy
import EccGlobalData
from CommonDataClass.DataClass import *
from Common.Expression import *
from CommonDataClass.Exceptions import *
from MetaFileTable import MetaFileStorage
## A decorator used to parse macro definition
def ParseMacro(Parser):
def MacroParser(self):
if not Match:
# Not 'DEFINE/EDK_GLOBAL' statement, call decorated method
return
# Syntax check
if not TokenList[0]:
# Global macros can be only defined via environment variable
# Only upper case letters, digit and '_' are allowed
# DEFINE defined macros
if Type == TAB_DSC_DEFINES_DEFINE:
else:
else:
# EDK_GLOBAL defined macros
EdkLogger.error('Parser', FORMAT_INVALID, "EDK_GLOBAL defined a macro with the same name and different value as one defined by 'DEFINE'",
return MacroParser
## Base class of parser
#
# This class is used for derivation purpose. The specific parser for one kind
# type file must derive this class and implement some public interfaces.
#
# @param FilePath The path of platform description file
# @param FileType The raw data of DSC file
# @param Macros Macros used for replacement in file
# @param Owner Owner ID (for sub-section parsing)
# @param From ID from which the data comes (for !INCLUDE directive)
#
class MetaFileParser(object):
# data type (file content) for specific file type
DataType = {}
# Parser objects used to implement singleton
MetaFiles = {}
## Factory method
#
# One file, one parser object. This factory method makes sure that there's
# only one object constructed for one meta file.
#
# @param Class class object of real AutoGen class
# (InfParser, DecParser or DscParser)
# @param FilePath The path of meta file
# @param *args The specific class related parameters
# @param **kwargs The specific class related dict parameters
#
else:
return ParserObject
## Constructor of MetaFileParser
#
# Initialize object of MetaFileParser
#
# @param FilePath The path of platform description file
# @param FileType The raw data of DSC file
# @param Macros Macros used for replacement in file
# @param Owner Owner ID (for sub-section parsing)
# @param From ID from which the data comes (for !INCLUDE directive)
#
self._FileLocalMacros = {}
self._SectionsMacroDict = {}
# for recursive parsing
# parsr status for parsing
# Different version of meta-file has different way to parse.
## Store the parsed data in table
## Virtual method for starting parse
raise NotImplementedError
## Notify a post-process is needed
def DoPostProcess(self):
## Set parsing complete flag in both class and table
## Do not set end flag when processing included files
def _PostProcess(self):
## Get the parse complete flag
def _GetFinished(self):
## Set the complete flag
## Use [] style to query data in table, just for readability
#
# DataInfo = [data_type, scope1(arch), scope2(platform/moduletype)]
#
# Parse the file first, if necessary
else:
# No specific ARCH or Platform given, use raw data
# Do post-process if necessary
if not self._PostProcessed:
## Data parser for the common format in different type of file
#
# The common format in the meatfile is like
#
# xxx1 | xxx2 | xxx3
#
def _CommonParser(self):
## Data parser for the format in which there's path
#
# Only path can have macro used. So we need to replace them before use.
#
def _PathParser(self):
# Don't do macro replacement for dsc file at this point
## Skip unsupported data
## Section header parser
#
# The section header is always in following format:
#
# [section_name.arch<.platform|module_type>]
#
def _SectionHeaderParser(self):
if Item == '':
continue
# different section should not mix in one section
else:
# S1 is always Arch
else:
S1 = 'COMMON'
# S2 may be Platform or ModuleType
else:
S2 = 'COMMON'
# 'COMMON' must not be used with specific ARCHs at the same section
# If the section information is needed later, it should be stored in database
## [defines] section parser
def _DefineParser(self):
# Sometimes, we need to make differences between EDK and EDK2 modules
if Name == 'INF_VERSION':
try:
except:
# EDK module allows using defines as macros
## [BuildOptions] section parser
def _BuildOptionParser(self):
else:
'Parser',
)
def _GetMacros(self):
Macros = {}
return Macros
## Get section Macros that are applicable to current line, which may come from other sections
## that share the same name while scope is wider
Macros = {}
return Macros
_SectionParser = {}
## INF file parser class
#
# @param FilePath The path of platform description file
# @param FileType The raw data of DSC file
# @param Macros Macros used for replacement in file
#
class InfParser(MetaFileParser):
# INF file supported data types (one type per section)
DataType = {
}
## Constructor of InfParser
#
# Initialize object of InfParser
#
# @param FilePath The path of module description file
# @param FileType The raw data of DSC file
# @param Macros Macros used for replacement in file
#
# prevent re-initialization
return
## Parser starter
NmakeLine = ''
Content = ''
try:
except:
#
# Insert a record for file
#
if FileID:
else:
# parse the file line by line
# skip empty, commented, block commented lines
NextLine = ''
if Line == '':
continue
continue
continue
continue
# section header
# Check invalid sections
continue
# merge two lines specified by '\' in section NMAKE
if NextLine == '':
NmakeLine = ''
else:
NmakeLine = ''
else:
continue
else:
NmakeLine = ''
# section content
# parse current line, result will be put in self._ValueList
continue
#
# Model, Value1, Value2, Value3, Arch, Platform, BelongsToItem=-1,
# LineBegin=-1, ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, Enabled=-1
#
Arch,
-1,
-1,
0
)
EdkLogger.error("Parser", FORMAT_INVALID, "Open block comments (starting with /*) are expected to end with */",
## Data parser for the format in which there's path
#
# Only path can have macro used. So we need to replace them before use.
#
def _IncludeParser(self):
if Macros:
if not Value:
continue
if Value.upper().find('$(EFI_SOURCE)\Edk'.upper()) > -1 or Value.upper().find('$(EFI_SOURCE)/Edk'.upper()) > -1:
pass
pass
pass
else:
## Parse [Sources] section
#
# Only path can have macro used. So we need to replace them before use.
#
def _SourceFileParser(self):
# For Acpi tables, remove macro like ' TABLE_NAME=Sata1'
if 'COMPONENT_TYPE' in Macros:
pass
## Parse [Binaries] section
#
# Only path can have macro used. So we need to replace them before use.
#
def _BinaryFileParser(self):
if not TokenList[0]:
if not TokenList[1]:
## [nmake] section parser (Edk.x style only)
def _NmakeParser(self):
# remove macros
# remove self-reference in macro setting
#self._ValueList[1] = ReplaceMacro(self._ValueList[1], {self._ValueList[0]:''})
## [FixedPcd], [FeaturePcd], [PatchPcd], [Pcd] and [PcdEx] sections parser
def _PcdParser(self):
# if value are 'True', 'true', 'TRUE' or 'False', 'false', 'FALSE', replace with integer 1 or 0.
## [depex] section parser
def _DepexParser(self):
_SectionParser = {
}
## DSC file parser class
#
# @param FilePath The path of platform description file
# @param FileType The raw data of DSC file
# @param Macros Macros used for replacement in file
# @param Owner Owner ID (for sub-section parsing)
# @param From ID from which the data comes (for !INCLUDE directive)
#
class DscParser(MetaFileParser):
# DSC file supported data types (one type per section)
DataType = {
}
# Valid names in define section
DefineKeywords = [
"DSC_SPECIFICATION",
"PLATFORM_NAME",
"PLATFORM_GUID",
"PLATFORM_VERSION",
"SKUID_IDENTIFIER",
"SUPPORTED_ARCHITECTURES",
"BUILD_TARGETS",
"OUTPUT_DIRECTORY",
"FLASH_DEFINITION",
"BUILD_NUMBER",
"RFC_LANGUAGES",
"ISO_LANGUAGES",
"TIME_STAMP_FILE",
"VPD_TOOL_GUID",
"FIX_LOAD_TOP_MEMORY_ADDRESS"
]
## Constructor of DscParser
#
# Initialize object of DscParser
#
# @param FilePath The path of platform description file
# @param FileType The raw data of DSC file
# @param Macros Macros used for replacement in file
# @param Owner Owner ID (for sub-section parsing)
# @param From ID from which the data comes (for !INCLUDE directive)
#
# prevent re-initialization
return
# to store conditional directive evaluation result
self._DirectiveStack = []
self._DirectiveEvalStack = []
# Final valid replacable symbols
#
# Map the ID between the original table and new table to track
# the owner item
#
## Parser starter
Content = ''
try:
except:
#
# Insert a record for file
#
if FileID:
else:
# skip empty line
if Line == '':
continue
# section header
# subsection ending
continue
# subsection header
# directive line
continue
if self._InSubsection:
else:
if self._ValueList == None:
continue
#
# Model, Value1, Value2, Value3, Arch, ModuleType, BelongsToItem=-1, BelongsToFile=-1,
# LineBegin=-1, ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, Enabled=-1
#
Arch,
-1,
-1,
)
if self._DirectiveStack:
## <subsection_header> parser
def _SubsectionHeaderParser(self):
else:
## Directive statement parser
def _DirectiveParser(self):
# Syntax check
if DirectiveName in ['!IF', '!IFDEF', '!INCLUDE', '!IFNDEF', '!ELSEIF'] and self._ValueList[1] == '':
# Remove all directives between !if and !endif, including themselves
while self._DirectiveStack:
# Remove any !else or !elseif
break
else:
elif ItemType != MODEL_META_DATA_INCLUDE:
# Break if there's a !else is followed by a !elseif
if ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF and \
self._DirectiveStack and \
"No '!include' allowed in included file",
#
# Model, Value1, Value2, Value3, Arch, ModuleType, BelongsToItem=-1, BelongsToFile=-1,
# LineBegin=-1, ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, Enabled=-1
#
'COMMON',
'COMMON',
-1,
-1,
0
)
## [defines] section parser
def _DefineParser(self):
# Syntax check
"Unknown keyword found: %s. "
"If this is a macro you must "
def _SkuIdParser(self):
## Parse Edk style of library modules
def _LibraryInstanceParser(self):
## PCD sections parser
#
# [PcdsFixedAtBuild]
# [PcdsPatchableInModule]
# [PcdsFeatureFlag]
# [PcdsDynamicEx
# [PcdsDynamicExDefault]
# [PcdsDynamicExVpd]
# [PcdsDynamicExHii]
# [PcdsDynamic]
# [PcdsDynamicDefault]
# [PcdsDynamicVpd]
# [PcdsDynamicHii]
#
def _PcdParser(self):
# if value are 'True', 'true', 'TRUE' or 'False', 'false', 'FALSE', replace with integer 1 or 0.
## [components] section parser
def _ComponentParser(self):
else:
## [LibraryClasses] section
def _LibraryClassParser(self):
## [BuildOptions] section parser
def _BuildOptionParser(self):
else:
'Parser',
)
## Override parent's method since we'll do all macro replacements in parser
def _GetMacros(self):
Macros = {}
# PCD cannot be referenced in macro definition
return Macros
def _PostProcess(self):
Processer = {
}
self._DirectiveStack = []
self._DirectiveEvalStack = []
self._FileLocalMacros = {}
self._SectionsMacroDict = {}
# Get all macro and PCD which has straitforward value
try:
except EvaluationException, Excpt:
#
# Only catch expression evaluation error here. We need to report
# the precise number of line on which the error occurred
#
except MacroException, Excpt:
if self._ValueList == None:
continue
S1,
S2,
-1,
-1,
)
for Record in RecordList:
EccGlobalData.gDb.TblDsc.Insert(Record[1],Record[2],Record[3],Record[4],Record[5],Record[6],Record[7],Record[8],Record[9],Record[10],Record[11],Record[12],Record[13],Record[14])
def __ProcessSectionHeader(self):
else:
else:
def __RetrievePcdValue(self):
# Only use PCD whose value is straitforward (no macro and PCD)
continue
# Don't use PCD with different values.
continue
# Only use PCD whose value is straitforward (no macro and PCD)
continue
# Don't use PCD with different values.
continue
def __ProcessDefine(self):
return
else:
#
# Keyword in [Defines] section can be used as Macros
#
def __ProcessDirective(self):
Result = None
try:
except SymbolNotFound, Exc:
except WrnExpression, Excpt:
#
# Catch expression evaluation warning here. We need to report
# the precise number of line and return the evaluation result
#
else:
# Back to the nearest !if/!ifdef/!ifndef
while self._DirectiveStack:
break
# The included file must be relative to workspace or same directory as DSC file
__IncludeMacros = {}
#
# Allow using system environment variables in path after !include
#
#
# During GenFds phase call DSC parser, will go into this branch.
#
#
# Allow using MACROs comes from [Defines] section to keep compatible.
#
#
# First search the include file under the same directory as DSC file
#
if ErrorCode != 0:
#
# Also search file under the WORKSPACE directory
#
if ErrorCode != 0:
# set the parser status with current status
# Parse the included file
# update current status with sub-parser's status
# Insert all records in the table for the included file into dsc file table
if Records:
self._ValueList = None
def __ProcessSkuId(self):
def __ProcessLibraryInstance(self):
def __ProcessLibraryClass(self):
def __ProcessPcd(self):
#
# PCD value can be an expression
#
try:
except WrnExpression, Value:
else:
try:
except WrnExpression, Value:
def __ProcessComponent(self):
def __ProcessBuildOption(self):
_SectionParser = {
}
## DEC file parser class
#
# @param FilePath The path of platform description file
# @param FileType The raw data of DSC file
# @param Macros Macros used for replacement in file
#
class DecParser(MetaFileParser):
# DEC file supported data types (one type per section)
DataType = {
}
## Constructor of DecParser
#
# Initialize object of DecParser
#
# @param FilePath The path of platform description file
# @param FileType The raw data of DSC file
# @param Macros Macros used for replacement in file
#
# prevent re-initialization
return
## Parser starter
Content = ''
try:
except:
#
# Insert a record for file
#
if FileID:
else:
# save comment for later use
if Comment:
# skip empty line
if Line == '':
continue
# section header
continue
continue
# section content
continue
#
# Model, Value1, Value2, Value3, Arch, BelongsToItem=-1, LineBegin=-1,
# ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, FeatureFlag='', Enabled=-1
#
Type,
Arch,
-1,
-1,
0
)
Arch,
-1,
-1,
0
)
Macros = {}
return Macros
## Section header parser
#
# The section header is always in following format:
#
# [section_name.arch<.platform|module_type>]
#
def _SectionHeaderParser(self):
self._SectionType = []
if Item == '':
continue
# different types of PCD are permissible in one section
else:
continue
'Parser',
"%s must not be in the same section of other types of PCD" % TAB_PCDS_FEATURE_FLAG_NULL,
)
# S1 is always Arch
else:
S1 = 'COMMON'
# S2 may be Platform or ModuleType
else:
S2 = 'COMMON'
# 'COMMON' must not be used with specific ARCHs at the same section
## [guids], [ppis] and [protocols] section parser
def _GuidParser(self):
if TokenList[1][0] != '{' or TokenList[1][-1] != '}' or GuidStructureStringToGuidString(TokenList[1]) == '':
" (<CName> = <GuidValueInCFormat:{8,4,4,{2,2,2,2,2,2,2,2}}>)",
#Parse the Guid value format
Index = 0
HexList = []
for GuidValue in GuidValueList:
Index += 1
continue
else:
Index += 1
self._ValueList[1] = "{ %s, %s, %s, { %s, %s, %s, %s, %s, %s, %s, %s }}" % (HexList[0], HexList[1], HexList[2],HexList[3],HexList[4],HexList[5],HexList[6],HexList[7],HexList[8],HexList[9],HexList[10])
else:
" (<CName> = <GuidValueInCFormat:{8,4,4,{2,2,2,2,2,2,2,2}}>)",
## PCD sections parser
#
# [PcdsFixedAtBuild]
# [PcdsPatchableInModule]
# [PcdsFeatureFlag]
# [PcdsDynamicEx
# [PcdsDynamic]
#
def _PcdParser(self):
# check PCD information
" (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
# check PCD datum information
" (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
# Has VOID* type string, may contain "|" character in the string.
else:
# check if there's enough datum information given
" (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
# check default value
" (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
# check datum type
" (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
# check token of the PCD
" (<TokenSpaceGuidCName>.<PcdCName>|<DefaultValue>|<DatumType>|<Token>)",
# check format of default value against the datum type
if not IsValid:
_SectionParser = {
}
## FdfObject
#
# This class defined basic Fdf object which is used by inheriting
#
# @param object: Inherited from object class
#
## Fdf
#
# This class defined the structure used in Fdf object
#
# @param FdfObject: Inherited from FdfObject class
# @param Filename: Input value for Ffilename of Fdf file, default is None
# @param WorkspaceDir: Input value for current workspace directory, default is None
#
#
# Load Fdf file if filename is not None
#
if Filename != None:
#
# Insert a FDF file record into database
#
FileID = -1
## Load Fdf file
#
# Load the file if it exists
#
# @param Filename: Input value for filename of Fdf file
#
FileList = []
#
# Parse Fdf file
#
#
# Insert inf file and pcd information
#
if self.IsToDatabase:
(Model, Value1, Value2, Value3, Scope1, Scope2, BelongsToItem, BelongsToFile, StartLine, StartColumn, EndLine, EndColumn, Enabled) = \
(0, '', '', '', 'COMMON', 'COMMON', -1, -1, -1, -1, -1, -1, 0)
pass
self.TblFdf.Insert(Model, Value1, Value2, Value3, Scope1, Scope2, BelongsToItem, BelongsToFile, StartLine, StartColumn, EndLine, EndColumn, Enabled)
Value2 = ''
self.TblFdf.Insert(Model, Value1, Value2, Value3, Scope1, Scope2, BelongsToItem, BelongsToFile, StartLine, StartColumn, EndLine, EndColumn, Enabled)
##
#
# This acts like the main() function for the script, unless it is 'import'ed into another
# script.
#
if __name__ == '__main__':
pass