code
stringlengths
17
6.64M
class NoMatch(Token): 'A token that will never match.' def __init__(self): super(NoMatch, self).__init__() self.name = 'NoMatch' self.mayReturnEmpty = True self.mayIndexError = False self.errmsg = 'Unmatchable token' def parseImpl(self, instring, loc, doActions=True): raise ParseException(instring, loc, self.errmsg, self)
class Literal(Token): 'Token to exactly match a specified string.' def __init__(self, matchString): super(Literal, self).__init__() self.match = matchString self.matchLen = len(matchString) try: self.firstMatchChar = matchString[0] except IndexError: warnings.warn('null string passed to Literal; use Empty() instead', SyntaxWarning, stacklevel=2) self.__class__ = Empty self.name = ('"%s"' % _ustr(self.match)) self.errmsg = ('Expected ' + self.name) self.mayReturnEmpty = False self.mayIndexError = False def parseImpl(self, instring, loc, doActions=True): if ((instring[loc] == self.firstMatchChar) and ((self.matchLen == 1) or instring.startswith(self.match, loc))): return ((loc + self.matchLen), self.match) raise ParseException(instring, loc, self.errmsg, self)
class Keyword(Token): 'Token to exactly match a specified string as a keyword, that is, it must be\n immediately followed by a non-keyword character. Compare with C{L{Literal}}::\n Literal("if") will match the leading C{\'if\'} in C{\'ifAndOnlyIf\'}.\n Keyword("if") will not; it will only match the leading C{\'if\'} in C{\'if x=1\'}, or C{\'if(y==2)\'}\n Accepts two optional constructor arguments in addition to the keyword string:\n C{identChars} is a string of characters that would be valid identifier characters,\n defaulting to all alphanumerics + "_" and "$"; C{caseless} allows case-insensitive\n matching, default is C{False}.\n ' DEFAULT_KEYWORD_CHARS = (alphanums + '_$') def __init__(self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False): super(Keyword, self).__init__() self.match = matchString self.matchLen = len(matchString) try: self.firstMatchChar = matchString[0] except IndexError: warnings.warn('null string passed to Keyword; use Empty() instead', SyntaxWarning, stacklevel=2) self.name = ('"%s"' % self.match) self.errmsg = ('Expected ' + self.name) self.mayReturnEmpty = False self.mayIndexError = False self.caseless = caseless if caseless: self.caselessmatch = matchString.upper() identChars = identChars.upper() self.identChars = set(identChars) def parseImpl(self, instring, loc, doActions=True): if self.caseless: if ((instring[loc:(loc + self.matchLen)].upper() == self.caselessmatch) and ((loc >= (len(instring) - self.matchLen)) or (instring[(loc + self.matchLen)].upper() not in self.identChars)) and ((loc == 0) or (instring[(loc - 1)].upper() not in self.identChars))): return ((loc + self.matchLen), self.match) elif ((instring[loc] == self.firstMatchChar) and ((self.matchLen == 1) or instring.startswith(self.match, loc)) and ((loc >= (len(instring) - self.matchLen)) or (instring[(loc + self.matchLen)] not in self.identChars)) and ((loc == 0) or (instring[(loc - 1)] not in self.identChars))): return ((loc + self.matchLen), self.match) raise ParseException(instring, loc, self.errmsg, self) def copy(self): c = super(Keyword, self).copy() c.identChars = Keyword.DEFAULT_KEYWORD_CHARS return c def setDefaultKeywordChars(chars): 'Overrides the default Keyword chars\n ' Keyword.DEFAULT_KEYWORD_CHARS = chars setDefaultKeywordChars = staticmethod(setDefaultKeywordChars)
class CaselessLiteral(Literal): 'Token to match a specified string, ignoring case of letters.\n Note: the matched results will always be in the case of the given\n match string, NOT the case of the input text.\n ' def __init__(self, matchString): super(CaselessLiteral, self).__init__(matchString.upper()) self.returnString = matchString self.name = ("'%s'" % self.returnString) self.errmsg = ('Expected ' + self.name) def parseImpl(self, instring, loc, doActions=True): if (instring[loc:(loc + self.matchLen)].upper() == self.match): return ((loc + self.matchLen), self.returnString) raise ParseException(instring, loc, self.errmsg, self)
class CaselessKeyword(Keyword): def __init__(self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS): super(CaselessKeyword, self).__init__(matchString, identChars, caseless=True) def parseImpl(self, instring, loc, doActions=True): if ((instring[loc:(loc + self.matchLen)].upper() == self.caselessmatch) and ((loc >= (len(instring) - self.matchLen)) or (instring[(loc + self.matchLen)].upper() not in self.identChars))): return ((loc + self.matchLen), self.match) raise ParseException(instring, loc, self.errmsg, self)
class Word(Token): 'Token for matching words composed of allowed character sets.\n Defined with string containing all allowed initial characters,\n an optional string containing allowed body characters (if omitted,\n defaults to the initial character set), and an optional minimum,\n maximum, and/or exact length. The default value for C{min} is 1 (a\n minimum value < 1 is not valid); the default values for C{max} and C{exact}\n are 0, meaning no maximum or exact length restriction. An optional\n C{exclude} parameter can list characters that might be found in \n the input C{bodyChars} string; useful to define a word of all printables\n except for one or two characters, for instance.\n ' def __init__(self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False, excludeChars=None): super(Word, self).__init__() if excludeChars: initChars = ''.join((c for c in initChars if (c not in excludeChars))) if bodyChars: bodyChars = ''.join((c for c in bodyChars if (c not in excludeChars))) self.initCharsOrig = initChars self.initChars = set(initChars) if bodyChars: self.bodyCharsOrig = bodyChars self.bodyChars = set(bodyChars) else: self.bodyCharsOrig = initChars self.bodyChars = set(initChars) self.maxSpecified = (max > 0) if (min < 1): raise ValueError('cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted') self.minLen = min if (max > 0): self.maxLen = max else: self.maxLen = _MAX_INT if (exact > 0): self.maxLen = exact self.minLen = exact self.name = _ustr(self) self.errmsg = ('Expected ' + self.name) self.mayIndexError = False self.asKeyword = asKeyword if ((' ' not in (self.initCharsOrig + self.bodyCharsOrig)) and ((min == 1) and (max == 0) and (exact == 0))): if (self.bodyCharsOrig == self.initCharsOrig): self.reString = ('[%s]+' % _escapeRegexRangeChars(self.initCharsOrig)) elif (len(self.bodyCharsOrig) == 1): self.reString = ('%s[%s]*' % (re.escape(self.initCharsOrig), _escapeRegexRangeChars(self.bodyCharsOrig))) else: self.reString = ('[%s][%s]*' % (_escapeRegexRangeChars(self.initCharsOrig), _escapeRegexRangeChars(self.bodyCharsOrig))) if self.asKeyword: self.reString = (('\\b' + self.reString) + '\\b') try: self.re = re.compile(self.reString) except: self.re = None def parseImpl(self, instring, loc, doActions=True): if self.re: result = self.re.match(instring, loc) if (not result): raise ParseException(instring, loc, self.errmsg, self) loc = result.end() return (loc, result.group()) if (not (instring[loc] in self.initChars)): raise ParseException(instring, loc, self.errmsg, self) start = loc loc += 1 instrlen = len(instring) bodychars = self.bodyChars maxloc = (start + self.maxLen) maxloc = min(maxloc, instrlen) while ((loc < maxloc) and (instring[loc] in bodychars)): loc += 1 throwException = False if ((loc - start) < self.minLen): throwException = True if (self.maxSpecified and (loc < instrlen) and (instring[loc] in bodychars)): throwException = True if self.asKeyword: if (((start > 0) and (instring[(start - 1)] in bodychars)) or ((loc < instrlen) and (instring[loc] in bodychars))): throwException = True if throwException: raise ParseException(instring, loc, self.errmsg, self) return (loc, instring[start:loc]) def __str__(self): try: return super(Word, self).__str__() except: pass if (self.strRepr is None): def charsAsStr(s): if (len(s) > 4): return (s[:4] + '...') else: return s if (self.initCharsOrig != self.bodyCharsOrig): self.strRepr = ('W:(%s,%s)' % (charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig))) else: self.strRepr = ('W:(%s)' % charsAsStr(self.initCharsOrig)) return self.strRepr
class Regex(Token): 'Token for matching strings that match a given regular expression.\n Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module.\n ' compiledREtype = type(re.compile('[A-Z]')) def __init__(self, pattern, flags=0): 'The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags.' super(Regex, self).__init__() if isinstance(pattern, basestring): if (len(pattern) == 0): warnings.warn('null string passed to Regex; use Empty() instead', SyntaxWarning, stacklevel=2) self.pattern = pattern self.flags = flags try: self.re = re.compile(self.pattern, self.flags) self.reString = self.pattern except sre_constants.error: warnings.warn(('invalid pattern (%s) passed to Regex' % pattern), SyntaxWarning, stacklevel=2) raise elif isinstance(pattern, Regex.compiledREtype): self.re = pattern self.pattern = self.reString = str(pattern) self.flags = flags else: raise ValueError('Regex may only be constructed with a string or a compiled RE object') self.name = _ustr(self) self.errmsg = ('Expected ' + self.name) self.mayIndexError = False self.mayReturnEmpty = True def parseImpl(self, instring, loc, doActions=True): result = self.re.match(instring, loc) if (not result): raise ParseException(instring, loc, self.errmsg, self) loc = result.end() d = result.groupdict() ret = ParseResults(result.group()) if d: for k in d: ret[k] = d[k] return (loc, ret) def __str__(self): try: return super(Regex, self).__str__() except: pass if (self.strRepr is None): self.strRepr = ('Re:(%s)' % repr(self.pattern)) return self.strRepr
class QuotedString(Token): 'Token for matching strings that are delimited by quoting characters.\n ' def __init__(self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None): '\n Defined with the following parameters:\n - quoteChar - string of one or more characters defining the quote delimiting string\n - escChar - character to escape quotes, typically backslash (default=None)\n - escQuote - special quote sequence to escape an embedded quote string (such as SQL\'s "" to escape an embedded ") (default=None)\n - multiline - boolean indicating whether quotes can span multiple lines (default=C{False})\n - unquoteResults - boolean indicating whether the matched text should be unquoted (default=C{True})\n - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=C{None} => same as quoteChar)\n ' super(QuotedString, self).__init__() quoteChar = quoteChar.strip() if (len(quoteChar) == 0): warnings.warn('quoteChar cannot be the empty string', SyntaxWarning, stacklevel=2) raise SyntaxError() if (endQuoteChar is None): endQuoteChar = quoteChar else: endQuoteChar = endQuoteChar.strip() if (len(endQuoteChar) == 0): warnings.warn('endQuoteChar cannot be the empty string', SyntaxWarning, stacklevel=2) raise SyntaxError() self.quoteChar = quoteChar self.quoteCharLen = len(quoteChar) self.firstQuoteChar = quoteChar[0] self.endQuoteChar = endQuoteChar self.endQuoteCharLen = len(endQuoteChar) self.escChar = escChar self.escQuote = escQuote self.unquoteResults = unquoteResults if multiline: self.flags = (re.MULTILINE | re.DOTALL) self.pattern = ('%s(?:[^%s%s]' % (re.escape(self.quoteChar), _escapeRegexRangeChars(self.endQuoteChar[0]), (((escChar is not None) and _escapeRegexRangeChars(escChar)) or ''))) else: self.flags = 0 self.pattern = ('%s(?:[^%s\\n\\r%s]' % (re.escape(self.quoteChar), _escapeRegexRangeChars(self.endQuoteChar[0]), (((escChar is not None) and _escapeRegexRangeChars(escChar)) or ''))) if (len(self.endQuoteChar) > 1): self.pattern += (('|(?:' + ')|(?:'.join((('%s[^%s]' % (re.escape(self.endQuoteChar[:i]), _escapeRegexRangeChars(self.endQuoteChar[i]))) for i in range((len(self.endQuoteChar) - 1), 0, (- 1))))) + ')') if escQuote: self.pattern += ('|(?:%s)' % re.escape(escQuote)) if escChar: self.pattern += ('|(?:%s.)' % re.escape(escChar)) charset = ''.join(set((self.quoteChar[0] + self.endQuoteChar[0]))).replace('^', '\\^').replace('-', '\\-') self.escCharReplacePattern = (re.escape(self.escChar) + ('([%s])' % charset)) self.pattern += (')*%s' % re.escape(self.endQuoteChar)) try: self.re = re.compile(self.pattern, self.flags) self.reString = self.pattern except sre_constants.error: warnings.warn(('invalid pattern (%s) passed to Regex' % self.pattern), SyntaxWarning, stacklevel=2) raise self.name = _ustr(self) self.errmsg = ('Expected ' + self.name) self.mayIndexError = False self.mayReturnEmpty = True def parseImpl(self, instring, loc, doActions=True): result = (((instring[loc] == self.firstQuoteChar) and self.re.match(instring, loc)) or None) if (not result): raise ParseException(instring, loc, self.errmsg, self) loc = result.end() ret = result.group() if self.unquoteResults: ret = ret[self.quoteCharLen:(- self.endQuoteCharLen)] if isinstance(ret, basestring): if self.escChar: ret = re.sub(self.escCharReplacePattern, '\\g<1>', ret) if self.escQuote: ret = ret.replace(self.escQuote, self.endQuoteChar) return (loc, ret) def __str__(self): try: return super(QuotedString, self).__str__() except: pass if (self.strRepr is None): self.strRepr = ('quoted string, starting with %s ending with %s' % (self.quoteChar, self.endQuoteChar)) return self.strRepr
class CharsNotIn(Token): 'Token for matching words composed of characters *not* in a given set.\n Defined with string containing all disallowed characters, and an optional\n minimum, maximum, and/or exact length. The default value for C{min} is 1 (a\n minimum value < 1 is not valid); the default values for C{max} and C{exact}\n are 0, meaning no maximum or exact length restriction.\n ' def __init__(self, notChars, min=1, max=0, exact=0): super(CharsNotIn, self).__init__() self.skipWhitespace = False self.notChars = notChars if (min < 1): raise ValueError('cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted') self.minLen = min if (max > 0): self.maxLen = max else: self.maxLen = _MAX_INT if (exact > 0): self.maxLen = exact self.minLen = exact self.name = _ustr(self) self.errmsg = ('Expected ' + self.name) self.mayReturnEmpty = (self.minLen == 0) self.mayIndexError = False def parseImpl(self, instring, loc, doActions=True): if (instring[loc] in self.notChars): raise ParseException(instring, loc, self.errmsg, self) start = loc loc += 1 notchars = self.notChars maxlen = min((start + self.maxLen), len(instring)) while ((loc < maxlen) and (instring[loc] not in notchars)): loc += 1 if ((loc - start) < self.minLen): raise ParseException(instring, loc, self.errmsg, self) return (loc, instring[start:loc]) def __str__(self): try: return super(CharsNotIn, self).__str__() except: pass if (self.strRepr is None): if (len(self.notChars) > 4): self.strRepr = ('!W:(%s...)' % self.notChars[:4]) else: self.strRepr = ('!W:(%s)' % self.notChars) return self.strRepr
class White(Token): 'Special matching class for matching whitespace. Normally, whitespace is ignored\n by pyparsing grammars. This class is included when some whitespace structures\n are significant. Define with a string containing the whitespace characters to be\n matched; default is C{" \\t\\r\\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments,\n as defined for the C{L{Word}} class.' whiteStrs = {' ': '<SPC>', '\t': '<TAB>', '\n': '<LF>', '\r': '<CR>', '\x0c': '<FF>'} def __init__(self, ws=' \t\r\n', min=1, max=0, exact=0): super(White, self).__init__() self.matchWhite = ws self.setWhitespaceChars(''.join((c for c in self.whiteChars if (c not in self.matchWhite)))) self.name = ''.join((White.whiteStrs[c] for c in self.matchWhite)) self.mayReturnEmpty = True self.errmsg = ('Expected ' + self.name) self.minLen = min if (max > 0): self.maxLen = max else: self.maxLen = _MAX_INT if (exact > 0): self.maxLen = exact self.minLen = exact def parseImpl(self, instring, loc, doActions=True): if (not (instring[loc] in self.matchWhite)): raise ParseException(instring, loc, self.errmsg, self) start = loc loc += 1 maxloc = (start + self.maxLen) maxloc = min(maxloc, len(instring)) while ((loc < maxloc) and (instring[loc] in self.matchWhite)): loc += 1 if ((loc - start) < self.minLen): raise ParseException(instring, loc, self.errmsg, self) return (loc, instring[start:loc])
class _PositionToken(Token): def __init__(self): super(_PositionToken, self).__init__() self.name = self.__class__.__name__ self.mayReturnEmpty = True self.mayIndexError = False
class GoToColumn(_PositionToken): 'Token to advance to a specific column of input text; useful for tabular report scraping.' def __init__(self, colno): super(GoToColumn, self).__init__() self.col = colno def preParse(self, instring, loc): if (col(loc, instring) != self.col): instrlen = len(instring) if self.ignoreExprs: loc = self._skipIgnorables(instring, loc) while ((loc < instrlen) and instring[loc].isspace() and (col(loc, instring) != self.col)): loc += 1 return loc def parseImpl(self, instring, loc, doActions=True): thiscol = col(loc, instring) if (thiscol > self.col): raise ParseException(instring, loc, 'Text not in expected column', self) newloc = ((loc + self.col) - thiscol) ret = instring[loc:newloc] return (newloc, ret)
class LineStart(_PositionToken): 'Matches if current position is at the beginning of a line within the parse string' def __init__(self): super(LineStart, self).__init__() self.setWhitespaceChars(ParserElement.DEFAULT_WHITE_CHARS.replace('\n', '')) self.errmsg = 'Expected start of line' def preParse(self, instring, loc): preloc = super(LineStart, self).preParse(instring, loc) if (instring[preloc] == '\n'): loc += 1 return loc def parseImpl(self, instring, loc, doActions=True): if (not ((loc == 0) or (loc == self.preParse(instring, 0)) or (instring[(loc - 1)] == '\n'))): raise ParseException(instring, loc, self.errmsg, self) return (loc, [])
class LineEnd(_PositionToken): 'Matches if current position is at the end of a line within the parse string' def __init__(self): super(LineEnd, self).__init__() self.setWhitespaceChars(ParserElement.DEFAULT_WHITE_CHARS.replace('\n', '')) self.errmsg = 'Expected end of line' def parseImpl(self, instring, loc, doActions=True): if (loc < len(instring)): if (instring[loc] == '\n'): return ((loc + 1), '\n') else: raise ParseException(instring, loc, self.errmsg, self) elif (loc == len(instring)): return ((loc + 1), []) else: raise ParseException(instring, loc, self.errmsg, self)
class StringStart(_PositionToken): 'Matches if current position is at the beginning of the parse string' def __init__(self): super(StringStart, self).__init__() self.errmsg = 'Expected start of text' def parseImpl(self, instring, loc, doActions=True): if (loc != 0): if (loc != self.preParse(instring, 0)): raise ParseException(instring, loc, self.errmsg, self) return (loc, [])
class StringEnd(_PositionToken): 'Matches if current position is at the end of the parse string' def __init__(self): super(StringEnd, self).__init__() self.errmsg = 'Expected end of text' def parseImpl(self, instring, loc, doActions=True): if (loc < len(instring)): raise ParseException(instring, loc, self.errmsg, self) elif (loc == len(instring)): return ((loc + 1), []) elif (loc > len(instring)): return (loc, []) else: raise ParseException(instring, loc, self.errmsg, self)
class WordStart(_PositionToken): 'Matches if the current position is at the beginning of a Word, and\n is not preceded by any character in a given set of C{wordChars}\n (default=C{printables}). To emulate the C{\x08} behavior of regular expressions,\n use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of\n the string being parsed, or at the beginning of a line.\n ' def __init__(self, wordChars=printables): super(WordStart, self).__init__() self.wordChars = set(wordChars) self.errmsg = 'Not at the start of a word' def parseImpl(self, instring, loc, doActions=True): if (loc != 0): if ((instring[(loc - 1)] in self.wordChars) or (instring[loc] not in self.wordChars)): raise ParseException(instring, loc, self.errmsg, self) return (loc, [])
class WordEnd(_PositionToken): 'Matches if the current position is at the end of a Word, and\n is not followed by any character in a given set of C{wordChars}\n (default=C{printables}). To emulate the C{\x08} behavior of regular expressions,\n use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of\n the string being parsed, or at the end of a line.\n ' def __init__(self, wordChars=printables): super(WordEnd, self).__init__() self.wordChars = set(wordChars) self.skipWhitespace = False self.errmsg = 'Not at the end of a word' def parseImpl(self, instring, loc, doActions=True): instrlen = len(instring) if ((instrlen > 0) and (loc < instrlen)): if ((instring[loc] in self.wordChars) or (instring[(loc - 1)] not in self.wordChars)): raise ParseException(instring, loc, self.errmsg, self) return (loc, [])
class ParseExpression(ParserElement): 'Abstract subclass of ParserElement, for combining and post-processing parsed tokens.' def __init__(self, exprs, savelist=False): super(ParseExpression, self).__init__(savelist) if isinstance(exprs, _generatorType): exprs = list(exprs) if isinstance(exprs, basestring): self.exprs = [Literal(exprs)] elif isinstance(exprs, collections.Sequence): if all((isinstance(expr, basestring) for expr in exprs)): exprs = map(Literal, exprs) self.exprs = list(exprs) else: try: self.exprs = list(exprs) except TypeError: self.exprs = [exprs] self.callPreparse = False def __getitem__(self, i): return self.exprs[i] def append(self, other): self.exprs.append(other) self.strRepr = None return self def leaveWhitespace(self): 'Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on\n all contained expressions.' self.skipWhitespace = False self.exprs = [e.copy() for e in self.exprs] for e in self.exprs: e.leaveWhitespace() return self def ignore(self, other): if isinstance(other, Suppress): if (other not in self.ignoreExprs): super(ParseExpression, self).ignore(other) for e in self.exprs: e.ignore(self.ignoreExprs[(- 1)]) else: super(ParseExpression, self).ignore(other) for e in self.exprs: e.ignore(self.ignoreExprs[(- 1)]) return self def __str__(self): try: return super(ParseExpression, self).__str__() except: pass if (self.strRepr is None): self.strRepr = ('%s:(%s)' % (self.__class__.__name__, _ustr(self.exprs))) return self.strRepr def streamline(self): super(ParseExpression, self).streamline() for e in self.exprs: e.streamline() if (len(self.exprs) == 2): other = self.exprs[0] if (isinstance(other, self.__class__) and (not other.parseAction) and (other.resultsName is None) and (not other.debug)): self.exprs = (other.exprs[:] + [self.exprs[1]]) self.strRepr = None self.mayReturnEmpty |= other.mayReturnEmpty self.mayIndexError |= other.mayIndexError other = self.exprs[(- 1)] if (isinstance(other, self.__class__) and (not other.parseAction) and (other.resultsName is None) and (not other.debug)): self.exprs = (self.exprs[:(- 1)] + other.exprs[:]) self.strRepr = None self.mayReturnEmpty |= other.mayReturnEmpty self.mayIndexError |= other.mayIndexError return self def setResultsName(self, name, listAllMatches=False): ret = super(ParseExpression, self).setResultsName(name, listAllMatches) return ret def validate(self, validateTrace=[]): tmp = (validateTrace[:] + [self]) for e in self.exprs: e.validate(tmp) self.checkRecursion([]) def copy(self): ret = super(ParseExpression, self).copy() ret.exprs = [e.copy() for e in self.exprs] return ret
class And(ParseExpression): "Requires all given C{ParseExpression}s to be found in the given order.\n Expressions may be separated by whitespace.\n May be constructed using the C{'+'} operator.\n " class _ErrorStop(Empty): def __init__(self, *args, **kwargs): super(And._ErrorStop, self).__init__(*args, **kwargs) self.name = '-' self.leaveWhitespace() def __init__(self, exprs, savelist=True): super(And, self).__init__(exprs, savelist) self.mayReturnEmpty = all((e.mayReturnEmpty for e in self.exprs)) self.setWhitespaceChars(exprs[0].whiteChars) self.skipWhitespace = exprs[0].skipWhitespace self.callPreparse = True def parseImpl(self, instring, loc, doActions=True): (loc, resultlist) = self.exprs[0]._parse(instring, loc, doActions, callPreParse=False) errorStop = False for e in self.exprs[1:]: if isinstance(e, And._ErrorStop): errorStop = True continue if errorStop: try: (loc, exprtokens) = e._parse(instring, loc, doActions) except ParseSyntaxException: raise except ParseBaseException as pe: pe.__traceback__ = None raise ParseSyntaxException(pe) except IndexError: raise ParseSyntaxException(ParseException(instring, len(instring), self.errmsg, self)) else: (loc, exprtokens) = e._parse(instring, loc, doActions) if (exprtokens or exprtokens.haskeys()): resultlist += exprtokens return (loc, resultlist) def __iadd__(self, other): if isinstance(other, basestring): other = Literal(other) return self.append(other) def checkRecursion(self, parseElementList): subRecCheckList = (parseElementList[:] + [self]) for e in self.exprs: e.checkRecursion(subRecCheckList) if (not e.mayReturnEmpty): break def __str__(self): if hasattr(self, 'name'): return self.name if (self.strRepr is None): self.strRepr = (('{' + ' '.join((_ustr(e) for e in self.exprs))) + '}') return self.strRepr
class Or(ParseExpression): "Requires that at least one C{ParseExpression} is found.\n If two expressions match, the expression that matches the longest string will be used.\n May be constructed using the C{'^'} operator.\n " def __init__(self, exprs, savelist=False): super(Or, self).__init__(exprs, savelist) if self.exprs: self.mayReturnEmpty = any((e.mayReturnEmpty for e in self.exprs)) else: self.mayReturnEmpty = True def parseImpl(self, instring, loc, doActions=True): maxExcLoc = (- 1) maxMatchLoc = (- 1) maxException = None for e in self.exprs: try: loc2 = e.tryParse(instring, loc) except ParseException as err: err.__traceback__ = None if (err.loc > maxExcLoc): maxException = err maxExcLoc = err.loc except IndexError: if (len(instring) > maxExcLoc): maxException = ParseException(instring, len(instring), e.errmsg, self) maxExcLoc = len(instring) else: if (loc2 > maxMatchLoc): maxMatchLoc = loc2 maxMatchExp = e if (maxMatchLoc < 0): if (maxException is not None): raise maxException else: raise ParseException(instring, loc, 'no defined alternatives to match', self) return maxMatchExp._parse(instring, loc, doActions) def __ixor__(self, other): if isinstance(other, basestring): other = ParserElement.literalStringClass(other) return self.append(other) def __str__(self): if hasattr(self, 'name'): return self.name if (self.strRepr is None): self.strRepr = (('{' + ' ^ '.join((_ustr(e) for e in self.exprs))) + '}') return self.strRepr def checkRecursion(self, parseElementList): subRecCheckList = (parseElementList[:] + [self]) for e in self.exprs: e.checkRecursion(subRecCheckList)
class MatchFirst(ParseExpression): "Requires that at least one C{ParseExpression} is found.\n If two expressions match, the first one listed is the one that will match.\n May be constructed using the C{'|'} operator.\n " def __init__(self, exprs, savelist=False): super(MatchFirst, self).__init__(exprs, savelist) if self.exprs: self.mayReturnEmpty = any((e.mayReturnEmpty for e in self.exprs)) else: self.mayReturnEmpty = True def parseImpl(self, instring, loc, doActions=True): maxExcLoc = (- 1) maxException = None for e in self.exprs: try: ret = e._parse(instring, loc, doActions) return ret except ParseException as err: if (err.loc > maxExcLoc): maxException = err maxExcLoc = err.loc except IndexError: if (len(instring) > maxExcLoc): maxException = ParseException(instring, len(instring), e.errmsg, self) maxExcLoc = len(instring) else: if (maxException is not None): raise maxException else: raise ParseException(instring, loc, 'no defined alternatives to match', self) def __ior__(self, other): if isinstance(other, basestring): other = ParserElement.literalStringClass(other) return self.append(other) def __str__(self): if hasattr(self, 'name'): return self.name if (self.strRepr is None): self.strRepr = (('{' + ' | '.join((_ustr(e) for e in self.exprs))) + '}') return self.strRepr def checkRecursion(self, parseElementList): subRecCheckList = (parseElementList[:] + [self]) for e in self.exprs: e.checkRecursion(subRecCheckList)
class Each(ParseExpression): "Requires all given C{ParseExpression}s to be found, but in any order.\n Expressions may be separated by whitespace.\n May be constructed using the C{'&'} operator.\n " def __init__(self, exprs, savelist=True): super(Each, self).__init__(exprs, savelist) self.mayReturnEmpty = all((e.mayReturnEmpty for e in self.exprs)) self.skipWhitespace = True self.initExprGroups = True def parseImpl(self, instring, loc, doActions=True): if self.initExprGroups: opt1 = [e.expr for e in self.exprs if isinstance(e, Optional)] opt2 = [e for e in self.exprs if (e.mayReturnEmpty and (e not in opt1))] self.optionals = (opt1 + opt2) self.multioptionals = [e.expr for e in self.exprs if isinstance(e, ZeroOrMore)] self.multirequired = [e.expr for e in self.exprs if isinstance(e, OneOrMore)] self.required = [e for e in self.exprs if (not isinstance(e, (Optional, ZeroOrMore, OneOrMore)))] self.required += self.multirequired self.initExprGroups = False tmpLoc = loc tmpReqd = self.required[:] tmpOpt = self.optionals[:] matchOrder = [] keepMatching = True while keepMatching: tmpExprs = (((tmpReqd + tmpOpt) + self.multioptionals) + self.multirequired) failed = [] for e in tmpExprs: try: tmpLoc = e.tryParse(instring, tmpLoc) except ParseException: failed.append(e) else: matchOrder.append(e) if (e in tmpReqd): tmpReqd.remove(e) elif (e in tmpOpt): tmpOpt.remove(e) if (len(failed) == len(tmpExprs)): keepMatching = False if tmpReqd: missing = ', '.join((_ustr(e) for e in tmpReqd)) raise ParseException(instring, loc, ('Missing one or more required elements (%s)' % missing)) matchOrder += [e for e in self.exprs if (isinstance(e, Optional) and (e.expr in tmpOpt))] resultlist = [] for e in matchOrder: (loc, results) = e._parse(instring, loc, doActions) resultlist.append(results) finalResults = ParseResults([]) for r in resultlist: dups = {} for k in r.keys(): if (k in finalResults): tmp = ParseResults(finalResults[k]) tmp += ParseResults(r[k]) dups[k] = tmp finalResults += ParseResults(r) for (k, v) in dups.items(): finalResults[k] = v return (loc, finalResults) def __str__(self): if hasattr(self, 'name'): return self.name if (self.strRepr is None): self.strRepr = (('{' + ' & '.join((_ustr(e) for e in self.exprs))) + '}') return self.strRepr def checkRecursion(self, parseElementList): subRecCheckList = (parseElementList[:] + [self]) for e in self.exprs: e.checkRecursion(subRecCheckList)
class ParseElementEnhance(ParserElement): 'Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens.' def __init__(self, expr, savelist=False): super(ParseElementEnhance, self).__init__(savelist) if isinstance(expr, basestring): expr = Literal(expr) self.expr = expr self.strRepr = None if (expr is not None): self.mayIndexError = expr.mayIndexError self.mayReturnEmpty = expr.mayReturnEmpty self.setWhitespaceChars(expr.whiteChars) self.skipWhitespace = expr.skipWhitespace self.saveAsList = expr.saveAsList self.callPreparse = expr.callPreparse self.ignoreExprs.extend(expr.ignoreExprs) def parseImpl(self, instring, loc, doActions=True): if (self.expr is not None): return self.expr._parse(instring, loc, doActions, callPreParse=False) else: raise ParseException('', loc, self.errmsg, self) def leaveWhitespace(self): self.skipWhitespace = False self.expr = self.expr.copy() if (self.expr is not None): self.expr.leaveWhitespace() return self def ignore(self, other): if isinstance(other, Suppress): if (other not in self.ignoreExprs): super(ParseElementEnhance, self).ignore(other) if (self.expr is not None): self.expr.ignore(self.ignoreExprs[(- 1)]) else: super(ParseElementEnhance, self).ignore(other) if (self.expr is not None): self.expr.ignore(self.ignoreExprs[(- 1)]) return self def streamline(self): super(ParseElementEnhance, self).streamline() if (self.expr is not None): self.expr.streamline() return self def checkRecursion(self, parseElementList): if (self in parseElementList): raise RecursiveGrammarException((parseElementList + [self])) subRecCheckList = (parseElementList[:] + [self]) if (self.expr is not None): self.expr.checkRecursion(subRecCheckList) def validate(self, validateTrace=[]): tmp = (validateTrace[:] + [self]) if (self.expr is not None): self.expr.validate(tmp) self.checkRecursion([]) def __str__(self): try: return super(ParseElementEnhance, self).__str__() except: pass if ((self.strRepr is None) and (self.expr is not None)): self.strRepr = ('%s:(%s)' % (self.__class__.__name__, _ustr(self.expr))) return self.strRepr
class FollowedBy(ParseElementEnhance): 'Lookahead matching of the given parse expression. C{FollowedBy}\n does *not* advance the parsing position within the input string, it only\n verifies that the specified parse expression matches at the current\n position. C{FollowedBy} always returns a null token list.' def __init__(self, expr): super(FollowedBy, self).__init__(expr) self.mayReturnEmpty = True def parseImpl(self, instring, loc, doActions=True): self.expr.tryParse(instring, loc) return (loc, [])
class NotAny(ParseElementEnhance): "Lookahead to disallow matching with the given parse expression. C{NotAny}\n does *not* advance the parsing position within the input string, it only\n verifies that the specified parse expression does *not* match at the current\n position. Also, C{NotAny} does *not* skip over leading whitespace. C{NotAny}\n always returns a null token list. May be constructed using the '~' operator." def __init__(self, expr): super(NotAny, self).__init__(expr) self.skipWhitespace = False self.mayReturnEmpty = True self.errmsg = ('Found unwanted token, ' + _ustr(self.expr)) def parseImpl(self, instring, loc, doActions=True): try: self.expr.tryParse(instring, loc) except (ParseException, IndexError): pass else: raise ParseException(instring, loc, self.errmsg, self) return (loc, []) def __str__(self): if hasattr(self, 'name'): return self.name if (self.strRepr is None): self.strRepr = (('~{' + _ustr(self.expr)) + '}') return self.strRepr
class ZeroOrMore(ParseElementEnhance): 'Optional repetition of zero or more of the given expression.' def __init__(self, expr): super(ZeroOrMore, self).__init__(expr) self.mayReturnEmpty = True def parseImpl(self, instring, loc, doActions=True): tokens = [] try: (loc, tokens) = self.expr._parse(instring, loc, doActions, callPreParse=False) hasIgnoreExprs = (len(self.ignoreExprs) > 0) while 1: if hasIgnoreExprs: preloc = self._skipIgnorables(instring, loc) else: preloc = loc (loc, tmptokens) = self.expr._parse(instring, preloc, doActions) if (tmptokens or tmptokens.haskeys()): tokens += tmptokens except (ParseException, IndexError): pass return (loc, tokens) def __str__(self): if hasattr(self, 'name'): return self.name if (self.strRepr is None): self.strRepr = (('[' + _ustr(self.expr)) + ']...') return self.strRepr def setResultsName(self, name, listAllMatches=False): ret = super(ZeroOrMore, self).setResultsName(name, listAllMatches) ret.saveAsList = True return ret
class OneOrMore(ParseElementEnhance): 'Repetition of one or more of the given expression.' def parseImpl(self, instring, loc, doActions=True): (loc, tokens) = self.expr._parse(instring, loc, doActions, callPreParse=False) try: hasIgnoreExprs = (len(self.ignoreExprs) > 0) while 1: if hasIgnoreExprs: preloc = self._skipIgnorables(instring, loc) else: preloc = loc (loc, tmptokens) = self.expr._parse(instring, preloc, doActions) if (tmptokens or tmptokens.haskeys()): tokens += tmptokens except (ParseException, IndexError): pass return (loc, tokens) def __str__(self): if hasattr(self, 'name'): return self.name if (self.strRepr is None): self.strRepr = (('{' + _ustr(self.expr)) + '}...') return self.strRepr def setResultsName(self, name, listAllMatches=False): ret = super(OneOrMore, self).setResultsName(name, listAllMatches) ret.saveAsList = True return ret
class _NullToken(object): def __bool__(self): return False __nonzero__ = __bool__ def __str__(self): return ''
class Optional(ParseElementEnhance): 'Optional matching of the given expression.\n A default return string can also be specified, if the optional expression\n is not found.\n ' def __init__(self, expr, default=_optionalNotMatched): super(Optional, self).__init__(expr, savelist=False) self.defaultValue = default self.mayReturnEmpty = True def parseImpl(self, instring, loc, doActions=True): try: (loc, tokens) = self.expr._parse(instring, loc, doActions, callPreParse=False) except (ParseException, IndexError): if (self.defaultValue is not _optionalNotMatched): if self.expr.resultsName: tokens = ParseResults([self.defaultValue]) tokens[self.expr.resultsName] = self.defaultValue else: tokens = [self.defaultValue] else: tokens = [] return (loc, tokens) def __str__(self): if hasattr(self, 'name'): return self.name if (self.strRepr is None): self.strRepr = (('[' + _ustr(self.expr)) + ']') return self.strRepr
class SkipTo(ParseElementEnhance): 'Token for skipping over all undefined text until the matched expression is found.\n If C{include} is set to true, the matched expression is also parsed (the skipped text\n and matched expression are returned as a 2-element list). The C{ignore}\n argument is used to define grammars (typically quoted strings and comments) that\n might contain false matches.\n ' def __init__(self, other, include=False, ignore=None, failOn=None): super(SkipTo, self).__init__(other) self.ignoreExpr = ignore self.mayReturnEmpty = True self.mayIndexError = False self.includeMatch = include self.asList = False if ((failOn is not None) and isinstance(failOn, basestring)): self.failOn = Literal(failOn) else: self.failOn = failOn self.errmsg = ('No match found for ' + _ustr(self.expr)) def parseImpl(self, instring, loc, doActions=True): startLoc = loc instrlen = len(instring) expr = self.expr failParse = False while (loc <= instrlen): try: if self.failOn: try: self.failOn.tryParse(instring, loc) except ParseBaseException: pass else: failParse = True raise ParseException(instring, loc, ('Found expression ' + str(self.failOn))) failParse = False if (self.ignoreExpr is not None): while 1: try: loc = self.ignoreExpr.tryParse(instring, loc) except ParseBaseException: break expr._parse(instring, loc, doActions=False, callPreParse=False) skipText = instring[startLoc:loc] if self.includeMatch: (loc, mat) = expr._parse(instring, loc, doActions, callPreParse=False) if mat: skipRes = ParseResults(skipText) skipRes += mat return (loc, [skipRes]) else: return (loc, [skipText]) else: return (loc, [skipText]) except (ParseException, IndexError): if failParse: raise else: loc += 1 raise ParseException(instring, loc, self.errmsg, self)
class Forward(ParseElementEnhance): "Forward declaration of an expression to be defined later -\n used for recursive grammars, such as algebraic infix notation.\n When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator.\n\n Note: take care when assigning to C{Forward} not to overlook precedence of operators.\n Specifically, '|' has a lower precedence than '<<', so that::\n fwdExpr << a | b | c\n will actually be evaluated as::\n (fwdExpr << a) | b | c\n thereby leaving b and c out as parseable alternatives. It is recommended that you\n explicitly group the values inserted into the C{Forward}::\n fwdExpr << (a | b | c)\n Converting to use the '<<=' operator instead will avoid this problem.\n " def __init__(self, other=None): super(Forward, self).__init__(other, savelist=False) def __lshift__(self, other): if isinstance(other, basestring): other = ParserElement.literalStringClass(other) self.expr = other self.mayReturnEmpty = other.mayReturnEmpty self.strRepr = None self.mayIndexError = self.expr.mayIndexError self.mayReturnEmpty = self.expr.mayReturnEmpty self.setWhitespaceChars(self.expr.whiteChars) self.skipWhitespace = self.expr.skipWhitespace self.saveAsList = self.expr.saveAsList self.ignoreExprs.extend(self.expr.ignoreExprs) return self def __ilshift__(self, other): return (self << other) def leaveWhitespace(self): self.skipWhitespace = False return self def streamline(self): if (not self.streamlined): self.streamlined = True if (self.expr is not None): self.expr.streamline() return self def validate(self, validateTrace=[]): if (self not in validateTrace): tmp = (validateTrace[:] + [self]) if (self.expr is not None): self.expr.validate(tmp) self.checkRecursion([]) def __str__(self): if hasattr(self, 'name'): return self.name self._revertClass = self.__class__ self.__class__ = _ForwardNoRecurse try: if (self.expr is not None): retString = _ustr(self.expr) else: retString = 'None' finally: self.__class__ = self._revertClass return ((self.__class__.__name__ + ': ') + retString) def copy(self): if (self.expr is not None): return super(Forward, self).copy() else: ret = Forward() ret <<= self return ret
class _ForwardNoRecurse(Forward): def __str__(self): return '...'
class TokenConverter(ParseElementEnhance): 'Abstract subclass of C{ParseExpression}, for converting parsed results.' def __init__(self, expr, savelist=False): super(TokenConverter, self).__init__(expr) self.saveAsList = False
class Upcase(TokenConverter): 'Converter to upper case all matching tokens.' def __init__(self, *args): super(Upcase, self).__init__(*args) warnings.warn('Upcase class is deprecated, use upcaseTokens parse action instead', DeprecationWarning, stacklevel=2) def postParse(self, instring, loc, tokenlist): return list(map(str.upper, tokenlist))
class Combine(TokenConverter): "Converter to concatenate all matching tokens to a single string.\n By default, the matching patterns must also be contiguous in the input string;\n this can be disabled by specifying C{'adjacent=False'} in the constructor.\n " def __init__(self, expr, joinString='', adjacent=True): super(Combine, self).__init__(expr) if adjacent: self.leaveWhitespace() self.adjacent = adjacent self.skipWhitespace = True self.joinString = joinString self.callPreparse = True def ignore(self, other): if self.adjacent: ParserElement.ignore(self, other) else: super(Combine, self).ignore(other) return self def postParse(self, instring, loc, tokenlist): retToks = tokenlist.copy() del retToks[:] retToks += ParseResults([''.join(tokenlist._asStringList(self.joinString))], modal=self.modalResults) if (self.resultsName and retToks.haskeys()): return [retToks] else: return retToks
class Group(TokenConverter): 'Converter to return the matched tokens as a list - useful for returning tokens of C{L{ZeroOrMore}} and C{L{OneOrMore}} expressions.' def __init__(self, expr): super(Group, self).__init__(expr) self.saveAsList = True def postParse(self, instring, loc, tokenlist): return [tokenlist]
class Dict(TokenConverter): 'Converter to return a repetitive expression as a list, but also as a dictionary.\n Each element can also be referenced using the first token in the expression as its key.\n Useful for tabular report scraping when the first column can be used as a item key.\n ' def __init__(self, expr): super(Dict, self).__init__(expr) self.saveAsList = True def postParse(self, instring, loc, tokenlist): for (i, tok) in enumerate(tokenlist): if (len(tok) == 0): continue ikey = tok[0] if isinstance(ikey, int): ikey = _ustr(tok[0]).strip() if (len(tok) == 1): tokenlist[ikey] = _ParseResultsWithOffset('', i) elif ((len(tok) == 2) and (not isinstance(tok[1], ParseResults))): tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i) else: dictvalue = tok.copy() del dictvalue[0] if ((len(dictvalue) != 1) or (isinstance(dictvalue, ParseResults) and dictvalue.haskeys())): tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i) else: tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i) if self.resultsName: return [tokenlist] else: return tokenlist
class Suppress(TokenConverter): 'Converter for ignoring the results of a parsed expression.' def postParse(self, instring, loc, tokenlist): return [] def suppress(self): return self
class OnlyOnce(object): 'Wrapper for parse actions, to ensure they are only called once.' def __init__(self, methodCall): self.callable = _trim_arity(methodCall) self.called = False def __call__(self, s, l, t): if (not self.called): results = self.callable(s, l, t) self.called = True return results raise ParseException(s, l, '') def reset(self): self.called = False
def traceParseAction(f): 'Decorator for debugging parse actions.' f = _trim_arity(f) def z(*paArgs): thisFunc = f.func_name (s, l, t) = paArgs[(- 3):] if (len(paArgs) > 3): thisFunc = ((paArgs[0].__class__.__name__ + '.') + thisFunc) sys.stderr.write((">>entering %s(line: '%s', %d, %s)\n" % (thisFunc, line(l, s), l, t))) try: ret = f(*paArgs) except Exception as exc: sys.stderr.write(('<<leaving %s (exception: %s)\n' % (thisFunc, exc))) raise sys.stderr.write(('<<leaving %s (ret: %s)\n' % (thisFunc, ret))) return ret try: z.__name__ = f.__name__ except AttributeError: pass return z
def delimitedList(expr, delim=',', combine=False): "Helper to define a delimited list of expressions - the delimiter defaults to ','.\n By default, the list elements and delimiters can have intervening whitespace, and\n comments, but this can be overridden by passing C{combine=True} in the constructor.\n If C{combine} is set to C{True}, the matching tokens are returned as a single token\n string, with the delimiters included; otherwise, the matching tokens are returned\n as a list of tokens, with the delimiters suppressed.\n " dlName = (((((_ustr(expr) + ' [') + _ustr(delim)) + ' ') + _ustr(expr)) + ']...') if combine: return Combine((expr + ZeroOrMore((delim + expr)))).setName(dlName) else: return (expr + ZeroOrMore((Suppress(delim) + expr))).setName(dlName)
def countedArray(expr, intExpr=None): 'Helper to define a counted list of expressions.\n This helper defines a pattern of the form::\n integer expr expr expr...\n where the leading integer tells how many expr expressions follow.\n The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.\n ' arrayExpr = Forward() def countFieldParseAction(s, l, t): n = t[0] (arrayExpr << ((n and Group(And(([expr] * n)))) or Group(empty))) return [] if (intExpr is None): intExpr = Word(nums).setParseAction((lambda t: int(t[0]))) else: intExpr = intExpr.copy() intExpr.setName('arrayLen') intExpr.addParseAction(countFieldParseAction, callDuringTry=True) return (intExpr + arrayExpr)
def _flatten(L): ret = [] for i in L: if isinstance(i, list): ret.extend(_flatten(i)) else: ret.append(i) return ret
def matchPreviousLiteral(expr): 'Helper to define an expression that is indirectly defined from\n the tokens matched in a previous expression, that is, it looks\n for a \'repeat\' of a previous expression. For example::\n first = Word(nums)\n second = matchPreviousLiteral(first)\n matchExpr = first + ":" + second\n will match C{"1:1"}, but not C{"1:2"}. Because this matches a\n previous literal, will also match the leading C{"1:1"} in C{"1:10"}.\n If this is not desired, use C{matchPreviousExpr}.\n Do *not* use with packrat parsing enabled.\n ' rep = Forward() def copyTokenToRepeater(s, l, t): if t: if (len(t) == 1): (rep << t[0]) else: tflat = _flatten(t.asList()) (rep << And([Literal(tt) for tt in tflat])) else: (rep << Empty()) expr.addParseAction(copyTokenToRepeater, callDuringTry=True) return rep
def matchPreviousExpr(expr): 'Helper to define an expression that is indirectly defined from\n the tokens matched in a previous expression, that is, it looks\n for a \'repeat\' of a previous expression. For example::\n first = Word(nums)\n second = matchPreviousExpr(first)\n matchExpr = first + ":" + second\n will match C{"1:1"}, but not C{"1:2"}. Because this matches by\n expressions, will *not* match the leading C{"1:1"} in C{"1:10"};\n the expressions are evaluated first, and then compared, so\n C{"1"} is compared with C{"10"}.\n Do *not* use with packrat parsing enabled.\n ' rep = Forward() e2 = expr.copy() rep <<= e2 def copyTokenToRepeater(s, l, t): matchTokens = _flatten(t.asList()) def mustMatchTheseTokens(s, l, t): theseTokens = _flatten(t.asList()) if (theseTokens != matchTokens): raise ParseException('', 0, '') rep.setParseAction(mustMatchTheseTokens, callDuringTry=True) expr.addParseAction(copyTokenToRepeater, callDuringTry=True) return rep
def _escapeRegexRangeChars(s): for c in '\\^-]': s = s.replace(c, (_bslash + c)) s = s.replace('\n', '\\n') s = s.replace('\t', '\\t') return _ustr(s)
def oneOf(strs, caseless=False, useRegex=True): 'Helper to quickly define a set of alternative Literals, and makes sure to do\n longest-first testing when there is a conflict, regardless of the input order,\n but returns a C{L{MatchFirst}} for best performance.\n\n Parameters:\n - strs - a string of space-delimited literals, or a list of string literals\n - caseless - (default=False) - treat all literals as caseless\n - useRegex - (default=True) - as an optimization, will generate a Regex\n object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or\n if creating a C{Regex} raises an exception)\n ' if caseless: isequal = (lambda a, b: (a.upper() == b.upper())) masks = (lambda a, b: b.upper().startswith(a.upper())) parseElementClass = CaselessLiteral else: isequal = (lambda a, b: (a == b)) masks = (lambda a, b: b.startswith(a)) parseElementClass = Literal if isinstance(strs, basestring): symbols = strs.split() elif isinstance(strs, collections.Sequence): symbols = list(strs[:]) elif isinstance(strs, _generatorType): symbols = list(strs) else: warnings.warn('Invalid argument to oneOf, expected string or list', SyntaxWarning, stacklevel=2) i = 0 while (i < (len(symbols) - 1)): cur = symbols[i] for (j, other) in enumerate(symbols[(i + 1):]): if isequal(other, cur): del symbols[((i + j) + 1)] break elif masks(cur, other): del symbols[((i + j) + 1)] symbols.insert(i, other) cur = other break else: i += 1 if ((not caseless) and useRegex): try: if (len(symbols) == len(''.join(symbols))): return Regex(('[%s]' % ''.join((_escapeRegexRangeChars(sym) for sym in symbols)))) else: return Regex('|'.join((re.escape(sym) for sym in symbols))) except: warnings.warn('Exception creating Regex for oneOf, building MatchFirst', SyntaxWarning, stacklevel=2) return MatchFirst([parseElementClass(sym) for sym in symbols])
def dictOf(key, value): 'Helper to easily and clearly define a dictionary by specifying the respective patterns\n for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens\n in the proper order. The key pattern can include delimiting markers or punctuation,\n as long as they are suppressed, thereby leaving the significant key text. The value\n pattern can include named results, so that the C{Dict} results can include named token\n fields.\n ' return Dict(ZeroOrMore(Group((key + value))))
def originalTextFor(expr, asString=True): 'Helper to return the original, untokenized text for a given expression. Useful to\n restore the parsed fields of an HTML start tag into the raw tag text itself, or to\n revert separate tokens with intervening whitespace back to the original matching\n input text. Simpler to use than the parse action C{L{keepOriginalText}}, and does not\n require the inspect module to chase up the call stack. By default, returns a \n string containing the original parsed text. \n \n If the optional C{asString} argument is passed as C{False}, then the return value is a \n C{L{ParseResults}} containing any results names that were originally matched, and a \n single token containing the original matched text from the input string. So if \n the expression passed to C{L{originalTextFor}} contains expressions with defined\n results names, you must set C{asString} to C{False} if you want to preserve those\n results name values.' locMarker = Empty().setParseAction((lambda s, loc, t: loc)) endlocMarker = locMarker.copy() endlocMarker.callPreparse = False matchExpr = ((locMarker('_original_start') + expr) + endlocMarker('_original_end')) if asString: extractText = (lambda s, l, t: s[t._original_start:t._original_end]) else: def extractText(s, l, t): del t[:] t.insert(0, s[t._original_start:t._original_end]) del t['_original_start'] del t['_original_end'] matchExpr.setParseAction(extractText) return matchExpr
def ungroup(expr): "Helper to undo pyparsing's default grouping of And expressions, even\n if all but one are non-empty." return TokenConverter(expr).setParseAction((lambda t: t[0]))
def locatedExpr(expr): 'Helper to decorate a returned token with its starting and ending locations in the input string.\n This helper adds the following results names:\n - locn_start = location where matched expression begins\n - locn_end = location where matched expression ends\n - value = the actual parsed results\n\n Be careful if the input text contains C{<TAB>} characters, you may want to call\n C{L{ParserElement.parseWithTabs}}\n ' locator = Empty().setParseAction((lambda s, l, t: l)) return Group(((locator('locn_start') + expr('value')) + locator.copy().leaveWhitespace()('locn_end')))
def srange(s): 'Helper to easily define string ranges for use in Word construction. Borrows\n syntax from regexp \'[]\' string range definitions::\n srange("[0-9]") -> "0123456789"\n srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"\n srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"\n The input string must be enclosed in []\'s, and the returned string is the expanded\n character set joined into a single string.\n The values enclosed in the []\'s may be::\n a single character\n an escaped character with a leading backslash (such as \\- or \\])\n an escaped hex character with a leading \'\\x\' (\\x21, which is a \'!\' character) \n (\\0x## is also supported for backwards compatibility) \n an escaped octal character with a leading \'\\0\' (\\041, which is a \'!\' character)\n a range of any of the above, separated by a dash (\'a-z\', etc.)\n any combination of the above (\'aeiouy\', \'a-zA-Z0-9_$\', etc.)\n ' _expanded = (lambda p: (p if (not isinstance(p, ParseResults)) else ''.join((unichr(c) for c in range(ord(p[0]), (ord(p[1]) + 1)))))) try: return ''.join((_expanded(part) for part in _reBracketExpr.parseString(s).body)) except: return ''
def matchOnlyAtCol(n): 'Helper method for defining parse actions that require matching at a specific\n column in the input text.\n ' def verifyCol(strg, locn, toks): if (col(locn, strg) != n): raise ParseException(strg, locn, ('matched token not at column %d' % n)) return verifyCol
def replaceWith(replStr): 'Helper method for common parse actions that simply return a literal value. Especially\n useful when used with C{L{transformString<ParserElement.transformString>}()}.\n ' def _replFunc(*args): return [replStr] return _replFunc
def removeQuotes(s, l, t): 'Helper parse action for removing quotation marks from parsed quoted strings.\n To use, add this parse action to quoted string using::\n quotedString.setParseAction( removeQuotes )\n ' return t[0][1:(- 1)]
def upcaseTokens(s, l, t): 'Helper parse action to convert tokens to upper case.' return [tt.upper() for tt in map(_ustr, t)]
def downcaseTokens(s, l, t): 'Helper parse action to convert tokens to lower case.' return [tt.lower() for tt in map(_ustr, t)]
def keepOriginalText(s, startLoc, t): 'DEPRECATED - use new helper method C{L{originalTextFor}}.\n Helper parse action to preserve original parsed text,\n overriding any nested parse actions.' try: endloc = getTokensEndLoc() except ParseException: raise ParseFatalException('incorrect usage of keepOriginalText - may only be called as a parse action') del t[:] t += ParseResults(s[startLoc:endloc]) return t
def getTokensEndLoc(): 'Method to be called from within a parse action to determine the end\n location of the parsed tokens.' import inspect fstack = inspect.stack() try: for f in fstack[2:]: if (f[3] == '_parseNoCache'): endloc = f[0].f_locals['loc'] return endloc else: raise ParseFatalException('incorrect usage of getTokensEndLoc - may only be called from within a parse action') finally: del fstack
def _makeTags(tagStr, xml): 'Internal helper to construct opening and closing tag expressions, given a tag name' if isinstance(tagStr, basestring): resname = tagStr tagStr = Keyword(tagStr, caseless=(not xml)) else: resname = tagStr.name tagAttrName = Word(alphas, (alphanums + '_-:')) if xml: tagAttrValue = dblQuotedString.copy().setParseAction(removeQuotes) openTag = ((((Suppress('<') + tagStr('tag')) + Dict(ZeroOrMore(Group(((tagAttrName + Suppress('=')) + tagAttrValue))))) + Optional('/', default=[False]).setResultsName('empty').setParseAction((lambda s, l, t: (t[0] == '/')))) + Suppress('>')) else: printablesLessRAbrack = ''.join((c for c in printables if (c not in '>'))) tagAttrValue = (quotedString.copy().setParseAction(removeQuotes) | Word(printablesLessRAbrack)) openTag = ((((Suppress('<') + tagStr('tag')) + Dict(ZeroOrMore(Group((tagAttrName.setParseAction(downcaseTokens) + Optional((Suppress('=') + tagAttrValue))))))) + Optional('/', default=[False]).setResultsName('empty').setParseAction((lambda s, l, t: (t[0] == '/')))) + Suppress('>')) closeTag = Combine(((_L('</') + tagStr) + '>')) openTag = openTag.setResultsName(('start' + ''.join(resname.replace(':', ' ').title().split()))).setName(('<%s>' % tagStr)) closeTag = closeTag.setResultsName(('end' + ''.join(resname.replace(':', ' ').title().split()))).setName(('</%s>' % tagStr)) openTag.tag = resname closeTag.tag = resname return (openTag, closeTag)
def makeHTMLTags(tagStr): 'Helper to construct opening and closing tag expressions for HTML, given a tag name' return _makeTags(tagStr, False)
def makeXMLTags(tagStr): 'Helper to construct opening and closing tag expressions for XML, given a tag name' return _makeTags(tagStr, True)
def withAttribute(*args, **attrDict): 'Helper to create a validating parse action to be used with start tags created\n with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag\n with a required attribute value, to avoid false matches on common tags such as\n C{<TD>} or C{<DIV>}.\n\n Call C{withAttribute} with a series of attribute names and values. Specify the list\n of filter attributes names and values as:\n - keyword arguments, as in C{(align="right")}, or\n - as an explicit dict with C{**} operator, when an attribute name is also a Python\n reserved word, as in C{**{"class":"Customer", "align":"right"}}\n - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )\n For attribute names with a namespace prefix, you must use the second form. Attribute\n names are matched insensitive to upper/lower case.\n\n To verify that the attribute exists, but without specifying a value, pass\n C{withAttribute.ANY_VALUE} as the value.\n ' if args: attrs = args[:] else: attrs = attrDict.items() attrs = [(k, v) for (k, v) in attrs] def pa(s, l, tokens): for (attrName, attrValue) in attrs: if (attrName not in tokens): raise ParseException(s, l, ('no matching attribute ' + attrName)) if ((attrValue != withAttribute.ANY_VALUE) and (tokens[attrName] != attrValue)): raise ParseException(s, l, ("attribute '%s' has value '%s', must be '%s'" % (attrName, tokens[attrName], attrValue))) return pa
def infixNotation(baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')')): "Helper method for constructing grammars of expressions made up of\n operators working in a precedence hierarchy. Operators may be unary or\n binary, left- or right-associative. Parse actions can also be attached\n to operator expressions.\n\n Parameters:\n - baseExpr - expression representing the most basic element for the nested\n - opList - list of tuples, one for each operator precedence level in the\n expression grammar; each tuple is of the form\n (opExpr, numTerms, rightLeftAssoc, parseAction), where:\n - opExpr is the pyparsing expression for the operator;\n may also be a string, which will be converted to a Literal;\n if numTerms is 3, opExpr is a tuple of two expressions, for the\n two operators separating the 3 terms\n - numTerms is the number of terms for this operator (must\n be 1, 2, or 3)\n - rightLeftAssoc is the indicator whether the operator is\n right or left associative, using the pyparsing-defined\n constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}.\n - parseAction is the parse action to be associated with\n expressions matching this operator expression (the\n parse action tuple member may be omitted)\n - lpar - expression for matching left-parentheses (default=Suppress('('))\n - rpar - expression for matching right-parentheses (default=Suppress(')'))\n " ret = Forward() lastExpr = (baseExpr | ((lpar + ret) + rpar)) for (i, operDef) in enumerate(opList): (opExpr, arity, rightLeftAssoc, pa) = (operDef + (None,))[:4] if (arity == 3): if ((opExpr is None) or (len(opExpr) != 2)): raise ValueError('if numterms=3, opExpr must be a tuple or list of two expressions') (opExpr1, opExpr2) = opExpr thisExpr = Forward() if (rightLeftAssoc == opAssoc.LEFT): if (arity == 1): matchExpr = (FollowedBy((lastExpr + opExpr)) + Group((lastExpr + OneOrMore(opExpr)))) elif (arity == 2): if (opExpr is not None): matchExpr = (FollowedBy(((lastExpr + opExpr) + lastExpr)) + Group((lastExpr + OneOrMore((opExpr + lastExpr))))) else: matchExpr = (FollowedBy((lastExpr + lastExpr)) + Group((lastExpr + OneOrMore(lastExpr)))) elif (arity == 3): matchExpr = (FollowedBy(((((lastExpr + opExpr1) + lastExpr) + opExpr2) + lastExpr)) + Group(((((lastExpr + opExpr1) + lastExpr) + opExpr2) + lastExpr))) else: raise ValueError('operator must be unary (1), binary (2), or ternary (3)') elif (rightLeftAssoc == opAssoc.RIGHT): if (arity == 1): if (not isinstance(opExpr, Optional)): opExpr = Optional(opExpr) matchExpr = (FollowedBy((opExpr.expr + thisExpr)) + Group((opExpr + thisExpr))) elif (arity == 2): if (opExpr is not None): matchExpr = (FollowedBy(((lastExpr + opExpr) + thisExpr)) + Group((lastExpr + OneOrMore((opExpr + thisExpr))))) else: matchExpr = (FollowedBy((lastExpr + thisExpr)) + Group((lastExpr + OneOrMore(thisExpr)))) elif (arity == 3): matchExpr = (FollowedBy(((((lastExpr + opExpr1) + thisExpr) + opExpr2) + thisExpr)) + Group(((((lastExpr + opExpr1) + thisExpr) + opExpr2) + thisExpr))) else: raise ValueError('operator must be unary (1), binary (2), or ternary (3)') else: raise ValueError('operator must indicate right or left associativity') if pa: matchExpr.setParseAction(pa) thisExpr <<= (matchExpr | lastExpr) lastExpr = thisExpr ret <<= lastExpr return ret
def nestedExpr(opener='(', closer=')', content=None, ignoreExpr=quotedString.copy()): 'Helper method for defining nested lists enclosed in opening and closing\n delimiters ("(" and ")" are the default).\n\n Parameters:\n - opener - opening character for a nested list (default="("); can also be a pyparsing expression\n - closer - closing character for a nested list (default=")"); can also be a pyparsing expression\n - content - expression for items within the nested lists (default=None)\n - ignoreExpr - expression for ignoring opening and closing delimiters (default=quotedString)\n\n If an expression is not provided for the content argument, the nested\n expression will capture all whitespace-delimited content between delimiters\n as a list of separate values.\n\n Use the C{ignoreExpr} argument to define expressions that may contain\n opening or closing characters that should not be treated as opening\n or closing characters for nesting, such as quotedString or a comment\n expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}.\n The default is L{quotedString}, but if no expressions are to be ignored,\n then pass C{None} for this argument.\n ' if (opener == closer): raise ValueError('opening and closing strings cannot be the same') if (content is None): if (isinstance(opener, basestring) and isinstance(closer, basestring)): if ((len(opener) == 1) and (len(closer) == 1)): if (ignoreExpr is not None): content = Combine(OneOrMore(((~ ignoreExpr) + CharsNotIn(((opener + closer) + ParserElement.DEFAULT_WHITE_CHARS), exact=1)))).setParseAction((lambda t: t[0].strip())) else: content = (empty.copy() + CharsNotIn(((opener + closer) + ParserElement.DEFAULT_WHITE_CHARS)).setParseAction((lambda t: t[0].strip()))) elif (ignoreExpr is not None): content = Combine(OneOrMore(((((~ ignoreExpr) + (~ Literal(opener))) + (~ Literal(closer))) + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)))).setParseAction((lambda t: t[0].strip())) else: content = Combine(OneOrMore((((~ Literal(opener)) + (~ Literal(closer))) + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)))).setParseAction((lambda t: t[0].strip())) else: raise ValueError('opening and closing arguments must be strings if no content expression is given') ret = Forward() if (ignoreExpr is not None): ret <<= Group(((Suppress(opener) + ZeroOrMore(((ignoreExpr | ret) | content))) + Suppress(closer))) else: ret <<= Group(((Suppress(opener) + ZeroOrMore((ret | content))) + Suppress(closer))) return ret
def indentedBlock(blockStatementExpr, indentStack, indent=True): 'Helper method for defining space-delimited indentation blocks, such as\n those used to define block statements in Python source code.\n\n Parameters:\n - blockStatementExpr - expression defining syntax of statement that\n is repeated within the indented block\n - indentStack - list created by caller to manage indentation stack\n (multiple statementWithIndentedBlock expressions within a single grammar\n should share a common indentStack)\n - indent - boolean indicating whether block must be indented beyond the\n the current level; set to False for block of left-most statements\n (default=True)\n\n A valid block must contain at least one C{blockStatement}.\n ' def checkPeerIndent(s, l, t): if (l >= len(s)): return curCol = col(l, s) if (curCol != indentStack[(- 1)]): if (curCol > indentStack[(- 1)]): raise ParseFatalException(s, l, 'illegal nesting') raise ParseException(s, l, 'not a peer entry') def checkSubIndent(s, l, t): curCol = col(l, s) if (curCol > indentStack[(- 1)]): indentStack.append(curCol) else: raise ParseException(s, l, 'not a subentry') def checkUnindent(s, l, t): if (l >= len(s)): return curCol = col(l, s) if (not (indentStack and (curCol < indentStack[(- 1)]) and (curCol <= indentStack[(- 2)]))): raise ParseException(s, l, 'not an unindent') indentStack.pop() NL = OneOrMore(LineEnd().setWhitespaceChars('\t ').suppress()) INDENT = (Empty() + Empty().setParseAction(checkSubIndent)) PEER = Empty().setParseAction(checkPeerIndent) UNDENT = Empty().setParseAction(checkUnindent) if indent: smExpr = Group((((Optional(NL) + INDENT) + OneOrMore(((PEER + Group(blockStatementExpr)) + Optional(NL)))) + UNDENT)) else: smExpr = Group((Optional(NL) + OneOrMore(((PEER + Group(blockStatementExpr)) + Optional(NL))))) blockStatementExpr.ignore((_bslash + LineEnd())) return smExpr
class LitConfig(): "LitConfig - Configuration data for a 'lit' test runner instance, shared\n across all tests.\n\n The LitConfig object is also used to communicate with client configuration\n files, it is always passed in as the global variable 'lit' so that\n configuration files can access common functionality and internal components\n easily.\n " def __init__(self, progname, path, quiet, useValgrind, valgrindLeakCheck, valgrindArgs, noExecute, debug, isWindows, params, config_prefix=None): self.progname = progname self.path = [str(p) for p in path] self.quiet = bool(quiet) self.useValgrind = bool(useValgrind) self.valgrindLeakCheck = bool(valgrindLeakCheck) self.valgrindUserArgs = list(valgrindArgs) self.noExecute = noExecute self.debug = debug self.isWindows = bool(isWindows) self.params = dict(params) self.bashPath = None self.config_prefix = (config_prefix or 'lit') self.config_name = ('%s.cfg' % (self.config_prefix,)) self.site_config_name = ('%s.site.cfg' % (self.config_prefix,)) self.local_config_name = ('%s.local.cfg' % (self.config_prefix,)) self.numErrors = 0 self.numWarnings = 0 self.valgrindArgs = [] if self.useValgrind: self.valgrindArgs = ['valgrind', '-q', '--run-libc-freeres=no', '--tool=memcheck', '--trace-children=yes', '--error-exitcode=123'] if self.valgrindLeakCheck: self.valgrindArgs.append('--leak-check=full') else: self.valgrindArgs.append('--leak-check=no') self.valgrindArgs.extend(self.valgrindUserArgs) def load_config(self, config, path): 'load_config(config, path) - Load a config object from an alternate\n path.' if self.debug: self.note(('load_config from %r' % path)) config.load_from_path(path, self) return config def getBashPath(self): "getBashPath - Get the path to 'bash'" if (self.bashPath is not None): return self.bashPath self.bashPath = lit.util.which('bash', os.pathsep.join(self.path)) if (self.bashPath is None): self.bashPath = lit.util.which('bash') if (self.bashPath is None): self.warning("Unable to find 'bash'.") self.bashPath = '' return self.bashPath def getToolsPath(self, dir, paths, tools): if ((dir is not None) and os.path.isabs(dir) and os.path.isdir(dir)): if (not lit.util.checkToolsPath(dir, tools)): return None else: dir = lit.util.whichTools(tools, paths) self.bashPath = lit.util.which('bash', dir) if (self.bashPath is None): self.note("Unable to find 'bash.exe'.") self.bashPath = '' return dir def _write_message(self, kind, message): f = inspect.currentframe() f = f.f_back.f_back (file, line, _, _, _) = inspect.getframeinfo(f) location = ('%s:%d' % (os.path.basename(file), line)) sys.stderr.write(('%s: %s: %s: %s\n' % (self.progname, location, kind, message))) def note(self, message): self._write_message('note', message) def warning(self, message): self._write_message('warning', message) self.numWarnings += 1 def error(self, message): self._write_message('error', message) self.numErrors += 1 def fatal(self, message): self._write_message('fatal', message) sys.exit(2)
class UnresolvedError(RuntimeError): pass
class LitTestCase(unittest.TestCase): def __init__(self, test, run): unittest.TestCase.__init__(self) self._test = test self._run = run def id(self): return self._test.getFullName() def shortDescription(self): return self._test.getFullName() def runTest(self): self._run.execute_test(self._test) result = self._test.result if (result.code is lit.Test.UNRESOLVED): raise UnresolvedError(result.output) elif result.code.isFailure: self.fail(result.output)
def to_bytes(str): return str.encode('ISO-8859-1')
class TerminalController(): "\n A class that can be used to portably generate formatted output to\n a terminal. \n \n `TerminalController` defines a set of instance variables whose\n values are initialized to the control sequence necessary to\n perform a given action. These can be simply included in normal\n output to the terminal:\n\n >>> term = TerminalController()\n >>> print('This is '+term.GREEN+'green'+term.NORMAL)\n\n Alternatively, the `render()` method can used, which replaces\n '${action}' with the string required to perform 'action':\n\n >>> term = TerminalController()\n >>> print(term.render('This is ${GREEN}green${NORMAL}'))\n\n If the terminal doesn't support a given action, then the value of\n the corresponding instance variable will be set to ''. As a\n result, the above code will still work on terminals that do not\n support color, except that their output will not be colored.\n Also, this means that you can test whether the terminal supports a\n given action by simply testing the truth value of the\n corresponding instance variable:\n\n >>> term = TerminalController()\n >>> if term.CLEAR_SCREEN:\n ... print('This terminal supports clearning the screen.')\n\n Finally, if the width and height of the terminal are known, then\n they will be stored in the `COLS` and `LINES` attributes.\n " BOL = '' UP = '' DOWN = '' LEFT = '' RIGHT = '' CLEAR_SCREEN = '' CLEAR_EOL = '' CLEAR_BOL = '' CLEAR_EOS = '' BOLD = '' BLINK = '' DIM = '' REVERSE = '' NORMAL = '' HIDE_CURSOR = '' SHOW_CURSOR = '' COLS = None LINES = None BLACK = BLUE = GREEN = CYAN = RED = MAGENTA = YELLOW = WHITE = '' BG_BLACK = BG_BLUE = BG_GREEN = BG_CYAN = '' BG_RED = BG_MAGENTA = BG_YELLOW = BG_WHITE = '' _STRING_CAPABILITIES = '\n BOL=cr UP=cuu1 DOWN=cud1 LEFT=cub1 RIGHT=cuf1\n CLEAR_SCREEN=clear CLEAR_EOL=el CLEAR_BOL=el1 CLEAR_EOS=ed BOLD=bold\n BLINK=blink DIM=dim REVERSE=rev UNDERLINE=smul NORMAL=sgr0\n HIDE_CURSOR=cinvis SHOW_CURSOR=cnorm'.split() _COLORS = 'BLACK BLUE GREEN CYAN RED MAGENTA YELLOW WHITE'.split() _ANSICOLORS = 'BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE'.split() def __init__(self, term_stream=sys.stdout): '\n Create a `TerminalController` and initialize its attributes\n with appropriate values for the current terminal.\n `term_stream` is the stream that will be used for terminal\n output; if this stream is not a tty, then the terminal is\n assumed to be a dumb terminal (i.e., have no capabilities).\n ' try: import curses except: return if (not term_stream.isatty()): return try: curses.setupterm() except: return self.COLS = curses.tigetnum('cols') self.LINES = curses.tigetnum('lines') self.XN = curses.tigetflag('xenl') for capability in self._STRING_CAPABILITIES: (attrib, cap_name) = capability.split('=') setattr(self, attrib, (self._tigetstr(cap_name) or '')) set_fg = self._tigetstr('setf') if set_fg: for (i, color) in zip(range(len(self._COLORS)), self._COLORS): setattr(self, color, self._tparm(set_fg, i)) set_fg_ansi = self._tigetstr('setaf') if set_fg_ansi: for (i, color) in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, color, self._tparm(set_fg_ansi, i)) set_bg = self._tigetstr('setb') if set_bg: for (i, color) in zip(range(len(self._COLORS)), self._COLORS): setattr(self, ('BG_' + color), self._tparm(set_bg, i)) set_bg_ansi = self._tigetstr('setab') if set_bg_ansi: for (i, color) in zip(range(len(self._ANSICOLORS)), self._ANSICOLORS): setattr(self, ('BG_' + color), self._tparm(set_bg_ansi, i)) def _tparm(self, arg, index): import curses return (curses.tparm(to_bytes(arg), index).decode('ascii') or '') def _tigetstr(self, cap_name): import curses cap = curses.tigetstr(cap_name) if (cap is None): cap = '' else: cap = cap.decode('ascii') return re.sub('\\$<\\d+>[/*]?', '', cap) def render(self, template): "\n Replace each $-substitutions in the given template string with\n the corresponding terminal control string (if it's defined) or\n '' (if it's not).\n " return re.sub('\\$\\$|\\${\\w+}', self._render_sub, template) def _render_sub(self, match): s = match.group() if (s == '$$'): return s else: return getattr(self, s[2:(- 1)])
class SimpleProgressBar(): "\n A simple progress bar which doesn't need any terminal support.\n\n This prints out a progress bar like:\n 'Header: 0 .. 10.. 20.. ...'\n " def __init__(self, header): self.header = header self.atIndex = None def update(self, percent, message): if (self.atIndex is None): sys.stdout.write(self.header) self.atIndex = 0 next = int((percent * 50)) if (next == self.atIndex): return for i in range(self.atIndex, next): idx = (i % 5) if (idx == 0): sys.stdout.write(('%-2d' % (i * 2))) elif (idx == 1): pass elif (idx < 4): sys.stdout.write('.') else: sys.stdout.write(' ') sys.stdout.flush() self.atIndex = next def clear(self): if (self.atIndex is not None): sys.stdout.write('\n') sys.stdout.flush() self.atIndex = None
class ProgressBar(): '\n A 3-line progress bar, which looks like::\n \n Header\n 20% [===========----------------------------------]\n progress message\n\n The progress bar is colored, if the terminal supports color\n output; and adjusts to the width of the terminal.\n ' BAR = '%s${GREEN}[${BOLD}%s%s${NORMAL}${GREEN}]${NORMAL}%s' HEADER = '${BOLD}${CYAN}%s${NORMAL}\n\n' def __init__(self, term, header, useETA=True): self.term = term if (not (self.term.CLEAR_EOL and self.term.UP and self.term.BOL)): raise ValueError("Terminal isn't capable enough -- you should use a simpler progress dispaly.") self.BOL = self.term.BOL self.XNL = '\n' if self.term.COLS: self.width = self.term.COLS if (not self.term.XN): self.BOL = (self.term.UP + self.term.BOL) self.XNL = '' else: self.width = 75 self.bar = term.render(self.BAR) self.header = self.term.render((self.HEADER % header.center(self.width))) self.cleared = 1 self.useETA = useETA if self.useETA: self.startTime = time.time() self.update(0, '') def update(self, percent, message): if self.cleared: sys.stdout.write(self.header) self.cleared = 0 prefix = ('%3d%% ' % ((percent * 100),)) suffix = '' if self.useETA: elapsed = (time.time() - self.startTime) if ((percent > 0.0001) and (elapsed > 1)): total = (elapsed / percent) eta = int((total - elapsed)) h = (eta // 3600.0) m = ((eta // 60) % 60) s = (eta % 60) suffix = (' ETA: %02d:%02d:%02d' % (h, m, s)) barWidth = (((self.width - len(prefix)) - len(suffix)) - 2) n = int((barWidth * percent)) if (len(message) < self.width): message = (message + (' ' * (self.width - len(message)))) else: message = ('... ' + message[(- (self.width - 4)):]) sys.stdout.write(((((((self.BOL + self.term.UP) + self.term.CLEAR_EOL) + (self.bar % (prefix, ('=' * n), ('-' * (barWidth - n)), suffix))) + self.XNL) + self.term.CLEAR_EOL) + message)) if (not self.term.XN): sys.stdout.flush() def clear(self): if (not self.cleared): sys.stdout.write((((((self.BOL + self.term.CLEAR_EOL) + self.term.UP) + self.term.CLEAR_EOL) + self.term.UP) + self.term.CLEAR_EOL)) sys.stdout.flush() self.cleared = 1
def test(): tc = TerminalController() p = ProgressBar(tc, 'Tests') for i in range(101): p.update((i / 100.0), str(i)) time.sleep(0.3)
class Command(): def __init__(self, args, redirects): self.args = list(args) self.redirects = list(redirects) def __repr__(self): return ('Command(%r, %r)' % (self.args, self.redirects)) def __eq__(self, other): if (not isinstance(other, Command)): return False return ((self.args, self.redirects) == (other.args, other.redirects)) def toShell(self, file): for arg in self.args: if ("'" not in arg): quoted = ("'%s'" % arg) elif (('"' not in arg) and ('$' not in arg)): quoted = ('"%s"' % arg) else: raise NotImplementedError(('Unable to quote %r' % arg)) file.write(quoted) import ShUtil dequoted = list(ShUtil.ShLexer(quoted).lex()) if (dequoted != [arg]): raise NotImplementedError(('Unable to quote %r' % arg)) for r in self.redirects: if (len(r[0]) == 1): file.write(("%s '%s'" % (r[0][0], r[1]))) else: file.write(("%s%s '%s'" % (r[0][1], r[0][0], r[1])))
class Pipeline(): def __init__(self, commands, negate=False, pipe_err=False): self.commands = commands self.negate = negate self.pipe_err = pipe_err def __repr__(self): return ('Pipeline(%r, %r, %r)' % (self.commands, self.negate, self.pipe_err)) def __eq__(self, other): if (not isinstance(other, Pipeline)): return False return ((self.commands, self.negate, self.pipe_err) == (other.commands, other.negate, self.pipe_err)) def toShell(self, file, pipefail=False): if (pipefail != self.pipe_err): raise ValueError('Inconsistent "pipefail" attribute!') if self.negate: file.write('! ') for cmd in self.commands: cmd.toShell(file) if (cmd is not self.commands[(- 1)]): file.write('|\n ')
class Seq(): def __init__(self, lhs, op, rhs): assert (op in (';', '&', '||', '&&')) self.op = op self.lhs = lhs self.rhs = rhs def __repr__(self): return ('Seq(%r, %r, %r)' % (self.lhs, self.op, self.rhs)) def __eq__(self, other): if (not isinstance(other, Seq)): return False return ((self.lhs, self.op, self.rhs) == (other.lhs, other.op, other.rhs)) def toShell(self, file, pipefail=False): self.lhs.toShell(file, pipefail) file.write((' %s\n' % self.op)) self.rhs.toShell(file, pipefail)
class ShLexer(): def __init__(self, data, win32Escapes=False): self.data = data self.pos = 0 self.end = len(data) self.win32Escapes = win32Escapes def eat(self): c = self.data[self.pos] self.pos += 1 return c def look(self): return self.data[self.pos] def maybe_eat(self, c): '\n maybe_eat(c) - Consume the character c if it is the next character,\n returning True if a character was consumed. ' if (self.data[self.pos] == c): self.pos += 1 return True return False def lex_arg_fast(self, c): chunk = self.data[(self.pos - 1):].split(None, 1)[0] if (('|' in chunk) or ('&' in chunk) or ('<' in chunk) or ('>' in chunk) or ("'" in chunk) or ('"' in chunk) or (';' in chunk) or ('\\' in chunk)): return None self.pos = ((self.pos - 1) + len(chunk)) return chunk def lex_arg_slow(self, c): if (c in '\'"'): str = self.lex_arg_quoted(c) else: str = c while (self.pos != self.end): c = self.look() if (c.isspace() or (c in '|&;')): break elif (c in '><'): if (not str.isdigit()): break num = int(str) tok = self.lex_one_token() assert (isinstance(tok, tuple) and (len(tok) == 1)) return (tok[0], num) elif (c == '"'): self.eat() str += self.lex_arg_quoted('"') elif (c == "'"): self.eat() str += self.lex_arg_quoted("'") elif ((not self.win32Escapes) and (c == '\\')): self.eat() if (self.pos == self.end): lit.util.warning(('escape at end of quoted argument in: %r' % self.data)) return str str += self.eat() else: str += self.eat() return str def lex_arg_quoted(self, delim): str = '' while (self.pos != self.end): c = self.eat() if (c == delim): return str elif ((c == '\\') and (delim == '"')): if (self.pos == self.end): lit.util.warning(('escape at end of quoted argument in: %r' % self.data)) return str c = self.eat() if (c == '"'): str += '"' elif (c == '\\'): str += '\\' else: str += ('\\' + c) else: str += c lit.util.warning(('missing quote character in %r' % self.data)) return str def lex_arg_checked(self, c): pos = self.pos res = self.lex_arg_fast(c) end = self.pos self.pos = pos reference = self.lex_arg_slow(c) if (res is not None): if (res != reference): raise ValueError(('Fast path failure: %r != %r' % (res, reference))) if (self.pos != end): raise ValueError(('Fast path failure: %r != %r' % (self.pos, end))) return reference def lex_arg(self, c): return (self.lex_arg_fast(c) or self.lex_arg_slow(c)) def lex_one_token(self): "\n lex_one_token - Lex a single 'sh' token. " c = self.eat() if (c == ';'): return (c,) if (c == '|'): if self.maybe_eat('|'): return ('||',) return (c,) if (c == '&'): if self.maybe_eat('&'): return ('&&',) if self.maybe_eat('>'): return ('&>',) return (c,) if (c == '>'): if self.maybe_eat('&'): return ('>&',) if self.maybe_eat('>'): return ('>>',) return (c,) if (c == '<'): if self.maybe_eat('&'): return ('<&',) if self.maybe_eat('>'): return ('<<',) return (c,) return self.lex_arg(c) def lex(self): while (self.pos != self.end): if self.look().isspace(): self.eat() else: (yield self.lex_one_token())
class ShParser(): def __init__(self, data, win32Escapes=False, pipefail=False): self.data = data self.pipefail = pipefail self.tokens = ShLexer(data, win32Escapes=win32Escapes).lex() def lex(self): for item in self.tokens: return item return None def look(self): token = self.lex() if (token is not None): self.tokens = itertools.chain([token], self.tokens) return token def parse_command(self): tok = self.lex() if (not tok): raise ValueError('empty command!') if isinstance(tok, tuple): raise ValueError(('syntax error near unexpected token %r' % tok[0])) args = [tok] redirects = [] while 1: tok = self.look() if (tok is None): break if isinstance(tok, str): args.append(self.lex()) continue assert isinstance(tok, tuple) if (tok[0] in ('|', ';', '&', '||', '&&')): break op = self.lex() arg = self.lex() if (not arg): raise ValueError(('syntax error near token %r' % op[0])) redirects.append((op, arg)) return Command(args, redirects) def parse_pipeline(self): negate = False commands = [self.parse_command()] while (self.look() == ('|',)): self.lex() commands.append(self.parse_command()) return Pipeline(commands, negate, self.pipefail) def parse(self): lhs = self.parse_pipeline() while self.look(): operator = self.lex() assert (isinstance(operator, tuple) and (len(operator) == 1)) if (not self.look()): raise ValueError(('missing argument to operator %r' % operator[0])) lhs = Seq(lhs, operator[0], self.parse_pipeline()) return lhs
class TestShLexer(unittest.TestCase): def lex(self, str, *args, **kwargs): return list(ShLexer(str, *args, **kwargs).lex()) def test_basic(self): self.assertEqual(self.lex('a|b>c&d<e;f'), ['a', ('|',), 'b', ('>',), 'c', ('&',), 'd', ('<',), 'e', (';',), 'f']) def test_redirection_tokens(self): self.assertEqual(self.lex('a2>c'), ['a2', ('>',), 'c']) self.assertEqual(self.lex('a 2>c'), ['a', ('>', 2), 'c']) def test_quoting(self): self.assertEqual(self.lex(" 'a' "), ['a']) self.assertEqual(self.lex(' "hello\\"world" '), ['hello"world']) self.assertEqual(self.lex(' "hello\\\'world" '), ["hello\\'world"]) self.assertEqual(self.lex(' "hello\\\\world" '), ['hello\\world']) self.assertEqual(self.lex(' he"llo wo"rld '), ['hello world']) self.assertEqual(self.lex(' a\\ b a\\\\b '), ['a b', 'a\\b']) self.assertEqual(self.lex(' "" "" '), ['', '']) self.assertEqual(self.lex(' a\\ b ', win32Escapes=True), ['a\\', 'b'])
class TestShParse(unittest.TestCase): def parse(self, str): return ShParser(str).parse() def test_basic(self): self.assertEqual(self.parse('echo hello'), Pipeline([Command(['echo', 'hello'], [])], False)) self.assertEqual(self.parse('echo ""'), Pipeline([Command(['echo', ''], [])], False)) self.assertEqual(self.parse("echo -DFOO='a'"), Pipeline([Command(['echo', '-DFOO=a'], [])], False)) self.assertEqual(self.parse('echo -DFOO="a"'), Pipeline([Command(['echo', '-DFOO=a'], [])], False)) def test_redirection(self): self.assertEqual(self.parse('echo hello > c'), Pipeline([Command(['echo', 'hello'], [(('>',), 'c')])], False)) self.assertEqual(self.parse('echo hello > c >> d'), Pipeline([Command(['echo', 'hello'], [(('>',), 'c'), (('>>',), 'd')])], False)) self.assertEqual(self.parse('a 2>&1'), Pipeline([Command(['a'], [(('>&', 2), '1')])], False)) def test_pipeline(self): self.assertEqual(self.parse('a | b'), Pipeline([Command(['a'], []), Command(['b'], [])], False)) self.assertEqual(self.parse('a | b | c'), Pipeline([Command(['a'], []), Command(['b'], []), Command(['c'], [])], False)) def test_list(self): self.assertEqual(self.parse('a ; b'), Seq(Pipeline([Command(['a'], [])], False), ';', Pipeline([Command(['b'], [])], False))) self.assertEqual(self.parse('a & b'), Seq(Pipeline([Command(['a'], [])], False), '&', Pipeline([Command(['b'], [])], False))) self.assertEqual(self.parse('a && b'), Seq(Pipeline([Command(['a'], [])], False), '&&', Pipeline([Command(['b'], [])], False))) self.assertEqual(self.parse('a || b'), Seq(Pipeline([Command(['a'], [])], False), '||', Pipeline([Command(['b'], [])], False))) self.assertEqual(self.parse('a && b || c'), Seq(Seq(Pipeline([Command(['a'], [])], False), '&&', Pipeline([Command(['b'], [])], False)), '||', Pipeline([Command(['c'], [])], False))) self.assertEqual(self.parse('a; b'), Seq(Pipeline([Command(['a'], [])], False), ';', Pipeline([Command(['b'], [])], False)))
class ResultCode(object): 'Test result codes.' _instances = {} def __new__(cls, name, isFailure): res = cls._instances.get(name) if (res is None): cls._instances[name] = res = super(ResultCode, cls).__new__(cls) return res def __getnewargs__(self): return (self.name, self.isFailure) def __init__(self, name, isFailure): self.name = name self.isFailure = isFailure def __repr__(self): return ('%s%r' % (self.__class__.__name__, (self.name, self.isFailure)))
class MetricValue(object): def format(self): '\n format() -> str\n\n Convert this metric to a string suitable for displaying as part of the\n console output.\n ' raise RuntimeError('abstract method') def todata(self): '\n todata() -> json-serializable data\n\n Convert this metric to content suitable for serializing in the JSON test\n output.\n ' raise RuntimeError('abstract method')
class IntMetricValue(MetricValue): def __init__(self, value): self.value = value def format(self): return str(self.value) def todata(self): return self.value
class RealMetricValue(MetricValue): def __init__(self, value): self.value = value def format(self): return ('%.4f' % self.value) def todata(self): return self.value
class Result(object): 'Wrapper for the results of executing an individual test.' def __init__(self, code, output='', elapsed=None): self.code = code self.output = output self.elapsed = elapsed self.metrics = {} def addMetric(self, name, value): '\n addMetric(name, value)\n\n Attach a test metric to the test result, with the given name and list of\n values. It is an error to attempt to attach the metrics with the same\n name multiple times.\n\n Each value must be an instance of a MetricValue subclass.\n ' if (name in self.metrics): raise ValueError(('result already includes metrics for %r' % (name,))) if (not isinstance(value, MetricValue)): raise TypeError(('unexpected metric value: %r' % (value,))) self.metrics[name] = value
class TestSuite(): 'TestSuite - Information on a group of tests.\n\n A test suite groups together a set of logically related tests.\n ' def __init__(self, name, source_root, exec_root, config): self.name = name self.source_root = source_root self.exec_root = exec_root self.config = config def getSourcePath(self, components): return os.path.join(self.source_root, *components) def getExecPath(self, components): return os.path.join(self.exec_root, *components)
class Test(): 'Test - Information on a single test instance.' def __init__(self, suite, path_in_suite, config, file_path=None): self.suite = suite self.path_in_suite = path_in_suite self.config = config self.file_path = file_path self.xfails = [] self.result = None def setResult(self, result): if (self.result is not None): raise ArgumentError('test result already set') if (not isinstance(result, Result)): raise ArgumentError('unexpected result type') self.result = result if self.isExpectedToFail(): if (self.result.code == PASS): self.result.code = XPASS elif (self.result.code == FAIL): self.result.code = XFAIL def getFullName(self): return ((self.suite.config.name + ' :: ') + '/'.join(self.path_in_suite)) def getFilePath(self): if self.file_path: return self.file_path return self.getSourcePath() def getSourcePath(self): return self.suite.getSourcePath(self.path_in_suite) def getExecPath(self): return self.suite.getExecPath(self.path_in_suite) def isExpectedToFail(self): '\n isExpectedToFail() -> bool\n\n Check whether this test is expected to fail in the current\n configuration. This check relies on the test xfails property which by\n some test formats may not be computed until the test has first been\n executed.\n ' for item in self.xfails: if (item == '*'): return True if (item in self.config.available_features): return True if (item in self.suite.config.target_triple): return True return False
class InternalShellError(Exception): def __init__(self, command, message): self.command = command self.message = message
def executeShCmd(cmd, cfg, cwd, results): if isinstance(cmd, ShUtil.Seq): if (cmd.op == ';'): res = executeShCmd(cmd.lhs, cfg, cwd, results) return executeShCmd(cmd.rhs, cfg, cwd, results) if (cmd.op == '&'): raise InternalShellError(cmd, "unsupported shell operator: '&'") if (cmd.op == '||'): res = executeShCmd(cmd.lhs, cfg, cwd, results) if (res != 0): res = executeShCmd(cmd.rhs, cfg, cwd, results) return res if (cmd.op == '&&'): res = executeShCmd(cmd.lhs, cfg, cwd, results) if (res is None): return res if (res == 0): res = executeShCmd(cmd.rhs, cfg, cwd, results) return res raise ValueError(('Unknown shell command: %r' % cmd.op)) assert isinstance(cmd, ShUtil.Pipeline) procs = [] input = subprocess.PIPE stderrTempFiles = [] opened_files = [] named_temp_files = [] for (i, j) in enumerate(cmd.commands): redirects = [(0,), (1,), (2,)] for r in j.redirects: if (r[0] == ('>', 2)): redirects[2] = [r[1], 'w', None] elif (r[0] == ('>>', 2)): redirects[2] = [r[1], 'a', None] elif ((r[0] == ('>&', 2)) and (r[1] in '012')): redirects[2] = redirects[int(r[1])] elif ((r[0] == ('>&',)) or (r[0] == ('&>',))): redirects[1] = redirects[2] = [r[1], 'w', None] elif (r[0] == ('>',)): redirects[1] = [r[1], 'w', None] elif (r[0] == ('>>',)): redirects[1] = [r[1], 'a', None] elif (r[0] == ('<',)): redirects[0] = [r[1], 'r', None] else: raise InternalShellError(j, ('Unsupported redirect: %r' % (r,))) final_redirects = [] for (index, r) in enumerate(redirects): if (r == (0,)): result = input elif (r == (1,)): if (index == 0): raise InternalShellError(j, 'Unsupported redirect for stdin') elif (index == 1): result = subprocess.PIPE else: result = subprocess.STDOUT elif (r == (2,)): if (index != 2): raise InternalShellError(j, 'Unsupported redirect on stdout') result = subprocess.PIPE else: if (r[2] is None): if (kAvoidDevNull and (r[0] == '/dev/null')): r[2] = tempfile.TemporaryFile(mode=r[1]) else: r[2] = open(r[0], r[1]) if (r[1] == 'a'): r[2].seek(0, 2) opened_files.append(r[2]) result = r[2] final_redirects.append(result) (stdin, stdout, stderr) = final_redirects if ((stderr == subprocess.STDOUT) and (stdout != subprocess.PIPE)): stderr = subprocess.PIPE stderrIsStdout = True else: stderrIsStdout = False if ((stderr == subprocess.PIPE) and (j != cmd.commands[(- 1)])): stderr = tempfile.TemporaryFile(mode='w+b') stderrTempFiles.append((i, stderr)) args = list(j.args) executable = lit.util.which(args[0], cfg.environment['PATH']) if (not executable): raise InternalShellError(j, ('%r: command not found' % j.args[0])) if kAvoidDevNull: for (i, arg) in enumerate(args): if (arg == '/dev/null'): f = tempfile.NamedTemporaryFile(delete=False) f.close() named_temp_files.append(f.name) args[i] = f.name procs.append(subprocess.Popen(args, cwd=cwd, executable=executable, stdin=stdin, stdout=stdout, stderr=stderr, env=cfg.environment, close_fds=kUseCloseFDs)) if (stdin == subprocess.PIPE): procs[(- 1)].stdin.close() procs[(- 1)].stdin = None if (stdout == subprocess.PIPE): input = procs[(- 1)].stdout elif stderrIsStdout: input = procs[(- 1)].stderr else: input = subprocess.PIPE for f in opened_files: f.close() procData = ([None] * len(procs)) procData[(- 1)] = procs[(- 1)].communicate() for i in range((len(procs) - 1)): if (procs[i].stdout is not None): out = procs[i].stdout.read() else: out = '' if (procs[i].stderr is not None): err = procs[i].stderr.read() else: err = '' procData[i] = (out, err) for (i, f) in stderrTempFiles: f.seek(0, 0) procData[i] = (procData[i][0], f.read()) exitCode = None for (i, (out, err)) in enumerate(procData): res = procs[i].wait() if (res == (- signal.SIGINT)): raise KeyboardInterrupt try: out = str(out.decode('ascii')) except: out = str(out) try: err = str(err.decode('ascii')) except: err = str(err) results.append((cmd.commands[i], out, err, res)) if cmd.pipe_err: if (exitCode is None): exitCode = res elif (res < 0): exitCode = min(exitCode, res) else: exitCode = max(exitCode, res) else: exitCode = res for f in named_temp_files: try: os.remove(f) except OSError: pass if cmd.negate: exitCode = (not exitCode) return exitCode
def executeScriptInternal(test, litConfig, tmpBase, commands, cwd): cmds = [] for ln in commands: try: cmds.append(ShUtil.ShParser(ln, litConfig.isWindows, test.config.pipefail).parse()) except: return lit.Test.Result(Test.FAIL, ('shell parser error on: %r' % ln)) cmd = cmds[0] for c in cmds[1:]: cmd = ShUtil.Seq(cmd, '&&', c) results = [] try: exitCode = executeShCmd(cmd, test.config, cwd, results) except InternalShellError: e = sys.exc_info()[1] exitCode = 127 results.append((e.command, '', e.message, exitCode)) out = err = '' for (i, (cmd, cmd_out, cmd_err, res)) in enumerate(results): out += ('Command %d: %s\n' % (i, ' '.join((('"%s"' % s) for s in cmd.args)))) out += ('Command %d Result: %r\n' % (i, res)) out += ('Command %d Output:\n%s\n\n' % (i, cmd_out)) out += ('Command %d Stderr:\n%s\n\n' % (i, cmd_err)) return (out, err, exitCode)
def executeScript(test, litConfig, tmpBase, commands, cwd): bashPath = litConfig.getBashPath() isWin32CMDEXE = (litConfig.isWindows and (not bashPath)) script = (tmpBase + '.script') if isWin32CMDEXE: script += '.bat' mode = 'w' if (litConfig.isWindows and (not isWin32CMDEXE)): mode += 'b' f = open(script, mode) if isWin32CMDEXE: f.write('\nif %ERRORLEVEL% NEQ 0 EXIT\n'.join(commands)) else: if test.config.pipefail: f.write('set -o pipefail;') f.write((('{ ' + '; } &&\n{ '.join(commands)) + '; }')) f.write('\n') f.close() if isWin32CMDEXE: command = ['cmd', '/c', script] else: if bashPath: command = [bashPath, script] else: command = ['/bin/sh', script] if litConfig.useValgrind: command = (litConfig.valgrindArgs + command) return lit.util.executeCommand(command, cwd=cwd, env=test.config.environment)
def parseIntegratedTestScriptCommands(source_path): '\n parseIntegratedTestScriptCommands(source_path) -> commands\n\n Parse the commands in an integrated test script file into a list of\n (line_number, command_type, line).\n ' def to_bytes(str): return str.encode('ISO-8859-1') keywords = ('RUN:', 'XFAIL:', 'REQUIRES:', 'END.') keywords_re = re.compile(to_bytes(('(%s)(.*)\n' % ('|'.join((k for k in keywords)),)))) f = open(source_path, 'rb') try: data = f.read() line_number = 1 last_match_position = 0 for match in keywords_re.finditer(data): match_position = match.start() line_number += data.count(to_bytes('\n'), last_match_position, match_position) last_match_position = match_position (keyword, ln) = match.groups() (yield (line_number, str(keyword[:(- 1)].decode('ascii')), str(ln.decode('ascii')))) finally: f.close()
def parseIntegratedTestScript(test, normalize_slashes=False, extra_substitutions=[]): "parseIntegratedTestScript - Scan an LLVM/Clang style integrated test\n script and extract the lines to 'RUN' as well as 'XFAIL' and 'REQUIRES'\n information. The RUN lines also will have variable substitution performed.\n " sourcepath = test.getSourcePath() sourcedir = os.path.dirname(sourcepath) execpath = test.getExecPath() (execdir, execbase) = os.path.split(execpath) tmpDir = os.path.join(execdir, 'Output') tmpBase = os.path.join(tmpDir, execbase) if normalize_slashes: sourcepath = sourcepath.replace('\\', '/') sourcedir = sourcedir.replace('\\', '/') tmpDir = tmpDir.replace('\\', '/') tmpBase = tmpBase.replace('\\', '/') substitutions = list(extra_substitutions) substitutions.extend([('%%', '#_MARKER_#')]) substitutions.extend(test.config.substitutions) substitutions.extend([('%s', sourcepath), ('%S', sourcedir), ('%p', sourcedir), ('%{pathsep}', os.pathsep), ('%t', (tmpBase + '.tmp')), ('%T', tmpDir), ('#_MARKER_#', '%')]) substitutions.extend([('%/s', sourcepath.replace('\\', '/')), ('%/S', sourcedir.replace('\\', '/')), ('%/p', sourcedir.replace('\\', '/')), ('%/t', (tmpBase.replace('\\', '/') + '.tmp')), ('%/T', tmpDir.replace('\\', '/'))]) script = [] requires = [] for (line_number, command_type, ln) in parseIntegratedTestScriptCommands(sourcepath): if (command_type == 'RUN'): ln = ln.rstrip() ln = re.sub('%\\(line\\)', str(line_number), ln) def replace_line_number(match): if (match.group(1) == '+'): return str((line_number + int(match.group(2)))) if (match.group(1) == '-'): return str((line_number - int(match.group(2)))) ln = re.sub('%\\(line *([\\+-]) *(\\d+)\\)', replace_line_number, ln) if (script and (script[(- 1)][(- 1)] == '\\')): script[(- 1)] = (script[(- 1)][:(- 1)] + ln) else: script.append(ln) elif (command_type == 'XFAIL'): test.xfails.extend([s.strip() for s in ln.split(',')]) elif (command_type == 'REQUIRES'): requires.extend([s.strip() for s in ln.split(',')]) elif (command_type == 'END'): if (not ln.strip()): break else: raise ValueError(('unknown script command type: %r' % (command_type,))) def processLine(ln): for (a, b) in substitutions: if kIsWindows: b = b.replace('\\', '\\\\') ln = re.sub(a, b, ln) return ln.strip() script = [processLine(ln) for ln in script] if (not script): return lit.Test.Result(Test.UNRESOLVED, 'Test has no run line!') if (script[(- 1)][(- 1)] == '\\'): return lit.Test.Result(Test.UNRESOLVED, "Test has unterminated run lines (with '\\')") missing_required_features = [f for f in requires if (f not in test.config.available_features)] if missing_required_features: msg = ', '.join(missing_required_features) return lit.Test.Result(Test.UNSUPPORTED, ('Test requires the following features: %s' % msg)) return (script, tmpBase, execdir)
def executeShTest(test, litConfig, useExternalSh, extra_substitutions=[]): if test.config.unsupported: return (Test.UNSUPPORTED, 'Test is unsupported') res = parseIntegratedTestScript(test, useExternalSh, extra_substitutions) if isinstance(res, lit.Test.Result): return res if litConfig.noExecute: return lit.Test.Result(Test.PASS) (script, tmpBase, execdir) = res lit.util.mkdir_p(os.path.dirname(tmpBase)) if useExternalSh: res = executeScript(test, litConfig, tmpBase, script, execdir) else: res = executeScriptInternal(test, litConfig, tmpBase, script, execdir) if isinstance(res, lit.Test.Result): return res (out, err, exitCode) = res if (exitCode == 0): status = Test.PASS else: status = Test.FAIL output = ('Script:\n--\n%s\n--\nExit Code: %d\n\n' % ('\n'.join(script), exitCode)) if out: output += ('Command Output (stdout):\n--\n%s\n--\n' % (out,)) if err: output += ('Command Output (stderr):\n--\n%s\n--\n' % (err,)) return lit.Test.Result(status, output)
class TestingConfig(): '"\n TestingConfig - Information on the tests inside a suite.\n ' @staticmethod def fromdefaults(litConfig): '\n fromdefaults(litConfig) -> TestingConfig\n\n Create a TestingConfig object with default values.\n ' environment = {'LIBRARY_PATH': os.environ.get('LIBRARY_PATH', ''), 'LD_LIBRARY_PATH': os.environ.get('LD_LIBRARY_PATH', ''), 'PATH': os.pathsep.join((litConfig.path + [os.environ.get('PATH', '')])), 'SYSTEMROOT': os.environ.get('SYSTEMROOT', ''), 'TERM': os.environ.get('TERM', ''), 'LLVM_DISABLE_CRASH_REPORT': '1'} if (sys.platform == 'win32'): environment.update({'INCLUDE': os.environ.get('INCLUDE', ''), 'PATHEXT': os.environ.get('PATHEXT', ''), 'PYTHONUNBUFFERED': '1', 'TEMP': os.environ.get('TEMP', ''), 'TMP': os.environ.get('TMP', '')}) if ('LIT_PRESERVES_TMP' in os.environ): environment.update({'TEMP': os.environ.get('TEMP', ''), 'TMP': os.environ.get('TMP', ''), 'TMPDIR': os.environ.get('TMPDIR', '')}) available_features = [] if litConfig.useValgrind: available_features.append('valgrind') if litConfig.valgrindLeakCheck: available_features.append('vg_leak') return TestingConfig(None, name='<unnamed>', suffixes=set(), test_format=None, environment=environment, substitutions=[], unsupported=False, test_exec_root=None, test_source_root=None, excludes=[], available_features=available_features, pipefail=True) def load_from_path(self, path, litConfig): '\n load_from_path(path, litConfig)\n\n Load the configuration module at the provided path into the given config\n object.\n ' data = None if (not OldPy): f = open(path) try: data = f.read() except: litConfig.fatal(('unable to load config file: %r' % (path,))) f.close() cfg_globals = dict(globals()) cfg_globals['config'] = self cfg_globals['lit_config'] = litConfig cfg_globals['__file__'] = path try: if OldPy: execfile(path, cfg_globals) else: exec(compile(data, path, 'exec'), cfg_globals, None) if litConfig.debug: litConfig.note(('... loaded config %r' % path)) except SystemExit: e = sys.exc_info()[1] if e.args: raise except: import traceback litConfig.fatal(('unable to parse config file %r, traceback: %s' % (path, traceback.format_exc()))) self.finish(litConfig) def __init__(self, parent, name, suffixes, test_format, environment, substitutions, unsupported, test_exec_root, test_source_root, excludes, available_features, pipefail): self.parent = parent self.name = str(name) self.suffixes = set(suffixes) self.test_format = test_format self.environment = dict(environment) self.substitutions = list(substitutions) self.unsupported = unsupported self.test_exec_root = test_exec_root self.test_source_root = test_source_root self.excludes = set(excludes) self.available_features = set(available_features) self.pipefail = pipefail def finish(self, litConfig): 'finish() - Finish this config object, after loading is complete.' self.name = str(self.name) self.suffixes = set(self.suffixes) self.environment = dict(self.environment) self.substitutions = list(self.substitutions) if (self.test_exec_root is not None): self.test_exec_root = str(self.test_exec_root) if (self.test_source_root is not None): self.test_source_root = str(self.test_source_root) self.excludes = set(self.excludes) @property def root(self): 'root attribute - The root configuration for the test suite.' if (self.parent is None): return self else: return self.parent.root
def dirContainsTestSuite(path, lit_config): cfgpath = os.path.join(path, lit_config.site_config_name) if os.path.exists(cfgpath): return cfgpath cfgpath = os.path.join(path, lit_config.config_name) if os.path.exists(cfgpath): return cfgpath
def getTestSuite(item, litConfig, cache): 'getTestSuite(item, litConfig, cache) -> (suite, relative_path)\n\n Find the test suite containing @arg item.\n\n @retval (None, ...) - Indicates no test suite contains @arg item.\n @retval (suite, relative_path) - The suite that @arg item is in, and its\n relative path inside that suite.\n ' def search1(path): cfgpath = dirContainsTestSuite(path, litConfig) if (not cfgpath): (parent, base) = os.path.split(path) if (parent == path): return (None, ()) (ts, relative) = search(parent) return (ts, (relative + (base,))) if litConfig.debug: litConfig.note(('loading suite config %r' % cfgpath)) cfg = TestingConfig.fromdefaults(litConfig) cfg.load_from_path(cfgpath, litConfig) source_root = os.path.realpath((cfg.test_source_root or path)) exec_root = os.path.realpath((cfg.test_exec_root or path)) return (Test.TestSuite(cfg.name, source_root, exec_root, cfg), ()) def search(path): res = cache.get(path) if (res is None): cache[path] = res = search1(path) return res item = os.path.realpath(item) components = [] while (not os.path.isdir(item)): (parent, base) = os.path.split(item) if (parent == item): return (None, ()) components.append(base) item = parent components.reverse() (ts, relative) = search(item) return (ts, tuple((relative + tuple(components))))
def getLocalConfig(ts, path_in_suite, litConfig, cache): def search1(path_in_suite): if (not path_in_suite): parent = ts.config else: parent = search(path_in_suite[:(- 1)]) source_path = ts.getSourcePath(path_in_suite) cfgpath = os.path.join(source_path, litConfig.local_config_name) if (not os.path.exists(cfgpath)): return parent config = copy.copy(parent) if litConfig.debug: litConfig.note(('loading local config %r' % cfgpath)) config.load_from_path(cfgpath, litConfig) return config def search(path_in_suite): key = (ts, path_in_suite) res = cache.get(key) if (res is None): cache[key] = res = search1(path_in_suite) return res return search(path_in_suite)