Ejemplo n.º 1
0
        public override FunctionType Deserialize(SerializedSignature ss, Frame frame)
        {
            if (ss == null)
                return null;
            this.argDeser = new ArgumentDeserializer(this, Architecture, frame, 0, Architecture.WordWidth.Size);
            Identifier ret = null;
            int fpuDelta = FpuStackOffset;

            FpuStackOffset = 0;
            if (ss.ReturnValue != null)
            {
                ret = argDeser.DeserializeReturnValue(ss.ReturnValue);
                fpuDelta += FpuStackOffset;
            }

            FpuStackOffset = 0;
            var args = new List<Identifier>();
            if (ss.Arguments != null)
            {
                for (int iArg = 0; iArg < ss.Arguments.Length; ++iArg)
                {
                    var sArg = ss.Arguments[iArg];
                    var arg = DeserializeArgument(sArg, iArg, ss.Convention);
                    args.Add(arg);
                }
                fpuDelta -= FpuStackOffset;
            }
            FpuStackOffset = fpuDelta;

            var sig = new FunctionType(ret, args.ToArray());
            ApplyConvention(ss, sig);
            return sig;
        }
Ejemplo n.º 2
0
 public Function(string prefix, string name, List<AstNode> argumentList)
 {
     this.functionType = FunctionType.FuncUserDefined;
     this.prefix = prefix;
     this.name = name;
     this.argumentList = new List<AstNode>(argumentList);
 }
        /// <summary>
        /// Sets whether functions 5 to 8 of the locomotive are momentaty or on/off
        /// </summary>
        /// <remarks>
        /// The type of each function is stored in a database maintained by the command station.
        /// </remarks>
        /// <param name="address">The address of the locomotive (0 - 9999)</param>
        /// <param name="f5">Function 5</param>
        /// <param name="f6">Function 6</param>
        /// <param name="f7">Function 7</param>
        /// <param name="f8">Function 8</param>
        public SetFunctionType_Group2Message(int address, FunctionType f5, FunctionType f6, FunctionType f7, FunctionType f8)
            : base(PacketHeaderType.LocomotiveFunction)
        {
            Payload.Add(Convert.ToByte(PacketIdentifier.LocomotiveFunctionRequest.SetFunctionState_Group2));

            byte[] data = new byte[3];

            if (address >= XpressNetConstants.MIN_LOCO_ADDRESS && address <= XpressNetConstants.MAX_LOCO_ADDRESS)
                ValueConverter.LocoAddress(address, out data[0], out data[1]);
            else
                throw new XpressNetProtocolViolationException("Number out of bounds");

            data[2] = 0x00;
            //TODO: check if & operator speeds up this function
            if (f8 == FunctionType.OnOff)
                data[2] += 8;

            if (f7 == FunctionType.OnOff)
                data[2] += 4;

            if (f6 == FunctionType.OnOff)
                data[2] += 2;

            if (f5 == FunctionType.OnOff)
                data[2] += 1;

            Payload.AddRange(data);
        }
Ejemplo n.º 4
0
 public Token(FunctionType functionType, int operandsCount)
 {
     this.Type = TokenType.Function;
     this.FunctionType = functionType;
     this.OperandsCount = operandsCount;
     this.Precedence = GetPrecedence();
 }
Ejemplo n.º 5
0
 public KernelEntryPoint(Function kernelFunction, FunctionType entryPointType)
     : base(kernelFunction.GetModule())
 {
     SetFunctionType(entryPointType);
     this.flags = MemberFlags.Static;
     this.kernelFunction = kernelFunction;
 }
Ejemplo n.º 6
0
 public Function(string prefix, string name, List<AstNode> argumentList)
 {
     _functionType = FunctionType.FuncUserDefined;
     _prefix = prefix;
     _name = name;
     _argumentList = new List<AstNode>(argumentList);
 }
Ejemplo n.º 7
0
        public static FunctionParameter CreateFunctionParameter(IList<string> list, string reference, string matchCount)
        {
            FunctionType[] types = new FunctionType[list.Count];
            for (int i = 0; i < list.Count; i++) {
                string s = list[i];
                FunctionType funType;
                if (String.Compare(s, "any", true) == 0) {
                    funType = FunctionType.Any;
                } else if (String.Compare(s, "comparable", true) == 0) {
                    funType = FunctionType.Comparable;
                } else if (String.Compare(s, "table", true) == 0) {
                    funType = FunctionType.Table;
                } else {
                    funType = new FunctionType(SqlType.Parse(s));
                }

                types[i] = funType;
            }

            FunctionParameterMatch match;
            if (matchCount == "1") {
                match = FunctionParameterMatch.Exact;
            } else if (matchCount == "+") {
                match = FunctionParameterMatch.OneOrMore;
            } else if (matchCount == "*") {
                match = FunctionParameterMatch.ZeroOrMore;
            } else {
                match = FunctionParameterMatch.ZeroOrOne;
            }

            return new FunctionParameter(types, reference, match);
        }
