Ejemplo n.º 1
0
 public override void OnArrayTypeReference(Boo.Lang.Compiler.Ast.ArrayTypeReference node)
 {
     MethodInvocationExpression mie = new MethodInvocationExpression(
             node.LexicalInfo,
             CreateReference(node, "Boo.Lang.Compiler.Ast.ArrayTypeReference"));
     mie.Arguments.Add(Serialize(node.LexicalInfo));
     if (ShouldSerialize(node.IsPointer))
     {
         mie.NamedArguments.Add(
             new ExpressionPair(
                 CreateReference(node, "IsPointer"),
                 Serialize(node.IsPointer)));
     }
     if (ShouldSerialize(node.ElementType))
     {
         mie.NamedArguments.Add(
             new ExpressionPair(
                 CreateReference(node, "ElementType"),
                 Serialize(node.ElementType)));
     }
     if (ShouldSerialize(node.Rank))
     {
         mie.NamedArguments.Add(
             new ExpressionPair(
                 CreateReference(node, "Rank"),
                 Serialize(node.Rank)));
     }
     Push(mie);
 }
        /// <summary>
        /// Initializes a new instance of the ConstructorInitializerStatement class.
        /// </summary>
        /// <param name="proxy">Proxy object for the statement.</param>
        /// <param name="expression">The expression within this statement.</param>
        internal ConstructorInitializerStatement(CodeUnitProxy proxy, MethodInvocationExpression expression)
            : base(proxy, StatementType.ConstructorInitializer)
        {
            Param.AssertNotNull(proxy, "proxy");
            Param.AssertNotNull(expression, "expression");

            this.expression.Value = expression;
        }
        /// <summary>
        /// Initializes a new instance of the ConstructorInitializerStatement class.
        /// </summary>
        /// <param name="tokens">
        /// The list of tokens that form the statement.
        /// </param>
        /// <param name="expression">
        /// The expression within this statement.
        /// </param>
        internal ConstructorInitializerStatement(CsTokenList tokens, MethodInvocationExpression expression)
            : base(StatementType.ConstructorInitializer, tokens)
        {
            Param.AssertNotNull(tokens, "tokens");
            Param.AssertNotNull(expression, "expression");

            this.expression = expression;
            this.AddExpression(expression);
        }
Ejemplo n.º 4
0
		/// <summary>
		///     Handles the replacement of the <paramref name="invocation" />'s arguments.
		/// </summary>
		public void AddArgumentReplacements(MethodInvocationExpression invocation)
		{
			var methodBody = invocation.Method.MethodBody;
			var parameters = methodBody.Parameters.ToArray();
			var arguments = invocation.Arguments.ToArray();

			Assert.That(parameters.Length == arguments.Length, "Parameters and arguments don't match up.");

			for (var i = 0; i < parameters.Length; ++i)
			{
				if (arguments[i].RefKind != RefKind.None || !VariableAccessClassifier.Classify(methodBody.Body, parameters[i]).IsWritten())
					AddVariableReplacement(parameters[i], arguments[i].Expression);
			}
		}
Ejemplo n.º 5
0
		/// <summary>
		///     Visits an element of type <see cref="MethodInvocationExpression" />.
		/// </summary>
		/// <param name="expression">The <see cref="MethodInvocationExpression" /> instance that should be visited.</param>
		protected internal override BoundNode VisitMethodInvocationExpression(MethodInvocationExpression expression)
		{
			var body = expression.Method.MethodBody.Body;
			var returnStatement = body.Statements[0] as ReturnStatement;

			Requires.That(returnStatement != null,
				"Detected an invalid invocation of method '{0}' declared by '{1}' within the formula: The invoked method does not " +
				"consist of a single return statement only.",
				expression.Method.MethodInfo, expression.Method.MethodInfo.DeclaringType.FullName);

			_variableReplacer.AddArgumentReplacements(expression);

			var replacedBody = (Expression)_variableReplacer.Visit(returnStatement.Expression);
			return Visit(replacedBody);
		}
Ejemplo n.º 6
0
 public override void OnArrayLiteralExpression(Boo.Lang.Compiler.Ast.ArrayLiteralExpression node)
 {
     MethodInvocationExpression mie = new MethodInvocationExpression(
             node.LexicalInfo,
             CreateReference(node, "Boo.Lang.Compiler.Ast.ArrayLiteralExpression"));
     if (ShouldSerialize(node.Items))
     {
         mie.NamedArguments.Add(
             new ExpressionPair(
                 CreateReference(node, "Items"),
                 SerializeCollection(node, "Boo.Lang.Compiler.Ast.ExpressionCollection", node.Items)));
     }
     if (ShouldSerialize(node.Type))
     {
         mie.NamedArguments.Add(
             new ExpressionPair(
                 CreateReference(node, "Type"),
                 Serialize(node.Type)));
     }
     Push(mie);
 }
Ejemplo n.º 7
0
		internal void SerializeSpliceTypeReference(Boo.Lang.Compiler.Ast.SpliceTypeReference node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.SpliceTypeReference"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.IsPointer))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "IsPointer"),
						Serialize(node.IsPointer)));
			}
			if (ShouldSerialize(node.Expression))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Expression"),
						Serialize(node.Expression)));
			}
			Push(mie);
		}
Ejemplo n.º 8
0
		override public void OnConditionalExpression(Boo.Lang.Compiler.Ast.ConditionalExpression node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.ConditionalExpression"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Condition))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Condition"),
						Serialize(node.Condition)));
			}
			if (ShouldSerialize(node.TrueValue))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "TrueValue"),
						Serialize(node.TrueValue)));
			}
			if (ShouldSerialize(node.FalseValue))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "FalseValue"),
						Serialize(node.FalseValue)));
			}
			Push(mie);
		}
 public override void Visit(MethodInvocationExpression node)
 {
     CannotOptimize(node);
 }
Ejemplo n.º 10
0
		override public void OnBlockExpression(Boo.Lang.Compiler.Ast.BlockExpression node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.BlockExpression"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Parameters))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Parameters"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.ParameterDeclarationCollection", node.Parameters)));
			}
			if (ShouldSerialize(node.ReturnType))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "ReturnType"),
						Serialize(node.ReturnType)));
			}
			if (ShouldSerialize(node.Body))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Body"),
						Serialize(node.Body)));
			}
			Push(mie);
		}
Ejemplo n.º 11
0
		override public void OnField(Boo.Lang.Compiler.Ast.Field node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.Field"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Modifiers))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Modifiers"),
						Serialize(node.Modifiers)));
			}
			if (ShouldSerialize(node.Name))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Name"),
						Serialize(node.Name)));
			}
			if (ShouldSerialize(node.Attributes))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Attributes"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.AttributeCollection", node.Attributes)));
			}
			if (ShouldSerialize(node.Type))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Type"),
						Serialize(node.Type)));
			}
			if (ShouldSerialize(node.Initializer))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Initializer"),
						Serialize(node.Initializer)));
			}
			if (ShouldSerialize(node.IsVolatile))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "IsVolatile"),
						Serialize(node.IsVolatile)));
			}
			Push(mie);
		}
Ejemplo n.º 12
0
		override public void OnStatementTypeMember(Boo.Lang.Compiler.Ast.StatementTypeMember node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.StatementTypeMember"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Modifiers))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Modifiers"),
						Serialize(node.Modifiers)));
			}
			if (ShouldSerialize(node.Name))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Name"),
						Serialize(node.Name)));
			}
			if (ShouldSerialize(node.Attributes))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Attributes"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.AttributeCollection", node.Attributes)));
			}
			if (ShouldSerialize(node.Statement))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Statement"),
						Serialize(node.Statement)));
			}
			Push(mie);
		}
Ejemplo n.º 13
0
		override public void OnSlicingExpression(Boo.Lang.Compiler.Ast.SlicingExpression node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.SlicingExpression"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Target))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Target"),
						Serialize(node.Target)));
			}
			if (ShouldSerialize(node.Indices))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Indices"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.SliceCollection", node.Indices)));
			}
			Push(mie);
		}
Ejemplo n.º 14
0
 protected override bool ExpandExtension(ref MethodInvocationExpression extension, MacroStatement macro, MacroStatement parent, ref Statement expansion)
 {
     extension.Arguments.Add(macro.Arguments[0]);
     return(true);
 }
Ejemplo n.º 15
0
 private MethodInvocationExpression CreateGetEnumeratorInvocation(MethodInvocationExpression enumerableConstructorInvocation)
 {
     return(CodeBuilder.CreateMethodInvocation(
                enumerableConstructorInvocation,
                GetGetEnumeratorEntity()));
 }
Ejemplo n.º 16
0
 public override void Visit(MethodInvocationExpression methodInvocationExpression)
 {
     base.Visit(methodInvocationExpression);
     AddReference(GetDeclarationContainer(), (Node)methodInvocationExpression.TypeInference.Declaration);
 }
Ejemplo n.º 17
0
 protected virtual void ExpandQuackInvocation(MethodInvocationExpression node)
 {
     ExpandQuackInvocation(node, RuntimeServices_Invoke);
 }
        // MyCollection list = new MyCollection() { 1, { 2, 2 } , 3 };
        //
        // ==
        //
        // MyCollection temp = new MyCollection();
        // temp.Add(1);
        // temp.Add(2, 2);
        // temp.Add(3);
        // MyCollection list = temp;

        protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount)
        {
            result = null;
            replacedStatementsCount = 0;

            ObjectCreationExpression objectCreation;
            Expression assignee;

            if (!TryGetObjectCreation(statements, startIndex, out objectCreation, out assignee))
            {
                return(false);
            }

            if (objectCreation.Initializer != null && objectCreation.Initializer.InitializerType != InitializerType.CollectionInitializer)
            {
                return(false);
            }

            if (!ImplementsInterface(objectCreation.Type, "System.Collections.IEnumerable"))
            {
                return(false);
            }

            ExpressionCollection addedExpressions = new ExpressionCollection();

            for (int i = startIndex + 1; i < statements.Count; i++)
            {
                Expression expression;
                if (!TryGetNextExpression(statements[i], out expression))
                {
                    break;
                }

                if (expression.CodeNodeType != CodeNodeType.MethodInvocationExpression)
                {
                    break;
                }
                MethodInvocationExpression methodInvocation = (expression as MethodInvocationExpression);
                MethodDefinition           methodDefinition = methodInvocation.MethodExpression.MethodDefinition;

                if (!CompareTargets(assignee, methodInvocation.MethodExpression.Target))
                {
                    break;
                }

                if (methodDefinition.Name != "Add")
                {
                    break;
                }

                if (methodInvocation.Arguments.Count == 0)
                {
                    break;
                }
                else if (methodInvocation.Arguments.Count == 1)
                {
                    addedExpressions.Add(methodInvocation.Arguments[0].Clone());
                }
                else
                {
                    ExpressionCollection currentArguments = new ExpressionCollection(
                        methodInvocation.Arguments.Select(x => x.Clone()));

                    BlockExpression blockExpression = new BlockExpression(currentArguments, null);
                    addedExpressions.Add(blockExpression);
                }
            }

            if (addedExpressions.Count == 0)
            {
                return(false);
            }

            if (objectCreation.Initializer == null)
            {
                var initializer = new InitializerExpression(addedExpressions, InitializerType.CollectionInitializer);
                initializer.IsMultiLine    = true;
                objectCreation.Initializer = initializer;
            }
            else
            {
                foreach (var item in addedExpressions)
                {
                    objectCreation.Initializer.Expressions.Add(item);
                }
            }

            result = statements[startIndex];
            replacedStatementsCount = addedExpressions.Count + 1;
            return(true);
        }
Ejemplo n.º 19
0
        protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, ClassEmitter @class, INamingScope namingScope)
        {
            var invocationType = invocation;

            var genericArguments = Type.EmptyTypes;

            var constructor = invocation.GetConstructors()[0];

            IExpression proxiedMethodTokenExpression;

            if (MethodToOverride.IsGenericMethod)
            {
                // Not in the cache: generic method
                genericArguments             = emitter.MethodBuilder.GetGenericArguments();
                proxiedMethodTokenExpression = new MethodTokenExpression(MethodToOverride.MakeGenericMethod(genericArguments));

                if (invocationType.IsGenericTypeDefinition)
                {
                    // bind generic method arguments to invocation's type arguments
                    invocationType = invocationType.MakeGenericType(genericArguments);
                    constructor    = TypeBuilder.GetConstructor(invocationType, constructor);
                }
            }
            else
            {
                var proxiedMethodToken = @class.CreateStaticField(namingScope.GetUniqueName("token_" + MethodToOverride.Name), typeof(MethodInfo));
                @class.ClassConstructor.CodeBuilder.AddStatement(new AssignStatement(proxiedMethodToken, new MethodTokenExpression(MethodToOverride)));

                proxiedMethodTokenExpression = proxiedMethodToken;
            }

            var methodInterceptors = SetMethodInterceptors(@class, namingScope, emitter, proxiedMethodTokenExpression);

            var dereferencedArguments = IndirectReference.WrapIfByRef(emitter.Arguments);
            var hasByRefArguments     = HasByRefArguments(emitter.Arguments);

            var arguments     = GetCtorArguments(@class, proxiedMethodTokenExpression, dereferencedArguments, methodInterceptors);
            var ctorArguments = ModifyArguments(@class, arguments);

            var invocationLocal = emitter.CodeBuilder.DeclareLocal(invocationType);

            emitter.CodeBuilder.AddStatement(new AssignStatement(invocationLocal,
                                                                 new NewInstanceExpression(constructor, ctorArguments)));

            if (MethodToOverride.ContainsGenericParameters)
            {
                EmitLoadGenericMethodArguments(emitter, MethodToOverride.MakeGenericMethod(genericArguments), invocationLocal);
            }

            if (hasByRefArguments)
            {
                emitter.CodeBuilder.AddStatement(new TryStatement());
            }

            var proceed = new MethodInvocationExpression(invocationLocal, InvocationMethods.Proceed);

            emitter.CodeBuilder.AddStatement(proceed);

            if (hasByRefArguments)
            {
                emitter.CodeBuilder.AddStatement(new FinallyStatement());
            }

            GeneratorUtil.CopyOutAndRefParameters(dereferencedArguments, invocationLocal, MethodToOverride, emitter);

            if (hasByRefArguments)
            {
                emitter.CodeBuilder.AddStatement(new EndExceptionBlockStatement());
            }

            if (MethodToOverride.ReturnType != typeof(void))
            {
                var getRetVal = new MethodInvocationExpression(invocationLocal, InvocationMethods.GetReturnValue);

                // Emit code to ensure a value type return type is not null, otherwise the cast will cause a null-deref
                if (emitter.ReturnType.IsValueType && !emitter.ReturnType.IsNullableType())
                {
                    LocalReference returnValue = emitter.CodeBuilder.DeclareLocal(typeof(object));
                    emitter.CodeBuilder.AddStatement(new AssignStatement(returnValue, getRetVal));

                    emitter.CodeBuilder.AddStatement(new IfNullExpression(returnValue, new ThrowStatement(typeof(InvalidOperationException),
                                                                                                          "Interceptors failed to set a return value, or swallowed the exception thrown by the target")));
                }

                // Emit code to return with cast from ReturnValue
                emitter.CodeBuilder.AddStatement(new ReturnStatement(new ConvertExpression(emitter.ReturnType, getRetVal)));
            }
            else
            {
                emitter.CodeBuilder.AddStatement(new ReturnStatement());
            }

            return(emitter);
        }
Ejemplo n.º 20
0
		internal void SerializeSpliceParameterDeclaration(Boo.Lang.Compiler.Ast.SpliceParameterDeclaration node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.SpliceParameterDeclaration"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Name))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Name"),
						Serialize(node.Name)));
			}
			if (ShouldSerialize(node.Type))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Type"),
						Serialize(node.Type)));
			}
			if (ShouldSerialize(node.Modifiers))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Modifiers"),
						Serialize(node.Modifiers)));
			}
			if (ShouldSerialize(node.Attributes))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Attributes"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.AttributeCollection", node.Attributes)));
			}
			if (ShouldSerialize(node.ParameterDeclaration))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "ParameterDeclaration"),
						Serialize(node.ParameterDeclaration)));
			}
			if (ShouldSerialize(node.NameExpression))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "NameExpression"),
						Serialize(node.NameExpression)));
			}
			Push(mie);
		}
Ejemplo n.º 21
0
		override public void OnExtendedGeneratorExpression(Boo.Lang.Compiler.Ast.ExtendedGeneratorExpression node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.ExtendedGeneratorExpression"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Items))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Items"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.GeneratorExpressionCollection", node.Items)));
			}
			Push(mie);
		}
Ejemplo n.º 22
0
 public override void OnMethodInvocationExpression(MethodInvocationExpression node)
 {
     base.OnMethodInvocationExpression(node);
     node.ExpressionType = _replacer.MapType(node.ExpressionType);
 }
Ejemplo n.º 23
0
		override public void OnCustomStatement(Boo.Lang.Compiler.Ast.CustomStatement node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.CustomStatement"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Modifier))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Modifier"),
						Serialize(node.Modifier)));
			}
			Push(mie);
		}
