Exemplo n.º 1
0
        public static DynamicMetaObject Bind(DynamicMetaObject target, Compiler.Expression expr, BindingRestrictions restrictions, DynamicMetaObject errorSuggestion)
        {
            var report = new Compiler.Report(ErrorPrinter.Instance)
            {
                WarningLevel = 0
            };
            var ctx = new Compiler.CompilerContext(report);

            Compiler.RootContext.ToplevelTypes = new Compiler.ModuleContainer(ctx, true);

            InitializeCompiler(ctx);

            Expression res;

            try {
                // TODO: ResolveOptions
                Compiler.ResolveContext rc = new Compiler.ResolveContext(new RuntimeBinderContext(ctx));

                // Static typemanager and internal caches are not thread-safe
                lock (resolver) {
                    expr = expr.Resolve(rc);
                }

                if (expr == null)
                {
                    throw new RuntimeBinderInternalCompilerException("Expression resolved to null");
                }

                res = expr.MakeExpression(new Compiler.BuilderContext());
            } catch (RuntimeBinderException e) {
                if (errorSuggestion != null)
                {
                    return(errorSuggestion);
                }

                if (binder_exception_ctor == null)
                {
                    binder_exception_ctor = typeof(RuntimeBinderException).GetConstructor(new[] { typeof(string) });
                }

                //
                // Uses target type to keep expressions composition working
                //
                res = Expression.Throw(Expression.New(binder_exception_ctor, Expression.Constant(e.Message)), target.LimitType);
            } catch (Exception) {
                if (errorSuggestion != null)
                {
                    return(errorSuggestion);
                }

                throw;
            }

            return(new DynamicMetaObject(res, restrictions));
        }
Exemplo n.º 2
0
        public override Expression DoResolve(ResolveContext ec)
        {
            if (op != Binary.Operator.Addition && op != Binary.Operator.Subtraction)
            {
                target.Error_AssignmentEventOnly(ec);
            }

            source = source.Resolve(ec);
            if (source == null)
            {
                return(null);
            }

            source = Convert.ImplicitConversionRequired(ec, source, target.Type, loc);
            if (source == null)
            {
                return(null);
            }

            eclass = ExprClass.Value;
            type   = TypeManager.void_type;
            return(this);
        }
Exemplo n.º 3
0
        public override Expression DoResolve(EmitContext ec)
        {
            CloneContext cc    = new CloneContext();
            Expression   clone = source.Clone(cc);

            clone = clone.Resolve(ec);
            if (clone == null)
            {
                return(null);
            }

            // This means its really a statement.
            if (clone.Type == TypeManager.void_type)
            {
                source = source.Resolve(ec);
                target = null;
                type   = TypeManager.void_type;
                eclass = ExprClass.Value;
                return(this);
            }

            return(base.DoResolve(ec));
        }
Exemplo n.º 4
0
        public DynamicMetaObject Bind(DynamicContext ctx, Type callingType)
        {
            Expression res;

            try {
                var rc = new Compiler.ResolveContext(new RuntimeBinderContext(ctx, callingType), ResolveOptions);

                // Static typemanager and internal caches are not thread-safe
                lock (resolver) {
                    expr = expr.Resolve(rc, Compiler.ResolveFlags.VariableOrValue);
                }

                if (expr == null)
                {
                    throw new RuntimeBinderInternalCompilerException("Expression resolved to null");
                }

                res = expr.MakeExpression(new Compiler.BuilderContext());
            } catch (RuntimeBinderException e) {
                if (errorSuggestion != null)
                {
                    return(errorSuggestion);
                }

                res = CreateBinderException(e.Message);
            } catch (Exception) {
                if (errorSuggestion != null)
                {
                    return(errorSuggestion);
                }

                throw;
            }

            return(new DynamicMetaObject(res, restrictions));
        }
Exemplo n.º 5
0
        public override Expression DoResolve(EmitContext ec)
        {
            original_source = original_source.Resolve(ec);
            if (original_source == null)
            {
                return(null);
            }

            using (ec.Set(EmitContext.Flags.InCompoundAssignment)) {
                target = target.Resolve(ec);
            }

            if (target == null)
            {
                return(null);
            }

            if (target is MethodGroupExpr)
            {
                Error_CannotAssign(((MethodGroupExpr)target).Name, target.ExprClassName);
                return(null);
            }

            if (target is EventExpr)
            {
                return(new EventAddOrRemove(target, op, original_source, loc).DoResolve(ec));
            }

            //
            // Only now we can decouple the original source/target
            // into a tree, to guarantee that we do not have side
            // effects.
            //
            source = new Binary(op, new TargetExpression(target), original_source, true);
            return(base.DoResolve(ec));
        }
Exemplo n.º 6
0
        protected override Expression DoResolve(ResolveContext ec)
        {
            right = right.Resolve(ec);
            if (right == null)
            {
                return(null);
            }

            MemberAccess ma = target as MemberAccess;

            using (ec.Set(ResolveContext.Options.CompoundAssignmentScope)) {
                target = target.Resolve(ec);
            }

            if (target == null)
            {
                return(null);
            }

            if (target is MethodGroupExpr)
            {
                ec.Report.Error(1656, loc,
                                "Cannot assign to `{0}' because it is a `{1}'",
                                ((MethodGroupExpr)target).Name, target.ExprClassName);
                return(null);
            }

            var event_expr = target as EventExpr;

            if (event_expr != null)
            {
                source = Convert.ImplicitConversionRequired(ec, right, target.Type, loc);
                if (source == null)
                {
                    return(null);
                }

                Expression rside;
                if (op == Binary.Operator.Addition)
                {
                    rside = EmptyExpression.EventAddition;
                }
                else if (op == Binary.Operator.Subtraction)
                {
                    rside = EmptyExpression.EventSubtraction;
                }
                else
                {
                    rside = null;
                }

                target = target.ResolveLValue(ec, rside);
                if (target == null)
                {
                    return(null);
                }

                eclass = ExprClass.Value;
                type   = event_expr.Operator.ReturnType;
                return(this);
            }

            //
            // Only now we can decouple the original source/target
            // into a tree, to guarantee that we do not have side
            // effects.
            //
            if (left == null)
            {
                left = new TargetExpression(target);
            }

            source = new Binary(op, left, right, true, loc);

            if (target is DynamicMemberAssignable)
            {
                Arguments targs = ((DynamicMemberAssignable)target).Arguments;
                source = source.Resolve(ec);

                Arguments args = new Arguments(targs.Count + 1);
                args.AddRange(targs);
                args.Add(new Argument(source));

                var binder_flags = CSharpBinderFlags.ValueFromCompoundAssignment;

                //
                // Compound assignment does target conversion using additional method
                // call, set checked context as the binary operation can overflow
                //
                if (ec.HasSet(ResolveContext.Options.CheckedScope))
                {
                    binder_flags |= CSharpBinderFlags.CheckedContext;
                }

                if (target is DynamicMemberBinder)
                {
                    source = new DynamicMemberBinder(ma.Name, binder_flags, args, loc).Resolve(ec);

                    // Handles possible event addition/subtraction
                    if (op == Binary.Operator.Addition || op == Binary.Operator.Subtraction)
                    {
                        args = new Arguments(targs.Count + 1);
                        args.AddRange(targs);
                        args.Add(new Argument(right));
                        string method_prefix = op == Binary.Operator.Addition ?
                                               Event.AEventAccessor.AddPrefix : Event.AEventAccessor.RemovePrefix;

                        var invoke = DynamicInvocation.CreateSpecialNameInvoke(
                            new MemberAccess(right, method_prefix + ma.Name, loc), args, loc).Resolve(ec);

                        args = new Arguments(targs.Count);
                        args.AddRange(targs);
                        source = new DynamicEventCompoundAssign(ma.Name, args,
                                                                (ExpressionStatement)source, (ExpressionStatement)invoke, loc).Resolve(ec);
                    }
                }
                else
                {
                    source = new DynamicIndexBinder(binder_flags, args, loc).Resolve(ec);
                }

                return(source);
            }

            return(base.DoResolve(ec));
        }
Exemplo n.º 7
0
			protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
			{
				if (!Variable.Type.IsPointer && li == Variable) {
					bc.Report.Error (209, TypeExpression.Location,
						"The type of locals declared in a fixed statement must be a pointer type");
					return null;
				}

				//
				// The rules for the possible declarators are pretty wise,
				// but the production on the grammar is more concise.
				//
				// So we have to enforce these rules here.
				//
				// We do not resolve before doing the case 1 test,
				// because the grammar is explicit in that the token &
				// is present, so we need to test for this particular case.
				//

				if (initializer is Cast) {
					bc.Report.Error (254, initializer.Location, "The right hand side of a fixed statement assignment may not be a cast expression");
					return null;
				}

				initializer = initializer.Resolve (bc);

				if (initializer == null)
					return null;

				//
				// Case 1: Array
				//
				if (initializer.Type.IsArray) {
					TypeSpec array_type = TypeManager.GetElementType (initializer.Type);

					//
					// Provided that array_type is unmanaged,
					//
					if (!TypeManager.VerifyUnmanaged (bc.Compiler, array_type, loc))
						return null;

					//
					// and T* is implicitly convertible to the
					// pointer type given in the fixed statement.
					//
					ArrayPtr array_ptr = new ArrayPtr (initializer, array_type, loc);

					Expression converted = Convert.ImplicitConversionRequired (
						bc, array_ptr, li.Type, loc);
					if (converted == null)
						return null;

					//
					// fixed (T* e_ptr = (e == null || e.Length == 0) ? null : converted [0])
					//
					converted = new Conditional (new BooleanExpression (new Binary (Binary.Operator.LogicalOr,
						new Binary (Binary.Operator.Equality, initializer, new NullLiteral (loc), loc),
						new Binary (Binary.Operator.Equality, new MemberAccess (initializer, "Length"), new IntConstant (0, loc), loc), loc)),
							new NullPointer (loc),
							converted, loc);

					converted = converted.Resolve (bc);

					return new ExpressionEmitter (converted, li);
				}

				//
				// Case 2: string
				//
				if (initializer.Type == TypeManager.string_type) {
					return new StringEmitter (initializer, li, loc).Resolve (bc);
				}

				// Case 3: fixed buffer
				if (initializer is FixedBufferPtr) {
					return new ExpressionEmitter (initializer, li);
				}

				//
				// Case 4: & object.
				//
				bool already_fixed = true;
				Unary u = initializer as Unary;
				if (u != null && u.Oper == Unary.Operator.AddressOf) {
					IVariableReference vr = u.Expr as IVariableReference;
					if (vr == null || !vr.IsFixed) {
						already_fixed = false;
					}
				}

				if (already_fixed) {
					bc.Report.Error (213, loc, "You cannot use the fixed statement to take the address of an already fixed expression");
				}

				initializer = Convert.ImplicitConversionRequired (bc, initializer, li.Type, loc);
				return new ExpressionEmitter (initializer, li);
			}
Exemplo n.º 8
0
		public ExpressionStatement CreateExpressionTreeVariable (BlockContext ec)
		{
			if ((modFlags & Modifier.ISBYREF) != 0)
				ec.Report.Error (1951, Location, "An expression tree parameter cannot use `ref' or `out' modifier");

			expr_tree_variable = new TemporaryVariable (ResolveParameterExpressionType (ec, Location).Type, Location);
			expr_tree_variable = expr_tree_variable.Resolve (ec);

			Arguments arguments = new Arguments (2);
			arguments.Add (new Argument (new TypeOf (
				new TypeExpression (parameter_type, Location), Location)));
			arguments.Add (new Argument (new StringConstant (Name, Location)));
			return new SimpleAssign (ExpressionTreeVariableReference (),
				Expression.CreateExpressionFactoryCall (ec, "Parameter", null, arguments, Location));
		}
Exemplo n.º 9
0
			protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
			{
				if (li.Type == InternalType.Dynamic) {
					initializer = initializer.Resolve (bc);
					if (initializer == null)
						return null;

					// Once there is dynamic used defer conversion to runtime even if we know it will never succeed
					Arguments args = new Arguments (1);
					args.Add (new Argument (initializer));
					initializer = new DynamicConversion (TypeManager.idisposable_type, 0, args, initializer.Location).Resolve (bc);
					if (initializer == null)
						return null;

					var var = LocalVariable.CreateCompilerGenerated (TypeManager.idisposable_type, bc.CurrentBlock, loc);
					dispose_call = CreateDisposeCall (bc, var);
					dispose_call.Resolve (bc);

					return base.ResolveInitializer (bc, li, new SimpleAssign (var.CreateReferenceExpression (bc, loc), initializer, loc));
				}

				if (li == Variable) {
					CheckIDiposableConversion (bc, li, initializer);
					dispose_call = CreateDisposeCall (bc, li);
					dispose_call.Resolve (bc);
				}

				return base.ResolveInitializer (bc, li, initializer);
			}
Exemplo n.º 10
0
        public override Expression DoResolve(ResolveContext ec)
        {
            Expression expr_resolved = expr.Resolve(ec,
                                                    ResolveFlags.VariableOrValue | ResolveFlags.Type |
                                                    ResolveFlags.Intermediate | ResolveFlags.DisableStructFlowAnalysis);

            if (expr_resolved == null)
            {
                return(null);
            }

            Type expr_type = expr_resolved.Type;

            if (expr_type.IsPointer || expr_type == TypeManager.void_type || expr_type == TypeManager.null_type || expr_type == InternalType.AnonymousMethod)
            {
                Unary.Error_OperatorCannotBeApplied(ec, loc, ".", expr_type);
                return(null);
            }

            if (targs != null)
            {
                if (!targs.Resolve(ec))
                {
                    return(null);
                }
            }

            ArrayList results = new ArrayList();

            if (expr_resolved is Namespace)
            {
                Namespace nexpr = expr_resolved as Namespace;
                string    namespaced_partial;

                if (partial_name == null)
                {
                    namespaced_partial = nexpr.Name;
                }
                else
                {
                    namespaced_partial = nexpr.Name + "." + partial_name;
                }

#if false
                Console.WriteLine("Workign with: namespaced partial {0}", namespaced_partial);
                foreach (var x in ec.TypeContainer.NamespaceEntry.CompletionGetTypesStartingWith(ec.TypeContainer, namespaced_partial))
                {
                    Console.WriteLine("    {0}", x);
                }
#endif

                CompletionSimpleName.AppendResults(
                    results,
                    partial_name,
                    ec.CurrentTypeDefinition.NamespaceEntry.CompletionGetTypesStartingWith(namespaced_partial));
            }
            else
            {
                MemberInfo [] result = expr_type.FindMembers(
                    MemberTypes.All, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public,
                    CollectingFilter, partial_name);

                foreach (MemberInfo r in result)
                {
                    string name;

                    MethodBase rasb = r as MethodBase;
                    if (rasb != null && rasb.IsSpecialName)
                    {
                        continue;
                    }

                    if (partial_name == null)
                    {
                        name = r.Name;
                    }
                    else
                    {
                        name = r.Name.Substring(partial_name.Length);
                    }

                    if (results.Contains(name))
                    {
                        continue;
                    }
                    results.Add(name);
                }
            }

            throw new CompletionResult(partial_name == null ? "" : partial_name, (string [])results.ToArray(typeof(string)));
        }
Exemplo n.º 11
0
        protected override Expression DoResolve(ResolveContext rc)
        {
            var src = source.Resolve(rc);

            if (src == null)
            {
                return(null);
            }

            if (InternalType.HasNoType(src.Type))
            {
                rc.Report.Error(8131, source.Location, "Deconstruct assignment requires an expression with a type on the right-hand-side");
                return(null);
            }

            var src_type = src.Type;

            if (src_type.IsTupleType)
            {
                if (src_type.Arity != targetExprs.Count)
                {
                    rc.Report.Error(8132, loc, "Cannot deconstruct a tuple of `{0}' elements into `{1}' variables",
                                    src_type.Arity.ToString(), targetExprs.Count.ToString());
                    return(null);
                }

                var tupleLiteral = src as TupleLiteral;
                if (tupleLiteral == null && !ExpressionAnalyzer.IsInexpensiveLoad(src))
                {
                    var expr_variable = LocalVariable.CreateCompilerGenerated(source.Type, rc.CurrentBlock, loc);
                    source   = new CompilerAssign(expr_variable.CreateReferenceExpression(rc, loc), source, loc);
                    instance = expr_variable.CreateReferenceExpression(rc, loc);
                }

                for (int i = 0; i < targetExprs.Count; ++i)
                {
                    var tle = src_type.TypeArguments [i];

                    var lv = variablesToInfer? [i];
                    if (lv != null)
                    {
                        if (InternalType.HasNoType(tle))
                        {
                            rc.Report.Error(8130, Location, "Cannot infer the type of implicitly-typed deconstruction variable `{0}'", lv.Name);
                            lv.Type = InternalType.ErrorType;
                            continue;
                        }

                        lv.Type = tle;
                        lv.PrepareAssignmentAnalysis((BlockContext)rc);
                    }


                    var element_src = tupleLiteral == null ? new MemberAccess(instance, NamedTupleSpec.GetElementPropertyName(i)) : tupleLiteral.Elements [i].Expr;
                    targetExprs [i] = new SimpleAssign(targetExprs [i], element_src).Resolve(rc);
                }

                eclass = ExprClass.Value;

                // TODO: The type is same only if there is no target element conversion
                // var res = (/*byte*/ b, /*short*/ s) = (2, 4);
                type = src.Type;
                return(this);
            }

            if (src_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
            {
                rc.Report.Error(8133, loc, "Cannot deconstruct dynamic objects");
                return(null);
            }

            /*
             * var args = new Arguments (targetExprs.Count);
             * foreach (var t in targetExprs) {
             *      args.Add (new Argument (t, Argument.AType.Out));
             * }
             *
             * var invocation = new Invocation (new MemberAccess (src, "Deconstruct"), args);
             * var res = invocation.Resolve (rc);
             */

            throw new NotImplementedException("Custom deconstruct");
        }
Exemplo n.º 12
0
        protected override Expression DoResolve(ResolveContext ec)
        {
            var e = base.DoResolve(ec);

            if (e == null || e != this)
            {
                return(e);
            }

            var fld = target as FieldExpr;

            if (fld == null)
            {
                var access = target as MemberAccess;
                if (access != null)
                {
                    fld = access.LeftExpression as FieldExpr;
                }

                if (fld == null)
                {
                    Expression simple = target as SimpleName;
                    simple = simple != null?simple.Resolve(ec) : null;

                    fld = simple as FieldExpr;
                }
                if (fld == null)
                {
                    return(e);
                }
            }
            if (!fld.IsRole)
            {
                return(e);
            }

            //assigning to a role. Check that the contract is fullfilled
            var contractName = CSharpParser.GetCurrentRoleContractName(fld.DeclaringType.Name, fld.Name);

            if (CSharpParser.RoleContracts.ContainsKey(contractName))
            {
                if (source.Type == null)
                {
                    source = source.Resolve(ec);
                }
                var contract = CSharpParser.RoleContracts[contractName];
                if (!source.Type.FullfillsContract(contract))
                {
                    var index         = -1;
                    var current_class = contract.Parent;
                    if (current_class.IsGeneric)
                    {
                        var typeParameters = current_class.TypeParameters;
                        for (int i = 0; index < 0 && i < typeParameters.Length; i++)
                        {
                            var param = typeParameters[i];
                            if (target.Type.Name == param.Name)
                            {
                                index = i;
                            }
                        }
                    }
                    if (index < 0)
                    {
                        ec.Report.Error(10009, loc, "Assignment to role '{0}' does not full fill contract", fld.Name);
                    }
                    else
                    {
                        current_class.Spec.AddTypesAndContracts(index, contract);
                    }
                }
            }

            return(this);
        }
Exemplo n.º 13
0
        protected override Expression DoResolve(ResolveContext ec)
        {
            if (ec.Target == Target.JavaScript)
            {
                type   = ec.BuiltinTypes.Dynamic;
                eclass = ExprClass.Value;
                return(this);
            }

            if (Expr is AsArrayInitializer)
            {
                return(Expr.Resolve(ec));
            }

            New newExpr = null;

            if (Expr is Invocation)
            {
                var inv = Expr as Invocation;

                //
                // Special case for PlayScript scalar types with 1 argument -
                // just do an assignment. This is required for cosntructs like
                //
                //	var num:Number = new Number(1.0);
                //
                // since the underlying C# types are primitives and don't have
                // constructors which take arugments.
                //
                var sn = inv.Exp as SimpleName;
                if (sn != null && IsPlayScriptScalarClass(sn.Name) && inv.Arguments != null && inv.Arguments.Count == 1)
                {
                    Argument arg = inv.Arguments [0].Clone(new CloneContext());
                    arg.Resolve(ec);
                    if (arg.Expr.Type != null)
                    {
                        if (BuiltinTypeSpec.IsPrimitiveType(arg.Expr.Type) || arg.Expr.Type.BuiltinType == BuiltinTypeSpec.Type.String)
                        {
                            return(arg.Expr);
                        }
                    }
                    // TODO: ActionScript does actually allow this, but its runtime
                    // rules are hard to implement at compile time, and this should
                    // be a rare use case, so I am leaving it as a compiler error for
                    // now.
                    ec.Report.Error(7112, loc, "The type `{0}' does not contain a constructor that takes non-scalar arguments", sn.Name);
                    return(null);
                }

                newExpr = new New(inv.Exp, inv.Arguments, loc);
            }
            else if (Expr is ElementAccess)
            {
                if (loc.SourceFile != null && !loc.SourceFile.PsExtended)
                {
                    ec.Report.Error(7103, loc, "Native arrays are only suppored in ASX.'");
                    return(null);
                }
                var elemAcc  = Expr as ElementAccess;
                var exprList = new List <Expression>();
                foreach (var arg in elemAcc.Arguments)
                {
                    exprList.Add(arg.Expr);
                }
                // TODO: Handle jagged arrays
                var arrayCreate = new ArrayCreation((FullNamedExpression)elemAcc.Expr, exprList,
                                                    new ComposedTypeSpecifier(exprList.Count, loc), null, loc);
                return(arrayCreate.Resolve(ec));
            }
            else
            {
                var resolveExpr = Expr.Resolve(ec);
                if (resolveExpr == null)
                {
                    return(null);
                }
                if (resolveExpr is TypeOf)
                {
                    newExpr = new New(((TypeOf)resolveExpr).TypeExpression, new Arguments(0), loc);
                }
                else
                {
                    newExpr = new New(resolveExpr, new Arguments(0), loc);
                }
            }

            return(newExpr.Resolve(ec));
        }
Exemplo n.º 14
0
		/// <summary>
		///   Resolves the expression `e' into a boolean expression: either through
		///   an implicit conversion, or through an `operator true' invocation
		/// </summary>
		public static Expression ResolveBoolean (EmitContext ec, Expression e, Location loc)
		{
			e = e.Resolve (ec);
			if (e == null)
				return null;

			if (e.Type == TypeManager.bool_type)
				return e;

			Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);

			if (converted != null)
				return converted;

			//
			// If no implicit conversion to bool exists, try using `operator true'
			//
			converted = Expression.GetOperatorTrue (ec, e, loc);
			if (converted == null){
				e.Error_ValueCannotBeConverted (ec, loc, TypeManager.bool_type, false);
				return null;
			}
			return converted;
		}
Exemplo n.º 15
0
        protected override Expression DoResolve(ResolveContext ec)
        {
            // We have to set these
            this.type   = mg.BestCandidateReturnType;
            this.eclass = ExprClass.Value;

            expr = expr.Resolve(ec);
            if (expr == null)
            {
                return(null);
            }

            Expression argExp;

            bool dynamic_arg;

            if (arguments != null)
            {
                arguments.Resolve(ec, out dynamic_arg);
            }

            switch (mg.Name)
            {
            case "Emit":
                if (!CheckConstant(ec, arguments [0]))
                {
                    return(null);
                }
                this.opcode = _opCodes [(int)((Constant)arguments [0].Expr).GetValue()];
                break;

            case "Load":
                break;

            case "LoadAddr":
                argExp = arguments [0].Expr;
                if (argExp is BoxedCast)
                {
                    argExp = ((BoxedCast)argExp).Child;
                }
                var memloc = argExp as IMemoryLocation;
                if (memloc == null)
                {
                    ec.Report.Error(7803, expr.Location, "Argument must be a valid memory location");
                    return(null);
                }
                break;

            case "LoadInd":
                if (!CheckTypeExpr(ec, arguments[0]))
                {
                    return(null);
                }
                if (!CheckConstant(ec, arguments [1]))
                {
                    return(null);
                }
                break;

            case "Store":
                argExp = arguments [0].Expr;
                if (argExp is BoxedCast)
                {
                    argExp = ((BoxedCast)argExp).Child;
                }
                var t = argExp as IAssignMethod;
                if (t == null)
                {
                    ec.Report.Error(7804, expr.Location, "Argument must be a valid assignment target");
                    return(null);
                }
                if (!CheckConstant(ec, arguments [1]))
                {
                    return(null);
                }
                break;

            case "StoreInd":
                if (!CheckTypeExpr(ec, arguments[0]))
                {
                    return(null);
                }
                if (!CheckConstant(ec, arguments [1]))
                {
                    return(null);
                }
                break;

            default:
                ec.Report.Error(7802, "Invalid intrinsic method");
                return(null);
            }

            return(this);
        }
Exemplo n.º 16
0
		public Expression DoResolve (EmitContext ec, Expression right_side, ResolveFlags flags)
		{
			if (type != null)
				throw new Exception ();
			//
			// Resolve the expression with flow analysis turned off, we'll do the definite
			// assignment checks later.  This is because we don't know yet what the expression
			// will resolve to - it may resolve to a FieldExpr and in this case we must do the
			// definite assignment check on the actual field and not on the whole struct.
			//

			Expression original = expr;
			expr = expr.Resolve (ec, flags | ResolveFlags.DisableFlowAnalysis);

			if (expr == null)
				return null;

			if (expr is SimpleName){
				SimpleName child_expr = (SimpleName) expr;
				
				Expression new_expr = new SimpleName (child_expr.Name, Identifier, loc);

				return new_expr.Resolve (ec, flags);
			}
					
			//
			// TODO: I mailed Ravi about this, and apparently we can get rid
			// of this and put it in the right place.
			// 
			// Handle enums here when they are in transit.
			// Note that we cannot afford to hit MemberLookup in this case because
			// it will fail to find any members at all
			//

			int errors = Report.Errors;
			
			Type expr_type = expr.Type;
			if ((expr is TypeExpr) &&
			    (expr_type == TypeManager.enum_type ||
			     expr_type.IsSubclassOf (TypeManager.enum_type))){
				
				Enum en = TypeManager.LookupEnum (expr_type);
				
				if (en != null) {
					object value = en.LookupEnumValue (ec, Identifier, loc);

					if (value != null){
						Constant c = Constantify (value, en.UnderlyingType);
						return new EnumConstant (c, expr_type);
					}
				}
			}

			if (expr_type.IsPointer){
				Error (23, "The `.' operator can not be applied to pointer operands (" +
				       TypeManager.CSharpName (expr_type) + ")");
				return null;
			}

			member_lookup = MemberLookupFinal (ec, expr_type, expr_type, Identifier, loc);
			if (member_lookup == null)
				return null;

			if (member_lookup is TypeExpr){
				member_lookup.Resolve (ec, ResolveFlags.Type);
				return member_lookup;
			} else if ((flags & ResolveFlags.MaskExprClass) == ResolveFlags.Type)
				return null;
			
			member_lookup = ResolveMemberAccess (ec, member_lookup, expr, loc, original);
			if (member_lookup == null)
				return null;

			// The following DoResolve/DoResolveLValue will do the definite assignment
			// check.

			if (right_side != null)
				member_lookup = member_lookup.DoResolveLValue (ec, right_side);
			else
				member_lookup = member_lookup.DoResolve (ec);

			return member_lookup;
		}
Exemplo n.º 17
0
		public static Expression ResolveMemberAccess (EmitContext ec, Expression member_lookup,
							      Expression left, Location loc,
							      Expression left_original)
		{
			bool left_is_type, left_is_explicit;

			// If `left' is null, then we're called from SimpleNameResolve and this is
			// a member in the currently defining class.
			if (left == null) {
				left_is_type = ec.IsStatic || ec.IsFieldInitializer;
				left_is_explicit = false;

				// Implicitly default to `this' unless we're static.
				if (!ec.IsStatic && !ec.IsFieldInitializer && !ec.InEnumContext)
					left = ec.This;
			} else {
				left_is_type = left is TypeExpr;
				left_is_explicit = true;
			}

			if (member_lookup is FieldExpr){
				FieldExpr fe = (FieldExpr) member_lookup;
				FieldInfo fi = fe.FieldInfo;
				Type decl_type = fi.DeclaringType;
				
				if (fi is FieldBuilder) {
					Const c = TypeManager.LookupConstant ((FieldBuilder) fi);
					
					if (c != null) {
						object o = c.LookupConstantValue (ec);
						if (o == null)
							return null;
						
						object real_value = ((Constant) c.Expr).GetValue ();

						return Constantify (real_value, fi.FieldType);
					}
				}

				if (fi.IsLiteral) {
					Type t = fi.FieldType;
					
					object o;

					if (fi is FieldBuilder)
						o = TypeManager.GetValue ((FieldBuilder) fi);
					else
						o = fi.GetValue (fi);
					
					if (decl_type.IsSubclassOf (TypeManager.enum_type)) {
						if (left_is_explicit && !left_is_type &&
						    !IdenticalNameAndTypeName (ec, left_original, loc)) {
							error176 (loc, fe.FieldInfo.Name);
							return null;
						}					
						
						Expression enum_member = MemberLookup (
							ec, decl_type, "value__", MemberTypes.Field,
							AllBindingFlags, loc); 

						Enum en = TypeManager.LookupEnum (decl_type);

						Constant c;
						if (en != null)
							c = Constantify (o, en.UnderlyingType);
						else 
							c = Constantify (o, enum_member.Type);
						
						return new EnumConstant (c, decl_type);
					}
					
					Expression exp = Constantify (o, t);

					if (left_is_explicit && !left_is_type) {
						error176 (loc, fe.FieldInfo.Name);
						return null;
					}
					
					return exp;
				}

				if (fi.FieldType.IsPointer && !ec.InUnsafe){
					UnsafeError (loc);
					return null;
				}
			}

			if (member_lookup is EventExpr) {

				EventExpr ee = (EventExpr) member_lookup;
				
				//
				// If the event is local to this class, we transform ourselves into
				// a FieldExpr
				//

				if (ee.EventInfo.DeclaringType == ec.ContainerType) {
					MemberInfo mi = GetFieldFromEvent (ee);

					if (mi == null) {
						//
						// If this happens, then we have an event with its own
						// accessors and private field etc so there's no need
						// to transform ourselves : we should instead flag an error
						//
						Assign.error70 (ee.EventInfo, loc);
						return null;
					}

					Expression ml = ExprClassFromMemberInfo (ec, mi, loc);
					
					if (ml == null) {
						Report.Error (-200, loc, "Internal error!!");
						return null;
					}
					
					return ResolveMemberAccess (ec, ml, left, loc, left_original);
				}
			}
			
			if (member_lookup is IMemberExpr) {
				IMemberExpr me = (IMemberExpr) member_lookup;

				if (left_is_type){
					MethodGroupExpr mg = me as MethodGroupExpr;
					if ((mg != null) && left_is_explicit && left.Type.IsInterface)
						mg.IsExplicitImpl = left_is_explicit;

					if (!me.IsStatic){
						if (IdenticalNameAndTypeName (ec, left_original, loc))
							return member_lookup;

						SimpleName.Error_ObjectRefRequired (ec, loc, me.Name);
						return null;
					}

				} else {
					if (!me.IsInstance){
						if (IdenticalNameAndTypeName (ec, left_original, loc))
							return member_lookup;

						if (left_is_explicit) {
							error176 (loc, me.Name);
							return null;
						}
					}

					//
					// Since we can not check for instance objects in SimpleName,
					// becaue of the rule that allows types and variables to share
					// the name (as long as they can be de-ambiguated later, see 
					// IdenticalNameAndTypeName), we have to check whether left 
					// is an instance variable in a static context
					//
					// However, if the left-hand value is explicitly given, then
					// it is already our instance expression, so we aren't in
					// static context.
					//

					if (ec.IsStatic && !left_is_explicit && left is IMemberExpr){
						IMemberExpr mexp = (IMemberExpr) left;

						if (!mexp.IsStatic){
							SimpleName.Error_ObjectRefRequired (ec, loc, mexp.Name);
							return null;
						}
					}

					me.InstanceExpression = left;
				}

				return member_lookup;
			}

			if (member_lookup is TypeExpr){
				member_lookup.Resolve (ec, ResolveFlags.Type);
				return member_lookup;
			}
			
			Console.WriteLine ("Left is: " + left);
			Report.Error (-100, loc, "Support for [" + member_lookup + "] is not present yet");
			Environment.Exit (0);
			return null;
		}
Exemplo n.º 18
0
        public override Expression DoResolve(ResolveContext ec)
        {
            right = right.Resolve(ec);
            if (right == null)
            {
                return(null);
            }

            MemberAccess ma = target as MemberAccess;

            using (ec.Set(ResolveContext.Options.CompoundAssignmentScope)) {
                target = target.Resolve(ec);
            }

            if (target == null)
            {
                return(null);
            }

            if (target is MethodGroupExpr)
            {
                ec.Report.Error(1656, loc,
                                "Cannot assign to `{0}' because it is a `{1}'",
                                ((MethodGroupExpr)target).Name, target.ExprClassName);
                return(null);
            }

            if (target is EventExpr)
            {
                return(new EventAddOrRemove(target, op, right, loc).DoResolve(ec));
            }

            //
            // Only now we can decouple the original source/target
            // into a tree, to guarantee that we do not have side
            // effects.
            //
            if (left == null)
            {
                left = new TargetExpression(target);
            }

            source = new Binary(op, left, right, true);

            // TODO: TargetExpression breaks MemberAccess composition
            if (target is DynamicMemberBinder)
            {
                Arguments targs = ((DynamicMemberBinder)target).Arguments;
                source = source.Resolve(ec);

                Arguments args = new Arguments(2);
                args.AddRange(targs);
                args.Add(new Argument(source));
                source = new DynamicMemberBinder(true, ma.Name, args, loc).Resolve(ec);

                // Handles possible event addition/subtraction
                if (op == Binary.Operator.Addition || op == Binary.Operator.Subtraction)
                {
                    args = new Arguments(2);
                    args.AddRange(targs);
                    args.Add(new Argument(right));
                    string method_prefix = op == Binary.Operator.Addition ?
                                           Event.AEventAccessor.AddPrefix : Event.AEventAccessor.RemovePrefix;

                    Expression invoke = new DynamicInvocation(
                        new MemberAccess(right, method_prefix + ma.Name, loc), args, loc).Resolve(ec);

                    args = new Arguments(1);
                    args.AddRange(targs);
                    source = new DynamicEventCompoundAssign(ma.Name, args,
                                                            (ExpressionStatement)source, (ExpressionStatement)invoke, loc).Resolve(ec);
                }

                return(source);
            }

            return(base.DoResolve(ec));
        }
