Skip to content

VB to C#: Rewrite query syntax conversion around range variable scope - #1305

Merged
GrahamTheCoder merged 45 commits into
icsharpcode:masterfrom
GrahamTheCoder:claude/admiring-franklin-rmhxyp
Nov 9, 2026
Merged

GrahamTheCoder merged 45 commits into
icsharpcode:masterfrom
GrahamTheCoder:claude/admiring-franklin-rmhxyp

Conversation

@GrahamTheCoder

@GrahamTheCoder GrahamTheCoder commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Line changes: Production: +1444, -495. Test: +3212, -106. Md files: +98

Fixes the "Difficult area" LINQ query syntax issues (VB -> C#); each has a regression test:

Problem

The old QueryConverter split VB clauses into segments up front and converted clause syntax one-to-one, adding special cases as issues arrived. Almost every reported bug has the same root cause: VB and C# disagree about which range variables are in scope after each clause (VB Select and Group By replace the scope, C# can only drop variables with into), and about what a query returns without a final Select (VB returns an anonymous type of all range variables in scope). Clause-by-clause syntax can't express either, so each new combination needed another patch.

Documentation: CodeConverter/CSharp/Queries/README.md. It sets out the VB and C# rules the conversion relies on (with sources: Roslyn's query binders and the language docs, plus running VB) and where the implementation meets each.

Solution

Classes in CodeConverter/CSharp/Queries:

  • QueryClauseConverter converts VB clauses left to right into a CsQueryBuilder. The joins and grouping parts are partials, because they recursively convert nested clauses.
  • CsQueryBuilder tracks the VB scope (which alone decides the element) and the C# expression currently evaluating each VB range variable (x, g.Key.P1, g.Sum(t => t.A), e.x after a method call, ...).
  • SubstitutionRules decides when a value can be substituted rather than declared with let, for the clauses of the (sub)query being built.
  • FlatJoinPlanner decides whether nested joins can be flat C# joins.
  • QuerySourceConverter makes VB's implicit AsEnumerable/Cast/CType on a source explicit.
  • ExpressionTreeDetector reads VB's own translation (ITranslatedQueryOperation) to tell whether a query compiles to delegates or to expression trees.
  • RangeVariableReplacements is keyed by range variable symbol and consulted in ConvertIdentifierNameAsync, so every reference (including inside nested lambdas and queries) is substituted. The VB binder handles shadowing, case-insensitivity and nested queries.

What the conversion does:

  • Because the element is always built from VB's scope, C# can keep variables VB dropped. A mid-query Select becomes lets or substitutions (renaming on clashes), Group By becomes group ... into g with keys and aggregations expressed via g, and Join sides are chosen by the symbols each side references.
  • A value is substituted only where that keeps VB's evaluation: the same elements, the same order, the same number of times and the same time relative to mutable state. Otherwise it stays a let, typed where C# can't infer it (As types, Nothing, delegates).
  • Nested joins are flattened where valid. Otherwise they become a subquery joined as one compound variable, mirroring VB's own xs.Join(ys.Join(zs, ...)).
  • Output gets less idiomatic only as the input requires it: plain clauses, then let, then continuation, then a method call with a resumed from, then a join subquery, then NotImplementedException (a compile error comment) for anything unrepresentable.

Comparisons (per review discussion)

  • Delegates (LINQ to objects): a query is just code, so comparisons get VB's semantics exactly as outside a query: Nothing = "", Option Compare Text, and nullable logic. Previously every query was simplified, which gave different results for null strings, nullables and Option Compare Text.
  • Neatest correct form: in a boolean context VB treats Nothing as False. C#'s lifted operators are already false whenever VB would give Nothing for = (one nullable side) and for </>/<=/>=, so those are plain: where e.N == 123, where e.N > 1 && (e.S ?? "") == (s ?? "").
    • Only <> and both-nullable = need a pattern.
    • The boolean context here is If/Where/Skip/Take While and the operands of AndAlso/OrElse within them. It excludes the left of AndAlso when the right could throw or have side effects, since VB evaluates the right even when the left is Nothing.
    • This also tidies If statements outside queries, e.g. if (status == PasswordStatus.Locked) instead of if (status.HasValue && status.Value == PasswordStatus.Locked), with the same behaviour.
  • Expression trees (IQueryable, e.g. EF): plain C# operators (x == s, b == true for a Boolean? operand of &&), which the provider translates. This is the case behind VB -> C# System.Linq.Expression needs special treatment #316 and VB -> C#: wrong conversion of linq expression containing nullable value #894: the provider decides the semantics (e.g. collation), and it may not translate VB's runtime helpers or C# patterns.
    • The parts of the query the provider receives as values run in memory, so they get VB's semantics. These are the first source, a join's inner source and Skip/Take counts, including those of an Aggregate clause within a delegate query.
    • Risk, noted in the README: an IQueryable evaluated in memory (e.g. list.AsQueryable(), or client-side evaluation) runs the plain C# comparisons, so it differs from VB for Nothing = "", nullables and Option Compare Text.
    • Unchanged from master: Object comparisons and relational string comparisons still emit VB runtime helpers even in expression trees.

Blind reviews

Fresh reviewers, with no anchoring on earlier results, did 7 rounds of review. Each verified its findings by running them. Every real finding has a regression test (mostly self-verifying runtime tests) and a fix.

  1. Round 1: capture by later lambda locals and range variables, conditional evaluation in the final Select, unnamed Select past a filter, composite join keys of different types, text-only parenthesization, and a Func lambda inside an expression tree.
  2. Round 2: values dropped by a later Select, evaluation order in the final Select, lambda values, Aggregate over IQueryable misdetected as an expression tree, and older bugs: As types, Nothing, Where on Boolean?.
  3. Round 3: VB calls without parentheses, NameOf, Take While on Boolean?, a bare From x In list changing type, implicit AsEnumerable, nested Aggregate, delegate-typed Let, and Boolean? AndAlso in expression trees.
  4. Round 4: a let value evaluated before an earlier substituted one, VB calls without parentheses on the right of AndAlso, Boolean? aggregation predicates, and a redundant == true.
  5. Round 5: a Let inside an Aggregate moved past its Where, cheap locals read later inside lambdas, AndAlso with a throwing right side, boxing/nullable As types, AddressOf; plus where Group.Count() > 1 for single-use aggregations.
  6. Round 6: reverted round 5's substitution into Order By, the first fix to flip-flop, because OrderBy reads every element before evaluating any key. Also: range variables judged by what's substituted for them, Group By items holding lazy queries, and the in-memory parts of IQueryable queries.
  7. Round 7, guided by coverage and Stryker survivors: Aggregate clauses' in-memory/expression-tree boundary, Skip/Take counts converted to Integer, and a duplicate declaration. It also added tests for mutation and coverage gaps and removed two conditions that can't change the result.

Stopping point: round 6 flip-flopped on Order By, and round 7's remaining bugs were narrow (the IQueryable/Aggregate boundary). The loop stops here, though another round is easy to run.

Declined, as not worth the code:

  • parenthesizing a join subquery (the simplifier removes the parentheses);
  • passing a range variable ByRef;
  • lambdas outside query syntax with Boolean? bodies;
  • the last two are pre-existing.

Limitations (also in the README):

  • Values cheap to repeat (names, member accesses, literals) are substituted, so a property getter with side effects could run a different number of times. Getters, and member access on a possibly-null receiver, are also assumed not to throw on the right of AndAlso.

  • Operators before a substituted value in the same clause are assumed not to throw.

  • Tests:

    • 68 conversion tests in LinqQueryScopeTests, LinqQueryJoinTests, LinqQueryGroupByTests and LinqQueryAggregateTests, plus more in LinqExpressionTests.cs and BinaryExpressionTests.cs.
    • 130 self-verifying tests (LinqExpressionTests.vb, LinqEvaluationTests.vb, LinqComparisonTests.vb, LinqOptionCompareTextTests.vb) run each VB query and its C# conversion and compare the results. Many log the order in which values are evaluated.
    • Coverage and mutation testing: coverlet coverage and Stryker.NET mutation testing over the query code found further test gaps.
      • The latest Stryker score is 77%, but it understates coverage because Stryker doesn't count the self-verifying tests. The round 7 reviewer found that many listed survivors are killed by them.
      • The remaining survivors are guards for invalid VB or equivalent mutants.

Locally on Linux, the suite has the same failures as master (line-ending/solution-file/enum-rounding tests that already fail there) and no new ones.

Process

  • Attachment level: Zero/low. Written by an LLM (Claude Code session), TDD with atomic commits, refactor commits separate from behaviour changes.
  • LLM primarily used: Claude Code (Anthropic)
Look at the "difficult area" issues involving linq query syntax ... understand the full detail of the query syntax in both languages, and design an appropriate conversion approach ... Put together full documentation ... implement the best path with full tests for all relevant issues ... use progressive fallback to uglier code ... Be aware of cross-cutting things like option text compare's effect too ... atomic commits and TDD ... blind reviewed/fixed
Is there a way to cover those not converted yet items in a way that doesn't degrade the output in existing cases or make the existing code more tangled? ... pure refactor first if needed
The design doc should turn into documentation of how the implementation matches the requirements ... a readme ... focused and terse ... names ... adjusted so the code self documents
Partial classes are ok if needed, though breaking out truly separate classes with clear responsibilities is best. I'd also recommend trying some test cases that don't relate to a specific issue but are in uncovered areas. Code coverage or mutation testing can help here.
For the "most in need of attention", do any checks you can, and otherwise make it very clear what you need an opinion/decision on (and the context/tradeoffs) ... iterate on fixes from blind reviews until they reach the "nitpick" stage, or flip flop with previous fixes.
For the decision needed items, we should ensure correctness within this PR since we're rewriting the query processing. i.e. We should output the neatest version of a comparison that matches what the VB compiler would receive ... Probably best to use the simple check that will work with EF in the case of iqueryable, though we can note the risk in the readme ...
Feed test/mutation coverage into the next review round

🤖 Generated with Claude Code

https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G

claude added 30 commits November 9, 2026 02:05
Introduce a new query converter that walks VB query clauses left to right,
tracking which VB range variables are in scope and the C# expression for
each, rather than splitting the query into segments up front.

- Range variable references are substituted by symbol, so a VB Select that
  isn't the last clause no longer needs a continuation: names are reused
  where possible, renamed on clashes, and the implicit final select is built
  from VB's scope (fixes icsharpcode#1163, icsharpcode#1172).
- Values that can be inlined without changing evaluation count are
  substituted, otherwise a let clause is introduced.
- Distinct/Skip/Take/Skip While/Take While materialize the current element
  and continue the query from the method call.

Queries using Join, Group Join, Group By or Aggregate still go through the
legacy converter for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
- The inner side of each join condition is found from the range variable
  symbols it references, rather than the syntax of the left hand side, so
  any expression works on either side (fixes icsharpcode#936).
- Group Join aggregates become method calls on the join...into variable,
  which is named after the `Group` aggregation where present, so
  `Into Group` no longer throws (fixes icsharpcode#935).
- Joins nested within a Join are flattened, attaching each condition to the
  earliest join where everything it references is in scope.
- Queries ending without a Select now return all VB range variables in
  scope (fixes icsharpcode#931), and Order By after Select works (fixes icsharpcode#1016).
- Inlined values keep their source mapping when used immediately, so
  comments stay in order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
After a VB Group By the range variables in scope are its keys and
aggregations, so each is expressed in terms of the C# continuation
variable: keys as `g.Key`/`g.Key.Name`, aggregations as method calls on the
group with a lambda over the group's element.

- Multiple keys no longer throw (fixes icsharpcode#1014, icsharpcode#298), and aggregations are
  no longer dropped (fixes icsharpcode#1272, icsharpcode#867).
- Key references are rewritten, e.g. Order By after Group By (fixes icsharpcode#948),
  and named groups keep their name (icsharpcode#1180).
- Group items and compound elements (several range variables in scope)
  become anonymous types, with aggregate lambdas reading their members.
- An inferred anonymous type member keeps VB's name when the converted
  expression would infer a different one, e.g. after substitution.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
- An initial Aggregate becomes method calls on the (possibly filtered)
  source. With several aggregations the result is an anonymous type, and
  the source is only repeated if that's cheap, otherwise it's evaluated
  once like VB does.
- Aggregate within a query adds a range variable per aggregation over a
  nested query, with the nested query held in a group variable when it's
  used by several aggregations, mirroring VB's translation.
- Nested queries know their enclosing query's range variables, so
  generated names don't clash.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Every VB query clause is now handled by the scope-tracking converter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
- `From x As T In xs` uses C#'s typed from (Cast<T>) only for reference
  conversions, where it behaves the same as VB's CType. Other conversions
  (e.g. numeric widening, which Cast<T> would throw for) select the
  converted value instead.
- Non-generic sources (e.g. ArrayList), which VB implicitly casts to
  Object, get an explicitly typed from clause as C# requires.
- Self-verifying tests run each VB query and its conversion and compare the
  results, covering every clause kind and the reported issues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Comparisons within queries are deliberately kept simple so that providers
like EF can translate them from expression trees. But for a query that
runs as delegates, dropping Option Compare Text changed which strings
matched.

The VB compiler's translation of the query shows whether its lambdas are
expression trees, so case-insensitive equality is now kept for queries that
aren't, consistent with how lambdas are already converted. Query operators
themselves (Group By, Distinct, Join, Order By) aren't affected by Option
Compare in VB, which the new self-verifying tests confirm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Covers VB and C# query semantics (from the Roslyn binders and verified by
running VB), why the previous converter needed a special case per issue,
the scope-tracking model, inline vs let rules, naming, the progressive
fallback order, Option Compare Text, and known limitations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
- Substituted expressions can reference C# range variables VB has dropped,
  so they're no longer substituted where a later lambda parameter of the
  same name would capture them, and generated lambda parameters don't
  reuse such names. Previously e.g. `Select y = x Where
  ys.Any(Function(x) x > y)` silently compared x with itself.
- Generated names avoid names declared within the query and enclosing
  lambda parameters.
- `Join c As T In xs` keeps its type, like From.
- Only compiler generated operator calls decide whether a query is an
  expression tree, so a user's IQueryable lambda inside a LINQ to objects
  query doesn't lose Option Compare Text; a query nested in an expression
  tree is treated as part of it.
- An explicit identity Select is kept, since it changes the result type.
- A query resumed after a method call selects its from variable rather than
  rebuilding an identical anonymous type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Pure refactor: join planning returns the conditions for each join (or null
when they can't be flattened), and conditions/aggregations work with the
joined element (one or more range variables) rather than a single variable,
ready for joining against a subquery.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
VB allows joins nested within a Join or Group Join. Flattening them into a
sequence of C# joins only works for inner joins whose conditions each use
one joined variable on the inner side, so previously a Group Join among
them threw, a nested Join within a Group Join threw, and a condition like
`On x Equals y + z` produced C# that didn't compile.

Those cases now mirror VB's own translation (`xs.Join(ys.Join(zs, ...))`):
the joined variable and its nested joins become a subquery, joined as one
compound C# variable whose members the VB variables refer to. Flattenable
joins are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
The VB parser rejects them (BC30205) and the VB binder asserts they never
occur, so this isn't a conversion limitation. The guard stays for code with
errors, rather than silently dropping clauses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Pure refactor:
- Split QueryClauseConverter into partial files for joins, grouping and
  substitution rules.
- Rename to describe intent, e.g. Define -> DefineVariable(canSubstitute,
  keepSourceMapping), IsMethodBoundary -> IsConvertedToMethodCall,
  EnsureQuery -> EnsureQueryOpen, and extract helpers such as
  EvaluateOnce, CallCast, SelectConverted and UsesSimplifiedQueryComparison.
- Trim doc comments to the reasons the code can't show.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…entation

States the VB and C# rules (with sources) that the conversion relies on,
and where the implementation meets each, without historical context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Pure refactor. Parts with a self-contained responsibility now have their
own class:
- SubstitutionRules: whether a value can be substituted for its variable
- FlatJoinPlanner: whether nested joins can be written as flat C# joins
- QuerySourceConverter: making VB's implicit AsEnumerable/Cast/CType on a
  range variable's collection explicit

Join and grouping conversion stay as partials of QueryClauseConverter,
since they recursively convert nested clauses and share its variable
registration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Coverage and Stryker.NET mutation testing over the query conversion code
showed paths no test exercised, including:
- builder state across several continuations (two Group Bys), method
  calls after a continuation, and a method call right before the final
  Select
- nested joins only unflattenable once both variables are in scope
- substitution not being blocked by unrelated or earlier lambda
  parameters, or member names
- generated names avoiding element members and enclosing queries
- expression tree and query flags being combined for nested queries and
  restored afterwards
- typed From over a non-generic source

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Pure refactor: AddFrom no longer special-cases the first clause, and an
argument and fallback that made no difference to any valid query are
removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Covers names generated in a nested query avoiding C#-only names in the
enclosing query, two join subqueries in one query, a typed Group Join
variable, and a typed From whose variable isn't called x.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Pure refactor:
- The builder no longer reopens the query in each method: the converter
  already opens it before each clause, as EnsureQueryOpen documents.
- The generated select before a method call no longer needs line mapping.
- Range variables are no longer unregistered after a query, since their
  symbols can't occur elsewhere.
- A redundant element name check and null filter are removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
VB evaluates a Let or mid-query Select value once for each element reaching
that clause. Substituting it past a Where, Order By, Skip/Take etc. changed
which elements it ran for and in what order, and an unused value was dropped
entirely, so side effects and exceptions differed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Roslyn's formatter puts two line breaks after a `}` separated from the next
token only by elastic trivia, e.g. `from x in new[] { 1 } where ...` written
on one VB line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…fferently

Found by blind review:
* A dropped range variable could be captured by a local or loop variable in a
  later lambda, and a referenced field by a later range variable of the same name.
* A value substituted into a conditional operand of the final Select was only
  evaluated on one branch.
* An unnamed mid-query Select was always substituted, even past a filter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
C# infers a single join key's type from both sides, but anonymous composite
key members must match exactly, e.g. Integer and Integer? (CS1941).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…dexing

`$"{y}"` with a substituted conditional, and `a(0)` with a substituted
`New Integer(x) {}`, didn't compile when the output was parsed as text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
A Func lambda in an IQueryable query (`o.Items.Any(Function(i) i.S = s)`) is
still translated by the provider, so its comparisons stay simplified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…ut of queries

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…r evaluation

Found by blind review:
* A value dropped by a later mid-query Select was never evaluated.
* Substituting into the final Select could evaluate values out of declaration order,
  or after a call the Select makes first.
* A substituted lambda was invoked directly (CS0149), and couldn't be a let without a
  delegate type (CS1932).
* A range variable's As type and a Nothing value's type were lost (CS1061, CS0828).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
An Aggregate over an IQueryable inside a LINQ to objects query made the whole
query look like an expression tree, losing Option Compare Text equality.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
`Where b` with `b As Boolean?` didn't compile (CS0266); VB treats Nothing as False.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
claude added 15 commits November 9, 2026 15:54
…condition to Boolean

The lambda is applied to the query's result, where the query's own range
variables aren't in scope, so `x` needn't become `x1`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…ntext

Where only whether a condition is True matters, VB treats Nothing like False.
C#'s lifted relational operators are false when an operand is null, as is its
lifted == unless both operands are null, so `If n = 1` can be `if (n == 1)`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
Only queries compiled to expression trees (e.g. IQueryable for EF) keep plain C#
comparisons, since the provider decides their semantics and may not translate VB's
runtime helpers or C# patterns (icsharpcode#316, icsharpcode#894). A query compiled to delegates is just
code, so `Where x = s` now treats Nothing like "" as VB does.

That makes in-query handling the same as expression tree handling, so the two
query tracker flags become one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…ery value substitution

Found by blind review:
* `Select a = G, b = y` called G before evaluating the substituted y, since a VB
  call without parentheses looks like a name.
* `NameOf(y)` of a substituted range variable became `nameof(x + 1)`, or "Key" for
  a group key, and counted as the value's only evaluation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
* A query of only `From x In list` became `list`, changing its type.
* An implicit AsEnumerable wasn't parenthesized, or emitted at all for an instance method.
* An Aggregate nested in an Aggregate crashed the expression tree check.
* `Let f As Predicate(Of Integer) = Function(a) ...` was wrapped twice as a Func.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…rElse in expression trees

`Take While b` with `b As Boolean?` cast to bool and threw on Nothing, and
`Where b AndAlso x` in an IQueryable query didn't compile (CS0019). Providers
translate `b == true`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…hare range variable naming

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…ion predicates

Found by blind review:
* `n = 1 AndAlso Check` skipped calling Check when n was Nothing, since a VB call
  without parentheses looks like a name.
* `Into Count(n > 1)` over Integer? didn't compile; VB converts the predicate to
  Boolean (throwing for Nothing).
* An already-bool lifted comparison got a redundant `== true` in expression trees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…e NameOf of a member

Found by blind review:
* `Let a = F(x) Let b = G(x) Select a` evaluated G first, since b stayed a let while
  a moved to the final select.
* `NameOf(a.Member)` of a substituted range variable didn't compile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
`If n = 1 AndAlso 1 \ z = 0` evaluates the division in VB even when n is Nothing,
so the left can only become a lifted operator if the right is free of arithmetic,
narrowing conversions and user-defined operators as well as calls.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…d and delegate types

Found by blind review:
* A Let within an Aggregate clause was substituted past its Where/Order By, since
  the rules only looked at the outer query's clauses.
* A cheap value like a local was substituted into a lambda or nested query in the
  final Select, so read later than VB reads it.
* `From x As Object In ints` and `Let o As Integer? = x` lost the declared type.
* `Let f As Func(Of Integer) = AddressOf Five` didn't compile.

Also substitutes a single-use value into a Where, Let or first Order By key where
that keeps VB's evaluation, e.g. `Into Count() Where Count > 1`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…y what they hold

Found by blind review:
* Order By reads every element before evaluating any key, so a value substituted
  into it ran after earlier lets for all elements (or not at all for Count()).
* `Let d = y` where y was substituted with a call, or a field, counted as cheap or
  unchanging, reordering evaluation or reading the field too late.
* A Group By item can hold a lazy nested query, so reads a value as late as a Let.
* An anonymous type member name looked like a name a later range variable shadows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…son semantics

A provider is passed the first source, a join's inner source and Skip/Take counts
as values, so they're ordinary code rather than part of the expression tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
… convert Skip/Take counts

Found by a review guided by mutation testing and coverage:
* An Aggregate clause's source runs within the enclosing query's lambda (or as
  ordinary code for an initial Aggregate), so takes its semantics from there,
  not from the whole query.
* `Skip n` with a Long, or `Take 1.5`, didn't compile; VB converts to Integer.
* A named range variable was also registered as a plain declaration, keeping a
  needless let.

Also adds tests for gaps the mutation run found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
…d correct README examples

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019FEr8GSsdfh4WNGNkwrb9G
@GrahamTheCoder
GrahamTheCoder merged commit 82e9842 into icsharpcode:master Nov 9, 2026
3 checks passed
GrahamTheCoder added a commit that referenced this pull request Nov 9, 2026
Added note about Linq query conversion changes in pull request #1305.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment