Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions DIVERGENCE_STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,16 +72,23 @@ Le défaut se mesure sur `endjin/main`, pas sur l'ancienne pile `b425802b`.
| #37 ValueTuple | amont affecte les champs publics : le défaut de construction ValueTuple est absorbé | adopter amont ; aucun report du hunk fork |
| #38 types anonymes | amont délègue la lecture au marshaller partagé : le défaut est absorbé | adopter amont ; aucun report du hunk fork |
| #40 symbole `Rational` | `TheoremVariableTypeMappingAttribute` fournit la voie générique ; le support exact du fork reste local | aucune nouvelle PR symbole |
| #40 constante d'un type mappé | test rouge sur `964f177` : `(ExactReal)2.5` lève `NotImplementedException` dans `VisitConvert` ; endjin#114 est CLOSED sans merge | correction atomique proposée dans **endjin#129** ; 4 tests ciblés et 372/372 sur net10.0, net8.0 restant à mesurer |
| #40 constante d'un type mappé | test rouge sur `964f177` : `(ExactReal)2.5` lève `NotImplementedException` dans `VisitConvert` ; endjin#114 est CLOSED sans merge | correction atomique **endjin#129** (OPEN), cherry-pickée ici ; le fork y ajoute une garde de son propre pré-pli `PartialEval` — sans elle la pile resynchronisée reste à 475/2/473 |
| record positionnel | le fork conserve la construction par constructeur ; endjin#127 (OPEN) porte cette capacité et le témoin de modèle | pas de nouvelle PR amont dupliquée |

Mesures de cette branche (2026-11-25), sur `5071d6f` avec `endjin#129` cherry-pické : sans garde,
475 tests / 2 échecs / 473 réussites ; avec la garde `ExpressionVisitor.MentionsMappedTypeConversion`,
475/475 sur net10.0 et 475/475 sur net8.0. La jambe net8.0 est mesurée sur un échafaudage
multi-cible de sonde, non commité : l'amont est net10.0 par construction
(`solutions/Directory.Build.props`), que `Z3.Linq.csproj` du fork remplace par `net8.0;net10.0`
tandis que le projet de tests hérite de l'amont.

Les tests utiles des trois PRs restent des actifs de couverture à porter séparément ; ils ne
justifient pas de conserver les réimplémentations supplantées. Les contrats exacts et d'overflow
de `Rational` doivent être prouvés à travers la voie générique avant toute substitution.
La PR fork #43 conserve la matrice datée du 2026-10-25 : elle n'est ni fusionnée dans cette
branche ni écrasée ici.

## PRs amont ouvertes au 2026-11-24
## PRs amont ouvertes au 2026-11-25

| PR | Sujet | Base |
|---|---|---|
Expand All @@ -93,6 +100,7 @@ branche ni écrasée ici.
| #126 | banc de formes de collection/capture du fork | `feature/nested-collection-symbols` |
| #127 | témoin de modèle et environnements par constructeur | `main` |
| #128 | `SoftWhere`, MaxSAT pondéré | `main` |
| #129 | conversion vers un type mappé | `main` |

## Anti-divergence (HARD)

Expand Down Expand Up @@ -125,5 +133,5 @@ le comportement ; jamais de réimplémentation silencieuse d'un mécanisme amont

- EPIC parent : #14169 ; issue de resynchronisation : jsboige/CoursIA#19237.
- G1 #16050 · G1-bis #16053 (PR #16070) · Epic #1206 · issue historique #16609.
- Amont : #43, #110, #114, #118 ; suivi ouvert : #120 à #124, #126 à #128.
- Amont : #43, #110, #114, #118 ; suivi ouvert : #120 à #124, #126 à #129.
- Matrice G4 datée : PR fork #43 (`docs/g4-divergence-20261025`).
93 changes: 93 additions & 0 deletions solutions/Z3.Linq.Tests/MappedTypeConversionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
namespace Z3.Linq.Tests;