Exemplo n.º 19
0
                public override bool Resolve(EmitContext ec)
                {
                    TypeExpression storey_type_expr = new TypeExpression(host.TypeBuilder, loc);
                    ArrayList      init             = null;

                    if (host.hoisted_this != null)
                    {
                        init = new ArrayList(host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
                        HoistedThis ht   = host.hoisted_this;
                        FieldExpr   from = new FieldExpr(ht.Field.FieldBuilder, loc);
                        from.InstanceExpression = CompilerGeneratedThis.Instance;
                        init.Add(new ElementInitializer(ht.Field.Name, from, loc));
                    }

                    if (host.hoisted_params != null)
                    {
                        if (init == null)
                        {
                            init = new ArrayList(host.HoistedParameters.Count);
                        }

                        for (int i = 0; i < host.hoisted_params.Count; ++i)
                        {
                            HoistedParameter hp    = (HoistedParameter)host.hoisted_params [i];
                            HoistedParameter hp_cp = (HoistedParameter)host.hoisted_params_copy [i];

                            FieldExpr from = new FieldExpr(hp_cp.Field.FieldBuilder, loc);
                            from.InstanceExpression = CompilerGeneratedThis.Instance;

                            init.Add(new ElementInitializer(hp.Field.Name, from, loc));
                        }
                    }

                    if (init != null)
                    {
                        new_storey = new NewInitialize(storey_type_expr, new ArrayList(0),
                                                       new CollectionOrObjectInitializers(init, loc), loc);
                    }
                    else
                    {
                        new_storey = new New(storey_type_expr, new ArrayList(0), loc);
                    }

                    new_storey = new_storey.Resolve(ec);
                    if (new_storey != null)
                    {
                        new_storey = Convert.ImplicitConversionRequired(ec, new_storey, host_method.MemberType, loc);
                    }

                    if (TypeManager.int_interlocked_compare_exchange == null)
                    {
                        Type t = TypeManager.CoreLookupType("System.Threading", "Interlocked", Kind.Class, true);
                        if (t != null)
                        {
                            TypeManager.int_interlocked_compare_exchange = TypeManager.GetPredefinedMethod(
                                t, "CompareExchange", loc, TypeManager.int32_type,
                                TypeManager.int32_type, TypeManager.int32_type);
                        }
                    }

                    ec.CurrentBranching.CurrentUsageVector.Goto();
                    return(true);
                }
Exemplo n.º 20
0
            public override bool Resolve(BlockContext ec)
            {
                enumerator_type = TypeManager.ienumerator_type;

                bool is_dynamic = expr.Type == InternalType.Dynamic;
                if (is_dynamic)
                    expr = Convert.ImplicitConversionRequired (ec, expr, TypeManager.ienumerable_type, loc);

                if (!ProbeCollectionType (ec, expr.Type)) {
                    Error_Enumerator (ec);
                    return false;
                }

                VarExpr ve = var_type as VarExpr;
                if (ve != null) {
                    // Infer implicitly typed local variable from foreach enumerable type
                    var_type = new TypeExpression (
                        is_dynamic ? InternalType.Dynamic : get_current.Type,
                        var_type.Location);
                }

                var_type = var_type.ResolveAsTypeTerminal (ec, false);
                if (var_type == null)
                    return false;

                enumerator = new TemporaryVariable (enumerator_type, loc);
                enumerator.Resolve (ec);

                init = new Invocation (get_enumerator, null);
                init = init.Resolve (ec);
                if (init == null)
                    return false;

                Expression move_next_expr;
                {
                    var mi = new List<MemberSpec> (1) { move_next };
                    MethodGroupExpr mg = new MethodGroupExpr (mi, var_type.Type, loc);
                    mg.InstanceExpression = enumerator;

                    move_next_expr = new Invocation (mg, null);
                }

                get_current.InstanceExpression = enumerator;

                Statement block = new CollectionForeachStatement (
                    var_type.Type, variable, get_current, statement, loc);

                loop = new While (new BooleanExpression (move_next_expr), block, loc);

                bool implements_idisposable = enumerator_type.ImplementsInterface (TypeManager.idisposable_type);
                if (implements_idisposable || !enumerator_type.IsSealed) {
                    wrapper = new DisposableWrapper (this, implements_idisposable);
                } else {
                    wrapper = new NonDisposableWrapper (this);
                }

                return wrapper.Resolve (ec);
            }
Exemplo n.º 21
0
        protected override Expression DoResolve(ResolveContext rc)
        {
            var src = source.Resolve(rc);

            if (src == null)
            {
                return(null);
            }

            if (InternalType.HasNoType(src.Type))
            {
                rc.Report.Error(8131, source.Location, "Deconstruct assignment requires an expression with a type on the right-hand-side");
                return(null);
            }

            var src_type = src.Type;

            if (src_type.IsTupleType)
            {
                int target_count;

                if (targetExprs == null)
                {
                    target_count = variables.Count;
                    targetExprs  = new List <Expression> (target_count);
                }
                else
                {
                    target_count = targetExprs.Count;
                }

                if (src_type.Arity != target_count)
                {
                    rc.Report.Error(8132, loc, "Cannot deconstruct a tuple of `{0}' elements into `{1}' variables",
                                    src_type.Arity.ToString(CultureInfo.InvariantCulture), target_count.ToString(CultureInfo.InvariantCulture));
                    return(null);
                }

                var tupleLiteral = src as TupleLiteral;
                if (tupleLiteral == null && !ExpressionAnalyzer.IsInexpensiveLoad(src))
                {
                    var expr_variable = LocalVariable.CreateCompilerGenerated(source.Type, rc.CurrentBlock, loc);
                    source   = new CompilerAssign(expr_variable.CreateReferenceExpression(rc, loc), source, loc);
                    instance = expr_variable.CreateReferenceExpression(rc, loc);
                }

                var element_srcs = new List <Expression> ();
                var src_names    = new List <string> ();
                for (int i = 0; i < target_count; ++i)
                {
                    var element_src = tupleLiteral == null ? new MemberAccess(instance, NamedTupleSpec.GetElementPropertyName(i)) : tupleLiteral.Elements [i].Expr;
                    element_srcs.Add(element_src);
                    if (element_src is VariableReference)
                    {
                        src_names.Add((element_src as VariableReference)?.Name);
                    }
                }

                for (int i = 0; i < target_count; ++i)
                {
                    var tle = src_type.TypeArguments [i];

                    if (variables != null)
                    {
                        var variable = variables [i].Variable;

                        if (variable.Type == InternalType.Discard)
                        {
                            variables [i] = null;
                            targetExprs.Add(EmptyExpressionStatement.Instance);
                            continue;
                        }

                        var variable_type = variables [i].TypeExpression;

                        targetExprs.Add(new LocalVariableReference(variable, variable.Location));

                        if (variable_type is VarExpr)
                        {
                            if (InternalType.HasNoType(tle))
                            {
                                rc.Report.Error(8130, Location, "Cannot infer the type of implicitly-typed deconstruction variable `{0}'", variable.Name);
                                tle = InternalType.ErrorType;
                            }

                            variable.Type = tle;
                        }
                        else
                        {
                            variable.Type = variable_type.ResolveAsType(rc);
                        }

                        variable.PrepareAssignmentAnalysis((BlockContext)rc);
                    }

                    var element_target = (targetExprs [i] as SimpleName)?.LookupNameExpression(rc, MemberLookupRestrictions.None);

                    if (element_target != null && src_names.Contains((element_target as VariableReference)?.Name))
                    {
                        var tempType = element_target.Resolve(rc).Type;

                        var temp = new LocalTemporary(tempType);
                        tempExprs.Add(new SimpleAssign(temp, element_srcs [i]).Resolve(rc));
                        targetExprs [i] = new SimpleAssign(targetExprs [i], temp).Resolve(rc);
                    }
                    else
                    {
                        targetExprs [i] = new SimpleAssign(targetExprs [i], element_srcs [i]).Resolve(rc);
                    }
                }

                eclass = ExprClass.Value;

                // TODO: The type is same only if there is no target element conversion
                // var res = (/*byte*/ b, /*short*/ s) = (2, 4);
                type = src.Type;
                return(this);
            }

            if (src_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
            {
                rc.Report.Error(8133, loc, "Cannot deconstruct dynamic objects");
                return(null);
            }

            /*
             * var args = new Arguments (targetExprs.Count);
             * foreach (var t in targetExprs) {
             *      args.Add (new Argument (t, Argument.AType.Out));
             * }
             *
             * var invocation = new Invocation (new MemberAccess (src, "Deconstruct"), args);
             * var res = invocation.Resolve (rc);
             */

            throw new NotImplementedException("Custom deconstruct");
        }
Exemplo n.º 22
0
		protected override Expression DoResolve (ResolveContext rc)
		{
			var sn = expr as SimpleName;
			const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;

			if (sn != null) {
				expr = sn.LookupNameExpression (rc, MemberLookupRestrictions.ReadAccess | MemberLookupRestrictions.ExactArity);

				//
				// Resolve expression which does have type set as we need expression type
				// with disable flow analysis as we don't know whether left side expression
				// is used as variable or type
				//
				if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess) {
					expr = expr.Resolve (rc);
				} else if (expr is TypeParameterExpr) {
					expr.Error_UnexpectedKind (rc, flags, sn.Location);
					expr = null;
				}
			} else {
				expr = expr.Resolve (rc, flags);
			}

			if (expr == null)
				return null;

			TypeSpec expr_type = expr.Type;
			if (expr_type.IsPointer || expr_type.Kind == MemberKind.Void || expr_type == InternalType.NullLiteral || expr_type == InternalType.AnonymousMethod) {
				expr.Error_OperatorCannotBeApplied (rc, loc, ".", expr_type);
				return null;
			}

			if (targs != null) {
				if (!targs.Resolve (rc))
					return null;
			}

			var results = new List<string> ();
			var nexpr = expr as NamespaceExpression;
			if (nexpr != null) {
				string namespaced_partial;

				if (partial_name == null)
					namespaced_partial = nexpr.Namespace.Name;
				else
					namespaced_partial = nexpr.Namespace.Name + "." + partial_name;

				rc.CurrentMemberDefinition.GetCompletionStartingWith (namespaced_partial, results);
				if (partial_name != null)
					results = results.Select (l => l.Substring (partial_name.Length)).ToList ();
			} else {
				var r = MemberCache.GetCompletitionMembers (rc, expr_type, partial_name).Select (l => l.Name);
				AppendResults (results, partial_name, r);
			}

			throw new CompletionResult (partial_name == null ? "" : partial_name, results.Distinct ().ToArray ());
		}
Exemplo n.º 23
0
        protected override Expression DoResolve(ResolveContext ec)
        {
            if (ec.Target == Target.JavaScript)
            {
                type   = ec.BuiltinTypes.Dynamic;
                eclass = ExprClass.Value;
                return(this);
            }

            if (Expr is ElementAccess)
            {
                var elem_access = Expr as ElementAccess;

                if (elem_access.Arguments.Count != 1)
                {
                    ec.Report.Error(7021, loc, "delete statement must have only one index argument.");
                    return(null);
                }

                var expr = elem_access.Expr.Resolve(ec);
                if (expr.Type == null)
                {
                    return(null);
                }

                if (expr.Type.IsArray)
                {
                    ec.Report.Error(7021, loc, "delete statement not allowed on arrays.");
                    return(null);
                }

                if (ec.Target == Target.JavaScript)
                {
                    Expr = Expr.Resolve(ec);
                    return(this);
                }

                if (!expr.Type.IsAsDynamicClass && (expr.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic))
                {
                    ec.Report.Error(7021, loc, "delete statement only allowed on dynamic types or dynamic classes");
                    return(null);
                }

                // cast expression to IDynamicClass and invoke __DeleteDynamicValue
                var dynClass = new Cast(new MemberAccess(new SimpleName("PlayScript", loc), "IDynamicClass", loc), expr, loc);
                removeExpr = new Invocation(new MemberAccess(dynClass, "__DeleteDynamicValue", loc), elem_access.Arguments);
                return(removeExpr.Resolve(ec));
            }
            else if (Expr is MemberAccess)
            {
                if (ec.Target == Target.JavaScript)
                {
                    Expr = Expr.Resolve(ec);
                    return(this);
                }

                var memb_access = Expr as MemberAccess;

                var expr = memb_access.LeftExpression.Resolve(ec);
                if (expr.Type == null)
                {
                    return(null);
                }

                if (!expr.Type.IsAsDynamicClass && (expr.Type.BuiltinType != BuiltinTypeSpec.Type.Dynamic))
                {
                    ec.Report.Error(7021, loc, "delete statement only allowed on dynamic types or dynamic classes");
                    return(null);
                }

                // cast expression to IDynamicClass and invoke __DeleteDynamicValue
                var dynClass = new Cast(new MemberAccess(new SimpleName("PlayScript", loc), "IDynamicClass", loc), expr, loc);
                var args     = new Arguments(1);
                args.Add(new Argument(new StringLiteral(ec.BuiltinTypes, memb_access.Name, loc)));
                removeExpr = new Invocation(new MemberAccess(dynClass, "__DeleteDynamicValue", loc), args);
                return(removeExpr.Resolve(ec));
            }
            else
            {
                // Error is reported elsewhere.
                return(null);
            }
        }
Exemplo n.º 24
0
		public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
		{
			if (right_side == EmptyExpression.OutAccess) {
				right_side.DoResolveLValue (rc, this);
				return null;
			}

			var res_right_side = right_side.Resolve (rc);

			if (DoResolveCore (rc) && res_right_side != null) {
				setter_args = CreateSetterArguments (rc, res_right_side);

				// create setter callsite
				var dc = (binder as IDynamicCallSite);
				if (rc.Module.PredefinedTypes.IsPlayScriptAotMode && (dc != null) && dc.UseCallSite(rc, setter_args)) {
					this.useDelegateInvoke = false;
					setter_args.CreateDynamicBinderArguments(rc);
					setter = CreateCallSite(rc, setter_args, true);
				} else {
					this.useDelegateInvoke = true;
					setter = CreateCallSiteBinder (rc, setter_args, true);
				}
			}

			eclass = ExprClass.Variable;
			return this;
		}
Exemplo n.º 25
0
        protected override Expression DoResolve(ResolveContext rc)
        {
            var sn = expr as SimpleName;
            const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;

            if (sn != null)
            {
                expr = sn.LookupNameExpression(rc, MemberLookupRestrictions.ReadAccess | MemberLookupRestrictions.ExactArity);

                //
                // Resolve expression which does have type set as we need expression type
                // with disable flow analysis as we don't know whether left side expression
                // is used as variable or type
                //
                if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess)
                {
                    expr = expr.Resolve(rc);
                }
                else if (expr is TypeParameterExpr)
                {
                    expr.Error_UnexpectedKind(rc, flags, sn.Location);
                    expr = null;
                }
            }
            else
            {
                expr = expr.Resolve(rc, flags);
            }

            if (expr == null)
            {
                return(null);
            }

            TypeSpec expr_type = expr.Type;

            if (expr_type.IsPointer || expr_type.Kind == MemberKind.Void || expr_type == InternalType.NullLiteral || expr_type == InternalType.AnonymousMethod)
            {
                expr.Error_OperatorCannotBeApplied(rc, loc, ".", expr_type);
                return(null);
            }

            if (targs != null)
            {
                if (!targs.Resolve(rc, true))
                {
                    return(null);
                }
            }

            var results = new List <string> ();
            var nexpr   = expr as NamespaceExpression;

            if (nexpr != null)
            {
                string namespaced_partial;

                if (partial_name == null)
                {
                    namespaced_partial = nexpr.Namespace.Name;
                }
                else
                {
                    namespaced_partial = nexpr.Namespace.Name + "." + partial_name;
                }

                rc.CurrentMemberDefinition.GetCompletionStartingWith(namespaced_partial, results);
                if (partial_name != null)
                {
                    results = results.Select(l => l.Substring(partial_name.Length)).ToList();
                }
            }
            else
            {
                var r = MemberCache.GetCompletitionMembers(rc, expr_type, partial_name).Select(l => l.Name);
                AppendResults(results, partial_name, r);
            }

            throw new CompletionResult(partial_name == null ? "" : partial_name, results.Distinct().ToArray());
        }
