private void Emit(BlockExpression node, EmitAs emitAs) {
            int count = node.ExpressionCount;

            // Labels defined immediately in the block are valid for the whole block

            for(int i = 0; i < count; i++) {
                Expression e = node.GetExpression(i);

                var label = e as LabelExpression;
                if (label != null) {
                    DefineLabel(label.Label);
                }
            }

            EnterScope(node);

            for (int index = 0; index < count - 1; index++) {
                EmitExpressionAsVoid(node.GetExpression(index));
            }

            // if the type of Block it means this is not a Comma
            // so we will force the last expression to emit as void.
            if (emitAs == EmitAs.Void || node.Type == typeof(void)) {
                EmitExpressionAsVoid(node.GetExpression(count - 1));
            } else {
                EmitExpression(node.GetExpression(count - 1));
            }

            ExitScope(node);
        }
        private void Emit(BlockExpression node, EmitAs emitAs) {
            EnterScope(node);

            int count = node.ExpressionCount;
            for (int index = 0; index < count - 1; index++) {
                var e = node.GetExpression(index);

                if (_emitDebugSymbols) {
                    //No need to emit a clearance if the next expression in the block is also a
                    //DebugInfoExprssion.
                    var debugInfo = e as DebugInfoExpression;
                    if (debugInfo != null && debugInfo.IsClear && node.GetExpression(index + 1) is DebugInfoExpression) {
                        continue;
                    }
                }
                EmitExpressionAsVoid(e);
            }

            // if the type of Block it means this is not a Comma
            // so we will force the last expression to emit as void.
            if (emitAs == EmitAs.Void || node.Type == typeof(void)) {
                EmitExpressionAsVoid(node.GetExpression(count - 1));
            } else {
                EmitExpressionAsType(node.GetExpression(count - 1), node.Type);
            }

            ExitScope(node);
        }
예제 #3
0
 public FunctionExpression(Token token, string name, List<string> arguments, BlockExpression block)
     : base(token.FileName, token.Line)
 {
     Name = name;
     Arguments = arguments.AsReadOnly();
     Block = block;
 }
        private void Emit(BlockExpression node, CompilationFlags flags)
        {
            int count = node.ExpressionCount;

            if (count == 0)
            {
                return;
            }

            EnterScope(node);

            CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask;

            CompilationFlags tailCall = flags & CompilationFlags.EmitAsTailCallMask;
            for (int index = 0; index < count - 1; index++)
            {
                var e = node.GetExpression(index);
                var next = node.GetExpression(index + 1);

                CompilationFlags tailCallFlag;
                if (tailCall != CompilationFlags.EmitAsNoTail)
                {
                    var g = next as GotoExpression;
                    if (g != null && (g.Value == null || !Significant(g.Value)) && ReferenceLabel(g.Target).CanReturn)
                    {
                        // Since tail call flags are not passed into EmitTryExpression, CanReturn means the goto will be emitted
                        // as Ret. Therefore we can emit the current expression with tail call.
                        tailCallFlag = CompilationFlags.EmitAsTail;
                    }
                    else
                    {
                        // In the middle of the block.
                        // We may do better here by marking it as Tail if the following expressions are not going to emit any IL.
                        tailCallFlag = CompilationFlags.EmitAsMiddle;
                    }
                }
                else
                {
                    tailCallFlag = CompilationFlags.EmitAsNoTail;
                }

                flags = UpdateEmitAsTailCallFlag(flags, tailCallFlag);
                EmitExpressionAsVoid(e, flags);
            }

            // if the type of Block it means this is not a Comma
            // so we will force the last expression to emit as void.
            // We don't need EmitAsType flag anymore, should only pass
            // the EmitTailCall field in flags to emitting the last expression.
            if (emitAs == CompilationFlags.EmitAsVoidType || node.Type == typeof(void))
            {
                EmitExpressionAsVoid(node.GetExpression(count - 1), tailCall);
            }
            else
            {
                EmitExpressionAsType(node.GetExpression(count - 1), node.Type, tailCall);
            }

            ExitScope(node);
        }
예제 #5
0
 public ForExpression(Token token, Expression initializer, Expression condition, BlockExpression increment, BlockExpression block)
     : base(token.FileName, token.Line)
 {
     Initializer = initializer;
     Condition = condition;
     Increment = increment;
     Block = block;
 }
 protected virtual BlockExpression UpdateBlockExpression(BlockExpression exp, IEnumerable<Expression> expressions, IEnumerable<ParameterExpression> variables)
 {
     if (exp.Expressions != expressions ||
         exp.Variables != variables) {
         return Expression.Block(
             variables, expressions
         );
     }
     return exp;
 }
예제 #7
0
 public override Expression VisitBlockExpression(BlockExpression blockExpression){
   if (blockExpression == null) return null;
   Block block = blockExpression.Block;
   if (block != null && block.Statements != null && block.Statements.Count == 1) {
     ExpressionStatement es = block.Statements[0] as ExpressionStatement;
     if (es != null) {
       es.Expression = this.VisitExpression(es.Expression);
       this.composers.Clear();
       this.composers.Add(this.GetComposer(es.Expression));
       return (Expression) this.Compose(blockExpression, this.composers);
     }
   }
   return base.VisitBlockExpression(blockExpression);
 }    
        private void Emit(BlockExpression node, CompilationFlags flags) {
            EnterScope(node);

            CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask;

            int count = node.ExpressionCount;
            CompilationFlags tailCall = flags & CompilationFlags.EmitAsTailCallMask;
            CompilationFlags middleTailCall = tailCall == CompilationFlags.EmitAsNoTail ? CompilationFlags.EmitAsNoTail : CompilationFlags.EmitAsMiddle;

            for (int index = 0; index < count - 1; index++) {
                var e = node.GetExpression(index);
                var next = node.GetExpression(index + 1);

                if (EmitDebugSymbols) {
                    // No need to emit a clearance if the next expression in the block is also a
                    // DebugInfoExprssion.
                    var debugInfo = e as DebugInfoExpression;
                    if (debugInfo != null && debugInfo.IsClear && next is DebugInfoExpression) {
                        continue;
                    }
                }
                // In the middle of the block.
                // We may do better here by marking it as Tail if the following expressions are not going to emit any IL.
                var tailCallFlag = middleTailCall;

                var g = next as GotoExpression;
                if (g != null && (g.Value == null || !Significant(g.Value))) {
                    var labelInfo = ReferenceLabel(g.Target);
                    if (labelInfo.CanReturn) {
                        // Since tail call flags are not passed into EmitTryExpression, CanReturn means the goto will be emitted
                        // as Ret. Therefore we can emit the current expression with tail call.
                        tailCallFlag = CompilationFlags.EmitAsTail;
                    }
                }
                flags = UpdateEmitAsTailCallFlag(flags, tailCallFlag);
                EmitExpressionAsVoid(e, flags);
            }

            // if the type of Block it means this is not a Comma
            // so we will force the last expression to emit as void.
            // We don't need EmitAsType flag anymore, should only pass
            // the EmitTailCall field in flags to emitting the last expression.
            if (emitAs == CompilationFlags.EmitAsVoidType || node.Type == typeof(void)) {
                EmitExpressionAsVoid(node.GetExpression(count - 1), tailCall);
            } else {
                EmitExpressionAsType(node.GetExpression(count - 1), node.Type, tailCall);
            }

            ExitScope(node);
        }
        private void EnterScope(BlockExpression node) {
            if (node.Variables.Count > 0 &&
                (_scope.MergedScopes == null || !_scope.MergedScopes.Contains(node))) {

                CompilerScope scope;
                if (!_tree.Scopes.TryGetValue(node, out scope)) {
                    //
                    // Very often, we want to compile nodes as reductions
                    // rather than as IL, but usually they need to allocate
                    // some IL locals. To support this, we allow emitting a
                    // BlockExpression that was not bound by VariableBinder.
                    // This works as long as the variables are only used
                    // locally -- i.e. not closed over.
                    //
                    // User-created blocks will never hit this case; only our
                    // internally reduced nodes will.
                    //
                    scope = new CompilerScope(node) { NeedsClosure = _scope.NeedsClosure };
                }

                _scope = scope.Enter(this, _scope);
                Debug.Assert(_scope.Node == node);
            }
        }
예제 #10
0
 public override Expression VisitBlockExpression(BlockExpression blockExpression)
 {
     if (blockExpression == null) return null;
     return base.VisitBlockExpression((BlockExpression)blockExpression.Clone());
 }
예제 #11
0
    public override Expression VisitBlockExpression(BlockExpression blockExpression) {
      if (blockExpression == null) return null;
      // This is either
      // 1) a call of the form {newLocal = e; &newLocal; }.M(...)
      //    where M.DeclaringType is Struct
      //    We simply serialize e
      // or
      // 2) of the form { newLocal = e; AssertNotNull(newLocal); newLocal; }
      // or
      // 3) of the form { AssertNotNull(e); e; } // where e is a variable
      //    We simply serialize e
      // or
      // 4) of the form { Exception e; <boolean expression involving e> }
      //    This arises from "throws (E e) ensures Q" clauses. Q sits in an ExpressionStatement
      //     with e as a bound variable of the block scope.
      Block block = blockExpression.Block;
      if (block == null || block.Statements == null || 3 < block.Statements.Count) return blockExpression;
      //Debug.Assert(block.Statements.Count == 2 || block.Statements.Count == 3);
      AssignmentStatement a = block.Statements[0] as AssignmentStatement;
      if (a != null) { // case (1) or (2)
        ExpressionStatement es = (ExpressionStatement)block.Statements[1];
        Debug.Assert(es.Expression.NodeType == NodeType.AddressOf || es.Expression.NodeType == NodeType.Call);
        this.Visit(a.Source);
      } else if (block.Statements.Count == 1) { // case (4) (is a stronger test needed here?
        // overload the comprehension serialization and compensate after it has been deserialized as a comprehension
        // NB: this code now lives in two places (here and VisitComprehension)!
        this._string.Append("{|");
        if (0 < block.Scope.Members.Count) {
          this._string.Append("{");
          Field f = block.Scope.Members[0] as Field; // what if there is more than one?
          this.AddType(f.Type);
          this._string.Append(",");
          this.VisitField(f);
          this._string.Append(",null}");

        }
        this._string.Append(";");
        ExpressionStatement es = block.Statements[0] as ExpressionStatement;
        this.VisitExpression(es.Expression);
        this._string.Append("|}");
      }else { // case (3)
        ExpressionStatement es = (ExpressionStatement)block.Statements[1];
        this.Visit(es.Expression);
      }
      return blockExpression;
    }
예제 #12
0
 public DoWhileExpression(Token token, BlockExpression block, Expression condition)
     : base(token.FileName, token.Line)
 {
     Block     = block;
     Condition = condition;
 }
예제 #13
0
파일: Setter.cs 프로젝트: deipax/Deipax
        public Expression <SetDelegate <T, TValue> > GetExpression <TValue>()
        {
            var xType = typeof(TValue);

            var tmp      = Expression.Variable(typeof(TProp), "tmp");
            var input    = Expression.Parameter(typeof(TValue), "input");
            var instance = Expression.Parameter(typeof(T).MakeByRefType(), "instance");
            var provider = Expression.Parameter(typeof(IFormatProvider), "provider");

            var memberExpression = Expression.MakeMemberAccess(
                instance,
                ModelInfo.GetOptimalMemberInfo());

            var invoke = Expression.Invoke(
                Expression.Constant(ConvertTo <TValue, TProp> .From),
                input,
                provider);

            BlockExpression block = null;

            if (ModelInfo.Type == xType)
            {
                block = Expression.Block(Expression.Assign(memberExpression, input));
            }
            else if (ModelInfo.Type == typeof(object) &&
                     !xType.IsNullable())
            {
                block = Expression.Block(Expression.Assign(
                                             memberExpression,
                                             Expression.Convert(input, typeof(object))));
            }
            else if (ModelInfo.Type == typeof(object) &&
                     xType.IsNullable())
            {
                var value = Expression.Property(input, "Value");

                var ifThenElse = Expression.IfThenElse(
                    Expression.Property(input, "HasValue"),
                    Expression.Assign(memberExpression, Expression.Convert(value, typeof(object))),
                    Expression.Assign(memberExpression, Expression.Default(ModelInfo.Type)));

                block = Expression.Block(ifThenElse);
            }
            else if (xType.IsNullable() &&
                     Nullable.GetUnderlyingType(xType) == ModelInfo.Type)
            {
                var value = Expression.Property(input, "Value");

                var ifThenElse = Expression.IfThenElse(
                    Expression.Property(input, "HasValue"),
                    Expression.Assign(memberExpression, Expression.Convert(value, ModelInfo.Type)),
                    Expression.Assign(memberExpression, Expression.Default(ModelInfo.Type)));

                block = Expression.Block(ifThenElse);
            }
            else if (ModelInfo.Type.IsNullable() &&
                     Nullable.GetUnderlyingType(ModelInfo.Type) == xType)
            {
                block = Expression.Block(Expression.Assign(
                                             memberExpression,
                                             Expression.Convert(input, ModelInfo.Type)));
            }
            else if (xType == typeof(object))
            {
                var ifThenElse = Expression.IfThenElse(
                    Expression.TypeEqual(input, ModelInfo.Type),
                    Expression.Assign(memberExpression, Expression.Convert(input, ModelInfo.Type)),
                    Expression.Block(
                        new[] { tmp },
                        Expression.Assign(tmp, invoke),
                        Expression.Assign(memberExpression, tmp)));

                block = Expression.Block(ifThenElse);
            }
            else if (xType != ModelInfo.Type)
            {
                block = Expression.Block(
                    new[] { tmp },
                    Expression.Assign(tmp, invoke),
                    Expression.Assign(memberExpression, tmp));
            }

            return(Expression.Lambda <SetDelegate <T, TValue> >(
                       block,
                       instance,
                       input,
                       provider));
        }
예제 #14
0
 public virtual Expression VisitBlockExpression(BlockExpression blockExpression){
   if (blockExpression == null) return null;
   blockExpression.Block = this.VisitBlock(blockExpression.Block);
   return blockExpression;
 }
예제 #15
0
 private Expression ReplaceIn(BlockExpression block)
 {
     return(ReplaceIn(
                block,
                b => b.Update(b.Variables.Select(ReplaceIn), b.Expressions.Select(Replace))));
 }
예제 #16
0
 private static BlockExpression SetChildren(ReadOnlySpan <Expression> newChildren, BlockExpression b)
 => b.Update(b.Variables, newChildren.ToArray());
예제 #17
0
        /// <summary>
        /// To the result tree member expression
        /// </summary>
        /// <param name="rule">The rule.</param>
        /// <param name="childRuleResults">The child rule results.</param>
        /// <param name="isSuccessExp">The is success exp.</param>
        /// <param name="childRuleResultsblockexpr">The child rule results block expression.</param>
        /// <returns></returns>
        internal static MemberInitExpression ToResultTree(Rule rule, IEnumerable <MemberInitExpression> childRuleResults, BinaryExpression isSuccessExp, IEnumerable <ParameterExpression> typeParamExpressions, BlockExpression childRuleResultsblockexpr, string exceptionMessage = "")
        {
            var createdType = typeof(RuleResultTree);
            var ctor        = Expression.New(createdType);

            var ruleProp        = createdType.GetProperty(nameof(RuleResultTree.Rule));
            var isSuccessProp   = createdType.GetProperty(nameof(RuleResultTree.IsSuccess));
            var childResultProp = createdType.GetProperty(nameof(RuleResultTree.ChildResults));
            var inputProp       = createdType.GetProperty(nameof(RuleResultTree.Input));
            var exceptionProp   = createdType.GetProperty(nameof(RuleResultTree.ExceptionMessage));

            var rulePropBinding      = Expression.Bind(ruleProp, Expression.Constant(rule));
            var isSuccessPropBinding = Expression.Bind(isSuccessProp, isSuccessExp);
            var inputBinding         = Expression.Bind(inputProp, typeParamExpressions.FirstOrDefault());
            var exceptionBinding     = Expression.Bind(exceptionProp, Expression.Constant(exceptionMessage));

            MemberInitExpression memberInit;

            if (childRuleResults != null)
            {
                var ruleResultTreeArr = Expression.NewArrayInit(typeof(RuleResultTree), childRuleResults);

                var childResultPropBinding = Expression.Bind(childResultProp, ruleResultTreeArr);
                memberInit = Expression.MemberInit(ctor, new[] { rulePropBinding, isSuccessPropBinding, childResultPropBinding, inputBinding, exceptionBinding });
            }
            else if (childRuleResultsblockexpr != null)
            {
                var childResultPropBinding = Expression.Bind(childResultProp, childRuleResultsblockexpr);
                memberInit = Expression.MemberInit(ctor, new[] { rulePropBinding, isSuccessPropBinding, childResultPropBinding, inputBinding, exceptionBinding });
            }
            else
            {
                memberInit = Expression.MemberInit(ctor, new[] { rulePropBinding, isSuccessPropBinding, inputBinding, exceptionBinding });
            }

            return(memberInit);
        }