Ejemplo n.º 8
0
        public NativeTableItem( UFunction function )
        {
            if( function.IsOperator() )
            {
                Type = FunctionType.Operator;
            }
            else if( function.IsPost() )
            {
                Type = FunctionType.PostOperator;
            }
            else if( function.IsPre() )
            {
                Type = FunctionType.PreOperator;
            }
            else
            {
                Type = FunctionType.Function;
            }

            OperPrecedence = function.OperPrecedence;
            ByteToken = function.NativeToken;
            Name = Type == FunctionType.Function
                ? function.Name
                : function.FriendlyName;
        }
Ejemplo n.º 9
0
        public override FunctionType Deserialize(SerializedSignature ss, Frame frame)
        {
            if (ss == null)
                return new FunctionType();
            if (ss == null)
                return null;
            var argser = new ArgumentDeserializer(this, Architecture, frame, 0, Architecture.WordWidth.Size);
            Identifier ret = null;

            if (ss.ReturnValue != null)
            {
                ret = argser.DeserializeReturnValue(ss.ReturnValue);
            }

            var args = new List<Identifier>();
            this.gr = 0;
            if (ss.Arguments != null)
            {
                for (int iArg = 0; iArg < ss.Arguments.Length; ++iArg)
                {
                    var sArg = ss.Arguments[iArg];
                    Identifier arg = DeserializeArgument(argser, sArg);
                    args.Add(arg);
                }
            }

            var sig = new FunctionType(ret, args.ToArray());
            return sig;
        }
Ejemplo n.º 10
0
 public FunctionInfo(ObjectName routineName, RoutineParameter[] parameters, DataType returnType, FunctionType functionType)
     : base(routineName, parameters)
 {
     ReturnType = returnType;
     FunctionType = functionType;
     AssertUnboundAtEnd();
 }