Exemplo n.º 26
0
		public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
		{
			if (right_side == EmptyExpression.OutAccess) {
				right_side.DoResolveLValue (rc, this);
				return null;
			}

			var res_right_side = right_side.Resolve (rc);

			if (DoResolveCore (rc) && res_right_side != null) {
				setter_args = CreateSetterArguments (rc, res_right_side);
				setter = CreateCallSiteBinder (rc, setter_args, true);
			}

			eclass = ExprClass.Variable;
			return this;
		}
Exemplo n.º 27
0
		/// <summary>
		///   Resolves the expression `e' into a boolean expression: either through
		///   an implicit conversion, or through an `operator true' invocation
		/// </summary>
		public static Expression ResolveBoolean (ResolveContext ec, Expression e, Location loc)
		{
			e = e.Resolve (ec);
			if (e == null)
				return null;

			if (e.Type == TypeManager.bool_type)
				return e;

			if (TypeManager.IsDynamicType (e.Type)) {
				Arguments args = new Arguments (1);
				args.Add (new Argument (e));
				return new DynamicUnaryConversion ("IsTrue", args, loc).Resolve (ec);
			}

			Expression converted = Convert.ImplicitConversion (ec, e, TypeManager.bool_type, Location.Null);

			if (converted != null)
				return converted;

			//
			// If no implicit conversion to bool exists, try using `operator true'
			//
			converted = Expression.GetOperatorTrue (ec, e, loc);
			if (converted == null){
				e.Error_ValueCannotBeConverted (ec, loc, TypeManager.bool_type, false);
				return null;
			}
			return converted;
		}
Exemplo n.º 28
0
		protected override Expression DoResolve (ResolveContext rc)
		{
			var sn = expr as SimpleName;
			const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;

			//
			// Resolve the expression with flow analysis turned off, we'll do the definite
			// assignment checks later.  This is because we don't know yet what the expression
			// will resolve to - it may resolve to a FieldExpr and in this case we must do the
			// definite assignment check on the actual field and not on the whole struct.
			//
			using (rc.Set (ResolveContext.Options.OmitStructFlowAnalysis)) {
				if (sn != null) {
					expr = sn.LookupNameExpression (rc, MemberLookupRestrictions.ReadAccess | MemberLookupRestrictions.ExactArity);

					//
					// Resolve expression which does have type set as we need expression type
					// with disable flow analysis as we don't know whether left side expression
					// is used as variable or type
					//
					if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess) {
						using (rc.With (ResolveContext.Options.DoFlowAnalysis, false)) {
							expr = expr.Resolve (rc);
						}
					} else if (expr is TypeParameterExpr) {
						expr.Error_UnexpectedKind (rc, flags, sn.Location);
						expr = null;
					}
				} else {
					expr = expr.Resolve (rc, flags);
				}
			}

			if (expr == null)
				return null;

			TypeSpec expr_type = expr.Type;
			if (expr_type.IsPointer || expr_type.Kind == MemberKind.Void || expr_type == InternalType.NullLiteral || expr_type == InternalType.AnonymousMethod) {
				expr.Error_OperatorCannotBeApplied (rc, loc, ".", expr_type);
				return null;
			}

			if (targs != null) {
				if (!targs.Resolve (rc))
					return null;
			}

			var results = new List<string> ();
			if (expr is Namespace) {
				Namespace nexpr = expr as Namespace;
				string namespaced_partial;

				if (partial_name == null)
					namespaced_partial = nexpr.Name;
				else
					namespaced_partial = nexpr.Name + "." + partial_name;

				rc.CurrentMemberDefinition.GetCompletionStartingWith (namespaced_partial, results);
				if (partial_name != null)
					results = results.Select (l => l.Substring (partial_name.Length)).ToList ();
			} else {
				var r = MemberCache.GetCompletitionMembers (rc, expr_type, partial_name).Select (l => l.Name);
				AppendResults (results, partial_name, r);
			}

			throw new CompletionResult (partial_name == null ? "" : partial_name, results.Distinct ().ToArray ());
		}
Exemplo n.º 29
0
			public override bool Resolve (EmitContext ec)
			{
				enumerator_type = TypeManager.ienumerator_type;

				if (!ProbeCollectionType (ec, expr.Type)) {
					Error_Enumerator ();
					return false;
				}

				bool is_disposable = !enumerator_type.IsSealed ||
					TypeManager.ImplementsInterface (enumerator_type, TypeManager.idisposable_type);

				VarExpr ve = var_type as VarExpr;
				if (ve != null) {
					// Infer implicitly typed local variable from foreach enumerable type
					var_type = new TypeExpression (get_current.PropertyInfo.PropertyType, var_type.Location);
				}

				var_type = var_type.ResolveAsTypeTerminal (ec, false);
				if (var_type == null)
					return false;
								
				enumerator = new TemporaryVariable (enumerator_type, loc);
				enumerator.Resolve (ec);

				init = new Invocation (get_enumerator, null);
				init = init.Resolve (ec);
				if (init == null)
					return false;

				Expression move_next_expr;
				{
					MemberInfo[] mi = new MemberInfo[] { move_next };
					MethodGroupExpr mg = new MethodGroupExpr (mi, var_type.Type, loc);
					mg.InstanceExpression = enumerator;

					move_next_expr = new Invocation (mg, null);
				}

				get_current.InstanceExpression = enumerator;

				Statement block = new CollectionForeachStatement (
					var_type.Type, variable, get_current, statement, loc);

				loop = new While (move_next_expr, block, loc);

				wrapper = is_disposable ?
					(Statement) new DisposableWrapper (this) :
					(Statement) new NonDisposableWrapper (this);
				return wrapper.Resolve (ec);
			}
