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