예제 #18
0
 protected override Expression VisitBlock(BlockExpression node)
 {
     Stop();
     return(base.VisitBlock(node));
 }
예제 #19
0
 private static void GetChildren(Span <Expression> children, BlockExpression b)
 {
     Copy(b.Expressions, children);
 }
예제 #20
0
 /// <summary>
 /// Visits the children of <see cref="System.Linq.Expressions.BlockExpression"/>.
 /// </summary>
 /// <param name="node">The expression to visit.</param>
 /// <returns>The modified expression, if it or any subexpression was modified; otherwise,
 /// returns the original expression.</returns>
 protected override Expression VisitBlock(BlockExpression node)
 {
     throw new NotSupportedException(string.Format(Resources.EX_PROCESS_NODE_NOT_SUPPORT, node.GetType().Name));
 }
예제 #21
0
 protected override Expression VisitBlock(BlockExpression node)
 {
     this.expressions.Add(node);
     return(base.VisitBlock(node));
 }
예제 #22
0
 protected override Expression VisitBlock(BlockExpression node)
 {
     Console.WriteLine($"call {MethodBase.GetCurrentMethod().Name} : {node}");
     return(base.VisitBlock(node));
 }
예제 #23
0
    public virtual Expression ImplicitCoercion(Expression source, TypeNode targetType, TypeViewer typeViewer){
      TypeNode originalTargetType = targetType;
      if (targetType == null || targetType.Name == Looker.NotFound) return source;
      if (source == null) return null;
      //HS D
      if (source is Hole)
          {
              source.Type = targetType;
              return source;
          }
      //HS D
      if (source is LambdaHole)
          {
              if (targetType == SystemTypes.Boolean)
                  source = new LambdaHole(source, new Literal(0), NodeType.Ge, source.SourceContext);                      
              source.Type = targetType;
              return source;
          }
      Literal sourceLit = source as Literal;
      if (sourceLit != null && sourceLit.Value is TypeNode){
        this.HandleError(source, Error.TypeInVariableContext, this.GetTypeName((TypeNode)sourceLit.Value), "class", "variable");
        return null;
      }
      //Ignore parentheses
      if (source.NodeType == NodeType.Parentheses){
        UnaryExpression uex = (UnaryExpression)source;
        uex.Operand = this.ImplicitCoercion(uex.Operand, targetType, typeViewer);
        if (uex.Operand == null) return null;
        uex.Type = uex.Operand.Type;
        return uex;
      }
      bool targetIsNonNullType = this.IsNonNullType(targetType);
      targetType = TypeNode.StripModifier(targetType, SystemTypes.NonNullType);
      targetType = TypeNode.StripModifier(targetType, SystemTypes.NullableType);
      //TODO: handle SkipCheck and EnforceCheck
      //Special case for closure expressions
      if (source.NodeType == NodeType.AnonymousNestedFunction)
        return this.CoerceAnonymousNestedFunction((AnonymousNestedFunction)source, targetType, false, typeViewer);
      TypeNode sourceType = source.Type;
      if (sourceType == null) sourceType = SystemTypes.Object;
      bool sourceIsNonNullType = this.IsNonNullType(source.Type);
      sourceType = TypeNode.StripModifier(sourceType, SystemTypes.NonNullType);
      sourceType = TypeNode.StripModifier(sourceType, SystemTypes.NullableType);
      if (sourceType == SystemTypes.String && !sourceIsNonNullType && source is Literal)
        sourceIsNonNullType = ((Literal)source).Value != null;
      if (this.currentParameter != null && targetType is Reference){
        UnaryExpression uex = source as UnaryExpression;
        if (uex != null){
          if (sourceIsNonNullType && !targetIsNonNullType){
            string ttypeName = this.GetTypeName(targetType);
            string stypeName = this.GetTypeName(source.Type);
            this.HandleError(source, Error.NoImplicitCoercion, stypeName, ttypeName);
            return null;
          }
          if (!sourceIsNonNullType && targetIsNonNullType){
            string ttypeName = this.GetTypeName(targetType);
            string stypeName = this.GetTypeName(source.Type);
            this.HandleError(source, Error.NoImplicitCoercion, stypeName, ttypeName);
            return null;
          }
          if (uex.NodeType == NodeType.OutAddress){
            if ((this.currentParameter.Flags & ParameterFlags.Out) == 0){
              this.currentParameter.Flags |= ParameterFlags.Out;
              string stypeName = this.GetTypeName(sourceType);
              this.currentParameter.Flags &= ~ParameterFlags.Out;
              this.HandleError(source, Error.NoImplicitCoercion, stypeName, this.GetTypeName(targetType));
              return null;
            }
          }else if (uex.NodeType == NodeType.RefAddress){
            if ((this.currentParameter.Flags & ParameterFlags.Out) != 0){
              this.currentParameter.Flags &= ~ParameterFlags.Out;
              string stypeName = this.GetTypeName(sourceType);
              this.currentParameter.Flags |= ParameterFlags.Out;
              this.HandleError(source, Error.NoImplicitCoercion, stypeName, this.GetTypeName(targetType));
              return null;
            }
          }
        }
      }
      Expression result = this.StandardImplicitCoercion(source, sourceIsNonNullType, sourceType, targetIsNonNullType, targetType, originalTargetType, typeViewer);
      if (result != null) return result;
      Method coercion = this.UserDefinedImplicitCoercionMethod(source, sourceType, targetType, true, typeViewer);
      if (coercion != null){
        if (this.IsNullableType(targetType) && this.IsNullableType(sourceType) && !this.IsNullableType(coercion.Parameters[0].Type))
          return this.CoerceWithLiftedCoercion(source, sourceType, targetType, coercion, false, typeViewer);
        ExpressionList args = new ExpressionList(1);
        args.Add(this.ImplicitCoercion(source, coercion.Parameters[0].Type, typeViewer));
        return this.ImplicitCoercion(new MethodCall(new MemberBinding(null, coercion), args, NodeType.Call, coercion.ReturnType, source.SourceContext), targetType, typeViewer);
      }
      if (sourceType == SystemTypes.Type && source is Literal)
        this.HandleError(source, Error.TypeInVariableContext, this.GetTypeName((TypeNode)((Literal)source).Value), "class", "variable");
      else if (this.IsNullableType(sourceType) && this.IsNullableType(targetType) && this.ImplicitCoercionFromTo(this.RemoveNullableWrapper(sourceType), this.RemoveNullableWrapper(targetType))) {
        TypeNode usType = this.RemoveNullableWrapper(sourceType);
        TypeNode utType = this.RemoveNullableWrapper(targetType);

        Local tempSrc = new Local(sourceType);
        Local tempTar = new Local(targetType);
        StatementList statements = new StatementList();
        BlockExpression result1 = new BlockExpression(new Block(statements));
        statements.Add(new AssignmentStatement(tempSrc, source));

        Method hasValue = sourceType.GetMethod(StandardIds.getHasValue);
        Method getValueOrDefault = sourceType.GetMethod(StandardIds.GetValueOrDefault);
        Method ctor = targetType.GetMethod(StandardIds.Ctor, utType);
        Block pushValue = new Block();
        Block done = new Block();

        Expression tempHasValue = new MethodCall(new MemberBinding(new UnaryExpression(tempSrc, NodeType.AddressOf), hasValue), null);
        tempHasValue.Type = SystemTypes.Boolean;
        statements.Add(new Branch(tempHasValue, pushValue));
        statements.Add(new AssignmentStatement(new AddressDereference(new UnaryExpression(tempTar, NodeType.AddressOf), targetType), new Literal(null, CoreSystemTypes.Object)));
        statements.Add(new Branch(null, done));
        statements.Add(pushValue);
        Expression value = new MethodCall(new MemberBinding(new UnaryExpression(tempSrc, NodeType.AddressOf), getValueOrDefault), null);
        value.Type = usType;
        value = this.ImplicitCoercion(value, utType);
        Construct cons = new Construct(new MemberBinding(null, ctor), new ExpressionList(value));
        result1.Type = ctor.DeclaringType;
        statements.Add(new AssignmentStatement(tempTar, cons));
        statements.Add(done);

        statements.Add(new ExpressionStatement(tempTar));
        return result1;
      }else
        this.HandleError(source, Error.NoImplicitCoercion, this.GetTypeName(sourceType), this.GetTypeName(originalTargetType));
      return null;
    }
예제 #24
0
 private static int CountChildren(BlockExpression b)
 => b.Expressions.Count;
예제 #25
0
 public virtual Expression CoerceTypeUnionToObject(Expression source, TypeViewer typeViewer){
   TypeUnion sourceType = (TypeUnion)source.Type;
   Method getValue = TypeViewer.GetTypeView(typeViewer, sourceType).GetMethod(StandardIds.GetValue);
   Local temp = new Local(Identifier.Empty, sourceType);
   Expression tempAddr = new UnaryExpression(temp, NodeType.AddressOf);
   StatementList statements = new StatementList(2);
   statements.Add(new AssignmentStatement(temp, source));
   statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(tempAddr, getValue), null)));
   BlockExpression result = new BlockExpression(new Block(statements));
   result.Type = SystemTypes.Object;
   return result;
 }
예제 #26
0
            } // ctor

            protected override Expression VisitBlock(BlockExpression node)
            {
                return(base.VisitBlock(Expression.Block(node.Type, node.Variables, ReduceDebugExpressions(node.Expressions))));
            } // func VisitBlock
예제 #27
0
 protected override Expression VisitBlock(BlockExpression node)
 {
     return(Expression.Block(
                node.Variables,
                node.Expressions.Select(Visit)));
 }
 public AnonymousFunctionExpression(TupleDeclarationExpression arguments, TypeName returnType, BlockExpression body)
 {
     this.arguments  = arguments;
     this.returnType = returnType;
     this.body       = body;
 }
 public BlockExpressionProxy(BlockExpression node) {
     _node = node;
 }
 public override void OnBlockExpression(BlockExpression node)
 {
 }
예제 #31
0
 bool IEvaluatableExpressionFilter.IsEvaluatableBlock(BlockExpression node) => true;
예제 #32
0
        public static void part1()
        {
            //var aa = new MyQueryable<Student>();
            //var bb = aa.Where(s => s.Name == "李军");
            //var cc = bb.Where(s => s.Age > 24);
            //var dd = cc.AsEnumerable();
            //var ee = dd.ToList();

            LabelTarget         labelTarget = Expression.Label();
            ParameterExpression loopIndex   = Expression.Parameter(typeof(int), "index");

            Expression.Assign(loopIndex, Expression.Constant(1));

            BlockExpression block = Expression.Block(
                new[] { loopIndex },
                Expression.Assign(loopIndex, Expression.Constant(1)),
                Expression.Loop(
                    Expression.IfThenElse(
                        Expression.LessThanOrEqual(loopIndex, Expression.Constant(10)),
                        Expression.Block(
                            Expression.Call(null,
                                            typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                                            Expression.Constant("hello")),
                            Expression.PostIncrementAssign(loopIndex)
                            ),
                        Expression.Break(labelTarget)
                        ), labelTarget));

            Expression <Action> lambda = Expression.Lambda <Action>(block);

            lambda.Compile()();

            Expression <Func <int, int> > func = x => x + 1;

            TypeBinaryExpression type = Expression.TypeIs(Expression.Constant("pro"), typeof(int));

            ParameterExpression arr   = Expression.Parameter(typeof(int[]), "arr");
            ParameterExpression index = Expression.Parameter(typeof(int), "index");
            ParameterExpression value = Expression.Parameter(typeof(int), "value");

            Expression arrAccess = Expression.ArrayAccess(arr, index);

            Expression <Func <int[], int, int, int> > lambdaExpr =
                Expression.Lambda <Func <int[], int, int, int> >
                (
                    Expression.Assign(arrAccess, Expression.Add(arrAccess, value)),
                    arr, index, value
                );

            Console.WriteLine(arrAccess.ToString());
            Console.WriteLine(lambdaExpr.ToString());

            Console.WriteLine(lambdaExpr.Compile()(new int[] { 1, 2, 3 }, 0, 5));

            Expression <Func <int, int, bool> > largeSumTest = (num1, num2) => (num1 + num2) > 1000;
            InvocationExpression invocation = Expression.Invoke(
                largeSumTest,
                Expression.Constant(100),
                Expression.Constant(100));

            //ParameterExpression student = Expression.Parameter(typeof(Student));
            //var expr = Expression.Property(student, "Name");
            //var where = Expression.Equal(expr, Expression.Constant("小明"));
            //var orderExpr = Expression.Lambda<Func<Student, bool>>(where, student);

            //var orderedStudentArrary = StudentArrary.Where(orderExpr.Compile());

            var modules = new List <Module> {
                new Module {
                    Name = "01"
                },
                new Module {
                    Name = "02"
                },
                new Module {
                    Name = "03"
                },
                new Module {
                    Name = "04", IsDeleted = true
                },
                new Module {
                    Name = "05"
                },
            };
            ParameterExpression Module = Expression.Parameter(typeof(Module));
            var proExpr         = Expression.Property(Module, "Name");
            var condition       = Expression.Equal(proExpr, Expression.Constant("02"));
            var proExprDel      = Expression.Property(Module, "IsDeleted");
            var deleteCondition = Expression.Equal(proExprDel, Expression.Constant(false));

            var predicateExp = Expression.AndAlso(condition, deleteCondition);
            var predicate    = Expression.Lambda <Func <Module, bool> >(predicateExp, Module).Compile();
            var filter       = modules.Where(predicate);
        }
예제 #33
0
 BlockExpression Convert(BlockExpression expr)
 {
     return(expr.Update(Process(expr.Variables), Process(expr.Expressions)));
 }
예제 #34
0
 public override void LeaveBlockExpression(BlockExpression node)
 {
     OnExpression(node);
 }
예제 #35
0
 public virtual Expression VisitBlockExpression(BlockExpression blockExpression1, BlockExpression blockExpression2)
 {
     if (blockExpression1 == null) return null;
     if (blockExpression2 == null)
         blockExpression1.Block = this.VisitBlock(blockExpression1.Block, null);
     else
         blockExpression1.Block = this.VisitBlock(blockExpression1.Block, blockExpression2.Block);
     return blockExpression1;
 }
 public override Expression VisitBlockExpression(BlockExpression blockExpression)
 {
   throw new ApplicationException("unimplemented");
 }
예제 #37
0
 public Branch(Expression condition, BlockExpression block)
 {
     Condition = condition;
     Block = block;
 }
