2 // Permission is hereby granted, free of charge, to any person obtaining
3 // a copy of this software and associated documentation files (the
4 // "Software"), to deal in the Software without restriction, including
5 // without limitation the rights to use, copy, modify, merge, publish,
6 // distribute, sublicense, and/or sell copies of the Software, and to
7 // permit persons to whom the Software is furnished to do so, subject to
8 // the following conditions:
10 // The above copyright notice and this permission notice shall be
11 // included in all copies or substantial portions of the Software.
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
16 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
17 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
18 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
19 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 // Copyright (C) Lluis Sanchez Gual, 2004
26 using System.Reflection;
27 using System.Reflection.Emit;
28 using Mono.CodeGeneration;
30 namespace Mono.CodeGeneration
32 public class CodeCast: CodeExpression
37 public CodeCast (Type type, CodeExpression exp)
43 public override void Generate (ILGenerator gen)
47 Type typeObj = exp.GetResultType ();
49 if (type.IsAssignableFrom (typeObj)) {
50 if (typeObj.IsValueType)
51 gen.Emit (OpCodes.Box, typeObj);
54 else if (type.IsValueType && typeObj == typeof(object)) {
56 gen.Emit (OpCodes.Unbox, type);
57 CodeGenerationHelper.LoadFromPtr (gen, type);
60 else if (typeObj.IsAssignableFrom (type)) {
62 gen.Emit (OpCodes.Castclass, type);
65 else if (CodeGenerationHelper.IsNumber (type) && CodeGenerationHelper.IsNumber (typeObj)) {
66 switch (Type.GetTypeCode (type))
69 gen.Emit (OpCodes.Conv_U1);
72 gen.Emit (OpCodes.Conv_R8);
75 gen.Emit (OpCodes.Conv_I2);
78 gen.Emit (OpCodes.Conv_I4);
81 gen.Emit (OpCodes.Conv_I8);
84 gen.Emit (OpCodes.Conv_I1);
87 gen.Emit (OpCodes.Conv_R4);
90 gen.Emit (OpCodes.Conv_U2);
93 gen.Emit (OpCodes.Conv_U4);
96 gen.Emit (OpCodes.Conv_U8);
101 MethodInfo imp = type.GetMethod ("op_Implicit", new Type[] { typeObj });
103 gen.Emit (OpCodes.Call, imp);
107 foreach (MethodInfo m in typeObj.GetMember ("op_Explicit"))
108 if (m.ReturnType == type) {
109 gen.Emit (OpCodes.Call, m);
113 throw new InvalidOperationException ("Can't cast from " + typeObj + " to " + type);
116 public override void PrintCode (CodeWriter cp)
118 Type typeObj = exp.GetResultType ();
119 if (type.IsAssignableFrom (typeObj)) {
124 cp.Write ("((" + type.FullName + ") ");
129 public override Type GetResultType ()