Skip to content

Resolve the GetEnumerator call inside a foreach #16

erik-kallen opened this Issue Mar 5, 2012 · 5 comments

2 participants


I think it would be useful if resolving the iterator inside a foreach() somehow returned the invoked GetEnumerator method

ICSharpCode member

I don't think we should resolve only the GetEnumerator() call; if we start expanding the foreach pattern, we should also resolve the loop with the MoveNext() and get_Current() calls.
I'm not sure how to expose that in the API; unless we start exposing semantic trees for statements.


You are probably right. As a user of the API, though, it would be very handy not having to read, understand and correctly implement section 8.8.4 myself. I guess this is also needed to ensure that find references will find implicit usages of member in foreach, so once that is implemented it would be nice if the implementation were somehow published.

Failing test illustrating the problem as exposed by find references:

public void FindReferenceToGetEnumeratorUsedImplicitlyInForeach()
    Init(@"using System;
class MyEnumerable {
 public IEnumerator GetEnumerator();
class Test {
 static void T() {
  var x = new MyEnumerable();
  foreach (var y in x) {
    var test = compilation.MainAssembly.TopLevelTypeDefinitions.Single(t => t.Name == "MyEnumerable");
    var getEnumerator = test.Methods.Single(m => m.Name == "GetEnumerator");
    var actual = FindReferences(getEnumerator).ToList();
    Assert.That(actual.Count, Is.EqualTo(2));
    Assert.That(actual.Any(r => r.StartLocation == new TextLocation(3, 21)));
    Assert.That(actual.Any(r => r.StartLocation.Line == 8));
ICSharpCode member

True, find references on GetEnumerator should work in this case.
So I suggest we'll introduce a new resolve result for representing foreach:

class ForEachResolveResult : ResolveResult
    public ResolveResult GetEnumeratorCall { get; }
    public IType CollectionType { get; }
    public IType EnumeratorType { get; }

    public IType ElementType { get; }
    public IVariable ElementVariable { get; }

    public IProperty CurrentProperty { get; }
    public IMethod MoveNextMethod { get; }

Perhaps it should also include

public Conversion ConversionToIDisposable { get; }

since (if my understanding is correct), this might use an op_implicit.

ICSharpCode member

Implemented in 3e72441. I did not add the ConversionToIDisposable as op_Implicit calls are not possible there (C# does not allow user-defined implicit conversions to interface types).

@dgrunwald dgrunwald closed this Mar 7, 2012
@dgrunwald dgrunwald added a commit to icsharpcode/ILSpy that referenced this issue Apr 14, 2012
@dgrunwald dgrunwald Squashed 'NRefactory/' changes from b374e40..180a690
180a690 Create .pdb file in release build.
f074239 NRefactory release.
11ab30b Added custom event declaration case to code settings.
e0f3421 Add support for type forwarders.
bb27ef5 Fixed completion bug.
86fede3 Fixed anther system.core 3.5 vs. 4.0 type lookup case.
b277e75 Fixed GetClassTypeReference resolving error. Use case: Lib uses System.Core 3.5, Project 4.0 - the 3.5 assembly can't be resolved in the project context.
7dd4c63 Updated formatting tests.
04f8720 Added formatting factory - formatting options should be created with that.
ca289f5 Improved array initializer wrapping options.
3ec1d7b Fixed exception in create method action.
42f6bfb Fixed completion bug.
64ca5a0 Fixed completion bug.
9511d48 Added KeepCommentsAtFirstColumn option.
c882a84 Added space in named argument formatting option.
0326e93 Fixed other enum base type context.
bd20152 Fixed enum base type bug.
bfb4d50 Merge branch 'master' of
c0b97ae Updated mcs/fixes some unit tests.
d9a88ce Changed the action text of remove backing store action.
629bdce Fixed extract method link bug.
8478cc6 Merge branch 'master' of
b8dd515 Updated mcs.
eec8403 Added new lines between generated members.
e499b7a Updated mcs.
1576e08 Added some generated code member categories.
0cbca24 Added whitespace and text node. They are needed anyways, now the ast should be theretically round-trip complete.
c7e1236 Added NewLine ast node.
3eff925 Fixed code completion exception.
14ca306 Added function to create a DA object to the refactoring context.
484c142 Added some documentation.
f94402f Made it easier to get the issues out of the gather visitor.
7509ba5 Applied patch by Mansheng Yang to improve the remove braces action.
66a365e Updated mcs.
3761df4 Merge branch 'master' of
90eadb3 Fixed completion bug.
6669636 Fixed bug in parameter completion.
265a9ec Merge branch 'master' of
3932a6e Fixed failing completion tests.
374f1cb Fixed parameter completion bug.
53acb15 * ICSharpCode.NRefactory.CSharp.csproj: * SpecializedCodeAction.cs: * ConvertDecToHexAction.cs: * GeneratePropertyAction.cs: * CheckIfParameterIsNullAction.cs:
075ffe3 Fixed completion category bug.
6b3da28 Revert "Changed refactoring context behaviour. It now works on adjacent nodes"
1465739 Changed refactoring context behaviour. It now works on adjacent nodes as well.
1bc751b Added end inclusive GetNodeAt to AstNode.
c114f71 Added unit tests for the open mcs nrefactory related bugs. We should ensure that mcs doesn't regress there.
eb6a774 Fixed some issues in the output visitor. Note that the block statement newline should be done more elegant (new lines should be done in the parent).
6c96156 [NRefactory] Fixed CurrentType check for some actions.
50aa6e0 Fixed a case where extract method returned null.
8111e26 Add issue provider for explicit conversions in foreach loops.
9e1d371 Fixed RedundantUsingIssue to no longer remove "System.Linq" if it is required for a query expression.
f098db8 Fix bugs in RedundantNamespaceUsageIssue and CreatePropertyAction.
0a8825e Fix build of NR.ConsistencyCheck.
656093a [FastSerializer] Added bugfix from Marek Safar.
3ccf18d ResolveAtLocation now uses resolve visitor navigator.
9e622c1 Create class action can now generate interface implementation. Need to think about that feature, maybe just adding the base type is better and letting the user choose implicit/explicit implementation ?
69a7136 Fixed remove brace action tests.
83d4cb2 Fixed link mode in extract method/introduce constant action.
8444dff Startet exctract method action.
b4b3e64 Improved type guessing.
ceef571 Added introduce constant action.
4644a07 Fixed method declaration case.
a627665 Merge branch 'master' of
bb4cafa Fixed null reference exception in control flow graph builder.
44f8d23 Merge branch 'master' of
cfe6272 Fixed possible null exception in control flow node.
8bb2301 Fixed tests.
769ea3e Merge branch 'master' of
a851b1c Fixed indenting behaviour of comments and directives.
444fe4e Make IParsedFile.LastWriteTime nullable.
048a4b9 Updated Fdg rules.
4f47170 Fixed type inference bug introduced in 2e40a34 - array covariance was ignored.
deb6bcd Add CancellationToken to AXmlParser.
b21e85f Updated indent engine.
2ec03c2 Added a text editor options class that contains options for text output.
e5d6452 Code completion name propsoal now uses the word parser to break words.
d85bb0e Fixed completion bug.
acce74e Fixed bug in create method declaration action.
5012f3f Handled static class <--> non static member clash in create field/method/property actions.
c3aea07 Turn off issue marker for var keyword issue (handled by action).
af87519 Removed debug message.
89ee8bc Allow '_' and 'm_' as field prefix name.
256dae8 Fixed create method declaration case.
34b3e18 Adjusted default Fdg rules a bit (private static fields are now camelCase).
62ebfc7 Disabled out name filter for create field,property and method.
b1dfdba Added create delegate action.
718dfe4 Added more cases for create class declaration.
93fb777 Added flag to specify if explict types should be used or not.
9e070b9 Hide not implemented exception issue in the text editor.
c33d15e Fixed bug where code actions could be null.
6b61741 Added create class declaration action.
d4f9318 Added create constructor declaration action/fixed bugs in other creation actions.
2d80884 Fixed failing unit tests.
bcf36de Fixed find type parameter references.
8c55a4e Fixed type parameter rename dialog action.
99270db Fixed type parameter naming.
795e6c8 Improved naming issue checking for some special cases of entities.
98e7a57 Fixed type parameter naming rule.
9ab32dc Fixed inconsistent naming issues.
a14ed3b Fixed inconsistent naming tests.
74e365b DeclareLocal variable action now links the identifiers.
1ca41d1 Added declare local variable action.
b6bdb90 Added inline local variable action.
9ec0d68 Added create indexer action.
627bbb7 Fixed parameter name guessing.
0b6ca98 Handled create method/property in other types.
635af4b Don't show create local/field/property on invocations.
402e112 Fixed create static field/property.
ee71c30 Merge branch 'master' of
a234f8b Create actions now respect naming convention settings.
ce7bdd7 Added IServiceProvided infrastructure for the refactoring context.
cb60935 Use ImproveDReturnAllResults type inference algorithm in GuessType.
b5bd653 Leave upper bounds empty.
1d3d3df Merge branch 'master' of
52ebb26 Added create method declaration action/use type inference to guess the correct type.
75b6cc6 Enabled generate getter/property tests.
0c6ea80 Fixed create field, local and property actions.
003b8c9 Added more entities & missing flags.
604011b Fixed check of visibility mask.
fcfbbdb Completed the features of the inconsistent naming issue.
0a55295 Added compiler warnings & errors issue categories.
5e7b449 Set namespace naming rule name.
3e256c4 Added default names for fdg naming rules.
293859f Naming rules now get their rules out of the refactoring context.
fba2d7c ITextSource.MoveOffsetTo: make AnchorMovementType parameter optional.
daa1cff Remove BaseRefactoringContext.StartScript().
439010a Added some inconsistent naming tests.
6b41506 Added missing is null or empty inspector cases.
41d5b50 Worked on inconsistent naming issue.
a179782 Fixed code completion bug.
193a153 Fixed completion bug.
e282837 Fixed parameter completion issue.
9fb443a Improved code issue tests - renamed some issues and actions.
296fc86 Fixed some translation strings/code issues can now offer more actions.
e54b06b Disable the failing unit tests.
6ef14c2 Added documentation for issue severity.
acfcf37 Changed the ContextAction/Inspector API.
3915a4c Add IsEligibleExtensionMethod to public API.
82af219 Added TranslateString method to the context.
ddc74b3 [UnitTests] Track API changes.
615248e Renamed InspectionIssue to CodeIssue.
436eab7 Corrected name token start/end node calls.
974879b Applied sharpdevelop formatting style.
b41059f Added check for links in the context action tests.
16ea65a Started to implement tests for the inspectors.
66dfd28 Fixed context action tests.
8e66275 Fixed unit test.
b6ad6d4 RedundantUsingInspector: visit simple type.
bf71baf Implemented redundant using inspector.
9771b6d Fix icsharpcode/NRefactory#33: Determining if a ThisResolveResult represents this. or base.
a3ced27 Simplified several inspectors. Includes some minor bugfixes.
61d6c02 Fixed loop variable bug.
8d0abbe Fix icsharpcode/NRefactory#30: Target of extension method invocation
d4dd164 Implemented the new options for overridden members in FindReferences.
3336a43 Fixed redundant this inspector.
df285ae Merge branch 'master' of
efa4b0b Added more inspectors.
ac49370 Simplify ConditionalToNullCoalescingInspector using pattern matching.
c3feace Merge branch 'master' of
141829a Started inspection API.
eab8372 Fixed resolver crash when resolving the arguments of an ObjectCreateExpression with unresolved type (e.g. due to missing using).
2e40a34 FindReferences: API idea for new options
b3acaaf Added support for specialized members to InheritanceHelper.GetBaseMember().
777be39 Rewrite of the substitution logic in SpecializedMember.
7474cdb Fixed member reference expression bug.
afbf9c9 Fixed for variable initializer name context.
af6c3b2 Updated mcs.
bf42e08 Add support for IReadOnlyList<T>.
e213758 Replace LazyInit.ReadBarrier() with LazyInit.VolatileRead().
1713776 Fixed warnings.
be4e8bb Added function to get the word segment at caret position.
af7cccf Merge branch 'master' of
54b3bae Fixed possible null reference exception.
f78b052 Fixed bug in override completion.
e2c8922 Fixed formatting filter.
d07356a Fixed ast formatter.
c51a5f6 Fixed stub mechanic.
29da952 Fixed some warnings.
6f4a46c Fixed failing unit test.
837d48d Completion engine now works on freezed compilation units.
40a00e7 GetMemberTextToCaret now gives back the correct member start location.
11b8c3b Removed IRelocatable infrastructure - the start line could now be altered in the lexer directly.
9393ea6 [Refactoring] Refactoring context resolver is now protected.
0907829 Fixed ref/out/params keywords.
d338acc Fix icsharpcode/NRefactory#18: ResolveResult for object creation
ab024b9 Fix icsharpcode/NRefactory#28: Identity of lambda parameters
a798d1a Fixed override completion data bug.
ce2e528 Documentation update.
47d7d5a Fix icsharpcode/NRefactory#29: NullReferenceException when using FindReferencedEntities navigator
08e6a88 AppendMissingClosingBrackets is now reusable.
51bd416 Correctly set OperatorResolveResult.IsLiftedOperator in more cases.
df380b6 Fixed potential cause of CSharpAstResolver.Resolve returning null.
e80f142 Fixed bug in CSharpAstResolver.GetExpectedType().
f74bf90 Make AstNode freezable.
4465839 Fixed error caused by Root role. Ok now I know why it needs to be there :)
2c97bfa Added more location checks / added -verbose command line option for the ast verifier.
6c5b439 Added little command line tool to test the AST roundtrip.
cf134db Fixed potential null reference exception.
da0d25b GtkDemo now uses standard text view.
3c350c1 Merge branch 'master' of
55f858e Fix icsharpcode/NRefactory#26: Static methods are reported as having "this" as the target
3ac1e56 Fix icsharpcode/NRefactory#22: Event accessors should be called add_X and remove_X
c27f57f Fix icsharpcode/NRefactory#25: OperatorResolveResult.IsLiftedOperator for unary operators
4ea7ebc Moved more roles to the Roles class/Changed TypeDeclaration representation (saves some memory and class type is now always defined).
749a13c formatting visitor now does either place if statement on new line or indent the embedded statement - not both.
cd349d2 Fixed some issues in the formatter.
0b3b290 Fixed case label indentation.
45cab9b Fixed an issue with overlapping segments/fixed failing unit test.
3503318 Track role name changes in nrefactory.c#.
6a0a96c Moved some roles to the Roles class.
90bf204 Moved the roles class out of AstNode.
e93009a Fixed context action unit tests.
5d33b31 Revert "Refactoring context now exposes the document instead of the document"
3d4550c Refactoring context now exposes the document instead of the document like functions.
b44d6c6 Fixed typo.
5e93376 Took out ifdef. (I suppose that patch wont make it upstream)
473f6a7 Added some additional bounds check. As the parser improves they may become required.
ae28762 Fixed destructor identifier.
b491ea8 Rename Conversions to CSharpConversions.
3df0cd3 Make CSharpAstResolver and Conversions thread-safe.
cf331bb Fixed resolving partial method definitions.
24d2d19 Use specialized method for MethodGroupConversion. icsharpcode/NRefactory#21
a731b93 Fix icsharpcode/NRefactory#19: OperatorResolveResult.IsLiftedOperator is false for lifted built-in operators.
3215504 Fix icsharpcode/NRefactory#20: Copy virtual/override/static/etc. modifiers from properties/events to accessor methods.
3fbcf2f Add support for partial methods.
c3d00d1 Add StringBuilderDocument to NR.Editor.
bcad2e1 DocumentScript bugfixes.
8179556 Add DocumentScript that implements Script using a mutable document.
c6ae6c3 Script refactoring.
61c4481 [FindReferences] Added destructor find support.
a76cab2 Merge branch 'master' of
cfe0d42 Made resolve result == null assertion more verbose.
abe5ca4 Merge branch 'master' of
fe8e098 Fixed some FxCop warnings.
cbd5a46 Enabled working unit test.
fdfdffb Fixed several query expression locations.
a360992 Fixed type parameter comma locations.
12c0472 Fixed incorrect parser positions in FixedStatement test.
5a9d33f Fixed attribute empty arglist parens.
f1fa0e0 Enabled working unit test.
d6d1f08 Fixed ignored unit test.
1100022 [UnitTests] Track API changes.
b4c1946 Added CancellationToken support for the context actions.
d0618b4 Set version number to
eba0218 FindReferences for IEnumerator.Current now finds foreach statements.
b06160b No longer require a specifil nunit version.
5dfe563 Fixed naming.
96e434e Added GenerateProperty context action.
3e72441 Fix icsharpcode/NRefactory#16: Resolve the GetEnumerator call inside a foreach
fb0dbc9 Fix icsharpcode/NRefactory#17: Resolving "is" and "as" expressions loses the semantics
2ede14a Disabled loction changes by the #line directive.
1503054 TextReplace actions can now depend on each other.
4499d32 Fixed IsInsideDocComment method. TODO: Move the detection of comments & string regions to the IMemberProvider (needs rename) and handle that with a tree on IDE level.
e058867 Fixed interface return type tests.
6eaa0fd Fixed interface return type test.
05fc277 Added interface return types test.
36456b4 Updated mcs & improved try context handling.
fa2db3b Fixed anonymous method brace style formatting.
b13dad1 Resolve visitor change: If the type of an object create expression can't be resolved give back the type resolution failure. This is required to tell why the object creation couldn't be resolved.
11ab326 Readded the 'IsInside' function that checks the position inclusive the end location.
a55cbb4 Semantic change: Contains now excludes the end location.
964b6c0 Fixed unit test.
d284cbb Remove region context action is now more efficient in choosing the subtrees to analyze.
de443b7 Fixed possible exception in create event incocation context action.
a353f23 Combine AttributedNode and MemberDeclaration into EntityDeclaration.
b416f38 CSharpAmbience: allow passing in a custom IOutputFormatter.
d6f3c84 Replace ConversionFlags.UseFullyQualifiedMemberNames with ConversionFlags.ShowDeclaringType.
e8f0928 Add support for calling constructors on COM interfaces.
e436347 * AstFormattingVisitor.cs: Fixed bug in binary operator expression.
7451607 Added "RemoveRegion" context action.
b91ed7e Fixed get current parameter index.
c0deae7 Fixed 2 mcs issues.
3813344 Updated mcs & added unit test.
670975c Parameter data providers now contain the start offset of their expression (makes it easier to count the correct parameter number).
4575266 Filter out members that are not suited for code completion.
c1a777b Applied a similiar handling for field initializers than for the binary operator line breaks.
47c5b9f Improved binary operator line break handling.
e2b3043 Fixed using declaration context.
698164a Merge branch 'master' of
95ebebc Updated mcs.
008e961 Fixed build under mono.
ab7a24e Removed code duplication. btw. was the worst case of duplication - the methods should do the same but had slightly different semantics.
338bedc Used simpler Identifier.Create calls.
b0de873 Fixed some more attribute completion tests.
e394fb5 Added some more attribute context tests & fixes.
288ab73 Fixed some completion tests.
f49f142 Fixed parameter completion unit test.
47d00e1 Added banner style brace output format.
c22e11d Added banner style brace style.
a993df9 Use simpler IAstVisitor for InsertParenthesesVisitor and TypeSystemConvertVisitor.
2f85914 Use simpler IAstVisitor for ResolveVisitor.
3eee346 CSharpOutputVisitor is now using the IAstVisitor with void return type.
0ffe61e Trim whitespace within XmlDocumentationElements.
a0f7de3 Fixed modifier issues in TypeSystemAstBuilder
5bef6f2 Added some comments for the token classes.
3ae2fe7 The formatting visitor is now using an easier visitor pattern.
47bd60c Removed debug message.
24f5bc9 Fixed bug in operator declaration getrole function.
3ffbaa2 Refactored c# token representation, it's now more consistent with the other nodes and takes up a bit less memory.
73e63dd Added GetText function to AstNode.
196e618 Added some Parse methods to the compilation unit.
72d1381 Provided IAstVisitor and IAstVisitor<T> visitor patterns.
c180304 Fix DocumentationElement.IsTextNode for the root element.
d47cb9d Fix icsharpcode/NRefactory#15
944ba9c Fixed formatting bug.
14bf452 Rename InterfaceImplementations -> ImplementedInterfaceMembers.
274fe41 Add "XmlDocumentationElement", a simplified tree for XML documentation comments that expands "<inheritdoc/>"
18c96e0 Add support for multiline XML documentation comments.
59c9e99 DefaultResolvedTypeDefinition: lazily initialize the list of members.
e52e57e Fixed crash in CSharpAmbience on delegate declarations.
00743d5 Fix project options.
def9943 Add AXmlObject.CreateReader() method.
2c7c1c7 Fixed failing unit test, added a test to document a wrong parser behaviour.
54b6c57 Added some bounds checking.
cb576fb * ICSharpCode.NRefactory.csproj: * IdStringProvider.cs: * IDStringTests.cs: * DocumentationComment.cs: * IdStringMemberReference.cs: * XmlDocumentationProvider.cs: * IDStringConsistencyCheck.cs: * CSharpCrefLookupTests.cs: Renamed IDString -> IdString to follow   .NET naming guidelines.
a21ee06 Added easier string translation for documentation comment class.
d757e48 Fixed possible null reference exception.
c74577a Updated mcs.
d8d65fc Fixed code completion bug.
ca41af4 Add TagMatchingHeuristics.
ea14dc8 Updated parameter data provider interface.
d280684 Put properly nested elements into AXmlElement.
d62f366 Add null node for VariableInitializer.
32626ac Implemented incremental tag soup parser.
06bf2f4 Add consistency check for incremental tag soup parser
191ac7c Use GlobalAssemblyInfo.cs for all projects.
2faf35e Add ICSharpCode.NRefactory.Xml.
29c1b59 Add ICompilation.Assemblies.
2bebee4 C# XML documentation support.
b31e104 Protect against [InternalsVisibleTo] stack overflow and fixed a possible cause for that stack overflow
bd9348d Add documentation about XML documentation.
ec225c1 Fixed bugs related to ID strings.
ee92c68 TypeParameterReference now resolves to a dummy type parameter instead of UnknownType when no ITypeParameter is available in the resolve context.
7a76a80 Add DocumentationComment class that allows looking up 'cref' attributes.
4632c42 Fixed unit test.
de6870b Fixed completion unit test.
d89d25c Added failing unit test.
a6fa72e Fixed constructor initializer parameter completion.
3c3840b Cleaned up code a bit.
789e0cc Cleaned up code a bit.
c3b136b Fixed attribute context cases.
0983e85 Fixed some keyword contexts.
d03d17b Use lazy initialization for C# resolved type definitions.
9df7940 Normalize newlines.
01b538f Fix CSharpToVBConverterVisitor (use Pattern.AnyString).

git-subtree-dir: NRefactory
git-subtree-split: 180a690f373354796520d9468138d95f193f8156
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.