]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/Common/String.py
Fix Build fail for NT32 platform.
[mirror_edk2.git] / BaseTools / Source / Python / Common / String.py
CommitLineData
30fdf114
LG
1## @file\r
2# This file is used to define common string related functions used in parsing process\r
3#\r
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
17import re\r
18import DataType\r
19import os.path\r
20import string\r
21import EdkLogger as EdkLogger\r
22\r
23from GlobalData import *\r
24from BuildToolError import *\r
25\r
08dd311f
LG
26gHexVerPatt = re.compile('0x[a-f0-9]{4}[a-f0-9]{4}$',re.IGNORECASE)\r
27gHumanReadableVerPatt = 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
41def 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
53def 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
73def 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
97def 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
116def 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
138def 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
162def 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
192def 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
213def ReplaceMacro(String, MacroDefinitions={}, SelfReplacement = False):\r
214 LastString = String\r
215 while MacroDefinitions:\r
216 MacroUsed = gMacroPattern.findall(String)\r
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
244def 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
274def 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
280 # Replace R8's comment character\r
281 #\r
282 if AllowCppStyleComment:\r
283 Line = Line.replace(DataType.TAB_COMMENT_R8_SPLIT, CommentCharacter)\r
284 #\r
9053bc51 285 # remove comments, but we should escape comment character in string\r
30fdf114 286 #\r
9053bc51 287 InString = False\r
288 for Index in range(0, len(Line)):\r
289 if Line[Index] == '"':\r
290 InString = not InString\r
291 elif Line[Index] == CommentCharacter and not InString:\r
292 Line = Line[0: Index]\r
293 break\r
294 \r
30fdf114
LG
295 #\r
296 # remove whitespace again\r
297 #\r
298 Line = Line.strip();\r
299\r
300 return Line\r
301\r
e56468c0 302## CleanString2\r
303#\r
304# Split comments in a string\r
305# Remove spaces\r
306#\r
307# @param Line: The string to be cleaned\r
308# @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT\r
309#\r
310# @retval Path Formatted path\r
311#\r
312def CleanString2(Line, CommentCharacter = DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False):\r
313 #\r
314 # remove whitespace\r
315 #\r
316 Line = Line.strip();\r
317 #\r
318 # Replace R8's comment character\r
319 #\r
320 if AllowCppStyleComment:\r
321 Line = Line.replace(DataType.TAB_COMMENT_R8_SPLIT, CommentCharacter)\r
322 #\r
323 # separate comments and statements\r
324 #\r
325 LineParts = Line.split(CommentCharacter, 1);\r
326 #\r
327 # remove whitespace again\r
328 #\r
329 Line = LineParts[0].strip();\r
330 if len(LineParts) > 1:\r
331 Comment = LineParts[1].strip()\r
332 # Remove prefixed and trailing comment characters\r
333 Start = 0\r
334 End = len(Comment)\r
335 while Start < End and Comment.startswith(CommentCharacter, Start, End):\r
336 Start += 1\r
337 while End >= 0 and Comment.endswith(CommentCharacter, Start, End):\r
338 End -= 1\r
339 Comment = Comment[Start:End]\r
340 Comment = Comment.strip()\r
341 else:\r
342 Comment = ''\r
343\r
344 return Line, Comment\r
345\r
30fdf114
LG
346## GetMultipleValuesOfKeyFromLines\r
347#\r
348# Parse multiple strings to clean comment and spaces\r
349# The result is saved to KeyValues\r
350#\r
351# @param Lines: The content to be parsed\r
352# @param Key: Reserved\r
353# @param KeyValues: To store data after parsing\r
354# @param CommentCharacter: Comment char, used to ignore comment content\r
355#\r
356# @retval True Successfully executed\r
357#\r
358def GetMultipleValuesOfKeyFromLines(Lines, Key, KeyValues, CommentCharacter):\r
359 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
360 LineList = Lines.split('\n')\r
361 for Line in LineList:\r
362 Line = CleanString(Line, CommentCharacter)\r
363 if Line != '' and Line[0] != CommentCharacter:\r
364 KeyValues += [Line]\r
365\r
366 return True\r
367\r
368## GetDefineValue\r
369#\r
370# Parse a DEFINE statement to get defined value\r
371# DEFINE Key Value\r
372#\r
373# @param String: The content to be parsed\r
374# @param Key: The key of DEFINE statement\r
375# @param CommentCharacter: Comment char, used to ignore comment content\r
376#\r
377# @retval string The defined value\r
378#\r
379def GetDefineValue(String, Key, CommentCharacter):\r
380 String = CleanString(String)\r
381 return String[String.find(Key + ' ') + len(Key + ' ') : ]\r
382\r
08dd311f
LG
383## GetHexVerValue\r
384#\r
385# Get a Hex Version Value\r
386#\r
387# @param VerString: The version string to be parsed\r
388#\r
389#\r
390# @retval: If VerString is incorrectly formatted, return "None" which will break the build.\r
391# If VerString is correctly formatted, return a Hex value of the Version Number (0xmmmmnnnn)\r
392# where mmmm is the major number and nnnn is the adjusted minor number.\r
393#\r
394def GetHexVerValue(VerString):\r
395 VerString = CleanString(VerString)\r
396\r
397 if gHumanReadableVerPatt.match(VerString):\r
398 ValueList = VerString.split('.')\r
399 Major = ValueList[0]\r
400 Minor = ValueList[1]\r
401 if len(Minor) == 1:\r
402 Minor += '0'\r
403 DeciValue = (int(Major) << 16) + int(Minor);\r
404 return "0x%08x"%DeciValue\r
405 elif gHexVerPatt.match(VerString):\r
406 return VerString\r
407 else:\r
408 return None\r
409\r
410\r
30fdf114
LG
411## GetSingleValueOfKeyFromLines\r
412#\r
413# Parse multiple strings as below to get value of each definition line\r
414# Key1 = Value1\r
415# Key2 = Value2\r
416# The result is saved to Dictionary\r
417#\r
418# @param Lines: The content to be parsed\r
419# @param Dictionary: To store data after parsing\r
420# @param CommentCharacter: Comment char, be used to ignore comment content\r
421# @param KeySplitCharacter: Key split char, between key name and key value. Key1 = Value1, '=' is the key split char\r
422# @param ValueSplitFlag: Value split flag, be used to decide if has multiple values\r
423# @param ValueSplitCharacter: Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char\r
424#\r
425# @retval True Successfully executed\r
426#\r
427def GetSingleValueOfKeyFromLines(Lines, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):\r
428 Lines = Lines.split('\n')\r
429 Keys = []\r
430 Value = ''\r
431 DefineValues = ['']\r
432 SpecValues = ['']\r
433\r
434 for Line in Lines:\r
435 #\r
436 # Handle DEFINE and SPEC\r
437 #\r
438 if Line.find(DataType.TAB_INF_DEFINES_DEFINE + ' ') > -1:\r
439 if '' in DefineValues:\r
440 DefineValues.remove('')\r
441 DefineValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_DEFINE, CommentCharacter))\r
442 continue\r
443 if Line.find(DataType.TAB_INF_DEFINES_SPEC + ' ') > -1:\r
444 if '' in SpecValues:\r
445 SpecValues.remove('')\r
446 SpecValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_SPEC, CommentCharacter))\r
447 continue\r
448\r
449 #\r
450 # Handle Others\r
451 #\r
452 LineList = Line.split(KeySplitCharacter, 1)\r
453 if len(LineList) >= 2:\r
454 Key = LineList[0].split()\r
455 if len(Key) == 1 and Key[0][0] != CommentCharacter:\r
456 #\r
457 # Remove comments and white spaces\r
458 #\r
459 LineList[1] = CleanString(LineList[1], CommentCharacter)\r
460 if ValueSplitFlag:\r
461 Value = map(string.strip, LineList[1].split(ValueSplitCharacter))\r
462 else:\r
463 Value = CleanString(LineList[1], CommentCharacter).splitlines()\r
464\r
465 if Key[0] in Dictionary:\r
466 if Key[0] not in Keys:\r
467 Dictionary[Key[0]] = Value\r
468 Keys.append(Key[0])\r
469 else:\r
470 Dictionary[Key[0]].extend(Value)\r
471 else:\r
472 Dictionary[DataType.TAB_INF_DEFINES_MACRO][Key[0]] = Value[0]\r
473\r
474 if DefineValues == []:\r
475 DefineValues = ['']\r
476 if SpecValues == []:\r
477 SpecValues = ['']\r
478 Dictionary[DataType.TAB_INF_DEFINES_DEFINE] = DefineValues\r
479 Dictionary[DataType.TAB_INF_DEFINES_SPEC] = SpecValues\r
480\r
481 return True\r
482\r
483## The content to be parsed\r
484#\r
485# Do pre-check for a file before it is parsed\r
486# Check $()\r
487# Check []\r
488#\r
489# @param FileName: Used for error report\r
490# @param FileContent: File content to be parsed\r
491# @param SupSectionTag: Used for error report\r
492#\r
493def PreCheck(FileName, FileContent, SupSectionTag):\r
494 LineNo = 0\r
495 IsFailed = False\r
496 NewFileContent = ''\r
497 for Line in FileContent.splitlines():\r
498 LineNo = LineNo + 1\r
499 #\r
500 # Clean current line\r
501 #\r
502 Line = CleanString(Line)\r
503\r
504 #\r
505 # Remove commented line\r
506 #\r
507 if Line.find(DataType.TAB_COMMA_SPLIT) == 0:\r
508 Line = ''\r
509 #\r
510 # Check $()\r
511 #\r
512 if Line.find('$') > -1:\r
513 if Line.find('$(') < 0 or Line.find(')') < 0:\r
514 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError = EdkLogger.IsRaiseError)\r
515\r
516 #\r
517 # Check []\r
518 #\r
519 if Line.find('[') > -1 or Line.find(']') > -1:\r
520 #\r
521 # Only get one '[' or one ']'\r
522 #\r
523 if not (Line.find('[') > -1 and Line.find(']') > -1):\r
524 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError = EdkLogger.IsRaiseError)\r
525\r
526 #\r
527 # Regenerate FileContent\r
528 #\r
529 NewFileContent = NewFileContent + Line + '\r\n'\r
530\r
531 if IsFailed:\r
532 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError = EdkLogger.IsRaiseError)\r
533\r
534 return NewFileContent\r
535\r
536## CheckFileType\r
537#\r
538# Check if the Filename is including ExtName\r
539# Return True if it exists\r
540# Raise a error message if it not exists\r
541#\r
542# @param CheckFilename: Name of the file to be checked\r
543# @param ExtName: Ext name of the file to be checked\r
544# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
545# @param SectionName: Used for error report\r
546# @param Line: The line in container file which defines the file to be checked\r
547#\r
548# @retval True The file type is correct\r
549#\r
550def CheckFileType(CheckFilename, ExtName, ContainerFilename, SectionName, Line, LineNo = -1):\r
551 if CheckFilename != '' and CheckFilename != None:\r
552 (Root, Ext) = os.path.splitext(CheckFilename)\r
553 if Ext.upper() != ExtName.upper():\r
554 ContainerFile = open(ContainerFilename, 'r').read()\r
555 if LineNo == -1:\r
556 LineNo = GetLineNo(ContainerFile, Line)\r
557 ErrorMsg = "Invalid %s. '%s' is found, but '%s' file is needed" % (SectionName, CheckFilename, ExtName)\r
558 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, Line=LineNo,\r
559 File=ContainerFilename, RaiseError = EdkLogger.IsRaiseError)\r
560\r
561 return True\r
562\r
563## CheckFileExist\r
564#\r
565# Check if the file exists\r
566# Return True if it exists\r
567# Raise a error message if it not exists\r
568#\r
569# @param CheckFilename: Name of the file to be checked\r
570# @param WorkspaceDir: Current workspace dir\r
571# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
572# @param SectionName: Used for error report\r
573# @param Line: The line in container file which defines the file to be checked\r
574#\r
575# @retval The file full path if the file exists\r
576#\r
577def CheckFileExist(WorkspaceDir, CheckFilename, ContainerFilename, SectionName, Line, LineNo = -1):\r
578 CheckFile = ''\r
579 if CheckFilename != '' and CheckFilename != None:\r
580 CheckFile = WorkspaceFile(WorkspaceDir, CheckFilename)\r
581 if not os.path.isfile(CheckFile):\r
582 ContainerFile = open(ContainerFilename, 'r').read()\r
583 if LineNo == -1:\r
584 LineNo = GetLineNo(ContainerFile, Line)\r
585 ErrorMsg = "Can't find file '%s' defined in section '%s'" % (CheckFile, SectionName)\r
586 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg,\r
587 File=ContainerFilename, Line = LineNo, RaiseError = EdkLogger.IsRaiseError)\r
588\r
589 return CheckFile\r
590\r
591## GetLineNo\r
592#\r
593# Find the index of a line in a file\r
594#\r
595# @param FileContent: Search scope\r
596# @param Line: Search key\r
597#\r
598# @retval int Index of the line\r
599# @retval -1 The line is not found\r
600#\r
601def GetLineNo(FileContent, Line, IsIgnoreComment = True):\r
602 LineList = FileContent.splitlines()\r
603 for Index in range(len(LineList)):\r
604 if LineList[Index].find(Line) > -1:\r
605 #\r
606 # Ignore statement in comment\r
607 #\r
608 if IsIgnoreComment:\r
609 if LineList[Index].strip()[0] == DataType.TAB_COMMENT_SPLIT:\r
610 continue\r
611 return Index + 1\r
612\r
613 return -1\r
614\r
615## RaiseParserError\r
616#\r
617# Raise a parser error\r
618#\r
619# @param Line: String which has error\r
620# @param Section: Used for error report\r
621# @param File: File which has the string\r
622# @param Format: Correct format\r
623#\r
624def RaiseParserError(Line, Section, File, Format = '', LineNo = -1):\r
625 if LineNo == -1:\r
626 LineNo = GetLineNo(open(os.path.normpath(File), 'r').read(), Line)\r
627 ErrorMsg = "Invalid statement '%s' is found in section '%s'" % (Line, Section)\r
628 if Format != '':\r
629 Format = "Correct format is " + Format\r
630 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, File=File, Line=LineNo, ExtraData=Format, RaiseError = EdkLogger.IsRaiseError)\r
631\r
632## WorkspaceFile\r
633#\r
634# Return a full path with workspace dir\r
635#\r
636# @param WorkspaceDir: Workspace dir\r
637# @param Filename: Relative file name\r
638#\r
639# @retval string A full path\r
640#\r
641def WorkspaceFile(WorkspaceDir, Filename):\r
642 return os.path.join(NormPath(WorkspaceDir), NormPath(Filename))\r
643\r
644## Split string\r
645#\r
646# Revmove '"' which startswith and endswith string\r
647#\r
648# @param String: The string need to be splited\r
649#\r
650# @retval String: The string after removed '""'\r
651#\r
652def SplitString(String):\r
653 if String.startswith('\"'):\r
654 String = String[1:]\r
655 if String.endswith('\"'):\r
656 String = String[:-1]\r
657\r
658 return String\r
659\r
660## Convert To Sql String\r
661#\r
662# 1. Replace "'" with "''" in each item of StringList\r
663#\r
664# @param StringList: A list for strings to be converted\r
665#\r
666def ConvertToSqlString(StringList):\r
667 return map(lambda s: s.replace("'", "''") , StringList)\r
668\r
669## Convert To Sql String\r
670#\r
671# 1. Replace "'" with "''" in the String\r
672#\r
673# @param String: A String to be converted\r
674#\r
675def ConvertToSqlString2(String):\r
676 return String.replace("'", "''")\r
677\r
678#\r
679# Remove comment block\r
680#\r
681def RemoveBlockComment(Lines):\r
682 IsFindBlockComment = False\r
683 IsFindBlockCode = False\r
684 ReservedLine = ''\r
685 NewLines = []\r
686\r
687 for Line in Lines:\r
688 Line = Line.strip()\r
689 #\r
690 # Remove comment block\r
691 #\r
692 if Line.find(DataType.TAB_COMMENT_R8_START) > -1:\r
693 ReservedLine = GetSplitValueList(Line, DataType.TAB_COMMENT_R8_START, 1)[0]\r
694 IsFindBlockComment = True\r
695 if Line.find(DataType.TAB_COMMENT_R8_END) > -1:\r
696 Line = ReservedLine + GetSplitValueList(Line, DataType.TAB_COMMENT_R8_END, 1)[1]\r
697 ReservedLine = ''\r
698 IsFindBlockComment = False\r
699 if IsFindBlockComment:\r
700 NewLines.append('')\r
701 continue\r
702\r
703 NewLines.append(Line)\r
704 return NewLines\r
705\r
706#\r
707# Get String of a List\r
708#\r
709def GetStringOfList(List, Split = ' '):\r
710 if type(List) != type([]):\r
711 return List\r
712 Str = ''\r
713 for Item in List:\r
714 Str = Str + Item + Split\r
715\r
716 return Str.strip()\r
717\r
718#\r
719# Get HelpTextList from HelpTextClassList\r
720#\r
721def GetHelpTextList(HelpTextClassList):\r
722 List = []\r
723 if HelpTextClassList:\r
724 for HelpText in HelpTextClassList:\r
725 if HelpText.String.endswith('\n'):\r
726 HelpText.String = HelpText.String[0: len(HelpText.String) - len('\n')]\r
727 List.extend(HelpText.String.split('\n'))\r
728\r
729 return List\r
730\r
731def StringToArray(String):\r
732 if isinstance(String, unicode):\r
733 if len(unicode) ==0:\r
734 return "{0x00, 0x00}"\r
735 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C) for C in String])\r
736 elif String.startswith('L"'):\r
737 if String == "L\"\"":\r
738 return "{0x00, 0x00}"\r
739 else:\r
740 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C) for C in String[2:-1]])\r
741 elif String.startswith('"'):\r
742 if String == "\"\"":\r
743 return "{0x00}";\r
744 else:\r
745 return "{%s, 0x00}" % ", ".join(["0x%02x" % ord(C) for C in String[1:-1]])\r
746 else:\r
747 return '{%s, 0}' % ', '.join(String.split())\r
748\r
749def StringArrayLength(String):\r
750 if isinstance(String, unicode):\r
751 return (len(String) + 1) * 2 + 1;\r
752 elif String.startswith('L"'):\r
753 return (len(String) - 3 + 1) * 2\r
754 elif String.startswith('"'):\r
755 return (len(String) - 2 + 1)\r
756 else:\r
757 return len(String.split()) + 1\r
758 \r
759def RemoveDupOption(OptionString, Which="/I", Against=None):\r
760 OptionList = OptionString.split()\r
761 ValueList = []\r
762 if Against:\r
763 ValueList += Against\r
764 for Index in range(len(OptionList)):\r
765 Opt = OptionList[Index]\r
766 if not Opt.startswith(Which):\r
767 continue\r
768 if len(Opt) > len(Which):\r
769 Val = Opt[len(Which):]\r
770 else:\r
771 Val = ""\r
772 if Val in ValueList:\r
773 OptionList[Index] = ""\r
774 else:\r
775 ValueList.append(Val)\r
776 return " ".join(OptionList)\r
777\r
778##\r
779#\r
780# This acts like the main() function for the script, unless it is 'import'ed into another\r
781# script.\r
782#\r
783if __name__ == '__main__':\r
784 pass\r
785\r