/// <summary>
/// A constant cast to a user type mapped by <see cref="TheoremVariableTypeMappingAttribute"/>
/// uses the same Z3 sort as a symbol of that type.
/// </summary>
[TestClass]
public class MappedTypeConversionTests
{
[TestMethod]
public void Solve_ConstantCastToMappedType_TranslatesUsingTheMappedSort()
{
using var context = new Z3Context();

var result = context.NewTheorem<ExactRealEnvironment>()
.Where(t => t.X == (ExactReal)2.5)
.Solve();

result.ShouldNotBeNull();
result.X.Value.ShouldBe(2.5);
}

[TestMethod]
public void Solve_MappedSymbolsAndConstantsInArithmetic_RelateThem()
{
using var context = new Z3Context();

var result = context.NewTheorem<ExactRealEnvironment>()
.Where(t => t.X + t.Y == (ExactReal)3.0)
.Where(t => t.X - t.Y == (ExactReal)1.0)
.Solve();

result.ShouldNotBeNull();
result.X.Value.ShouldBe(2.0);
result.Y.Value.ShouldBe(1.0);
}

[TestMethod]
public void Solve_MappedSymbol_ReadsBackThroughItsConstructor()
{
using var context = new Z3Context();

var result = context.NewTheorem<ExactRealEnvironment>()
.Where(t => t.X > t.Y)
.Solve();

result.ShouldNotBeNull();
result.X.Value.ShouldBeGreaterThan(result.Y.Value);
}

[TestMethod]
public void Solve_MappedInstanceAsConstant_RemainsUnsupported()
{
using var context = new Z3Context();
var value = new ExactReal(0.5);
var theorem = context.NewTheorem<ExactRealEnvironment>().Where(t => t.X == value);

Should.Throw<NotSupportedException>(() => theorem.Solve());
}

private sealed class ExactRealEnvironment
{
public ExactReal X { get; set; }

public ExactReal Y { get; set; }
}

[TheoremVariableTypeMapping(typeof(double))]
private readonly struct ExactReal
{
public ExactReal(double value) => this.Value = value;

public double Value { get; }

public static implicit operator ExactReal(double value) => new(value);

public static bool operator ==(ExactReal left, ExactReal right) => left.Value == right.Value;

public static bool operator !=(ExactReal left, ExactReal right) => left.Value != right.Value;

public static bool operator <(ExactReal left, ExactReal right) => left.Value < right.Value;

public static bool operator >(ExactReal left, ExactReal right) => left.Value > right.Value;

public static ExactReal operator +(ExactReal left, ExactReal right) => new(left.Value + right.Value);

public static ExactReal operator -(ExactReal left, ExactReal right) => new(left.Value - right.Value);

public override bool Equals(object? obj) => obj is ExactReal other && this.Value.Equals(other.Value);

public override int GetHashCode() => this.Value.GetHashCode();
}
}
57 changes: 54 additions & 3 deletions solutions/Z3.Linq/ExpressionVisitor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,28 @@ internal static bool MentionsExceptionClosure(Expression expression)
return finder.Found;
}

/// <summary>
/// Reports whether an expression converts a value to a type that carries a
/// <see cref="TheoremVariableTypeMappingAttribute"/>.
/// </summary>
/// <param name="expression">The expression to scan.</param>
/// <returns><see langword="true"/> when a conversion to a mapped type appears anywhere in the tree.</returns>
/// <remarks>
/// A cast such as <c>(ExactReal)2.5</c> is an operator call on a constant, so a host evaluation
/// folds it into a constant of the mapped type. The visitor then receives a value it refuses,
/// while the conversion node itself carries what it needs to select the sort: translated, the
/// cast is the identity construction the mapping promises, and an arbitrary instance of the
/// mapped type stays unsupported. A constraint that mentions such a conversion is therefore
/// translated without the fold. See <c>Theorem.TranslateConstraint</c> and MappedTypeConversionTests.
/// </remarks>
internal static bool MentionsMappedTypeConversion(Expression expression)
{
var finder = new MappedTypeConversionFinder();
finder.Visit(expression);

return finder.Found;
}

