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