X-Git-Url: https://git.proxmox.com/?a=blobdiff_plain;f=BaseTools%2FSource%2FPython%2FAutoGen%2FUniClassObject.py;h=9f6a2715668c0d590e5cd36211aac14aa6721f23;hb=1b8caf0d87eacc66aba70e8698c7bd1518bb7be1;hp=1eb65c1e9a4bd6bf9db105c2ad9411ab19cac233;hpb=08dd311f5dc735c595d39faf2e6f7e2810bb79a9;p=mirror_edk2.git
diff --git a/BaseTools/Source/Python/AutoGen/UniClassObject.py b/BaseTools/Source/Python/AutoGen/UniClassObject.py
index 1eb65c1e9a..9f6a271566 100644
--- a/BaseTools/Source/Python/AutoGen/UniClassObject.py
+++ b/BaseTools/Source/Python/AutoGen/UniClassObject.py
@@ -1,26 +1,25 @@
-# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.
-# This program and the accompanying materials
-# are licensed and made available under the terms and conditions of the BSD License
-# which accompanies this distribution. The full text of the license may be found at
-# http://opensource.org/licenses/bsd-license.php
+## @file
+# This file is used to collect all defined strings in multiple uni files
#
-# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
#
-#This file is used to collect all defined strings in multiple uni files
+# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
+# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent
##
# Import Modules
#
-import os, codecs, re
+from __future__ import print_function
+import Common.LongFilePathOs as os, codecs, re
import distutils.util
import Common.EdkLogger as EdkLogger
+from io import BytesIO
from Common.BuildToolError import *
-from Common.String import GetLineNo
+from Common.StringUtils import GetLineNo
from Common.Misc import PathClass
-
+from Common.LongFilePathSupport import LongFilePath
+from Common.GlobalData import *
##
# Static definitions
#
@@ -37,22 +36,10 @@ CR = u'\u000D'
LF = u'\u000A'
NULL = u'\u0000'
TAB = u'\t'
-BACK_SPLASH = u'\\'
+BACK_SLASH_PLACEHOLDER = u'\u0006'
gIncludePattern = re.compile("^#include +[\"<]+([^\"< >]+)[>\"]+$", re.MULTILINE | re.UNICODE)
-## Convert a python unicode string to a normal string
-#
-# Convert a python unicode string to a normal string
-# UniToStr(u'I am a string') is 'I am a string'
-#
-# @param Uni: The python unicode string
-#
-# @retval: The formatted normal string
-#
-def UniToStr(Uni):
- return repr(Uni)[2:-1]
-
## Convert a unicode string to a Hex list
#
# Convert a unicode string to a Hex list
@@ -106,22 +93,20 @@ LangConvTable = {'eng':'en', 'fra':'fr', \
## GetLanguageCode
#
# Check the language code read from .UNI file and convert ISO 639-2 codes to RFC 4646 codes if appropriate
-# ISO 639-2 language codes supported in compatiblity mode
+# ISO 639-2 language codes supported in compatibility mode
# RFC 4646 language codes supported in native mode
#
# @param LangName: Language codes read from .UNI file
#
-# @retval LangName: Valid lanugage code in RFC 4646 format or None
+# @retval LangName: Valid language code in RFC 4646 format or None
#
def GetLanguageCode(LangName, IsCompatibleMode, File):
- global LangConvTable
-
length = len(LangName)
if IsCompatibleMode:
if length == 3 and LangName.isalpha():
TempLangName = LangConvTable.get(LangName.lower())
- if TempLangName != None:
- return TempLangName
+ if TempLangName is not None:
+ return TempLangName
return LangName
else:
EdkLogger.error("Unicode File Parser", FORMAT_INVALID, "Invalid ISO 639-2 language code : %s" % LangName, File)
@@ -132,7 +117,7 @@ def GetLanguageCode(LangName, IsCompatibleMode, File):
if LangName.isalpha():
return LangName
elif length == 3:
- if LangName.isalpha() and LangConvTable.get(LangName.lower()) == None:
+ if LangName.isalpha() and LangConvTable.get(LangName.lower()) is None:
return LangName
elif length == 5:
if LangName[0:2].isalpha() and LangName[2] == '-':
@@ -140,11 +125,42 @@ def GetLanguageCode(LangName, IsCompatibleMode, File):
elif length >= 6:
if LangName[0:2].isalpha() and LangName[2] == '-':
return LangName
- if LangName[0:3].isalpha() and LangConvTable.get(LangName.lower()) == None and LangName[3] == '-':
+ if LangName[0:3].isalpha() and LangConvTable.get(LangName.lower()) is None and LangName[3] == '-':
return LangName
EdkLogger.error("Unicode File Parser", FORMAT_INVALID, "Invalid RFC 4646 language code : %s" % LangName, File)
+## Ucs2Codec
+#
+# This is only a partial codec implementation. It only supports
+# encoding, and is primarily used to check that all the characters are
+# valid for UCS-2.
+#
+class Ucs2Codec(codecs.Codec):
+ def __init__(self):
+ self.__utf16 = codecs.lookup('utf-16')
+
+ def encode(self, input, errors='strict'):
+ for Char in input:
+ CodePoint = ord(Char)
+ if CodePoint >= 0xd800 and CodePoint <= 0xdfff:
+ 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)
+
+TheUcs2Codec = Ucs2Codec()
+def Ucs2Search(name):
+ if name == 'ucs-2':
+ return codecs.CodecInfo(
+ name=name,
+ encode=TheUcs2Codec.encode,
+ decode=TheUcs2Codec.decode)
+ else:
+ return None
+codecs.register(Ucs2Search)
+
## StringDefClassObject
#
# A structure for language definition
@@ -160,14 +176,14 @@ class StringDefClassObject(object):
self.UseOtherLangDef = UseOtherLangDef
self.Length = 0
- if Name != None:
+ if Name is not None:
self.StringName = Name
self.StringNameByteList = UniToHexList(Name)
- if Value != None:
+ if Value is not None:
self.StringValue = Value + u'\x00' # Add a NULL at string tail
self.StringValueByteList = UniToHexList(self.StringValue)
self.Length = len(self.StringValueByteList)
- if Token != None:
+ if Token is not None:
self.Token = Token
def __str__(self):
@@ -178,11 +194,24 @@ class StringDefClassObject(object):
repr(self.UseOtherLangDef)
def UpdateValue(self, Value = None):
- if Value != None:
+ if Value is not None:
self.StringValue = Value + u'\x00' # Add a NULL at string tail
self.StringValueByteList = UniToHexList(self.StringValue)
self.Length = len(self.StringValueByteList)
+def StripComments(Line):
+ Comment = u'//'
+ CommentPos = Line.find(Comment)
+ while CommentPos >= 0:
+ # if there are non matched quotes before the comment header
+ # then we are in the middle of a string
+ # but we need to ignore the escaped quotes and backslashes.
+ if ((Line.count(u'"', 0, CommentPos) - Line.count(u'\\"', 0, CommentPos)) & 1) == 1:
+ CommentPos = Line.find (Comment, CommentPos + 1)
+ else:
+ return Line[:CommentPos].strip()
+ return Line.strip()
+
## UniFileClassObject
#
# A structure for .uni file definition
@@ -193,6 +222,8 @@ class UniFileClassObject(object):
self.Token = 2
self.LanguageDef = [] #[ [u'LanguageIdentifier', u'PrintableName'], ... ]
self.OrderedStringList = {} #{ u'LanguageIdentifier' : [StringDefClassObject] }
+ self.OrderedStringDict = {} #{ u'LanguageIdentifier' : {StringName:(IndexInList)} }
+ self.OrderedStringListByToken = {} #{ u'LanguageIdentifier' : {Token: StringDefClassObject} }
self.IsCompatibleMode = IsCompatibleMode
self.IncludePathList = IncludePathList
if len(self.FileList) > 0:
@@ -205,14 +236,14 @@ class UniFileClassObject(object):
Lang = distutils.util.split_quoted((Line.split(u"//")[0]))
if len(Lang) != 3:
try:
- FileIn = codecs.open(File.Path, mode='rb', encoding='utf-16').read()
- except UnicodeError, X:
+ FileIn = UniFileClassObject.OpenUniFile(LongFilePath(File.Path))
+ except UnicodeError as X:
EdkLogger.error("build", FILE_READ_FAILURE, "File read failure: %s" % str(X), ExtraData=File);
except:
EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=File);
LineNo = GetLineNo(FileIn, Line, False)
EdkLogger.error("Unicode File Parser", PARSER_ERROR, "Wrong language definition",
- ExtraData="""%s\n\t*Correct format is like '#langdef en-US "English"'""" % Line, File = File, Line = LineNo)
+ ExtraData="""%s\n\t*Correct format is like '#langdef en-US "English"'""" % Line, File=File, Line=LineNo)
else:
LangName = GetLanguageCode(Lang[1], self.IsCompatibleMode, self.File)
LangPrintName = Lang[2]
@@ -235,7 +266,7 @@ class UniFileClassObject(object):
if not IsLangInDef:
#
# The found STRING tokens will be added into new language string list
- # so that the unique STRING identifier is reserved for all languages in the package list.
+ # so that the unique STRING identifier is reserved for all languages in the package list.
#
FirstLangName = self.LanguageDef[0][0]
if LangName != FirstLangName:
@@ -246,23 +277,79 @@ class UniFileClassObject(object):
else:
OtherLang = FirstLangName
self.OrderedStringList[LangName].append (StringDefClassObject(Item.StringName, '', Item.Referenced, Item.Token, OtherLang))
-
+ self.OrderedStringDict[LangName][Item.StringName] = len(self.OrderedStringList[LangName]) - 1
return True
+ @staticmethod
+ def OpenUniFile(FileName):
+ #
+ # Read file
+ #
+ try:
+ UniFile = open(FileName, mode='rb')
+ FileIn = UniFile.read()
+ UniFile.close()
+ except:
+ EdkLogger.Error("build", FILE_OPEN_FAILURE, ExtraData=File)
+
+ #
+ # Detect Byte Order Mark at beginning of file. Default to UTF-8
+ #
+ Encoding = 'utf-8'
+ if (FileIn.startswith(codecs.BOM_UTF16_BE) or
+ FileIn.startswith(codecs.BOM_UTF16_LE)):
+ Encoding = 'utf-16'
+
+ UniFileClassObject.VerifyUcs2Data(FileIn, FileName, Encoding)
+
+ UniFile = BytesIO(FileIn)
+ Info = codecs.lookup(Encoding)
+ (Reader, Writer) = (Info.streamreader, Info.streamwriter)
+ return codecs.StreamReaderWriter(UniFile, Reader, Writer)
+
+ @staticmethod
+ def VerifyUcs2Data(FileIn, FileName, Encoding):
+ Ucs2Info = codecs.lookup('ucs-2')
+ #
+ # Convert to unicode
+ #
+ try:
+ FileDecoded = codecs.decode(FileIn, Encoding)
+ Ucs2Info.encode(FileDecoded)
+ except:
+ UniFile = BytesIO(FileIn)
+ Info = codecs.lookup(Encoding)
+ (Reader, Writer) = (Info.streamreader, Info.streamwriter)
+ File = codecs.StreamReaderWriter(UniFile, Reader, Writer)
+ LineNumber = 0
+ ErrMsg = lambda Encoding, LineNumber: \
+ '%s contains invalid %s characters on line %d.' % \
+ (FileName, Encoding, LineNumber)
+ while True:
+ LineNumber = LineNumber + 1
+ try:
+ Line = File.readline()
+ if Line == '':
+ EdkLogger.error('Unicode File Parser', PARSER_ERROR,
+ ErrMsg(Encoding, LineNumber))
+ Ucs2Info.encode(Line)
+ except:
+ EdkLogger.error('Unicode File Parser', PARSER_ERROR,
+ ErrMsg('UCS-2', LineNumber))
+
#
# Get String name and value
#
def GetStringObject(self, Item):
- Name = ''
Language = ''
Value = ''
Name = Item.split()[1]
- # Check the string name is the upper character
- if not self.IsCompatibleMode and Name != '':
- MatchString = re.match('[A-Z0-9_]+', Name, re.UNICODE)
- if MatchString == None or MatchString.end(0) != len(Name):
- EdkLogger.error('Unicode File Parser', FORMAT_INVALID, 'The string token name %s defined in UNI file %s contains the invalid lower case character.' %(Name, self.File))
+ # Check the string name
+ if Name != '':
+ MatchString = gIdentifierPattern.match(Name)
+ if MatchString is None:
+ EdkLogger.error('Unicode File Parser', FORMAT_INVALID, 'The string token name %s defined in UNI file %s contains the invalid character.' % (Name, self.File))
LanguageList = Item.split(u'#language ')
for IndexI in range(len(LanguageList)):
if IndexI == 0:
@@ -288,8 +375,8 @@ class UniFileClassObject(object):
EdkLogger.error("Unicode File Parser", FILE_NOT_FOUND, ExtraData=File.Path)
try:
- FileIn = codecs.open(File.Path, mode='rb', encoding='utf-16').readlines()
- except UnicodeError, X:
+ FileIn = UniFileClassObject.OpenUniFile(LongFilePath(File.Path))
+ except UnicodeError as X:
EdkLogger.error("build", FILE_READ_FAILURE, "File read failure: %s" % str(X), ExtraData=File.Path);
except:
EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=File.Path);
@@ -300,11 +387,16 @@ class UniFileClassObject(object):
#
for Line in FileIn:
Line = Line.strip()
+ Line = Line.replace(u'\\\\', BACK_SLASH_PLACEHOLDER)
+ Line = StripComments(Line)
+
#
- # Ignore comment line and empty line
+ # Ignore empty line
#
- if Line == u'' or Line.startswith(u'//'):
+ if len(Line) == 0:
continue
+
+
Line = Line.replace(u'/langdef', u'#langdef')
Line = Line.replace(u'/string', u'#string')
Line = Line.replace(u'/language', u'#language')
@@ -314,18 +406,28 @@ class UniFileClassObject(object):
Line = Line.replace(UNICODE_NARROW_CHAR, NARROW_CHAR)
Line = Line.replace(UNICODE_NON_BREAKING_CHAR, NON_BREAKING_CHAR)
- Line = Line.replace(u'\\\\', u'\u0006')
Line = Line.replace(u'\\r\\n', CR + LF)
Line = Line.replace(u'\\n', CR + LF)
Line = Line.replace(u'\\r', CR)
- Line = Line.replace(u'\\t', u'\t')
- Line = Line.replace(u'''\"''', u'''"''')
+ Line = Line.replace(u'\\t', u' ')
Line = Line.replace(u'\t', u' ')
- Line = Line.replace(u'\u0006', u'\\')
-
-# if Line.find(u'\\x'):
-# hex = Line[Line.find(u'\\x') + 2 : Line.find(u'\\x') + 6]
-# hex = "u'\\u" + hex + "'"
+ Line = Line.replace(u'\\"', u'"')
+ Line = Line.replace(u"\\'", u"'")
+ Line = Line.replace(BACK_SLASH_PLACEHOLDER, u'\\')
+
+ StartPos = Line.find(u'\\x')
+ while (StartPos != -1):
+ EndPos = Line.find(u'\\', StartPos + 1, StartPos + 7)
+ if EndPos != -1 and EndPos - StartPos == 6 :
+ if g4HexChar.match(Line[StartPos + 2 : EndPos], re.UNICODE):
+ EndStr = Line[EndPos: ]
+ UniStr = Line[StartPos + 2: EndPos]
+ if EndStr.startswith(u'\\x') and len(EndStr) >= 7:
+ if EndStr[6] == u'\\' and g4HexChar.match(EndStr[2 : 6], re.UNICODE):
+ Line = Line[0 : StartPos] + UniStr + EndStr
+ else:
+ Line = Line[0 : StartPos] + UniStr + EndStr[1:]
+ StartPos = Line.find(u'\\x', StartPos + 1)
IncList = gIncludePattern.findall(Line)
if len(IncList) == 1:
@@ -346,7 +448,7 @@ class UniFileClassObject(object):
# Load a .uni file
#
def LoadUniFile(self, File = None):
- if File == None:
+ if File is None:
EdkLogger.error("Unicode File Parser", PARSER_ERROR, 'No unicode file is given')
self.File = File
#
@@ -399,11 +501,11 @@ class UniFileClassObject(object):
break
# Value = Value.replace(u'\r\n', u'')
Language = GetLanguageCode(Language, self.IsCompatibleMode, self.File)
- # Check the string name is the upper character
+ # Check the string name
if not self.IsCompatibleMode and Name != '':
- MatchString = re.match('[A-Z0-9_]+', Name, re.UNICODE)
- if MatchString == None or MatchString.end(0) != len(Name):
- EdkLogger.error('Unicode File Parser', FORMAT_INVALID, 'The string token name %s defined in UNI file %s contains the invalid lower case character.' %(Name, self.File))
+ MatchString = gIdentifierPattern.match(Name)
+ if MatchString is None:
+ EdkLogger.error('Unicode File Parser', FORMAT_INVALID, 'The string token name %s defined in UNI file %s contains the invalid character.' % (Name, self.File))
self.AddStringToList(Name, Language, Value)
continue
@@ -450,27 +552,29 @@ class UniFileClassObject(object):
else:
EdkLogger.error('Unicode File Parser', FORMAT_NOT_SUPPORTED, "The language '%s' for %s is not defined in Unicode file %s." \
% (Language, Name, self.File))
-
+
if Language not in self.OrderedStringList:
self.OrderedStringList[Language] = []
+ self.OrderedStringDict[Language] = {}
IsAdded = True
- for Item in self.OrderedStringList[Language]:
- if Name == Item.StringName:
- IsAdded = False
- if Value != None:
- Item.UpdateValue(Value)
- Item.UseOtherLangDef = ''
- break
+ if Name in self.OrderedStringDict[Language]:
+ IsAdded = False
+ if Value is not None:
+ ItemIndexInList = self.OrderedStringDict[Language][Name]
+ Item = self.OrderedStringList[Language][ItemIndexInList]
+ Item.UpdateValue(Value)
+ Item.UseOtherLangDef = ''
if IsAdded:
Token = len(self.OrderedStringList[Language])
if Index == -1:
self.OrderedStringList[Language].append(StringDefClassObject(Name, Value, Referenced, Token, UseOtherLangDef))
+ self.OrderedStringDict[Language][Name] = Token
for LangName in self.LanguageDef:
#
# New STRING token will be added into all language string lists.
- # so that the unique STRING identifier is reserved for all languages in the package list.
+ # so that the unique STRING identifier is reserved for all languages in the package list.
#
if LangName[0] != Language:
if UseOtherLangDef != '':
@@ -478,8 +582,10 @@ class UniFileClassObject(object):
else:
OtherLangDef = Language
self.OrderedStringList[LangName[0]].append(StringDefClassObject(Name, '', Referenced, Token, OtherLangDef))
+ self.OrderedStringDict[LangName[0]][Name] = len(self.OrderedStringList[LangName[0]]) - 1
else:
self.OrderedStringList[Language].insert(Index, StringDefClassObject(Name, Value, Referenced, Token, UseOtherLangDef))
+ self.OrderedStringDict[Language][Name] = Index
#
# Set the string as referenced
@@ -490,17 +596,18 @@ class UniFileClassObject(object):
# So, only update the status of string stoken in first language string list.
#
Lang = self.LanguageDef[0][0]
- for Item in self.OrderedStringList[Lang]:
- if Name == Item.StringName:
- Item.Referenced = True
- break
+ if Name in self.OrderedStringDict[Lang]:
+ ItemIndexInList = self.OrderedStringDict[Lang][Name]
+ Item = self.OrderedStringList[Lang][ItemIndexInList]
+ Item.Referenced = True
+
#
# Search the string in language definition by Name
#
def FindStringValue(self, Name, Lang):
- for Item in self.OrderedStringList[Lang]:
- if Item.StringName == Name:
- return Item
+ if Name in self.OrderedStringDict[Lang]:
+ ItemIndexInList = self.OrderedStringDict[Lang][Name]
+ return self.OrderedStringList[Lang][ItemIndexInList]
return None
@@ -523,6 +630,10 @@ class UniFileClassObject(object):
#
FirstLangName = self.LanguageDef[0][0]
+ # Convert the OrderedStringList to be OrderedStringListByToken in order to faciliate future search by token
+ for LangNameItem in self.LanguageDef:
+ self.OrderedStringListByToken[LangNameItem[0]] = {}
+
#
# Use small token for all referred string stoken.
#
@@ -535,6 +646,7 @@ class UniFileClassObject(object):
OtherLangItem = self.OrderedStringList[LangName][Index]
OtherLangItem.Referenced = True
OtherLangItem.Token = RefToken
+ self.OrderedStringListByToken[LangName][OtherLangItem.Token] = OtherLangItem
RefToken = RefToken + 1
#
@@ -548,24 +660,25 @@ class UniFileClassObject(object):
LangName = LangNameItem[0]
OtherLangItem = self.OrderedStringList[LangName][Index]
OtherLangItem.Token = RefToken + UnRefToken
+ self.OrderedStringListByToken[LangName][OtherLangItem.Token] = OtherLangItem
UnRefToken = UnRefToken + 1
#
# Show the instance itself
#
def ShowMe(self):
- print self.LanguageDef
+ print(self.LanguageDef)
#print self.OrderedStringList
for Item in self.OrderedStringList:
- print Item
+ print(Item)
for Member in self.OrderedStringList[Item]:
- print str(Member)
+ print(str(Member))
# This acts like the main() function for the script, unless it is 'import'ed into another
# script.
if __name__ == '__main__':
EdkLogger.Initialize()
EdkLogger.SetLevel(EdkLogger.DEBUG_0)
- a = UniFileClassObject(['C:\\Edk\\Strings.uni', 'C:\\Edk\\Strings2.uni'])
+ a = UniFileClassObject([PathClass("C:\\Edk\\Strings.uni"), PathClass("C:\\Edk\\Strings2.uni")])
a.ReToken()
a.ShowMe()