示例#1
0
文件: SLCOM.cs 项目: thakgit/StiLib
        /// <summary>
        /// Read COM port
        /// </summary>
        /// <returns></returns>
        public string ReadCOM()
        {
            int count = Port.BytesToRead;

            byte[] msg = new byte[count];
            string MSG = "";

            try
            {
                if (!Port.IsOpen)
                {
                    OpenCOM(Port.PortName);
                }

                if (Port.IsOpen)
                {
                    Port.Read(msg, 0, count);
                    Port.DiscardInBuffer();
                    MSG = Port.Encoding.GetString(msg);
                }
            }
            catch (Exception e)
            {
                SLConstant.ShowException(e);
            }

            return(MSG);
        }
示例#2
0
文件: SLCOM.cs 项目: thakgit/StiLib
        /// <summary>
        /// Write COM port
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public bool WriteCOM(string text)
        {
            bool success = false;

            try
            {
                if (!Port.IsOpen)
                {
                    OpenCOM(Port.PortName);
                }

                if (Port.IsOpen)
                {
                    Port.WriteLine(text);
                    Port.DiscardOutBuffer();
                    success = true;
                }
            }
            catch (Exception e)
            {
                SLConstant.ShowException(e);
            }

            return(success);
        }
示例#3
0
        public void SimpleLet()
        {
            SLLine line = SLDeclaration.LetLine("foo", SLSimpleType.Int, SLConstant.Val(5), Visibility.Public);
            string code = CodeWriter.WriteToString(line);

            Compiler.CompileStringUsing(null, XCodeCompiler.SwiftcCustom, code, null);
        }
示例#4
0
        void FuncReturningFoo(SLType type, SLConstant val)
        {
            SLLine      line  = SLReturn.ReturnLine(val);
            SLCodeBlock block = new SLCodeBlock(new ICodeElement [] { line });
            SLFunc      func  = new SLFunc(Visibility.Public, type, new SLIdentifier("simpleFunc"), null, block);

            string code = CodeWriter.WriteToString(func);

            Compiler.CompileStringUsing(null, XCodeCompiler.SwiftcCustom, code, null);
        }
示例#5
0
 public void TestLetInt()
 {
     BindToValue(true, SLSimpleType.Int, SLConstant.Val(42), Visibility.Public);
     BindToValue(false, SLSimpleType.Int, SLConstant.Val(42), Visibility.Public);
     BindToValue(true, SLSimpleType.Int, SLConstant.Val(42), Visibility.Private);
     BindToValue(false, SLSimpleType.Int, SLConstant.Val(42), Visibility.Private);
     BindToValue(true, SLSimpleType.Int, SLConstant.Val(42), Visibility.Internal);
     BindToValue(false, SLSimpleType.Int, SLConstant.Val(42), Visibility.Internal);
     BindToValue(true, SLSimpleType.Int, SLConstant.Val(42), Visibility.None);
     BindToValue(false, SLSimpleType.Int, SLConstant.Val(42), Visibility.None);
 }
示例#6
0
 /// <summary>
 /// Creates a new object that is a copy of the current instance
 /// </summary>
 /// <returns></returns>
 public override object Clone()
 {
     if (gdRef != null)
     {
         return(new Primitive(distance2Display, displayRatio, displaySize, globalCamera, unit, gdRef, Para));
     }
     else
     {
         SLConstant.ShowMessage("No Internal GraphicsDevice Reference, Please InitVS(GraphicsDevice gd) First !");
         return("No gdRef");
     }
 }
示例#7
0
 /// <summary>
 /// Creates a new object that is a copy of the current instance
 /// </summary>
 /// <returns></returns>
 public override object Clone()
 {
     if (gdRef != null)
     {
         return(new Text(distance2Display, displayRatio, displaySize, globalCamera, unit, gdRef, contentManager.ServiceProvider, contentManager.RootDirectory, Para));
     }
     else
     {
         SLConstant.ShowMessage("No Internal GraphicsDevice Reference, Please InitVS(GraphicsDevice gd) First !");
         return("No gdRef");
     }
 }
示例#8
0
文件: SLCOM.cs 项目: thakgit/StiLib
 /// <summary>
 /// SerialDataReceived EventHandler Delegate
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected virtual void DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     newReceivedData = "";
     try
     {
         newReceivedData     = Port.ReadExisting();
         receivedDataLength += newReceivedData.Length;
     }
     catch (Exception ex)
     {
         SLConstant.ShowException(ex);
     }
 }
