/src/Boo.Lang.Compiler/Steps/EmitAssembly.cs
C# | 5680 lines | 4675 code | 807 blank | 198 comment | 887 complexity | af1838b67c0ca4a5b3a2b75e2abbb7b1 MD5 | raw file
Possible License(s): GPL-2.0
Large files files are truncated, but you can click here to view the full file
- #region license
- // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
- // All rights reserved.
- //
- // Redistribution and use in source and binary forms, with or without modification,
- // are permitted provided that the following conditions are met:
- //
- // * Redistributions of source code must retain the above copyright notice,
- // this list of conditions and the following disclaimer.
- // * Redistributions in binary form must reproduce the above copyright notice,
- // this list of conditions and the following disclaimer in the documentation
- // and/or other materials provided with the distribution.
- // * Neither the name of Rodrigo B. de Oliveira nor the names of its
- // contributors may be used to endorse or promote products derived from this
- // software without specific prior written permission.
- //
- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
- // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- #endregion
-
- using System;
- using System.Collections;
- using System.Diagnostics;
- using System.Diagnostics.SymbolStore;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Resources;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading;
- using System.Security;
- using Boo.Lang.Compiler.Ast;
- using Boo.Lang.Compiler.TypeSystem.Services;
- using Boo.Lang.Compiler.Util;
- using Boo.Lang.Compiler.TypeSystem;
- using Boo.Lang.Compiler.TypeSystem.Generics;
- using Boo.Lang.Compiler.TypeSystem.Internal;
- using Boo.Lang.Compiler.TypeSystem.Reflection;
- using Boo.Lang.Runtime;
- using Attribute = Boo.Lang.Compiler.Ast.Attribute;
- using Module = Boo.Lang.Compiler.Ast.Module;
- using System.Collections.Generic;
- using Method = Boo.Lang.Compiler.Ast.Method;
- using ExceptionHandler = Boo.Lang.Compiler.Ast.ExceptionHandler;
-
- namespace Boo.Lang.Compiler.Steps
- {
- sealed class LoopInfo
- {
- public Label BreakLabel;
-
- public Label ContinueLabel;
-
- public int TryBlockDepth;
-
- public LoopInfo(Label breakLabel, Label continueLabel, int tryBlockDepth)
- {
- BreakLabel = breakLabel;
- ContinueLabel = continueLabel;
- TryBlockDepth = tryBlockDepth;
- }
- }
-
- public class EmitAssembly : AbstractFastVisitorCompilerStep
- {
- static ConstructorInfo DebuggableAttribute_Constructor = Methods.ConstructorOf(() => new DebuggableAttribute(DebuggableAttribute.DebuggingModes.Default));
-
- static ConstructorInfo RuntimeCompatibilityAttribute_Constructor = Methods.ConstructorOf(() => new System.Runtime.CompilerServices.RuntimeCompatibilityAttribute());
-
- static ConstructorInfo SerializableAttribute_Constructor = Methods.ConstructorOf(() => new SerializableAttribute());
-
- static PropertyInfo[] RuntimeCompatibilityAttribute_Property = new[] { Properties.Of<System.Runtime.CompilerServices.RuntimeCompatibilityAttribute, bool>(a => a.WrapNonExceptionThrows) };
-
- static ConstructorInfo DuckTypedAttribute_Constructor = Methods.ConstructorOf(() => new DuckTypedAttribute());
-
- static ConstructorInfo ParamArrayAttribute_Constructor = Methods.ConstructorOf(() => new ParamArrayAttribute());
-
- static MethodInfo RuntimeServices_NormalizeArrayIndex = Methods.Of<Array, int, int>(RuntimeServices.NormalizeArrayIndex);
-
- static MethodInfo RuntimeServices_ToBool_Object = Types.RuntimeServices.GetMethod("ToBool", new Type[] { Types.Object });
-
- static MethodInfo RuntimeServices_ToBool_Decimal = Types.RuntimeServices.GetMethod("ToBool", new Type[] { Types.Decimal });
-
- static MethodInfo Builtins_ArrayTypedConstructor = Types.Builtins.GetMethod("array", new Type[] { Types.Type, Types.Int });
-
- static MethodInfo Builtins_ArrayGenericConstructor = Types.Builtins.GetMethod("array", new Type[] { Types.Int });
-
- static MethodInfo Builtins_ArrayTypedCollectionConstructor = Types.Builtins.GetMethod("array", new Type[] { Types.Type, Types.ICollection });
-
- private static MethodInfo Array_get_Length = Methods.GetterOf<Array, int>(a => a.Length);
-
- static MethodInfo Math_Pow = Methods.Of<double, double, double>(Math.Pow);
-
- static ConstructorInfo List_EmptyConstructor = Types.List.GetConstructor(Type.EmptyTypes);
-
- static ConstructorInfo List_ArrayBoolConstructor = Types.List.GetConstructor(new Type[] { Types.ObjectArray, Types.Bool });
-
- static ConstructorInfo Hash_Constructor = Types.Hash.GetConstructor(Type.EmptyTypes);
-
- static ConstructorInfo Regex_Constructor = typeof(Regex).GetConstructor(new Type[] { Types.String });
-
- static ConstructorInfo Regex_Constructor_Options = typeof(Regex).GetConstructor(new Type[] { Types.String, typeof(RegexOptions) });
-
- static MethodInfo Hash_Add = Types.Hash.GetMethod("Add", new Type[] { typeof(object), typeof(object) });
-
- private static ConstructorInfo TimeSpan_LongConstructor = Methods.ConstructorOf(() => new TimeSpan(default(long)));
-
- private static MethodInfo Type_GetTypeFromHandle = Methods.Of<RuntimeTypeHandle, Type>(Type.GetTypeFromHandle);
-
- static MethodInfo String_IsNullOrEmpty = Methods.Of<string, bool>(string.IsNullOrEmpty);
-
- static MethodInfo RuntimeHelpers_InitializeArray = Methods.Of<Array, RuntimeFieldHandle>(System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray);
-
-
- AssemblyBuilder _asmBuilder;
-
- ModuleBuilder _moduleBuilder;
-
- Hashtable _symbolDocWriters = new Hashtable();
-
- // IL generation state
- ILGenerator _il;
- Method _method; //current method
- int _returnStatements;//number of return statements in current method
- bool _hasLeaveWithStoredValue;//has a explicit return inside a try block (a `leave')
- bool _returnImplicit; //method ends with an implicit return
- Label _returnLabel; //label for `ret'
- Label _implicitLabel; //label for implicit return (with default value)
- Label _leaveLabel; //label to load the stored return value (because of a `leave')
- IType _returnType;
- int _tryBlock; // are we in a try block?
- bool _checked = true;
- bool _rawArrayIndexing = false;
- bool _perModuleRawArrayIndexing = false;
-
- Dictionary<IType, Type> _typeCache = new Dictionary<IType, Type>();
-
- // keeps track of types on the IL stack
- readonly Stack<IType> _types = new Stack<IType>();
-
- readonly Stack<LoopInfo> _loopInfoStack = new Stack<LoopInfo>();
-
- readonly AttributeCollection _assemblyAttributes = new AttributeCollection();
-
- LoopInfo _currentLoopInfo;
-
- void EnterLoop(Label breakLabel, Label continueLabel)
- {
- _loopInfoStack.Push(_currentLoopInfo);
- _currentLoopInfo = new LoopInfo(breakLabel, continueLabel, _tryBlock);
- }
-
- bool InTryInLoop()
- {
- return _tryBlock > _currentLoopInfo.TryBlockDepth;
- }
-
- void LeaveLoop()
- {
- _currentLoopInfo = _loopInfoStack.Pop();
- }
-
- void PushType(IType type)
- {
- _types.Push(type);
- }
-
- void PushBool()
- {
- PushType(TypeSystemServices.BoolType);
- }
-
- void PushVoid()
- {
- PushType(TypeSystemServices.VoidType);
- }
-
- IType PopType()
- {
- return _types.Pop();
- }
-
- IType PeekTypeOnStack()
- {
- return (_types.Count != 0) ? _types.Peek() : null;
- }
-
- override public void Run()
- {
- if (Errors.Count > 0)
- return;
-
- GatherAssemblyAttributes();
- SetUpAssembly();
-
- DefineTypes();
-
- DefineResources();
- DefineAssemblyAttributes();
- DefineEntryPoint();
-
- // Define the unmanaged version information resource, which
- // contains the attribute informaion applied earlier
- _asmBuilder.DefineVersionInfoResource();
-
- _moduleBuilder.CreateGlobalFunctions(); //setup global .data
- }
-
- void GatherAssemblyAttributes()
- {
- foreach (var module in CompileUnit.Modules)
- foreach (var attribute in module.AssemblyAttributes)
- _assemblyAttributes.Add(attribute);
- }
-
- void DefineTypes()
- {
- if (CompileUnit.Modules.Count == 0)
- return;
-
- var types = CollectTypes();
- foreach (var type in types)
- DefineType(type);
-
- foreach (var type in types)
- {
- DefineGenericParameters(type);
- DefineTypeMembers(type);
- }
-
- foreach (var module in CompileUnit.Modules)
- OnModule(module);
-
- EmitAttributes();
- CreateTypes(types);
- }
-
- sealed class AttributeEmitVisitor : FastDepthFirstVisitor
- {
- EmitAssembly _emitter;
-
- public AttributeEmitVisitor(EmitAssembly emitter)
- {
- _emitter = emitter;
- }
-
- public override void OnField(Field node)
- {
- _emitter.EmitFieldAttributes(node);
- }
-
- public override void OnEnumMember(EnumMember node)
- {
- _emitter.EmitFieldAttributes(node);
- }
-
- public override void OnEvent(Event node)
- {
- _emitter.EmitEventAttributes(node);
- }
-
- public override void OnProperty(Property node)
- {
- Visit(node.Getter);
- Visit(node.Setter);
- _emitter.EmitPropertyAttributes(node);
- }
-
- public override void OnConstructor(Constructor node)
- {
- Visit(node.Parameters);
- _emitter.EmitConstructorAttributes(node);
- }
-
- public override void OnMethod(Method node)
- {
- Visit(node.Parameters);
- _emitter.EmitMethodAttributes(node);
- }
-
- public override void OnParameterDeclaration(ParameterDeclaration node)
- {
- _emitter.EmitParameterAttributes(node);
- }
-
- public override void OnClassDefinition(ClassDefinition node)
- {
- base.OnClassDefinition(node);
- _emitter.EmitTypeAttributes(node);
- }
-
- public override void OnInterfaceDefinition(InterfaceDefinition node)
- {
- base.OnInterfaceDefinition(node);
- _emitter.EmitTypeAttributes(node);
- }
-
- public override void OnEnumDefinition(EnumDefinition node)
- {
- base.OnEnumDefinition(node);
- _emitter.EmitTypeAttributes(node);
- }
- }
-
- delegate void CustomAttributeSetter(CustomAttributeBuilder attribute);
-
- void EmitAttributes(INodeWithAttributes node, CustomAttributeSetter setCustomAttribute)
- {
- foreach (Attribute attribute in node.Attributes)
- setCustomAttribute(GetCustomAttributeBuilder(attribute));
- }
-
- void EmitPropertyAttributes(Property node)
- {
- PropertyBuilder builder = GetPropertyBuilder(node);
- EmitAttributes(node, builder.SetCustomAttribute);
- }
-
- void EmitParameterAttributes(ParameterDeclaration node)
- {
- ParameterBuilder builder = (ParameterBuilder)GetBuilder(node);
- EmitAttributes(node, builder.SetCustomAttribute);
- }
-
- void EmitEventAttributes(Event node)
- {
- EventBuilder builder = (EventBuilder)GetBuilder(node);
- EmitAttributes(node, builder.SetCustomAttribute);
- }
-
- void EmitConstructorAttributes(Constructor node)
- {
- ConstructorBuilder builder = (ConstructorBuilder)GetBuilder(node);
- EmitAttributes(node, builder.SetCustomAttribute);
- }
-
- void EmitMethodAttributes(Method node)
- {
- MethodBuilder builder = GetMethodBuilder(node);
- EmitAttributes(node, builder.SetCustomAttribute);
- }
-
- void EmitTypeAttributes(TypeDefinition node)
- {
- TypeBuilder builder = GetTypeBuilder(node);
- EmitAttributes(node, builder.SetCustomAttribute);
- }
-
- void EmitFieldAttributes(TypeMember node)
- {
- FieldBuilder builder = GetFieldBuilder(node);
- EmitAttributes(node, builder.SetCustomAttribute);
- }
-
- void EmitAttributes()
- {
- AttributeEmitVisitor visitor = new AttributeEmitVisitor(this);
- foreach (Module module in CompileUnit.Modules)
- module.Accept(visitor);
- }
-
- void CreateTypes(List<TypeDefinition> types)
- {
- new TypeCreator(this, types).Run();
- }
-
- /// <summary>
- /// Ensures that all types are created in the correct order.
- /// </summary>
- sealed class TypeCreator
- {
- EmitAssembly _emitter;
-
- Set<TypeDefinition> _created;
-
- List<TypeDefinition> _types;
-
- TypeDefinition _current;
-
- public TypeCreator(EmitAssembly emitter, List<TypeDefinition> types)
- {
- _emitter = emitter;
- _types = types;
- _created = new Set<TypeDefinition>();
- }
-
- public void Run()
- {
- AppDomain domain = Thread.GetDomain();
- try
- {
- domain.TypeResolve += OnTypeResolve;
- CreateTypes();
- }
- finally
- {
- domain.TypeResolve -= OnTypeResolve;
- }
- }
-
- private Assembly OnTypeResolve(object sender, ResolveEventArgs args)
- {
- Trace("OnTypeResolve('{0}') during '{1}' creation.", args.Name, _current);
- EnsureInternalFieldDependencies(_current);
- return _emitter._asmBuilder;
- }
-
- private void CreateTypes()
- {
- foreach (var type in _types)
- CreateType(type);
- }
-
- void CreateType(TypeDefinition type)
- {
- if (_created.Contains(type))
- return;
-
- _created.Add(type);
-
- var saved = _current;
- _current = type;
- try
- {
- HandleTypeCreation(type);
- }
- catch (Exception e)
- {
- throw CompilerErrorFactory.InternalError(type, string.Format("Failed to create '{0}' type.", type), e);
- }
- _current = saved;
- }
-
- private void HandleTypeCreation(TypeDefinition type)
- {
- Trace("creating type '{0}'", type);
-
- if (IsNestedType(type))
- CreateOuterTypeOf(type);
-
- CreateRelatedTypes(type);
- var typeBuilder = (TypeBuilder)_emitter.GetBuilder(type);
- typeBuilder.CreateType();
- Trace("type '{0}' successfully created", type);
- }
-
- private void CreateOuterTypeOf(TypeMember type)
- {
- CreateType(type.DeclaringType);
- }
-
- private void CreateRelatedTypes(TypeDefinition typedef)
- {
- CreateRelatedTypes(typedef.BaseTypes);
- foreach (var gpd in typedef.GenericParameters)
- CreateRelatedTypes(gpd.BaseTypes);
- }
-
- private void EnsureInternalFieldDependencies(TypeDefinition typedef)
- {
- foreach (var field in typedef.Members.OfType<Field>())
- EnsureInternalDependencies((IType)field.Type.Entity);
- }
-
- private void CreateRelatedTypes(IEnumerable<TypeReference> typerefs)
- {
- foreach (var typeref in typerefs)
- {
- var type = _emitter.GetType(typeref);
- EnsureInternalDependencies(type);
- }
- }
-
- private void EnsureInternalDependencies(IType type)
- {
- var internalType = type as AbstractInternalType;
- if (null != internalType)
- {
- CreateType(internalType.TypeDefinition);
- return;
- }
-
- if (type.ConstructedInfo != null)
- {
- EnsureInternalDependencies(type.ConstructedInfo.GenericDefinition);
- foreach (var typeArg in type.ConstructedInfo.GenericArguments)
- EnsureInternalDependencies(typeArg);
- }
- }
-
- static bool IsNestedType(TypeMember type)
- {
- switch (type.ParentNode.NodeType)
- {
- case NodeType.ClassDefinition:
- case NodeType.InterfaceDefinition:
- return true;
- }
- return false;
- }
-
- void Trace(string format, params object[] args)
- {
- _emitter.Context.TraceVerbose(format, args);
- }
- }
-
- List<TypeDefinition> CollectTypes()
- {
- var types = new List<TypeDefinition>();
- foreach (Module module in CompileUnit.Modules)
- CollectTypes(types, module.Members);
- return types;
- }
-
- void CollectTypes(List<TypeDefinition> types, TypeMemberCollection members)
- {
- foreach (var member in members)
- {
- switch (member.NodeType)
- {
- case NodeType.InterfaceDefinition:
- case NodeType.ClassDefinition:
- {
- var typeDefinition = ((TypeDefinition)member);
- types.Add(typeDefinition);
- CollectTypes(types, typeDefinition.Members);
- break;
- }
- case NodeType.EnumDefinition:
- {
- types.Add((TypeDefinition) member);
- break;
- }
- }
- }
- }
-
- override public void Dispose()
- {
- base.Dispose();
-
- _asmBuilder = null;
- _moduleBuilder = null;
- _symbolDocWriters.Clear();
- _il = null;
- _returnStatements = 0;
- _hasLeaveWithStoredValue = false;
- _returnImplicit = false;
- _returnType = null;
- _tryBlock = 0;
- _checked = true;
- _rawArrayIndexing = false;
- _types.Clear();
- _typeCache.Clear();
- _builders.Clear();
- _assemblyAttributes.Clear();
- _defaultValueHolders.Clear();
- _packedArrays.Clear();
- }
-
- override public void OnAttribute(Attribute node)
- {
- }
-
- override public void OnModule(Module module)
- {
- _perModuleRawArrayIndexing = AstAnnotations.IsRawIndexing(module);
- _checked = AstAnnotations.IsChecked(module, Parameters.Checked);
- Visit(module.Members);
- }
-
- override public void OnEnumDefinition(EnumDefinition node)
- {
- var typeBuilder = GetTypeBuilder(node);
- foreach (EnumMember member in node.Members)
- {
- var field = typeBuilder.DefineField(member.Name, typeBuilder,
- FieldAttributes.Public |
- FieldAttributes.Static |
- FieldAttributes.Literal);
- field.SetConstant(InitializerValueOf(member, node));
- SetBuilder(member, field);
- }
- }
-
- private object InitializerValueOf(EnumMember enumMember, EnumDefinition enumType)
- {
- return Convert.ChangeType(((IntegerLiteralExpression) enumMember.Initializer).Value,
- GetEnumUnderlyingType(enumType));
- }
-
- override public void OnArrayTypeReference(ArrayTypeReference node)
- {
- }
-
- override public void OnClassDefinition(ClassDefinition node)
- {
- EmitTypeDefinition(node);
- }
-
- override public void OnField(Field node)
- {
- FieldBuilder builder = GetFieldBuilder(node);
- if (builder.IsLiteral)
- {
- builder.SetConstant(GetInternalFieldStaticValue((InternalField)node.Entity));
- }
- }
-
- override public void OnInterfaceDefinition(InterfaceDefinition node)
- {
- TypeBuilder builder = GetTypeBuilder(node);
- foreach (TypeReference baseType in node.BaseTypes)
- {
- builder.AddInterfaceImplementation(GetSystemType(baseType));
- }
- }
-
- override public void OnMacroStatement(MacroStatement node)
- {
- NotImplemented(node, "Unexpected macro: " + node.ToCodeString());
- }
-
- override public void OnCallableDefinition(CallableDefinition node)
- {
- NotImplemented(node, "Unexpected callable definition!");
- }
-
- void EmitTypeDefinition(TypeDefinition node)
- {
- TypeBuilder current = GetTypeBuilder(node);
- EmitBaseTypesAndAttributes(node, current);
- Visit(node.Members);
- }
-
- override public void OnMethod(Method method)
- {
- if (method.IsRuntime) return;
- if (IsPInvoke(method)) return;
-
- MethodBuilder methodBuilder = GetMethodBuilder(method);
- DefineExplicitImplementationInfo(method);
-
- EmitMethod(method, methodBuilder.GetILGenerator());
- }
-
- private void DefineExplicitImplementationInfo(Method method)
- {
- if (null == method.ExplicitInfo)
- return;
-
- IMethod ifaceMethod = (IMethod)method.ExplicitInfo.Entity;
- MethodInfo ifaceInfo = GetMethodInfo(ifaceMethod);
- MethodInfo implInfo = GetMethodInfo((IMethod)method.Entity);
-
- TypeBuilder typeBuilder = GetTypeBuilder(method.DeclaringType);
- typeBuilder.DefineMethodOverride(implInfo, ifaceInfo);
- }
-
- void EmitMethod(Method method, ILGenerator generator)
- {
- _il = generator;
- _method = method;
-
- DefineLabels(method);
- Visit(method.Locals);
-
- BeginMethodBody(GetEntity(method).ReturnType);
- Visit(method.Body);
- EndMethodBody(method);
- }
-
- void BeginMethodBody(IType returnType)
- {
- _defaultValueHolders.Clear();
-
- _returnType = returnType;
- _returnStatements = 0;
- _returnImplicit = IsVoid(returnType);
- _hasLeaveWithStoredValue = false;
-
- //we may not actually use (any/all of) them, but at least they're ready
- _returnLabel = _il.DefineLabel();
- _leaveLabel = _il.DefineLabel();
- _implicitLabel = _il.DefineLabel();
- }
-
- void EndMethodBody(Method method)
- {
- if (!_returnImplicit)
- _returnImplicit = !AstUtil.AllCodePathsReturnOrRaise(method.Body);
-
- //At most a method epilogue contains 3 independent load instructions:
- //1) load of the value of an actual return (emitted elsewhere and branched to _returnLabel)
- //2) load of a default value (implicit returns [e.g return without expression])
- //3) load of the `leave' stored value
-
- bool hasDefaultValueReturn = _returnImplicit && !IsVoid(_returnType);
- if (hasDefaultValueReturn)
- {
- if (_returnStatements == -1) //emit branch only if instructed to do so (-1)
- _il.Emit(OpCodes.Br_S, _returnLabel);
-
- //load default return value for implicit return
- _il.MarkLabel(_implicitLabel);
- EmitDefaultValue(_returnType);
- PopType();
- }
-
- if (_hasLeaveWithStoredValue)
- {
- if (hasDefaultValueReturn || _returnStatements == -1)
- _il.Emit(OpCodes.Br_S, _returnLabel);
-
- //load the stored return value and `ret'
- _il.MarkLabel(_leaveLabel);
- _il.Emit(OpCodes.Ldloc, GetDefaultValueHolder(_returnType));
- }
-
- if (_returnImplicit || _returnStatements != 0)
- {
- _il.MarkLabel(_returnLabel);
- _il.Emit(OpCodes.Ret);
- }
- }
-
- private bool IsPInvoke(Method method)
- {
- return GetEntity(method).IsPInvoke;
- }
-
- override public void OnBlock(Block block)
- {
- var currentChecked = _checked;
- _checked = AstAnnotations.IsChecked(block, currentChecked);
-
- var currentArrayIndexing = _rawArrayIndexing;
- _rawArrayIndexing = _perModuleRawArrayIndexing || AstAnnotations.IsRawIndexing(block);
-
- Visit(block.Statements);
-
- _rawArrayIndexing = currentArrayIndexing;
- _checked = currentChecked;
- }
-
- void DefineLabels(Method method)
- {
- foreach (var label in LabelsOn(method))
- label.Label = _il.DefineLabel();
- }
-
- private InternalLabel[] LabelsOn(Method method)
- {
- return ((InternalMethod) method.Entity).Labels;
- }
-
- override public void OnConstructor(Constructor constructor)
- {
- if (constructor.IsRuntime) return;
-
- ConstructorBuilder builder = GetConstructorBuilder(constructor);
- EmitMethod(constructor, builder.GetILGenerator());
- }
-
- override public void OnLocal(Local local)
- {
- InternalLocal info = GetInternalLocal(local);
- info.LocalBuilder = _il.DeclareLocal(GetSystemType(local), info.Type.IsPointer);
- if (Parameters.Debug)
- {
- info.LocalBuilder.SetLocalSymInfo(local.Name);
- }
- }
-
- override public void OnForStatement(ForStatement node)
- {
- NotImplemented("ForStatement");
- }
-
- override public void OnReturnStatement(ReturnStatement node)
- {
- EmitDebugInfo(node);
-
- var retOpCode = _tryBlock > 0 ? OpCodes.Leave : OpCodes.Br;
- var label = _returnLabel;
-
- var expression = node.Expression;
- if (expression != null)
- {
- ++_returnStatements;
-
- LoadExpressionWithType(_returnType, expression);
-
- if (retOpCode == OpCodes.Leave)
- {
- //`leave' clears the stack, so we have to store return value temporarily
- //we can use a default value holder for that since it won't be read afterwards
- //of course this is necessary only if return type is not void
- LocalBuilder temp = GetDefaultValueHolder(_returnType);
- _il.Emit(OpCodes.Stloc, temp);
- label = _leaveLabel;
- _hasLeaveWithStoredValue = true;
- }
- }
- else if (_returnType != TypeSystemServices.VoidType)
- {
- _returnImplicit = true;
- label = _implicitLabel;
- }
-
- if (_method.Body.LastStatement != node)
- _il.Emit(retOpCode, label);
- else if (null != expression)
- _returnStatements = -1; //instruct epilogue to branch last ret only if necessary
- }
-
- private void LoadExpressionWithType(IType expectedType, Expression expression)
- {
- Visit(expression);
- EmitCastIfNeeded(expectedType, PopType());
- }
-
- override public void OnRaiseStatement(RaiseStatement node)
- {
- EmitDebugInfo(node);
- if (node.Exception == null)
- {
- _il.Emit(OpCodes.Rethrow);
- }
- else
- {
- Visit(node.Exception); PopType();
- _il.Emit(OpCodes.Throw);
- }
- }
-
- override public void OnTryStatement(TryStatement node)
- {
- ++_tryBlock;
- Label end = _il.BeginExceptionBlock();
-
- // The fault handler isn't very well supported by the
- // the ILGenerator. Thus, when there is a failure block
- // in the same try as an except or ensure block, we
- // need to do some special brute forcing with the exception
- // block context in the ILGenerator.
- if(null != node.FailureBlock && null != node.EnsureBlock)
- {
- ++_tryBlock;
- _il.BeginExceptionBlock();
- }
-
- if(null != node.FailureBlock && node.ExceptionHandlers.Count > 0)
- {
- ++_tryBlock;
- _il.BeginExceptionBlock();
- }
-
- Visit(node.ProtectedBlock);
-
- Visit(node.ExceptionHandlers);
-
- if(null != node.FailureBlock)
- {
- // Logic to back out of the manually forced blocks
- if(node.ExceptionHandlers.Count > 0)
- {
- _il.EndExceptionBlock();
- --_tryBlock;
- }
-
- _il.BeginFaultBlock();
- Visit(node.FailureBlock);
-
- // Logic to back out of the manually forced blocks once more
- if(null != node.EnsureBlock)
- {
- _il.EndExceptionBlock();
- --_tryBlock;
- }
- }
-
- if (null != node.EnsureBlock)
- {
- _il.BeginFinallyBlock();
- Visit(node.EnsureBlock);
- }
-
- _il.EndExceptionBlock();
- --_tryBlock;
- }
-
- override public void OnExceptionHandler(ExceptionHandler node)
- {
- if((node.Flags & ExceptionHandlerFlags.Filter) == ExceptionHandlerFlags.Filter)
- {
- _il.BeginExceptFilterBlock();
-
- Label endLabel = _il.DefineLabel();
-
- // If the filter is not untyped, then test the exception type
- // before testing the filter condition
- if((node.Flags & ExceptionHandlerFlags.Untyped) == ExceptionHandlerFlags.None)
- {
- Label filterCondition = _il.DefineLabel();
-
- // Test the type of the exception.
- _il.Emit(OpCodes.Isinst, GetSystemType(node.Declaration.Type));
-
- // Duplicate it. If it is null, then it will be used to
- // skip the filter.
- Dup();
-
- // If the exception is of the right type, branch
- // to test the filter condition.
- _il.Emit(OpCodes.Brtrue_S, filterCondition);
-
- // Otherwise, clean up the stack and prepare the stack
- // to skip the filter.
- EmitStoreOrPopException(node);
-
- _il.Emit(OpCodes.Ldc_I4_0);
- _il.Emit(OpCodes.Br, endLabel);
- _il.MarkLabel(filterCondition);
-
- }
- else if((node.Flags & ExceptionHandlerFlags.Anonymous) == ExceptionHandlerFlags.None)
- {
- // Cast the exception to the default except type
- _il.Emit(OpCodes.Isinst, GetSystemType(node.Declaration.Type));
- }
-
- EmitStoreOrPopException(node);
-
- // Test the condition and convert to boolean if needed.
- node.FilterCondition.Accept(this);
- PopType();
- EmitToBoolIfNeeded(node.FilterCondition);
-
- // If the type is right and the condition is true,
- // proceed with the handler.
- _il.MarkLabel(endLabel);
- _il.Emit(OpCodes.Ldc_I4_0);
- _il.Emit(OpCodes.Cgt_Un);
-
- _il.BeginCatchBlock(null);
- }
- else
- {
- // Begin a normal catch block of the appropriate type.
- _il.BeginCatchBlock(GetSystemType(node.Declaration.Type));
-
- // Clean up the stack or store the exception if not anonymous.
- EmitStoreOrPopException(node);
- }
-
- Visit(node.Block);
- }
-
- private void EmitStoreOrPopException(ExceptionHandler node)
- {
- if((node.Flags & ExceptionHandlerFlags.Anonymous) == ExceptionHandlerFlags.None)
- {
- _il.Emit(OpCodes.Stloc, GetLocalBuilder(node.Declaration));
- }
- else
- {
- _il.Emit(OpCodes.Pop);
- }
- }
-
- override public void OnUnpackStatement(UnpackStatement node)
- {
- NotImplemented("Unpacking");
- }
-
- override public void OnExpressionStatement(ExpressionStatement node)
- {
- EmitDebugInfo(node);
-
- base.OnExpressionStatement(node);
-
- // if the type of the inner expression is not
- // void we need to pop its return value to leave
- // the stack sane
- DiscardValueOnStack();
- }
-
- void DiscardValueOnStack()
- {
- if (!IsVoid(PopType()))
- _il.Emit(OpCodes.Pop);
- }
-
- bool IsVoid(IType type)
- {
- return type == TypeSystemServices.VoidType;
- }
-
- override public void OnUnlessStatement(UnlessStatement node)
- {
- Label endLabel = _il.DefineLabel();
- EmitDebugInfo(node);
- EmitBranchTrue(node.Condition, endLabel);
- node.Block.Accept(this);
- _il.MarkLabel(endLabel);
- }
-
- void OnSwitch(MethodInvocationExpression node)
- {
- var args = node.Arguments;
- LoadExpressionWithType(TypeSystemServices.IntType, args[0]);
- _il.Emit(OpCodes.Switch, args.Skip(1).Select(e => LabelFor(e)).ToArray());
-
- PushVoid();
- }
-
- private static Label LabelFor(Expression expression)
- {
- return ((InternalLabel) expression.Entity).Label;
- }
-
- override public void OnGotoStatement(GotoStatement node)
- {
- EmitDebugInfo(node);
-
- InternalLabel label = (InternalLabel)GetEntity(node.Label);
- int gotoDepth = AstAnnotations.GetTryBlockDepth(node);
- int targetDepth = AstAnnotations.GetTryBlockDepth(label.LabelStatement);
-
- if (targetDepth == gotoDepth)
- {
- _il.Emit(OpCodes.Br, label.Label);
- }
- else
- {
- _il.Emit(OpCodes.Leave, label.Label);
- }
- }
-
- override public void OnLabelStatement(LabelStatement node)
- {
- EmitDebugInfo(node);
- _il.MarkLabel(((InternalLabel)node.Entity).Label);
- }
-
- override public void OnConditionalExpression(ConditionalExpression node)
- {
- var type = GetExpressionType(node);
-
- var endLabel = _il.DefineLabel();
-
- EmitBranchFalse(node.Condition, endLabel);
- LoadExpressionWithType(type, node.TrueValue);
-
- var elseEndLabel = _il.DefineLabel();
- _il.Emit(OpCodes.Br, elseEndLabel);
- _il.MarkLabel(endLabel);
-
- endLabel = elseEndLabel;
- LoadExpressionWithType(type, node.FalseValue);
-
- _il.MarkLabel(endLabel);
-
- PushType(type);
- }
-
- override public void OnIfStatement(IfStatement node)
- {
- Label endLabel = _il.DefineLabel();
-
- EmitDebugInfo(node);
- EmitBranchFalse(node.Condition, endLabel);
-
- node.TrueBlock.Accept(this);
- if (null != node.FalseBlock)
- {
- Label elseEndLabel = _il.DefineLabel();
- if (!node.TrueBlock.EndsWith<ReturnStatement>() && !node.TrueBlock.EndsWith<RaiseStatement>())
- _il.Emit(OpCodes.Br, elseEndLabel);
- _il.MarkLabel(endLabel);
-
- endLabel = elseEndLabel;
- node.FalseBlock.Accept(this);
- }
-
- _il.MarkLabel(endLabel);
- }
-
-
- void EmitBranchTrue(Expression expression, Label label)
- {
- EmitBranch(true, expression, label);
- }
-
- void EmitBranchFalse(Expression expression, Label label)
- {
- EmitBranch(false, expression, label);
- }
-
- void EmitBranch(bool branchOnTrue, BinaryExpression expression, Label label)
- {
- switch (expression.Operator)
- {
- case BinaryOperatorType.TypeTest:
- EmitTypeTest(expression);
- _il.Emit(branchOnTrue ? OpCodes.Brtrue : OpCodes.Brfalse, label);
- break;
-
- case BinaryOperatorType.Or:
- if (branchOnTrue)
- {
- EmitBranch(true, expression.Left, label);
- EmitBranch(true, expression.Right, label);
- }
- else
- {
- Label skipRhs = _il.DefineLabel();
- EmitBranch(true, expression.Left, skipRhs);
- EmitBranch(false, expression.Right, label);
- _il.MarkLabel(skipRhs);
- }
- break;
-
- case BinaryOperatorType.And:
- if (branchOnTrue)
- {
- Label skipRhs = _il.DefineLabel();
- EmitBranch(false, expression.Left, skipRhs);
- EmitBranch(true, expression.Right, label);
- _il.MarkLabel(skipRhs);
- }
- else
- {
- EmitBranch(false, expression.Left, label);
- EmitBranch(false, expression.Right, label);
- }
- break;
-
- case BinaryOperatorType.Equality:
- if (IsZeroEquivalent(expression.Left))
- EmitBranch(!branchOnTrue, expression.Right, label);
- else if (IsZeroEquivalent(expression.Right))
- EmitBranch(!branchOnTrue, expression.Left, label);
- else
- {
- LoadCmpOperands(expression);
- _il.Emit(branchOnTrue ? OpCodes.Beq : OpCodes.Bne_Un, label);
- }
- break;
-
- case BinaryOperatorType.Inequality:
- if (IsZeroEquivalent(expression.Left))
- {
- EmitBranch(branchOnTrue, expression.Right, label);
- }
- else if (IsZeroEquivalent(expression.Right))
- {
- EmitBranch(branchOnTrue, expression.Left, label);
- }
- else
- {
- LoadCmpOperands(expression);
- _il.Emit(branchOnTrue ? OpCodes.Bne_Un : OpCodes.Beq, label);
- }
- break;
-
- case BinaryOperatorType.ReferenceEquality:
- if (IsNull(expression.Left))
- {
- EmitRawBranch(!branchOnTrue, expression.Right, label);
- break;
- }
- if (IsNull(expression.Right))
- {
- EmitRawBranch(!branchOnTrue, expression.Left, label);
- break;
- }
- Visit(expression.Left); PopType();
- Visit(expression.Right); PopType();
- _il.Emit(branchOnTrue ? OpCodes.Beq : OpCodes.Bne_Un, label);
- break;
-
- case BinaryOperatorType.ReferenceInequality:
- if (IsNull(expression.Left))
- {
- EmitRawBranch(branchOnTrue, expression.Right, label);
- break;
- }
- if (IsNull(expression.Right))
- {
- EmitRawBranch(branchOnTrue, expression.Left, label);
- break;
- }
- Visit(expression.Left); PopType();
- Visit(expression.Right); PopType();
- _il.Emit(branchOnTrue ? OpCodes.Bne_Un : OpCodes.Beq, label);
- break;
-
- case BinaryOperatorType.GreaterThan:
- LoadCmpOperands(expression);
- _il.Emit(branchOnTrue ? OpCodes.Bgt : OpCodes.Ble, label);
- break;
-
- case BinaryOperatorType.GreaterThanOrEqual:
- LoadCmpOperands(expression);
- _il.Emit(branchOnTrue ? OpCodes.Bge : OpCodes.Blt, label);
- break;
-
- case BinaryOperatorType.LessThan:
- LoadCmpOperands(expression);
- _il.Emit(branchOnTrue ? OpCodes.Blt : OpCodes.Bge, label);
- break;
-
- case BinaryOperatorType.LessThanOrEqual:
- LoadCmpOperands(expression);
- _il.Emit(branchOnTrue ? OpCodes.Ble : OpCodes.Bgt, label);
- break;
-
- default:
- EmitDefaultBranch(branchOnTrue, expression, label);
- break;
- }
- }
-
- void EmitBranch(bool branchOnTrue, UnaryExpression expression, Label label)
- {
- if (UnaryOperatorType.LogicalNot == expression.Operator)
- {
- EmitBranch(!branchOnTrue, expression.Operand, label);
- }
- else
- {
- EmitDefaultBranch(branchOnTrue, expression, label);
- }
- }
-
- void EmitBranch(bool branchOnTrue, Expression expression, Label label)
- {
- switch (expression.NodeType)
- {
- case NodeType.BinaryExpression:
- {
- EmitBranch(branchOnTrue, (BinaryExpression)expression, label);
- break;
- }
-
- case NodeType.UnaryExpression:
- {
- EmitBranch(branchOnTrue, (UnaryExpression)expression, label);
- break;
- }
-
- default:
- {
- EmitDefaultBranch(branchOnTrue, expression, label);
- break;
- }
- }
- }
-
- void EmitRawBranch(bool branch, Expression condition, Label label)
- {
- condition.Accept(this); PopType();
- _il.Emit(branch ? OpCodes.Brtrue : OpCodes.Brfalse, label);
- }
-
- void EmitDefaultBranch(bool branch, Expression condition, Label label)
- {
- if (branch && IsOneEquivalent(condition))
- {
- _il.Emit(OpCodes.Br, label);
- return;
- }
-
- if (!branch && IsZeroEquivalent(condition))
- {
- _il.Emit(OpCodes.Br, label);
- return;
- }
-
- condition.Accept(this);
-
- var type = PopType();
- if (TypeSystemServices.IsFloatingPointNumber(type))
- {
- EmitDefaultValue(type);
- _il.Emit(branch ? OpCodes.Bne_Un : OpCodes.Beq, label);
- return;
- }
-
- EmitToBoolIfNeeded(condition);
- _il.Emit(branch ? OpCodes.Brtrue : OpCodes.Brfalse, label);
- }
-
- private static bool IsZeroEquivalent(Expression expression)
- {
- return (IsNull(expression) || IsZero(expression) || IsFalse(expression));
- }
-
- private static bool IsOneEquivalent(Expression expression)
- {
- return IsBooleanLiteral(expression, true) || IsNumberLiteral(expression, 1);
- }
-
- private static bool IsNull(Expression expression)
- {
- return NodeType.NullLiteralExpression == expression.NodeType;
- }
-
- private static bool IsFalse(Expression expression)
- {
- return IsBooleanLiteral(expression, false);
- }
-
- private static bool IsBooleanLiteral(Expression expression, bool value)
- {
- return NodeType.BoolLiteralExpression == expression.NodeType
- && (value == ((BoolLiteralExpression)expression).Value);
- }
-
- private static bool IsZero(Expression expression)
- {
- return IsNumberLiteral(expression, 0);
- }
-
- private static bool IsNumberLiteral(Expression expression, int value)
- {
- return (NodeType.IntegerLiteralExpression == expression.NodeType
- && (value == ((IntegerLiteralExpression)expression).Value))
- ||
- (NodeType.DoubleLiteralExpression == expression.NodeType
- && (value == ((DoubleLiteralExpression)expression).Value));
- }
-
- override public void OnBreakStatement(BreakStatement node)
- {
- EmitGoTo(_currentLoopInfo.BreakLabel, node);
- }
-
- private void EmitGoTo(Label label, Node debugInfo)
- {
- EmitDebugInfo(debugInfo);
- _il.Emit(InTryInLoop() ? OpCodes.Leave : OpCodes.Br, label);
- }
-
- override public void OnContinueStatement(ContinueStatement node)
- {
- EmitGoTo(_currentLoopInfo.ContinueLabel, node);
- }
-
- override public void OnWhileStatement(WhileStatement node)
- {
- Label endLabel = _il.DefineLabel();
- Label bodyLabel = _il.DefineLabel();
- Label conditionLabel = _il.DefineLabel();
-
- _il.Emit(OpCodes.Br, conditionLabel);
- _il.MarkLabel(bodyLabel);
-
- EnterLoop(endLabel, conditionLabel);
- node.Block.Accept(this);
- LeaveLoop();
-
- _il.MarkLabel(conditionLabel);
- EmitDebugInfo(node);
- EmitBranchTrue(node.Condition, bodyLabel);
- Visit(node.OrBlock);
- Visit(node.ThenBlock);
- _il.MarkLabel(endLabel);
- }
-
- void EmitIntNot()
- {
- _il.Emit(OpCodes.Ldc_I4_0);
- _il.Emit(OpCodes.Ceq);
- }
-
- void EmitGenericNot()
- {
- // bool codification:
- // value_on_stack ? 0 : 1
- Label wasTrue = _il.DefineLabel();
- Label wasFalse = _il.DefineLabel();
- _il.Emit(OpCodes.Brfalse_S, wasFalse);
- _il.Emit(OpCodes.Ldc_I4_0);
- _il.Emit(OpCodes.Br_S, wasTrue);
- _il.MarkLabel(wasFalse);
- _il.Emit(OpCodes.Ldc_I4_1);
- _il.MarkLabel(wasTrue);
- }
-
- override public void OnUnaryExpression(UnaryExpression node)
- {
- switch (node.Operator)
- {
- case UnaryOperatorType.LogicalNot:
- {
- EmitLogicalNot(node);
- break;
- }
-
- case UnaryOperatorType.UnaryNegation:
- {
- EmitUnaryNegation(node);
- break;
- }
-
- case UnaryOperatorType.OnesComplement:
- {
- EmitOnesComplement(node);
- break;
- }
-
- case UnaryOperatorType.AddressOf:
- {
- EmitAddressOf(node);
- break;
- }
-
- case UnaryOperatorType.Indirection:
- {
- EmitIndirection(node);
- break;
- }
-
- default:
- {
- NotImplemented(node, "unary operator not supported");
- break;
- }
- }
- }
-
- IType _byAddress = null;
- bool IsByAddress(IType type)
- {
- return (_byAddress == type);
- }
-
- void EmitDefaultValue(IType type)
- {
- var isGenericParameter = GenericsServices.IsGenericParameter(type);
-
- if (!type.IsValueType && !isGenericParameter)
- _il.Emit(OpCodes.Ldnull);
- else if (type == TypeSystemServices.BoolType)
- _il.Emit(OpCodes.Ldc_I4_0);
- else if (TypeSystemServices.IsFloatingPointNumber(type))
- EmitLoadLiteral(type, 0.0);
- else if (TypeSystemServices.IsPrimitiveNumber(type) || type == TypeSystemServices.CharType)
- EmitLoadLiteral(type, 0);
- else if (isGenericParameter && TypeSystemServices.IsReferenceType(type))
- {
- _il.Emit(OpCodes.Ldnull);
- _il.Emit(OpCodes.Unbox_Any, GetSystemType(type));
- }
- else //valuetype or valuetype/unconstrained generic parameter
- {
- //TODO: if MethodBody.InitLocals is false
- //_il.Emit(OpCodes.Ldloca, GetDefaultValueHolder(type));
- //_il.Emit(OpCodes.Initobj, GetSystemType(type));
- _il.Emit(OpCodes.Ldloc, GetDefaultValueHolder(type));
- }
-
- PushType(type);
- }
-
- Dictionary<IType, LocalBuilder> _defaultValueHolders = new Dictionary<IType, LocalBuilder>();
-
- //get the default value holder (a local actually) for a given type
- //default value holder pool is cleared before each method body processing
- LocalBuilder GetDefaultValueHolder(IType type)
- {
- LocalBuilder holder;
- if (_defaultValueHolders.TryGetValue(type, out holder))
- return holder;
-
- holder = _il.DeclareLocal(GetSystemType(type));
- _defaultValueHolders.Add(type, holder);
- return holder;
- }
-
-
- private void EmitOnesComplement(UnaryExpression node)
- {
- node.Operand.Accept(this);
- _il.Emit(OpCodes.Not);
- }
-
- private void EmitLogicalNot(UnaryExpression node)
- {
- Expression operand = node.Operand;
- operand.Accept(this);
- IType typeOnStack = PopType();
- bool notContext = true;
-
- if (IsBoolOrInt(typeOnStack))
- {
- EmitIntNot();
- }
- else if (EmitToBoolIfNeeded(operand, ref notContext))
- {
- if (!notContext) //we are in a not context and emit to bool is also in a not context
- EmitIntNot();//so we do not need any not (false && false => true)
- }
- else
- {
- EmitGenericNot();
- }
- PushBool();
- }
-
- private void EmitUnaryNegation(UnaryExpression node)
- {
- var operandType = GetExpressionType(node.Operand);
- if (IsCheckedIntegerOperand(operandType))
- {
- _il.Emit(OpCodes.Ldc_I4_0);
- if (IsLong(operandType) || operandType == TypeSystemServices.ULongType)
- _il.Emit(OpCodes.Conv_I8);
- node.Operand.Accept(this);
- _il.Emit(TypeSystemServices.IsSignedNumber(operandType)
- ? OpCodes.Sub_Ovf
- : OpCodes.Sub_Ovf_Un);
- if (!IsLong(operandType) && operandType != TypeSystemServices.ULongType)
- EmitCastIfNeeded(operandType, TypeSystemServices.IntType);
- }
- else
- {
- //a single/double unary negation never overflow
- node.Operand.Accept(this);
- _il.Emit(OpCodes.Neg);
- }
- }
-
- private bool IsCheckedIntegerOperand(IType operandType)
- {
- return _checked && IsInteger(operandType);
- }
-
- void EmitAddressOf(UnaryExpression node)
- {
- _byAddress = GetExpressionType(node.Operand);
- node.Operand.Accept(this);
- PushType(PopType().MakePointerType());
- _byAddress = null;
- }
-
- void EmitIndirection(UnaryExpression node)
- {
- node.Operand.Accept(this);
-
- if (node.Operand.NodeType != NodeType.ReferenceExpression
- && node.ParentNode.NodeType != NodeType.MemberReferenceExpression)
- {
- //pointer arithmetic, need to load the address
- IType et = PeekTypeOnStack().ElementType;
- OpCode code = GetLoadRefParamCode(et);
- if (code == OpCodes.Ldobj)
- _il.Emit(code, GetSystemType(et));
- else
- _il.Emit(code);
-
- PopType();
- PushType(et);
- }
- }
-
- static bool ShouldLeaveValueOnStack(Expression node)
- {
- return node.ParentNode.NodeType != NodeType.ExpressionStatement;
- }
-
- void OnReferenceComparison(BinaryExpression node)
- {
- node.Left.Accept(this); PopType();
- node.Right.Accept(this); PopType();
- _il.Emit(OpCodes.Ceq);
- if (BinaryOperatorType.ReferenceInequality == node.Operator)
- {
- EmitIntNot();
- }
- PushBool();
- }
-
- void OnAssignmentToSlice(BinaryExpression node)
- {
- var slice = (SlicingExpression)node.Left;
- Visit(slice.Target);
-
- var arrayType = (IArrayType)PopType();
- if (arrayType.Rank == 1)
- EmitAssignmentToSingleDimensionalArrayElement(arrayType, slice, node);
- else
- EmitAssignmentToMultiDimensionalArrayElement(arrayType, slice, node);
- }
-
- private void EmitAssignmentToMultiDimensionalArrayElement(IArrayType arrayType, SlicingExpression slice, BinaryExpression node)
- {
- var elementType = arrayType.ElementType;
- LoadArrayIndices(slice);
- var temp = LoadAssignmentOperand(elementType, node);
- CallArrayMethod(arrayType, "Set", typeof(void), ParameterTypesForArraySet(arrayType));
- FlushAssignmentOperand(elementType, temp);
- }
-
- private void EmitAssignmentToSingleDimensionalArrayElement(IArrayType arrayType, SlicingExpression slice, BinaryExpression node)
- {
- var elementType = arrayType.ElementType;
-
- var index = slice.Indices[0];
- EmitNormalizedArrayIndex(slice, index.Begin);
-
- var opcode = GetStoreEntityOpCode(elementType);
- bool stobj = IsStobj(opcode);
- if (stobj) _il.Emit(OpCodes.Ldelema, GetSystemType(elementType));
-
- var temp = LoadAssignmentOperand(elementType, node);
-
- if (stobj)
- _il.Emit(opcode, GetSystemType(elementType));
- else
- _il.Emit(opcode);
-
- FlushAssignmentOperand(elementType, temp);
- }
-
- private void FlushAssignmentOperand(IType elementType, LocalBuilder temp)
- {
- if (temp != null)
- LoadLocal(temp, elementType);
- else
- PushVoid();
- }
-
- private LocalBuilder LoadAssignmentOperand(IType elementType, BinaryExpression node)
- {
- LoadExpressionWithType(elementType, node.Right);
- var leaveValueOnStack = ShouldLeaveValueOnStack(node);
- LocalBuilder temp = null;
- if (leaveValueOnStack)
- {
- Dup();
- temp = StoreTempLocal(elementType);
- }
- return temp;
- }
-
- LocalBuilder _currentLocal = null;
-
- void LoadLocal(LocalBuilder local, IType localType)
- {
- _il.Emit(OpCodes.Ldloc, local);
-
- PushType(localType);
- _currentLocal = local;
- }
-
- void LoadLocal(InternalLocal local)
- {
- LoadLocal(local, false);
- }
-
- void LoadLocal(InternalLocal local, bool byAddress)
- {
- _il.Emit(IsByAddress(local.Type) ? OpCodes.Ldloca : OpCodes.Ldloc, local.LocalBuilder);
-
- PushType(local.Type);
- _currentLocal = local.LocalBuilder;
- }
-
- void LoadIndirectLocal(InternalLocal local)
- {
- LoadLocal(local);
-
- IType et = local.Type.ElementType;
- PopType();
- PushType(et);
- OpCode code = GetLoadRefParamCode(et);
- if (code == OpCodes.Ldobj)
- _il.Emit(code, GetSystemType(et));
- else
- _il.Emit(code);
- }
-
- private LocalBuilder StoreTempLocal(IType elementType)
- {
- LocalBuilder temp;
- temp = _il.DeclareLocal(GetSystemType(elementType));
- _il.Emit(OpCodes.Stloc, temp);
- return temp;
- }
-
- void OnAssignment(BinaryExpression node)
- {
- if (NodeType.SlicingExpression == node.Left.NodeType)
- {
- OnAssignmentToSlice(node);
- return;
- }
-
- // when the parent is not a statement we need to leave
- // the value on the stack
- bool leaveValueOnStack = ShouldLeaveValueOnStack(node);
- IEntity tag = TypeSystemServices.GetEntity(node.Left);
- switch (tag.EntityType)
- {
- case EntityType.Local:
- {
- SetLocal(node, (InternalLocal)tag, leaveValueOnStack);
- break;
- }
-
- case EntityType.Parameter:
- {
- InternalParameter param = (InternalParameter)tag;
- if (param.Parameter.IsByRef)
- {
- SetByRefParam(param, node.Right, leaveValueOnStack);
- break;
- }
-
- LoadExpressionWithType(param.Type, node.Right);
-
- if (leaveValueOnStack)
- {
- Dup();
- PushType(param.Type);
- }
- _il.Emit(OpCodes.Starg, param.Index);
- break;
- }
-
- case EntityType.Field:
- {
- IField field = (IField)tag;
- SetField(node, field, node.Left, node.Right, leaveValueOnStack);
- break;
- }
-
- case EntityType.Property:
- {
- SetProperty((IProperty)tag, node.Left, node.Right, leaveValueOnStack);
- break;
- }
-
- case EntityType.Event: //event=null (always internal in this context)
- {
- InternalEvent e = (InternalEvent) tag;
- OpCode opcode = e.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld;
- _il.Emit(OpCodes.Ldnull);
- _il.Emit(opcode, GetFieldBuilder(e.BackingField.Field));
- break;
- }
-
- default:
- {
- NotImplemented(node, tag.ToString());
- break;
- }
- }
- if (!leaveValueOnStack)
- {
- PushVoid();
- }
- }
-
- private void SetByRefParam(InternalParameter param, Expression right, bool leaveValueOnStack)
- {
- LocalBuilder temp = null;
- IType tempType = null;
- if (leaveValueOnStack)
- {
- Visit(right);
- tempType = PopType();
- temp = StoreTempLocal(tempType);
- }
-
- LoadParam(param);
- if (temp != null)
- {
- LoadLocal(temp, tempType);
- PopType();
- }
- else
- LoadExpressionWithType(param.Type, right);
-
- var storecode = GetStoreRefParamCode(param.Type);
- if (IsStobj(storecode)) //passing struct/decimal byref
- _il.Emit(storecode, GetSystemType(param.Type));
- else
- _il.Emit(storecode);
-
- if (null != temp)
- LoadLocal(temp, tempType);
- }
-
- void EmitTypeTest(BinaryExpression node)
- {
- Visit(node.Left);
- IType actualType = PopType();
-
- EmitBoxIfNeeded(TypeSy…
Large files files are truncated, but you can click here to view the full file