Ejemplo n.º 24
0
        override public void Apply(Boo.Lang.Compiler.Ast.Node node)
        {
            string name;
            Node   parent;
            string errorMessage = null;

            ParameterDeclaration pd = node as ParameterDeclaration;

            if (pd != null)
            {
                name   = pd.Name;
                parent = pd.ParentNode;
            }
            else
            {
                Property prop = node as Property;
                if (prop != null && prop.Setter != null)
                {
                    name   = "value";
                    parent = prop.Setter;
                }
                else
                {
                    InvalidNodeForAttribute("ParameterDeclaration or Property");
                    return;
                }
            }

            string            exceptionClass = null;
            StatementModifier modifier       = null;

            if (null == _condition)
            {
                exceptionClass = "ArgumentNullException";
                modifier       = new StatementModifier(
                    StatementModifierType.If,
                    new BinaryExpression(BinaryOperatorType.ReferenceEquality,
                                         new ReferenceExpression(name),
                                         new NullLiteralExpression()));
            }
            else
            {
                exceptionClass = "ArgumentException";
                modifier       = new StatementModifier(
                    StatementModifierType.Unless,
                    _condition);
                errorMessage = "Expected: " + _condition.ToString();
            }

            MethodInvocationExpression x = new MethodInvocationExpression();

            x.Target = new MemberReferenceExpression(
                new ReferenceExpression("System"),
                exceptionClass);
            if (null != errorMessage)
            {
                x.Arguments.Add(new StringLiteralExpression(errorMessage));
            }
            x.Arguments.Add(new StringLiteralExpression(name));

            RaiseStatement rs = new RaiseStatement(x, modifier);

            rs.LexicalInfo = LexicalInfo;

            Method method = parent as Method;

            if (null != method)
            {
                method.Body.Statements.Insert(0, rs);
            }
            else
            {
                Property property = (Property)parent;
                if (null != property.Getter)
                {
                    property.Getter.Body.Statements.Insert(0, rs);
                }
                if (null != property.Setter)
                {
                    property.Setter.Body.Statements.Insert(0, rs.CloneNode());
                }
            }
        }
Ejemplo n.º 25
0
		override public void OnImport(Boo.Lang.Compiler.Ast.Import node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.Import"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Expression))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Expression"),
						Serialize(node.Expression)));
			}
			if (ShouldSerialize(node.AssemblyReference))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "AssemblyReference"),
						Serialize(node.AssemblyReference)));
			}
			if (ShouldSerialize(node.Alias))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Alias"),
						Serialize(node.Alias)));
			}
			Push(mie);
		}
Ejemplo n.º 26
0
 protected virtual void PrepareConstructorCalls()
 {
     _stateMachineConstructorInvocation = CodeBuilder.CreateGenericConstructorInvocation(
         (IType)_stateMachineClass.ClassDefinition.Entity,
         GetStateMachineGenericParams());
 }
Ejemplo n.º 27
0
		override public void OnEvent(Boo.Lang.Compiler.Ast.Event node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.Event"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Modifiers))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Modifiers"),
						Serialize(node.Modifiers)));
			}
			if (ShouldSerialize(node.Name))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Name"),
						Serialize(node.Name)));
			}
			if (ShouldSerialize(node.Attributes))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Attributes"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.AttributeCollection", node.Attributes)));
			}
			if (ShouldSerialize(node.Add))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Add"),
						Serialize(node.Add)));
			}
			if (ShouldSerialize(node.Remove))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Remove"),
						Serialize(node.Remove)));
			}
			if (ShouldSerialize(node.Raise))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Raise"),
						Serialize(node.Raise)));
			}
			if (ShouldSerialize(node.Type))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Type"),
						Serialize(node.Type)));
			}
			Push(mie);
		}
Ejemplo n.º 28
0
 public override void VisitMethodInvocationExpression(MethodInvocationExpression node)
 {
     TrySetMethodInvocationPendingName(node.MethodExpression);
     ClearPendingForSuggestion();
     base.VisitMethodInvocationExpression(node);
 }
Ejemplo n.º 29
0
 override public void LeaveMethodInvocationExpression(MethodInvocationExpression node)
 {
     OnExpression(node);
 }
 public override ICodeNode VisitMethodInvocationExpression(MethodInvocationExpression node)
 {
     dummyVar0 = this.VisitMethodInvocationExpression(node);
     this.FixArguments(node.get_MethodExpression().get_Method(), node.get_Arguments());
     return(node);
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CompileExpression"/> class.
 /// </summary>
 /// <param name="profile">
 /// The profile.
 /// </param>
 /// <param name="function">
 /// The function.
 /// </param>
 public CompileExpression(string profile, MethodInvocationExpression function)
 {
     Profile  = new Identifier(profile);
     Function = function;
 }
Ejemplo n.º 32
0
 public static Expression dependencies(MethodInvocationExpression addDependencyMethod)
 {
     return(addDependencyMethod);
 }
        private bool CheckTheFinallyClause(BlockStatement theFinally)
        {
            //At most the finally can be: bool cond = flag != false; if(cond) { Monitor.Exit(...); }
            int statementsCount = theFinally.Statements.Count;

            if (statementsCount > 2 && statementsCount == 0)
            {
                return(false);
            }

            MethodInvocationExpression theMethodInvocation = null;

            if (this.lockType == LockType.WithFlag)
            {
                VariableReference theConditionVariable = null;
                if (statementsCount == 2)
                {
                    if (theFinally.Statements[0].CodeNodeType != CodeNodeType.ExpressionStatement)
                    {
                        return(false);
                    }

                    BinaryExpression theConditionAssignExpression = (theFinally.Statements[0] as ExpressionStatement).Expression as BinaryExpression;
                    if (theConditionAssignExpression == null || !theConditionAssignExpression.IsAssignmentExpression ||
                        theConditionAssignExpression.Left.CodeNodeType != CodeNodeType.VariableReferenceExpression)
                    {
                        return(false);
                    }

                    theConditionVariable = (theConditionAssignExpression.Left as VariableReferenceExpression).Variable;
                }

                if (statementsCount == 0)
                {
                    return(false);
                }

                IfStatement theIf = theFinally.Statements[statementsCount - 1] as IfStatement;
                if (theIf == null)
                {
                    return(false);
                }

                if (theConditionVariable != null &&
                    (theIf.Condition.CodeNodeType != CodeNodeType.UnaryExpression ||
                     (theIf.Condition as UnaryExpression).Operator != UnaryOperator.LogicalNot ||
                     (theIf.Condition as UnaryExpression).Operand.CodeNodeType != CodeNodeType.VariableReferenceExpression ||
                     ((theIf.Condition as UnaryExpression).Operand as VariableReferenceExpression).Variable != theConditionVariable))
                {
                    return(false);
                }

                return(CheckTheIfStatement(theIf));
            }
            else //LockType.Simple
            {
                if (statementsCount > 1 || theFinally.Statements[0].CodeNodeType != CodeNodeType.ExpressionStatement)
                {
                    return(false);
                }

                theMethodInvocation = (theFinally.Statements[0] as ExpressionStatement).Expression as MethodInvocationExpression;
                return(CheckTheMethodInvocation(theMethodInvocation, "Exit"));
            }
        }
Ejemplo n.º 34
0
 public static Expression get_from(MethodInvocationExpression get)
 {
     return(get);
 }
Ejemplo n.º 35
0
		override public void OnBinaryExpression(Boo.Lang.Compiler.Ast.BinaryExpression node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.BinaryExpression"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Operator))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Operator"),
						Serialize(node.Operator)));
			}
			if (ShouldSerialize(node.Left))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Left"),
						Serialize(node.Left)));
			}
			if (ShouldSerialize(node.Right))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Right"),
						Serialize(node.Right)));
			}
			Push(mie);
		}
Ejemplo n.º 36
0
 public virtual T VisitMethodInvocationExpression(MethodInvocationExpression methodInvocationExpression)
 {
     return(VisitChildren(methodInvocationExpression));
 }
Ejemplo n.º 37
0
		override public void OnDoubleLiteralExpression(Boo.Lang.Compiler.Ast.DoubleLiteralExpression node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.DoubleLiteralExpression"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Value))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Value"),
						Serialize(node.Value)));
			}
			if (ShouldSerialize(node.IsSingle))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "IsSingle"),
						Serialize(node.IsSingle)));
			}
			Push(mie);
		}