private Expr Visit(Expression expression)
{
// Largely table-driven mechanism, providing constructor lambdas to Visit* methods,
Expand Down Expand Up @@ -255,17 +277,31 @@ private Expr VisitConvert(UnaryExpression expression)
// This used to be a switch on the target type alone, which assumed the operand sort from
// it - int-to-real for every conversion to double, real-to-int for every conversion to
// int - and had no arm at all for long, float or decimal. See #63 and #76.
Sort? targetSort = expression.Type == typeof(char)
// The target is asked for the sort its symbols are declared with, so a type carrying a
// TheoremVariableTypeMappingAttribute is converted to the sort of the type it stands for.
Type targetType = Theorem.MappedType(expression.Type);

Sort? targetSort = targetType == typeof(char)
? this.context.IntSort
: Theorem.TryGetSymbolSort(this.context, Type.GetTypeCode(expression.Type));
: Theorem.TryGetSymbolSort(this.context, Type.GetTypeCode(targetType));

if (targetSort is not null)
{
// A conversion that calls an operator method runs C# the visitor cannot see into, so
// translating it from the sorts alone would drop whatever the operator does. Decimal's
// built-in conversions are operator methods on decimal too, and are the numeric
// conversions translated here; any other operator is refused.
if (expression.Method is { } method && method.DeclaringType != typeof(decimal))
//
// The exception is the identity construction promised by a variable type mapping: the
// cast's target carries the mapping, and its operator accepts the regular type and
// returns that same target. The sort conversion below stands in for the constructor.
// An arbitrary instance of the mapped type is still refused by VisitConstantValue.
if (expression.Method is { } method && method.DeclaringType != typeof(decimal)
&& !(expression.Method.IsSpecialName
&& (expression.Method.Name == "op_Implicit" || expression.Method.Name == "op_Explicit")
&& expression.Method.ReturnType == expression.Type
&& expression.Method.GetParameters() is [{ } parameter]
&& parameter.ParameterType == targetType))
{
throw new NotSupportedException(
$"The conversion '{expression}' calls the user-defined operator {method.DeclaringType}.{method.Name}, which cannot be translated: only built-in numeric conversions are supported.");
Expand Down Expand Up @@ -1422,4 +1458,19 @@ protected override Expression VisitMethodCall(MethodCallExpression node)
return this.Found ? node : base.VisitMethodCall(node);
}
}

/// <summary>Reports whether a conversion targets a type mapped by a variable type mapping.</summary>
private sealed class MappedTypeConversionFinder : ExprVisitor
{
internal bool Found { get; private set; }

protected override Expression VisitUnary(UnaryExpression node)
{
this.Found = this.Found
|| (node.NodeType is ExpressionType.Convert or ExpressionType.ConvertChecked
&& Theorem.MappedType(node.Type) != node.Type);

return this.Found ? node : base.VisitUnary(node);
}
}
}
33 changes: 24 additions & 9 deletions solutions/Z3.Linq/Theorem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -567,10 +567,15 @@ private Status CheckStatus(Context ctx, Z3Object approach, CancellationToken can
/// subtree by an exception-closure call. The artificial node no longer carries the member chain
/// the user wrote, so it is not translated; the original constraint goes through the visitor,
/// whose captured-member path names the null link. See ConstantMemberTests.
/// A conversion to a mapped type is a second shape the fold must not touch: evaluated on the
/// host, <c>(ExactReal)2.5</c> becomes a constant of the mapped type, which the visitor refuses,
/// whereas the conversion node itself translates to the sort the mapping declares. See
/// <c>ExpressionVisitor.MentionsMappedTypeConversion</c> and MappedTypeConversionTests.
/// </remarks>
private static Expr TranslateConstraint(Context context, Environment environment, LambdaExpression constraint)
{
Expression body = ExpressionVisitor.MentionsTranslationMarker(constraint.Body)
|| ExpressionVisitor.MentionsMappedTypeConversion(constraint.Body)
? constraint.Body
: PartialEvaluator.PartialEval(constraint, ExpressionInterpreter.Instance).Body;

Expand Down Expand Up @@ -760,8 +765,23 @@ internal static (long Low, long High)? GetBounds(TypeCode typeCode)
/// <returns>The type the symbol is declared and read as.</returns>
private static Type SymbolType(MemberInfo member)
{
Type type = MemberClrType(member);
return MappedType(MemberClrType(member));
}

/// <summary>
/// The type a CLR type stands for in a theorem: itself, or the type a
/// <see cref="TheoremVariableTypeMappingAttribute"/> on it maps it to.
/// </summary>
/// <param name="type">A declared CLR type, of a member or of a converted constant.</param>
/// <returns>The type the symbol is declared and read as.</returns>
/// <remarks>
/// The environment builder, the bounds asserter, the marshaller and the expression visitor all
/// have to agree on this answer. They asked the mapping separately and the visitor did not ask
/// at all, so a mapped type was a real symbol in the environment and an untranslatable
/// constant in the predicate.
/// </remarks>
internal static Type MappedType(Type type)
{
return GetTypeMapping(type)?.RegularType ?? type;
}

Expand Down Expand Up @@ -1045,9 +1065,7 @@ private Environment GetEnvironment(Context context, MemberInfo parameter, string
{
var toReturn = new Environment();

var parameterType = MemberClrType(parameter);

parameterType = GetTypeMapping(parameterType)?.RegularType ?? parameterType;
var parameterType = MappedType(MemberClrType(parameter));

// Map the environment onto Z3-compatible types.
Expr constrExp;
Expand Down Expand Up @@ -1101,10 +1119,7 @@ private static object ConvertZ3Expression(object destinationObject, Context cont
// Normalize types when facing Z3. Theorem variable type mappings allow for strong
// typing within the theorem, while underlying variable representations are Z3-
// friendly types.
var parameterType = MemberClrType(parameter);

TheoremVariableTypeMappingAttribute? parameterTypeMapping = GetTypeMapping(parameterType);
parameterType = parameterTypeMapping?.RegularType ?? parameterType;
var parameterType = MappedType(MemberClrType(parameter));

object value;
TypeCode typeCode = Type.GetTypeCode(parameterType);
Expand Down Expand Up @@ -1147,7 +1162,7 @@ private static object ConvertZ3Expression(object destinationObject, Context cont

// If there was a type mapping, we need to convert back to the original type.
// In that case we expect a constructor with the mapped type to be available.
if (parameterTypeMapping != null)
if (MappedType(MemberClrType(parameter)) != MemberClrType(parameter))
{
if (parameter is PropertyInfo propertyInfo)
{
Expand Down