]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/Workspace/MetaFileParser.py
BaseTools: Use absolute import in Workspace
[mirror_edk2.git] / BaseTools / Source / Python / Workspace / MetaFileParser.py
index 95ea6fb45abb5af1704c5dae9e0e316c6ab5684d..fbfc182c8bfff2f142da3a7c7aec80b157fcfdf1 100644 (file)
@@ -2,7 +2,7 @@
 # This file is used to parse meta files\r
 #\r
 # Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR>\r
-# (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP<BR>\r
+# (C) Copyright 2015-2018 Hewlett Packard Enterprise Development LP<BR>\r
 # This program and the accompanying materials\r
 # are licensed and made available under the terms and conditions of the BSD License\r
 # which accompanies this distribution.  The full text of the license may be found at\r
@@ -15,6 +15,8 @@
 ##\r
 # Import Modules\r
 #\r
+from __future__ import print_function\r
+from __future__ import absolute_import\r
 import Common.LongFilePathOs as os\r
 import re\r
 import time\r
@@ -26,14 +28,18 @@ import Common.GlobalData as GlobalData
 \r
 from CommonDataClass.DataClass import *\r
 from Common.DataType import *\r
-from Common.String import *\r
+from Common.StringUtils import *\r
 from Common.Misc import GuidStructureStringToGuidString, CheckPcdDatum, PathClass, AnalyzePcdData, AnalyzeDscPcd, AnalyzePcdExpression, ParseFieldValue\r
 from Common.Expression import *\r
 from CommonDataClass.Exceptions import *\r
 from Common.LongFilePathSupport import OpenLongFilePath as open\r
+from collections import defaultdict\r
+from .MetaFileTable import MetaFileStorage\r
+from .MetaFileCommentParser import CheckInfComment\r
 \r
-from MetaFileTable import MetaFileStorage\r
-from MetaFileCommentParser import CheckInfComment\r
+## RegEx for finding file versions\r
+hexVersionPattern = re.compile(r'0[xX][\da-f-A-F]{5,8}')\r
+decVersionPattern = re.compile(r'\d+\.\d+')\r
 \r
 ## A decorator used to parse macro definition\r
 def ParseMacro(Parser):\r
@@ -73,10 +79,10 @@ def ParseMacro(Parser):
             #\r
             # First judge whether this DEFINE is in conditional directive statements or not.\r
             #\r
-            if type(self) == DscParser and self._InDirective > -1:\r
+            if isinstance(self, DscParser) and self._InDirective > -1:\r
                 pass\r
             else:\r
-                if type(self) == DecParser:\r
+                if isinstance(self, DecParser):\r
                     if MODEL_META_DATA_HEADER in self._SectionType:\r
                         self._FileLocalMacros[Name] = Value\r
                     else:\r
@@ -87,7 +93,7 @@ def ParseMacro(Parser):
                     self._ConstructSectionMacroDict(Name, Value)\r
 \r
         # EDK_GLOBAL defined macros\r
-        elif type(self) != DscParser:\r
+        elif not isinstance(self, DscParser):\r
             EdkLogger.error('Parser', FORMAT_INVALID, "EDK_GLOBAL can only be used in .dsc file",\r
                             ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1)\r
         elif self._SectionType != MODEL_META_DATA_HEADER:\r
@@ -159,7 +165,7 @@ class MetaFileParser(object):
         self._FileDir = self.MetaFile.Dir\r
         self._Defines = {}\r
         self._FileLocalMacros = {}\r
-        self._SectionsMacroDict = {}\r
+        self._SectionsMacroDict = defaultdict(dict)\r
 \r
         # for recursive parsing\r
         self._Owner = [Owner]\r
@@ -219,7 +225,7 @@ class MetaFileParser(object):
         NewRecordList = []\r
         for Record in RecordList:\r
             Arch = Record[3]\r
-            if Arch == 'COMMON' or Arch == FilterArch:\r
+            if Arch == TAB_ARCH_COMMON or Arch == FilterArch:\r
                 NewRecordList.append(Record)\r
         return NewRecordList\r
 \r
@@ -228,7 +234,7 @@ class MetaFileParser(object):
     #   DataInfo = [data_type, scope1(arch), scope2(platform/moduletype)]\r
     #\r
     def __getitem__(self, DataInfo):\r
-        if type(DataInfo) != type(()):\r
+        if not isinstance(DataInfo, type(())):\r
             DataInfo = (DataInfo,)\r
 \r
         # Parse the file first, if necessary\r
@@ -241,7 +247,7 @@ class MetaFileParser(object):
                 self.Start()\r
 \r
         # No specific ARCH or Platform given, use raw data\r
-        if self._RawTable and (len(DataInfo) == 1 or DataInfo[1] == None):\r
+        if self._RawTable and (len(DataInfo) == 1 or DataInfo[1] is None):\r
             return self._FilterRecordList(self._RawTable.Query(*DataInfo), self._Arch)\r
 \r
         # Do post-process if necessary\r
