Пример #1
0
 private void GenerateNewArray(NewArray newArrayNode, ILGenerator ilGenerator)
 {
     //load arr size onto stack
     GenerateExpression(newArrayNode.ArraySize, ilGenerator);
     //new array
     ilGenerator.Emit(OpCodes.Newarr, newArrayNode.ReturnType.ConvertToType(false));
 }
Пример #2
0
            protected internal override void VisitNewArray(NewArray node, object data)
            {
                StackTypes stack = data as StackTypes;

                Verifier.ProcessNewArr(stack, node.Type);
                AddTask(node.Next, stack);
            }
        public SemanticAtom Visit(NewArray n)
        {
            var t = new UtilizedType(Primitive.IntArray.Name, n.Location);

            AddToGlobalUtilization(t, null);
            return(null);
        }
Пример #4
0
 public void Visit(NewArray n)
 {
     Helpers.WriteColor("new int ", ConsoleColor.DarkCyan, ConsoleColor.Black);
     Helpers.Write("[");
     n.Size.Accept(this);
     Helpers.Write("]");
 }
        public void GivenNewArrayExpressionWhenNewArrayCreatedThenShouldInitializeExpressionsList()
        {
            var expr   = Expression.NewArrayInit(typeof(int), Expression.Constant(1), Expression.Constant(2));
            var target = new NewArray(expr);

            Assert.NotNull(target.Expressions);
        }
        public void GivenNewArrayExpressionWhenNewArrayCreatedThenShouldSetArrayType()
        {
            var expr   = Expression.NewArrayInit(typeof(int), Expression.Constant(1), Expression.Constant(2));
            var target = new NewArray(expr);

            Assert.Equal(expr.Type.GetElementType(), TestSerializer.MemberAdapter.GetMemberForKey <Type>(target.ArrayTypeKey));
        }
Пример #7
0
        public override AstNode VisitNewArray(NewArray ast)
        {
            Visit(ast.Length);

            var elementType = typeof(int);

            m_ilgen.Emit(OpCodes.Newarr, elementType);

            return(ast);
        }
Пример #8
0
 public void WriteNewArray(NewArray s, ExpressionUsage u)
 {
     if (s.Initializers != null)
     {
         WriteNewArray(s.Source, s.ArrayType, s.Initializers, u);
     }
     else
     {
         WriteNewArray(s.Source, s.ArrayType, s.Size, u);
     }
 }
Пример #9
0
        public void Visit(NewArray n)
        {
            Helpers.WriteLine($"{_tab}{n.Text} [{n.Location.StartLine}, {n.Location.StartColumn}]");
            Tab();

            Helpers.WriteLine($"{_tab}Size");
            Tab();
            n.Size.Accept(this);
            Untab();

            Untab();
        }
Пример #10
0
        public override AstNode VisitNewArray(NewArray ast)
        {
            Visit(ast.Length);

            if (ast.Length.ExpressionType != PrimaryType.Int)
            {
                AddError(c_SE_InvalidCast, ast.LengthSpan, ast.Length.ExpressionType.Name, PrimaryType.Int.Name);
            }

            ast.ExpressionType = ArrayType.IntArray;

            return(ast);
        }
        private static IEnumerable <IInstruction> GetNewArrayInstructions(this NewArray newArray)
        {
            JasminTypeArgumentInstruction arrayCreationInstruction = newArray.InnerElementsReturnType.IsPrimitiveType()
                ? (JasminTypeArgumentInstruction)Instructions.NewArrayInstruction
                : Instructions.ANewArrayInstruction;

            List <IInstruction> instructions = new List <IInstruction>();

            instructions.AddRange(newArray.ArraySize.GetInstructions());

            instructions.Add(
                arrayCreationInstruction.WithType(newArray.InnerElementsReturnType.ConvertToKeywordRepresentation()));
            return(instructions);
        }
Пример #12
0
        public override Type visitNewArray(NewArray newArray, Environment env)
        {
            Type      elemType  = scan(newArray.elemenTypeTree, env);
            ArrayType arrayType = symtab.arrayTypeOf(elemType);

            newArray.type = arrayType;

            Type lenType = analyzeExpr(newArray.length, env);

            if (!lenType.IsIntegral || lenType.Tag == TypeTag.LONG)
            {
                log.error(newArray.Pos, messages.arrayLengthType);
            }

            return(arrayType);
        }
Пример #13
0
        public void AddItem(int item)
        {
            if (Counter >= this.NewArray.Length)
            {
                // we need to double to make bigger.
                SizeOfArray *= 2;
                int[] temp = new int[SizeOfArray];
                NewArray.CopyTo(temp, 0);
                NewArray = temp;
            }
            NewArray[Counter] = item;

            BubbleUp(Counter);

            Counter++;
        }
Пример #14
0
        public void Visit(NewArray n)
        {
            Globals.Builder.Start($"new int[] [{n.Location.StartLine}, {n.Location.StartColumn}]");

            n.Size.Accept(this);

            // rax has the size, add one to it so there is a slot for size.
            Globals.Builder.WriteUnaryOp("push", "rax");
            Globals.Builder.WriteBinaryOp("add", "rax", 1.ToString());

            Globals.Builder.AllocateMemory("rax", 8.ToString(), n.Location);

            // Move the size into the first slot.
            Globals.Builder.WriteUnaryOp("pop", "r10");
            Globals.Builder.WriteBinaryOp("mov", "[rax]", "r10");

            Globals.Builder.End($"new int[] [{n.Location.EndLine}, {n.Location.EndColumn}]");
        }
Пример #15
0
        protected override void VisitNewArray(NewArray downNode, object o)
        {
            PointerToNode        ptrUpNode = (o as Data).PointerToNode;
            StructValue          idx       = this.state.Stack.Pop() as StructValue;
            Array                arr       = Array.CreateInstance(downNode.Type, SpecializingVisitor.toInt(idx));
            ObjectReferenceValue obj       = new ObjectReferenceValue(arr);

            if (Annotation.GetArrayElementsBTType(downNode) == BTType.Dynamic)
            {
                for (int i = 0; i < SpecializingVisitor.toInt(idx); i++)
                {
                    Variable varUp = this.mbbUp.Variables.CreateVar(downNode.Type, VariableKind.Local);
                    this.varsHash[new PointerToElementValue(arr, i)] = varUp;
                    ptrUpNode = SpecializingVisitor.initVariable(varUp, ptrUpNode);
                }
            }

            this.state.Stack.Push(obj);
            this.AddTask(downNode.Next, ptrUpNode);
        }
Пример #16
0
        private static void Process(this NewArray newArray)
        {
            if (newArray.ArraySize != null && newArray.InitializationParameters.Count > 0)
            {
                throw new ScopeException("You can't specify array size and include initialization parameters");
            }
            if (newArray.ArraySize == null && newArray.InitializationParameters.Count == 0)
            {
                throw new ScopeException("You must specify array size");
            }
            if (newArray.ArraySize != null)
            {
                newArray.ArraySize.Process();
                if (newArray.ArraySize.ReturnType != ReturnType.Int)
                {
                    throw new ScopeException(
                              $"Array size must be of {ReturnType.Int} type, but {newArray.ArraySize.ReturnType} is specified");
                }
            }
            var arrayInnerType = newArray.ReturnType.CastTo <ArrayReturnType>()
                                 .InnerType;

            newArray.InitializationParameters.ForEach(expression =>
            {
                expression.Process();
                if (expression.ReturnType != arrayInnerType)
                {
                    if (expression.ReturnType.IsCastableTo(arrayInnerType))
                    {
                        expression.CastToType = arrayInnerType;
                    }
                    else
                    {
                        throw new ScopeException(
                            $"Initialization parameter must be of type {arrayInnerType}, but received {expression.ReturnType}");
                    }
                }
            });
        }
Пример #17
0
        public ClassDeclarationSyntax GenerateServiceClass(SourceFileContext ctx)
        {
            var cls = Class(Modifier.Public, ServiceTyp, ctx.Type <BaseClientService>()).WithXmlDoc(XmlDoc.Summary($"The {ClassName} Service."));

            using (ctx.InClass(cls))
            {
                var discoveryVersionTyp = Typ.Manual("Google.Apis.Discovery", "DiscoveryVersion");
                var version             = Field(Modifier.Public | Modifier.Const, ctx.Type <string>(), "Version")
                                          .WithInitializer(ApiVersion)
                                          .WithXmlDoc(XmlDoc.Summary("The API version."));
                var discoveryVersion = Field(Modifier.Public | Modifier.Static, ctx.Type(discoveryVersionTyp), "DiscoveryVersionUsed")
                                       .WithInitializer(ctx.Type(discoveryVersionTyp).Access(nameof(DiscoveryVersion.Version_1_0)))
                                       .WithXmlDoc(XmlDoc.Summary("The discovery version used to generate this service."));

                var parameterlessCtor = Ctor(Modifier.Public, cls, ThisInitializer(New(ctx.Type <BaseClientService.Initializer>())()))()
                                        .WithBody()
                                        .WithXmlDoc(XmlDoc.Summary("Constructs a new service."));

                var initializerParam = Parameter(ctx.Type <BaseClientService.Initializer>(), "initializer");

                var featuresArrayInitializer = ApiFeatures.Any()
                    ? NewArray(ctx.ArrayType(Typ.Of <string[]>()))(ApiFeatures.ToArray())
                    : NewArray(ctx.ArrayType(Typ.Of <string[]>()), LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)));
                var features = Property(Modifier.Public | Modifier.Override, ctx.Type <IList <string> >(), "Features")
                               .WithGetBody(featuresArrayInitializer)
                               .WithXmlDoc(XmlDoc.Summary("Gets the service supported features."));

                var nameProperty = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "Name")
                                   .WithGetBody(ApiName)
                                   .WithXmlDoc(XmlDoc.Summary("Gets the service name."));

                // Note: the following 4 properties have special handling post-generation, in terms
                // of adding the #if directives in.
                var baseUri = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BaseUri")
                              .WithGetBody(IdentifierName("BaseUriOverride").NullCoalesce(BaseUri))
                              .WithXmlDoc(XmlDoc.Summary("Gets the service base URI."));

                var basePath = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BasePath")
                               .WithGetBody(BasePath)
                               .WithXmlDoc(XmlDoc.Summary("Gets the service base path."));

                var batchUri = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BatchUri")
                               .WithGetBody(BatchUri)
                               .WithXmlDoc(XmlDoc.Summary("Gets the batch base URI; ", XmlDoc.C("null"), " if unspecified."));
                var batchPath = Property(Modifier.Public | Modifier.Override, ctx.Type <string>(), "BatchPath")
                                .WithGetBody(BatchPath)
                                .WithXmlDoc(XmlDoc.Summary("Gets the batch base path; ", XmlDoc.C("null"), " if unspecified."));

                var resourceProperties = Resources.Select(resource => resource.GenerateProperty(ctx)).ToArray();

                var parameterizedCtor = Ctor(Modifier.Public, cls, BaseInitializer(initializerParam))(initializerParam)
                                        .WithBlockBody(resourceProperties.Zip(Resources).Select(pair => pair.First.Assign(New(ctx.Type(pair.Second.Typ))(This))).ToArray())
                                        .WithXmlDoc(
                    XmlDoc.Summary("Constructs a new service."),
                    XmlDoc.Param(initializerParam, "The service initializer."));

                cls = cls.AddMembers(version, discoveryVersion, parameterlessCtor, parameterizedCtor, features, nameProperty, baseUri, basePath, batchUri, batchPath);

                if (AuthScopes.Any())
                {
                    var scopeClass = Class(Modifier.Public, Typ.Manual(PackageName, "Scope"))
                                     .WithXmlDoc(XmlDoc.Summary($"Available OAuth 2.0 scopes for use with the {Title}."));
                    using (ctx.InClass(scopeClass))
                    {
                        foreach (var scope in AuthScopes)
                        {
                            var field = Field(Modifier.Public | Modifier.Static, ctx.Type <string>(), scope.Name)
                                        .WithInitializer(scope.Value)
                                        .WithXmlDoc(XmlDoc.Summary(scope.Description));
                            scopeClass = scopeClass.AddMembers(field);
                        }
                    }

                    var scopeConstantsClass = Class(Modifier.Public | Modifier.Static, Typ.Manual(PackageName, "ScopeConstants"))
                                              .WithXmlDoc(XmlDoc.Summary($"Available OAuth 2.0 scope constants for use with the {Title}."));
                    using (ctx.InClass(scopeConstantsClass))
                    {
                        foreach (var scope in AuthScopes)
                        {
                            var field = Field(Modifier.Public | Modifier.Const, ctx.Type <string>(), scope.Name)
                                        .WithInitializer(scope.Value)
                                        .WithXmlDoc(XmlDoc.Summary(scope.Description));
                            scopeConstantsClass = scopeConstantsClass.AddMembers(field);
                        }
                    }

                    cls = cls.AddMembers(scopeClass, scopeConstantsClass);
                }

                // TODO: Find an example of this...
                foreach (var method in Methods)
                {
                    cls = cls.AddMembers(method.GenerateDeclarations(ctx).ToArray());
                }

                cls = cls.AddMembers(resourceProperties);
            }
            return(cls);
        }
Пример #18
0
        public override AstNode VisitNewArray(NewArray ast)
        {
            Visit(ast.Length);

            if (ast.Length.ExpressionType != PrimaryType.Int)
            {
                m_errorManager.AddError(c_SE_InvalidCast, ast.LengthSpan, ast.Length.ExpressionType.Name, PrimaryType.Int.Name);
            }

            ast.ExpressionType = ArrayType.IntArray;

            return ast;
        }
Пример #19
0
        /// <summary>
        /// Lowers new array values into static allocation instances and structures.
        /// </summary>
        private static void Lower(
            RewriterContext context,
            TypeLowering <ArrayType> typeLowering,
            NewArray value)
        {
            var builder            = context.Builder;
            var location           = value.Location;
            var targetAddressSpace = (typeLowering as ArrayTypeLowering)
                                     .TargetAddressSpace;

            // Compute array length
            Value totalLength = builder.CreatePrimitiveValue(location, 1);

            foreach (Value length in value)
            {
                totalLength = builder.CreateArithmetic(
                    location,
                    totalLength,
                    length,
                    BinaryArithmeticKind.Mul);
            }

            // Check for a compile-time known constant
            if (!(totalLength is PrimitiveValue primitiveLength) ||
                primitiveLength.Int32Value < 0)
            {
                throw location.GetNotSupportedException(
                          ErrorMessages.NotSupportNonConstArrayDimension,
                          totalLength.ToString());
            }

            // Create array structure.
            var arrayType = typeLowering
                            .ConvertType(value.Type)
                            .As <StructureType>(location);
            var   result = builder.CreateStructure(location, arrayType);
            Value view;

            // Check for empty array allocations
            if (primitiveLength.HasIntValue(0))
            {
                // Create an empty view.
                view = builder.CreateNewView(
                    location,
                    builder.CreateNull(
                        location,
                        builder.CreatePointerType(
                            value.ElementType,
                            targetAddressSpace)),
                    primitiveLength);
                result.Add(view);

                // Insert a dimension length of 0 in each dimension
                for (int i = 0, e = value.Count; i < e; ++i)
                {
                    result.Add(primitiveLength);
                }
            }
            else
            {
                // Create the allocation and the base view
                var allocation = builder.CreateStaticAllocaArray(
                    location,
                    totalLength,
                    value.ElementType,
                    targetAddressSpace);
                view = builder.CreateNewView(location, allocation, totalLength);
                result.Add(view);

                // Insert dimension information for each array rank
                foreach (Value length in value)
                {
                    result.Add(length);
                }
            }

            // Clear all array elements using explicit stores. We emit the code in
            // the form of an unrolled loop to avoid additional loops from being
            // generated.
            // TODO: replace this loop with a high-level memset operation later on
            var defaultElement = builder.CreateNull(location, value.Type.ElementType);

            for (int i = 0, e = primitiveLength.Int32Value; i < e; ++i)
            {
                var address = builder.CreateLoadElementAddress(
                    location,
                    view,
                    builder.CreatePrimitiveValue(location, i));
                builder.CreateStore(location, address, defaultElement);
            }

            // Replace the current value with a new structure instance
            context.ReplaceAndRemove(value, result.Seal());
        }