Ejemplo n.º 38
0
        private static Expression GetQueryExpression(ActionFlowGraph afg)
        {
            IDictionary <int, Expression> variables = new Dictionary <int, Expression>();
            ActionBlock block = afg.Blocks[0];

            while (block != null)
            {
                switch (block.ActionType)
                {
                case ActionType.Invoke:
                    InvokeActionBlock          invokeBlock = (InvokeActionBlock)block;
                    MethodInvocationExpression invocation  = invokeBlock.Expression;
                    if (IsActivateInvocation(invocation) ||
                        IsNoSideEffectIndirectActivationInvocation(invocation))
                    {
                        block = invokeBlock.Next;
                        break;
                    }

                    UnsupportedExpression(invocation);
                    break;

                case ActionType.ConditionalBranch:
                    UnsupportedPredicate("Conditional blocks are not supported.");
                    break;

                case ActionType.Branch:
                    block = ((BranchActionBlock)block).Target;
                    break;

                case ActionType.Assign:
                {
                    AssignActionBlock           assignBlock = (AssignActionBlock)block;
                    AssignExpression            assign      = assignBlock.AssignExpression;
                    VariableReferenceExpression variable    = assign.Target as VariableReferenceExpression;
                    if (null == variable)
                    {
                        UnsupportedExpression(assign);
                    }
                    else
                    {
                        if (variables.ContainsKey(variable.Variable.Index))
                        {
                            UnsupportedExpression(assign.Expression);
                        }

                        variables.Add(variable.Variable.Index, assign.Expression);
                        block = assignBlock.Next;
                    }
                    break;
                }

                case ActionType.Return:
                {
                    Expression expression = ((ReturnActionBlock)block).Expression;
                    VariableReferenceExpression variable = expression as VariableReferenceExpression;
                    return(null == variable
                                                                ? expression
                                                                : variables[variable.Variable.Index]);
                }
                }
            }
            return(null);
        }
Ejemplo n.º 39
0
		internal void SerializeSpliceMemberReferenceExpression(Boo.Lang.Compiler.Ast.SpliceMemberReferenceExpression node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.SpliceMemberReferenceExpression"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Target))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Target"),
						Serialize(node.Target)));
			}
			if (ShouldSerialize(node.NameExpression))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "NameExpression"),
						Serialize(node.NameExpression)));
			}
			Push(mie);
		}
Ejemplo n.º 40
0
        protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, ClassEmitter @class,
                                                                ProxyGenerationOptions options, INamingScope namingScope)
        {
            var invocationType = invocation;

            Trace.Assert(MethodToOverride.IsGenericMethod == invocationType.IsGenericTypeDefinition());
            var genericArguments = TypeExtender.EmptyTypes;

            var constructor = invocation.GetConstructors()[0];

            Expression proxiedMethodTokenExpression;

            if (MethodToOverride.IsGenericMethod)
            {
                // bind generic method arguments to invocation's type arguments
                genericArguments = emitter.MethodBuilder.GetGenericArguments();
                invocationType   = invocationType.MakeGenericType(genericArguments);
                constructor      = TypeBuilder.GetConstructor(invocationType, constructor);

                // Not in the cache: generic method
                proxiedMethodTokenExpression = new MethodTokenExpression(MethodToOverride.MakeGenericMethod(genericArguments));
            }
            else
            {
                var proxiedMethodToken = @class.CreateStaticField(namingScope.GetUniqueName("token_" + MethodToOverride.Name),
                                                                  typeof(MethodInfo));
                @class.ClassConstructor.CodeBuilder.AddStatement(new AssignStatement(proxiedMethodToken,
                                                                                     new MethodTokenExpression(MethodToOverride)));

                proxiedMethodTokenExpression = proxiedMethodToken.ToExpression();
            }

            var dereferencedArguments = IndirectReference.WrapIfByRef(emitter.Arguments);
            var hasByRefArguments     = HasByRefArguments(emitter.Arguments);

            var arguments = GetCtorArguments(@class, namingScope, proxiedMethodTokenExpression,
                                             dereferencedArguments);
            var ctorArguments = ModifyArguments(@class, arguments);

            var invocationLocal = emitter.CodeBuilder.DeclareLocal(invocationType);

            emitter.CodeBuilder.AddStatement(new AssignStatement(invocationLocal,
                                                                 new NewInstanceExpression(constructor, ctorArguments)));

            if (MethodToOverride.ContainsGenericParameters)
            {
                EmitLoadGenricMethodArguments(emitter, MethodToOverride.MakeGenericMethod(genericArguments), invocationLocal);
            }

            if (hasByRefArguments)
            {
                emitter.CodeBuilder.AddStatement(new TryStatement());
            }

            var proceed = new ExpressionStatement(new MethodInvocationExpression(invocationLocal, InvocationMethods.Proceed));

            emitter.CodeBuilder.AddStatement(proceed);

            if (hasByRefArguments)
            {
                emitter.CodeBuilder.AddStatement(new FinallyStatement());
            }

            GeneratorUtil.CopyOutAndRefParameters(dereferencedArguments, invocationLocal, MethodToOverride, emitter);

            if (hasByRefArguments)
            {
                emitter.CodeBuilder.AddStatement(new EndExceptionBlockStatement());
            }

            if (MethodToOverride.ReturnType != typeof(void))
            {
                // Emit code to return with cast from ReturnValue

                // @mbrit - 2012-05-31 - see the note associated with the GetReturnValueForWinRt declaration
                // for more information on this...

                var useWinRtGenericHandler = false;
#if NETFX_CORE
                if (emitter.ReturnType == typeof(int) || emitter.ReturnType == typeof(bool))
                {
                    useWinRtGenericHandler = true;
                }
#endif
                if (!(useWinRtGenericHandler))
                {
                    var getRetVal = new MethodInvocationExpression(invocationLocal, InvocationMethods.GetReturnValue);
                    emitter.CodeBuilder.AddStatement(new ReturnStatement(new ConvertExpression(emitter.ReturnType, getRetVal)));
                }
                else
                {
#if NETFX_CORE
                    var grvArgs   = new Type[] { emitter.ReturnType };
                    var grvCall   = InvocationMethods.GetReturnValueForWinRt.MakeGenericMethod(grvArgs);
                    var getRetVal = new MethodInvocationExpression(invocationLocal, grvCall);
                    emitter.CodeBuilder.AddStatement(new ReturnStatement(getRetVal));
#endif
                }
            }
            else
            {
                emitter.CodeBuilder.AddStatement(new ReturnStatement());
            }

            return(emitter);
        }
Ejemplo n.º 41
0
		override public void OnCollectionInitializationExpression(Boo.Lang.Compiler.Ast.CollectionInitializationExpression node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.CollectionInitializationExpression"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Collection))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Collection"),
						Serialize(node.Collection)));
			}
			if (ShouldSerialize(node.Initializer))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Initializer"),
						Serialize(node.Initializer)));
			}
			Push(mie);
		}