Exemplo n.º 30
0
        protected override Expression DoResolve(ResolveContext ec)
        {
            Expression expr_resolved = expr.Resolve(ec,
                                                    ResolveFlags.VariableOrValue | ResolveFlags.Type);

            if (expr_resolved == null)
            {
                return(null);
            }

            TypeSpec expr_type = expr_resolved.Type;

            if (expr_type.IsPointer || expr_type.Kind == MemberKind.Void || expr_type == InternalType.NullLiteral || expr_type == InternalType.AnonymousMethod)
            {
                Unary.Error_OperatorCannotBeApplied(ec, loc, ".", expr_type);
                return(null);
            }

            if (targs != null)
            {
                if (!targs.Resolve(ec))
                {
                    return(null);
                }
            }

            var results = new List <string> ();

            if (expr_resolved is Namespace)
            {
                Namespace nexpr = expr_resolved as Namespace;
                string    namespaced_partial;

                if (partial_name == null)
                {
                    namespaced_partial = nexpr.Name;
                }
                else
                {
                    namespaced_partial = nexpr.Name + "." + partial_name;
                }

#if false
                Console.WriteLine("Workign with: namespaced partial {0}", namespaced_partial);
                foreach (var x in ec.TypeContainer.NamespaceEntry.CompletionGetTypesStartingWith(ec.TypeContainer, namespaced_partial))
                {
                    Console.WriteLine("    {0}", x);
                }
#endif

                CompletionSimpleName.AppendResults(
                    results,
                    partial_name,
                    ec.CurrentMemberDefinition.Parent.NamespaceEntry.CompletionGetTypesStartingWith(namespaced_partial));
            }
            else
            {
                var r = MemberCache.GetCompletitionMembers(ec, expr_type, partial_name).Select(l => l.Name);
                AppendResults(results, partial_name, r);
            }

            throw new CompletionResult(partial_name == null ? "" : partial_name, results.Distinct().ToArray());
        }
Exemplo n.º 31
0
        // <summary>
        //   Resolve is used in method definitions
        // </summary>
        public virtual Type Resolve(IMemberContext rc)
        {
            if (parameter_type != null)
            {
                return(parameter_type);
            }

            if (attributes != null)
            {
                attributes.AttachTo(this, rc);
            }

            TypeExpr texpr = TypeName.ResolveAsTypeTerminal(rc, false);

            if (texpr == null)
            {
                return(null);
            }

            parameter_type = texpr.Type;

            // Ignore all checks for dummy members
            AbstractPropertyEventMethod pem = rc as AbstractPropertyEventMethod;

            if (pem != null && pem.IsDummy)
            {
                return(parameter_type);
            }

            if (default_expr != null)
            {
                ResolveContext ec = new ResolveContext(rc);
                default_expr = default_expr.Resolve(ec);
                if (default_expr != null)
                {
                    Constant value = default_expr as Constant;
                    if (value == null)
                    {
                        if (default_expr != null)
                        {
                            bool is_valid = false;
                            if (default_expr is DefaultValueExpression)
                            {
                                is_valid = true;
                            }
                            else if (default_expr is New && ((New)default_expr).IsDefaultValueType)
                            {
                                is_valid = TypeManager.IsEqual(parameter_type, default_expr.Type) ||
                                           (TypeManager.IsNullableType(parameter_type) &&
                                            Convert.ImplicitNulableConversion(ec, default_expr, parameter_type) != EmptyExpression.Null);
                            }
                            else
                            {
                                rc.Compiler.Report.Error(1736, default_expr.Location,
                                                         "The expression being assigned to optional parameter `{0}' must be a constant or default value",
                                                         Name);
                                is_valid = true;
                            }

                            if (!is_valid)
                            {
                                default_expr = null;
                                ec.Compiler.Report.Error(1763, Location,
                                                         "Optional parameter `{0}' of type `{1}' can only be initialized with `null'",
                                                         Name, GetSignatureForError());
                            }
                        }
                    }
                    else
                    {
                        Constant c = value.ConvertImplicitly(parameter_type);
                        if (c == null)
                        {
                            if (parameter_type == TypeManager.object_type)
                            {
                                rc.Compiler.Report.Error(1763, Location,
                                                         "Optional parameter `{0}' of type `{1}' can only be initialized with `null'",
                                                         Name, GetSignatureForError());
                            }
                            else
                            {
                                rc.Compiler.Report.Error(1750, Location,
                                                         "Optional parameter value `{0}' cannot be converted to parameter type `{1}'",
                                                         value.GetValue(), GetSignatureForError());
                            }
                            default_expr = null;
                        }
                    }
                }
            }

            if ((modFlags & Parameter.Modifier.ISBYREF) != 0 &&
                TypeManager.IsSpecialType(parameter_type))
            {
                rc.Compiler.Report.Error(1601, Location, "Method or delegate parameter cannot be of type `{0}'",
                                         GetSignatureForError());
                return(null);
            }

            TypeManager.CheckTypeVariance(parameter_type,
                                          (modFlags & Parameter.Modifier.ISBYREF) != 0 ? Variance.None : Variance.Contravariant,
                                          rc);

            if (TypeManager.IsGenericParameter(parameter_type))
            {
                return(parameter_type);
            }

            if ((parameter_type.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute)
            {
                rc.Compiler.Report.Error(721, Location, "`{0}': static types cannot be used as parameters",
                                         texpr.GetSignatureForError());
                return(parameter_type);
            }

            if ((modFlags & Modifier.This) != 0 && (parameter_type.IsPointer || TypeManager.IsDynamicType(parameter_type)))
            {
                rc.Compiler.Report.Error(1103, Location, "The extension method cannot be of type `{0}'",
                                         TypeManager.CSharpName(parameter_type));
            }

            return(parameter_type);
        }
Exemplo n.º 32
0
                public override bool Resolve(BlockContext ec)
                {
                    TypeExpression    storey_type_expr = new TypeExpression(host.Definition, loc);
                    List <Expression> init             = null;

                    if (host.hoisted_this != null)
                    {
                        init = new List <Expression> (host.hoisted_params == null ? 1 : host.HoistedParameters.Count + 1);
                        HoistedThis ht   = host.hoisted_this;
                        FieldExpr   from = new FieldExpr(ht.Field, loc);
                        from.InstanceExpression = CompilerGeneratedThis.Instance;
                        init.Add(new ElementInitializer(ht.Field.Name, from, loc));
                    }

                    if (host.hoisted_params != null)
                    {
                        if (init == null)
                        {
                            init = new List <Expression> (host.HoistedParameters.Count);
                        }

                        for (int i = 0; i < host.hoisted_params.Count; ++i)
                        {
                            HoistedParameter hp    = (HoistedParameter)host.hoisted_params [i];
                            HoistedParameter hp_cp = (HoistedParameter)host.hoisted_params_copy [i];

                            FieldExpr from = new FieldExpr(hp_cp.Field, loc);
                            from.InstanceExpression = CompilerGeneratedThis.Instance;

                            init.Add(new ElementInitializer(hp.Field.Name, from, loc));
                        }
                    }

                    if (init != null)
                    {
                        new_storey = new NewInitialize(storey_type_expr, null,
                                                       new CollectionOrObjectInitializers(init, loc), loc);
                    }
                    else
                    {
                        new_storey = new New(storey_type_expr, null, loc);
                    }

                    new_storey = new_storey.Resolve(ec);
                    if (new_storey != null)
                    {
                        new_storey = Convert.ImplicitConversionRequired(ec, new_storey, host_method.MemberType, loc);
                    }

                    var t = ec.Module.PredefinedTypes.Interlocked.Resolve(loc);

                    if (t != null)
                    {
                        var p = new ParametersImported(
                            new[] {
                            new ParameterData(null, Parameter.Modifier.REF),
                            new ParameterData(null, Parameter.Modifier.NONE),
                            new ParameterData(null, Parameter.Modifier.NONE)
                        },
                            new[] {
                            TypeManager.int32_type, TypeManager.int32_type, TypeManager.int32_type
                        },
                            false);
                        var f = new MemberFilter("CompareExchange", 0, MemberKind.Method, p, TypeManager.int32_type);
                        TypeManager.int_interlocked_compare_exchange = TypeManager.GetPredefinedMethod(t, f, loc);
                    }

                    ec.CurrentBranching.CurrentUsageVector.Goto();
                    return(true);
                }
Exemplo n.º 33
0
        protected override Expression DoResolve(ResolveContext rc)
        {
            var sn = expr as SimpleName;
            const ResolveFlags flags = ResolveFlags.VariableOrValue | ResolveFlags.Type;

            //
            // Resolve the expression with flow analysis turned off, we'll do the definite
            // assignment checks later.  This is because we don't know yet what the expression
            // will resolve to - it may resolve to a FieldExpr and in this case we must do the
            // definite assignment check on the actual field and not on the whole struct.
            //
            using (rc.Set(ResolveContext.Options.OmitStructFlowAnalysis)) {
                if (sn != null)
                {
                    expr = sn.LookupNameExpression(rc, MemberLookupRestrictions.ReadAccess | MemberLookupRestrictions.ExactArity);

                    //
                    // Resolve expression which does have type set as we need expression type
                    // with disable flow analysis as we don't know whether left side expression
                    // is used as variable or type
                    //
                    if (expr is VariableReference || expr is ConstantExpr || expr is Linq.TransparentMemberAccess)
                    {
                        using (rc.With(ResolveContext.Options.DoFlowAnalysis, false)) {
                            expr = expr.Resolve(rc);
                        }
                    }
                    else if (expr is TypeParameterExpr)
                    {
                        expr.Error_UnexpectedKind(rc, flags, sn.Location);
                        expr = null;
                    }
                }
                else
                {
                    expr = expr.Resolve(rc, flags);
                }
            }

            if (expr == null)
            {
                return(null);
            }

            TypeSpec expr_type = expr.Type;

            if (expr_type.IsPointer || expr_type.Kind == MemberKind.Void || expr_type == InternalType.NullLiteral || expr_type == InternalType.AnonymousMethod)
            {
                expr.Error_OperatorCannotBeApplied(rc, loc, ".", expr_type);
                return(null);
            }

            if (targs != null)
            {
                if (!targs.Resolve(rc))
                {
                    return(null);
                }
            }

            var results = new List <string> ();

            if (expr is Namespace)
            {
                Namespace nexpr = expr as Namespace;
                string    namespaced_partial;

                if (partial_name == null)
                {
                    namespaced_partial = nexpr.Name;
                }
                else
                {
                    namespaced_partial = nexpr.Name + "." + partial_name;
                }

                rc.CurrentMemberDefinition.GetCompletionStartingWith(namespaced_partial, results);
                if (partial_name != null)
                {
                    results = results.Select(l => l.Substring(partial_name.Length)).ToList();
                }
            }
            else
            {
                var r = MemberCache.GetCompletitionMembers(rc, expr_type, partial_name).Select(l => l.Name);
                AppendResults(results, partial_name, r);
            }

            throw new CompletionResult(partial_name == null ? "" : partial_name, results.Distinct().ToArray());
        }
Exemplo n.º 34
0
		protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
		{
			initializer = initializer.Resolve (bc);
			if (initializer == null)
				return null;

			var c = initializer as Constant;
			if (c == null) {
				initializer.Error_ExpressionMustBeConstant (bc, initializer.Location, li.Name);
				return null;
			}

			c = c.ConvertImplicitly (bc, li.Type);
			if (c == null) {
				if (TypeManager.IsReferenceType (li.Type))
					initializer.Error_ConstantCanBeInitializedWithNullOnly (bc, li.Type, initializer.Location, li.Name);
				else
					initializer.Error_ValueCannotBeConverted (bc, initializer.Location, li.Type, false);

				return null;
			}

			li.ConstantValue = c;
			return initializer;
		}
Exemplo n.º 35
0
		public override Expression DoResolve (ResolveContext ec)
		{
			if (left == null)
				return null;

			if ((oper == Operator.Subtraction) && (left is ParenthesizedExpression)) {
				left = ((ParenthesizedExpression) left).Expr;
				left = left.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.Type);
				if (left == null)
					return null;

				if (left.eclass == ExprClass.Type) {
					ec.Report.Error (75, loc, "To cast a negative value, you must enclose the value in parentheses");
					return null;
				}
			} else
				left = left.Resolve (ec);

			if (left == null)
				return null;

			Constant lc = left as Constant;

			if (lc != null && lc.Type == TypeManager.bool_type &&
				((oper == Operator.LogicalAnd && lc.IsDefaultValue) ||
				 (oper == Operator.LogicalOr && !lc.IsDefaultValue))) {

				// FIXME: resolve right expression as unreachable
				// right.Resolve (ec);

				ec.Report.Warning (429, 4, loc, "Unreachable expression code detected");
				return left;
			}

			right = right.Resolve (ec);
			if (right == null)
				return null;

			eclass = ExprClass.Value;
			Constant rc = right as Constant;

			// The conversion rules are ignored in enum context but why
			if (!ec.HasSet (ResolveContext.Options.EnumScope) && lc != null && rc != null && (TypeManager.IsEnumType (left.Type) || TypeManager.IsEnumType (right.Type))) {
				lc = EnumLiftUp (ec, lc, rc, loc);
				if (lc != null)
					rc = EnumLiftUp (ec, rc, lc, loc);
			}

			if (rc != null && lc != null) {
				int prev_e = ec.Report.Errors;
				Expression e = ConstantFold.BinaryFold (
					ec, oper, lc, rc, loc);
				if (e != null || ec.Report.Errors != prev_e)
					return e;
			} else if ((oper == Operator.BitwiseAnd || oper == Operator.LogicalAnd) && !TypeManager.IsDynamicType (left.Type) &&
					((lc != null && lc.IsDefaultValue && !(lc is NullLiteral)) || (rc != null && rc.IsDefaultValue && !(rc is NullLiteral)))) {

				if ((ResolveOperator (ec)) == null) {
					Error_OperatorCannotBeApplied (ec, left, right);
					return null;
				}

				//
				// The result is a constant with side-effect
				//
				Constant side_effect = rc == null ?
					new SideEffectConstant (lc, right, loc) :
					new SideEffectConstant (rc, left, loc);

				return ReducedExpression.Create (side_effect, this);
			}

			// Comparison warnings
			if ((oper & Operator.ComparisonMask) != 0) {
				if (left.Equals (right)) {
					ec.Report.Warning (1718, 3, loc, "A comparison made to same variable. Did you mean to compare something else?");
				}
				CheckUselessComparison (ec, lc, right.Type);
				CheckUselessComparison (ec, rc, left.Type);
			}

			if (TypeManager.IsDynamicType (left.Type) || TypeManager.IsDynamicType (right.Type)) {
				Arguments args = new Arguments (2);
				args.Add (new Argument (left));
				args.Add (new Argument (right));
				return new DynamicExpressionStatement (this, args, loc).Resolve (ec);
			}

			if (RootContext.Version >= LanguageVersion.ISO_2 &&
				((TypeManager.IsNullableType (left.Type) && (right is NullLiteral || TypeManager.IsNullableType (right.Type) || TypeManager.IsValueType (right.Type))) ||
				(TypeManager.IsValueType (left.Type) && right is NullLiteral) ||
				(TypeManager.IsNullableType (right.Type) && (left is NullLiteral || TypeManager.IsNullableType (left.Type) || TypeManager.IsValueType (left.Type))) ||
				(TypeManager.IsValueType (right.Type) && left is NullLiteral)))
				return new Nullable.LiftedBinaryOperator (oper, left, right, loc).Resolve (ec);

			return DoResolveCore (ec, left, right);
		}
