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