Ejemplo n.º 42
0
        /// <summary>
        /// Optimize the <c>for item in range()</c> construct
        /// </summary>
        /// <param name="node">the for statement to check</param>
        private void CheckForItemInRangeLoop(ForStatement node)
        {
            MethodInvocationExpression mi = node.Iterator as MethodInvocationExpression;

            if (null == mi)
            {
                return;
            }
            if (!IsRangeInvocation(mi))
            {
                return;
            }

            DeclarationCollection declarations = node.Declarations;

            if (declarations.Count != 1)
            {
                return;
            }

            ExpressionCollection args = mi.Arguments;
            Block body = new Block(node.LexicalInfo);

            Expression min;
            Expression max;
            Expression step;

            if (args.Count == 1)
            {
                min  = CodeBuilder.CreateIntegerLiteral(0);
                max  = args[0];
                step = CodeBuilder.CreateIntegerLiteral(1);
            }
            else if (args.Count == 2)
            {
                min  = args[0];
                max  = args[1];
                step = CodeBuilder.CreateIntegerLiteral(1);
            }
            else
            {
                min  = args[0];
                max  = args[1];
                step = args[2];
            }

            InternalLocal numVar = CodeBuilder.DeclareTempLocal(
                _currentMethod,
                TypeSystemServices.IntType);
            Expression numRef = CodeBuilder.CreateReference(numVar);

            // __num = <min>
            body.Add(
                CodeBuilder.CreateAssignment(
                    numRef,
                    min));

            Expression endRef;

            if (max.NodeType == NodeType.IntegerLiteralExpression)
            {
                endRef = max;
            }
            else
            {
                InternalLocal endVar = CodeBuilder.DeclareTempLocal(
                    _currentMethod,
                    TypeSystemServices.IntType);
                endRef = CodeBuilder.CreateReference(endVar);

                // __end = <end>
                body.Add(
                    CodeBuilder.CreateAssignment(
                        endRef,
                        max));
            }

            if (args.Count == 1)
            {
                if (max.NodeType == NodeType.IntegerLiteralExpression)
                {
                    if (((IntegerLiteralExpression)max).Value < 0)
                    {
                        // raise ArgumentOutOfRangeException("max") (if <max> < 0)
                        Statement statement = CodeBuilder.RaiseException(
                            body.LexicalInfo,
                            TypeSystemServices.Map(System_ArgumentOutOfRangeException_ctor),
                            CodeBuilder.CreateStringLiteral("max"));

                        body.Add(statement);
                    }
                }
                else
                {
                    IfStatement ifStatement = new IfStatement(body.LexicalInfo);
                    ifStatement.TrueBlock = new Block();

                    // raise ArgumentOutOfRangeException("max") if __end < 0
                    Statement statement = CodeBuilder.RaiseException(
                        body.LexicalInfo,
                        TypeSystemServices.Map(System_ArgumentOutOfRangeException_ctor),
                        CodeBuilder.CreateStringLiteral("max"));

                    ifStatement.Condition = CodeBuilder.CreateBoundBinaryExpression(
                        TypeSystemServices.BoolType,
                        BinaryOperatorType.LessThan,
                        endRef,
                        CodeBuilder.CreateIntegerLiteral(0));

                    ifStatement.TrueBlock.Add(statement);

                    body.Add(ifStatement);
                }
            }

            Expression stepRef;

            switch (args.Count)
            {
            case 1:
                stepRef = CodeBuilder.CreateIntegerLiteral(1);
                break;

            case 2:
                if ((min.NodeType == NodeType.IntegerLiteralExpression) &&
                    (max.NodeType == NodeType.IntegerLiteralExpression) &&
                    (((IntegerLiteralExpression)max).Value < ((IntegerLiteralExpression)min).Value))
                {
                    // __step = -1
                    stepRef = CodeBuilder.CreateIntegerLiteral(-1);
                }
                else if ((min.NodeType == NodeType.IntegerLiteralExpression) &&
                         (max.NodeType == NodeType.IntegerLiteralExpression))
                {
                    // __step = 1
                    stepRef = CodeBuilder.CreateIntegerLiteral(1);
                }
                else
                {
                    InternalLocal stepVar = CodeBuilder.DeclareTempLocal(
                        _currentMethod,
                        TypeSystemServices.IntType);
                    stepRef = CodeBuilder.CreateReference(stepVar);

                    // __step = 1
                    body.Add(
                        CodeBuilder.CreateAssignment(
                            stepRef,
                            CodeBuilder.CreateIntegerLiteral(1)));

                    // __step = -1 if __end < __num
                    IfStatement ifStatement = new IfStatement(node.LexicalInfo);

                    ifStatement.Condition = CodeBuilder.CreateBoundBinaryExpression(
                        TypeSystemServices.BoolType,
                        BinaryOperatorType.LessThan,
                        endRef,
                        numRef);

                    ifStatement.TrueBlock = new Block();

                    ifStatement.TrueBlock.Add(
                        CodeBuilder.CreateAssignment(
                            stepRef,
                            CodeBuilder.CreateIntegerLiteral(-1)));

                    body.Add(ifStatement);
                }
                break;

            default:
                if (step.NodeType == NodeType.IntegerLiteralExpression)
                {
                    stepRef = step;
                }
                else
                {
                    InternalLocal stepVar = CodeBuilder.DeclareTempLocal(
                        _currentMethod,
                        TypeSystemServices.IntType);
                    stepRef = CodeBuilder.CreateReference(stepVar);

                    // __step = <step>
                    body.Add(
                        CodeBuilder.CreateAssignment(
                            stepRef,
                            step));
                }
                break;
            }


            if (args.Count == 3)
            {
                Expression condition = null;
                bool       run       = false;

                if (step.NodeType == NodeType.IntegerLiteralExpression)
                {
                    if (((IntegerLiteralExpression)step).Value < 0)
                    {
                        if ((max.NodeType == NodeType.IntegerLiteralExpression) &&
                            (min.NodeType == NodeType.IntegerLiteralExpression))
                        {
                            run = (((IntegerLiteralExpression)max).Value > ((IntegerLiteralExpression)min).Value);
                        }
                        else
                        {
                            condition = CodeBuilder.CreateBoundBinaryExpression(
                                TypeSystemServices.BoolType,
                                BinaryOperatorType.GreaterThan,
                                endRef,
                                numRef);
                        }
                    }
                    else
                    {
                        if ((max.NodeType == NodeType.IntegerLiteralExpression) &&
                            (min.NodeType == NodeType.IntegerLiteralExpression))
                        {
                            run = (((IntegerLiteralExpression)max).Value < ((IntegerLiteralExpression)min).Value);
                        }
                        else
                        {
                            condition = CodeBuilder.CreateBoundBinaryExpression(
                                TypeSystemServices.BoolType,
                                BinaryOperatorType.LessThan,
                                endRef,
                                numRef);
                        }
                    }
                }
                else
                {
                    if ((max.NodeType == NodeType.IntegerLiteralExpression) &&
                        (min.NodeType == NodeType.IntegerLiteralExpression))
                    {
                        if (((IntegerLiteralExpression)max).Value < ((IntegerLiteralExpression)min).Value)
                        {
                            condition = CodeBuilder.CreateBoundBinaryExpression(
                                TypeSystemServices.BoolType,
                                BinaryOperatorType.GreaterThan,
                                stepRef,
                                CodeBuilder.CreateIntegerLiteral(0));
                        }
                        else
                        {
                            condition = CodeBuilder.CreateBoundBinaryExpression(
                                TypeSystemServices.BoolType,
                                BinaryOperatorType.LessThan,
                                stepRef,
                                CodeBuilder.CreateIntegerLiteral(0));
                        }
                    }
                    else
                    {
                        condition = CodeBuilder.CreateBoundBinaryExpression(
                            TypeSystemServices.BoolType,
                            BinaryOperatorType.Or,
                            CodeBuilder.CreateBoundBinaryExpression(
                                TypeSystemServices.BoolType,
                                BinaryOperatorType.And,
                                CodeBuilder.CreateBoundBinaryExpression(
                                    TypeSystemServices.BoolType,
                                    BinaryOperatorType.LessThan,
                                    stepRef,
                                    CodeBuilder.CreateIntegerLiteral(0)),
                                CodeBuilder.CreateBoundBinaryExpression(
                                    TypeSystemServices.BoolType,
                                    BinaryOperatorType.GreaterThan,
                                    endRef,
                                    numRef)),
                            CodeBuilder.CreateBoundBinaryExpression(
                                TypeSystemServices.BoolType,
                                BinaryOperatorType.And,
                                CodeBuilder.CreateBoundBinaryExpression(
                                    TypeSystemServices.BoolType,
                                    BinaryOperatorType.GreaterThan,
                                    stepRef,
                                    CodeBuilder.CreateIntegerLiteral(0)),
                                CodeBuilder.CreateBoundBinaryExpression(
                                    TypeSystemServices.BoolType,
                                    BinaryOperatorType.LessThan,
                                    endRef,
                                    numRef)));
                    }
                }

                // raise ArgumentOutOfRangeException("step") if (__step < 0 and __end > __begin) or (__step > 0 and __end < __begin)
                Statement statement = CodeBuilder.RaiseException(
                    body.LexicalInfo,
                    TypeSystemServices.Map(System_ArgumentOutOfRangeException_ctor),
                    CodeBuilder.CreateStringLiteral("step"));

                if (condition != null)
                {
                    IfStatement ifStatement = new IfStatement(body.LexicalInfo);
                    ifStatement.TrueBlock = new Block();

                    ifStatement.Condition = condition;

                    ifStatement.TrueBlock.Add(statement);

                    body.Add(ifStatement);
                }
                else if (run)
                {
                    body.Add(statement);
                }

                // __end = __num + __step * cast(int, Math.Ceiling((__end - __num)/cast(double, __step)))
                if ((step.NodeType == NodeType.IntegerLiteralExpression) &&
                    (max.NodeType == NodeType.IntegerLiteralExpression) &&
                    (min.NodeType == NodeType.IntegerLiteralExpression))
                {
                    int stepVal = (int)((IntegerLiteralExpression)step).Value;
                    int maxVal  = (int)((IntegerLiteralExpression)max).Value;
                    int minVal  = (int)((IntegerLiteralExpression)min).Value;
                    endRef = CodeBuilder.CreateIntegerLiteral(
                        minVal + stepVal * (int)System.Math.Ceiling((maxVal - minVal) / ((double)stepVal)));
                }
                else
                {
                    Expression endBak = endRef;
                    if (max.NodeType == NodeType.IntegerLiteralExpression)
                    {
                        InternalLocal endVar = CodeBuilder.DeclareTempLocal(
                            _currentMethod,
                            TypeSystemServices.IntType);
                        endRef = CodeBuilder.CreateReference(endVar);
                    }

                    body.Add(
                        CodeBuilder.CreateAssignment(
                            endRef,
                            CodeBuilder.CreateBoundBinaryExpression(
                                TypeSystemServices.IntType,
                                BinaryOperatorType.Addition,
                                numRef,
                                CodeBuilder.CreateBoundBinaryExpression(
                                    TypeSystemServices.IntType,
                                    BinaryOperatorType.Multiply,
                                    stepRef,
                                    CodeBuilder.CreateCast(
                                        TypeSystemServices.IntType,
                                        CodeBuilder.CreateMethodInvocation(
                                            TypeSystemServices.Map(System_Math_Ceiling),
                                            CodeBuilder.CreateBoundBinaryExpression(
                                                TypeSystemServices.DoubleType,
                                                BinaryOperatorType.Division,
                                                CodeBuilder.CreateBoundBinaryExpression(
                                                    TypeSystemServices.IntType,
                                                    BinaryOperatorType.Subtraction,
                                                    endBak,
                                                    numRef),
                                                CodeBuilder.CreateCast(
                                                    TypeSystemServices.DoubleType,
                                                    stepRef))))))));
                }
            }

            // while __num != __end:
            WhileStatement ws = new WhileStatement(node.LexicalInfo);

            BinaryOperatorType op = BinaryOperatorType.Inequality;

            if (stepRef.NodeType == NodeType.IntegerLiteralExpression)
            {
                if (((IntegerLiteralExpression)stepRef).Value > 0)
                {
                    op = BinaryOperatorType.LessThan;
                }
                else
                {
                    op = BinaryOperatorType.GreaterThan;
                }
            }

            ws.Condition = CodeBuilder.CreateBoundBinaryExpression(
                TypeSystemServices.BoolType,
                op,
                numRef,
                endRef);
            ws.Condition.LexicalInfo = node.LexicalInfo;

            //	item = __num
            ws.Block.Add(
                CodeBuilder.CreateAssignment(
                    CodeBuilder.CreateReference((InternalLocal)declarations[0].Entity),
                    numRef));

            Block rawBlock = new Block();

            rawBlock["checked"] = false;

            //  __num += __step
            rawBlock.Add(
                CodeBuilder.CreateAssignment(
                    numRef,
                    CodeBuilder.CreateBoundBinaryExpression(
                        TypeSystemServices.IntType,
                        BinaryOperatorType.Addition,
                        numRef,
                        stepRef)));

            ws.Block.Add(rawBlock as Statement);

            //	<block>
            ws.Block.Add(node.Block);

            body.Add(ws);

            ReplaceCurrentNode(body);
        }
Ejemplo n.º 43
0
		override public void OnSlice(Boo.Lang.Compiler.Ast.Slice node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.Slice"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Begin))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Begin"),
						Serialize(node.Begin)));
			}
			if (ShouldSerialize(node.End))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "End"),
						Serialize(node.End)));
			}
			if (ShouldSerialize(node.Step))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Step"),
						Serialize(node.Step)));
			}
			Push(mie);
		}
Ejemplo n.º 44
0
 bool IsInsideWithBlock(MethodInvocationExpression expression)
 {
     return(expression.ParentNode is WithMacro.WithBinaryExpression);
 }
Ejemplo n.º 45
0
		override public void OnTryCastExpression(Boo.Lang.Compiler.Ast.TryCastExpression node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.TryCastExpression"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Target))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Target"),
						Serialize(node.Target)));
			}
			if (ShouldSerialize(node.Type))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Type"),
						Serialize(node.Type)));
			}
			Push(mie);
		}
 public virtual ICodeNode VisitMethodInvocationExpression(MethodInvocationExpression node)
 {
     node.MethodExpression = (MethodReferenceExpression)Visit(node.MethodExpression);
     node.Arguments        = (ExpressionCollection)Visit(node.Arguments);
     return(node);
 }
Ejemplo n.º 47
0
		override public void OnCustomExpression(Boo.Lang.Compiler.Ast.CustomExpression node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.CustomExpression"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			Push(mie);
		}
 private ICodeNode VisitCtorExpression(MethodInvocationExpression node)
 {
     node.Arguments = (ExpressionCollection)Visit(node.Arguments);
     return(node);
 }
Ejemplo n.º 49
0
		override public void OnGenericTypeDefinitionReference(Boo.Lang.Compiler.Ast.GenericTypeDefinitionReference node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.GenericTypeDefinitionReference"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.IsPointer))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "IsPointer"),
						Serialize(node.IsPointer)));
			}
			if (ShouldSerialize(node.Name))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Name"),
						Serialize(node.Name)));
			}
			if (ShouldSerialize(node.GenericPlaceholders))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "GenericPlaceholders"),
						Serialize(node.GenericPlaceholders)));
			}
			Push(mie);
		}
Ejemplo n.º 50
0
 protected virtual bool ExpandExtension(ref MethodInvocationExpression extension,
                                        MacroStatement macro, MacroStatement parent,
                                        ref Statement expansion)
 {
     return(true);
 }
Ejemplo n.º 51
0
		override public void OnEnumDefinition(Boo.Lang.Compiler.Ast.EnumDefinition node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.EnumDefinition"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Modifiers))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Modifiers"),
						Serialize(node.Modifiers)));
			}
			if (ShouldSerialize(node.Name))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Name"),
						Serialize(node.Name)));
			}
			if (ShouldSerialize(node.Attributes))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Attributes"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.AttributeCollection", node.Attributes)));
			}
			if (ShouldSerialize(node.Members))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Members"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.TypeMemberCollection", node.Members)));
			}
			if (ShouldSerialize(node.BaseTypes))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "BaseTypes"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.TypeReferenceCollection", node.BaseTypes)));
			}
			if (ShouldSerialize(node.GenericParameters))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "GenericParameters"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.GenericParameterDeclarationCollection", node.GenericParameters)));
			}
			Push(mie);
		}
Ejemplo n.º 52
0
        private void FixAsyncMethodBody(MethodInvocationExpression stateMachineConstructorInvocation)
        {
            var method = _method.Method;
            // If the async method's result type is a type parameter of the method, then the AsyncTaskMethodBuilder<T>
            // needs to use the method's type parameters inside the rewritten method body. All other methods generated
            // during async rewriting are members of the synthesized state machine struct, and use the type parameters
            // structs type parameters.
            AsyncMethodBuilderMemberCollection methodScopeAsyncMethodBuilderMemberCollection;

            if (!AsyncMethodBuilderMemberCollection.TryCreate(
                    TypeSystemServices,
                    method,
                    MethodGenArg(false),
                    out methodScopeAsyncMethodBuilderMemberCollection))
            {
                throw new NotImplementedException("Custom async patterns are not supported");
            }

            var bodyBuilder     = new Block();
            var builderVariable = CodeBuilder.DeclareTempLocal(method, methodScopeAsyncMethodBuilderMemberCollection.BuilderType);

            var stateMachineType = stateMachineConstructorInvocation.ExpressionType;

            var stateMachineVariable = CodeBuilder.DeclareLocal(
                method,
                UniqueName("async"),
                stateMachineType);

            bodyBuilder.Add(CodeBuilder.CreateAssignment(
                                CodeBuilder.CreateLocalReference(stateMachineVariable),
                                stateMachineConstructorInvocation));

            // local.$builder = System.Runtime.CompilerServices.AsyncTaskMethodBuilder<typeArgs>.Create();
            bodyBuilder.Add(
                CodeBuilder.CreateAssignment(
                    CodeBuilder.CreateMemberReference(
                        CodeBuilder.CreateLocalReference(stateMachineVariable),
                        ExternalFieldEntity((IField)_asyncMethodBuilderField.Entity, stateMachineType)),
                    CodeBuilder.CreateMethodInvocation(methodScopeAsyncMethodBuilderMemberCollection.CreateBuilder)));

            // local.$stateField = NotStartedStateMachine
            bodyBuilder.Add(
                CodeBuilder.CreateAssignment(
                    CodeBuilder.CreateMemberReference(
                        CodeBuilder.CreateLocalReference(stateMachineVariable),
                        ExternalFieldEntity(_state, stateMachineType)),
                    CodeBuilder.CreateIntegerLiteral(StateMachineStates.NotStartedStateMachine)));

            bodyBuilder.Add(
                CodeBuilder.CreateAssignment(
                    CodeBuilder.CreateLocalReference(builderVariable),
                    CodeBuilder.CreateMemberReference(
                        CodeBuilder.CreateLocalReference(stateMachineVariable),
                        ExternalFieldEntity((IField)_asyncMethodBuilderField.Entity, stateMachineType))));

            // local.$builder.Start(ref local) -- binding to the method AsyncTaskMethodBuilder<typeArgs>.Start()
            bodyBuilder.Add(
                CodeBuilder.CreateMethodInvocation(
                    CodeBuilder.CreateLocalReference(builderVariable),
                    methodScopeAsyncMethodBuilderMemberCollection.Start.GenericInfo.ConstructMethod(stateMachineType),
                    CodeBuilder.CreateLocalReference(stateMachineVariable)));

            var methodBuilderField = stateMachineType.ConstructedInfo == null
                        ? (IField)_asyncMethodBuilderField.Entity
                        : stateMachineType.ConstructedInfo.Map((IField)_asyncMethodBuilderField.Entity);

            bodyBuilder.Add(method.ReturnType.Entity == TypeSystemServices.VoidType
                ? new ReturnStatement()
                : new ReturnStatement(
                                CodeBuilder.CreateMethodInvocation(
                                    CodeBuilder.CreateMemberReference(
                                        CodeBuilder.CreateLocalReference(stateMachineVariable),
                                        methodBuilderField),
                                    methodScopeAsyncMethodBuilderMemberCollection.Task.GetGetMethod())));

            _method.Method.Body = bodyBuilder;
        }
