/* * tkImgPhInstance.c -- * * Implements the rendering of images of type "photo" for Tk. Photo * images are stored in full color (32 bits per pixel including alpha * channel) and displayed using dithering if necessary. * * Copyright (c) 1994 The Australian National University. * Copyright (c) 1994-1997 Sun Microsystems, Inc. * Copyright (c) 2002-2008 Donal K. Fellows * Copyright (c) 2003 ActiveState Corporation. * * See the file "license.terms" for information on usage and redistribution of * this file, and for a DISCLAIMER OF ALL WARRANTIES. * * Author: Paul Mackerras (paulus@cs.anu.edu.au), * Department of Computer Science, * Australian National University. */ #include "tkImgPhoto.h" #include "tkPort.h" /* * Declaration for internal Xlib function used here: */ extern int _XInitImageFuncPtrs(XImage *image); /* * Forward declarations */ #ifndef TK_CAN_RENDER_RGBA static void BlendComplexAlpha(XImage *bgImg, PhotoInstance *iPtr, int xOffset, int yOffset, int width, int height); #endif static int IsValidPalette(PhotoInstance *instancePtr, const char *palette); static int CountBits(pixel mask); static void GetColorTable(PhotoInstance *instancePtr); static void FreeColorTable(ColorTable *colorPtr, int force); static void AllocateColors(ColorTable *colorPtr); static void DisposeColorTable(ClientData clientData); static int ReclaimColors(ColorTableId *id, int numColors); /* * Hash table used to hash from (display, colormap, palette, gamma) to * ColorTable address. */ static Tcl_HashTable imgPhotoColorHash; static int imgPhotoColorHashInitialized; #define N_COLOR_HASH (sizeof(ColorTableId) / sizeof(int)) /* *---------------------------------------------------------------------- * * TkImgPhotoConfigureInstance -- * * This function is called to create displaying information for a photo * image instance based on the configuration information in the model. * It is invoked both when new instances are created and when the model * is reconfigured. * * Results: * None. * * Side effects: * Generates errors via Tcl_BackgroundException if there are problems in * setting up the instance. * *---------------------------------------------------------------------- */ void TkImgPhotoConfigureInstance( PhotoInstance *instancePtr) /* Instance to reconfigure. */ { PhotoModel *modelPtr = instancePtr->masterPtr; XImage *imagePtr; int bitsPerPixel; ColorTable *colorTablePtr; XRectangle validBox; /* * If the -palette configuration option has been set for the model, use * the value specified for our palette, but only if it is a valid palette * for our windows. Use the gamma value specified the model. */ if ((modelPtr->palette && modelPtr->palette[0]) && IsValidPalette(instancePtr, modelPtr->palette)) { instancePtr->palette = modelPtr->palette; } else { instancePtr->palette = instancePtr->defaultPalette; } instancePtr->gamma = modelPtr->gamma; /* * If we don't currently have a color table, or if the one we have no * longer applies (e.g. because our palette or gamma has changed), get a * new one. */ colorTablePtr = instancePtr->colorTablePtr; if ((colorTablePtr == NULL) || (instancePtr->colormap != colorTablePtr->id.colormap) || (instancePtr->palette != colorTablePtr->id.palette) || (instancePtr->gamma != colorTablePtr->id.gamma)) { /* * Free up our old color table, and get a new one. */ if (colorTablePtr != NULL) { colorTablePtr->liveRefCount -= 1; FreeColorTable(colorTablePtr, 0); } GetColorTable(instancePtr); /* * Create a new XImage structure for sending data to the X server, if * necessary. */ if (instancePtr->colorTablePtr->flags & BLACK_AND_WHITE) { bitsPerPixel = 1; } else { bitsPerPixel = instancePtr->visualInfo.depth; } if ((instancePtr->imagePtr == NULL) || (instancePtr->imagePtr->bits_per_pixel != bitsPerPixel)) { if (instancePtr->imagePtr != NULL) { XDestroyImage(instancePtr->imagePtr); } imagePtr = XCreateImage(instancePtr->display, instancePtr->visualInfo.visual, (unsigned) bitsPerPixel, (bitsPerPixel > 1? ZPixmap: XYBitmap), 0, NULL, 1, 1, 32, 0); instancePtr->imagePtr = imagePtr; /* * We create images using the local host's endianness, rather than * the endianness of the server; otherwise we would have to * byte-swap any 16 or 32 bit values that we store in the image * if the server's endianness is different from ours. */ if (imagePtr != NULL) { #ifdef WORDS_BIGENDIAN imagePtr->byte_order = MSBFirst; #else imagePtr->byte_order = LSBFirst; #endif _XInitImageFuncPtrs(imagePtr); } } } /* * If the user has specified a width and/or height for the model which is * different from our current width/height, set the size to the values * specified by the user. If we have no pixmap, we do this also, since it * has the side effect of allocating a pixmap for us. */ if ((instancePtr->pixels == None) || (instancePtr->error == NULL) || (instancePtr->width != modelPtr->width) || (instancePtr->height != modelPtr->height)) { TkImgPhotoInstanceSetSize(instancePtr); } /* * Redither this instance if necessary. */ if ((modelPtr->flags & IMAGE_CHANGED) || (instancePtr->colorTablePtr != colorTablePtr)) { TkClipBox(modelPtr->validRegion, &validBox); if ((validBox.width > 0) && (validBox.height > 0)) { TkImgDitherInstance(instancePtr, validBox.x, validBox.y, validBox.width, validBox.height); } } } /* *---------------------------------------------------------------------- * * TkImgPhotoGet -- * * This function is called for each use of a photo image in a widget. * * Results: * The return value is a token for the instance, which is passed back to * us in calls to TkImgPhotoDisplay and ImgPhotoFree. * * Side effects: * A data structure is set up for the instance (or, an existing instance * is re-used for the new one). * *---------------------------------------------------------------------- */ ClientData TkImgPhotoGet( Tk_Window tkwin, /* Window in which the instance will be * used. */ ClientData modelData) /* Pointer to our model structure for the * image. */ { PhotoModel *modelPtr = modelData; PhotoInstance *instancePtr; Colormap colormap; int mono, nRed, nGreen, nBlue, numVisuals; XVisualInfo visualInfo, *visInfoPtr; char buf[TCL_INTEGER_SPACE * 3]; XColor *white, *black; XGCValues gcValues; /* * Table of "best" choices for palette for PseudoColor displays with * between 3 and 15 bits/pixel. */ static const int paletteChoice[13][3] = { /* #red, #green, #blue */ {2, 2, 2, /* 3 bits, 8 colors */}, {2, 3, 2, /* 4 bits, 12 colors */}, {3, 4, 2, /* 5 bits, 24 colors */}, {4, 5, 3, /* 6 bits, 60 colors */}, {5, 6, 4, /* 7 bits, 120 colors */}, {7, 7, 4, /* 8 bits, 198 colors */}, {8, 10, 6, /* 9 bits, 480 colors */}, {10, 12, 8, /* 10 bits, 960 colors */}, {14, 15, 9, /* 11 bits, 1890 colors */}, {16, 20, 12, /* 12 bits, 3840 colors */}, {20, 24, 16, /* 13 bits, 7680 colors */}, {26, 30, 20, /* 14 bits, 15600 colors */}, {32, 32, 30, /* 15 bits, 30720 colors */} }; /* * See if there is already an instance for windows using the same * colormap. If so then just re-use it. */ colormap = Tk_Colormap(tkwin); for (instancePtr = modelPtr->instancePtr; instancePtr != NULL; instancePtr = instancePtr->nextPtr) { if ((colormap == instancePtr->colormap) && (Tk_Display(tkwin) == instancePtr->display)) { /* * Re-use this instance. */ if (instancePtr->refCount == 0) { /* * We are resurrecting this instance. */ Tcl_CancelIdleCall(TkImgDisposeInstance, instancePtr); if (instancePtr->colorTablePtr != NULL) { FreeColorTable(instancePtr->colorTablePtr, 0); } GetColorTable(instancePtr); } instancePtr->refCount++; return instancePtr; } } /* * The image isn't already in use in a window with the same colormap. Make * a new instance of the image. */ instancePtr = ckalloc(sizeof(PhotoInstance)); instancePtr->masterPtr = modelPtr; instancePtr->display = Tk_Display(tkwin); instancePtr->colormap = Tk_Colormap(tkwin); Tk_PreserveColormap(instancePtr->display, instancePtr->colormap); instancePtr->refCount = 1; instancePtr->colorTablePtr = NULL; instancePtr->pixels = None; instancePtr->error = NULL; instancePtr->width = 0; instancePtr->height = 0; instancePtr->imagePtr = 0; instancePtr->nextPtr = modelPtr->instancePtr; modelPtr->instancePtr = instancePtr; /* * Obtain information about the visual and decide on the default palette. */ visualInfo.screen = Tk_ScreenNumber(tkwin); visualInfo.visualid = XVisualIDFromVisual(Tk_Visual(tkwin)); visInfoPtr = XGetVisualInfo(Tk_Display(tkwin), VisualScreenMask | VisualIDMask, &visualInfo, &numVisuals); if (visInfoPtr == NULL) { Tcl_Panic("TkImgPhotoGet couldn't find visual for window"); } nRed = 2; nGreen = nBlue = 0; mono = 1; instancePtr->visualInfo = *visInfoPtr; switch (visInfoPtr->c_class) { case DirectColor: case TrueColor: nRed = 1 << CountBits(visInfoPtr->red_mask); nGreen = 1 << CountBits(visInfoPtr->green_mask); nBlue = 1 << CountBits(visInfoPtr->blue_mask); mono = 0; break; case PseudoColor: case StaticColor: if (visInfoPtr->depth > 15) { nRed = 32; nGreen = 32; nBlue = 32; mono = 0; } else if (visInfoPtr->depth >= 3) { const int *ip = paletteChoice[visInfoPtr->depth - 3]; nRed = ip[0]; nGreen = ip[1]; nBlue = ip[2]; mono = 0; } break; case GrayScale: case StaticGray: nRed = 1 << visInfoPtr->depth; break; } XFree((char *) visInfoPtr); if (mono) { sprintf(buf, "%d", nRed); } else { sprintf(buf, "%d/%d/%d", nRed, nGreen, nBlue); } instancePtr->defaultPalette = Tk_GetUid(buf); /* * Make a GC with background = black and foreground = white. */ white = Tk_GetColor(modelPtr->interp, tkwin, "white"); black = Tk_GetColor(modelPtr->interp, tkwin, "black"); gcValues.foreground = (white != NULL)? white->pixel: WhitePixelOfScreen(Tk_Screen(tkwin)); gcValues.background = (black != NULL)? black->pixel: BlackPixelOfScreen(Tk_Screen(tkwin)); Tk_FreeColor(white); Tk_FreeColor(black); gcValues.graphics_exposures = False; instancePtr->gc = Tk_GetGC(tkwin, GCForeground|GCBackground|GCGraphicsExposures, &gcValues); /* * Set configuration options and finish the initialization of the * instance. This will also dither the image if necessary. */ TkImgPhotoConfigureInstance(instancePtr); /* * If this is the first instance, must set the size of the image. */ if (instancePtr->nextPtr == NULL) { Tk_ImageChanged(modelPtr->tkMaster, 0, 0, 0, 0, modelPtr->width, modelPtr->height); } return instancePtr; } /* *---------------------------------------------------------------------- * * BlendComplexAlpha -- * * This function is called when an image with partially transparent * pixels must be drawn over another image. It blends the photo data onto * a local copy of the surface that we are drawing on, *including* the * pixels drawn by everything that should be drawn underneath the image. * * Much of this code has hard-coded values in for speed because this * routine is performance critical for complex image drawing. * * Results: * None. * * Side effects: * Background image passed in gets drawn over with image data. * * Notes: * This should work on all platforms that set mask and shift data * properly from the visualInfo. RGB is really only a 24+ bpp version * whereas RGB15 is the correct version and works for 15bpp+, but it * slower, so it's only used for 15bpp+. * * Note that Win32 pre-defines those operations that we really need. * *---------------------------------------------------------------------- */ #ifndef TK_CAN_RENDER_RGBA #ifndef _WIN32 #define GetRValue(rgb) (UCHAR(((rgb) & red_mask) >> red_shift)) #define GetGValue(rgb) (UCHAR(((rgb) & green_mask) >> green_shift)) #define GetBValue(rgb) (UCHAR(((rgb) & blue_mask) >> blue_shift)) #define RGB(r, g, b) ((unsigned)( \ (UCHAR(r) << red_shift) | \ (UCHAR(g) << green_shift) | \ (UCHAR(b) << blue_shift) )) #define RGB15(r, g, b) ((unsigned)( \ (((r) * red_mask / 255) & red_mask) | \ (((g) * green_mask / 255) & green_mask) | \ (((b) * blue_mask / 255) & blue_mask) )) #endif /* !_WIN32 */ static void BlendComplexAlpha( XImage *bgImg, /* Background image to draw on. */ PhotoInstance *iPtr, /* Image instance to draw. */ int xOffset, int yOffset, /* X & Y offset into image instance to * draw. */ int width, int height) /* Width & height of image to draw. */ { int x, y, line; unsigned long pixel; unsigned char r, g, b, alpha, unalpha, *modelPtr; unsigned char *alphaAr = iPtr->masterPtr->pix32; /* * This blending is an integer version of the Source-Over compositing rule * (see Porter&Duff, "Compositing Digital Images", proceedings of SIGGRAPH * 1984) that has been hard-coded (for speed) to work with targetting a * solid surface. * * The 'unalpha' field must be 255-alpha; it is separated out to encourage * more efficient compilation. */ #define ALPHA_BLEND(bgPix, imgPix, alpha, unalpha) \ ((bgPix * unalpha + imgPix * alpha) / 255) /* * We have to get the mask and shift info from the visual on non-Win32 so * that the macros Get*Value(), RGB() and RGB15() work correctly. This * might be cached for better performance. */ #ifndef _WIN32 unsigned long red_mask, green_mask, blue_mask; unsigned long red_shift, green_shift, blue_shift; Visual *visual = iPtr->visualInfo.visual; red_mask = visual->red_mask; green_mask = visual->green_mask; blue_mask = visual->blue_mask; red_shift = 0; green_shift = 0; blue_shift = 0; while ((0x0001 & (red_mask >> red_shift)) == 0) { red_shift++; } while ((0x0001 & (green_mask >> green_shift)) == 0) { green_shift++; } while ((0x0001 & (blue_mask >> blue_shift)) == 0) { blue_shift++; } #endif /* !_WIN32 */ /* * Only UNIX requires the special case for <24bpp. It varies with 3 extra * shifts and uses RGB15. The 24+bpp version could also then be further * optimized. */ #if !defined(_WIN32) if (bgImg->depth < 24) { unsigned char red_mlen, green_mlen, blue_mlen; red_mlen = 8 - CountBits(red_mask >> red_shift); green_mlen = 8 - CountBits(green_mask >> green_shift); blue_mlen = 8 - CountBits(blue_mask >> blue_shift); for (y = 0; y < height; y++) { line = (y + yOffset) * iPtr->masterPtr->width; for (x = 0; x < width; x++) { modelPtr = alphaAr + ((line + x + xOffset) * 4); alpha = modelPtr[3]; /* * Ignore pixels that are fully transparent */ if (alpha) { /* * We could perhaps be more efficient than XGetPixel for * 24 and 32 bit displays, but this seems "fast enough". */ r = modelPtr[0]; g = modelPtr[1]; b = modelPtr[2]; if (alpha != 255) { /* * Only blend pixels that have some transparency */ unsigned char ra, ga, ba; pixel = XGetPixel(bgImg, x, y); ra = GetRValue(pixel) << red_mlen; ga = GetGValue(pixel) << green_mlen; ba = GetBValue(pixel) << blue_mlen; unalpha = 255 - alpha; /* Calculate once. */ r = ALPHA_BLEND(ra, r, alpha, unalpha); g = ALPHA_BLEND(ga, g, alpha, unalpha); b = ALPHA_BLEND(ba, b, alpha, unalpha); } XPutPixel(bgImg, x, y, RGB15(r, g, b)); } } } return; } #endif /* !_WIN32 */ for (y = 0; y < height; y++) { line = (y + yOffset) * iPtr->masterPtr->width; for (x = 0; x < width; x++) { modelPtr = alphaAr + ((line + x + xOffset) * 4); alpha = modelPtr[3]; /* * Ignore pixels that are fully transparent */ if (alpha) { /* * We could perhaps be more efficient than XGetPixel for 24 * and 32 bit displays, but this seems "fast enough". */ r = modelPtr[0]; g = modelPtr[1]; b = modelPtr[2]; if (alpha != 255) { /* * Only blend pixels that have some transparency */ unsigned char ra, ga, ba; pixel = XGetPixel(bgImg, x, y); ra = GetRValue(pixel); ga = GetGValue(pixel); ba = GetBValue(pixel); unalpha = 255 - alpha; /* Calculate once. */ r = ALPHA_BLEND(ra, r, alpha, unalpha); g = ALPHA_BLEND(ga, g, alpha, unalpha); b = ALPHA_BLEND(ba, b, alpha, unalpha); } XPutPixel(bgImg, x, y, RGB(r, g, b)); } } } #undef ALPHA_BLEND } #endif /* TK_CAN_RENDER_RGBA */ /* *---------------------------------------------------------------------- * * TkImgPhotoDisplay -- * * This function is invoked to draw a photo image. * * Results: * None. * * Side effects: * A portion of the image gets rendered in a pixmap or window. * *---------------------------------------------------------------------- */ void TkImgPhotoDisplay( ClientData clientData, /* Pointer to PhotoInstance structure for * instance to be displayed. */ Display *display, /* Display on which to draw image. */ Drawable drawable, /* Pixmap or window in which to draw image. */ int imageX, int imageY, /* Upper-left corner of region within image to * draw. */ int width, int height, /* Dimensions of region within image to * draw. */ int drawableX,int drawableY)/* Coordinates within drawable that correspond * to imageX and imageY. */ { PhotoInstance *instancePtr = clientData; #ifndef TK_CAN_RENDER_RGBA XVisualInfo visInfo = instancePtr->visualInfo; #endif /* * If there's no pixmap, it means that an error occurred while creating * the image instance so it can't be displayed. */ if (instancePtr->pixels == None) { return; } #ifdef TK_CAN_RENDER_RGBA /* * We can use TkpPutRGBAImage to render RGBA Ximages directly so there is * no need to call XGetImage or to do the Porter-Duff compositing by hand. */ unsigned char *rgbaPixels = instancePtr->masterPtr->pix32; XImage *photo = XCreateImage(display, NULL, 32, ZPixmap, 0, (char*)rgbaPixels, (unsigned int)instancePtr->width, (unsigned int)instancePtr->height, 0, (unsigned int)(4 * instancePtr->width)); TkpPutRGBAImage(display, drawable, instancePtr->gc, photo, imageX, imageY, drawableX, drawableY, (unsigned int) width, (unsigned int) height); photo->data = NULL; XDestroyImage(photo); #else if ((instancePtr->masterPtr->flags & COMPLEX_ALPHA) && visInfo.depth >= 15 && (visInfo.c_class == DirectColor || visInfo.c_class == TrueColor)) { Tk_ErrorHandler handler; XImage *bgImg = NULL; /* * Create an error handler to suppress the case where the input was * not properly constrained, which can cause an X error. [Bug 979239] */ handler = Tk_CreateErrorHandler(display, -1, -1, -1, NULL, NULL); /* * Pull the current background from the display to blend with */ bgImg = XGetImage(display, drawable, drawableX, drawableY, (unsigned int)width, (unsigned int)height, AllPlanes, ZPixmap); if (bgImg == NULL) { Tk_DeleteErrorHandler(handler); /* We failed to get the image, so draw without blending alpha. * It's the best we can do. */ goto fallBack; } BlendComplexAlpha(bgImg, instancePtr, imageX, imageY, width, height); /* * Color info is unimportant as we only do this operation for depth >= * 15. */ TkPutImage(NULL, 0, display, drawable, instancePtr->gc, bgImg, 0, 0, drawableX, drawableY, (unsigned int) width, (unsigned int) height); XDestroyImage(bgImg); Tk_DeleteErrorHandler(handler); } else { /* * modelPtr->region describes which parts of the image contain valid * data. We set this region as the clip mask for the gc, setting its * origin appropriately, and use it when drawing the image. */ fallBack: TkSetRegion(display, instancePtr->gc, instancePtr->masterPtr->validRegion); XSetClipOrigin(display, instancePtr->gc, drawableX - imageX, drawableY - imageY); XCopyArea(display, instancePtr->pixels, drawable, instancePtr->gc, imageX, imageY, (unsigned) width, (unsigned) height, drawableX, drawableY); XSetClipMask(display, instancePtr->gc, None); XSetClipOrigin(display, instancePtr->gc, 0, 0); } (void)XFlush(display); #endif } /* *---------------------------------------------------------------------- * * TkImgPhotoFree -- * * This function is called when a widget ceases to use a particular * instance of an image. We don't actually get rid of the instance until * later because we may be about to get this instance again. * * Results: * None. * * Side effects: * Internal data structures get cleaned up, later. * *---------------------------------------------------------------------- */ void TkImgPhotoFree( ClientData clientData, /* Pointer to PhotoInstance structure for * instance to be displayed. */ Display *display) /* Display containing window that used * image. */ { PhotoInstance *instancePtr = clientData; ColorTable *colorPtr; if (instancePtr->refCount-- > 1) { return; } /* * There are no more uses of the image within this widget. Decrement the * count of live uses of its color table, so that its colors can be * reclaimed if necessary, and set up an idle call to free the instance * structure. */ colorPtr = instancePtr->colorTablePtr; if (colorPtr != NULL) { colorPtr->liveRefCount -= 1; } Tcl_DoWhenIdle(TkImgDisposeInstance, instancePtr); } /* *---------------------------------------------------------------------- * * TkImgPhotoInstanceSetSize -- * * This function reallocates the instance pixmap and dithering error * array for a photo instance, as necessary, to change the image's size * to `width' x `height' pixels. * * Results: * None. * * Side effects: * Storage gets reallocated, here and in the X server. * *---------------------------------------------------------------------- */ void TkImgPhotoInstanceSetSize( PhotoInstance *instancePtr) /* Instance whose size is to be changed. */ { PhotoModel *modelPtr; schar *newError, *errSrcPtr, *errDestPtr; int h, offset; XRectangle validBox; Pixmap newPixmap; modelPtr = instancePtr->masterPtr; TkClipBox(modelPtr->validRegion, &validBox); if ((instancePtr->width != modelPtr->width) || (instancePtr->height != modelPtr->height) || (instancePtr->pixels == None)) { newPixmap = Tk_GetPixmap(instancePtr->display, RootWindow(instancePtr->display, instancePtr->visualInfo.screen), (modelPtr->width > 0) ? modelPtr->width: 1, (modelPtr->height > 0) ? modelPtr->height: 1, instancePtr->visualInfo.depth); if (!newPixmap) { Tcl_Panic("Fail to create pixmap with Tk_GetPixmap in TkImgPhotoInstanceSetSize"); } /* * The following is a gross hack needed to properly support colormaps * under Windows. Before the pixels can be copied to the pixmap, the * relevent colormap must be associated with the drawable. Normally we * can infer this association from the window that was used to create * the pixmap. However, in this case we're using the root window, so * we have to be more explicit. */ TkSetPixmapColormap(newPixmap, instancePtr->colormap); if (instancePtr->pixels != None) { /* * Copy any common pixels from the old pixmap and free it. */ XCopyArea(instancePtr->display, instancePtr->pixels, newPixmap, instancePtr->gc, validBox.x, validBox.y, validBox.width, validBox.height, validBox.x, validBox.y); Tk_FreePixmap(instancePtr->display, instancePtr->pixels); } instancePtr->pixels = newPixmap; } if ((instancePtr->width != modelPtr->width) || (instancePtr->height != modelPtr->height) || (instancePtr->error == NULL)) { if (modelPtr->height > 0 && modelPtr->width > 0) { /* * TODO: use attemptckalloc() here once there is a strategy that * will allow us to recover from failure. Right now, there's no * such possibility. */ newError = ckalloc(modelPtr->height * modelPtr->width * 3 * sizeof(schar)); /* * Zero the new array so that we don't get bogus error values * propagating into areas we dither later. */ if ((instancePtr->error != NULL) && ((instancePtr->width == modelPtr->width) || (validBox.width == modelPtr->width))) { if (validBox.y > 0) { memset(newError, 0, (size_t) validBox.y * modelPtr->width * 3 * sizeof(schar)); } h = validBox.y + validBox.height; if (h < modelPtr->height) { memset(newError + h*modelPtr->width*3, 0, (size_t) (modelPtr->height - h) * modelPtr->width * 3 * sizeof(schar)); } } else { memset(newError, 0, (size_t) modelPtr->height * modelPtr->width *3*sizeof(schar)); } } else { newError = NULL; } if (instancePtr->error != NULL) { /* * Copy the common area over to the new array and free the old * array. */ if (modelPtr->width == instancePtr->width) { offset = validBox.y * modelPtr->width * 3; memcpy(newError + offset, instancePtr->error + offset, (size_t) (validBox.height * modelPtr->width * 3 * sizeof(schar))); } else if (validBox.width > 0 && validBox.height > 0) { errDestPtr = newError + (validBox.y * modelPtr->width + validBox.x) * 3; errSrcPtr = instancePtr->error + (validBox.y * instancePtr->width + validBox.x) * 3; for (h = validBox.height; h > 0; --h) { memcpy(errDestPtr, errSrcPtr, validBox.width * 3 * sizeof(schar)); errDestPtr += modelPtr->width * 3; errSrcPtr += instancePtr->width * 3; } } ckfree(instancePtr->error); } instancePtr->error = newError; } instancePtr->width = modelPtr->width; instancePtr->height = modelPtr->height; } /* *---------------------------------------------------------------------- * * IsValidPalette -- * * This function is called to check whether a value given for the * -palette option is valid for a particular instance of a photo image. * * Results: * A boolean value: 1 if the palette is acceptable, 0 otherwise. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int IsValidPalette( PhotoInstance *instancePtr, /* Instance to which the palette specification * is to be applied. */ const char *palette) /* Palette specification string. */ { int nRed, nGreen, nBlue, mono, numColors; char *endp; /* * First parse the specification: it must be of the form %d or %d/%d/%d. */ nRed = strtol(palette, &endp, 10); if ((endp == palette) || ((*endp != 0) && (*endp != '/')) || (nRed < 2) || (nRed > 256)) { return 0; } if (*endp == 0) { mono = 1; nGreen = nBlue = nRed; } else { palette = endp + 1; nGreen = strtol(palette, &endp, 10); if ((endp == palette) || (*endp != '/') || (nGreen < 2) || (nGreen > 256)) { return 0; } palette = endp + 1; nBlue = strtol(palette, &endp, 10); if ((endp == palette) || (*endp != 0) || (nBlue < 2) || (nBlue > 256)) { return 0; } mono = 0; } switch (instancePtr->visualInfo.c_class) { case DirectColor: case TrueColor: if ((nRed > (1 << CountBits(instancePtr->visualInfo.red_mask))) || (nGreen>(1<visualInfo.green_mask))) || (nBlue>(1<visualInfo.blue_mask)))) { return 0; } break; case PseudoColor: case StaticColor: numColors = nRed; if (!mono) { numColors *= nGreen * nBlue; } if (numColors > (1 << instancePtr->visualInfo.depth)) { return 0; } break; case GrayScale: case StaticGray: if (!mono || (nRed > (1 << instancePtr->visualInfo.depth))) { return 0; } break; } return 1; } /* *---------------------------------------------------------------------- * * CountBits -- * * This function counts how many bits are set to 1 in `mask'. * * Results: * The integer number of bits. * * Side effects: * None. * *---------------------------------------------------------------------- */ static int CountBits( pixel mask) /* Value to count the 1 bits in. */ { int n; for (n=0 ; mask!=0 ; mask&=mask-1) { n++; } return n; } /* *---------------------------------------------------------------------- * * GetColorTable -- * * This function is called to allocate a table of colormap information * for an instance of a photo image. Only one such table is allocated for * all photo instances using the same display, colormap, palette and * gamma values, so that the application need only request a set of * colors from the X server once for all such photo widgets. This * function maintains a hash table to find previously-allocated * ColorTables. * * Results: * None. * * Side effects: * A new ColorTable may be allocated and placed in the hash table, and * have colors allocated for it. * *---------------------------------------------------------------------- */ static void GetColorTable( PhotoInstance *instancePtr) /* Instance needing a color table. */ { ColorTable *colorPtr; Tcl_HashEntry *entry; ColorTableId id; int isNew; /* * Look for an existing ColorTable in the hash table. */ memset(&id, 0, sizeof(id)); id.display = instancePtr->display; id.colormap = instancePtr->colormap; id.palette = instancePtr->palette; id.gamma = instancePtr->gamma; if (!imgPhotoColorHashInitialized) { Tcl_InitHashTable(&imgPhotoColorHash, N_COLOR_HASH); imgPhotoColorHashInitialized = 1; } entry = Tcl_CreateHashEntry(&imgPhotoColorHash, (char *) &id, &isNew); if (!isNew) { /* * Re-use the existing entry. */ colorPtr = Tcl_GetHashValue(entry); } else { /* * No color table currently available; need to make one. */ colorPtr = ckalloc(sizeof(ColorTable)); /* * The following line of code should not normally be needed due to the * assignment in the following line. However, it compensates for bugs * in some compilers (HP, for example) where sizeof(ColorTable) is 24 * but the assignment only copies 20 bytes, leaving 4 bytes * uninitialized; these cause problems when using the id for lookups * in imgPhotoColorHash, and can result in core dumps. */ memset(&colorPtr->id, 0, sizeof(ColorTableId)); colorPtr->id = id; Tk_PreserveColormap(colorPtr->id.display, colorPtr->id.colormap); colorPtr->flags = 0; colorPtr->refCount = 0; colorPtr->liveRefCount = 0; colorPtr->numColors = 0; colorPtr->visualInfo = instancePtr->visualInfo; colorPtr->pixelMap = NULL; Tcl_SetHashValue(entry, colorPtr); } colorPtr->refCount++; colorPtr->liveRefCount++; instancePtr->colorTablePtr = colorPtr; if (colorPtr->flags & DISPOSE_PENDING) { Tcl_CancelIdleCall(DisposeColorTable, colorPtr); colorPtr->flags &= ~DISPOSE_PENDING; } /* * Allocate colors for this color table if necessary. */ if ((colorPtr->numColors == 0) && !(colorPtr->flags & BLACK_AND_WHITE)) { AllocateColors(colorPtr); } } /* *---------------------------------------------------------------------- * * FreeColorTable -- * * This function is called when an instance ceases using a color table. * * Results: * None. * * Side effects: * If no other instances are using this color table, a when-idle handler * is registered to free up the color table and the colors allocated for * it. * *---------------------------------------------------------------------- */ static void FreeColorTable( ColorTable *colorPtr, /* Pointer to the color table which is no * longer required by an instance. */ int force) /* Force free to happen immediately. */ { colorPtr->refCount--; if (colorPtr->refCount > 0) { return; } if (force) { if (colorPtr->flags & DISPOSE_PENDING) { Tcl_CancelIdleCall(DisposeColorTable, colorPtr); colorPtr->flags &= ~DISPOSE_PENDING; } DisposeColorTable(colorPtr); } else if (!(colorPtr->flags & DISPOSE_PENDING)) { Tcl_DoWhenIdle(DisposeColorTable, colorPtr); colorPtr->flags |= DISPOSE_PENDING; } } /* *---------------------------------------------------------------------- * * AllocateColors -- * * This function allocates the colors required by a color table, and sets * up the fields in the color table data structure which are used in * dithering. * * Results: * None. * * Side effects: * Colors are allocated from the X server. Fields in the color table data * structure are updated. * *---------------------------------------------------------------------- */ static void AllocateColors( ColorTable *colorPtr) /* Pointer to the color table requiring colors * to be allocated. */ { int i, r, g, b, rMult, mono; int numColors, nRed, nGreen, nBlue; double fr, fg, fb, igam; XColor *colors; unsigned long *pixels; /* * 16-bit intensity value for i/n of full intensity. */ #define CFRAC(i, n) ((i) * 65535 / (n)) /* As for CFRAC, but apply exponent of g. */ #define CGFRAC(i, n, g) ((int)(65535 * pow((double)(i) / (n), (g)))) /* * First parse the palette specification to get the required number of * shades of each primary. */ mono = sscanf(colorPtr->id.palette, "%d/%d/%d", &nRed, &nGreen, &nBlue) <= 1; igam = 1.0 / colorPtr->id.gamma; /* * Each time around this loop, we reduce the number of colors we're trying * to allocate until we succeed in allocating all of the colors we need. */ for (;;) { /* * If we are using 1 bit/pixel, we don't need to allocate any colors * (we just use the foreground and background colors in the GC). */ if (mono && (nRed <= 2)) { colorPtr->flags |= BLACK_AND_WHITE; return; } /* * Calculate the RGB coordinates of the colors we want to allocate and * store them in *colors. */ if ((colorPtr->visualInfo.c_class == DirectColor) || (colorPtr->visualInfo.c_class == TrueColor)) { /* * Direct/True Color: allocate shades of red, green, blue * independently. */ if (mono) { numColors = nGreen = nBlue = nRed; } else { numColors = MAX(MAX(nRed, nGreen), nBlue); } colors = ckalloc(numColors * sizeof(XColor)); for (i = 0; i < numColors; ++i) { if (igam == 1.0) { colors[i].red = CFRAC(i, nRed - 1); colors[i].green = CFRAC(i, nGreen - 1); colors[i].blue = CFRAC(i, nBlue - 1); } else { colors[i].red = CGFRAC(i, nRed - 1, igam); colors[i].green = CGFRAC(i, nGreen - 1, igam); colors[i].blue = CGFRAC(i, nBlue - 1, igam); } } } else { /* * PseudoColor, StaticColor, GrayScale or StaticGray visual: we * have to allocate each color in the color cube separately. */ numColors = (mono) ? nRed: (nRed * nGreen * nBlue); colors = ckalloc(numColors * sizeof(XColor)); if (!mono) { /* * Color display using a PseudoColor or StaticColor visual. */ i = 0; for (r = 0; r < nRed; ++r) { for (g = 0; g < nGreen; ++g) { for (b = 0; b < nBlue; ++b) { if (igam == 1.0) { colors[i].red = CFRAC(r, nRed - 1); colors[i].green = CFRAC(g, nGreen - 1); colors[i].blue = CFRAC(b, nBlue - 1); } else { colors[i].red = CGFRAC(r, nRed - 1, igam); colors[i].green = CGFRAC(g, nGreen - 1, igam); colors[i].blue = CGFRAC(b, nBlue - 1, igam); } i++; } } } } else { /* * Monochrome display - allocate the shades of gray we want. */ for (i = 0; i < numColors; ++i) { if (igam == 1.0) { r = CFRAC(i, numColors - 1); } else { r = CGFRAC(i, numColors - 1, igam); } colors[i].red = colors[i].green = colors[i].blue = r; } } } /* * Now try to allocate the colors we've calculated. */ pixels = ckalloc(numColors * sizeof(unsigned long)); for (i = 0; i < numColors; ++i) { if (!XAllocColor(colorPtr->id.display, colorPtr->id.colormap, &colors[i])) { /* * Can't get all the colors we want in the default colormap; * first try freeing colors from other unused color tables. */ if (!ReclaimColors(&colorPtr->id, numColors - i) || !XAllocColor(colorPtr->id.display, colorPtr->id.colormap, &colors[i])) { /* * Still can't allocate the color. */ break; } } pixels[i] = colors[i].pixel; } /* * If we didn't get all of the colors, reduce the resolution of the * color cube, free the ones we got, and try again. */ if (i >= numColors) { break; } XFreeColors(colorPtr->id.display, colorPtr->id.colormap, pixels, i, 0); ckfree(colors); ckfree(pixels); if (!mono) { if ((nRed == 2) && (nGreen == 2) && (nBlue == 2)) { /* * Fall back to 1-bit monochrome display. */ mono = 1; } else { /* * Reduce the number of shades of each primary to about 3/4 of * the previous value. This should reduce the total number of * colors required to about half the previous value for * PseudoColor displays. */ nRed = (nRed * 3 + 2) / 4; nGreen = (nGreen * 3 + 2) / 4; nBlue = (nBlue * 3 + 2) / 4; } } else { /* * Reduce the number of shades of gray to about 1/2. */ nRed = nRed / 2; } } /* * We have allocated all of the necessary colors: fill in various fields * of the ColorTable record. */ if (!mono) { colorPtr->flags |= COLOR_WINDOW; /* * The following is a hairy hack. We only want to index into the * pixelMap on colormap displays. However, if the display is on * Windows, then we actually want to store the index not the value * since we will be passing the color table into the TkPutImage call. */ #ifndef _WIN32 if ((colorPtr->visualInfo.c_class != DirectColor) && (colorPtr->visualInfo.c_class != TrueColor)) { colorPtr->flags |= MAP_COLORS; } #endif /* _WIN32 */ } colorPtr->numColors = numColors; colorPtr->pixelMap = pixels; /* * Set up quantization tables for dithering. */ rMult = nGreen * nBlue; for (i = 0; i < 256; ++i) { r = (i * (nRed - 1) + 127) / 255; if (mono) { fr = (double) colors[r].red / 65535.0; if (colorPtr->id.gamma != 1.0 ) { fr = pow(fr, colorPtr->id.gamma); } colorPtr->colorQuant[0][i] = (int)(fr * 255.99); colorPtr->redValues[i] = colors[r].pixel; } else { g = (i * (nGreen - 1) + 127) / 255; b = (i * (nBlue - 1) + 127) / 255; if ((colorPtr->visualInfo.c_class == DirectColor) || (colorPtr->visualInfo.c_class == TrueColor)) { colorPtr->redValues[i] = colors[r].pixel & colorPtr->visualInfo.red_mask; colorPtr->greenValues[i] = colors[g].pixel & colorPtr->visualInfo.green_mask; colorPtr->blueValues[i] = colors[b].pixel & colorPtr->visualInfo.blue_mask; } else { r *= rMult; g *= nBlue; colorPtr->redValues[i] = r; colorPtr->greenValues[i] = g; colorPtr->blueValues[i] = b; } fr = (double) colors[r].red / 65535.0; fg = (double) colors[g].green / 65535.0; fb = (double) colors[b].blue / 65535.0; if (colorPtr->id.gamma != 1.0) { fr = pow(fr, colorPtr->id.gamma); fg = pow(fg, colorPtr->id.gamma); fb = pow(fb, colorPtr->id.gamma); } colorPtr->colorQuant[0][i] = (int)(fr * 255.99); colorPtr->colorQuant[1][i] = (int)(fg * 255.99); colorPtr->colorQuant[2][i] = (int)(fb * 255.99); } } ckfree(colors); } /* *---------------------------------------------------------------------- * * DisposeColorTable -- * * Release a color table and its associated resources. * * Results: * None. * * Side effects: * The colors in the argument color table are freed, as is the color * table structure itself. The color table is removed from the hash table * which is used to locate color tables. * *---------------------------------------------------------------------- */ static void DisposeColorTable( ClientData clientData) /* Pointer to the ColorTable whose * colors are to be released. */ { ColorTable *colorPtr = clientData; Tcl_HashEntry *entry; if (colorPtr->pixelMap != NULL) { if (colorPtr->numColors > 0) { XFreeColors(colorPtr->id.display, colorPtr->id.colormap, colorPtr->pixelMap, colorPtr->numColors, 0); Tk_FreeColormap(colorPtr->id.display, colorPtr->id.colormap); } ckfree(colorPtr->pixelMap); } entry = Tcl_FindHashEntry(&imgPhotoColorHash, (char *) &colorPtr->id); if (entry == NULL) { Tcl_Panic("DisposeColorTable couldn't find hash entry"); } Tcl_DeleteHashEntry(entry); ckfree(colorPtr); } /* *---------------------------------------------------------------------- * * ReclaimColors -- * * This function is called to try to free up colors in the colormap used * by a color table. It looks for other color tables with the same * colormap and with a zero live reference count, and frees their colors. * It only does so if there is the possibility of freeing up at least * `numColors' colors. * * Results: * The return value is TRUE if any colors were freed, FALSE otherwise. * * Side effects: * ColorTables which are not currently in use may lose their color * allocations. * *---------------------------------------------------------------------- */ static int ReclaimColors( ColorTableId *id, /* Pointer to information identifying * the color table which needs more colors. */ int numColors) /* Number of colors required. */ { Tcl_HashSearch srch; Tcl_HashEntry *entry; ColorTable *colorPtr; int nAvail = 0; /* * First scan through the color hash table to get an upper bound on how * many colors we might be able to free. */ entry = Tcl_FirstHashEntry(&imgPhotoColorHash, &srch); while (entry != NULL) { colorPtr = Tcl_GetHashValue(entry); if ((colorPtr->id.display == id->display) && (colorPtr->id.colormap == id->colormap) && (colorPtr->liveRefCount == 0 )&& (colorPtr->numColors != 0) && ((colorPtr->id.palette != id->palette) || (colorPtr->id.gamma != id->gamma))) { /* * We could take this guy's colors off him. */ nAvail += colorPtr->numColors; } entry = Tcl_NextHashEntry(&srch); } /* * nAvail is an (over)estimate of the number of colors we could free. */ if (nAvail < numColors) { return 0; } /* * Scan through a second time freeing colors. */ entry = Tcl_FirstHashEntry(&imgPhotoColorHash, &srch); while ((entry != NULL) && (numColors > 0)) { colorPtr = Tcl_GetHashValue(entry); if ((colorPtr->id.display == id->display) && (colorPtr->id.colormap == id->colormap) && (colorPtr->liveRefCount == 0) && (colorPtr->numColors != 0) && ((colorPtr->id.palette != id->palette) || (colorPtr->id.gamma != id->gamma))) { /* * Free the colors that this ColorTable has. */ XFreeColors(colorPtr->id.display, colorPtr->id.colormap, colorPtr->pixelMap, colorPtr->numColors, 0); numColors -= colorPtr->numColors; colorPtr->numColors = 0; ckfree(colorPtr->pixelMap); colorPtr->pixelMap = NULL; } entry = Tcl_NextHashEntry(&srch); } return 1; /* We freed some colors. */ } /* *---------------------------------------------------------------------- * * TkImgDisposeInstance -- * * This function is called to finally free up an instance of a photo * image which is no longer required. * * Results: * None. * * Side effects: * The instance data structure and the resources it references are freed. * *---------------------------------------------------------------------- */ void TkImgDisposeInstance( ClientData clientData) /* Pointer to the instance whose resources are * to be released. */ { PhotoInstance *instancePtr = clientData; PhotoInstance *prevPtr; if (instancePtr->pixels != None) { Tk_FreePixmap(instancePtr->display, instancePtr->pixels); } if (instancePtr->gc != NULL) { Tk_FreeGC(instancePtr->display, instancePtr->gc); } if (instancePtr->imagePtr != NULL) { XDestroyImage(instancePtr->imagePtr); } if (instancePtr->error != NULL) { ckfree(instancePtr->error); } if (instancePtr->colorTablePtr != NULL) { FreeColorTable(instancePtr->colorTablePtr, 1); } if (instancePtr->masterPtr->instancePtr == instancePtr) { instancePtr->masterPtr->instancePtr = instancePtr->nextPtr; } else { for (prevPtr = instancePtr->masterPtr->instancePtr; prevPtr->nextPtr != instancePtr; prevPtr = prevPtr->nextPtr) { /* Empty loop body. */ } prevPtr->nextPtr = instancePtr->nextPtr; } Tk_FreeColormap(instancePtr->display, instancePtr->colormap); ckfree(instancePtr); } /* *---------------------------------------------------------------------- * * TkImgDitherInstance -- * * This function is called to update an area of an instance's pixmap by * dithering the corresponding area of the model. * * Results: * None. * * Side effects: * The instance's pixmap gets updated. * *---------------------------------------------------------------------- */ void TkImgDitherInstance( PhotoInstance *instancePtr, /* The instance to be updated. */ int xStart, int yStart, /* Coordinates of the top-left pixel in the * block to be dithered. */ int width, int height) /* Dimensions of the block to be dithered. */ { PhotoModel *modelPtr = instancePtr->masterPtr; ColorTable *colorPtr = instancePtr->colorTablePtr; XImage *imagePtr; int nLines, bigEndian, i, c, x, y, xEnd, doDithering = 1; int bitsPerPixel, bytesPerLine, lineLength; unsigned char *srcLinePtr; schar *errLinePtr; pixel firstBit, word, mask; /* * Turn dithering off in certain cases where it is not needed (TrueColor, * DirectColor with many colors). */ if ((colorPtr->visualInfo.c_class == DirectColor) || (colorPtr->visualInfo.c_class == TrueColor)) { int nRed, nGreen, nBlue, result; result = sscanf(colorPtr->id.palette, "%d/%d/%d", &nRed, &nGreen, &nBlue); if ((nRed >= 256) && ((result == 1) || ((nGreen >= 256) && (nBlue >= 256)))) { doDithering = 0; } } /* * First work out how many lines to do at a time, then how many bytes * we'll need for pixel storage, and allocate it. */ nLines = (MAX_PIXELS + width - 1) / width; if (nLines < 1) { nLines = 1; } if (nLines > height ) { nLines = height; } imagePtr = instancePtr->imagePtr; if (imagePtr == NULL) { return; /* We must be really tight on memory. */ } bitsPerPixel = imagePtr->bits_per_pixel; bytesPerLine = ((bitsPerPixel * width + 31) >> 3) & ~3; imagePtr->width = width; imagePtr->height = nLines; imagePtr->bytes_per_line = bytesPerLine; /* * TODO: use attemptckalloc() here once we have some strategy for * recovering from the failure. */ imagePtr->data = ckalloc(imagePtr->bytes_per_line * nLines); bigEndian = imagePtr->bitmap_bit_order == MSBFirst; firstBit = bigEndian? (1 << (imagePtr->bitmap_unit - 1)): 1; lineLength = modelPtr->width * 3; srcLinePtr = modelPtr->pix32 + (yStart * modelPtr->width + xStart) * 4; errLinePtr = instancePtr->error + yStart * lineLength + xStart * 3; xEnd = xStart + width; /* * Loop over the image, doing at most nLines lines before updating the * screen image. */ for (; height > 0; height -= nLines) { unsigned char *dstLinePtr = (unsigned char *) imagePtr->data; int yEnd; if (nLines > height) { nLines = height; } yEnd = yStart + nLines; for (y = yStart; y < yEnd; ++y) { unsigned char *srcPtr = srcLinePtr; schar *errPtr = errLinePtr; unsigned char *destBytePtr = dstLinePtr; pixel *destLongPtr = (pixel *) dstLinePtr; if (colorPtr->flags & COLOR_WINDOW) { /* * Color window. We dither the three components independently, * using Floyd-Steinberg dithering, which propagates errors * from the quantization of pixels to the pixels below and to * the right. */ for (x = xStart; x < xEnd; ++x) { int col[3]; if (doDithering) { for (i = 0; i < 3; ++i) { /* * Compute the error propagated into this pixel * for this component. If e[x,y] is the array of * quantization error values, we compute * 7/16 * e[x-1,y] + 1/16 * e[x-1,y-1] * + 5/16 * e[x,y-1] + 3/16 * e[x+1,y-1] * and round it to an integer. * * The expression ((c + 2056) >> 4) - 128 computes * round(c / 16), and works correctly on machines * without a sign-extending right shift. */ c = (x > 0) ? errPtr[-3] * 7: 0; if (y > 0) { if (x > 0) { c += errPtr[-lineLength-3]; } c += errPtr[-lineLength] * 5; if ((x + 1) < modelPtr->width) { c += errPtr[-lineLength+3] * 3; } } /* * Add the propagated error to the value of this * component, quantize it, and store the * quantization error. */ c = ((c + 2056) >> 4) - 128 + *srcPtr++; if (c < 0) { c = 0; } else if (c > 255) { c = 255; } col[i] = colorPtr->colorQuant[i][c]; *errPtr++ = c - col[i]; } } else { /* * Output is virtually continuous in this case, so * don't bother dithering. */ col[0] = *srcPtr++; col[1] = *srcPtr++; col[2] = *srcPtr++; } srcPtr++; /* * Translate the quantized component values into an X * pixel value, and store it in the image. */ i = colorPtr->redValues[col[0]] + colorPtr->greenValues[col[1]] + colorPtr->blueValues[col[2]]; if (colorPtr->flags & MAP_COLORS) { i = colorPtr->pixelMap[i]; } switch (bitsPerPixel) { case NBBY: *destBytePtr++ = i; break; #ifndef _WIN32 /* * This case is not valid for Windows because the * image format is different from the pixel format in * Win32. Eventually we need to fix the image code in * Tk to use the Windows native image ordering. This * would speed up the image code for all of the common * sizes. */ case NBBY * sizeof(pixel): *destLongPtr++ = i; break; #endif default: XPutPixel(imagePtr, x - xStart, y - yStart, (unsigned) i); } } } else if (bitsPerPixel > 1) { /* * Multibit monochrome window. The operation here is similar * to the color window case above, except that there is only * one component. If the model image is in color, use the * luminance computed as * 0.344 * red + 0.5 * green + 0.156 * blue. */ for (x = xStart; x < xEnd; ++x) { c = (x > 0) ? errPtr[-1] * 7: 0; if (y > 0) { if (x > 0) { c += errPtr[-lineLength-1]; } c += errPtr[-lineLength] * 5; if (x + 1 < modelPtr->width) { c += errPtr[-lineLength+1] * 3; } } c = ((c + 2056) >> 4) - 128; if (modelPtr->flags & COLOR_IMAGE) { c += (unsigned) (srcPtr[0] * 11 + srcPtr[1] * 16 + srcPtr[2] * 5 + 16) >> 5; } else { c += srcPtr[0]; } srcPtr += 4; if (c < 0) { c = 0; } else if (c > 255) { c = 255; } i = colorPtr->colorQuant[0][c]; *errPtr++ = c - i; i = colorPtr->redValues[i]; switch (bitsPerPixel) { case NBBY: *destBytePtr++ = i; break; #ifndef _WIN32 /* * This case is not valid for Windows because the * image format is different from the pixel format in * Win32. Eventually we need to fix the image code in * Tk to use the Windows native image ordering. This * would speed up the image code for all of the common * sizes. */ case NBBY * sizeof(pixel): *destLongPtr++ = i; break; #endif default: XPutPixel(imagePtr, x - xStart, y - yStart, (unsigned) i); } } } else { /* * 1-bit monochrome window. This is similar to the multibit * monochrome case above, except that the quantization is * simpler (we only have black = 0 and white = 255), and we * produce an XY-Bitmap. */ word = 0; mask = firstBit; for (x = xStart; x < xEnd; ++x) { /* * If we have accumulated a whole word, store it in the * image and start a new word. */ if (mask == 0) { *destLongPtr++ = word; mask = firstBit; word = 0; } c = (x > 0) ? errPtr[-1] * 7: 0; if (y > 0) { if (x > 0) { c += errPtr[-lineLength-1]; } c += errPtr[-lineLength] * 5; if (x + 1 < modelPtr->width) { c += errPtr[-lineLength+1] * 3; } } c = ((c + 2056) >> 4) - 128; if (modelPtr->flags & COLOR_IMAGE) { c += (unsigned)(srcPtr[0] * 11 + srcPtr[1] * 16 + srcPtr[2] * 5 + 16) >> 5; } else { c += srcPtr[0]; } srcPtr += 4; if (c < 0) { c = 0; } else if (c > 255) { c = 255; } if (c >= 128) { word |= mask; *errPtr++ = c - 255; } else { *errPtr++ = c; } mask = bigEndian? (mask >> 1): (mask << 1); } *destLongPtr = word; } srcLinePtr += modelPtr->width * 4; errLinePtr += lineLength; dstLinePtr += bytesPerLine; } /* * Update the pixmap for this instance with the block of pixels that * we have just computed. */ TkPutImage(colorPtr->pixelMap, colorPtr->numColors, instancePtr->display, instancePtr->pixels, instancePtr->gc, imagePtr, 0, 0, xStart, yStart, (unsigned) width, (unsigned) nLines); yStart = yEnd; } ckfree(imagePtr->data); imagePtr->data = NULL; } /* *---------------------------------------------------------------------- * * TkImgResetDither -- * * This function is called to eliminate the content of a photo instance's * dither error buffer. It's called when the overall image is blanked. * * Results: * None. * * Side effects: * The instance's dither buffer gets cleared. * *---------------------------------------------------------------------- */ void TkImgResetDither( PhotoInstance *instancePtr) { if (instancePtr->error) { memset(instancePtr->error, 0, /*(size_t)*/ (instancePtr->masterPtr->width * instancePtr->masterPtr->height * 3 * sizeof(schar))); } } /* * Local Variables: * mode: c * c-basic-offset: 4 * fill-column: 78 * End: */ 504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304
"""This module tests SyntaxErrors.

Here's an example of the sort of thing that is tested.

>>> def f(x):
...     global x
Traceback (most recent call last):
SyntaxError: name 'x' is parameter and global

The tests are all raise SyntaxErrors.  They were created by checking
each C call that raises SyntaxError.  There are several modules that
raise these exceptions-- ast.c, compile.c, future.c, pythonrun.c, and
symtable.c.

The parser itself outlaws a lot of invalid syntax.  None of these
errors are tested here at the moment.  We should add some tests; since
there are infinitely many programs with invalid syntax, we would need
to be judicious in selecting some.

The compiler generates a synthetic module name for code executed by
doctest.  Since all the code comes from the same module, a suffix like
[1] is appended to the module name, As a consequence, changing the
order of tests in this module means renumbering all the errors after
it.  (Maybe we should enable the ellipsis option for these tests.)

In ast.c, syntax errors are raised by calling ast_error().

Errors from set_context():

>>> obj.None = 1
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> None = 1
Traceback (most recent call last):
SyntaxError: cannot assign to None

>>> obj.True = 1
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> True = 1
Traceback (most recent call last):
SyntaxError: cannot assign to True

>>> (True := 1)
Traceback (most recent call last):
SyntaxError: cannot use assignment expressions with True

>>> obj.__debug__ = 1
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> __debug__ = 1
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> (__debug__ := 1)
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> def __debug__(): pass
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> async def __debug__(): pass
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> class __debug__: pass
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> del __debug__
Traceback (most recent call last):
SyntaxError: cannot delete __debug__

>>> f() = 1
Traceback (most recent call last):
SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?

>>> yield = 1
Traceback (most recent call last):
SyntaxError: assignment to yield expression not possible

>>> del f()
Traceback (most recent call last):
SyntaxError: cannot delete function call

>>> a + 1 = 2
Traceback (most recent call last):
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?

>>> (x for x in x) = 1
Traceback (most recent call last):
SyntaxError: cannot assign to generator expression

>>> 1 = 1
Traceback (most recent call last):
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

>>> "abc" = 1
Traceback (most recent call last):
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

>>> b"" = 1
Traceback (most recent call last):
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

>>> ... = 1
Traceback (most recent call last):
SyntaxError: cannot assign to ellipsis here. Maybe you meant '==' instead of '='?

>>> `1` = 1
Traceback (most recent call last):
SyntaxError: invalid syntax

If the left-hand side of an assignment is a list or tuple, an illegal
expression inside that contain should still cause a syntax error.
This test just checks a couple of cases rather than enumerating all of
them.

>>> (a, "b", c) = (1, 2, 3)
Traceback (most recent call last):
SyntaxError: cannot assign to literal

>>> (a, True, c) = (1, 2, 3)
Traceback (most recent call last):
SyntaxError: cannot assign to True

>>> (a, __debug__, c) = (1, 2, 3)
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> (a, *True, c) = (1, 2, 3)
Traceback (most recent call last):
SyntaxError: cannot assign to True

>>> (a, *__debug__, c) = (1, 2, 3)
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> [a, b, c + 1] = [1, 2, 3]
Traceback (most recent call last):
SyntaxError: cannot assign to expression

>>> [a, b[1], c + 1] = [1, 2, 3]
Traceback (most recent call last):
SyntaxError: cannot assign to expression

>>> [a, b.c.d, c + 1] = [1, 2, 3]
Traceback (most recent call last):
SyntaxError: cannot assign to expression

>>> a if 1 else b = 1
Traceback (most recent call last):
SyntaxError: cannot assign to conditional expression

>>> a = 42 if True
Traceback (most recent call last):
SyntaxError: expected 'else' after 'if' expression

>>> a = (42 if True)
Traceback (most recent call last):
SyntaxError: expected 'else' after 'if' expression

>>> a = [1, 42 if True, 4]
Traceback (most recent call last):
SyntaxError: expected 'else' after 'if' expression

>>> x = 1 if 1 else pass
Traceback (most recent call last):
SyntaxError: expected expression after 'else', but statement is given

>>> x = pass if 1 else 1
Traceback (most recent call last):
SyntaxError: expected expression before 'if', but statement is given

>>> x = pass if 1 else pass
Traceback (most recent call last):
SyntaxError: expected expression before 'if', but statement is given

>>> if True:
...     print("Hello"
...
... if 2:
...    print(123))
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> True = True = 3
Traceback (most recent call last):
SyntaxError: cannot assign to True

>>> x = y = True = z = 3
Traceback (most recent call last):
SyntaxError: cannot assign to True

>>> x = y = yield = 1
Traceback (most recent call last):
SyntaxError: assignment to yield expression not possible

>>> a, b += 1, 2
Traceback (most recent call last):
SyntaxError: 'tuple' is an illegal expression for augmented assignment

>>> (a, b) += 1, 2
Traceback (most recent call last):
SyntaxError: 'tuple' is an illegal expression for augmented assignment

>>> [a, b] += 1, 2
Traceback (most recent call last):
SyntaxError: 'list' is an illegal expression for augmented assignment

Invalid targets in `for` loops and `with` statements should also
produce a specialized error message

>>> for a() in b: pass
Traceback (most recent call last):
SyntaxError: cannot assign to function call

>>> for (a, b()) in b: pass
Traceback (most recent call last):
SyntaxError: cannot assign to function call

>>> for [a, b()] in b: pass
Traceback (most recent call last):
SyntaxError: cannot assign to function call

>>> for (*a, b, c+1) in b: pass
Traceback (most recent call last):
SyntaxError: cannot assign to expression

>>> for (x, *(y, z.d())) in b: pass
Traceback (most recent call last):
SyntaxError: cannot assign to function call

>>> for a, b() in c: pass
Traceback (most recent call last):
SyntaxError: cannot assign to function call

>>> for a, b, (c + 1, d()): pass
Traceback (most recent call last):
SyntaxError: cannot assign to expression

>>> for i < (): pass
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> for a, b
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> with a as b(): pass
Traceback (most recent call last):
SyntaxError: cannot assign to function call

>>> with a as (b, c()): pass
Traceback (most recent call last):
SyntaxError: cannot assign to function call

>>> with a as [b, c()]: pass
Traceback (most recent call last):
SyntaxError: cannot assign to function call

>>> with a as (*b, c, d+1): pass
Traceback (most recent call last):
SyntaxError: cannot assign to expression

>>> with a as (x, *(y, z.d())): pass
Traceback (most recent call last):
SyntaxError: cannot assign to function call

>>> with a as b, c as d(): pass
Traceback (most recent call last):
SyntaxError: cannot assign to function call

>>> with a as b
Traceback (most recent call last):
SyntaxError: expected ':'

>>> p = p =
Traceback (most recent call last):
SyntaxError: invalid syntax

Comprehensions without 'in' keyword:

>>> [x for x if range(1)]
Traceback (most recent call last):
SyntaxError: 'in' expected after for-loop variables

>>> tuple(x for x if range(1))
Traceback (most recent call last):
SyntaxError: 'in' expected after for-loop variables

>>> [x for x() in a]
Traceback (most recent call last):
SyntaxError: cannot assign to function call

>>> [x for a, b, (c + 1, d()) in y]
Traceback (most recent call last):
SyntaxError: cannot assign to expression

>>> [x for a, b, (c + 1, d()) if y]
Traceback (most recent call last):
SyntaxError: 'in' expected after for-loop variables

>>> [x for x+1 in y]
Traceback (most recent call last):
SyntaxError: cannot assign to expression

>>> [x for x+1, x() in y]
Traceback (most recent call last):
SyntaxError: cannot assign to expression

Comprehensions creating tuples without parentheses
should produce a specialized error message:

>>> [x,y for x,y in range(100)]
Traceback (most recent call last):
SyntaxError: did you forget parentheses around the comprehension target?

>>> {x,y for x,y in range(100)}
Traceback (most recent call last):
SyntaxError: did you forget parentheses around the comprehension target?

# Incorrectly closed strings

>>> "The interesting object "The important object" is very important"
Traceback (most recent call last):
SyntaxError: invalid syntax. Is this intended to be part of the string?

# Missing commas in literals collections should not
# produce special error messages regarding missing
# parentheses, but about missing commas instead

>>> [1, 2 3]
Traceback (most recent call last):
SyntaxError: invalid syntax. Perhaps you forgot a comma?

>>> {1, 2 3}
Traceback (most recent call last):
SyntaxError: invalid syntax. Perhaps you forgot a comma?

>>> {1:2, 2:5 3:12}
Traceback (most recent call last):
SyntaxError: invalid syntax. Perhaps you forgot a comma?

>>> (1, 2 3)
Traceback (most recent call last):
SyntaxError: invalid syntax. Perhaps you forgot a comma?

# Make sure soft keywords constructs don't raise specialized
# errors regarding missing commas or other spezialiced errors

>>> match x:
...     y = 3
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> match x:
...     case y:
...        3 $ 3
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> match x:
...     case $:
...        ...
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> match ...:
...     case {**rest, "key": value}:
...        ...
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> match ...:
...     case {**_}:
...        ...
Traceback (most recent call last):
SyntaxError: invalid syntax

# But prefixes of soft keywords should
# still raise specialized errors

>>> (mat x)
Traceback (most recent call last):
SyntaxError: invalid syntax. Perhaps you forgot a comma?

From compiler_complex_args():

>>> def f(None=1):
...     pass
Traceback (most recent call last):
SyntaxError: invalid syntax

From ast_for_arguments():

>>> def f(x, y=1, z):
...     pass
Traceback (most recent call last):
SyntaxError: parameter without a default follows parameter with a default

>>> def f(x, /, y=1, z):
...     pass
Traceback (most recent call last):
SyntaxError: parameter without a default follows parameter with a default

>>> def f(x, None):
...     pass
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> def f(*None):
...     pass
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> def f(**None):
...     pass
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> def foo(/,a,b=,c):
...    pass
Traceback (most recent call last):
SyntaxError: at least one argument must precede /

>>> def foo(a,/,/,b,c):
...    pass
Traceback (most recent call last):
SyntaxError: / may appear only once

>>> def foo(a,/,a1,/,b,c):
...    pass
Traceback (most recent call last):
SyntaxError: / may appear only once

>>> def foo(a=1,/,/,*b,/,c):
...    pass
Traceback (most recent call last):
SyntaxError: / may appear only once

>>> def foo(a,/,a1=1,/,b,c):
...    pass
Traceback (most recent call last):
SyntaxError: / may appear only once

>>> def foo(a,*b,c,/,d,e):
...    pass
Traceback (most recent call last):
SyntaxError: / must be ahead of *

>>> def foo(a=1,*b,c=3,/,d,e):
...    pass
Traceback (most recent call last):
SyntaxError: / must be ahead of *

>>> def foo(a,*b=3,c):
...    pass
Traceback (most recent call last):
SyntaxError: var-positional argument cannot have default value

>>> def foo(a,*b: int=,c):
...    pass
Traceback (most recent call last):
SyntaxError: var-positional argument cannot have default value

>>> def foo(a,**b=3):
...    pass
Traceback (most recent call last):
SyntaxError: var-keyword argument cannot have default value

>>> def foo(a,**b: int=3):
...    pass
Traceback (most recent call last):
SyntaxError: var-keyword argument cannot have default value

>>> def foo(a,*a, b, **c, d):
...    pass
Traceback (most recent call last):
SyntaxError: arguments cannot follow var-keyword argument

>>> def foo(a,*a, b, **c, d=4):
...    pass
Traceback (most recent call last):
SyntaxError: arguments cannot follow var-keyword argument

>>> def foo(a,*a, b, **c, *d):
...    pass
Traceback (most recent call last):
SyntaxError: arguments cannot follow var-keyword argument

>>> def foo(a,*a, b, **c, **d):
...    pass
Traceback (most recent call last):
SyntaxError: arguments cannot follow var-keyword argument

>>> def foo(a=1,/,**b,/,c):
...    pass
Traceback (most recent call last):
SyntaxError: arguments cannot follow var-keyword argument

>>> def foo(*b,*d):
...    pass
Traceback (most recent call last):
SyntaxError: * argument may appear only once

>>> def foo(a,*b,c,*d,*e,c):
...    pass
Traceback (most recent call last):
SyntaxError: * argument may appear only once

>>> def foo(a,b,/,c,*b,c,*d,*e,c):
...    pass
Traceback (most recent call last):
SyntaxError: * argument may appear only once

>>> def foo(a,b,/,c,*b,c,*d,**e):
...    pass
Traceback (most recent call last):
SyntaxError: * argument may appear only once

>>> def foo(a=1,/*,b,c):
...    pass
Traceback (most recent call last):
SyntaxError: expected comma between / and *

>>> def foo(a=1,d=,c):
...    pass
Traceback (most recent call last):
SyntaxError: expected default value expression

>>> def foo(a,d=,c):
...    pass
Traceback (most recent call last):
SyntaxError: expected default value expression

>>> def foo(a,d: int=,c):
...    pass
Traceback (most recent call last):
SyntaxError: expected default value expression

>>> lambda /,a,b,c: None
Traceback (most recent call last):
SyntaxError: at least one argument must precede /

>>> lambda a,/,/,b,c: None
Traceback (most recent call last):
SyntaxError: / may appear only once

>>> lambda a,/,a1,/,b,c: None
Traceback (most recent call last):
SyntaxError: / may appear only once

>>> lambda a=1,/,/,*b,/,c: None
Traceback (most recent call last):
SyntaxError: / may appear only once

>>> lambda a,/,a1=1,/,b,c: None
Traceback (most recent call last):
SyntaxError: / may appear only once

>>> lambda a,*b,c,/,d,e: None
Traceback (most recent call last):
SyntaxError: / must be ahead of *

>>> lambda a=1,*b,c=3,/,d,e: None
Traceback (most recent call last):
SyntaxError: / must be ahead of *

>>> lambda a=1,/*,b,c: None
Traceback (most recent call last):
SyntaxError: expected comma between / and *

>>> lambda a,*b=3,c: None
Traceback (most recent call last):
SyntaxError: var-positional argument cannot have default value

>>> lambda a,**b=3: None
Traceback (most recent call last):
SyntaxError: var-keyword argument cannot have default value

>>> lambda a, *a, b, **c, d: None
Traceback (most recent call last):
SyntaxError: arguments cannot follow var-keyword argument

>>> lambda a,*a, b, **c, d=4: None
Traceback (most recent call last):
SyntaxError: arguments cannot follow var-keyword argument

>>> lambda a,*a, b, **c, *d: None
Traceback (most recent call last):
SyntaxError: arguments cannot follow var-keyword argument

>>> lambda a,*a, b, **c, **d: None
Traceback (most recent call last):
SyntaxError: arguments cannot follow var-keyword argument

>>> lambda a=1,/,**b,/,c: None
Traceback (most recent call last):
SyntaxError: arguments cannot follow var-keyword argument

>>> lambda *b,*d: None
Traceback (most recent call last):
SyntaxError: * argument may appear only once

>>> lambda a,*b,c,*d,*e,c: None
Traceback (most recent call last):
SyntaxError: * argument may appear only once

>>> lambda a,b,/,c,*b,c,*d,*e,c: None
Traceback (most recent call last):
SyntaxError: * argument may appear only once

>>> lambda a,b,/,c,*b,c,*d,**e: None
Traceback (most recent call last):
SyntaxError: * argument may appear only once

>>> lambda a=1,d=,c: None
Traceback (most recent call last):
SyntaxError: expected default value expression

>>> lambda a,d=,c: None
Traceback (most recent call last):
SyntaxError: expected default value expression

>>> lambda a,d=3,c: None
Traceback (most recent call last):
SyntaxError: parameter without a default follows parameter with a default

>>> lambda a,/,d=3,c: None
Traceback (most recent call last):
SyntaxError: parameter without a default follows parameter with a default

>>> import ast; ast.parse('''
... def f(
...     *, # type: int
...     a, # type: int
... ):
...     pass
... ''', type_comments=True)
Traceback (most recent call last):
SyntaxError: bare * has associated type comment


From ast_for_funcdef():

>>> def None(x):
...     pass
Traceback (most recent call last):
SyntaxError: invalid syntax


From ast_for_call():

>>> def f(it, *varargs, **kwargs):
...     return list(it)
>>> L = range(10)
>>> f(x for x in L)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> f(x for x in L, 1)
Traceback (most recent call last):
SyntaxError: Generator expression must be parenthesized
>>> f(x for x in L, y=1)
Traceback (most recent call last):
SyntaxError: Generator expression must be parenthesized
>>> f(x for x in L, *[])
Traceback (most recent call last):
SyntaxError: Generator expression must be parenthesized
>>> f(x for x in L, **{})
Traceback (most recent call last):
SyntaxError: Generator expression must be parenthesized
>>> f(L, x for x in L)
Traceback (most recent call last):
SyntaxError: Generator expression must be parenthesized
>>> f(x for x in L, y for y in L)
Traceback (most recent call last):
SyntaxError: Generator expression must be parenthesized
>>> f(x for x in L,)
Traceback (most recent call last):
SyntaxError: Generator expression must be parenthesized
>>> f((x for x in L), 1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> class C(x for x in L):
...     pass
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> def g(*args, **kwargs):
...     print(args, sorted(kwargs.items()))
>>> g(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
...   20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
...   38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
...   56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
...   74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
...   92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
...   108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
...   122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
...   136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
...   150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
...   164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
...   178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
...   192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
...   206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
...   220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
...   234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
...   248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
...   262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275,
...   276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
...   290, 291, 292, 293, 294, 295, 296, 297, 298, 299)  # doctest: +ELLIPSIS
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 297, 298, 299) []

>>> g(a000=0, a001=1, a002=2, a003=3, a004=4, a005=5, a006=6, a007=7, a008=8,
...   a009=9, a010=10, a011=11, a012=12, a013=13, a014=14, a015=15, a016=16,
...   a017=17, a018=18, a019=19, a020=20, a021=21, a022=22, a023=23, a024=24,
...   a025=25, a026=26, a027=27, a028=28, a029=29, a030=30, a031=31, a032=32,
...   a033=33, a034=34, a035=35, a036=36, a037=37, a038=38, a039=39, a040=40,
...   a041=41, a042=42, a043=43, a044=44, a045=45, a046=46, a047=47, a048=48,
...   a049=49, a050=50, a051=51, a052=52, a053=53, a054=54, a055=55, a056=56,
...   a057=57, a058=58, a059=59, a060=60, a061=61, a062=62, a063=63, a064=64,
...   a065=65, a066=66, a067=67, a068=68, a069=69, a070=70, a071=71, a072=72,
...   a073=73, a074=74, a075=75, a076=76, a077=77, a078=78, a079=79, a080=80,
...   a081=81, a082=82, a083=83, a084=84, a085=85, a086=86, a087=87, a088=88,
...   a089=89, a090=90, a091=91, a092=92, a093=93, a094=94, a095=95, a096=96,
...   a097=97, a098=98, a099=99, a100=100, a101=101, a102=102, a103=103,
...   a104=104, a105=105, a106=106, a107=107, a108=108, a109=109, a110=110,
...   a111=111, a112=112, a113=113, a114=114, a115=115, a116=116, a117=117,
...   a118=118, a119=119, a120=120, a121=121, a122=122, a123=123, a124=124,
...   a125=125, a126=126, a127=127, a128=128, a129=129, a130=130, a131=131,
...   a132=132, a133=133, a134=134, a135=135, a136=136, a137=137, a138=138,
...   a139=139, a140=140, a141=141, a142=142, a143=143, a144=144, a145=145,
...   a146=146, a147=147, a148=148, a149=149, a150=150, a151=151, a152=152,
...   a153=153, a154=154, a155=155, a156=156, a157=157, a158=158, a159=159,
...   a160=160, a161=161, a162=162, a163=163, a164=164, a165=165, a166=166,
...   a167=167, a168=168, a169=169, a170=170, a171=171, a172=172, a173=173,
...   a174=174, a175=175, a176=176, a177=177, a178=178, a179=179, a180=180,
...   a181=181, a182=182, a183=183, a184=184, a185=185, a186=186, a187=187,
...   a188=188, a189=189, a190=190, a191=191, a192=192, a193=193, a194=194,
...   a195=195, a196=196, a197=197, a198=198, a199=199, a200=200, a201=201,
...   a202=202, a203=203, a204=204, a205=205, a206=206, a207=207, a208=208,
...   a209=209, a210=210, a211=211, a212=212, a213=213, a214=214, a215=215,
...   a216=216, a217=217, a218=218, a219=219, a220=220, a221=221, a222=222,
...   a223=223, a224=224, a225=225, a226=226, a227=227, a228=228, a229=229,
...   a230=230, a231=231, a232=232, a233=233, a234=234, a235=235, a236=236,
...   a237=237, a238=238, a239=239, a240=240, a241=241, a242=242, a243=243,
...   a244=244, a245=245, a246=246, a247=247, a248=248, a249=249, a250=250,
...   a251=251, a252=252, a253=253, a254=254, a255=255, a256=256, a257=257,
...   a258=258, a259=259, a260=260, a261=261, a262=262, a263=263, a264=264,
...   a265=265, a266=266, a267=267, a268=268, a269=269, a270=270, a271=271,
...   a272=272, a273=273, a274=274, a275=275, a276=276, a277=277, a278=278,
...   a279=279, a280=280, a281=281, a282=282, a283=283, a284=284, a285=285,
...   a286=286, a287=287, a288=288, a289=289, a290=290, a291=291, a292=292,
...   a293=293, a294=294, a295=295, a296=296, a297=297, a298=298, a299=299)
...  # doctest: +ELLIPSIS
() [('a000', 0), ('a001', 1), ('a002', 2), ..., ('a298', 298), ('a299', 299)]

>>> class C:
...     def meth(self, *args):
...         return args
>>> obj = C()
>>> obj.meth(
...   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
...   20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
...   38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
...   56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
...   74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
...   92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
...   108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
...   122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
...   136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
...   150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
...   164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
...   178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
...   192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
...   206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
...   220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
...   234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
...   248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
...   262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275,
...   276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
...   290, 291, 292, 293, 294, 295, 296, 297, 298, 299)  # doctest: +ELLIPSIS
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 297, 298, 299)

>>> f(lambda x: x[0] = 3)
Traceback (most recent call last):
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

# Check that this error doesn't trigger for names:
>>> f(a={x: for x in {}})
Traceback (most recent call last):
SyntaxError: invalid syntax

The grammar accepts any test (basically, any expression) in the
keyword slot of a call site.  Test a few different options.

>>> f(x()=2)
Traceback (most recent call last):
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
>>> f(a or b=1)
Traceback (most recent call last):
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
>>> f(x.y=1)
Traceback (most recent call last):
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
>>> f((x)=2)
Traceback (most recent call last):
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
>>> f(True=1)
Traceback (most recent call last):
SyntaxError: cannot assign to True
>>> f(False=1)
Traceback (most recent call last):
SyntaxError: cannot assign to False
>>> f(None=1)
Traceback (most recent call last):
SyntaxError: cannot assign to None
>>> f(__debug__=1)
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__
>>> __debug__: int
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__
>>> x.__debug__: int
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__
>>> f(a=)
Traceback (most recent call last):
SyntaxError: expected argument value expression
>>> f(a, b, c=)
Traceback (most recent call last):
SyntaxError: expected argument value expression
>>> f(a, b, c=, d)
Traceback (most recent call last):
SyntaxError: expected argument value expression
>>> f(*args=[0])
Traceback (most recent call last):
SyntaxError: cannot assign to iterable argument unpacking
>>> f(a, b, *args=[0])
Traceback (most recent call last):
SyntaxError: cannot assign to iterable argument unpacking
>>> f(**kwargs={'a': 1})
Traceback (most recent call last):
SyntaxError: cannot assign to keyword argument unpacking
>>> f(a, b, *args, **kwargs={'a': 1})
Traceback (most recent call last):
SyntaxError: cannot assign to keyword argument unpacking


More set_context():

>>> (x for x in x) += 1
Traceback (most recent call last):
SyntaxError: 'generator expression' is an illegal expression for augmented assignment
>>> None += 1
Traceback (most recent call last):
SyntaxError: 'None' is an illegal expression for augmented assignment
>>> __debug__ += 1
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__
>>> f() += 1
Traceback (most recent call last):
SyntaxError: 'function call' is an illegal expression for augmented assignment


Test control flow in finally

continue in for loop under finally should be ok.

    >>> def test():
    ...     try:
    ...         pass
    ...     finally:
    ...         for abc in range(10):
    ...             continue
    ...     print(abc)
    >>> test()
    9

break in for loop under finally should be ok.

    >>> def test():
    ...     try:
    ...         pass
    ...     finally:
    ...         for abc in range(10):
    ...             break
    ...     print(abc)
    >>> test()
    0

return in function under finally should be ok.

    >>> def test():
    ...     try:
    ...         pass
    ...     finally:
    ...         def f():
    ...             return 42
    ...     print(f())
    >>> test()
    42

combine for loop and function def

return in function under finally should be ok.

    >>> def test():
    ...     try:
    ...         pass
    ...     finally:
    ...         for i in range(10):
    ...             def f():
    ...                 return 42
    ...     print(f())
    >>> test()
    42

    >>> def test():
    ...     try:
    ...         pass
    ...     finally:
    ...         def f():
    ...             for i in range(10):
    ...                 return 42
    ...     print(f())
    >>> test()
    42

A continue outside loop should not be allowed.

    >>> def foo():
    ...     try:
    ...         continue
    ...     finally:
    ...         pass
    Traceback (most recent call last):
      ...
    SyntaxError: 'continue' not properly in loop

There is one test for a break that is not in a loop.  The compiler
uses a single data structure to keep track of try-finally and loops,
so we need to be sure that a break is actually inside a loop.  If it
isn't, there should be a syntax error.

   >>> try:
   ...     print(1)
   ...     break
   ...     print(2)
   ... finally:
   ...     print(3)
   Traceback (most recent call last):
     ...
   SyntaxError: 'break' outside loop

elif can't come after an else.

    >>> if a % 2 == 0:
    ...     pass
    ... else:
    ...     pass
    ... elif a % 2 == 1:
    ...     pass
    Traceback (most recent call last):
      ...
    SyntaxError: 'elif' block follows an 'else' block

Misuse of the nonlocal and global statement can lead to a few unique syntax errors.

   >>> def f():
   ...     print(x)
   ...     global x
   Traceback (most recent call last):
     ...
   SyntaxError: name 'x' is used prior to global declaration

   >>> def f():
   ...     x = 1
   ...     global x
   Traceback (most recent call last):
     ...
   SyntaxError: name 'x' is assigned to before global declaration

   >>> def f(x):
   ...     global x
   Traceback (most recent call last):
     ...
   SyntaxError: name 'x' is parameter and global

   >>> def f():
   ...     x = 1
   ...     def g():
   ...         print(x)
   ...         nonlocal x
   Traceback (most recent call last):
     ...
   SyntaxError: name 'x' is used prior to nonlocal declaration

   >>> def f():
   ...     x = 1
   ...     def g():
   ...         x = 2
   ...         nonlocal x
   Traceback (most recent call last):
     ...
   SyntaxError: name 'x' is assigned to before nonlocal declaration

   >>> def f(x):
   ...     nonlocal x
   Traceback (most recent call last):
     ...
   SyntaxError: name 'x' is parameter and nonlocal

   >>> def f():
   ...     global x
   ...     nonlocal x
   Traceback (most recent call last):
     ...
   SyntaxError: name 'x' is nonlocal and global

   >>> def f():
   ...     nonlocal x
   Traceback (most recent call last):
     ...
   SyntaxError: no binding for nonlocal 'x' found

From SF bug #1705365
   >>> nonlocal x
   Traceback (most recent call last):
     ...
   SyntaxError: nonlocal declaration not allowed at module level

From https://bugs.python.org/issue25973
   >>> class A:
   ...     def f(self):
   ...         nonlocal __x
   Traceback (most recent call last):
     ...
   SyntaxError: no binding for nonlocal '_A__x' found


This tests assignment-context; there was a bug in Python 2.5 where compiling
a complex 'if' (one with 'elif') would fail to notice an invalid suite,
leading to spurious errors.

   >>> if 1:
   ...   x() = 1
   ... elif 1:
   ...   pass
   Traceback (most recent call last):
     ...
   SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?

   >>> if 1:
   ...   pass
   ... elif 1:
   ...   x() = 1
   Traceback (most recent call last):
     ...
   SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?

   >>> if 1:
   ...   x() = 1
   ... elif 1:
   ...   pass
   ... else:
   ...   pass
   Traceback (most recent call last):
     ...
   SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?

   >>> if 1:
   ...   pass
   ... elif 1:
   ...   x() = 1
   ... else:
   ...   pass
   Traceback (most recent call last):
     ...
   SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?

   >>> if 1:
   ...   pass
   ... elif 1:
   ...   pass
   ... else:
   ...   x() = 1
   Traceback (most recent call last):
     ...
   SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?

Missing ':' before suites:

   >>> def f()
   ...     pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> def f[T]()
   ...     pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> class A
   ...     pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> class A[T]
   ...     pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> class A[T]()
   ...     pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> class R&D:
   ...     pass
   Traceback (most recent call last):
   SyntaxError: invalid syntax

   >>> if 1
   ...   pass
   ... elif 1:
   ...   pass
   ... else:
   ...   x() = 1
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> if 1:
   ...   pass
   ... elif 1
   ...   pass
   ... else:
   ...   x() = 1
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> if 1:
   ...   pass
   ... elif 1:
   ...   pass
   ... else
   ...   x() = 1
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> for x in range(10)
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> for x in range 10:
   ...   pass
   Traceback (most recent call last):
   SyntaxError: invalid syntax

   >>> while True
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> with blech as something
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> with blech
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> with blech, block as something
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> with blech, block as something, bluch
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> with (blech as something)
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> with (blech)
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> with (blech, block as something)
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> with (blech, block as something, bluch)
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> with block ad something:
   ...   pass
   Traceback (most recent call last):
   SyntaxError: invalid syntax. Did you mean 'and'?

   >>> try
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> try:
   ...   pass
   ... except
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> match x
   ...   case list():
   ...       pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> match x x:
   ...   case list():
   ...       pass
   Traceback (most recent call last):
   SyntaxError: invalid syntax

   >>> match x:
   ...   case list()
   ...       pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> match x:
   ...   case [y] if y > 0
   ...       pass
   Traceback (most recent call last):
   SyntaxError: expected ':'

   >>> match x:
   ...   case a, __debug__, b:
   ...       pass
   Traceback (most recent call last):
   SyntaxError: cannot assign to __debug__

   >>> match x:
   ...   case a, b, *__debug__:
   ...       pass
   Traceback (most recent call last):
   SyntaxError: cannot assign to __debug__

   >>> match x:
   ...   case Foo(a, __debug__=1, b=2):
   ...       pass
   Traceback (most recent call last):
   SyntaxError: cannot assign to __debug__

   >>> if x = 3:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

   >>> while x = 3:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

   >>> if x.a = 3:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?

   >>> while x.a = 3:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?


Missing parens after function definition

   >>> def f:
   Traceback (most recent call last):
   SyntaxError: expected '('

   >>> async def f:
   Traceback (most recent call last):
   SyntaxError: expected '('

   >>> def f -> int:
   Traceback (most recent call last):
   SyntaxError: expected '('

   >>> async def f -> int:  # type: int
   Traceback (most recent call last):
   SyntaxError: expected '('

   >>> async def f[T]:
   Traceback (most recent call last):
   SyntaxError: expected '('

   >>> def f[T] -> str:
   Traceback (most recent call last):
   SyntaxError: expected '('

Parenthesized arguments in function definitions

   >>> def f(x, (y, z), w):
   ...    pass
   Traceback (most recent call last):
   SyntaxError: Function parameters cannot be parenthesized

   >>> def f((x, y, z, w)):
   ...    pass
   Traceback (most recent call last):
   SyntaxError: Function parameters cannot be parenthesized

   >>> def f(x, (y, z, w)):
   ...    pass
   Traceback (most recent call last):
   SyntaxError: Function parameters cannot be parenthesized

   >>> def f((x, y, z), w):
   ...    pass
   Traceback (most recent call last):
   SyntaxError: Function parameters cannot be parenthesized

   >>> lambda x, (y, z), w: None
   Traceback (most recent call last):
   SyntaxError: Lambda expression parameters cannot be parenthesized

   >>> lambda (x, y, z, w): None
   Traceback (most recent call last):
   SyntaxError: Lambda expression parameters cannot be parenthesized

   >>> lambda x, (y, z, w): None
   Traceback (most recent call last):
   SyntaxError: Lambda expression parameters cannot be parenthesized

   >>> lambda (x, y, z), w: None
   Traceback (most recent call last):
   SyntaxError: Lambda expression parameters cannot be parenthesized

Custom error messages for try blocks that are not followed by except/finally

   >>> try:
   ...    x = 34
   ...
   Traceback (most recent call last):
   SyntaxError: expected 'except' or 'finally' block

Custom error message for __debug__ as exception variable

   >>> try:
   ...    pass
   ... except TypeError as __debug__:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: cannot assign to __debug__

Custom error message for try block mixing except and except*

   >>> try:
   ...    pass
   ... except TypeError:
   ...    pass
   ... except* ValueError:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: cannot have both 'except' and 'except*' on the same 'try'

   >>> try:
   ...    pass
   ... except* TypeError:
   ...    pass
   ... except ValueError:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: cannot have both 'except' and 'except*' on the same 'try'

   >>> try:
   ...    pass
   ... except TypeError:
   ...    pass
   ... except TypeError:
   ...    pass
   ... except* ValueError:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: cannot have both 'except' and 'except*' on the same 'try'

   >>> try:
   ...    pass
   ... except* TypeError:
   ...    pass
   ... except* TypeError:
   ...    pass
   ... except ValueError:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: cannot have both 'except' and 'except*' on the same 'try'

Better error message for using `except as` with not a name:

   >>> try:
   ...    pass
   ... except TypeError as obj.attr:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: cannot use except statement with attribute

   >>> try:
   ...    pass
   ... except TypeError as obj[1]:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: cannot use except statement with subscript

   >>> try:
   ...    pass
   ... except* TypeError as (obj, name):
   ...    pass
   Traceback (most recent call last):
   SyntaxError: cannot use except* statement with tuple

   >>> try:
   ...    pass
   ... except* TypeError as 1:
   ...    pass
   Traceback (most recent call last):
   SyntaxError: cannot use except* statement with literal

Regression tests for gh-133999:

   >>> try: pass
   ... except TypeError as name: raise from None
   Traceback (most recent call last):
   SyntaxError: invalid syntax

   >>> try: pass
   ... except* TypeError as name: raise from None
   Traceback (most recent call last):
   SyntaxError: invalid syntax

   >>> match 1:
   ...     case 1 | 2 as abc: raise from None
   Traceback (most recent call last):
   SyntaxError: invalid syntax

Ensure that early = are not matched by the parser as invalid comparisons
   >>> f(2, 4, x=34); 1 $ 2
   Traceback (most recent call last):
   SyntaxError: invalid syntax

   >>> dict(x=34); x $ y
   Traceback (most recent call last):
   SyntaxError: invalid syntax

   >>> dict(x=34, (x for x in range 10), 1); x $ y
   Traceback (most recent call last):
   SyntaxError: invalid syntax

   >>> dict(x=34, x=1, y=2); x $ y
   Traceback (most recent call last):
   SyntaxError: invalid syntax

Incomplete dictionary literals

   >>> {1:2, 3:4, 5}
   Traceback (most recent call last):
   SyntaxError: ':' expected after dictionary key

   >>> {1:2, 3:4, 5:}
   Traceback (most recent call last):
   SyntaxError: expression expected after dictionary key and ':'

   >>> {1: *12+1, 23: 1}
   Traceback (most recent call last):
   SyntaxError: cannot use a starred expression in a dictionary value

   >>> {1: *12+1}
   Traceback (most recent call last):
   SyntaxError: cannot use a starred expression in a dictionary value

   >>> {1: 23, 1: *12+1}
   Traceback (most recent call last):
   SyntaxError: cannot use a starred expression in a dictionary value

   >>> {1:}
   Traceback (most recent call last):
   SyntaxError: expression expected after dictionary key and ':'

   # Ensure that the error is not raised for syntax errors that happen after sets

   >>> {1} $
   Traceback (most recent call last):
   SyntaxError: invalid syntax

   # Ensure that the error is not raised for invalid expressions

   >>> {1: 2, 3: foo(,), 4: 5}
   Traceback (most recent call last):
   SyntaxError: invalid syntax

   >>> {1: $, 2: 3}
   Traceback (most recent call last):
   SyntaxError: invalid syntax

Specialized indentation errors:

   >>> while condition:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'while' statement on line 1

   >>> for x in range(10):
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'for' statement on line 1

   >>> for x in range(10):
   ...     pass
   ... else:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'else' statement on line 3

   >>> async for x in range(10):
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'for' statement on line 1

   >>> async for x in range(10):
   ...     pass
   ... else:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'else' statement on line 3

   >>> if something:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'if' statement on line 1

   >>> if something:
   ...     pass
   ... elif something_else:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'elif' statement on line 3

   >>> if something:
   ...     pass
   ... elif something_else:
   ...     pass
   ... else:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'else' statement on line 5

   >>> try:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'try' statement on line 1

   >>> try:
   ...     something()
   ... except:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'except' statement on line 3

   >>> try:
   ...     something()
   ... except A:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'except' statement on line 3

   >>> try:
   ...     something()
   ... except* A:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'except*' statement on line 3

   >>> try:
   ...     something()
   ... except A:
   ...     pass
   ... finally:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'finally' statement on line 5

   >>> try:
   ...     something()
   ... except* A:
   ...     pass
   ... finally:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'finally' statement on line 5

   >>> with A:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'with' statement on line 1

   >>> with A as a, B as b:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'with' statement on line 1

   >>> with (A as a, B as b):
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'with' statement on line 1

   >>> async with A:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'with' statement on line 1

   >>> async with A as a, B as b:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'with' statement on line 1

   >>> async with (A as a, B as b):
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'with' statement on line 1

   >>> def foo(x, /, y, *, z=2):
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after function definition on line 1

   >>> def foo[T](x, /, y, *, z=2):
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after function definition on line 1

   >>> class Blech(A):
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after class definition on line 1

   >>> class Blech[T](A):
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after class definition on line 1

   >>> class C(__debug__=42): ...
   Traceback (most recent call last):
   SyntaxError: cannot assign to __debug__

   >>> class Meta(type):
   ...     def __new__(*args, **kwargs):
   ...         pass

   >>> class C(metaclass=Meta, __debug__=42):
   ...     pass
   Traceback (most recent call last):
   SyntaxError: cannot assign to __debug__

   >>> match something:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'match' statement on line 1

   >>> match something:
   ...     case []:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'case' statement on line 2

   >>> match something:
   ...     case []:
   ...         ...
   ...     case {}:
   ... pass
   Traceback (most recent call last):
   IndentationError: expected an indented block after 'case' statement on line 4

Make sure that the old "raise X, Y[, Z]" form is gone:
   >>> raise X, Y
   Traceback (most recent call last):
     ...
   SyntaxError: invalid syntax
   >>> raise X, Y, Z
   Traceback (most recent call last):
     ...
   SyntaxError: invalid syntax

Check that an multiple exception types with missing parentheses
raise a custom exception only when using 'as'

   >>> try:
   ...   pass
   ... except A, B, C as blech:
   ...   pass
   Traceback (most recent call last):
   SyntaxError: multiple exception types must be parenthesized when using 'as'

   >>> try:
   ...   pass
   ... except A, B, C as blech:
   ...   pass
   ... finally:
   ...   pass
   Traceback (most recent call last):
   SyntaxError: multiple exception types must be parenthesized when using 'as'


   >>> try:
   ...   pass
   ... except* A, B, C as blech:
   ...   pass
   Traceback (most recent call last):
   SyntaxError: multiple exception types must be parenthesized when using 'as'

   >>> try:
   ...   pass
   ... except* A, B, C as blech:
   ...   pass
   ... finally:
   ...   pass
   Traceback (most recent call last):
   SyntaxError: multiple exception types must be parenthesized when using 'as'

Custom exception for 'except*' without an exception type

   >>> try:
   ...   pass
   ... except* A as a:
   ...   pass
   ... except*:
   ...   pass
   Traceback (most recent call last):
   SyntaxError: expected one or more exception types

Check custom exceptions for keywords with typos

>>> fur a in b:
...   pass
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'for'?

>>> for a in b:
...   pass
... elso:
...   pass
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'else'?

>>> whille True:
...   pass
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'while'?

>>> while True:
...   pass
... elso:
...   pass
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'else'?

>>> iff x > 5:
...   pass
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'if'?

>>> if x:
...   pass
... elseif y:
...   pass
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'elif'?

>>> if x:
...   pass
... elif y:
...   pass
... elso:
...   pass
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'else'?

>>> tyo:
...   pass
... except y:
...   pass
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'try'?

>>> classe MyClass:
...   pass
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'class'?

>>> impor math
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'import'?

>>> form x import y
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'from'?

>>> defn calculate_sum(a, b):
...   return a + b
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'def'?

>>> def foo():
...   returm result
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'return'?

>>> lamda x: x ** 2
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'lambda'?

>>> def foo():
...   yeld i
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'yield'?

>>> def foo():
...   globel counter
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'global'?

>>> frum math import sqrt
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'from'?

>>> asynch def fetch_data():
...   pass
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'async'?

>>> async def foo():
...   awaid fetch_data()
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'await'?

>>> raisee ValueError("Error")
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'raise'?

>>> [
... x for x
... in range(3)
... of x
... ]
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'if'?

>>> [
... 123 fur x
... in range(3)
... if x
... ]
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'for'?


>>> for x im n:
...     pass
Traceback (most recent call last):
SyntaxError: invalid syntax. Did you mean 'in'?

>>> f(a=23, a=234)
Traceback (most recent call last):
   ...
SyntaxError: keyword argument repeated: a

>>> {1, 2, 3} = 42
Traceback (most recent call last):
SyntaxError: cannot assign to set display here. Maybe you meant '==' instead of '='?

>>> {1: 2, 3: 4} = 42
Traceback (most recent call last):
SyntaxError: cannot assign to dict literal here. Maybe you meant '==' instead of '='?

>>> f'{x}' = 42
Traceback (most recent call last):
SyntaxError: cannot assign to f-string expression here. Maybe you meant '==' instead of '='?

>>> f'{x}-{y}' = 42
Traceback (most recent call last):
SyntaxError: cannot assign to f-string expression here. Maybe you meant '==' instead of '='?

>>> ub''
Traceback (most recent call last):
SyntaxError: 'u' and 'b' prefixes are incompatible

>>> bu"привет"
Traceback (most recent call last):
SyntaxError: 'u' and 'b' prefixes are incompatible

>>> ur''
Traceback (most recent call last):
SyntaxError: 'u' and 'r' prefixes are incompatible

>>> ru"\t"
Traceback (most recent call last):
SyntaxError: 'u' and 'r' prefixes are incompatible

>>> uf'{1 + 1}'
Traceback (most recent call last):
SyntaxError: 'u' and 'f' prefixes are incompatible

>>> fu""
Traceback (most recent call last):
SyntaxError: 'u' and 'f' prefixes are incompatible

>>> ut'{1}'
Traceback (most recent call last):
SyntaxError: 'u' and 't' prefixes are incompatible

>>> tu"234"
Traceback (most recent call last):
SyntaxError: 'u' and 't' prefixes are incompatible

>>> bf'{x!r}'
Traceback (most recent call last):
SyntaxError: 'b' and 'f' prefixes are incompatible

>>> fb"text"
Traceback (most recent call last):
SyntaxError: 'b' and 'f' prefixes are incompatible

>>> bt"text"
Traceback (most recent call last):
SyntaxError: 'b' and 't' prefixes are incompatible

>>> tb''
Traceback (most recent call last):
SyntaxError: 'b' and 't' prefixes are incompatible

>>> tf"{0.3:.02f}"
Traceback (most recent call last):
SyntaxError: 'f' and 't' prefixes are incompatible

>>> ft'{x=}'
Traceback (most recent call last):
SyntaxError: 'f' and 't' prefixes are incompatible

>>> tfu"{x=}"
Traceback (most recent call last):
SyntaxError: 'u' and 'f' prefixes are incompatible

>>> turf"{x=}"
Traceback (most recent call last):
SyntaxError: 'u' and 'r' prefixes are incompatible

>>> burft"{x=}"
Traceback (most recent call last):
SyntaxError: 'u' and 'b' prefixes are incompatible

>>> brft"{x=}"
Traceback (most recent call last):
SyntaxError: 'b' and 'f' prefixes are incompatible

>>> t'{x}' = 42
Traceback (most recent call last):
SyntaxError: cannot assign to t-string expression here. Maybe you meant '==' instead of '='?

>>> t'{x}-{y}' = 42
Traceback (most recent call last):
SyntaxError: cannot assign to t-string expression here. Maybe you meant '==' instead of '='?

>>> (x, y, z=3, d, e)
Traceback (most recent call last):
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

>>> [x, y, z=3, d, e]
Traceback (most recent call last):
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

>>> [z=3]
Traceback (most recent call last):
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

>>> {x, y, z=3, d, e}
Traceback (most recent call last):
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

>>> {z=3}
Traceback (most recent call last):
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

>>> from t import x,
Traceback (most recent call last):
SyntaxError: trailing comma not allowed without surrounding parentheses

>>> from t import x,y,
Traceback (most recent call last):
SyntaxError: trailing comma not allowed without surrounding parentheses

>>> import a from b
Traceback (most recent call last):
SyntaxError: Did you mean to use 'from ... import ...' instead?

>>> import a.y.z from b.y.z
Traceback (most recent call last):
SyntaxError: Did you mean to use 'from ... import ...' instead?

>>> import a from b as bar
Traceback (most recent call last):
SyntaxError: Did you mean to use 'from ... import ...' instead?

>>> import a.y.z from b.y.z as bar
Traceback (most recent call last):
SyntaxError: Did you mean to use 'from ... import ...' instead?

>>> import a, b,c from b
Traceback (most recent call last):
SyntaxError: Did you mean to use 'from ... import ...' instead?

>>> import a.y.z, b.y.z, c.y.z from b.y.z
Traceback (most recent call last):
SyntaxError: Did you mean to use 'from ... import ...' instead?

>>> import a,b,c from b as bar
Traceback (most recent call last):
SyntaxError: Did you mean to use 'from ... import ...' instead?

>>> import a.y.z, b.y.z, c.y.z from b.y.z as bar
Traceback (most recent call last):
SyntaxError: Did you mean to use 'from ... import ...' instead?

>>> import __debug__
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> import a as __debug__
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> import a.b.c as __debug__
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> from a import __debug__
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> from a import b as __debug__
Traceback (most recent call last):
SyntaxError: cannot assign to __debug__

>>> import a as b.c
Traceback (most recent call last):
SyntaxError: cannot use attribute as import target

>>> import a.b as (a, b)
Traceback (most recent call last):
SyntaxError: cannot use tuple as import target

>>> import a, a.b as 1
Traceback (most recent call last):
SyntaxError: cannot use literal as import target

>>> import a.b as 'a', a
Traceback (most recent call last):
SyntaxError: cannot use literal as import target

>>> from a import (b as c.d)
Traceback (most recent call last):
SyntaxError: cannot use attribute as import target

>>> from a import b as 1
Traceback (most recent call last):
SyntaxError: cannot use literal as import target

>>> from a import (
...   b as f())
Traceback (most recent call last):
SyntaxError: cannot use function call as import target

>>> from a import (
...   b as [],
... )
Traceback (most recent call last):
SyntaxError: cannot use list as import target

>>> from a import (
...   b,
...   c as ()
... )
Traceback (most recent call last):
SyntaxError: cannot use tuple as import target

>>> from a import b, с as d[e]
Traceback (most recent call last):
SyntaxError: cannot use subscript as import target

>>> from a import с as d[e], b
Traceback (most recent call last):
SyntaxError: cannot use subscript as import target

# Check that we dont raise the "trailing comma" error if there is more
# input to the left of the valid part that we parsed.

>>> from t import x,y, and 3
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> from i import
Traceback (most recent call last):
SyntaxError: Expected one or more names after 'import'

>>> from .. import
Traceback (most recent call last):
SyntaxError: Expected one or more names after 'import'

>>> import
Traceback (most recent call last):
SyntaxError: Expected one or more names after 'import'

>>> (): int
Traceback (most recent call last):
SyntaxError: only single target (not tuple) can be annotated
>>> []: int
Traceback (most recent call last):
SyntaxError: only single target (not list) can be annotated
>>> (()): int
Traceback (most recent call last):
SyntaxError: only single target (not tuple) can be annotated
>>> ([]): int
Traceback (most recent call last):
SyntaxError: only single target (not list) can be annotated

# 'not' after operators:

>>> 3 + not 3
Traceback (most recent call last):
SyntaxError: 'not' after an operator must be parenthesized

>>> 3 * not 3
Traceback (most recent call last):
SyntaxError: 'not' after an operator must be parenthesized

>>> + not 3
Traceback (most recent call last):
SyntaxError: 'not' after an operator must be parenthesized

>>> - not 3
Traceback (most recent call last):
SyntaxError: 'not' after an operator must be parenthesized

>>> ~ not 3
Traceback (most recent call last):
SyntaxError: 'not' after an operator must be parenthesized

>>> 3 + - not 3
Traceback (most recent call last):
SyntaxError: 'not' after an operator must be parenthesized

>>> 3 + not -1
Traceback (most recent call last):
SyntaxError: 'not' after an operator must be parenthesized

# Check that we don't introduce misleading errors
>>> not 1 */ 2
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> not 1 +
Traceback (most recent call last):
SyntaxError: invalid syntax

>>> not + 1 +
Traceback (most recent call last):
SyntaxError: invalid syntax

Corner-cases that used to fail to raise the correct error:

    >>> def f(*, x=lambda __debug__:0): pass
    Traceback (most recent call last):
    SyntaxError: cannot assign to __debug__

    >>> def f(*args:(lambda __debug__:0)): pass
    Traceback (most recent call last):
    SyntaxError: cannot assign to __debug__

    >>> def f(**kwargs:(lambda __debug__:0)): pass
    Traceback (most recent call last):
    SyntaxError: cannot assign to __debug__

    >>> with (lambda *:0): pass
    Traceback (most recent call last):
    SyntaxError: named arguments must follow bare *

Corner-cases that used to crash:

    >>> def f(**__debug__): pass
    Traceback (most recent call last):
    SyntaxError: cannot assign to __debug__

    >>> def f(*xx, __debug__): pass
    Traceback (most recent call last):
    SyntaxError: cannot assign to __debug__

    >>> import ä £
    Traceback (most recent call last):
    SyntaxError: invalid character '£' (U+00A3)

  Invalid pattern matching constructs:

    >>> match ...:
    ...   case 42 as _:
    ...     ...
    Traceback (most recent call last):
    SyntaxError: cannot use '_' as a target

    >>> match ...:
    ...   case 42 as 1+2+4:
    ...     ...
    Traceback (most recent call last):
    SyntaxError: cannot use expression as pattern target

    >>> match ...:
    ...   case 42 as a.b:
    ...     ...
    Traceback (most recent call last):
    SyntaxError: cannot use attribute as pattern target

    >>> match ...:
    ...   case 42 as (a, b):
    ...     ...
    Traceback (most recent call last):
    SyntaxError: cannot use tuple as pattern target

    >>> match ...:
    ...   case 42 as (a + 1):
    ...     ...
    Traceback (most recent call last):
    SyntaxError: cannot use expression as pattern target

    >>> match ...:
    ...   case (32 as x) | (42 as a()):
    ...     ...
    Traceback (most recent call last):
    SyntaxError: cannot use function call as pattern target

    >>> match ...:
    ...   case Foo(z=1, y=2, x):
    ...     ...
    Traceback (most recent call last):
    SyntaxError: positional patterns follow keyword patterns

    >>> match ...:
    ...   case Foo(a, z=1, y=2, x):
    ...     ...
    Traceback (most recent call last):
    SyntaxError: positional patterns follow keyword patterns

    >>> match ...:
    ...   case Foo(z=1, x, y=2):
    ...     ...
    Traceback (most recent call last):
    SyntaxError: positional patterns follow keyword patterns

    >>> match ...:
    ...   case C(a=b, c, d=e, f, g=h, i, j=k, ...):
    ...     ...
    Traceback (most recent call last):
    SyntaxError: positional patterns follow keyword patterns

Uses of the star operator which should fail:

A[:*b]

    >>> A[:*b]
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax
    >>> A[:(*b)]
    Traceback (most recent call last):
        ...
    SyntaxError: cannot use starred expression here
    >>> A[:*b] = 1
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax
    >>> del A[:*b]
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax

A[*b:]

    >>> A[*b:]
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax
    >>> A[(*b):]
    Traceback (most recent call last):
        ...
    SyntaxError: cannot use starred expression here
    >>> A[*b:] = 1
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax
    >>> del A[*b:]
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax

A[*b:*b]

    >>> A[*b:*b]
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax
    >>> A[(*b:*b)]
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax
    >>> A[*b:*b] = 1
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax
    >>> del A[*b:*b]
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax

A[*(1:2)]

    >>> A[*(1:2)]
    Traceback (most recent call last):
        ...
    SyntaxError: Invalid star expression
    >>> A[*(1:2)] = 1
    Traceback (most recent call last):
        ...
    SyntaxError: Invalid star expression
    >>> del A[*(1:2)]
    Traceback (most recent call last):
        ...
    SyntaxError: Invalid star expression

A[*:] and A[:*]

    >>> A[*:]
    Traceback (most recent call last):
        ...
    SyntaxError: Invalid star expression
    >>> A[:*]
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax

A[*]

    >>> A[*]
    Traceback (most recent call last):
        ...
    SyntaxError: Invalid star expression

A[**]

    >>> A[**]
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax

A[**b]

    >>> A[**b]
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax
    >>> A[**b] = 1
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax
    >>> del A[**b]
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax

def f(x: *b)

    >>> def f6(x: *b): pass
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax
    >>> def f7(x: *b = 1): pass
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax

**kwargs: *a

    >>> def f8(**kwargs: *a): pass
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax

x: *b

    >>> x: *b
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax
    >>> x: *b = 1
    Traceback (most recent call last):
        ...
    SyntaxError: invalid syntax

Invalid bytes literals:

   >>> b"Ā"
   Traceback (most recent call last):
      ...
       b"Ā"
        ^^^
   SyntaxError: bytes can only contain ASCII literal characters

   >>> b"абвгде"
   Traceback (most recent call last):
      ...
       b"абвгде"
        ^^^^^^^^
   SyntaxError: bytes can only contain ASCII literal characters

   >>> b"abc ъющый"  # first 3 letters are ascii
   Traceback (most recent call last):
      ...
       b"abc ъющый"
        ^^^^^^^^^^^
   SyntaxError: bytes can only contain ASCII literal characters

Invalid expressions in type scopes:

   >>> type A[] = int
   Traceback (most recent call last):
   ...
   SyntaxError: Type parameter list cannot be empty

   >>> class A[]: ...
   Traceback (most recent call last):
   ...
   SyntaxError: Type parameter list cannot be empty

   >>> def some[](): ...
   Traceback (most recent call last):
   ...
   SyntaxError: Type parameter list cannot be empty

   >>> def some[]()
   Traceback (most recent call last):
   ...
   SyntaxError: Type parameter list cannot be empty

   >>> async def some[]:  # type: int
   Traceback (most recent call last):
   ...
   SyntaxError: Type parameter list cannot be empty

   >>> def f[T: (x:=3)](): pass
   Traceback (most recent call last):
      ...
   SyntaxError: named expression cannot be used within a TypeVar bound

   >>> def f[T: ((x:= 3), int)](): pass
   Traceback (most recent call last):
      ...
   SyntaxError: named expression cannot be used within a TypeVar constraint

   >>> def f[T = ((x:=3))](): pass
   Traceback (most recent call last):
      ...
   SyntaxError: named expression cannot be used within a TypeVar default

   >>> async def f[T: (x:=3)](): pass
   Traceback (most recent call last):
      ...
   SyntaxError: named expression cannot be used within a TypeVar bound

   >>> async def f[T: ((x:= 3), int)](): pass
   Traceback (most recent call last):
      ...
   SyntaxError: named expression cannot be used within a TypeVar constraint

   >>> async def f[T = ((x:=3))](): pass
   Traceback (most recent call last):
      ...
   SyntaxError: named expression cannot be used within a TypeVar default

   >>> type A[T: (x:=3)] = int
   Traceback (most recent call last):
      ...
   SyntaxError: named expression cannot be used within a TypeVar bound

   >>> type A[T: ((x:= 3), int)] = int
   Traceback (most recent call last):
      ...
   SyntaxError: named expression cannot be used within a TypeVar constraint

   >>> type A[T = ((x:=3))] = int
   Traceback (most recent call last):
      ...
   SyntaxError: named expression cannot be used within a TypeVar default

   >>> def f[T: (yield)](): pass
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVar bound

   >>> def f[T: (int, (yield))](): pass
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVar constraint

   >>> def f[T = (yield)](): pass
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVar default

   >>> def f[*Ts = (yield)](): pass
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVarTuple default

   >>> def f[**P = [(yield), int]](): pass
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a ParamSpec default

   >>> type A[T: (yield 3)] = int
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVar bound

   >>> type A[T: (int, (yield 3))] = int
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVar constraint

   >>> type A[T = (yield 3)] = int
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVar default

   >>> type A[T: (await 3)] = int
   Traceback (most recent call last):
      ...
   SyntaxError: await expression cannot be used within a TypeVar bound

   >>> type A[T: (yield from [])] = int
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVar bound

   >>> class A[T: (yield 3)]: pass
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVar bound

   >>> class A[T: (int, (yield 3))]: pass
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVar constraint

   >>> class A[T = (yield)]: pass
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVar default

   >>> class A[*Ts = (yield)]: pass
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a TypeVarTuple default

   >>> class A[**P = [(yield), int]]: pass
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a ParamSpec default

   >>> type A = (x := 3)
   Traceback (most recent call last):
      ...
   SyntaxError: named expression cannot be used within a type alias

   >>> type A = (yield 3)
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a type alias

   >>> type A = (await 3)
   Traceback (most recent call last):
      ...
   SyntaxError: await expression cannot be used within a type alias

   >>> type A = (yield from [])
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within a type alias

   >>> type __debug__ = int
   Traceback (most recent call last):
   SyntaxError: cannot assign to __debug__

   >>> class A[__debug__]: pass
   Traceback (most recent call last):
   SyntaxError: cannot assign to __debug__

   >>> class A[T]((x := 3)): ...
   Traceback (most recent call last):
      ...
   SyntaxError: named expression cannot be used within the definition of a generic

   >>> class A[T]((yield 3)): ...
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within the definition of a generic

   >>> class A[T]((await 3)): ...
   Traceback (most recent call last):
      ...
   SyntaxError: await expression cannot be used within the definition of a generic

   >>> class A[T]((yield from [])): ...
   Traceback (most recent call last):
      ...
   SyntaxError: yield expression cannot be used within the definition of a generic

    >>> f(**x, *y)
    Traceback (most recent call last):
    SyntaxError: iterable argument unpacking follows keyword argument unpacking

    >>> f(**x, *)
    Traceback (most recent call last):
    SyntaxError: Invalid star expression

    >>> f(x, *:)
    Traceback (most recent call last):
    SyntaxError: Invalid star expression

    >>> f(x, *)
    Traceback (most recent call last):
    SyntaxError: Invalid star expression

    >>> f(x = 5, *)
    Traceback (most recent call last):
    SyntaxError: Invalid star expression

    >>> f(x = 5, *:)
    Traceback (most recent call last):
    SyntaxError: Invalid star expression
"""

