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