@@ -270,7 +276,7 @@ class MetaFileParser(object):
         TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT)\r
         self._ValueList[0:len(TokenList)] = TokenList\r
         # Don't do macro replacement for dsc file at this point\r
-        if type(self) != DscParser:\r
+        if not isinstance(self, DscParser):\r
             Macros = self._Macros\r
             self._ValueList = [ReplaceMacro(Value, Macros) for Value in self._ValueList]\r
 \r
@@ -297,7 +303,7 @@ class MetaFileParser(object):
         for Item in GetSplitValueList(self._CurrentLine[1:-1], TAB_COMMA_SPLIT):\r
             if Item == '':\r
                 continue\r
-            ItemList = GetSplitValueList(Item, TAB_SPLIT,3)\r
+            ItemList = GetSplitValueList(Item, TAB_SPLIT, 3)\r
             # different section should not mix in one section\r
             if self._SectionName != '' and self._SectionName != ItemList[0].upper():\r
                 EdkLogger.error('Parser', FORMAT_INVALID, "Different section names in the same section",\r
@@ -306,7 +312,7 @@ class MetaFileParser(object):
             if self._SectionName in self.DataType:\r
                 self._SectionType = self.DataType[self._SectionName]\r
                 # Check if the section name is valid\r
-                if self._SectionName not in SECTIONS_HAVE_ITEM_AFTER_ARCH and len(ItemList) > 3:\r
+                if self._SectionName not in SECTIONS_HAVE_ITEM_AFTER_ARCH_SET and len(ItemList) > 3:\r
                     EdkLogger.error("Parser", FORMAT_UNKNOWN_ERROR, "%s is not a valid section name" % Item,\r
                                     self.MetaFile, self._LineIndex + 1, self._CurrentLine)\r
             elif self._Version >= 0x00010005:\r
@@ -319,25 +325,25 @@ class MetaFileParser(object):
             if len(ItemList) > 1:\r
                 S1 = ItemList[1].upper()\r
             else:\r
-                S1 = 'COMMON'\r
+                S1 = TAB_ARCH_COMMON\r
             ArchList.add(S1)\r
 \r
             # S2 may be Platform or ModuleType\r
             if len(ItemList) > 2:\r
-                if self._SectionName.upper() in SECTIONS_HAVE_ITEM_PCD:\r
+                if self._SectionName.upper() in SECTIONS_HAVE_ITEM_PCD_SET:\r
                     S2 = ItemList[2]\r
                 else:\r
                     S2 = ItemList[2].upper()\r
             else:\r
-                S2 = 'COMMON'\r
+                S2 = TAB_COMMON\r
             if len(ItemList) > 3:\r
                 S3 = ItemList[3]\r
             else:\r
-                S3 = "COMMON"\r
+                S3 = TAB_COMMON\r
             self._Scope.append([S1, S2, S3])\r
 \r
         # 'COMMON' must not be used with specific ARCHs at the same section\r
-        if 'COMMON' in ArchList and len(ArchList) > 1:\r
+        if TAB_ARCH_COMMON in ArchList and len(ArchList) > 1:\r
             EdkLogger.error('Parser', FORMAT_INVALID, "'common' ARCH must not be used with specific ARCHs",\r
                             File=self.MetaFile, Line=self._LineIndex + 1, ExtraData=self._CurrentLine)\r
         # If the section information is needed later, it should be stored in database\r
@@ -364,11 +370,11 @@ class MetaFileParser(object):
                     EdkLogger.error("Parser", FORMAT_INVALID, "Global macro %s is not permitted." % (Macro), ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1)\r
             else:\r
                 EdkLogger.error("Parser", FORMAT_INVALID, "%s not defined" % (Macro), ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1)\r
-        # Sometimes, we need to make differences between EDK and EDK2 modules \r
+        # Sometimes, we need to make differences between EDK and EDK2 modules\r
         if Name == 'INF_VERSION':\r
-            if re.match(r'0[xX][\da-f-A-F]{5,8}', Value):\r
-                self._Version = int(Value, 0)   \r
-            elif re.match(r'\d+\.\d+', Value):\r
+            if hexVersionPattern.match(Value):\r
+                self._Version = int(Value, 0)\r
+            elif decVersionPattern.match(Value):\r
                 ValueList = Value.split('.')\r
                 Major = '%04o' % int(ValueList[0], 0)\r
                 Minor = '%04o' % int(ValueList[1], 0)\r
@@ -377,7 +383,7 @@ class MetaFileParser(object):
                 EdkLogger.error('Parser', FORMAT_INVALID, "Invalid version number",\r
                                 ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1)\r
 \r
-        if type(self) == InfParser and self._Version < 0x00010005:\r
+        if isinstance(self, InfParser) and self._Version < 0x00010005:\r
             # EDK module allows using defines as macros\r
             self._FileLocalMacros[Name] = Value\r
         self._Defines[Name] = Value\r
@@ -393,7 +399,7 @@ class MetaFileParser(object):
             self._ValueList[1] = TokenList2[1]              # keys\r
         else:\r
             self._ValueList[1] = TokenList[0]\r
-        if len(TokenList) == 2 and type(self) != DscParser: # value\r
+        if len(TokenList) == 2 and not isinstance(self, DscParser): # value\r
             self._ValueList[2] = ReplaceMacro(TokenList[1], self._Macros)\r
 \r
         if self._ValueList[1].count('_') != 4:\r
@@ -413,23 +419,22 @@ class MetaFileParser(object):
         Macros.update(self._GetApplicableSectionMacro())\r
         return Macros\r
 \r
-    ## Construct section Macro dict \r
+    ## Construct section Macro dict\r
     def _ConstructSectionMacroDict(self, Name, Value):\r
-        ScopeKey = [(Scope[0], Scope[1],Scope[2]) for Scope in self._Scope]\r
+        ScopeKey = [(Scope[0], Scope[1], Scope[2]) for Scope in self._Scope]\r
         ScopeKey = tuple(ScopeKey)\r
-        SectionDictKey = self._SectionType, ScopeKey\r
         #\r
         # DecParser SectionType is a list, will contain more than one item only in Pcd Section\r
         # As Pcd section macro usage is not alllowed, so here it is safe\r
         #\r
-        if type(self) == DecParser:\r
+        if isinstance(self, DecParser):\r
             SectionDictKey = self._SectionType[0], ScopeKey\r
-        if SectionDictKey not in self._SectionsMacroDict:\r
-            self._SectionsMacroDict[SectionDictKey] = {}\r
-        SectionLocalMacros = self._SectionsMacroDict[SectionDictKey]\r
-        SectionLocalMacros[Name] = Value\r
+        else:\r
+            SectionDictKey = self._SectionType, ScopeKey\r
+\r
+        self._SectionsMacroDict[SectionDictKey][Name] = Value\r
 \r
-    ## Get section Macros that are applicable to current line, which may come from other sections \r
+    ## Get section Macros that are applicable to current line, which may come from other sections\r
     ## that share the same name while scope is wider\r
     def _GetApplicableSectionMacro(self):\r
         Macros = {}\r
@@ -439,7 +444,7 @@ class MetaFileParser(object):
         SpeSpeMacroDict = {}\r
 \r
         ActiveSectionType = self._SectionType\r
-        if type(self) == DecParser:\r
+        if isinstance(self, DecParser):\r
             ActiveSectionType = self._SectionType[0]\r
 \r
         for (SectionType, Scope) in self._SectionsMacroDict:\r
@@ -447,20 +452,20 @@ class MetaFileParser(object):
                 continue\r
 \r
             for ActiveScope in self._Scope:\r
-                Scope0, Scope1 ,Scope2= ActiveScope[0], ActiveScope[1],ActiveScope[2]\r
-                if(Scope0, Scope1,Scope2) not in Scope:\r
+                Scope0, Scope1, Scope2= ActiveScope[0], ActiveScope[1], ActiveScope[2]\r
+                if(Scope0, Scope1, Scope2) not in Scope:\r
                     break\r
             else:\r
                 SpeSpeMacroDict.update(self._SectionsMacroDict[(SectionType, Scope)])\r
 \r
             for ActiveScope in self._Scope:\r
-                Scope0, Scope1,Scope2 = ActiveScope[0], ActiveScope[1],ActiveScope[2]\r
-                if(Scope0, Scope1,Scope2) not in Scope and (Scope0, "COMMON","COMMON") not in Scope and ("COMMON", Scope1,"COMMON") not in Scope:\r
+                Scope0, Scope1, Scope2 = ActiveScope[0], ActiveScope[1], ActiveScope[2]\r
+                if(Scope0, Scope1, Scope2) not in Scope and (Scope0, TAB_COMMON, TAB_COMMON) not in Scope and (TAB_COMMON, Scope1, TAB_COMMON) not in Scope:\r
                     break\r
             else:\r
                 ComSpeMacroDict.update(self._SectionsMacroDict[(SectionType, Scope)])\r
 \r
-            if ("COMMON", "COMMON","COMMON") in Scope:\r
+            if (TAB_COMMON, TAB_COMMON, TAB_COMMON) in Scope:\r
                 ComComMacroDict.update(self._SectionsMacroDict[(SectionType, Scope)])\r
 \r
         Macros.update(ComComMacroDict)\r
@@ -568,8 +573,8 @@ class InfParser(MetaFileParser):
             if Line[0] == TAB_SECTION_START and Line[-1] == TAB_SECTION_END:\r
                 if not GetHeaderComment:\r
                     for Cmt, LNo in Comments:\r
-                        self._Store(MODEL_META_DATA_HEADER_COMMENT, Cmt, '', '', 'COMMON',\r
-                                    'COMMON', self._Owner[-1], LNo, -1, LNo, -1, 0)\r
+                        self._Store(MODEL_META_DATA_HEADER_COMMENT, Cmt, '', '', TAB_COMMON,\r
+                                    TAB_COMMON, self._Owner[-1], LNo, -1, LNo, -1, 0)\r
                     GetHeaderComment = True\r
                 else:\r
                     TailComments.extend(SectionComments + Comments)\r
@@ -620,7 +625,7 @@ class InfParser(MetaFileParser):
             self._ValueList = ['', '', '']\r
             # parse current line, result will be put in self._ValueList\r
             self._SectionParser[self._SectionType](self)\r
-            if self._ValueList == None or self._ItemType == MODEL_META_DATA_DEFINE:\r
+            if self._ValueList is None or self._ItemType == MODEL_META_DATA_DEFINE:\r
                 self._ItemType = -1\r
                 Comments = []\r
                 continue\r
@@ -632,7 +637,7 @@ class InfParser(MetaFileParser):
             # Model, Value1, Value2, Value3, Arch, Platform, BelongsToItem=-1,\r
             # LineBegin=-1, ColumnBegin=-1, LineEnd=-1, ColumnEnd=-1, Enabled=-1\r
             #\r
-            for Arch, Platform,_ in self._Scope:\r
+            for Arch, Platform, _ in self._Scope:\r
                 LastItem = self._Store(self._SectionType,\r
                             self._ValueList[0],\r
                             self._ValueList[1],\r
@@ -658,8 +663,8 @@ class InfParser(MetaFileParser):
 \r
         # If there are tail comments in INF file, save to database whatever the comments are\r
         for Comment in TailComments:\r
-            self._Store(MODEL_META_DATA_TAIL_COMMENT, Comment[0], '', '', 'COMMON',\r
-                                'COMMON', self._Owner[-1], -1, -1, -1, -1, 0)\r
+            self._Store(MODEL_META_DATA_TAIL_COMMENT, Comment[0], '', '', TAB_COMMON,\r
+                                TAB_COMMON, self._Owner[-1], -1, -1, -1, -1, 0)\r
         self._Done()\r
 \r
     ## Data parser for the format in which there's path\r
@@ -835,6 +840,7 @@ class DscParser(MetaFileParser):
         TAB_ELSE.upper()                            :   MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSE,\r
         TAB_END_IF.upper()                          :   MODEL_META_DATA_CONDITIONAL_STATEMENT_ENDIF,\r
         TAB_USER_EXTENSIONS.upper()                 :   MODEL_META_DATA_USER_EXTENSION,\r
+        TAB_ERROR.upper()                           :   MODEL_META_DATA_CONDITIONAL_STATEMENT_ERROR,\r
     }\r
 \r
     # Valid names in define section\r
@@ -881,7 +887,7 @@ class DscParser(MetaFileParser):
     #\r
     def __init__(self, FilePath, FileType, Arch, Table, Owner= -1, From= -1):\r
         # prevent re-initialization\r
-        if hasattr(self, "_Table"):\r
+        if hasattr(self, "_Table") and self._Table is Table:\r
             return\r
         MetaFileParser.__init__(self, FilePath, FileType, Arch, Table, Owner, From)\r
         self._Version = 0x00010005  # Only EDK2 dsc file is supported\r
@@ -932,17 +938,24 @@ class DscParser(MetaFileParser):
                 self._SubsectionType = MODEL_UNKNOWN\r
                 self._SubsectionName = ''\r
                 self._Owner[-1] = -1\r
-                OwnerId = {}\r
+                OwnerId.clear()\r
                 continue\r
             # subsection header\r
             elif Line[0] == TAB_OPTION_START and Line[-1] == TAB_OPTION_END:\r
                 self._SubsectionType = MODEL_META_DATA_SUBSECTION_HEADER\r
             # directive line\r
             elif Line[0] == '!':\r
-                self._DirectiveParser()\r
+                TokenList = GetSplitValueList(Line, ' ', 1)\r
+                if TokenList[0] == TAB_INCLUDE:\r
+                    for Arch, ModuleType, DefaultStore in self._Scope:\r
+                        if self._SubsectionType != MODEL_UNKNOWN and Arch in OwnerId:\r
+                            self._Owner[-1] = OwnerId[Arch]\r
+                        self._DirectiveParser()\r
+                else:\r
+                    self._DirectiveParser()\r
                 continue\r
             if Line[0] == TAB_OPTION_START and not self._InSubsection:\r
-                EdkLogger.error("Parser", FILE_READ_FAILURE, "Missing the '{' before %s in Line %s" % (Line, Index+1),ExtraData=self.MetaFile)\r
+                EdkLogger.error("Parser", FILE_READ_FAILURE, "Missing the '{' before %s in Line %s" % (Line, Index+1), ExtraData=self.MetaFile)\r
 \r
             if self._InSubsection:\r
                 SectionType = self._SubsectionType\r
@@ -952,7 +965,7 @@ class DscParser(MetaFileParser):
 \r
             self._ValueList = ['', '', '']\r
             self._SectionParser[SectionType](self)\r
-            if self._ValueList == None:\r
+            if self._ValueList is None:\r
                 continue\r
             #\r
             # Model, Value1, Value2, Value3, Arch, ModuleType, BelongsToItem=-1, BelongsToFile=-1,\r
@@ -960,7 +973,7 @@ class DscParser(MetaFileParser):
             #\r
             for Arch, ModuleType, DefaultStore in self._Scope:\r
                 Owner = self._Owner[-1]\r
-                if self._SubsectionType != MODEL_UNKNOWN:\r
+                if self._SubsectionType != MODEL_UNKNOWN and Arch in OwnerId:\r
                     Owner = OwnerId[Arch]\r
                 self._LastItem = self._Store(\r
                                         self._ItemType,\r
@@ -1022,9 +1035,11 @@ class DscParser(MetaFileParser):
                             ExtraData=self._CurrentLine)\r
 \r
         ItemType = self.DataType[DirectiveName]\r
-        Scope = [['COMMON', 'COMMON','COMMON']]\r
+        Scope = [[TAB_COMMON, TAB_COMMON, TAB_COMMON]]\r
         if ItemType == MODEL_META_DATA_INCLUDE:\r
             Scope = self._Scope\r
+        elif ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ERROR:\r
+            Scope = self._Scope\r
         if ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ENDIF:\r
             # Remove all directives between !if and !endif, including themselves\r
             while self._DirectiveStack:\r
@@ -1038,7 +1053,7 @@ class DscParser(MetaFileParser):
                 EdkLogger.error("Parser", FORMAT_INVALID, "Redundant '!endif'",\r
                                 File=self.MetaFile, Line=self._LineIndex + 1,\r
                                 ExtraData=self._CurrentLine)\r
-        elif ItemType != MODEL_META_DATA_INCLUDE:\r
+        elif ItemType not in {MODEL_META_DATA_INCLUDE, MODEL_META_DATA_CONDITIONAL_STATEMENT_ERROR}:\r
             # Break if there's a !else is followed by a !elseif\r
             if ItemType == MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF and \\r
                self._DirectiveStack and \\r
@@ -1097,7 +1112,7 @@ class DscParser(MetaFileParser):
     @ParseMacro\r
     def _SkuIdParser(self):\r
         TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT)\r