import re
import doctest
import textwrap
import unittest

from test import support

class SyntaxWarningTest(unittest.TestCase):
    def check_warning(self, code, errtext, filename="<testcase>", mode="exec"):
        """Check that compiling code raises SyntaxWarning with errtext.

        errtest is a regular expression that must be present in the
        text of the warning raised.
        """
        with self.assertWarnsRegex(SyntaxWarning, errtext):
            compile(code, filename, mode)

    def test_return_in_finally(self):
        source = textwrap.dedent("""
            def f():
                try:
                    pass
                finally:
                    return 42
            """)
        self.check_warning(source, "'return' in a 'finally' block")

        source = textwrap.dedent("""
            def f():
                try:
                    pass
                finally:
                    try:
                        return 42
                    except:
                        pass
            """)
        self.check_warning(source, "'return' in a 'finally' block")

        source = textwrap.dedent("""
            def f():
                try:
                    pass
                finally:
                    try:
                        pass
                    except:
                        return 42
            """)
        self.check_warning(source, "'return' in a 'finally' block")

    def test_break_and_continue_in_finally(self):
        for kw in ('break', 'continue'):

            source = textwrap.dedent(f"""
                for abc in range(10):
                    try:
                        pass
                    finally:
                        {kw}
                """)
            self.check_warning(source, f"'{kw}' in a 'finally' block")

            source = textwrap.dedent(f"""
                for abc in range(10):
                    try:
                        pass
                    finally:
                        try:
                            {kw}
                        except:
                            pass
                """)
            self.check_warning(source, f"'{kw}' in a 'finally' block")

            source = textwrap.dedent(f"""
                for abc in range(10):
                    try:
                        pass
                    finally:
                        try:
                            pass
                        except:
                            {kw}
                """)
            self.check_warning(source, f"'{kw}' in a 'finally' block")