示例#9
0
文件: SLCOM.cs 项目: thakgit/StiLib
        /// <summary>
        /// Open a COM port with custom parameters
        /// </summary>
        /// <param name="portName"></param>
        /// <param name="readTimeout">0: InfiniteTimeout(ms)</param>
        /// <param name="writeTimeout">0: InfiniteTimeout(ms)</param>
        /// <param name="baudRate"></param>
        /// <param name="parity"></param>
        /// <param name="dataBits"></param>
        /// <param name="stopBits"></param>
        /// <param name="handShake"></param>
        /// <returns></returns>
        public bool OpenCOM(string portName, int readTimeout, int writeTimeout, int baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handShake)
        {
            bool hr = false;

            try
            {
                if (isCOMExist)
                {
                    if (!Port.IsOpen)
                    {
                        if (readTimeout > 0)
                        {
                            Port.ReadTimeout = readTimeout;
                        }
                        else
                        {
                            Port.ReadTimeout = SerialPort.InfiniteTimeout;
                        }
                        if (writeTimeout > 0)
                        {
                            Port.WriteTimeout = writeTimeout;
                        }
                        else
                        {
                            Port.WriteTimeout = SerialPort.InfiniteTimeout;
                        }

                        Port.PortName  = portName;
                        Port.BaudRate  = baudRate;
                        Port.Parity    = parity;
                        Port.DataBits  = dataBits;
                        Port.StopBits  = stopBits;
                        Port.Handshake = handShake;

                        Port.DataReceived  += DataReceivedEventHandler;
                        Port.ErrorReceived += ErrorReceivedEventHandler;
                        Port.PinChanged    += PinChangedEventHandler;

                        Port.Open();
                        hr = true;
                    }
                }
            }
            catch (Exception e)
            {
                SLConstant.ShowException(e);
            }

            return(hr);
        }
示例#10
0
文件: SLCOM.cs 项目: thakgit/StiLib
 /// <summary>
 /// Close current port
 /// </summary>
 public void CloseCOM()
 {
     try
     {
         if (Port.IsOpen)
         {
             Port.Close();
         }
     }
     catch (Exception e)
     {
         SLConstant.ShowException(e);
     }
 }
示例#11
0
        /// <summary>
        /// Init Each Element of Collection According to StiLib Configuration, Custom Vision Stimulus Type and Parameters Object
        /// </summary>
        /// <param name="count"></param>
        /// <param name="vstype"></param>
        /// <param name="gd"></param>
        /// <param name="slconfig"></param>
        /// <param name="service"></param>
        /// <param name="path"></param>
        /// <param name="vspara"></param>
        public virtual void Init(int count, VSType vstype, GraphicsDevice gd, AssemblySettings slconfig, IServiceProvider service, string path, object vspara)
        {
            vsType temp = null;

            try
            {
                switch (vstype)
                {
                case VSType.Bar:
                    temp = new Bar(gd, slconfig, (BarPara)vspara) as vsType;
                    break;

                case VSType.Grating:
                    temp = new Grating(gd, slconfig, service, path, (GratingPara)vspara) as vsType;
                    break;

                case VSType.Image:
                    temp = new Image(gd, slconfig, service, path, (ImagePara)vspara) as vsType;
                    break;

                case VSType.Primitive:
                    temp = new Primitive(gd, slconfig, (PrimitivePara)vspara) as vsType;
                    break;

                case VSType.SLModel:
                    temp = new SLModel(gd, slconfig, service, path, (ModelPara)vspara) as vsType;
                    break;

                case VSType.SLQuad:
                    temp = new SLQuad(gd, slconfig, service, path, (Quad)vspara) as vsType;
                    break;

                case VSType.SLVideo:
                    temp = new SLVideo(gd, slconfig, service, path, (VideoPara)vspara) as vsType;
                    break;

                case VSType.Text:
                    temp = new Text(gd, slconfig, service, path, (TextPara)vspara) as vsType;
                    break;
                }

                Init(count, gd, temp);
            }
            catch (Exception e)
            {
                SLConstant.ShowException(e);
            }
        }
示例#12
0
 /// <summary>
 /// Log message string
 /// </summary>
 /// <param name="info"></param>
 public void Log(string info)
 {
     try
     {
         message.Append(DateTime.Now.ToString()).Append("  ---  ").Append(info);
         writer.WriteLine(message.ToString());
         writer.Flush();
     }
     catch (Exception e)
     {
         SLConstant.ShowException(e);
     }
     finally
     {
         message.Remove(0, message.Length);
     }
 }