예제 #38
0
        private static void AssertBlockIsOptimized(BlockExpression expr, IReadOnlyList<Expression> args)
        {
            var n = args.Count;

            var updated = Update(expr);
            var visited = Visit(expr);

            foreach (var node in new[] { expr, updated, visited })
            {
                AssertBlock(n, node);

                Assert.Equal(n, node.Expressions.Count);

                if (node != visited) // our visitor clones argument nodes
                {
                    for (var i = 0; i < n; i++)
                    {
                        Assert.Same(args[i], node.Expressions[i]);
                    }
                }
            }
        }
 protected override Expression VisitBlock(BlockExpression node)
 {
     var exprs = node.Expressions.SelectMany(e => new Expression[] { _log(Expression.Constant("S" + _n++)), Visit(e) }).ToList();
     return node.Update(node.Variables, exprs);
 }
예제 #40
0
        private static BlockExpression Visit(BlockExpression node)
        {
            // Tests dispatch of ExpressionVisitor into Rewrite method which calls Expression.Block factories.

            return (BlockExpression)new Visitor().Visit(node);
        }
예제 #41
0
 protected virtual Expression StandardImplicitCoercion(Expression source, bool sourceIsNonNullType, TypeNode sourceType, bool targetIsNonNullType, TypeNode targetType, TypeNode originalTargetType, TypeViewer typeViewer){
   if (Literal.IsNullLiteral(source)) {
     if (this.IsNullableType(targetType)) {
       Local temp = new Local(targetType);
       StatementList statements = new StatementList();
       BlockExpression result = new BlockExpression(new Block(statements));
       statements.Add(new AssignmentStatement(new AddressDereference(new UnaryExpression(temp, NodeType.AddressOf), targetType), new Literal(null, CoreSystemTypes.Object)));
       statements.Add(new ExpressionStatement(temp));
       return result;
     }
     if (targetType.IsTemplateParameter && !targetType.IsReferenceType) {
       // Check for reference constraint
       this.HandleError(source, Error.TypeVarCantBeNull, targetType.Name.Name);
       return new Local(targetType);
     }
   }
   //Identity coercion
   if (sourceType == targetType && (!targetIsNonNullType || (targetIsNonNullType == sourceIsNonNullType))) return source;
   ITypeParameter stp = sourceType as ITypeParameter;
   ITypeParameter ttp = targetType as ITypeParameter;
   if (stp != null && ttp != null && stp.ParameterListIndex == ttp.ParameterListIndex && stp.DeclaringMember == ttp.DeclaringMember &&
     (!targetIsNonNullType || (targetIsNonNullType == sourceIsNonNullType))) return source;
   if (source is This && targetType != null && sourceType == targetType.Template && targetType.IsNotFullySpecialized)
     //TODO: add check for sourceType.TemplateParameters == targetType.TemplateArguments
     return source;
   //Dereference source
   Reference sr = sourceType as Reference;
   if (sr != null){
     sourceType = sr.ElementType;
     Pointer pType = targetType as Pointer;
     if (pType != null && this.StandardImplicitCoercionFromTo(null, sourceType, pType.ElementType, typeViewer))
       return source;
     else if (pType != null && pType.ElementType == SystemTypes.Void)
       return source;
     bool sourceIsThis = source is This;
     source = new AddressDereference(source, sourceType, source.SourceContext);
     source.Type = sourceType;
     sourceIsNonNullType = this.IsNonNullType(sourceType);
     sourceType = TypeNode.StripModifier(sourceType, SystemTypes.NonNullType);
     //Special case for coercion of this in template class
     if (sourceIsThis && targetType != null && sourceType == targetType.Template && targetType.IsNotFullySpecialized)
       //TODO: add check for sourceType.TemplateParameters == targetType.TemplateArguments
       return source;
   }
   //Identity coercion after dereference
   if (sourceType == targetType && (!targetIsNonNullType || (targetIsNonNullType == sourceIsNonNullType))) return source;
   //Special case for null literal
   if (Literal.IsNullLiteral(source)){
     if (targetIsNonNullType) 
       return ImplicitNonNullCoercion(this.ErrorHandler, source, originalTargetType);
     if (targetType is ITypeParameter && this.useGenerics)
       return new BinaryExpression(source, new Literal(targetType, SystemTypes.Type), NodeType.UnboxAny);
     if (!targetType.IsValueType || targetType.Template == SystemTypes.GenericBoxed)
       return new Literal(null, targetType, source.SourceContext);
     if (this.IsNullableType(targetType))
       return new Local(StandardIds.NewObj, targetType, source.SourceContext);
     TypeAlias tAlias = targetType as TypeAlias;
     if (tAlias != null){
       if (tAlias.RequireExplicitCoercionFromUnderlyingType) return null;
       source = this.ImplicitCoercion(source, tAlias.AliasedType, typeViewer);
       if (source == null) return null;
       Method coercion = this.UserDefinedImplicitCoercionMethod(source, tAlias.AliasedType, targetType, false, typeViewer);
       if (coercion != null){
         ExpressionList args = new ExpressionList(this.ImplicitCoercion(source, coercion.Parameters[0].Type, typeViewer));
         return new MethodCall(new MemberBinding(null, coercion), args, NodeType.Call, coercion.ReturnType);
       }
     }else{
       Method coercion = this.UserDefinedImplicitCoercionMethod(source, source.Type, targetType, true, typeViewer);
       if (coercion != null){
         ExpressionList args = new ExpressionList(this.ImplicitCoercion(source, coercion.Parameters[0].Type, typeViewer));
         return new MethodCall(new MemberBinding(null, coercion), args, NodeType.Call, coercion.ReturnType);
       }
     }
     this.HandleError(source, Error.CannotCoerceNullToValueType, this.GetTypeName(targetType));
     return new Local(targetType);
   }
   //Special case for string literal
   if (source.NodeType == NodeType.Literal && sourceType == SystemTypes.String &&
       (targetType.Template == SystemTypes.GenericNonNull || targetType.Template == SystemTypes.GenericInvariant) && 
       this.GetStreamElementType(targetType, typeViewer) == SystemTypes.String)
       return this.ExplicitCoercion(source, targetType, typeViewer);
   //Implicit numeric coercions + implicit enumeration coercions + implicit constant expression coercions
   if (sourceType.IsPrimitive && sourceType != SystemTypes.String && (targetType.IsPrimitive || targetType == SystemTypes.Decimal || targetType is EnumNode)){
     Expression primitiveCoercion = this.ImplicitPrimitiveCoercion(source, sourceType, targetType, typeViewer);
     if (primitiveCoercion != null) return primitiveCoercion;
   }
   //Implicit coercion from string literal to numbers or eums
   if (this.allowStringLiteralToOtherPrimitiveCoercion && sourceType == SystemTypes.String && (targetType.IsPrimitive || targetType == SystemTypes.Decimal || targetType is EnumNode)){
     Expression primitiveCoercion = this.ImplicitPrimitiveCoercion(source, sourceType, targetType, typeViewer);
     if (primitiveCoercion != null) return primitiveCoercion;
   }
   
   //Implicit reference coercions
   if (TypeViewer.GetTypeView(typeViewer, sourceType).IsAssignableTo(targetType)){
     if (targetIsNonNullType && !(sourceIsNonNullType) && !sourceType.IsValueType) {
       //Handling for non null types
       return ImplicitNonNullCoercion(this.ErrorHandler, source, originalTargetType);
     }else if (sourceType.IsValueType && !targetType.IsValueType){
       if (sourceType.NodeType == NodeType.TypeUnion){
         Debug.Assert(targetType == SystemTypes.Object);
         return this.CoerceTypeUnionToObject(source, typeViewer);
       }
       if (sourceType is TupleType){
         if (targetType == SystemTypes.Object)
           return this.TupleCoercion(source, sourceType, targetType, false, typeViewer);
       }else if (targetType.Template != SystemTypes.GenericIEnumerable && this.GetStreamElementType(sourceType, typeViewer) != sourceType)
         return this.ExplicitCoercion(this.CoerceStreamToObject(source, sourceType, typeViewer), targetType, typeViewer);
       Expression e = new BinaryExpression(source, new MemberBinding(null, sourceType), NodeType.Box, targetType, source.SourceContext);
       e.Type = targetType;
       return e;
     }else if (this.useGenerics && (sourceType is TypeParameter || sourceType is ClassParameter)){
       source = new BinaryExpression(source, new MemberBinding(null, sourceType), NodeType.Box, sourceType);
       if (targetType == SystemTypes.Object) return source;
       return new BinaryExpression(source, new MemberBinding(null, targetType), NodeType.UnboxAny, targetType);
     }
     else if (this.useGenerics && sourceType is ArrayType) {
       ArrayType sat = (ArrayType)sourceType;
       while (sat.ElementType is ArrayType) sat = (ArrayType)sat.ElementType;
       if (sat.ElementType is ITypeParameter)
         return new BinaryExpression(source, new MemberBinding(null, targetType), NodeType.Castclass, targetType, source.SourceContext);
       return source;
     }else
       return source;
   }
   //Special case for delegates
   if (targetType is DelegateNode)
     return this.CoerceToDelegate(source, sourceType, (DelegateNode)targetType, false, typeViewer);
   //Special case for type union to common base type
   if (sourceType.NodeType == NodeType.TypeUnion)
     return this.CoerceFromTypeUnion(source, (TypeUnion)sourceType, targetType, false, originalTargetType, typeViewer);
   //Special case for Type intersection target type
   if (targetType.NodeType == NodeType.TypeIntersection)
     return this.CoerceToTypeIntersection(source, sourceType, (TypeIntersection)targetType, false, typeViewer);
   //Special cases for typed streams
   Expression streamCoercion = this.StreamCoercion(source, sourceType, targetType, false, originalTargetType, typeViewer);
   if (streamCoercion != null) return streamCoercion;
   //Implicit tuple coercions
   return this.TupleCoercion(source, sourceType, targetType, false, typeViewer);
 }