class SyntaxErrorTestCase(unittest.TestCase):

    def _check_error(self, code, errtext,
                     filename="<testcase>", mode="exec", subclass=None,
                     lineno=None, offset=None, end_lineno=None, end_offset=None):
        """Check that compiling code raises SyntaxError with errtext.

        errtest is a regular expression that must be present in the
        text of the exception raised.  If subclass is specified it
        is the expected subclass of SyntaxError (e.g. IndentationError).
        """
        try:
            compile(code, filename, mode)
        except SyntaxError as err:
            if subclass and not isinstance(err, subclass):
                self.fail("SyntaxError is not a %s" % subclass.__name__)
            mo = re.search(errtext, str(err))
            if mo is None:
                self.fail("SyntaxError did not contain %r" % (errtext,))
            self.assertEqual(err.filename, filename)
            if lineno is not None:
                self.assertEqual(err.lineno, lineno)
            if offset is not None:
                self.assertEqual(err.offset, offset)
            if end_lineno is not None:
                self.assertEqual(err.end_lineno, end_lineno)
            if end_offset is not None:
                self.assertEqual(err.end_offset, end_offset)

        else:
            self.fail("compile() did not raise SyntaxError")

    def test_expression_with_assignment(self):
        self._check_error(
            "print(end1 + end2 = ' ')",
            'expression cannot contain assignment, perhaps you meant "=="?',
            offset=7
        )

    def test_curly_brace_after_primary_raises_immediately(self):
        self._check_error("f{}", "invalid syntax", mode="single")

    def test_assign_call(self):
        self._check_error("f() = 1", "assign")

    def test_assign_del(self):
        self._check_error("del (,)", "invalid syntax")
        self._check_error("del 1", "cannot delete literal")
        self._check_error("del (1, 2)", "cannot delete literal")
        self._check_error("del None", "cannot delete None")
        self._check_error("del *x", "cannot delete starred")
        self._check_error("del (*x)", "cannot use starred expression")
        self._check_error("del (*x,)", "cannot delete starred")
        self._check_error("del [*x,]", "cannot delete starred")
        self._check_error("del f()", "cannot delete function call")
        self._check_error("del f(a, b)", "cannot delete function call")
        self._check_error("del o.f()", "cannot delete function call")
        self._check_error("del a[0]()", "cannot delete function call")
        self._check_error("del x, f()", "cannot delete function call")
        self._check_error("del f(), x", "cannot delete function call")
        self._check_error("del [a, b, ((c), (d,), e.f())]", "cannot delete function call")
        self._check_error("del (a if True else b)", "cannot delete conditional")
        self._check_error("del +a", "cannot delete expression")
        self._check_error("del a, +b", "cannot delete expression")
        self._check_error("del a + b", "cannot delete expression")
        self._check_error("del (a + b, c)", "cannot delete expression")
        self._check_error("del (c[0], a + b)", "cannot delete expression")
        self._check_error("del a.b.c + 2", "cannot delete expression")
        self._check_error("del a.b.c[0] + 2", "cannot delete expression")
        self._check_error("del (a, b, (c, d.e.f + 2))", "cannot delete expression")
        self._check_error("del [a, b, (c, d.e.f[0] + 2)]", "cannot delete expression")
        self._check_error("del (a := 5)", "cannot delete named expression")
        # We don't have a special message for this, but make sure we don't
        # report "cannot delete name"
        self._check_error("del a += b", "invalid syntax")

    def test_global_param_err_first(self):
        source = """if 1:
            def error(a):
                global a  # SyntaxError
            def error2():
                b = 1
                global b  # SyntaxError
            """
        self._check_error(source, "parameter and global", lineno=3)

    def test_nonlocal_param_err_first(self):
        source = """if 1:
            def error(a):
                nonlocal a  # SyntaxError
            def error2():
                b = 1
                global b  # SyntaxError
            """
        self._check_error(source, "parameter and nonlocal", lineno=3)

    def test_yield_outside_function(self):
        self._check_error("if 0: yield",                "outside function")
        self._check_error("if 0: yield\nelse:  x=1",    "outside function")
        self._check_error("if 1: pass\nelse: yield",    "outside function")
        self._check_error("while 0: yield",             "outside function")
        self._check_error("while 0: yield\nelse:  x=1", "outside function")
        self._check_error("class C:\n  if 0: yield",    "outside function")
        self._check_error("class C:\n  if 1: pass\n  else: yield",
                          "outside function")
        self._check_error("class C:\n  while 0: yield", "outside function")
        self._check_error("class C:\n  while 0: yield\n  else:  x = 1",
                          "outside function")

    def test_return_outside_function(self):
        self._check_error("if 0: return",                "outside function")
        self._check_error("if 0: return\nelse:  x=1",    "outside function")
        self._check_error("if 1: pass\nelse: return",    "outside function")
        self._check_error("while 0: return",             "outside function")
        self._check_error("class C:\n  if 0: return",    "outside function")
        self._check_error("class C:\n  while 0: return", "outside function")
        self._check_error("class C:\n  while 0: return\n  else:  x=1",
                          "outside function")
        self._check_error("class C:\n  if 0: return\n  else: x= 1",
                          "outside function")
        self._check_error("class C:\n  if 1: pass\n  else: return",
                          "outside function")

    def test_break_outside_loop(self):
        msg = "outside loop"
        self._check_error("break", msg, lineno=1)
        self._check_error("if 0: break", msg, lineno=1)
        self._check_error("if 0: break\nelse:  x=1", msg, lineno=1)
        self._check_error("if 1: pass\nelse: break", msg, lineno=2)
        self._check_error("class C:\n  if 0: break", msg, lineno=2)
        self._check_error("class C:\n  if 1: pass\n  else: break",
                          msg, lineno=3)
        self._check_error("with object() as obj:\n break",
                          msg, lineno=2)

    def test_continue_outside_loop(self):
        msg = "not properly in loop"
        self._check_error("if 0: continue", msg, lineno=1)
        self._check_error("if 0: continue\nelse:  x=1", msg, lineno=1)
        self._check_error("if 1: pass\nelse: continue", msg, lineno=2)
        self._check_error("class C:\n  if 0: continue", msg, lineno=2)
        self._check_error("class C:\n  if 1: pass\n  else: continue",
                          msg, lineno=3)
        self._check_error("with object() as obj:\n    continue",
                          msg, lineno=2)

    def test_unexpected_indent(self):
        self._check_error("foo()\n bar()\n", "unexpected indent",
                          subclass=IndentationError)

    def test_no_indent(self):
        self._check_error("if 1:\nfoo()", "expected an indented block",
                          subclass=IndentationError)

    def test_bad_outdent(self):
        self._check_error("if 1:\n  foo()\n bar()",
                          "unindent does not match .* level",
                          subclass=IndentationError)

    def test_kwargs_last(self):
        self._check_error("int(base=10, '2')",
                          "positional argument follows keyword argument")

    def test_kwargs_last2(self):
        self._check_error("int(**{'base': 10}, '2')",
                          "positional argument follows "
                          "keyword argument unpacking")

    def test_kwargs_last3(self):
        self._check_error("int(**{'base': 10}, *['2'])",
                          "iterable argument unpacking follows "
                          "keyword argument unpacking")

    def test_generator_in_function_call(self):
        self._check_error("foo(x,    y for y in range(3) for z in range(2) if z    , p)",
                          "Generator expression must be parenthesized",
                          lineno=1, end_lineno=1, offset=11, end_offset=53)

    def test_except_then_except_star(self):
        self._check_error("try: pass\nexcept ValueError: pass\nexcept* TypeError: pass",
                          r"cannot have both 'except' and 'except\*' on the same 'try'",
                          lineno=3, end_lineno=3, offset=1, end_offset=8)

    def test_except_star_then_except(self):
        self._check_error("try: pass\nexcept* ValueError: pass\nexcept TypeError: pass",
                          r"cannot have both 'except' and 'except\*' on the same 'try'",
                          lineno=3, end_lineno=3, offset=1, end_offset=7)

    def test_empty_line_after_linecont(self):
        # See issue-40847
        s = r"""\
pass
        \

pass
"""
        try:
            compile(s, '<string>', 'exec')
        except SyntaxError:
            self.fail("Empty line after a line continuation character is valid.")

        # See issue-46091
        s1 = r"""\
def fib(n):
    \
'''Print a Fibonacci series up to n.'''
    \
a, b = 0, 1
"""
        s2 = r"""\
def fib(n):
    '''Print a Fibonacci series up to n.'''
    a, b = 0, 1
"""
        try:
            compile(s1, '<string>', 'exec')
            compile(s2, '<string>', 'exec')
        except SyntaxError:
            self.fail("Indented statement over multiple lines is valid")

    def test_continuation_bad_indentation(self):
        # Check that code that breaks indentation across multiple lines raises a syntax error

        code = r"""\
if x:
    y = 1
  \
  foo = 1
        """

        self.assertRaises(IndentationError, exec, code)

    @support.cpython_only
    def test_disallowed_type_param_names(self):
        # See gh-128632

        self._check_error(f"class A[__classdict__]: pass",
                        f"reserved name '__classdict__' cannot be used for type parameter")
        self._check_error(f"def f[__classdict__](): pass",
                        f"reserved name '__classdict__' cannot be used for type parameter")
        self._check_error(f"type T[__classdict__] = tuple[__classdict__]",
                        f"reserved name '__classdict__' cannot be used for type parameter")

        # These compilations are here to make sure __class__, __classcell__ and __classdictcell__
        # don't break in the future like __classdict__ did in this case.
        for name in ('__class__', '__classcell__', '__classdictcell__'):
            compile(f"""
class A:
    class B[{name}]: pass
                """, "<testcase>", mode="exec")

    @support.cpython_only
    def test_nested_named_except_blocks(self):
        code = ""
        for i in range(12):
            code += f"{'    '*i}try:\n"
            code += f"{'    '*(i+1)}raise Exception\n"
            code += f"{'    '*i}except Exception as e:\n"
        code += f"{' '*4*12}pass"
        self._check_error(code, "too many statically nested blocks")

    @support.cpython_only
    def test_with_statement_many_context_managers(self):
        # See gh-113297

        def get_code(n):
            code = textwrap.dedent("""
                def bug():
                    with (
                    a
                """)
            for i in range(n):
                code += f"    as a{i}, a\n"
            code += "): yield a"
            return code

        CO_MAXBLOCKS = 21  # static nesting limit of the compiler
        MAX_MANAGERS = CO_MAXBLOCKS - 1  # One for the StopIteration block

        for n in range(MAX_MANAGERS):
            with self.subTest(f"within range: {n=}"):
                compile(get_code(n), "<string>", "exec")

        for n in range(MAX_MANAGERS, MAX_MANAGERS + 5):
            with self.subTest(f"out of range: {n=}"):
                self._check_error(get_code(n), "too many statically nested blocks")

    @support.cpython_only
    def test_async_with_statement_many_context_managers(self):
        # See gh-116767

        def get_code(n):
            code = [ textwrap.dedent("""
                async def bug():
                    async with (
                    a
                """) ]
            for i in range(n):
                code.append(f"    as a{i}, a\n")
            code.append("): yield a")
            return "".join(code)

        CO_MAXBLOCKS = 21  # static nesting limit of the compiler
        MAX_MANAGERS = CO_MAXBLOCKS - 1  # One for the StopIteration block

        for n in range(MAX_MANAGERS):
            with self.subTest(f"within range: {n=}"):
                compile(get_code(n), "<string>", "exec")

        for n in range(MAX_MANAGERS, MAX_MANAGERS + 5):
            with self.subTest(f"out of range: {n=}"):
                self._check_error(get_code(n), "too many statically nested blocks")

    def test_barry_as_flufl_with_syntax_errors(self):
        # The "barry_as_flufl" rule can produce some "bugs-at-a-distance" if
        # is reading the wrong token in the presence of syntax errors later
        # in the file. See bpo-42214 for more information.
        code = """
def func1():
    if a != b:
        raise ValueError

def func2():
    try
        return 1
    finally:
        pass
"""
        self._check_error(code, "expected ':'")

    def test_invalid_line_continuation_error_position(self):
        self._check_error(r"a = 3 \ 4",
                          "unexpected character after line continuation character",
                          lineno=1, offset=8)
        self._check_error('1,\\#\n2',
                          "unexpected character after line continuation character",
                          lineno=1, offset=4)
        self._check_error('\nfgdfgf\n1,\\#\n2\n',
                          "unexpected character after line continuation character",
                          lineno=3, offset=4)

    def test_invalid_line_continuation_left_recursive(self):
        # Check bpo-42218: SyntaxErrors following left-recursive rules
        # (t_primary_raw in this case) need to be tested explicitly
        self._check_error("A.\u018a\\ ",
                          "unexpected character after line continuation character")
        self._check_error("A.\u03bc\\\n",
                          "unexpected EOF while parsing")

    def test_error_parenthesis(self):
        for paren in "([{":
            self._check_error(paren + "1 + 2", f"\\{paren}' was never closed")

        for paren in "([{":
            self._check_error(f"a = {paren} 1, 2, 3\nb=3", f"\\{paren}' was never closed")

        for paren in ")]}":
            self._check_error(paren + "1 + 2", f"unmatched '\\{paren}'")

        # Some more complex examples:
        code = """\
func(
    a=["unclosed], # Need a quote in this comment: "
    b=2,
)
"""
        self._check_error(code, "parenthesis '\\)' does not match opening parenthesis '\\['")

        self._check_error("match y:\n case e(e=v,v,", " was never closed")

        # Examples with dencodings
        s = b'# coding=latin\n(aaaaaaaaaaaaaaaaa\naaaaaaaaaaa\xb5'
        self._check_error(s, r"'\(' was never closed")

    def test_error_string_literal(self):

        self._check_error("'blech", r"unterminated string literal \(.*\)$")
        self._check_error('"blech', r"unterminated string literal \(.*\)$")
        self._check_error(
            r'"blech\"', r"unterminated string literal \(.*\); perhaps you escaped the end quote"
        )
        self._check_error(
            r'r"blech\"', r"unterminated string literal \(.*\); perhaps you escaped the end quote"
        )
        self._check_error("'''blech", "unterminated triple-quoted string literal")
        self._check_error('"""blech', "unterminated triple-quoted string literal")

    def test_invisible_characters(self):
        self._check_error('print\x17("Hello")', "invalid non-printable character")
        self._check_error(b"with(0,,):\n\x01", "invalid non-printable character")

    def test_match_call_does_not_raise_syntax_error(self):
        code = """
def match(x):
    return 1+1

match(34)
"""
        compile(code, "<string>", "exec")

    def test_case_call_does_not_raise_syntax_error(self):
        code = """
def case(x):
    return 1+1

case(34)
"""
        compile(code, "<string>", "exec")

    def test_multiline_compiler_error_points_to_the_end(self):
        self._check_error(
            "call(\na=1,\na=1\n)",
            "keyword argument repeated",
            lineno=3
        )

    @support.cpython_only
    def test_syntax_error_on_deeply_nested_blocks(self):
        # This raises a SyntaxError, it used to raise a SystemError. Context
        # for this change can be found on issue #27514

        # In 2.5 there was a missing exception and an assert was triggered in a
        # debug build.  The number of blocks must be greater than CO_MAXBLOCKS.
        # SF #1565514

        source = """
while 1:
 while 2:
  while 3:
   while 4:
    while 5:
     while 6:
      while 8:
       while 9:
        while 10:
         while 11:
          while 12:
           while 13:
            while 14:
             while 15:
              while 16:
               while 17:
                while 18:
                 while 19:
                  while 20:
                   while 21:
                    while 22:
                     while 23:
                      break
"""
        self._check_error(source, "too many statically nested blocks")

    @support.cpython_only
    def test_error_on_parser_stack_overflow(self):
        source = "-" * 100000 + "4"
        for mode in ["exec", "eval", "single"]:
            with self.subTest(mode=mode):
                with self.assertRaisesRegex(MemoryError, r"too complex"):
                    compile(source, "<string>", mode)

    @support.cpython_only
    @support.skip_wasi_stack_overflow()
    def test_deep_invalid_rule(self):
        # Check that a very deep invalid rule in the PEG
        # parser doesn't have exponential backtracking.
        source = "d{{{{{{{{{{{{{{{{{{{{{{{{{```{{{{{{{ef f():y"
        with self.assertRaises(SyntaxError):
            compile(source, "<string>", "exec")

    def test_except_stmt_invalid_as_expr(self):
        self._check_error(
            textwrap.dedent(
                """
                try:
                    pass
                except ValueError as obj.attr:
                    pass
                """
            ),
            errtext="cannot use except statement with attribute",
            lineno=4,
            end_lineno=4,
            offset=22,
            end_offset=22 + len("obj.attr"),
        )

    def test_match_stmt_invalid_as_expr(self):
        self._check_error(
            textwrap.dedent(
                """
                match 1:
                    case x as obj.attr:
                        ...
                """
            ),
            errtext="cannot use attribute as pattern target",
            lineno=3,
            end_lineno=3,
            offset=15,
            end_offset=15 + len("obj.attr"),
        )

    def test_ifexp_else_stmt(self):
        msg = "expected expression after 'else', but statement is given"

        for stmt in [
            "pass",
            "return",
            "return 2",
            "raise Exception('a')",
            "del a",
            "yield 2",
            "assert False",
            "break",
            "continue",
            "import",
            "import ast",
            "from",
            "from ast import *"
        ]:
            self._check_error(f"x = 1 if 1 else {stmt}", msg)

    def test_ifexp_body_stmt_else_expression(self):
        msg = "expected expression before 'if', but statement is given"

        for stmt in [
            "pass",
            "break",
            "continue"
        ]:
            self._check_error(f"x = {stmt} if 1 else 1", msg)

    def test_ifexp_body_stmt_else_stmt(self):
        msg = "expected expression before 'if', but statement is given"
        for lhs_stmt, rhs_stmt in [
            ("pass", "pass"),
            ("break", "pass"),
            ("continue", "import ast")
        ]:
            self._check_error(f"x = {lhs_stmt} if 1 else {rhs_stmt}", msg)

def load_tests(loader, tests, pattern):
    tests.addTest(doctest.DocTestSuite())
    return tests


if __name__ == "__main__":
    unittest.main()