a |_d@sBdZdZdZddlmZddlmZmZddl Z ddl m Z ddl Z ddlZddlZddlTdd lmZed ejZed ejZddlZejgd Z[Gd dde ddZddZddZddZdZdZeedeeeZdZdZ dZ!dZ"dZ#ee e!e"e#Z$dZ%edd ee%Z&d!e%Z'ee&e'Z(ed"e(d#Z)ee)e(e$Z*d$d%Z+d&d'Z,ee+Z-d(Z.d)Z/d*Z0d+Z1ee-d,e-d-Z2ee-d.e-d/Z3ee4ej5e6ed0d1Z7ed2e7Z8ee*e8e3eZ9ee9Z:ee-d3ed4de-d5ed6dZ;ed7ee2Ze+D]6Z?e.e>e?d4<e/e>e?d6<e0e>e?d,<e1e>e?d-<q&e@ZAe@ZBe+D]JZCeCd6eCd4fD]ZDeAEeDqeCd-eCd,fD]ZDeBEeDqqpd8ZFGd9d:d:eGZHGd;d<dd>ZJd?d@ZKdAdBZLdCdDZMdEdFZdGdHZNdIdJZOdKdLZPdMdNZQeRdOkr>eQdS)PaoTokenization help for Python programs. tokenize(readline) is a generator that breaks a stream of bytes into Python tokens. It decodes the bytes according to PEP-0263 for determining source file encoding. It accepts a readline-like method which is called repeatedly to get the next line of input (or b"" for EOF). It generates 5-tuples with these members: the token type (see token.py) the token (a string) the starting (row, column) indices of the token (a 2-tuple of ints) the ending (row, column) indices of the token (a 2-tuple of ints) the original line (string) It is designed to match the working of the Python tokenizer exactly, except that it produces COMMENT tokens for comments and gives type OP for all operators. Additionally, all token lists start with an ENCODING token which tells you which encoding was used to decode the bytes stream. zKa-Ping Yee zpGvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger, Trent Nelson, Michael Foord)open)lookupBOM_UTF8N) TextIOWrapper)*)EXACT_TOKEN_TYPESz&^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)s^[ \t\f]*(?:[#\r\n]|$))tokenizegenerate_tokensdetect_encoding untokenize TokenInfoc@s eZdZddZeddZdS)r cCs$d|jt|jf}d|j|dS)Nz%d (%s)z8TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r))type)r tok_name_replace)selfZannotated_typer$/usr/local/lib/python3.9/tokenize.py__repr__.s zTokenInfo.__repr__cCs(|jtkr|jtvrt|jS|jSdSN)r OPstringrrrrr exact_type3s zTokenInfo.exact_typeN)__name__ __module__ __qualname__rpropertyrrrrrr -sr ztype string start end linecGsdd|dS)N(|))joinchoicesrrrgroup:r#cGs t|dS)Nrr#r!rrrany;r$r&cGs t|dS)N?r%r!rrrmaybe<r$r(z[ \f\t]*z #[^\r\n]*z\\\r?\nz\w+z0[xX](?:_?[0-9a-fA-F])+z0[bB](?:_?[01])+z0[oO](?:_?[0-7])+z(?:0(?:_?0)*|[1-9](?:_?[0-9])*)z[eE][-+]?[0-9](?:_?[0-9])*z)[0-9](?:_?[0-9])*\.(?:[0-9](?:_?[0-9])*)?z\.[0-9](?:_?[0-9])*z[0-9](?:_?[0-9])*z[0-9](?:_?[0-9])*[jJ]z[jJ]cCsVgd}dh}|D]>}t|D].}tjdd|DD]}|d|q8q q|S)N)brufbrfrcSsg|]}||fqSr)upper).0crrr ^r$z(_all_string_prefixes..) _itertools permutationsproductaddr )Z_valid_string_prefixesresultprefixtr+rrr_all_string_prefixesSsr;cCst|tjSr)recompileUNICODE)Zexprrrr_compilebsr?z[^'\\]*(?:\\.[^'\\]*)*'z[^"\\]*(?:\\.[^"\\]*)*"z%[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''z%[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""z'''z"""z'[^\n'\\]*(?:\\.[^\n'\\]*)*'z"[^\n"\\]*(?:\\.[^\n"\\]*)*"T)reversez\r?\nz'[^\n'\\]*(?:\\.[^\n'\\]*)*'z"[^\n"\\]*(?:\\.[^\n"\\]*)*"z \\\r?\n|\Zc@s eZdZdS) TokenErrorNrrrrrrrrDr$rDc@s eZdZdS)StopTokenizingNrErrrrrFr$rFc@s,eZdZddZddZddZddZd S) UntokenizercCsg|_d|_d|_d|_dS)Nr)tokensprev_rowprev_colencodingrrrr__init__szUntokenizer.__init__cCs|\}}||jks&||jkr>||jkr>td|||j|j||j}|rb|jd|d|_||j}|r|jd|dS)Nz+start ({},{}) precedes previous end ({},{})\ r )rJrK ValueErrorformatrIappend)rstartrowZcolZ row_offset col_offsetrrradd_whitespaces   zUntokenizer.add_whitespacec Cs6t|}g}d}|D]}t|dkr8|||q*|\}}}} } |tkrV||_q|tkrdq*|tkrz||qnl|tkr| | \|_ |_ qnL|t t fvrd}n:|r|r|d} |dt| kr|j| t| |_ d}|||j|| \|_ |_ |t t fvr|j d7_ d|_ qd|jS)NFTrHrr/)iterlencompatENCODINGrL ENDMARKERINDENTrRDEDENTpoprJrKNEWLINENLrIrVr ) riterableitindents startliner:Ztok_typetokenrSendlineindentrrrr sF            zUntokenizer.untokenizec Csg}|jj}|dttfv}d}t|g|D]}|dd\}} |tkrR| |_q.|tt fvrf| d7} |t kr|rzd| } d}nd}|t kr|| q.n>|t kr| q.n*|ttfvrd}n|r|r||dd}|| q.dS)NrFrWrOTrX)rIrRrarbr4chainr\rLNAMENUMBERSTRINGr^r_r`) rrgrcreZ toks_appendrfZ prevstringZtokZtoknumZtokvalrrrr[s8    zUntokenizer.compatN)rrrrMrVr r[rrrrrGs %rGcCs*t}||}|jdur&||j}|S)aTransform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the resulting output is poor. Round-trip invariant for full input: Untokenized source will match input source exactly Round-trip invariant for limited input: # Output bytes will tokenize back to the input t1 = [tok[:2] for tok in tokenize(f.readline)] newcode = untokenize(t1) readline = BytesIO(newcode).readline t2 = [tok[:2] for tok in tokenize(readline)] assert t1 == t2 N)rGr rLencode)rcZutoutrrrr s    r cCsH|dddd}|dks*|dr.dS|dvs@|drDd S|S) z(Imitates get_normal_name in tokenizer.c.N _-utf-8zutf-8-)zlatin-1 iso-8859-1z iso-latin-1)zlatin-1-z iso-8859-1-z iso-latin-1-ru)lowerreplace startswith)Zorig_encencrrr_get_normal_namesrzcsz jjWnty"dYn0dd}d}fdd}fdd}|}|trnd|d d}d }|sz|gfS||}|r||gfSt|s||gfS|}|s||gfS||}|r|||gfS|||gfS) a The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes) it has read in. It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in pep-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. If the encoding cookie is an invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, 'utf-8-sig' is returned. If no encoding is specified, then the default of 'utf-8' will be returned. NFrtcs"zWStyYdS0dS)Nr$) StopIterationrreadlinerr read_or_stop?s z%detect_encoding..read_or_stopcsz|d}Wn2ty@d}dur4d|}t|Yn0t|}|sTdSt|d}z t|}Wn8t ydurd|}n d|}t|Yn0r|dkrԈdurd}n d}t||d 7}|S) Nrtz'invalid or missing encoding declarationz {} for {!r}rHzunknown encoding: zunknown encoding for {!r}: {}zencoding problem: utf-8z encoding problem for {!r}: utf-8z-sig) decodeUnicodeDecodeErrorrQ SyntaxError cookie_rematchrzr#r LookupError)riZ line_stringmsgrrLcodec) bom_foundfilenamerr find_cookieEs8       z$detect_encoding..find_cookieT utf-8-sig)__self__nameAttributeErrorrxrblank_rer)r}rLdefaultr~rfirstsecondr)rrr}rr 's8    &       r cCsXt|d}z2t|j\}}|dt||dd}d|_|WS|Yn0dS)zXOpen a file in read only mode using the encoding detected by detect_encoding(). rbrT)line_bufferingr*N) _builtin_openr r}seekrmodeclose)rbufferrLlinestextrrrrs  rcCs6t|\}}td}t|t|d|}t|j|S)a The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the readline() method of built-in file objects. Each call to the function should return one line of input as bytes. Alternatively, readline can be a callable function terminating with StopIteration: readline = open(myfile, 'rb').__next__ # Example of alternate readline The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed is the physical line. The first token sequence will always be an ENCODING token which tells you which encoding was used to decode the bytes stream. r$)r r4repeatrkrY _tokenize__next__)r}rLconsumedemptyZrl_genrrrrs  rccszd}}}d}d\}}d}dg} |durH|dkr6d}tt|dddVd} d} z| } |} Wntytd} Yn0|dur| |} |d 7}dt| } } |rn| std ||| }|r|d} }tt|| d||||f|| Vd\}}d}nf|rX| d dd krX| d ddkrXtt || ||t| f|Vd}d}qPn|| }|| }qPn|dkr|s| sqd}| | kr| | dkr|d 7}n8| | dkr|t d t }n| | dkrd}nq| d 7} q| | krq| | dvr| | dkr\| | d d}tt ||| f|| t|f| V| t|7} tt | | d|| f|t| f| VqP|| dkr| |tt| d| |df|| f| V|| dkr,|| vrtdd|| | f| dd} ttd|| f|| f| Vqn| s(td|dfd}| | krPtt| | }|r|d \}}||f||f|}}} ||kr~q,| ||| |}}||vs|dkr|dkr|dkrtt|||| Vq|dvr|dkrtt |||| Vntt|||| Vq|dkr@|dr*Jtt |||| Vq|tvrtt|}|| | }|r|d} | || }tt|||| f| Vn||f}| |d}| }qPq|tvs|ddtvs|ddtvrT|ddkr@||f}tt|p"t|d p"t|d}| |dd }}| }qPntt|||| Vnf|rrtt|||| VnH|dkrd }n8|dvr|d 7}n|d vr|d 8}tt|||| Vn*tt | | || f|| d f| V| d 7} q,qP| r.| ddvr.ttd|d t| f|d t| d fdV| d dD] }ttd|df|dfdVq:ttd|df|dfdVdS)!Nr 0123456789)r/rrrt)rrr/r$rHzEOF in multi-line stringrNz\ rO  z# #z rXz3unindent does not match any outer indentation levelz zEOF in multi-line statement.z... rWr\z([{z)]}) r r\r{rrZrDrrhrnZ ERRORTOKENtabsizerstripZCOMMENTrbrRr^IndentationErrorr_r? PseudoTokenspanrmraendswith triple_quotedendpats single_quotedget isidentifierrlrr])r}rLZlnumZparenlevZ continuedZnumcharsZcontstrZneedcontZcontlinere last_lineriposmaxZstrstartZendprogZendmatchrhcolumnZ comment_tokenZ pseudomatchrSZsposZeposrginitialrjrrrrs(       *        "                        .rcCs t|dS)zTokenize a source reading Python code as unicode strings. This has the same API as tokenize(), except that it expects the *readline* callable to return str objects instead of bytes. N)rr|rrrr dsr c s@ddl}dddfdd }|jdd}|jdd d d d |jd ddddd|}z|jr|j}t|d}tt|j}Wdq1s0Ynd}t t j jd}|D]>}|j }|j r|j}d|j|j} td| t||jfqWn@tyL} z8| jddd\} } || jd|| | fWYd} ~ nd} ~ 0ty} z0| jd\} } || jd|| | fWYd} ~ nd} ~ 0ty} z|| |WYd} ~ nd} ~ 0ty} z|| WYd} ~ nVd} ~ 0tytdYn4ty:} zd| WYd} ~ n d} ~ 00dS)NrcSstj|tjddS)Nr)sysstderrwrite)messagerrrperrorps zmain..perrorcsR|r"|f||f}d|n"|r8d||fn d|tddS)Nz%s:%d:%d: error: %sz %s: error: %sz error: %srH)rexit)rrlocationargsrrrerrorts zmain..errorzpython -m tokenize)progrr'z filename.pyz'the file to tokenize; defaults to stdin)destnargsmetavarhelpz-ez--exactexact store_truez(display token names using the exact type)ractionrrzz %d,%d-%d,%d:z%-20s%-15s%-15rrHrz interrupted zunexpected error: %s)NN)argparseArgumentParser add_argument parse_argsrrlistrr}rrstdinr rrrSrhprintrrrrrDrOSErrorKeyboardInterrupt Exception) rrparserrrr,rIrgZ token_typeZ token_rangeerrrirrrrmainlsT   .**  r__main__)S__doc__ __author__Z __credits__builtinsrrcodecsrr collectionsior itertoolsr4r<rrgrr=ASCIIrr__all__ namedtupler r#r&r(Z WhitespaceZCommentZIgnoreZNameZ HexnumberZ BinnumberZ OctnumberZ DecnumberZ IntnumberZExponentZ PointfloatZExpfloatZ FloatnumberZ ImagnumberZNumberr;r?Z StringPrefixZSingleZDoubleZSingle3ZDouble3ZTripleZStringmapescapesortedZSpecialZFunnyZ PlainTokenZTokenZContStrZ PseudoExtrasrr_prefixsetrrr:r+r7rrrDrFrGr rzr rrr rrrrrrs              _ ]8=