예제 #42
0
 public ClosureSignatureInferrer(BlockExpression closure)
 {
     _closure = closure;
     InitializeInputTypes();
 }
예제 #43
0
        // Move off the main stack
        private Expression BuildScopedExpression(ServiceCallSite callSite)
        {
            ConstantExpression callSiteExpression = Expression.Constant(
                callSite,
                typeof(ServiceCallSite));

            // We want to directly use the callsite value if it's set and the scope is the root scope.
            // We've already called into the RuntimeResolver and pre-computed any singletons or root scope
            // Avoid the compilation for singletons (or promoted singletons)
            MethodCallExpression resolveRootScopeExpression = Expression.Call(
                CallSiteRuntimeResolverInstanceExpression,
                ServiceLookupHelpers.ResolveCallSiteAndScopeMethodInfo,
                callSiteExpression,
                ScopeParameter);

            ConstantExpression keyExpression = Expression.Constant(
                callSite.Cache.Key,
                typeof(ServiceCacheKey));

            ParameterExpression resolvedVariable = Expression.Variable(typeof(object), "resolved");

            ParameterExpression resolvedServices = ResolvedServices;

            MethodCallExpression tryGetValueExpression = Expression.Call(
                resolvedServices,
                ServiceLookupHelpers.TryGetValueMethodInfo,
                keyExpression,
                resolvedVariable);

            Expression captureDisposible = TryCaptureDisposable(callSite, ScopeParameter, VisitCallSiteMain(callSite, null));

            BinaryExpression assignExpression = Expression.Assign(
                resolvedVariable,
                captureDisposible);

            MethodCallExpression addValueExpression = Expression.Call(
                resolvedServices,
                ServiceLookupHelpers.AddMethodInfo,
                keyExpression,
                resolvedVariable);

            BlockExpression blockExpression = Expression.Block(
                typeof(object),
                new[]
            {
                resolvedVariable
            },
                Expression.IfThen(
                    Expression.Not(tryGetValueExpression),
                    Expression.Block(
                        assignExpression,
                        addValueExpression)),
                resolvedVariable);


            // The C# compiler would copy the lock object to guard against mutation.
            // We don't, since we know the lock object is readonly.
            ParameterExpression lockWasTaken = Expression.Variable(typeof(bool), "lockWasTaken");
            ParameterExpression sync         = Sync;

            MethodCallExpression monitorEnter = Expression.Call(ServiceLookupHelpers.MonitorEnterMethodInfo, sync, lockWasTaken);
            MethodCallExpression monitorExit  = Expression.Call(ServiceLookupHelpers.MonitorExitMethodInfo, sync);

            BlockExpression       tryBody     = Expression.Block(monitorEnter, blockExpression);
            ConditionalExpression finallyBody = Expression.IfThen(lockWasTaken, monitorExit);

            return(Expression.Condition(
                       Expression.Property(
                           ScopeParameter,
                           typeof(ServiceProviderEngineScope)
                           .GetProperty(nameof(ServiceProviderEngineScope.IsRootScope), BindingFlags.Instance | BindingFlags.Public)),
                       resolveRootScopeExpression,
                       Expression.Block(
                           typeof(object),
                           new[] { lockWasTaken },
                           Expression.TryFinally(tryBody, finallyBody))
                       ));
        }
예제 #44
0
        public override Expression Reduce()
        {
            LabelTarget forLabel = Label("<ironsilver_for>");
            VariableExpression forReturn = null;
            LeftHandValueExpression forReturnLh = null;
            bool useReturn = true;
            if (Body.Type == typeof (void)) {
                useReturn = false;
            }
            else {
                forReturn = Variable(Constant("<ironsilver_for_return>"));
                forReturnLh = LeftHandValue(forReturn);
                forReturn.Scope = ((AstExpression) Body).Scope;
                forReturnLh.Scope = ((AstExpression) Body).Scope;
            }
            VariableExpression forTest = Variable(Constant("<ironsilver_for_test>"));
            LeftHandValueExpression forTestLh = LeftHandValue(forTest);
            forTest.Scope = ((AstExpression) Body).Scope;
            forTestLh.Scope = ((AstExpression) Body).Scope;
            var realBody = new List<Expression> {
                Init,
                Label(forLabel),
            };
            AssignmentExpression testAssign = Assign(forTestLh, Test);
            realBody.Add(Label(SilverParser.RetryTarget));
            testAssign.Scope = (Body as AstExpression).Scope;
            realBody.Add(testAssign);
            IfExpression testIf;
            if (useReturn) {
                AssignmentExpression returnAssign = Assign(forReturnLh, Body);
                returnAssign.Scope = (Body as AstExpression).Scope;
                testIf = IfThen(forTest, returnAssign);
            }
            else {
                testIf = IfThen(forTest, Body);
            }
            testIf.Scope = ((AstExpression) Body).Scope;
            realBody.Add(testIf);
            realBody.Add(Label(SilverParser.ContinueTarget));
            realBody.Add(Step);
            realBody.Add(IfThen(forTest, Goto(forLabel)));
            realBody.Add(Label(SilverParser.BreakTarget));
            if (useReturn) {
                realBody.Add(forReturn);
            }

            var block = new BlockExpression(realBody) {Scope = (Body as AstExpression).Scope};
            return Convert(block, Type);
        }