-        if len(TokenList) not in (2,3):\r
+        if len(TokenList) not in (2, 3):\r
             EdkLogger.error('Parser', FORMAT_INVALID, "Correct format is '<Number>|<UiName>[|<UiName>]'",\r
                             ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1)\r
         self._ValueList[0:len(TokenList)] = TokenList\r
@@ -1157,7 +1172,7 @@ class DscParser(MetaFileParser):
 \r
         # Validate the datum type of Dynamic Defaul PCD and DynamicEx Default PCD\r
         ValueList = GetSplitValueList(self._ValueList[2])\r
-        if len(ValueList) > 1 and ValueList[1] in [TAB_UINT8 , TAB_UINT16, TAB_UINT32 , TAB_UINT64] \\r
+        if len(ValueList) > 1 and ValueList[1] in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64] \\r
                               and self._ItemType in [MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX_DEFAULT]:\r
             EdkLogger.error('Parser', FORMAT_INVALID, "The datum type '%s' of PCD is wrong" % ValueList[1],\r
                             ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1)\r
@@ -1165,7 +1180,7 @@ class DscParser(MetaFileParser):
         # Validate the VariableName of DynamicHii and DynamicExHii for PCD Entry must not be an empty string\r
         if self._ItemType in [MODEL_PCD_DYNAMIC_HII, MODEL_PCD_DYNAMIC_EX_HII]:\r
             DscPcdValueList = GetSplitValueList(TokenList[1], TAB_VALUE_SPLIT, 1)\r