Ejemplo n.º 53
0
		override public void OnProperty(Boo.Lang.Compiler.Ast.Property node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.Property"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Modifiers))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Modifiers"),
						Serialize(node.Modifiers)));
			}
			if (ShouldSerialize(node.Name))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Name"),
						Serialize(node.Name)));
			}
			if (ShouldSerialize(node.Attributes))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Attributes"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.AttributeCollection", node.Attributes)));
			}
			if (ShouldSerialize(node.Parameters))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Parameters"),
						SerializeCollection(node, "Boo.Lang.Compiler.Ast.ParameterDeclarationCollection", node.Parameters)));
			}
			if (ShouldSerialize(node.Getter))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Getter"),
						Serialize(node.Getter)));
			}
			if (ShouldSerialize(node.Setter))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Setter"),
						Serialize(node.Setter)));
			}
			if (ShouldSerialize(node.Type))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Type"),
						Serialize(node.Type)));
			}
			if (ShouldSerialize(node.ExplicitInfo))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "ExplicitInfo"),
						Serialize(node.ExplicitInfo)));
			}
			Push(mie);
		}
 public override void VisitMethodInvocationExpression(MethodInvocationExpression node)
 {
     this.VisitMethodInvocationExpression(node);
     this.CheckArguments(node.get_MethodExpression().get_Method().get_Parameters(), node.get_Arguments());
     return;
 }
Ejemplo n.º 55
0
		override public void OnLocal(Boo.Lang.Compiler.Ast.Local node)
		{
			MethodInvocationExpression mie = new MethodInvocationExpression(
					node.LexicalInfo,
					CreateReference(node, "Boo.Lang.Compiler.Ast.Local"));
			mie.Arguments.Add(Serialize(node.LexicalInfo));
			if (ShouldSerialize(node.Name))
			{
				mie.NamedArguments.Add(
					new ExpressionPair(
						CreateReference(node, "Name"),
						Serialize(node.Name)));
			}
			Push(mie);
		}
Ejemplo n.º 56
0
        protected virtual void ImplementInvokeMethodOnTarget(AbstractTypeEmitter invocation, ParameterInfo[] parameters,
                                                             MethodEmitter invokeMethodOnTarget,
                                                             Reference targetField)
        {
            var callbackMethod = GetCallbackMethod(invocation);

            if (callbackMethod == null)
            {
                EmitCallThrowOnNoTarget(invokeMethodOnTarget);
                return;
            }

            if (canChangeTarget)
            {
                EmitCallEnsureValidTarget(invokeMethodOnTarget);
            }

            var args = new Expression[parameters.Length];

            // Idea: instead of grab parameters one by one
            // we should grab an array
            var byRefArguments = new Dictionary <int, LocalReference>();

            for (var i = 0; i < parameters.Length; i++)
            {
                var param = parameters[i];

                var paramType = invocation.GetClosedParameterType(param.ParameterType);
                if (paramType.IsByRef)
                {
                    var localReference = invokeMethodOnTarget.CodeBuilder.DeclareLocal(paramType.GetElementType());
                    invokeMethodOnTarget.CodeBuilder
                    .AddStatement(
                        new AssignStatement(localReference,
                                            new ConvertExpression(paramType.GetElementType(),
                                                                  new MethodInvocationExpression(SelfReference.Self,
                                                                                                 InvocationMethods.GetArgumentValue,
                                                                                                 new LiteralIntExpression(i)))));
                    var byRefReference = new ByRefReference(localReference);
                    args[i]           = new ReferenceExpression(byRefReference);
                    byRefArguments[i] = localReference;
                }
                else
                {
                    args[i] =
                        new ConvertExpression(paramType,
                                              new MethodInvocationExpression(SelfReference.Self,
                                                                             InvocationMethods.GetArgumentValue,
                                                                             new LiteralIntExpression(i)));
                }
            }

            if (byRefArguments.Count > 0)
            {
                invokeMethodOnTarget.CodeBuilder.AddStatement(new TryStatement());
            }

            var methodOnTargetInvocationExpression = GetCallbackMethodInvocation(invocation, args, callbackMethod, targetField, invokeMethodOnTarget);

            LocalReference returnValue = null;

            if (callbackMethod.ReturnType != typeof(void))
            {
                var returnType = invocation.GetClosedParameterType(callbackMethod.ReturnType);
                returnValue = invokeMethodOnTarget.CodeBuilder.DeclareLocal(returnType);
                invokeMethodOnTarget.CodeBuilder.AddStatement(new AssignStatement(returnValue, methodOnTargetInvocationExpression));
            }
            else
            {
                invokeMethodOnTarget.CodeBuilder.AddStatement(new ExpressionStatement(methodOnTargetInvocationExpression));
            }

            AssignBackByRefArguments(invokeMethodOnTarget, byRefArguments);

            if (callbackMethod.ReturnType != typeof(void))
            {
                var setRetVal =
                    new MethodInvocationExpression(SelfReference.Self,
                                                   InvocationMethods.SetReturnValue,
                                                   new ConvertExpression(typeof(object), returnValue.Type, returnValue.ToExpression()));

                invokeMethodOnTarget.CodeBuilder.AddStatement(new ExpressionStatement(setRetVal));
            }

            invokeMethodOnTarget.CodeBuilder.AddStatement(new ReturnStatement());
        }
        /// <summary>
        /// Reads a method access expression.
        /// </summary>
        /// <param name="methodName">The name of the method being called.</param>
        /// <param name="previousPrecedence">The precedence of the previous expression.</param>
        /// <param name="unsafeCode">Indicates whether the code being parsed resides in an unsafe code block.</param>
        /// <returns>Returns the expression.</returns>
        private MethodInvocationExpression GetMethodInvocationExpression(
            Expression methodName, ExpressionPrecedence previousPrecedence, bool unsafeCode)
        {
            Param.AssertNotNull(methodName, "methodName");
            Param.Ignore(previousPrecedence);
            Param.Ignore(unsafeCode);

            MethodInvocationExpression expression = null;
            if (this.CheckPrecedence(previousPrecedence, ExpressionPrecedence.Primary))
            {
                // The next symbol will be the opening parenthesis.
                Bracket openParenthesis = this.GetBracketToken(CsTokenType.OpenParenthesis, SymbolType.OpenParenthesis);
                Node<CsToken> openParenthesisNode = this.tokens.InsertLast(openParenthesis);

                // Get the argument list now.
                IList<Expression> argumentList = this.GetArgumentList(SymbolType.CloseParenthesis, unsafeCode);

                // Get the closing parenthesis.
                Bracket closeParenthesis = this.GetBracketToken(CsTokenType.CloseParenthesis, SymbolType.CloseParenthesis);
                Node<CsToken> closeParenthesisNode = this.tokens.InsertLast(closeParenthesis);

                openParenthesis.MatchingBracketNode = closeParenthesisNode;
                closeParenthesis.MatchingBracketNode = openParenthesisNode;

                // Pull out the first token from the method name.
                Debug.Assert(methodName.Tokens.First != null, "The method name should not be empty");
                Node<CsToken> firstTokenNode = methodName.Tokens.First;

                // Create the token list for the method invocation expression.
                CsTokenList partialTokens = new CsTokenList(this.tokens, firstTokenNode, this.tokens.Last);

                // Create and return the expression.
                expression = new MethodInvocationExpression(partialTokens, methodName, argumentList);
            }

            return expression;
        }