Ejemplo n.º 11
0
 public FunctionInfo(ObjectName routineName, DataType returnType, FunctionType functionType)
     : base(routineName)
 {
     ReturnType = returnType;
     FunctionType = functionType;
     AssertUnboundAtEnd();
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Инициализирует экземпляр класса Neuron с нулевыми значениями входных сигналов и случайными начальными весами.
        /// </summary>
        /// <param name="signalsCount">Число синапсов на входе нейрона.</param>
        /// <param name="ft">Тип активационной функции нейрона.</param>
        /// <param name="funcParam">Значение параметра активационной функции.</param>
        public Neuron(int signalsCount, FunctionType ft, double funcParam)
        {
            SignalsIn = new double[signalsCount];
            Weights = new double[signalsCount];
            _param = funcParam;
            var r = RandomProvider.GetThreadRandom();

            Offset = Convert.ToDouble(r.Next(-100, 100)) / 1000;
            for (int i = 0; i < SignalsIn.Length; ++i)
            {
                Weights[i] = Convert.ToDouble(r.Next(-100, 100)) / 1000; //инициализация весов
                SignalsIn[i] = 0;
            }
            _activationFunc = ft;
            switch (ft) //инициализация активационной функции нейрона
            {
                case FunctionType.Linear:
                    _afd = LinearFunc; //линейная
                break;
                case FunctionType.Sigmoid:
                    _afd = LogSigmoidFunc; //лог-сигмоидальная
                    break;
                case FunctionType.HyperbolicTangent:
                    _afd = HyperbolicTangentFunc; //гиперболический тангенс
                    break;
                case FunctionType.Threshold:
                    _afd = ThresholdFunc; //пороговая
                    break;
                default:
                    throw new Exception("Неизвестный тип активационной функции");
            }
        }
 public Function(string prefix, string name, ArrayList argumentList)
 {
     this.functionType = FunctionType.FuncUserDefined;
     this.prefix = prefix;
     this.name = name;
     this.argumentList = new ArrayList(argumentList);
 }
Ejemplo n.º 14
0
        public FunctionDescriptor(
            string assembly, string className, string name, string summary,
            IEnumerable<TypedParameter> parameters, string returnType, FunctionType type,
            bool isVisibleInLibrary = true, IEnumerable<string> returnKeys = null, bool isVarArg = false)
        {
            this.summary = summary;
            Assembly = assembly;
            ClassName = className;
            Name = name;

            if (parameters == null)
                Parameters = new List<TypedParameter>();
            else
            {
                Parameters = parameters.Select(
                    x =>
                    {
                        x.Function = this;
                        return x;
                    });
            }

            ReturnType = returnType == null ? "var[]..[]" : returnType.Split('.').Last();
            Type = type;
            ReturnKeys = returnKeys ?? new List<string>();
            IsVarArg = isVarArg;
            IsVisibleInLibrary = isVisibleInLibrary;
        }
Ejemplo n.º 15
0
 public Building(int id,int price,string name, FunctionType type)
 {
     ID = id;
     Price = price;
     Name = name;
     Type = type;
 }
Ejemplo n.º 16
0
 public void Setup()
 {
     this.sc = new ServiceContainer();
     this.x86 = new X86ArchitectureFlat32();
     this.ppc = new PowerPcArchitecture32();
     this.m = new ProcedureBuilder();
     this.printfChr = new ProcedureCharacteristics()
     {
         VarargsParserClass =
             "Reko.Libraries.Libc.PrintfFormatParser,Reko.Libraries.Libc"
     };
     this.x86PrintfSig = new FunctionType(
         null,
         StackId(null,   4, CStringType()),
         StackId("...",  8, new UnknownType()));
     this.x86SprintfSig = new FunctionType(
         null,
         StackId(null,   4, CStringType()),
         StackId(null,   8, CStringType()),
         StackId("...", 12, new UnknownType()));
     this.ppcPrintfSig = new FunctionType(
         null,
         RegId(null,  ppc, "r3", CStringType()),
         RegId("...", ppc, "r4", new UnknownType()));
     this.addrInstr = Address.Ptr32(0x123400);
 }
Ejemplo n.º 17
0
 public override string DetermineCallingConvention(FunctionType signature)
 {
     if (!signature.HasVoidReturn)
     {
         var reg = signature.ReturnValue.Storage as RegisterStorage;
         if (reg != null)
         {
             if (reg != Registers.al && reg != Registers.ax)
                 return null;
         }
         var seq = signature.ReturnValue.Storage as SequenceStorage;
         if (seq != null)
         {
             if (seq.Head != Registers.dx || seq.Tail != Registers.ax)
                 return null;
         }
     }
     if (signature.Parameters.Any(p => !(p.Storage is StackArgumentStorage)))
         return null;
     if (signature.FpuStackDelta != 0 || signature.FpuStackArgumentMax >= 0)
         return null;
     if (signature.StackDelta == 0)
         return "__cdecl";
     else
         return "__pascal";
 }
Ejemplo n.º 18
0
        public MlpNeuron(List<Connection> inputs, List<Connection> outputs, 
		                  FunctionType functionType, ITunableParameterService paramService)
        {
            Inputs = inputs;
            Outputs = outputs;
            _functionType = functionType;
            _sigmoidAlpha = paramService.SigmoidAlpha;
        }
Ejemplo n.º 19
0
        internal BuiltinFunction(string/*!*/ name, MethodBase/*!*/[]/*!*/ originalTargets, Type/*!*/ declaringType, FunctionType functionType) {
            Assert.NotNull(name);
            Assert.NotNull(declaringType);
            Assert.NotNullItems(originalTargets);

            _data = new BuiltinFunctionData(name, originalTargets, declaringType, functionType);
            _instance = _noInstance;
        }
Ejemplo n.º 20
0
 public void Setup()
 {
     this.mr = new MockRepository();
     this.arch = new MipsLe32Architecture();
     this.typeLoader = mr.Stub<ISerializedTypeVisitor<DataType>>();
     this.ssig = null;
     this.sig = null;
 }
Ejemplo n.º 21
0
 public FunctionDeclarationHeader(SymbolDefinition name, AccessModifier visibility, FunctionType type)
     : base(CodeElementType.FunctionDeclarationHeader)
 {
     this.FunctionName = name;
     this.Visibility = visibility;
     this.UserDefinedType = type != null ? type : FunctionType.Undefined;
     this.Profile = new ParametersProfile();
 }
Ejemplo n.º 22
0
 public void ApplyConvention(SerializedSignature ssig, FunctionType sig)
 {
     string d = ssig.Convention;
     if (d == null || d.Length == 0)
         d = DefaultConvention;
     sig.StackDelta = 0;
     sig.FpuStackDelta = FpuStackOffset;
 }
 /// <summary>
 /// Finds a typedef with the same return type and parameter types.
 /// </summary>
 /// <param name="typedefs">The typedef list to search.</param>
 /// <param name="functionType">The function to match.</param>
 /// <returns>The matching typedef, or null if not found.</returns>
 private static TypedefDecl FindMatchingTypedef(IEnumerable<Typedef> typedefs, FunctionType functionType)
 {
     return (from typedef in typedefs
         let type = (FunctionType)typedef.Declaration.Type.GetPointee()
         where type.ReturnType == functionType.ReturnType &&
               type.Parameters.SequenceEqual(functionType.Parameters, ParameterTypeComparer.Instance)
         select typedef.Declaration).SingleOrDefault();
 }
Ejemplo n.º 24
0
 public Hero(int id,string name,FunctionType type,string imgPath, string description)
 {
     Id = id;
     Name = name;
     Type = type;
     ImgPath = imgPath;
     Description = description;
 }
Ejemplo n.º 25
0
		/// <summary>
		/// Creates a built-in function for a .NET method declared on a type.
		/// </summary>
		internal static BuiltinFunction MakeMethod(string name, MethodBase[] infos, Type declaringType, FunctionType ft)
		{
			foreach(MethodBase mi in infos){
				if (mi.ContainsGenericParameters)
					return new GenericBuiltinFunction(name, infos, declaringType, ft);
			}
			
			return new BuiltinFunction(name, infos, declaringType, ft);
		}
Ejemplo n.º 26
0
 public Building(int id,int price,string name,FunctionType type,string imgPath, string description)
 {
     Id = id;
     Price = price;
     Name = name;
     Type = type;
     ImgPath = imgPath;
     Description = description;
 }
Ejemplo n.º 27
0
 public static void Add(List<Building> bl, FunctionType type, string name, int price,string imgPath, string description, ref int Startnum, int num)
 {
     for (int i = Startnum; i < Startnum + num; i++)
     {
         Building b = new Building(i, price, name, type,imgPath,description);
         bl.Add(b);
     }
     Startnum += num;
 }
Ejemplo n.º 28
0
 public Function Find(FunctionType type, bool isStatic)
 {
     MakeConcrete();
     FunctionGroupName gname = new FunctionGroupName(type, isStatic);
     FunctionGroupName oldName = functions.Find(gname);
     if(oldName != null)
         return oldName.GetFunction();
     return null;
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Инициализирует экземпляр класса Layer с заданным числом нейронов c одним входным сигналом(используется когда связи неизвестны заранее).
        /// </summary>
        /// <param name="neuronCount">Число нейронов для слоя.</param>
        /// <param name="func">Активационная функция по-умолчанию.</param>
        public Layer(int neuronCount, FunctionType func)
        {
            _neurons = new Neuron[neuronCount]; //сами нейроны в конструкторе слоя не создаются, только резервируется место под них

            for (int i = 0; i < _neurons.Length; ++i)
                _neurons[i] = new Neuron(1, func, 1.0);
            LayerFunction = func;
            FuncDefaultParam = 1.0;
        }
Ejemplo n.º 30
0
        private static Function EmitFunction(Module module, MethodBase method)
        {
            var methodInfo = method as MethodInfo;
            var methodConstructor = method as ConstructorInfo;
            var declaringType = method.DeclaringType;
            if (methodInfo == null && methodConstructor == null)
                throw new CudaSharpException("Unknown MethodBase type " + method.GetType().FullName);
            if (declaringType == null)
                throw new CudaSharpException("Could not find the declaring type of " + method.Name.StripNameToValidPtx());

            var parameters = method.GetParameters().Select(p => p.ParameterType);
            if (methodConstructor != null)
                parameters = new[] { declaringType.MakeByRefType() }.Concat(parameters);
            if (methodInfo != null && methodInfo.IsStatic == false)
            {
                if (declaringType.IsValueType == false)
                    throw new CudaSharpException("Cannot compile object instance methods (did you forget to mark the method as static?)");
                parameters = new[] { declaringType.MakeByRefType() }.Concat(parameters);
            }
            var llvmParameters =
                parameters.Select(t => ConvertType(module, t)).ToArray();
            var funcType = new FunctionType(ConvertType(module, methodInfo == null ? typeof(void) : methodInfo.ReturnType), llvmParameters);

            var intrinsic = method.GetCustomAttribute<Gpu.BuiltinAttribute>();
            if (intrinsic != null)
            {
                var name = intrinsic.Intrinsic;
                var preExisting = module.GetFunction(name);
                if (preExisting != null)
                    return preExisting;
                return module.CreateFunction(name, funcType);
            }

            var function = module.CreateFunction(methodConstructor == null ? method.Name.StripNameToValidPtx() : declaringType.Name.StripNameToValidPtx() + "_ctor", funcType);

            var block = new Block("entry", module.Context, function);
            var writer = new InstructionBuilder(module.Context, block);

            var opcodes = method.Disassemble().ToList();
            FindBranchTargets(opcodes, module.Context, function);

            var body = method.GetMethodBody();
            var efo = new EmitFuncObj(module, function, body, writer, null, new Stack<Value>(),
                body == null ? null : new Value[body.LocalVariables.Count], new Value[llvmParameters.Length]);

            PrintHeader(efo);
            foreach (var opcode in opcodes)
            {
                if (EmitFunctions.ContainsKey(opcode.Opcode) == false)
                    throw new CudaSharpException("Unsupported CIL instruction " + opcode.Opcode);
                var func = EmitFunctions[opcode.Opcode];
                efo.Argument = opcode.Parameter;
                func(efo);
            }

            return function;
        }
Ejemplo n.º 31
0
 private static bool IsMatchingOpType(FunctionType opType, OperatorTypeButton otb)
 {
     return((otb.MetaOp.Inputs.Count > 0) &&
            ((otb.MetaOp.Inputs[0].OpPart.Type == opType) ||
             (otb.MetaOp.Inputs[0].OpPart.Type == FunctionType.Generic)));
 }
Ejemplo n.º 32
0
        public override void VisitCallInstruction(CallInstruction ci)
        {
            FunctionType sig = GetProcedureSignature(ci.Callee);

            if (sig != null && sig.ParametersValid)
            {
                var procCallee = ((ProcedureConstant)ci.Callee).Procedure;
                var ab         = new ApplicationBuilder(
                    Procedure.Architecture,
                    Procedure.Frame,
                    ci.CallSite,
                    new ProcedureConstant(program.Platform.PointerType, procCallee),
                    sig,
                    false);
                if (!sig.HasVoidReturn)
                {
                    varLive.Def(ab.Bind(sig.ReturnValue));
                }
                foreach (Identifier arg in sig.Parameters)
                {
                    if (arg.Storage is OutArgumentStorage)
                    {
                        varLive.Def(ab.Bind(arg));
                    }
                }

                foreach (Identifier arg in sig.Parameters)
                {
                    if (!(arg.Storage is OutArgumentStorage))
                    {
                        varLive.Use(ab.Bind(arg));
                    }
                }
            }
            else
            {
                var pc = ci.Callee as ProcedureConstant;
                if (pc == null)
                {
                    return;
                }
                var procCallee = pc.Procedure as Procedure;
                if (procCallee == null)
                {
                    return;
                }

                if (state.PropagateThroughExitNodes)
                {
                    PropagateToCalleeExitBlocks(stmCur);
                }

                // Update trash information.

                ProcedureFlow pi   = mpprocData[procCallee];
                ProcedureFlow item = mpprocData[Procedure];

                // The registers that are still live before a call are those
                // that were live after the call and were bypassed by the called function
                // or used by the called function.

                var ids = new HashSet <RegisterStorage>(pi.TrashedRegisters);
                ids.ExceptWith(pi.ByPass);
                varLive.Identifiers.ExceptWith(ids);
                varLive.Identifiers.UnionWith(pi.MayUse);
                // varLive.BitSet = pi.MayUse | ((pi.ByPass    | ~pi.TrashedRegisters) & varLive.BitSet);
                varLive.Grf = pi.grfMayUse | ((pi.grfByPass | ~pi.grfTrashed) & varLive.Grf);
                // Any stack parameters are also considered live.
                MarkLiveStackParameters(ci);
            }
        }
Ejemplo n.º 33
0
 public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
 {
     Context.Return.Write(Context.ReturnVarName);
     return(true);
 }
Ejemplo n.º 34
0
 public override void OnProcedureLeft(FunctionType procedureSignature)
 {
     throw new System.NotImplementedException();
 }
Ejemplo n.º 35
0
        public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
        {
            var returnType = function.ReturnType;

            return(returnType.Visit(this));
        }
Ejemplo n.º 36
0
 public override void OnProcedureLeft(FunctionType sig)
 {
 }
Ejemplo n.º 37
0
        private static BuiltinFunction MakeBuiltinFunction(string name, MethodInfo info, MethodBase[] targets, FunctionType functionType)
        {
            switch (info.GetParameters().Length)
            {
            case 0: return(new OptimizedFunction0(name, info, targets, functionType));

            case 1: return(new OptimizedFunction1(name, info, targets, functionType));

            case 2: return(new OptimizedFunction2(name, info, targets, functionType));

            case 3: return(new OptimizedFunction3(name, info, targets, functionType));

            case 4: return(new OptimizedFunction4(name, info, targets, functionType));

            case 5: return(new OptimizedFunction5(name, info, targets, functionType));
            }
            throw new InvalidOperationException("too many args");
        }
Ejemplo n.º 38
0
 public OptimizedFunctionN(string name, MethodInfo info, MethodBase[] targets, FunctionType functionType) : base(name, targets, functionType)
 {
     target = IronPython.Compiler.CodeGen.CreateDelegate(info, typeof(CallTargetN)) as CallTargetN;
 }
 /// <summary>
 /// Finds a typedef with the same return type and parameter types.
 /// </summary>
 /// <param name="typedefs">The typedef list to search.</param>
 /// <param name="functionType">The function to match.</param>
 /// <returns>The matching typedef, or null if not found.</returns>
 private static TypedefDecl FindMatchingTypedef(IEnumerable <Typedef> typedefs, FunctionType functionType)
 {
     return((from typedef in typedefs
             let type = (FunctionType)typedef.Declaration.Type.GetPointee()
                        where type.ReturnType == functionType.ReturnType &&
                        type.Parameters.SequenceEqual(functionType.Parameters, ParameterTypeComparer.Instance)
                        select typedef.Declaration).SingleOrDefault());
 }
Ejemplo n.º 40
0
 public PseudoProcedure(string name, FunctionType sig) : base(name)
 {
     this.sig = sig;
 }
Ejemplo n.º 41
0
 public CodeFormatter VisitFunctionType(FunctionType ft)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 42
0
 public virtual TypePrinterResult VisitDelegate(FunctionType function)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 43
0
        public void Uvr_Signature()
        {
            var arch = new FakeArchitecture();
            var pb   = new ProgramBuilder(arch);
            var _r1  = arch.GetRegister("r1");
            var _r2  = arch.GetRegister("r2");

            pb.Add("main", m =>
            {
                var r1 = m.Frame.EnsureRegister(_r1);
                m.Assign(m.Frame.EnsureRegister(m.Architecture.StackRegister), m.Frame.FramePointer);
                m.Call("foo", 0);
                m.MStore(m.Word32(0x123420), r1);
            });
            pb.Add("foo", m =>
            {
                var r1 = m.Frame.EnsureRegister(_r1);
                var r2 = m.Frame.EnsureRegister(_r2);
                m.Assign(m.Frame.EnsureRegister(m.Architecture.StackRegister), m.Frame.FramePointer);
                m.Assign(r1, m.Mem32(m.Word32(0x123400)));
                m.MStore(m.Word32(0x123408), r1);
                m.Assign(r2, m.Mem32(m.Word32(0x123410)));
                m.MStore(m.Word32(0x123418), r2);
                m.Return();

                m.Procedure.Signature = FunctionType.Func(
                    new Identifier(null, PrimitiveType.Word32, _r1),
                    new Identifier("arg1", PrimitiveType.Word32, _r2));
            });

            pb.BuildProgram();

            var sExp =
                #region Expected
                @"// main
// Return size: 0
define main
main_entry:
	def r2
	// succ:  l1
l1:
	r1_4 = foo(r2)
	Mem5[0x00123420:word32] = r1_4
main_exit:
===
// foo
// Return size: 0
word32 foo(word32 arg1)
foo_entry:
	def fp
	def Mem0
	// succ:  l1
l1:
	r63_2 = fp
	r1_4 = Mem0[0x00123400:word32]
	Mem5[0x00123408:word32] = r1_4
	r2_6 = Mem5[0x00123410:word32]
	Mem7[0x00123418:word32] = r2_6
	return
	// succ:  foo_exit
foo_exit:
	use r1_4
===
";

            #endregion

            RunTest(sExp, pb.Program);
        }
Ejemplo n.º 44
0
 public virtual TypePrinterResult VisitFunctionType(FunctionType function,
                                                    TypeQualifiers quals)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 45
0
 public bool VisitDelegateType(FunctionType function, string type)
 {
     Context.Return.Write("{0} == null ? global::System.IntPtr.Zero : Marshal.GetFunctionPointerForDelegate({0})",
                          Context.Parameter.Name);
     return(true);
 }
Ejemplo n.º 46
0
 public string DetermineCallingConvention(FunctionType signature)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 47
0
 public CSharpTypePrinterResult VisitDelegate(FunctionType function)
 {
     return(string.Format("delegate {0} {{0}}({1})",
                          function.ReturnType.Visit(this),
                          VisitParameters(function.Parameters, hasNames: true)));
 }
Ejemplo n.º 48
0
 public FunctionWrapper(FunctionType type = FunctionType.Liner)
 {
     ChoseFun(type);
 }
Ejemplo n.º 49
0
 public IEnumerable <WorkItem> VisitFunctionType(FunctionType ft)
 {
     throw new NotImplementedException();
 }
        public FunctionAndOperatorCommandParameter(UserInteractionType functionUserInteractionType, UserInteractionType operatorUserInteractionType, FunctionType functionType, OperatorType operatorType)
        {
            FunctionUserInteractionType = functionUserInteractionType;
            OperatorUserInteractionType = operatorUserInteractionType;

            FunctionType = functionType;
            OperatorType = operatorType;

            FunctionText = Functions.GetFunctionText(functionType);
            OperatorText = Operators.GetOperatorText(operatorType);
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Deserializes the signature <paramref name="ss"/>. Any instantiated
        /// registers or stack variables are introduced into the Frame.
        /// </summary>
        /// <param name="ss"></param>
        /// <param name="frame"></param>
        /// <returns></returns>
        public FunctionType?Deserialize(SerializedSignature?ss, Frame frame)
        {
            if (ss == null)
            {
                return(null);
            }
            // If there is no explict return address size,
            // use the architecture's default return address size.

            var retAddrSize = ss.ReturnAddressOnStack != 0
                ? ss.ReturnAddressOnStack
                : this.Architecture.ReturnAddressOnStack;

            if (!ss.ParametersValid)
            {
                return(new FunctionType
                {
                    StackDelta = ss.StackDelta,
                    ReturnAddressOnStack = retAddrSize,
                });
            }

            var parameters = new List <Identifier>();

            Identifier?ret = null;

            if (UseUserSpecifiedStorages(ss))
            {
                this.argDeser = new ArgumentDeserializer(
                    this,
                    Architecture,
                    frame,
                    retAddrSize,
                    Architecture.WordWidth.Size);
                if (ss.Arguments != null)
                {
                    FpuStackGrowing = true;
                    for (int iArg = 0; iArg < ss.Arguments.Length; ++iArg)
                    {
                        var sArg = ss.Arguments[iArg];
                        var arg  = DeserializeArgument(sArg, ss.Convention);
                        if (arg != null)
                        {
                            parameters.Add(arg);
                        }
                    }
                }
                if (ss.ReturnValue != null)
                {
                    FpuStackGrowing = false;
                    ret             = DeserializeArgument(ss.ReturnValue, "");
                }
                FpuStackOffset = -FpuStackOffset;
                var sig = FunctionType.Create(ret, parameters.ToArray());
                sig.IsVariadic      = this.IsVariadic;
                sig.IsInstanceMetod = ss.IsInstanceMethod;
                ApplyConvention(ss, sig);
                return(sig);
            }
            else
            {
                var dtRet = ss.ReturnValue != null && ss.ReturnValue.Type != null
                    ? ss.ReturnValue.Type.Accept(TypeLoader)
                    : null;

                var dtThis = ss.EnclosingType != null
                    ? new Pointer(ss.EnclosingType.Accept(TypeLoader), Architecture.PointerType.BitSize)
                    : null;
                var dtParameters = ss.Arguments != null
                    ? ss.Arguments
                                   .TakeWhile(p => p.Name != "...")
                                   .Select(p => p.Type !.Accept(TypeLoader))
                                   .ToList()
                    : new List <DataType>();

                // A calling convention governs the storage of a the
                // parameters

                var cc = platform.GetCallingConvention(ss.Convention);
                if (cc == null)
                {
                    // It was impossible to determine a calling convention,
                    // so we don't know how to decode this signature accurately.
                    return(new FunctionType
                    {
                        StackDelta = ss.StackDelta,
                        ReturnAddressOnStack = retAddrSize,
                    });
                }
                var res = new CallingConventionEmitter();
                cc.Generate(res, dtRet, dtThis, dtParameters);
                if (res.Return != null)
                {
                    ret = new Identifier(
                        res.Return is RegisterStorage retReg ? retReg.Name : "",
                        dtRet ?? VoidType.Instance,
                        res.Return);
                }
                if (res.ImplicitThis != null)
                {
                    var param = new Identifier("this", dtThis !, res.ImplicitThis);
                    parameters.Add(param);
                }
                bool isVariadic = false;
                if (ss.Arguments != null)
                {
                    for (int i = 0; i < ss.Arguments.Length; ++i)
                    {
                        if (ss.Arguments[i].Name == "...")
                        {
                            isVariadic = true;
                        }
                        else
                        {
                            var name  = GenerateParameterName(ss.Arguments[i].Name, dtParameters[i], res.Parameters[i]);
                            var param = new Identifier(name, dtParameters[i], res.Parameters[i]);
                            parameters.Add(param);
                        }
                    }
                }
                var ft = FunctionType.Create(ret, parameters.ToArray());
                ft.IsInstanceMetod = ss.IsInstanceMethod;
                ft.StackDelta      = ss.StackDelta != 0
                        ? ss.StackDelta
                        : res.StackDelta;
                ft.FpuStackDelta        = res.FpuStackDelta;
                ft.ReturnAddressOnStack = retAddrSize;
                ft.IsVariadic           = isVariadic;
                return(ft);
            }
        }
Ejemplo n.º 52
0
 public FunctionToken(string name, Func <double, double> function, FunctionType functionType)
 {
     this.function = function;
     this.Name     = name;
     FunctionType  = functionType;
 }
Ejemplo n.º 53
0
 public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
 {
     Context.Return.Write("{0} == null ? global::System.IntPtr.Zero : Marshal.GetFunctionPointerForDelegate({0})",
                          Context.Parameter.Name);
     return(true);
 }
Ejemplo n.º 54
0
        public override TType GetFunction <TType, TModel>(Expression <Func <TModel, bool> > expression, Expression <Func <TModel, TType> > selectField, FunctionType functionType, bool compileSp = false)
        {
            var query = new MongoDBLambdaQuery <TModel>(dbContext);

            query.Select(selectField.Body);
            query.Where(expression);
            var    collection = _MongoDB.GetCollection <TModel>(query.QueryTableName);
            object result     = null;

            //https://blog.csdn.net/shiyaru1314/article/details/52370478
            //https://www.jb51.net/article/113820.htm
            //https://blog.csdn.net/u013476435/article/details/81560089
            switch (functionType)
            {
            case FunctionType.COUNT:
                result = collection.Count(query.__MongoDBFilter);
                break;

            default:
                throw new NotSupportedException("MongoDB不支持的函数:" + functionType);
            }
            return(ObjectConvert.ConvertObject <TType>(result));
        }
Ejemplo n.º 55
0
 public void VisitFunctionType(FunctionType ft)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 56
0
        //public TType Sum<TType, TModel>(Expression<Func<TModel, bool>> expression, string field, bool compileSp = false) where TModel : IModel, new()
        //{
        //    return GetFunction<TType, TModel>(expression, field, FunctionType.SUM, compileSp);
        //}
        #endregion

        internal abstract TType GetFunction <TType, TModel>(Expression <Func <TModel, bool> > expression, Expression <Func <TModel, TType> > selectField, FunctionType functionType, bool compileSp = false) where TModel : IModel, new();
Ejemplo n.º 57
0
 public override void OnProcedureLeft(FunctionType procedureSignature)
 {
 }
Ejemplo n.º 58
0
 public override void OnAfterCall(FunctionType sigCallee)
 {
 }
Ejemplo n.º 59
0
        public OptimizedFunctionAny(string name, MethodInfo[] infos, MethodBase[] targets, FunctionType functionType) : base(name, targets, functionType)
        {
            for (int i = 0; i < infos.Length; i++)
            {
                Debug.Assert(infos[i].IsStatic);

                switch (infos[i].GetParameters().Length)
                {
                case 0: target0 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget0)) as CallTarget0; break;

                case 1:
                    if (!infos[i].GetParameters()[0].ParameterType.HasElementType)
                    {
                        target1 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget1)) as CallTarget1;
                    }
                    else
                    {
                        targetN = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTargetN)) as CallTargetN;
                    }
                    break;

                case 2: target2 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget2)) as CallTarget2; break;

                case 3: target3 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget3)) as CallTarget3; break;

                case 4: target4 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget4)) as CallTarget4; break;

                case 5: target5 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget5)) as CallTarget5; break;
                }
            }
        }