예제 #45
0
        private void __limitCompare_Init()
        {
            ParameterExpression pLimitMin = Expression.Parameter(typeof(DateTime));
            ParameterExpression pLimitMax = Expression.Parameter(typeof(DateTime));
            ParameterExpression pDate     = Expression.Parameter(typeof(DateTime));
            ParameterExpression pResult   = Expression.Parameter(typeof(DateTime));
            BlockExpression     block     = null;

            Expression eComparisonGreater = Expression.IfThenElse(
                Expression.GreaterThanOrEqual(pDate, pLimitMin),
                Expression.Assign(pResult, pDate),
                Expression.Assign(pResult, pLimitMin)
                );
            Expression eComparisonLess = Expression.IfThenElse(
                Expression.LessThanOrEqual(pDate, pLimitMax),
                Expression.Assign(pResult, pDate),
                Expression.Assign(pResult, pLimitMax)
                );

            Expression eMinMax = Expression.IfThenElse(
                Expression.GreaterThan(pDate, pLimitMax),
                Expression.Assign(pResult, pLimitMax),
                Expression.Assign(pResult, pLimitMin)
                );

            Expression eComparisonRange = Expression.IfThenElse(
                Expression.AndAlso(
                    Expression.GreaterThanOrEqual(pDate, pLimitMin),
                    Expression.LessThanOrEqual(pDate, pLimitMax)
                    ),
                Expression.Assign(pResult, pDate),
                eMinMax
                );

            switch (limit)
            {
            case e_dot_Limit.inDate:
                __setLR(true, false);
                block = Expression.Block(
                    typeof(DateTime),
                    new[] { pResult },
                    Expression.Assign(pResult, pLimitMin),
                    pResult
                    );
                break;

            case e_dot_Limit.notEarlier:
                __setLR(true, false);
                block = Expression.Block(
                    typeof(DateTime),
                    new[] { pResult },
                    eComparisonGreater,
                    pResult
                    );
                break;

            case e_dot_Limit.notLater:
                __setLR(false, true);
                block = Expression.Block(
                    typeof(DateTime),
                    new[] { pResult },
                    eComparisonLess,
                    pResult
                    );
                break;

                /*case e_dot_Limit.Range:
                 *  __setLR(true, true);
                 *  block = Expression.Block(
                 *      typeof(DateTime),
                 *      new[] { pResult },
                 *      eComparisonRange,
                 *      pResult
                 *      );
                 *  break;*/

                /*case e_dot_Limit.None:
                 * default:
                 *  __setLR(false, false);
                 *  block = Expression.Block(
                 *      typeof(DateTime),
                 *      new[] { pResult },
                 *      Expression.Assign(pResult, pDate),
                 *      pResult
                 *      );
                 *  break;*/
            }

            __limitCMP = null;
            __limitCMP = Expression.Lambda <Func <DateTime, DateTime, DateTime, DateTime> >(block, pLimitMin, pLimitMax, pDate).Compile();
        }
예제 #46
0
        /// <summary>
        /// Creates a mapper Func for a POCO.
        /// </summary>
        private Func <Row, T> CreateMapperForPoco <T>(RowSet rows, PocoData pocoData)
        {
            // We're going to store the method body expressions in a list since we need to use some looping to generate it
            ICollection <Expression> methodBodyExpressions = new LinkedList <Expression>();

            // The input parameter for our Func<Row, T>, a C* Row
            ParameterExpression row = Expression.Parameter(CassandraRowType, "row");

            // T poco = new T();
            var poco = Expression.Variable(pocoData.PocoType, "poco");

            if (pocoData.PocoType.GetTypeInfo().GetConstructor(Type.EmptyTypes) != null)
            {
                //It has default constructor
                methodBodyExpressions.Add(Expression.Assign(poco, Expression.New(pocoData.PocoType)));
            }
            else
            {
                var constructor = pocoData.PocoType.GetTypeInfo().GetConstructors().FirstOrDefault(c => c.GetParameters().Length == rows.Columns.Length);
                if (constructor == null)
                {
                    throw new ArgumentException(
                              string.Format("RowSet columns length is {0} but type {1} does not contain a constructor with the same amount of parameters",
                                            rows.Columns.Length,
                                            pocoData.PocoType));
                }
                var parameterInfos       = constructor.GetParameters();
                var parameterExpressions = new List <Expression>();
                for (var i = 0; i < rows.Columns.Length; i++)
                {
                    var c         = rows.Columns[i];
                    var param     = parameterInfos[i];
                    var getValueT = GetExpressionToGetColumnValueFromRow(row, c, param.ParameterType);
                    parameterExpressions.Add(getValueT);
                }
                methodBodyExpressions.Add(Expression.Assign(poco, Expression.New(constructor, parameterExpressions)));
            }

            // Keep track of any variables we need in the method body, starting with the poco variable
            var methodBodyVariables = new List <ParameterExpression> {
                poco
            };

            foreach (var dbColumn in rows.Columns)
            {
                // Try to find a corresponding column on the POCO and if not found, don't map that column from the RowSet
                PocoColumn pocoColumn;
                if (pocoData.Columns.TryGetItem(dbColumn.Name, out pocoColumn) == false)
                {
                    continue;
                }

                // Figure out if we're going to need to do any casting/conversion when we call Row.GetValue<T>(columnIndex)
                Expression getColumnValue = GetExpressionToGetColumnValueFromRow(row, dbColumn, pocoColumn.MemberInfoType);

                // poco.SomeFieldOrProp = ... getColumnValue call ...
                BinaryExpression getValueAndAssign = Expression.Assign(Expression.MakeMemberAccess(poco, pocoColumn.MemberInfo), getColumnValue);

                // Start with an expression that does nothing if the row is null
                Expression ifRowValueIsNull = Expression.Empty();

                // Cassandra will return null for empty collections, so make an effort to populate collection properties on the POCO with
                // empty collections instead of null in those cases
                Expression createEmptyCollection;
                if (TryGetCreateEmptyCollectionExpression(dbColumn, pocoColumn.MemberInfoType, out createEmptyCollection))
                {
                    // poco.SomeFieldOrProp = ... createEmptyCollection ...
                    ifRowValueIsNull = Expression.Assign(Expression.MakeMemberAccess(poco, pocoColumn.MemberInfo), createEmptyCollection);
                }

                var columnIndex = Expression.Constant(dbColumn.Index, IntType);
                //Expression equivalent to
                // if (row.IsNull(columnIndex) == false) => getValueAndAssign ...
                // else => ifRowIsNull ...
                methodBodyExpressions.Add(Expression.IfThenElse(Expression.IsFalse(Expression.Call(row, IsNullMethod, columnIndex)),
                                                                getValueAndAssign,
                                                                ifRowValueIsNull));
            }

            // The last expression in the method body is the return value, so put our new POCO at the end
            methodBodyExpressions.Add(poco);

            // Create a block expression for the method body expressions
            BlockExpression methodBody = Expression.Block(methodBodyVariables, methodBodyExpressions);

            // Return compiled expression
            return(Expression.Lambda <Func <Row, T> >(methodBody, row).Compile());
        }
예제 #47
0
 public virtual void VisitBlockExpression(BlockExpression blockExpression)
 {
   if (blockExpression == null) return;
   this.VisitBlock(blockExpression.Block);
 }
예제 #48
0
 protected override bool TryMatchInternal(StatementCollection statements, int startIndex, out Statement result, out int replacedStatementsCount)
 {
     result = null;
     replacedStatementsCount = 0;
     if (!this.TryGetObjectCreation(statements, startIndex, out V_0, out V_1))
     {
         return(false);
     }
     if (V_0.get_Initializer() != null && V_0.get_Initializer().get_InitializerType() != InitializerType.CollectionInitializer)
     {
         return(false);
     }
     if (!this.ImplementsInterface(V_0.get_Type(), "System.Collections.IEnumerable"))
     {
         return(false);
     }
     V_2 = new ExpressionCollection();
     V_3 = startIndex + 1;
     while (V_3 < statements.get_Count() && this.TryGetNextExpression(statements.get_Item(V_3), out V_4) && V_4.get_CodeNodeType() == 19)
     {
         V_5 = V_4 as MethodInvocationExpression;
         V_6 = V_5.get_MethodExpression().get_MethodDefinition();
         if (!this.CompareTargets(V_1, V_5.get_MethodExpression().get_Target()) || String.op_Inequality(V_6.get_Name(), "Add") || V_5.get_Arguments().get_Count() == 0)
         {
             break;
         }
         if (V_5.get_Arguments().get_Count() != 1)
         {
             stackVariable88 = V_5.get_Arguments();
             stackVariable89 = CollectionInitializationPattern.u003cu003ec.u003cu003e9__1_0;
             if (stackVariable89 == null)
             {
                 dummyVar0       = stackVariable89;
                 stackVariable89 = new Func <Expression, Expression>(CollectionInitializationPattern.u003cu003ec.u003cu003e9.u003cTryMatchInternalu003eb__1_0);
                 CollectionInitializationPattern.u003cu003ec.u003cu003e9__1_0 = stackVariable89;
             }
             V_7 = new BlockExpression(new ExpressionCollection(stackVariable88.Select <Expression, Expression>(stackVariable89)), null);
             V_2.Add(V_7);
         }
         else
         {
             V_2.Add(V_5.get_Arguments().get_Item(0).Clone());
         }
         V_3 = V_3 + 1;
     }
     if (V_2.get_Count() == 0)
     {
         return(false);
     }
     if (V_0.get_Initializer() != null)
     {
         V_9 = V_2.GetEnumerator();
         try
         {
             while (V_9.MoveNext())
             {
                 V_10 = V_9.get_Current();
                 V_0.get_Initializer().get_Expressions().Add(V_10);
             }
         }
         finally
         {
             if (V_9 != null)
             {
                 V_9.Dispose();
             }
         }
     }
     else
     {
         V_8 = new InitializerExpression(V_2, 0);
         V_8.set_IsMultiLine(true);
         V_0.set_Initializer(V_8);
     }
     result = statements.get_Item(startIndex);
     replacedStatementsCount = V_2.get_Count() + 1;
     return(true);
 }
