]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/Common/StringUtils.py
UefiCpuPkg: Move AsmRelocateApLoopStart from Mpfuncs.nasm to AmdSev.nasm
[mirror_edk2.git] / BaseTools / Source / Python / Common / StringUtils.py
CommitLineData
30fdf114
LG
1## @file\r
2# This file is used to define common string related functions used in parsing process\r
3#\r
9eb87141 4# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>\r
2e351cbe 5# SPDX-License-Identifier: BSD-2-Clause-Patent\r
30fdf114
LG
6#\r
7\r
8##\r
9# Import Modules\r
10#\r
1ccc4d89 11from __future__ import absolute_import\r
30fdf114 12import re\r
f3fc5b47 13from . import DataType\r
1be2ed90 14import Common.LongFilePathOs as os\r
30fdf114 15import string\r
f3fc5b47 16from . import EdkLogger as EdkLogger\r
30fdf114 17\r
f3fc5b47
GL
18from . import GlobalData\r
19from .BuildToolError import *\r
0d2711a6 20from CommonDataClass.Exceptions import *\r
1be2ed90 21from Common.LongFilePathSupport import OpenLongFilePath as open\r
05cc51ad 22from Common.MultipleWorkspace import MultipleWorkspace as mws\r
30fdf114 23\r
d40b2ee6 24gHexVerPatt = re.compile('0x[a-f0-9]{4}[a-f0-9]{4}$', re.IGNORECASE)\r
08dd311f
LG
25gHumanReadableVerPatt = re.compile(r'([1-9][0-9]*|0)\.[0-9]{1,2}$')\r
26\r
30fdf114
LG
27## GetSplitValueList\r
28#\r
fb0b35e0 29# Get a value list from a string with multiple values split with SplitTag\r
30fdf114
LG
30# The default SplitTag is DataType.TAB_VALUE_SPLIT\r
31# 'AAA|BBB|CCC' -> ['AAA', 'BBB', 'CCC']\r
32#\r
33# @param String: The input string to be splitted\r
34# @param SplitTag: The split key, default is DataType.TAB_VALUE_SPLIT\r
35# @param MaxSplit: The max number of split values, default is -1\r
36#\r
37# @retval list() A list for splitted string\r
38#\r
d40b2ee6 39def GetSplitValueList(String, SplitTag=DataType.TAB_VALUE_SPLIT, MaxSplit= -1):\r
0d2711a6
LG
40 ValueList = []\r
41 Last = 0\r
42 Escaped = False\r
ea927d2f
FY
43 InSingleQuoteString = False\r
44 InDoubleQuoteString = False\r
413d51cc 45 InParenthesis = 0\r
0d2711a6
LG
46 for Index in range(0, len(String)):\r
47 Char = String[Index]\r
48\r
49 if not Escaped:\r
50 # Found a splitter not in a string, split it\r
ea927d2f 51 if (not InSingleQuoteString or not InDoubleQuoteString) and InParenthesis == 0 and Char == SplitTag:\r
0d2711a6 52 ValueList.append(String[Last:Index].strip())\r
d40b2ee6 53 Last = Index + 1\r
0d2711a6
LG
54 if MaxSplit > 0 and len(ValueList) >= MaxSplit:\r
55 break\r
56\r
ea927d2f 57 if Char == '\\' and (InSingleQuoteString or InDoubleQuoteString):\r
0d2711a6 58 Escaped = True\r
ea927d2f
FY
59 elif Char == '"' and not InSingleQuoteString:\r
60 if not InDoubleQuoteString:\r
61 InDoubleQuoteString = True\r
0d2711a6 62 else:\r
ea927d2f
FY
63 InDoubleQuoteString = False\r
64 elif Char == "'" and not InDoubleQuoteString:\r
65 if not InSingleQuoteString:\r
66 InSingleQuoteString = True\r
67 else:\r
68 InSingleQuoteString = False\r
413d51cc
YF
69 elif Char == '(':\r
70 InParenthesis = InParenthesis + 1\r
71 elif Char == ')':\r
72 InParenthesis = InParenthesis - 1\r
0d2711a6
LG
73 else:\r
74 Escaped = False\r
75\r
76 if Last < len(String):\r
77 ValueList.append(String[Last:].strip())\r
78 elif Last == len(String):\r
79 ValueList.append('')\r
80\r
81 return ValueList\r
82\r
83## GetSplitList\r
84#\r
fb0b35e0 85# Get a value list from a string with multiple values split with SplitString\r
0d2711a6
LG
86# The default SplitTag is DataType.TAB_VALUE_SPLIT\r
87# 'AAA|BBB|CCC' -> ['AAA', 'BBB', 'CCC']\r
88#\r
89# @param String: The input string to be splitted\r
90# @param SplitStr: The split key, default is DataType.TAB_VALUE_SPLIT\r
91# @param MaxSplit: The max number of split values, default is -1\r
92#\r
93# @retval list() A list for splitted string\r
94#\r
d40b2ee6 95def GetSplitList(String, SplitStr=DataType.TAB_VALUE_SPLIT, MaxSplit= -1):\r
f8d11e5a 96 return list(map(lambda l: l.strip(), String.split(SplitStr, MaxSplit)))\r
30fdf114
LG
97\r
98## MergeArches\r
99#\r
100# Find a key's all arches in dict, add the new arch to the list\r
101# If not exist any arch, set the arch directly\r
102#\r
103# @param Dict: The input value for Dict\r
104# @param Key: The input value for Key\r
105# @param Arch: The Arch to be added or merged\r
106#\r
107def MergeArches(Dict, Key, Arch):\r
9eb87141 108 if Key in Dict:\r
30fdf114
LG
109 Dict[Key].append(Arch)\r
110 else:\r
111 Dict[Key] = Arch.split()\r
112\r
113## GenDefines\r
114#\r
115# Parse a string with format "DEFINE <VarName> = <PATH>"\r
116# Generate a map Defines[VarName] = PATH\r
117# Return False if invalid format\r
118#\r
119# @param String: String with DEFINE statement\r
fb0b35e0 120# @param Arch: Supported Arch\r
30fdf114
LG
121# @param Defines: DEFINE statement to be parsed\r
122#\r
123# @retval 0 DEFINE statement found, and valid\r
124# @retval 1 DEFINE statement found, but not valid\r
125# @retval -1 DEFINE statement not found\r
126#\r
127def GenDefines(String, Arch, Defines):\r
128 if String.find(DataType.TAB_DEFINE + ' ') > -1:\r
129 List = String.replace(DataType.TAB_DEFINE + ' ', '').split(DataType.TAB_EQUAL_SPLIT)\r
130 if len(List) == 2:\r
131 Defines[(CleanString(List[0]), Arch)] = CleanString(List[1])\r
132 return 0\r
133 else:\r
134 return -1\r
135\r
136 return 1\r
137\r
138## GenInclude\r
139#\r
140# Parse a string with format "!include <Filename>"\r
141# Return the file path\r
142# Return False if invalid format or NOT FOUND\r
143#\r
144# @param String: String with INCLUDE statement\r
145# @param IncludeFiles: INCLUDE statement to be parsed\r
fb0b35e0 146# @param Arch: Supported Arch\r
30fdf114
LG
147#\r
148# @retval True\r
149# @retval False\r
150#\r
151def GenInclude(String, IncludeFiles, Arch):\r
152 if String.upper().find(DataType.TAB_INCLUDE.upper() + ' ') > -1:\r
153 IncludeFile = CleanString(String[String.upper().find(DataType.TAB_INCLUDE.upper() + ' ') + len(DataType.TAB_INCLUDE + ' ') : ])\r
154 MergeArches(IncludeFiles, IncludeFile, Arch)\r
155 return True\r
156 else:\r
157 return False\r
158\r
159## GetLibraryClassesWithModuleType\r
160#\r
161# Get Library Class definition when no module type defined\r
162#\r
163# @param Lines: The content to be parsed\r
164# @param Key: Reserved\r
165# @param KeyValues: To store data after parsing\r
166# @param CommentCharacter: Comment char, used to ignore comment content\r
167#\r
168# @retval True Get library classes successfully\r
169#\r
170def GetLibraryClassesWithModuleType(Lines, Key, KeyValues, CommentCharacter):\r
171 newKey = SplitModuleType(Key)\r
172 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
173 LineList = Lines.splitlines()\r
174 for Line in LineList:\r
175 Line = CleanString(Line, CommentCharacter)\r
176 if Line != '' and Line[0] != CommentCharacter:\r
177 KeyValues.append([CleanString(Line, CommentCharacter), newKey[1]])\r
178\r
179 return True\r
180\r
181## GetDynamics\r
182#\r
183# Get Dynamic Pcds\r
184#\r
185# @param Lines: The content to be parsed\r
186# @param Key: Reserved\r
187# @param KeyValues: To store data after parsing\r
188# @param CommentCharacter: Comment char, used to ignore comment content\r
189#\r
190# @retval True Get Dynamic Pcds successfully\r
191#\r
192def GetDynamics(Lines, Key, KeyValues, CommentCharacter):\r
193 #\r
194 # Get SkuId Name List\r
195 #\r
196 SkuIdNameList = SplitModuleType(Key)\r
197\r
198 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
199 LineList = Lines.splitlines()\r
200 for Line in LineList:\r
201 Line = CleanString(Line, CommentCharacter)\r
202 if Line != '' and Line[0] != CommentCharacter:\r
203 KeyValues.append([CleanString(Line, CommentCharacter), SkuIdNameList[1]])\r
204\r
205 return True\r
206\r
207## SplitModuleType\r
208#\r
209# Split ModuleType out of section defien to get key\r
210# [LibraryClass.Arch.ModuleType|ModuleType|ModuleType] -> [ 'LibraryClass.Arch', ['ModuleType', 'ModuleType', 'ModuleType'] ]\r
211#\r
212# @param Key: String to be parsed\r
213#\r
214# @retval ReturnValue A list for module types\r
215#\r
216def SplitModuleType(Key):\r
217 KeyList = Key.split(DataType.TAB_SPLIT)\r
218 #\r
219 # Fill in for arch\r
220 #\r
221 KeyList.append('')\r
222 #\r
223 # Fill in for moduletype\r
224 #\r
225 KeyList.append('')\r
226 ReturnValue = []\r
227 KeyValue = KeyList[0]\r
228 if KeyList[1] != '':\r
229 KeyValue = KeyValue + DataType.TAB_SPLIT + KeyList[1]\r
230 ReturnValue.append(KeyValue)\r
231 ReturnValue.append(GetSplitValueList(KeyList[2]))\r
232\r
233 return ReturnValue\r
234\r
235## Replace macro in strings list\r
236#\r
237# This method replace macros used in a given string list. The macros are\r
238# given in a dictionary.\r
239#\r
240# @param StringList StringList to be processed\r
241# @param MacroDefinitions The macro definitions in the form of dictionary\r
242# @param SelfReplacement To decide whether replace un-defined macro to ''\r
243#\r
244# @retval NewList A new string list whose macros are replaced\r
245#\r
e32f7bc9 246def ReplaceMacros(StringList, MacroDefinitions=None, SelfReplacement=False):\r
30fdf114 247 NewList = []\r
e32f7bc9
FZ
248 if MacroDefinitions is None:\r
249 MacroDefinitions = {}\r
30fdf114 250 for String in StringList:\r
0d1f5b2b 251 if isinstance(String, type('')):\r
30fdf114
LG
252 NewList.append(ReplaceMacro(String, MacroDefinitions, SelfReplacement))\r
253 else:\r
254 NewList.append(String)\r
255\r
256 return NewList\r
257\r
258## Replace macro in string\r
259#\r
260# This method replace macros used in given string. The macros are given in a\r
261# dictionary.\r
262#\r
263# @param String String to be processed\r
264# @param MacroDefinitions The macro definitions in the form of dictionary\r
265# @param SelfReplacement To decide whether replace un-defined macro to ''\r
266#\r
267# @retval string The string whose macros are replaced\r
268#\r
e32f7bc9 269def ReplaceMacro(String, MacroDefinitions=None, SelfReplacement=False, RaiseError=False):\r
30fdf114 270 LastString = String\r
e32f7bc9
FZ
271 if MacroDefinitions is None:\r
272 MacroDefinitions = {}\r
0d2711a6
LG
273 while String and MacroDefinitions:\r
274 MacroUsed = GlobalData.gMacroRefPattern.findall(String)\r
30fdf114
LG
275 # no macro found in String, stop replacing\r
276 if len(MacroUsed) == 0:\r
277 break\r
278\r
279 for Macro in MacroUsed:\r
280 if Macro not in MacroDefinitions:\r
0d2711a6
LG
281 if RaiseError:\r
282 raise SymbolNotFound("%s not defined" % Macro)\r
30fdf114
LG
283 if SelfReplacement:\r
284 String = String.replace("$(%s)" % Macro, '')\r
285 continue\r
ce2f5940
HC
286 if "$(%s)" % Macro not in MacroDefinitions[Macro]:\r
287 String = String.replace("$(%s)" % Macro, MacroDefinitions[Macro])\r
30fdf114
LG
288 # in case there's macro not defined\r
289 if String == LastString:\r
290 break\r
291 LastString = String\r
292\r
293 return String\r
294\r
295## NormPath\r
296#\r
297# Create a normal path\r
fb0b35e0 298# And replace DEFINE in the path\r
30fdf114
LG
299#\r
300# @param Path: The input value for Path to be converted\r
301# @param Defines: A set for DEFINE statement\r
302#\r
303# @retval Path Formatted path\r
304#\r
e32f7bc9 305def NormPath(Path, Defines=None):\r
30fdf114
LG
306 IsRelativePath = False\r
307 if Path:\r
308 if Path[0] == '.':\r
309 IsRelativePath = True\r
310 #\r
311 # Replace with Define\r
312 #\r
313 if Defines:\r
314 Path = ReplaceMacro(Path, Defines)\r
315 #\r
316 # To local path format\r
317 #\r
318 Path = os.path.normpath(Path)\r
97058144 319 if Path.startswith(GlobalData.gWorkspace) and not Path.startswith(GlobalData.gBuildDirectory) and not os.path.exists(Path):\r
05cc51ad
LY
320 Path = Path[len (GlobalData.gWorkspace):]\r
321 if Path[0] == os.path.sep:\r
322 Path = Path[1:]\r
323 Path = mws.join(GlobalData.gWorkspace, Path)\r
30fdf114
LG
324\r
325 if IsRelativePath and Path[0] != '.':\r
326 Path = os.path.join('.', Path)\r
327\r
328 return Path\r
329\r
330## CleanString\r
331#\r
332# Remove comments in a string\r
333# Remove spaces\r
334#\r
335# @param Line: The string to be cleaned\r
336# @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT\r
337#\r
338# @retval Path Formatted path\r
339#\r
64b2609f 340def CleanString(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False, BuildOption=False):\r
30fdf114
LG
341 #\r
342 # remove whitespace\r
343 #\r
344 Line = Line.strip();\r
345 #\r
b36d134f 346 # Replace Edk's comment character\r
30fdf114
LG
347 #\r
348 if AllowCppStyleComment:\r
b36d134f 349 Line = Line.replace(DataType.TAB_COMMENT_EDK_SPLIT, CommentCharacter)\r
30fdf114 350 #\r
9053bc51 351 # remove comments, but we should escape comment character in string\r
30fdf114 352 #\r
ea927d2f
FY
353 InDoubleQuoteString = False\r
354 InSingleQuoteString = False\r
b36d134f 355 CommentInString = False\r
9053bc51 356 for Index in range(0, len(Line)):\r
ea927d2f
FY
357 if Line[Index] == '"' and not InSingleQuoteString:\r
358 InDoubleQuoteString = not InDoubleQuoteString\r
359 elif Line[Index] == "'" and not InDoubleQuoteString:\r
360 InSingleQuoteString = not InSingleQuoteString\r
361 elif Line[Index] == CommentCharacter and (InSingleQuoteString or InDoubleQuoteString):\r
b36d134f 362 CommentInString = True\r
ea927d2f 363 elif Line[Index] == CommentCharacter and not (InSingleQuoteString or InDoubleQuoteString):\r
9053bc51 364 Line = Line[0: Index]\r
365 break\r
d40b2ee6 366\r
64b2609f 367 if CommentInString and BuildOption:\r
b36d134f
LG
368 Line = Line.replace('"', '')\r
369 ChIndex = Line.find('#')\r
370 while ChIndex >= 0:\r
371 if GlobalData.gIsWindows:\r
d40b2ee6 372 if ChIndex == 0 or Line[ChIndex - 1] != '^':\r
b36d134f
LG
373 Line = Line[0:ChIndex] + '^' + Line[ChIndex:]\r
374 ChIndex = Line.find('#', ChIndex + 2)\r
375 else:\r
376 ChIndex = Line.find('#', ChIndex + 1)\r
377 else:\r
d40b2ee6 378 if ChIndex == 0 or Line[ChIndex - 1] != '\\':\r
b36d134f
LG
379 Line = Line[0:ChIndex] + '\\' + Line[ChIndex:]\r
380 ChIndex = Line.find('#', ChIndex + 2)\r
381 else:\r
382 ChIndex = Line.find('#', ChIndex + 1)\r
30fdf114
LG
383 #\r
384 # remove whitespace again\r
385 #\r
386 Line = Line.strip();\r
387\r
388 return Line\r
389\r
e56468c0 390## CleanString2\r
391#\r
4afd3d04 392# Split statement with comments in a string\r
e56468c0 393# Remove spaces\r
394#\r
395# @param Line: The string to be cleaned\r
396# @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT\r
397#\r
398# @retval Path Formatted path\r
399#\r
d40b2ee6 400def CleanString2(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False):\r
e56468c0 401 #\r
402 # remove whitespace\r
403 #\r
404 Line = Line.strip();\r
405 #\r
b36d134f 406 # Replace Edk's comment character\r
e56468c0 407 #\r
408 if AllowCppStyleComment:\r
b36d134f 409 Line = Line.replace(DataType.TAB_COMMENT_EDK_SPLIT, CommentCharacter)\r
e56468c0 410 #\r
4afd3d04 411 # separate comments and statements, but we should escape comment character in string\r
e56468c0 412 #\r
ea927d2f
FY
413 InDoubleQuoteString = False\r
414 InSingleQuoteString = False\r
4afd3d04
LG
415 CommentInString = False\r
416 Comment = ''\r
417 for Index in range(0, len(Line)):\r
ea927d2f
FY
418 if Line[Index] == '"' and not InSingleQuoteString:\r
419 InDoubleQuoteString = not InDoubleQuoteString\r
420 elif Line[Index] == "'" and not InDoubleQuoteString:\r
421 InSingleQuoteString = not InSingleQuoteString\r
422 elif Line[Index] == CommentCharacter and (InDoubleQuoteString or InSingleQuoteString):\r
4afd3d04 423 CommentInString = True\r
ea927d2f 424 elif Line[Index] == CommentCharacter and not (InDoubleQuoteString or InSingleQuoteString):\r
4afd3d04
LG
425 Comment = Line[Index:].strip()\r
426 Line = Line[0:Index].strip()\r
427 break\r
e56468c0 428\r
429 return Line, Comment\r
430\r
30fdf114
LG
431## GetMultipleValuesOfKeyFromLines\r
432#\r
433# Parse multiple strings to clean comment and spaces\r
434# The result is saved to KeyValues\r
435#\r
436# @param Lines: The content to be parsed\r
437# @param Key: Reserved\r
438# @param KeyValues: To store data after parsing\r
439# @param CommentCharacter: Comment char, used to ignore comment content\r
440#\r
441# @retval True Successfully executed\r
442#\r
443def GetMultipleValuesOfKeyFromLines(Lines, Key, KeyValues, CommentCharacter):\r
444 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
445 LineList = Lines.split('\n')\r
446 for Line in LineList:\r
447 Line = CleanString(Line, CommentCharacter)\r
448 if Line != '' and Line[0] != CommentCharacter:\r
caf74495 449 KeyValues.append(Line)\r
30fdf114
LG
450\r
451 return True\r
452\r
453## GetDefineValue\r
454#\r
455# Parse a DEFINE statement to get defined value\r
456# DEFINE Key Value\r
457#\r
458# @param String: The content to be parsed\r
459# @param Key: The key of DEFINE statement\r
460# @param CommentCharacter: Comment char, used to ignore comment content\r
461#\r
462# @retval string The defined value\r
463#\r
464def GetDefineValue(String, Key, CommentCharacter):\r
465 String = CleanString(String)\r
466 return String[String.find(Key + ' ') + len(Key + ' ') : ]\r
467\r
08dd311f
LG
468## GetHexVerValue\r
469#\r
470# Get a Hex Version Value\r
471#\r
472# @param VerString: The version string to be parsed\r
473#\r
474#\r
475# @retval: If VerString is incorrectly formatted, return "None" which will break the build.\r
476# If VerString is correctly formatted, return a Hex value of the Version Number (0xmmmmnnnn)\r
477# where mmmm is the major number and nnnn is the adjusted minor number.\r
478#\r
479def GetHexVerValue(VerString):\r
480 VerString = CleanString(VerString)\r
481\r
482 if gHumanReadableVerPatt.match(VerString):\r
483 ValueList = VerString.split('.')\r
484 Major = ValueList[0]\r
485 Minor = ValueList[1]\r
486 if len(Minor) == 1:\r
487 Minor += '0'\r
488 DeciValue = (int(Major) << 16) + int(Minor);\r
d40b2ee6 489 return "0x%08x" % DeciValue\r
08dd311f
LG
490 elif gHexVerPatt.match(VerString):\r
491 return VerString\r
492 else:\r
493 return None\r
494\r
495\r
30fdf114
LG
496## GetSingleValueOfKeyFromLines\r
497#\r
498# Parse multiple strings as below to get value of each definition line\r
499# Key1 = Value1\r
500# Key2 = Value2\r
501# The result is saved to Dictionary\r
502#\r
503# @param Lines: The content to be parsed\r
504# @param Dictionary: To store data after parsing\r
505# @param CommentCharacter: Comment char, be used to ignore comment content\r
506# @param KeySplitCharacter: Key split char, between key name and key value. Key1 = Value1, '=' is the key split char\r
507# @param ValueSplitFlag: Value split flag, be used to decide if has multiple values\r
508# @param ValueSplitCharacter: Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char\r
509#\r
510# @retval True Successfully executed\r
511#\r
512def GetSingleValueOfKeyFromLines(Lines, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):\r
513 Lines = Lines.split('\n')\r
514 Keys = []\r
515 Value = ''\r
516 DefineValues = ['']\r
517 SpecValues = ['']\r
518\r
519 for Line in Lines:\r
520 #\r
521 # Handle DEFINE and SPEC\r
522 #\r
523 if Line.find(DataType.TAB_INF_DEFINES_DEFINE + ' ') > -1:\r
524 if '' in DefineValues:\r
525 DefineValues.remove('')\r
526 DefineValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_DEFINE, CommentCharacter))\r
527 continue\r
528 if Line.find(DataType.TAB_INF_DEFINES_SPEC + ' ') > -1:\r
529 if '' in SpecValues:\r
530 SpecValues.remove('')\r
531 SpecValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_SPEC, CommentCharacter))\r
532 continue\r
533\r
534 #\r
535 # Handle Others\r
536 #\r
537 LineList = Line.split(KeySplitCharacter, 1)\r
538 if len(LineList) >= 2:\r
539 Key = LineList[0].split()\r
540 if len(Key) == 1 and Key[0][0] != CommentCharacter:\r
541 #\r
542 # Remove comments and white spaces\r
543 #\r
544 LineList[1] = CleanString(LineList[1], CommentCharacter)\r
545 if ValueSplitFlag:\r
f8d11e5a 546 Value = list(map(string.strip, LineList[1].split(ValueSplitCharacter)))\r
30fdf114
LG
547 else:\r
548 Value = CleanString(LineList[1], CommentCharacter).splitlines()\r
549\r
550 if Key[0] in Dictionary:\r
551 if Key[0] not in Keys:\r
552 Dictionary[Key[0]] = Value\r
553 Keys.append(Key[0])\r
554 else:\r
555 Dictionary[Key[0]].extend(Value)\r
556 else:\r
557 Dictionary[DataType.TAB_INF_DEFINES_MACRO][Key[0]] = Value[0]\r
558\r
559 if DefineValues == []:\r
560 DefineValues = ['']\r
561 if SpecValues == []:\r
562 SpecValues = ['']\r
563 Dictionary[DataType.TAB_INF_DEFINES_DEFINE] = DefineValues\r
564 Dictionary[DataType.TAB_INF_DEFINES_SPEC] = SpecValues\r
565\r
566 return True\r
567\r
568## The content to be parsed\r
569#\r
570# Do pre-check for a file before it is parsed\r
571# Check $()\r
572# Check []\r
573#\r
574# @param FileName: Used for error report\r
575# @param FileContent: File content to be parsed\r
576# @param SupSectionTag: Used for error report\r
577#\r
578def PreCheck(FileName, FileContent, SupSectionTag):\r
579 LineNo = 0\r
580 IsFailed = False\r
581 NewFileContent = ''\r
582 for Line in FileContent.splitlines():\r
583 LineNo = LineNo + 1\r
584 #\r
585 # Clean current line\r
586 #\r
587 Line = CleanString(Line)\r
588\r
589 #\r
590 # Remove commented line\r
591 #\r
592 if Line.find(DataType.TAB_COMMA_SPLIT) == 0:\r
593 Line = ''\r
594 #\r
595 # Check $()\r
596 #\r
597 if Line.find('$') > -1:\r
598 if Line.find('$(') < 0 or Line.find(')') < 0:\r
d40b2ee6 599 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
600\r
601 #\r
602 # Check []\r
603 #\r
604 if Line.find('[') > -1 or Line.find(']') > -1:\r
605 #\r
606 # Only get one '[' or one ']'\r
607 #\r
608 if not (Line.find('[') > -1 and Line.find(']') > -1):\r
d40b2ee6 609 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
610\r
611 #\r
612 # Regenerate FileContent\r
613 #\r
1ccc4d89 614 NewFileContent = NewFileContent + Line + '\r\n'\r
30fdf114
LG
615\r
616 if IsFailed:\r
d40b2ee6 617 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
618\r
619 return NewFileContent\r
620\r
621## CheckFileType\r
622#\r
623# Check if the Filename is including ExtName\r
624# Return True if it exists\r
625# Raise a error message if it not exists\r
626#\r
627# @param CheckFilename: Name of the file to be checked\r
628# @param ExtName: Ext name of the file to be checked\r
629# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
630# @param SectionName: Used for error report\r
631# @param Line: The line in container file which defines the file to be checked\r
632#\r
633# @retval True The file type is correct\r
634#\r
d40b2ee6 635def CheckFileType(CheckFilename, ExtName, ContainerFilename, SectionName, Line, LineNo= -1):\r
4231a819 636 if CheckFilename != '' and CheckFilename is not None:\r
30fdf114
LG
637 (Root, Ext) = os.path.splitext(CheckFilename)\r
638 if Ext.upper() != ExtName.upper():\r
639 ContainerFile = open(ContainerFilename, 'r').read()\r
640 if LineNo == -1:\r
641 LineNo = GetLineNo(ContainerFile, Line)\r
642 ErrorMsg = "Invalid %s. '%s' is found, but '%s' file is needed" % (SectionName, CheckFilename, ExtName)\r
643 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, Line=LineNo,\r
d40b2ee6 644 File=ContainerFilename, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
645\r
646 return True\r
647\r
648## CheckFileExist\r
649#\r
650# Check if the file exists\r
651# Return True if it exists\r
652# Raise a error message if it not exists\r
653#\r
654# @param CheckFilename: Name of the file to be checked\r
655# @param WorkspaceDir: Current workspace dir\r
656# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
657# @param SectionName: Used for error report\r
658# @param Line: The line in container file which defines the file to be checked\r
659#\r
660# @retval The file full path if the file exists\r
661#\r
d40b2ee6 662def CheckFileExist(WorkspaceDir, CheckFilename, ContainerFilename, SectionName, Line, LineNo= -1):\r
30fdf114 663 CheckFile = ''\r
4231a819 664 if CheckFilename != '' and CheckFilename is not None:\r
30fdf114
LG
665 CheckFile = WorkspaceFile(WorkspaceDir, CheckFilename)\r
666 if not os.path.isfile(CheckFile):\r
667 ContainerFile = open(ContainerFilename, 'r').read()\r
668 if LineNo == -1:\r
669 LineNo = GetLineNo(ContainerFile, Line)\r
670 ErrorMsg = "Can't find file '%s' defined in section '%s'" % (CheckFile, SectionName)\r
671 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg,\r
d40b2ee6 672 File=ContainerFilename, Line=LineNo, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
673\r
674 return CheckFile\r
675\r
676## GetLineNo\r
677#\r
678# Find the index of a line in a file\r
679#\r
680# @param FileContent: Search scope\r
681# @param Line: Search key\r
682#\r
683# @retval int Index of the line\r
684# @retval -1 The line is not found\r
685#\r
d40b2ee6 686def GetLineNo(FileContent, Line, IsIgnoreComment=True):\r
30fdf114
LG
687 LineList = FileContent.splitlines()\r
688 for Index in range(len(LineList)):\r
689 if LineList[Index].find(Line) > -1:\r
690 #\r
691 # Ignore statement in comment\r
692 #\r
693 if IsIgnoreComment:\r
694 if LineList[Index].strip()[0] == DataType.TAB_COMMENT_SPLIT:\r
695 continue\r
696 return Index + 1\r
697\r
698 return -1\r
699\r
700## RaiseParserError\r
701#\r
702# Raise a parser error\r
703#\r
704# @param Line: String which has error\r
705# @param Section: Used for error report\r
706# @param File: File which has the string\r
707# @param Format: Correct format\r
708#\r
d40b2ee6 709def RaiseParserError(Line, Section, File, Format='', LineNo= -1):\r
30fdf114
LG
710 if LineNo == -1:\r
711 LineNo = GetLineNo(open(os.path.normpath(File), 'r').read(), Line)\r
712 ErrorMsg = "Invalid statement '%s' is found in section '%s'" % (Line, Section)\r
713 if Format != '':\r
714 Format = "Correct format is " + Format\r
d40b2ee6 715 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, File=File, Line=LineNo, ExtraData=Format, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
716\r
717## WorkspaceFile\r
718#\r
719# Return a full path with workspace dir\r
720#\r
721# @param WorkspaceDir: Workspace dir\r
722# @param Filename: Relative file name\r
723#\r
724# @retval string A full path\r
725#\r
726def WorkspaceFile(WorkspaceDir, Filename):\r
05cc51ad 727 return mws.join(NormPath(WorkspaceDir), NormPath(Filename))\r
30fdf114
LG
728\r
729## Split string\r
730#\r
fb0b35e0 731# Remove '"' which startswith and endswith string\r
30fdf114 732#\r
fb0b35e0 733# @param String: The string need to be split\r
30fdf114
LG
734#\r
735# @retval String: The string after removed '""'\r
736#\r
737def SplitString(String):\r
738 if String.startswith('\"'):\r
739 String = String[1:]\r
740 if String.endswith('\"'):\r
741 String = String[:-1]\r
742\r
743 return String\r
744\r
745## Convert To Sql String\r
746#\r
747# 1. Replace "'" with "''" in each item of StringList\r
748#\r
749# @param StringList: A list for strings to be converted\r
750#\r
751def ConvertToSqlString(StringList):\r
f8d11e5a 752 return list(map(lambda s: s.replace("'", "''"), StringList))\r
30fdf114
LG
753\r
754## Convert To Sql String\r
755#\r
756# 1. Replace "'" with "''" in the String\r
757#\r
758# @param String: A String to be converted\r
759#\r
760def ConvertToSqlString2(String):\r
761 return String.replace("'", "''")\r
762\r
763#\r
764# Remove comment block\r
765#\r
766def RemoveBlockComment(Lines):\r
767 IsFindBlockComment = False\r
768 IsFindBlockCode = False\r
769 ReservedLine = ''\r
770 NewLines = []\r
771\r
772 for Line in Lines:\r
773 Line = Line.strip()\r
774 #\r
775 # Remove comment block\r
776 #\r
b36d134f 777 if Line.find(DataType.TAB_COMMENT_EDK_START) > -1:\r
d40b2ee6 778 ReservedLine = GetSplitList(Line, DataType.TAB_COMMENT_EDK_START, 1)[0]\r
30fdf114 779 IsFindBlockComment = True\r
b36d134f 780 if Line.find(DataType.TAB_COMMENT_EDK_END) > -1:\r
d40b2ee6 781 Line = ReservedLine + GetSplitList(Line, DataType.TAB_COMMENT_EDK_END, 1)[1]\r
30fdf114
LG
782 ReservedLine = ''\r
783 IsFindBlockComment = False\r
784 if IsFindBlockComment:\r
785 NewLines.append('')\r
786 continue\r
787\r
788 NewLines.append(Line)\r
789 return NewLines\r
790\r
791#\r
792# Get String of a List\r
793#\r
d40b2ee6 794def GetStringOfList(List, Split=' '):\r
0d1f5b2b 795 if not isinstance(List, type([])):\r
30fdf114
LG
796 return List\r
797 Str = ''\r
798 for Item in List:\r
799 Str = Str + Item + Split\r
800\r
801 return Str.strip()\r
802\r
803#\r
804# Get HelpTextList from HelpTextClassList\r
805#\r
806def GetHelpTextList(HelpTextClassList):\r
807 List = []\r
808 if HelpTextClassList:\r
809 for HelpText in HelpTextClassList:\r
810 if HelpText.String.endswith('\n'):\r
811 HelpText.String = HelpText.String[0: len(HelpText.String) - len('\n')]\r
812 List.extend(HelpText.String.split('\n'))\r
813\r
814 return List\r
815\r
816def StringToArray(String):\r
d943b0c3 817 if String.startswith('L"'):\r
30fdf114 818 if String == "L\"\"":\r
6ee9c689 819 return "{0x00,0x00}"\r
30fdf114 820 else:\r
8252e6bf 821 return "{%s,0x00,0x00}" % ",".join("0x%02x,0x00" % ord(C) for C in String[2:-1])\r
30fdf114
LG
822 elif String.startswith('"'):\r
823 if String == "\"\"":\r
2bc3256c 824 return "{0x00,0x00}"\r
30fdf114 825 else:\r
2bc3256c
LG
826 StringLen = len(String[1:-1])\r
827 if StringLen % 2:\r
8252e6bf 828 return "{%s,0x00}" % ",".join("0x%02x" % ord(C) for C in String[1:-1])\r
2bc3256c 829 else:\r
8252e6bf 830 return "{%s,0x00,0x00}" % ",".join("0x%02x" % ord(C) for C in String[1:-1])\r
2bc3256c 831 elif String.startswith('{'):\r
4cf022f2 832 return "{%s}" % ",".join(C.strip() for C in String[1:-1].split(','))\r
30fdf114 833 else:\r
2bc3256c 834 if len(String.split()) % 2:\r
6ee9c689 835 return '{%s,0}' % ','.join(String.split())\r
2bc3256c 836 else:\r
6ee9c689 837 return '{%s,0,0}' % ','.join(String.split())\r
30fdf114
LG
838\r
839def StringArrayLength(String):\r
d943b0c3 840 if String.startswith('L"'):\r
30fdf114
LG
841 return (len(String) - 3 + 1) * 2\r
842 elif String.startswith('"'):\r
843 return (len(String) - 2 + 1)\r
844 else:\r
845 return len(String.split()) + 1\r
d40b2ee6 846\r
30fdf114
LG
847def RemoveDupOption(OptionString, Which="/I", Against=None):\r
848 OptionList = OptionString.split()\r
849 ValueList = []\r
850 if Against:\r
851 ValueList += Against\r
852 for Index in range(len(OptionList)):\r
853 Opt = OptionList[Index]\r
854 if not Opt.startswith(Which):\r
855 continue\r
856 if len(Opt) > len(Which):\r
857 Val = Opt[len(Which):]\r
858 else:\r
859 Val = ""\r
860 if Val in ValueList:\r
861 OptionList[Index] = ""\r
862 else:\r
863 ValueList.append(Val)\r
864 return " ".join(OptionList)\r
865\r
866##\r
867#\r
868# This acts like the main() function for the script, unless it is 'import'ed into another\r
869# script.\r
870#\r
871if __name__ == '__main__':\r
872 pass\r
873\r