Ejemplo n.º 60
0
        private List <Mapping> GetMappings(InputKey inputKey, IEmulationSlot slot, FunctionType functionType)
        {
            var filtered = slot.Preset.FilterByKey(inputKey);
            var mappings = new List <Mapping>();

            switch (functionType)
            {
            case FunctionType.Button:
            {
                // Normal buttons
                foreach (var presetButton in filtered.Buttons)
                {
                    var button = presetButton.Button;
                    var keys   = slot.Preset.GetKeys(presetButton);
                    mappings.Add(new Mapping(button, keys));
                }

                // Custom buttons
                foreach (var customFunction in filtered.CustomFunctions)
                {
                    var xboxFunction = (XboxCustomFunction)customFunction.Function;
                    var funcType     = Helpers.CustomFunctionHelper.GetFunctionType(xboxFunction);
                    if (funcType == functionType)
                    {
                        var button = (uint)Helpers.CustomFunctionHelper.GetXboxButton(xboxFunction);
                        var keys   = slot.Preset.GetKeys(customFunction);
                        mappings.Add(new Mapping(button, keys));
                    }
                }
            }

            break;

            case FunctionType.Axis:
            {
                // Normal axes
                foreach (var presetAxis in filtered.Axes)
                {
                    mappings.Add(new Mapping(presetAxis.Axis, slot.Preset.GetKeys(presetAxis), presetAxis.Value));
                }

                // Custom axes
                foreach (var presetCustom in filtered.CustomFunctions)
                {
                    var xboxCustomFunction = (XboxCustomFunction)presetCustom.Function;
                    var funcType           = Helpers.CustomFunctionHelper.GetFunctionType(xboxCustomFunction);
                    if (funcType == functionType)
                    {
                        XboxAxisPosition pos;
                        var axis = Helpers.CustomFunctionHelper.GetXboxAxis(xboxCustomFunction, out pos);
                        mappings.Add(new Mapping((uint)axis, slot.Preset.GetKeys(presetCustom), pos));
                    }
                }
            }

            break;

            case FunctionType.Dpad:
                // Normal dpad directions
                foreach (var presetDpad in filtered.Dpads)
                {
                    mappings.Add(new Mapping(presetDpad.Direction, slot.Preset.GetKeys(presetDpad)));
                }

                // Custom dpad directions
                foreach (var customDpad in filtered.CustomFunctions)
                {
                    var xboxFunction = (XboxCustomFunction)customDpad.Function;
                    var funcType     = Helpers.CustomFunctionHelper.GetFunctionType(xboxFunction);
                    if (funcType == functionType)
                    {
                        var direction = Helpers.CustomFunctionHelper.GetDpadDirection(xboxFunction);
                        var keys      = slot.Preset.GetKeys(customDpad);
                        mappings.Add(new Mapping(direction, keys));
                    }
                }

                break;

            case FunctionType.Trigger:
            {
                // Normal triggers
                foreach (var presetTrigger in filtered.Triggers)
                {
                    var trigger = presetTrigger.Trigger;
                    var keys    = slot.Preset.GetKeys(presetTrigger);
                    mappings.Add(new Mapping(trigger, keys));
                }

                // Custom triggers
                foreach (var customFunction in filtered.CustomFunctions)
                {
                    var xboxFunction = (XboxCustomFunction)customFunction.Function;
                    var funcType     = Helpers.CustomFunctionHelper.GetFunctionType(xboxFunction);
                    if (funcType == functionType)
                    {
                        var trigger = (uint)Helpers.CustomFunctionHelper.GetXboxTrigger(xboxFunction);
                        var keys    = slot.Preset.GetKeys(customFunction);
                        mappings.Add(new Mapping(trigger, keys));
                    }
                }
            }

            break;

            default:
                break;
            }

            return(mappings);
        }