Exemplo n.º 36
0
			protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
			{
				Assign assign;
				if (li.Type == InternalType.Dynamic) {
					initializer = initializer.Resolve (bc);
					if (initializer == null)
						return null;

					initializer = Convert.ImplicitConversionRequired (bc, initializer, TypeManager.idisposable_type, loc);
					if (initializer == null)
						return null;

					var var = LocalVariable.CreateCompilerGenerated (TypeManager.idisposable_type, bc.CurrentBlock, loc);
					assign = new SimpleAssign (var.CreateReferenceExpression (bc, loc), initializer, loc);
					assign.ResolveStatement (bc);

					dispose_call = CreateDisposeCall (bc, var);
					dispose_call.Resolve (bc);

					return assign;
				}

				if (li == Variable) {
					CheckIDiposableConversion (bc, li, initializer);
					dispose_call = CreateDisposeCall (bc, li);
					dispose_call.Resolve (bc);
				}

				return base.ResolveInitializer (bc, li, initializer);
			}
Exemplo n.º 37
0
		protected virtual Expression ResolveArrayElement (ResolveContext ec, Expression element)
		{
			element = element.Resolve (ec);
			if (element == null)
				return null;

			if (element is CompoundAssign.TargetExpression) {
				if (first_emit != null)
					throw new InternalErrorException ("Can only handle one mutator at a time");
				first_emit = element;
				element = first_emit_temp = new LocalTemporary (element.Type);
			}

			return Convert.ImplicitConversionRequired (
				ec, element, array_element_type, loc);
		}
Exemplo n.º 38
0
        protected override Expression DoResolve(ResolveContext ec)
        {
            if (ec.Target == Target.JavaScript)
            {
                type   = ec.BuiltinTypes.Dynamic;
                eclass = ExprClass.Value;
                return(this);
            }

            if (Expr is ElementAccess)
            {
                var elem_access = Expr as ElementAccess;

                if (elem_access.Arguments.Count != 1)
                {
                    ec.Report.Error(7021, loc, "delete statement must have only one index argument.");
                    return(null);
                }

                var expr = elem_access.Expr.Resolve(ec);
                if (expr.Type == null)
                {
                    return(null);
                }

                if (expr.Type.IsArray)
                {
                    ec.Report.Error(7021, loc, "delete statement not allowed on arrays.");
                    return(null);
                }

                if (ec.Target == Target.JavaScript)
                {
                    Expr = Expr.Resolve(ec);
                    return(this);
                }

                removeExpr = new Invocation(new MemberAccess(expr, "Remove", loc), elem_access.Arguments);
                return(removeExpr.Resolve(ec));
            }
            else if (Expr is MemberAccess)
            {
                if (ec.Target == Target.JavaScript)
                {
                    Expr = Expr.Resolve(ec);
                    return(this);
                }

                var memb_access = Expr as MemberAccess;

                var expr = memb_access.LeftExpression.Resolve(ec);
                if (expr.Type == null)
                {
                    return(null);
                }

                var args = new Arguments(1);
                args.Add(new Argument(new StringLiteral(ec.BuiltinTypes, memb_access.Name, loc)));
                removeExpr = new Invocation(new MemberAccess(expr, "Remove", loc), args);
                return(removeExpr.Resolve(ec));
            }
            else
            {
                // Error is reported elsewhere.
                return(null);
            }
        }
Exemplo n.º 39
0
		protected override Expression ResolveArrayElement (ResolveContext ec, Expression element)
		{
			element = element.Resolve (ec);
			if (element == null)
				return null;
			
			if (array_element_type == null) {
				if (element.Type != TypeManager.null_type)
					array_element_type = element.Type;

				return element;
			}

			if (Convert.ImplicitConversionExists (ec, element, array_element_type)) {
				return element;
			}

			if (Convert.ImplicitConversionExists (ec, new TypeExpression (array_element_type, loc), element.Type)) {
				array_element_type = element.Type;
				return element;
			}

			Error_NoBestType (ec);
			return null;
		}