示例#13
0
        /// <summary>
        /// Linearize Gamma According to Current Gamma Value Using GraphicsDevice GammaRamp
        /// </summary>
        /// <param name="gamma">current R, G, B gamma value</param>
        public void SetGamma(Vector3 gamma)
        {
            bool isfullscreengamma;
            GraphicsDeviceCapabilities gdcap = gd.GraphicsDeviceCapabilities;

            if (gdcap.DriverCapabilities.SupportsFullScreenGamma)
            {
                isfullscreengamma = true;
            }
            else
            {
                isfullscreengamma = false;
                SLConstant.ShowMessage("This GraphicsDevice Does Not Support Full Screen Gamma Correction !");
            }
            if (isfullscreengamma && gd.PresentationParameters.IsFullScreen && (gamma.X != 1.0f || gamma.Y != 1.0f || gamma.Z != 1.0f))
            {
                gd.SetGammaRamp(false, SLAlgorithm.GetGamma(gamma));
            }
        }
示例#14
0
        /// <summary>
        /// Linearize Gamma According to Current Gamma Value Using GraphicsDevice GammaRamp
        /// </summary>
        /// <param name="gamma">current R, G, B gamma value</param>
        public void SetGamma(Vector3 gamma)
        {
            bool isfullscreengamma;
            GraphicsDeviceCapabilities gdcap = GraphicsAdapter.DefaultAdapter.GetCapabilities(DeviceType.Hardware);

            if (gdcap.DriverCapabilities.SupportsFullScreenGamma)
            {
                isfullscreengamma = true;
            }
            else
            {
                isfullscreengamma = false;
                SLConstant.ShowMessage("This Adapter Does Not Support Full Screen Gamma Correction !");
            }
            if (isfullscreengamma && gdm.IsFullScreen && (gamma.X != 1.0f || gamma.Y != 1.0f || gamma.Z != 1.0f))
            {
                gdm.GraphicsDevice.SetGammaRamp(false, SLAlgorithm.GetGamma(gamma));
                this.gamma = gamma;
            }
        }
示例#15
0
 public static SLBaseExpr operator >>(SLBaseExpr lhs, int bits)
 {
     return(new SLBinaryExpr(BinaryOp.RightShift, lhs, SLConstant.Val(bits)));
 }
