Commit 31bcad2a authored by Guido van Rossum's avatar Guido van Rossum

Merge alpha100 branch back to main trunk

parent c660f7fc
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -30,6 +30,10 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -30,6 +30,10 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/* "allobjects.c" -- Source for precompiled header "allobjects.h" */ /* "allobjects.c" -- Source for precompiled header "allobjects.h" */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef THINK_C #ifdef THINK_C
#define macintosh #define macintosh
#endif #endif
...@@ -37,7 +41,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -37,7 +41,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include "PROTO.h" #include "myproto.h"
#include "object.h" #include "object.h"
#include "objimpl.h" #include "objimpl.h"
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -28,7 +28,13 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -28,7 +28,13 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************/ ******************************************************************/
#ifdef MPW /* This is for MPW's File command */
#define assert(e) { if (!(e)) { printf("### Python: Assertion failed:\n\
File %s; Line %d\n", __FILE__, __LINE__); abort(); } }
#else
#define assert(e) { if (!(e)) { printf("Assertion failed\n"); abort(); } } #define assert(e) { if (!(e)) { printf("Assertion failed\n"); abort(); } }
#endif
#ifdef __cplusplus #ifdef __cplusplus
} }
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -31,6 +31,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -31,6 +31,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/* Built-in module interface */ /* Built-in module interface */
extern object *getbuiltin PROTO((object *)); extern object *getbuiltin PROTO((object *));
extern int setbuiltin PROTO((char *, object *));
#ifdef __cplusplus #ifdef __cplusplus
} }
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -35,6 +35,7 @@ object *call_object PROTO((object *, object *)); ...@@ -35,6 +35,7 @@ object *call_object PROTO((object *, object *));
object *getglobals PROTO((void)); object *getglobals PROTO((void));
object *getlocals PROTO((void)); object *getlocals PROTO((void));
object *getowner PROTO((void)); object *getowner PROTO((void));
object *getframe PROTO((void));
void printtraceback PROTO((object *)); void printtraceback PROTO((object *));
void flushline PROTO((void)); void flushline PROTO((void));
...@@ -87,7 +88,7 @@ extern void init_save_thread PROTO((void)); ...@@ -87,7 +88,7 @@ extern void init_save_thread PROTO((void));
extern object *save_thread PROTO((void)); extern object *save_thread PROTO((void));
extern void restore_thread PROTO((object *)); extern void restore_thread PROTO((object *));
#ifdef USE_THREAD #ifdef WITH_THREAD
#define BGN_SAVE { \ #define BGN_SAVE { \
object *_save; \ object *_save; \
...@@ -97,14 +98,14 @@ extern void restore_thread PROTO((object *)); ...@@ -97,14 +98,14 @@ extern void restore_thread PROTO((object *));
#define END_SAVE restore_thread(_save); \ #define END_SAVE restore_thread(_save); \
} }
#else /* !USE_THREAD */ #else /* !WITH_THREAD */
#define BGN_SAVE { #define BGN_SAVE {
#define RET_SAVE #define RET_SAVE
#define RES_SAVE #define RES_SAVE
#define END_SAVE } #define END_SAVE }
#endif /* !USE_THREAD */ #endif /* !WITH_THREAD */
#ifdef __cplusplus #ifdef __cplusplus
} }
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -35,7 +35,7 @@ typedef char *string; ...@@ -35,7 +35,7 @@ typedef char *string;
#define mknewlongobject(x) newintobject(x) #define mknewlongobject(x) newintobject(x)
#define mknewshortobject(x) newintobject((long)x) #define mknewshortobject(x) newintobject((long)x)
#define mknewfloatobject(x) newfloatobject(x) #define mknewfloatobject(x) newfloatobject(x)
#define mknewcharobject(c) mkvalue("c", c) #define mknewcharobject(ch) mkvalue("c", ch)
extern int getiobjectarg PROTO((object *args, int nargs, int i, object **p_a)); extern int getiobjectarg PROTO((object *args, int nargs, int i, object **p_a));
extern int getilongarg PROTO((object *args, int nargs, int i, long *p_a)); extern int getilongarg PROTO((object *args, int nargs, int i, long *p_a));
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -29,11 +29,15 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -29,11 +29,15 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************/ ******************************************************************/
/* Error codes passed around between file input, tokenizer, parser and /* Error codes passed around between file input, tokenizer, parser and
interpreter. This was necessary so we can turn them into Python interpreter. This is necessary so we can turn them into Python
exceptions at a higher level. */ exceptions at a higher level. Note that some errors have a
slightly different meaning when passed from the tokenizer to the
parser than when passed from the parser to the interpreter; e.g.
the parser only returns E_EOF when it hits EOF immediately, and it
never returns E_OK. */
#define E_OK 10 /* No error */ #define E_OK 10 /* No error */
#define E_EOF 11 /* (Unexpected) EOF read */ #define E_EOF 11 /* End Of File */
#define E_INTR 12 /* Interrupted */ #define E_INTR 12 /* Interrupted */
#define E_TOKEN 13 /* Bad token */ #define E_TOKEN 13 /* Bad token */
#define E_SYNTAX 14 /* Syntax error */ #define E_SYNTAX 14 /* Syntax error */
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -33,7 +33,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -33,7 +33,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
void err_set PROTO((object *)); void err_set PROTO((object *));
void err_setval PROTO((object *, object *)); void err_setval PROTO((object *, object *));
void err_setstr PROTO((object *, char *)); void err_setstr PROTO((object *, char *));
int err_occurred PROTO((void)); object *err_occurred PROTO((void));
void err_get PROTO((object **, object **)); void err_get PROTO((object **, object **));
void err_clear PROTO((void)); void err_clear PROTO((void));
...@@ -64,12 +64,13 @@ extern object *ZeroDivisionError; ...@@ -64,12 +64,13 @@ extern object *ZeroDivisionError;
extern int err_badarg PROTO((void)); extern int err_badarg PROTO((void));
extern object *err_nomem PROTO((void)); extern object *err_nomem PROTO((void));
extern object *err_errno PROTO((object *)); extern object *err_errno PROTO((object *));
extern void err_input PROTO((int));
extern void err_badcall PROTO((void)); extern void err_badcall PROTO((void));
extern object *err_getexc PROTO((void)); extern object *err_getexc PROTO((void));
extern int sigcheck PROTO((void)); /* In sigcheck.c or signalmodule.c */
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -35,6 +35,7 @@ extern typeobject Filetype; ...@@ -35,6 +35,7 @@ extern typeobject Filetype;
#define is_fileobject(op) ((op)->ob_type == &Filetype) #define is_fileobject(op) ((op)->ob_type == &Filetype)
extern object *newfileobject PROTO((char *, char *)); extern object *newfileobject PROTO((char *, char *));
extern void setfilebufsize PROTO((object *, int));
extern object *newopenfileobject extern object *newopenfileobject
PROTO((FILE *, char *, char *, int (*)FPROTO((FILE *)))); PROTO((FILE *, char *, char *, int (*)FPROTO((FILE *))));
extern FILE *getfilefile PROTO((object *)); extern FILE *getfilefile PROTO((object *));
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -52,6 +52,7 @@ typedef struct _frame { ...@@ -52,6 +52,7 @@ typedef struct _frame {
int f_iblock; /* index in f_blockstack */ int f_iblock; /* index in f_blockstack */
int f_lasti; /* Last instruction if called */ int f_lasti; /* Last instruction if called */
int f_lineno; /* Current line number */ int f_lineno; /* Current line number */
object *f_trace; /* Trace function */
} frameobject; } frameobject;
...@@ -70,11 +71,11 @@ frameobject * newframeobject PROTO( ...@@ -70,11 +71,11 @@ frameobject * newframeobject PROTO(
/* List access macros */ /* List access macros */
#ifdef NDEBUG #ifdef NDEBUG
#define GETITEM(v, i) GETLISTITEM((listobject *)(v), (i)) #define GETITEM(v, i) GETTUPLEITEM((tupleobject *)(v), (i))
#define GETITEMNAME(v, i) GETSTRINGVALUE((stringobject *)GETITEM((v), (i))) #define GETITEMNAME(v, i) GETSTRINGVALUE((stringobject *)GETITEM((v), (i)))
#else #else
#define GETITEM(v, i) getlistitem((v), (i)) #define GETITEM(v, i) gettupleitem((v), (i))
#define GETITEMNAME(v, i) getstringvalue(getlistitem((v), (i))) #define GETITEMNAME(v, i) getstringvalue(GETITEM(v, i))
#endif #endif
#define GETUSTRINGVALUE(s) ((unsigned char *)GETSTRINGVALUE(s)) #define GETUSTRINGVALUE(s) ((unsigned char *)GETSTRINGVALUE(s))
...@@ -95,6 +96,11 @@ block *pop_block PROTO((frameobject *)); ...@@ -95,6 +96,11 @@ block *pop_block PROTO((frameobject *));
object **extend_stack PROTO((frameobject *, int, int)); object **extend_stack PROTO((frameobject *, int, int));
/* Conversions between "fast locals" and locals in dictionary */
void locals_2_fast PROTO((frameobject *, int));
void fast_2_locals PROTO((frameobject *));
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -35,6 +35,8 @@ typedef struct { ...@@ -35,6 +35,8 @@ typedef struct {
object *func_code; object *func_code;
object *func_globals; object *func_globals;
object *func_name; object *func_name;
int func_argcount;
object *func_argdefs;
} funcobject; } funcobject;
extern typeobject Functype; extern typeobject Functype;
...@@ -44,6 +46,8 @@ extern typeobject Functype; ...@@ -44,6 +46,8 @@ extern typeobject Functype;
extern object *newfuncobject PROTO((object *, object *)); extern object *newfuncobject PROTO((object *, object *));
extern object *getfunccode PROTO((object *)); extern object *getfunccode PROTO((object *));
extern object *getfuncglobals PROTO((object *)); extern object *getfuncglobals PROTO((object *));
extern object *getfuncargstuff PROTO((object *, int *));
extern int setfuncargstuff PROTO((object *, int, object *));
#ifdef __cplusplus #ifdef __cplusplus
} }
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -34,7 +34,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -34,7 +34,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/* A label of an arc */ /* A label of an arc */
typedef struct _label { typedef struct {
int lb_type; int lb_type;
char *lb_str; char *lb_str;
} label; } label;
...@@ -43,21 +43,21 @@ typedef struct _label { ...@@ -43,21 +43,21 @@ typedef struct _label {
/* A list of labels */ /* A list of labels */
typedef struct _labellist { typedef struct {
int ll_nlabels; int ll_nlabels;
label *ll_label; label *ll_label;
} labellist; } labellist;
/* An arc from one state to another */ /* An arc from one state to another */
typedef struct _arc { typedef struct {
short a_lbl; /* Label of this arc */ short a_lbl; /* Label of this arc */
short a_arrow; /* State where this arc goes to */ short a_arrow; /* State where this arc goes to */
} arc; } arc;
/* A state in a DFA */ /* A state in a DFA */
typedef struct _state { typedef struct {
int s_narcs; int s_narcs;
arc *s_arc; /* Array of arcs */ arc *s_arc; /* Array of arcs */
...@@ -70,7 +70,7 @@ typedef struct _state { ...@@ -70,7 +70,7 @@ typedef struct _state {
/* A DFA */ /* A DFA */
typedef struct _dfa { typedef struct {
int d_type; /* Non-terminal this represents */ int d_type; /* Non-terminal this represents */
char *d_name; /* For printing */ char *d_name; /* For printing */
int d_initial; /* Initial state */ int d_initial; /* Initial state */
...@@ -81,7 +81,7 @@ typedef struct _dfa { ...@@ -81,7 +81,7 @@ typedef struct _dfa {
/* A grammar */ /* A grammar */
typedef struct _grammar { typedef struct {
int g_ndfas; int g_ndfas;
dfa *g_dfa; /* Array of DFAs */ dfa *g_dfa; /* Array of DFAs */
labellist g_ll; labellist g_ll;
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -62,6 +62,7 @@ extern int addlistitem PROTO((object *, object *)); ...@@ -62,6 +62,7 @@ extern int addlistitem PROTO((object *, object *));
extern object *getlistslice PROTO((object *, int, int)); extern object *getlistslice PROTO((object *, int, int));
extern int setlistslice PROTO((object *, int, int, object *)); extern int setlistslice PROTO((object *, int, int, object *));
extern int sortlist PROTO((object *)); extern int sortlist PROTO((object *));
extern object *listtuple PROTO((object *));
/* Macro, trading safety for speed */ /* Macro, trading safety for speed */
#define GETLISTITEM(op, i) ((op)->ob_item[i]) #define GETLISTITEM(op, i) ((op)->ob_item[i])
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -42,6 +42,7 @@ extern long getlongvalue PROTO((object *)); ...@@ -42,6 +42,7 @@ extern long getlongvalue PROTO((object *));
extern double dgetlongvalue PROTO((object *)); extern double dgetlongvalue PROTO((object *));
object *long_scan PROTO((char *, int)); object *long_scan PROTO((char *, int));
object *long_escan PROTO((char *, char **, int));
#ifdef __cplusplus #ifdef __cplusplus
} }
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -30,22 +30,29 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -30,22 +30,29 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/* Module support interface */ /* Module support interface */
#ifdef HAVE_PROTOTYPES #ifdef HAVE_STDARG_PROTOTYPES
#define USE_STDARG
#endif
#ifdef USE_STDARG
#include <stdarg.h> #include <stdarg.h>
extern int getargs PROTO((object *, char *, ...));
extern object *mkvalue PROTO((char *, ...));
#else #else
#include <varargs.h> #include <varargs.h>
/* Better to have no prototypes at all for varargs functions in this case */
extern int getargs();
extern object *mkvalue();
#endif #endif
extern object *initmodule PROTO((char *, struct methodlist *));
extern int getargs PROTO((object *, char *, ...));
extern int vgetargs PROTO((object *, char *, va_list)); extern int vgetargs PROTO((object *, char *, va_list));
extern object *mkvalue PROTO((char *, ...));
extern object *vmkvalue PROTO((char *, va_list)); extern object *vmkvalue PROTO((char *, va_list));
extern object *initmodule PROTO((char *, struct methodlist *));
extern object *initmodule2 PROTO((char *, struct methodlist *, object *));
/* The following are obsolete -- use getargs directly! */ /* The following are obsolete -- use getargs directly! */
#define getnoarg(v) getargs(v, "") #define getnoarg(v) getargs(v, "")
#define getintarg(v, a) getargs(v, "i", a) #define getintarg(v, a) getargs(v, "i", a)
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -32,41 +32,35 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -32,41 +32,35 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#ifdef macintosh #ifdef macintosh
#define ANY void #define ANY void
#ifndef THINK_C_3_0
#define HAVE_STDLIB
#endif
#endif
#ifdef sun
/* Maybe not for very old versions of SunOS ? */
#define HAVE_STDLIB
#endif
#ifdef sgi
#define HAVE_STDLIB
#endif #endif
#ifdef __STDC__ #ifdef __STDC__
#define ANY void #define ANY void
#define HAVE_STDLIB
#endif #endif
#ifdef __TURBOC__ #ifdef __TURBOC__
#define ANY void #define ANY void
#define HAVE_STDLIB
#endif #endif
#ifdef __GNUC__ #ifdef __GNUC__
#define ANY void #define ANY void
#define HAVE_STDLIB
#endif #endif
#ifndef ANY #ifndef ANY
#define ANY char #define ANY char
#endif #endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#else /* !HAVE_STDLIB */
extern ANY *malloc PROTO((size_t));
extern ANY *calloc PROTO((size_t, size_t));
extern ANY *realloc PROTO((ANY *, size_t));
extern void free PROTO((ANY *)); /* XXX sometimes int on Unix old systems */
#endif /* !HAVE_STDLIB */
#ifndef NULL #ifndef NULL
#define NULL 0 #define NULL ((ANY *)0)
#endif #endif
/* XXX Always allocate one extra byte, since some malloc's return NULL /* XXX Always allocate one extra byte, since some malloc's return NULL
...@@ -80,17 +74,6 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -80,17 +74,6 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#define DEL(p) free((ANY *)p) #define DEL(p) free((ANY *)p)
#define XDEL(p) if ((p) == NULL) ; else DEL(p) #define XDEL(p) if ((p) == NULL) ; else DEL(p)
#ifdef HAVE_STDLIB
#include <stdlib.h>
#define MALLARG size_t
#else
#define MALLARG size_t
extern ANY *malloc PROTO((MALLARG));
extern ANY *calloc PROTO((MALLARG, MALLARG));
extern ANY *realloc PROTO((ANY *, MALLARG));
extern void free PROTO((ANY *)); /* XXX sometimes int on Unix old systems */
#endif
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -28,38 +28,28 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -28,38 +28,28 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************/ ******************************************************************/
/* Common definitions for files that use the BSD select system call. /* Include file for users of select() */
This is so complicated because every UNIX variant requires that
you include a different set of headers. Customizing this one file
should be easier than patching each of the files using select()... */
/* NB caller must include <sys/types.h> */
/* XXX You may have to include some of these only if not already included */ #ifdef HAVE_SYS_SELECT_H
#include <sys/types.h>
#include <sys/time.h> /* Implies <time.h> everywhere, as far as I know */
#include <sys/param.h>
/* Hacks for various systems that need hand-holding... */
#ifdef _SEQUENT_
#include <sys/select.h> #include <sys/select.h>
/* Sequent doesn't seem to define struct timezone anywhere?!?! */
struct timezone {
int tz_minuteswest;
int tz_dsttime;
};
#endif
#ifdef _AIX /* I *think* this works */ #ifdef SYS_SELECT_WITH_SYS_TIME
/* AIX defines fd_set in a separate file. Sigh... */ #include "mytime.h"
#include <sys/select.h> #else /* !SYS_SELECT_WITH_SYS_TIME */
#endif #include <time.h>
#endif /* !SYS_SELECT_WITH_SYS_TIME */
#else /* !HAVE_SYS_SELECT_H */
#include "mytime.h"
#endif /* !HAVE_SYS_SELECT_H */
/* (Very) old versions of BSD don't define the FD_* set of macros. /* If the fd manipulation macros aren't defined,
The following will usually do... */ here is a set that should do the job */
#ifndef FD_SETSIZE #ifndef FD_SETSIZE
#define FD_SETSIZE 256 #define FD_SETSIZE 256
...@@ -67,12 +57,12 @@ struct timezone { ...@@ -67,12 +57,12 @@ struct timezone {
#ifndef FD_SET #ifndef FD_SET
typedef long fd_mask; typedef long fd_mask;
#define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */ #define NFDBITS (sizeof(fd_mask) * NBBY) /* bits per mask */
#ifndef howmany #ifndef howmany
#define howmany(x, y) (((x)+((y)-1))/(y)) #define howmany(x, y) (((x)+((y)-1))/(y))
#endif #endif /* howmany */
typedef struct fd_set { typedef struct fd_set {
fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)]; fd_mask fds_bits[howmany(FD_SETSIZE, NFDBITS)];
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -133,48 +133,66 @@ NB: the methods for certain type groups are now contained in separate ...@@ -133,48 +133,66 @@ NB: the methods for certain type groups are now contained in separate
method blocks. method blocks.
*/ */
typedef object * (*unaryfunc) PROTO((object *));
typedef object * (*binaryfunc) PROTO((object *, object *));
typedef int (*inquiry) PROTO((object *));
typedef int (*coercion) PROTO((object **, object **));
typedef object *(*intargfunc) PROTO((object *, int));
typedef object *(*intintargfunc) PROTO((object *, int, int));
typedef int(*intobjargproc) PROTO((object *, int, object *));
typedef int(*intintobjargproc) PROTO((object *, int, int, object *));
typedef int(*objobjargproc) PROTO((object *, object *, object *));
typedef struct { typedef struct {
object *(*nb_add) FPROTO((object *, object *)); binaryfunc nb_add;
object *(*nb_subtract) FPROTO((object *, object *)); binaryfunc nb_subtract;
object *(*nb_multiply) FPROTO((object *, object *)); binaryfunc nb_multiply;
object *(*nb_divide) FPROTO((object *, object *)); binaryfunc nb_divide;
object *(*nb_remainder) FPROTO((object *, object *)); binaryfunc nb_remainder;
object *(*nb_divmod) FPROTO((object *, object *)); binaryfunc nb_divmod;
object *(*nb_power) FPROTO((object *, object *)); binaryfunc nb_power;
object *(*nb_negative) FPROTO((object *)); unaryfunc nb_negative;
object *(*nb_positive) FPROTO((object *)); unaryfunc nb_positive;
object *(*nb_absolute) FPROTO((object *)); unaryfunc nb_absolute;
int (*nb_nonzero) FPROTO((object *)); inquiry nb_nonzero;
object *(*nb_invert) FPROTO((object *)); unaryfunc nb_invert;
object *(*nb_lshift) FPROTO((object *, object *)); binaryfunc nb_lshift;
object *(*nb_rshift) FPROTO((object *, object *)); binaryfunc nb_rshift;
object *(*nb_and) FPROTO((object *, object *)); binaryfunc nb_and;
object *(*nb_xor) FPROTO((object *, object *)); binaryfunc nb_xor;
object *(*nb_or) FPROTO((object *, object *)); binaryfunc nb_or;
int (*nb_coerce) FPROTO((object **, object **)); coercion nb_coerce;
object *(*nb_int) FPROTO((object *)); unaryfunc nb_int;
object *(*nb_long) FPROTO((object *)); unaryfunc nb_long;
object *(*nb_float) FPROTO((object *)); unaryfunc nb_float;
object *(*nb_oct) FPROTO((object *)); unaryfunc nb_oct;
object *(*nb_hex) FPROTO((object *)); unaryfunc nb_hex;
} number_methods; } number_methods;
typedef struct { typedef struct {
int (*sq_length) FPROTO((object *)); inquiry sq_length;
object *(*sq_concat) FPROTO((object *, object *)); binaryfunc sq_concat;
object *(*sq_repeat) FPROTO((object *, int)); intargfunc sq_repeat;
object *(*sq_item) FPROTO((object *, int)); intargfunc sq_item;
object *(*sq_slice) FPROTO((object *, int, int)); intintargfunc sq_slice;
int (*sq_ass_item) FPROTO((object *, int, object *)); intobjargproc sq_ass_item;
int (*sq_ass_slice) FPROTO((object *, int, int, object *)); intintobjargproc sq_ass_slice;
} sequence_methods; } sequence_methods;
typedef struct { typedef struct {
int (*mp_length) FPROTO((object *)); inquiry mp_length;
object *(*mp_subscript) FPROTO((object *, object *)); binaryfunc mp_subscript;
int (*mp_ass_subscript) FPROTO((object *, object *, object *)); objobjargproc mp_ass_subscript;
} mapping_methods; } mapping_methods;
typedef void (*destructor) PROTO((object *));
typedef int (*printfunc) PROTO((object *, FILE *, int));
typedef object *(*getattrfunc) PROTO((object *, char *));
typedef int (*setattrfunc) PROTO((object *, char *, object *));
typedef int (*cmpfunc) PROTO((object *, object *));
typedef object *(*reprfunc) PROTO((object *));
typedef long (*hashfunc) PROTO((object *));
typedef struct _typeobject { typedef struct _typeobject {
OB_VARHEAD OB_VARHEAD
char *tp_name; /* For printing */ char *tp_name; /* For printing */
...@@ -182,12 +200,12 @@ typedef struct _typeobject { ...@@ -182,12 +200,12 @@ typedef struct _typeobject {
/* Methods to implement standard operations */ /* Methods to implement standard operations */
void (*tp_dealloc) FPROTO((object *)); destructor tp_dealloc;
int (*tp_print) FPROTO((object *, FILE *, int)); printfunc tp_print;
object *(*tp_getattr) FPROTO((object *, char *)); getattrfunc tp_getattr;
int (*tp_setattr) FPROTO((object *, char *, object *)); setattrfunc tp_setattr;
int (*tp_compare) FPROTO((object *, object *)); cmpfunc tp_compare;
object *(*tp_repr) FPROTO((object *)); reprfunc tp_repr;
/* Method suites for standard classes */ /* Method suites for standard classes */
...@@ -197,7 +215,8 @@ typedef struct _typeobject { ...@@ -197,7 +215,8 @@ typedef struct _typeobject {
/* More standard operations (at end for binary compatibility) */ /* More standard operations (at end for binary compatibility) */
long (*tp_hash) FPROTO((object *)); hashfunc tp_hash;
binaryfunc tp_call;
#ifdef COUNT_ALLOCS #ifdef COUNT_ALLOCS
/* these must be last */ /* these must be last */
int tp_alloc; int tp_alloc;
...@@ -326,6 +345,29 @@ extern object NoObject; /* Don't use this directly */ ...@@ -326,6 +345,29 @@ extern object NoObject; /* Don't use this directly */
#define None (&NoObject) #define None (&NoObject)
/*
A common programming style in Python requires the forward declaration
of static, initialized structures, e.g. for a typeobject that is used
by the functions whose address must be used in the initializer.
Some compilers (notably SCO ODT 3.0, I seem to remember early AIX as
well) botch this if you use the static keyword for both declarations
(they allocate two objects, and use the first, uninitialized one until
the second declaration is encountered). Therefore, the forward
declaration should use the 'forwardstatic' keyword. This expands to
static on most systems, but to extern on a few. The actual storage
and name will still be static because the second declaration is
static, so no linker visible symbols will be generated. (Standard C
compilers take offense to the extern forward declaration of a static
object, so I can't just put extern in all cases. :-( )
*/
#ifdef BAD_STATIC_FORWARD
#define staticforward extern
#else
#define staticforward static
#endif /* BAD_STATIC_FORWARD */
/* /*
123456789-123456789-123456789-123456789-123456789-123456789-123456789-12 123456789-123456789-123456789-123456789-123456789-123456789-123456789-12
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -119,6 +119,8 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -119,6 +119,8 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#define LOAD_LOCAL 115 /* Index in name list */ #define LOAD_LOCAL 115 /* Index in name list */
#define LOAD_GLOBAL 116 /* Index in name list */ #define LOAD_GLOBAL 116 /* Index in name list */
#define SET_FUNC_ARGS 117 /* Argcount */
#define SETUP_LOOP 120 /* Target address (absolute) */ #define SETUP_LOOP 120 /* Target address (absolute) */
#define SETUP_EXCEPT 121 /* "" */ #define SETUP_EXCEPT 121 /* "" */
#define SETUP_FINALLY 122 /* "" */ #define SETUP_FINALLY 122 /* "" */
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -36,7 +36,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -36,7 +36,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#define DELIM ' ' #define DELIM ' '
#endif #endif
#ifdef MSDOS #if defined(MSDOS) || defined(NT)
#define SEP '\\' #define SEP '\\'
#define MAXPATHLEN 256 #define MAXPATHLEN 256
#define DELIM ';' #define DELIM ';'
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -30,9 +30,17 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -30,9 +30,17 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/* Parser-tokenizer link interface */ /* Parser-tokenizer link interface */
extern int parsestring PROTO((char *, grammar *, int, node **_ret)); typedef struct {
extern int parsefile PROTO((FILE *, char *, grammar *, int, int error;
char *, char *, node **)); char *filename;
int lineno;
int offset;
char *text;
} perrdetail;
extern node *parsestring PROTO((char *, grammar *, int, perrdetail *));
extern node *parsefile PROTO((FILE *, char *, grammar *, int,
char *, char *, perrdetail *));
#ifdef __cplusplus #ifdef __cplusplus
} }
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -31,9 +31,12 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -31,9 +31,12 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
/* Include files and extern declarations used by most of the parser. /* Include files and extern declarations used by most of the parser.
This is a precompiled header for THINK C. */ This is a precompiled header for THINK C. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef THINK_C #ifdef THINK_C
#define macintosh #define macintosh
/* #define THINK_C_3_0 /*** TURN THIS ON FOR THINK C 3.0 ***/
#endif #endif
#include <stdio.h> #include <stdio.h>
...@@ -44,17 +47,11 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -44,17 +47,11 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#undef label #undef label
#endif #endif
#ifdef THINK_C_3_0 #ifdef HAVE_STDLIB_H
#include <proto.h>
#endif
#ifdef macintosh
#ifndef THINK_C_3_0
#include <stdlib.h> #include <stdlib.h>
#endif #endif
#endif
#include "PROTO.h" #include "myproto.h"
#include "mymalloc.h" #include "mymalloc.h"
extern void fatal PROTO((char *)); extern void fatal PROTO((char *));
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -33,7 +33,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ...@@ -33,7 +33,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
void err_set PROTO((object *)); void err_set PROTO((object *));
void err_setval PROTO((object *, object *)); void err_setval PROTO((object *, object *));
void err_setstr PROTO((object *, char *)); void err_setstr PROTO((object *, char *));
int err_occurred PROTO((void)); object *err_occurred PROTO((void));
void err_get PROTO((object **, object **)); void err_get PROTO((object **, object **));
void err_clear PROTO((void)); void err_clear PROTO((void));
...@@ -64,12 +64,13 @@ extern object *ZeroDivisionError; ...@@ -64,12 +64,13 @@ extern object *ZeroDivisionError;
extern int err_badarg PROTO((void)); extern int err_badarg PROTO((void));
extern object *err_nomem PROTO((void)); extern object *err_nomem PROTO((void));
extern object *err_errno PROTO((object *)); extern object *err_errno PROTO((object *));
extern void err_input PROTO((int));
extern void err_badcall PROTO((void)); extern void err_badcall PROTO((void));
extern object *err_getexc PROTO((void)); extern object *err_getexc PROTO((void));
extern int sigcheck PROTO((void)); /* In sigcheck.c or signalmodule.c */
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -39,8 +39,8 @@ int run_script PROTO((FILE *, char *)); ...@@ -39,8 +39,8 @@ int run_script PROTO((FILE *, char *));
int run_tty_1 PROTO((FILE *, char *)); int run_tty_1 PROTO((FILE *, char *));
int run_tty_loop PROTO((FILE *, char *)); int run_tty_loop PROTO((FILE *, char *));
int parse_string PROTO((char *, int, struct _node **)); struct _node *parse_string PROTO((char *, int));
int parse_file PROTO((FILE *, char *, int, struct _node **)); struct _node *parse_file PROTO((FILE *, char *, int));
object *run_string PROTO((char *, int, object *, object *)); object *run_string PROTO((char *, int, object *, object *));
object *run_file PROTO((FILE *, char *, int, object *, object *)); object *run_file PROTO((FILE *, char *, int, object *, object *));
...@@ -51,6 +51,8 @@ void print_error PROTO((void)); ...@@ -51,6 +51,8 @@ void print_error PROTO((void));
void goaway PROTO((int)); void goaway PROTO((int));
void cleanup PROTO((void));
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
......
#ifndef _THREAD_H_included #ifndef _THREAD_H_included
#define _THREAD_H_included #define _THREAD_H_included
#define NO_EXIT_PROG /* don't define exit_prog() */
/* (the result is no use of signals on SGI) */
#ifndef PROTO #ifndef PROTO
#if defined(__STDC__) || defined(__cplusplus) #if defined(__STDC__) || defined(__cplusplus)
#define PROTO(args) args #define PROTO(args) args
...@@ -20,6 +23,7 @@ void init_thread PROTO((void)); ...@@ -20,6 +23,7 @@ void init_thread PROTO((void));
int start_new_thread PROTO((void (*)(void *), void *)); int start_new_thread PROTO((void (*)(void *), void *));
void exit_thread PROTO((void)); void exit_thread PROTO((void));
void _exit_thread PROTO((void)); void _exit_thread PROTO((void));
long get_thread_ident PROTO((void));
type_lock allocate_lock PROTO((void)); type_lock allocate_lock PROTO((void));
void free_lock PROTO((type_lock)); void free_lock PROTO((type_lock));
...@@ -33,8 +37,10 @@ void free_sema PROTO((type_sema)); ...@@ -33,8 +37,10 @@ void free_sema PROTO((type_sema));
void down_sema PROTO((type_sema)); void down_sema PROTO((type_sema));
void up_sema PROTO((type_sema)); void up_sema PROTO((type_sema));
#ifndef NO_EXIT_PROG
void exit_prog PROTO((int)); void exit_prog PROTO((int));
void _exit_prog PROTO((int)); void _exit_prog PROTO((int));
#endif
#ifdef __cplusplus #ifdef __cplusplus
} }
......
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
...@@ -66,6 +66,7 @@ extern object *newstringobject PROTO((char *)); ...@@ -66,6 +66,7 @@ extern object *newstringobject PROTO((char *));
extern unsigned int getstringsize PROTO((object *)); extern unsigned int getstringsize PROTO((object *));
extern char *getstringvalue PROTO((object *)); extern char *getstringvalue PROTO((object *));
extern void joinstring PROTO((object **, object *)); extern void joinstring PROTO((object **, object *));
extern void joinstring_decref PROTO((object **, object *));
extern int resizestring PROTO((object **, int)); extern int resizestring PROTO((object **, int));
extern object *formatstring PROTO((object *, object *)); extern object *formatstring PROTO((object *, object *));
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
#ifndef _THREAD_H_included #ifndef _THREAD_H_included
#define _THREAD_H_included #define _THREAD_H_included
#define NO_EXIT_PROG /* don't define exit_prog() */
/* (the result is no use of signals on SGI) */
#ifndef PROTO #ifndef PROTO
#if defined(__STDC__) || defined(__cplusplus) #if defined(__STDC__) || defined(__cplusplus)
#define PROTO(args) args #define PROTO(args) args
...@@ -20,6 +23,7 @@ void init_thread PROTO((void)); ...@@ -20,6 +23,7 @@ void init_thread PROTO((void));
int start_new_thread PROTO((void (*)(void *), void *)); int start_new_thread PROTO((void (*)(void *), void *));
void exit_thread PROTO((void)); void exit_thread PROTO((void));
void _exit_thread PROTO((void)); void _exit_thread PROTO((void));
long get_thread_ident PROTO((void));
type_lock allocate_lock PROTO((void)); type_lock allocate_lock PROTO((void));
void free_lock PROTO((type_lock)); void free_lock PROTO((type_lock));
...@@ -33,8 +37,10 @@ void free_sema PROTO((type_sema)); ...@@ -33,8 +37,10 @@ void free_sema PROTO((type_sema));
void down_sema PROTO((type_sema)); void down_sema PROTO((type_sema));
void up_sema PROTO((type_sema)); void up_sema PROTO((type_sema));
#ifndef NO_EXIT_PROG
void exit_prog PROTO((int)); void exit_prog PROTO((int));
void _exit_prog PROTO((int)); void _exit_prog PROTO((int));
#endif
#ifdef __cplusplus #ifdef __cplusplus
} }
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
...@@ -5,7 +5,7 @@ extern "C" { ...@@ -5,7 +5,7 @@ extern "C" {
#endif #endif
/*********************************************************** /***********************************************************
Copyright 1991, 1992, 1993 by Stichting Mathematisch Centrum, Copyright 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands. Amsterdam, The Netherlands.
All Rights Reserved All Rights Reserved
......
# A more or less complete user-defined wrapper around list objects # A more or less complete user-defined wrapper around list objects
class UserList: class UserList:
def __init__(self, *args): def __init__(self, list = None):
if len(args) > 1: raise TypeError, 'too many args'
self.data = [] self.data = []
if args: if list is not None:
list = args[0]
if type(list) == type(self.data): if type(list) == type(self.data):
self.data[:] = list self.data[:] = list
else: else:
......
...@@ -179,7 +179,10 @@ def _read_short(file): ...@@ -179,7 +179,10 @@ def _read_short(file):
def _read_string(file): def _read_string(file):
length = ord(file.read(1)) length = ord(file.read(1))
data = file.read(length) if length == 0:
data = ''
else:
data = file.read(length)
if length & 1 == 0: if length & 1 == 0:
dummy = file.read(1) dummy = file.read(1)
return data return data
......
import AL, SUNAUDIODEV
error = 'audiodev.error' error = 'audiodev.error'
class Play_Audio_sgi: class Play_Audio_sgi:
# Private instance variables # Private instance variables
access frameratelist, nchannelslist, sampwidthlist, oldparams, \ access frameratelist, nchannelslist, sampwidthlist, oldparams, \
params, config, inited_outrate, inited_width, \ params, config, inited_outrate, inited_width, \
inited_nchannels, port, converter: private inited_nchannels, port, converter, classinited: private
frameratelist = [(48000, AL.RATE_48000), classinited = 0
(44100, AL.RATE_44100), frameratelist = nchannelslist = sampwidthlist = None
(32000, AL.RATE_32000),
(22050, AL.RATE_22050), def initclass(self):
(16000, AL.RATE_16000), import AL
(11025, AL.RATE_11025), Play_Audio_sgi.frameratelist = [
( 8000, AL.RATE_8000)] (48000, AL.RATE_48000),
nchannelslist = [(1, AL.MONO), (44100, AL.RATE_44100),
(2, AL.STEREO)] (32000, AL.RATE_32000),
sampwidthlist = [(1, AL.SAMPLE_8), (22050, AL.RATE_22050),
(2, AL.SAMPLE_16), (16000, AL.RATE_16000),
(3, AL.SAMPLE_24)] (11025, AL.RATE_11025),
( 8000, AL.RATE_8000),
]
Play_Audio_sgi.nchannelslist = [
(1, AL.MONO),
(2, AL.STEREO),
]
Play_Audio_sgi.sampwidthlist = [
(1, AL.SAMPLE_8),
(2, AL.SAMPLE_16),
(3, AL.SAMPLE_24),
]
Play_Audio_sgi.classinited = 1
def __init__(self): def __init__(self):
import al import al, AL
if not self.classinited:
self.initclass()
self.oldparams = [] self.oldparams = []
self.params = [AL.OUTPUT_RATE, 0] self.params = [AL.OUTPUT_RATE, 0]
self.config = al.newconfig() self.config = al.newconfig()
...@@ -37,7 +49,7 @@ class Play_Audio_sgi: ...@@ -37,7 +49,7 @@ class Play_Audio_sgi:
if self.port: if self.port:
self.stop() self.stop()
if self.oldparams: if self.oldparams:
import al import al, AL
al.setparams(AL.DEFAULT_DEVICE, self.oldparams) al.setparams(AL.DEFAULT_DEVICE, self.oldparams)
self.oldparams = [] self.oldparams = []
...@@ -54,7 +66,7 @@ class Play_Audio_sgi: ...@@ -54,7 +66,7 @@ class Play_Audio_sgi:
self.port.closeport() self.port.closeport()
self.port = None self.port = None
if self.oldparams: if self.oldparams:
import al import al, AL
al.setparams(AL.DEFAULT_DEVICE, self.oldparams) al.setparams(AL.DEFAULT_DEVICE, self.oldparams)
self.oldparams = [] self.oldparams = []
...@@ -75,6 +87,7 @@ class Play_Audio_sgi: ...@@ -75,6 +87,7 @@ class Play_Audio_sgi:
break break
else: else:
if width == 0: if width == 0:
import AL
self.inited_width = 0 self.inited_width = 0
self.config.setwidth(AL.SAMPLE_16) self.config.setwidth(AL.SAMPLE_16)
self.converter = self.ulaw2lin self.converter = self.ulaw2lin
...@@ -94,7 +107,7 @@ class Play_Audio_sgi: ...@@ -94,7 +107,7 @@ class Play_Audio_sgi:
if not (self.inited_outrate and self.inited_nchannels): if not (self.inited_outrate and self.inited_nchannels):
raise error, 'params not specified' raise error, 'params not specified'
if not self.port: if not self.port:
import al import al, AL
self.port = al.openport('Python', 'w', self.config) self.port = al.openport('Python', 'w', self.config)
self.oldparams = self.params[:] self.oldparams = self.params[:]
al.getparams(AL.DEFAULT_DEVICE, self.oldparams) al.getparams(AL.DEFAULT_DEVICE, self.oldparams)
...@@ -156,7 +169,7 @@ class Play_Audio_sun: ...@@ -156,7 +169,7 @@ class Play_Audio_sun:
if not (self.inited_outrate and self.inited_width and self.inited_nchannels): if not (self.inited_outrate and self.inited_width and self.inited_nchannels):
raise error, 'params not specified' raise error, 'params not specified'
if not self.port: if not self.port:
import sunaudiodev import sunaudiodev, SUNAUDIODEV
self.port = sunaudiodev.open('w') self.port = sunaudiodev.open('w')
info = self.port.getinfo() info = self.port.getinfo()
info.o_sample_rate = self.outrate info.o_sample_rate = self.outrate
......
...@@ -17,6 +17,8 @@ class Bdb: # Basic Debugger ...@@ -17,6 +17,8 @@ class Bdb: # Basic Debugger
self.breaks = {} self.breaks = {}
def reset(self): def reset(self):
import linecache
linecache.checkcache()
self.botframe = None self.botframe = None
self.stopframe = None self.stopframe = None
self.returnframe = None self.returnframe = None
...@@ -134,11 +136,35 @@ class Bdb: # Basic Debugger ...@@ -134,11 +136,35 @@ class Bdb: # Basic Debugger
self.returnframe = frame self.returnframe = frame
self.quitting = 0 self.quitting = 0
def set_trace(self):
# Start debugging from here
try:
1 + ''
except:
frame = sys.exc_traceback.tb_frame.f_back
self.reset()
while frame:
frame.f_trace = self.trace_dispatch
self.botframe = frame
frame = frame.f_back
self.set_step()
sys.settrace(self.trace_dispatch)
def set_continue(self): def set_continue(self):
# Don't stop except at breakpoints or when finished # Don't stop except at breakpoints or when finished
self.stopframe = self.botframe self.stopframe = self.botframe
self.returnframe = None self.returnframe = None
self.quitting = 0 self.quitting = 0
if not self.breaks:
# no breakpoints; run without debugger overhead
sys.settrace(None)
try:
1 + '' # raise an exception
except:
frame = sys.exc_traceback.tb_frame.f_back
while frame and frame is not self.botframe:
del frame.f_trace
frame = frame.f_back
def set_quit(self): def set_quit(self):
self.stopframe = self.botframe self.stopframe = self.botframe
...@@ -177,7 +203,7 @@ class Bdb: # Basic Debugger ...@@ -177,7 +203,7 @@ class Bdb: # Basic Debugger
return 'There are no breakpoints in that file!' return 'There are no breakpoints in that file!'
del self.breaks[filename] del self.breaks[filename]
def clear_all_breaks(self, filename, lineno): def clear_all_breaks(self):
if not self.breaks: if not self.breaks:
return 'There are no breakpoints!' return 'There are no breakpoints!'
self.breaks = {} self.breaks = {}
...@@ -217,11 +243,14 @@ class Bdb: # Basic Debugger ...@@ -217,11 +243,14 @@ class Bdb: # Basic Debugger
# #
def format_stack_entry(self, frame_lineno): def format_stack_entry(self, frame_lineno):
import codehack, linecache, repr, string import linecache, repr, string
frame, lineno = frame_lineno frame, lineno = frame_lineno
filename = frame.f_code.co_filename filename = frame.f_code.co_filename
s = filename + '(' + `lineno` + ')' s = filename + '(' + `lineno` + ')'
s = s + codehack.getcodename(frame.f_code) if frame.f_code.co_name:
s = s + frame.f_code.co_name
else:
s = s + "<lambda>"
if frame.f_locals.has_key('__args__'): if frame.f_locals.has_key('__args__'):
args = frame.f_locals['__args__'] args = frame.f_locals['__args__']
if args is not None: if args is not None:
...@@ -269,17 +298,19 @@ class Bdb: # Basic Debugger ...@@ -269,17 +298,19 @@ class Bdb: # Basic Debugger
sys.settrace(None) sys.settrace(None)
def set_trace():
Bdb().set_trace()
# -------------------- testing -------------------- # -------------------- testing --------------------
class Tdb(Bdb): class Tdb(Bdb):
def user_call(self, frame, args): def user_call(self, frame, args):
import codehack name = frame.f_code.co_name
name = codehack.getcodename(frame.f_code)
if not name: name = '???' if not name: name = '???'
print '+++ call', name, args print '+++ call', name, args
def user_line(self, frame): def user_line(self, frame):
import linecache, string, codehack import linecache, string
name = codehack.getcodename(frame.f_code) name = frame.f_code.co_name
if not name: name = '???' if not name: name = '???'
fn = frame.f_code.co_filename fn = frame.f_code.co_filename
line = linecache.getline(fn, frame.f_lineno) line = linecache.getline(fn, frame.f_lineno)
...@@ -300,7 +331,5 @@ def bar(a): ...@@ -300,7 +331,5 @@ def bar(a):
return a/2 return a/2
def test(): def test():
import linecache
linecache.checkcache()
t = Tdb() t = Tdb()
t.run('import bdb; bdb.foo(10)') t.run('import bdb; bdb.foo(10)')
...@@ -106,12 +106,7 @@ def weekheader(width): ...@@ -106,12 +106,7 @@ def weekheader(width):
return str return str
# Print a month's calendar # Print a month's calendar
def prmonth(year, month, *rest): def prmonth(year, month, w = 0, l = 0):
if rest[2:]: raise TypeError, 'too many args'
w = 0
l = 0
if rest[0:]: w = rest[0]
if rest[1:]: l = rest[1]
w = max(2, w) w = max(2, w)
l = max(1, l) l = max(1, l)
print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1), print _center(month_name[month] + ' ' + `year`, 7*(w+1) - 1),
......
...@@ -56,8 +56,36 @@ class Cmd: ...@@ -56,8 +56,36 @@ class Cmd:
else: else:
import newdir import newdir
names = newdir.dir(self.__class__) names = newdir.dir(self.__class__)
cmds = [] cmds_doc = []
cmds_undoc = []
help = {}
for name in names:
if name[:5] == 'help_':
help[name[5:]]=1
for name in names: for name in names:
if name[:3] == 'do_': if name[:3] == 'do_':
cmds.append(name[3:]) cmd=name[3:]
print cmds if help.has_key(cmd):
cmds_doc.append(cmd)
del help[cmd]
else:
cmds_undoc.append(cmd)
print
self.print_topics("Documented commands (type help " \
"<topic>):",cmds_doc, 15, 80)
self.print_topics("Miscellaneous help topics:",
help.keys(), 15, 80)
self.print_topics("Undocumented commands:",
cmds_undoc, 15, 80)
def print_topics(self, header, cmds, cmdlen, maxcol):
if cmds:
print header;
print "="*len(header)
(cmds_per_line,junk)=divmod(maxcol,cmdlen)
col=cmds_per_line
for cmd in cmds:
if col==0: print
print (("%-"+`cmdlen`+"s") % cmd),
col = (col+1) % cmds_per_line
print "\n"
...@@ -7,6 +7,10 @@ import string ...@@ -7,6 +7,10 @@ import string
import os import os
import linecache import linecache
# XXX The functions getcodename() and getfuncname() are now obsolete
# XXX as code and function objects now have a name attribute --
# XXX co.co_name and f.func_name.
# Extract the function or class name from a code object. # Extract the function or class name from a code object.
# This is a bit of a hack, since a code object doesn't contain # This is a bit of a hack, since a code object doesn't contain
# the name directly. So what do we do: # the name directly. So what do we do:
......
...@@ -135,7 +135,8 @@ def_op('BREAK_LOOP', 80) ...@@ -135,7 +135,8 @@ def_op('BREAK_LOOP', 80)
def_op('RAISE_EXCEPTION', 81) def_op('RAISE_EXCEPTION', 81)
def_op('LOAD_LOCALS', 82) def_op('LOAD_LOCALS', 82)
def_op('RETURN_VALUE', 83) def_op('RETURN_VALUE', 83)
def_op('LOAD_GLOBALS', 84)
def_op('EXEC_STMT', 85)
def_op('BUILD_FUNCTION', 86) def_op('BUILD_FUNCTION', 86)
def_op('POP_BLOCK', 87) def_op('POP_BLOCK', 87)
def_op('END_FINALLY', 88) def_op('END_FINALLY', 88)
...@@ -173,6 +174,7 @@ jrel_op('FOR_LOOP', 114) # Number of bytes to skip ...@@ -173,6 +174,7 @@ jrel_op('FOR_LOOP', 114) # Number of bytes to skip
name_op('LOAD_LOCAL', 115) # Index in name list name_op('LOAD_LOCAL', 115) # Index in name list
name_op('LOAD_GLOBAL', 116) # Index in name list name_op('LOAD_GLOBAL', 116) # Index in name list
def_op('SET_FUNC_ARGS', 117) # Argcount
jrel_op('SETUP_LOOP', 120) # Distance to target address jrel_op('SETUP_LOOP', 120) # Distance to target address
jrel_op('SETUP_EXCEPT', 121) # "" jrel_op('SETUP_EXCEPT', 121) # ""
......
...@@ -9,10 +9,7 @@ ...@@ -9,10 +9,7 @@
# >>> from ftplib import FTP # >>> from ftplib import FTP
# >>> ftp = FTP('ftp.cwi.nl') # connect to host, default port # >>> ftp = FTP('ftp.cwi.nl') # connect to host, default port
# >>> ftp.login() # default, i.e.: user anonymous, passwd user@hostname # >>> ftp.login() # default, i.e.: user anonymous, passwd user@hostname
# >>> def handle_one_line(line): # callback for ftp.retrlines # >>> ftp.retrlines('LIST') # list directory contents
# ... print line
# ...
# >>> ftp.retrlines('LIST', handle_one_line) # list directory contents
# total 43 # total 43
# d--x--x--x 2 root root 512 Jul 1 16:50 bin # d--x--x--x 2 root root 512 Jul 1 16:50 bin
# d--x--x--x 2 root root 512 Sep 16 1991 etc # d--x--x--x 2 root root 512 Sep 16 1991 etc
...@@ -20,7 +17,7 @@ ...@@ -20,7 +17,7 @@
# drwxr-srwt 15 root ftp 10240 Nov 5 20:43 pub # drwxr-srwt 15 root ftp 10240 Nov 5 20:43 pub
# >>> ftp.quit() # >>> ftp.quit()
# #
# To download a file, use ftp.retrlines('RETR ' + filename, handle_one_line), # To download a file, use ftp.retrlines('RETR ' + filename),
# or ftp.retrbinary() with slightly different arguments. # or ftp.retrbinary() with slightly different arguments.
# To upload a file, use ftp.storlines() or ftp.storbinary(), which have # To upload a file, use ftp.storlines() or ftp.storbinary(), which have
# an open file as argument. # an open file as argument.
...@@ -30,9 +27,14 @@ ...@@ -30,9 +27,14 @@
import os import os
import sys import sys
import socket
import string import string
# Import SOCKS module if it exists, else standard socket module socket
try:
import SOCKS; socket = SOCKS
except ImportError:
import socket
# Magic number from <socket.h> # Magic number from <socket.h>
MSG_OOB = 0x1 # Process data out of band MSG_OOB = 0x1 # Process data out of band
...@@ -59,14 +61,6 @@ all_errors = (error_reply, error_temp, error_perm, error_proto, \ ...@@ -59,14 +61,6 @@ all_errors = (error_reply, error_temp, error_perm, error_proto, \
CRLF = '\r\n' CRLF = '\r\n'
# Next port to be used by makeport(), with PORT_OFFSET added
# (This is now only used when the python interpreter doesn't support
# the getsockname() method yet)
nextport = 0
PORT_OFFSET = 40000
PORT_CYCLE = 1000
# The class itself # The class itself
class FTP: class FTP:
...@@ -74,7 +68,7 @@ class FTP: ...@@ -74,7 +68,7 @@ class FTP:
# Initialize host to localhost, port to standard ftp port # Initialize host to localhost, port to standard ftp port
# Optional arguments are host (for connect()), # Optional arguments are host (for connect()),
# and user, passwd, acct (for login()) # and user, passwd, acct (for login())
def __init__(self, *args): def __init__(self, host = '', user = '', passwd = '', acct = ''):
# Initialize the instance to something mostly harmless # Initialize the instance to something mostly harmless
self.debugging = 0 self.debugging = 0
self.host = '' self.host = ''
...@@ -82,18 +76,16 @@ class FTP: ...@@ -82,18 +76,16 @@ class FTP:
self.sock = None self.sock = None
self.file = None self.file = None
self.welcome = None self.welcome = None
if args: if host:
self.connect(args[0]) self.connect(host)
if args[1:]: if user: self.login(user, passwd, acct)
apply(self.login, args[1:])
# Connect to host. Arguments: # Connect to host. Arguments:
# - host: hostname to connect to (default previous host) # - host: hostname to connect to (default previous host)
# - port: port to connect to (default previous port) # - port: port to connect to (default previous port)
def connect(self, *args): def connect(self, host = '', port = 0):
if args: self.host = args[0] if host: self.host = host
if args[1:]: self.port = args[1] if port: self.port = port
if args[2:]: raise TypeError, 'too many args'
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(self.host, self.port) self.sock.connect(self.host, self.port)
self.file = self.sock.makefile('r') self.file = self.sock.makefile('r')
...@@ -208,19 +200,8 @@ class FTP: ...@@ -208,19 +200,8 @@ class FTP:
def makeport(self): def makeport(self):
global nextport global nextport
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try: sock.listen(1)
getsockname = sock.getsockname host, port = sock.getsockname()
except AttributeError:
if self.debugging > 1:
print '*** getsockname not supported',
print '-- using manual port assignment ***'
port = nextport + PORT_OFFSET
nextport = (nextport + 1) % PORT_CYCLE
sock.bind('', port)
getsockname = None
sock.listen(0) # Assigns the port if not explicitly bound
if getsockname:
host, port = getsockname()
resp = self.sendport(port) resp = self.sendport(port)
return sock return sock
...@@ -235,13 +216,7 @@ class FTP: ...@@ -235,13 +216,7 @@ class FTP:
return conn return conn
# Login, default anonymous # Login, default anonymous
def login(self, *args): def login(self, user = '', passwd = '', acct = ''):
user = passwd = acct = ''
n = len(args)
if n > 3: raise TypeError, 'too many arguments'
if n > 0: user = args[0]
if n > 1: passwd = args[1]
if n > 2: acct = args[2]
if not user: user = 'anonymous' if not user: user = 'anonymous'
if user == 'anonymous' and passwd in ('', '-'): if user == 'anonymous' and passwd in ('', '-'):
thishost = socket.gethostname() thishost = socket.gethostname()
...@@ -278,11 +253,7 @@ class FTP: ...@@ -278,11 +253,7 @@ class FTP:
# The callback function is called for each line, with trailing # The callback function is called for each line, with trailing
# CRLF stripped. This creates a new port for you. # CRLF stripped. This creates a new port for you.
# print_lines is the default callback # print_lines is the default callback
def retrlines(self, cmd, *args): def retrlines(self, cmd, callback = None):
callback = None
if args:
callback = args[0]
if args[1:]: raise TypeError, 'too many args'
if not callback: callback = print_line if not callback: callback = print_line
resp = self.sendcmd('TYPE A') resp = self.sendcmd('TYPE A')
conn = self.transfercmd(cmd) conn = self.transfercmd(cmd)
...@@ -423,30 +394,22 @@ def print_line(line): ...@@ -423,30 +394,22 @@ def print_line(line):
# Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ... # Usage: ftp [-d] host [-l[dir]] [-d[dir]] [file] ...
def test(): def test():
import marshal import marshal
global nextport debugging = 0
try: while sys.argv[1] == '-d':
nextport = marshal.load(open('.@nextport', 'r')) debugging = debugging+1
except IOError: del sys.argv[1]
pass host = sys.argv[1]
try: ftp = FTP(host)
debugging = 0 ftp.set_debuglevel(debugging)
while sys.argv[1] == '-d': ftp.login()
debugging = debugging+1 for file in sys.argv[2:]:
del sys.argv[1] if file[:2] == '-l':
host = sys.argv[1] ftp.dir(file[2:])
ftp = FTP(host) elif file[:2] == '-d':
ftp.set_debuglevel(debugging) cmd = 'CWD'
ftp.login() if file[2:]: cmd = cmd + ' ' + file[2:]
for file in sys.argv[2:]: resp = ftp.sendcmd(cmd)
if file[:2] == '-l': else:
ftp.dir(file[2:]) ftp.retrbinary('RETR ' + file, \
elif file[:2] == '-d': sys.stdout.write, 1024)
cmd = 'CWD' ftp.quit()
if file[2:]: cmd = cmd + ' ' + file[2:]
resp = ftp.sendcmd(cmd)
else:
ftp.retrbinary('RETR ' + file, \
sys.stdout.write, 1024)
ftp.quit()
finally:
marshal.dump(nextport, open('.@nextport', 'w'))
# These lines were generated by h2py.py (see demo/scripts) # Generated by h2py from /usr/include/sys/fcntl.h
# from <sys/fcntl.h> on Irix 4.0.2.
# The applicability on other systems is not clear.
FNDELAY = 0x04 FNDELAY = 0x04
FAPPEND = 0x08 FAPPEND = 0x08
FSYNC = 0x10 FSYNC = 0x10
FRCACH = 0x20 FNONBLOCK = 0x80
FASYNC = 0x40 FASYNC = 0x1000
FNONBLK = 0x80 FNONBLK = FNONBLOCK
FCREAT = 0x100 FDIRECT = 0x8000
FTRUNC = 0x200 FCREAT = 0x0100
FEXCL = 0x400 FTRUNC = 0x0200
FNOCTTY = 0x800 FEXCL = 0x0400
FNOCTTY = 0x0800
O_RDONLY = 0 O_RDONLY = 0
O_WRONLY = 1 O_WRONLY = 1
O_RDWR = 2 O_RDWR = 2
O_ACCMODE = 0x3 O_NDELAY = 0x04
O_NDELAY = FNDELAY O_APPEND = 0x08
O_APPEND = FAPPEND O_SYNC = 0x10
O_SYNC = FSYNC O_NONBLOCK = 0x80
O_NONBLOCK = FNONBLK O_DIRECT = 0x8000
O_CREAT = FCREAT O_CREAT = 0x100
O_TRUNC = FTRUNC O_TRUNC = 0x200
O_EXCL = FEXCL O_EXCL = 0x400
O_NOCTTY = FNOCTTY O_NOCTTY = 0x800
F_DUPFD = 0 F_DUPFD = 0
F_GETFD = 1 F_GETFD = 1
F_SETFD = 2 F_SETFD = 2
F_GETFL = 3 F_GETFL = 3
F_SETFL = 4 F_SETFL = 4
F_GETLK = 5 F_GETLK = 14
F_O_GETLK = 5
F_GETLK = 14
F_SETLK = 6 F_SETLK = 6
F_SETLKW = 7 F_SETLKW = 7
F_CHKFL = 8 F_CHKFL = 8
...@@ -37,13 +37,17 @@ F_ALLOCSP = 10 ...@@ -37,13 +37,17 @@ F_ALLOCSP = 10
F_FREESP = 11 F_FREESP = 11
F_SETBSDLK = 12 F_SETBSDLK = 12
F_SETBSDLKW = 13 F_SETBSDLKW = 13
F_RGETLK = 20 F_DIOINFO = 30
F_RSETLK = 21 F_RSETLK = 20
F_RGETLK = 21
F_RSETLKW = 22 F_RSETLKW = 22
F_GETOWN = 10 F_GETOWN = 23
F_SETOWN = 11 F_SETOWN = 24
F_O_GETOWN = 10
F_O_SETOWN = 11
F_RDLCK = 01 F_RDLCK = 01
F_WRLCK = 02 F_WRLCK = 02
F_UNLCK = 03 F_UNLCK = 03
FD_CLOEXEC = 0x1 O_ACCMODE = 3
FD_NODUP_FORK = 0x2 FD_CLOEXEC = 1
FD_NODUP_FORK = 4
# Symbolic constants from <netinet/in.h>. # Generated by h2py from /usr/include/netinet/in.h
# These constants are SGI specific!
# See demo/scripts/h2py.py for a tool to help generate a version for
# your system.
IPPROTO_IP = 0 IPPROTO_IP = 0
IPPROTO_ICMP = 1 IPPROTO_ICMP = 1
IPPROTO_IGMP = 2 IPPROTO_IGMP = 2
...@@ -14,6 +10,8 @@ IPPROTO_UDP = 17 ...@@ -14,6 +10,8 @@ IPPROTO_UDP = 17
IPPROTO_IDP = 22 IPPROTO_IDP = 22
IPPROTO_TP = 29 IPPROTO_TP = 29
IPPROTO_XTP = 36 IPPROTO_XTP = 36
IPPROTO_HELLO = 63
IPPROTO_ND = 77
IPPROTO_EON = 80 IPPROTO_EON = 80
IPPROTO_RAW = 255 IPPROTO_RAW = 255
IPPROTO_MAX = 256 IPPROTO_MAX = 256
...@@ -42,6 +40,11 @@ INADDR_MAX_LOCAL_GROUP = 0xe00000ff ...@@ -42,6 +40,11 @@ INADDR_MAX_LOCAL_GROUP = 0xe00000ff
INADDR_NONE = 0xffffffff INADDR_NONE = 0xffffffff
IN_LOOPBACKNET = 127 IN_LOOPBACKNET = 127
IP_OPTIONS = 1 IP_OPTIONS = 1
IP_MULTICAST_IF = 2
IP_MULTICAST_TTL = 3
IP_MULTICAST_LOOP = 4
IP_ADD_MEMBERSHIP = 5
IP_DROP_MEMBERSHIP = 6
IP_HDRINCL = 7 IP_HDRINCL = 7
IP_TOS = 8 IP_TOS = 8
IP_TTL = 9 IP_TTL = 9
...@@ -49,11 +52,32 @@ IP_RECVOPTS = 10 ...@@ -49,11 +52,32 @@ IP_RECVOPTS = 10
IP_RECVRETOPTS = 11 IP_RECVRETOPTS = 11
IP_RECVDSTADDR = 12 IP_RECVDSTADDR = 12
IP_RETOPTS = 13 IP_RETOPTS = 13
IP_MULTICAST_IF = 2 IP_OPTIONS = 1
IP_MULTICAST_TTL = 3 IP_HDRINCL = 2
IP_MULTICAST_LOOP = 4 IP_TOS = 3
IP_ADD_MEMBERSHIP = 5 IP_TTL = 4
IP_DROP_MEMBERSHIP = 6 IP_RECVOPTS = 5
IP_RECVRETOPTS = 6
IP_RECVDSTADDR = 7
IP_RETOPTS = 8
IP_MULTICAST_IF = 20
IP_MULTICAST_TTL = 21
IP_MULTICAST_LOOP = 22
IP_ADD_MEMBERSHIP = 23
IP_DROP_MEMBERSHIP = 24
IRIX4_IP_OPTIONS = 1
IRIX4_IP_MULTICAST_IF = 2
IRIX4_IP_MULTICAST_TTL = 3
IRIX4_IP_MULTICAST_LOOP = 4
IRIX4_IP_ADD_MEMBERSHIP = 5
IRIX4_IP_DROP_MEMBERSHIP = 6
IRIX4_IP_HDRINCL = 7
IRIX4_IP_TOS = 8
IRIX4_IP_TTL = 9
IRIX4_IP_RECVOPTS = 10
IRIX4_IP_RECVRETOPTS = 11
IRIX4_IP_RECVDSTADDR = 12
IRIX4_IP_RETOPTS = 13
IP_DEFAULT_MULTICAST_TTL = 1 IP_DEFAULT_MULTICAST_TTL = 1
IP_DEFAULT_MULTICAST_LOOP = 1 IP_DEFAULT_MULTICAST_LOOP = 1
IP_MAX_MEMBERSHIPS = 20 IP_MAX_MEMBERSHIPS = 20
# Generated by h2py from /usr/include/sys/socket.h
SOCK_STREAM = 1 SOCK_STREAM = 1
SOCK_DGRAM = 2 SOCK_DGRAM = 2
SOCK_RAW = 3 SOCK_RAW = 3
SOCK_RDM = 4 SOCK_RDM = 4
SOCK_SEQPACKET = 5 SOCK_SEQPACKET = 5
NC_TPI_CLTS = 1
NC_TPI_COTS = 2
NC_TPI_COTS_ORD = 3
NC_TPI_RAW = 4
SOCK_DGRAM = NC_TPI_CLTS
SOCK_STREAM = NC_TPI_COTS
SOCK_RAW = NC_TPI_RAW
SOCK_RDM = 5
SOCK_SEQPACKET = 6
IRIX4_SOCK_STREAM = 1
IRIX4_SOCK_DGRAM = 2
IRIX4_SOCK_RAW = 3
IRIX4_SOCK_RDM = 4
IRIX4_SOCK_SEQPACKET = 5
SO_DEBUG = 0x0001 SO_DEBUG = 0x0001
SO_ACCEPTCONN = 0x0002 SO_ACCEPTCONN = 0x0002
SO_REUSEADDR = 0x0004 SO_REUSEADDR = 0x0004
...@@ -13,6 +28,9 @@ SO_USELOOPBACK = 0x0040 ...@@ -13,6 +28,9 @@ SO_USELOOPBACK = 0x0040
SO_LINGER = 0x0080 SO_LINGER = 0x0080
SO_OOBINLINE = 0x0100 SO_OOBINLINE = 0x0100
SO_REUSEPORT = 0x0200 SO_REUSEPORT = 0x0200
SO_ORDREL = 0x0200
SO_IMASOCKET = 0x0400
SO_CHAMELEON = 0x1000
SO_SNDBUF = 0x1001 SO_SNDBUF = 0x1001
SO_RCVBUF = 0x1002 SO_RCVBUF = 0x1002
SO_SNDLOWAT = 0x1003 SO_SNDLOWAT = 0x1003
...@@ -21,6 +39,7 @@ SO_SNDTIMEO = 0x1005 ...@@ -21,6 +39,7 @@ SO_SNDTIMEO = 0x1005
SO_RCVTIMEO = 0x1006 SO_RCVTIMEO = 0x1006
SO_ERROR = 0x1007 SO_ERROR = 0x1007
SO_TYPE = 0x1008 SO_TYPE = 0x1008
SO_PROTOTYPE = 0x1009
SOL_SOCKET = 0xffff SOL_SOCKET = 0xffff
AF_UNSPEC = 0 AF_UNSPEC = 0
AF_UNIX = 1 AF_UNIX = 1
...@@ -30,7 +49,6 @@ AF_PUP = 4 ...@@ -30,7 +49,6 @@ AF_PUP = 4
AF_CHAOS = 5 AF_CHAOS = 5
AF_NS = 6 AF_NS = 6
AF_ISO = 7 AF_ISO = 7
AF_OSI = AF_ISO
AF_ECMA = 8 AF_ECMA = 8
AF_DATAKIT = 9 AF_DATAKIT = 9
AF_CCITT = 10 AF_CCITT = 10
...@@ -44,7 +62,14 @@ AF_ROUTE = 17 ...@@ -44,7 +62,14 @@ AF_ROUTE = 17
AF_RAW = 18 AF_RAW = 18
AF_LINK = 18 AF_LINK = 18
pseudo_AF_XTP = 19 pseudo_AF_XTP = 19
AF_MAX = 20 AF_NIT = 17
AF_802 = 18
AF_OSI = 19
AF_X25 = 20
AF_OSINET = 21
AF_GOSIP = 22
AF_SDL = 23
AF_MAX = (AF_SDL+1)
PF_UNSPEC = AF_UNSPEC PF_UNSPEC = AF_UNSPEC
PF_UNIX = AF_UNIX PF_UNIX = AF_UNIX
PF_INET = AF_INET PF_INET = AF_INET
...@@ -53,7 +78,6 @@ PF_PUP = AF_PUP ...@@ -53,7 +78,6 @@ PF_PUP = AF_PUP
PF_CHAOS = AF_CHAOS PF_CHAOS = AF_CHAOS
PF_NS = AF_NS PF_NS = AF_NS
PF_ISO = AF_ISO PF_ISO = AF_ISO
PF_OSI = AF_ISO
PF_ECMA = AF_ECMA PF_ECMA = AF_ECMA
PF_DATAKIT = AF_DATAKIT PF_DATAKIT = AF_DATAKIT
PF_CCITT = AF_CCITT PF_CCITT = AF_CCITT
...@@ -67,11 +91,18 @@ PF_ROUTE = AF_ROUTE ...@@ -67,11 +91,18 @@ PF_ROUTE = AF_ROUTE
PF_LINK = AF_LINK PF_LINK = AF_LINK
PF_XTP = pseudo_AF_XTP PF_XTP = pseudo_AF_XTP
PF_RAW = AF_RAW PF_RAW = AF_RAW
PF_NIT = AF_NIT
PF_802 = AF_802
PF_OSI = AF_OSI
PF_X25 = AF_X25
PF_OSINET = AF_OSINET
PF_GOSIP = AF_GOSIP
PF_MAX = AF_MAX PF_MAX = AF_MAX
SOMAXCONN = 5 SOMAXCONN = 5
MSG_OOB = 0x1 MSG_OOB = 0x1
MSG_PEEK = 0x2 MSG_PEEK = 0x2
MSG_DONTROUTE = 0x4 MSG_DONTROUTE = 0x4
MSG_EOR = 0x8
MSG_BTAG = 0x40 MSG_BTAG = 0x40
MSG_ETAG = 0x80 MSG_ETAG = 0x80
MSG_MAXIOVLEN = 16 MSG_MAXIOVLEN = 16
...@@ -138,6 +138,19 @@ class Cddb: ...@@ -138,6 +138,19 @@ class Cddb:
continue continue
self.track[trackno] = value self.track[trackno] = value
f.close() f.close()
for i in range(2, len(self.track)):
track = self.track[i]
# if track title starts with `,', use initial part
# of previous track's title
if track[0] == ',':
try:
off = string.index(self.track[i - 1],
',')
except string.index_error:
pass
else:
self.track[i] = self.track[i-1][:off] \
+ track
def write(self): def write(self):
import posixpath import posixpath
...@@ -153,6 +166,17 @@ class Cddb: ...@@ -153,6 +166,17 @@ class Cddb:
f.write('album.title:\t' + self.title + '\n') f.write('album.title:\t' + self.title + '\n')
f.write('album.artist:\t' + self.artist + '\n') f.write('album.artist:\t' + self.artist + '\n')
f.write('album.toc:\t' + self.toc + '\n') f.write('album.toc:\t' + self.toc + '\n')
prevpref = None
for i in range(1, len(self.track)): for i in range(1, len(self.track)):
f.write('track' + `i` + '.title:\t' + self.track[i] + '\n') track = self.track[i]
try:
off = string.index(track, ',')
except string.index_error:
prevpref = None
else:
if prevpref and track[:off] == prevpref:
track = track[off:]
else:
prevpref = track[:off]
f.write('track' + `i` + '.title:\t' + track + '\n')
f.close() f.close()
...@@ -432,10 +432,10 @@ def _select_crfunc(fm, cl): ...@@ -432,10 +432,10 @@ def _select_crfunc(fm, cl):
def test(): def test():
import time import time
t0 = time.millitimer() t0 = time.time()
if len(sys.argv) == 2: if len(sys.argv) == 2:
forms = parse_forms(sys.argv[1]) forms = parse_forms(sys.argv[1])
t1 = time.millitimer() t1 = time.time()
print 'parse time:', 0.001*(t1-t0), 'sec.' print 'parse time:', 0.001*(t1-t0), 'sec.'
keys = forms.keys() keys = forms.keys()
keys.sort() keys.sort()
...@@ -443,8 +443,8 @@ def test(): ...@@ -443,8 +443,8 @@ def test():
_printform(forms[i]) _printform(forms[i])
elif len(sys.argv) == 3: elif len(sys.argv) == 3:
form = parse_form(sys.argv[1], sys.argv[2]) form = parse_form(sys.argv[1], sys.argv[2])
t1 = time.millitimer() t1 = time.time()
print 'parse time:', 0.001*(t1-t0), 'sec.' print 'parse time:', round(t1-t0, 3), 'sec.'
_printform(form) _printform(form)
else: else:
print 'Usage: test fdfile [form]' print 'Usage: test fdfile [form]'
......
...@@ -7,6 +7,10 @@ import string ...@@ -7,6 +7,10 @@ import string
import os import os
import linecache import linecache
# XXX The functions getcodename() and getfuncname() are now obsolete
# XXX as code and function objects now have a name attribute --
# XXX co.co_name and f.func_name.
# Extract the function or class name from a code object. # Extract the function or class name from a code object.
# This is a bit of a hack, since a code object doesn't contain # This is a bit of a hack, since a code object doesn't contain
# the name directly. So what do we do: # the name directly. So what do we do:
......
...@@ -65,11 +65,9 @@ def is_function(x): ...@@ -65,11 +65,9 @@ def is_function(x):
# Approximation of builtin dir(); but note that this lists the user's # Approximation of builtin dir(); but note that this lists the user's
# variables by default, not the current local name space. # variables by default, not the current local name space.
def dir(*args): def dir(x = None):
if len(args) > 0: if x is not None:
if len(args) == 1: return listattrs(x)
args = args[0]
return listattrs(args)
else: else:
import __main__ import __main__
return listattrs(__main__) return listattrs(__main__)
...@@ -41,12 +41,28 @@ def packsome(outfp, dirname, names): ...@@ -41,12 +41,28 @@ def packsome(outfp, dirname, names):
# Pack all files from a directory # Pack all files from a directory
def packall(outfp, dirname): def packall(outfp, dirname):
names = os.listdir(dirname) names = os.listdir(dirname)
try:
names.remove('.')
except:
pass
try:
names.remove('..')
except:
pass
names.sort() names.sort()
packsome(outfp, dirname, names) packsome(outfp, dirname, names)
# Pack all files from a directory that are not older than a give one # Pack all files from a directory that are not older than a give one
def packnotolder(outfp, dirname, oldest): def packnotolder(outfp, dirname, oldest):
names = os.listdir(dirname) names = os.listdir(dirname)
try:
names.remove('.')
except:
pass
try:
names.remove('..')
except:
pass
oldest = os.path.join(dirname, oldest) oldest = os.path.join(dirname, oldest)
st = os.stat(oldest) st = os.stat(oldest)
mtime = st[ST_MTIME] mtime = st[ST_MTIME]
...@@ -67,6 +83,14 @@ def packtree(outfp, dirname): ...@@ -67,6 +83,14 @@ def packtree(outfp, dirname):
print 'packtree', dirname print 'packtree', dirname
outfp.write('mkdir ' + unixfix(dirname) + '\n') outfp.write('mkdir ' + unixfix(dirname) + '\n')
names = os.listdir(dirname) names = os.listdir(dirname)
try:
names.remove('.')
except:
pass
try:
names.remove('..')
except:
pass
subdirs = [] subdirs = []
for name in names: for name in names:
fullname = os.path.join(dirname, name) fullname = os.path.join(dirname, name)
......
# Combine a real-time scheduling queue and stdwin event handling. # Combine a real-time scheduling queue and stdwin event handling.
# Uses the millisecond timer. # Keeps times in milliseconds.
import stdwin, stdwinq import stdwin, stdwinq
from stdwinevents import WE_TIMER from stdwinevents import WE_TIMER
...@@ -19,11 +19,11 @@ def delayfunc(msecs): ...@@ -19,11 +19,11 @@ def delayfunc(msecs):
mainloop.dispatch(event) mainloop.dispatch(event)
return return
# #
# Use millisleep for very short delays or if there are no windows # Use sleep for very short delays or if there are no windows
# #
if msecs < 100 or mainloop.countwindows() == 0: if msecs < 100 or mainloop.countwindows() == 0:
if msecs > 0: if msecs > 0:
time.millisleep(msecs) time.sleep(msecs * 0.001)
return return
# #
# Post a timer event on an arbitrary window and wait for it # Post a timer event on an arbitrary window and wait for it
...@@ -35,7 +35,10 @@ def delayfunc(msecs): ...@@ -35,7 +35,10 @@ def delayfunc(msecs):
if event[0] <> WE_TIMER: if event[0] <> WE_TIMER:
mainloop.dispatch(event) mainloop.dispatch(event)
q = sched.scheduler(time.millitimer, delayfunc) def millitimer():
return int(1000 * time.time())
q = sched.scheduler(millitimer, delayfunc)
# Export functions enter, enterabs and cancel just like a scheduler # Export functions enter, enterabs and cancel just like a scheduler
# #
......
...@@ -2,19 +2,19 @@ ...@@ -2,19 +2,19 @@
# File windows, a subclass of textwin (which is a subclass of gwin) # File windows, a subclass of textwin (which is a subclass of gwin)
import textwin import textwin
import builtin import __builtin__
# FILE WINDOW # FILE WINDOW
def open_readonly(fn): # Open a file window def open_readonly(fn): # Open a file window
fp = builtin.open(fn, 'r') fp = __builtin__.open(fn, 'r')
w = textwin.open_readonly(fn, fp.read()) w = textwin.open_readonly(fn, fp.read())
w.fn = fn w.fn = fn
return w return w
def open(fn): # Open a file window def open(fn): # Open a file window
fp = builtin.open(fn, 'r') fp = __builtin__.open(fn, 'r')
w = textwin.open(fn, fp.read()) w = textwin.open(fn, fp.read())
w.fn = fn w.fn = fn
return w return w
...@@ -241,7 +241,7 @@ class Wdb(bdb.Bdb, basewin.BaseWindow): # Window debugger ...@@ -241,7 +241,7 @@ class Wdb(bdb.Bdb, basewin.BaseWindow): # Window debugger
stdwin.fleep() stdwin.fleep()
def draw(self, detail): def draw(self, detail):
import linecache, codehack, string import linecache, string
d = self.win.begindrawing() d = self.win.begindrawing()
try: try:
h, v = 0, 0 h, v = 0, 0
...@@ -252,7 +252,7 @@ class Wdb(bdb.Bdb, basewin.BaseWindow): # Window debugger ...@@ -252,7 +252,7 @@ class Wdb(bdb.Bdb, basewin.BaseWindow): # Window debugger
else: else:
s = ' ' s = ' '
s = s + fn + '(' + `lineno` + ')' s = s + fn + '(' + `lineno` + ')'
s = s + codehack.getcodename(f.f_code) s = s + f.f_code.co_name
if f.f_locals.has_key('__args__'): if f.f_locals.has_key('__args__'):
args = f.f_locals['__args__'] args = f.f_locals['__args__']
if args is not None: if args is not None:
...@@ -286,6 +286,8 @@ def runcall(*args): ...@@ -286,6 +286,8 @@ def runcall(*args):
try: apply(x.runcall, args) try: apply(x.runcall, args)
finally: x.close() finally: x.close()
def set_trace():
Wdb().set_trace()
# Post-Mortem interface # Post-Mortem interface
...@@ -304,6 +306,4 @@ def pm(): ...@@ -304,6 +306,4 @@ def pm():
TESTCMD = 'import x; x.main()' TESTCMD = 'import x; x.main()'
def test(): def test():
import linecache
linecache.checkcache()
run(TESTCMD) run(TESTCMD)
# Various tools used by MIME-reading or MIME-writing programs. # Various tools used by MIME-reading or MIME-writing programs.
import string import os
import rfc822 import rfc822
import string
import tempfile
# A derived class of rfc822.Message that knows about MIME headers and # A derived class of rfc822.Message that knows about MIME headers and
...@@ -67,7 +69,7 @@ class Message(rfc822.Message): ...@@ -67,7 +69,7 @@ class Message(rfc822.Message):
def getencoding(self): def getencoding(self):
if self.encodingheader == None: if self.encodingheader == None:
return '7bit' return '7bit'
return self.encodingheader return string.lower(self.encodingheader)
def gettype(self): def gettype(self):
return self.type return self.type
...@@ -110,3 +112,75 @@ def choose_boundary(): ...@@ -110,3 +112,75 @@ def choose_boundary():
timestamp = `int(time.time())` timestamp = `int(time.time())`
seed = `rand.rand()` seed = `rand.rand()`
return _prefix + '.' + timestamp + '.' + seed return _prefix + '.' + timestamp + '.' + seed
# Subroutines for decoding some common content-transfer-types
# XXX This requires that uudecode and mmencode are in $PATH
def decode(input, output, encoding):
if decodetab.has_key(encoding):
pipethrough(input, decodetab[encoding], output)
else:
raise ValueError, \
'unknown Content-Transfer-Encoding: %s' % encoding
def encode(input, output, encoding):
if encodetab.has_key(encoding):
pipethrough(input, encodetab[encoding], output)
else:
raise ValueError, \
'unknown Content-Transfer-Encoding: %s' % encoding
uudecode_pipe = '''(
TEMP=/tmp/@uu.$$
sed "s%^begin [0-7][0-7]* .*%begin 600 $TEMP%" | uudecode
cat $TEMP
rm $TEMP
)'''
decodetab = {
'uuencode': uudecode_pipe,
'x-uuencode': uudecode_pipe,
'quoted-printable': 'mmencode -u -q',
'base64': 'mmencode -u -b',
}
encodetab = {
'x-uuencode': 'uuencode tempfile',
'uuencode': 'uuencode tempfile',
'quoted-printable': 'mmencode -q',
'base64': 'mmencode -b',
}
def pipeto(input, command):
pipe = os.popen(command, 'w')
copyliteral(input, pipe)
pipe.close()
def pipethrough(input, command, output):
tempname = tempfile.mktemp()
try:
temp = open(tempname, 'w')
except IOError:
print '*** Cannot create temp file', `tempname`
return
copyliteral(input, temp)
temp.close()
pipe = os.popen(command + ' <' + tempname, 'r')
copybinary(pipe, output)
pipe.close()
os.unlink(tempname)
def copyliteral(input, output):
while 1:
line = input.readline()
if not line: break
output.write(line)
def copybinary(input, output):
BUFSIZE = 8192
while 1:
line = input.read(BUFSIZE)
if not line: break
output.write(line)
...@@ -85,6 +85,17 @@ class MultiFile: ...@@ -85,6 +85,17 @@ class MultiFile:
err('*** Missing endmarker in MultiFile.readline()\n') err('*** Missing endmarker in MultiFile.readline()\n')
return '' return ''
# #
def readlines(self):
list = []
while 1:
line = self.readline()
if not line: break
list.append(line)
return list
#
def read(self): # Note: no size argument -- read until EOF only!
return string.joinfields(self.readlines(), '')
#
def next(self): def next(self):
while self.readline(): pass while self.readline(): pass
if self.level > 1 or self.last: if self.level > 1 or self.last:
......
...@@ -65,11 +65,9 @@ def is_function(x): ...@@ -65,11 +65,9 @@ def is_function(x):
# Approximation of builtin dir(); but note that this lists the user's # Approximation of builtin dir(); but note that this lists the user's
# variables by default, not the current local name space. # variables by default, not the current local name space.
def dir(*args): def dir(x = None):
if len(args) > 0: if x is not None:
if len(args) == 1: return listattrs(x)
args = args[0]
return listattrs(args)
else: else:
import __main__ import __main__
return listattrs(__main__) return listattrs(__main__)
...@@ -60,10 +60,7 @@ class NNTP: ...@@ -60,10 +60,7 @@ class NNTP:
# - host: hostname to connect to # - host: hostname to connect to
# - port: port to connect to (default the standard NNTP port) # - port: port to connect to (default the standard NNTP port)
def __init__(self, host, *args): def __init__(self, host, port = NNTP_PORT):
if len(args) > 1: raise TypeError, 'too many args'
if args: port = args[0]
else: port = NNTP_PORT
self.host = host self.host = host
self.port = port self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
......
# ospath.py is to {posix,mac}path.py what os.py is to modules {posix,mac} # ospath.py is obsolete
import os
try: exec 'from %s import *' % os.name
import posix
name = 'posix'
del posix
except ImportError:
import mac
name = 'mac'
del mac
if name == 'posix':
from posixpath import *
elif name == 'mac':
from macpath import *
...@@ -41,12 +41,28 @@ def packsome(outfp, dirname, names): ...@@ -41,12 +41,28 @@ def packsome(outfp, dirname, names):
# Pack all files from a directory # Pack all files from a directory
def packall(outfp, dirname): def packall(outfp, dirname):
names = os.listdir(dirname) names = os.listdir(dirname)
try:
names.remove('.')
except:
pass
try:
names.remove('..')
except:
pass
names.sort() names.sort()
packsome(outfp, dirname, names) packsome(outfp, dirname, names)
# Pack all files from a directory that are not older than a give one # Pack all files from a directory that are not older than a give one
def packnotolder(outfp, dirname, oldest): def packnotolder(outfp, dirname, oldest):
names = os.listdir(dirname) names = os.listdir(dirname)
try:
names.remove('.')
except:
pass
try:
names.remove('..')
except:
pass
oldest = os.path.join(dirname, oldest) oldest = os.path.join(dirname, oldest)
st = os.stat(oldest) st = os.stat(oldest)
mtime = st[ST_MTIME] mtime = st[ST_MTIME]
...@@ -67,6 +83,14 @@ def packtree(outfp, dirname): ...@@ -67,6 +83,14 @@ def packtree(outfp, dirname):
print 'packtree', dirname print 'packtree', dirname
outfp.write('mkdir ' + unixfix(dirname) + '\n') outfp.write('mkdir ' + unixfix(dirname) + '\n')
names = os.listdir(dirname) names = os.listdir(dirname)
try:
names.remove('.')
except:
pass
try:
names.remove('..')
except:
pass
subdirs = [] subdirs = []
for name in names: for name in names:
fullname = os.path.join(dirname, name) fullname = os.path.join(dirname, name)
......
...@@ -61,9 +61,10 @@ u(p) ...@@ -61,9 +61,10 @@ u(p)
Move the current frame one level up in the stack trace Move the current frame one level up in the stack trace
(to a newer frame). (to a newer frame).
b(reak) [lineno] b(reak) [lineno | function]
With a line number argument, set a break there in the current file. With a line number argument, set a break there in the current
Without argument, list all breaks. file. With a function name, set a break at the entry of that
function. Without argument, list all breaks.
cl(ear) [lineno] cl(ear) [lineno]
With a line number argument, clear that break in the current file. With a line number argument, clear that break in the current file.
......
...@@ -74,17 +74,31 @@ class Pdb(bdb.Bdb, cmd.Cmd): ...@@ -74,17 +74,31 @@ class Pdb(bdb.Bdb, cmd.Cmd):
# Return true to exit from the command loop # Return true to exit from the command loop
do_h = cmd.Cmd.do_help do_h = cmd.Cmd.do_help
def do_break(self, arg): def do_break(self, arg):
if not arg: if not arg:
print self.get_all_breaks() # XXX print self.get_all_breaks() # XXX
return return
try: # Try line number as argument
try:
lineno = int(eval(arg)) lineno = int(eval(arg))
filename = self.curframe.f_code.co_filename
except: except:
print '*** Error in argument:', `arg` # Try function name as the argument
return import codehack
filename = self.curframe.f_code.co_filename try:
func = eval(arg, self.curframe.f_globals,
self.curframe.f_locals)
if hasattr(func, 'im_func'):
func = func.im_func
code = func.func_code
except:
print '*** Could not eval argument:', arg
return
lineno = codehack.getlineno(code)
filename = code.co_filename
# now set the break point
err = self.set_break(filename, lineno) err = self.set_break(filename, lineno)
if err: print '***', err if err: print '***', err
do_b = do_break do_b = do_break
...@@ -159,10 +173,10 @@ class Pdb(bdb.Bdb, cmd.Cmd): ...@@ -159,10 +173,10 @@ class Pdb(bdb.Bdb, cmd.Cmd):
do_q = do_quit do_q = do_quit
def do_args(self, arg): def do_args(self, arg):
if self.curframe.f_locals.has_key('__return__'): if self.curframe.f_locals.has_key('__args__'):
print `self.curframe.f_locals['__return__']` print `self.curframe.f_locals['__args__']`
else: else:
print '*** Not arguments?!' print '*** No arguments?!'
do_a = do_args do_a = do_args
def do_retval(self, arg): def do_retval(self, arg):
...@@ -229,7 +243,6 @@ class Pdb(bdb.Bdb, cmd.Cmd): ...@@ -229,7 +243,6 @@ class Pdb(bdb.Bdb, cmd.Cmd):
do_l = do_list do_l = do_list
def do_whatis(self, arg): def do_whatis(self, arg):
import codehack
try: try:
value = eval(arg, self.curframe.f_globals, \ value = eval(arg, self.curframe.f_globals, \
self.curframe.f_locals) self.curframe.f_locals)
...@@ -241,13 +254,13 @@ class Pdb(bdb.Bdb, cmd.Cmd): ...@@ -241,13 +254,13 @@ class Pdb(bdb.Bdb, cmd.Cmd):
try: code = value.func_code try: code = value.func_code
except: pass except: pass
if code: if code:
print 'Function', codehack.getcodename(code) print 'Function', code.co_name
return return
# Is it an instance method? # Is it an instance method?
try: code = value.im_func.func_code try: code = value.im_func.func_code
except: pass except: pass
if code: if code:
print 'Method', codehack.getcodename(code) print 'Method', code.co_name
return return
# None of the above... # None of the above...
print type(value) print type(value)
...@@ -276,6 +289,137 @@ class Pdb(bdb.Bdb, cmd.Cmd): ...@@ -276,6 +289,137 @@ class Pdb(bdb.Bdb, cmd.Cmd):
print self.format_stack_entry(frame_lineno) print self.format_stack_entry(frame_lineno)
# Help methods (derived from pdb.doc)
def help_help(self):
self.help_h()
def help_h(self):
print """h(elp)
Without argument, print the list of available commands.
With a command name as argument, print help about that command
"help pdb" pipes the full documentation file to the $PAGER
"help exec" gives help on the ! command"""
def help_where(self):
self.help_w()
def help_w(self):
print """w(here)
Print a stack trace, with the most recent frame at the bottom.
An arrow indicates the "current frame", which determines the
context of most commands."""
def help_down(self):
self.help_d()
def help_d(self):
print """d(own)
Move the current frame one level down in the stack trace
(to an older frame)."""
def help_up(self):
self.help_u()
def help_u(self):
print """u(p)
Move the current frame one level up in the stack trace
(to a newer frame)."""
def help_break(self):
self.help_b()
def help_b(self):
print """b(reak) [lineno | function]
With a line number argument, set a break there in the current
file. With a function name, set a break at the entry of that
function. Without argument, list all breaks."""
def help_clear(self):
self.help_cl()
def help_cl(self):
print """cl(ear) [lineno]
With a line number argument, clear that break in the current file.
Without argument, clear all breaks (but first ask confirmation)."""
def help_step(self):
self.help_s()
def help_s(self):
print """s(tep)
Execute the current line, stop at the first possible occasion
(either in a function that is called or in the current function)."""
def help_next(self):
self.help_n()
def help_n(self):
print """n(ext)
Continue execution until the next line in the current function
is reached or it returns."""
def help_return(self):
self.help_r()
def help_r(self):
print """r(eturn)
Continue execution until the current function returns."""
def help_continue(self):
self.help_c()
def help_cont(self):
self.help_c()
def help_c(self):
print """c(ont(inue))
Continue execution, only stop when a breakpoint is encountered."""
def help_list(self):
self.help_l()
def help_l(self):
print """l(ist) [first [,last]]
List source code for the current file.
Without arguments, list 11 lines around the current line
or continue the previous listing.
With one argument, list 11 lines starting at that line.
With two arguments, list the given range;
if the second argument is less than the first, it is a count."""
def help_args(self):
self.help_a()
def help_a(self):
print """a(rgs)
Print the argument list of the current function."""
def help_p(self):
print """p expression
Print the value of the expression."""
def help_exec(self):
print """(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
(Pdb)"""
def help_quit(self):
self.help_q()
def help_q(self):
print """q(uit) Quit from the debugger.
The program being executed is aborted."""
def help_pdb(self):
help()
# Simplified interface # Simplified interface
def run(statement): def run(statement):
...@@ -287,6 +431,8 @@ def runctx(statement, globals, locals): ...@@ -287,6 +431,8 @@ def runctx(statement, globals, locals):
def runcall(*args): def runcall(*args):
apply(Pdb().runcall, args) apply(Pdb().runcall, args)
def set_trace():
Pdb().set_trace()
# Post-Mortem interface # Post-Mortem interface
...@@ -306,8 +452,6 @@ def pm(): ...@@ -306,8 +452,6 @@ def pm():
TESTCMD = 'import x; x.main()' TESTCMD = 'import x; x.main()'
def test(): def test():
import linecache
linecache.checkcache()
run(TESTCMD) run(TESTCMD)
# print help # print help
......
# These lines were generated by h2py.py (see demo/scripts) # Generated by h2py from /usr/include/sys/fcntl.h
# from <sys/fcntl.h> on Irix 4.0.2.
# The applicability on other systems is not clear.
FNDELAY = 0x04 FNDELAY = 0x04
FAPPEND = 0x08 FAPPEND = 0x08
FSYNC = 0x10 FSYNC = 0x10
FRCACH = 0x20 FNONBLOCK = 0x80
FASYNC = 0x40 FASYNC = 0x1000
FNONBLK = 0x80 FNONBLK = FNONBLOCK
FCREAT = 0x100 FDIRECT = 0x8000
FTRUNC = 0x200 FCREAT = 0x0100
FEXCL = 0x400 FTRUNC = 0x0200
FNOCTTY = 0x800 FEXCL = 0x0400
FNOCTTY = 0x0800
O_RDONLY = 0 O_RDONLY = 0
O_WRONLY = 1 O_WRONLY = 1
O_RDWR = 2 O_RDWR = 2
O_ACCMODE = 0x3 O_NDELAY = 0x04
O_NDELAY = FNDELAY O_APPEND = 0x08
O_APPEND = FAPPEND O_SYNC = 0x10
O_SYNC = FSYNC O_NONBLOCK = 0x80
O_NONBLOCK = FNONBLK O_DIRECT = 0x8000
O_CREAT = FCREAT O_CREAT = 0x100
O_TRUNC = FTRUNC O_TRUNC = 0x200
O_EXCL = FEXCL O_EXCL = 0x400
O_NOCTTY = FNOCTTY O_NOCTTY = 0x800
F_DUPFD = 0 F_DUPFD = 0
F_GETFD = 1 F_GETFD = 1
F_SETFD = 2 F_SETFD = 2
F_GETFL = 3 F_GETFL = 3
F_SETFL = 4 F_SETFL = 4
F_GETLK = 5 F_GETLK = 14
F_O_GETLK = 5
F_GETLK = 14
F_SETLK = 6 F_SETLK = 6
F_SETLKW = 7 F_SETLKW = 7
F_CHKFL = 8 F_CHKFL = 8
...@@ -37,13 +37,17 @@ F_ALLOCSP = 10 ...@@ -37,13 +37,17 @@ F_ALLOCSP = 10
F_FREESP = 11 F_FREESP = 11
F_SETBSDLK = 12 F_SETBSDLK = 12
F_SETBSDLKW = 13 F_SETBSDLKW = 13
F_RGETLK = 20 F_DIOINFO = 30
F_RSETLK = 21 F_RSETLK = 20
F_RGETLK = 21
F_RSETLKW = 22 F_RSETLKW = 22
F_GETOWN = 10 F_GETOWN = 23
F_SETOWN = 11 F_SETOWN = 24
F_O_GETOWN = 10
F_O_SETOWN = 11
F_RDLCK = 01 F_RDLCK = 01
F_WRLCK = 02 F_WRLCK = 02
F_UNLCK = 03 F_UNLCK = 03
FD_CLOEXEC = 0x1 O_ACCMODE = 3
FD_NODUP_FORK = 0x2 FD_CLOEXEC = 1
FD_NODUP_FORK = 4
# Symbolic constants from <netinet/in.h>. # Generated by h2py from /usr/include/netinet/in.h
# These constants are SGI specific!
# See demo/scripts/h2py.py for a tool to help generate a version for
# your system.
IPPROTO_IP = 0 IPPROTO_IP = 0
IPPROTO_ICMP = 1 IPPROTO_ICMP = 1
IPPROTO_IGMP = 2 IPPROTO_IGMP = 2
...@@ -14,6 +10,8 @@ IPPROTO_UDP = 17 ...@@ -14,6 +10,8 @@ IPPROTO_UDP = 17
IPPROTO_IDP = 22 IPPROTO_IDP = 22
IPPROTO_TP = 29 IPPROTO_TP = 29
IPPROTO_XTP = 36 IPPROTO_XTP = 36
IPPROTO_HELLO = 63
IPPROTO_ND = 77
IPPROTO_EON = 80 IPPROTO_EON = 80
IPPROTO_RAW = 255 IPPROTO_RAW = 255
IPPROTO_MAX = 256 IPPROTO_MAX = 256
...@@ -42,6 +40,11 @@ INADDR_MAX_LOCAL_GROUP = 0xe00000ff ...@@ -42,6 +40,11 @@ INADDR_MAX_LOCAL_GROUP = 0xe00000ff
INADDR_NONE = 0xffffffff INADDR_NONE = 0xffffffff
IN_LOOPBACKNET = 127 IN_LOOPBACKNET = 127
IP_OPTIONS = 1 IP_OPTIONS = 1
IP_MULTICAST_IF = 2
IP_MULTICAST_TTL = 3
IP_MULTICAST_LOOP = 4
IP_ADD_MEMBERSHIP = 5
IP_DROP_MEMBERSHIP = 6
IP_HDRINCL = 7 IP_HDRINCL = 7
IP_TOS = 8 IP_TOS = 8
IP_TTL = 9 IP_TTL = 9
...@@ -49,11 +52,32 @@ IP_RECVOPTS = 10 ...@@ -49,11 +52,32 @@ IP_RECVOPTS = 10
IP_RECVRETOPTS = 11 IP_RECVRETOPTS = 11
IP_RECVDSTADDR = 12 IP_RECVDSTADDR = 12
IP_RETOPTS = 13 IP_RETOPTS = 13
IP_MULTICAST_IF = 2 IP_OPTIONS = 1
IP_MULTICAST_TTL = 3 IP_HDRINCL = 2
IP_MULTICAST_LOOP = 4 IP_TOS = 3
IP_ADD_MEMBERSHIP = 5 IP_TTL = 4
IP_DROP_MEMBERSHIP = 6 IP_RECVOPTS = 5
IP_RECVRETOPTS = 6
IP_RECVDSTADDR = 7
IP_RETOPTS = 8
IP_MULTICAST_IF = 20
IP_MULTICAST_TTL = 21
IP_MULTICAST_LOOP = 22
IP_ADD_MEMBERSHIP = 23
IP_DROP_MEMBERSHIP = 24
IRIX4_IP_OPTIONS = 1
IRIX4_IP_MULTICAST_IF = 2
IRIX4_IP_MULTICAST_TTL = 3
IRIX4_IP_MULTICAST_LOOP = 4
IRIX4_IP_ADD_MEMBERSHIP = 5
IRIX4_IP_DROP_MEMBERSHIP = 6
IRIX4_IP_HDRINCL = 7
IRIX4_IP_TOS = 8
IRIX4_IP_TTL = 9
IRIX4_IP_RECVOPTS = 10
IRIX4_IP_RECVRETOPTS = 11
IRIX4_IP_RECVDSTADDR = 12
IRIX4_IP_RETOPTS = 13
IP_DEFAULT_MULTICAST_TTL = 1 IP_DEFAULT_MULTICAST_TTL = 1
IP_DEFAULT_MULTICAST_LOOP = 1 IP_DEFAULT_MULTICAST_LOOP = 1
IP_MAX_MEMBERSHIPS = 20 IP_MAX_MEMBERSHIPS = 20
# Generated by h2py from /usr/include/sys/socket.h
SOCK_STREAM = 1 SOCK_STREAM = 1
SOCK_DGRAM = 2 SOCK_DGRAM = 2
SOCK_RAW = 3 SOCK_RAW = 3
SOCK_RDM = 4 SOCK_RDM = 4
SOCK_SEQPACKET = 5 SOCK_SEQPACKET = 5
NC_TPI_CLTS = 1
NC_TPI_COTS = 2
NC_TPI_COTS_ORD = 3
NC_TPI_RAW = 4
SOCK_DGRAM = NC_TPI_CLTS
SOCK_STREAM = NC_TPI_COTS
SOCK_RAW = NC_TPI_RAW
SOCK_RDM = 5
SOCK_SEQPACKET = 6
IRIX4_SOCK_STREAM = 1
IRIX4_SOCK_DGRAM = 2
IRIX4_SOCK_RAW = 3
IRIX4_SOCK_RDM = 4
IRIX4_SOCK_SEQPACKET = 5
SO_DEBUG = 0x0001 SO_DEBUG = 0x0001
SO_ACCEPTCONN = 0x0002 SO_ACCEPTCONN = 0x0002
SO_REUSEADDR = 0x0004 SO_REUSEADDR = 0x0004
...@@ -13,6 +28,9 @@ SO_USELOOPBACK = 0x0040 ...@@ -13,6 +28,9 @@ SO_USELOOPBACK = 0x0040
SO_LINGER = 0x0080 SO_LINGER = 0x0080
SO_OOBINLINE = 0x0100 SO_OOBINLINE = 0x0100
SO_REUSEPORT = 0x0200 SO_REUSEPORT = 0x0200
SO_ORDREL = 0x0200
SO_IMASOCKET = 0x0400
SO_CHAMELEON = 0x1000
SO_SNDBUF = 0x1001 SO_SNDBUF = 0x1001
SO_RCVBUF = 0x1002 SO_RCVBUF = 0x1002
SO_SNDLOWAT = 0x1003 SO_SNDLOWAT = 0x1003
...@@ -21,6 +39,7 @@ SO_SNDTIMEO = 0x1005 ...@@ -21,6 +39,7 @@ SO_SNDTIMEO = 0x1005
SO_RCVTIMEO = 0x1006 SO_RCVTIMEO = 0x1006
SO_ERROR = 0x1007 SO_ERROR = 0x1007
SO_TYPE = 0x1008 SO_TYPE = 0x1008
SO_PROTOTYPE = 0x1009
SOL_SOCKET = 0xffff SOL_SOCKET = 0xffff
AF_UNSPEC = 0 AF_UNSPEC = 0
AF_UNIX = 1 AF_UNIX = 1
...@@ -30,7 +49,6 @@ AF_PUP = 4 ...@@ -30,7 +49,6 @@ AF_PUP = 4
AF_CHAOS = 5 AF_CHAOS = 5
AF_NS = 6 AF_NS = 6
AF_ISO = 7 AF_ISO = 7
AF_OSI = AF_ISO
AF_ECMA = 8 AF_ECMA = 8
AF_DATAKIT = 9 AF_DATAKIT = 9
AF_CCITT = 10 AF_CCITT = 10
...@@ -44,7 +62,14 @@ AF_ROUTE = 17 ...@@ -44,7 +62,14 @@ AF_ROUTE = 17
AF_RAW = 18 AF_RAW = 18
AF_LINK = 18 AF_LINK = 18
pseudo_AF_XTP = 19 pseudo_AF_XTP = 19
AF_MAX = 20 AF_NIT = 17
AF_802 = 18
AF_OSI = 19
AF_X25 = 20
AF_OSINET = 21
AF_GOSIP = 22
AF_SDL = 23
AF_MAX = (AF_SDL+1)
PF_UNSPEC = AF_UNSPEC PF_UNSPEC = AF_UNSPEC
PF_UNIX = AF_UNIX PF_UNIX = AF_UNIX
PF_INET = AF_INET PF_INET = AF_INET
...@@ -53,7 +78,6 @@ PF_PUP = AF_PUP ...@@ -53,7 +78,6 @@ PF_PUP = AF_PUP
PF_CHAOS = AF_CHAOS PF_CHAOS = AF_CHAOS
PF_NS = AF_NS PF_NS = AF_NS
PF_ISO = AF_ISO PF_ISO = AF_ISO
PF_OSI = AF_ISO
PF_ECMA = AF_ECMA PF_ECMA = AF_ECMA
PF_DATAKIT = AF_DATAKIT PF_DATAKIT = AF_DATAKIT
PF_CCITT = AF_CCITT PF_CCITT = AF_CCITT
...@@ -67,11 +91,18 @@ PF_ROUTE = AF_ROUTE ...@@ -67,11 +91,18 @@ PF_ROUTE = AF_ROUTE
PF_LINK = AF_LINK PF_LINK = AF_LINK
PF_XTP = pseudo_AF_XTP PF_XTP = pseudo_AF_XTP
PF_RAW = AF_RAW PF_RAW = AF_RAW
PF_NIT = AF_NIT
PF_802 = AF_802
PF_OSI = AF_OSI
PF_X25 = AF_X25
PF_OSINET = AF_OSINET
PF_GOSIP = AF_GOSIP
PF_MAX = AF_MAX PF_MAX = AF_MAX
SOMAXCONN = 5 SOMAXCONN = 5
MSG_OOB = 0x1 MSG_OOB = 0x1
MSG_PEEK = 0x2 MSG_PEEK = 0x2
MSG_DONTROUTE = 0x4 MSG_DONTROUTE = 0x4
MSG_EOR = 0x8
MSG_BTAG = 0x40 MSG_BTAG = 0x40
MSG_ETAG = 0x80 MSG_ETAG = 0x80
MSG_MAXIOVLEN = 16 MSG_MAXIOVLEN = 16
...@@ -138,6 +138,19 @@ class Cddb: ...@@ -138,6 +138,19 @@ class Cddb:
continue continue
self.track[trackno] = value self.track[trackno] = value
f.close() f.close()
for i in range(2, len(self.track)):
track = self.track[i]
# if track title starts with `,', use initial part
# of previous track's title
if track[0] == ',':
try:
off = string.index(self.track[i - 1],
',')
except string.index_error:
pass
else:
self.track[i] = self.track[i-1][:off] \
+ track
def write(self): def write(self):
import posixpath import posixpath
...@@ -153,6 +166,17 @@ class Cddb: ...@@ -153,6 +166,17 @@ class Cddb:
f.write('album.title:\t' + self.title + '\n') f.write('album.title:\t' + self.title + '\n')
f.write('album.artist:\t' + self.artist + '\n') f.write('album.artist:\t' + self.artist + '\n')
f.write('album.toc:\t' + self.toc + '\n') f.write('album.toc:\t' + self.toc + '\n')
prevpref = None
for i in range(1, len(self.track)): for i in range(1, len(self.track)):
f.write('track' + `i` + '.title:\t' + self.track[i] + '\n') track = self.track[i]
try:
off = string.index(track, ',')
except string.index_error:
prevpref = None
else:
if prevpref and track[:off] == prevpref:
track = track[off:]
else:
prevpref = track[:off]
f.write('track' + `i` + '.title:\t' + track + '\n')
f.close() f.close()
...@@ -432,10 +432,10 @@ def _select_crfunc(fm, cl): ...@@ -432,10 +432,10 @@ def _select_crfunc(fm, cl):
def test(): def test():
import time import time
t0 = time.millitimer() t0 = time.time()
if len(sys.argv) == 2: if len(sys.argv) == 2:
forms = parse_forms(sys.argv[1]) forms = parse_forms(sys.argv[1])
t1 = time.millitimer() t1 = time.time()
print 'parse time:', 0.001*(t1-t0), 'sec.' print 'parse time:', 0.001*(t1-t0), 'sec.'
keys = forms.keys() keys = forms.keys()
keys.sort() keys.sort()
...@@ -443,8 +443,8 @@ def test(): ...@@ -443,8 +443,8 @@ def test():
_printform(forms[i]) _printform(forms[i])
elif len(sys.argv) == 3: elif len(sys.argv) == 3:
form = parse_form(sys.argv[1], sys.argv[2]) form = parse_form(sys.argv[1], sys.argv[2])
t1 = time.millitimer() t1 = time.time()
print 'parse time:', 0.001*(t1-t0), 'sec.' print 'parse time:', round(t1-t0, 3), 'sec.'
_printform(form) _printform(form)
else: else:
print 'Usage: test fdfile [form]' print 'Usage: test fdfile [form]'
......
# Generated by h2py from stdin
_FOPEN = (-1) _FOPEN = (-1)
_FREAD = 0x0001 _FREAD = 0x0001
_FWRITE = 0x0002 _FWRITE = 0x0002
_FNDELAY = 0x0004 _FNDELAY = 0x0004
_FAPPEND = 0x0008 _FAPPEND = 0x0008
_FMARK = 0x0010 _FSETBLK = 0x0010
_FDEFER = 0x0020
_FASYNC = 0x0040 _FASYNC = 0x0040
_FSHLOCK = 0x0080 _FSHLOCK = 0x0080
_FEXLOCK = 0x0100 _FEXLOCK = 0x0100
...@@ -15,6 +15,8 @@ _FNBIO = 0x1000 ...@@ -15,6 +15,8 @@ _FNBIO = 0x1000
_FSYNC = 0x2000 _FSYNC = 0x2000
_FNONBLOCK = 0x4000 _FNONBLOCK = 0x4000
_FNOCTTY = 0x8000 _FNOCTTY = 0x8000
_FMARK = 0x10000
_FDEFER = 0x20000
O_RDONLY = 0 O_RDONLY = 0
O_WRONLY = 1 O_WRONLY = 1
O_RDWR = 2 O_RDWR = 2
...@@ -25,7 +27,6 @@ O_EXCL = _FEXCL ...@@ -25,7 +27,6 @@ O_EXCL = _FEXCL
O_NONBLOCK = _FNONBLOCK O_NONBLOCK = _FNONBLOCK
O_NOCTTY = _FNOCTTY O_NOCTTY = _FNOCTTY
O_SYNC = _FSYNC O_SYNC = _FSYNC
O_ACCMODE = (O_RDONLY|O_WRONLY|O_RDWR)
FAPPEND = _FAPPEND FAPPEND = _FAPPEND
FSYNC = _FSYNC FSYNC = _FSYNC
FASYNC = _FASYNC FASYNC = _FASYNC
...@@ -36,6 +37,7 @@ FREAD = _FREAD ...@@ -36,6 +37,7 @@ FREAD = _FREAD
FWRITE = _FWRITE FWRITE = _FWRITE
FMARK = _FMARK FMARK = _FMARK
FDEFER = _FDEFER FDEFER = _FDEFER
FSETBLK = _FSETBLK
FSHLOCK = _FSHLOCK FSHLOCK = _FSHLOCK
FEXLOCK = _FEXLOCK FEXLOCK = _FEXLOCK
FOPEN = _FOPEN FOPEN = _FOPEN
...@@ -62,3 +64,4 @@ F_RDLCK = 1 ...@@ -62,3 +64,4 @@ F_RDLCK = 1
F_WRLCK = 2 F_WRLCK = 2
F_UNLCK = 3 F_UNLCK = 3
F_UNLKSYS = 4 F_UNLKSYS = 4
O_ACCMODE = (O_RDONLY|O_WRONLY|O_RDWR)
# Symbolic constants from <netinet/in.h>. # Generated by h2py from /usr/include/netinet/in.h
# These constants are SunOS specific! (Possibly even SunOS 4.1.1)
# See demo/scripts/h2py.py for a tool to help generate a version for
# your system.
IPPROTO_IP = 0 IPPROTO_IP = 0
IPPROTO_ICMP = 1 IPPROTO_ICMP = 1
IPPROTO_IGMP = 2 IPPROTO_IGMP = 2
......
# Generated by h2py from /usr/include/sys/socket.h
SOCK_STREAM = 1 SOCK_STREAM = 1
SOCK_DGRAM = 2 SOCK_DGRAM = 2
SOCK_RAW = 3 SOCK_RAW = 3
......
# Generated by h2py from /usr/include/sys/wait.h
WUNTRACED = 0004
WNOHANG = 0100
WEXITED = 0001
WTRAPPED = 0002
WSTOPPED = WUNTRACED
WCONTINUED = 0010
WNOWAIT = 0200
WOPTMASK = (WEXITED|WTRAPPED|WSTOPPED|WCONTINUED|WNOHANG|WNOWAIT)
WSTOPFLG = 0177
WCONTFLG = 0177777
WCOREFLG = 0200
WSIGMASK = 0177
...@@ -8,4 +8,5 @@ set -v ...@@ -8,4 +8,5 @@ set -v
h2py </usr/include/sys/fcntlcom.h >FCNTL.py h2py </usr/include/sys/fcntlcom.h >FCNTL.py
echo "O_ACCMODE = (O_RDONLY|O_WRONLY|O_RDWR)" >>FCNTL.py echo "O_ACCMODE = (O_RDONLY|O_WRONLY|O_RDWR)" >>FCNTL.py
h2py /usr/include/sys/socket.h h2py /usr/include/sys/socket.h
h2py /usr/include/sys/wait.h
h2py -i '(u_long)' /usr/include/netinet/in.h h2py -i '(u_long)' /usr/include/netinet/in.h
...@@ -130,7 +130,7 @@ def isdir(path): ...@@ -130,7 +130,7 @@ def isdir(path):
# Is a path a regular file? # Is a path a regular file?
# This follows symbolic links, so both islink() and isdir() can be true # This follows symbolic links, so both islink() and isfile() can be true
# for the same path. # for the same path.
def isfile(path): def isfile(path):
...@@ -205,7 +205,7 @@ def walk(top, func, arg): ...@@ -205,7 +205,7 @@ def walk(top, func, arg):
for name in names: for name in names:
if name not in exceptions: if name not in exceptions:
name = join(top, name) name = join(top, name)
if isdir(name): if isdir(name) and not islink(name):
walk(name, func, arg) walk(name, func, arg)
...@@ -239,29 +239,35 @@ def expanduser(path): ...@@ -239,29 +239,35 @@ def expanduser(path):
# Expand paths containing shell variable substitutions. # Expand paths containing shell variable substitutions.
# This is done by piping it through the shell. # This expands the forms $variable and ${variable} only.
# Shell quoting characters (\ " ' `) are protected by a backslash. # Non-existant variables are left unchanged.
# NB: a future version may avoid starting a subprocess and do the
# substitutions internally. This may slightly change the syntax _varprog = None
# for variables.
def expandvars(path): def expandvars(path):
global _varprog
if '$' not in path: if '$' not in path:
return path return path
q = '' if not _varprog:
for c in path: import regex
if c in ('\\', '"', '\'', '`'): _varprog = regex.compile('$\([a-zA-Z0-9_]+\|{[^}]*}\)')
c = '\\' + c i = 0
q = q + c while 1:
d = '!' i = _varprog.search(path, i)
if q == d: if i < 0:
d = '+' break
p = posix.popen('cat <<' + d + '\n' + q + '\n' + d + '\n', 'r') name = _varprog.group(1)
res = p.read() j = i + len(_varprog.group(0))
del p if name[:1] == '{' and name[-1:] == '}':
if res[-1:] == '\n': name = name[1:-1]
res = res[:-1] if posix.environ.has_key(name):
return res tail = path[j:]
path = path[:i] + posix.environ[name]
i = len(path)
path = path + tail
else:
i = j
return path
# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B. # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
......
This diff is collapsed.
This diff is collapsed.
...@@ -10,13 +10,7 @@ class Prog: ...@@ -10,13 +10,7 @@ class Prog:
self.prog = regex.compile(pat) self.prog = regex.compile(pat)
finally: finally:
xxx = regex.set_syntax(save_syntax) xxx = regex.set_syntax(save_syntax)
def match(self, *args): def match(self, str, offset = 0):
if len(args) == 2:
str, offset = args
elif len(args) == 1:
str, offset = args[0], 0
else:
raise TypeError, 'wrong argument count'
if self.prog.search(str, offset) < 0: if self.prog.search(str, offset) < 0:
return () return ()
regs = self.prog.regs regs = self.prog.regs
......
...@@ -77,6 +77,19 @@ class Repr: ...@@ -77,6 +77,19 @@ class Repr:
j = max(0, self.maxlong-3-i) j = max(0, self.maxlong-3-i)
s = s[:i] + '...' + s[len(s)-j:] s = s[:i] + '...' + s[len(s)-j:]
return s return s
def repr_instance(self, x, level):
try:
s = `x`
# Bugs in x.__repr__() can cause arbitrary
# exceptions -- then make up something
except:
return '<' + x.__class__.__name__ + ' instance at ' + \
hex(id(x))[2:] + '>'
if len(s) > self.maxstring:
i = max(0, (self.maxstring-3)/2)
j = max(0, self.maxstring-3-i)
s = s[:i] + '...' + s[len(s)-j:]
return s
aRepr = Repr() aRepr = Repr()
repr = aRepr.repr repr = aRepr.repr
# RFC-822 message manipulation class. # RFC-822 message manipulation class.
# #
# XXX This is only a very rough sketch of a full RFC-822 parser; # XXX This is only a very rough sketch of a full RFC-822 parser;
# additional methods are needed to parse addresses and dates, and to # in particular the tokenizing of addresses does not adhere to all the
# tokenize lines according to various other syntax rules. # quoting rules.
# #
# Directions for use: # Directions for use:
# #
...@@ -22,6 +22,17 @@ ...@@ -22,6 +22,17 @@
# embedded whitespace (including newlines) exactly as they are # embedded whitespace (including newlines) exactly as they are
# specified in the header, and leave the case of the text unchanged. # specified in the header, and leave the case of the text unchanged.
# #
# For addresses and address lists there are functions
# realname, mailaddress = m.getaddr(name) and
# list = m.getaddrlist(name)
# where the latter returns a list of (realname, mailaddr) tuples.
#
# There is also a method
# time = m.getdate(name)
# which parses a Date-like field and returns a time-compatible tuple,
# i.e. a tuple such as returned by time.localtime() or accepted by
# time.mktime().
#
# See the class definition for lower level access methods. # See the class definition for lower level access methods.
# #
# There are also some utility functions here. # There are also some utility functions here.
...@@ -29,6 +40,7 @@ ...@@ -29,6 +40,7 @@
import regex import regex
import string import string
import time
class Message: class Message:
...@@ -105,12 +117,13 @@ class Message: ...@@ -105,12 +117,13 @@ class Message:
# Method to determine whether a line is a legal end of # Method to determine whether a line is a legal end of
# RFC-822 headers. You may override this method if your # RFC-822 headers. You may override this method if your
# application wants to bend the rules, e.g. to accept lines # application wants to bend the rules, e.g. to strip trailing
# ending in '\r\n', to strip trailing whitespace, or to # whitespace, or to recognise MH template separators
# recognise MH template separators ('--------'). # ('--------'). For convenience (e.g. for code reading from
# sockets) a line consisting of \r\n also matches.
def islast(self, line): def islast(self, line):
return line == '\n' return line == '\n' or line == '\r\n'
# Look through the list of headers and find all lines matching # Look through the list of headers and find all lines matching
...@@ -178,27 +191,94 @@ class Message: ...@@ -178,27 +191,94 @@ class Message:
return string.strip(text) return string.strip(text)
# XXX The next step would be to define self.getaddr(name) # Retrieve a single address from a header as a tuple, e.g.
# and self.getaddrlist(name) which would parse a header # ('Guido van Rossum', 'guido@cwi.nl').
# consisting of a single mail address and a number of mail
# addresses, respectively. Lower level functions would be def getaddr(self, name):
# parseaddr(string) and parseaddrlist(string). data = self.getheader(name)
if not data:
return None, None
return parseaddr(data)
# Retrieve a list of addresses from a header, where each
# address is a tuple as returned by getaddr().
def getaddrlist(self, name):
# XXX This function is not really correct. The split
# on ',' might fail in the case of commas within
# quoted strings.
data = self.getheader(name)
if not data:
return []
data = string.splitfields(data, ',')
for i in range(len(data)):
data[i] = parseaddr(data[i])
return data
# Retrieve a date field from a header as a tuple compatible
# with time.mktime().
def getdate(self, name):
data = self.getheader(name)
if not data:
return None
return parsedate(data)
# XXX Similar, there would be a function self.getdate(name) to # Access as a dictionary (only finds first header of each type):
# return a date in canonical form (perhaps a number compatible
# to time.time()) and a function parsedate(string).
# XXX The inverses of the parse functions may also be useful. def __len__(self):
types = {}
for line in self.headers:
if line[0] in string.whitespace: continue
i = string.find(line, ':')
if i > 0:
name = string.lower(line[:i])
types[name] = None
return len(types)
def __getitem__(self, name):
value = self.getheader(name)
if value is None: raise KeyError, name
return value
def has_key(self, name):
value = self.getheader(name)
return value is not None
def keys(self):
types = {}
for line in self.headers:
if line[0] in string.whitespace: continue
i = string.find(line, ':')
if i > 0:
name = line[:i]
key = string.lower(name)
types[key] = name
return types.values()
def values(self):
values = []
for name in self.keys():
values.append(self[name])
return values
def items(self):
items = []
for name in self.keys():
items.append(name, self[name])
return items
# Utility functions # Utility functions
# ----------------- # -----------------
# XXX Should fix these to be really conformant.
# XXX The inverses of the parse functions may also be useful.
# Remove quotes from a string. # Remove quotes from a string.
# XXX Should fix this to be really conformant.
def unquote(str): def unquote(str):
if len(str) > 1: if len(str) > 1:
...@@ -207,3 +287,107 @@ def unquote(str): ...@@ -207,3 +287,107 @@ def unquote(str):
if str[0] == '<' and str[-1:] == '>': if str[0] == '<' and str[-1:] == '>':
return str[1:-1] return str[1:-1]
return str return str
# Parse an address into (name, address) tuple
def parseaddr(address):
# This is probably not perfect
address = string.strip(address)
# Case 1: part of the address is in <xx@xx> form.
pos = regex.search('<.*>', address)
if pos >= 0:
name = address[:pos]
address = address[pos:]
length = regex.match('<.*>', address)
name = name + address[length:]
address = address[:length]
else:
# Case 2: part of the address is in (comment) form
pos = regex.search('(.*)', address)
if pos >= 0:
name = address[pos:]
address = address[:pos]
length = regex.match('(.*)', name)
address = address + name[length:]
name = name[:length]
else:
# Case 3: neither. Only an address
name = ''
name = string.strip(name)
address = string.strip(address)
if address and address[0] == '<' and address[-1] == '>':
address = address[1:-1]
if name and name[0] == '(' and name[-1] == ')':
name = name[1:-1]
return name, address
# Parse a date field
_monthnames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
def parsedate(data):
# XXX This completely ignores timezone matters at the moment...
data = string.split(data)
if data[0][-1] == ',':
# There's a dayname here. Skip it
del data[0]
if len(data) < 5:
return None
data = data[:5]
[dd, mm, yy, tm, tz] = data
if not mm in _monthnames:
return None
mm = _monthnames.index(mm)+1
tm = string.splitfields(tm, ':')
if len(tm) == 2:
[thh, tmm] = tm
tss = '0'
else:
[thh, tmm, tss] = tm
try:
yy = string.atoi(yy)
dd = string.atoi(dd)
thh = string.atoi(thh)
tmm = string.atoi(tmm)
tss = string.atoi(tss)
except string.atoi_error:
return None
tuple = (yy, mm, dd, thh, tmm, tss, 0, 0, 0)
return tuple
# When used as script, run a small test program.
# The first command line argument must be a filename containing one
# message in RFC-822 format.
if __name__ == '__main__':
import sys
file = '/ufs/guido/Mail/drafts/,1'
if sys.argv[1:]: file = sys.argv[1]
f = open(file, 'r')
m = Message(f)
print 'From:', m.getaddr('from')
print 'To:', m.getaddrlist('to')
print 'Subject:', m.getheader('subject')
print 'Date:', m.getheader('date')
date = m.getdate('date')
if date:
print 'ParsedDate:', time.asctime(date)
else:
print 'ParsedDate:', None
m.rewindbody()
n = 0
while f.readline():
n = n + 1
print 'Lines:', n
print '-'*70
print 'len =', len(m)
if m.has_key('Date'): print 'Date =', m['Date']
if m.has_key('X-Nonsense'): pass
print 'keys =', m.keys()
print 'values =', m.values()
print 'items =', m.items()
...@@ -6,12 +6,11 @@ ...@@ -6,12 +6,11 @@
# #
# Each instance is parametrized with two functions, one that is # Each instance is parametrized with two functions, one that is
# supposed to return the current time, one that is supposed to # supposed to return the current time, one that is supposed to
# implement a delay. You can implement fine- or course-grained # implement a delay. You can implement real-time scheduling by
# real-time scheduling by substituting time and sleep or millitimer # substituting time and sleep from built-in module time, or you can
# and millisleep from the built-in module time, or you can implement # implement simulated time by writing your own functions. This can
# simulated time by writing your own functions. This can also be # also be used to integrate scheduling with STDWIN events; the delay
# used to integrate scheduling with STDWIN events; the delay function # function is allowed to modify the queue. Time can be expressed as
# is allowed to modify the queue. Time can be expressed as
# integers or floating point numbers, as long as it is consistent. # integers or floating point numbers, as long as it is consistent.
# Events are specified by tuples (time, priority, action, argument). # Events are specified by tuples (time, priority, action, argument).
......
# Combine a real-time scheduling queue and stdwin event handling. # Combine a real-time scheduling queue and stdwin event handling.
# Uses the millisecond timer. # Keeps times in milliseconds.
import stdwin, stdwinq import stdwin, stdwinq
from stdwinevents import WE_TIMER from stdwinevents import WE_TIMER
...@@ -19,11 +19,11 @@ def delayfunc(msecs): ...@@ -19,11 +19,11 @@ def delayfunc(msecs):
mainloop.dispatch(event) mainloop.dispatch(event)
return return
# #
# Use millisleep for very short delays or if there are no windows # Use sleep for very short delays or if there are no windows
# #
if msecs < 100 or mainloop.countwindows() == 0: if msecs < 100 or mainloop.countwindows() == 0:
if msecs > 0: if msecs > 0:
time.millisleep(msecs) time.sleep(msecs * 0.001)
return return
# #
# Post a timer event on an arbitrary window and wait for it # Post a timer event on an arbitrary window and wait for it
...@@ -35,7 +35,10 @@ def delayfunc(msecs): ...@@ -35,7 +35,10 @@ def delayfunc(msecs):
if event[0] <> WE_TIMER: if event[0] <> WE_TIMER:
mainloop.dispatch(event) mainloop.dispatch(event)
q = sched.scheduler(time.millitimer, delayfunc) def millitimer():
return int(1000 * time.time())
q = sched.scheduler(millitimer, delayfunc)
# Export functions enter, enterabs and cancel just like a scheduler # Export functions enter, enterabs and cancel just like a scheduler
# #
......
...@@ -2,19 +2,19 @@ ...@@ -2,19 +2,19 @@
# File windows, a subclass of textwin (which is a subclass of gwin) # File windows, a subclass of textwin (which is a subclass of gwin)
import textwin import textwin
import builtin import __builtin__
# FILE WINDOW # FILE WINDOW
def open_readonly(fn): # Open a file window def open_readonly(fn): # Open a file window
fp = builtin.open(fn, 'r') fp = __builtin__.open(fn, 'r')
w = textwin.open_readonly(fn, fp.read()) w = textwin.open_readonly(fn, fp.read())
w.fn = fn w.fn = fn
return w return w
def open(fn): # Open a file window def open(fn): # Open a file window
fp = builtin.open(fn, 'r') fp = __builtin__.open(fn, 'r')
w = textwin.open(fn, fp.read()) w = textwin.open(fn, fp.read())
w.fn = fn w.fn = fn
return w return w
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment