]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/UPT/Library/StringUtils.py
BaseTools: Handle the bytes and str difference
[mirror_edk2.git] / BaseTools / Source / Python / UPT / Library / StringUtils.py
CommitLineData
4234283c 1## @file\r
421ccda3 2# This file is used to define common string related functions used in parsing\r
4234283c
LG
3# process\r
4#\r
64285f15 5# Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR>\r
4234283c 6#\r
421ccda3
HC
7# This program and the accompanying materials are licensed and made available\r
8# under the terms and conditions of the BSD License which accompanies this\r
9# distribution. The full text of the license may be found at\r
4234283c
LG
10# http://opensource.org/licenses/bsd-license.php\r
11#\r
12# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
13# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
14#\r
15'''\r
64285f15 16StringUtils\r
4234283c
LG
17'''\r
18##\r
19# Import Modules\r
20#\r
21import re\r
22import os.path\r
4234283c
LG
23import Logger.Log as Logger\r
24import Library.DataType as DataType\r
25from Logger.ToolError import FORMAT_INVALID\r
26from Logger.ToolError import PARSER_ERROR\r
27from Logger import StringTable as ST\r
28\r
29#\r
30# Regular expression for matching macro used in DSC/DEC/INF file inclusion\r
31#\r
32gMACRO_PATTERN = re.compile("\$\(([_A-Z][_A-Z0-9]*)\)", re.UNICODE)\r
33\r
34## GetSplitValueList\r
35#\r
36# Get a value list from a string with multiple values splited with SplitTag\r
37# The default SplitTag is DataType.TAB_VALUE_SPLIT\r
38# 'AAA|BBB|CCC' -> ['AAA', 'BBB', 'CCC']\r
39#\r
40# @param String: The input string to be splitted\r
41# @param SplitTag: The split key, default is DataType.TAB_VALUE_SPLIT\r
42# @param MaxSplit: The max number of split values, default is -1\r
43#\r
44#\r
421ccda3 45def GetSplitValueList(String, SplitTag=DataType.TAB_VALUE_SPLIT, MaxSplit= -1):\r
174a9d3c 46 return list(map(lambda l: l.strip(), String.split(SplitTag, MaxSplit)))\r
4234283c
LG
47\r
48## MergeArches\r
49#\r
50# Find a key's all arches in dict, add the new arch to the list\r
51# If not exist any arch, set the arch directly\r
52#\r
53# @param Dict: The input value for Dict\r
54# @param Key: The input value for Key\r
55# @param Arch: The Arch to be added or merged\r
56#\r
57def MergeArches(Dict, Key, Arch):\r
58 if Key in Dict.keys():\r
59 Dict[Key].append(Arch)\r
60 else:\r
61 Dict[Key] = Arch.split()\r
62\r
63## GenDefines\r
64#\r
65# Parse a string with format "DEFINE <VarName> = <PATH>"\r
66# Generate a map Defines[VarName] = PATH\r
67# Return False if invalid format\r
68#\r
69# @param String: String with DEFINE statement\r
70# @param Arch: Supportted Arch\r
71# @param Defines: DEFINE statement to be parsed\r
72#\r
73def GenDefines(String, Arch, Defines):\r
74 if String.find(DataType.TAB_DEFINE + ' ') > -1:\r
75 List = String.replace(DataType.TAB_DEFINE + ' ', '').\\r
76 split(DataType.TAB_EQUAL_SPLIT)\r
77 if len(List) == 2:\r
78 Defines[(CleanString(List[0]), Arch)] = CleanString(List[1])\r
79 return 0\r
80 else:\r
81 return -1\r
82 return 1\r
83\r
84## GetLibraryClassesWithModuleType\r
85#\r
86# Get Library Class definition when no module type defined\r
87#\r
88# @param Lines: The content to be parsed\r
89# @param Key: Reserved\r
90# @param KeyValues: To store data after parsing\r
91# @param CommentCharacter: Comment char, used to ignore comment content\r
92#\r
93def GetLibraryClassesWithModuleType(Lines, Key, KeyValues, CommentCharacter):\r
94 NewKey = SplitModuleType(Key)\r
95 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
96 LineList = Lines.splitlines()\r
97 for Line in LineList:\r
98 Line = CleanString(Line, CommentCharacter)\r
99 if Line != '' and Line[0] != CommentCharacter:\r
100 KeyValues.append([CleanString(Line, CommentCharacter), NewKey[1]])\r
101\r
102 return True\r
103\r
104## GetDynamics\r
105#\r
106# Get Dynamic Pcds\r
107#\r
108# @param Lines: The content to be parsed\r
109# @param Key: Reserved\r
110# @param KeyValues: To store data after parsing\r
111# @param CommentCharacter: Comment char, used to ignore comment content\r
112#\r
113def GetDynamics(Lines, Key, KeyValues, CommentCharacter):\r
114 #\r
115 # Get SkuId Name List\r
116 #\r
117 SkuIdNameList = SplitModuleType(Key)\r
118\r
119 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
120 LineList = Lines.splitlines()\r
121 for Line in LineList:\r
122 Line = CleanString(Line, CommentCharacter)\r
123 if Line != '' and Line[0] != CommentCharacter:\r
124 KeyValues.append([CleanString(Line, CommentCharacter), SkuIdNameList[1]])\r
125\r
126 return True\r
127\r
128## SplitModuleType\r
129#\r
130# Split ModuleType out of section defien to get key\r
421ccda3 131# [LibraryClass.Arch.ModuleType|ModuleType|ModuleType] -> [\r
4234283c
LG
132# 'LibraryClass.Arch', ['ModuleType', 'ModuleType', 'ModuleType'] ]\r
133#\r
134# @param Key: String to be parsed\r
135#\r
136def SplitModuleType(Key):\r
137 KeyList = Key.split(DataType.TAB_SPLIT)\r
138 #\r
139 # Fill in for arch\r
140 #\r
141 KeyList.append('')\r
142 #\r
143 # Fill in for moduletype\r
144 #\r
145 KeyList.append('')\r
146 ReturnValue = []\r
147 KeyValue = KeyList[0]\r
148 if KeyList[1] != '':\r
149 KeyValue = KeyValue + DataType.TAB_SPLIT + KeyList[1]\r
150 ReturnValue.append(KeyValue)\r
151 ReturnValue.append(GetSplitValueList(KeyList[2]))\r
152\r
153 return ReturnValue\r
154\r
155## Replace macro in string\r
156#\r
157# This method replace macros used in given string. The macros are given in a\r
158# dictionary.\r
159#\r
160# @param String String to be processed\r
161# @param MacroDefinitions The macro definitions in the form of dictionary\r
162# @param SelfReplacement To decide whether replace un-defined macro to ''\r
163# @param Line: The content contain line string and line number\r
164# @param FileName: The meta-file file name\r
165#\r
421ccda3 166def ReplaceMacro(String, MacroDefinitions=None, SelfReplacement=False, Line=None, FileName=None, Flag=False):\r
4234283c 167 LastString = String\r
4231a819 168 if MacroDefinitions is None:\r
4234283c
LG
169 MacroDefinitions = {}\r
170 while MacroDefinitions:\r
171 QuotedStringList = []\r
172 HaveQuotedMacroFlag = False\r
173 if not Flag:\r
174 MacroUsed = gMACRO_PATTERN.findall(String)\r
175 else:\r
176 ReQuotedString = re.compile('\"')\r
177 QuotedStringList = ReQuotedString.split(String)\r
178 if len(QuotedStringList) >= 3:\r
179 HaveQuotedMacroFlag = True\r
180 Count = 0\r
181 MacroString = ""\r
182 for QuotedStringItem in QuotedStringList:\r
183 Count += 1\r
184 if Count % 2 != 0:\r
185 MacroString += QuotedStringItem\r
421ccda3
HC
186\r
187 if Count == len(QuotedStringList) and Count % 2 == 0:\r
4234283c 188 MacroString += QuotedStringItem\r
421ccda3 189\r
4234283c
LG
190 MacroUsed = gMACRO_PATTERN.findall(MacroString)\r
191 #\r
192 # no macro found in String, stop replacing\r
193 #\r
194 if len(MacroUsed) == 0:\r
195 break\r
196 for Macro in MacroUsed:\r
197 if Macro not in MacroDefinitions:\r
198 if SelfReplacement:\r
199 String = String.replace("$(%s)" % Macro, '')\r
421ccda3 200 Logger.Debug(5, "Delete undefined MACROs in file %s line %d: %s!" % (FileName, Line[1], Line[0]))\r
4234283c
LG
201 continue\r
202 if not HaveQuotedMacroFlag:\r
203 String = String.replace("$(%s)" % Macro, MacroDefinitions[Macro])\r
204 else:\r
205 Count = 0\r
206 for QuotedStringItem in QuotedStringList:\r
207 Count += 1\r
208 if Count % 2 != 0:\r
421ccda3 209 QuotedStringList[Count - 1] = QuotedStringList[Count - 1].replace("$(%s)" % Macro,\r
4234283c 210 MacroDefinitions[Macro])\r
421ccda3
HC
211 elif Count == len(QuotedStringList) and Count % 2 == 0:\r
212 QuotedStringList[Count - 1] = QuotedStringList[Count - 1].replace("$(%s)" % Macro,\r
4234283c 213 MacroDefinitions[Macro])\r
421ccda3 214\r
4234283c
LG
215 RetString = ''\r
216 if HaveQuotedMacroFlag:\r
217 Count = 0\r
218 for QuotedStringItem in QuotedStringList:\r
421ccda3 219 Count += 1\r
4234283c 220 if Count != len(QuotedStringList):\r
421ccda3 221 RetString += QuotedStringList[Count - 1] + "\""\r
4234283c 222 else:\r
421ccda3
HC
223 RetString += QuotedStringList[Count - 1]\r
224\r
4234283c 225 String = RetString\r
421ccda3
HC
226\r
227 #\r
4234283c
LG
228 # in case there's macro not defined\r
229 #\r
230 if String == LastString:\r
231 break\r
232 LastString = String\r
233\r
234 return String\r
235\r
236## NormPath\r
237#\r
238# Create a normal path\r
239# And replace DFEINE in the path\r
240#\r
241# @param Path: The input value for Path to be converted\r
242# @param Defines: A set for DEFINE statement\r
243#\r
421ccda3 244def NormPath(Path, Defines=None):\r
4234283c 245 IsRelativePath = False\r
4231a819 246 if Defines is None:\r
4234283c
LG
247 Defines = {}\r
248 if Path:\r
249 if Path[0] == '.':\r
250 IsRelativePath = True\r
251 #\r
252 # Replace with Define\r
253 #\r
254 if Defines:\r
255 Path = ReplaceMacro(Path, Defines)\r
256 #\r
257 # To local path format\r
258 #\r
259 Path = os.path.normpath(Path)\r
260\r
261 if IsRelativePath and Path[0] != '.':\r
262 Path = os.path.join('.', Path)\r
263 return Path\r
264\r
265## CleanString\r
266#\r
267# Remove comments in a string\r
268# Remove spaces\r
269#\r
270# @param Line: The string to be cleaned\r
421ccda3 271# @param CommentCharacter: Comment char, used to ignore comment content,\r
4234283c
LG
272# default is DataType.TAB_COMMENT_SPLIT\r
273#\r
274def CleanString(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False):\r
275 #\r
276 # remove whitespace\r
277 #\r
278 Line = Line.strip()\r
279 #\r
280 # Replace EDK1's comment character\r
281 #\r
282 if AllowCppStyleComment:\r
283 Line = Line.replace(DataType.TAB_COMMENT_EDK1_SPLIT, CommentCharacter)\r
284 #\r
285 # remove comments, but we should escape comment character in string\r
286 #\r
287 InString = False\r
288 for Index in range(0, len(Line)):\r
289 if Line[Index] == '"':\r
290 InString = not InString\r
291 elif Line[Index] == CommentCharacter and not InString:\r
292 Line = Line[0: Index]\r
293 break\r
294 #\r
295 # remove whitespace again\r
296 #\r
297 Line = Line.strip()\r
298\r
299 return Line\r
300\r
301## CleanString2\r
302#\r
303# Split comments in a string\r
304# Remove spaces\r
305#\r
306# @param Line: The string to be cleaned\r
421ccda3 307# @param CommentCharacter: Comment char, used to ignore comment content,\r
4234283c
LG
308# default is DataType.TAB_COMMENT_SPLIT\r
309#\r
310def CleanString2(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False):\r
311 #\r
312 # remove whitespace\r
313 #\r
314 Line = Line.strip()\r
315 #\r
316 # Replace EDK1's comment character\r
317 #\r
318 if AllowCppStyleComment:\r
319 Line = Line.replace(DataType.TAB_COMMENT_EDK1_SPLIT, CommentCharacter)\r
320 #\r
321 # separate comments and statements\r
322 #\r
323 LineParts = Line.split(CommentCharacter, 1)\r
324 #\r
325 # remove whitespace again\r
326 #\r
327 Line = LineParts[0].strip()\r
328 if len(LineParts) > 1:\r
329 Comment = LineParts[1].strip()\r
330 #\r
331 # Remove prefixed and trailing comment characters\r
332 #\r
333 Start = 0\r
334 End = len(Comment)\r
335 while Start < End and Comment.startswith(CommentCharacter, Start, End):\r
336 Start += 1\r
337 while End >= 0 and Comment.endswith(CommentCharacter, Start, End):\r
338 End -= 1\r
339 Comment = Comment[Start:End]\r
340 Comment = Comment.strip()\r
341 else:\r
342 Comment = ''\r
343\r
344 return Line, Comment\r
345\r
346## GetMultipleValuesOfKeyFromLines\r
347#\r
348# Parse multiple strings to clean comment and spaces\r
349# The result is saved to KeyValues\r
350#\r
351# @param Lines: The content to be parsed\r
352# @param Key: Reserved\r
353# @param KeyValues: To store data after parsing\r
354# @param CommentCharacter: Comment char, used to ignore comment content\r
355#\r
356def GetMultipleValuesOfKeyFromLines(Lines, Key, KeyValues, CommentCharacter):\r
357 if Key:\r
358 pass\r
359 if KeyValues:\r
360 pass\r
361 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
362 LineList = Lines.split('\n')\r
363 for Line in LineList:\r
364 Line = CleanString(Line, CommentCharacter)\r
365 if Line != '' and Line[0] != CommentCharacter:\r
366 KeyValues += [Line]\r
367 return True\r
368\r
369## GetDefineValue\r
370#\r
371# Parse a DEFINE statement to get defined value\r
372# DEFINE Key Value\r
373#\r
374# @param String: The content to be parsed\r
375# @param Key: The key of DEFINE statement\r
376# @param CommentCharacter: Comment char, used to ignore comment content\r
377#\r
378def GetDefineValue(String, Key, CommentCharacter):\r
379 if CommentCharacter:\r
380 pass\r
381 String = CleanString(String)\r
382 return String[String.find(Key + ' ') + len(Key + ' ') : ]\r
383\r
384## GetSingleValueOfKeyFromLines\r
385#\r
386# Parse multiple strings as below to get value of each definition line\r
387# Key1 = Value1\r
388# Key2 = Value2\r
389# The result is saved to Dictionary\r
390#\r
391# @param Lines: The content to be parsed\r
392# @param Dictionary: To store data after parsing\r
393# @param CommentCharacter: Comment char, be used to ignore comment content\r
394# @param KeySplitCharacter: Key split char, between key name and key value.\r
395# Key1 = Value1, '=' is the key split char\r
421ccda3 396# @param ValueSplitFlag: Value split flag, be used to decide if has\r
4234283c 397# multiple values\r
421ccda3
HC
398# @param ValueSplitCharacter: Value split char, be used to split multiple\r
399# values. Key1 = Value1|Value2, '|' is the value\r
4234283c
LG
400# split char\r
401#\r
402def GetSingleValueOfKeyFromLines(Lines, Dictionary, CommentCharacter, KeySplitCharacter, \\r
403 ValueSplitFlag, ValueSplitCharacter):\r
404 Lines = Lines.split('\n')\r
405 Keys = []\r
406 Value = ''\r
407 DefineValues = ['']\r
408 SpecValues = ['']\r
409\r
410 for Line in Lines:\r
411 #\r
412 # Handle DEFINE and SPEC\r
413 #\r
414 if Line.find(DataType.TAB_INF_DEFINES_DEFINE + ' ') > -1:\r
415 if '' in DefineValues:\r
416 DefineValues.remove('')\r
417 DefineValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_DEFINE, CommentCharacter))\r
418 continue\r
419 if Line.find(DataType.TAB_INF_DEFINES_SPEC + ' ') > -1:\r
420 if '' in SpecValues:\r
421 SpecValues.remove('')\r
422 SpecValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_SPEC, CommentCharacter))\r
423 continue\r
424\r
425 #\r
426 # Handle Others\r
427 #\r
428 LineList = Line.split(KeySplitCharacter, 1)\r
429 if len(LineList) >= 2:\r
430 Key = LineList[0].split()\r
431 if len(Key) == 1 and Key[0][0] != CommentCharacter:\r
432 #\r
433 # Remove comments and white spaces\r
434 #\r
435 LineList[1] = CleanString(LineList[1], CommentCharacter)\r
436 if ValueSplitFlag:\r
174a9d3c 437 Value = list(map(lambda x: x.strip(), LineList[1].split(ValueSplitCharacter)))\r
4234283c
LG
438 else:\r
439 Value = CleanString(LineList[1], CommentCharacter).splitlines()\r
440\r
441 if Key[0] in Dictionary:\r
442 if Key[0] not in Keys:\r
443 Dictionary[Key[0]] = Value\r
444 Keys.append(Key[0])\r
445 else:\r
446 Dictionary[Key[0]].extend(Value)\r
447 else:\r
448 Dictionary[DataType.TAB_INF_DEFINES_MACRO][Key[0]] = Value[0]\r
449\r
450 if DefineValues == []:\r
451 DefineValues = ['']\r
452 if SpecValues == []:\r
453 SpecValues = ['']\r
454 Dictionary[DataType.TAB_INF_DEFINES_DEFINE] = DefineValues\r
455 Dictionary[DataType.TAB_INF_DEFINES_SPEC] = SpecValues\r
456\r
457 return True\r
458\r
459## The content to be parsed\r
460#\r
461# Do pre-check for a file before it is parsed\r
462# Check $()\r
463# Check []\r
464#\r
465# @param FileName: Used for error report\r
466# @param FileContent: File content to be parsed\r
467# @param SupSectionTag: Used for error report\r
468#\r
469def PreCheck(FileName, FileContent, SupSectionTag):\r
470 if SupSectionTag:\r
471 pass\r
472 LineNo = 0\r
473 IsFailed = False\r
474 NewFileContent = ''\r
475 for Line in FileContent.splitlines():\r
476 LineNo = LineNo + 1\r
477 #\r
478 # Clean current line\r
479 #\r
480 Line = CleanString(Line)\r
481 #\r
482 # Remove commented line\r
483 #\r
484 if Line.find(DataType.TAB_COMMA_SPLIT) == 0:\r
485 Line = ''\r
486 #\r
487 # Check $()\r
488 #\r
489 if Line.find('$') > -1:\r
490 if Line.find('$(') < 0 or Line.find(')') < 0:\r
421ccda3 491 Logger.Error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=Logger.IS_RAISE_ERROR)\r
4234283c
LG
492 #\r
493 # Check []\r
494 #\r
495 if Line.find('[') > -1 or Line.find(']') > -1:\r
496 #\r
497 # Only get one '[' or one ']'\r
498 #\r
499 if not (Line.find('[') > -1 and Line.find(']') > -1):\r
421ccda3 500 Logger.Error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=Logger.IS_RAISE_ERROR)\r
4234283c
LG
501 #\r
502 # Regenerate FileContent\r
503 #\r
1ccc4d89 504 NewFileContent = NewFileContent + Line + '\r\n'\r
4234283c
LG
505\r
506 if IsFailed:\r
421ccda3 507 Logger.Error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=Logger.IS_RAISE_ERROR)\r
4234283c
LG
508\r
509 return NewFileContent\r
510\r
511## CheckFileType\r
512#\r
513# Check if the Filename is including ExtName\r
514# Return True if it exists\r
515# Raise a error message if it not exists\r
516#\r
517# @param CheckFilename: Name of the file to be checked\r
518# @param ExtName: Ext name of the file to be checked\r
519# @param ContainerFilename: The container file which describes the file to be\r
520# checked, used for error report\r
521# @param SectionName: Used for error report\r
522# @param Line: The line in container file which defines the file\r
523# to be checked\r
524#\r
421ccda3 525def CheckFileType(CheckFilename, ExtName, ContainerFilename, SectionName, Line, LineNo= -1):\r
4231a819 526 if CheckFilename != '' and CheckFilename is not None:\r
4234283c
LG
527 (Root, Ext) = os.path.splitext(CheckFilename)\r
528 if Ext.upper() != ExtName.upper() and Root:\r
529 ContainerFile = open(ContainerFilename, 'r').read()\r
530 if LineNo == -1:\r
531 LineNo = GetLineNo(ContainerFile, Line)\r
532 ErrorMsg = ST.ERR_SECTIONNAME_INVALID % (SectionName, CheckFilename, ExtName)\r
533 Logger.Error("Parser", PARSER_ERROR, ErrorMsg, Line=LineNo, \\r
534 File=ContainerFilename, RaiseError=Logger.IS_RAISE_ERROR)\r
535\r
536 return True\r
537\r
538## CheckFileExist\r
539#\r
540# Check if the file exists\r
541# Return True if it exists\r
542# Raise a error message if it not exists\r
543#\r
544# @param CheckFilename: Name of the file to be checked\r
545# @param WorkspaceDir: Current workspace dir\r
421ccda3 546# @param ContainerFilename: The container file which describes the file to\r
4234283c
LG
547# be checked, used for error report\r
548# @param SectionName: Used for error report\r
421ccda3 549# @param Line: The line in container file which defines the\r
4234283c
LG
550# file to be checked\r
551#\r
421ccda3 552def CheckFileExist(WorkspaceDir, CheckFilename, ContainerFilename, SectionName, Line, LineNo= -1):\r
4234283c 553 CheckFile = ''\r
4231a819 554 if CheckFilename != '' and CheckFilename is not None:\r
4234283c
LG
555 CheckFile = WorkspaceFile(WorkspaceDir, CheckFilename)\r
556 if not os.path.isfile(CheckFile):\r
557 ContainerFile = open(ContainerFilename, 'r').read()\r
558 if LineNo == -1:\r
559 LineNo = GetLineNo(ContainerFile, Line)\r
560 ErrorMsg = ST.ERR_CHECKFILE_NOTFOUND % (CheckFile, SectionName)\r
561 Logger.Error("Parser", PARSER_ERROR, ErrorMsg,\r
421ccda3 562 File=ContainerFilename, Line=LineNo, RaiseError=Logger.IS_RAISE_ERROR)\r
4234283c
LG
563 return CheckFile\r
564\r
565## GetLineNo\r
566#\r
567# Find the index of a line in a file\r
568#\r
569# @param FileContent: Search scope\r
570# @param Line: Search key\r
571#\r
572def GetLineNo(FileContent, Line, IsIgnoreComment=True):\r
573 LineList = FileContent.splitlines()\r
574 for Index in range(len(LineList)):\r
575 if LineList[Index].find(Line) > -1:\r
576 #\r
577 # Ignore statement in comment\r
578 #\r
579 if IsIgnoreComment:\r
580 if LineList[Index].strip()[0] == DataType.TAB_COMMENT_SPLIT:\r
581 continue\r
582 return Index + 1\r
583\r
584 return -1\r
585\r
586## RaiseParserError\r
587#\r
588# Raise a parser error\r
589#\r
590# @param Line: String which has error\r
591# @param Section: Used for error report\r
592# @param File: File which has the string\r
593# @param Format: Correct format\r
594#\r
421ccda3 595def RaiseParserError(Line, Section, File, Format='', LineNo= -1):\r
4234283c
LG
596 if LineNo == -1:\r
597 LineNo = GetLineNo(open(os.path.normpath(File), 'r').read(), Line)\r
598 ErrorMsg = ST.ERR_INVALID_NOTFOUND % (Line, Section)\r
599 if Format != '':\r
600 Format = "Correct format is " + Format\r
601 Logger.Error("Parser", PARSER_ERROR, ErrorMsg, File=File, Line=LineNo, \\r
602 ExtraData=Format, RaiseError=Logger.IS_RAISE_ERROR)\r
603\r
604## WorkspaceFile\r
605#\r
606# Return a full path with workspace dir\r
607#\r
608# @param WorkspaceDir: Workspace dir\r
609# @param Filename: Relative file name\r
610#\r
611def WorkspaceFile(WorkspaceDir, Filename):\r
612 return os.path.join(NormPath(WorkspaceDir), NormPath(Filename))\r
613\r
614## Split string\r
615#\r
616# Revmove '"' which startswith and endswith string\r
617#\r
618# @param String: The string need to be splited\r
619#\r
620def SplitString(String):\r
621 if String.startswith('\"'):\r
622 String = String[1:]\r
623 if String.endswith('\"'):\r
624 String = String[:-1]\r
625 return String\r
626\r
627## Convert To Sql String\r
628#\r
629# Replace "'" with "''" in each item of StringList\r
630#\r
631# @param StringList: A list for strings to be converted\r
632#\r
633def ConvertToSqlString(StringList):\r
174a9d3c 634 return list(map(lambda s: s.replace("'", "''"), StringList))\r
4234283c
LG
635\r
636## Convert To Sql String\r
637#\r
638# Replace "'" with "''" in the String\r
639#\r
640# @param String: A String to be converted\r
641#\r
642def ConvertToSqlString2(String):\r
643 return String.replace("'", "''")\r
644\r
4234283c
LG
645## GetStringOfList\r
646#\r
647# Get String of a List\r
648#\r
649# @param Lines: string list\r
650# @param Split: split character\r
651#\r
421ccda3 652def GetStringOfList(List, Split=' '):\r
0d1f5b2b 653 if not isinstance(List, type([])):\r
4234283c
LG
654 return List\r
655 Str = ''\r
656 for Item in List:\r
657 Str = Str + Item + Split\r
658 return Str.strip()\r
659\r
660## Get HelpTextList\r
661#\r
662# Get HelpTextList from HelpTextClassList\r
663#\r
664# @param HelpTextClassList: Help Text Class List\r
665#\r
666def GetHelpTextList(HelpTextClassList):\r
667 List = []\r
668 if HelpTextClassList:\r
669 for HelpText in HelpTextClassList:\r
670 if HelpText.String.endswith('\n'):\r
671 HelpText.String = HelpText.String[0: len(HelpText.String) - len('\n')]\r
672 List.extend(HelpText.String.split('\n'))\r
673 return List\r
674\r
675## Get String Array Length\r
676#\r
677# Get String Array Length\r
678#\r
679# @param String: the source string\r
680#\r
681def StringArrayLength(String):\r
d943b0c3 682 if String.startswith('L"'):\r
4234283c
LG
683 return (len(String) - 3 + 1) * 2\r
684 elif String.startswith('"'):\r
685 return (len(String) - 2 + 1)\r
686 else:\r
687 return len(String.split()) + 1\r
688\r
689## RemoveDupOption\r
690#\r
691# Remove Dup Option\r
692#\r
693# @param OptionString: the option string\r
694# @param Which: Which flag\r
695# @param Against: Against flag\r
421ccda3 696#\r
4234283c
LG
697def RemoveDupOption(OptionString, Which="/I", Against=None):\r
698 OptionList = OptionString.split()\r
699 ValueList = []\r
700 if Against:\r
701 ValueList += Against\r
702 for Index in range(len(OptionList)):\r
703 Opt = OptionList[Index]\r
704 if not Opt.startswith(Which):\r
705 continue\r
706 if len(Opt) > len(Which):\r
707 Val = Opt[len(Which):]\r
708 else:\r
709 Val = ""\r
710 if Val in ValueList:\r
711 OptionList[Index] = ""\r
712 else:\r
713 ValueList.append(Val)\r
714 return " ".join(OptionList)\r
715\r
716## Check if the string is HexDgit\r
717#\r
421ccda3
HC
718# Return true if all characters in the string are digits and there is at\r
719# least one character\r
4234283c 720# or valid Hexs (started with 0x, following by hexdigit letters)\r
421ccda3 721# , false otherwise.\r
4234283c
LG
722# @param string: input string\r
723#\r
724def IsHexDigit(Str):\r
421ccda3 725 try:\r
4234283c
LG
726 int(Str, 10)\r
727 return True\r
728 except ValueError:\r
729 if len(Str) > 2 and Str.upper().startswith('0X'):\r
730 try:\r
731 int(Str, 16)\r
732 return True\r
733 except ValueError:\r
734 return False\r
735 return False\r
736\r
421ccda3 737## Check if the string is HexDgit and its interger value within limit of UINT32\r
4234283c 738#\r
421ccda3
HC
739# Return true if all characters in the string are digits and there is at\r
740# least one character\r
4234283c 741# or valid Hexs (started with 0x, following by hexdigit letters)\r
421ccda3 742# , false otherwise.\r
4234283c
LG
743# @param string: input string\r
744#\r
745def IsHexDigitUINT32(Str):\r
421ccda3 746 try:\r
4234283c
LG
747 Value = int(Str, 10)\r
748 if (Value <= 0xFFFFFFFF) and (Value >= 0):\r
749 return True\r
750 except ValueError:\r
751 if len(Str) > 2 and Str.upper().startswith('0X'):\r
752 try:\r
753 Value = int(Str, 16)\r
754 if (Value <= 0xFFFFFFFF) and (Value >= 0):\r
755 return True\r
756 except ValueError:\r
757 return False\r
758 return False\r
759\r
760## CleanSpecialChar\r
421ccda3
HC
761#\r
762# The ASCII text files of type INF, DEC, INI are edited by developers,\r
4234283c 763# and may contain characters that cannot be directly translated to strings that\r
421ccda3
HC
764# are conformant with the UDP XML Schema. Any characters in this category\r
765# (0x00-0x08, TAB [0x09], 0x0B, 0x0C, 0x0E-0x1F, 0x80-0xFF)\r
4234283c
LG
766# must be converted to a space character[0x20] as part of the parsing process.\r
767#\r
768def ConvertSpecialChar(Lines):\r
769 RetLines = []\r
770 for line in Lines:\r
771 ReMatchSpecialChar = re.compile(r"[\x00-\x08]|\x09|\x0b|\x0c|[\x0e-\x1f]|[\x7f-\xff]")\r
772 RetLines.append(ReMatchSpecialChar.sub(' ', line))\r
421ccda3 773\r
4234283c
LG
774 return RetLines\r
775\r
776## __GetTokenList\r
777#\r
778# Assume Str is a valid feature flag expression.\r
779# Return a list which contains tokens: alpha numeric token and other token\r
780# Whitespace are not stripped\r
781#\r
782def __GetTokenList(Str):\r
783 InQuote = False\r
784 Token = ''\r
785 TokenOP = ''\r
786 PreChar = ''\r
787 List = []\r
788 for Char in Str:\r
789 if InQuote:\r
790 Token += Char\r
791 if Char == '"' and PreChar != '\\':\r
792 InQuote = not InQuote\r
793 List.append(Token)\r
794 Token = ''\r
795 continue\r
796 if Char == '"':\r
797 if Token and Token != 'L':\r
798 List.append(Token)\r
799 Token = ''\r
800 if TokenOP:\r
801 List.append(TokenOP)\r
802 TokenOP = ''\r
803 InQuote = not InQuote\r
804 Token += Char\r
805 continue\r
806\r
807 if not (Char.isalnum() or Char in '_'):\r
808 TokenOP += Char\r
809 if Token:\r
810 List.append(Token)\r
811 Token = ''\r
812 else:\r
813 Token += Char\r
814 if TokenOP:\r
815 List.append(TokenOP)\r
816 TokenOP = ''\r
421ccda3 817\r
4234283c
LG
818 if PreChar == '\\' and Char == '\\':\r
819 PreChar = ''\r
820 else:\r
821 PreChar = Char\r
822 if Token:\r
823 List.append(Token)\r
824 if TokenOP:\r
825 List.append(TokenOP)\r
826 return List\r
827\r
828## ConvertNEToNOTEQ\r
829#\r
830# Convert NE operator to NOT EQ\r
831# For example: 1 NE 2 -> 1 NOT EQ 2\r
832#\r
833# @param Expr: Feature flag expression to be converted\r
834#\r
835def ConvertNEToNOTEQ(Expr):\r
836 List = __GetTokenList(Expr)\r
837 for Index in range(len(List)):\r
838 if List[Index] == 'NE':\r
839 List[Index] = 'NOT EQ'\r
840 return ''.join(List)\r
841\r
842## ConvertNOTEQToNE\r
843#\r
844# Convert NOT EQ operator to NE\r
845# For example: 1 NOT NE 2 -> 1 NE 2\r
846#\r
847# @param Expr: Feature flag expression to be converted\r
848#\r
849def ConvertNOTEQToNE(Expr):\r
850 List = __GetTokenList(Expr)\r
851 HasNOT = False\r
852 RetList = []\r
853 for Token in List:\r
854 if HasNOT and Token == 'EQ':\r
855 # At least, 'NOT' is in the list\r
856 while not RetList[-1].strip():\r
857 RetList.pop()\r
858 RetList[-1] = 'NE'\r
859 HasNOT = False\r
860 continue\r
861 if Token == 'NOT':\r
862 HasNOT = True\r
863 elif Token.strip():\r
864 HasNOT = False\r
865 RetList.append(Token)\r
866\r
867 return ''.join(RetList)\r
868\r
869## SplitPcdEntry\r
421ccda3 870#\r
4234283c
LG
871# Split an PCD entry string to Token.CName and PCD value and FFE.\r
872# NOTE: PCD Value and FFE can contain "|" in it's expression. And in INF specification, have below rule.\r
421ccda3 873# When using the characters "|" or "||" in an expression, the expression must be encapsulated in\r
4234283c 874# open "(" and close ")" parenthesis.\r
421ccda3 875#\r
4234283c 876# @param String An PCD entry string need to be split.\r
421ccda3
HC
877#\r
878# @return List [PcdTokenCName, Value, FFE]\r
4234283c
LG
879#\r
880def SplitPcdEntry(String):\r
881 if not String:\r
421ccda3
HC
882 return ['', '', ''], False\r
883\r
4234283c
LG
884 PcdTokenCName = ''\r
885 PcdValue = ''\r
886 PcdFeatureFlagExp = ''\r
421ccda3 887\r
4234283c 888 ValueList = GetSplitValueList(String, "|", 1)\r
421ccda3 889\r
4234283c
LG
890 #\r
891 # Only contain TokenCName\r
892 #\r
893 if len(ValueList) == 1:\r
894 return [ValueList[0]], True\r
421ccda3 895\r
4234283c 896 NewValueList = []\r
421ccda3 897\r
4234283c
LG
898 if len(ValueList) == 2:\r
899 PcdTokenCName = ValueList[0]\r
421ccda3
HC
900\r
901 InQuote = False\r
902 InParenthesis = False\r
903 StrItem = ''\r
904 for StrCh in ValueList[1]:\r
905 if StrCh == '"':\r
906 InQuote = not InQuote\r
907 elif StrCh == '(' or StrCh == ')':\r
908 InParenthesis = not InParenthesis\r
909\r
910 if StrCh == '|':\r
911 if not InQuote or not InParenthesis:\r
912 NewValueList.append(StrItem.strip())\r
913 StrItem = ' '\r
914 continue\r
915\r
916 StrItem += StrCh\r
917\r
918 NewValueList.append(StrItem.strip())\r
4234283c
LG
919\r
920 if len(NewValueList) == 1:\r
921 PcdValue = NewValueList[0]\r
922 return [PcdTokenCName, PcdValue], True\r
923 elif len(NewValueList) == 2:\r
924 PcdValue = NewValueList[0]\r
925 PcdFeatureFlagExp = NewValueList[1]\r
926 return [PcdTokenCName, PcdValue, PcdFeatureFlagExp], True\r
927 else:\r
928 return ['', '', ''], False\r
421ccda3 929\r
4234283c 930 return ['', '', ''], False\r
e4ac870f
LG
931\r
932## Check if two arches matched?\r
933#\r
934# @param Arch1\r
935# @param Arch2\r
936#\r
937def IsMatchArch(Arch1, Arch2):\r
938 if 'COMMON' in Arch1 or 'COMMON' in Arch2:\r
939 return True\r
174a9d3c
ZF
940 try:\r
941 if isinstance(Arch1, list) and isinstance(Arch2, list):\r
942 for Item1 in Arch1:\r
943 for Item2 in Arch2:\r
944 if Item1 == Item2:\r
945 return True\r
e4ac870f 946\r
174a9d3c
ZF
947 elif isinstance(Arch1, list):\r
948 return Arch2 in Arch1\r
e4ac870f 949\r
174a9d3c
ZF
950 elif isinstance(Arch2, list):\r
951 return Arch1 in Arch2\r
e4ac870f 952\r
174a9d3c
ZF
953 else:\r
954 if Arch1 == Arch2:\r
955 return True\r
956 except:\r
957 return False\r
06eb3540
HC
958\r
959# Search all files in FilePath to find the FileName with the largest index\r
960# Return the FileName with index +1 under the FilePath\r
961#\r
962def GetUniFileName(FilePath, FileName):\r
9e730bd1
HC
963 Files = []\r
964 try:\r
965 Files = os.listdir(FilePath)\r
966 except:\r
967 pass\r
968\r
06eb3540 969 LargestIndex = -1\r
f71b1630 970 IndexNotFound = True\r
06eb3540
HC
971 for File in Files:\r
972 if File.upper().startswith(FileName.upper()) and File.upper().endswith('.UNI'):\r
973 Index = File.upper().replace(FileName.upper(), '').replace('.UNI', '')\r
974 if Index:\r
975 try:\r
976 Index = int(Index)\r
977 except Exception:\r
978 Index = -1\r
979 else:\r
f71b1630 980 IndexNotFound = False\r
06eb3540
HC
981 Index = 0\r
982 if Index > LargestIndex:\r
983 LargestIndex = Index + 1\r
984\r
f71b1630 985 if LargestIndex > -1 and not IndexNotFound:\r
06eb3540
HC
986 return os.path.normpath(os.path.join(FilePath, FileName + str(LargestIndex) + '.uni'))\r
987 else:\r
988 return os.path.normpath(os.path.join(FilePath, FileName + '.uni'))\r