B \]i/@sdZdZdZddlmZddlmZmZddl Z ddl m Z ddl m Z ddl ZddlZddlZdd lTed ejZed ejZddlZejd d ddgZ[eeeeeeeeee e!e"e#e$e%e&e'e(e)e*e+e,e-e.e/e0e1e2e3e4e5e6e7e8e9e:e;ee?e@eAeBeCeDd.ZEGddde FddZGddZHddZIddZJdZKdZLeKeIdeKeJeLZMdZNdZOdZPdZQd ZReHeOePeQeRZSd!ZTeHd"d#eJeTZUd$eTZVeHeUeVZWeHd%eWd&ZXeHeXeWeSZYd'd(ZZd)d*Z[eHeZZ\d+Z]d,Z^d-Z_d.Z`eHe\d/e\d0ZaeHe\d1e\d2ZbeHd3d4d5d6d7d8d9d:Zcd;ZdeHdZeeHecedeeZfeHeYefebeNZgeMegZheHe\d?eHd@de\dAeHdBdZieHdCeLeaZjeKeHejeYefeieNZkiZlx@eZD]6Zme]elemd@<e^elemdB<e_elemd/<e`elemd0<qWenZoenZpx\eZD]RZqx$eqdBeqd@fD]ZreoserqWx$eqd0eqd/fD]Zrepserq(WqWdDZtGdEdFdFeuZvGdGdHdHeuZwGdIdJdJZxdKdZydLdMZzdNd Z{dOdPZdQd Z|dRdSZ}dTdUZ~dVdWZedXkredS)YaoTokenization 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)chain)*z&^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)s^[ \t\f]*(?:[#\r\n]|$)tokenizedetect_encoding untokenize TokenInfo).()[]:,;+-r/|&<>=.%{}z==z!=z<=z>=~^z<>z**z+=z-=z*=z/=z%=z&=z|=z^=z<<=z>>=z**=z//z//=z...z->@z@=c@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.7/tokenize.py__repr___szTokenInfo.__repr__cCs(|jtkr|jtkrt|jS|jSdS)N)r"OPstringEXACT_TOKEN_TYPES)r%r&r&r' exact_typeds zTokenInfo.exact_typeN)__name__ __module__ __qualname__r(propertyr,r&r&r&r'r ^sztype string start end linecGsdd|dS)Nr rr )join)choicesr&r&r'groupkr3cGs t|dS)Nr)r3)r2r&r&r'anylr4r5cGs t|dS)N?)r3)r2r&r&r'maybemr4r7z[ \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]cCsjddddddg}dh}xN|D]F}x@t|D]2}x,tjdd |DD]}|d|qFWq,WqW|S) NbrufbrfrcSsg|]}||fqSr&)upper).0cr&r&r' sz(_all_string_prefixes..) _itertools permutationsproductaddr1)Z_valid_string_prefixesresultprefixtr:r&r&r'_all_string_prefixess rJcCst|tjS)N)recompileUNICODE)Zexprr&r&r'_compilesrNz[^'\\]*(?:\\.[^'\\]*)*'z[^"\\]*(?:\\.[^"\\]*)*"z%[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''z%[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""z'''z"""z'[^\n'\\]*(?:\\.[^\n'\\]*)*'z"[^\n"\\]*(?:\\.[^\n"\\]*)*"z\*\*=?z>>=?z<<=?z!=z//=?z->z[+\-*/%&@|^=<>]=?rz[][(){}]z\r?\nz\.\.\.z[:;.,@]z'[^\n'\\]*(?:\\.[^\n'\\]*)*'z"[^\n"\\]*(?:\\.[^\n"\\]*)*"z \\\r?\n|\Zc@s eZdZdS) TokenErrorN)r-r.r/r&r&r&r'rRsrRc@s eZdZdS)StopTokenizingN)r-r.r/r&r&r&r'rSsrSc@s,eZdZddZddZddZddZd S) UntokenizercCsg|_d|_d|_d|_dS)Nr)tokensprev_rowprev_colencoding)r%r&r&r'__init__szUntokenizer.__init__cCs|\}}||jks&||jkr>||jkr>td|||j|j||j}|rb|jd|d|_||j}|r|jd|dS)Nz+start ({},{}) precedes previous end ({},{})z\ r )rWrX ValueErrorformatrVappend)r%startrowZcolZ row_offsetZ col_offsetr&r&r'add_whitespaces  zUntokenizer.add_whitespacec Cs4t|}g}d}x|D] }t|dkr8|||P|\}}}} } |tkrV||_q|tkr`P|tkrv||qnl|tkr| | \|_ |_ qnL|t t fkrd}n:|r|r|d} |dt| kr|j| t| |_ d}|||j|| \|_ |_ |t t fkr|j d7_ d|_ qWd|jS)NFTrUrr>)iterlencompatENCODINGrY ENDMARKERINDENTr^DEDENTpoprWrXNEWLINENLrVrar1) r%iterableitindents startlinerIZtok_typetokenr_endlineindentr&r&r'r sF            zUntokenizer.untokenizec Csg}|jj}|dttfk}d}xt|g|D]}|dd\}} |tkrR| |_q.|ttfkrf| d7} |t kr|rzd| } d}nd}|t kr|| q.n>|t kr| q.n*|ttfkrd}n|r|r||dd}|| q.WdS)NrFrbr[Trc) rVr^rlrmrrgrYNAMENUMBERSTRINGrirjrk) r%rrrnrpZ toks_appendrqZ prevstringZtokZtoknumZtokvalr&r&r'rfs8    zUntokenizer.compatN)r-r.r/rZrar rfr&r&r&r'rTs %rTcCs*t}||}|jdk r&||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)rTr rYencode)rnZutoutr&r&r'r 8s    cCsH|dddd}|dks*|dr.dS|dks@|drDd S|S) z(Imitates get_normal_name in tokenizer.c.N _rzutf-8zutf-8-)zlatin-1z iso-8859-1z iso-latin-1)zlatin-1-z iso-8859-1-z iso-latin-1-z iso-8859-1)lowerreplace startswith)Zorig_encencr&r&r'_get_normal_nameSs rcsy jjWntk r$dYnXdd}d}fdd}fdd}|}|trpd|d d}d }|s||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. NFzutf-8cs yStk rdSXdS)Nr4) StopIterationr&)readliner&r' read_or_stopvsz%detect_encoding..read_or_stopcsy|d}Wn4tk rBd}dk r6d|}t|YnXt|}|sVdSt|d}y t|}Wn:t k rdkrd|}n d|}t|YnXr|dkr؈dkrd}n d}t||d 7}|S) Nzutf-8z'invalid or missing encoding declarationz {} for {!r}rUzunknown encoding: zunknown encoding for {!r}: {}zencoding problem: utf-8z encoding problem for {!r}: utf-8z-sig) decodeUnicodeDecodeErrorr] SyntaxError cookie_rematchrr3r LookupError)rtZ line_stringmsgrrYZcodec) bom_foundfilenamer&r' find_cookie|s6     z$detect_encoding..find_cookieTz utf-8-sig)__self__nameAttributeErrorrrblank_rer)rrYdefaultrrfirstZsecondr&)rrrr'r ^s8   &       cCsVt|d}y0t|j\}}|dt||dd}d|_|S|YnXdS)zXOpen a file in read only mode using the encoding detected by detect_encoding(). rbrT)line_bufferingr9N) _builtin_openr rseekrmodeclose)rbufferrYlinestextr&r&r'rs  rcCsBddlm}m}t|\}}t|d}|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 logical line; continuation lines are included. The first token sequence will always be an ENCODING token which tells you which encoding was used to decode the bytes stream. r)rrepeatr4) itertoolsrrr rd _tokenize__next__)rrrrYconsumedZrl_genemptyr&r&r'rs   ccsd}}}d}d\}}d}dg} |dk rH|dkr6d}tt|dddVd} d} xy| } |} Wntk rzd} YnX|dk r| |} |d 7}dt| } } |rt| std ||| }|r |d} }tt|| d||||f|| Vd\}}d}nf|r^| d dd kr^| d ddkr^tt || ||t| f|Vd}d}qTn|| }|| }qTn|dkr|s| sPd}xf| | kr| | dkr|d 7}n6| | dkr|t d t }n| | dkrd}nP| d 7} qW| | krP| | dkr| | dkr`| | d d}tt ||| f|| t|f| V| t|7} tt | | d|| f|t| f| VqT|| dkr| |tt| d| |df|| f| Vxp|| dkr|| krtdd|| | f| dd} ttd|| f|| f| VqWn| s0td|dfd}x| | krtt| | }|r|d \}}||f||f|}}} ||krq8| ||| |}}||ks|dkr|dkr|dkrtt|||| Vq|dkr|dkrtt |||| Vntt|||| Vq|dkrN|dr8ttt |||| Vq|tkrtt|}|| | }|r|d} | || }tt|||| f| Vn||f}| |d}| }Pq|tks|ddtks|ddtkrb|ddkrN||f}tt|p0t|d p0t|d}| |dd }}| }Pntt|||| Vnf|rtt|||| VnH|dkrd }n8|dkr|d 7}n|d kr|d 8}tt|||| Vn*tt | | || f|| d f| V| d 7} q8WqTW| r@| ddkr@ttd|d t| f|d t| d fdVx0| d dD] }ttd|df|dfdVqNWtt d|df|dfdVdS)!Nr 0123456789)r>rz utf-8-sigzutf-8)rrr>r4rUzEOF in multi-line stringz\ z\ r[  z# #z rcz3unindent does not match any outer indentation levelz zEOF in multi-line statementrz... rbr\z([{z)]})!r rgrrrerRrrsrxZ ERRORTOKENtabsizerstripZCOMMENTrmr^riIndentationErrorrjrN PseudoTokenspanrwrlendswithAssertionError triple_quotedendpats single_quotedget isidentifierrvr)rh)rrYZlnumZparenlevZ continuedZnumcharsZcontstrZneedcontZcontlinerp last_linertposmaxZstrstartZendprogZendmatchrscolumnZ comment_tokenZ pseudomatchr_ZsposZeposrrZinitialrur&r&r'rs      *      "  "                  . rcCs t|dS)N)r)rr&r&r'generate_tokenssrc s(ddl}dddfdd }|jdd}|jdd d d d |jd ddddd|}y|jr|j}t|d}tt|j}WdQRXnd}t t j jd}xF|D]>}|j }|j r|j}d|j|j} td| t||jfqWWn8tk r:} z0| jddd\} } || jd|| | fWdd} ~ XYntk r} z(| jd\} } || jd|| | fWdd} ~ XYntk r} z|| |Wdd} ~ XYnxtk r} z || Wdd} ~ XYnNtk rtdYn2tk r"} zd| Wdd} ~ XYnXdS)NrcSst|tjddS)N)file)printsysstderr)messager&r&r'perrorszmain..perrorcsR|r"|f||f}d|n"|r8d||fn d|tddS)Nz%s:%d:%d: error: %sz %s: error: %sz error: %srU)rexit)rrlocationargs)rr&r'errors zmain..errorzpython -m tokenize)Zprogrr6z filename.pyz'the file to tokenize; defaults to stdin)destZnargsZmetavarhelpz-ez--exactexactZ store_truez(display token names using the exact type)ractionrrzz %d,%d-%d,%d:z%-20s%-15s%-15rrUrz interrupted zunexpected error: %s)NN)argparseZArgumentParserZ add_argumentZ parse_argsrrlistrrrrstdinr"rr,r_rsrr#r*rrrRrOSErrorKeyboardInterrupt Exception) rrZparserrrr;rVrrZ token_typeZ token_rangeerrrtrr&)rr'mainsN    &&  r__main__)__doc__ __author__Z __credits__builtinsrrcodecsrr collectionsiorrrrCrKrrrrLASCIIrr__all__ZLPARZRPARZLSQBZRSQBZCOLONZCOMMAZSEMIZPLUSZMINUSZSTARZSLASHZVBARZAMPERZLESSZGREATERZEQUALZDOTZPERCENTZLBRACEZRBRACEZEQEQUALZNOTEQUALZ LESSEQUALZ GREATEREQUALZTILDEZ CIRCUMFLEXZ LEFTSHIFTZ RIGHTSHIFTZ DOUBLESTARZ PLUSEQUALZMINEQUALZ STAREQUALZ SLASHEQUALZ PERCENTEQUALZ AMPEREQUALZ VBAREQUALZCIRCUMFLEXEQUALZLEFTSHIFTEQUALZRIGHTSHIFTEQUALZDOUBLESTAREQUALZ DOUBLESLASHZDOUBLESLASHEQUALZELLIPSISZRARROWATZATEQUALr+ namedtupler r3r5r7Z WhitespaceZCommentZIgnoreZNameZ HexnumberZ BinnumberZ OctnumberZ DecnumberZ IntnumberZExponentZ PointfloatZExpfloatZ FloatnumberZ ImagnumberZNumberrJrNZ StringPrefixZSingleZDoubleZSingle3ZDouble3ZTripleZStringZOperatorZBracketZSpecialZFunnyZ PlainTokenZTokenZContStrZ PseudoExtrasrrZ_prefixsetrrrIr:rFrrrRrSrTr rr rrrrr-r&r&r&r's                   _ ]:<