-            if len(DscPcdValueList[0].replace('L','').replace('"','').strip()) == 0:\r
+            if len(DscPcdValueList[0].replace('L', '').replace('"', '').strip()) == 0:\r
                 EdkLogger.error('Parser', FORMAT_INVALID, "The VariableName field in the HII format PCD entry must not be an empty string",\r
                             ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1)\r
 \r
@@ -1183,6 +1198,7 @@ class DscParser(MetaFileParser):
         if self._CurrentLine[-1] == '{':\r
             self._ValueList[0] = self._CurrentLine[0:-1].strip()\r
             self._InSubsection = True\r
+            self._SubsectionType = MODEL_UNKNOWN\r
         else:\r
             self._ValueList[0] = self._CurrentLine\r
 \r
@@ -1243,6 +1259,13 @@ class DscParser(MetaFileParser):
         # PCD cannot be referenced in macro definition\r
         if self._ItemType not in [MODEL_META_DATA_DEFINE, MODEL_META_DATA_GLOBAL_DEFINE]:\r
             Macros.update(self._Symbols)\r
+        if GlobalData.BuildOptionPcd:\r
+            for Item in GlobalData.BuildOptionPcd:\r
+                if isinstance(Item, tuple):\r
+                    continue\r
+                PcdName, TmpValue = Item.split("=")\r
+                TmpValue = BuildOptionValue(TmpValue, self._GuidDict)\r
+                Macros[PcdName.strip()] = TmpValue\r
         return Macros\r
 \r
     def _PostProcess(self):\r
