]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/AutoGen/UniClassObject.py
Sync EDKII BaseTools to BaseTools project r1971
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / UniClassObject.py
1 # Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
2 # This program and the accompanying materials
3 # are licensed and made available under the terms and conditions of the BSD License
4 # which accompanies this distribution. The full text of the license may be found at
5 # http://opensource.org/licenses/bsd-license.php
6 #
7 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
8 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
9
10 #
11 #This file is used to collect all defined strings in multiple uni files
12 #
13
14 ##
15 # Import Modules
16 #
17 import os, codecs, re
18 import distutils.util
19 import Common.EdkLogger as EdkLogger
20 from Common.BuildToolError import *
21 from Common.String import GetLineNo
22 from Common.Misc import PathClass
23
24 ##
25 # Static definitions
26 #
27 UNICODE_WIDE_CHAR = u'\\wide'
28 UNICODE_NARROW_CHAR = u'\\narrow'
29 UNICODE_NON_BREAKING_CHAR = u'\\nbr'
30 UNICODE_UNICODE_CR = '\r'
31 UNICODE_UNICODE_LF = '\n'
32
33 NARROW_CHAR = u'\uFFF0'
34 WIDE_CHAR = u'\uFFF1'
35 NON_BREAKING_CHAR = u'\uFFF2'
36 CR = u'\u000D'
37 LF = u'\u000A'
38 NULL = u'\u0000'
39 TAB = u'\t'
40 BACK_SPLASH = u'\\'
41
42 gIncludePattern = re.compile("^#include +[\"<]+([^\"< >]+)[>\"]+$", re.MULTILINE | re.UNICODE)
43
44 ## Convert a python unicode string to a normal string
45 #
46 # Convert a python unicode string to a normal string
47 # UniToStr(u'I am a string') is 'I am a string'
48 #
49 # @param Uni: The python unicode string
50 #
51 # @retval: The formatted normal string
52 #
53 def UniToStr(Uni):
54 return repr(Uni)[2:-1]
55
56 ## Convert a unicode string to a Hex list
57 #
58 # Convert a unicode string to a Hex list
59 # UniToHexList('ABC') is ['0x41', '0x00', '0x42', '0x00', '0x43', '0x00']
60 #
61 # @param Uni: The python unicode string
62 #
63 # @retval List: The formatted hex list
64 #
65 def UniToHexList(Uni):
66 List = []
67 for Item in Uni:
68 Temp = '%04X' % ord(Item)
69 List.append('0x' + Temp[2:4])
70 List.append('0x' + Temp[0:2])
71 return List
72
73 LangConvTable = {'eng':'en', 'fra':'fr', \
74 'aar':'aa', 'abk':'ab', 'ave':'ae', 'afr':'af', 'aka':'ak', 'amh':'am', \
75 'arg':'an', 'ara':'ar', 'asm':'as', 'ava':'av', 'aym':'ay', 'aze':'az', \
76 'bak':'ba', 'bel':'be', 'bul':'bg', 'bih':'bh', 'bis':'bi', 'bam':'bm', \
77 'ben':'bn', 'bod':'bo', 'bre':'br', 'bos':'bs', 'cat':'ca', 'che':'ce', \
78 'cha':'ch', 'cos':'co', 'cre':'cr', 'ces':'cs', 'chu':'cu', 'chv':'cv', \
79 'cym':'cy', 'dan':'da', 'deu':'de', 'div':'dv', 'dzo':'dz', 'ewe':'ee', \
80 'ell':'el', 'epo':'eo', 'spa':'es', 'est':'et', 'eus':'eu', 'fas':'fa', \
81 'ful':'ff', 'fin':'fi', 'fij':'fj', 'fao':'fo', 'fry':'fy', 'gle':'ga', \
82 'gla':'gd', 'glg':'gl', 'grn':'gn', 'guj':'gu', 'glv':'gv', 'hau':'ha', \
83 'heb':'he', 'hin':'hi', 'hmo':'ho', 'hrv':'hr', 'hat':'ht', 'hun':'hu', \
84 'hye':'hy', 'her':'hz', 'ina':'ia', 'ind':'id', 'ile':'ie', 'ibo':'ig', \
85 'iii':'ii', 'ipk':'ik', 'ido':'io', 'isl':'is', 'ita':'it', 'iku':'iu', \
86 'jpn':'ja', 'jav':'jv', 'kat':'ka', 'kon':'kg', 'kik':'ki', 'kua':'kj', \
87 'kaz':'kk', 'kal':'kl', 'khm':'km', 'kan':'kn', 'kor':'ko', 'kau':'kr', \
88 'kas':'ks', 'kur':'ku', 'kom':'kv', 'cor':'kw', 'kir':'ky', 'lat':'la', \
89 'ltz':'lb', 'lug':'lg', 'lim':'li', 'lin':'ln', 'lao':'lo', 'lit':'lt', \
90 'lub':'lu', 'lav':'lv', 'mlg':'mg', 'mah':'mh', 'mri':'mi', 'mkd':'mk', \
91 'mal':'ml', 'mon':'mn', 'mar':'mr', 'msa':'ms', 'mlt':'mt', 'mya':'my', \
92 'nau':'na', 'nob':'nb', 'nde':'nd', 'nep':'ne', 'ndo':'ng', 'nld':'nl', \
93 'nno':'nn', 'nor':'no', 'nbl':'nr', 'nav':'nv', 'nya':'ny', 'oci':'oc', \
94 'oji':'oj', 'orm':'om', 'ori':'or', 'oss':'os', 'pan':'pa', 'pli':'pi', \
95 'pol':'pl', 'pus':'ps', 'por':'pt', 'que':'qu', 'roh':'rm', 'run':'rn', \
96 'ron':'ro', 'rus':'ru', 'kin':'rw', 'san':'sa', 'srd':'sc', 'snd':'sd', \
97 'sme':'se', 'sag':'sg', 'sin':'si', 'slk':'sk', 'slv':'sl', 'smo':'sm', \
98 'sna':'sn', 'som':'so', 'sqi':'sq', 'srp':'sr', 'ssw':'ss', 'sot':'st', \
99 'sun':'su', 'swe':'sv', 'swa':'sw', 'tam':'ta', 'tel':'te', 'tgk':'tg', \
100 'tha':'th', 'tir':'ti', 'tuk':'tk', 'tgl':'tl', 'tsn':'tn', 'ton':'to', \
101 'tur':'tr', 'tso':'ts', 'tat':'tt', 'twi':'tw', 'tah':'ty', 'uig':'ug', \
102 'ukr':'uk', 'urd':'ur', 'uzb':'uz', 'ven':'ve', 'vie':'vi', 'vol':'vo', \
103 'wln':'wa', 'wol':'wo', 'xho':'xh', 'yid':'yi', 'yor':'yo', 'zha':'za', \
104 'zho':'zh', 'zul':'zu'}
105
106 ## GetLanguageCode
107 #
108 # Check the language code read from .UNI file and convert ISO 639-2 codes to RFC 4646 codes if appropriate
109 # ISO 639-2 language codes supported in compatiblity mode
110 # RFC 4646 language codes supported in native mode
111 #
112 # @param LangName: Language codes read from .UNI file
113 #
114 # @retval LangName: Valid lanugage code in RFC 4646 format or None
115 #
116 def GetLanguageCode(LangName, IsCompatibleMode, File):
117 global LangConvTable
118
119 length = len(LangName)
120 if IsCompatibleMode:
121 if length == 3 and LangName.isalpha():
122 TempLangName = LangConvTable.get(LangName.lower())
123 if TempLangName != None:
124 return TempLangName
125 return LangName
126 else:
127 EdkLogger.error("Unicode File Parser", FORMAT_INVALID, "Invalid ISO 639-2 language code : %s" % LangName, File)
128
129 if (LangName[0] == 'X' or LangName[0] == 'x') and LangName[1] == '-':
130 return LangName
131 if length == 2:
132 if LangName.isalpha():
133 return LangName
134 elif length == 3:
135 if LangName.isalpha() and LangConvTable.get(LangName.lower()) == None:
136 return LangName
137 elif length == 5:
138 if LangName[0:2].isalpha() and LangName[2] == '-':
139 return LangName
140 elif length >= 6:
141 if LangName[0:2].isalpha() and LangName[2] == '-':
142 return LangName
143 if LangName[0:3].isalpha() and LangConvTable.get(LangName.lower()) == None and LangName[3] == '-':
144 return LangName
145
146 EdkLogger.error("Unicode File Parser", FORMAT_INVALID, "Invalid RFC 4646 language code : %s" % LangName, File)
147
148 ## StringDefClassObject
149 #
150 # A structure for language definition
151 #
152 class StringDefClassObject(object):
153 def __init__(self, Name = None, Value = None, Referenced = False, Token = None, UseOtherLangDef = ''):
154 self.StringName = ''
155 self.StringNameByteList = []
156 self.StringValue = ''
157 self.StringValueByteList = ''
158 self.Token = 0
159 self.Referenced = Referenced
160 self.UseOtherLangDef = UseOtherLangDef
161 self.Length = 0
162
163 if Name != None:
164 self.StringName = Name
165 self.StringNameByteList = UniToHexList(Name)
166 if Value != None:
167 self.StringValue = Value + u'\x00' # Add a NULL at string tail
168 self.StringValueByteList = UniToHexList(self.StringValue)
169 self.Length = len(self.StringValueByteList)
170 if Token != None:
171 self.Token = Token
172
173 def __str__(self):
174 return repr(self.StringName) + ' ' + \
175 repr(self.Token) + ' ' + \
176 repr(self.Referenced) + ' ' + \
177 repr(self.StringValue) + ' ' + \
178 repr(self.UseOtherLangDef)
179
180 ## UniFileClassObject
181 #
182 # A structure for .uni file definition
183 #
184 class UniFileClassObject(object):
185 def __init__(self, FileList = [], IsCompatibleMode = False):
186 self.FileList = FileList
187 self.Token = 2
188 self.LanguageDef = [] #[ [u'LanguageIdentifier', u'PrintableName'], ... ]
189 self.OrderedStringList = {} #{ u'LanguageIdentifier' : [StringDefClassObject] }
190 self.IsCompatibleMode = IsCompatibleMode
191
192 if len(self.FileList) > 0:
193 self.LoadUniFiles(FileList)
194
195 #
196 # Get Language definition
197 #
198 def GetLangDef(self, File, Line):
199 Lang = distutils.util.split_quoted((Line.split(u"//")[0]))
200 if len(Lang) != 3:
201 try:
202 FileIn = codecs.open(File.Path, mode='rb', encoding='utf-16').read()
203 except UnicodeError, X:
204 EdkLogger.error("build", FILE_READ_FAILURE, "File read failure: %s" % str(X), ExtraData=File);
205 except:
206 EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=File);
207 LineNo = GetLineNo(FileIn, Line, False)
208 EdkLogger.error("Unicode File Parser", PARSER_ERROR, "Wrong language definition",
209 ExtraData="""%s\n\t*Correct format is like '#langdef en-US "English"'""" % Line, File = File, Line = LineNo)
210 else:
211 LangName = GetLanguageCode(Lang[1], self.IsCompatibleMode, self.File)
212 LangPrintName = Lang[2]
213
214 IsLangInDef = False
215 for Item in self.LanguageDef:
216 if Item[0] == LangName:
217 IsLangInDef = True
218 break;
219
220 if not IsLangInDef:
221 self.LanguageDef.append([LangName, LangPrintName])
222
223 #
224 # Add language string
225 #
226 self.AddStringToList(u'$LANGUAGE_NAME', LangName, LangName, 0, True, Index=0)
227 self.AddStringToList(u'$PRINTABLE_LANGUAGE_NAME', LangName, LangPrintName, 1, True, Index=1)
228
229 return True
230
231 #
232 # Get String name and value
233 #
234 def GetStringObject(self, Item):
235 Name = ''
236 Language = ''
237 Value = ''
238
239 Name = Item.split()[1]
240 # Check the string name is the upper character
241 if not self.IsCompatibleMode and Name != '':
242 MatchString = re.match('[A-Z0-9_]+', Name, re.UNICODE)
243 if MatchString == None or MatchString.end(0) != len(Name):
244 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))
245 LanguageList = Item.split(u'#language ')
246 for IndexI in range(len(LanguageList)):
247 if IndexI == 0:
248 continue
249 else:
250 Language = LanguageList[IndexI].split()[0]
251 Value = LanguageList[IndexI][LanguageList[IndexI].find(u'\"') + len(u'\"') : LanguageList[IndexI].rfind(u'\"')] #.replace(u'\r\n', u'')
252 Language = GetLanguageCode(Language, self.IsCompatibleMode, self.File)
253 self.AddStringToList(Name, Language, Value)
254
255 #
256 # Get include file list and load them
257 #
258 def GetIncludeFile(self, Item, Dir):
259 FileName = Item[Item.find(u'#include ') + len(u'#include ') :Item.find(u' ', len(u'#include '))][1:-1]
260 self.LoadUniFile(FileName)
261
262 #
263 # Pre-process before parse .uni file
264 #
265 def PreProcess(self, File):
266 if not os.path.exists(File.Path) or not os.path.isfile(File.Path):
267 EdkLogger.error("Unicode File Parser", FILE_NOT_FOUND, ExtraData=File.Path)
268
269 Dir = File.Dir
270 try:
271 FileIn = codecs.open(File.Path, mode='rb', encoding='utf-16').readlines()
272 except UnicodeError, X:
273 EdkLogger.error("build", FILE_READ_FAILURE, "File read failure: %s" % str(X), ExtraData=File.Path);
274 except:
275 EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=File.Path);
276
277 Lines = []
278 #
279 # Use unique identifier
280 #
281 for Line in FileIn:
282 Line = Line.strip()
283 #
284 # Ignore comment line and empty line
285 #
286 if Line == u'' or Line.startswith(u'//'):
287 continue
288 Line = Line.replace(u'/langdef', u'#langdef')
289 Line = Line.replace(u'/string', u'#string')
290 Line = Line.replace(u'/language', u'#language')
291 Line = Line.replace(u'/include', u'#include')
292
293 Line = Line.replace(UNICODE_WIDE_CHAR, WIDE_CHAR)
294 Line = Line.replace(UNICODE_NARROW_CHAR, NARROW_CHAR)
295 Line = Line.replace(UNICODE_NON_BREAKING_CHAR, NON_BREAKING_CHAR)
296
297 Line = Line.replace(u'\\\\', u'\u0006')
298 Line = Line.replace(u'\\r\\n', CR + LF)
299 Line = Line.replace(u'\\n', CR + LF)
300 Line = Line.replace(u'\\r', CR)
301 Line = Line.replace(u'\\t', u'\t')
302 Line = Line.replace(u'''\"''', u'''"''')
303 Line = Line.replace(u'\t', u' ')
304 Line = Line.replace(u'\u0006', u'\\')
305
306 # if Line.find(u'\\x'):
307 # hex = Line[Line.find(u'\\x') + 2 : Line.find(u'\\x') + 6]
308 # hex = "u'\\u" + hex + "'"
309
310 IncList = gIncludePattern.findall(Line)
311 if len(IncList) == 1:
312 Lines.extend(self.PreProcess(PathClass(str(IncList[0]), Dir)))
313 continue
314
315 Lines.append(Line)
316
317 return Lines
318
319 #
320 # Load a .uni file
321 #
322 def LoadUniFile(self, File = None):
323 if File == None:
324 EdkLogger.error("Unicode File Parser", PARSER_ERROR, 'No unicode file is given')
325 self.File = File
326 #
327 # Process special char in file
328 #
329 Lines = self.PreProcess(File)
330
331 #
332 # Get Unicode Information
333 #
334 for IndexI in range(len(Lines)):
335 Line = Lines[IndexI]
336 if (IndexI + 1) < len(Lines):
337 SecondLine = Lines[IndexI + 1]
338 if (IndexI + 2) < len(Lines):
339 ThirdLine = Lines[IndexI + 2]
340
341 #
342 # Get Language def information
343 #
344 if Line.find(u'#langdef ') >= 0:
345 self.GetLangDef(File, Line)
346 continue
347
348 Name = ''
349 Language = ''
350 Value = ''
351 #
352 # Get string def information format 1 as below
353 #
354 # #string MY_STRING_1
355 # #language eng
356 # My first English string line 1
357 # My first English string line 2
358 # #string MY_STRING_1
359 # #language spa
360 # Mi segunda secuencia 1
361 # Mi segunda secuencia 2
362 #
363 if Line.find(u'#string ') >= 0 and Line.find(u'#language ') < 0 and \
364 SecondLine.find(u'#string ') < 0 and SecondLine.find(u'#language ') >= 0 and \
365 ThirdLine.find(u'#string ') < 0 and ThirdLine.find(u'#language ') < 0:
366 Name = Line[Line.find(u'#string ') + len(u'#string ') : ].strip(' ')
367 Language = SecondLine[SecondLine.find(u'#language ') + len(u'#language ') : ].strip(' ')
368 for IndexJ in range(IndexI + 2, len(Lines)):
369 if Lines[IndexJ].find(u'#string ') < 0 and Lines[IndexJ].find(u'#language ') < 0:
370 Value = Value + Lines[IndexJ]
371 else:
372 IndexI = IndexJ
373 break
374 # Value = Value.replace(u'\r\n', u'')
375 Language = GetLanguageCode(Language, self.IsCompatibleMode, self.File)
376 # Check the string name is the upper character
377 if not self.IsCompatibleMode and Name != '':
378 MatchString = re.match('[A-Z0-9_]+', Name, re.UNICODE)
379 if MatchString == None or MatchString.end(0) != len(Name):
380 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))
381 self.AddStringToList(Name, Language, Value)
382 continue
383
384 #
385 # Get string def information format 2 as below
386 #
387 # #string MY_STRING_1 #language eng "My first English string line 1"
388 # "My first English string line 2"
389 # #language spa "Mi segunda secuencia 1"
390 # "Mi segunda secuencia 2"
391 # #string MY_STRING_2 #language eng "My first English string line 1"
392 # "My first English string line 2"
393 # #string MY_STRING_2 #language spa "Mi segunda secuencia 1"
394 # "Mi segunda secuencia 2"
395 #
396 if Line.find(u'#string ') >= 0 and Line.find(u'#language ') >= 0:
397 StringItem = Line
398 for IndexJ in range(IndexI + 1, len(Lines)):
399 if Lines[IndexJ].find(u'#string ') >= 0 and Lines[IndexJ].find(u'#language ') >= 0:
400 IndexI = IndexJ
401 break
402 elif Lines[IndexJ].find(u'#string ') < 0 and Lines[IndexJ].find(u'#language ') >= 0:
403 StringItem = StringItem + Lines[IndexJ]
404 elif Lines[IndexJ].count(u'\"') >= 2:
405 StringItem = StringItem[ : StringItem.rfind(u'\"')] + Lines[IndexJ][Lines[IndexJ].find(u'\"') + len(u'\"') : ]
406 self.GetStringObject(StringItem)
407 continue
408
409 #
410 # Load multiple .uni files
411 #
412 def LoadUniFiles(self, FileList):
413 if len(FileList) > 0:
414 for File in FileList:
415 self.LoadUniFile(File)
416
417 #
418 # Add a string to list
419 #
420 def AddStringToList(self, Name, Language, Value, Token = None, Referenced = False, UseOtherLangDef = '', Index = -1):
421 if Language not in self.OrderedStringList:
422 self.OrderedStringList[Language] = []
423
424 IsAdded = False
425 for Item in self.OrderedStringList[Language]:
426 if Name == Item.StringName:
427 IsAdded = True
428 break
429 if not IsAdded:
430 Token = len(self.OrderedStringList[Language])
431 if Index == -1:
432 self.OrderedStringList[Language].append(StringDefClassObject(Name, Value, Referenced, Token, UseOtherLangDef))
433 else:
434 self.OrderedStringList[Language].insert(Index, StringDefClassObject(Name, Value, Referenced, Token, UseOtherLangDef))
435
436 #
437 # Set the string as referenced
438 #
439 def SetStringReferenced(self, Name):
440 for Lang in self.OrderedStringList:
441 for Item in self.OrderedStringList[Lang]:
442 if Name == Item.StringName:
443 Item.Referenced = True
444 break
445 #
446 # Search the string in language definition by Name
447 #
448 def FindStringValue(self, Name, Lang):
449 for Item in self.OrderedStringList[Lang]:
450 if Item.StringName == Name:
451 return Item
452
453 return None
454
455 #
456 # Search the string in language definition by Token
457 #
458 def FindByToken(self, Token, Lang):
459 for Item in self.OrderedStringList[Lang]:
460 if Item.Token == Token:
461 return Item
462
463 return None
464
465 #
466 # Re-order strings and re-generate tokens
467 #
468 def ReToken(self):
469 #
470 # Search each string to find if it is defined for each language
471 # Use secondary language value to replace if missing in any one language
472 #
473 for IndexI in range(0, len(self.LanguageDef)):
474 LangKey = self.LanguageDef[IndexI][0]
475 for Item in self.OrderedStringList[LangKey]:
476 Name = Item.StringName
477 Value = Item.StringValue[0:-1]
478 Referenced = Item.Referenced
479 Index = self.OrderedStringList[LangKey].index(Item)
480 for IndexJ in range(0, len(self.LanguageDef)):
481 LangFind = self.LanguageDef[IndexJ][0]
482 if self.FindStringValue(Name, LangFind) == None:
483 EdkLogger.debug(EdkLogger.DEBUG_5, Name)
484 Token = len(self.OrderedStringList[LangFind])
485 self.AddStringToList(Name, LangFind, Value, Token, Referenced, LangKey, Index)
486 #
487 # Retoken
488 #
489 # First re-token the first language
490 LangName = self.LanguageDef[0][0]
491 ReferencedStringList = []
492 NotReferencedStringList = []
493 Token = 0
494
495 #
496 # Order UNI token by their String Name
497 #
498 StringNameList = []
499 for Item in self.OrderedStringList[LangName]:
500 StringNameList.append (Item.StringName)
501 StringNameList.sort()
502
503 for Name in StringNameList:
504 Item = self.FindStringValue (Name, LangName)
505 if Item.Referenced == True:
506 Item.Token = Token
507 ReferencedStringList.append(Item)
508 Token = Token + 1
509 else:
510 NotReferencedStringList.append(Item)
511 self.OrderedStringList[LangName] = ReferencedStringList
512 for Index in range(len(NotReferencedStringList)):
513 NotReferencedStringList[Index].Token = Token + Index
514 self.OrderedStringList[LangName].append(NotReferencedStringList[Index])
515
516 #
517 # Adjust the orders of other languages
518 #
519 for IndexOfLanguage in range(1, len(self.LanguageDef)):
520 for OrderedString in self.OrderedStringList[LangName]:
521 for UnOrderedString in self.OrderedStringList[self.LanguageDef[IndexOfLanguage][0]]:
522 if OrderedString.StringName == UnOrderedString.StringName:
523 UnOrderedString.Token = OrderedString.Token
524 break
525
526 #
527 # Show the instance itself
528 #
529 def ShowMe(self):
530 print self.LanguageDef
531 #print self.OrderedStringList
532 for Item in self.OrderedStringList:
533 print Item
534 for Member in self.OrderedStringList[Item]:
535 print str(Member)
536
537 # This acts like the main() function for the script, unless it is 'import'ed into another
538 # script.
539 if __name__ == '__main__':
540 EdkLogger.Initialize()
541 EdkLogger.SetLevel(EdkLogger.DEBUG_0)
542 a = UniFileClassObject(['C:\\Edk\\Strings.uni', 'C:\\Edk\\Strings2.uni'])
543 a.ReToken()
544 a.ShowMe()