File: ResolverTestBase.cs

package info (click to toggle)
monodevelop 4.0.12%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 219,596 kB
  • ctags: 253,200
  • sloc: cs: 1,486,058; xml: 952,347; java: 60,981; makefile: 4,213; sh: 1,727; ansic: 867; objc: 302; sql: 111
file content (272 lines) | stat: -rw-r--r-- 10,433 bytes parent folder | download | duplicates (4)
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
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Parser;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using NUnit.Framework;

namespace ICSharpCode.NRefactory.CSharp.Resolver
{
	/// <summary>
	/// Base class with helper functions for resolver unit tests.
	/// </summary>
	public abstract class ResolverTestBase
	{
		protected readonly IUnresolvedAssembly mscorlib = CecilLoaderTests.Mscorlib;
		protected IProjectContent project;
		protected ICompilation compilation;
		
		[SetUp]
		public virtual void SetUp()
		{
			project = new CSharpProjectContent().AddAssemblyReferences(new [] { mscorlib, CecilLoaderTests.SystemCore });
			compilation = project.CreateCompilation();
		}
		
		protected IType ResolveType(Type type)
		{
			IType t = compilation.FindType(type);
			if (t.Kind == TypeKind.Unknown)
				throw new InvalidOperationException("Could not resolve type");
			return t;
		}
		
		protected ConstantResolveResult MakeConstant(object value)
		{
			if (value == null)
				return new ConstantResolveResult(SpecialType.NullType, null);
			IType type = ResolveType(value.GetType());
			if (type.Kind == TypeKind.Enum)
				value = Convert.ChangeType(value, Enum.GetUnderlyingType(value.GetType()));
			return new ConstantResolveResult(type, value);
		}
		
		protected ResolveResult MakeResult(Type type)
		{
			return new ResolveResult(ResolveType(type));
		}
		
		protected static TypeOrNamespaceReference MakeReference(string namespaceName)
		{
			string[] nameParts = namespaceName.Split('.');
			TypeOrNamespaceReference r = new SimpleTypeOrNamespaceReference(nameParts[0], new ITypeReference[0], NameLookupMode.TypeInUsingDeclaration);
			for (int i = 1; i < nameParts.Length; i++) {
				r = new MemberTypeOrNamespaceReference(r, nameParts[i], new ITypeReference[0]);
			}
			return r;
		}
		
		protected void AssertConstant(object expectedValue, ResolveResult rr)
		{
			Assert.IsFalse(rr.IsError, rr.ToString() + " is an error");
			Assert.IsTrue(rr.IsCompileTimeConstant, rr.ToString() + " is not a compile-time constant");
			Type expectedType = expectedValue.GetType();
			Assert.AreEqual(ResolveType(expectedType), rr.Type, "ResolveResult.Type is wrong");
			if (expectedType.IsEnum) {
				Assert.AreEqual(Enum.GetUnderlyingType(expectedType), rr.ConstantValue.GetType(), "ResolveResult.ConstantValue has wrong Type");
				Assert.AreEqual(Convert.ChangeType(expectedValue, Enum.GetUnderlyingType(expectedType)), rr.ConstantValue);
			} else {
				Assert.AreEqual(expectedType, rr.ConstantValue.GetType(), "ResolveResult.ConstantValue has wrong Type");
				Assert.AreEqual(expectedValue, rr.ConstantValue);
			}
		}
		
		protected void AssertType(Type expectedType, ResolveResult rr)
		{
			Assert.IsFalse(rr.IsError, rr.ToString() + " is an error");
			Assert.IsFalse(rr.IsCompileTimeConstant, rr.ToString() + " is a compile-time constant");
			Assert.AreEqual(compilation.FindType(expectedType), rr.Type);
		}
		
		protected void AssertError(Type expectedType, ResolveResult rr)
		{
			Assert.IsTrue(rr.IsError, rr.ToString() + " is not an error, but an error was expected");
			Assert.IsFalse(rr.IsCompileTimeConstant, rr.ToString() + " is a compile-time constant");
			Assert.AreEqual(compilation.FindType(expectedType), rr.Type);
		}
		
		protected void TestOperator(UnaryOperatorType op, ResolveResult input,
		                            Conversion expectedConversion, Type expectedResultType)
		{
			CSharpResolver resolver = new CSharpResolver(compilation);
			var rr = resolver.ResolveUnaryOperator(op, input);
			AssertType(expectedResultType, rr);
			Assert.AreEqual(typeof(OperatorResolveResult), rr.GetType());
			var uorr = (OperatorResolveResult)rr;
			AssertConversion(uorr.Operands[0], input, expectedConversion, "Conversion");
		}
		
		protected void TestOperator(ResolveResult lhs, BinaryOperatorType op, ResolveResult rhs,
		                            Conversion expectedLeftConversion, Conversion expectedRightConversion, Type expectedResultType)
		{
			CSharpResolver resolver = new CSharpResolver(compilation);
			var rr = resolver.ResolveBinaryOperator(op, lhs, rhs);
			AssertType(expectedResultType, rr);
			Assert.AreEqual(typeof(OperatorResolveResult), rr.GetType());
			var borr = (OperatorResolveResult)rr;
			AssertConversion(borr.Operands[0], lhs, expectedLeftConversion, "Left conversion");
			AssertConversion(borr.Operands[1], rhs, expectedRightConversion, "Right conversion");
		}
		