@@ -1277,6 +1300,7 @@ class DscParser(MetaFileParser):
             MODEL_META_DATA_BUILD_OPTION                    :   self.__ProcessBuildOption,\r
             MODEL_UNKNOWN                                   :   self._Skip,\r
             MODEL_META_DATA_USER_EXTENSION                  :   self._SkipUserExtension,\r
+            MODEL_META_DATA_CONDITIONAL_STATEMENT_ERROR     :   self._ProcessError,\r
         }\r
 \r
         self._Table = MetaFileStorage(self._RawTable.Cur, self.MetaFile, MODEL_FILE_DSC, True)\r
@@ -1285,7 +1309,7 @@ class DscParser(MetaFileParser):
         self._DirectiveEvalStack = []\r
         self._FileWithError = self.MetaFile\r
         self._FileLocalMacros = {}\r
-        self._SectionsMacroDict = {}\r
+        self._SectionsMacroDict.clear()\r
         GlobalData.gPlatformDefines = {}\r
 \r
         # Get all macro and PCD which has straitforward value\r
@@ -1294,7 +1318,7 @@ class DscParser(MetaFileParser):
         self._ContentIndex = 0\r
         self._InSubsection = False\r
         while self._ContentIndex < len(self._Content) :\r
-            Id, self._ItemType, V1, V2, V3, S1, S2, S3,Owner, self._From, \\r
+            Id, self._ItemType, V1, V2, V3, S1, S2, S3, Owner, self._From, \\r
                 LineStart, ColStart, LineEnd, ColEnd, Enabled = self._Content[self._ContentIndex]\r
 \r
             if self._From < 0:\r