示例#16
0
 public void FuncReturningInt()
 {
     FuncReturningFoo(SLSimpleType.Int, SLConstant.Val(4));
 }
        SLBaseExpr MarshalTupleTypeSpec(BaseDeclaration declContext, string name, TupleTypeSpec tuple)
        {
            var bindingName = new SLIdentifier(MarshalEngine.Uniqueify(name, identifiersUsed));
            var argType     = typeMapper.TypeSpecMapper.MapType(declContext, imports, tuple, false);
            var ptrType     = new SLBoundGenericType("UnsafeMutablePointer", argType);

            identifiersUsed.Add(bindingName.Name);
            var decl = new SLDeclaration(true, bindingName, ptrType,
                                         new SLFunctionCall(ptrType + ".allocate", false, new SLArgument(new SLIdentifier("capacity"), SLConstant.Val(1), true)),
                                         Visibility.None, false);
            var varBinding = new SLLine(decl);

            preMarshalCode.Add(varBinding);
            var initCall = SLFunctionCall.FunctionCallLine(bindingName.Name + ".initialize",
                                                           new SLArgument(new SLIdentifier("to"), new SLIdentifier(name), true));

            preMarshalCode.Add(initCall);
            imports.AddIfNotPresent("XamGlue");
            if (tuple.IsInOut)
            {
                postMarshalCode.Add(new SLLine(new SLBinding(name, bindingName.Dot(new SLIdentifier("pointee")))));
            }
            return(new SLFunctionCall("toIntPtr", false, new SLArgument(new SLIdentifier("value"), bindingName, true)));
        }
        public IEnumerable <ICodeElement> MarshalFunctionCall(FunctionDeclaration func, string vtableName, string vtableElementName)
        {
            preMarshalCode.Clear();
            postMarshalCode.Clear();
            ICodeElement returnLine         = null;
            var          instanceEntity     = typeMapper.GetEntityForTypeSpec(func.ParameterLists [0] [0].TypeSpec);
            bool         instanceIsProtocol = instanceEntity.EntityType == EntityType.Protocol;
            //			bool returnIsGeneric = func.ReturnTypeSpec != null && func.IsGenericType(func.ReturnTypeSpec);
            SLIdentifier returnIdent = null;

            if (func.ParameterLists.Count != 2)
            {
                throw new ArgumentException(String.Format("Method {0} is has {1} parameter lists - it should really have two (normal for an instance method).",
                                                          func.ToFullyQualifiedName(true), func.ParameterLists.Count));
            }

            var closureArgs = new List <SLBaseExpr> ();


            // marshal the regular arguments
            for (int i = 0; i < func.ParameterLists [1].Count; i++)
            {
                var parm        = func.ParameterLists [1] [i];
                var privateName = !String.IsNullOrEmpty(parm.PrivateName) ? parm.PrivateName : TypeSpecToSLType.ConjureIdentifier(null, i).Name;
                if (func.IsTypeSpecGeneric(parm))
                {
                    Tuple <int, int> depthIndex = func.GetGenericDepthAndIndex(parm.TypeSpec);
                    closureArgs.Add(MarshalGenericTypeSpec(func, privateName, parm.TypeSpec as NamedTypeSpec, depthIndex.Item1, depthIndex.Item2));
                }
                else
                {
                    closureArgs.Add(MarshalTypeSpec(func, privateName, parm.TypeSpec));
                }
            }
            string callName       = String.Format("{0}.{1}", vtableName, vtableElementName);
            var    callInvocation = new SLPostBang(new SLIdentifier(callName), false);

            if (instanceIsProtocol)
            {
                string protoName = MarshalEngine.Uniqueify("selfProto", identifiersUsed);
                identifiersUsed.Add(protoName);
                var selfProtoDecl = new SLDeclaration(false,
                                                      new SLBinding(protoName, new SLIdentifier("self"), new SLSimpleType(func.ParameterLists [0] [0].TypeName.NameWithoutModule())),
                                                      Visibility.None);
                preMarshalCode.Add(new SLLine(selfProtoDecl));
                closureArgs.Insert(0, new SLAddressOf(new SLIdentifier(protoName), false));
            }
            else
            {
                // add self as a parameter
                imports.AddIfNotPresent("XamGlue");
                closureArgs.Insert(0, new SLFunctionCall("toIntPtr", false, new SLArgument(new SLIdentifier("value"), new SLIdentifier("self"), true)));
            }

            string       throwReturnName = null;
            SLIdentifier throwReturn     = null;
            SLType       throwReturnType = null;

            throwReturnType = new SLTupleType(
                new SLNameTypePair(SLParameterKind.None, "_", func.ReturnTypeSpec == null || func.ReturnTypeSpec.IsEmptyTuple ?
                                   SLSimpleType.Void : typeMapper.TypeSpecMapper.MapType(func, imports, func.ReturnTypeSpec, true)),
                new SLNameTypePair(SLParameterKind.None, "_", new SLSimpleType("Swift.Error")),
                new SLNameTypePair(SLParameterKind.None, "_", new SLSimpleType("Bool")));

            if (func.HasThrows)
            {
                throwReturnName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                identifiersUsed.Add(throwReturnName);
                throwReturn = new SLIdentifier(throwReturnName);
                imports.AddIfNotPresent("XamGlue");
                // FIXME for generics
                var throwReturnDecl = new SLDeclaration(true, new SLBinding(throwReturn,
                                                                            new SLFunctionCall(String.Format("UnsafeMutablePointer<{0}>.allocate", throwReturnType.ToString()),
                                                                                               false, new SLArgument(new SLIdentifier("capacity"), SLConstant.Val(1), true))), Visibility.None);
                closureArgs.Insert(0, new SLFunctionCall("toIntPtr", false, new SLArgument(new SLIdentifier("value"), throwReturn, true)));
                preMarshalCode.Add(new SLLine(throwReturnDecl));
            }


            if (func.HasThrows)
            {
                returnLine = new SLLine(new SLNamedClosureCall(callInvocation, new CommaListElementCollection <SLBaseExpr> (closureArgs)));
                string errName = MarshalEngine.Uniqueify("err", identifiersUsed);
                identifiersUsed.Add(errName);
                var errIdent = new SLIdentifier(errName);
                var errDecl  = new SLDeclaration(true, new SLBinding(errIdent, new SLFunctionCall("getExceptionThrown", false,
                                                                                                  new SLArgument(new SLIdentifier("retval"), throwReturn, true))), Visibility.None);
                postMarshalCode.Add(new SLLine(errDecl));
                var         ifblock   = new SLCodeBlock(null);
                SLCodeBlock elseblock = null;

                ifblock.Add(SLFunctionCall.FunctionCallLine($"{throwReturnName}.deinitialize", new SLArgument(new SLIdentifier("count"), SLConstant.Val(1), true)));
                ifblock.Add(SLFunctionCall.FunctionCallLine($"{throwReturnName}.deallocate"));
                ifblock.Add(new SLLine(new SLThrow(new SLPostBang(errIdent, false))));


                if (func.ReturnTypeSpec != null && !func.ReturnTypeSpec.IsEmptyTuple)
                {
                    elseblock = new SLCodeBlock(null);
                    string retvalvalName = MarshalEngine.Uniqueify("retvalval", identifiersUsed);
                    identifiersUsed.Add(retvalvalName);
                    SLIdentifier retvalval     = new SLIdentifier(retvalvalName);
                    string       tuplecracker  = "getExceptionNotThrown";
                    var          retvalvaldecl =
                        new SLDeclaration(true, new SLBinding(retvalval,
                                                              new SLFunctionCall(tuplecracker, false,
                                                                                 new SLArgument(new SLIdentifier("retval"), throwReturn, true))), Visibility.None);
                    elseblock.Add(new SLLine(retvalvaldecl));
                    elseblock.Add(SLFunctionCall.FunctionCallLine($"{throwReturnName}.deallocate"));
                    ISLExpr returnExpr = new SLPostBang(retvalval, false);
                    elseblock.Add(SLReturn.ReturnLine(returnExpr));
                }
                postMarshalCode.Add(new SLIfElse(new SLBinaryExpr(BinaryOp.NotEqual, errIdent, SLConstant.Nil),
                                                 ifblock, elseblock));
            }
            else
            {
                if (func.ReturnTypeSpec == null || func.ReturnTypeSpec.IsEmptyTuple)
                {
                    // On no return value
                    // _vtable.entry!(args)
                    //
                    returnLine = new SLLine(new SLNamedClosureCall(callInvocation, new CommaListElementCollection <SLBaseExpr> (closureArgs)));
                }
                else
                {
                    if (TypeSpec.IsBuiltInValueType(func.ReturnTypeSpec))
                    {
                        // on simple return types (Int, UInt, Bool, etc)
                        // return _vtable.entry!(args)
                        //
                        var closureCall = new SLNamedClosureCall(callInvocation, new CommaListElementCollection <SLBaseExpr> (closureArgs));
                        if (postMarshalCode.Count == 0)
                        {
                            returnLine = SLReturn.ReturnLine(closureCall);
                        }
                        else
                        {
                            returnIdent = new SLIdentifier(MarshalEngine.Uniqueify("retval", identifiersUsed));
                            identifiersUsed.Add(returnIdent.Name);
                            var retvalDecl = new SLDeclaration(true, returnIdent, null, closureCall, Visibility.None);
                            returnLine = new SLLine(retvalDecl);
                            postMarshalCode.Add(SLReturn.ReturnLine(returnIdent));
                        }
                    }
                    else
                    {
                        if (func.IsTypeSpecGeneric(func.ReturnTypeSpec))
                        {
                            imports.AddIfNotPresent("XamGlue");
                            // dealing with a generic here.
                            // UnsafeMutablePointer<T> retval = UnsafeMutablePointer<T>.alloc(1)
                            // someCall(toIntPtr(retval), ...)
                            // T actualRetval = retval.move()
                            // retval.dealloc(1)
                            // return actualRetval
                            returnIdent = new SLIdentifier(MarshalEngine.Uniqueify("retval", identifiersUsed));
                            identifiersUsed.Add(returnIdent.Name);
                            Tuple <int, int> depthIndex = func.GetGenericDepthAndIndex(func.ReturnTypeSpec);
                            var retvalDecl = new SLDeclaration(true, returnIdent, null,
                                                               new SLFunctionCall(String.Format("UnsafeMutablePointer<{0}>.allocate", SLGenericReferenceType.DefaultNamer(depthIndex.Item1, depthIndex.Item2)),
                                                                                  false, new SLArgument(new SLIdentifier("capacity"), SLConstant.Val(1), true)),
                                                               Visibility.None);
                            preMarshalCode.Add(new SLLine(retvalDecl));
                            closureArgs.Insert(0, new SLFunctionCall("toIntPtr", false, new SLArgument(new SLIdentifier("value"), returnIdent, true)));
                            SLIdentifier actualReturnIdent = new SLIdentifier(MarshalEngine.Uniqueify("actualRetval", identifiersUsed));
                            identifiersUsed.Add(actualReturnIdent.Name);

                            returnLine = new SLLine(new SLNamedClosureCall(callInvocation, new CommaListElementCollection <SLBaseExpr> (closureArgs)));

                            var actualRetvalDecl = new SLDeclaration(true, actualReturnIdent, null,
                                                                     new SLFunctionCall(String.Format("{0}.move", returnIdent.Name), false),
                                                                     Visibility.None);
                            postMarshalCode.Add(new SLLine(actualRetvalDecl));
                            postMarshalCode.Add(SLFunctionCall.FunctionCallLine(String.Format("{0}.deallocate", returnIdent.Name)));
                            postMarshalCode.Add(SLReturn.ReturnLine(actualReturnIdent));
                        }
                        else if (NamedSpecIsClass(func.ReturnTypeSpec as NamedTypeSpec))
                        {
                            // class (not struct or enum) return type is a pointer
                            // if we have no post marshal code:
                            // return fromIntPtr(_vtable.entry!(args))
                            // if we have post marshal code:
                            // let retval:returnType = fromIntPtr(_vtable.entry!(args))
                            // ... post marshal code
                            // return retval;
                            imports.AddIfNotPresent("XamGlue");
                            SLBaseExpr callExpr = new SLFunctionCall("fromIntPtr", false,
                                                                     new SLArgument(new SLIdentifier("ptr"), new SLNamedClosureCall(callInvocation, new CommaListElementCollection <SLBaseExpr> (closureArgs)), true));
                            if (postMarshalCode.Count > 0)
                            {
                                string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                                var    retDecl    = new SLDeclaration(true, retvalName,
                                                                      typeMapper.TypeSpecMapper.MapType(func, imports, func.ReturnTypeSpec, true), callExpr);
                                returnLine = new SLLine(retDecl);
                                postMarshalCode.Add(SLReturn.ReturnLine(new SLIdentifier(retvalName)));
                            }
                            else
                            {
                                returnLine = SLReturn.ReturnLine(callExpr);
                            }
                        }
                        else
                        {
                            var entity = typeMapper.GetEntityForTypeSpec(func.ReturnTypeSpec);
                            if (func.ReturnTypeSpec is NamedTypeSpec && entity == null)
                            {
                                throw new NotImplementedException($"Function {func.ToFullyQualifiedName (true)} has an unknown return type {func.ReturnTypeSpec.ToString ()}");
                            }
                            if (entity?.EntityType == EntityType.TrivialEnum)
                            {
                                imports.AddIfNotPresent(entity.Type.Module.Name);
                                var        slSelf   = new SLIdentifier($"{entity.Type.Name}.self");
                                SLBaseExpr callExpr = new SLFunctionCall("unsafeBitCast", false,
                                                                         new SLArgument(new SLIdentifier("_"), new SLNamedClosureCall(callInvocation, new CommaListElementCollection <SLBaseExpr> (closureArgs)), false),
                                                                         new SLArgument(new SLIdentifier("to"), slSelf, true));
                                if (postMarshalCode.Count == 0)
                                {
                                    returnLine = SLReturn.ReturnLine(callExpr);
                                }
                                else
                                {
                                    returnIdent = new SLIdentifier(MarshalEngine.Uniqueify("retval", identifiersUsed));
                                    identifiersUsed.Add(returnIdent.Name);
                                    var retvalDecl = new SLDeclaration(true, returnIdent, null, callExpr, Visibility.None);
                                    returnLine = new SLLine(retvalDecl);
                                    postMarshalCode.Add(SLReturn.ReturnLine(returnIdent));
                                }
                            }
                            else
                            {
                                switch (func.ReturnTypeSpec.Kind)
                                {
                                case TypeSpecKind.Closure:

                                    // let retval:CT = allocSwiftClosureToFunc_ARGS ()
                                    // _vtable.entry!(retval, args)
                                    // let actualReturn = netFuncToSwiftClosure (retval.move())
                                    // retval.deallocate()
                                    // return actualReturn

                                    var ct      = func.ReturnTypeSpec as ClosureTypeSpec;
                                    var slct    = new SLBoundGenericType("UnsafeMutablePointer", ToMarshaledClosureType(func, ct));
                                    var ptrName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                                    identifiersUsed.Add(ptrName);

                                    var ptrAllocCallSite = ct.HasReturn() ? $"allocSwiftClosureToFunc_{ct.ArgumentCount()}" : $"allocSwiftClosureToAction_{ct.ArgumentCount ()}";
                                    var ptrAllocCall     = new SLFunctionCall(ptrAllocCallSite, false);
                                    var ptrDecl          = new SLDeclaration(true, new SLIdentifier(ptrName), slct, ptrAllocCall, Visibility.None);
                                    preMarshalCode.Add(new SLLine(ptrDecl));
                                    closureArgs.Insert(0, new SLIdentifier(ptrName));

                                    returnLine = new SLLine(new SLNamedClosureCall(callInvocation, new CommaListElementCollection <SLBaseExpr> (closureArgs)));

                                    var actualReturnName = MarshalEngine.Uniqueify("actualReturn", identifiersUsed);
                                    identifiersUsed.Add(actualReturnName);
                                    var convertCallSite = ct.HasReturn() ? "netFuncToSwiftClosure" : "netActionToSwiftClosure";
                                    var isEmptyClosure  = !ct.HasReturn() && !ct.HasArguments();
                                    var pointerMove     = new SLFunctionCall($"{ptrName}.move", false);
                                    var convertCall     = isEmptyClosure ? pointerMove : new SLFunctionCall(convertCallSite, false, new SLArgument(new SLIdentifier("a1"), pointerMove, true));
                                    var actualDecl      = new SLDeclaration(true, actualReturnName, value: convertCall, vis: Visibility.None);
                                    postMarshalCode.Add(new SLLine(actualDecl));
                                    postMarshalCode.Add(new SLReturn(new SLIdentifier(actualReturnName)));
                                    break;

                                case TypeSpecKind.ProtocolList:
                                case TypeSpecKind.Tuple:
                                case TypeSpecKind.Named:
                                    var namedReturn = func.ReturnTypeSpec as NamedTypeSpec;
                                    // enums and structs can't get returned directly
                                    // instead they will be inserted at the head of the argument list
                                    // let retval = UnsafeMutablePointer<StructOrEnumType>.allocate(capacity: 1)
                                    // _vtable.entry!(retval, args)
                                    // T actualRetval = retval.move()
                                    // retval.deallocate()
                                    // return actualRetval
                                    string allocCallSite = String.Format("UnsafeMutablePointer<{0}>.allocate", func.ReturnTypeName);
                                    if (namedReturn != null)
                                    {
                                        imports.AddIfNotPresent(namedReturn.Module);
                                    }
                                    string retvalName = MarshalEngine.Uniqueify("retval", identifiersUsed);
                                    identifiersUsed.Add(retvalName);
                                    var retDecl = new SLDeclaration(true, retvalName,
                                                                    null, new SLFunctionCall(allocCallSite, false, new SLArgument(new SLIdentifier("capacity"),
                                                                                                                                  SLConstant.Val(1), true)), Visibility.None);
                                    preMarshalCode.Add(new SLLine(retDecl));
                                    closureArgs.Insert(0, new SLIdentifier(retvalName));
                                    returnLine = new SLLine(new SLNamedClosureCall(callInvocation, new CommaListElementCollection <SLBaseExpr> (closureArgs)));

                                    SLIdentifier actualReturnIdent = new SLIdentifier(MarshalEngine.Uniqueify("actualRetval", identifiersUsed));
                                    identifiersUsed.Add(actualReturnIdent.Name);
                                    var actualRetvalDecl = new SLDeclaration(true, actualReturnIdent, null,
                                                                             new SLFunctionCall(String.Format("{0}.move", retvalName), false),
                                                                             Visibility.None);
                                    postMarshalCode.Add(new SLLine(actualRetvalDecl));
                                    postMarshalCode.Add(SLFunctionCall.FunctionCallLine(
                                                            String.Format("{0}.deallocate", retvalName)));
                                    postMarshalCode.Add(SLReturn.ReturnLine(actualReturnIdent));

                                    break;
                                }
                            }
                        }
                    }
                }
            }

            foreach (ICodeElement line in preMarshalCode)
            {
                yield return(line);
            }
            yield return(returnLine);

            foreach (ICodeElement line in postMarshalCode)
            {
                yield return(line);
            }
        }
示例#19
0
 public void FuncReturningBool()
 {
     FuncReturningFoo(SLSimpleType.Bool, SLConstant.Val(false));
 }
示例#20
0
 public void FuncReturningDouble()
 {
     FuncReturningFoo(SLSimpleType.Float, SLConstant.Val(4.0));
 }
        SLBaseExpr MarshalGenericTypeSpec(BaseDeclaration declContext, string name, NamedTypeSpec spec, int depth, int index)
        {
            // given Foo(T x)
            // the vtable entry should be something like
            // foo : ((@convention(c)(UnsafeRawPointer)->())
            //
            // UnsafeMutablePointer<T> xPtr = UnsafeMutablePointer<T>.alloc(1);
            // pointerToX.initialize(x)
            // vtable.foo(toIntPtr(pointerToX))
            // pointerToX.deinitialize(1)
            // pointerToX.deallocate()
            imports.AddIfNotPresent("XamGlue");
            var xPtr = new SLIdentifier(MarshalEngine.Uniqueify(name + "Ptr", identifiersUsed));

            identifiersUsed.Add(xPtr.Name);
            var xPtrDecl = new SLDeclaration(true, xPtr, null,
                                             new SLFunctionCall(String.Format("UnsafeMutablePointer<{0}>.allocate", SLGenericReferenceType.DefaultNamer(depth, index)),
                                                                false, new SLArgument(new SLIdentifier("capacity"), SLConstant.Val(1), true)),
                                             Visibility.None);
            var xPtrBinding = new SLLine(xPtrDecl);

            preMarshalCode.Add(xPtrBinding);
            var xPtrInit = SLFunctionCall.FunctionCallLine(xPtr.Name + ".initialize",
                                                           new SLArgument(new SLIdentifier("to"), new SLIdentifier(name), true));

            preMarshalCode.Add(xPtrInit);

            var xPtrDeinit = SLFunctionCall.FunctionCallLine(xPtr.Name + ".deinitialize",
                                                             new SLArgument(new SLIdentifier("count"), SLConstant.Val(1), true));

            var xPtrDalloc = SLFunctionCall.FunctionCallLine(xPtr.Name + ".deallocate");

            postMarshalCode.Add(xPtrDeinit);
            postMarshalCode.Add(xPtrDalloc);

            return(new SLFunctionCall("toIntPtr", false, new SLArgument(new SLIdentifier("value"), xPtr, true)));
        }
