]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/UPT/Library/StringUtils.py
BaseTools/UPT:merge UPT Tool use Python2 and Python3
[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
1ccc4d89
LG
682 if isinstance(String, unicode):\r
683 return (len(String) + 1) * 2 + 1\r
684 elif String.startswith('L"'):\r
4234283c
LG
685 return (len(String) - 3 + 1) * 2\r
686 elif String.startswith('"'):\r
687 return (len(String) - 2 + 1)\r
688 else:\r
689 return len(String.split()) + 1\r
690\r
691## RemoveDupOption\r
692#\r
693# Remove Dup Option\r
694#\r
695# @param OptionString: the option string\r
696# @param Which: Which flag\r
697# @param Against: Against flag\r
421ccda3 698#\r
4234283c
LG
699def RemoveDupOption(OptionString, Which="/I", Against=None):\r
700 OptionList = OptionString.split()\r
701 ValueList = []\r
702 if Against:\r
703 ValueList += Against\r
704 for Index in range(len(OptionList)):\r
705 Opt = OptionList[Index]\r
706 if not Opt.startswith(Which):\r
707 continue\r
708 if len(Opt) > len(Which):\r
709 Val = Opt[len(Which):]\r
710 else:\r
711 Val = ""\r
712 if Val in ValueList:\r
713 OptionList[Index] = ""\r
714 else:\r
715 ValueList.append(Val)\r
716 return " ".join(OptionList)\r
717\r
718## Check if the string is HexDgit\r
719#\r
421ccda3
HC
720# Return true if all characters in the string are digits and there is at\r
721# least one character\r
4234283c 722# or valid Hexs (started with 0x, following by hexdigit letters)\r
421ccda3 723# , false otherwise.\r
4234283c
LG
724# @param string: input string\r
725#\r
726def IsHexDigit(Str):\r
421ccda3 727 try:\r
4234283c
LG
728 int(Str, 10)\r
729 return True\r
730 except ValueError:\r
731 if len(Str) > 2 and Str.upper().startswith('0X'):\r
732 try:\r
733 int(Str, 16)\r
734 return True\r
735 except ValueError:\r
736 return False\r
737 return False\r
738\r
421ccda3 739## Check if the string is HexDgit and its interger value within limit of UINT32\r
4234283c 740#\r
421ccda3
HC
741# Return true if all characters in the string are digits and there is at\r
742# least one character\r
4234283c 743# or valid Hexs (started with 0x, following by hexdigit letters)\r
421ccda3 744# , false otherwise.\r
4234283c
LG
745# @param string: input string\r
746#\r
747def IsHexDigitUINT32(Str):\r
421ccda3 748 try:\r
4234283c
LG
749 Value = int(Str, 10)\r
750 if (Value <= 0xFFFFFFFF) and (Value >= 0):\r
751 return True\r
752 except ValueError:\r
753 if len(Str) > 2 and Str.upper().startswith('0X'):\r
754 try:\r
755 Value = int(Str, 16)\r
756 if (Value <= 0xFFFFFFFF) and (Value >= 0):\r
757 return True\r
758 except ValueError:\r
759 return False\r
760 return False\r
761\r
762## CleanSpecialChar\r
421ccda3
HC
763#\r
764# The ASCII text files of type INF, DEC, INI are edited by developers,\r
4234283c 765# and may contain characters that cannot be directly translated to strings that\r
421ccda3
HC
766# are conformant with the UDP XML Schema. Any characters in this category\r
767# (0x00-0x08, TAB [0x09], 0x0B, 0x0C, 0x0E-0x1F, 0x80-0xFF)\r
4234283c
LG
768# must be converted to a space character[0x20] as part of the parsing process.\r
769#\r
770def ConvertSpecialChar(Lines):\r
771 RetLines = []\r
772 for line in Lines:\r
773 ReMatchSpecialChar = re.compile(r"[\x00-\x08]|\x09|\x0b|\x0c|[\x0e-\x1f]|[\x7f-\xff]")\r
774 RetLines.append(ReMatchSpecialChar.sub(' ', line))\r
421ccda3 775\r
4234283c
LG
776 return RetLines\r
777\r
778## __GetTokenList\r
779#\r
780# Assume Str is a valid feature flag expression.\r
781# Return a list which contains tokens: alpha numeric token and other token\r
782# Whitespace are not stripped\r
783#\r
784def __GetTokenList(Str):\r
785 InQuote = False\r
786 Token = ''\r
787 TokenOP = ''\r
788 PreChar = ''\r
789 List = []\r
790 for Char in Str:\r
791 if InQuote:\r
792 Token += Char\r
793 if Char == '"' and PreChar != '\\':\r
794 InQuote = not InQuote\r
795 List.append(Token)\r
796 Token = ''\r
797 continue\r
798 if Char == '"':\r
799 if Token and Token != 'L':\r
800 List.append(Token)\r
801 Token = ''\r
802 if TokenOP:\r
803 List.append(TokenOP)\r
804 TokenOP = ''\r
805 InQuote = not InQuote\r
806 Token += Char\r
807 continue\r
808\r
809 if not (Char.isalnum() or Char in '_'):\r
810 TokenOP += Char\r
811 if Token:\r
812 List.append(Token)\r
813 Token = ''\r
814 else:\r
815 Token += Char\r
816 if TokenOP:\r
817 List.append(TokenOP)\r
818 TokenOP = ''\r
421ccda3 819\r
4234283c
LG
820 if PreChar == '\\' and Char == '\\':\r
821 PreChar = ''\r
822 else:\r
823 PreChar = Char\r
824 if Token:\r
825 List.append(Token)\r
826 if TokenOP:\r
827 List.append(TokenOP)\r
828 return List\r
829\r
830## ConvertNEToNOTEQ\r
831#\r
832# Convert NE operator to NOT EQ\r
833# For example: 1 NE 2 -> 1 NOT EQ 2\r
834#\r
835# @param Expr: Feature flag expression to be converted\r
836#\r
837def ConvertNEToNOTEQ(Expr):\r
838 List = __GetTokenList(Expr)\r
839 for Index in range(len(List)):\r
840 if List[Index] == 'NE':\r
841 List[Index] = 'NOT EQ'\r
842 return ''.join(List)\r
843\r
844## ConvertNOTEQToNE\r
845#\r
846# Convert NOT EQ operator to NE\r
847# For example: 1 NOT NE 2 -> 1 NE 2\r
848#\r
849# @param Expr: Feature flag expression to be converted\r
850#\r
851def ConvertNOTEQToNE(Expr):\r
852 List = __GetTokenList(Expr)\r
853 HasNOT = False\r
854 RetList = []\r
855 for Token in List:\r
856 if HasNOT and Token == 'EQ':\r
857 # At least, 'NOT' is in the list\r
858 while not RetList[-1].strip():\r
859 RetList.pop()\r
860 RetList[-1] = 'NE'\r
861 HasNOT = False\r
862 continue\r
863 if Token == 'NOT':\r
864 HasNOT = True\r
865 elif Token.strip():\r
866 HasNOT = False\r
867 RetList.append(Token)\r
868\r
869 return ''.join(RetList)\r
870\r
871## SplitPcdEntry\r
421ccda3 872#\r
4234283c
LG
873# Split an PCD entry string to Token.CName and PCD value and FFE.\r
874# NOTE: PCD Value and FFE can contain "|" in it's expression. And in INF specification, have below rule.\r
421ccda3 875# When using the characters "|" or "||" in an expression, the expression must be encapsulated in\r
4234283c 876# open "(" and close ")" parenthesis.\r
421ccda3 877#\r
4234283c 878# @param String An PCD entry string need to be split.\r
421ccda3
HC
879#\r
880# @return List [PcdTokenCName, Value, FFE]\r
4234283c
LG
881#\r
882def SplitPcdEntry(String):\r
883 if not String:\r
421ccda3
HC
884 return ['', '', ''], False\r
885\r
4234283c
LG
886 PcdTokenCName = ''\r
887 PcdValue = ''\r
888 PcdFeatureFlagExp = ''\r
421ccda3 889\r
4234283c 890 ValueList = GetSplitValueList(String, "|", 1)\r
421ccda3 891\r
4234283c
LG
892 #\r
893 # Only contain TokenCName\r
894 #\r
895 if len(ValueList) == 1:\r
896 return [ValueList[0]], True\r
421ccda3 897\r
4234283c 898 NewValueList = []\r
421ccda3 899\r
4234283c
LG
900 if len(ValueList) == 2:\r
901 PcdTokenCName = ValueList[0]\r
421ccda3
HC
902\r
903 InQuote = False\r
904 InParenthesis = False\r
905 StrItem = ''\r
906 for StrCh in ValueList[1]:\r
907 if StrCh == '"':\r
908 InQuote = not InQuote\r
909 elif StrCh == '(' or StrCh == ')':\r
910 InParenthesis = not InParenthesis\r
911\r
912 if StrCh == '|':\r
913 if not InQuote or not InParenthesis:\r
914 NewValueList.append(StrItem.strip())\r
915 StrItem = ' '\r
916 continue\r
917\r
918 StrItem += StrCh\r
919\r
920 NewValueList.append(StrItem.strip())\r
4234283c
LG
921\r
922 if len(NewValueList) == 1:\r
923 PcdValue = NewValueList[0]\r
924 return [PcdTokenCName, PcdValue], True\r
925 elif len(NewValueList) == 2:\r
926 PcdValue = NewValueList[0]\r
927 PcdFeatureFlagExp = NewValueList[1]\r
928 return [PcdTokenCName, PcdValue, PcdFeatureFlagExp], True\r
929 else:\r
930 return ['', '', ''], False\r
421ccda3 931\r
4234283c 932 return ['', '', ''], False\r
e4ac870f
LG
933\r
934## Check if two arches matched?\r
935#\r
936# @param Arch1\r
937# @param Arch2\r
938#\r
939def IsMatchArch(Arch1, Arch2):\r
940 if 'COMMON' in Arch1 or 'COMMON' in Arch2:\r
941 return True\r
174a9d3c
ZF
942 try:\r
943 if isinstance(Arch1, list) and isinstance(Arch2, list):\r
944 for Item1 in Arch1:\r
945 for Item2 in Arch2:\r
946 if Item1 == Item2:\r
947 return True\r
e4ac870f 948\r
174a9d3c
ZF
949 elif isinstance(Arch1, list):\r
950 return Arch2 in Arch1\r
e4ac870f 951\r
174a9d3c
ZF
952 elif isinstance(Arch2, list):\r
953 return Arch1 in Arch2\r
e4ac870f 954\r
174a9d3c
ZF
955 else:\r
956 if Arch1 == Arch2:\r
957 return True\r
958 except:\r
959 return False\r
06eb3540
HC
960\r
961# Search all files in FilePath to find the FileName with the largest index\r
962# Return the FileName with index +1 under the FilePath\r
963#\r
964def GetUniFileName(FilePath, FileName):\r
9e730bd1
HC
965 Files = []\r
966 try:\r
967 Files = os.listdir(FilePath)\r
968 except:\r
969 pass\r
970\r
06eb3540 971 LargestIndex = -1\r
f71b1630 972 IndexNotFound = True\r
06eb3540
HC
973 for File in Files:\r
974 if File.upper().startswith(FileName.upper()) and File.upper().endswith('.UNI'):\r
975 Index = File.upper().replace(FileName.upper(), '').replace('.UNI', '')\r
976 if Index:\r
977 try:\r
978 Index = int(Index)\r
979 except Exception:\r
980 Index = -1\r
981 else:\r
f71b1630 982 IndexNotFound = False\r
06eb3540
HC
983 Index = 0\r
984 if Index > LargestIndex:\r
985 LargestIndex = Index + 1\r
986\r
f71b1630 987 if LargestIndex > -1 and not IndexNotFound:\r
06eb3540
HC
988 return os.path.normpath(os.path.join(FilePath, FileName + str(LargestIndex) + '.uni'))\r
989 else:\r
990 return os.path.normpath(os.path.join(FilePath, FileName + '.uni'))\r