]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/Common/StringUtils.py
BaseTools: Replace BSD License with BSD+Patent License
[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
d40b2ee6 246def ReplaceMacros(StringList, MacroDefinitions={}, SelfReplacement=False):\r
30fdf114
LG
247 NewList = []\r
248 for String in StringList:\r
0d1f5b2b 249 if isinstance(String, type('')):\r
30fdf114
LG
250 NewList.append(ReplaceMacro(String, MacroDefinitions, SelfReplacement))\r
251 else:\r
252 NewList.append(String)\r
253\r
254 return NewList\r
255\r
256## Replace macro in string\r
257#\r
258# This method replace macros used in given string. The macros are given in a\r
259# dictionary.\r
260#\r
261# @param String String to be processed\r
262# @param MacroDefinitions The macro definitions in the form of dictionary\r
263# @param SelfReplacement To decide whether replace un-defined macro to ''\r
264#\r
265# @retval string The string whose macros are replaced\r
266#\r
0d2711a6 267def ReplaceMacro(String, MacroDefinitions={}, SelfReplacement=False, RaiseError=False):\r
30fdf114 268 LastString = String\r
0d2711a6
LG
269 while String and MacroDefinitions:\r
270 MacroUsed = GlobalData.gMacroRefPattern.findall(String)\r
30fdf114
LG
271 # no macro found in String, stop replacing\r
272 if len(MacroUsed) == 0:\r
273 break\r
274\r
275 for Macro in MacroUsed:\r
276 if Macro not in MacroDefinitions:\r
0d2711a6
LG
277 if RaiseError:\r
278 raise SymbolNotFound("%s not defined" % Macro)\r
30fdf114
LG
279 if SelfReplacement:\r
280 String = String.replace("$(%s)" % Macro, '')\r
281 continue\r
ce2f5940
HC
282 if "$(%s)" % Macro not in MacroDefinitions[Macro]:\r
283 String = String.replace("$(%s)" % Macro, MacroDefinitions[Macro])\r
30fdf114
LG
284 # in case there's macro not defined\r
285 if String == LastString:\r
286 break\r
287 LastString = String\r
288\r
289 return String\r
290\r
291## NormPath\r
292#\r
293# Create a normal path\r
fb0b35e0 294# And replace DEFINE in the path\r
30fdf114
LG
295#\r
296# @param Path: The input value for Path to be converted\r
297# @param Defines: A set for DEFINE statement\r
298#\r
299# @retval Path Formatted path\r
300#\r
d40b2ee6 301def NormPath(Path, Defines={}):\r
30fdf114
LG
302 IsRelativePath = False\r
303 if Path:\r
304 if Path[0] == '.':\r
305 IsRelativePath = True\r
306 #\r
307 # Replace with Define\r
308 #\r
309 if Defines:\r
310 Path = ReplaceMacro(Path, Defines)\r
311 #\r
312 # To local path format\r
313 #\r
314 Path = os.path.normpath(Path)\r
97058144 315 if Path.startswith(GlobalData.gWorkspace) and not Path.startswith(GlobalData.gBuildDirectory) and not os.path.exists(Path):\r
05cc51ad
LY
316 Path = Path[len (GlobalData.gWorkspace):]\r
317 if Path[0] == os.path.sep:\r
318 Path = Path[1:]\r
319 Path = mws.join(GlobalData.gWorkspace, Path)\r
30fdf114
LG
320\r
321 if IsRelativePath and Path[0] != '.':\r
322 Path = os.path.join('.', Path)\r
323\r
324 return Path\r
325\r
326## CleanString\r
327#\r
328# Remove comments in a string\r
329# Remove spaces\r
330#\r
331# @param Line: The string to be cleaned\r
332# @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT\r
333#\r
334# @retval Path Formatted path\r
335#\r
64b2609f 336def CleanString(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False, BuildOption=False):\r
30fdf114
LG
337 #\r
338 # remove whitespace\r
339 #\r
340 Line = Line.strip();\r
341 #\r
b36d134f 342 # Replace Edk's comment character\r
30fdf114
LG
343 #\r
344 if AllowCppStyleComment:\r
b36d134f 345 Line = Line.replace(DataType.TAB_COMMENT_EDK_SPLIT, CommentCharacter)\r
30fdf114 346 #\r
9053bc51 347 # remove comments, but we should escape comment character in string\r
30fdf114 348 #\r
ea927d2f
FY
349 InDoubleQuoteString = False\r
350 InSingleQuoteString = False\r
b36d134f 351 CommentInString = False\r
9053bc51 352 for Index in range(0, len(Line)):\r
ea927d2f
FY
353 if Line[Index] == '"' and not InSingleQuoteString:\r
354 InDoubleQuoteString = not InDoubleQuoteString\r
355 elif Line[Index] == "'" and not InDoubleQuoteString:\r
356 InSingleQuoteString = not InSingleQuoteString\r
357 elif Line[Index] == CommentCharacter and (InSingleQuoteString or InDoubleQuoteString):\r
b36d134f 358 CommentInString = True\r
ea927d2f 359 elif Line[Index] == CommentCharacter and not (InSingleQuoteString or InDoubleQuoteString):\r
9053bc51 360 Line = Line[0: Index]\r
361 break\r
d40b2ee6 362\r
64b2609f 363 if CommentInString and BuildOption:\r
b36d134f
LG
364 Line = Line.replace('"', '')\r
365 ChIndex = Line.find('#')\r
366 while ChIndex >= 0:\r
367 if GlobalData.gIsWindows:\r
d40b2ee6 368 if ChIndex == 0 or Line[ChIndex - 1] != '^':\r
b36d134f
LG
369 Line = Line[0:ChIndex] + '^' + Line[ChIndex:]\r
370 ChIndex = Line.find('#', ChIndex + 2)\r
371 else:\r
372 ChIndex = Line.find('#', ChIndex + 1)\r
373 else:\r
d40b2ee6 374 if ChIndex == 0 or Line[ChIndex - 1] != '\\':\r
b36d134f
LG
375 Line = Line[0:ChIndex] + '\\' + Line[ChIndex:]\r
376 ChIndex = Line.find('#', ChIndex + 2)\r
377 else:\r
378 ChIndex = Line.find('#', ChIndex + 1)\r
30fdf114
LG
379 #\r
380 # remove whitespace again\r
381 #\r
382 Line = Line.strip();\r
383\r
384 return Line\r
385\r
e56468c0 386## CleanString2\r
387#\r
4afd3d04 388# Split statement with comments in a string\r
e56468c0 389# Remove spaces\r
390#\r
391# @param Line: The string to be cleaned\r
392# @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT\r
393#\r
394# @retval Path Formatted path\r
395#\r
d40b2ee6 396def CleanString2(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False):\r
e56468c0 397 #\r
398 # remove whitespace\r
399 #\r
400 Line = Line.strip();\r
401 #\r
b36d134f 402 # Replace Edk's comment character\r
e56468c0 403 #\r
404 if AllowCppStyleComment:\r
b36d134f 405 Line = Line.replace(DataType.TAB_COMMENT_EDK_SPLIT, CommentCharacter)\r
e56468c0 406 #\r
4afd3d04 407 # separate comments and statements, but we should escape comment character in string\r
e56468c0 408 #\r
ea927d2f
FY
409 InDoubleQuoteString = False\r
410 InSingleQuoteString = False\r
4afd3d04
LG
411 CommentInString = False\r
412 Comment = ''\r
413 for Index in range(0, len(Line)):\r
ea927d2f
FY
414 if Line[Index] == '"' and not InSingleQuoteString:\r
415 InDoubleQuoteString = not InDoubleQuoteString\r
416 elif Line[Index] == "'" and not InDoubleQuoteString:\r
417 InSingleQuoteString = not InSingleQuoteString\r
418 elif Line[Index] == CommentCharacter and (InDoubleQuoteString or InSingleQuoteString):\r
4afd3d04 419 CommentInString = True\r
ea927d2f 420 elif Line[Index] == CommentCharacter and not (InDoubleQuoteString or InSingleQuoteString):\r
4afd3d04
LG
421 Comment = Line[Index:].strip()\r
422 Line = Line[0:Index].strip()\r
423 break\r
e56468c0 424\r
425 return Line, Comment\r
426\r
30fdf114
LG
427## GetMultipleValuesOfKeyFromLines\r
428#\r
429# Parse multiple strings to clean comment and spaces\r
430# The result is saved to KeyValues\r
431#\r
432# @param Lines: The content to be parsed\r
433# @param Key: Reserved\r
434# @param KeyValues: To store data after parsing\r
435# @param CommentCharacter: Comment char, used to ignore comment content\r
436#\r
437# @retval True Successfully executed\r
438#\r
439def GetMultipleValuesOfKeyFromLines(Lines, Key, KeyValues, CommentCharacter):\r
440 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
441 LineList = Lines.split('\n')\r
442 for Line in LineList:\r
443 Line = CleanString(Line, CommentCharacter)\r
444 if Line != '' and Line[0] != CommentCharacter:\r
caf74495 445 KeyValues.append(Line)\r
30fdf114
LG
446\r
447 return True\r
448\r
449## GetDefineValue\r
450#\r
451# Parse a DEFINE statement to get defined value\r
452# DEFINE Key Value\r
453#\r
454# @param String: The content to be parsed\r
455# @param Key: The key of DEFINE statement\r
456# @param CommentCharacter: Comment char, used to ignore comment content\r
457#\r
458# @retval string The defined value\r
459#\r
460def GetDefineValue(String, Key, CommentCharacter):\r
461 String = CleanString(String)\r
462 return String[String.find(Key + ' ') + len(Key + ' ') : ]\r
463\r
08dd311f
LG
464## GetHexVerValue\r
465#\r
466# Get a Hex Version Value\r
467#\r
468# @param VerString: The version string to be parsed\r
469#\r
470#\r
471# @retval: If VerString is incorrectly formatted, return "None" which will break the build.\r
472# If VerString is correctly formatted, return a Hex value of the Version Number (0xmmmmnnnn)\r
473# where mmmm is the major number and nnnn is the adjusted minor number.\r
474#\r
475def GetHexVerValue(VerString):\r
476 VerString = CleanString(VerString)\r
477\r
478 if gHumanReadableVerPatt.match(VerString):\r
479 ValueList = VerString.split('.')\r
480 Major = ValueList[0]\r
481 Minor = ValueList[1]\r
482 if len(Minor) == 1:\r
483 Minor += '0'\r
484 DeciValue = (int(Major) << 16) + int(Minor);\r
d40b2ee6 485 return "0x%08x" % DeciValue\r
08dd311f
LG
486 elif gHexVerPatt.match(VerString):\r
487 return VerString\r
488 else:\r
489 return None\r
490\r
491\r
30fdf114
LG
492## GetSingleValueOfKeyFromLines\r
493#\r
494# Parse multiple strings as below to get value of each definition line\r
495# Key1 = Value1\r
496# Key2 = Value2\r
497# The result is saved to Dictionary\r
498#\r
499# @param Lines: The content to be parsed\r
500# @param Dictionary: To store data after parsing\r
501# @param CommentCharacter: Comment char, be used to ignore comment content\r
502# @param KeySplitCharacter: Key split char, between key name and key value. Key1 = Value1, '=' is the key split char\r
503# @param ValueSplitFlag: Value split flag, be used to decide if has multiple values\r
504# @param ValueSplitCharacter: Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char\r
505#\r
506# @retval True Successfully executed\r
507#\r
508def GetSingleValueOfKeyFromLines(Lines, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):\r
509 Lines = Lines.split('\n')\r
510 Keys = []\r
511 Value = ''\r
512 DefineValues = ['']\r
513 SpecValues = ['']\r
514\r
515 for Line in Lines:\r
516 #\r
517 # Handle DEFINE and SPEC\r
518 #\r
519 if Line.find(DataType.TAB_INF_DEFINES_DEFINE + ' ') > -1:\r
520 if '' in DefineValues:\r
521 DefineValues.remove('')\r
522 DefineValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_DEFINE, CommentCharacter))\r
523 continue\r
524 if Line.find(DataType.TAB_INF_DEFINES_SPEC + ' ') > -1:\r
525 if '' in SpecValues:\r
526 SpecValues.remove('')\r
527 SpecValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_SPEC, CommentCharacter))\r
528 continue\r
529\r
530 #\r
531 # Handle Others\r
532 #\r
533 LineList = Line.split(KeySplitCharacter, 1)\r
534 if len(LineList) >= 2:\r
535 Key = LineList[0].split()\r
536 if len(Key) == 1 and Key[0][0] != CommentCharacter:\r
537 #\r
538 # Remove comments and white spaces\r
539 #\r
540 LineList[1] = CleanString(LineList[1], CommentCharacter)\r
541 if ValueSplitFlag:\r
f8d11e5a 542 Value = list(map(string.strip, LineList[1].split(ValueSplitCharacter)))\r
30fdf114
LG
543 else:\r
544 Value = CleanString(LineList[1], CommentCharacter).splitlines()\r
545\r
546 if Key[0] in Dictionary:\r
547 if Key[0] not in Keys:\r
548 Dictionary[Key[0]] = Value\r
549 Keys.append(Key[0])\r
550 else:\r
551 Dictionary[Key[0]].extend(Value)\r
552 else:\r
553 Dictionary[DataType.TAB_INF_DEFINES_MACRO][Key[0]] = Value[0]\r
554\r
555 if DefineValues == []:\r
556 DefineValues = ['']\r
557 if SpecValues == []:\r
558 SpecValues = ['']\r
559 Dictionary[DataType.TAB_INF_DEFINES_DEFINE] = DefineValues\r
560 Dictionary[DataType.TAB_INF_DEFINES_SPEC] = SpecValues\r
561\r
562 return True\r
563\r
564## The content to be parsed\r
565#\r
566# Do pre-check for a file before it is parsed\r
567# Check $()\r
568# Check []\r
569#\r
570# @param FileName: Used for error report\r
571# @param FileContent: File content to be parsed\r
572# @param SupSectionTag: Used for error report\r
573#\r
574def PreCheck(FileName, FileContent, SupSectionTag):\r
575 LineNo = 0\r
576 IsFailed = False\r
577 NewFileContent = ''\r
578 for Line in FileContent.splitlines():\r
579 LineNo = LineNo + 1\r
580 #\r
581 # Clean current line\r
582 #\r
583 Line = CleanString(Line)\r
584\r
585 #\r
586 # Remove commented line\r
587 #\r
588 if Line.find(DataType.TAB_COMMA_SPLIT) == 0:\r
589 Line = ''\r
590 #\r
591 # Check $()\r
592 #\r
593 if Line.find('$') > -1:\r
594 if Line.find('$(') < 0 or Line.find(')') < 0:\r
d40b2ee6 595 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
596\r
597 #\r
598 # Check []\r
599 #\r
600 if Line.find('[') > -1 or Line.find(']') > -1:\r
601 #\r
602 # Only get one '[' or one ']'\r
603 #\r
604 if not (Line.find('[') > -1 and Line.find(']') > -1):\r
d40b2ee6 605 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
606\r
607 #\r
608 # Regenerate FileContent\r
609 #\r
1ccc4d89 610 NewFileContent = NewFileContent + Line + '\r\n'\r
30fdf114
LG
611\r
612 if IsFailed:\r
d40b2ee6 613 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
614\r
615 return NewFileContent\r
616\r
617## CheckFileType\r
618#\r
619# Check if the Filename is including ExtName\r
620# Return True if it exists\r
621# Raise a error message if it not exists\r
622#\r
623# @param CheckFilename: Name of the file to be checked\r
624# @param ExtName: Ext name of the file to be checked\r
625# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
626# @param SectionName: Used for error report\r
627# @param Line: The line in container file which defines the file to be checked\r
628#\r
629# @retval True The file type is correct\r
630#\r
d40b2ee6 631def CheckFileType(CheckFilename, ExtName, ContainerFilename, SectionName, Line, LineNo= -1):\r
4231a819 632 if CheckFilename != '' and CheckFilename is not None:\r
30fdf114
LG
633 (Root, Ext) = os.path.splitext(CheckFilename)\r
634 if Ext.upper() != ExtName.upper():\r
635 ContainerFile = open(ContainerFilename, 'r').read()\r
636 if LineNo == -1:\r
637 LineNo = GetLineNo(ContainerFile, Line)\r
638 ErrorMsg = "Invalid %s. '%s' is found, but '%s' file is needed" % (SectionName, CheckFilename, ExtName)\r
639 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, Line=LineNo,\r
d40b2ee6 640 File=ContainerFilename, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
641\r
642 return True\r
643\r
644## CheckFileExist\r
645#\r
646# Check if the file exists\r
647# Return True if it exists\r
648# Raise a error message if it not exists\r
649#\r
650# @param CheckFilename: Name of the file to be checked\r
651# @param WorkspaceDir: Current workspace dir\r
652# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
653# @param SectionName: Used for error report\r
654# @param Line: The line in container file which defines the file to be checked\r
655#\r
656# @retval The file full path if the file exists\r
657#\r
d40b2ee6 658def CheckFileExist(WorkspaceDir, CheckFilename, ContainerFilename, SectionName, Line, LineNo= -1):\r
30fdf114 659 CheckFile = ''\r
4231a819 660 if CheckFilename != '' and CheckFilename is not None:\r
30fdf114
LG
661 CheckFile = WorkspaceFile(WorkspaceDir, CheckFilename)\r
662 if not os.path.isfile(CheckFile):\r
663 ContainerFile = open(ContainerFilename, 'r').read()\r
664 if LineNo == -1:\r
665 LineNo = GetLineNo(ContainerFile, Line)\r
666 ErrorMsg = "Can't find file '%s' defined in section '%s'" % (CheckFile, SectionName)\r
667 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg,\r
d40b2ee6 668 File=ContainerFilename, Line=LineNo, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
669\r
670 return CheckFile\r
671\r
672## GetLineNo\r
673#\r
674# Find the index of a line in a file\r
675#\r
676# @param FileContent: Search scope\r
677# @param Line: Search key\r
678#\r
679# @retval int Index of the line\r
680# @retval -1 The line is not found\r
681#\r
d40b2ee6 682def GetLineNo(FileContent, Line, IsIgnoreComment=True):\r
30fdf114
LG
683 LineList = FileContent.splitlines()\r
684 for Index in range(len(LineList)):\r
685 if LineList[Index].find(Line) > -1:\r
686 #\r
687 # Ignore statement in comment\r
688 #\r
689 if IsIgnoreComment:\r
690 if LineList[Index].strip()[0] == DataType.TAB_COMMENT_SPLIT:\r
691 continue\r
692 return Index + 1\r
693\r
694 return -1\r
695\r
696## RaiseParserError\r
697#\r
698# Raise a parser error\r
699#\r
700# @param Line: String which has error\r
701# @param Section: Used for error report\r
702# @param File: File which has the string\r
703# @param Format: Correct format\r
704#\r
d40b2ee6 705def RaiseParserError(Line, Section, File, Format='', LineNo= -1):\r
30fdf114
LG
706 if LineNo == -1:\r
707 LineNo = GetLineNo(open(os.path.normpath(File), 'r').read(), Line)\r
708 ErrorMsg = "Invalid statement '%s' is found in section '%s'" % (Line, Section)\r
709 if Format != '':\r
710 Format = "Correct format is " + Format\r
d40b2ee6 711 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, File=File, Line=LineNo, ExtraData=Format, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
712\r
713## WorkspaceFile\r
714#\r
715# Return a full path with workspace dir\r
716#\r
717# @param WorkspaceDir: Workspace dir\r
718# @param Filename: Relative file name\r
719#\r
720# @retval string A full path\r
721#\r
722def WorkspaceFile(WorkspaceDir, Filename):\r
05cc51ad 723 return mws.join(NormPath(WorkspaceDir), NormPath(Filename))\r
30fdf114
LG
724\r
725## Split string\r
726#\r
fb0b35e0 727# Remove '"' which startswith and endswith string\r
30fdf114 728#\r
fb0b35e0 729# @param String: The string need to be split\r
30fdf114
LG
730#\r
731# @retval String: The string after removed '""'\r
732#\r
733def SplitString(String):\r
734 if String.startswith('\"'):\r
735 String = String[1:]\r
736 if String.endswith('\"'):\r
737 String = String[:-1]\r
738\r
739 return String\r
740\r
741## Convert To Sql String\r
742#\r
743# 1. Replace "'" with "''" in each item of StringList\r
744#\r
745# @param StringList: A list for strings to be converted\r
746#\r
747def ConvertToSqlString(StringList):\r
f8d11e5a 748 return list(map(lambda s: s.replace("'", "''"), StringList))\r
30fdf114
LG
749\r
750## Convert To Sql String\r
751#\r
752# 1. Replace "'" with "''" in the String\r
753#\r
754# @param String: A String to be converted\r
755#\r
756def ConvertToSqlString2(String):\r
757 return String.replace("'", "''")\r
758\r
759#\r
760# Remove comment block\r
761#\r
762def RemoveBlockComment(Lines):\r
763 IsFindBlockComment = False\r
764 IsFindBlockCode = False\r
765 ReservedLine = ''\r
766 NewLines = []\r
767\r
768 for Line in Lines:\r
769 Line = Line.strip()\r
770 #\r
771 # Remove comment block\r
772 #\r
b36d134f 773 if Line.find(DataType.TAB_COMMENT_EDK_START) > -1:\r
d40b2ee6 774 ReservedLine = GetSplitList(Line, DataType.TAB_COMMENT_EDK_START, 1)[0]\r
30fdf114 775 IsFindBlockComment = True\r
b36d134f 776 if Line.find(DataType.TAB_COMMENT_EDK_END) > -1:\r
d40b2ee6 777 Line = ReservedLine + GetSplitList(Line, DataType.TAB_COMMENT_EDK_END, 1)[1]\r
30fdf114
LG
778 ReservedLine = ''\r
779 IsFindBlockComment = False\r
780 if IsFindBlockComment:\r
781 NewLines.append('')\r
782 continue\r
783\r
784 NewLines.append(Line)\r
785 return NewLines\r
786\r
787#\r
788# Get String of a List\r
789#\r
d40b2ee6 790def GetStringOfList(List, Split=' '):\r
0d1f5b2b 791 if not isinstance(List, type([])):\r
30fdf114
LG
792 return List\r
793 Str = ''\r
794 for Item in List:\r
795 Str = Str + Item + Split\r
796\r
797 return Str.strip()\r
798\r
799#\r
800# Get HelpTextList from HelpTextClassList\r
801#\r
802def GetHelpTextList(HelpTextClassList):\r
803 List = []\r
804 if HelpTextClassList:\r
805 for HelpText in HelpTextClassList:\r
806 if HelpText.String.endswith('\n'):\r
807 HelpText.String = HelpText.String[0: len(HelpText.String) - len('\n')]\r
808 List.extend(HelpText.String.split('\n'))\r
809\r
810 return List\r
811\r
812def StringToArray(String):\r
d943b0c3 813 if String.startswith('L"'):\r
30fdf114 814 if String == "L\"\"":\r
6ee9c689 815 return "{0x00,0x00}"\r
30fdf114 816 else:\r
8252e6bf 817 return "{%s,0x00,0x00}" % ",".join("0x%02x,0x00" % ord(C) for C in String[2:-1])\r
30fdf114
LG
818 elif String.startswith('"'):\r
819 if String == "\"\"":\r
2bc3256c 820 return "{0x00,0x00}"\r
30fdf114 821 else:\r
2bc3256c
LG
822 StringLen = len(String[1:-1])\r
823 if StringLen % 2:\r
8252e6bf 824 return "{%s,0x00}" % ",".join("0x%02x" % ord(C) for C in String[1:-1])\r
2bc3256c 825 else:\r
8252e6bf 826 return "{%s,0x00,0x00}" % ",".join("0x%02x" % ord(C) for C in String[1:-1])\r
2bc3256c 827 elif String.startswith('{'):\r
4cf022f2 828 return "{%s}" % ",".join(C.strip() for C in String[1:-1].split(','))\r
30fdf114 829 else:\r
2bc3256c 830 if len(String.split()) % 2:\r
6ee9c689 831 return '{%s,0}' % ','.join(String.split())\r
2bc3256c 832 else:\r
6ee9c689 833 return '{%s,0,0}' % ','.join(String.split())\r
30fdf114
LG
834\r
835def StringArrayLength(String):\r
d943b0c3 836 if String.startswith('L"'):\r
30fdf114
LG
837 return (len(String) - 3 + 1) * 2\r
838 elif String.startswith('"'):\r
839 return (len(String) - 2 + 1)\r
840 else:\r
841 return len(String.split()) + 1\r
d40b2ee6 842\r
30fdf114
LG
843def RemoveDupOption(OptionString, Which="/I", Against=None):\r
844 OptionList = OptionString.split()\r
845 ValueList = []\r
846 if Against:\r
847 ValueList += Against\r
848 for Index in range(len(OptionList)):\r
849 Opt = OptionList[Index]\r
850 if not Opt.startswith(Which):\r
851 continue\r
852 if len(Opt) > len(Which):\r
853 Val = Opt[len(Which):]\r
854 else:\r
855 Val = ""\r
856 if Val in ValueList:\r
857 OptionList[Index] = ""\r
858 else:\r
859 ValueList.append(Val)\r
860 return " ".join(OptionList)\r
861\r
862##\r
863#\r
864# This acts like the main() function for the script, unless it is 'import'ed into another\r
865# script.\r
866#\r
867if __name__ == '__main__':\r
868 pass\r
869\r