You can subscribe to this list here.
2000 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(1) |
Nov
(107) |
Dec
(67) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2001 |
Jan
(76) |
Feb
(125) |
Mar
(72) |
Apr
(13) |
May
(18) |
Jun
(12) |
Jul
(129) |
Aug
(47) |
Sep
(1) |
Oct
(36) |
Nov
(128) |
Dec
(124) |
2002 |
Jan
(59) |
Feb
|
Mar
(14) |
Apr
(14) |
May
(72) |
Jun
(9) |
Jul
(3) |
Aug
(5) |
Sep
(18) |
Oct
(65) |
Nov
(28) |
Dec
(12) |
2003 |
Jan
(10) |
Feb
(2) |
Mar
(4) |
Apr
(33) |
May
(21) |
Jun
(9) |
Jul
(29) |
Aug
(34) |
Sep
(4) |
Oct
(8) |
Nov
(15) |
Dec
(4) |
2004 |
Jan
(26) |
Feb
(12) |
Mar
(11) |
Apr
(9) |
May
(7) |
Jun
|
Jul
(5) |
Aug
|
Sep
(3) |
Oct
(7) |
Nov
(1) |
Dec
(10) |
2005 |
Jan
(2) |
Feb
(72) |
Mar
(16) |
Apr
(39) |
May
(48) |
Jun
(97) |
Jul
(57) |
Aug
(13) |
Sep
(16) |
Oct
(24) |
Nov
(100) |
Dec
(24) |
2006 |
Jan
(15) |
Feb
(34) |
Mar
(33) |
Apr
(31) |
May
(79) |
Jun
(64) |
Jul
(41) |
Aug
(64) |
Sep
(31) |
Oct
(46) |
Nov
(55) |
Dec
(37) |
2007 |
Jan
(32) |
Feb
(61) |
Mar
(11) |
Apr
(58) |
May
(46) |
Jun
(30) |
Jul
(94) |
Aug
(93) |
Sep
(86) |
Oct
(69) |
Nov
(125) |
Dec
(177) |
2008 |
Jan
(169) |
Feb
(97) |
Mar
(74) |
Apr
(113) |
May
(120) |
Jun
(334) |
Jul
(215) |
Aug
(237) |
Sep
(72) |
Oct
(189) |
Nov
(126) |
Dec
(160) |
2009 |
Jan
(180) |
Feb
(45) |
Mar
(98) |
Apr
(140) |
May
(151) |
Jun
(71) |
Jul
(107) |
Aug
(119) |
Sep
(73) |
Oct
(121) |
Nov
(14) |
Dec
(6) |
2010 |
Jan
(13) |
Feb
(9) |
Mar
(10) |
Apr
(64) |
May
(3) |
Jun
(16) |
Jul
(7) |
Aug
(23) |
Sep
(17) |
Oct
(37) |
Nov
(5) |
Dec
(8) |
2011 |
Jan
(10) |
Feb
(11) |
Mar
(77) |
Apr
(11) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <fwi...@us...> - 2008-07-04 12:21:31
|
Revision: 4848 http://jython.svn.sourceforge.net/jython/?rev=4848&view=rev Author: fwierzbicki Date: 2008-07-04 05:21:30 -0700 (Fri, 04 Jul 2008) Log Message: ----------- Removed ENDMARKER from Python.g and applied Leo Soto's patch to add a newline to the end of input that ends w/o a newline. Modified Paths: -------------- branches/asm/grammar/Python.g branches/asm/src/org/python/antlr/PythonTokenSource.java Modified: branches/asm/grammar/Python.g =================================================================== --- branches/asm/grammar/Python.g 2008-07-04 02:01:44 UTC (rev 4847) +++ branches/asm/grammar/Python.g 2008-07-04 12:21:30 UTC (rev 4848) @@ -77,7 +77,6 @@ tokens { INDENT; DEDENT; - ENDMARKER; Module; Interactive; @@ -483,18 +482,18 @@ } //single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE -single_input : NEWLINE ENDMARKER? -> ^(Interactive) - | simple_stmt ENDMARKER? -> ^(Interactive simple_stmt) - | compound_stmt NEWLINE ENDMARKER? -> ^(Interactive compound_stmt) +single_input : NEWLINE -> ^(Interactive) + | simple_stmt -> ^(Interactive simple_stmt) + | compound_stmt NEWLINE -> ^(Interactive compound_stmt) ; //file_input: (NEWLINE | stmt)* ENDMARKER -file_input : (NEWLINE | stmt)* ENDMARKER? {debug("parsed file_input");} +file_input : (NEWLINE | stmt)* {debug("parsed file_input");} -> ^(Module stmt*) ; //eval_input: testlist NEWLINE* ENDMARKER -eval_input : (NEWLINE)* testlist[expr_contextType.Load] (NEWLINE)* ENDMARKER? -> ^(Expression testlist) +eval_input : (NEWLINE)* testlist[expr_contextType.Load] (NEWLINE)* -> ^(Expression testlist) ; //not in CPython's Grammar file @@ -566,7 +565,7 @@ ; //simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE -simple_stmt : small_stmt (options {greedy=true;}:SEMI small_stmt)* (SEMI)? (NEWLINE|ENDMARKER) +simple_stmt : small_stmt (options {greedy=true;}:SEMI small_stmt)* (SEMI)? NEWLINE -> small_stmt+ ; //small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | Modified: branches/asm/src/org/python/antlr/PythonTokenSource.java =================================================================== --- branches/asm/src/org/python/antlr/PythonTokenSource.java 2008-07-04 02:01:44 UTC (rev 4847) +++ branches/asm/src/org/python/antlr/PythonTokenSource.java 2008-07-04 12:21:30 UTC (rev 4848) @@ -125,13 +125,6 @@ // if something in queue, just remove and return it if ( tokens.size()>0 ) { Token t = (Token)tokens.firstElement(); - if ( !atEnd && t.getType()==Token.EOF ) { - atEnd = true; - Token em = new ClassicToken(PythonPartialParser.ENDMARKER,"END"); - em.setCharPositionInLine(t.getCharPositionInLine()); - em.setLine(t.getLine()); - return em; - } tokens.removeElementAt(0); //System.out.println(t); return t; @@ -147,8 +140,8 @@ Token t = stream.LT(1); stream.consume(); - // if not a NEWLINE, doesn't signal indent/dedent work; just enqueue - if ( t.getType()!=PythonLexer.NEWLINE ) { + // if the current token is not a NEWLINE or EOF, it doesn't signal indent/dedent work; just enqueue + if (t.getType() != PythonLexer.NEWLINE && t.getType() != PythonLexer.EOF) { List hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); if ( hiddenTokens!=null ) { tokens.addAll(hiddenTokens); @@ -158,25 +151,34 @@ return; } - // save NEWLINE in the queue - //System.out.println("found newline: "+t+" stack is "+stackString()); - CommonToken newline = (CommonToken)t; - List hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); - if ( hiddenTokens!=null ) { - tokens.addAll(hiddenTokens); - } - lastTokenAddedIndex = t.getTokenIndex(); - tokens.addElement(t); + CommonToken newline; + if (t.getType() == PythonLexer.NEWLINE) { + // save NEWLINE in the queue + //System.out.println("found newline: "+t+" stack is "+stackString()); + newline = (CommonToken)t; + List hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); + if (hiddenTokens!=null) { + tokens.addAll(hiddenTokens); + } + lastTokenAddedIndex = t.getTokenIndex(); + tokens.addElement(t); - // grab first token of next line - t = stream.LT(1); - stream.consume(); + // grab first token of next line + t = stream.LT(1); + stream.consume(); - hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); - if ( hiddenTokens!=null ) { - tokens.addAll(hiddenTokens); + hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); + if (hiddenTokens!=null) { + tokens.addAll(hiddenTokens); + } + lastTokenAddedIndex = t.getTokenIndex(); + } else { + // Imaginary newline before EOF + newline = new CommonToken(PythonLexer.NEWLINE, "\n"); + newline.setLine(t.getLine()); + newline.setCharPositionInLine(t.getCharPositionInLine()); + tokens.addElement(newline); } - lastTokenAddedIndex = t.getTokenIndex(); // compute cpos as the char pos of next non-WS token in line int cpos = t.getCharPositionInLine(); // column dictates indent/dedent @@ -195,7 +197,7 @@ if ( cpos > lastIndent ) { // they indented; track and gen INDENT push(cpos); //System.out.println("push("+cpos+"): "+stackString()); - Token indent = new ClassicToken(PythonParser.INDENT,""); + Token indent = new ImaginaryToken(PythonParser.INDENT,""); indent.setCharPositionInLine(t.getCharPositionInLine()); indent.setLine(t.getLine()); tokens.addElement(indent); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-07-04 02:01:49
|
Revision: 4847 http://jython.svn.sourceforge.net/jython/?rev=4847&view=rev Author: fwierzbicki Date: 2008-07-03 19:01:44 -0700 (Thu, 03 Jul 2008) Log Message: ----------- import test_support. Modified Paths: -------------- branches/asm/Lib/test/test_jy_compile.py Modified: branches/asm/Lib/test/test_jy_compile.py =================================================================== --- branches/asm/Lib/test/test_jy_compile.py 2008-07-04 01:49:41 UTC (rev 4846) +++ branches/asm/Lib/test/test_jy_compile.py 2008-07-04 02:01:44 UTC (rev 4847) @@ -2,7 +2,8 @@ test compile. derived from test_codeop """ import unittest -from test_support import run_unittest +from test import test_support +from test.test_support import run_unittest def compile_(source,name="<input>",symbol="single"): This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-07-04 01:49:42
|
Revision: 4846 http://jython.svn.sourceforge.net/jython/?rev=4846&view=rev Author: fwierzbicki Date: 2008-07-03 18:49:41 -0700 (Thu, 03 Jul 2008) Log Message: ----------- Introduced ENDMARKER to Python.g -- needed for files that lack a newline. Modified Paths: -------------- branches/asm/grammar/Python.g branches/asm/src/org/python/antlr/PythonTokenSource.java Modified: branches/asm/grammar/Python.g =================================================================== --- branches/asm/grammar/Python.g 2008-07-04 01:13:07 UTC (rev 4845) +++ branches/asm/grammar/Python.g 2008-07-04 01:49:41 UTC (rev 4846) @@ -77,7 +77,8 @@ tokens { INDENT; DEDENT; - + ENDMARKER; + Module; Interactive; Expression; @@ -482,18 +483,18 @@ } //single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE -single_input : NEWLINE -> ^(Interactive) - | simple_stmt -> ^(Interactive simple_stmt) - | compound_stmt NEWLINE -> ^(Interactive compound_stmt) +single_input : NEWLINE ENDMARKER? -> ^(Interactive) + | simple_stmt ENDMARKER? -> ^(Interactive simple_stmt) + | compound_stmt NEWLINE ENDMARKER? -> ^(Interactive compound_stmt) ; //file_input: (NEWLINE | stmt)* ENDMARKER -file_input : (NEWLINE | stmt)* {debug("parsed file_input");} +file_input : (NEWLINE | stmt)* ENDMARKER? {debug("parsed file_input");} -> ^(Module stmt*) ; //eval_input: testlist NEWLINE* ENDMARKER -eval_input : (NEWLINE)* testlist[expr_contextType.Load] (NEWLINE)* -> ^(Expression testlist) +eval_input : (NEWLINE)* testlist[expr_contextType.Load] (NEWLINE)* ENDMARKER? -> ^(Expression testlist) ; //not in CPython's Grammar file @@ -565,7 +566,7 @@ ; //simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE -simple_stmt : small_stmt (options {greedy=true;}:SEMI small_stmt)* (SEMI)? NEWLINE +simple_stmt : small_stmt (options {greedy=true;}:SEMI small_stmt)* (SEMI)? (NEWLINE|ENDMARKER) -> small_stmt+ ; //small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt | Modified: branches/asm/src/org/python/antlr/PythonTokenSource.java =================================================================== --- branches/asm/src/org/python/antlr/PythonTokenSource.java 2008-07-04 01:13:07 UTC (rev 4845) +++ branches/asm/src/org/python/antlr/PythonTokenSource.java 2008-07-04 01:49:41 UTC (rev 4846) @@ -88,6 +88,8 @@ int lastTokenAddedIndex = -1; + boolean atEnd = false; + public PythonTokenSource(PythonLexer lexer) { } @@ -123,8 +125,15 @@ // if something in queue, just remove and return it if ( tokens.size()>0 ) { Token t = (Token)tokens.firstElement(); + if ( !atEnd && t.getType()==Token.EOF ) { + atEnd = true; + Token em = new ClassicToken(PythonPartialParser.ENDMARKER,"END"); + em.setCharPositionInLine(t.getCharPositionInLine()); + em.setLine(t.getLine()); + return em; + } tokens.removeElementAt(0); - // System.out.println(t); + //System.out.println(t); return t; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fwi...@us...> - 2008-07-04 01:13:16
|
Revision: 4845 http://jython.svn.sourceforge.net/jython/?rev=4845&view=rev Author: fwierzbicki Date: 2008-07-03 18:13:07 -0700 (Thu, 03 Jul 2008) Log Message: ----------- change token name from ENDMARK to ENDMARKER to better fit with CPython's Grammar/Grammar file. Alse some tabs->spaces. Modified Paths: -------------- branches/asm/grammar/PythonPartial.g branches/asm/src/org/python/antlr/PythonPartialTokenSource.java branches/asm/src/org/python/antlr/PythonTokenSource.java Modified: branches/asm/grammar/PythonPartial.g =================================================================== --- branches/asm/grammar/PythonPartial.g 2008-07-03 13:44:52 UTC (rev 4844) +++ branches/asm/grammar/PythonPartial.g 2008-07-04 01:13:07 UTC (rev 4845) @@ -67,7 +67,7 @@ tokens { INDENT; DEDENT; - ENDMARK; + ENDMARKER; } @header { @@ -232,7 +232,7 @@ | compound_stmt ; -simple_stmt : small_stmt (options {greedy=true;}:SEMI small_stmt)* (SEMI)? (NEWLINE|ENDMARK) +simple_stmt : small_stmt (options {greedy=true;}:SEMI small_stmt)* (SEMI)? (NEWLINE|ENDMARKER) ; small_stmt : expr_stmt @@ -389,7 +389,7 @@ ; suite : simple_stmt - | NEWLINE ((INDENT (stmt)+ (DEDENT|ENDMARK))|ENDMARK) + | NEWLINE ((INDENT (stmt)+ (DEDENT|ENDMARKER))|ENDMARKER) ; test: or_test {debug("matched test: or_test");} Modified: branches/asm/src/org/python/antlr/PythonPartialTokenSource.java =================================================================== --- branches/asm/src/org/python/antlr/PythonPartialTokenSource.java 2008-07-03 13:44:52 UTC (rev 4844) +++ branches/asm/src/org/python/antlr/PythonPartialTokenSource.java 2008-07-04 01:13:07 UTC (rev 4845) @@ -83,7 +83,7 @@ stream.consume(); if ( t.getType()==Token.EOF ) { atEnd = true; - Token em = new ClassicToken(PythonPartialParser.ENDMARK,""); + Token em = new ClassicToken(PythonPartialParser.ENDMARKER,""); em.setCharPositionInLine(t.getCharPositionInLine()); em.setLine(t.getLine()); tokens.addElement(em); @@ -123,7 +123,7 @@ int cpos = t.getCharPositionInLine(); // column dictates indent/dedent if ( t.getType()==Token.EOF ) { atEnd = true; - Token em = new ClassicToken(PythonPartialParser.ENDMARK,""); + Token em = new ClassicToken(PythonPartialParser.ENDMARKER,""); em.setCharPositionInLine(t.getCharPositionInLine()); em.setLine(t.getLine()); tokens.addElement(em); @@ -155,7 +155,7 @@ for (int d=sp-1; d>=prevIndex; d--) { Token tok; if (atEnd) { - tok = new ClassicToken(PythonPartialParser.ENDMARK,""); + tok = new ClassicToken(PythonPartialParser.ENDMARKER,""); } else { tok = new ClassicToken(PythonPartialParser.DEDENT,""); } Modified: branches/asm/src/org/python/antlr/PythonTokenSource.java =================================================================== --- branches/asm/src/org/python/antlr/PythonTokenSource.java 2008-07-03 13:44:52 UTC (rev 4844) +++ branches/asm/src/org/python/antlr/PythonTokenSource.java 2008-07-04 01:13:07 UTC (rev 4845) @@ -72,189 +72,189 @@ February 2004 */ public class PythonTokenSource implements TokenSource { - public static final int MAX_INDENTS = 100; - public static final int FIRST_CHAR_POSITION = 0; + public static final int MAX_INDENTS = 100; + public static final int FIRST_CHAR_POSITION = 0; - /** The stack of indent levels (column numbers) */ - int[] indentStack = new int[MAX_INDENTS]; - /** stack pointer */ - int sp=-1; // grow upwards + /** The stack of indent levels (column numbers) */ + int[] indentStack = new int[MAX_INDENTS]; + /** stack pointer */ + int sp=-1; // grow upwards - /** The queue of tokens */ - Vector tokens = new Vector(); + /** The queue of tokens */ + Vector tokens = new Vector(); - /** We pull real tokens from this lexer */ - CommonTokenStream stream; + /** We pull real tokens from this lexer */ + CommonTokenStream stream; - int lastTokenAddedIndex = -1; + int lastTokenAddedIndex = -1; - public PythonTokenSource(PythonLexer lexer) { - } + public PythonTokenSource(PythonLexer lexer) { + } - public PythonTokenSource(CommonTokenStream stream) { - this.stream = stream; - // "state" of indent level is FIRST_CHAR_POSITION - push(FIRST_CHAR_POSITION); - } + public PythonTokenSource(CommonTokenStream stream) { + this.stream = stream; + // "state" of indent level is FIRST_CHAR_POSITION + push(FIRST_CHAR_POSITION); + } - /** From http://www.python.org/doc/2.2.3/ref/indentation.html + /** From http://www.python.org/doc/2.2.3/ref/indentation.html - "Before the first line of the file is read, a single zero is - pushed on the stack; this will never be popped off again. The - numbers pushed on the stack will always be strictly increasing - from bottom to top. At the beginning of each logical line, the - line's indentation level is compared to the top of the - stack. If it is equal, nothing happens. If it is larger, it is - pushed on the stack, and one INDENT token is generated. If it - is smaller, it must be one of the numbers occurring on the - stack; all numbers on the stack that are larger are popped - off, and for each number popped off a DEDENT token is - generated. At the end of the file, a DEDENT token is generated - for each number remaining on the stack that is larger than - zero." + "Before the first line of the file is read, a single zero is + pushed on the stack; this will never be popped off again. The + numbers pushed on the stack will always be strictly increasing + from bottom to top. At the beginning of each logical line, the + line's indentation level is compared to the top of the + stack. If it is equal, nothing happens. If it is larger, it is + pushed on the stack, and one INDENT token is generated. If it + is smaller, it must be one of the numbers occurring on the + stack; all numbers on the stack that are larger are popped + off, and for each number popped off a DEDENT token is + generated. At the end of the file, a DEDENT token is generated + for each number remaining on the stack that is larger than + zero." - I use char position in line 0..n-1 instead. + I use char position in line 0..n-1 instead. - The DEDENTS possibly needed at EOF are gracefully handled by forcing - EOF to have char pos 0 even though with UNIX it's hard to get EOF - at a non left edge. - */ - public Token nextToken() { - // if something in queue, just remove and return it - if ( tokens.size()>0 ) { - Token t = (Token)tokens.firstElement(); - tokens.removeElementAt(0); - // System.out.println(t); - return t; - } + The DEDENTS possibly needed at EOF are gracefully handled by forcing + EOF to have char pos 0 even though with UNIX it's hard to get EOF + at a non left edge. + */ + public Token nextToken() { + // if something in queue, just remove and return it + if ( tokens.size()>0 ) { + Token t = (Token)tokens.firstElement(); + tokens.removeElementAt(0); + // System.out.println(t); + return t; + } - insertImaginaryIndentDedentTokens(); + insertImaginaryIndentDedentTokens(); - return nextToken(); - } + return nextToken(); + } - protected void insertImaginaryIndentDedentTokens() - { - Token t = stream.LT(1); - stream.consume(); + protected void insertImaginaryIndentDedentTokens() + { + Token t = stream.LT(1); + stream.consume(); - // if not a NEWLINE, doesn't signal indent/dedent work; just enqueue - if ( t.getType()!=PythonLexer.NEWLINE ) { - List hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); - if ( hiddenTokens!=null ) { - tokens.addAll(hiddenTokens); - } - lastTokenAddedIndex = t.getTokenIndex(); - tokens.addElement(t); - return; - } + // if not a NEWLINE, doesn't signal indent/dedent work; just enqueue + if ( t.getType()!=PythonLexer.NEWLINE ) { + List hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); + if ( hiddenTokens!=null ) { + tokens.addAll(hiddenTokens); + } + lastTokenAddedIndex = t.getTokenIndex(); + tokens.addElement(t); + return; + } - // save NEWLINE in the queue - //System.out.println("found newline: "+t+" stack is "+stackString()); + // save NEWLINE in the queue + //System.out.println("found newline: "+t+" stack is "+stackString()); CommonToken newline = (CommonToken)t; - List hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); - if ( hiddenTokens!=null ) { - tokens.addAll(hiddenTokens); - } - lastTokenAddedIndex = t.getTokenIndex(); - tokens.addElement(t); + List hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); + if ( hiddenTokens!=null ) { + tokens.addAll(hiddenTokens); + } + lastTokenAddedIndex = t.getTokenIndex(); + tokens.addElement(t); - // grab first token of next line - t = stream.LT(1); - stream.consume(); + // grab first token of next line + t = stream.LT(1); + stream.consume(); - hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); - if ( hiddenTokens!=null ) { - tokens.addAll(hiddenTokens); - } - lastTokenAddedIndex = t.getTokenIndex(); + hiddenTokens = stream.getTokens(lastTokenAddedIndex+1,t.getTokenIndex()-1); + if ( hiddenTokens!=null ) { + tokens.addAll(hiddenTokens); + } + lastTokenAddedIndex = t.getTokenIndex(); - // compute cpos as the char pos of next non-WS token in line - int cpos = t.getCharPositionInLine(); // column dictates indent/dedent - if ( t.getType()==Token.EOF ) { - cpos = -1; // pretend EOF always happens at left edge - } - else if ( t.getType()==PythonLexer.LEADING_WS ) { - cpos = t.getText().length(); - } + // compute cpos as the char pos of next non-WS token in line + int cpos = t.getCharPositionInLine(); // column dictates indent/dedent + if ( t.getType()==Token.EOF ) { + cpos = -1; // pretend EOF always happens at left edge + } + else if ( t.getType()==PythonLexer.LEADING_WS ) { + cpos = t.getText().length(); + } - //System.out.println("next token is: "+t); + //System.out.println("next token is: "+t); - // compare to last indent level - int lastIndent = peek(); - //System.out.println("cpos, lastIndent = "+cpos+", "+lastIndent); - if ( cpos > lastIndent ) { // they indented; track and gen INDENT - push(cpos); - //System.out.println("push("+cpos+"): "+stackString()); - Token indent = new ClassicToken(PythonParser.INDENT,""); - indent.setCharPositionInLine(t.getCharPositionInLine()); - indent.setLine(t.getLine()); - tokens.addElement(indent); - } - else if ( cpos < lastIndent ) { // they dedented - // how far back did we dedent? - int prevIndex = findPreviousIndent(cpos); - //System.out.println("dedented; prevIndex of cpos="+cpos+" is "+prevIndex); - // generate DEDENTs for each indent level we backed up over - for (int d=sp-1; d>=prevIndex; d--) { - ImaginaryToken dedent = new ImaginaryToken(PythonParser.DEDENT,""); - dedent.setCharPositionInLine(t.getCharPositionInLine()); - dedent.setLine(t.getLine()); + // compare to last indent level + int lastIndent = peek(); + //System.out.println("cpos, lastIndent = "+cpos+", "+lastIndent); + if ( cpos > lastIndent ) { // they indented; track and gen INDENT + push(cpos); + //System.out.println("push("+cpos+"): "+stackString()); + Token indent = new ClassicToken(PythonParser.INDENT,""); + indent.setCharPositionInLine(t.getCharPositionInLine()); + indent.setLine(t.getLine()); + tokens.addElement(indent); + } + else if ( cpos < lastIndent ) { // they dedented + // how far back did we dedent? + int prevIndex = findPreviousIndent(cpos); + //System.out.println("dedented; prevIndex of cpos="+cpos+" is "+prevIndex); + // generate DEDENTs for each indent level we backed up over + for (int d=sp-1; d>=prevIndex; d--) { + ImaginaryToken dedent = new ImaginaryToken(PythonParser.DEDENT,""); + dedent.setCharPositionInLine(t.getCharPositionInLine()); + dedent.setLine(t.getLine()); //XXX: this will get messed up by comments. dedent.setStartIndex(newline.getStartIndex()); dedent.setStopIndex(newline.getStopIndex()); - tokens.addElement(dedent); - } - sp = prevIndex; // pop those off indent level - } - if ( t.getType()!=PythonLexer.LEADING_WS ) { // discard WS - tokens.addElement(t); - } - } + tokens.addElement(dedent); + } + sp = prevIndex; // pop those off indent level + } + if ( t.getType()!=PythonLexer.LEADING_WS ) { // discard WS + tokens.addElement(t); + } + } - // T O K E N S T A C K M E T H O D S + // T O K E N S T A C K M E T H O D S - protected void push(int i) { - if (sp>=MAX_INDENTS) { - throw new IllegalStateException("stack overflow"); - } - sp++; - indentStack[sp] = i; - } + protected void push(int i) { + if (sp>=MAX_INDENTS) { + throw new IllegalStateException("stack overflow"); + } + sp++; + indentStack[sp] = i; + } - protected int pop() { - if (sp<0) { - throw new IllegalStateException("stack underflow"); - } - int top = indentStack[sp]; - sp--; - return top; - } + protected int pop() { + if (sp<0) { + throw new IllegalStateException("stack underflow"); + } + int top = indentStack[sp]; + sp--; + return top; + } - protected int peek() { - return indentStack[sp]; - } + protected int peek() { + return indentStack[sp]; + } - /** Return the index on stack of previous indent level == i else -1 */ - protected int findPreviousIndent(int i) { - for (int j=sp-1; j>=0; j--) { - if ( indentStack[j]==i ) { - return j; - } - } - return FIRST_CHAR_POSITION; - } + /** Return the index on stack of previous indent level == i else -1 */ + protected int findPreviousIndent(int i) { + for (int j=sp-1; j>=0; j--) { + if ( indentStack[j]==i ) { + return j; + } + } + return FIRST_CHAR_POSITION; + } - public String stackString() { - StringBuffer buf = new StringBuffer(); - for (int j=sp; j>=0; j--) { - buf.append(" "); - buf.append(indentStack[j]); - } - return buf.toString(); - } + public String stackString() { + StringBuffer buf = new StringBuffer(); + for (int j=sp; j>=0; j--) { + buf.append(" "); + buf.append(indentStack[j]); + } + return buf.toString(); + } //FIXME: needed this for the Antlr 3.1b interface change. public String getSourceName() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <th...@us...> - 2008-07-03 13:44:59
|
Revision: 4844 http://jython.svn.sourceforge.net/jython/?rev=4844&view=rev Author: thobes Date: 2008-07-03 06:44:52 -0700 (Thu, 03 Jul 2008) Log Message: ----------- Changed the advanced branch to be a branch from the asm branch instead. Committing the changed base before further changes. Modified Paths: -------------- branches/advanced/.classpath branches/advanced/build.xml branches/advanced/compiler/org/python/bytecode/ReferenceResolver.java branches/advanced/compiler/org/python/compiler/advanced/AbstractEnvironment.java branches/advanced/compiler/org/python/compiler/advanced/BytecodeBundle.java branches/advanced/compiler/org/python/compiler/advanced/BytecodeLoader.java branches/advanced/compiler/org/python/compiler/advanced/ClassEnvironment.java branches/advanced/compiler/org/python/compiler/advanced/CodeInfo.java branches/advanced/compiler/org/python/compiler/advanced/CompilerFlag.java branches/advanced/compiler/org/python/compiler/advanced/CompilerPolicy.java branches/advanced/compiler/org/python/compiler/advanced/CompilerVariable.java branches/advanced/compiler/org/python/compiler/advanced/Environment.java branches/advanced/compiler/org/python/compiler/advanced/EnvironmentError.java branches/advanced/compiler/org/python/compiler/advanced/EnvironmentHolder.java branches/advanced/compiler/org/python/compiler/advanced/EnvironmentInfo.java branches/advanced/compiler/org/python/compiler/advanced/FunctionEnvironment.java branches/advanced/compiler/org/python/compiler/advanced/Future.java branches/advanced/compiler/org/python/compiler/advanced/GlobalEnvironment.java branches/advanced/compiler/org/python/compiler/advanced/ScopeInfo.java branches/advanced/compiler/org/python/compiler/advanced/YieldPoint.java branches/advanced/compiler/org/python/compiler/advanced/ast/AstToBytecode.java branches/advanced/compiler/org/python/compiler/advanced/ast/ContextBuilder.java branches/advanced/compiler/org/python/compiler/advanced/bytecode/BytecodeCompiler.java branches/advanced/compiler/org/python/compiler/advanced/bytecode/PythonBytecodeCompilingBundle.java Added Paths: ----------- branches/advanced/ branches/advanced/BRANCH.txt branches/advanced/agent/ branches/advanced/agent/org/ branches/advanced/agent/org/python/ branches/advanced/agent/org/python/javaagent/ branches/advanced/agent/org/python/javaagent/DeferringAgent.java branches/advanced/compiler/ branches/advanced/compiler/org/python/compiler/advanced/ branches/advanced/compiler/org/python/javaagent/ branches/advanced/compiler/org/python/javaagent/InstrumentationProxy.java branches/advanced/continuations/ branches/advanced/continuations/org/ branches/advanced/continuations/org/python/ branches/advanced/continuations/org/python/continuations/ branches/advanced/continuations/org/python/continuations/Continuation.java branches/advanced/interpreter/ branches/advanced/interpreter/org/ branches/advanced/interpreter/org/python/ branches/advanced/interpreter/org/python/interpreter/ branches/advanced/interpreter/org/python/interpreter/BytecodeInterpreter.java Removed Paths: ------------- branches/advanced/ branches/advanced/agent/org/ branches/advanced/agent/org/python/ branches/advanced/agent/org/python/javaagent/ branches/advanced/agent/org/python/javaagent/DeferringAgent.java branches/advanced/compiler/org/python/compiler/iface/ branches/advanced/compiler/org/python/newcompiler/ branches/advanced/continuations/org/ branches/advanced/continuations/org/python/ branches/advanced/continuations/org/python/continuations/ branches/advanced/continuations/org/python/continuations/Continuation.java branches/advanced/interpreter/org/ branches/advanced/interpreter/org/python/ branches/advanced/interpreter/org/python/interpreter/ branches/advanced/interpreter/org/python/interpreter/BytecodeInterpreter.java Copied: branches/advanced (from rev 4843, branches/asm) Modified: branches/advanced/.classpath =================================================================== --- branches/asm/.classpath 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/.classpath 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,10 +1,14 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="lib" path="build/exposed"/> - <classpathentry excluding="com/ziclix/python/sql/handler/InformixDataHandler.java|com/ziclix/python/sql/handler/OracleDataHandler.java" kind="src" output="build/classes" path="src"/> + <classpathentry excluding="com/ziclix/python/sql/handler/InformixDataHandler.java|com/ziclix/python/sql/handler/OracleDataHandler.java|org/python/compiler/TentativeCompiler.java" kind="src" output="build/classes" path="src"/> <classpathentry kind="src" output="build/classes" path="build/gensrc"/> <classpathentry kind="src" output="build/classes" path="tests/java"/> <classpathentry kind="src" path="bugtests/classes"/> + <classpathentry kind="src" path="agent"/> + <classpathentry kind="src" path="compiler"/> + <classpathentry kind="src" path="continuations"/> + <classpathentry kind="src" path="interpreter"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/3"/> <classpathentry kind="lib" path="extlibs/jline-0.9.94.jar"/> @@ -14,7 +18,7 @@ <classpathentry kind="lib" path="extlibs/postgresql-8.3-603.jdbc4.jar"/> <classpathentry kind="lib" path="extlibs/servlet-api-2.5.jar"/> <classpathentry kind="lib" path="build/jarjar"/> - <classpathentry kind="var" path="ANT_HOME/lib/ant.jar"/> - <classpathentry kind="lib" path="extlibs/antlr-runtime-3.1b1.jar"/> + <classpathentry kind="var" path="Ant"/> + <classpathentry kind="lib" path="extlibs/antlr-3.1b1.jar"/> <classpathentry kind="output" path="bugtests/classes"/> </classpath> Added: branches/advanced/BRANCH.txt =================================================================== --- branches/advanced/BRANCH.txt (rev 0) +++ branches/advanced/BRANCH.txt 2008-07-03 13:44:52 UTC (rev 4844) @@ -0,0 +1,5 @@ +Advanced Compiler Branch +======================== + +The advanced compiler is a project that strives to add an optimizing, advanced +compiler to Jython. \ No newline at end of file Copied: branches/advanced/agent (from rev 4843, branches/advanced/agent) Copied: branches/advanced/agent/org (from rev 4843, branches/advanced/agent/org) Copied: branches/advanced/agent/org/python (from rev 4843, branches/advanced/agent/org/python) Copied: branches/advanced/agent/org/python/javaagent (from rev 4843, branches/advanced/agent/org/python/javaagent) Deleted: branches/advanced/agent/org/python/javaagent/DeferringAgent.java =================================================================== --- branches/advanced/agent/org/python/javaagent/DeferringAgent.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/agent/org/python/javaagent/DeferringAgent.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,65 +0,0 @@ -package org.python.javaagent; - -import java.lang.instrument.Instrumentation; - -/** - * A foreign agent that provides access to the Bytecode instrumentation library. - * - * @author Tobias Ivarsson - */ -public class DeferringAgent { - - private final Instrumentation instrumentation; - - private static DeferringAgent agent = null; - - private DeferringAgent(Instrumentation inst) { - this.instrumentation = inst; - } - - /** - * Get the instrumentation this agent received upon attachment, or try to attach the agent by - * invoking the provided attacher. - * - * @param attacher - * A task that gets executed to attach the agent if it has not already been attached. - * @return The instrumentation associated with this agent. - */ - public static Instrumentation getInstrumentation(Runnable attacher) { - if (agent == null) { - attacher.run(); - if (agent == null) { - synchronized (DeferringAgent.class) { - if (agent == null) { - agent = new DeferringAgent(null); - } - } - } - } - return agent.instrumentation; - } - - /** - * Attach the agent upon start of the JVM. - * - * @param agentArgs - * Arguments are ignored. - * @param inst - * The instrumentation that will be associated with this agent. - */ - public static void premain(String agentArgs, Instrumentation inst) { - agentmain(agentArgs, inst); - } - - /** - * Attach the agent upon remote arrival to the JVM. - * - * @param agentArgs - * Arguments are ignored. - * @param inst - * The instrumentation that will be associated with this agent. - */ - public static void agentmain(String agentArgs, Instrumentation inst) { - agent = new DeferringAgent(inst); - } -} Copied: branches/advanced/agent/org/python/javaagent/DeferringAgent.java (from rev 4843, branches/advanced/agent/org/python/javaagent/DeferringAgent.java) =================================================================== --- branches/advanced/agent/org/python/javaagent/DeferringAgent.java (rev 0) +++ branches/advanced/agent/org/python/javaagent/DeferringAgent.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -0,0 +1,68 @@ +package org.python.javaagent; + +import java.lang.instrument.Instrumentation; + +/** + * A foreign agent that provides access to the byte code instrumentation + * library. + * + * @see org.python.javaagent.InstrumentationProxy + * + * @author Tobias Ivarsson + */ +public class DeferringAgent { + + private final Instrumentation instrumentation; + + private static volatile DeferringAgent agent = null; + + private DeferringAgent(Instrumentation inst) { + this.instrumentation = inst; + } + + /** + * Get the instrumentation this agent received upon attachment, or try to + * attach the agent by invoking the provided attacher. + * + * @param attacher A task that gets executed to attach the agent if it has + * not already been attached. + * @return The instrumentation associated with this agent. + */ + public static Instrumentation getInstrumentation(Runnable attacher) { + DeferringAgent agent = DeferringAgent.agent; + if (agent == null) { + attacher.run(); + agent = DeferringAgent.agent; + if (agent == null) { + synchronized (DeferringAgent.class) { + agent = DeferringAgent.agent; + if (agent == null) { + agent = new DeferringAgent(null); + DeferringAgent.agent = agent; + } + } + } + } + return agent.instrumentation; + } + + /** + * Attach the agent upon start of the JVM. + * + * @param agentArgs Arguments are ignored. + * @param inst The instrumentation that will be associated with this agent. + */ + public static void premain(String agentArgs, Instrumentation inst) { + agentmain(agentArgs, inst); + } + + /** + * Attach the agent upon remote arrival to the JVM. + * + * @param agentArgs Arguments are ignored. + * @param inst The instrumentation that will be associated with this agent. + */ + public static void agentmain(String agentArgs, Instrumentation inst) { + agent = new DeferringAgent(inst); + } +} Modified: branches/advanced/build.xml =================================================================== --- branches/asm/build.xml 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/build.xml 2008-07-03 13:44:52 UTC (rev 4844) @@ -139,6 +139,10 @@ <property name="jython.base.dir" value="${work.dir}" /> <property name="source.dir" value="${jython.base.dir}/src" /> + <property name="agent.source.dir" value="${jython.base.dir}/agent" /> + <property name="compiler.source.dir" value="${jython.base.dir}/compiler" /> + <property name="continuations.source.dir" value="${jython.base.dir}/continuations" /> + <property name="interpreter.source.dir" value="${jython.base.dir}/interpreter" /> <property name="test.source.dir" value="${jython.base.dir}/tests/java" /> <property name="test.shell.dir" value="${jython.base.dir}/tests/shell" /> <property name="templates.dir" value="${source.dir}/templates" /> @@ -154,6 +158,7 @@ <property name="dist.dir" value="${work.dir}/dist" /> <property name="apidoc.dir" value="${dist.dir}/Doc/javadoc" /> <property name="parser.dir" value="${source.dir}/org/python/parser" /> + <property name="agent.class" value="org.python.javaagent.DeferringAgent"/> <!-- classpaths --> <path id="main.classpath"> @@ -464,6 +469,10 @@ nowarn="${nowarn}"> <src path="${source.dir}"/> <src path="${gensrc.dir}"/> + <src path="${agent.source.dir}"/> + <src path="${compiler.source.dir}"/> + <src path="${continuations.source.dir}"/> + <src path="${interpreter.source.dir}"/> <exclude name="org/python/parser/python.java" /> <exclude name="**/handler/InformixDataHandler.java" unless="informix.present" /> @@ -534,6 +543,25 @@ </unjar> </target> + <target name="agent" depends="compile"> + <jar destfile="${dist.dir}/agent.jar" update="true"> + <fileset dir="${build.dir}"> + <include name="org/python/javaagent/**"/> + </fileset> + <manifest> + <!-- Instrumentation agent, for a more dynamic newcompiler --> + <attribute name="Premain-Class" value="${agent.class}"/> + <attribute name="Can-Redefine-Classes" value="true"/> + <!-- Java 6 stuff - more powerful agents --> + <!-- All code is still Java 5 safe though, + these are just further manifest declarations understood by Java 6, + and ignored by previous JVMs. --> + <attribute name="Agent-Class" value="${agent.class}"/> + <attribute name="Can-Retransform-Classes" value="true"/> + </manifest> + </jar> + </target> + <target name="jar" depends="compile,expose,jarjar"> <jar destfile="${dist.dir}/jython.jar"> <fileset dir="${compile.dir}"/> Copied: branches/advanced/compiler (from rev 4843, branches/advanced/compiler) Modified: branches/advanced/compiler/org/python/bytecode/ReferenceResolver.java =================================================================== --- branches/advanced/compiler/org/python/bytecode/ReferenceResolver.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/bytecode/ReferenceResolver.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -9,8 +9,8 @@ import java.util.TreeMap; import org.python.core.PyObject; -import org.python.newcompiler.YieldPoint; -import org.python.newcompiler.bytecode.BytecodeCompiler; +import org.python.compiler.advanced.YieldPoint; +import org.python.compiler.advanced.bytecode.BytecodeCompiler; /** * Copied: branches/advanced/compiler/org/python/compiler/advanced (from rev 4843, branches/advanced/compiler/org/python/newcompiler) Modified: branches/advanced/compiler/org/python/compiler/advanced/AbstractEnvironment.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/AbstractEnvironment.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/AbstractEnvironment.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; import java.util.Collections; import java.util.EnumSet; @@ -9,7 +9,7 @@ import org.python.bytecode.Label; import org.python.bytecode.VariableContext; -import org.python.newcompiler.EnvironmentError.EnvironmentProblem; +import org.python.compiler.advanced.EnvironmentError.EnvironmentProblem; abstract class AbstractEnvironment implements Environment, EnvironmentInfo, CodeInfo, ScopeInfo { Modified: branches/advanced/compiler/org/python/compiler/advanced/BytecodeBundle.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/BytecodeBundle.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/BytecodeBundle.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; import java.io.File; Modified: branches/advanced/compiler/org/python/compiler/advanced/BytecodeLoader.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/BytecodeLoader.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/BytecodeLoader.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; public interface BytecodeLoader { Modified: branches/advanced/compiler/org/python/compiler/advanced/ClassEnvironment.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/ClassEnvironment.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/ClassEnvironment.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; public class ClassEnvironment extends AbstractEnvironment { Modified: branches/advanced/compiler/org/python/compiler/advanced/CodeInfo.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/CodeInfo.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/CodeInfo.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; public interface CodeInfo { Modified: branches/advanced/compiler/org/python/compiler/advanced/CompilerFlag.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/CompilerFlag.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/CompilerFlag.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; import java.util.Collection; import java.util.EnumSet; Modified: branches/advanced/compiler/org/python/compiler/advanced/CompilerPolicy.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/CompilerPolicy.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/CompilerPolicy.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; import java.util.Set; Modified: branches/advanced/compiler/org/python/compiler/advanced/CompilerVariable.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/CompilerVariable.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/CompilerVariable.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,3 +1,3 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; public class CompilerVariable {} Modified: branches/advanced/compiler/org/python/compiler/advanced/Environment.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/Environment.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/Environment.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; import java.util.Set; Modified: branches/advanced/compiler/org/python/compiler/advanced/EnvironmentError.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/EnvironmentError.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/EnvironmentError.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; /** * TODO: Add code for failing and producing error messages, warnings and so on. Modified: branches/advanced/compiler/org/python/compiler/advanced/EnvironmentHolder.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/EnvironmentHolder.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/EnvironmentHolder.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; import org.python.antlr.PythonTree; import org.python.antlr.ast.exprType; Modified: branches/advanced/compiler/org/python/compiler/advanced/EnvironmentInfo.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/EnvironmentInfo.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/EnvironmentInfo.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; import java.util.Set; Modified: branches/advanced/compiler/org/python/compiler/advanced/FunctionEnvironment.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/FunctionEnvironment.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/FunctionEnvironment.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; import java.util.ArrayList; import java.util.Collections; Modified: branches/advanced/compiler/org/python/compiler/advanced/Future.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/Future.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/Future.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,8 +1,8 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; import java.util.Set; -import org.python.parser.ParseException; +import org.python.antlr.ParseException; /** * An enumeration of the future features. Modified: branches/advanced/compiler/org/python/compiler/advanced/GlobalEnvironment.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/GlobalEnvironment.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/GlobalEnvironment.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; public class GlobalEnvironment extends AbstractEnvironment { Modified: branches/advanced/compiler/org/python/compiler/advanced/ScopeInfo.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/ScopeInfo.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/ScopeInfo.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; public interface ScopeInfo { Modified: branches/advanced/compiler/org/python/compiler/advanced/YieldPoint.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/YieldPoint.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/YieldPoint.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler; +package org.python.compiler.advanced; import org.python.bytecode.BytecodeVisitor; import org.python.bytecode.Instruction; Modified: branches/advanced/compiler/org/python/compiler/advanced/ast/AstToBytecode.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/ast/AstToBytecode.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/ast/AstToBytecode.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler.ast; +package org.python.compiler.advanced.ast; import java.util.Stack; @@ -72,22 +72,22 @@ import org.python.bytecode.SliceMode; import org.python.bytecode.UnaryOperator; import org.python.bytecode.VariableContext; -import org.python.newcompiler.BytecodeBundle; -import org.python.newcompiler.CodeInfo; -import org.python.newcompiler.CompilerFlag; -import org.python.newcompiler.CompilerVariable; -import org.python.newcompiler.EnvironmentHolder; -import org.python.newcompiler.EnvironmentInfo; -import org.python.newcompiler.YieldPoint; -import org.python.newcompiler.bytecode.BytecodeCompiler; -import org.python.newcompiler.bytecode.PythonBytecodeCompilingBundle; +import org.python.compiler.advanced.BytecodeBundle; +import org.python.compiler.advanced.CodeInfo; +import org.python.compiler.advanced.CompilerFlag; +import org.python.compiler.advanced.CompilerVariable; +import org.python.compiler.advanced.EnvironmentHolder; +import org.python.compiler.advanced.EnvironmentInfo; +import org.python.compiler.advanced.YieldPoint; +import org.python.compiler.advanced.bytecode.BytecodeCompiler; +import org.python.compiler.advanced.bytecode.PythonBytecodeCompilingBundle; import org.python.core.Py; import org.python.core.PyInteger; import org.python.core.PyLong; import org.python.core.PyObject; import org.python.core.PyString; import org.python.core.PyUnicode; -import org.python.newcompiler.CompilerPolicy; +import org.python.compiler.advanced.CompilerPolicy; /** * An AST visitor that feeds a Bytecode visitor. @@ -970,7 +970,15 @@ } public BytecodeBundle visitStr(Str node) throws Exception { - compiler.visitLoadConstant(new PyString(node.s)); + PyString string; + if (node.s instanceof PyString) { + string = (PyString)node.s; + } else if (node.s instanceof String) { + string = new PyString((String)node.s); + } else { + string = new PyString(node.s.toString()); + } + compiler.visitLoadConstant(string); return bundle; } @@ -1115,7 +1123,17 @@ } public BytecodeBundle visitUnicode(Unicode node) throws Exception { - compiler.visitLoadConstant(new PyUnicode(node.s)); + PyUnicode string; + if (node.s instanceof PyUnicode) { + string = (PyUnicode)node.s; + } else if (node.s instanceof PyString) { + string = ((PyString)node.s).__unicode__(); + } else if (node.s instanceof String) { + string = new PyUnicode((String)node.s); + } else { + string = new PyUnicode(node.s.toString()); + } + compiler.visitLoadConstant(string); return bundle; } Modified: branches/advanced/compiler/org/python/compiler/advanced/ast/ContextBuilder.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/ast/ContextBuilder.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/ast/ContextBuilder.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,4 +1,4 @@ -package org.python.newcompiler.ast; +package org.python.compiler.advanced.ast; import java.util.HashMap; import java.util.LinkedHashMap; @@ -25,16 +25,16 @@ import org.python.antlr.ast.exprType; import org.python.antlr.ast.stmtType; import org.python.bytecode.Label; -import org.python.newcompiler.ClassEnvironment; -import org.python.newcompiler.Environment; -import org.python.newcompiler.EnvironmentHolder; -import org.python.newcompiler.EnvironmentInfo; -import org.python.newcompiler.FunctionEnvironment; -import org.python.newcompiler.Future; -import org.python.newcompiler.GlobalEnvironment; -import org.python.newcompiler.YieldPoint; -import org.python.newcompiler.CompilerPolicy; -import org.python.parser.ParseException; +import org.python.compiler.advanced.ClassEnvironment; +import org.python.compiler.advanced.Environment; +import org.python.compiler.advanced.EnvironmentHolder; +import org.python.compiler.advanced.EnvironmentInfo; +import org.python.compiler.advanced.FunctionEnvironment; +import org.python.compiler.advanced.Future; +import org.python.compiler.advanced.GlobalEnvironment; +import org.python.compiler.advanced.YieldPoint; +import org.python.compiler.advanced.CompilerPolicy; +import org.python.antlr.ParseException; public class ContextBuilder extends VisitorBase<EnvironmentHolder> implements EnvironmentHolder { Modified: branches/advanced/compiler/org/python/compiler/advanced/bytecode/BytecodeCompiler.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/bytecode/BytecodeCompiler.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/bytecode/BytecodeCompiler.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,11 +1,11 @@ -package org.python.newcompiler.bytecode; +package org.python.compiler.advanced.bytecode; import java.util.Set; import org.python.bytecode.BytecodeVisitor; import org.python.bytecode.Label; -import org.python.newcompiler.CompilerFlag; -import org.python.newcompiler.CompilerVariable; +import org.python.compiler.advanced.CompilerFlag; +import org.python.compiler.advanced.CompilerVariable; public interface BytecodeCompiler extends BytecodeVisitor { Modified: branches/advanced/compiler/org/python/compiler/advanced/bytecode/PythonBytecodeCompilingBundle.java =================================================================== --- branches/advanced/compiler/org/python/newcompiler/bytecode/PythonBytecodeCompilingBundle.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/compiler/org/python/compiler/advanced/bytecode/PythonBytecodeCompilingBundle.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,10 +1,10 @@ -package org.python.newcompiler.bytecode; +package org.python.compiler.advanced.bytecode; import java.util.Set; -import org.python.newcompiler.BytecodeBundle; -import org.python.newcompiler.CodeInfo; -import org.python.newcompiler.CompilerFlag; +import org.python.compiler.advanced.BytecodeBundle; +import org.python.compiler.advanced.CodeInfo; +import org.python.compiler.advanced.CompilerFlag; public interface PythonBytecodeCompilingBundle extends BytecodeBundle { Added: branches/advanced/compiler/org/python/javaagent/InstrumentationProxy.java =================================================================== --- branches/advanced/compiler/org/python/javaagent/InstrumentationProxy.java (rev 0) +++ branches/advanced/compiler/org/python/javaagent/InstrumentationProxy.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -0,0 +1,54 @@ +package org.python.javaagent; + +import java.lang.instrument.Instrumentation; +import java.lang.reflect.Method; + +/** + * @see org.python.javaagent.DeferringAgent + * + * @author Tobias Ivarsson + */ +public final class InstrumentationProxy { + + private static volatile InstrumentationProxy proxy; + private final Instrumentation instrumentation; + private static final Runnable attacher = new Runnable() { + @Override + public void run() { + // TODO: add means to attach an agent to this, already running, JVM + } + }; + + private InstrumentationProxy() { + Instrumentation value; + try { + Class<?> agentClass = Class.forName("org.python.javaagent.DeferringAgent"); + Method getMethod = agentClass.getMethod("getInstrumentation", + Runnable.class); + value = (Instrumentation) getMethod.invoke(null, attacher); + } catch (Exception e) { + value = null; + } + instrumentation = value; + } + + /** + * Retrieve an {@link Instrumentation} instance for the current JVM. + * + * @return The instrumentation associated with this agent. + */ + public static Instrumentation getInstrumentation() { + InstrumentationProxy instance = proxy; + if (instance == null) { + synchronized (InstrumentationProxy.class) { + instance = proxy; + if (instance == null) { + instance = new InstrumentationProxy(); + proxy = instance; + } + } + } + return instance.instrumentation; + } + +} Copied: branches/advanced/continuations (from rev 4843, branches/advanced/continuations) Copied: branches/advanced/continuations/org (from rev 4843, branches/advanced/continuations/org) Copied: branches/advanced/continuations/org/python (from rev 4843, branches/advanced/continuations/org/python) Copied: branches/advanced/continuations/org/python/continuations (from rev 4843, branches/advanced/continuations/org/python/continuations) Deleted: branches/advanced/continuations/org/python/continuations/Continuation.java =================================================================== --- branches/advanced/continuations/org/python/continuations/Continuation.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/continuations/org/python/continuations/Continuation.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,39 +0,0 @@ -package org.python.continuations; - -public abstract class Continuation { - - private Continuation() { - } - - private static class Break extends Throwable { - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } - } - - private static final Break stop = new Break(); - - public static Object dispatch(Continuation current) { - while (true) { - try { - current = current.succeed(); - } catch (Break stop) { - return current.value; - } catch (Throwable tr) { - current = current.fail(tr); - } - } - } - - private Object value; - - private Continuation fail(Throwable tr) { - return null; - } - - private Continuation succeed() throws Throwable { - return null; - } -} Copied: branches/advanced/continuations/org/python/continuations/Continuation.java (from rev 4843, branches/advanced/continuations/org/python/continuations/Continuation.java) =================================================================== --- branches/advanced/continuations/org/python/continuations/Continuation.java (rev 0) +++ branches/advanced/continuations/org/python/continuations/Continuation.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -0,0 +1,39 @@ +package org.python.continuations; + +public abstract class Continuation { + + private Continuation() { + } + + private static class Break extends Throwable { + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + } + + private static final Break stop = new Break(); + + public static Object dispatch(Continuation current) { + while (true) { + try { + current = current.succeed(); + } catch (Break stop) { + return current.value; + } catch (Throwable tr) { + current = current.fail(tr); + } + } + } + + private Object value; + + private Continuation fail(Throwable tr) { + return null; + } + + private Continuation succeed() throws Throwable { + return null; + } +} Copied: branches/advanced/interpreter (from rev 4843, branches/advanced/interpreter) Copied: branches/advanced/interpreter/org (from rev 4843, branches/advanced/interpreter/org) Copied: branches/advanced/interpreter/org/python (from rev 4843, branches/advanced/interpreter/org/python) Copied: branches/advanced/interpreter/org/python/interpreter (from rev 4843, branches/advanced/interpreter/org/python/interpreter) Deleted: branches/advanced/interpreter/org/python/interpreter/BytecodeInterpreter.java =================================================================== --- branches/advanced/interpreter/org/python/interpreter/BytecodeInterpreter.java 2008-07-03 02:39:07 UTC (rev 4843) +++ branches/advanced/interpreter/org/python/interpreter/BytecodeInterpreter.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -1,104 +0,0 @@ -package org.python.interpreter; - -import org.python.bytecode.BytecodeVersion; -import org.python.bytecode.Instruction; -import org.python.bytecode.RawBytecodeVisitor; -import org.python.bytecode.VariableContext; - - -public class BytecodeInterpreter implements RawBytecodeVisitor { - - private final BytecodeVersion version; - - public BytecodeInterpreter(BytecodeVersion version) { - this.version = version; - } - - public void visitAbsouteJump(int addr) { - // TODO Auto-generated method stub - } - - public void visitContinue(int addr) { - // TODO Auto-generated method stub - } - - public void visitDelete(VariableContext context, int nameIndex) { - // TODO Auto-generated method stub - } - - public void visitDeleteAttribute(int nameIndex) { - // TODO Auto-generated method stub - } - - public void visitForIteration(int delta) { - // TODO Auto-generated method stub - } - - public void visitImportFrom(int nameIndex) { - // TODO Auto-generated method stub - } - - public void visitImportName(int nameIndex) { - // TODO Auto-generated method stub - } - - public void visitInstruction(Instruction instruction) { - // TODO Auto-generated method stub - } - - public void visitJumpIfFalse(int delta) { - // TODO Auto-generated method stub - } - - public void visitJumpIfTrue(int delta) { - // TODO Auto-generated method stub - } - - public void visitLoad(VariableContext context, int nameIndex) { - // TODO Auto-generated method stub - } - - public void visitLoadAttribute(int nameIndex) { - // TODO Auto-generated method stub - } - - public void visitLoadClosure(int nameIndex) { - // TODO Auto-generated method stub - } - - public void visitLoadConstant(int constIndex) { - // TODO Auto-generated method stub - } - - public void visitRelativeJump(int delta) { - // TODO Auto-generated method stub - } - - public void visitSetupExcept(int delta) { - // TODO Auto-generated method stub - } - - public void visitSetupFinally(int delta) { - // TODO Auto-generated method stub - } - - public void visitSetupLoop(int delta) { - // TODO Auto-generated method stub - } - - public void visitStop(Instruction stop) { - // TODO Auto-generated method stub - } - - public void visitStore(VariableContext context, int nameIndex) { - // TODO Auto-generated method stub - } - - public void visitStoreAttribute(int nameIndex) { - // TODO Auto-generated method stub - } - - public void visitYield() { - // TODO Auto-generated method stub - } -} Copied: branches/advanced/interpreter/org/python/interpreter/BytecodeInterpreter.java (from rev 4843, branches/advanced/interpreter/org/python/interpreter/BytecodeInterpreter.java) =================================================================== --- branches/advanced/interpreter/org/python/interpreter/BytecodeInterpreter.java (rev 0) +++ branches/advanced/interpreter/org/python/interpreter/BytecodeInterpreter.java 2008-07-03 13:44:52 UTC (rev 4844) @@ -0,0 +1,104 @@ +package org.python.interpreter; + +import org.python.bytecode.BytecodeVersion; +import org.python.bytecode.Instruction; +import org.python.bytecode.RawBytecodeVisitor; +import org.python.bytecode.VariableContext; + + +public class BytecodeInterpreter implements RawBytecodeVisitor { + + private final BytecodeVersion version; + + public BytecodeInterpreter(BytecodeVersion version) { + this.version = version; + } + + public void visitAbsouteJump(int addr) { + // TODO Auto-generated method stub + } + + public void visitContinue(int addr) { + // TODO Auto-generated method stub + } + + public void visitDelete(VariableContext context, int nameIndex) { + // TODO Auto-generated method stub + } + + public void visitDeleteAttribute(int nameIndex) { + // TODO Auto-generated method stub + } + + public void visitForIteration(int delta) { + // TODO Auto-generated method stub + } + + public void visitImportFrom(int nameIndex) { + // TODO Auto-generated method stub + } + + public void visitImportName(int nameIndex) { + // TODO Auto-generated method stub + } + + public void visitInstruction(Instruction instruction) { + // TODO Auto-generated method stub + } + + public void visitJumpIfFalse(int delta) { + // TODO Auto-generated method stub + } + + public void visitJumpIfTrue(int delta) { + // TODO Auto-generated method stub + } + + public void visitLoad(VariableContext context, int nameIndex) { + // TODO Auto-generated method stub + } + + public void visitLoadAttribute(int nameIndex) { + // TODO Auto-generated method stub + } + + public void visitLoadClosure(int nameIndex) { + // TODO Auto-generated method stub + } + + public void visitLoadConstant(int constIndex) { + // TODO Auto-generated method stub + } + + public void visitRelativeJump(int delta) { + // TODO Auto-generated method stub + } + + public void visitSetupExcept(int delta) { + // TODO Auto-generated method stub + } + + public void visitSetupFinally(int delta) { + // TODO Auto-generated method stub + } + + public void visitSetupLoop(int delta) { + // TODO Auto-generated method stub + } + + public void visitStop(Instruction stop) { + // TODO Auto-generated method stub + } + + public void visitStore(VariableContext context, int nameIndex) { + // TODO Auto-generated method stub + } + + public void visitStoreAttribute(int nameIndex) { + // TODO Auto-generated method stub + } + + public void visitYield() { + // TODO Auto-generated method stub + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-07-03 02:39:09
|
Revision: 4843 http://jython.svn.sourceforge.net/jython/?rev=4843&view=rev Author: leosoto Date: 2008-07-02 19:39:07 -0700 (Wed, 02 Jul 2008) Log Message: ----------- Limiting the buffer size used for discovering the encoding, to avoid crashing when reading big files (such as django/tests/regressiontests/forms/fields.py), as the default size of BufferedReader was too close to the readlimit set by the mark() call Modified Paths: -------------- branches/asm/src/org/python/core/ParserFacade.java Modified: branches/asm/src/org/python/core/ParserFacade.java =================================================================== --- branches/asm/src/org/python/core/ParserFacade.java 2008-07-03 00:36:50 UTC (rev 4842) +++ branches/asm/src/org/python/core/ParserFacade.java 2008-07-03 02:39:07 UTC (rev 4843) @@ -206,7 +206,7 @@ private static String readEncoding(InputStream stream) throws IOException { stream.mark(10000); String encoding = null; - BufferedReader br = new BufferedReader(new InputStreamReader(stream)); + BufferedReader br = new BufferedReader(new InputStreamReader(stream), 512); for (int i = 0; i < 2; i++) { String strLine = br.readLine(); if (strLine == null) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-07-03 00:36:53
|
Revision: 4842 http://jython.svn.sourceforge.net/jython/?rev=4842&view=rev Author: leosoto Date: 2008-07-02 17:36:50 -0700 (Wed, 02 Jul 2008) Log Message: ----------- Enable utf-8 source encoding support (the test_cookielib issue was fixed upstream: http://bugs.python.org/issue3261). Also recognize 'latin-1' as an alias for 'iso8859-1' Modified Paths: -------------- branches/asm/src/org/python/core/ParserFacade.java Modified: branches/asm/src/org/python/core/ParserFacade.java =================================================================== --- branches/asm/src/org/python/core/ParserFacade.java 2008-07-02 21:43:16 UTC (rev 4841) +++ branches/asm/src/org/python/core/ParserFacade.java 2008-07-03 00:36:50 UTC (rev 4842) @@ -226,16 +226,9 @@ if (encoding == null) { return null; } - if (encoding.equals("Latin-1")) { + if (encoding.equals("Latin-1") || encoding.equals("latin-1")) { return "ISO8859_1"; } - //FIXME: I'm not at all sure why utf-8 is breaking test_cookielib.py - // but this fixes it on my machine. I'm hoping it is a Java - // default behavior, but I'm afraid it may be a Java on Mac - // default behavior. - if (encoding.equals("utf-8")) { - return null; - } return encoding; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-07-02 21:43:18
|
Revision: 4841 http://jython.svn.sourceforge.net/jython/?rev=4841&view=rev Author: leosoto Date: 2008-07-02 14:43:16 -0700 (Wed, 02 Jul 2008) Log Message: ----------- Fixing Derived#__cmp__ to avoid raise TypeError when __cmp__ has not been overrided and super.__cmp__() returns -2 (see #1031) Modified Paths: -------------- branches/asm/Lib/test/test_dict_jy.py branches/asm/src/org/python/core/PyArrayDerived.java branches/asm/src/org/python/core/PyBaseExceptionDerived.java branches/asm/src/org/python/core/PyBooleanDerived.java branches/asm/src/org/python/core/PyClassMethodDerived.java branches/asm/src/org/python/core/PyComplexDerived.java branches/asm/src/org/python/core/PyDictionaryDerived.java branches/asm/src/org/python/core/PyFileDerived.java branches/asm/src/org/python/core/PyFloatDerived.java branches/asm/src/org/python/core/PyFrozenSetDerived.java branches/asm/src/org/python/core/PyIntegerDerived.java branches/asm/src/org/python/core/PyListDerived.java branches/asm/src/org/python/core/PyLongDerived.java branches/asm/src/org/python/core/PyModuleDerived.java branches/asm/src/org/python/core/PyObjectDerived.java branches/asm/src/org/python/core/PyPropertyDerived.java branches/asm/src/org/python/core/PySetDerived.java branches/asm/src/org/python/core/PySliceDerived.java branches/asm/src/org/python/core/PyStringDerived.java branches/asm/src/org/python/core/PySuperDerived.java branches/asm/src/org/python/core/PyTupleDerived.java branches/asm/src/org/python/core/PyTypeDerived.java branches/asm/src/org/python/core/PyUnicodeDerived.java branches/asm/src/org/python/modules/_weakref/ReferenceTypeDerived.java branches/asm/src/org/python/modules/collections/PyDefaultDictDerived.java branches/asm/src/org/python/modules/collections/PyDequeDerived.java branches/asm/src/org/python/modules/random/PyRandomDerived.java branches/asm/src/org/python/modules/thread/PyLocalDerived.java branches/asm/src/org/python/modules/zipimport/zipimporterDerived.java branches/asm/src/templates/object.derived Modified: branches/asm/Lib/test/test_dict_jy.py =================================================================== --- branches/asm/Lib/test/test_dict_jy.py 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/Lib/test/test_dict_jy.py 2008-07-02 21:43:16 UTC (rev 4841) @@ -1,14 +1,14 @@ -import test_support +from test import test_support import unittest class DictInitTest(unittest.TestCase): def testInternalSetitemInInit(self): - '''Test for http://jython.org/bugs/1816134 + """Test for http://jython.org/bugs/1816134 CPython's dict uses an internal setitem method to initialize itself rather than the one on its subclasses, and this tests that Jython does as well. - ''' + """ class Subdict(dict): def __init__(self): super(Subdict, self).__init__([('a',1)]) @@ -23,6 +23,50 @@ s[7] = 'called' self.assertEquals('called', s.createdInInit) +class DictCmpTest(unittest.TestCase): + "Test for http://bugs.jython.org/issue1031" + def testDictCmp(self): + # 'Implicit' comparision of dicts against other types instances + # shouldn't raise exception: + self.assertNotEqual({}, '') + # The same, but explicitly calling __cmp__ should raise TypeError: + self.assertRaises(TypeError, {}.__cmp__, '') + def testDictDerivedCmp(self): + # With derived classes that doesn't override __cmp__, the behaviour + # should be the same that with dicts: + class derived_dict(dict): pass + self.assertNotEqual(derived_dict(), '') + self.assertRaises(TypeError, derived_dict().__cmp__, '') + # But, if they *override* __cmp__ and raise TypeError from there, we + # have exception raised when checking for equality... + class non_comparable_dict(dict): + def __cmp__(self, other): + raise TypeError, "I always raise TypeError" + self.assertRaises(TypeError, lambda: non_comparable_dict() == '') + self.assertRaises(TypeError, non_comparable_dict().__cmp__, '') + # ...unless you compare it with other dicts: + # self.assertEqual(non_comparable_dict(), {}) + + # The same happens even if the overridden __cmp__ doesn't nothing apart + # from calling super: + class dummy_dict_with_cmp(dict): + def __cmp__(self, other): + return super(dummy_dict_with_cmp, self).__cmp__(other) + + self.assertEqual(dummy_dict_with_cmp(), {}) + # But TypeError is raised when comparing against other types + self.assertRaises(TypeError, lambda: dummy_dict_with_cmp() == '') + self.assertRaises(TypeError, dummy_dict_with_cmp().__cmp__, '') + # Finally, the Python implementation shouldn't be tricked by not + # implementing __cmp__ on the actual type of the dict-derived instance, + # but implementing it on a superclass. + class derived_dict_with_custom_cmp(dict): + def __cmp__(self, other): + return 0 + class yet_another_dict(derived_dict_with_custom_cmp): pass + self.assertEqual(derived_dict_with_custom_cmp(), '') + self.assertEqual(yet_another_dict(), '') + class DerivedDictTest(unittest.TestCase): "Tests for derived dict behaviour" def test_raising_custom_key_error(self): @@ -35,7 +79,7 @@ def test_main(): - test_support.run_unittest(DictInitTest, DerivedDictTest) + test_support.run_unittest(DictInitTest, DictCmpTest, DerivedDictTest) if __name__ == '__main__': test_main() Modified: branches/asm/src/org/python/core/PyArrayDerived.java =================================================================== --- branches/asm/src/org/python/core/PyArrayDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyArrayDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyBaseExceptionDerived.java =================================================================== --- branches/asm/src/org/python/core/PyBaseExceptionDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyBaseExceptionDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -741,16 +741,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyBooleanDerived.java =================================================================== --- branches/asm/src/org/python/core/PyBooleanDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyBooleanDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyClassMethodDerived.java =================================================================== --- branches/asm/src/org/python/core/PyClassMethodDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyClassMethodDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyComplexDerived.java =================================================================== --- branches/asm/src/org/python/core/PyComplexDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyComplexDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyDictionaryDerived.java =================================================================== --- branches/asm/src/org/python/core/PyDictionaryDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyDictionaryDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyFileDerived.java =================================================================== --- branches/asm/src/org/python/core/PyFileDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyFileDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyFloatDerived.java =================================================================== --- branches/asm/src/org/python/core/PyFloatDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyFloatDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyFrozenSetDerived.java =================================================================== --- branches/asm/src/org/python/core/PyFrozenSetDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyFrozenSetDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyIntegerDerived.java =================================================================== --- branches/asm/src/org/python/core/PyIntegerDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyIntegerDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyListDerived.java =================================================================== --- branches/asm/src/org/python/core/PyListDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyListDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyLongDerived.java =================================================================== --- branches/asm/src/org/python/core/PyLongDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyLongDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyModuleDerived.java =================================================================== --- branches/asm/src/org/python/core/PyModuleDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyModuleDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -741,16 +741,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyObjectDerived.java =================================================================== --- branches/asm/src/org/python/core/PyObjectDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyObjectDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyPropertyDerived.java =================================================================== --- branches/asm/src/org/python/core/PyPropertyDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyPropertyDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PySetDerived.java =================================================================== --- branches/asm/src/org/python/core/PySetDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PySetDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PySliceDerived.java =================================================================== --- branches/asm/src/org/python/core/PySliceDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PySliceDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyStringDerived.java =================================================================== --- branches/asm/src/org/python/core/PyStringDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyStringDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PySuperDerived.java =================================================================== --- branches/asm/src/org/python/core/PySuperDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PySuperDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyTupleDerived.java =================================================================== --- branches/asm/src/org/python/core/PyTupleDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyTupleDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyTypeDerived.java =================================================================== --- branches/asm/src/org/python/core/PyTypeDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyTypeDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -741,16 +741,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/core/PyUnicodeDerived.java =================================================================== --- branches/asm/src/org/python/core/PyUnicodeDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/core/PyUnicodeDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -765,16 +765,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/modules/_weakref/ReferenceTypeDerived.java =================================================================== --- branches/asm/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/modules/_weakref/ReferenceTypeDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -767,16 +767,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/modules/collections/PyDefaultDictDerived.java =================================================================== --- branches/asm/src/org/python/modules/collections/PyDefaultDictDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/modules/collections/PyDefaultDictDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -767,16 +767,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/modules/collections/PyDequeDerived.java =================================================================== --- branches/asm/src/org/python/modules/collections/PyDequeDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/modules/collections/PyDequeDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -767,16 +767,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/modules/random/PyRandomDerived.java =================================================================== --- branches/asm/src/org/python/modules/random/PyRandomDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/modules/random/PyRandomDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -767,16 +767,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/modules/thread/PyLocalDerived.java =================================================================== --- branches/asm/src/org/python/modules/thread/PyLocalDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/modules/thread/PyLocalDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -743,16 +743,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/org/python/modules/zipimport/zipimporterDerived.java =================================================================== --- branches/asm/src/org/python/modules/zipimport/zipimporterDerived.java 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/org/python/modules/zipimport/zipimporterDerived.java 2008-07-02 21:43:16 UTC (rev 4841) @@ -743,16 +743,22 @@ public int __cmp__(PyObject other) { PyType self_type=getType(); - PyObject impl=self_type.lookup("__cmp__"); - if (impl!=null) { - PyObject res=impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v=((PyInteger)res).getValue(); - return v<0?-1:v>0?1:0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType[]where_type=new PyType[1]; + PyObject impl=self_type.lookup_where("__cmp__",where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl==null||where_type[0]==TYPE||Py.isSubClass(TYPE,where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v<0?-1:v>0?1:0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { Modified: branches/asm/src/templates/object.derived =================================================================== --- branches/asm/src/templates/object.derived 2008-07-02 21:09:14 UTC (rev 4840) +++ branches/asm/src/templates/object.derived 2008-07-02 21:43:16 UTC (rev 4841) @@ -51,7 +51,7 @@ throw Py.TypeError("__int__"+" should return an integer"); } return super.__int__(); - } + } public PyObject __long__() { PyType self_type=getType(); @@ -91,24 +91,30 @@ if (res instanceof PyUnicode) return(PyUnicode)res; if (res instanceof PyString) - return new PyUnicode((PyString)res); + return new PyUnicode((PyString)res); throw Py.TypeError("__unicode__"+" should return a "+"unicode"); } return super.__unicode__(); } public int __cmp__(PyObject other) { - PyType self_type = getType(); - PyObject impl = self_type.lookup("__cmp__"); - if (impl != null) { - PyObject res = impl.__get__(this,self_type).__call__(other); - if (res instanceof PyInteger) { - int v = ((PyInteger)res).getValue(); - return v < 0 ? -1 : v > 0 ? 1 : 0; - } - throw Py.TypeError("__cmp__ should return a int"); + PyType self_type=getType(); + PyType[] where_type = new PyType[1]; + PyObject impl = self_type.lookup_where("__cmp__", where_type); + // Full Compatibility with CPython __cmp__: + // If the derived type don't override __cmp__, the + // *internal* super().__cmp__ should be called, not the + // exposed one. The difference is that the exposed __cmp__ + // throws a TypeError if the argument is an instance of the same type. + if (impl == null || where_type[0] == TYPE || Py.isSubClass(TYPE, where_type[0])) { + return super.__cmp__(other); } - return super.__cmp__(other); + PyObject res = impl.__get__(this,self_type).__call__(other); + if (res instanceof PyInteger) { + int v=((PyInteger)res).getValue(); + return v < 0 ? -1 : v > 0 ? 1 : 0; + } + throw Py.TypeError("__cmp__ should return a int"); } public boolean __nonzero__() { @@ -158,7 +164,7 @@ PyObject impl = self_type.lookup("next"); if (impl != null) { try { - return impl.__get__(this,self_type).__call__(); + return impl.__get__(this,self_type).__call__(); } catch (PyException exc) { if (Py.matchException(exc, Py.StopIteration)) return null; @@ -173,7 +179,7 @@ PyObject impl = self_type.lookup("__getitem__"); if (impl != null) try { - return impl.__get__(this,self_type).__call__(key); + return impl.__get__(this,self_type).__call__(key); } catch (PyException exc) { if (Py.matchException(exc, Py.LookupError)) return null; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-07-02 21:09:16
|
Revision: 4840 http://jython.svn.sourceforge.net/jython/?rev=4840&view=rev Author: leosoto Date: 2008-07-02 14:09:14 -0700 (Wed, 02 Jul 2008) Log Message: ----------- Syncing PyBaseExceptionDerived Modified Paths: -------------- branches/asm/src/org/python/core/PyBaseExceptionDerived.java Modified: branches/asm/src/org/python/core/PyBaseExceptionDerived.java =================================================================== --- branches/asm/src/org/python/core/PyBaseExceptionDerived.java 2008-07-02 20:17:29 UTC (rev 4839) +++ branches/asm/src/org/python/core/PyBaseExceptionDerived.java 2008-07-02 21:09:14 UTC (rev 4840) @@ -529,104 +529,156 @@ public PyObject __iadd__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__iadd__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__iadd__(other); } public PyObject __isub__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__isub__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__isub__(other); } public PyObject __imul__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__imul__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__imul__(other); } public PyObject __idiv__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__idiv__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__idiv__(other); } public PyObject __ifloordiv__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__ifloordiv__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__ifloordiv__(other); } public PyObject __itruediv__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__itruediv__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__itruediv__(other); } public PyObject __imod__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__imod__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__imod__(other); } public PyObject __ipow__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__ipow__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__ipow__(other); } public PyObject __ilshift__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__ilshift__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__ilshift__(other); } public PyObject __irshift__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__irshift__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__irshift__(other); } public PyObject __iand__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__iand__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__iand__(other); } public PyObject __ior__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__ior__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__ior__(other); } public PyObject __ixor__(PyObject other) { PyType self_type=getType(); PyObject impl=self_type.lookup("__ixor__"); - if (impl!=null) - return impl.__get__(this,self_type).__call__(other); + if (impl!=null) { + PyObject res=impl.__get__(this,self_type).__call__(other); + if (res==Py.NotImplemented) + return null; + return res; + } return super.__ixor__(other); } @@ -659,12 +711,17 @@ PyObject impl=self_type.lookup("__hash__"); if (impl!=null) { PyObject res=impl.__get__(this,self_type).__call__(); - if (res instanceof PyInteger) + if (res instanceof PyInteger) { return((PyInteger)res).getValue(); + } else + if (res instanceof PyLong) { + return((PyLong)res).getValue().intValue(); + } throw Py.TypeError("__hash__ should return a int"); } - if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) + if (self_type.lookup("__eq__")!=null||self_type.lookup("__cmp__")!=null) { throw Py.TypeError("unhashable type"); + } return super.hashCode(); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-07-02 20:17:37
|
Revision: 4839 http://jython.svn.sourceforge.net/jython/?rev=4839&view=rev Author: leosoto Date: 2008-07-02 13:17:29 -0700 (Wed, 02 Jul 2008) Log Message: ----------- Updated eclipse configuration to use the antlr3.1b1 JAR instead of 3.0.1 Modified Paths: -------------- branches/asm/.classpath Modified: branches/asm/.classpath =================================================================== --- branches/asm/.classpath 2008-07-02 05:56:10 UTC (rev 4838) +++ branches/asm/.classpath 2008-07-02 20:17:29 UTC (rev 4839) @@ -14,7 +14,7 @@ <classpathentry kind="lib" path="extlibs/postgresql-8.3-603.jdbc4.jar"/> <classpathentry kind="lib" path="extlibs/servlet-api-2.5.jar"/> <classpathentry kind="lib" path="build/jarjar"/> - <classpathentry kind="lib" path="extlibs/antlr-3.0.1.jar"/> <classpathentry kind="var" path="ANT_HOME/lib/ant.jar"/> + <classpathentry kind="lib" path="extlibs/antlr-runtime-3.1b1.jar"/> <classpathentry kind="output" path="bugtests/classes"/> </classpath> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-07-02 05:56:12
|
Revision: 4838 http://jython.svn.sourceforge.net/jython/?rev=4838&view=rev Author: zyasoft Date: 2008-07-01 22:56:10 -0700 (Tue, 01 Jul 2008) Log Message: ----------- cmath.log now takes a base parameter; all functions now test for ValueError to reraise as a TypeError, to be consistent with CPython Modified Paths: -------------- branches/asm/src/org/python/modules/cmath.java Modified: branches/asm/src/org/python/modules/cmath.java =================================================================== --- branches/asm/src/org/python/modules/cmath.java 2008-07-02 03:51:43 UTC (rev 4837) +++ branches/asm/src/org/python/modules/cmath.java 2008-07-02 05:56:10 UTC (rev 4838) @@ -28,12 +28,23 @@ try{ return(in.__complex__()); } catch(PyException e){ - if(e.type == Py.AttributeError) { + if(e.type == Py.AttributeError || e.type == Py.ValueError) { throw Py.TypeError("a float is required"); } throw e; } } + + private static double doubleFromPyObject(PyObject in) { + try{ + return(in.__float__().getValue()); + } catch(PyException e){ + if(e.type == Py.AttributeError || e.type == Py.ValueError) { + throw Py.TypeError("a float is required"); + } + throw e; + } + } public static PyObject acos(PyObject in) { PyComplex x = complexFromPyObject(in); @@ -133,6 +144,19 @@ r.real = math.log10(new PyFloat(l)); return (r); } + + public static PyComplex log(PyObject in, PyObject base) { + return log(complexFromPyObject(in), doubleFromPyObject(base)); + } + + public static PyComplex log(PyComplex x, double base) { + PyComplex r = new PyComplex(0.0, 0.0); + double l = hypot(x.real, x.imag); + double log_base = Math.log(base); + r.imag = Math.atan2(x.imag, x.real) / log_base; + r.real = math.log(new PyFloat(l)) / log_base; + return (r); + } public static PyComplex sin(PyObject in) { PyComplex r = new PyComplex(0.0, 0.0); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-07-02 03:51:45
|
Revision: 4837 http://jython.svn.sourceforge.net/jython/?rev=4837&view=rev Author: leosoto Date: 2008-07-01 20:51:43 -0700 (Tue, 01 Jul 2008) Log Message: ----------- Another string interpolation fix, this time when the left operand is an unicode containing non-ascii chars and there are no unicodes on the right argument Modified Paths: -------------- branches/asm/Lib/test/test_str_jy.py branches/asm/src/org/python/core/PyString.java branches/asm/src/org/python/core/PyUnicode.java Modified: branches/asm/Lib/test/test_str_jy.py =================================================================== --- branches/asm/Lib/test/test_str_jy.py 2008-07-02 00:33:20 UTC (rev 4836) +++ branches/asm/Lib/test/test_str_jy.py 2008-07-02 03:51:43 UTC (rev 4837) @@ -1,4 +1,4 @@ -import test_support +from test import test_support import unittest class WrappedStrCmpTest(unittest.TestCase): @@ -23,13 +23,13 @@ self.assertEquals(1, d[ABC]) class IntToStrTest(unittest.TestCase): - + def test_int_to_string_format(self): # 0.001 comes out as 0.0010 self.assertEquals(str(0.001), "0.001") class StringSlicingTest(unittest.TestCase): - + def test_out_of_bounds(self): try: "a"[10:] @@ -37,7 +37,7 @@ self.fail("str slice threw StringOutOfBoundsError") class FormatTest(unittest.TestCase): - + def test_add_zeros(self): # 2 "%012d" % -4 displays '0000000000-4' s = "%012d" % -4 @@ -51,8 +51,8 @@ self.assertEquals("%e" % 1e-6, "1.000000e-06") self.assertEquals("%+f" % -5, "-5.000000") self.assertEquals("%+f" % 5, "+5.000000") - + def test_argument_count_exception(self): "exception thrown when too many or too few arguments for format string" foo = False @@ -70,6 +70,35 @@ except TypeError, e: self.failUnless("not enough arguments for format string" in str(e)) + def test_unicode_arg(self): + # When the right-side operand is a unicode, the result should be unicode + # too + self.assertEquals("%s" % u"foo", u"foo") + self.assertEquals("%s" % u"\u00e7", u"\u00e7") + + def test_unicode_in_args(self): + # When at least one of the right-side operands is a unicode, the result + # should be unicode too + self.assertEquals("%s %s" % (u"foo", "bar"), u"foo bar") + self.assertEquals("%s %s" % ("foo", u"bar"), u"foo bar") + + class S(object): + def __str__(self): return "str" + def __unicode__(self): return "unicode" + + # Also, once a unicode has been found, next args should be __unicode__'d + self.assertEquals("%s %s %s" % ("foo", u"bar", S()), u"foo bar unicode") + # But, args found before the first unicode should not be __unicode__'d + self.assertEquals("%s %s %s" % (S(), u"bar", S()), u"str bar unicode") + + def test_non_ascii_unicode_mod_str(self): + # Regression test for a problem on the formatting logic: when no unicode + # args were found, Jython stored the resulting buffer on a PyString, + # decoding it later to make a PyUnicode. That crashed when the left side + # of % was a unicode containing non-ascii chars + self.assertEquals(u"\u00e7%s" % "foo", u"\u00e7foo") + + class DisplayTest(unittest.TestCase): def test_str_and_repr(self): Modified: branches/asm/src/org/python/core/PyString.java =================================================================== --- branches/asm/src/org/python/core/PyString.java 2008-07-02 00:33:20 UTC (rev 4836) +++ branches/asm/src/org/python/core/PyString.java 2008-07-02 03:51:43 UTC (rev 4837) @@ -2478,7 +2478,7 @@ public PyString format(PyObject args) { PyObject dict = null; this.args = args; - boolean needUnicode = false; + boolean needUnicode = unicodeCoercion; if (args instanceof PyTuple) { argIndex = 0; } else { @@ -2577,7 +2577,7 @@ needUnicode = true; } if (c == 's') - if (unicodeCoercion || needUnicode) + if (needUnicode) string = arg.__unicode__().toString(); else string = arg.__str__().toString(); Modified: branches/asm/src/org/python/core/PyUnicode.java =================================================================== --- branches/asm/src/org/python/core/PyUnicode.java 2008-07-02 00:33:20 UTC (rev 4836) +++ branches/asm/src/org/python/core/PyUnicode.java 2008-07-02 03:51:43 UTC (rev 4837) @@ -190,7 +190,7 @@ @ExposedMethod final PyObject unicode___mod__(PyObject other) { StringFormatter fmt = new StringFormatter(string, true); - return fmt.format(other).__unicode__(); + return fmt.format(other); } @ExposedMethod This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-07-02 00:33:21
|
Revision: 4836 http://jython.svn.sourceforge.net/jython/?rev=4836&view=rev Author: leosoto Date: 2008-07-01 17:33:20 -0700 (Tue, 01 Jul 2008) Log Message: ----------- Workaround for issue 1047. At least on my system (jdk 1.6.0_06) it makes pulldom usable Modified Paths: -------------- branches/asm/Lib/xml/dom/pulldom.py Modified: branches/asm/Lib/xml/dom/pulldom.py =================================================================== --- branches/asm/Lib/xml/dom/pulldom.py 2008-07-01 23:38:37 UTC (rev 4835) +++ branches/asm/Lib/xml/dom/pulldom.py 2008-07-02 00:33:20 UTC (rev 4836) @@ -280,6 +280,8 @@ """ Fallback replacement for getEvent() that emits the events that _slurp() read previously. """ + if self.pulldom.firstEvent[1] is None: + return None rc = self.pulldom.firstEvent[1][0] self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1] return rc This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-07-01 23:38:40
|
Revision: 4835 http://jython.svn.sourceforge.net/jython/?rev=4835&view=rev Author: leosoto Date: 2008-07-01 16:38:37 -0700 (Tue, 01 Jul 2008) Log Message: ----------- zxJDBC: Avoid preparing a statement when executemany() is called with an empty sequence Modified Paths: -------------- branches/asm/src/com/ziclix/python/sql/PyCursor.java Modified: branches/asm/src/com/ziclix/python/sql/PyCursor.java =================================================================== --- branches/asm/src/com/ziclix/python/sql/PyCursor.java 2008-07-01 22:24:50 UTC (rev 4834) +++ branches/asm/src/com/ziclix/python/sql/PyCursor.java 2008-07-01 23:38:37 UTC (rev 4835) @@ -506,7 +506,11 @@ * @param maxRows */ public void executemany(PyObject sql, PyObject params, PyObject bindings, PyObject maxRows) { - execute(sql, params, bindings, maxRows); + if (isSeq(params) && params.__len__() == 0) { + //executemany with an empty params tuple is a no-op + return; + } + execute(sql, params, bindings, maxRows); } /** This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-07-01 22:24:52
|
Revision: 4834 http://jython.svn.sourceforge.net/jython/?rev=4834&view=rev Author: leosoto Date: 2008-07-01 15:24:50 -0700 (Tue, 01 Jul 2008) Log Message: ----------- zxJDBC: Added BigInteger support to the PostgreSQLDataHandler Modified Paths: -------------- branches/asm/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java Modified: branches/asm/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java =================================================================== --- branches/asm/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java 2008-07-01 22:02:55 UTC (rev 4833) +++ branches/asm/src/com/ziclix/python/sql/handler/PostgresqlDataHandler.java 2008-07-01 22:24:50 UTC (rev 4834) @@ -14,6 +14,7 @@ import org.python.core.PyObject; import java.math.BigDecimal; +import java.math.BigInteger; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -122,4 +123,16 @@ super.setJDBCObject(stmt, index, object, type); } } + public void setJDBCObject(PreparedStatement stmt, int index, PyObject object) throws SQLException { + // PostgreSQL doesn't support BigIntegers without explicitely setting the + // type. + Object value = object.__tojava__(Object.class); + if (value instanceof BigInteger) { + super.setJDBCObject(stmt, index, object, Types.BIGINT); + } else { + super.setJDBCObject(stmt, index, object); + } + + } + } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-07-01 22:02:58
|
Revision: 4833 http://jython.svn.sourceforge.net/jython/?rev=4833&view=rev Author: zyasoft Date: 2008-07-01 15:02:55 -0700 (Tue, 01 Jul 2008) Log Message: ----------- cStringIO#readline should not insert backslash-n (ambigous reading, but CPython implementation says otherwise) Modified Paths: -------------- branches/asm/CPythonLib.includes branches/asm/Lib/test/test_long_int_args.py branches/asm/src/org/python/modules/cStringIO.java Modified: branches/asm/CPythonLib.includes =================================================================== --- branches/asm/CPythonLib.includes 2008-07-01 21:30:12 UTC (rev 4832) +++ branches/asm/CPythonLib.includes 2008-07-01 22:02:55 UTC (rev 4833) @@ -35,6 +35,7 @@ colorsys.py commands.py compileall.py +contextlib.py ConfigParser.py cookielib.py copy.py @@ -113,6 +114,7 @@ repr.py rfc822.py rlcompleter.py +runpy.py sched.py sha.py sets.py @@ -154,6 +156,7 @@ weakref.py whichdb.py whrandom.py +wsgiref/*.py xdrlib.py xmllib.py xmlrpclib.py Modified: branches/asm/Lib/test/test_long_int_args.py =================================================================== --- branches/asm/Lib/test/test_long_int_args.py 2008-07-01 21:30:12 UTC (rev 4832) +++ branches/asm/Lib/test/test_long_int_args.py 2008-07-01 22:02:55 UTC (rev 4833) @@ -5,7 +5,7 @@ import array import cStringIO import tempfile -import test_support +from test import test_support import unittest import StringIO Modified: branches/asm/src/org/python/modules/cStringIO.java =================================================================== --- branches/asm/src/org/python/modules/cStringIO.java 2008-07-01 21:30:12 UTC (rev 4832) +++ branches/asm/src/org/python/modules/cStringIO.java 2008-07-01 22:02:55 UTC (rev 4833) @@ -77,6 +77,13 @@ if (closed) throw Py.ValueError("I/O operation on closed file"); } + + private int _convert_to_int(long val) { + if (val > Integer.MAX_VALUE) { + throw Py.OverflowError("long int too large to convert to int"); + } + return (int)val; + } public void __setattr__(String name, PyObject value) { if (name == "softspace") { @@ -116,7 +123,7 @@ * Position the file pointer to the absolute position. * @param pos the position in the file. */ - public void seek(int pos) { + public void seek(long pos) { seek(pos, os.SEEK_SET); } @@ -126,18 +133,18 @@ * @param pos the position in the file. * @param mode; 0=from the start, 1=relative, 2=from the end. */ - public void seek(int pos, int mode) { + public void seek(long pos, int mode) { _complain_ifclosed(); switch (mode) { case os.SEEK_CUR: this.pos += pos; break; case os.SEEK_END: - this.pos = pos + buf.length(); + this.pos = _convert_to_int(pos + buf.length()); break; case os.SEEK_SET: default: - this.pos = pos; + this.pos = _convert_to_int(pos); break; } } @@ -178,15 +185,18 @@ * @param size the number of characters to read. * @returns A string containing the data read. */ - public String read(int size) { + + public String read(long size) { _complain_ifclosed(); + int size_int = _convert_to_int(size); int len = buf.length(); String substr; if (size < 0) { substr = pos >= len ? "" : buf.substring(pos); pos = len; } else { - int newpos = Math.min(pos + size, len); + // ensure no overflow + int newpos = _convert_to_int(Math.min(pos + size, len)); substr = buf.substring(pos, newpos); pos = newpos; } @@ -215,8 +225,9 @@ * returned. * @returns data from the file up to and including the newline. */ - public String readline(int size) { + public String readline(long size) { _complain_ifclosed(); + int size_int = _convert_to_int(size); int len = buf.length(); if (pos == len) { return ""; @@ -224,11 +235,11 @@ int i = buf.indexOf("\n", pos); int newpos = (i < 0) ? len : i + 1; if (size >= 0) { - newpos = Math.min(newpos - pos, size) + pos; + newpos = _convert_to_int(Math.min(newpos - pos, size) + pos); } String r = buf.substring(pos, newpos); pos = newpos; - return (i < 0 && size <= 0) ? r + "\n" : r; + return r; } @@ -265,15 +276,17 @@ * the lines thus read. * @return a list of the lines. */ - public PyObject readlines(int sizehint) { + public PyObject readlines(long sizehint) { _complain_ifclosed(); + + int sizehint_int = (int)sizehint; int total = 0; PyList lines = new PyList(); String line = readline(); while (line.length() > 0) { lines.append(new PyString(line)); total += line.length(); - if (0 < sizehint && sizehint <= total) + if (0 < sizehint_int && sizehint_int <= total) break; line = readline(); } @@ -290,11 +303,12 @@ /** * truncate the file at the position pos. */ - public void truncate(int pos) { - if (pos < 0) - pos = this.pos; - buf.setLength(pos); - this.pos = pos; + public void truncate(long pos) { + int pos_int = _convert_to_int(pos); + if (pos_int < 0) + pos_int = this.pos; + buf.setLength(pos_int); + this.pos = pos_int; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <le...@us...> - 2008-07-01 21:30:14
|
Revision: 4832 http://jython.svn.sourceforge.net/jython/?rev=4832&view=rev Author: leosoto Date: 2008-07-01 14:30:12 -0700 (Tue, 01 Jul 2008) Log Message: ----------- pyBoolean.__tojava__(Object.class) now returns a Boolean instead of an Integer. Also used valueOf static methods instead of constructors. Modified Paths: -------------- branches/asm/src/org/python/core/PyBoolean.java Modified: branches/asm/src/org/python/core/PyBoolean.java =================================================================== --- branches/asm/src/org/python/core/PyBoolean.java 2008-07-01 21:12:34 UTC (rev 4831) +++ branches/asm/src/org/python/core/PyBoolean.java 2008-07-01 21:30:12 UTC (rev 4832) @@ -76,25 +76,24 @@ } public Object __tojava__(Class c) { + if (c == Boolean.TYPE || c == Boolean.class || + c == Object.class ) { + return Boolean.valueOf(value); + } if (c == Integer.TYPE || c == Number.class || - c == Object.class || c == Integer.class || - c == Serializable.class) - { - return new Integer(value ? 1 : 0); + c == Integer.class) { + return Integer.valueOf(value ? 1 : 0); } - - if (c == Boolean.TYPE || c == Boolean.class) - return new Boolean(value); if (c == Byte.TYPE || c == Byte.class) - return new Byte((byte)(value ? 1 : 0)); + return Byte.valueOf((byte)(value ? 1 : 0)); if (c == Short.TYPE || c == Short.class) - return new Short((short)(value ? 1 : 0)); + return Short.valueOf((short)(value ? 1 : 0)); if (c == Long.TYPE || c == Long.class) - return new Long(value ? 1 : 0); + return Long.valueOf(value ? 1 : 0); if (c == Float.TYPE || c == Float.class) - return new Float(value ? 1 : 0); + return Float.valueOf(value ? 1 : 0); if (c == Double.TYPE || c == Double.class) - return new Double(value ? 1 : 0); + return Double.valueOf(value ? 1 : 0); return super.__tojava__(c); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-07-01 21:12:45
|
Revision: 4831 http://jython.svn.sourceforge.net/jython/?rev=4831&view=rev Author: zyasoft Date: 2008-07-01 14:12:34 -0700 (Tue, 01 Jul 2008) Log Message: ----------- Removed spurious placement of test_bigmem Removed Paths: ------------- branches/asm/Lib/test_bigmem.py Deleted: branches/asm/Lib/test_bigmem.py =================================================================== --- branches/asm/Lib/test_bigmem.py 2008-07-01 20:38:05 UTC (rev 4830) +++ branches/asm/Lib/test_bigmem.py 2008-07-01 21:12:34 UTC (rev 4831) @@ -1,972 +0,0 @@ -from test import test_support -from test.test_support import bigmemtest, _1G, _2G - -import unittest -import operator -import string -import sys - -# Bigmem testing houserules: -# -# - Try not to allocate too many large objects. It's okay to rely on -# refcounting semantics, but don't forget that 's = create_largestring()' -# doesn't release the old 's' (if it exists) until well after its new -# value has been created. Use 'del s' before the create_largestring call. -# -# - Do *not* compare large objects using assertEquals or similar. It's a -# lengty operation and the errormessage will be utterly useless due to -# its size. To make sure whether a result has the right contents, better -# to use the strip or count methods, or compare meaningful slices. -# -# - Don't forget to test for large indices, offsets and results and such, -# in addition to large sizes. -# -# - When repeating an object (say, a substring, or a small list) to create -# a large object, make the subobject of a length that is not a power of -# 2. That way, int-wrapping problems are more easily detected. -# -# - While the bigmemtest decorator speaks of 'minsize', all tests will -# actually be called with a much smaller number too, in the normal -# test run (5Kb currently.) This is so the tests themselves get frequent -# testing. Consequently, always make all large allocations based on the -# passed-in 'size', and don't rely on the size being very large. Also, -# memuse-per-size should remain sane (less than a few thousand); if your -# test uses more, adjust 'size' upward, instead. - -class StrTest(unittest.TestCase): - @bigmemtest(minsize=_2G, memuse=2) - def test_capitalize(self, size): - SUBSTR = ' abc def ghi' - s = '-' * size + SUBSTR - caps = s.capitalize() - self.assertEquals(caps[-len(SUBSTR):], - SUBSTR.capitalize()) - self.assertEquals(caps.lstrip('-'), SUBSTR) - - @bigmemtest(minsize=_2G + 10, memuse=1) - def test_center(self, size): - SUBSTR = ' abc def ghi' - s = SUBSTR.center(size) - self.assertEquals(len(s), size) - lpadsize = rpadsize = (len(s) - len(SUBSTR)) // 2 - if len(s) % 2: - lpadsize += 1 - self.assertEquals(s[lpadsize:-rpadsize], SUBSTR) - self.assertEquals(s.strip(), SUBSTR.strip()) - - @bigmemtest(minsize=_2G, memuse=2) - def test_count(self, size): - SUBSTR = ' abc def ghi' - s = '.' * size + SUBSTR - self.assertEquals(s.count('.'), size) - s += '.' - self.assertEquals(s.count('.'), size + 1) - self.assertEquals(s.count(' '), 3) - self.assertEquals(s.count('i'), 1) - self.assertEquals(s.count('j'), 0) - - @bigmemtest(minsize=_2G + 2, memuse=3) - def test_decode(self, size): - s = '.' * size - self.assertEquals(len(s.decode('utf-8')), size) - - @bigmemtest(minsize=_2G + 2, memuse=3) - def test_encode(self, size): - s = u'.' * size - self.assertEquals(len(s.encode('utf-8')), size) - - @bigmemtest(minsize=_2G, memuse=2) - def test_endswith(self, size): - SUBSTR = ' abc def ghi' - s = '-' * size + SUBSTR - self.failUnless(s.endswith(SUBSTR)) - self.failUnless(s.endswith(s)) - s2 = '...' + s - self.failUnless(s2.endswith(s)) - self.failIf(s.endswith('a' + SUBSTR)) - self.failIf(SUBSTR.endswith(s)) - - @bigmemtest(minsize=_2G + 10, memuse=2) - def test_expandtabs(self, size): - s = '-' * size - tabsize = 8 - self.assertEquals(s.expandtabs(), s) - del s - slen, remainder = divmod(size, tabsize) - s = ' \t' * slen - s = s.expandtabs(tabsize) - self.assertEquals(len(s), size - remainder) - self.assertEquals(len(s.strip(' ')), 0) - - @bigmemtest(minsize=_2G, memuse=2) - def test_find(self, size): - SUBSTR = ' abc def ghi' - sublen = len(SUBSTR) - s = ''.join([SUBSTR, '-' * size, SUBSTR]) - self.assertEquals(s.find(' '), 0) - self.assertEquals(s.find(SUBSTR), 0) - self.assertEquals(s.find(' ', sublen), sublen + size) - self.assertEquals(s.find(SUBSTR, len(SUBSTR)), sublen + size) - self.assertEquals(s.find('i'), SUBSTR.find('i')) - self.assertEquals(s.find('i', sublen), - sublen + size + SUBSTR.find('i')) - self.assertEquals(s.find('i', size), - sublen + size + SUBSTR.find('i')) - self.assertEquals(s.find('j'), -1) - - @bigmemtest(minsize=_2G, memuse=2) - def test_index(self, size): - SUBSTR = ' abc def ghi' - sublen = len(SUBSTR) - s = ''.join([SUBSTR, '-' * size, SUBSTR]) - self.assertEquals(s.index(' '), 0) - self.assertEquals(s.index(SUBSTR), 0) - self.assertEquals(s.index(' ', sublen), sublen + size) - self.assertEquals(s.index(SUBSTR, sublen), sublen + size) - self.assertEquals(s.index('i'), SUBSTR.index('i')) - self.assertEquals(s.index('i', sublen), - sublen + size + SUBSTR.index('i')) - self.assertEquals(s.index('i', size), - sublen + size + SUBSTR.index('i')) - self.assertRaises(ValueError, s.index, 'j') - - @bigmemtest(minsize=_2G, memuse=2) - def test_isalnum(self, size): - SUBSTR = '123456' - s = 'a' * size + SUBSTR - self.failUnless(s.isalnum()) - s += '.' - self.failIf(s.isalnum()) - - @bigmemtest(minsize=_2G, memuse=2) - def test_isalpha(self, size): - SUBSTR = 'zzzzzzz' - s = 'a' * size + SUBSTR - self.failUnless(s.isalpha()) - s += '.' - self.failIf(s.isalpha()) - - @bigmemtest(minsize=_2G, memuse=2) - def test_isdigit(self, size): - SUBSTR = '123456' - s = '9' * size + SUBSTR - self.failUnless(s.isdigit()) - s += 'z' - self.failIf(s.isdigit()) - - @bigmemtest(minsize=_2G, memuse=2) - def test_islower(self, size): - chars = ''.join([ chr(c) for c in range(255) if not chr(c).isupper() ]) - repeats = size // len(chars) + 2 - s = chars * repeats - self.failUnless(s.islower()) - s += 'A' - self.failIf(s.islower()) - - @bigmemtest(minsize=_2G, memuse=2) - def test_isspace(self, size): - whitespace = ' \f\n\r\t\v' - repeats = size // len(whitespace) + 2 - s = whitespace * repeats - self.failUnless(s.isspace()) - s += 'j' - self.failIf(s.isspace()) - - @bigmemtest(minsize=_2G, memuse=2) - def test_istitle(self, size): - SUBSTR = '123456' - s = ''.join(['A', 'a' * size, SUBSTR]) - self.failUnless(s.istitle()) - s += 'A' - self.failUnless(s.istitle()) - s += 'aA' - self.failIf(s.istitle()) - - @bigmemtest(minsize=_2G, memuse=2) - def test_isupper(self, size): - chars = ''.join([ chr(c) for c in range(255) if not chr(c).islower() ]) - repeats = size // len(chars) + 2 - s = chars * repeats - self.failUnless(s.isupper()) - s += 'a' - self.failIf(s.isupper()) - - @bigmemtest(minsize=_2G, memuse=2) - def test_join(self, size): - s = 'A' * size - x = s.join(['aaaaa', 'bbbbb']) - self.assertEquals(x.count('a'), 5) - self.assertEquals(x.count('b'), 5) - self.failUnless(x.startswith('aaaaaA')) - self.failUnless(x.endswith('Abbbbb')) - - @bigmemtest(minsize=_2G + 10, memuse=1) - def test_ljust(self, size): - SUBSTR = ' abc def ghi' - s = SUBSTR.ljust(size) - self.failUnless(s.startswith(SUBSTR + ' ')) - self.assertEquals(len(s), size) - self.assertEquals(s.strip(), SUBSTR.strip()) - - @bigmemtest(minsize=_2G + 10, memuse=2) - def test_lower(self, size): - s = 'A' * size - s = s.lower() - self.assertEquals(len(s), size) - self.assertEquals(s.count('a'), size) - - @bigmemtest(minsize=_2G + 10, memuse=1) - def test_lstrip(self, size): - SUBSTR = 'abc def ghi' - s = SUBSTR.rjust(size) - self.assertEquals(len(s), size) - self.assertEquals(s.lstrip(), SUBSTR.lstrip()) - del s - s = SUBSTR.ljust(size) - self.assertEquals(len(s), size) - stripped = s.lstrip() - # jython - unlike python, we cannot rely on this string - # maintaining its identity - self.failUnless(stripped == s) - - @bigmemtest(minsize=_2G + 10, memuse=2) - def test_replace(self, size): - replacement = 'a' - s = ' ' * size - s = s.replace(' ', replacement) - self.assertEquals(len(s), size) - self.assertEquals(s.count(replacement), size) - s = s.replace(replacement, ' ', size - 4) - self.assertEquals(len(s), size) - self.assertEquals(s.count(replacement), 4) - self.assertEquals(s[-10:], ' aaaa') - - @bigmemtest(minsize=_2G, memuse=2) - def test_rfind(self, size): - SUBSTR = ' abc def ghi' - sublen = len(SUBSTR) - s = ''.join([SUBSTR, '-' * size, SUBSTR]) - self.assertEquals(s.rfind(' '), sublen + size + SUBSTR.rfind(' ')) - self.assertEquals(s.rfind(SUBSTR), sublen + size) - self.assertEquals(s.rfind(' ', 0, size), SUBSTR.rfind(' ')) - self.assertEquals(s.rfind(SUBSTR, 0, sublen + size), 0) - self.assertEquals(s.rfind('i'), sublen + size + SUBSTR.rfind('i')) - self.assertEquals(s.rfind('i', 0, sublen), SUBSTR.rfind('i')) - self.assertEquals(s.rfind('i', 0, sublen + size), - SUBSTR.rfind('i')) - self.assertEquals(s.rfind('j'), -1) - - @bigmemtest(minsize=_2G, memuse=2) - def test_rindex(self, size): - SUBSTR = ' abc def ghi' - sublen = len(SUBSTR) - s = ''.join([SUBSTR, '-' * size, SUBSTR]) - self.assertEquals(s.rindex(' '), - sublen + size + SUBSTR.rindex(' ')) - self.assertEquals(s.rindex(SUBSTR), sublen + size) - self.assertEquals(s.rindex(' ', 0, sublen + size - 1), - SUBSTR.rindex(' ')) - self.assertEquals(s.rindex(SUBSTR, 0, sublen + size), 0) - self.assertEquals(s.rindex('i'), - sublen + size + SUBSTR.rindex('i')) - self.assertEquals(s.rindex('i', 0, sublen), SUBSTR.rindex('i')) - self.assertEquals(s.rindex('i', 0, sublen + size), - SUBSTR.rindex('i')) - self.assertRaises(ValueError, s.rindex, 'j') - - @bigmemtest(minsize=_2G + 10, memuse=1) - def test_rjust(self, size): - SUBSTR = ' abc def ghi' - s = SUBSTR.ljust(size) - self.failUnless(s.startswith(SUBSTR + ' ')) - self.assertEquals(len(s), size) - self.assertEquals(s.strip(), SUBSTR.strip()) - - @bigmemtest(minsize=_2G + 10, memuse=1) - def test_rstrip(self, size): - SUBSTR = ' abc def ghi' - s = SUBSTR.ljust(size) - self.assertEquals(len(s), size) - self.assertEquals(s.rstrip(), SUBSTR.rstrip()) - del s - s = SUBSTR.rjust(size) - self.assertEquals(len(s), size) - stripped = s.rstrip() - # jython - unlike python, we cannot rely on this string - # maintaining its identity - self.failUnless(stripped == s) - - # The test takes about size bytes to build a string, and then about - # sqrt(size) substrings of sqrt(size) in size and a list to - # hold sqrt(size) items. It's close but just over 2x size. - @bigmemtest(minsize=_2G, memuse=2.1) - def test_split_small(self, size): - # Crudely calculate an estimate so that the result of s.split won't - # take up an inordinate amount of memory - chunksize = int(size ** 0.5 + 2) - SUBSTR = 'a' + ' ' * chunksize - s = SUBSTR * chunksize - l = s.split() - self.assertEquals(len(l), chunksize) - self.assertEquals(set(l), set(['a'])) - del l - l = s.split('a') - self.assertEquals(len(l), chunksize + 1) - self.assertEquals(set(l), set(['', ' ' * chunksize])) - - # Allocates a string of twice size (and briefly two) and a list of - # size. Because of internal affairs, the s.split() call produces a - # list of size times the same one-character string, so we only - # suffer for the list size. (Otherwise, it'd cost another 48 times - # size in bytes!) Nevertheless, a list of size takes - # 8*size bytes. - @bigmemtest(minsize=_2G + 5, memuse=10) - def test_split_large(self, size): - s = ' a' * size + ' ' - l = s.split() - self.assertEquals(len(l), size) - self.assertEquals(set(l), set(['a'])) - del l - l = s.split('a') - self.assertEquals(len(l), size + 1) - self.assertEquals(set(l), set([' '])) - - @bigmemtest(minsize=_2G, memuse=2.1) - def test_splitlines(self, size): - # Crudely calculate an estimate so that the result of s.split won't - # take up an inordinate amount of memory - chunksize = int(size ** 0.5 + 2) // 2 - SUBSTR = ' ' * chunksize + '\n' + ' ' * chunksize + '\r\n' - s = SUBSTR * chunksize - l = s.splitlines() - self.assertEquals(len(l), chunksize * 2) - self.assertEquals(set(l), set([' ' * chunksize])) - - @bigmemtest(minsize=_2G, memuse=2) - def test_startswith(self, size): - SUBSTR = ' abc def ghi' - s = '-' * size + SUBSTR - self.failUnless(s.startswith(s)) - self.failUnless(s.startswith('-' * size)) - self.failIf(s.startswith(SUBSTR)) - - @bigmemtest(minsize=_2G, memuse=1) - def test_strip(self, size): - SUBSTR = ' abc def ghi ' - s = SUBSTR.rjust(size) - self.assertEquals(len(s), size) - self.assertEquals(s.strip(), SUBSTR.strip()) - del s - s = SUBSTR.ljust(size) - self.assertEquals(len(s), size) - self.assertEquals(s.strip(), SUBSTR.strip()) - - @bigmemtest(minsize=_2G, memuse=2) - def test_swapcase(self, size): - SUBSTR = "aBcDeFG12.'\xa9\x00" - sublen = len(SUBSTR) - repeats = size // sublen + 2 - s = SUBSTR * repeats - s = s.swapcase() - self.assertEquals(len(s), sublen * repeats) - self.assertEquals(s[:sublen * 3], SUBSTR.swapcase() * 3) - self.assertEquals(s[-sublen * 3:], SUBSTR.swapcase() * 3) - - @bigmemtest(minsize=_2G, memuse=2) - def test_title(self, size): - SUBSTR = 'SpaaHAaaAaham' - s = SUBSTR * (size // len(SUBSTR) + 2) - s = s.title() - self.failUnless(s.startswith((SUBSTR * 3).title())) - self.failUnless(s.endswith(SUBSTR.lower() * 3)) - - @bigmemtest(minsize=_2G, memuse=2) - def test_translate(self, size): - trans = string.maketrans('.aZ', '-!$') - SUBSTR = 'aZz.z.Aaz.' - sublen = len(SUBSTR) - repeats = size // sublen + 2 - s = SUBSTR * repeats - s = s.translate(trans) - self.assertEquals(len(s), repeats * sublen) - self.assertEquals(s[:sublen], SUBSTR.translate(trans)) - self.assertEquals(s[-sublen:], SUBSTR.translate(trans)) - self.assertEquals(s.count('.'), 0) - self.assertEquals(s.count('!'), repeats * 2) - self.assertEquals(s.count('z'), repeats * 3) - - @bigmemtest(minsize=_2G + 5, memuse=2) - def test_upper(self, size): - s = 'a' * size - s = s.upper() - self.assertEquals(len(s), size) - self.assertEquals(s.count('A'), size) - - @bigmemtest(minsize=_2G + 20, memuse=1) - def test_zfill(self, size): - SUBSTR = '-568324723598234' - s = SUBSTR.zfill(size) - self.failUnless(s.endswith('0' + SUBSTR[1:])) - self.failUnless(s.startswith('-0')) - self.assertEquals(len(s), size) - self.assertEquals(s.count('0'), size - len(SUBSTR)) - - @bigmemtest(minsize=_2G + 10, memuse=2) - def test_format(self, size): - s = '-' * size - sf = '%s' % (s,) - self.failUnless(s == sf) - del sf - sf = '..%s..' % (s,) - self.assertEquals(len(sf), len(s) + 4) - self.failUnless(sf.startswith('..-')) - self.failUnless(sf.endswith('-..')) - del s, sf - - size //= 2 - edge = '-' * size - s = ''.join([edge, '%s', edge]) - del edge - s = s % '...' - self.assertEquals(len(s), size * 2 + 3) - self.assertEquals(s.count('.'), 3) - self.assertEquals(s.count('-'), size * 2) - - @bigmemtest(minsize=_2G + 10, memuse=2) - def test_repr_small(self, size): - s = '-' * size - s = repr(s) - self.assertEquals(len(s), size + 2) - self.assertEquals(s[0], "'") - self.assertEquals(s[-1], "'") - self.assertEquals(s.count('-'), size) - del s - # repr() will create a string four times as large as this 'binary - # string', but we don't want to allocate much more than twice - # size in total. (We do extra testing in test_repr_large()) - size = size // 5 * 2 - s = '\x00' * size - s = repr(s) - self.assertEquals(len(s), size * 4 + 2) - self.assertEquals(s[0], "'") - self.assertEquals(s[-1], "'") - self.assertEquals(s.count('\\'), size) - self.assertEquals(s.count('0'), size * 2) - - @bigmemtest(minsize=_2G + 10, memuse=5) - def test_repr_large(self, size): - s = '\x00' * size - s = repr(s) - self.assertEquals(len(s), size * 4 + 2) - self.assertEquals(s[0], "'") - self.assertEquals(s[-1], "'") - self.assertEquals(s.count('\\'), size) - self.assertEquals(s.count('0'), size * 2) - - # This test is meaningful even with size < 2G, as long as the - # doubled string is > 2G (but it tests more if both are > 2G :) - @bigmemtest(minsize=_1G + 2, memuse=3) - def test_concat(self, size): - s = '.' * size - self.assertEquals(len(s), size) - s = s + s - self.assertEquals(len(s), size * 2) - self.assertEquals(s.count('.'), size * 2) - - # This test is meaningful even with size < 2G, as long as the - # repeated string is > 2G (but it tests more if both are > 2G :) - @bigmemtest(minsize=_1G + 2, memuse=3) - def test_repeat(self, size): - s = '.' * size - self.assertEquals(len(s), size) - s = s * 2 - self.assertEquals(len(s), size * 2) - self.assertEquals(s.count('.'), size * 2) - - @bigmemtest(minsize=_2G + 20, memuse=1) - def test_slice_and_getitem(self, size): - SUBSTR = '0123456789' - sublen = len(SUBSTR) - s = SUBSTR * (size // sublen) - stepsize = len(s) // 100 - stepsize = stepsize - (stepsize % sublen) - for i in range(0, len(s) - stepsize, stepsize): - self.assertEquals(s[i], SUBSTR[0]) - self.assertEquals(s[i:i + sublen], SUBSTR) - self.assertEquals(s[i:i + sublen:2], SUBSTR[::2]) - if i > 0: - self.assertEquals(s[i + sublen - 1:i - 1:-3], - SUBSTR[sublen::-3]) - # Make sure we do some slicing and indexing near the end of the - # string, too. - self.assertEquals(s[len(s) - 1], SUBSTR[-1]) - self.assertEquals(s[-1], SUBSTR[-1]) - self.assertEquals(s[len(s) - 10], SUBSTR[0]) - self.assertEquals(s[-sublen], SUBSTR[0]) - self.assertEquals(s[len(s):], '') - self.assertEquals(s[len(s) - 1:], SUBSTR[-1]) - self.assertEquals(s[-1:], SUBSTR[-1]) - self.assertEquals(s[len(s) - sublen:], SUBSTR) - self.assertEquals(s[-sublen:], SUBSTR) - self.assertEquals(len(s[:]), len(s)) - self.assertEquals(len(s[:len(s) - 5]), len(s) - 5) - self.assertEquals(len(s[5:-5]), len(s) - 10) - - self.assertRaises(IndexError, operator.getitem, s, len(s)) - self.assertRaises(IndexError, operator.getitem, s, len(s) + 1) - self.assertRaises(IndexError, operator.getitem, s, len(s) + 1<<31) - - @bigmemtest(minsize=_2G, memuse=2) - def test_contains(self, size): - SUBSTR = '0123456789' - edge = '-' * (size // 2) - s = ''.join([edge, SUBSTR, edge]) - del edge - self.failUnless(SUBSTR in s) - self.failIf(SUBSTR * 2 in s) - self.failUnless('-' in s) - self.failIf('a' in s) - s += 'a' - self.failUnless('a' in s) - - @bigmemtest(minsize=_2G + 10, memuse=2) - def test_compare(self, size): - s1 = '-' * size - s2 = '-' * size - self.failUnless(s1 == s2) - del s2 - s2 = s1 + 'a' - self.failIf(s1 == s2) - del s2 - s2 = '.' * size - self.failIf(s1 == s2) - - @bigmemtest(minsize=_2G + 10, memuse=1) - def test_hash(self, size): - # Not sure if we can do any meaningful tests here... Even if we - # start relying on the exact algorithm used, the result will be - # different depending on the size of the C 'long int'. Even this - # test is dodgy (there's no *guarantee* that the two things should - # have a different hash, even if they, in the current - # implementation, almost always do.) - s = '\x00' * size - print len(s) - h1 = hash(s) - del s - s = '\x00' * (size + 1) - print len(s) - self.failIf(h1 == hash(s)) - -class TupleTest(unittest.TestCase): - - # Tuples have a small, fixed-sized head and an array of pointers to - # data. Since we're testing 64-bit addressing, we can assume that the - # pointers are 8 bytes, and that thus that the tuples take up 8 bytes - # per size. - - # As a side-effect of testing long tuples, these tests happen to test - # having more than 2<<31 references to any given object. Hence the - # use of different types of objects as contents in different tests. - - @bigmemtest(minsize=_2G + 2, memuse=16) - def test_compare(self, size): - t1 = (u'',) * size - t2 = (u'',) * size - self.failUnless(t1 == t2) - del t2 - t2 = (u'',) * (size + 1) - self.failIf(t1 == t2) - del t2 - t2 = (1,) * size - self.failIf(t1 == t2) - - # Test concatenating into a single tuple of more than 2G in length, - # and concatenating a tuple of more than 2G in length separately, so - # the smaller test still gets run even if there isn't memory for the - # larger test (but we still let the tester know the larger test is - # skipped, in verbose mode.) - def basic_concat_test(self, size): - t = ((),) * size - self.assertEquals(len(t), size) - t = t + t - self.assertEquals(len(t), size * 2) - - @bigmemtest(minsize=_2G // 2 + 2, memuse=24) - def test_concat_small(self, size): - return self.basic_concat_test(size) - - @bigmemtest(minsize=_2G + 2, memuse=24) - def test_concat_large(self, size): - return self.basic_concat_test(size) - - @bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5) - def test_contains(self, size): - t = (1, 2, 3, 4, 5) * size - self.assertEquals(len(t), size * 5) - self.failUnless(5 in t) - self.failIf((1, 2, 3, 4, 5) in t) - self.failIf(0 in t) - - @bigmemtest(minsize=_2G + 10, memuse=8) - def test_hash(self, size): - t1 = (0,) * size - h1 = hash(t1) - del t1 - t2 = (0,) * (size + 1) - self.failIf(h1 == hash(t2)) - - @bigmemtest(minsize=_2G + 10, memuse=8) - def test_index_and_slice(self, size): - t = (None,) * size - self.assertEquals(len(t), size) - self.assertEquals(t[-1], None) - self.assertEquals(t[5], None) - self.assertEquals(t[size - 1], None) - self.assertRaises(IndexError, operator.getitem, t, size) - self.assertEquals(t[:5], (None,) * 5) - self.assertEquals(t[-5:], (None,) * 5) - self.assertEquals(t[20:25], (None,) * 5) - self.assertEquals(t[-25:-20], (None,) * 5) - self.assertEquals(t[size - 5:], (None,) * 5) - self.assertEquals(t[size - 5:size], (None,) * 5) - self.assertEquals(t[size - 6:size - 2], (None,) * 4) - self.assertEquals(t[size:size], ()) - self.assertEquals(t[size:size+5], ()) - - # Like test_concat, split in two. - def basic_test_repeat(self, size): - t = ('',) * size - self.assertEquals(len(t), size) - t = t * 2 - self.assertEquals(len(t), size * 2) - - @bigmemtest(minsize=_2G // 2 + 2, memuse=24) - def test_repeat_small(self, size): - return self.basic_test_repeat(size) - - @bigmemtest(minsize=_2G + 2, memuse=24) - def test_repeat_large(self, size): - return self.basic_test_repeat(size) - - # Like test_concat, split in two. - def basic_test_repr(self, size): - t = (0,) * size - s = repr(t) - # The repr of a tuple of 0's is exactly three times the tuple length. - self.assertEquals(len(s), size * 3) - self.assertEquals(s[:5], '(0, 0') - self.assertEquals(s[-5:], '0, 0)') - self.assertEquals(s.count('0'), size) - - @bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3) - def test_repr_small(self, size): - return self.basic_test_repr(size) - - @bigmemtest(minsize=_2G + 2, memuse=8 + 3) - def test_repr_large(self, size): - return self.basic_test_repr(size) - -class ListTest(unittest.TestCase): - - # Like tuples, lists have a small, fixed-sized head and an array of - # pointers to data, so 8 bytes per size. Also like tuples, we make the - # lists hold references to various objects to test their refcount - # limits. - - @bigmemtest(minsize=_2G + 2, memuse=16) - def test_compare(self, size): - l1 = [u''] * size - l2 = [u''] * size - self.failUnless(l1 == l2) - del l2 - l2 = [u''] * (size + 1) - self.failIf(l1 == l2) - del l2 - l2 = [2] * size - self.failIf(l1 == l2) - - # Test concatenating into a single list of more than 2G in length, - # and concatenating a list of more than 2G in length separately, so - # the smaller test still gets run even if there isn't memory for the - # larger test (but we still let the tester know the larger test is - # skipped, in verbose mode.) - def basic_test_concat(self, size): - l = [[]] * size - self.assertEquals(len(l), size) - l = l + l - self.assertEquals(len(l), size * 2) - - @bigmemtest(minsize=_2G // 2 + 2, memuse=24) - def test_concat_small(self, size): - return self.basic_test_concat(size) - - @bigmemtest(minsize=_2G + 2, memuse=24) - def test_concat_large(self, size): - return self.basic_test_concat(size) - - def basic_test_inplace_concat(self, size): - l = [sys.stdout] * size - l += l - self.assertEquals(len(l), size * 2) - self.failUnless(l[0] is l[-1]) - self.failUnless(l[size - 1] is l[size + 1]) - - @bigmemtest(minsize=_2G // 2 + 2, memuse=24) - def test_inplace_concat_small(self, size): - return self.basic_test_inplace_concat(size) - - @bigmemtest(minsize=_2G + 2, memuse=24) - def test_inplace_concat_large(self, size): - return self.basic_test_inplace_concat(size) - - @bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5) - def test_contains(self, size): - l = [1, 2, 3, 4, 5] * size - self.assertEquals(len(l), size * 5) - self.failUnless(5 in l) - self.failIf([1, 2, 3, 4, 5] in l) - self.failIf(0 in l) - - @bigmemtest(minsize=_2G + 10, memuse=8) - def test_hash(self, size): - l = [0] * size - self.failUnlessRaises(TypeError, hash, l) - - @bigmemtest(minsize=_2G + 10, memuse=8) - def test_index_and_slice(self, size): - l = [None] * size - self.assertEquals(len(l), size) - self.assertEquals(l[-1], None) - self.assertEquals(l[5], None) - self.assertEquals(l[size - 1], None) - self.assertRaises(IndexError, operator.getitem, l, size) - self.assertEquals(l[:5], [None] * 5) - self.assertEquals(l[-5:], [None] * 5) - self.assertEquals(l[20:25], [None] * 5) - self.assertEquals(l[-25:-20], [None] * 5) - self.assertEquals(l[size - 5:], [None] * 5) - self.assertEquals(l[size - 5:size], [None] * 5) - self.assertEquals(l[size - 6:size - 2], [None] * 4) - self.assertEquals(l[size:size], []) - self.assertEquals(l[size:size+5], []) - - l[size - 2] = 5 - self.assertEquals(len(l), size) - self.assertEquals(l[-3:], [None, 5, None]) - self.assertEquals(l.count(5), 1) - self.assertRaises(IndexError, operator.setitem, l, size, 6) - self.assertEquals(len(l), size) - - l[size - 7:] = [1, 2, 3, 4, 5] - size -= 2 - self.assertEquals(len(l), size) - self.assertEquals(l[-7:], [None, None, 1, 2, 3, 4, 5]) - - l[:7] = [1, 2, 3, 4, 5] - size -= 2 - self.assertEquals(len(l), size) - self.assertEquals(l[:7], [1, 2, 3, 4, 5, None, None]) - - del l[size - 1] - size -= 1 - self.assertEquals(len(l), size) - self.assertEquals(l[-1], 4) - - del l[-2:] - size -= 2 - self.assertEquals(len(l), size) - self.assertEquals(l[-1], 2) - - del l[0] - size -= 1 - self.assertEquals(len(l), size) - self.assertEquals(l[0], 2) - - del l[:2] - size -= 2 - self.assertEquals(len(l), size) - self.assertEquals(l[0], 4) - - # Like test_concat, split in two. - def basic_test_repeat(self, size): - l = [] * size - self.failIf(l) - l = [''] * size - self.assertEquals(len(l), size) - l = l * 2 - self.assertEquals(len(l), size * 2) - - @bigmemtest(minsize=_2G // 2 + 2, memuse=24) - def test_repeat_small(self, size): - return self.basic_test_repeat(size) - - @bigmemtest(minsize=_2G + 2, memuse=24) - def test_repeat_large(self, size): - return self.basic_test_repeat(size) - - def basic_test_inplace_repeat(self, size): - l = [''] - l *= size - self.assertEquals(len(l), size) - self.failUnless(l[0] is l[-1]) - del l - - l = [''] * size - l *= 2 - self.assertEquals(len(l), size * 2) - self.failUnless(l[size - 1] is l[-1]) - - @bigmemtest(minsize=_2G // 2 + 2, memuse=16) - def test_inplace_repeat_small(self, size): - return self.basic_test_inplace_repeat(size) - - @bigmemtest(minsize=_2G + 2, memuse=16) - def test_inplace_repeat_large(self, size): - return self.basic_test_inplace_repeat(size) - - def basic_test_repr(self, size): - l = [0] * size - s = repr(l) - # The repr of a list of 0's is exactly three times the list length. - self.assertEquals(len(s), size * 3) - self.assertEquals(s[:5], '[0, 0') - self.assertEquals(s[-5:], '0, 0]') - self.assertEquals(s.count('0'), size) - - @bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3) - def test_repr_small(self, size): - return self.basic_test_repr(size) - - @bigmemtest(minsize=_2G + 2, memuse=8 + 3) - def test_repr_large(self, size): - return self.basic_test_repr(size) - - # list overallocates ~1/8th of the total size (on first expansion) so - # the single list.append call puts memuse at 9 bytes per size. - @bigmemtest(minsize=_2G, memuse=9) - def test_append(self, size): - l = [object()] * size - l.append(object()) - self.assertEquals(len(l), size+1) - self.failUnless(l[-3] is l[-2]) - self.failIf(l[-2] is l[-1]) - - @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) - def test_count(self, size): - l = [1, 2, 3, 4, 5] * size - self.assertEquals(l.count(1), size) - self.assertEquals(l.count("1"), 0) - - def basic_test_extend(self, size): - l = [file] * size - l.extend(l) - self.assertEquals(len(l), size * 2) - self.failUnless(l[0] is l[-1]) - self.failUnless(l[size - 1] is l[size + 1]) - - @bigmemtest(minsize=_2G // 2 + 2, memuse=16) - def test_extend_small(self, size): - return self.basic_test_extend(size) - - @bigmemtest(minsize=_2G + 2, memuse=16) - def test_extend_large(self, size): - return self.basic_test_extend(size) - - @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) - def test_index(self, size): - l = [1L, 2L, 3L, 4L, 5L] * size - size *= 5 - self.assertEquals(l.index(1), 0) - self.assertEquals(l.index(5, size - 5), size - 1) - self.assertEquals(l.index(5, size - 5, size), size - 1) - self.assertRaises(ValueError, l.index, 1, size - 4, size) - self.assertRaises(ValueError, l.index, 6L) - - # This tests suffers from overallocation, just like test_append. - @bigmemtest(minsize=_2G + 10, memuse=9) - def test_insert(self, size): - l = [1.0] * size - l.insert(size - 1, "A") - size += 1 - self.assertEquals(len(l), size) - self.assertEquals(l[-3:], [1.0, "A", 1.0]) - - l.insert(size + 1, "B") - size += 1 - self.assertEquals(len(l), size) - self.assertEquals(l[-3:], ["A", 1.0, "B"]) - - l.insert(1, "C") - size += 1 - self.assertEquals(len(l), size) - self.assertEquals(l[:3], [1.0, "C", 1.0]) - self.assertEquals(l[size - 3:], ["A", 1.0, "B"]) - - @bigmemtest(minsize=_2G // 5 + 4, memuse=8 * 5) - def test_pop(self, size): - l = [u"a", u"b", u"c", u"d", u"e"] * size - size *= 5 - self.assertEquals(len(l), size) - - item = l.pop() - size -= 1 - self.assertEquals(len(l), size) - self.assertEquals(item, u"e") - self.assertEquals(l[-2:], [u"c", u"d"]) - - item = l.pop(0) - size -= 1 - self.assertEquals(len(l), size) - self.assertEquals(item, u"a") - self.assertEquals(l[:2], [u"b", u"c"]) - - item = l.pop(size - 2) - size -= 1 - self.assertEquals(len(l), size) - self.assertEquals(item, u"c") - self.assertEquals(l[-2:], [u"b", u"d"]) - - @bigmemtest(minsize=_2G + 10, memuse=8) - def test_remove(self, size): - l = [10] * size - self.assertEquals(len(l), size) - - l.remove(10) - size -= 1 - self.assertEquals(len(l), size) - - # Because of the earlier l.remove(), this append doesn't trigger - # a resize. - l.append(5) - size += 1 - self.assertEquals(len(l), size) - self.assertEquals(l[-2:], [10, 5]) - l.remove(5) - size -= 1 - self.assertEquals(len(l), size) - self.assertEquals(l[-2:], [10, 10]) - - @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) - def test_reverse(self, size): - l = [1, 2, 3, 4, 5] * size - l.reverse() - self.assertEquals(len(l), size * 5) - self.assertEquals(l[-5:], [5, 4, 3, 2, 1]) - self.assertEquals(l[:5], [5, 4, 3, 2, 1]) - - @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) - def test_sort(self, size): - l = [1, 2, 3, 4, 5] * size - l.sort() - self.assertEquals(len(l), size * 5) - self.assertEquals(l.count(1), size) - self.assertEquals(l[:10], [1] * 10) - self.assertEquals(l[-10:], [5] * 10) - -def test_main(): - test_support.run_unittest(StrTest, TupleTest, ListTest) - -if __name__ == '__main__': - if len(sys.argv) > 1: - test_support.set_memlimit(sys.argv[1]) - test_main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-07-01 20:38:39
|
Revision: 4830 http://jython.svn.sourceforge.net/jython/?rev=4830&view=rev Author: zyasoft Date: 2008-07-01 13:38:05 -0700 (Tue, 01 Jul 2008) Log Message: ----------- test_mailbox has been rewritten since 2.2, the version that was committed Removed Paths: ------------- branches/asm/Lib/test/test_mailbox.py Deleted: branches/asm/Lib/test/test_mailbox.py =================================================================== --- branches/asm/Lib/test/test_mailbox.py 2008-07-01 17:21:43 UTC (rev 4829) +++ branches/asm/Lib/test/test_mailbox.py 2008-07-01 20:38:05 UTC (rev 4830) @@ -1,113 +0,0 @@ -import mailbox -import os -import test_support -import time -import unittest - -# cleanup earlier tests -try: - os.unlink(test_support.TESTFN) -except os.error: - pass - - -DUMMY_MESSAGE = """\ -From: som...@du...main -To: me...@my...main - -This is a dummy message. -""" - - -class MaildirTestCase(unittest.TestCase): - - def setUp(self): - # create a new maildir mailbox to work with: - self._dir = test_support.TESTFN - os.mkdir(self._dir) - os.mkdir(os.path.join(self._dir, "cur")) - os.mkdir(os.path.join(self._dir, "tmp")) - os.mkdir(os.path.join(self._dir, "new")) - self._counter = 1 - self._msgfiles = [] - - def tearDown(self): - map(os.unlink, self._msgfiles) - os.rmdir(os.path.join(self._dir, "cur")) - os.rmdir(os.path.join(self._dir, "tmp")) - os.rmdir(os.path.join(self._dir, "new")) - os.rmdir(self._dir) - - def createMessage(self, dir): - t = int(time.time() % 1000000) - pid = self._counter - self._counter += 1 - filename = os.extsep.join((str(t), str(pid), "myhostname", "mydomain")) - tmpname = os.path.join(self._dir, "tmp", filename) - newname = os.path.join(self._dir, dir, filename) - fp = open(tmpname, "w") - self._msgfiles.append(tmpname) - fp.write(DUMMY_MESSAGE) - fp.close() - if hasattr(os, "link"): - os.link(tmpname, newname) - else: - fp = open(newname, "w") - fp.write(DUMMY_MESSAGE) - fp.close() - self._msgfiles.append(newname) - - def assert_msg_exists(self): - msg = self.mbox.next() - self.assert_(msg is not None) - #Force the file closed on Jython since Windows won't allow a file to - #be deleted if something has an open handle on it and garbage collection - #doesn't happen quickly enough to make this occur naturally - if os.name == 'java': - msg.fp.close() - - def test_empty_maildir(self): - """Test an empty maildir mailbox""" - # Test for regression on bug #117490: - # Make sure the boxes attribute actually gets set. - self.mbox = mailbox.Maildir(test_support.TESTFN) - self.assert_(hasattr(self.mbox, "boxes")) - self.assert_(len(self.mbox.boxes) == 0) - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) - - def test_nonempty_maildir_cur(self): - self.createMessage("cur") - self.mbox = mailbox.Maildir(test_support.TESTFN) - self.assert_(len(self.mbox.boxes) == 1) - self.assert_msg_exists() - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) - - def test_nonempty_maildir_new(self): - self.createMessage("new") - self.mbox = mailbox.Maildir(test_support.TESTFN) - self.assert_(len(self.mbox.boxes) == 1) - self.assert_msg_exists() - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) - - def test_nonempty_maildir_both(self): - self.createMessage("cur") - self.createMessage("new") - self.mbox = mailbox.Maildir(test_support.TESTFN) - self.assert_(len(self.mbox.boxes) == 2) - self.assert_msg_exists() - self.assert_msg_exists() - self.assert_(self.mbox.next() is None) - self.assert_(self.mbox.next() is None) - - # XXX We still need more tests! - - -def test_main(): - test_support.run_unittest(MaildirTestCase) - - -if __name__ == "__main__": - test_main() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-07-01 17:21:47
|
Revision: 4829 http://jython.svn.sourceforge.net/jython/?rev=4829&view=rev Author: zyasoft Date: 2008-07-01 10:21:43 -0700 (Tue, 01 Jul 2008) Log Message: ----------- Removed modules/tests that should be updated to CPythonLib. Incidentally, test_cmath now tests that cmath.log takes a base Removed Paths: ------------- branches/asm/Lib/test/test_cmath.py branches/asm/Lib/test/test_heapq.py branches/asm/Lib/uu.py branches/asm/Lib/wsgiref/ Deleted: branches/asm/Lib/test/test_cmath.py =================================================================== --- branches/asm/Lib/test/test_cmath.py 2008-07-01 15:50:43 UTC (rev 4828) +++ branches/asm/Lib/test/test_cmath.py 2008-07-01 17:21:43 UTC (rev 4829) @@ -1,109 +0,0 @@ -#! /usr/bin/env python -""" Simple test script for cmathmodule.c - Roger E. Masse -""" -import cmath -import unittest -from test import test_support -from test.test_support import verbose - -p = cmath.pi -e = cmath.e -if verbose: - print 'PI = ', abs(p) - print 'E = ', abs(e) - - -class CmathTestCase(unittest.TestCase): - def assertAlmostEqual(self, x, y, places=5, msg=None): - unittest.TestCase.assertAlmostEqual(self, x.real, y.real, places, msg) - unittest.TestCase.assertAlmostEqual(self, x.imag, y.imag, places, msg) - - def test_acos(self): - self.assertAlmostEqual(complex(0.936812, -2.30551), - cmath.acos(complex(3, 4))) - - def test_acosh(self): - self.assertAlmostEqual(complex(2.30551, 0.93681), - cmath.acosh(complex(3, 4))) - - def test_asin(self): - self.assertAlmostEqual(complex(0.633984, 2.30551), - cmath.asin(complex(3, 4))) - - def test_asinh(self): - self.assertAlmostEqual(complex(2.29991, 0.917617), - cmath.asinh(complex(3, 4))) - - def test_atan(self): - self.assertAlmostEqual(complex(1.44831, 0.158997), - cmath.atan(complex(3, 4))) - - def test_atanh(self): - self.assertAlmostEqual(complex(0.11750, 1.40992), - cmath.atanh(complex(3, 4))) - - def test_cos(self): - self.assertAlmostEqual(complex(-27.03495, -3.851153), - cmath.cos(complex(3, 4))) - - def test_cosh(self): - self.assertAlmostEqual(complex(-6.58066, -7.58155), - cmath.cosh(complex(3, 4))) - - def test_exp(self): - self.assertAlmostEqual(complex(-13.12878, -15.20078), - cmath.exp(complex(3, 4))) - - def test_log(self): - self.assertAlmostEqual(complex(1.60944, 0.927295), - cmath.log(complex(3, 4))) - - def test_log10(self): - self.assertAlmostEqual(complex(0.69897, 0.40272), - cmath.log10(complex(3, 4))) - - def test_sin(self): - self.assertAlmostEqual(complex(3.853738, -27.01681), - cmath.sin(complex(3, 4))) - - def test_sinh(self): - self.assertAlmostEqual(complex(-6.54812, -7.61923), - cmath.sinh(complex(3, 4))) - - def test_sqrt_real_positive(self): - self.assertAlmostEqual(complex(2, 1), - cmath.sqrt(complex(3, 4))) - - def test_sqrt_real_zero(self): - self.assertAlmostEqual(complex(1.41421, 1.41421), - cmath.sqrt(complex(0, 4))) - - def test_sqrt_real_negative(self): - self.assertAlmostEqual(complex(1, 2), - cmath.sqrt(complex(-3, 4))) - - def test_sqrt_imaginary_zero(self): - self.assertAlmostEqual(complex(0.0, 1.73205), - cmath.sqrt(complex(-3, 0))) - - def test_sqrt_imaginary_negative(self): - self.assertAlmostEqual(complex(1.0, -2.0), - cmath.sqrt(complex(-3, -4))) - - def test_tan(self): - self.assertAlmostEqual(complex(-0.000187346, 0.999356), - cmath.tan(complex(3, 4))) - - def test_tanh(self): - self.assertAlmostEqual(complex(1.00071, 0.00490826), - cmath.tanh(complex(3, 4))) - -def test_main(): - test_support.run_unittest(CmathTestCase) - -if __name__ == "__main__": - test_main() - - - Deleted: branches/asm/Lib/test/test_heapq.py =================================================================== --- branches/asm/Lib/test/test_heapq.py 2008-07-01 15:50:43 UTC (rev 4828) +++ branches/asm/Lib/test/test_heapq.py 2008-07-01 17:21:43 UTC (rev 4829) @@ -1,92 +0,0 @@ -"""Unittests for heapq.""" - -from test.test_support import verify, vereq, verbose, TestFailed - -from heapq import heappush, heappop, heapify, heapreplace -import random - -def check_invariant(heap): - # Check the heap invariant. - for pos, item in enumerate(heap): - if pos: # pos 0 has no parent - parentpos = (pos-1) >> 1 - verify(heap[parentpos] <= item) - -# An iterator returning a heap's elements, smallest-first. -class heapiter(object): - def __init__(self, heap): - self.heap = heap - - def next(self): - try: - return heappop(self.heap) - except IndexError: - raise StopIteration - - def __iter__(self): - return self - -def test_main(): - # 1) Push 100 random numbers and pop them off, verifying all's OK. - heap = [] - data = [] - check_invariant(heap) - for i in range(256): - item = random.random() - data.append(item) - heappush(heap, item) - check_invariant(heap) - results = [] - while heap: - item = heappop(heap) - check_invariant(heap) - results.append(item) - data_sorted = data[:] - data_sorted.sort() - vereq(data_sorted, results) - # 2) Check that the invariant holds for a sorted array - check_invariant(results) - # 3) Naive "N-best" algorithm - heap = [] - for item in data: - heappush(heap, item) - if len(heap) > 10: - heappop(heap) - heap.sort() - vereq(heap, data_sorted[-10:]) - # 4) Test heapify. - for size in range(30): - heap = [random.random() for dummy in range(size)] - heapify(heap) - check_invariant(heap) - # 5) Less-naive "N-best" algorithm, much faster (if len(data) is big - # enough <wink>) than sorting all of data. However, if we had a max - # heap instead of a min heap, it could go faster still via - # heapify'ing all of data (linear time), then doing 10 heappops - # (10 log-time steps). - heap = data[:10] - heapify(heap) - for item in data[10:]: - if item > heap[0]: # this gets rarer the longer we run - heapreplace(heap, item) - vereq(list(heapiter(heap)), data_sorted[-10:]) - # 6) Exercise everything with repeated heapsort checks - for trial in xrange(100): - size = random.randrange(50) - data = [random.randrange(25) for i in range(size)] - if trial & 1: # Half of the time, use heapify - heap = data[:] - heapify(heap) - else: # The rest of the time, use heappush - heap = [] - for item in data: - heappush(heap,item) - data.sort() - sorted = [heappop(heap) for i in range(size)] - vereq(data, sorted) - # Make user happy - if verbose: - print "All OK" - -if __name__ == "__main__": - test_main() Deleted: branches/asm/Lib/uu.py =================================================================== --- branches/asm/Lib/uu.py 2008-07-01 15:50:43 UTC (rev 4828) +++ branches/asm/Lib/uu.py 2008-07-01 17:21:43 UTC (rev 4829) @@ -1,195 +0,0 @@ -#! /usr/bin/env python - -# Copyright 1994 by Lance Ellinghouse -# Cathedral City, California Republic, United States of America. -# All Rights Reserved -# Permission to use, copy, modify, and distribute this software and its -# documentation for any purpose and without fee is hereby granted, -# provided that the above copyright notice appear in all copies and that -# both that copyright notice and this permission notice appear in -# supporting documentation, and that the name of Lance Ellinghouse -# not be used in advertising or publicity pertaining to distribution -# of the software without specific, written prior permission. -# LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO -# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -# FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE -# FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -# -# Modified by Jack Jansen, CWI, July 1995: -# - Use binascii module to do the actual line-by-line conversion -# between ascii and binary. This results in a 1000-fold speedup. The C -# version is still 5 times faster, though. -# - Arguments more compliant with python standard - -"""Implementation of the UUencode and UUdecode functions. - -encode(in_file, out_file [,name, mode]) -decode(in_file [, out_file, mode]) -""" - -import binascii -import os -import sys -from types import StringType - -__all__ = ["Error", "encode", "decode"] - -class Error(Exception): - pass - -def encode(in_file, out_file, name=None, mode=None): - """Uuencode file""" - # - # If in_file is a pathname open it and change defaults - # - if in_file == '-': - in_file = sys.stdin - elif isinstance(in_file, StringType): - if name is None: - name = os.path.basename(in_file) - if mode is None: - try: - mode = os.stat(in_file).st_mode - except AttributeError: - pass - in_file = open(in_file, 'rb') - # - # Open out_file if it is a pathname - # - if out_file == '-': - out_file = sys.stdout - elif isinstance(out_file, StringType): - out_file = open(out_file, 'w') - # - # Set defaults for name and mode - # - if name is None: - name = '-' - if mode is None: - mode = 0666 - # - # Write the data - # - out_file.write('begin %o %s\n' % ((mode&0777),name)) - str = in_file.read(45) - while len(str) > 0: - out_file.write(binascii.b2a_uu(str)) - str = in_file.read(45) - out_file.write(' \nend\n') - - -def decode(in_file, out_file=None, mode=None, quiet=0): - """Decode uuencoded file""" - # - # Open the input file, if needed. - # - if in_file == '-': - in_file = sys.stdin - elif isinstance(in_file, StringType): - in_file = open(in_file) - # - # Read until a begin is encountered or we've exhausted the file - # - while 1: - hdr = in_file.readline() - if not hdr: - raise Error, 'No valid begin line found in input file' - if hdr[:5] != 'begin': - continue - hdrfields = hdr.split(" ", 2) - if len(hdrfields) == 3 and hdrfields[0] == 'begin': - try: - int(hdrfields[1], 8) - break - except ValueError: - pass - if out_file is None: - out_file = hdrfields[2].rstrip() - if os.path.exists(out_file): - raise Error, 'Cannot overwrite existing file: %s' % out_file - if mode is None: - mode = int(hdrfields[1], 8) - # - # Open the output file - # - opened = False - if out_file == '-': - out_file = sys.stdout - elif isinstance(out_file, StringType): - fp = open(out_file, 'wb') - try: - os.path.chmod(out_file, mode) - except AttributeError: - pass - out_file = fp - opened = True - # - # Main decoding loop - # - s = in_file.readline() - while s and s.strip() != 'end': - try: - data = binascii.a2b_uu(s) - except binascii.Error, v: - # Workaround for broken uuencoders by /Fredrik Lundh - nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3 - data = binascii.a2b_uu(s[:nbytes]) - if not quiet: - sys.stderr.write("Warning: %s\n" % str(v)) - out_file.write(data) - s = in_file.readline() - if not s: - raise Error, 'Truncated input file' - if opened: - out_file.close() - -def test(): - """uuencode/uudecode main program""" - import getopt - - dopt = 0 - topt = 0 - input = sys.stdin - output = sys.stdout - ok = 1 - try: - optlist, args = getopt.getopt(sys.argv[1:], 'dt') - except getopt.error: - ok = 0 - if not ok or len(args) > 2: - print 'Usage:', sys.argv[0], '[-d] [-t] [input [output]]' - print ' -d: Decode (in stead of encode)' - print ' -t: data is text, encoded format unix-compatible text' - sys.exit(1) - - for o, a in optlist: - if o == '-d': dopt = 1 - if o == '-t': topt = 1 - - if len(args) > 0: - input = args[0] - if len(args) > 1: - output = args[1] - - if dopt: - if topt: - if isinstance(output, StringType): - output = open(output, 'w') - else: - print sys.argv[0], ': cannot do -t to stdout' - sys.exit(1) - decode(input, output) - else: - if topt: - if isinstance(input, StringType): - input = open(input, 'r') - else: - print sys.argv[0], ': cannot do -t from stdin' - sys.exit(1) - encode(input, output) - -if __name__ == '__main__': - test() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-07-01 15:50:46
|
Revision: 4828 http://jython.svn.sourceforge.net/jython/?rev=4828&view=rev Author: zyasoft Date: 2008-07-01 08:50:43 -0700 (Tue, 01 Jul 2008) Log Message: ----------- Removed modules/tests that are trivially changed with respect to CPythonLib Removed Paths: ------------- branches/asm/Lib/Queue.py branches/asm/Lib/copy.py branches/asm/Lib/test/test_contains.py branches/asm/Lib/test/test_list.py branches/asm/Lib/test/test_math.py branches/asm/Lib/test/test_popen.py branches/asm/Lib/test/test_slice.py branches/asm/Lib/test/test_unicodedata.py branches/asm/Lib/weakref.py Deleted: branches/asm/Lib/Queue.py =================================================================== --- branches/asm/Lib/Queue.py 2008-07-01 13:52:38 UTC (rev 4827) +++ branches/asm/Lib/Queue.py 2008-07-01 15:50:43 UTC (rev 4828) @@ -1,215 +0,0 @@ -"""A multi-producer, multi-consumer queue.""" - -from time import time as _time -from collections import deque - -__all__ = ['Empty', 'Full', 'Queue'] - -class Empty(Exception): - "Exception raised by Queue.get(block=0)/get_nowait()." - pass - -class Full(Exception): - "Exception raised by Queue.put(block=0)/put_nowait()." - pass - -class Queue: - """Create a queue object with a given maximum size. - - If maxsize is <= 0, the queue size is infinite. - """ - def __init__(self, maxsize=0): - try: - import threading - except ImportError: - import dummy_threading as threading - self._init(maxsize) - # mutex must be held whenever the queue is mutating. All methods - # that acquire mutex must release it before returning. mutex - # is shared between the two conditions, so acquiring and - # releasing the conditions also acquires and releases mutex. - self.mutex = threading.Lock() - # Notify not_empty whenever an item is added to the queue; a - # thread waiting to get is notified then. - self.not_empty = threading.Condition(self.mutex) - # Notify not_full whenever an item is removed from the queue; - # a thread waiting to put is notified then. - self.not_full = threading.Condition(self.mutex) - # Notify all_tasks_done whenever the number of unfinished tasks - # drops to zero; thread waiting to join() is notified to resume - self.all_tasks_done = threading.Condition(self.mutex) - self.unfinished_tasks = 0 - - def task_done(self): - """Indicate that a formerly enqueued task is complete. - - Used by Queue consumer threads. For each get() used to fetch a task, - a subsequent call to task_done() tells the queue that the processing - on the task is complete. - - If a join() is currently blocking, it will resume when all items - have been processed (meaning that a task_done() call was received - for every item that had been put() into the queue). - - Raises a ValueError if called more times than there were items - placed in the queue. - """ - self.all_tasks_done.acquire() - try: - unfinished = self.unfinished_tasks - 1 - if unfinished <= 0: - if unfinished < 0: - raise ValueError('task_done() called too many times') - self.all_tasks_done.notifyAll() - self.unfinished_tasks = unfinished - finally: - self.all_tasks_done.release() - - def join(self): - """Blocks until all items in the Queue have been gotten and processed. - - The count of unfinished tasks goes up whenever an item is added to the - queue. The count goes down whenever a consumer thread calls task_done() - to indicate the item was retrieved and all work on it is complete. - - When the count of unfinished tasks drops to zero, join() unblocks. - """ - self.all_tasks_done.acquire() - try: - while self.unfinished_tasks: - self.all_tasks_done.wait() - finally: - self.all_tasks_done.release() - - def qsize(self): - """Return the approximate size of the queue (not reliable!).""" - self.mutex.acquire() - n = self._qsize() - self.mutex.release() - return n - - def empty(self): - """Return True if the queue is empty, False otherwise (not reliable!).""" - self.mutex.acquire() - n = self._empty() - self.mutex.release() - return n - - def full(self): - """Return True if the queue is full, False otherwise (not reliable!).""" - self.mutex.acquire() - n = self._full() - self.mutex.release() - return n - - def put(self, item, block=True, timeout=None): - """Put an item into the queue. - - If optional args 'block' is true and 'timeout' is None (the default), - block if necessary until a free slot is available. If 'timeout' is - a positive number, it blocks at most 'timeout' seconds and raises - the Full exception if no free slot was available within that time. - Otherwise ('block' is false), put an item on the queue if a free slot - is immediately available, else raise the Full exception ('timeout' - is ignored in that case). - """ - self.not_full.acquire() - try: - if not block: - if self._full(): - raise Full - elif timeout is None: - while self._full(): - self.not_full.wait() - else: - if timeout < 0: - raise ValueError("'timeout' must be a positive number") - endtime = _time() + timeout - while self._full(): - remaining = endtime - _time() - if remaining <= 0.0: - raise Full - self.not_full.wait(remaining) - self._put(item) - self.unfinished_tasks += 1 - self.not_empty.notify() - finally: - self.not_full.release() - - def put_nowait(self, item): - """Put an item into the queue without blocking. - - Only enqueue the item if a free slot is immediately available. - Otherwise raise the Full exception. - """ - return self.put(item, False) - - def get(self, block=True, timeout=None): - """Remove and return an item from the queue. - - If optional args 'block' is true and 'timeout' is None (the default), - block if necessary until an item is available. If 'timeout' is - a positive number, it blocks at most 'timeout' seconds and raises - the Empty exception if no item was available within that time. - Otherwise ('block' is false), return an item if one is immediately - available, else raise the Empty exception ('timeout' is ignored - in that case). - """ - self.not_empty.acquire() - try: - if not block: - if self._empty(): - raise Empty - elif timeout is None: - while self._empty(): - self.not_empty.wait() - else: - if timeout < 0: - raise ValueError("'timeout' must be a positive number") - endtime = _time() + timeout - while self._empty(): - remaining = endtime - _time() - if remaining <= 0.0: - raise Empty - self.not_empty.wait(remaining) - item = self._get() - self.not_full.notify() - return item - finally: - self.not_empty.release() - - def get_nowait(self): - """Remove and return an item from the queue without blocking. - - Only get an item if one is immediately available. Otherwise - raise the Empty exception. - """ - return self.get(False) - - # Override these methods to implement other queue organizations - # (e.g. stack or priority queue). - # These will only be called with appropriate locks held - - # Initialize the queue representation - def _init(self, maxsize): - self.maxsize = maxsize - self.queue = deque() - - def _qsize(self): - return len(self.queue) - - # Check whether the queue is empty - def _empty(self): - return not self.queue - - # Check whether the queue is full - def _full(self): - return self.maxsize > 0 and len(self.queue) == self.maxsize - - # Put a new item in the queue - def _put(self, item): - self.queue.append(item) - - # Get an item from the queue - def _get(self): - return self.queue.popleft() Deleted: branches/asm/Lib/copy.py =================================================================== --- branches/asm/Lib/copy.py 2008-07-01 13:52:38 UTC (rev 4827) +++ branches/asm/Lib/copy.py 2008-07-01 15:50:43 UTC (rev 4828) @@ -1,413 +0,0 @@ -"""Generic (shallow and deep) copying operations. - -Interface summary: - - import copy - - x = copy.copy(y) # make a shallow copy of y - x = copy.deepcopy(y) # make a deep copy of y - -For module specific errors, copy.Error is raised. - -The difference between shallow and deep copying is only relevant for -compound objects (objects that contain other objects, like lists or -class instances). - -- A shallow copy constructs a new compound object and then (to the - extent possible) inserts *the same objects* into it that the - original contains. - -- A deep copy constructs a new compound object and then, recursively, - inserts *copies* into it of the objects found in the original. - -Two problems often exist with deep copy operations that don't exist -with shallow copy operations: - - a) recursive objects (compound objects that, directly or indirectly, - contain a reference to themselves) may cause a recursive loop - - b) because deep copy copies *everything* it may copy too much, e.g. - administrative data structures that should be shared even between - copies - -Python's deep copy operation avoids these problems by: - - a) keeping a table of objects already copied during the current - copying pass - - b) letting user-defined classes override the copying operation or the - set of components copied - -This version does not copy types like module, class, function, method, -nor stack trace, stack frame, nor file, socket, window, nor array, nor -any similar types. - -Classes can use the same interfaces to control copying that they use -to control pickling: they can define methods called __getinitargs__(), -__getstate__() and __setstate__(). See the documentation for module -"pickle" for information on these methods. -""" - -import types -from copy_reg import dispatch_table - -class Error(Exception): - pass -error = Error # backward compatibility - -try: - from org.python.core import PyStringMap -except ImportError: - PyStringMap = None - -__all__ = ["Error", "copy", "deepcopy"] - -def copy(x): - """Shallow copy operation on arbitrary Python objects. - - See the module's __doc__ string for more info. - """ - - cls = type(x) - - copier = _copy_dispatch.get(cls) - if copier: - return copier(x) - - copier = getattr(cls, "__copy__", None) - if copier: - return copier(x) - - reductor = dispatch_table.get(cls) - if reductor: - rv = reductor(x) - else: - reductor = getattr(x, "__reduce_ex__", None) - if reductor: - rv = reductor(2) - else: - reductor = getattr(x, "__reduce__", None) - if reductor: - rv = reductor() - else: - raise Error("un(shallow)copyable object of type %s" % cls) - - return _reconstruct(x, rv, 0) - - -_copy_dispatch = d = {} - -def _copy_immutable(x): - return x -for t in (type(None), int, long, float, bool, str, tuple, - frozenset, type, xrange, types.ClassType, - types.BuiltinFunctionType, - types.FunctionType): - d[t] = _copy_immutable -for name in ("ComplexType", "UnicodeType", "CodeType"): - t = getattr(types, name, None) - if t is not None: - d[t] = _copy_immutable - -def _copy_with_constructor(x): - return type(x)(x) -for t in (list, dict, set): - d[t] = _copy_with_constructor - -def _copy_with_copy_method(x): - return x.copy() -if PyStringMap is not None: - d[PyStringMap] = _copy_with_copy_method - -def _copy_inst(x): - if hasattr(x, '__copy__'): - return x.__copy__() - if hasattr(x, '__getinitargs__'): - args = x.__getinitargs__() - y = x.__class__(*args) - else: - y = _EmptyClass() - y.__class__ = x.__class__ - if hasattr(x, '__getstate__'): - state = x.__getstate__() - else: - state = x.__dict__ - if hasattr(y, '__setstate__'): - y.__setstate__(state) - else: - y.__dict__.update(state) - return y -d[types.InstanceType] = _copy_inst - -del d - -def deepcopy(x, memo=None, _nil=[]): - """Deep copy operation on arbitrary Python objects. - - See the module's __doc__ string for more info. - """ - if memo is None: - memo = {} - - d = id(x) - y = memo.get(d, _nil) - if y is not _nil: - return y - - cls = type(x) - - copier = _deepcopy_dispatch.get(cls) - if copier: - y = copier(x, memo) - else: - try: - issc = issubclass(cls, type) - except TypeError: # cls is not a class (old Boost; see SF #502085) - issc = 0 - if issc: - y = _deepcopy_atomic(x, memo) - else: - copier = getattr(x, "__deepcopy__", None) - if copier: - y = copier(memo) - else: - reductor = dispatch_table.get(cls) - if reductor: - rv = reductor(x) - else: - reductor = getattr(x, "__reduce_ex__", None) - if reductor: - rv = reductor(2) - else: - reductor = getattr(x, "__reduce__", None) - if reductor: - rv = reductor() - else: - raise Error( - "un(deep)copyable object of type %s" % cls) - y = _reconstruct(x, rv, 1, memo) - - memo[d] = y - _keep_alive(x, memo) # Make sure x lives at least as long as d - return y - -_deepcopy_dispatch = d = {} - -def _deepcopy_atomic(x, memo): - return x -d[type(None)] = _deepcopy_atomic -d[int] = _deepcopy_atomic -d[long] = _deepcopy_atomic -d[float] = _deepcopy_atomic -d[bool] = _deepcopy_atomic -try: - d[complex] = _deepcopy_atomic -except NameError: - pass -d[str] = _deepcopy_atomic -try: - d[unicode] = _deepcopy_atomic -except NameError: - pass -try: - d[types.CodeType] = _deepcopy_atomic -except AttributeError: - pass -d[type] = _deepcopy_atomic -d[xrange] = _deepcopy_atomic -d[types.ClassType] = _deepcopy_atomic -d[types.BuiltinFunctionType] = _deepcopy_atomic -d[types.FunctionType] = _deepcopy_atomic - -def _deepcopy_list(x, memo): - y = [] - memo[id(x)] = y - for a in x: - y.append(deepcopy(a, memo)) - return y -d[list] = _deepcopy_list - -def _deepcopy_tuple(x, memo): - y = [] - for a in x: - y.append(deepcopy(a, memo)) - d = id(x) - try: - return memo[d] - except KeyError: - pass - for i in range(len(x)): - if x[i] is not y[i]: - y = tuple(y) - break - else: - y = x - memo[d] = y - return y -d[tuple] = _deepcopy_tuple - -def _deepcopy_dict(x, memo): - y = {} - memo[id(x)] = y - for key, value in x.iteritems(): - y[deepcopy(key, memo)] = deepcopy(value, memo) - return y -d[dict] = _deepcopy_dict -if PyStringMap is not None: - d[PyStringMap] = _deepcopy_dict - -def _keep_alive(x, memo): - """Keeps a reference to the object x in the memo. - - Because we remember objects by their id, we have - to assure that possibly temporary objects are kept - alive by referencing them. - We store a reference at the id of the memo, which should - normally not be used unless someone tries to deepcopy - the memo itself... - """ - try: - memo[id(memo)].append(x) - except KeyError: - # aha, this is the first one :-) - memo[id(memo)]=[x] - -def _deepcopy_inst(x, memo): - if hasattr(x, '__deepcopy__'): - return x.__deepcopy__(memo) - if hasattr(x, '__getinitargs__'): - args = x.__getinitargs__() - args = deepcopy(args, memo) - y = x.__class__(*args) - else: - y = _EmptyClass() - y.__class__ = x.__class__ - memo[id(x)] = y - if hasattr(x, '__getstate__'): - state = x.__getstate__() - else: - state = x.__dict__ - state = deepcopy(state, memo) - if hasattr(y, '__setstate__'): - y.__setstate__(state) - else: - y.__dict__.update(state) - return y -d[types.InstanceType] = _deepcopy_inst - -def _reconstruct(x, info, deep, memo=None): - if isinstance(info, str): - return x - assert isinstance(info, tuple) - if memo is None: - memo = {} - n = len(info) - assert n in (2, 3, 4, 5) - callable, args = info[:2] - if n > 2: - state = info[2] - else: - state = {} - if n > 3: - listiter = info[3] - else: - listiter = None - if n > 4: - dictiter = info[4] - else: - dictiter = None - if deep: - args = deepcopy(args, memo) - y = callable(*args) - memo[id(x)] = y - if listiter is not None: - for item in listiter: - if deep: - item = deepcopy(item, memo) - y.append(item) - if dictiter is not None: - for key, value in dictiter: - if deep: - key = deepcopy(key, memo) - value = deepcopy(value, memo) - y[key] = value - if state: - if deep: - state = deepcopy(state, memo) - if hasattr(y, '__setstate__'): - y.__setstate__(state) - else: - if isinstance(state, tuple) and len(state) == 2: - state, slotstate = state - else: - slotstate = None - if state is not None: - y.__dict__.update(state) - if slotstate is not None: - for key, value in slotstate.iteritems(): - setattr(y, key, value) - return y - -del d - -del types - -# Helper for instance creation without calling __init__ -class _EmptyClass: - pass - -def _test(): - l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'], - {'abc': 'ABC'}, (), [], {}] - l1 = copy(l) - print l1==l - l1 = map(copy, l) - print l1==l - l1 = deepcopy(l) - print l1==l - class C: - def __init__(self, arg=None): - self.a = 1 - self.arg = arg - if __name__ == '__main__': - import sys - file = sys.argv[0] - else: - file = __file__ - self.fp = open(file) - self.fp.close() - def __getstate__(self): - return {'a': self.a, 'arg': self.arg} - def __setstate__(self, state): - for key, value in state.iteritems(): - setattr(self, key, value) - def __deepcopy__(self, memo=None): - new = self.__class__(deepcopy(self.arg, memo)) - new.a = self.a - return new - c = C('argument sketch') - l.append(c) - l2 = copy(l) - print l == l2 - print l - print l2 - l2 = deepcopy(l) - print l == l2 - print l - print l2 - l.append({l[1]: l, 'xyz': l[2]}) - l3 = copy(l) - import repr - print map(repr.repr, l) - print map(repr.repr, l1) - print map(repr.repr, l2) - print map(repr.repr, l3) - l3 = deepcopy(l) - import repr - print map(repr.repr, l) - print map(repr.repr, l1) - print map(repr.repr, l2) - print map(repr.repr, l3) - -if __name__ == '__main__': - _test() Deleted: branches/asm/Lib/test/test_contains.py =================================================================== --- branches/asm/Lib/test/test_contains.py 2008-07-01 13:52:38 UTC (rev 4827) +++ branches/asm/Lib/test/test_contains.py 2008-07-01 15:50:43 UTC (rev 4828) @@ -1,133 +0,0 @@ -from test.test_support import TestFailed, have_unicode - -class base_set: - - def __init__(self, el): - self.el = el - -class set(base_set): - - def __contains__(self, el): - return self.el == el - -class seq(base_set): - - def __getitem__(self, n): - return [self.el][n] - -def check(ok, *args): - if not ok: - raise TestFailed, " ".join(map(str, args)) - -a = base_set(1) -b = set(1) -c = seq(1) - -check(1 in b, "1 not in set(1)") -check(0 not in b, "0 in set(1)") -check(1 in c, "1 not in seq(1)") -check(0 not in c, "0 in seq(1)") - -try: - 1 in a - check(0, "in base_set did not raise error") -except TypeError: - pass - -try: - 1 not in a - check(0, "not in base_set did not raise error") -except TypeError: - pass - -# Test char in string - -check('c' in 'abc', "'c' not in 'abc'") -check('d' not in 'abc', "'d' in 'abc'") - -check('' in '', "'' not in ''") -check('' in 'abc', "'' not in 'abc'") - -try: - None in 'abc' - check(0, "None in 'abc' did not raise error") -except TypeError: - pass - - -if have_unicode: - - # Test char in Unicode - - check('c' in unicode('abc'), "'c' not in u'abc'") - check('d' not in unicode('abc'), "'d' in u'abc'") - - check('' in unicode(''), "'' not in u''") - check(unicode('') in '', "u'' not in ''") - check(unicode('') in unicode(''), "u'' not in u''") - check('' in unicode('abc'), "'' not in u'abc'") - check(unicode('') in 'abc', "u'' not in 'abc'") - check(unicode('') in unicode('abc'), "u'' not in u'abc'") - - try: - None in unicode('abc') - check(0, "None in u'abc' did not raise error") - except TypeError: - pass - - # Test Unicode char in Unicode - - check(unicode('c') in unicode('abc'), "u'c' not in u'abc'") - check(unicode('d') not in unicode('abc'), "u'd' in u'abc'") - - # Test Unicode char in string - - check(unicode('c') in 'abc', "u'c' not in 'abc'") - check(unicode('d') not in 'abc', "u'd' in 'abc'") - -# A collection of tests on builtin sequence types -a = range(10) -for i in a: - check(i in a, "%s not in %s" % (`i`, `a`)) -check(16 not in a, "16 not in %s" % `a`) -check(a not in a, "%s not in %s" % (`a`, `a`)) - -a = tuple(a) -for i in a: - check(i in a, "%s not in %s" % (`i`, `a`)) -check(16 not in a, "16 not in %s" % `a`) -check(a not in a, "%s not in %s" % (`a`, `a`)) - -class Deviant1: - """Behaves strangely when compared - - This class is designed to make sure that the contains code - works when the list is modified during the check. - """ - - aList = range(15) - - def __cmp__(self, other): - if other == 12: - self.aList.remove(12) - self.aList.remove(13) - self.aList.remove(14) - return 1 - -check(Deviant1() not in Deviant1.aList, "Deviant1 failed") - -class Deviant2: - """Behaves strangely when compared - - This class raises an exception during comparison. That in - turn causes the comparison to fail with a TypeError. - """ - - def __cmp__(self, other): - if other == 4: - raise RuntimeError, "gotcha" - -try: - check(Deviant2() not in a, "oops") -except TypeError: - pass Deleted: branches/asm/Lib/test/test_list.py =================================================================== --- branches/asm/Lib/test/test_list.py 2008-07-01 13:52:38 UTC (rev 4827) +++ branches/asm/Lib/test/test_list.py 2008-07-01 15:50:43 UTC (rev 4828) @@ -1,38 +0,0 @@ -# From Python 2.4.4 -import unittest -from test import test_support, list_tests - -class ListTest(list_tests.CommonTest): - type2test = list - - def test_truth(self): - super(ListTest, self).test_truth() - self.assert_(not []) - self.assert_([42]) - - def test_identity(self): - self.assert_([] is not []) - - def test_len(self): - super(ListTest, self).test_len() - self.assertEqual(len([]), 0) - self.assertEqual(len([0]), 1) - self.assertEqual(len([0, 1, 2]), 3) - -def test_main(verbose=None): - test_support.run_unittest(ListTest) - - # verify reference counting - import sys - if verbose and hasattr(sys, "gettotalrefcount"): - import gc - counts = [None] * 5 - for i in xrange(len(counts)): - test_support.run_unittest(ListTest) - gc.collect() - counts[i] = sys.gettotalrefcount() - print counts - - -if __name__ == "__main__": - test_main(verbose=True) Deleted: branches/asm/Lib/test/test_math.py =================================================================== --- branches/asm/Lib/test/test_math.py 2008-07-01 13:52:38 UTC (rev 4827) +++ branches/asm/Lib/test/test_math.py 2008-07-01 15:50:43 UTC (rev 4828) @@ -1,209 +0,0 @@ -# XXX Taken from CPython's release25-maint revision 56608 -# Python test set -- math module -# XXXX Should not do tests around zero only - -from test.test_support import TestFailed, verbose - -seps='1e-05' -eps = eval(seps) -print 'math module, testing with eps', seps -import math - -def testit(name, value, expected): - if abs(value-expected) > eps: - raise TestFailed, '%s returned %f, expected %f'%\ - (name, value, expected) - -print 'constants' -testit('pi', math.pi, 3.1415926) -testit('e', math.e, 2.7182818) - -print 'acos' -testit('acos(-1)', math.acos(-1), math.pi) -testit('acos(0)', math.acos(0), math.pi/2) -testit('acos(1)', math.acos(1), 0) - -print 'asin' -testit('asin(-1)', math.asin(-1), -math.pi/2) -testit('asin(0)', math.asin(0), 0) -testit('asin(1)', math.asin(1), math.pi/2) - -print 'atan' -testit('atan(-1)', math.atan(-1), -math.pi/4) -testit('atan(0)', math.atan(0), 0) -testit('atan(1)', math.atan(1), math.pi/4) - -print 'atan2' -testit('atan2(-1, 0)', math.atan2(-1, 0), -math.pi/2) -testit('atan2(-1, 1)', math.atan2(-1, 1), -math.pi/4) -testit('atan2(0, 1)', math.atan2(0, 1), 0) -testit('atan2(1, 1)', math.atan2(1, 1), math.pi/4) -testit('atan2(1, 0)', math.atan2(1, 0), math.pi/2) - -print 'ceil' -testit('ceil(0.5)', math.ceil(0.5), 1) -testit('ceil(1.0)', math.ceil(1.0), 1) -testit('ceil(1.5)', math.ceil(1.5), 2) -testit('ceil(-0.5)', math.ceil(-0.5), 0) -testit('ceil(-1.0)', math.ceil(-1.0), -1) -testit('ceil(-1.5)', math.ceil(-1.5), -1) - -print 'cos' -testit('cos(-pi/2)', math.cos(-math.pi/2), 0) -testit('cos(0)', math.cos(0), 1) -testit('cos(pi/2)', math.cos(math.pi/2), 0) -testit('cos(pi)', math.cos(math.pi), -1) - -print 'cosh' -testit('cosh(0)', math.cosh(0), 1) -testit('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert - -print 'degrees' -testit('degrees(pi)', math.degrees(math.pi), 180.0) -testit('degrees(pi/2)', math.degrees(math.pi/2), 90.0) -testit('degrees(-pi/4)', math.degrees(-math.pi/4), -45.0) - -print 'exp' -testit('exp(-1)', math.exp(-1), 1/math.e) -testit('exp(0)', math.exp(0), 1) -testit('exp(1)', math.exp(1), math.e) - -print 'fabs' -testit('fabs(-1)', math.fabs(-1), 1) -testit('fabs(0)', math.fabs(0), 0) -testit('fabs(1)', math.fabs(1), 1) - -print 'floor' -testit('floor(0.5)', math.floor(0.5), 0) -testit('floor(1.0)', math.floor(1.0), 1) -testit('floor(1.5)', math.floor(1.5), 1) -testit('floor(-0.5)', math.floor(-0.5), -1) -testit('floor(-1.0)', math.floor(-1.0), -1) -testit('floor(-1.5)', math.floor(-1.5), -2) - -print 'fmod' -testit('fmod(10,1)', math.fmod(10,1), 0) -testit('fmod(10,0.5)', math.fmod(10,0.5), 0) -testit('fmod(10,1.5)', math.fmod(10,1.5), 1) -testit('fmod(-10,1)', math.fmod(-10,1), 0) -testit('fmod(-10,0.5)', math.fmod(-10,0.5), 0) -testit('fmod(-10,1.5)', math.fmod(-10,1.5), -1) - -print 'frexp' -def testfrexp(name, (mant, exp), (emant, eexp)): - if abs(mant-emant) > eps or exp != eexp: - raise TestFailed, '%s returned %r, expected %r'%\ - (name, (mant, exp), (emant,eexp)) - -testfrexp('frexp(-1)', math.frexp(-1), (-0.5, 1)) -testfrexp('frexp(0)', math.frexp(0), (0, 0)) -testfrexp('frexp(1)', math.frexp(1), (0.5, 1)) -testfrexp('frexp(2)', math.frexp(2), (0.5, 2)) - -print 'hypot' -testit('hypot(0,0)', math.hypot(0,0), 0) -testit('hypot(3,4)', math.hypot(3,4), 5) - -print 'ldexp' -testit('ldexp(0,1)', math.ldexp(0,1), 0) -testit('ldexp(1,1)', math.ldexp(1,1), 2) -testit('ldexp(1,-1)', math.ldexp(1,-1), 0.5) -testit('ldexp(-1,1)', math.ldexp(-1,1), -2) - -print 'log' -testit('log(1/e)', math.log(1/math.e), -1) -testit('log(1)', math.log(1), 0) -testit('log(e)', math.log(math.e), 1) -testit('log(32,2)', math.log(32,2), 5) -testit('log(10**40, 10)', math.log(10**40, 10), 40) -testit('log(10**40, 10**20)', math.log(10**40, 10**20), 2) - -print 'log10' -testit('log10(0.1)', math.log10(0.1), -1) -testit('log10(1)', math.log10(1), 0) -testit('log10(10)', math.log10(10), 1) - -print 'modf' -def testmodf(name, (v1, v2), (e1, e2)): - if abs(v1-e1) > eps or abs(v2-e2): - raise TestFailed, '%s returned %r, expected %r'%\ - (name, (v1,v2), (e1,e2)) - -testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0)) -testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0)) - -print 'pow' -testit('pow(0,1)', math.pow(0,1), 0) -testit('pow(1,0)', math.pow(1,0), 1) -testit('pow(2,1)', math.pow(2,1), 2) -testit('pow(2,-1)', math.pow(2,-1), 0.5) - -print 'radians' -testit('radians(180)', math.radians(180), math.pi) -testit('radians(90)', math.radians(90), math.pi/2) -testit('radians(-45)', math.radians(-45), -math.pi/4) - -print 'sin' -testit('sin(0)', math.sin(0), 0) -testit('sin(pi/2)', math.sin(math.pi/2), 1) -testit('sin(-pi/2)', math.sin(-math.pi/2), -1) - -print 'sinh' -testit('sinh(0)', math.sinh(0), 0) -testit('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1) -testit('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0) - -print 'sqrt' -testit('sqrt(0)', math.sqrt(0), 0) -testit('sqrt(1)', math.sqrt(1), 1) -testit('sqrt(4)', math.sqrt(4), 2) - -print 'tan' -testit('tan(0)', math.tan(0), 0) -testit('tan(pi/4)', math.tan(math.pi/4), 1) -testit('tan(-pi/4)', math.tan(-math.pi/4), -1) - -print 'tanh' -testit('tanh(0)', math.tanh(0), 0) -testit('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0) - -# RED_FLAG 16-Oct-2000 Tim -# While 2.0 is more consistent about exceptions than previous releases, it -# still fails this part of the test on some platforms. For now, we only -# *run* test_exceptions() in verbose mode, so that this isn't normally -# tested. - -def test_exceptions(): - print 'exceptions' - try: - x = math.exp(-1000000000) - except: - # mathmodule.c is failing to weed out underflows from libm, or - # we've got an fp format with huge dynamic range - raise TestFailed("underflowing exp() should not have raised " - "an exception") - if x != 0: - raise TestFailed("underflowing exp() should have returned 0") - - # If this fails, probably using a strict IEEE-754 conforming libm, and x - # is +Inf afterwards. But Python wants overflows detected by default. - try: - x = math.exp(1000000000) - except OverflowError: - pass - else: - raise TestFailed("overflowing exp() didn't trigger OverflowError") - - # If this fails, it could be a puzzle. One odd possibility is that - # mathmodule.c's macros are getting confused while comparing - # Inf (HUGE_VAL) to a NaN, and artificially setting errno to ERANGE - # as a result (and so raising OverflowError instead). - try: - x = math.sqrt(-1.0) - except ValueError: - pass - else: - raise TestFailed("sqrt(-1) didn't raise ValueError") - -if verbose: - test_exceptions() Deleted: branches/asm/Lib/test/test_popen.py =================================================================== --- branches/asm/Lib/test/test_popen.py 2008-07-01 13:52:38 UTC (rev 4827) +++ branches/asm/Lib/test/test_popen.py 2008-07-01 15:50:43 UTC (rev 4828) @@ -1,41 +0,0 @@ -#! /usr/bin/env python -"""Basic tests for os.popen() - - Particularly useful for platforms that fake popen. -""" - -import os -import sys -from test.test_support import TestSkipped -from os import popen - -# Test that command-lines get down as we expect. -# To do this we execute: -# python -c "import sys;print sys.argv" {rest_of_commandline} -# This results in Python being spawned and printing the sys.argv list. -# We can then eval() the result of this, and see what each argv was. -python = sys.executable -if not sys.executable: - raise TestSkipped, 'sys.executable undefined on this platform' -if ' ' in python: - python = '"' + python + '"' # quote embedded space for cmdline -def _do_test_commandline(cmdline, expected): - cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline) - data = popen(cmd).read() - got = eval(data)[1:] # strip off argv[0] - if got != expected: - print "Error in popen commandline handling." - print " executed '%s', expected '%r', but got '%r'" \ - % (cmdline, expected, got) - -def _test_commandline(): - _do_test_commandline("foo bar", ["foo", "bar"]) - _do_test_commandline('foo "spam and eggs" "silly walk"', ["foo", "spam and eggs", "silly walk"]) - _do_test_commandline('foo "a \\"quoted\\" arg" bar', ["foo", 'a "quoted" arg', "bar"]) - print "popen seemed to process the command-line correctly" - -def main(): - print "Test popen:" - _test_commandline() - -main() Deleted: branches/asm/Lib/test/test_slice.py =================================================================== --- branches/asm/Lib/test/test_slice.py 2008-07-01 13:52:38 UTC (rev 4827) +++ branches/asm/Lib/test/test_slice.py 2008-07-01 15:50:43 UTC (rev 4828) @@ -1,99 +0,0 @@ -# tests for slice objects; in particular the indices method. - -import unittest -from test import test_support - -import sys - -class SliceTest(unittest.TestCase): - - def test_constructor(self): - self.assertRaises(TypeError, slice) - self.assertRaises(TypeError, slice, 1, 2, 3, 4) - - def test_repr(self): - self.assertEqual(repr(slice(1, 2, 3)), "slice(1, 2, 3)") - - def test_hash(self): - # Verify clearing of SF bug #800796 - self.assertRaises(TypeError, hash, slice(5)) - self.assertRaises(TypeError, slice(5).__hash__) - - def test_cmp(self): - s1 = slice(1, 2, 3) - s2 = slice(1, 2, 3) - s3 = slice(1, 2, 4) - self.assertEqual(s1, s2) - self.assertNotEqual(s1, s3) - - class Exc(Exception): - pass - - class BadCmp(object): - def __eq__(self, other): - raise Exc - - s1 = slice(BadCmp()) - s2 = slice(BadCmp()) - self.assertRaises(Exc, cmp, s1, s2) - self.assertEqual(s1, s1) - - s1 = slice(1, BadCmp()) - s2 = slice(1, BadCmp()) - self.assertEqual(s1, s1) - self.assertRaises(Exc, cmp, s1, s2) - - s1 = slice(1, 2, BadCmp()) - s2 = slice(1, 2, BadCmp()) - self.assertEqual(s1, s1) - self.assertRaises(Exc, cmp, s1, s2) - - def test_members(self): - s = slice(1) - self.assertEqual(s.start, None) - self.assertEqual(s.stop, 1) - self.assertEqual(s.step, None) - - s = slice(1, 2) - self.assertEqual(s.start, 1) - self.assertEqual(s.stop, 2) - self.assertEqual(s.step, None) - - s = slice(1, 2, 3) - self.assertEqual(s.start, 1) - self.assertEqual(s.stop, 2) - self.assertEqual(s.step, 3) - - class AnyClass: - pass - - obj = AnyClass() - s = slice(obj) - self.assert_(s.stop is obj) - - def test_indices(self): - self.assertEqual(slice(None ).indices(10), (0, 10, 1)) - self.assertEqual(slice(None, None, 2).indices(10), (0, 10, 2)) - self.assertEqual(slice(1, None, 2).indices(10), (1, 10, 2)) - self.assertEqual(slice(None, None, -1).indices(10), (9, -1, -1)) - self.assertEqual(slice(None, None, -2).indices(10), (9, -1, -2)) - self.assertEqual(slice(3, None, -2).indices(10), (3, -1, -2)) - self.assertEqual( - slice(-100, 100 ).indices(10), - slice(None).indices(10) - ) - self.assertEqual( - slice(100, -100, -1).indices(10), - slice(None, None, -1).indices(10) - ) - self.assertEqual(slice(-100L, 100L, 2L).indices(10), (0, 10, 2)) - - self.assertEqual(range(10)[::sys.maxint - 1], [0]) - - self.assertRaises(OverflowError, slice(None).indices, 1L<<100) - -def test_main(): - test_support.run_unittest(SliceTest) - -if __name__ == "__main__": - test_main() Deleted: branches/asm/Lib/test/test_unicodedata.py =================================================================== --- branches/asm/Lib/test/test_unicodedata.py 2008-07-01 13:52:38 UTC (rev 4827) +++ branches/asm/Lib/test/test_unicodedata.py 2008-07-01 15:50:43 UTC (rev 4828) @@ -1,214 +0,0 @@ -""" Test script for the unicodedata module. - - Written by Marc-Andre Lemburg (ma...@le...). - - (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. - -"""#" -import unicodedata -import unittest, test.test_support -import sha - -encoding = 'utf-8' - - -### Run tests - -class UnicodeMethodsTest(unittest.TestCase): - - # update this, if the database changes - expectedchecksum = 'a37276dc2c158bef6dfd908ad34525c97180fad9' - - def test_method_checksum(self): - h = sha.sha() - for i in range(65536): - char = unichr(i) - data = [ - # Predicates (single char) - u"01"[char.isalnum()], - u"01"[char.isalpha()], - u"01"[char.isdecimal()], - u"01"[char.isdigit()], - u"01"[char.islower()], - u"01"[char.isnumeric()], - u"01"[char.isspace()], - u"01"[char.istitle()], - u"01"[char.isupper()], - - # Predicates (multiple chars) - u"01"[(char + u'abc').isalnum()], - u"01"[(char + u'abc').isalpha()], - u"01"[(char + u'123').isdecimal()], - u"01"[(char + u'123').isdigit()], - u"01"[(char + u'abc').islower()], - u"01"[(char + u'123').isnumeric()], - u"01"[(char + u' \t').isspace()], - u"01"[(char + u'abc').istitle()], - u"01"[(char + u'ABC').isupper()], - - # Mappings (single char) - char.lower(), - char.upper(), - char.title(), - - # Mappings (multiple chars) - (char + u'abc').lower(), - (char + u'ABC').upper(), - (char + u'abc').title(), - (char + u'ABC').title(), - - ] - h.update(u''.join(data).encode(encoding)) - result = h.hexdigest() - self.assertEqual(result, self.expectedchecksum) - -class UnicodeDatabaseTest(unittest.TestCase): - - def setUp(self): - # In case unicodedata is not available, this will raise an ImportError, - # but the other test cases will still be run - import unicodedata - self.db = unicodedata - - def tearDown(self): - del self.db - -class UnicodeFunctionsTest(UnicodeDatabaseTest): - - # update this, if the database changes - expectedchecksum = 'cfe20a967a450ebc82ca68c3e4eed344164e11af' - - def test_function_checksum(self): - data = [] - h = sha.sha() - - for i in range(0x10000): - char = unichr(i) - data = [ - # Properties - str(self.db.digit(char, -1)), - str(self.db.numeric(char, -1)), - str(self.db.decimal(char, -1)), - self.db.category(char), - self.db.bidirectional(char), - self.db.decomposition(char), - str(self.db.mirrored(char)), - str(self.db.combining(char)), - ] - h.update(''.join(data)) - result = h.hexdigest() - self.assertEqual(result, self.expectedchecksum) - - def test_digit(self): - self.assertEqual(self.db.digit(u'A', None), None) - self.assertEqual(self.db.digit(u'9'), 9) - self.assertEqual(self.db.digit(u'\u215b', None), None) - self.assertEqual(self.db.digit(u'\u2468'), 9) - - self.assertRaises(TypeError, self.db.digit) - self.assertRaises(TypeError, self.db.digit, u'xx') - self.assertRaises(ValueError, self.db.digit, u'x') - - def test_numeric(self): - self.assertEqual(self.db.numeric(u'A',None), None) - self.assertEqual(self.db.numeric(u'9'), 9) - self.assertEqual(self.db.numeric(u'\u215b'), 0.125) - self.assertEqual(self.db.numeric(u'\u2468'), 9.0) - - self.assertRaises(TypeError, self.db.numeric) - self.assertRaises(TypeError, self.db.numeric, u'xx') - self.assertRaises(ValueError, self.db.numeric, u'x') - - def test_decimal(self): - self.assertEqual(self.db.decimal(u'A',None), None) - self.assertEqual(self.db.decimal(u'9'), 9) - self.assertEqual(self.db.decimal(u'\u215b', None), None) - self.assertEqual(self.db.decimal(u'\u2468', None), None) - - self.assertRaises(TypeError, self.db.decimal) - self.assertRaises(TypeError, self.db.decimal, u'xx') - self.assertRaises(ValueError, self.db.decimal, u'x') - - def test_category(self): - self.assertEqual(self.db.category(u'\uFFFE'), 'Cn') - self.assertEqual(self.db.category(u'a'), 'Ll') - self.assertEqual(self.db.category(u'A'), 'Lu') - - self.assertRaises(TypeError, self.db.category) - self.assertRaises(TypeError, self.db.category, u'xx') - - def test_bidirectional(self): - self.assertEqual(self.db.bidirectional(u'\uFFFE'), '') - self.assertEqual(self.db.bidirectional(u' '), 'WS') - self.assertEqual(self.db.bidirectional(u'A'), 'L') - - self.assertRaises(TypeError, self.db.bidirectional) - self.assertRaises(TypeError, self.db.bidirectional, u'xx') - - def test_decomposition(self): - self.assertEqual(self.db.decomposition(u'\uFFFE'),'') - self.assertEqual(self.db.decomposition(u'\u00bc'), '<fraction> 0031 2044 0034') - - self.assertRaises(TypeError, self.db.decomposition) - self.assertRaises(TypeError, self.db.decomposition, u'xx') - - def test_mirrored(self): - self.assertEqual(self.db.mirrored(u'\uFFFE'), 0) - self.assertEqual(self.db.mirrored(u'a'), 0) - self.assertEqual(self.db.mirrored(u'\u2201'), 1) - - self.assertRaises(TypeError, self.db.mirrored) - self.assertRaises(TypeError, self.db.mirrored, u'xx') - - def test_combining(self): - self.assertEqual(self.db.combining(u'\uFFFE'), 0) - self.assertEqual(self.db.combining(u'a'), 0) - self.assertEqual(self.db.combining(u'\u20e1'), 230) - - self.assertRaises(TypeError, self.db.combining) - self.assertRaises(TypeError, self.db.combining, u'xx') - - def test_normalize(self): - self.assertRaises(TypeError, self.db.normalize) - self.assertRaises(ValueError, self.db.normalize, 'unknown', u'xx') - # The rest can be found in test_normalization.py - # which requires an external file. - - -class UnicodeMiscTest(UnicodeDatabaseTest): - - def test_decimal_numeric_consistent(self): - # Test that decimal and numeric are consistent, - # i.e. if a character has a decimal value, - # it's numeric value should be the same. - count = 0 - for i in xrange(0x10000): - c = unichr(i) - dec = self.db.decimal(c, -1) - if dec != -1: - self.assertEqual(dec, self.db.numeric(c)) - count += 1 - self.assert_(count >= 10) # should have tested at least the ASCII digits - - def test_digit_numeric_consistent(self): - # Test that digit and numeric are consistent, - # i.e. if a character has a digit value, - # it's numeric value should be the same. - count = 0 - for i in xrange(0x10000): - c = unichr(i) - dec = self.db.digit(c, -1) - if dec != -1: - self.assertEqual(dec, self.db.numeric(c)) - count += 1 - self.assert_(count >= 10) # should have tested at least the ASCII digits - -def test_main(): - test.test_support.run_unittest( - UnicodeMiscTest, - UnicodeMethodsTest, - UnicodeFunctionsTest - ) - -if __name__ == "__main__": - test_main() Deleted: branches/asm/Lib/weakref.py =================================================================== --- branches/asm/Lib/weakref.py 2008-07-01 13:52:38 UTC (rev 4827) +++ branches/asm/Lib/weakref.py 2008-07-01 15:50:43 UTC (rev 4828) @@ -1,355 +0,0 @@ -"""Weak reference support for Python. - -This module is an implementation of PEP 205: - -http://python.sourceforge.net/peps/pep-0205.html -""" - -# Naming convention: Variables named "wr" are weak reference objects; -# they are called this instead of "ref" to avoid name collisions with -# the module-global ref() function imported from _weakref. - -import UserDict - -from _weakref import \ - getweakrefcount, \ - getweakrefs, \ - ref, \ - proxy, \ - CallableProxyType, \ - ProxyType, \ - ReferenceType - -from exceptions import ReferenceError - - -ProxyTypes = (ProxyType, CallableProxyType) - -__all__ = ["ref", "proxy", "getweakrefcount", "getweakrefs", - "WeakKeyDictionary", "ReferenceType", "ProxyType", - "CallableProxyType", "ProxyTypes", "WeakValueDictionary"] - - -class WeakValueDictionary(UserDict.UserDict): - """Mapping class that references values weakly. - - Entries in the dictionary will be discarded when no strong - reference to the value exists anymore - """ - # We inherit the constructor without worrying about the input - # dictionary; since it uses our .update() method, we get the right - # checks (if the other dictionary is a WeakValueDictionary, - # objects are unwrapped on the way out, and we always wrap on the - # way in). - - def __init__(self, *args, **kw): - def remove(wr, selfref=ref(self)): - self = selfref() - if self is not None: - del self.data[wr.key] - self._remove = remove - UserDict.UserDict.__init__(self, *args, **kw) - - def __getitem__(self, key): - o = self.data[key]() - if o is None: - raise KeyError, key - else: - return o - - def __contains__(self, key): - try: - o = self.data[key]() - except KeyError: - return False - return o is not None - - def has_key(self, key): - try: - o = self.data[key]() - except KeyError: - return False - return o is not None - - def __repr__(self): - return "<WeakValueDictionary at %s>" % id(self) - - def __setitem__(self, key, value): - self.data[key] = KeyedRef(value, self._remove, key) - - def copy(self): - new = WeakValueDictionary() - for key, wr in self.data.items(): - o = wr() - if o is not None: - new[key] = o - return new - - def get(self, key, default=None): - try: - wr = self.data[key] - except KeyError: - return default - else: - o = wr() - if o is None: - # This should only happen - return default - else: - return o - - def items(self): - L = [] - for key, wr in self.data.items(): - o = wr() - if o is not None: - L.append((key, o)) - return L - - def iteritems(self): - for wr in self.data.itervalues(): - value = wr() - if value is not None: - yield wr.key, value - - def iterkeys(self): - return self.data.iterkeys() - - def __iter__(self): - return self.data.iterkeys() - - def itervaluerefs(self): - """Return an iterator that yields the weak references to the values. - - The references are not guaranteed to be 'live' at the time - they are used, so the result of calling the references needs - to be checked before being used. This can be used to avoid - creating references that will cause the garbage collector to - keep the values around longer than needed. - - """ - return self.data.itervalues() - - def itervalues(self): - for wr in self.data.itervalues(): - obj = wr() - if obj is not None: - yield obj - - def popitem(self): - while 1: - key, wr = self.data.popitem() - o = wr() - if o is not None: - return key, o - - def pop(self, key, *args): - try: - o = self.data.pop(key)() - except KeyError: - if args: - return args[0] - raise - if o is None: - raise KeyError, key - else: - return o - - def setdefault(self, key, default=None): - try: - wr = self.data[key] - except KeyError: - self.data[key] = KeyedRef(default, self._remove, key) - return default - else: - return wr() - - def update(self, dict=None, **kwargs): - d = self.data - if dict is not None: - if not hasattr(dict, "items"): - dict = type({})(dict) - for key, o in dict.items(): - d[key] = KeyedRef(o, self._remove, key) - if len(kwargs): - self.update(kwargs) - - def valuerefs(self): - """Return a list of weak references to the values. - - The references are not guaranteed to be 'live' at the time - they are used, so the result of calling the references needs - to be checked before being used. This can be used to avoid - creating references that will cause the garbage collector to - keep the values around longer than needed. - - """ - return self.data.values() - - def values(self): - L = [] - for wr in self.data.values(): - o = wr() - if o is not None: - L.append(o) - return L - - -class KeyedRef(ref): - """Specialized reference that includes a key corresponding to the value. - - This is used in the WeakValueDictionary to avoid having to create - a function object for each key stored in the mapping. A shared - callback object can use the 'key' attribute of a KeyedRef instead - of getting a reference to the key from an enclosing scope. - - """ - - __slots__ = "key", - - def __new__(type, ob, callback, key): - self = ref.__new__(type, ob, callback) - self.key = key - return self - - def __init__(self, ob, callback, key): - super(KeyedRef, self).__init__(ob, callback) - - -class WeakKeyDictionary(UserDict.UserDict): - """ Mapping class that references keys weakly. - - Entries in the dictionary will be discarded when there is no - longer a strong reference to the key. This can be used to - associate additional data with an object owned by other parts of - an application without adding attributes to those objects. This - can be especially useful with objects that override attribute - accesses. - """ - - def __init__(self, dict=None): - self.data = {} - def remove(k, selfref=ref(self)): - self = selfref() - if self is not None: - del self.data[k] - self._remove = remove - if dict is not None: self.update(dict) - - def __delitem__(self, key): - del self.data[ref(key)] - - def __getitem__(self, key): - return self.data[ref(key)] - - def __repr__(self): - return "<WeakKeyDictionary at %s>" % id(self) - - def __setitem__(self, key, value): - self.data[ref(key, self._remove)] = value - - def copy(self): - new = WeakKeyDictionary() - for key, value in self.data.items(): - o = key() - if o is not None: - new[o] = value - return new - - def get(self, key, default=None): - return self.data.get(ref(key),default) - - def has_key(self, key): - try: - wr = ref(key) - except TypeError: - return 0 - return wr in self.data - - def __contains__(self, key): - try: - wr = ref(key) - except TypeError: - return 0 - return wr in self.data - - def items(self): - L = [] - for key, value in self.data.items(): - o = key() - if o is not None: - L.append((o, value)) - return L - - def iteritems(self): - for wr, value in self.data.iteritems(): - key = wr() - if key is not None: - yield key, value - - def iterkeyrefs(self): - """Return an iterator that yields the weak references to the keys. - - The references are not guaranteed to be 'live' at the time - they are used, so the result of calling the references needs - to be checked before being used. This can be used to avoid - creating references that will cause the garbage collector to - keep the keys around longer than needed. - - """ - return self.data.iterkeys() - - def iterkeys(self): - for wr in self.data.iterkeys(): - obj = wr() - if obj is not None: - yield obj - - def __iter__(self): - return self.iterkeys() - - def itervalues(self): - return self.data.itervalues() - - def keyrefs(self): - """Return a list of weak references to the keys. - - The references are not guaranteed to be 'live' at the time - they are used, so the result of calling the references needs - to be checked before being used. This can be used to avoid - creating references that will cause the garbage collector to - keep the keys around longer than needed. - - """ - return self.data.keys() - - def keys(self): - L = [] - for wr in self.data.keys(): - o = wr() - if o is not None: - L.append(o) - return L - - def popitem(self): - while 1: - key, value = self.data.popitem() - o = key() - if o is not None: - return o, value - - def pop(self, key, *args): - return self.data.pop(ref(key), *args) - - def setdefault(self, key, default=None): - return self.data.setdefault(ref(key, self._remove),default) - - def update(self, dict=None, **kwargs): - d = self.data - if dict is not None: - if not hasattr(dict, "items"): - dict = type({})(dict) - for key, value in dict.items(): - d[ref(key, self._remove)] = value - if len(kwargs): - self.update(kwargs) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-07-01 13:52:44
|
Revision: 4827 http://jython.svn.sourceforge.net/jython/?rev=4827&view=rev Author: zyasoft Date: 2008-07-01 06:52:38 -0700 (Tue, 01 Jul 2008) Log Message: ----------- Removed modules and tests exactly duplicated from CPythonLib Removed Paths: ------------- branches/asm/Lib/UserString.py branches/asm/Lib/__future__.py branches/asm/Lib/runpy.py branches/asm/Lib/test/mapping_tests.py branches/asm/Lib/test/test_bisect.py branches/asm/Lib/test/test_call.py branches/asm/Lib/test/test_contextlib.py branches/asm/Lib/test/test_dict.py branches/asm/Lib/test/test_funcattrs.py branches/asm/Lib/test/test_generators.py branches/asm/Lib/test/test_iterlen.py branches/asm/Lib/test/test_queue.py branches/asm/Lib/test/test_runpy.py branches/asm/Lib/test/test_wsgiref.py Deleted: branches/asm/Lib/UserString.py =================================================================== --- branches/asm/Lib/UserString.py 2008-06-30 18:08:37 UTC (rev 4826) +++ branches/asm/Lib/UserString.py 2008-07-01 13:52:38 UTC (rev 4827) @@ -1,194 +0,0 @@ -#!/usr/bin/env python -## vim:ts=4:et:nowrap -"""A user-defined wrapper around string objects - -Note: string objects have grown methods in Python 1.6 -This module requires Python 1.6 or later. -""" -import sys - -__all__ = ["UserString","MutableString"] - -class UserString: - def __init__(self, seq): - if isinstance(seq, basestring): - self.data = seq - elif isinstance(seq, UserString): - self.data = seq.data[:] - else: - self.data = str(seq) - def __str__(self): return str(self.data) - def __repr__(self): return repr(self.data) - def __int__(self): return int(self.data) - def __long__(self): return long(self.data) - def __float__(self): return float(self.data) - def __complex__(self): return complex(self.data) - def __hash__(self): return hash(self.data) - - def __cmp__(self, string): - if isinstance(string, UserString): - return cmp(self.data, string.data) - else: - return cmp(self.data, string) - def __contains__(self, char): - return char in self.data - - def __len__(self): return len(self.data) - def __getitem__(self, index): return self.__class__(self.data[index]) - def __getslice__(self, start, end): - start = max(start, 0); end = max(end, 0) - return self.__class__(self.data[start:end]) - - def __add__(self, other): - if isinstance(other, UserString): - return self.__class__(self.data + other.data) - elif isinstance(other, basestring): - return self.__class__(self.data + other) - else: - return self.__class__(self.data + str(other)) - def __radd__(self, other): - if isinstance(other, basestring): - return self.__class__(other + self.data) - else: - return self.__class__(str(other) + self.data) - def __mul__(self, n): - return self.__class__(self.data*n) - __rmul__ = __mul__ - def __mod__(self, args): - return self.__class__(self.data % args) - - # the following methods are defined in alphabetical order: - def capitalize(self): return self.__class__(self.data.capitalize()) - def center(self, width, *args): - return self.__class__(self.data.center(width, *args)) - def count(self, sub, start=0, end=sys.maxint): - return self.data.count(sub, start, end) - def decode(self, encoding=None, errors=None): # XXX improve this? - if encoding: - if errors: - return self.__class__(self.data.decode(encoding, errors)) - else: - return self.__class__(self.data.decode(encoding)) - else: - return self.__class__(self.data.decode()) - def encode(self, encoding=None, errors=None): # XXX improve this? - if encoding: - if errors: - return self.__class__(self.data.encode(encoding, errors)) - else: - return self.__class__(self.data.encode(encoding)) - else: - return self.__class__(self.data.encode()) - def endswith(self, suffix, start=0, end=sys.maxint): - return self.data.endswith(suffix, start, end) - def expandtabs(self, tabsize=8): - return self.__class__(self.data.expandtabs(tabsize)) - def find(self, sub, start=0, end=sys.maxint): - return self.data.find(sub, start, end) - def index(self, sub, start=0, end=sys.maxint): - return self.data.index(sub, start, end) - def isalpha(self): return self.data.isalpha() - def isalnum(self): return self.data.isalnum() - def isdecimal(self): return self.data.isdecimal() - def isdigit(self): return self.data.isdigit() - def islower(self): return self.data.islower() - def isnumeric(self): return self.data.isnumeric() - def isspace(self): return self.data.isspace() - def istitle(self): return self.data.istitle() - def isupper(self): return self.data.isupper() - def join(self, seq): return self.data.join(seq) - def ljust(self, width, *args): - return self.__class__(self.data.ljust(width, *args)) - def lower(self): return self.__class__(self.data.lower()) - def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars)) - def partition(self, sep): - return self.data.partition(sep) - def replace(self, old, new, maxsplit=-1): - return self.__class__(self.data.replace(old, new, maxsplit)) - def rfind(self, sub, start=0, end=sys.maxint): - return self.data.rfind(sub, start, end) - def rindex(self, sub, start=0, end=sys.maxint): - return self.data.rindex(sub, start, end) - def rjust(self, width, *args): - return self.__class__(self.data.rjust(width, *args)) - def rpartition(self, sep): - return self.data.rpartition(sep) - def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars)) - def split(self, sep=None, maxsplit=-1): - return self.data.split(sep, maxsplit) - def rsplit(self, sep=None, maxsplit=-1): - return self.data.rsplit(sep, maxsplit) - def splitlines(self, keepends=0): return self.data.splitlines(keepends) - def startswith(self, prefix, start=0, end=sys.maxint): - return self.data.startswith(prefix, start, end) - def strip(self, chars=None): return self.__class__(self.data.strip(chars)) - def swapcase(self): return self.__class__(self.data.swapcase()) - def title(self): return self.__class__(self.data.title()) - def translate(self, *args): - return self.__class__(self.data.translate(*args)) - def upper(self): return self.__class__(self.data.upper()) - def zfill(self, width): return self.__class__(self.data.zfill(width)) - -class MutableString(UserString): - """mutable string objects - - Python strings are immutable objects. This has the advantage, that - strings may be used as dictionary keys. If this property isn't needed - and you insist on changing string values in place instead, you may cheat - and use MutableString. - - But the purpose of this class is an educational one: to prevent - people from inventing their own mutable string class derived - from UserString and than forget thereby to remove (override) the - __hash__ method inherited from UserString. This would lead to - errors that would be very hard to track down. - - A faster and better solution is to rewrite your program using lists.""" - def __init__(self, string=""): - self.data = string - def __hash__(self): - raise TypeError, "unhashable type (it is mutable)" - def __setitem__(self, index, sub): - if index < 0: - index += len(self.data) - if index < 0 or index >= len(self.data): raise IndexError - self.data = self.data[:index] + sub + self.data[index+1:] - def __delitem__(self, index): - if index < 0: - index += len(self.data) - if index < 0 or index >= len(self.data): raise IndexError - self.data = self.data[:index] + self.data[index+1:] - def __setslice__(self, start, end, sub): - start = max(start, 0); end = max(end, 0) - if isinstance(sub, UserString): - self.data = self.data[:start]+sub.data+self.data[end:] - elif isinstance(sub, basestring): - self.data = self.data[:start]+sub+self.data[end:] - else: - self.data = self.data[:start]+str(sub)+self.data[end:] - def __delslice__(self, start, end): - start = max(start, 0); end = max(end, 0) - self.data = self.data[:start] + self.data[end:] - def immutable(self): - return UserString(self.data) - def __iadd__(self, other): - if isinstance(other, UserString): - self.data += other.data - elif isinstance(other, basestring): - self.data += other - else: - self.data += str(other) - return self - def __imul__(self, n): - self.data *= n - return self - -if __name__ == "__main__": - # execute the regression test to stdout, if called as a script: - import os - called_in_dir, called_as = os.path.split(sys.argv[0]) - called_as, py = os.path.splitext(called_as) - if '-q' in sys.argv: - from test import test_support - test_support.verbose = 0 - __import__('test.test_' + called_as.lower()) Deleted: branches/asm/Lib/__future__.py =================================================================== --- branches/asm/Lib/__future__.py 2008-06-30 18:08:37 UTC (rev 4826) +++ branches/asm/Lib/__future__.py 2008-07-01 13:52:38 UTC (rev 4827) @@ -1,116 +0,0 @@ -"""Record of phased-in incompatible language changes. - -Each line is of the form: - - FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease "," - CompilerFlag ")" - -where, normally, OptionalRelease < MandatoryRelease, and both are 5-tuples -of the same form as sys.version_info: - - (PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int - PY_MINOR_VERSION, # the 1; an int - PY_MICRO_VERSION, # the 0; an int - PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string - PY_RELEASE_SERIAL # the 3; an int - ) - -OptionalRelease records the first release in which - - from __future__ import FeatureName - -was accepted. - -In the case of MandatoryReleases that have not yet occurred, -MandatoryRelease predicts the release in which the feature will become part -of the language. - -Else MandatoryRelease records when the feature became part of the language; -in releases at or after that, modules no longer need - - from __future__ import FeatureName - -to use the feature in question, but may continue to use such imports. - -MandatoryRelease may also be None, meaning that a planned feature got -dropped. - -Instances of class _Feature have two corresponding methods, -.getOptionalRelease() and .getMandatoryRelease(). - -CompilerFlag is the (bitfield) flag that should be passed in the fourth -argument to the builtin function compile() to enable the feature in -dynamically compiled code. This flag is stored in the .compiler_flag -attribute on _Future instances. These values must match the appropriate -#defines of CO_xxx flags in Include/compile.h. - -No feature line is ever to be deleted from this file. -""" - -all_feature_names = [ - "nested_scopes", - "generators", - "division", - "absolute_import", - "with_statement", -] - -__all__ = ["all_feature_names"] + all_feature_names - -# The CO_xxx symbols are defined here under the same names used by -# compile.h, so that an editor search will find them here. However, -# they're not exported in __all__, because they don't really belong to -# this module. -CO_NESTED = 0x0010 # nested_scopes -CO_GENERATOR_ALLOWED = 0 # generators (obsolete, was 0x1000) -CO_FUTURE_DIVISION = 0x2000 # division -CO_FUTURE_ABSOLUTE_IMPORT = 0x4000 # perform absolute imports by default -CO_FUTURE_WITH_STATEMENT = 0x8000 # with statement - -class _Feature: - def __init__(self, optionalRelease, mandatoryRelease, compiler_flag): - self.optional = optionalRelease - self.mandatory = mandatoryRelease - self.compiler_flag = compiler_flag - - def getOptionalRelease(self): - """Return first release in which this feature was recognized. - - This is a 5-tuple, of the same form as sys.version_info. - """ - - return self.optional - - def getMandatoryRelease(self): - """Return release in which this feature will become mandatory. - - This is a 5-tuple, of the same form as sys.version_info, or, if - the feature was dropped, is None. - """ - - return self.mandatory - - def __repr__(self): - return "_Feature" + repr((self.optional, - self.mandatory, - self.compiler_flag)) - -nested_scopes = _Feature((2, 1, 0, "beta", 1), - (2, 2, 0, "alpha", 0), - CO_NESTED) - -generators = _Feature((2, 2, 0, "alpha", 1), - (2, 3, 0, "final", 0), - CO_GENERATOR_ALLOWED) - -division = _Feature((2, 2, 0, "alpha", 2), - (3, 0, 0, "alpha", 0), - CO_FUTURE_DIVISION) - -absolute_import = _Feature((2, 5, 0, "alpha", 1), - (2, 7, 0, "alpha", 0), - CO_FUTURE_ABSOLUTE_IMPORT) - -with_statement = _Feature((2, 5, 0, "alpha", 1), - (2, 6, 0, "alpha", 0), - CO_FUTURE_WITH_STATEMENT) Deleted: branches/asm/Lib/runpy.py =================================================================== --- branches/asm/Lib/runpy.py 2008-06-30 18:08:37 UTC (rev 4826) +++ branches/asm/Lib/runpy.py 2008-07-01 13:52:38 UTC (rev 4827) @@ -1,104 +0,0 @@ -"""runpy.py - locating and running Python code using the module namespace - -Provides support for locating and running Python scripts using the Python -module namespace instead of the native filesystem. - -This allows Python code to play nicely with non-filesystem based PEP 302 -importers when locating support scripts as well as when importing modules. -""" -# Written by Nick Coghlan <ncoghlan at gmail.com> -# to implement PEP 338 (Executing Modules as Scripts) - -import sys -import imp -try: - from imp import get_loader -except ImportError: - from pkgutil import get_loader - -__all__ = [ - "run_module", -] - - -def _run_code(code, run_globals, init_globals, - mod_name, mod_fname, mod_loader): - """Helper for _run_module_code""" - if init_globals is not None: - run_globals.update(init_globals) - run_globals.update(__name__ = mod_name, - __file__ = mod_fname, - __loader__ = mod_loader) - exec code in run_globals - return run_globals - -def _run_module_code(code, init_globals=None, - mod_name=None, mod_fname=None, - mod_loader=None, alter_sys=False): - """Helper for run_module""" - # Set up the top level namespace dictionary - if alter_sys: - # Modify sys.argv[0] and sys.module[mod_name] - temp_module = imp.new_module(mod_name) - mod_globals = temp_module.__dict__ - saved_argv0 = sys.argv[0] - restore_module = mod_name in sys.modules - if restore_module: - saved_module = sys.modules[mod_name] - sys.argv[0] = mod_fname - sys.modules[mod_name] = temp_module - try: - _run_code(code, mod_globals, init_globals, - mod_name, mod_fname, mod_loader) - finally: - sys.argv[0] = saved_argv0 - if restore_module: - sys.modules[mod_name] = saved_module - else: - del sys.modules[mod_name] - # Copy the globals of the temporary module, as they - # may be cleared when the temporary module goes away - return mod_globals.copy() - else: - # Leave the sys module alone - return _run_code(code, {}, init_globals, - mod_name, mod_fname, mod_loader) - - -# This helper is needed due to a missing component in the PEP 302 -# loader protocol (specifically, "get_filename" is non-standard) -def _get_filename(loader, mod_name): - try: - get_filename = loader.get_filename - except AttributeError: - return None - else: - return get_filename(mod_name) - - -def run_module(mod_name, init_globals=None, - run_name=None, alter_sys=False): - """Execute a module's code without importing it - - Returns the resulting top level namespace dictionary - """ - loader = get_loader(mod_name) - if loader is None: - raise ImportError("No module named " + mod_name) - code = loader.get_code(mod_name) - if code is None: - raise ImportError("No code object available for " + mod_name) - filename = _get_filename(loader, mod_name) - if run_name is None: - run_name = mod_name - return _run_module_code(code, init_globals, run_name, - filename, loader, alter_sys) - - -if __name__ == "__main__": - # Run the module specified as the next command line argument - if len(sys.argv) < 2: - print >> sys.stderr, "No module specified for execution" - else: - del sys.argv[0] # Make the requested module sys.argv[0] - run_module(sys.argv[0], run_name="__main__", alter_sys=True) Deleted: branches/asm/Lib/test/mapping_tests.py =================================================================== --- branches/asm/Lib/test/mapping_tests.py 2008-06-30 18:08:37 UTC (rev 4826) +++ branches/asm/Lib/test/mapping_tests.py 2008-07-01 13:52:38 UTC (rev 4827) @@ -1,672 +0,0 @@ -# tests common to dict and UserDict -import unittest -import UserDict - - -class BasicTestMappingProtocol(unittest.TestCase): - # This base class can be used to check that an object conforms to the - # mapping protocol - - # Functions that can be useful to override to adapt to dictionary - # semantics - type2test = None # which class is being tested (overwrite in subclasses) - - def _reference(self): - """Return a dictionary of values which are invariant by storage - in the object under test.""" - return {1:2, "key1":"value1", "key2":(1,2,3)} - def _empty_mapping(self): - """Return an empty mapping object""" - return self.type2test() - def _full_mapping(self, data): - """Return a mapping object with the value contained in data - dictionary""" - x = self._empty_mapping() - for key, value in data.items(): - x[key] = value - return x - - def __init__(self, *args, **kw): - unittest.TestCase.__init__(self, *args, **kw) - self.reference = self._reference().copy() - - # A (key, value) pair not in the mapping - key, value = self.reference.popitem() - self.other = {key:value} - - # A (key, value) pair in the mapping - key, value = self.reference.popitem() - self.inmapping = {key:value} - self.reference[key] = value - - def test_read(self): - # Test for read only operations on mapping - p = self._empty_mapping() - p1 = dict(p) #workaround for singleton objects - d = self._full_mapping(self.reference) - if d is p: - p = p1 - #Indexing - for key, value in self.reference.items(): - self.assertEqual(d[key], value) - knownkey = self.other.keys()[0] - self.failUnlessRaises(KeyError, lambda:d[knownkey]) - #len - self.assertEqual(len(p), 0) - self.assertEqual(len(d), len(self.reference)) - #has_key - for k in self.reference: - self.assert_(d.has_key(k)) - self.assert_(k in d) - for k in self.other: - self.failIf(d.has_key(k)) - self.failIf(k in d) - #cmp - self.assertEqual(cmp(p,p), 0) - self.assertEqual(cmp(d,d), 0) - self.assertEqual(cmp(p,d), -1) - self.assertEqual(cmp(d,p), 1) - #__non__zero__ - if p: self.fail("Empty mapping must compare to False") - if not d: self.fail("Full mapping must compare to True") - # keys(), items(), iterkeys() ... - def check_iterandlist(iter, lst, ref): - self.assert_(hasattr(iter, 'next')) - self.assert_(hasattr(iter, '__iter__')) - x = list(iter) - self.assert_(set(x)==set(lst)==set(ref)) - check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys()) - check_iterandlist(iter(d), d.keys(), self.reference.keys()) - check_iterandlist(d.itervalues(), d.values(), self.reference.values()) - check_iterandlist(d.iteritems(), d.items(), self.reference.items()) - #get - key, value = d.iteritems().next() - knownkey, knownvalue = self.other.iteritems().next() - self.assertEqual(d.get(key, knownvalue), value) - self.assertEqual(d.get(knownkey, knownvalue), knownvalue) - self.failIf(knownkey in d) - - def test_write(self): - # Test for write operations on mapping - p = self._empty_mapping() - #Indexing - for key, value in self.reference.items(): - p[key] = value - self.assertEqual(p[key], value) - for key in self.reference.keys(): - del p[key] - self.failUnlessRaises(KeyError, lambda:p[key]) - p = self._empty_mapping() - #update - p.update(self.reference) - self.assertEqual(dict(p), self.reference) - items = p.items() - p = self._empty_mapping() - p.update(items) - self.assertEqual(dict(p), self.reference) - d = self._full_mapping(self.reference) - #setdefault - key, value = d.iteritems().next() - knownkey, knownvalue = self.other.iteritems().next() - self.assertEqual(d.setdefault(key, knownvalue), value) - self.assertEqual(d[key], value) - self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue) - self.assertEqual(d[knownkey], knownvalue) - #pop - self.assertEqual(d.pop(knownkey), knownvalue) - self.failIf(knownkey in d) - self.assertRaises(KeyError, d.pop, knownkey) - default = 909 - d[knownkey] = knownvalue - self.assertEqual(d.pop(knownkey, default), knownvalue) - self.failIf(knownkey in d) - self.assertEqual(d.pop(knownkey, default), default) - #popitem - key, value = d.popitem() - self.failIf(key in d) - self.assertEqual(value, self.reference[key]) - p=self._empty_mapping() - self.assertRaises(KeyError, p.popitem) - - def test_constructor(self): - self.assertEqual(self._empty_mapping(), self._empty_mapping()) - - def test_bool(self): - self.assert_(not self._empty_mapping()) - self.assert_(self.reference) - self.assert_(bool(self._empty_mapping()) is False) - self.assert_(bool(self.reference) is True) - - def test_keys(self): - d = self._empty_mapping() - self.assertEqual(d.keys(), []) - d = self.reference - self.assert_(self.inmapping.keys()[0] in d.keys()) - self.assert_(self.other.keys()[0] not in d.keys()) - self.assertRaises(TypeError, d.keys, None) - - def test_values(self): - d = self._empty_mapping() - self.assertEqual(d.values(), []) - - self.assertRaises(TypeError, d.values, None) - - def test_items(self): - d = self._empty_mapping() - self.assertEqual(d.items(), []) - - self.assertRaises(TypeError, d.items, None) - - def test_len(self): - d = self._empty_mapping() - self.assertEqual(len(d), 0) - - def test_getitem(self): - d = self.reference - self.assertEqual(d[self.inmapping.keys()[0]], self.inmapping.values()[0]) - - self.assertRaises(TypeError, d.__getitem__) - - def test_update(self): - # mapping argument - d = self._empty_mapping() - d.update(self.other) - self.assertEqual(d.items(), self.other.items()) - - # No argument - d = self._empty_mapping() - d.update() - self.assertEqual(d, self._empty_mapping()) - - # item sequence - d = self._empty_mapping() - d.update(self.other.items()) - self.assertEqual(d.items(), self.other.items()) - - # Iterator - d = self._empty_mapping() - d.update(self.other.iteritems()) - self.assertEqual(d.items(), self.other.items()) - - # FIXME: Doesn't work with UserDict - # self.assertRaises((TypeError, AttributeError), d.update, None) - self.assertRaises((TypeError, AttributeError), d.update, 42) - - outerself = self - class SimpleUserDict: - def __init__(self): - self.d = outerself.reference - def keys(self): - return self.d.keys() - def __getitem__(self, i): - return self.d[i] - d.clear() - d.update(SimpleUserDict()) - i1 = d.items() - i2 = self.reference.items() - i1.sort() - i2.sort() - self.assertEqual(i1, i2) - - class Exc(Exception): pass - - d = self._empty_mapping() - class FailingUserDict: - def keys(self): - raise Exc - self.assertRaises(Exc, d.update, FailingUserDict()) - - d.clear() - - class FailingUserDict: - def keys(self): - class BogonIter: - def __init__(self): - self.i = 1 - def __iter__(self): - return self - def next(self): - if self.i: - self.i = 0 - return 'a' - raise Exc - return BogonIter() - def __getitem__(self, key): - return key - self.assertRaises(Exc, d.update, FailingUserDict()) - - class FailingUserDict: - def keys(self): - class BogonIter: - def __init__(self): - self.i = ord('a') - def __iter__(self): - return self - def next(self): - if self.i <= ord('z'): - rtn = chr(self.i) - self.i += 1 - return rtn - raise StopIteration - return BogonIter() - def __getitem__(self, key): - raise Exc - self.assertRaises(Exc, d.update, FailingUserDict()) - - d = self._empty_mapping() - class badseq(object): - def __iter__(self): - return self - def next(self): - raise Exc() - - self.assertRaises(Exc, d.update, badseq()) - - self.assertRaises(ValueError, d.update, [(1, 2, 3)]) - - # no test_fromkeys or test_copy as both os.environ and selves don't support it - - def test_get(self): - d = self._empty_mapping() - self.assert_(d.get(self.other.keys()[0]) is None) - self.assertEqual(d.get(self.other.keys()[0], 3), 3) - d = self.reference - self.assert_(d.get(self.other.keys()[0]) is None) - self.assertEqual(d.get(self.other.keys()[0], 3), 3) - self.assertEqual(d.get(self.inmapping.keys()[0]), self.inmapping.values()[0]) - self.assertEqual(d.get(self.inmapping.keys()[0], 3), self.inmapping.values()[0]) - self.assertRaises(TypeError, d.get) - self.assertRaises(TypeError, d.get, None, None, None) - - def test_setdefault(self): - d = self._empty_mapping() - self.assertRaises(TypeError, d.setdefault) - - def test_popitem(self): - d = self._empty_mapping() - self.assertRaises(KeyError, d.popitem) - self.assertRaises(TypeError, d.popitem, 42) - - def test_pop(self): - d = self._empty_mapping() - k, v = self.inmapping.items()[0] - d[k] = v - self.assertRaises(KeyError, d.pop, self.other.keys()[0]) - - self.assertEqual(d.pop(k), v) - self.assertEqual(len(d), 0) - - self.assertRaises(KeyError, d.pop, k) - - -class TestMappingProtocol(BasicTestMappingProtocol): - def test_constructor(self): - BasicTestMappingProtocol.test_constructor(self) - self.assert_(self._empty_mapping() is not self._empty_mapping()) - self.assertEqual(self.type2test(x=1, y=2), {"x": 1, "y": 2}) - - def test_bool(self): - BasicTestMappingProtocol.test_bool(self) - self.assert_(not self._empty_mapping()) - self.assert_(self._full_mapping({"x": "y"})) - self.assert_(bool(self._empty_mapping()) is False) - self.assert_(bool(self._full_mapping({"x": "y"})) is True) - - def test_keys(self): - BasicTestMappingProtocol.test_keys(self) - d = self._empty_mapping() - self.assertEqual(d.keys(), []) - d = self._full_mapping({'a': 1, 'b': 2}) - k = d.keys() - self.assert_('a' in k) - self.assert_('b' in k) - self.assert_('c' not in k) - - def test_values(self): - BasicTestMappingProtocol.test_values(self) - d = self._full_mapping({1:2}) - self.assertEqual(d.values(), [2]) - - def test_items(self): - BasicTestMappingProtocol.test_items(self) - - d = self._full_mapping({1:2}) - self.assertEqual(d.items(), [(1, 2)]) - - def test_has_key(self): - d = self._empty_mapping() - self.assert_(not d.has_key('a')) - d = self._full_mapping({'a': 1, 'b': 2}) - k = d.keys() - k.sort() - self.assertEqual(k, ['a', 'b']) - - self.assertRaises(TypeError, d.has_key) - - def test_contains(self): - d = self._empty_mapping() - self.assert_(not ('a' in d)) - self.assert_('a' not in d) - d = self._full_mapping({'a': 1, 'b': 2}) - self.assert_('a' in d) - self.assert_('b' in d) - self.assert_('c' not in d) - - self.assertRaises(TypeError, d.__contains__) - - def test_len(self): - BasicTestMappingProtocol.test_len(self) - d = self._full_mapping({'a': 1, 'b': 2}) - self.assertEqual(len(d), 2) - - def test_getitem(self): - BasicTestMappingProtocol.test_getitem(self) - d = self._full_mapping({'a': 1, 'b': 2}) - self.assertEqual(d['a'], 1) - self.assertEqual(d['b'], 2) - d['c'] = 3 - d['a'] = 4 - self.assertEqual(d['c'], 3) - self.assertEqual(d['a'], 4) - del d['b'] - self.assertEqual(d, {'a': 4, 'c': 3}) - - self.assertRaises(TypeError, d.__getitem__) - - def test_clear(self): - d = self._full_mapping({1:1, 2:2, 3:3}) - d.clear() - self.assertEqual(d, {}) - - self.assertRaises(TypeError, d.clear, None) - - def test_update(self): - BasicTestMappingProtocol.test_update(self) - # mapping argument - d = self._empty_mapping() - d.update({1:100}) - d.update({2:20}) - d.update({1:1, 2:2, 3:3}) - self.assertEqual(d, {1:1, 2:2, 3:3}) - - # no argument - d.update() - self.assertEqual(d, {1:1, 2:2, 3:3}) - - # keyword arguments - d = self._empty_mapping() - d.update(x=100) - d.update(y=20) - d.update(x=1, y=2, z=3) - self.assertEqual(d, {"x":1, "y":2, "z":3}) - - # item sequence - d = self._empty_mapping() - d.update([("x", 100), ("y", 20)]) - self.assertEqual(d, {"x":100, "y":20}) - - # Both item sequence and keyword arguments - d = self._empty_mapping() - d.update([("x", 100), ("y", 20)], x=1, y=2) - self.assertEqual(d, {"x":1, "y":2}) - - # iterator - d = self._full_mapping({1:3, 2:4}) - d.update(self._full_mapping({1:2, 3:4, 5:6}).iteritems()) - self.assertEqual(d, {1:2, 2:4, 3:4, 5:6}) - - class SimpleUserDict: - def __init__(self): - self.d = {1:1, 2:2, 3:3} - def keys(self): - return self.d.keys() - def __getitem__(self, i): - return self.d[i] - d.clear() - d.update(SimpleUserDict()) - self.assertEqual(d, {1:1, 2:2, 3:3}) - - def test_fromkeys(self): - self.assertEqual(self.type2test.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) - d = self._empty_mapping() - self.assert_(not(d.fromkeys('abc') is d)) - self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None}) - self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0}) - self.assertEqual(d.fromkeys([]), {}) - def g(): - yield 1 - self.assertEqual(d.fromkeys(g()), {1:None}) - self.assertRaises(TypeError, {}.fromkeys, 3) - class dictlike(self.type2test): pass - self.assertEqual(dictlike.fromkeys('a'), {'a':None}) - self.assertEqual(dictlike().fromkeys('a'), {'a':None}) - self.assert_(dictlike.fromkeys('a').__class__ is dictlike) - self.assert_(dictlike().fromkeys('a').__class__ is dictlike) - # FIXME: the following won't work with UserDict, because it's an old style class - # self.assert_(type(dictlike.fromkeys('a')) is dictlike) - class mydict(self.type2test): - def __new__(cls): - return UserDict.UserDict() - ud = mydict.fromkeys('ab') - self.assertEqual(ud, {'a':None, 'b':None}) - # FIXME: the following won't work with UserDict, because it's an old style class - # self.assert_(isinstance(ud, UserDict.UserDict)) - self.assertRaises(TypeError, dict.fromkeys) - - class Exc(Exception): pass - - class baddict1(self.type2test): - def __init__(self): - raise Exc() - - self.assertRaises(Exc, baddict1.fromkeys, [1]) - - class BadSeq(object): - def __iter__(self): - return self - def next(self): - raise Exc() - - self.assertRaises(Exc, self.type2test.fromkeys, BadSeq()) - - class baddict2(self.type2test): - def __setitem__(self, key, value): - raise Exc() - - self.assertRaises(Exc, baddict2.fromkeys, [1]) - - def test_copy(self): - d = self._full_mapping({1:1, 2:2, 3:3}) - self.assertEqual(d.copy(), {1:1, 2:2, 3:3}) - d = self._empty_mapping() - self.assertEqual(d.copy(), d) - self.assert_(isinstance(d.copy(), d.__class__)) - self.assertRaises(TypeError, d.copy, None) - - def test_get(self): - BasicTestMappingProtocol.test_get(self) - d = self._empty_mapping() - self.assert_(d.get('c') is None) - self.assertEqual(d.get('c', 3), 3) - d = self._full_mapping({'a' : 1, 'b' : 2}) - self.assert_(d.get('c') is None) - self.assertEqual(d.get('c', 3), 3) - self.assertEqual(d.get('a'), 1) - self.assertEqual(d.get('a', 3), 1) - - def test_setdefault(self): - BasicTestMappingProtocol.test_setdefault(self) - d = self._empty_mapping() - self.assert_(d.setdefault('key0') is None) - d.setdefault('key0', []) - self.assert_(d.setdefault('key0') is None) - d.setdefault('key', []).append(3) - self.assertEqual(d['key'][0], 3) - d.setdefault('key', []).append(4) - self.assertEqual(len(d['key']), 2) - - def test_popitem(self): - BasicTestMappingProtocol.test_popitem(self) - for copymode in -1, +1: - # -1: b has same structure as a - # +1: b is a.copy() - for log2size in range(12): - size = 2**log2size - a = self._empty_mapping() - b = self._empty_mapping() - for i in range(size): - a[repr(i)] = i - if copymode < 0: - b[repr(i)] = i - if copymode > 0: - b = a.copy() - for i in range(size): - ka, va = ta = a.popitem() - self.assertEqual(va, int(ka)) - kb, vb = tb = b.popitem() - self.assertEqual(vb, int(kb)) - self.assert_(not(copymode < 0 and ta != tb)) - self.assert_(not a) - self.assert_(not b) - - def test_pop(self): - BasicTestMappingProtocol.test_pop(self) - - # Tests for pop with specified key - d = self._empty_mapping() - k, v = 'abc', 'def' - - # verify longs/ints get same value when key > 32 bits (for 64-bit archs) - # see SF bug #689659 - x = 4503599627370496L - y = 4503599627370496 - h = self._full_mapping({x: 'anything', y: 'something else'}) - self.assertEqual(h[x], h[y]) - - self.assertEqual(d.pop(k, v), v) - d[k] = v - self.assertEqual(d.pop(k, 1), v) - - -class TestHashMappingProtocol(TestMappingProtocol): - - def test_getitem(self): - TestMappingProtocol.test_getitem(self) - class Exc(Exception): pass - - class BadEq(object): - def __eq__(self, other): - raise Exc() - - d = self._empty_mapping() - d[BadEq()] = 42 - self.assertRaises(KeyError, d.__getitem__, 23) - - class BadHash(object): - fail = False - def __hash__(self): - if self.fail: - raise Exc() - else: - return 42 - - d = self._empty_mapping() - x = BadHash() - d[x] = 42 - x.fail = True - self.assertRaises(Exc, d.__getitem__, x) - - def test_fromkeys(self): - TestMappingProtocol.test_fromkeys(self) - class mydict(self.type2test): - def __new__(cls): - return UserDict.UserDict() - ud = mydict.fromkeys('ab') - self.assertEqual(ud, {'a':None, 'b':None}) - self.assert_(isinstance(ud, UserDict.UserDict)) - - def test_pop(self): - TestMappingProtocol.test_pop(self) - - class Exc(Exception): pass - - class BadHash(object): - fail = False - def __hash__(self): - if self.fail: - raise Exc() - else: - return 42 - - d = self._empty_mapping() - x = BadHash() - d[x] = 42 - x.fail = True - self.assertRaises(Exc, d.pop, x) - - def test_mutatingiteration(self): - d = self._empty_mapping() - d[1] = 1 - try: - for i in d: - d[i+1] = 1 - except RuntimeError: - pass - else: - self.fail("changing dict size during iteration doesn't raise Error") - - def test_repr(self): - d = self._empty_mapping() - self.assertEqual(repr(d), '{}') - d[1] = 2 - self.assertEqual(repr(d), '{1: 2}') - d = self._empty_mapping() - d[1] = d - self.assertEqual(repr(d), '{1: {...}}') - - class Exc(Exception): pass - - class BadRepr(object): - def __repr__(self): - raise Exc() - - d = self._full_mapping({1: BadRepr()}) - self.assertRaises(Exc, repr, d) - - def test_le(self): - self.assert_(not (self._empty_mapping() < self._empty_mapping())) - self.assert_(not (self._full_mapping({1: 2}) < self._full_mapping({1L: 2L}))) - - class Exc(Exception): pass - - class BadCmp(object): - def __eq__(self, other): - raise Exc() - - d1 = self._full_mapping({BadCmp(): 1}) - d2 = self._full_mapping({1: 1}) - try: - d1 < d2 - except Exc: - pass - else: - self.fail("< didn't raise Exc") - - def test_setdefault(self): - TestMappingProtocol.test_setdefault(self) - - class Exc(Exception): pass - - class BadHash(object): - fail = False - def __hash__(self): - if self.fail: - raise Exc() - else: - return 42 - - d = self._empty_mapping() - x = BadHash() - d[x] = 42 - x.fail = True - self.assertRaises(Exc, d.setdefault, x, []) Deleted: branches/asm/Lib/test/test_bisect.py =================================================================== --- branches/asm/Lib/test/test_bisect.py 2008-06-30 18:08:37 UTC (rev 4826) +++ branches/asm/Lib/test/test_bisect.py 2008-07-01 13:52:38 UTC (rev 4827) @@ -1,253 +0,0 @@ -import unittest -from test import test_support -from bisect import bisect_right, bisect_left, insort_left, insort_right, insort, bisect -from UserList import UserList - -class TestBisect(unittest.TestCase): - - precomputedCases = [ - (bisect_right, [], 1, 0), - (bisect_right, [1], 0, 0), - (bisect_right, [1], 1, 1), - (bisect_right, [1], 2, 1), - (bisect_right, [1, 1], 0, 0), - (bisect_right, [1, 1], 1, 2), - (bisect_right, [1, 1], 2, 2), - (bisect_right, [1, 1, 1], 0, 0), - (bisect_right, [1, 1, 1], 1, 3), - (bisect_right, [1, 1, 1], 2, 3), - (bisect_right, [1, 1, 1, 1], 0, 0), - (bisect_right, [1, 1, 1, 1], 1, 4), - (bisect_right, [1, 1, 1, 1], 2, 4), - (bisect_right, [1, 2], 0, 0), - (bisect_right, [1, 2], 1, 1), - (bisect_right, [1, 2], 1.5, 1), - (bisect_right, [1, 2], 2, 2), - (bisect_right, [1, 2], 3, 2), - (bisect_right, [1, 1, 2, 2], 0, 0), - (bisect_right, [1, 1, 2, 2], 1, 2), - (bisect_right, [1, 1, 2, 2], 1.5, 2), - (bisect_right, [1, 1, 2, 2], 2, 4), - (bisect_right, [1, 1, 2, 2], 3, 4), - (bisect_right, [1, 2, 3], 0, 0), - (bisect_right, [1, 2, 3], 1, 1), - (bisect_right, [1, 2, 3], 1.5, 1), - (bisect_right, [1, 2, 3], 2, 2), - (bisect_right, [1, 2, 3], 2.5, 2), - (bisect_right, [1, 2, 3], 3, 3), - (bisect_right, [1, 2, 3], 4, 3), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 0, 0), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1, 1), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1.5, 1), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2, 3), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2.5, 3), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3, 6), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3.5, 6), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 4, 10), - (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 5, 10), - - (bisect_left, [], 1, 0), - (bisect_left, [1], 0, 0), - (bisect_left, [1], 1, 0), - (bisect_left, [1], 2, 1), - (bisect_left, [1, 1], 0, 0), - (bisect_left, [1, 1], 1, 0), - (bisect_left, [1, 1], 2, 2), - (bisect_left, [1, 1, 1], 0, 0), - (bisect_left, [1, 1, 1], 1, 0), - (bisect_left, [1, 1, 1], 2, 3), - (bisect_left, [1, 1, 1, 1], 0, 0), - (bisect_left, [1, 1, 1, 1], 1, 0), - (bisect_left, [1, 1, 1, 1], 2, 4), - (bisect_left, [1, 2], 0, 0), - (bisect_left, [1, 2], 1, 0), - (bisect_left, [1, 2], 1.5, 1), - (bisect_left, [1, 2], 2, 1), - (bisect_left, [1, 2], 3, 2), - (bisect_left, [1, 1, 2, 2], 0, 0), - (bisect_left, [1, 1, 2, 2], 1, 0), - (bisect_left, [1, 1, 2, 2], 1.5, 2), - (bisect_left, [1, 1, 2, 2], 2, 2), - (bisect_left, [1, 1, 2, 2], 3, 4), - (bisect_left, [1, 2, 3], 0, 0), - (bisect_left, [1, 2, 3], 1, 0), - (bisect_left, [1, 2, 3], 1.5, 1), - (bisect_left, [1, 2, 3], 2, 1), - (bisect_left, [1, 2, 3], 2.5, 2), - (bisect_left, [1, 2, 3], 3, 2), - (bisect_left, [1, 2, 3], 4, 3), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 0, 0), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1, 0), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1.5, 1), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2, 1), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2.5, 3), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3, 3), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3.5, 6), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 4, 6), - (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 5, 10) - ] - - def test_precomputed(self): - for func, data, elem, expected in self.precomputedCases: - self.assertEqual(func(data, elem), expected) - self.assertEqual(func(UserList(data), elem), expected) - - def test_random(self, n=25): - from random import randrange - for i in xrange(n): - data = [randrange(0, n, 2) for j in xrange(i)] - data.sort() - elem = randrange(-1, n+1) - ip = bisect_left(data, elem) - if ip < len(data): - self.failUnless(elem <= data[ip]) - if ip > 0: - self.failUnless(data[ip-1] < elem) - ip = bisect_right(data, elem) - if ip < len(data): - self.failUnless(elem < data[ip]) - if ip > 0: - self.failUnless(data[ip-1] <= elem) - - def test_optionalSlicing(self): - for func, data, elem, expected in self.precomputedCases: - for lo in xrange(4): - lo = min(len(data), lo) - for hi in xrange(3,8): - hi = min(len(data), hi) - ip = func(data, elem, lo, hi) - self.failUnless(lo <= ip <= hi) - if func is bisect_left and ip < hi: - self.failUnless(elem <= data[ip]) - if func is bisect_left and ip > lo: - self.failUnless(data[ip-1] < elem) - if func is bisect_right and ip < hi: - self.failUnless(elem < data[ip]) - if func is bisect_right and ip > lo: - self.failUnless(data[ip-1] <= elem) - self.assertEqual(ip, max(lo, min(hi, expected))) - - def test_backcompatibility(self): - self.assertEqual(bisect, bisect_right) - - def test_keyword_args(self): - data = [10, 20, 30, 40, 50] - self.assertEqual(bisect_left(a=data, x=25, lo=1, hi=3), 2) - self.assertEqual(bisect_right(a=data, x=25, lo=1, hi=3), 2) - self.assertEqual(bisect(a=data, x=25, lo=1, hi=3), 2) - insort_left(a=data, x=25, lo=1, hi=3) - insort_right(a=data, x=25, lo=1, hi=3) - insort(a=data, x=25, lo=1, hi=3) - self.assertEqual(data, [10, 20, 25, 25, 25, 30, 40, 50]) - -#============================================================================== - -class TestInsort(unittest.TestCase): - - def test_vsBuiltinSort(self, n=500): - from random import choice - for insorted in (list(), UserList()): - for i in xrange(n): - digit = choice("0123456789") - if digit in "02468": - f = insort_left - else: - f = insort_right - f(insorted, digit) - self.assertEqual(sorted(insorted), insorted) - - def test_backcompatibility(self): - self.assertEqual(insort, insort_right) - -#============================================================================== - - -class LenOnly: - "Dummy sequence class defining __len__ but not __getitem__." - def __len__(self): - return 10 - -class GetOnly: - "Dummy sequence class defining __getitem__ but not __len__." - def __getitem__(self, ndx): - return 10 - -class CmpErr: - "Dummy element that always raises an error during comparison" - def __cmp__(self, other): - raise ZeroDivisionError - -class TestErrorHandling(unittest.TestCase): - - def test_non_sequence(self): - for f in (bisect_left, bisect_right, insort_left, insort_right): - self.assertRaises(TypeError, f, 10, 10) - - def test_len_only(self): - for f in (bisect_left, bisect_right, insort_left, insort_right): - self.assertRaises(AttributeError, f, LenOnly(), 10) - - def test_get_only(self): - for f in (bisect_left, bisect_right, insort_left, insort_right): - self.assertRaises(AttributeError, f, GetOnly(), 10) - - def test_cmp_err(self): - seq = [CmpErr(), CmpErr(), CmpErr()] - for f in (bisect_left, bisect_right, insort_left, insort_right): - self.assertRaises(ZeroDivisionError, f, seq, 10) - - def test_arg_parsing(self): - for f in (bisect_left, bisect_right, insort_left, insort_right): - self.assertRaises(TypeError, f, 10) - -#============================================================================== - -libreftest = """ -Example from the Library Reference: Doc/lib/libbisect.tex - -The bisect() function is generally useful for categorizing numeric data. -This example uses bisect() to look up a letter grade for an exam total -(say) based on a set of ordered numeric breakpoints: 85 and up is an `A', -75..84 is a `B', etc. - - >>> grades = "FEDCBA" - >>> breakpoints = [30, 44, 66, 75, 85] - >>> from bisect import bisect - >>> def grade(total): - ... return grades[bisect(breakpoints, total)] - ... - >>> grade(66) - 'C' - >>> map(grade, [33, 99, 77, 44, 12, 88]) - ['E', 'A', 'B', 'D', 'F', 'A'] - -""" - -#------------------------------------------------------------------------------ - -__test__ = {'libreftest' : libreftest} - -def test_main(verbose=None): - from test import test_bisect - from types import BuiltinFunctionType - import sys - - test_classes = [TestBisect, TestInsort] - if isinstance(bisect_left, BuiltinFunctionType): - test_classes.append(TestErrorHandling) - - test_support.run_unittest(*test_classes) - test_support.run_doctest(test_bisect, verbose) - - # verify reference counting - if verbose and hasattr(sys, "gettotalrefcount"): - import gc - counts = [None] * 5 - for i in xrange(len(counts)): - test_support.run_unittest(*test_classes) - gc.collect() - counts[i] = sys.gettotalrefcount() - print counts - -if __name__ == "__main__": - test_main(verbose=True) Deleted: branches/asm/Lib/test/test_call.py =================================================================== --- branches/asm/Lib/test/test_call.py 2008-06-30 18:08:37 UTC (rev 4826) +++ branches/asm/Lib/test/test_call.py 2008-07-01 13:52:38 UTC (rev 4827) @@ -1,131 +0,0 @@ -import unittest -from test import test_support - -# The test cases here cover several paths through the function calling -# code. They depend on the METH_XXX flag that is used to define a C -# function, which can't be verified from Python. If the METH_XXX decl -# for a C function changes, these tests may not cover the right paths. - -class CFunctionCalls(unittest.TestCase): - - def test_varargs0(self): - self.assertRaises(TypeError, {}.has_key) - - def test_varargs1(self): - {}.has_key(0) - - def test_varargs2(self): - self.assertRaises(TypeError, {}.has_key, 0, 1) - - def test_varargs0_ext(self): - try: - {}.has_key(*()) - except TypeError: - pass - - def test_varargs1_ext(self): - {}.has_key(*(0,)) - - def test_varargs2_ext(self): - try: - {}.has_key(*(1, 2)) - except TypeError: - pass - else: - raise RuntimeError - - def test_varargs0_kw(self): - self.assertRaises(TypeError, {}.has_key, x=2) - - def test_varargs1_kw(self): - self.assertRaises(TypeError, {}.has_key, x=2) - - def test_varargs2_kw(self): - self.assertRaises(TypeError, {}.has_key, x=2, y=2) - - def test_oldargs0_0(self): - {}.keys() - - def test_oldargs0_1(self): - self.assertRaises(TypeError, {}.keys, 0) - - def test_oldargs0_2(self): - self.assertRaises(TypeError, {}.keys, 0, 1) - - def test_oldargs0_0_ext(self): - {}.keys(*()) - - def test_oldargs0_1_ext(self): - try: - {}.keys(*(0,)) - except TypeError: - pass - else: - raise RuntimeError - - def test_oldargs0_2_ext(self): - try: - {}.keys(*(1, 2)) - except TypeError: - pass - else: - raise RuntimeError - - def test_oldargs0_0_kw(self): - try: - {}.keys(x=2) - except TypeError: - pass - else: - raise RuntimeError - - def test_oldargs0_1_kw(self): - self.assertRaises(TypeError, {}.keys, x=2) - - def test_oldargs0_2_kw(self): - self.assertRaises(TypeError, {}.keys, x=2, y=2) - - def test_oldargs1_0(self): - self.assertRaises(TypeError, [].count) - - def test_oldargs1_1(self): - [].count(1) - - def test_oldargs1_2(self): - self.assertRaises(TypeError, [].count, 1, 2) - - def test_oldargs1_0_ext(self): - try: - [].count(*()) - except TypeError: - pass - else: - raise RuntimeError - - def test_oldargs1_1_ext(self): - [].count(*(1,)) - - def test_oldargs1_2_ext(self): - try: - [].count(*(1, 2)) - except TypeError: - pass - else: - raise RuntimeError - - def test_oldargs1_0_kw(self): - self.assertRaises(TypeError, [].count, x=2) - - def test_oldargs1_1_kw(self): - self.assertRaises(TypeError, [].count, {}, x=2) - - def test_oldargs1_2_kw(self): - self.assertRaises(TypeError, [].count, x=2, y=2) - - -def test_main(): - test_support.run_unittest(CFunctionCalls) - - -if __name__ == "__main__": - test_main() Deleted: branches/asm/Lib/test/test_contextlib.py =================================================================== --- branches/asm/Lib/test/test_contextlib.py 2008-06-30 18:08:37 UTC (rev 4826) +++ branches/asm/Lib/test/test_contextlib.py 2008-07-01 13:52:38 UTC (rev 4827) @@ -1,340 +0,0 @@ -"""Unit tests for contextlib.py, and other context managers.""" - -from __future__ import with_statement - -import sys -import os -import decimal -import tempfile -import unittest -import threading -from contextlib import * # Tests __all__ -from test.test_support import run_suite - -class ContextManagerTestCase(unittest.TestCase): - - def test_contextmanager_plain(self): - state = [] - @contextmanager - def woohoo(): - state.append(1) - yield 42 - state.append(999) - with woohoo() as x: - self.assertEqual(state, [1]) - self.assertEqual(x, 42) - state.append(x) - self.assertEqual(state, [1, 42, 999]) - - def test_contextmanager_finally(self): - state = [] - @contextmanager - def woohoo(): - state.append(1) - try: - yield 42 - finally: - state.append(999) - try: - with woohoo() as x: - self.assertEqual(state, [1]) - self.assertEqual(x, 42) - state.append(x) - raise ZeroDivisionError() - except ZeroDivisionError: - pass - else: - self.fail("Expected ZeroDivisionError") - self.assertEqual(state, [1, 42, 999]) - - def test_contextmanager_no_reraise(self): - @contextmanager - def whee(): - yield - ctx = whee() - ctx.__enter__() - # Calling __exit__ should not result in an exception - self.failIf(ctx.__exit__(TypeError, TypeError("foo"), None)) - - def test_contextmanager_trap_yield_after_throw(self): - @contextmanager - def whoo(): - try: - yield - except: - yield - ctx = whoo() - ctx.__enter__() - self.assertRaises( - RuntimeError, ctx.__exit__, TypeError, TypeError("foo"), None - ) - - def test_contextmanager_except(self): - state = [] - @contextmanager - def woohoo(): - state.append(1) - try: - yield 42 - except ZeroDivisionError, e: - state.append(e.args[0]) - self.assertEqual(state, [1, 42, 999]) - with woohoo() as x: - self.assertEqual(state, [1]) - self.assertEqual(x, 42) - state.append(x) - raise ZeroDivisionError(999) - self.assertEqual(state, [1, 42, 999]) - - def test_contextmanager_attribs(self): - def attribs(**kw): - def decorate(func): - for k,v in kw.items(): - setattr(func,k,v) - return func - return decorate - @contextmanager - @attribs(foo='bar') - def baz(spam): - """Whee!""" - self.assertEqual(baz.__name__,'baz') - self.assertEqual(baz.foo, 'bar') - self.assertEqual(baz.__doc__, "Whee!") - -class NestedTestCase(unittest.TestCase): - - # XXX This needs more work - - def test_nested(self): - @contextmanager - def a(): - yield 1 - @contextmanager - def b(): - yield 2 - @contextmanager - def c(): - yield 3 - with nested(a(), b(), c()) as (x, y, z): - self.assertEqual(x, 1) - self.assertEqual(y, 2) - self.assertEqual(z, 3) - - def test_nested_cleanup(self): - state = [] - @contextmanager - def a(): - state.append(1) - try: - yield 2 - finally: - state.append(3) - @contextmanager - def b(): - state.append(4) - try: - yield 5 - finally: - state.append(6) - try: - with nested(a(), b()) as (x, y): - state.append(x) - state.append(y) - 1/0 - except ZeroDivisionError: - self.assertEqual(state, [1, 4, 2, 5, 6, 3]) - else: - self.fail("Didn't raise ZeroDivisionError") - - def test_nested_right_exception(self): - state = [] - @contextmanager - def a(): - yield 1 - class b(object): - def __enter__(self): - return 2 - def __exit__(self, *exc_info): - try: - raise Exception() - except: - pass - try: - with nested(a(), b()) as (x, y): - 1/0 - except ZeroDivisionError: - self.assertEqual((x, y), (1, 2)) - except Exception: - self.fail("Reraised wrong exception") - else: - self.fail("Didn't raise ZeroDivisionError") - - def test_nested_b_swallows(self): - @contextmanager - def a(): - yield - @contextmanager - def b(): - try: - yield - except: - # Swallow the exception - pass - try: - with nested(a(), b()): - 1/0 - except ZeroDivisionError: - self.fail("Didn't swallow ZeroDivisionError") - - def test_nested_break(self): - @contextmanager - def a(): - yield - state = 0 - while True: - state += 1 - with nested(a(), a()): - break - state += 10 - self.assertEqual(state, 1) - - def test_nested_continue(self): - @contextmanager - def a(): - yield - state = 0 - while state < 3: - state += 1 - with nested(a(), a()): - contin... [truncated message content] |
From: <zy...@us...> - 2008-06-30 18:08:38
|
Revision: 4826 http://jython.svn.sourceforge.net/jython/?rev=4826&view=rev Author: zyasoft Date: 2008-06-30 11:08:37 -0700 (Mon, 30 Jun 2008) Log Message: ----------- Restored cStringIO.getString Modified Paths: -------------- branches/asm/src/org/python/modules/cStringIO.java Modified: branches/asm/src/org/python/modules/cStringIO.java =================================================================== --- branches/asm/src/org/python/modules/cStringIO.java 2008-06-30 16:14:30 UTC (rev 4825) +++ branches/asm/src/org/python/modules/cStringIO.java 2008-06-30 18:08:37 UTC (rev 4826) @@ -354,5 +354,20 @@ } } + + private static String[] strings = new String[256]; + static String getString(char ch) { + if (ch > 255) { + return new String(new char[] { ch }); + } + String s = strings[ch]; + + if (s == null) { + s = new String(new char[] { ch }); + strings[ch] = s; + } + return s; + } + } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-06-30 16:14:31
|
Revision: 4825 http://jython.svn.sourceforge.net/jython/?rev=4825&view=rev Author: zyasoft Date: 2008-06-30 09:14:30 -0700 (Mon, 30 Jun 2008) Log Message: ----------- Change cStringIO to use StringBuilder semantics. Use via thread confinement, or with external locking. Keep it simple, keep it lightweight. Modified Paths: -------------- branches/asm/src/org/python/modules/cStringIO.java Modified: branches/asm/src/org/python/modules/cStringIO.java =================================================================== --- branches/asm/src/org/python/modules/cStringIO.java 2008-06-30 08:59:43 UTC (rev 4824) +++ branches/asm/src/org/python/modules/cStringIO.java 2008-06-30 16:14:30 UTC (rev 4825) @@ -6,8 +6,8 @@ * The Netherlands. */ -// we probably should use StringBuffer instead of StringBuilder, since StringIO -// most likely means not thread-confined, so we want those locking semantics. +// cStringIO with StringBuilder semantics - don't use without using external +// synchronization. Java does provide other alternatives. package org.python.modules; @@ -62,15 +62,15 @@ public boolean closed = false; public int pos = 0; - private final StringBuffer buf; + private final StringBuilder buf; StringIO() { - buf = new StringBuffer(); + buf = new StringBuilder(); } StringIO(String buffer) { - buf = new StringBuffer(buffer); + buf = new StringBuilder(buffer); } private void _complain_ifclosed() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <zy...@us...> - 2008-06-30 08:59:44
|
Revision: 4824 http://jython.svn.sourceforge.net/jython/?rev=4824&view=rev Author: zyasoft Date: 2008-06-30 01:59:43 -0700 (Mon, 30 Jun 2008) Log Message: ----------- Fixed unicode coercion logic for PyString.__mod__. Removed 2.5 contextlib.py in favor of direct from CPythonLib Modified Paths: -------------- branches/asm/src/org/python/core/PyString.java Removed Paths: ------------- branches/asm/Lib/contextlib.py Deleted: branches/asm/Lib/contextlib.py =================================================================== --- branches/asm/Lib/contextlib.py 2008-06-30 08:18:38 UTC (rev 4823) +++ branches/asm/Lib/contextlib.py 2008-06-30 08:59:43 UTC (rev 4824) @@ -1,154 +0,0 @@ -"""Utilities for with-statement contexts. See PEP 343.""" - -import sys - -__all__ = ["contextmanager", "nested", "closing"] - -class GeneratorContextManager(object): - """Helper for @contextmanager decorator.""" - - def __init__(self, gen): - self.gen = gen - - def __enter__(self): - try: - return self.gen.next() - except StopIteration: - raise RuntimeError("generator didn't yield") - - def __exit__(self, type, value, traceback): - if type is None: - try: - self.gen.next() - except StopIteration: - return - else: - raise RuntimeError("generator didn't stop") - else: - try: - self.gen.throw(type, value, traceback) - raise RuntimeError("generator didn't stop after throw()") - except StopIteration, exc: - # Suppress the exception *unless* it's the same exception that - # was passed to throw(). This prevents a StopIteration - # raised inside the "with" statement from being suppressed - return exc is not value - except: - # only re-raise if it's *not* the exception that was - # passed to throw(), because __exit__() must not raise - # an exception unless __exit__() itself failed. But throw() - # has to raise the exception to signal propagation, so this - # fixes the impedance mismatch between the throw() protocol - # and the __exit__() protocol. - # - if sys.exc_info()[1] is not value: - raise - - -def contextmanager(func): - """@contextmanager decorator. - - Typical usage: - - @contextmanager - def some_generator(<arguments>): - <setup> - try: - yield <value> - finally: - <cleanup> - - This makes this: - - with some_generator(<arguments>) as <variable>: - <body> - - equivalent to this: - - <setup> - try: - <variable> = <value> - <body> - finally: - <cleanup> - - """ - def helper(*args, **kwds): - return GeneratorContextManager(func(*args, **kwds)) - try: - helper.__name__ = func.__name__ - helper.__doc__ = func.__doc__ - helper.__dict__ = func.__dict__ - except: - pass - return helper - - -@contextmanager -def nested(*managers): - """Support multiple context managers in a single with-statement. - - Code like this: - - with nested(A, B, C) as (X, Y, Z): - <body> - - is equivalent to this: - - with A as X: - with B as Y: - with C as Z: - <body> - - """ - exits = [] - vars = [] - exc = (None, None, None) - try: - try: - for mgr in managers: - exit = mgr.__exit__ - enter = mgr.__enter__ - vars.append(enter()) - exits.append(exit) - yield vars - except: - exc = sys.exc_info() - finally: - while exits: - exit = exits.pop() - try: - if exit(*exc): - exc = (None, None, None) - except: - exc = sys.exc_info() - if exc != (None, None, None): - # Don't rely on sys.exc_info() still containing - # the right information. Another exception may - # have been raised and caught by an exit method - raise exc[0], exc[1], exc[2] - - -class closing(object): - """Context to automatically close something at the end of a block. - - Code like this: - - with closing(<module>.open(<arguments>)) as f: - <block> - - is equivalent to this: - - f = <module>.open(<arguments>) - try: - <block> - finally: - f.close() - - """ - def __init__(self, thing): - self.thing = thing - def __enter__(self): - return self.thing - def __exit__(self, *exc_info): - self.thing.close() Modified: branches/asm/src/org/python/core/PyString.java =================================================================== --- branches/asm/src/org/python/core/PyString.java 2008-06-30 08:18:38 UTC (rev 4823) +++ branches/asm/src/org/python/core/PyString.java 2008-06-30 08:59:43 UTC (rev 4824) @@ -712,7 +712,7 @@ @ExposedMethod public PyObject str___mod__(PyObject other){ - StringFormatter fmt = new StringFormatter(string, true); + StringFormatter fmt = new StringFormatter(string, false); return fmt.format(other); } @@ -2573,8 +2573,11 @@ case 's': case 'r': fill = ' '; + if (arg instanceof PyUnicode) { + needUnicode = true; + } if (c == 's') - if (unicodeCoercion) + if (unicodeCoercion || needUnicode) string = arg.__unicode__().toString(); else string = arg.__str__().toString(); @@ -2583,9 +2586,7 @@ if (precision >= 0 && string.length() > precision) { string = string.substring(0, precision); } - if (arg instanceof PyUnicode) { - needUnicode = true; - } + break; case 'i': case 'd': This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |