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