예제 #49
0
        private static BlockExpression Update(BlockExpression node)
        {
            // Tests the call of Update to Expression.Block factories.

            var res = node.Update(node.Variables, node.Expressions.ToArray());

            Assert.NotSame(node, res);

            return res;
        }
예제 #50
0
        public void Init1()
        {
            try
            {
                var finalExpression = CreateCore();
                _func = finalExpression.Compile();
                Expression <Func <CreateClaptrapInput, ValidateResult> > CreateCore()
                {
                    ParameterExpression input = Expression.Parameter(typeof(CreateClaptrapInput), "input");

                    LabelTarget         returnLabel = Expression.Label(typeof(ValidateResult));
                    ParameterExpression resultExp   = Expression.Variable(typeof(ValidateResult));

                    List <Expression> list = new List <Expression> {
                        CreateDefaultResult()
                    };

                    foreach (PropertyInfo item in typeof(CreateClaptrapInput).GetProperties().Where(a => a.PropertyType == typeof(string)))
                    {
                        if (item.GetCustomAttribute <RequiredAttribute>() != null)
                        {
                            list.Add(CreateValidate(item, CreateValidateStringRequiredExp()));
                        }
                        var minLength = item.GetCustomAttribute <MinLengthAttribute>();
                        if (minLength != null)
                        {
                            list.Add(CreateValidate(item, CreateValidateStringMinLengthExp(minLength.Length)));
                        }
                    }
                    list.Add(Expression.Label(returnLabel, resultExp));

                    var body = Expression.Block(new[] { resultExp }, list.ToArray());

                    Expression <Func <CreateClaptrapInput, ValidateResult> > expression = Expression.Lambda <Func <CreateClaptrapInput, ValidateResult> >(body, input);

                    return(expression);

                    Expression CreateValidate(PropertyInfo property, Expression <Func <string, string, ValidateResult> > expression)
                    {
                        ConstantExpression nameExp  = Expression.Constant(property.Name, typeof(string));
                        MemberExpression   valueExp = Expression.Property(input, property);
                        PropertyInfo       isOk     = typeof(ValidateResult).GetProperty(nameof(ValidateResult.IsOk));

                        InvocationExpression result    = Expression.Invoke(expression, nameExp, valueExp);
                        BinaryExpression     assignExp = Expression.Assign(resultExp, result);

                        UnaryExpression       flageExp  = Expression.IsFalse(Expression.Property(result, isOk));
                        ConditionalExpression ifThanExp = Expression.IfThen(flageExp, Expression.Return(returnLabel, resultExp));

                        BlockExpression re = Expression.Block(new[] { resultExp }, assignExp, ifThanExp);

                        return(re);
                    }

                    Expression CreateDefaultResult()
                    {
                        MethodInfo           okMethodInfo   = typeof(ValidateResult).GetMethod(nameof(ValidateResult.Ok));
                        MethodCallExpression callExpression = Expression.Call(okMethodInfo);

                        var re = Expression.Assign(resultExp, callExpression);

                        return(re);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #51
0
        private void EmitBranchBlock(bool branch, BlockExpression node, Label label) {
            EnterScope(node);

            int count = node.ExpressionCount;
            for (int i = 0; i < count - 1; i++) {
                EmitExpressionAsVoid(node.GetExpression(i));
            }
            EmitExpressionAndBranch(branch, node.GetExpression(count - 1), label);

            ExitScope(node);
        }
예제 #52
0
        public virtual bool IsEvaluatableBlock(BlockExpression node)
        {
            ArgumentUtility.CheckNotNull("node", node);

            return(true);
        }
예제 #53
0
 public override Expression VisitBlockExpression(BlockExpression blockExpression){
   if (blockExpression == null) return null;
   Block b = blockExpression.Block = this.VisitBlock(blockExpression.Block);
   blockExpression.Type = SystemTypes.Void;
   StatementList statements = b == null ? null : b.Statements;
   if (statements != null && statements.Count > 0){
     ExpressionStatement es = statements[statements.Count-1] as ExpressionStatement;
     if (es != null && es.Expression != null && es.Expression.Type != null) {
       blockExpression.Type = es.Expression.Type;
       if (es.Expression is Literal && statements.Count == 1){
         return es.Expression;
       }
     }
   }
   return blockExpression;
 }
 protected override Expression VisitBlock(BlockExpression node)
 {
     return(GiveUp(node));
 }
예제 #55
0
 public override Expression VisitBlockExpression(BlockExpression blockExpression) {
   if (blockExpression == null) return null;
   blockExpression.Block = this.VisitBlock(blockExpression.Block);
   return blockExpression;
   //TODO: give an error. This method should always be overridden
 }
예제 #56
0
 protected override Expression VisitBlock(BlockExpression node)
 {
     return(Visiting((expr) => base.VisitBlock(expr as BlockExpression), node));
 }
예제 #57
0
    public virtual Differences VisitBlockExpression(BlockExpression blockExpression1, BlockExpression blockExpression2){
      Differences differences = new Differences(blockExpression1, blockExpression2);
      if (blockExpression1 == null || blockExpression2 == null){
        if (blockExpression1 != blockExpression2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++;
        return differences;
      }
      BlockExpression changes = (BlockExpression)blockExpression2.Clone();
      BlockExpression deletions = (BlockExpression)blockExpression2.Clone();
      BlockExpression insertions = (BlockExpression)blockExpression2.Clone();
  
      Differences diff = this.VisitBlock(blockExpression1.Block, blockExpression2.Block);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Block = diff.Changes as Block;
      deletions.Block = diff.Deletions as Block;
      insertions.Block = diff.Insertions as Block;
      Debug.Assert(diff.Changes == changes.Block && diff.Deletions == deletions.Block && diff.Insertions == insertions.Block);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      if (differences.NumberOfDifferences == 0){
        differences.Changes = null;
        differences.Deletions = null;
        differences.Insertions = null;
      }else{
        differences.Changes = changes;
        differences.Deletions = deletions;
        differences.Insertions = insertions;
      }
      return differences;
    }
 public object Visit(BlockExpression block)
 {
     return(null);
 }
예제 #59
0
 public virtual Expression VisitBlockExpression(BlockExpression blockExpression, BlockExpression changes, BlockExpression deletions, BlockExpression insertions){
   this.UpdateSourceContext(blockExpression, changes);
   if (blockExpression == null) return changes;
   if (changes != null){
     if (deletions == null || insertions == null)
       Debug.Assert(false);
     else{
       blockExpression.Block = this.VisitBlock(blockExpression.Block, changes.Block, deletions.Block, insertions.Block);
     }
   }else if (deletions != null)
     return null;
   return blockExpression;
 }
예제 #60
0
 public DoWhileExpression(Token token, BlockExpression block, Expression condition)
     : base(token)
 {
     Block     = block;
     Condition = condition;
 }