		protected void AssertConversion(ResolveResult conversionResult, ResolveResult expectedRR, Conversion expectedConversion, string text)
		{
			if (expectedConversion == Conversion.IdentityConversion) {
				Assert.AreSame(expectedRR, conversionResult, "Expected no " + text);
			} else {
				ConversionResolveResult crr = conversionResult as ConversionResolveResult;
				Assert.IsNotNull(crr, "Could not find ConversionResolveResult for " + text);
				Assert.AreEqual(expectedConversion, crr.Conversion, text);
				Assert.AreSame(expectedRR, crr.Input, "Input of " + text);
			}
		}
		
		protected IEnumerable<TextLocation> FindDollarSigns(string code)
		{
			int line = 1;
			int col = 1;
			foreach (char c in code) {
				if (c == '$') {
					yield return new TextLocation(line, col);
				} else if (c == '\n') {
					line++;
					col = 1;
				} else {
					col++;
				}
			}
		}
		
		protected Tuple<CSharpAstResolver, AstNode> PrepareResolver(string code)
		{
			SyntaxTree syntaxTree = new CSharpParser().Parse(code.Replace("$", ""), "code.cs");
			
			TextLocation[] dollars = FindDollarSigns(code).ToArray();
			Assert.AreEqual(2, dollars.Length, "Expected 2 dollar signs marking start+end of desired node");
			
			SetUp();
			
			CSharpUnresolvedFile unresolvedFile = syntaxTree.ToTypeSystem();
			project = project.AddOrUpdateFiles(unresolvedFile);
			compilation = project.CreateCompilation();
			
			CSharpAstResolver resolver = new CSharpAstResolver(compilation, syntaxTree, unresolvedFile);
			return Tuple.Create(resolver, FindNode(syntaxTree, dollars[0], dollars[1]));
		}
		
		protected ResolveResult Resolve(string code)
		{
			var prep = PrepareResolver(code);
			Debug.WriteLine(new string('=', 70));
			Debug.WriteLine("Starting new resolver for " + prep.Item2);
			
			ResolveResult rr = prep.Item1.Resolve(prep.Item2);
			Assert.IsNotNull(rr, "ResolveResult is null - did something go wrong while navigating to the target node?");
			Debug.WriteLine("ResolveResult is " + rr);
			return rr;
		}
		
		protected Conversion GetConversion(string code)
		{
			var prep = PrepareResolver(code);
			return prep.Item1.GetConversion((Expression)prep.Item2);
		}
		
		protected IType GetExpectedType(string code)
		{
			var prep = PrepareResolver(code);
			return prep.Item1.GetExpectedType((Expression)prep.Item2);
		}
		
		protected T Resolve<T>(string code) where T : ResolveResult
		{
			ResolveResult rr = Resolve(code);
			Assert.IsNotNull(rr);
			if (typeof(T) == typeof(LambdaResolveResult)) {
				Assert.IsTrue(rr is LambdaResolveResult, "Resolve should be " + typeof(T).Name + ", but was " + rr.GetType().Name);
			} else {
				Assert.IsTrue(rr.GetType() == typeof(T), "Resolve should be " + typeof(T).Name + ", but was " + rr.GetType().Name);
			}
			return (T)rr;
		}
		
		protected AstNode FindNode(SyntaxTree syntaxTree, TextLocation start, TextLocation end)
		{
			FindNodeVisitor fnv = new FindNodeVisitor(start, end);
			syntaxTree.AcceptVisitor(fnv);
			Assert.IsNotNull(fnv.ResultNode, "Did not find DOM node at the specified location");
			return fnv.ResultNode;
		}
		
		sealed class FindNodeVisitor : DepthFirstAstVisitor
		{
			readonly TextLocation start;
			readonly TextLocation end;
			public AstNode ResultNode;
			
			public FindNodeVisitor(TextLocation start, TextLocation end)
			{
				this.start = start;
				this.end = end;
			}
			
			protected override void VisitChildren(AstNode node)
			{
				if (node.StartLocation == start && node.EndLocation == end) {
					if (ResultNode != null)
						throw new InvalidOperationException("found multiple nodes with same start+end");
					ResultNode = node;
					return;
				}
				base.VisitChildren(node);
			}
		}
		
		protected ResolveResult ResolveAtLocation(string code)
		{
			SyntaxTree syntaxTree = SyntaxTree.Parse(code.Replace("$", ""), "test.cs");
			
			TextLocation[] dollars = FindDollarSigns(code).ToArray();
			Assert.AreEqual(1, dollars.Length, "Expected 1 dollar signs marking the location");
			
			SetUp();
			
			CSharpUnresolvedFile unresolvedFile = syntaxTree.ToTypeSystem();
			project = project.AddOrUpdateFiles(unresolvedFile);
			compilation = project.CreateCompilation();
			
			ResolveResult rr = Resolver.ResolveAtLocation.Resolve(compilation, unresolvedFile, syntaxTree, dollars[0]);
			return rr;
		}
		
		protected T ResolveAtLocation<T>(string code) where T : ResolveResult
		{
			ResolveResult rr = ResolveAtLocation(code);
			Assert.IsNotNull(rr);
			Assert.IsTrue(rr.GetType() == typeof(T), "Resolve should be " + typeof(T).Name + ", but was " + rr.GetType().Name);
			return (T)rr;
		}
	}
}