@@ -370,19 +370,52 @@ def not_yet_in_unique_list(val: Ex) -> bool: # type: ignore # covariant type pa
370370 assert self .max_size >= len (result ) >= self .min_size
371371 return result
372372
373- def _invert (self , value : Any ) -> tuple [ChoiceT , ...]:
374- if self .tuple_suffixes is not None :
375- # each element interleaves an element_strategy draw with a
376- # tuple_suffixes draw, which we cannot separate here
377- raise CannotInvert (f"cannot invert { self !r} with tuple_suffixes" )
378- # A valid unique list draws exactly like a ListStrategy, since every
379- # element passes the uniqueness filter on its first draw.
380- choices = ListStrategy ._invert (self , value )
373+ def _check_unique_keys (self , elements : list [Any ]) -> None :
381374 for keyfunc in self .keys :
382- keys = list (map (keyfunc , value ))
383- if len (set (keys )) != len (keys ):
384- raise CannotInvert (f"{ value !r} has duplicate keys for { self !r} " )
385- return choices
375+ try :
376+ keys = list (map (keyfunc , elements ))
377+ unique = len (set (keys )) == len (keys )
378+ except Exception :
379+ raise CannotInvert (
380+ f"could not compute uniqueness keys for { self !r} "
381+ ) from None
382+ if not unique :
383+ raise CannotInvert (f"{ elements !r} has duplicate keys for { self !r} " )
384+
385+ def _split_suffixed (self , value : Any ) -> list [Any ]:
386+ # With tuple_suffixes, each element is (key, *suffix): the key drawn
387+ # from element_strategy, then the suffix from tuple_suffixes.
388+ # Uniqueness applies to the key alone.
389+ if not isinstance (value , list ):
390+ raise CannotInvert (f"{ value !r} is not a list" )
391+ if not all (isinstance (e , tuple ) and e for e in value ):
392+ raise CannotInvert (f"{ value !r} is not a list of nonempty tuples" )
393+ return [e [0 ] for e in value ]
394+
395+ def _invert (self , value : Any ) -> tuple [ChoiceT , ...]:
396+ if self .tuple_suffixes is None :
397+ # A valid unique list draws exactly like a ListStrategy, since
398+ # every element passes the uniqueness filter on its first draw.
399+ self ._check_unique_keys (value )
400+ return ListStrategy ._invert (self , value )
401+ self ._check_unique_keys (self ._split_suffixed (value ))
402+ if not (self .min_size <= len (value ) <= self .max_size ):
403+ raise CannotInvert (
404+ f"len={ len (value )} outside "
405+ f"[{ self .min_size } , { self .max_size !r} ] for { self !r} "
406+ )
407+ elements = cu .invert_many (self .min_size , self .max_size )
408+ choices : list [ChoiceT ] = []
409+ for i , element in enumerate (value ):
410+ choices .extend (elements .more ())
411+ try :
412+ choices .extend (self .element_strategy ._invert (element [0 ]))
413+ choices .extend (self .tuple_suffixes ._invert (tuple (element [1 :])))
414+ except CannotInvert as exc :
415+ add_note (exc , f"at index { i } of { value !r} , strategy={ self !r} " )
416+ raise
417+ choices .extend (elements .done ())
418+ return tuple (choices )
386419
387420
388421class UniqueSampledListStrategy (UniqueListStrategy ):
@@ -420,22 +453,21 @@ def do_draw(self, data: ConjectureData) -> list[Ex]:
420453 return result
421454
422455 def _invert (self , value : Any ) -> tuple [ChoiceT , ...]:
423- if self .tuple_suffixes is not None :
424- raise CannotInvert (f"cannot invert { self !r} with tuple_suffixes" )
425456 if not isinstance (value , list ):
426457 raise CannotInvert (f"{ value !r} is not a list" )
427458 if not (self .min_size <= len (value ) <= self .max_size ):
428459 raise CannotInvert (
429460 f"len={ len (value )} outside "
430461 f"[{ self .min_size } , { self .max_size !r} ] for { self !r} "
431462 )
463+ targets = value if self .tuple_suffixes is None else self ._split_suffixed (value )
432464 # do_draw indexes into the pool of not-yet-drawn elements, so each
433465 # index is relative to what remains, not to the original elements.
434466 assert isinstance (self .element_strategy , SampledFromStrategy )
435467 remaining = list (self .element_strategy .elements )
436468 elements = cu .invert_many (self .min_size , self .max_size )
437469 choices : list [ChoiceT ] = []
438- for i , target in enumerate (value ):
470+ for i , ( element , target ) in enumerate (zip ( value , targets , strict = True ) ):
439471 choices .extend (elements .more ())
440472 for j , candidate in enumerate (remaining ):
441473 if equal_values (self .element_strategy ._transform (candidate ), target ):
@@ -447,6 +479,12 @@ def _invert(self, value: Any) -> tuple[ChoiceT, ...]:
447479 f"at index { i } of { value !r} : { target !r} is not among the "
448480 f"remaining elements of { self !r} "
449481 )
482+ if self .tuple_suffixes is not None :
483+ try :
484+ choices .extend (self .tuple_suffixes ._invert (tuple (element [1 :])))
485+ except CannotInvert as exc :
486+ add_note (exc , f"at index { i } of { value !r} , strategy={ self !r} " )
487+ raise
450488 if remaining :
451489 # with an exhausted pool, do_draw stops without drawing a boolean
452490 choices .extend (elements .done ())
@@ -513,6 +551,52 @@ def do_draw(self, data: ConjectureData) -> Mapping[Any, Any]:
513551 )
514552 return value
515553
554+ def _invert (self , value : Any ) -> tuple [ChoiceT , ...]:
555+ if not isinstance (value , Mapping ):
556+ raise CannotInvert (f"{ value !r} is not a mapping" )
557+ optional = self .optional or {}
558+ if any (k not in value for k in self .mapping ) or any (
559+ k not in self .mapping and k not in optional for k in value
560+ ):
561+ raise CannotInvert (f"{ value !r} has the wrong keys for { self !r} " )
562+
563+ choices : list [ChoiceT ] = []
564+ npairs = len (self .mapping )
565+ for key , strategy in self .mapping .items ():
566+ try :
567+ choices .extend (strategy ._invert (value [key ]))
568+ except CannotInvert as exc :
569+ add_note (exc , f"at key { key !r} of { value !r} , strategy={ self !r} " )
570+ raise
571+
572+ if self .optional is not None :
573+ # do_draw selects each present optional key by its index in the
574+ # remaining-keys list, which pops via swap-with-last.
575+ remaining = [k for k , v in self .optional .items () if not v .is_empty ]
576+ present = [k for k in remaining if k in value and k not in self .mapping ]
577+ if npairs + len (present ) != len (value ):
578+ # a present optional key whose strategy is empty
579+ raise CannotInvert (f"{ value !r} has the wrong keys for { self !r} " )
580+ selector = cu .invert_many (0 , len (remaining ))
581+ for key in present :
582+ choices .extend (selector .more ())
583+ j = remaining .index (key )
584+ choices .append (j )
585+ remaining [- 1 ], remaining [j ] = remaining [j ], remaining [- 1 ]
586+ remaining .pop ()
587+ try :
588+ choices .extend (self .optional [key ]._invert (value [key ]))
589+ except CannotInvert as exc :
590+ add_note (exc , f"at key { key !r} of { value !r} , strategy={ self !r} " )
591+ raise
592+ choices .extend (selector .done ())
593+ npairs += len (present )
594+
595+ # an identity shuffle for do_draw's final fisher_yates_shuffle of the
596+ # pairs; mappings compare equal regardless of iteration order
597+ choices .extend (range (npairs - 1 ))
598+ return tuple (choices )
599+
516600 def calc_is_empty (self , recur : RecurT ) -> bool :
517601 return recur (self .fixed )
518602
0 commit comments