@@ -1312,8 +1336,8 @@ class DscParser(MetaFileParser):
                     break\r
                 Record = self._Content[self._ContentIndex]\r
                 if LineStart == Record[10] and LineEnd == Record[12]:\r
-                    if [Record[5], Record[6],Record[7]] not in self._Scope:\r
-                        self._Scope.append([Record[5], Record[6],Record[7]])\r
+                    if [Record[5], Record[6], Record[7]] not in self._Scope:\r
+                        self._Scope.append([Record[5], Record[6], Record[7]])\r
                     self._ContentIndex += 1\r
                 else:\r
                     break\r
@@ -1327,8 +1351,8 @@ class DscParser(MetaFileParser):
                 self._InSubsection = False\r
             try:\r
                 Processer[self._ItemType]()\r
-            except EvaluationException, Excpt:\r
-                # \r
+            except EvaluationException as Excpt:\r
+                #\r
                 # Only catch expression evaluation error here. We need to report\r
                 # the precise number of line on which the error occurred\r
                 #\r
@@ -1349,12 +1373,12 @@ class DscParser(MetaFileParser):
                     EdkLogger.error('Parser', FORMAT_INVALID, "Invalid expression: %s" % str(Excpt),\r
                                     File=self._FileWithError, ExtraData=' '.join(self._ValueList),\r
                                     Line=self._LineIndex + 1)\r
-            except MacroException, Excpt:\r
+            except MacroException as Excpt:\r
                 EdkLogger.error('Parser', FORMAT_INVALID, str(Excpt),\r
                                 File=self._FileWithError, ExtraData=' '.join(self._ValueList),\r
                                 Line=self._LineIndex + 1)\r
 \r
-            if self._ValueList == None:\r
+            if self._ValueList is None:\r
                 continue\r
 \r
             NewOwner = self._IdMapping.get(Owner, -1)\r
@@ -1380,6 +1404,10 @@ class DscParser(MetaFileParser):
         GlobalData.gPlatformDefines.update(self._FileLocalMacros)\r
         self._PostProcessed = True\r
         self._Content = None\r
+    def _ProcessError(self):\r
+        if not self._Enabled:\r
+            return\r
+        EdkLogger.error('Parser', ERROR_STATEMENT, self._ValueList[1], File=self.MetaFile, Line=self._LineIndex + 1)\r
 \r
     def __ProcessSectionHeader(self):\r
         self._SectionName = self._ValueList[0]\r
@@ -1402,7 +1430,7 @@ class DscParser(MetaFileParser):
                         MODEL_PCD_DYNAMIC_VPD, MODEL_PCD_DYNAMIC_EX_DEFAULT, MODEL_PCD_DYNAMIC_EX_HII,\r
                         MODEL_PCD_DYNAMIC_EX_VPD):\r
             Records = self._RawTable.Query(PcdType, BelongsToItem= -1.0)\r
-            for TokenSpaceGuid, PcdName, Value, Dummy2, Dummy3, Dummy4,ID, Line in Records:\r
+            for TokenSpaceGuid, PcdName, Value, Dummy2, Dummy3, Dummy4, ID, Line in Records:\r
                 Name = TokenSpaceGuid + '.' + PcdName\r
                 if Name not in GlobalData.gPlatformOtherPcds:\r
                     PcdLine = Line\r
