]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/Common/String.py
Sync BaseTool trunk (version r2397) into EDKII BaseTools. The change mainly includes
[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):
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:
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 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
391 #
392 LineParts = Line.split(CommentCharacter, 1);
393 #
394 # remove whitespace again
395 #
396 Line = LineParts[0].strip();
397 if len(LineParts) > 1:
398 Comment = LineParts[1].strip()
399 # Remove prefixed and trailing comment characters
400 Start = 0
401 End = len(Comment)
402 while Start < End and Comment.startswith(CommentCharacter, Start, End):
403 Start += 1
404 while End >= 0 and Comment.endswith(CommentCharacter, Start, End):
405 End -= 1
406 Comment = Comment[Start:End]
407 Comment = Comment.strip()
408 else:
409 Comment = ''
410
411 return Line, Comment
412
413 ## GetMultipleValuesOfKeyFromLines
414 #
415 # Parse multiple strings to clean comment and spaces
416 # The result is saved to KeyValues
417 #
418 # @param Lines: The content to be parsed
419 # @param Key: Reserved
420 # @param KeyValues: To store data after parsing
421 # @param CommentCharacter: Comment char, used to ignore comment content
422 #
423 # @retval True Successfully executed
424 #
425 def GetMultipleValuesOfKeyFromLines(Lines, Key, KeyValues, CommentCharacter):
426 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]
427 LineList = Lines.split('\n')
428 for Line in LineList:
429 Line = CleanString(Line, CommentCharacter)
430 if Line != '' and Line[0] != CommentCharacter:
431 KeyValues += [Line]
432
433 return True
434
435 ## GetDefineValue
436 #
437 # Parse a DEFINE statement to get defined value
438 # DEFINE Key Value
439 #
440 # @param String: The content to be parsed
441 # @param Key: The key of DEFINE statement
442 # @param CommentCharacter: Comment char, used to ignore comment content
443 #
444 # @retval string The defined value
445 #
446 def GetDefineValue(String, Key, CommentCharacter):
447 String = CleanString(String)
448 return String[String.find(Key + ' ') + len(Key + ' ') : ]
449
450 ## GetHexVerValue
451 #
452 # Get a Hex Version Value
453 #
454 # @param VerString: The version string to be parsed
455 #
456 #
457 # @retval: If VerString is incorrectly formatted, return "None" which will break the build.
458 # If VerString is correctly formatted, return a Hex value of the Version Number (0xmmmmnnnn)
459 # where mmmm is the major number and nnnn is the adjusted minor number.
460 #
461 def GetHexVerValue(VerString):
462 VerString = CleanString(VerString)
463
464 if gHumanReadableVerPatt.match(VerString):
465 ValueList = VerString.split('.')
466 Major = ValueList[0]
467 Minor = ValueList[1]
468 if len(Minor) == 1:
469 Minor += '0'
470 DeciValue = (int(Major) << 16) + int(Minor);
471 return "0x%08x" % DeciValue
472 elif gHexVerPatt.match(VerString):
473 return VerString
474 else:
475 return None
476
477
478 ## GetSingleValueOfKeyFromLines
479 #
480 # Parse multiple strings as below to get value of each definition line
481 # Key1 = Value1
482 # Key2 = Value2
483 # The result is saved to Dictionary
484 #
485 # @param Lines: The content to be parsed
486 # @param Dictionary: To store data after parsing
487 # @param CommentCharacter: Comment char, be used to ignore comment content
488 # @param KeySplitCharacter: Key split char, between key name and key value. Key1 = Value1, '=' is the key split char
489 # @param ValueSplitFlag: Value split flag, be used to decide if has multiple values
490 # @param ValueSplitCharacter: Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char
491 #
492 # @retval True Successfully executed
493 #
494 def GetSingleValueOfKeyFromLines(Lines, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):
495 Lines = Lines.split('\n')
496 Keys = []
497 Value = ''
498 DefineValues = ['']
499 SpecValues = ['']
500
501 for Line in Lines:
502 #
503 # Handle DEFINE and SPEC
504 #
505 if Line.find(DataType.TAB_INF_DEFINES_DEFINE + ' ') > -1:
506 if '' in DefineValues:
507 DefineValues.remove('')
508 DefineValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_DEFINE, CommentCharacter))
509 continue
510 if Line.find(DataType.TAB_INF_DEFINES_SPEC + ' ') > -1:
511 if '' in SpecValues:
512 SpecValues.remove('')
513 SpecValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_SPEC, CommentCharacter))
514 continue
515
516 #
517 # Handle Others
518 #
519 LineList = Line.split(KeySplitCharacter, 1)
520 if len(LineList) >= 2:
521 Key = LineList[0].split()
522 if len(Key) == 1 and Key[0][0] != CommentCharacter:
523 #
524 # Remove comments and white spaces
525 #
526 LineList[1] = CleanString(LineList[1], CommentCharacter)
527 if ValueSplitFlag:
528 Value = map(string.strip, LineList[1].split(ValueSplitCharacter))
529 else:
530 Value = CleanString(LineList[1], CommentCharacter).splitlines()
531
532 if Key[0] in Dictionary:
533 if Key[0] not in Keys:
534 Dictionary[Key[0]] = Value
535 Keys.append(Key[0])
536 else:
537 Dictionary[Key[0]].extend(Value)
538 else:
539 Dictionary[DataType.TAB_INF_DEFINES_MACRO][Key[0]] = Value[0]
540
541 if DefineValues == []:
542 DefineValues = ['']
543 if SpecValues == []:
544 SpecValues = ['']
545 Dictionary[DataType.TAB_INF_DEFINES_DEFINE] = DefineValues
546 Dictionary[DataType.TAB_INF_DEFINES_SPEC] = SpecValues
547
548 return True
549
550 ## The content to be parsed
551 #
552 # Do pre-check for a file before it is parsed
553 # Check $()
554 # Check []
555 #
556 # @param FileName: Used for error report
557 # @param FileContent: File content to be parsed
558 # @param SupSectionTag: Used for error report
559 #
560 def PreCheck(FileName, FileContent, SupSectionTag):
561 LineNo = 0
562 IsFailed = False
563 NewFileContent = ''
564 for Line in FileContent.splitlines():
565 LineNo = LineNo + 1
566 #
567 # Clean current line
568 #
569 Line = CleanString(Line)
570
571 #
572 # Remove commented line
573 #
574 if Line.find(DataType.TAB_COMMA_SPLIT) == 0:
575 Line = ''
576 #
577 # Check $()
578 #
579 if Line.find('$') > -1:
580 if Line.find('$(') < 0 or Line.find(')') < 0:
581 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)
582
583 #
584 # Check []
585 #
586 if Line.find('[') > -1 or Line.find(']') > -1:
587 #
588 # Only get one '[' or one ']'
589 #
590 if not (Line.find('[') > -1 and Line.find(']') > -1):
591 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)
592
593 #
594 # Regenerate FileContent
595 #
596 NewFileContent = NewFileContent + Line + '\r\n'
597
598 if IsFailed:
599 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)
600
601 return NewFileContent
602
603 ## CheckFileType
604 #
605 # Check if the Filename is including ExtName
606 # Return True if it exists
607 # Raise a error message if it not exists
608 #
609 # @param CheckFilename: Name of the file to be checked
610 # @param ExtName: Ext name of the file to be checked
611 # @param ContainerFilename: The container file which describes the file to be checked, used for error report
612 # @param SectionName: Used for error report
613 # @param Line: The line in container file which defines the file to be checked
614 #
615 # @retval True The file type is correct
616 #
617 def CheckFileType(CheckFilename, ExtName, ContainerFilename, SectionName, Line, LineNo= -1):
618 if CheckFilename != '' and CheckFilename != None:
619 (Root, Ext) = os.path.splitext(CheckFilename)
620 if Ext.upper() != ExtName.upper():
621 ContainerFile = open(ContainerFilename, 'r').read()
622 if LineNo == -1:
623 LineNo = GetLineNo(ContainerFile, Line)
624 ErrorMsg = "Invalid %s. '%s' is found, but '%s' file is needed" % (SectionName, CheckFilename, ExtName)
625 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, Line=LineNo,
626 File=ContainerFilename, RaiseError=EdkLogger.IsRaiseError)
627
628 return True
629
630 ## CheckFileExist
631 #
632 # Check if the file exists
633 # Return True if it exists
634 # Raise a error message if it not exists
635 #
636 # @param CheckFilename: Name of the file to be checked
637 # @param WorkspaceDir: Current workspace dir
638 # @param ContainerFilename: The container file which describes the file to be checked, used for error report
639 # @param SectionName: Used for error report
640 # @param Line: The line in container file which defines the file to be checked
641 #
642 # @retval The file full path if the file exists
643 #
644 def CheckFileExist(WorkspaceDir, CheckFilename, ContainerFilename, SectionName, Line, LineNo= -1):
645 CheckFile = ''
646 if CheckFilename != '' and CheckFilename != None:
647 CheckFile = WorkspaceFile(WorkspaceDir, CheckFilename)
648 if not os.path.isfile(CheckFile):
649 ContainerFile = open(ContainerFilename, 'r').read()
650 if LineNo == -1:
651 LineNo = GetLineNo(ContainerFile, Line)
652 ErrorMsg = "Can't find file '%s' defined in section '%s'" % (CheckFile, SectionName)
653 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg,
654 File=ContainerFilename, Line=LineNo, RaiseError=EdkLogger.IsRaiseError)
655
656 return CheckFile
657
658 ## GetLineNo
659 #
660 # Find the index of a line in a file
661 #
662 # @param FileContent: Search scope
663 # @param Line: Search key
664 #
665 # @retval int Index of the line
666 # @retval -1 The line is not found
667 #
668 def GetLineNo(FileContent, Line, IsIgnoreComment=True):
669 LineList = FileContent.splitlines()
670 for Index in range(len(LineList)):
671 if LineList[Index].find(Line) > -1:
672 #
673 # Ignore statement in comment
674 #
675 if IsIgnoreComment:
676 if LineList[Index].strip()[0] == DataType.TAB_COMMENT_SPLIT:
677 continue
678 return Index + 1
679
680 return -1
681
682 ## RaiseParserError
683 #
684 # Raise a parser error
685 #
686 # @param Line: String which has error
687 # @param Section: Used for error report
688 # @param File: File which has the string
689 # @param Format: Correct format
690 #
691 def RaiseParserError(Line, Section, File, Format='', LineNo= -1):
692 if LineNo == -1:
693 LineNo = GetLineNo(open(os.path.normpath(File), 'r').read(), Line)
694 ErrorMsg = "Invalid statement '%s' is found in section '%s'" % (Line, Section)
695 if Format != '':
696 Format = "Correct format is " + Format
697 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, File=File, Line=LineNo, ExtraData=Format, RaiseError=EdkLogger.IsRaiseError)
698
699 ## WorkspaceFile
700 #
701 # Return a full path with workspace dir
702 #
703 # @param WorkspaceDir: Workspace dir
704 # @param Filename: Relative file name
705 #
706 # @retval string A full path
707 #
708 def WorkspaceFile(WorkspaceDir, Filename):
709 return os.path.join(NormPath(WorkspaceDir), NormPath(Filename))
710
711 ## Split string
712 #
713 # Revmove '"' which startswith and endswith string
714 #
715 # @param String: The string need to be splited
716 #
717 # @retval String: The string after removed '""'
718 #
719 def SplitString(String):
720 if String.startswith('\"'):
721 String = String[1:]
722 if String.endswith('\"'):
723 String = String[:-1]
724
725 return String
726
727 ## Convert To Sql String
728 #
729 # 1. Replace "'" with "''" in each item of StringList
730 #
731 # @param StringList: A list for strings to be converted
732 #
733 def ConvertToSqlString(StringList):
734 return map(lambda s: s.replace("'", "''") , StringList)
735
736 ## Convert To Sql String
737 #
738 # 1. Replace "'" with "''" in the String
739 #
740 # @param String: A String to be converted
741 #
742 def ConvertToSqlString2(String):
743 return String.replace("'", "''")
744
745 #
746 # Remove comment block
747 #
748 def RemoveBlockComment(Lines):
749 IsFindBlockComment = False
750 IsFindBlockCode = False
751 ReservedLine = ''
752 NewLines = []
753
754 for Line in Lines:
755 Line = Line.strip()
756 #
757 # Remove comment block
758 #
759 if Line.find(DataType.TAB_COMMENT_EDK_START) > -1:
760 ReservedLine = GetSplitList(Line, DataType.TAB_COMMENT_EDK_START, 1)[0]
761 IsFindBlockComment = True
762 if Line.find(DataType.TAB_COMMENT_EDK_END) > -1:
763 Line = ReservedLine + GetSplitList(Line, DataType.TAB_COMMENT_EDK_END, 1)[1]
764 ReservedLine = ''
765 IsFindBlockComment = False
766 if IsFindBlockComment:
767 NewLines.append('')
768 continue
769
770 NewLines.append(Line)
771 return NewLines
772
773 #
774 # Get String of a List
775 #
776 def GetStringOfList(List, Split=' '):
777 if type(List) != type([]):
778 return List
779 Str = ''
780 for Item in List:
781 Str = Str + Item + Split
782
783 return Str.strip()
784
785 #
786 # Get HelpTextList from HelpTextClassList
787 #
788 def GetHelpTextList(HelpTextClassList):
789 List = []
790 if HelpTextClassList:
791 for HelpText in HelpTextClassList:
792 if HelpText.String.endswith('\n'):
793 HelpText.String = HelpText.String[0: len(HelpText.String) - len('\n')]
794 List.extend(HelpText.String.split('\n'))
795
796 return List
797
798 def StringToArray(String):
799 if isinstance(String, unicode):
800 if len(unicode) == 0:
801 return "{0x00, 0x00}"
802 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C) for C in String])
803 elif String.startswith('L"'):
804 if String == "L\"\"":
805 return "{0x00, 0x00}"
806 else:
807 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C) for C in String[2:-1]])
808 elif String.startswith('"'):
809 if String == "\"\"":
810 return "{0x00}";
811 else:
812 return "{%s, 0x00}" % ", ".join(["0x%02x" % ord(C) for C in String[1:-1]])
813 else:
814 return '{%s, 0}' % ', '.join(String.split())
815
816 def StringArrayLength(String):
817 if isinstance(String, unicode):
818 return (len(String) + 1) * 2 + 1;
819 elif String.startswith('L"'):
820 return (len(String) - 3 + 1) * 2
821 elif String.startswith('"'):
822 return (len(String) - 2 + 1)
823 else:
824 return len(String.split()) + 1
825
826 def RemoveDupOption(OptionString, Which="/I", Against=None):
827 OptionList = OptionString.split()
828 ValueList = []
829 if Against:
830 ValueList += Against
831 for Index in range(len(OptionList)):
832 Opt = OptionList[Index]
833 if not Opt.startswith(Which):
834 continue
835 if len(Opt) > len(Which):
836 Val = Opt[len(Which):]
837 else:
838 Val = ""
839 if Val in ValueList:
840 OptionList[Index] = ""
841 else:
842 ValueList.append(Val)
843 return " ".join(OptionList)
844
845 ##
846 #
847 # This acts like the main() function for the script, unless it is 'import'ed into another
848 # script.
849 #
850 if __name__ == '__main__':
851 pass
852