From nobody Fri May 3 05:47:03 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 1526321371529319.37918102675246; Mon, 14 May 2018 11:09:31 -0700 (PDT) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 5B7BB21CAD9BA; Mon, 14 May 2018 11:09:26 -0700 (PDT) Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 21EC920969673 for ; Mon, 14 May 2018 11:09:25 -0700 (PDT) Received: from orsmga001.jf.intel.com ([10.7.209.18]) by orsmga105.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 14 May 2018 11:09:23 -0700 Received: from jcarsey-desk1.amr.corp.intel.com ([10.7.159.144]) by orsmga001.jf.intel.com with ESMTP; 14 May 2018 11:09:23 -0700 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.100; helo=mga07.intel.com; envelope-from=jaben.carsey@intel.com; receiver=edk2-devel@lists.01.org X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.49,401,1520924400"; d="scan'208";a="55814253" From: Jaben Carsey To: edk2-devel@lists.01.org Date: Mon, 14 May 2018 11:09:10 -0700 Message-Id: <1d945b8d75cc240968753642344be9909eb265bb.1526321052.git.jaben.carsey@intel.com> X-Mailer: git-send-email 2.16.2.windows.1 In-Reply-To: References: In-Reply-To: References: Subject: [edk2] [PATCH v1 01/11] BaseTools: decorate base classes to prevent instantiation X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.26 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Liming Gao MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" use python's ABC (abstract base class) to raise type errors if we instantia= te classes we designed to be used only as base classes for other classes. Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jaben Carsey --- BaseTools/Source/Python/AutoGen/AutoGen.py | 4 ++++ BaseTools/Source/Python/AutoGen/GenMake.py | 4 ++++ BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py | 4 ++++ BaseTools/Source/Python/Common/Expression.py | 4 ++++ BaseTools/Source/Python/Common/VariableAttributes.py | 6 +++++- BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py | 4 ++++ BaseTools/Source/Python/Table/Table.py | 6 +++++- BaseTools/Source/Python/Workspace/BuildClassObject.py | 7 +++++++ BaseTools/Source/Python/Workspace/MetaFileParser.py | 4 ++++ 9 files changed, 41 insertions(+), 2 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/AutoGen.py b/BaseTools/Source/= Python/AutoGen/AutoGen.py index 54f6b1f173b2..619e1e41e32b 100644 --- a/BaseTools/Source/Python/AutoGen/AutoGen.py +++ b/BaseTools/Source/Python/AutoGen/AutoGen.py @@ -47,6 +47,7 @@ import hashlib from GenVar import VariableMgr,var_info from collections import OrderedDict from collections import defaultdict +from abc import ABCMeta, abstractmethod =20 ## Regular expression for splitting Dependency Expression string into toke= ns gDepexTokenPattern =3D re.compile("(\(|\)|\w+| \S+\.inf)") @@ -197,6 +198,9 @@ class AutoGen(object): cls.__ObjectCache[Key] =3D super(AutoGen, cls).__new__(cls) return cls.__ObjectCache[Key] =20 + __metaclass__ =3D ABCMeta + # prevent this class from being accidentally instantiated + @abstractmethod def __init__ (self, Workspace, MetaFile, Target, Toolchain, Arch, *arg= s, **kwargs): super(AutoGen, self).__init__(self, Workspace, MetaFile, Target, T= oolchain, Arch, *args, **kwargs) =20 diff --git a/BaseTools/Source/Python/AutoGen/GenMake.py b/BaseTools/Source/= Python/AutoGen/GenMake.py index a37350742240..68ec9a817133 100644 --- a/BaseTools/Source/Python/AutoGen/GenMake.py +++ b/BaseTools/Source/Python/AutoGen/GenMake.py @@ -26,6 +26,7 @@ from Common.String import * from BuildEngine import * import Common.GlobalData as GlobalData from collections import OrderedDict +from abc import ABCMeta, abstractmethod =20 ## Regular expression for finding header file inclusions gIncludePattern =3D re.compile(r"^[ \t]*#?[ \t]*include(?:[ \t]*(?:\\(?:\r= \n|\r|\n))*[ \t]*)*(?:\(?[\"<]?[ \t]*)([-\w.\\/() \t]+)(?:[ \t]*[\">]?\)?)"= , re.MULTILINE | re.UNICODE | re.IGNORECASE) @@ -171,6 +172,9 @@ class BuildFile(object): # # @param AutoGenObject Object of AutoGen class # + __metaclass__ =3D ABCMeta + # prevent this class from being accidentally instantiated + @abstractmethod def __init__(self, AutoGenObject): self._AutoGenObject =3D AutoGenObject self._FileType =3D gMakeType diff --git a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py b/B= aseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py index 64d4965e9662..e2b4795129ef 100644 --- a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py +++ b/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py @@ -20,6 +20,7 @@ from Common.Misc import * from StringIO import StringIO from struct import pack from Common.DataType import * +from abc import ABCMeta, abstractmethod =20 class VAR_CHECK_PCD_VARIABLE_TAB_CONTAINER(object): def __init__(self): @@ -222,6 +223,9 @@ class VAR_CHECK_PCD_VARIABLE_TAB(object): =20 =20 class VAR_CHECK_PCD_VALID_OBJ(object): + __metaclass__ =3D ABCMeta + # prevent this class from being accidentally instantiated + @abstractmethod def __init__(self, VarOffset, data, PcdDataType): self.Type =3D 1 self.Length =3D 0 # Length include this header diff --git a/BaseTools/Source/Python/Common/Expression.py b/BaseTools/Sourc= e/Python/Common/Expression.py index 9e9d9fdc02e7..9fa07c6add16 100644 --- a/BaseTools/Source/Python/Common/Expression.py +++ b/BaseTools/Source/Python/Common/Expression.py @@ -19,6 +19,7 @@ from Misc import GuidStringToGuidStructureString, ParseFi= eldValue, IsFieldValueA import Common.EdkLogger as EdkLogger import copy from Common.DataType import * +from abc import ABCMeta, abstractmethod =20 ERR_STRING_EXPR =3D 'This operator cannot be used in string expres= sion: [%s].' ERR_SNYTAX =3D 'Syntax error, the rest of expression cannot b= e evaluated: [%s].' @@ -202,6 +203,9 @@ def IntToStr(Value): SupportedInMacroList =3D ['TARGET', 'TOOL_CHAIN_TAG', 'ARCH', 'FAMILY'] =20 class BaseExpression(object): + __metaclass__ =3D ABCMeta + # prevent this class from being accidentally instantiated + @abstractmethod def __init__(self, *args, **kwargs): super(BaseExpression, self).__init__() =20 diff --git a/BaseTools/Source/Python/Common/VariableAttributes.py b/BaseToo= ls/Source/Python/Common/VariableAttributes.py index a2e22ca0409c..72f64fff3864 100644 --- a/BaseTools/Source/Python/Common/VariableAttributes.py +++ b/BaseTools/Source/Python/Common/VariableAttributes.py @@ -3,7 +3,7 @@ # This file is used to handle the variable attributes and property informa= tion # # -# Copyright (c) 2015, Intel Corporation. All rights reserved.
+# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
# This program and the accompanying materials # are licensed and made available under the terms and conditions of the BS= D License # which accompanies this distribution. The full text of the license may b= e found at @@ -12,6 +12,7 @@ # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMP= LIED. # +from abc import ABCMeta, abstractmethod =20 class VariableAttributes(object): EFI_VARIABLE_NON_VOLATILE =3D 0x00000001 @@ -25,6 +26,9 @@ class VariableAttributes(object): "RO":VAR_CHECK_VARIABLE_PROPERTY_READ_ONLY } =20 + __metaclass__ =3D ABCMeta + # prevent this class from being accidentally instantiated + @abstractmethod def __init__(self): pass =20 diff --git a/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.p= y b/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py index 4d61cd1cea91..e5c43b629151 100644 --- a/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py @@ -35,6 +35,7 @@ from MetaFileTable import MetaFileStorage from GenFds.FdfParser import FdfParser from Common.LongFilePathSupport import OpenLongFilePath as open from Common.LongFilePathSupport import CodecOpenLongFilePath +from abc import ABCMeta, abstractmethod =20 ## A decorator used to parse macro definition def ParseMacro(Parser): @@ -146,6 +147,9 @@ class MetaFileParser(object): # @param Owner Owner ID (for sub-section parsing) # @param From ID from which the data comes (for !INC= LUDE directive) # + __metaclass__ =3D ABCMeta + # prevent this class from being accidentally instantiated + @abstractmethod def __init__(self, FilePath, FileType, Table, Owner=3D-1, From=3D-1): self._Table =3D Table self._RawTable =3D Table diff --git a/BaseTools/Source/Python/Table/Table.py b/BaseTools/Source/Pyth= on/Table/Table.py index c311df91c2ec..46bc92ea8377 100644 --- a/BaseTools/Source/Python/Table/Table.py +++ b/BaseTools/Source/Python/Table/Table.py @@ -1,7 +1,7 @@ ## @file # This file is used to create/update/query/erase a common table # -# Copyright (c) 2008, Intel Corporation. All rights reserved.
+# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.
# This program and the accompanying materials # are licensed and made available under the terms and conditions of the BS= D License # which accompanies this distribution. The full text of the license may b= e found at @@ -15,6 +15,7 @@ # Import Modules # import Common.EdkLogger as EdkLogger +from abc import ABCMeta, abstractmethod =20 ## TableFile # @@ -26,6 +27,9 @@ import Common.EdkLogger as EdkLogger # @param TableName: Name of the table # class Table(object): + __metaclass__ =3D ABCMeta + # prevent this class from being accidentally instantiated + @abstractmethod def __init__(self, Cursor): self.Cur =3D Cursor self.Table =3D '' diff --git a/BaseTools/Source/Python/Workspace/BuildClassObject.py b/BaseTo= ols/Source/Python/Workspace/BuildClassObject.py index 209315d901b2..5f34e8e0bc69 100644 --- a/BaseTools/Source/Python/Workspace/BuildClassObject.py +++ b/BaseTools/Source/Python/Workspace/BuildClassObject.py @@ -18,6 +18,7 @@ from Common.Misc import RealPath2 from Common.BuildToolError import * from Common.DataType import * import collections +from abc import ABCMeta, abstractmethod =20 ## PcdClassObject # @@ -381,6 +382,9 @@ class ModuleBuildClassObject(object): # { [(PcdCName, PcdGuidCName)] : PcdClassObject} # class PackageBuildClassObject(object): + __metaclass__ =3D ABCMeta + # prevent this class from being accidentally instantiated + @abstractmethod def __init__(self): self.MetaFile =3D '' self.PackageName =3D '' @@ -451,6 +455,9 @@ class PackageBuildClassObject(object): # { [BuildOptionKey] : BuildOptionValue } # class PlatformBuildClassObject(object): + __metaclass__ =3D ABCMeta + # prevent this class from being accidentally instantiated + @abstractmethod def __init__(self): self.MetaFile =3D '' self.PlatformName =3D '' diff --git a/BaseTools/Source/Python/Workspace/MetaFileParser.py b/BaseTool= s/Source/Python/Workspace/MetaFileParser.py index 36843643ed13..21b20bce4018 100644 --- a/BaseTools/Source/Python/Workspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Workspace/MetaFileParser.py @@ -34,6 +34,7 @@ from Common.LongFilePathSupport import OpenLongFilePath a= s open from collections import defaultdict from MetaFileTable import MetaFileStorage from MetaFileCommentParser import CheckInfComment +from abc import ABCMeta, abstractmethod =20 ## RegEx for finding file versions hexVersionPattern =3D re.compile(r'0[xX][\da-f-A-F]{5,8}') @@ -154,6 +155,9 @@ class MetaFileParser(object): # @param Owner Owner ID (for sub-section parsing) # @param From ID from which the data comes (for !INC= LUDE directive) # + __metaclass__ =3D ABCMeta + # prevent this class from being accidentally instantiated + @abstractmethod def __init__(self, FilePath, FileType, Arch, Table, Owner=3D -1, From= =3D -1): self._Table =3D Table self._RawTable =3D Table --=20 2.16.2.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Fri May 3 05:47:03 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 1526321374486168.3859400920502; Mon, 14 May 2018 11:09:34 -0700 (PDT) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 8963C2096966E; Mon, 14 May 2018 11:09:26 -0700 (PDT) Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 1E76620969670 for ; Mon, 14 May 2018 11:09:25 -0700 (PDT) Received: from orsmga001.jf.intel.com ([10.7.209.18]) by orsmga105.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 14 May 2018 11:09:23 -0700 Received: from jcarsey-desk1.amr.corp.intel.com ([10.7.159.144]) by orsmga001.jf.intel.com with ESMTP; 14 May 2018 11:09:23 -0700 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.100; helo=mga07.intel.com; envelope-from=jaben.carsey@intel.com; receiver=edk2-devel@lists.01.org X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.49,401,1520924400"; d="scan'208";a="55814257" From: Jaben Carsey To: edk2-devel@lists.01.org Date: Mon, 14 May 2018 11:09:11 -0700 Message-Id: <66919e48fca06bf2e58e529e4b0243beb45e3185.1526321052.git.jaben.carsey@intel.com> X-Mailer: git-send-email 2.16.2.windows.1 In-Reply-To: References: In-Reply-To: References: Subject: [edk2] [PATCH v1 02/11] BaseTools: Workspace - create a base class X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.26 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Liming Gao MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" refactor 3 classes and create a new base class for their shared functions. Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jaben Carsey --- BaseTools/Source/Python/Workspace/BuildClassObject.py | 140 +++++++-------= ------ 1 file changed, 50 insertions(+), 90 deletions(-) diff --git a/BaseTools/Source/Python/Workspace/BuildClassObject.py b/BaseTo= ols/Source/Python/Workspace/BuildClassObject.py index 5f34e8e0bc69..db9518cdff17 100644 --- a/BaseTools/Source/Python/Workspace/BuildClassObject.py +++ b/BaseTools/Source/Python/Workspace/BuildClassObject.py @@ -253,6 +253,47 @@ class LibraryClassObject(object): if Type is not None: self.SupModList =3D CleanString(Type).split(DataType.TAB_SPACE= _SPLIT) =20 +## BuildClassObjectBase +# +# This is a base class for classes later in this file. it simplifies by=20 +# not requiring duplication of standard functions. +# This class is not intended for use outside of being a base class. +# +class BuildClassObjectBase(object): + __metaclass__ =3D ABCMeta + # prevent this class from being accidentally instantiated + @abstractmethod + def __init__(self, *a,**k): + super(BuildClassObjectBase,self).__init__(*a,**k) + + ## Convert the class to a string + # + # Convert member MetaFile of the class to a string + # + # @retval string Formatted String + # + def __str__(self): + return str(self.MetaFile) + + ## Override __eq__ function + # + # Check whether ModuleBuildClassObjects are the same + # + # @retval False The two ModuleBuildClassObjects are different + # @retval True The two ModuleBuildClassObjects are the same + # + def __eq__(self, Other): + return Other and self.MetaFile =3D=3D Other + + ## Override __hash__ function + # + # Use MetaFile as key in hash table + # + # @retval string Key for hash table + # + def __hash__(self): + return hash(self.MetaFile) + ## ModuleBuildClassObject # # This Class defines ModuleBuildClass @@ -297,8 +338,9 @@ class LibraryClassObject(object): # { [BuildOptionKey] : BuildOptionValue} # @var Depex: To store value for Depex # -class ModuleBuildClassObject(object): - def __init__(self): +class ModuleBuildClassObject(BuildClassObjectBase): + def __init__(self, *a, **k): + super(ModuleBuildClassObject,self).__init__(*a,**k) self.AutoGenVersion =3D 0 self.MetaFile =3D '' self.BaseName =3D '' @@ -330,34 +372,6 @@ class ModuleBuildClassObject(object): self.BuildOptions =3D {} self.Depex =3D {} =20 - ## Convert the class to a string - # - # Convert member MetaFile of the class to a string - # - # @retval string Formatted String - # - def __str__(self): - return str(self.MetaFile) - - ## Override __eq__ function - # - # Check whether ModuleBuildClassObjects are the same - # - # @retval False The two ModuleBuildClassObjects are different - # @retval True The two ModuleBuildClassObjects are the same - # - def __eq__(self, Other): - return self.MetaFile =3D=3D Other - - ## Override __hash__ function - # - # Use MetaFile as key in hash table - # - # @retval string Key for hash table - # - def __hash__(self): - return hash(self.MetaFile) - ## PackageBuildClassObject # # This Class defines PackageBuildClass @@ -381,11 +395,12 @@ class ModuleBuildClassObject(object): # @var Pcds: To store value for Pcds, it is a set structure as # { [(PcdCName, PcdGuidCName)] : PcdClassObject} # -class PackageBuildClassObject(object): +class PackageBuildClassObject(BuildClassObjectBase): __metaclass__ =3D ABCMeta # prevent this class from being accidentally instantiated @abstractmethod - def __init__(self): + def __init__(self, *a, **k): + super(PackageBuildClassObject,self).__init__(*a,**k) self.MetaFile =3D '' self.PackageName =3D '' self.Guid =3D '' @@ -398,34 +413,6 @@ class PackageBuildClassObject(object): self.LibraryClasses =3D {} self.Pcds =3D {} =20 - ## Convert the class to a string - # - # Convert member MetaFile of the class to a string - # - # @retval string Formatted String - # - def __str__(self): - return str(self.MetaFile) - - ## Override __eq__ function - # - # Check whether PackageBuildClassObjects are the same - # - # @retval False The two PackageBuildClassObjects are different - # @retval True The two PackageBuildClassObjects are the same - # - def __eq__(self, Other): - return self.MetaFile =3D=3D Other - - ## Override __hash__ function - # - # Use MetaFile as key in hash table - # - # @retval string Key for hash table - # - def __hash__(self): - return hash(self.MetaFile) - ## PlatformBuildClassObject # # This Class defines PlatformBuildClass @@ -454,11 +441,12 @@ class PackageBuildClassObject(object): # @var BuildOptions: To store value for BuildOptions, it is a set str= ucture as # { [BuildOptionKey] : BuildOptionValue } # -class PlatformBuildClassObject(object): +class PlatformBuildClassObject(BuildClassObjectBase): __metaclass__ =3D ABCMeta # prevent this class from being accidentally instantiated @abstractmethod - def __init__(self): + def __init__(self, *a, **k): + super(PlatformBuildClassObject,self).__init__(*a,**k) self.MetaFile =3D '' self.PlatformName =3D '' self.Guid =3D '' @@ -476,31 +464,3 @@ class PlatformBuildClassObject(object): self.Libraries =3D {} self.Pcds =3D {} self.BuildOptions =3D {} - - ## Convert the class to a string - # - # Convert member MetaFile of the class to a string - # - # @retval string Formatted String - # - def __str__(self): - return str(self.MetaFile) - - ## Override __eq__ function - # - # Check whether PlatformBuildClassObjects are the same - # - # @retval False The two PlatformBuildClassObjects are different - # @retval True The two PlatformBuildClassObjects are the same - # - def __eq__(self, Other): - return self.MetaFile =3D=3D Other - - ## Override __hash__ function - # - # Use MetaFile as key in hash table - # - # @retval string Key for hash table - # - def __hash__(self): - return hash(self.MetaFile) --=20 2.16.2.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Fri May 3 05:47:03 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 1526321384259321.6695703549633; Mon, 14 May 2018 11:09:44 -0700 (PDT) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 26C7E20969677; Mon, 14 May 2018 11:09:27 -0700 (PDT) Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 340F42096966D for ; Mon, 14 May 2018 11:09:25 -0700 (PDT) Received: from orsmga001.jf.intel.com ([10.7.209.18]) by orsmga105.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 14 May 2018 11:09:23 -0700 Received: from jcarsey-desk1.amr.corp.intel.com ([10.7.159.144]) by orsmga001.jf.intel.com with ESMTP; 14 May 2018 11:09:23 -0700 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.100; helo=mga07.intel.com; envelope-from=jaben.carsey@intel.com; receiver=edk2-devel@lists.01.org X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.49,401,1520924400"; d="scan'208";a="55814261" From: Jaben Carsey To: edk2-devel@lists.01.org Date: Mon, 14 May 2018 11:09:12 -0700 Message-Id: X-Mailer: git-send-email 2.16.2.windows.1 In-Reply-To: References: In-Reply-To: References: Subject: [edk2] [PATCH v1 03/11] BaseTools: remove unused code X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.26 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Liming Gao MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" delete commented out code delete never used class/variable/function/import refactor to remove Ffs class dont construct class just for class attribute Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jaben Carsey --- BaseTools/Source/Python/AutoGen/GenMake.py | 17 ++-- BaseTools/Source/Python/CommonDataClass/DataClass.py | 47 +---------- BaseTools/Source/Python/Ecc/Database.py | 76 +-------------= --- BaseTools/Source/Python/Ecc/c.py | 1 - BaseTools/Source/Python/GenFds/CapsuleData.py | 1 - BaseTools/Source/Python/GenFds/CompressSection.py | 6 +- BaseTools/Source/Python/GenFds/DataSection.py | 4 +- BaseTools/Source/Python/GenFds/DepexSection.py | 1 - BaseTools/Source/Python/GenFds/EfiSection.py | 16 ++-- BaseTools/Source/Python/GenFds/Ffs.py | 88 ++++++++------= ------ BaseTools/Source/Python/GenFds/FfsFileStatement.py | 4 +- BaseTools/Source/Python/GenFds/FfsInfStatement.py | 10 +-- BaseTools/Source/Python/GenFds/Fv.py | 1 - BaseTools/Source/Python/GenFds/FvImageSection.py | 6 +- BaseTools/Source/Python/GenFds/GuidSection.py | 4 +- BaseTools/Source/Python/GenFds/OptRomInfStatement.py | 7 +- BaseTools/Source/Python/GenFds/UiSection.py | 6 +- BaseTools/Source/Python/GenFds/VerSection.py | 6 +- BaseTools/Source/Python/Workspace/WorkspaceDatabase.py | 18 ++-- BaseTools/Source/Python/build/build.py | 2 +- 20 files changed, 81 insertions(+), 240 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/GenMake.py b/BaseTools/Source/= Python/AutoGen/GenMake.py index 68ec9a817133..1c8ab7fe1ec8 100644 --- a/BaseTools/Source/Python/AutoGen/GenMake.py +++ b/BaseTools/Source/Python/AutoGen/GenMake.py @@ -74,8 +74,6 @@ class BuildFile(object): ## template used to generate the build file (i.e. makefile if using ma= ke) _TEMPLATE_ =3D TemplateString('') =20 - _DEFAULT_FILE_NAME_ =3D "Makefile" - ## default file name for each type of build file _FILE_NAME_ =3D { "nmake" : "Makefile", @@ -151,23 +149,18 @@ class BuildFile(object): "gmake" : "test -f %(Src)s && $(CP) %(Src)s %(Dst)s" } =20 - _CD_TEMPLATE_ =3D { - "nmake" : 'if exist %(dir)s cd %(dir)s', - "gmake" : "test -e %(dir)s && cd %(dir)s" - } - _MAKE_TEMPLATE_ =3D { "nmake" : 'if exist %(file)s "$(MAKE)" $(MAKE_FLAGS) -f %(file)s= ', "gmake" : 'test -e %(file)s && "$(MAKE)" $(MAKE_FLAGS) -f %(file= )s' } =20 - _INCLUDE_CMD_ =3D { - "nmake" : '!INCLUDE', - "gmake" : "include" + _INC_FLAG_ =3D { + "MSFT" : "/I", + "GCC" : "-I", + "INTEL" : "-I", + "RVCT" : "-I" } =20 - _INC_FLAG_ =3D {"MSFT" : "/I", "GCC" : "-I", "INTEL" : "-I", "RVCT" : = "-I"} - ## Constructor of BuildFile # # @param AutoGenObject Object of AutoGen class diff --git a/BaseTools/Source/Python/CommonDataClass/DataClass.py b/BaseToo= ls/Source/Python/CommonDataClass/DataClass.py index 31ed46c7ec56..ddf3270ad8a5 100644 --- a/BaseTools/Source/Python/CommonDataClass/DataClass.py +++ b/BaseTools/Source/Python/CommonDataClass/DataClass.py @@ -1,7 +1,7 @@ ## @file # This file is used to define class for data structure used in ECC # -# Copyright (c) 2008 - 2014, Intel Corporation. All rights reserved.
+# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.
# This program and the accompanying materials # are licensed and made available under the terms and conditions of the BS= D License # which accompanies this distribution. The full text of the license may= be found at @@ -290,51 +290,6 @@ class IdentifierClass(object): self.EndLine =3D EndLine self.EndColumn =3D EndColumn =20 -## PcdClass -# -# This class defines a structure of a Pcd -# -# @param ID: ID of a Pcd -# @param CName: CName of a Pcd -# @param TokenSpaceGuidCName: TokenSpaceGuidCName of a Pcd -# @param Token: Token of a Pcd -# @param DatumType: DatumType of a Pcd -# @param Model: Model of a Pcd -# @param BelongsToFile: The Pcd belongs to which file -# @param BelongsToFunction: The Pcd belongs to which function -# @param StartLine: StartLine of a Pcd -# @param StartColumn: StartColumn of a Pcd -# @param EndLine: EndLine of a Pcd -# @param EndColumn: EndColumn of a Pcd -# -# @var ID: ID of a Pcd -# @var CName: CName of a Pcd -# @var TokenSpaceGuidCName: TokenSpaceGuidCName of a Pcd -# @var Token: Token of a Pcd -# @var DatumType: DatumType of a Pcd -# @var Model: Model of a Pcd -# @var BelongsToFile: The Pcd belongs to which file -# @var BelongsToFunction: The Pcd belongs to which function -# @var StartLine: StartLine of a Pcd -# @var StartColumn: StartColumn of a Pcd -# @var EndLine: EndLine of a Pcd -# @var EndColumn: EndColumn of a Pcd -# -class PcdDataClass(object): - def __init__(self, ID =3D -1, CName =3D '', TokenSpaceGuidCName =3D ''= , Token =3D '', DatumType =3D '', Model =3D MODEL_UNKNOWN, \ - BelongsToFile =3D -1, BelongsToFunction =3D -1, StartLine= =3D -1, StartColumn =3D -1, EndLine =3D -1, EndColumn =3D -1): - self.ID =3D ID - self.CName =3D CName - self.TokenSpaceGuidCName =3D TokenSpaceGuidCName - self.Token =3D Token - self.DatumType =3D DatumType - self.BelongsToFile =3D BelongsToFile - self.BelongsToFunction =3D BelongsToFunction - self.StartLine =3D StartLine - self.StartColumn =3D StartColumn - self.EndLine =3D EndLine - self.EndColumn =3D EndColumn - ## FileClass # # This class defines a structure of a file diff --git a/BaseTools/Source/Python/Ecc/Database.py b/BaseTools/Source/Pyt= hon/Ecc/Database.py index 204117512452..dbc699502934 100644 --- a/BaseTools/Source/Python/Ecc/Database.py +++ b/BaseTools/Source/Python/Ecc/Database.py @@ -1,7 +1,7 @@ ## @file # This file is used to create a database used by ECC tool # -# Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.
+# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# This program and the accompanying materials # are licensed and made available under the terms and conditions of the BS= D License # which accompanies this distribution. The full text of the license may b= e found at @@ -211,59 +211,6 @@ class Database(object): =20 EdkLogger.verbose("Insert information from file %s ... DONE!" % Fi= le.FullPath) =20 - ## UpdateIdentifierBelongsToFunction - # - # Update the field "BelongsToFunction" for each Indentifier - # - # - def UpdateIdentifierBelongsToFunction_disabled(self): - EdkLogger.verbose("Update 'BelongsToFunction' for Identifiers star= ted ...") - - SqlCommand =3D """select ID, BelongsToFile, StartLine, EndLine, Mo= del from Identifier""" - EdkLogger.debug(4, "SqlCommand: %s" %SqlCommand) - self.Cur.execute(SqlCommand) - Records =3D self.Cur.fetchall() - for Record in Records: - IdentifierID =3D Record[0] - BelongsToFile =3D Record[1] - StartLine =3D Record[2] - EndLine =3D Record[3] - Model =3D Record[4] - - # - # Check whether an identifier belongs to a function - # - EdkLogger.debug(4, "For common identifiers ... ") - SqlCommand =3D """select ID from Function - where StartLine < %s and EndLine > %s - and BelongsToFile =3D %s""" % (StartLine, EndLine,= BelongsToFile) - EdkLogger.debug(4, "SqlCommand: %s" %SqlCommand) - self.Cur.execute(SqlCommand) - IDs =3D self.Cur.fetchall() - for ID in IDs: - SqlCommand =3D """Update Identifier set BelongsToFunction = =3D %s where ID =3D %s""" % (ID[0], IdentifierID) - EdkLogger.debug(4, "SqlCommand: %s" %SqlCommand) - self.Cur.execute(SqlCommand) - - # - # Check whether the identifier is a function header - # - EdkLogger.debug(4, "For function headers ... ") - if Model =3D=3D DataClass.MODEL_IDENTIFIER_COMMENT: - SqlCommand =3D """select ID from Function - where StartLine =3D %s + 1 - and BelongsToFile =3D %s""" % (EndLine, BelongsToF= ile) - EdkLogger.debug(4, "SqlCommand: %s" %SqlCommand) - self.Cur.execute(SqlCommand) - IDs =3D self.Cur.fetchall() - for ID in IDs: - SqlCommand =3D """Update Identifier set BelongsToFunct= ion =3D %s, Model =3D %s where ID =3D %s""" % (ID[0], DataClass.MODEL_IDENT= IFIER_FUNCTION_HEADER, IdentifierID) - EdkLogger.debug(4, "SqlCommand: %s" %SqlCommand) - self.Cur.execute(SqlCommand) - - EdkLogger.verbose("Update 'BelongsToFunction' for Identifiers ... = DONE") - - ## UpdateIdentifierBelongsToFunction # # Update the field "BelongsToFunction" for each Indentifier @@ -281,8 +228,6 @@ class Database(object): BelongsToFile =3D Record[1] StartLine =3D Record[2] EndLine =3D Record[3] - #Data1.append(("'file%s'" % BelongsToFile, FunctionID, Belongs= ToFile, StartLine, EndLine)) - #Data2.append(("'file%s'" % BelongsToFile, FunctionID, DataCla= ss.MODEL_IDENTIFIER_FUNCTION_HEADER, BelongsToFile, DataClass.MODEL_IDENTIF= IER_COMMENT, StartLine - 1)) =20 SqlCommand =3D """Update Identifier%s set BelongsToFunction = =3D %s where BelongsToFile =3D %s and StartLine > %s and EndLine < %s""" % \ (BelongsToFile, FunctionID, BelongsToFile, StartLi= ne, EndLine) @@ -291,25 +236,6 @@ class Database(object): SqlCommand =3D """Update Identifier%s set BelongsToFunction = =3D %s, Model =3D %s where BelongsToFile =3D %s and Model =3D %s and EndLin= e =3D %s""" % \ (BelongsToFile, FunctionID, DataClass.MODEL_IDENT= IFIER_FUNCTION_HEADER, BelongsToFile, DataClass.MODEL_IDENTIFIER_COMMENT, S= tartLine - 1) self.TblIdentifier.Exec(SqlCommand) -# # -# # Check whether an identifier belongs to a function -# # -# print Data1 -# SqlCommand =3D """Update ? set BelongsToFunction =3D ? where Belon= gsToFile =3D ? and StartLine > ? and EndLine < ?""" -# print SqlCommand -# EdkLogger.debug(4, "SqlCommand: %s" %SqlCommand) -# self.Cur.executemany(SqlCommand, Data1) -# -# # -# # Check whether the identifier is a function header -# # -# EdkLogger.debug(4, "For function headers ... ") -# SqlCommand =3D """Update ? set BelongsToFunction =3D ?, Model =3D = ? where BelongsToFile =3D ? and Model =3D ? and EndLine =3D ?""" -# EdkLogger.debug(4, "SqlCommand: %s" %SqlCommand) -# self.Cur.executemany(SqlCommand, Data2) -# -# EdkLogger.verbose("Update 'BelongsToFunction' for Identifiers ... = DONE") - =20 ## # diff --git a/BaseTools/Source/Python/Ecc/c.py b/BaseTools/Source/Python/Ecc= /c.py index 93ee1990ba28..bc72abdce477 100644 --- a/BaseTools/Source/Python/Ecc/c.py +++ b/BaseTools/Source/Python/Ecc/c.py @@ -18,7 +18,6 @@ import string import CodeFragmentCollector import FileProfile from CommonDataClass import DataClass -import Database from Common import EdkLogger from EccToolError import * import EccGlobalData diff --git a/BaseTools/Source/Python/GenFds/CapsuleData.py b/BaseTools/Sour= ce/Python/GenFds/CapsuleData.py index b376d6b2e9be..dd4c27bd15c7 100644 --- a/BaseTools/Source/Python/GenFds/CapsuleData.py +++ b/BaseTools/Source/Python/GenFds/CapsuleData.py @@ -15,7 +15,6 @@ ## # Import Modules # -import Ffs from GenFdsGlobalVariable import GenFdsGlobalVariable import StringIO from struct import pack diff --git a/BaseTools/Source/Python/GenFds/CompressSection.py b/BaseTools/= Source/Python/GenFds/CompressSection.py index 4ae14f27b3e1..cdae74c52fd9 100644 --- a/BaseTools/Source/Python/GenFds/CompressSection.py +++ b/BaseTools/Source/Python/GenFds/CompressSection.py @@ -1,7 +1,7 @@ ## @file # process compress section generation # -# Copyright (c) 2007 - 2017, Intel Corporation. All rights reserved.
+# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# # This program and the accompanying materials # are licensed and made available under the terms and conditions of the B= SD License @@ -15,7 +15,7 @@ ## # Import Modules # -from Ffs import Ffs +from Ffs import SectionSuffix import Section import subprocess import Common.LongFilePathOs as os @@ -85,7 +85,7 @@ class CompressSection (CompressSectionClassObject) : ModuleName + \ SUP_MODULE_SEC + \ SecNum + \ - Ffs.SectionSuffix['COMPRESS'] + SectionSuffix['COMPRESS'] OutputFile =3D os.path.normpath(OutputFile) DummyFile =3D OutputFile + '.dummy' GenFdsGlobalVariable.GenerateSection(DummyFile, SectFiles, InputAl= ign=3DSectAlign, IsMakefile=3DIsMakefile) diff --git a/BaseTools/Source/Python/GenFds/DataSection.py b/BaseTools/Sour= ce/Python/GenFds/DataSection.py index 29caa00c0d8d..f0e5efab4178 100644 --- a/BaseTools/Source/Python/GenFds/DataSection.py +++ b/BaseTools/Source/Python/GenFds/DataSection.py @@ -18,7 +18,7 @@ import Section from GenFdsGlobalVariable import GenFdsGlobalVariable import subprocess -from Ffs import Ffs +from Ffs import SectionSuffix import Common.LongFilePathOs as os from CommonDataClass.FdfClass import DataSectionClassObject from Common.Misc import PeImageClass @@ -120,7 +120,7 @@ class DataSection (DataSectionClassObject): ) self.SectFileName =3D TeFile =20 - OutputFile =3D os.path.join (OutputPath, ModuleName + SUP_MODULE_S= EC + SecNum + Ffs.SectionSuffix.get(self.SecType)) + OutputFile =3D os.path.join (OutputPath, ModuleName + 'SEC' + SecN= um + SectionSuffix.get(self.SecType)) OutputFile =3D os.path.normpath(OutputFile) GenFdsGlobalVariable.GenerateSection(OutputFile, [self.SectFileNam= e], Section.Section.SectionType.get(self.SecType), IsMakefile =3D IsMakefil= e) FileList =3D [OutputFile] diff --git a/BaseTools/Source/Python/GenFds/DepexSection.py b/BaseTools/Sou= rce/Python/GenFds/DepexSection.py index f42162d5a27e..6e63cb97e51d 100644 --- a/BaseTools/Source/Python/GenFds/DepexSection.py +++ b/BaseTools/Source/Python/GenFds/DepexSection.py @@ -18,7 +18,6 @@ import Section from GenFdsGlobalVariable import GenFdsGlobalVariable import subprocess -from Ffs import Ffs import Common.LongFilePathOs as os from CommonDataClass.FdfClass import DepexSectionClassObject from AutoGen.GenDepex import DependencyExpression diff --git a/BaseTools/Source/Python/GenFds/EfiSection.py b/BaseTools/Sourc= e/Python/GenFds/EfiSection.py index 5405d0a8da13..0064196a5a4e 100644 --- a/BaseTools/Source/Python/GenFds/EfiSection.py +++ b/BaseTools/Source/Python/GenFds/EfiSection.py @@ -19,7 +19,7 @@ from struct import * import Section from GenFdsGlobalVariable import GenFdsGlobalVariable import subprocess -from Ffs import Ffs +from Ffs import SectionSuffix import Common.LongFilePathOs as os from CommonDataClass.FdfClass import EfiSectionClassObject from Common import EdkLogger @@ -123,7 +123,7 @@ class EfiSection (EfiSectionClassObject): BuildNumTuple =3D tuple() =20 Num =3D SecNum - OutputFile =3D os.path.join( OutputPath, ModuleName + SUP_= MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join( OutputPath, ModuleName + 'SEC= ' + str(Num) + SectionSuffix.get(SectionType)) GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_= SECTION_VERSION', #Ui=3DStringData, Ver=3DBuildNum, @@ -134,7 +134,7 @@ class EfiSection (EfiSectionClassObject): for File in FileList: Index =3D Index + 1 Num =3D '%s.%d' %(SecNum , Index) - OutputFile =3D os.path.join(OutputPath, ModuleName + S= UP_MODULE_SEC + Num + Ffs.SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join(OutputPath, ModuleName + '= SEC' + Num + SectionSuffix.get(SectionType)) f =3D open(File, 'r') VerString =3D f.read() f.close() @@ -163,7 +163,7 @@ class EfiSection (EfiSectionClassObject): else: EdkLogger.error("GenFds", GENFDS_ERROR, "File: %s = miss Version Section value" %InfFileName) Num =3D SecNum - OutputFile =3D os.path.join( OutputPath, ModuleName + SUP_= MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join( OutputPath, ModuleName + 'SEC= ' + str(Num) + SectionSuffix.get(SectionType)) GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_= SECTION_VERSION', #Ui=3DVerString, Ver=3DBuildNum, @@ -184,7 +184,7 @@ class EfiSection (EfiSectionClassObject): Num =3D SecNum if IsMakefile and StringData =3D=3D ModuleNameStr: StringData =3D "$(MODULE_NAME)" - OutputFile =3D os.path.join( OutputPath, ModuleName + SUP_= MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join( OutputPath, ModuleName + 'SEC= ' + str(Num) + SectionSuffix.get(SectionType)) GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_= SECTION_USER_INTERFACE', Ui=3DStringData, IsMa= kefile=3DIsMakefile) OutputFileList.append(OutputFile) @@ -193,7 +193,7 @@ class EfiSection (EfiSectionClassObject): for File in FileList: Index =3D Index + 1 Num =3D '%s.%d' %(SecNum , Index) - OutputFile =3D os.path.join(OutputPath, ModuleName + S= UP_MODULE_SEC + Num + Ffs.SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join(OutputPath, ModuleName + '= SEC' + Num + SectionSuffix.get(SectionType)) f =3D open(File, 'r') UiString =3D f.read() f.close() @@ -217,7 +217,7 @@ class EfiSection (EfiSectionClassObject): Num =3D SecNum if IsMakefile and StringData =3D=3D ModuleNameStr: StringData =3D "$(MODULE_NAME)" - OutputFile =3D os.path.join( OutputPath, ModuleName + SUP_= MODULE_SEC + str(Num) + Ffs.SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join( OutputPath, ModuleName + 'SEC= ' + str(Num) + SectionSuffix.get(SectionType)) GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_= SECTION_USER_INTERFACE', Ui=3DStringData, IsMa= kefile=3DIsMakefile) OutputFileList.append(OutputFile) @@ -238,7 +238,7 @@ class EfiSection (EfiSectionClassObject): """ Copy Map file to FFS output path """ Index =3D Index + 1 Num =3D '%s.%d' %(SecNum , Index) - OutputFile =3D os.path.join( OutputPath, ModuleName + = SUP_MODULE_SEC + Num + Ffs.SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join( OutputPath, ModuleName + = 'SEC' + Num + SectionSuffix.get(SectionType)) File =3D GenFdsGlobalVariable.MacroExtend(File, Dict) =20 #Get PE Section alignment when align is set to AUTO diff --git a/BaseTools/Source/Python/GenFds/Ffs.py b/BaseTools/Source/Pytho= n/GenFds/Ffs.py index df585f3d819b..12d4dfe1b04c 100644 --- a/BaseTools/Source/Python/GenFds/Ffs.py +++ b/BaseTools/Source/Python/GenFds/Ffs.py @@ -1,7 +1,7 @@ ## @file # process FFS generation # -# Copyright (c) 2007-2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# # This program and the accompanying materials # are licensed and made available under the terms and conditions of the B= SD License @@ -12,56 +12,40 @@ # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IM= PLIED. # =20 -## -# Import Modules -# -from CommonDataClass.FdfClass import FDClassObject from Common.DataType import * +# mapping between FILE type in FDF and file type for GenFfs +FdfFvFileTypeToFileType =3D { + SUP_MODULE_SEC : 'EFI_FV_FILETYPE_SECURITY_CORE', + SUP_MODULE_PEI_CORE : 'EFI_FV_FILETYPE_PEI_CORE', + SUP_MODULE_PEIM : 'EFI_FV_FILETYPE_PEIM', + SUP_MODULE_DXE_CORE : 'EFI_FV_FILETYPE_DXE_CORE', + 'FREEFORM' : 'EFI_FV_FILETYPE_FREEFORM', + 'DRIVER' : 'EFI_FV_FILETYPE_DRIVER', + 'APPLICATION' : 'EFI_FV_FILETYPE_APPLICATION', + 'FV_IMAGE' : 'EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE', + 'RAW' : 'EFI_FV_FILETYPE_RAW', + 'PEI_DXE_COMBO' : 'EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER', + 'SMM' : 'EFI_FV_FILETYPE_SMM', + SUP_MODULE_SMM_CORE : 'EFI_FV_FILETYPE_SMM_CORE', + SUP_MODULE_MM_STANDALONE : 'EFI_FV_FILETYPE_MM_STANDALONE', + SUP_MODULE_MM_CORE_STANDALONE : 'EFI_FV_FILETYPE_MM_CORE_STANDALONE' +} =20 -## generate FFS -# -# -class Ffs(FDClassObject): - # mapping between FILE type in FDF and file type for GenFfs - FdfFvFileTypeToFileType =3D { - SUP_MODULE_SEC : 'EFI_FV_FILETYPE_SECURITY_CORE', - SUP_MODULE_PEI_CORE : 'EFI_FV_FILETYPE_PEI_CORE', - SUP_MODULE_PEIM : 'EFI_FV_FILETYPE_PEIM', - SUP_MODULE_DXE_CORE : 'EFI_FV_FILETYPE_DXE_CORE', - 'FREEFORM' : 'EFI_FV_FILETYPE_FREEFORM', - 'DRIVER' : 'EFI_FV_FILETYPE_DRIVER', - 'APPLICATION' : 'EFI_FV_FILETYPE_APPLICATION', - 'FV_IMAGE' : 'EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE', - 'RAW' : 'EFI_FV_FILETYPE_RAW', - 'PEI_DXE_COMBO' : 'EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER', - 'SMM' : 'EFI_FV_FILETYPE_SMM', - SUP_MODULE_SMM_CORE : 'EFI_FV_FILETYPE_SMM_CORE', - SUP_MODULE_MM_STANDALONE : 'EFI_FV_FILETYPE_MM_STANDALONE', - SUP_MODULE_MM_CORE_STANDALONE : 'EFI_FV_FILETYPE_MM_CORE_STANDALON= E' - } - =20 - # mapping between section type in FDF and file suffix - SectionSuffix =3D { - BINARY_FILE_TYPE_PE32 : '.pe32', - BINARY_FILE_TYPE_PIC : '.pic', - BINARY_FILE_TYPE_TE : '.te', - BINARY_FILE_TYPE_DXE_DEPEX : '.dpx', - 'VERSION' : '.ver', - BINARY_FILE_TYPE_UI : '.ui', - 'COMPAT16' : '.com16', - 'RAW' : '.raw', - 'FREEFORM_SUBTYPE_GUID': '.guid', - 'SUBTYPE_GUID' : '.guid', =20 - 'FV_IMAGE' : 'fv.sec', - 'COMPRESS' : '.com', - 'GUIDED' : '.guided', - BINARY_FILE_TYPE_PEI_DEPEX : '.dpx', - BINARY_FILE_TYPE_SMM_DEPEX : '.dpx' - } - =20 - ## The constructor - # - # @param self The object pointer - # - def __init__(self): - FfsClassObject.__init__(self) +# mapping between section type in FDF and file suffix +SectionSuffix =3D { + BINARY_FILE_TYPE_PE32 : '.pe32', + BINARY_FILE_TYPE_PIC : '.pic', + BINARY_FILE_TYPE_TE : '.te', + BINARY_FILE_TYPE_DXE_DEPEX : '.dpx', + 'VERSION' : '.ver', + BINARY_FILE_TYPE_UI : '.ui', + 'COMPAT16' : '.com16', + 'RAW' : '.raw', + 'FREEFORM_SUBTYPE_GUID': '.guid', + 'SUBTYPE_GUID' : '.guid', =20 + 'FV_IMAGE' : 'fv.sec', + 'COMPRESS' : '.com', + 'GUIDED' : '.guided', + BINARY_FILE_TYPE_PEI_DEPEX : '.dpx', + BINARY_FILE_TYPE_SMM_DEPEX : '.dpx' +} diff --git a/BaseTools/Source/Python/GenFds/FfsFileStatement.py b/BaseTools= /Source/Python/GenFds/FfsFileStatement.py index ba8e0465ef34..871499d3d2ad 100644 --- a/BaseTools/Source/Python/GenFds/FfsFileStatement.py +++ b/BaseTools/Source/Python/GenFds/FfsFileStatement.py @@ -15,7 +15,7 @@ ## # Import Modules # -import Ffs +from Ffs import FdfFvFileTypeToFileType import Rule import Common.LongFilePathOs as os import StringIO @@ -167,7 +167,7 @@ class FileStatement (FileStatementClassObject) : # FfsFileOutput =3D os.path.join(OutputDir, self.NameGuid + '.ffs') GenFdsGlobalVariable.GenerateFfs(FfsFileOutput, SectionFiles, - Ffs.Ffs.FdfFvFileTypeToFileType.g= et(self.FvFileType), + FdfFvFileTypeToFileType.get(self.= FvFileType), self.NameGuid, Fixed=3Dself.Fixed, CheckSum=3Dself.CheckSum, diff --git a/BaseTools/Source/Python/GenFds/FfsInfStatement.py b/BaseTools/= Source/Python/GenFds/FfsInfStatement.py index c332eee6079d..f76563d736f6 100644 --- a/BaseTools/Source/Python/GenFds/FfsInfStatement.py +++ b/BaseTools/Source/Python/GenFds/FfsInfStatement.py @@ -21,7 +21,7 @@ import Common.LongFilePathOs as os import StringIO from struct import * from GenFdsGlobalVariable import GenFdsGlobalVariable -import Ffs +from Ffs import FdfFvFileTypeToFileType,SectionSuffix import subprocess import sys import Section @@ -761,7 +761,7 @@ class FfsInfStatement(FfsInfStatementClassObject): =20 SecNum =3D '%d' %Index GenSecOutputFile=3D self.__ExtendMacro__(Rule.NameGuid) + \ - Ffs.Ffs.SectionSuffix[SectionType] + SUP_MOD= ULE_SEC + SecNum + SectionSuffix[SectionType] + 'SEC' + SecNum Index =3D Index + 1 OutputFile =3D os.path.join(self.OutputPath, GenSecOutputF= ile) File =3D GenFdsGlobalVariable.MacroExtend(File, Dict, self= .CurrentArch) @@ -804,7 +804,7 @@ class FfsInfStatement(FfsInfStatementClassObject): else: SecNum =3D '%d' %Index GenSecOutputFile=3D self.__ExtendMacro__(Rule.NameGuid) + \ - Ffs.Ffs.SectionSuffix[SectionType] + SUP_MOD= ULE_SEC + SecNum + SectionSuffix[SectionType] + 'SEC' + SecNum OutputFile =3D os.path.join(self.OutputPath, GenSecOutputFile) GenSecInputFile =3D GenFdsGlobalVariable.MacroExtend(GenSecInp= utFile, Dict, self.CurrentArch) =20 @@ -883,7 +883,7 @@ class FfsInfStatement(FfsInfStatementClassObject): self.ModuleGuid =3D RegistryGuidStr =20 GenFdsGlobalVariable.GenerateFfs(FfsOutput, InputSection, - Ffs.Ffs.FdfFvFileTypeToFileTy= pe[Rule.FvFileType], + FdfFvFileTypeToFileType[Rule.= FvFileType], self.ModuleGuid, Fixed=3DRule= .Fixed, CheckSum=3DRule.CheckSum, Ali= gn=3DRule.Alignment, SectionAlign=3DSectionAlignme= nts, @@ -1056,7 +1056,7 @@ class FfsInfStatement(FfsInfStatementClassObject): =20 FfsOutput =3D os.path.join( self.OutputPath, self.ModuleGuid + '.f= fs') GenFdsGlobalVariable.GenerateFfs(FfsOutput, InputFile, - Ffs.Ffs.FdfFvFileTypeToFileTy= pe[Rule.FvFileType], + FdfFvFileTypeToFileType[Rule.= FvFileType], self.ModuleGuid, Fixed=3DRule= .Fixed, CheckSum=3DRule.CheckSum, Ali= gn=3DRule.Alignment, SectionAlign=3DAlignments, diff --git a/BaseTools/Source/Python/GenFds/Fv.py b/BaseTools/Source/Python= /GenFds/Fv.py index 6714838f6fc9..29daba5a3a3e 100644 --- a/BaseTools/Source/Python/GenFds/Fv.py +++ b/BaseTools/Source/Python/GenFds/Fv.py @@ -20,7 +20,6 @@ import subprocess import StringIO from struct import * =20 -import Ffs import AprioriSection import FfsFileStatement from GenFdsGlobalVariable import GenFdsGlobalVariable diff --git a/BaseTools/Source/Python/GenFds/FvImageSection.py b/BaseTools/S= ource/Python/GenFds/FvImageSection.py index 57ecea0377bf..380fbe56f1c4 100644 --- a/BaseTools/Source/Python/GenFds/FvImageSection.py +++ b/BaseTools/Source/Python/GenFds/FvImageSection.py @@ -17,7 +17,7 @@ # import Section import StringIO -from Ffs import Ffs +from Ffs import SectionSuffix import subprocess from GenFdsGlobalVariable import GenFdsGlobalVariable import Common.LongFilePathOs as os @@ -75,7 +75,7 @@ class FvImageSection(FvImageSectionClassObject): if FvAlignmentValue > MaxFvAlignment: MaxFvAlignment =3D FvAlignmentValue =20 - OutputFile =3D os.path.join(OutputPath, ModuleName + SUP_M= ODULE_SEC + Num + Ffs.SectionSuffix.get("FV_IMAGE")) + OutputFile =3D os.path.join(OutputPath, ModuleName + 'SEC'= + Num + SectionSuffix["FV_IMAGE"]) GenFdsGlobalVariable.GenerateSection(OutputFile, [FvFileNa= me], 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE', IsMakefile=3DIsMakefile) OutputFileList.append(OutputFile) =20 @@ -139,7 +139,7 @@ class FvImageSection(FvImageSectionClassObject): # # Prepare the parameter of GenSection # - OutputFile =3D os.path.join(OutputPath, ModuleName + SUP_MODUL= E_SEC + SecNum + Ffs.SectionSuffix.get("FV_IMAGE")) + OutputFile =3D os.path.join(OutputPath, ModuleName + 'SEC' + S= ecNum + SectionSuffix["FV_IMAGE"]) GenFdsGlobalVariable.GenerateSection(OutputFile, [FvFileName],= 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE', IsMakefile=3DIsMakefile) OutputFileList.append(OutputFile) =20 diff --git a/BaseTools/Source/Python/GenFds/GuidSection.py b/BaseTools/Sour= ce/Python/GenFds/GuidSection.py index bda185476b95..104650d16781 100644 --- a/BaseTools/Source/Python/GenFds/GuidSection.py +++ b/BaseTools/Source/Python/GenFds/GuidSection.py @@ -18,7 +18,7 @@ # import Section import subprocess -from Ffs import Ffs +from Ffs import SectionSuffix import Common.LongFilePathOs as os from GenFdsGlobalVariable import GenFdsGlobalVariable from CommonDataClass.FdfClass import GuidSectionClassObject @@ -125,7 +125,7 @@ class GuidSection(GuidSectionClassObject) : ModuleName + \ SUP_MODULE_SEC + \ SecNum + \ - Ffs.SectionSuffix['GUIDED'] + SectionSuffix['GUIDED'] OutputFile =3D os.path.normpath(OutputFile) =20 ExternalTool =3D None diff --git a/BaseTools/Source/Python/GenFds/OptRomInfStatement.py b/BaseToo= ls/Source/Python/GenFds/OptRomInfStatement.py index a865ac4436d5..6179bfa181cb 100644 --- a/BaseTools/Source/Python/GenFds/OptRomInfStatement.py +++ b/BaseTools/Source/Python/GenFds/OptRomInfStatement.py @@ -1,7 +1,7 @@ ## @file # process OptionROM generation from INF statement # -# Copyright (c) 2007 - 2017, Intel Corporation. All rights reserved.
+# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# # This program and the accompanying materials # are licensed and made available under the terms and conditions of the B= SD License @@ -69,11 +69,6 @@ class OptRomInfStatement (FfsInfStatement): if self.OverrideAttribs.PciRevision is None: self.OverrideAttribs.PciRevision =3D self.OptRomDefs.get ('PCI= _REVISION') =20 -# InfObj =3D GenFdsGlobalVariable.WorkSpace.BuildObject[self.PathCl= assObj, self.CurrentArch] =20 -# RecordList =3D InfObj._RawData[MODEL_META_DATA_HEADER, InfObj._Ar= ch, InfObj._Platform] -# for Record in RecordList: -# Record =3D ReplaceMacros(Record, GlobalData.gEdkGlobal, False) -# Name =3D Record[0] =20 ## GenFfs() method # # Generate FFS diff --git a/BaseTools/Source/Python/GenFds/UiSection.py b/BaseTools/Source= /Python/GenFds/UiSection.py index 280500952b63..fe1e026f5edf 100644 --- a/BaseTools/Source/Python/GenFds/UiSection.py +++ b/BaseTools/Source/Python/GenFds/UiSection.py @@ -1,7 +1,7 @@ ## @file # process UI section generation # -# Copyright (c) 2007 - 2017, Intel Corporation. All rights reserved.
+# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# # This program and the accompanying materials # are licensed and made available under the terms and conditions of the B= SD License @@ -16,7 +16,7 @@ # Import Modules # import Section -from Ffs import Ffs +from Ffs import SectionSuffix import subprocess import Common.LongFilePathOs as os from GenFdsGlobalVariable import GenFdsGlobalVariable @@ -58,7 +58,7 @@ class UiSection (UiSectionClassObject): self.StringData =3D FfsInf.__ExtendMacro__(self.StringData) self.FileName =3D FfsInf.__ExtendMacro__(self.FileName) =20 - OutputFile =3D os.path.join(OutputPath, ModuleName + SUP_MODULE_SE= C + SecNum + Ffs.SectionSuffix.get(BINARY_FILE_TYPE_UI)) + OutputFile =3D os.path.join(OutputPath, ModuleName + 'SEC' + SecNu= m + SectionSuffix['UI']) =20 if self.StringData is not None : NameString =3D self.StringData diff --git a/BaseTools/Source/Python/GenFds/VerSection.py b/BaseTools/Sourc= e/Python/GenFds/VerSection.py index 456a430079bb..1bcdc8110d30 100644 --- a/BaseTools/Source/Python/GenFds/VerSection.py +++ b/BaseTools/Source/Python/GenFds/VerSection.py @@ -1,7 +1,7 @@ ## @file # process Version section generation # -# Copyright (c) 2007 - 2017, Intel Corporation. All rights reserved.
+# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# # This program and the accompanying materials # are licensed and made available under the terms and conditions of the B= SD License @@ -15,7 +15,7 @@ ## # Import Modules # -from Ffs import Ffs +from Ffs import SectionSuffix import Section import Common.LongFilePathOs as os import subprocess @@ -60,7 +60,7 @@ class VerSection (VerSectionClassObject): self.FileName =3D FfsInf.__ExtendMacro__(self.FileName) =20 OutputFile =3D os.path.join(OutputPath, - ModuleName + SUP_MODULE_SEC + SecNum + F= fs.SectionSuffix.get('VERSION')) + ModuleName + 'SEC' + SecNum + SectionSuf= fix['VERSION']) OutputFile =3D os.path.normpath(OutputFile) =20 # Get String Data diff --git a/BaseTools/Source/Python/Workspace/WorkspaceDatabase.py b/BaseT= ools/Source/Python/Workspace/WorkspaceDatabase.py index 14dcb1ae8136..7c0949da079d 100644 --- a/BaseTools/Source/Python/Workspace/WorkspaceDatabase.py +++ b/BaseTools/Source/Python/Workspace/WorkspaceDatabase.py @@ -133,15 +133,6 @@ class WorkspaceDatabase(object): self._CACHE_[Key] =3D BuildObject return BuildObject =20 - # placeholder for file format conversion - class TransformObjectFactory: - def __init__(self, WorkspaceDb): - self.WorkspaceDb =3D WorkspaceDb - - # key =3D FilePath, Arch - def __getitem__(self, Key): - pass - ## Constructor of WorkspaceDatabase # # @param DbPath Path of database file @@ -182,7 +173,6 @@ class WorkspaceDatabase(object): =20 # conversion object for build or file format conversion purpose self.BuildObject =3D WorkspaceDatabase.BuildObjectFactory(self) - self.TransformObject =3D WorkspaceDatabase.TransformObjectFactory(= self) =20 ## Check whether workspace database need to be renew. # The renew reason maybe: @@ -198,10 +188,12 @@ class WorkspaceDatabase(object): # def _CheckWhetherDbNeedRenew (self, force, DbPath): # if database does not exist, we need do nothing - if not os.path.exists(DbPath): return False + if not os.path.exists(DbPath): + return False =20 # if user force to renew database, then not check whether database= is out of date - if force: return True + if force: + return True =20 # =20 # Check the time of last modified source file or build.exe @@ -223,7 +215,7 @@ determine whether database file is out of date!\n") for root, dirs, files in os.walk (rootPath): for dir in dirs: # bypass source control folder=20 - if dir.lower() in [".svn", "_svn", "cvs"]: + if dir.lower() in {".svn", "_svn", "cvs", ".git"}: dirs.remove(dir) =20 for file in files: diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Pyth= on/build/build.py index 1ef2dc5bfe70..99e4881b3ea4 100644 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -1261,7 +1261,7 @@ class Build(): (AutoGenObject.BuildTarget, AutoGenObject.= ToolChain, AutoGenObject.Arch), ExtraData=3Dstr(AutoGenObject)) =20 - makefile =3D GenMake.BuildFile(AutoGenObject)._FILE_NAME_[GenMake.= gMakeType] + makefile =3D GenMake.BuildFile._FILE_NAME_[GenMake.gMakeType] =20 # run if Target =3D=3D 'run': --=20 2.16.2.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Fri May 3 05:47:03 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 152632137742163.6005145667076; Mon, 14 May 2018 11:09:37 -0700 (PDT) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id B892121DF8098; Mon, 14 May 2018 11:09:26 -0700 (PDT) Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 2E1C320969676 for ; Mon, 14 May 2018 11:09:25 -0700 (PDT) Received: from orsmga001.jf.intel.com ([10.7.209.18]) by orsmga105.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 14 May 2018 11:09:23 -0700 Received: from jcarsey-desk1.amr.corp.intel.com ([10.7.159.144]) by orsmga001.jf.intel.com with ESMTP; 14 May 2018 11:09:23 -0700 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.100; helo=mga07.intel.com; envelope-from=jaben.carsey@intel.com; receiver=edk2-devel@lists.01.org X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.49,401,1520924400"; d="scan'208";a="55814264" From: Jaben Carsey To: edk2-devel@lists.01.org Date: Mon, 14 May 2018 11:09:13 -0700 Message-Id: X-Mailer: git-send-email 2.16.2.windows.1 In-Reply-To: References: In-Reply-To: References: Subject: [edk2] [PATCH v1 04/11] BaseTools: remove repeated calls to startswith/endswith X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.26 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Liming Gao MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" As both can take a tuple, use that instead of calling repeatedly. Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jaben Carsey --- BaseTools/Source/Python/AutoGen/GenMake.py | 2 +- BaseTools/Source/Python/AutoGen/StrGather.py | 2 +- BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py | 2 +- BaseTools/Source/Python/BPDG/GenVpd.py | 2 +- BaseTools/Source/Python/Common/Expression.py | 13 +++++= +------- BaseTools/Source/Python/Common/Misc.py | 6 +++--- BaseTools/Source/Python/Ecc/Check.py | 6 +++--- BaseTools/Source/Python/Ecc/CodeFragmentCollector.py | 4 ++-- BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py | 2 +- BaseTools/Source/Python/Ecc/c.py | 14 +++++= ++------- BaseTools/Source/Python/Eot/CodeFragmentCollector.py | 9 +++--= ---- BaseTools/Source/Python/GenFds/FdfParser.py | 10 ++++-= ----- BaseTools/Source/Python/Trim/Trim.py | 2 +- BaseTools/Source/Python/Workspace/BuildClassObject.py | 2 +- BaseTools/Source/Python/Workspace/DscBuildData.py | 2 +- BaseTools/Source/Python/Workspace/InfBuildData.py | 2 +- BaseTools/Source/Python/build/BuildReport.py | 2 +- 17 files changed, 38 insertions(+), 44 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/GenMake.py b/BaseTools/Source/= Python/AutoGen/GenMake.py index 1c8ab7fe1ec8..d70c5c26ffc8 100644 --- a/BaseTools/Source/Python/AutoGen/GenMake.py +++ b/BaseTools/Source/Python/AutoGen/GenMake.py @@ -741,7 +741,7 @@ cleanlib: index =3D index + 1 if CmdName =3D=3D 'Trim': SecDepsFileList.append(os.path.join('$(DEBUG_D= IR)', os.path.basename(OutputFile).replace('offset', 'efi'))) - if OutputFile.endswith('.ui') or OutputFile.endswi= th('.ver'): + if OutputFile.endswith(('.ui','.ver')): SecDepsFileList.append(os.path.join('$(MODULE_= DIR)','$(MODULE_FILE)')) self.FfsOutputFileList.append((OutputFile, ' '.joi= n(SecDepsFileList), SecCmdStr)) if len(SecDepsFileList) > 0: diff --git a/BaseTools/Source/Python/AutoGen/StrGather.py b/BaseTools/Sourc= e/Python/AutoGen/StrGather.py index 73af1214eb0a..e5e4f25efd5d 100644 --- a/BaseTools/Source/Python/AutoGen/StrGather.py +++ b/BaseTools/Source/Python/AutoGen/StrGather.py @@ -290,7 +290,7 @@ def GetFilteredLanguage(UniLanguageList, LanguageFilter= List): if DefaultTag not in UniLanguageListFiltered: # check whether language code with primary code equiva= lent with DefaultTag already in the list, if so, use that for UniLanguage in UniLanguageList: - if UniLanguage.startswith('en-') or UniLanguage.st= artswith('eng-'): + if UniLanguage.startswith(('eng-','en-')): if UniLanguage not in UniLanguageListFiltered: UniLanguageListFiltered +=3D [UniLanguage] break diff --git a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py b/B= aseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py index e2b4795129ef..3b54865000bf 100644 --- a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py +++ b/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py @@ -254,7 +254,7 @@ class VAR_CHECK_PCD_VALID_LIST(VAR_CHECK_PCD_VALID_OBJ): for valid_num in valid_num_list: valid_num =3D valid_num.strip() =20 - if valid_num.startswith('0x') or valid_num.startswith('0X'): + if valid_num.startswith(('0x','0X')): self.data.add(int(valid_num, 16)) else: self.data.add(int(valid_num)) diff --git a/BaseTools/Source/Python/BPDG/GenVpd.py b/BaseTools/Source/Pyth= on/BPDG/GenVpd.py index 69a9665f5a76..4fa12b7d59de 100644 --- a/BaseTools/Source/Python/BPDG/GenVpd.py +++ b/BaseTools/Source/Python/BPDG/GenVpd.py @@ -172,7 +172,7 @@ class PcdEntry: # @param ValueString The Integer type string for pack. # =20 def _PackPtrValue(self, ValueString, Size): - if ValueString.startswith('L"') or ValueString.startswith("L'"): + if ValueString.startswith(("L'",'L"')): self._PackUnicode(ValueString, Size) elif ValueString.startswith('{') and ValueString.endswith('}'): self._PackByteArray(ValueString, Size) diff --git a/BaseTools/Source/Python/Common/Expression.py b/BaseTools/Sourc= e/Python/Common/Expression.py index 9fa07c6add16..e5d17e6b4de0 100644 --- a/BaseTools/Source/Python/Common/Expression.py +++ b/BaseTools/Source/Python/Common/Expression.py @@ -130,7 +130,7 @@ def IsValidCName(Str): def BuildOptionValue(PcdValue, GuidDict): if PcdValue.startswith('H'): InputValue =3D PcdValue[1:] - elif PcdValue.startswith("L'") or PcdValue.startswith("'"): + elif PcdValue.startswith(("L'", "'")): InputValue =3D PcdValue elif PcdValue.startswith('L'): InputValue =3D 'L"' + PcdValue[1:] + '"' @@ -390,7 +390,7 @@ class ValueExpression(BaseExpression): elif not Val: Val =3D False RealVal =3D '""' - elif not Val.startswith('L"') and not Val.startswith('{') and = not Val.startswith("L'"): + elif not Val.startswith(('L"',"L'",'{')): Val =3D True RealVal =3D '"' + RealVal + '"' =20 @@ -532,7 +532,7 @@ class ValueExpression(BaseExpression): Radix =3D 10 if self._Token.lower()[0:2] =3D=3D '0x' and len(self._Token) > 2: Radix =3D 16 - if self._Token.startswith('"') or self._Token.startswith('L"'): + if self._Token.startswith(('"','L"')): Flag =3D 0 for Index in range(len(self._Token)): if self._Token[Index] in {'"'}: @@ -541,7 +541,7 @@ class ValueExpression(BaseExpression): Flag +=3D 1 if Flag =3D=3D 2 and self._Token.endswith('"'): return True - if self._Token.startswith("'") or self._Token.startswith("L'"): + if self._Token.startswith(("'","L'")): Flag =3D 0 for Index in range(len(self._Token)): if self._Token[Index] in {"'"}: @@ -810,15 +810,14 @@ class ValueExpressionEx(ValueExpression): PcdValue =3D self.PcdValue try: PcdValue =3D ValueExpression.__call__(self, RealValue, Depth) - if self.PcdType =3D=3D TAB_VOID and (PcdValue.startswith("'") = or PcdValue.startswith("L'")): + if self.PcdType =3D=3D TAB_VOID and PcdValue.startswith(("'","= L'")): PcdValue, Size =3D ParseFieldValue(PcdValue) PcdValueList =3D [] for I in range(Size): PcdValueList.append('0x%02X'%(PcdValue & 0xff)) PcdValue =3D PcdValue >> 8 PcdValue =3D '{' + ','.join(PcdValueList) + '}' - elif self.PcdType in TAB_PCD_NUMERIC_TYPES and (PcdValue.start= swith("'") or \ - PcdValue.startswith('"') or PcdValue.startswith("L'"= ) or PcdValue.startswith('L"') or PcdValue.startswith('{')): + elif self.PcdType in TAB_PCD_NUMERIC_TYPES and PcdValue.starts= with(("'",'"',"L'",'L"','{')): raise BadExpression except WrnExpression, Value: PcdValue =3D Value.result diff --git a/BaseTools/Source/Python/Common/Misc.py b/BaseTools/Source/Pyth= on/Common/Misc.py index 90350f863826..17907a318944 100644 --- a/BaseTools/Source/Python/Common/Misc.py +++ b/BaseTools/Source/Python/Common/Misc.py @@ -1568,8 +1568,8 @@ def AnalyzePcdData(Setting): def CheckPcdDatum(Type, Value): if Type =3D=3D TAB_VOID: ValueRe =3D re.compile(r'\s*L?\".*\"\s*$') - if not (((Value.startswith('L"') or Value.startswith('"')) and Val= ue.endswith('"')) - or (Value.startswith('{') and Value.endswith('}')) or (Val= ue.startswith("L'") or Value.startswith("'") and Value.endswith("'")) + if not ((Value.startswith(('L"','"')) and Value.endswith('"')) + or (Value.startswith('{') and Value.endswith('}')) or (Val= ue.startswith(("L'","'")) and Value.endswith("'")) ): return False, "Invalid value [%s] of type [%s]; must be in the= form of {...} for array"\ ", \"...\" or \'...\' for string, L\"...\" or L\= '...\' for unicode string" % (Value, Type) @@ -2106,7 +2106,7 @@ def GetIntegerValue(Input): if String.endswith("LL"): String =3D String[:-2] =20 - if String.startswith("0x") or String.startswith("0X"): + if String.startswith(("0x","0X")): return int(String, 16) elif String =3D=3D '': return 0 diff --git a/BaseTools/Source/Python/Ecc/Check.py b/BaseTools/Source/Python= /Ecc/Check.py index dde7d7841082..e7bd97297538 100644 --- a/BaseTools/Source/Python/Ecc/Check.py +++ b/BaseTools/Source/Python/Ecc/Check.py @@ -777,7 +777,7 @@ class Check(object): SqlCommand =3D """select ID, Value1, Value2 from Dsc where Mod= el =3D %s""" % MODEL_EFI_LIBRARY_CLASS LibraryClasses =3D EccGlobalData.gDb.TblDsc.Exec(SqlCommand) for LibraryClass in LibraryClasses: - if LibraryClass[1].upper() =3D=3D 'NULL' or LibraryClass[1= ].startswith('!ifdef') or LibraryClass[1].startswith('!ifndef') or LibraryC= lass[1].endswith('!endif'): + if LibraryClass[1].upper() =3D=3D 'NULL' or LibraryClass[1= ].startswith(('!ifdef','!ifndef')) or LibraryClass[1].endswith('!endif'): continue else: LibraryIns =3D os.path.normpath(mws.join(EccGlobalData= .gWorkspace, LibraryClass[2])) @@ -1029,9 +1029,9 @@ class Check(object): if not EccGlobalData.gException.IsException(ERROR_= META_DATA_FILE_CHECK_PCD_TYPE, FunName): if Model in [MODEL_PCD_FIXED_AT_BUILD] and not= FunName.startswith('FixedPcdGet'): EccGlobalData.gDb.TblReport.Insert(ERROR_M= ETA_DATA_FILE_CHECK_PCD_TYPE, OtherMsg=3D"The pcd '%s' is defined as a FixP= cd but now it is called by c function [%s]" % (PcdName, FunName), BelongsTo= Table=3DTblName, BelongsToItem=3DRecord[1]) - if Model in [MODEL_PCD_FEATURE_FLAG] and (not = FunName.startswith('FeaturePcdGet') and not FunName.startswith('FeaturePcdS= et')): + if Model in [MODEL_PCD_FEATURE_FLAG] and not F= unName.startswith(('FeaturePcdGet','FeaturePcdSet')): EccGlobalData.gDb.TblReport.Insert(ERROR_M= ETA_DATA_FILE_CHECK_PCD_TYPE, OtherMsg=3D"The pcd '%s' is defined as a Feat= urePcd but now it is called by c function [%s]" % (PcdName, FunName), Belon= gsToTable=3DTblName, BelongsToItem=3DRecord[1]) - if Model in [MODEL_PCD_PATCHABLE_IN_MODULE] an= d (not FunName.startswith('PatchablePcdGet') and not FunName.startswith('Pa= tchablePcdSet')): + if Model in [MODEL_PCD_PATCHABLE_IN_MODULE] an= d not FunName.startswith(('PatchablePcdGet','PatchablePcdSet')): EccGlobalData.gDb.TblReport.Insert(ERROR_M= ETA_DATA_FILE_CHECK_PCD_TYPE, OtherMsg=3D"The pcd '%s' is defined as a Patc= hablePcd but now it is called by c function [%s]" % (PcdName, FunName), Bel= ongsToTable=3DTblName, BelongsToItem=3DRecord[1]) =20 #ERROR_META_DATA_FILE_CHECK_PCD_TYPE diff --git a/BaseTools/Source/Python/Ecc/CodeFragmentCollector.py b/BaseToo= ls/Source/Python/Ecc/CodeFragmentCollector.py index ffa51de7c1bf..a2d2817b73f4 100644 --- a/BaseTools/Source/Python/Ecc/CodeFragmentCollector.py +++ b/BaseTools/Source/Python/Ecc/CodeFragmentCollector.py @@ -221,7 +221,7 @@ class CodeFragmentCollector: =20 if self.Profile.FileLinesList[Line - 1][0] !=3D T_CHAR_HASH: BeforeHashPart =3D str(self.Profile.FileLinesList[Line - 1]).s= plit(T_CHAR_HASH)[0] - if BeforeHashPart.rstrip().endswith(T_CHAR_COMMA) or BeforeHas= hPart.rstrip().endswith(';'): + if BeforeHashPart.rstrip().endswith((T_CHAR_COMMA,';')): return =20 if Line - 2 >=3D 0 and str(self.Profile.FileLinesList[Line - 2]).r= strip().endswith(','): @@ -230,7 +230,7 @@ class CodeFragmentCollector: if Line - 2 >=3D 0 and str(self.Profile.FileLinesList[Line - 2]).r= strip().endswith(';'): return =20 - if str(self.Profile.FileLinesList[Line]).lstrip().startswith(',') = or str(self.Profile.FileLinesList[Line]).lstrip().startswith(';'): + if str(self.Profile.FileLinesList[Line]).lstrip().startswith((',',= ';')): return =20 self.Profile.FileLinesList[Line - 1].insert(self.CurrentOffsetWith= inLine, ',') diff --git a/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.p= y b/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py index e5c43b629151..0f9711ba109e 100644 --- a/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py @@ -1712,7 +1712,7 @@ class DecParser(MetaFileParser): if len(GuidValueList) =3D=3D 11: for GuidValue in GuidValueList: GuidValue =3D GuidValue.strip() - if GuidValue.startswith('0x') or GuidValue.startswith('0X'= ): + if GuidValue.startswith(('0x','0X')): HexList.append('0x' + str(GuidValue[2:])) Index +=3D 1 continue diff --git a/BaseTools/Source/Python/Ecc/c.py b/BaseTools/Source/Python/Ecc= /c.py index bc72abdce477..4c49d1ca570f 100644 --- a/BaseTools/Source/Python/Ecc/c.py +++ b/BaseTools/Source/Python/Ecc/c.py @@ -1372,7 +1372,7 @@ def CheckFuncLayoutName(FullFileName): PrintErrorMsg(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME,= 'Parameter [%s] NOT follow naming convention.' % Param.Name, FileTable, Re= sult[1]) StartLine =3D Param.StartLine =20 - if not Result[0].endswith('\n )') and not Result[0].endswith('\r = )'): + if not Result[0].endswith(('\n )','\r )')): PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, '\'= )\' should be on a new line and indented two spaces', FileTable, Result[1]) =20 SqlStatement =3D """ select Modifier, ID, FunNameStartColumn, Name @@ -1398,7 +1398,7 @@ def CheckFuncLayoutName(FullFileName): if not Pattern.match(Param.Name) and not Param.Name in ParamIg= noreList and not EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTI= ON_CHECK_VARIABLE_NAME, Param.Name): PrintErrorMsg(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME,= 'Parameter [%s] NOT follow naming convention.' % Param.Name, FileTable, Re= sult[1]) StartLine =3D Param.StartLine - if not Result[0].endswith('\n )') and not Result[0].endswith('\r = )'): + if not Result[0].endswith(('\n )','\r )')): PrintErrorMsg(ERROR_C_FUNCTION_LAYOUT_CHECK_FUNCTION_NAME, '\'= )\' should be on a new line and indented two spaces', 'Function', Result[1]) =20 def CheckFuncLayoutPrototype(FullFileName): @@ -2193,7 +2193,7 @@ def CheckHeaderFileIfndef(FullFileName): """ % (FileTable, Result[1]) ResultSet =3D Db.TblFile.Exec(SqlStatement) for Result in ResultSet: - if not Result[0].startswith('/*') and not Result[0].startswith= ('//'): + if not Result[0].startswith(('/*','//')): PrintErrorMsg(ERROR_INCLUDE_FILE_CHECK_IFNDEF_STATEMENT_2,= '', 'File', FileID) break =20 @@ -2203,7 +2203,7 @@ def CheckHeaderFileIfndef(FullFileName): """ % (FileTable, FileTable, DataClass.MODEL_IDENTIFIER= _MACRO_ENDIF) ResultSet =3D Db.TblFile.Exec(SqlStatement) for Result in ResultSet: - if not Result[0].startswith('/*') and not Result[0].startswith('//= '): + if not Result[0].startswith(('/*','//')): PrintErrorMsg(ERROR_INCLUDE_FILE_CHECK_IFNDEF_STATEMENT_3, '',= 'File', FileID) return ErrorMsgList =20 @@ -2374,7 +2374,7 @@ def CheckFileHeaderDoxygenComments(FullFileName): break # Check whether C File header Comment content start with two s= paces. if EccGlobalData.gConfig.HeaderCheckCFileCommentStartSpacesNum= =3D=3D '1' or EccGlobalData.gConfig.HeaderCheckAll =3D=3D '1' or EccGlobal= Data.gConfig.CheckAll =3D=3D '1': - if CommentLine.startswith('/** @file') =3D=3D False and Co= mmentLine.startswith('**/') =3D=3D False and CommentLine.strip() and Commen= tLine.startswith(' ') =3D=3D False: + if not CommentLine.startswith(('/** @file','**/',' ')) an= d CommentLine.strip(): PrintErrorMsg(ERROR_HEADER_CHECK_FILE, 'File header co= mment content should start with two spaces at each line', FileTable, ID) =20 CommentLine =3D CommentLine.strip() @@ -2401,7 +2401,7 @@ def CheckFileHeaderDoxygenComments(FullFileName): # Check whether C File header Comment's each reference= at list should begin with a bullet character. if EccGlobalData.gConfig.HeaderCheckCFileCommentRefere= nceFormat =3D=3D '1' or EccGlobalData.gConfig.HeaderCheckAll =3D=3D '1' or = EccGlobalData.gConfig.CheckAll =3D=3D '1': if RefListFlag =3D=3D True: - if RefLine.strip() and RefLine.strip().startsw= ith('**/') =3D=3D False and RefLine.startswith(' -') =3D=3D False: = =20 + if RefLine.strip() and not RefLine.strip().sta= rtswith(('**/',' -')): =20 PrintErrorMsg(ERROR_HEADER_CHECK_FILE, 'Ea= ch reference on a separate line should begin with a bullet character ""-"" = ', FileTable, ID) =20 =20 if NoHeaderCommentStartFlag: @@ -2614,7 +2614,7 @@ def CheckFunctionHeaderConsistentWithDoxygenComment(F= uncModifier, FuncHeader, Fu ErrorMsgList.append('Line %d : VOID return type need NO do= xygen tags in comment' % CommentStartLine) PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'VOID r= eturn type need no doxygen tags in comment ', TableName, CommentId) else: - if Index < DoxygenTagNumber and not DoxygenStrList[Index].star= tswith('@retval') and not DoxygenStrList[Index].startswith('@return'): + if Index < DoxygenTagNumber and not DoxygenStrList[Index].star= tswith(('@retval','@return')): ErrorMsgList.append('Line %d : Number of @param doxygen ta= gs in comment does NOT match number of function parameters' % CommentStartL= ine) PrintErrorMsg(ERROR_DOXYGEN_CHECK_FUNCTION_HEADER, 'Number= of @param doxygen tags in comment does NOT match number of function parame= ters ', TableName, CommentId) else: diff --git a/BaseTools/Source/Python/Eot/CodeFragmentCollector.py b/BaseToo= ls/Source/Python/Eot/CodeFragmentCollector.py index 87f179206d84..b962ad019161 100644 --- a/BaseTools/Source/Python/Eot/CodeFragmentCollector.py +++ b/BaseTools/Source/Python/Eot/CodeFragmentCollector.py @@ -215,16 +215,13 @@ class CodeFragmentCollector: =20 if self.Profile.FileLinesList[Line - 1][0] !=3D T_CHAR_HASH: BeforeHashPart =3D str(self.Profile.FileLinesList[Line - 1]).s= plit(T_CHAR_HASH)[0] - if BeforeHashPart.rstrip().endswith(T_CHAR_COMMA) or BeforeHas= hPart.rstrip().endswith(';'): + if BeforeHashPart.rstrip().endswith((T_CHAR_COMMA,';')): return =20 - if Line - 2 >=3D 0 and str(self.Profile.FileLinesList[Line - 2]).r= strip().endswith(','): + if Line - 2 >=3D 0 and str(self.Profile.FileLinesList[Line - 2]).r= strip().endswith((',',';')): return =20 - if Line - 2 >=3D 0 and str(self.Profile.FileLinesList[Line - 2]).r= strip().endswith(';'): - return - - if str(self.Profile.FileLinesList[Line]).lstrip().startswith(',') = or str(self.Profile.FileLinesList[Line]).lstrip().startswith(';'): + if str(self.Profile.FileLinesList[Line]).lstrip().startswith((',',= ';')): return =20 self.Profile.FileLinesList[Line - 1].insert(self.CurrentOffsetWith= inLine, ',') diff --git a/BaseTools/Source/Python/GenFds/FdfParser.py b/BaseTools/Source= /Python/GenFds/FdfParser.py index 8a9296c49d1d..2439d8ab9455 100644 --- a/BaseTools/Source/Python/GenFds/FdfParser.py +++ b/BaseTools/Source/Python/GenFds/FdfParser.py @@ -1250,7 +1250,7 @@ class FdfParser: # @retval False Not able to find a string data, file buffer po= inter not changed # def __GetStringData(self): - if self.__Token.startswith("\"") or self.__Token.startswith("L\""): + if self.__Token.startswith(("\"","L\"")): self.__UndoToken() self.__SkipToToken("\"") currentLineNumber =3D self.CurrentLineNumber @@ -1262,7 +1262,7 @@ class FdfParser: self.__Token =3D self.__SkippedChars.rstrip('\"') return True =20 - elif self.__Token.startswith("\'") or self.__Token.startswith("L\'= "): + elif self.__Token.startswith(("\'","L\'")): self.__UndoToken() self.__SkipToToken("\'") currentLineNumber =3D self.CurrentLineNumber @@ -1392,8 +1392,7 @@ class FdfParser: =20 def SectionParser(self, section): S =3D section.upper() - if not S.startswith("[DEFINES") and not S.startswith("[FD.") and n= ot S.startswith("[FV.") and not S.startswith("[CAPSULE.") \ - and not S.startswith("[VTF.") and not S.startswith("[RULE.") a= nd not S.startswith("[OPTIONROM.") and not S.startswith('[FMPPAYLOAD.'): + if not S.startswith(("[DEFINES","[FD.","[FV.","[CAPSULE.","[VTF.",= "[RULE.","[OPTIONROM.",'[FMPPAYLOAD.')): raise Warning("Unknown section or section appear sequence erro= r (The correct sequence should be [DEFINES], [FD.], [FV.], [Capsule.], [VTF= .], [Rule.], [OptionRom.], [FMPPAYLOAD.])", self.FileName, self.CurrentLine= Number) =20 ## __GetDefines() method @@ -1457,8 +1456,7 @@ class FdfParser: =20 S =3D self.__Token.upper() if S.startswith("[") and not S.startswith("[FD."): - if not S.startswith("[FV.") and not S.startswith('[FMPPAYLOAD.= ') and not S.startswith("[CAPSULE.") \ - and not S.startswith("[VTF.") and not S.startswith("[RULE.= ") and not S.startswith("[OPTIONROM."): + if not S.startswith(("[FV.",'[FMPPAYLOAD.',"[CAPSULE.","[VTF."= ,"[RULE.","[OPTIONROM.")): raise Warning("Unknown section", self.FileName, self.Curre= ntLineNumber) self.__UndoToken() return False diff --git a/BaseTools/Source/Python/Trim/Trim.py b/BaseTools/Source/Python= /Trim/Trim.py index a74075859148..d2e6d317676c 100644 --- a/BaseTools/Source/Python/Trim/Trim.py +++ b/BaseTools/Source/Python/Trim/Trim.py @@ -409,7 +409,7 @@ def TrimAslFile(Source, Target, IncludePathFile): LineNum =3D 0 for Line in open(IncludePathFile,'r'): LineNum +=3D 1 - if Line.startswith("/I") or Line.startswith ("-I"): + if Line.startswith(("/I","-I")): IncludePathList.append(Line[2:].strip()) else: EdkLogger.warn("Trim", "Invalid include line in includ= e list file.", IncludePathFile, LineNum) diff --git a/BaseTools/Source/Python/Workspace/BuildClassObject.py b/BaseTo= ols/Source/Python/Workspace/BuildClassObject.py index db9518cdff17..3e68be3ce34e 100644 --- a/BaseTools/Source/Python/Workspace/BuildClassObject.py +++ b/BaseTools/Source/Python/Workspace/BuildClassObject.py @@ -82,7 +82,7 @@ class PcdClassObject(object): if self.PcdValueFromComm: if self.PcdValueFromComm.startswith("{") and self.PcdValueFrom= Comm.endswith("}"): return max([len(self.PcdValueFromComm.split(",")),MaxSize]) - elif self.PcdValueFromComm.startswith("\"") or self.PcdValueFr= omComm.startswith("\'"): + elif self.PcdValueFromComm.startswith(("\"","\'")): return max([len(self.PcdValueFromComm)-2+1,MaxSize]) elif self.PcdValueFromComm.startswith("L\""): return max([2*(len(self.PcdValueFromComm)-3+1),MaxSize]) diff --git a/BaseTools/Source/Python/Workspace/DscBuildData.py b/BaseTools/= Source/Python/Workspace/DscBuildData.py index 8476543c5352..2de8a84b9bd7 100644 --- a/BaseTools/Source/Python/Workspace/DscBuildData.py +++ b/BaseTools/Source/Python/Workspace/DscBuildData.py @@ -1062,7 +1062,7 @@ class DscBuildData(PlatformBuildClassObject): except BadExpression, Value: =20 EdkLogger.error('Parser', FORMAT_INVALID, 'PCD [%s.%s] Val= ue "%s", %s' % (TokenSpaceGuidCName, TokenCName, PcdValue= , Value)) - elif PcdValue.startswith("L'") or PcdValue.startswith("'"): + elif PcdValue.startswith(("L'","'")): if FieldName and IsFieldValueAnArray(PcdValue): PcdDatumType =3D TAB_VOID IsArray =3D True diff --git a/BaseTools/Source/Python/Workspace/InfBuildData.py b/BaseTools/= Source/Python/Workspace/InfBuildData.py index bd1c84154123..12d848b5fc41 100644 --- a/BaseTools/Source/Python/Workspace/InfBuildData.py +++ b/BaseTools/Source/Python/Workspace/InfBuildData.py @@ -1080,7 +1080,7 @@ class InfBuildData(ModuleBuildClassObject): # Check hexadecimal token value length and format. # ReIsValidPcdTokenValue =3D re.compile(r"^[0][x|X][0]*[= 0-9a-fA-F]{1,8}$", re.DOTALL) - if Pcd.TokenValue.startswith("0x") or Pcd.TokenValue.s= tartswith("0X"): + if Pcd.TokenValue.startswith(("0x","0X")): if ReIsValidPcdTokenValue.match(Pcd.TokenValue) is= None: EdkLogger.error( 'build', diff --git a/BaseTools/Source/Python/build/BuildReport.py b/BaseTools/Sourc= e/Python/build/BuildReport.py index cf45ef173498..72a557dfea50 100644 --- a/BaseTools/Source/Python/build/BuildReport.py +++ b/BaseTools/Source/Python/build/BuildReport.py @@ -1318,7 +1318,7 @@ class PcdReport(object): return value[1:-1] for ch in value[1:-1].split(','): ch =3D ch.strip() - if ch.startswith('0x') or ch.startswith('0X'): + if ch.startswith(('0x','0X')): valuelist.append(ch) continue try: --=20 2.16.2.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Fri May 3 05:47:03 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 1526321368513842.6733030167713; Mon, 14 May 2018 11:09:28 -0700 (PDT) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 2DBD72096AEC3; Mon, 14 May 2018 11:09:26 -0700 (PDT) Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 0CA962096966E for ; Mon, 14 May 2018 11:09:25 -0700 (PDT) Received: from orsmga001.jf.intel.com ([10.7.209.18]) by orsmga105.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 14 May 2018 11:09:23 -0700 Received: from jcarsey-desk1.amr.corp.intel.com ([10.7.159.144]) by orsmga001.jf.intel.com with ESMTP; 14 May 2018 11:09:23 -0700 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.100; helo=mga07.intel.com; envelope-from=jaben.carsey@intel.com; receiver=edk2-devel@lists.01.org X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.49,401,1520924400"; d="scan'208";a="55814267" From: Jaben Carsey To: edk2-devel@lists.01.org Date: Mon, 14 May 2018 11:09:14 -0700 Message-Id: X-Mailer: git-send-email 2.16.2.windows.1 In-Reply-To: References: In-Reply-To: References: Subject: [edk2] [PATCH v1 05/11] BaseTools: use set presence instead of series of equality X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.26 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Liming Gao MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" Instead of testing each equality individually, just make a set and test onc= e. Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jaben Carsey --- BaseTools/Source/Python/Ecc/Configuration.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/BaseTools/Source/Python/Ecc/Configuration.py b/BaseTools/Sourc= e/Python/Ecc/Configuration.py index fee7ecb9703d..d37ce8e19e67 100644 --- a/BaseTools/Source/Python/Ecc/Configuration.py +++ b/BaseTools/Source/Python/Ecc/Configuration.py @@ -404,17 +404,9 @@ class Configuration(object): ErrorMsg =3D "Invalid configuration option '%s' was fo= und" % List[0] EdkLogger.error("Ecc", EdkLogger.ECC_ERROR, ErrorMsg, = File =3D Filepath, Line =3D LineNo) assert _ConfigFileToInternalTranslation[List[0]] in self._= _dict__ - if List[0] =3D=3D 'ModifierList': - List[1] =3D GetSplitValueList(List[1], TAB_COMMA_SPLIT) if List[0] =3D=3D 'MetaDataFileCheckPathOfGenerateFileList= ' and List[1] =3D=3D "": continue - if List[0] =3D=3D 'SkipDirList': - List[1] =3D GetSplitValueList(List[1], TAB_COMMA_SPLIT) - if List[0] =3D=3D 'SkipFileList': - List[1] =3D GetSplitValueList(List[1], TAB_COMMA_SPLIT) - if List[0] =3D=3D 'BinaryExtList': - List[1] =3D GetSplitValueList(List[1], TAB_COMMA_SPLIT) - if List[0] =3D=3D 'Copyright': + if List[0] in {'ModifierList','SkipDirList','SkipFileList'= ,'BinaryExtList','Copyright'}: List[1] =3D GetSplitValueList(List[1], TAB_COMMA_SPLIT) self.__dict__[_ConfigFileToInternalTranslation[List[0]]] = =3D List[1] =20 --=20 2.16.2.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Fri May 3 05:47:03 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 152632138076595.4367920607142; Mon, 14 May 2018 11:09:40 -0700 (PDT) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id E68DF21E11D1A; Mon, 14 May 2018 11:09:26 -0700 (PDT) Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 3B66520969677 for ; Mon, 14 May 2018 11:09:25 -0700 (PDT) Received: from orsmga001.jf.intel.com ([10.7.209.18]) by orsmga105.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 14 May 2018 11:09:24 -0700 Received: from jcarsey-desk1.amr.corp.intel.com ([10.7.159.144]) by orsmga001.jf.intel.com with ESMTP; 14 May 2018 11:09:23 -0700 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.100; helo=mga07.intel.com; envelope-from=jaben.carsey@intel.com; receiver=edk2-devel@lists.01.org X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.49,401,1520924400"; d="scan'208";a="55814271" From: Jaben Carsey To: edk2-devel@lists.01.org Date: Mon, 14 May 2018 11:09:15 -0700 Message-Id: <10fc6ddcc1a79a8cd26c26871c9b52cbea15c1b3.1526321052.git.jaben.carsey@intel.com> X-Mailer: git-send-email 2.16.2.windows.1 In-Reply-To: References: In-Reply-To: References: Subject: [edk2] [PATCH v1 06/11] BaseTools: refactor section generation X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.26 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Liming Gao MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" use with for opening files remove unneeded variables dont seek to 0 for just opened file Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jaben Carsey --- BaseTools/Source/Python/Common/DataType.py | 1 + BaseTools/Source/Python/GenFds/CompressSection.py | 18 +- BaseTools/Source/Python/GenFds/DataSection.py | 28 +-- BaseTools/Source/Python/GenFds/DepexSection.py | 2 +- BaseTools/Source/Python/GenFds/EfiSection.py | 109 +++++---- BaseTools/Source/Python/GenFds/FfsInfStatement.py | 10 +- BaseTools/Source/Python/GenFds/FvImageSection.py | 28 +-- BaseTools/Source/Python/GenFds/GuidSection.py | 8 +- BaseTools/Source/Python/GenFds/OptRomInfStatement.py | 4 +- BaseTools/Source/Python/GenFds/Section.py | 231 ++++++++-------= ----- BaseTools/Source/Python/GenFds/UiSection.py | 18 +- BaseTools/Source/Python/GenFds/VerSection.py | 22 +- 12 files changed, 206 insertions(+), 273 deletions(-) diff --git a/BaseTools/Source/Python/Common/DataType.py b/BaseTools/Source/= Python/Common/DataType.py index a72c7e6f067f..93136dff0db2 100644 --- a/BaseTools/Source/Python/Common/DataType.py +++ b/BaseTools/Source/Python/Common/DataType.py @@ -50,6 +50,7 @@ TAB_EDK_SOURCE =3D '$(EDK_SOURCE)' TAB_EFI_SOURCE =3D '$(EFI_SOURCE)' TAB_WORKSPACE =3D '$(WORKSPACE)' TAB_FV_DIRECTORY =3D 'FV' +TAB_SEC_DIRECTORY =3D 'SEC' =20 TAB_ARCH_NULL =3D '' TAB_ARCH_COMMON =3D 'COMMON' diff --git a/BaseTools/Source/Python/GenFds/CompressSection.py b/BaseTools/= Source/Python/GenFds/CompressSection.py index cdae74c52fd9..b7aa72e43992 100644 --- a/BaseTools/Source/Python/GenFds/CompressSection.py +++ b/BaseTools/Source/Python/GenFds/CompressSection.py @@ -56,7 +56,7 @@ class CompressSection (CompressSectionClassObject) : # def GenSection(self, OutputPath, ModuleName, SecNum, KeyStringList, Ff= sInf =3D None, Dict =3D {}, IsMakefile =3D False): =20 - if FfsInf is not None: + if FfsInf: self.CompType =3D FfsInf.__ExtendMacro__(self.CompType) self.Alignment =3D FfsInf.__ExtendMacro__(self.Alignment) =20 @@ -68,13 +68,13 @@ class CompressSection (CompressSectionClassObject) : Index =3D Index + 1 SecIndex =3D '%s.%d' %(SecNum, Index) ReturnSectList, AlignValue =3D Sect.GenSection(OutputPath, Mod= uleName, SecIndex, KeyStringList, FfsInf, Dict, IsMakefile=3DIsMakefile) - if AlignValue is not None: - if MaxAlign is None: + if AlignValue: + if not MaxAlign: MaxAlign =3D AlignValue if GenFdsGlobalVariable.GetAlignment (AlignValue) > GenFds= GlobalVariable.GetAlignment (MaxAlign): MaxAlign =3D AlignValue if ReturnSectList !=3D []: - if AlignValue is None: + if not AlignValue: AlignValue =3D "1" for FileData in ReturnSectList: SectFiles +=3D (FileData,) @@ -83,17 +83,13 @@ class CompressSection (CompressSectionClassObject) : OutputFile =3D OutputPath + \ os.sep + \ ModuleName + \ - SUP_MODULE_SEC + \ + SUP_MODULE_SEC + \ SecNum + \ SectionSuffix['COMPRESS'] OutputFile =3D os.path.normpath(OutputFile) DummyFile =3D OutputFile + '.dummy' GenFdsGlobalVariable.GenerateSection(DummyFile, SectFiles, InputAl= ign=3DSectAlign, IsMakefile=3DIsMakefile) =20 - GenFdsGlobalVariable.GenerateSection(OutputFile, [DummyFile], Sect= ion.Section.SectionType['COMPRESS'], + GenFdsGlobalVariable.GenerateSection(OutputFile, [DummyFile], Sect= ion.SectionType['COMPRESS'], CompressionType=3Dself.CompTy= peDict[self.CompType], IsMakefile=3DIsMakefile) - OutputFileList =3D [] - OutputFileList.append(OutputFile) - return OutputFileList, self.Alignment - - + return [OutputFile], self.Alignment diff --git a/BaseTools/Source/Python/GenFds/DataSection.py b/BaseTools/Sour= ce/Python/GenFds/DataSection.py index f0e5efab4178..71c2796b0b39 100644 --- a/BaseTools/Source/Python/GenFds/DataSection.py +++ b/BaseTools/Source/Python/GenFds/DataSection.py @@ -50,39 +50,39 @@ class DataSection (DataSectionClassObject): # @retval tuple (Generated file name list, section alignment) # def GenSection(self, OutputPath, ModuleName, SecNum, keyStringList, Ff= sFile =3D None, Dict =3D {}, IsMakefile =3D False): + + self.SectFileName =3D GenFdsGlobalVariable.ReplaceWorkspaceMacro(s= elf.SectFileName) # # Prepare the parameter of GenSection # - if FfsFile is not None: - self.SectFileName =3D GenFdsGlobalVariable.ReplaceWorkspaceMac= ro(self.SectFileName) + if FfsFile: self.SectFileName =3D GenFdsGlobalVariable.MacroExtend(self.Se= ctFileName, Dict, FfsFile.CurrentArch) else: - self.SectFileName =3D GenFdsGlobalVariable.ReplaceWorkspaceMac= ro(self.SectFileName) self.SectFileName =3D GenFdsGlobalVariable.MacroExtend(self.Se= ctFileName, Dict) =20 - """Check Section file exist or not !""" - + # + # Check Section file exist or not + # if not os.path.exists(self.SectFileName): self.SectFileName =3D os.path.join (GenFdsGlobalVariable.WorkS= paceDir, self.SectFileName) =20 - """Copy Map file to Ffs output""" + # + # Copy Map file to Ffs output + # Filename =3D GenFdsGlobalVariable.MacroExtend(self.SectFileName) - if Filename[(len(Filename)-4):] =3D=3D '.efi': + if Filename.endswith('.efi'): MapFile =3D Filename.replace('.efi', '.map') CopyMapFile =3D os.path.join(OutputPath, ModuleName + '.map') if IsMakefile: - if GenFdsGlobalVariable.CopyList =3D=3D []: - GenFdsGlobalVariable.CopyList =3D [(MapFile, CopyMapFi= le)] - else: - GenFdsGlobalVariable.CopyList.append((MapFile, CopyMap= File)) + GenFdsGlobalVariable.CopyList.append((MapFile, CopyMapFile= )) else: if os.path.exists(MapFile): if not os.path.exists(CopyMapFile) or (os.path.getmtim= e(MapFile) > os.path.getmtime(CopyMapFile)): CopyLongFilePath(MapFile, CopyMapFile) =20 #Get PE Section alignment when align is set to AUTO - if self.Alignment =3D=3D 'Auto' and self.SecType in (BINARY_FILE_T= YPE_TE, BINARY_FILE_TYPE_PE32): + if self.Alignment =3D=3D 'Auto' and self.SecType in {BINARY_FILE_T= YPE_TE, BINARY_FILE_TYPE_PE32}: ImageObj =3D PeImageClass (Filename) if ImageObj.SectionAlignment < 0x400: self.Alignment =3D str (ImageObj.SectionAlignment) @@ -120,8 +120,8 @@ class DataSection (DataSectionClassObject): ) self.SectFileName =3D TeFile =20 - OutputFile =3D os.path.join (OutputPath, ModuleName + 'SEC' + SecN= um + SectionSuffix.get(self.SecType)) + OutputFile =3D os.path.join (OutputPath, ModuleName + TAB_SEC_DIRE= CTORY + SecNum + SectionSuffix.get(self.SecType)) OutputFile =3D os.path.normpath(OutputFile) - GenFdsGlobalVariable.GenerateSection(OutputFile, [self.SectFileNam= e], Section.Section.SectionType.get(self.SecType), IsMakefile =3D IsMakefil= e) + GenFdsGlobalVariable.GenerateSection(OutputFile, [self.SectFileNam= e], Section.SectionType.get(self.SecType), IsMakefile =3D IsMakefile) FileList =3D [OutputFile] return FileList, self.Alignment diff --git a/BaseTools/Source/Python/GenFds/DepexSection.py b/BaseTools/Sou= rce/Python/GenFds/DepexSection.py index 6e63cb97e51d..4392b9c62409 100644 --- a/BaseTools/Source/Python/GenFds/DepexSection.py +++ b/BaseTools/Source/Python/GenFds/DepexSection.py @@ -114,5 +114,5 @@ class DepexSection (DepexSectionClassObject): OutputFile =3D os.path.join (OutputPath, ModuleName + SUP_MODULE_S= EC + SecNum + '.dpx') OutputFile =3D os.path.normpath(OutputFile) =20 - GenFdsGlobalVariable.GenerateSection(OutputFile, [InputFile], Sect= ion.Section.SectionType.get (SecType), IsMakefile=3DIsMakefile) + GenFdsGlobalVariable.GenerateSection(OutputFile, [InputFile], Sect= ion.SectionType.get (SecType), IsMakefile=3DIsMakefile) return [OutputFile], self.Alignment diff --git a/BaseTools/Source/Python/GenFds/EfiSection.py b/BaseTools/Sourc= e/Python/GenFds/EfiSection.py index 0064196a5a4e..5e8379548d27 100644 --- a/BaseTools/Source/Python/GenFds/EfiSection.py +++ b/BaseTools/Source/Python/GenFds/EfiSection.py @@ -58,8 +58,11 @@ class EfiSection (EfiSectionClassObject): =20 if self.FileName is not None and self.FileName.startswith('PCD('): self.FileName =3D GenFdsGlobalVariable.GetPcdValue(self.FileNa= me) - """Prepare the parameter of GenSection""" - if FfsInf is not None : + =20 + # + # Prepare the parameter of GenSection + # + if FfsInf: InfFileName =3D FfsInf.InfFileName SectionType =3D FfsInf.__ExtendMacro__(self.SectionType) Filename =3D FfsInf.__ExtendMacro__(self.FileName) @@ -67,21 +70,23 @@ class EfiSection (EfiSectionClassObject): StringData =3D FfsInf.__ExtendMacro__(self.StringData) ModuleNameStr =3D FfsInf.__ExtendMacro__('$(MODULE_NAME)') NoStrip =3D True - if FfsInf.ModuleType in (SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, = SUP_MODULE_PEIM) and SectionType in (BINARY_FILE_TYPE_TE, BINARY_FILE_TYPE_= PE32): - if FfsInf.KeepReloc is not None: + if FfsInf.ModuleType in {SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, = SUP_MODULE_PEIM} and SectionType in {BINARY_FILE_TYPE_TE, BINARY_FILE_TYPE_= PE32}: + if FfsInf.KeepReloc: NoStrip =3D FfsInf.KeepReloc - elif FfsInf.KeepRelocFromRule is not None: + elif FfsInf.KeepRelocFromRule: NoStrip =3D FfsInf.KeepRelocFromRule - elif self.KeepReloc is not None: + elif self.KeepReloc: NoStrip =3D self.KeepReloc - elif FfsInf.ShadowFromInfFile is not None: + elif FfsInf.ShadowFromInfFile: NoStrip =3D FfsInf.ShadowFromInfFile else: EdkLogger.error("GenFds", GENFDS_ERROR, "Module %s apply rule = for None!" %ModuleName) =20 - """If the file name was pointed out, add it in FileList""" + # + # If the file name was pointed out, add it in FileList + # FileList =3D [] - if Filename is not None: + if Filename: Filename =3D GenFdsGlobalVariable.MacroExtend(Filename, Dict) # check if the path is absolute or relative if os.path.isabs(Filename): @@ -98,34 +103,26 @@ class EfiSection (EfiSectionClassObject): if '.depex' in SuffixMap: FileList.append(Filename) else: - FileList, IsSect =3D Section.Section.GetFileList(FfsInf, self.= FileType, self.FileExtension, Dict, IsMakefile=3DIsMakefile) + FileList, IsSect =3D Section.GetSectionFileList(FfsInf, self.F= ileType, self.FileExtension, Dict, IsMakefile=3DIsMakefile) if IsSect : return FileList, self.Alignment =20 Index =3D 0 Align =3D self.Alignment =20 - """ If Section type is 'VERSION'""" + # + # If Section type is 'VERSION' + # OutputFileList =3D [] if SectionType =3D=3D 'VERSION': - InfOverrideVerString =3D False - if FfsInf.Version is not None: - #StringData =3D FfsInf.Version + if FfsInf.Version: BuildNum =3D FfsInf.Version InfOverrideVerString =3D True =20 if InfOverrideVerString: - #VerTuple =3D ('-n', '"' + StringData + '"') - if BuildNum is not None and BuildNum !=3D '': - BuildNumTuple =3D ('-j', BuildNum) - else: - BuildNumTuple =3D tuple() - - Num =3D SecNum - OutputFile =3D os.path.join( OutputPath, ModuleName + 'SEC= ' + str(Num) + SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join( OutputPath, ModuleName + TAB_= SEC_DIRECTORY + str(SecNum) + SectionSuffix.get(SectionType)) GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_= SECTION_VERSION', - #Ui=3DStringData, Ver=3DBuildNum, IsMakefile=3DIsMakefil= e) OutputFileList.append(OutputFile) @@ -134,38 +131,31 @@ class EfiSection (EfiSectionClassObject): for File in FileList: Index =3D Index + 1 Num =3D '%s.%d' %(SecNum , Index) - OutputFile =3D os.path.join(OutputPath, ModuleName + '= SEC' + Num + SectionSuffix.get(SectionType)) - f =3D open(File, 'r') - VerString =3D f.read() - f.close() + OutputFile =3D os.path.join(OutputPath, ModuleName + T= AB_SEC_DIRECTORY + Num + SectionSuffix.get(SectionType)) + with open(File, 'r') as f: + VerString =3D f.read() BuildNum =3D VerString - if BuildNum is not None and BuildNum !=3D '': - BuildNumTuple =3D ('-j', BuildNum) GenFdsGlobalVariable.GenerateSection(OutputFile, [], '= EFI_SECTION_VERSION', - #Ui=3DVerString, Ver=3DBuildNum, IsMakefile=3DIsMak= efile) OutputFileList.append(OutputFile) =20 else: BuildNum =3D StringData - if BuildNum is not None and BuildNum !=3D '': + if BuildNum: BuildNumTuple =3D ('-j', BuildNum) else: BuildNumTuple =3D tuple() BuildNumString =3D ' ' + ' '.join(BuildNumTuple) =20 - #if VerString =3D=3D '' and=20 if BuildNumString =3D=3D '': if self.Optional =3D=3D True : GenFdsGlobalVariable.VerboseLogger( "Optional Sect= ion don't exist!") return [], None else: EdkLogger.error("GenFds", GENFDS_ERROR, "File: %s = miss Version Section value" %InfFileName) - Num =3D SecNum - OutputFile =3D os.path.join( OutputPath, ModuleName + 'SEC= ' + str(Num) + SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join( OutputPath, ModuleName + TAB_= SEC_DIRECTORY + str(SecNum) + SectionSuffix.get(SectionType)) GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_= SECTION_VERSION', - #Ui=3DVerString, Ver=3DBuildNum, IsMakefile=3DIsMakefil= e) OutputFileList.append(OutputFile) @@ -176,15 +166,14 @@ class EfiSection (EfiSectionClassObject): elif SectionType =3D=3D BINARY_FILE_TYPE_UI: =20 InfOverrideUiString =3D False - if FfsInf.Ui is not None: + if FfsInf.Ui: StringData =3D FfsInf.Ui InfOverrideUiString =3D True =20 if InfOverrideUiString: - Num =3D SecNum if IsMakefile and StringData =3D=3D ModuleNameStr: StringData =3D "$(MODULE_NAME)" - OutputFile =3D os.path.join( OutputPath, ModuleName + 'SEC= ' + str(Num) + SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join( OutputPath, ModuleName + TAB_= SEC_DIRECTORY + str(SecNum) + SectionSuffix.get(SectionType)) GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_= SECTION_USER_INTERFACE', Ui=3DStringData, IsMa= kefile=3DIsMakefile) OutputFileList.append(OutputFile) @@ -193,38 +182,34 @@ class EfiSection (EfiSectionClassObject): for File in FileList: Index =3D Index + 1 Num =3D '%s.%d' %(SecNum , Index) - OutputFile =3D os.path.join(OutputPath, ModuleName + '= SEC' + Num + SectionSuffix.get(SectionType)) - f =3D open(File, 'r') - UiString =3D f.read() - f.close() + OutputFile =3D os.path.join(OutputPath, ModuleName + T= AB_SEC_DIRECTORY + Num + SectionSuffix.get(SectionType)) + with open(File, 'r') as f: + UiString =3D f.read() if IsMakefile and UiString =3D=3D ModuleNameStr: UiString =3D "$(MODULE_NAME)" GenFdsGlobalVariable.GenerateSection(OutputFile, [], '= EFI_SECTION_USER_INTERFACE', Ui=3DUiString, IsM= akefile=3DIsMakefile) OutputFileList.append(OutputFile) else: - if StringData is not None and len(StringData) > 0: - UiTuple =3D ('-n', '"' + StringData + '"') - else: - UiTuple =3D tuple() - + if not StringData: if self.Optional =3D=3D True : GenFdsGlobalVariable.VerboseLogger( "Optional Sect= ion don't exist!") return '', None else: EdkLogger.error("GenFds", GENFDS_ERROR, "File: %s = miss UI Section value" %InfFileName) =20 - Num =3D SecNum if IsMakefile and StringData =3D=3D ModuleNameStr: StringData =3D "$(MODULE_NAME)" - OutputFile =3D os.path.join( OutputPath, ModuleName + 'SEC= ' + str(Num) + SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join( OutputPath, ModuleName + TAB_= SEC_DIRECTORY + str(SecNum) + SectionSuffix.get(SectionType)) GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_= SECTION_USER_INTERFACE', Ui=3DStringData, IsMa= kefile=3DIsMakefile) OutputFileList.append(OutputFile) =20 =20 else: - """If File List is empty""" + # + # If File List is empty + # if FileList =3D=3D [] : if self.Optional =3D=3D True: GenFdsGlobalVariable.VerboseLogger("Optional Section d= on't exist!") @@ -233,16 +218,20 @@ class EfiSection (EfiSectionClassObject): EdkLogger.error("GenFds", GENFDS_ERROR, "Output file f= or %s section could not be found for %s" % (SectionType, InfFileName)) =20 else: - """Convert the File to Section file one by one """ + # + # Convert the File to Section file one by one + # for File in FileList: - """ Copy Map file to FFS output path """ + # + # Copy Map file to FFS output path + # Index =3D Index + 1 Num =3D '%s.%d' %(SecNum , Index) - OutputFile =3D os.path.join( OutputPath, ModuleName + = 'SEC' + Num + SectionSuffix.get(SectionType)) + OutputFile =3D os.path.join( OutputPath, ModuleName + = TAB_SEC_DIRECTORY + Num + SectionSuffix.get(SectionType)) File =3D GenFdsGlobalVariable.MacroExtend(File, Dict) =20 #Get PE Section alignment when align is set to AUTO - if self.Alignment =3D=3D 'Auto' and (SectionType =3D= =3D BINARY_FILE_TYPE_PE32 or SectionType =3D=3D BINARY_FILE_TYPE_TE): + if self.Alignment =3D=3D 'Auto' and SectionType in {BI= NARY_FILE_TYPE_PE32, BINARY_FILE_TYPE_TE}: ImageObj =3D PeImageClass (File) if ImageObj.SectionAlignment < 0x400: Align =3D str (ImageObj.SectionAlignment) @@ -251,7 +240,7 @@ class EfiSection (EfiSectionClassObject): else: Align =3D str (ImageObj.SectionAlignment / 0x1= 00000) + 'M' =20 - if File[(len(File)-4):] =3D=3D '.efi': + if File.endswith('.efi'): MapFile =3D File.replace('.efi', '.map') CopyMapFile =3D os.path.join(OutputPath, ModuleNam= e + '.map') if IsMakefile: @@ -285,7 +274,9 @@ class EfiSection (EfiSectionClassObject): ) File =3D StrippedFile =20 - """For TE Section call GenFw to generate TE image""" + # + # For TE Section call GenFw to generate TE image + # =20 if SectionType =3D=3D BINARY_FILE_TYPE_TE: TeFile =3D os.path.join( OutputPath, ModuleName + = 'Te.raw') @@ -297,10 +288,12 @@ class EfiSection (EfiSectionClassObject): ) File =3D TeFile =20 - """Call GenSection""" + # + # Call GenSection + # GenFdsGlobalVariable.GenerateSection(OutputFile, [File], - Section.Section.Se= ctionType.get (SectionType), + Section.SectionTyp= e.get (SectionType), IsMakefile=3DIsMak= efile ) OutputFileList.append(OutputFile) diff --git a/BaseTools/Source/Python/GenFds/FfsInfStatement.py b/BaseTools/= Source/Python/GenFds/FfsInfStatement.py index f76563d736f6..39426b939b4a 100644 --- a/BaseTools/Source/Python/GenFds/FfsInfStatement.py +++ b/BaseTools/Source/Python/GenFds/FfsInfStatement.py @@ -731,7 +731,7 @@ class FfsInfStatement(FfsInfStatementClassObject): else: GenSecInputFile =3D os.path.normpath(os.path.join(self.Efi= OutputPath, GenSecInputFile)) else: - FileList, IsSect =3D Section.Section.GetFileList(self, '', Rul= e.FileExtension) + FileList, IsSect =3D Section.GetSectionFileList(self, '', Rule= .FileExtension) =20 Index =3D 1 SectionType =3D Rule.SectionType @@ -761,7 +761,7 @@ class FfsInfStatement(FfsInfStatementClassObject): =20 SecNum =3D '%d' %Index GenSecOutputFile=3D self.__ExtendMacro__(Rule.NameGuid) + \ - SectionSuffix[SectionType] + 'SEC' + SecNum + SectionSuffix[SectionType] + TAB_SEC_DIRECTO= RY + SecNum Index =3D Index + 1 OutputFile =3D os.path.join(self.OutputPath, GenSecOutputF= ile) File =3D GenFdsGlobalVariable.MacroExtend(File, Dict, self= .CurrentArch) @@ -799,12 +799,12 @@ class FfsInfStatement(FfsInfStatementClassObject): IsMakefile=3DIsMakefile ) File =3D TeFile - GenFdsGlobalVariable.GenerateSection(OutputFile, [File], S= ection.Section.SectionType[SectionType], IsMakefile=3DIsMakefile) + GenFdsGlobalVariable.GenerateSection(OutputFile, [File], S= ection.SectionType[SectionType], IsMakefile=3DIsMakefile) OutputFileList.append(OutputFile) else: SecNum =3D '%d' %Index GenSecOutputFile=3D self.__ExtendMacro__(Rule.NameGuid) + \ - SectionSuffix[SectionType] + 'SEC' + SecNum + SectionSuffix[SectionType] + TAB_SEC_DIRECTO= RY + SecNum OutputFile =3D os.path.join(self.OutputPath, GenSecOutputFile) GenSecInputFile =3D GenFdsGlobalVariable.MacroExtend(GenSecInp= utFile, Dict, self.CurrentArch) =20 @@ -842,7 +842,7 @@ class FfsInfStatement(FfsInfStatementClassObject): IsMakefile=3DIsMakefile ) GenSecInputFile =3D TeFile - GenFdsGlobalVariable.GenerateSection(OutputFile, [GenSecInputF= ile], Section.Section.SectionType[SectionType], IsMakefile=3DIsMakefile) + GenFdsGlobalVariable.GenerateSection(OutputFile, [GenSecInputF= ile], Section.SectionType[SectionType], IsMakefile=3DIsMakefile) OutputFileList.append(OutputFile) =20 return OutputFileList diff --git a/BaseTools/Source/Python/GenFds/FvImageSection.py b/BaseTools/S= ource/Python/GenFds/FvImageSection.py index 380fbe56f1c4..dc5dcb7f8e0d 100644 --- a/BaseTools/Source/Python/GenFds/FvImageSection.py +++ b/BaseTools/Source/Python/GenFds/FvImageSection.py @@ -54,28 +54,24 @@ class FvImageSection(FvImageSectionClassObject): def GenSection(self, OutputPath, ModuleName, SecNum, KeyStringList, Ff= sInf =3D None, Dict =3D {}, IsMakefile =3D False): =20 OutputFileList =3D [] - if self.FvFileType is not None: - FileList, IsSect =3D Section.Section.GetFileList(FfsInf, self.= FvFileType, self.FvFileExtension) + if self.FvFileType: + FileList, IsSect =3D Section.GetSectionFileList(FfsInf, self.F= vFileType, self.FvFileExtension) if IsSect : return FileList, self.Alignment =20 - Num =3D SecNum - MaxFvAlignment =3D 0 for FvFileName in FileList: FvAlignmentValue =3D 0 if os.path.isfile(FvFileName): - FvFileObj =3D open (FvFileName,'rb') - FvFileObj.seek(0) + with open (FvFileName,'rb') as FvFileObj: # PI FvHeader is 0x48 byte FvHeaderBuffer =3D FvFileObj.read(0x48) # FV alignment position. FvAlignmentValue =3D 1 << (ord (FvHeaderBuffer[0x2E]) = & 0x1F) - FvFileObj.close() if FvAlignmentValue > MaxFvAlignment: MaxFvAlignment =3D FvAlignmentValue =20 - OutputFile =3D os.path.join(OutputPath, ModuleName + 'SEC'= + Num + SectionSuffix["FV_IMAGE"]) + OutputFile =3D os.path.join(OutputPath, ModuleName + TAB_S= EC_DIRECTORY + SecNum + SectionSuffix["FV_IMAGE"]) GenFdsGlobalVariable.GenerateSection(OutputFile, [FvFileNa= me], 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE', IsMakefile=3DIsMakefile) OutputFileList.append(OutputFile) =20 @@ -97,24 +93,23 @@ class FvImageSection(FvImageSectionClassObject): # # Generate Fv # - if self.FvName is not None: + if self.FvName: Buffer =3D StringIO.StringIO('') Fv =3D GenFdsGlobalVariable.FdfParser.Profile.FvDict.get(self.= FvName) - if Fv is not None: + if Fv: self.Fv =3D Fv FvFileName =3D Fv.AddToBuffer(Buffer, self.FvAddr, MacroDi= ct =3D Dict, Flag=3DIsMakefile) - if Fv.FvAlignment is not None: - if self.Alignment is None: + if Fv.FvAlignment: + if not self.Alignment: self.Alignment =3D Fv.FvAlignment else: if GenFdsGlobalVariable.GetAlignment (Fv.FvAlignme= nt) > GenFdsGlobalVariable.GetAlignment (self.Alignment): self.Alignment =3D Fv.FvAlignment else: - if self.FvFileName is not None: + if self.FvFileName: FvFileName =3D GenFdsGlobalVariable.ReplaceWorkspaceMa= cro(self.FvFileName) if os.path.isfile(FvFileName): - FvFileObj =3D open (FvFileName,'rb') - FvFileObj.seek(0) + with open (FvFileName,'rb') as FvFileObj: # PI FvHeader is 0x48 byte FvHeaderBuffer =3D FvFileObj.read(0x48) # FV alignment position. @@ -132,14 +127,13 @@ class FvImageSection(FvImageSectionClassObject): else: # FvAlignmentValue is less than 1K self.Alignment =3D str (FvAlignmentValue) - FvFileObj.close() else: EdkLogger.error("GenFds", GENFDS_ERROR, "FvImageSectio= n Failed! %s NOT found in FDF" % self.FvName) =20 # # Prepare the parameter of GenSection # - OutputFile =3D os.path.join(OutputPath, ModuleName + 'SEC' + S= ecNum + SectionSuffix["FV_IMAGE"]) + OutputFile =3D os.path.join(OutputPath, ModuleName + TAB_SEC_D= IRECTORY + SecNum + SectionSuffix["FV_IMAGE"]) GenFdsGlobalVariable.GenerateSection(OutputFile, [FvFileName],= 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE', IsMakefile=3DIsMakefile) OutputFileList.append(OutputFile) =20 diff --git a/BaseTools/Source/Python/GenFds/GuidSection.py b/BaseTools/Sour= ce/Python/GenFds/GuidSection.py index 104650d16781..bc95c7cd9d42 100644 --- a/BaseTools/Source/Python/GenFds/GuidSection.py +++ b/BaseTools/Source/Python/GenFds/GuidSection.py @@ -139,7 +139,7 @@ class GuidSection(GuidSectionClassObject) : # if self.NameGuid is None : GenFdsGlobalVariable.VerboseLogger("Use GenSection function Ge= nerate CRC32 Section") - GenFdsGlobalVariable.GenerateSection(OutputFile, SectFile, Sec= tion.Section.SectionType[self.SectionType], InputAlign=3DSectAlign, IsMakef= ile=3DIsMakefile) + GenFdsGlobalVariable.GenerateSection(OutputFile, SectFile, Sec= tion.SectionType[self.SectionType], InputAlign=3DSectAlign, IsMakefile=3DIs= Makefile) OutputFileList =3D [] OutputFileList.append(OutputFile) return OutputFileList, self.Alignment @@ -243,7 +243,7 @@ class GuidSection(GuidSectionClassObject) : =20 if self.AuthStatusValid in ("TRUE", "1"): Attribute.append('AUTH_STATUS_VALID') - GenFdsGlobalVariable.GenerateSection(OutputFile, [TempFile= ], Section.Section.SectionType['GUIDED'], + GenFdsGlobalVariable.GenerateSection(OutputFile, [TempFile= ], Section.SectionType['GUIDED'], Guid=3Dself.NameGuid,= GuidAttr=3DAttribute, GuidHdrLen=3DHeaderLength) =20 else: @@ -256,14 +256,14 @@ class GuidSection(GuidSectionClassObject) : if self.AuthStatusValid in ("TRUE", "1"): Attribute.append('AUTH_STATUS_VALID') if self.ProcessRequired =3D=3D "NONE" and HeaderLength is = None: - GenFdsGlobalVariable.GenerateSection(OutputFile, [Temp= File], Section.Section.SectionType['GUIDED'], + GenFdsGlobalVariable.GenerateSection(OutputFile, [Temp= File], Section.SectionType['GUIDED'], Guid=3Dself.NameG= uid, GuidAttr=3DAttribute, GuidHdrLen=3DHead= erLength, DummyFile=3DDummyFile, IsMakefile=3DIsMakefile) else: if self.ProcessRequired in ("TRUE", "1"): if 'PROCESSING_REQUIRED' not in Attribute: Attribute.append('PROCESSING_REQUIRED') - GenFdsGlobalVariable.GenerateSection(OutputFile, [Temp= File], Section.Section.SectionType['GUIDED'], + GenFdsGlobalVariable.GenerateSection(OutputFile, [Temp= File], Section.SectionType['GUIDED'], Guid=3Dself.NameG= uid, GuidAttr=3DAttribute, GuidHdrLen=3DHead= erLength, IsMakefile=3DIsMakefile) =20 diff --git a/BaseTools/Source/Python/GenFds/OptRomInfStatement.py b/BaseToo= ls/Source/Python/GenFds/OptRomInfStatement.py index 6179bfa181cb..93c4456eb89f 100644 --- a/BaseTools/Source/Python/GenFds/OptRomInfStatement.py +++ b/BaseTools/Source/Python/GenFds/OptRomInfStatement.py @@ -119,7 +119,7 @@ class OptRomInfStatement (FfsInfStatement): GenSecInputFile =3D self.__ExtendMacro__(Rule.FileName) OutputFileList.append(GenSecInputFile) else: - OutputFileList, IsSect =3D Section.Section.GetFileList(self, '= ', Rule.FileExtension) + OutputFileList, IsSect =3D Section.GetSectionFileList(self, ''= , Rule.FileExtension) =20 return OutputFileList =20 @@ -141,7 +141,7 @@ class OptRomInfStatement (FfsInfStatement): GenSecInputFile =3D self.__ExtendMacro__(Sect.FileName) OutputFileList.append(GenSecInputFile) else: - FileList, IsSect =3D Section.Section.GetFileList(self,= '', Sect.FileExtension) + FileList, IsSect =3D Section.GetSectionFileList(self, = '', Sect.FileExtension) OutputFileList.extend(FileList) =20 =20 return OutputFileList diff --git a/BaseTools/Source/Python/GenFds/Section.py b/BaseTools/Source/P= ython/GenFds/Section.py index 5895998158b6..92d49da333eb 100644 --- a/BaseTools/Source/Python/GenFds/Section.py +++ b/BaseTools/Source/Python/GenFds/Section.py @@ -22,148 +22,107 @@ from Common import EdkLogger from Common.BuildToolError import * from Common.DataType import * =20 -## section base class -# -# -class Section (SectionClassObject): - SectionType =3D { - 'RAW' : 'EFI_SECTION_RAW', - 'FREEFORM' : 'EFI_SECTION_FREEFORM_SUBTYPE_GUID', - BINARY_FILE_TYPE_PE32 : 'EFI_SECTION_PE32', - BINARY_FILE_TYPE_PIC : 'EFI_SECTION_PIC', - BINARY_FILE_TYPE_TE : 'EFI_SECTION_TE', - 'FV_IMAGE' : 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE', - BINARY_FILE_TYPE_DXE_DEPEX : 'EFI_SECTION_DXE_DEPEX', - BINARY_FILE_TYPE_PEI_DEPEX : 'EFI_SECTION_PEI_DEPEX', - 'GUIDED' : 'EFI_SECTION_GUID_DEFINED', - 'COMPRESS' : 'EFI_SECTION_COMPRESSION', - BINARY_FILE_TYPE_UI : 'EFI_SECTION_USER_INTERFACE', - BINARY_FILE_TYPE_SMM_DEPEX : 'EFI_SECTION_SMM_DEPEX' - } - - BinFileType =3D { - BINARY_FILE_TYPE_GUID : '.guid', - 'ACPI' : '.acpi', - 'ASL' : '.asl' , - BINARY_FILE_TYPE_UEFI_APP : '.app', - BINARY_FILE_TYPE_LIB : '.lib', - BINARY_FILE_TYPE_PE32 : '.pe32', - BINARY_FILE_TYPE_PIC : '.pic', - BINARY_FILE_TYPE_PEI_DEPEX : '.depex', - 'SEC_PEI_DEPEX' : '.depex', - BINARY_FILE_TYPE_TE : '.te', - BINARY_FILE_TYPE_UNI_VER : '.ver', - BINARY_FILE_TYPE_VER : '.ver', - BINARY_FILE_TYPE_UNI_UI : '.ui', - BINARY_FILE_TYPE_UI : '.ui', - BINARY_FILE_TYPE_BIN : '.bin', - 'RAW' : '.raw', - 'COMPAT16' : '.comp16', - BINARY_FILE_TYPE_FV : '.fv' - } - - SectFileType =3D { - 'SEC_GUID' : '.sec' , - 'SEC_PE32' : '.sec' , - 'SEC_PIC' : '.sec', - 'SEC_TE' : '.sec', - 'SEC_VER' : '.sec', - 'SEC_UI' : '.sec', - 'SEC_COMPAT16' : '.sec', - 'SEC_BIN' : '.sec' - } +SectionType =3D { + 'RAW' : 'EFI_SECTION_RAW', + 'FREEFORM' : 'EFI_SECTION_FREEFORM_SUBTYPE_GUID', + BINARY_FILE_TYPE_PE32 : 'EFI_SECTION_PE32', + BINARY_FILE_TYPE_PIC : 'EFI_SECTION_PIC', + BINARY_FILE_TYPE_TE : 'EFI_SECTION_TE', + 'FV_IMAGE' : 'EFI_SECTION_FIRMWARE_VOLUME_IMAGE', + BINARY_FILE_TYPE_DXE_DEPEX : 'EFI_SECTION_DXE_DEPEX', + BINARY_FILE_TYPE_PEI_DEPEX : 'EFI_SECTION_PEI_DEPEX', + 'GUIDED' : 'EFI_SECTION_GUID_DEFINED', + 'COMPRESS' : 'EFI_SECTION_COMPRESSION', + BINARY_FILE_TYPE_UI : 'EFI_SECTION_USER_INTERFACE', + BINARY_FILE_TYPE_SMM_DEPEX : 'EFI_SECTION_SMM_DEPEX' +} =20 - ToolGuid =3D { - '0xa31280ad-0x481e-0x41b6-0x95e8-0x127f-0x4c984779' : 'TianoCompre= ss', - '0xee4e5898-0x3914-0x4259-0x9d6e-0xdc7b-0xd79403cf' : 'LzmaCompres= s' - } +BinFileType =3D { + BINARY_FILE_TYPE_GUID : '.guid', + 'ACPI' : '.acpi', + 'ASL' : '.asl' , + BINARY_FILE_TYPE_UEFI_APP : '.app', + BINARY_FILE_TYPE_LIB : '.lib', + BINARY_FILE_TYPE_PE32 : '.pe32', + BINARY_FILE_TYPE_PIC : '.pic', + BINARY_FILE_TYPE_PEI_DEPEX : '.depex', + 'SEC_PEI_DEPEX' : '.depex', + BINARY_FILE_TYPE_TE : '.te', + BINARY_FILE_TYPE_UNI_VER : '.ver', + BINARY_FILE_TYPE_VER : '.ver', + BINARY_FILE_TYPE_UNI_UI : '.ui', + BINARY_FILE_TYPE_UI : '.ui', + BINARY_FILE_TYPE_BIN : '.bin', + 'RAW' : '.raw', + 'COMPAT16' : '.comp16', + BINARY_FILE_TYPE_FV : '.fv' +} =20 - ## The constructor - # - # @param self The object pointer - # - def __init__(self): - SectionClassObject.__init__(self) +SectValidFileType =3D {'SEC_GUID', 'SEC_PE32', 'SEC_PIC', 'SEC_TE', 'SEC_V= ER', 'SEC_UI', 'SEC_COMPAT16', 'SEC_BIN'} =20 - ## GenSection() method - # - # virtual function - # - # @param self The object pointer - # @param OutputPath Where to place output file - # @param ModuleName Which module this section belongs to - # @param SecNum Index of section - # @param KeyStringList Filter for inputs of section generation - # @param FfsInf FfsInfStatement object that contains this sect= ion data - # @param Dict dictionary contains macro and its value - # - def GenSection(self, OutputPath, GuidName, SecNum, keyStringList, FfsI= nf =3D None, Dict =3D {}): - pass - - ## GetFileList() method - # - # Generate compressed section - # - # @param self The object pointer - # @param FfsInf FfsInfStatement object that contains file list - # @param FileType File type to get - # @param FileExtension File extension to get - # @param Dict dictionary contains macro and its value - # @retval tuple (File list, boolean) - # - def GetFileList(FfsInf, FileType, FileExtension, Dict =3D {}, IsMakefi= le=3DFalse): - IsSect =3D FileType in Section.SectFileType +## GetFileList() method +# +# Generate compressed section +# +# @param self The object pointer +# @param FfsInf FfsInfStatement object that contains file list +# @param FileType File type to get +# @param FileExtension File extension to get +# @param Dict dictionary contains macro and its value +# @retval tuple (File list, boolean) +# +def GetSectionFileList(FfsInf, FileType, FileExtension, Dict =3D {}, IsMak= efile=3DFalse): + IsSect =3D FileType in SectValidFileType =20 - if FileExtension is not None: - Suffix =3D FileExtension - elif IsSect : - Suffix =3D Section.SectionType.get(FileType) - else: - Suffix =3D Section.BinFileType.get(FileType) - if FfsInf is None: - EdkLogger.error("GenFds", GENFDS_ERROR, 'Inf File does not exi= st!') + if FileExtension: + Suffix =3D FileExtension + elif IsSect: + Suffix =3D SectionType.get(FileType) + else: + Suffix =3D BinFileType.get(FileType) + if FfsInf is None: + EdkLogger.error("GenFds", GENFDS_ERROR, 'Inf File does not exist!') =20 - FileList =3D [] - if FileType is not None: - for File in FfsInf.BinFileList: - if File.Arch =3D=3D TAB_ARCH_COMMON or FfsInf.CurrentArch = =3D=3D File.Arch: - if File.Type =3D=3D FileType or (int(FfsInf.PiSpecVers= ion, 16) >=3D 0x0001000A \ - and FileType =3D=3D 'DXE_= DPEX' and File.Type =3D=3D BINARY_FILE_TYPE_SMM_DEPEX) \ - or (FileType =3D=3D BINAR= Y_FILE_TYPE_TE and File.Type =3D=3D BINARY_FILE_TYPE_PE32): - if '*' in FfsInf.TargetOverrideList or File.Target= =3D=3D '*' or File.Target in FfsInf.TargetOverrideList or FfsInf.TargetOve= rrideList =3D=3D []: - FileList.append(FfsInf.PatchEfiFile(File.Path,= File.Type)) - else: - GenFdsGlobalVariable.InfLogger ("\nBuild Targe= t \'%s\' of File %s is not in the Scope of %s specified by INF %s in FDF" %= (File.Target, File.File, FfsInf.TargetOverrideList, FfsInf.InfFileName)) + FileList =3D [] + if FileType is not None: + for File in FfsInf.BinFileList: + if File.Arch =3D=3D TAB_ARCH_COMMON or FfsInf.CurrentArch =3D= =3D File.Arch: + if File.Type =3D=3D FileType or (int(FfsInf.PiSpecVersion,= 16) >=3D 0x0001000A \ + and FileType =3D=3D 'DXE_DPEX= ' and File.Type =3D=3D BINARY_FILE_TYPE_SMM_DEPEX) \ + or (FileType =3D=3D BINARY_FI= LE_TYPE_TE and File.Type =3D=3D BINARY_FILE_TYPE_PE32): + if '*' in FfsInf.TargetOverrideList or File.Target =3D= =3D '*' or File.Target in FfsInf.TargetOverrideList or FfsInf.TargetOverrid= eList =3D=3D []: + FileList.append(FfsInf.PatchEfiFile(File.Path, Fil= e.Type)) else: - GenFdsGlobalVariable.VerboseLogger ("\nFile Type \= '%s\' of File %s in %s is not same with file type \'%s\' from Rule in FDF" = %(File.Type, File.File, FfsInf.InfFileName, FileType)) + GenFdsGlobalVariable.InfLogger ("\nBuild Target \'= %s\' of File %s is not in the Scope of %s specified by INF %s in FDF" %(Fil= e.Target, File.File, FfsInf.TargetOverrideList, FfsInf.InfFileName)) else: - GenFdsGlobalVariable.InfLogger ("\nCurrent ARCH \'%s\'= of File %s is not in the Support Arch Scope of %s specified by INF %s in F= DF" %(FfsInf.CurrentArch, File.File, File.Arch, FfsInf.InfFileName)) + GenFdsGlobalVariable.VerboseLogger ("\nFile Type \'%s\= ' of File %s in %s is not same with file type \'%s\' from Rule in FDF" %(Fi= le.Type, File.File, FfsInf.InfFileName, FileType)) + else: + GenFdsGlobalVariable.InfLogger ("\nCurrent ARCH \'%s\' of = File %s is not in the Support Arch Scope of %s specified by INF %s in FDF" = %(FfsInf.CurrentArch, File.File, File.Arch, FfsInf.InfFileName)) =20 - if (not IsMakefile and Suffix is not None and os.path.exists(FfsIn= f.EfiOutputPath)) or (IsMakefile and Suffix is not None): - # - # Get Makefile path and time stamp - # - MakefileDir =3D FfsInf.EfiOutputPath[:-len('OUTPUT')] - Makefile =3D os.path.join(MakefileDir, 'Makefile') - if not os.path.exists(Makefile): - Makefile =3D os.path.join(MakefileDir, 'GNUmakefile') - if os.path.exists(Makefile): - # Update to search files with suffix in all sub-dirs. - Tuple =3D os.walk(FfsInf.EfiOutputPath) - for Dirpath, Dirnames, Filenames in Tuple: - for F in Filenames: - if os.path.splitext(F)[1] =3D=3D Suffix: - FullName =3D os.path.join(Dirpath, F) - if os.path.getmtime(FullName) > os.path.getmti= me(Makefile): - FileList.append(FullName) - if not FileList: - SuffixMap =3D FfsInf.GetFinalTargetSuffixMap() - if Suffix in SuffixMap: - FileList.extend(SuffixMap[Suffix]) - =20 - #Process the file lists is alphabetical for a same section type - if len (FileList) > 1: - FileList.sort() + if (not IsMakefile and Suffix is not None and os.path.exists(FfsInf.Ef= iOutputPath)) or (IsMakefile and Suffix is not None): + # + # Get Makefile path and time stamp + # + MakefileDir =3D FfsInf.EfiOutputPath[:-len('OUTPUT')] + Makefile =3D os.path.join(MakefileDir, 'Makefile') + if not os.path.exists(Makefile): + Makefile =3D os.path.join(MakefileDir, 'GNUmakefile') + if os.path.exists(Makefile): + # Update to search files with suffix in all sub-dirs. + Tuple =3D os.walk(FfsInf.EfiOutputPath) + for Dirpath, Dirnames, Filenames in Tuple: + for F in Filenames: + if os.path.splitext(F)[1] =3D=3D Suffix: + FullName =3D os.path.join(Dirpath, F) + if os.path.getmtime(FullName) > os.path.getmtime(M= akefile): + FileList.append(FullName) + if not FileList: + SuffixMap =3D FfsInf.GetFinalTargetSuffixMap() + if Suffix in SuffixMap: + FileList.extend(SuffixMap[Suffix]) + =20 + #Process the file lists is alphabetical for a same section type + if len (FileList) > 1: + FileList.sort() =20 - return FileList, IsSect - GetFileList =3D staticmethod(GetFileList) + return FileList, IsSect diff --git a/BaseTools/Source/Python/GenFds/UiSection.py b/BaseTools/Source= /Python/GenFds/UiSection.py index fe1e026f5edf..f8b5cdbf7cf9 100644 --- a/BaseTools/Source/Python/GenFds/UiSection.py +++ b/BaseTools/Source/Python/GenFds/UiSection.py @@ -15,7 +15,6 @@ ## # Import Modules # -import Section from Ffs import SectionSuffix import subprocess import Common.LongFilePathOs as os @@ -53,25 +52,22 @@ class UiSection (UiSectionClassObject): # # Prepare the parameter of GenSection # - if FfsInf is not None: + if FfsInf: self.Alignment =3D FfsInf.__ExtendMacro__(self.Alignment) self.StringData =3D FfsInf.__ExtendMacro__(self.StringData) self.FileName =3D FfsInf.__ExtendMacro__(self.FileName) =20 - OutputFile =3D os.path.join(OutputPath, ModuleName + 'SEC' + SecNu= m + SectionSuffix['UI']) + OutputFile =3D os.path.join(OutputPath, ModuleName + TAB_SEC_DIREC= TORY + SecNum + SectionSuffix['UI']) =20 - if self.StringData is not None : + if self.StringData: NameString =3D self.StringData - elif self.FileName is not None: + elif self.FileName: FileNameStr =3D GenFdsGlobalVariable.ReplaceWorkspaceMacro(sel= f.FileName) FileNameStr =3D GenFdsGlobalVariable.MacroExtend(FileNameStr, = Dict) - FileObj =3D open(FileNameStr, 'r') - NameString =3D FileObj.read() - FileObj.close() + with open(FileNameStr, 'r') as FileObj: + NameString =3D FileObj.read() else: NameString =3D '' GenFdsGlobalVariable.GenerateSection(OutputFile, None, 'EFI_SECTIO= N_USER_INTERFACE', Ui=3DNameString, IsMakefile=3DIsMakefile) =20 - OutputFileList =3D [] - OutputFileList.append(OutputFile) - return OutputFileList, self.Alignment + return [OutputFile], self.Alignment diff --git a/BaseTools/Source/Python/GenFds/VerSection.py b/BaseTools/Sourc= e/Python/GenFds/VerSection.py index 1bcdc8110d30..e6e79cff5be3 100644 --- a/BaseTools/Source/Python/GenFds/VerSection.py +++ b/BaseTools/Source/Python/GenFds/VerSection.py @@ -16,13 +16,12 @@ # Import Modules # from Ffs import SectionSuffix -import Section import Common.LongFilePathOs as os import subprocess from GenFdsGlobalVariable import GenFdsGlobalVariable from CommonDataClass.FdfClass import VerSectionClassObject from Common.LongFilePathSupport import OpenLongFilePath as open -from Common.DataType import SUP_MODULE_SEC +from Common.DataType import TAB_SEC_DIRECTORY =20 ## generate version section # @@ -53,31 +52,26 @@ class VerSection (VerSectionClassObject): # # Prepare the parameter of GenSection # - if FfsInf is not None: + if FfsInf: self.Alignment =3D FfsInf.__ExtendMacro__(self.Alignment) self.BuildNum =3D FfsInf.__ExtendMacro__(self.BuildNum) self.StringData =3D FfsInf.__ExtendMacro__(self.StringData) self.FileName =3D FfsInf.__ExtendMacro__(self.FileName) =20 OutputFile =3D os.path.join(OutputPath, - ModuleName + 'SEC' + SecNum + SectionSuf= fix['VERSION']) + ModuleName + TAB_SEC_DIRECTORY + SecNum = + SectionSuffix['VERSION']) OutputFile =3D os.path.normpath(OutputFile) =20 # Get String Data - StringData =3D '' - if self.StringData is not None: + if self.StringData: StringData =3D self.StringData - elif self.FileName is not None: + elif self.FileName: FileNameStr =3D GenFdsGlobalVariable.ReplaceWorkspaceMacro(sel= f.FileName) FileNameStr =3D GenFdsGlobalVariable.MacroExtend(FileNameStr, = Dict) - FileObj =3D open(FileNameStr, 'r') - StringData =3D FileObj.read() - StringData =3D '"' + StringData + '"' - FileObj.close() + with open(FileNameStr, 'r') as FileObj: + StringData =3D '"' + FileObj.read() + '"' else: StringData =3D '' GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_= VERSION', Ver=3DStringData, BuildNumber= =3Dself.BuildNum, IsMakefile=3DIsMakefile) - OutputFileList =3D [] - OutputFileList.append(OutputFile) - return OutputFileList, self.Alignment + return [OutputFile], self.Alignment --=20 2.16.2.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Fri May 3 05:47:03 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 1526321387917415.69147351640595; Mon, 14 May 2018 11:09:47 -0700 (PDT) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 5843621F2E16B; Mon, 14 May 2018 11:09:27 -0700 (PDT) Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 4956821CAD9B2 for ; Mon, 14 May 2018 11:09:25 -0700 (PDT) Received: from orsmga001.jf.intel.com ([10.7.209.18]) by orsmga105.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 14 May 2018 11:09:24 -0700 Received: from jcarsey-desk1.amr.corp.intel.com ([10.7.159.144]) by orsmga001.jf.intel.com with ESMTP; 14 May 2018 11:09:23 -0700 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.100; helo=mga07.intel.com; envelope-from=jaben.carsey@intel.com; receiver=edk2-devel@lists.01.org X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.49,401,1520924400"; d="scan'208";a="55814275" From: Jaben Carsey To: edk2-devel@lists.01.org Date: Mon, 14 May 2018 11:09:16 -0700 Message-Id: <1f4398bc1a9cf10dc4ed62457066fbc1151754b2.1526321052.git.jaben.carsey@intel.com> X-Mailer: git-send-email 2.16.2.windows.1 In-Reply-To: References: In-Reply-To: References: Subject: [edk2] [PATCH v1 07/11] BaseTools: refactor file opening/writing X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.26 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Liming Gao MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" change mode minimal needed permissions change to use with statement Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jaben Carsey --- BaseTools/Source/Python/AutoGen/AutoGen.py | 71 +++++--= ----- BaseTools/Source/Python/AutoGen/GenC.py | 5 +- BaseTools/Source/Python/AutoGen/GenMake.py | 5 +- BaseTools/Source/Python/AutoGen/IdfClassObject.py | 21 ++-- BaseTools/Source/Python/AutoGen/StrGather.py | 18 +-- BaseTools/Source/Python/AutoGen/UniClassObject.py | 5 +- BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py | 5 +- BaseTools/Source/Python/BPDG/GenVpd.py | 30 +++-- BaseTools/Source/Python/Common/Misc.py | 39 +++---- BaseTools/Source/Python/Common/TargetTxtClassObject.py | 13 +-- BaseTools/Source/Python/Common/ToolDefClassObject.py | 4 +- BaseTools/Source/Python/Common/VpdInfoFile.py | 4 +- BaseTools/Source/Python/Ecc/Ecc.py | 4 +- BaseTools/Source/Python/Eot/EotGlobalData.py | 14 +-- BaseTools/Source/Python/Eot/FileProfile.py | 8 +- BaseTools/Source/Python/Eot/Report.py | 6 +- BaseTools/Source/Python/GenFds/Capsule.py | 7 +- BaseTools/Source/Python/GenFds/CapsuleData.py | 10 +- BaseTools/Source/Python/GenFds/FdfParser.py | 20 +--- BaseTools/Source/Python/GenFds/FfsFileStatement.py | 5 +- BaseTools/Source/Python/GenFds/Fv.py | 37 +++--- BaseTools/Source/Python/GenFds/FvImageSection.py | 8 +- BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py | 53 ++++---= -- BaseTools/Source/Python/GenFds/GuidSection.py | 45 ++++---- BaseTools/Source/Python/GenFds/Region.py | 15 +-- BaseTools/Source/Python/GenFds/Vtf.py | 122 +++++++= +++---------- BaseTools/Source/Python/GenPatchPcdTable/GenPatchPcdTable.py | 21 ++-- BaseTools/Source/Python/PatchPcdValue/PatchPcdValue.py | 19 ++- BaseTools/Source/Python/Table/TableReport.py | 47 ++++---- BaseTools/Source/Python/TargetTool/TargetTool.py | 97 +++++++= +-------- BaseTools/Source/Python/Trim/Trim.py | 67 +++++--= ---- BaseTools/Source/Python/Workspace/DscBuildData.py | 17 +-- BaseTools/Source/Python/build/BuildReport.py | 81 +++++++= ------ BaseTools/Source/Python/build/build.py | 106 +++++++= +--------- 34 files changed, 453 insertions(+), 576 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/AutoGen.py b/BaseTools/Source/= Python/AutoGen/AutoGen.py index 619e1e41e32b..009e5c56781d 100644 --- a/BaseTools/Source/Python/AutoGen/AutoGen.py +++ b/BaseTools/Source/Python/AutoGen/AutoGen.py @@ -653,10 +653,8 @@ class WorkspaceAutoGen(AutoGen): for files in AllWorkSpaceMetaFiles: if files.endswith('.dec'): continue - f =3D open(files, 'r') - Content =3D f.read() - f.close() - m.update(Content) + with open(files, 'r') as f: + m.update(f.read()) SaveFileOnChange(os.path.join(self.BuildDir, 'AutoGen.hash'), = m.hexdigest(), True) GlobalData.gPlatformHash =3D m.hexdigest() =20 @@ -664,11 +662,11 @@ class WorkspaceAutoGen(AutoGen): # Write metafile list to build directory # AutoGenFilePath =3D os.path.join(self.BuildDir, 'AutoGen') - if os.path.exists (AutoGenFilePath): - os.remove(AutoGenFilePath) if not os.path.exists(self.BuildDir): os.makedirs(self.BuildDir) - with open(os.path.join(self.BuildDir, 'AutoGen'), 'w+') as file: + elif os.path.exists (AutoGenFilePath): + os.remove(AutoGenFilePath) + with open(AutoGenFilePath, 'w') as file: for f in AllWorkSpaceMetaFiles: print >> file, f return True @@ -679,20 +677,16 @@ class WorkspaceAutoGen(AutoGen): HashFile =3D os.path.join(PkgDir, Pkg.PackageName + '.hash') m =3D hashlib.md5() # Get .dec file's hash value - f =3D open(Pkg.MetaFile.Path, 'r') - Content =3D f.read() - f.close() - m.update(Content) + with open(Pkg.MetaFile.Path, 'r') as f: + m.update(f.read()) # Get include files hash value if Pkg.Includes: for inc in Pkg.Includes: for Root, Dirs, Files in os.walk(str(inc)): for File in Files: File_Path =3D os.path.join(Root, File) - f =3D open(File_Path, 'r') - Content =3D f.read() - f.close() - m.update(Content) + with open(File_Path, 'r') as f: + m.update(f.read()) SaveFileOnChange(HashFile, m.hexdigest(), True) if Pkg.PackageName not in GlobalData.gPackageHash[Pkg.Arch]: GlobalData.gPackageHash[Pkg.Arch][Pkg.PackageName] =3D m.hexdi= gest() @@ -3779,9 +3773,8 @@ class ModuleAutoGen(AutoGen): Vfri =3D os.path.join(self.OutputDir, SrcFile.BaseName + '.i') if not os.path.exists(Vfri): continue - VfriFile =3D open(Vfri, 'r') - Content =3D VfriFile.read() - VfriFile.close() + with open(Vfri, 'r') as VfriFile: + Content =3D VfriFile.read() Pos =3D Content.find('efivarstore') while Pos !=3D -1: # @@ -3850,11 +3843,6 @@ class ModuleAutoGen(AutoGen): OutputName =3D '%sOffset.bin' % self.Name UniVfrOffsetFileName =3D os.path.join( self.OutputDir, OutputN= ame) =20 - try: - fInputfile =3D open(UniVfrOffsetFileName, "wb+", 0) - except: - EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed = for %s" % UniVfrOffsetFileName,None) - # Use a instance of StringIO to cache data fStringIO =3D StringIO('') =20 =20 @@ -3881,17 +3869,19 @@ class ModuleAutoGen(AutoGen): fStringIO.write(''.join(VfrGuid)) =20 VfrValue =3D pack ('Q', int (Item[1], 16)) fStringIO.write (VfrValue) - # - # write data into file. - # - try : =20 - fInputfile.write (fStringIO.getvalue()) + + try: + with open(UniVfrOffsetFileName, "wb", 0) as fInputfile: + # write data into file. + try : + fInputfile.write (fStringIO.getvalue()) + except: + EdkLogger.error("build", FILE_WRITE_FAILURE, "Write da= ta to file %s failed, please check whether the " + "file been locked or using by other ap= plications." %UniVfrOffsetFileName,None) except: - EdkLogger.error("build", FILE_WRITE_FAILURE, "Write data to fi= le %s failed, please check whether the " - "file been locked or using by other applicatio= ns." %UniVfrOffsetFileName,None) + EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed = for %s" % UniVfrOffsetFileName,None) =20 fStringIO.close () - fInputfile.close () return OutputName =20 ## Create AsBuilt INF file the module @@ -4282,9 +4272,8 @@ class ModuleAutoGen(AutoGen): FileDir =3D path.join(GlobalData.gBinCacheSource, self.Arch, self.= SourceDir, self.MetaFile.BaseName) HashFile =3D path.join(FileDir, self.Name + '.hash') if os.path.exists(HashFile): - f =3D open(HashFile, 'r') - CacheHash =3D f.read() - f.close() + with open(HashFile, 'r') as f: + CacheHash =3D f.read() if GlobalData.gModuleHash[self.Arch][self.Name]: if CacheHash =3D=3D GlobalData.gModuleHash[self.Arch][self= .Name]: for root, dir, files in os.walk(FileDir): @@ -4448,17 +4437,13 @@ class ModuleAutoGen(AutoGen): m.update(GlobalData.gModuleHash[self.Arch][Lib.Name]) =20 # Add Module self - f =3D open(str(self.MetaFile), 'r') - Content =3D f.read() - f.close() - m.update(Content) + with open(str(self.MetaFile), 'r') as f: + m.update(f.read()) # Add Module's source files if self.SourceFileList: for File in self.SourceFileList: - f =3D open(str(File), 'r') - Content =3D f.read() - f.close() - m.update(Content) + with open(str(File), 'r') as f: + m.update(f.read()) =20 ModuleHashFile =3D path.join(self.BuildDir, self.Name + ".hash") if self.Name not in GlobalData.gModuleHash[self.Arch]: @@ -4519,7 +4504,7 @@ class ModuleAutoGen(AutoGen): =20 if os.path.exists (self.GetTimeStampPath()): os.remove (self.GetTimeStampPath()) - with open(self.GetTimeStampPath(), 'w+') as file: + with open(self.GetTimeStampPath(), 'w') as file: for f in FileSet: print >> file, f =20 diff --git a/BaseTools/Source/Python/AutoGen/GenC.py b/BaseTools/Source/Pyt= hon/AutoGen/GenC.py index 40a343ca1057..46c7c1c1390b 100644 --- a/BaseTools/Source/Python/AutoGen/GenC.py +++ b/BaseTools/Source/Python/AutoGen/GenC.py @@ -1814,9 +1814,8 @@ def CreateIdfFileCode(Info, AutoGenC, StringH, IdfGen= CFlag, IdfGenBinBuffer): Index +=3D 1 continue =20 - TmpFile =3D open(File.Path, 'rb') - Buffer =3D TmpFile.read() - TmpFile.close() + with open(File.Path, 'rb') as f: + Buffer =3D f.read() if File.Ext.upper() =3D=3D '.PNG': TempBuffer =3D pack('B', EFI_HII_IIBT_IMAG= E_PNG) TempBuffer +=3D pack('I', len(Buffer)) diff --git a/BaseTools/Source/Python/AutoGen/GenMake.py b/BaseTools/Source/= Python/AutoGen/GenMake.py index d70c5c26ffc8..30280d449f62 100644 --- a/BaseTools/Source/Python/AutoGen/GenMake.py +++ b/BaseTools/Source/Python/AutoGen/GenMake.py @@ -1026,12 +1026,11 @@ cleanlib: CurrentFileDependencyList =3D DepDb[F] else: try: - Fd =3D open(F.Path, 'r') + with open(F.Path, 'r') as f: + FileContent =3D f.read() except BaseException, X: EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData= =3DF.Path + "\n\t" + str(X)) =20 - FileContent =3D Fd.read() - Fd.close() if len(FileContent) =3D=3D 0: continue =20 diff --git a/BaseTools/Source/Python/AutoGen/IdfClassObject.py b/BaseTools/= Source/Python/AutoGen/IdfClassObject.py index 769790d965b5..8b84806f9f36 100644 --- a/BaseTools/Source/Python/AutoGen/IdfClassObject.py +++ b/BaseTools/Source/Python/AutoGen/IdfClassObject.py @@ -1,7 +1,7 @@ ## @file # This file is used to collect all defined strings in Image Definition fil= es # -# Copyright (c) 2016, Intel Corporation. All rights reserved.
+# Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
# This program and the accompanying materials # are licensed and made available under the terms and conditions of the BS= D License # which accompanies this distribution. The full text of the license may b= e found at @@ -69,13 +69,12 @@ class IdfFileClassObject(object): self.ImageFilesDict =3D {} self.ImageIDList =3D [] for File in FileList: - if File is None: + if not File: EdkLogger.error("Image Definition File Parser", PARSER_ERR= OR, 'No Image definition file is given.') =20 try: - IdfFile =3D open(LongFilePath(File.Path), mode=3D'r') - FileIn =3D IdfFile.read() - IdfFile.close() + with open(LongFilePath(File.Path), mode=3D'r') as f: + FileIn =3D f.read() except: EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=3DFi= le) =20 @@ -118,12 +117,12 @@ def SearchImageID(ImageFileObject, FileList): =20 for File in FileList: if os.path.isfile(File): - Lines =3D open(File, 'r') - for Line in Lines: - ImageIdList =3D IMAGE_TOKEN.findall(Line) - for ID in ImageIdList: - EdkLogger.debug(EdkLogger.DEBUG_5, "Found ImageID iden= tifier: " + ID) - ImageFileObject.SetImageIDReferenced(ID) + with open(File, 'r') as f: + for Line in f: + ImageIdList =3D IMAGE_TOKEN.findall(Line) + for ID in ImageIdList: + EdkLogger.debug(EdkLogger.DEBUG_5, "Found ImageID = identifier: " + ID) + ImageFileObject.SetImageIDReferenced(ID) =20 class ImageFileObject(object): def __init__(self, FileName, ImageID, TransParent =3D False): diff --git a/BaseTools/Source/Python/AutoGen/StrGather.py b/BaseTools/Sourc= e/Python/AutoGen/StrGather.py index e5e4f25efd5d..c0a39e4a12f1 100644 --- a/BaseTools/Source/Python/AutoGen/StrGather.py +++ b/BaseTools/Source/Python/AutoGen/StrGather.py @@ -529,11 +529,11 @@ def SearchString(UniObjectClass, FileList, IsCompatib= leMode): =20 for File in FileList: if os.path.isfile(File): - Lines =3D open(File, 'r') - for Line in Lines: - for StrName in STRING_TOKEN.findall(Line): - EdkLogger.debug(EdkLogger.DEBUG_5, "Found string ident= ifier: " + StrName) - UniObjectClass.SetStringReferenced(StrName) + with open(File, 'r') as f: + for Line in f: + for StrName in STRING_TOKEN.findall(Line): + EdkLogger.debug(EdkLogger.DEBUG_5, "Found string i= dentifier: " + StrName) + UniObjectClass.SetStringReferenced(StrName) =20 UniObjectClass.ReToken() =20 @@ -603,9 +603,9 @@ if __name__ =3D=3D '__main__': SkipList =3D ['.inf', '.uni'] BaseName =3D 'DriverSample' (h, c) =3D GetStringFiles(UniFileList, SrcFileList, IncludeList, SkipL= ist, BaseName, True) - hfile =3D open('unistring.h', 'w') - cfile =3D open('unistring.c', 'w') - hfile.write(h) - cfile.write(c) + with open('unistring.h', 'w') as f: + f.write(h) + with open('unistring.c', 'w') as f: + f.write(c) =20 EdkLogger.info('end') diff --git a/BaseTools/Source/Python/AutoGen/UniClassObject.py b/BaseTools/= Source/Python/AutoGen/UniClassObject.py index 54b6fb22a08a..bb37fbfd6a0c 100644 --- a/BaseTools/Source/Python/AutoGen/UniClassObject.py +++ b/BaseTools/Source/Python/AutoGen/UniClassObject.py @@ -303,9 +303,8 @@ class UniFileClassObject(object): # Read file # try: - UniFile =3D open(FileName, mode=3D'rb') - FileIn =3D UniFile.read() - UniFile.close() + with open(FileName, mode=3D'rb') as f: + FileIn =3D f.read() except: EdkLogger.Error("build", FILE_OPEN_FAILURE, ExtraData=3DFile) =20 diff --git a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py b/B= aseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py index 3b54865000bf..2c6bb8e396a9 100644 --- a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py +++ b/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py @@ -165,9 +165,8 @@ class VAR_CHECK_PCD_VARIABLE_TAB_CONTAINER(object): =20 DbFile =3D StringIO() if Phase =3D=3D 'DXE' and os.path.exists(BinFilePath): - BinFile =3D open(BinFilePath, "rb") - BinBuffer =3D BinFile.read() - BinFile.close() + with open(BinFilePath, "rb") as f: + BinBuffer =3D f.read() BinBufferSize =3D len(BinBuffer) if (BinBufferSize % 4): for i in range(4 - (BinBufferSize % 4)): diff --git a/BaseTools/Source/Python/BPDG/GenVpd.py b/BaseTools/Source/Pyth= on/BPDG/GenVpd.py index 4fa12b7d59de..dba815415f92 100644 --- a/BaseTools/Source/Python/BPDG/GenVpd.py +++ b/BaseTools/Source/Python/BPDG/GenVpd.py @@ -323,13 +323,11 @@ class GenVPD : self.PcdFixedOffsetSizeList =3D [] self.PcdUnknownOffsetList =3D [] try: - fInputfile =3D open(InputFileName, "r", 0) - try: - self.FileLinesList =3D fInputfile.readlines() - except: - EdkLogger.error("BPDG", BuildToolError.FILE_READ_FAILURE, = "File read failed for %s" % InputFileName, None) - finally: - fInputfile.close() + with open(InputFileName, "r", 0) as f: + try: + self.FileLinesList =3D f.readlines() + except: + EdkLogger.error("BPDG", BuildToolError.FILE_READ_FAILU= RE, "File read failed for %s" % InputFileName, None) except: EdkLogger.error("BPDG", BuildToolError.FILE_OPEN_FAILURE, "Fil= e open failed for %s" % InputFileName, None) =20 @@ -661,12 +659,6 @@ class GenVPD : def GenerateVpdFile (self, MapFileName, BinFileName): #Open an VPD file to process =20 - try: - fVpdFile =3D open(BinFileName, "wb", 0) - except: - # Open failed - EdkLogger.error("BPDG", BuildToolError.FILE_OPEN_FAILURE, "Fil= e open failed for %s" % self.VpdFileName, None) - try : fMapFile =3D open(MapFileName, "w", 0) except: @@ -697,12 +689,16 @@ class GenVPD : else: fStringIO.write (eachPcd.PcdValue) =20 - try : - fVpdFile.write (fStringIO.getvalue()) + try: + with open(BinFileName, "wb", 0) as fVpdFile: + try : + fVpdFile.write (fStringIO.getvalue()) + except: + EdkLogger.error("BPDG", BuildToolError.FILE_WRITE_FAIL= URE, "Write data to file %s failed, please check whether the file been lock= ed or using by other applications." % self.VpdFileName, None) except: - EdkLogger.error("BPDG", BuildToolError.FILE_WRITE_FAILURE, "Wr= ite data to file %s failed, please check whether the file been locked or us= ing by other applications." % self.VpdFileName, None) + # Open failed + EdkLogger.error("BPDG", BuildToolError.FILE_OPEN_FAILURE, "Fil= e open failed for %s" % self.VpdFileName, None) =20 fStringIO.close () - fVpdFile.close () fMapFile.close () =20 diff --git a/BaseTools/Source/Python/Common/Misc.py b/BaseTools/Source/Pyth= on/Common/Misc.py index 17907a318944..0bfb26548d9b 100644 --- a/BaseTools/Source/Python/Common/Misc.py +++ b/BaseTools/Source/Python/Common/Misc.py @@ -63,15 +63,14 @@ def GetVariableOffset(mapfilepath, efifilepath, varname= s): =20 @return List whos elements are tuple with variable name and raw offset """ - lines =3D [] try: - f =3D open(mapfilepath, 'r') - lines =3D f.readlines() - f.close() + with open(mapfilepath, 'r') as f: + lines =3D f.readlines() except: return None =20 - if len(lines) =3D=3D 0: return None + if len(lines) =3D=3D 0:=20 + return None firstline =3D lines[0].strip() if (firstline.startswith("Archive member included ") and firstline.endswith(" file (symbol)")): @@ -471,13 +470,11 @@ def SaveFileOnChange(File, Content, IsBinaryFile=3DTr= ue): if not SaveFileToDisk(File, Content): EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData= =3DFile) except: - Fd =3D open(File, "wb") + with open(File, "wb") as Fd: + Fd.write(Content) + else: + with open(File, "wb") as Fd: Fd.write(Content) - Fd.close() - else: - Fd =3D open(File, "wb") - Fd.write(Content) - Fd.close() except IOError, X: EdkLogger.error(None, FILE_CREATE_FAILURE, ExtraData=3D'IOError %s= ' % X) =20 @@ -489,15 +486,11 @@ def SaveFileOnChange(File, Content, IsBinaryFile=3DTr= ue): # @param File The path of file to store the object # def DataDump(Data, File): - Fd =3D None try: - Fd =3D open(File, 'wb') - cPickle.dump(Data, Fd, cPickle.HIGHEST_PROTOCOL) + with open(File, 'wb') as Fd: + cPickle.dump(Data, Fd, cPickle.HIGHEST_PROTOCOL) except: EdkLogger.error("", FILE_OPEN_FAILURE, ExtraData=3DFile, RaiseErro= r=3DFalse) - finally: - if Fd is not None: - Fd.close() =20 ## Restore a Python object from a file # @@ -507,18 +500,12 @@ def DataDump(Data, File): # @retval None If failure in file operation # def DataRestore(File): - Data =3D None - Fd =3D None try: - Fd =3D open(File, 'rb') - Data =3D cPickle.load(Fd) + with open(File, 'rb') as Fd: + return cPickle.load(Fd) except Exception, e: EdkLogger.verbose("Failed to load [%s]\n\t%s" % (File, str(e))) - Data =3D None - finally: - if Fd is not None: - Fd.close() - return Data + return None =20 ## Retrieve and cache the real path name in file system # diff --git a/BaseTools/Source/Python/Common/TargetTxtClassObject.py b/BaseT= ools/Source/Python/Common/TargetTxtClassObject.py index f8459c892e36..6f5e5f0d173d 100644 --- a/BaseTools/Source/Python/Common/TargetTxtClassObject.py +++ b/BaseTools/Source/Python/Common/TargetTxtClassObject.py @@ -77,16 +77,14 @@ class TargetTxtClassObject(object): # @retval 1 Open file failed # def ConvertTextFileToDict(self, FileName, CommentCharacter, KeySplitCh= aracter): - F =3D None + self.ConfDirectoryPath =3D os.path.dirname(FileName) try: - F =3D open(FileName, 'r') - self.ConfDirectoryPath =3D os.path.dirname(FileName) + with open(FileName, 'r') as F: + Lines =3D F.readlines() except: EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=3DFileNa= me) - if F is not None: - F.close() =20 - for Line in F: + for Line in Lines: Line =3D Line.strip() if Line.startswith(CommentCharacter) or Line =3D=3D '': continue @@ -131,10 +129,7 @@ class TargetTxtClassObject(object): EdkLogger.error("build", FORMAT_INVALID, "Invalid numb= er of [%s]: %s." % (Key, Value), File=3DFileName) self.TargetTxtDictionary[Key] =3D Value - #elif Key not in GlobalData.gGlobalDefines: - # GlobalData.gGlobalDefines[Key] =3D Value =20 - F.close() return 0 =20 ## TargetTxtDict diff --git a/BaseTools/Source/Python/Common/ToolDefClassObject.py b/BaseToo= ls/Source/Python/Common/ToolDefClassObject.py index 83359586b994..d464330d9f98 100644 --- a/BaseTools/Source/Python/Common/ToolDefClassObject.py +++ b/BaseTools/Source/Python/Common/ToolDefClassObject.py @@ -117,8 +117,8 @@ class ToolDefClassObject(object): FileContent =3D [] if os.path.isfile(FileName): try: - F =3D open(FileName, 'r') - FileContent =3D F.readlines() + with open(FileName, 'r') as F: + FileContent =3D F.readlines() except: EdkLogger.error("tools_def.txt parser", FILE_OPEN_FAILURE,= ExtraData=3DFileName) else: diff --git a/BaseTools/Source/Python/Common/VpdInfoFile.py b/BaseTools/Sour= ce/Python/Common/VpdInfoFile.py index 32895deb5d0c..7d76f04d6c31 100644 --- a/BaseTools/Source/Python/Common/VpdInfoFile.py +++ b/BaseTools/Source/Python/Common/VpdInfoFile.py @@ -153,12 +153,12 @@ class VpdInfoFile: # @param FilePath The full path string for existing VPD PCD info file. def Read(self, FilePath): try: - fd =3D open(FilePath, "r") + with open(FilePath, "r") as fd: + Lines =3D fd.readlines() except: EdkLogger.error("VpdInfoFile",=20 BuildToolError.FILE_OPEN_FAILURE,=20 "Fail to open file %s for written." % FilePath) - Lines =3D fd.readlines() for Line in Lines: Line =3D Line.strip() if len(Line) =3D=3D 0 or Line.startswith("#"): diff --git a/BaseTools/Source/Python/Ecc/Ecc.py b/BaseTools/Source/Python/E= cc/Ecc.py index 60dfc00260f1..554e29e6e0f8 100644 --- a/BaseTools/Source/Python/Ecc/Ecc.py +++ b/BaseTools/Source/Python/Ecc/Ecc.py @@ -1,7 +1,7 @@ ## @file # This file is used to be the main entrance of ECC tool # -# Copyright (c) 2009 - 2016, Intel Corporation. All rights reserved.
+# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
# This program and the accompanying materials # are licensed and made available under the terms and conditions of the BS= D License # which accompanies this distribution. The full text of the license may b= e found at @@ -201,7 +201,7 @@ class Ecc(object): for specificDir in SpecificDirs: =20 ScanFolders.append(os.path.join(EccGlobalData.gTarget, spe= cificDir)) EdkLogger.quiet("Building database for meta data files ...") - Op =3D open(EccGlobalData.gConfig.MetaDataFileCheckPathOfGenerateF= ileList, 'w+') + Op =3D open(EccGlobalData.gConfig.MetaDataFileCheckPathOfGenerateF= ileList, 'w') #SkipDirs =3D Read from config file SkipDirs =3D EccGlobalData.gConfig.SkipDirList SkipDirString =3D string.join(SkipDirs, '|') diff --git a/BaseTools/Source/Python/Eot/EotGlobalData.py b/BaseTools/Sourc= e/Python/Eot/EotGlobalData.py index a9f51189c1eb..1b561a70e805 100644 --- a/BaseTools/Source/Python/Eot/EotGlobalData.py +++ b/BaseTools/Source/Python/Eot/EotGlobalData.py @@ -1,7 +1,7 @@ ## @file # This file is used to save global datas # -# Copyright (c) 2008 - 2014, Intel Corporation. All rights reserved.
+# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.
# This program and the accompanying materials # are licensed and made available under the terms and conditions of the BS= D License # which accompanies this distribution. The full text of the license may b= e found at @@ -38,27 +38,27 @@ gMACRO['CAPSULE_INF'] =3D '' =20 # Log file for unmatched variables gUN_MATCHED_LOG =3D 'Log_UnMatched.log' -gOP_UN_MATCHED =3D open(gUN_MATCHED_LOG, 'w+') +gOP_UN_MATCHED =3D open(gUN_MATCHED_LOG, 'w') =20 # Log file for all INF files gINF_FILES =3D 'Log_Inf_File.log' -gOP_INF =3D open(gINF_FILES, 'w+') +gOP_INF =3D open(gINF_FILES, 'w') =20 # Log file for not dispatched PEIM/DRIVER gUN_DISPATCHED_LOG =3D 'Log_UnDispatched.log' -gOP_UN_DISPATCHED =3D open(gUN_DISPATCHED_LOG, 'w+') +gOP_UN_DISPATCHED =3D open(gUN_DISPATCHED_LOG, 'w') =20 # Log file for unmatched variables in function calling gUN_MATCHED_IN_LIBRARY_CALLING_LOG =3D 'Log_UnMatchedInLibraryCalling.log' -gOP_UN_MATCHED_IN_LIBRARY_CALLING =3D open(gUN_MATCHED_IN_LIBRARY_CALLING_= LOG, 'w+') +gOP_UN_MATCHED_IN_LIBRARY_CALLING =3D open(gUN_MATCHED_IN_LIBRARY_CALLING_= LOG, 'w') =20 # Log file for order of dispatched PEIM/DRIVER gDISPATCH_ORDER_LOG =3D 'Log_DispatchOrder.log' -gOP_DISPATCH_ORDER =3D open(gDISPATCH_ORDER_LOG, 'w+') +gOP_DISPATCH_ORDER =3D open(gDISPATCH_ORDER_LOG, 'w') =20 # Log file for found source files gSOURCE_FILES =3D 'Log_SourceFiles.log' -gOP_SOURCE_FILES =3D open(gSOURCE_FILES, 'w+') +gOP_SOURCE_FILES =3D open(gSOURCE_FILES, 'w') =20 # Dict for GUID found in DEC files gGuidDict =3D dict() diff --git a/BaseTools/Source/Python/Eot/FileProfile.py b/BaseTools/Source/= Python/Eot/FileProfile.py index 0544c0d55b44..bf6a4c054baa 100644 --- a/BaseTools/Source/Python/Eot/FileProfile.py +++ b/BaseTools/Source/Python/Eot/FileProfile.py @@ -1,7 +1,7 @@ ## @file # fragments of source file # -# Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.
+# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# # This program and the accompanying materials # are licensed and made available under the terms and conditions of the B= SD License @@ -49,11 +49,7 @@ class FileProfile : self.FileLinesList =3D [] self.FileLinesListFromFile =3D [] try: - fsock =3D open(FileName, "rb", 0) - try: + with open(FileName, "rb", 0) as fsock: self.FileLinesListFromFile =3D fsock.readlines() - finally: - fsock.close() - except IOError: raise Warning("Error when opening file %s" % FileName) diff --git a/BaseTools/Source/Python/Eot/Report.py b/BaseTools/Source/Pytho= n/Eot/Report.py index 7435b4d7c930..99b8b152180a 100644 --- a/BaseTools/Source/Python/Eot/Report.py +++ b/BaseTools/Source/Python/Eot/Report.py @@ -1,7 +1,7 @@ ## @file # This file is used to create report for Eot tool # -# Copyright (c) 2008 - 2014, Intel Corporation. All rights reserved.
+# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.
# This program and the accompanying materials # are licensed and made available under the terms and conditions of the BS= D License # which accompanies this distribution. The full text of the license may b= e found at @@ -33,10 +33,10 @@ class Report(object): # def __init__(self, ReportName =3D 'Report.html', FvObj =3D None, Dispa= tchName=3DNone): self.ReportName =3D ReportName - self.Op =3D open(ReportName, 'w+') + self.Op =3D open(ReportName, 'w') self.DispatchList =3D None if DispatchName: - self.DispatchList =3D open(DispatchName, 'w+') + self.DispatchList =3D open(DispatchName, 'w') self.FvObj =3D FvObj self.FfsIndex =3D 0 self.PpiIndex =3D 0 diff --git a/BaseTools/Source/Python/GenFds/Capsule.py b/BaseTools/Source/P= ython/GenFds/Capsule.py index fbd48f3c6d76..6aae2fcb7d97 100644 --- a/BaseTools/Source/Python/GenFds/Capsule.py +++ b/BaseTools/Source/Python/GenFds/Capsule.py @@ -137,9 +137,8 @@ class Capsule (CapsuleClassObject) : FileName =3D driver.GenCapsuleSubItem() FwMgrHdr.write(pack('=3DQ', PreSize)) PreSize +=3D os.path.getsize(FileName) - File =3D open(FileName, 'rb') - Content.write(File.read()) - File.close() + with open(FileName, 'rb') as File: + Content.write(File.read()) for fmp in self.FmpPayloadList: if fmp.Existed: FwMgrHdr.write(pack('=3DQ', PreSize)) @@ -247,7 +246,7 @@ class Capsule (CapsuleClassObject) : def GenCapInf(self): self.CapInfFileName =3D os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName + "_Cap" + '.inf') - CapInfFile =3D StringIO.StringIO() #open (self.CapInfFileName , 'w= +') + CapInfFile =3D StringIO.StringIO() =20 CapInfFile.writelines("[options]" + T_CHAR_LF) =20 diff --git a/BaseTools/Source/Python/GenFds/CapsuleData.py b/BaseTools/Sour= ce/Python/GenFds/CapsuleData.py index dd4c27bd15c7..9916bd4d2627 100644 --- a/BaseTools/Source/Python/GenFds/CapsuleData.py +++ b/BaseTools/Source/Python/GenFds/CapsuleData.py @@ -233,12 +233,10 @@ class CapsulePayload(CapsuleData): # # Append file content to the structure # - ImageFile =3D open(self.ImageFile, 'rb') - Buffer +=3D ImageFile.read() - ImageFile.close() + with open(self.ImageFile, 'rb') as ImageFile: + Buffer +=3D ImageFile.read() if self.VendorCodeFile: - VendorFile =3D open(self.VendorCodeFile, 'rb') - Buffer +=3D VendorFile.read() - VendorFile.close() + with open(self.VendorCodeFile, 'rb') as VendorFile: + Buffer +=3D VendorFile.read() self.Existed =3D True return Buffer diff --git a/BaseTools/Source/Python/GenFds/FdfParser.py b/BaseTools/Source= /Python/GenFds/FdfParser.py index 2439d8ab9455..8d1a4b543f0e 100644 --- a/BaseTools/Source/Python/GenFds/FdfParser.py +++ b/BaseTools/Source/Python/GenFds/FdfParser.py @@ -155,16 +155,11 @@ class IncludeFileProfile : self.FileName =3D FileName self.FileLinesList =3D [] try: - fsock =3D open(FileName, "rb", 0) - try: + with open(FileName, "rb", 0) as fsock: self.FileLinesList =3D fsock.readlines() - for index, line in enumerate(self.FileLinesList): - if not line.endswith('\n'): - self.FileLinesList[index] +=3D '\n' - - finally: - fsock.close() - + for index, line in enumerate(self.FileLinesList): + if not line.endswith('\n'): + self.FileLinesList[index] +=3D '\n' except: EdkLogger.error("FdfParser", FILE_OPEN_FAILURE, ExtraData=3DFi= leName) =20 @@ -216,16 +211,11 @@ class FileProfile : def __init__(self, FileName): self.FileLinesList =3D [] try: - fsock =3D open(FileName, "rb", 0) - try: + with open(FileName, "rb", 0) as fsock: self.FileLinesList =3D fsock.readlines() - finally: - fsock.close() - except: EdkLogger.error("FdfParser", FILE_OPEN_FAILURE, ExtraData=3DFi= leName) =20 - self.PcdDict =3D {} self.InfList =3D [] self.InfDict =3D {'ArchTBD':[]} diff --git a/BaseTools/Source/Python/GenFds/FfsFileStatement.py b/BaseTools= /Source/Python/GenFds/FfsFileStatement.py index 871499d3d2ad..1449d363eac3 100644 --- a/BaseTools/Source/Python/GenFds/FfsFileStatement.py +++ b/BaseTools/Source/Python/GenFds/FfsFileStatement.py @@ -104,11 +104,10 @@ class FileStatement (FileStatementClassObject) : MaxAlignValue =3D 1 for Index, File in enumerate(self.FileName): try: - f =3D open(File, 'rb') + with open(File, 'rb') as f: + Content =3D f.read() except: GenFdsGlobalVariable.ErrorLogger("Error openin= g RAW file %s." % (File)) - Content =3D f.read() - f.close() AlignValue =3D 1 if self.SubAlignment[Index] is not None: AlignValue =3D GenFdsGlobalVariable.GetAlignme= nt(self.SubAlignment[Index]) diff --git a/BaseTools/Source/Python/GenFds/Fv.py b/BaseTools/Source/Python= /GenFds/Fv.py index 29daba5a3a3e..d4b0611fc55a 100644 --- a/BaseTools/Source/Python/GenFds/Fv.py +++ b/BaseTools/Source/Python/GenFds/Fv.py @@ -163,8 +163,8 @@ class FV (FvClassObject): NewFvInfo =3D open(FvInfoFileName, 'r').read() if NewFvInfo is not None and NewFvInfo !=3D OrigFvInfo: FvChildAddr =3D [] - AddFileObj =3D open(FvInfoFileName, 'r') - AddrStrings =3D AddFileObj.readlines() + with open(FvInfoFileName, 'r') as AddFileObj: + AddrStrings =3D AddFileObj.readlines() AddrKeyFound =3D False for AddrString in AddrStrings: if AddrKeyFound: @@ -172,7 +172,6 @@ class FV (FvClassObject): FvChildAddr.append (AddrString) elif AddrString.find ("[FV_BASE_ADDRESS]") !=3D -1: AddrKeyFound =3D True - AddFileObj.close() =20 if FvChildAddr !=3D []: # Update Ffs again @@ -195,14 +194,14 @@ class FV (FvClassObject): # Write the Fv contents to Buffer # if os.path.isfile(FvOutputFile): - FvFileObj =3D open(FvOutputFile, 'rb') + with open(FvOutputFile, 'rb') as FvFileObj: + Buffer.write(FvFileObj.read()) + FvFileObj.seek(0) + # PI FvHeader is 0x48 byte + FvHeaderBuffer =3D FvFileObj.read(0x48) + GenFdsGlobalVariable.VerboseLogger("\nGenerate %s FV Succe= ssfully" % self.UiFvName) GenFdsGlobalVariable.SharpCounter =3D 0 - - Buffer.write(FvFileObj.read()) - FvFileObj.seek(0) - # PI FvHeader is 0x48 byte - FvHeaderBuffer =3D FvFileObj.read(0x48) # FV alignment position. FvAlignmentValue =3D 1 << (ord(FvHeaderBuffer[0x2E]) & 0x1= F) if FvAlignmentValue >=3D 0x400: @@ -217,7 +216,6 @@ class FV (FvClassObject): else: # FvAlignmentValue is less than 1K self.FvAlignment =3D str (FvAlignmentValue) - FvFileObj.close() GenFds.ImageBinDict[self.UiFvName.upper() + 'fv'] =3D FvOu= tputFile GenFdsGlobalVariable.LargeFileInFvFlags.pop() else: @@ -378,16 +376,15 @@ class FV (FvClassObject): # check if the file path exists or not if not os.path.isfile(FileFullPath): GenFdsGlobalVariable.ErrorLogger("Error opening FV= Extension Header Entry file %s." % (self.FvExtEntryData[Index])) - FvExtFile =3D open (FileFullPath,'rb') - FvExtFile.seek(0,2) - Size =3D FvExtFile.tell() - if Size >=3D 0x10000: - GenFdsGlobalVariable.ErrorLogger("The size of FV E= xtension Header Entry file %s exceeds 0x10000." % (self.FvExtEntryData[Inde= x])) - TotalSize +=3D (Size + 4) - FvExtFile.seek(0) - Buffer +=3D pack('HH', (Size + 4), int(self.FvExtEntry= TypeValue[Index], 16)) - Buffer +=3D FvExtFile.read()=20 - FvExtFile.close() + with open (FileFullPath,'rb') as FvExtFile: + FvExtFile.seek(0,2) + Size =3D FvExtFile.tell() + if Size >=3D 0x10000: + GenFdsGlobalVariable.ErrorLogger("The size of = FV Extension Header Entry file %s exceeds 0x10000." % (self.FvExtEntryData[= Index])) + TotalSize +=3D (Size + 4) + FvExtFile.seek(0) + Buffer +=3D pack('HH', (Size + 4), int(self.FvExtE= ntryTypeValue[Index], 16)) + Buffer +=3D FvExtFile.read() if self.FvExtEntryType[Index] =3D=3D 'DATA': ByteList =3D self.FvExtEntryData[Index].split(',') Size =3D len (ByteList) diff --git a/BaseTools/Source/Python/GenFds/FvImageSection.py b/BaseTools/S= ource/Python/GenFds/FvImageSection.py index dc5dcb7f8e0d..9f808480e787 100644 --- a/BaseTools/Source/Python/GenFds/FvImageSection.py +++ b/BaseTools/Source/Python/GenFds/FvImageSection.py @@ -64,8 +64,8 @@ class FvImageSection(FvImageSectionClassObject): FvAlignmentValue =3D 0 if os.path.isfile(FvFileName): with open (FvFileName,'rb') as FvFileObj: - # PI FvHeader is 0x48 byte - FvHeaderBuffer =3D FvFileObj.read(0x48) + # PI FvHeader is 0x48 byte + FvHeaderBuffer =3D FvFileObj.read(0x48) # FV alignment position. FvAlignmentValue =3D 1 << (ord (FvHeaderBuffer[0x2E]) = & 0x1F) if FvAlignmentValue > MaxFvAlignment: @@ -110,8 +110,8 @@ class FvImageSection(FvImageSectionClassObject): FvFileName =3D GenFdsGlobalVariable.ReplaceWorkspaceMa= cro(self.FvFileName) if os.path.isfile(FvFileName): with open (FvFileName,'rb') as FvFileObj: - # PI FvHeader is 0x48 byte - FvHeaderBuffer =3D FvFileObj.read(0x48) + # PI FvHeader is 0x48 byte + FvHeaderBuffer =3D FvFileObj.read(0x48) # FV alignment position. FvAlignmentValue =3D 1 << (ord (FvHeaderBuffer[0x2= E]) & 0x1F) # FvAlignmentValue is larger than or equal to 1K diff --git a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py b/BaseT= ools/Source/Python/GenFds/GenFdsGlobalVariable.py index 6cf82526efd2..8537800bc2b2 100644 --- a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py +++ b/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py @@ -300,31 +300,27 @@ class GenFdsGlobalVariable: # Create FV Address inf file # GenFdsGlobalVariable.FvAddressFileName =3D os.path.join(GenFdsGlob= alVariable.FfsDir, 'FvAddress.inf') - FvAddressFile =3D open(GenFdsGlobalVariable.FvAddressFileName, 'w') - # - # Add [Options] - # - FvAddressFile.writelines("[options]" + T_CHAR_LF) BsAddress =3D '0' for Arch in ArchList: if GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVari= able.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVar= iable.ToolChainTag].BsBaseAddress: BsAddress =3D GenFdsGlobalVariable.WorkSpace.BuildObject[G= enFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, = GenFdsGlobalVariable.ToolChainTag].BsBaseAddress break - - FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS =3D " + \ - BsAddress + \ - T_CHAR_LF) - RtAddress =3D '0' for Arch in ArchList: if GenFdsGlobalVariable.WorkSpace.BuildObject[GenFdsGlobalVari= able.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVar= iable.ToolChainTag].RtBaseAddress: RtAddress =3D GenFdsGlobalVariable.WorkSpace.BuildObject[G= enFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, = GenFdsGlobalVariable.ToolChainTag].RtBaseAddress + with open(GenFdsGlobalVariable.FvAddressFileName, 'w') as FvAddres= sFile: + # + # Add [Options] + # + FvAddressFile.writelines("[options]" + T_CHAR_LF) + FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS =3D " += \ + BsAddress + \ + T_CHAR_LF) + FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS =3D = " + \ + RtAddress + \ + T_CHAR_LF) =20 - FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS =3D " + \ - RtAddress + \ - T_CHAR_LF) - - FvAddressFile.close() =20 def SetEnv(FdfParser, WorkSpace, ArchList, GlobalData): GenFdsGlobalVariable.ModuleFile =3D WorkSpace.ModuleFile @@ -361,11 +357,6 @@ class GenFdsGlobalVariable: # Create FV Address inf file # GenFdsGlobalVariable.FvAddressFileName =3D os.path.join(GenFdsGlob= alVariable.FfsDir, 'FvAddress.inf') - FvAddressFile =3D open(GenFdsGlobalVariable.FvAddressFileName, 'w') - # - # Add [Options] - # - FvAddressFile.writelines("[options]" + T_CHAR_LF) BsAddress =3D '0' for Arch in ArchList: BsAddress =3D GenFdsGlobalVariable.WorkSpace.BuildObject[GenFd= sGlobalVariable.ActivePlatform, Arch, @@ -373,11 +364,6 @@ class GenFdsGlobalVariable: GlobalD= ata.gGlobalDefines["TOOL_CHAIN_TAG"]].BsBaseAddress if BsAddress: break - - FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS =3D " + \ - BsAddress + \ - T_CHAR_LF) - RtAddress =3D '0' for Arch in ArchList: if GenFdsGlobalVariable.WorkSpace.BuildObject[ @@ -386,12 +372,17 @@ class GenFdsGlobalVariable: RtAddress =3D GenFdsGlobalVariable.WorkSpace.BuildObject[ GenFdsGlobalVariable.ActivePlatform, Arch, GlobalData.= gGlobalDefines['TARGET'], GlobalData.gGlobalDefines["TOOL_CHAIN_TAG"]].RtBaseAdd= ress - - FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS =3D " + \ - RtAddress + \ - T_CHAR_LF) - - FvAddressFile.close() + with open(GenFdsGlobalVariable.FvAddressFileName, 'w') as FvAddres= sFile: + # + # Add [Options] + # + FvAddressFile.writelines("[options]" + T_CHAR_LF) + FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS =3D " += \ + BsAddress + \ + T_CHAR_LF) + FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS =3D = " + \ + RtAddress + \ + T_CHAR_LF) =20 ## ReplaceWorkspaceMacro() # diff --git a/BaseTools/Source/Python/GenFds/GuidSection.py b/BaseTools/Sour= ce/Python/GenFds/GuidSection.py index bc95c7cd9d42..28571292f5a6 100644 --- a/BaseTools/Source/Python/GenFds/GuidSection.py +++ b/BaseTools/Source/Python/GenFds/GuidSection.py @@ -202,33 +202,28 @@ class GuidSection(GuidSectionClassObject) : if not os.path.exists(TempFile) : EdkLogger.error("GenFds", COMMAND_FAILURE, 'Fail to ca= ll %s, no output file was generated' % ExternalTool) =20 - FileHandleIn =3D open(DummyFile, 'rb') - FileHandleIn.seek(0, 2) - InputFileSize =3D FileHandleIn.tell() + with open(DummyFile, 'rb') as FileHandleIn, open(TempFile,= 'rb') as FileHandleOut: + FileHandleIn.seek(0, 2) + InputFileSize =3D FileHandleIn.tell() + FileHandleOut.seek(0, 2) + TempFileSize =3D FileHandleOut.tell() =20 - FileHandleOut =3D open(TempFile, 'rb') - FileHandleOut.seek(0, 2) - TempFileSize =3D FileHandleOut.tell() + Attribute =3D [] + HeaderLength =3D None + if self.ExtraHeaderSize !=3D -1: + HeaderLength =3D str(self.ExtraHeaderSize) =20 - Attribute =3D [] - HeaderLength =3D None - if self.ExtraHeaderSize !=3D -1: - HeaderLength =3D str(self.ExtraHeaderSize) - - if self.ProcessRequired =3D=3D "NONE" and HeaderLength is = None: - if TempFileSize > InputFileSize: - FileHandleIn.seek(0) - BufferIn =3D FileHandleIn.read() - FileHandleOut.seek(0) - BufferOut =3D FileHandleOut.read() - if BufferIn =3D=3D BufferOut[TempFileSize - InputF= ileSize:]: - HeaderLength =3D str(TempFileSize - InputFileS= ize) - #auto sec guided attribute with process required - if HeaderLength is None: - Attribute.append('PROCESSING_REQUIRED') - - FileHandleIn.close() - FileHandleOut.close() + if self.ProcessRequired =3D=3D "NONE" and HeaderLength= is None: + if TempFileSize > InputFileSize: + FileHandleIn.seek(0) + BufferIn =3D FileHandleIn.read() + FileHandleOut.seek(0) + BufferOut =3D FileHandleOut.read() + if BufferIn =3D=3D BufferOut[TempFileSize - In= putFileSize:]: + HeaderLength =3D str(TempFileSize - InputF= ileSize) + #auto sec guided attribute with process required + if HeaderLength is None: + Attribute.append('PROCESSING_REQUIRED') =20 if FirstCall and 'PROCESSING_REQUIRED' in Attribute: # Guided data by -z option on first call is the proces= s required data. Call the guided tool with the real option. diff --git a/BaseTools/Source/Python/GenFds/Region.py b/BaseTools/Source/Py= thon/GenFds/Region.py index 9d632b6321e2..e67d056cc178 100644 --- a/BaseTools/Source/Python/GenFds/Region.py +++ b/BaseTools/Source/Python/GenFds/Region.py @@ -159,9 +159,8 @@ class Region(RegionClassObject): EdkLogger.error("GenFds", GENFDS_ERROR, "Size of FV File (%s) is large= r than Region Size 0x%X specified." \ % (RegionData, Size)) - BinFile =3D open(FileName, 'rb') - Buffer.write(BinFile.read()) - BinFile.close() + with open(FileName, 'rb') as BinFile: + Buffer.write(BinFile.read()) Size =3D Size - FileLength # # Pad the left buffer @@ -213,9 +212,8 @@ class Region(RegionClassObject): EdkLogger.error("GenFds", GENFDS_ERROR, "Size 0x%X of Capsule File (%s) is lar= ger than Region Size 0x%X specified." \ % (FileLength, RegionData, Size)) - BinFile =3D open(FileName, 'rb') - Buffer.write(BinFile.read()) - BinFile.close() + with open(FileName, 'rb') as BinFile: + Buffer.write(BinFile.read()) Size =3D Size - FileLength # # Pad the left buffer @@ -245,9 +243,8 @@ class Region(RegionClassObject): "Size of File (%s) is larger than Regi= on Size 0x%X specified." \ % (RegionData, Size)) GenFdsGlobalVariable.InfLogger(' Region File Name =3D %s= ' % RegionData) - BinFile =3D open(RegionData, 'rb') - Buffer.write(BinFile.read()) - BinFile.close() + with open(RegionData, 'rb') as BinFile: + Buffer.write(BinFile.read()) Size =3D Size - FileLength # # Pad the left buffer diff --git a/BaseTools/Source/Python/GenFds/Vtf.py b/BaseTools/Source/Pytho= n/GenFds/Vtf.py index 18ea37b9afdd..291070827b78 100644 --- a/BaseTools/Source/Python/GenFds/Vtf.py +++ b/BaseTools/Source/Python/GenFds/Vtf.py @@ -1,7 +1,7 @@ ## @file # process VTF generation # -# Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.
+# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# # This program and the accompanying materials # are licensed and made available under the terms and conditions of the B= SD License @@ -67,81 +67,79 @@ class Vtf (VtfClassObject): def GenBsfInf (self): FvList =3D self.GetFvList() self.BsfInfName =3D os.path.join(GenFdsGlobalVariable.FvDir, self.= UiName + '.inf') - BsfInf =3D open(self.BsfInfName, 'w+') - if self.ResetBin is not None: - BsfInf.writelines ("[OPTIONS]" + T_CHAR_LF) - BsfInf.writelines ("IA32_RST_BIN" + \ - " =3D " + \ - GenFdsGlobalVariable.MacroExtend(GenFdsGlob= alVariable.ReplaceWorkspaceMacro(self.ResetBin)) + \ - T_CHAR_LF) - BsfInf.writelines (T_CHAR_LF) - - BsfInf.writelines ("[COMPONENTS]" + T_CHAR_LF) - - for ComponentObj in self.ComponentStatementList : - BsfInf.writelines ("COMP_NAME" + \ - " =3D " + \ - ComponentObj.CompName + \ - T_CHAR_LF) - if ComponentObj.CompLoc.upper() =3D=3D 'NONE': - BsfInf.writelines ("COMP_LOC" + \ + with open(self.BsfInfName, 'w') as BsfInf: + if self.ResetBin is not None: + BsfInf.writelines ("[OPTIONS]" + T_CHAR_LF) + BsfInf.writelines ("IA32_RST_BIN" + \ " =3D " + \ - 'N' + \ + GenFdsGlobalVariable.MacroExtend(GenFds= GlobalVariable.ReplaceWorkspaceMacro(self.ResetBin)) + \ T_CHAR_LF) + BsfInf.writelines (T_CHAR_LF) + + BsfInf.writelines ("[COMPONENTS]" + T_CHAR_LF) =20 - elif ComponentObj.FilePos is not None: - BsfInf.writelines ("COMP_LOC" + \ + for ComponentObj in self.ComponentStatementList : + BsfInf.writelines ("COMP_NAME" + \ " =3D " + \ - ComponentObj.FilePos + \ + ComponentObj.CompName + \ T_CHAR_LF) - else: - Index =3D FvList.index(ComponentObj.CompLoc.upper()) - if Index =3D=3D 0: + if ComponentObj.CompLoc.upper() =3D=3D 'NONE': BsfInf.writelines ("COMP_LOC" + \ " =3D " + \ - 'F' + \ + 'N' + \ T_CHAR_LF) - elif Index =3D=3D 1: + + elif ComponentObj.FilePos is not None: BsfInf.writelines ("COMP_LOC" + \ " =3D " + \ - 'S' + \ + ComponentObj.FilePos + \ T_CHAR_LF) + else: + Index =3D FvList.index(ComponentObj.CompLoc.upper()) + if Index =3D=3D 0: + BsfInf.writelines ("COMP_LOC" + \ + " =3D " + \ + 'F' + \ + T_CHAR_LF) + elif Index =3D=3D 1: + BsfInf.writelines ("COMP_LOC" + \ + " =3D " + \ + 'S' + \ + T_CHAR_LF) =20 - BsfInf.writelines ("COMP_TYPE" + \ - " =3D " + \ - ComponentObj.CompType + \ - T_CHAR_LF) - BsfInf.writelines ("COMP_VER" + \ - " =3D " + \ - ComponentObj.CompVer + \ - T_CHAR_LF) - BsfInf.writelines ("COMP_CS" + \ - " =3D " + \ - ComponentObj.CompCs + \ - T_CHAR_LF) - - BinPath =3D ComponentObj.CompBin - if BinPath !=3D '-': - BinPath =3D GenFdsGlobalVariable.MacroExtend(GenFdsGlobalV= ariable.ReplaceWorkspaceMacro(BinPath)) - BsfInf.writelines ("COMP_BIN" + \ - " =3D " + \ - BinPath + \ - T_CHAR_LF) + BsfInf.writelines ("COMP_TYPE" + \ + " =3D " + \ + ComponentObj.CompType + \ + T_CHAR_LF) + BsfInf.writelines ("COMP_VER" + \ + " =3D " + \ + ComponentObj.CompVer + \ + T_CHAR_LF) + BsfInf.writelines ("COMP_CS" + \ + " =3D " + \ + ComponentObj.CompCs + \ + T_CHAR_LF) =20 - SymPath =3D ComponentObj.CompSym - if SymPath !=3D '-': - SymPath =3D GenFdsGlobalVariable.MacroExtend(GenFdsGlobalV= ariable.ReplaceWorkspaceMacro(SymPath)) - BsfInf.writelines ("COMP_SYM" + \ - " =3D " + \ - SymPath + \ - T_CHAR_LF) - BsfInf.writelines ("COMP_SIZE" + \ - " =3D " + \ - ComponentObj.CompSize + \ - T_CHAR_LF) - BsfInf.writelines (T_CHAR_LF) + BinPath =3D ComponentObj.CompBin + if BinPath !=3D '-': + BinPath =3D GenFdsGlobalVariable.MacroExtend(GenFdsGlo= balVariable.ReplaceWorkspaceMacro(BinPath)) + BsfInf.writelines ("COMP_BIN" + \ + " =3D " + \ + BinPath + \ + T_CHAR_LF) =20 - BsfInf.close() + SymPath =3D ComponentObj.CompSym + if SymPath !=3D '-': + SymPath =3D GenFdsGlobalVariable.MacroExtend(GenFdsGlo= balVariable.ReplaceWorkspaceMacro(SymPath)) + BsfInf.writelines ("COMP_SYM" + \ + " =3D " + \ + SymPath + \ + T_CHAR_LF) + BsfInf.writelines ("COMP_SIZE" + \ + " =3D " + \ + ComponentObj.CompSize + \ + T_CHAR_LF) + BsfInf.writelines (T_CHAR_LF) =20 ## GenFvList() method # diff --git a/BaseTools/Source/Python/GenPatchPcdTable/GenPatchPcdTable.py b= /BaseTools/Source/Python/GenPatchPcdTable/GenPatchPcdTable.py index f40c8bd01b23..aa61bc00f277 100644 --- a/BaseTools/Source/Python/GenPatchPcdTable/GenPatchPcdTable.py +++ b/BaseTools/Source/Python/GenPatchPcdTable/GenPatchPcdTable.py @@ -46,13 +46,13 @@ def parsePcdInfoFromMapFile(mapfilepath, efifilepath): """ lines =3D [] try: - f =3D open(mapfilepath, 'r') - lines =3D f.readlines() - f.close() + with open(mapfilepath, 'r') as f: + lines =3D f.readlines() except: return None =20 - if len(lines) =3D=3D 0: return None + if len(lines) =3D=3D 0:=20 + return None firstline =3D lines[0].strip() if (firstline.startswith("Archive member included ") and firstline.endswith(" file (symbol)")): @@ -190,18 +190,13 @@ def _parseGeneral(lines, efifilepath): =20 def generatePcdTable(list, pcdpath): try: - f =3D open(pcdpath, 'w') + with open(pcdpath, 'w') as f: + f.write('PCD Name Offset Section Name= \r\n') + for pcditem in list: + f.write('%-30s 0x%-08X %-6s\r\n' % (pcditem[0], pcditem[1]= , pcditem[2])) except: pass =20 - f.write('PCD Name Offset Section Name\r\n') - =20 - for pcditem in list: - f.write('%-30s 0x%-08X %-6s\r\n' % (pcditem[0], pcditem[1], pcdite= m[2])) - f.close() - - #print 'Success to generate Binary Patch PCD table at %s!' % pcdpath=20 - if __name__ =3D=3D '__main__': UsageString =3D "%prog -m -e -o " AdditionalNotes =3D "\nPCD table is generated in file name with .Binar= yPcdTable.txt postfix" diff --git a/BaseTools/Source/Python/PatchPcdValue/PatchPcdValue.py b/BaseT= ools/Source/Python/PatchPcdValue/PatchPcdValue.py index cf2fc7c4f70a..76fef41176ac 100644 --- a/BaseTools/Source/Python/PatchPcdValue/PatchPcdValue.py +++ b/BaseTools/Source/Python/PatchPcdValue/PatchPcdValue.py @@ -49,10 +49,9 @@ def PatchBinaryFile(FileName, ValueOffset, TypeName, Val= ueString, MaxSize=3D0): # # Length of Binary File # - FileHandle =3D open(FileName, 'rb') - FileHandle.seek (0, 2) - FileLength =3D FileHandle.tell() - FileHandle.close() + with open(FileName, 'rb') as FileHandle: + FileHandle.seek (0, 2) + FileLength =3D FileHandle.tell() # # Unify string to upper string # @@ -85,10 +84,9 @@ def PatchBinaryFile(FileName, ValueOffset, TypeName, Val= ueString, MaxSize=3D0): # # Read binary file into array # - FileHandle =3D open(FileName, 'rb') - ByteArray =3D array.array('B') - ByteArray.fromfile(FileHandle, FileLength) - FileHandle.close() + with open(FileName, 'rb') as FileHandle: + ByteArray =3D array.array('B') + ByteArray.fromfile(FileHandle, FileLength) OrigByteList =3D ByteArray.tolist() ByteList =3D ByteArray.tolist() # @@ -193,9 +191,8 @@ def PatchBinaryFile(FileName, ValueOffset, TypeName, Va= lueString, MaxSize=3D0): if ByteList !=3D OrigByteList: ByteArray =3D array.array('B') ByteArray.fromlist(ByteList) - FileHandle =3D open(FileName, 'wb') - ByteArray.tofile(FileHandle) - FileHandle.close() + with open(FileName, 'wb') as FileHandle: + ByteArray.tofile(FileHandle) return 0, "Patch Value into File %s successfully." % (FileName) =20 ## Parse command line options diff --git a/BaseTools/Source/Python/Table/TableReport.py b/BaseTools/Sourc= e/Python/Table/TableReport.py index 4af0e98d86b4..145c66c4b415 100644 --- a/BaseTools/Source/Python/Table/TableReport.py +++ b/BaseTools/Source/Python/Table/TableReport.py @@ -1,7 +1,7 @@ ## @file # This file is used to create/update/query/erase table for ECC reports # -# Copyright (c) 2008 - 2015, Intel Corporation. All rights reserved.
+# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.
# This program and the accompanying materials # are licensed and made available under the terms and conditions of the BS= D License # which accompanies this distribution. The full text of the license may b= e found at @@ -100,31 +100,30 @@ class TableReport(Table): # def ToCSV(self, Filename=3D'Report.csv'): try: - File =3D open(Filename, 'w+') - File.write("""No, Error Code, Error Message, File, LineNo, Oth= er Error Message\n""") - RecordSet =3D self.Query() - Index =3D 0 - for Record in RecordSet: - Index =3D Index + 1 - ErrorID =3D Record[1] - OtherMsg =3D Record[2] - BelongsToTable =3D Record[3] - BelongsToItem =3D Record[4] - IsCorrected =3D Record[5] - SqlCommand =3D '' - if BelongsToTable =3D=3D 'File': - SqlCommand =3D """select 1, FullPath from %s where ID = =3D %s - """ % (BelongsToTable, BelongsToItem) - else: - SqlCommand =3D """select A.StartLine, B.FullPath from = %s as A, File as B - where A.ID =3D %s and B.ID =3D A.Belon= gsToFile + with open(Filename, 'w') as File: + File.write("""No, Error Code, Error Message, File, LineNo,= Other Error Message\n""") + RecordSet =3D self.Query() + Index =3D 0 + for Record in RecordSet: + Index =3D Index + 1 + ErrorID =3D Record[1] + OtherMsg =3D Record[2] + BelongsToTable =3D Record[3] + BelongsToItem =3D Record[4] + IsCorrected =3D Record[5] + SqlCommand =3D '' + if BelongsToTable =3D=3D 'File': + SqlCommand =3D """select 1, FullPath from %s where= ID =3D %s """ % (BelongsToTable, BelongsToItem) - NewRecord =3D self.Exec(SqlCommand) - if NewRecord !=3D []: - File.write("""%s,%s,"%s",%s,%s,"%s"\n""" % (Index, Err= orID, EccToolError.gEccErrorMessage[ErrorID], NewRecord[0][1], NewRecord[0]= [0], OtherMsg)) - EdkLogger.quiet("%s(%s): [%s]%s %s" % (NewRecord[0][1]= , NewRecord[0][0], ErrorID, EccToolError.gEccErrorMessage[ErrorID], OtherMs= g)) + else: + SqlCommand =3D """select A.StartLine, B.FullPath f= rom %s as A, File as B + where A.ID =3D %s and B.ID =3D A.B= elongsToFile + """ % (BelongsToTable, BelongsToItem) + NewRecord =3D self.Exec(SqlCommand) + if NewRecord !=3D []: + File.write("""%s,%s,"%s",%s,%s,"%s"\n""" % (Index,= ErrorID, EccToolError.gEccErrorMessage[ErrorID], NewRecord[0][1], NewRecor= d[0][0], OtherMsg)) + EdkLogger.quiet("%s(%s): [%s]%s %s" % (NewRecord[0= ][1], NewRecord[0][0], ErrorID, EccToolError.gEccErrorMessage[ErrorID], Oth= erMsg)) =20 - File.close() except IOError: NewFilename =3D 'Report_' + time.strftime("%Y%m%d_%H%M%S.csv",= time.localtime()) EdkLogger.warn("ECC", "The report file %s is locked by other p= rogress, use %s instead!" % (Filename, NewFilename)) diff --git a/BaseTools/Source/Python/TargetTool/TargetTool.py b/BaseTools/S= ource/Python/TargetTool/TargetTool.py index ecac316b7a3a..5c463df6bce5 100644 --- a/BaseTools/Source/Python/TargetTool/TargetTool.py +++ b/BaseTools/Source/Python/TargetTool/TargetTool.py @@ -58,22 +58,21 @@ class TargetTool(): def ConvertTextFileToDict(self, FileName, CommentCharacter, KeySplitCh= aracter): """Convert a text file to a dictionary of (name:value) pairs.""" try: - f =3D open(FileName,'r') - for Line in f: - if Line.startswith(CommentCharacter) or Line.strip() =3D= =3D '': - continue - LineList =3D Line.split(KeySplitCharacter,1) - if len(LineList) >=3D 2: - Key =3D LineList[0].strip() - if Key.startswith(CommentCharacter) =3D=3D False and K= ey in self.TargetTxtDictionary: - if Key =3D=3D TAB_TAT_DEFINES_ACTIVE_PLATFORM or K= ey =3D=3D TAB_TAT_DEFINES_TOOL_CHAIN_CONF \ - or Key =3D=3D TAB_TAT_DEFINES_MAX_CONCURRENT_THR= EAD_NUMBER \ - or Key =3D=3D TAB_TAT_DEFINES_ACTIVE_MODULE: - self.TargetTxtDictionary[Key] =3D LineList[1].= replace('\\', '/').strip() - elif Key =3D=3D TAB_TAT_DEFINES_TARGET or Key =3D= =3D TAB_TAT_DEFINES_TARGET_ARCH \ - or Key =3D=3D TAB_TAT_DEFINES_TOOL_CHAIN_TAG or = Key =3D=3D TAB_TAT_DEFINES_BUILD_RULE_CONF: - self.TargetTxtDictionary[Key] =3D LineList[1].= split() - f.close() + with open(FileName,'r') as f: + for Line in f: + if Line.startswith(CommentCharacter) or Line.strip() = =3D=3D '': + continue + LineList =3D Line.split(KeySplitCharacter,1) + if len(LineList) >=3D 2: + Key =3D LineList[0].strip() + if Key.startswith(CommentCharacter) =3D=3D False a= nd Key in self.TargetTxtDictionary: + if Key =3D=3D TAB_TAT_DEFINES_ACTIVE_PLATFORM = or Key =3D=3D TAB_TAT_DEFINES_TOOL_CHAIN_CONF \ + or Key =3D=3D TAB_TAT_DEFINES_MAX_CONCURRENT= _THREAD_NUMBER \ + or Key =3D=3D TAB_TAT_DEFINES_ACTIVE_MODULE: + self.TargetTxtDictionary[Key] =3D LineList= [1].replace('\\', '/').strip() + elif Key =3D=3D TAB_TAT_DEFINES_TARGET or Key = =3D=3D TAB_TAT_DEFINES_TARGET_ARCH \ + or Key =3D=3D TAB_TAT_DEFINES_TOOL_CHAIN_TAG= or Key =3D=3D TAB_TAT_DEFINES_BUILD_RULE_CONF: + self.TargetTxtDictionary[Key] =3D LineList= [1].split() return 0 except: last_type, last_value, last_tb =3D sys.exc_info() @@ -94,42 +93,38 @@ class TargetTool(): =20 def RWFile(self, CommentCharacter, KeySplitCharacter, Num): try: - fr =3D open(self.FileName, 'r') - fw =3D open(os.path.normpath(os.path.join(self.WorkSpace, 'Con= f\\targetnew.txt')), 'w') - - existKeys =3D [] - for Line in fr: - if Line.startswith(CommentCharacter) or Line.strip() =3D= =3D '': - fw.write(Line) - else: - LineList =3D Line.split(KeySplitCharacter,1) - if len(LineList) >=3D 2: - Key =3D LineList[0].strip() - if Key.startswith(CommentCharacter) =3D=3D False a= nd Key in self.TargetTxtDictionary: - if Key not in existKeys: - existKeys.append(Key) - else: - print "Warning: Found duplicate key item i= n original configuration files!" - =20 - if Num =3D=3D 0: - Line =3D "%-30s =3D \n" % Key - else: - ret =3D GetConfigureKeyValue(self, Key) - if ret is not None: - Line =3D ret - fw.write(Line) - for key in self.TargetTxtDictionary: - if key not in existKeys: - print "Warning: %s does not exist in original configur= ation file" % key - Line =3D GetConfigureKeyValue(self, key) - if Line is None: - Line =3D "%-30s =3D " % key - fw.write(Line) + with open(self.FileName, 'r') as fr: + FileRead =3D fr.readlines() + with open(self.FileName, 'w') as fw: + existKeys =3D [] + for Line in FileRead: + if Line.startswith(CommentCharacter) or Line.strip() = =3D=3D '': + fw.write(Line) + else: + LineList =3D Line.split(KeySplitCharacter,1) + if len(LineList) >=3D 2: + Key =3D LineList[0].strip() + if Key.startswith(CommentCharacter) =3D=3D Fal= se and Key in self.TargetTxtDictionary: + if Key not in existKeys: + existKeys.append(Key) + else: + print "Warning: Found duplicate key it= em in original configuration files!" + =20 + if Num =3D=3D 0: + Line =3D "%-30s =3D \n" % Key + else: + ret =3D GetConfigureKeyValue(self, Key) + if ret is not None: + Line =3D ret + fw.write(Line) + for key in self.TargetTxtDictionary: + if key not in existKeys: + print "Warning: %s does not exist in original conf= iguration file" % key + Line =3D GetConfigureKeyValue(self, key) + if Line is None: + Line =3D "%-30s =3D " % key + fw.write(Line) =20 - fr.close() - fw.close() - os.remove(self.FileName) - os.rename(os.path.normpath(os.path.join(self.WorkSpace, 'Conf\= \targetnew.txt')), self.FileName) =20 except: last_type, last_value, last_tb =3D sys.exc_info() diff --git a/BaseTools/Source/Python/Trim/Trim.py b/BaseTools/Source/Python= /Trim/Trim.py index d2e6d317676c..a92df52979c6 100644 --- a/BaseTools/Source/Python/Trim/Trim.py +++ b/BaseTools/Source/Python/Trim/Trim.py @@ -141,14 +141,12 @@ gIncludedAslFile =3D [] def TrimPreprocessedFile(Source, Target, ConvertHex, TrimLong): CreateDirectory(os.path.dirname(Target)) try: - f =3D open (Source, 'r') + with open (Source, 'r') as f: + # read whole file + Lines =3D f.readlines() except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=3DSource) =20 - # read whole file - Lines =3D f.readlines() - f.close() - PreprocessedFile =3D "" InjectedFile =3D "" LineIndexOfOriginalFile =3D None @@ -243,11 +241,10 @@ def TrimPreprocessedFile(Source, Target, ConvertHex, = TrimLong): =20 # save to file try: - f =3D open (Target, 'wb') + with open (Target, 'wb') as f: + f.writelines(NewLines) except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=3DTarget) - f.writelines(NewLines) - f.close() =20 ## Trim preprocessed VFR file # @@ -261,12 +258,11 @@ def TrimPreprocessedVfr(Source, Target): CreateDirectory(os.path.dirname(Target)) =20 try: - f =3D open (Source,'r') + with open (Source,'r') as f: + # read whole file + Lines =3D f.readlines() except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=3DSource) - # read whole file - Lines =3D f.readlines() - f.close() =20 FoundTypedef =3D False Brace =3D 0 @@ -310,11 +306,10 @@ def TrimPreprocessedVfr(Source, Target): =20 # save all lines trimmed try: - f =3D open (Target,'w') + with open (Target,'w') as f: + f.writelines(Lines) except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=3DTarget) - f.writelines(Lines) - f.close() =20 ## Read the content ASL file, including ASL included, recursively # @@ -340,7 +335,8 @@ def DoInclude(Source, Indent=3D'', IncludePathList=3D[]= , LocalSearchPath=3DNone): for IncludePath in SearchPathList: IncludeFile =3D os.path.join(IncludePath, Source) if os.path.isfile(IncludeFile): - F =3D open(IncludeFile, "r") + with open(IncludeFile, "r") as OpenFile: + FileLines =3D OpenFile.readlines() break else: EdkLogger.error("Trim", "Failed to find include file %s" % Sou= rce) @@ -356,7 +352,7 @@ def DoInclude(Source, Indent=3D'', IncludePathList=3D[]= , LocalSearchPath=3DNone): return [] gIncludedAslFile.append(IncludeFile) =20 - for Line in F: + for Line in FileLines: LocalSearchPath =3D None Result =3D gAslIncludePattern.findall(Line) if len(Result) =3D=3D 0: @@ -375,7 +371,6 @@ def DoInclude(Source, Indent=3D'', IncludePathList=3D[]= , LocalSearchPath=3DNone): NewFileContent.append("\n") =20 gIncludedAslFile.pop() - F.close() =20 return NewFileContent =20 @@ -425,12 +420,11 @@ def TrimAslFile(Source, Target, IncludePathFile): =20 # save all lines trimmed try: - f =3D open (Target,'w') + with open (Target,'w') as f: + f.writelines(Lines) except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=3DTarget) =20 - f.writelines(Lines) - f.close() =20 def GenerateVfrBinSec(ModuleName, DebugDir, OutputFile): VfrNameList =3D [] @@ -450,11 +444,6 @@ def GenerateVfrBinSec(ModuleName, DebugDir, OutputFile= ): if not VfrUniOffsetList: return =20 - try: - fInputfile =3D open(OutputFile, "wb+", 0) - except: - EdkLogger.error("Trim", FILE_OPEN_FAILURE, "File open failed for %= s" %OutputFile, None) - # Use a instance of StringIO to cache data fStringIO =3D StringIO.StringIO('') =20 @@ -483,16 +472,16 @@ def GenerateVfrBinSec(ModuleName, DebugDir, OutputFil= e): VfrValue =3D pack ('Q', int (Item[1], 16)) fStringIO.write (VfrValue) =20 - # - # write data into file. - # - try : - fInputfile.write (fStringIO.getvalue()) + try: + with open(OutputFile, "wb+", 0) as fInputfile: + try : + fInputfile.write (fStringIO.getvalue()) + except: + EdkLogger.error("Trim", FILE_WRITE_FAILURE, "Write data to= file %s failed, please check whether the file been locked or using by othe= r applications." %OutputFile, None) except: - EdkLogger.error("Trim", FILE_WRITE_FAILURE, "Write data to file %s= failed, please check whether the file been locked or using by other applic= ations." %OutputFile, None) + EdkLogger.error("Trim", FILE_OPEN_FAILURE, "File open failed for %= s" %OutputFile, None) =20 fStringIO.close () - fInputfile.close () =20 ## Trim EDK source code file(s) # @@ -560,12 +549,11 @@ def TrimEdkSourceCode(Source, Target): CreateDirectory(os.path.dirname(Target)) =20 try: - f =3D open (Source,'rb') + with open (Source,'rb') as f: + # read whole file + Lines =3D f.read() except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=3DSource) - # read whole file - Lines =3D f.read() - f.close() =20 NewLines =3D None for Re,Repl in gImportCodePatterns: @@ -579,11 +567,10 @@ def TrimEdkSourceCode(Source, Target): return =20 try: - f =3D open (Target,'wb') + with open (Target,'wb') as f: + f.write(NewLines) except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=3DTarget) - f.write(NewLines) - f.close() =20 =20 ## Parse command line options diff --git a/BaseTools/Source/Python/Workspace/DscBuildData.py b/BaseTools/= Source/Python/Workspace/DscBuildData.py index 2de8a84b9bd7..d714c781e970 100644 --- a/BaseTools/Source/Python/Workspace/DscBuildData.py +++ b/BaseTools/Source/Python/Workspace/DscBuildData.py @@ -118,13 +118,10 @@ def GetDependencyList(FileStack,SearchPathList): CurrentFileDependencyList =3D DepDb[F] else: try: - Fd =3D open(F, 'r') - FileContent =3D Fd.read() + with open(F, 'r') as Fd: + FileContent =3D Fd.read() except BaseException, X: EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=3DF = + "\n\t" + str(X)) - finally: - if "Fd" in dir(locals()): - Fd.close() =20 if len(FileContent) =3D=3D 0: continue @@ -2109,9 +2106,8 @@ class DscBuildData(PlatformBuildClassObject): MessageGroup =3D [] if returncode <>0: CAppBaseFileName =3D os.path.join(self.OutputPath, PcdValueIni= tName) - File =3D open (CAppBaseFileName + '.c', 'r') - FileData =3D File.readlines() - File.close() + with open (CAppBaseFileName + '.c', 'r') as File: + FileData =3D File.readlines() for Message in Messages: if " error" in Message or "warning" in Message: FileInfo =3D Message.strip().split('(') @@ -2155,9 +2151,8 @@ class DscBuildData(PlatformBuildClassObject): if returncode <> 0: EdkLogger.warn('Build', COMMAND_FAILURE, 'Can not collect = output from command: %s' % Command) =20 - File =3D open (OutputValueFile, 'r') - FileBuffer =3D File.readlines() - File.close() + with open (OutputValueFile, 'r') as File: + FileBuffer =3D File.readlines() =20 StructurePcdSet =3D [] for Pcd in FileBuffer: diff --git a/BaseTools/Source/Python/build/BuildReport.py b/BaseTools/Sourc= e/Python/build/BuildReport.py index 72a557dfea50..db9e1ed062fb 100644 --- a/BaseTools/Source/Python/build/BuildReport.py +++ b/BaseTools/Source/Python/build/BuildReport.py @@ -291,18 +291,18 @@ class DepexParser(object): # @param DepexFileName The file name of binary dependency expression= file. # def ParseDepexFile(self, DepexFileName): - DepexFile =3D open(DepexFileName, "rb") DepexStatement =3D [] - OpCode =3D DepexFile.read(1) - while OpCode: - Statement =3D gOpCodeList[struct.unpack("B", OpCode)[0]] - if Statement in ["BEFORE", "AFTER", "PUSH"]: - GuidValue =3D "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02= X%02X" % \ - struct.unpack(PACK_PATTERN_GUID, DepexFile.rea= d(16)) - GuidString =3D self._GuidDb.get(GuidValue, GuidValue) - Statement =3D "%s %s" % (Statement, GuidString) - DepexStatement.append(Statement) + with open(DepexFileName, "rb") as DepexFile: OpCode =3D DepexFile.read(1) + while OpCode: + Statement =3D gOpCodeList[struct.unpack("B", OpCode)[0]] + if Statement in ["BEFORE", "AFTER", "PUSH"]: + GuidValue =3D "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02= X%02X%02X" % \ + struct.unpack(PACK_PATTERN_GUID, DepexFile= .read(16)) + GuidString =3D self._GuidDb.get(GuidValue, GuidValue) + Statement =3D "%s %s" % (Statement, GuidString) + DepexStatement.append(Statement) + OpCode =3D DepexFile.read(1) =20 return DepexStatement =20 @@ -629,14 +629,14 @@ class ModuleReport(object): FwReportFileName =3D os.path.join(self._BuildDir, "DEBUG", self.Mo= duleName + ".txt") if os.path.isfile(FwReportFileName): try: - FileContents =3D open(FwReportFileName).read() - Match =3D gModuleSizePattern.search(FileContents) - if Match: - self.Size =3D int(Match.group(1)) + with open(FwReportFileName).read() as FileContents: + Match =3D gModuleSizePattern.search(FileContents) + if Match: + self.Size =3D int(Match.group(1)) =20 - Match =3D gTimeStampPattern.search(FileContents) - if Match: - self.BuildTimeStamp =3D datetime.fromtimestamp(int(Mat= ch.group(1))) + Match =3D gTimeStampPattern.search(FileContents) + if Match: + self.BuildTimeStamp =3D datetime.fromtimestamp(int= (Match.group(1))) except IOError: EdkLogger.warn(None, "Fail to read report file", FwReportF= ileName) =20 @@ -1483,14 +1483,12 @@ class PredictionReport(object): GuidList =3D os.path.join(self._EotDir, "GuidList.txt") DispatchList =3D os.path.join(self._EotDir, "Dispatch.txt") =20 - TempFile =3D open(SourceList, "w+") - for Item in self._SourceList: - FileWrite(TempFile, Item) - TempFile.close() - TempFile =3D open(GuidList, "w+") - for Key in self._GuidMap: - FileWrite(TempFile, "%s %s" % (Key, self._GuidMap[Key])) - TempFile.close() + with open(SourceList, "w") as TempFile: + for Item in self._SourceList: + FileWrite(TempFile, Item) + with open(GuidList, "w") as TempFile: + for Key in self._GuidMap: + FileWrite(TempFile, "%s %s" % (Key, self._GuidMap[Key])) =20 try: from Eot.Eot import Eot @@ -1881,23 +1879,22 @@ class FdReport(object): break =20 if os.path.isfile(self.VpdFilePath): - fd =3D open(self.VpdFilePath, "r") - Lines =3D fd.readlines() - for Line in Lines: - Line =3D Line.strip() - if len(Line) =3D=3D 0 or Line.startswith("#"): - continue - try: - PcdName, SkuId, Offset, Size, Value =3D Line.split("#"= )[0].split("|") - PcdName, SkuId, Offset, Size, Value =3D PcdName.strip(= ), SkuId.strip(), Offset.strip(), Size.strip(), Value.strip() - if Offset.lower().startswith('0x'): - Offset =3D '0x%08X' % (int(Offset, 16) + self.VPDB= aseAddress) - else: - Offset =3D '0x%08X' % (int(Offset, 10) + self.VPDB= aseAddress) - self.VPDInfoList.append("%s | %s | %s | %s | %s" % (Pc= dName, SkuId, Offset, Size, Value)) - except: - EdkLogger.error("BuildReport", CODE_ERROR, "Fail to pa= rse VPD information file %s" % self.VpdFilePath) - fd.close() + with open(self.VpdFilePath, "r") as fd: + Lines =3D fd.readlines() + for Line in Lines: + Line =3D Line.strip() + if len(Line) =3D=3D 0 or Line.startswith("#"): + continue + try: + PcdName, SkuId, Offset, Size, Value =3D Line.split= ("#")[0].split("|") + PcdName, SkuId, Offset, Size, Value =3D PcdName.st= rip(), SkuId.strip(), Offset.strip(), Size.strip(), Value.strip() + if Offset.lower().startswith('0x'): + Offset =3D '0x%08X' % (int(Offset, 16) + self.= VPDBaseAddress) + else: + Offset =3D '0x%08X' % (int(Offset, 10) + self.= VPDBaseAddress) + self.VPDInfoList.append("%s | %s | %s | %s | %s" %= (PcdName, SkuId, Offset, Size, Value)) + except: + EdkLogger.error("BuildReport", CODE_ERROR, "Fail t= o parse VPD information file %s" % self.VpdFilePath) =20 ## # Generate report for the firmware device. diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Pyth= on/build/build.py index 99e4881b3ea4..1fb8c7985d99 100644 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -320,9 +320,8 @@ def LaunchCommand(Command, WorkingDir): # print out the Response file and its content when make failure RespFile =3D os.path.join(WorkingDir, 'OUTPUT', 'respfilelist.txt') if os.path.isfile(RespFile): - f =3D open(RespFile) - RespContent =3D f.read() - f.close() + with open(RespFile) as f: + RespContent =3D f.read() EdkLogger.info(RespContent) =20 EdkLogger.error("build", COMMAND_FAILURE, ExtraData=3D"%s [%s]" % = (Command, WorkingDir)) @@ -1169,9 +1168,8 @@ class Build(): EdkLogger.error("Prebuild", PREBUILD_ERROR, 'Prebuild proc= ess is not success!') =20 if os.path.exists(PrebuildEnvFile): - f =3D open(PrebuildEnvFile) - envs =3D f.readlines() - f.close() + with open(PrebuildEnvFile) as f: + envs =3D f.readlines() envs =3D itertools.imap(lambda l: l.split('=3D',1), envs) envs =3D itertools.ifilter(lambda l: len(l) =3D=3D 2, envs) envs =3D itertools.imap(lambda l: [i.strip() for i in l], = envs) @@ -1451,29 +1449,28 @@ class Build(): FunctionList =3D [] if os.path.exists(ImageMapTable): OrigImageBaseAddress =3D 0 - ImageMap =3D open(ImageMapTable, 'r') - for LinStr in ImageMap: - if len (LinStr.strip()) =3D=3D 0: - continue - # - # Get the preferred address set on link time. - # - if LinStr.find ('Preferred load address is') !=3D -1: + with open(ImageMapTable, 'r') as ImageMap: + for LinStr in ImageMap: + if len (LinStr.strip()) =3D=3D 0: + continue + # + # Get the preferred address set on link time. + # + if LinStr.find ('Preferred load address is') !=3D = -1: + StrList =3D LinStr.split() + OrigImageBaseAddress =3D int (StrList[len(StrL= ist) - 1], 16) + StrList =3D LinStr.split() - OrigImageBaseAddress =3D int (StrList[len(StrList)= - 1], 16) - - StrList =3D LinStr.split() - if len (StrList) > 4: - if StrList[3] =3D=3D 'f' or StrList[3] =3D=3D 'F': - Name =3D StrList[1] - RelativeAddress =3D int (StrList[2], 16) - Ori= gImageBaseAddress - FunctionList.append ((Name, RelativeAddress)) - if ModuleInfo.Arch =3D=3D 'IPF' and Name.endsw= ith('_ModuleEntryPoint'): - # - # Get the real entry point address for IPF= image. - # - ModuleInfo.Image.EntryPoint =3D RelativeAd= dress - ImageMap.close() + if len (StrList) > 4: + if StrList[3] =3D=3D 'f' or StrList[3] =3D=3D = 'F': + Name =3D StrList[1] + RelativeAddress =3D int (StrList[2], 16) -= OrigImageBaseAddress + FunctionList.append ((Name, RelativeAddres= s)) + if ModuleInfo.Arch =3D=3D 'IPF' and Name.e= ndswith('_ModuleEntryPoint'): + # + # Get the real entry point address for= IPF image. + # + ModuleInfo.Image.EntryPoint =3D Relati= veAddress # # Add general information. # @@ -1528,32 +1525,30 @@ class Build(): FvMapBuffer =3D os.path.join(Wa.FvDir, FvName + '.Fv.map') if not os.path.exists(FvMapBuffer): continue - FvMap =3D open(FvMapBuffer, 'r') - #skip FV size information - FvMap.readline() - FvMap.readline() - FvMap.readline() - FvMap.readline() - for Line in FvMap: - MatchGuid =3D GuidPattern.match(Line) - if MatchGuid is not None: + with open(FvMapBuffer, 'r') as FvMap: + #skip FV size information + FvMap.readline() + FvMap.readline() + FvMap.readline() + FvMap.readline() + for Line in FvMap: + MatchGuid =3D GuidPattern.match(Line) + if MatchGuid is not None: + # + # Replace GUID with module name + # + GuidString =3D MatchGuid.group() + if GuidString.upper() in ModuleList: + Line =3D Line.replace(GuidString, ModuleLi= st[GuidString.upper()].Name) + MapBuffer.write('%s' % (Line)) # - # Replace GUID with module name + # Add the debug image full path. # - GuidString =3D MatchGuid.group() - if GuidString.upper() in ModuleList: - Line =3D Line.replace(GuidString, ModuleList[G= uidString.upper()].Name) - MapBuffer.write('%s' % (Line)) - # - # Add the debug image full path. - # - MatchGuid =3D GuidName.match(Line) - if MatchGuid is not None: - GuidString =3D MatchGuid.group().split("=3D")[1] - if GuidString.upper() in ModuleList: - MapBuffer.write('(IMAGE=3D%s)\n' % (os.path.jo= in(ModuleList[GuidString.upper()].DebugDir, ModuleList[GuidString.upper()].= Name + '.efi'))) - - FvMap.close() + MatchGuid =3D GuidName.match(Line) + if MatchGuid is not None: + GuidString =3D MatchGuid.group().split("=3D")[= 1] + if GuidString.upper() in ModuleList: + MapBuffer.write('(IMAGE=3D%s)\n' % (os.pat= h.join(ModuleList[GuidString.upper()].DebugDir, ModuleList[GuidString.upper= ()].Name + '.efi'))) =20 ## Collect MAP information of all modules # @@ -2193,10 +2188,9 @@ class Build(): =20 # Write out GuidedSecTools.txt toolsFile =3D os.path.join(FvDir, 'GuidedSectionTools.= txt') - toolsFile =3D open(toolsFile, 'wt') - for guidedSectionTool in guidAttribs: - print >> toolsFile, ' '.join(guidedSectionTool) - toolsFile.close() + with open(toolsFile, 'w') as toolsFile: + for guidedSectionTool in guidAttribs: + print >> toolsFile, ' '.join(guidedSectionTool) =20 ## Returns the full path of the tool. # --=20 2.16.2.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Fri May 3 05:47:03 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 1526321396419822.0376744980775; Mon, 14 May 2018 11:09:56 -0700 (PDT) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id A4C562096AECE; Mon, 14 May 2018 11:09:27 -0700 (PDT) Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 4C20021CAD9BA for ; Mon, 14 May 2018 11:09:25 -0700 (PDT) Received: from orsmga001.jf.intel.com ([10.7.209.18]) by orsmga105.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 14 May 2018 11:09:24 -0700 Received: from jcarsey-desk1.amr.corp.intel.com ([10.7.159.144]) by orsmga001.jf.intel.com with ESMTP; 14 May 2018 11:09:24 -0700 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.100; helo=mga07.intel.com; envelope-from=jaben.carsey@intel.com; receiver=edk2-devel@lists.01.org X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.49,401,1520924400"; d="scan'208";a="55814278" From: Jaben Carsey To: edk2-devel@lists.01.org Date: Mon, 14 May 2018 11:09:17 -0700 Message-Id: <271980cc1367f9a32c28b0ceb6cd7d040535ea9c.1526321053.git.jaben.carsey@intel.com> X-Mailer: git-send-email 2.16.2.windows.1 In-Reply-To: References: In-Reply-To: References: Subject: [edk2] [PATCH v1 08/11] BaseTools: refactor to change object types X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.26 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Liming Gao MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" change to object types that are closer to use case. for example: when using a list as a double ended queue, use the built in object. Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jaben Carsey --- BaseTools/Source/Python/AutoGen/AutoGen.py | 30 +++++++++++-----= ---- BaseTools/Source/Python/GenFds/FdfParser.py | 5 ++-- BaseTools/Source/Python/Workspace/WorkspaceCommon.py | 20 ++++++------- 3 files changed, 29 insertions(+), 26 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/AutoGen.py b/BaseTools/Source/= Python/AutoGen/AutoGen.py index 009e5c56781d..599331060187 100644 --- a/BaseTools/Source/Python/AutoGen/AutoGen.py +++ b/BaseTools/Source/Python/AutoGen/AutoGen.py @@ -45,10 +45,14 @@ import InfSectionParser import datetime import hashlib from GenVar import VariableMgr,var_info -from collections import OrderedDict -from collections import defaultdict +from collections import OrderedDict,defaultdict,deque from abc import ABCMeta, abstractmethod =20 +class OrderedListDict(OrderedDict, defaultdict): + def __init__(self, *args, **kwargs): + super(OrderedListDict, self).__init__(*args, **kwargs) + self.default_factory =3D list + ## Regular expression for splitting Dependency Expression string into toke= ns gDepexTokenPattern =3D re.compile("(\(|\)|\w+| \S+\.inf)") =20 @@ -2172,8 +2176,8 @@ class PlatformAutoGen(AutoGen): =20 # EdkII module LibraryConsumerList =3D [Module] - Constructor =3D [] - ConsumedByList =3D OrderedDict() + Constructor =3D set() + ConsumedByList =3D OrderedListDict() LibraryInstance =3D OrderedDict() =20 EdkLogger.verbose("") @@ -2219,10 +2223,8 @@ class PlatformAutoGen(AutoGen): continue =20 if LibraryModule.ConstructorList !=3D [] and LibraryModule= not in Constructor: - Constructor.append(LibraryModule) + Constructor.add(LibraryModule) =20 - if LibraryModule not in ConsumedByList: - ConsumedByList[LibraryModule] =3D [] # don't add current module itself to consumer list if M !=3D Module: if M in ConsumedByList[LibraryModule]: @@ -2235,8 +2237,8 @@ class PlatformAutoGen(AutoGen): # # Q <- Set of all nodes with no incoming edges # - LibraryList =3D [] #LibraryInstance.values() - Q =3D [] + LibraryList =3D [] + Q =3D deque() for LibraryClassName in LibraryInstance: M =3D LibraryInstance[LibraryClassName] LibraryList.append(M) @@ -2248,7 +2250,7 @@ class PlatformAutoGen(AutoGen): # while True: EdgeRemoved =3D True - while Q =3D=3D [] and EdgeRemoved: + while not Q and EdgeRemoved: EdgeRemoved =3D False # for each node Item with a Constructor for Item in LibraryList: @@ -2263,12 +2265,12 @@ class PlatformAutoGen(AutoGen): EdgeRemoved =3D True if ConsumedByList[Item] =3D=3D []: # insert Item into Q - Q.insert(0, Item) + Q.appendleft(Item) break - if Q !=3D []: + if Q: break # DAG is done if there's no more incoming edge for all nodes - if Q =3D=3D []: + if not Q: break =20 # remove node from Q @@ -2286,7 +2288,7 @@ class PlatformAutoGen(AutoGen): if ConsumedByList[Item] !=3D []: continue # insert Item into Q, if Item has no other incoming edges - Q.insert(0, Item) + Q.appendleft(Item) =20 # # if any remaining node Item in the graph has a constructor and an= incoming edge, then the graph has a cycle diff --git a/BaseTools/Source/Python/GenFds/FdfParser.py b/BaseTools/Source= /Python/GenFds/FdfParser.py index 8d1a4b543f0e..d511cf4f9d5a 100644 --- a/BaseTools/Source/Python/GenFds/FdfParser.py +++ b/BaseTools/Source/Python/GenFds/FdfParser.py @@ -43,6 +43,7 @@ import OptionRom import OptRomInfStatement import OptRomFileStatement import string +from collections import deque =20 from GenFdsGlobalVariable import GenFdsGlobalVariable from Common.BuildToolError import * @@ -89,7 +90,7 @@ BaseAddrValuePattern =3D re.compile('^0[xX][0-9a-fA-F]+') FileExtensionPattern =3D re.compile(r'([a-zA-Z][a-zA-Z0-9]*)') TokenFindPattern =3D re.compile(r'([a-zA-Z0-9\-]+|\$\(TARGET\)|\*)_([a-zA-= Z0-9\-]+|\$\(TOOL_CHAIN_TAG\)|\*)_([a-zA-Z0-9\-]+|\$\(ARCH\)|\*)') =20 -AllIncludeFileList =3D [] +AllIncludeFileList =3D deque() =20 # Get the closest parent def GetParentAtLine (Line): @@ -685,7 +686,7 @@ class FdfParser: InsertAtLine +=3D 1 =20 # reversely sorted to better determine error in file - AllIncludeFileList.insert(0, IncFileProfile) + AllIncludeFileList.appendleft(IncFileProfile) =20 # comment out the processed include file statement TempList =3D list(self.Profile.FileLinesList[IncludeLine -= 1]) diff --git a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py b/BaseToo= ls/Source/Python/Workspace/WorkspaceCommon.py index 573100081815..a793055b6d18 100644 --- a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py +++ b/BaseTools/Source/Python/Workspace/WorkspaceCommon.py @@ -11,7 +11,7 @@ # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMP= LIED. # =20 -from collections import OrderedDict, defaultdict +from collections import OrderedDict, defaultdict, deque from Common.DataType import SUP_MODULE_USER_DEFINED from BuildClassObject import LibraryClassObject import Common.GlobalData as GlobalData @@ -110,7 +110,7 @@ def _GetModuleLibraryInstances(Module, Platform, BuildD= atabase, Arch, Target, To =20 # EdkII module LibraryConsumerList =3D [Module] - Constructor =3D [] + Constructor =3D set() ConsumedByList =3D OrderedListDict() LibraryInstance =3D OrderedDict() =20 @@ -148,7 +148,7 @@ def _GetModuleLibraryInstances(Module, Platform, BuildD= atabase, Arch, Target, To continue =20 if LibraryModule.ConstructorList !=3D [] and LibraryModule not= in Constructor: - Constructor.append(LibraryModule) + Constructor.add(LibraryModule) =20 # don't add current module itself to consumer list if M !=3D Module: @@ -162,8 +162,8 @@ def _GetModuleLibraryInstances(Module, Platform, BuildD= atabase, Arch, Target, To # # Q <- Set of all nodes with no incoming edges # - LibraryList =3D [] #LibraryInstance.values() - Q =3D [] + LibraryList =3D [] + Q =3D deque() for LibraryClassName in LibraryInstance: M =3D LibraryInstance[LibraryClassName] LibraryList.append(M) @@ -175,7 +175,7 @@ def _GetModuleLibraryInstances(Module, Platform, BuildD= atabase, Arch, Target, To # while True: EdgeRemoved =3D True - while Q =3D=3D [] and EdgeRemoved: + while not Q and EdgeRemoved: EdgeRemoved =3D False # for each node Item with a Constructor for Item in LibraryList: @@ -190,12 +190,12 @@ def _GetModuleLibraryInstances(Module, Platform, Buil= dDatabase, Arch, Target, To EdgeRemoved =3D True if len(ConsumedByList[Item]) =3D=3D 0: # insert Item into Q - Q.insert(0, Item) + Q.appendleft(Item) break - if Q !=3D []: + if Q: break # DAG is done if there's no more incoming edge for all nodes - if Q =3D=3D []: + if not Q: break =20 # remove node from Q @@ -213,7 +213,7 @@ def _GetModuleLibraryInstances(Module, Platform, BuildD= atabase, Arch, Target, To if len(ConsumedByList[Item]) !=3D 0: continue # insert Item into Q, if Item has no other incoming edges - Q.insert(0, Item) + Q.appendleft(Item) =20 # # if any remaining node Item in the graph has a constructor and an inc= oming edge, then the graph has a cycle --=20 2.16.2.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Fri May 3 05:47:03 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 1526321403089255.18128590296863; Mon, 14 May 2018 11:10:03 -0700 (PDT) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 0A5382096967F; Mon, 14 May 2018 11:09:30 -0700 (PDT) Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 592A621CB74A7 for ; Mon, 14 May 2018 11:09:25 -0700 (PDT) Received: from orsmga001.jf.intel.com ([10.7.209.18]) by orsmga105.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 14 May 2018 11:09:24 -0700 Received: from jcarsey-desk1.amr.corp.intel.com ([10.7.159.144]) by orsmga001.jf.intel.com with ESMTP; 14 May 2018 11:09:24 -0700 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.100; helo=mga07.intel.com; envelope-from=jaben.carsey@intel.com; receiver=edk2-devel@lists.01.org X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.49,401,1520924400"; d="scan'208";a="55814283" From: Jaben Carsey To: edk2-devel@lists.01.org Date: Mon, 14 May 2018 11:09:18 -0700 Message-Id: X-Mailer: git-send-email 2.16.2.windows.1 In-Reply-To: References: In-Reply-To: References: Subject: [edk2] [PATCH v1 09/11] BaseTools: refactor to stop re-allocating strings X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.26 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Liming Gao MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" strings are immutable. allocate minimal duplication. Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jaben Carsey --- BaseTools/Source/Python/AutoGen/AutoGen.py | 94 ++++++++++= +--------- BaseTools/Source/Python/AutoGen/GenC.py | 2 +- BaseTools/Source/Python/AutoGen/GenDepex.py | 15 ++-- BaseTools/Source/Python/AutoGen/GenMake.py | 6 +- BaseTools/Source/Python/AutoGen/GenVar.py | 2 +- BaseTools/Source/Python/AutoGen/IdfClassObject.py | 2 +- BaseTools/Source/Python/AutoGen/StrGather.py | 4 +- BaseTools/Source/Python/AutoGen/UniClassObject.py | 3 +- BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py | 17 ++-- BaseTools/Source/Python/Common/Expression.py | 42 +++++---- BaseTools/Source/Python/Common/Misc.py | 8 +- BaseTools/Source/Python/Common/String.py | 2 +- BaseTools/Source/Python/CommonDataClass/CommonClass.py | 29 +++--- BaseTools/Source/Python/GenFds/Capsule.py | 19 ++-- BaseTools/Source/Python/GenFds/FdfParser.py | 8 +- BaseTools/Source/Python/GenFds/FfsInfStatement.py | 8 +- BaseTools/Source/Python/GenFds/Fv.py | 72 +++++-----= ----- BaseTools/Source/Python/GenFds/GenFds.py | 4 +- BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py | 24 ++--- BaseTools/Source/Python/GenFds/OptionRom.py | 2 - BaseTools/Source/Python/GenFds/Vtf.py | 76 +++++-----= ------ BaseTools/Source/Python/Table/TableDataModel.py | 11 +-- BaseTools/Source/Python/Workspace/DscBuildData.py | 14 +-- BaseTools/Source/Python/Workspace/InfBuildData.py | 4 +- BaseTools/Source/Python/Workspace/MetaDataTable.py | 10 +-- BaseTools/Source/Python/Workspace/MetaFileParser.py | 4 +- 26 files changed, 196 insertions(+), 286 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/AutoGen.py b/BaseTools/Source/= Python/AutoGen/AutoGen.py index 599331060187..4ccb50a0a0af 100644 --- a/BaseTools/Source/Python/AutoGen/AutoGen.py +++ b/BaseTools/Source/Python/AutoGen/AutoGen.py @@ -815,42 +815,46 @@ class WorkspaceAutoGen(AutoGen): _PcdName =3D FfsFile.NameGuid.lstrip("PCD(").rstri= p(")") PcdFoundFlag =3D False for Pa in self.AutoGenObjectList: - if not PcdFoundFlag: - for PcdItem in Pa.AllPcdList: - if (PcdItem.TokenSpaceGuidCName + "." = + PcdItem.TokenCName) =3D=3D _PcdName: + # + # once found, get out of the loop + # + if PcdFoundFlag: + break + for PcdItem in Pa.AllPcdList: + if "{TSG}.{CN}".format(TSG=3DPcdItem.Token= SpaceGuidCName, CN=3DPcdItem.TokenCName) =3D=3D _PcdName: + # + # First convert from CFormatGuid to GU= ID string + # + _PcdGuidString =3D GuidStructureString= ToGuidString(PcdItem.DefaultValue) + + if not _PcdGuidString: # - # First convert from CFormatGuid t= o GUID string + # Then try Byte array. # - _PcdGuidString =3D GuidStructureSt= ringToGuidString(PcdItem.DefaultValue) - - if not _PcdGuidString: - # - # Then try Byte array. - # - _PcdGuidString =3D GuidStructu= reByteArrayToGuidString(PcdItem.DefaultValue) + _PcdGuidString =3D GuidStructureBy= teArrayToGuidString(PcdItem.DefaultValue) =20 - if not _PcdGuidString: - # - # Not Byte array or CFormat GU= ID, raise error. - # - EdkLogger.error("build", - FORMAT_INVALID, - "The format of= PCD value is incorrect. PCD: %s , Value: %s\n" % (_PcdName, PcdItem.Defaul= tValue), - ExtraData=3Dse= lf.FdfFile) + if not _PcdGuidString: + # + # Not Byte array or CFormat GUID, = raise error. + # + EdkLogger.error("build", + FORMAT_INVALID, + "The format of PCD= value is incorrect. PCD: %s , Value: %s\n" % (_PcdName, PcdItem.DefaultVal= ue), + ExtraData=3Dself.F= dfFile) =20 - if _PcdGuidString.upper() not in _= GuidDict: - _GuidDict[_PcdGuidString.upper= ()] =3D FfsFile - PcdFoundFlag =3D True - break - else: - EdkLogger.error("build", - FORMAT_INVALID, - "Duplicate GUI= D found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.= CurrentLineNum, - = FfsFile.Cu= rrentLineContent, - = _GuidDict[= _PcdGuidString.upper()].CurrentLineNum, - = _GuidDict[= _PcdGuidString.upper()].CurrentLineContent, - = FfsFile.Na= meGuid.upper()), - ExtraData=3Dse= lf.FdfFile) + if _PcdGuidString.upper() not in _Guid= Dict: + _GuidDict[_PcdGuidString.upper()] = =3D FfsFile + PcdFoundFlag =3D True + break + else: + EdkLogger.error("build", + FORMAT_INVALID, + "Duplicate GUID fo= und for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.Curr= entLineNum, + = FfsFile.Curren= tLineContent, + = _GuidDict[_Pcd= GuidString.upper()].CurrentLineNum, + = _GuidDict[_Pcd= GuidString.upper()].CurrentLineContent, + = FfsFile.NameGu= id.upper()), + ExtraData=3Dself.F= dfFile) =20 if FfsFile.NameGuid.upper() not in _GuidDict: _GuidDict[FfsFile.NameGuid.upper()] =3D FfsFile @@ -1832,13 +1836,13 @@ class PlatformAutoGen(AutoGen): if os.path.isabs(self.OutputDir): self._BuildDir =3D path.join( path.abspath(self.OutputDir), - self.BuildTarget + "_" + self.= ToolChain, + "{BT}_{TC}".format(BT=3Dself.B= uildTarget, TC=3Dself.ToolChain), ) else: self._BuildDir =3D path.join( self.WorkspaceDir, self.OutputDir, - self.BuildTarget + "_" + self.= ToolChain, + "{BT}_{TC}".format(BT=3Dself.B= uildTarget, TC=3Dself.ToolChain), ) GlobalData.gBuildDirectory =3D self._BuildDir return self._BuildDir @@ -1916,7 +1920,7 @@ class PlatformAutoGen(AutoGen): Value =3D self.BuildOption[Tool][Attr][1:] else: if Attr !=3D 'PATH': - Value +=3D " " + self.BuildOption[Tool][At= tr] + Value =3D "{Val} {At}".format(Val=3DValue,= At=3Dself.BuildOption[Tool][Attr]) else: Value =3D self.BuildOption[Tool][Attr] =20 @@ -1934,8 +1938,10 @@ class PlatformAutoGen(AutoGen): ToolsDef +=3D "\n" =20 SaveFileOnChange(self.ToolDefinitionFile, ToolsDef) - for DllPath in DllPathList: - os.environ["PATH"] =3D DllPath + os.pathsep + os.environ["= PATH"] + os.environ["PATH"]=3D'{new}{sep}{start}'.format( + new=3Dos.pathsep.join(DllPathList), + sep=3Dos.pathsep, + start=3Dos.environ["PATH"]) os.environ["MAKE_FLAGS"] =3D MakeFlags =20 return self._ToolDefinitions @@ -1943,7 +1949,7 @@ class PlatformAutoGen(AutoGen): ## Return the paths of tools def _GetToolDefFile(self): if self._ToolDefFile is None: - self._ToolDefFile =3D os.path.join(self.MakeFileDir, "TOOLS_DE= F." + self.Arch) + self._ToolDefFile =3D os.path.join(self.MakeFileDir, "TOOLS_DE= F.{ARCH}".format(ARCH=3Dself.Arch)) return self._ToolDefFile =20 ## Retrieve the toolchain family of given toolchain tag. Default to 'M= SFT'. @@ -2215,7 +2221,7 @@ class PlatformAutoGen(AutoGen): =20 LibraryInstance[LibraryClassName] =3D LibraryModule LibraryConsumerList.append(LibraryModule) - EdkLogger.verbose("\t" + str(LibraryClassName) + " : "= + str(LibraryModule)) + EdkLogger.verbose("\t{LCN}:{LM}".format(LCN=3Dstr(Libr= aryClassName), LM=3Dstr(LibraryModule))) else: LibraryModule =3D LibraryInstance[LibraryClassName] =20 @@ -2295,7 +2301,7 @@ class PlatformAutoGen(AutoGen): # for Item in LibraryList: if ConsumedByList[Item] !=3D [] and Item in Constructor and le= n(Constructor) > 1: - ErrorMessage =3D "\tconsumed by " + "\n\tconsumed by ".joi= n(str(L) for L in ConsumedByList[Item]) + ErrorMessage =3D "\tconsumed by {LIST}".format(LIST=3D"\n\= tconsumed by ".join(str(L) for L in ConsumedByList[Item])) EdkLogger.error("build", BUILD_ERROR, 'Library [%s] with c= onstructors has a cycle' % str(Item), ExtraData=3DErrorMessage, File=3Dself.Meta= File) if Item not in SortedLibraryList: @@ -2491,7 +2497,7 @@ class PlatformAutoGen(AutoGen): if Library not in LibraryList: LibraryList.append(Library) LibraryConsumerList.append(Library) - EdkLogger.verbose("\t" + LibraryName + " : " + str(Lib= rary) + ' ' + str(type(Library))) + EdkLogger.verbose("\t{LN}:{LIB} {TYPE}".format(LN=3DLi= braryName, LIB=3Dstr(Library), TYPE=3Dstr(type(Library)))) return LibraryList =20 ## Calculate the priority value of the build option @@ -2604,7 +2610,7 @@ class PlatformAutoGen(AutoGen): else: # append options for the same tool except PATH if Attr !=3D 'PATH': - BuildOptions[Tool][Attr] +=3D " " + Option= s[Key] + BuildOptions[Tool][Attr] =3D "{ORIG} {NEW}= ".format(ORIG=3DBuildOptions[Tool][Attr], NEW=3DOptions[Key]) else: BuildOptions[Tool][Attr] =3D Options[Key] # Build Option Family has been checked, which need't to be checked= again for family. @@ -2639,7 +2645,7 @@ class PlatformAutoGen(AutoGen): else: # append options for the same tool except PATH if Attr !=3D 'PATH': - BuildOptions[Tool][Attr] +=3D " " + Option= s[Key] + BuildOptions[Tool][Attr] =3D "{ORIG} {NEW}= ".format(ORIG=3DBuildOptions[Tool][Attr], NEW=3DOptions[Key]) else: BuildOptions[Tool][Attr] =3D Options[Key] return BuildOptions @@ -2693,7 +2699,7 @@ class PlatformAutoGen(AutoGen): BuildOptions[Tool][Attr] =3D mws.handleWsMacro(Val= ue[1:]) else: if Attr !=3D 'PATH': - BuildOptions[Tool][Attr] +=3D " " + mws.handle= WsMacro(Value) + BuildOptions[Tool][Attr] =3D "{ORIG} {NEW}".fo= rmat(ORIG=3DBuildOptions[Tool][Attr], NEW=3Dmws.handleWsMacro(Value)) else: BuildOptions[Tool][Attr] =3D mws.handleWsMacro= (Value) =20 diff --git a/BaseTools/Source/Python/AutoGen/GenC.py b/BaseTools/Source/Pyt= hon/AutoGen/GenC.py index 46c7c1c1390b..e73d83395255 100644 --- a/BaseTools/Source/Python/AutoGen/GenC.py +++ b/BaseTools/Source/Python/AutoGen/GenC.py @@ -917,7 +917,7 @@ def CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd): TokenNumber =3D PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceG= uidCName] AutoGenH.Append('\n#define %s %dU\n' % (PcdTokenName, TokenNumber= )) =20 - EdkLogger.debug(EdkLogger.DEBUG_3, "Creating code for " + TokenCName += "." + Pcd.TokenSpaceGuidCName) + EdkLogger.debug(EdkLogger.DEBUG_3, "Creating code for {TCN}.{CN}".form= at(TCN=3DTokenCName, CN=3DPcd.TokenSpaceGuidCName)) if Pcd.Type not in gItemTypeStringDatabase: EdkLogger.error("build", AUTOGEN_ERROR, "Unknown PCD type [%s] of PCD %s.%s" % (Pcd.Type, = Pcd.TokenSpaceGuidCName, TokenCName), diff --git a/BaseTools/Source/Python/AutoGen/GenDepex.py b/BaseTools/Source= /Python/AutoGen/GenDepex.py index ed5df2b75440..873ed6e59300 100644 --- a/BaseTools/Source/Python/AutoGen/GenDepex.py +++ b/BaseTools/Source/Python/AutoGen/GenDepex.py @@ -156,19 +156,16 @@ class DependencyExpression: EdkLogger.debug(EdkLogger.DEBUG_8, repr(self)) if Optimize: self.Optimize() - EdkLogger.debug(EdkLogger.DEBUG_8, "\n Optimized: " + repr(= self)) + EdkLogger.debug(EdkLogger.DEBUG_8, "\n Optimized: {ME}".for= mat(ME=3Drepr(self))) =20 def __str__(self): return " ".join(self.TokenList) =20 def __repr__(self): - WellForm =3D '' - for Token in self.PostfixNotation: - if Token in self.SupportedOpcode: - WellForm +=3D "\n " + Token - else: - WellForm +=3D ' ' + Token - return WellForm + return ''.join("{sep}{tok}".format( + tok=3DToken, + sep=3D"\n " if Token in DependencyExpression.SupportedO= pcode else ' ') + for Token in self.PostfixNotation) =20 ## Split the expression string into token list def GetExpressionTokenList(self): @@ -359,11 +356,9 @@ class DependencyExpression: else: Buffer.write(self.GetGuidValue(Item)) =20 - FilePath =3D "" FileChangeFlag =3D True if File is None: sys.stdout.write(Buffer.getvalue()) - FilePath =3D "STDOUT" else: FileChangeFlag =3D SaveFileOnChange(File, Buffer.getvalue(), T= rue) =20 diff --git a/BaseTools/Source/Python/AutoGen/GenMake.py b/BaseTools/Source/= Python/AutoGen/GenMake.py index 30280d449f62..4ae977ccd400 100644 --- a/BaseTools/Source/Python/AutoGen/GenMake.py +++ b/BaseTools/Source/Python/AutoGen/GenMake.py @@ -1029,7 +1029,7 @@ cleanlib: with open(F.Path, 'r') as f: FileContent =3D f.read() except BaseException, X: - EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData= =3DF.Path + "\n\t" + str(X)) + EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData= =3D"{PATH}\n\t{VAL}".format(PATH=3DF.Path, VAL=3Dstr(X))) =20 if len(FileContent) =3D=3D 0: continue @@ -1552,9 +1552,9 @@ class TopLevelMakefile(BuildFile): else: pcdname =3D '.'.join(pcd[0:2]) if pcd[3].startswith('{'): - ExtraOption +=3D " --pcd " + pcdname + '=3D' + 'H' + '"' += pcd[3] + '"' + ExtraOption =3D '{ORIG} --pcd {NAME}=3DH"{VAL}"'.format(NA= ME=3Dpcdname, VAL=3Dpcd[3], ORIG=3DExtraOption) else: - ExtraOption +=3D " --pcd " + pcdname + '=3D' + pcd[3] + ExtraOption =3D "{ORIG} --pcd {NAME}=3D{VAL}".format(NAME= =3Dpcdname, VAL=3Dpcd[3], ORIG=3DExtraOption) =20 MakefileName =3D self._FILE_NAME_[self._FileType] SubBuildCommandList =3D [] diff --git a/BaseTools/Source/Python/AutoGen/GenVar.py b/BaseTools/Source/P= ython/AutoGen/GenVar.py index 2eab278d6876..35f022ac2e19 100644 --- a/BaseTools/Source/Python/AutoGen/GenVar.py +++ b/BaseTools/Source/Python/AutoGen/GenVar.py @@ -78,7 +78,7 @@ class VariableMgr(object): value_list +=3D [hex(unpack("B",data_byte)[0])] newvalue[int(item.var_offset,16) if item.var_offset.upper(= ).startswith("0X") else int(item.var_offset)] =3D value_list try: - newvaluestr =3D "{" + ",".join(VariableMgr.assemble_variab= le(newvalue)) +"}" + newvaluestr =3D '{{{mid}}}'.format(mid=3D",".join(Variable= Mgr.assemble_variable(newvalue))) except: EdkLogger.error("build", AUTOGEN_ERROR, "Variable offset c= onflict in PCDs: %s \n" % (" and ".join(item.pcdname for item in sku_var_in= fo_offset_list))) n =3D sku_var_info_offset_list[0] diff --git a/BaseTools/Source/Python/AutoGen/IdfClassObject.py b/BaseTools/= Source/Python/AutoGen/IdfClassObject.py index 8b84806f9f36..8a1f51daf435 100644 --- a/BaseTools/Source/Python/AutoGen/IdfClassObject.py +++ b/BaseTools/Source/Python/AutoGen/IdfClassObject.py @@ -121,7 +121,7 @@ def SearchImageID(ImageFileObject, FileList): for Line in f: ImageIdList =3D IMAGE_TOKEN.findall(Line) for ID in ImageIdList: - EdkLogger.debug(EdkLogger.DEBUG_5, "Found ImageID = identifier: " + ID) + EdkLogger.debug(EdkLogger.DEBUG_5, "Found ImageID = identifier: {id}".format(id=3DID)) ImageFileObject.SetImageIDReferenced(ID) =20 class ImageFileObject(object): diff --git a/BaseTools/Source/Python/AutoGen/StrGather.py b/BaseTools/Sourc= e/Python/AutoGen/StrGather.py index c0a39e4a12f1..bc5a23e9d920 100644 --- a/BaseTools/Source/Python/AutoGen/StrGather.py +++ b/BaseTools/Source/Python/AutoGen/StrGather.py @@ -110,7 +110,7 @@ def DecToHexStr(Dec, Digit =3D 8): # def DecToHexList(Dec, Digit =3D 8): Hex =3D '{0:0{1}X}'.format(Dec,Digit) - return ["0x" + Hex[Bit:Bit + 2] for Bit in range(Digit - 2, -1, -2)] + return ["0x{HEX}".format(HEX=3DHex[Bit:Bit + 2]) for Bit in range(Digi= t - 2, -1, -2)] =20 ## Convert a acsii string to a hex list # @@ -532,7 +532,7 @@ def SearchString(UniObjectClass, FileList, IsCompatible= Mode): with open(File, 'r') as f: for Line in f: for StrName in STRING_TOKEN.findall(Line): - EdkLogger.debug(EdkLogger.DEBUG_5, "Found string i= dentifier: " + StrName) + EdkLogger.debug(EdkLogger.DEBUG_5, "Found string i= dentifier: {NAME}".format(NAME=3DStrName)) UniObjectClass.SetStringReferenced(StrName) =20 UniObjectClass.ReToken() diff --git a/BaseTools/Source/Python/AutoGen/UniClassObject.py b/BaseTools/= Source/Python/AutoGen/UniClassObject.py index bb37fbfd6a0c..73ca5b54778f 100644 --- a/BaseTools/Source/Python/AutoGen/UniClassObject.py +++ b/BaseTools/Source/Python/AutoGen/UniClassObject.py @@ -161,8 +161,7 @@ class Ucs2Codec(codecs.Codec): for Char in input: CodePoint =3D ord(Char) if CodePoint >=3D 0xd800 and CodePoint <=3D 0xdfff: - raise ValueError("Code Point is in range reserved for " + - "UTF-16 surrogate pairs") + raise ValueError("Code Point is in range reserved for UTF-= 16 surrogate pairs") elif CodePoint > 0xffff: raise ValueError("Code Point too large to encode in UCS-2") return self.__utf16.encode(input) diff --git a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py b/B= aseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py index 2c6bb8e396a9..b2a9bb1134ed 100644 --- a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py +++ b/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py @@ -186,7 +186,7 @@ class VAR_CHECK_PCD_VARIABLE_TAB(object): self.Type =3D 0 self.Reserved =3D 0 self.Attributes =3D 0x00000000 - self.Guid =3D eval("[" + TokenSpaceGuid.replace("{", "").replace("= }", "") + "]") + self.Guid =3D eval("[{GUID}]".format(GUID=3DTokenSpaceGuid.replace= ("{", "").replace("}", ""))) self.Name =3D PcdCName self.validtab =3D [] =20 @@ -258,7 +258,6 @@ class VAR_CHECK_PCD_VALID_LIST(VAR_CHECK_PCD_VALID_OBJ): else: self.data.add(int(valid_num)) =20 - =20 self.Length =3D 5 + len(self.data) * self.StorageWidth =20 =20 @@ -266,13 +265,10 @@ class VAR_CHECK_PCD_VALID_RANGE(VAR_CHECK_PCD_VALID_O= BJ): def __init__(self, VarOffset, validrange, PcdDataType): super(VAR_CHECK_PCD_VALID_RANGE, self).__init__(VarOffset, validra= nge, PcdDataType) self.Type =3D 2 - RangeExpr =3D "" - i =3D 0 - for item in self.rawdata: - if i =3D=3D 0: - RangeExpr =3D "( " + item + " )" - else: - RangeExpr =3D RangeExpr + "OR ( " + item + " )" + if self.rawdata: + RangeExpr =3D "( {ITEM} )".format(ITEM=3Dself.rawdata[-1]) + else: + RangeExpr =3D "" range_result =3D RangeExpression(RangeExpr, self.PcdDataType)(True) for rangelist in range_result: for obj in rangelist.pop(): @@ -285,5 +281,4 @@ def GetValidationObject(PcdClass, VarOffset): return VAR_CHECK_PCD_VALID_RANGE(VarOffset, PcdClass.validaterange= s, PcdClass.DatumType) if PcdClass.validlists: return VAR_CHECK_PCD_VALID_LIST(VarOffset, PcdClass.validlists, Pc= dClass.DatumType) - else: - return None + return None diff --git a/BaseTools/Source/Python/Common/Expression.py b/BaseTools/Sourc= e/Python/Common/Expression.py index e5d17e6b4de0..36f2654fc9cf 100644 --- a/BaseTools/Source/Python/Common/Expression.py +++ b/BaseTools/Source/Python/Common/Expression.py @@ -133,7 +133,7 @@ def BuildOptionValue(PcdValue, GuidDict): elif PcdValue.startswith(("L'", "'")): InputValue =3D PcdValue elif PcdValue.startswith('L'): - InputValue =3D 'L"' + PcdValue[1:] + '"' + InputValue =3D 'L"{VAL}"'.format(VAL=3DPcdValue[1:]) else: InputValue =3D PcdValue if IsFieldValueAnArray(InputValue): @@ -178,7 +178,7 @@ def ReplaceExprMacro(String, Macros, ExceptionList =3D = None): # For example: DEFINE ARCH =3D IA32 X64 # $(ARCH) is replaced with "IA32 X64" if ExceptionList and Macro in ExceptionList: - RetStr +=3D '"' + Macros[Macro] + '"' + RetStr =3D '{ORIG}"{MACRO}"'.format(MACRO=3DMacros[Mac= ro], ORIG=3DRetStr) elif Macros[Macro].strip(): RetStr +=3D Macros[Macro] else: @@ -197,7 +197,7 @@ def IntToStr(Value): while Value > 0: StrList.append(chr(Value & 0xff)) Value =3D Value >> 8 - Value =3D '"' + ''.join(StrList) + '"' + Value =3D '"{VAL}"'.format(VAL=3D''.join(StrList)) return Value =20 SupportedInMacroList =3D ['TARGET', 'TOOL_CHAIN_TAG', 'ARCH', 'FAMILY'] @@ -223,17 +223,24 @@ class BaseExpression(object): class ValueExpression(BaseExpression): # Logical operator mapping LogicalOperators =3D { - '&&' : 'and', '||' : 'or', - '!' : 'not', 'AND': 'and', - 'OR' : 'or' , 'NOT': 'not', - 'XOR': '^' , 'xor': '^', - 'EQ' : '=3D=3D' , 'NE' : '!=3D', - 'GT' : '>' , 'LT' : '<', - 'GE' : '>=3D' , 'LE' : '<=3D', + '&&' : 'and', + '||' : 'or', + '!' : 'not', + 'AND': 'and', + 'OR' : 'or', + 'NOT': 'not', + 'XOR': '^', + 'xor': '^', + 'EQ' : '=3D=3D', + 'NE' : '!=3D', + 'GT' : '>', + 'LT' : '<', + 'GE' : '>=3D', + 'LE' : '<=3D', 'IN' : 'in' } =20 - NonLetterOpLst =3D ['+', '-', '*', '/', '%', '&', '|', '^', '~', '<<',= '>>', '!', '=3D', '>', '<', '?', ':'] + NonLetterOpLst =3D {'+', '-', '*', '/', '%', '&', '|', '^', '~', '<<',= '>>', '!', '=3D', '>', '<', '?', ':'} =20 =20 SymbolPattern =3D re.compile("(" @@ -710,18 +717,15 @@ class ValueExpression(BaseExpression): if Expr.startswith('L"'): # Skip L self._Idx +=3D 1 - UStr =3D self.__GetString() - self._Token =3D 'L"' + UStr + '"' + self._Token =3D 'L"{STR}"'.format(STR=3Dself.__GetString()) return self._Token elif Expr.startswith("L'"): # Skip L self._Idx +=3D 1 - UStr =3D self.__GetString() - self._Token =3D "L'" + UStr + "'" + self._Token =3D "L'{STR}'".format(STR=3Dself.__GetString()) return self._Token elif Expr.startswith("'"): - UStr =3D self.__GetString() - self._Token =3D "'" + UStr + "'" + self._Token =3D "'{STR}'".format(STR=3Dself.__GetString()) return self._Token elif Expr.startswith('UINT'): Re =3D re.compile('(?:UINT8|UINT16|UINT32|UINT64)\((.+)\)') @@ -758,7 +762,7 @@ class ValueExpression(BaseExpression): return self.__GetString() elif Ch =3D=3D '{': return self.__GetArray() - elif Ch =3D=3D '(' or Ch =3D=3D ')': + elif Ch in {'(', ')'}: self._Idx +=3D 1 self._Token =3D Ch return self._Token @@ -768,7 +772,7 @@ class ValueExpression(BaseExpression): # Parse operator def _GetOperator(self): self.__SkipWS() - LegalOpLst =3D ['&&', '||', '!=3D', '=3D=3D', '>=3D', '<=3D'] + se= lf.NonLetterOpLst + ['?',':'] + LegalOpLst =3D {'&&', '||', '!=3D', '=3D=3D', '>=3D', '<=3D', '?',= ':'}.union(self.NonLetterOpLst) =20 self._Token =3D '' Expr =3D self._Expr[self._Idx:] diff --git a/BaseTools/Source/Python/Common/Misc.py b/BaseTools/Source/Pyth= on/Common/Misc.py index 0bfb26548d9b..bfb6e56a923f 100644 --- a/BaseTools/Source/Python/Common/Misc.py +++ b/BaseTools/Source/Python/Common/Misc.py @@ -713,7 +713,7 @@ class TemplateString(object): self._SubSectionList =3D [TemplateSection] =20 def __str__(self): - return self._Template + " : " + str(self._PlaceHolderList) + return "{TEM} : {LIST}".format(TEM=3Dself._Template, LIST=3Dst= r(self._PlaceHolderList)) =20 def Instantiate(self, PlaceHolderValues): RepeatTime =3D -1 @@ -894,7 +894,7 @@ class Progressor: TimeUp =3D self.Interval time.sleep(self._CheckInterval) TimeUp -=3D self._CheckInterval - sys.stdout.write(" " + self.CodaMessage + "\n") + sys.stdout.write(" {MSG}\n".format(MSG=3Dself.CodaMessage)) sys.stdout.flush() =20 ## Abort the progress display @@ -1313,7 +1313,7 @@ def ParseFieldValue (Value): if Value[0] =3D=3D '"' and Value[-1] =3D=3D '"': Value =3D Value[1:-1] try: - Value =3D "'" + uuid.UUID(Value).get_bytes_le() + "'" + Value =3D "'{GUID}'".format(GUID=3Duuid.UUID(Value).get_bytes_= le()) except ValueError, Message: raise BadExpression('%s' % Message) Value, Size =3D ParseFieldValue(Value) @@ -2050,7 +2050,7 @@ class SkuClass(): ArrayStrList.append(hex(int(self.AvailableSkuIds[skuna= me]))) skuname =3D self.GetNextSkuId(skuname) ArrayStrList.append("0x0") - ArrayStr =3D "{" + ",".join(ArrayStrList) + "}" + ArrayStr =3D "{{{ARRAY}}}".format(ARRAY=3D",".join(ArrayStrLis= t)) return ArrayStr def __GetAvailableSkuIds(self): return self.AvailableSkuIds diff --git a/BaseTools/Source/Python/Common/String.py b/BaseTools/Source/Py= thon/Common/String.py index 34361ecdd58c..1516e6c2ae9c 100644 --- a/BaseTools/Source/Python/Common/String.py +++ b/BaseTools/Source/Python/Common/String.py @@ -712,7 +712,7 @@ def RaiseParserError(Line, Section, File, Format=3D'', = LineNo=3D -1): LineNo =3D GetLineNo(open(os.path.normpath(File), 'r').read(), Lin= e) ErrorMsg =3D "Invalid statement '%s' is found in section '%s'" % (Line= , Section) if Format !=3D '': - Format =3D "Correct format is " + Format + Format =3D "Correct format is {FMT}".format(FMT=3DFormat) EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, File=3DFile, Line=3D= LineNo, ExtraData=3DFormat, RaiseError=3DEdkLogger.IsRaiseError) =20 ## WorkspaceFile diff --git a/BaseTools/Source/Python/CommonDataClass/CommonClass.py b/BaseT= ools/Source/Python/CommonDataClass/CommonClass.py index e29f5211d5c7..d7123fe91ee1 100644 --- a/BaseTools/Source/Python/CommonDataClass/CommonClass.py +++ b/BaseTools/Source/Python/CommonDataClass/CommonClass.py @@ -35,16 +35,14 @@ # @var DefaultValue: To store value for DefaultValue # class SkuInfoClass(object): - def __init__(self, SkuIdName =3D '', SkuId =3D '', VariableName =3D ''= , VariableGuid =3D '', VariableOffset =3D '',=20 - HiiDefaultValue =3D '', VpdOffset =3D '', DefaultValue = =3D '', VariableGuidValue =3D '', VariableAttribute =3D '', DefaultStore = =3D None): + def __init__(self, SkuIdName =3D '', SkuId =3D '', VariableName =3D ''= , VariableGuid =3D '', VariableOffset =3D '', + HiiDefaultValue =3D '', VpdOffset =3D '', DefaultValue = =3D '', VariableGuidValue =3D '', VariableAttribute =3D '', DefaultStore = =3D {}): self.SkuIdName =3D SkuIdName self.SkuId =3D SkuId =20 # # Used by Hii # - if DefaultStore is None: - DefaultStore =3D {} self.VariableName =3D VariableName self.VariableGuid =3D VariableGuid self.VariableGuidValue =3D VariableGuidValue @@ -68,15 +66,18 @@ class SkuInfoClass(object): # Convert each member of the class to string # Organize to a signle line format string # - # @retval Rtn Formatted String + # @retval Formatted String # def __str__(self): - Rtn =3D 'SkuId =3D ' + str(self.SkuId) + "," + \ - 'SkuIdName =3D ' + str(self.SkuIdName) + "," + \ - 'VariableName =3D ' + str(self.VariableName) + "," + \ - 'VariableGuid =3D ' + str(self.VariableGuid) + "," + \ - 'VariableOffset =3D ' + str(self.VariableOffset) + ","= + \ - 'HiiDefaultValue =3D ' + str(self.HiiDefaultValue) + "= ," + \ - 'VpdOffset =3D ' + str(self.VpdOffset) + "," + \ - 'DefaultValue =3D ' + str(self.DefaultValue) + "," - return Rtn + return 'SkuId =3D {SKUID},SkuIdName =3D {SKUNAME},'\ + 'VariableName =3D {VARNAME},VariableGuid =3D {VARGUID},'\ + 'VariableOffset =3D {VAROFFSET},HiiDefaultValue =3D {DEF},'\ + 'VpdOffset =3D {OFFSET},DefaultValue =3D {DEF2},'.format( + SKUID=3Dself.SkuId, + SKUNAME=3Dself.SkuIdName, + VARNAME=3Dself.VariableName, + VARGUID=3Dself.VariableGuid, + VAROFFSET=3Dself.VariableOffset, + DEF=3Dself.HiiDefaultValue, + OFFSET=3Dself.VpdOffset, + DEF2=3Dself.DefaultValue) diff --git a/BaseTools/Source/Python/GenFds/Capsule.py b/BaseTools/Source/P= ython/GenFds/Capsule.py index 6aae2fcb7d97..ab5ea9fc0dd0 100644 --- a/BaseTools/Source/Python/GenFds/Capsule.py +++ b/BaseTools/Source/Python/GenFds/Capsule.py @@ -28,9 +28,8 @@ from struct import pack from GenFds import FindExtendTool from Common import EdkLogger from Common.BuildToolError import * +from Common.DataType import TAB_LINE_BREAK =20 - -T_CHAR_LF =3D '\n' WIN_CERT_REVISION =3D 0x0200 WIN_CERT_TYPE_EFI_GUID =3D 0x0EF1 EFI_CERT_TYPE_PKCS7_GUID =3D uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d37566= 5a7}') @@ -209,16 +208,14 @@ class Capsule (CapsuleClassObject) : return self.GenFmpCapsule() =20 CapInfFile =3D self.GenCapInf() - CapInfFile.writelines("[files]" + T_CHAR_LF) + CapInfFile.writelines("[files]{END}".format(END=3DTAB_LINE_BREAK)) CapFileList =3D [] for CapsuleDataObj in self.CapsuleDataList : CapsuleDataObj.CapsuleName =3D self.CapsuleName FileName =3D CapsuleDataObj.GenCapsuleSubItem() CapsuleDataObj.CapsuleName =3D None CapFileList.append(FileName) - CapInfFile.writelines("EFI_FILE_NAME =3D " + \ - FileName + \ - T_CHAR_LF) + CapInfFile.writelines("EFI_FILE_NAME =3D {NAME}{END}".format(N= AME=3DFileName, END=3DTAB_LINE_BREAK)) SaveFileOnChange(self.CapInfFileName, CapInfFile.getvalue(), False) CapInfFile.close() # @@ -245,16 +242,12 @@ class Capsule (CapsuleClassObject) : # def GenCapInf(self): self.CapInfFileName =3D os.path.join(GenFdsGlobalVariable.FvDir, - self.UiCapsuleName + "_Cap" + '.inf') + "{NAME}_Cap.inf".format(NAME=3Dself.UiC= apsuleName)) CapInfFile =3D StringIO.StringIO() =20 - CapInfFile.writelines("[options]" + T_CHAR_LF) + CapInfFile.writelines("[options]{END}".format(END=3DTAB_LINE_BREAK= )) =20 for Item in self.TokensDict: - CapInfFile.writelines("EFI_" + \ - Item + \ - ' =3D ' + \ - self.TokensDict[Item] + \ - T_CHAR_LF) + CapInfFile.writelines("EFI_{ITEM} =3D {ENTRY}{END}".format(ITE= M=3DItem, ENTRY=3Dself.TokensDict[Item], END=3DTAB_LINE_BREAK)) =20 return CapInfFile diff --git a/BaseTools/Source/Python/GenFds/FdfParser.py b/BaseTools/Source= /Python/GenFds/FdfParser.py index d511cf4f9d5a..55348083b954 100644 --- a/BaseTools/Source/Python/GenFds/FdfParser.py +++ b/BaseTools/Source/Python/GenFds/FdfParser.py @@ -2019,9 +2019,9 @@ class FdfParser: AllStrLen =3D len (AllString) DataString =3D "" while AllStrLen > 4: - DataString =3D DataString + "0x" + AllString[AllStrLen - 2: Al= lStrLen] + "," + DataString =3D "{ORIG}0x{VAL},".format(ORIG=3DDataString, VAL= =3DAllString[AllStrLen - 2: AllStrLen]) AllStrLen =3D AllStrLen - 2 - DataString =3D DataString + AllString[:AllStrLen] + "," + DataString =3D "{ORIG}{VAL},".format(ORIG=3DDataString, VAL=3DAllS= tring[:AllStrLen]) =20 # byte value array if len (self.__Token) <=3D 4: @@ -2059,9 +2059,9 @@ class FdfParser: AllStrLen =3D len (AllString) DataString =3D "" while AllStrLen > 4: - DataString =3D DataString + "0x" + AllString[AllStrLen - 2= : AllStrLen] + "," + DataString =3D "{ORIG}0x{VAL},".format(ORIG=3DDataString, = VAL=3DAllString[AllStrLen - 2: AllStrLen]) AllStrLen =3D AllStrLen - 2 - DataString =3D DataString + AllString[:AllStrLen] + "," + DataString =3D "{ORIG}{VAL},".format(ORIG=3DDataString, VAL=3D= AllString[:AllStrLen]) =20 # byte value array if len (self.__Token) <=3D 4: diff --git a/BaseTools/Source/Python/GenFds/FfsInfStatement.py b/BaseTools/= Source/Python/GenFds/FfsInfStatement.py index 39426b939b4a..e4276c3a8c07 100644 --- a/BaseTools/Source/Python/GenFds/FfsInfStatement.py +++ b/BaseTools/Source/Python/GenFds/FfsInfStatement.py @@ -361,7 +361,7 @@ class FfsInfStatement(FfsInfStatementClassObject): os.makedirs(self.OutputPath) =20 self.EfiOutputPath, self.EfiDebugPath =3D self.__GetEFIOutPutPath_= _() - GenFdsGlobalVariable.VerboseLogger( "ModuelEFIPath: " + self.EfiOu= tputPath) + GenFdsGlobalVariable.VerboseLogger( "ModuelEFIPath: {PATH}".format= (PATH=3Dself.EfiOutputPath)) =20 ## PatchEfiFile # @@ -564,7 +564,7 @@ class FfsInfStatement(FfsInfStatementClassObject): =20 Rule =3D GenFdsGlobalVariable.FdfParser.Profile.RuleDict.get(R= uleName) if Rule is not None: - GenFdsGlobalVariable.VerboseLogger ("Want To Find Rule Nam= e is : " + RuleName) + GenFdsGlobalVariable.VerboseLogger ("Want To Find Rule Nam= e is : {NAME}".format(NAME=3DRuleName)) return Rule =20 RuleName =3D 'RULE' + \ @@ -582,7 +582,7 @@ class FfsInfStatement(FfsInfStatementClassObject): =20 Rule =3D GenFdsGlobalVariable.FdfParser.Profile.RuleDict.get(RuleN= ame) if Rule is not None: - GenFdsGlobalVariable.VerboseLogger ("Want To Find Rule Name is= : " + RuleName) + GenFdsGlobalVariable.VerboseLogger ("Want To Find Rule Name is= : {NAME}".format(NAME=3DRuleName)) return Rule =20 if Rule is None : @@ -634,7 +634,7 @@ class FfsInfStatement(FfsInfStatementClassObject): CurArchList =3D TargetArchList if PlatformArchList !=3D []: CurArchList =3D list(set (TargetArchList) & set (PlatformArchL= ist)) - GenFdsGlobalVariable.VerboseLogger ("Valid target architecture(s) = is : " + " ".join(CurArchList)) + GenFdsGlobalVariable.VerboseLogger ("Valid target architecture(s) = is : {ARCH}".format(ARCH=3D" ".join(CurArchList))) =20 ArchList =3D [] if self.KeyStringList !=3D []: diff --git a/BaseTools/Source/Python/GenFds/Fv.py b/BaseTools/Source/Python= /GenFds/Fv.py index d4b0611fc55a..c672f1d7d8fa 100644 --- a/BaseTools/Source/Python/GenFds/Fv.py +++ b/BaseTools/Source/Python/GenFds/Fv.py @@ -108,9 +108,7 @@ class FV (FvClassObject): FfsFileList.append(FileName) # Add Apriori file name to Inf file if not Flag: - self.FvInfFile.writelines("EFI_FILE_NAME =3D " + \ - FileName + \ - TAB_LINE_BREAK) + self.FvInfFile.writelines("EFI_FILE_NAME =3D {FN}{END}".fo= rmat(FN=3DFileName, END=3DTAB_LINE_BREAK)) =20 # Process Modules in FfsList for FfsFile in self.FfsList : @@ -122,9 +120,7 @@ class FV (FvClassObject): FileName =3D FfsFile.GenFfs(MacroDict, FvParentAddr=3DBaseAddr= ess, IsMakefile=3DFlag, FvName=3Dself.UiFvName) FfsFileList.append(FileName) if not Flag: - self.FvInfFile.writelines("EFI_FILE_NAME =3D " + \ - FileName + \ - TAB_LINE_BREAK) + self.FvInfFile.writelines("EFI_FILE_NAME =3D {FN}{END}".fo= rmat(FN=3DFileName, END=3DTAB_LINE_BREAK)) if not Flag: SaveFileOnChange(self.InfFileName, self.FvInfFile.getvalue(), = False) self.FvInfFile.close() @@ -267,67 +263,46 @@ class FV (FvClassObject): # # Add [Options] # - self.FvInfFile.writelines("[options]" + TAB_LINE_BREAK) + self.FvInfFile.writelines("[options]{END}".format(END=3DTAB_LINE_B= REAK)) if BaseAddress is not None : - self.FvInfFile.writelines("EFI_BASE_ADDRESS =3D " + \ - BaseAddress + \ - TAB_LINE_BREAK) + self.FvInfFile.writelines("EFI_BASE_ADDRESS =3D {BA}{END}".for= mat(BA=3DBaseAddress,END=3DTAB_LINE_BREAK)) =20 if BlockSize is not None: - self.FvInfFile.writelines("EFI_BLOCK_SIZE =3D " + \ - '0x%X' %BlockSize + \ - TAB_LINE_BREAK) + self.FvInfFile.writelines("EFI_BLOCK_SIZE =3D 0x{BS:x}{END}".f= ormat(BS=3DBlockSize,END=3DTAB_LINE_BREAK)) if BlockNum is not None: - self.FvInfFile.writelines("EFI_NUM_BLOCKS =3D " + \ - ' 0x%X' %BlockNum + \ - TAB_LINE_BREAK) + self.FvInfFile.writelines("EFI_NUM_BLOCKS =3D 0x{BN:x}{E= ND}".format(BN=3DBlockNum, END=3DTAB_LINE_BREAK)) else: if self.BlockSizeList =3D=3D []: if not self._GetBlockSize(): #set default block size is 1 - self.FvInfFile.writelines("EFI_BLOCK_SIZE =3D 0x1" + = TAB_LINE_BREAK) + self.FvInfFile.writelines("EFI_BLOCK_SIZE =3D 0x1{END= }".format(END=3DTAB_LINE_BREAK)) =20 for BlockSize in self.BlockSizeList : if BlockSize[0] is not None: - self.FvInfFile.writelines("EFI_BLOCK_SIZE =3D " + \ - '0x%X' %BlockSize[0] + \ - TAB_LINE_BREAK) + self.FvInfFile.writelines("EFI_BLOCK_SIZE =3D 0x{BS:x= }{END}".format(BS=3DBlockSize[0], END=3DTAB_LINE_BREAK)) =20 if BlockSize[1] is not None: - self.FvInfFile.writelines("EFI_NUM_BLOCKS =3D " + \ - ' 0x%X' %BlockSize[1] + \ - TAB_LINE_BREAK) + self.FvInfFile.writelines("EFI_NUM_BLOCKS =3D 0x{BN:= x}{END}".format(BN=3DBlockSize[1], END=3DTAB_LINE_BREAK)) =20 if self.BsBaseAddress is not None: - self.FvInfFile.writelines('EFI_BOOT_DRIVER_BASE_ADDRESS =3D ' = + \ - '0x%X' %self.BsBaseAddress) + self.FvInfFile.writelines('EFI_BOOT_DRIVER_BASE_ADDRESS =3D 0x= {BA:x}'.format(BA=3Dself.BsBaseAddress)) if self.RtBaseAddress is not None: - self.FvInfFile.writelines('EFI_RUNTIME_DRIVER_BASE_ADDRESS =3D= ' + \ - '0x%X' %self.RtBaseAddress) + self.FvInfFile.writelines('EFI_RUNTIME_DRIVER_BASE_ADDRESS =3D= 0x{BA:x}'.format(BA=3Dself.RtBaseAddress)) # # Add attribute # - self.FvInfFile.writelines("[attributes]" + TAB_LINE_BREAK) + self.FvInfFile.writelines("[attributes]{END}".format(END=3DTAB_LIN= E_BREAK)) =20 - self.FvInfFile.writelines("EFI_ERASE_POLARITY =3D " + \ - ' %s' %ErasePloarity + \ - TAB_LINE_BREAK) - if not (self.FvAttributeDict is None): + self.FvInfFile.writelines("EFI_ERASE_POLARITY =3D {EP}{END}".fo= rmat(EP=3DErasePloarity, END=3DTAB_LINE_BREAK)) + if self.FvAttributeDict: for FvAttribute in self.FvAttributeDict.keys() : if FvAttribute =3D=3D "FvUsedSizeEnable": - if self.FvAttributeDict[FvAttribute].upper() in ('TRUE= ', '1') : + if self.FvAttributeDict[FvAttribute].upper() in {'TRUE= ', '1'}: self.UsedSizeEnable =3D True continue - self.FvInfFile.writelines("EFI_" + \ - FvAttribute + \ - ' =3D ' + \ - self.FvAttributeDict[FvAttribute= ] + \ - TAB_LINE_BREAK ) - if self.FvAlignment is not None: - self.FvInfFile.writelines("EFI_FVB2_ALIGNMENT_" + \ - self.FvAlignment.strip() + \ - " =3D TRUE" + \ - TAB_LINE_BREAK) + self.FvInfFile.writelines("EFI_{FA} =3D {VAL}{END}".format= (FA=3DFvAttribute, VAL=3Dself.FvAttributeDict[FvAttribute], END=3DTAB_LINE_= BREAK)) + if self.FvAlignment: + self.FvInfFile.writelines("EFI_FVB2_ALIGNMENT_{FA} =3D TRUE{EN= D}".format(FA=3Dself.FvAlignment.strip(), END=3DTAB_LINE_BREAK)) =20 # # Generate FV extension header file @@ -410,16 +385,11 @@ class FV (FvClassObject): if Changed: if os.path.exists (self.InfFileName): os.remove (self.InfFileName) - self.FvInfFile.writelines("EFI_FV_EXT_HEADER_FILE_NAME =3D= " + \ - FvExtHeaderFileName = + \ - TAB_LINE_BREAK) - + self.FvInfFile.writelines("EFI_FV_EXT_HEADER_FILE_NAME =3D= {NAME}{END}".format(NAME=3DFvExtHeaderFileName, END=3DTAB_LINE_BREAK)) =20 # # Add [Files] # - self.FvInfFile.writelines("[files]" + TAB_LINE_BREAK) + self.FvInfFile.writelines("[files]{END}".format(END=3DTAB_LINE_BRE= AK)) if VtfDict and self.UiFvName in VtfDict: - self.FvInfFile.writelines("EFI_FILE_NAME =3D " = + \ - VtfDict[self.UiFvName] = + \ - TAB_LINE_BREAK) + self.FvInfFile.writelines("EFI_FILE_NAME =3D {NAME}{END}".form= at(NAME=3DVtfDict[self.UiFvName], END=3DTAB_LINE_BREAK)) diff --git a/BaseTools/Source/Python/GenFds/GenFds.py b/BaseTools/Source/Py= thon/GenFds/GenFds.py index f0b51e25dfa2..998bd5345c3c 100644 --- a/BaseTools/Source/Python/GenFds/GenFds.py +++ b/BaseTools/Source/Python/GenFds/GenFds.py @@ -95,7 +95,7 @@ def main(): if 'EDK_SOURCE' in os.environ: GenFdsGlobalVariable.EdkSourceDir =3D os.path.normcase(os.= environ['EDK_SOURCE']) if (Options.debug): - GenFdsGlobalVariable.VerboseLogger("Using Workspace:" + Wo= rkspace) + GenFdsGlobalVariable.VerboseLogger("Using Workspace: {WKSP= }".format(WKSP=3DWorkspace)) if Options.GenfdsMultiThread: GenFdsGlobalVariable.EnableGenfdsMultiThread =3D True os.chdir(GenFdsGlobalVariable.WorkSpaceDir) @@ -207,7 +207,7 @@ def main(): GlobalData.gEdkSource =3D List[1].strip() GlobalData.gGlobalDefines["EDK_SOURCE"] =3D Global= Data.gEdkSource continue - elif List[0].strip() in ["WORKSPACE", "TARGET", "TOOLC= HAIN"]: + elif List[0].strip() in {"WORKSPACE", "TARGET", "TOOLC= HAIN"}: GlobalData.gGlobalDefines[List[0].strip()] =3D Lis= t[1].strip() else: GlobalData.gCommandLineDefines[List[0].strip()] = =3D List[1].strip() diff --git a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py b/BaseT= ools/Source/Python/GenFds/GenFdsGlobalVariable.py index 8537800bc2b2..b840079e7ad4 100644 --- a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py +++ b/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py @@ -295,7 +295,6 @@ class GenFdsGlobalVariable: if not os.path.exists(GenFdsGlobalVariable.FfsDir) : os.makedirs(GenFdsGlobalVariable.FfsDir) =20 - T_CHAR_LF =3D '\n' # # Create FV Address inf file # @@ -313,13 +312,9 @@ class GenFdsGlobalVariable: # # Add [Options] # - FvAddressFile.writelines("[options]" + T_CHAR_LF) - FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS =3D " += \ - BsAddress + \ - T_CHAR_LF) - FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS =3D = " + \ - RtAddress + \ - T_CHAR_LF) + FvAddressFile.writelines("[options]{END}".format(END=3DDataTyp= e.TAB_LINE_BREAK)) + FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS =3D {BS= }{END}".format(BS=3DBsAddress, END=3DDataType.TAB_LINE_BREAK)) + FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS =3D = {RT}{END}".format(RT=3DRtAddress, END=3DDataType.TAB_LINE_BREAK)) =20 =20 def SetEnv(FdfParser, WorkSpace, ArchList, GlobalData): @@ -352,7 +347,6 @@ class GenFdsGlobalVariable: if not os.path.exists(GenFdsGlobalVariable.FfsDir): os.makedirs(GenFdsGlobalVariable.FfsDir) =20 - T_CHAR_LF =3D '\n' # # Create FV Address inf file # @@ -376,13 +370,9 @@ class GenFdsGlobalVariable: # # Add [Options] # - FvAddressFile.writelines("[options]" + T_CHAR_LF) - FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS =3D " += \ - BsAddress + \ - T_CHAR_LF) - FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS =3D = " + \ - RtAddress + \ - T_CHAR_LF) + FvAddressFile.writelines("[options]{END}".format(END=3DDataTyp= e.TAB_LINE_BREAK)) + FvAddressFile.writelines("EFI_BOOT_DRIVER_BASE_ADDRESS =3D {BS= }{END}".format(BS=3DBsAddress, END=3DDataType.TAB_LINE_BREAK)) + FvAddressFile.writelines("EFI_RUNTIME_DRIVER_BASE_ADDRESS =3D = {RT}{END}".format(RT=3DRtAddress, END=3DDataType.TAB_LINE_BREAK)) =20 ## ReplaceWorkspaceMacro() # @@ -692,7 +682,7 @@ class GenFdsGlobalVariable: if " ".join(Cmd).strip() not in GenFdsGlobalVariable.SecCmdLis= t: GenFdsGlobalVariable.SecCmdList.append(" ".join(Cmd).strip= ()) else: - GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to call " += ToolPath, returnValue) + GenFdsGlobalVariable.CallExternalTool(Cmd, "Failed to call {PA= TH}".format(PATH=3DToolPath), returnValue) =20 def CallExternalTool (cmd, errorMess, returnValue=3D[]): =20 diff --git a/BaseTools/Source/Python/GenFds/OptionRom.py b/BaseTools/Source= /Python/GenFds/OptionRom.py index b05841529940..0b8e79588ff1 100644 --- a/BaseTools/Source/Python/GenFds/OptionRom.py +++ b/BaseTools/Source/Python/GenFds/OptionRom.py @@ -27,8 +27,6 @@ from Common.Misc import SaveFileOnChange from Common import EdkLogger from Common.BuildToolError import * =20 -T_CHAR_LF =3D '\n' - ##=20 # # diff --git a/BaseTools/Source/Python/GenFds/Vtf.py b/BaseTools/Source/Pytho= n/GenFds/Vtf.py index 291070827b78..6016b6d94e94 100644 --- a/BaseTools/Source/Python/GenFds/Vtf.py +++ b/BaseTools/Source/Python/GenFds/Vtf.py @@ -19,7 +19,7 @@ from GenFdsGlobalVariable import GenFdsGlobalVariable import Common.LongFilePathOs as os from CommonDataClass.FdfClass import VtfClassObject from Common.LongFilePathSupport import OpenLongFilePath as open -T_CHAR_LF =3D '\n' +from Common.DataType import TAB_LINE_BREAK =20 ## generate VTF # @@ -43,7 +43,7 @@ class Vtf (VtfClassObject): # def GenVtf(self, FdAddressDict) : self.GenBsfInf() - OutputFile =3D os.path.join(GenFdsGlobalVariable.FvDir, self.UiNam= e + '.Vtf') + OutputFile =3D os.path.join(GenFdsGlobalVariable.FvDir, '{NAME}.Vt= f'.format(self.UiName)) BaseAddArg =3D self.GetBaseAddressArg(FdAddressDict) OutputArg, VtfRawDict =3D self.GenOutputArg() =20 @@ -69,77 +69,43 @@ class Vtf (VtfClassObject): self.BsfInfName =3D os.path.join(GenFdsGlobalVariable.FvDir, self.= UiName + '.inf') with open(self.BsfInfName, 'w') as BsfInf: if self.ResetBin is not None: - BsfInf.writelines ("[OPTIONS]" + T_CHAR_LF) - BsfInf.writelines ("IA32_RST_BIN" + \ - " =3D " + \ - GenFdsGlobalVariable.MacroExtend(GenFds= GlobalVariable.ReplaceWorkspaceMacro(self.ResetBin)) + \ - T_CHAR_LF) - BsfInf.writelines (T_CHAR_LF) + BsfInf.writelines ("[OPTIONS]{END}".format(END=3DTAB_LINE_= BREAK)) + BsfInf.writelines ("IA32_RST_BIN =3D {DATA}{END}".format( + DATA=3DGenFdsGlobalVariable.MacroExtend(GenFdsGlobalVa= riable.ReplaceWorkspaceMacro(self.ResetBin)), + END=3DTAB_LINE_BREAK)) + BsfInf.writelines (TAB_LINE_BREAK) =20 - BsfInf.writelines ("[COMPONENTS]" + T_CHAR_LF) + BsfInf.writelines ("[COMPONENTS]{END}".format(END=3DTAB_LINE_B= REAK)) =20 for ComponentObj in self.ComponentStatementList : - BsfInf.writelines ("COMP_NAME" + \ - " =3D " + \ - ComponentObj.CompName + \ - T_CHAR_LF) + BsfInf.writelines ("COMP_NAME =3D {DATA}{END}".format(DATA= =3DComponentObj.CompName,END=3DTAB_LINE_BREAK)) + if ComponentObj.CompLoc.upper() =3D=3D 'NONE': - BsfInf.writelines ("COMP_LOC" + \ - " =3D " + \ - 'N' + \ - T_CHAR_LF) - + BsfInf.writelines ("COMP_LOC =3D N{END}".format(END=3D= TAB_LINE_BREAK)) elif ComponentObj.FilePos is not None: - BsfInf.writelines ("COMP_LOC" + \ - " =3D " + \ - ComponentObj.FilePos + \ - T_CHAR_LF) + BsfInf.writelines ("COMP_LOC =3D {POS}{END}".format(PO= S=3DComponentObj.FilePos, END=3DTAB_LINE_BREAK)) else: Index =3D FvList.index(ComponentObj.CompLoc.upper()) if Index =3D=3D 0: - BsfInf.writelines ("COMP_LOC" + \ - " =3D " + \ - 'F' + \ - T_CHAR_LF) + BsfInf.writelines ("COMP_LOC =3D F{END}".format(EN= D=3DTAB_LINE_BREAK)) elif Index =3D=3D 1: - BsfInf.writelines ("COMP_LOC" + \ - " =3D " + \ - 'S' + \ - T_CHAR_LF) + BsfInf.writelines ("COMP_LOC =3D S{END}".format(EN= D=3DTAB_LINE_BREAK)) =20 - BsfInf.writelines ("COMP_TYPE" + \ - " =3D " + \ - ComponentObj.CompType + \ - T_CHAR_LF) - BsfInf.writelines ("COMP_VER" + \ - " =3D " + \ - ComponentObj.CompVer + \ - T_CHAR_LF) - BsfInf.writelines ("COMP_CS" + \ - " =3D " + \ - ComponentObj.CompCs + \ - T_CHAR_LF) + BsfInf.writelines ("COMP_TYPE =3D {DATA}{END}".format(DATA= =3DComponentObj.CompType,END=3DTAB_LINE_BREAK)) + BsfInf.writelines ("COMP_VER =3D {DATA}{END}".format(DATA= =3DComponentObj.CompVer,END=3DTAB_LINE_BREAK)) + BsfInf.writelines ("COMP_CS =3D {DATA}{END}".format(DATA= =3DComponentObj.CompCs,END=3DTAB_LINE_BREAK)) =20 BinPath =3D ComponentObj.CompBin if BinPath !=3D '-': BinPath =3D GenFdsGlobalVariable.MacroExtend(GenFdsGlo= balVariable.ReplaceWorkspaceMacro(BinPath)) - BsfInf.writelines ("COMP_BIN" + \ - " =3D " + \ - BinPath + \ - T_CHAR_LF) + BsfInf.writelines ("COMP_BIN =3D {DATA}{END}".format(DATA= =3DBinPath, END=3DTAB_LINE_BREAK)) =20 SymPath =3D ComponentObj.CompSym if SymPath !=3D '-': SymPath =3D GenFdsGlobalVariable.MacroExtend(GenFdsGlo= balVariable.ReplaceWorkspaceMacro(SymPath)) - BsfInf.writelines ("COMP_SYM" + \ - " =3D " + \ - SymPath + \ - T_CHAR_LF) - BsfInf.writelines ("COMP_SIZE" + \ - " =3D " + \ - ComponentObj.CompSize + \ - T_CHAR_LF) - BsfInf.writelines (T_CHAR_LF) + BsfInf.writelines ("COMP_SYM =3D {DATA}{END}".format(DATA= =3DSymPath, END=3DTAB_LINE_BREAK)) + BsfInf.writelines ("COMP_SIZE =3D {DATA}{END}".format(DATA= =3DComponentObj.CompSiz, END=3DTAB_LINE_BREAK)) + BsfInf.writelines (TAB_LINE_BREAK) =20 ## GenFvList() method # diff --git a/BaseTools/Source/Python/Table/TableDataModel.py b/BaseTools/So= urce/Python/Table/TableDataModel.py index 9c3d7bd9345f..ec47b9f37097 100644 --- a/BaseTools/Source/Python/Table/TableDataModel.py +++ b/BaseTools/Source/Python/Table/TableDataModel.py @@ -1,7 +1,7 @@ ## @file # This file is used to create/update/query/erase table for data models # -# Copyright (c) 2008, Intel Corporation. All rights reserved.
+# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.
# This program and the accompanying materials # are licensed and made available under the terms and conditions of the BS= D License # which accompanies this distribution. The full text of the license may b= e found at @@ -60,7 +60,7 @@ class TableDataModel(Table): def Insert(self, CrossIndex, Name, Description): self.ID =3D self.ID + 1 (Name, Description) =3D ConvertToSqlString((Name, Description)) - SqlCommand =3D """insert into %s values(%s, %s, '%s', '%s')""" % (= self.Table, self.ID, CrossIndex, Name, Description) + SqlCommand =3D "insert into %s values(%s, %s, '%s', '%s')" % (self= .Table, self.ID, CrossIndex, Name, Description) Table.Insert(self, SqlCommand) =20 return self.ID @@ -87,9 +87,6 @@ class TableDataModel(Table): # def GetCrossIndex(self, ModelName): CrossIndex =3D -1 - SqlCommand =3D """select CrossIndex from DataModel where name =3D = '""" + ModelName + """'""" + SqlCommand =3D "select CrossIndex from DataModel where name =3D '{= NAME}'".format(NAME=3DModelName) self.Cur.execute(SqlCommand) - for Item in self.Cur: - CrossIndex =3D Item[0] - =20 - return CrossIndex + return self.Cur[-1][0] diff --git a/BaseTools/Source/Python/Workspace/DscBuildData.py b/BaseTools/= Source/Python/Workspace/DscBuildData.py index d714c781e970..7b062b564da5 100644 --- a/BaseTools/Source/Python/Workspace/DscBuildData.py +++ b/BaseTools/Source/Python/Workspace/DscBuildData.py @@ -220,7 +220,7 @@ class DscBuildData(PlatformBuildClassObject): @property def OutputPath(self): if os.getenv("WORKSPACE"): - return os.path.join(os.getenv("WORKSPACE"), self.OutputDirecto= ry, self._Target + "_" + self._Toolchain,PcdValueInitName) + return os.path.join(os.getenv("WORKSPACE"), self.OutputDirecto= ry, "{TGT}_{TC}".format(TGT=3Dself._Target, TC=3Dself._Toolchain),PcdValueI= nitName) else: return os.path.dirname(self.DscFile) =20 @@ -762,7 +762,7 @@ class DscBuildData(PlatformBuildClassObject): Module.BuildOptions[ToolChainFamily, ToolChain] =3D Op= tion else: OptionString =3D Module.BuildOptions[ToolChainFamily, = ToolChain] - Module.BuildOptions[ToolChainFamily, ToolChain] =3D Op= tionString + " " + Option + Module.BuildOptions[ToolChainFamily, ToolChain] =3D "{= OPT1} {OPT2}".format(OPT1=3DOptionString, OPT2=3DOption) =20 RecordList =3D self._RawData[MODEL_META_DATA_HEADER, self._Arc= h, None, ModuleId] if DuplicatedFile and not RecordList: @@ -1539,7 +1539,7 @@ class DscBuildData(PlatformBuildClassObject): if not FieldList: continue for FieldName in FieldList: - FieldName =3D "." + FieldName + FieldName =3D ".{ORIG}".format(ORIG=3DFieldName) IsArray =3D IsFieldValueAnArray(FieldList[FieldName.strip(= ".")][0]) if IsArray and not (FieldList[FieldName.strip(".")][0].sta= rtswith('{GUID') and FieldList[FieldName.strip(".")][0].endswith('}')): try: @@ -1569,7 +1569,7 @@ class DscBuildData(PlatformBuildClassObject): if not FieldList: continue for FieldName in FieldList: - FieldName =3D "." + FieldName + FieldName =3D ".{ORIG}".format(ORIG=3DFieldName) IsArray =3D IsFieldValueAnArray(FieldList[FieldNam= e.strip(".")][0]) if IsArray and not (FieldList[FieldName.strip(".")= ][0].startswith('{GUID') and FieldList[FieldName.strip(".")][0].endswith('}= ')): try: @@ -1593,7 +1593,7 @@ class DscBuildData(PlatformBuildClassObject): if Pcd.PcdFieldValueFromComm: CApp =3D CApp + "// From Command Line \n" for FieldName in Pcd.PcdFieldValueFromComm: - FieldName =3D "." + FieldName + FieldName =3D ".{ORIG}".format(ORIG=3DFieldName) IsArray =3D IsFieldValueAnArray(Pcd.PcdFieldValueFromComm[Fiel= dName.strip(".")][0]) if IsArray and not (Pcd.PcdFieldValueFromComm[FieldName.strip(= ".")][0].startswith('{GUID') and Pcd.PcdFieldValueFromComm[FieldName.strip(= ".")][0].endswith('}')): try: @@ -2043,7 +2043,7 @@ class DscBuildData(PlatformBuildClassObject): else: # append options for the same tool except PATH if Attr !=3D 'PATH': - BuildOptions[Tool][Attr] +=3D " " + self.B= uildOptions[Options] + BuildOptions[Tool][Attr] =3D "{ORIG} {NEW}= ".format(ORIG=3DBuildOptions[Tool][Attr], NEW=3Dself.BuildOptions[Options]) else: BuildOptions[Tool][Attr] =3D self.BuildOpt= ions[Options] if BuildOptions: @@ -2054,7 +2054,7 @@ class DscBuildData(PlatformBuildClassObject): ValueList =3D Value.split() if ValueList: for Id, Item in enumerate(ValueList): - if Item in ['-D', '/D', '-U', '/U']: + if Item in {'-D', '/D', '-U', '/U'}: CC_FLAGS +=3D ' ' + Item if Id + 1 < len(ValueList): CC_FLAGS +=3D ' ' + ValueList[Id += 1] diff --git a/BaseTools/Source/Python/Workspace/InfBuildData.py b/BaseTools/= Source/Python/Workspace/InfBuildData.py index 12d848b5fc41..3d9391039f4f 100644 --- a/BaseTools/Source/Python/Workspace/InfBuildData.py +++ b/BaseTools/Source/Python/Workspace/InfBuildData.py @@ -395,7 +395,7 @@ class InfBuildData(ModuleBuildClassObject): self._BuildOptions[ToolChainFamily, ToolChain]= =3D Value else: OptionString =3D self._BuildOptions[ToolChainF= amily, ToolChain] - self._BuildOptions[ToolChainFamily, ToolChain]= =3D OptionString + " " + Value + self._BuildOptions[ToolChainFamily, ToolChain]= =3D "{OPTION} {VAL}".format(OPTION=3DOptionString, VAL=3DValue) # set _Header to non-None in order to avoid database re-querying self._Header_ =3D 'DUMMY' =20 @@ -863,7 +863,7 @@ class InfBuildData(ModuleBuildClassObject): else: # concatenate the option string if they're for the sam= e tool OptionString =3D self._BuildOptions[ToolChainFamily, T= oolChain] - self._BuildOptions[ToolChainFamily, ToolChain] =3D Opt= ionString + " " + Option + self._BuildOptions[ToolChainFamily, ToolChain] =3D "{O= PTION} {OPT}".format(OPTION=3DOptionString, OPT=3DOption) return self._BuildOptions =20 ## Retrieve dependency expression diff --git a/BaseTools/Source/Python/Workspace/MetaDataTable.py b/BaseTools= /Source/Python/Workspace/MetaDataTable.py index e37a10c82f8f..83963008ef4c 100644 --- a/BaseTools/Source/Python/Workspace/MetaDataTable.py +++ b/BaseTools/Source/Python/Workspace/MetaDataTable.py @@ -22,7 +22,7 @@ from CommonDataClass.DataClass import FileClass =20 ## Convert to SQL required string format def ConvertToSqlString(StringList): - return map(lambda s: "'" + s.replace("'", "''") + "'", StringList) + return map(lambda s: "'{mid}'".format(mid=3Ds.replace("'", "''")), Str= ingList) =20 ## TableFile # @@ -329,10 +329,6 @@ class TableDataModel(Table): # def GetCrossIndex(self, ModelName): CrossIndex =3D -1 - SqlCommand =3D """select CrossIndex from DataModel where name =3D = '""" + ModelName + """'""" + SqlCommand =3D "select CrossIndex from DataModel where name =3D '{= NAME}'".format(NAME=3DModelName) self.Cur.execute(SqlCommand) - for Item in self.Cur: - CrossIndex =3D Item[0] - - return CrossIndex - + return self.Cur[-1][0] diff --git a/BaseTools/Source/Python/Workspace/MetaFileParser.py b/BaseTool= s/Source/Python/Workspace/MetaFileParser.py index 21b20bce4018..2c116ddbcb71 100644 --- a/BaseTools/Source/Python/Workspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Workspace/MetaFileParser.py @@ -1924,10 +1924,10 @@ class DecParser(MetaFileParser): return =20 if self._include_flag: - self._ValueList[1] =3D "_" + md5.new(self= ._CurrentLine).hexdigest() + self._ValueList[1] =3D "_{MD5}".format(MD= 5=3Dmd5.new(self._CurrentLine).hexdigest()) self._ValueList[2] =3D self._CurrentLine if self._package_flag and "}" !=3D self._CurrentLine: - self._ValueList[1] =3D "_" + md5.new(self._C= urrentLine).hexdigest() + self._ValueList[1] =3D "_{MD5}".format(MD5= =3Dmd5.new(self._CurrentLine).hexdigest()) self._ValueList[2] =3D self._CurrentLine if self._CurrentLine =3D=3D "}": self._package_flag =3D False --=20 2.16.2.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Fri May 3 05:47:03 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 1526321408370386.0937365185765; Mon, 14 May 2018 11:10:08 -0700 (PDT) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 348D421CB74B7; Mon, 14 May 2018 11:09:30 -0700 (PDT) Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 6580121CB74B7 for ; Mon, 14 May 2018 11:09:25 -0700 (PDT) Received: from orsmga001.jf.intel.com ([10.7.209.18]) by orsmga105.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 14 May 2018 11:09:24 -0700 Received: from jcarsey-desk1.amr.corp.intel.com ([10.7.159.144]) by orsmga001.jf.intel.com with ESMTP; 14 May 2018 11:09:24 -0700 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.100; helo=mga07.intel.com; envelope-from=jaben.carsey@intel.com; receiver=edk2-devel@lists.01.org X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.49,401,1520924400"; d="scan'208";a="55814290" From: Jaben Carsey To: edk2-devel@lists.01.org Date: Mon, 14 May 2018 11:09:19 -0700 Message-Id: X-Mailer: git-send-email 2.16.2.windows.1 In-Reply-To: References: In-Reply-To: References: Subject: [edk2] [PATCH v1 10/11] BaseTools: change to set for membership testing X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.26 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Liming Gao MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" when doing testing for membership in a list or a tuple, use a set instead. when order matters, use a list or tuple (i.e. for loop) Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jaben Carsey --- BaseTools/Source/Python/AutoGen/AutoGen.py | 49 +++-= --- BaseTools/Source/Python/AutoGen/GenC.py | 68 ++++= ----- BaseTools/Source/Python/AutoGen/GenDepex.py | 27 ++-- BaseTools/Source/Python/AutoGen/GenMake.py | 9 +- BaseTools/Source/Python/AutoGen/GenPcdDb.py | 52 +++-= --- BaseTools/Source/Python/AutoGen/GenVar.py | 4 +- BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py | 4 +- BaseTools/Source/Python/BPDG/BPDG.py | 2 +- BaseTools/Source/Python/BPDG/GenVpd.py | 6 +- BaseTools/Source/Python/Common/DataType.py | 36 +++-- BaseTools/Source/Python/Common/Expression.py | 8 +- BaseTools/Source/Python/Common/Misc.py | 24 ++-- BaseTools/Source/Python/Common/Parsing.py | 2 +- BaseTools/Source/Python/Common/RangeExpression.py | 10 +- BaseTools/Source/Python/Common/TargetTxtClassObject.py | 8 +- BaseTools/Source/Python/Ecc/Check.py | 121 ++--= ------------ BaseTools/Source/Python/Ecc/MetaDataParser.py | 4 +- BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py | 48 +++-= --- BaseTools/Source/Python/Ecc/c.py | 27 ++-- BaseTools/Source/Python/Eot/Parser.py | 4 +- BaseTools/Source/Python/Eot/Report.py | 13 +- BaseTools/Source/Python/Eot/c.py | 2 +- BaseTools/Source/Python/GenFds/DataSection.py | 2 +- BaseTools/Source/Python/GenFds/DepexSection.py | 5 +- BaseTools/Source/Python/GenFds/FdfParser.py | 152 ++++= ++++++---------- BaseTools/Source/Python/GenFds/FfsInfStatement.py | 4 +- BaseTools/Source/Python/GenFds/Fv.py | 4 +- BaseTools/Source/Python/GenFds/GenFds.py | 4 +- BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py | 16 +-- BaseTools/Source/Python/GenFds/GuidSection.py | 14 +- BaseTools/Source/Python/GenFds/OptRomInfStatement.py | 4 +- BaseTools/Source/Python/GenFds/Region.py | 2 +- BaseTools/Source/Python/PatchPcdValue/PatchPcdValue.py | 20 +-- BaseTools/Source/Python/Trim/Trim.py | 7 +- BaseTools/Source/Python/Workspace/DecBuildData.py | 2 +- BaseTools/Source/Python/Workspace/DscBuildData.py | 86 ++++= +------ BaseTools/Source/Python/Workspace/InfBuildData.py | 26 ++-- BaseTools/Source/Python/Workspace/MetaFileCommentParser.py | 4 +- BaseTools/Source/Python/Workspace/MetaFileParser.py | 66 ++++= ----- BaseTools/Source/Python/build/BuildReport.py | 34 ++--- BaseTools/Source/Python/build/build.py | 32 ++--- 41 files changed, 462 insertions(+), 550 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/AutoGen.py b/BaseTools/Source/= Python/AutoGen/AutoGen.py index 4ccb50a0a0af..dcad8b4f32f6 100644 --- a/BaseTools/Source/Python/AutoGen/AutoGen.py +++ b/BaseTools/Source/Python/AutoGen/AutoGen.py @@ -1540,7 +1540,7 @@ class PlatformAutoGen(AutoGen): self._PlatformPcds[pcd] =3D self.Platform.Pcds[pcd] =20 for item in self._PlatformPcds: - if self._PlatformPcds[item].DatumType and self._PlatformPcds[i= tem].DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64, TAB_V= OID, "BOOLEAN"]: + if self._PlatformPcds[item].DatumType and self._PlatformPcds[i= tem].DatumType not in TAB_PCD_NUMERIC_TYPES_VOID: self._PlatformPcds[item].DatumType =3D TAB_VOID =20 if (self.Workspace.ArchList[-1] =3D=3D self.Arch):=20 @@ -1549,12 +1549,12 @@ class PlatformAutoGen(AutoGen): Sku =3D Pcd.SkuInfoList.values()[0] Sku.VpdOffset =3D Sku.VpdOffset.strip() =20 - if Pcd.DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32= , TAB_UINT64, TAB_VOID, "BOOLEAN"]: + if Pcd.DatumType not in TAB_PCD_NUMERIC_TYPES_VOID: Pcd.DatumType =3D TAB_VOID =20 # if found PCD which datum value is unicode string the= insert to left size of UnicodeIndex # if found HII type PCD then insert to right of Unicod= eIndex - if Pcd.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_= VPD]: + if Pcd.Type in {TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_= VPD}: VpdPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)] = =3D Pcd =20 #Collect DynamicHii PCD values and assign it to DynamicExVpd P= CD gEfiMdeModulePkgTokenSpaceGuid.PcdNvStoreDefaultValueBuffer @@ -1576,7 +1576,7 @@ class PlatformAutoGen(AutoGen): VpdSkuMap =3D {} for PcdKey in PlatformPcds: Pcd =3D self._PlatformPcds[PcdKey] - if Pcd.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_= VPD] and \ + if Pcd.Type in {TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_= VPD} and \ PcdKey in VpdPcdDict: Pcd =3D VpdPcdDict[PcdKey] SkuValueMap =3D {} @@ -1630,7 +1630,7 @@ class PlatformAutoGen(AutoGen): # =20 for DscPcd in PlatformPcds: DscPcdEntry =3D self._PlatformPcds[DscPcd] - if DscPcdEntry.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYN= AMIC_EX_VPD]: + if DscPcdEntry.Type in {TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYN= AMIC_EX_VPD}: if not (self.Platform.VpdToolGuid is None or self.Plat= form.VpdToolGuid =3D=3D ''): FoundFlag =3D False for VpdPcd in VpdFile._VpdArray: @@ -1748,7 +1748,7 @@ class PlatformAutoGen(AutoGen): Sku =3D Pcd.SkuInfoList.values()[0] Sku.VpdOffset =3D Sku.VpdOffset.strip() =20 - if Pcd.DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32= , TAB_UINT64, TAB_VOID, "BOOLEAN"]: + if Pcd.DatumType not in TAB_PCD_NUMERIC_TYPES_VOID: Pcd.DatumType =3D TAB_VOID =20 PcdValue =3D Sku.DefaultValue @@ -1768,7 +1768,7 @@ class PlatformAutoGen(AutoGen): for pcd in self._DynamicPcdList: if len(pcd.SkuInfoList) =3D=3D 1: for (SkuName,SkuId) in allskuset: - if type(SkuId) in (str,unicode) and eval(SkuId) =3D=3D= 0 or SkuId =3D=3D 0: + if type(SkuId) in {str,unicode} and eval(SkuId) =3D=3D= 0 or SkuId =3D=3D 0: continue pcd.SkuInfoList[SkuName] =3D copy.deepcopy(pcd.SkuInfo= List[TAB_DEFAULT]) pcd.SkuInfoList[SkuName].SkuId =3D SkuId @@ -3086,13 +3086,10 @@ class ModuleAutoGen(AutoGen): # @retval list The list of package object # def _GetDerivedPackageList(self): - PackageList =3D [] + PackageSet =3D set() for M in [self.Module] + self.DependentLibraryList: - for Package in M.Packages: - if Package in PackageList: - continue - PackageList.append(Package) - return PackageList + PackageSet =3D PackageSet.union(M.Packages) + return list(PackageSet) =20 ## Get the depex string # @@ -3120,7 +3117,7 @@ class ModuleAutoGen(AutoGen): else: if Arch.upper() =3D=3D TAB_ARCH_COMMON or \ (Arch.upper() =3D=3D self.Arch.upper() and \ - ModuleType.upper() in [TAB_ARCH_COMMON, self.Mod= uleType.upper()]): + ModuleType.upper() in {TAB_ARCH_COMMON, self.Mod= uleType.upper()}): DepexList.append({(Arch, ModuleType): DepexExp= r}) =20 #the type of build module is USER_DEFINED. @@ -3279,9 +3276,9 @@ class ModuleAutoGen(AutoGen): # Regular expression for finding Include Directories, the diff= erence between MSFT and INTEL/GCC/RVCT # is the former use /I , the Latter used -I to specify include= directories # - if self.PlatformInfo.ToolChainFamily in ('MSFT'): + if self.PlatformInfo.ToolChainFamily =3D=3D 'MSFT': BuildOptIncludeRegEx =3D gBuildOptIncludePatternMsft - elif self.PlatformInfo.ToolChainFamily in ('INTEL', 'GCC', 'RV= CT'): + elif self.PlatformInfo.ToolChainFamily in {'INTEL', 'GCC', 'RV= CT'}: BuildOptIncludeRegEx =3D gBuildOptIncludePatternOther else: # @@ -3291,7 +3288,7 @@ class ModuleAutoGen(AutoGen): return self._BuildOptionIncPathList =20 BuildOptionIncPathList =3D [] - for Tool in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'AS= M'): + for Tool in ['CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'AS= M']: Attr =3D 'FLAGS' try: FlagOption =3D self.BuildOption[Tool][Attr] @@ -3339,12 +3336,12 @@ class ModuleAutoGen(AutoGen): self._SourceFileList =3D [] for F in self.Module.Sources: # match tool chain - if F.TagName not in ("", "*", self.ToolChain): + if F.TagName not in {"", "*", self.ToolChain}: EdkLogger.debug(EdkLogger.DEBUG_9, "The toolchain [%s]= for processing file [%s] is found, " "but [%s] is needed" % (F.TagName, str= (F), self.ToolChain)) continue # match tool chain family or build rule family - if F.ToolChainFamily not in ("", "*", self.ToolChainFamily= , self.BuildRuleFamily): + if F.ToolChainFamily not in {"", "*", self.ToolChainFamily= , self.BuildRuleFamily}: EdkLogger.debug( EdkLogger.DEBUG_0, "The file [%s] must be built by tools of [= %s], " \ @@ -3423,7 +3420,7 @@ class ModuleAutoGen(AutoGen): if self._BinaryFileList is None: self._BinaryFileList =3D [] for F in self.Module.Binaries: - if F.Target not in [TAB_ARCH_COMMON, '*'] and F.Target != =3D self.BuildTarget: + if F.Target not in {TAB_ARCH_COMMON, '*'} and F.Target != =3D self.BuildTarget: continue self._BinaryFileList.append(F) self._ApplyBuildRule(F, F.Type) @@ -4049,11 +4046,11 @@ class ModuleAutoGen(AutoGen): AsBuiltInfDict['binary_item'] +=3D ['BIN|' + File] if self.DepexGenerated: self.OutputFile.add(self.Name + '.depex') - if self.ModuleType in [SUP_MODULE_PEIM]: + if self.ModuleType =3D=3D SUP_MODULE_PEIM: AsBuiltInfDict['binary_item'] +=3D ['PEI_DEPEX|' + self.Na= me + '.depex'] - if self.ModuleType in [SUP_MODULE_DXE_DRIVER, SUP_MODULE_DXE_R= UNTIME_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, SUP_MODULE_UEFI_DRIVER]: + if self.ModuleType in {SUP_MODULE_DXE_DRIVER, SUP_MODULE_DXE_R= UNTIME_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, SUP_MODULE_UEFI_DRIVER}: AsBuiltInfDict['binary_item'] +=3D ['DXE_DEPEX|' + self.Na= me + '.depex'] - if self.ModuleType in [SUP_MODULE_DXE_SMM_DRIVER]: + if self.ModuleType =3D=3D SUP_MODULE_DXE_SMM_DRIVER: AsBuiltInfDict['binary_item'] +=3D ['SMM_DEPEX|' + self.Na= me + '.depex'] =20 Bin =3D self._GenOffsetBin() @@ -4107,11 +4104,11 @@ class ModuleAutoGen(AutoGen): else: continue PcdValue =3D '' - if Pcd.DatumType =3D=3D 'BOOLEAN': + if Pcd.DatumType =3D=3D TAB_BOOLEAN: BoolValue =3D Pcd.DefaultValue.upper() - if BoolValue =3D=3D 'TRUE': + if BoolValue =3D=3D TAB_TRUE_1: Pcd.DefaultValue =3D '1' - elif BoolValue =3D=3D 'FALSE': + elif BoolValue =3D=3D TAB_FALSE_1: Pcd.DefaultValue =3D '0' =20 if Pcd.DatumType in TAB_PCD_NUMERIC_TYPES: diff --git a/BaseTools/Source/Python/AutoGen/GenC.py b/BaseTools/Source/Pyt= hon/AutoGen/GenC.py index e73d83395255..60066e47bbce 100644 --- a/BaseTools/Source/Python/AutoGen/GenC.py +++ b/BaseTools/Source/Python/AutoGen/GenC.py @@ -43,9 +43,9 @@ gItemTypeStringDatabase =3D { =20 =20 ## Datum size -gDatumSizeStringDatabase =3D {TAB_UINT8:'8',TAB_UINT16:'16',TAB_UINT32:'32= ',TAB_UINT64:'64','BOOLEAN':'BOOLEAN',TAB_VOID:'8'} -gDatumSizeStringDatabaseH =3D {TAB_UINT8:'8',TAB_UINT16:'16',TAB_UINT32:'3= 2',TAB_UINT64:'64','BOOLEAN':'BOOL',TAB_VOID:'PTR'} -gDatumSizeStringDatabaseLib =3D {TAB_UINT8:'8',TAB_UINT16:'16',TAB_UINT32:= '32',TAB_UINT64:'64','BOOLEAN':'Bool',TAB_VOID:'Ptr'} +gDatumSizeStringDatabase =3D {TAB_UINT8:'8',TAB_UINT16:'16',TAB_UINT32:'32= ',TAB_UINT64:'64',TAB_BOOLEAN:TAB_BOOLEAN,TAB_VOID:'8'} +gDatumSizeStringDatabaseH =3D {TAB_UINT8:'8',TAB_UINT16:'16',TAB_UINT32:'3= 2',TAB_UINT64:'64',TAB_BOOLEAN:'BOOL',TAB_VOID:'PTR'} +gDatumSizeStringDatabaseLib =3D {TAB_UINT8:'8',TAB_UINT16:'16',TAB_UINT32:= '32',TAB_UINT64:'64',TAB_BOOLEAN:'Bool',TAB_VOID:'Ptr'} =20 ## AutoGen File Header Templates gAutoGenHeaderString =3D TemplateString("""\ @@ -996,11 +996,11 @@ def CreateModulePcdCode(Info, AutoGenC, AutoGenH, Pcd= ): Unicode =3D False ValueNumber =3D 0 =20 - if Pcd.DatumType =3D=3D 'BOOLEAN': + if Pcd.DatumType =3D=3D TAB_BOOLEAN: BoolValue =3D Value.upper() - if BoolValue =3D=3D 'TRUE' or BoolValue =3D=3D '1': + if BoolValue =3D=3D TAB_TRUE_1 or BoolValue =3D=3D '1': Value =3D '1U' - elif BoolValue =3D=3D 'FALSE' or BoolValue =3D=3D '0': + elif BoolValue =3D=3D TAB_FALSE_1 or BoolValue =3D=3D '0': Value =3D '0U' =20 if Pcd.DatumType in TAB_PCD_CLEAN_NUMERIC_TYPES: @@ -1367,17 +1367,17 @@ def CreateLibraryConstructorCode(Info, AutoGenC, Au= toGenH): if len(Lib.ConstructorList) <=3D 0: continue Dict =3D {'Function':Lib.ConstructorList} - if Lib.ModuleType in [SUP_MODULE_BASE, SUP_MODULE_SEC]: + if Lib.ModuleType in {SUP_MODULE_BASE, SUP_MODULE_SEC}: ConstructorPrototypeString.Append(gLibraryStructorPrototype[SU= P_MODULE_BASE].Replace(Dict)) ConstructorCallingString.Append(gLibraryStructorCall[SUP_MODUL= E_BASE].Replace(Dict)) elif Lib.ModuleType in SUP_MODULE_SET_PEI: ConstructorPrototypeString.Append(gLibraryStructorPrototype['P= EI'].Replace(Dict)) ConstructorCallingString.Append(gLibraryStructorCall['PEI'].Re= place(Dict)) - elif Lib.ModuleType in [SUP_MODULE_DXE_CORE,SUP_MODULE_DXE_DRIVER,= SUP_MODULE_DXE_SMM_DRIVER,SUP_MODULE_DXE_RUNTIME_DRIVER, - SUP_MODULE_DXE_SAL_DRIVER,SUP_MODULE_UEFI_= DRIVER,SUP_MODULE_UEFI_APPLICATION,SUP_MODULE_SMM_CORE]: + elif Lib.ModuleType in {SUP_MODULE_DXE_CORE,SUP_MODULE_DXE_DRIVER,= SUP_MODULE_DXE_SMM_DRIVER,SUP_MODULE_DXE_RUNTIME_DRIVER, + SUP_MODULE_DXE_SAL_DRIVER,SUP_MODULE_UEFI_= DRIVER,SUP_MODULE_UEFI_APPLICATION,SUP_MODULE_SMM_CORE}: ConstructorPrototypeString.Append(gLibraryStructorPrototype['D= XE'].Replace(Dict)) ConstructorCallingString.Append(gLibraryStructorCall['DXE'].Re= place(Dict)) - elif Lib.ModuleType in [SUP_MODULE_MM_STANDALONE,SUP_MODULE_MM_COR= E_STANDALONE]: + elif Lib.ModuleType in {SUP_MODULE_MM_STANDALONE,SUP_MODULE_MM_COR= E_STANDALONE}: ConstructorPrototypeString.Append(gLibraryStructorPrototype['M= M'].Replace(Dict)) ConstructorCallingString.Append(gLibraryStructorCall['MM'].Rep= lace(Dict)) =20 @@ -1398,14 +1398,14 @@ def CreateLibraryConstructorCode(Info, AutoGenC, Au= toGenH): if Info.IsLibrary: AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict) else: - if Info.ModuleType in [SUP_MODULE_BASE, SUP_MODULE_SEC]: + if Info.ModuleType in {SUP_MODULE_BASE, SUP_MODULE_SEC}: AutoGenC.Append(gLibraryString[SUP_MODULE_BASE].Replace(Dict)) elif Info.ModuleType in SUP_MODULE_SET_PEI: AutoGenC.Append(gLibraryString['PEI'].Replace(Dict)) - elif Info.ModuleType in [SUP_MODULE_DXE_CORE,SUP_MODULE_DXE_DRIVER= ,SUP_MODULE_DXE_SMM_DRIVER,SUP_MODULE_DXE_RUNTIME_DRIVER, - SUP_MODULE_DXE_SAL_DRIVER,SUP_MODULE_UEFI= _DRIVER,SUP_MODULE_UEFI_APPLICATION,SUP_MODULE_SMM_CORE]: + elif Info.ModuleType in {SUP_MODULE_DXE_CORE,SUP_MODULE_DXE_DRIVER= ,SUP_MODULE_DXE_SMM_DRIVER,SUP_MODULE_DXE_RUNTIME_DRIVER, + SUP_MODULE_DXE_SAL_DRIVER,SUP_MODULE_UEFI= _DRIVER,SUP_MODULE_UEFI_APPLICATION,SUP_MODULE_SMM_CORE}: AutoGenC.Append(gLibraryString['DXE'].Replace(Dict)) - elif Info.ModuleType in [SUP_MODULE_MM_STANDALONE,SUP_MODULE_MM_CO= RE_STANDALONE]: + elif Info.ModuleType in {SUP_MODULE_MM_STANDALONE,SUP_MODULE_MM_CO= RE_STANDALONE}: AutoGenC.Append(gLibraryString['MM'].Replace(Dict)) =20 ## Create code for library destructor @@ -1429,17 +1429,17 @@ def CreateLibraryDestructorCode(Info, AutoGenC, Aut= oGenH): if len(Lib.DestructorList) <=3D 0: continue Dict =3D {'Function':Lib.DestructorList} - if Lib.ModuleType in [SUP_MODULE_BASE, SUP_MODULE_SEC]: + if Lib.ModuleType in {SUP_MODULE_BASE, SUP_MODULE_SEC}: DestructorPrototypeString.Append(gLibraryStructorPrototype[SUP= _MODULE_BASE].Replace(Dict)) DestructorCallingString.Append(gLibraryStructorCall[SUP_MODULE= _BASE].Replace(Dict)) elif Lib.ModuleType in SUP_MODULE_SET_PEI: DestructorPrototypeString.Append(gLibraryStructorPrototype['PE= I'].Replace(Dict)) DestructorCallingString.Append(gLibraryStructorCall['PEI'].Rep= lace(Dict)) - elif Lib.ModuleType in [SUP_MODULE_DXE_CORE,SUP_MODULE_DXE_DRIVER,= SUP_MODULE_DXE_SMM_DRIVER,SUP_MODULE_DXE_RUNTIME_DRIVER, - SUP_MODULE_DXE_SAL_DRIVER,SUP_MODULE_UEFI_= DRIVER,SUP_MODULE_UEFI_APPLICATION, SUP_MODULE_SMM_CORE]: + elif Lib.ModuleType in {SUP_MODULE_DXE_CORE,SUP_MODULE_DXE_DRIVER,= SUP_MODULE_DXE_SMM_DRIVER,SUP_MODULE_DXE_RUNTIME_DRIVER, + SUP_MODULE_DXE_SAL_DRIVER,SUP_MODULE_UEFI_= DRIVER,SUP_MODULE_UEFI_APPLICATION, SUP_MODULE_SMM_CORE}: DestructorPrototypeString.Append(gLibraryStructorPrototype['DX= E'].Replace(Dict)) DestructorCallingString.Append(gLibraryStructorCall['DXE'].Rep= lace(Dict)) - elif Lib.ModuleType in [SUP_MODULE_MM_STANDALONE,SUP_MODULE_MM_COR= E_STANDALONE]: + elif Lib.ModuleType in {SUP_MODULE_MM_STANDALONE,SUP_MODULE_MM_COR= E_STANDALONE}: DestructorPrototypeString.Append(gLibraryStructorPrototype['MM= '].Replace(Dict)) DestructorCallingString.Append(gLibraryStructorCall['MM'].Repl= ace(Dict)) =20 @@ -1460,14 +1460,14 @@ def CreateLibraryDestructorCode(Info, AutoGenC, Aut= oGenH): if Info.IsLibrary: AutoGenH.Append("${BEGIN}${FunctionPrototype}${END}", Dict) else: - if Info.ModuleType in [SUP_MODULE_BASE, SUP_MODULE_SEC]: + if Info.ModuleType in {SUP_MODULE_BASE, SUP_MODULE_SEC}: AutoGenC.Append(gLibraryString[SUP_MODULE_BASE].Replace(Dict)) elif Info.ModuleType in SUP_MODULE_SET_PEI: AutoGenC.Append(gLibraryString['PEI'].Replace(Dict)) - elif Info.ModuleType in [SUP_MODULE_DXE_CORE,SUP_MODULE_DXE_DRIVER= ,SUP_MODULE_DXE_SMM_DRIVER,SUP_MODULE_DXE_RUNTIME_DRIVER, - SUP_MODULE_DXE_SAL_DRIVER,SUP_MODULE_UEFI= _DRIVER,SUP_MODULE_UEFI_APPLICATION,SUP_MODULE_SMM_CORE]: + elif Info.ModuleType in {SUP_MODULE_DXE_CORE,SUP_MODULE_DXE_DRIVER= ,SUP_MODULE_DXE_SMM_DRIVER,SUP_MODULE_DXE_RUNTIME_DRIVER, + SUP_MODULE_DXE_SAL_DRIVER,SUP_MODULE_UEFI= _DRIVER,SUP_MODULE_UEFI_APPLICATION,SUP_MODULE_SMM_CORE}: AutoGenC.Append(gLibraryString['DXE'].Replace(Dict)) - elif Info.ModuleType in [SUP_MODULE_MM_STANDALONE,SUP_MODULE_MM_CO= RE_STANDALONE]: + elif Info.ModuleType in {SUP_MODULE_MM_STANDALONE,SUP_MODULE_MM_CO= RE_STANDALONE}: AutoGenC.Append(gLibraryString['MM'].Replace(Dict)) =20 =20 @@ -1478,7 +1478,7 @@ def CreateLibraryDestructorCode(Info, AutoGenC, AutoG= enH): # @param AutoGenH The TemplateString object for header file # def CreateModuleEntryPointCode(Info, AutoGenC, AutoGenH): - if Info.IsLibrary or Info.ModuleType in [SUP_MODULE_USER_DEFINED, SUP_= MODULE_SEC]: + if Info.IsLibrary or Info.ModuleType in {SUP_MODULE_USER_DEFINED, SUP_= MODULE_SEC}: return # # Module Entry Points @@ -1498,7 +1498,7 @@ def CreateModuleEntryPointCode(Info, AutoGenC, AutoGe= nH): 'UefiSpecVersion': UefiSpecVersion + 'U' } =20 - if Info.ModuleType in [SUP_MODULE_PEI_CORE, SUP_MODULE_DXE_CORE, SUP_M= ODULE_SMM_CORE, SUP_MODULE_MM_CORE_STANDALONE]: + if Info.ModuleType in {SUP_MODULE_PEI_CORE, SUP_MODULE_DXE_CORE, SUP_M= ODULE_SMM_CORE, SUP_MODULE_MM_CORE_STANDALONE}: if Info.SourceFileList: if NumEntryPoints !=3D 1: EdkLogger.error( @@ -1526,7 +1526,7 @@ def CreateModuleEntryPointCode(Info, AutoGenC, AutoGe= nH): else: AutoGenC.Append(gPeimEntryPointString[2].Replace(Dict)) AutoGenH.Append(gPeimEntryPointPrototype.Replace(Dict)) - elif Info.ModuleType in [SUP_MODULE_DXE_RUNTIME_DRIVER,SUP_MODULE_DXE_= DRIVER,SUP_MODULE_DXE_SAL_DRIVER,SUP_MODULE_UEFI_DRIVER]: + elif Info.ModuleType in {SUP_MODULE_DXE_RUNTIME_DRIVER,SUP_MODULE_DXE_= DRIVER,SUP_MODULE_DXE_SAL_DRIVER,SUP_MODULE_UEFI_DRIVER}: if NumEntryPoints < 2: AutoGenC.Append(gUefiDriverEntryPointString[NumEntryPoints].Re= place(Dict)) else: @@ -1558,7 +1558,7 @@ def CreateModuleEntryPointCode(Info, AutoGenC, AutoGe= nH): # @param AutoGenH The TemplateString object for header file # def CreateModuleUnloadImageCode(Info, AutoGenC, AutoGenH): - if Info.IsLibrary or Info.ModuleType in [SUP_MODULE_USER_DEFINED, SUP_= MODULE_SEC]: + if Info.IsLibrary or Info.ModuleType in {SUP_MODULE_USER_DEFINED, SUP_= MODULE_SEC}: return # # Unload Image Handlers @@ -1578,7 +1578,7 @@ def CreateModuleUnloadImageCode(Info, AutoGenC, AutoG= enH): # @param AutoGenH The TemplateString object for header file # def CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH): - if Info.ModuleType in [SUP_MODULE_USER_DEFINED, SUP_MODULE_BASE]: + if Info.ModuleType in {SUP_MODULE_USER_DEFINED, SUP_MODULE_BASE}: GuidType =3D TAB_GUID else: GuidType =3D "EFI_GUID" @@ -1602,7 +1602,7 @@ def CreateGuidDefinitionCode(Info, AutoGenC, AutoGenH= ): # @param AutoGenH The TemplateString object for header file # def CreateProtocolDefinitionCode(Info, AutoGenC, AutoGenH): - if Info.ModuleType in [SUP_MODULE_USER_DEFINED, SUP_MODULE_BASE]: + if Info.ModuleType in {SUP_MODULE_USER_DEFINED, SUP_MODULE_BASE}: GuidType =3D TAB_GUID else: GuidType =3D "EFI_GUID" @@ -1626,7 +1626,7 @@ def CreateProtocolDefinitionCode(Info, AutoGenC, Auto= GenH): # @param AutoGenH The TemplateString object for header file # def CreatePpiDefinitionCode(Info, AutoGenC, AutoGenH): - if Info.ModuleType in [SUP_MODULE_USER_DEFINED, SUP_MODULE_BASE]: + if Info.ModuleType in {SUP_MODULE_USER_DEFINED, SUP_MODULE_BASE}: GuidType =3D TAB_GUID else: GuidType =3D "EFI_GUID" @@ -1663,7 +1663,7 @@ def CreatePcdCode(Info, AutoGenC, AutoGenH): # Add extern declarations to AutoGen.h if one or more Token Space GUID= s were found if TokenSpaceList: AutoGenH.Append("\n// Definition of PCD Token Space GUIDs used in = this module\n\n") - if Info.ModuleType in [SUP_MODULE_USER_DEFINED, SUP_MODULE_BASE]: + if Info.ModuleType in {SUP_MODULE_USER_DEFINED, SUP_MODULE_BASE}: GuidType =3D TAB_GUID else: GuidType =3D "EFI_GUID" =20 @@ -1782,7 +1782,7 @@ def CreateIdfFileCode(Info, AutoGenC, StringH, IdfGen= CFlag, IdfGenBinBuffer): for FileObj in ImageFiles.ImageFilesDict[Idf]: for sourcefile in Info.SourceFileList: if FileObj.FileName =3D=3D sourcefile.File: - if not sourcefile.Ext.upper() in ['.PNG', = '.BMP', '.JPG']: + if not sourcefile.Ext.upper() in {'.PNG', = '.BMP', '.JPG'}: EdkLogger.error("build", AUTOGEN_ERROR= , "The %s's postfix must be one of .bmp, .jpg, .png" % (FileObj.FileName), = ExtraData=3D"[%s]" % str(Info)) FileObj.File =3D sourcefile break @@ -2107,11 +2107,11 @@ def CreateCode(Info, AutoGenC, AutoGenH, StringH, U= niGenCFlag, UniGenBinBuffer, if Pcd.Type =3D=3D TAB_PCDS_FIXED_AT_BUILD: TokenCName =3D Pcd.TokenCName Value =3D Pcd.DefaultValue - if Pcd.DatumType =3D=3D 'BOOLEAN': + if Pcd.DatumType =3D=3D TAB_BOOLEAN: BoolValue =3D Value.upper() - if BoolValue =3D=3D 'TRUE': + if BoolValue =3D=3D TAB_TRUE_1: Value =3D '1' - elif BoolValue =3D=3D 'FALSE': + elif BoolValue =3D=3D TAB_FALSE_1: Value =3D '0' for PcdItem in GlobalData.MixedPcd: if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in Gl= obalData.MixedPcd[PcdItem]: diff --git a/BaseTools/Source/Python/AutoGen/GenDepex.py b/BaseTools/Source= /Python/AutoGen/GenDepex.py index 873ed6e59300..d4730dd227df 100644 --- a/BaseTools/Source/Python/AutoGen/GenDepex.py +++ b/BaseTools/Source/Python/AutoGen/GenDepex.py @@ -114,18 +114,15 @@ class DependencyExpression: } =20 # all supported op codes and operands - SupportedOpcode =3D [DEPEX_OPCODE_BEFORE, DEPEX_OPCODE_AFTER, DEPEX_OP= CODE_PUSH, DEPEX_OPCODE_AND, DEPEX_OPCODE_OR, DEPEX_OPCODE_NOT, DEPEX_OPCOD= E_END, DEPEX_OPCODE_SOR] - SupportedOperand =3D [DEPEX_OPCODE_TRUE, DEPEX_OPCODE_FALSE] - - OpcodeWithSingleOperand =3D [DEPEX_OPCODE_NOT, DEPEX_OPCODE_BEFORE, DE= PEX_OPCODE_AFTER] - OpcodeWithTwoOperand =3D [DEPEX_OPCODE_AND, DEPEX_OPCODE_OR] + SupportedOpcode =3D {DEPEX_OPCODE_BEFORE, DEPEX_OPCODE_AFTER, DEPEX_OP= CODE_PUSH, DEPEX_OPCODE_AND, DEPEX_OPCODE_OR, DEPEX_OPCODE_NOT, DEPEX_OPCOD= E_END, DEPEX_OPCODE_SOR} + SupportedOperand =3D {DEPEX_OPCODE_TRUE, DEPEX_OPCODE_FALSE} =20 # op code that should not be the last one - NonEndingOpcode =3D [DEPEX_OPCODE_AND, DEPEX_OPCODE_OR, DEPEX_OPCODE_N= OT, DEPEX_OPCODE_SOR] + NonEndingOpcode =3D {DEPEX_OPCODE_AND, DEPEX_OPCODE_OR, DEPEX_OPCODE_N= OT, DEPEX_OPCODE_SOR} # op code must not present at the same time - ExclusiveOpcode =3D [DEPEX_OPCODE_BEFORE, DEPEX_OPCODE_AFTER] + ExclusiveOpcode =3D {DEPEX_OPCODE_BEFORE, DEPEX_OPCODE_AFTER} # op code that should be the first one if it presents - AboveAllOpcode =3D [DEPEX_OPCODE_SOR, DEPEX_OPCODE_BEFORE, DEPEX_OPCOD= E_AFTER] + AboveAllOpcode =3D {DEPEX_OPCODE_SOR, DEPEX_OPCODE_BEFORE, DEPEX_OPCOD= E_AFTER} =20 # # open and close brace must be taken as individual tokens @@ -177,7 +174,7 @@ class DependencyExpression: LastToken =3D '' for Token in self.TokenList: if Token =3D=3D "(": - if LastToken not in self.SupportedOpcode + ['(', '', None]: + if LastToken not in self.SupportedOpcode.union(['(', '', N= one]): EdkLogger.error("GenDepex", PARSER_ERROR, "Invalid dep= endency expression: missing operator before open parentheses", ExtraData=3D"Near %s" % LastToken) Stack.append(Token) @@ -185,7 +182,7 @@ class DependencyExpression: if '(' not in Stack: EdkLogger.error("GenDepex", PARSER_ERROR, "Invalid dep= endency expression: mismatched parentheses", ExtraData=3Dstr(self)) - elif LastToken in self.SupportedOpcode + ['', None]: + elif LastToken in self.SupportedOpcode.union(['', None]): EdkLogger.error("GenDepex", PARSER_ERROR, "Invalid dep= endency expression: missing operand before close parentheses", ExtraData=3D"Near %s" % LastToken) while len(Stack) > 0: @@ -195,10 +192,10 @@ class DependencyExpression: self.PostfixNotation.append(Stack.pop()) elif Token in self.OpcodePriority: if Token =3D=3D DEPEX_OPCODE_NOT: - if LastToken not in self.SupportedOpcode + ['(', '', N= one]: + if LastToken not in self.SupportedOpcode.union(['(', '= ', None]): EdkLogger.error("GenDepex", PARSER_ERROR, "Invalid= dependency expression: missing operator before NOT", ExtraData=3D"Near %s" % LastToken) - elif LastToken in self.SupportedOpcode + ['(', '', None]: + elif LastToken in self.SupportedOpcode.union(['(', '', Non= e]): EdkLogger.error("GenDepex", PARSER_ERROR, "Invalid= dependency expression: missing operand before " + Token, ExtraData=3D"Near %s" % LastToken) =20 @@ -211,7 +208,7 @@ class DependencyExpression: else: if Token not in self.SupportedOpcode: # not OP, take it as GUID - if LastToken not in self.SupportedOpcode + ['(', '', N= one]: + if LastToken not in self.SupportedOpcode.union(['(', '= ', None]): EdkLogger.error("GenDepex", PARSER_ERROR, "Invalid= dependency expression: missing operator before %s" % Token, ExtraData=3D"Near %s" % LastToken) if len(self.OpcodeList) =3D=3D 0 or self.OpcodeList[-1= ] not in self.ExclusiveOpcode: @@ -274,7 +271,7 @@ class DependencyExpression: return Op =3D OpcodeSet.pop() #if Op isn't either OR or AND, return - if Op not in [DEPEX_OPCODE_AND, DEPEX_OPCODE_OR]: + if Op not in {DEPEX_OPCODE_AND, DEPEX_OPCODE_OR}: return NewOperand =3D [] AllOperand =3D set() @@ -302,7 +299,7 @@ class DependencyExpression: return =20 # don't generate depex if all operands are architecture protocols - if self.ModuleType in [SUP_MODULE_UEFI_DRIVER, SUP_MODULE_DXE_DRIV= ER, SUP_MODULE_DXE_RUNTIME_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, SUP_MODULE_DX= E_SMM_DRIVER, SUP_MODULE_MM_STANDALONE] and \ + if self.ModuleType in {SUP_MODULE_UEFI_DRIVER, SUP_MODULE_DXE_DRIV= ER, SUP_MODULE_DXE_RUNTIME_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, SUP_MODULE_DX= E_SMM_DRIVER, SUP_MODULE_MM_STANDALONE} and \ Op =3D=3D DEPEX_OPCODE_AND and \ self.ArchProtocols =3D=3D set(GuidStructureStringToGuidString(G= uid) for Guid in AllOperand): self.PostfixNotation =3D [] diff --git a/BaseTools/Source/Python/AutoGen/GenMake.py b/BaseTools/Source/= Python/AutoGen/GenMake.py index 4ae977ccd400..12e871a8b8d3 100644 --- a/BaseTools/Source/Python/AutoGen/GenMake.py +++ b/BaseTools/Source/Python/AutoGen/GenMake.py @@ -23,6 +23,7 @@ from Common.MultipleWorkspace import MultipleWorkspace as= mws from Common.BuildToolError import * from Common.Misc import * from Common.String import * +from Common.DataType import * from BuildEngine import * import Common.GlobalData as GlobalData from collections import OrderedDict @@ -499,7 +500,7 @@ cleanlib: =20 PCI_COMPRESS_Flag =3D False for k, v in self._AutoGenObject.Module.Defines.iteritems(): - if 'PCI_COMPRESS' =3D=3D k and 'TRUE' =3D=3D v: + if 'PCI_COMPRESS' =3D=3D k and TAB_TRUE_1 =3D=3D v: PCI_COMPRESS_Flag =3D True =20 # tools definitions @@ -900,7 +901,7 @@ cleanlib: self._AutoGenObject.AutoGenDepSet |=3D set(self.FileDependency= [File]) =20 # skip non-C files - if File.Ext not in [".c", ".C"] or File.Name =3D=3D "AutoGen.c= ": + if File.Ext not in {".c", ".C"} or File.Name =3D=3D "AutoGen.c= ": continue elif DepSet is None: DepSet =3D set(self.FileDependency[File]) @@ -917,7 +918,7 @@ cleanlib: =20 for File in self.FileDependency: # skip non-C files - if File.Ext not in [".c", ".C"] or File.Name =3D=3D "AutoGen.c= ": + if File.Ext not in {".c", ".C"} or File.Name =3D=3D "AutoGen.c= ": continue NewDepSet =3D set(self.FileDependency[File]) NewDepSet -=3D DepSet @@ -958,7 +959,7 @@ cleanlib: # Use file list macro as dependency if T.GenFileListMacro: Deps.append("$(%s)" % T.FileListMacro) - if Type in [TAB_OBJECT_FILE, TAB_STATIC_LIBRARY]: + if Type in {TAB_OBJECT_FILE, TAB_STATIC_LIBRARY}: Deps.append("$(%s)" % T.ListFileMacro) =20 TargetDict =3D { diff --git a/BaseTools/Source/Python/AutoGen/GenPcdDb.py b/BaseTools/Source= /Python/AutoGen/GenPcdDb.py index d2d42fe9d08e..48b34e6f87e5 100644 --- a/BaseTools/Source/Python/AutoGen/GenPcdDb.py +++ b/BaseTools/Source/Python/AutoGen/GenPcdDb.py @@ -293,7 +293,7 @@ class DbItemList: =20 Buffer =3D '' for Datas in self.RawDataList: - if type(Datas) in (list, tuple): + if type(Datas) in {list, tuple}: for Data in Datas: if PackStr: Buffer +=3D pack(PackStr, GetIntegerValue(Data)) @@ -368,7 +368,7 @@ class DbComItemList (DbItemList): Buffer =3D '' for DataList in self.RawDataList: for Data in DataList: - if type(Data) in (list, tuple): + if type(Data) in {list, tuple}: for SingleData in Data: Buffer +=3D pack(PackStr, GetIntegerValue(SingleDa= ta)) else: @@ -414,7 +414,7 @@ class DbStringHeadTableItemList(DbItemList): Offset +=3D len(self.RawDataList[ItemIndex]) else: for innerIndex in range(Index): - if type(self.RawDataList[innerIndex]) in (list, tuple): + if type(self.RawDataList[innerIndex]) in {list, tuple}: Offset +=3D len(self.RawDataList[innerIndex]) * self.I= temSize else: Offset +=3D self.ItemSize @@ -431,7 +431,7 @@ class DbStringHeadTableItemList(DbItemList): self.ListSize =3D self.GetInterOffset(len(self.RawDataList) - = 1) + len(self.RawDataList[len(self.RawDataList)-1]) else: for Datas in self.RawDataList: - if type(Datas) in (list, tuple): + if type(Datas) in {list, tuple}: self.ListSize +=3D len(Datas) * self.ItemSize else: self.ListSize +=3D self.ItemSize @@ -783,7 +783,7 @@ def BuildExDataBase(Dict): Pad =3D 0xDA =20 UninitDataBaseSize =3D 0 - for Item in (DbUnInitValueUint64, DbUnInitValueUint32, DbUnInitValueUi= nt16, DbUnInitValueUint8, DbUnInitValueBoolean): + for Item in {DbUnInitValueUint64, DbUnInitValueUint32, DbUnInitValueUi= nt16, DbUnInitValueUint8, DbUnInitValueBoolean}: UninitDataBaseSize +=3D Item.GetListSize() =20 if (DbTotalLength - UninitDataBaseSize) % 8: @@ -1001,11 +1001,11 @@ def CreatePcdDatabasePhaseSpecificAutoGen (Platform= , DynamicPcdList, Phase): 'EX_TOKEN_NUMBER' : '0U', 'SIZE_TABLE_SIZE' : '2U', 'SKU_HEAD_SIZE' : '1U', - 'GUID_TABLE_EMPTY' : 'TRUE', - 'STRING_TABLE_EMPTY' : 'TRUE', - 'SKUID_TABLE_EMPTY' : 'TRUE', - 'DATABASE_EMPTY' : 'TRUE', - 'EXMAP_TABLE_EMPTY' : 'TRUE', + 'GUID_TABLE_EMPTY' : TAB_TRUE_1, + 'STRING_TABLE_EMPTY' : TAB_TRUE_1, + 'SKUID_TABLE_EMPTY' : TAB_TRUE_1, + 'DATABASE_EMPTY' : TAB_TRUE_1, + 'EXMAP_TABLE_EMPTY' : TAB_TRUE_1, 'PCD_DATABASE_UNINIT_EMPTY' : ' UINT8 dummy; /* PCD_DATABASE= _UNINIT is emptry */', 'SYSTEM_SKU_ID' : ' SKU_ID SystemSkuI= d;', 'SYSTEM_SKU_ID_VALUE' : '0U' @@ -1022,14 +1022,14 @@ def CreatePcdDatabasePhaseSpecificAutoGen (Platform= , DynamicPcdList, Phase): Dict['VARDEF_SKUID_' + DatumType] =3D [] Dict['VARDEF_VALUE_' + DatumType] =3D [] Dict['VARDEF_DB_VALUE_' + DatumType] =3D [] - for Init in ['INIT','UNINIT']: + for Init in {'INIT','UNINIT'}: Dict[Init+'_CNAME_DECL_' + DatumType] =3D [] Dict[Init+'_GUID_DECL_' + DatumType] =3D [] Dict[Init+'_NUMSKUS_DECL_' + DatumType] =3D [] Dict[Init+'_VALUE_' + DatumType] =3D [] Dict[Init+'_DB_VALUE_'+DatumType] =3D [] =20 - for Type in ['STRING_HEAD','VPD_HEAD','VARIABLE_HEAD']: + for Type in {'STRING_HEAD','VPD_HEAD','VARIABLE_HEAD'}: Dict[Type + '_CNAME_DECL'] =3D [] Dict[Type + '_GUID_DECL'] =3D [] Dict[Type + '_NUMSKUS_DECL'] =3D [] @@ -1087,7 +1087,7 @@ def CreatePcdDatabasePhaseSpecificAutoGen (Platform, = DynamicPcdList, Phase): i =3D 0 ReorderedDynPcdList =3D GetOrderedDynamicPcdList(DynamicPcdList, Platf= orm.PcdTokenNumber) for item in ReorderedDynPcdList: - if item.DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_U= INT64, TAB_VOID, "BOOLEAN"]: + if item.DatumType not in TAB_PCD_NUMERIC_TYPES_VOID: item.DatumType =3D TAB_VOID for Pcd in ReorderedDynPcdList: VoidStarTypeCurrSize =3D [] @@ -1130,11 +1130,11 @@ def CreatePcdDatabasePhaseSpecificAutoGen (Platform= , DynamicPcdList, Phase): Pcd.InitString =3D 'UNINIT' =20 if Pcd.DatumType =3D=3D TAB_VOID: - if Pcd.Type not in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_= VPD]: + if Pcd.Type not in {TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_= VPD}: Pcd.TokenTypeList =3D ['PCD_TYPE_STRING'] else: Pcd.TokenTypeList =3D [] - elif Pcd.DatumType =3D=3D 'BOOLEAN': + elif Pcd.DatumType =3D=3D TAB_BOOLEAN: Pcd.TokenTypeList =3D ['PCD_DATUM_TYPE_UINT8_BOOLEAN'] else: Pcd.TokenTypeList =3D ['PCD_DATUM_TYPE_' + Pcd.DatumType] @@ -1235,10 +1235,10 @@ def CreatePcdDatabasePhaseSpecificAutoGen (Platform= , DynamicPcdList, Phase): =20 if Pcd.DatumType =3D=3D TAB_UINT64: Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.Hii= DefaultValue + "ULL") - elif Pcd.DatumType in (TAB_UINT32, TAB_UINT16, TAB_UIN= T8): + elif Pcd.DatumType in {TAB_UINT32, TAB_UINT16, TAB_UIN= T8}: Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.Hii= DefaultValue + "U") - elif Pcd.DatumType =3D=3D "BOOLEAN": - if eval(Sku.HiiDefaultValue) in [1,0]: + elif Pcd.DatumType =3D=3D TAB_BOOLEAN: + if eval(Sku.HiiDefaultValue) in {1,0}: Dict['VARDEF_VALUE_'+Pcd.DatumType].append(str= (eval(Sku.HiiDefaultValue)) + "U") else: Dict['VARDEF_VALUE_'+Pcd.DatumType].append(Sku.Hii= DefaultValue) @@ -1323,7 +1323,7 @@ def CreatePcdDatabasePhaseSpecificAutoGen (Platform, = DynamicPcdList, Phase): else: if "PCD_TYPE_HII" not in Pcd.TokenTypeList: Pcd.TokenTypeList +=3D ['PCD_TYPE_DATA'] - if Sku.DefaultValue =3D=3D 'TRUE': + if Sku.DefaultValue =3D=3D TAB_TRUE_1: Pcd.InitString =3D 'INIT' else: Pcd.InitString =3D Pcd.isinit @@ -1333,10 +1333,10 @@ def CreatePcdDatabasePhaseSpecificAutoGen (Platform= , DynamicPcdList, Phase): # if Pcd.DatumType =3D=3D TAB_UINT64: ValueList.append(Sku.DefaultValue + "ULL") - elif Pcd.DatumType in (TAB_UINT32, TAB_UINT16, TAB_UINT8): + elif Pcd.DatumType in {TAB_UINT32, TAB_UINT16, TAB_UINT8}: ValueList.append(Sku.DefaultValue + "U") - elif Pcd.DatumType =3D=3D "BOOLEAN": - if Sku.DefaultValue in ["1", "0"]: + elif Pcd.DatumType =3D=3D TAB_BOOLEAN: + if Sku.DefaultValue in {"1", "0"}: ValueList.append(Sku.DefaultValue + "U") = =20 else: ValueList.append(Sku.DefaultValue) @@ -1516,7 +1516,7 @@ def CreatePcdDatabasePhaseSpecificAutoGen (Platform, = DynamicPcdList, Phase): StringTableSize +=3D Dict['PCD_CNAME_LENGTH'][index] StringTableIndex +=3D 1 if GuidList !=3D []: - Dict['GUID_TABLE_EMPTY'] =3D 'FALSE' + Dict['GUID_TABLE_EMPTY'] =3D TAB_FALSE_1 Dict['GUID_TABLE_SIZE'] =3D str(len(GuidList)) + 'U' else: Dict['GUID_STRUCTURE'] =3D [GuidStringToGuidStructureString('00000= 000-0000-0000-0000-000000000000')] @@ -1528,7 +1528,7 @@ def CreatePcdDatabasePhaseSpecificAutoGen (Platform, = DynamicPcdList, Phase): Dict['STRING_TABLE_GUID'].append('') Dict['STRING_TABLE_VALUE'].append('{ 0 }') else: - Dict['STRING_TABLE_EMPTY'] =3D 'FALSE' + Dict['STRING_TABLE_EMPTY'] =3D TAB_FALSE_1 Dict['STRING_TABLE_SIZE'] =3D str(StringTableSize) + 'U' =20 if Dict['SIZE_TABLE_CNAME'] =3D=3D []: @@ -1538,12 +1538,12 @@ def CreatePcdDatabasePhaseSpecificAutoGen (Platform= , DynamicPcdList, Phase): Dict['SIZE_TABLE_MAXIMUM_LENGTH'].append('0U') =20 if NumberOfLocalTokens !=3D 0: - Dict['DATABASE_EMPTY'] =3D 'FALSE' + Dict['DATABASE_EMPTY'] =3D TAB_FALSE_1 Dict['LOCAL_TOKEN_NUMBER_TABLE_SIZE'] =3D NumberOfLocalTokens Dict['LOCAL_TOKEN_NUMBER'] =3D NumberOfLocalTokens =20 if NumberOfExTokens !=3D 0: - Dict['EXMAP_TABLE_EMPTY'] =3D 'FALSE' + Dict['EXMAP_TABLE_EMPTY'] =3D TAB_FALSE_1 Dict['EXMAPPING_TABLE_SIZE'] =3D str(NumberOfExTokens) + 'U' Dict['EX_TOKEN_NUMBER'] =3D str(NumberOfExTokens) + 'U' else: diff --git a/BaseTools/Source/Python/AutoGen/GenVar.py b/BaseTools/Source/P= ython/AutoGen/GenVar.py index 35f022ac2e19..c01661864c6d 100644 --- a/BaseTools/Source/Python/AutoGen/GenVar.py +++ b/BaseTools/Source/Python/AutoGen/GenVar.py @@ -295,8 +295,8 @@ class VariableMgr(object): for value_char in tail.split(","): Buffer +=3D pack("=3DB",int(value_char,16)) data_len +=3D len(tail.split(",")) - elif data_type =3D=3D "BOOLEAN": - Buffer +=3D pack("=3DB",True) if var_value.upper() =3D=3D "TRU= E" else pack("=3DB",False) + elif data_type =3D=3D TAB_BOOLEAN: + Buffer +=3D pack("=3DB",True) if var_value.upper() =3D=3D TAB_= TRUE_1 else pack("=3DB",False) data_len +=3D 1 elif data_type =3D=3D DataType.TAB_UINT8: Buffer +=3D pack("=3DB",GetIntegerValue(var_value)) diff --git a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py b/B= aseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py index b2a9bb1134ed..63add891e3f1 100644 --- a/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py +++ b/BaseTools/Source/Python/AutoGen/ValidCheckingInfoObject.py @@ -58,7 +58,7 @@ class VAR_CHECK_PCD_VARIABLE_TAB_CONTAINER(object): itemIndex +=3D 1 realLength +=3D 5 for v_data in item.data: - if type(v_data) in (int, long): + if type(v_data) in {int, long}: realLength +=3D item.StorageWidth else: realLength +=3D item.StorageWidth @@ -138,7 +138,7 @@ class VAR_CHECK_PCD_VARIABLE_TAB_CONTAINER(object): Buffer +=3D b realLength +=3D 1 for v_data in item.data: - if type(v_data) in (int, long): + if type(v_data) in {int, long}: b =3D pack(PACK_CODE_BY_SIZE[item.StorageWidth], v= _data) Buffer +=3D b realLength +=3D item.StorageWidth diff --git a/BaseTools/Source/Python/BPDG/BPDG.py b/BaseTools/Source/Python= /BPDG/BPDG.py index 6c8f89f5d12b..88e12b247c58 100644 --- a/BaseTools/Source/Python/BPDG/BPDG.py +++ b/BaseTools/Source/Python/BPDG/BPDG.py @@ -134,7 +134,7 @@ def StartBpdg(InputFileName, MapFileName, VpdFileName, = Force): if os.path.exists(VpdFileName) and not Force: print "\nFile %s already exist, Overwrite(Yes/No)?[Y]: " % VpdFile= Name choice =3D sys.stdin.readline() - if choice.strip().lower() not in ['y', 'yes', '']: + if choice.strip().lower() not in {'y', 'yes', ''}: return =20 GenVPD =3D GenVpd.GenVPD (InputFileName, MapFileName, VpdFileName) diff --git a/BaseTools/Source/Python/BPDG/GenVpd.py b/BaseTools/Source/Pyth= on/BPDG/GenVpd.py index dba815415f92..7125788b5bfe 100644 --- a/BaseTools/Source/Python/BPDG/GenVpd.py +++ b/BaseTools/Source/Python/BPDG/GenVpd.py @@ -72,9 +72,9 @@ class PcdEntry: # =20 def _IsBoolean(self, ValueString, Size): if (Size =3D=3D "1"): - if ValueString.upper() in ["TRUE", "FALSE"]: + if ValueString.upper() in TAB_TRUE_FALSE_SET: return True - elif ValueString in ["0", "1", "0x0", "0x1", "0x00", "0x01"]: + elif ValueString in {"0", "1", "0x0", "0x1", "0x00", "0x01"}: return True =20 return False @@ -101,7 +101,7 @@ class PcdEntry: #=20 #=20 def _PackBooleanValue(self, ValueString): - if ValueString.upper() =3D=3D "TRUE" or ValueString in ["1", "0x1"= , "0x01"]: + if ValueString.upper() =3D=3D TAB_TRUE_1 or ValueString in {"1", "= 0x1", "0x01"}: try: self.PcdValue =3D pack(_FORMAT_CHAR[1], 1) except: diff --git a/BaseTools/Source/Python/Common/DataType.py b/BaseTools/Source/= Python/Common/DataType.py index 93136dff0db2..b86e403c10fb 100644 --- a/BaseTools/Source/Python/Common/DataType.py +++ b/BaseTools/Source/Python/Common/DataType.py @@ -41,10 +41,11 @@ TAB_UINT32 =3D 'UINT32' TAB_UINT64 =3D 'UINT64' TAB_VOID =3D 'VOID*' TAB_GUID =3D 'GUID' +TAB_BOOLEAN =3D 'BOOLEAN' =20 TAB_PCD_CLEAN_NUMERIC_TYPES =3D {TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UI= NT64} -TAB_PCD_NUMERIC_TYPES =3D {TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64, = 'BOOLEAN'} -TAB_PCD_NUMERIC_TYPES_VOID =3D {TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UIN= T64, 'BOOLEAN', TAB_VOID} +TAB_PCD_NUMERIC_TYPES =3D {TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64, = TAB_BOOLEAN} +TAB_PCD_NUMERIC_TYPES_VOID =3D {TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UIN= T64, TAB_BOOLEAN, TAB_VOID} =20 TAB_EDK_SOURCE =3D '$(EDK_SOURCE)' TAB_EFI_SOURCE =3D '$(EFI_SOURCE)' @@ -79,10 +80,10 @@ SUP_MODULE_SMM_CORE =3D 'SMM_CORE' SUP_MODULE_MM_STANDALONE =3D 'MM_STANDALONE' SUP_MODULE_MM_CORE_STANDALONE =3D 'MM_CORE_STANDALONE' =20 -SUP_MODULE_LIST =3D [SUP_MODULE_BASE, SUP_MODULE_SEC, SUP_MODULE_PEI_CORE,= SUP_MODULE_PEIM, SUP_MODULE_DXE_CORE, SUP_MODULE_DXE_DRIVER, \ +SUP_MODULE_SET =3D {SUP_MODULE_BASE, SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, = SUP_MODULE_PEIM, SUP_MODULE_DXE_CORE, SUP_MODULE_DXE_DRIVER, \ SUP_MODULE_DXE_RUNTIME_DRIVER, SUP_MODULE_DXE_SAL_DRIVE= R, SUP_MODULE_DXE_SMM_DRIVER, SUP_MODULE_UEFI_DRIVER, \ - SUP_MODULE_UEFI_APPLICATION, SUP_MODULE_USER_DEFINED, S= UP_MODULE_SMM_CORE, SUP_MODULE_MM_STANDALONE, SUP_MODULE_MM_CORE_STANDALONE] -SUP_MODULE_LIST_STRING =3D TAB_VALUE_SPLIT.join(SUP_MODULE_LIST) + SUP_MODULE_UEFI_APPLICATION, SUP_MODULE_USER_DEFINED, S= UP_MODULE_SMM_CORE, SUP_MODULE_MM_STANDALONE, SUP_MODULE_MM_CORE_STANDALONE} +SUP_MODULE_LIST_STRING =3D TAB_VALUE_SPLIT.join(SUP_MODULE_SET) SUP_MODULE_SET_PEI =3D {SUP_MODULE_PEIM, SUP_MODULE_PEI_CORE} =20 EDK_COMPONENT_TYPE_LIBRARY =3D 'LIBRARY' @@ -290,9 +291,23 @@ TAB_PCDS_PATCHABLE_LOAD_FIX_ADDRESS_SET =3D {TAB_PCDS= _PATCHABLE_LOAD_FIX_ADDRESS_ TAB_PCDS_PATCHABLE_LOAD_FIX_AD= DRESS_SMM_PAGE_SIZE} =20 ## The mapping dictionary from datum type to its maximum number. -MAX_VAL_TYPE =3D {"BOOLEAN":0x01, TAB_UINT8:0xFF, TAB_UINT16:0xFFFF, TAB_U= INT32:0xFFFFFFFF, TAB_UINT64:0xFFFFFFFFFFFFFFFF} +MAX_VAL_TYPE =3D {TAB_BOOLEAN:0x01, TAB_UINT8:0xFF, TAB_UINT16:0xFFFF, TAB= _UINT32:0xFFFFFFFF, TAB_UINT64:0xFFFFFFFFFFFFFFFF} ## The mapping dictionary from datum type to size string. -MAX_SIZE_TYPE =3D {"BOOLEAN":1, TAB_UINT8:1, TAB_UINT16:2, TAB_UINT32:4, T= AB_UINT64:8} +MAX_SIZE_TYPE =3D {TAB_BOOLEAN:1, TAB_UINT8:1, TAB_UINT16:2, TAB_UINT32:4,= TAB_UINT64:8} + +TAB_TRUE_1 =3D 'TRUE' +TAB_TRUE_2 =3D 'true' +TAB_TRUE_3 =3D 'True' + +TAB_FALSE_1 =3D 'FALSE' +TAB_FALSE_2 =3D 'false' +TAB_FALSE_3 =3D 'False' + +TAB_TRUE_SET =3D {TAB_TRUE_1,TAB_TRUE_2,TAB_TRUE_3} +TAB_FALSE_SET =3D {TAB_FALSE_1,TAB_FALSE_2,TAB_FALSE_3} + +TAB_TRUE_FALSE_SET =3D {TAB_TRUE_1,TAB_FALSE_1} + =20 TAB_DEPEX =3D 'Depex' TAB_DEPEX_COMMON =3D TAB_DEPEX + TAB_SPLIT + TAB_ARCH_COMMON @@ -500,7 +515,12 @@ DEPEX_OPCODE_TRUE =3D "TRUE" DEPEX_OPCODE_FALSE =3D "FALSE" =20 # Dependency Expression -DEPEX_SUPPORTED_OPCODE_SET =3D {"BEFORE", "AFTER", "PUSH", "AND", "OR", "N= OT", "END", "SOR", "TRUE", "FALSE", '(', ')'} +DEPEX_SUPPORTED_OPCODE_SET =3D {DEPEX_OPCODE_BEFORE, DEPEX_OPCODE_AFTER, + DEPEX_OPCODE_PUSH, DEPEX_OPCODE_AND,=20 + DEPEX_OPCODE_OR, DEPEX_OPCODE_NOT,=20 + DEPEX_OPCODE_END, DEPEX_OPCODE_SOR, + DEPEX_OPCODE_TRUE, DEPEX_OPCODE_FALSE, + '(', ')'} =20 TAB_STATIC_LIBRARY =3D "STATIC-LIBRARY-FILE" TAB_DYNAMIC_LIBRARY =3D "DYNAMIC-LIBRARY-FILE" diff --git a/BaseTools/Source/Python/Common/Expression.py b/BaseTools/Sourc= e/Python/Common/Expression.py index 36f2654fc9cf..3133f610b4a7 100644 --- a/BaseTools/Source/Python/Common/Expression.py +++ b/BaseTools/Source/Python/Common/Expression.py @@ -656,9 +656,9 @@ class ValueExpression(BaseExpression): =20 if self._Token.startswith('"'): self._Token =3D self._Token[1:-1] - elif self._Token in {"FALSE", "false", "False"}: + elif self._Token in TAB_FALSE_SET: self._Token =3D False - elif self._Token in {"TRUE", "true", "True"}: + elif self._Token in TAB_TRUE_SET: self._Token =3D True else: self.__IsNumberToken() @@ -1020,9 +1020,9 @@ class ValueExpressionEx(ValueExpression): else: raise BadExpression("Type: %s, Value: %s, %s"%(se= lf.PcdType, PcdValue, Value)) =20 - if PcdValue =3D=3D 'True': + if PcdValue =3D=3D TAB_TRUE_3: PcdValue =3D '1' - if PcdValue =3D=3D 'False': + if PcdValue =3D=3D TAB_FALSE_3: PcdValue =3D '0' =20 if RealValue: diff --git a/BaseTools/Source/Python/Common/Misc.py b/BaseTools/Source/Pyth= on/Common/Misc.py index bfb6e56a923f..5b8459e5007b 100644 --- a/BaseTools/Source/Python/Common/Misc.py +++ b/BaseTools/Source/Python/Common/Misc.py @@ -1403,9 +1403,9 @@ def ParseFieldValue (Value): if Value =3D=3D 0: return 0, 1 return Value, (Value.bit_length() + 7) / 8 - if Value.lower() =3D=3D 'true': + if Value.lower() =3D=3D TAB_TRUE_2: return 1, 1 - if Value.lower() =3D=3D 'false': + if Value.lower() =3D=3D TAB_FALSE_2: return 0, 1 return Value, 1 =20 @@ -1438,7 +1438,7 @@ def AnalyzeDscPcd(Setting, PcdType, DataType=3D''): FieldList =3D AnalyzePcdExpression(Setting) =20 IsValid =3D True - if PcdType in (MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_PATCHABLE_IN_MODULE= , MODEL_PCD_FEATURE_FLAG): + if PcdType in {MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_PATCHABLE_IN_MODULE= , MODEL_PCD_FEATURE_FLAG}: Value =3D FieldList[0] Size =3D '' if len(FieldList) > 1: @@ -1461,7 +1461,7 @@ def AnalyzeDscPcd(Setting, PcdType, DataType=3D''): IsValid =3D False Size =3D -1 return [str(Value), '', str(Size)], IsValid, 0 - elif PcdType in (MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX_DEFAU= LT): + elif PcdType in {MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX_DEFAU= LT}: Value =3D FieldList[0] Size =3D Type =3D '' if len(FieldList) > 1: @@ -1482,7 +1482,7 @@ def AnalyzeDscPcd(Setting, PcdType, DataType=3D''): IsValid =3D False Size =3D -1 return [Value, Type, str(Size)], IsValid, 0 - elif PcdType in (MODEL_PCD_DYNAMIC_VPD, MODEL_PCD_DYNAMIC_EX_VPD): + elif PcdType in {MODEL_PCD_DYNAMIC_VPD, MODEL_PCD_DYNAMIC_EX_VPD}: VpdOffset =3D FieldList[0] Value =3D Size =3D '' if not DataType =3D=3D TAB_VOID: @@ -1504,7 +1504,7 @@ def AnalyzeDscPcd(Setting, PcdType, DataType=3D''): IsValid =3D False Size =3D -1 return [VpdOffset, str(Size), Value], IsValid, 2 - elif PcdType in (MODEL_PCD_DYNAMIC_HII, MODEL_PCD_DYNAMIC_EX_HII): + elif PcdType in {MODEL_PCD_DYNAMIC_HII, MODEL_PCD_DYNAMIC_EX_HII}: HiiString =3D FieldList[0] Guid =3D Offset =3D Value =3D Attribute =3D '' if len(FieldList) > 1: @@ -1574,11 +1574,11 @@ def CheckPcdDatum(Type, Value): PrintList =3D list(Printset) PrintList.sort() return False, "Invalid PCD string value of type [%s]; must= be printable chars %s." % (Type, PrintList) - elif Type =3D=3D 'BOOLEAN': - if Value not in ['TRUE', 'True', 'true', '0x1', '0x01', '1', 'FALS= E', 'False', 'false', '0x0', '0x00', '0']: + elif Type =3D=3D TAB_BOOLEAN: + if Value not in {TAB_TRUE_1, TAB_TRUE_2, TAB_TRUE_3, '0x1', '0x01'= , '1', TAB_FALSE_1, TAB_FALSE_2, TAB_FALSE_3, '0x0', '0x00', '0'}: return False, "Invalid value [%s] of type [%s]; must be one of= TRUE, True, true, 0x1, 0x01, 1"\ ", FALSE, False, false, 0x0, 0x00, 0" % (Value, = Type) - elif Type in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64]: + elif Type in {TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64}: try: Value =3D long(Value, 0) except: @@ -1601,7 +1601,7 @@ def SplitOption(OptionString): QuotationMark =3D "" for Index in range(0, len(OptionString)): CurrentChar =3D OptionString[Index] - if CurrentChar in ['"', "'"]: + if CurrentChar in {'"', "'"}: if QuotationMark =3D=3D CurrentChar: QuotationMark =3D "" elif QuotationMark =3D=3D "": @@ -1610,7 +1610,7 @@ def SplitOption(OptionString): elif QuotationMark: continue =20 - if CurrentChar in ["/", "-"] and LastChar in [" ", "\t", "\r", "\n= "]: + if CurrentChar in {"/", "-"} and LastChar in {" ", "\t", "\r", "\n= "}: if Index > OptionStart: OptionList.append(OptionString[OptionStart:Index - 1]) OptionStart =3D Index @@ -2083,7 +2083,7 @@ def PackRegistryFormatGuid(Guid): # @retval Value The integer value that the input represents # def GetIntegerValue(Input): - if type(Input) in (int, long): + if type(Input) in {int, long}: return Input String =3D Input if String.endswith("U"): diff --git a/BaseTools/Source/Python/Common/Parsing.py b/BaseTools/Source/P= ython/Common/Parsing.py index 453c2039e3d9..94e73f2b78f9 100644 --- a/BaseTools/Source/Python/Common/Parsing.py +++ b/BaseTools/Source/Python/Common/Parsing.py @@ -42,7 +42,7 @@ def ParseDefineMacro2(Table, RecordSets, GlobalMacro): # # Replace the Macros # - for Value in (v for v in RecordSets.values() if v): + for Value in [v for v in RecordSets.values() if v]: for Item in Value: Item[0] =3D ReplaceMacro(Item[0], Macros) =20 diff --git a/BaseTools/Source/Python/Common/RangeExpression.py b/BaseTools/= Source/Python/Common/RangeExpression.py index 7f504d6e310c..fe78bcfd90bb 100644 --- a/BaseTools/Source/Python/Common/RangeExpression.py +++ b/BaseTools/Source/Python/Common/RangeExpression.py @@ -327,12 +327,12 @@ class RangeExpression(BaseExpression): =20 def Eval(self, Operator, Oprand1, Oprand2 =3D None): =20 - if Operator in ["!", "NOT", "not"]: + if Operator in {"!", "NOT", "not"}: if not gGuidPattern.match(Oprand1.strip()): raise BadExpression(ERR_STRING_EXPR % Operator) return self.NegtiveRange(Oprand1) else: - if Operator in ["=3D=3D", ">=3D", "<=3D", ">", "<", '^']: + if Operator in {"=3D=3D", ">=3D", "<=3D", ">", "<", '^'}: return self.EvalRange(Operator, Oprand1) elif Operator =3D=3D 'and' : if not gGuidPatternEnd.match(Oprand1.strip()) or not gGuid= PatternEnd.match(Oprand2.strip()): @@ -439,7 +439,7 @@ class RangeExpression(BaseExpression): Val =3D self._RelExpr() while self._IsOperator({"!=3D", "NOT", "not"}): Op =3D self._Token - if Op in ["!", "NOT", "not"]: + if Op in {"!", "NOT", "not"}: if not self._IsOperator({"IN", "in"}): raise BadExpression(ERR_REL_NOT_IN) Op +=3D ' ' + self._Token @@ -576,9 +576,9 @@ class RangeExpression(BaseExpression): =20 if self._Token.startswith('"'): self._Token =3D self._Token[1:-1] - elif self._Token in ["FALSE", "false", "False"]: + elif self._Token in TAB_FALSE_SET: self._Token =3D False - elif self._Token in ["TRUE", "true", "True"]: + elif self._Token in TAB_TRUE_SET: self._Token =3D True else: self.__IsNumberToken() diff --git a/BaseTools/Source/Python/Common/TargetTxtClassObject.py b/BaseT= ools/Source/Python/Common/TargetTxtClassObject.py index 6f5e5f0d173d..ca116ed9b0aa 100644 --- a/BaseTools/Source/Python/Common/TargetTxtClassObject.py +++ b/BaseTools/Source/Python/Common/TargetTxtClassObject.py @@ -96,8 +96,8 @@ class TargetTxtClassObject(object): else: Value =3D "" =20 - if Key in [DataType.TAB_TAT_DEFINES_ACTIVE_PLATFORM, DataType.= TAB_TAT_DEFINES_TOOL_CHAIN_CONF, \ - DataType.TAB_TAT_DEFINES_ACTIVE_MODULE, DataType.TA= B_TAT_DEFINES_BUILD_RULE_CONF]: + if Key in {DataType.TAB_TAT_DEFINES_ACTIVE_PLATFORM, DataType.= TAB_TAT_DEFINES_TOOL_CHAIN_CONF, \ + DataType.TAB_TAT_DEFINES_ACTIVE_MODULE, DataType.TA= B_TAT_DEFINES_BUILD_RULE_CONF}: self.TargetTxtDictionary[Key] =3D Value.replace('\\', '/') if Key =3D=3D DataType.TAB_TAT_DEFINES_TOOL_CHAIN_CONF and= self.TargetTxtDictionary[Key]: if self.TargetTxtDictionary[Key].startswith("Conf/"): @@ -119,8 +119,8 @@ class TargetTxtClassObject(object): # The File pointed to by BUILD_RULE_CONF is not in= a Conf/ directory Build_Rule =3D os.path.join(self.ConfDirectoryPath= , self.TargetTxtDictionary[Key].strip()) self.TargetTxtDictionary[Key] =3D Build_Rule - elif Key in [DataType.TAB_TAT_DEFINES_TARGET, DataType.TAB_TAT= _DEFINES_TARGET_ARCH, \ - DataType.TAB_TAT_DEFINES_TOOL_CHAIN_TAG]: + elif Key in {DataType.TAB_TAT_DEFINES_TARGET, DataType.TAB_TAT= _DEFINES_TARGET_ARCH, \ + DataType.TAB_TAT_DEFINES_TOOL_CHAIN_TAG}: self.TargetTxtDictionary[Key] =3D Value.split() elif Key =3D=3D DataType.TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD= _NUMBER: try: diff --git a/BaseTools/Source/Python/Ecc/Check.py b/BaseTools/Source/Python= /Ecc/Check.py index e7bd97297538..6bb86f86a706 100644 --- a/BaseTools/Source/Python/Ecc/Check.py +++ b/BaseTools/Source/Python/Ecc/Check.py @@ -239,11 +239,6 @@ class Check(object): if EccGlobalData.gConfig.CFunctionLayoutCheckReturnType =3D=3D '1'= or EccGlobalData.gConfig.CFunctionLayoutCheckAll =3D=3D '1' or EccGlobalDa= ta.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking function layout return type ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.c', '.h'): -# FullName =3D os.path.join(Dirpath, F) -# c.CheckFuncLayoutReturnType(FullName) for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFil= eList: c.CheckFuncLayoutReturnType(FullName) =20 @@ -252,11 +247,6 @@ class Check(object): if EccGlobalData.gConfig.CFunctionLayoutCheckOptionalFunctionalMod= ifier =3D=3D '1' or EccGlobalData.gConfig.CFunctionLayoutCheckAll =3D=3D '1= ' or EccGlobalData.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking function layout modifier ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.c', '.h'): -# FullName =3D os.path.join(Dirpath, F) -# c.CheckFuncLayoutModifier(FullName) for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFil= eList: c.CheckFuncLayoutModifier(FullName) =20 @@ -266,11 +256,6 @@ class Check(object): if EccGlobalData.gConfig.CFunctionLayoutCheckFunctionName =3D=3D '= 1' or EccGlobalData.gConfig.CFunctionLayoutCheckAll =3D=3D '1' or EccGlobal= Data.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking function layout function name ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.c', '.h'): -# FullName =3D os.path.join(Dirpath, F) -# c.CheckFuncLayoutName(FullName) for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFil= eList: c.CheckFuncLayoutName(FullName) =20 @@ -279,12 +264,6 @@ class Check(object): if EccGlobalData.gConfig.CFunctionLayoutCheckFunctionPrototype =3D= =3D '1' or EccGlobalData.gConfig.CFunctionLayoutCheckAll =3D=3D '1' or EccG= lobalData.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking function layout function prototype .= ..") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.c'): -# FullName =3D os.path.join(Dirpath, F) -# EdkLogger.quiet("[PROTOTYPE]" + FullName) -# c.CheckFuncLayoutPrototype(FullName) for FullName in EccGlobalData.gCFileList: EdkLogger.quiet("[PROTOTYPE]" + FullName) c.CheckFuncLayoutPrototype(FullName) @@ -294,11 +273,6 @@ class Check(object): if EccGlobalData.gConfig.CFunctionLayoutCheckFunctionBody =3D=3D '= 1' or EccGlobalData.gConfig.CFunctionLayoutCheckAll =3D=3D '1' or EccGlobal= Data.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking function layout function body ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.c'): -# FullName =3D os.path.join(Dirpath, F) -# c.CheckFuncLayoutBody(FullName) for FullName in EccGlobalData.gCFileList: c.CheckFuncLayoutBody(FullName) =20 @@ -309,12 +283,6 @@ class Check(object): if EccGlobalData.gConfig.CFunctionLayoutCheckNoInitOfVariable =3D= =3D '1' or EccGlobalData.gConfig.CFunctionLayoutCheckAll =3D=3D '1' or EccG= lobalData.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking function layout local variables ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.c'): -# FullName =3D os.path.join(Dirpath, F) -# c.CheckFuncLayoutLocalVariable(FullName) - for FullName in EccGlobalData.gCFileList: c.CheckFuncLayoutLocalVariable(FullName) =20 @@ -337,11 +305,6 @@ class Check(object): if EccGlobalData.gConfig.DeclarationDataTypeCheckNoUseCType =3D=3D= '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll =3D=3D '1' or Ecc= GlobalData.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking Declaration No use C type ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.h', '.c'): -# FullName =3D os.path.join(Dirpath, F) -# c.CheckDeclNoUseCType(FullName) for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFil= eList: c.CheckDeclNoUseCType(FullName) =20 @@ -350,11 +313,6 @@ class Check(object): if EccGlobalData.gConfig.DeclarationDataTypeCheckInOutModifier =3D= =3D '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll =3D=3D '1' or = EccGlobalData.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking Declaration argument modifier ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.h', '.c'): -# FullName =3D os.path.join(Dirpath, F) -# c.CheckDeclArgModifier(FullName) for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFil= eList: c.CheckDeclArgModifier(FullName) =20 @@ -368,12 +326,6 @@ class Check(object): if EccGlobalData.gConfig.DeclarationDataTypeCheckEnumeratedType = =3D=3D '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll =3D=3D '1' = or EccGlobalData.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking Declaration enum typedef ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.h', '.c'): -# FullName =3D os.path.join(Dirpath, F) -# EdkLogger.quiet("[ENUM]" + FullName) -# c.CheckDeclEnumTypedef(FullName) for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFil= eList: EdkLogger.quiet("[ENUM]" + FullName) c.CheckDeclEnumTypedef(FullName) @@ -383,12 +335,6 @@ class Check(object): if EccGlobalData.gConfig.DeclarationDataTypeCheckStructureDeclarat= ion =3D=3D '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll =3D=3D = '1' or EccGlobalData.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking Declaration struct typedef ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.h', '.c'): -# FullName =3D os.path.join(Dirpath, F) -# EdkLogger.quiet("[STRUCT]" + FullName) -# c.CheckDeclStructTypedef(FullName) for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFil= eList: EdkLogger.quiet("[STRUCT]" + FullName) c.CheckDeclStructTypedef(FullName) @@ -420,12 +366,6 @@ class Check(object): if EccGlobalData.gConfig.DeclarationDataTypeCheckUnionType =3D=3D = '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll =3D=3D '1' or EccG= lobalData.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking Declaration union typedef ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.h', '.c'): -# FullName =3D os.path.join(Dirpath, F) -# EdkLogger.quiet("[UNION]" + FullName) -# c.CheckDeclUnionTypedef(FullName) for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFil= eList: EdkLogger.quiet("[UNION]" + FullName) c.CheckDeclUnionTypedef(FullName) @@ -441,12 +381,6 @@ class Check(object): if EccGlobalData.gConfig.PredicateExpressionCheckBooleanValue =3D= =3D '1' or EccGlobalData.gConfig.PredicateExpressionCheckAll =3D=3D '1' or = EccGlobalData.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking predicate expression Boolean value .= ..") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.c'): -# FullName =3D os.path.join(Dirpath, F) -# EdkLogger.quiet("[BOOLEAN]" + FullName) -# c.CheckBooleanValueComparison(FullName) for FullName in EccGlobalData.gCFileList: EdkLogger.quiet("[BOOLEAN]" + FullName) c.CheckBooleanValueComparison(FullName) @@ -456,12 +390,6 @@ class Check(object): if EccGlobalData.gConfig.PredicateExpressionCheckNonBooleanOperato= r =3D=3D '1' or EccGlobalData.gConfig.PredicateExpressionCheckAll =3D=3D '1= ' or EccGlobalData.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking predicate expression Non-Boolean var= iable...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.c'): -# FullName =3D os.path.join(Dirpath, F) -# EdkLogger.quiet("[NON-BOOLEAN]" + FullName) -# c.CheckNonBooleanValueComparison(FullName) for FullName in EccGlobalData.gCFileList: EdkLogger.quiet("[NON-BOOLEAN]" + FullName) c.CheckNonBooleanValueComparison(FullName) @@ -471,12 +399,6 @@ class Check(object): if EccGlobalData.gConfig.PredicateExpressionCheckComparisonNullTyp= e =3D=3D '1' or EccGlobalData.gConfig.PredicateExpressionCheckAll =3D=3D '1= ' or EccGlobalData.gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking predicate expression NULL pointer ..= .") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.c'): -# FullName =3D os.path.join(Dirpath, F) -# EdkLogger.quiet("[POINTER]" + FullName) -# c.CheckPointerNullComparison(FullName) for FullName in EccGlobalData.gCFileList: EdkLogger.quiet("[POINTER]" + FullName) c.CheckPointerNullComparison(FullName) @@ -518,11 +440,6 @@ class Check(object): if EccGlobalData.gConfig.IncludeFileCheckIfndefStatement =3D=3D '1= ' or EccGlobalData.gConfig.IncludeFileCheckAll =3D=3D '1' or EccGlobalData.= gConfig.CheckAll =3D=3D '1': EdkLogger.quiet("Checking header file ifndef ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.h'): -# FullName =3D os.path.join(Dirpath, F) -# MsgList =3D c.CheckHeaderFileIfndef(FullName) for FullName in EccGlobalData.gHFileList: MsgList =3D c.CheckHeaderFileIfndef(FullName) =20 @@ -531,11 +448,6 @@ class Check(object): if EccGlobalData.gConfig.IncludeFileCheckData =3D=3D '1' or EccGlo= balData.gConfig.IncludeFileCheckAll =3D=3D '1' or EccGlobalData.gConfig.Che= ckAll =3D=3D '1': EdkLogger.quiet("Checking header file data ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.h'): -# FullName =3D os.path.join(Dirpath, F) -# MsgList =3D c.CheckHeaderFileData(FullName) for FullName in EccGlobalData.gHFileList: MsgList =3D c.CheckHeaderFileData(FullName) =20 @@ -555,10 +467,10 @@ class Check(object): for Dirpath, Dirnames, Filenames in self.WalkTree(): for F in Filenames: Ext =3D os.path.splitext(F)[1] - if Ext in ('.h', '.c'): + if Ext in {'.h', '.c'}: FullName =3D os.path.join(Dirpath, F) MsgList =3D c.CheckFileHeaderDoxygenComments(FullN= ame) - elif Ext in ('.inf', '.dec', '.dsc', '.fdf'): + elif Ext in {'.inf', '.dec', '.dsc', '.fdf'}: FullName =3D os.path.join(Dirpath, F) op =3D open(FullName).readlines() FileLinesList =3D op @@ -642,11 +554,6 @@ class Check(object): if EccGlobalData.gConfig.DoxygenCheckFunctionHeader =3D=3D '1' or = EccGlobalData.gConfig.DoxygenCheckAll =3D=3D '1' or EccGlobalData.gConfig.C= heckAll =3D=3D '1': EdkLogger.quiet("Checking Doxygen function header ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.h', '.c'): -# FullName =3D os.path.join(Dirpath, F) -# MsgList =3D c.CheckFuncHeaderDoxygenComments(Full= Name) for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFil= eList: MsgList =3D c.CheckFuncHeaderDoxygenComments(FullName) =20 @@ -662,11 +569,6 @@ class Check(object): if EccGlobalData.gConfig.DoxygenCheckCommentFormat =3D=3D '1' or E= ccGlobalData.gConfig.DoxygenCheckAll =3D=3D '1' or EccGlobalData.gConfig.Ch= eckAll =3D=3D '1': EdkLogger.quiet("Checking Doxygen comment ///< ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.h', '.c'): -# FullName =3D os.path.join(Dirpath, F) -# MsgList =3D c.CheckDoxygenTripleForwardSlash(Full= Name) for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFil= eList: MsgList =3D c.CheckDoxygenTripleForwardSlash(FullName) =20 @@ -675,11 +577,6 @@ class Check(object): if EccGlobalData.gConfig.DoxygenCheckCommand =3D=3D '1' or EccGlob= alData.gConfig.DoxygenCheckAll =3D=3D '1' or EccGlobalData.gConfig.CheckAll= =3D=3D '1': EdkLogger.quiet("Checking Doxygen command ...") =20 -# for Dirpath, Dirnames, Filenames in self.WalkTree(): -# for F in Filenames: -# if os.path.splitext(F)[1] in ('.h', '.c'): -# FullName =3D os.path.join(Dirpath, F) -# MsgList =3D c.CheckDoxygenCommand(FullName) for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFil= eList: MsgList =3D c.CheckDoxygenCommand(FullName) =20 @@ -1027,11 +924,11 @@ class Check(object): for Record in RecordSet: FunName =3D Record[0] if not EccGlobalData.gException.IsException(ERROR_= META_DATA_FILE_CHECK_PCD_TYPE, FunName): - if Model in [MODEL_PCD_FIXED_AT_BUILD] and not= FunName.startswith('FixedPcdGet'): + if Model =3D=3D MODEL_PCD_FIXED_AT_BUILD and n= ot FunName.startswith('FixedPcdGet'): EccGlobalData.gDb.TblReport.Insert(ERROR_M= ETA_DATA_FILE_CHECK_PCD_TYPE, OtherMsg=3D"The pcd '%s' is defined as a FixP= cd but now it is called by c function [%s]" % (PcdName, FunName), BelongsTo= Table=3DTblName, BelongsToItem=3DRecord[1]) - if Model in [MODEL_PCD_FEATURE_FLAG] and not F= unName.startswith(('FeaturePcdGet','FeaturePcdSet')): + if Model =3D=3D MODEL_PCD_FEATURE_FLAG and not= FunName.startswith(('FeaturePcdGet','FeaturePcdSet')): EccGlobalData.gDb.TblReport.Insert(ERROR_M= ETA_DATA_FILE_CHECK_PCD_TYPE, OtherMsg=3D"The pcd '%s' is defined as a Feat= urePcd but now it is called by c function [%s]" % (PcdName, FunName), Belon= gsToTable=3DTblName, BelongsToItem=3DRecord[1]) - if Model in [MODEL_PCD_PATCHABLE_IN_MODULE] an= d not FunName.startswith(('PatchablePcdGet','PatchablePcdSet')): + if Model =3D=3D MODEL_PCD_PATCHABLE_IN_MODULE = and not FunName.startswith(('PatchablePcdGet','PatchablePcdSet')): EccGlobalData.gDb.TblReport.Insert(ERROR_M= ETA_DATA_FILE_CHECK_PCD_TYPE, OtherMsg=3D"The pcd '%s' is defined as a Patc= hablePcd but now it is called by c function [%s]" % (PcdName, FunName), Bel= ongsToTable=3DTblName, BelongsToItem=3DRecord[1]) =20 #ERROR_META_DATA_FILE_CHECK_PCD_TYPE @@ -1188,12 +1085,12 @@ class Check(object): if Usage.startswith(DT.TAB_SPECIAL_COMMENT): PcdCommentList =3D Usage[2:].split(DT.TAB_SPECIAL_COMM= ENT) if len(PcdCommentList) >=3D 1: - if Model in [MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_F= EATURE_FLAG] \ + if Model in {MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_F= EATURE_FLAG} \ and not PcdCommentList[0].strip().startswith((= DT.TAB_INF_USAGE_SOME_PRO, = DT.TAB_INF_USAGE_CON, = DT.TAB_INF_USAGE_UNDEFINED)): EccGlobalData.gDb.TblReport.Insert(ERROR_META_= DATA_FILE_CHECK_FORMAT_PCD, OtherMsg=3DMsg, BelongsToTable=3DTable.Table, B= elongsToItem=3DRecord[0]) - if Model in [MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_= PCD_DYNAMIC, MODEL_PCD_DYNAMIC_EX] \ + if Model in {MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_= PCD_DYNAMIC, MODEL_PCD_DYNAMIC_EX} \ and not PcdCommentList[0].strip().startswith((= DT.TAB_INF_USAGE_PRO, = DT.TAB_INF_USAGE_SOME_PRO, = DT.TAB_INF_USAGE_CON, @@ -1259,7 +1156,7 @@ class Check(object): or EccGlobalData.gConfig.CheckAll =3D=3D '1': for Dirpath, Dirnames, Filenames in self.WalkTree(): for F in Filenames: - if os.path.splitext(F)[1] in ('.h', '.c'): + if os.path.splitext(F)[1] in {'.h', '.c'}: FullName =3D os.path.join(Dirpath, F) Id =3D c.GetTableID(FullName) if Id < 0: @@ -1269,7 +1166,7 @@ class Check(object): self.NamingConventionCheckTypedefStatement(FileTab= le) self.NamingConventionCheckVariableName(FileTable) self.NamingConventionCheckSingleCharacterVariable(= FileTable) - if os.path.splitext(F)[1] in ('.h'): + if os.path.splitext(F)[1] =3D=3D '.h': self.NamingConventionCheckIfndefStatement(File= Table) =20 self.NamingConventionCheckPathName() diff --git a/BaseTools/Source/Python/Ecc/MetaDataParser.py b/BaseTools/Sour= ce/Python/Ecc/MetaDataParser.py index 82ede3eb330c..f3b7b41298bc 100644 --- a/BaseTools/Source/Python/Ecc/MetaDataParser.py +++ b/BaseTools/Source/Python/Ecc/MetaDataParser.py @@ -135,8 +135,8 @@ def ParseHeaderCommentSection(CommentList, FileName =3D= None): # indication of different block; or in the position that Abstract = should be, also keep it # as it indicates that no abstract # - if not Comment and HeaderCommentStage not in [HEADER_COMMENT_LICEN= SE, \ - HEADER_COMMENT_DESCR= IPTION, HEADER_COMMENT_ABSTRACT]: + if not Comment and HeaderCommentStage not in {HEADER_COMMENT_LICEN= SE, \ + HEADER_COMMENT_DESCR= IPTION, HEADER_COMMENT_ABSTRACT}: continue =20 if HeaderCommentStage =3D=3D HEADER_COMMENT_NOT_STARTED: diff --git a/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.p= y b/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py index 0f9711ba109e..9baa59f94d9c 100644 --- a/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Ecc/MetaFileWorkspace/MetaFileParser.py @@ -482,14 +482,14 @@ class InfParser(MetaFileParser): IsFindBlockComment =3D False =20 for Index in range(0, len(Content)): - if self._SectionType in [MODEL_EFI_GUID, + if self._SectionType in {MODEL_EFI_GUID, MODEL_EFI_PROTOCOL, MODEL_EFI_PPI, MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_FEATURE_FLAG, MODEL_PCD_DYNAMIC_EX, - MODEL_PCD_DYNAMIC]: + MODEL_PCD_DYNAMIC}: Line =3D Content[Index].strip() if Line.startswith(TAB_SPECIAL_COMMENT): Usage +=3D ' ' + Line[Line.find(TAB_SPECIAL_COMMENT):] @@ -525,7 +525,7 @@ class InfParser(MetaFileParser): self._SectionHeaderParser() # Check invalid sections if self._Version < 0x00010005: - if self._SectionType in [MODEL_META_DATA_BUILD_OPTION, + if self._SectionType in {MODEL_META_DATA_BUILD_OPTION, MODEL_EFI_LIBRARY_CLASS, MODEL_META_DATA_PACKAGE, MODEL_PCD_FIXED_AT_BUILD, @@ -536,13 +536,13 @@ class InfParser(MetaFileParser): MODEL_EFI_GUID, MODEL_EFI_PROTOCOL, MODEL_EFI_PPI, - MODEL_META_DATA_USER_EXTENSIO= N]: + MODEL_META_DATA_USER_EXTENSIO= N}: EdkLogger.error('Parser', FORMAT_INVALID, "Section [%s] is not allowed in in= f file without version" % (self._SectionName), ExtraData=3Dself._CurrentLine, Fil= e=3Dself.MetaFile, Line=3Dself._LineIndex+1) - elif self._SectionType in [MODEL_EFI_INCLUDE, + elif self._SectionType in {MODEL_EFI_INCLUDE, MODEL_EFI_LIBRARY_INSTANCE, - MODEL_META_DATA_NMAKE]: + MODEL_META_DATA_NMAKE}: EdkLogger.error('Parser', FORMAT_INVALID, "Section [%s] is not allowed in inf fi= le with version 0x%08x" % (self._SectionName, self._Version), ExtraData=3Dself._CurrentLine, File=3D= self.MetaFile, Line=3Dself._LineIndex+1) @@ -694,9 +694,9 @@ class InfParser(MetaFileParser): # if value are 'True', 'true', 'TRUE' or 'False', 'false', 'FALSE'= , replace with integer 1 or 0. if self._ValueList[2] !=3D '': InfPcdValueList =3D GetSplitValueList(TokenList[1], TAB_VALUE_= SPLIT, 1) - if InfPcdValueList[0] in ['True', 'true', 'TRUE']: + if InfPcdValueList[0] in TAB_TRUE_SET: self._ValueList[2] =3D TokenList[1].replace(InfPcdValueLis= t[0], '1', 1); - elif InfPcdValueList[0] in ['False', 'false', 'FALSE']: + elif InfPcdValueList[0] in TAB_FALSE_SET: self._ValueList[2] =3D TokenList[1].replace(InfPcdValueLis= t[0], '0', 1); =20 ## [depex] section parser @@ -933,7 +933,7 @@ class DscParser(MetaFileParser): if DirectiveName not in self.DataType: EdkLogger.error("Parser", FORMAT_INVALID, "Unknown directive [= %s]" % DirectiveName, File=3Dself.MetaFile, Line=3Dself._LineIndex+1) - if DirectiveName in ['!IF', '!IFDEF', '!INCLUDE', '!IFNDEF', '!ELS= EIF'] and self._ValueList[1] =3D=3D '': + if DirectiveName in {'!IF', '!IFDEF', '!INCLUDE', '!IFNDEF', '!ELS= EIF'} and self._ValueList[1] =3D=3D '': EdkLogger.error("Parser", FORMAT_INVALID, "Missing expression", File=3Dself.MetaFile, Line=3Dself._LineIndex+1, ExtraData=3Dself._CurrentLine) @@ -944,9 +944,9 @@ class DscParser(MetaFileParser): while self._DirectiveStack: # Remove any !else or !elseif DirectiveInfo =3D self._DirectiveStack.pop() - if DirectiveInfo[0] in [MODEL_META_DATA_CONDITIONAL_STATEM= ENT_IF, + if DirectiveInfo[0] in {MODEL_META_DATA_CONDITIONAL_STATEM= ENT_IF, MODEL_META_DATA_CONDITIONAL_STATEM= ENT_IFDEF, - MODEL_META_DATA_CONDITIONAL_STATEM= ENT_IFNDEF]: + MODEL_META_DATA_CONDITIONAL_STATEM= ENT_IFNDEF}: break else: EdkLogger.error("Parser", FORMAT_INVALID, "Redundant '!end= if'", @@ -1053,9 +1053,9 @@ class DscParser(MetaFileParser): File=3Dself.MetaFile, Line=3Dself._LineIndex+1) # if value are 'True', 'true', 'TRUE' or 'False', 'false', 'FALSE'= , replace with integer 1 or 0. DscPcdValueList =3D GetSplitValueList(TokenList[1], TAB_VALUE_SPLI= T, 1) - if DscPcdValueList[0] in ['True', 'true', 'TRUE']: + if DscPcdValueList[0] in TAB_TRUE_SET: self._ValueList[2] =3D TokenList[1].replace(DscPcdValueList[0]= , '1', 1); - elif DscPcdValueList[0] in ['False', 'false', 'FALSE']: + elif DscPcdValueList[0] in TAB_FALSE_SET: self._ValueList[2] =3D TokenList[1].replace(DscPcdValueList[0]= , '0', 1); =20 ## [components] section parser @@ -1121,7 +1121,7 @@ class DscParser(MetaFileParser): Macros.update(GlobalData.gPlatformDefines) Macros.update(GlobalData.gCommandLineDefines) # PCD cannot be referenced in macro definition - if self._ItemType not in [MODEL_META_DATA_DEFINE, MODEL_META_DATA_= GLOBAL_DEFINE]: + if self._ItemType not in {MODEL_META_DATA_DEFINE, MODEL_META_DATA_= GLOBAL_DEFINE}: Macros.update(self._Symbols) return Macros =20 @@ -1303,8 +1303,8 @@ class DscParser(MetaFileParser): =20 def __ProcessDirective(self): Result =3D None - if self._ItemType in [MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, - MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF= ]: + if self._ItemType in {MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, + MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF= }: Macros =3D self._Macros Macros.update(GlobalData.gGlobalDefines) try: @@ -1325,9 +1325,9 @@ class DscParser(MetaFileParser): EdkLogger.debug(EdkLogger.DEBUG_5, str(Exc), self._ValueLi= st[1]) Result =3D False =20 - if self._ItemType in [MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, + if self._ItemType in {MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, MODEL_META_DATA_CONDITIONAL_STATEMENT_IFDEF, - MODEL_META_DATA_CONDITIONAL_STATEMENT_IFNDEF= ]: + MODEL_META_DATA_CONDITIONAL_STATEMENT_IFNDEF= }: self._DirectiveStack.append(self._ItemType) if self._ItemType =3D=3D MODEL_META_DATA_CONDITIONAL_STATEMENT= _IF: Result =3D bool(Result) @@ -1350,10 +1350,10 @@ class DscParser(MetaFileParser): while self._DirectiveStack: self._DirectiveEvalStack.pop() Directive =3D self._DirectiveStack.pop() - if Directive in [MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, + if Directive in {MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, MODEL_META_DATA_CONDITIONAL_STATEMENT_IFD= EF, MODEL_META_DATA_CONDITIONAL_STATEMENT_ELS= E, - MODEL_META_DATA_CONDITIONAL_STATEMENT_IFN= DEF]: + MODEL_META_DATA_CONDITIONAL_STATEMENT_IFN= DEF}: break elif self._ItemType =3D=3D MODEL_META_DATA_INCLUDE: # The included file must be relative to workspace or same dire= ctory as DSC file @@ -1450,9 +1450,9 @@ class DscParser(MetaFileParser): except WrnExpression, Value: ValueList[-1] =3D Value.result =20 - if ValueList[-1] =3D=3D 'True': + if ValueList[-1] =3D=3D TAB_TRUE_3: ValueList[-1] =3D '1' - if ValueList[-1] =3D=3D 'False': + if ValueList[-1] =3D=3D TAB_FALSE_3: ValueList[-1] =3D '0' =20 =20 self._ValueList[2] =3D '|'.join(ValueList) @@ -1880,9 +1880,9 @@ class DecParser(MetaFileParser): if self._UniObj: self._UniObj.CheckPcdInfo(TokenList[0]) =20 - if ValueList[0] in ['True', 'true', 'TRUE']: + if ValueList[0] in TAB_TRUE_SET: ValueList[0] =3D '1' - elif ValueList[0] in ['False', 'false', 'FALSE']: + elif ValueList[0] in TAB_FALSE_SET: ValueList[0] =3D '0' =20 self._ValueList[2] =3D ValueList[0].strip() + '|' + ValueList[1].s= trip() + '|' + ValueList[2].strip() diff --git a/BaseTools/Source/Python/Ecc/c.py b/BaseTools/Source/Python/Ecc= /c.py index 4c49d1ca570f..29e8a81d8ef9 100644 --- a/BaseTools/Source/Python/Ecc/c.py +++ b/BaseTools/Source/Python/Ecc/c.py @@ -22,6 +22,7 @@ from Common import EdkLogger from EccToolError import * import EccGlobalData import MetaDataParser +from Common.DataType import TAB_BOOLEAN =20 IncludeFileListDict =3D {} AllIncludeFileListDict =3D {} @@ -518,7 +519,7 @@ def CollectSourceCodeDataIntoDB(RootDir): collector =3D None FullName =3D os.path.normpath(os.path.join(dirpath, f)) model =3D DataClass.MODEL_FILE_OTHERS - if os.path.splitext(f)[1] in ('.h', '.c'): + if os.path.splitext(f)[1] in {'.h', '.c'}: EdkLogger.info("Parsing " + FullName) model =3D f.endswith('c') and DataClass.MODEL_FILE_C or Da= taClass.MODEL_FILE_H collector =3D CodeFragmentCollector.CodeFragmentCollector(= FullName) @@ -543,7 +544,7 @@ def CollectSourceCodeDataIntoDB(RootDir): =20 Db =3D GetDB() for file in FileObjList: - if file.ExtName.upper() not in ['INF', 'DEC', 'DSC', 'FDF']: + if file.ExtName.upper() not in {'INF', 'DEC', 'DSC', 'FDF'}: Db.InsertOneFile(file) =20 Db.UpdateIdentifierBelongsToFunction() @@ -571,7 +572,7 @@ def GetTableID(FullFileName, ErrorMsgList=3DNone): return FileID =20 def GetIncludeFileList(FullFileName): - if os.path.splitext(FullFileName)[1].upper() not in ('.H'): + if os.path.splitext(FullFileName)[1].upper() not =3D=3D '.H': return [] IFList =3D IncludeFileListDict.get(FullFileName) if IFList is not None: @@ -991,7 +992,7 @@ def GetFinalTypeValue(Type, FieldName, TypedefDict, SUD= ict): while LBPos =3D=3D -1: FTList =3D Value.split() for FT in FTList: - if FT not in ('struct', 'union'): + if FT not in {'struct', 'union'}: Value =3D TypedefDict.get(FT) if Value is None: Value =3D SUDict.get(FT) @@ -1639,7 +1640,7 @@ def CheckMemberVariableFormat(Name, Value, FileTable,= TdId, ModelId): TokenList =3D Field.split() # Remove pointers before variable Token =3D TokenList[-1] - if Token in ['OPTIONAL']: + if Token =3D=3D 'OPTIONAL': Token =3D TokenList[-2] if not Pattern.match(Token.lstrip('*')): ErrMsgList.append(Token.lstrip('*')) @@ -2046,18 +2047,18 @@ def CheckNonBooleanValueComparison(FullFileName): if SearchInCache: Type =3D FuncReturnTypeDict.get(PredVarStr) if Type is not None: - if Type.find('BOOLEAN') =3D=3D -1: + if Type.find(TAB_BOOLEAN) =3D=3D -1: PrintErrorMsg(ERROR_PREDICATE_EXPRESSION_CHECK= _NO_BOOLEAN_OPERATOR, 'Predicate Expression: %s' % Exp, FileTable, Str[2]) continue =20 if PredVarStr in FuncReturnTypeDict: continue - Type =3D GetVarInfo(PredVarList, FuncRecord, FullFileName,= IsFuncCall, 'BOOLEAN', StarList) + Type =3D GetVarInfo(PredVarList, FuncRecord, FullFileName,= IsFuncCall, TAB_BOOLEAN, StarList) if SearchInCache: FuncReturnTypeDict[PredVarStr] =3D Type if Type is None: continue - if Type.find('BOOLEAN') =3D=3D -1: + if Type.find(TAB_BOOLEAN) =3D=3D -1: PrintErrorMsg(ERROR_PREDICATE_EXPRESSION_CHECK_NO_BOOL= EAN_OPERATOR, 'Predicate Expression: %s' % Exp, FileTable, Str[2]) =20 =20 @@ -2101,7 +2102,7 @@ def CheckBooleanValueComparison(FullFileName): =20 for Exp in GetPredicateListFromPredicateExpStr(Str[0]): PredInfo =3D SplitPredicateStr(Exp) - if PredInfo[1] in ('=3D=3D', '!=3D') and PredInfo[0][1] in ('T= RUE', 'FALSE'): + if PredInfo[1] in {'=3D=3D', '!=3D'} and PredInfo[0][1] in TAB= _TRUE_FALSE_SET: PredVarStr =3D PredInfo[0][0].strip() IsFuncCall =3D False SearchInCache =3D False @@ -2125,19 +2126,19 @@ def CheckBooleanValueComparison(FullFileName): if SearchInCache: Type =3D FuncReturnTypeDict.get(PredVarStr) if Type is not None: - if Type.find('BOOLEAN') !=3D -1: + if Type.find(TAB_BOOLEAN) !=3D -1: PrintErrorMsg(ERROR_PREDICATE_EXPRESSION_CHECK= _BOOLEAN_VALUE, 'Predicate Expression: %s' % Exp, FileTable, Str[2]) continue =20 if PredVarStr in FuncReturnTypeDict: continue =20 - Type =3D GetVarInfo(PredVarList, FuncRecord, FullFileName,= IsFuncCall, 'BOOLEAN', StarList) + Type =3D GetVarInfo(PredVarList, FuncRecord, FullFileName,= IsFuncCall, TAB_BOOLEAN, StarList) if SearchInCache: FuncReturnTypeDict[PredVarStr] =3D Type if Type is None: continue - if Type.find('BOOLEAN') !=3D -1: + if Type.find(TAB_BOOLEAN) !=3D -1: PrintErrorMsg(ERROR_PREDICATE_EXPRESSION_CHECK_BOOLEAN= _VALUE, 'Predicate Expression: %s' % Exp, FileTable, Str[2]) =20 =20 @@ -2236,7 +2237,7 @@ def CheckDoxygenCommand(FullFileName): continue if not Part.replace('@', '').strip(): continue - if Part.lstrip('@') in ['{', '}']: + if Part.lstrip('@') in {'{', '}'}: continue if Part.lstrip('@').isalpha(): if Part.lstrip('@') not in DoxygenCommandList: diff --git a/BaseTools/Source/Python/Eot/Parser.py b/BaseTools/Source/Pytho= n/Eot/Parser.py index 14c287588a01..f7ce6371e0ea 100644 --- a/BaseTools/Source/Python/Eot/Parser.py +++ b/BaseTools/Source/Python/Eot/Parser.py @@ -72,8 +72,8 @@ def PreProcess(Filename, MergeMultipleLines =3D True, Lin= eNo =3D -1): if IsFindBlockCode and Line[-1] !=3D TAB_SLASH: ReservedLine =3D (ReservedLine + TAB_SPACE_SPLIT + Line).s= trip() Lines.append(ReservedLine) - for Index in (0, ReservedLineLength): - Lines.append('') + Lines.append('') + Lines.append('') ReservedLine =3D '' ReservedLineLength =3D 0 IsFindBlockCode =3D False diff --git a/BaseTools/Source/Python/Eot/Report.py b/BaseTools/Source/Pytho= n/Eot/Report.py index 99b8b152180a..0e9d7300f4f2 100644 --- a/BaseTools/Source/Python/Eot/Report.py +++ b/BaseTools/Source/Python/Eot/Report.py @@ -17,6 +17,7 @@ import Common.LongFilePathOs as os import EotGlobalData from Common.LongFilePathSupport import OpenLongFilePath as open +from Common.DataType import * =20 ## Report() class # @@ -138,11 +139,13 @@ class Report(object): # @param DepexString: A DEPEX string needed to be parsed # def GenerateDepex(self, DepexString): - NonGuidList =3D ['AND', 'OR', 'NOT', 'BEFORE', 'AFTER', 'TRUE', 'F= ALSE'] + NonGuidSet =3D {DEPEX_OPCODE_BEFORE, DEPEX_OPCODE_AFTER,=20 + DEPEX_OPCODE_AND, DEPEX_OPCODE_OR, DEPEX_OPCODE_NOT, + DEPEX_OPCODE_TRUE, DEPEX_OPCODE_FALSE} ItemList =3D DepexString.split(' ') DepexString =3D '' for Item in ItemList: - if Item not in NonGuidList: + if Item not in NonGuidSet: SqlCommand =3D """select DISTINCT GuidName from Report whe= re GuidValue like '%s' and ItemMode =3D 'Produced' group by GuidName""" % (= Item) RecordSet =3D EotGlobalData.gDb.TblReport.Exec(SqlCommand) if RecordSet !=3D []: @@ -234,7 +237,7 @@ class Report(object): # def GenerateFfs(self, FfsObj): self.FfsIndex =3D self.FfsIndex + 1 - if FfsObj is not None and FfsObj.Type in [0x03, 0x04, 0x05, 0x06, = 0x07, 0x08, 0xA]: + if FfsObj is not None and FfsObj.Type in {0x03, 0x04, 0x05, 0x06, = 0x07, 0x08, 0xA}: FfsGuid =3D FfsObj.Guid FfsOffset =3D FfsObj._OFF_ FfsName =3D 'Unknown-Module' @@ -278,9 +281,9 @@ class Report(object): """ % (self= .FfsIndex, self.FfsIndex, self.FfsIndex, FfsPath, FfsName, FfsGuid, FfsOffs= et, FfsType, self.FfsIndex) =20 if self.DispatchList: - if FfsObj.Type in [0x04, 0x06]: + if FfsObj.Type in {0x04, 0x06}: self.DispatchList.write("%s %s %s %s\n" % (FfsGuid, "P= ", FfsName, FfsPath)) - if FfsObj.Type in [0x05, 0x07, 0x08, 0x0A]: + if FfsObj.Type in {0x05, 0x07, 0x08, 0x0A}: self.DispatchList.write("%s %s %s %s\n" % (FfsGuid, "D= ", FfsName, FfsPath)) =20 self.WriteLn(Content) diff --git a/BaseTools/Source/Python/Eot/c.py b/BaseTools/Source/Python/Eot= /c.py index 8199ce5ee73e..84a6f0961279 100644 --- a/BaseTools/Source/Python/Eot/c.py +++ b/BaseTools/Source/Python/Eot/c.py @@ -345,7 +345,7 @@ def CreateCCodeDB(FileNameList): ParseErrorFileList =3D [] ParsedFiles =3D {} for FullName in FileNameList: - if os.path.splitext(FullName)[1] in ('.h', '.c'): + if os.path.splitext(FullName)[1] in {'.h', '.c'}: if FullName.lower() in ParsedFiles: continue ParsedFiles[FullName.lower()] =3D 1 diff --git a/BaseTools/Source/Python/GenFds/DataSection.py b/BaseTools/Sour= ce/Python/GenFds/DataSection.py index 71c2796b0b39..cc9c4d5b9aa7 100644 --- a/BaseTools/Source/Python/GenFds/DataSection.py +++ b/BaseTools/Source/Python/GenFds/DataSection.py @@ -92,7 +92,7 @@ class DataSection (DataSectionClassObject): self.Alignment =3D str (ImageObj.SectionAlignment / 0x1000= 00) + 'M' =20 NoStrip =3D True - if self.SecType in (BINARY_FILE_TYPE_TE, BINARY_FILE_TYPE_PE32): + if self.SecType in {BINARY_FILE_TYPE_TE, BINARY_FILE_TYPE_PE32}: if self.KeepReloc is not None: NoStrip =3D self.KeepReloc =20 diff --git a/BaseTools/Source/Python/GenFds/DepexSection.py b/BaseTools/Sou= rce/Python/GenFds/DepexSection.py index 4392b9c62409..0521dd5b8d43 100644 --- a/BaseTools/Source/Python/GenFds/DepexSection.py +++ b/BaseTools/Source/Python/GenFds/DepexSection.py @@ -82,7 +82,10 @@ class DepexSection (DepexSectionClassObject): ExpList =3D self.Expression.split() =20 for Exp in ExpList: - if Exp.upper() not in ('AND', 'OR', 'NOT', 'TRUE', 'FALSE'= , 'SOR', 'BEFORE', 'AFTER', 'END'): + if Exp.upper() not in {DEPEX_OPCODE_BEFORE, DEPEX_OPCODE_A= FTER,=20 + DEPEX_OPCODE_AND, DEPEX_OPCODE_OR, DEPEX_OPCODE_NO= T, + DEPEX_OPCODE_END, DEPEX_OPCODE_SOR, DEPEX_OPCODE_T= RUE, + DEPEX_OPCODE_FALSE}: GuidStr =3D self.__FindGuidValue(Exp) if GuidStr is None: EdkLogger.error("GenFds", RESOURCE_NOT_AVAILABLE, diff --git a/BaseTools/Source/Python/GenFds/FdfParser.py b/BaseTools/Source= /Python/GenFds/FdfParser.py index 55348083b954..61b31bd36ff2 100644 --- a/BaseTools/Source/Python/GenFds/FdfParser.py +++ b/BaseTools/Source/Python/GenFds/FdfParser.py @@ -280,7 +280,7 @@ class FdfParser: Count =3D 0 while not self.__EndOfFile(): Count +=3D 1 - if self.__CurrentChar() in (T_CHAR_NULL, T_CHAR_CR, T_CHAR_LF,= T_CHAR_SPACE, T_CHAR_TAB): + if self.__CurrentChar() in {T_CHAR_NULL, T_CHAR_CR, T_CHAR_LF,= T_CHAR_SPACE, T_CHAR_TAB}: self.__SkippedChars +=3D str(self.__CurrentChar()) self.__GetOneChar() =20 @@ -423,14 +423,14 @@ class FdfParser: return =20 Offset =3D StartPos[1] - while self.Profile.FileLinesList[StartPos[0]][Offset] not in ('\r'= , '\n'): + while self.Profile.FileLinesList[StartPos[0]][Offset] not in {'\r'= , '\n'}: self.Profile.FileLinesList[StartPos[0]][Offset] =3D Value Offset +=3D 1 =20 Line =3D StartPos[0] while Line < EndPos[0]: Offset =3D 0 - while self.Profile.FileLinesList[Line][Offset] not in ('\r', '= \n'): + while self.Profile.FileLinesList[Line][Offset] not in {'\r', '= \n'}: self.Profile.FileLinesList[Line][Offset] =3D Value Offset +=3D 1 Line +=3D 1 @@ -741,7 +741,7 @@ class FdfParser: PreIndex =3D 0 StartPos =3D CurLine.find('$(', PreIndex) EndPos =3D CurLine.find(')', StartPos+2) - while StartPos !=3D -1 and EndPos !=3D -1 and self.__T= oken not in ['!ifdef', '!ifndef', '!if', '!elseif']: + while StartPos !=3D -1 and EndPos !=3D -1 and self.__T= oken not in {'!ifdef', '!ifndef', '!if', '!elseif'}: MacroName =3D CurLine[StartPos+2 : EndPos] MacorValue =3D self.__GetMacroValue(MacroName) if MacorValue is not None: @@ -792,7 +792,7 @@ class FdfParser: self.Profile.PcdFileLineDict[PcdPair] =3D FileLineTuple =20 self.__WipeOffArea.append(((SetLine, SetOffset), (self.Cur= rentLineNumber - 1, self.CurrentOffsetWithinLine - 1))) - elif self.__Token in ('!ifdef', '!ifndef', '!if'): + elif self.__Token in {'!ifdef', '!ifndef', '!if'}: IfStartPos =3D (self.CurrentLineNumber - 1, self.CurrentOf= fsetWithinLine - len(self.__Token)) IfList.append([IfStartPos, None, None]) =20 @@ -810,7 +810,7 @@ class FdfParser: IfList[-1] =3D [IfList[-1][0], ConditionSatisfied, BranchD= etermined] if ConditionSatisfied: self.__WipeOffArea.append((IfList[-1][0], (self.Curren= tLineNumber - 1, self.CurrentOffsetWithinLine - 1))) =20 - elif self.__Token in ('!elseif', '!else'): + elif self.__Token in {'!elseif', '!else'}: ElseStartPos =3D (self.CurrentLineNumber - 1, self.Current= OffsetWithinLine - len(self.__Token)) if len(IfList) <=3D 0: raise Warning("Missing !if statement", self.FileName, = self.CurrentLineNumber) @@ -1001,7 +1001,7 @@ class FdfParser: def __GetExpression(self): Line =3D self.Profile.FileLinesList[self.CurrentLineNumber - 1] Index =3D len(Line) - 1 - while Line[Index] in ['\r', '\n']: + while Line[Index] in {'\r', '\n'}: Index -=3D 1 ExpressionString =3D self.Profile.FileLinesList[self.CurrentLineNu= mber - 1][self.CurrentOffsetWithinLine:Index+1] self.CurrentOffsetWithinLine +=3D len(ExpressionString) @@ -1489,7 +1489,7 @@ class FdfParser: =20 while self.__GetTokenStatements(FdObj): pass - for Attr in ("BaseAddress", "Size", "ErasePolarity"): + for Attr in ["BaseAddress", "Size", "ErasePolarity"]: if getattr(FdObj, Attr) is None: self.__GetNextToken() raise Warning("Keyword %s missing" % Attr, self.FileName, = self.CurrentLineNumber) @@ -1831,7 +1831,7 @@ class FdfParser: if not self.__GetNextWord(): return True =20 - if not self.__Token in ("SET", BINARY_FILE_TYPE_FV, "FILE", "DATA"= , "CAPSULE", "INF"): + if self.__Token not in {"SET", BINARY_FILE_TYPE_FV, "FILE", "DATA"= , "CAPSULE", "INF"}: # # If next token is a word which is not a valid FV type, it mig= ht be part of [PcdOffset[|PcdSize]] # Or it might be next region's offset described by an expressi= on which starts with a PCD. @@ -2134,7 +2134,7 @@ class FdfParser: self.__GetFvExtEntryStatement(FvObj) or self.__GetFvNameSt= ring(FvObj)): break =20 - if FvObj.FvNameString =3D=3D 'TRUE' and not FvObj.FvNameGuid: + if FvObj.FvNameString =3D=3D TAB_TRUE_1 and not FvObj.FvNameGuid: raise Warning("FvNameString found but FvNameGuid was not found= ", self.FileName, self.CurrentLineNumber) =20 self.__GetAprioriSection(FvObj, FvObj.DefineVarDict.copy()) @@ -2168,10 +2168,10 @@ class FdfParser: if not self.__GetNextToken(): raise Warning("expected alignment value", self.FileName, self.= CurrentLineNumber) =20 - if self.__Token.upper() not in ("1", "2", "4", "8", "16", "32", "6= 4", "128", "256", "512", \ + if self.__Token.upper() not in {"1", "2", "4", "8", "16", "32", "6= 4", "128", "256", "512", \ "1K", "2K", "4K", "8K", "16K", "32= K", "64K", "128K", "256K", "512K", \ "1M", "2M", "4M", "8M", "16M", "32= M", "64M", "128M", "256M", "512M", \ - "1G", "2G"): + "1G", "2G"}: raise Warning("Unknown alignment value '%s'" % self.__Token, s= elf.FileName, self.CurrentLineNumber) Obj.FvAlignment =3D self.__Token return True @@ -2221,12 +2221,12 @@ class FdfParser: if not self.__GetNextToken(): raise Warning("expected FvForceRebase value", self.FileName, s= elf.CurrentLineNumber) =20 - if self.__Token.upper() not in ["TRUE", "FALSE", "0", "0X0", "0X00= ", "1", "0X1", "0X01"]: + if self.__Token.upper() not in {TAB_TRUE_1, TAB_FALSE_1, "0", "0X0= ", "0X00", "1", "0X1", "0X01"}: raise Warning("Unknown FvForceRebase value '%s'" % self.__Toke= n, self.FileName, self.CurrentLineNumber) =20 - if self.__Token.upper() in ["TRUE", "1", "0X1", "0X01"]: + if self.__Token.upper() in {TAB_TRUE_1, "1", "0X1", "0X01"}: Obj.FvForceRebase =3D True - elif self.__Token.upper() in ["FALSE", "0", "0X0", "0X00"]: + elif self.__Token.upper() in {TAB_FALSE_1, "0", "0X0", "0X00"}: Obj.FvForceRebase =3D False else: Obj.FvForceRebase =3D None @@ -2247,19 +2247,19 @@ class FdfParser: while self.__GetNextWord(): IsWordToken =3D True name =3D self.__Token - if name not in ("ERASE_POLARITY", "MEMORY_MAPPED", \ + if name not in {"ERASE_POLARITY", "MEMORY_MAPPED", \ "STICKY_WRITE", "LOCK_CAP", "LOCK_STATUS", "WRI= TE_ENABLED_CAP", \ "WRITE_DISABLED_CAP", "WRITE_STATUS", "READ_ENA= BLED_CAP", \ "READ_DISABLED_CAP", "READ_STATUS", "READ_LOCK_= CAP", \ "READ_LOCK_STATUS", "WRITE_LOCK_CAP", "WRITE_LO= CK_STATUS", \ - "WRITE_POLICY_RELIABLE", "WEAK_ALIGNMENT", "FvU= sedSizeEnable"): + "WRITE_POLICY_RELIABLE", "WEAK_ALIGNMENT", "FvU= sedSizeEnable"}: self.__UndoToken() return False =20 if not self.__IsToken( "=3D"): raise Warning("expected '=3D'", self.FileName, self.Curren= tLineNumber) =20 - if not self.__GetNextToken() or self.__Token.upper() not in ("= TRUE", "FALSE", "1", "0"): + if not self.__GetNextToken() or self.__Token.upper() not in {T= AB_TRUE_1, TAB_FALSE_1, "1", "0"}: raise Warning("expected TRUE/FALSE (1/0)", self.FileName, = self.CurrentLineNumber) =20 FvObj.FvAttributeDict[name] =3D self.__Token @@ -2297,7 +2297,7 @@ class FdfParser: if not self.__IsToken( "=3D"): raise Warning("expected '=3D'", self.FileName, self.CurrentLin= eNumber) =20 - if not self.__GetNextToken() or self.__Token not in ('TRUE', 'FALS= E'): + if not self.__GetNextToken() or self.__Token not in TAB_TRUE_FALSE= _SET: raise Warning("expected TRUE or FALSE for FvNameString", self.= FileName, self.CurrentLineNumber) =20 FvObj.FvNameString =3D self.__Token @@ -2614,7 +2614,7 @@ class FdfParser: # @staticmethod def __FileCouldHaveRelocFlag (FileType): - if FileType in (SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, SUP_MODULE_PE= IM, 'PEI_DXE_COMBO'): + if FileType in {SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, SUP_MODULE_PE= IM, 'PEI_DXE_COMBO'}: return True else: return False @@ -2629,7 +2629,7 @@ class FdfParser: # @staticmethod def __SectionCouldHaveRelocFlag (SectionType): - if SectionType in (BINARY_FILE_TYPE_TE, BINARY_FILE_TYPE_PE32): + if SectionType in {BINARY_FILE_TYPE_TE, BINARY_FILE_TYPE_PE32}: return True else: return False @@ -2676,7 +2676,7 @@ class FdfParser: raise Warning("expected FD name", self.FileName, self.Curr= entLineNumber) FfsFileObj.FdName =3D self.__Token =20 - elif self.__Token in ("DEFINE", "APRIORI", "SECTION"): + elif self.__Token in {"DEFINE", "APRIORI", "SECTION"}: self.__UndoToken() self.__GetSectionData( FfsFileObj, MacroDict) =20 @@ -2707,8 +2707,8 @@ class FdfParser: while True: AlignValue =3D None if self.__GetAlignment(): - if self.__Token not in ("Auto", "8", "16", "32", "64", "12= 8", "512", "1K", "4K", "32K" ,"64K", "128K", - "256K", "512K", "1M", "2M", "4M", = "8M", "16M"): + if self.__Token not in {"Auto", "8", "16", "32", "64", "12= 8", "512", "1K", "4K", "32K" ,"64K", "128K", + "256K", "512K", "1M", "2M", "4M", = "8M", "16M"}: raise Warning("Incorrect alignment '%s'" % self.__Toke= n, self.FileName, self.CurrentLineNumber) #For FFS, Auto is default option same to "" if not self.__Token =3D=3D "Auto": @@ -2766,8 +2766,8 @@ class FdfParser: FfsFileObj.CheckSum =3D True =20 if self.__GetAlignment(): - if self.__Token not in ("Auto", "8", "16", "32", "64", "128", = "512", "1K", "4K", "32K" ,"64K", "128K", - "256K", "512K", "1M", "2M", "4M", "8M"= , "16M"): + if self.__Token not in {"Auto", "8", "16", "32", "64", "128", = "512", "1K", "4K", "32K" ,"64K", "128K", + "256K", "512K", "1M", "2M", "4M", "8M"= , "16M"}: raise Warning("Incorrect alignment '%s'" % self.__Token, s= elf.FileName, self.CurrentLineNumber) #For FFS, Auto is default option same to "" if not self.__Token =3D=3D "Auto": @@ -2838,8 +2838,8 @@ class FdfParser: =20 AlignValue =3D None if self.__GetAlignment(): - if self.__Token not in ("Auto", "8", "16", "32", "64", "128", = "512", "1K", "4K", "32K" ,"64K", "128K", - "256K", "512K", "1M", "2M", "4M", "8M"= , "16M"): + if self.__Token not in {"Auto", "8", "16", "32", "64", "128", = "512", "1K", "4K", "32K" ,"64K", "128K", + "256K", "512K", "1M", "2M", "4M", "8M"= , "16M"}: raise Warning("Incorrect alignment '%s'" % self.__Token, s= elf.FileName, self.CurrentLineNumber) AlignValue =3D self.__Token =20 @@ -2953,8 +2953,8 @@ class FdfParser: self.SetFileBufferPos(OldPos) return False =20 - if self.__Token not in ("COMPAT16", BINARY_FILE_TYPE_PE32, BIN= ARY_FILE_TYPE_PIC, BINARY_FILE_TYPE_TE, "FV_IMAGE", "RAW", BINARY_FILE_TYPE= _DXE_DEPEX,\ - BINARY_FILE_TYPE_UI, "VERSION", BINARY_FILE= _TYPE_PEI_DEPEX, "SUBTYPE_GUID", BINARY_FILE_TYPE_SMM_DEPEX): + if self.__Token not in {"COMPAT16", BINARY_FILE_TYPE_PE32, BIN= ARY_FILE_TYPE_PIC, BINARY_FILE_TYPE_TE, "FV_IMAGE", "RAW", BINARY_FILE_TYPE= _DXE_DEPEX,\ + BINARY_FILE_TYPE_UI, "VERSION", BINARY_FILE= _TYPE_PEI_DEPEX, "SUBTYPE_GUID", BINARY_FILE_TYPE_SMM_DEPEX}: raise Warning("Unknown section type '%s'" % self.__Token, = self.FileName, self.CurrentLineNumber) if AlignValue =3D=3D 'Auto'and (not self.__Token =3D=3D BINARY= _FILE_TYPE_PE32) and (not self.__Token =3D=3D BINARY_FILE_TYPE_TE): raise Warning("Auto alignment can only be used in PE32 or = TE section ", self.FileName, self.CurrentLineNumber) @@ -3102,7 +3102,7 @@ class FdfParser: continue except ValueError: raise Warning("expected Number", self.FileName, self.C= urrentLineNumber) - elif self.__Token.upper() not in ("TRUE", "FALSE", "1", "0"): + elif self.__Token.upper() not in {TAB_TRUE_1, TAB_FALSE_1, "1"= , "0"}: raise Warning("expected TRUE/FALSE (1/0)", self.FileName, = self.CurrentLineNumber) AttribDict[AttribKey] =3D self.__Token =20 @@ -3128,8 +3128,8 @@ class FdfParser: =20 AlignValue =3D None if self.__GetAlignment(): - if self.__Token not in ("8", "16", "32", "64", "128", "512", "= 1K", "4K", "32K" ,"64K", "128K", - "256K", "512K", "1M", "2M", "4M", "8M"= , "16M"): + if self.__Token not in {"8", "16", "32", "64", "128", "512", "= 1K", "4K", "32K" ,"64K", "128K", + "256K", "512K", "1M", "2M", "4M", "8M"= , "16M"}: raise Warning("Incorrect alignment '%s'" % self.__Token, s= elf.FileName, self.CurrentLineNumber) AlignValue =3D self.__Token =20 @@ -3292,21 +3292,21 @@ class FdfParser: def __GetCapsuleTokens(self, Obj): if not self.__GetNextToken(): return False - while self.__Token in ("CAPSULE_GUID", "CAPSULE_HEADER_SIZE", "CAP= SULE_FLAGS", "OEM_CAPSULE_FLAGS", "CAPSULE_HEADER_INIT_VERSION"): + while self.__Token in {"CAPSULE_GUID", "CAPSULE_HEADER_SIZE", "CAP= SULE_FLAGS", "OEM_CAPSULE_FLAGS", "CAPSULE_HEADER_INIT_VERSION"}: Name =3D self.__Token.strip() if not self.__IsToken("=3D"): raise Warning("expected '=3D'", self.FileName, self.Curren= tLineNumber) if not self.__GetNextToken(): raise Warning("expected value", self.FileName, self.Curren= tLineNumber) if Name =3D=3D 'CAPSULE_FLAGS': - if not self.__Token in ("PersistAcrossReset", "PopulateSys= temTable", "InitiateReset"): + if self.__Token not in {"PersistAcrossReset", "PopulateSys= temTable", "InitiateReset"}: raise Warning("expected PersistAcrossReset, PopulateSy= stemTable, or InitiateReset", self.FileName, self.CurrentLineNumber) Value =3D self.__Token.strip() while self.__IsToken(","): Value +=3D ',' if not self.__GetNextToken(): raise Warning("expected value", self.FileName, sel= f.CurrentLineNumber) - if not self.__Token in ("PersistAcrossReset", "Populat= eSystemTable", "InitiateReset"): + if self.__Token not in {"PersistAcrossReset", "Populat= eSystemTable", "InitiateReset"}: raise Warning("expected PersistAcrossReset, Popula= teSystemTable, or InitiateReset", self.FileName, self.CurrentLineNumber) Value +=3D self.__Token.strip() elif Name =3D=3D 'OEM_CAPSULE_FLAGS': @@ -3521,7 +3521,7 @@ class FdfParser: AfileName =3D self.__Token AfileBaseName =3D os.path.basename(AfileName) =20 - if os.path.splitext(AfileBaseName)[1] not in [".bin",".BIN",".Bin= ",".dat",".DAT",".Dat",".data",".DATA",".Data"]: + if os.path.splitext(AfileBaseName)[1] not in {".bin",".BIN",".Bin= ",".dat",".DAT",".Dat",".data",".DATA",".Data"}: raise Warning('invalid binary file type, should be one of "bin= ",BINARY_FILE_TYPE_BIN,"Bin","dat","DAT","Dat","data","DATA","Data"', \ self.FileName, self.CurrentLineNumber) =20 @@ -3614,12 +3614,12 @@ class FdfParser: =20 if not self.__GetNextWord(): raise Warning("expected Module type", self.FileName, self.Curr= entLineNumber) - if self.__Token.upper() not in (SUP_MODULE_SEC, SUP_MODULE_PEI_COR= E, SUP_MODULE_PEIM, SUP_MODULE_DXE_CORE, \ + if self.__Token.upper() not in {SUP_MODULE_SEC, SUP_MODULE_PEI_COR= E, SUP_MODULE_PEIM, SUP_MODULE_DXE_CORE, \ SUP_MODULE_DXE_DRIVER, SUP_MODULE_DXE_SAL_DRI= VER, \ SUP_MODULE_DXE_SMM_DRIVER, SUP_MODULE_DXE_RUN= TIME_DRIVER, \ SUP_MODULE_UEFI_DRIVER, SUP_MODULE_UEFI_APPLI= CATION, SUP_MODULE_USER_DEFINED, "DEFAULT", SUP_MODULE_BASE, \ EDK_COMPONENT_TYPE_SECURITY_CORE, EDK_COMPONE= NT_TYPE_COMBINED_PEIM_DRIVER, EDK_COMPONENT_TYPE_PIC_PEIM, EDK_COMPONENT_TY= PE_RELOCATABLE_PEIM, \ - "PE32_PEIM", EDK_COMPONENT_TYPE_BS= _DRIVER, EDK_COMPONENT_TYPE_RT_DRIVER, EDK_COMPONENT_TYPE_SAL_RT_DRIVER, ED= K_COMPONENT_TYPE_APPLICATION, "ACPITABLE", SUP_MODULE_SMM_CORE, SUP_MODULE_= MM_STANDALONE, SUP_MODULE_MM_CORE_STANDALONE): + "PE32_PEIM", EDK_COMPONENT_TYPE_BS= _DRIVER, EDK_COMPONENT_TYPE_RT_DRIVER, EDK_COMPONENT_TYPE_SAL_RT_DRIVER, ED= K_COMPONENT_TYPE_APPLICATION, "ACPITABLE", SUP_MODULE_SMM_CORE, SUP_MODULE_= MM_STANDALONE, SUP_MODULE_MM_CORE_STANDALONE}: raise Warning("Unknown Module type '%s'" % self.__Token, self.= FileName, self.CurrentLineNumber) return self.__Token =20 @@ -3661,8 +3661,8 @@ class FdfParser: raise Warning("expected FFS type", self.FileName, self.Current= LineNumber) =20 Type =3D self.__Token.strip().upper() - if Type not in ("RAW", "FREEFORM", SUP_MODULE_SEC, SUP_MODULE_PEI_= CORE, SUP_MODULE_PEIM,\ - "PEI_DXE_COMBO", "DRIVER", SUP_MODULE_DXE_COR= E, EDK_COMPONENT_TYPE_APPLICATION, "FV_IMAGE", "SMM", SUP_MODULE_SMM_CORE, = SUP_MODULE_MM_STANDALONE, SUP_MODULE_MM_CORE_STANDALONE): + if Type not in {"RAW", "FREEFORM", SUP_MODULE_SEC, SUP_MODULE_PEI_= CORE, SUP_MODULE_PEIM,\ + "PEI_DXE_COMBO", "DRIVER", SUP_MODULE_DXE_COR= E, EDK_COMPONENT_TYPE_APPLICATION, "FV_IMAGE", "SMM", SUP_MODULE_SMM_CORE, = SUP_MODULE_MM_STANDALONE, SUP_MODULE_MM_CORE_STANDALONE}: raise Warning("Unknown FV type '%s'" % self.__Token, self.File= Name, self.CurrentLineNumber) =20 if not self.__IsToken("=3D"): @@ -3718,8 +3718,8 @@ class FdfParser: =20 AlignValue =3D "" if self.__GetAlignment(): - if self.__Token not in ("Auto", "8", "16", "32", "64", "128", = "512", "1K", "4K", "32K" ,"64K", "128K", - "256K", "512K", "1M", "2M", "4M", "8M"= , "16M"): + if self.__Token not in {"Auto", "8", "16", "32", "64", "128", = "512", "1K", "4K", "32K" ,"64K", "128K", + "256K", "512K", "1M", "2M", "4M", "8M"= , "16M"}: raise Warning("Incorrect alignment '%s'" % self.__Token, s= elf.FileName, self.CurrentLineNumber) #For FFS, Auto is default option same to "" if not self.__Token =3D=3D "Auto": @@ -3755,8 +3755,8 @@ class FdfParser: =20 SectionName =3D self.__Token =20 - if SectionName not in ("COMPAT16", BINARY_FILE_TYPE_PE32, BINA= RY_FILE_TYPE_PIC, BINARY_FILE_TYPE_TE, "FV_IMAGE", "RAW", BINARY_FILE_TYPE_= DXE_DEPEX,\ - BINARY_FILE_TYPE_UI, BINARY_FILE_TYPE_= PEI_DEPEX, "VERSION", "SUBTYPE_GUID", BINARY_FILE_TYPE_SMM_DEPEX): + if SectionName not in {"COMPAT16", BINARY_FILE_TYPE_PE32, BINA= RY_FILE_TYPE_PIC, BINARY_FILE_TYPE_TE, "FV_IMAGE", "RAW", BINARY_FILE_TYPE_= DXE_DEPEX,\ + BINARY_FILE_TYPE_UI, BINARY_FILE_TYPE_= PEI_DEPEX, "VERSION", "SUBTYPE_GUID", BINARY_FILE_TYPE_SMM_DEPEX}: raise Warning("Unknown leaf section name '%s'" % SectionNa= me, self.FileName, self.CurrentLineNumber) =20 =20 @@ -3768,8 +3768,8 @@ class FdfParser: =20 SectAlignment =3D "" if self.__GetAlignment(): - if self.__Token not in ("Auto", "8", "16", "32", "64", "12= 8", "512", "1K", "4K", "32K" ,"64K", "128K", - "256K", "512K", "1M", "2M", "4M", = "8M", "16M"): + if self.__Token not in {"Auto", "8", "16", "32", "64", "12= 8", "512", "1K", "4K", "32K" ,"64K", "128K", + "256K", "512K", "1M", "2M", "4M", = "8M", "16M"}: raise Warning("Incorrect alignment '%s'" % self.__Toke= n, self.FileName, self.CurrentLineNumber) if self.__Token =3D=3D 'Auto' and (not SectionName =3D=3D = BINARY_FILE_TYPE_PE32) and (not SectionName =3D=3D BINARY_FILE_TYPE_TE): raise Warning("Auto alignment can only be used in PE32= or TE section ", self.FileName, self.CurrentLineNumber) @@ -3812,8 +3812,8 @@ class FdfParser: return False SectionName =3D self.__Token =20 - if SectionName not in ("COMPAT16", BINARY_FILE_TYPE_PE32, BINARY_F= ILE_TYPE_PIC, BINARY_FILE_TYPE_TE, "FV_IMAGE", "RAW", BINARY_FILE_TYPE_DXE_= DEPEX,\ - BINARY_FILE_TYPE_UI, "VERSION", BINARY_FILE= _TYPE_PEI_DEPEX, BINARY_FILE_TYPE_GUID, BINARY_FILE_TYPE_SMM_DEPEX): + if SectionName not in {"COMPAT16", BINARY_FILE_TYPE_PE32, BINARY_F= ILE_TYPE_PIC, BINARY_FILE_TYPE_TE, "FV_IMAGE", "RAW", BINARY_FILE_TYPE_DXE_= DEPEX,\ + BINARY_FILE_TYPE_UI, "VERSION", BINARY_FILE= _TYPE_PEI_DEPEX, BINARY_FILE_TYPE_GUID, BINARY_FILE_TYPE_SMM_DEPEX}: self.__UndoToken() return False =20 @@ -3848,16 +3848,16 @@ class FdfParser: FvImageSectionObj.FvFileType =3D self.__Token =20 if self.__GetAlignment(): - if self.__Token not in ("8", "16", "32", "64", "128", = "512", "1K", "4K", "32K" ,"64K", "128K", - "256K", "512K", "1M", "2M", "4= M", "8M", "16M"): + if self.__Token not in {"8", "16", "32", "64", "128", = "512", "1K", "4K", "32K" ,"64K", "128K", + "256K", "512K", "1M", "2M", "4= M", "8M", "16M"}: raise Warning("Incorrect alignment '%s'" % self.__= Token, self.FileName, self.CurrentLineNumber) FvImageSectionObj.Alignment =3D self.__Token =20 if self.__IsToken('|'): FvImageSectionObj.FvFileExtension =3D self.__GetFileEx= tension() elif self.__GetNextToken(): - if self.__Token not in ("}", "COMPAT16", BINARY_FILE_T= YPE_PE32, BINARY_FILE_TYPE_PIC, BINARY_FILE_TYPE_TE, "FV_IMAGE", "RAW", BIN= ARY_FILE_TYPE_DXE_DEPEX,\ - BINARY_FILE_TYPE_UI, "VERSION", BINARY_FILE= _TYPE_PEI_DEPEX, BINARY_FILE_TYPE_GUID, BINARY_FILE_TYPE_SMM_DEPEX): + if self.__Token not in {"}", "COMPAT16", BINARY_FILE_T= YPE_PE32, BINARY_FILE_TYPE_PIC, BINARY_FILE_TYPE_TE, "FV_IMAGE", "RAW", BIN= ARY_FILE_TYPE_DXE_DEPEX,\ + BINARY_FILE_TYPE_UI, "VERSION", BINARY_FILE= _TYPE_PEI_DEPEX, BINARY_FILE_TYPE_GUID, BINARY_FILE_TYPE_SMM_DEPEX}: FvImageSectionObj.FvFileName =3D self.__Token else: self.__UndoToken() @@ -3916,8 +3916,8 @@ class FdfParser: EfiSectionObj.BuildNum =3D self.__Token =20 if self.__GetAlignment(): - if self.__Token not in ("Auto", "8", "16", "32", "64", "128", = "512", "1K", "4K", "32K" ,"64K", "128K", - "256K", "512K", "1M", "2M", "4M", "8M"= , "16M"): + if self.__Token not in {"Auto", "8", "16", "32", "64", "128", = "512", "1K", "4K", "32K" ,"64K", "128K", + "256K", "512K", "1M", "2M", "4M", "8M"= , "16M"}: raise Warning("Incorrect alignment '%s'" % self.__Token, s= elf.FileName, self.CurrentLineNumber) if self.__Token =3D=3D 'Auto' and (not SectionName =3D=3D BINA= RY_FILE_TYPE_PE32) and (not SectionName =3D=3D BINARY_FILE_TYPE_TE): raise Warning("Auto alignment can only be used in PE32 or = TE section ", self.FileName, self.CurrentLineNumber) @@ -3938,8 +3938,8 @@ class FdfParser: if self.__IsToken('|'): EfiSectionObj.FileExtension =3D self.__GetFileExtension() elif self.__GetNextToken(): - if self.__Token not in ("}", "COMPAT16", BINARY_FILE_TYPE_PE32= , BINARY_FILE_TYPE_PIC, BINARY_FILE_TYPE_TE, "FV_IMAGE", "RAW", BINARY_FILE= _TYPE_DXE_DEPEX,\ - BINARY_FILE_TYPE_UI, "VERSION", BINARY_FILE_TYPE_PE= I_DEPEX, BINARY_FILE_TYPE_GUID, BINARY_FILE_TYPE_SMM_DEPEX): + if self.__Token not in {"}", "COMPAT16", BINARY_FILE_TYPE_PE32= , BINARY_FILE_TYPE_PIC, BINARY_FILE_TYPE_TE, "FV_IMAGE", "RAW", BINARY_FILE= _TYPE_DXE_DEPEX,\ + BINARY_FILE_TYPE_UI, "VERSION", BINARY_FILE_TYPE_PE= I_DEPEX, BINARY_FILE_TYPE_GUID, BINARY_FILE_TYPE_SMM_DEPEX}: =20 if self.__Token.startswith('PCD'): self.__UndoToken() @@ -3973,7 +3973,7 @@ class FdfParser: # @staticmethod def __RuleSectionCouldBeOptional(SectionType): - if SectionType in (BINARY_FILE_TYPE_DXE_DEPEX, BINARY_FILE_TYPE_UI= , "VERSION", BINARY_FILE_TYPE_PEI_DEPEX, "RAW", BINARY_FILE_TYPE_SMM_DEPEX): + if SectionType in {BINARY_FILE_TYPE_DXE_DEPEX, BINARY_FILE_TYPE_UI= , "VERSION", BINARY_FILE_TYPE_PEI_DEPEX, "RAW", BINARY_FILE_TYPE_SMM_DEPEX}: return True else: return False @@ -3988,7 +3988,7 @@ class FdfParser: # @staticmethod def __RuleSectionCouldHaveBuildNum(SectionType): - if SectionType in ("VERSION"): + if SectionType =3D=3D "VERSION": return True else: return False @@ -4003,7 +4003,7 @@ class FdfParser: # @staticmethod def __RuleSectionCouldHaveString(SectionType): - if SectionType in (BINARY_FILE_TYPE_UI, "VERSION"): + if SectionType in {BINARY_FILE_TYPE_UI, "VERSION"}: return True else: return False @@ -4018,34 +4018,34 @@ class FdfParser: # def __CheckRuleSectionFileType(self, SectionType, FileType): if SectionType =3D=3D "COMPAT16": - if FileType not in ("COMPAT16", "SEC_COMPAT16"): + if FileType not in {"COMPAT16", "SEC_COMPAT16"}: raise Warning("Incorrect section file type '%s'" % FileTyp= e, self.FileName, self.CurrentLineNumber) elif SectionType =3D=3D BINARY_FILE_TYPE_PE32: - if FileType not in (BINARY_FILE_TYPE_PE32, "SEC_PE32"): + if FileType not in {BINARY_FILE_TYPE_PE32, "SEC_PE32"}: raise Warning("Incorrect section file type '%s'" % FileTyp= e, self.FileName, self.CurrentLineNumber) elif SectionType =3D=3D BINARY_FILE_TYPE_PIC: - if FileType not in (BINARY_FILE_TYPE_PIC, BINARY_FILE_TYPE_PIC= ): + if FileType not in {BINARY_FILE_TYPE_PIC, BINARY_FILE_TYPE_PIC= }: raise Warning("Incorrect section file type '%s'" % FileTyp= e, self.FileName, self.CurrentLineNumber) elif SectionType =3D=3D BINARY_FILE_TYPE_TE: - if FileType not in (BINARY_FILE_TYPE_TE, "SEC_TE"): + if FileType not in {BINARY_FILE_TYPE_TE, "SEC_TE"}: raise Warning("Incorrect section file type '%s'" % FileTyp= e, self.FileName, self.CurrentLineNumber) elif SectionType =3D=3D "RAW": - if FileType not in (BINARY_FILE_TYPE_BIN, "SEC_BIN", "RAW", "A= SL", "ACPI"): + if FileType not in {BINARY_FILE_TYPE_BIN, "SEC_BIN", "RAW", "A= SL", "ACPI"}: raise Warning("Incorrect section file type '%s'" % FileTyp= e, self.FileName, self.CurrentLineNumber) elif SectionType =3D=3D BINARY_FILE_TYPE_DXE_DEPEX or SectionType = =3D=3D BINARY_FILE_TYPE_SMM_DEPEX: - if FileType not in (BINARY_FILE_TYPE_DXE_DEPEX, "SEC_DXE_DEPEX= ", BINARY_FILE_TYPE_SMM_DEPEX): + if FileType not in {BINARY_FILE_TYPE_DXE_DEPEX, "SEC_DXE_DEPEX= ", BINARY_FILE_TYPE_SMM_DEPEX}: raise Warning("Incorrect section file type '%s'" % FileTyp= e, self.FileName, self.CurrentLineNumber) elif SectionType =3D=3D BINARY_FILE_TYPE_UI: - if FileType not in (BINARY_FILE_TYPE_UI, "SEC_UI"): + if FileType not in {BINARY_FILE_TYPE_UI, "SEC_UI"}: raise Warning("Incorrect section file type '%s'" % FileTyp= e, self.FileName, self.CurrentLineNumber) elif SectionType =3D=3D "VERSION": - if FileType not in ("VERSION", "SEC_VERSION"): + if FileType not in {"VERSION", "SEC_VERSION"}: raise Warning("Incorrect section file type '%s'" % FileTyp= e, self.FileName, self.CurrentLineNumber) elif SectionType =3D=3D BINARY_FILE_TYPE_PEI_DEPEX: - if FileType not in (BINARY_FILE_TYPE_PEI_DEPEX, "SEC_PEI_DEPEX= "): + if FileType not in {BINARY_FILE_TYPE_PEI_DEPEX, "SEC_PEI_DEPEX= "}: raise Warning("Incorrect section file type '%s'" % FileTyp= e, self.FileName, self.CurrentLineNumber) elif SectionType =3D=3D BINARY_FILE_TYPE_GUID: - if FileType not in (BINARY_FILE_TYPE_PE32, "SEC_GUID"): + if FileType not in {BINARY_FILE_TYPE_PE32, "SEC_GUID"}: raise Warning("Incorrect section file type '%s'" % FileTyp= e, self.FileName, self.CurrentLineNumber) =20 ## __GetRuleEncapsulationSection() method @@ -4147,7 +4147,7 @@ class FdfParser: raise Warning("expected '.'", self.FileName, self.CurrentLineN= umber) =20 Arch =3D self.__SkippedChars.rstrip(".").upper() - if Arch not in ("IA32", "X64", "IPF", "ARM", "AARCH64"): + if Arch not in {"IA32", "X64", "IPF", "ARM", "AARCH64"}: raise Warning("Unknown Arch '%s'" % Arch, self.FileName, self.= CurrentLineNumber) =20 if not self.__GetNextWord(): @@ -4161,7 +4161,7 @@ class FdfParser: if self.__IsToken(","): if not self.__GetNextWord(): raise Warning("expected Arch list", self.FileName, self.Cu= rrentLineNumber) - if self.__Token.upper() not in ("IA32", "X64", "IPF", "ARM", "= AARCH64"): + if self.__Token.upper() not in {"IA32", "X64", "IPF", "ARM", "= AARCH64"}: raise Warning("Unknown Arch '%s'" % self.__Token, self.Fil= eName, self.CurrentLineNumber) VtfObj.ArchList =3D self.__Token.upper() =20 @@ -4224,7 +4224,7 @@ class FdfParser: if not self.__GetNextWord(): raise Warning("Expected Region Name", self.FileName, s= elf.CurrentLineNumber) =20 - if self.__Token not in ("F", "N", "S"): #, "H", "L", "P= H", "PL"): not support + if self.__Token not in {"F", "N", "S"}: #, "H", "L", "P= H", "PL"): not support raise Warning("Unknown location type '%s'" % self.__To= ken, self.FileName, self.CurrentLineNumber) =20 CompStatementObj.FilePos =3D self.__Token @@ -4240,7 +4240,7 @@ class FdfParser: =20 if not self.__GetNextToken(): raise Warning("expected Component type", self.FileName, self.C= urrentLineNumber) - if self.__Token not in ("FIT", "PAL_B", "PAL_A", "OEM"): + if self.__Token not in {"FIT", "PAL_B", "PAL_A", "OEM"}: if not self.__Token.startswith("0x") or len(self.__Token) < 3 = or len(self.__Token) > 4 or \ not self.__Token[2] in string.hexdigits or not self.__Toke= n[-1] in string.hexdigits: raise Warning("Unknown location type '%s'" % self.__Token,= self.FileName, self.CurrentLineNumber) @@ -4268,7 +4268,7 @@ class FdfParser: =20 if not self.__GetNextToken(): raise Warning("expected Component CS", self.FileName, self.Cur= rentLineNumber) - if self.__Token not in ("1", "0"): + if self.__Token not in {"1", "0"}: raise Warning("Unknown Component CS '%s'" % self.__Token, sel= f.FileName, self.CurrentLineNumber) CompStatementObj.CompCs =3D self.__Token =20 @@ -4456,7 +4456,7 @@ class FdfParser: raise Warning("expected '=3D'", self.FileName, sel= f.CurrentLineNumber) if not self.__GetNextToken(): raise Warning("expected TRUE/FALSE for compress", = self.FileName, self.CurrentLineNumber) - Overrides.NeedCompress =3D self.__Token.upper() =3D=3D= 'TRUE' + Overrides.NeedCompress =3D self.__Token.upper() =3D=3D= TAB_TRUE_1 continue =20 if self.__IsToken( "}"): diff --git a/BaseTools/Source/Python/GenFds/FfsInfStatement.py b/BaseTools/= Source/Python/GenFds/FfsInfStatement.py index e4276c3a8c07..f62ee73b1238 100644 --- a/BaseTools/Source/Python/GenFds/FfsInfStatement.py +++ b/BaseTools/Source/Python/GenFds/FfsInfStatement.py @@ -748,7 +748,7 @@ class FfsInfStatement(FfsInfStatementClassObject): if SectionType =3D=3D BINARY_FILE_TYPE_SMM_DEPEX: EdkLogger.error("GenFds", FORMAT_NOT_SUPPORTED, "Framework= SMM module doesn't support SMM_DEPEX section type", File=3Dself.InfFileNam= e) NoStrip =3D True - if self.ModuleType in (SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, SUP_MO= DULE_PEIM): + if self.ModuleType in {SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, SUP_MO= DULE_PEIM}: if self.KeepReloc is not None: NoStrip =3D self.KeepReloc elif Rule.KeepReloc is not None: @@ -902,7 +902,7 @@ class FfsInfStatement(FfsInfStatementClassObject): # @retval string File name of the generated section file # def __GenComplexFileSection__(self, Rule, FvChildAddr, FvParentAddr, I= sMakefile =3D False): - if self.ModuleType in (SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, SUP_MO= DULE_PEIM): + if self.ModuleType in {SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, SUP_MO= DULE_PEIM}: if Rule.KeepReloc is not None: self.KeepRelocFromRule =3D Rule.KeepReloc SectFiles =3D [] diff --git a/BaseTools/Source/Python/GenFds/Fv.py b/BaseTools/Source/Python= /GenFds/Fv.py index c672f1d7d8fa..6c90fa3ca9e6 100644 --- a/BaseTools/Source/Python/GenFds/Fv.py +++ b/BaseTools/Source/Python/GenFds/Fv.py @@ -297,7 +297,7 @@ class FV (FvClassObject): if self.FvAttributeDict: for FvAttribute in self.FvAttributeDict.keys() : if FvAttribute =3D=3D "FvUsedSizeEnable": - if self.FvAttributeDict[FvAttribute].upper() in {'TRUE= ', '1'}: + if self.FvAttributeDict[FvAttribute].upper() in {TAB_T= RUE_1, '1'}: self.UsedSizeEnable =3D True continue self.FvInfFile.writelines("EFI_{FA} =3D {VAL}{END}".format= (FA=3DFvAttribute, VAL=3Dself.FvAttributeDict[FvAttribute], END=3DTAB_LINE_= BREAK)) @@ -323,7 +323,7 @@ class FV (FvClassObject): # } EFI_FIRMWARE_VOLUME_EXT_ENTRY_USED_SIZE_TYPE; Buffer +=3D pack('HHL', 8, 3, 0) =20 - if self.FvNameString =3D=3D 'TRUE': + if self.FvNameString =3D=3D TAB_TRUE_1: # # Create EXT entry for FV UI name # This GUID is used: A67DF1FA-8DE8-4E98-AF09-4BDF2EFFBC7C diff --git a/BaseTools/Source/Python/GenFds/GenFds.py b/BaseTools/Source/Py= thon/GenFds/GenFds.py index 998bd5345c3c..b9167bac7eda 100644 --- a/BaseTools/Source/Python/GenFds/GenFds.py +++ b/BaseTools/Source/Python/GenFds/GenFds.py @@ -212,7 +212,7 @@ def main(): else: GlobalData.gCommandLineDefines[List[0].strip()] = =3D List[1].strip() else: - GlobalData.gCommandLineDefines[List[0].strip()] =3D "T= RUE" + GlobalData.gCommandLineDefines[List[0].strip()] =3D TA= B_TRUE_1 os.environ["WORKSPACE"] =3D Workspace =20 # Use the -t and -b option as gGlobalDefines's TOOLCHAIN and TARGE= T if they are not defined @@ -432,7 +432,7 @@ def FindExtendTool(KeyStringList, CurrentArchList, Name= Guid): List =3D Key.split('_') if List[Index] =3D=3D '*': for String in ToolDb[ToolList[Index]]: - if String in [Arch, GenFdsGlobalVariable.Targe= tName, GenFdsGlobalVariable.ToolChainTag]: + if String in {Arch, GenFdsGlobalVariable.Targe= tName, GenFdsGlobalVariable.ToolChainTag}: List[Index] =3D String NewKey =3D '%s_%s_%s_%s_%s' % tuple(List) if NewKey not in BuildOption: diff --git a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py b/BaseT= ools/Source/Python/GenFds/GenFdsGlobalVariable.py index b840079e7ad4..e7dd212b649e 100644 --- a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py +++ b/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py @@ -212,12 +212,12 @@ class GenFdsGlobalVariable: =20 if not Inf.IsBinaryModule: for File in Inf.Sources: - if File.TagName in ("", "*", GenFdsGlobalVariable.ToolChai= nTag) and \ - File.ToolChainFamily in ("", "*", GenFdsGlobalVariable= .ToolChainFamily): + if File.TagName in {"", "*", GenFdsGlobalVariable.ToolChai= nTag} and \ + File.ToolChainFamily in {"", "*", GenFdsGlobalVariable= .ToolChainFamily}: FileList.append((File, DataType.TAB_UNKNOWN_FILE)) =20 for File in Inf.Binaries: - if File.Target in [DataType.TAB_COMMON, '*', GenFdsGlobalVaria= ble.TargetName]: + if File.Target in {DataType.TAB_COMMON, '*', GenFdsGlobalVaria= ble.TargetName}: FileList.append((File, File.Type)) =20 for File, FileType in FileList: @@ -494,9 +494,9 @@ class GenFdsGlobalVariable: def GetAlignment (AlignString): if AlignString is None: return 0 - if AlignString in ("1K", "2K", "4K", "8K", "16K", "32K", "64K", "1= 28K", "256K", "512K"): + if AlignString in {"1K", "2K", "4K", "8K", "16K", "32K", "64K", "1= 28K", "256K", "512K"}: return int (AlignString.rstrip('K')) * 1024 - elif AlignString in ("1M", "2M", "4M", "8M", "16M"): + elif AlignString in {"1M", "2M", "4M", "8M", "16M"}: return int (AlignString.rstrip('M')) * 1024 * 1024 else: return int (AlignString) @@ -551,9 +551,9 @@ class GenFdsGlobalVariable: Cmd +=3D ["-r", BaseAddress] =20 if ForceRebase =3D=3D False: - Cmd +=3D ["-F", "FALSE"] + Cmd +=3D ["-F", DataType.TAB_FALSE_1] elif ForceRebase =3D=3D True: - Cmd +=3D ["-F", "TRUE"] + Cmd +=3D ["-F", DataType.TAB_TRUE_1] =20 if Capsule: Cmd +=3D ["-c"] @@ -686,7 +686,7 @@ class GenFdsGlobalVariable: =20 def CallExternalTool (cmd, errorMess, returnValue=3D[]): =20 - if type(cmd) not in (tuple, list): + if type(cmd) not in {tuple, list}: GenFdsGlobalVariable.ErrorLogger("ToolError! Invalid paramete= r type in call to CallExternalTool") =20 if GenFdsGlobalVariable.DebugLevel !=3D -1: diff --git a/BaseTools/Source/Python/GenFds/GuidSection.py b/BaseTools/Sour= ce/Python/GenFds/GuidSection.py index 28571292f5a6..b36d2868059a 100644 --- a/BaseTools/Source/Python/GenFds/GuidSection.py +++ b/BaseTools/Source/Python/GenFds/GuidSection.py @@ -77,7 +77,7 @@ class GuidSection(GuidSectionClassObject) : else: FvAddrIsSet =3D False =20 - if self.ProcessRequired in ("TRUE", "1"): + if self.ProcessRequired in {TAB_TRUE_1, "1"}: if self.FvAddr !=3D []: #no use FvAddr when the image is processed. self.FvAddr =3D [] @@ -175,7 +175,7 @@ class GuidSection(GuidSectionClassObject) : if ExternalOption is not None: CmdOption =3D CmdOption + ' ' + ExternalOption if not GenFdsGlobalVariable.EnableGenfdsMultiThread: - if self.ProcessRequired not in ("TRUE", "1") and self.Incl= udeFvSection and not FvAddrIsSet and self.FvParentAddr is not None: + if self.ProcessRequired not in {TAB_TRUE_1, "1"} and self.= IncludeFvSection and not FvAddrIsSet and self.FvParentAddr is not None: #FirstCall is only set for the encapsulated flash FV i= mage without process required attribute. FirstCall =3D True # @@ -232,11 +232,11 @@ class GuidSection(GuidSectionClassObject) : # # Call Gensection Add Section Header # - if self.ProcessRequired in ("TRUE", "1"): + if self.ProcessRequired in {TAB_TRUE_1, "1"}: if 'PROCESSING_REQUIRED' not in Attribute: Attribute.append('PROCESSING_REQUIRED') =20 - if self.AuthStatusValid in ("TRUE", "1"): + if self.AuthStatusValid in {TAB_TRUE_1, "1"}: Attribute.append('AUTH_STATUS_VALID') GenFdsGlobalVariable.GenerateSection(OutputFile, [TempFile= ], Section.SectionType['GUIDED'], Guid=3Dself.NameGuid,= GuidAttr=3DAttribute, GuidHdrLen=3DHeaderLength) @@ -248,14 +248,14 @@ class GuidSection(GuidSectionClassObject) : HeaderLength =3D None if self.ExtraHeaderSize !=3D -1: HeaderLength =3D str(self.ExtraHeaderSize) - if self.AuthStatusValid in ("TRUE", "1"): + if self.AuthStatusValid in {TAB_TRUE_1, "1"}: Attribute.append('AUTH_STATUS_VALID') if self.ProcessRequired =3D=3D "NONE" and HeaderLength is = None: GenFdsGlobalVariable.GenerateSection(OutputFile, [Temp= File], Section.SectionType['GUIDED'], Guid=3Dself.NameG= uid, GuidAttr=3DAttribute, GuidHdrLen=3DHead= erLength, DummyFile=3DDummyFile, IsMakefile=3DIsMakefile) else: - if self.ProcessRequired in ("TRUE", "1"): + if self.ProcessRequired in {TAB_TRUE_1, "1"}: if 'PROCESSING_REQUIRED' not in Attribute: Attribute.append('PROCESSING_REQUIRED') GenFdsGlobalVariable.GenerateSection(OutputFile, [Temp= File], Section.SectionType['GUIDED'], @@ -268,7 +268,7 @@ class GuidSection(GuidSectionClassObject) : # reset guided section alignment to none for the processed= required guided data self.Alignment =3D None self.IncludeFvSection =3D False - self.ProcessRequired =3D "TRUE" + self.ProcessRequired =3D TAB_TRUE_1 if IsMakefile and self.Alignment is not None and self.Alignmen= t.strip() =3D=3D '0': self.Alignment =3D '1' return OutputFileList, self.Alignment diff --git a/BaseTools/Source/Python/GenFds/OptRomInfStatement.py b/BaseToo= ls/Source/Python/GenFds/OptRomInfStatement.py index 93c4456eb89f..a20c28314894 100644 --- a/BaseTools/Source/Python/GenFds/OptRomInfStatement.py +++ b/BaseTools/Source/Python/GenFds/OptRomInfStatement.py @@ -52,10 +52,10 @@ class OptRomInfStatement (FfsInfStatement): if self.OverrideAttribs.NeedCompress is None: self.OverrideAttribs.NeedCompress =3D self.OptRomDefs.get ('PC= I_COMPRESS') if self.OverrideAttribs.NeedCompress is not None: - if self.OverrideAttribs.NeedCompress.upper() not in ('TRUE= ', 'FALSE'): + if self.OverrideAttribs.NeedCompress.upper() not in TAB_TR= UE_FALSE_SET: GenFdsGlobalVariable.ErrorLogger( "Expected TRUE/FALSE= for PCI_COMPRESS: %s" %self.InfFileName) self.OverrideAttribs.NeedCompress =3D \ - self.OverrideAttribs.NeedCompress.upper() =3D=3D 'TRUE' + self.OverrideAttribs.NeedCompress.upper() =3D=3D TAB_T= RUE_1 =20 if self.OverrideAttribs.PciVendorId is None: self.OverrideAttribs.PciVendorId =3D self.OptRomDefs.get ('PCI= _VENDOR_ID') diff --git a/BaseTools/Source/Python/GenFds/Region.py b/BaseTools/Source/Py= thon/GenFds/Region.py index e67d056cc178..57d5d15c36a5 100644 --- a/BaseTools/Source/Python/GenFds/Region.py +++ b/BaseTools/Source/Python/GenFds/Region.py @@ -220,7 +220,7 @@ class Region(RegionClassObject): # self.PadBuffer(Buffer, ErasePolarity, Size) =20 - if self.RegionType in ('FILE', 'INF'): + if self.RegionType in {'FILE', 'INF'}: for RegionData in self.RegionDataList: if self.RegionType =3D=3D 'INF': RegionData.__InfParse__(None) diff --git a/BaseTools/Source/Python/PatchPcdValue/PatchPcdValue.py b/BaseT= ools/Source/Python/PatchPcdValue/PatchPcdValue.py index 76fef41176ac..6c85ff4dd073 100644 --- a/BaseTools/Source/Python/PatchPcdValue/PatchPcdValue.py +++ b/BaseTools/Source/Python/PatchPcdValue/PatchPcdValue.py @@ -59,18 +59,8 @@ def PatchBinaryFile(FileName, ValueOffset, TypeName, Val= ueString, MaxSize=3D0): # # Get PCD value data length # - ValueLength =3D 0 - if TypeName =3D=3D 'BOOLEAN': - ValueLength =3D 1 - elif TypeName =3D=3D TAB_UINT8: - ValueLength =3D 1 - elif TypeName =3D=3D TAB_UINT16: - ValueLength =3D 2 - elif TypeName =3D=3D TAB_UINT32: - ValueLength =3D 4 - elif TypeName =3D=3D TAB_UINT64: - ValueLength =3D 8 - elif TypeName =3D=3D TAB_VOID: + ValueLength =3D MAX_SIZE_TYPE.get(TypeName,0) + if TypeName =3D=3D TAB_VOID: if MaxSize =3D=3D 0: return OPTION_MISSING, "PcdMaxSize is not specified for VOID* = type PCD." ValueLength =3D int(MaxSize) @@ -100,14 +90,14 @@ def PatchBinaryFile(FileName, ValueOffset, TypeName, V= alueString, MaxSize=3D0): SavedStr =3D ValueString ValueString =3D ValueString.upper() ValueNumber =3D 0 - if TypeName =3D=3D 'BOOLEAN': + if TypeName =3D=3D TAB_BOOLEAN: # # Get PCD value for BOOLEAN data type # try: - if ValueString =3D=3D 'TRUE': + if ValueString =3D=3D TAB_TRUE_1: ValueNumber =3D 1 - elif ValueString =3D=3D 'FALSE': + elif ValueString =3D=3D TAB_FALSE_1: ValueNumber =3D 0 ValueNumber =3D int (ValueString, 0) if ValueNumber !=3D 0: diff --git a/BaseTools/Source/Python/Trim/Trim.py b/BaseTools/Source/Python= /Trim/Trim.py index a92df52979c6..b65c7bead814 100644 --- a/BaseTools/Source/Python/Trim/Trim.py +++ b/BaseTools/Source/Python/Trim/Trim.py @@ -300,7 +300,7 @@ def TrimPreprocessedVfr(Source, Target): FoundTypedef =3D False TypedefEnd =3D Index # keep all "typedef struct" except to GUID, EFI_PLABEL and PAL= _CALL_RETURN - if Line.strip("} ;\r\n") in [TAB_GUID, "EFI_PLABEL", "PAL_CALL= _RETURN"]: + if Line.strip("} ;\r\n") in {TAB_GUID, "EFI_PLABEL", "PAL_CALL= _RETURN"}: for i in range(TypedefStart, TypedefEnd+1): Lines[i] =3D "\n" =20 @@ -357,7 +357,7 @@ def DoInclude(Source, Indent=3D'', IncludePathList=3D[]= , LocalSearchPath=3DNone): Result =3D gAslIncludePattern.findall(Line) if len(Result) =3D=3D 0: Result =3D gAslCIncludePattern.findall(Line) - if len(Result) =3D=3D 0 or os.path.splitext(Result[0][1])[1].l= ower() not in [".asl", ".asi"]: + if len(Result) =3D=3D 0 or os.path.splitext(Result[0][1])[1].l= ower() not in {".asl", ".asi"}: NewFileContent.append("%s%s" % (Indent, Line)) continue # @@ -499,7 +499,8 @@ def TrimEdkSources(Source, Target): =20 for FileName in Files: Dummy, Ext =3D os.path.splitext(FileName) - if Ext.upper() not in ['.C', '.H']: continue + if Ext.upper() not in {'.C', '.H'}: + continue if Target is None or Target =3D=3D '': TrimEdkSourceCode( os.path.join(CurrentDir, FileName), diff --git a/BaseTools/Source/Python/Workspace/DecBuildData.py b/BaseTools/= Source/Python/Workspace/DecBuildData.py index 1fbd095f743c..cb6e431b09be 100644 --- a/BaseTools/Source/Python/Workspace/DecBuildData.py +++ b/BaseTools/Source/Python/Workspace/DecBuildData.py @@ -453,7 +453,7 @@ class DecBuildData(PackageBuildClassObject): Pcds[pcd.TokenCName, pcd.TokenSpaceGuidCName, self._PCD_TYPE_S= TRING_[Type]] =3D pcd StructPattern =3D re.compile(r'[_a-zA-Z][0-9A-Za-z_]*$') for pcd in Pcds.values(): - if pcd.DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TA= B_UINT64, TAB_VOID, "BOOLEAN"]: + if pcd.DatumType not in TAB_PCD_NUMERIC_TYPES_VOID: if StructPattern.match(pcd.DatumType) is None: EdkLogger.error('build', FORMAT_INVALID, "DatumType on= ly support BOOLEAN, UINT8, UINT16, UINT32, UINT64, VOID* or a valid struct = name.", pcd.DefinitionPosition[0],pcd.DefinitionPosition[1]) for struct_pcd in Pcds.values(): diff --git a/BaseTools/Source/Python/Workspace/DscBuildData.py b/BaseTools/= Source/Python/Workspace/DscBuildData.py index 7b062b564da5..7944f7cf4d23 100644 --- a/BaseTools/Source/Python/Workspace/DscBuildData.py +++ b/BaseTools/Source/Python/Workspace/DscBuildData.py @@ -483,16 +483,16 @@ class DscBuildData(PlatformBuildClassObject): return self._BuildTargets =20 def _GetPcdInfoFlag(self): - if self._PcdInfoFlag is None or self._PcdInfoFlag.upper() =3D=3D '= FALSE': + if self._PcdInfoFlag is None or self._PcdInfoFlag.upper() =3D=3D T= AB_FALSE_1: return False - elif self._PcdInfoFlag.upper() =3D=3D 'TRUE': + elif self._PcdInfoFlag.upper() =3D=3D TAB_TRUE_1: return True else: return False def _GetVarCheckFlag(self): - if self._VarCheckFlag is None or self._VarCheckFlag.upper() =3D=3D= 'FALSE': + if self._VarCheckFlag is None or self._VarCheckFlag.upper() =3D=3D= TAB_FALSE_1: return False - elif self._VarCheckFlag.upper() =3D=3D 'TRUE': + elif self._VarCheckFlag.upper() =3D=3D TAB_TRUE_1: return True else: return False @@ -810,7 +810,7 @@ class DscBuildData(PlatformBuildClassObject): EdkLogger.error('build', ErrorCode, File=3Dself.MetaFi= le, Line=3DLineNo, ExtraData=3DErrorInfo) =20 - if ModuleType !=3D TAB_COMMON and ModuleType not in SUP_MO= DULE_LIST: + if ModuleType !=3D TAB_COMMON and ModuleType not in SUP_MO= DULE_SET: EdkLogger.error('build', OPTION_UNKNOWN, "Unknown modu= le type [%s]" % ModuleType, File=3Dself.MetaFile, ExtraData=3DLibr= aryInstance, Line=3DLineNo) LibraryClassDict[Arch, ModuleType, LibraryClass] =3D Libra= ryInstance @@ -821,7 +821,7 @@ class DscBuildData(PlatformBuildClassObject): self._LibraryClasses =3D tdict(True) for LibraryClass in LibraryClassSet: # try all possible module types - for ModuleType in SUP_MODULE_LIST: + for ModuleType in SUP_MODULE_SET: LibraryInstance =3D LibraryClassDict[self._Arch, Modul= eType, LibraryClass] if LibraryInstance is None: continue @@ -873,7 +873,7 @@ class DscBuildData(PlatformBuildClassObject): File=3Dself.MetaFile, Line=3DLineNo) ValueList, IsValid, Index =3D AnalyzeDscPcd(Setting, PcdType, self= ._DecPcds[PcdCName, TokenSpaceGuid].DatumType) if not IsValid: - if PcdType not in [MODEL_PCD_FEATURE_FLAG, MODEL_PCD_FIXED_AT_= BUILD]: + if PcdType not in {MODEL_PCD_FEATURE_FLAG, MODEL_PCD_FIXED_AT_= BUILD}: EdkLogger.error('build', FORMAT_INVALID, "Pcd format incor= rect.", File=3Dself.MetaFile, Line=3DLineNo, ExtraData=3D"%s.%s|%s" % (TokenSpaceGuid, = PcdCName, Setting)) else: @@ -907,7 +907,7 @@ class DscBuildData(PlatformBuildClassObject): if not Valid: EdkLogger.error('build', FORMAT_INVALID, ErrStr, File=3Dse= lf.MetaFile, Line=3DLineNo, ExtraData=3D"%s.%s" % (TokenSpaceGuid, Pcd= CName)) - if PcdType in (MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX= _DEFAULT): + if PcdType in {MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX= _DEFAULT}: if self._DecPcds[PcdCName, TokenSpaceGuid].DatumType.strip= () !=3D ValueList[1].strip(): EdkLogger.error('build', FORMAT_INVALID, "Pcd datumtyp= e used in DSC file is not the same as its declaration in DEC file." , File= =3Dself.MetaFile, Line=3DLineNo, ExtraData=3D"%s.%s|%s" % (TokenSpaceGuid, = PcdCName, Setting)) @@ -933,7 +933,7 @@ class DscBuildData(PlatformBuildClassObject): Pcds[pcdname].SkuOverrideValues =3D {skuid:pcd.SkuOver= rideValues[skuid] for skuid in pcd.SkuOverrideValues if skuid in available_= sku} return Pcds def CompleteHiiPcdsDefaultStores(self,Pcds): - HiiPcd =3D [Pcds[pcd] for pcd in Pcds if Pcds[pcd].Type in [self._= PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_D= YNAMIC_EX_HII]]] + HiiPcd =3D [Pcds[pcd] for pcd in Pcds if Pcds[pcd].Type in {self._= PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_D= YNAMIC_EX_HII]}] DefaultStoreMgr =3D DefaultStore(self.DefaultStores) for pcd in HiiPcd: for skuid in pcd.SkuInfoList: @@ -946,10 +946,10 @@ class DscBuildData(PlatformBuildClassObject): =20 def RecoverCommandLinePcd(self): def UpdateCommandLineValue(pcd): - if pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUIL= D], - self._PCD_TYPE_STRING_[MODEL_PCD_P= ATCHABLE_IN_MODULE]]: + if pcd.Type in {self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUIL= D], + self._PCD_TYPE_STRING_[MODEL_PCD_P= ATCHABLE_IN_MODULE]}: pcd.PcdValueFromComm =3D pcd.DefaultValue - elif pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII= ], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]: + elif pcd.Type in {self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII= ], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]}: pcd.PcdValueFromComm =3D pcd.SkuInfoList.get(TAB_DEFAULT).= HiiDefaultValue else: pcd.PcdValueFromComm =3D pcd.SkuInfoList.get(TAB_DEFAULT).= DefaultValue @@ -1083,9 +1083,9 @@ class DscBuildData(PlatformBuildClassObject): EdkLogger.error('Parser', FORMAT_INVALID, 'PCD [%s.%s] Val= ue "%s", %s' % (TokenSpaceGuidCName, TokenCName, PcdValue= , Value)) else: - if PcdValue.upper() =3D=3D 'FALSE': + if PcdValue.upper() =3D=3D TAB_FALSE_1: PcdValue =3D str(0) - if PcdValue.upper() =3D=3D 'TRUE': + if PcdValue.upper() =3D=3D TAB_TRUE_1: PcdValue =3D str(1) if not FieldName: if PcdDatumType not in TAB_PCD_NUMERIC_TYPES: @@ -1142,7 +1142,7 @@ class DscBuildData(PlatformBuildClassObject): # # Retrieve build option for EDKII and EDK style module # - for CodeBase in (EDKII_NAME, EDK_NAME): + for CodeBase in {EDKII_NAME, EDK_NAME}: RecordList =3D self._RawData[MODEL_META_DATA_BUILD_OPTION,= self._Arch, CodeBase] for ToolChainFamily, ToolChain, Option, Dummy1, Dummy2, Du= mmy3, Dummy4,Dummy5 in RecordList: if Dummy3.upper() !=3D TAB_COMMON: @@ -1237,7 +1237,7 @@ class DscBuildData(PlatformBuildClassObject): SkuInfo.HiiDefaultValue =3D NoFiledValues[(Pcd= .TokenSpaceGuidCName,Pcd.TokenCName)][0] for defaultstore in SkuInfo.DefaultStoreDict: SkuInfo.DefaultStoreDict[defaultstore] =3D= NoFiledValues[(Pcd.TokenSpaceGuidCName,Pcd.TokenCName)][0] - if Pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAM= IC_EX_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII]]: + if Pcd.Type in {self._PCD_TYPE_STRING_[MODEL_PCD_DYNAM= IC_EX_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII]}: if Pcd.DatumType =3D=3D TAB_VOID: if not Pcd.MaxDatumSize: Pcd.MaxDatumSize =3D '0' @@ -1249,9 +1249,9 @@ class DscBuildData(PlatformBuildClassObject): PcdInDec =3D self.DecPcds.get((Name,Guid)) if PcdInDec: PcdInDec.PcdValueFromComm =3D NoFiledValues[(Guid,Name= )][0] - if PcdInDec.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_= FIXED_AT_BUILD], + if PcdInDec.Type in {self._PCD_TYPE_STRING_[MODEL_PCD_= FIXED_AT_BUILD], self._PCD_TYPE_STRING_[MODEL_PCD_P= ATCHABLE_IN_MODULE], - self._PCD_TYPE_STRING_[MODEL_PCD_F= EATURE_FLAG]]: + self._PCD_TYPE_STRING_[MODEL_PCD_F= EATURE_FLAG]}: self.Pcds[Name, Guid] =3D copy.deepcopy(PcdInDec) self.Pcds[Name, Guid].DefaultValue =3D NoFiledValu= es[( Guid,Name)][0] return AllPcds @@ -1302,7 +1302,7 @@ class DscBuildData(PlatformBuildClassObject): str_pcd_obj_str.copy(str_pcd_dec) if str_pcd_obj: str_pcd_obj_str.copy(str_pcd_obj) - if str_pcd_obj.Type in [self._PCD_TYPE_STRING_[MODEL_P= CD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]: + if str_pcd_obj.Type in {self._PCD_TYPE_STRING_[MODEL_P= CD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]}: str_pcd_obj_str.DefaultFromDSC =3D {skuname:{defau= ltstore: str_pcd_obj.SkuInfoList[skuname].DefaultStoreDict.get(defaultstore= , str_pcd_obj.SkuInfoList[skuname].HiiDefaultValue) for defaultstore in Def= aultStores} for skuname in str_pcd_obj.SkuInfoList} else: str_pcd_obj_str.DefaultFromDSC =3D {skuname:{defau= ltstore: str_pcd_obj.SkuInfoList[skuname].DefaultStoreDict.get(defaultstore= , str_pcd_obj.SkuInfoList[skuname].DefaultValue) for defaultstore in Defaul= tStores} for skuname in str_pcd_obj.SkuInfoList} @@ -1323,7 +1323,7 @@ class DscBuildData(PlatformBuildClassObject): str_pcd_obj =3D Pcds.get(Pcd, None) if str_pcd_obj: str_pcd_obj_str.copy(str_pcd_obj) - if str_pcd_obj.Type in [self._PCD_TYPE_STRING_[MOD= EL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]: + if str_pcd_obj.Type in {self._PCD_TYPE_STRING_[MOD= EL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]}: str_pcd_obj_str.DefaultFromDSC =3D {skuname:{d= efaultstore: str_pcd_obj.SkuInfoList[skuname].DefaultStoreDict.get(defaults= tore, str_pcd_obj.SkuInfoList[skuname].HiiDefaultValue) for defaultstore in= DefaultStores} for skuname in str_pcd_obj.SkuInfoList} else: str_pcd_obj_str.DefaultFromDSC =3D {skuname:{d= efaultstore: str_pcd_obj.SkuInfoList[skuname].DefaultStoreDict.get(defaults= tore, str_pcd_obj.SkuInfoList[skuname].DefaultValue) for defaultstore in De= faultStores} for skuname in str_pcd_obj.SkuInfoList} @@ -1345,7 +1345,7 @@ class DscBuildData(PlatformBuildClassObject): stru_pcd.SkuOverrideValues[skuid] =3D copy.deepcopy(st= ru_pcd.SkuOverrideValues[nextskuid]) if not NoDefault else copy.deepcopy({d= efaultstorename: stru_pcd.DefaultValues for defaultstorename in DefaultStor= es} if DefaultStores else {TAB_DEFAULT_STORES_DEFAULT:stru_pcd.DefaultValue= s}) if not NoDefault: stru_pcd.ValueChain.add(skuid,'') - if stru_pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_= HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]: + if stru_pcd.Type in {self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_= HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]}: for skuid in SkuIds: nextskuid =3D skuid NoDefault =3D False @@ -1372,16 +1372,16 @@ class DscBuildData(PlatformBuildClassObject): if str_pcd_obj is None: print PcdName, PcdGuid raise - if str_pcd_obj.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_D= YNAMIC_HII], - self._PCD_TYPE_STRING_[MODEL_PCD_D= YNAMIC_EX_HII]]: + if str_pcd_obj.Type in {self._PCD_TYPE_STRING_[MODEL_PCD_D= YNAMIC_HII], + self._PCD_TYPE_STRING_[MODEL_PCD_D= YNAMIC_EX_HII]}: if skuname not in str_pcd_obj.SkuInfoList: str_pcd_obj.SkuInfoList[skuname] =3D SkuInfoClass(= SkuIdName=3Dskuname, SkuId=3Dself.SkuIds[skuname][0], HiiDefaultValue=3DPcd= Value, DefaultStore =3D {StoreName:PcdValue}) else: str_pcd_obj.SkuInfoList[skuname].HiiDefaultValue = =3D PcdValue str_pcd_obj.SkuInfoList[skuname].DefaultStoreDict.= update({StoreName:PcdValue}) - elif str_pcd_obj.Type in [self._PCD_TYPE_STRING_[MODEL_PCD= _FIXED_AT_BUILD], - self._PCD_TYPE_STRING_[MODEL_PCD_P= ATCHABLE_IN_MODULE]]: - if skuname in (self.SkuIdMgr.SystemSkuId, TAB_DEFAULT,= TAB_COMMON): + elif str_pcd_obj.Type in {self._PCD_TYPE_STRING_[MODEL_PCD= _FIXED_AT_BUILD], + self._PCD_TYPE_STRING_[MODEL_PCD_P= ATCHABLE_IN_MODULE]}: + if skuname in {self.SkuIdMgr.SystemSkuId, TAB_DEFAULT,= TAB_COMMON}: str_pcd_obj.DefaultValue =3D PcdValue else: if skuname not in str_pcd_obj.SkuInfoList: @@ -1398,8 +1398,8 @@ class DscBuildData(PlatformBuildClassObject): else: str_pcd_obj.SkuInfoList[skuname].DefaultValue =3D = PcdValue for str_pcd_obj in S_pcd_set.values(): - if str_pcd_obj.Type not in [self._PCD_TYPE_STRING_[MODEL_P= CD_DYNAMIC_HII], - self._PCD_TYPE_STRING_[MODEL_PCD_D= YNAMIC_EX_HII]]: + if str_pcd_obj.Type not in {self._PCD_TYPE_STRING_[MODEL_P= CD_DYNAMIC_HII], + self._PCD_TYPE_STRING_[MODEL_PCD_D= YNAMIC_EX_HII]}: continue PcdDefaultStoreSet =3D set(defaultstorename for skuobj in = str_pcd_obj.SkuInfoList.values() for defaultstorename in skuobj.DefaultStor= eDict) DefaultStoreObj =3D DefaultStore(self._GetDefaultStores()) @@ -1447,7 +1447,7 @@ class DscBuildData(PlatformBuildClassObject): if SkuName not in AvailableSkuIdSet: EdkLogger.error('build ', PARAMETER_INVALID, 'Sku %s is no= t defined in [SkuIds] section' % SkuName, File=3Dself.MetaFile, Line=3DD= ummy5) - if SkuName in (self.SkuIdMgr.SystemSkuId, TAB_DEFAULT, TAB_COM= MON): + if SkuName in {self.SkuIdMgr.SystemSkuId, TAB_DEFAULT, TAB_COM= MON}: if "." not in TokenSpaceGuid: PcdSet.add((PcdCName, TokenSpaceGuid, SkuName, Dummy5)) PcdDict[Arch, PcdCName, TokenSpaceGuid, SkuName] =3D Setti= ng @@ -1491,7 +1491,7 @@ class DscBuildData(PlatformBuildClassObject): =20 def GetStructurePcdMaxSize(self, str_pcd): pcd_default_value =3D str_pcd.DefaultValue - sku_values =3D [skuobj.HiiDefaultValue if str_pcd.Type in [self._P= CD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DY= NAMIC_EX_HII]] else skuobj.DefaultValue for skuobj in str_pcd.SkuInfoList.v= alues()] + sku_values =3D [skuobj.HiiDefaultValue if str_pcd.Type in {self._P= CD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DY= NAMIC_EX_HII]} else skuobj.DefaultValue for skuobj in str_pcd.SkuInfoList.v= alues()] sku_values.append(pcd_default_value) =20 def get_length(value): @@ -1891,8 +1891,8 @@ class DscBuildData(PlatformBuildClassObject): # Assign field values in PCD # CApp =3D CApp + DscBuildData.GenerateDefaultValueAssignStateme= nt(Pcd) - if Pcd.Type not in [self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_= BUILD], - self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODU= LE]]: + if Pcd.Type not in {self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_= BUILD], + self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODU= LE]}: for skuname in self.SkuIdMgr.GetSkuChain(SkuName): storeset =3D [DefaultStoreName] if DefaultStoreName = =3D=3D TAB_DEFAULT_STORES_DEFAULT else [TAB_DEFAULT_STORES_DEFAULT, Default= StoreName] for defaultstorenameitem in storeset: @@ -1940,8 +1940,8 @@ class DscBuildData(PlatformBuildClassObject): CApp =3D CApp + self.GenerateSizeFunction(Pcd) CApp =3D CApp + self.GenerateDefaultValueAssignFunction(Pcd) CApp =3D CApp + self.GenerateCommandLineValue(Pcd) - if not Pcd.SkuOverrideValues or Pcd.Type in [self._PCD_TYPE_ST= RING_[MODEL_PCD_FIXED_AT_BUILD], - self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODU= LE]]: + if not Pcd.SkuOverrideValues or Pcd.Type in {self._PCD_TYPE_ST= RING_[MODEL_PCD_FIXED_AT_BUILD], + self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODU= LE]}: CApp =3D CApp + self.GenerateInitValueFunction(Pcd,self.Sk= uIdMgr.SystemSkuId, TAB_DEFAULT_STORES_DEFAULT) else: for SkuName in self.SkuIdMgr.SkuOverrideOrder(): @@ -1949,8 +1949,8 @@ class DscBuildData(PlatformBuildClassObject): continue for DefaultStoreName in Pcd.SkuOverrideValues[SkuName]: CApp =3D CApp + self.GenerateInitValueFunction(Pcd= ,SkuName,DefaultStoreName) - if not Pcd.SkuOverrideValues or Pcd.Type in [self._PCD_TYPE_ST= RING_[MODEL_PCD_FIXED_AT_BUILD], - self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODU= LE]]: + if not Pcd.SkuOverrideValues or Pcd.Type in {self._PCD_TYPE_ST= RING_[MODEL_PCD_FIXED_AT_BUILD], + self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODU= LE]}: InitByteValue, CApp =3D self.GenerateInitializeFunc(self.S= kuIdMgr.SystemSkuId, TAB_DEFAULT_STORES_DEFAULT, Pcd, InitByteValue, CApp) else: for SkuName in self.SkuIdMgr.SkuOverrideOrder(): @@ -1966,7 +1966,7 @@ class DscBuildData(PlatformBuildClassObject): CApp =3D CApp + ' )\n' CApp =3D CApp + '{\n' for Pcd in StructuredPcds.values(): - if not Pcd.SkuOverrideValues or Pcd.Type in [self._PCD_TYPE_ST= RING_[MODEL_PCD_FIXED_AT_BUILD],self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_= IN_MODULE]]: + if not Pcd.SkuOverrideValues or Pcd.Type in {self._PCD_TYPE_ST= RING_[MODEL_PCD_FIXED_AT_BUILD],self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_= IN_MODULE]}: CApp =3D CApp + ' Initialize_%s_%s_%s_%s();\n' % (self.Sk= uIdMgr.SystemSkuId, TAB_DEFAULT_STORES_DEFAULT, Pcd.TokenSpaceGuidCName, Pc= d.TokenCName) else: for SkuName in self.SkuIdMgr.SkuOverrideOrder(): @@ -2288,13 +2288,13 @@ class DscBuildData(PlatformBuildClassObject): def CopyDscRawValue(self,Pcd): if Pcd.DscRawValue is None: Pcd.DscRawValue =3D dict() - if Pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUILD], = self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODULE]]: + if Pcd.Type in {self._PCD_TYPE_STRING_[MODEL_PCD_FIXED_AT_BUILD], = self._PCD_TYPE_STRING_[MODEL_PCD_PATCHABLE_IN_MODULE]}: if self.SkuIdMgr.SystemSkuId not in Pcd.DscRawValue: Pcd.DscRawValue[self.SkuIdMgr.SystemSkuId] =3D {} Pcd.DscRawValue[self.SkuIdMgr.SystemSkuId][TAB_DEFAULT_STORES_= DEFAULT] =3D Pcd.DefaultValue for skuname in Pcd.SkuInfoList: Pcd.DscRawValue[skuname] =3D {} - if Pcd.Type in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII],= self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]: + if Pcd.Type in {self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII],= self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]}: for defaultstore in Pcd.SkuInfoList[skuname].DefaultStoreD= ict: Pcd.DscRawValue[skuname][defaultstore] =3D Pcd.SkuInfo= List[skuname].DefaultStoreDict[defaultstore] else: @@ -2307,16 +2307,16 @@ class DscBuildData(PlatformBuildClassObject): for PcdCName, TokenSpaceGuid in PcdSet: PcdObj =3D PcdSet[(PcdCName, TokenSpaceGuid)] self.CopyDscRawValue(PcdObj) - if PcdObj.Type not in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMI= C_DEFAULT], + if PcdObj.Type not in {self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMI= C_DEFAULT], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_VPD], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_DEFAUL= T], self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII], - self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_VPD]]: + self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_VPD]}: Pcds[PcdCName, TokenSpaceGuid]=3D PcdObj continue PcdType =3D PcdObj.Type - if PcdType in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], = self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]: + if PcdType in {self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], = self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]}: for skuid in PcdObj.SkuInfoList: skuobj =3D PcdObj.SkuInfoList[skuid] mindefaultstorename =3D DefaultStoreObj.GetMin(set(def= aultstorename for defaultstorename in skuobj.DefaultStoreDict)) @@ -2332,7 +2332,7 @@ class DscBuildData(PlatformBuildClassObject): PcdObj.SkuInfoList[skuname] =3D copy.deepcopy(PcdObj.S= kuInfoList[nextskuid]) PcdObj.SkuInfoList[skuname].SkuId =3D skuid PcdObj.SkuInfoList[skuname].SkuIdName =3D skuname - if PcdType in [self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], = self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]]: + if PcdType in {self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_HII], = self._PCD_TYPE_STRING_[MODEL_PCD_DYNAMIC_EX_HII]}: PcdObj.DefaultValue =3D PcdObj.SkuInfoList.values()[0].Hii= DefaultValue if self.SkuIdMgr.SkuUsageType =3D=3D self.SkuIdMgr.SINGLE else= PcdObj.SkuInfoList[TAB_DEFAULT].HiiDefaultValue Pcds[PcdCName, TokenSpaceGuid]=3D PcdObj return Pcds diff --git a/BaseTools/Source/Python/Workspace/InfBuildData.py b/BaseTools/= Source/Python/Workspace/InfBuildData.py index 3d9391039f4f..ef91df6e612e 100644 --- a/BaseTools/Source/Python/Workspace/InfBuildData.py +++ b/BaseTools/Source/Python/Workspace/InfBuildData.py @@ -230,8 +230,8 @@ class InfBuildData(ModuleBuildClassObject): self._Defs[Name] =3D Value self._Macros[Name] =3D Value # some special items in [Defines] section need special treatme= nt - elif Name in ('EFI_SPECIFICATION_VERSION', 'UEFI_SPECIFICATION= _VERSION', 'EDK_RELEASE_VERSION', 'PI_SPECIFICATION_VERSION'): - if Name in ('EFI_SPECIFICATION_VERSION', 'UEFI_SPECIFICATI= ON_VERSION'): + elif Name in {'EFI_SPECIFICATION_VERSION', 'UEFI_SPECIFICATION= _VERSION', 'EDK_RELEASE_VERSION', 'PI_SPECIFICATION_VERSION'}: + if Name in {'EFI_SPECIFICATION_VERSION', 'UEFI_SPECIFICATI= ON_VERSION'}: Name =3D 'UEFI_SPECIFICATION_VERSION' if self._Specification is None: self._Specification =3D OrderedDict() @@ -248,8 +248,8 @@ class InfBuildData(ModuleBuildClassObject): if len(ValueList) > 1: SupModuleList =3D GetSplitValueList(ValueList[1], ' ') else: - SupModuleList =3D SUP_MODULE_LIST - self._LibraryClass.append(LibraryClassObject(LibraryClass,= SupModuleList)) + SupModuleList =3D SUP_MODULE_SET + self._LibraryClass.append(LibraryClassObject(LibraryClass,= list(SupModuleList))) elif Name =3D=3D 'ENTRY_POINT': if self._ModuleEntryPointList is None: self._ModuleEntryPointList =3D [] @@ -280,7 +280,7 @@ class InfBuildData(ModuleBuildClassObject): self._CustomMakefile['MSFT'] =3D TokenList[0] self._CustomMakefile['GCC'] =3D TokenList[0] else: - if TokenList[0] not in ['MSFT', 'GCC']: + if TokenList[0] not in {'MSFT', 'GCC'}: EdkLogger.error("build", FORMAT_NOT_SUPPORTED, "No supported family [%s]" % Token= List[0], File=3Dself.MetaFile, Line=3DRecor= d[-1]) @@ -296,7 +296,7 @@ class InfBuildData(ModuleBuildClassObject): if not self._ModuleType: EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "MODULE_TYPE is not given", File=3Dself.Me= taFile) - if self._ModuleType not in SUP_MODULE_LIST: + if self._ModuleType not in SUP_MODULE_SET: RecordList =3D self._RawData[MODEL_META_DATA_HEADER, self.= _Arch, self._Platform] for Record in RecordList: Name =3D Record[1] @@ -304,7 +304,7 @@ class InfBuildData(ModuleBuildClassObject): LineNo =3D Record[6] break EdkLogger.error("build", FORMAT_NOT_SUPPORTED, - "MODULE_TYPE %s is not supported for EDK I= I, valid values are:\n %s" % (self._ModuleType, ' '.join(l for l in SUP_MOD= ULE_LIST)), + "MODULE_TYPE %s is not supported for EDK I= I, valid values are:\n %s" % (self._ModuleType, ' '.join(l for l in SUP_MOD= ULE_SET)), File=3Dself.MetaFile, Line=3DLineNo) if (self._Specification is None) or (not 'PI_SPECIFICATION_VER= SION' in self._Specification) or (int(self._Specification['PI_SPECIFICATION= _VERSION'], 16) < 0x0001000A): if self._ModuleType =3D=3D SUP_MODULE_SMM_CORE: @@ -318,11 +318,11 @@ class InfBuildData(ModuleBuildClassObject): and 'PCI_CLASS_CODE' in self._Defs and 'PCI_REVISION' in se= lf._Defs: self._BuildType =3D 'UEFI_OPTIONROM' if 'PCI_COMPRESS' in self._Defs: - if self._Defs['PCI_COMPRESS'] not in ('TRUE', 'FALSE'): + if self._Defs['PCI_COMPRESS'] not in TAB_TRUE_FALSE_SE= T: EdkLogger.error("build", FORMAT_INVALID, "Expected= TRUE/FALSE for PCI_COMPRESS: %s" % self.MetaFile) =20 elif 'UEFI_HII_RESOURCE_SECTION' in self._Defs \ - and self._Defs['UEFI_HII_RESOURCE_SECTION'] =3D=3D 'TRUE': + and self._Defs['UEFI_HII_RESOURCE_SECTION'] =3D=3D TAB_TRUE= _1: self._BuildType =3D 'UEFI_HII' else: self._BuildType =3D self._ModuleType.upper() @@ -345,7 +345,7 @@ class InfBuildData(ModuleBuildClassObject): if self._ComponentType in COMPONENT_TO_MODULE_MAP_DICT: self._ModuleType =3D COMPONENT_TO_MODULE_MAP_DICT[self._Co= mponentType] if self._ComponentType =3D=3D EDK_COMPONENT_TYPE_LIBRARY: - self._LibraryClass =3D [LibraryClassObject(self._BaseName,= SUP_MODULE_LIST)] + self._LibraryClass =3D [LibraryClassObject(self._BaseName,= list(SUP_MODULE_SET))] # make use some [nmake] section macros Macros =3D self._Macros Macros["EDK_SOURCE"] =3D GlobalData.gEcpSource @@ -442,7 +442,7 @@ class InfBuildData(ModuleBuildClassObject): self._GetHeaderInfo() if self._ModuleType is None: self._ModuleType =3D SUP_MODULE_BASE - if self._ModuleType not in SUP_MODULE_LIST: + if self._ModuleType not in SUP_MODULE_SET: self._ModuleType =3D SUP_MODULE_USER_DEFINED return self._ModuleType =20 @@ -496,7 +496,7 @@ class InfBuildData(ModuleBuildClassObject): if self._Shadow is None: if self._Header_ is None: self._GetHeaderInfo() - if self._Shadow is not None and self._Shadow.upper() =3D=3D 'T= RUE': + if self._Shadow is not None and self._Shadow.upper() =3D=3D TA= B_TRUE_1: self._Shadow =3D True else: self._Shadow =3D False @@ -886,7 +886,7 @@ class InfBuildData(ModuleBuildClassObject): =20 if len(RecordList) !=3D 0 and self.ModuleType =3D=3D SUP_MODUL= E_USER_DEFINED: for Record in RecordList: - if Record[4] not in [SUP_MODULE_PEIM, SUP_MODULE_DXE_D= RIVER, SUP_MODULE_DXE_SMM_DRIVER]: + if Record[4] not in {SUP_MODULE_PEIM, SUP_MODULE_DXE_D= RIVER, SUP_MODULE_DXE_SMM_DRIVER}: EdkLogger.error('build', FORMAT_INVALID, "'%s' module must specify the type= of [Depex] section" % self.ModuleType, File=3Dself.MetaFile) diff --git a/BaseTools/Source/Python/Workspace/MetaFileCommentParser.py b/B= aseTools/Source/Python/Workspace/MetaFileCommentParser.py index df1e90faf5a0..8650a51933d6 100644 --- a/BaseTools/Source/Python/Workspace/MetaFileCommentParser.py +++ b/BaseTools/Source/Python/Workspace/MetaFileCommentParser.py @@ -33,9 +33,9 @@ ErrorMsgMap =3D { } =20 def CheckInfComment(SectionType, Comments, InfFile, LineNo, ValueList): - if SectionType in [MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_DYNAMIC_EX= , MODEL_PCD_DYNAMIC]: + if SectionType in {MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_DYNAMIC_EX= , MODEL_PCD_DYNAMIC}: CheckUsage(Comments, UsageList, InfFile, LineNo, ValueList[0]+'.'+= ValueList[1], ErrorMsgMap[MODEL_PCD_DYNAMIC]) - elif SectionType in [MODEL_EFI_GUID, MODEL_EFI_PPI]: + elif SectionType in {MODEL_EFI_GUID, MODEL_EFI_PPI}: CheckUsage(Comments, UsageList, InfFile, LineNo, ValueList[0], Err= orMsgMap[SectionType]) elif SectionType =3D=3D MODEL_EFI_PROTOCOL: CheckUsage(Comments, UsageList + ("TO_START", "BY_START"), InfFile= , LineNo, ValueList[0], ErrorMsgMap[SectionType]) diff --git a/BaseTools/Source/Python/Workspace/MetaFileParser.py b/BaseTool= s/Source/Python/Workspace/MetaFileParser.py index 2c116ddbcb71..50a74bc415ef 100644 --- a/BaseTools/Source/Python/Workspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Workspace/MetaFileParser.py @@ -584,7 +584,7 @@ class InfParser(MetaFileParser): self._SectionHeaderParser() # Check invalid sections if self._Version < 0x00010005: - if self._SectionType in [MODEL_META_DATA_BUILD_OPTION, + if self._SectionType in {MODEL_META_DATA_BUILD_OPTION, MODEL_EFI_LIBRARY_CLASS, MODEL_META_DATA_PACKAGE, MODEL_PCD_FIXED_AT_BUILD, @@ -595,13 +595,13 @@ class InfParser(MetaFileParser): MODEL_EFI_GUID, MODEL_EFI_PROTOCOL, MODEL_EFI_PPI, - MODEL_META_DATA_USER_EXTENSIO= N]: + MODEL_META_DATA_USER_EXTENSIO= N}: EdkLogger.error('Parser', FORMAT_INVALID, "Section [%s] is not allowed in in= f file without version" % (self._SectionName), ExtraData=3Dself._CurrentLine, Fil= e=3Dself.MetaFile, Line=3Dself._LineIndex + 1) - elif self._SectionType in [MODEL_EFI_INCLUDE, + elif self._SectionType in {MODEL_EFI_INCLUDE, MODEL_EFI_LIBRARY_INSTANCE, - MODEL_META_DATA_NMAKE]: + MODEL_META_DATA_NMAKE}: EdkLogger.error('Parser', FORMAT_INVALID, "Section [%s] is not allowed in inf fi= le with version 0x%08x" % (self._SectionName, self._Version), ExtraData=3Dself._CurrentLine, File=3D= self.MetaFile, Line=3Dself._LineIndex + 1) @@ -764,9 +764,9 @@ class InfParser(MetaFileParser): # if value are 'True', 'true', 'TRUE' or 'False', 'false', 'FALSE'= , replace with integer 1 or 0. if self._ValueList[2] !=3D '': InfPcdValueList =3D GetSplitValueList(TokenList[1], TAB_VALUE_= SPLIT, 1) - if InfPcdValueList[0] in ['True', 'true', 'TRUE']: + if InfPcdValueList[0] in TAB_TRUE_SET: self._ValueList[2] =3D TokenList[1].replace(InfPcdValueLis= t[0], '1', 1); - elif InfPcdValueList[0] in ['False', 'false', 'FALSE']: + elif InfPcdValueList[0] in TAB_FALSE_SET: self._ValueList[2] =3D TokenList[1].replace(InfPcdValueLis= t[0], '0', 1); if (self._ValueList[0], self._ValueList[1]) not in self.PcdsDict: self.PcdsDict[self._ValueList[0], self._ValueList[1]] =3D self= ._SectionType @@ -1017,13 +1017,13 @@ class DscParser(MetaFileParser): EdkLogger.error("Parser", FORMAT_INVALID, "Unknown directive [= %s]" % DirectiveName, File=3Dself.MetaFile, Line=3Dself._LineIndex += 1) =20 - if DirectiveName in ['!IF', '!IFDEF', '!IFNDEF']: + if DirectiveName in {'!IF', '!IFDEF', '!IFNDEF'}: self._InDirective +=3D 1 =20 - if DirectiveName in ['!ENDIF']: + if DirectiveName =3D=3D '!ENDIF': self._InDirective -=3D 1 =20 - if DirectiveName in ['!IF', '!IFDEF', '!INCLUDE', '!IFNDEF', '!ELS= EIF'] and self._ValueList[1] =3D=3D '': + if DirectiveName in {'!IF', '!IFDEF', '!INCLUDE', '!IFNDEF', '!ELS= EIF'} and self._ValueList[1] =3D=3D '': EdkLogger.error("Parser", FORMAT_INVALID, "Missing expression", File=3Dself.MetaFile, Line=3Dself._LineIndex += 1, ExtraData=3Dself._CurrentLine) @@ -1037,9 +1037,9 @@ class DscParser(MetaFileParser): while self._DirectiveStack: # Remove any !else or !elseif DirectiveInfo =3D self._DirectiveStack.pop() - if DirectiveInfo[0] in [MODEL_META_DATA_CONDITIONAL_STATEM= ENT_IF, + if DirectiveInfo[0] in {MODEL_META_DATA_CONDITIONAL_STATEM= ENT_IF, MODEL_META_DATA_CONDITIONAL_STATEM= ENT_IFDEF, - MODEL_META_DATA_CONDITIONAL_STATEM= ENT_IFNDEF]: + MODEL_META_DATA_CONDITIONAL_STATEM= ENT_IFNDEF}: break else: EdkLogger.error("Parser", FORMAT_INVALID, "Redundant '!end= if'", @@ -1104,7 +1104,7 @@ class DscParser(MetaFileParser): @ParseMacro def _SkuIdParser(self): TokenList =3D GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT) - if len(TokenList) not in (2,3): + if len(TokenList) not in {2,3}: EdkLogger.error('Parser', FORMAT_INVALID, "Correct format is '= |[|]'", ExtraData=3Dself._CurrentLine, File=3Dself.Met= aFile, Line=3Dself._LineIndex + 1) self._ValueList[0:len(TokenList)] =3D TokenList @@ -1156,7 +1156,7 @@ class DscParser(MetaFileParser): # # The PCD values are optional for FIXEDATBUILD, PATCHABLEINMOD= ULE, Dynamic/DynamicEx default # - if self._SectionType in (MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_P= ATCHABLE_IN_MODULE, MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX_DEFAULT= ): + if self._SectionType in {MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_P= ATCHABLE_IN_MODULE, MODEL_PCD_DYNAMIC_DEFAULT, MODEL_PCD_DYNAMIC_EX_DEFAULT= }: return EdkLogger.error('Parser', FORMAT_INVALID, "No PCD value given", ExtraData=3Dself._CurrentLine + " (.|)", @@ -1164,13 +1164,13 @@ class DscParser(MetaFileParser): =20 # Validate the datum type of Dynamic Defaul PCD and DynamicEx Defa= ult PCD ValueList =3D GetSplitValueList(self._ValueList[2]) - if len(ValueList) > 1 and ValueList[1] in [TAB_UINT8 , TAB_UINT16,= TAB_UINT32 , TAB_UINT64] \ - and self._ItemType in [MODEL_PCD_DYNAMIC_DEF= AULT, MODEL_PCD_DYNAMIC_EX_DEFAULT]: + if len(ValueList) > 1 and ValueList[1] in {TAB_UINT8 , TAB_UINT16,= TAB_UINT32 , TAB_UINT64} \ + and self._ItemType in {MODEL_PCD_DYNAMIC_DEF= AULT, MODEL_PCD_DYNAMIC_EX_DEFAULT}: EdkLogger.error('Parser', FORMAT_INVALID, "The datum type '%s'= of PCD is wrong" % ValueList[1], ExtraData=3Dself._CurrentLine, File=3Dself.Met= aFile, Line=3Dself._LineIndex + 1) =20 # Validate the VariableName of DynamicHii and DynamicExHii for PCD= Entry must not be an empty string - if self._ItemType in [MODEL_PCD_DYNAMIC_HII, MODEL_PCD_DYNAMIC_EX_= HII]: + if self._ItemType in {MODEL_PCD_DYNAMIC_HII, MODEL_PCD_DYNAMIC_EX_= HII}: DscPcdValueList =3D GetSplitValueList(TokenList[1], TAB_VALUE_= SPLIT, 1) if len(DscPcdValueList[0].replace('L','').replace('"','').stri= p()) =3D=3D 0: EdkLogger.error('Parser', FORMAT_INVALID, "The VariableNam= e field in the HII format PCD entry must not be an empty string", @@ -1178,9 +1178,9 @@ class DscParser(MetaFileParser): =20 # if value are 'True', 'true', 'TRUE' or 'False', 'false', 'FALSE'= , replace with integer 1 or 0. DscPcdValueList =3D GetSplitValueList(TokenList[1], TAB_VALUE_SPLI= T, 1) - if DscPcdValueList[0] in ['True', 'true', 'TRUE']: + if DscPcdValueList[0] in TAB_TRUE_SET: self._ValueList[2] =3D TokenList[1].replace(DscPcdValueList[0]= , '1', 1); - elif DscPcdValueList[0] in ['False', 'false', 'FALSE']: + elif DscPcdValueList[0] in TAB_FALSE_SET: self._ValueList[2] =3D TokenList[1].replace(DscPcdValueList[0]= , '0', 1); =20 =20 @@ -1248,7 +1248,7 @@ class DscParser(MetaFileParser): Macros.update(GlobalData.gPlatformDefines) Macros.update(GlobalData.gCommandLineDefines) # PCD cannot be referenced in macro definition - if self._ItemType not in [MODEL_META_DATA_DEFINE, MODEL_META_DATA_= GLOBAL_DEFINE]: + if self._ItemType not in {MODEL_META_DATA_DEFINE, MODEL_META_DATA_= GLOBAL_DEFINE}: Macros.update(self._Symbols) if GlobalData.BuildOptionPcd: for Item in GlobalData.BuildOptionPcd: @@ -1412,9 +1412,9 @@ class DscParser(MetaFileParser): def __RetrievePcdValue(self): Content =3D open(str(self.MetaFile), 'r').readlines() GlobalData.gPlatformOtherPcds['DSCFILE'] =3D str(self.MetaFile) - for PcdType in (MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_DYNAMIC_D= EFAULT, MODEL_PCD_DYNAMIC_HII, + for PcdType in [MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_DYNAMIC_D= EFAULT, MODEL_PCD_DYNAMIC_HII, MODEL_PCD_DYNAMIC_VPD, MODEL_PCD_DYNAMIC_EX_DEFAUL= T, MODEL_PCD_DYNAMIC_EX_HII, - MODEL_PCD_DYNAMIC_EX_VPD): + MODEL_PCD_DYNAMIC_EX_VPD]: Records =3D self._RawTable.Query(PcdType, BelongsToItem=3D -1.= 0) for TokenSpaceGuid, PcdName, Value, Dummy2, Dummy3, Dummy4,ID,= Line in Records: Name =3D TokenSpaceGuid + '.' + PcdName @@ -1455,8 +1455,8 @@ class DscParser(MetaFileParser): =20 def __ProcessDirective(self): Result =3D None - if self._ItemType in [MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, - MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF= ]: + if self._ItemType in {MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, + MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSEIF= }: Macros =3D self._Macros Macros.update(GlobalData.gGlobalDefines) try: @@ -1474,9 +1474,9 @@ class DscParser(MetaFileParser): Line=3Dself._LineIndex + 1) Result =3D Excpt.result =20 - if self._ItemType in [MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, + if self._ItemType in {MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, MODEL_META_DATA_CONDITIONAL_STATEMENT_IFDEF, - MODEL_META_DATA_CONDITIONAL_STATEMENT_IFNDEF= ]: + MODEL_META_DATA_CONDITIONAL_STATEMENT_IFNDEF= }: self._DirectiveStack.append(self._ItemType) if self._ItemType =3D=3D MODEL_META_DATA_CONDITIONAL_STATEMENT= _IF: Result =3D bool(Result) @@ -1500,9 +1500,9 @@ class DscParser(MetaFileParser): while self._DirectiveStack: self._DirectiveEvalStack.pop() Directive =3D self._DirectiveStack.pop() - if Directive in [MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, + if Directive in {MODEL_META_DATA_CONDITIONAL_STATEMENT_IF, MODEL_META_DATA_CONDITIONAL_STATEMENT_IFD= EF, - MODEL_META_DATA_CONDITIONAL_STATEMENT_IFN= DEF]: + MODEL_META_DATA_CONDITIONAL_STATEMENT_IFN= DEF}: break elif self._ItemType =3D=3D MODEL_META_DATA_INCLUDE: # The included file must be relative to workspace or same dire= ctory as DSC file @@ -1600,7 +1600,7 @@ class DscParser(MetaFileParser): self._ValueList[1] =3D ReplaceMacro(self._ValueList[1], self._Macr= os, RaiseError=3DTrue) =20 def __ProcessPcd(self): - if self._ItemType not in [MODEL_PCD_FEATURE_FLAG, MODEL_PCD_FIXED_= AT_BUILD]: + if self._ItemType not in {MODEL_PCD_FEATURE_FLAG, MODEL_PCD_FIXED_= AT_BUILD}: self._ValueList[2] =3D ReplaceMacro(self._ValueList[2], self._= Macros, RaiseError=3DTrue) return =20 @@ -1617,9 +1617,9 @@ class DscParser(MetaFileParser): except: pass =20 - if ValList[Index] =3D=3D 'True': + if ValList[Index] =3D=3D TAB_TRUE_3: ValList[Index] =3D '1' - if ValList[Index] =3D=3D 'False': + if ValList[Index] =3D=3D TAB_FALSE_3: ValList[Index] =3D '0' =20 if (not self._DirectiveEvalStack) or (False not in self._Directive= EvalStack): @@ -1852,7 +1852,7 @@ class DecParser(MetaFileParser): if len(ItemList) > 2: S2 =3D ItemList[2].upper() # only Includes, GUIDs, PPIs, Protocols section have Priva= te tag - if self._SectionName in [TAB_INCLUDES.upper(), TAB_GUIDS.u= pper(), TAB_PROTOCOLS.upper(), TAB_PPIS.upper()]: + if self._SectionName in {TAB_INCLUDES.upper(), TAB_GUIDS.u= pper(), TAB_PROTOCOLS.upper(), TAB_PPIS.upper()}: if S2 !=3D 'PRIVATE': EdkLogger.error("Parser", FORMAT_INVALID, 'Please = use keyword "Private" as section tag modifier.', File=3Dself.MetaFile, Line=3Dself.= _LineIndex + 1, ExtraData=3Dself._CurrentLine) @@ -2030,9 +2030,9 @@ class DecParser(MetaFileParser): self._ValueList[0] =3D self._CurrentStructurePcdName self._ValueList[1] =3D ValueList[1].strip() =20 - if ValueList[0] in ['True', 'true', 'TRUE']: + if ValueList[0] in TAB_TRUE_SET: ValueList[0] =3D '1' - elif ValueList[0] in ['False', 'false', 'FALSE']: + elif ValueList[0] in TAB_FALSE_SET: ValueList[0] =3D '0' =20 # check for duplicate PCD definition diff --git a/BaseTools/Source/Python/build/BuildReport.py b/BaseTools/Sourc= e/Python/build/BuildReport.py index db9e1ed062fb..478dab3b61b0 100644 --- a/BaseTools/Source/Python/build/BuildReport.py +++ b/BaseTools/Source/Python/build/BuildReport.py @@ -124,7 +124,9 @@ gDriverTypeMap =3D { } =20 ## The look up table of the supported opcode in the dependency expression = binaries -gOpCodeList =3D ["BEFORE", "AFTER", "PUSH", "AND", "OR", "NOT", "TRUE", "F= ALSE", "END", "SOR"] +gOpCodeList =3D [DEPEX_OPCODE_BEFORE, DEPEX_OPCODE_AFTER, DEPEX_OPCODE_PUS= H, + DEPEX_OPCODE_AND, DEPEX_OPCODE_OR, DEPEX_OPCODE_NOT, DEPEX_= OPCODE_TRUE, + DEPEX_OPCODE_FALSE, DEPEX_OPCODE_END, DEPEX_OPCODE_SOR] =20 ## # Writes a string to the file object. @@ -296,7 +298,7 @@ class DepexParser(object): OpCode =3D DepexFile.read(1) while OpCode: Statement =3D gOpCodeList[struct.unpack("B", OpCode)[0]] - if Statement in ["BEFORE", "AFTER", "PUSH"]: + if Statement in {"BEFORE", "AFTER", "PUSH"}: GuidValue =3D "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02= X%02X%02X" % \ struct.unpack(PACK_PATTERN_GUID, DepexFile= .read(16)) GuidString =3D self._GuidDb.get(GuidValue, GuidValue) @@ -409,7 +411,7 @@ class DepexReport(object): if not ModuleType: ModuleType =3D COMPONENT_TO_MODULE_MAP_DICT.get(M.ComponentTyp= e, "") =20 - if ModuleType in [SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, SUP_MODULE_= DXE_CORE, SUP_MODULE_SMM_CORE, SUP_MODULE_MM_CORE_STANDALONE, SUP_MODULE_UE= FI_APPLICATION]: + if ModuleType in {SUP_MODULE_SEC, SUP_MODULE_PEI_CORE, SUP_MODULE_= DXE_CORE, SUP_MODULE_SMM_CORE, SUP_MODULE_MM_CORE_STANDALONE, SUP_MODULE_UE= FI_APPLICATION}: return =20 for Source in M.SourceFileList: @@ -493,25 +495,25 @@ class BuildFlagsReport(object): # for Source in M.SourceFileList: Ext =3D os.path.splitext(Source.File)[1].lower() - if Ext in [".c", ".cc", ".cpp"]: + if Ext in {".c", ".cc", ".cpp"}: BuildOptions["CC"] =3D 1 - elif Ext in [".s", ".asm"]: + elif Ext in {".s", ".asm"}: BuildOptions["PP"] =3D 1 BuildOptions["ASM"] =3D 1 - elif Ext in [".vfr"]: + elif Ext =3D=3D ".vfr": BuildOptions["VFRPP"] =3D 1 BuildOptions["VFR"] =3D 1 - elif Ext in [".dxs"]: + elif Ext =3D=3D ".dxs": BuildOptions["APP"] =3D 1 BuildOptions["CC"] =3D 1 - elif Ext in [".asl"]: + elif Ext =3D=3D ".asl": BuildOptions["ASLPP"] =3D 1 BuildOptions["ASL"] =3D 1 - elif Ext in [".aslc"]: + elif Ext =3D=3D ".aslc": BuildOptions["ASLCC"] =3D 1 BuildOptions["ASLDLINK"] =3D 1 BuildOptions["CC"] =3D 1 - elif Ext in [".asm16"]: + elif Ext =3D=3D ".asm16": BuildOptions["ASMLINK"] =3D 1 BuildOptions["SLINK"] =3D 1 BuildOptions["DLINK"] =3D 1 @@ -1030,11 +1032,11 @@ class PcdReport(object): IsStructure =3D False if GlobalData.gStructurePcd and (self.Arch in GlobalDa= ta.gStructurePcd) and ((Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalD= ata.gStructurePcd[self.Arch]): IsStructure =3D True - if TypeName in ('DYNVPD', 'DEXVPD'): + if TypeName in {'DYNVPD', 'DEXVPD'}: SkuInfoList =3D Pcd.SkuInfoList Pcd =3D GlobalData.gStructurePcd[self.Arch][(Pcd.T= okenCName, Pcd.TokenSpaceGuidCName)] Pcd.DatumType =3D Pcd.StructName - if TypeName in ('DYNVPD', 'DEXVPD'): + if TypeName in {'DYNVPD', 'DEXVPD'}: Pcd.SkuInfoList =3D SkuInfoList if Pcd.PcdFieldValueFromComm: BuildOptionMatch =3D True @@ -1052,7 +1054,7 @@ class PcdReport(object): SkuList =3D sorted(Pcd.SkuInfoList.keys()) for Sku in SkuList: SkuInfo =3D Pcd.SkuInfoList[Sku] - if TypeName in ('DYNHII', 'DEXHII'): + if TypeName in {'DYNHII', 'DEXHII'}: if SkuInfo.DefaultStoreDict: DefaultStoreList =3D sorted(Sk= uInfo.DefaultStoreDict.keys()) for DefaultStore in DefaultSto= reList: @@ -1091,7 +1093,7 @@ class PcdReport(object): if ModulePcdSet is None: if IsStructure: continue - if not TypeName in ('PATCH', 'FLAG', 'FIXED'): + if TypeName not in {'PATCH', 'FLAG', 'FIXED'}: continue if not BuildOptionMatch: ModuleOverride =3D self.ModulePcdOverride.get(= (Pcd.TokenCName, Pcd.TokenSpaceGuidCName), {}) @@ -1186,7 +1188,7 @@ class PcdReport(object): for Sku in SkuList: SkuInfo =3D Pcd.SkuInfoList[Sku] SkuIdName =3D SkuInfo.SkuIdName - if TypeName in ('DYNHII', 'DEXHII'): + if TypeName in {'DYNHII', 'DEXHII'}: if SkuInfo.DefaultStoreDict: DefaultStoreList =3D sorted(SkuInfo.DefaultStoreDi= ct.keys()) for DefaultStore in DefaultStoreList: @@ -1271,7 +1273,7 @@ class PcdReport(object): FileWrite(File, ' %-*s : %6s %10s =3D %s= ' % (self.MaxLen, ' ' , TypeName, '(' + Pcd.DatumType + ')', Value)) else: FileWrite(File, ' %-*s : %6s %10s %10s = =3D %s' % (self.MaxLen, ' ' , TypeName, '(' + Pcd.DatumType + ')', '(' + Sk= uIdName + ')', Value)) - if TypeName in ('DYNVPD', 'DEXVPD'): + if TypeName in {'DYNVPD', 'DEXVPD'}: FileWrite(File, '%*s' % (self.MaxLen + 4, SkuInfo.= VpdOffset)) if IsStructure: OverrideValues =3D Pcd.SkuOverrideValues[Sku] diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Pyth= on/build/build.py index 1fb8c7985d99..66a97fc8c1cd 100644 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -224,7 +224,7 @@ def NormFile(FilePath, Workspace): EdkLogger.error("build", FILE_NOT_FOUND, ExtraData=3D"\t%s (Please= give file in absolute path or relative to WORKSPACE)" % FileFullPath) =20 # remove workspace directory from the beginning part of the file path - if Workspace[-1] in ["\\", "/"]: + if Workspace[-1] in {"\\", "/"}: return FileFullPath[len(Workspace):] else: return FileFullPath[(len(Workspace) + 1):] @@ -410,7 +410,7 @@ class ModuleMakeUnit(BuildUnit): def __init__(self, Obj, Target): Dependency =3D [ModuleMakeUnit(La, Target) for La in Obj.LibraryAu= toGenList] BuildUnit.__init__(self, Obj, Obj.BuildCommand, Target, Dependency= , Obj.MakeFileDir) - if Target in [None, "", "all"]: + if Target in {None, "", "all"}: self.Target =3D "tbuild" =20 ## The smallest platform unit that can be built by nmake/make command in m= ulti-thread build mode @@ -1228,7 +1228,7 @@ class Build(): return False =20 # skip file generation for cleanxxx targets, run and fds target - if Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']: + if Target not in {'clean', 'cleanlib', 'cleanall', 'run', 'fds'}: # for target which must generate AutoGen code and makefile if not self.SkipAutoGen or Target =3D=3D 'genc': self.Progress.Start("Generating code") @@ -1347,7 +1347,7 @@ class Build(): return False =20 # skip file generation for cleanxxx targets, run and fds target - if Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']: + if Target not in {'clean', 'cleanlib', 'cleanall', 'run', 'fds'}: # for target which must generate AutoGen code and makefile if not self.SkipAutoGen or Target =3D=3D 'genc': self.Progress.Start("Generating code") @@ -1488,7 +1488,7 @@ class Build(): for SectionHeader in ModuleInfo.Image.SectionHeaderList: if SectionHeader[0] =3D=3D '.text': TextSectionAddress =3D SectionHeader[1] - elif SectionHeader[0] in ['.data', '.sdata']: + elif SectionHeader[0] in {'.data', '.sdata'}: DataSectionAddress =3D SectionHeader[1] if AddrIsOffset: MapBuffer.write('(GUID=3D%s, .textbaseaddress=3D-0x%010X, = .databaseaddress=3D-0x%010X)\n' % (ModuleInfo.Guid, 0 - (BaseAddress + Text= SectionAddress), 0 - (BaseAddress + DataSectionAddress))) @@ -1583,19 +1583,19 @@ class Build(): if not ImageClass.IsValid: EdkLogger.error("build", FILE_PARSE_FAILURE, Extra= Data=3DImageClass.ErrorInfo) ImageInfo =3D PeImageInfo(Module.Name, Module.Guid, Mo= dule.Arch, Module.OutputDir, Module.DebugDir, ImageClass) - if Module.ModuleType in [SUP_MODULE_PEI_CORE, SUP_MODU= LE_PEIM, EDK_COMPONENT_TYPE_COMBINED_PEIM_DRIVER, EDK_COMPONENT_TYPE_PIC_PE= IM, EDK_COMPONENT_TYPE_RELOCATABLE_PEIM, SUP_MODULE_DXE_CORE]: + if Module.ModuleType in {SUP_MODULE_PEI_CORE, SUP_MODU= LE_PEIM, EDK_COMPONENT_TYPE_COMBINED_PEIM_DRIVER, EDK_COMPONENT_TYPE_PIC_PE= IM, EDK_COMPONENT_TYPE_RELOCATABLE_PEIM, SUP_MODULE_DXE_CORE}: PeiModuleList[Module.MetaFile] =3D ImageInfo PeiSize +=3D ImageInfo.Image.Size - elif Module.ModuleType in [EDK_COMPONENT_TYPE_BS_DRIVE= R, SUP_MODULE_DXE_DRIVER, SUP_MODULE_UEFI_DRIVER]: + elif Module.ModuleType in {EDK_COMPONENT_TYPE_BS_DRIVE= R, SUP_MODULE_DXE_DRIVER, SUP_MODULE_UEFI_DRIVER}: BtModuleList[Module.MetaFile] =3D ImageInfo BtSize +=3D ImageInfo.Image.Size - elif Module.ModuleType in [SUP_MODULE_DXE_RUNTIME_DRIV= ER, EDK_COMPONENT_TYPE_RT_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, EDK_COMPONENT_= TYPE_SAL_RT_DRIVER]: + elif Module.ModuleType in {SUP_MODULE_DXE_RUNTIME_DRIV= ER, EDK_COMPONENT_TYPE_RT_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, EDK_COMPONENT_= TYPE_SAL_RT_DRIVER}: RtModuleList[Module.MetaFile] =3D ImageInfo #IPF runtime driver needs to be at 2 page alignmen= t. if IsIpfPlatform and ImageInfo.Image.Size % 0x2000= !=3D 0: ImageInfo.Image.Size =3D (ImageInfo.Image.Size= / 0x2000 + 1) * 0x2000 RtSize +=3D ImageInfo.Image.Size - elif Module.ModuleType in [SUP_MODULE_SMM_CORE, SUP_MO= DULE_DXE_SMM_DRIVER, SUP_MODULE_MM_STANDALONE, SUP_MODULE_MM_CORE_STANDALON= E]: + elif Module.ModuleType in {SUP_MODULE_SMM_CORE, SUP_MO= DULE_DXE_SMM_DRIVER, SUP_MODULE_MM_STANDALONE, SUP_MODULE_MM_CORE_STANDALON= E}: SmmModuleList[Module.MetaFile] =3D ImageInfo SmmSize +=3D ImageInfo.Image.Size if Module.ModuleType =3D=3D SUP_MODULE_DXE_SMM_DRI= VER: @@ -1757,7 +1757,7 @@ class Build(): self._BuildPa(self.Target, Pa, FfsCommand=3DCmdListDic= t) =20 # Create MAP file when Load Fix Address is enabled. - if self.Target in ["", "all", "fds"]: + if self.Target in {"", "all", "fds"}: for Arch in Wa.ArchList: GlobalData.gGlobalDefines['ARCH'] =3D Arch # @@ -1855,7 +1855,7 @@ class Build(): self.HashSkipModules.append(Ma) continue # Not to auto-gen for targets 'clean', 'cleanl= ib', 'cleanall', 'run', 'fds' - if self.Target not in ['clean', 'cleanlib', 'c= leanall', 'run', 'fds']: + if self.Target not in {'clean', 'cleanlib', 'c= leanall', 'run', 'fds'}: # for target which must generate AutoGen c= ode and makefile if not self.SkipAutoGen or self.Target =3D= =3D 'genc': self.Progress.Start("Generating code") @@ -2036,7 +2036,7 @@ class Build(): continue =20 # Not to auto-gen for targets 'clean', 'cleanlib',= 'cleanall', 'run', 'fds' - if self.Target not in ['clean', 'cleanlib', 'clean= all', 'run', 'fds']: + if self.Target not in {'clean', 'cleanlib', 'clean= all', 'run', 'fds'}: # for target which must generate AutoGen code = and makefile if not self.SkipAutoGen or self.Target =3D=3D = 'genc': Ma.CreateCodeFile(True) @@ -2101,7 +2101,7 @@ class Build(): EdkLogger.error("build", BUILD_ERROR, "Failed to build= module", ExtraData=3DGlobalData.gBuildingModule) =20 # Create MAP file when Load Fix Address is enabled. - if self.Target in ["", "all", "fds"]: + if self.Target in {"", "all", "fds"}: for Arch in Wa.ArchList: # # Check whether the set fix address is above 4G fo= r 32bit image. @@ -2213,7 +2213,7 @@ class Build(): # def Launch(self): if not self.ModuleFile: - if not self.SpawnMode or self.Target not in ["", "all"]: + if not self.SpawnMode or self.Target not in {"", "all"}: self.SpawnMode =3D False self._BuildPlatform() else: @@ -2274,7 +2274,7 @@ def ParseDefines(DefineList=3D[]): ExtraData=3DDefineTokenList[0]) =20 if len(DefineTokenList) =3D=3D 1: - DefineDict[DefineTokenList[0]] =3D "TRUE" + DefineDict[DefineTokenList[0]] =3D TAB_TRUE_1 else: DefineDict[DefineTokenList[0]] =3D DefineTokenList[1].stri= p() return DefineDict @@ -2478,7 +2478,7 @@ def Main(): if ErrorCode !=3D 0: EdkLogger.error("build", ErrorCode, ExtraData=3DErrorInfo) =20 - if Option.Flag is not None and Option.Flag not in ['-c', '-s']: + if Option.Flag is not None and Option.Flag not in {'-c', '-s'}: EdkLogger.error("build", OPTION_VALUE_INVALID, "UNI flag must = be one of -c or -s") =20 MyBuild =3D Build(Target, Workspace, Option) --=20 2.16.2.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Fri May 3 05:47:03 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 15263213986631017.6202677204723; Mon, 14 May 2018 11:09:58 -0700 (PDT) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id CDC312096AED9; Mon, 14 May 2018 11:09:29 -0700 (PDT) Received: from mga07.intel.com (mga07.intel.com [134.134.136.100]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 58DC721CB74A4 for ; Mon, 14 May 2018 11:09:25 -0700 (PDT) Received: from orsmga001.jf.intel.com ([10.7.209.18]) by orsmga105.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 14 May 2018 11:09:24 -0700 Received: from jcarsey-desk1.amr.corp.intel.com ([10.7.159.144]) by orsmga001.jf.intel.com with ESMTP; 14 May 2018 11:09:24 -0700 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.100; helo=mga07.intel.com; envelope-from=jaben.carsey@intel.com; receiver=edk2-devel@lists.01.org X-Amp-Result: SKIPPED(no attachment in message) X-Amp-File-Uploaded: False X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.49,401,1520924400"; d="scan'208";a="55814292" From: Jaben Carsey To: edk2-devel@lists.01.org Date: Mon, 14 May 2018 11:09:20 -0700 Message-Id: <3549b85c66f032efb55c119327516bf853f84828.1526321053.git.jaben.carsey@intel.com> X-Mailer: git-send-email 2.16.2.windows.1 In-Reply-To: References: In-Reply-To: References: Subject: [edk2] [PATCH v1 11/11] BaseTools: remove extra assignment X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.26 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Liming Gao MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" there is no use to assign back to a variable. just return the result. Cc: Liming Gao Cc: Yonghong Zhu Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jaben Carsey --- BaseTools/Source/Python/Common/Expression.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/BaseTools/Source/Python/Common/Expression.py b/BaseTools/Sourc= e/Python/Common/Expression.py index 3133f610b4a7..3036af058c1d 100644 --- a/BaseTools/Source/Python/Common/Expression.py +++ b/BaseTools/Source/Python/Common/Expression.py @@ -197,8 +197,7 @@ def IntToStr(Value): while Value > 0: StrList.append(chr(Value & 0xff)) Value =3D Value >> 8 - Value =3D '"{VAL}"'.format(VAL=3D''.join(StrList)) - return Value + return '"{VAL}"'.format(VAL=3D''.join(StrList)) =20 SupportedInMacroList =3D ['TARGET', 'TOOL_CHAIN_TAG', 'ARCH', 'FAMILY'] =20 --=20 2.16.2.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel