BaseTools: Use precompiled RegExp
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / UniClassObject.py
CommitLineData
97fa0ee9
YL
1## @file\r
2# This file is used to collect all defined strings in multiple uni files\r
3#\r
71f02911
CS
4#\r
5# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.<BR>\r
6#\r
018f7b82 7# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>\r
40d841f6 8# This program and the accompanying materials\r
30fdf114
LG
9# are licensed and made available under the terms and conditions of the BSD License\r
10# which accompanies this distribution. The full text of the license may be found at\r
11# http://opensource.org/licenses/bsd-license.php\r
12#\r
13# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
14# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
15\r
30fdf114
LG
16##\r
17# Import Modules\r
18#\r
1be2ed90 19import Common.LongFilePathOs as os, codecs, re\r
40d841f6 20import distutils.util\r
30fdf114 21import Common.EdkLogger as EdkLogger\r
d80e451b 22import StringIO\r
30fdf114
LG
23from Common.BuildToolError import *\r
24from Common.String import GetLineNo\r
25from Common.Misc import PathClass\r
1be2ed90 26from Common.LongFilePathSupport import LongFilePath\r
018f7b82 27from Common.GlobalData import *\r
30fdf114
LG
28##\r
29# Static definitions\r
30#\r
31UNICODE_WIDE_CHAR = u'\\wide'\r
32UNICODE_NARROW_CHAR = u'\\narrow'\r
33UNICODE_NON_BREAKING_CHAR = u'\\nbr'\r
34UNICODE_UNICODE_CR = '\r'\r
35UNICODE_UNICODE_LF = '\n'\r
36\r
37NARROW_CHAR = u'\uFFF0'\r
38WIDE_CHAR = u'\uFFF1'\r
39NON_BREAKING_CHAR = u'\uFFF2'\r
40CR = u'\u000D'\r
41LF = u'\u000A'\r
42NULL = u'\u0000'\r
43TAB = u'\t'\r
71f02911 44BACK_SLASH_PLACEHOLDER = u'\u0006'\r
30fdf114
LG
45\r
46gIncludePattern = re.compile("^#include +[\"<]+([^\"< >]+)[>\"]+$", re.MULTILINE | re.UNICODE)\r
47\r
48## Convert a python unicode string to a normal string\r
49#\r
50# Convert a python unicode string to a normal string\r
51# UniToStr(u'I am a string') is 'I am a string'\r
52#\r
53# @param Uni: The python unicode string\r
54#\r
55# @retval: The formatted normal string\r
56#\r
57def UniToStr(Uni):\r
58 return repr(Uni)[2:-1]\r
59\r
60## Convert a unicode string to a Hex list\r
61#\r
62# Convert a unicode string to a Hex list\r
63# UniToHexList('ABC') is ['0x41', '0x00', '0x42', '0x00', '0x43', '0x00']\r
64#\r
65# @param Uni: The python unicode string\r
66#\r
67# @retval List: The formatted hex list\r
68#\r
69def UniToHexList(Uni):\r
70 List = []\r
71 for Item in Uni:\r
72 Temp = '%04X' % ord(Item)\r
73 List.append('0x' + Temp[2:4])\r
74 List.append('0x' + Temp[0:2])\r
75 return List\r
76\r
77LangConvTable = {'eng':'en', 'fra':'fr', \\r
78 'aar':'aa', 'abk':'ab', 'ave':'ae', 'afr':'af', 'aka':'ak', 'amh':'am', \\r
79 'arg':'an', 'ara':'ar', 'asm':'as', 'ava':'av', 'aym':'ay', 'aze':'az', \\r
80 'bak':'ba', 'bel':'be', 'bul':'bg', 'bih':'bh', 'bis':'bi', 'bam':'bm', \\r
81 'ben':'bn', 'bod':'bo', 'bre':'br', 'bos':'bs', 'cat':'ca', 'che':'ce', \\r
82 'cha':'ch', 'cos':'co', 'cre':'cr', 'ces':'cs', 'chu':'cu', 'chv':'cv', \\r
83 'cym':'cy', 'dan':'da', 'deu':'de', 'div':'dv', 'dzo':'dz', 'ewe':'ee', \\r
84 'ell':'el', 'epo':'eo', 'spa':'es', 'est':'et', 'eus':'eu', 'fas':'fa', \\r
85 'ful':'ff', 'fin':'fi', 'fij':'fj', 'fao':'fo', 'fry':'fy', 'gle':'ga', \\r
86 'gla':'gd', 'glg':'gl', 'grn':'gn', 'guj':'gu', 'glv':'gv', 'hau':'ha', \\r
87 'heb':'he', 'hin':'hi', 'hmo':'ho', 'hrv':'hr', 'hat':'ht', 'hun':'hu', \\r
88 'hye':'hy', 'her':'hz', 'ina':'ia', 'ind':'id', 'ile':'ie', 'ibo':'ig', \\r
89 'iii':'ii', 'ipk':'ik', 'ido':'io', 'isl':'is', 'ita':'it', 'iku':'iu', \\r
90 'jpn':'ja', 'jav':'jv', 'kat':'ka', 'kon':'kg', 'kik':'ki', 'kua':'kj', \\r
91 'kaz':'kk', 'kal':'kl', 'khm':'km', 'kan':'kn', 'kor':'ko', 'kau':'kr', \\r
92 'kas':'ks', 'kur':'ku', 'kom':'kv', 'cor':'kw', 'kir':'ky', 'lat':'la', \\r
93 'ltz':'lb', 'lug':'lg', 'lim':'li', 'lin':'ln', 'lao':'lo', 'lit':'lt', \\r
94 'lub':'lu', 'lav':'lv', 'mlg':'mg', 'mah':'mh', 'mri':'mi', 'mkd':'mk', \\r
95 'mal':'ml', 'mon':'mn', 'mar':'mr', 'msa':'ms', 'mlt':'mt', 'mya':'my', \\r
96 'nau':'na', 'nob':'nb', 'nde':'nd', 'nep':'ne', 'ndo':'ng', 'nld':'nl', \\r
97 'nno':'nn', 'nor':'no', 'nbl':'nr', 'nav':'nv', 'nya':'ny', 'oci':'oc', \\r
98 'oji':'oj', 'orm':'om', 'ori':'or', 'oss':'os', 'pan':'pa', 'pli':'pi', \\r
99 'pol':'pl', 'pus':'ps', 'por':'pt', 'que':'qu', 'roh':'rm', 'run':'rn', \\r
100 'ron':'ro', 'rus':'ru', 'kin':'rw', 'san':'sa', 'srd':'sc', 'snd':'sd', \\r
101 'sme':'se', 'sag':'sg', 'sin':'si', 'slk':'sk', 'slv':'sl', 'smo':'sm', \\r
102 'sna':'sn', 'som':'so', 'sqi':'sq', 'srp':'sr', 'ssw':'ss', 'sot':'st', \\r
103 'sun':'su', 'swe':'sv', 'swa':'sw', 'tam':'ta', 'tel':'te', 'tgk':'tg', \\r
104 'tha':'th', 'tir':'ti', 'tuk':'tk', 'tgl':'tl', 'tsn':'tn', 'ton':'to', \\r
105 'tur':'tr', 'tso':'ts', 'tat':'tt', 'twi':'tw', 'tah':'ty', 'uig':'ug', \\r
106 'ukr':'uk', 'urd':'ur', 'uzb':'uz', 'ven':'ve', 'vie':'vi', 'vol':'vo', \\r
107 'wln':'wa', 'wol':'wo', 'xho':'xh', 'yid':'yi', 'yor':'yo', 'zha':'za', \\r
108 'zho':'zh', 'zul':'zu'}\r
109\r
110## GetLanguageCode\r
111#\r
112# Check the language code read from .UNI file and convert ISO 639-2 codes to RFC 4646 codes if appropriate\r
113# ISO 639-2 language codes supported in compatiblity mode\r
114# RFC 4646 language codes supported in native mode\r
115#\r
116# @param LangName: Language codes read from .UNI file\r
117#\r
118# @retval LangName: Valid lanugage code in RFC 4646 format or None\r
119#\r
120def GetLanguageCode(LangName, IsCompatibleMode, File):\r
121 global LangConvTable\r
122\r
123 length = len(LangName)\r
124 if IsCompatibleMode:\r
125 if length == 3 and LangName.isalpha():\r
126 TempLangName = LangConvTable.get(LangName.lower())\r
127 if TempLangName != None:\r
da92f276 128 return TempLangName\r
30fdf114
LG
129 return LangName\r
130 else:\r
131 EdkLogger.error("Unicode File Parser", FORMAT_INVALID, "Invalid ISO 639-2 language code : %s" % LangName, File)\r
132\r
40d841f6
LG
133 if (LangName[0] == 'X' or LangName[0] == 'x') and LangName[1] == '-':\r
134 return LangName\r
30fdf114
LG
135 if length == 2:\r
136 if LangName.isalpha():\r
137 return LangName\r
138 elif length == 3:\r
139 if LangName.isalpha() and LangConvTable.get(LangName.lower()) == None:\r
140 return LangName\r
141 elif length == 5:\r
142 if LangName[0:2].isalpha() and LangName[2] == '-':\r
143 return LangName\r
144 elif length >= 6:\r
145 if LangName[0:2].isalpha() and LangName[2] == '-':\r
146 return LangName\r
147 if LangName[0:3].isalpha() and LangConvTable.get(LangName.lower()) == None and LangName[3] == '-':\r
148 return LangName\r
149\r
150 EdkLogger.error("Unicode File Parser", FORMAT_INVALID, "Invalid RFC 4646 language code : %s" % LangName, File)\r
151\r
d80e451b
JJ
152## Ucs2Codec\r
153#\r
154# This is only a partial codec implementation. It only supports\r
155# encoding, and is primarily used to check that all the characters are\r
156# valid for UCS-2.\r
157#\r
158class Ucs2Codec(codecs.Codec):\r
159 def __init__(self):\r
160 self.__utf16 = codecs.lookup('utf-16')\r
161\r
162 def encode(self, input, errors='strict'):\r
163 for Char in input:\r
164 CodePoint = ord(Char)\r
165 if CodePoint >= 0xd800 and CodePoint <= 0xdfff:\r
166 raise ValueError("Code Point is in range reserved for " +\r
167 "UTF-16 surrogate pairs")\r
168 elif CodePoint > 0xffff:\r
169 raise ValueError("Code Point too large to encode in UCS-2")\r
170 return self.__utf16.encode(input)\r
171\r
172TheUcs2Codec = Ucs2Codec()\r
173def Ucs2Search(name):\r
174 if name == 'ucs-2':\r
175 return codecs.CodecInfo(\r
176 name=name,\r
177 encode=TheUcs2Codec.encode,\r
178 decode=TheUcs2Codec.decode)\r
179 else:\r
180 return None\r
181codecs.register(Ucs2Search)\r
182\r
30fdf114
LG
183## StringDefClassObject\r
184#\r
185# A structure for language definition\r
186#\r
187class StringDefClassObject(object):\r
188 def __init__(self, Name = None, Value = None, Referenced = False, Token = None, UseOtherLangDef = ''):\r
189 self.StringName = ''\r
190 self.StringNameByteList = []\r
191 self.StringValue = ''\r
192 self.StringValueByteList = ''\r
193 self.Token = 0\r
194 self.Referenced = Referenced\r
195 self.UseOtherLangDef = UseOtherLangDef\r
196 self.Length = 0\r
197\r
198 if Name != None:\r
199 self.StringName = Name\r
200 self.StringNameByteList = UniToHexList(Name)\r
201 if Value != None:\r
202 self.StringValue = Value + u'\x00' # Add a NULL at string tail\r
203 self.StringValueByteList = UniToHexList(self.StringValue)\r
204 self.Length = len(self.StringValueByteList)\r
205 if Token != None:\r
206 self.Token = Token\r
207\r
208 def __str__(self):\r
209 return repr(self.StringName) + ' ' + \\r
210 repr(self.Token) + ' ' + \\r
211 repr(self.Referenced) + ' ' + \\r
212 repr(self.StringValue) + ' ' + \\r
213 repr(self.UseOtherLangDef)\r
214\r
756ad8f8
LG
215 def UpdateValue(self, Value = None):\r
216 if Value != None:\r
217 self.StringValue = Value + u'\x00' # Add a NULL at string tail\r
218 self.StringValueByteList = UniToHexList(self.StringValue)\r
219 self.Length = len(self.StringValueByteList)\r
220\r
30fdf114
LG
221## UniFileClassObject\r
222#\r
223# A structure for .uni file definition\r
224#\r
225class UniFileClassObject(object):\r
756ad8f8 226 def __init__(self, FileList = [], IsCompatibleMode = False, IncludePathList = []):\r
30fdf114
LG
227 self.FileList = FileList\r
228 self.Token = 2\r
229 self.LanguageDef = [] #[ [u'LanguageIdentifier', u'PrintableName'], ... ]\r
230 self.OrderedStringList = {} #{ u'LanguageIdentifier' : [StringDefClassObject] }\r
79b74a03
LG
231 self.OrderedStringDict = {} #{ u'LanguageIdentifier' : {StringName:(IndexInList)} }\r
232 self.OrderedStringListByToken = {} #{ u'LanguageIdentifier' : {Token: StringDefClassObject} }\r
30fdf114 233 self.IsCompatibleMode = IsCompatibleMode\r
756ad8f8 234 self.IncludePathList = IncludePathList\r
30fdf114
LG
235 if len(self.FileList) > 0:\r
236 self.LoadUniFiles(FileList)\r
237\r
238 #\r
239 # Get Language definition\r
240 #\r
241 def GetLangDef(self, File, Line):\r
40d841f6 242 Lang = distutils.util.split_quoted((Line.split(u"//")[0]))\r
30fdf114
LG
243 if len(Lang) != 3:\r
244 try:\r
d80e451b 245 FileIn = self.OpenUniFile(LongFilePath(File.Path))\r
30fdf114
LG
246 except UnicodeError, X:\r
247 EdkLogger.error("build", FILE_READ_FAILURE, "File read failure: %s" % str(X), ExtraData=File);\r
248 except:\r
249 EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=File);\r
250 LineNo = GetLineNo(FileIn, Line, False)\r
251 EdkLogger.error("Unicode File Parser", PARSER_ERROR, "Wrong language definition",\r
47fea6af 252 ExtraData="""%s\n\t*Correct format is like '#langdef en-US "English"'""" % Line, File=File, Line=LineNo)\r
30fdf114
LG
253 else:\r
254 LangName = GetLanguageCode(Lang[1], self.IsCompatibleMode, self.File)\r
40d841f6 255 LangPrintName = Lang[2]\r
30fdf114
LG
256\r
257 IsLangInDef = False\r
258 for Item in self.LanguageDef:\r
259 if Item[0] == LangName:\r
260 IsLangInDef = True\r
261 break;\r
262\r
263 if not IsLangInDef:\r
264 self.LanguageDef.append([LangName, LangPrintName])\r
265\r
266 #\r
267 # Add language string\r
268 #\r
269 self.AddStringToList(u'$LANGUAGE_NAME', LangName, LangName, 0, True, Index=0)\r
270 self.AddStringToList(u'$PRINTABLE_LANGUAGE_NAME', LangName, LangPrintName, 1, True, Index=1)\r
271\r
756ad8f8
LG
272 if not IsLangInDef:\r
273 #\r
274 # The found STRING tokens will be added into new language string list\r
275 # so that the unique STRING identifier is reserved for all languages in the package list. \r
276 #\r
277 FirstLangName = self.LanguageDef[0][0]\r
278 if LangName != FirstLangName:\r
279 for Index in range (2, len (self.OrderedStringList[FirstLangName])):\r
280 Item = self.OrderedStringList[FirstLangName][Index]\r
281 if Item.UseOtherLangDef != '':\r
282 OtherLang = Item.UseOtherLangDef\r
283 else:\r
284 OtherLang = FirstLangName\r
285 self.OrderedStringList[LangName].append (StringDefClassObject(Item.StringName, '', Item.Referenced, Item.Token, OtherLang))\r
79b74a03 286 self.OrderedStringDict[LangName][Item.StringName] = len(self.OrderedStringList[LangName]) - 1\r
30fdf114
LG
287 return True\r
288\r
d80e451b
JJ
289 def OpenUniFile(self, FileName):\r
290 #\r
291 # Read file\r
292 #\r
293 try:\r
294 UniFile = open(FileName, mode='rb')\r
295 FileIn = UniFile.read()\r
296 UniFile.close()\r
297 except:\r
298 EdkLogger.Error("build", FILE_OPEN_FAILURE, ExtraData=File)\r
299\r
300 #\r
be264422 301 # Detect Byte Order Mark at beginning of file. Default to UTF-8\r
d80e451b 302 #\r
be264422
JJ
303 Encoding = 'utf-8'\r
304 if (FileIn.startswith(codecs.BOM_UTF16_BE) or\r
305 FileIn.startswith(codecs.BOM_UTF16_LE)):\r
306 Encoding = 'utf-16'\r
d80e451b
JJ
307\r
308 self.VerifyUcs2Data(FileIn, FileName, Encoding)\r
309\r
310 UniFile = StringIO.StringIO(FileIn)\r
311 Info = codecs.lookup(Encoding)\r
312 (Reader, Writer) = (Info.streamreader, Info.streamwriter)\r
313 return codecs.StreamReaderWriter(UniFile, Reader, Writer)\r
314\r
315 def VerifyUcs2Data(self, FileIn, FileName, Encoding):\r
316 Ucs2Info = codecs.lookup('ucs-2')\r
317 #\r
318 # Convert to unicode\r
319 #\r
320 try:\r
321 FileDecoded = codecs.decode(FileIn, Encoding)\r
322 Ucs2Info.encode(FileDecoded)\r
323 except:\r
324 UniFile = StringIO.StringIO(FileIn)\r
325 Info = codecs.lookup(Encoding)\r
326 (Reader, Writer) = (Info.streamreader, Info.streamwriter)\r
327 File = codecs.StreamReaderWriter(UniFile, Reader, Writer)\r
328 LineNumber = 0\r
329 ErrMsg = lambda Encoding, LineNumber: \\r
330 '%s contains invalid %s characters on line %d.' % \\r
331 (FileName, Encoding, LineNumber)\r
332 while True:\r
333 LineNumber = LineNumber + 1\r
334 try:\r
335 Line = File.readline()\r
336 if Line == '':\r
337 EdkLogger.error('Unicode File Parser', PARSER_ERROR,\r
338 ErrMsg(Encoding, LineNumber))\r
339 Ucs2Info.encode(Line)\r
340 except:\r
341 EdkLogger.error('Unicode File Parser', PARSER_ERROR,\r
342 ErrMsg('UCS-2', LineNumber))\r
343\r
30fdf114
LG
344 #\r
345 # Get String name and value\r
346 #\r
347 def GetStringObject(self, Item):\r
30fdf114
LG
348 Language = ''\r
349 Value = ''\r
350\r
351 Name = Item.split()[1]\r
c3915fa5 352 # Check the string name\r
2bcc713e 353 if Name != '':\r
c3915fa5 354 MatchString = re.match('^[a-zA-Z][a-zA-Z0-9_]*$', Name, re.UNICODE)\r
b303ea72 355 if MatchString == None or MatchString.end(0) != len(Name):\r
c3915fa5 356 EdkLogger.error('Unicode File Parser', FORMAT_INVALID, 'The string token name %s defined in UNI file %s contains the invalid character.' % (Name, self.File))\r
30fdf114
LG
357 LanguageList = Item.split(u'#language ')\r
358 for IndexI in range(len(LanguageList)):\r
359 if IndexI == 0:\r
360 continue\r
361 else:\r
362 Language = LanguageList[IndexI].split()[0]\r
363 Value = LanguageList[IndexI][LanguageList[IndexI].find(u'\"') + len(u'\"') : LanguageList[IndexI].rfind(u'\"')] #.replace(u'\r\n', u'')\r
364 Language = GetLanguageCode(Language, self.IsCompatibleMode, self.File)\r
365 self.AddStringToList(Name, Language, Value)\r
366\r
367 #\r
368 # Get include file list and load them\r
369 #\r
370 def GetIncludeFile(self, Item, Dir):\r
371 FileName = Item[Item.find(u'#include ') + len(u'#include ') :Item.find(u' ', len(u'#include '))][1:-1]\r
372 self.LoadUniFile(FileName)\r
373\r
71f02911
CS
374 def StripComments(self, Line):\r
375 Comment = u'//'\r
376 CommentPos = Line.find(Comment)\r
377 while CommentPos >= 0:\r
378 # if there are non matched quotes before the comment header\r
379 # then we are in the middle of a string\r
380 # but we need to ignore the escaped quotes and backslashes.\r
381 if ((Line.count(u'"', 0, CommentPos) - Line.count(u'\\"', 0, CommentPos)) & 1) == 1:\r
382 CommentPos = Line.find (Comment, CommentPos + 1)\r
383 else:\r
45265a86
YL
384 return Line[:CommentPos].strip()\r
385 return Line.strip()\r
71f02911
CS
386 \r
387\r
30fdf114
LG
388 #\r
389 # Pre-process before parse .uni file\r
390 #\r
391 def PreProcess(self, File):\r
392 if not os.path.exists(File.Path) or not os.path.isfile(File.Path):\r
393 EdkLogger.error("Unicode File Parser", FILE_NOT_FOUND, ExtraData=File.Path)\r
394\r
30fdf114 395 try:\r
d80e451b 396 FileIn = self.OpenUniFile(LongFilePath(File.Path))\r
30fdf114
LG
397 except UnicodeError, X:\r
398 EdkLogger.error("build", FILE_READ_FAILURE, "File read failure: %s" % str(X), ExtraData=File.Path);\r
399 except:\r
400 EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=File.Path);\r
401\r
402 Lines = []\r
403 #\r
404 # Use unique identifier\r
405 #\r
406 for Line in FileIn:\r
407 Line = Line.strip()\r
71f02911
CS
408 Line = Line.replace(u'\\\\', BACK_SLASH_PLACEHOLDER)\r
409 Line = self.StripComments(Line)\r
410\r
30fdf114 411 #\r
71f02911 412 # Ignore empty line\r
30fdf114 413 #\r
71f02911
CS
414 if len(Line) == 0: \r
415 continue \r
da92f276 416 \r
71f02911 417 \r
30fdf114
LG
418 Line = Line.replace(u'/langdef', u'#langdef')\r
419 Line = Line.replace(u'/string', u'#string')\r
420 Line = Line.replace(u'/language', u'#language')\r
421 Line = Line.replace(u'/include', u'#include')\r
422\r
423 Line = Line.replace(UNICODE_WIDE_CHAR, WIDE_CHAR)\r
424 Line = Line.replace(UNICODE_NARROW_CHAR, NARROW_CHAR)\r
425 Line = Line.replace(UNICODE_NON_BREAKING_CHAR, NON_BREAKING_CHAR)\r
426\r
30fdf114
LG
427 Line = Line.replace(u'\\r\\n', CR + LF)\r
428 Line = Line.replace(u'\\n', CR + LF)\r
429 Line = Line.replace(u'\\r', CR)\r
71f02911 430 Line = Line.replace(u'\\t', u' ')\r
8546dfea 431 Line = Line.replace(u'\t', u' ')\r
71f02911
CS
432 Line = Line.replace(u'\\"', u'"') \r
433 Line = Line.replace(u"\\'", u"'") \r
434 Line = Line.replace(BACK_SLASH_PLACEHOLDER, u'\\')\r
4afd3d04 435\r
314e2fb1
YZ
436 StartPos = Line.find(u'\\x')\r
437 while (StartPos != -1):\r
438 EndPos = Line.find(u'\\', StartPos + 1, StartPos + 7)\r
439 if EndPos != -1 and EndPos - StartPos == 6 :\r
018f7b82 440 if g4HexChar.match(Line[StartPos + 2 : EndPos], re.UNICODE):\r
314e2fb1
YZ
441 EndStr = Line[EndPos: ]\r
442 UniStr = ('\u' + (Line[StartPos + 2 : EndPos])).decode('unicode_escape')\r
443 if EndStr.startswith(u'\\x') and len(EndStr) >= 7:\r
018f7b82 444 if EndStr[6] == u'\\' and g4HexChar.match(EndStr[2 : 6], re.UNICODE):\r
314e2fb1
YZ
445 Line = Line[0 : StartPos] + UniStr + EndStr\r
446 else:\r
447 Line = Line[0 : StartPos] + UniStr + EndStr[1:]\r
ad319b93 448 StartPos = Line.find(u'\\x', StartPos + 1)\r
30fdf114
LG
449\r
450 IncList = gIncludePattern.findall(Line)\r
451 if len(IncList) == 1:\r
756ad8f8
LG
452 for Dir in [File.Dir] + self.IncludePathList:\r
453 IncFile = PathClass(str(IncList[0]), Dir)\r
454 if os.path.isfile(IncFile.Path):\r
455 Lines.extend(self.PreProcess(IncFile))\r
456 break\r
457 else:\r
458 EdkLogger.error("Unicode File Parser", FILE_NOT_FOUND, Message="Cannot find include file", ExtraData=str(IncList[0]))\r
30fdf114
LG
459 continue\r
460\r
461 Lines.append(Line)\r
462\r
463 return Lines\r
464\r
465 #\r
466 # Load a .uni file\r
467 #\r
468 def LoadUniFile(self, File = None):\r
469 if File == None:\r
470 EdkLogger.error("Unicode File Parser", PARSER_ERROR, 'No unicode file is given')\r
471 self.File = File\r
472 #\r
473 # Process special char in file\r
474 #\r
475 Lines = self.PreProcess(File)\r
476\r
477 #\r
478 # Get Unicode Information\r
479 #\r
480 for IndexI in range(len(Lines)):\r
481 Line = Lines[IndexI]\r
482 if (IndexI + 1) < len(Lines):\r
483 SecondLine = Lines[IndexI + 1]\r
484 if (IndexI + 2) < len(Lines):\r
485 ThirdLine = Lines[IndexI + 2]\r
486\r
487 #\r
488 # Get Language def information\r
489 #\r
490 if Line.find(u'#langdef ') >= 0:\r
491 self.GetLangDef(File, Line)\r
492 continue\r
493\r
494 Name = ''\r
495 Language = ''\r
496 Value = ''\r
497 #\r
498 # Get string def information format 1 as below\r
499 #\r
500 # #string MY_STRING_1\r
501 # #language eng\r
502 # My first English string line 1\r
503 # My first English string line 2\r
504 # #string MY_STRING_1\r
505 # #language spa\r
506 # Mi segunda secuencia 1\r
507 # Mi segunda secuencia 2\r
508 #\r
509 if Line.find(u'#string ') >= 0 and Line.find(u'#language ') < 0 and \\r
510 SecondLine.find(u'#string ') < 0 and SecondLine.find(u'#language ') >= 0 and \\r
511 ThirdLine.find(u'#string ') < 0 and ThirdLine.find(u'#language ') < 0:\r
512 Name = Line[Line.find(u'#string ') + len(u'#string ') : ].strip(' ')\r
513 Language = SecondLine[SecondLine.find(u'#language ') + len(u'#language ') : ].strip(' ')\r
514 for IndexJ in range(IndexI + 2, len(Lines)):\r
515 if Lines[IndexJ].find(u'#string ') < 0 and Lines[IndexJ].find(u'#language ') < 0:\r
516 Value = Value + Lines[IndexJ]\r
517 else:\r
518 IndexI = IndexJ\r
519 break\r
520 # Value = Value.replace(u'\r\n', u'')\r
521 Language = GetLanguageCode(Language, self.IsCompatibleMode, self.File)\r
c3915fa5 522 # Check the string name\r
b303ea72 523 if not self.IsCompatibleMode and Name != '':\r
c3915fa5 524 MatchString = re.match('^[a-zA-Z][a-zA-Z0-9_]*$', Name, re.UNICODE)\r
b303ea72 525 if MatchString == None or MatchString.end(0) != len(Name):\r
c3915fa5 526 EdkLogger.error('Unicode File Parser', FORMAT_INVALID, 'The string token name %s defined in UNI file %s contains the invalid character.' % (Name, self.File))\r
30fdf114
LG
527 self.AddStringToList(Name, Language, Value)\r
528 continue\r
529\r
530 #\r
531 # Get string def information format 2 as below\r
532 #\r
533 # #string MY_STRING_1 #language eng "My first English string line 1"\r
534 # "My first English string line 2"\r
535 # #language spa "Mi segunda secuencia 1"\r
536 # "Mi segunda secuencia 2"\r
537 # #string MY_STRING_2 #language eng "My first English string line 1"\r
538 # "My first English string line 2"\r
539 # #string MY_STRING_2 #language spa "Mi segunda secuencia 1"\r
540 # "Mi segunda secuencia 2"\r
541 #\r
542 if Line.find(u'#string ') >= 0 and Line.find(u'#language ') >= 0:\r
543 StringItem = Line\r
544 for IndexJ in range(IndexI + 1, len(Lines)):\r
545 if Lines[IndexJ].find(u'#string ') >= 0 and Lines[IndexJ].find(u'#language ') >= 0:\r
546 IndexI = IndexJ\r
547 break\r
548 elif Lines[IndexJ].find(u'#string ') < 0 and Lines[IndexJ].find(u'#language ') >= 0:\r
549 StringItem = StringItem + Lines[IndexJ]\r
550 elif Lines[IndexJ].count(u'\"') >= 2:\r
551 StringItem = StringItem[ : StringItem.rfind(u'\"')] + Lines[IndexJ][Lines[IndexJ].find(u'\"') + len(u'\"') : ]\r
552 self.GetStringObject(StringItem)\r
553 continue\r
554\r
555 #\r
556 # Load multiple .uni files\r
557 #\r
52302d4d 558 def LoadUniFiles(self, FileList):\r
30fdf114 559 if len(FileList) > 0:\r
52302d4d
LG
560 for File in FileList:\r
561 self.LoadUniFile(File)\r
30fdf114
LG
562\r
563 #\r
564 # Add a string to list\r
565 #\r
566 def AddStringToList(self, Name, Language, Value, Token = None, Referenced = False, UseOtherLangDef = '', Index = -1):\r
08dd311f
LG
567 for LangNameItem in self.LanguageDef:\r
568 if Language == LangNameItem[0]:\r
569 break\r
570 else:\r
571 EdkLogger.error('Unicode File Parser', FORMAT_NOT_SUPPORTED, "The language '%s' for %s is not defined in Unicode file %s." \\r
572 % (Language, Name, self.File))\r
573 \r
30fdf114
LG
574 if Language not in self.OrderedStringList:\r
575 self.OrderedStringList[Language] = []\r
79b74a03 576 self.OrderedStringDict[Language] = {}\r
30fdf114 577\r
756ad8f8 578 IsAdded = True\r
79b74a03
LG
579 if Name in self.OrderedStringDict[Language]:\r
580 IsAdded = False\r
581 if Value != None:\r
582 ItemIndexInList = self.OrderedStringDict[Language][Name]\r
583 Item = self.OrderedStringList[Language][ItemIndexInList]\r
584 Item.UpdateValue(Value)\r
47fea6af 585 Item.UseOtherLangDef = ''\r
756ad8f8
LG
586\r
587 if IsAdded:\r
30fdf114
LG
588 Token = len(self.OrderedStringList[Language])\r
589 if Index == -1:\r
590 self.OrderedStringList[Language].append(StringDefClassObject(Name, Value, Referenced, Token, UseOtherLangDef))\r
79b74a03 591 self.OrderedStringDict[Language][Name] = Token\r
756ad8f8
LG
592 for LangName in self.LanguageDef:\r
593 #\r
594 # New STRING token will be added into all language string lists.\r
595 # so that the unique STRING identifier is reserved for all languages in the package list. \r
596 #\r
597 if LangName[0] != Language:\r
598 if UseOtherLangDef != '':\r
599 OtherLangDef = UseOtherLangDef\r
600 else:\r
601 OtherLangDef = Language\r
602 self.OrderedStringList[LangName[0]].append(StringDefClassObject(Name, '', Referenced, Token, OtherLangDef))\r
79b74a03 603 self.OrderedStringDict[LangName[0]][Name] = len(self.OrderedStringList[LangName[0]]) - 1\r
30fdf114
LG
604 else:\r
605 self.OrderedStringList[Language].insert(Index, StringDefClassObject(Name, Value, Referenced, Token, UseOtherLangDef))\r
79b74a03 606 self.OrderedStringDict[Language][Name] = Index\r
30fdf114
LG
607\r
608 #\r
609 # Set the string as referenced\r
610 #\r
611 def SetStringReferenced(self, Name):\r
756ad8f8
LG
612 #\r
613 # String stoken are added in the same order in all language string lists.\r
614 # So, only update the status of string stoken in first language string list.\r
615 #\r
616 Lang = self.LanguageDef[0][0]\r
79b74a03
LG
617 if Name in self.OrderedStringDict[Lang]:\r
618 ItemIndexInList = self.OrderedStringDict[Lang][Name]\r
619 Item = self.OrderedStringList[Lang][ItemIndexInList]\r
620 Item.Referenced = True\r
621\r
30fdf114
LG
622 #\r
623 # Search the string in language definition by Name\r
624 #\r
625 def FindStringValue(self, Name, Lang):\r
79b74a03
LG
626 if Name in self.OrderedStringDict[Lang]:\r
627 ItemIndexInList = self.OrderedStringDict[Lang][Name]\r
628 return self.OrderedStringList[Lang][ItemIndexInList]\r
30fdf114
LG
629\r
630 return None\r
631\r
632 #\r
633 # Search the string in language definition by Token\r
634 #\r
635 def FindByToken(self, Token, Lang):\r
636 for Item in self.OrderedStringList[Lang]:\r
637 if Item.Token == Token:\r
638 return Item\r
639\r
640 return None\r
641\r
642 #\r
643 # Re-order strings and re-generate tokens\r
644 #\r
645 def ReToken(self):\r
646 #\r
756ad8f8 647 # Retoken all language strings according to the status of string stoken in the first language string.\r
30fdf114 648 #\r
756ad8f8 649 FirstLangName = self.LanguageDef[0][0]\r
52302d4d 650\r
79b74a03
LG
651 # Convert the OrderedStringList to be OrderedStringListByToken in order to faciliate future search by token\r
652 for LangNameItem in self.LanguageDef:\r
653 self.OrderedStringListByToken[LangNameItem[0]] = {}\r
654\r
52302d4d 655 #\r
756ad8f8 656 # Use small token for all referred string stoken.\r
52302d4d 657 #\r
756ad8f8
LG
658 RefToken = 0\r
659 for Index in range (0, len (self.OrderedStringList[FirstLangName])):\r
660 FirstLangItem = self.OrderedStringList[FirstLangName][Index]\r
661 if FirstLangItem.Referenced == True:\r
662 for LangNameItem in self.LanguageDef:\r
663 LangName = LangNameItem[0]\r
664 OtherLangItem = self.OrderedStringList[LangName][Index]\r
665 OtherLangItem.Referenced = True\r
666 OtherLangItem.Token = RefToken\r
79b74a03 667 self.OrderedStringListByToken[LangName][OtherLangItem.Token] = OtherLangItem\r
756ad8f8 668 RefToken = RefToken + 1\r
30fdf114
LG
669\r
670 #\r
756ad8f8 671 # Use big token for all unreferred string stoken.\r
30fdf114 672 #\r
756ad8f8
LG
673 UnRefToken = 0\r
674 for Index in range (0, len (self.OrderedStringList[FirstLangName])):\r
675 FirstLangItem = self.OrderedStringList[FirstLangName][Index]\r
676 if FirstLangItem.Referenced == False:\r
677 for LangNameItem in self.LanguageDef:\r
678 LangName = LangNameItem[0]\r
679 OtherLangItem = self.OrderedStringList[LangName][Index]\r
680 OtherLangItem.Token = RefToken + UnRefToken\r
79b74a03 681 self.OrderedStringListByToken[LangName][OtherLangItem.Token] = OtherLangItem\r
756ad8f8 682 UnRefToken = UnRefToken + 1\r
30fdf114
LG
683\r
684 #\r
685 # Show the instance itself\r
686 #\r
687 def ShowMe(self):\r
688 print self.LanguageDef\r
689 #print self.OrderedStringList\r
690 for Item in self.OrderedStringList:\r
691 print Item\r
692 for Member in self.OrderedStringList[Item]:\r
693 print str(Member)\r
694\r
695# This acts like the main() function for the script, unless it is 'import'ed into another\r
696# script.\r
697if __name__ == '__main__':\r
698 EdkLogger.Initialize()\r
699 EdkLogger.SetLevel(EdkLogger.DEBUG_0)\r
da92f276 700 a = UniFileClassObject([PathClass("C:\\Edk\\Strings.uni"), PathClass("C:\\Edk\\Strings2.uni")])\r
30fdf114
LG
701 a.ReToken()\r
702 a.ShowMe()\r