@@ -1447,11 +1475,11 @@ class DscParser(MetaFileParser):
             Macros.update(GlobalData.gGlobalDefines)\r
             try:\r
                 Result = ValueExpression(self._ValueList[1], Macros)()\r
-            except SymbolNotFound, Exc:\r
+            except SymbolNotFound as Exc:\r
                 EdkLogger.debug(EdkLogger.DEBUG_5, str(Exc), self._ValueList[1])\r
                 Result = False\r
-            except WrnExpression, Excpt:\r
-                # \r
+            except WrnExpression as Excpt:\r
+                #\r
                 # Catch expression evaluation warning here. We need to report\r
                 # the precise number of line and return the evaluation result\r
                 #\r
@@ -1497,18 +1525,18 @@ class DscParser(MetaFileParser):
             # Allow using system environment variables  in path after !include\r
             #\r
             __IncludeMacros['WORKSPACE'] = GlobalData.gGlobalDefines['WORKSPACE']\r
-            if "ECP_SOURCE" in GlobalData.gGlobalDefines.keys():\r
+            if "ECP_SOURCE" in GlobalData.gGlobalDefines:\r
                 __IncludeMacros['ECP_SOURCE'] = GlobalData.gGlobalDefines['ECP_SOURCE']\r
             #\r
             # During GenFds phase call DSC parser, will go into this branch.\r
             #\r
-            elif "ECP_SOURCE" in GlobalData.gCommandLineDefines.keys():\r
+            elif "ECP_SOURCE" in GlobalData.gCommandLineDefines:\r
                 __IncludeMacros['ECP_SOURCE'] = GlobalData.gCommandLineDefines['ECP_SOURCE']\r
 \r
             __IncludeMacros['EFI_SOURCE'] = GlobalData.gGlobalDefines['EFI_SOURCE']\r
             __IncludeMacros['EDK_SOURCE'] = GlobalData.gGlobalDefines['EDK_SOURCE']\r
             #\r
-            # Allow using MACROs comes from [Defines] section to keep compatible. \r
+            # Allow using MACROs comes from [Defines] section to keep compatible.\r
             #\r
             __IncludeMacros.update(self._Macros)\r
 \r
@@ -1530,32 +1558,27 @@ class DscParser(MetaFileParser):
 \r
             self._FileWithError = IncludedFile1\r
 \r
-            IncludedFileTable = MetaFileStorage(self._Table.Cur, IncludedFile1, MODEL_FILE_DSC, False)\r
-            Owner = self._Content[self._ContentIndex - 1][0]\r
+            FromItem = self._Content[self._ContentIndex - 1][0]\r
+            if self._InSubsection:\r
+                Owner = self._Content[self._ContentIndex - 1][8]\r
+            else:\r
+                Owner = self._Content[self._ContentIndex - 1][0]\r
+            IncludedFileTable = MetaFileStorage(self._Table.Cur, IncludedFile1, MODEL_FILE_DSC, False, FromItem=FromItem)\r
             Parser = DscParser(IncludedFile1, self._FileType, self._Arch, IncludedFileTable,\r
-                               Owner=Owner, From=Owner)\r
+                               Owner=Owner, From=FromItem)\r
 \r
             self.IncludedFiles.add (IncludedFile1)\r
 \r
-            # Does not allow lower level included file to include upper level included file\r
-            if Parser._From != Owner and int(Owner) > int (Parser._From):\r
-                EdkLogger.error('parser', FILE_ALREADY_EXIST, File=self._FileWithError,\r
-                    Line=self._LineIndex + 1, ExtraData="{0} is already included at a higher level.".format(IncludedFile1))\r
-\r
-\r
             # set the parser status with current status\r
             Parser._SectionName = self._SectionName\r
+            Parser._SubsectionType = self._SubsectionType\r
+            Parser._InSubsection = self._InSubsection\r
             Parser._SectionType = self._SectionType\r
             Parser._Scope = self._Scope\r
             Parser._Enabled = self._Enabled\r
             # Parse the included file\r
             Parser.Start()\r
 \r
-            # update current status with sub-parser's status\r
-            self._SectionName = Parser._SectionName\r
-            self._SectionType = Parser._SectionType\r
-            self._Scope = Parser._Scope\r
-            self._Enabled = Parser._Enabled\r
 \r
             # Insert all records in the table for the included file into dsc file table\r
             Records = IncludedFileTable.GetAll()\r
@@ -1591,7 +1614,7 @@ class DscParser(MetaFileParser):
         if PcdValue and "." not in self._ValueList[0]:\r
             try:\r
                 ValList[Index] = ValueExpression(PcdValue, self._Macros)(True)\r
-            except WrnExpression, Value:\r
+            except WrnExpression as Value:\r
                 ValList[Index] = Value.result\r
             except:\r
                 pass\r
