Simple impl to MockRailsEngineContext.Url
[castle.git] / Tools / DynamicProxy / Castle.DynamicProxy / Builder / CodeBuilder / SimpleAST / ConvertExpression.cs
blobcd89d821d5f24000b00f24471e565259251d5ee5
1 // Copyright 2004-2007 Castle Project - http://www.castleproject.org/
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 namespace Castle.DynamicProxy.Builder.CodeBuilder.SimpleAST
17 using System;
18 using System.Reflection.Emit;
20 using Castle.DynamicProxy.Builder.CodeBuilder.Utils;
22 /// <summary>
23 /// Summary description for ConvertExpression.
24 /// </summary>
25 [CLSCompliant(false)]
26 public class ConvertExpression : Expression
28 private Type _target;
29 private Type _fromType;
30 private Expression _right;
32 public ConvertExpression( Type targetType, Expression right ) : this(targetType, typeof(object), right)
36 public ConvertExpression( Type targetType, Type fromType, Expression right )
38 _target = targetType;
39 _fromType = fromType;
40 _right = right;
43 public override void Emit(IEasyMember member, ILGenerator gen)
45 _right.Emit(member, gen);
47 if (_fromType == _target)
49 return;
52 if (_fromType.IsByRef)
54 throw new NotSupportedException("Cannot convert from ByRef types");
57 if (_target.IsByRef)
59 throw new NotSupportedException("Cannot convert to ByRef types");
62 if (_target.IsValueType)
64 if (_fromType.IsValueType)
66 throw new NotImplementedException("Cannot convert between distinct value types at the moment");
68 else
70 // Unbox conversion
71 // Assumes fromType is a boxed value
72 gen.Emit(OpCodes.Unbox, _target);
73 OpCodeUtil.EmitLoadIndirectOpCodeForType(gen, _target);
76 else
78 if (_fromType.IsValueType)
80 // Box conversion
81 gen.Emit(OpCodes.Box, _fromType);
82 EmitCastIfNeeded(typeof(object), _target, gen);
84 else
86 // Possible down-cast
87 EmitCastIfNeeded(_fromType, _target, gen);
92 private void EmitCastIfNeeded(Type from, Type target, ILGenerator gen)
94 if (target.IsSubclassOf(from))
96 gen.Emit(OpCodes.Castclass, target);