Ejemplo n.º 58
0
        ClassDefinition CreateAdaptor(ICallableType to, ICallableType from)
        {
            BooClassBuilder adaptor = CodeBuilder.CreateClass("$adaptor$" + from.Name + "$" + to.Name + "$" + _adaptors.Count);

            adaptor.AddBaseType(TypeSystemServices.ObjectType);
            adaptor.Modifiers = TypeMemberModifiers.Final | TypeMemberModifiers.Internal;

            Field callable = adaptor.AddField("$from", from);

            BooMethodBuilder     constructor = adaptor.AddConstructor();
            ParameterDeclaration param       = constructor.AddParameter("from", from);

            constructor.Body.Add(
                CodeBuilder.CreateSuperConstructorInvocation(TypeSystemServices.ObjectType));
            constructor.Body.Add(
                CodeBuilder.CreateAssignment(
                    CodeBuilder.CreateReference(callable),
                    CodeBuilder.CreateReference(param)));

            CallableSignature signature = to.GetSignature();
            BooMethodBuilder  invoke    = adaptor.AddMethod("Invoke", signature.ReturnType);

            foreach (IParameter parameter in signature.Parameters)
            {
                invoke.AddParameter(parameter.Name, parameter.Type, parameter.IsByRef);
            }
            MethodInvocationExpression mie = CodeBuilder.CreateMethodInvocation(
                CodeBuilder.CreateReference(callable),
                GetInvokeMethod(from));
            int fromParameterCount = from.GetSignature().Parameters.Length;

            for (int i = 0; i < fromParameterCount; ++i)
            {
                mie.Arguments.Add(
                    CodeBuilder.CreateReference(invoke.Parameters[i]));
            }
            if (signature.ReturnType != TypeSystemServices.VoidType &&
                from.GetSignature().ReturnType != TypeSystemServices.VoidType)
            {
                invoke.Body.Add(new ReturnStatement(mie));
            }
            else
            {
                invoke.Body.Add(mie);
            }

            BooMethodBuilder adapt = adaptor.AddMethod("Adapt", to);

            adapt.Modifiers = TypeMemberModifiers.Static | TypeMemberModifiers.Public;
            param           = adapt.AddParameter("from", from);
            adapt.Body.Add(
                new ReturnStatement(
                    CodeBuilder.CreateConstructorInvocation(
                        to.GetConstructors().First(),
                        CodeBuilder.CreateConstructorInvocation(
                            (IConstructor)constructor.Entity,
                            CodeBuilder.CreateReference(param)),
                        CodeBuilder.CreateAddressOfExpression(invoke.Entity))));

            var collector = new GenericTypeCollector(this.CodeBuilder);

            collector.Process(adaptor.ClassDefinition);
            RegisterAdaptor(to, from, adaptor.ClassDefinition);

            return(adaptor.ClassDefinition);
        }
Ejemplo n.º 59
0
			protected internal override void VisitMethodInvocationExpression(MethodInvocationExpression expression)
			{
				_expr = Ssm.CreateCall(expression.Method.Name, expression.Method.MethodInfo.DeclaringType.FullName,
					expression.Method.MethodInfo.GetParameters().Select(p => Transform(p.ParameterType)),
					expression.Method.MethodInfo.GetParameters().Select(p =>
					{
						if (p.IsOut)
							return Ssm.ParamDir.Out;

						if (p.ParameterType.IsByRef)
							return Ssm.ParamDir.InOut;

						return Ssm.ParamDir.In;
					}), Transform(expression.Method.MethodInfo.ReturnType), expression.Arguments.Select(GetTransformed));

				if (expression.Method.DeclaringObject == _this)
					return;

				var component = (ComponentMetadata)expression.Method.DeclaringObject;
				var field = Ssm.Var.NewField(component.Name, Ssm.Type.NewClassType(component.GetType().FullName));
				_expr = Ssm.Expr.NewMemberExpr(field, _expr);
			}
        /*
         * The following pattern matches BlockStatements with similar content
         * {
         *      stackVariable6 = exception_0 as Exception;
         *      if (stackVariable6 != null)
         *      {
         *          ProjectData.SetProjectError(stackVariable6);
         *          ex = stackVariable6;
         *          stackVariable15 = Program.Bool() && b is int;
         *      }
         *      else
         *      {
         *          stackVariable15 = false;
         *      }
         *      stackVariable15;
         * }
         * - stackVariable6 = exception_0 as Exception; - the VariableDeclarationExpression is build using this variable reference
         * - Program.Bool() && b is int - The filter expression
         * - ex = stackVariable6; - Not required line, if present the variable reference is used to build the VariableDeclarationExpression
         * - ProjectData.SetProjectError(stackVariable6); - Not required line. It is generated by the VB compiler. It could be after ex = stackVariable6;
         */
        public static bool TryMatch(BlockStatement filter, out VariableDeclarationExpression variableDeclaration, out Expression filterExpression)
        {
            variableDeclaration = null;
            filterExpression    = null;

            if (!TryMatchVariableDeclaration(filter, out variableDeclaration))
            {
                return(false);
            }

            // Save cast of the exception
            // If-else statement for the filter expression
            // Variable reference of the result of the filter block
            if (filter.Statements.Count != 3)
            {
                return(false);
            }

            IfStatement ifStatement = filter.Statements[1] as IfStatement;

            if (ifStatement == null)
            {
                return(false);
            }

            BlockStatement exceptionAssignmentBlock            = null;
            BlockStatement negativeFilterResultAssignmentBlock = null;

            if ((ifStatement.Condition as BinaryExpression).Operator == BinaryOperator.ValueInequality)
            {
                exceptionAssignmentBlock            = ifStatement.Then;
                negativeFilterResultAssignmentBlock = ifStatement.Else;
            }
            else
            {
                exceptionAssignmentBlock            = ifStatement.Else;
                negativeFilterResultAssignmentBlock = ifStatement.Then;
            }

            ExpressionStatement exceptionAssignmentStatement = null;
            ExpressionStatement methodInvocationStatement    = null;

            if ((exceptionAssignmentBlock.Statements.Count != 1 && exceptionAssignmentBlock.Statements.Count != 2 && exceptionAssignmentBlock.Statements.Count != 3) ||
                negativeFilterResultAssignmentBlock.Statements.Count != 1)
            {
                return(false);
            }

            if (exceptionAssignmentBlock.Statements.Count == 2)
            {
                ExpressionStatement firstThenStatement = exceptionAssignmentBlock.Statements[0] as ExpressionStatement;
                if (firstThenStatement == null)
                {
                    return(false);
                }

                if (firstThenStatement.Expression.CodeNodeType == CodeNodeType.BinaryExpression)
                {
                    exceptionAssignmentStatement = firstThenStatement;
                }
                else if (firstThenStatement.Expression.CodeNodeType == CodeNodeType.MethodInvocationExpression)
                {
                    methodInvocationStatement = firstThenStatement;
                }
                else
                {
                    return(false);
                }
            }
            else if (exceptionAssignmentBlock.Statements.Count == 3)
            {
                ExpressionStatement firstThenStatement  = exceptionAssignmentBlock.Statements[0] as ExpressionStatement;
                ExpressionStatement secondThenStatement = exceptionAssignmentBlock.Statements[1] as ExpressionStatement;
                if (firstThenStatement == null || secondThenStatement == null)
                {
                    return(false);
                }

                if (firstThenStatement.Expression.CodeNodeType == CodeNodeType.BinaryExpression &&
                    secondThenStatement.Expression.CodeNodeType == CodeNodeType.MethodInvocationExpression)
                {
                    exceptionAssignmentStatement = firstThenStatement;
                    methodInvocationStatement    = secondThenStatement;
                }
                else if (firstThenStatement.Expression.CodeNodeType == CodeNodeType.MethodInvocationExpression &&
                         secondThenStatement.Expression.CodeNodeType == CodeNodeType.BinaryExpression)
                {
                    methodInvocationStatement    = firstThenStatement;
                    exceptionAssignmentStatement = secondThenStatement;
                }
                else
                {
                    return(false);
                }
            }

            if (exceptionAssignmentStatement != null)
            {
                BinaryExpression exceptionAssignment = exceptionAssignmentStatement.Expression as BinaryExpression;
                if (exceptionAssignment == null || !exceptionAssignment.IsAssignmentExpression ||
                    exceptionAssignment.ExpressionType.FullName != variableDeclaration.ExpressionType.FullName)
                {
                    return(false);
                }

                VariableReferenceExpression left  = exceptionAssignment.Left as VariableReferenceExpression;
                VariableReferenceExpression right = exceptionAssignment.Right as VariableReferenceExpression;
                if (left == null || right == null)
                {
                    return(false);
                }
            }

            if (methodInvocationStatement != null)
            {
                MethodInvocationExpression methodInvocation = methodInvocationStatement.Expression as MethodInvocationExpression;
                if (methodInvocation == null ||
                    methodInvocation.MethodExpression.Method.FullName != "System.Void Microsoft.VisualBasic.CompilerServices.ProjectData::SetProjectError(System.Exception)")
                {
                    return(false);
                }
            }

            ExpressionStatement lastExpressionStatement = filter.Statements[2] as ExpressionStatement;

            if (lastExpressionStatement == null)
            {
                return(false);
            }

            VariableReferenceExpression lastExpression = lastExpressionStatement.Expression as VariableReferenceExpression;

            if (lastExpression == null)
            {
                return(false);
            }

            if (!TryMatchFilterExpression(ifStatement, variableDeclaration.Variable.VariableType, lastExpression, out filterExpression))
            {
                return(false);
            }

            return(true);
        }