@@ -1607,7 +1630,7 @@ class DscParser(MetaFileParser):
         try:\r
             self._ValueList[2] = '|'.join(ValList)\r
         except Exception:\r
-            print ValList\r
+            print(ValList)\r
 \r
     def __ProcessComponent(self):\r
         self._ValueList[0] = ReplaceMacro(self._ValueList[0], self._Macros)\r
@@ -1733,7 +1756,7 @@ class DecParser(MetaFileParser):
             # section content\r
             self._ValueList = ['', '', '']\r
             self._SectionParser[self._SectionType[0]](self)\r
-            if self._ValueList == None or self._ItemType == MODEL_META_DATA_DEFINE:\r
+            if self._ValueList is None or self._ItemType == MODEL_META_DATA_DEFINE:\r
                 self._ItemType = -1\r
                 self._Comments = []\r
                 continue\r
@@ -1776,7 +1799,7 @@ class DecParser(MetaFileParser):
         if self._DefinesCount > 1:\r
             EdkLogger.error('Parser', FORMAT_INVALID, 'Multiple [Defines] section is exist.', self.MetaFile )\r
         if self._DefinesCount == 0:\r
-            EdkLogger.error('Parser', FORMAT_INVALID, 'No [Defines] section exist.',self.MetaFile)\r
+            EdkLogger.error('Parser', FORMAT_INVALID, 'No [Defines] section exist.', self.MetaFile)\r
         self._Done()\r
 \r
 \r
@@ -1825,7 +1848,7 @@ class DecParser(MetaFileParser):
             if len(ItemList) > 1:\r
                 S1 = ItemList[1].upper()\r
             else:\r
-                S1 = 'COMMON'\r
+                S1 = TAB_ARCH_COMMON\r
             ArchList.add(S1)\r
             # S2 may be Platform or ModuleType\r
             if len(ItemList) > 2:\r
@@ -1836,18 +1859,18 @@ class DecParser(MetaFileParser):
                         EdkLogger.error("Parser", FORMAT_INVALID, 'Please use keyword "Private" as section tag modifier.',\r
                                         File=self.MetaFile, Line=self._LineIndex + 1, ExtraData=self._CurrentLine)\r
             else:\r
-                S2 = 'COMMON'\r
+                S2 = TAB_COMMON\r
             PrivateList.add(S2)\r
             if [S1, S2, self.DataType[self._SectionName]] not in self._Scope:\r
                 self._Scope.append([S1, S2, self.DataType[self._SectionName]])\r
 \r
         # 'COMMON' must not be used with specific ARCHs at the same section\r
-        if 'COMMON' in ArchList and len(ArchList) > 1:\r
+        if TAB_ARCH_COMMON in ArchList and len(ArchList) > 1:\r
             EdkLogger.error('Parser', FORMAT_INVALID, "'common' ARCH must not be used with specific ARCHs",\r
                             File=self.MetaFile, Line=self._LineIndex + 1, ExtraData=self._CurrentLine)\r
 \r
         # It is not permissible to mix section tags without the Private attribute with section tags with the Private attribute\r
-        if 'COMMON' in PrivateList and len(PrivateList) > 1:\r
+        if TAB_COMMON in PrivateList and len(PrivateList) > 1:\r
             EdkLogger.error('Parser', FORMAT_INVALID, "Can't mix section tags without the Private attribute with section tags with the Private attribute",\r
                             File=self.MetaFile, Line=self._LineIndex + 1, ExtraData=self._CurrentLine)\r
 \r
@@ -1920,7 +1943,7 @@ class DecParser(MetaFileParser):
                     self._CurrentStructurePcdName = ""\r
                 else:\r
                     if self._CurrentStructurePcdName != TAB_SPLIT.join(PcdNames[:2]):\r
-                        EdkLogger.error('Parser', FORMAT_INVALID, "Pcd Name does not match: %s and %s " % (self._CurrentStructurePcdName , TAB_SPLIT.join(PcdNames[:2])),\r
+                        EdkLogger.error('Parser', FORMAT_INVALID, "Pcd Name does not match: %s and %s " % (self._CurrentStructurePcdName, TAB_SPLIT.join(PcdNames[:2])),\r
                                 File=self.MetaFile, Line=self._LineIndex + 1)\r
                     self._ValueList[1] = TAB_SPLIT.join(PcdNames[2:])\r
                     self._ValueList[2] = PcdTockens[1]\r
@@ -1996,7 +2019,7 @@ class DecParser(MetaFileParser):
                 try:\r
                     self._GuidDict.update(self._AllPcdDict)\r
                     ValueList[0] = ValueExpressionEx(ValueList[0], ValueList[1], self._GuidDict)(True)\r
-                except BadExpression, Value:\r
+                except BadExpression as Value:\r
                     EdkLogger.error('Parser', FORMAT_INVALID, Value, ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1)\r
             # check format of default value against the datum type\r
             IsValid, Cause = CheckPcdDatum(ValueList[1], ValueList[0])\r