示例#22
0
 public void TestLetFloat()
 {
     BindToValue(true, SLSimpleType.Float, SLConstant.Val(42f), Visibility.Public);
     BindToValue(false, SLSimpleType.Float, SLConstant.Val(42f), Visibility.Public);
 }
        SLBaseExpr MarshalProtocolListTypeSpec(BaseDeclaration declContext, string name, ProtocolListTypeSpec protocols)
        {
            // let p = UnsafeMutablePointer<protoType>.allocate (argName)
            // p.initialize(to: argName)
            // exp is toIntPtr(value: p)
            // ...
            // if isInOut:
            // argName = p.pointee
            // always:
            // p.deinitialize ()
            // p.deallocate ()
            var bindingName = new SLIdentifier(MarshalEngine.Uniqueify(name, identifiersUsed));
            var argType     = typeMapper.TypeSpecMapper.MapType(declContext, imports, protocols, false);
            var ptrType     = new SLBoundGenericType("UnsafeMutablePointer", argType);

            identifiersUsed.Add(bindingName.Name);
            var decl = new SLDeclaration(true, bindingName, ptrType,
                                         new SLFunctionCall(ptrType + ".allocate", false, new SLArgument(new SLIdentifier("capacity"), SLConstant.Val(1), true)),
                                         Visibility.None, false);
            var varBinding = new SLLine(decl);

            preMarshalCode.Add(varBinding);
            var initCall = SLFunctionCall.FunctionCallLine(bindingName.Name + ".initialize",
                                                           new SLArgument(new SLIdentifier("to"), new SLIdentifier(name), true));

            preMarshalCode.Add(initCall);
            imports.AddIfNotPresent("XamGlue");
            if (protocols.IsInOut)
            {
                postMarshalCode.Add(new SLLine(new SLBinding(name, bindingName.Dot(new SLIdentifier("pointee")))));
            }
            postMarshalCode.Add(SLFunctionCall.FunctionCallLine($"{bindingName.Name}.deinitialize", new SLArgument(new SLIdentifier("count"), SLConstant.Val(1), true)));
            postMarshalCode.Add(SLFunctionCall.FunctionCallLine($"{bindingName.Name}.deallocate"));
            return(new SLFunctionCall("toIntPtr", false, new SLArgument(new SLIdentifier("value"), bindingName, true)));
        }
示例#24
0
 public void TestLetFloatInfer()
 {
     BindToValue(true, null, SLConstant.Val(42f), Visibility.Public);
     BindToValue(false, null, SLConstant.Val(42f), Visibility.Public);
 }