Пример #20
0
        public static MethodBodyBlock Convert(MethodEx method)
        {
            if (!method.IsVerified)
            {
                throw new ConvertionException();
            }
            MethodInfoExtention _method_  = new MethodInfoExtention(method.Method);
            MethodBodyBlock     mainBlock = new MethodBodyBlock(_method_.GetReturnType().type);

            mainBlock.Options["StackTypes"] = new StackTypes();
            Block currentBlock = mainBlock;

            Node[] heads = new Node[method.Count];
            Node[] tails = new Node[method.Count];
            Node   head = null;
            Node   tail = null;
            Node   firstBlock = null;
            Node   lastBlock = null;
            int    iNum, iNumNext;

            Variable[]    locals        = new Variable[method.Locals.Count];
            Variable[]    args          = new Variable[_method_.ArgCount];
            VariablesList methodVarList = mainBlock.Variables;

            for (int i = 0; i < args.Length; i++)
            {
                args[i]      = methodVarList.CreateVar(_method_.GetArgType(i).type, VariableKind.Parameter);
                args[i].Name = "Arg" + i;
//				methodVarList.Add(args[i]);
            }
            for (int i = 0; i < locals.Length; i++)
            {
                locals[i]      = methodVarList.CreateVar(method.Locals[i], VariableKind.Local);
                locals[i].Name = "Loc" + i;
//				methodVarList.Add(locals[i]);
            }

            BlockType nextBlockType;
            int       nextBlockStart = -1;
            int       nextBlockEnd   = 1 << 30;
            int       nextBlockIndex;
            Type      nextCatchBlockType;
            Hashtable tryBlocks    = new Hashtable();
            Hashtable filterBlocks = new Hashtable();
            Stack     blockEnds    = new Stack();

            blockEnds.Push(method.Count);
            FindNextBlockStart(method.EHClauses, out nextBlockType, ref nextBlockStart, ref nextBlockEnd, out nextCatchBlockType, out nextBlockIndex);

            //Nodes and blocks creation, blocks linkage
            for (iNum = 0; iNum < method.Count; iNum++)
            {
                while (iNum == (int)blockEnds.Peek())
                {
                    currentBlock = currentBlock.Parent;
                    blockEnds.Pop();
                }

                firstBlock = null;
                lastBlock  = null;
                Node thisBlock = null;
                while (iNum == nextBlockStart)
                {
                    Block currentBlockOld = currentBlock;

                    switch (nextBlockType)
                    {
                    case BlockType.Try:
                        currentBlock = new ProtectedBlock();
                        break;

                    case BlockType.Catch:
                        currentBlock = new CatchBlock(nextCatchBlockType);
                        break;

                    case BlockType.Finally:
                        currentBlock = new FinallyBlock(false);
                        break;

                    case BlockType.Filter:
                        currentBlock = new FilterBlock();
                        break;

                    case BlockType.FilteredCatch:
                        currentBlock = new UserFilteredBlock();
                        break;
                    }

                    currentBlock.setParent(currentBlockOld);

                    blockEnds.Push(nextBlockEnd);
                    if (thisBlock == null)
                    {
                        thisBlock = firstBlock = currentBlock;
                    }
                    else
                    {
                        thisBlock.Next = currentBlock;
                        thisBlock      = currentBlock;
                    }
                    switch (nextBlockType)
                    {
                    case BlockType.Try:
                        tryBlocks.Add(new Segment(nextBlockStart, nextBlockEnd), thisBlock);
                        break;

                    case BlockType.Filter:
                        filterBlocks.Add(new Segment(nextBlockStart, nextBlockEnd), thisBlock);
                        break;

                    case BlockType.Finally:
                    case BlockType.Catch:
                    {
                        Segment        tryBlockKey = FindProtectedBlock(method.EHClauses, nextBlockIndex);
                        ProtectedBlock tryBlock    = tryBlocks[tryBlockKey] as ProtectedBlock;
                        tryBlock.AddHandler(thisBlock as EHBlock);
                    }       break;

                    case BlockType.FilteredCatch:
                    {
                        Segment        tryBlockKey = FindProtectedBlock(method.EHClauses, nextBlockIndex);
                        ProtectedBlock tryBlock    = tryBlocks[tryBlockKey] as ProtectedBlock;
                        tryBlock.AddHandler(thisBlock as EHBlock);

                        Segment     filterKey   = FindFilterBlock(method.EHClauses, nextBlockIndex);
                        FilterBlock filterBlock = filterBlocks[filterKey] as FilterBlock;
                        (thisBlock as UserFilteredBlock).Filter = filterBlock;
                    }       break;
                    }
                    FindNextBlockStart(method.EHClauses, out nextBlockType, ref nextBlockStart, ref nextBlockEnd, out nextCatchBlockType, out nextBlockIndex);
                }
                lastBlock = thisBlock;

                Instruction i = method[iNum];
                switch (i.Code)
                {
                case InstructionCode.NEG:
                case InstructionCode.NOT:
                {
                    head = tail = new UnaryOp(UnaryOpFromCode(i.Code));
                    /*!*/ head.setParent(currentBlock);
                } break;

                case InstructionCode.ADD:
                case InstructionCode.AND:
                case InstructionCode.CEQ:
                case InstructionCode.CGT:
                case InstructionCode.CLT:
                case InstructionCode.DIV:
                case InstructionCode.MUL:
                case InstructionCode.OR:
                case InstructionCode.REM:
                case InstructionCode.SHL:
                case InstructionCode.SHR:
                case InstructionCode.SUB:
                case InstructionCode.XOR:
                {
                    head = tail = new BinaryOp(BinaryOpFromCode(i.Code), i.OverflowFlag, i.UnsignedFlag);
                    /*!*/ head.setParent(currentBlock);
                } break;

                case InstructionCode.LDC:
                    head = tail = new LoadConst(i.Param);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDARG:
                    head = tail = new LoadVar(args[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDLOC:
                    head = tail = new LoadVar(locals[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDARGA:
                    head = tail = new LoadVarAddr(args[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDLOCA:
                    head = tail = new LoadVarAddr(locals[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDIND:
                    head = tail = new LoadIndirect(i.TypeBySuffixOrParam());
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDFLD:
                {
                    FieldInfo field = i.Param as FieldInfo;
                    if (field.IsStatic)
                    {
                        head = new RemoveStackTop();
                        /*!*/ head.setParent(currentBlock);
                        //remove the object instance when accessing the static field with LDFLD
                        tail = new LoadField(field);
                        /*!*/ tail.setParent(currentBlock);
                        head.Next = tail;
                    }
                    else
                    {
                        head = tail = new LoadField(field);
                        /*!*/ head.setParent(currentBlock);
                    }
                }       break;

                case InstructionCode.LDFLDA:
                {
                    FieldInfo field = i.Param as FieldInfo;
                    if (field.IsStatic)
                    {
                        head = new RemoveStackTop();
                        /*!*/ head.setParent(currentBlock);
                        tail = new LoadFieldAddr(field);
                        /*!*/ tail.setParent(currentBlock);
                        head.Next = tail;
                    }
                    else
                    {
                        head = tail = new LoadFieldAddr(field);
                        /*!*/ head.setParent(currentBlock);
                    }
                }       break;

                case InstructionCode.LDSFLD:
                    head = tail = new LoadField(i.Param as FieldInfo);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDSFLDA:
                    head = tail = new LoadFieldAddr(i.Param as FieldInfo);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDELEM:
                    head = tail = new LoadElement(i.TypeBySuffixOrParam());
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDELEMA:
                    head = tail = new LoadElementAddr(i.TypeBySuffixOrParam());
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDOBJ:
                    head = tail = new LoadIndirect(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.SIZEOF:
                    head = tail = new LoadSizeOfValue(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDLEN:
                    head = tail = new LoadLength();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDTOKEN:
                    if (i.Param is Type)
                    {
                        head = tail = new LoadConst((i.Param as Type).TypeHandle);
                    }
                    else if (i.Param is MethodBase)
                    {
                        head = tail = new LoadConst((i.Param as MethodBase).MethodHandle);
                    }
                    else if (i.Param is FieldInfo)
                    {
                        head = tail = new LoadConst((i.Param as FieldInfo).FieldHandle);
                    }
                    else
                    {
                        throw new ConvertionException();
                    }
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDNULL:
                    head = tail = new LoadConst(null);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.LDSTR:
                    head = tail = new LoadConst(i.Param);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STARG:
                    head = tail = new StoreVar(args[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STLOC:
                    head = tail = new StoreVar(locals[(int)(i.Param)]);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STIND:
                    head = tail = new StoreIndirect(i.TypeBySuffixOrParam());
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STFLD:
                {
                    FieldInfo field = i.Param as FieldInfo;
                    if (field.IsStatic)
                    {
                        head = new StoreField(field);
                        /*!*/ head.setParent(currentBlock);
                        tail = new RemoveStackTop();
                        /*!*/ tail.setParent(currentBlock);
                        head.Next = tail;
                    }
                    else
                    {
                        head = tail = new StoreField(i.Param as FieldInfo);
                        /*!*/ head.setParent(currentBlock);
                    }
                }       break;

                case InstructionCode.STSFLD:
                    head = tail = new StoreField(i.Param as FieldInfo);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STELEM:
                    head = tail = new StoreElement(i.TypeBySuffixOrParam());
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.STOBJ:
                    head = tail = new StoreIndirect(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.CPOBJ:
                    head = new LoadIndirect(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    tail = new StoreIndirect(i.Param as Type);
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.DUP:
                    head = tail = new DuplicateStackTop();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.CALL:
                    head = tail = new CallMethod(i.Param as MethodBase, false, i.HasTail);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.CALLVIRT:
                    MethodInfo callee = i.Param as MethodInfo;
                    head = tail = new CallMethod(callee, callee.IsVirtual, i.HasTail);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.NEWOBJ:
                { ConstructorInfo ctor = i.Param as ConstructorInfo;
                  if (Verifier.IsDelegate(ctor.DeclaringType))
                  {
                      if (Verifier.IsInstanceDispatch(method, iNum))
                      {
                          heads[iNum - 1] = tails[iNum - 1] = null;
                          head            = tail = new CreateDelegate(ctor, method[iNum - 1].Param as MethodInfo, false);
                      }
                      else if (Verifier.IsVirtualDispatch(method, iNum))
                      {
                          heads[iNum - 2] = tails[iNum - 2] = null;
                          heads[iNum - 1] = tails[iNum - 1] = null;
                          head            = tail = new CreateDelegate(ctor, method[iNum - 1].Param as MethodInfo, true);
                      }
                  }
                  else
                  {
                      head = tail = new NewObject(ctor);
                  }
                  /*!*/ head.setParent(currentBlock); }       break;

                case InstructionCode.NEWARR:
                    head = tail = new NewArray(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.INITOBJ:
                    head = tail = new InitValue(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.ISINST:
                    head = tail = new CastClass(i.Param as Type, false);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.CASTCLASS:
                    head = tail = new CastClass(i.Param as Type, true);
                    /*!*/ head.setParent(currentBlock);
                    break;


                case InstructionCode.BOX:
                    head = tail = new BoxValue(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.UNBOX:
                    head = tail = new UnboxValue(i.Param as Type);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.CONV:
                    head = tail = new ConvertValue(i.TypeBySuffixOrParam(), i.OverflowFlag, i.UnsignedFlag);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.POP:
                    head = tail = new RemoveStackTop();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.BEQ:
                    head = new BinaryOp(BinaryOp.ArithOp.CEQ, false, false);
                    /*!*/ head.setParent(currentBlock);
                    tail = new Branch();
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BNE:
                    head = new BinaryOp(BinaryOp.ArithOp.CEQ, false, false);
                    /*!*/ head.setParent(currentBlock);
                    tail = new Branch();
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BGE:
                    if (TypeFixer.IsFloatOrCompatible(i.Stack.Top()))
                    {
                        head = new BinaryOp(BinaryOp.ArithOp.CLT, false, !i.UnsignedFlag);
                    }
                    else
                    {
                        head = new BinaryOp(BinaryOp.ArithOp.CLT, false, i.UnsignedFlag);
                    }
                    tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BGT:
                    head = new BinaryOp(BinaryOp.ArithOp.CGT, false, i.UnsignedFlag);
                    tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BLE:
                    if (TypeFixer.IsFloatOrCompatible(i.Stack.Top()))
                    {
                        head = new BinaryOp(BinaryOp.ArithOp.CGT, false, !i.UnsignedFlag);
                    }
                    else
                    {
                        head = new BinaryOp(BinaryOp.ArithOp.CGT, false, i.UnsignedFlag);
                    }
                    tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BLT:
                    head = new BinaryOp(BinaryOp.ArithOp.CLT, false, i.UnsignedFlag);
                    tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    /*!*/ tail.setParent(currentBlock);
                    head.Next = tail;
                    break;

                case InstructionCode.BRTRUE:
                    head = tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.BRFALSE:
                    head = tail = new Branch();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.SWITCH:
                    head = tail = new Switch((i.Param as int[]).Length);
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.BR:
                case InstructionCode.NOP:
                case InstructionCode.BREAK:
                case InstructionCode.LDFTN:                             // Expecting further delegate construction...
                case InstructionCode.LDVIRTFTN:                         //
                    head = tail = new DummyNode();
                    /*!*/ head.setParent(currentBlock);
                    break;

                case InstructionCode.THROW:
                    head = tail = new ThrowException();
                    /*!*/ head.setParent(currentBlock);
                    break;


                case InstructionCode.RET:
                case InstructionCode.ENDFINALLY:
                case InstructionCode.ENDFILTER:
                case InstructionCode.LEAVE:
                    head = tail = new Leave();
                    /*!*/ head.setParent(currentBlock);
                    break;

                default:
                    throw new ConvertionException();
                }
                if (head != null)
                {
                    head.Options["StackTypes"] = i.Stack.Clone() as StackTypes;
                }
                if (head != tail)                //=>   head :: BinaryOp, tail :: Branch
                //||   head :: LoadIndirect, tail :: StoreIndirect
                {
                    if (head is BinaryOp && tail is Branch)
                    {
                        StackTypes stack = i.Stack.Clone() as StackTypes;
                        stack.Pop();
                        stack.Pop();
                        stack.Push(typeof(int));
                        tail.Options["StackTypes"] = stack;
                    }
                    else if (head is LoadIndirect && tail is StoreIndirect)
                    {
                        StackTypes stack = i.Stack.Clone() as StackTypes;
                        TypeEx     type  = stack.Pop();                    //type == S&
                        stack.Push(type.type.GetElementType());
                        tail.Options["StackTypes"] = stack;
                    }
                }
                if (firstBlock != null)
                {
                    lastBlock.Next = head;
                    for (Node n = firstBlock; n != head; n = n.Next)
                    {
                        n.Options["StackTypes"] = i.Stack.Clone() as StackTypes;
                    }
                    head = firstBlock;
                    if (tail == null)
                    {
                        tail = lastBlock;                         //This may occure what the NOP instruction starts some block
                    }
                }
                heads[iNum] = head;
                tails[iNum] = tail;
            }            //for
            mainBlock.Next = heads[0];
            //Control flow linkage
            for (iNum = 0; iNum < method.Count; iNum++)
            {
                if (heads[iNum] == null)
                {
                    throw new ConvertionException();                     //impossible :)
                }
                Instruction i = method[iNum];

                switch (i.Code)
                {
                case InstructionCode.BR:
                case InstructionCode.LEAVE:
                    tails[iNum].Next = heads[(int)i.Param];
                    break;

                case InstructionCode.RET:
                case InstructionCode.ENDFINALLY:
                case InstructionCode.ENDFILTER:
                case InstructionCode.THROW:
                case InstructionCode.RETHROW:
                    break;

                case InstructionCode.BRFALSE:                     //false
                case InstructionCode.BGE:                         //false
                case InstructionCode.BLE:                         //false
                case InstructionCode.BNE:                         //false
                    tails[iNum].Next            = heads[(int)i.Param];
                    (tails[iNum] as Branch).Alt = heads[iNum + 1];
                    break;

                case InstructionCode.BRTRUE:                      //true
                case InstructionCode.BEQ:                         //true
                case InstructionCode.BGT:                         //true
                case InstructionCode.BLT:                         //true
                    tails[iNum].Next            = heads[iNum + 1];
                    (tails[iNum] as Branch).Alt = heads[(int)i.Param];
                    break;

                case InstructionCode.SWITCH:
                    tails[iNum].Next = heads[iNum + 1];
                    Switch node = tails[iNum] as Switch;
                    int[]  alt  = i.Param as int[];
                    for (int j = 0; j < node.Count; j++)
                    {
                        node[j] = heads[alt[j]];
                    }
                    break;

                default:
                    tails[iNum].Next = heads[iNum + 1];
                    break;
                }
            }

            //Removing DummyNodes
            for (iNum = 0; iNum < method.Count; iNum++)
            {
                if (heads[iNum] is DummyNode)
                {
                    Node   dummy = heads[iNum];
                    Node[] prev  = new Node[dummy.PrevArray.Count];
                    for (int j = 0; j < prev.Length; j++)
                    {
                        prev[j] = dummy.PrevArray[j];
                    }
                    for (int j = 0; j < prev.Length; j++)
                    {
                        prev[j].NextArray[prev[j].NextArray.IndexOf(dummy)] = dummy.Next;
                    }
                    dummy.RemoveFromGraph();
                }
            }


            return(mainBlock);
        }
Пример #21
0
 public virtual T visitNewArray(NewArray newArray, A env) => visit(newArray, env);
            private IEnumerable <MethodDeclarationSyntax> ParseMethods()
            {
                var paramName            = _def.ResourceNameTyp.Name.ToLowerCamelCase();
                var name                 = Parameter(_ctx.Type <string>(), paramName);
                var allowUnparsed        = Parameter(_ctx.Type <bool>(), "allowUnparsed");
                var result               = Parameter(_ctx.Type(_def.ResourceNameTyp), "result").Out();
                var resultLocal          = Local(_ctx.Type(_def.ResourceNameTyp), "result");
                var resourceName         = Local(_ctx.Type <TemplatedResourceName>(), paramName == "resourceName" ? "resourceName2" : "resourceName");
                var unparsedResourceName = Local(_ctx.Type <UnparsedResourceName>(), "unparsedResourceName");
                MethodDeclarationSyntax parseSplitHelper;

                if (PatternDetails.SelectMany(x => x.PathSegments).Any(x => x.Segment.IsComplex))
                {
                    var s          = Parameter(_ctx.Type <string>(), "s");
                    var separators = Parameter(_ctx.ArrayType <char[]>(), "separators");
                    var i0         = Local(_ctx.Type <int>(), "i0");
                    var i1         = Local(_ctx.Type <int>(), "i1");
                    var i          = Local(_ctx.Type <int>(), "i");
                    var pshResult  = Local(_ctx.ArrayType <string[]>(), "result");
                    parseSplitHelper = Method(Private | Static, _ctx.ArrayType <string[]>(), "ParseSplitHelper")(s, separators)
                                       .WithBody(
                        pshResult.WithInitializer(NewArray(_ctx.ArrayType <string[]>(), separators.Access(nameof(Array.Length)).Plus(1))),
                        i0.WithInitializer(0),
                        For(i.WithInitializer(0), i.LessThanOrEqual(separators.Access(nameof(Array.Length))), i.PlusPlus())(
                            i1.WithInitializer(i.LessThan(separators.Access(nameof(Array.Length))).ConditionalOperator(
                                                   s.Call(nameof(string.IndexOf))(separators.ElementAccess(i), i0), s.Access(nameof(string.Length)))),
                            If(i1.LessThan(0).Or(i1.Equality(i0))).Then(Return(Null)),
                            pshResult.ElementAccess(i).Assign(s.Call(nameof(string.Substring))(i0, i1.Minus(i0))),
                            i0.Assign(i1.Plus(1))),
                        Return(pshResult));
                }
                else
                {
                    parseSplitHelper = null;
                }
                var tryParse2 = Method(Public | Static, _ctx.Type <bool>(), "TryParse")(name, allowUnparsed, result)
                                .WithBody(
                    _ctx.Type(typeof(GaxPreconditions)).Call(nameof(GaxPreconditions.CheckNotNull))(name, Nameof(name)),
                    resourceName,
                    PatternDetails.Zip(FromMethods(), (pattern, create) =>
                {
                    IEnumerable <(object code, IEnumerable <ExpressionSyntax> args)> codeAndArgs = pattern.PathSegments
                                                                                                   .Where(x => x.Segment.ParameterCount > 0)
                                                                                                   .Select((seg, segmentIndex) =>
                    {
                        if (seg.Segment.IsComplex)
                        {
                            var splitResult = Local(_ctx.ArrayType <string[]>(), $"split{segmentIndex}")
                                              .WithInitializer(This.Call(parseSplitHelper)(
                                                                   resourceName.ElementAccess(segmentIndex), NewArray(_ctx.ArrayType <char[]>())(seg.Segment.Separators.ToArray())));
                            var splitIf = If(splitResult.Equality(Null)).Then(
                                result.Assign(Null),
                                Return(false));
                            var args = Enumerable.Range(0, seg.Segment.ParameterCount).Select(i => splitResult.ElementAccess(i));
                            return((object)new object[] { splitResult, splitIf }, args);
                        }
                        else
                        {
                            return((object)null, new[] { resourceName.ElementAccess(segmentIndex) });
                        }
                    });
                    var elements = codeAndArgs.SelectMany(x => x.args);
                    return(If(pattern.PathTemplateField.Call(nameof(PathTemplate.TryParseName))(name, Out(resourceName))).Then(
                               codeAndArgs.Select(x => x.code),
                               result.Assign(This.Call(create)(elements.ToArray())),
                               Return(true)));
                }),
Пример #23
0
 /// <summary cref="IValueVisitor.Visit(NewArray)"/>
 public void Visit(NewArray value) =>
 throw new InvalidCodeGenerationException();
        public Expression[] TryApplyDefaultValuesOnArgumentList(Source src, Parameter[] list, Expression[] args)
        {
            if (args.Length < list.Length)
            {
                var result = new Expression[list.Length];

                for (int i = args.Length; i < list.Length; i++)
                {
                    if (list[i].OptionalDefault != null && list[i].Modifier == 0)
                    {
                        result[i] = GetParameterDefaultValue(src, list[i]);
                    }
                    else if (list[i].Modifier == ParameterModifier.Params && list[i].Type is RefArrayType)
                    {
                        result[i] = new NewArray(src, list[i].Type as RefArrayType, new Constant(src, Essentials.Int, 0));
                    }
                    else
                    {
                        return(args);
                    }
                }

                for (int i = 0; i < args.Length; i++)
                {
                    result[i] = args[i];
                }

                return(result);
            }

            if (list.Length > 0 && list[list.Length - 1].Modifier == ParameterModifier.Params && list[list.Length - 1].Type is RefArrayType)
            {
                var arrType = list[list.Length - 1].Type as RefArrayType;

                if (args.Length == list.Length && args[list.Length - 1].ReturnType == arrType)
                {
                    return(args);
                }

                var result = new Expression[list.Length];

                for (int i = 0; i < list.Length - 1; i++)
                {
                    result[i] = args[i];
                }

                if (args.Length == list.Length)
                {
                    var arr = TryCompileImplicitCast(src, arrType, args[list.Length - 1]);

                    if (arr != null)
                    {
                        result[list.Length - 1] = arr;
                        return(result);
                    }
                }

                var paramArray = new Expression[args.Length - list.Length + 1];
                var elmType    = arrType.ElementType;

                for (int i = 0; i < paramArray.Length; i++)
                {
                    var elm = TryCompileImplicitCast(src, elmType, args[i + list.Length - 1]);
                    if (elm == null)
                    {
                        return(args);
                    }

                    paramArray[i] = elm;
                }

                result[list.Length - 1] = new NewArray(src, arrType, paramArray);
                return(result);
            }

            return(args);
        }
 public SemanticAtom Visit(NewArray n)
 {
     return(Primitive.IntArray);
 }
Пример #26
0
 protected override void VisitNewArray(NewArray node, object data)
 {
     state.Stack.Perform_NewArray(node.Type, out exc);
     nextNode = node.Next;
 }
Пример #27
0
 void OP_NEWARRAY(out pBaseLangObject outObj, pBaseLangObject parent)
 {
     var obj = new NewArray(parent); outObj = obj; pBaseLangObject blo;
     Expect(14);
     if (StartOf(3)) {
         EXPRESSION(out blo, obj);
         obj.addChild(blo);
         while (la.kind == 18) {
             Get();
             EXPRESSION(out blo, obj);
             obj.addChild(blo);
         }
     }
     Expect(15);
 }
Пример #28
0
        public override AstNode VisitNewArray(NewArray ast)
        {
            Visit(ast.Length);

            var elementType = typeof(int);

            m_ilgen.Emit(OpCodes.Newarr, elementType);

            return ast;
        }
Пример #29
0
 protected internal virtual void VisitNewArray(NewArray node, object data)
 {
     throw new NodeNotSupportedException(node);
 }
Пример #30
0
 public override Exit visitNewArray(NewArray newArray, Environment env)
 {
     analyzeExpr(newArray.length, env);
     return(0);
 }
Пример #31
0
 public virtual AstNode VisitNewArray(NewArray ast)
 {
     return(ast);
 }