home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Python / getargs.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  28.8 KB  |  1,301 lines

  1.  
  2. /* New getargs implementation */
  3.  
  4. /* XXX There are several unchecked sprintf or strcat calls in this file.
  5.    XXX The only way these can become a danger is if some C code in the
  6.    XXX Python source (or in an extension) uses ridiculously long names
  7.    XXX or ridiculously deep nesting in format strings. */
  8.  
  9. #include "Python.h"
  10.  
  11. #include <ctype.h>
  12.  
  13.  
  14. int PyArg_Parse(PyObject *, char *, ...);
  15. int PyArg_ParseTuple(PyObject *, char *, ...);
  16. int PyArg_VaParse(PyObject *, char *, va_list);
  17.  
  18. int PyArg_ParseTupleAndKeywords(PyObject *, PyObject *,
  19.                 char *, char **, ...);
  20.  
  21. /* Forward */
  22. static int vgetargs1(PyObject *, char *, va_list *, int);
  23. static void seterror(int, char *, int *, char *, char *);
  24. static char *convertitem(PyObject *, char **, va_list *, int *, char *);
  25. static char *converttuple(PyObject *, char **, va_list *,
  26.               int *, char *, int);
  27. static char *convertsimple(PyObject *, char **, va_list *, char *);
  28. static char *convertsimple1(PyObject *, char **, va_list *);
  29.  
  30. static int vgetargskeywords(PyObject *, PyObject *,
  31.                 char *, char **, va_list *);
  32. static char *skipitem(char **, va_list *);
  33.  
  34. int PyArg_Parse(PyObject *args, char *format, ...)
  35. {
  36.     int retval;
  37.     va_list va;
  38.     
  39.     va_start(va, format);
  40.     retval = vgetargs1(args, format, &va, 1);
  41.     va_end(va);
  42.     return retval;
  43. }
  44.  
  45.  
  46. int PyArg_ParseTuple(PyObject *args, char *format, ...)
  47. {
  48.     int retval;
  49.     va_list va;
  50.     
  51.     va_start(va, format);
  52.     retval = vgetargs1(args, format, &va, 0);
  53.     va_end(va);
  54.     return retval;
  55. }
  56.  
  57.  
  58. int
  59. PyArg_VaParse(PyObject *args, char *format, va_list va)
  60. {
  61.     va_list lva;
  62.  
  63. #ifdef VA_LIST_IS_ARRAY
  64.     memcpy(lva, va, sizeof(va_list));
  65. #else
  66.     lva = va;
  67. #endif
  68.  
  69.     return vgetargs1(args, format, &lva, 0);
  70. }
  71.  
  72.  
  73. static int
  74. vgetargs1(PyObject *args, char *format, va_list *p_va, int compat)
  75. {
  76.     char msgbuf[256];
  77.     int levels[32];
  78.     char *fname = NULL;
  79.     char *message = NULL;
  80.     int min = -1;
  81.     int max = 0;
  82.     int level = 0;
  83.     char *formatsave = format;
  84.     int i, len;
  85.     char *msg;
  86.     
  87.     for (;;) {
  88.         int c = *format++;
  89.         if (c == '(' /* ')' */) {
  90.             if (level == 0)
  91.                 max++;
  92.             level++;
  93.         }
  94.         else if (/* '(' */ c == ')') {
  95.             if (level == 0)
  96.                 Py_FatalError(/* '(' */
  97.                       "excess ')' in getargs format");
  98.             else
  99.                 level--;
  100.         }
  101.         else if (c == '\0')
  102.             break;
  103.         else if (c == ':') {
  104.             fname = format;
  105.             break;
  106.         }
  107.         else if (c == ';') {
  108.             message = format;
  109.             break;
  110.         }
  111.         else if (level != 0)
  112.             ; /* Pass */
  113.         else if (c == 'e')
  114.             ; /* Pass */
  115.         else if (isalpha(c))
  116.             max++;
  117.         else if (c == '|')
  118.             min = max;
  119.     }
  120.     
  121.     if (level != 0)
  122.         Py_FatalError(/* '(' */ "missing ')' in getargs format");
  123.     
  124.     if (min < 0)
  125.         min = max;
  126.     
  127.     format = formatsave;
  128.     
  129.     if (compat) {
  130.         if (max == 0) {
  131.             if (args == NULL)
  132.                 return 1;
  133.             sprintf(msgbuf, "%s requires no arguments",
  134.                 fname==NULL ? "function" : fname);
  135.             PyErr_SetString(PyExc_TypeError, msgbuf);
  136.             return 0;
  137.         }
  138.         else if (min == 1 && max == 1) {
  139.             if (args == NULL) {
  140.                 sprintf(msgbuf,
  141.                     "%s requires at least one argument",
  142.                     fname==NULL ? "function" : fname);
  143.                 PyErr_SetString(PyExc_TypeError, msgbuf);
  144.                 return 0;
  145.             }
  146.             msg = convertitem(args, &format, p_va, levels, msgbuf);
  147.             if (msg == NULL)
  148.                 return 1;
  149.             seterror(levels[0], msg, levels+1, fname, message);
  150.             return 0;
  151.         }
  152.         else {
  153.             PyErr_SetString(PyExc_SystemError,
  154.                 "old style getargs format uses new features");
  155.             return 0;
  156.         }
  157.     }
  158.     
  159.     if (!PyTuple_Check(args)) {
  160.         PyErr_SetString(PyExc_SystemError,
  161.             "new style getargs format but argument is not a tuple");
  162.         return 0;
  163.     }
  164.     
  165.     len = PyTuple_Size(args);
  166.     
  167.     if (len < min || max < len) {
  168.         if (message == NULL) {
  169.             sprintf(msgbuf,
  170.                 "%s requires %s %d argument%s; %d given",
  171.                 fname==NULL ? "function" : fname,
  172.                 min==max ? "exactly"
  173.                          : len < min ? "at least" : "at most",
  174.                 len < min ? min : max,
  175.                 (len < min ? min : max) == 1 ? "" : "s",
  176.                 len);
  177.             message = msgbuf;
  178.         }
  179.         PyErr_SetString(PyExc_TypeError, message);
  180.         return 0;
  181.     }
  182.     
  183.     for (i = 0; i < len; i++) {
  184.         if (*format == '|')
  185.             format++;
  186.         msg = convertitem(PyTuple_GetItem(args, i), &format, p_va,
  187.                  levels, msgbuf);
  188.         if (msg) {
  189.             seterror(i+1, msg, levels, fname, message);
  190.             return 0;
  191.         }
  192.     }
  193.  
  194.     if (*format != '\0' && !isalpha((int)(*format)) &&
  195.         *format != '(' &&
  196.         *format != '|' && *format != ':' && *format != ';') {
  197.         PyErr_Format(PyExc_SystemError,
  198.                  "bad format string: %.200s", formatsave);
  199.         return 0;
  200.     }
  201.     
  202.     return 1;
  203. }
  204.  
  205.  
  206.  
  207. static void
  208. seterror(int iarg, char *msg, int *levels, char *fname, char *message)
  209. {
  210.     char buf[256];
  211.     int i;
  212.     char *p = buf;
  213.  
  214.     if (PyErr_Occurred())
  215.         return;
  216.     if (iarg == 0 && message == NULL)
  217.         message = msg;
  218.     else if (message == NULL) {
  219.         if (fname != NULL) {
  220.             sprintf(p, "%s, ", fname);
  221.             p += strlen(p);
  222.         }
  223.         sprintf(p, "argument %d", iarg);
  224.         i = 0;
  225.         p += strlen(p);
  226.         while (levels[i] > 0) {
  227.             sprintf(p, ", item %d", levels[i]-1);
  228.             p += strlen(p);
  229.             i++;
  230.         }
  231.         sprintf(p, ": expected %s found", msg);
  232.         message = buf;
  233.     }
  234.     PyErr_SetString(PyExc_TypeError, message);
  235. }
  236.  
  237.  
  238. /* Convert a tuple argument.
  239.    On entry, *p_format points to the character _after_ the opening '('.
  240.    On successful exit, *p_format points to the closing ')'.
  241.    If successful:
  242.       *p_format and *p_va are updated,
  243.       *levels and *msgbuf are untouched,
  244.       and NULL is returned.
  245.    If the argument is invalid:
  246.       *p_format is unchanged,
  247.       *p_va is undefined,
  248.       *levels is a 0-terminated list of item numbers,
  249.       *msgbuf contains an error message, whose format is:
  250.          "<typename1>, <typename2>", where:
  251.             <typename1> is the name of the expected type, and
  252.             <typename2> is the name of the actual type,
  253.          (so you can surround it by "expected ... found"),
  254.       and msgbuf is returned.
  255. */
  256.  
  257. static char *
  258. converttuple(PyObject *arg, char **p_format, va_list *p_va, int *levels,
  259.          char *msgbuf, int toplevel)
  260. {
  261.     int level = 0;
  262.     int n = 0;
  263.     char *format = *p_format;
  264.     int i;
  265.     
  266.     for (;;) {
  267.         int c = *format++;
  268.         if (c == '(') {
  269.             if (level == 0)
  270.                 n++;
  271.             level++;
  272.         }
  273.         else if (c == ')') {
  274.             if (level == 0)
  275.                 break;
  276.             level--;
  277.         }
  278.         else if (c == ':' || c == ';' || c == '\0')
  279.             break;
  280.         else if (level == 0 && isalpha(c))
  281.             n++;
  282.     }
  283.     
  284.     if (!PySequence_Check(arg)) {
  285.         levels[0] = 0;
  286.         sprintf(msgbuf,
  287.             toplevel ? "%d arguments, %s" : "%d-sequence, %s",
  288.             n, arg == Py_None ? "None" : arg->ob_type->tp_name);
  289.         return msgbuf;
  290.     }
  291.     
  292.     if ((i = PySequence_Size(arg)) != n) {
  293.         levels[0] = 0;
  294.         sprintf(msgbuf,
  295.             toplevel ? "%d arguments, %d" : "%d-sequence, %d-sequence",
  296.             n, i);
  297.         return msgbuf;
  298.     }
  299.     
  300.     format = *p_format;
  301.     for (i = 0; i < n; i++) {
  302.         char *msg;
  303.         PyObject *item;
  304.         item = PySequence_GetItem(arg, i);
  305.         msg = convertitem(item, &format, p_va, levels+1, msgbuf);
  306.         /* PySequence_GetItem calls tp->sq_item, which INCREFs */
  307.         Py_XDECREF(item);
  308.         if (msg != NULL) {
  309.             levels[0] = i+1;
  310.             return msg;
  311.         }
  312.     }
  313.     
  314.     *p_format = format;
  315.     return NULL;
  316. }
  317.  
  318.  
  319. /* Convert a single item. */
  320.  
  321. static char *
  322. convertitem(PyObject *arg, char **p_format, va_list *p_va, int *levels,
  323.         char *msgbuf)
  324. {
  325.     char *msg;
  326.     char *format = *p_format;
  327.     
  328.     if (*format == '(' /* ')' */) {
  329.         format++;
  330.         msg = converttuple(arg, &format, p_va, levels, msgbuf, 0);
  331.         if (msg == NULL)
  332.             format++;
  333.     }
  334.     else {
  335.         msg = convertsimple(arg, &format, p_va, msgbuf);
  336.         if (msg != NULL)
  337.             levels[0] = 0;
  338.     }
  339.     if (msg == NULL)
  340.         *p_format = format;
  341.     return msg;
  342. }
  343.  
  344.  
  345. /* Convert a non-tuple argument.  Adds to convertsimple1 functionality
  346.    by appending ", <actual argument type>" to error message. */
  347.  
  348. static char *
  349. convertsimple(PyObject *arg, char **p_format, va_list *p_va, char *msgbuf)
  350. {
  351.     char *msg = convertsimple1(arg, p_format, p_va);
  352.     if (msg != NULL) {
  353.         sprintf(msgbuf, "%.50s, %.50s", msg,
  354.             arg == Py_None ? "None" : arg->ob_type->tp_name);
  355.         msg = msgbuf;
  356.     }
  357.     return msg;
  358. }
  359.  
  360.  
  361. /* Internal API needed by convertsimple1(): */
  362. extern 
  363. PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
  364.                   const char *errors);
  365.  
  366. /* Convert a non-tuple argument.  Return NULL if conversion went OK,
  367.    or a string representing the expected type if the conversion failed.
  368.    When failing, an exception may or may not have been raised.
  369.    Don't call if a tuple is expected. */
  370.  
  371. static char *
  372. convertsimple1(PyObject *arg, char **p_format, va_list *p_va)
  373. {
  374.     char *format = *p_format;
  375.     char c = *format++;
  376.     
  377.     switch (c) {
  378.     
  379.     case 'b': /* unsigned byte -- very short int */
  380.         {
  381.             char *p = va_arg(*p_va, char *);
  382.             long ival = PyInt_AsLong(arg);
  383.             if (ival == -1 && PyErr_Occurred())
  384.                 return "integer<b>";
  385.             else if (ival < 0) {
  386.                 PyErr_SetString(PyExc_OverflowError,
  387.                   "unsigned byte integer is less than minimum");
  388.                 return "integer<b>";
  389.             }
  390.             else if (ival > UCHAR_MAX) {
  391.                 PyErr_SetString(PyExc_OverflowError,
  392.                   "unsigned byte integer is greater than maximum");
  393.                 return "integer<b>";
  394.             }
  395.             else
  396.                 *p = (unsigned char) ival;
  397.             break;
  398.         }
  399.     
  400.     case 'B': /* byte sized bitfield - both signed and unsigned values allowed */
  401.         {
  402.             char *p = va_arg(*p_va, char *);
  403.             long ival = PyInt_AsLong(arg);
  404.             if (ival == -1 && PyErr_Occurred())
  405.                 return "integer<b>";
  406.             else if (ival < SCHAR_MIN) {
  407.                 PyErr_SetString(PyExc_OverflowError,
  408.                   "byte-sized integer bitfield is less than minimum");
  409.                 return "integer<B>";
  410.             }
  411.             else if (ival > (int)UCHAR_MAX) {
  412.                 PyErr_SetString(PyExc_OverflowError,
  413.                   "byte-sized integer bitfield is greater than maximum");
  414.                 return "integer<B>";
  415.             }
  416.             else
  417.                 *p = (unsigned char) ival;
  418.             break;
  419.         }
  420.     
  421.     case 'h': /* signed short int */
  422.         {
  423.             short *p = va_arg(*p_va, short *);
  424.             long ival = PyInt_AsLong(arg);
  425.             if (ival == -1 && PyErr_Occurred())
  426.                 return "integer<h>";
  427.             else if (ival < SHRT_MIN) {
  428.                 PyErr_SetString(PyExc_OverflowError,
  429.                   "signed short integer is less than minimum");
  430.                 return "integer<h>";
  431.             }
  432.             else if (ival > SHRT_MAX) {
  433.                 PyErr_SetString(PyExc_OverflowError,
  434.                   "signed short integer is greater than maximum");
  435.                 return "integer<h>";
  436.             }
  437.             else
  438.                 *p = (short) ival;
  439.             break;
  440.         }
  441.     
  442.     case 'H': /* short int sized bitfield, both signed and unsigned allowed */
  443.         {
  444.             unsigned short *p = va_arg(*p_va, unsigned short *);
  445.             long ival = PyInt_AsLong(arg);
  446.             if (ival == -1 && PyErr_Occurred())
  447.                 return "integer<H>";
  448.             else if (ival < SHRT_MIN) {
  449.                 PyErr_SetString(PyExc_OverflowError,
  450.                   "short integer bitfield is less than minimum");
  451.                 return "integer<H>";
  452.             }
  453.             else if (ival > USHRT_MAX) {
  454.                 PyErr_SetString(PyExc_OverflowError,
  455.                   "short integer bitfield is greater than maximum");
  456.                 return "integer<H>";
  457.             }
  458.             else
  459.                 *p = (unsigned short) ival;
  460.             break;
  461.         }
  462.     
  463.     case 'i': /* signed int */
  464.         {
  465.             int *p = va_arg(*p_va, int *);
  466.             long ival = PyInt_AsLong(arg);
  467.             if (ival == -1 && PyErr_Occurred())
  468.                 return "integer<i>";
  469.             else if (ival > INT_MAX) {
  470.                 PyErr_SetString(PyExc_OverflowError,
  471.                     "signed integer is greater than maximum");
  472.                 return "integer<i>";
  473.             }
  474.             else if (ival < INT_MIN) {
  475.                 PyErr_SetString(PyExc_OverflowError,
  476.                     "signed integer is less than minimum");
  477.                 return "integer<i>";
  478.             }
  479.             else
  480.                 *p = ival;
  481.             break;
  482.         }
  483.     case 'l': /* long int */
  484.         {
  485.             long *p = va_arg(*p_va, long *);
  486.             long ival = PyInt_AsLong(arg);
  487.             if (ival == -1 && PyErr_Occurred())
  488.                 return "integer<l>";
  489.             else
  490.                 *p = ival;
  491.             break;
  492.         }
  493.     
  494. #ifdef HAVE_LONG_LONG
  495.     case 'L': /* LONG_LONG */
  496.         {
  497.             LONG_LONG *p = va_arg( *p_va, LONG_LONG * );
  498.             LONG_LONG ival = PyLong_AsLongLong( arg );
  499.             if( ival == (LONG_LONG)-1 && PyErr_Occurred() ) {
  500.                 return "long<L>";
  501.             } else {
  502.                 *p = ival;
  503.             }
  504.             break;
  505.         }
  506. #endif
  507.     
  508.     case 'f': /* float */
  509.         {
  510.             float *p = va_arg(*p_va, float *);
  511.             double dval = PyFloat_AsDouble(arg);
  512.             if (PyErr_Occurred())
  513.                 return "float<f>";
  514.             else
  515.                 *p = (float) dval;
  516.             break;
  517.         }
  518.     
  519.     case 'd': /* double */
  520.         {
  521.             double *p = va_arg(*p_va, double *);
  522.             double dval = PyFloat_AsDouble(arg);
  523.             if (PyErr_Occurred())
  524.                 return "float<d>";
  525.             else
  526.                 *p = dval;
  527.             break;
  528.         }
  529.     
  530. #ifndef WITHOUT_COMPLEX
  531.     case 'D': /* complex double */
  532.         {
  533.             Py_complex *p = va_arg(*p_va, Py_complex *);
  534.             Py_complex cval;
  535.             cval = PyComplex_AsCComplex(arg);
  536.             if (PyErr_Occurred())
  537.                 return "complex<D>";
  538.             else
  539.                 *p = cval;
  540.             break;
  541.         }
  542. #endif /* WITHOUT_COMPLEX */
  543.     
  544.     case 'c': /* char */
  545.         {
  546.             char *p = va_arg(*p_va, char *);
  547.             if (PyString_Check(arg) && PyString_Size(arg) == 1)
  548.                 *p = PyString_AsString(arg)[0];
  549.             else
  550.                 return "char";
  551.             break;
  552.         }
  553.     
  554.     case 's': /* string */
  555.         {
  556.             if (*format == '#') {
  557.                 void **p = (void **)va_arg(*p_va, char **);
  558.                 int *q = va_arg(*p_va, int *);
  559.  
  560.                 if (PyString_Check(arg)) {
  561.                     *p = PyString_AS_STRING(arg);
  562.                     *q = PyString_GET_SIZE(arg);
  563.                 }
  564.                 else if (PyUnicode_Check(arg)) {
  565.                     arg = _PyUnicode_AsDefaultEncodedString(
  566.                                         arg, NULL);
  567.                     if (arg == NULL)
  568.                     return "unicode conversion error";
  569.                     *p = PyString_AS_STRING(arg);
  570.                     *q = PyString_GET_SIZE(arg);
  571.                 }
  572.                 else { /* any buffer-like object */
  573.                     PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
  574.                     int count;
  575.                     if ( pb == NULL ||
  576.                      pb->bf_getreadbuffer == NULL ||
  577.                      pb->bf_getsegcount == NULL )
  578.                     return "read-only buffer";
  579.                     if ( (*pb->bf_getsegcount)(arg, NULL) != 1 )
  580.                     return "single-segment read-only buffer";
  581.                     if ( (count =
  582.                       (*pb->bf_getreadbuffer)(arg, 0, p)) < 0 )
  583.                     return "(unspecified)";
  584.                     *q = count;
  585.                 }
  586.                 format++;
  587.             } else {
  588.                 char **p = va_arg(*p_va, char **);
  589.             
  590.                 if (PyString_Check(arg))
  591.                     *p = PyString_AS_STRING(arg);
  592.                 else if (PyUnicode_Check(arg)) {
  593.                     arg = _PyUnicode_AsDefaultEncodedString(
  594.                                         arg, NULL);
  595.                     if (arg == NULL)
  596.                     return "unicode conversion error";
  597.                     *p = PyString_AS_STRING(arg);
  598.                 }
  599.                 else
  600.                   return "string";
  601.                 if ((int)strlen(*p) != PyString_Size(arg))
  602.                   return "string without null bytes";
  603.             }
  604.             break;
  605.         }
  606.  
  607.     case 'z': /* string, may be NULL (None) */
  608.         {
  609.             if (*format == '#') { /* any buffer-like object */
  610.                 void **p = (void **)va_arg(*p_va, char **);
  611.                 int *q = va_arg(*p_va, int *);
  612.  
  613.                 if (arg == Py_None) {
  614.                   *p = 0;
  615.                   *q = 0;
  616.                 }
  617.                 else if (PyString_Check(arg)) {
  618.                     *p = PyString_AS_STRING(arg);
  619.                     *q = PyString_GET_SIZE(arg);
  620.                 }
  621.                 else if (PyUnicode_Check(arg)) {
  622.                     arg = _PyUnicode_AsDefaultEncodedString(
  623.                                         arg, NULL);
  624.                     if (arg == NULL)
  625.                     return "unicode conversion error";
  626.                     *p = PyString_AS_STRING(arg);
  627.                     *q = PyString_GET_SIZE(arg);
  628.                 }
  629.                 else { /* any buffer-like object */
  630.                     PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
  631.                     int count;
  632.                     if ( pb == NULL ||
  633.                      pb->bf_getreadbuffer == NULL ||
  634.                      pb->bf_getsegcount == NULL )
  635.                     return "read-only buffer";
  636.                     if ( (*pb->bf_getsegcount)(arg, NULL) != 1 )
  637.                     return "single-segment read-only buffer";
  638.                     if ( (count =
  639.                       (*pb->bf_getreadbuffer)(arg, 0, p)) < 0 )
  640.                     return "(unspecified)";
  641.                     *q = count;
  642.                 }
  643.                 format++;
  644.             } else {
  645.                 char **p = va_arg(*p_va, char **);
  646.             
  647.                 if (arg == Py_None)
  648.                   *p = 0;
  649.                 else if (PyString_Check(arg))
  650.                   *p = PyString_AsString(arg);
  651.                 else if (PyUnicode_Check(arg)) {
  652.                   arg = _PyUnicode_AsDefaultEncodedString(
  653.                                   arg, NULL);
  654.                   if (arg == NULL)
  655.                       return "unicode conversion error";
  656.                   *p = PyString_AS_STRING(arg);
  657.                 }
  658.                 else
  659.                   return "None or string";
  660.                 if (*format == '#') {
  661.                   int *q = va_arg(*p_va, int *);
  662.                   if (arg == Py_None)
  663.                     *q = 0;
  664.                   else
  665.                     *q = PyString_Size(arg);
  666.                   format++;
  667.                 }
  668.                 else if (*p != NULL &&
  669.                      (int)strlen(*p) != PyString_Size(arg))
  670.                   return "None or string without null bytes";
  671.             }
  672.             break;
  673.         }
  674.     
  675.     case 'e': /* encoded string */
  676.         {
  677.             char **buffer;
  678.             const char *encoding;
  679.             PyObject *u, *s;
  680.             int size;
  681.  
  682.             /* Get 'e' parameter: the encoding name */
  683.             encoding = (const char *)va_arg(*p_va, const char *);
  684.             if (encoding == NULL)
  685.                     encoding = PyUnicode_GetDefaultEncoding();
  686.             
  687.             /* Get 's' parameter: the output buffer to use */
  688.             if (*format != 's')
  689.                 return "(unknown parser marker combination)";
  690.             buffer = (char **)va_arg(*p_va, char **);
  691.             format++;
  692.             if (buffer == NULL)
  693.                 return "(buffer is NULL)";
  694.             
  695.             /* Convert object to Unicode */
  696.             u = PyUnicode_FromObject(arg);
  697.             if (u == NULL)
  698.                 return "string, unicode or text buffer";
  699.             
  700.             /* Encode object; use default error handling */
  701.             s = PyUnicode_AsEncodedString(u,
  702.                               encoding,
  703.                               NULL);
  704.             Py_DECREF(u);
  705.             if (s == NULL)
  706.                 return "(encoding failed)";
  707.             if (!PyString_Check(s)) {
  708.                 Py_DECREF(s);
  709.                 return "(encoder failed to return a string)";
  710.             }
  711.             size = PyString_GET_SIZE(s);
  712.  
  713.             /* Write output; output is guaranteed to be
  714.                0-terminated */
  715.             if (*format == '#') { 
  716.                 /* Using buffer length parameter '#':
  717.  
  718.                    - if *buffer is NULL, a new buffer
  719.                    of the needed size is allocated and
  720.                    the data copied into it; *buffer is
  721.                    updated to point to the new buffer;
  722.                    the caller is responsible for
  723.                    PyMem_Free()ing it after usage
  724.  
  725.                    - if *buffer is not NULL, the data
  726.                    is copied to *buffer; *buffer_len
  727.                    has to be set to the size of the
  728.                    buffer on input; buffer overflow is
  729.                    signalled with an error; buffer has
  730.                    to provide enough room for the
  731.                    encoded string plus the trailing
  732.                    0-byte
  733.  
  734.                    - in both cases, *buffer_len is
  735.                    updated to the size of the buffer
  736.                    /excluding/ the trailing 0-byte
  737.  
  738.                 */
  739.                 int *buffer_len = va_arg(*p_va, int *);
  740.  
  741.                 format++;
  742.                 if (buffer_len == NULL)
  743.                     return "(buffer_len is NULL)";
  744.                 if (*buffer == NULL) {
  745.                     *buffer = PyMem_NEW(char, size + 1);
  746.                     if (*buffer == NULL) {
  747.                         Py_DECREF(s);
  748.                         return "(memory error)";
  749.                     }
  750.                 } else {
  751.                     if (size + 1 > *buffer_len) {
  752.                         Py_DECREF(s);
  753.                         return "(buffer overflow)";
  754.                     }
  755.                 }
  756.                 memcpy(*buffer,
  757.                        PyString_AS_STRING(s),
  758.                        size + 1);
  759.                 *buffer_len = size;
  760.             } else {
  761.                 /* Using a 0-terminated buffer:
  762.  
  763.                    - the encoded string has to be
  764.                    0-terminated for this variant to
  765.                    work; if it is not, an error raised
  766.  
  767.                    - a new buffer of the needed size
  768.                    is allocated and the data copied
  769.                    into it; *buffer is updated to
  770.                    point to the new buffer; the caller
  771.                    is responsible for PyMem_Free()ing it
  772.                    after usage
  773.  
  774.                  */
  775.                 if ((int)strlen(PyString_AS_STRING(s)) != size)
  776.                     return "(encoded string without "\
  777.                            "NULL bytes)";
  778.                 *buffer = PyMem_NEW(char, size + 1);
  779.                 if (*buffer == NULL) {
  780.                     Py_DECREF(s);
  781.                     return "(memory error)";
  782.                 }
  783.                 memcpy(*buffer,
  784.                        PyString_AS_STRING(s),
  785.                        size + 1);
  786.             }
  787.             Py_DECREF(s);
  788.             break;
  789.         }
  790.  
  791.     case 'u': /* raw unicode buffer (Py_UNICODE *) */
  792.         {
  793.             if (*format == '#') { /* any buffer-like object */
  794.                 void **p = (void **)va_arg(*p_va, char **);
  795.                 PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
  796.                 int *q = va_arg(*p_va, int *);
  797.                 int count;
  798.  
  799.                 if ( pb == NULL ||
  800.                      pb->bf_getreadbuffer == NULL ||
  801.                      pb->bf_getsegcount == NULL )
  802.                   return "read-only buffer";
  803.                 if ( (*pb->bf_getsegcount)(arg, NULL) != 1 )
  804.                   return "single-segment read-only buffer";
  805.                 if ( (count =
  806.                       (*pb->bf_getreadbuffer)(arg, 0, p)) < 0 )
  807.                   return "(unspecified)";
  808.                 /* buffer interface returns bytes, we want
  809.                    length in characters */
  810.                 *q = count/(sizeof(Py_UNICODE)); 
  811.                 format++;
  812.             } else {
  813.                 Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **);
  814.             
  815.                 if (PyUnicode_Check(arg))
  816.                     *p = PyUnicode_AS_UNICODE(arg);
  817.                 else
  818.                   return "unicode";
  819.             }
  820.             break;
  821.         }
  822.  
  823.     case 'S': /* string object */
  824.         {
  825.             PyObject **p = va_arg(*p_va, PyObject **);
  826.             if (PyString_Check(arg))
  827.                 *p = arg;
  828.             else
  829.                 return "string";
  830.             break;
  831.         }
  832.     
  833.     case 'U': /* Unicode object */
  834.         {
  835.             PyObject **p = va_arg(*p_va, PyObject **);
  836.             if (PyUnicode_Check(arg))
  837.                 *p = arg;
  838.             else
  839.                 return "unicode";
  840.             break;
  841.         }
  842.     
  843.     case 'O': /* object */
  844.         {
  845.             PyTypeObject *type;
  846.             PyObject **p;
  847.             if (*format == '!') {
  848.                 type = va_arg(*p_va, PyTypeObject*);
  849.                 p = va_arg(*p_va, PyObject **);
  850.                 format++;
  851.                 if (arg->ob_type == type)
  852.                     *p = arg;
  853.                 else
  854.                     return type->tp_name;
  855.  
  856.             }
  857.             else if (*format == '?') {
  858.                 inquiry pred = va_arg(*p_va, inquiry);
  859.                 p = va_arg(*p_va, PyObject **);
  860.                 format++;
  861.                 if ((*pred)(arg)) 
  862.                     *p = arg;
  863.                 else
  864.                     return "(unspecified)";
  865.                 
  866.             }
  867.             else if (*format == '&') {
  868.                 typedef int (*converter)(PyObject *, void *);
  869.                 converter convert = va_arg(*p_va, converter);
  870.                 void *addr = va_arg(*p_va, void *);
  871.                 format++;
  872.                 if (! (*convert)(arg, addr))
  873.                     return "(unspecified)";
  874.             }
  875.             else {
  876.                 p = va_arg(*p_va, PyObject **);
  877.                 *p = arg;
  878.             }
  879.             break;
  880.         }
  881.         
  882.         
  883.     case 'w': /* memory buffer, read-write access */
  884.         {
  885.             void **p = va_arg(*p_va, void **);
  886.             PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
  887.             int count;
  888.             
  889.             if ( pb == NULL || pb->bf_getwritebuffer == NULL ||
  890.                     pb->bf_getsegcount == NULL )
  891.                 return "read-write buffer";
  892.             if ( (*pb->bf_getsegcount)(arg, NULL) != 1 )
  893.                 return "single-segment read-write buffer";
  894.             if ( (count = pb->bf_getwritebuffer(arg, 0, p)) < 0 )
  895.                 return "(unspecified)";
  896.             if (*format == '#') {
  897.                 int *q = va_arg(*p_va, int *);
  898.                 
  899.                 *q = count;
  900.                 format++;
  901.             }
  902.             break;
  903.         }
  904.         
  905.     case 't': /* 8-bit character buffer, read-only access */
  906.         {
  907.             const char **p = va_arg(*p_va, const char **);
  908.             PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
  909.             int count;
  910.  
  911.             if ( *format++ != '#' )
  912.                 return "invalid use of 't' format character";
  913.             if ( !PyType_HasFeature(
  914.                 arg->ob_type,
  915.                 Py_TPFLAGS_HAVE_GETCHARBUFFER) ||
  916.                  pb == NULL ||
  917.                  pb->bf_getcharbuffer == NULL ||
  918.                  pb->bf_getsegcount == NULL )
  919.                 return "read-only character buffer";
  920.             if ( (*pb->bf_getsegcount)(arg, NULL) != 1 )
  921.                 return "single-segment read-only buffer";
  922.             if ( (count = pb->bf_getcharbuffer(arg, 0, p)) < 0 )
  923.                 return "(unspecified)";
  924.  
  925.             *va_arg(*p_va, int *) = count;
  926.  
  927.             break;
  928.         }
  929.         
  930.     
  931.     default:
  932.         return "impossible<bad format char>";
  933.     
  934.     }
  935.     
  936.     *p_format = format;
  937.     return NULL;
  938. }
  939.  
  940.  
  941. /* Support for keyword arguments donated by
  942.    Geoff Philbrick <philbric@delphi.hks.com> */
  943.  
  944. int PyArg_ParseTupleAndKeywords(PyObject *args,
  945.                 PyObject *keywords,
  946.                 char *format, 
  947.                 char **kwlist, ...)
  948. {
  949.     int retval;
  950.     va_list va;
  951.     
  952.     va_start(va, kwlist);
  953.     retval = vgetargskeywords(args, keywords, format, kwlist, &va);    
  954.     va_end(va);
  955.     return retval;
  956. }
  957.  
  958.  
  959. static int
  960. vgetargskeywords(PyObject *args, PyObject *keywords, char *format,
  961.              char **kwlist, va_list *p_va)
  962. {
  963.     char msgbuf[256];
  964.     int levels[32];
  965.     char *fname = NULL;
  966.     char *message = NULL;
  967.     int min = -1;
  968.     int max = 0;
  969.     char *formatsave = format;
  970.     int i, len, tplen, kwlen;
  971.     char *msg, *ks, **p;
  972.     int nkwds, pos, match, converted;
  973.     PyObject *key, *value;
  974.     
  975.     /* nested tuples cannot be parsed when using keyword arguments */
  976.     
  977.     for (;;) {
  978.         int c = *format++;
  979.         if (c == '(') {
  980.             PyErr_SetString(PyExc_SystemError,
  981.               "tuple found in format when using keyword arguments");
  982.             return 0;
  983.         }
  984.         else if (c == '\0')
  985.             break;
  986.         else if (c == ':') {
  987.             fname = format;
  988.             break;
  989.         }
  990.         else if (c == ';') {
  991.             message = format;
  992.             break;
  993.         }
  994.         else if (c == 'e')
  995.             ; /* Pass */
  996.         else if (isalpha(c))
  997.             max++;
  998.         else if (c == '|')
  999.             min = max;
  1000.     }    
  1001.     
  1002.     if (min < 0)
  1003.         min = max;
  1004.     
  1005.     format = formatsave;
  1006.     
  1007.     if (!PyTuple_Check(args)) {
  1008.         PyErr_SetString(PyExc_SystemError,
  1009.             "new style getargs format but argument is not a tuple");
  1010.         return 0;
  1011.     }    
  1012.     
  1013.     tplen = PyTuple_Size(args);
  1014.     
  1015.     /* do a cursory check of the keywords just to see how many we got */
  1016.        
  1017.     if (keywords) {     
  1018.         if (!PyDict_Check(keywords)) {
  1019.             PyErr_SetString(PyExc_SystemError,
  1020.       "non-dictionary object received when keyword dictionary expected");
  1021.             return 0;
  1022.         }    
  1023.         kwlen = PyDict_Size(keywords);
  1024.     }
  1025.     else {
  1026.         kwlen = 0;
  1027.     }
  1028.             
  1029.     /* make sure there are no duplicate values for an argument;
  1030.        its not clear when to use the term "keyword argument vs. 
  1031.        keyword parameter in messages */
  1032.     
  1033.     if (keywords) {
  1034.         for (i = 0; i < tplen; i++) {
  1035.             if (PyMapping_HasKeyString(keywords, kwlist[i])) {
  1036.                 sprintf(msgbuf,
  1037.                     "keyword parameter %s redefined",
  1038.                     kwlist[i]);
  1039.                 PyErr_SetString(PyExc_TypeError, msgbuf);
  1040.                 return 0;
  1041.             }
  1042.         }
  1043.     }
  1044.     PyErr_Clear(); /* I'm not which Py functions set the error string */
  1045.         
  1046.     /* required arguments missing from args can be supplied by keyword 
  1047.        arguments */
  1048.     
  1049.     len = tplen;
  1050.     if (keywords && tplen < min) {
  1051.         for (i = tplen; i < min; i++) {
  1052.           if (PyMapping_HasKeyString(keywords, kwlist[i])) {
  1053.                 len++;
  1054.           }
  1055.         }
  1056.     }
  1057.     PyErr_Clear();    
  1058.     
  1059.     /* make sure we got an acceptable number of arguments; the message
  1060.        is a little confusing with keywords since keyword arguments
  1061.        which are supplied, but don't match the required arguments
  1062.        are not included in the "%d given" part of the message */
  1063.  
  1064.     if (len < min || max < len) {
  1065.         if (message == NULL) {
  1066.             sprintf(msgbuf,
  1067.                 "%s requires %s %d argument%s; %d given",
  1068.                 fname==NULL ? "function" : fname,
  1069.                 min==max ? "exactly"
  1070.                          : len < min ? "at least" : "at most",
  1071.                 len < min ? min : max,
  1072.                 (len < min ? min : max) == 1 ? "" : "s",
  1073.                 len);
  1074.             message = msgbuf;
  1075.         }
  1076.         PyErr_SetString(PyExc_TypeError, message);
  1077.         return 0;
  1078.     }
  1079.     
  1080.     for (i = 0; i < tplen; i++) {
  1081.         if (*format == '|')
  1082.             format++;
  1083.         msg = convertitem(PyTuple_GetItem(args, i), &format, p_va,
  1084.                  levels, msgbuf);
  1085.         if (msg) {
  1086.             seterror(i+1, msg, levels, fname, message);
  1087.             return 0;
  1088.         }
  1089.     }
  1090.  
  1091.     /* handle no keyword parameters in call  */    
  1092.               
  1093.     if (!keywords) return 1; 
  1094.         
  1095.     /* make sure the number of keywords in the keyword list matches the 
  1096.        number of items in the format string */
  1097.       
  1098.     nkwds = 0;
  1099.     p =  kwlist;
  1100.     for (;;) {
  1101.         if (!*(p++)) break;
  1102.         nkwds++;
  1103.     }
  1104.  
  1105.     if (nkwds != max) {
  1106.         PyErr_SetString(PyExc_SystemError,
  1107.       "number of items in format string and keyword list do not match");
  1108.         return 0;
  1109.     }            
  1110.             
  1111.     /* convert the keyword arguments; this uses the format 
  1112.        string where it was left after processing args */
  1113.     
  1114.     converted = 0;
  1115.     for (i = tplen; i < nkwds; i++) {
  1116.         PyObject *item;
  1117.         if (*format == '|')
  1118.             format++;
  1119.         item = PyMapping_GetItemString(keywords, kwlist[i]);
  1120.         if (item != NULL) {
  1121.             msg = convertitem(item, &format, p_va, levels, msgbuf);
  1122.             if (msg) {
  1123.                 seterror(i+1, msg, levels, fname, message);
  1124.                 return 0;
  1125.             }
  1126.             converted++;
  1127.         }
  1128.         else {
  1129.             PyErr_Clear();
  1130.             msg = skipitem(&format, p_va);
  1131.             if (msg) {
  1132.                 seterror(i+1, msg, levels, fname, message);
  1133.                 return 0;
  1134.             }
  1135.         }
  1136.     }
  1137.     
  1138.     /* make sure there are no extraneous keyword arguments */
  1139.     
  1140.     pos = 0;
  1141.     if (converted < kwlen) {
  1142.         while (PyDict_Next(keywords, &pos, &key, &value)) {
  1143.             match = 0;
  1144.             ks = PyString_AsString(key);
  1145.             for (i = 0; i < nkwds; i++) {
  1146.                 if (!strcmp(ks, kwlist[i])) {
  1147.                     match = 1;
  1148.                     break;
  1149.                 }
  1150.             }
  1151.             if (!match) {
  1152.                 sprintf(msgbuf,
  1153.             "%s is an invalid keyword argument for this function",
  1154.                     ks);
  1155.                 PyErr_SetString(PyExc_TypeError, msgbuf);
  1156.                 return 0;
  1157.             }
  1158.         }
  1159.     }
  1160.     
  1161.     return 1;
  1162. }
  1163.  
  1164.  
  1165. static char *
  1166. skipitem(char **p_format, va_list *p_va)
  1167. {
  1168.     char *format = *p_format;
  1169.     char c = *format++;
  1170.     
  1171.     switch (c) {
  1172.     
  1173.     case 'b': /* byte -- very short int */
  1174.     case 'B': /* byte as bitfield */
  1175.         {
  1176.             (void) va_arg(*p_va, char *);
  1177.             break;
  1178.         }
  1179.     
  1180.     case 'h': /* short int */
  1181.         {
  1182.             (void) va_arg(*p_va, short *);
  1183.             break;
  1184.         }
  1185.     
  1186.     case 'H': /* short int as bitfield */
  1187.         {
  1188.             (void) va_arg(*p_va, unsigned short *);
  1189.             break;
  1190.         }
  1191.     
  1192.     case 'i': /* int */
  1193.         {
  1194.             (void) va_arg(*p_va, int *);
  1195.             break;
  1196.         }
  1197.     
  1198.     case 'l': /* long int */
  1199.         {
  1200.             (void) va_arg(*p_va, long *);
  1201.             break;
  1202.         }
  1203.     
  1204. #ifdef HAVE_LONG_LONG
  1205.     case 'L': /* LONG_LONG int */
  1206.         {
  1207.             (void) va_arg(*p_va, LONG_LONG *);
  1208.             break;
  1209.         }
  1210. #endif
  1211.     
  1212.     case 'f': /* float */
  1213.         {
  1214.             (void) va_arg(*p_va, float *);
  1215.             break;
  1216.         }
  1217.     
  1218.     case 'd': /* double */
  1219.         {
  1220.             (void) va_arg(*p_va, double *);
  1221.             break;
  1222.         }
  1223.     
  1224. #ifndef WITHOUT_COMPLEX
  1225.     case 'D': /* complex double */
  1226.         {
  1227.             (void) va_arg(*p_va, Py_complex *);
  1228.             break;
  1229.         }
  1230. #endif /* WITHOUT_COMPLEX */
  1231.     
  1232.     case 'c': /* char */
  1233.         {
  1234.             (void) va_arg(*p_va, char *);
  1235.             break;
  1236.         }
  1237.     
  1238.     case 's': /* string */
  1239.         {
  1240.             (void) va_arg(*p_va, char **);
  1241.             if (*format == '#') {
  1242.                 (void) va_arg(*p_va, int *);
  1243.                 format++;
  1244.             }
  1245.             break;
  1246.         }
  1247.     
  1248.     case 'z': /* string */
  1249.         {
  1250.             (void) va_arg(*p_va, char **);
  1251.             if (*format == '#') {
  1252.                 (void) va_arg(*p_va, int *);
  1253.                 format++;
  1254.             }
  1255.             break;
  1256.         }
  1257.     
  1258.     case 'S': /* string object */
  1259.         {
  1260.             (void) va_arg(*p_va, PyObject **);
  1261.             break;
  1262.         }
  1263.     
  1264.     case 'O': /* object */
  1265.         {
  1266.             if (*format == '!') {
  1267.                 format++;
  1268.                 (void) va_arg(*p_va, PyTypeObject*);
  1269.                 (void) va_arg(*p_va, PyObject **);
  1270.             }
  1271. #if 0
  1272. /* I don't know what this is for */
  1273.             else if (*format == '?') {
  1274.                 inquiry pred = va_arg(*p_va, inquiry);
  1275.                 format++;
  1276.                 if ((*pred)(arg)) {
  1277.                     (void) va_arg(*p_va, PyObject **);
  1278.                 }
  1279.             }
  1280. #endif
  1281.             else if (*format == '&') {
  1282.                 typedef int (*converter)(PyObject *, void *);
  1283.                 (void) va_arg(*p_va, converter);
  1284.                 (void) va_arg(*p_va, void *);
  1285.                 format++;
  1286.             }
  1287.             else {
  1288.                 (void) va_arg(*p_va, PyObject **);
  1289.             }
  1290.             break;
  1291.         }
  1292.     
  1293.     default:
  1294.         return "impossible<bad format char>";
  1295.     
  1296.     }
  1297.     
  1298.     *p_format = format;
  1299.     return NULL;
  1300. }
  1301.